@flagsmith/flagsmith 11.0.0-internal.6 → 11.0.0-internal.7

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/index.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).index={})}(this,(function(t){"use strict";var e={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},n=function(){return n=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},n.apply(this,arguments)};function i(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{s(i.next(t))}catch(t){o(t)}}function l(t){try{s(i.throw(t))}catch(t){o(t)}}function s(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,l)}s((i=i.apply(t,e||[])).next())}))}function a(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function o(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var r=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function l(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!r(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function s(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function u(t){return!!t&&"object"==typeof t&&void 0!==t.value}function c(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))}function v(t){return n(n({},t),{identity:t.identity?n(n({},t.identity),{traits:c(t.identity.traits||{})}):void 0})}function h(t){return t.endsWith("/")?t:t+"/"}var d,g,f,p="11.0.0-internal.6";t.FlagSource=void 0,(d=t.FlagSource||(t.FlagSource={})).NONE="NONE",d.DEFAULT_FLAGS="DEFAULT_FLAGS",d.CACHE="CACHE",d.SERVER="SERVER",t.PipelineEventType=void 0,(g=t.PipelineEventType||(t.PipelineEventType={})).FLAG_EVALUATION="flag_evaluation",g.CUSTOM_EVENT="custom_event";var y,m=null,S="FLAGSMITH_EVENT",C=S,E="https://edge.api.flagsmith.com/api/v1/",_="flagsmith_value_",b="flagsmith_enabled_",x="flagsmith_trait_",F=function(){function e(e){var o=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var e=o,i=e.api,a=e.evaluationContext;o.log("Get Flags"),o.isLoading=!0,o.loadingState.isFetching||o.setLoadingState(n(n({},o.loadingState),{isFetching:!0}));var r="".concat(o.getContext().identity),u=function(e){var i,a,u,c;if(e&&r==="".concat(o.getContext().identity)){var v=e.flags,h=e.traits,d=e.identifier;o.isLoading=!1;var g={},f={};h=h||[],(v=v||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),h.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),o.oldFlags=n({},o.flags);var p=l(o.oldFlags,g),y=l(null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.traits,f);if((d||Object.keys(f).length)&&(o.evaluationContext.identity=n(n({},o.evaluationContext.identity),{traits:f}),d&&(o.evaluationContext.identity.identifier=d,o.identity=d)),o.flags=g,o.updateStorage(),o._onChange(o.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},o._loadedState(null,t.FlagSource.SERVER)),o.datadogRum)try{if(o.datadogRum.trackTraits){var m={};Object.keys((null===(a=o.evaluationContext.identity)||void 0===a?void 0:a.traits)||{}).map((function(t){m[x+t]=o.getTrait(t)}));var S=n(n(n({},o.datadogRum.client.getUser()),{id:o.datadogRum.client.getUser().id||(null===(u=o.evaluationContext.identity)||void 0===u?void 0:u.identifier)}),m);o.log("Setting Datadog user",S),o.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(o.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(o.flags).map((function(t){s(C,_+t,o.getValue(t,{skipAnalytics:!0})),s(C,b+t,o.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=o.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){s(C,x+t,o.getTrait(t))})),o.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),o.log("Sending date traits to dynatrace",C.date),o.log("Sending shortString traits to dynatrace",C.shortString),o.log("Sending javaDouble to dynatrace",C.javaDouble),o.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return a.identity?Promise.all([a.identity.traits&&Object.keys(a.identity.traits).length||!a.identity.identifier?o.getJSON(i+"identities/","POST",JSON.stringify({identifier:a.identity.identifier,transient:a.identity.transient,traits:Object.entries(a.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(o.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):o.getJSON(i+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(t){return o.evaluationContext.identity=n(n({},o.evaluationContext.identity),{traits:{}}),u(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):o.getJSON(i+"flags/").then((function(t){return u({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=o.api;if(o.evaluationEvent&&o.evaluationContext.environment&&o.evaluationEvent[o.evaluationContext.environment.apiKey])return o.evaluationEvent&&0!==Object.getOwnPropertyNames(o.evaluationEvent).length&&0!==Object.getOwnPropertyNames(o.evaluationEvent[o.evaluationContext.environment.apiKey]).length?o.getJSON(t+"analytics/flags/","POST",JSON.stringify(o.evaluationEvent[o.evaluationContext.environment.apiKey])).then((function(t){if(o.evaluationContext.environment){var e=o.getState();o.evaluationEvent||(o.evaluationEvent={}),o.evaluationEvent[o.evaluationContext.environment.apiKey]={},o.setState(n(n({},e),{evaluationEvent:o.evaluationEvent})),o.updateEventStorage()}})).catch((function(t){o.log("Exception fetching evaluationEvent",t)})):void 0},this.flushPipelineAnalytics=function(){return i(o,void 0,void 0,(function(){var t,e,i,o,r,l,s;return a(this,(function(a){switch(a.label){case 0:if(t=this.evaluationAnalyticsUrl&&this.evaluationContext.environment,e=this.pipelineEvents.length>0&&(!this.isPipelineFlushing||0===this.pipelineFlushInterval),!t||!e)return[2];i=this.evaluationContext.environment.apiKey,this.isPipelineFlushing=!0,o=this.pipelineEvents.slice(0,this.evaluationAnalyticsMaxBuffer),this.pipelineEvents=this.pipelineEvents.slice(this.evaluationAnalyticsMaxBuffer),this.pipelineRecordedKeys.clear(),r={events:o,environment_key:i},a.label=1;case 1:return a.trys.push([1,3,4,5]),[4,f(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(r),headers:n({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":i},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat(p)})})];case 2:if(!(l=a.sent()).status||l.status<200||l.status>=300)throw new Error("Pipeline analytics: unexpected status ".concat(l.status));return this.log("Pipeline analytics: flush successful"),[3,5];case 3:return s=a.sent(),this.pipelineEvents=o.concat(this.pipelineEvents),this.log("Pipeline analytics: flush failed, events re-queued",s),[3,5];case 4:return this.isPipelineFlushing=!1,[7];case 5:return[2]}}))}))},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:t.FlagSource.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.evaluationAnalyticsUrl=null,this.evaluationAnalyticsMaxBuffer=1e3,this.pipelineEvents=[],this.pipelineAnalyticsInterval=null,this.isPipelineFlushing=!1,this.pipelineRecordedKeys=new Map,this.getValue=function(t,e,n){var i=o.flags&&o.flags[t.toLowerCase().replace(/ /g,"_")],a=null;if(i&&(a=i.value),(null==e?void 0:e.skipAnalytics)||n||o.evaluateFlag(t,"VALUE"),null===a&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===a?(o.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(a)}catch(t){return e.fallback}return a},this.getTrait=function(t){var e,n;return(null===(e=o.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=o.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=o.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var e,i,a=v(t);return o.evaluationContext=n(n({},a),{environment:a.environment||o.evaluationContext.environment}),o.identity=null===(i=null===(e=o.getContext())||void 0===e?void 0:e.identity)||void 0===i?void 0:i.identifier,o.initialised?o.getFlags():Promise.resolve()},this.getContext=function(){return o.evaluationContext},this.updateContext=function(t){return o.setContext(n(n({},o.getContext()),t))},this.setTrait=function(t,e){var i;if(o.api)return o.setContext(n(n({},o.evaluationContext),{identity:n(n({},o.evaluationContext.identity),{traits:n(n({},null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.traits),c(Object.fromEntries([[t,e]])))})}))},this.setTraits=function(t){var e;if(o.api)return o.setContext(n(n({},o.evaluationContext),{identity:n(n({},o.evaluationContext.identity),{traits:n(n({},null===(e=o.evaluationContext.identity)||void 0===e?void 0:e.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,i,a="object"==typeof e,r=o.flags&&o.flags[t.toLowerCase().replace(/ /g,"_")],l=!1;if(!r&&a&&void 0!==e.fallback?l=null==e?void 0:e.fallback:r&&r.enabled&&(l=!0),(a&&!e.skipAnalytics||!e)&&o.evaluateFlag(t,"ENABLED"),o.sentryClient)try{null===(i=null===(n=o.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===i||i.call(n,t,l)}catch(t){console.error(t)}return l},this.getStorageKey=function(){var t,e;return(null===(t=o.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=o.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var i,a,r,l=o.headers,s={method:e||"GET",body:n,cache:"no-cache",headers:{}};o.evaluationContext.environment&&(s.headers["X-Environment-Key"]=o.evaluationContext.environment.apiKey),e&&"GET"!==e&&(s.headers["Content-Type"]="application/json; charset=utf-8"),(null===(i=o.applicationMetadata)||void 0===i?void 0:i.name)&&(s.headers["Flagsmith-Application-Name"]=o.applicationMetadata.name),(null===(a=o.applicationMetadata)||void 0===a?void 0:a.version)&&(s.headers["Flagsmith-Application-Version"]=o.applicationMetadata.version),s.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat(p),l&&Object.assign(s.headers,l),f||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=o.evaluationContext.identity)||void 0===r?void 0:r.identifier);return f(t,s).then((function(n){var i,a,r="".concat(null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.identifier);if(u===r){var l=null===(a=n.headers)||void 0===a?void 0:a.get("x-flagsmith-document-updated-at");if(l)try{var s=parseFloat(l);if(isNaN(s))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");o.timestamp=s}catch(t){o.log(t,"Failed to parse x-flagsmith-document-updated-at",l)}return o.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}o.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(o.datadogRum&&(o.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?o.datadogRum.client.addFeatureFlagEvaluation(_+t,o.getValue(t,{},!0)):o.datadogRum.client.addFeatureFlagEvaluation(b+t,o.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),o.enableAnalytics){if(!o.evaluationEvent||!o.evaluationContext.environment)return;o.evaluationEvent[o.evaluationContext.environment.apiKey]||(o.evaluationEvent[o.evaluationContext.environment.apiKey]={}),void 0===o.evaluationEvent[o.evaluationContext.environment.apiKey][t]&&(o.evaluationEvent[o.evaluationContext.environment.apiKey][t]=0),o.evaluationEvent[o.evaluationContext.environment.apiKey][t]+=1}o.evaluationAnalyticsUrl&&o.recordPipelineEvent(t),o.updateEventStorage()},this.pipelineFlushInterval=1e4,this.trackEvent=function(e,n){if(o.evaluationAnalyticsUrl&&e){var i=o.buildAnalyticEvent(t.PipelineEventType.CUSTOM_EVENT,e,{extraMetadata:n});o.pipelineEvents.push(i),(0===o.pipelineFlushInterval||o.pipelineEvents.length>=o.evaluationAnalyticsMaxBuffer)&&o.flushPipelineAnalytics()}},this._onChange=function(t,e,n){var i,a;o.setLoadingState(n),null===(i=o.onChange)||void 0===i||i.call(o,t,e,o.loadingState),null===(a=o._trigger)||void 0===a||a.call(o)},f=e.fetch?e.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!e.browserlessStorage,this.applicationMetadata=e.applicationMetadata,this.log("Constructing flagsmith instance "+e),e.eventSource&&(y=e.eventSource),e.AsyncStorage&&(m=e.AsyncStorage)}return e.prototype.init=function(e){var o,r,s,u;return i(this,void 0,void 0,(function(){var c,d,g,p,y,S,_,b,x,F,O,A,w,I,L,j,P,T,k,N,R,U,K,M,D,G,J,V,B,H,q,W,X,Y,$,z,Q=this;return a(this,(function(Z){switch(Z.label){case 0:c=v(e.evaluationContext||this.evaluationContext),Z.label=1;case 1:if(Z.trys.push([1,13,,14]),d=e.AsyncStorage,g=e._trigger,p=e._triggerLoadingState,y=e.angularHttpClient,S=e.api,_=void 0===S?E:S,b=e.applicationMetadata,x=e.cacheFlags,F=e.cacheOptions,O=e.datadogRum,A=e.defaultFlags,w=e.enableAnalytics,I=e.enableDynatrace,L=e.enableLogs,j=e.environmentID,P=e.evaluationAnalyticsConfig,T=e.eventSourceUrl,k=void 0===T?"https://realtime.flagsmith.com/":T,N=e.fetch,R=e.headers,U=e.identity,K=e.onChange,M=e.onError,D=e.preventFetch,G=e.realtime,J=e.sentryClient,V=e.state,B=e.traits,c.environment=j?{apiKey:j}:c.environment,!c.environment||!c.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(c.identity=U||B?{identifier:U,traits:B?Object.fromEntries(Object.entries(B).map((function(t){return[t[0],{value:t[1]}]}))):{}}:c.identity,this.evaluationContext=c,this.api=h(_),this.headers=R,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=K,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=g||this._trigger,this._triggerLoadingState=p||this._triggerLoadingState,this.onError=function(t){Q.setLoadingState(n(n({},Q.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==M||M(t)},this.enableLogs=L||!1,this.cacheOptions=F?{skipAPI:!!F.skipAPI,ttl:F.ttl||0,storageKey:F.storageKey,loadStale:!!F.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),N&&(f=N),this.enableAnalytics=w||!1,this.flags=Object.assign({},A)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==m&&!!x,this.applicationMetadata=b,C="FLAGSMITH_EVENT_"+c.environment.apiKey,d&&(m=d),G&&"undefined"!=typeof window&&this.setupRealtime(k,c.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=n(n({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(V),this.log("Initialising with properties",e,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),y&&(f=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},l=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(l(t,!t.status||t.status>=200&&t.status<300))},s=function(t){return n(l(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,s);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,s);default:return s({status:405,message:"Unsupported method: ".concat(a)})}}))}}(y)),m&&this.canUseStorage&&m.getItem(C).then((function(t){try{Q.evaluationEvent=JSON.parse(t)||{}}catch(t){Q.evaluationEvent={}}Q.analyticsInterval=setInterval(Q.analyticsFlags,Q.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),m&&this.canUseStorage&&m.getItem(C,(function(t,e){if(e&&Q.evaluationContext.environment){var i=JSON.parse(e);if(i[Q.evaluationContext.environment.apiKey]){var a=Q.getState();Q.log("Retrieved events from cache",e),Q.setState(n(n({},a),{evaluationEvent:i[Q.evaluationContext.environment.apiKey]}))}}}))),P?this.initPipelineAnalytics(P):this.stopPipelineAnalytics(),!x)return[3,9];if(!m||!this.canUseStorage)return[3,8];q=function(e,o){return i(Q,void 0,void 0,(function(){var e,i,r,s,u,c,h,d,g,f,p,y,m,S,C,E,_,b,x,F=this;return a(this,(function(a){switch(a.label){case 0:if(!o)return[3,7];e=null,i=null,a.label=1;case 1:return a.trys.push([1,5,,6]),r=JSON.parse(o),s=!1,u=!1,r&&r.api===this.api&&(null===(f=null===(g=r.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(c=!0,this.evaluationContext.identity&&(null===(m=null===(y=r.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=r.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),c=!1),this.cacheOptions.ttl&&(!r.ts||(new Date).valueOf()-r.ts>this.cacheOptions.ttl)&&(r.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),c=!1):r.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),u=!0,c=!0)),c&&(s=!0,e=l(this.flags,r.flags),this.setState(n(n({},r),{evaluationContext:v(n(n({},r.evaluationContext),{identity:(null===(E=r.evaluationContext)||void 0===E?void 0:E.identity)?n(n({},null===(_=r.evaluationContext)||void 0===_?void 0:_.identity),{traits:n({},B||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),s?(h=!D&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,t.FlagSource.CACHE,h)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!u&&this.log("Skipping API, using cache"),h&&this.getFlags().catch((function(t){var e;null===(e=F.onError)||void 0===e||e.call(F,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:a.sent(),a.label=4;case 4:return[3,6];case 5:throw d=a.sent(),this.log("Exception fetching cached logs",d),d;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return a.sent(),[3,10];case 9:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(b=this.evaluationContext.identity)||void 0===b?void 0:b.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(H);this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS))}a.label=10;case 10:return[2]}}))}))},Z.label=2;case 2:return Z.trys.push([2,7,,8]),m.getItemSync?(W=m.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,m.getItem(this.getStorageKey())];case 4:W=Z.sent(),Z.label=5;case 5:return[4,q(null,W)];case 6:return Z.sent(),[3,8];case 7:if(X=Z.sent(),!this.flags||0===Object.keys(this.flags).length)throw X;return z=X instanceof Error?X:new Error("".concat(X)),null===(o=this.onError)||void 0===o||o.call(this,z),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return Z.sent(),[3,12];case 11:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:l({},A),traitsChanged:l({},null===(r=c.identity)||void 0===r?void 0:r.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else if(this.flags&&(Y=null,0===Object.keys(this.flags).length&&(Y=H),this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(s=c.identity)||void 0===s?void 0:s.traits)},this._loadedState(Y,t.FlagSource.DEFAULT_FLAGS)),Y))throw new Error(Y);Z.label=12;case 12:return[3,14];case 13:throw $=Z.sent(),this.log("Error during initialisation ",$),z=$ instanceof Error?$:new Error("".concat($)),null===(u=this.onError)||void 0===u||u.call(this,z),$;case 14:return[2]}}))}))},e.prototype.getAllFlags=function(){return this.flags},e.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},e.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},e.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||E,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this))},e.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},e.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},e.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},e.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},e.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,o(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},e.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),m.setItem(this.getStorageKey(),t)}},e.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);m.setItem(C,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},e.prototype.initPipelineAnalytics=function(t){var e,n,i,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=h(t.analyticsServerUrl),this.evaluationAnalyticsMaxBuffer=null!==(e=t.maxBuffer)&&void 0!==e?e:1e3,this.pipelineFlushInterval=null!==(n=t.flushInterval)&&void 0!==n?n:1e4,this.pipelineEvents=[],this.pipelineFlushInterval>0&&(this.pipelineAnalyticsInterval=setInterval(this.flushPipelineAnalytics,this.pipelineFlushInterval),null===(a=null===(i=this.pipelineAnalyticsInterval)||void 0===i?void 0:i.unref)||void 0===a||a.call(i))},e.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},e.prototype.currentTraitsSnapshot=function(){var t;return(null===(t=this.evaluationContext.identity)||void 0===t?void 0:t.traits)?n({},this.evaluationContext.identity.traits):null},e.prototype.getPageUrl=function(){return"undefined"!=typeof window&&window.location?window.location.href:null},e.prototype.getEventMetadata=function(t){var e=this.getPageUrl();return n(n(n({},t||{}),e?{page_url:e}:{}),{sdk_version:p})},e.prototype.buildAnalyticEvent=function(t,e,n){var i,a,o,r,l;return{event_id:e,event_type:t,evaluated_at:null!==(i=null==n?void 0:n.timestamp)&&void 0!==i?i:Date.now(),identity_identifier:null!==(o=null===(a=this.evaluationContext.identity)||void 0===a?void 0:a.identifier)&&void 0!==o?o:null,enabled:null!==(r=null==n?void 0:n.enabled)&&void 0!==r?r:null,value:null!==(l=null==n?void 0:n.value)&&void 0!==l?l:null,traits:this.currentTraitsSnapshot(),metadata:this.getEventMetadata(null==n?void 0:n.extraMetadata)}},e.prototype.recordPipelineEvent=function(e){var n,i,a,o,r=e.toLowerCase().replace(/ /g,"_"),l=this.flags&&this.flags[r],s="".concat(null!==(i=null===(n=this.evaluationContext.identity)||void 0===n?void 0:n.identifier)&&void 0!==i?i:"none","|").concat(null!==(a=null==l?void 0:l.enabled)&&void 0!==a&&a,"|").concat(null!==(o=null==l?void 0:l.value)&&void 0!==o?o:"null");if(this.pipelineRecordedKeys.get(r)!==s){this.pipelineRecordedKeys.set(r,s);var u=this.buildAnalyticEvent(t.PipelineEventType.FLAG_EVALUATION,r,{enabled:l?l.enabled:null,value:l?l.value:null,extraMetadata:l?{id:l.id}:void 0});this.pipelineEvents.push(u),(0===this.pipelineFlushInterval||this.pipelineEvents.length>=this.evaluationAnalyticsMaxBuffer)&&this.flushPipelineAnalytics()}},e.prototype.setLoadingState=function(t){var e;r(t,this.loadingState)||(this.loadingState=n({},t),this.log("Loading state changed",t),null===(e=this._triggerLoadingState)||void 0===e||e.call(this))},e.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";y?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new y(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},e}();function O(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new F({fetch:e,AsyncStorage:n,eventSource:i})}var A,w=(A=function(t,e){return A=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},A(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}A(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),I=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},L=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},j=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},P=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return w(e,t),e}(Error),T=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new P;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=I(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=I(j([],L(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=j(j([],L(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var k=function(t,e){return e=e||{},new Promise((function(n,i){var a=new XMLHttpRequest,o=[],r=[],l={},s=function(){return{ok:2==(a.status/100|0),statusText:a.statusText,status:a.status,url:a.responseURL,text:function(){return Promise.resolve(a.responseText)},json:function(){return Promise.resolve(a.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([a.response]))},clone:s,headers:{keys:function(){return o},entries:function(){return r},get:function(t){return l[t.toLowerCase()]},has:function(t){return t.toLowerCase()in l}}}};for(var u in a.open(e.method||"get",t,!0),a.onload=function(){a.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(t,e,n){o.push(e=e.toLowerCase()),r.push([e,n]),l[e]=l[e]?l[e]+","+n:n})),n(s())},a.onerror=i,a.withCredentials="include"==e.credentials,e.headers)a.setRequestHeader(u,e.headers[u]);a.send(e.body||null)}))},N=O({AsyncStorage:e,fetch:k,eventSource:T});"undefined"!=typeof window&&(window.flagsmith=N);t.createFlagsmithInstance=function(){return O({AsyncStorage:e,fetch:k,eventSource:T})},t.default=N,Object.defineProperty(t,"__esModule",{value:!0})}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).index={})}(this,(function(t){"use strict";var e={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},n=function(){return n=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},n.apply(this,arguments)};function i(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{s(i.next(t))}catch(t){o(t)}}function l(t){try{s(i.throw(t))}catch(t){o(t)}}function s(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,l)}s((i=i.apply(t,e||[])).next())}))}function a(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function o(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var r=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function l(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!r(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function s(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function u(t){return!!t&&"object"==typeof t&&void 0!==t.value}function c(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))}function v(t){return n(n({},t),{identity:t.identity?n(n({},t.identity),{traits:c(t.identity.traits||{})}):void 0})}function h(t){return t.endsWith("/")?t:t+"/"}var d,g,f,p="11.0.0-internal.7";t.FlagSource=void 0,(d=t.FlagSource||(t.FlagSource={})).NONE="NONE",d.DEFAULT_FLAGS="DEFAULT_FLAGS",d.CACHE="CACHE",d.SERVER="SERVER",t.PipelineEventType=void 0,(g=t.PipelineEventType||(t.PipelineEventType={})).FLAG_EVALUATION="flag_evaluation",g.CUSTOM_EVENT="custom_event";var y,m=null,S="FLAGSMITH_EVENT",C=S,E="https://edge.api.flagsmith.com/api/v1/",_="flagsmith_value_",b="flagsmith_enabled_",x="flagsmith_trait_",F=function(){function e(e){var o=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var e=o,i=e.api,a=e.evaluationContext;o.log("Get Flags"),o.isLoading=!0,o.loadingState.isFetching||o.setLoadingState(n(n({},o.loadingState),{isFetching:!0}));var r="".concat(o.getContext().identity),u=function(e){var i,a,u,c;if(e&&r==="".concat(o.getContext().identity)){var v=e.flags,h=e.traits,d=e.identifier;o.isLoading=!1;var g={},f={};h=h||[],(v=v||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),h.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),o.oldFlags=n({},o.flags);var p=l(o.oldFlags,g),y=l(null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.traits,f);if((d||Object.keys(f).length)&&(o.evaluationContext.identity=n(n({},o.evaluationContext.identity),{traits:f}),d&&(o.evaluationContext.identity.identifier=d,o.identity=d)),o.flags=g,o.updateStorage(),o._onChange(o.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},o._loadedState(null,t.FlagSource.SERVER)),o.datadogRum)try{if(o.datadogRum.trackTraits){var m={};Object.keys((null===(a=o.evaluationContext.identity)||void 0===a?void 0:a.traits)||{}).map((function(t){m[x+t]=o.getTrait(t)}));var S=n(n(n({},o.datadogRum.client.getUser()),{id:o.datadogRum.client.getUser().id||(null===(u=o.evaluationContext.identity)||void 0===u?void 0:u.identifier)}),m);o.log("Setting Datadog user",S),o.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(o.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(o.flags).map((function(t){s(C,_+t,o.getValue(t,{skipAnalytics:!0})),s(C,b+t,o.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=o.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){s(C,x+t,o.getTrait(t))})),o.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),o.log("Sending date traits to dynatrace",C.date),o.log("Sending shortString traits to dynatrace",C.shortString),o.log("Sending javaDouble to dynatrace",C.javaDouble),o.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return a.identity?Promise.all([a.identity.traits&&Object.keys(a.identity.traits).length||!a.identity.identifier?o.getJSON(i+"identities/","POST",JSON.stringify({identifier:a.identity.identifier,transient:a.identity.transient,traits:Object.entries(a.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(o.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):o.getJSON(i+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(t){return o.evaluationContext.identity=n(n({},o.evaluationContext.identity),{traits:{}}),u(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):o.getJSON(i+"flags/").then((function(t){return u({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=o.api;if(o.evaluationEvent&&o.evaluationContext.environment&&o.evaluationEvent[o.evaluationContext.environment.apiKey])return o.evaluationEvent&&0!==Object.getOwnPropertyNames(o.evaluationEvent).length&&0!==Object.getOwnPropertyNames(o.evaluationEvent[o.evaluationContext.environment.apiKey]).length?o.getJSON(t+"analytics/flags/","POST",JSON.stringify(o.evaluationEvent[o.evaluationContext.environment.apiKey])).then((function(t){if(o.evaluationContext.environment){var e=o.getState();o.evaluationEvent||(o.evaluationEvent={}),o.evaluationEvent[o.evaluationContext.environment.apiKey]={},o.setState(n(n({},e),{evaluationEvent:o.evaluationEvent})),o.updateEventStorage()}})).catch((function(t){o.log("Exception fetching evaluationEvent",t)})):void 0},this.flushPipelineAnalytics=function(){return i(o,void 0,void 0,(function(){var t,e,i,o,r,l,s;return a(this,(function(a){switch(a.label){case 0:if(t=this.evaluationAnalyticsUrl&&this.evaluationContext.environment,e=this.pipelineEvents.length>0&&(!this.isPipelineFlushing||0===this.pipelineFlushInterval),!t||!e)return[2];i=this.evaluationContext.environment.apiKey,this.isPipelineFlushing=!0,o=this.pipelineEvents.slice(0,this.evaluationAnalyticsMaxBuffer),this.pipelineEvents=this.pipelineEvents.slice(this.evaluationAnalyticsMaxBuffer),this.pipelineRecordedKeys.clear(),r={events:o,environment_key:i},a.label=1;case 1:return a.trys.push([1,3,4,5]),[4,f(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(r),headers:n({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":i},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat(p)})})];case 2:if(!(l=a.sent()).status||l.status<200||l.status>=300)throw new Error("Pipeline analytics: unexpected status ".concat(l.status));return this.log("Pipeline analytics: flush successful"),[3,5];case 3:return s=a.sent(),this.pipelineEvents=o.concat(this.pipelineEvents),this.log("Pipeline analytics: flush failed, events re-queued",s),[3,5];case 4:return this.isPipelineFlushing=!1,[7];case 5:return[2]}}))}))},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:t.FlagSource.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.evaluationAnalyticsUrl=null,this.evaluationAnalyticsMaxBuffer=1e3,this.pipelineEvents=[],this.pipelineAnalyticsInterval=null,this.isPipelineFlushing=!1,this.pipelineRecordedKeys=new Map,this.getValue=function(t,e,n){var i=o.flags&&o.flags[t.toLowerCase().replace(/ /g,"_")],a=null;if(i&&(a=i.value),(null==e?void 0:e.skipAnalytics)||n||o.evaluateFlag(t,"VALUE"),null===a&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===a?(o.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(a)}catch(t){return e.fallback}return a},this.getTrait=function(t){var e,n;return(null===(e=o.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=o.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=o.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var e,i,a=v(t);return o.evaluationContext=n(n({},a),{environment:a.environment||o.evaluationContext.environment}),o.identity=null===(i=null===(e=o.getContext())||void 0===e?void 0:e.identity)||void 0===i?void 0:i.identifier,o.initialised?o.getFlags():Promise.resolve()},this.getContext=function(){return o.evaluationContext},this.updateContext=function(t){return o.setContext(n(n({},o.getContext()),t))},this.setTrait=function(t,e){var i;if(o.api)return o.setContext(n(n({},o.evaluationContext),{identity:n(n({},o.evaluationContext.identity),{traits:n(n({},null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.traits),c(Object.fromEntries([[t,e]])))})}))},this.setTraits=function(t){var e;if(o.api)return o.setContext(n(n({},o.evaluationContext),{identity:n(n({},o.evaluationContext.identity),{traits:n(n({},null===(e=o.evaluationContext.identity)||void 0===e?void 0:e.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,i,a="object"==typeof e,r=o.flags&&o.flags[t.toLowerCase().replace(/ /g,"_")],l=!1;if(!r&&a&&void 0!==e.fallback?l=null==e?void 0:e.fallback:r&&r.enabled&&(l=!0),(a&&!e.skipAnalytics||!e)&&o.evaluateFlag(t,"ENABLED"),o.sentryClient)try{null===(i=null===(n=o.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===i||i.call(n,t,l)}catch(t){console.error(t)}return l},this.getStorageKey=function(){var t,e;return(null===(t=o.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=o.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var i,a,r,l=o.headers,s={method:e||"GET",body:n,cache:"no-cache",headers:{}};o.evaluationContext.environment&&(s.headers["X-Environment-Key"]=o.evaluationContext.environment.apiKey),e&&"GET"!==e&&(s.headers["Content-Type"]="application/json; charset=utf-8"),(null===(i=o.applicationMetadata)||void 0===i?void 0:i.name)&&(s.headers["Flagsmith-Application-Name"]=o.applicationMetadata.name),(null===(a=o.applicationMetadata)||void 0===a?void 0:a.version)&&(s.headers["Flagsmith-Application-Version"]=o.applicationMetadata.version),s.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat(p),l&&Object.assign(s.headers,l),f||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=o.evaluationContext.identity)||void 0===r?void 0:r.identifier);return f(t,s).then((function(n){var i,a,r="".concat(null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.identifier);if(u===r){var l=null===(a=n.headers)||void 0===a?void 0:a.get("x-flagsmith-document-updated-at");if(l)try{var s=parseFloat(l);if(isNaN(s))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");o.timestamp=s}catch(t){o.log(t,"Failed to parse x-flagsmith-document-updated-at",l)}return o.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}o.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(o.datadogRum&&(o.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?o.datadogRum.client.addFeatureFlagEvaluation(_+t,o.getValue(t,{},!0)):o.datadogRum.client.addFeatureFlagEvaluation(b+t,o.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),o.enableAnalytics){if(!o.evaluationEvent||!o.evaluationContext.environment)return;o.evaluationEvent[o.evaluationContext.environment.apiKey]||(o.evaluationEvent[o.evaluationContext.environment.apiKey]={}),void 0===o.evaluationEvent[o.evaluationContext.environment.apiKey][t]&&(o.evaluationEvent[o.evaluationContext.environment.apiKey][t]=0),o.evaluationEvent[o.evaluationContext.environment.apiKey][t]+=1}o.evaluationAnalyticsUrl&&o.recordPipelineEvent(t),o.updateEventStorage()},this.pipelineFlushInterval=1e4,this.trackEvent=function(e,n){if(o.evaluationAnalyticsUrl&&e){var i=o.buildAnalyticEvent(t.PipelineEventType.CUSTOM_EVENT,e,{extraMetadata:n});o.pipelineEvents.push(i),(0===o.pipelineFlushInterval||o.pipelineEvents.length>=o.evaluationAnalyticsMaxBuffer)&&o.flushPipelineAnalytics()}},this._onChange=function(t,e,n){var i,a;o.setLoadingState(n),null===(i=o.onChange)||void 0===i||i.call(o,t,e,o.loadingState),null===(a=o._trigger)||void 0===a||a.call(o)},f=e.fetch?e.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!e.browserlessStorage,this.applicationMetadata=e.applicationMetadata,this.log("Constructing flagsmith instance "+e),e.eventSource&&(y=e.eventSource),e.AsyncStorage&&(m=e.AsyncStorage)}return e.prototype.init=function(e){var o,r,s,u;return i(this,void 0,void 0,(function(){var c,d,g,p,y,S,_,b,x,F,O,A,w,I,L,j,P,T,k,N,R,U,K,M,D,G,J,V,B,H,q,W,X,Y,$,z,Q=this;return a(this,(function(Z){switch(Z.label){case 0:c=v(e.evaluationContext||this.evaluationContext),Z.label=1;case 1:if(Z.trys.push([1,13,,14]),d=e.AsyncStorage,g=e._trigger,p=e._triggerLoadingState,y=e.angularHttpClient,S=e.api,_=void 0===S?E:S,b=e.applicationMetadata,x=e.cacheFlags,F=e.cacheOptions,O=e.datadogRum,A=e.defaultFlags,w=e.enableAnalytics,I=e.enableDynatrace,L=e.enableLogs,j=e.environmentID,P=e.evaluationAnalyticsConfig,T=e.eventSourceUrl,k=void 0===T?"https://realtime.flagsmith.com/":T,N=e.fetch,R=e.headers,U=e.identity,K=e.onChange,M=e.onError,D=e.preventFetch,G=e.realtime,J=e.sentryClient,V=e.state,B=e.traits,c.environment=j?{apiKey:j}:c.environment,!c.environment||!c.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(c.identity=U||B?{identifier:U,traits:B?Object.fromEntries(Object.entries(B).map((function(t){return[t[0],{value:t[1]}]}))):{}}:c.identity,this.evaluationContext=c,this.api=h(_),this.headers=R,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=K,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=g||this._trigger,this._triggerLoadingState=p||this._triggerLoadingState,this.onError=function(t){Q.setLoadingState(n(n({},Q.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==M||M(t)},this.enableLogs=L||!1,this.cacheOptions=F?{skipAPI:!!F.skipAPI,ttl:F.ttl||0,storageKey:F.storageKey,loadStale:!!F.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),N&&(f=N),this.enableAnalytics=w||!1,this.flags=Object.assign({},A)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==m&&!!x,this.applicationMetadata=b,C="FLAGSMITH_EVENT_"+c.environment.apiKey,d&&(m=d),G&&"undefined"!=typeof window&&this.setupRealtime(k,c.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=n(n({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(V),this.log("Initialising with properties",e,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),y&&(f=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},l=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(l(t,!t.status||t.status>=200&&t.status<300))},s=function(t){return n(l(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,s);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,s);default:return s({status:405,message:"Unsupported method: ".concat(a)})}}))}}(y)),m&&this.canUseStorage&&m.getItem(C).then((function(t){try{Q.evaluationEvent=JSON.parse(t)||{}}catch(t){Q.evaluationEvent={}}Q.analyticsInterval=setInterval(Q.analyticsFlags,Q.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),m&&this.canUseStorage&&m.getItem(C,(function(t,e){if(e&&Q.evaluationContext.environment){var i=JSON.parse(e);if(i[Q.evaluationContext.environment.apiKey]){var a=Q.getState();Q.log("Retrieved events from cache",e),Q.setState(n(n({},a),{evaluationEvent:i[Q.evaluationContext.environment.apiKey]}))}}}))),P?this.initPipelineAnalytics(P):this.stopPipelineAnalytics(),!x)return[3,9];if(!m||!this.canUseStorage)return[3,8];q=function(e,o){return i(Q,void 0,void 0,(function(){var e,i,r,s,u,c,h,d,g,f,p,y,m,S,C,E,_,b,x,F=this;return a(this,(function(a){switch(a.label){case 0:if(!o)return[3,7];e=null,i=null,a.label=1;case 1:return a.trys.push([1,5,,6]),r=JSON.parse(o),s=!1,u=!1,r&&r.api===this.api&&(null===(f=null===(g=r.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(c=!0,this.evaluationContext.identity&&(null===(m=null===(y=r.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=r.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),c=!1),this.cacheOptions.ttl&&(!r.ts||(new Date).valueOf()-r.ts>this.cacheOptions.ttl)&&(r.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),c=!1):r.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),u=!0,c=!0)),c&&(s=!0,e=l(this.flags,r.flags),this.setState(n(n({},r),{evaluationContext:v(n(n({},r.evaluationContext),{identity:(null===(E=r.evaluationContext)||void 0===E?void 0:E.identity)?n(n({},null===(_=r.evaluationContext)||void 0===_?void 0:_.identity),{traits:n({},B||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),s?(h=!D&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,t.FlagSource.CACHE,h)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!u&&this.log("Skipping API, using cache"),h&&this.getFlags().catch((function(t){var e;null===(e=F.onError)||void 0===e||e.call(F,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:a.sent(),a.label=4;case 4:return[3,6];case 5:throw d=a.sent(),this.log("Exception fetching cached logs",d),d;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return a.sent(),[3,10];case 9:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(b=this.evaluationContext.identity)||void 0===b?void 0:b.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(H);this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS))}a.label=10;case 10:return[2]}}))}))},Z.label=2;case 2:return Z.trys.push([2,7,,8]),m.getItemSync?(W=m.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,m.getItem(this.getStorageKey())];case 4:W=Z.sent(),Z.label=5;case 5:return[4,q(null,W)];case 6:return Z.sent(),[3,8];case 7:if(X=Z.sent(),!this.flags||0===Object.keys(this.flags).length)throw X;return z=X instanceof Error?X:new Error("".concat(X)),null===(o=this.onError)||void 0===o||o.call(this,z),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return Z.sent(),[3,12];case 11:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:l({},A),traitsChanged:l({},null===(r=c.identity)||void 0===r?void 0:r.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else if(this.flags&&(Y=null,0===Object.keys(this.flags).length&&(Y=H),this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(s=c.identity)||void 0===s?void 0:s.traits)},this._loadedState(Y,t.FlagSource.DEFAULT_FLAGS)),Y))throw new Error(Y);Z.label=12;case 12:return[3,14];case 13:throw $=Z.sent(),this.log("Error during initialisation ",$),z=$ instanceof Error?$:new Error("".concat($)),null===(u=this.onError)||void 0===u||u.call(this,z),$;case 14:return[2]}}))}))},e.prototype.getAllFlags=function(){return this.flags},e.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},e.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},e.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||E,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this))},e.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},e.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},e.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},e.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},e.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,o(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},e.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),m.setItem(this.getStorageKey(),t)}},e.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);m.setItem(C,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},e.prototype.initPipelineAnalytics=function(t){var e,n,i,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=h(t.analyticsServerUrl),this.evaluationAnalyticsMaxBuffer=null!==(e=t.maxBuffer)&&void 0!==e?e:1e3,this.pipelineFlushInterval=null!==(n=t.flushInterval)&&void 0!==n?n:1e4,this.pipelineEvents=[],this.pipelineFlushInterval>0&&(this.pipelineAnalyticsInterval=setInterval(this.flushPipelineAnalytics,this.pipelineFlushInterval),null===(a=null===(i=this.pipelineAnalyticsInterval)||void 0===i?void 0:i.unref)||void 0===a||a.call(i))},e.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},e.prototype.currentTraitsSnapshot=function(){var t;return(null===(t=this.evaluationContext.identity)||void 0===t?void 0:t.traits)?n({},this.evaluationContext.identity.traits):null},e.prototype.getPageUrl=function(){return"undefined"!=typeof window&&window.location?window.location.href:null},e.prototype.getEventMetadata=function(t){var e=this.getPageUrl();return n(n(n({},t||{}),e?{page_url:e}:{}),{sdk_version:p})},e.prototype.buildAnalyticEvent=function(t,e,n){var i,a,o,r,l;return{event_id:e,event_type:t,evaluated_at:null!==(i=null==n?void 0:n.timestamp)&&void 0!==i?i:Date.now(),identity_identifier:null!==(o=null===(a=this.evaluationContext.identity)||void 0===a?void 0:a.identifier)&&void 0!==o?o:null,enabled:null!==(r=null==n?void 0:n.enabled)&&void 0!==r?r:null,value:null!==(l=null==n?void 0:n.value)&&void 0!==l?l:null,traits:this.currentTraitsSnapshot(),metadata:this.getEventMetadata(null==n?void 0:n.extraMetadata)}},e.prototype.recordPipelineEvent=function(e){var n,i,a,o,r=e.toLowerCase().replace(/ /g,"_"),l=this.flags&&this.flags[r],s="".concat(null!==(i=null===(n=this.evaluationContext.identity)||void 0===n?void 0:n.identifier)&&void 0!==i?i:"none","|").concat(null!==(a=null==l?void 0:l.enabled)&&void 0!==a&&a,"|").concat(null!==(o=null==l?void 0:l.value)&&void 0!==o?o:"null");if(this.pipelineRecordedKeys.get(r)!==s){this.pipelineRecordedKeys.set(r,s);var u=this.buildAnalyticEvent(t.PipelineEventType.FLAG_EVALUATION,r,{enabled:l?l.enabled:null,value:l?l.value:null,extraMetadata:l?{id:l.id}:void 0});this.pipelineEvents.push(u),(0===this.pipelineFlushInterval||this.pipelineEvents.length>=this.evaluationAnalyticsMaxBuffer)&&this.flushPipelineAnalytics()}},e.prototype.setLoadingState=function(t){var e;r(t,this.loadingState)||(this.loadingState=n({},t),this.log("Loading state changed",t),null===(e=this._triggerLoadingState)||void 0===e||e.call(this))},e.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";y?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new y(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},e}();function O(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new F({fetch:e,AsyncStorage:n,eventSource:i})}var A,w=(A=function(t,e){return A=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},A(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}A(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),I=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},L=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},j=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},P=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return w(e,t),e}(Error),T=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new P;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=I(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=I(j([],L(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=j(j([],L(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var k=function(t,e){return e=e||{},new Promise((function(n,i){var a=new XMLHttpRequest,o=[],r=[],l={},s=function(){return{ok:2==(a.status/100|0),statusText:a.statusText,status:a.status,url:a.responseURL,text:function(){return Promise.resolve(a.responseText)},json:function(){return Promise.resolve(a.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([a.response]))},clone:s,headers:{keys:function(){return o},entries:function(){return r},get:function(t){return l[t.toLowerCase()]},has:function(t){return t.toLowerCase()in l}}}};for(var u in a.open(e.method||"get",t,!0),a.onload=function(){a.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(t,e,n){o.push(e=e.toLowerCase()),r.push([e,n]),l[e]=l[e]?l[e]+","+n:n})),n(s())},a.onerror=i,a.withCredentials="include"==e.credentials,e.headers)a.setRequestHeader(u,e.headers[u]);a.send(e.body||null)}))},N=O({AsyncStorage:e,fetch:k,eventSource:T});"undefined"!=typeof window&&(window.flagsmith=N);t.createFlagsmithInstance=function(){return O({AsyncStorage:e,fetch:k,eventSource:T})},t.default=N,Object.defineProperty(t,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=index.js.map
package/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var t={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},e=function(){return e=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},e.apply(this,arguments)};function n(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{s(i.next(t))}catch(t){o(t)}}function l(t){try{s(i.throw(t))}catch(t){o(t)}}function s(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,l)}s((i=i.apply(t,e||[])).next())}))}function i(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function a(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var o=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function r(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!o(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function l(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function s(t){return!!t&&"object"==typeof t&&void 0!==t.value}function u(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))}function c(t){return e(e({},t),{identity:t.identity?e(e({},t.identity),{traits:u(t.identity.traits||{})}):void 0})}function v(t){return t.endsWith("/")?t:t+"/"}var h,d,g;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(h||(h={})),function(t){t.FLAG_EVALUATION="flag_evaluation",t.CUSTOM_EVENT="custom_event"}(d||(d={}));var f,p=null,y="FLAGSMITH_EVENT",m="https://edge.api.flagsmith.com/api/v1/",S=function(){function t(t){var a=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var t=a,n=t.api,i=t.evaluationContext;a.log("Get Flags"),a.isLoading=!0,a.loadingState.isFetching||a.setLoadingState(e(e({},a.loadingState),{isFetching:!0}));var o="".concat(a.getContext().identity),s=function(t){var n,i,s,u;if(t&&o==="".concat(a.getContext().identity)){var c=t.flags,v=t.traits,d=t.identifier;a.isLoading=!1;var g={},f={};v=v||[],(c=c||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),v.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),a.oldFlags=e({},a.flags);var p=r(a.oldFlags,g),y=r(null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.traits,f);if((d||Object.keys(f).length)&&(a.evaluationContext.identity=e(e({},a.evaluationContext.identity),{traits:f}),d&&(a.evaluationContext.identity.identifier=d,a.identity=d)),a.flags=g,a.updateStorage(),a._onChange(a.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},a._loadedState(null,h.SERVER)),a.datadogRum)try{if(a.datadogRum.trackTraits){var m={};Object.keys((null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.traits)||{}).map((function(t){m["flagsmith_trait_"+t]=a.getTrait(t)}));var S=e(e(e({},a.datadogRum.client.getUser()),{id:a.datadogRum.client.getUser().id||(null===(s=a.evaluationContext.identity)||void 0===s?void 0:s.identifier)}),m);a.log("Setting Datadog user",S),a.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(a.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(a.flags).map((function(t){l(C,"flagsmith_value_"+t,a.getValue(t,{skipAnalytics:!0})),l(C,"flagsmith_enabled_"+t,a.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(u=a.evaluationContext.identity)||void 0===u?void 0:u.traits)||{}).map((function(t){l(C,"flagsmith_trait_"+t,a.getTrait(t))})),a.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),a.log("Sending date traits to dynatrace",C.date),a.log("Sending shortString traits to dynatrace",C.shortString),a.log("Sending javaDouble to dynatrace",C.javaDouble),a.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return i.identity?Promise.all([i.identity.traits&&Object.keys(i.identity.traits).length||!i.identity.identifier?a.getJSON(n+"identities/","POST",JSON.stringify({identifier:i.identity.identifier,transient:i.identity.transient,traits:Object.entries(i.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(a.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):a.getJSON(n+"identities/?identifier="+encodeURIComponent(i.identity.identifier)+(i.identity.transient?"&transient=true":""))]).then((function(t){return a.evaluationContext.identity=e(e({},a.evaluationContext.identity),{traits:{}}),s(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):a.getJSON(n+"flags/").then((function(t){return s({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=a.api;if(a.evaluationEvent&&a.evaluationContext.environment&&a.evaluationEvent[a.evaluationContext.environment.apiKey])return a.evaluationEvent&&0!==Object.getOwnPropertyNames(a.evaluationEvent).length&&0!==Object.getOwnPropertyNames(a.evaluationEvent[a.evaluationContext.environment.apiKey]).length?a.getJSON(t+"analytics/flags/","POST",JSON.stringify(a.evaluationEvent[a.evaluationContext.environment.apiKey])).then((function(t){if(a.evaluationContext.environment){var n=a.getState();a.evaluationEvent||(a.evaluationEvent={}),a.evaluationEvent[a.evaluationContext.environment.apiKey]={},a.setState(e(e({},n),{evaluationEvent:a.evaluationEvent})),a.updateEventStorage()}})).catch((function(t){a.log("Exception fetching evaluationEvent",t)})):void 0},this.flushPipelineAnalytics=function(){return n(a,void 0,void 0,(function(){var t,n,a,o,r,l,s;return i(this,(function(i){switch(i.label){case 0:if(t=this.evaluationAnalyticsUrl&&this.evaluationContext.environment,n=this.pipelineEvents.length>0&&(!this.isPipelineFlushing||0===this.pipelineFlushInterval),!t||!n)return[2];a=this.evaluationContext.environment.apiKey,this.isPipelineFlushing=!0,o=this.pipelineEvents.slice(0,this.evaluationAnalyticsMaxBuffer),this.pipelineEvents=this.pipelineEvents.slice(this.evaluationAnalyticsMaxBuffer),this.pipelineRecordedKeys.clear(),r={events:o,environment_key:a},i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,g(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(r),headers:e({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":a},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat("11.0.0-internal.6")})})];case 2:if(!(l=i.sent()).status||l.status<200||l.status>=300)throw new Error("Pipeline analytics: unexpected status ".concat(l.status));return this.log("Pipeline analytics: flush successful"),[3,5];case 3:return s=i.sent(),this.pipelineEvents=o.concat(this.pipelineEvents),this.log("Pipeline analytics: flush failed, events re-queued",s),[3,5];case 4:return this.isPipelineFlushing=!1,[7];case 5:return[2]}}))}))},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:h.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.evaluationAnalyticsUrl=null,this.evaluationAnalyticsMaxBuffer=1e3,this.pipelineEvents=[],this.pipelineAnalyticsInterval=null,this.isPipelineFlushing=!1,this.pipelineRecordedKeys=new Map,this.getValue=function(t,e,n){var i=a.flags&&a.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(i&&(o=i.value),(null==e?void 0:e.skipAnalytics)||n||a.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(a.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,n;return(null===(e=a.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=a.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=a.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var n,i,o=c(t);return a.evaluationContext=e(e({},o),{environment:o.environment||a.evaluationContext.environment}),a.identity=null===(i=null===(n=a.getContext())||void 0===n?void 0:n.identity)||void 0===i?void 0:i.identifier,a.initialised?a.getFlags():Promise.resolve()},this.getContext=function(){return a.evaluationContext},this.updateContext=function(t){return a.setContext(e(e({},a.getContext()),t))},this.setTrait=function(t,n){var i;if(a.api)return a.setContext(e(e({},a.evaluationContext),{identity:e(e({},a.evaluationContext.identity),{traits:e(e({},null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.traits),u(Object.fromEntries([[t,n]])))})}))},this.setTraits=function(t){var n;if(a.api)return a.setContext(e(e({},a.evaluationContext),{identity:e(e({},a.evaluationContext.identity),{traits:e(e({},null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,i,o="object"==typeof e,r=a.flags&&a.flags[t.toLowerCase().replace(/ /g,"_")],l=!1;if(!r&&o&&void 0!==e.fallback?l=null==e?void 0:e.fallback:r&&r.enabled&&(l=!0),(o&&!e.skipAnalytics||!e)&&a.evaluateFlag(t,"ENABLED"),a.sentryClient)try{null===(i=null===(n=a.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===i||i.call(n,t,l)}catch(t){console.error(t)}return l},this.getStorageKey=function(){var t,e;return(null===(t=a.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=a.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var i,o,r,l=a.headers,s={method:e||"GET",body:n,cache:"no-cache",headers:{}};a.evaluationContext.environment&&(s.headers["X-Environment-Key"]=a.evaluationContext.environment.apiKey),e&&"GET"!==e&&(s.headers["Content-Type"]="application/json; charset=utf-8"),(null===(i=a.applicationMetadata)||void 0===i?void 0:i.name)&&(s.headers["Flagsmith-Application-Name"]=a.applicationMetadata.name),(null===(o=a.applicationMetadata)||void 0===o?void 0:o.version)&&(s.headers["Flagsmith-Application-Version"]=a.applicationMetadata.version),s.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("11.0.0-internal.6"),l&&Object.assign(s.headers,l),g||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=a.evaluationContext.identity)||void 0===r?void 0:r.identifier);return g(t,s).then((function(n){var i,o,r="".concat(null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.identifier);if(u===r){var l=null===(o=n.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(l)try{var s=parseFloat(l);if(isNaN(s))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");a.timestamp=s}catch(t){a.log(t,"Failed to parse x-flagsmith-document-updated-at",l)}return a.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}a.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(a.datadogRum&&(a.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?a.datadogRum.client.addFeatureFlagEvaluation("flagsmith_value_"+t,a.getValue(t,{},!0)):a.datadogRum.client.addFeatureFlagEvaluation("flagsmith_enabled_"+t,a.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),a.enableAnalytics){if(!a.evaluationEvent||!a.evaluationContext.environment)return;a.evaluationEvent[a.evaluationContext.environment.apiKey]||(a.evaluationEvent[a.evaluationContext.environment.apiKey]={}),void 0===a.evaluationEvent[a.evaluationContext.environment.apiKey][t]&&(a.evaluationEvent[a.evaluationContext.environment.apiKey][t]=0),a.evaluationEvent[a.evaluationContext.environment.apiKey][t]+=1}a.evaluationAnalyticsUrl&&a.recordPipelineEvent(t),a.updateEventStorage()},this.pipelineFlushInterval=1e4,this.trackEvent=function(t,e){if(a.evaluationAnalyticsUrl&&t){var n=a.buildAnalyticEvent(d.CUSTOM_EVENT,t,{extraMetadata:e});a.pipelineEvents.push(n),(0===a.pipelineFlushInterval||a.pipelineEvents.length>=a.evaluationAnalyticsMaxBuffer)&&a.flushPipelineAnalytics()}},this._onChange=function(t,e,n){var i,o;a.setLoadingState(n),null===(i=a.onChange)||void 0===i||i.call(a,t,e,a.loadingState),null===(o=a._trigger)||void 0===o||o.call(a)},g=t.fetch?t.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!t.browserlessStorage,this.applicationMetadata=t.applicationMetadata,this.log("Constructing flagsmith instance "+t),t.eventSource&&(f=t.eventSource),t.AsyncStorage&&(p=t.AsyncStorage)}return t.prototype.init=function(t){var a,o,l,s;return n(this,void 0,void 0,(function(){var u,d,f,S,C,_,E,b,x,O,F,A,w,I,L,j,P,T,k,N,R,U,K,M,D,G,J,V,B,H,q,W,X,Y,$,z,Q=this;return i(this,(function(Z){switch(Z.label){case 0:u=c(t.evaluationContext||this.evaluationContext),Z.label=1;case 1:if(Z.trys.push([1,13,,14]),d=t.AsyncStorage,f=t._trigger,S=t._triggerLoadingState,C=t.angularHttpClient,_=t.api,E=void 0===_?m:_,b=t.applicationMetadata,x=t.cacheFlags,O=t.cacheOptions,F=t.datadogRum,A=t.defaultFlags,w=t.enableAnalytics,I=t.enableDynatrace,L=t.enableLogs,j=t.environmentID,P=t.evaluationAnalyticsConfig,T=t.eventSourceUrl,k=void 0===T?"https://realtime.flagsmith.com/":T,N=t.fetch,R=t.headers,U=t.identity,K=t.onChange,M=t.onError,D=t.preventFetch,G=t.realtime,J=t.sentryClient,V=t.state,B=t.traits,u.environment=j?{apiKey:j}:u.environment,!u.environment||!u.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(u.identity=U||B?{identifier:U,traits:B?Object.fromEntries(Object.entries(B).map((function(t){return[t[0],{value:t[1]}]}))):{}}:u.identity,this.evaluationContext=u,this.api=v(E),this.headers=R,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=K,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=f||this._trigger,this._triggerLoadingState=S||this._triggerLoadingState,this.onError=function(t){Q.setLoadingState(e(e({},Q.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==M||M(t)},this.enableLogs=L||!1,this.cacheOptions=O?{skipAPI:!!O.skipAPI,ttl:O.ttl||0,storageKey:O.storageKey,loadStale:!!O.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),N&&(g=N),this.enableAnalytics=w||!1,this.flags=Object.assign({},A)||{},this.datadogRum=F||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==p&&!!x,this.applicationMetadata=b,y="FLAGSMITH_EVENT_"+u.environment.apiKey,d&&(p=d),G&&"undefined"!=typeof window&&this.setupRealtime(k,u.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:h.DEFAULT_FLAGS})),this.setState(V),this.log("Initialising with properties",t,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),C&&(g=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},l=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(l(t,!t.status||t.status>=200&&t.status<300))},s=function(t){return n(l(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,s);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,s);default:return s({status:405,message:"Unsupported method: ".concat(a)})}}))}}(C)),p&&this.canUseStorage&&p.getItem(y).then((function(t){try{Q.evaluationEvent=JSON.parse(t)||{}}catch(t){Q.evaluationEvent={}}Q.analyticsInterval=setInterval(Q.analyticsFlags,Q.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),p&&this.canUseStorage&&p.getItem(y,(function(t,n){if(n&&Q.evaluationContext.environment){var i=JSON.parse(n);if(i[Q.evaluationContext.environment.apiKey]){var a=Q.getState();Q.log("Retrieved events from cache",n),Q.setState(e(e({},a),{evaluationEvent:i[Q.evaluationContext.environment.apiKey]}))}}}))),P?this.initPipelineAnalytics(P):this.stopPipelineAnalytics(),!x)return[3,9];if(!p||!this.canUseStorage)return[3,8];q=function(t,a){return n(Q,void 0,void 0,(function(){var t,n,o,l,s,u,v,d,g,f,p,y,m,S,C,_,E,b,x,O=this;return i(this,(function(i){switch(i.label){case 0:if(!a)return[3,7];t=null,n=null,i.label=1;case 1:return i.trys.push([1,5,,6]),o=JSON.parse(a),l=!1,s=!1,o&&o.api===this.api&&(null===(f=null===(g=o.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(u=!0,this.evaluationContext.identity&&(null===(m=null===(y=o.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=o.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),u=!1),this.cacheOptions.ttl&&(!o.ts||(new Date).valueOf()-o.ts>this.cacheOptions.ttl)&&(o.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),u=!1):o.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),s=!0,u=!0)),u&&(l=!0,t=r(this.flags,o.flags),this.setState(e(e({},o),{evaluationContext:c(e(e({},o.evaluationContext),{identity:(null===(_=o.evaluationContext)||void 0===_?void 0:_.identity)?e(e({},null===(E=o.evaluationContext)||void 0===E?void 0:E.identity),{traits:e({},B||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),l?(v=!D&&(!this.cacheOptions.skipAPI||s),this._onChange(null,{isFromServer:!1,flagsChanged:t,traitsChanged:n},this._loadedState(null,h.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&l&&!s&&this.log("Skipping API, using cache"),v&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:i.sent(),i.label=4;case 4:return[3,6];case 5:throw d=i.sent(),this.log("Exception fetching cached logs",d),d;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(b=this.evaluationContext.identity)||void 0===b?void 0:b.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(H);this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,h.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},Z.label=2;case 2:return Z.trys.push([2,7,,8]),p.getItemSync?(W=p.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,p.getItem(this.getStorageKey())];case 4:W=Z.sent(),Z.label=5;case 5:return[4,q(null,W)];case 6:return Z.sent(),[3,8];case 7:if(X=Z.sent(),!this.flags||0===Object.keys(this.flags).length)throw X;return z=X instanceof Error?X:new Error("".concat(X)),null===(a=this.onError)||void 0===a||a.call(this,z),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return Z.sent(),[3,12];case 11:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:r({},A),traitsChanged:r({},null===(o=u.identity)||void 0===o?void 0:o.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else if(this.flags&&(Y=null,0===Object.keys(this.flags).length&&(Y=H),this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(l=u.identity)||void 0===l?void 0:l.traits)},this._loadedState(Y,h.DEFAULT_FLAGS)),Y))throw new Error(Y);Z.label=12;case 12:return[3,14];case 13:throw $=Z.sent(),this.log("Error during initialisation ",$),z=$ instanceof Error?$:new Error("".concat($)),null===(s=this.onError)||void 0===s||s.call(this,z),$;case 14:return[2]}}))}))},t.prototype.getAllFlags=function(){return this.flags},t.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},t.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},t.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||m,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this))},t.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},t.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},t.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},t.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,a(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},t.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),p.setItem(this.getStorageKey(),t)}},t.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);p.setItem(y,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},t.prototype.initPipelineAnalytics=function(t){var e,n,i,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=v(t.analyticsServerUrl),this.evaluationAnalyticsMaxBuffer=null!==(e=t.maxBuffer)&&void 0!==e?e:1e3,this.pipelineFlushInterval=null!==(n=t.flushInterval)&&void 0!==n?n:1e4,this.pipelineEvents=[],this.pipelineFlushInterval>0&&(this.pipelineAnalyticsInterval=setInterval(this.flushPipelineAnalytics,this.pipelineFlushInterval),null===(a=null===(i=this.pipelineAnalyticsInterval)||void 0===i?void 0:i.unref)||void 0===a||a.call(i))},t.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},t.prototype.currentTraitsSnapshot=function(){var t;return(null===(t=this.evaluationContext.identity)||void 0===t?void 0:t.traits)?e({},this.evaluationContext.identity.traits):null},t.prototype.getPageUrl=function(){return"undefined"!=typeof window&&window.location?window.location.href:null},t.prototype.getEventMetadata=function(t){var n=this.getPageUrl();return e(e(e({},t||{}),n?{page_url:n}:{}),{sdk_version:"11.0.0-internal.6"})},t.prototype.buildAnalyticEvent=function(t,e,n){var i,a,o,r,l;return{event_id:e,event_type:t,evaluated_at:null!==(i=null==n?void 0:n.timestamp)&&void 0!==i?i:Date.now(),identity_identifier:null!==(o=null===(a=this.evaluationContext.identity)||void 0===a?void 0:a.identifier)&&void 0!==o?o:null,enabled:null!==(r=null==n?void 0:n.enabled)&&void 0!==r?r:null,value:null!==(l=null==n?void 0:n.value)&&void 0!==l?l:null,traits:this.currentTraitsSnapshot(),metadata:this.getEventMetadata(null==n?void 0:n.extraMetadata)}},t.prototype.recordPipelineEvent=function(t){var e,n,i,a,o=t.toLowerCase().replace(/ /g,"_"),r=this.flags&&this.flags[o],l="".concat(null!==(n=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==n?n:"none","|").concat(null!==(i=null==r?void 0:r.enabled)&&void 0!==i&&i,"|").concat(null!==(a=null==r?void 0:r.value)&&void 0!==a?a:"null");if(this.pipelineRecordedKeys.get(o)!==l){this.pipelineRecordedKeys.set(o,l);var s=this.buildAnalyticEvent(d.FLAG_EVALUATION,o,{enabled:r?r.enabled:null,value:r?r.value:null,extraMetadata:r?{id:r.id}:void 0});this.pipelineEvents.push(s),(0===this.pipelineFlushInterval||this.pipelineEvents.length>=this.evaluationAnalyticsMaxBuffer)&&this.flushPipelineAnalytics()}},t.prototype.setLoadingState=function(t){var n;o(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(n=this._triggerLoadingState)||void 0===n||n.call(this))},t.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";f?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new f(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},t}();function C(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new S({fetch:e,AsyncStorage:n,eventSource:i})}var _,E=(_=function(t,e){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},_(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}_(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),b=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},x=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},O=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},F=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return E(e,t),e}(Error),A=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new F;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=b(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=b(O([],x(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=O(O([],x(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var w=function(t,e){return e=e||{},new Promise((function(n,i){var a=new XMLHttpRequest,o=[],r=[],l={},s=function(){return{ok:2==(a.status/100|0),statusText:a.statusText,status:a.status,url:a.responseURL,text:function(){return Promise.resolve(a.responseText)},json:function(){return Promise.resolve(a.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([a.response]))},clone:s,headers:{keys:function(){return o},entries:function(){return r},get:function(t){return l[t.toLowerCase()]},has:function(t){return t.toLowerCase()in l}}}};for(var u in a.open(e.method||"get",t,!0),a.onload=function(){a.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(t,e,n){o.push(e=e.toLowerCase()),r.push([e,n]),l[e]=l[e]?l[e]+","+n:n})),n(s())},a.onerror=i,a.withCredentials="include"==e.credentials,e.headers)a.setRequestHeader(u,e.headers[u]);a.send(e.body||null)}))},I=C({AsyncStorage:t,fetch:w,eventSource:A});"undefined"!=typeof window&&(window.flagsmith=I);var L=function(){return C({AsyncStorage:t,fetch:w,eventSource:A})};export{h as FlagSource,d as PipelineEventType,L as createFlagsmithInstance,I as default};
1
+ var t={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},e=function(){return e=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},e.apply(this,arguments)};function n(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{s(i.next(t))}catch(t){o(t)}}function l(t){try{s(i.throw(t))}catch(t){o(t)}}function s(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,l)}s((i=i.apply(t,e||[])).next())}))}function i(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function a(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var o=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function r(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!o(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function l(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function s(t){return!!t&&"object"==typeof t&&void 0!==t.value}function u(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))}function c(t){return e(e({},t),{identity:t.identity?e(e({},t.identity),{traits:u(t.identity.traits||{})}):void 0})}function v(t){return t.endsWith("/")?t:t+"/"}var h,d,g;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(h||(h={})),function(t){t.FLAG_EVALUATION="flag_evaluation",t.CUSTOM_EVENT="custom_event"}(d||(d={}));var f,p=null,y="FLAGSMITH_EVENT",m="https://edge.api.flagsmith.com/api/v1/",S=function(){function t(t){var a=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var t=a,n=t.api,i=t.evaluationContext;a.log("Get Flags"),a.isLoading=!0,a.loadingState.isFetching||a.setLoadingState(e(e({},a.loadingState),{isFetching:!0}));var o="".concat(a.getContext().identity),s=function(t){var n,i,s,u;if(t&&o==="".concat(a.getContext().identity)){var c=t.flags,v=t.traits,d=t.identifier;a.isLoading=!1;var g={},f={};v=v||[],(c=c||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),v.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),a.oldFlags=e({},a.flags);var p=r(a.oldFlags,g),y=r(null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.traits,f);if((d||Object.keys(f).length)&&(a.evaluationContext.identity=e(e({},a.evaluationContext.identity),{traits:f}),d&&(a.evaluationContext.identity.identifier=d,a.identity=d)),a.flags=g,a.updateStorage(),a._onChange(a.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},a._loadedState(null,h.SERVER)),a.datadogRum)try{if(a.datadogRum.trackTraits){var m={};Object.keys((null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.traits)||{}).map((function(t){m["flagsmith_trait_"+t]=a.getTrait(t)}));var S=e(e(e({},a.datadogRum.client.getUser()),{id:a.datadogRum.client.getUser().id||(null===(s=a.evaluationContext.identity)||void 0===s?void 0:s.identifier)}),m);a.log("Setting Datadog user",S),a.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(a.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(a.flags).map((function(t){l(C,"flagsmith_value_"+t,a.getValue(t,{skipAnalytics:!0})),l(C,"flagsmith_enabled_"+t,a.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(u=a.evaluationContext.identity)||void 0===u?void 0:u.traits)||{}).map((function(t){l(C,"flagsmith_trait_"+t,a.getTrait(t))})),a.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),a.log("Sending date traits to dynatrace",C.date),a.log("Sending shortString traits to dynatrace",C.shortString),a.log("Sending javaDouble to dynatrace",C.javaDouble),a.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return i.identity?Promise.all([i.identity.traits&&Object.keys(i.identity.traits).length||!i.identity.identifier?a.getJSON(n+"identities/","POST",JSON.stringify({identifier:i.identity.identifier,transient:i.identity.transient,traits:Object.entries(i.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(a.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):a.getJSON(n+"identities/?identifier="+encodeURIComponent(i.identity.identifier)+(i.identity.transient?"&transient=true":""))]).then((function(t){return a.evaluationContext.identity=e(e({},a.evaluationContext.identity),{traits:{}}),s(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):a.getJSON(n+"flags/").then((function(t){return s({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=a.api;if(a.evaluationEvent&&a.evaluationContext.environment&&a.evaluationEvent[a.evaluationContext.environment.apiKey])return a.evaluationEvent&&0!==Object.getOwnPropertyNames(a.evaluationEvent).length&&0!==Object.getOwnPropertyNames(a.evaluationEvent[a.evaluationContext.environment.apiKey]).length?a.getJSON(t+"analytics/flags/","POST",JSON.stringify(a.evaluationEvent[a.evaluationContext.environment.apiKey])).then((function(t){if(a.evaluationContext.environment){var n=a.getState();a.evaluationEvent||(a.evaluationEvent={}),a.evaluationEvent[a.evaluationContext.environment.apiKey]={},a.setState(e(e({},n),{evaluationEvent:a.evaluationEvent})),a.updateEventStorage()}})).catch((function(t){a.log("Exception fetching evaluationEvent",t)})):void 0},this.flushPipelineAnalytics=function(){return n(a,void 0,void 0,(function(){var t,n,a,o,r,l,s;return i(this,(function(i){switch(i.label){case 0:if(t=this.evaluationAnalyticsUrl&&this.evaluationContext.environment,n=this.pipelineEvents.length>0&&(!this.isPipelineFlushing||0===this.pipelineFlushInterval),!t||!n)return[2];a=this.evaluationContext.environment.apiKey,this.isPipelineFlushing=!0,o=this.pipelineEvents.slice(0,this.evaluationAnalyticsMaxBuffer),this.pipelineEvents=this.pipelineEvents.slice(this.evaluationAnalyticsMaxBuffer),this.pipelineRecordedKeys.clear(),r={events:o,environment_key:a},i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,g(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(r),headers:e({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":a},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat("11.0.0-internal.7")})})];case 2:if(!(l=i.sent()).status||l.status<200||l.status>=300)throw new Error("Pipeline analytics: unexpected status ".concat(l.status));return this.log("Pipeline analytics: flush successful"),[3,5];case 3:return s=i.sent(),this.pipelineEvents=o.concat(this.pipelineEvents),this.log("Pipeline analytics: flush failed, events re-queued",s),[3,5];case 4:return this.isPipelineFlushing=!1,[7];case 5:return[2]}}))}))},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:h.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.evaluationAnalyticsUrl=null,this.evaluationAnalyticsMaxBuffer=1e3,this.pipelineEvents=[],this.pipelineAnalyticsInterval=null,this.isPipelineFlushing=!1,this.pipelineRecordedKeys=new Map,this.getValue=function(t,e,n){var i=a.flags&&a.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(i&&(o=i.value),(null==e?void 0:e.skipAnalytics)||n||a.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(a.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,n;return(null===(e=a.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=a.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=a.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var n,i,o=c(t);return a.evaluationContext=e(e({},o),{environment:o.environment||a.evaluationContext.environment}),a.identity=null===(i=null===(n=a.getContext())||void 0===n?void 0:n.identity)||void 0===i?void 0:i.identifier,a.initialised?a.getFlags():Promise.resolve()},this.getContext=function(){return a.evaluationContext},this.updateContext=function(t){return a.setContext(e(e({},a.getContext()),t))},this.setTrait=function(t,n){var i;if(a.api)return a.setContext(e(e({},a.evaluationContext),{identity:e(e({},a.evaluationContext.identity),{traits:e(e({},null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.traits),u(Object.fromEntries([[t,n]])))})}))},this.setTraits=function(t){var n;if(a.api)return a.setContext(e(e({},a.evaluationContext),{identity:e(e({},a.evaluationContext.identity),{traits:e(e({},null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,i,o="object"==typeof e,r=a.flags&&a.flags[t.toLowerCase().replace(/ /g,"_")],l=!1;if(!r&&o&&void 0!==e.fallback?l=null==e?void 0:e.fallback:r&&r.enabled&&(l=!0),(o&&!e.skipAnalytics||!e)&&a.evaluateFlag(t,"ENABLED"),a.sentryClient)try{null===(i=null===(n=a.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===i||i.call(n,t,l)}catch(t){console.error(t)}return l},this.getStorageKey=function(){var t,e;return(null===(t=a.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=a.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var i,o,r,l=a.headers,s={method:e||"GET",body:n,cache:"no-cache",headers:{}};a.evaluationContext.environment&&(s.headers["X-Environment-Key"]=a.evaluationContext.environment.apiKey),e&&"GET"!==e&&(s.headers["Content-Type"]="application/json; charset=utf-8"),(null===(i=a.applicationMetadata)||void 0===i?void 0:i.name)&&(s.headers["Flagsmith-Application-Name"]=a.applicationMetadata.name),(null===(o=a.applicationMetadata)||void 0===o?void 0:o.version)&&(s.headers["Flagsmith-Application-Version"]=a.applicationMetadata.version),s.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("11.0.0-internal.7"),l&&Object.assign(s.headers,l),g||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=a.evaluationContext.identity)||void 0===r?void 0:r.identifier);return g(t,s).then((function(n){var i,o,r="".concat(null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.identifier);if(u===r){var l=null===(o=n.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(l)try{var s=parseFloat(l);if(isNaN(s))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");a.timestamp=s}catch(t){a.log(t,"Failed to parse x-flagsmith-document-updated-at",l)}return a.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}a.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(a.datadogRum&&(a.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?a.datadogRum.client.addFeatureFlagEvaluation("flagsmith_value_"+t,a.getValue(t,{},!0)):a.datadogRum.client.addFeatureFlagEvaluation("flagsmith_enabled_"+t,a.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),a.enableAnalytics){if(!a.evaluationEvent||!a.evaluationContext.environment)return;a.evaluationEvent[a.evaluationContext.environment.apiKey]||(a.evaluationEvent[a.evaluationContext.environment.apiKey]={}),void 0===a.evaluationEvent[a.evaluationContext.environment.apiKey][t]&&(a.evaluationEvent[a.evaluationContext.environment.apiKey][t]=0),a.evaluationEvent[a.evaluationContext.environment.apiKey][t]+=1}a.evaluationAnalyticsUrl&&a.recordPipelineEvent(t),a.updateEventStorage()},this.pipelineFlushInterval=1e4,this.trackEvent=function(t,e){if(a.evaluationAnalyticsUrl&&t){var n=a.buildAnalyticEvent(d.CUSTOM_EVENT,t,{extraMetadata:e});a.pipelineEvents.push(n),(0===a.pipelineFlushInterval||a.pipelineEvents.length>=a.evaluationAnalyticsMaxBuffer)&&a.flushPipelineAnalytics()}},this._onChange=function(t,e,n){var i,o;a.setLoadingState(n),null===(i=a.onChange)||void 0===i||i.call(a,t,e,a.loadingState),null===(o=a._trigger)||void 0===o||o.call(a)},g=t.fetch?t.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!t.browserlessStorage,this.applicationMetadata=t.applicationMetadata,this.log("Constructing flagsmith instance "+t),t.eventSource&&(f=t.eventSource),t.AsyncStorage&&(p=t.AsyncStorage)}return t.prototype.init=function(t){var a,o,l,s;return n(this,void 0,void 0,(function(){var u,d,f,S,C,_,E,b,x,O,F,A,w,I,L,j,P,T,k,N,R,U,K,M,D,G,J,V,B,H,q,W,X,Y,$,z,Q=this;return i(this,(function(Z){switch(Z.label){case 0:u=c(t.evaluationContext||this.evaluationContext),Z.label=1;case 1:if(Z.trys.push([1,13,,14]),d=t.AsyncStorage,f=t._trigger,S=t._triggerLoadingState,C=t.angularHttpClient,_=t.api,E=void 0===_?m:_,b=t.applicationMetadata,x=t.cacheFlags,O=t.cacheOptions,F=t.datadogRum,A=t.defaultFlags,w=t.enableAnalytics,I=t.enableDynatrace,L=t.enableLogs,j=t.environmentID,P=t.evaluationAnalyticsConfig,T=t.eventSourceUrl,k=void 0===T?"https://realtime.flagsmith.com/":T,N=t.fetch,R=t.headers,U=t.identity,K=t.onChange,M=t.onError,D=t.preventFetch,G=t.realtime,J=t.sentryClient,V=t.state,B=t.traits,u.environment=j?{apiKey:j}:u.environment,!u.environment||!u.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(u.identity=U||B?{identifier:U,traits:B?Object.fromEntries(Object.entries(B).map((function(t){return[t[0],{value:t[1]}]}))):{}}:u.identity,this.evaluationContext=u,this.api=v(E),this.headers=R,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=K,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=f||this._trigger,this._triggerLoadingState=S||this._triggerLoadingState,this.onError=function(t){Q.setLoadingState(e(e({},Q.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==M||M(t)},this.enableLogs=L||!1,this.cacheOptions=O?{skipAPI:!!O.skipAPI,ttl:O.ttl||0,storageKey:O.storageKey,loadStale:!!O.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),N&&(g=N),this.enableAnalytics=w||!1,this.flags=Object.assign({},A)||{},this.datadogRum=F||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==p&&!!x,this.applicationMetadata=b,y="FLAGSMITH_EVENT_"+u.environment.apiKey,d&&(p=d),G&&"undefined"!=typeof window&&this.setupRealtime(k,u.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:h.DEFAULT_FLAGS})),this.setState(V),this.log("Initialising with properties",t,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),C&&(g=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},l=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(l(t,!t.status||t.status>=200&&t.status<300))},s=function(t){return n(l(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,s);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,s);default:return s({status:405,message:"Unsupported method: ".concat(a)})}}))}}(C)),p&&this.canUseStorage&&p.getItem(y).then((function(t){try{Q.evaluationEvent=JSON.parse(t)||{}}catch(t){Q.evaluationEvent={}}Q.analyticsInterval=setInterval(Q.analyticsFlags,Q.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),p&&this.canUseStorage&&p.getItem(y,(function(t,n){if(n&&Q.evaluationContext.environment){var i=JSON.parse(n);if(i[Q.evaluationContext.environment.apiKey]){var a=Q.getState();Q.log("Retrieved events from cache",n),Q.setState(e(e({},a),{evaluationEvent:i[Q.evaluationContext.environment.apiKey]}))}}}))),P?this.initPipelineAnalytics(P):this.stopPipelineAnalytics(),!x)return[3,9];if(!p||!this.canUseStorage)return[3,8];q=function(t,a){return n(Q,void 0,void 0,(function(){var t,n,o,l,s,u,v,d,g,f,p,y,m,S,C,_,E,b,x,O=this;return i(this,(function(i){switch(i.label){case 0:if(!a)return[3,7];t=null,n=null,i.label=1;case 1:return i.trys.push([1,5,,6]),o=JSON.parse(a),l=!1,s=!1,o&&o.api===this.api&&(null===(f=null===(g=o.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(u=!0,this.evaluationContext.identity&&(null===(m=null===(y=o.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=o.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),u=!1),this.cacheOptions.ttl&&(!o.ts||(new Date).valueOf()-o.ts>this.cacheOptions.ttl)&&(o.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),u=!1):o.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),s=!0,u=!0)),u&&(l=!0,t=r(this.flags,o.flags),this.setState(e(e({},o),{evaluationContext:c(e(e({},o.evaluationContext),{identity:(null===(_=o.evaluationContext)||void 0===_?void 0:_.identity)?e(e({},null===(E=o.evaluationContext)||void 0===E?void 0:E.identity),{traits:e({},B||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),l?(v=!D&&(!this.cacheOptions.skipAPI||s),this._onChange(null,{isFromServer:!1,flagsChanged:t,traitsChanged:n},this._loadedState(null,h.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&l&&!s&&this.log("Skipping API, using cache"),v&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:i.sent(),i.label=4;case 4:return[3,6];case 5:throw d=i.sent(),this.log("Exception fetching cached logs",d),d;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(b=this.evaluationContext.identity)||void 0===b?void 0:b.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(H);this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,h.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},Z.label=2;case 2:return Z.trys.push([2,7,,8]),p.getItemSync?(W=p.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,p.getItem(this.getStorageKey())];case 4:W=Z.sent(),Z.label=5;case 5:return[4,q(null,W)];case 6:return Z.sent(),[3,8];case 7:if(X=Z.sent(),!this.flags||0===Object.keys(this.flags).length)throw X;return z=X instanceof Error?X:new Error("".concat(X)),null===(a=this.onError)||void 0===a||a.call(this,z),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return Z.sent(),[3,12];case 11:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:r({},A),traitsChanged:r({},null===(o=u.identity)||void 0===o?void 0:o.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else if(this.flags&&(Y=null,0===Object.keys(this.flags).length&&(Y=H),this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(l=u.identity)||void 0===l?void 0:l.traits)},this._loadedState(Y,h.DEFAULT_FLAGS)),Y))throw new Error(Y);Z.label=12;case 12:return[3,14];case 13:throw $=Z.sent(),this.log("Error during initialisation ",$),z=$ instanceof Error?$:new Error("".concat($)),null===(s=this.onError)||void 0===s||s.call(this,z),$;case 14:return[2]}}))}))},t.prototype.getAllFlags=function(){return this.flags},t.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},t.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},t.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||m,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this))},t.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},t.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},t.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},t.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,a(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},t.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),p.setItem(this.getStorageKey(),t)}},t.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);p.setItem(y,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},t.prototype.initPipelineAnalytics=function(t){var e,n,i,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=v(t.analyticsServerUrl),this.evaluationAnalyticsMaxBuffer=null!==(e=t.maxBuffer)&&void 0!==e?e:1e3,this.pipelineFlushInterval=null!==(n=t.flushInterval)&&void 0!==n?n:1e4,this.pipelineEvents=[],this.pipelineFlushInterval>0&&(this.pipelineAnalyticsInterval=setInterval(this.flushPipelineAnalytics,this.pipelineFlushInterval),null===(a=null===(i=this.pipelineAnalyticsInterval)||void 0===i?void 0:i.unref)||void 0===a||a.call(i))},t.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},t.prototype.currentTraitsSnapshot=function(){var t;return(null===(t=this.evaluationContext.identity)||void 0===t?void 0:t.traits)?e({},this.evaluationContext.identity.traits):null},t.prototype.getPageUrl=function(){return"undefined"!=typeof window&&window.location?window.location.href:null},t.prototype.getEventMetadata=function(t){var n=this.getPageUrl();return e(e(e({},t||{}),n?{page_url:n}:{}),{sdk_version:"11.0.0-internal.7"})},t.prototype.buildAnalyticEvent=function(t,e,n){var i,a,o,r,l;return{event_id:e,event_type:t,evaluated_at:null!==(i=null==n?void 0:n.timestamp)&&void 0!==i?i:Date.now(),identity_identifier:null!==(o=null===(a=this.evaluationContext.identity)||void 0===a?void 0:a.identifier)&&void 0!==o?o:null,enabled:null!==(r=null==n?void 0:n.enabled)&&void 0!==r?r:null,value:null!==(l=null==n?void 0:n.value)&&void 0!==l?l:null,traits:this.currentTraitsSnapshot(),metadata:this.getEventMetadata(null==n?void 0:n.extraMetadata)}},t.prototype.recordPipelineEvent=function(t){var e,n,i,a,o=t.toLowerCase().replace(/ /g,"_"),r=this.flags&&this.flags[o],l="".concat(null!==(n=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==n?n:"none","|").concat(null!==(i=null==r?void 0:r.enabled)&&void 0!==i&&i,"|").concat(null!==(a=null==r?void 0:r.value)&&void 0!==a?a:"null");if(this.pipelineRecordedKeys.get(o)!==l){this.pipelineRecordedKeys.set(o,l);var s=this.buildAnalyticEvent(d.FLAG_EVALUATION,o,{enabled:r?r.enabled:null,value:r?r.value:null,extraMetadata:r?{id:r.id}:void 0});this.pipelineEvents.push(s),(0===this.pipelineFlushInterval||this.pipelineEvents.length>=this.evaluationAnalyticsMaxBuffer)&&this.flushPipelineAnalytics()}},t.prototype.setLoadingState=function(t){var n;o(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(n=this._triggerLoadingState)||void 0===n||n.call(this))},t.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";f?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new f(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},t}();function C(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new S({fetch:e,AsyncStorage:n,eventSource:i})}var _,E=(_=function(t,e){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},_(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}_(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),b=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},x=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},O=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},F=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return E(e,t),e}(Error),A=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new F;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=b(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=b(O([],x(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=O(O([],x(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var w=function(t,e){return e=e||{},new Promise((function(n,i){var a=new XMLHttpRequest,o=[],r=[],l={},s=function(){return{ok:2==(a.status/100|0),statusText:a.statusText,status:a.status,url:a.responseURL,text:function(){return Promise.resolve(a.responseText)},json:function(){return Promise.resolve(a.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([a.response]))},clone:s,headers:{keys:function(){return o},entries:function(){return r},get:function(t){return l[t.toLowerCase()]},has:function(t){return t.toLowerCase()in l}}}};for(var u in a.open(e.method||"get",t,!0),a.onload=function(){a.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(t,e,n){o.push(e=e.toLowerCase()),r.push([e,n]),l[e]=l[e]?l[e]+","+n:n})),n(s())},a.onerror=i,a.withCredentials="include"==e.credentials,e.headers)a.setRequestHeader(u,e.headers[u]);a.send(e.body||null)}))},I=C({AsyncStorage:t,fetch:w,eventSource:A});"undefined"!=typeof window&&(window.flagsmith=I);var L=function(){return C({AsyncStorage:t,fetch:w,eventSource:A})};export{h as FlagSource,d as PipelineEventType,L as createFlagsmithInstance,I as default};
2
2
  //# sourceMappingURL=index.mjs.map
package/isomorphic.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).isomorphic={})}(this,(function(t){"use strict";var e={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},n=function(){return n=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},n.apply(this,arguments)};function i(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{s(i.next(t))}catch(t){o(t)}}function l(t){try{s(i.throw(t))}catch(t){o(t)}}function s(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,l)}s((i=i.apply(t,e||[])).next())}))}function a(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function o(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var r=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function l(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!r(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function s(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function u(t){return!!t&&"object"==typeof t&&void 0!==t.value}function c(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))}function v(t){return n(n({},t),{identity:t.identity?n(n({},t.identity),{traits:c(t.identity.traits||{})}):void 0})}function h(t){return t.endsWith("/")?t:t+"/"}var d,g,f,p="11.0.0-internal.6";t.FlagSource=void 0,(d=t.FlagSource||(t.FlagSource={})).NONE="NONE",d.DEFAULT_FLAGS="DEFAULT_FLAGS",d.CACHE="CACHE",d.SERVER="SERVER",function(t){t.FLAG_EVALUATION="flag_evaluation",t.CUSTOM_EVENT="custom_event"}(g||(g={}));var y,m=null,S="FLAGSMITH_EVENT",C=S,E="https://edge.api.flagsmith.com/api/v1/",_="flagsmith_value_",b="flagsmith_enabled_",x="flagsmith_trait_",F=function(){function e(e){var o=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var e=o,i=e.api,a=e.evaluationContext;o.log("Get Flags"),o.isLoading=!0,o.loadingState.isFetching||o.setLoadingState(n(n({},o.loadingState),{isFetching:!0}));var r="".concat(o.getContext().identity),u=function(e){var i,a,u,c;if(e&&r==="".concat(o.getContext().identity)){var v=e.flags,h=e.traits,d=e.identifier;o.isLoading=!1;var g={},f={};h=h||[],(v=v||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),h.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),o.oldFlags=n({},o.flags);var p=l(o.oldFlags,g),y=l(null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.traits,f);if((d||Object.keys(f).length)&&(o.evaluationContext.identity=n(n({},o.evaluationContext.identity),{traits:f}),d&&(o.evaluationContext.identity.identifier=d,o.identity=d)),o.flags=g,o.updateStorage(),o._onChange(o.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},o._loadedState(null,t.FlagSource.SERVER)),o.datadogRum)try{if(o.datadogRum.trackTraits){var m={};Object.keys((null===(a=o.evaluationContext.identity)||void 0===a?void 0:a.traits)||{}).map((function(t){m[x+t]=o.getTrait(t)}));var S=n(n(n({},o.datadogRum.client.getUser()),{id:o.datadogRum.client.getUser().id||(null===(u=o.evaluationContext.identity)||void 0===u?void 0:u.identifier)}),m);o.log("Setting Datadog user",S),o.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(o.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(o.flags).map((function(t){s(C,_+t,o.getValue(t,{skipAnalytics:!0})),s(C,b+t,o.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=o.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){s(C,x+t,o.getTrait(t))})),o.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),o.log("Sending date traits to dynatrace",C.date),o.log("Sending shortString traits to dynatrace",C.shortString),o.log("Sending javaDouble to dynatrace",C.javaDouble),o.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return a.identity?Promise.all([a.identity.traits&&Object.keys(a.identity.traits).length||!a.identity.identifier?o.getJSON(i+"identities/","POST",JSON.stringify({identifier:a.identity.identifier,transient:a.identity.transient,traits:Object.entries(a.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(o.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):o.getJSON(i+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(t){return o.evaluationContext.identity=n(n({},o.evaluationContext.identity),{traits:{}}),u(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):o.getJSON(i+"flags/").then((function(t){return u({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=o.api;if(o.evaluationEvent&&o.evaluationContext.environment&&o.evaluationEvent[o.evaluationContext.environment.apiKey])return o.evaluationEvent&&0!==Object.getOwnPropertyNames(o.evaluationEvent).length&&0!==Object.getOwnPropertyNames(o.evaluationEvent[o.evaluationContext.environment.apiKey]).length?o.getJSON(t+"analytics/flags/","POST",JSON.stringify(o.evaluationEvent[o.evaluationContext.environment.apiKey])).then((function(t){if(o.evaluationContext.environment){var e=o.getState();o.evaluationEvent||(o.evaluationEvent={}),o.evaluationEvent[o.evaluationContext.environment.apiKey]={},o.setState(n(n({},e),{evaluationEvent:o.evaluationEvent})),o.updateEventStorage()}})).catch((function(t){o.log("Exception fetching evaluationEvent",t)})):void 0},this.flushPipelineAnalytics=function(){return i(o,void 0,void 0,(function(){var t,e,i,o,r,l,s;return a(this,(function(a){switch(a.label){case 0:if(t=this.evaluationAnalyticsUrl&&this.evaluationContext.environment,e=this.pipelineEvents.length>0&&(!this.isPipelineFlushing||0===this.pipelineFlushInterval),!t||!e)return[2];i=this.evaluationContext.environment.apiKey,this.isPipelineFlushing=!0,o=this.pipelineEvents.slice(0,this.evaluationAnalyticsMaxBuffer),this.pipelineEvents=this.pipelineEvents.slice(this.evaluationAnalyticsMaxBuffer),this.pipelineRecordedKeys.clear(),r={events:o,environment_key:i},a.label=1;case 1:return a.trys.push([1,3,4,5]),[4,f(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(r),headers:n({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":i},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat(p)})})];case 2:if(!(l=a.sent()).status||l.status<200||l.status>=300)throw new Error("Pipeline analytics: unexpected status ".concat(l.status));return this.log("Pipeline analytics: flush successful"),[3,5];case 3:return s=a.sent(),this.pipelineEvents=o.concat(this.pipelineEvents),this.log("Pipeline analytics: flush failed, events re-queued",s),[3,5];case 4:return this.isPipelineFlushing=!1,[7];case 5:return[2]}}))}))},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:t.FlagSource.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.evaluationAnalyticsUrl=null,this.evaluationAnalyticsMaxBuffer=1e3,this.pipelineEvents=[],this.pipelineAnalyticsInterval=null,this.isPipelineFlushing=!1,this.pipelineRecordedKeys=new Map,this.getValue=function(t,e,n){var i=o.flags&&o.flags[t.toLowerCase().replace(/ /g,"_")],a=null;if(i&&(a=i.value),(null==e?void 0:e.skipAnalytics)||n||o.evaluateFlag(t,"VALUE"),null===a&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===a?(o.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(a)}catch(t){return e.fallback}return a},this.getTrait=function(t){var e,n;return(null===(e=o.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=o.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=o.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var e,i,a=v(t);return o.evaluationContext=n(n({},a),{environment:a.environment||o.evaluationContext.environment}),o.identity=null===(i=null===(e=o.getContext())||void 0===e?void 0:e.identity)||void 0===i?void 0:i.identifier,o.initialised?o.getFlags():Promise.resolve()},this.getContext=function(){return o.evaluationContext},this.updateContext=function(t){return o.setContext(n(n({},o.getContext()),t))},this.setTrait=function(t,e){var i;if(o.api)return o.setContext(n(n({},o.evaluationContext),{identity:n(n({},o.evaluationContext.identity),{traits:n(n({},null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.traits),c(Object.fromEntries([[t,e]])))})}))},this.setTraits=function(t){var e;if(o.api)return o.setContext(n(n({},o.evaluationContext),{identity:n(n({},o.evaluationContext.identity),{traits:n(n({},null===(e=o.evaluationContext.identity)||void 0===e?void 0:e.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,i,a="object"==typeof e,r=o.flags&&o.flags[t.toLowerCase().replace(/ /g,"_")],l=!1;if(!r&&a&&void 0!==e.fallback?l=null==e?void 0:e.fallback:r&&r.enabled&&(l=!0),(a&&!e.skipAnalytics||!e)&&o.evaluateFlag(t,"ENABLED"),o.sentryClient)try{null===(i=null===(n=o.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===i||i.call(n,t,l)}catch(t){console.error(t)}return l},this.getStorageKey=function(){var t,e;return(null===(t=o.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=o.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var i,a,r,l=o.headers,s={method:e||"GET",body:n,cache:"no-cache",headers:{}};o.evaluationContext.environment&&(s.headers["X-Environment-Key"]=o.evaluationContext.environment.apiKey),e&&"GET"!==e&&(s.headers["Content-Type"]="application/json; charset=utf-8"),(null===(i=o.applicationMetadata)||void 0===i?void 0:i.name)&&(s.headers["Flagsmith-Application-Name"]=o.applicationMetadata.name),(null===(a=o.applicationMetadata)||void 0===a?void 0:a.version)&&(s.headers["Flagsmith-Application-Version"]=o.applicationMetadata.version),s.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat(p),l&&Object.assign(s.headers,l),f||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=o.evaluationContext.identity)||void 0===r?void 0:r.identifier);return f(t,s).then((function(n){var i,a,r="".concat(null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.identifier);if(u===r){var l=null===(a=n.headers)||void 0===a?void 0:a.get("x-flagsmith-document-updated-at");if(l)try{var s=parseFloat(l);if(isNaN(s))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");o.timestamp=s}catch(t){o.log(t,"Failed to parse x-flagsmith-document-updated-at",l)}return o.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}o.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(o.datadogRum&&(o.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?o.datadogRum.client.addFeatureFlagEvaluation(_+t,o.getValue(t,{},!0)):o.datadogRum.client.addFeatureFlagEvaluation(b+t,o.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),o.enableAnalytics){if(!o.evaluationEvent||!o.evaluationContext.environment)return;o.evaluationEvent[o.evaluationContext.environment.apiKey]||(o.evaluationEvent[o.evaluationContext.environment.apiKey]={}),void 0===o.evaluationEvent[o.evaluationContext.environment.apiKey][t]&&(o.evaluationEvent[o.evaluationContext.environment.apiKey][t]=0),o.evaluationEvent[o.evaluationContext.environment.apiKey][t]+=1}o.evaluationAnalyticsUrl&&o.recordPipelineEvent(t),o.updateEventStorage()},this.pipelineFlushInterval=1e4,this.trackEvent=function(t,e){if(o.evaluationAnalyticsUrl&&t){var n=o.buildAnalyticEvent(g.CUSTOM_EVENT,t,{extraMetadata:e});o.pipelineEvents.push(n),(0===o.pipelineFlushInterval||o.pipelineEvents.length>=o.evaluationAnalyticsMaxBuffer)&&o.flushPipelineAnalytics()}},this._onChange=function(t,e,n){var i,a;o.setLoadingState(n),null===(i=o.onChange)||void 0===i||i.call(o,t,e,o.loadingState),null===(a=o._trigger)||void 0===a||a.call(o)},f=e.fetch?e.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!e.browserlessStorage,this.applicationMetadata=e.applicationMetadata,this.log("Constructing flagsmith instance "+e),e.eventSource&&(y=e.eventSource),e.AsyncStorage&&(m=e.AsyncStorage)}return e.prototype.init=function(e){var o,r,s,u;return i(this,void 0,void 0,(function(){var c,d,g,p,y,S,_,b,x,F,O,A,w,I,j,L,P,T,k,N,U,K,R,M,D,G,J,V,B,H,q,W,X,Y,z,Q,Z=this;return a(this,(function($){switch($.label){case 0:c=v(e.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),d=e.AsyncStorage,g=e._trigger,p=e._triggerLoadingState,y=e.angularHttpClient,S=e.api,_=void 0===S?E:S,b=e.applicationMetadata,x=e.cacheFlags,F=e.cacheOptions,O=e.datadogRum,A=e.defaultFlags,w=e.enableAnalytics,I=e.enableDynatrace,j=e.enableLogs,L=e.environmentID,P=e.evaluationAnalyticsConfig,T=e.eventSourceUrl,k=void 0===T?"https://realtime.flagsmith.com/":T,N=e.fetch,U=e.headers,K=e.identity,R=e.onChange,M=e.onError,D=e.preventFetch,G=e.realtime,J=e.sentryClient,V=e.state,B=e.traits,c.environment=L?{apiKey:L}:c.environment,!c.environment||!c.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(c.identity=K||B?{identifier:K,traits:B?Object.fromEntries(Object.entries(B).map((function(t){return[t[0],{value:t[1]}]}))):{}}:c.identity,this.evaluationContext=c,this.api=h(_),this.headers=U,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=g||this._trigger,this._triggerLoadingState=p||this._triggerLoadingState,this.onError=function(t){Z.setLoadingState(n(n({},Z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==M||M(t)},this.enableLogs=j||!1,this.cacheOptions=F?{skipAPI:!!F.skipAPI,ttl:F.ttl||0,storageKey:F.storageKey,loadStale:!!F.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),N&&(f=N),this.enableAnalytics=w||!1,this.flags=Object.assign({},A)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==m&&!!x,this.applicationMetadata=b,C="FLAGSMITH_EVENT_"+c.environment.apiKey,d&&(m=d),G&&"undefined"!=typeof window&&this.setupRealtime(k,c.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=n(n({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(V),this.log("Initialising with properties",e,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),y&&(f=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},l=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(l(t,!t.status||t.status>=200&&t.status<300))},s=function(t){return n(l(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,s);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,s);default:return s({status:405,message:"Unsupported method: ".concat(a)})}}))}}(y)),m&&this.canUseStorage&&m.getItem(C).then((function(t){try{Z.evaluationEvent=JSON.parse(t)||{}}catch(t){Z.evaluationEvent={}}Z.analyticsInterval=setInterval(Z.analyticsFlags,Z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),m&&this.canUseStorage&&m.getItem(C,(function(t,e){if(e&&Z.evaluationContext.environment){var i=JSON.parse(e);if(i[Z.evaluationContext.environment.apiKey]){var a=Z.getState();Z.log("Retrieved events from cache",e),Z.setState(n(n({},a),{evaluationEvent:i[Z.evaluationContext.environment.apiKey]}))}}}))),P?this.initPipelineAnalytics(P):this.stopPipelineAnalytics(),!x)return[3,9];if(!m||!this.canUseStorage)return[3,8];q=function(e,o){return i(Z,void 0,void 0,(function(){var e,i,r,s,u,c,h,d,g,f,p,y,m,S,C,E,_,b,x,F=this;return a(this,(function(a){switch(a.label){case 0:if(!o)return[3,7];e=null,i=null,a.label=1;case 1:return a.trys.push([1,5,,6]),r=JSON.parse(o),s=!1,u=!1,r&&r.api===this.api&&(null===(f=null===(g=r.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(c=!0,this.evaluationContext.identity&&(null===(m=null===(y=r.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=r.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),c=!1),this.cacheOptions.ttl&&(!r.ts||(new Date).valueOf()-r.ts>this.cacheOptions.ttl)&&(r.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),c=!1):r.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),u=!0,c=!0)),c&&(s=!0,e=l(this.flags,r.flags),this.setState(n(n({},r),{evaluationContext:v(n(n({},r.evaluationContext),{identity:(null===(E=r.evaluationContext)||void 0===E?void 0:E.identity)?n(n({},null===(_=r.evaluationContext)||void 0===_?void 0:_.identity),{traits:n({},B||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),s?(h=!D&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,t.FlagSource.CACHE,h)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!u&&this.log("Skipping API, using cache"),h&&this.getFlags().catch((function(t){var e;null===(e=F.onError)||void 0===e||e.call(F,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:a.sent(),a.label=4;case 4:return[3,6];case 5:throw d=a.sent(),this.log("Exception fetching cached logs",d),d;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return a.sent(),[3,10];case 9:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(b=this.evaluationContext.identity)||void 0===b?void 0:b.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(H);this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS))}a.label=10;case 10:return[2]}}))}))},$.label=2;case 2:return $.trys.push([2,7,,8]),m.getItemSync?(W=m.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,m.getItem(this.getStorageKey())];case 4:W=$.sent(),$.label=5;case 5:return[4,q(null,W)];case 6:return $.sent(),[3,8];case 7:if(X=$.sent(),!this.flags||0===Object.keys(this.flags).length)throw X;return Q=X instanceof Error?X:new Error("".concat(X)),null===(o=this.onError)||void 0===o||o.call(this,Q),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:l({},A),traitsChanged:l({},null===(r=c.identity)||void 0===r?void 0:r.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else if(this.flags&&(Y=null,0===Object.keys(this.flags).length&&(Y=H),this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(s=c.identity)||void 0===s?void 0:s.traits)},this._loadedState(Y,t.FlagSource.DEFAULT_FLAGS)),Y))throw new Error(Y);$.label=12;case 12:return[3,14];case 13:throw z=$.sent(),this.log("Error during initialisation ",z),Q=z instanceof Error?z:new Error("".concat(z)),null===(u=this.onError)||void 0===u||u.call(this,Q),z;case 14:return[2]}}))}))},e.prototype.getAllFlags=function(){return this.flags},e.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},e.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},e.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||E,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this))},e.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},e.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},e.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},e.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},e.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,o(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},e.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),m.setItem(this.getStorageKey(),t)}},e.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);m.setItem(C,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},e.prototype.initPipelineAnalytics=function(t){var e,n,i,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=h(t.analyticsServerUrl),this.evaluationAnalyticsMaxBuffer=null!==(e=t.maxBuffer)&&void 0!==e?e:1e3,this.pipelineFlushInterval=null!==(n=t.flushInterval)&&void 0!==n?n:1e4,this.pipelineEvents=[],this.pipelineFlushInterval>0&&(this.pipelineAnalyticsInterval=setInterval(this.flushPipelineAnalytics,this.pipelineFlushInterval),null===(a=null===(i=this.pipelineAnalyticsInterval)||void 0===i?void 0:i.unref)||void 0===a||a.call(i))},e.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},e.prototype.currentTraitsSnapshot=function(){var t;return(null===(t=this.evaluationContext.identity)||void 0===t?void 0:t.traits)?n({},this.evaluationContext.identity.traits):null},e.prototype.getPageUrl=function(){return"undefined"!=typeof window&&window.location?window.location.href:null},e.prototype.getEventMetadata=function(t){var e=this.getPageUrl();return n(n(n({},t||{}),e?{page_url:e}:{}),{sdk_version:p})},e.prototype.buildAnalyticEvent=function(t,e,n){var i,a,o,r,l;return{event_id:e,event_type:t,evaluated_at:null!==(i=null==n?void 0:n.timestamp)&&void 0!==i?i:Date.now(),identity_identifier:null!==(o=null===(a=this.evaluationContext.identity)||void 0===a?void 0:a.identifier)&&void 0!==o?o:null,enabled:null!==(r=null==n?void 0:n.enabled)&&void 0!==r?r:null,value:null!==(l=null==n?void 0:n.value)&&void 0!==l?l:null,traits:this.currentTraitsSnapshot(),metadata:this.getEventMetadata(null==n?void 0:n.extraMetadata)}},e.prototype.recordPipelineEvent=function(t){var e,n,i,a,o=t.toLowerCase().replace(/ /g,"_"),r=this.flags&&this.flags[o],l="".concat(null!==(n=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==n?n:"none","|").concat(null!==(i=null==r?void 0:r.enabled)&&void 0!==i&&i,"|").concat(null!==(a=null==r?void 0:r.value)&&void 0!==a?a:"null");if(this.pipelineRecordedKeys.get(o)!==l){this.pipelineRecordedKeys.set(o,l);var s=this.buildAnalyticEvent(g.FLAG_EVALUATION,o,{enabled:r?r.enabled:null,value:r?r.value:null,extraMetadata:r?{id:r.id}:void 0});this.pipelineEvents.push(s),(0===this.pipelineFlushInterval||this.pipelineEvents.length>=this.evaluationAnalyticsMaxBuffer)&&this.flushPipelineAnalytics()}},e.prototype.setLoadingState=function(t){var e;r(t,this.loadingState)||(this.loadingState=n({},t),this.log("Loading state changed",t),null===(e=this._triggerLoadingState)||void 0===e||e.call(this))},e.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";y?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new y(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},e}();function O(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new F({fetch:e,AsyncStorage:n,eventSource:i})}var A,w=(A=function(t,e){return A=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},A(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}A(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),I=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},j=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},L=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},P=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return w(e,t),e}(Error),T=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new P;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=I(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=I(L([],j(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=L(L([],j(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var k=O({AsyncStorage:e,eventSource:"undefined"!=typeof window?T:null});"undefined"!=typeof window&&(window.flagsmith=k);t.createFlagsmithInstance=function(){return O({AsyncStorage:e,eventSource:"undefined"!=typeof window?T:null})},t.default=k,Object.defineProperty(t,"__esModule",{value:!0})}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).isomorphic={})}(this,(function(t){"use strict";var e={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},n=function(){return n=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},n.apply(this,arguments)};function i(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{s(i.next(t))}catch(t){o(t)}}function l(t){try{s(i.throw(t))}catch(t){o(t)}}function s(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,l)}s((i=i.apply(t,e||[])).next())}))}function a(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function o(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var r=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function l(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!r(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function s(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function u(t){return!!t&&"object"==typeof t&&void 0!==t.value}function c(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))}function v(t){return n(n({},t),{identity:t.identity?n(n({},t.identity),{traits:c(t.identity.traits||{})}):void 0})}function h(t){return t.endsWith("/")?t:t+"/"}var d,g,f,p="11.0.0-internal.7";t.FlagSource=void 0,(d=t.FlagSource||(t.FlagSource={})).NONE="NONE",d.DEFAULT_FLAGS="DEFAULT_FLAGS",d.CACHE="CACHE",d.SERVER="SERVER",function(t){t.FLAG_EVALUATION="flag_evaluation",t.CUSTOM_EVENT="custom_event"}(g||(g={}));var y,m=null,S="FLAGSMITH_EVENT",C=S,E="https://edge.api.flagsmith.com/api/v1/",_="flagsmith_value_",b="flagsmith_enabled_",x="flagsmith_trait_",F=function(){function e(e){var o=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var e=o,i=e.api,a=e.evaluationContext;o.log("Get Flags"),o.isLoading=!0,o.loadingState.isFetching||o.setLoadingState(n(n({},o.loadingState),{isFetching:!0}));var r="".concat(o.getContext().identity),u=function(e){var i,a,u,c;if(e&&r==="".concat(o.getContext().identity)){var v=e.flags,h=e.traits,d=e.identifier;o.isLoading=!1;var g={},f={};h=h||[],(v=v||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),h.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),o.oldFlags=n({},o.flags);var p=l(o.oldFlags,g),y=l(null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.traits,f);if((d||Object.keys(f).length)&&(o.evaluationContext.identity=n(n({},o.evaluationContext.identity),{traits:f}),d&&(o.evaluationContext.identity.identifier=d,o.identity=d)),o.flags=g,o.updateStorage(),o._onChange(o.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},o._loadedState(null,t.FlagSource.SERVER)),o.datadogRum)try{if(o.datadogRum.trackTraits){var m={};Object.keys((null===(a=o.evaluationContext.identity)||void 0===a?void 0:a.traits)||{}).map((function(t){m[x+t]=o.getTrait(t)}));var S=n(n(n({},o.datadogRum.client.getUser()),{id:o.datadogRum.client.getUser().id||(null===(u=o.evaluationContext.identity)||void 0===u?void 0:u.identifier)}),m);o.log("Setting Datadog user",S),o.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(o.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(o.flags).map((function(t){s(C,_+t,o.getValue(t,{skipAnalytics:!0})),s(C,b+t,o.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=o.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){s(C,x+t,o.getTrait(t))})),o.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),o.log("Sending date traits to dynatrace",C.date),o.log("Sending shortString traits to dynatrace",C.shortString),o.log("Sending javaDouble to dynatrace",C.javaDouble),o.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return a.identity?Promise.all([a.identity.traits&&Object.keys(a.identity.traits).length||!a.identity.identifier?o.getJSON(i+"identities/","POST",JSON.stringify({identifier:a.identity.identifier,transient:a.identity.transient,traits:Object.entries(a.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(o.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):o.getJSON(i+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(t){return o.evaluationContext.identity=n(n({},o.evaluationContext.identity),{traits:{}}),u(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):o.getJSON(i+"flags/").then((function(t){return u({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=o.api;if(o.evaluationEvent&&o.evaluationContext.environment&&o.evaluationEvent[o.evaluationContext.environment.apiKey])return o.evaluationEvent&&0!==Object.getOwnPropertyNames(o.evaluationEvent).length&&0!==Object.getOwnPropertyNames(o.evaluationEvent[o.evaluationContext.environment.apiKey]).length?o.getJSON(t+"analytics/flags/","POST",JSON.stringify(o.evaluationEvent[o.evaluationContext.environment.apiKey])).then((function(t){if(o.evaluationContext.environment){var e=o.getState();o.evaluationEvent||(o.evaluationEvent={}),o.evaluationEvent[o.evaluationContext.environment.apiKey]={},o.setState(n(n({},e),{evaluationEvent:o.evaluationEvent})),o.updateEventStorage()}})).catch((function(t){o.log("Exception fetching evaluationEvent",t)})):void 0},this.flushPipelineAnalytics=function(){return i(o,void 0,void 0,(function(){var t,e,i,o,r,l,s;return a(this,(function(a){switch(a.label){case 0:if(t=this.evaluationAnalyticsUrl&&this.evaluationContext.environment,e=this.pipelineEvents.length>0&&(!this.isPipelineFlushing||0===this.pipelineFlushInterval),!t||!e)return[2];i=this.evaluationContext.environment.apiKey,this.isPipelineFlushing=!0,o=this.pipelineEvents.slice(0,this.evaluationAnalyticsMaxBuffer),this.pipelineEvents=this.pipelineEvents.slice(this.evaluationAnalyticsMaxBuffer),this.pipelineRecordedKeys.clear(),r={events:o,environment_key:i},a.label=1;case 1:return a.trys.push([1,3,4,5]),[4,f(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(r),headers:n({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":i},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat(p)})})];case 2:if(!(l=a.sent()).status||l.status<200||l.status>=300)throw new Error("Pipeline analytics: unexpected status ".concat(l.status));return this.log("Pipeline analytics: flush successful"),[3,5];case 3:return s=a.sent(),this.pipelineEvents=o.concat(this.pipelineEvents),this.log("Pipeline analytics: flush failed, events re-queued",s),[3,5];case 4:return this.isPipelineFlushing=!1,[7];case 5:return[2]}}))}))},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:t.FlagSource.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.evaluationAnalyticsUrl=null,this.evaluationAnalyticsMaxBuffer=1e3,this.pipelineEvents=[],this.pipelineAnalyticsInterval=null,this.isPipelineFlushing=!1,this.pipelineRecordedKeys=new Map,this.getValue=function(t,e,n){var i=o.flags&&o.flags[t.toLowerCase().replace(/ /g,"_")],a=null;if(i&&(a=i.value),(null==e?void 0:e.skipAnalytics)||n||o.evaluateFlag(t,"VALUE"),null===a&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===a?(o.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(a)}catch(t){return e.fallback}return a},this.getTrait=function(t){var e,n;return(null===(e=o.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=o.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=o.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var e,i,a=v(t);return o.evaluationContext=n(n({},a),{environment:a.environment||o.evaluationContext.environment}),o.identity=null===(i=null===(e=o.getContext())||void 0===e?void 0:e.identity)||void 0===i?void 0:i.identifier,o.initialised?o.getFlags():Promise.resolve()},this.getContext=function(){return o.evaluationContext},this.updateContext=function(t){return o.setContext(n(n({},o.getContext()),t))},this.setTrait=function(t,e){var i;if(o.api)return o.setContext(n(n({},o.evaluationContext),{identity:n(n({},o.evaluationContext.identity),{traits:n(n({},null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.traits),c(Object.fromEntries([[t,e]])))})}))},this.setTraits=function(t){var e;if(o.api)return o.setContext(n(n({},o.evaluationContext),{identity:n(n({},o.evaluationContext.identity),{traits:n(n({},null===(e=o.evaluationContext.identity)||void 0===e?void 0:e.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,i,a="object"==typeof e,r=o.flags&&o.flags[t.toLowerCase().replace(/ /g,"_")],l=!1;if(!r&&a&&void 0!==e.fallback?l=null==e?void 0:e.fallback:r&&r.enabled&&(l=!0),(a&&!e.skipAnalytics||!e)&&o.evaluateFlag(t,"ENABLED"),o.sentryClient)try{null===(i=null===(n=o.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===i||i.call(n,t,l)}catch(t){console.error(t)}return l},this.getStorageKey=function(){var t,e;return(null===(t=o.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=o.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var i,a,r,l=o.headers,s={method:e||"GET",body:n,cache:"no-cache",headers:{}};o.evaluationContext.environment&&(s.headers["X-Environment-Key"]=o.evaluationContext.environment.apiKey),e&&"GET"!==e&&(s.headers["Content-Type"]="application/json; charset=utf-8"),(null===(i=o.applicationMetadata)||void 0===i?void 0:i.name)&&(s.headers["Flagsmith-Application-Name"]=o.applicationMetadata.name),(null===(a=o.applicationMetadata)||void 0===a?void 0:a.version)&&(s.headers["Flagsmith-Application-Version"]=o.applicationMetadata.version),s.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat(p),l&&Object.assign(s.headers,l),f||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=o.evaluationContext.identity)||void 0===r?void 0:r.identifier);return f(t,s).then((function(n){var i,a,r="".concat(null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.identifier);if(u===r){var l=null===(a=n.headers)||void 0===a?void 0:a.get("x-flagsmith-document-updated-at");if(l)try{var s=parseFloat(l);if(isNaN(s))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");o.timestamp=s}catch(t){o.log(t,"Failed to parse x-flagsmith-document-updated-at",l)}return o.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}o.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(o.datadogRum&&(o.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?o.datadogRum.client.addFeatureFlagEvaluation(_+t,o.getValue(t,{},!0)):o.datadogRum.client.addFeatureFlagEvaluation(b+t,o.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),o.enableAnalytics){if(!o.evaluationEvent||!o.evaluationContext.environment)return;o.evaluationEvent[o.evaluationContext.environment.apiKey]||(o.evaluationEvent[o.evaluationContext.environment.apiKey]={}),void 0===o.evaluationEvent[o.evaluationContext.environment.apiKey][t]&&(o.evaluationEvent[o.evaluationContext.environment.apiKey][t]=0),o.evaluationEvent[o.evaluationContext.environment.apiKey][t]+=1}o.evaluationAnalyticsUrl&&o.recordPipelineEvent(t),o.updateEventStorage()},this.pipelineFlushInterval=1e4,this.trackEvent=function(t,e){if(o.evaluationAnalyticsUrl&&t){var n=o.buildAnalyticEvent(g.CUSTOM_EVENT,t,{extraMetadata:e});o.pipelineEvents.push(n),(0===o.pipelineFlushInterval||o.pipelineEvents.length>=o.evaluationAnalyticsMaxBuffer)&&o.flushPipelineAnalytics()}},this._onChange=function(t,e,n){var i,a;o.setLoadingState(n),null===(i=o.onChange)||void 0===i||i.call(o,t,e,o.loadingState),null===(a=o._trigger)||void 0===a||a.call(o)},f=e.fetch?e.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!e.browserlessStorage,this.applicationMetadata=e.applicationMetadata,this.log("Constructing flagsmith instance "+e),e.eventSource&&(y=e.eventSource),e.AsyncStorage&&(m=e.AsyncStorage)}return e.prototype.init=function(e){var o,r,s,u;return i(this,void 0,void 0,(function(){var c,d,g,p,y,S,_,b,x,F,O,A,w,I,j,L,P,T,k,N,U,K,R,M,D,G,J,V,B,H,q,W,X,Y,z,Q,Z=this;return a(this,(function($){switch($.label){case 0:c=v(e.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),d=e.AsyncStorage,g=e._trigger,p=e._triggerLoadingState,y=e.angularHttpClient,S=e.api,_=void 0===S?E:S,b=e.applicationMetadata,x=e.cacheFlags,F=e.cacheOptions,O=e.datadogRum,A=e.defaultFlags,w=e.enableAnalytics,I=e.enableDynatrace,j=e.enableLogs,L=e.environmentID,P=e.evaluationAnalyticsConfig,T=e.eventSourceUrl,k=void 0===T?"https://realtime.flagsmith.com/":T,N=e.fetch,U=e.headers,K=e.identity,R=e.onChange,M=e.onError,D=e.preventFetch,G=e.realtime,J=e.sentryClient,V=e.state,B=e.traits,c.environment=L?{apiKey:L}:c.environment,!c.environment||!c.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(c.identity=K||B?{identifier:K,traits:B?Object.fromEntries(Object.entries(B).map((function(t){return[t[0],{value:t[1]}]}))):{}}:c.identity,this.evaluationContext=c,this.api=h(_),this.headers=U,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=g||this._trigger,this._triggerLoadingState=p||this._triggerLoadingState,this.onError=function(t){Z.setLoadingState(n(n({},Z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==M||M(t)},this.enableLogs=j||!1,this.cacheOptions=F?{skipAPI:!!F.skipAPI,ttl:F.ttl||0,storageKey:F.storageKey,loadStale:!!F.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),N&&(f=N),this.enableAnalytics=w||!1,this.flags=Object.assign({},A)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==m&&!!x,this.applicationMetadata=b,C="FLAGSMITH_EVENT_"+c.environment.apiKey,d&&(m=d),G&&"undefined"!=typeof window&&this.setupRealtime(k,c.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=n(n({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(V),this.log("Initialising with properties",e,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),y&&(f=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},l=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(l(t,!t.status||t.status>=200&&t.status<300))},s=function(t){return n(l(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,s);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,s);default:return s({status:405,message:"Unsupported method: ".concat(a)})}}))}}(y)),m&&this.canUseStorage&&m.getItem(C).then((function(t){try{Z.evaluationEvent=JSON.parse(t)||{}}catch(t){Z.evaluationEvent={}}Z.analyticsInterval=setInterval(Z.analyticsFlags,Z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),m&&this.canUseStorage&&m.getItem(C,(function(t,e){if(e&&Z.evaluationContext.environment){var i=JSON.parse(e);if(i[Z.evaluationContext.environment.apiKey]){var a=Z.getState();Z.log("Retrieved events from cache",e),Z.setState(n(n({},a),{evaluationEvent:i[Z.evaluationContext.environment.apiKey]}))}}}))),P?this.initPipelineAnalytics(P):this.stopPipelineAnalytics(),!x)return[3,9];if(!m||!this.canUseStorage)return[3,8];q=function(e,o){return i(Z,void 0,void 0,(function(){var e,i,r,s,u,c,h,d,g,f,p,y,m,S,C,E,_,b,x,F=this;return a(this,(function(a){switch(a.label){case 0:if(!o)return[3,7];e=null,i=null,a.label=1;case 1:return a.trys.push([1,5,,6]),r=JSON.parse(o),s=!1,u=!1,r&&r.api===this.api&&(null===(f=null===(g=r.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(c=!0,this.evaluationContext.identity&&(null===(m=null===(y=r.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=r.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),c=!1),this.cacheOptions.ttl&&(!r.ts||(new Date).valueOf()-r.ts>this.cacheOptions.ttl)&&(r.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),c=!1):r.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),u=!0,c=!0)),c&&(s=!0,e=l(this.flags,r.flags),this.setState(n(n({},r),{evaluationContext:v(n(n({},r.evaluationContext),{identity:(null===(E=r.evaluationContext)||void 0===E?void 0:E.identity)?n(n({},null===(_=r.evaluationContext)||void 0===_?void 0:_.identity),{traits:n({},B||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),s?(h=!D&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,t.FlagSource.CACHE,h)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!u&&this.log("Skipping API, using cache"),h&&this.getFlags().catch((function(t){var e;null===(e=F.onError)||void 0===e||e.call(F,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:a.sent(),a.label=4;case 4:return[3,6];case 5:throw d=a.sent(),this.log("Exception fetching cached logs",d),d;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return a.sent(),[3,10];case 9:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(b=this.evaluationContext.identity)||void 0===b?void 0:b.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(H);this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS))}a.label=10;case 10:return[2]}}))}))},$.label=2;case 2:return $.trys.push([2,7,,8]),m.getItemSync?(W=m.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,m.getItem(this.getStorageKey())];case 4:W=$.sent(),$.label=5;case 5:return[4,q(null,W)];case 6:return $.sent(),[3,8];case 7:if(X=$.sent(),!this.flags||0===Object.keys(this.flags).length)throw X;return Q=X instanceof Error?X:new Error("".concat(X)),null===(o=this.onError)||void 0===o||o.call(this,Q),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:l({},A),traitsChanged:l({},null===(r=c.identity)||void 0===r?void 0:r.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else if(this.flags&&(Y=null,0===Object.keys(this.flags).length&&(Y=H),this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(s=c.identity)||void 0===s?void 0:s.traits)},this._loadedState(Y,t.FlagSource.DEFAULT_FLAGS)),Y))throw new Error(Y);$.label=12;case 12:return[3,14];case 13:throw z=$.sent(),this.log("Error during initialisation ",z),Q=z instanceof Error?z:new Error("".concat(z)),null===(u=this.onError)||void 0===u||u.call(this,Q),z;case 14:return[2]}}))}))},e.prototype.getAllFlags=function(){return this.flags},e.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},e.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},e.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||E,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this))},e.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},e.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},e.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},e.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},e.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,o(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},e.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),m.setItem(this.getStorageKey(),t)}},e.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);m.setItem(C,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},e.prototype.initPipelineAnalytics=function(t){var e,n,i,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=h(t.analyticsServerUrl),this.evaluationAnalyticsMaxBuffer=null!==(e=t.maxBuffer)&&void 0!==e?e:1e3,this.pipelineFlushInterval=null!==(n=t.flushInterval)&&void 0!==n?n:1e4,this.pipelineEvents=[],this.pipelineFlushInterval>0&&(this.pipelineAnalyticsInterval=setInterval(this.flushPipelineAnalytics,this.pipelineFlushInterval),null===(a=null===(i=this.pipelineAnalyticsInterval)||void 0===i?void 0:i.unref)||void 0===a||a.call(i))},e.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},e.prototype.currentTraitsSnapshot=function(){var t;return(null===(t=this.evaluationContext.identity)||void 0===t?void 0:t.traits)?n({},this.evaluationContext.identity.traits):null},e.prototype.getPageUrl=function(){return"undefined"!=typeof window&&window.location?window.location.href:null},e.prototype.getEventMetadata=function(t){var e=this.getPageUrl();return n(n(n({},t||{}),e?{page_url:e}:{}),{sdk_version:p})},e.prototype.buildAnalyticEvent=function(t,e,n){var i,a,o,r,l;return{event_id:e,event_type:t,evaluated_at:null!==(i=null==n?void 0:n.timestamp)&&void 0!==i?i:Date.now(),identity_identifier:null!==(o=null===(a=this.evaluationContext.identity)||void 0===a?void 0:a.identifier)&&void 0!==o?o:null,enabled:null!==(r=null==n?void 0:n.enabled)&&void 0!==r?r:null,value:null!==(l=null==n?void 0:n.value)&&void 0!==l?l:null,traits:this.currentTraitsSnapshot(),metadata:this.getEventMetadata(null==n?void 0:n.extraMetadata)}},e.prototype.recordPipelineEvent=function(t){var e,n,i,a,o=t.toLowerCase().replace(/ /g,"_"),r=this.flags&&this.flags[o],l="".concat(null!==(n=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==n?n:"none","|").concat(null!==(i=null==r?void 0:r.enabled)&&void 0!==i&&i,"|").concat(null!==(a=null==r?void 0:r.value)&&void 0!==a?a:"null");if(this.pipelineRecordedKeys.get(o)!==l){this.pipelineRecordedKeys.set(o,l);var s=this.buildAnalyticEvent(g.FLAG_EVALUATION,o,{enabled:r?r.enabled:null,value:r?r.value:null,extraMetadata:r?{id:r.id}:void 0});this.pipelineEvents.push(s),(0===this.pipelineFlushInterval||this.pipelineEvents.length>=this.evaluationAnalyticsMaxBuffer)&&this.flushPipelineAnalytics()}},e.prototype.setLoadingState=function(t){var e;r(t,this.loadingState)||(this.loadingState=n({},t),this.log("Loading state changed",t),null===(e=this._triggerLoadingState)||void 0===e||e.call(this))},e.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";y?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new y(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},e}();function O(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new F({fetch:e,AsyncStorage:n,eventSource:i})}var A,w=(A=function(t,e){return A=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},A(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}A(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),I=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},j=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},L=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},P=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return w(e,t),e}(Error),T=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new P;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=I(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=I(L([],j(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=L(L([],j(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var k=O({AsyncStorage:e,eventSource:"undefined"!=typeof window?T:null});"undefined"!=typeof window&&(window.flagsmith=k);t.createFlagsmithInstance=function(){return O({AsyncStorage:e,eventSource:"undefined"!=typeof window?T:null})},t.default=k,Object.defineProperty(t,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=isomorphic.js.map
package/isomorphic.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var t={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},e=function(){return e=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},e.apply(this,arguments)};function n(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{s(i.next(t))}catch(t){o(t)}}function l(t){try{s(i.throw(t))}catch(t){o(t)}}function s(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,l)}s((i=i.apply(t,e||[])).next())}))}function i(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function a(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var o=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function r(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!o(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function l(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function s(t){return!!t&&"object"==typeof t&&void 0!==t.value}function u(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))}function c(t){return e(e({},t),{identity:t.identity?e(e({},t.identity),{traits:u(t.identity.traits||{})}):void 0})}function v(t){return t.endsWith("/")?t:t+"/"}var h,d,g;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(h||(h={})),function(t){t.FLAG_EVALUATION="flag_evaluation",t.CUSTOM_EVENT="custom_event"}(d||(d={}));var f,p=null,y="FLAGSMITH_EVENT",m="https://edge.api.flagsmith.com/api/v1/",S=function(){function t(t){var a=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var t=a,n=t.api,i=t.evaluationContext;a.log("Get Flags"),a.isLoading=!0,a.loadingState.isFetching||a.setLoadingState(e(e({},a.loadingState),{isFetching:!0}));var o="".concat(a.getContext().identity),s=function(t){var n,i,s,u;if(t&&o==="".concat(a.getContext().identity)){var c=t.flags,v=t.traits,d=t.identifier;a.isLoading=!1;var g={},f={};v=v||[],(c=c||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),v.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),a.oldFlags=e({},a.flags);var p=r(a.oldFlags,g),y=r(null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.traits,f);if((d||Object.keys(f).length)&&(a.evaluationContext.identity=e(e({},a.evaluationContext.identity),{traits:f}),d&&(a.evaluationContext.identity.identifier=d,a.identity=d)),a.flags=g,a.updateStorage(),a._onChange(a.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},a._loadedState(null,h.SERVER)),a.datadogRum)try{if(a.datadogRum.trackTraits){var m={};Object.keys((null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.traits)||{}).map((function(t){m["flagsmith_trait_"+t]=a.getTrait(t)}));var S=e(e(e({},a.datadogRum.client.getUser()),{id:a.datadogRum.client.getUser().id||(null===(s=a.evaluationContext.identity)||void 0===s?void 0:s.identifier)}),m);a.log("Setting Datadog user",S),a.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(a.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(a.flags).map((function(t){l(C,"flagsmith_value_"+t,a.getValue(t,{skipAnalytics:!0})),l(C,"flagsmith_enabled_"+t,a.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(u=a.evaluationContext.identity)||void 0===u?void 0:u.traits)||{}).map((function(t){l(C,"flagsmith_trait_"+t,a.getTrait(t))})),a.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),a.log("Sending date traits to dynatrace",C.date),a.log("Sending shortString traits to dynatrace",C.shortString),a.log("Sending javaDouble to dynatrace",C.javaDouble),a.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return i.identity?Promise.all([i.identity.traits&&Object.keys(i.identity.traits).length||!i.identity.identifier?a.getJSON(n+"identities/","POST",JSON.stringify({identifier:i.identity.identifier,transient:i.identity.transient,traits:Object.entries(i.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(a.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):a.getJSON(n+"identities/?identifier="+encodeURIComponent(i.identity.identifier)+(i.identity.transient?"&transient=true":""))]).then((function(t){return a.evaluationContext.identity=e(e({},a.evaluationContext.identity),{traits:{}}),s(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):a.getJSON(n+"flags/").then((function(t){return s({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=a.api;if(a.evaluationEvent&&a.evaluationContext.environment&&a.evaluationEvent[a.evaluationContext.environment.apiKey])return a.evaluationEvent&&0!==Object.getOwnPropertyNames(a.evaluationEvent).length&&0!==Object.getOwnPropertyNames(a.evaluationEvent[a.evaluationContext.environment.apiKey]).length?a.getJSON(t+"analytics/flags/","POST",JSON.stringify(a.evaluationEvent[a.evaluationContext.environment.apiKey])).then((function(t){if(a.evaluationContext.environment){var n=a.getState();a.evaluationEvent||(a.evaluationEvent={}),a.evaluationEvent[a.evaluationContext.environment.apiKey]={},a.setState(e(e({},n),{evaluationEvent:a.evaluationEvent})),a.updateEventStorage()}})).catch((function(t){a.log("Exception fetching evaluationEvent",t)})):void 0},this.flushPipelineAnalytics=function(){return n(a,void 0,void 0,(function(){var t,n,a,o,r,l,s;return i(this,(function(i){switch(i.label){case 0:if(t=this.evaluationAnalyticsUrl&&this.evaluationContext.environment,n=this.pipelineEvents.length>0&&(!this.isPipelineFlushing||0===this.pipelineFlushInterval),!t||!n)return[2];a=this.evaluationContext.environment.apiKey,this.isPipelineFlushing=!0,o=this.pipelineEvents.slice(0,this.evaluationAnalyticsMaxBuffer),this.pipelineEvents=this.pipelineEvents.slice(this.evaluationAnalyticsMaxBuffer),this.pipelineRecordedKeys.clear(),r={events:o,environment_key:a},i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,g(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(r),headers:e({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":a},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat("11.0.0-internal.6")})})];case 2:if(!(l=i.sent()).status||l.status<200||l.status>=300)throw new Error("Pipeline analytics: unexpected status ".concat(l.status));return this.log("Pipeline analytics: flush successful"),[3,5];case 3:return s=i.sent(),this.pipelineEvents=o.concat(this.pipelineEvents),this.log("Pipeline analytics: flush failed, events re-queued",s),[3,5];case 4:return this.isPipelineFlushing=!1,[7];case 5:return[2]}}))}))},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:h.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.evaluationAnalyticsUrl=null,this.evaluationAnalyticsMaxBuffer=1e3,this.pipelineEvents=[],this.pipelineAnalyticsInterval=null,this.isPipelineFlushing=!1,this.pipelineRecordedKeys=new Map,this.getValue=function(t,e,n){var i=a.flags&&a.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(i&&(o=i.value),(null==e?void 0:e.skipAnalytics)||n||a.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(a.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,n;return(null===(e=a.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=a.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=a.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var n,i,o=c(t);return a.evaluationContext=e(e({},o),{environment:o.environment||a.evaluationContext.environment}),a.identity=null===(i=null===(n=a.getContext())||void 0===n?void 0:n.identity)||void 0===i?void 0:i.identifier,a.initialised?a.getFlags():Promise.resolve()},this.getContext=function(){return a.evaluationContext},this.updateContext=function(t){return a.setContext(e(e({},a.getContext()),t))},this.setTrait=function(t,n){var i;if(a.api)return a.setContext(e(e({},a.evaluationContext),{identity:e(e({},a.evaluationContext.identity),{traits:e(e({},null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.traits),u(Object.fromEntries([[t,n]])))})}))},this.setTraits=function(t){var n;if(a.api)return a.setContext(e(e({},a.evaluationContext),{identity:e(e({},a.evaluationContext.identity),{traits:e(e({},null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,i,o="object"==typeof e,r=a.flags&&a.flags[t.toLowerCase().replace(/ /g,"_")],l=!1;if(!r&&o&&void 0!==e.fallback?l=null==e?void 0:e.fallback:r&&r.enabled&&(l=!0),(o&&!e.skipAnalytics||!e)&&a.evaluateFlag(t,"ENABLED"),a.sentryClient)try{null===(i=null===(n=a.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===i||i.call(n,t,l)}catch(t){console.error(t)}return l},this.getStorageKey=function(){var t,e;return(null===(t=a.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=a.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var i,o,r,l=a.headers,s={method:e||"GET",body:n,cache:"no-cache",headers:{}};a.evaluationContext.environment&&(s.headers["X-Environment-Key"]=a.evaluationContext.environment.apiKey),e&&"GET"!==e&&(s.headers["Content-Type"]="application/json; charset=utf-8"),(null===(i=a.applicationMetadata)||void 0===i?void 0:i.name)&&(s.headers["Flagsmith-Application-Name"]=a.applicationMetadata.name),(null===(o=a.applicationMetadata)||void 0===o?void 0:o.version)&&(s.headers["Flagsmith-Application-Version"]=a.applicationMetadata.version),s.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("11.0.0-internal.6"),l&&Object.assign(s.headers,l),g||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=a.evaluationContext.identity)||void 0===r?void 0:r.identifier);return g(t,s).then((function(n){var i,o,r="".concat(null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.identifier);if(u===r){var l=null===(o=n.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(l)try{var s=parseFloat(l);if(isNaN(s))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");a.timestamp=s}catch(t){a.log(t,"Failed to parse x-flagsmith-document-updated-at",l)}return a.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}a.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(a.datadogRum&&(a.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?a.datadogRum.client.addFeatureFlagEvaluation("flagsmith_value_"+t,a.getValue(t,{},!0)):a.datadogRum.client.addFeatureFlagEvaluation("flagsmith_enabled_"+t,a.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),a.enableAnalytics){if(!a.evaluationEvent||!a.evaluationContext.environment)return;a.evaluationEvent[a.evaluationContext.environment.apiKey]||(a.evaluationEvent[a.evaluationContext.environment.apiKey]={}),void 0===a.evaluationEvent[a.evaluationContext.environment.apiKey][t]&&(a.evaluationEvent[a.evaluationContext.environment.apiKey][t]=0),a.evaluationEvent[a.evaluationContext.environment.apiKey][t]+=1}a.evaluationAnalyticsUrl&&a.recordPipelineEvent(t),a.updateEventStorage()},this.pipelineFlushInterval=1e4,this.trackEvent=function(t,e){if(a.evaluationAnalyticsUrl&&t){var n=a.buildAnalyticEvent(d.CUSTOM_EVENT,t,{extraMetadata:e});a.pipelineEvents.push(n),(0===a.pipelineFlushInterval||a.pipelineEvents.length>=a.evaluationAnalyticsMaxBuffer)&&a.flushPipelineAnalytics()}},this._onChange=function(t,e,n){var i,o;a.setLoadingState(n),null===(i=a.onChange)||void 0===i||i.call(a,t,e,a.loadingState),null===(o=a._trigger)||void 0===o||o.call(a)},g=t.fetch?t.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!t.browserlessStorage,this.applicationMetadata=t.applicationMetadata,this.log("Constructing flagsmith instance "+t),t.eventSource&&(f=t.eventSource),t.AsyncStorage&&(p=t.AsyncStorage)}return t.prototype.init=function(t){var a,o,l,s;return n(this,void 0,void 0,(function(){var u,d,f,S,C,_,E,b,x,O,F,A,w,I,L,j,P,k,T,N,U,K,R,M,D,G,J,V,B,H,q,W,X,Y,z,Q,Z=this;return i(this,(function($){switch($.label){case 0:u=c(t.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),d=t.AsyncStorage,f=t._trigger,S=t._triggerLoadingState,C=t.angularHttpClient,_=t.api,E=void 0===_?m:_,b=t.applicationMetadata,x=t.cacheFlags,O=t.cacheOptions,F=t.datadogRum,A=t.defaultFlags,w=t.enableAnalytics,I=t.enableDynatrace,L=t.enableLogs,j=t.environmentID,P=t.evaluationAnalyticsConfig,k=t.eventSourceUrl,T=void 0===k?"https://realtime.flagsmith.com/":k,N=t.fetch,U=t.headers,K=t.identity,R=t.onChange,M=t.onError,D=t.preventFetch,G=t.realtime,J=t.sentryClient,V=t.state,B=t.traits,u.environment=j?{apiKey:j}:u.environment,!u.environment||!u.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(u.identity=K||B?{identifier:K,traits:B?Object.fromEntries(Object.entries(B).map((function(t){return[t[0],{value:t[1]}]}))):{}}:u.identity,this.evaluationContext=u,this.api=v(E),this.headers=U,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=f||this._trigger,this._triggerLoadingState=S||this._triggerLoadingState,this.onError=function(t){Z.setLoadingState(e(e({},Z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==M||M(t)},this.enableLogs=L||!1,this.cacheOptions=O?{skipAPI:!!O.skipAPI,ttl:O.ttl||0,storageKey:O.storageKey,loadStale:!!O.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),N&&(g=N),this.enableAnalytics=w||!1,this.flags=Object.assign({},A)||{},this.datadogRum=F||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==p&&!!x,this.applicationMetadata=b,y="FLAGSMITH_EVENT_"+u.environment.apiKey,d&&(p=d),G&&"undefined"!=typeof window&&this.setupRealtime(T,u.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:h.DEFAULT_FLAGS})),this.setState(V),this.log("Initialising with properties",t,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),C&&(g=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},l=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(l(t,!t.status||t.status>=200&&t.status<300))},s=function(t){return n(l(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,s);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,s);default:return s({status:405,message:"Unsupported method: ".concat(a)})}}))}}(C)),p&&this.canUseStorage&&p.getItem(y).then((function(t){try{Z.evaluationEvent=JSON.parse(t)||{}}catch(t){Z.evaluationEvent={}}Z.analyticsInterval=setInterval(Z.analyticsFlags,Z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),p&&this.canUseStorage&&p.getItem(y,(function(t,n){if(n&&Z.evaluationContext.environment){var i=JSON.parse(n);if(i[Z.evaluationContext.environment.apiKey]){var a=Z.getState();Z.log("Retrieved events from cache",n),Z.setState(e(e({},a),{evaluationEvent:i[Z.evaluationContext.environment.apiKey]}))}}}))),P?this.initPipelineAnalytics(P):this.stopPipelineAnalytics(),!x)return[3,9];if(!p||!this.canUseStorage)return[3,8];q=function(t,a){return n(Z,void 0,void 0,(function(){var t,n,o,l,s,u,v,d,g,f,p,y,m,S,C,_,E,b,x,O=this;return i(this,(function(i){switch(i.label){case 0:if(!a)return[3,7];t=null,n=null,i.label=1;case 1:return i.trys.push([1,5,,6]),o=JSON.parse(a),l=!1,s=!1,o&&o.api===this.api&&(null===(f=null===(g=o.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(u=!0,this.evaluationContext.identity&&(null===(m=null===(y=o.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=o.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),u=!1),this.cacheOptions.ttl&&(!o.ts||(new Date).valueOf()-o.ts>this.cacheOptions.ttl)&&(o.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),u=!1):o.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),s=!0,u=!0)),u&&(l=!0,t=r(this.flags,o.flags),this.setState(e(e({},o),{evaluationContext:c(e(e({},o.evaluationContext),{identity:(null===(_=o.evaluationContext)||void 0===_?void 0:_.identity)?e(e({},null===(E=o.evaluationContext)||void 0===E?void 0:E.identity),{traits:e({},B||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),l?(v=!D&&(!this.cacheOptions.skipAPI||s),this._onChange(null,{isFromServer:!1,flagsChanged:t,traitsChanged:n},this._loadedState(null,h.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&l&&!s&&this.log("Skipping API, using cache"),v&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:i.sent(),i.label=4;case 4:return[3,6];case 5:throw d=i.sent(),this.log("Exception fetching cached logs",d),d;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(b=this.evaluationContext.identity)||void 0===b?void 0:b.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(H);this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,h.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},$.label=2;case 2:return $.trys.push([2,7,,8]),p.getItemSync?(W=p.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,p.getItem(this.getStorageKey())];case 4:W=$.sent(),$.label=5;case 5:return[4,q(null,W)];case 6:return $.sent(),[3,8];case 7:if(X=$.sent(),!this.flags||0===Object.keys(this.flags).length)throw X;return Q=X instanceof Error?X:new Error("".concat(X)),null===(a=this.onError)||void 0===a||a.call(this,Q),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:r({},A),traitsChanged:r({},null===(o=u.identity)||void 0===o?void 0:o.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else if(this.flags&&(Y=null,0===Object.keys(this.flags).length&&(Y=H),this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(l=u.identity)||void 0===l?void 0:l.traits)},this._loadedState(Y,h.DEFAULT_FLAGS)),Y))throw new Error(Y);$.label=12;case 12:return[3,14];case 13:throw z=$.sent(),this.log("Error during initialisation ",z),Q=z instanceof Error?z:new Error("".concat(z)),null===(s=this.onError)||void 0===s||s.call(this,Q),z;case 14:return[2]}}))}))},t.prototype.getAllFlags=function(){return this.flags},t.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},t.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},t.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||m,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this))},t.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},t.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},t.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},t.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,a(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},t.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),p.setItem(this.getStorageKey(),t)}},t.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);p.setItem(y,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},t.prototype.initPipelineAnalytics=function(t){var e,n,i,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=v(t.analyticsServerUrl),this.evaluationAnalyticsMaxBuffer=null!==(e=t.maxBuffer)&&void 0!==e?e:1e3,this.pipelineFlushInterval=null!==(n=t.flushInterval)&&void 0!==n?n:1e4,this.pipelineEvents=[],this.pipelineFlushInterval>0&&(this.pipelineAnalyticsInterval=setInterval(this.flushPipelineAnalytics,this.pipelineFlushInterval),null===(a=null===(i=this.pipelineAnalyticsInterval)||void 0===i?void 0:i.unref)||void 0===a||a.call(i))},t.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},t.prototype.currentTraitsSnapshot=function(){var t;return(null===(t=this.evaluationContext.identity)||void 0===t?void 0:t.traits)?e({},this.evaluationContext.identity.traits):null},t.prototype.getPageUrl=function(){return"undefined"!=typeof window&&window.location?window.location.href:null},t.prototype.getEventMetadata=function(t){var n=this.getPageUrl();return e(e(e({},t||{}),n?{page_url:n}:{}),{sdk_version:"11.0.0-internal.6"})},t.prototype.buildAnalyticEvent=function(t,e,n){var i,a,o,r,l;return{event_id:e,event_type:t,evaluated_at:null!==(i=null==n?void 0:n.timestamp)&&void 0!==i?i:Date.now(),identity_identifier:null!==(o=null===(a=this.evaluationContext.identity)||void 0===a?void 0:a.identifier)&&void 0!==o?o:null,enabled:null!==(r=null==n?void 0:n.enabled)&&void 0!==r?r:null,value:null!==(l=null==n?void 0:n.value)&&void 0!==l?l:null,traits:this.currentTraitsSnapshot(),metadata:this.getEventMetadata(null==n?void 0:n.extraMetadata)}},t.prototype.recordPipelineEvent=function(t){var e,n,i,a,o=t.toLowerCase().replace(/ /g,"_"),r=this.flags&&this.flags[o],l="".concat(null!==(n=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==n?n:"none","|").concat(null!==(i=null==r?void 0:r.enabled)&&void 0!==i&&i,"|").concat(null!==(a=null==r?void 0:r.value)&&void 0!==a?a:"null");if(this.pipelineRecordedKeys.get(o)!==l){this.pipelineRecordedKeys.set(o,l);var s=this.buildAnalyticEvent(d.FLAG_EVALUATION,o,{enabled:r?r.enabled:null,value:r?r.value:null,extraMetadata:r?{id:r.id}:void 0});this.pipelineEvents.push(s),(0===this.pipelineFlushInterval||this.pipelineEvents.length>=this.evaluationAnalyticsMaxBuffer)&&this.flushPipelineAnalytics()}},t.prototype.setLoadingState=function(t){var n;o(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(n=this._triggerLoadingState)||void 0===n||n.call(this))},t.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";f?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new f(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},t}();function C(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new S({fetch:e,AsyncStorage:n,eventSource:i})}var _,E=(_=function(t,e){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},_(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}_(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),b=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},x=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},O=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},F=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return E(e,t),e}(Error),A=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new F;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=b(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=b(O([],x(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=O(O([],x(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var w=C({AsyncStorage:t,eventSource:"undefined"!=typeof window?A:null});"undefined"!=typeof window&&(window.flagsmith=w);var I=function(){return C({AsyncStorage:t,eventSource:"undefined"!=typeof window?A:null})};export{h as FlagSource,I as createFlagsmithInstance,w as default};
1
+ var t={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},e=function(){return e=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},e.apply(this,arguments)};function n(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{s(i.next(t))}catch(t){o(t)}}function l(t){try{s(i.throw(t))}catch(t){o(t)}}function s(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,l)}s((i=i.apply(t,e||[])).next())}))}function i(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function a(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var o=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function r(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!o(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function l(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function s(t){return!!t&&"object"==typeof t&&void 0!==t.value}function u(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))}function c(t){return e(e({},t),{identity:t.identity?e(e({},t.identity),{traits:u(t.identity.traits||{})}):void 0})}function v(t){return t.endsWith("/")?t:t+"/"}var h,d,g;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(h||(h={})),function(t){t.FLAG_EVALUATION="flag_evaluation",t.CUSTOM_EVENT="custom_event"}(d||(d={}));var f,p=null,y="FLAGSMITH_EVENT",m="https://edge.api.flagsmith.com/api/v1/",S=function(){function t(t){var a=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var t=a,n=t.api,i=t.evaluationContext;a.log("Get Flags"),a.isLoading=!0,a.loadingState.isFetching||a.setLoadingState(e(e({},a.loadingState),{isFetching:!0}));var o="".concat(a.getContext().identity),s=function(t){var n,i,s,u;if(t&&o==="".concat(a.getContext().identity)){var c=t.flags,v=t.traits,d=t.identifier;a.isLoading=!1;var g={},f={};v=v||[],(c=c||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),v.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),a.oldFlags=e({},a.flags);var p=r(a.oldFlags,g),y=r(null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.traits,f);if((d||Object.keys(f).length)&&(a.evaluationContext.identity=e(e({},a.evaluationContext.identity),{traits:f}),d&&(a.evaluationContext.identity.identifier=d,a.identity=d)),a.flags=g,a.updateStorage(),a._onChange(a.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},a._loadedState(null,h.SERVER)),a.datadogRum)try{if(a.datadogRum.trackTraits){var m={};Object.keys((null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.traits)||{}).map((function(t){m["flagsmith_trait_"+t]=a.getTrait(t)}));var S=e(e(e({},a.datadogRum.client.getUser()),{id:a.datadogRum.client.getUser().id||(null===(s=a.evaluationContext.identity)||void 0===s?void 0:s.identifier)}),m);a.log("Setting Datadog user",S),a.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(a.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(a.flags).map((function(t){l(C,"flagsmith_value_"+t,a.getValue(t,{skipAnalytics:!0})),l(C,"flagsmith_enabled_"+t,a.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(u=a.evaluationContext.identity)||void 0===u?void 0:u.traits)||{}).map((function(t){l(C,"flagsmith_trait_"+t,a.getTrait(t))})),a.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),a.log("Sending date traits to dynatrace",C.date),a.log("Sending shortString traits to dynatrace",C.shortString),a.log("Sending javaDouble to dynatrace",C.javaDouble),a.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return i.identity?Promise.all([i.identity.traits&&Object.keys(i.identity.traits).length||!i.identity.identifier?a.getJSON(n+"identities/","POST",JSON.stringify({identifier:i.identity.identifier,transient:i.identity.transient,traits:Object.entries(i.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(a.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):a.getJSON(n+"identities/?identifier="+encodeURIComponent(i.identity.identifier)+(i.identity.transient?"&transient=true":""))]).then((function(t){return a.evaluationContext.identity=e(e({},a.evaluationContext.identity),{traits:{}}),s(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):a.getJSON(n+"flags/").then((function(t){return s({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=a.api;if(a.evaluationEvent&&a.evaluationContext.environment&&a.evaluationEvent[a.evaluationContext.environment.apiKey])return a.evaluationEvent&&0!==Object.getOwnPropertyNames(a.evaluationEvent).length&&0!==Object.getOwnPropertyNames(a.evaluationEvent[a.evaluationContext.environment.apiKey]).length?a.getJSON(t+"analytics/flags/","POST",JSON.stringify(a.evaluationEvent[a.evaluationContext.environment.apiKey])).then((function(t){if(a.evaluationContext.environment){var n=a.getState();a.evaluationEvent||(a.evaluationEvent={}),a.evaluationEvent[a.evaluationContext.environment.apiKey]={},a.setState(e(e({},n),{evaluationEvent:a.evaluationEvent})),a.updateEventStorage()}})).catch((function(t){a.log("Exception fetching evaluationEvent",t)})):void 0},this.flushPipelineAnalytics=function(){return n(a,void 0,void 0,(function(){var t,n,a,o,r,l,s;return i(this,(function(i){switch(i.label){case 0:if(t=this.evaluationAnalyticsUrl&&this.evaluationContext.environment,n=this.pipelineEvents.length>0&&(!this.isPipelineFlushing||0===this.pipelineFlushInterval),!t||!n)return[2];a=this.evaluationContext.environment.apiKey,this.isPipelineFlushing=!0,o=this.pipelineEvents.slice(0,this.evaluationAnalyticsMaxBuffer),this.pipelineEvents=this.pipelineEvents.slice(this.evaluationAnalyticsMaxBuffer),this.pipelineRecordedKeys.clear(),r={events:o,environment_key:a},i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,g(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(r),headers:e({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":a},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat("11.0.0-internal.7")})})];case 2:if(!(l=i.sent()).status||l.status<200||l.status>=300)throw new Error("Pipeline analytics: unexpected status ".concat(l.status));return this.log("Pipeline analytics: flush successful"),[3,5];case 3:return s=i.sent(),this.pipelineEvents=o.concat(this.pipelineEvents),this.log("Pipeline analytics: flush failed, events re-queued",s),[3,5];case 4:return this.isPipelineFlushing=!1,[7];case 5:return[2]}}))}))},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:h.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.evaluationAnalyticsUrl=null,this.evaluationAnalyticsMaxBuffer=1e3,this.pipelineEvents=[],this.pipelineAnalyticsInterval=null,this.isPipelineFlushing=!1,this.pipelineRecordedKeys=new Map,this.getValue=function(t,e,n){var i=a.flags&&a.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(i&&(o=i.value),(null==e?void 0:e.skipAnalytics)||n||a.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(a.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,n;return(null===(e=a.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=a.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=a.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var n,i,o=c(t);return a.evaluationContext=e(e({},o),{environment:o.environment||a.evaluationContext.environment}),a.identity=null===(i=null===(n=a.getContext())||void 0===n?void 0:n.identity)||void 0===i?void 0:i.identifier,a.initialised?a.getFlags():Promise.resolve()},this.getContext=function(){return a.evaluationContext},this.updateContext=function(t){return a.setContext(e(e({},a.getContext()),t))},this.setTrait=function(t,n){var i;if(a.api)return a.setContext(e(e({},a.evaluationContext),{identity:e(e({},a.evaluationContext.identity),{traits:e(e({},null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.traits),u(Object.fromEntries([[t,n]])))})}))},this.setTraits=function(t){var n;if(a.api)return a.setContext(e(e({},a.evaluationContext),{identity:e(e({},a.evaluationContext.identity),{traits:e(e({},null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,i,o="object"==typeof e,r=a.flags&&a.flags[t.toLowerCase().replace(/ /g,"_")],l=!1;if(!r&&o&&void 0!==e.fallback?l=null==e?void 0:e.fallback:r&&r.enabled&&(l=!0),(o&&!e.skipAnalytics||!e)&&a.evaluateFlag(t,"ENABLED"),a.sentryClient)try{null===(i=null===(n=a.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===i||i.call(n,t,l)}catch(t){console.error(t)}return l},this.getStorageKey=function(){var t,e;return(null===(t=a.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=a.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var i,o,r,l=a.headers,s={method:e||"GET",body:n,cache:"no-cache",headers:{}};a.evaluationContext.environment&&(s.headers["X-Environment-Key"]=a.evaluationContext.environment.apiKey),e&&"GET"!==e&&(s.headers["Content-Type"]="application/json; charset=utf-8"),(null===(i=a.applicationMetadata)||void 0===i?void 0:i.name)&&(s.headers["Flagsmith-Application-Name"]=a.applicationMetadata.name),(null===(o=a.applicationMetadata)||void 0===o?void 0:o.version)&&(s.headers["Flagsmith-Application-Version"]=a.applicationMetadata.version),s.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("11.0.0-internal.7"),l&&Object.assign(s.headers,l),g||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=a.evaluationContext.identity)||void 0===r?void 0:r.identifier);return g(t,s).then((function(n){var i,o,r="".concat(null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.identifier);if(u===r){var l=null===(o=n.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(l)try{var s=parseFloat(l);if(isNaN(s))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");a.timestamp=s}catch(t){a.log(t,"Failed to parse x-flagsmith-document-updated-at",l)}return a.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}a.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(a.datadogRum&&(a.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?a.datadogRum.client.addFeatureFlagEvaluation("flagsmith_value_"+t,a.getValue(t,{},!0)):a.datadogRum.client.addFeatureFlagEvaluation("flagsmith_enabled_"+t,a.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),a.enableAnalytics){if(!a.evaluationEvent||!a.evaluationContext.environment)return;a.evaluationEvent[a.evaluationContext.environment.apiKey]||(a.evaluationEvent[a.evaluationContext.environment.apiKey]={}),void 0===a.evaluationEvent[a.evaluationContext.environment.apiKey][t]&&(a.evaluationEvent[a.evaluationContext.environment.apiKey][t]=0),a.evaluationEvent[a.evaluationContext.environment.apiKey][t]+=1}a.evaluationAnalyticsUrl&&a.recordPipelineEvent(t),a.updateEventStorage()},this.pipelineFlushInterval=1e4,this.trackEvent=function(t,e){if(a.evaluationAnalyticsUrl&&t){var n=a.buildAnalyticEvent(d.CUSTOM_EVENT,t,{extraMetadata:e});a.pipelineEvents.push(n),(0===a.pipelineFlushInterval||a.pipelineEvents.length>=a.evaluationAnalyticsMaxBuffer)&&a.flushPipelineAnalytics()}},this._onChange=function(t,e,n){var i,o;a.setLoadingState(n),null===(i=a.onChange)||void 0===i||i.call(a,t,e,a.loadingState),null===(o=a._trigger)||void 0===o||o.call(a)},g=t.fetch?t.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!t.browserlessStorage,this.applicationMetadata=t.applicationMetadata,this.log("Constructing flagsmith instance "+t),t.eventSource&&(f=t.eventSource),t.AsyncStorage&&(p=t.AsyncStorage)}return t.prototype.init=function(t){var a,o,l,s;return n(this,void 0,void 0,(function(){var u,d,f,S,C,_,E,b,x,O,F,A,w,I,L,j,P,k,T,N,U,K,R,M,D,G,J,V,B,H,q,W,X,Y,z,Q,Z=this;return i(this,(function($){switch($.label){case 0:u=c(t.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),d=t.AsyncStorage,f=t._trigger,S=t._triggerLoadingState,C=t.angularHttpClient,_=t.api,E=void 0===_?m:_,b=t.applicationMetadata,x=t.cacheFlags,O=t.cacheOptions,F=t.datadogRum,A=t.defaultFlags,w=t.enableAnalytics,I=t.enableDynatrace,L=t.enableLogs,j=t.environmentID,P=t.evaluationAnalyticsConfig,k=t.eventSourceUrl,T=void 0===k?"https://realtime.flagsmith.com/":k,N=t.fetch,U=t.headers,K=t.identity,R=t.onChange,M=t.onError,D=t.preventFetch,G=t.realtime,J=t.sentryClient,V=t.state,B=t.traits,u.environment=j?{apiKey:j}:u.environment,!u.environment||!u.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(u.identity=K||B?{identifier:K,traits:B?Object.fromEntries(Object.entries(B).map((function(t){return[t[0],{value:t[1]}]}))):{}}:u.identity,this.evaluationContext=u,this.api=v(E),this.headers=U,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=f||this._trigger,this._triggerLoadingState=S||this._triggerLoadingState,this.onError=function(t){Z.setLoadingState(e(e({},Z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==M||M(t)},this.enableLogs=L||!1,this.cacheOptions=O?{skipAPI:!!O.skipAPI,ttl:O.ttl||0,storageKey:O.storageKey,loadStale:!!O.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),N&&(g=N),this.enableAnalytics=w||!1,this.flags=Object.assign({},A)||{},this.datadogRum=F||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==p&&!!x,this.applicationMetadata=b,y="FLAGSMITH_EVENT_"+u.environment.apiKey,d&&(p=d),G&&"undefined"!=typeof window&&this.setupRealtime(T,u.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:h.DEFAULT_FLAGS})),this.setState(V),this.log("Initialising with properties",t,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),C&&(g=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},l=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(l(t,!t.status||t.status>=200&&t.status<300))},s=function(t){return n(l(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,s);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,s);default:return s({status:405,message:"Unsupported method: ".concat(a)})}}))}}(C)),p&&this.canUseStorage&&p.getItem(y).then((function(t){try{Z.evaluationEvent=JSON.parse(t)||{}}catch(t){Z.evaluationEvent={}}Z.analyticsInterval=setInterval(Z.analyticsFlags,Z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),p&&this.canUseStorage&&p.getItem(y,(function(t,n){if(n&&Z.evaluationContext.environment){var i=JSON.parse(n);if(i[Z.evaluationContext.environment.apiKey]){var a=Z.getState();Z.log("Retrieved events from cache",n),Z.setState(e(e({},a),{evaluationEvent:i[Z.evaluationContext.environment.apiKey]}))}}}))),P?this.initPipelineAnalytics(P):this.stopPipelineAnalytics(),!x)return[3,9];if(!p||!this.canUseStorage)return[3,8];q=function(t,a){return n(Z,void 0,void 0,(function(){var t,n,o,l,s,u,v,d,g,f,p,y,m,S,C,_,E,b,x,O=this;return i(this,(function(i){switch(i.label){case 0:if(!a)return[3,7];t=null,n=null,i.label=1;case 1:return i.trys.push([1,5,,6]),o=JSON.parse(a),l=!1,s=!1,o&&o.api===this.api&&(null===(f=null===(g=o.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(u=!0,this.evaluationContext.identity&&(null===(m=null===(y=o.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=o.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),u=!1),this.cacheOptions.ttl&&(!o.ts||(new Date).valueOf()-o.ts>this.cacheOptions.ttl)&&(o.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),u=!1):o.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),s=!0,u=!0)),u&&(l=!0,t=r(this.flags,o.flags),this.setState(e(e({},o),{evaluationContext:c(e(e({},o.evaluationContext),{identity:(null===(_=o.evaluationContext)||void 0===_?void 0:_.identity)?e(e({},null===(E=o.evaluationContext)||void 0===E?void 0:E.identity),{traits:e({},B||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),l?(v=!D&&(!this.cacheOptions.skipAPI||s),this._onChange(null,{isFromServer:!1,flagsChanged:t,traitsChanged:n},this._loadedState(null,h.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&l&&!s&&this.log("Skipping API, using cache"),v&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:i.sent(),i.label=4;case 4:return[3,6];case 5:throw d=i.sent(),this.log("Exception fetching cached logs",d),d;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(b=this.evaluationContext.identity)||void 0===b?void 0:b.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(H);this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,h.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},$.label=2;case 2:return $.trys.push([2,7,,8]),p.getItemSync?(W=p.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,p.getItem(this.getStorageKey())];case 4:W=$.sent(),$.label=5;case 5:return[4,q(null,W)];case 6:return $.sent(),[3,8];case 7:if(X=$.sent(),!this.flags||0===Object.keys(this.flags).length)throw X;return Q=X instanceof Error?X:new Error("".concat(X)),null===(a=this.onError)||void 0===a||a.call(this,Q),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(A)this._onChange(null,{isFromServer:!1,flagsChanged:r({},A),traitsChanged:r({},null===(o=u.identity)||void 0===o?void 0:o.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else if(this.flags&&(Y=null,0===Object.keys(this.flags).length&&(Y=H),this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(l=u.identity)||void 0===l?void 0:l.traits)},this._loadedState(Y,h.DEFAULT_FLAGS)),Y))throw new Error(Y);$.label=12;case 12:return[3,14];case 13:throw z=$.sent(),this.log("Error during initialisation ",z),Q=z instanceof Error?z:new Error("".concat(z)),null===(s=this.onError)||void 0===s||s.call(this,Q),z;case 14:return[2]}}))}))},t.prototype.getAllFlags=function(){return this.flags},t.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},t.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},t.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||m,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this))},t.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},t.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},t.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},t.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,a(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},t.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),p.setItem(this.getStorageKey(),t)}},t.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);p.setItem(y,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},t.prototype.initPipelineAnalytics=function(t){var e,n,i,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=v(t.analyticsServerUrl),this.evaluationAnalyticsMaxBuffer=null!==(e=t.maxBuffer)&&void 0!==e?e:1e3,this.pipelineFlushInterval=null!==(n=t.flushInterval)&&void 0!==n?n:1e4,this.pipelineEvents=[],this.pipelineFlushInterval>0&&(this.pipelineAnalyticsInterval=setInterval(this.flushPipelineAnalytics,this.pipelineFlushInterval),null===(a=null===(i=this.pipelineAnalyticsInterval)||void 0===i?void 0:i.unref)||void 0===a||a.call(i))},t.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},t.prototype.currentTraitsSnapshot=function(){var t;return(null===(t=this.evaluationContext.identity)||void 0===t?void 0:t.traits)?e({},this.evaluationContext.identity.traits):null},t.prototype.getPageUrl=function(){return"undefined"!=typeof window&&window.location?window.location.href:null},t.prototype.getEventMetadata=function(t){var n=this.getPageUrl();return e(e(e({},t||{}),n?{page_url:n}:{}),{sdk_version:"11.0.0-internal.7"})},t.prototype.buildAnalyticEvent=function(t,e,n){var i,a,o,r,l;return{event_id:e,event_type:t,evaluated_at:null!==(i=null==n?void 0:n.timestamp)&&void 0!==i?i:Date.now(),identity_identifier:null!==(o=null===(a=this.evaluationContext.identity)||void 0===a?void 0:a.identifier)&&void 0!==o?o:null,enabled:null!==(r=null==n?void 0:n.enabled)&&void 0!==r?r:null,value:null!==(l=null==n?void 0:n.value)&&void 0!==l?l:null,traits:this.currentTraitsSnapshot(),metadata:this.getEventMetadata(null==n?void 0:n.extraMetadata)}},t.prototype.recordPipelineEvent=function(t){var e,n,i,a,o=t.toLowerCase().replace(/ /g,"_"),r=this.flags&&this.flags[o],l="".concat(null!==(n=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==n?n:"none","|").concat(null!==(i=null==r?void 0:r.enabled)&&void 0!==i&&i,"|").concat(null!==(a=null==r?void 0:r.value)&&void 0!==a?a:"null");if(this.pipelineRecordedKeys.get(o)!==l){this.pipelineRecordedKeys.set(o,l);var s=this.buildAnalyticEvent(d.FLAG_EVALUATION,o,{enabled:r?r.enabled:null,value:r?r.value:null,extraMetadata:r?{id:r.id}:void 0});this.pipelineEvents.push(s),(0===this.pipelineFlushInterval||this.pipelineEvents.length>=this.evaluationAnalyticsMaxBuffer)&&this.flushPipelineAnalytics()}},t.prototype.setLoadingState=function(t){var n;o(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(n=this._triggerLoadingState)||void 0===n||n.call(this))},t.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";f?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new f(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},t}();function C(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new S({fetch:e,AsyncStorage:n,eventSource:i})}var _,E=(_=function(t,e){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},_(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}_(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),b=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},x=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},O=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},F=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return E(e,t),e}(Error),A=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new F;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=b(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=b(O([],x(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=O(O([],x(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var w=C({AsyncStorage:t,eventSource:"undefined"!=typeof window?A:null});"undefined"!=typeof window&&(window.flagsmith=w);var I=function(){return C({AsyncStorage:t,eventSource:"undefined"!=typeof window?A:null})};export{h as FlagSource,I as createFlagsmithInstance,w as default};
2
2
  //# sourceMappingURL=isomorphic.mjs.map
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["next-middleware"]={})}(this,(function(t){"use strict";var e=function(){return e=Object.assign||function(t){for(var e,i=1,n=arguments.length;i<n;i++)for(var a in e=arguments[i])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},e.apply(this,arguments)};function i(t,e,i,n){return new(i||(i=Promise))((function(a,l){function o(t){try{r(n.next(t))}catch(t){l(t)}}function s(t){try{r(n.throw(t))}catch(t){l(t)}}function r(t){var e;t.done?a(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,s)}r((n=n.apply(t,e||[])).next())}))}function n(t,e){var i,n,a,l,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return l={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function s(l){return function(s){return function(l){if(i)throw new TypeError("Generator is already executing.");for(;o;)try{if(i=1,n&&(a=2&l[0]?n.return:l[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,l[1])).done)return a;switch(n=0,a&&(l=[2&l[0],a.value]),l[0]){case 0:case 1:a=l;break;case 4:return o.label++,{value:l[1],done:!1};case 5:o.label++,n=l[1],l=[0];continue;case 7:l=o.ops.pop(),o.trys.pop();continue;default:if(!(a=o.trys,(a=a.length>0&&a[a.length-1])||6!==l[0]&&2!==l[0])){o=0;continue}if(3===l[0]&&(!a||l[1]>a[0]&&l[1]<a[3])){o.label=l[1];break}if(6===l[0]&&o.label<a[1]){o.label=a[1],a=l;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(l);break}a[2]&&o.ops.pop(),o.trys.pop();continue}l=e.call(t,o)}catch(t){l=[6,t],n=0}finally{i=a=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}([l,s])}}}function a(t,e,i){if(i||2===arguments.length)for(var n,a=0,l=e.length;a<l;a++)!n&&a in e||(n||(n=Array.prototype.slice.call(e,0,a)),n[a]=e[a]);return t.concat(n||Array.prototype.slice.call(e))}var l=function t(e,i){if(e===i)return!0;if(e&&i&&"object"==typeof e&&"object"==typeof i){if(e.constructor!==i.constructor)return!1;var n,a,l;if(Array.isArray(e)){if((n=e.length)!=i.length)return!1;for(a=n;0!=a--;)if(!t(e[a],i[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===i.source&&e.flags===i.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===i.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===i.toString();if((n=(l=Object.keys(e)).length)!==Object.keys(i).length)return!1;for(a=n;0!=a--;)if(!Object.prototype.hasOwnProperty.call(i,l[a]))return!1;for(a=n;0!=a--;){var o=l[a];if(!t(e[o],i[o]))return!1}return!0}return e!=e&&i!=i};function o(t,e){var i=Object.keys(e||{}).filter((function(i){var n=null==t?void 0:t[i],a=null==e?void 0:e[i];return!l(n,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||i.push(t)})),Object.keys(i).length?i:null}function s(t,e,i){var n="shortString",a=!0;"number"==typeof i&&(n="javaDouble",a=!1),t[n]=t[n]||{},t[n][e]=a?i+"":i}function r(t){return!!t&&"object"==typeof t&&void 0!==t.value}function u(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],i=t[1];return[e,r(i)?i:{value:i}]})))}function c(t){return e(e({},t),{identity:t.identity?e(e({},t.identity),{traits:u(t.identity.traits||{})}):void 0})}function v(t){return t.endsWith("/")?t:t+"/"}var d,h,g,f="11.0.0-internal.6";t.FlagSource=void 0,(d=t.FlagSource||(t.FlagSource={})).NONE="NONE",d.DEFAULT_FLAGS="DEFAULT_FLAGS",d.CACHE="CACHE",d.SERVER="SERVER",function(t){t.FLAG_EVALUATION="flag_evaluation",t.CUSTOM_EVENT="custom_event"}(h||(h={}));var p,y=null,m="FLAGSMITH_EVENT",S=m,C="https://edge.api.flagsmith.com/api/v1/",E="flagsmith_value_",b="flagsmith_enabled_",F="flagsmith_trait_",x=function(){function d(a){var l=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var i=l,n=i.api,a=i.evaluationContext;l.log("Get Flags"),l.isLoading=!0,l.loadingState.isFetching||l.setLoadingState(e(e({},l.loadingState),{isFetching:!0}));var r="".concat(l.getContext().identity),u=function(i){var n,a,u,c;if(i&&r==="".concat(l.getContext().identity)){var v=i.flags,d=i.traits,h=i.identifier;l.isLoading=!1;var g={},f={};d=d||[],(v=v||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),d.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),l.oldFlags=e({},l.flags);var p=o(l.oldFlags,g),y=o(null===(n=l.evaluationContext.identity)||void 0===n?void 0:n.traits,f);if((h||Object.keys(f).length)&&(l.evaluationContext.identity=e(e({},l.evaluationContext.identity),{traits:f}),h&&(l.evaluationContext.identity.identifier=h,l.identity=h)),l.flags=g,l.updateStorage(),l._onChange(l.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},l._loadedState(null,t.FlagSource.SERVER)),l.datadogRum)try{if(l.datadogRum.trackTraits){var m={};Object.keys((null===(a=l.evaluationContext.identity)||void 0===a?void 0:a.traits)||{}).map((function(t){m[F+t]=l.getTrait(t)}));var S=e(e(e({},l.datadogRum.client.getUser()),{id:l.datadogRum.client.getUser().id||(null===(u=l.evaluationContext.identity)||void 0===u?void 0:u.identifier)}),m);l.log("Setting Datadog user",S),l.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(l.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(l.flags).map((function(t){s(C,E+t,l.getValue(t,{skipAnalytics:!0})),s(C,b+t,l.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=l.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){s(C,F+t,l.getTrait(t))})),l.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),l.log("Sending date traits to dynatrace",C.date),l.log("Sending shortString traits to dynatrace",C.shortString),l.log("Sending javaDouble to dynatrace",C.javaDouble),l.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return a.identity?Promise.all([a.identity.traits&&Object.keys(a.identity.traits).length||!a.identity.identifier?l.getJSON(n+"identities/","POST",JSON.stringify({identifier:a.identity.identifier,transient:a.identity.transient,traits:Object.entries(a.identity.traits).map((function(t){var e=t[0],i=t[1];return{trait_key:e,trait_value:null==i?void 0:i.value,transient:null==i?void 0:i.transient}})).filter((function(t){return void 0!==t.trait_value||(l.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):l.getJSON(n+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(t){return l.evaluationContext.identity=e(e({},l.evaluationContext.identity),{traits:{}}),u(null==t?void 0:t[0])})).catch((function(t){var e=t.message,i=new Error(e);return Promise.reject(i)})):l.getJSON(n+"flags/").then((function(t){return u({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=l.api;if(l.evaluationEvent&&l.evaluationContext.environment&&l.evaluationEvent[l.evaluationContext.environment.apiKey])return l.evaluationEvent&&0!==Object.getOwnPropertyNames(l.evaluationEvent).length&&0!==Object.getOwnPropertyNames(l.evaluationEvent[l.evaluationContext.environment.apiKey]).length?l.getJSON(t+"analytics/flags/","POST",JSON.stringify(l.evaluationEvent[l.evaluationContext.environment.apiKey])).then((function(t){if(l.evaluationContext.environment){var i=l.getState();l.evaluationEvent||(l.evaluationEvent={}),l.evaluationEvent[l.evaluationContext.environment.apiKey]={},l.setState(e(e({},i),{evaluationEvent:l.evaluationEvent})),l.updateEventStorage()}})).catch((function(t){l.log("Exception fetching evaluationEvent",t)})):void 0},this.flushPipelineAnalytics=function(){return i(l,void 0,void 0,(function(){var t,i,a,l,o,s,r;return n(this,(function(n){switch(n.label){case 0:if(t=this.evaluationAnalyticsUrl&&this.evaluationContext.environment,i=this.pipelineEvents.length>0&&(!this.isPipelineFlushing||0===this.pipelineFlushInterval),!t||!i)return[2];a=this.evaluationContext.environment.apiKey,this.isPipelineFlushing=!0,l=this.pipelineEvents.slice(0,this.evaluationAnalyticsMaxBuffer),this.pipelineEvents=this.pipelineEvents.slice(this.evaluationAnalyticsMaxBuffer),this.pipelineRecordedKeys.clear(),o={events:l,environment_key:a},n.label=1;case 1:return n.trys.push([1,3,4,5]),[4,g(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(o),headers:e({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":a},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat(f)})})];case 2:if(!(s=n.sent()).status||s.status<200||s.status>=300)throw new Error("Pipeline analytics: unexpected status ".concat(s.status));return this.log("Pipeline analytics: flush successful"),[3,5];case 3:return r=n.sent(),this.pipelineEvents=l.concat(this.pipelineEvents),this.log("Pipeline analytics: flush failed, events re-queued",r),[3,5];case 4:return this.isPipelineFlushing=!1,[7];case 5:return[2]}}))}))},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:t.FlagSource.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.evaluationAnalyticsUrl=null,this.evaluationAnalyticsMaxBuffer=1e3,this.pipelineEvents=[],this.pipelineAnalyticsInterval=null,this.isPipelineFlushing=!1,this.pipelineRecordedKeys=new Map,this.getValue=function(t,e,i){var n=l.flags&&l.flags[t.toLowerCase().replace(/ /g,"_")],a=null;if(n&&(a=n.value),(null==e?void 0:e.skipAnalytics)||i||l.evaluateFlag(t,"VALUE"),null===a&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===a?(l.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(a)}catch(t){return e.fallback}return a},this.getTrait=function(t){var e,i;return(null===(e=l.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(i=l.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===i?void 0:i.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=l.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],i=t[1];return[e,null==i?void 0:i.value]})))},this.setContext=function(t){var i,n,a=c(t);return l.evaluationContext=e(e({},a),{environment:a.environment||l.evaluationContext.environment}),l.identity=null===(n=null===(i=l.getContext())||void 0===i?void 0:i.identity)||void 0===n?void 0:n.identifier,l.initialised?l.getFlags():Promise.resolve()},this.getContext=function(){return l.evaluationContext},this.updateContext=function(t){return l.setContext(e(e({},l.getContext()),t))},this.setTrait=function(t,i){var n;if(l.api)return l.setContext(e(e({},l.evaluationContext),{identity:e(e({},l.evaluationContext.identity),{traits:e(e({},null===(n=l.evaluationContext.identity)||void 0===n?void 0:n.traits),u(Object.fromEntries([[t,i]])))})}))},this.setTraits=function(t){var i;if(l.api)return l.setContext(e(e({},l.evaluationContext),{identity:e(e({},l.evaluationContext.identity),{traits:e(e({},null===(i=l.evaluationContext.identity)||void 0===i?void 0:i.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],i=t[1];return[e,r(i)?i:{value:i}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var i,n,a="object"==typeof e,o=l.flags&&l.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!o&&a&&void 0!==e.fallback?s=null==e?void 0:e.fallback:o&&o.enabled&&(s=!0),(a&&!e.skipAnalytics||!e)&&l.evaluateFlag(t,"ENABLED"),l.sentryClient)try{null===(n=null===(i=l.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===i?void 0:i.addFeatureFlag)||void 0===n||n.call(i,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=l.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=l.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,i){var n,a,o,s=l.headers,r={method:e||"GET",body:i,cache:"no-cache",headers:{}};l.evaluationContext.environment&&(r.headers["X-Environment-Key"]=l.evaluationContext.environment.apiKey),e&&"GET"!==e&&(r.headers["Content-Type"]="application/json; charset=utf-8"),(null===(n=l.applicationMetadata)||void 0===n?void 0:n.name)&&(r.headers["Flagsmith-Application-Name"]=l.applicationMetadata.name),(null===(a=l.applicationMetadata)||void 0===a?void 0:a.version)&&(r.headers["Flagsmith-Application-Version"]=l.applicationMetadata.version),r.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat(f),s&&Object.assign(r.headers,s),g||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(o=l.evaluationContext.identity)||void 0===o?void 0:o.identifier);return g(t,r).then((function(i){var n,a,o="".concat(null===(n=l.evaluationContext.identity)||void 0===n?void 0:n.identifier);if(u===o){var s=null===(a=i.headers)||void 0===a?void 0:a.get("x-flagsmith-document-updated-at");if(s)try{var r=parseFloat(s);if(isNaN(r))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");l.timestamp=r}catch(t){l.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return l.log("Fetch response: "+i.status+" "+(e||"GET")+0+t),i.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&i.status&&(e="API Response: ".concat(i.status)),i.status&&i.status>=200&&i.status<300?e:Promise.reject(new Error(e))}))}l.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(o))}))},this.evaluateFlag=function(t,e){if(l.datadogRum&&(l.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?l.datadogRum.client.addFeatureFlagEvaluation(E+t,l.getValue(t,{},!0)):l.datadogRum.client.addFeatureFlagEvaluation(b+t,l.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),l.enableAnalytics){if(!l.evaluationEvent||!l.evaluationContext.environment)return;l.evaluationEvent[l.evaluationContext.environment.apiKey]||(l.evaluationEvent[l.evaluationContext.environment.apiKey]={}),void 0===l.evaluationEvent[l.evaluationContext.environment.apiKey][t]&&(l.evaluationEvent[l.evaluationContext.environment.apiKey][t]=0),l.evaluationEvent[l.evaluationContext.environment.apiKey][t]+=1}l.evaluationAnalyticsUrl&&l.recordPipelineEvent(t),l.updateEventStorage()},this.pipelineFlushInterval=1e4,this.trackEvent=function(t,e){if(l.evaluationAnalyticsUrl&&t){var i=l.buildAnalyticEvent(h.CUSTOM_EVENT,t,{extraMetadata:e});l.pipelineEvents.push(i),(0===l.pipelineFlushInterval||l.pipelineEvents.length>=l.evaluationAnalyticsMaxBuffer)&&l.flushPipelineAnalytics()}},this._onChange=function(t,e,i){var n,a;l.setLoadingState(i),null===(n=l.onChange)||void 0===n||n.call(l,t,e,l.loadingState),null===(a=l._trigger)||void 0===a||a.call(l)},g=a.fetch?a.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!a.browserlessStorage,this.applicationMetadata=a.applicationMetadata,this.log("Constructing flagsmith instance "+a),a.eventSource&&(p=a.eventSource),a.AsyncStorage&&(y=a.AsyncStorage)}return d.prototype.init=function(a){var l,s,r,u;return i(this,void 0,void 0,(function(){var d,h,f,p,m,E,b,F,x,O,A,_,w,I,j,L,P,k,T,U,K,N,R,M,D,G,J,V,B,H,q,W,X,Y,z,Q,Z=this;return n(this,(function($){switch($.label){case 0:d=c(a.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),h=a.AsyncStorage,f=a._trigger,p=a._triggerLoadingState,m=a.angularHttpClient,E=a.api,b=void 0===E?C:E,F=a.applicationMetadata,x=a.cacheFlags,O=a.cacheOptions,A=a.datadogRum,_=a.defaultFlags,w=a.enableAnalytics,I=a.enableDynatrace,j=a.enableLogs,L=a.environmentID,P=a.evaluationAnalyticsConfig,k=a.eventSourceUrl,T=void 0===k?"https://realtime.flagsmith.com/":k,U=a.fetch,K=a.headers,N=a.identity,R=a.onChange,M=a.onError,D=a.preventFetch,G=a.realtime,J=a.sentryClient,V=a.state,B=a.traits,d.environment=L?{apiKey:L}:d.environment,!d.environment||!d.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(d.identity=N||B?{identifier:N,traits:B?Object.fromEntries(Object.entries(B).map((function(t){return[t[0],{value:t[1]}]}))):{}}:d.identity,this.evaluationContext=d,this.api=v(b),this.headers=K,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=f||this._trigger,this._triggerLoadingState=p||this._triggerLoadingState,this.onError=function(t){Z.setLoadingState(e(e({},Z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==M||M(t)},this.enableLogs=j||!1,this.cacheOptions=O?{skipAPI:!!O.skipAPI,ttl:O.ttl||0,storageKey:O.storageKey,loadStale:!!O.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),U&&(g=U),this.enableAnalytics=w||!1,this.flags=Object.assign({},_)||{},this.datadogRum=A||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==y&&!!x,this.applicationMetadata=F,S="FLAGSMITH_EVENT_"+d.environment.apiKey,h&&(y=h),G&&"undefined"!=typeof window&&this.setupRealtime(T,d.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(V),this.log("Initialising with properties",a,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),m&&(g=function(t){return function(e,i){var n=i.headers,a=i.method,l=i.body,o={headers:n,observe:"response",responseType:"text"},s=function(t,e){var i=t.status,n=t.headers,a=t.body,l=t.error,o=t.message;return{status:null!=i?i:e?200:500,ok:e,headers:{get:function(t){var e,i;return null!==(i=null===(e=null==n?void 0:n.get)||void 0===e?void 0:e.call(n,t))&&void 0!==i?i:null}},text:function(){var t,e,i=null!==(e=null!==(t=null!=a?a:l)&&void 0!==t?t:o)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof i?JSON.stringify(i):i)}}};return new Promise((function(i){var n=function(t){return i(s(t,!t.status||t.status>=200&&t.status<300))},r=function(t){return i(s(t,!1))};switch(a){case"GET":return t.get(e,o).subscribe(n,r);case"POST":case"PUT":return t.post(e,null!=l?l:"",o).subscribe(n,r);default:return r({status:405,message:"Unsupported method: ".concat(a)})}}))}}(m)),y&&this.canUseStorage&&y.getItem(S).then((function(t){try{Z.evaluationEvent=JSON.parse(t)||{}}catch(t){Z.evaluationEvent={}}Z.analyticsInterval=setInterval(Z.analyticsFlags,Z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),y&&this.canUseStorage&&y.getItem(S,(function(t,i){if(i&&Z.evaluationContext.environment){var n=JSON.parse(i);if(n[Z.evaluationContext.environment.apiKey]){var a=Z.getState();Z.log("Retrieved events from cache",i),Z.setState(e(e({},a),{evaluationEvent:n[Z.evaluationContext.environment.apiKey]}))}}}))),P?this.initPipelineAnalytics(P):this.stopPipelineAnalytics(),!x)return[3,9];if(!y||!this.canUseStorage)return[3,8];q=function(a,l){return i(Z,void 0,void 0,(function(){var i,a,s,r,u,v,d,h,g,f,p,y,m,S,C,E,b,F,x,O=this;return n(this,(function(n){switch(n.label){case 0:if(!l)return[3,7];i=null,a=null,n.label=1;case 1:return n.trys.push([1,5,,6]),s=JSON.parse(l),r=!1,u=!1,s&&s.api===this.api&&(null===(f=null===(g=s.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(v=!0,this.evaluationContext.identity&&(null===(m=null===(y=s.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=s.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),v=!1),this.cacheOptions.ttl&&(!s.ts||(new Date).valueOf()-s.ts>this.cacheOptions.ttl)&&(s.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+s.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-s.ts)+"ms"),v=!1):s.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+s.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-s.ts)+"ms"),u=!0,v=!0)),v&&(r=!0,i=o(this.flags,s.flags),this.setState(e(e({},s),{evaluationContext:c(e(e({},s.evaluationContext),{identity:(null===(E=s.evaluationContext)||void 0===E?void 0:E.identity)?e(e({},null===(b=s.evaluationContext)||void 0===b?void 0:b.identity),{traits:e({},B||{})}):void 0}))})),this.log("Retrieved flags from cache",s))),r?(d=!D&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:i,traitsChanged:a},this._loadedState(null,t.FlagSource.CACHE,d)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&r&&!u&&this.log("Skipping API, using cache"),d&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:n.sent(),n.label=4;case 4:return[3,6];case 5:throw h=n.sent(),this.log("Exception fetching cached logs",h),h;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return n.sent(),[3,10];case 9:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:o({},this.flags),traitsChanged:o({},null===(F=this.evaluationContext.identity)||void 0===F?void 0:F.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(H);this._onChange(null,{isFromServer:!1,flagsChanged:o({},this.flags),traitsChanged:o({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS))}n.label=10;case 10:return[2]}}))}))},$.label=2;case 2:return $.trys.push([2,7,,8]),y.getItemSync?(W=y.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,y.getItem(this.getStorageKey())];case 4:W=$.sent(),$.label=5;case 5:return[4,q(null,W)];case 6:return $.sent(),[3,8];case 7:if(X=$.sent(),!this.flags||0===Object.keys(this.flags).length)throw X;return Q=X instanceof Error?X:new Error("".concat(X)),null===(l=this.onError)||void 0===l||l.call(this,Q),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:o({},_),traitsChanged:o({},null===(s=d.identity)||void 0===s?void 0:s.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else if(this.flags&&(Y=null,0===Object.keys(this.flags).length&&(Y=H),this._onChange(null,{isFromServer:!1,flagsChanged:o({},this.flags),traitsChanged:o({},null===(r=d.identity)||void 0===r?void 0:r.traits)},this._loadedState(Y,t.FlagSource.DEFAULT_FLAGS)),Y))throw new Error(Y);$.label=12;case 12:return[3,14];case 13:throw z=$.sent(),this.log("Error during initialisation ",z),Q=z instanceof Error?z:new Error("".concat(z)),null===(u=this.onError)||void 0===u||u.call(this,Q),z;case 14:return[2]}}))}))},d.prototype.getAllFlags=function(){return this.flags},d.prototype.identify=function(t,e,i){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:i,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],i=t[1];return[e,r(i)?i:{value:i}]})))),this.initialised?this.getFlags():Promise.resolve()},d.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},d.prototype.setState=function(t){var e,i;t&&(this.initialised=!0,this.api=t.api||this.api||C,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(i=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===i?void 0:i.identifier,this.log("setState called",this))},d.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},d.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},d.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},d.prototype._loadedState=function(t,e,i){return void 0===t&&(t=null),void 0===i&&(i=!1),{error:t,isFetching:i,isLoading:!1,source:e}},d.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,a(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},d.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),y.setItem(this.getStorageKey(),t)}},d.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);y.setItem(S,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},d.prototype.initPipelineAnalytics=function(t){var e,i,n,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=v(t.analyticsServerUrl),this.evaluationAnalyticsMaxBuffer=null!==(e=t.maxBuffer)&&void 0!==e?e:1e3,this.pipelineFlushInterval=null!==(i=t.flushInterval)&&void 0!==i?i:1e4,this.pipelineEvents=[],this.pipelineFlushInterval>0&&(this.pipelineAnalyticsInterval=setInterval(this.flushPipelineAnalytics,this.pipelineFlushInterval),null===(a=null===(n=this.pipelineAnalyticsInterval)||void 0===n?void 0:n.unref)||void 0===a||a.call(n))},d.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},d.prototype.currentTraitsSnapshot=function(){var t;return(null===(t=this.evaluationContext.identity)||void 0===t?void 0:t.traits)?e({},this.evaluationContext.identity.traits):null},d.prototype.getPageUrl=function(){return"undefined"!=typeof window&&window.location?window.location.href:null},d.prototype.getEventMetadata=function(t){var i=this.getPageUrl();return e(e(e({},t||{}),i?{page_url:i}:{}),{sdk_version:f})},d.prototype.buildAnalyticEvent=function(t,e,i){var n,a,l,o,s;return{event_id:e,event_type:t,evaluated_at:null!==(n=null==i?void 0:i.timestamp)&&void 0!==n?n:Date.now(),identity_identifier:null!==(l=null===(a=this.evaluationContext.identity)||void 0===a?void 0:a.identifier)&&void 0!==l?l:null,enabled:null!==(o=null==i?void 0:i.enabled)&&void 0!==o?o:null,value:null!==(s=null==i?void 0:i.value)&&void 0!==s?s:null,traits:this.currentTraitsSnapshot(),metadata:this.getEventMetadata(null==i?void 0:i.extraMetadata)}},d.prototype.recordPipelineEvent=function(t){var e,i,n,a,l=t.toLowerCase().replace(/ /g,"_"),o=this.flags&&this.flags[l],s="".concat(null!==(i=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==i?i:"none","|").concat(null!==(n=null==o?void 0:o.enabled)&&void 0!==n&&n,"|").concat(null!==(a=null==o?void 0:o.value)&&void 0!==a?a:"null");if(this.pipelineRecordedKeys.get(l)!==s){this.pipelineRecordedKeys.set(l,s);var r=this.buildAnalyticEvent(h.FLAG_EVALUATION,l,{enabled:o?o.enabled:null,value:o?o.value:null,extraMetadata:o?{id:o.id}:void 0});this.pipelineEvents.push(r),(0===this.pipelineFlushInterval||this.pipelineEvents.length>=this.evaluationAnalyticsMaxBuffer)&&this.flushPipelineAnalytics()}},d.prototype.setLoadingState=function(t){var i;l(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(i=this._triggerLoadingState)||void 0===i||i.call(this))},d.prototype.setupRealtime=function(t,e){var i=this,n=t+"sse/environments/"+e+"/stream";p?this.eventSource||(this.log("Creating event source with url "+n),this.eventSource=new p(n),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){i.log("Could not parse sse event",t)}e?!i.timestamp||e>i.timestamp?i.isLoading?i.log("updated_at is new, but flags are loading",t.data,i.timestamp):(i.log("updated_at is new, fetching flags",t.data,i.timestamp),i.getFlags()):i.log("updated_at is outdated, skipping get flags",t.data,i.timestamp):i.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},d}();function O(t){var e=t.fetch,i=t.AsyncStorage,n=t.eventSource;return new x({fetch:e,AsyncStorage:i,eventSource:n})}var A=O({});t.createFlagsmithInstance=function(){return O({})},t.default=A,Object.defineProperty(t,"__esModule",{value:!0})}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["next-middleware"]={})}(this,(function(t){"use strict";var e=function(){return e=Object.assign||function(t){for(var e,i=1,n=arguments.length;i<n;i++)for(var a in e=arguments[i])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},e.apply(this,arguments)};function i(t,e,i,n){return new(i||(i=Promise))((function(a,l){function o(t){try{r(n.next(t))}catch(t){l(t)}}function s(t){try{r(n.throw(t))}catch(t){l(t)}}function r(t){var e;t.done?a(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,s)}r((n=n.apply(t,e||[])).next())}))}function n(t,e){var i,n,a,l,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return l={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function s(l){return function(s){return function(l){if(i)throw new TypeError("Generator is already executing.");for(;o;)try{if(i=1,n&&(a=2&l[0]?n.return:l[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,l[1])).done)return a;switch(n=0,a&&(l=[2&l[0],a.value]),l[0]){case 0:case 1:a=l;break;case 4:return o.label++,{value:l[1],done:!1};case 5:o.label++,n=l[1],l=[0];continue;case 7:l=o.ops.pop(),o.trys.pop();continue;default:if(!(a=o.trys,(a=a.length>0&&a[a.length-1])||6!==l[0]&&2!==l[0])){o=0;continue}if(3===l[0]&&(!a||l[1]>a[0]&&l[1]<a[3])){o.label=l[1];break}if(6===l[0]&&o.label<a[1]){o.label=a[1],a=l;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(l);break}a[2]&&o.ops.pop(),o.trys.pop();continue}l=e.call(t,o)}catch(t){l=[6,t],n=0}finally{i=a=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}([l,s])}}}function a(t,e,i){if(i||2===arguments.length)for(var n,a=0,l=e.length;a<l;a++)!n&&a in e||(n||(n=Array.prototype.slice.call(e,0,a)),n[a]=e[a]);return t.concat(n||Array.prototype.slice.call(e))}var l=function t(e,i){if(e===i)return!0;if(e&&i&&"object"==typeof e&&"object"==typeof i){if(e.constructor!==i.constructor)return!1;var n,a,l;if(Array.isArray(e)){if((n=e.length)!=i.length)return!1;for(a=n;0!=a--;)if(!t(e[a],i[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===i.source&&e.flags===i.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===i.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===i.toString();if((n=(l=Object.keys(e)).length)!==Object.keys(i).length)return!1;for(a=n;0!=a--;)if(!Object.prototype.hasOwnProperty.call(i,l[a]))return!1;for(a=n;0!=a--;){var o=l[a];if(!t(e[o],i[o]))return!1}return!0}return e!=e&&i!=i};function o(t,e){var i=Object.keys(e||{}).filter((function(i){var n=null==t?void 0:t[i],a=null==e?void 0:e[i];return!l(n,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||i.push(t)})),Object.keys(i).length?i:null}function s(t,e,i){var n="shortString",a=!0;"number"==typeof i&&(n="javaDouble",a=!1),t[n]=t[n]||{},t[n][e]=a?i+"":i}function r(t){return!!t&&"object"==typeof t&&void 0!==t.value}function u(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],i=t[1];return[e,r(i)?i:{value:i}]})))}function c(t){return e(e({},t),{identity:t.identity?e(e({},t.identity),{traits:u(t.identity.traits||{})}):void 0})}function v(t){return t.endsWith("/")?t:t+"/"}var d,h,g,f="11.0.0-internal.7";t.FlagSource=void 0,(d=t.FlagSource||(t.FlagSource={})).NONE="NONE",d.DEFAULT_FLAGS="DEFAULT_FLAGS",d.CACHE="CACHE",d.SERVER="SERVER",function(t){t.FLAG_EVALUATION="flag_evaluation",t.CUSTOM_EVENT="custom_event"}(h||(h={}));var p,y=null,m="FLAGSMITH_EVENT",S=m,C="https://edge.api.flagsmith.com/api/v1/",E="flagsmith_value_",b="flagsmith_enabled_",F="flagsmith_trait_",x=function(){function d(a){var l=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var i=l,n=i.api,a=i.evaluationContext;l.log("Get Flags"),l.isLoading=!0,l.loadingState.isFetching||l.setLoadingState(e(e({},l.loadingState),{isFetching:!0}));var r="".concat(l.getContext().identity),u=function(i){var n,a,u,c;if(i&&r==="".concat(l.getContext().identity)){var v=i.flags,d=i.traits,h=i.identifier;l.isLoading=!1;var g={},f={};d=d||[],(v=v||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),d.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),l.oldFlags=e({},l.flags);var p=o(l.oldFlags,g),y=o(null===(n=l.evaluationContext.identity)||void 0===n?void 0:n.traits,f);if((h||Object.keys(f).length)&&(l.evaluationContext.identity=e(e({},l.evaluationContext.identity),{traits:f}),h&&(l.evaluationContext.identity.identifier=h,l.identity=h)),l.flags=g,l.updateStorage(),l._onChange(l.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},l._loadedState(null,t.FlagSource.SERVER)),l.datadogRum)try{if(l.datadogRum.trackTraits){var m={};Object.keys((null===(a=l.evaluationContext.identity)||void 0===a?void 0:a.traits)||{}).map((function(t){m[F+t]=l.getTrait(t)}));var S=e(e(e({},l.datadogRum.client.getUser()),{id:l.datadogRum.client.getUser().id||(null===(u=l.evaluationContext.identity)||void 0===u?void 0:u.identifier)}),m);l.log("Setting Datadog user",S),l.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(l.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(l.flags).map((function(t){s(C,E+t,l.getValue(t,{skipAnalytics:!0})),s(C,b+t,l.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=l.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){s(C,F+t,l.getTrait(t))})),l.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),l.log("Sending date traits to dynatrace",C.date),l.log("Sending shortString traits to dynatrace",C.shortString),l.log("Sending javaDouble to dynatrace",C.javaDouble),l.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return a.identity?Promise.all([a.identity.traits&&Object.keys(a.identity.traits).length||!a.identity.identifier?l.getJSON(n+"identities/","POST",JSON.stringify({identifier:a.identity.identifier,transient:a.identity.transient,traits:Object.entries(a.identity.traits).map((function(t){var e=t[0],i=t[1];return{trait_key:e,trait_value:null==i?void 0:i.value,transient:null==i?void 0:i.transient}})).filter((function(t){return void 0!==t.trait_value||(l.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):l.getJSON(n+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(t){return l.evaluationContext.identity=e(e({},l.evaluationContext.identity),{traits:{}}),u(null==t?void 0:t[0])})).catch((function(t){var e=t.message,i=new Error(e);return Promise.reject(i)})):l.getJSON(n+"flags/").then((function(t){return u({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=l.api;if(l.evaluationEvent&&l.evaluationContext.environment&&l.evaluationEvent[l.evaluationContext.environment.apiKey])return l.evaluationEvent&&0!==Object.getOwnPropertyNames(l.evaluationEvent).length&&0!==Object.getOwnPropertyNames(l.evaluationEvent[l.evaluationContext.environment.apiKey]).length?l.getJSON(t+"analytics/flags/","POST",JSON.stringify(l.evaluationEvent[l.evaluationContext.environment.apiKey])).then((function(t){if(l.evaluationContext.environment){var i=l.getState();l.evaluationEvent||(l.evaluationEvent={}),l.evaluationEvent[l.evaluationContext.environment.apiKey]={},l.setState(e(e({},i),{evaluationEvent:l.evaluationEvent})),l.updateEventStorage()}})).catch((function(t){l.log("Exception fetching evaluationEvent",t)})):void 0},this.flushPipelineAnalytics=function(){return i(l,void 0,void 0,(function(){var t,i,a,l,o,s,r;return n(this,(function(n){switch(n.label){case 0:if(t=this.evaluationAnalyticsUrl&&this.evaluationContext.environment,i=this.pipelineEvents.length>0&&(!this.isPipelineFlushing||0===this.pipelineFlushInterval),!t||!i)return[2];a=this.evaluationContext.environment.apiKey,this.isPipelineFlushing=!0,l=this.pipelineEvents.slice(0,this.evaluationAnalyticsMaxBuffer),this.pipelineEvents=this.pipelineEvents.slice(this.evaluationAnalyticsMaxBuffer),this.pipelineRecordedKeys.clear(),o={events:l,environment_key:a},n.label=1;case 1:return n.trys.push([1,3,4,5]),[4,g(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(o),headers:e({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":a},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat(f)})})];case 2:if(!(s=n.sent()).status||s.status<200||s.status>=300)throw new Error("Pipeline analytics: unexpected status ".concat(s.status));return this.log("Pipeline analytics: flush successful"),[3,5];case 3:return r=n.sent(),this.pipelineEvents=l.concat(this.pipelineEvents),this.log("Pipeline analytics: flush failed, events re-queued",r),[3,5];case 4:return this.isPipelineFlushing=!1,[7];case 5:return[2]}}))}))},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:t.FlagSource.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.evaluationAnalyticsUrl=null,this.evaluationAnalyticsMaxBuffer=1e3,this.pipelineEvents=[],this.pipelineAnalyticsInterval=null,this.isPipelineFlushing=!1,this.pipelineRecordedKeys=new Map,this.getValue=function(t,e,i){var n=l.flags&&l.flags[t.toLowerCase().replace(/ /g,"_")],a=null;if(n&&(a=n.value),(null==e?void 0:e.skipAnalytics)||i||l.evaluateFlag(t,"VALUE"),null===a&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===a?(l.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(a)}catch(t){return e.fallback}return a},this.getTrait=function(t){var e,i;return(null===(e=l.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(i=l.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===i?void 0:i.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=l.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],i=t[1];return[e,null==i?void 0:i.value]})))},this.setContext=function(t){var i,n,a=c(t);return l.evaluationContext=e(e({},a),{environment:a.environment||l.evaluationContext.environment}),l.identity=null===(n=null===(i=l.getContext())||void 0===i?void 0:i.identity)||void 0===n?void 0:n.identifier,l.initialised?l.getFlags():Promise.resolve()},this.getContext=function(){return l.evaluationContext},this.updateContext=function(t){return l.setContext(e(e({},l.getContext()),t))},this.setTrait=function(t,i){var n;if(l.api)return l.setContext(e(e({},l.evaluationContext),{identity:e(e({},l.evaluationContext.identity),{traits:e(e({},null===(n=l.evaluationContext.identity)||void 0===n?void 0:n.traits),u(Object.fromEntries([[t,i]])))})}))},this.setTraits=function(t){var i;if(l.api)return l.setContext(e(e({},l.evaluationContext),{identity:e(e({},l.evaluationContext.identity),{traits:e(e({},null===(i=l.evaluationContext.identity)||void 0===i?void 0:i.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],i=t[1];return[e,r(i)?i:{value:i}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var i,n,a="object"==typeof e,o=l.flags&&l.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!o&&a&&void 0!==e.fallback?s=null==e?void 0:e.fallback:o&&o.enabled&&(s=!0),(a&&!e.skipAnalytics||!e)&&l.evaluateFlag(t,"ENABLED"),l.sentryClient)try{null===(n=null===(i=l.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===i?void 0:i.addFeatureFlag)||void 0===n||n.call(i,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=l.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=l.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,i){var n,a,o,s=l.headers,r={method:e||"GET",body:i,cache:"no-cache",headers:{}};l.evaluationContext.environment&&(r.headers["X-Environment-Key"]=l.evaluationContext.environment.apiKey),e&&"GET"!==e&&(r.headers["Content-Type"]="application/json; charset=utf-8"),(null===(n=l.applicationMetadata)||void 0===n?void 0:n.name)&&(r.headers["Flagsmith-Application-Name"]=l.applicationMetadata.name),(null===(a=l.applicationMetadata)||void 0===a?void 0:a.version)&&(r.headers["Flagsmith-Application-Version"]=l.applicationMetadata.version),r.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat(f),s&&Object.assign(r.headers,s),g||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(o=l.evaluationContext.identity)||void 0===o?void 0:o.identifier);return g(t,r).then((function(i){var n,a,o="".concat(null===(n=l.evaluationContext.identity)||void 0===n?void 0:n.identifier);if(u===o){var s=null===(a=i.headers)||void 0===a?void 0:a.get("x-flagsmith-document-updated-at");if(s)try{var r=parseFloat(s);if(isNaN(r))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");l.timestamp=r}catch(t){l.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return l.log("Fetch response: "+i.status+" "+(e||"GET")+0+t),i.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&i.status&&(e="API Response: ".concat(i.status)),i.status&&i.status>=200&&i.status<300?e:Promise.reject(new Error(e))}))}l.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(o))}))},this.evaluateFlag=function(t,e){if(l.datadogRum&&(l.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?l.datadogRum.client.addFeatureFlagEvaluation(E+t,l.getValue(t,{},!0)):l.datadogRum.client.addFeatureFlagEvaluation(b+t,l.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),l.enableAnalytics){if(!l.evaluationEvent||!l.evaluationContext.environment)return;l.evaluationEvent[l.evaluationContext.environment.apiKey]||(l.evaluationEvent[l.evaluationContext.environment.apiKey]={}),void 0===l.evaluationEvent[l.evaluationContext.environment.apiKey][t]&&(l.evaluationEvent[l.evaluationContext.environment.apiKey][t]=0),l.evaluationEvent[l.evaluationContext.environment.apiKey][t]+=1}l.evaluationAnalyticsUrl&&l.recordPipelineEvent(t),l.updateEventStorage()},this.pipelineFlushInterval=1e4,this.trackEvent=function(t,e){if(l.evaluationAnalyticsUrl&&t){var i=l.buildAnalyticEvent(h.CUSTOM_EVENT,t,{extraMetadata:e});l.pipelineEvents.push(i),(0===l.pipelineFlushInterval||l.pipelineEvents.length>=l.evaluationAnalyticsMaxBuffer)&&l.flushPipelineAnalytics()}},this._onChange=function(t,e,i){var n,a;l.setLoadingState(i),null===(n=l.onChange)||void 0===n||n.call(l,t,e,l.loadingState),null===(a=l._trigger)||void 0===a||a.call(l)},g=a.fetch?a.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!a.browserlessStorage,this.applicationMetadata=a.applicationMetadata,this.log("Constructing flagsmith instance "+a),a.eventSource&&(p=a.eventSource),a.AsyncStorage&&(y=a.AsyncStorage)}return d.prototype.init=function(a){var l,s,r,u;return i(this,void 0,void 0,(function(){var d,h,f,p,m,E,b,F,x,O,A,_,w,I,j,L,P,k,T,U,K,N,R,M,D,G,J,V,B,H,q,W,X,Y,z,Q,Z=this;return n(this,(function($){switch($.label){case 0:d=c(a.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),h=a.AsyncStorage,f=a._trigger,p=a._triggerLoadingState,m=a.angularHttpClient,E=a.api,b=void 0===E?C:E,F=a.applicationMetadata,x=a.cacheFlags,O=a.cacheOptions,A=a.datadogRum,_=a.defaultFlags,w=a.enableAnalytics,I=a.enableDynatrace,j=a.enableLogs,L=a.environmentID,P=a.evaluationAnalyticsConfig,k=a.eventSourceUrl,T=void 0===k?"https://realtime.flagsmith.com/":k,U=a.fetch,K=a.headers,N=a.identity,R=a.onChange,M=a.onError,D=a.preventFetch,G=a.realtime,J=a.sentryClient,V=a.state,B=a.traits,d.environment=L?{apiKey:L}:d.environment,!d.environment||!d.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(d.identity=N||B?{identifier:N,traits:B?Object.fromEntries(Object.entries(B).map((function(t){return[t[0],{value:t[1]}]}))):{}}:d.identity,this.evaluationContext=d,this.api=v(b),this.headers=K,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=f||this._trigger,this._triggerLoadingState=p||this._triggerLoadingState,this.onError=function(t){Z.setLoadingState(e(e({},Z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==M||M(t)},this.enableLogs=j||!1,this.cacheOptions=O?{skipAPI:!!O.skipAPI,ttl:O.ttl||0,storageKey:O.storageKey,loadStale:!!O.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),U&&(g=U),this.enableAnalytics=w||!1,this.flags=Object.assign({},_)||{},this.datadogRum=A||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==y&&!!x,this.applicationMetadata=F,S="FLAGSMITH_EVENT_"+d.environment.apiKey,h&&(y=h),G&&"undefined"!=typeof window&&this.setupRealtime(T,d.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(V),this.log("Initialising with properties",a,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),m&&(g=function(t){return function(e,i){var n=i.headers,a=i.method,l=i.body,o={headers:n,observe:"response",responseType:"text"},s=function(t,e){var i=t.status,n=t.headers,a=t.body,l=t.error,o=t.message;return{status:null!=i?i:e?200:500,ok:e,headers:{get:function(t){var e,i;return null!==(i=null===(e=null==n?void 0:n.get)||void 0===e?void 0:e.call(n,t))&&void 0!==i?i:null}},text:function(){var t,e,i=null!==(e=null!==(t=null!=a?a:l)&&void 0!==t?t:o)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof i?JSON.stringify(i):i)}}};return new Promise((function(i){var n=function(t){return i(s(t,!t.status||t.status>=200&&t.status<300))},r=function(t){return i(s(t,!1))};switch(a){case"GET":return t.get(e,o).subscribe(n,r);case"POST":case"PUT":return t.post(e,null!=l?l:"",o).subscribe(n,r);default:return r({status:405,message:"Unsupported method: ".concat(a)})}}))}}(m)),y&&this.canUseStorage&&y.getItem(S).then((function(t){try{Z.evaluationEvent=JSON.parse(t)||{}}catch(t){Z.evaluationEvent={}}Z.analyticsInterval=setInterval(Z.analyticsFlags,Z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),y&&this.canUseStorage&&y.getItem(S,(function(t,i){if(i&&Z.evaluationContext.environment){var n=JSON.parse(i);if(n[Z.evaluationContext.environment.apiKey]){var a=Z.getState();Z.log("Retrieved events from cache",i),Z.setState(e(e({},a),{evaluationEvent:n[Z.evaluationContext.environment.apiKey]}))}}}))),P?this.initPipelineAnalytics(P):this.stopPipelineAnalytics(),!x)return[3,9];if(!y||!this.canUseStorage)return[3,8];q=function(a,l){return i(Z,void 0,void 0,(function(){var i,a,s,r,u,v,d,h,g,f,p,y,m,S,C,E,b,F,x,O=this;return n(this,(function(n){switch(n.label){case 0:if(!l)return[3,7];i=null,a=null,n.label=1;case 1:return n.trys.push([1,5,,6]),s=JSON.parse(l),r=!1,u=!1,s&&s.api===this.api&&(null===(f=null===(g=s.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(v=!0,this.evaluationContext.identity&&(null===(m=null===(y=s.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=s.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),v=!1),this.cacheOptions.ttl&&(!s.ts||(new Date).valueOf()-s.ts>this.cacheOptions.ttl)&&(s.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+s.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-s.ts)+"ms"),v=!1):s.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+s.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-s.ts)+"ms"),u=!0,v=!0)),v&&(r=!0,i=o(this.flags,s.flags),this.setState(e(e({},s),{evaluationContext:c(e(e({},s.evaluationContext),{identity:(null===(E=s.evaluationContext)||void 0===E?void 0:E.identity)?e(e({},null===(b=s.evaluationContext)||void 0===b?void 0:b.identity),{traits:e({},B||{})}):void 0}))})),this.log("Retrieved flags from cache",s))),r?(d=!D&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:i,traitsChanged:a},this._loadedState(null,t.FlagSource.CACHE,d)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&r&&!u&&this.log("Skipping API, using cache"),d&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:n.sent(),n.label=4;case 4:return[3,6];case 5:throw h=n.sent(),this.log("Exception fetching cached logs",h),h;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return n.sent(),[3,10];case 9:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:o({},this.flags),traitsChanged:o({},null===(F=this.evaluationContext.identity)||void 0===F?void 0:F.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(H);this._onChange(null,{isFromServer:!1,flagsChanged:o({},this.flags),traitsChanged:o({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS))}n.label=10;case 10:return[2]}}))}))},$.label=2;case 2:return $.trys.push([2,7,,8]),y.getItemSync?(W=y.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,y.getItem(this.getStorageKey())];case 4:W=$.sent(),$.label=5;case 5:return[4,q(null,W)];case 6:return $.sent(),[3,8];case 7:if(X=$.sent(),!this.flags||0===Object.keys(this.flags).length)throw X;return Q=X instanceof Error?X:new Error("".concat(X)),null===(l=this.onError)||void 0===l||l.call(this,Q),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:o({},_),traitsChanged:o({},null===(s=d.identity)||void 0===s?void 0:s.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else if(this.flags&&(Y=null,0===Object.keys(this.flags).length&&(Y=H),this._onChange(null,{isFromServer:!1,flagsChanged:o({},this.flags),traitsChanged:o({},null===(r=d.identity)||void 0===r?void 0:r.traits)},this._loadedState(Y,t.FlagSource.DEFAULT_FLAGS)),Y))throw new Error(Y);$.label=12;case 12:return[3,14];case 13:throw z=$.sent(),this.log("Error during initialisation ",z),Q=z instanceof Error?z:new Error("".concat(z)),null===(u=this.onError)||void 0===u||u.call(this,Q),z;case 14:return[2]}}))}))},d.prototype.getAllFlags=function(){return this.flags},d.prototype.identify=function(t,e,i){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:i,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],i=t[1];return[e,r(i)?i:{value:i}]})))),this.initialised?this.getFlags():Promise.resolve()},d.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},d.prototype.setState=function(t){var e,i;t&&(this.initialised=!0,this.api=t.api||this.api||C,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(i=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===i?void 0:i.identifier,this.log("setState called",this))},d.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},d.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},d.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},d.prototype._loadedState=function(t,e,i){return void 0===t&&(t=null),void 0===i&&(i=!1),{error:t,isFetching:i,isLoading:!1,source:e}},d.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,a(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},d.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),y.setItem(this.getStorageKey(),t)}},d.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);y.setItem(S,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},d.prototype.initPipelineAnalytics=function(t){var e,i,n,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=v(t.analyticsServerUrl),this.evaluationAnalyticsMaxBuffer=null!==(e=t.maxBuffer)&&void 0!==e?e:1e3,this.pipelineFlushInterval=null!==(i=t.flushInterval)&&void 0!==i?i:1e4,this.pipelineEvents=[],this.pipelineFlushInterval>0&&(this.pipelineAnalyticsInterval=setInterval(this.flushPipelineAnalytics,this.pipelineFlushInterval),null===(a=null===(n=this.pipelineAnalyticsInterval)||void 0===n?void 0:n.unref)||void 0===a||a.call(n))},d.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},d.prototype.currentTraitsSnapshot=function(){var t;return(null===(t=this.evaluationContext.identity)||void 0===t?void 0:t.traits)?e({},this.evaluationContext.identity.traits):null},d.prototype.getPageUrl=function(){return"undefined"!=typeof window&&window.location?window.location.href:null},d.prototype.getEventMetadata=function(t){var i=this.getPageUrl();return e(e(e({},t||{}),i?{page_url:i}:{}),{sdk_version:f})},d.prototype.buildAnalyticEvent=function(t,e,i){var n,a,l,o,s;return{event_id:e,event_type:t,evaluated_at:null!==(n=null==i?void 0:i.timestamp)&&void 0!==n?n:Date.now(),identity_identifier:null!==(l=null===(a=this.evaluationContext.identity)||void 0===a?void 0:a.identifier)&&void 0!==l?l:null,enabled:null!==(o=null==i?void 0:i.enabled)&&void 0!==o?o:null,value:null!==(s=null==i?void 0:i.value)&&void 0!==s?s:null,traits:this.currentTraitsSnapshot(),metadata:this.getEventMetadata(null==i?void 0:i.extraMetadata)}},d.prototype.recordPipelineEvent=function(t){var e,i,n,a,l=t.toLowerCase().replace(/ /g,"_"),o=this.flags&&this.flags[l],s="".concat(null!==(i=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==i?i:"none","|").concat(null!==(n=null==o?void 0:o.enabled)&&void 0!==n&&n,"|").concat(null!==(a=null==o?void 0:o.value)&&void 0!==a?a:"null");if(this.pipelineRecordedKeys.get(l)!==s){this.pipelineRecordedKeys.set(l,s);var r=this.buildAnalyticEvent(h.FLAG_EVALUATION,l,{enabled:o?o.enabled:null,value:o?o.value:null,extraMetadata:o?{id:o.id}:void 0});this.pipelineEvents.push(r),(0===this.pipelineFlushInterval||this.pipelineEvents.length>=this.evaluationAnalyticsMaxBuffer)&&this.flushPipelineAnalytics()}},d.prototype.setLoadingState=function(t){var i;l(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(i=this._triggerLoadingState)||void 0===i||i.call(this))},d.prototype.setupRealtime=function(t,e){var i=this,n=t+"sse/environments/"+e+"/stream";p?this.eventSource||(this.log("Creating event source with url "+n),this.eventSource=new p(n),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){i.log("Could not parse sse event",t)}e?!i.timestamp||e>i.timestamp?i.isLoading?i.log("updated_at is new, but flags are loading",t.data,i.timestamp):(i.log("updated_at is new, fetching flags",t.data,i.timestamp),i.getFlags()):i.log("updated_at is outdated, skipping get flags",t.data,i.timestamp):i.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},d}();function O(t){var e=t.fetch,i=t.AsyncStorage,n=t.eventSource;return new x({fetch:e,AsyncStorage:i,eventSource:n})}var A=O({});t.createFlagsmithInstance=function(){return O({})},t.default=A,Object.defineProperty(t,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=next-middleware.js.map
@@ -1,2 +1,2 @@
1
- var t=function(){return t=Object.assign||function(t){for(var e,i=1,n=arguments.length;i<n;i++)for(var a in e=arguments[i])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},t.apply(this,arguments)};function e(t,e,i,n){return new(i||(i=Promise))((function(a,l){function o(t){try{r(n.next(t))}catch(t){l(t)}}function s(t){try{r(n.throw(t))}catch(t){l(t)}}function r(t){var e;t.done?a(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,s)}r((n=n.apply(t,e||[])).next())}))}function i(t,e){var i,n,a,l,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return l={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function s(l){return function(s){return function(l){if(i)throw new TypeError("Generator is already executing.");for(;o;)try{if(i=1,n&&(a=2&l[0]?n.return:l[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,l[1])).done)return a;switch(n=0,a&&(l=[2&l[0],a.value]),l[0]){case 0:case 1:a=l;break;case 4:return o.label++,{value:l[1],done:!1};case 5:o.label++,n=l[1],l=[0];continue;case 7:l=o.ops.pop(),o.trys.pop();continue;default:if(!(a=o.trys,(a=a.length>0&&a[a.length-1])||6!==l[0]&&2!==l[0])){o=0;continue}if(3===l[0]&&(!a||l[1]>a[0]&&l[1]<a[3])){o.label=l[1];break}if(6===l[0]&&o.label<a[1]){o.label=a[1],a=l;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(l);break}a[2]&&o.ops.pop(),o.trys.pop();continue}l=e.call(t,o)}catch(t){l=[6,t],n=0}finally{i=a=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}([l,s])}}}function n(t,e,i){if(i||2===arguments.length)for(var n,a=0,l=e.length;a<l;a++)!n&&a in e||(n||(n=Array.prototype.slice.call(e,0,a)),n[a]=e[a]);return t.concat(n||Array.prototype.slice.call(e))}var a=function t(e,i){if(e===i)return!0;if(e&&i&&"object"==typeof e&&"object"==typeof i){if(e.constructor!==i.constructor)return!1;var n,a,l;if(Array.isArray(e)){if((n=e.length)!=i.length)return!1;for(a=n;0!=a--;)if(!t(e[a],i[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===i.source&&e.flags===i.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===i.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===i.toString();if((n=(l=Object.keys(e)).length)!==Object.keys(i).length)return!1;for(a=n;0!=a--;)if(!Object.prototype.hasOwnProperty.call(i,l[a]))return!1;for(a=n;0!=a--;){var o=l[a];if(!t(e[o],i[o]))return!1}return!0}return e!=e&&i!=i};function l(t,e){var i=Object.keys(e||{}).filter((function(i){var n=null==t?void 0:t[i],l=null==e?void 0:e[i];return!a(n,l)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||i.push(t)})),Object.keys(i).length?i:null}function o(t,e,i){var n="shortString",a=!0;"number"==typeof i&&(n="javaDouble",a=!1),t[n]=t[n]||{},t[n][e]=a?i+"":i}function s(t){return!!t&&"object"==typeof t&&void 0!==t.value}function r(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],i=t[1];return[e,s(i)?i:{value:i}]})))}function u(e){return t(t({},e),{identity:e.identity?t(t({},e.identity),{traits:r(e.identity.traits||{})}):void 0})}function c(t){return t.endsWith("/")?t:t+"/"}var v,d,h;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(v||(v={})),function(t){t.FLAG_EVALUATION="flag_evaluation",t.CUSTOM_EVENT="custom_event"}(d||(d={}));var g,f=null,p="FLAGSMITH_EVENT",y="https://edge.api.flagsmith.com/api/v1/",m=function(){function m(n){var a=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var e=a,i=e.api,n=e.evaluationContext;a.log("Get Flags"),a.isLoading=!0,a.loadingState.isFetching||a.setLoadingState(t(t({},a.loadingState),{isFetching:!0}));var s="".concat(a.getContext().identity),r=function(e){var i,n,r,u;if(e&&s==="".concat(a.getContext().identity)){var c=e.flags,d=e.traits,h=e.identifier;a.isLoading=!1;var g={},f={};d=d||[],(c=c||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),d.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),a.oldFlags=t({},a.flags);var p=l(a.oldFlags,g),y=l(null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.traits,f);if((h||Object.keys(f).length)&&(a.evaluationContext.identity=t(t({},a.evaluationContext.identity),{traits:f}),h&&(a.evaluationContext.identity.identifier=h,a.identity=h)),a.flags=g,a.updateStorage(),a._onChange(a.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},a._loadedState(null,v.SERVER)),a.datadogRum)try{if(a.datadogRum.trackTraits){var m={};Object.keys((null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.traits)||{}).map((function(t){m["flagsmith_trait_"+t]=a.getTrait(t)}));var S=t(t(t({},a.datadogRum.client.getUser()),{id:a.datadogRum.client.getUser().id||(null===(r=a.evaluationContext.identity)||void 0===r?void 0:r.identifier)}),m);a.log("Setting Datadog user",S),a.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(a.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(a.flags).map((function(t){o(C,"flagsmith_value_"+t,a.getValue(t,{skipAnalytics:!0})),o(C,"flagsmith_enabled_"+t,a.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(u=a.evaluationContext.identity)||void 0===u?void 0:u.traits)||{}).map((function(t){o(C,"flagsmith_trait_"+t,a.getTrait(t))})),a.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),a.log("Sending date traits to dynatrace",C.date),a.log("Sending shortString traits to dynatrace",C.shortString),a.log("Sending javaDouble to dynatrace",C.javaDouble),a.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return n.identity?Promise.all([n.identity.traits&&Object.keys(n.identity.traits).length||!n.identity.identifier?a.getJSON(i+"identities/","POST",JSON.stringify({identifier:n.identity.identifier,transient:n.identity.transient,traits:Object.entries(n.identity.traits).map((function(t){var e=t[0],i=t[1];return{trait_key:e,trait_value:null==i?void 0:i.value,transient:null==i?void 0:i.transient}})).filter((function(t){return void 0!==t.trait_value||(a.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):a.getJSON(i+"identities/?identifier="+encodeURIComponent(n.identity.identifier)+(n.identity.transient?"&transient=true":""))]).then((function(e){return a.evaluationContext.identity=t(t({},a.evaluationContext.identity),{traits:{}}),r(null==e?void 0:e[0])})).catch((function(t){var e=t.message,i=new Error(e);return Promise.reject(i)})):a.getJSON(i+"flags/").then((function(t){return r({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var e=a.api;if(a.evaluationEvent&&a.evaluationContext.environment&&a.evaluationEvent[a.evaluationContext.environment.apiKey])return a.evaluationEvent&&0!==Object.getOwnPropertyNames(a.evaluationEvent).length&&0!==Object.getOwnPropertyNames(a.evaluationEvent[a.evaluationContext.environment.apiKey]).length?a.getJSON(e+"analytics/flags/","POST",JSON.stringify(a.evaluationEvent[a.evaluationContext.environment.apiKey])).then((function(e){if(a.evaluationContext.environment){var i=a.getState();a.evaluationEvent||(a.evaluationEvent={}),a.evaluationEvent[a.evaluationContext.environment.apiKey]={},a.setState(t(t({},i),{evaluationEvent:a.evaluationEvent})),a.updateEventStorage()}})).catch((function(t){a.log("Exception fetching evaluationEvent",t)})):void 0},this.flushPipelineAnalytics=function(){return e(a,void 0,void 0,(function(){var e,n,a,l,o,s,r;return i(this,(function(i){switch(i.label){case 0:if(e=this.evaluationAnalyticsUrl&&this.evaluationContext.environment,n=this.pipelineEvents.length>0&&(!this.isPipelineFlushing||0===this.pipelineFlushInterval),!e||!n)return[2];a=this.evaluationContext.environment.apiKey,this.isPipelineFlushing=!0,l=this.pipelineEvents.slice(0,this.evaluationAnalyticsMaxBuffer),this.pipelineEvents=this.pipelineEvents.slice(this.evaluationAnalyticsMaxBuffer),this.pipelineRecordedKeys.clear(),o={events:l,environment_key:a},i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,h(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(o),headers:t({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":a},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat("11.0.0-internal.6")})})];case 2:if(!(s=i.sent()).status||s.status<200||s.status>=300)throw new Error("Pipeline analytics: unexpected status ".concat(s.status));return this.log("Pipeline analytics: flush successful"),[3,5];case 3:return r=i.sent(),this.pipelineEvents=l.concat(this.pipelineEvents),this.log("Pipeline analytics: flush failed, events re-queued",r),[3,5];case 4:return this.isPipelineFlushing=!1,[7];case 5:return[2]}}))}))},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:v.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.evaluationAnalyticsUrl=null,this.evaluationAnalyticsMaxBuffer=1e3,this.pipelineEvents=[],this.pipelineAnalyticsInterval=null,this.isPipelineFlushing=!1,this.pipelineRecordedKeys=new Map,this.getValue=function(t,e,i){var n=a.flags&&a.flags[t.toLowerCase().replace(/ /g,"_")],l=null;if(n&&(l=n.value),(null==e?void 0:e.skipAnalytics)||i||a.evaluateFlag(t,"VALUE"),null===l&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===l?(a.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(l)}catch(t){return e.fallback}return l},this.getTrait=function(t){var e,i;return(null===(e=a.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(i=a.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===i?void 0:i.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=a.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],i=t[1];return[e,null==i?void 0:i.value]})))},this.setContext=function(e){var i,n,l=u(e);return a.evaluationContext=t(t({},l),{environment:l.environment||a.evaluationContext.environment}),a.identity=null===(n=null===(i=a.getContext())||void 0===i?void 0:i.identity)||void 0===n?void 0:n.identifier,a.initialised?a.getFlags():Promise.resolve()},this.getContext=function(){return a.evaluationContext},this.updateContext=function(e){return a.setContext(t(t({},a.getContext()),e))},this.setTrait=function(e,i){var n;if(a.api)return a.setContext(t(t({},a.evaluationContext),{identity:t(t({},a.evaluationContext.identity),{traits:t(t({},null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.traits),r(Object.fromEntries([[e,i]])))})}))},this.setTraits=function(e){var i;if(a.api)return a.setContext(t(t({},a.evaluationContext),{identity:t(t({},a.evaluationContext.identity),{traits:t(t({},null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.traits),Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],i=t[1];return[e,s(i)?i:{value:i}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var i,n,l="object"==typeof e,o=a.flags&&a.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!o&&l&&void 0!==e.fallback?s=null==e?void 0:e.fallback:o&&o.enabled&&(s=!0),(l&&!e.skipAnalytics||!e)&&a.evaluateFlag(t,"ENABLED"),a.sentryClient)try{null===(n=null===(i=a.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===i?void 0:i.addFeatureFlag)||void 0===n||n.call(i,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=a.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=a.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,i){var n,l,o,s=a.headers,r={method:e||"GET",body:i,cache:"no-cache",headers:{}};a.evaluationContext.environment&&(r.headers["X-Environment-Key"]=a.evaluationContext.environment.apiKey),e&&"GET"!==e&&(r.headers["Content-Type"]="application/json; charset=utf-8"),(null===(n=a.applicationMetadata)||void 0===n?void 0:n.name)&&(r.headers["Flagsmith-Application-Name"]=a.applicationMetadata.name),(null===(l=a.applicationMetadata)||void 0===l?void 0:l.version)&&(r.headers["Flagsmith-Application-Version"]=a.applicationMetadata.version),r.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("11.0.0-internal.6"),s&&Object.assign(r.headers,s),h||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(o=a.evaluationContext.identity)||void 0===o?void 0:o.identifier);return h(t,r).then((function(i){var n,l,o="".concat(null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.identifier);if(u===o){var s=null===(l=i.headers)||void 0===l?void 0:l.get("x-flagsmith-document-updated-at");if(s)try{var r=parseFloat(s);if(isNaN(r))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");a.timestamp=r}catch(t){a.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return a.log("Fetch response: "+i.status+" "+(e||"GET")+0+t),i.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&i.status&&(e="API Response: ".concat(i.status)),i.status&&i.status>=200&&i.status<300?e:Promise.reject(new Error(e))}))}a.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(o))}))},this.evaluateFlag=function(t,e){if(a.datadogRum&&(a.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?a.datadogRum.client.addFeatureFlagEvaluation("flagsmith_value_"+t,a.getValue(t,{},!0)):a.datadogRum.client.addFeatureFlagEvaluation("flagsmith_enabled_"+t,a.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),a.enableAnalytics){if(!a.evaluationEvent||!a.evaluationContext.environment)return;a.evaluationEvent[a.evaluationContext.environment.apiKey]||(a.evaluationEvent[a.evaluationContext.environment.apiKey]={}),void 0===a.evaluationEvent[a.evaluationContext.environment.apiKey][t]&&(a.evaluationEvent[a.evaluationContext.environment.apiKey][t]=0),a.evaluationEvent[a.evaluationContext.environment.apiKey][t]+=1}a.evaluationAnalyticsUrl&&a.recordPipelineEvent(t),a.updateEventStorage()},this.pipelineFlushInterval=1e4,this.trackEvent=function(t,e){if(a.evaluationAnalyticsUrl&&t){var i=a.buildAnalyticEvent(d.CUSTOM_EVENT,t,{extraMetadata:e});a.pipelineEvents.push(i),(0===a.pipelineFlushInterval||a.pipelineEvents.length>=a.evaluationAnalyticsMaxBuffer)&&a.flushPipelineAnalytics()}},this._onChange=function(t,e,i){var n,l;a.setLoadingState(i),null===(n=a.onChange)||void 0===n||n.call(a,t,e,a.loadingState),null===(l=a._trigger)||void 0===l||l.call(a)},h=n.fetch?n.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!n.browserlessStorage,this.applicationMetadata=n.applicationMetadata,this.log("Constructing flagsmith instance "+n),n.eventSource&&(g=n.eventSource),n.AsyncStorage&&(f=n.AsyncStorage)}return m.prototype.init=function(n){var a,o,s,r;return e(this,void 0,void 0,(function(){var d,g,m,S,C,E,b,x,F,O,A,_,w,I,L,j,P,k,T,U,K,N,R,M,D,G,J,V,B,H,q,W,X,Y,z,Q,Z=this;return i(this,(function($){switch($.label){case 0:d=u(n.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),g=n.AsyncStorage,m=n._trigger,S=n._triggerLoadingState,C=n.angularHttpClient,E=n.api,b=void 0===E?y:E,x=n.applicationMetadata,F=n.cacheFlags,O=n.cacheOptions,A=n.datadogRum,_=n.defaultFlags,w=n.enableAnalytics,I=n.enableDynatrace,L=n.enableLogs,j=n.environmentID,P=n.evaluationAnalyticsConfig,k=n.eventSourceUrl,T=void 0===k?"https://realtime.flagsmith.com/":k,U=n.fetch,K=n.headers,N=n.identity,R=n.onChange,M=n.onError,D=n.preventFetch,G=n.realtime,J=n.sentryClient,V=n.state,B=n.traits,d.environment=j?{apiKey:j}:d.environment,!d.environment||!d.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(d.identity=N||B?{identifier:N,traits:B?Object.fromEntries(Object.entries(B).map((function(t){return[t[0],{value:t[1]}]}))):{}}:d.identity,this.evaluationContext=d,this.api=c(b),this.headers=K,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=m||this._trigger,this._triggerLoadingState=S||this._triggerLoadingState,this.onError=function(e){Z.setLoadingState(t(t({},Z.loadingState),{isFetching:!1,isLoading:!1,error:e})),null==M||M(e)},this.enableLogs=L||!1,this.cacheOptions=O?{skipAPI:!!O.skipAPI,ttl:O.ttl||0,storageKey:O.storageKey,loadStale:!!O.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),U&&(h=U),this.enableAnalytics=w||!1,this.flags=Object.assign({},_)||{},this.datadogRum=A||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==f&&!!F,this.applicationMetadata=x,p="FLAGSMITH_EVENT_"+d.environment.apiKey,g&&(f=g),G&&"undefined"!=typeof window&&this.setupRealtime(T,d.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=t(t({},this.loadingState),{isLoading:!1,source:v.DEFAULT_FLAGS})),this.setState(V),this.log("Initialising with properties",n,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),C&&(h=function(t){return function(e,i){var n=i.headers,a=i.method,l=i.body,o={headers:n,observe:"response",responseType:"text"},s=function(t,e){var i=t.status,n=t.headers,a=t.body,l=t.error,o=t.message;return{status:null!=i?i:e?200:500,ok:e,headers:{get:function(t){var e,i;return null!==(i=null===(e=null==n?void 0:n.get)||void 0===e?void 0:e.call(n,t))&&void 0!==i?i:null}},text:function(){var t,e,i=null!==(e=null!==(t=null!=a?a:l)&&void 0!==t?t:o)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof i?JSON.stringify(i):i)}}};return new Promise((function(i){var n=function(t){return i(s(t,!t.status||t.status>=200&&t.status<300))},r=function(t){return i(s(t,!1))};switch(a){case"GET":return t.get(e,o).subscribe(n,r);case"POST":case"PUT":return t.post(e,null!=l?l:"",o).subscribe(n,r);default:return r({status:405,message:"Unsupported method: ".concat(a)})}}))}}(C)),f&&this.canUseStorage&&f.getItem(p).then((function(t){try{Z.evaluationEvent=JSON.parse(t)||{}}catch(t){Z.evaluationEvent={}}Z.analyticsInterval=setInterval(Z.analyticsFlags,Z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),f&&this.canUseStorage&&f.getItem(p,(function(e,i){if(i&&Z.evaluationContext.environment){var n=JSON.parse(i);if(n[Z.evaluationContext.environment.apiKey]){var a=Z.getState();Z.log("Retrieved events from cache",i),Z.setState(t(t({},a),{evaluationEvent:n[Z.evaluationContext.environment.apiKey]}))}}}))),P?this.initPipelineAnalytics(P):this.stopPipelineAnalytics(),!F)return[3,9];if(!f||!this.canUseStorage)return[3,8];q=function(n,a){return e(Z,void 0,void 0,(function(){var e,n,o,s,r,c,d,h,g,f,p,y,m,S,C,E,b,x,F,O=this;return i(this,(function(i){switch(i.label){case 0:if(!a)return[3,7];e=null,n=null,i.label=1;case 1:return i.trys.push([1,5,,6]),o=JSON.parse(a),s=!1,r=!1,o&&o.api===this.api&&(null===(f=null===(g=o.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(c=!0,this.evaluationContext.identity&&(null===(m=null===(y=o.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=o.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),c=!1),this.cacheOptions.ttl&&(!o.ts||(new Date).valueOf()-o.ts>this.cacheOptions.ttl)&&(o.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),c=!1):o.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),r=!0,c=!0)),c&&(s=!0,e=l(this.flags,o.flags),this.setState(t(t({},o),{evaluationContext:u(t(t({},o.evaluationContext),{identity:(null===(E=o.evaluationContext)||void 0===E?void 0:E.identity)?t(t({},null===(b=o.evaluationContext)||void 0===b?void 0:b.identity),{traits:t({},B||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),s?(d=!D&&(!this.cacheOptions.skipAPI||r),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:n},this._loadedState(null,v.CACHE,d)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!r&&this.log("Skipping API, using cache"),d&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:i.sent(),i.label=4;case 4:return[3,6];case 5:throw h=i.sent(),this.log("Exception fetching cached logs",h),h;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,v.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(H);this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(F=this.evaluationContext.identity)||void 0===F?void 0:F.traits)},this._loadedState(null,v.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},$.label=2;case 2:return $.trys.push([2,7,,8]),f.getItemSync?(W=f.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,f.getItem(this.getStorageKey())];case 4:W=$.sent(),$.label=5;case 5:return[4,q(null,W)];case 6:return $.sent(),[3,8];case 7:if(X=$.sent(),!this.flags||0===Object.keys(this.flags).length)throw X;return Q=X instanceof Error?X:new Error("".concat(X)),null===(a=this.onError)||void 0===a||a.call(this,Q),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:l({},_),traitsChanged:l({},null===(o=d.identity)||void 0===o?void 0:o.traits)},this._loadedState(null,v.DEFAULT_FLAGS));else if(this.flags&&(Y=null,0===Object.keys(this.flags).length&&(Y=H),this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(s=d.identity)||void 0===s?void 0:s.traits)},this._loadedState(Y,v.DEFAULT_FLAGS)),Y))throw new Error(Y);$.label=12;case 12:return[3,14];case 13:throw z=$.sent(),this.log("Error during initialisation ",z),Q=z instanceof Error?z:new Error("".concat(z)),null===(r=this.onError)||void 0===r||r.call(this,Q),z;case 14:return[2]}}))}))},m.prototype.getAllFlags=function(){return this.flags},m.prototype.identify=function(t,e,i){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:i,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],i=t[1];return[e,s(i)?i:{value:i}]})))),this.initialised?this.getFlags():Promise.resolve()},m.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},m.prototype.setState=function(t){var e,i;t&&(this.initialised=!0,this.api=t.api||this.api||y,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(i=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===i?void 0:i.identifier,this.log("setState called",this))},m.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},m.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},m.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},m.prototype._loadedState=function(t,e,i){return void 0===t&&(t=null),void 0===i&&(i=!1),{error:t,isFetching:i,isLoading:!1,source:e}},m.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,n(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},m.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),f.setItem(this.getStorageKey(),t)}},m.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);f.setItem(p,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},m.prototype.initPipelineAnalytics=function(t){var e,i,n,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=c(t.analyticsServerUrl),this.evaluationAnalyticsMaxBuffer=null!==(e=t.maxBuffer)&&void 0!==e?e:1e3,this.pipelineFlushInterval=null!==(i=t.flushInterval)&&void 0!==i?i:1e4,this.pipelineEvents=[],this.pipelineFlushInterval>0&&(this.pipelineAnalyticsInterval=setInterval(this.flushPipelineAnalytics,this.pipelineFlushInterval),null===(a=null===(n=this.pipelineAnalyticsInterval)||void 0===n?void 0:n.unref)||void 0===a||a.call(n))},m.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},m.prototype.currentTraitsSnapshot=function(){var e;return(null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.traits)?t({},this.evaluationContext.identity.traits):null},m.prototype.getPageUrl=function(){return"undefined"!=typeof window&&window.location?window.location.href:null},m.prototype.getEventMetadata=function(e){var i=this.getPageUrl();return t(t(t({},e||{}),i?{page_url:i}:{}),{sdk_version:"11.0.0-internal.6"})},m.prototype.buildAnalyticEvent=function(t,e,i){var n,a,l,o,s;return{event_id:e,event_type:t,evaluated_at:null!==(n=null==i?void 0:i.timestamp)&&void 0!==n?n:Date.now(),identity_identifier:null!==(l=null===(a=this.evaluationContext.identity)||void 0===a?void 0:a.identifier)&&void 0!==l?l:null,enabled:null!==(o=null==i?void 0:i.enabled)&&void 0!==o?o:null,value:null!==(s=null==i?void 0:i.value)&&void 0!==s?s:null,traits:this.currentTraitsSnapshot(),metadata:this.getEventMetadata(null==i?void 0:i.extraMetadata)}},m.prototype.recordPipelineEvent=function(t){var e,i,n,a,l=t.toLowerCase().replace(/ /g,"_"),o=this.flags&&this.flags[l],s="".concat(null!==(i=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==i?i:"none","|").concat(null!==(n=null==o?void 0:o.enabled)&&void 0!==n&&n,"|").concat(null!==(a=null==o?void 0:o.value)&&void 0!==a?a:"null");if(this.pipelineRecordedKeys.get(l)!==s){this.pipelineRecordedKeys.set(l,s);var r=this.buildAnalyticEvent(d.FLAG_EVALUATION,l,{enabled:o?o.enabled:null,value:o?o.value:null,extraMetadata:o?{id:o.id}:void 0});this.pipelineEvents.push(r),(0===this.pipelineFlushInterval||this.pipelineEvents.length>=this.evaluationAnalyticsMaxBuffer)&&this.flushPipelineAnalytics()}},m.prototype.setLoadingState=function(e){var i;a(e,this.loadingState)||(this.loadingState=t({},e),this.log("Loading state changed",e),null===(i=this._triggerLoadingState)||void 0===i||i.call(this))},m.prototype.setupRealtime=function(t,e){var i=this,n=t+"sse/environments/"+e+"/stream";g?this.eventSource||(this.log("Creating event source with url "+n),this.eventSource=new g(n),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){i.log("Could not parse sse event",t)}e?!i.timestamp||e>i.timestamp?i.isLoading?i.log("updated_at is new, but flags are loading",t.data,i.timestamp):(i.log("updated_at is new, fetching flags",t.data,i.timestamp),i.getFlags()):i.log("updated_at is outdated, skipping get flags",t.data,i.timestamp):i.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},m}();function S(t){var e=t.fetch,i=t.AsyncStorage,n=t.eventSource;return new m({fetch:e,AsyncStorage:i,eventSource:n})}var C=S({}),E=function(){return S({})};export{v as FlagSource,E as createFlagsmithInstance,C as default};
1
+ var t=function(){return t=Object.assign||function(t){for(var e,i=1,n=arguments.length;i<n;i++)for(var a in e=arguments[i])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},t.apply(this,arguments)};function e(t,e,i,n){return new(i||(i=Promise))((function(a,l){function o(t){try{r(n.next(t))}catch(t){l(t)}}function s(t){try{r(n.throw(t))}catch(t){l(t)}}function r(t){var e;t.done?a(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,s)}r((n=n.apply(t,e||[])).next())}))}function i(t,e){var i,n,a,l,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return l={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function s(l){return function(s){return function(l){if(i)throw new TypeError("Generator is already executing.");for(;o;)try{if(i=1,n&&(a=2&l[0]?n.return:l[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,l[1])).done)return a;switch(n=0,a&&(l=[2&l[0],a.value]),l[0]){case 0:case 1:a=l;break;case 4:return o.label++,{value:l[1],done:!1};case 5:o.label++,n=l[1],l=[0];continue;case 7:l=o.ops.pop(),o.trys.pop();continue;default:if(!(a=o.trys,(a=a.length>0&&a[a.length-1])||6!==l[0]&&2!==l[0])){o=0;continue}if(3===l[0]&&(!a||l[1]>a[0]&&l[1]<a[3])){o.label=l[1];break}if(6===l[0]&&o.label<a[1]){o.label=a[1],a=l;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(l);break}a[2]&&o.ops.pop(),o.trys.pop();continue}l=e.call(t,o)}catch(t){l=[6,t],n=0}finally{i=a=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}([l,s])}}}function n(t,e,i){if(i||2===arguments.length)for(var n,a=0,l=e.length;a<l;a++)!n&&a in e||(n||(n=Array.prototype.slice.call(e,0,a)),n[a]=e[a]);return t.concat(n||Array.prototype.slice.call(e))}var a=function t(e,i){if(e===i)return!0;if(e&&i&&"object"==typeof e&&"object"==typeof i){if(e.constructor!==i.constructor)return!1;var n,a,l;if(Array.isArray(e)){if((n=e.length)!=i.length)return!1;for(a=n;0!=a--;)if(!t(e[a],i[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===i.source&&e.flags===i.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===i.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===i.toString();if((n=(l=Object.keys(e)).length)!==Object.keys(i).length)return!1;for(a=n;0!=a--;)if(!Object.prototype.hasOwnProperty.call(i,l[a]))return!1;for(a=n;0!=a--;){var o=l[a];if(!t(e[o],i[o]))return!1}return!0}return e!=e&&i!=i};function l(t,e){var i=Object.keys(e||{}).filter((function(i){var n=null==t?void 0:t[i],l=null==e?void 0:e[i];return!a(n,l)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||i.push(t)})),Object.keys(i).length?i:null}function o(t,e,i){var n="shortString",a=!0;"number"==typeof i&&(n="javaDouble",a=!1),t[n]=t[n]||{},t[n][e]=a?i+"":i}function s(t){return!!t&&"object"==typeof t&&void 0!==t.value}function r(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],i=t[1];return[e,s(i)?i:{value:i}]})))}function u(e){return t(t({},e),{identity:e.identity?t(t({},e.identity),{traits:r(e.identity.traits||{})}):void 0})}function c(t){return t.endsWith("/")?t:t+"/"}var v,d,h;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(v||(v={})),function(t){t.FLAG_EVALUATION="flag_evaluation",t.CUSTOM_EVENT="custom_event"}(d||(d={}));var g,f=null,p="FLAGSMITH_EVENT",y="https://edge.api.flagsmith.com/api/v1/",m=function(){function m(n){var a=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var e=a,i=e.api,n=e.evaluationContext;a.log("Get Flags"),a.isLoading=!0,a.loadingState.isFetching||a.setLoadingState(t(t({},a.loadingState),{isFetching:!0}));var s="".concat(a.getContext().identity),r=function(e){var i,n,r,u;if(e&&s==="".concat(a.getContext().identity)){var c=e.flags,d=e.traits,h=e.identifier;a.isLoading=!1;var g={},f={};d=d||[],(c=c||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),d.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),a.oldFlags=t({},a.flags);var p=l(a.oldFlags,g),y=l(null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.traits,f);if((h||Object.keys(f).length)&&(a.evaluationContext.identity=t(t({},a.evaluationContext.identity),{traits:f}),h&&(a.evaluationContext.identity.identifier=h,a.identity=h)),a.flags=g,a.updateStorage(),a._onChange(a.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},a._loadedState(null,v.SERVER)),a.datadogRum)try{if(a.datadogRum.trackTraits){var m={};Object.keys((null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.traits)||{}).map((function(t){m["flagsmith_trait_"+t]=a.getTrait(t)}));var S=t(t(t({},a.datadogRum.client.getUser()),{id:a.datadogRum.client.getUser().id||(null===(r=a.evaluationContext.identity)||void 0===r?void 0:r.identifier)}),m);a.log("Setting Datadog user",S),a.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(a.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(a.flags).map((function(t){o(C,"flagsmith_value_"+t,a.getValue(t,{skipAnalytics:!0})),o(C,"flagsmith_enabled_"+t,a.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(u=a.evaluationContext.identity)||void 0===u?void 0:u.traits)||{}).map((function(t){o(C,"flagsmith_trait_"+t,a.getTrait(t))})),a.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),a.log("Sending date traits to dynatrace",C.date),a.log("Sending shortString traits to dynatrace",C.shortString),a.log("Sending javaDouble to dynatrace",C.javaDouble),a.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return n.identity?Promise.all([n.identity.traits&&Object.keys(n.identity.traits).length||!n.identity.identifier?a.getJSON(i+"identities/","POST",JSON.stringify({identifier:n.identity.identifier,transient:n.identity.transient,traits:Object.entries(n.identity.traits).map((function(t){var e=t[0],i=t[1];return{trait_key:e,trait_value:null==i?void 0:i.value,transient:null==i?void 0:i.transient}})).filter((function(t){return void 0!==t.trait_value||(a.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):a.getJSON(i+"identities/?identifier="+encodeURIComponent(n.identity.identifier)+(n.identity.transient?"&transient=true":""))]).then((function(e){return a.evaluationContext.identity=t(t({},a.evaluationContext.identity),{traits:{}}),r(null==e?void 0:e[0])})).catch((function(t){var e=t.message,i=new Error(e);return Promise.reject(i)})):a.getJSON(i+"flags/").then((function(t){return r({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var e=a.api;if(a.evaluationEvent&&a.evaluationContext.environment&&a.evaluationEvent[a.evaluationContext.environment.apiKey])return a.evaluationEvent&&0!==Object.getOwnPropertyNames(a.evaluationEvent).length&&0!==Object.getOwnPropertyNames(a.evaluationEvent[a.evaluationContext.environment.apiKey]).length?a.getJSON(e+"analytics/flags/","POST",JSON.stringify(a.evaluationEvent[a.evaluationContext.environment.apiKey])).then((function(e){if(a.evaluationContext.environment){var i=a.getState();a.evaluationEvent||(a.evaluationEvent={}),a.evaluationEvent[a.evaluationContext.environment.apiKey]={},a.setState(t(t({},i),{evaluationEvent:a.evaluationEvent})),a.updateEventStorage()}})).catch((function(t){a.log("Exception fetching evaluationEvent",t)})):void 0},this.flushPipelineAnalytics=function(){return e(a,void 0,void 0,(function(){var e,n,a,l,o,s,r;return i(this,(function(i){switch(i.label){case 0:if(e=this.evaluationAnalyticsUrl&&this.evaluationContext.environment,n=this.pipelineEvents.length>0&&(!this.isPipelineFlushing||0===this.pipelineFlushInterval),!e||!n)return[2];a=this.evaluationContext.environment.apiKey,this.isPipelineFlushing=!0,l=this.pipelineEvents.slice(0,this.evaluationAnalyticsMaxBuffer),this.pipelineEvents=this.pipelineEvents.slice(this.evaluationAnalyticsMaxBuffer),this.pipelineRecordedKeys.clear(),o={events:l,environment_key:a},i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,h(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(o),headers:t({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":a},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat("11.0.0-internal.7")})})];case 2:if(!(s=i.sent()).status||s.status<200||s.status>=300)throw new Error("Pipeline analytics: unexpected status ".concat(s.status));return this.log("Pipeline analytics: flush successful"),[3,5];case 3:return r=i.sent(),this.pipelineEvents=l.concat(this.pipelineEvents),this.log("Pipeline analytics: flush failed, events re-queued",r),[3,5];case 4:return this.isPipelineFlushing=!1,[7];case 5:return[2]}}))}))},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:v.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.evaluationAnalyticsUrl=null,this.evaluationAnalyticsMaxBuffer=1e3,this.pipelineEvents=[],this.pipelineAnalyticsInterval=null,this.isPipelineFlushing=!1,this.pipelineRecordedKeys=new Map,this.getValue=function(t,e,i){var n=a.flags&&a.flags[t.toLowerCase().replace(/ /g,"_")],l=null;if(n&&(l=n.value),(null==e?void 0:e.skipAnalytics)||i||a.evaluateFlag(t,"VALUE"),null===l&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===l?(a.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(l)}catch(t){return e.fallback}return l},this.getTrait=function(t){var e,i;return(null===(e=a.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(i=a.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===i?void 0:i.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=a.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],i=t[1];return[e,null==i?void 0:i.value]})))},this.setContext=function(e){var i,n,l=u(e);return a.evaluationContext=t(t({},l),{environment:l.environment||a.evaluationContext.environment}),a.identity=null===(n=null===(i=a.getContext())||void 0===i?void 0:i.identity)||void 0===n?void 0:n.identifier,a.initialised?a.getFlags():Promise.resolve()},this.getContext=function(){return a.evaluationContext},this.updateContext=function(e){return a.setContext(t(t({},a.getContext()),e))},this.setTrait=function(e,i){var n;if(a.api)return a.setContext(t(t({},a.evaluationContext),{identity:t(t({},a.evaluationContext.identity),{traits:t(t({},null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.traits),r(Object.fromEntries([[e,i]])))})}))},this.setTraits=function(e){var i;if(a.api)return a.setContext(t(t({},a.evaluationContext),{identity:t(t({},a.evaluationContext.identity),{traits:t(t({},null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.traits),Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],i=t[1];return[e,s(i)?i:{value:i}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var i,n,l="object"==typeof e,o=a.flags&&a.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!o&&l&&void 0!==e.fallback?s=null==e?void 0:e.fallback:o&&o.enabled&&(s=!0),(l&&!e.skipAnalytics||!e)&&a.evaluateFlag(t,"ENABLED"),a.sentryClient)try{null===(n=null===(i=a.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===i?void 0:i.addFeatureFlag)||void 0===n||n.call(i,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=a.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=a.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,i){var n,l,o,s=a.headers,r={method:e||"GET",body:i,cache:"no-cache",headers:{}};a.evaluationContext.environment&&(r.headers["X-Environment-Key"]=a.evaluationContext.environment.apiKey),e&&"GET"!==e&&(r.headers["Content-Type"]="application/json; charset=utf-8"),(null===(n=a.applicationMetadata)||void 0===n?void 0:n.name)&&(r.headers["Flagsmith-Application-Name"]=a.applicationMetadata.name),(null===(l=a.applicationMetadata)||void 0===l?void 0:l.version)&&(r.headers["Flagsmith-Application-Version"]=a.applicationMetadata.version),r.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("11.0.0-internal.7"),s&&Object.assign(r.headers,s),h||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(o=a.evaluationContext.identity)||void 0===o?void 0:o.identifier);return h(t,r).then((function(i){var n,l,o="".concat(null===(n=a.evaluationContext.identity)||void 0===n?void 0:n.identifier);if(u===o){var s=null===(l=i.headers)||void 0===l?void 0:l.get("x-flagsmith-document-updated-at");if(s)try{var r=parseFloat(s);if(isNaN(r))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");a.timestamp=r}catch(t){a.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return a.log("Fetch response: "+i.status+" "+(e||"GET")+0+t),i.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&i.status&&(e="API Response: ".concat(i.status)),i.status&&i.status>=200&&i.status<300?e:Promise.reject(new Error(e))}))}a.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(o))}))},this.evaluateFlag=function(t,e){if(a.datadogRum&&(a.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?a.datadogRum.client.addFeatureFlagEvaluation("flagsmith_value_"+t,a.getValue(t,{},!0)):a.datadogRum.client.addFeatureFlagEvaluation("flagsmith_enabled_"+t,a.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),a.enableAnalytics){if(!a.evaluationEvent||!a.evaluationContext.environment)return;a.evaluationEvent[a.evaluationContext.environment.apiKey]||(a.evaluationEvent[a.evaluationContext.environment.apiKey]={}),void 0===a.evaluationEvent[a.evaluationContext.environment.apiKey][t]&&(a.evaluationEvent[a.evaluationContext.environment.apiKey][t]=0),a.evaluationEvent[a.evaluationContext.environment.apiKey][t]+=1}a.evaluationAnalyticsUrl&&a.recordPipelineEvent(t),a.updateEventStorage()},this.pipelineFlushInterval=1e4,this.trackEvent=function(t,e){if(a.evaluationAnalyticsUrl&&t){var i=a.buildAnalyticEvent(d.CUSTOM_EVENT,t,{extraMetadata:e});a.pipelineEvents.push(i),(0===a.pipelineFlushInterval||a.pipelineEvents.length>=a.evaluationAnalyticsMaxBuffer)&&a.flushPipelineAnalytics()}},this._onChange=function(t,e,i){var n,l;a.setLoadingState(i),null===(n=a.onChange)||void 0===n||n.call(a,t,e,a.loadingState),null===(l=a._trigger)||void 0===l||l.call(a)},h=n.fetch?n.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!n.browserlessStorage,this.applicationMetadata=n.applicationMetadata,this.log("Constructing flagsmith instance "+n),n.eventSource&&(g=n.eventSource),n.AsyncStorage&&(f=n.AsyncStorage)}return m.prototype.init=function(n){var a,o,s,r;return e(this,void 0,void 0,(function(){var d,g,m,S,C,E,b,x,F,O,A,_,w,I,L,j,P,k,T,U,K,N,R,M,D,G,J,V,B,H,q,W,X,Y,z,Q,Z=this;return i(this,(function($){switch($.label){case 0:d=u(n.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),g=n.AsyncStorage,m=n._trigger,S=n._triggerLoadingState,C=n.angularHttpClient,E=n.api,b=void 0===E?y:E,x=n.applicationMetadata,F=n.cacheFlags,O=n.cacheOptions,A=n.datadogRum,_=n.defaultFlags,w=n.enableAnalytics,I=n.enableDynatrace,L=n.enableLogs,j=n.environmentID,P=n.evaluationAnalyticsConfig,k=n.eventSourceUrl,T=void 0===k?"https://realtime.flagsmith.com/":k,U=n.fetch,K=n.headers,N=n.identity,R=n.onChange,M=n.onError,D=n.preventFetch,G=n.realtime,J=n.sentryClient,V=n.state,B=n.traits,d.environment=j?{apiKey:j}:d.environment,!d.environment||!d.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(d.identity=N||B?{identifier:N,traits:B?Object.fromEntries(Object.entries(B).map((function(t){return[t[0],{value:t[1]}]}))):{}}:d.identity,this.evaluationContext=d,this.api=c(b),this.headers=K,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=m||this._trigger,this._triggerLoadingState=S||this._triggerLoadingState,this.onError=function(e){Z.setLoadingState(t(t({},Z.loadingState),{isFetching:!1,isLoading:!1,error:e})),null==M||M(e)},this.enableLogs=L||!1,this.cacheOptions=O?{skipAPI:!!O.skipAPI,ttl:O.ttl||0,storageKey:O.storageKey,loadStale:!!O.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),U&&(h=U),this.enableAnalytics=w||!1,this.flags=Object.assign({},_)||{},this.datadogRum=A||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==f&&!!F,this.applicationMetadata=x,p="FLAGSMITH_EVENT_"+d.environment.apiKey,g&&(f=g),G&&"undefined"!=typeof window&&this.setupRealtime(T,d.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=t(t({},this.loadingState),{isLoading:!1,source:v.DEFAULT_FLAGS})),this.setState(V),this.log("Initialising with properties",n,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),C&&(h=function(t){return function(e,i){var n=i.headers,a=i.method,l=i.body,o={headers:n,observe:"response",responseType:"text"},s=function(t,e){var i=t.status,n=t.headers,a=t.body,l=t.error,o=t.message;return{status:null!=i?i:e?200:500,ok:e,headers:{get:function(t){var e,i;return null!==(i=null===(e=null==n?void 0:n.get)||void 0===e?void 0:e.call(n,t))&&void 0!==i?i:null}},text:function(){var t,e,i=null!==(e=null!==(t=null!=a?a:l)&&void 0!==t?t:o)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof i?JSON.stringify(i):i)}}};return new Promise((function(i){var n=function(t){return i(s(t,!t.status||t.status>=200&&t.status<300))},r=function(t){return i(s(t,!1))};switch(a){case"GET":return t.get(e,o).subscribe(n,r);case"POST":case"PUT":return t.post(e,null!=l?l:"",o).subscribe(n,r);default:return r({status:405,message:"Unsupported method: ".concat(a)})}}))}}(C)),f&&this.canUseStorage&&f.getItem(p).then((function(t){try{Z.evaluationEvent=JSON.parse(t)||{}}catch(t){Z.evaluationEvent={}}Z.analyticsInterval=setInterval(Z.analyticsFlags,Z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),f&&this.canUseStorage&&f.getItem(p,(function(e,i){if(i&&Z.evaluationContext.environment){var n=JSON.parse(i);if(n[Z.evaluationContext.environment.apiKey]){var a=Z.getState();Z.log("Retrieved events from cache",i),Z.setState(t(t({},a),{evaluationEvent:n[Z.evaluationContext.environment.apiKey]}))}}}))),P?this.initPipelineAnalytics(P):this.stopPipelineAnalytics(),!F)return[3,9];if(!f||!this.canUseStorage)return[3,8];q=function(n,a){return e(Z,void 0,void 0,(function(){var e,n,o,s,r,c,d,h,g,f,p,y,m,S,C,E,b,x,F,O=this;return i(this,(function(i){switch(i.label){case 0:if(!a)return[3,7];e=null,n=null,i.label=1;case 1:return i.trys.push([1,5,,6]),o=JSON.parse(a),s=!1,r=!1,o&&o.api===this.api&&(null===(f=null===(g=o.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(c=!0,this.evaluationContext.identity&&(null===(m=null===(y=o.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=o.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),c=!1),this.cacheOptions.ttl&&(!o.ts||(new Date).valueOf()-o.ts>this.cacheOptions.ttl)&&(o.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),c=!1):o.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),r=!0,c=!0)),c&&(s=!0,e=l(this.flags,o.flags),this.setState(t(t({},o),{evaluationContext:u(t(t({},o.evaluationContext),{identity:(null===(E=o.evaluationContext)||void 0===E?void 0:E.identity)?t(t({},null===(b=o.evaluationContext)||void 0===b?void 0:b.identity),{traits:t({},B||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),s?(d=!D&&(!this.cacheOptions.skipAPI||r),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:n},this._loadedState(null,v.CACHE,d)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!r&&this.log("Skipping API, using cache"),d&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:i.sent(),i.label=4;case 4:return[3,6];case 5:throw h=i.sent(),this.log("Exception fetching cached logs",h),h;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,v.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(H);this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(F=this.evaluationContext.identity)||void 0===F?void 0:F.traits)},this._loadedState(null,v.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},$.label=2;case 2:return $.trys.push([2,7,,8]),f.getItemSync?(W=f.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,f.getItem(this.getStorageKey())];case 4:W=$.sent(),$.label=5;case 5:return[4,q(null,W)];case 6:return $.sent(),[3,8];case 7:if(X=$.sent(),!this.flags||0===Object.keys(this.flags).length)throw X;return Q=X instanceof Error?X:new Error("".concat(X)),null===(a=this.onError)||void 0===a||a.call(this,Q),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:l({},_),traitsChanged:l({},null===(o=d.identity)||void 0===o?void 0:o.traits)},this._loadedState(null,v.DEFAULT_FLAGS));else if(this.flags&&(Y=null,0===Object.keys(this.flags).length&&(Y=H),this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(s=d.identity)||void 0===s?void 0:s.traits)},this._loadedState(Y,v.DEFAULT_FLAGS)),Y))throw new Error(Y);$.label=12;case 12:return[3,14];case 13:throw z=$.sent(),this.log("Error during initialisation ",z),Q=z instanceof Error?z:new Error("".concat(z)),null===(r=this.onError)||void 0===r||r.call(this,Q),z;case 14:return[2]}}))}))},m.prototype.getAllFlags=function(){return this.flags},m.prototype.identify=function(t,e,i){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:i,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],i=t[1];return[e,s(i)?i:{value:i}]})))),this.initialised?this.getFlags():Promise.resolve()},m.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},m.prototype.setState=function(t){var e,i;t&&(this.initialised=!0,this.api=t.api||this.api||y,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(i=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===i?void 0:i.identifier,this.log("setState called",this))},m.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},m.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},m.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},m.prototype._loadedState=function(t,e,i){return void 0===t&&(t=null),void 0===i&&(i=!1),{error:t,isFetching:i,isLoading:!1,source:e}},m.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,n(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},m.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),f.setItem(this.getStorageKey(),t)}},m.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);f.setItem(p,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},m.prototype.initPipelineAnalytics=function(t){var e,i,n,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=c(t.analyticsServerUrl),this.evaluationAnalyticsMaxBuffer=null!==(e=t.maxBuffer)&&void 0!==e?e:1e3,this.pipelineFlushInterval=null!==(i=t.flushInterval)&&void 0!==i?i:1e4,this.pipelineEvents=[],this.pipelineFlushInterval>0&&(this.pipelineAnalyticsInterval=setInterval(this.flushPipelineAnalytics,this.pipelineFlushInterval),null===(a=null===(n=this.pipelineAnalyticsInterval)||void 0===n?void 0:n.unref)||void 0===a||a.call(n))},m.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},m.prototype.currentTraitsSnapshot=function(){var e;return(null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.traits)?t({},this.evaluationContext.identity.traits):null},m.prototype.getPageUrl=function(){return"undefined"!=typeof window&&window.location?window.location.href:null},m.prototype.getEventMetadata=function(e){var i=this.getPageUrl();return t(t(t({},e||{}),i?{page_url:i}:{}),{sdk_version:"11.0.0-internal.7"})},m.prototype.buildAnalyticEvent=function(t,e,i){var n,a,l,o,s;return{event_id:e,event_type:t,evaluated_at:null!==(n=null==i?void 0:i.timestamp)&&void 0!==n?n:Date.now(),identity_identifier:null!==(l=null===(a=this.evaluationContext.identity)||void 0===a?void 0:a.identifier)&&void 0!==l?l:null,enabled:null!==(o=null==i?void 0:i.enabled)&&void 0!==o?o:null,value:null!==(s=null==i?void 0:i.value)&&void 0!==s?s:null,traits:this.currentTraitsSnapshot(),metadata:this.getEventMetadata(null==i?void 0:i.extraMetadata)}},m.prototype.recordPipelineEvent=function(t){var e,i,n,a,l=t.toLowerCase().replace(/ /g,"_"),o=this.flags&&this.flags[l],s="".concat(null!==(i=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==i?i:"none","|").concat(null!==(n=null==o?void 0:o.enabled)&&void 0!==n&&n,"|").concat(null!==(a=null==o?void 0:o.value)&&void 0!==a?a:"null");if(this.pipelineRecordedKeys.get(l)!==s){this.pipelineRecordedKeys.set(l,s);var r=this.buildAnalyticEvent(d.FLAG_EVALUATION,l,{enabled:o?o.enabled:null,value:o?o.value:null,extraMetadata:o?{id:o.id}:void 0});this.pipelineEvents.push(r),(0===this.pipelineFlushInterval||this.pipelineEvents.length>=this.evaluationAnalyticsMaxBuffer)&&this.flushPipelineAnalytics()}},m.prototype.setLoadingState=function(e){var i;a(e,this.loadingState)||(this.loadingState=t({},e),this.log("Loading state changed",e),null===(i=this._triggerLoadingState)||void 0===i||i.call(this))},m.prototype.setupRealtime=function(t,e){var i=this,n=t+"sse/environments/"+e+"/stream";g?this.eventSource||(this.log("Creating event source with url "+n),this.eventSource=new g(n),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){i.log("Could not parse sse event",t)}e?!i.timestamp||e>i.timestamp?i.isLoading?i.log("updated_at is new, but flags are loading",t.data,i.timestamp):(i.log("updated_at is new, fetching flags",t.data,i.timestamp),i.getFlags()):i.log("updated_at is outdated, skipping get flags",t.data,i.timestamp):i.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},m}();function S(t){var e=t.fetch,i=t.AsyncStorage,n=t.eventSource;return new m({fetch:e,AsyncStorage:i,eventSource:n})}var C=S({}),E=function(){return S({})};export{v as FlagSource,E as createFlagsmithInstance,C as default};
2
2
  //# sourceMappingURL=next-middleware.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flagsmith/flagsmith",
3
- "version": "11.0.0-internal.6",
3
+ "version": "11.0.0-internal.7",
4
4
  "description": "Feature flagging to support continuous development",
5
5
  "main": "./index.js",
6
6
  "module": "./index.mjs",
@@ -1,2 +1,2 @@
1
1
  // Auto-generated by write-version.js
2
- export const SDK_VERSION = "11.0.0-internal.6";
2
+ export const SDK_VERSION = "11.0.0-internal.7";
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "11.0.0-internal.6";
1
+ export declare const SDK_VERSION = "11.0.0-internal.7";