UNPKG

configcat-vue

Version:

A community-maintained SDK for integrating ConfigCat feature flags into Vue.js applications.

6 lines 75 kB
(function(h,T){typeof exports=="object"&&typeof module<"u"?T(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],T):(h=typeof globalThis<"u"?globalThis:h||self,T(h["configcat-vue"]={},h.Vue))})(this,function(h,T){"use strict";var ue;(function(i){i[i.No=0]="No",i[i.Should=1]="Should",i[i.Force=2]="Force"})(ue||(ue={})),h.SettingType=void 0,function(i){i[i.Boolean=0]="Boolean",i[i.String=1]="String",i[i.Int=2]="Int",i[i.Double=3]="Double"}(h.SettingType||(h.SettingType={})),h.UserComparator=void 0,function(i){i[i.TextIsOneOf=0]="TextIsOneOf",i[i.TextIsNotOneOf=1]="TextIsNotOneOf",i[i.TextContainsAnyOf=2]="TextContainsAnyOf",i[i.TextNotContainsAnyOf=3]="TextNotContainsAnyOf",i[i.SemVerIsOneOf=4]="SemVerIsOneOf",i[i.SemVerIsNotOneOf=5]="SemVerIsNotOneOf",i[i.SemVerLess=6]="SemVerLess",i[i.SemVerLessOrEquals=7]="SemVerLessOrEquals",i[i.SemVerGreater=8]="SemVerGreater",i[i.SemVerGreaterOrEquals=9]="SemVerGreaterOrEquals",i[i.NumberEquals=10]="NumberEquals",i[i.NumberNotEquals=11]="NumberNotEquals",i[i.NumberLess=12]="NumberLess",i[i.NumberLessOrEquals=13]="NumberLessOrEquals",i[i.NumberGreater=14]="NumberGreater",i[i.NumberGreaterOrEquals=15]="NumberGreaterOrEquals",i[i.SensitiveTextIsOneOf=16]="SensitiveTextIsOneOf",i[i.SensitiveTextIsNotOneOf=17]="SensitiveTextIsNotOneOf",i[i.DateTimeBefore=18]="DateTimeBefore",i[i.DateTimeAfter=19]="DateTimeAfter",i[i.SensitiveTextEquals=20]="SensitiveTextEquals",i[i.SensitiveTextNotEquals=21]="SensitiveTextNotEquals",i[i.SensitiveTextStartsWithAnyOf=22]="SensitiveTextStartsWithAnyOf",i[i.SensitiveTextNotStartsWithAnyOf=23]="SensitiveTextNotStartsWithAnyOf",i[i.SensitiveTextEndsWithAnyOf=24]="SensitiveTextEndsWithAnyOf",i[i.SensitiveTextNotEndsWithAnyOf=25]="SensitiveTextNotEndsWithAnyOf",i[i.SensitiveArrayContainsAnyOf=26]="SensitiveArrayContainsAnyOf",i[i.SensitiveArrayNotContainsAnyOf=27]="SensitiveArrayNotContainsAnyOf",i[i.TextEquals=28]="TextEquals",i[i.TextNotEquals=29]="TextNotEquals",i[i.TextStartsWithAnyOf=30]="TextStartsWithAnyOf",i[i.TextNotStartsWithAnyOf=31]="TextNotStartsWithAnyOf",i[i.TextEndsWithAnyOf=32]="TextEndsWithAnyOf",i[i.TextNotEndsWithAnyOf=33]="TextNotEndsWithAnyOf",i[i.ArrayContainsAnyOf=34]="ArrayContainsAnyOf",i[i.ArrayNotContainsAnyOf=35]="ArrayNotContainsAnyOf"}(h.UserComparator||(h.UserComparator={})),h.PrerequisiteFlagComparator=void 0,function(i){i[i.Equals=0]="Equals",i[i.NotEquals=1]="NotEquals"}(h.PrerequisiteFlagComparator||(h.PrerequisiteFlagComparator={})),h.SegmentComparator=void 0,function(i){i[i.IsIn=0]="IsIn",i[i.IsNotIn=1]="IsNotIn"}(h.SegmentComparator||(h.SegmentComparator={}));const yt=Object.freeze(Object.defineProperty({__proto__:null,get PrerequisiteFlagComparator(){return h.PrerequisiteFlagComparator},get RedirectMode(){return ue},get SegmentComparator(){return h.SegmentComparator},get SettingType(){return h.SettingType},get UserComparator(){return h.UserComparator}},Symbol.toStringTag,{value:"Module"}));class S{static equals(e,t){return e.httpETag&&t.httpETag?e.httpETag===t.httpETag:e.configJson===t.configJson}constructor(e,t,n,s){this.configJson=e,this.config=t,this.timestamp=n,this.httpETag=s}with(e){return new S(this.configJson,this.config,e,this.httpETag)}get isEmpty(){return!this.config}isExpired(e){return this===S.empty||this.timestamp+e<S.generateTimestamp()}static generateTimestamp(){return new Date().getTime()}static serialize(e){var t,n;return e.timestamp+` `+((t=e.httpETag)!==null&&t!==void 0?t:"")+` `+((n=e.configJson)!==null&&n!==void 0?n:"")}static deserialize(e){const t=Array(2);let n=0;for(let u=0;u<t.length;u++){if(n=e.indexOf(` `,n),n<0)throw new Error("Number of values is fewer than expected.");t[u]=n++}let s=t[0],r=e.substring(0,s);const o=parseInt(r);if(isNaN(o))throw new Error("Invalid fetch time: "+r);n=s+1,s=t[1],r=e.substring(n,s);const a=r.length>0?r:void 0;n=s+1,r=e.substring(n);let l,c;return r.length>0&&(l=V.deserialize(r),c=r),new S(c,l,o,a)}}S.serializationFormatVersion="v2",S.empty=new S(void 0,void 0,0,void 0);class V{static deserialize(e){const t=JSON.parse(e);if(typeof t!="object"||!t)throw new Error("Invalid config JSON content:"+e);return new V(t)}constructor(e){var t,n;this.preferences=e.p!=null?new mt(e.p):void 0,this.segments=(n=(t=e.s)===null||t===void 0?void 0:t.map(s=>new Et(s)))!==null&&n!==void 0?n:[],this.settings=e.f!=null?Object.entries(e.f).reduce((s,[r,o])=>(s[r]=new P(o,this),s),{}):{}}get salt(){var e;return(e=this.preferences)===null||e===void 0?void 0:e.salt}}class mt{constructor(e){this.baseUrl=e.u,this.redirectMode=e.r,this.salt=e.s}}class Et{constructor(e){var t,n;this.name=e.n,this.conditions=(n=(t=e.r)===null||t===void 0?void 0:t.map(s=>new ke(s)))!==null&&n!==void 0?n:[]}}class he{constructor(e,t=!1){this.value=t?e.v:De(e.v),this.variationId=e.i}}class P extends he{constructor(e,t){var n,s,r,o,a,l;super(e,e.t<0),this.type=e.t,this.percentageOptionsAttribute=(n=e.a)!==null&&n!==void 0?n:"Identifier",this.targetingRules=(r=(s=e.r)===null||s===void 0?void 0:s.map(c=>new St(c,t)))!==null&&r!==void 0?r:[],this.percentageOptions=(a=(o=e.p)===null||o===void 0?void 0:o.map(c=>new Le(c)))!==null&&a!==void 0?a:[],this.configJsonSalt=(l=t==null?void 0:t.salt)!==null&&l!==void 0?l:""}static fromValue(e){return new P({t:-1,v:e})}}class St{constructor(e,t){var n,s;this.conditions=(s=(n=e.c)===null||n===void 0?void 0:n.map(r=>r.u!=null?new ke(r.u):r.p!=null?new Ot(r.p):r.s!=null?new At(r.s,t):void 0))!==null&&s!==void 0?s:[],this.then=e.p!=null?e.p.map(r=>new Le(r)):new he(e.s)}}class Le extends he{constructor(e){super(e),this.percentage=e.p}}class ke{constructor(e){var t,n;this.type="UserCondition",this.comparisonAttribute=e.a,this.comparator=e.c,this.comparisonValue=(n=(t=e.s)!==null&&t!==void 0?t:e.d)!==null&&n!==void 0?n:e.l}}class Ot{constructor(e){this.type="PrerequisiteFlagCondition",this.prerequisiteFlagKey=e.f,this.comparator=e.c,this.comparisonValue=De(e.v)}}class At{constructor(e,t){this.type="SegmentCondition",this.segment=t.segments[e.s],this.comparator=e.c}}function De(i){var e,t,n;return(n=(t=(e=i.b)!==null&&e!==void 0?e:i.s)!==null&&t!==void 0?t:i.i)!==null&&n!==void 0?n:i.d}function wt(i){return h.SettingType[i]}var ge;(function(i){i[i.Fetched=0]="Fetched",i[i.NotModified=1]="NotModified",i[i.Errored=2]="Errored"})(ge||(ge={}));class b{constructor(e,t,n,s){this.status=e,this.config=t,this.errorMessage=n,this.errorException=s}static success(e){return new b(0,e)}static notModified(e){return new b(1,e)}static error(e,t,n){return new b(2,e,t??"Unknown error.",n)}}class R extends Error{constructor(e,...t){super(((n,s)=>{switch(n){case"abort":return"Request was aborted.";case"timeout":const[r]=s;return`Request timed out. Timeout value: ${r}ms`;case"failure":const[o]=s,a="Request failed due to a network or protocol error.";return o?a+" "+(o instanceof Error?o.message:o+""):a}})(e,t)),this.cause=e,this instanceof R||(Object.setPrototypeOf||((n,s)=>n.__proto__=s))(this,R.prototype),this.args=t}}class N{constructor(e,t){this.errorMessage=e,this.errorException=t}get isSuccess(){return this.errorMessage===null}static from(e){return e.status!==2?N.success():N.failure(e.errorMessage,e.errorException)}static success(){return new N(null)}static failure(e,t){return new N(e,t)}}h.ClientCacheState=void 0,function(i){i[i.NoFlagData=0]="NoFlagData",i[i.HasLocalOverrideFlagDataOnly=1]="HasLocalOverrideFlagDataOnly",i[i.HasCachedFlagDataOnly=2]="HasCachedFlagDataOnly",i[i.HasUpToDateFlagData=3]="HasUpToDateFlagData"}(h.ClientCacheState||(h.ClientCacheState={}));var fe;(function(i){i[i.Online=0]="Online",i[i.Offline=1]="Offline",i[i.Disposed=2]="Disposed"})(fe||(fe={}));function $e(i){return fe[i]}class de{constructor(e,t){this.configFetcher=e,this.options=t,this.pendingFetch=null,this.cacheKey=t.getCacheKey(),this.configFetcher=e,this.options=t,this.status=t.offline?1:0}dispose(){this.status=2}get disposed(){return this.status===2}async refreshConfigAsync(){const e=await this.options.cache.get(this.cacheKey);if(this.isOffline){const t=this.options.logger.configServiceCannotInitiateHttpCalls().toString();return[N.failure(t),e]}else{const[t,n]=await this.refreshConfigCoreAsync(e);return[N.from(t),n]}}async refreshConfigCoreAsync(e){const t=await this.fetchAsync(e);let n=!1;const s=t.status===0;return(s||t.config.timestamp>e.timestamp&&(!t.config.isEmpty||e.isEmpty))&&(await this.options.cache.set(this.cacheKey,t.config),n=s&&!S.equals(t.config,e),e=t.config),this.onConfigFetched(t.config),n&&this.onConfigChanged(t.config),[t,e]}onConfigFetched(e){this.options.logger.debug("config fetched")}onConfigChanged(e){var t;this.options.logger.debug("config changed"),this.options.hooks.emit("configChanged",(t=e.config)!==null&&t!==void 0?t:new V({}))}fetchAsync(e){var t;return(t=this.pendingFetch)!==null&&t!==void 0?t:this.pendingFetch=(async()=>{try{return await this.fetchLogicAsync(e)}finally{this.pendingFetch=null}})()}async fetchLogicAsync(e){var t;const n=this.options;n.logger.debug("ConfigServiceBase.fetchLogicAsync() - called.");let s;try{const[r,o]=await this.fetchRequestAsync((t=e.httpETag)!==null&&t!==void 0?t:null);switch(r.statusCode){case 200:return o instanceof V?(n.logger.debug("ConfigServiceBase.fetchLogicAsync(): fetch was successful. Returning new config."),b.success(new S(r.body,o,S.generateTimestamp(),r.eTag))):(s=n.logger.fetchReceived200WithInvalidBody(o).toString(),n.logger.debug(`ConfigServiceBase.fetchLogicAsync(): ${r.statusCode} ${r.reasonPhrase} was received but the HTTP response content was invalid. Returning null.`),b.error(e,s,o));case 304:return e.isEmpty?(s=n.logger.fetchReceived304WhenLocalCacheIsEmpty(r.statusCode,r.reasonPhrase).toString(),n.logger.debug(`ConfigServiceBase.fetchLogicAsync(): ${r.statusCode} ${r.reasonPhrase} was received when no config is cached locally. Returning null.`),b.error(e,s)):(n.logger.debug("ConfigServiceBase.fetchLogicAsync(): content was not modified. Returning last config with updated timestamp."),b.notModified(e.with(S.generateTimestamp())));case 403:case 404:return s=n.logger.fetchFailedDueToInvalidSdkKey().toString(),n.logger.debug("ConfigServiceBase.fetchLogicAsync(): fetch was unsuccessful. Returning last config (if any) with updated timestamp."),b.error(e.with(S.generateTimestamp()),s);default:return s=n.logger.fetchFailedDueToUnexpectedHttpResponse(r.statusCode,r.reasonPhrase).toString(),n.logger.debug("ConfigServiceBase.fetchLogicAsync(): fetch was unsuccessful. Returning null."),b.error(e,s)}}catch(r){return s=(r instanceof R&&r.cause==="timeout"?n.logger.fetchFailedDueToRequestTimeout(r.args[0],r):n.logger.fetchFailedDueToUnexpectedError(r)).toString(),n.logger.debug("ConfigServiceBase.fetchLogicAsync(): fetch was unsuccessful. Returning null."),b.error(e,s,r)}}async fetchRequestAsync(e,t=2){const n=this.options;n.logger.debug("ConfigServiceBase.fetchRequestAsync() - called.");for(let s=0;;s++){n.logger.debug(`ConfigServiceBase.fetchRequestAsync(): calling fetchLogic()${s>0?`, retry ${s}/${t}`:""}`);const r=await this.configFetcher.fetchLogic(n,e);if(r.statusCode!==200)return[r];if(!r.body)return n.logger.debug("ConfigServiceBase.fetchRequestAsync(): no response body."),[r,new Error("No response body.")];let o;try{o=V.deserialize(r.body)}catch(u){return n.logger.debug("ConfigServiceBase.fetchRequestAsync(): invalid response body."),[r,u]}const a=o.preferences;if(!a)return n.logger.debug("ConfigServiceBase.fetchRequestAsync(): preferences is empty."),[r,o];const l=a.baseUrl;if(!l||l===n.baseUrl)return n.logger.debug("ConfigServiceBase.fetchRequestAsync(): baseUrl OK."),[r,o];const c=a.redirectMode;if(n.baseUrlOverriden&&c!==2)return n.logger.debug("ConfigServiceBase.fetchRequestAsync(): options.baseUrlOverriden && redirect !== 2."),[r,o];if(n.baseUrl=l,c===0)return[r,o];if(c===1&&n.logger.dataGovernanceIsOutOfSync(),s>=t)return n.logger.fetchFailedDueToRedirectLoop(),[r,o]}}get isOfflineExactly(){return this.status===1}get isOffline(){return this.status!==0}setOnlineCore(){}setOnline(){this.status===1?(this.setOnlineCore(),this.status=0,this.options.logger.configServiceStatusChanged($e(this.status))):this.disposed&&this.options.logger.configServiceMethodHasNoEffectDueToDisposedClient("setOnline")}setOfflineCore(){}setOffline(){this.status===0?(this.setOfflineCore(),this.status=1,this.options.logger.configServiceStatusChanged($e(this.status))):this.disposed&&this.options.logger.configServiceMethodHasNoEffectDueToDisposedClient("setOffline")}syncUpWithCache(){return this.options.cache.get(this.cacheKey)}async getReadyPromise(e,t){const n=await t(e);return this.options.hooks.emit("clientReady",n),n}}class ve{constructor(){this.callbacks=[]}get aborted(){return!this.callbacks}abort(){if(!this.aborted){const e=this.callbacks;this.callbacks=null;for(const t of e)t()}}registerCallback(e){return this.aborted?(e(),()=>{}):(this.callbacks.push(e),()=>{const t=this.callbacks;let n;t&&(n=t.indexOf(e))>=0&&t.splice(n,1)})}}function Pe(i,e){let t;return new Promise(n=>{const s=e==null?void 0:e.registerCallback(()=>{clearTimeout(t),n(!1)});t=setTimeout(()=>{s==null||s(),n(!0)},i)})}function M(i,e=!1){return i instanceof Error?e&&i.stack?i.stack:i.toString():i+""}function Me(i){throw i}function q(i){return Array.isArray(i)}function pe(i){return q(i)&&!i.some(e=>typeof e!="string")}function ye(i,e=0,t,n=", "){const s=i.length;if(!s)return"";let r="";return e>0&&s>e&&(i=i.slice(0,e),t&&(r=t(s-e))),"'"+i.join("'"+n+"'")+"'"+r}function Tt(i){return typeof(i==null?void 0:i.then)=="function"}function B(i){function e(o,a){const l=o.charCodeAt(a);if(55296<=l&&l<56320){const c=o.charCodeAt(a+1);if(56320<=c&&c<=57343)return(l<<10)+c-56613888}return l}let t="",n=0;const s=String.fromCharCode;let r;for(r=0;r<i.length;r++){const o=e(i,r);o<=127||(t+=i.slice(n,r),o<=2047?(t+=s(192|o>>6),t+=s(128|o&63)):o<=65535?(t+=s(224|o>>12),t+=s(128|o>>6&63),t+=s(128|o&63)):(t+=s(240|o>>18),t+=s(128|o>>12&63),t+=s(128|o>>6&63),t+=s(128|o&63),++r),n=r+1)}return t+=i.slice(n,r)}function me(i){return typeof i=="number"?i:typeof i!="string"||!i.length||/^\s*$|^\s*0[^\d.e]/.test(i)?NaN:+i}const bt=500;class Ct extends de{constructor(e,t){super(e,t),this.signalInitialization=()=>{},this.stopToken=new ve,this.pollIntervalMs=t.pollIntervalSeconds*1e3,this.pollExpirationMs=this.pollIntervalMs-bt;const n=this.syncUpWithCache();if(t.maxInitWaitTimeSeconds!==0){this.initialized=!1;const s=new Promise(r=>this.signalInitialization=r);this.initializationPromise=this.waitForInitializationAsync(s).then(r=>(this.initialized=!0,r))}else this.initialized=!0,this.initializationPromise=Promise.resolve(!1);this.readyPromise=this.getReadyPromise(this.initializationPromise,async s=>(await s,this.getCacheState(this.options.cache.getInMemory()))),t.offline||this.startRefreshWorker(n,this.stopToken)}async waitForInitializationAsync(e){if(this.options.maxInitWaitTimeSeconds<0)return await e,!0;const t=new ve,n=await Promise.race([e.then(()=>!0),Pe(this.options.maxInitWaitTimeSeconds*1e3,t).then(()=>!1)]);return t.abort(),n}async getConfig(){this.options.logger.debug("AutoPollConfigService.getConfig() called.");function e(n){n.debug("AutoPollConfigService.getConfig() - returning value from cache.")}let t;if(!this.isOffline&&!this.initialized){if(t=await this.options.cache.get(this.cacheKey),!t.isExpired(this.pollIntervalMs))return e(this.options.logger),t;this.options.logger.debug("AutoPollConfigService.getConfig() - cache is empty or expired, waiting for initialization."),await this.initializationPromise}return t=await this.options.cache.get(this.cacheKey),t.isExpired(this.pollIntervalMs)?this.options.logger.debug("AutoPollConfigService.getConfig() - cache is empty or expired."):e(this.options.logger),t}refreshConfigAsync(){return this.options.logger.debug("AutoPollConfigService.refreshConfigAsync() called."),super.refreshConfigAsync()}dispose(){this.options.logger.debug("AutoPollConfigService.dispose() called."),super.dispose(),this.stopToken.aborted||this.stopRefreshWorker()}onConfigFetched(e){this.signalInitialization(),super.onConfigFetched(e)}setOnlineCore(){this.startRefreshWorker(null,this.stopToken)}setOfflineCore(){this.stopRefreshWorker(),this.stopToken=new ve}async startRefreshWorker(e,t){this.options.logger.debug("AutoPollConfigService.startRefreshWorker() called.");let n=!0;for(;!t.aborted;){try{const s=new Date().getTime()+this.pollIntervalMs;try{await this.refreshWorkerLogic(n,e)}catch(o){this.options.logger.autoPollConfigServiceErrorDuringPolling(o)}const r=s-new Date().getTime();r>0&&await Pe(r,t)}catch(s){this.options.logger.autoPollConfigServiceErrorDuringPolling(s)}n=!1,e=null}}stopRefreshWorker(){this.options.logger.debug("AutoPollConfigService.stopRefreshWorker() called."),this.stopToken.abort()}async refreshWorkerLogic(e,t){this.options.logger.debug("AutoPollConfigService.refreshWorkerLogic() - called.");const n=await(t??this.options.cache.get(this.cacheKey));n.isExpired(this.pollExpirationMs)?(e?!this.isOfflineExactly:!this.isOffline)&&await this.refreshConfigCoreAsync(n):e&&this.signalInitialization()}getCacheState(e){return e.isEmpty?0:e.isExpired(this.pollIntervalMs)?2:3}}class Ue{constructor(){this.cachedConfig=S.empty}set(e,t){this.cachedConfig=t}get(e){return this.cachedConfig}getInMemory(){return this.cachedConfig}}class Y{constructor(e,t){this.cache=e,this.logger=t,this.cachedConfig=S.empty}async set(e,t){try{if(!t.isEmpty)this.cachedSerializedConfig=S.serialize(t),this.cachedConfig=t;else{this.cachedSerializedConfig=void 0,this.cachedConfig=t;return}await this.cache.set(e,this.cachedSerializedConfig)}catch(n){this.logger.configServiceCacheWriteError(n)}}updateCachedConfig(e){e==null||e===this.cachedSerializedConfig||(this.cachedConfig=S.deserialize(e),this.cachedSerializedConfig=e)}get(e){try{const t=this.cache.get(e);if(Tt(t))return(async n=>{try{this.updateCachedConfig(await n)}catch(s){this.logger.configServiceCacheReadError(s)}return this.cachedConfig})(t);this.updateCachedConfig(t)}catch(t){this.logger.configServiceCacheReadError(t)}return Promise.resolve(this.cachedConfig)}getInMemory(){return this.cachedConfig}}h.LogLevel=void 0,function(i){i[i.Debug=4]="Debug",i[i.Info=3]="Info",i[i.Warn=2]="Warn",i[i.Error=1]="Error",i[i.Off=-1]="Off"}(h.LogLevel||(h.LogLevel={}));function It(i){return h.LogLevel[i]}class m{static from(...e){return(t,...n)=>new m(t,e,n)}constructor(e,t,n){this.strings=e,this.argNames=t,this.argValues=n}get defaultFormattedMessage(){let e=this.cachedDefaultFormattedMessage;if(e===void 0){e="";const{strings:t,argValues:n}=this;let s=0;for(;s<t.length-1;s++)e+=t[s],e+=n[s];e+=t[s],this.cachedDefaultFormattedMessage=e}return e}toString(){return this.defaultFormattedMessage}}class Rt{get level(){var e;return(e=this.logger.level)!==null&&e!==void 0?e:2}get eol(){var e;return(e=this.logger.eol)!==null&&e!==void 0?e:` `}constructor(e,t){this.logger=e,this.hooks=t}isEnabled(e){return this.level>=e}log(e,t,n,s){var r;return this.isEnabled(e)&&this.logger.log(e,t,n,s),e===1&&((r=this.hooks)===null||r===void 0||r.emit("clientError",n.toString(),s)),n}debug(e){this.log(4,0,e)}configJsonIsNotPresent(e){return this.log(1,1e3,m.from("DEFAULT_RETURN_VALUE")`Config JSON is not present. Returning ${e}.`)}configJsonIsNotPresentSingle(e,t,n){return this.log(1,1e3,m.from("KEY","DEFAULT_PARAM_NAME","DEFAULT_PARAM_VALUE")`Config JSON is not present when evaluating setting '${e}'. Returning the \`${t}\` parameter that you specified in your application: '${n}'.`)}settingEvaluationFailedDueToMissingKey(e,t,n,s){return this.log(1,1001,m.from("KEY","DEFAULT_PARAM_NAME","DEFAULT_PARAM_VALUE","AVAILABLE_KEYS")`Failed to evaluate setting '${e}' (the key was not found in config JSON). Returning the \`${t}\` parameter that you specified in your application: '${n}'. Available keys: [${s}].`)}settingEvaluationError(e,t,n){return this.log(1,1002,m.from("METHOD_NAME","DEFAULT_RETURN_VALUE")`Error occurred in the \`${e}\` method. Returning ${t}.`,n)}settingEvaluationErrorSingle(e,t,n,s,r){return this.log(1,1002,m.from("METHOD_NAME","KEY","DEFAULT_PARAM_NAME","DEFAULT_PARAM_VALUE")`Error occurred in the \`${e}\` method while evaluating setting '${t}'. Returning the \`${n}\` parameter that you specified in your application: '${s}'.`,r)}forceRefreshError(e,t){return this.log(1,1003,m.from("METHOD_NAME")`Error occurred in the \`${e}\` method.`,t)}fetchFailedDueToInvalidSdkKey(){return this.log(1,1100,"Your SDK Key seems to be wrong. You can find the valid SDK Key at https://app.configcat.com/sdkkey")}fetchFailedDueToUnexpectedHttpResponse(e,t){return this.log(1,1101,m.from("STATUS_CODE","REASON_PHRASE")`Unexpected HTTP response was received while trying to fetch config JSON: ${e} ${t}`)}fetchFailedDueToRequestTimeout(e,t){return this.log(1,1102,m.from("TIMEOUT")`Request timed out while trying to fetch config JSON. Timeout value: ${e}ms`,t)}fetchFailedDueToUnexpectedError(e){return this.log(1,1103,"Unexpected error occurred while trying to fetch config JSON. It is most likely due to a local network issue. Please make sure your application can reach the ConfigCat CDN servers (or your proxy server) over HTTP.",e)}fetchFailedDueToRedirectLoop(){return this.log(1,1104,"Redirection loop encountered while trying to fetch config JSON. Please contact us at https://configcat.com/support/")}fetchReceived200WithInvalidBody(e){return this.log(1,1105,"Fetching config JSON was successful but the HTTP response content was invalid.",e)}fetchReceived304WhenLocalCacheIsEmpty(e,t){return this.log(1,1106,m.from("STATUS_CODE","REASON_PHRASE")`Unexpected HTTP response was received when no config JSON is cached locally: ${e} ${t}`)}autoPollConfigServiceErrorDuringPolling(e){return this.log(1,1200,"Error occurred during auto polling.",e)}settingForVariationIdIsNotPresent(e){return this.log(1,2011,m.from("VARIATION_ID")`Could not find the setting for the specified variation ID: '${e}'.`)}configServiceCacheReadError(e){return this.log(1,2200,"Error occurred while reading the cache.",e)}configServiceCacheWriteError(e){return this.log(1,2201,"Error occurred while writing the cache.",e)}clientIsAlreadyCreated(e){return this.log(2,3e3,m.from("SDK_KEY")`There is an existing client instance for the specified SDK Key. No new client instance will be created and the specified options are ignored. Returning the existing client instance. SDK Key: '${e}'.`)}userObjectIsMissing(e){return this.log(2,3001,m.from("KEY")`Cannot evaluate targeting rules and % options for setting '${e}' (User Object is missing). You should pass a User Object to the evaluation methods like \`getValueAsync()\` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/`)}dataGovernanceIsOutOfSync(){return this.log(2,3002,"The `dataGovernance` parameter specified at the client initialization is not in sync with the preferences on the ConfigCat Dashboard. Read more: https://configcat.com/docs/advanced/data-governance/")}userObjectAttributeIsMissingPercentage(e,t){return this.log(2,3003,m.from("KEY","ATTRIBUTE_NAME","ATTRIBUTE_NAME")`Cannot evaluate % options for setting '${e}' (the User.${t} attribute is missing). You should set the User.${t} attribute in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/`)}userObjectAttributeIsMissingCondition(e,t,n){return this.log(2,3003,m.from("CONDITION","KEY","ATTRIBUTE_NAME","ATTRIBUTE_NAME")`Cannot evaluate condition (${e}) for setting '${t}' (the User.${n} attribute is missing). You should set the User.${n} attribute in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/`)}userObjectAttributeIsInvalid(e,t,n,s){return this.log(2,3004,m.from("CONDITION","KEY","REASON","ATTRIBUTE_NAME")`Cannot evaluate condition (${e}) for setting '${t}' (${n}). Please check the User.${s} attribute and make sure that its value corresponds to the comparison operator.`)}userObjectAttributeIsAutoConverted(e,t,n,s){return this.log(2,3005,m.from("CONDITION","KEY","ATTRIBUTE_NAME","ATTRIBUTE_VALUE")`Evaluation of condition (${e}) for setting '${t}' may not produce the expected result (the User.${n} attribute is not a string value, thus it was automatically converted to the string value '${s}'). Please make sure that using a non-string value was intended.`)}configServiceCannotInitiateHttpCalls(){return this.log(2,3200,"Client is in offline mode, it cannot initiate HTTP calls.")}configServiceMethodHasNoEffectDueToDisposedClient(e){return this.log(2,3201,m.from("METHOD_NAME")`The client object is already disposed, thus \`${e}()\` has no effect.`)}configServiceMethodHasNoEffectDueToOverrideBehavior(e,t){return this.log(2,3202,m.from("OVERRIDE_BEHAVIOR","METHOD_NAME")`Client is configured to use the \`${e}\` override behavior, thus \`${t}()\` has no effect.`)}settingEvaluated(e){return this.log(3,5e3,m.from("EVALUATE_LOG")`${e}`)}configServiceStatusChanged(e){return this.log(3,5200,m.from("MODE")`Switched to ${e.toUpperCase()} mode.`)}}class _e{constructor(e=2,t=` `){this.level=e,this.eol=t,this.SOURCE="ConfigCat"}log(e,t,n,s){const[r,o]=e===4?[console.info,"DEBUG"]:e===3?[console.info,"INFO"]:e===2?[console.warn,"WARN"]:e===1?[console.error,"ERROR"]:[console.log,It(e).toUpperCase()],a=s!==void 0?this.eol+M(s,!0):"";r(`${this.SOURCE} - ${o} - [${t}] ${n}${a}`)}}class Ee{constructor(){this.addListener=this.on,this.off=this.removeListener}on(){return this}once(){return this}removeListener(){return this}removeAllListeners(){return this}listeners(){return[]}listenerCount(){return 0}eventNames(){return[]}emit(){return!1}}function Ve(i){function e(D,$){var ce=D<<$|D>>>32-$;return ce}var t,n,s,r=new Array(80),o=1732584193,a=4023233417,l=2562383102,c=271733878,u=3285377520,g,f,d,p,E,w;i=B(i);var O=i.length,I=new Array;for(n=0;n<O-3;n+=4)s=i.charCodeAt(n)<<24|i.charCodeAt(n+1)<<16|i.charCodeAt(n+2)<<8|i.charCodeAt(n+3),I.push(s);switch(O%4){case 0:n=2147483648;break;case 1:n=i.charCodeAt(O-1)<<24|8388608;break;case 2:n=i.charCodeAt(O-2)<<24|i.charCodeAt(O-1)<<16|32768;break;case 3:n=i.charCodeAt(O-3)<<24|i.charCodeAt(O-2)<<16|i.charCodeAt(O-1)<<8|128;break}for(I.push(n);I.length%16!=14;)I.push(0);for(I.push(O>>>29),I.push(O<<3&4294967295),t=0;t<I.length;t+=16){for(n=0;n<16;n++)r[n]=I[t+n];for(n=16;n<=79;n++)r[n]=e(r[n-3]^r[n-8]^r[n-14]^r[n-16],1);for(g=o,f=a,d=l,p=c,E=u,n=0;n<=19;n++)w=e(g,5)+(f&d|~f&p)+E+r[n]+1518500249&4294967295,E=p,p=d,d=e(f,30),f=g,g=w;for(n=20;n<=39;n++)w=e(g,5)+(f^d^p)+E+r[n]+1859775393&4294967295,E=p,p=d,d=e(f,30),f=g,g=w;for(n=40;n<=59;n++)w=e(g,5)+(f&d|f&p|d&p)+E+r[n]+2400959708&4294967295,E=p,p=d,d=e(f,30),f=g,g=w;for(n=60;n<=79;n++)w=e(g,5)+(f^d^p)+E+r[n]+3395469782&4294967295,E=p,p=d,d=e(f,30),f=g,g=w;o=o+g&4294967295,a=a+f&4294967295,l=l+d&4294967295,c=c+p&4294967295,u=u+E&4294967295}return Be([o,a,l,c,u])}function qe(i){function e(vt,pt){return vt>>>pt|vt<<32-pt}const t="length";var n=Math.pow,s=n(2,32),r,o,a=qe,l=a.h,c=a.k;if(!c){l=[],c=[];for(var u={},g=2,f=0;f<64;g++)if(!u[g]){for(r=0;r<313;r+=g)u[r]=g;l[f]=n(g,.5)*s|0,c[f++]=n(g,1/3)*s|0}a.h=l=l.slice(0,8),a.k=c}var d=i[t]*8;i+="€";for(var p=[];i[t]%64-56;)i+="\0";for(r=0;r<i[t];r++)o=i.charCodeAt(r),p[r>>2]|=o<<(3-r)%4*8;for(p[p[t]]=d/s|0,p[p[t]]=d,o=0;o<p[t];){var E=p.slice(o,o+=16),w=l;for(l=l.slice(0,8),r=0;r<64;r++){var O=E[r-15],I=E[r-2],D=l[0],$=l[4],ce=l[7]+(e($,6)^e($,11)^e($,25))+($&l[5]^~$&l[6])+c[r]+(E[r]=r<16?E[r]:E[r-16]+(e(O,7)^e(O,18)^O>>>3)+E[r-7]+(e(I,17)^e(I,19)^I>>>10)|0),pn=(e(D,2)^e(D,13)^e(D,22))+(D&l[1]^D&l[2]^l[1]&l[2]);l=[ce+pn|0].concat(l),l[4]=l[4]+ce|0}for(r=0;r<8;r++)l[r]=l[r]+w[r]|0}return Be(l,8)}function Be(i,e){const t="0123456789abcdef";var n="";e??(e=i.length);for(let s=0;s<e;s++)for(let r=3;r>=0;r--){const o=i[s]>>(r<<3)&255;n+=t[o>>4],n+=t[o&15]}return n}const xe=new Ee;class We{constructor(e){this.addListener=this.on,this.off=this.removeListener,this.eventEmitter=e}tryDisconnect(){const e=this.eventEmitter;return this.eventEmitter=xe,e!==xe}on(e,t){return this.eventEmitter.on(e,t),this}once(e,t){return this.eventEmitter.once(e,t),this}removeListener(e,t){return this.eventEmitter.removeListener(e,t),this}removeAllListeners(e){return this.eventEmitter.removeAllListeners(e),this}listeners(e){return this.eventEmitter.listeners(e)}listenerCount(e){return this.eventEmitter.listenerCount(e)}eventNames(){return this.eventEmitter.eventNames()}emit(e,...t){return this.eventEmitter.emit(e,...t)}}function Ke(){const i=function(e){this.target=e};return i.prototype.deref=function(){return this.target},i.isFallback=!0,i}const He=()=>typeof WeakRef=="function";h.PollingMode=void 0,function(i){i[i.AutoPoll=0]="AutoPoll",i[i.LazyLoad=1]="LazyLoad",i[i.ManualPoll=2]="ManualPoll"}(h.PollingMode||(h.PollingMode={})),h.DataGovernance=void 0,function(i){i[i.Global=0]="Global",i[i.EuOnly=1]="EuOnly"}(h.DataGovernance||(h.DataGovernance={}));class U{constructor(e,t,n,s,r){var o,a,l;if(this.requestTimeoutMs=3e4,this.baseUrlOverriden=!1,this.offline=!1,!e)throw new Error("Invalid 'sdkKey' value");switch(this.sdkKey=e,this.clientVersion=t,this.dataGovernance=(o=n==null?void 0:n.dataGovernance)!==null&&o!==void 0?o:0,this.dataGovernance){case 1:this.baseUrl="https://cdn-eu.configcat.com";break;default:this.baseUrl="https://cdn-global.configcat.com";break}const c=(a=r==null?void 0:r())!==null&&a!==void 0?a:new Ee,u=new We(c),g=new(He()?WeakRef:Ke())(u);this.hooks={hooks:u,hooksWeakRef:g,emit(p,...E){var w,O;return(O=(w=this.hooksWeakRef.deref())===null||w===void 0?void 0:w.emit(p,...E))!==null&&O!==void 0?O:!1}};let f,d;if(n){if(f=n.logger,d=n.cache,n.requestTimeoutMs){if(n.requestTimeoutMs<0)throw new Error("Invalid 'requestTimeoutMs' value");this.requestTimeoutMs=n.requestTimeoutMs}n.baseUrl&&(this.baseUrl=n.baseUrl,this.baseUrlOverriden=!0),n.flagOverrides&&(this.flagOverrides=n.flagOverrides),n.defaultUser&&(this.defaultUser=n.defaultUser),n.offline&&(this.offline=n.offline),(l=n.setupHooks)===null||l===void 0||l.call(n,u)}this.logger=new Rt(f??new _e,this.hooks),this.cache=d?new Y(d,this.logger):s?s(this):new Ue}yieldHooks(){const e=this.hooks,t=e.hooks;return delete e.hooks,t??new We(new Ee)}getUrl(){return this.baseUrl+"/configuration-files/"+this.sdkKey+"/"+U.configFileName+"?sdk="+this.clientVersion}getCacheKey(){return Ve(`${this.sdkKey}_${U.configFileName}_${S.serializationFormatVersion}`)}}U.configFileName="config_v6.json";class ze extends U{constructor(e,t,n,s,r,o){super(e,t+"/a-"+n,s,r,o),this.pollIntervalSeconds=60,this.maxInitWaitTimeSeconds=5,s&&(s.pollIntervalSeconds!=null&&(this.pollIntervalSeconds=s.pollIntervalSeconds),s.maxInitWaitTimeSeconds!=null&&(this.maxInitWaitTimeSeconds=s.maxInitWaitTimeSeconds));const a=2147483;if(!(typeof this.pollIntervalSeconds=="number"&&1<=this.pollIntervalSeconds&&this.pollIntervalSeconds<=a))throw new Error("Invalid 'pollIntervalSeconds' value");if(!(typeof this.maxInitWaitTimeSeconds=="number"&&this.maxInitWaitTimeSeconds<=a))throw new Error("Invalid 'maxInitWaitTimeSeconds' value")}}class je extends U{constructor(e,t,n,s,r,o){super(e,t+"/m-"+n,s,r,o)}}class Je extends U{constructor(e,t,n,s,r,o){if(super(e,t+"/l-"+n,s,r,o),this.cacheTimeToLiveSeconds=60,s&&s.cacheTimeToLiveSeconds!=null&&(this.cacheTimeToLiveSeconds=s.cacheTimeToLiveSeconds),!(typeof this.cacheTimeToLiveSeconds=="number"&&1<=this.cacheTimeToLiveSeconds&&this.cacheTimeToLiveSeconds<=2147483647))throw new Error("Invalid 'cacheTimeToLiveSeconds' value")}}h.OverrideBehaviour=void 0,function(i){i[i.LocalOnly=0]="LocalOnly",i[i.LocalOverRemote=1]="LocalOverRemote",i[i.RemoteOverLocal=2]="RemoteOverLocal"}(h.OverrideBehaviour||(h.OverrideBehaviour={}));function Nt(i){return h.OverrideBehaviour[i]}class Ft{constructor(e,t){this.initialSettings=Ge(e),t&&(this.map=e)}getOverrides(){return Promise.resolve(this.getOverridesSync())}getOverridesSync(){return this.map?Ge(this.map):this.initialSettings}}function Ge(i){const e={};for(const t in i)Object.prototype.hasOwnProperty.call(i,t)&&(e[t]=P.fromValue(i[t]));return e}const Lt="cc-",Q=";str";class kt{get currentValue(){if(!(typeof location>"u"))return location.search}}let X;class Dt{constructor(e,t,n){this.watchChanges=e,this.paramPrefix=t??Lt,n??(n=X??(X=new kt)),this.queryStringProvider=n;const s=n.currentValue;this.settings=Qe(s,this.paramPrefix),this.queryString=Ye(s)}getOverrides(){return Promise.resolve(this.getOverridesSync())}getOverridesSync(){if(this.watchChanges){const e=this.queryStringProvider.currentValue,t=Ye(e);this.queryString!==t&&(this.settings=Qe(e,this.paramPrefix),this.queryString=t)}return this.settings}}function Ye(i){if(i==null)return"";if(typeof i=="string")return i;let e="",t="?";for(const n in i){if(!Object.prototype.hasOwnProperty.call(i,n))continue;const s=i[n];let r,o;if(!q(s))r=s,o=1;else if(s.length)r=s[0],o=s.length;else continue;for(let a=0;e+=t+encodeURIComponent(n)+"="+encodeURIComponent(r),!(++a>=o);)t="&",r=s[a]}return e}function Qe(i,e){const t={};return typeof i=="string"?Pt(i,e,t):i!=null&&$t(i,e,t),t}function $t(i,e,t){for(const n in i){if(!Object.prototype.hasOwnProperty.call(i,n))continue;const s=i[n];let r,o;if(!q(s))r=s,o=1;else if(s.length)r=s[0],o=s.length;else continue;for(let a=0;Xe(n,r,e,t),!(++a>=o);)r=s[a]}}function Pt(i,e,t){if(!i||i.lastIndexOf("?",0)<0)return;const n=i.substring(1).split("&");for(let s of n){s=s.replace(/\+/g," ");const r=s.indexOf("="),o=decodeURIComponent(r>=0?s.substring(0,r):s),a=r>=0?decodeURIComponent(s.substring(r+1)):"";Xe(o,a,e,t)}}function Xe(i,e,t,n){if(!i||i.length<=t.length||i.lastIndexOf(t,0)<0)return;i=i.substring(t.length),i.length>Q.length&&i.indexOf(Q,i.length-Q.length)>=0?i=i.substring(0,i.length-Q.length):e=Mt(e),n[i]=P.fromValue(e)}function Mt(i){switch(i.toLowerCase()){case"false":return!1;case"true":return!0;default:const e=me(i);return isNaN(e)?i:e}}class Ut extends de{constructor(e,t){super(e,t),this.cacheTimeToLiveMs=t.cacheTimeToLiveSeconds*1e3;const n=this.syncUpWithCache();this.readyPromise=this.getReadyPromise(n,async s=>this.getCacheState(await s))}async getConfig(){this.options.logger.debug("LazyLoadConfigService.getConfig() called.");function e(n,s=""){n.debug(`LazyLoadConfigService.getConfig(): cache is empty or expired${s}.`)}let t=await this.options.cache.get(this.cacheKey);return t.isExpired(this.cacheTimeToLiveMs)?(this.isOffline?e(this.options.logger):(e(this.options.logger,", calling refreshConfigCoreAsync()"),[,t]=await this.refreshConfigCoreAsync(t)),t):(this.options.logger.debug("LazyLoadConfigService.getConfig(): cache is valid, returning from cache."),t)}refreshConfigAsync(){return this.options.logger.debug("LazyLoadConfigService.refreshConfigAsync() called."),super.refreshConfigAsync()}getCacheState(e){return e.isEmpty?0:e.isExpired(this.cacheTimeToLiveMs)?2:3}}class _t extends de{constructor(e,t){super(e,t);const n=this.syncUpWithCache();this.readyPromise=this.getReadyPromise(n,async s=>this.getCacheState(await s))}getCacheState(e){return e.isEmpty?0:2}async getConfig(){return this.options.logger.debug("ManualPollService.getConfig() called."),await this.options.cache.get(this.cacheKey)}refreshConfigAsync(){return this.options.logger.debug("ManualPollService.refreshConfigAsync() called."),super.refreshConfigAsync()}}const Ze="<invalid value>",Se="<invalid name>",Oe="<invalid operator>",et="<invalid reference>",Vt=10;class tt{constructor(e){this.eol=e,this.log="",this.indent=""}resetIndent(){return this.indent="",this}increaseIndent(){return this.indent+=" ",this}decreaseIndent(){return this.indent=this.indent.slice(0,-2),this}newLine(e){return this.log+=this.eol+this.indent+(e??""),this}append(e){return this.log+=e,this}toString(){return this.log}appendUserConditionCore(e,t,n){return this.append(`User.${e} ${Ae(t)} '${n??Ze}'`)}appendUserConditionString(e,t,n,s){return typeof n!="string"?this.appendUserConditionCore(e,t):this.appendUserConditionCore(e,t,s?"<hashed value>":n)}appendUserConditionStringList(e,t,n,s){if(!pe(n))return this.appendUserConditionCore(e,t);const r="value",o="values",a=Ae(t);if(s)return this.append(`User.${e} ${a} [<${n.length} hashed ${n.length===1?r:o}>]`);{const l=ye(n,Vt,c=>`, ... <${c} more ${c===1?r:o}>`);return this.append(`User.${e} ${a} [${l}]`)}}appendUserConditionNumber(e,t,n,s){if(typeof n!="number")return this.appendUserConditionCore(e,t);const r=Ae(t);let o;return s&&!isNaN(o=new Date(n*1e3))?this.append(`User.${e} ${r} '${n}' (${o.toISOString()} UTC)`):this.append(`User.${e} ${r} '${n}'`)}appendUserCondition(e){const t=typeof e.comparisonAttribute=="string"?e.comparisonAttribute:Se,n=e.comparator;switch(e.comparator){case 0:case 1:case 2:case 3:case 4:case 5:case 30:case 31:case 32:case 33:case 34:case 35:return this.appendUserConditionStringList(t,n,e.comparisonValue,!1);case 6:case 7:case 8:case 9:case 28:case 29:return this.appendUserConditionString(t,n,e.comparisonValue,!1);case 10:case 11:case 12:case 13:case 14:case 15:return this.appendUserConditionNumber(t,n,e.comparisonValue);case 16:case 17:case 22:case 23:case 24:case 25:case 26:case 27:return this.appendUserConditionStringList(t,n,e.comparisonValue,!0);case 18:case 19:return this.appendUserConditionNumber(t,n,e.comparisonValue,!0);case 20:case 21:return this.appendUserConditionString(t,n,e.comparisonValue,!0);default:return this.appendUserConditionCore(t,n,e.comparisonValue)}}appendPrerequisiteFlagCondition(e,t){const n=typeof e.prerequisiteFlagKey!="string"?Se:e.prerequisiteFlagKey in t?e.prerequisiteFlagKey:et,s=e.comparator,r=e.comparisonValue;return this.append(`Flag '${n}' ${qt(s)} '${Z(r)}'`)}appendSegmentCondition(e){const t=e.segment,n=e.comparator,s=t==null?et:typeof t.name!="string"||!t.name?Se:t.name;return this.append(`User ${nt(n)} '${s}'`)}appendConditionResult(e){return this.append(`${e}`)}appendConditionConsequence(e){return this.append(" => ").appendConditionResult(e),e?this:this.append(", skipping the remaining AND conditions")}appendTargetingRuleThenPart(e,t){(t?this.newLine():this.append(" ")).append("THEN");const n=e.then;return this.append(q(n)?" % options":` '${Z(n.value)}'`)}appendTargetingRuleConsequence(e,t,n){return this.increaseIndent(),this.appendTargetingRuleThenPart(e,n).append(" => ").append(t===!0?"MATCH, applying rule":t===!1?"no match":t),this.decreaseIndent()}}function Ae(i){switch(i){case 0:case 16:case 4:return"IS ONE OF";case 1:case 17:case 5:return"IS NOT ONE OF";case 2:return"CONTAINS ANY OF";case 3:return"NOT CONTAINS ANY OF";case 6:case 12:return"<";case 7:case 13:return"<=";case 8:case 14:return">";case 9:case 15:return">=";case 10:return"=";case 11:return"!=";case 18:return"BEFORE";case 19:return"AFTER";case 28:case 20:return"EQUALS";case 29:case 21:return"NOT EQUALS";case 30:case 22:return"STARTS WITH ANY OF";case 31:case 23:return"NOT STARTS WITH ANY OF";case 32:case 24:return"ENDS WITH ANY OF";case 33:case 25:return"NOT ENDS WITH ANY OF";case 34:case 26:return"ARRAY CONTAINS ANY OF";case 35:case 27:return"ARRAY NOT CONTAINS ANY OF";default:return Oe}}function we(i){return new tt("").appendUserCondition(i).toString()}function qt(i){switch(i){case 0:return"EQUALS";case 1:return"NOT EQUALS";default:return Oe}}function nt(i){switch(i){case 0:return"IS IN SEGMENT";case 1:return"IS NOT IN SEGMENT";default:return Oe}}function Z(i){return z(i)?i.toString():Ze}const it=/^[0-9]+$/,x=(i,e)=>{const t=it.test(i),n=it.test(e);return t&&n&&(i=+i,e=+e),i===e?0:t&&!n?-1:n&&!t?1:i<e?-1:1},Te=256,ee=Number.MAX_SAFE_INTEGER||9007199254740991,W=[],y=[],v={};let Bt=0;const A=(i,e)=>{const t=Bt++;v[i]=t,y[t]=e,W[t]=new RegExp(e)};A("NUMERICIDENTIFIER","0|[1-9]\\d*"),A("NUMERICIDENTIFIERLOOSE","[0-9]+"),A("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*"),A("MAINVERSION",`(${y[v.NUMERICIDENTIFIER]})\\.(${y[v.NUMERICIDENTIFIER]})\\.(${y[v.NUMERICIDENTIFIER]})`),A("MAINVERSIONLOOSE",`(${y[v.NUMERICIDENTIFIERLOOSE]})\\.(${y[v.NUMERICIDENTIFIERLOOSE]})\\.(${y[v.NUMERICIDENTIFIERLOOSE]})`),A("PRERELEASEIDENTIFIER",`(?:${y[v.NUMERICIDENTIFIER]}|${y[v.NONNUMERICIDENTIFIER]})`),A("PRERELEASEIDENTIFIERLOOSE",`(?:${y[v.NUMERICIDENTIFIERLOOSE]}|${y[v.NONNUMERICIDENTIFIER]})`),A("PRERELEASE",`(?:-(${y[v.PRERELEASEIDENTIFIER]}(?:\\.${y[v.PRERELEASEIDENTIFIER]})*))`),A("PRERELEASELOOSE",`(?:-?(${y[v.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${y[v.PRERELEASEIDENTIFIERLOOSE]})*))`),A("BUILDIDENTIFIER","[0-9A-Za-z-]+"),A("BUILD",`(?:\\+(${y[v.BUILDIDENTIFIER]}(?:\\.${y[v.BUILDIDENTIFIER]})*))`),A("FULLPLAIN",`v?${y[v.MAINVERSION]}${y[v.PRERELEASE]}?${y[v.BUILD]}?`),A("FULL",`^${y[v.FULLPLAIN]}$`),A("LOOSEPLAIN",`[v=\\s]*${y[v.MAINVERSIONLOOSE]}${y[v.PRERELEASELOOSE]}?${y[v.BUILD]}?`),A("LOOSE",`^${y[v.LOOSEPLAIN]}$`);class C{constructor(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof C){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid Version: ${e}`);if(e.length>Te)throw new TypeError(`version is longer than ${Te} characters`);this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const n=e.trim().match(t.loose?W[v.LOOSE]:W[v.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>ee||this.major<0)throw new TypeError("Invalid major version");if(this.minor>ee||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>ee||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){const r=+s;if(r>=0&&r<ee)return r}return s}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(!(e instanceof C)){if(typeof e=="string"&&e===this.version)return 0;e=new C(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof C||(e=new C(e,this.options)),x(this.major,e.major)||x(this.minor,e.minor)||x(this.patch,e.patch)}comparePre(e){if(e instanceof C||(e=new C(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{const n=this.prerelease[t],s=e.prerelease[t];if(n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return x(n,s)}while(++t)}compareBuild(e){e instanceof C||(e=new C(e,this.options));let t=0;do{const n=this.build[t],s=e.build[t];if(n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return x(n,s)}while(++t)}inc(e,t){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t),this.inc("pre",t);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t),this.inc("pre",t);break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":if(this.prerelease.length===0)this.prerelease=[0];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);n===-1&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error(`invalid increment argument: ${e}`)}return this.format(),this.raw=this.version,this}}const be=(i,e)=>{if((!e||typeof e!="object")&&(e={loose:!!e,includePrerelease:!1}),i instanceof C)return i;if(typeof i!="string"||i.length>Te||!(e.loose?W[v.LOOSE]:W[v.FULL]).test(i))return null;try{return new C(i,e)}catch{return null}};class xt{constructor(e,t,n,s={}){this.identifier=e,this.email=t,this.country=n,this.custom=s}}function st(i,e){var t,n;switch(e){case"Identifier":return(t=i.identifier)!==null&&t!==void 0?t:"";case"Email":return i.email;case"Country":return i.country;default:return(n=i.custom)===null||n===void 0?void 0:n[e]}}function Wt(i){var e;const t={},n="Identifier",s="Email",r="Country";if(t[n]=(e=i.identifier)!==null&&e!==void 0?e:"",i.email!=null&&(t[s]=i.email),i.country!=null&&(t[r]=i.country),i.custom!=null){const o=[n,s,r];for(const[a,l]of Object.entries(i.custom))l!=null&&o.indexOf(a)<0&&(t[a]=l)}return t}class K{get visitedFlags(){var e;return(e=this.$visitedFlags)!==null&&e!==void 0?e:this.$visitedFlags=[]}constructor(e,t,n,s){this.key=e,this.setting=t,this.user=n,this.settings=s}static forPrerequisiteFlag(e,t,n){const s=new K(e,t,n.user,n.settings);return s.$visitedFlags=n.visitedFlags,s.logBuilder=n.logBuilder,s}}const rt="The current targeting rule is ignored and the evaluation continues with the next rule.",Ce="cannot evaluate, User Object is missing",Kt=i=>`cannot evaluate, the User.${i} attribute is missing`,Ht=(i,e)=>`cannot evaluate, the User.${i} attribute is invalid (${e})`;class zt{constructor(e){this.logger=e}evaluate(e,t){this.logger.debug("RolloutEvaluator.evaluate() called.");let n=t.logBuilder;this.logger.isEnabled(3)&&(t.logBuilder=n=new tt(this.logger.eol),n.append(`Evaluating '${t.key}'`),t.user&&n.append(` for User '${JSON.stringify(Wt(t.user))}'`),n.increaseIndent());let s;try{let r,o;if(e!=null){const a=t.setting.type;if(a>=0&&!Gt(e,a)){const l=wt(a);throw new TypeError(`The type of a setting must match the type of the specified default value. Setting's type was ${l} but the default value's type was ${typeof e}. Please use a default value which corresponds to the setting type ${l}. Learn more: https://configcat.com/docs/sdk-reference/js/#setting-type-mapping`)}r=this.evaluateSetting(t),s=r.selectedValue.value,o=typeof s==typeof e}else r=this.evaluateSetting(t),s=r.selectedValue.value,o=z(s);return o||Ne(s),r}catch(r){throw n==null||n.resetIndent().increaseIndent(),s=e,r}finally{n&&(n.newLine(`Returning '${s}'.`).decreaseIndent(),this.logger.settingEvaluated(n.toString()))}}evaluateSetting(e){let t;const n=e.setting.targetingRules;if(n.length>0&&(t=this.evaluateTargetingRules(n,e)))return t;const s=e.setting.percentageOptions;return s.length>0&&(t=this.evaluatePercentageOptions(s,void 0,e))?t:{selectedValue:e.setting}}evaluateTargetingRules(e,t){const n=t.logBuilder;n==null||n.newLine("Evaluating targeting rules and applying the first match if any:");for(let s=0;s<e.length;s++){const r=e[s],o=r.conditions,a=this.evaluateConditions(o,r,t.key,t);if(a!==!0){H(a)&&(n==null||n.increaseIndent().newLine(rt).decreaseIndent());continue}if(!q(r.then))return{selectedValue:r.then,matchedTargetingRule:r};const l=r.then;n==null||n.increaseIndent();const c=this.evaluatePercentageOptions(l,r,t);if(c)return n==null||n.decreaseIndent(),c;n==null||n.newLine(rt).decreaseIndent()}}evaluatePercentageOptions(e,t,n){const s=n.logBuilder;if(!n.user){s==null||s.newLine("Skipping % options because the User Object is missing."),n.isMissingUserObjectLogged||(this.logger.userObjectIsMissing(n.key),n.isMissingUserObjectLogged=!0);return}const r=n.setting.percentageOptionsAttribute,o=st(n.user,r);if(o==null){s==null||s.newLine(`Skipping % options because the User.${r} attribute is missing.`),n.isMissingUserObjectAttributeLogged||(this.logger.userObjectAttributeIsMissingPercentage(n.key,r),n.isMissingUserObjectAttributeLogged=!0);return}s==null||s.newLine(`Evaluating % options based on the User.${r} attribute:`);const a=Ve(n.key+at(o)),l=parseInt(a.substring(0,7),16)%100;s==null||s.newLine(`- Computing hash in the [0..99] range from User.${r} => ${l} (this value is sticky and consistent across all SDKs)`);let c=0;for(let u=0;u<e.length;u++){const g=e[u];if(c+=g.percentage,!(l>=c))return s==null||s.newLine(`- Hash value ${l} selects % option ${u+1} (${g.percentage}%), '${Z(g.value)}'.`),{selectedValue:g,matchedTargetingRule:t,matchedPercentageOption:g}}throw new Error("Sum of percentage option percentages is less than 100.")}evaluateConditions(e,t,n,s){let r=!0;const o=s.logBuilder;let a=!1;o==null||o.newLine("- ");for(let l=0;l<e.length;l++){const c=e[l];switch(o&&(l?o.increaseIndent().newLine("AND "):o.append("IF ").increaseIndent()),c.type){case"UserCondition":r=this.evaluateUserCondition(c,n,s),a=e.length>1;break;case"PrerequisiteFlagCondition":r=this.evaluatePrerequisiteFlagCondition(c,s),a=!0;break;case"SegmentCondition":r=this.evaluateSegmentCondition(c,s),a=!H(r)||r!==Ce||e.length>1;break;default:throw new Error}const u=r===!0;if(o&&((!t||e.length>1)&&o.appendConditionConsequence(u),o.decreaseIndent()),!u)break}return t&&(o==null||o.appendTargetingRuleConsequence(t,r,a)),r}evaluateUserCondition(e,t,n){const s=n.logBuilder;if(s==null||s.appendUserCondition(e),!n.user)return n.isMissingUserObjectLogged||(this.logger.userObjectIsMissing(n.key),n.isMissingUserObjectLogged=!0),Ce;const r=e.comparisonAttribute,o=st(n.user,r);if(o==null||o==="")return this.logger.userObjectAttributeIsMissingCondition(we(e),n.key,r),Kt(r);let a,l,c,u;switch(e.comparator){case 28:case 29:return a=F(r,o,e,n.key,this.logger),this.evaluateTextEquals(a,e.comparisonValue,e.comparator===29);case 20:case 21:return a=F(r,o,e,n.key,this.logger),this.evaluateSensitiveTextEquals(a,e.comparisonValue,n.setting.configJsonSalt,t,e.comparator===21);case 0:case 1:return a=F(r,o,e,n.key,this.logger),this.evaluateTextIsOneOf(a,e.comparisonValue,e.comparator===1);case 16:case 17:return a=F(r,o,e,n.key,this.logger),this.evaluateSensitiveTextIsOneOf(a,e.comparisonValue,n.setting.configJsonSalt,t,e.comparator===17);case 30: