@harnessio/ff-nodejs-server-sdk
Advanced tools
Comparing version 1.1.0 to 1.1.1
@@ -1,5 +0,5 @@ | ||
var Xt=Object.create;var te=Object.defineProperty,Zt=Object.defineProperties,er=Object.getOwnPropertyDescriptor,tr=Object.getOwnPropertyDescriptors,rr=Object.getOwnPropertyNames,He=Object.getOwnPropertySymbols,ir=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty,nr=Object.prototype.propertyIsEnumerable;var Ye=(r,e,t)=>e in r?te(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,o=(r,e)=>{for(var t in e||(e={}))ze.call(e,t)&&Ye(r,t,e[t]);if(He)for(var t of He(e))nr.call(e,t)&&Ye(r,t,e[t]);return r},ce=(r,e)=>Zt(r,tr(e)),$e=r=>te(r,"__esModule",{value:!0});var L=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),sr=(r,e)=>{$e(r);for(var t in e)te(r,t,{get:e[t],enumerable:!0})},ar=(r,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of rr(e))!ze.call(r,i)&&i!=="default"&&te(r,i,{get:()=>e[i],enumerable:!(t=er(e,i))||t.enumerable});return r},T=r=>ar($e(te(r!=null?Xt(ir(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var Xe=L((Dr,Je)=>{"use strict";function ye(r){this.message=r}ye.prototype=new Error,ye.prototype.name="InvalidCharacterError";var We=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(r){var e=String(r).replace(/=+$/,"");if(e.length%4==1)throw new ye("'atob' failed: The string to be decoded is not correctly encoded.");for(var t,i,n=0,s=0,a="";i=e.charAt(s++);~i&&(t=n%4?64*t+i:i,n++%4)?a+=String.fromCharCode(255&t>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return a};function or(r){var e=r.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(We(t).replace(/(.)/g,function(i,n){var s=n.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch(t){return We(e)}}function re(r){this.message=r}function Qe(r,e){if(typeof r!="string")throw new re("Invalid token specified");var t=(e=e||{}).header===!0?0:1;try{return JSON.parse(or(r.split(".")[t]))}catch(i){throw new re("Invalid token specified: "+i.message)}}re.prototype=new Error,re.prototype.name="InvalidTokenError";var Ee=Qe;Ee.default=Qe,Ee.InvalidTokenError=re,Je.exports=Ee});var et=L((Fr,Ze)=>{"use strict";var ur=["ETIMEDOUT","ECONNRESET","EADDRINUSE","ESOCKETTIMEDOUT","ECONNREFUSED","EPIPE","EHOSTUNREACH","EAI_AGAIN"],lr=["ENOTFOUND","ENETUNREACH","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_CRL","UNABLE_TO_DECRYPT_CERT_SIGNATURE","UNABLE_TO_DECRYPT_CRL_SIGNATURE","UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY","CERT_SIGNATURE_FAILURE","CRL_SIGNATURE_FAILURE","CERT_NOT_YET_VALID","CERT_HAS_EXPIRED","CRL_NOT_YET_VALID","CRL_HAS_EXPIRED","ERROR_IN_CERT_NOT_BEFORE_FIELD","ERROR_IN_CERT_NOT_AFTER_FIELD","ERROR_IN_CRL_LAST_UPDATE_FIELD","ERROR_IN_CRL_NEXT_UPDATE_FIELD","OUT_OF_MEM","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_CHAIN_TOO_LONG","CERT_REVOKED","INVALID_CA","PATH_LENGTH_EXCEEDED","INVALID_PURPOSE","CERT_UNTRUSTED","CERT_REJECTED"];Ze.exports=function(r){return!r||!r.code||ur.indexOf(r.code)!==-1?!0:lr.indexOf(r.code)===-1}});var st=L(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});var cr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r};F.isNetworkError=Ae;F.isRetryableError=fe;F.isSafeRequestError=rt;F.isIdempotentRequestError=be;F.isNetworkOrIdempotentRequestError=Re;F.exponentialDelay=it;F.default=j;var fr=et(),gr=hr(fr);function hr(r){return r&&r.__esModule?r:{default:r}}var Te="axios-retry";function Ae(r){return!r.response&&Boolean(r.code)&&r.code!=="ECONNABORTED"&&(0,gr.default)(r)}var tt=["get","head","options"],pr=tt.concat(["put","delete"]);function fe(r){return r.code!=="ECONNABORTED"&&(!r.response||r.response.status>=500&&r.response.status<=599)}function rt(r){return r.config?fe(r)&&tt.indexOf(r.config.method)!==-1:!1}function be(r){return r.config?fe(r)&&pr.indexOf(r.config.method)!==-1:!1}function Re(r){return Ae(r)||be(r)}function mr(){return 0}function it(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=Math.pow(2,r)*100,t=e*.2*Math.random();return e+t}function nt(r){var e=r[Te]||{};return e.retryCount=e.retryCount||0,r[Te]=e,e}function dr(r,e){return Object.assign({},e,r[Te])}function vr(r,e){r.defaults.agent===e.agent&&delete e.agent,r.defaults.httpAgent===e.httpAgent&&delete e.httpAgent,r.defaults.httpsAgent===e.httpsAgent&&delete e.httpsAgent}async function yr(r,e,t,i){var n=t.retryCount<r&&e(i);if((typeof n=="undefined"?"undefined":cr(n))==="object")try{return await n,!0}catch(s){return!1}return n}function j(r,e){r.interceptors.request.use(function(t){var i=nt(t);return i.lastRequestTime=Date.now(),t}),r.interceptors.response.use(null,async function(t){var i=t.config;if(!i)return Promise.reject(t);var n=dr(i,e),s=n.retries,a=s===void 0?3:s,u=n.retryCondition,c=u===void 0?Re:u,f=n.retryDelay,l=f===void 0?mr:f,p=n.shouldResetTimeout,S=p===void 0?!1:p,k=nt(i);if(await yr(a,c,k,t)){k.retryCount+=1;var D=l(k.retryCount,t);if(vr(r,i),!S&&i.timeout&&k.lastRequestTime){var y=Date.now()-k.lastRequestTime;i.timeout=Math.max(i.timeout-y-D,1)}return i.transformRequest=[function(g){return g}],new Promise(function(g){return setTimeout(function(){return g(r(i))},D)})}return Promise.reject(t)})}j.isNetworkError=Ae;j.isSafeRequestError=rt;j.isIdempotentRequestError=be;j.isNetworkOrIdempotentRequestError=Re;j.exponentialDelay=it;j.isRetryableError=fe});var ot=L((Ur,at)=>{at.exports=st().default});var ct=L((ai,lt)=>{"use strict";lt.exports=function(r){r.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}});var gt=L((oi,ft)=>{"use strict";ft.exports=h;h.Node=H;h.create=h;function h(r){var e=this;if(e instanceof h||(e=new h),e.tail=null,e.head=null,e.length=0,r&&typeof r.forEach=="function")r.forEach(function(n){e.push(n)});else if(arguments.length>0)for(var t=0,i=arguments.length;t<i;t++)e.push(arguments[t]);return e}h.prototype.removeNode=function(r){if(r.list!==this)throw new Error("removing node which does not belong to this list");var e=r.next,t=r.prev;return e&&(e.prev=t),t&&(t.next=e),r===this.head&&(this.head=e),r===this.tail&&(this.tail=t),r.list.length--,r.next=null,r.prev=null,r.list=null,e};h.prototype.unshiftNode=function(r){if(r!==this.head){r.list&&r.list.removeNode(r);var e=this.head;r.list=this,r.next=e,e&&(e.prev=r),this.head=r,this.tail||(this.tail=r),this.length++}};h.prototype.pushNode=function(r){if(r!==this.tail){r.list&&r.list.removeNode(r);var e=this.tail;r.list=this,r.prev=e,e&&(e.next=r),this.tail=r,this.head||(this.head=r),this.length++}};h.prototype.push=function(){for(var r=0,e=arguments.length;r<e;r++)Rr(this,arguments[r]);return this.length};h.prototype.unshift=function(){for(var r=0,e=arguments.length;r<e;r++)xr(this,arguments[r]);return this.length};h.prototype.pop=function(){if(!!this.tail){var r=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,r}};h.prototype.shift=function(){if(!!this.head){var r=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,r}};h.prototype.forEach=function(r,e){e=e||this;for(var t=this.head,i=0;t!==null;i++)r.call(e,t.value,i,this),t=t.next};h.prototype.forEachReverse=function(r,e){e=e||this;for(var t=this.tail,i=this.length-1;t!==null;i--)r.call(e,t.value,i,this),t=t.prev};h.prototype.get=function(r){for(var e=0,t=this.head;t!==null&&e<r;e++)t=t.next;if(e===r&&t!==null)return t.value};h.prototype.getReverse=function(r){for(var e=0,t=this.tail;t!==null&&e<r;e++)t=t.prev;if(e===r&&t!==null)return t.value};h.prototype.map=function(r,e){e=e||this;for(var t=new h,i=this.head;i!==null;)t.push(r.call(e,i.value,this)),i=i.next;return t};h.prototype.mapReverse=function(r,e){e=e||this;for(var t=new h,i=this.tail;i!==null;)t.push(r.call(e,i.value,this)),i=i.prev;return t};h.prototype.reduce=function(r,e){var t,i=this.head;if(arguments.length>1)t=e;else if(this.head)i=this.head.next,t=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=0;i!==null;n++)t=r(t,i.value,n),i=i.next;return t};h.prototype.reduceReverse=function(r,e){var t,i=this.tail;if(arguments.length>1)t=e;else if(this.tail)i=this.tail.prev,t=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=this.length-1;i!==null;n--)t=r(t,i.value,n),i=i.prev;return t};h.prototype.toArray=function(){for(var r=new Array(this.length),e=0,t=this.head;t!==null;e++)r[e]=t.value,t=t.next;return r};h.prototype.toArrayReverse=function(){for(var r=new Array(this.length),e=0,t=this.tail;t!==null;e++)r[e]=t.value,t=t.prev;return r};h.prototype.slice=function(r,e){e=e||this.length,e<0&&(e+=this.length),r=r||0,r<0&&(r+=this.length);var t=new h;if(e<r||e<0)return t;r<0&&(r=0),e>this.length&&(e=this.length);for(var i=0,n=this.head;n!==null&&i<r;i++)n=n.next;for(;n!==null&&i<e;i++,n=n.next)t.push(n.value);return t};h.prototype.sliceReverse=function(r,e){e=e||this.length,e<0&&(e+=this.length),r=r||0,r<0&&(r+=this.length);var t=new h;if(e<r||e<0)return t;r<0&&(r=0),e>this.length&&(e=this.length);for(var i=this.length,n=this.tail;n!==null&&i>e;i--)n=n.prev;for(;n!==null&&i>r;i--,n=n.prev)t.push(n.value);return t};h.prototype.splice=function(r,e,...t){r>this.length&&(r=this.length-1),r<0&&(r=this.length+r);for(var i=0,n=this.head;n!==null&&i<r;i++)n=n.next;for(var s=[],i=0;n&&i<e;i++)s.push(n.value),n=this.removeNode(n);n===null&&(n=this.tail),n!==this.head&&n!==this.tail&&(n=n.prev);for(var i=0;i<t.length;i++)n=br(this,n,t[i]);return s};h.prototype.reverse=function(){for(var r=this.head,e=this.tail,t=r;t!==null;t=t.prev){var i=t.prev;t.prev=t.next,t.next=i}return this.head=e,this.tail=r,this};function br(r,e,t){var i=e===r.head?new H(t,null,e,r):new H(t,e,e.next,r);return i.next===null&&(r.tail=i),i.prev===null&&(r.head=i),r.length++,i}function Rr(r,e){r.tail=new H(e,r.tail,null,r),r.head||(r.head=r.tail),r.length++}function xr(r,e){r.head=new H(e,null,r.head,r),r.tail||(r.tail=r.head),r.length++}function H(r,e,t,i){if(!(this instanceof H))return new H(r,e,t,i);this.list=i,this.value=r,e?(e.next=this,this.prev=e):this.prev=null,t?(t.prev=this,this.next=t):this.next=null}try{ct()(h)}catch(r){}});var _e=L((ui,yt)=>{"use strict";var Sr=gt(),z=Symbol("max"),U=Symbol("length"),J=Symbol("lengthCalculator"),ne=Symbol("allowStale"),Y=Symbol("maxAge"),q=Symbol("dispose"),ht=Symbol("noDisposeOnSet"),d=Symbol("lruList"),x=Symbol("cache"),pt=Symbol("updateAgeOnGet"),Oe=()=>1,mt=class{constructor(e){if(typeof e=="number"&&(e={max:e}),e||(e={}),e.max&&(typeof e.max!="number"||e.max<0))throw new TypeError("max must be a non-negative number");let t=this[z]=e.max||1/0,i=e.length||Oe;if(this[J]=typeof i!="function"?Oe:i,this[ne]=e.stale||!1,e.maxAge&&typeof e.maxAge!="number")throw new TypeError("maxAge must be a number");this[Y]=e.maxAge||0,this[q]=e.dispose,this[ht]=e.noDisposeOnSet||!1,this[pt]=e.updateAgeOnGet||!1,this.reset()}set max(e){if(typeof e!="number"||e<0)throw new TypeError("max must be a non-negative number");this[z]=e||1/0,se(this)}get max(){return this[z]}set allowStale(e){this[ne]=!!e}get allowStale(){return this[ne]}set maxAge(e){if(typeof e!="number")throw new TypeError("maxAge must be a non-negative number");this[Y]=e,se(this)}get maxAge(){return this[Y]}set lengthCalculator(e){typeof e!="function"&&(e=Oe),e!==this[J]&&(this[J]=e,this[U]=0,this[d].forEach(t=>{t.length=this[J](t.value,t.key),this[U]+=t.length})),se(this)}get lengthCalculator(){return this[J]}get length(){return this[U]}get itemCount(){return this[d].length}rforEach(e,t){t=t||this;for(let i=this[d].tail;i!==null;){let n=i.prev;vt(this,e,i,t),i=n}}forEach(e,t){t=t||this;for(let i=this[d].head;i!==null;){let n=i.next;vt(this,e,i,t),i=n}}keys(){return this[d].toArray().map(e=>e.key)}values(){return this[d].toArray().map(e=>e.value)}reset(){this[q]&&this[d]&&this[d].length&&this[d].forEach(e=>this[q](e.key,e.value)),this[x]=new Map,this[d]=new Sr,this[U]=0}dump(){return this[d].map(e=>de(this,e)?!1:{k:e.key,v:e.value,e:e.now+(e.maxAge||0)}).toArray().filter(e=>e)}dumpLru(){return this[d]}set(e,t,i){if(i=i||this[Y],i&&typeof i!="number")throw new TypeError("maxAge must be a number");let n=i?Date.now():0,s=this[J](t,e);if(this[x].has(e)){if(s>this[z])return X(this,this[x].get(e)),!1;let c=this[x].get(e).value;return this[q]&&(this[ht]||this[q](e,c.value)),c.now=n,c.maxAge=i,c.value=t,this[U]+=s-c.length,c.length=s,this.get(e),se(this),!0}let a=new dt(e,t,s,n,i);return a.length>this[z]?(this[q]&&this[q](e,t),!1):(this[U]+=a.length,this[d].unshift(a),this[x].set(e,this[d].head),se(this),!0)}has(e){if(!this[x].has(e))return!1;let t=this[x].get(e).value;return!de(this,t)}get(e){return Ce(this,e,!0)}peek(e){return Ce(this,e,!1)}pop(){let e=this[d].tail;return e?(X(this,e),e.value):null}del(e){X(this,this[x].get(e))}load(e){this.reset();let t=Date.now();for(let i=e.length-1;i>=0;i--){let n=e[i],s=n.e||0;if(s===0)this.set(n.k,n.v);else{let a=s-t;a>0&&this.set(n.k,n.v,a)}}}prune(){this[x].forEach((e,t)=>Ce(this,t,!1))}},Ce=(r,e,t)=>{let i=r[x].get(e);if(i){let n=i.value;if(de(r,n)){if(X(r,i),!r[ne])return}else t&&(r[pt]&&(i.value.now=Date.now()),r[d].unshiftNode(i));return n.value}},de=(r,e)=>{if(!e||!e.maxAge&&!r[Y])return!1;let t=Date.now()-e.now;return e.maxAge?t>e.maxAge:r[Y]&&t>r[Y]},se=r=>{if(r[U]>r[z])for(let e=r[d].tail;r[U]>r[z]&&e!==null;){let t=e.prev;X(r,e),e=t}},X=(r,e)=>{if(e){let t=e.value;r[q]&&r[q](t.key,t.value),r[U]-=t.length,r[x].delete(t.key),r[d].removeNode(e)}},dt=class{constructor(e,t,i,n,s){this.key=e,this.value=t,this.length=i,this.now=n,this.maxAge=s||0}},vt=(r,e,t,i)=>{let n=t.value;de(r,n)&&(X(r,t),r[ne]||(n=void 0)),n&&e.call(i,n.value,n.key,r)};yt.exports=mt});var jt=L((Si,Le)=>{(function(){var r=this;let e=a=>new TextEncoder().encode(a);function t(a,u){typeof a=="string"&&(a=e(a));for(var c=a.length,f=u^c,l=0,p;c>=4;)p=a[l]&255|(a[++l]&255)<<8|(a[++l]&255)<<16|(a[++l]&255)<<24,p=(p&65535)*1540483477+(((p>>>16)*1540483477&65535)<<16),p^=p>>>24,p=(p&65535)*1540483477+(((p>>>16)*1540483477&65535)<<16),f=(f&65535)*1540483477+(((f>>>16)*1540483477&65535)<<16)^p,c-=4,++l;switch(c){case 3:f^=(a[l+2]&255)<<16;case 2:f^=(a[l+1]&255)<<8;case 1:f^=a[l]&255,f=(f&65535)*1540483477+(((f>>>16)*1540483477&65535)<<16)}return f^=f>>>13,f=(f&65535)*1540483477+(((f>>>16)*1540483477&65535)<<16),f^=f>>>15,f>>>0}function i(a,u){typeof a=="string"&&(a=e(a));var c,f,l,p,S,k,D,y,g,v;for(c=a.length&3,f=a.length-c,l=u,S=3432918353,D=461845907,v=0;v<f;)g=a[v]&255|(a[++v]&255)<<8|(a[++v]&255)<<16|(a[++v]&255)<<24,++v,g=(g&65535)*S+(((g>>>16)*S&65535)<<16)&4294967295,g=g<<15|g>>>17,g=(g&65535)*D+(((g>>>16)*D&65535)<<16)&4294967295,l^=g,l=l<<13|l>>>19,p=(l&65535)*5+(((l>>>16)*5&65535)<<16)&4294967295,l=(p&65535)+27492+(((p>>>16)+58964&65535)<<16);switch(g=0,c){case 3:g^=(a[v+2]&255)<<16;case 2:g^=(a[v+1]&255)<<8;case 1:g^=a[v]&255,g=(g&65535)*S+(((g>>>16)*S&65535)<<16)&4294967295,g=g<<15|g>>>17,g=(g&65535)*D+(((g>>>16)*D&65535)<<16)&4294967295,l^=g}return l^=a.length,l^=l>>>16,l=(l&65535)*2246822507+(((l>>>16)*2246822507&65535)<<16)&4294967295,l^=l>>>13,l=(l&65535)*3266489909+(((l>>>16)*3266489909&65535)<<16)&4294967295,l^=l>>>16,l>>>0}var n=i;if(n.v2=t,n.v3=i,typeof Le!="undefined")Le.exports=n;else{var s=r.murmur;n.noConflict=function(){return r.murmur=s,n},r.murmur=n}})()});sr(exports,{Client:()=>ue,ClientEvent:()=>V,FileStore:()=>ae,LRU:()=>$t.default,default:()=>wr});var zt=T(require("events")),Yt=T(Xe()),Ke=T(require("axios")),ke=T(ot());var A;(function(s){s.READY="stream_ready",s.CONNECTED="stream_connected",s.DISCONNECTED="stream_disconnected",s.CHANGED="stream_changed",s.ERROR="stream_error"})(A||(A={}));var _=T(require("axios"));var ut=T(require("axios")),R="http://localhost/api/1.0".replace(/\/+$/,"");var ge=class{constructor(e,t=R,i=ut.default){this.basePath=t;this.axios=i;e&&(this.configuration=e,this.basePath=e.basePath||this.basePath)}},xe=class extends Error{constructor(e,t){super(t);this.field=e;this.name="RequiredError"}};var P="https://example.com",E=function(r,e,t){if(t==null)throw new xe(e,`Required parameter ${e} was null or undefined when calling ${r}.`)};var N=async function(r,e){if(e&&e.accessToken){let t=typeof e.accessToken=="function"?await e.accessToken():await e.accessToken;r.Authorization="Bearer "+t}};var I=function(r,...e){let t=new URLSearchParams(r.search);for(let i of e)for(let n in i)if(Array.isArray(i[n])){t.delete(n);for(let s of i[n])t.append(n,s)}else t.set(n,i[n]);r.search=t.toString()},Se=function(r,e,t){let i=typeof r!="string";return(i&&t&&t.isJsonMime?t.isJsonMime(e.headers["Content-Type"]):i)?JSON.stringify(r!==void 0?r:{}):r||""},O=function(r){return r.pathname+r.search+r.hash},C=function(r,e,t,i){return(n=e,s=t)=>{let a=ce(o({},r.options),{url:((i==null?void 0:i.basePath)||s)+r.url});return n.request(a)}};var G;(function(n){n.Boolean="boolean",n.Int="int",n.String="string",n.Json="json"})(G||(G={}));var he;(function(t){t.On="on",t.Off="off"})(he||(he={}));var pe;(function(e){e.Ffmetrics="FFMETRICS"})(pe||(pe={}));var Er=function(r){return{authenticate:async(e,t={})=>{let i="/client/auth",n=new URL(i,P),s;r&&(s=r.baseOptions);let a=o(o({method:"POST"},s),t),u={},c={};u["Content-Type"]="application/json",I(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),a.data=Se(e,a,r),{url:O(n),options:a}},getAllSegments:async(e,t={})=>{E("getAllSegments","environmentUUID",e);let i="/client/env/{environmentUUID}/target-segments".replace("{environmentUUID}",encodeURIComponent(String(e))),n=new URL(i,P),s;r&&(s=r.baseOptions);let a=o(o({method:"GET"},s),t),u={},c={};await N(u,r),I(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),{url:O(n),options:a}},getEvaluationByIdentifier:async(e,t,i,n={})=>{E("getEvaluationByIdentifier","environmentUUID",e),E("getEvaluationByIdentifier","feature",t),E("getEvaluationByIdentifier","target",i);let s="/client/env/{environmentUUID}/target/{target}/evaluations/{feature}".replace("{environmentUUID}",encodeURIComponent(String(e))).replace("{feature}",encodeURIComponent(String(t))).replace("{target}",encodeURIComponent(String(i))),a=new URL(s,P),u;r&&(u=r.baseOptions);let c=o(o({method:"GET"},u),n),f={},l={};await N(f,r),I(a,l,n.query);let p=u&&u.headers?u.headers:{};return c.headers=o(o(o({},f),p),n.headers),{url:O(a),options:c}},getEvaluations:async(e,t,i={})=>{E("getEvaluations","environmentUUID",e),E("getEvaluations","target",t);let n="/client/env/{environmentUUID}/target/{target}/evaluations".replace("{environmentUUID}",encodeURIComponent(String(e))).replace("{target}",encodeURIComponent(String(t))),s=new URL(n,P),a;r&&(a=r.baseOptions);let u=o(o({method:"GET"},a),i),c={},f={};await N(c,r),I(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),{url:O(s),options:u}},getFeatureConfig:async(e,t={})=>{E("getFeatureConfig","environmentUUID",e);let i="/client/env/{environmentUUID}/feature-configs".replace("{environmentUUID}",encodeURIComponent(String(e))),n=new URL(i,P),s;r&&(s=r.baseOptions);let a=o(o({method:"GET"},s),t),u={},c={};await N(u,r),I(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),{url:O(n),options:a}},getFeatureConfigByIdentifier:async(e,t,i={})=>{E("getFeatureConfigByIdentifier","identifier",e),E("getFeatureConfigByIdentifier","environmentUUID",t);let n="/client/env/{environmentUUID}/feature-configs/{identifier}".replace("{identifier}",encodeURIComponent(String(e))).replace("{environmentUUID}",encodeURIComponent(String(t))),s=new URL(n,P),a;r&&(a=r.baseOptions);let u=o(o({method:"GET"},a),i),c={},f={};await N(c,r),I(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),{url:O(s),options:u}},getSegmentByIdentifier:async(e,t,i={})=>{E("getSegmentByIdentifier","identifier",e),E("getSegmentByIdentifier","environmentUUID",t);let n="/client/env/{environmentUUID}/target-segments/{identifier}".replace("{identifier}",encodeURIComponent(String(e))).replace("{environmentUUID}",encodeURIComponent(String(t))),s=new URL(n,P),a;r&&(a=r.baseOptions);let u=o(o({method:"GET"},a),i),c={},f={};await N(c,r),I(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),{url:O(s),options:u}},stream:async(e,t={})=>{E("stream","aPIKey",e);let i="/stream",n=new URL(i,P),s;r&&(s=r.baseOptions);let a=o(o({method:"GET"},s),t),u={},c={};await N(u,r),e!=null&&(u["API-Key"]=String(e)),I(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),{url:O(n),options:a}}}},B=function(r){let e=Er(r);return{async authenticate(t,i){let n=await e.authenticate(t,i);return C(n,_.default,R,r)},async getAllSegments(t,i){let n=await e.getAllSegments(t,i);return C(n,_.default,R,r)},async getEvaluationByIdentifier(t,i,n,s){let a=await e.getEvaluationByIdentifier(t,i,n,s);return C(a,_.default,R,r)},async getEvaluations(t,i,n){let s=await e.getEvaluations(t,i,n);return C(s,_.default,R,r)},async getFeatureConfig(t,i){let n=await e.getFeatureConfig(t,i);return C(n,_.default,R,r)},async getFeatureConfigByIdentifier(t,i,n){let s=await e.getFeatureConfigByIdentifier(t,i,n);return C(s,_.default,R,r)},async getSegmentByIdentifier(t,i,n){let s=await e.getSegmentByIdentifier(t,i,n);return C(s,_.default,R,r)},async stream(t,i){let n=await e.stream(t,i);return C(n,_.default,R,r)}}};var Pe=class extends ge{authenticate(e,t){return B(this.configuration).authenticate(e,t).then(i=>i(this.axios,this.basePath))}getAllSegments(e,t){return B(this.configuration).getAllSegments(e,t).then(i=>i(this.axios,this.basePath))}getEvaluationByIdentifier(e,t,i,n){return B(this.configuration).getEvaluationByIdentifier(e,t,i,n).then(s=>s(this.axios,this.basePath))}getEvaluations(e,t,i){return B(this.configuration).getEvaluations(e,t,i).then(n=>n(this.axios,this.basePath))}getFeatureConfig(e,t){return B(this.configuration).getFeatureConfig(e,t).then(i=>i(this.axios,this.basePath))}getFeatureConfigByIdentifier(e,t,i){return B(this.configuration).getFeatureConfigByIdentifier(e,t,i).then(n=>n(this.axios,this.basePath))}getSegmentByIdentifier(e,t,i){return B(this.configuration).getSegmentByIdentifier(e,t,i).then(n=>n(this.axios,this.basePath))}stream(e,t){return B(this.configuration).stream(e,t).then(i=>i(this.axios,this.basePath))}},Tr=function(r){return{postMetrics:async(e,t,i={})=>{E("postMetrics","environment",e);let n="/metrics/{environment}".replace("{environment}",encodeURIComponent(String(e))),s=new URL(n,P),a;r&&(a=r.baseOptions);let u=o(o({method:"POST"},a),i),c={},f={};await N(c,r),c["Content-Type"]="application/json",I(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),u.data=Se(t,u,r),{url:O(s),options:u}}}},Ar=function(r){let e=Tr(r);return{async postMetrics(t,i,n){let s=await e.postMetrics(t,i,n);return C(s,_.default,R,r)}}};var Ie=class extends ge{postMetrics(e,t,i){return Ar(this.configuration).postMetrics(e,t,i).then(n=>n(this.axios,this.basePath))}};var ie=class{constructor(e={}){this.apiKey=e.apiKey,this.username=e.username,this.password=e.password,this.accessToken=e.accessToken,this.basePath=e.basePath,this.baseOptions=e.baseOptions,this.formDataCtor=e.formDataCtor}isJsonMime(e){let t=new RegExp("^(application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(;.*)?$","i");return e!==null&&(t.test(e)||e.toLowerCase()==="application/json-patch+json")}};var me="1.1.0";var At=T(_e());var we=class{trace(e,...t){console.trace(e,...t)}debug(e,...t){console.debug(e,...t)}info(e,...t){console.info(e,...t)}warn(e,...t){console.warn(e,...t)}error(e,...t){console.error(e,...t)}};var Et=T(require("keyv")),Tt=T(require("keyv-file")),ae=class{constructor(e={}){this.keyv=new Et.default({store:new Tt.KeyvFile(e)})}set(e,t){return this.keyv.set(e,t)}get(e){return this.keyv.get(e)}del(e){return this.keyv.delete(e)}};var bt=100;var Rt="featureIdentifier",xt="featureName",St="variationIdentifier";var Pt="target",It="SDK_VERSION",Ot="SDK_TYPE",Ct="server",_t="SDK_LANGUAGE",wt="javascript",Vt="global",Dt="segmentMatch",Ft="in",Nt="equal",Ut="gt",qt="starts_with",Lt="ends_with",Bt="contains",Mt="equal_sensitive",Pr="https://config.ff.harness.io/api/1.0",Ir="https://events.ff.harness.io/api/1.0",Or=1e3,Kt=60*Or,Cr=1*Kt,_r=1*Kt,b={baseUrl:Pr,eventsUrl:Ir,pollInterval:Cr,eventsSyncInterval:_r,enableStream:!0,enableAnalytics:!0,cache:new At.default({max:100}),store:new ae,logger:new we};var w=b.logger,$;(function(t){t.READY="poller_ready",t.ERROR="poller_error"})($||($={}));var Ve=class{constructor(e,t,i,n,s,a){this.stopped=!0;this.initialized=!1;this.api=i,this.options=n,this.environment=e,this.cluster=t,this.repository=a,this.eventBus=s}poll(){if(this.stopped)return;let e=new Date().getTime(),t=()=>{let i=new Date().getTime()-e,n=Math.max(this.options.pollInterval-i,0);setTimeout(()=>this.poll(),n)};Promise.all([this.retrieveFlags(),this.retrieveSegments()]).then(()=>{this.initialized||(this.initialized=!0,this.eventBus.emit($.READY))}).catch(i=>{this.eventBus.emit($.ERROR,{error:i})}).finally(t)}async retrieveFlags(){try{w.debug("Fetching flags started");let e=await this.api.getFeatureConfig(this.environment,{params:{cluster:this.cluster}});w.debug("Fetching flags finished"),e.data.forEach(t=>this.repository.setFlag(t.feature,t))}catch(e){throw w.error("Error loading flags",e),e}}async retrieveSegments(){try{w.debug("Fetching segments started");let e=await this.api.getAllSegments(this.environment,{params:{cluster:this.cluster}});w.debug("Fetching segments finished"),e.data.forEach(t=>this.repository.setSegment(t.identifier,t))}catch(e){throw w.error("Error loading segments",e),e}}start(){if(!this.stopped){w.info("PollingProcessor already started");return}w.info("Starting PollingProcessor with request interval: ",this.options.pollInterval),this.stopped=!1,this.poll()}stop(){w.info("Stopping PollingProcessor"),this.stopped=!0}close(){w.info("Closing PollingProcessor"),this.stop()}};var kt=T(require("eventsource"));var M=b.logger,De=class{constructor(e,t,i,n,s,a,u,c){this.api=e,this.apiKey=t,this.environment=i,this.jwtToken=n,this.options=s,this.cluster=a,this.eventBus=u,this.repository=c}start(){M.info("Starting StreamProcessor");let e=new kt.default(`${this.options.baseUrl}/stream?cluster=${this.cluster}`,{headers:{Authorization:`Bearer ${this.jwtToken}`,"API-Key":this.apiKey}});e.onopen=t=>{M.debug("Stream connected",t),this.eventBus.emit(A.CONNECTED)},e.onerror=t=>{M.debug("Stream has issue",t),this.eventBus.emit(A.ERROR,t)},e.addEventListener("*",t=>{let i=JSON.parse(t.data);M.debug("Received event from stream: ",i),i.domain==="flag"?this.msgProcessor(i,this.api.getFeatureConfigByIdentifier.bind(this.api),this.repository.setFlag.bind(this.repository),this.repository.deleteFlag.bind(this.repository)):i.domain==="target-segment"&&this.msgProcessor(i,this.api.getSegmentByIdentifier.bind(this.api),this.repository.setSegment.bind(this.repository),this.repository.deleteSegment.bind(this.repository))}),this.eventSource=e,this.eventBus.emit(A.READY)}async msgProcessor(e,t,i,n){M.info("Processing message",e);try{let a=(await t(e.identifier,this.environment)).data;e.event==="create"||e.event==="patch"?i(e.identifier,a):e.event==="delete"&&n(e.identifier)}catch(s){throw M.error("Error while fetching data with identifier:",e.identifier,s),s}M.info("Processing message finished",e)}connected(){return this.eventSource.readyState==De.CONNECTED}stop(){M.info("Stopping StreamProcessor"),this.eventSource.close(),this.eventBus.emit(A.DISCONNECTED)}close(){this.stop()}},ve=De;ve.CONNECTED=1;var Fe=class{constructor(e){this.value=e}startsWith(e){return!1}endsWith(e){return!1}match(e){return!1}contains(e){return!1}equalSensitive(e){return!1}equal(e){return this.value===(e[0].toLowerCase()==="true")}greaterThan(e){return!1}greaterThanEqual(e){return!1}lessThan(e){return!1}lessThanEqual(e){return!1}inList(e){return this.value}};var Ne=class{startsWith(e){return!1}endsWith(e){return!1}match(e){return!1}contains(e){return!1}equalSensitive(e){return!1}equal(e){return!1}greaterThan(e){return!1}greaterThanEqual(e){return!1}lessThan(e){return!1}lessThanEqual(e){return!1}inList(e){return!1}};var Ue=class{constructor(e){this.value=e}startsWith(e){return!1}endsWith(e){return!1}match(e){return!1}contains(e){return!1}equalSensitive(e){return!1}equal(e){return this.value===parseFloat(e==null?void 0:e[0])}greaterThan(e){return this.value>parseFloat(e==null?void 0:e[0])}greaterThanEqual(e){return this.value>=parseFloat(e==null?void 0:e[0])}lessThan(e){return this.value<parseFloat(e==null?void 0:e[0])}lessThanEqual(e){return this.value<=parseFloat(e==null?void 0:e[0])}inList(e){return e.map(i=>parseFloat(i)).includes(this.value)}};var qe=class{constructor(e){this.value=e}startsWith(e){return this.value.startsWith(e==null?void 0:e[0])}endsWith(e){return this.value.endsWith(e==null?void 0:e[0])}match(e){return this.value.match(e==null?void 0:e[0])!==void 0}contains(e){return this.value.includes(e==null?void 0:e[0])}equalSensitive(e){return this.value===(e==null?void 0:e[0])}equal(e){var t;return this.value.toLocaleLowerCase()===((t=e==null?void 0:e[0])==null?void 0:t.toLocaleLowerCase())}greaterThan(e){return this.value>(e==null?void 0:e[0])}greaterThanEqual(e){return this.value>=(e==null?void 0:e[0])}lessThan(e){return this.value<(e==null?void 0:e[0])}lessThanEqual(e){return this.value<=(e==null?void 0:e[0])}inList(e){return e.includes(this.value)}};var Gt=T(jt()),W=b.logger,Be=class{constructor(e){this.query=e}getAttrValue(e,t){var i;return e[t]||((i=e.attributes)==null?void 0:i[t])}findVariation(e,t){return e.find(i=>i.identifier===t)}getNormalizedNumberWithNormalizer(e,t,i){let n=[t,e].join(":");return parseInt((0,Gt.default)(n).toString())%i+1}getNormalizedNumber(e,t){return this.getNormalizedNumberWithNormalizer(e,t,bt)}isEnabled(e,t,i){let n=this.getAttrValue(e,t);if(!n)return!1;let s=this.getNormalizedNumber(n,t);return i>0&&s<=i}evaluateDistribution(e,t){if(!e)return;let i="";for(let n of e.variations)if(i=n.variation,this.isEnabled(t,e.bucketBy,n.weight))return n.variation;return i}getOperator(e,t){let i=this.getAttrValue(e,t);switch(typeof i){case"boolean":return new Fe(i);case"string":return new qe(i);case"number":return new Ue(i);case"object":return new Ne}}convertApiTargetsToEvalTargets(e){return e.map(t=>({identifier:t.identifier,name:t.name,anonymous:t.anonymous,attributes:t.attributes}))}async isTargetIncludedOrExcludedInSegment(e,t){for(let i of e){let n=await this.query.getSegment(i);if(n){if(this.convertApiTargetsToEvalTargets(n.excluded).includes(t))return W.debug(`Target %s excluded from segment %s via exclude list | ||
`,t.name,n.name),!1;if(this.convertApiTargetsToEvalTargets(n.included).includes(t))return W.debug(`Target %s included in segment %s via include list | ||
`,t.name,n.name),!0;if(n.rules&&this.evaluateClauses(n.rules,t))return W.debug(`Target %s included in segment %s via rules | ||
`,t.name,n.name),!0}}return!1}async evaluateClause(e,t){if(!e.op)return!1;let i=this.getOperator(t,e.attribute);switch(e.op){case Ft:return i.inList(e.values);case Nt:return i.equal(e.values);case Mt:return i.equalSensitive(e.values);case Ut:return i.greaterThan(e.values);case qt:return i.startsWith(e.values);case Lt:return i.endsWith(e.values);case Bt:return i.contains(e.values);case Dt:return this.isTargetIncludedOrExcludedInSegment(e.values,t)}return!1}async evaluateClauses(e,t){for(let i of e)if(!await this.evaluateClause(i,t))return!1;return!0}evaluateRule(e,t){return this.evaluateClauses(e.clauses,t)}async evaluateRules(e,t){if(!t||!e)return;e.sort((n,s)=>n.priority>s.priority?1:-1);let i;for(let n of e)if(!!await this.evaluateRule(n,t))return n.serve.distribution&&(i=this.evaluateDistribution(n.serve.distribution,t)),n.serve.variation&&(i=n.serve.variation),i}evaluateVariationMap(e,t){var i;if(!(!t||!e))for(let n of e){if((i=n.targets)==null?void 0:i.find(u=>u.identifier===t.identifier))return n.variation;let a=n.targetSegments;if(a&&this.isTargetIncludedOrExcludedInSegment(a,t))return n.variation}}async evaluateFlag(e,t){let i=e.offVariation;return e.state===he.On&&(i=this.evaluateVariationMap(e.variationToTargetMap,t)||await this.evaluateRules(e.rules,t)||this.evaluateDistribution(e.defaultServe.distribution,t)||e.defaultServe.variation),this.findVariation(e.variations,i)}async checkPreRequisite(e,t){if(e.prerequisites){W.info("Checking pre requisites %s of parent feature %s",e.prerequisites,e.feature);for(let i of e.prerequisites){let n=await this.query.getFlag(i.feature);if(!n)return W.warn("Could not retrieve the pre requisite details of feature flag: %s",e.feature),!0;let s=await this.evaluateFlag(n,t);return W.info("Pre requisite flag %s has variation %s for target %s",n.feature,s,t),W.info("Pre requisite flag %s should have the variations %s",n.feature,i.variations),i.variations.includes(s.identifier)?await this.checkPreRequisite(n,t):!1}}return!0}async evaluate(e,t,i,n){let s=await this.query.getFlag(e);if(!s||s.kind!==i)return;if(s.prerequisites&&!await this.checkPreRequisite(s,t))return this.findVariation(s.variations,s.offVariation);let a=await this.evaluateFlag(s,t);if(a)return n&&n(s,t,a),a}async boolVariation(e,t,i=!1,n){let s=await this.evaluate(e,t,G.Boolean,n);return s?s.value.toLowerCase()==="true":i}async stringVariation(e,t,i="",n){let s=await this.evaluate(e,t,G.String,n);return s?s.value:i}async numberVariation(e,t,i=0,n){let s=await this.evaluate(e,t,G.Int,n);return s?parseFloat(s.value):i}async jsonVariation(e,t,i={},n){let s=await this.evaluate(e,t,G.Json,n);return s?JSON.parse(s.value):i}};var Me=class{constructor(e,t){if(!e)throw new Error("Cache is required argument and cannot be undefined");this.cache=e,this.store=t}async setFlag(e,t){let i=this.formatFlagKey(e);await this.isFlagOutdated(i,t)||(this.store?(await this.store.set(i,t),this.cache.del(i)):this.cache.set(i,t))}async setSegment(e,t){let i=this.formatSegmentKey(e);await this.isSegmentOutdated(i,t)||(this.store?(await this.store.set(i,t),this.cache.del(i)):this.cache.set(i,t))}async deleteFlag(e){let t=this.formatFlagKey(e);this.store&&await this.store.del(t),this.cache.del(t)}async deleteSegment(e){let t=this.formatSegmentKey(e);this.store&&await this.store.del(t),this.cache.del(t)}async getFlag(e,t=!0){let i=this.formatFlagKey(e),n=this.cache.get(i);if(n)return n;if(this.store)return n=await this.store.get(i),n&&t&&this.cache.set(i,n),n}async getSegment(e,t=!0){let i=this.formatSegmentKey(e),n=this.cache.get(i);if(n)return n;if(this.store)return n=await this.store.get(i),n&&t&&this.cache.set(i,n),n}async isFlagOutdated(e,t){let i=await this.getFlag(e,!1);return(i==null?void 0:i.version)&&i.version>(t==null?void 0:t.version)}async isSegmentOutdated(e,t){let i=await this.getSegment(e,!1);return(i==null?void 0:i.version)&&i.version>(t==null?void 0:t.version)}formatFlagKey(e){return`flags/${e}`}formatSegmentKey(e){return`segments/${e}`}};var Q=b.logger,Z;(function(t){t.READY="metrics_ready",t.ERROR="metrics_error"})(Z||(Z={}));var Ht=(r,e="1",t,i,n)=>{let s=new Map,a,u=new ie(ce(o({},t),{basePath:i.eventsUrl})),c=new Ie(u),f=(y,g,v)=>{let m={target:y,featureConfig:g,variation:v,count:0},ee=l(m),le=s.get(ee);le?le.count++:(m.count=1,s.set(ee,m))},l=y=>{let g=y.featureConfig.feature,v=y.variation.identifier,m=y.variation.value;return`${g}/${v}/${m}/${Vt}`},p=()=>{if(!s){Q.debug("No metrics data!");return}let y=[],g=[],v=new Map(s);s.clear();for(let m of v.values()){if(m.target&&!m.target.anonymous){let je=[];m.target.attributes&&(je=Object.entries(m.target.attributes).map(([Qt,Jt])=>({key:Qt,value:Jt})));let Ge=m.target.identifier;m.target.name&&(Ge=m.target.name);let Wt={identifier:m.target.identifier,name:Ge,attributes:je};y.push(Wt)}let ee=[{key:Rt,value:m.featureConfig.feature},{key:xt,value:m.featureConfig.feature},{key:St,value:m.variation.identifier},{key:Ot,value:Ct},{key:_t,value:wt},{key:It,value:me},{key:Pt,value:m.target.identifier}],le={timestamp:Date.now(),count:m.count,metricsType:pe.Ffmetrics,attributes:ee};g.push(le)}return{targetData:y,metricsData:g}},S=()=>{let y=p();y&&(Q.debug("Start sending metrics data"),c.postMetrics(r,y,{params:{cluster:e}}).then(g=>{Q.debug("Metrics server returns: ",g.status),g.status>=400&&Q.error("Error while sending metrics data with status code: ",g.status)}).catch(g=>{Q.debug("Metrics server returns error: ",g)}))};return{start:()=>{Q.info("Starting MetricsProcessor with request interval: ",i.eventsSyncInterval),a=setInterval(S,i.eventsSyncInterval),n.emit(Z.READY)},close:()=>{Q.info("Closing MetricsProcessor"),clearInterval(a),S()},enqueue:f}};Ke.default.defaults.timeout=3e4;(0,ke.default)(Ke.default,{retries:3,retryDelay:ke.default.exponentialDelay});var oe=b.logger,K;(function(i){i[i.POLL=0]="POLL",i[i.STREAM=1]="STREAM",i[i.METRICS=2]="METRICS"})(K||(K={}));var V;(function(i){i.READY="ready",i.FAILED="failed",i.CHANGED="changed"})(V||(V={}));var ue=class{constructor(e,t={}){this.cluster="1";this.eventBus=new zt.EventEmitter;this.initialized=!1;this.failure=!1;this.pollerReady=!1;this.streamReady=!1;this.metricReady=!1;this.sdkKey=e,t.pollInterval<1e3&&(t.pollInterval=b.pollInterval,oe.warn("Polling interval cannot be lower than 1000 ms")),this.options=o(o({},b),t),this.configuration=new ie({basePath:this.options.baseUrl,baseOptions:{headers:{"User-Agent":`NodeJsSDK/${me}`}}}),this.repository=new Me(this.options.cache,this.options.store),this.evaluator=new Be(this.repository),this.api=new Pe(this.configuration),this.processEvents(),this.run()}processEvents(){this.eventBus.on($.READY,()=>{this.initialize(0)}),this.eventBus.on($.ERROR,()=>{this.failure=!0,this.eventBus.emit(V.FAILED)}),this.eventBus.on(A.READY,()=>{this.initialize(1)}),this.eventBus.on(A.ERROR,()=>{this.failure=!0,this.eventBus.emit(V.FAILED)}),this.eventBus.on(Z.READY,()=>{this.initialize(2)}),this.eventBus.on(Z.ERROR,()=>{this.failure=!0,this.eventBus.emit(V.FAILED)}),this.eventBus.on(A.CONNECTED,()=>{this.pollProcessor.stop()}),this.eventBus.on(A.DISCONNECTED,()=>{this.pollProcessor.start()})}async authenticate(){try{let e=await this.api.authenticate({apiKey:this.sdkKey});this.authToken=e.data.authToken,this.configuration.accessToken=this.authToken;let t=(0,Yt.default)(this.authToken);this.environment=t.environment,this.cluster=t.clusterIdentifier||"1"}catch(e){this.failure=!0,console.error("Error while authenticating, err: ",e)}}waitForInitialization(){return this.waitForInitialize?this.waitForInitialize:(this.initialized?this.waitForInitialize=Promise.resolve(this):this.failure?this.waitForInitialize=Promise.reject(this.failure):this.waitForInitialize=new Promise((e,t)=>{this.eventBus.once(V.READY,()=>{e(this)}),this.eventBus.once(V.FAILED,t)}),this.waitForInitialize)}initialize(e){switch(e){case 0:this.pollerReady=!0,oe.debug("PollingProcessor ready");break;case 1:this.streamReady=!0,oe.debug("StreamingProcessor ready");break;case 2:this.metricReady=!0,oe.debug("MetricsProcessor ready");break}this.options.enableStream&&!this.streamReady||this.options.enableAnalytics&&!this.metricReady||!this.pollerReady||(this.initialized=!0,this.eventBus.emit(V.READY))}async run(){await this.authenticate(),this.pollProcessor=new Ve(this.environment,this.cluster,this.api,this.options,this.eventBus,this.repository),this.pollProcessor.start(),this.options.enableStream&&(this.streamProcessor=new ve(this.api,this.sdkKey,this.environment,this.authToken,this.options,this.cluster,this.eventBus,this.repository),this.streamProcessor.start()),this.options.enableAnalytics&&(this.metricsProcessor=Ht(this.environment,this.cluster,this.configuration,this.options,this.eventBus),this.metricsProcessor.start()),oe.info("finished setting up processors")}boolVariation(e,t,i=!1){return this.evaluator.boolVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}stringVariation(e,t,i=""){return this.evaluator.stringVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}numberVariation(e,t,i=0){return this.evaluator.numberVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}jsonVariation(e,t,i={}){return this.evaluator.jsonVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}close(){this.pollProcessor.close(),this.streamProcessor&&this.streamProcessor.close(),this.metricsProcessor&&this.metricsProcessor.close()}};var $t=T(_e());var wr={instance:void 0,init:function(r,e){this.instance||(this.instance=new ue(r,e))},waitForInitialization:function(){return this.instance.waitForInitialization()},boolVariation:function(r,e,t=!1){return this.instance.boolVariation(r,e,t)},stringVariation:function(r,e,t=""){return this.instance.stringVariation(r,e,t)},numberVariation:function(r,e,t=0){return this.instance.numberVariation(r,e,t)},jsonVariation:function(r,e,t=""){return this.instance.jsonVariation(r,e,t)},close:function(){return this.instance.close()}};0&&(module.exports={Client,ClientEvent,FileStore,LRU}); | ||
var er=Object.create;var re=Object.defineProperty,tr=Object.defineProperties,rr=Object.getOwnPropertyDescriptor,ir=Object.getOwnPropertyDescriptors,nr=Object.getOwnPropertyNames,He=Object.getOwnPropertySymbols,sr=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty,ar=Object.prototype.propertyIsEnumerable;var Ye=(r,e,t)=>e in r?re(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,o=(r,e)=>{for(var t in e||(e={}))ze.call(e,t)&&Ye(r,t,e[t]);if(He)for(var t of He(e))ar.call(e,t)&&Ye(r,t,e[t]);return r},ce=(r,e)=>tr(r,ir(e)),$e=r=>re(r,"__esModule",{value:!0});var B=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),or=(r,e)=>{$e(r);for(var t in e)re(r,t,{get:e[t],enumerable:!0})},ur=(r,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nr(e))!ze.call(r,i)&&i!=="default"&&re(r,i,{get:()=>e[i],enumerable:!(t=rr(e,i))||t.enumerable});return r},T=r=>ur($e(re(r!=null?er(sr(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var Xe=B((Fr,Je)=>{"use strict";function ye(r){this.message=r}ye.prototype=new Error,ye.prototype.name="InvalidCharacterError";var We=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(r){var e=String(r).replace(/=+$/,"");if(e.length%4==1)throw new ye("'atob' failed: The string to be decoded is not correctly encoded.");for(var t,i,n=0,s=0,a="";i=e.charAt(s++);~i&&(t=n%4?64*t+i:i,n++%4)?a+=String.fromCharCode(255&t>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return a};function lr(r){var e=r.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(We(t).replace(/(.)/g,function(i,n){var s=n.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch(t){return We(e)}}function ie(r){this.message=r}function Qe(r,e){if(typeof r!="string")throw new ie("Invalid token specified");var t=(e=e||{}).header===!0?0:1;try{return JSON.parse(lr(r.split(".")[t]))}catch(i){throw new ie("Invalid token specified: "+i.message)}}ie.prototype=new Error,ie.prototype.name="InvalidTokenError";var Ee=Qe;Ee.default=Qe,Ee.InvalidTokenError=ie,Je.exports=Ee});var et=B((Ur,Ze)=>{"use strict";var cr=["ETIMEDOUT","ECONNRESET","EADDRINUSE","ESOCKETTIMEDOUT","ECONNREFUSED","EPIPE","EHOSTUNREACH","EAI_AGAIN"],fr=["ENOTFOUND","ENETUNREACH","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_CRL","UNABLE_TO_DECRYPT_CERT_SIGNATURE","UNABLE_TO_DECRYPT_CRL_SIGNATURE","UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY","CERT_SIGNATURE_FAILURE","CRL_SIGNATURE_FAILURE","CERT_NOT_YET_VALID","CERT_HAS_EXPIRED","CRL_NOT_YET_VALID","CRL_HAS_EXPIRED","ERROR_IN_CERT_NOT_BEFORE_FIELD","ERROR_IN_CERT_NOT_AFTER_FIELD","ERROR_IN_CRL_LAST_UPDATE_FIELD","ERROR_IN_CRL_NEXT_UPDATE_FIELD","OUT_OF_MEM","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_CHAIN_TOO_LONG","CERT_REVOKED","INVALID_CA","PATH_LENGTH_EXCEEDED","INVALID_PURPOSE","CERT_UNTRUSTED","CERT_REJECTED"];Ze.exports=function(r){return!r||!r.code||cr.indexOf(r.code)!==-1?!0:fr.indexOf(r.code)===-1}});var st=B(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});var gr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r};N.isNetworkError=Ae;N.isRetryableError=fe;N.isSafeRequestError=rt;N.isIdempotentRequestError=be;N.isNetworkOrIdempotentRequestError=Re;N.exponentialDelay=it;N.default=G;var hr=et(),pr=mr(hr);function mr(r){return r&&r.__esModule?r:{default:r}}var Te="axios-retry";function Ae(r){return!r.response&&Boolean(r.code)&&r.code!=="ECONNABORTED"&&(0,pr.default)(r)}var tt=["get","head","options"],dr=tt.concat(["put","delete"]);function fe(r){return r.code!=="ECONNABORTED"&&(!r.response||r.response.status>=500&&r.response.status<=599)}function rt(r){return r.config?fe(r)&&tt.indexOf(r.config.method)!==-1:!1}function be(r){return r.config?fe(r)&&dr.indexOf(r.config.method)!==-1:!1}function Re(r){return Ae(r)||be(r)}function vr(){return 0}function it(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=Math.pow(2,r)*100,t=e*.2*Math.random();return e+t}function nt(r){var e=r[Te]||{};return e.retryCount=e.retryCount||0,r[Te]=e,e}function yr(r,e){return Object.assign({},e,r[Te])}function Er(r,e){r.defaults.agent===e.agent&&delete e.agent,r.defaults.httpAgent===e.httpAgent&&delete e.httpAgent,r.defaults.httpsAgent===e.httpsAgent&&delete e.httpsAgent}async function Tr(r,e,t,i){var n=t.retryCount<r&&e(i);if((typeof n=="undefined"?"undefined":gr(n))==="object")try{return await n,!0}catch(s){return!1}return n}function G(r,e){r.interceptors.request.use(function(t){var i=nt(t);return i.lastRequestTime=Date.now(),t}),r.interceptors.response.use(null,async function(t){var i=t.config;if(!i)return Promise.reject(t);var n=yr(i,e),s=n.retries,a=s===void 0?3:s,u=n.retryCondition,c=u===void 0?Re:u,f=n.retryDelay,l=f===void 0?vr:f,p=n.shouldResetTimeout,S=p===void 0?!1:p,j=nt(i);if(await Tr(a,c,j,t)){j.retryCount+=1;var D=l(j.retryCount,t);if(Er(r,i),!S&&i.timeout&&j.lastRequestTime){var y=Date.now()-j.lastRequestTime;i.timeout=Math.max(i.timeout-y-D,1)}return i.transformRequest=[function(g){return g}],new Promise(function(g){return setTimeout(function(){return g(r(i))},D)})}return Promise.reject(t)})}G.isNetworkError=Ae;G.isSafeRequestError=rt;G.isIdempotentRequestError=be;G.isNetworkOrIdempotentRequestError=Re;G.exponentialDelay=it;G.isRetryableError=fe});var ot=B((Lr,at)=>{at.exports=st().default});var ct=B((ui,lt)=>{"use strict";lt.exports=function(r){r.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}});var gt=B((li,ft)=>{"use strict";ft.exports=h;h.Node=z;h.create=h;function h(r){var e=this;if(e instanceof h||(e=new h),e.tail=null,e.head=null,e.length=0,r&&typeof r.forEach=="function")r.forEach(function(n){e.push(n)});else if(arguments.length>0)for(var t=0,i=arguments.length;t<i;t++)e.push(arguments[t]);return e}h.prototype.removeNode=function(r){if(r.list!==this)throw new Error("removing node which does not belong to this list");var e=r.next,t=r.prev;return e&&(e.prev=t),t&&(t.next=e),r===this.head&&(this.head=e),r===this.tail&&(this.tail=t),r.list.length--,r.next=null,r.prev=null,r.list=null,e};h.prototype.unshiftNode=function(r){if(r!==this.head){r.list&&r.list.removeNode(r);var e=this.head;r.list=this,r.next=e,e&&(e.prev=r),this.head=r,this.tail||(this.tail=r),this.length++}};h.prototype.pushNode=function(r){if(r!==this.tail){r.list&&r.list.removeNode(r);var e=this.tail;r.list=this,r.prev=e,e&&(e.next=r),this.tail=r,this.head||(this.head=r),this.length++}};h.prototype.push=function(){for(var r=0,e=arguments.length;r<e;r++)Sr(this,arguments[r]);return this.length};h.prototype.unshift=function(){for(var r=0,e=arguments.length;r<e;r++)Pr(this,arguments[r]);return this.length};h.prototype.pop=function(){if(!!this.tail){var r=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,r}};h.prototype.shift=function(){if(!!this.head){var r=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,r}};h.prototype.forEach=function(r,e){e=e||this;for(var t=this.head,i=0;t!==null;i++)r.call(e,t.value,i,this),t=t.next};h.prototype.forEachReverse=function(r,e){e=e||this;for(var t=this.tail,i=this.length-1;t!==null;i--)r.call(e,t.value,i,this),t=t.prev};h.prototype.get=function(r){for(var e=0,t=this.head;t!==null&&e<r;e++)t=t.next;if(e===r&&t!==null)return t.value};h.prototype.getReverse=function(r){for(var e=0,t=this.tail;t!==null&&e<r;e++)t=t.prev;if(e===r&&t!==null)return t.value};h.prototype.map=function(r,e){e=e||this;for(var t=new h,i=this.head;i!==null;)t.push(r.call(e,i.value,this)),i=i.next;return t};h.prototype.mapReverse=function(r,e){e=e||this;for(var t=new h,i=this.tail;i!==null;)t.push(r.call(e,i.value,this)),i=i.prev;return t};h.prototype.reduce=function(r,e){var t,i=this.head;if(arguments.length>1)t=e;else if(this.head)i=this.head.next,t=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=0;i!==null;n++)t=r(t,i.value,n),i=i.next;return t};h.prototype.reduceReverse=function(r,e){var t,i=this.tail;if(arguments.length>1)t=e;else if(this.tail)i=this.tail.prev,t=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=this.length-1;i!==null;n--)t=r(t,i.value,n),i=i.prev;return t};h.prototype.toArray=function(){for(var r=new Array(this.length),e=0,t=this.head;t!==null;e++)r[e]=t.value,t=t.next;return r};h.prototype.toArrayReverse=function(){for(var r=new Array(this.length),e=0,t=this.tail;t!==null;e++)r[e]=t.value,t=t.prev;return r};h.prototype.slice=function(r,e){e=e||this.length,e<0&&(e+=this.length),r=r||0,r<0&&(r+=this.length);var t=new h;if(e<r||e<0)return t;r<0&&(r=0),e>this.length&&(e=this.length);for(var i=0,n=this.head;n!==null&&i<r;i++)n=n.next;for(;n!==null&&i<e;i++,n=n.next)t.push(n.value);return t};h.prototype.sliceReverse=function(r,e){e=e||this.length,e<0&&(e+=this.length),r=r||0,r<0&&(r+=this.length);var t=new h;if(e<r||e<0)return t;r<0&&(r=0),e>this.length&&(e=this.length);for(var i=this.length,n=this.tail;n!==null&&i>e;i--)n=n.prev;for(;n!==null&&i>r;i--,n=n.prev)t.push(n.value);return t};h.prototype.splice=function(r,e,...t){r>this.length&&(r=this.length-1),r<0&&(r=this.length+r);for(var i=0,n=this.head;n!==null&&i<r;i++)n=n.next;for(var s=[],i=0;n&&i<e;i++)s.push(n.value),n=this.removeNode(n);n===null&&(n=this.tail),n!==this.head&&n!==this.tail&&(n=n.prev);for(var i=0;i<t.length;i++)n=xr(this,n,t[i]);return s};h.prototype.reverse=function(){for(var r=this.head,e=this.tail,t=r;t!==null;t=t.prev){var i=t.prev;t.prev=t.next,t.next=i}return this.head=e,this.tail=r,this};function xr(r,e,t){var i=e===r.head?new z(t,null,e,r):new z(t,e,e.next,r);return i.next===null&&(r.tail=i),i.prev===null&&(r.head=i),r.length++,i}function Sr(r,e){r.tail=new z(e,r.tail,null,r),r.head||(r.head=r.tail),r.length++}function Pr(r,e){r.head=new z(e,null,r.head,r),r.tail||(r.tail=r.head),r.length++}function z(r,e,t,i){if(!(this instanceof z))return new z(r,e,t,i);this.list=i,this.value=r,e?(e.next=this,this.prev=e):this.prev=null,t?(t.prev=this,this.next=t):this.next=null}try{ct()(h)}catch(r){}});var _e=B((ci,yt)=>{"use strict";var Ir=gt(),Y=Symbol("max"),U=Symbol("length"),Z=Symbol("lengthCalculator"),se=Symbol("allowStale"),$=Symbol("maxAge"),q=Symbol("dispose"),ht=Symbol("noDisposeOnSet"),d=Symbol("lruList"),x=Symbol("cache"),pt=Symbol("updateAgeOnGet"),Oe=()=>1,mt=class{constructor(e){if(typeof e=="number"&&(e={max:e}),e||(e={}),e.max&&(typeof e.max!="number"||e.max<0))throw new TypeError("max must be a non-negative number");let t=this[Y]=e.max||1/0,i=e.length||Oe;if(this[Z]=typeof i!="function"?Oe:i,this[se]=e.stale||!1,e.maxAge&&typeof e.maxAge!="number")throw new TypeError("maxAge must be a number");this[$]=e.maxAge||0,this[q]=e.dispose,this[ht]=e.noDisposeOnSet||!1,this[pt]=e.updateAgeOnGet||!1,this.reset()}set max(e){if(typeof e!="number"||e<0)throw new TypeError("max must be a non-negative number");this[Y]=e||1/0,ae(this)}get max(){return this[Y]}set allowStale(e){this[se]=!!e}get allowStale(){return this[se]}set maxAge(e){if(typeof e!="number")throw new TypeError("maxAge must be a non-negative number");this[$]=e,ae(this)}get maxAge(){return this[$]}set lengthCalculator(e){typeof e!="function"&&(e=Oe),e!==this[Z]&&(this[Z]=e,this[U]=0,this[d].forEach(t=>{t.length=this[Z](t.value,t.key),this[U]+=t.length})),ae(this)}get lengthCalculator(){return this[Z]}get length(){return this[U]}get itemCount(){return this[d].length}rforEach(e,t){t=t||this;for(let i=this[d].tail;i!==null;){let n=i.prev;vt(this,e,i,t),i=n}}forEach(e,t){t=t||this;for(let i=this[d].head;i!==null;){let n=i.next;vt(this,e,i,t),i=n}}keys(){return this[d].toArray().map(e=>e.key)}values(){return this[d].toArray().map(e=>e.value)}reset(){this[q]&&this[d]&&this[d].length&&this[d].forEach(e=>this[q](e.key,e.value)),this[x]=new Map,this[d]=new Ir,this[U]=0}dump(){return this[d].map(e=>de(this,e)?!1:{k:e.key,v:e.value,e:e.now+(e.maxAge||0)}).toArray().filter(e=>e)}dumpLru(){return this[d]}set(e,t,i){if(i=i||this[$],i&&typeof i!="number")throw new TypeError("maxAge must be a number");let n=i?Date.now():0,s=this[Z](t,e);if(this[x].has(e)){if(s>this[Y])return ee(this,this[x].get(e)),!1;let c=this[x].get(e).value;return this[q]&&(this[ht]||this[q](e,c.value)),c.now=n,c.maxAge=i,c.value=t,this[U]+=s-c.length,c.length=s,this.get(e),ae(this),!0}let a=new dt(e,t,s,n,i);return a.length>this[Y]?(this[q]&&this[q](e,t),!1):(this[U]+=a.length,this[d].unshift(a),this[x].set(e,this[d].head),ae(this),!0)}has(e){if(!this[x].has(e))return!1;let t=this[x].get(e).value;return!de(this,t)}get(e){return Ce(this,e,!0)}peek(e){return Ce(this,e,!1)}pop(){let e=this[d].tail;return e?(ee(this,e),e.value):null}del(e){ee(this,this[x].get(e))}load(e){this.reset();let t=Date.now();for(let i=e.length-1;i>=0;i--){let n=e[i],s=n.e||0;if(s===0)this.set(n.k,n.v);else{let a=s-t;a>0&&this.set(n.k,n.v,a)}}}prune(){this[x].forEach((e,t)=>Ce(this,t,!1))}},Ce=(r,e,t)=>{let i=r[x].get(e);if(i){let n=i.value;if(de(r,n)){if(ee(r,i),!r[se])return}else t&&(r[pt]&&(i.value.now=Date.now()),r[d].unshiftNode(i));return n.value}},de=(r,e)=>{if(!e||!e.maxAge&&!r[$])return!1;let t=Date.now()-e.now;return e.maxAge?t>e.maxAge:r[$]&&t>r[$]},ae=r=>{if(r[U]>r[Y])for(let e=r[d].tail;r[U]>r[Y]&&e!==null;){let t=e.prev;ee(r,e),e=t}},ee=(r,e)=>{if(e){let t=e.value;r[q]&&r[q](t.key,t.value),r[U]-=t.length,r[x].delete(t.key),r[d].removeNode(e)}},dt=class{constructor(e,t,i,n,s){this.key=e,this.value=t,this.length=i,this.now=n,this.maxAge=s||0}},vt=(r,e,t,i)=>{let n=t.value;de(r,n)&&(ee(r,t),r[se]||(n=void 0)),n&&e.call(i,n.value,n.key,r)};yt.exports=mt});var jt=B((Ii,Le)=>{(function(){var r=this;let e=a=>new TextEncoder().encode(a);function t(a,u){typeof a=="string"&&(a=e(a));for(var c=a.length,f=u^c,l=0,p;c>=4;)p=a[l]&255|(a[++l]&255)<<8|(a[++l]&255)<<16|(a[++l]&255)<<24,p=(p&65535)*1540483477+(((p>>>16)*1540483477&65535)<<16),p^=p>>>24,p=(p&65535)*1540483477+(((p>>>16)*1540483477&65535)<<16),f=(f&65535)*1540483477+(((f>>>16)*1540483477&65535)<<16)^p,c-=4,++l;switch(c){case 3:f^=(a[l+2]&255)<<16;case 2:f^=(a[l+1]&255)<<8;case 1:f^=a[l]&255,f=(f&65535)*1540483477+(((f>>>16)*1540483477&65535)<<16)}return f^=f>>>13,f=(f&65535)*1540483477+(((f>>>16)*1540483477&65535)<<16),f^=f>>>15,f>>>0}function i(a,u){typeof a=="string"&&(a=e(a));var c,f,l,p,S,j,D,y,g,v;for(c=a.length&3,f=a.length-c,l=u,S=3432918353,D=461845907,v=0;v<f;)g=a[v]&255|(a[++v]&255)<<8|(a[++v]&255)<<16|(a[++v]&255)<<24,++v,g=(g&65535)*S+(((g>>>16)*S&65535)<<16)&4294967295,g=g<<15|g>>>17,g=(g&65535)*D+(((g>>>16)*D&65535)<<16)&4294967295,l^=g,l=l<<13|l>>>19,p=(l&65535)*5+(((l>>>16)*5&65535)<<16)&4294967295,l=(p&65535)+27492+(((p>>>16)+58964&65535)<<16);switch(g=0,c){case 3:g^=(a[v+2]&255)<<16;case 2:g^=(a[v+1]&255)<<8;case 1:g^=a[v]&255,g=(g&65535)*S+(((g>>>16)*S&65535)<<16)&4294967295,g=g<<15|g>>>17,g=(g&65535)*D+(((g>>>16)*D&65535)<<16)&4294967295,l^=g}return l^=a.length,l^=l>>>16,l=(l&65535)*2246822507+(((l>>>16)*2246822507&65535)<<16)&4294967295,l^=l>>>13,l=(l&65535)*3266489909+(((l>>>16)*3266489909&65535)<<16)&4294967295,l^=l>>>16,l>>>0}var n=i;if(n.v2=t,n.v3=i,typeof Le!="undefined")Le.exports=n;else{var s=r.murmur;n.noConflict=function(){return r.murmur=s,n},r.murmur=n}})()});or(exports,{Client:()=>le,ClientEvent:()=>V,FileStore:()=>oe,LRU:()=>$t.default,default:()=>Dr});var zt=T(require("events")),Yt=T(Xe()),Ke=T(require("axios")),ke=T(ot());var A;(function(s){s.READY="stream_ready",s.CONNECTED="stream_connected",s.DISCONNECTED="stream_disconnected",s.CHANGED="stream_changed",s.ERROR="stream_error"})(A||(A={}));var _=T(require("axios"));var ut=T(require("axios")),R="http://localhost/api/1.0".replace(/\/+$/,"");var ge=class{constructor(e,t=R,i=ut.default){this.basePath=t;this.axios=i;e&&(this.configuration=e,this.basePath=e.basePath||this.basePath)}},xe=class extends Error{constructor(e,t){super(t);this.field=e;this.name="RequiredError"}};var P="https://example.com",E=function(r,e,t){if(t==null)throw new xe(e,`Required parameter ${e} was null or undefined when calling ${r}.`)};var F=async function(r,e){if(e&&e.accessToken){let t=typeof e.accessToken=="function"?await e.accessToken():await e.accessToken;r.Authorization="Bearer "+t}};var I=function(r,...e){let t=new URLSearchParams(r.search);for(let i of e)for(let n in i)if(Array.isArray(i[n])){t.delete(n);for(let s of i[n])t.append(n,s)}else t.set(n,i[n]);r.search=t.toString()},Se=function(r,e,t){let i=typeof r!="string";return(i&&t&&t.isJsonMime?t.isJsonMime(e.headers["Content-Type"]):i)?JSON.stringify(r!==void 0?r:{}):r||""},O=function(r){return r.pathname+r.search+r.hash},C=function(r,e,t,i){return(n=e,s=t)=>{let a=ce(o({},r.options),{url:((i==null?void 0:i.basePath)||s)+r.url});return n.request(a)}};var H;(function(n){n.Boolean="boolean",n.Int="int",n.String="string",n.Json="json"})(H||(H={}));var he;(function(t){t.On="on",t.Off="off"})(he||(he={}));var pe;(function(e){e.Ffmetrics="FFMETRICS"})(pe||(pe={}));var Ar=function(r){return{authenticate:async(e,t={})=>{let i="/client/auth",n=new URL(i,P),s;r&&(s=r.baseOptions);let a=o(o({method:"POST"},s),t),u={},c={};u["Content-Type"]="application/json",I(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),a.data=Se(e,a,r),{url:O(n),options:a}},getAllSegments:async(e,t={})=>{E("getAllSegments","environmentUUID",e);let i="/client/env/{environmentUUID}/target-segments".replace("{environmentUUID}",encodeURIComponent(String(e))),n=new URL(i,P),s;r&&(s=r.baseOptions);let a=o(o({method:"GET"},s),t),u={},c={};await F(u,r),I(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),{url:O(n),options:a}},getEvaluationByIdentifier:async(e,t,i,n={})=>{E("getEvaluationByIdentifier","environmentUUID",e),E("getEvaluationByIdentifier","feature",t),E("getEvaluationByIdentifier","target",i);let s="/client/env/{environmentUUID}/target/{target}/evaluations/{feature}".replace("{environmentUUID}",encodeURIComponent(String(e))).replace("{feature}",encodeURIComponent(String(t))).replace("{target}",encodeURIComponent(String(i))),a=new URL(s,P),u;r&&(u=r.baseOptions);let c=o(o({method:"GET"},u),n),f={},l={};await F(f,r),I(a,l,n.query);let p=u&&u.headers?u.headers:{};return c.headers=o(o(o({},f),p),n.headers),{url:O(a),options:c}},getEvaluations:async(e,t,i={})=>{E("getEvaluations","environmentUUID",e),E("getEvaluations","target",t);let n="/client/env/{environmentUUID}/target/{target}/evaluations".replace("{environmentUUID}",encodeURIComponent(String(e))).replace("{target}",encodeURIComponent(String(t))),s=new URL(n,P),a;r&&(a=r.baseOptions);let u=o(o({method:"GET"},a),i),c={},f={};await F(c,r),I(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),{url:O(s),options:u}},getFeatureConfig:async(e,t={})=>{E("getFeatureConfig","environmentUUID",e);let i="/client/env/{environmentUUID}/feature-configs".replace("{environmentUUID}",encodeURIComponent(String(e))),n=new URL(i,P),s;r&&(s=r.baseOptions);let a=o(o({method:"GET"},s),t),u={},c={};await F(u,r),I(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),{url:O(n),options:a}},getFeatureConfigByIdentifier:async(e,t,i={})=>{E("getFeatureConfigByIdentifier","identifier",e),E("getFeatureConfigByIdentifier","environmentUUID",t);let n="/client/env/{environmentUUID}/feature-configs/{identifier}".replace("{identifier}",encodeURIComponent(String(e))).replace("{environmentUUID}",encodeURIComponent(String(t))),s=new URL(n,P),a;r&&(a=r.baseOptions);let u=o(o({method:"GET"},a),i),c={},f={};await F(c,r),I(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),{url:O(s),options:u}},getSegmentByIdentifier:async(e,t,i={})=>{E("getSegmentByIdentifier","identifier",e),E("getSegmentByIdentifier","environmentUUID",t);let n="/client/env/{environmentUUID}/target-segments/{identifier}".replace("{identifier}",encodeURIComponent(String(e))).replace("{environmentUUID}",encodeURIComponent(String(t))),s=new URL(n,P),a;r&&(a=r.baseOptions);let u=o(o({method:"GET"},a),i),c={},f={};await F(c,r),I(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),{url:O(s),options:u}},stream:async(e,t={})=>{E("stream","aPIKey",e);let i="/stream",n=new URL(i,P),s;r&&(s=r.baseOptions);let a=o(o({method:"GET"},s),t),u={},c={};await F(u,r),e!=null&&(u["API-Key"]=String(e)),I(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),{url:O(n),options:a}}}},M=function(r){let e=Ar(r);return{async authenticate(t,i){let n=await e.authenticate(t,i);return C(n,_.default,R,r)},async getAllSegments(t,i){let n=await e.getAllSegments(t,i);return C(n,_.default,R,r)},async getEvaluationByIdentifier(t,i,n,s){let a=await e.getEvaluationByIdentifier(t,i,n,s);return C(a,_.default,R,r)},async getEvaluations(t,i,n){let s=await e.getEvaluations(t,i,n);return C(s,_.default,R,r)},async getFeatureConfig(t,i){let n=await e.getFeatureConfig(t,i);return C(n,_.default,R,r)},async getFeatureConfigByIdentifier(t,i,n){let s=await e.getFeatureConfigByIdentifier(t,i,n);return C(s,_.default,R,r)},async getSegmentByIdentifier(t,i,n){let s=await e.getSegmentByIdentifier(t,i,n);return C(s,_.default,R,r)},async stream(t,i){let n=await e.stream(t,i);return C(n,_.default,R,r)}}};var Pe=class extends ge{authenticate(e,t){return M(this.configuration).authenticate(e,t).then(i=>i(this.axios,this.basePath))}getAllSegments(e,t){return M(this.configuration).getAllSegments(e,t).then(i=>i(this.axios,this.basePath))}getEvaluationByIdentifier(e,t,i,n){return M(this.configuration).getEvaluationByIdentifier(e,t,i,n).then(s=>s(this.axios,this.basePath))}getEvaluations(e,t,i){return M(this.configuration).getEvaluations(e,t,i).then(n=>n(this.axios,this.basePath))}getFeatureConfig(e,t){return M(this.configuration).getFeatureConfig(e,t).then(i=>i(this.axios,this.basePath))}getFeatureConfigByIdentifier(e,t,i){return M(this.configuration).getFeatureConfigByIdentifier(e,t,i).then(n=>n(this.axios,this.basePath))}getSegmentByIdentifier(e,t,i){return M(this.configuration).getSegmentByIdentifier(e,t,i).then(n=>n(this.axios,this.basePath))}stream(e,t){return M(this.configuration).stream(e,t).then(i=>i(this.axios,this.basePath))}},br=function(r){return{postMetrics:async(e,t,i={})=>{E("postMetrics","environment",e);let n="/metrics/{environment}".replace("{environment}",encodeURIComponent(String(e))),s=new URL(n,P),a;r&&(a=r.baseOptions);let u=o(o({method:"POST"},a),i),c={},f={};await F(c,r),c["Content-Type"]="application/json",I(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),u.data=Se(t,u,r),{url:O(s),options:u}}}},Rr=function(r){let e=br(r);return{async postMetrics(t,i,n){let s=await e.postMetrics(t,i,n);return C(s,_.default,R,r)}}};var Ie=class extends ge{postMetrics(e,t,i){return Rr(this.configuration).postMetrics(e,t,i).then(n=>n(this.axios,this.basePath))}};var ne=class{constructor(e={}){this.apiKey=e.apiKey,this.username=e.username,this.password=e.password,this.accessToken=e.accessToken,this.basePath=e.basePath,this.baseOptions=e.baseOptions,this.formDataCtor=e.formDataCtor}isJsonMime(e){let t=new RegExp("^(application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(;.*)?$","i");return e!==null&&(t.test(e)||e.toLowerCase()==="application/json-patch+json")}};var me="1.1.1";var At=T(_e());var we=class{trace(e,...t){console.trace(e,...t)}debug(e,...t){console.debug(e,...t)}info(e,...t){console.info(e,...t)}warn(e,...t){console.warn(e,...t)}error(e,...t){console.error(e,...t)}};var Et=T(require("keyv")),Tt=T(require("keyv-file")),oe=class{constructor(e={}){this.keyv=new Et.default({store:new Tt.KeyvFile(e)})}set(e,t){return this.keyv.set(e,t)}get(e){return this.keyv.get(e)}del(e){return this.keyv.delete(e)}};var bt=100;var Rt="featureIdentifier",xt="featureName",St="variationIdentifier";var Pt="target",It="SDK_VERSION",Ot="SDK_TYPE",Ct="server",_t="SDK_LANGUAGE",wt="javascript",Vt="global",Dt="segmentMatch",Nt="in",Ft="equal",Ut="gt",qt="starts_with",Lt="ends_with",Bt="contains",Mt="equal_sensitive",Or="https://config.ff.harness.io/api/1.0",Cr="https://events.ff.harness.io/api/1.0",_r=1e3,Kt=60*_r,wr=1*Kt,Vr=1*Kt,b={baseUrl:Or,eventsUrl:Cr,pollInterval:wr,eventsSyncInterval:Vr,enableStream:!0,enableAnalytics:!0,cache:new At.default({max:100}),store:new oe,logger:new we};var w=b.logger,W;(function(t){t.READY="poller_ready",t.ERROR="poller_error"})(W||(W={}));var Ve=class{constructor(e,t,i,n,s,a){this.stopped=!0;this.initialized=!1;this.api=i,this.options=n,this.environment=e,this.cluster=t,this.repository=a,this.eventBus=s}poll(){if(this.stopped)return;let e=new Date().getTime(),t=()=>{let i=new Date().getTime()-e,n=Math.max(this.options.pollInterval-i,0);setTimeout(()=>this.poll(),n)};Promise.all([this.retrieveFlags(),this.retrieveSegments()]).then(()=>{this.initialized||(this.initialized=!0,this.eventBus.emit(W.READY))}).catch(i=>{this.eventBus.emit(W.ERROR,{error:i})}).finally(t)}async retrieveFlags(){try{w.debug("Fetching flags started");let e=await this.api.getFeatureConfig(this.environment,{params:{cluster:this.cluster}});w.debug("Fetching flags finished"),e.data.forEach(t=>this.repository.setFlag(t.feature,t))}catch(e){throw w.error("Error loading flags",e),e}}async retrieveSegments(){try{w.debug("Fetching segments started");let e=await this.api.getAllSegments(this.environment,{params:{cluster:this.cluster}});w.debug("Fetching segments finished"),e.data.forEach(t=>this.repository.setSegment(t.identifier,t))}catch(e){throw w.error("Error loading segments",e),e}}start(){if(!this.stopped){w.info("PollingProcessor already started");return}w.info("Starting PollingProcessor with request interval: ",this.options.pollInterval),this.stopped=!1,this.poll()}stop(){w.info("Stopping PollingProcessor"),this.stopped=!0}close(){w.info("Closing PollingProcessor"),this.stop()}};var kt=T(require("eventsource"));var K=b.logger,De=class{constructor(e,t,i,n,s,a,u,c){this.api=e,this.apiKey=t,this.environment=i,this.jwtToken=n,this.options=s,this.cluster=a,this.eventBus=u,this.repository=c}start(){K.info("Starting StreamProcessor");let e=new kt.default(`${this.options.baseUrl}/stream?cluster=${this.cluster}`,{headers:{Authorization:`Bearer ${this.jwtToken}`,"API-Key":this.apiKey}});e.onopen=t=>{K.debug("Stream connected",t),this.eventBus.emit(A.CONNECTED)},e.onerror=t=>{K.debug("Stream has issue",t),this.eventBus.emit(A.ERROR,t)},e.addEventListener("*",t=>{let i=JSON.parse(t.data);K.debug("Received event from stream: ",i),i.domain==="flag"?this.msgProcessor(i,this.api.getFeatureConfigByIdentifier.bind(this.api),this.repository.setFlag.bind(this.repository),this.repository.deleteFlag.bind(this.repository)):i.domain==="target-segment"&&this.msgProcessor(i,this.api.getSegmentByIdentifier.bind(this.api),this.repository.setSegment.bind(this.repository),this.repository.deleteSegment.bind(this.repository))}),this.eventSource=e,this.eventBus.emit(A.READY)}async msgProcessor(e,t,i,n){K.info("Processing message",e);try{let a=(await t(e.identifier,this.environment)).data;e.event==="create"||e.event==="patch"?i(e.identifier,a):e.event==="delete"&&n(e.identifier)}catch(s){throw K.error("Error while fetching data with identifier:",e.identifier,s),s}K.info("Processing message finished",e)}connected(){return this.eventSource.readyState==De.CONNECTED}stop(){K.info("Stopping StreamProcessor"),this.eventSource.close(),this.eventBus.emit(A.DISCONNECTED)}close(){this.stop()}},ve=De;ve.CONNECTED=1;var Ne=class{constructor(e){this.value=e}startsWith(e){return!1}endsWith(e){return!1}match(e){return!1}contains(e){return!1}equalSensitive(e){return!1}equal(e){return this.value===(e[0].toLowerCase()==="true")}greaterThan(e){return!1}greaterThanEqual(e){return!1}lessThan(e){return!1}lessThanEqual(e){return!1}inList(e){return this.value}};var Fe=class{startsWith(e){return!1}endsWith(e){return!1}match(e){return!1}contains(e){return!1}equalSensitive(e){return!1}equal(e){return!1}greaterThan(e){return!1}greaterThanEqual(e){return!1}lessThan(e){return!1}lessThanEqual(e){return!1}inList(e){return!1}};var Ue=class{constructor(e){this.value=e}startsWith(e){return!1}endsWith(e){return!1}match(e){return!1}contains(e){return!1}equalSensitive(e){return!1}equal(e){return this.value===parseFloat(e==null?void 0:e[0])}greaterThan(e){return this.value>parseFloat(e==null?void 0:e[0])}greaterThanEqual(e){return this.value>=parseFloat(e==null?void 0:e[0])}lessThan(e){return this.value<parseFloat(e==null?void 0:e[0])}lessThanEqual(e){return this.value<=parseFloat(e==null?void 0:e[0])}inList(e){return e.map(i=>parseFloat(i)).includes(this.value)}};var qe=class{constructor(e){this.value=e}startsWith(e){return this.value.startsWith(e==null?void 0:e[0])}endsWith(e){return this.value.endsWith(e==null?void 0:e[0])}match(e){return this.value.match(e==null?void 0:e[0])!==void 0}contains(e){return this.value.includes(e==null?void 0:e[0])}equalSensitive(e){return this.value===(e==null?void 0:e[0])}equal(e){var t;return this.value.toLocaleLowerCase()===((t=e==null?void 0:e[0])==null?void 0:t.toLocaleLowerCase())}greaterThan(e){return this.value>(e==null?void 0:e[0])}greaterThanEqual(e){return this.value>=(e==null?void 0:e[0])}lessThan(e){return this.value<(e==null?void 0:e[0])}lessThanEqual(e){return this.value<=(e==null?void 0:e[0])}inList(e){return e.includes(this.value)}};var Gt=T(jt()),Q=b.logger,Be=class{constructor(e){this.query=e}getAttrValue(e,t){var i;return e[t]||((i=e.attributes)==null?void 0:i[t])}findVariation(e,t){return e.find(i=>i.identifier===t)}getNormalizedNumberWithNormalizer(e,t,i){let n=[t,e].join(":");return parseInt((0,Gt.default)(n).toString())%i+1}getNormalizedNumber(e,t){return this.getNormalizedNumberWithNormalizer(e,t,bt)}isEnabled(e,t,i){let n=this.getAttrValue(e,t);if(!n)return!1;let s=this.getNormalizedNumber(n,t);return i>0&&s<=i}evaluateDistribution(e,t){if(!e)return;let i="";for(let n of e.variations)if(i=n.variation,this.isEnabled(t,e.bucketBy,n.weight))return n.variation;return i}getOperator(e,t){let i=this.getAttrValue(e,t);switch(typeof i){case"boolean":return new Ne(i);case"string":return new qe(i);case"number":return new Ue(i);case"object":return new Fe}}convertApiTargetsToEvalTargets(e){return e.map(t=>({identifier:t.identifier,name:t.name,anonymous:t.anonymous,attributes:t.attributes}))}async isTargetIncludedOrExcludedInSegment(e,t){for(let i of e){let n=await this.query.getSegment(i);if(n){if(this.convertApiTargetsToEvalTargets(n.excluded).includes(t))return Q.debug(`Target %s excluded from segment %s via exclude list | ||
`,t.name,n.name),!1;if(this.convertApiTargetsToEvalTargets(n.included).includes(t))return Q.debug(`Target %s included in segment %s via include list | ||
`,t.name,n.name),!0;if(n.rules&&this.evaluateClauses(n.rules,t))return Q.debug(`Target %s included in segment %s via rules | ||
`,t.name,n.name),!0}}return!1}async evaluateClause(e,t){if(!e.op)return!1;let i=this.getOperator(t,e.attribute);switch(e.op){case Nt:return i.inList(e.values);case Ft:return i.equal(e.values);case Mt:return i.equalSensitive(e.values);case Ut:return i.greaterThan(e.values);case qt:return i.startsWith(e.values);case Lt:return i.endsWith(e.values);case Bt:return i.contains(e.values);case Dt:return this.isTargetIncludedOrExcludedInSegment(e.values,t)}return!1}async evaluateClauses(e,t){for(let i of e)if(!await this.evaluateClause(i,t))return!1;return!0}evaluateRule(e,t){return this.evaluateClauses(e.clauses,t)}async evaluateRules(e,t){if(!t||!e)return;e.sort((n,s)=>n.priority>s.priority?1:-1);let i;for(let n of e)if(!!await this.evaluateRule(n,t))return n.serve.distribution&&(i=this.evaluateDistribution(n.serve.distribution,t)),n.serve.variation&&(i=n.serve.variation),i}evaluateVariationMap(e,t){var i;if(!(!t||!e))for(let n of e){if((i=n.targets)==null?void 0:i.find(u=>u.identifier===t.identifier))return n.variation;let a=n.targetSegments;if(a&&this.isTargetIncludedOrExcludedInSegment(a,t))return n.variation}}async evaluateFlag(e,t){let i=e.offVariation;return e.state===he.On&&(i=this.evaluateVariationMap(e.variationToTargetMap,t)||await this.evaluateRules(e.rules,t)||this.evaluateDistribution(e.defaultServe.distribution,t)||e.defaultServe.variation),this.findVariation(e.variations,i)}async checkPreRequisite(e,t){if(e.prerequisites){Q.info("Checking pre requisites %s of parent feature %s",e.prerequisites,e.feature);for(let i of e.prerequisites){let n=await this.query.getFlag(i.feature);if(!n)return Q.warn("Could not retrieve the pre requisite details of feature flag: %s",e.feature),!0;let s=await this.evaluateFlag(n,t);return Q.info("Pre requisite flag %s has variation %s for target %s",n.feature,s,t),Q.info("Pre requisite flag %s should have the variations %s",n.feature,i.variations),i.variations.includes(s.identifier)?await this.checkPreRequisite(n,t):!1}}return!0}async evaluate(e,t,i,n){let s=await this.query.getFlag(e);if(!s||s.kind!==i)return;if(s.prerequisites&&!await this.checkPreRequisite(s,t))return this.findVariation(s.variations,s.offVariation);let a=await this.evaluateFlag(s,t);if(a)return n&&n(s,t,a),a}async boolVariation(e,t,i=!1,n){let s=await this.evaluate(e,t,H.Boolean,n);return s?s.value.toLowerCase()==="true":i}async stringVariation(e,t,i="",n){let s=await this.evaluate(e,t,H.String,n);return s?s.value:i}async numberVariation(e,t,i=0,n){let s=await this.evaluate(e,t,H.Int,n);return s?parseFloat(s.value):i}async jsonVariation(e,t,i={},n){let s=await this.evaluate(e,t,H.Json,n);return s?JSON.parse(s.value):i}};var Me=class{constructor(e,t){if(!e)throw new Error("Cache is required argument and cannot be undefined");this.cache=e,this.store=t}async setFlag(e,t){let i=this.formatFlagKey(e);await this.isFlagOutdated(i,t)||(this.store?(await this.store.set(i,t),this.cache.del(i)):this.cache.set(i,t))}async setSegment(e,t){let i=this.formatSegmentKey(e);await this.isSegmentOutdated(i,t)||(this.store?(await this.store.set(i,t),this.cache.del(i)):this.cache.set(i,t))}async deleteFlag(e){let t=this.formatFlagKey(e);this.store&&await this.store.del(t),this.cache.del(t)}async deleteSegment(e){let t=this.formatSegmentKey(e);this.store&&await this.store.del(t),this.cache.del(t)}async getFlag(e,t=!0){let i=this.formatFlagKey(e),n=this.cache.get(i);if(n)return n;if(this.store)return n=await this.store.get(i),n&&t&&this.cache.set(i,n),n}async getSegment(e,t=!0){let i=this.formatSegmentKey(e),n=this.cache.get(i);if(n)return n;if(this.store)return n=await this.store.get(i),n&&t&&this.cache.set(i,n),n}async isFlagOutdated(e,t){let i=await this.getFlag(e,!1);return(i==null?void 0:i.version)&&i.version>(t==null?void 0:t.version)}async isSegmentOutdated(e,t){let i=await this.getSegment(e,!1);return(i==null?void 0:i.version)&&i.version>(t==null?void 0:t.version)}formatFlagKey(e){return`flags/${e}`}formatSegmentKey(e){return`segments/${e}`}};var J=b.logger,te;(function(t){t.READY="metrics_ready",t.ERROR="metrics_error"})(te||(te={}));var Ht=(r,e="1",t,i,n)=>{let s=new Map,a,u=new ne(ce(o({},t),{basePath:i.eventsUrl})),c=new Ie(u),f=(y,g,v)=>{let L={target:y,featureConfig:g,variation:v,count:0},X=l(L),m=s.get(X);m?m.count++:(L.count=1,s.set(X,L))},l=y=>{let g=y.featureConfig.feature,v=y.variation.identifier,L=y.variation.value;return`${g}/${v}/${L}/${Vt}`},p=()=>{var L,X;if(!s){J.debug("No metrics data!");return}let y=[],g=[],v=new Map(s);s.clear();for(let m of v.values()){if(m.target&&!m.target.anonymous){let je=[];m.target.attributes&&(je=Object.entries(m.target.attributes).map(([Xt,Zt])=>({key:Xt,value:Zt})));let Ge=m.target.identifier;m.target.name&&(Ge=m.target.name);let Jt={identifier:m.target.identifier,name:Ge,attributes:je};y.push(Jt)}let Wt=[{key:Rt,value:m.featureConfig.feature},{key:xt,value:m.featureConfig.feature},{key:St,value:m.variation.identifier},{key:Ot,value:Ct},{key:_t,value:wt},{key:It,value:me},{key:Pt,value:(X=(L=m==null?void 0:m.target)==null?void 0:L.identifier)!=null?X:null}],Qt={timestamp:Date.now(),count:m.count,metricsType:pe.Ffmetrics,attributes:Wt};g.push(Qt)}return{targetData:y,metricsData:g}},S=()=>{let y=p();y&&(J.debug("Start sending metrics data"),c.postMetrics(r,y,{params:{cluster:e}}).then(g=>{J.debug("Metrics server returns: ",g.status),g.status>=400&&J.error("Error while sending metrics data with status code: ",g.status)}).catch(g=>{J.debug("Metrics server returns error: ",g)}))};return{start:()=>{J.info("Starting MetricsProcessor with request interval: ",i.eventsSyncInterval),a=setInterval(S,i.eventsSyncInterval),n.emit(te.READY)},close:()=>{J.info("Closing MetricsProcessor"),clearInterval(a),S()},enqueue:f}};Ke.default.defaults.timeout=3e4;(0,ke.default)(Ke.default,{retries:3,retryDelay:ke.default.exponentialDelay});var ue=b.logger,k;(function(i){i[i.POLL=0]="POLL",i[i.STREAM=1]="STREAM",i[i.METRICS=2]="METRICS"})(k||(k={}));var V;(function(i){i.READY="ready",i.FAILED="failed",i.CHANGED="changed"})(V||(V={}));var le=class{constructor(e,t={}){this.cluster="1";this.eventBus=new zt.EventEmitter;this.initialized=!1;this.failure=!1;this.pollerReady=!1;this.streamReady=!1;this.metricReady=!1;this.sdkKey=e,t.pollInterval<1e3&&(t.pollInterval=b.pollInterval,ue.warn("Polling interval cannot be lower than 1000 ms")),this.options=o(o({},b),t),this.configuration=new ne({basePath:this.options.baseUrl,baseOptions:{headers:{"User-Agent":`NodeJsSDK/${me}`}}}),this.repository=new Me(this.options.cache,this.options.store),this.evaluator=new Be(this.repository),this.api=new Pe(this.configuration),this.processEvents(),this.run()}processEvents(){this.eventBus.on(W.READY,()=>{this.initialize(0)}),this.eventBus.on(W.ERROR,()=>{this.failure=!0,this.eventBus.emit(V.FAILED)}),this.eventBus.on(A.READY,()=>{this.initialize(1)}),this.eventBus.on(A.ERROR,()=>{this.failure=!0,this.eventBus.emit(V.FAILED)}),this.eventBus.on(te.READY,()=>{this.initialize(2)}),this.eventBus.on(te.ERROR,()=>{this.failure=!0,this.eventBus.emit(V.FAILED)}),this.eventBus.on(A.CONNECTED,()=>{this.pollProcessor.stop()}),this.eventBus.on(A.DISCONNECTED,()=>{this.pollProcessor.start()})}async authenticate(){try{let e=await this.api.authenticate({apiKey:this.sdkKey});this.authToken=e.data.authToken,this.configuration.accessToken=this.authToken;let t=(0,Yt.default)(this.authToken);this.environment=t.environment,this.cluster=t.clusterIdentifier||"1"}catch(e){this.failure=!0,console.error("Error while authenticating, err: ",e)}}waitForInitialization(){return this.waitForInitialize?this.waitForInitialize:(this.initialized?this.waitForInitialize=Promise.resolve(this):this.failure?this.waitForInitialize=Promise.reject(this.failure):this.waitForInitialize=new Promise((e,t)=>{this.eventBus.once(V.READY,()=>{e(this)}),this.eventBus.once(V.FAILED,t)}),this.waitForInitialize)}initialize(e){switch(e){case 0:this.pollerReady=!0,ue.debug("PollingProcessor ready");break;case 1:this.streamReady=!0,ue.debug("StreamingProcessor ready");break;case 2:this.metricReady=!0,ue.debug("MetricsProcessor ready");break}this.options.enableStream&&!this.streamReady||this.options.enableAnalytics&&!this.metricReady||!this.pollerReady||(this.initialized=!0,this.eventBus.emit(V.READY))}async run(){await this.authenticate(),this.pollProcessor=new Ve(this.environment,this.cluster,this.api,this.options,this.eventBus,this.repository),this.pollProcessor.start(),this.options.enableStream&&(this.streamProcessor=new ve(this.api,this.sdkKey,this.environment,this.authToken,this.options,this.cluster,this.eventBus,this.repository),this.streamProcessor.start()),this.options.enableAnalytics&&(this.metricsProcessor=Ht(this.environment,this.cluster,this.configuration,this.options,this.eventBus),this.metricsProcessor.start()),ue.info("finished setting up processors")}boolVariation(e,t,i=!1){return this.evaluator.boolVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}stringVariation(e,t,i=""){return this.evaluator.stringVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}numberVariation(e,t,i=0){return this.evaluator.numberVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}jsonVariation(e,t,i={}){return this.evaluator.jsonVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}close(){this.pollProcessor.close(),this.streamProcessor&&this.streamProcessor.close(),this.metricsProcessor&&this.metricsProcessor.close()}};var $t=T(_e());var Dr={instance:void 0,init:function(r,e){this.instance||(this.instance=new le(r,e))},waitForInitialization:function(){return this.instance.waitForInitialization()},boolVariation:function(r,e,t=!1){return this.instance.boolVariation(r,e,t)},stringVariation:function(r,e,t=""){return this.instance.stringVariation(r,e,t)},numberVariation:function(r,e,t=0){return this.instance.numberVariation(r,e,t)},jsonVariation:function(r,e,t=""){return this.instance.jsonVariation(r,e,t)},close:function(){return this.instance.close()}};0&&(module.exports={Client,ClientEvent,FileStore,LRU}); | ||
//# sourceMappingURL=index.js.map |
@@ -1,5 +0,5 @@ | ||
var Ht=Object.create;var oe=Object.defineProperty,zt=Object.defineProperties,Yt=Object.getOwnPropertyDescriptor,$t=Object.getOwnPropertyDescriptors,Wt=Object.getOwnPropertyNames,Ge=Object.getOwnPropertySymbols,Qt=Object.getPrototypeOf,He=Object.prototype.hasOwnProperty,Jt=Object.prototype.propertyIsEnumerable;var ze=(r,e,t)=>e in r?oe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,o=(r,e)=>{for(var t in e||(e={}))He.call(e,t)&&ze(r,t,e[t]);if(Ge)for(var t of Ge(e))Jt.call(e,t)&&ze(r,t,e[t]);return r},ue=(r,e)=>zt(r,$t(e)),Xt=r=>oe(r,"__esModule",{value:!0});var q=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Zt=(r,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Wt(e))!He.call(r,i)&&i!=="default"&&oe(r,i,{get:()=>e[i],enumerable:!(t=Yt(e,i))||t.enumerable});return r},ee=r=>Zt(Xt(oe(r!=null?Ht(Qt(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var Qe=q((wr,We)=>{"use strict";function ye(r){this.message=r}ye.prototype=new Error,ye.prototype.name="InvalidCharacterError";var Ye=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(r){var e=String(r).replace(/=+$/,"");if(e.length%4==1)throw new ye("'atob' failed: The string to be decoded is not correctly encoded.");for(var t,i,n=0,s=0,a="";i=e.charAt(s++);~i&&(t=n%4?64*t+i:i,n++%4)?a+=String.fromCharCode(255&t>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return a};function er(r){var e=r.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(Ye(t).replace(/(.)/g,function(i,n){var s=n.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch(t){return Ye(e)}}function te(r){this.message=r}function $e(r,e){if(typeof r!="string")throw new te("Invalid token specified");var t=(e=e||{}).header===!0?0:1;try{return JSON.parse(er(r.split(".")[t]))}catch(i){throw new te("Invalid token specified: "+i.message)}}te.prototype=new Error,te.prototype.name="InvalidTokenError";var Ee=$e;Ee.default=$e,Ee.InvalidTokenError=te,We.exports=Ee});var Xe=q((Vr,Je)=>{"use strict";var tr=["ETIMEDOUT","ECONNRESET","EADDRINUSE","ESOCKETTIMEDOUT","ECONNREFUSED","EPIPE","EHOSTUNREACH","EAI_AGAIN"],rr=["ENOTFOUND","ENETUNREACH","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_CRL","UNABLE_TO_DECRYPT_CERT_SIGNATURE","UNABLE_TO_DECRYPT_CRL_SIGNATURE","UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY","CERT_SIGNATURE_FAILURE","CRL_SIGNATURE_FAILURE","CERT_NOT_YET_VALID","CERT_HAS_EXPIRED","CRL_NOT_YET_VALID","CRL_HAS_EXPIRED","ERROR_IN_CERT_NOT_BEFORE_FIELD","ERROR_IN_CERT_NOT_AFTER_FIELD","ERROR_IN_CRL_LAST_UPDATE_FIELD","ERROR_IN_CRL_NEXT_UPDATE_FIELD","OUT_OF_MEM","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_CHAIN_TOO_LONG","CERT_REVOKED","INVALID_CA","PATH_LENGTH_EXCEEDED","INVALID_PURPOSE","CERT_UNTRUSTED","CERT_REJECTED"];Je.exports=function(r){return!r||!r.code||tr.indexOf(r.code)!==-1?!0:rr.indexOf(r.code)===-1}});var it=q(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});var ir=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r};w.isNetworkError=Ae;w.isRetryableError=le;w.isSafeRequestError=et;w.isIdempotentRequestError=be;w.isNetworkOrIdempotentRequestError=Re;w.exponentialDelay=tt;w.default=k;var nr=Xe(),sr=ar(nr);function ar(r){return r&&r.__esModule?r:{default:r}}var Te="axios-retry";function Ae(r){return!r.response&&Boolean(r.code)&&r.code!=="ECONNABORTED"&&(0,sr.default)(r)}var Ze=["get","head","options"],or=Ze.concat(["put","delete"]);function le(r){return r.code!=="ECONNABORTED"&&(!r.response||r.response.status>=500&&r.response.status<=599)}function et(r){return r.config?le(r)&&Ze.indexOf(r.config.method)!==-1:!1}function be(r){return r.config?le(r)&&or.indexOf(r.config.method)!==-1:!1}function Re(r){return Ae(r)||be(r)}function ur(){return 0}function tt(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=Math.pow(2,r)*100,t=e*.2*Math.random();return e+t}function rt(r){var e=r[Te]||{};return e.retryCount=e.retryCount||0,r[Te]=e,e}function lr(r,e){return Object.assign({},e,r[Te])}function cr(r,e){r.defaults.agent===e.agent&&delete e.agent,r.defaults.httpAgent===e.httpAgent&&delete e.httpAgent,r.defaults.httpsAgent===e.httpsAgent&&delete e.httpsAgent}async function fr(r,e,t,i){var n=t.retryCount<r&&e(i);if((typeof n=="undefined"?"undefined":ir(n))==="object")try{return await n,!0}catch(s){return!1}return n}function k(r,e){r.interceptors.request.use(function(t){var i=rt(t);return i.lastRequestTime=Date.now(),t}),r.interceptors.response.use(null,async function(t){var i=t.config;if(!i)return Promise.reject(t);var n=lr(i,e),s=n.retries,a=s===void 0?3:s,u=n.retryCondition,c=u===void 0?Re:u,f=n.retryDelay,l=f===void 0?ur:f,p=n.shouldResetTimeout,x=p===void 0?!1:p,K=rt(i);if(await fr(a,c,K,t)){K.retryCount+=1;var _=l(K.retryCount,t);if(cr(r,i),!x&&i.timeout&&K.lastRequestTime){var y=Date.now()-K.lastRequestTime;i.timeout=Math.max(i.timeout-y-_,1)}return i.transformRequest=[function(g){return g}],new Promise(function(g){return setTimeout(function(){return g(r(i))},_)})}return Promise.reject(t)})}k.isNetworkError=Ae;k.isSafeRequestError=et;k.isIdempotentRequestError=be;k.isNetworkOrIdempotentRequestError=Re;k.exponentialDelay=tt;k.isRetryableError=le});var st=q((Fr,nt)=>{nt.exports=it().default});var ot=q((ai,at)=>{"use strict";at.exports=function(r){r.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}});var lt=q((oi,ut)=>{"use strict";ut.exports=h;h.Node=G;h.create=h;function h(r){var e=this;if(e instanceof h||(e=new h),e.tail=null,e.head=null,e.length=0,r&&typeof r.forEach=="function")r.forEach(function(n){e.push(n)});else if(arguments.length>0)for(var t=0,i=arguments.length;t<i;t++)e.push(arguments[t]);return e}h.prototype.removeNode=function(r){if(r.list!==this)throw new Error("removing node which does not belong to this list");var e=r.next,t=r.prev;return e&&(e.prev=t),t&&(t.next=e),r===this.head&&(this.head=e),r===this.tail&&(this.tail=t),r.list.length--,r.next=null,r.prev=null,r.list=null,e};h.prototype.unshiftNode=function(r){if(r!==this.head){r.list&&r.list.removeNode(r);var e=this.head;r.list=this,r.next=e,e&&(e.prev=r),this.head=r,this.tail||(this.tail=r),this.length++}};h.prototype.pushNode=function(r){if(r!==this.tail){r.list&&r.list.removeNode(r);var e=this.tail;r.list=this,r.prev=e,e&&(e.next=r),this.tail=r,this.head||(this.head=r),this.length++}};h.prototype.push=function(){for(var r=0,e=arguments.length;r<e;r++)vr(this,arguments[r]);return this.length};h.prototype.unshift=function(){for(var r=0,e=arguments.length;r<e;r++)yr(this,arguments[r]);return this.length};h.prototype.pop=function(){if(!!this.tail){var r=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,r}};h.prototype.shift=function(){if(!!this.head){var r=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,r}};h.prototype.forEach=function(r,e){e=e||this;for(var t=this.head,i=0;t!==null;i++)r.call(e,t.value,i,this),t=t.next};h.prototype.forEachReverse=function(r,e){e=e||this;for(var t=this.tail,i=this.length-1;t!==null;i--)r.call(e,t.value,i,this),t=t.prev};h.prototype.get=function(r){for(var e=0,t=this.head;t!==null&&e<r;e++)t=t.next;if(e===r&&t!==null)return t.value};h.prototype.getReverse=function(r){for(var e=0,t=this.tail;t!==null&&e<r;e++)t=t.prev;if(e===r&&t!==null)return t.value};h.prototype.map=function(r,e){e=e||this;for(var t=new h,i=this.head;i!==null;)t.push(r.call(e,i.value,this)),i=i.next;return t};h.prototype.mapReverse=function(r,e){e=e||this;for(var t=new h,i=this.tail;i!==null;)t.push(r.call(e,i.value,this)),i=i.prev;return t};h.prototype.reduce=function(r,e){var t,i=this.head;if(arguments.length>1)t=e;else if(this.head)i=this.head.next,t=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=0;i!==null;n++)t=r(t,i.value,n),i=i.next;return t};h.prototype.reduceReverse=function(r,e){var t,i=this.tail;if(arguments.length>1)t=e;else if(this.tail)i=this.tail.prev,t=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=this.length-1;i!==null;n--)t=r(t,i.value,n),i=i.prev;return t};h.prototype.toArray=function(){for(var r=new Array(this.length),e=0,t=this.head;t!==null;e++)r[e]=t.value,t=t.next;return r};h.prototype.toArrayReverse=function(){for(var r=new Array(this.length),e=0,t=this.tail;t!==null;e++)r[e]=t.value,t=t.prev;return r};h.prototype.slice=function(r,e){e=e||this.length,e<0&&(e+=this.length),r=r||0,r<0&&(r+=this.length);var t=new h;if(e<r||e<0)return t;r<0&&(r=0),e>this.length&&(e=this.length);for(var i=0,n=this.head;n!==null&&i<r;i++)n=n.next;for(;n!==null&&i<e;i++,n=n.next)t.push(n.value);return t};h.prototype.sliceReverse=function(r,e){e=e||this.length,e<0&&(e+=this.length),r=r||0,r<0&&(r+=this.length);var t=new h;if(e<r||e<0)return t;r<0&&(r=0),e>this.length&&(e=this.length);for(var i=this.length,n=this.tail;n!==null&&i>e;i--)n=n.prev;for(;n!==null&&i>r;i--,n=n.prev)t.push(n.value);return t};h.prototype.splice=function(r,e,...t){r>this.length&&(r=this.length-1),r<0&&(r=this.length+r);for(var i=0,n=this.head;n!==null&&i<r;i++)n=n.next;for(var s=[],i=0;n&&i<e;i++)s.push(n.value),n=this.removeNode(n);n===null&&(n=this.tail),n!==this.head&&n!==this.tail&&(n=n.prev);for(var i=0;i<t.length;i++)n=dr(this,n,t[i]);return s};h.prototype.reverse=function(){for(var r=this.head,e=this.tail,t=r;t!==null;t=t.prev){var i=t.prev;t.prev=t.next,t.next=i}return this.head=e,this.tail=r,this};function dr(r,e,t){var i=e===r.head?new G(t,null,e,r):new G(t,e,e.next,r);return i.next===null&&(r.tail=i),i.prev===null&&(r.head=i),r.length++,i}function vr(r,e){r.tail=new G(e,r.tail,null,r),r.head||(r.head=r.tail),r.length++}function yr(r,e){r.head=new G(e,null,r.head,r),r.tail||(r.tail=r.head),r.length++}function G(r,e,t,i){if(!(this instanceof G))return new G(r,e,t,i);this.list=i,this.value=r,e?(e.next=this,this.prev=e):this.prev=null,t?(t.prev=this,this.next=t):this.next=null}try{ot()(h)}catch(r){}});var _e=q((ui,mt)=>{"use strict";var Er=lt(),H=Symbol("max"),F=Symbol("length"),Q=Symbol("lengthCalculator"),ie=Symbol("allowStale"),z=Symbol("maxAge"),N=Symbol("dispose"),ct=Symbol("noDisposeOnSet"),d=Symbol("lruList"),R=Symbol("cache"),ft=Symbol("updateAgeOnGet"),Oe=()=>1,gt=class{constructor(e){if(typeof e=="number"&&(e={max:e}),e||(e={}),e.max&&(typeof e.max!="number"||e.max<0))throw new TypeError("max must be a non-negative number");let t=this[H]=e.max||1/0,i=e.length||Oe;if(this[Q]=typeof i!="function"?Oe:i,this[ie]=e.stale||!1,e.maxAge&&typeof e.maxAge!="number")throw new TypeError("maxAge must be a number");this[z]=e.maxAge||0,this[N]=e.dispose,this[ct]=e.noDisposeOnSet||!1,this[ft]=e.updateAgeOnGet||!1,this.reset()}set max(e){if(typeof e!="number"||e<0)throw new TypeError("max must be a non-negative number");this[H]=e||1/0,ne(this)}get max(){return this[H]}set allowStale(e){this[ie]=!!e}get allowStale(){return this[ie]}set maxAge(e){if(typeof e!="number")throw new TypeError("maxAge must be a non-negative number");this[z]=e,ne(this)}get maxAge(){return this[z]}set lengthCalculator(e){typeof e!="function"&&(e=Oe),e!==this[Q]&&(this[Q]=e,this[F]=0,this[d].forEach(t=>{t.length=this[Q](t.value,t.key),this[F]+=t.length})),ne(this)}get lengthCalculator(){return this[Q]}get length(){return this[F]}get itemCount(){return this[d].length}rforEach(e,t){t=t||this;for(let i=this[d].tail;i!==null;){let n=i.prev;pt(this,e,i,t),i=n}}forEach(e,t){t=t||this;for(let i=this[d].head;i!==null;){let n=i.next;pt(this,e,i,t),i=n}}keys(){return this[d].toArray().map(e=>e.key)}values(){return this[d].toArray().map(e=>e.value)}reset(){this[N]&&this[d]&&this[d].length&&this[d].forEach(e=>this[N](e.key,e.value)),this[R]=new Map,this[d]=new Er,this[F]=0}dump(){return this[d].map(e=>pe(this,e)?!1:{k:e.key,v:e.value,e:e.now+(e.maxAge||0)}).toArray().filter(e=>e)}dumpLru(){return this[d]}set(e,t,i){if(i=i||this[z],i&&typeof i!="number")throw new TypeError("maxAge must be a number");let n=i?Date.now():0,s=this[Q](t,e);if(this[R].has(e)){if(s>this[H])return J(this,this[R].get(e)),!1;let c=this[R].get(e).value;return this[N]&&(this[ct]||this[N](e,c.value)),c.now=n,c.maxAge=i,c.value=t,this[F]+=s-c.length,c.length=s,this.get(e),ne(this),!0}let a=new ht(e,t,s,n,i);return a.length>this[H]?(this[N]&&this[N](e,t),!1):(this[F]+=a.length,this[d].unshift(a),this[R].set(e,this[d].head),ne(this),!0)}has(e){if(!this[R].has(e))return!1;let t=this[R].get(e).value;return!pe(this,t)}get(e){return Ce(this,e,!0)}peek(e){return Ce(this,e,!1)}pop(){let e=this[d].tail;return e?(J(this,e),e.value):null}del(e){J(this,this[R].get(e))}load(e){this.reset();let t=Date.now();for(let i=e.length-1;i>=0;i--){let n=e[i],s=n.e||0;if(s===0)this.set(n.k,n.v);else{let a=s-t;a>0&&this.set(n.k,n.v,a)}}}prune(){this[R].forEach((e,t)=>Ce(this,t,!1))}},Ce=(r,e,t)=>{let i=r[R].get(e);if(i){let n=i.value;if(pe(r,n)){if(J(r,i),!r[ie])return}else t&&(r[ft]&&(i.value.now=Date.now()),r[d].unshiftNode(i));return n.value}},pe=(r,e)=>{if(!e||!e.maxAge&&!r[z])return!1;let t=Date.now()-e.now;return e.maxAge?t>e.maxAge:r[z]&&t>r[z]},ne=r=>{if(r[F]>r[H])for(let e=r[d].tail;r[F]>r[H]&&e!==null;){let t=e.prev;J(r,e),e=t}},J=(r,e)=>{if(e){let t=e.value;r[N]&&r[N](t.key,t.value),r[F]-=t.length,r[R].delete(t.key),r[d].removeNode(e)}},ht=class{constructor(e,t,i,n,s){this.key=e,this.value=t,this.length=i,this.now=n,this.maxAge=s||0}},pt=(r,e,t,i)=>{let n=t.value;pe(r,n)&&(J(r,t),r[ie]||(n=void 0)),n&&e.call(i,n.value,n.key,r)};mt.exports=gt});var qt=q((Oi,Le)=>{(function(){var r=this;let e=a=>new TextEncoder().encode(a);function t(a,u){typeof a=="string"&&(a=e(a));for(var c=a.length,f=u^c,l=0,p;c>=4;)p=a[l]&255|(a[++l]&255)<<8|(a[++l]&255)<<16|(a[++l]&255)<<24,p=(p&65535)*1540483477+(((p>>>16)*1540483477&65535)<<16),p^=p>>>24,p=(p&65535)*1540483477+(((p>>>16)*1540483477&65535)<<16),f=(f&65535)*1540483477+(((f>>>16)*1540483477&65535)<<16)^p,c-=4,++l;switch(c){case 3:f^=(a[l+2]&255)<<16;case 2:f^=(a[l+1]&255)<<8;case 1:f^=a[l]&255,f=(f&65535)*1540483477+(((f>>>16)*1540483477&65535)<<16)}return f^=f>>>13,f=(f&65535)*1540483477+(((f>>>16)*1540483477&65535)<<16),f^=f>>>15,f>>>0}function i(a,u){typeof a=="string"&&(a=e(a));var c,f,l,p,x,K,_,y,g,v;for(c=a.length&3,f=a.length-c,l=u,x=3432918353,_=461845907,v=0;v<f;)g=a[v]&255|(a[++v]&255)<<8|(a[++v]&255)<<16|(a[++v]&255)<<24,++v,g=(g&65535)*x+(((g>>>16)*x&65535)<<16)&4294967295,g=g<<15|g>>>17,g=(g&65535)*_+(((g>>>16)*_&65535)<<16)&4294967295,l^=g,l=l<<13|l>>>19,p=(l&65535)*5+(((l>>>16)*5&65535)<<16)&4294967295,l=(p&65535)+27492+(((p>>>16)+58964&65535)<<16);switch(g=0,c){case 3:g^=(a[v+2]&255)<<16;case 2:g^=(a[v+1]&255)<<8;case 1:g^=a[v]&255,g=(g&65535)*x+(((g>>>16)*x&65535)<<16)&4294967295,g=g<<15|g>>>17,g=(g&65535)*_+(((g>>>16)*_&65535)<<16)&4294967295,l^=g}return l^=a.length,l^=l>>>16,l=(l&65535)*2246822507+(((l>>>16)*2246822507&65535)<<16)&4294967295,l^=l>>>13,l=(l&65535)*3266489909+(((l>>>16)*3266489909&65535)<<16)&4294967295,l^=l>>>16,l>>>0}var n=i;if(n.v2=t,n.v3=i,typeof Le!="undefined")Le.exports=n;else{var s=r.murmur;n.noConflict=function(){return r.murmur=s,n},r.murmur=n}})()});var Mt=ee(Qe()),Ke=ee(st());import{EventEmitter as Or}from"events";import Kt from"axios";var T;(function(s){s.READY="stream_ready",s.CONNECTED="stream_connected",s.DISCONNECTED="stream_disconnected",s.CHANGED="stream_changed",s.ERROR="stream_error"})(T||(T={}));import D from"axios";import gr from"axios";var b="http://localhost/api/1.0".replace(/\/+$/,"");var ce=class{constructor(e,t=b,i=gr){this.basePath=t;this.axios=i;e&&(this.configuration=e,this.basePath=e.basePath||this.basePath)}},xe=class extends Error{constructor(e,t){super(t);this.field=e;this.name="RequiredError"}};var S="https://example.com",E=function(r,e,t){if(t==null)throw new xe(e,`Required parameter ${e} was null or undefined when calling ${r}.`)};var V=async function(r,e){if(e&&e.accessToken){let t=typeof e.accessToken=="function"?await e.accessToken():await e.accessToken;r.Authorization="Bearer "+t}};var P=function(r,...e){let t=new URLSearchParams(r.search);for(let i of e)for(let n in i)if(Array.isArray(i[n])){t.delete(n);for(let s of i[n])t.append(n,s)}else t.set(n,i[n]);r.search=t.toString()},Se=function(r,e,t){let i=typeof r!="string";return(i&&t&&t.isJsonMime?t.isJsonMime(e.headers["Content-Type"]):i)?JSON.stringify(r!==void 0?r:{}):r||""},I=function(r){return r.pathname+r.search+r.hash},O=function(r,e,t,i){return(n=e,s=t)=>{let a=ue(o({},r.options),{url:((i==null?void 0:i.basePath)||s)+r.url});return n.request(a)}};var j;(function(n){n.Boolean="boolean",n.Int="int",n.String="string",n.Json="json"})(j||(j={}));var fe;(function(t){t.On="on",t.Off="off"})(fe||(fe={}));var ge;(function(e){e.Ffmetrics="FFMETRICS"})(ge||(ge={}));var hr=function(r){return{authenticate:async(e,t={})=>{let i="/client/auth",n=new URL(i,S),s;r&&(s=r.baseOptions);let a=o(o({method:"POST"},s),t),u={},c={};u["Content-Type"]="application/json",P(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),a.data=Se(e,a,r),{url:I(n),options:a}},getAllSegments:async(e,t={})=>{E("getAllSegments","environmentUUID",e);let i="/client/env/{environmentUUID}/target-segments".replace("{environmentUUID}",encodeURIComponent(String(e))),n=new URL(i,S),s;r&&(s=r.baseOptions);let a=o(o({method:"GET"},s),t),u={},c={};await V(u,r),P(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),{url:I(n),options:a}},getEvaluationByIdentifier:async(e,t,i,n={})=>{E("getEvaluationByIdentifier","environmentUUID",e),E("getEvaluationByIdentifier","feature",t),E("getEvaluationByIdentifier","target",i);let s="/client/env/{environmentUUID}/target/{target}/evaluations/{feature}".replace("{environmentUUID}",encodeURIComponent(String(e))).replace("{feature}",encodeURIComponent(String(t))).replace("{target}",encodeURIComponent(String(i))),a=new URL(s,S),u;r&&(u=r.baseOptions);let c=o(o({method:"GET"},u),n),f={},l={};await V(f,r),P(a,l,n.query);let p=u&&u.headers?u.headers:{};return c.headers=o(o(o({},f),p),n.headers),{url:I(a),options:c}},getEvaluations:async(e,t,i={})=>{E("getEvaluations","environmentUUID",e),E("getEvaluations","target",t);let n="/client/env/{environmentUUID}/target/{target}/evaluations".replace("{environmentUUID}",encodeURIComponent(String(e))).replace("{target}",encodeURIComponent(String(t))),s=new URL(n,S),a;r&&(a=r.baseOptions);let u=o(o({method:"GET"},a),i),c={},f={};await V(c,r),P(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),{url:I(s),options:u}},getFeatureConfig:async(e,t={})=>{E("getFeatureConfig","environmentUUID",e);let i="/client/env/{environmentUUID}/feature-configs".replace("{environmentUUID}",encodeURIComponent(String(e))),n=new URL(i,S),s;r&&(s=r.baseOptions);let a=o(o({method:"GET"},s),t),u={},c={};await V(u,r),P(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),{url:I(n),options:a}},getFeatureConfigByIdentifier:async(e,t,i={})=>{E("getFeatureConfigByIdentifier","identifier",e),E("getFeatureConfigByIdentifier","environmentUUID",t);let n="/client/env/{environmentUUID}/feature-configs/{identifier}".replace("{identifier}",encodeURIComponent(String(e))).replace("{environmentUUID}",encodeURIComponent(String(t))),s=new URL(n,S),a;r&&(a=r.baseOptions);let u=o(o({method:"GET"},a),i),c={},f={};await V(c,r),P(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),{url:I(s),options:u}},getSegmentByIdentifier:async(e,t,i={})=>{E("getSegmentByIdentifier","identifier",e),E("getSegmentByIdentifier","environmentUUID",t);let n="/client/env/{environmentUUID}/target-segments/{identifier}".replace("{identifier}",encodeURIComponent(String(e))).replace("{environmentUUID}",encodeURIComponent(String(t))),s=new URL(n,S),a;r&&(a=r.baseOptions);let u=o(o({method:"GET"},a),i),c={},f={};await V(c,r),P(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),{url:I(s),options:u}},stream:async(e,t={})=>{E("stream","aPIKey",e);let i="/stream",n=new URL(i,S),s;r&&(s=r.baseOptions);let a=o(o({method:"GET"},s),t),u={},c={};await V(u,r),e!=null&&(u["API-Key"]=String(e)),P(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),{url:I(n),options:a}}}},L=function(r){let e=hr(r);return{async authenticate(t,i){let n=await e.authenticate(t,i);return O(n,D,b,r)},async getAllSegments(t,i){let n=await e.getAllSegments(t,i);return O(n,D,b,r)},async getEvaluationByIdentifier(t,i,n,s){let a=await e.getEvaluationByIdentifier(t,i,n,s);return O(a,D,b,r)},async getEvaluations(t,i,n){let s=await e.getEvaluations(t,i,n);return O(s,D,b,r)},async getFeatureConfig(t,i){let n=await e.getFeatureConfig(t,i);return O(n,D,b,r)},async getFeatureConfigByIdentifier(t,i,n){let s=await e.getFeatureConfigByIdentifier(t,i,n);return O(s,D,b,r)},async getSegmentByIdentifier(t,i,n){let s=await e.getSegmentByIdentifier(t,i,n);return O(s,D,b,r)},async stream(t,i){let n=await e.stream(t,i);return O(n,D,b,r)}}};var Pe=class extends ce{authenticate(e,t){return L(this.configuration).authenticate(e,t).then(i=>i(this.axios,this.basePath))}getAllSegments(e,t){return L(this.configuration).getAllSegments(e,t).then(i=>i(this.axios,this.basePath))}getEvaluationByIdentifier(e,t,i,n){return L(this.configuration).getEvaluationByIdentifier(e,t,i,n).then(s=>s(this.axios,this.basePath))}getEvaluations(e,t,i){return L(this.configuration).getEvaluations(e,t,i).then(n=>n(this.axios,this.basePath))}getFeatureConfig(e,t){return L(this.configuration).getFeatureConfig(e,t).then(i=>i(this.axios,this.basePath))}getFeatureConfigByIdentifier(e,t,i){return L(this.configuration).getFeatureConfigByIdentifier(e,t,i).then(n=>n(this.axios,this.basePath))}getSegmentByIdentifier(e,t,i){return L(this.configuration).getSegmentByIdentifier(e,t,i).then(n=>n(this.axios,this.basePath))}stream(e,t){return L(this.configuration).stream(e,t).then(i=>i(this.axios,this.basePath))}},pr=function(r){return{postMetrics:async(e,t,i={})=>{E("postMetrics","environment",e);let n="/metrics/{environment}".replace("{environment}",encodeURIComponent(String(e))),s=new URL(n,S),a;r&&(a=r.baseOptions);let u=o(o({method:"POST"},a),i),c={},f={};await V(c,r),c["Content-Type"]="application/json",P(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),u.data=Se(t,u,r),{url:I(s),options:u}}}},mr=function(r){let e=pr(r);return{async postMetrics(t,i,n){let s=await e.postMetrics(t,i,n);return O(s,D,b,r)}}};var Ie=class extends ce{postMetrics(e,t,i){return mr(this.configuration).postMetrics(e,t,i).then(n=>n(this.axios,this.basePath))}};var re=class{constructor(e={}){this.apiKey=e.apiKey,this.username=e.username,this.password=e.password,this.accessToken=e.accessToken,this.basePath=e.basePath,this.baseOptions=e.baseOptions,this.formDataCtor=e.formDataCtor}isJsonMime(e){let t=new RegExp("^(application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(;.*)?$","i");return e!==null&&(t.test(e)||e.toLowerCase()==="application/json-patch+json")}};var he="1.1.0";var dt=ee(_e());var we=class{trace(e,...t){console.trace(e,...t)}debug(e,...t){console.debug(e,...t)}info(e,...t){console.info(e,...t)}warn(e,...t){console.warn(e,...t)}error(e,...t){console.error(e,...t)}};import Tr from"keyv";import{KeyvFile as Ar}from"keyv-file";var me=class{constructor(e={}){this.keyv=new Tr({store:new Ar(e)})}set(e,t){return this.keyv.set(e,t)}get(e){return this.keyv.get(e)}del(e){return this.keyv.delete(e)}};var vt=100;var yt="featureIdentifier",Et="featureName",Tt="variationIdentifier";var At="target",bt="SDK_VERSION",Rt="SDK_TYPE",xt="server",St="SDK_LANGUAGE",Pt="javascript",It="global",Ot="segmentMatch",Ct="in",_t="equal",wt="gt",Vt="starts_with",Dt="ends_with",Ft="contains",Nt="equal_sensitive",br="https://config.ff.harness.io/api/1.0",Rr="https://events.ff.harness.io/api/1.0",xr=1e3,Ut=60*xr,Sr=1*Ut,Pr=1*Ut,A={baseUrl:br,eventsUrl:Rr,pollInterval:Sr,eventsSyncInterval:Pr,enableStream:!0,enableAnalytics:!0,cache:new dt.default({max:100}),store:new me,logger:new we};var C=A.logger,Y;(function(t){t.READY="poller_ready",t.ERROR="poller_error"})(Y||(Y={}));var Ve=class{constructor(e,t,i,n,s,a){this.stopped=!0;this.initialized=!1;this.api=i,this.options=n,this.environment=e,this.cluster=t,this.repository=a,this.eventBus=s}poll(){if(this.stopped)return;let e=new Date().getTime(),t=()=>{let i=new Date().getTime()-e,n=Math.max(this.options.pollInterval-i,0);setTimeout(()=>this.poll(),n)};Promise.all([this.retrieveFlags(),this.retrieveSegments()]).then(()=>{this.initialized||(this.initialized=!0,this.eventBus.emit(Y.READY))}).catch(i=>{this.eventBus.emit(Y.ERROR,{error:i})}).finally(t)}async retrieveFlags(){try{C.debug("Fetching flags started");let e=await this.api.getFeatureConfig(this.environment,{params:{cluster:this.cluster}});C.debug("Fetching flags finished"),e.data.forEach(t=>this.repository.setFlag(t.feature,t))}catch(e){throw C.error("Error loading flags",e),e}}async retrieveSegments(){try{C.debug("Fetching segments started");let e=await this.api.getAllSegments(this.environment,{params:{cluster:this.cluster}});C.debug("Fetching segments finished"),e.data.forEach(t=>this.repository.setSegment(t.identifier,t))}catch(e){throw C.error("Error loading segments",e),e}}start(){if(!this.stopped){C.info("PollingProcessor already started");return}C.info("Starting PollingProcessor with request interval: ",this.options.pollInterval),this.stopped=!1,this.poll()}stop(){C.info("Stopping PollingProcessor"),this.stopped=!0}close(){C.info("Closing PollingProcessor"),this.stop()}};import Ir from"eventsource";var B=A.logger,De=class{constructor(e,t,i,n,s,a,u,c){this.api=e,this.apiKey=t,this.environment=i,this.jwtToken=n,this.options=s,this.cluster=a,this.eventBus=u,this.repository=c}start(){B.info("Starting StreamProcessor");let e=new Ir(`${this.options.baseUrl}/stream?cluster=${this.cluster}`,{headers:{Authorization:`Bearer ${this.jwtToken}`,"API-Key":this.apiKey}});e.onopen=t=>{B.debug("Stream connected",t),this.eventBus.emit(T.CONNECTED)},e.onerror=t=>{B.debug("Stream has issue",t),this.eventBus.emit(T.ERROR,t)},e.addEventListener("*",t=>{let i=JSON.parse(t.data);B.debug("Received event from stream: ",i),i.domain==="flag"?this.msgProcessor(i,this.api.getFeatureConfigByIdentifier.bind(this.api),this.repository.setFlag.bind(this.repository),this.repository.deleteFlag.bind(this.repository)):i.domain==="target-segment"&&this.msgProcessor(i,this.api.getSegmentByIdentifier.bind(this.api),this.repository.setSegment.bind(this.repository),this.repository.deleteSegment.bind(this.repository))}),this.eventSource=e,this.eventBus.emit(T.READY)}async msgProcessor(e,t,i,n){B.info("Processing message",e);try{let a=(await t(e.identifier,this.environment)).data;e.event==="create"||e.event==="patch"?i(e.identifier,a):e.event==="delete"&&n(e.identifier)}catch(s){throw B.error("Error while fetching data with identifier:",e.identifier,s),s}B.info("Processing message finished",e)}connected(){return this.eventSource.readyState==De.CONNECTED}stop(){B.info("Stopping StreamProcessor"),this.eventSource.close(),this.eventBus.emit(T.DISCONNECTED)}close(){this.stop()}},de=De;de.CONNECTED=1;var Fe=class{constructor(e){this.value=e}startsWith(e){return!1}endsWith(e){return!1}match(e){return!1}contains(e){return!1}equalSensitive(e){return!1}equal(e){return this.value===(e[0].toLowerCase()==="true")}greaterThan(e){return!1}greaterThanEqual(e){return!1}lessThan(e){return!1}lessThanEqual(e){return!1}inList(e){return this.value}};var Ne=class{startsWith(e){return!1}endsWith(e){return!1}match(e){return!1}contains(e){return!1}equalSensitive(e){return!1}equal(e){return!1}greaterThan(e){return!1}greaterThanEqual(e){return!1}lessThan(e){return!1}lessThanEqual(e){return!1}inList(e){return!1}};var Ue=class{constructor(e){this.value=e}startsWith(e){return!1}endsWith(e){return!1}match(e){return!1}contains(e){return!1}equalSensitive(e){return!1}equal(e){return this.value===parseFloat(e==null?void 0:e[0])}greaterThan(e){return this.value>parseFloat(e==null?void 0:e[0])}greaterThanEqual(e){return this.value>=parseFloat(e==null?void 0:e[0])}lessThan(e){return this.value<parseFloat(e==null?void 0:e[0])}lessThanEqual(e){return this.value<=parseFloat(e==null?void 0:e[0])}inList(e){return e.map(i=>parseFloat(i)).includes(this.value)}};var qe=class{constructor(e){this.value=e}startsWith(e){return this.value.startsWith(e==null?void 0:e[0])}endsWith(e){return this.value.endsWith(e==null?void 0:e[0])}match(e){return this.value.match(e==null?void 0:e[0])!==void 0}contains(e){return this.value.includes(e==null?void 0:e[0])}equalSensitive(e){return this.value===(e==null?void 0:e[0])}equal(e){var t;return this.value.toLocaleLowerCase()===((t=e==null?void 0:e[0])==null?void 0:t.toLocaleLowerCase())}greaterThan(e){return this.value>(e==null?void 0:e[0])}greaterThanEqual(e){return this.value>=(e==null?void 0:e[0])}lessThan(e){return this.value<(e==null?void 0:e[0])}lessThanEqual(e){return this.value<=(e==null?void 0:e[0])}inList(e){return e.includes(this.value)}};var Lt=ee(qt()),$=A.logger,Be=class{constructor(e){this.query=e}getAttrValue(e,t){var i;return e[t]||((i=e.attributes)==null?void 0:i[t])}findVariation(e,t){return e.find(i=>i.identifier===t)}getNormalizedNumberWithNormalizer(e,t,i){let n=[t,e].join(":");return parseInt((0,Lt.default)(n).toString())%i+1}getNormalizedNumber(e,t){return this.getNormalizedNumberWithNormalizer(e,t,vt)}isEnabled(e,t,i){let n=this.getAttrValue(e,t);if(!n)return!1;let s=this.getNormalizedNumber(n,t);return i>0&&s<=i}evaluateDistribution(e,t){if(!e)return;let i="";for(let n of e.variations)if(i=n.variation,this.isEnabled(t,e.bucketBy,n.weight))return n.variation;return i}getOperator(e,t){let i=this.getAttrValue(e,t);switch(typeof i){case"boolean":return new Fe(i);case"string":return new qe(i);case"number":return new Ue(i);case"object":return new Ne}}convertApiTargetsToEvalTargets(e){return e.map(t=>({identifier:t.identifier,name:t.name,anonymous:t.anonymous,attributes:t.attributes}))}async isTargetIncludedOrExcludedInSegment(e,t){for(let i of e){let n=await this.query.getSegment(i);if(n){if(this.convertApiTargetsToEvalTargets(n.excluded).includes(t))return $.debug(`Target %s excluded from segment %s via exclude list | ||
`,t.name,n.name),!1;if(this.convertApiTargetsToEvalTargets(n.included).includes(t))return $.debug(`Target %s included in segment %s via include list | ||
`,t.name,n.name),!0;if(n.rules&&this.evaluateClauses(n.rules,t))return $.debug(`Target %s included in segment %s via rules | ||
`,t.name,n.name),!0}}return!1}async evaluateClause(e,t){if(!e.op)return!1;let i=this.getOperator(t,e.attribute);switch(e.op){case Ct:return i.inList(e.values);case _t:return i.equal(e.values);case Nt:return i.equalSensitive(e.values);case wt:return i.greaterThan(e.values);case Vt:return i.startsWith(e.values);case Dt:return i.endsWith(e.values);case Ft:return i.contains(e.values);case Ot:return this.isTargetIncludedOrExcludedInSegment(e.values,t)}return!1}async evaluateClauses(e,t){for(let i of e)if(!await this.evaluateClause(i,t))return!1;return!0}evaluateRule(e,t){return this.evaluateClauses(e.clauses,t)}async evaluateRules(e,t){if(!t||!e)return;e.sort((n,s)=>n.priority>s.priority?1:-1);let i;for(let n of e)if(!!await this.evaluateRule(n,t))return n.serve.distribution&&(i=this.evaluateDistribution(n.serve.distribution,t)),n.serve.variation&&(i=n.serve.variation),i}evaluateVariationMap(e,t){var i;if(!(!t||!e))for(let n of e){if((i=n.targets)==null?void 0:i.find(u=>u.identifier===t.identifier))return n.variation;let a=n.targetSegments;if(a&&this.isTargetIncludedOrExcludedInSegment(a,t))return n.variation}}async evaluateFlag(e,t){let i=e.offVariation;return e.state===fe.On&&(i=this.evaluateVariationMap(e.variationToTargetMap,t)||await this.evaluateRules(e.rules,t)||this.evaluateDistribution(e.defaultServe.distribution,t)||e.defaultServe.variation),this.findVariation(e.variations,i)}async checkPreRequisite(e,t){if(e.prerequisites){$.info("Checking pre requisites %s of parent feature %s",e.prerequisites,e.feature);for(let i of e.prerequisites){let n=await this.query.getFlag(i.feature);if(!n)return $.warn("Could not retrieve the pre requisite details of feature flag: %s",e.feature),!0;let s=await this.evaluateFlag(n,t);return $.info("Pre requisite flag %s has variation %s for target %s",n.feature,s,t),$.info("Pre requisite flag %s should have the variations %s",n.feature,i.variations),i.variations.includes(s.identifier)?await this.checkPreRequisite(n,t):!1}}return!0}async evaluate(e,t,i,n){let s=await this.query.getFlag(e);if(!s||s.kind!==i)return;if(s.prerequisites&&!await this.checkPreRequisite(s,t))return this.findVariation(s.variations,s.offVariation);let a=await this.evaluateFlag(s,t);if(a)return n&&n(s,t,a),a}async boolVariation(e,t,i=!1,n){let s=await this.evaluate(e,t,j.Boolean,n);return s?s.value.toLowerCase()==="true":i}async stringVariation(e,t,i="",n){let s=await this.evaluate(e,t,j.String,n);return s?s.value:i}async numberVariation(e,t,i=0,n){let s=await this.evaluate(e,t,j.Int,n);return s?parseFloat(s.value):i}async jsonVariation(e,t,i={},n){let s=await this.evaluate(e,t,j.Json,n);return s?JSON.parse(s.value):i}};var Me=class{constructor(e,t){if(!e)throw new Error("Cache is required argument and cannot be undefined");this.cache=e,this.store=t}async setFlag(e,t){let i=this.formatFlagKey(e);await this.isFlagOutdated(i,t)||(this.store?(await this.store.set(i,t),this.cache.del(i)):this.cache.set(i,t))}async setSegment(e,t){let i=this.formatSegmentKey(e);await this.isSegmentOutdated(i,t)||(this.store?(await this.store.set(i,t),this.cache.del(i)):this.cache.set(i,t))}async deleteFlag(e){let t=this.formatFlagKey(e);this.store&&await this.store.del(t),this.cache.del(t)}async deleteSegment(e){let t=this.formatSegmentKey(e);this.store&&await this.store.del(t),this.cache.del(t)}async getFlag(e,t=!0){let i=this.formatFlagKey(e),n=this.cache.get(i);if(n)return n;if(this.store)return n=await this.store.get(i),n&&t&&this.cache.set(i,n),n}async getSegment(e,t=!0){let i=this.formatSegmentKey(e),n=this.cache.get(i);if(n)return n;if(this.store)return n=await this.store.get(i),n&&t&&this.cache.set(i,n),n}async isFlagOutdated(e,t){let i=await this.getFlag(e,!1);return(i==null?void 0:i.version)&&i.version>(t==null?void 0:t.version)}async isSegmentOutdated(e,t){let i=await this.getSegment(e,!1);return(i==null?void 0:i.version)&&i.version>(t==null?void 0:t.version)}formatFlagKey(e){return`flags/${e}`}formatSegmentKey(e){return`segments/${e}`}};var W=A.logger,X;(function(t){t.READY="metrics_ready",t.ERROR="metrics_error"})(X||(X={}));var Bt=(r,e="1",t,i,n)=>{let s=new Map,a,u=new re(ue(o({},t),{basePath:i.eventsUrl})),c=new Ie(u),f=(y,g,v)=>{let m={target:y,featureConfig:g,variation:v,count:0},Z=l(m),ae=s.get(Z);ae?ae.count++:(m.count=1,s.set(Z,m))},l=y=>{let g=y.featureConfig.feature,v=y.variation.identifier,m=y.variation.value;return`${g}/${v}/${m}/${It}`},p=()=>{if(!s){W.debug("No metrics data!");return}let y=[],g=[],v=new Map(s);s.clear();for(let m of v.values()){if(m.target&&!m.target.anonymous){let ke=[];m.target.attributes&&(ke=Object.entries(m.target.attributes).map(([jt,Gt])=>({key:jt,value:Gt})));let je=m.target.identifier;m.target.name&&(je=m.target.name);let kt={identifier:m.target.identifier,name:je,attributes:ke};y.push(kt)}let Z=[{key:yt,value:m.featureConfig.feature},{key:Et,value:m.featureConfig.feature},{key:Tt,value:m.variation.identifier},{key:Rt,value:xt},{key:St,value:Pt},{key:bt,value:he},{key:At,value:m.target.identifier}],ae={timestamp:Date.now(),count:m.count,metricsType:ge.Ffmetrics,attributes:Z};g.push(ae)}return{targetData:y,metricsData:g}},x=()=>{let y=p();y&&(W.debug("Start sending metrics data"),c.postMetrics(r,y,{params:{cluster:e}}).then(g=>{W.debug("Metrics server returns: ",g.status),g.status>=400&&W.error("Error while sending metrics data with status code: ",g.status)}).catch(g=>{W.debug("Metrics server returns error: ",g)}))};return{start:()=>{W.info("Starting MetricsProcessor with request interval: ",i.eventsSyncInterval),a=setInterval(x,i.eventsSyncInterval),n.emit(X.READY)},close:()=>{W.info("Closing MetricsProcessor"),clearInterval(a),x()},enqueue:f}};Kt.defaults.timeout=3e4;(0,Ke.default)(Kt,{retries:3,retryDelay:Ke.default.exponentialDelay});var se=A.logger,M;(function(i){i[i.POLL=0]="POLL",i[i.STREAM=1]="STREAM",i[i.METRICS=2]="METRICS"})(M||(M={}));var U;(function(i){i.READY="ready",i.FAILED="failed",i.CHANGED="changed"})(U||(U={}));var ve=class{constructor(e,t={}){this.cluster="1";this.eventBus=new Or;this.initialized=!1;this.failure=!1;this.pollerReady=!1;this.streamReady=!1;this.metricReady=!1;this.sdkKey=e,t.pollInterval<1e3&&(t.pollInterval=A.pollInterval,se.warn("Polling interval cannot be lower than 1000 ms")),this.options=o(o({},A),t),this.configuration=new re({basePath:this.options.baseUrl,baseOptions:{headers:{"User-Agent":`NodeJsSDK/${he}`}}}),this.repository=new Me(this.options.cache,this.options.store),this.evaluator=new Be(this.repository),this.api=new Pe(this.configuration),this.processEvents(),this.run()}processEvents(){this.eventBus.on(Y.READY,()=>{this.initialize(0)}),this.eventBus.on(Y.ERROR,()=>{this.failure=!0,this.eventBus.emit(U.FAILED)}),this.eventBus.on(T.READY,()=>{this.initialize(1)}),this.eventBus.on(T.ERROR,()=>{this.failure=!0,this.eventBus.emit(U.FAILED)}),this.eventBus.on(X.READY,()=>{this.initialize(2)}),this.eventBus.on(X.ERROR,()=>{this.failure=!0,this.eventBus.emit(U.FAILED)}),this.eventBus.on(T.CONNECTED,()=>{this.pollProcessor.stop()}),this.eventBus.on(T.DISCONNECTED,()=>{this.pollProcessor.start()})}async authenticate(){try{let e=await this.api.authenticate({apiKey:this.sdkKey});this.authToken=e.data.authToken,this.configuration.accessToken=this.authToken;let t=(0,Mt.default)(this.authToken);this.environment=t.environment,this.cluster=t.clusterIdentifier||"1"}catch(e){this.failure=!0,console.error("Error while authenticating, err: ",e)}}waitForInitialization(){return this.waitForInitialize?this.waitForInitialize:(this.initialized?this.waitForInitialize=Promise.resolve(this):this.failure?this.waitForInitialize=Promise.reject(this.failure):this.waitForInitialize=new Promise((e,t)=>{this.eventBus.once(U.READY,()=>{e(this)}),this.eventBus.once(U.FAILED,t)}),this.waitForInitialize)}initialize(e){switch(e){case 0:this.pollerReady=!0,se.debug("PollingProcessor ready");break;case 1:this.streamReady=!0,se.debug("StreamingProcessor ready");break;case 2:this.metricReady=!0,se.debug("MetricsProcessor ready");break}this.options.enableStream&&!this.streamReady||this.options.enableAnalytics&&!this.metricReady||!this.pollerReady||(this.initialized=!0,this.eventBus.emit(U.READY))}async run(){await this.authenticate(),this.pollProcessor=new Ve(this.environment,this.cluster,this.api,this.options,this.eventBus,this.repository),this.pollProcessor.start(),this.options.enableStream&&(this.streamProcessor=new de(this.api,this.sdkKey,this.environment,this.authToken,this.options,this.cluster,this.eventBus,this.repository),this.streamProcessor.start()),this.options.enableAnalytics&&(this.metricsProcessor=Bt(this.environment,this.cluster,this.configuration,this.options,this.eventBus),this.metricsProcessor.start()),se.info("finished setting up processors")}boolVariation(e,t,i=!1){return this.evaluator.boolVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}stringVariation(e,t,i=""){return this.evaluator.stringVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}numberVariation(e,t,i=0){return this.evaluator.numberVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}jsonVariation(e,t,i={}){return this.evaluator.jsonVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}close(){this.pollProcessor.close(),this.streamProcessor&&this.streamProcessor.close(),this.metricsProcessor&&this.metricsProcessor.close()}};var Cr=ee(_e());var _n={instance:void 0,init:function(r,e){this.instance||(this.instance=new ve(r,e))},waitForInitialization:function(){return this.instance.waitForInitialization()},boolVariation:function(r,e,t=!1){return this.instance.boolVariation(r,e,t)},stringVariation:function(r,e,t=""){return this.instance.stringVariation(r,e,t)},numberVariation:function(r,e,t=0){return this.instance.numberVariation(r,e,t)},jsonVariation:function(r,e,t=""){return this.instance.jsonVariation(r,e,t)},close:function(){return this.instance.close()}};var export_LRU=Cr.default;export{ve as Client,U as ClientEvent,me as FileStore,export_LRU as LRU,_n as default}; | ||
var Yt=Object.create;var oe=Object.defineProperty,$t=Object.defineProperties,Wt=Object.getOwnPropertyDescriptor,Qt=Object.getOwnPropertyDescriptors,Jt=Object.getOwnPropertyNames,Ge=Object.getOwnPropertySymbols,Xt=Object.getPrototypeOf,He=Object.prototype.hasOwnProperty,Zt=Object.prototype.propertyIsEnumerable;var ze=(r,e,t)=>e in r?oe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,o=(r,e)=>{for(var t in e||(e={}))He.call(e,t)&&ze(r,t,e[t]);if(Ge)for(var t of Ge(e))Zt.call(e,t)&&ze(r,t,e[t]);return r},ue=(r,e)=>$t(r,Qt(e)),er=r=>oe(r,"__esModule",{value:!0});var L=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var tr=(r,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Jt(e))!He.call(r,i)&&i!=="default"&&oe(r,i,{get:()=>e[i],enumerable:!(t=Wt(e,i))||t.enumerable});return r},te=r=>tr(er(oe(r!=null?Yt(Xt(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var Qe=L((Dr,We)=>{"use strict";function ye(r){this.message=r}ye.prototype=new Error,ye.prototype.name="InvalidCharacterError";var Ye=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(r){var e=String(r).replace(/=+$/,"");if(e.length%4==1)throw new ye("'atob' failed: The string to be decoded is not correctly encoded.");for(var t,i,n=0,s=0,a="";i=e.charAt(s++);~i&&(t=n%4?64*t+i:i,n++%4)?a+=String.fromCharCode(255&t>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return a};function rr(r){var e=r.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(Ye(t).replace(/(.)/g,function(i,n){var s=n.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch(t){return Ye(e)}}function re(r){this.message=r}function $e(r,e){if(typeof r!="string")throw new re("Invalid token specified");var t=(e=e||{}).header===!0?0:1;try{return JSON.parse(rr(r.split(".")[t]))}catch(i){throw new re("Invalid token specified: "+i.message)}}re.prototype=new Error,re.prototype.name="InvalidTokenError";var Ee=$e;Ee.default=$e,Ee.InvalidTokenError=re,We.exports=Ee});var Xe=L((Nr,Je)=>{"use strict";var ir=["ETIMEDOUT","ECONNRESET","EADDRINUSE","ESOCKETTIMEDOUT","ECONNREFUSED","EPIPE","EHOSTUNREACH","EAI_AGAIN"],nr=["ENOTFOUND","ENETUNREACH","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_CRL","UNABLE_TO_DECRYPT_CERT_SIGNATURE","UNABLE_TO_DECRYPT_CRL_SIGNATURE","UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY","CERT_SIGNATURE_FAILURE","CRL_SIGNATURE_FAILURE","CERT_NOT_YET_VALID","CERT_HAS_EXPIRED","CRL_NOT_YET_VALID","CRL_HAS_EXPIRED","ERROR_IN_CERT_NOT_BEFORE_FIELD","ERROR_IN_CERT_NOT_AFTER_FIELD","ERROR_IN_CRL_LAST_UPDATE_FIELD","ERROR_IN_CRL_NEXT_UPDATE_FIELD","OUT_OF_MEM","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_CHAIN_TOO_LONG","CERT_REVOKED","INVALID_CA","PATH_LENGTH_EXCEEDED","INVALID_PURPOSE","CERT_UNTRUSTED","CERT_REJECTED"];Je.exports=function(r){return!r||!r.code||ir.indexOf(r.code)!==-1?!0:nr.indexOf(r.code)===-1}});var it=L(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});var sr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r};w.isNetworkError=Ae;w.isRetryableError=le;w.isSafeRequestError=et;w.isIdempotentRequestError=be;w.isNetworkOrIdempotentRequestError=Re;w.exponentialDelay=tt;w.default=j;var ar=Xe(),or=ur(ar);function ur(r){return r&&r.__esModule?r:{default:r}}var Te="axios-retry";function Ae(r){return!r.response&&Boolean(r.code)&&r.code!=="ECONNABORTED"&&(0,or.default)(r)}var Ze=["get","head","options"],lr=Ze.concat(["put","delete"]);function le(r){return r.code!=="ECONNABORTED"&&(!r.response||r.response.status>=500&&r.response.status<=599)}function et(r){return r.config?le(r)&&Ze.indexOf(r.config.method)!==-1:!1}function be(r){return r.config?le(r)&&lr.indexOf(r.config.method)!==-1:!1}function Re(r){return Ae(r)||be(r)}function cr(){return 0}function tt(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=Math.pow(2,r)*100,t=e*.2*Math.random();return e+t}function rt(r){var e=r[Te]||{};return e.retryCount=e.retryCount||0,r[Te]=e,e}function fr(r,e){return Object.assign({},e,r[Te])}function gr(r,e){r.defaults.agent===e.agent&&delete e.agent,r.defaults.httpAgent===e.httpAgent&&delete e.httpAgent,r.defaults.httpsAgent===e.httpsAgent&&delete e.httpsAgent}async function hr(r,e,t,i){var n=t.retryCount<r&&e(i);if((typeof n=="undefined"?"undefined":sr(n))==="object")try{return await n,!0}catch(s){return!1}return n}function j(r,e){r.interceptors.request.use(function(t){var i=rt(t);return i.lastRequestTime=Date.now(),t}),r.interceptors.response.use(null,async function(t){var i=t.config;if(!i)return Promise.reject(t);var n=fr(i,e),s=n.retries,a=s===void 0?3:s,u=n.retryCondition,c=u===void 0?Re:u,f=n.retryDelay,l=f===void 0?cr:f,p=n.shouldResetTimeout,x=p===void 0?!1:p,k=rt(i);if(await hr(a,c,k,t)){k.retryCount+=1;var _=l(k.retryCount,t);if(gr(r,i),!x&&i.timeout&&k.lastRequestTime){var y=Date.now()-k.lastRequestTime;i.timeout=Math.max(i.timeout-y-_,1)}return i.transformRequest=[function(g){return g}],new Promise(function(g){return setTimeout(function(){return g(r(i))},_)})}return Promise.reject(t)})}j.isNetworkError=Ae;j.isSafeRequestError=et;j.isIdempotentRequestError=be;j.isNetworkOrIdempotentRequestError=Re;j.exponentialDelay=tt;j.isRetryableError=le});var st=L((Ur,nt)=>{nt.exports=it().default});var ot=L((ui,at)=>{"use strict";at.exports=function(r){r.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}});var lt=L((li,ut)=>{"use strict";ut.exports=h;h.Node=H;h.create=h;function h(r){var e=this;if(e instanceof h||(e=new h),e.tail=null,e.head=null,e.length=0,r&&typeof r.forEach=="function")r.forEach(function(n){e.push(n)});else if(arguments.length>0)for(var t=0,i=arguments.length;t<i;t++)e.push(arguments[t]);return e}h.prototype.removeNode=function(r){if(r.list!==this)throw new Error("removing node which does not belong to this list");var e=r.next,t=r.prev;return e&&(e.prev=t),t&&(t.next=e),r===this.head&&(this.head=e),r===this.tail&&(this.tail=t),r.list.length--,r.next=null,r.prev=null,r.list=null,e};h.prototype.unshiftNode=function(r){if(r!==this.head){r.list&&r.list.removeNode(r);var e=this.head;r.list=this,r.next=e,e&&(e.prev=r),this.head=r,this.tail||(this.tail=r),this.length++}};h.prototype.pushNode=function(r){if(r!==this.tail){r.list&&r.list.removeNode(r);var e=this.tail;r.list=this,r.prev=e,e&&(e.next=r),this.tail=r,this.head||(this.head=r),this.length++}};h.prototype.push=function(){for(var r=0,e=arguments.length;r<e;r++)Er(this,arguments[r]);return this.length};h.prototype.unshift=function(){for(var r=0,e=arguments.length;r<e;r++)Tr(this,arguments[r]);return this.length};h.prototype.pop=function(){if(!!this.tail){var r=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,r}};h.prototype.shift=function(){if(!!this.head){var r=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,r}};h.prototype.forEach=function(r,e){e=e||this;for(var t=this.head,i=0;t!==null;i++)r.call(e,t.value,i,this),t=t.next};h.prototype.forEachReverse=function(r,e){e=e||this;for(var t=this.tail,i=this.length-1;t!==null;i--)r.call(e,t.value,i,this),t=t.prev};h.prototype.get=function(r){for(var e=0,t=this.head;t!==null&&e<r;e++)t=t.next;if(e===r&&t!==null)return t.value};h.prototype.getReverse=function(r){for(var e=0,t=this.tail;t!==null&&e<r;e++)t=t.prev;if(e===r&&t!==null)return t.value};h.prototype.map=function(r,e){e=e||this;for(var t=new h,i=this.head;i!==null;)t.push(r.call(e,i.value,this)),i=i.next;return t};h.prototype.mapReverse=function(r,e){e=e||this;for(var t=new h,i=this.tail;i!==null;)t.push(r.call(e,i.value,this)),i=i.prev;return t};h.prototype.reduce=function(r,e){var t,i=this.head;if(arguments.length>1)t=e;else if(this.head)i=this.head.next,t=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=0;i!==null;n++)t=r(t,i.value,n),i=i.next;return t};h.prototype.reduceReverse=function(r,e){var t,i=this.tail;if(arguments.length>1)t=e;else if(this.tail)i=this.tail.prev,t=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=this.length-1;i!==null;n--)t=r(t,i.value,n),i=i.prev;return t};h.prototype.toArray=function(){for(var r=new Array(this.length),e=0,t=this.head;t!==null;e++)r[e]=t.value,t=t.next;return r};h.prototype.toArrayReverse=function(){for(var r=new Array(this.length),e=0,t=this.tail;t!==null;e++)r[e]=t.value,t=t.prev;return r};h.prototype.slice=function(r,e){e=e||this.length,e<0&&(e+=this.length),r=r||0,r<0&&(r+=this.length);var t=new h;if(e<r||e<0)return t;r<0&&(r=0),e>this.length&&(e=this.length);for(var i=0,n=this.head;n!==null&&i<r;i++)n=n.next;for(;n!==null&&i<e;i++,n=n.next)t.push(n.value);return t};h.prototype.sliceReverse=function(r,e){e=e||this.length,e<0&&(e+=this.length),r=r||0,r<0&&(r+=this.length);var t=new h;if(e<r||e<0)return t;r<0&&(r=0),e>this.length&&(e=this.length);for(var i=this.length,n=this.tail;n!==null&&i>e;i--)n=n.prev;for(;n!==null&&i>r;i--,n=n.prev)t.push(n.value);return t};h.prototype.splice=function(r,e,...t){r>this.length&&(r=this.length-1),r<0&&(r=this.length+r);for(var i=0,n=this.head;n!==null&&i<r;i++)n=n.next;for(var s=[],i=0;n&&i<e;i++)s.push(n.value),n=this.removeNode(n);n===null&&(n=this.tail),n!==this.head&&n!==this.tail&&(n=n.prev);for(var i=0;i<t.length;i++)n=yr(this,n,t[i]);return s};h.prototype.reverse=function(){for(var r=this.head,e=this.tail,t=r;t!==null;t=t.prev){var i=t.prev;t.prev=t.next,t.next=i}return this.head=e,this.tail=r,this};function yr(r,e,t){var i=e===r.head?new H(t,null,e,r):new H(t,e,e.next,r);return i.next===null&&(r.tail=i),i.prev===null&&(r.head=i),r.length++,i}function Er(r,e){r.tail=new H(e,r.tail,null,r),r.head||(r.head=r.tail),r.length++}function Tr(r,e){r.head=new H(e,null,r.head,r),r.tail||(r.tail=r.head),r.length++}function H(r,e,t,i){if(!(this instanceof H))return new H(r,e,t,i);this.list=i,this.value=r,e?(e.next=this,this.prev=e):this.prev=null,t?(t.prev=this,this.next=t):this.next=null}try{ot()(h)}catch(r){}});var _e=L((ci,mt)=>{"use strict";var Ar=lt(),z=Symbol("max"),N=Symbol("length"),X=Symbol("lengthCalculator"),ne=Symbol("allowStale"),Y=Symbol("maxAge"),F=Symbol("dispose"),ct=Symbol("noDisposeOnSet"),d=Symbol("lruList"),R=Symbol("cache"),ft=Symbol("updateAgeOnGet"),Oe=()=>1,gt=class{constructor(e){if(typeof e=="number"&&(e={max:e}),e||(e={}),e.max&&(typeof e.max!="number"||e.max<0))throw new TypeError("max must be a non-negative number");let t=this[z]=e.max||1/0,i=e.length||Oe;if(this[X]=typeof i!="function"?Oe:i,this[ne]=e.stale||!1,e.maxAge&&typeof e.maxAge!="number")throw new TypeError("maxAge must be a number");this[Y]=e.maxAge||0,this[F]=e.dispose,this[ct]=e.noDisposeOnSet||!1,this[ft]=e.updateAgeOnGet||!1,this.reset()}set max(e){if(typeof e!="number"||e<0)throw new TypeError("max must be a non-negative number");this[z]=e||1/0,se(this)}get max(){return this[z]}set allowStale(e){this[ne]=!!e}get allowStale(){return this[ne]}set maxAge(e){if(typeof e!="number")throw new TypeError("maxAge must be a non-negative number");this[Y]=e,se(this)}get maxAge(){return this[Y]}set lengthCalculator(e){typeof e!="function"&&(e=Oe),e!==this[X]&&(this[X]=e,this[N]=0,this[d].forEach(t=>{t.length=this[X](t.value,t.key),this[N]+=t.length})),se(this)}get lengthCalculator(){return this[X]}get length(){return this[N]}get itemCount(){return this[d].length}rforEach(e,t){t=t||this;for(let i=this[d].tail;i!==null;){let n=i.prev;pt(this,e,i,t),i=n}}forEach(e,t){t=t||this;for(let i=this[d].head;i!==null;){let n=i.next;pt(this,e,i,t),i=n}}keys(){return this[d].toArray().map(e=>e.key)}values(){return this[d].toArray().map(e=>e.value)}reset(){this[F]&&this[d]&&this[d].length&&this[d].forEach(e=>this[F](e.key,e.value)),this[R]=new Map,this[d]=new Ar,this[N]=0}dump(){return this[d].map(e=>pe(this,e)?!1:{k:e.key,v:e.value,e:e.now+(e.maxAge||0)}).toArray().filter(e=>e)}dumpLru(){return this[d]}set(e,t,i){if(i=i||this[Y],i&&typeof i!="number")throw new TypeError("maxAge must be a number");let n=i?Date.now():0,s=this[X](t,e);if(this[R].has(e)){if(s>this[z])return Z(this,this[R].get(e)),!1;let c=this[R].get(e).value;return this[F]&&(this[ct]||this[F](e,c.value)),c.now=n,c.maxAge=i,c.value=t,this[N]+=s-c.length,c.length=s,this.get(e),se(this),!0}let a=new ht(e,t,s,n,i);return a.length>this[z]?(this[F]&&this[F](e,t),!1):(this[N]+=a.length,this[d].unshift(a),this[R].set(e,this[d].head),se(this),!0)}has(e){if(!this[R].has(e))return!1;let t=this[R].get(e).value;return!pe(this,t)}get(e){return Ce(this,e,!0)}peek(e){return Ce(this,e,!1)}pop(){let e=this[d].tail;return e?(Z(this,e),e.value):null}del(e){Z(this,this[R].get(e))}load(e){this.reset();let t=Date.now();for(let i=e.length-1;i>=0;i--){let n=e[i],s=n.e||0;if(s===0)this.set(n.k,n.v);else{let a=s-t;a>0&&this.set(n.k,n.v,a)}}}prune(){this[R].forEach((e,t)=>Ce(this,t,!1))}},Ce=(r,e,t)=>{let i=r[R].get(e);if(i){let n=i.value;if(pe(r,n)){if(Z(r,i),!r[ne])return}else t&&(r[ft]&&(i.value.now=Date.now()),r[d].unshiftNode(i));return n.value}},pe=(r,e)=>{if(!e||!e.maxAge&&!r[Y])return!1;let t=Date.now()-e.now;return e.maxAge?t>e.maxAge:r[Y]&&t>r[Y]},se=r=>{if(r[N]>r[z])for(let e=r[d].tail;r[N]>r[z]&&e!==null;){let t=e.prev;Z(r,e),e=t}},Z=(r,e)=>{if(e){let t=e.value;r[F]&&r[F](t.key,t.value),r[N]-=t.length,r[R].delete(t.key),r[d].removeNode(e)}},ht=class{constructor(e,t,i,n,s){this.key=e,this.value=t,this.length=i,this.now=n,this.maxAge=s||0}},pt=(r,e,t,i)=>{let n=t.value;pe(r,n)&&(Z(r,t),r[ne]||(n=void 0)),n&&e.call(i,n.value,n.key,r)};mt.exports=gt});var qt=L((_i,Le)=>{(function(){var r=this;let e=a=>new TextEncoder().encode(a);function t(a,u){typeof a=="string"&&(a=e(a));for(var c=a.length,f=u^c,l=0,p;c>=4;)p=a[l]&255|(a[++l]&255)<<8|(a[++l]&255)<<16|(a[++l]&255)<<24,p=(p&65535)*1540483477+(((p>>>16)*1540483477&65535)<<16),p^=p>>>24,p=(p&65535)*1540483477+(((p>>>16)*1540483477&65535)<<16),f=(f&65535)*1540483477+(((f>>>16)*1540483477&65535)<<16)^p,c-=4,++l;switch(c){case 3:f^=(a[l+2]&255)<<16;case 2:f^=(a[l+1]&255)<<8;case 1:f^=a[l]&255,f=(f&65535)*1540483477+(((f>>>16)*1540483477&65535)<<16)}return f^=f>>>13,f=(f&65535)*1540483477+(((f>>>16)*1540483477&65535)<<16),f^=f>>>15,f>>>0}function i(a,u){typeof a=="string"&&(a=e(a));var c,f,l,p,x,k,_,y,g,v;for(c=a.length&3,f=a.length-c,l=u,x=3432918353,_=461845907,v=0;v<f;)g=a[v]&255|(a[++v]&255)<<8|(a[++v]&255)<<16|(a[++v]&255)<<24,++v,g=(g&65535)*x+(((g>>>16)*x&65535)<<16)&4294967295,g=g<<15|g>>>17,g=(g&65535)*_+(((g>>>16)*_&65535)<<16)&4294967295,l^=g,l=l<<13|l>>>19,p=(l&65535)*5+(((l>>>16)*5&65535)<<16)&4294967295,l=(p&65535)+27492+(((p>>>16)+58964&65535)<<16);switch(g=0,c){case 3:g^=(a[v+2]&255)<<16;case 2:g^=(a[v+1]&255)<<8;case 1:g^=a[v]&255,g=(g&65535)*x+(((g>>>16)*x&65535)<<16)&4294967295,g=g<<15|g>>>17,g=(g&65535)*_+(((g>>>16)*_&65535)<<16)&4294967295,l^=g}return l^=a.length,l^=l>>>16,l=(l&65535)*2246822507+(((l>>>16)*2246822507&65535)<<16)&4294967295,l^=l>>>13,l=(l&65535)*3266489909+(((l>>>16)*3266489909&65535)<<16)&4294967295,l^=l>>>16,l>>>0}var n=i;if(n.v2=t,n.v3=i,typeof Le!="undefined")Le.exports=n;else{var s=r.murmur;n.noConflict=function(){return r.murmur=s,n},r.murmur=n}})()});var Mt=te(Qe()),Ke=te(st());import{EventEmitter as _r}from"events";import Kt from"axios";var T;(function(s){s.READY="stream_ready",s.CONNECTED="stream_connected",s.DISCONNECTED="stream_disconnected",s.CHANGED="stream_changed",s.ERROR="stream_error"})(T||(T={}));import D from"axios";import pr from"axios";var b="http://localhost/api/1.0".replace(/\/+$/,"");var ce=class{constructor(e,t=b,i=pr){this.basePath=t;this.axios=i;e&&(this.configuration=e,this.basePath=e.basePath||this.basePath)}},xe=class extends Error{constructor(e,t){super(t);this.field=e;this.name="RequiredError"}};var S="https://example.com",E=function(r,e,t){if(t==null)throw new xe(e,`Required parameter ${e} was null or undefined when calling ${r}.`)};var V=async function(r,e){if(e&&e.accessToken){let t=typeof e.accessToken=="function"?await e.accessToken():await e.accessToken;r.Authorization="Bearer "+t}};var P=function(r,...e){let t=new URLSearchParams(r.search);for(let i of e)for(let n in i)if(Array.isArray(i[n])){t.delete(n);for(let s of i[n])t.append(n,s)}else t.set(n,i[n]);r.search=t.toString()},Se=function(r,e,t){let i=typeof r!="string";return(i&&t&&t.isJsonMime?t.isJsonMime(e.headers["Content-Type"]):i)?JSON.stringify(r!==void 0?r:{}):r||""},I=function(r){return r.pathname+r.search+r.hash},O=function(r,e,t,i){return(n=e,s=t)=>{let a=ue(o({},r.options),{url:((i==null?void 0:i.basePath)||s)+r.url});return n.request(a)}};var G;(function(n){n.Boolean="boolean",n.Int="int",n.String="string",n.Json="json"})(G||(G={}));var fe;(function(t){t.On="on",t.Off="off"})(fe||(fe={}));var ge;(function(e){e.Ffmetrics="FFMETRICS"})(ge||(ge={}));var mr=function(r){return{authenticate:async(e,t={})=>{let i="/client/auth",n=new URL(i,S),s;r&&(s=r.baseOptions);let a=o(o({method:"POST"},s),t),u={},c={};u["Content-Type"]="application/json",P(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),a.data=Se(e,a,r),{url:I(n),options:a}},getAllSegments:async(e,t={})=>{E("getAllSegments","environmentUUID",e);let i="/client/env/{environmentUUID}/target-segments".replace("{environmentUUID}",encodeURIComponent(String(e))),n=new URL(i,S),s;r&&(s=r.baseOptions);let a=o(o({method:"GET"},s),t),u={},c={};await V(u,r),P(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),{url:I(n),options:a}},getEvaluationByIdentifier:async(e,t,i,n={})=>{E("getEvaluationByIdentifier","environmentUUID",e),E("getEvaluationByIdentifier","feature",t),E("getEvaluationByIdentifier","target",i);let s="/client/env/{environmentUUID}/target/{target}/evaluations/{feature}".replace("{environmentUUID}",encodeURIComponent(String(e))).replace("{feature}",encodeURIComponent(String(t))).replace("{target}",encodeURIComponent(String(i))),a=new URL(s,S),u;r&&(u=r.baseOptions);let c=o(o({method:"GET"},u),n),f={},l={};await V(f,r),P(a,l,n.query);let p=u&&u.headers?u.headers:{};return c.headers=o(o(o({},f),p),n.headers),{url:I(a),options:c}},getEvaluations:async(e,t,i={})=>{E("getEvaluations","environmentUUID",e),E("getEvaluations","target",t);let n="/client/env/{environmentUUID}/target/{target}/evaluations".replace("{environmentUUID}",encodeURIComponent(String(e))).replace("{target}",encodeURIComponent(String(t))),s=new URL(n,S),a;r&&(a=r.baseOptions);let u=o(o({method:"GET"},a),i),c={},f={};await V(c,r),P(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),{url:I(s),options:u}},getFeatureConfig:async(e,t={})=>{E("getFeatureConfig","environmentUUID",e);let i="/client/env/{environmentUUID}/feature-configs".replace("{environmentUUID}",encodeURIComponent(String(e))),n=new URL(i,S),s;r&&(s=r.baseOptions);let a=o(o({method:"GET"},s),t),u={},c={};await V(u,r),P(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),{url:I(n),options:a}},getFeatureConfigByIdentifier:async(e,t,i={})=>{E("getFeatureConfigByIdentifier","identifier",e),E("getFeatureConfigByIdentifier","environmentUUID",t);let n="/client/env/{environmentUUID}/feature-configs/{identifier}".replace("{identifier}",encodeURIComponent(String(e))).replace("{environmentUUID}",encodeURIComponent(String(t))),s=new URL(n,S),a;r&&(a=r.baseOptions);let u=o(o({method:"GET"},a),i),c={},f={};await V(c,r),P(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),{url:I(s),options:u}},getSegmentByIdentifier:async(e,t,i={})=>{E("getSegmentByIdentifier","identifier",e),E("getSegmentByIdentifier","environmentUUID",t);let n="/client/env/{environmentUUID}/target-segments/{identifier}".replace("{identifier}",encodeURIComponent(String(e))).replace("{environmentUUID}",encodeURIComponent(String(t))),s=new URL(n,S),a;r&&(a=r.baseOptions);let u=o(o({method:"GET"},a),i),c={},f={};await V(c,r),P(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),{url:I(s),options:u}},stream:async(e,t={})=>{E("stream","aPIKey",e);let i="/stream",n=new URL(i,S),s;r&&(s=r.baseOptions);let a=o(o({method:"GET"},s),t),u={},c={};await V(u,r),e!=null&&(u["API-Key"]=String(e)),P(n,c,t.query);let f=s&&s.headers?s.headers:{};return a.headers=o(o(o({},u),f),t.headers),{url:I(n),options:a}}}},B=function(r){let e=mr(r);return{async authenticate(t,i){let n=await e.authenticate(t,i);return O(n,D,b,r)},async getAllSegments(t,i){let n=await e.getAllSegments(t,i);return O(n,D,b,r)},async getEvaluationByIdentifier(t,i,n,s){let a=await e.getEvaluationByIdentifier(t,i,n,s);return O(a,D,b,r)},async getEvaluations(t,i,n){let s=await e.getEvaluations(t,i,n);return O(s,D,b,r)},async getFeatureConfig(t,i){let n=await e.getFeatureConfig(t,i);return O(n,D,b,r)},async getFeatureConfigByIdentifier(t,i,n){let s=await e.getFeatureConfigByIdentifier(t,i,n);return O(s,D,b,r)},async getSegmentByIdentifier(t,i,n){let s=await e.getSegmentByIdentifier(t,i,n);return O(s,D,b,r)},async stream(t,i){let n=await e.stream(t,i);return O(n,D,b,r)}}};var Pe=class extends ce{authenticate(e,t){return B(this.configuration).authenticate(e,t).then(i=>i(this.axios,this.basePath))}getAllSegments(e,t){return B(this.configuration).getAllSegments(e,t).then(i=>i(this.axios,this.basePath))}getEvaluationByIdentifier(e,t,i,n){return B(this.configuration).getEvaluationByIdentifier(e,t,i,n).then(s=>s(this.axios,this.basePath))}getEvaluations(e,t,i){return B(this.configuration).getEvaluations(e,t,i).then(n=>n(this.axios,this.basePath))}getFeatureConfig(e,t){return B(this.configuration).getFeatureConfig(e,t).then(i=>i(this.axios,this.basePath))}getFeatureConfigByIdentifier(e,t,i){return B(this.configuration).getFeatureConfigByIdentifier(e,t,i).then(n=>n(this.axios,this.basePath))}getSegmentByIdentifier(e,t,i){return B(this.configuration).getSegmentByIdentifier(e,t,i).then(n=>n(this.axios,this.basePath))}stream(e,t){return B(this.configuration).stream(e,t).then(i=>i(this.axios,this.basePath))}},dr=function(r){return{postMetrics:async(e,t,i={})=>{E("postMetrics","environment",e);let n="/metrics/{environment}".replace("{environment}",encodeURIComponent(String(e))),s=new URL(n,S),a;r&&(a=r.baseOptions);let u=o(o({method:"POST"},a),i),c={},f={};await V(c,r),c["Content-Type"]="application/json",P(s,f,i.query);let l=a&&a.headers?a.headers:{};return u.headers=o(o(o({},c),l),i.headers),u.data=Se(t,u,r),{url:I(s),options:u}}}},vr=function(r){let e=dr(r);return{async postMetrics(t,i,n){let s=await e.postMetrics(t,i,n);return O(s,D,b,r)}}};var Ie=class extends ce{postMetrics(e,t,i){return vr(this.configuration).postMetrics(e,t,i).then(n=>n(this.axios,this.basePath))}};var ie=class{constructor(e={}){this.apiKey=e.apiKey,this.username=e.username,this.password=e.password,this.accessToken=e.accessToken,this.basePath=e.basePath,this.baseOptions=e.baseOptions,this.formDataCtor=e.formDataCtor}isJsonMime(e){let t=new RegExp("^(application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(;.*)?$","i");return e!==null&&(t.test(e)||e.toLowerCase()==="application/json-patch+json")}};var he="1.1.1";var dt=te(_e());var we=class{trace(e,...t){console.trace(e,...t)}debug(e,...t){console.debug(e,...t)}info(e,...t){console.info(e,...t)}warn(e,...t){console.warn(e,...t)}error(e,...t){console.error(e,...t)}};import br from"keyv";import{KeyvFile as Rr}from"keyv-file";var me=class{constructor(e={}){this.keyv=new br({store:new Rr(e)})}set(e,t){return this.keyv.set(e,t)}get(e){return this.keyv.get(e)}del(e){return this.keyv.delete(e)}};var vt=100;var yt="featureIdentifier",Et="featureName",Tt="variationIdentifier";var At="target",bt="SDK_VERSION",Rt="SDK_TYPE",xt="server",St="SDK_LANGUAGE",Pt="javascript",It="global",Ot="segmentMatch",Ct="in",_t="equal",wt="gt",Vt="starts_with",Dt="ends_with",Nt="contains",Ft="equal_sensitive",xr="https://config.ff.harness.io/api/1.0",Sr="https://events.ff.harness.io/api/1.0",Pr=1e3,Ut=60*Pr,Ir=1*Ut,Or=1*Ut,A={baseUrl:xr,eventsUrl:Sr,pollInterval:Ir,eventsSyncInterval:Or,enableStream:!0,enableAnalytics:!0,cache:new dt.default({max:100}),store:new me,logger:new we};var C=A.logger,$;(function(t){t.READY="poller_ready",t.ERROR="poller_error"})($||($={}));var Ve=class{constructor(e,t,i,n,s,a){this.stopped=!0;this.initialized=!1;this.api=i,this.options=n,this.environment=e,this.cluster=t,this.repository=a,this.eventBus=s}poll(){if(this.stopped)return;let e=new Date().getTime(),t=()=>{let i=new Date().getTime()-e,n=Math.max(this.options.pollInterval-i,0);setTimeout(()=>this.poll(),n)};Promise.all([this.retrieveFlags(),this.retrieveSegments()]).then(()=>{this.initialized||(this.initialized=!0,this.eventBus.emit($.READY))}).catch(i=>{this.eventBus.emit($.ERROR,{error:i})}).finally(t)}async retrieveFlags(){try{C.debug("Fetching flags started");let e=await this.api.getFeatureConfig(this.environment,{params:{cluster:this.cluster}});C.debug("Fetching flags finished"),e.data.forEach(t=>this.repository.setFlag(t.feature,t))}catch(e){throw C.error("Error loading flags",e),e}}async retrieveSegments(){try{C.debug("Fetching segments started");let e=await this.api.getAllSegments(this.environment,{params:{cluster:this.cluster}});C.debug("Fetching segments finished"),e.data.forEach(t=>this.repository.setSegment(t.identifier,t))}catch(e){throw C.error("Error loading segments",e),e}}start(){if(!this.stopped){C.info("PollingProcessor already started");return}C.info("Starting PollingProcessor with request interval: ",this.options.pollInterval),this.stopped=!1,this.poll()}stop(){C.info("Stopping PollingProcessor"),this.stopped=!0}close(){C.info("Closing PollingProcessor"),this.stop()}};import Cr from"eventsource";var M=A.logger,De=class{constructor(e,t,i,n,s,a,u,c){this.api=e,this.apiKey=t,this.environment=i,this.jwtToken=n,this.options=s,this.cluster=a,this.eventBus=u,this.repository=c}start(){M.info("Starting StreamProcessor");let e=new Cr(`${this.options.baseUrl}/stream?cluster=${this.cluster}`,{headers:{Authorization:`Bearer ${this.jwtToken}`,"API-Key":this.apiKey}});e.onopen=t=>{M.debug("Stream connected",t),this.eventBus.emit(T.CONNECTED)},e.onerror=t=>{M.debug("Stream has issue",t),this.eventBus.emit(T.ERROR,t)},e.addEventListener("*",t=>{let i=JSON.parse(t.data);M.debug("Received event from stream: ",i),i.domain==="flag"?this.msgProcessor(i,this.api.getFeatureConfigByIdentifier.bind(this.api),this.repository.setFlag.bind(this.repository),this.repository.deleteFlag.bind(this.repository)):i.domain==="target-segment"&&this.msgProcessor(i,this.api.getSegmentByIdentifier.bind(this.api),this.repository.setSegment.bind(this.repository),this.repository.deleteSegment.bind(this.repository))}),this.eventSource=e,this.eventBus.emit(T.READY)}async msgProcessor(e,t,i,n){M.info("Processing message",e);try{let a=(await t(e.identifier,this.environment)).data;e.event==="create"||e.event==="patch"?i(e.identifier,a):e.event==="delete"&&n(e.identifier)}catch(s){throw M.error("Error while fetching data with identifier:",e.identifier,s),s}M.info("Processing message finished",e)}connected(){return this.eventSource.readyState==De.CONNECTED}stop(){M.info("Stopping StreamProcessor"),this.eventSource.close(),this.eventBus.emit(T.DISCONNECTED)}close(){this.stop()}},de=De;de.CONNECTED=1;var Ne=class{constructor(e){this.value=e}startsWith(e){return!1}endsWith(e){return!1}match(e){return!1}contains(e){return!1}equalSensitive(e){return!1}equal(e){return this.value===(e[0].toLowerCase()==="true")}greaterThan(e){return!1}greaterThanEqual(e){return!1}lessThan(e){return!1}lessThanEqual(e){return!1}inList(e){return this.value}};var Fe=class{startsWith(e){return!1}endsWith(e){return!1}match(e){return!1}contains(e){return!1}equalSensitive(e){return!1}equal(e){return!1}greaterThan(e){return!1}greaterThanEqual(e){return!1}lessThan(e){return!1}lessThanEqual(e){return!1}inList(e){return!1}};var Ue=class{constructor(e){this.value=e}startsWith(e){return!1}endsWith(e){return!1}match(e){return!1}contains(e){return!1}equalSensitive(e){return!1}equal(e){return this.value===parseFloat(e==null?void 0:e[0])}greaterThan(e){return this.value>parseFloat(e==null?void 0:e[0])}greaterThanEqual(e){return this.value>=parseFloat(e==null?void 0:e[0])}lessThan(e){return this.value<parseFloat(e==null?void 0:e[0])}lessThanEqual(e){return this.value<=parseFloat(e==null?void 0:e[0])}inList(e){return e.map(i=>parseFloat(i)).includes(this.value)}};var qe=class{constructor(e){this.value=e}startsWith(e){return this.value.startsWith(e==null?void 0:e[0])}endsWith(e){return this.value.endsWith(e==null?void 0:e[0])}match(e){return this.value.match(e==null?void 0:e[0])!==void 0}contains(e){return this.value.includes(e==null?void 0:e[0])}equalSensitive(e){return this.value===(e==null?void 0:e[0])}equal(e){var t;return this.value.toLocaleLowerCase()===((t=e==null?void 0:e[0])==null?void 0:t.toLocaleLowerCase())}greaterThan(e){return this.value>(e==null?void 0:e[0])}greaterThanEqual(e){return this.value>=(e==null?void 0:e[0])}lessThan(e){return this.value<(e==null?void 0:e[0])}lessThanEqual(e){return this.value<=(e==null?void 0:e[0])}inList(e){return e.includes(this.value)}};var Lt=te(qt()),W=A.logger,Be=class{constructor(e){this.query=e}getAttrValue(e,t){var i;return e[t]||((i=e.attributes)==null?void 0:i[t])}findVariation(e,t){return e.find(i=>i.identifier===t)}getNormalizedNumberWithNormalizer(e,t,i){let n=[t,e].join(":");return parseInt((0,Lt.default)(n).toString())%i+1}getNormalizedNumber(e,t){return this.getNormalizedNumberWithNormalizer(e,t,vt)}isEnabled(e,t,i){let n=this.getAttrValue(e,t);if(!n)return!1;let s=this.getNormalizedNumber(n,t);return i>0&&s<=i}evaluateDistribution(e,t){if(!e)return;let i="";for(let n of e.variations)if(i=n.variation,this.isEnabled(t,e.bucketBy,n.weight))return n.variation;return i}getOperator(e,t){let i=this.getAttrValue(e,t);switch(typeof i){case"boolean":return new Ne(i);case"string":return new qe(i);case"number":return new Ue(i);case"object":return new Fe}}convertApiTargetsToEvalTargets(e){return e.map(t=>({identifier:t.identifier,name:t.name,anonymous:t.anonymous,attributes:t.attributes}))}async isTargetIncludedOrExcludedInSegment(e,t){for(let i of e){let n=await this.query.getSegment(i);if(n){if(this.convertApiTargetsToEvalTargets(n.excluded).includes(t))return W.debug(`Target %s excluded from segment %s via exclude list | ||
`,t.name,n.name),!1;if(this.convertApiTargetsToEvalTargets(n.included).includes(t))return W.debug(`Target %s included in segment %s via include list | ||
`,t.name,n.name),!0;if(n.rules&&this.evaluateClauses(n.rules,t))return W.debug(`Target %s included in segment %s via rules | ||
`,t.name,n.name),!0}}return!1}async evaluateClause(e,t){if(!e.op)return!1;let i=this.getOperator(t,e.attribute);switch(e.op){case Ct:return i.inList(e.values);case _t:return i.equal(e.values);case Ft:return i.equalSensitive(e.values);case wt:return i.greaterThan(e.values);case Vt:return i.startsWith(e.values);case Dt:return i.endsWith(e.values);case Nt:return i.contains(e.values);case Ot:return this.isTargetIncludedOrExcludedInSegment(e.values,t)}return!1}async evaluateClauses(e,t){for(let i of e)if(!await this.evaluateClause(i,t))return!1;return!0}evaluateRule(e,t){return this.evaluateClauses(e.clauses,t)}async evaluateRules(e,t){if(!t||!e)return;e.sort((n,s)=>n.priority>s.priority?1:-1);let i;for(let n of e)if(!!await this.evaluateRule(n,t))return n.serve.distribution&&(i=this.evaluateDistribution(n.serve.distribution,t)),n.serve.variation&&(i=n.serve.variation),i}evaluateVariationMap(e,t){var i;if(!(!t||!e))for(let n of e){if((i=n.targets)==null?void 0:i.find(u=>u.identifier===t.identifier))return n.variation;let a=n.targetSegments;if(a&&this.isTargetIncludedOrExcludedInSegment(a,t))return n.variation}}async evaluateFlag(e,t){let i=e.offVariation;return e.state===fe.On&&(i=this.evaluateVariationMap(e.variationToTargetMap,t)||await this.evaluateRules(e.rules,t)||this.evaluateDistribution(e.defaultServe.distribution,t)||e.defaultServe.variation),this.findVariation(e.variations,i)}async checkPreRequisite(e,t){if(e.prerequisites){W.info("Checking pre requisites %s of parent feature %s",e.prerequisites,e.feature);for(let i of e.prerequisites){let n=await this.query.getFlag(i.feature);if(!n)return W.warn("Could not retrieve the pre requisite details of feature flag: %s",e.feature),!0;let s=await this.evaluateFlag(n,t);return W.info("Pre requisite flag %s has variation %s for target %s",n.feature,s,t),W.info("Pre requisite flag %s should have the variations %s",n.feature,i.variations),i.variations.includes(s.identifier)?await this.checkPreRequisite(n,t):!1}}return!0}async evaluate(e,t,i,n){let s=await this.query.getFlag(e);if(!s||s.kind!==i)return;if(s.prerequisites&&!await this.checkPreRequisite(s,t))return this.findVariation(s.variations,s.offVariation);let a=await this.evaluateFlag(s,t);if(a)return n&&n(s,t,a),a}async boolVariation(e,t,i=!1,n){let s=await this.evaluate(e,t,G.Boolean,n);return s?s.value.toLowerCase()==="true":i}async stringVariation(e,t,i="",n){let s=await this.evaluate(e,t,G.String,n);return s?s.value:i}async numberVariation(e,t,i=0,n){let s=await this.evaluate(e,t,G.Int,n);return s?parseFloat(s.value):i}async jsonVariation(e,t,i={},n){let s=await this.evaluate(e,t,G.Json,n);return s?JSON.parse(s.value):i}};var Me=class{constructor(e,t){if(!e)throw new Error("Cache is required argument and cannot be undefined");this.cache=e,this.store=t}async setFlag(e,t){let i=this.formatFlagKey(e);await this.isFlagOutdated(i,t)||(this.store?(await this.store.set(i,t),this.cache.del(i)):this.cache.set(i,t))}async setSegment(e,t){let i=this.formatSegmentKey(e);await this.isSegmentOutdated(i,t)||(this.store?(await this.store.set(i,t),this.cache.del(i)):this.cache.set(i,t))}async deleteFlag(e){let t=this.formatFlagKey(e);this.store&&await this.store.del(t),this.cache.del(t)}async deleteSegment(e){let t=this.formatSegmentKey(e);this.store&&await this.store.del(t),this.cache.del(t)}async getFlag(e,t=!0){let i=this.formatFlagKey(e),n=this.cache.get(i);if(n)return n;if(this.store)return n=await this.store.get(i),n&&t&&this.cache.set(i,n),n}async getSegment(e,t=!0){let i=this.formatSegmentKey(e),n=this.cache.get(i);if(n)return n;if(this.store)return n=await this.store.get(i),n&&t&&this.cache.set(i,n),n}async isFlagOutdated(e,t){let i=await this.getFlag(e,!1);return(i==null?void 0:i.version)&&i.version>(t==null?void 0:t.version)}async isSegmentOutdated(e,t){let i=await this.getSegment(e,!1);return(i==null?void 0:i.version)&&i.version>(t==null?void 0:t.version)}formatFlagKey(e){return`flags/${e}`}formatSegmentKey(e){return`segments/${e}`}};var Q=A.logger,ee;(function(t){t.READY="metrics_ready",t.ERROR="metrics_error"})(ee||(ee={}));var Bt=(r,e="1",t,i,n)=>{let s=new Map,a,u=new ie(ue(o({},t),{basePath:i.eventsUrl})),c=new Ie(u),f=(y,g,v)=>{let q={target:y,featureConfig:g,variation:v,count:0},J=l(q),m=s.get(J);m?m.count++:(q.count=1,s.set(J,q))},l=y=>{let g=y.featureConfig.feature,v=y.variation.identifier,q=y.variation.value;return`${g}/${v}/${q}/${It}`},p=()=>{var q,J;if(!s){Q.debug("No metrics data!");return}let y=[],g=[],v=new Map(s);s.clear();for(let m of v.values()){if(m.target&&!m.target.anonymous){let ke=[];m.target.attributes&&(ke=Object.entries(m.target.attributes).map(([Ht,zt])=>({key:Ht,value:zt})));let je=m.target.identifier;m.target.name&&(je=m.target.name);let Gt={identifier:m.target.identifier,name:je,attributes:ke};y.push(Gt)}let kt=[{key:yt,value:m.featureConfig.feature},{key:Et,value:m.featureConfig.feature},{key:Tt,value:m.variation.identifier},{key:Rt,value:xt},{key:St,value:Pt},{key:bt,value:he},{key:At,value:(J=(q=m==null?void 0:m.target)==null?void 0:q.identifier)!=null?J:null}],jt={timestamp:Date.now(),count:m.count,metricsType:ge.Ffmetrics,attributes:kt};g.push(jt)}return{targetData:y,metricsData:g}},x=()=>{let y=p();y&&(Q.debug("Start sending metrics data"),c.postMetrics(r,y,{params:{cluster:e}}).then(g=>{Q.debug("Metrics server returns: ",g.status),g.status>=400&&Q.error("Error while sending metrics data with status code: ",g.status)}).catch(g=>{Q.debug("Metrics server returns error: ",g)}))};return{start:()=>{Q.info("Starting MetricsProcessor with request interval: ",i.eventsSyncInterval),a=setInterval(x,i.eventsSyncInterval),n.emit(ee.READY)},close:()=>{Q.info("Closing MetricsProcessor"),clearInterval(a),x()},enqueue:f}};Kt.defaults.timeout=3e4;(0,Ke.default)(Kt,{retries:3,retryDelay:Ke.default.exponentialDelay});var ae=A.logger,K;(function(i){i[i.POLL=0]="POLL",i[i.STREAM=1]="STREAM",i[i.METRICS=2]="METRICS"})(K||(K={}));var U;(function(i){i.READY="ready",i.FAILED="failed",i.CHANGED="changed"})(U||(U={}));var ve=class{constructor(e,t={}){this.cluster="1";this.eventBus=new _r;this.initialized=!1;this.failure=!1;this.pollerReady=!1;this.streamReady=!1;this.metricReady=!1;this.sdkKey=e,t.pollInterval<1e3&&(t.pollInterval=A.pollInterval,ae.warn("Polling interval cannot be lower than 1000 ms")),this.options=o(o({},A),t),this.configuration=new ie({basePath:this.options.baseUrl,baseOptions:{headers:{"User-Agent":`NodeJsSDK/${he}`}}}),this.repository=new Me(this.options.cache,this.options.store),this.evaluator=new Be(this.repository),this.api=new Pe(this.configuration),this.processEvents(),this.run()}processEvents(){this.eventBus.on($.READY,()=>{this.initialize(0)}),this.eventBus.on($.ERROR,()=>{this.failure=!0,this.eventBus.emit(U.FAILED)}),this.eventBus.on(T.READY,()=>{this.initialize(1)}),this.eventBus.on(T.ERROR,()=>{this.failure=!0,this.eventBus.emit(U.FAILED)}),this.eventBus.on(ee.READY,()=>{this.initialize(2)}),this.eventBus.on(ee.ERROR,()=>{this.failure=!0,this.eventBus.emit(U.FAILED)}),this.eventBus.on(T.CONNECTED,()=>{this.pollProcessor.stop()}),this.eventBus.on(T.DISCONNECTED,()=>{this.pollProcessor.start()})}async authenticate(){try{let e=await this.api.authenticate({apiKey:this.sdkKey});this.authToken=e.data.authToken,this.configuration.accessToken=this.authToken;let t=(0,Mt.default)(this.authToken);this.environment=t.environment,this.cluster=t.clusterIdentifier||"1"}catch(e){this.failure=!0,console.error("Error while authenticating, err: ",e)}}waitForInitialization(){return this.waitForInitialize?this.waitForInitialize:(this.initialized?this.waitForInitialize=Promise.resolve(this):this.failure?this.waitForInitialize=Promise.reject(this.failure):this.waitForInitialize=new Promise((e,t)=>{this.eventBus.once(U.READY,()=>{e(this)}),this.eventBus.once(U.FAILED,t)}),this.waitForInitialize)}initialize(e){switch(e){case 0:this.pollerReady=!0,ae.debug("PollingProcessor ready");break;case 1:this.streamReady=!0,ae.debug("StreamingProcessor ready");break;case 2:this.metricReady=!0,ae.debug("MetricsProcessor ready");break}this.options.enableStream&&!this.streamReady||this.options.enableAnalytics&&!this.metricReady||!this.pollerReady||(this.initialized=!0,this.eventBus.emit(U.READY))}async run(){await this.authenticate(),this.pollProcessor=new Ve(this.environment,this.cluster,this.api,this.options,this.eventBus,this.repository),this.pollProcessor.start(),this.options.enableStream&&(this.streamProcessor=new de(this.api,this.sdkKey,this.environment,this.authToken,this.options,this.cluster,this.eventBus,this.repository),this.streamProcessor.start()),this.options.enableAnalytics&&(this.metricsProcessor=Bt(this.environment,this.cluster,this.configuration,this.options,this.eventBus),this.metricsProcessor.start()),ae.info("finished setting up processors")}boolVariation(e,t,i=!1){return this.evaluator.boolVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}stringVariation(e,t,i=""){return this.evaluator.stringVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}numberVariation(e,t,i=0){return this.evaluator.numberVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}jsonVariation(e,t,i={}){return this.evaluator.jsonVariation(e,t,i,(n,s,a)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(s,n,a)})}close(){this.pollProcessor.close(),this.streamProcessor&&this.streamProcessor.close(),this.metricsProcessor&&this.metricsProcessor.close()}};var wr=te(_e());var Vn={instance:void 0,init:function(r,e){this.instance||(this.instance=new ve(r,e))},waitForInitialization:function(){return this.instance.waitForInitialization()},boolVariation:function(r,e,t=!1){return this.instance.boolVariation(r,e,t)},stringVariation:function(r,e,t=""){return this.instance.stringVariation(r,e,t)},numberVariation:function(r,e,t=0){return this.instance.numberVariation(r,e,t)},jsonVariation:function(r,e,t=""){return this.instance.jsonVariation(r,e,t)},close:function(){return this.instance.close()}};var export_LRU=wr.default;export{ve as Client,U as ClientEvent,me as FileStore,export_LRU as LRU,Vn as default}; | ||
//# sourceMappingURL=index.js.map |
@@ -1405,4 +1405,4 @@ /// <reference types="node" /> | ||
export interface Query { | ||
getFlag(identifier: string): Promise<FeatureConfig>; | ||
getSegment(identifier: string): Promise<Segment>; | ||
getFlag(identifier: string, cacheable?: boolean): Promise<FeatureConfig>; | ||
getSegment(identifier: string, cacheable?: boolean): Promise<Segment>; | ||
} | ||
@@ -1427,3 +1427,3 @@ export interface KeyValueStore { | ||
declare module "version" { | ||
export const VERSION = "1.1.0"; | ||
export const VERSION = "1.1.1"; | ||
} | ||
@@ -1430,0 +1430,0 @@ declare module "repository" { |
{ | ||
"name": "@harnessio/ff-nodejs-server-sdk", | ||
"version": "1.1.0", | ||
"version": "1.1.1", | ||
"description": "Feature flags SDK for NodeJS environments", | ||
@@ -5,0 +5,0 @@ "main": "dist/cjs/index.js", |
@@ -28,3 +28,3 @@ # Harness Feature Flags Server SDK for NodeJS | ||
```javascript | ||
const { Client } = require('ff-nodejs-server-sdk'); | ||
const { Client } = require('@harnessio/ff-nodejs-server-sdk'); | ||
``` | ||
@@ -35,3 +35,3 @@ | ||
```typescript | ||
import { Client } from 'ff-nodejs-server-sdk'; | ||
import { Client } from '@harnessio/ff-nodejs-server-sdk'; | ||
``` | ||
@@ -120,3 +120,3 @@ | ||
``` | ||
import CfClient from 'ff-nodejs-server-sdk'; | ||
import CfClient from '@harnessio/ff-nodejs-server-sdk'; | ||
@@ -142,3 +142,3 @@ CfClient.init('your server type SDK key'); | ||
``` | ||
const { Client } = require('ff-nodejs-server-sdk'); | ||
const { Client } = require('@harnessio/ff-nodejs-server-sdk'); | ||
@@ -145,0 +145,0 @@ console.log('Starting application'); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
1648235