@flagsmith/flagsmith 11.0.0-internal.3 → 11.0.0-internal.4
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 +1 -1
- package/index.mjs +1 -1
- package/isomorphic.js +1 -1
- package/isomorphic.mjs +1 -1
- package/next-middleware.js +1 -1
- package/next-middleware.mjs +1 -1
- package/package.json +1 -1
- package/src/types.d.ts +3 -3
- package/src/utils/version.ts +1 -1
- package/types.d.ts +3 -3
- package/utils/version.d.ts +1 -1
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{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((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:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){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,s])}}}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 s(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 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 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 h(t){return n(n({},t),{identity:t.identity?n(n({},t.identity),{traits:c(t.identity.traits||{})}):void 0})}function v(t){return t.endsWith("/")?t:t+"/"}var d,g,f="11.0.0-internal.3";t.FlagSource=void 0,(d=t.FlagSource||(t.FlagSource={})).NONE="NONE",d.DEFAULT_FLAGS="DEFAULT_FLAGS",d.CACHE="CACHE",d.SERVER="SERVER";var p,y=null,m="FLAGSMITH_EVENT",S=m,C="https://edge.api.flagsmith.com/api/v1/",_="flagsmith_value_",E="flagsmith_enabled_",b="flagsmith_trait_",x=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 h=e.flags,v=e.traits,d=e.identifier;o.isLoading=!1;var g={},f={};v=v||[],(h=h||[]).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}})),o.oldFlags=n({},o.flags);var p=s(o.oldFlags,g),y=s(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[b+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){l(C,_+t,o.getValue(t,{skipAnalytics:!0})),l(C,E+t,o.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=o.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){l(C,b+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,s,l;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,this.pipelineEvents=[],this.pipelineRecordedKeys.clear(),r={events:o,environment_key:i},a.label=1;case 1:return a.trys.push([1,3,4,5]),[4,g(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(f)})})];case 2:if(!(s=a.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 l=a.sent(),this.pipelineEvents=o.concat(this.pipelineEvents),this.trimPipelineBuffer(),this.log("Pipeline analytics: flush failed, events re-queued",l),[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=h(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,"_")],s=!1;if(!r&&a&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!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,s)}catch(t){console.error(t)}return s},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,s=o.headers,l={method:e||"GET",body:n,cache:"no-cache",headers:{}};o.evaluationContext.environment&&(l.headers["X-Environment-Key"]=o.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(i=o.applicationMetadata)||void 0===i?void 0:i.name)&&(l.headers["Flagsmith-Application-Name"]=o.applicationMetadata.name),(null===(a=o.applicationMetadata)||void 0===a?void 0:a.version)&&(l.headers["Flagsmith-Application-Version"]=o.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat(f),s&&Object.assign(l.headers,s),g||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 g(t,l).then((function(n){var i,a,r="".concat(null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.identifier);if(u===r){var s=null===(a=n.headers)||void 0===a?void 0:a.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");o.timestamp=l}catch(t){o.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}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(E+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._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)},g=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&&(p=e.eventSource),e.AsyncStorage&&(y=e.AsyncStorage)}return e.prototype.init=function(e){var o,r,l,u;return i(this,void 0,void 0,(function(){var c,d,f,p,m,_,E,b,x,F,O,w,A,I,j,L,P,k,T,N,R,K,U,D,M,J,G,B,H,V,q,W,X,Y,$,z,Q=this;return a(this,(function(Z){switch(Z.label){case 0:c=h(e.evaluationContext||this.evaluationContext),Z.label=1;case 1:if(Z.trys.push([1,13,,14]),d=e.AsyncStorage,f=e._trigger,p=e._triggerLoadingState,m=e.angularHttpClient,_=e.api,E=void 0===_?C:_,b=e.applicationMetadata,x=e.cacheFlags,F=e.cacheOptions,O=e.datadogRum,w=e.defaultFlags,A=e.enableAnalytics,I=e.enableDynatrace,j=e.enableLogs,L=e.environmentID,P=e.evaluationAnalyticsConfig,k=e.eventSourceUrl,T=void 0===k?"https://realtime.flagsmith.com/":k,N=e.fetch,R=e.headers,K=e.identity,U=e.onChange,D=e.onError,M=e.preventFetch,J=e.realtime,G=e.sentryClient,B=e.state,H=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||H?{identifier:K,traits:H?Object.fromEntries(Object.entries(H).map((function(t){return[t[0],{value:t[1]}]}))):{}}:c.identity,this.evaluationContext=c,this.api=v(E),this.headers=R,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=U,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=f||this._trigger,this._triggerLoadingState=p||this._triggerLoadingState,this.onError=function(t){Q.setLoadingState(n(n({},Q.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==D||D(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&&(g=N),this.enableAnalytics=A||!1,this.flags=Object.assign({},w)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==y&&!!x,this.applicationMetadata=b,S="FLAGSMITH_EVENT_"+c.environment.apiKey,d&&(y=d),J&&"undefined"!=typeof window&&this.setupRealtime(T,c.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=n(n({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(B),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),G&&(this.sentryClient=G),m&&(g=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=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(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(m)),y&&this.canUseStorage&&y.getItem(S).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),y&&this.canUseStorage&&y.getItem(S,(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(!y||!this.canUseStorage)return[3,8];q=function(e,o){return i(Q,void 0,void 0,(function(){var e,i,r,l,u,c,v,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),l=!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&&(l=!0,e=s(this.flags,r.flags),this.setState(n(n({},r),{evaluationContext:h(n(n({},r.evaluationContext),{identity:(null===(_=r.evaluationContext)||void 0===_?void 0:_.identity)?n(n({},null===(E=r.evaluationContext)||void 0===E?void 0:E.identity),{traits:n({},H||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),l?(v=!M&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,t.FlagSource.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&l&&!u&&this.log("Skipping API, using cache"),v&&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 M?[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 M?[3,9]:[4,this.getFlags()];case 8:return a.sent(),[3,10];case 9:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},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(V);this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},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]),y.getItemSync?(W=y.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,y.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 M?[3,11]:[4,this.getFlags()];case 10:return Z.sent(),[3,12];case 11:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:s({},w),traitsChanged:s({},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=V),this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(l=c.identity)||void 0===l?void 0:l.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||C,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),y.setItem(this.getStorageKey(),t)}},e.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)}))}},e.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))},e.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},e.prototype.trimPipelineBuffer=function(){if(this.pipelineEvents.length>this.evaluationAnalyticsMaxBuffer){var t=this.pipelineEvents.length-this.evaluationAnalyticsMaxBuffer;this.pipelineEvents=this.pipelineEvents.slice(t)}},e.prototype.recordPipelineEvent=function(t){var e,i,a,o,r,s,l,u=t.toLowerCase().replace(/ /g,"_"),c=this.flags&&this.flags[u],h="".concat(null!==(i=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==i?i:"none","|").concat(null!==(a=null==c?void 0:c.enabled)&&void 0!==a&&a,"|").concat(null!==(o=null==c?void 0:c.value)&&void 0!==o?o:"null");if(this.pipelineRecordedKeys.get(u)!==h){this.pipelineRecordedKeys.set(u,h);var v={event_id:u,event_type:"flag_evaluation",evaluated_at:Date.now(),identity_identifier:null!==(s=null===(r=this.evaluationContext.identity)||void 0===r?void 0:r.identifier)&&void 0!==s?s:"",enabled:c?c.enabled:null,value:c?c.value:null,traits:(null===(l=this.evaluationContext.identity)||void 0===l?void 0:l.traits)?n({},this.evaluationContext.identity.traits):null,metadata:n(n(n({},c?{id:c.id}:{}),"undefined"!=typeof window&&window.location?{page_url:window.location.href}:{}),{sdk_version:f})};this.pipelineEvents.push(v),this.trimPipelineBuffer(),0===this.pipelineFlushInterval&&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";p?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new p(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 F(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new x({fetch:e,AsyncStorage:n,eventSource:i})}var O,w=(O=function(t,e){return O=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])},O(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}O(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),A=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.")},I=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))},L=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),P=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 L;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=A(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=A(j([],I(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([],I(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=[],s={},l=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:l,headers:{keys:function(){return o},entries:function(){return r},get:function(t){return s[t.toLowerCase()]},has:function(t){return t.toLowerCase()in s}}}};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]),s[e]=s[e]?s[e]+","+n:n})),n(l())},a.onerror=i,a.withCredentials="include"==e.credentials,e.headers)a.setRequestHeader(u,e.headers[u]);a.send(e.body||null)}))},T=F({AsyncStorage:e,fetch:k,eventSource:P});"undefined"!=typeof window&&(window.flagsmith=T);t.createFlagsmithInstance=function(){return F({AsyncStorage:e,fetch:k,eventSource:P})},t.default=T,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{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((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:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){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,s])}}}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 s(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 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 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 h(t){return n(n({},t),{identity:t.identity?n(n({},t.identity),{traits:c(t.identity.traits||{})}):void 0})}function v(t){return t.endsWith("/")?t:t+"/"}var d,g,f="11.0.0-internal.4";t.FlagSource=void 0,(d=t.FlagSource||(t.FlagSource={})).NONE="NONE",d.DEFAULT_FLAGS="DEFAULT_FLAGS",d.CACHE="CACHE",d.SERVER="SERVER";var p,y=null,m="FLAGSMITH_EVENT",S=m,C="https://edge.api.flagsmith.com/api/v1/",_="flagsmith_value_",E="flagsmith_enabled_",b="flagsmith_trait_",x=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 h=e.flags,v=e.traits,d=e.identifier;o.isLoading=!1;var g={},f={};v=v||[],(h=h||[]).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}})),o.oldFlags=n({},o.flags);var p=s(o.oldFlags,g),y=s(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[b+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){l(C,_+t,o.getValue(t,{skipAnalytics:!0})),l(C,E+t,o.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=o.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){l(C,b+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,s,l;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,this.pipelineEvents=[],this.pipelineRecordedKeys.clear(),r={events:o,environment_key:i},a.label=1;case 1:return a.trys.push([1,3,4,5]),[4,g(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(f)})})];case 2:if(!(s=a.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 l=a.sent(),this.pipelineEvents=o.concat(this.pipelineEvents),this.trimPipelineBuffer(),this.log("Pipeline analytics: flush failed, events re-queued",l),[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=h(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,"_")],s=!1;if(!r&&a&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!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,s)}catch(t){console.error(t)}return s},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,s=o.headers,l={method:e||"GET",body:n,cache:"no-cache",headers:{}};o.evaluationContext.environment&&(l.headers["X-Environment-Key"]=o.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(i=o.applicationMetadata)||void 0===i?void 0:i.name)&&(l.headers["Flagsmith-Application-Name"]=o.applicationMetadata.name),(null===(a=o.applicationMetadata)||void 0===a?void 0:a.version)&&(l.headers["Flagsmith-Application-Version"]=o.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat(f),s&&Object.assign(l.headers,s),g||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 g(t,l).then((function(n){var i,a,r="".concat(null===(i=o.evaluationContext.identity)||void 0===i?void 0:i.identifier);if(u===r){var s=null===(a=n.headers)||void 0===a?void 0:a.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");o.timestamp=l}catch(t){o.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}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(E+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._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)},g=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&&(p=e.eventSource),e.AsyncStorage&&(y=e.AsyncStorage)}return e.prototype.init=function(e){var o,r,l,u;return i(this,void 0,void 0,(function(){var c,d,f,p,m,_,E,b,x,F,O,w,A,I,j,L,P,k,T,N,R,K,U,D,M,J,G,B,H,V,q,W,X,Y,$,z,Q=this;return a(this,(function(Z){switch(Z.label){case 0:c=h(e.evaluationContext||this.evaluationContext),Z.label=1;case 1:if(Z.trys.push([1,13,,14]),d=e.AsyncStorage,f=e._trigger,p=e._triggerLoadingState,m=e.angularHttpClient,_=e.api,E=void 0===_?C:_,b=e.applicationMetadata,x=e.cacheFlags,F=e.cacheOptions,O=e.datadogRum,w=e.defaultFlags,A=e.enableAnalytics,I=e.enableDynatrace,j=e.enableLogs,L=e.environmentID,P=e.evaluationAnalyticsConfig,k=e.eventSourceUrl,T=void 0===k?"https://realtime.flagsmith.com/":k,N=e.fetch,R=e.headers,K=e.identity,U=e.onChange,D=e.onError,M=e.preventFetch,J=e.realtime,G=e.sentryClient,B=e.state,H=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||H?{identifier:K,traits:H?Object.fromEntries(Object.entries(H).map((function(t){return[t[0],{value:t[1]}]}))):{}}:c.identity,this.evaluationContext=c,this.api=v(E),this.headers=R,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=U,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=f||this._trigger,this._triggerLoadingState=p||this._triggerLoadingState,this.onError=function(t){Q.setLoadingState(n(n({},Q.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==D||D(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&&(g=N),this.enableAnalytics=A||!1,this.flags=Object.assign({},w)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==y&&!!x,this.applicationMetadata=b,S="FLAGSMITH_EVENT_"+c.environment.apiKey,d&&(y=d),J&&"undefined"!=typeof window&&this.setupRealtime(T,c.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=n(n({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(B),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),G&&(this.sentryClient=G),m&&(g=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=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(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(m)),y&&this.canUseStorage&&y.getItem(S).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),y&&this.canUseStorage&&y.getItem(S,(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(!y||!this.canUseStorage)return[3,8];q=function(e,o){return i(Q,void 0,void 0,(function(){var e,i,r,l,u,c,v,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),l=!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&&(l=!0,e=s(this.flags,r.flags),this.setState(n(n({},r),{evaluationContext:h(n(n({},r.evaluationContext),{identity:(null===(_=r.evaluationContext)||void 0===_?void 0:_.identity)?n(n({},null===(E=r.evaluationContext)||void 0===E?void 0:E.identity),{traits:n({},H||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),l?(v=!M&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,t.FlagSource.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&l&&!u&&this.log("Skipping API, using cache"),v&&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 M?[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 M?[3,9]:[4,this.getFlags()];case 8:return a.sent(),[3,10];case 9:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},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(V);this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},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]),y.getItemSync?(W=y.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,y.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 M?[3,11]:[4,this.getFlags()];case 10:return Z.sent(),[3,12];case 11:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:s({},w),traitsChanged:s({},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=V),this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(l=c.identity)||void 0===l?void 0:l.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||C,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),y.setItem(this.getStorageKey(),t)}},e.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)}))}},e.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))},e.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},e.prototype.trimPipelineBuffer=function(){if(this.pipelineEvents.length>this.evaluationAnalyticsMaxBuffer){var t=this.pipelineEvents.length-this.evaluationAnalyticsMaxBuffer;this.pipelineEvents=this.pipelineEvents.slice(t)}},e.prototype.recordPipelineEvent=function(t){var e,i,a,o,r,s,l,u=t.toLowerCase().replace(/ /g,"_"),c=this.flags&&this.flags[u],h="".concat(null!==(i=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==i?i:"none","|").concat(null!==(a=null==c?void 0:c.enabled)&&void 0!==a&&a,"|").concat(null!==(o=null==c?void 0:c.value)&&void 0!==o?o:"null");if(this.pipelineRecordedKeys.get(u)!==h){this.pipelineRecordedKeys.set(u,h);var v={event_id:u,event_type:"flag_evaluation",evaluated_at:Date.now(),identity_identifier:null!==(s=null===(r=this.evaluationContext.identity)||void 0===r?void 0:r.identifier)&&void 0!==s?s:"",enabled:c?c.enabled:null,value:c?c.value:null,traits:(null===(l=this.evaluationContext.identity)||void 0===l?void 0:l.traits)?n({},this.evaluationContext.identity.traits):null,metadata:n(n(n({},c?{id:c.id}:{}),"undefined"!=typeof window&&window.location?{page_url:window.location.href}:{}),{sdk_version:f})};this.pipelineEvents.push(v),this.trimPipelineBuffer(),0===this.pipelineFlushInterval&&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";p?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new p(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 F(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new x({fetch:e,AsyncStorage:n,eventSource:i})}var O,w=(O=function(t,e){return O=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])},O(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}O(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),A=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.")},I=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))},L=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),P=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 L;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=A(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=A(j([],I(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([],I(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=[],s={},l=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:l,headers:{keys:function(){return o},entries:function(){return r},get:function(t){return s[t.toLowerCase()]},has:function(t){return t.toLowerCase()in s}}}};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]),s[e]=s[e]?s[e]+","+n:n})),n(l())},a.onerror=i,a.withCredentials="include"==e.credentials,e.headers)a.setRequestHeader(u,e.headers[u]);a.send(e.body||null)}))},T=F({AsyncStorage:e,fetch:k,eventSource:P});"undefined"!=typeof window&&(window.flagsmith=T);t.createFlagsmithInstance=function(){return F({AsyncStorage:e,fetch:k,eventSource:P})},t.default=T,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{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((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:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){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,s])}}}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 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 l(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,l(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 h(t){return t.endsWith("/")?t:t+"/"}var v,d;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(v||(v={}));var g,f=null,p="FLAGSMITH_EVENT",y="https://edge.api.flagsmith.com/api/v1/",m=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),l=function(t){var n,i,l,u;if(t&&o==="".concat(a.getContext().identity)){var c=t.flags,h=t.traits,d=t.identifier;a.isLoading=!1;var g={},f={};h=h||[],(c=c||[]).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}})),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,v.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===(l=a.evaluationContext.identity)||void 0===l?void 0:l.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){s(C,"flagsmith_value_"+t,a.getValue(t,{skipAnalytics:!0})),s(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){s(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:{}}),l(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 l({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,s,l;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,this.pipelineEvents=[],this.pipelineRecordedKeys.clear(),r={events:o,environment_key:a},i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,d(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.3")})})];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 l=i.sent(),this.pipelineEvents=o.concat(this.pipelineEvents),this.trimPipelineBuffer(),this.log("Pipeline analytics: flush failed, events re-queued",l),[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,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,l(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,"_")],s=!1;if(!r&&o&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!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,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,n){var i,o,r,s=a.headers,l={method:e||"GET",body:n,cache:"no-cache",headers:{}};a.evaluationContext.environment&&(l.headers["X-Environment-Key"]=a.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(i=a.applicationMetadata)||void 0===i?void 0:i.name)&&(l.headers["Flagsmith-Application-Name"]=a.applicationMetadata.name),(null===(o=a.applicationMetadata)||void 0===o?void 0:o.version)&&(l.headers["Flagsmith-Application-Version"]=a.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("11.0.0-internal.3"),s&&Object.assign(l.headers,s),d||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 d(t,l).then((function(n){var i,o,r="".concat(null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.identifier);if(u===r){var s=null===(o=n.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");a.timestamp=l}catch(t){a.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}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._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)},d=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&&(g=t.eventSource),t.AsyncStorage&&(f=t.AsyncStorage)}return t.prototype.init=function(t){var a,o,s,l;return n(this,void 0,void 0,(function(){var u,g,m,S,C,_,E,b,x,O,F,w,A,I,L,j,P,k,T,N,R,K,U,D,M,J,G,B,H,V,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]),g=t.AsyncStorage,m=t._trigger,S=t._triggerLoadingState,C=t.angularHttpClient,_=t.api,E=void 0===_?y:_,b=t.applicationMetadata,x=t.cacheFlags,O=t.cacheOptions,F=t.datadogRum,w=t.defaultFlags,A=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,R=t.headers,K=t.identity,U=t.onChange,D=t.onError,M=t.preventFetch,J=t.realtime,G=t.sentryClient,B=t.state,H=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||H?{identifier:K,traits:H?Object.fromEntries(Object.entries(H).map((function(t){return[t[0],{value:t[1]}]}))):{}}:u.identity,this.evaluationContext=u,this.api=h(E),this.headers=R,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=U,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=m||this._trigger,this._triggerLoadingState=S||this._triggerLoadingState,this.onError=function(t){Q.setLoadingState(e(e({},Q.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==D||D(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&&(d=N),this.enableAnalytics=A||!1,this.flags=Object.assign({},w)||{},this.datadogRum=F||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==f&&!!x,this.applicationMetadata=b,p="FLAGSMITH_EVENT_"+u.environment.apiKey,g&&(f=g),J&&"undefined"!=typeof window&&this.setupRealtime(T,u.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:v.DEFAULT_FLAGS})),this.setState(B),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),G&&(this.sentryClient=G),C&&(d=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=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(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(C)),f&&this.canUseStorage&&f.getItem(p).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),f&&this.canUseStorage&&f.getItem(p,(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(!f||!this.canUseStorage)return[3,8];q=function(t,a){return n(Q,void 0,void 0,(function(){var t,n,o,s,l,u,h,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),s=!1,l=!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"),l=!0,u=!0)),u&&(s=!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({},H||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),s?(h=!M&&(!this.cacheOptions.skipAPI||l),this._onChange(null,{isFromServer:!1,flagsChanged:t,traitsChanged:n},this._loadedState(null,v.CACHE,h)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!l&&this.log("Skipping API, using cache"),h&&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 M?[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 M?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(w)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,v.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);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,v.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},Z.label=2;case 2:return Z.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=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 M?[3,11]:[4,this.getFlags()];case 10:return Z.sent(),[3,12];case 11:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:r({},w),traitsChanged:r({},null===(o=u.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=V),this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(s=u.identity)||void 0===s?void 0:s.traits)},this._loadedState(Y,v.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===(l=this.onError)||void 0===l||l.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,l(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||y,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),f.setItem(this.getStorageKey(),t)}},t.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)}))}},t.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))},t.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},t.prototype.trimPipelineBuffer=function(){if(this.pipelineEvents.length>this.evaluationAnalyticsMaxBuffer){var t=this.pipelineEvents.length-this.evaluationAnalyticsMaxBuffer;this.pipelineEvents=this.pipelineEvents.slice(t)}},t.prototype.recordPipelineEvent=function(t){var n,i,a,o,r,s,l,u=t.toLowerCase().replace(/ /g,"_"),c=this.flags&&this.flags[u],h="".concat(null!==(i=null===(n=this.evaluationContext.identity)||void 0===n?void 0:n.identifier)&&void 0!==i?i:"none","|").concat(null!==(a=null==c?void 0:c.enabled)&&void 0!==a&&a,"|").concat(null!==(o=null==c?void 0:c.value)&&void 0!==o?o:"null");if(this.pipelineRecordedKeys.get(u)!==h){this.pipelineRecordedKeys.set(u,h);var v={event_id:u,event_type:"flag_evaluation",evaluated_at:Date.now(),identity_identifier:null!==(s=null===(r=this.evaluationContext.identity)||void 0===r?void 0:r.identifier)&&void 0!==s?s:"",enabled:c?c.enabled:null,value:c?c.value:null,traits:(null===(l=this.evaluationContext.identity)||void 0===l?void 0:l.traits)?e({},this.evaluationContext.identity.traits):null,metadata:e(e(e({},c?{id:c.id}:{}),"undefined"!=typeof window&&window.location?{page_url:window.location.href}:{}),{sdk_version:"11.0.0-internal.3"})};this.pipelineEvents.push(v),this.trimPipelineBuffer(),0===this.pipelineFlushInterval&&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";g?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new g(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 S(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new m({fetch:e,AsyncStorage:n,eventSource:i})}var C,_=(C=function(t,e){return C=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])},C(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}C(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),E=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.")},b=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},x=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))},O=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,t),e}(Error),F=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 O;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=E(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=E(x([],b(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]=x(x([],b(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=[],s={},l=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:l,headers:{keys:function(){return o},entries:function(){return r},get:function(t){return s[t.toLowerCase()]},has:function(t){return t.toLowerCase()in s}}}};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]),s[e]=s[e]?s[e]+","+n:n})),n(l())},a.onerror=i,a.withCredentials="include"==e.credentials,e.headers)a.setRequestHeader(u,e.headers[u]);a.send(e.body||null)}))},A=S({AsyncStorage:t,fetch:w,eventSource:F});"undefined"!=typeof window&&(window.flagsmith=A);var I=function(){return S({AsyncStorage:t,fetch:w,eventSource:F})};export{v as FlagSource,I as createFlagsmithInstance,A 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{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((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:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){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,s])}}}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 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 l(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,l(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 h(t){return t.endsWith("/")?t:t+"/"}var v,d;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(v||(v={}));var g,f=null,p="FLAGSMITH_EVENT",y="https://edge.api.flagsmith.com/api/v1/",m=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),l=function(t){var n,i,l,u;if(t&&o==="".concat(a.getContext().identity)){var c=t.flags,h=t.traits,d=t.identifier;a.isLoading=!1;var g={},f={};h=h||[],(c=c||[]).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}})),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,v.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===(l=a.evaluationContext.identity)||void 0===l?void 0:l.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){s(C,"flagsmith_value_"+t,a.getValue(t,{skipAnalytics:!0})),s(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){s(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:{}}),l(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 l({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,s,l;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,this.pipelineEvents=[],this.pipelineRecordedKeys.clear(),r={events:o,environment_key:a},i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,d(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.4")})})];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 l=i.sent(),this.pipelineEvents=o.concat(this.pipelineEvents),this.trimPipelineBuffer(),this.log("Pipeline analytics: flush failed, events re-queued",l),[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,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,l(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,"_")],s=!1;if(!r&&o&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!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,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,n){var i,o,r,s=a.headers,l={method:e||"GET",body:n,cache:"no-cache",headers:{}};a.evaluationContext.environment&&(l.headers["X-Environment-Key"]=a.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(i=a.applicationMetadata)||void 0===i?void 0:i.name)&&(l.headers["Flagsmith-Application-Name"]=a.applicationMetadata.name),(null===(o=a.applicationMetadata)||void 0===o?void 0:o.version)&&(l.headers["Flagsmith-Application-Version"]=a.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("11.0.0-internal.4"),s&&Object.assign(l.headers,s),d||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 d(t,l).then((function(n){var i,o,r="".concat(null===(i=a.evaluationContext.identity)||void 0===i?void 0:i.identifier);if(u===r){var s=null===(o=n.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");a.timestamp=l}catch(t){a.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}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._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)},d=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&&(g=t.eventSource),t.AsyncStorage&&(f=t.AsyncStorage)}return t.prototype.init=function(t){var a,o,s,l;return n(this,void 0,void 0,(function(){var u,g,m,S,C,_,E,b,x,O,F,w,A,I,L,j,P,k,T,N,R,K,U,D,M,J,G,B,H,V,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]),g=t.AsyncStorage,m=t._trigger,S=t._triggerLoadingState,C=t.angularHttpClient,_=t.api,E=void 0===_?y:_,b=t.applicationMetadata,x=t.cacheFlags,O=t.cacheOptions,F=t.datadogRum,w=t.defaultFlags,A=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,R=t.headers,K=t.identity,U=t.onChange,D=t.onError,M=t.preventFetch,J=t.realtime,G=t.sentryClient,B=t.state,H=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||H?{identifier:K,traits:H?Object.fromEntries(Object.entries(H).map((function(t){return[t[0],{value:t[1]}]}))):{}}:u.identity,this.evaluationContext=u,this.api=h(E),this.headers=R,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=U,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=m||this._trigger,this._triggerLoadingState=S||this._triggerLoadingState,this.onError=function(t){Q.setLoadingState(e(e({},Q.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==D||D(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&&(d=N),this.enableAnalytics=A||!1,this.flags=Object.assign({},w)||{},this.datadogRum=F||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==f&&!!x,this.applicationMetadata=b,p="FLAGSMITH_EVENT_"+u.environment.apiKey,g&&(f=g),J&&"undefined"!=typeof window&&this.setupRealtime(T,u.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:v.DEFAULT_FLAGS})),this.setState(B),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),G&&(this.sentryClient=G),C&&(d=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=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(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(C)),f&&this.canUseStorage&&f.getItem(p).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),f&&this.canUseStorage&&f.getItem(p,(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(!f||!this.canUseStorage)return[3,8];q=function(t,a){return n(Q,void 0,void 0,(function(){var t,n,o,s,l,u,h,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),s=!1,l=!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"),l=!0,u=!0)),u&&(s=!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({},H||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),s?(h=!M&&(!this.cacheOptions.skipAPI||l),this._onChange(null,{isFromServer:!1,flagsChanged:t,traitsChanged:n},this._loadedState(null,v.CACHE,h)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!l&&this.log("Skipping API, using cache"),h&&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 M?[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 M?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(w)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,v.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);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,v.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},Z.label=2;case 2:return Z.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=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 M?[3,11]:[4,this.getFlags()];case 10:return Z.sent(),[3,12];case 11:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:r({},w),traitsChanged:r({},null===(o=u.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=V),this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(s=u.identity)||void 0===s?void 0:s.traits)},this._loadedState(Y,v.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===(l=this.onError)||void 0===l||l.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,l(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||y,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),f.setItem(this.getStorageKey(),t)}},t.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)}))}},t.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))},t.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},t.prototype.trimPipelineBuffer=function(){if(this.pipelineEvents.length>this.evaluationAnalyticsMaxBuffer){var t=this.pipelineEvents.length-this.evaluationAnalyticsMaxBuffer;this.pipelineEvents=this.pipelineEvents.slice(t)}},t.prototype.recordPipelineEvent=function(t){var n,i,a,o,r,s,l,u=t.toLowerCase().replace(/ /g,"_"),c=this.flags&&this.flags[u],h="".concat(null!==(i=null===(n=this.evaluationContext.identity)||void 0===n?void 0:n.identifier)&&void 0!==i?i:"none","|").concat(null!==(a=null==c?void 0:c.enabled)&&void 0!==a&&a,"|").concat(null!==(o=null==c?void 0:c.value)&&void 0!==o?o:"null");if(this.pipelineRecordedKeys.get(u)!==h){this.pipelineRecordedKeys.set(u,h);var v={event_id:u,event_type:"flag_evaluation",evaluated_at:Date.now(),identity_identifier:null!==(s=null===(r=this.evaluationContext.identity)||void 0===r?void 0:r.identifier)&&void 0!==s?s:"",enabled:c?c.enabled:null,value:c?c.value:null,traits:(null===(l=this.evaluationContext.identity)||void 0===l?void 0:l.traits)?e({},this.evaluationContext.identity.traits):null,metadata:e(e(e({},c?{id:c.id}:{}),"undefined"!=typeof window&&window.location?{page_url:window.location.href}:{}),{sdk_version:"11.0.0-internal.4"})};this.pipelineEvents.push(v),this.trimPipelineBuffer(),0===this.pipelineFlushInterval&&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";g?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new g(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 S(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new m({fetch:e,AsyncStorage:n,eventSource:i})}var C,_=(C=function(t,e){return C=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])},C(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}C(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),E=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.")},b=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},x=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))},O=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,t),e}(Error),F=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 O;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=E(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=E(x([],b(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]=x(x([],b(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=[],s={},l=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:l,headers:{keys:function(){return o},entries:function(){return r},get:function(t){return s[t.toLowerCase()]},has:function(t){return t.toLowerCase()in s}}}};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]),s[e]=s[e]?s[e]+","+n:n})),n(l())},a.onerror=i,a.withCredentials="include"==e.credentials,e.headers)a.setRequestHeader(u,e.headers[u]);a.send(e.body||null)}))},A=S({AsyncStorage:t,fetch:w,eventSource:F});"undefined"!=typeof window&&(window.flagsmith=A);var I=function(){return S({AsyncStorage:t,fetch:w,eventSource:F})};export{v as FlagSource,I as createFlagsmithInstance,A 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 h(t){return n(n({},t),{identity:t.identity?n(n({},t.identity),{traits:c(t.identity.traits||{})}):void 0})}function v(t){return t.endsWith("/")?t:t+"/"}var d,g,f="11.0.0-internal.3";t.FlagSource=void 0,(d=t.FlagSource||(t.FlagSource={})).NONE="NONE",d.DEFAULT_FLAGS="DEFAULT_FLAGS",d.CACHE="CACHE",d.SERVER="SERVER";var p,y=null,m="FLAGSMITH_EVENT",S=m,C="https://edge.api.flagsmith.com/api/v1/",_="flagsmith_value_",E="flagsmith_enabled_",b="flagsmith_trait_",x=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 h=e.flags,v=e.traits,d=e.identifier;o.isLoading=!1;var g={},f={};v=v||[],(h=h||[]).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}})),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[b+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,E+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,b+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,this.pipelineEvents=[],this.pipelineRecordedKeys.clear(),r={events:o,environment_key:i},a.label=1;case 1:return a.trys.push([1,3,4,5]),[4,g(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(f)})})];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.trimPipelineBuffer(),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=h(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(f),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=o.evaluationContext.identity)||void 0===r?void 0:r.identifier);return g(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(E+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._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)},g=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&&(p=e.eventSource),e.AsyncStorage&&(y=e.AsyncStorage)}return e.prototype.init=function(e){var o,r,s,u;return i(this,void 0,void 0,(function(){var c,d,f,p,m,_,E,b,x,F,O,w,A,I,j,L,P,k,T,N,K,R,U,D,M,G,J,B,V,H,q,W,X,Y,z,Q,Z=this;return a(this,(function($){switch($.label){case 0:c=h(e.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),d=e.AsyncStorage,f=e._trigger,p=e._triggerLoadingState,m=e.angularHttpClient,_=e.api,E=void 0===_?C:_,b=e.applicationMetadata,x=e.cacheFlags,F=e.cacheOptions,O=e.datadogRum,w=e.defaultFlags,A=e.enableAnalytics,I=e.enableDynatrace,j=e.enableLogs,L=e.environmentID,P=e.evaluationAnalyticsConfig,k=e.eventSourceUrl,T=void 0===k?"https://realtime.flagsmith.com/":k,N=e.fetch,K=e.headers,R=e.identity,U=e.onChange,D=e.onError,M=e.preventFetch,G=e.realtime,J=e.sentryClient,B=e.state,V=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=R||V?{identifier:R,traits:V?Object.fromEntries(Object.entries(V).map((function(t){return[t[0],{value:t[1]}]}))):{}}:c.identity,this.evaluationContext=c,this.api=v(E),this.headers=K,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=U,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(n(n({},Z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==D||D(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&&(g=N),this.enableAnalytics=A||!1,this.flags=Object.assign({},w)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==y&&!!x,this.applicationMetadata=b,S="FLAGSMITH_EVENT_"+c.environment.apiKey,d&&(y=d),G&&"undefined"!=typeof window&&this.setupRealtime(T,c.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=n(n({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(B),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),m&&(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)})}}))}}(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,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(!y||!this.canUseStorage)return[3,8];q=function(e,o){return i(Z,void 0,void 0,(function(){var e,i,r,s,u,c,v,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:h(n(n({},r.evaluationContext),{identity:(null===(_=r.evaluationContext)||void 0===_?void 0:_.identity)?n(n({},null===(E=r.evaluationContext)||void 0===E?void 0:E.identity),{traits:n({},V||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),s?(v=!M&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,t.FlagSource.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!u&&this.log("Skipping API, using cache"),v&&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 M?[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 M?[3,9]:[4,this.getFlags()];case 8:return a.sent(),[3,10];case 9:if(w)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]),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===(o=this.onError)||void 0===o||o.call(this,Q),[3,8];case 8:return[3,12];case 9:return M?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:l({},w),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||C,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),y.setItem(this.getStorageKey(),t)}},e.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)}))}},e.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))},e.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},e.prototype.trimPipelineBuffer=function(){if(this.pipelineEvents.length>this.evaluationAnalyticsMaxBuffer){var t=this.pipelineEvents.length-this.evaluationAnalyticsMaxBuffer;this.pipelineEvents=this.pipelineEvents.slice(t)}},e.prototype.recordPipelineEvent=function(t){var e,i,a,o,r,l,s,u=t.toLowerCase().replace(/ /g,"_"),c=this.flags&&this.flags[u],h="".concat(null!==(i=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==i?i:"none","|").concat(null!==(a=null==c?void 0:c.enabled)&&void 0!==a&&a,"|").concat(null!==(o=null==c?void 0:c.value)&&void 0!==o?o:"null");if(this.pipelineRecordedKeys.get(u)!==h){this.pipelineRecordedKeys.set(u,h);var v={event_id:u,event_type:"flag_evaluation",evaluated_at:Date.now(),identity_identifier:null!==(l=null===(r=this.evaluationContext.identity)||void 0===r?void 0:r.identifier)&&void 0!==l?l:"",enabled:c?c.enabled:null,value:c?c.value:null,traits:(null===(s=this.evaluationContext.identity)||void 0===s?void 0:s.traits)?n({},this.evaluationContext.identity.traits):null,metadata:n(n(n({},c?{id:c.id}:{}),"undefined"!=typeof window&&window.location?{page_url:window.location.href}:{}),{sdk_version:f})};this.pipelineEvents.push(v),this.trimPipelineBuffer(),0===this.pipelineFlushInterval&&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";p?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new p(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 F(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new x({fetch:e,AsyncStorage:n,eventSource:i})}var O,w=(O=function(t,e){return O=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])},O(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}O(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),A=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.")},I=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))},L=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),P=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 L;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=A(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=A(j([],I(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([],I(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=F({AsyncStorage:e,eventSource:"undefined"!=typeof window?P:null});"undefined"!=typeof window&&(window.flagsmith=k);t.createFlagsmithInstance=function(){return F({AsyncStorage:e,eventSource:"undefined"!=typeof window?P: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 h(t){return n(n({},t),{identity:t.identity?n(n({},t.identity),{traits:c(t.identity.traits||{})}):void 0})}function v(t){return t.endsWith("/")?t:t+"/"}var d,g,f="11.0.0-internal.4";t.FlagSource=void 0,(d=t.FlagSource||(t.FlagSource={})).NONE="NONE",d.DEFAULT_FLAGS="DEFAULT_FLAGS",d.CACHE="CACHE",d.SERVER="SERVER";var p,y=null,m="FLAGSMITH_EVENT",S=m,C="https://edge.api.flagsmith.com/api/v1/",_="flagsmith_value_",E="flagsmith_enabled_",b="flagsmith_trait_",x=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 h=e.flags,v=e.traits,d=e.identifier;o.isLoading=!1;var g={},f={};v=v||[],(h=h||[]).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}})),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[b+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,E+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,b+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,this.pipelineEvents=[],this.pipelineRecordedKeys.clear(),r={events:o,environment_key:i},a.label=1;case 1:return a.trys.push([1,3,4,5]),[4,g(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(f)})})];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.trimPipelineBuffer(),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=h(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(f),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=o.evaluationContext.identity)||void 0===r?void 0:r.identifier);return g(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(E+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._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)},g=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&&(p=e.eventSource),e.AsyncStorage&&(y=e.AsyncStorage)}return e.prototype.init=function(e){var o,r,s,u;return i(this,void 0,void 0,(function(){var c,d,f,p,m,_,E,b,x,F,O,w,A,I,j,L,P,k,T,N,K,R,U,D,M,G,J,B,V,H,q,W,X,Y,z,Q,Z=this;return a(this,(function($){switch($.label){case 0:c=h(e.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),d=e.AsyncStorage,f=e._trigger,p=e._triggerLoadingState,m=e.angularHttpClient,_=e.api,E=void 0===_?C:_,b=e.applicationMetadata,x=e.cacheFlags,F=e.cacheOptions,O=e.datadogRum,w=e.defaultFlags,A=e.enableAnalytics,I=e.enableDynatrace,j=e.enableLogs,L=e.environmentID,P=e.evaluationAnalyticsConfig,k=e.eventSourceUrl,T=void 0===k?"https://realtime.flagsmith.com/":k,N=e.fetch,K=e.headers,R=e.identity,U=e.onChange,D=e.onError,M=e.preventFetch,G=e.realtime,J=e.sentryClient,B=e.state,V=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=R||V?{identifier:R,traits:V?Object.fromEntries(Object.entries(V).map((function(t){return[t[0],{value:t[1]}]}))):{}}:c.identity,this.evaluationContext=c,this.api=v(E),this.headers=K,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=U,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(n(n({},Z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==D||D(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&&(g=N),this.enableAnalytics=A||!1,this.flags=Object.assign({},w)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==y&&!!x,this.applicationMetadata=b,S="FLAGSMITH_EVENT_"+c.environment.apiKey,d&&(y=d),G&&"undefined"!=typeof window&&this.setupRealtime(T,c.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=n(n({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(B),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),m&&(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)})}}))}}(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,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(!y||!this.canUseStorage)return[3,8];q=function(e,o){return i(Z,void 0,void 0,(function(){var e,i,r,s,u,c,v,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:h(n(n({},r.evaluationContext),{identity:(null===(_=r.evaluationContext)||void 0===_?void 0:_.identity)?n(n({},null===(E=r.evaluationContext)||void 0===E?void 0:E.identity),{traits:n({},V||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),s?(v=!M&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,t.FlagSource.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!u&&this.log("Skipping API, using cache"),v&&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 M?[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 M?[3,9]:[4,this.getFlags()];case 8:return a.sent(),[3,10];case 9:if(w)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]),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===(o=this.onError)||void 0===o||o.call(this,Q),[3,8];case 8:return[3,12];case 9:return M?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:l({},w),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||C,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),y.setItem(this.getStorageKey(),t)}},e.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)}))}},e.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))},e.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},e.prototype.trimPipelineBuffer=function(){if(this.pipelineEvents.length>this.evaluationAnalyticsMaxBuffer){var t=this.pipelineEvents.length-this.evaluationAnalyticsMaxBuffer;this.pipelineEvents=this.pipelineEvents.slice(t)}},e.prototype.recordPipelineEvent=function(t){var e,i,a,o,r,l,s,u=t.toLowerCase().replace(/ /g,"_"),c=this.flags&&this.flags[u],h="".concat(null!==(i=null===(e=this.evaluationContext.identity)||void 0===e?void 0:e.identifier)&&void 0!==i?i:"none","|").concat(null!==(a=null==c?void 0:c.enabled)&&void 0!==a&&a,"|").concat(null!==(o=null==c?void 0:c.value)&&void 0!==o?o:"null");if(this.pipelineRecordedKeys.get(u)!==h){this.pipelineRecordedKeys.set(u,h);var v={event_id:u,event_type:"flag_evaluation",evaluated_at:Date.now(),identity_identifier:null!==(l=null===(r=this.evaluationContext.identity)||void 0===r?void 0:r.identifier)&&void 0!==l?l:"",enabled:c?c.enabled:null,value:c?c.value:null,traits:(null===(s=this.evaluationContext.identity)||void 0===s?void 0:s.traits)?n({},this.evaluationContext.identity.traits):null,metadata:n(n(n({},c?{id:c.id}:{}),"undefined"!=typeof window&&window.location?{page_url:window.location.href}:{}),{sdk_version:f})};this.pipelineEvents.push(v),this.trimPipelineBuffer(),0===this.pipelineFlushInterval&&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";p?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new p(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 F(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new x({fetch:e,AsyncStorage:n,eventSource:i})}var O,w=(O=function(t,e){return O=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])},O(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}O(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),A=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.")},I=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))},L=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),P=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 L;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=A(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=A(j([],I(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([],I(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=F({AsyncStorage:e,eventSource:"undefined"!=typeof window?P:null});"undefined"!=typeof window&&(window.flagsmith=k);t.createFlagsmithInstance=function(){return F({AsyncStorage:e,eventSource:"undefined"!=typeof window?P: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 h(t){return t.endsWith("/")?t:t+"/"}var v,d;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(v||(v={}));var g,f=null,p="FLAGSMITH_EVENT",y="https://edge.api.flagsmith.com/api/v1/",m=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,h=t.traits,d=t.identifier;a.isLoading=!1;var g={},f={};h=h||[],(c=c||[]).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}})),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,v.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,this.pipelineEvents=[],this.pipelineRecordedKeys.clear(),r={events:o,environment_key:a},i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,d(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.3")})})];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.trimPipelineBuffer(),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: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,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.3"),l&&Object.assign(s.headers,l),d||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 d(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._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)},d=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&&(g=t.eventSource),t.AsyncStorage&&(f=t.AsyncStorage)}return t.prototype.init=function(t){var a,o,l,s;return n(this,void 0,void 0,(function(){var u,g,m,S,C,_,E,b,x,O,F,w,A,I,j,L,P,k,T,N,K,R,U,D,M,G,J,B,V,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]),g=t.AsyncStorage,m=t._trigger,S=t._triggerLoadingState,C=t.angularHttpClient,_=t.api,E=void 0===_?y:_,b=t.applicationMetadata,x=t.cacheFlags,O=t.cacheOptions,F=t.datadogRum,w=t.defaultFlags,A=t.enableAnalytics,I=t.enableDynatrace,j=t.enableLogs,L=t.environmentID,P=t.evaluationAnalyticsConfig,k=t.eventSourceUrl,T=void 0===k?"https://realtime.flagsmith.com/":k,N=t.fetch,K=t.headers,R=t.identity,U=t.onChange,D=t.onError,M=t.preventFetch,G=t.realtime,J=t.sentryClient,B=t.state,V=t.traits,u.environment=L?{apiKey:L}:u.environment,!u.environment||!u.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(u.identity=R||V?{identifier:R,traits:V?Object.fromEntries(Object.entries(V).map((function(t){return[t[0],{value:t[1]}]}))):{}}:u.identity,this.evaluationContext=u,this.api=h(E),this.headers=K,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=U,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=m||this._trigger,this._triggerLoadingState=S||this._triggerLoadingState,this.onError=function(t){Z.setLoadingState(e(e({},Z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==D||D(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."),N&&(d=N),this.enableAnalytics=A||!1,this.flags=Object.assign({},w)||{},this.datadogRum=F||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==f&&!!x,this.applicationMetadata=b,p="FLAGSMITH_EVENT_"+u.environment.apiKey,g&&(f=g),G&&"undefined"!=typeof window&&this.setupRealtime(T,u.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:v.DEFAULT_FLAGS})),this.setState(B),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&&(d=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)),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(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(!f||!this.canUseStorage)return[3,8];q=function(t,a){return n(Z,void 0,void 0,(function(){var t,n,o,l,s,u,h,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({},V||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),l?(h=!M&&(!this.cacheOptions.skipAPI||s),this._onChange(null,{isFromServer:!1,flagsChanged:t,traitsChanged:n},this._loadedState(null,v.CACHE,h)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&l&&!s&&this.log("Skipping API, using cache"),h&&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 M?[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 M?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(w)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,v.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,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 M?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:r({},w),traitsChanged:r({},null===(o=u.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:r({},this.flags),traitsChanged:r({},null===(l=u.identity)||void 0===l?void 0:l.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===(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||y,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),f.setItem(this.getStorageKey(),t)}},t.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)}))}},t.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))},t.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},t.prototype.trimPipelineBuffer=function(){if(this.pipelineEvents.length>this.evaluationAnalyticsMaxBuffer){var t=this.pipelineEvents.length-this.evaluationAnalyticsMaxBuffer;this.pipelineEvents=this.pipelineEvents.slice(t)}},t.prototype.recordPipelineEvent=function(t){var n,i,a,o,r,l,s,u=t.toLowerCase().replace(/ /g,"_"),c=this.flags&&this.flags[u],h="".concat(null!==(i=null===(n=this.evaluationContext.identity)||void 0===n?void 0:n.identifier)&&void 0!==i?i:"none","|").concat(null!==(a=null==c?void 0:c.enabled)&&void 0!==a&&a,"|").concat(null!==(o=null==c?void 0:c.value)&&void 0!==o?o:"null");if(this.pipelineRecordedKeys.get(u)!==h){this.pipelineRecordedKeys.set(u,h);var v={event_id:u,event_type:"flag_evaluation",evaluated_at:Date.now(),identity_identifier:null!==(l=null===(r=this.evaluationContext.identity)||void 0===r?void 0:r.identifier)&&void 0!==l?l:"",enabled:c?c.enabled:null,value:c?c.value:null,traits:(null===(s=this.evaluationContext.identity)||void 0===s?void 0:s.traits)?e({},this.evaluationContext.identity.traits):null,metadata:e(e(e({},c?{id:c.id}:{}),"undefined"!=typeof window&&window.location?{page_url:window.location.href}:{}),{sdk_version:"11.0.0-internal.3"})};this.pipelineEvents.push(v),this.trimPipelineBuffer(),0===this.pipelineFlushInterval&&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";g?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new g(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 S(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new m({fetch:e,AsyncStorage:n,eventSource:i})}var C,_=(C=function(t,e){return C=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])},C(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}C(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),E=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.")},b=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},x=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))},O=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,t),e}(Error),F=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 O;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=E(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=E(x([],b(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]=x(x([],b(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=S({AsyncStorage:t,eventSource:"undefined"!=typeof window?F:null});"undefined"!=typeof window&&(window.flagsmith=w);var A=function(){return S({AsyncStorage:t,eventSource:"undefined"!=typeof window?F:null})};export{v as FlagSource,A 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 h(t){return t.endsWith("/")?t:t+"/"}var v,d;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(v||(v={}));var g,f=null,p="FLAGSMITH_EVENT",y="https://edge.api.flagsmith.com/api/v1/",m=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,h=t.traits,d=t.identifier;a.isLoading=!1;var g={},f={};h=h||[],(c=c||[]).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}})),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,v.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,this.pipelineEvents=[],this.pipelineRecordedKeys.clear(),r={events:o,environment_key:a},i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,d(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.4")})})];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.trimPipelineBuffer(),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: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,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.4"),l&&Object.assign(s.headers,l),d||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 d(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._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)},d=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&&(g=t.eventSource),t.AsyncStorage&&(f=t.AsyncStorage)}return t.prototype.init=function(t){var a,o,l,s;return n(this,void 0,void 0,(function(){var u,g,m,S,C,_,E,b,x,O,F,w,A,I,j,L,P,k,T,N,K,R,U,D,M,G,J,B,V,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]),g=t.AsyncStorage,m=t._trigger,S=t._triggerLoadingState,C=t.angularHttpClient,_=t.api,E=void 0===_?y:_,b=t.applicationMetadata,x=t.cacheFlags,O=t.cacheOptions,F=t.datadogRum,w=t.defaultFlags,A=t.enableAnalytics,I=t.enableDynatrace,j=t.enableLogs,L=t.environmentID,P=t.evaluationAnalyticsConfig,k=t.eventSourceUrl,T=void 0===k?"https://realtime.flagsmith.com/":k,N=t.fetch,K=t.headers,R=t.identity,U=t.onChange,D=t.onError,M=t.preventFetch,G=t.realtime,J=t.sentryClient,B=t.state,V=t.traits,u.environment=L?{apiKey:L}:u.environment,!u.environment||!u.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(u.identity=R||V?{identifier:R,traits:V?Object.fromEntries(Object.entries(V).map((function(t){return[t[0],{value:t[1]}]}))):{}}:u.identity,this.evaluationContext=u,this.api=h(E),this.headers=K,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=U,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=m||this._trigger,this._triggerLoadingState=S||this._triggerLoadingState,this.onError=function(t){Z.setLoadingState(e(e({},Z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==D||D(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."),N&&(d=N),this.enableAnalytics=A||!1,this.flags=Object.assign({},w)||{},this.datadogRum=F||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==f&&!!x,this.applicationMetadata=b,p="FLAGSMITH_EVENT_"+u.environment.apiKey,g&&(f=g),G&&"undefined"!=typeof window&&this.setupRealtime(T,u.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:v.DEFAULT_FLAGS})),this.setState(B),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&&(d=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)),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(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(!f||!this.canUseStorage)return[3,8];q=function(t,a){return n(Z,void 0,void 0,(function(){var t,n,o,l,s,u,h,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({},V||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),l?(h=!M&&(!this.cacheOptions.skipAPI||s),this._onChange(null,{isFromServer:!1,flagsChanged:t,traitsChanged:n},this._loadedState(null,v.CACHE,h)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&l&&!s&&this.log("Skipping API, using cache"),h&&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 M?[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 M?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(w)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,v.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,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 M?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:r({},w),traitsChanged:r({},null===(o=u.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:r({},this.flags),traitsChanged:r({},null===(l=u.identity)||void 0===l?void 0:l.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===(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||y,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),f.setItem(this.getStorageKey(),t)}},t.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)}))}},t.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))},t.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},t.prototype.trimPipelineBuffer=function(){if(this.pipelineEvents.length>this.evaluationAnalyticsMaxBuffer){var t=this.pipelineEvents.length-this.evaluationAnalyticsMaxBuffer;this.pipelineEvents=this.pipelineEvents.slice(t)}},t.prototype.recordPipelineEvent=function(t){var n,i,a,o,r,l,s,u=t.toLowerCase().replace(/ /g,"_"),c=this.flags&&this.flags[u],h="".concat(null!==(i=null===(n=this.evaluationContext.identity)||void 0===n?void 0:n.identifier)&&void 0!==i?i:"none","|").concat(null!==(a=null==c?void 0:c.enabled)&&void 0!==a&&a,"|").concat(null!==(o=null==c?void 0:c.value)&&void 0!==o?o:"null");if(this.pipelineRecordedKeys.get(u)!==h){this.pipelineRecordedKeys.set(u,h);var v={event_id:u,event_type:"flag_evaluation",evaluated_at:Date.now(),identity_identifier:null!==(l=null===(r=this.evaluationContext.identity)||void 0===r?void 0:r.identifier)&&void 0!==l?l:"",enabled:c?c.enabled:null,value:c?c.value:null,traits:(null===(s=this.evaluationContext.identity)||void 0===s?void 0:s.traits)?e({},this.evaluationContext.identity.traits):null,metadata:e(e(e({},c?{id:c.id}:{}),"undefined"!=typeof window&&window.location?{page_url:window.location.href}:{}),{sdk_version:"11.0.0-internal.4"})};this.pipelineEvents.push(v),this.trimPipelineBuffer(),0===this.pipelineFlushInterval&&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";g?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new g(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 S(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new m({fetch:e,AsyncStorage:n,eventSource:i})}var C,_=(C=function(t,e){return C=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])},C(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}C(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),E=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.")},b=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},x=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))},O=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,t),e}(Error),F=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 O;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=E(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=E(x([],b(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]=x(x([],b(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=S({AsyncStorage:t,eventSource:"undefined"!=typeof window?F:null});"undefined"!=typeof window&&(window.flagsmith=w);var A=function(){return S({AsyncStorage:t,eventSource:"undefined"!=typeof window?F:null})};export{v as FlagSource,A as createFlagsmithInstance,w as default};
|
|
2
2
|
//# sourceMappingURL=isomorphic.mjs.map
|
package/next-middleware.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)["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,o){function l(t){try{r(n.next(t))}catch(t){o(t)}}function s(t){try{r(n.throw(t))}catch(t){o(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(l,s)}r((n=n.apply(t,e||[])).next())}))}function n(t,e){var i,n,a,o,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;l;)try{if(i=1,n&&(a=2&o[0]?n.return:o[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,o[1])).done)return a;switch(n=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return l.label++,{value:o[1],done:!1};case 5:l.label++,n=o[1],o=[0];continue;case 7:o=l.ops.pop(),l.trys.pop();continue;default:if(!(a=l.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){l=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){l.label=o[1];break}if(6===o[0]&&l.label<a[1]){l.label=a[1],a=o;break}if(a&&l.label<a[2]){l.label=a[2],l.ops.push(o);break}a[2]&&l.ops.pop(),l.trys.pop();continue}o=e.call(t,l)}catch(t){o=[6,t],n=0}finally{i=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function a(t,e,i){if(i||2===arguments.length)for(var n,a=0,o=e.length;a<o;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 o=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,o;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=(o=Object.keys(e)).length)!==Object.keys(i).length)return!1;for(a=n;0!=a--;)if(!Object.prototype.hasOwnProperty.call(i,o[a]))return!1;for(a=n;0!=a--;){var l=o[a];if(!t(e[l],i[l]))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],a=null==e?void 0:e[i];return!o(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 d(t){return t.endsWith("/")?t:t+"/"}var v,h,g="11.0.0-internal.3";t.FlagSource=void 0,(v=t.FlagSource||(t.FlagSource={})).NONE="NONE",v.DEFAULT_FLAGS="DEFAULT_FLAGS",v.CACHE="CACHE",v.SERVER="SERVER";var f,p=null,y="FLAGSMITH_EVENT",m=y,S="https://edge.api.flagsmith.com/api/v1/",C="flagsmith_value_",b="flagsmith_enabled_",F="flagsmith_trait_",E=function(){function v(a){var o=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var i=o,n=i.api,a=i.evaluationContext;o.log("Get Flags"),o.isLoading=!0,o.loadingState.isFetching||o.setLoadingState(e(e({},o.loadingState),{isFetching:!0}));var r="".concat(o.getContext().identity),u=function(i){var n,a,u,c;if(i&&r==="".concat(o.getContext().identity)){var d=i.flags,v=i.traits,h=i.identifier;o.isLoading=!1;var g={},f={};v=v||[],(d=d||[]).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}})),o.oldFlags=e({},o.flags);var p=l(o.oldFlags,g),y=l(null===(n=o.evaluationContext.identity)||void 0===n?void 0:n.traits,f);if((h||Object.keys(f).length)&&(o.evaluationContext.identity=e(e({},o.evaluationContext.identity),{traits:f}),h&&(o.evaluationContext.identity.identifier=h,o.identity=h)),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[F+t]=o.getTrait(t)}));var S=e(e(e({},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 E={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(o.flags).map((function(t){s(E,C+t,o.getValue(t,{skipAnalytics:!0})),s(E,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(E,F+t,o.getTrait(t))})),o.log("Sending javaLongOrObject traits to dynatrace",E.javaLongOrObject),o.log("Sending date traits to dynatrace",E.date),o.log("Sending shortString traits to dynatrace",E.shortString),o.log("Sending javaDouble to dynatrace",E.javaDouble),o.dtrum.sendSessionProperties(E.javaLongOrObject,E.date,E.shortString,E.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(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||(o.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):o.getJSON(n+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(t){return o.evaluationContext.identity=e(e({},o.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)})):o.getJSON(n+"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 i=o.getState();o.evaluationEvent||(o.evaluationEvent={}),o.evaluationEvent[o.evaluationContext.environment.apiKey]={},o.setState(e(e({},i),{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,i,a,o,l,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,o=this.pipelineEvents,this.pipelineEvents=[],this.pipelineRecordedKeys.clear(),l={events:o,environment_key:a},n.label=1;case 1:return n.trys.push([1,3,4,5]),[4,h(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(l),headers:e({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":a},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat(g)})})];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=o.concat(this.pipelineEvents),this.trimPipelineBuffer(),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=o.flags&&o.flags[t.toLowerCase().replace(/ /g,"_")],a=null;if(n&&(a=n.value),(null==e?void 0:e.skipAnalytics)||i||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,i;return(null===(e=o.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(i=o.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=o.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 o.evaluationContext=e(e({},a),{environment:a.environment||o.evaluationContext.environment}),o.identity=null===(n=null===(i=o.getContext())||void 0===i?void 0:i.identity)||void 0===n?void 0:n.identifier,o.initialised?o.getFlags():Promise.resolve()},this.getContext=function(){return o.evaluationContext},this.updateContext=function(t){return o.setContext(e(e({},o.getContext()),t))},this.setTrait=function(t,i){var n;if(o.api)return o.setContext(e(e({},o.evaluationContext),{identity:e(e({},o.evaluationContext.identity),{traits:e(e({},null===(n=o.evaluationContext.identity)||void 0===n?void 0:n.traits),u(Object.fromEntries([[t,i]])))})}))},this.setTraits=function(t){var i;if(o.api)return o.setContext(e(e({},o.evaluationContext),{identity:e(e({},o.evaluationContext.identity),{traits:e(e({},null===(i=o.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,l=o.flags&&o.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!l&&a&&void 0!==e.fallback?s=null==e?void 0:e.fallback:l&&l.enabled&&(s=!0),(a&&!e.skipAnalytics||!e)&&o.evaluateFlag(t,"ENABLED"),o.sentryClient)try{null===(n=null===(i=o.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=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,i){var n,a,l,s=o.headers,r={method:e||"GET",body:i,cache:"no-cache",headers:{}};o.evaluationContext.environment&&(r.headers["X-Environment-Key"]=o.evaluationContext.environment.apiKey),e&&"GET"!==e&&(r.headers["Content-Type"]="application/json; charset=utf-8"),(null===(n=o.applicationMetadata)||void 0===n?void 0:n.name)&&(r.headers["Flagsmith-Application-Name"]=o.applicationMetadata.name),(null===(a=o.applicationMetadata)||void 0===a?void 0:a.version)&&(r.headers["Flagsmith-Application-Version"]=o.applicationMetadata.version),r.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat(g),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===(l=o.evaluationContext.identity)||void 0===l?void 0:l.identifier);return h(t,r).then((function(i){var n,a,l="".concat(null===(n=o.evaluationContext.identity)||void 0===n?void 0:n.identifier);if(u===l){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");o.timestamp=r}catch(t){o.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return o.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))}))}o.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(l))}))},this.evaluateFlag=function(t,e){if(o.datadogRum&&(o.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?o.datadogRum.client.addFeatureFlagEvaluation(C+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._onChange=function(t,e,i){var n,a;o.setLoadingState(i),null===(n=o.onChange)||void 0===n||n.call(o,t,e,o.loadingState),null===(a=o._trigger)||void 0===a||a.call(o)},h=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&&(f=a.eventSource),a.AsyncStorage&&(p=a.AsyncStorage)}return v.prototype.init=function(a){var o,s,r,u;return i(this,void 0,void 0,(function(){var v,g,f,y,C,b,F,E,x,O,A,w,_,I,j,L,P,k,K,T,R,N,U,D,M,J,G,B,V,H,q,W,X,Y,z,Q,Z=this;return n(this,(function($){switch($.label){case 0:v=c(a.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),g=a.AsyncStorage,f=a._trigger,y=a._triggerLoadingState,C=a.angularHttpClient,b=a.api,F=void 0===b?S:b,E=a.applicationMetadata,x=a.cacheFlags,O=a.cacheOptions,A=a.datadogRum,w=a.defaultFlags,_=a.enableAnalytics,I=a.enableDynatrace,j=a.enableLogs,L=a.environmentID,P=a.evaluationAnalyticsConfig,k=a.eventSourceUrl,K=void 0===k?"https://realtime.flagsmith.com/":k,T=a.fetch,R=a.headers,N=a.identity,U=a.onChange,D=a.onError,M=a.preventFetch,J=a.realtime,G=a.sentryClient,B=a.state,V=a.traits,v.environment=L?{apiKey:L}:v.environment,!v.environment||!v.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(v.identity=N||V?{identifier:N,traits:V?Object.fromEntries(Object.entries(V).map((function(t){return[t[0],{value:t[1]}]}))):{}}:v.identity,this.evaluationContext=v,this.api=d(F),this.headers=R,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=U,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=f||this._trigger,this._triggerLoadingState=y||this._triggerLoadingState,this.onError=function(t){Z.setLoadingState(e(e({},Z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==D||D(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."),T&&(h=T),this.enableAnalytics=_||!1,this.flags=Object.assign({},w)||{},this.datadogRum=A||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==p&&!!x,this.applicationMetadata=E,m="FLAGSMITH_EVENT_"+v.environment.apiKey,g&&(p=g),J&&"undefined"!=typeof window&&this.setupRealtime(K,v.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(B),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),G&&(this.sentryClient=G),C&&(h=function(t){return function(e,i){var n=i.headers,a=i.method,o=i.body,l={headers:n,observe:"response",responseType:"text"},s=function(t,e){var i=t.status,n=t.headers,a=t.body,o=t.error,l=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:o)&&void 0!==t?t:l)&&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,l).subscribe(n,r);case"POST":case"PUT":return t.post(e,null!=o?o:"",l).subscribe(n,r);default:return r({status:405,message:"Unsupported method: ".concat(a)})}}))}}(C)),p&&this.canUseStorage&&p.getItem(m).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(m,(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(!p||!this.canUseStorage)return[3,8];q=function(a,o){return i(Z,void 0,void 0,(function(){var i,a,s,r,u,d,v,h,g,f,p,y,m,S,C,b,F,E,x,O=this;return n(this,(function(n){switch(n.label){case 0:if(!o)return[3,7];i=null,a=null,n.label=1;case 1:return n.trys.push([1,5,,6]),s=JSON.parse(o),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)&&(d=!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),d=!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"),d=!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,d=!0)),d&&(r=!0,i=l(this.flags,s.flags),this.setState(e(e({},s),{evaluationContext:c(e(e({},s.evaluationContext),{identity:(null===(b=s.evaluationContext)||void 0===b?void 0:b.identity)?e(e({},null===(F=s.evaluationContext)||void 0===F?void 0:F.identity),{traits:e({},V||{})}):void 0}))})),this.log("Retrieved flags from cache",s))),r?(v=!M&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:i,traitsChanged:a},this._loadedState(null,t.FlagSource.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&r&&!u&&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 M?[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 M?[3,9]:[4,this.getFlags()];case 8:return n.sent(),[3,10];case 9:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(E=this.evaluationContext.identity)||void 0===E?void 0:E.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))}n.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===(o=this.onError)||void 0===o||o.call(this,Q),[3,8];case 8:return[3,12];case 9:return M?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:l({},w),traitsChanged:l({},null===(s=v.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:l({},this.flags),traitsChanged:l({},null===(r=v.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]}}))}))},v.prototype.getAllFlags=function(){return this.flags},v.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()},v.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},v.prototype.setState=function(t){var e,i;t&&(this.initialised=!0,this.api=t.api||this.api||S,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))},v.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},v.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},v.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},v.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}},v.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))},v.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)}},v.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);p.setItem(m,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},v.prototype.initPipelineAnalytics=function(t){var e,i,n,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=d(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))},v.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},v.prototype.trimPipelineBuffer=function(){if(this.pipelineEvents.length>this.evaluationAnalyticsMaxBuffer){var t=this.pipelineEvents.length-this.evaluationAnalyticsMaxBuffer;this.pipelineEvents=this.pipelineEvents.slice(t)}},v.prototype.recordPipelineEvent=function(t){var i,n,a,o,l,s,r,u=t.toLowerCase().replace(/ /g,"_"),c=this.flags&&this.flags[u],d="".concat(null!==(n=null===(i=this.evaluationContext.identity)||void 0===i?void 0:i.identifier)&&void 0!==n?n:"none","|").concat(null!==(a=null==c?void 0:c.enabled)&&void 0!==a&&a,"|").concat(null!==(o=null==c?void 0:c.value)&&void 0!==o?o:"null");if(this.pipelineRecordedKeys.get(u)!==d){this.pipelineRecordedKeys.set(u,d);var v={event_id:u,event_type:"flag_evaluation",evaluated_at:Date.now(),identity_identifier:null!==(s=null===(l=this.evaluationContext.identity)||void 0===l?void 0:l.identifier)&&void 0!==s?s:"",enabled:c?c.enabled:null,value:c?c.value:null,traits:(null===(r=this.evaluationContext.identity)||void 0===r?void 0:r.traits)?e({},this.evaluationContext.identity.traits):null,metadata:e(e(e({},c?{id:c.id}:{}),"undefined"!=typeof window&&window.location?{page_url:window.location.href}:{}),{sdk_version:g})};this.pipelineEvents.push(v),this.trimPipelineBuffer(),0===this.pipelineFlushInterval&&this.flushPipelineAnalytics()}},v.prototype.setLoadingState=function(t){var i;o(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(i=this._triggerLoadingState)||void 0===i||i.call(this))},v.prototype.setupRealtime=function(t,e){var i=this,n=t+"sse/environments/"+e+"/stream";f?this.eventSource||(this.log("Creating event source with url "+n),this.eventSource=new f(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")},v}();function x(t){var e=t.fetch,i=t.AsyncStorage,n=t.eventSource;return new E({fetch:e,AsyncStorage:i,eventSource:n})}var O=x({});t.createFlagsmithInstance=function(){return x({})},t.default=O,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,o){function l(t){try{r(n.next(t))}catch(t){o(t)}}function s(t){try{r(n.throw(t))}catch(t){o(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(l,s)}r((n=n.apply(t,e||[])).next())}))}function n(t,e){var i,n,a,o,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;l;)try{if(i=1,n&&(a=2&o[0]?n.return:o[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,o[1])).done)return a;switch(n=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return l.label++,{value:o[1],done:!1};case 5:l.label++,n=o[1],o=[0];continue;case 7:o=l.ops.pop(),l.trys.pop();continue;default:if(!(a=l.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){l=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){l.label=o[1];break}if(6===o[0]&&l.label<a[1]){l.label=a[1],a=o;break}if(a&&l.label<a[2]){l.label=a[2],l.ops.push(o);break}a[2]&&l.ops.pop(),l.trys.pop();continue}o=e.call(t,l)}catch(t){o=[6,t],n=0}finally{i=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function a(t,e,i){if(i||2===arguments.length)for(var n,a=0,o=e.length;a<o;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 o=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,o;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=(o=Object.keys(e)).length)!==Object.keys(i).length)return!1;for(a=n;0!=a--;)if(!Object.prototype.hasOwnProperty.call(i,o[a]))return!1;for(a=n;0!=a--;){var l=o[a];if(!t(e[l],i[l]))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],a=null==e?void 0:e[i];return!o(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 d(t){return t.endsWith("/")?t:t+"/"}var v,h,g="11.0.0-internal.4";t.FlagSource=void 0,(v=t.FlagSource||(t.FlagSource={})).NONE="NONE",v.DEFAULT_FLAGS="DEFAULT_FLAGS",v.CACHE="CACHE",v.SERVER="SERVER";var f,p=null,y="FLAGSMITH_EVENT",m=y,S="https://edge.api.flagsmith.com/api/v1/",C="flagsmith_value_",b="flagsmith_enabled_",F="flagsmith_trait_",E=function(){function v(a){var o=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var i=o,n=i.api,a=i.evaluationContext;o.log("Get Flags"),o.isLoading=!0,o.loadingState.isFetching||o.setLoadingState(e(e({},o.loadingState),{isFetching:!0}));var r="".concat(o.getContext().identity),u=function(i){var n,a,u,c;if(i&&r==="".concat(o.getContext().identity)){var d=i.flags,v=i.traits,h=i.identifier;o.isLoading=!1;var g={},f={};v=v||[],(d=d||[]).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}})),o.oldFlags=e({},o.flags);var p=l(o.oldFlags,g),y=l(null===(n=o.evaluationContext.identity)||void 0===n?void 0:n.traits,f);if((h||Object.keys(f).length)&&(o.evaluationContext.identity=e(e({},o.evaluationContext.identity),{traits:f}),h&&(o.evaluationContext.identity.identifier=h,o.identity=h)),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[F+t]=o.getTrait(t)}));var S=e(e(e({},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 E={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(o.flags).map((function(t){s(E,C+t,o.getValue(t,{skipAnalytics:!0})),s(E,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(E,F+t,o.getTrait(t))})),o.log("Sending javaLongOrObject traits to dynatrace",E.javaLongOrObject),o.log("Sending date traits to dynatrace",E.date),o.log("Sending shortString traits to dynatrace",E.shortString),o.log("Sending javaDouble to dynatrace",E.javaDouble),o.dtrum.sendSessionProperties(E.javaLongOrObject,E.date,E.shortString,E.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(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||(o.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):o.getJSON(n+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(t){return o.evaluationContext.identity=e(e({},o.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)})):o.getJSON(n+"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 i=o.getState();o.evaluationEvent||(o.evaluationEvent={}),o.evaluationEvent[o.evaluationContext.environment.apiKey]={},o.setState(e(e({},i),{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,i,a,o,l,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,o=this.pipelineEvents,this.pipelineEvents=[],this.pipelineRecordedKeys.clear(),l={events:o,environment_key:a},n.label=1;case 1:return n.trys.push([1,3,4,5]),[4,h(this.evaluationAnalyticsUrl+"v1/analytics/batch",{method:"POST",body:JSON.stringify(l),headers:e({"Content-Type":"application/json; charset=utf-8","X-Environment-Key":a},{"Flagsmith-SDK-User-Agent":"flagsmith-js-sdk/".concat(g)})})];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=o.concat(this.pipelineEvents),this.trimPipelineBuffer(),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=o.flags&&o.flags[t.toLowerCase().replace(/ /g,"_")],a=null;if(n&&(a=n.value),(null==e?void 0:e.skipAnalytics)||i||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,i;return(null===(e=o.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(i=o.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=o.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 o.evaluationContext=e(e({},a),{environment:a.environment||o.evaluationContext.environment}),o.identity=null===(n=null===(i=o.getContext())||void 0===i?void 0:i.identity)||void 0===n?void 0:n.identifier,o.initialised?o.getFlags():Promise.resolve()},this.getContext=function(){return o.evaluationContext},this.updateContext=function(t){return o.setContext(e(e({},o.getContext()),t))},this.setTrait=function(t,i){var n;if(o.api)return o.setContext(e(e({},o.evaluationContext),{identity:e(e({},o.evaluationContext.identity),{traits:e(e({},null===(n=o.evaluationContext.identity)||void 0===n?void 0:n.traits),u(Object.fromEntries([[t,i]])))})}))},this.setTraits=function(t){var i;if(o.api)return o.setContext(e(e({},o.evaluationContext),{identity:e(e({},o.evaluationContext.identity),{traits:e(e({},null===(i=o.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,l=o.flags&&o.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!l&&a&&void 0!==e.fallback?s=null==e?void 0:e.fallback:l&&l.enabled&&(s=!0),(a&&!e.skipAnalytics||!e)&&o.evaluateFlag(t,"ENABLED"),o.sentryClient)try{null===(n=null===(i=o.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=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,i){var n,a,l,s=o.headers,r={method:e||"GET",body:i,cache:"no-cache",headers:{}};o.evaluationContext.environment&&(r.headers["X-Environment-Key"]=o.evaluationContext.environment.apiKey),e&&"GET"!==e&&(r.headers["Content-Type"]="application/json; charset=utf-8"),(null===(n=o.applicationMetadata)||void 0===n?void 0:n.name)&&(r.headers["Flagsmith-Application-Name"]=o.applicationMetadata.name),(null===(a=o.applicationMetadata)||void 0===a?void 0:a.version)&&(r.headers["Flagsmith-Application-Version"]=o.applicationMetadata.version),r.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat(g),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===(l=o.evaluationContext.identity)||void 0===l?void 0:l.identifier);return h(t,r).then((function(i){var n,a,l="".concat(null===(n=o.evaluationContext.identity)||void 0===n?void 0:n.identifier);if(u===l){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");o.timestamp=r}catch(t){o.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return o.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))}))}o.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(l))}))},this.evaluateFlag=function(t,e){if(o.datadogRum&&(o.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?o.datadogRum.client.addFeatureFlagEvaluation(C+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._onChange=function(t,e,i){var n,a;o.setLoadingState(i),null===(n=o.onChange)||void 0===n||n.call(o,t,e,o.loadingState),null===(a=o._trigger)||void 0===a||a.call(o)},h=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&&(f=a.eventSource),a.AsyncStorage&&(p=a.AsyncStorage)}return v.prototype.init=function(a){var o,s,r,u;return i(this,void 0,void 0,(function(){var v,g,f,y,C,b,F,E,x,O,A,w,_,I,j,L,P,k,K,T,R,N,U,D,M,J,G,B,V,H,q,W,X,Y,z,Q,Z=this;return n(this,(function($){switch($.label){case 0:v=c(a.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),g=a.AsyncStorage,f=a._trigger,y=a._triggerLoadingState,C=a.angularHttpClient,b=a.api,F=void 0===b?S:b,E=a.applicationMetadata,x=a.cacheFlags,O=a.cacheOptions,A=a.datadogRum,w=a.defaultFlags,_=a.enableAnalytics,I=a.enableDynatrace,j=a.enableLogs,L=a.environmentID,P=a.evaluationAnalyticsConfig,k=a.eventSourceUrl,K=void 0===k?"https://realtime.flagsmith.com/":k,T=a.fetch,R=a.headers,N=a.identity,U=a.onChange,D=a.onError,M=a.preventFetch,J=a.realtime,G=a.sentryClient,B=a.state,V=a.traits,v.environment=L?{apiKey:L}:v.environment,!v.environment||!v.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(v.identity=N||V?{identifier:N,traits:V?Object.fromEntries(Object.entries(V).map((function(t){return[t[0],{value:t[1]}]}))):{}}:v.identity,this.evaluationContext=v,this.api=d(F),this.headers=R,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=U,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=f||this._trigger,this._triggerLoadingState=y||this._triggerLoadingState,this.onError=function(t){Z.setLoadingState(e(e({},Z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==D||D(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."),T&&(h=T),this.enableAnalytics=_||!1,this.flags=Object.assign({},w)||{},this.datadogRum=A||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==p&&!!x,this.applicationMetadata=E,m="FLAGSMITH_EVENT_"+v.environment.apiKey,g&&(p=g),J&&"undefined"!=typeof window&&this.setupRealtime(K,v.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(B),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),G&&(this.sentryClient=G),C&&(h=function(t){return function(e,i){var n=i.headers,a=i.method,o=i.body,l={headers:n,observe:"response",responseType:"text"},s=function(t,e){var i=t.status,n=t.headers,a=t.body,o=t.error,l=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:o)&&void 0!==t?t:l)&&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,l).subscribe(n,r);case"POST":case"PUT":return t.post(e,null!=o?o:"",l).subscribe(n,r);default:return r({status:405,message:"Unsupported method: ".concat(a)})}}))}}(C)),p&&this.canUseStorage&&p.getItem(m).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(m,(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(!p||!this.canUseStorage)return[3,8];q=function(a,o){return i(Z,void 0,void 0,(function(){var i,a,s,r,u,d,v,h,g,f,p,y,m,S,C,b,F,E,x,O=this;return n(this,(function(n){switch(n.label){case 0:if(!o)return[3,7];i=null,a=null,n.label=1;case 1:return n.trys.push([1,5,,6]),s=JSON.parse(o),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)&&(d=!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),d=!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"),d=!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,d=!0)),d&&(r=!0,i=l(this.flags,s.flags),this.setState(e(e({},s),{evaluationContext:c(e(e({},s.evaluationContext),{identity:(null===(b=s.evaluationContext)||void 0===b?void 0:b.identity)?e(e({},null===(F=s.evaluationContext)||void 0===F?void 0:F.identity),{traits:e({},V||{})}):void 0}))})),this.log("Retrieved flags from cache",s))),r?(v=!M&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:i,traitsChanged:a},this._loadedState(null,t.FlagSource.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&r&&!u&&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 M?[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 M?[3,9]:[4,this.getFlags()];case 8:return n.sent(),[3,10];case 9:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:l({},this.flags),traitsChanged:l({},null===(E=this.evaluationContext.identity)||void 0===E?void 0:E.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))}n.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===(o=this.onError)||void 0===o||o.call(this,Q),[3,8];case 8:return[3,12];case 9:return M?[3,11]:[4,this.getFlags()];case 10:return $.sent(),[3,12];case 11:if(w)this._onChange(null,{isFromServer:!1,flagsChanged:l({},w),traitsChanged:l({},null===(s=v.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:l({},this.flags),traitsChanged:l({},null===(r=v.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]}}))}))},v.prototype.getAllFlags=function(){return this.flags},v.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()},v.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},v.prototype.setState=function(t){var e,i;t&&(this.initialised=!0,this.api=t.api||this.api||S,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))},v.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},v.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},v.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},v.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}},v.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))},v.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)}},v.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);p.setItem(m,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},v.prototype.initPipelineAnalytics=function(t){var e,i,n,a;this.stopPipelineAnalytics(),this.evaluationAnalyticsUrl=d(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))},v.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},v.prototype.trimPipelineBuffer=function(){if(this.pipelineEvents.length>this.evaluationAnalyticsMaxBuffer){var t=this.pipelineEvents.length-this.evaluationAnalyticsMaxBuffer;this.pipelineEvents=this.pipelineEvents.slice(t)}},v.prototype.recordPipelineEvent=function(t){var i,n,a,o,l,s,r,u=t.toLowerCase().replace(/ /g,"_"),c=this.flags&&this.flags[u],d="".concat(null!==(n=null===(i=this.evaluationContext.identity)||void 0===i?void 0:i.identifier)&&void 0!==n?n:"none","|").concat(null!==(a=null==c?void 0:c.enabled)&&void 0!==a&&a,"|").concat(null!==(o=null==c?void 0:c.value)&&void 0!==o?o:"null");if(this.pipelineRecordedKeys.get(u)!==d){this.pipelineRecordedKeys.set(u,d);var v={event_id:u,event_type:"flag_evaluation",evaluated_at:Date.now(),identity_identifier:null!==(s=null===(l=this.evaluationContext.identity)||void 0===l?void 0:l.identifier)&&void 0!==s?s:"",enabled:c?c.enabled:null,value:c?c.value:null,traits:(null===(r=this.evaluationContext.identity)||void 0===r?void 0:r.traits)?e({},this.evaluationContext.identity.traits):null,metadata:e(e(e({},c?{id:c.id}:{}),"undefined"!=typeof window&&window.location?{page_url:window.location.href}:{}),{sdk_version:g})};this.pipelineEvents.push(v),this.trimPipelineBuffer(),0===this.pipelineFlushInterval&&this.flushPipelineAnalytics()}},v.prototype.setLoadingState=function(t){var i;o(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(i=this._triggerLoadingState)||void 0===i||i.call(this))},v.prototype.setupRealtime=function(t,e){var i=this,n=t+"sse/environments/"+e+"/stream";f?this.eventSource||(this.log("Creating event source with url "+n),this.eventSource=new f(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")},v}();function x(t){var e=t.fetch,i=t.AsyncStorage,n=t.eventSource;return new E({fetch:e,AsyncStorage:i,eventSource:n})}var O=x({});t.createFlagsmithInstance=function(){return x({})},t.default=O,Object.defineProperty(t,"__esModule",{value:!0})}));
|
|
2
2
|
//# sourceMappingURL=next-middleware.js.map
|
package/next-middleware.mjs
CHANGED
|
@@ -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;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(v||(v={}));var h,g=null,f="FLAGSMITH_EVENT",p="https://edge.api.flagsmith.com/api/v1/",y=function(){function y(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 C=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",C),a.datadogRum.client.setUser(C)}}catch(t){console.error(t)}if(a.dtrum)try{var S={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(a.flags).map((function(t){o(S,"flagsmith_value_"+t,a.getValue(t,{skipAnalytics:!0})),o(S,"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(S,"flagsmith_trait_"+t,a.getTrait(t))})),a.log("Sending javaLongOrObject traits to dynatrace",S.javaLongOrObject),a.log("Sending date traits to dynatrace",S.date),a.log("Sending shortString traits to dynatrace",S.shortString),a.log("Sending javaDouble to dynatrace",S.javaDouble),a.dtrum.sendSessionProperties(S.javaLongOrObject,S.date,S.shortString,S.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,this.pipelineEvents=[],this.pipelineRecordedKeys.clear(),o={events:l,environment_key:a},i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,d(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.3")})})];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.trimPipelineBuffer(),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.3"),s&&Object.assign(r.headers,s),d||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 d(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._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)},d=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&&(h=n.eventSource),n.AsyncStorage&&(g=n.AsyncStorage)}return y.prototype.init=function(n){var a,o,s,r;return e(this,void 0,void 0,(function(){var h,y,m,C,S,b,E,x,F,O,A,_,w,I,j,L,P,k,K,T,R,N,U,D,J,M,G,B,V,H,q,W,X,Y,z,Q,Z=this;return i(this,(function($){switch($.label){case 0:h=u(n.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),y=n.AsyncStorage,m=n._trigger,C=n._triggerLoadingState,S=n.angularHttpClient,b=n.api,E=void 0===b?p:b,x=n.applicationMetadata,F=n.cacheFlags,O=n.cacheOptions,A=n.datadogRum,_=n.defaultFlags,w=n.enableAnalytics,I=n.enableDynatrace,j=n.enableLogs,L=n.environmentID,P=n.evaluationAnalyticsConfig,k=n.eventSourceUrl,K=void 0===k?"https://realtime.flagsmith.com/":k,T=n.fetch,R=n.headers,N=n.identity,U=n.onChange,D=n.onError,J=n.preventFetch,M=n.realtime,G=n.sentryClient,B=n.state,V=n.traits,h.environment=L?{apiKey:L}:h.environment,!h.environment||!h.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(h.identity=N||V?{identifier:N,traits:V?Object.fromEntries(Object.entries(V).map((function(t){return[t[0],{value:t[1]}]}))):{}}:h.identity,this.evaluationContext=h,this.api=c(E),this.headers=R,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=U,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=m||this._trigger,this._triggerLoadingState=C||this._triggerLoadingState,this.onError=function(e){Z.setLoadingState(t(t({},Z.loadingState),{isFetching:!1,isLoading:!1,error:e})),null==D||D(e)},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."),T&&(d=T),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!==g&&!!F,this.applicationMetadata=x,f="FLAGSMITH_EVENT_"+h.environment.apiKey,y&&(g=y),M&&"undefined"!=typeof window&&this.setupRealtime(K,h.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=t(t({},this.loadingState),{isLoading:!1,source:v.DEFAULT_FLAGS})),this.setState(B),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),G&&(this.sentryClient=G),S&&(d=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)})}}))}}(S)),g&&this.canUseStorage&&g.getItem(f).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),g&&this.canUseStorage&&g.getItem(f,(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(!g||!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,C,S,b,E,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===(S=null===(C=o.evaluationContext)||void 0===C?void 0:C.identity)||void 0===S?void 0:S.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===(b=o.evaluationContext)||void 0===b?void 0:b.identity)?t(t({},null===(E=o.evaluationContext)||void 0===E?void 0:E.identity),{traits:t({},V||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),s?(d=!J&&(!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 J?[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 J?[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]),g.getItemSync?(W=g.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,g.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 J?[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=h.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=h.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]}}))}))},y.prototype.getAllFlags=function(){return this.flags},y.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()},y.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},y.prototype.setState=function(t){var e,i;t&&(this.initialised=!0,this.api=t.api||this.api||p,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))},y.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},y.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},y.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},y.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}},y.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))},y.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),g.setItem(this.getStorageKey(),t)}},y.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);g.setItem(f,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},y.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))},y.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},y.prototype.trimPipelineBuffer=function(){if(this.pipelineEvents.length>this.evaluationAnalyticsMaxBuffer){var t=this.pipelineEvents.length-this.evaluationAnalyticsMaxBuffer;this.pipelineEvents=this.pipelineEvents.slice(t)}},y.prototype.recordPipelineEvent=function(e){var i,n,a,l,o,s,r,u=e.toLowerCase().replace(/ /g,"_"),c=this.flags&&this.flags[u],v="".concat(null!==(n=null===(i=this.evaluationContext.identity)||void 0===i?void 0:i.identifier)&&void 0!==n?n:"none","|").concat(null!==(a=null==c?void 0:c.enabled)&&void 0!==a&&a,"|").concat(null!==(l=null==c?void 0:c.value)&&void 0!==l?l:"null");if(this.pipelineRecordedKeys.get(u)!==v){this.pipelineRecordedKeys.set(u,v);var d={event_id:u,event_type:"flag_evaluation",evaluated_at:Date.now(),identity_identifier:null!==(s=null===(o=this.evaluationContext.identity)||void 0===o?void 0:o.identifier)&&void 0!==s?s:"",enabled:c?c.enabled:null,value:c?c.value:null,traits:(null===(r=this.evaluationContext.identity)||void 0===r?void 0:r.traits)?t({},this.evaluationContext.identity.traits):null,metadata:t(t(t({},c?{id:c.id}:{}),"undefined"!=typeof window&&window.location?{page_url:window.location.href}:{}),{sdk_version:"11.0.0-internal.3"})};this.pipelineEvents.push(d),this.trimPipelineBuffer(),0===this.pipelineFlushInterval&&this.flushPipelineAnalytics()}},y.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))},y.prototype.setupRealtime=function(t,e){var i=this,n=t+"sse/environments/"+e+"/stream";h?this.eventSource||(this.log("Creating event source with url "+n),this.eventSource=new h(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")},y}();function m(t){var e=t.fetch,i=t.AsyncStorage,n=t.eventSource;return new y({fetch:e,AsyncStorage:i,eventSource:n})}var C=m({}),S=function(){return m({})};export{v as FlagSource,S 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;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(v||(v={}));var h,g=null,f="FLAGSMITH_EVENT",p="https://edge.api.flagsmith.com/api/v1/",y=function(){function y(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 C=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",C),a.datadogRum.client.setUser(C)}}catch(t){console.error(t)}if(a.dtrum)try{var S={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(a.flags).map((function(t){o(S,"flagsmith_value_"+t,a.getValue(t,{skipAnalytics:!0})),o(S,"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(S,"flagsmith_trait_"+t,a.getTrait(t))})),a.log("Sending javaLongOrObject traits to dynatrace",S.javaLongOrObject),a.log("Sending date traits to dynatrace",S.date),a.log("Sending shortString traits to dynatrace",S.shortString),a.log("Sending javaDouble to dynatrace",S.javaDouble),a.dtrum.sendSessionProperties(S.javaLongOrObject,S.date,S.shortString,S.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,this.pipelineEvents=[],this.pipelineRecordedKeys.clear(),o={events:l,environment_key:a},i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,d(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.4")})})];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.trimPipelineBuffer(),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.4"),s&&Object.assign(r.headers,s),d||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 d(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._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)},d=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&&(h=n.eventSource),n.AsyncStorage&&(g=n.AsyncStorage)}return y.prototype.init=function(n){var a,o,s,r;return e(this,void 0,void 0,(function(){var h,y,m,C,S,b,E,x,F,O,A,_,w,I,j,L,P,k,K,T,R,N,U,D,J,M,G,B,V,H,q,W,X,Y,z,Q,Z=this;return i(this,(function($){switch($.label){case 0:h=u(n.evaluationContext||this.evaluationContext),$.label=1;case 1:if($.trys.push([1,13,,14]),y=n.AsyncStorage,m=n._trigger,C=n._triggerLoadingState,S=n.angularHttpClient,b=n.api,E=void 0===b?p:b,x=n.applicationMetadata,F=n.cacheFlags,O=n.cacheOptions,A=n.datadogRum,_=n.defaultFlags,w=n.enableAnalytics,I=n.enableDynatrace,j=n.enableLogs,L=n.environmentID,P=n.evaluationAnalyticsConfig,k=n.eventSourceUrl,K=void 0===k?"https://realtime.flagsmith.com/":k,T=n.fetch,R=n.headers,N=n.identity,U=n.onChange,D=n.onError,J=n.preventFetch,M=n.realtime,G=n.sentryClient,B=n.state,V=n.traits,h.environment=L?{apiKey:L}:h.environment,!h.environment||!h.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(h.identity=N||V?{identifier:N,traits:V?Object.fromEntries(Object.entries(V).map((function(t){return[t[0],{value:t[1]}]}))):{}}:h.identity,this.evaluationContext=h,this.api=c(E),this.headers=R,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=U,H="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=m||this._trigger,this._triggerLoadingState=C||this._triggerLoadingState,this.onError=function(e){Z.setLoadingState(t(t({},Z.loadingState),{isFetching:!1,isLoading:!1,error:e})),null==D||D(e)},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."),T&&(d=T),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!==g&&!!F,this.applicationMetadata=x,f="FLAGSMITH_EVENT_"+h.environment.apiKey,y&&(g=y),M&&"undefined"!=typeof window&&this.setupRealtime(K,h.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=t(t({},this.loadingState),{isLoading:!1,source:v.DEFAULT_FLAGS})),this.setState(B),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),G&&(this.sentryClient=G),S&&(d=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)})}}))}}(S)),g&&this.canUseStorage&&g.getItem(f).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),g&&this.canUseStorage&&g.getItem(f,(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(!g||!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,C,S,b,E,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===(S=null===(C=o.evaluationContext)||void 0===C?void 0:C.identity)||void 0===S?void 0:S.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===(b=o.evaluationContext)||void 0===b?void 0:b.identity)?t(t({},null===(E=o.evaluationContext)||void 0===E?void 0:E.identity),{traits:t({},V||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),s?(d=!J&&(!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 J?[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 J?[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]),g.getItemSync?(W=g.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,g.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 J?[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=h.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=h.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]}}))}))},y.prototype.getAllFlags=function(){return this.flags},y.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()},y.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},y.prototype.setState=function(t){var e,i;t&&(this.initialised=!0,this.api=t.api||this.api||p,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))},y.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},y.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},y.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},y.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}},y.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))},y.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),g.setItem(this.getStorageKey(),t)}},y.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);g.setItem(f,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},y.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))},y.prototype.stopPipelineAnalytics=function(){this.pipelineAnalyticsInterval&&(clearInterval(this.pipelineAnalyticsInterval),this.pipelineAnalyticsInterval=null),this.evaluationAnalyticsUrl=null,this.pipelineEvents=[],this.pipelineRecordedKeys.clear()},y.prototype.trimPipelineBuffer=function(){if(this.pipelineEvents.length>this.evaluationAnalyticsMaxBuffer){var t=this.pipelineEvents.length-this.evaluationAnalyticsMaxBuffer;this.pipelineEvents=this.pipelineEvents.slice(t)}},y.prototype.recordPipelineEvent=function(e){var i,n,a,l,o,s,r,u=e.toLowerCase().replace(/ /g,"_"),c=this.flags&&this.flags[u],v="".concat(null!==(n=null===(i=this.evaluationContext.identity)||void 0===i?void 0:i.identifier)&&void 0!==n?n:"none","|").concat(null!==(a=null==c?void 0:c.enabled)&&void 0!==a&&a,"|").concat(null!==(l=null==c?void 0:c.value)&&void 0!==l?l:"null");if(this.pipelineRecordedKeys.get(u)!==v){this.pipelineRecordedKeys.set(u,v);var d={event_id:u,event_type:"flag_evaluation",evaluated_at:Date.now(),identity_identifier:null!==(s=null===(o=this.evaluationContext.identity)||void 0===o?void 0:o.identifier)&&void 0!==s?s:"",enabled:c?c.enabled:null,value:c?c.value:null,traits:(null===(r=this.evaluationContext.identity)||void 0===r?void 0:r.traits)?t({},this.evaluationContext.identity.traits):null,metadata:t(t(t({},c?{id:c.id}:{}),"undefined"!=typeof window&&window.location?{page_url:window.location.href}:{}),{sdk_version:"11.0.0-internal.4"})};this.pipelineEvents.push(d),this.trimPipelineBuffer(),0===this.pipelineFlushInterval&&this.flushPipelineAnalytics()}},y.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))},y.prototype.setupRealtime=function(t,e){var i=this,n=t+"sse/environments/"+e+"/stream";h?this.eventSource||(this.log("Creating event source with url "+n),this.eventSource=new h(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")},y}();function m(t){var e=t.fetch,i=t.AsyncStorage,n=t.eventSource;return new y({fetch:e,AsyncStorage:i,eventSource:n})}var C=m({}),S=function(){return m({})};export{v as FlagSource,S as createFlagsmithInstance,C as default};
|
|
2
2
|
//# sourceMappingURL=next-middleware.mjs.map
|
package/package.json
CHANGED
package/src/types.d.ts
CHANGED
|
@@ -132,15 +132,15 @@ export interface IInitConfig<F extends string | Record<string, any> = string, T
|
|
|
132
132
|
*/
|
|
133
133
|
applicationMetadata?: ApplicationMetadata;
|
|
134
134
|
/**
|
|
135
|
+
* @experimental Internal use only — API may change without notice.
|
|
135
136
|
* Configuration for the evaluation analytics pipeline. When provided,
|
|
136
137
|
* individual flag evaluation events are buffered and sent to the pipeline endpoint.
|
|
138
|
+
* @hidden
|
|
137
139
|
*/
|
|
140
|
+
/** @internal */
|
|
138
141
|
evaluationAnalyticsConfig?: {
|
|
139
|
-
/** URL of the pipeline server (e.g. 'https://analytics.flagsmith.com/'). */
|
|
140
142
|
analyticsServerUrl: string;
|
|
141
|
-
/** Maximum events to buffer in memory before dropping oldest. Default 1000. */
|
|
142
143
|
maxBuffer?: number;
|
|
143
|
-
/** Flush interval in milliseconds. Set to 0 to flush immediately after each evaluation. Default 10000 (10s). */
|
|
144
144
|
flushInterval?: number;
|
|
145
145
|
};
|
|
146
146
|
}
|
package/src/utils/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Auto-generated by write-version.js
|
|
2
|
-
export const SDK_VERSION = "11.0.0-internal.
|
|
2
|
+
export const SDK_VERSION = "11.0.0-internal.4";
|
package/types.d.ts
CHANGED
|
@@ -132,15 +132,15 @@ export interface IInitConfig<F extends string | Record<string, any> = string, T
|
|
|
132
132
|
*/
|
|
133
133
|
applicationMetadata?: ApplicationMetadata;
|
|
134
134
|
/**
|
|
135
|
+
* @experimental Internal use only — API may change without notice.
|
|
135
136
|
* Configuration for the evaluation analytics pipeline. When provided,
|
|
136
137
|
* individual flag evaluation events are buffered and sent to the pipeline endpoint.
|
|
138
|
+
* @hidden
|
|
137
139
|
*/
|
|
140
|
+
/** @internal */
|
|
138
141
|
evaluationAnalyticsConfig?: {
|
|
139
|
-
/** URL of the pipeline server (e.g. 'https://analytics.flagsmith.com/'). */
|
|
140
142
|
analyticsServerUrl: string;
|
|
141
|
-
/** Maximum events to buffer in memory before dropping oldest. Default 1000. */
|
|
142
143
|
maxBuffer?: number;
|
|
143
|
-
/** Flush interval in milliseconds. Set to 0 to flush immediately after each evaluation. Default 10000 (10s). */
|
|
144
144
|
flushInterval?: number;
|
|
145
145
|
};
|
|
146
146
|
}
|
package/utils/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const SDK_VERSION = "11.0.0-internal.
|
|
1
|
+
export declare const SDK_VERSION = "11.0.0-internal.4";
|