@statsig/web-analytics 0.0.1-beta.21

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 ADDED
@@ -0,0 +1,11 @@
1
+ # web-analytics
2
+
3
+ This library was generated with [Nx](https://nx.dev).
4
+
5
+ ## Building
6
+
7
+ Run `nx build web-analytics` to build the library.
8
+
9
+ ## Running unit tests
10
+
11
+ Run `nx test web-analytics` to execute the unit tests via [Jest](https://jestjs.io).
@@ -0,0 +1 @@
1
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.StatsigWebAnalytics=e():t.StatsigWebAnalytics=e()}(this,()=>(()=>{"use strict";var n={496:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0});var e="undefined"!=typeof window?window:{},n=void 0!==n.g?n.g:{},i="undefined"!=typeof globalThis?globalThis:{},o=null!=(o=null!=(o=null!=(o=e.__STATSIG__)?o:n.__STATSIG__)?o:i.__STATSIG__)?o:{};e.__STATSIG__=o,n.__STATSIG__=o,i.__STATSIG__=o},856:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0})},320:function(t,e,n){var r=this&&this.__awaiter||function(t,s,u,l){return new(u=u||Promise)(function(n,e){function i(t){try{r(l.next(t))}catch(t){e(t)}}function o(t){try{r(l.throw(t))}catch(t){e(t)}}function r(t){var e;t.done?n(t.value):((e=t.value)instanceof u?e:new u(function(t){t(e)})).then(i,o)}r((l=l.apply(t,s||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.DataAdapterCore=void 0;const i=n(512),o=n(780),s=n(104),u=n(283),l=n(296),a=n(444),c=n(412);e.DataAdapterCore=class{constructor(t,e){this.i=t,this.o=e,this.u=null,this.l=null,this.h={},this.v="statsig.last_modified_time."+e}attach(t,e){this.l=t,this.u=new i.ErrorBoundary(t),(0,s.monitorClass)(this.u,this)}getDataSync(t){var t=this._(t),e=this.h[t];return e||((e=this.p(t))?(this.m(t,e),this.h[t]):null)}getDataAsync(n,i){var o;return r(this,void 0,void 0,function*(){var t=null!=n?n:this.getDataSync(i),t=yield this.O(null!=(o=null==t?void 0:t.data)?o:null,i),e=this._(i);return t&&this.m(e,t),"Network"!==(null==t?void 0:t.source)&&"NetworkNotModified"!==(null==t?void 0:t.source)||(yield this.j(e,t)),t})}prefetchData(n){return r(this,void 0,void 0,function*(){var t=this._(n),e=yield this.getDataAsync(null,n);e&&this.m(t,Object.assign(Object.assign({},e),{source:"Prefetch"}))})}setData(t,e){e=this._(e);this.m(e,{source:"Bootstrap",data:t,receivedAt:Date.now()})}__primeInMemoryCache(t){this.h=Object.assign(Object.assign({},this.h),t)}O(n,i){return r(this,void 0,void 0,function*(){var t,e=yield this.S(n,i);return e?(t=(0,c.typedJsonParse)(e,"has_updates","Failure while attempting to persist latest value"),n&&!1===(null==t?void 0:t.has_updates)?{source:"NetworkNotModified",data:n,receivedAt:Date.now()}:!0!==(null==t?void 0:t.has_updates)?null:{source:"Network",data:e,receivedAt:Date.now()}):(o.Log.debug("No response returned for latest value"),null)})}N(){return null!=this.l?this.l:(o.Log.error(this.i+" is not attached to a Client"),"")}_(t){t=(0,l.getUserStorageKey)(this.N(),t);return`${u.DataAdapterCachePrefix}.${this.o}.`+t}m(t,e){var n=Object.entries(this.h);n.length<10||([n]=n.reduce((t,e)=>e[1]<t[1]?e:t),delete this.h[n]),this.h[t]=e}p(t){var e=null==(e=a.Storage.getItemSync)?void 0:e.call(a.Storage,t);return null!=e&&(t=(0,c.typedJsonParse)(e,"source","Failed to parse cached result"))?Object.assign(Object.assign({},t),{source:"Cache"}):null}j(t,e){return r(this,void 0,void 0,function*(){yield a.Storage.setItem(t,JSON.stringify(e)),yield this.I(t)})}I(n){var i;return r(this,void 0,void 0,function*(){var t=null!=(i=yield(0,a.getObjectFromStorage)(this.v))?i:{},e=(t[n]=Date.now(),Object.entries(t));e.length<=10||(delete t[(e=e.reduce((t,e)=>e[1]<t[1]?e:t))[0]],yield a.Storage.removeItem(e[0])),yield(0,a.setObjectInStorage)(this.v,t)})}}},280:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Diagnostics=e.captureDiagnostics=void 0;const i=n(780),o="undefined"!=typeof performance&&void 0!==performance.mark;let r=[];e.captureDiagnostics=function(t,e){s.mark(t+":start"),e=e();const n=()=>{s.mark(t+":end"),(t+":end").startsWith("initialize:")&&s.flush()};return e&&e instanceof Promise?e.finally(()=>n()):(n(),e)};class s{static mark(t,e){o&&(t=performance.mark(t,{detail:e}),r.push(t))}static flush(){var t=performance.getEntriesByType("resource").filter(t=>t.name.startsWith("https://api.statsig.com")),t={markers:r,resources:t};i.Log.debug("Diagnostics",t,JSON.stringify(t)),r=[]}}e.Diagnostics=s},512:function(t,u,e){var n=this&&this.__awaiter||function(t,s,u,l){return new(u=u||Promise)(function(n,e){function i(t){try{r(l.next(t))}catch(t){e(t)}}function o(t){try{r(l.throw(t))}catch(t){e(t)}}function r(t){var e;t.done?n(t.value):((e=t.value)instanceof u?e:new u(function(t){t(e)})).then(i,o)}r((l=l.apply(t,s||[])).next())})};Object.defineProperty(u,"__esModule",{value:!0}),u.ErrorBoundary=u.EXCEPTION_ENDPOINT=void 0;const i=e(780),l=e(972);u.EXCEPTION_ENDPOINT="https://statsigapi.net/v1/sdk_exception";u.ErrorBoundary=class{constructor(t){this.l=t,this.M=new Set}capture(e,t,n){try{var i=t();return i&&i instanceof Promise?i.catch(t=>this.T(e,t,n)):i}catch(t){return this.T(e,t,n),null}}logError(t,e){this.T(t,e)}T(o,r,s){try{i.Log.warn("Caught error in "+o,{error:r});n(this,void 0,void 0,function*(){var t,e=null!=r?r:Error("[Statsig] Error was empty"),n=e instanceof Error,i=n?e.name:"No Name";this.M.has(i)||(this.M.add(i),t=l.StatsigMetadataProvider.get(),n=n?e.stack:function(t){try{return JSON.stringify(t)}catch(t){return"[Statsig] Failed to get string for error."}}(e),e=JSON.stringify(Object.assign({tag:o,exception:i,info:n},t)),yield fetch(u.EXCEPTION_ENDPOINT,{method:"POST",headers:{"STATSIG-API-KEY":this.l,"STATSIG-SDK-TYPE":String(t.sdkType),"STATSIG-SDK-VERSION":String(t.sdkVersion),"Content-Type":"application/json"},body:e}),null!=s&&s({name:"error",error:r}))}).then(()=>{}).catch(()=>{})}catch(t){}}}},500:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0})},788:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0})},728:function(t,e,n){var i=this&&this.__awaiter||function(t,s,u,l){return new(u=u||Promise)(function(n,e){function i(t){try{r(l.next(t))}catch(t){e(t)}}function o(t){try{r(l.throw(t))}catch(t){e(t)}}function r(t){var e;t.done?n(t.value):((e=t.value)instanceof u?e:new u(function(t){t(e)})).then(i,o)}r((l=l.apply(t,s||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.EventLogger=void 0;const o=n(832),r=n(780),s=n(876),u=n(972),l=n(444),a=n(412),c=n(84),d=n(408),h="https://api.statsig.com/v1";e.EventLogger=class{constructor(t,e,n,i){this.l=t,this.D=e,this.A=n,this.P=i,this.C=[],this.qt={},this.Kt={},this.F=!1,this.L=Date.now(),this.V=!0===(null==i?void 0:i.disableLogging),this.R=null!=(t=null==i?void 0:i.loggingBufferMaxSize)?t:50;n=null!=(e=null==i?void 0:i.loggingIntervalMs)?e:1e4;this.K=setInterval(()=>this.q(),n),this.Ft=(0,c.Lt)(null==i?void 0:i.logEventUrl,null==i?void 0:i.api,"/rgstr",h),this.Vt=(0,c.Lt)(null==i?void 0:i.logEventBeaconUrl,null==i?void 0:i.api,"/log_event_beacon",h),d.VisibilityChangeObserver.add(this),this.J()}setLoggingDisabled(t){this.V=t}enqueue(t){this.U(t)&&(this.Jt(t),this.B(),this.C.length>this.R)&&this.q()}incrementNonExposureCount(t){var e=null!=(e=this.Kt[t])?e:0;this.Kt[t]=e+1}reset(){this.qt={}}onVisibilityChanged(t){"background"===t&&this.q()}shutdown(){return i(this,void 0,void 0,function*(){this.K&&(clearInterval(this.K),this.K=null),yield this.flush()})}flush(){return i(this,void 0,void 0,function*(){var t;this.zt(),0!==this.C.length&&(t=this.C,this.C=[],yield this.W(t))})}B(){this.F||(this.F=!0,200<Date.now()-this.L)||setTimeout(()=>this.q(),200)}U(t){if((0,s.isExposureEvent)(t)){var t=[t.eventName,null==(e=t.user)?void 0:e.userID,null==(e=t.metadata)?void 0:e.gate,null==(e=t.metadata)?void 0:e.config,null==(e=t.metadata)?void 0:e.ruleID].join("|"),e=this.qt[t],n=Date.now();if(e&&n-e<6e4)return!1;1e3<Object.keys(this.qt).length&&(this.qt={}),this.qt[t]=n}return!0}q(){this.flush().catch(()=>{})}W(t){return i(this,void 0,void 0,function*(){if(this.V)this.Y(t);else try{(!d.VisibilityChangeObserver.isCurrentlyVisible()&&this.A.isBeaconSupported()?yield this.H(t):yield this.X(t)).success?this.D({name:"logs_flushed",events:t}):this.Y(t)}catch(t){r.Log.warn("Failed to flush events.")}})}X(e){return i(this,void 0,void 0,function*(){var t=yield this.A.post({sdkKey:this.l,data:{events:e},url:this.Ft,retries:3,params:{ec:String(e.length)}}),t=null!=t&&t.body?(0,a.typedJsonParse)(t.body,"success","Failed to parse SendEventsResponse"):null;return{success:!0===(null==t?void 0:t.success)}})}H(t){return i(this,void 0,void 0,function*(){return{success:yield this.A.beacon({sdkKey:this.l,data:{events:t},url:this.Vt})}})}Y(t){for(;500<t.length;)t.shift();var e=this.Z();(0,l.setObjectInStorage)(e,t).catch(()=>{r.Log.warn("Unable to save failed logs to storage")})}J(){const e=this.Z();i(this,void 0,void 0,function*(){var t=yield(0,l.getObjectFromStorage)(e);t&&(yield l.Storage.removeItem(e),yield this.W(t))}).catch(()=>{r.Log.warn("Failed to flush stored logs")})}Z(){return"statsig.failed_logs."+(0,o.DJB2)(this.l)}Jt(t){t.user&&(t.user=Object.assign({},t.user),delete t.user.privateAttributes);var{sdkType:e,sdkVersion:n}=u.StatsigMetadataProvider.get();this.C.push(Object.assign(Object.assign({},t),{statsigMetadata:{sdkType:e,sdkVersion:n}}))}zt(){0!==Object.keys(this.Kt).length&&(this.Jt({eventName:"statsig::non_exposed_checks",user:null,time:Date.now(),metadata:{checks:Object.assign({},this.Kt)}}),this.Kt={})}}},832:(t,e)=>{function n(e){let n=0;for(let t=0;t<e.length;t++){var i=e.charCodeAt(t);n=(n<<5)-n+i,n&=n}return String(n>>>0)}Object.defineProperty(e,"__esModule",{value:!0}),e.DJB2Object=e.DJB2=void 0,e.DJB2=n,e.DJB2Object=function(t){return n(JSON.stringify(function n(i){if(null==i)return null;const t=Object.keys(i).sort();const o={};t.forEach(t=>{let e=i[t];e instanceof Object&&(e=n(e)),o[t]=e});return o}(t)))}},780:(t,e)=>{function n(t){return t.unshift("[Statsig]"),t}var i,o;Object.defineProperty(e,"__esModule",{value:!0}),e.Log=e.LogLevel=void 0,(o=i||(e.LogLevel=i={}))[o.None=0]="None",o[o.Error=1]="Error",o[o.Warn=2]="Warn",o[o.Info=3]="Info",o[o.Debug=4]="Debug";class r{static info(...t){this.level>=i.Info&&console.info(...n(t))}static debug(...t){this.level>=i.Debug&&console.debug(...n(t))}static warn(...t){this.level>=i.Warn&&console.warn(...n(t))}static error(...t){this.level>=i.Error&&console.error(...n(t))}}(e.Log=r).level=i.Error},104:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.monitorClass=void 0;const r=n(280),s=n(688);function c(t,e,n,i){var o=i instanceof s.StatsigClientBase?i.tt.bind(i):void 0;return t.capture(e,()=>(0,r.captureDiagnostics)(e,()=>n.apply(i)),o)}function d(t){return"object"==typeof t&&(t=Object.getPrototypeOf(t))&&"object"==typeof t?t:null}e.monitorClass=function(e,t){try{{var n=e;var i=t;var o;const r=i;for(const s of function(t){const e=new Set;let n=d(t);for(;n&&n!==Object.prototype;)Object.getOwnPropertyNames(n).filter(t=>"function"==typeof(null===n||void 0===n?void 0:n[t])).forEach(t=>e.add(t)),n=Object.getPrototypeOf(n);return Array.from(e)}(r))if("constructor"!==s){const u=r[s];r[s]=function(...t){return c(n,s,()=>u.apply(this,t),i)}}for(const l of function(t){const e=new Set,n=d(t);return Object.getOwnPropertyNames((null===n||void 0===n?void 0:n.constructor)||{}).filter(t=>{var e;return"caller"!==t&&"arguments"!==t&&"callee"!==t&&"function"==typeof(null==(e=null===n||void 0===n?void 0:n.constructor)?void 0:e[t])}).forEach(t=>e.add(t)),Array.from(e)}(r)){const a=null==(o=null===r||void 0===r?void 0:r.constructor)?void 0:o[l];(null===r||void 0===r?void 0:r.constructor)[l]=function(...t){return c(n,r.constructor.name+"."+l,()=>a.apply(r.constructor,t),i)}}return}}catch(t){e.logError("monitorClass",t)}}},188:function(t,e,n){var o=this&&this.__awaiter||function(t,s,u,l){return new(u=u||Promise)(function(n,e){function i(t){try{r(l.next(t))}catch(t){e(t)}}function o(t){try{r(l.throw(t))}catch(t){e(t)}}function r(t){var e;t.done?n(t.value):((e=t.value)instanceof u?e:new u(function(t){t(e)})).then(i,o)}r((l=l.apply(t,s||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.NetworkCore=void 0;const h=n(280),v=n(780),r=n(612),s=n(604),u=n(972);e.NetworkCore=class{constructor(t,e){this.P=t,this.D=e,this.et=null!=(e=null==t?void 0:t.networkTimeoutMs)?e:1e4}post(e){return o(this,void 0,void 0,function*(){var t=yield this.nt(e);return this.it(Object.assign({method:"POST",body:t},e))})}get(t){return o(this,void 0,void 0,function*(){return this.it(Object.assign({method:"GET"},t))})}isBeaconSupported(){return"undefined"!=typeof navigator&&"function"==typeof(null===navigator||void 0===navigator?void 0:navigator.sendBeacon)}beacon(n){return o(this,void 0,void 0,function*(){var t=this.rt(n),e=yield this.nt(n);return navigator.sendBeacon(t,e)})}it(c){var d;return o(this,void 0,void 0,function*(){var{method:e,body:n,retries:i}=c;const o=new AbortController;var t,r,s,u=setTimeout(()=>o.abort(`Timeout of ${this.et}ms expired.`),this.et),l=this.rt(c);let a=null;try{if(a=yield fetch(l,{method:e,body:n,headers:Object.assign({},c.headers),signal:o.signal}),clearTimeout(u),a.ok)return s=yield a.text(),h.Diagnostics.mark("_sendRequest:response-received",{status:a.status,contentLength:a.headers.get("content-length")}),{body:s,code:a.status};throw t=yield a.text().catch(()=>"No Text"),(r=new Error(`Failed to fetch: ${l} `+t)).name="NetworkError",r}catch(t){n=function(t,e){if(t.signal.aborted&&"string"==typeof t.signal.reason)return t.signal.reason;if("string"==typeof e)return e;if(e instanceof Error)return e.name+": "+e.message;return null}(o,t);return h.Diagnostics.mark("_sendRequest:error",{error:n,status:null===a||void 0===a?void 0:a.status,contentLength:null===a||void 0===a?void 0:a.headers.get("content-length")}),!i||i<=0?(null!=(d=this.D)&&d.call(this,{name:"error",error:t}),v.Log.error(`A networking error occured during ${e} request to ${l}.`,n,t),null):this.it(Object.assign(Object.assign({},c),{retries:i-1}))}})}rt(t){var e=u.StatsigMetadataProvider.get(),e=Object.assign({k:t.sdkKey,st:e.sdkType,sv:e.sdkVersion,t:String(Date.now()),sid:r.SessionID.get(t.sdkKey)},t.params),e=Object.entries(e).map(([t,e])=>encodeURIComponent(t)+"="+encodeURIComponent(e)).join("&");return t.url+(e?"?"+e:"")}nt(i){return o(this,void 0,void 0,function*(){var t=i["data"],e=yield s.StableID.get(i.sdkKey),n=r.SessionID.get(i.sdkKey);return JSON.stringify(Object.assign(Object.assign({},t),{statsigMetadata:Object.assign(Object.assign({},u.StatsigMetadataProvider.get()),{stableID:e,sessionID:n})}))})}}},264:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CombinationOverrideAdapter=void 0;e.CombinationOverrideAdapter=class{constructor(t){this.providers=t}getGateOverride(n,i){return this.ot(t=>{var e;return null!=(e=null==(e=t.getGateOverride)?void 0:e.call(t,n,i))?e:null})}getDynamicConfigOverride(n,i){return this.ot(t=>{var e;return null!=(e=null==(e=t.getDynamicConfigOverride)?void 0:e.call(t,n,i))?e:null})}ot(t){for(const n of this.providers){var e=t(n);if(e)return e}return null}}},612:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SessionID=void 0;const i=n(556),o={};e.SessionID={get:t=>(null==o[t]&&(o[t]=(0,i.getUUID)()),o[t])}},604:function(t,e,n){var i=this&&this.__awaiter||function(t,s,u,l){return new(u=u||Promise)(function(n,e){function i(t){try{r(l.next(t))}catch(t){e(t)}}function o(t){try{r(l.throw(t))}catch(t){e(t)}}function r(t){var e;t.done?n(t.value):((e=t.value)instanceof u?e:new u(function(t){t(e)})).then(i,o)}r((l=l.apply(t,s||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.StableID=void 0;const o=n(832),r=n(780),s=n(444),u=n(556),l={};function a(t){return"statsig.stable_id."+(0,o.DJB2)(t)}function c(t,e){e=a(e);(0,s.setObjectInStorage)(e,t).catch(()=>{r.Log.warn("Failed to save StableID")})}e.StableID={get:e=>i(void 0,void 0,void 0,function*(){return null==l[e]&&(l[e]=function(t){t=a(t);return(0,s.getObjectFromStorage)(t)}(e).then(t=>{return null!=t||c(t=(0,u.getUUID)(),e),t})),l[e]}),setOverride:(t,e)=>{l[e]=Promise.resolve(t),c(t,e)}}},688:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.StatsigClientBase=void 0,n(496);const r=n(512),s=n(728),u=n(780),l=n(604),a=n(444);e.StatsigClientBase=class{constructor(t,e,n,i){this.l=t,this.loadingStatus="Uninitialized",this.ut={},null!=i&&i.disableStorage&&a.Storage.setDisabled(!0),null!=i&&i.overrideStableID&&l.StableID.setOverride(i.overrideStableID,t),u.Log.level=null!=(o=null==i?void 0:i.logLevel)?o:u.LogLevel.Warn,this.Pt=null!=(o=null==i?void 0:i.overrideAdapter)?o:null,this.lt=new s.EventLogger(t,this.tt.bind(this),n,i),this.u=new r.ErrorBoundary(t);var o,n=null!=(o=(__STATSIG__=null!==__STATSIG__&&void 0!==__STATSIG__?__STATSIG__:{}).instances)?o:{};n[t]=this,__STATSIG__.instances=n,this.dataAdapter=e,this.dataAdapter.attach(t,i)}updateRuntimeOptions(t){null!=t.disableLogging&&this.lt.setLoggingDisabled(t.disableLogging),null!=t.disableStorage&&a.Storage.setDisabled(t.disableStorage)}flush(){return this.lt.flush()}on(t,e){this.ut[t]||(this.ut[t]=[]),this.ut[t].push(e)}off(t,e){this.ut[t]&&-1!==(e=this.ut[t].indexOf(e))&&this.ut[t].splice(e,1)}tt(e){var t;const n=t=>{try{t(e)}catch(t){u.Log.error("An error occurred in a StatsigClientEvent listener. This is not an issue with Statsig.",e)}};this.ut[e.name]&&this.ut[e.name].forEach(t=>n(t)),null!=(t=this.ut["*"])&&t.forEach(n)}ct(t,e){this.loadingStatus=t,this.tt({name:"values_updated",status:t,values:e})}dt(t,e,n){!0===(null==n?void 0:n.disableExposureLog)?this.lt.incrementNonExposureCount(t):this.lt.enqueue(e)}}},808:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0})},283:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DataAdapterCachePrefix=void 0,e.DataAdapterCachePrefix="statsig.cached"},876:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createLayerParameterExposure=e.createConfigExposure=e.createGateExposure=e.isExposureEvent=void 0;const n="statsig::config_exposure",i="statsig::gate_exposure";function l(t,e,n,i,o){return{eventName:t,user:e,value:null,metadata:function(t,e){e.reason=t.reason,t.lcut&&(e.lcut=String(t.lcut));t.receivedAt&&(e.receivedAt=String(t.receivedAt));return e}(n,i),secondaryExposures:o,time:Date.now()}}e.isExposureEvent=function({eventName:t}){return t===i||t===n},e.createGateExposure=function(t,e){return l(i,t,e.details,{gate:e.name,gateValue:String(e.value),ruleID:e.ruleID},null!=(e=null==(t=e.__evaluation)?void 0:t.secondary_exposures)?e:[])},e.createConfigExposure=function(t,e){return l(n,t,e.details,{config:e.name,ruleID:e.ruleID},null!=(e=null==(t=e.__evaluation)?void 0:t.secondary_exposures)?e:[])},e.createLayerParameterExposure=function(t,e,n){var i,o=e.__evaluation,r=!0===(null==(r=null==o?void 0:o.explicit_parameters)?void 0:r.includes(n));let s="",u=null!=(i=null==o?void 0:o.undelegated_secondary_exposures)?i:[];return r&&(s=null!=(i=o.allocated_experiment_name)?i:"",u=o.secondary_exposures),l("statsig::layer_exposure",t,e.details,{config:e.name,parameterName:n,ruleID:e.ruleID,allocatedExperiment:s,isExplicitParameter:String(r)},u)}},972:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.StatsigMetadataProvider=void 0;let n={sdkVersion:"0.0.1-beta.21",sdkType:"js-mono"};e.StatsigMetadataProvider={get:()=>n,add:t=>{n=Object.assign(Object.assign({},n),t)}}},384:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0})},136:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.makeLayer=e.makeDynamicConfig=e.makeFeatureGate=void 0;const o="default";e.makeFeatureGate=function(t,e,n){return{name:t,details:e,ruleID:null!=(t=null==n?void 0:n.rule_id)?t:o,value:!0===(null==n?void 0:n.value),__evaluation:n}},e.makeDynamicConfig=function(t,e,n){return{name:t,details:e,ruleID:null!=(t=null==n?void 0:n.rule_id)?t:o,value:null!=(e=null==n?void 0:n.value)?e:{},__evaluation:n}},e.makeLayer=function(t,e,n,i){return{name:t,details:e,getValue:null!=i?i:()=>{},ruleID:null!=(t=null==n?void 0:n.rule_id)?t:o,Et:null!=(e=null==n?void 0:n.value)?e:{},__evaluation:n}}},296:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getUnitIDFromUser=e.getUserStorageKey=e.normalizeUser=void 0;const i=n(832);e.normalizeUser=function(t,e){try{var n=JSON.parse(JSON.stringify(t));return null!=e&&(n.statsigEnvironment=e),n}catch(t){throw new Error("User object must be convertable to JSON string.")}},e.getUserStorageKey=function(t,e){return(0,i.DJB2Object)({sdkKey:t,user:e})},e.getUnitIDFromUser=function(t,e){var n;return"string"==typeof e&&"userid"!==e.toLowerCase()?null!=(n=null==(n=t.customIDs)?void 0:n[e])?n:null==(n=null==t?void 0:t.customIDs)?void 0:n[e.toLowerCase()]:t.userID}},444:function(t,e,n){var i=this&&this.__awaiter||function(t,s,u,l){return new(u=u||Promise)(function(n,e){function i(t){try{r(l.next(t))}catch(t){e(t)}}function o(t){try{r(l.throw(t))}catch(t){e(t)}}function r(t){var e;t.done?n(t.value):((e=t.value)instanceof u?e:new u(function(t){t(e)})).then(i,o)}r((l=l.apply(t,s||[])).next())})},n=(Object.defineProperty(e,"__esModule",{value:!0}),e.setObjectInStorage=e.getObjectFromStorage=e.Storage=void 0,n(780));const o={},r={getProviderName:()=>"InMemory",getItemSync(t){return null!=(t=o[t])?t:null},getItem(t){return Promise.resolve(null!=(t=o[t])?t:null)},setItem(t,e){return o[t]=e,Promise.resolve()},removeItem(t){return delete o[t],Promise.resolve()},getAllKeys(){return Promise.resolve(Object.keys(o))}};let s=null;try{"undefined"!=typeof window&&"localStorage"in window&&(s={getProviderName:()=>"LocalStorage",getItemSync(t){return localStorage.getItem(t)},getItem(t){return Promise.resolve(localStorage.getItem(t))},setItem(t,e){return localStorage.setItem(t,e),Promise.resolve()},removeItem(t){return localStorage.removeItem(t),Promise.resolve()},getAllKeys(){var t=Object.keys(localStorage);return Promise.resolve(t)}})}catch(t){n.Log.warn("Failed to setup localStorageProvider.")}let u=null!==s&&void 0!==s?s:r,l=u;e.Storage={getProviderName:()=>l.getProviderName(),getItem:t=>l.getItem(t),setItem:(t,e)=>l.setItem(t,e),removeItem:t=>l.removeItem(t),getAllKeys:()=>l.getAllKeys(),getItemSync:t=>{var e;return null!=(e=null==(e=l.getItemSync)?void 0:e.call(l,t))?e:null},setProvider:t=>{u=t,l=t},setDisabled:t=>{l=t?r:u}},e.getObjectFromStorage=function(e){return i(this,void 0,void 0,function*(){var t=yield l.getItem(e);return JSON.parse(null!=t?t:"null")})},e.setObjectInStorage=function(t,e){return i(this,void 0,void 0,function*(){yield l.setItem(t,JSON.stringify(e))})}},412:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.typedJsonParse=void 0;const o=n(780);e.typedJsonParse=function(t,e,n){try{var i=JSON.parse(t);return"object"==typeof i&&0 in i,i}catch(t){}return o.Log.error(n),null}},556:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getUUID=void 0,e.getUUID=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();let n=(new Date).getTime(),i="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;return`xxxxxxxx-xxxx-4xxx-${"89ab"[Math.floor(4*Math.random())]}xxx-xxxxxxxxxxxx`.replace(/[xy]/g,t=>{let e=16*Math.random();return 0<n?(e=(n+e)%16|0,n=Math.floor(n/16)):(e=(i+e)%16|0,i=Math.floor(i/16)),("x"===t?e:7&e|8).toString(16)})}},84:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Lt=void 0,e.Lt=function(t,e,n,i){return t||(e?""+e+n:""+i+n)}},539:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0})},408:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.VisibilityChangeObserver=void 0;class n{static isCurrentlyVisible(){return"foreground"===this.ht}static add(t){this.ut.push(t)}static remove(t){t=this.ut.indexOf(t);-1!==t&&this.ut.splice(t,1)}static notify(e){e!==this.ht&&(this.ht=e,this.ut.forEach(t=>t.onVisibilityChanged(e)))}}(e.VisibilityChangeObserver=n).ut=[],n.ht="foreground","undefined"!=typeof window&&"function"==typeof window.addEventListener&&(window.addEventListener("focus",()=>n.notify("foreground")),window.addEventListener("blur",()=>n.notify("background")),window.addEventListener("beforeunload",()=>n.notify("background"))),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("visibilitychange",()=>{n.notify("visible"===document.visibilityState?"foreground":"background")})},464:function(t,e,n){var i=this&&this.__createBinding||(Object.create?function(t,e,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(e,n);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,o)}:function(t,e,n,i){t[i=void 0===i?n:i]=e[n]}),o=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||Object.prototype.hasOwnProperty.call(e,n)||i(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.Log=e.Storage=e.EventLogger=void 0,n(496);const r=n(728),s=(Object.defineProperty(e,"EventLogger",{enumerable:!0,get:function(){return r.EventLogger}}),n(780)),u=(Object.defineProperty(e,"Log",{enumerable:!0,get:function(){return s.Log}}),n(444));Object.defineProperty(e,"Storage",{enumerable:!0,get:function(){return u.Storage}}),o(n(496),e),o(n(856),e),o(n(320),e),o(n(512),e),o(n(500),e),o(n(788),e),o(n(832),e),o(n(780),e),o(n(104),e),o(n(188),e),o(n(264),e),o(n(604),e),o(n(688),e),o(n(808),e),o(n(283),e),o(n(876),e),o(n(972),e),o(n(384),e),o(n(136),e),o(n(296),e),o(n(444),e),o(n(412),e),o(n(84),e),o(n(539),e),o(n(556),e),o(n(408),e),__STATSIG__=Object.assign(Object.assign({},null!==__STATSIG__&&void 0!==__STATSIG__?__STATSIG__:{}),{EventLogger:r.EventLogger,Log:s.Log,Storage:u.Storage})},96:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveDeltasResponse=void 0;const i=n(464);function o(t,e){null!=t&&t.forEach(t=>{delete e[t]})}e.resolveDeltasResponse=function(t,e){var n;return(e=(0,i.typedJsonParse)(e,"checksum","Failed to parse DeltasEvaluationResponse"))?(t=t,n=e,t=Object.assign(Object.assign(Object.assign({},t),n),{feature_gates:Object.assign(Object.assign({},t.feature_gates),n.feature_gates),layer_configs:Object.assign(Object.assign({},t.layer_configs),n.layer_configs),dynamic_configs:Object.assign(Object.assign({},t.dynamic_configs),n.dynamic_configs)}),o((t=n=t).deleted_gates,t.feature_gates),delete t.deleted_gates,o(n.deleted_configs,t.dynamic_configs),delete t.deleted_configs,o(n.deleted_layers,t.layer_configs),delete t.deleted_layers,n=t,(t=(0,i.DJB2Object)({feature_gates:n.feature_gates,dynamic_configs:n.dynamic_configs,layer_configs:n.layer_configs}))===e.checksum?JSON.stringify(n):{hadBadDeltaChecksum:!0,badChecksum:t,badMergedConfigs:n,badFullResponse:e.deltas_full_response}):{hadBadDeltaChecksum:!0}}},156:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0});const i=n(464);e.default=class{constructor(t){this.l=t,this.wt=null,this.xt="Uninitialized",this.Nt=0,this.It=0}reset(){this.wt=null,this.xt="Loading",this.Nt=0,this.It=0}finalize(){this.wt||(this.xt="NoValues")}setValuesFromDataAdapter(t){var e;t&&!0===(null==(e=(0,i.typedJsonParse)(t.data,"has_updates","Failed to parse EvaluationResponse"))?void 0:e.has_updates)&&(this.Nt=e.time,this.It=t.receivedAt,this.xt=t.source,this.wt=e)}getGate(t){var e,t=null!=(e=null==(e=this.wt)?void 0:e.feature_gates[t])?e:null;return this.Ut(t)}getConfig(t){var e,t=null!=(e=null==(e=this.wt)?void 0:e.dynamic_configs[t])?e:null;return this.Ut(t)}getLayer(t){var e,t=null!=(e=null==(e=this.wt)?void 0:e.layer_configs[t])?e:null;return this.Ut(t)}Ut(t){return{evaluation:t,details:this._t(null==t)}}_t(t){return"Uninitialized"===this.xt||"NoValues"===this.xt?{reason:this.xt}:{reason:this.xt+":"+(t?"Unrecognized":"Recognized"),lcut:this.Nt,receivedAt:this.It}}}},400:function(t,e,n){var r=this&&this.__awaiter||function(t,s,u,l){return new(u=u||Promise)(function(n,e){function i(t){try{r(l.next(t))}catch(t){e(t)}}function o(t){try{r(l.throw(t))}catch(t){e(t)}}function r(t){var e;t.done?n(t.value):((e=t.value)instanceof u?e:new u(function(t){t(e)})).then(i,o)}r((l=l.apply(t,s||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const s=n(464),u=n(96);class i extends s.NetworkCore{constructor(t,e){super(t,e),this.$t=(0,s.Lt)(null==t?void 0:t.initializeUrl,null==t?void 0:t.api,"/initialize","https://api.statsig.com/v1")}fetchEvaluations(n,i,o){return r(this,void 0,void 0,function*(){var t=i?(0,s.typedJsonParse)(i,"has_updates","Failed to parse cached EvaluationResponse"):null;let e={user:o,hash:"djb2",deltasResponseRequested:!1};return null!=t&&t.has_updates&&(e=Object.assign(Object.assign({},e),{sinceTime:t.time,previousDerivedFields:"derived_fields"in t?t.derived_fields:{},deltasResponseRequested:!0})),this.Bt(n,t,e)})}Bt(e,n,i){var o;return r(this,void 0,void 0,function*(){var t=yield this.post({sdkKey:e,url:this.$t,data:i,retries:2});return 204===(null==t?void 0:t.code)?'{"has_updates": false}':200!==(null==t?void 0:t.code)?null!=(o=null==t?void 0:t.body)?o:null:!0!==(null==n?void 0:n.has_updates)||!0!==(null==(o=t.body)?void 0:o.includes('"is_delta":true'))?t.body:"string"==typeof(t=(0,u.resolveDeltasResponse)(n,t.body))?t:this.Bt(e,n,Object.assign(Object.assign(Object.assign({},i),t),{deltasResponseRequested:!1}))})}}e.default=i},520:function(t,e,n){var i=this&&this.__awaiter||function(t,s,u,l){return new(u=u||Promise)(function(n,e){function i(t){try{r(l.next(t))}catch(t){e(t)}}function o(t){try{r(l.throw(t))}catch(t){e(t)}}function r(t){var e;t.done?n(t.value):((e=t.value)instanceof u?e:new u(function(t){t(e)})).then(i,o)}r((l=l.apply(t,s||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const s=n(464),r=n(156),u=n(400),l=n(364);n(807);class o extends s.StatsigClientBase{constructor(t,e,n=null){var i,o=new u.default(n,t=>{this.tt(t)});super(t,null!=(i=null==n?void 0:n.dataAdapter)?i:new l.StatsigEvaluationsDataAdapter,o,n),(0,s.monitorClass)(this.u,this),(0,s.monitorClass)(this.u,o),this.P=null!=n?n:{},this.vt=new r.default(t),this.A=o,this.Yt=e}initializeSync(){this.updateUserSync(this.Yt)}initializeAsync(){return this.updateUserAsync(this.Yt)}getCurrentUser(){return JSON.parse(JSON.stringify(this.Yt))}updateUserSync(t){this.Wt(t);t=this.dataAdapter.getDataSync(this.Yt);this.vt.setValuesFromDataAdapter(t),this.vt.finalize(),this.ct("Ready",t),this.Dt(null!=t?t:null,this.Yt)}updateUserAsync(n){return i(this,void 0,void 0,function*(){this.Wt(n);var t=this.Yt,e=this.dataAdapter.getDataSync(t);this.ct("Loading",e),this.vt.setValuesFromDataAdapter(e),e=yield this.dataAdapter.getDataAsync(e,t),t===this.Yt&&this.vt.setValuesFromDataAdapter(e),this.vt.finalize(),this.ct("Ready",e)})}shutdown(){return i(this,void 0,void 0,function*(){yield this.lt.shutdown()})}checkGate(t,e){return this.getFeatureGate(t,e).value}getFeatureGate(t,e){var n=(0,s.DJB2)(t),{evaluation:n,details:i}=this.vt.getGate(n),i=(0,s.makeFeatureGate)(t,i,n),o=null==(o=null==(n=this.Pt)?void 0:n.getGateOverride)?void 0:o.call(n,i,this.Yt,e),n=null!=o?o:i;return this.dt(t,(0,s.createGateExposure)(this.Yt,n),e),this.tt({name:"gate_evaluation",gate:n}),n}getDynamicConfig(t,e){t=this.kt("dynamic_config",t,e);return this.tt({name:"dynamic_config_evaluation",dynamicConfig:t}),t}getExperiment(t,e){t=this.kt("experiment",t,e);return this.tt({name:"experiment_evaluation",experiment:t}),t}getLayer(n,i){var t=(0,s.DJB2)(n),{evaluation:t,details:e}=this.vt.getLayer(t),e=(0,s.makeLayer)(n,e,t),o=null==(o=null==(t=this.Pt)?void 0:t.getLayerOverride)?void 0:o.call(t,e,this.Yt,i);const r=null!=o?o:e;return this.tt({name:"layer_evaluation",layer:r}),Object.assign(Object.assign({},r),{getValue:t=>{var e;return t in r.Et&&(e=(0,s.createLayerParameterExposure)(this.Yt,r,t),this.dt(n,e,i),null!=(e=r.Et[t]))?e:null}})}logEvent(t){this.lt.enqueue(Object.assign(Object.assign({},t),{user:this.Yt,time:Date.now()}))}Dt(t,e){this.dataAdapter.getDataAsync(t,e).catch(t=>{s.Log.error("An error occurred after update.",t)})}Wt(t){this.lt.reset(),this.vt.reset(),this.Yt=(0,s.normalizeUser)(t,this.P.environment)}kt(t,e,n){var i=(0,s.DJB2)(e),{evaluation:i,details:o}=this.vt.getConfig(i),o=(0,s.makeDynamicConfig)(e,o,i),i="experiment"===t?null==(t=null==(i=this.Pt)?void 0:i.getExperimentOverride)?void 0:t.call(i,o,this.Yt,n):null==(i=null==(t=this.Pt)?void 0:t.getDynamicConfigOverride)?void 0:i.call(t,o,this.Yt,n),t=null!=i?i:o;return this.dt(e,(0,s.createConfigExposure)(this.Yt,t),n),t}}e.default=o},364:function(t,e,n){var o=this&&this.__awaiter||function(t,s,u,l){return new(u=u||Promise)(function(n,e){function i(t){try{r(l.next(t))}catch(t){e(t)}}function o(t){try{r(l.throw(t))}catch(t){e(t)}}function r(t){var e;t.done?n(t.value):((e=t.value)instanceof u?e:new u(function(t){t(e)})).then(i,o)}r((l=l.apply(t,s||[])).next())})},i=(Object.defineProperty(e,"__esModule",{value:!0}),e.StatsigEvaluationsDataAdapter=void 0,n(464));const r=n(400);class s extends i.DataAdapterCore{constructor(){super("EvaluationsDataAdapter","evaluations"),this.A=null}attach(t,e){super.attach(t,e),this.A=new r.default(null!=e?e:{})}S(e,n){var i;return o(this,void 0,void 0,function*(){var t=yield null==(i=this.A)?void 0:i.fetchEvaluations(this.N(),e,n);return null!=t?t:null})}}e.StatsigEvaluationsDataAdapter=s},807:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SDK_TYPE=void 0;n=n(464);e.SDK_TYPE="javascript-client",n.StatsigMetadataProvider.add({sdkType:e.SDK_TYPE})},208:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.StatsigClient=e.StatsigEvaluationsDataAdapter=void 0;var i=n(520);e.StatsigClient=i.default;const o=n(364);Object.defineProperty(e,"StatsigEvaluationsDataAdapter",{enumerable:!0,get:function(){return o.StatsigEvaluationsDataAdapter}}),n(807),__STATSIG__=Object.assign(Object.assign({},null!==__STATSIG__&&void 0!==__STATSIG__?__STATSIG__:{}),{StatsigEvaluationsDataAdapter:o.StatsigEvaluationsDataAdapter,StatsigClient:i.default}),e.default=__STATSIG__},536:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AutoCapture=void 0;const i=n(464),o=n(76);e.AutoCapture=class{constructor(t,e){this.l=t,this.ve=e,this.Zt=Date.now(),this.te=0,"undefined"!=typeof document&&"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>this.ee()):this.ee()}ne(){var t;"undefined"!=typeof window&&"undefined"!=typeof document&&(t=t=>{this.ie(t||window.event)},(0,o.registerEventHandler)(document,"click",t),(0,o.registerEventHandler)(document,"submit",t),(0,o.registerEventHandler)(window,"error",t),(0,o.registerEventHandler)(window,"beforeunload",()=>this.re()),(0,o.registerEventHandler)(window,"scroll",()=>this.se()))}ie(t){var e;let n=null==(e=t.type)?void 0:e.toLowerCase();"error"===n&&t instanceof ErrorEvent?this.ue(t):(e=(0,o.getTargetNode)(t))&&(0,o.shouldLogEvent)(t,e)&&("submit"===n&&(n="form_submit"),{value:t,metadata:e}=(0,o.gatherEventData)(e),this.fe(n,t,e))}ee(){this.ne(),this.ae(),this.ce()}ue(t){var e=(null==t?void 0:t.error)||{};let n=e;if("object"==typeof e)try{n=JSON.stringify(e)}catch(t){n="function"==typeof(null==e?void 0:e.toString)?e.toString():"Unknown Error"}this.fe("error",t.message,{message:t.message,filename:t.filename,lineno:t.lineno,colno:t.colno,error_str:n})}ae(){setTimeout(()=>{var t=(0,o.getSafeUrl)();this._e("page_view",(0,o.getSanitizedPageUrl)(),{title:null===document||void 0===document?void 0:document.title,queryParams:Object.fromEntries(t.searchParams)})},1)}ce(){"undefined"!=typeof window&&void 0!==window.performance&&"function"==typeof window.performance.getEntriesByType&&"function"==typeof window.performance.getEntriesByName&&setTimeout(()=>{var t={},e=window.performance.getEntriesByType("navigation"),e=(e&&0<e.length&&e[0]instanceof PerformanceNavigationTiming&&(e=e[0],t.load_time_ms=e.duration,t.dom_interactive_time_ms=e.domInteractive-e.startTime,t.redirect_count=e.redirectCount,t.transfer_bytes=e.transferSize),window.performance.getEntriesByName("first-contentful-paint"));e&&0<e.length&&e[0]instanceof PerformancePaintTiming&&(t.first_contentful_paint_time_ms=e[0].startTime),this.fe("performance",(0,o.getSanitizedPageUrl)(),t)},1)}re(){this._e("page_view_end",(0,o.getSanitizedPageUrl)(),{scrollDepth:this.te,pageViewLength:Date.now()-this.Zt})}fe(t,e,n){e={eventName:"auto_capture::"+t,value:e,metadata:Object.assign({sessionId:(0,o.getWebSessionId)(this.l),page_url:(null==(t=null===window||void 0===window?void 0:window.location)?void 0:t.href)||""},n)};this.ve.logEvent(e),i.Log.debug("Enqueued Event",e)}_e(t,e,n){this.fe(t,e,n),this.ve.flush().catch(t=>{i.Log.error(t)})}se(){var t=document.body.scrollHeight||1;this.te=Math.max(this.te,Math.min(100,Math.round((window.scrollY+window.innerHeight)/t*100)))}}},76:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.registerEventHandler=e.getSanitizedPageUrl=e.getWebSessionId=e.getSafeUrl=e.shouldLogEvent=e.getTargetNode=e.gatherEventData=void 0;const o=n(464),r={};function s(e){if(e){let t=e;for(;t;){var n=t.tagName.toLowerCase();if(["body","document"].includes(n))return null;if("a"===t.tagName.toLowerCase())return t;t=t.parentElement}}return null}e.gatherEventData=function(t){var e=t.tagName.toLowerCase(),n={},i=e,o=("form"===e&&(n.action=t.getAttribute("action"),n.method=null!=(o=t.getAttribute("method"))?o:"GET",n.formName=t.getAttribute("name"),n.formId=t.getAttribute("id")),["input","select","textarea"].includes(e)&&"password"!==t.getAttribute("type")&&(n.content=t.value,n.inputName=t.getAttribute("name")),"button"===e&&(n.content=(t.textContent||"").trim()),s(t));return o&&(n.href=o.getAttribute("href")),{value:i,metadata:n}},e.getTargetNode=function(t){if(!t)return null;let e=t.target||t.srcElement;return e&&e instanceof Element?e=3===e.nodeType?e.parentNode||null:e:null},e.shouldLogEvent=function(t,e){if(!t||!e||1!==e.nodeType)return!1;var n=e.tagName.toLowerCase(),i=t.type.toLowerCase();switch(n){case"html":return!1;case"form":return"submit"===i;case"input":case"select":case"textarea":return["change"].includes(i);default:if("click"===i){if("button"===n)return!0;if(s(e))return!0}return!1}},e.getSafeUrl=function(){var t=(null==(t=null===window||void 0===window?void 0:window.location)?void 0:t.href)||"";let e;try{e=new URL(t)}catch(t){e=new URL("error:")}return e},e.getWebSessionId=function(t){var e=function(t){if(window&&window.localStorage)return window.localStorage.getItem(t);return r[t]}(t="statsig.web_analytics.session."+(0,o.DJB2)(t)),n=Date.now();let i=e?(0,o.typedJsonParse)(e,"lastAccessedTime","Failed to parse WebSession"):null;return(i=!i||144e5<n-i.startTime||6e5<n-i.lastAccessedTime?(e=Date.now(),{id:(0,o.getUUID)(),startTime:e,lastAccessedTime:e}):i).lastAccessedTime=n,e=t,n=JSON.stringify(i),window&&window.localStorage?window.localStorage.setItem(e,n):(r[e]=n,o.Log.error("Statsig Web AutoCapture: No window.localStorage")),i.id},e.getSanitizedPageUrl=function(){var t;return(null==(t=null==(t=null===window||void 0===window?void 0:window.location)?void 0:t.href)?void 0:t.split(/[?#]/)[0])||""},e.registerEventHandler=function(t,e,n){t&&t.addEventListener&&t.addEventListener(e,n,!0)}},976:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WebAnalytics=void 0;const i=n(464),o=n(208),r=n(536);class s{static autoInit(t){var e=null==(e=null===__STATSIG__||void 0===__STATSIG__?void 0:__STATSIG__.instances)?void 0:e[t];e instanceof o.StatsigClient&&(this.ve=e),this.ve||(this.ve=new o.StatsigClient(t,{userID:"web-analytics-user::"+(0,i.getUUID)()})),this.he=new r.AutoCapture(t,this.ve),this.ve.initializeSync()}}(e.WebAnalytics=s).he=null,s.ve=null}},i={};function o(t){var e=i[t];return void 0!==e||(e=i[t]={exports:{}},n[t].call(e.exports,e,e.exports,o)),e.exports}o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}();var t={};{var e,r=t;const a=o(464),c=o(536),d=o(976);if(__STATSIG__=Object.assign(Object.assign({},null!==__STATSIG__&&void 0!==__STATSIG__?__STATSIG__:{}),{WebAnalytics:d.WebAnalytics,AutoCapture:c.AutoCapture}),r.default=__STATSIG__,"undefined"!=typeof window&&"undefined"!=typeof document&&document.currentScript){var r=document.currentScript.getAttribute("src"),s=null==(s=null===window||void 0===window?void 0:window.location)?void 0:s.href;if(r&&s)try{var u=new URL(r,s).searchParams,l=null!=(e=u.get("sdkkey"))?e:u.get("sdkKey");l?d.WebAnalytics.autoInit(l):a.Log.error("Statsig Web AutoCapture: No SDK key provided")}catch(t){a.Log.error("Statsig Web AutoCapture: Invalid source URL")}}}return t.default})());
package/package.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "@statsig/web-analytics",
3
+ "version": "0.0.1-beta.21",
4
+ "dependencies": {
5
+ "@statsig/client-core": "0.0.1-beta.21",
6
+ "@statsig/js-client": "0.0.1-beta.21"
7
+ },
8
+ "type": "commonjs",
9
+ "main": "./src/index.js",
10
+ "typings": "./src/index.d.ts"
11
+ }
@@ -0,0 +1,18 @@
1
+ import { StatsigClient } from '@statsig/js-client';
2
+ export declare class AutoCapture {
3
+ private _sdkKey;
4
+ private _client;
5
+ private _startTime;
6
+ private _deepestScroll;
7
+ constructor(_sdkKey: string, _client: StatsigClient);
8
+ private _addEventHandlers;
9
+ private _autoLogEvent;
10
+ private _initialize;
11
+ private _logError;
12
+ private _logPageView;
13
+ private _logPerformance;
14
+ private _pageUnloadHandler;
15
+ private _enqueueAutoCapture;
16
+ private _logAutoCaptureImmediately;
17
+ private _scrollEventHandler;
18
+ }
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AutoCapture = void 0;
4
+ const client_core_1 = require("@statsig/client-core");
5
+ const Utils_1 = require("./Utils");
6
+ class AutoCapture {
7
+ constructor(_sdkKey, _client) {
8
+ this._sdkKey = _sdkKey;
9
+ this._client = _client;
10
+ this._startTime = Date.now();
11
+ this._deepestScroll = 0;
12
+ if (typeof document !== 'undefined' && document.readyState === 'loading') {
13
+ document.addEventListener('DOMContentLoaded', () => this._initialize());
14
+ return;
15
+ }
16
+ this._initialize();
17
+ }
18
+ _addEventHandlers() {
19
+ if (typeof window === 'undefined' || typeof document === 'undefined') {
20
+ return;
21
+ }
22
+ const eventHandler = (event) => {
23
+ this._autoLogEvent(event || window.event);
24
+ };
25
+ (0, Utils_1.registerEventHandler)(document, 'click', eventHandler);
26
+ (0, Utils_1.registerEventHandler)(document, 'submit', eventHandler);
27
+ (0, Utils_1.registerEventHandler)(window, 'error', eventHandler);
28
+ (0, Utils_1.registerEventHandler)(window, 'beforeunload', () => this._pageUnloadHandler());
29
+ (0, Utils_1.registerEventHandler)(window, 'scroll', () => this._scrollEventHandler());
30
+ }
31
+ _autoLogEvent(event) {
32
+ var _a;
33
+ let eventType = (_a = event.type) === null || _a === void 0 ? void 0 : _a.toLowerCase();
34
+ if (eventType === 'error' && event instanceof ErrorEvent) {
35
+ this._logError(event);
36
+ return;
37
+ }
38
+ const target = (0, Utils_1.getTargetNode)(event);
39
+ if (!target) {
40
+ return;
41
+ }
42
+ if (!(0, Utils_1.shouldLogEvent)(event, target)) {
43
+ return;
44
+ }
45
+ if (eventType === 'submit') {
46
+ eventType = 'form_submit';
47
+ }
48
+ const { value, metadata } = (0, Utils_1.gatherEventData)(target);
49
+ this._enqueueAutoCapture(eventType, value, metadata);
50
+ }
51
+ _initialize() {
52
+ this._addEventHandlers();
53
+ this._logPageView();
54
+ this._logPerformance();
55
+ }
56
+ _logError(event) {
57
+ const error = (event === null || event === void 0 ? void 0 : event.error) || {};
58
+ let errorStr = error;
59
+ if (typeof error === 'object') {
60
+ try {
61
+ errorStr = JSON.stringify(error);
62
+ }
63
+ catch (e) {
64
+ errorStr =
65
+ typeof (error === null || error === void 0 ? void 0 : error.toString) === 'function'
66
+ ? error.toString()
67
+ : 'Unknown Error';
68
+ }
69
+ }
70
+ this._enqueueAutoCapture('error', event.message, {
71
+ message: event.message,
72
+ filename: event.filename,
73
+ lineno: event.lineno,
74
+ colno: event.colno,
75
+ error_str: errorStr,
76
+ });
77
+ }
78
+ _logPageView() {
79
+ setTimeout(() => {
80
+ const url = (0, Utils_1.getSafeUrl)();
81
+ this._logAutoCaptureImmediately('page_view', (0, Utils_1.getSanitizedPageUrl)(), {
82
+ title: document === null || document === void 0 ? void 0 : document.title,
83
+ queryParams: Object.fromEntries(url.searchParams),
84
+ });
85
+ }, 1);
86
+ }
87
+ _logPerformance() {
88
+ if (typeof window === 'undefined' ||
89
+ typeof window.performance === 'undefined' ||
90
+ typeof window.performance.getEntriesByType !== 'function' ||
91
+ typeof window.performance.getEntriesByName !== 'function') {
92
+ return;
93
+ }
94
+ setTimeout(() => {
95
+ const metadata = {};
96
+ const navEntries = window.performance.getEntriesByType('navigation');
97
+ if (navEntries &&
98
+ navEntries.length > 0 &&
99
+ navEntries[0] instanceof PerformanceNavigationTiming) {
100
+ const nav = navEntries[0];
101
+ metadata['load_time_ms'] = nav.duration;
102
+ metadata['dom_interactive_time_ms'] =
103
+ nav.domInteractive - nav.startTime;
104
+ metadata['redirect_count'] = nav.redirectCount;
105
+ metadata['transfer_bytes'] = nav.transferSize;
106
+ }
107
+ const fpEntries = window.performance.getEntriesByName('first-contentful-paint');
108
+ if (fpEntries &&
109
+ fpEntries.length > 0 &&
110
+ fpEntries[0] instanceof PerformancePaintTiming) {
111
+ metadata['first_contentful_paint_time_ms'] = fpEntries[0].startTime;
112
+ }
113
+ this._enqueueAutoCapture('performance', (0, Utils_1.getSanitizedPageUrl)(), metadata);
114
+ }, 1);
115
+ }
116
+ _pageUnloadHandler() {
117
+ this._logAutoCaptureImmediately('page_view_end', (0, Utils_1.getSanitizedPageUrl)(), {
118
+ scrollDepth: this._deepestScroll,
119
+ pageViewLength: Date.now() - this._startTime,
120
+ });
121
+ }
122
+ _enqueueAutoCapture(name, value, metadata) {
123
+ var _a;
124
+ const event = {
125
+ eventName: `auto_capture::${name}`,
126
+ value,
127
+ metadata: Object.assign({ sessionId: (0, Utils_1.getWebSessionId)(this._sdkKey), page_url: ((_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.href) || '' }, metadata),
128
+ };
129
+ this._client.logEvent(event);
130
+ client_core_1.Log.debug('Enqueued Event', event);
131
+ }
132
+ _logAutoCaptureImmediately(name, value, metadata) {
133
+ this._enqueueAutoCapture(name, value, metadata);
134
+ this._client.flush().catch((e) => {
135
+ client_core_1.Log.error(e);
136
+ });
137
+ }
138
+ _scrollEventHandler() {
139
+ const scrollHeight = document.body.scrollHeight || 1;
140
+ this._deepestScroll = Math.max(this._deepestScroll, Math.min(100, Math.round(((window.scrollY + window.innerHeight) / scrollHeight) * 100)));
141
+ }
142
+ }
143
+ exports.AutoCapture = AutoCapture;
package/src/Utils.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ export declare function gatherEventData(target: Element): {
2
+ value: string;
3
+ metadata: Record<string, string | null>;
4
+ };
5
+ export declare function getTargetNode(e: Event): Element | null;
6
+ export declare function shouldLogEvent(e: Event, el: Element): boolean;
7
+ export declare function getSafeUrl(): URL;
8
+ export declare function getWebSessionId(sdkKey: string): string;
9
+ export declare function getSanitizedPageUrl(): string;
10
+ export declare function registerEventHandler(element: Document | Window, eventType: string, handler: (event: Event) => void): void;
package/src/Utils.js ADDED
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerEventHandler = exports.getSanitizedPageUrl = exports.getWebSessionId = exports.getSafeUrl = exports.shouldLogEvent = exports.getTargetNode = exports.gatherEventData = void 0;
4
+ const client_core_1 = require("@statsig/client-core");
5
+ const MAX_SESSION_IDLE_TIME = 10 * 60 * 1000; // 10 minutes
6
+ const MAX_SESSION_AGE = 4 * 60 * 60 * 1000; // 4 hours
7
+ const globals = {};
8
+ function gatherEventData(target) {
9
+ var _a;
10
+ const tagName = target.tagName.toLowerCase();
11
+ const metadata = {};
12
+ const value = tagName;
13
+ if (tagName === 'form') {
14
+ metadata['action'] = target.getAttribute('action');
15
+ metadata['method'] = (_a = target.getAttribute('method')) !== null && _a !== void 0 ? _a : 'GET';
16
+ metadata['formName'] = target.getAttribute('name');
17
+ metadata['formId'] = target.getAttribute('id');
18
+ }
19
+ if (['input', 'select', 'textarea'].includes(tagName) &&
20
+ target.getAttribute('type') !== 'password') {
21
+ metadata['content'] = target.value;
22
+ metadata['inputName'] = target.getAttribute('name');
23
+ }
24
+ if (tagName === 'button') {
25
+ metadata['content'] = (target.textContent || '').trim();
26
+ }
27
+ const anchor = _getAnchorNodeInHierarchy(target);
28
+ if (anchor) {
29
+ metadata['href'] = anchor.getAttribute('href');
30
+ }
31
+ return { value, metadata };
32
+ }
33
+ exports.gatherEventData = gatherEventData;
34
+ function getTargetNode(e) {
35
+ if (!e) {
36
+ return null;
37
+ }
38
+ let target = e.target || e.srcElement;
39
+ if (!target || !(target instanceof Element)) {
40
+ return null;
41
+ }
42
+ if (target.nodeType === 3) {
43
+ target = (target.parentNode || null);
44
+ }
45
+ return target;
46
+ }
47
+ exports.getTargetNode = getTargetNode;
48
+ function shouldLogEvent(e, el) {
49
+ if (!e || !el || el.nodeType !== 1) {
50
+ return false;
51
+ }
52
+ const tagName = el.tagName.toLowerCase();
53
+ const eventType = e.type.toLowerCase();
54
+ switch (tagName) {
55
+ case 'html':
56
+ return false;
57
+ case 'form':
58
+ return eventType === 'submit';
59
+ case 'input':
60
+ case 'select':
61
+ case 'textarea':
62
+ return ['change'].includes(eventType);
63
+ default:
64
+ if (eventType === 'click') {
65
+ if (tagName === 'button') {
66
+ return true;
67
+ }
68
+ const anchor = _getAnchorNodeInHierarchy(el);
69
+ if (anchor) {
70
+ return true;
71
+ }
72
+ }
73
+ return false;
74
+ }
75
+ }
76
+ exports.shouldLogEvent = shouldLogEvent;
77
+ function getSafeUrl() {
78
+ var _a;
79
+ const href = ((_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.href) || '';
80
+ let url;
81
+ try {
82
+ url = new URL(href);
83
+ }
84
+ catch (e) {
85
+ url = new URL('error:');
86
+ }
87
+ return url;
88
+ }
89
+ exports.getSafeUrl = getSafeUrl;
90
+ function getWebSessionId(sdkKey) {
91
+ const key = `statsig.web_analytics.session.${(0, client_core_1.DJB2)(sdkKey)}`;
92
+ const json = _getLocalValue(key);
93
+ const now = Date.now();
94
+ let session = json
95
+ ? (0, client_core_1.typedJsonParse)(json, 'lastAccessedTime', 'Failed to parse WebSession')
96
+ : null;
97
+ if (!session ||
98
+ now - session.startTime > MAX_SESSION_AGE ||
99
+ now - session.lastAccessedTime > MAX_SESSION_IDLE_TIME) {
100
+ session = _createNewSession();
101
+ }
102
+ session.lastAccessedTime = now;
103
+ _setLocalValue(key, JSON.stringify(session));
104
+ return session.id;
105
+ }
106
+ exports.getWebSessionId = getWebSessionId;
107
+ function getSanitizedPageUrl() {
108
+ var _a, _b;
109
+ const url = (_b = (_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.href) === null || _b === void 0 ? void 0 : _b.split(/[?#]/)[0];
110
+ return url || '';
111
+ }
112
+ exports.getSanitizedPageUrl = getSanitizedPageUrl;
113
+ function registerEventHandler(element, eventType, handler) {
114
+ if (!element || !element.addEventListener) {
115
+ return;
116
+ }
117
+ element.addEventListener(eventType, handler, true);
118
+ }
119
+ exports.registerEventHandler = registerEventHandler;
120
+ function _getAnchorNodeInHierarchy(node) {
121
+ if (!node) {
122
+ return null;
123
+ }
124
+ let parent = node;
125
+ while (parent) {
126
+ const parentTagName = parent.tagName.toLowerCase();
127
+ if (['body', 'document'].includes(parentTagName)) {
128
+ return null;
129
+ }
130
+ if (parent.tagName.toLowerCase() === 'a') {
131
+ return parent;
132
+ }
133
+ parent = parent.parentElement;
134
+ }
135
+ return null;
136
+ }
137
+ function _setLocalValue(key, value) {
138
+ if (window && window.localStorage) {
139
+ window.localStorage.setItem(key, value);
140
+ }
141
+ else {
142
+ globals[key] = value;
143
+ client_core_1.Log.error('Statsig Web AutoCapture: No window.localStorage');
144
+ }
145
+ }
146
+ function _getLocalValue(key) {
147
+ if (window && window.localStorage) {
148
+ return window.localStorage.getItem(key);
149
+ }
150
+ return globals[key];
151
+ }
152
+ function _createNewSession() {
153
+ const now = Date.now();
154
+ return {
155
+ id: (0, client_core_1.getUUID)(),
156
+ startTime: now,
157
+ lastAccessedTime: now,
158
+ };
159
+ }
@@ -0,0 +1,5 @@
1
+ export declare class WebAnalytics {
2
+ private static _capture;
3
+ private static _client;
4
+ static autoInit(sdkKey: string): void;
5
+ }
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebAnalytics = void 0;
4
+ const client_core_1 = require("@statsig/client-core");
5
+ const js_client_1 = require("@statsig/js-client");
6
+ const AutoCapture_1 = require("./AutoCapture");
7
+ class WebAnalytics {
8
+ static autoInit(sdkKey) {
9
+ var _a;
10
+ const current = (_a = __STATSIG__ === null || __STATSIG__ === void 0 ? void 0 : __STATSIG__.instances) === null || _a === void 0 ? void 0 : _a[sdkKey];
11
+ if (current instanceof js_client_1.StatsigClient) {
12
+ this._client = current;
13
+ }
14
+ if (!this._client) {
15
+ this._client = new js_client_1.StatsigClient(sdkKey, {
16
+ userID: `web-analytics-user::${(0, client_core_1.getUUID)()}`,
17
+ });
18
+ }
19
+ this._capture = new AutoCapture_1.AutoCapture(sdkKey, this._client);
20
+ this._client.initializeSync();
21
+ }
22
+ }
23
+ exports.WebAnalytics = WebAnalytics;
24
+ WebAnalytics._capture = null;
25
+ WebAnalytics._client = null;
package/src/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { AutoCapture } from './AutoCapture';
2
+ import { WebAnalytics } from './WebAnalytics';
3
+ export { WebAnalytics, AutoCapture };
4
+ export default __STATSIG__;
package/src/index.js ADDED
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AutoCapture = exports.WebAnalytics = void 0;
4
+ const client_core_1 = require("@statsig/client-core");
5
+ const AutoCapture_1 = require("./AutoCapture");
6
+ Object.defineProperty(exports, "AutoCapture", { enumerable: true, get: function () { return AutoCapture_1.AutoCapture; } });
7
+ const WebAnalytics_1 = require("./WebAnalytics");
8
+ Object.defineProperty(exports, "WebAnalytics", { enumerable: true, get: function () { return WebAnalytics_1.WebAnalytics; } });
9
+ __STATSIG__ = Object.assign(Object.assign({}, (__STATSIG__ !== null && __STATSIG__ !== void 0 ? __STATSIG__ : {})), { WebAnalytics: WebAnalytics_1.WebAnalytics,
10
+ AutoCapture: AutoCapture_1.AutoCapture });
11
+ exports.default = __STATSIG__;
12
+ function _attemptAutoInit() {
13
+ var _a, _b;
14
+ if (typeof window === 'undefined' ||
15
+ typeof document === 'undefined' ||
16
+ !document.currentScript) {
17
+ return;
18
+ }
19
+ const srcUrl = document.currentScript.getAttribute('src');
20
+ const baseUrl = (_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.href;
21
+ if (!srcUrl || !baseUrl) {
22
+ return;
23
+ }
24
+ try {
25
+ const url = new URL(srcUrl, baseUrl);
26
+ const params = url.searchParams;
27
+ const sdkKey = (_b = params.get('sdkkey')) !== null && _b !== void 0 ? _b : params.get('sdkKey');
28
+ if (sdkKey) {
29
+ WebAnalytics_1.WebAnalytics.autoInit(sdkKey);
30
+ }
31
+ else {
32
+ client_core_1.Log.error('Statsig Web AutoCapture: No SDK key provided');
33
+ }
34
+ }
35
+ catch (e) {
36
+ client_core_1.Log.error('Statsig Web AutoCapture: Invalid source URL');
37
+ }
38
+ }
39
+ _attemptAutoInit();