Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@harnessio/ff-nodejs-server-sdk

Package Overview
Dependencies
Maintainers
8
Versions
53
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@harnessio/ff-nodejs-server-sdk - npm Package Compare versions

Comparing version 1.4.0 to 1.4.1-rc.1

4

dist/cjs/index.js

@@ -1,5 +0,5 @@

"use strict";var Ht=Object.create;var ee=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var Qt=Object.getPrototypeOf,Jt=Object.prototype.hasOwnProperty;var ge=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Le=(s,e)=>{for(var t in e)ee(s,t,{get:e[t],enumerable:!0})},De=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Yt(e))!Jt.call(s,r)&&r!==t&&ee(s,r,{get:()=>e[r],enumerable:!(i=Wt(e,r))||i.enumerable});return s};var P=(s,e,t)=>(t=s!=null?Ht(Qt(s)):{},De(e||!s||!s.__esModule?ee(t,"default",{value:s,enumerable:!0}):t,s)),Xt=s=>De(ee({},"__esModule",{value:!0}),s);var Ne=ge((Pi,Be)=>{"use strict";function pe(s){this.message=s}pe.prototype=new Error,pe.prototype.name="InvalidCharacterError";var ke=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(s){var e=String(s).replace(/=+$/,"");if(e.length%4==1)throw new pe("'atob' failed: The string to be decoded is not correctly encoded.");for(var t,i,r=0,n=0,o="";i=e.charAt(n++);~i&&(t=r%4?64*t+i:i,r++%4)?o+=String.fromCharCode(255&t>>(-2*r&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o};function Zt(s){var e=s.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(ke(t).replace(/(.)/g,function(i,r){var n=r.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}(e)}catch{return ke(e)}}function Y(s){this.message=s}function Me(s,e){if(typeof s!="string")throw new Y("Invalid token specified");var t=(e=e||{}).header===!0?0:1;try{return JSON.parse(Zt(s.split(".")[t]))}catch(i){throw new Y("Invalid token specified: "+i.message)}}Y.prototype=new Error,Y.prototype.name="InvalidTokenError";var de=Me;de.default=Me,de.InvalidTokenError=Y,Be.exports=de});var Ve=ge((_i,Ue)=>{"use strict";var ei=new Set(["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","HOSTNAME_MISMATCH"]);Ue.exports=s=>!ei.has(s&&s.code)});var zt=ge((vr,Ce)=>{"use strict";(function(){let s=this,e=n=>new TextEncoder().encode(n);function t(n,o){typeof n=="string"&&(n=e(n));let a=n.length,c=o^a,l=0,h;for(;a>=4;)h=n[l]&255|(n[++l]&255)<<8|(n[++l]&255)<<16|(n[++l]&255)<<24,h=(h&65535)*1540483477+(((h>>>16)*1540483477&65535)<<16),h^=h>>>24,h=(h&65535)*1540483477+(((h>>>16)*1540483477&65535)<<16),c=(c&65535)*1540483477+(((c>>>16)*1540483477&65535)<<16)^h,a-=4,++l;switch(a){case 3:c^=(n[l+2]&255)<<16;case 2:c^=(n[l+1]&255)<<8;case 1:c^=n[l]&255,c=(c&65535)*1540483477+(((c>>>16)*1540483477&65535)<<16)}return c^=c>>>13,c=(c&65535)*1540483477+(((c>>>16)*1540483477&65535)<<16),c^=c>>>15,c>>>0}function i(n,o){typeof n=="string"&&(n=e(n));let a,c,l,h,f,d,p,S,u,g;for(a=n.length&3,c=n.length-a,l=o,f=3432918353,p=461845907,g=0;g<c;)u=n[g]&255|(n[++g]&255)<<8|(n[++g]&255)<<16|(n[++g]&255)<<24,++g,u=(u&65535)*f+(((u>>>16)*f&65535)<<16)&4294967295,u=u<<15|u>>>17,u=(u&65535)*p+(((u>>>16)*p&65535)<<16)&4294967295,l^=u,l=l<<13|l>>>19,h=(l&65535)*5+(((l>>>16)*5&65535)<<16)&4294967295,l=(h&65535)+27492+(((h>>>16)+58964&65535)<<16);switch(u=0,a){case 3:u^=(n[g+2]&255)<<16;case 2:u^=(n[g+1]&255)<<8;case 1:u^=n[g]&255,u=(u&65535)*f+(((u>>>16)*f&65535)<<16)&4294967295,u=u<<15|u>>>17,u=(u&65535)*p+(((u>>>16)*p&65535)<<16)&4294967295,l^=u}return l^=n.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}let r=i;if(r.v2=t,r.v3=i,typeof Ce<"u")Ce.exports=r;else{let n=s.murmur;r.noConflict=function(){return s.murmur=n,r},s.murmur=r}})()});var wi={};Le(wi,{Client:()=>H,Event:()=>fe,FileStore:()=>$,LRU:()=>_e,default:()=>Ri});module.exports=Xt(wi);var jt=P(require("events")),Gt=P(Ne()),Ie=P(require("axios"));var Ge=P(Ve(),1);function ze(s,e,t,i,r,n,o){try{var a=s[n](o),c=a.value}catch(l){t(l);return}a.done?e(c):Promise.resolve(c).then(i,r)}function je(s){return function(){var e=this,t=arguments;return new Promise(function(i,r){var n=s.apply(e,t);function o(c){ze(n,i,r,o,a,"next",c)}function a(c){ze(n,i,r,o,a,"throw",c)}o(void 0)})}}function qe(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i)}return t}function me(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?qe(Object(t),!0).forEach(function(i){ti(s,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):qe(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i))})}return s}function ti(s,e,t){return e in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}var $e="axios-retry";function He(s){var e=["ERR_CANCELED","ECONNABORTED"];return!s.response&&!!s.code&&!e.includes(s.code)&&(0,Ge.default)(s)}var We=["get","head","options"],ii=We.concat(["put","delete"]);function ye(s){return s.code!=="ECONNABORTED"&&(!s.response||s.response.status>=500&&s.response.status<=599)}function ri(s){return s.config?ye(s)&&We.indexOf(s.config.method)!==-1:!1}function Ye(s){return s.config?ye(s)&&ii.indexOf(s.config.method)!==-1:!1}function Qe(s){return He(s)||Ye(s)}function si(){return 0}function ni(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1?arguments[1]:void 0,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:100,i=Math.pow(2,s)*t,r=i*.2*Math.random();return i+r}var oi={retries:3,retryCondition:Qe,retryDelay:si,shouldResetTimeout:!1,onRetry:()=>{}};function ai(s,e){return me(me(me({},oi),e),s[$e])}function Ke(s,e){var t=ai(s,e);return t.retryCount=t.retryCount||0,s[$e]=t,t}function li(s,e){s.defaults.agent===e.agent&&delete e.agent,s.defaults.httpAgent===e.httpAgent&&delete e.httpAgent,s.defaults.httpsAgent===e.httpsAgent&&delete e.httpsAgent}function ci(s,e){return ve.apply(this,arguments)}function ve(){return ve=je(function*(s,e){var{retries:t,retryCondition:i}=s,r=s.retryCount<t&&i(e);if(typeof r=="object")try{var n=yield r;return n!==!1}catch{return!1}return r}),ve.apply(this,arguments)}function _(s,e){var t=s.interceptors.request.use(r=>{var n=Ke(r,e);return n.lastRequestTime=Date.now(),r}),i=s.interceptors.response.use(null,function(){var r=je(function*(n){var{config:o}=n;if(!o)return Promise.reject(n);var a=Ke(o,e);if(yield ci(a,n)){a.retryCount+=1;var{retryDelay:c,shouldResetTimeout:l,onRetry:h}=a,f=c(a.retryCount,n);if(li(s,o),!l&&o.timeout&&a.lastRequestTime){var d=Date.now()-a.lastRequestTime,p=o.timeout-d-f;if(p<=0)return Promise.reject(n);o.timeout=p}return o.transformRequest=[S=>S],yield h(a.retryCount,n,o),new Promise(S=>setTimeout(()=>S(s(o)),f))}return Promise.reject(n)});return function(n){return r.apply(this,arguments)}}());return{requestInterceptorId:t,responseInterceptorId:i}}_.isNetworkError=He;_.isSafeRequestError=ri;_.isIdempotentRequestError=Ye;_.isNetworkOrIdempotentRequestError=Qe;_.exponentialDelay=ni;_.isRetryableError=ye;var L=P(require("axios"));var Je=P(require("axios")),x="http://localhost/api/1.0".replace(/\/+$/,"");var Q=class{constructor(e,t=x,i=Je.default){this.basePath=t;this.axios=i;e&&(this.configuration=e,this.basePath=e.basePath||this.basePath)}},te=class extends Error{constructor(t,i){super(i);this.field=t;this.name="RequiredError"}};var C="https://example.com",R=function(s,e,t){if(t==null)throw new te(e,`Required parameter ${e} was null or undefined when calling ${s}.`)};var k=async function(s,e){if(e&&e.accessToken){let t=typeof e.accessToken=="function"?await e.accessToken():await e.accessToken;s.Authorization="Bearer "+t}};var O=function(s,...e){let t=new URLSearchParams(s.search);for(let i of e)for(let r in i)if(Array.isArray(i[r])){t.delete(r);for(let n of i[r])t.append(r,n)}else t.set(r,i[r]);s.search=t.toString()},Ee=function(s,e,t){let i=typeof s!="string";return(i&&t&&t.isJsonMime?t.isJsonMime(e.headers["Content-Type"]):i)?JSON.stringify(s!==void 0?s:{}):s||""},I=function(s){return s.pathname+s.search+s.hash},F=function(s,e,t,i){return(r=e,n=t)=>{let o={...s.options,url:((i==null?void 0:i.basePath)||n)+s.url};return r.request(o)}};var hi=function(s){return{authenticate:async(e,t={})=>{let i="/client/auth",r=new URL(i,C),n;s&&(n=s.baseOptions);let o={method:"POST",...n,...t},a={},c={};a["Content-Type"]="application/json",O(r,c,t.query);let l=n&&n.headers?n.headers:{};return o.headers={...a,...l,...t.headers},o.data=Ee(e,o,s),{url:I(r),options:o}},getAllSegments:async(e,t,i={})=>{R("getAllSegments","environmentUUID",e);let r="/client/env/{environmentUUID}/target-segments".replace("{environmentUUID}",encodeURIComponent(String(e))),n=new URL(r,C),o;s&&(o=s.baseOptions);let a={method:"GET",...o,...i},c={},l={};await k(c,s),t!==void 0&&(l.cluster=t),O(n,l,i.query);let h=o&&o.headers?o.headers:{};return a.headers={...c,...h,...i.headers},{url:I(n),options:a}},getEvaluationByIdentifier:async(e,t,i,r,n={})=>{R("getEvaluationByIdentifier","environmentUUID",e),R("getEvaluationByIdentifier","feature",t),R("getEvaluationByIdentifier","target",i);let o="/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(o,C),c;s&&(c=s.baseOptions);let l={method:"GET",...c,...n},h={},f={};await k(h,s),r!==void 0&&(f.cluster=r),O(a,f,n.query);let d=c&&c.headers?c.headers:{};return l.headers={...h,...d,...n.headers},{url:I(a),options:l}},getEvaluations:async(e,t,i,r={})=>{R("getEvaluations","environmentUUID",e),R("getEvaluations","target",t);let n="/client/env/{environmentUUID}/target/{target}/evaluations".replace("{environmentUUID}",encodeURIComponent(String(e))).replace("{target}",encodeURIComponent(String(t))),o=new URL(n,C),a;s&&(a=s.baseOptions);let c={method:"GET",...a,...r},l={},h={};await k(l,s),i!==void 0&&(h.cluster=i),O(o,h,r.query);let f=a&&a.headers?a.headers:{};return c.headers={...l,...f,...r.headers},{url:I(o),options:c}},getFeatureConfig:async(e,t,i={})=>{R("getFeatureConfig","environmentUUID",e);let r="/client/env/{environmentUUID}/feature-configs".replace("{environmentUUID}",encodeURIComponent(String(e))),n=new URL(r,C),o;s&&(o=s.baseOptions);let a={method:"GET",...o,...i},c={},l={};await k(c,s),t!==void 0&&(l.cluster=t),O(n,l,i.query);let h=o&&o.headers?o.headers:{};return a.headers={...c,...h,...i.headers},{url:I(n),options:a}},getFeatureConfigByIdentifier:async(e,t,i,r={})=>{R("getFeatureConfigByIdentifier","identifier",e),R("getFeatureConfigByIdentifier","environmentUUID",t);let n="/client/env/{environmentUUID}/feature-configs/{identifier}".replace("{identifier}",encodeURIComponent(String(e))).replace("{environmentUUID}",encodeURIComponent(String(t))),o=new URL(n,C),a;s&&(a=s.baseOptions);let c={method:"GET",...a,...r},l={},h={};await k(l,s),i!==void 0&&(h.cluster=i),O(o,h,r.query);let f=a&&a.headers?a.headers:{};return c.headers={...l,...f,...r.headers},{url:I(o),options:c}},getSegmentByIdentifier:async(e,t,i,r={})=>{R("getSegmentByIdentifier","identifier",e),R("getSegmentByIdentifier","environmentUUID",t);let n="/client/env/{environmentUUID}/target-segments/{identifier}".replace("{identifier}",encodeURIComponent(String(e))).replace("{environmentUUID}",encodeURIComponent(String(t))),o=new URL(n,C),a;s&&(a=s.baseOptions);let c={method:"GET",...a,...r},l={},h={};await k(l,s),i!==void 0&&(h.cluster=i),O(o,h,r.query);let f=a&&a.headers?a.headers:{};return c.headers={...l,...f,...r.headers},{url:I(o),options:c}},stream:async(e,t,i={})=>{R("stream","aPIKey",e);let r="/stream",n=new URL(r,C),o;s&&(o=s.baseOptions);let a={method:"GET",...o,...i},c={},l={};await k(c,s),t!==void 0&&(l.cluster=t),e!=null&&(c["API-Key"]=String(e)),O(n,l,i.query);let h=o&&o.headers?o.headers:{};return a.headers={...c,...h,...i.headers},{url:I(n),options:a}}}},B=function(s){let e=hi(s);return{async authenticate(t,i){let r=await e.authenticate(t,i);return F(r,L.default,x,s)},async getAllSegments(t,i,r){let n=await e.getAllSegments(t,i,r);return F(n,L.default,x,s)},async getEvaluationByIdentifier(t,i,r,n,o){let a=await e.getEvaluationByIdentifier(t,i,r,n,o);return F(a,L.default,x,s)},async getEvaluations(t,i,r,n){let o=await e.getEvaluations(t,i,r,n);return F(o,L.default,x,s)},async getFeatureConfig(t,i,r){let n=await e.getFeatureConfig(t,i,r);return F(n,L.default,x,s)},async getFeatureConfigByIdentifier(t,i,r,n){let o=await e.getFeatureConfigByIdentifier(t,i,r,n);return F(o,L.default,x,s)},async getSegmentByIdentifier(t,i,r,n){let o=await e.getSegmentByIdentifier(t,i,r,n);return F(o,L.default,x,s)},async stream(t,i,r){let n=await e.stream(t,i,r);return F(n,L.default,x,s)}}};var ie=class extends Q{authenticate(e,t){return B(this.configuration).authenticate(e,t).then(i=>i(this.axios,this.basePath))}getAllSegments(e,t,i){return B(this.configuration).getAllSegments(e,t,i).then(r=>r(this.axios,this.basePath))}getEvaluationByIdentifier(e,t,i,r,n){return B(this.configuration).getEvaluationByIdentifier(e,t,i,r,n).then(o=>o(this.axios,this.basePath))}getEvaluations(e,t,i,r){return B(this.configuration).getEvaluations(e,t,i,r).then(n=>n(this.axios,this.basePath))}getFeatureConfig(e,t,i){return B(this.configuration).getFeatureConfig(e,t,i).then(r=>r(this.axios,this.basePath))}getFeatureConfigByIdentifier(e,t,i,r){return B(this.configuration).getFeatureConfigByIdentifier(e,t,i,r).then(n=>n(this.axios,this.basePath))}getSegmentByIdentifier(e,t,i,r){return B(this.configuration).getSegmentByIdentifier(e,t,i,r).then(n=>n(this.axios,this.basePath))}stream(e,t,i){return B(this.configuration).stream(e,t,i).then(r=>r(this.axios,this.basePath))}},ui=function(s){return{postMetrics:async(e,t,i,r={})=>{R("postMetrics","environment",e);let n="/metrics/{environment}".replace("{environment}",encodeURIComponent(String(e))),o=new URL(n,C),a;s&&(a=s.baseOptions);let c={method:"POST",...a,...r},l={},h={};await k(l,s),t!==void 0&&(h.cluster=t),l["Content-Type"]="application/json",O(o,h,r.query);let f=a&&a.headers?a.headers:{};return c.headers={...l,...f,...r.headers},c.data=Ee(i,c,s),{url:I(o),options:c}}}},fi=function(s){let e=ui(s);return{async postMetrics(t,i,r,n){let o=await e.postMetrics(t,i,r,n);return F(o,L.default,x,s)}}};var re=class extends Q{postMetrics(e,t,i,r){return fi(this.configuration).postMetrics(e,t,i,r).then(n=>n(this.axios,this.basePath))}};var K=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 se="1.4.0";var Xe={1e3:"The SDK has successfully initialized",1001:"The SDK has failed to initialize due to an authentication error - defaults will be served",1002:"The SDK has failed to initialize due to a missing or empty API key - defaults will be served",2e3:"Authentication was successful",2001:"Authentication failed with a non-recoverable error",2002:"Authentication attempt failed:",2003:"Authentication failed and max retries have been exceeded",3e3:"Closing SDK",3001:"SDK Closed successfully",4e3:"Polling started, interval:",4001:"Polling stopped",5e3:"SSE stream successfully connected",5001:"SSE stream disconnected, reason:",5002:"SSE event received",5003:"SSE retrying to connect in",5004:"SSE stopped",6e3:"Evaluation successful: ",6001:"Evaluation Failed, returning default variation: ",6002:"BucketBy attribute not found in target attributes, falling back to 'identifier':",7e3:"Metrics thread started with request interval:",7001:"Metrics stopped",7002:"Posting metrics failed, reason:",7003:"Metrics posted successfully"};function gi(s){return s in Xe?Xe[s]:"Unknown SDK code"}function E(s,e=""){return`SDKCODE:${s}: ${gi(s)} ${e}`}function Ze(s){s.warn(E(1002))}function et(s,e){e.info(E(4e3,s/1e3+" seconds"))}function Se(s){s.info(E(1e3))}function tt(s){s.info(E(3e3))}function it(s){s.info(E(3001))}function Te(s){s.info(E(4001))}function rt(s){s.info(E(5e3))}function st(s){s.debug(E(5002))}function nt(s){s.info(E(5004))}function ot(s,e){e.info(E(7e3,s/1e3+" seconds"))}function at(s){s.info(E(7003))}function lt(s){s.info(E(7001))}function J(s,e,t,i){i.debug(E(6e3,`result=${s}, flag identifier=${e}, target=${JSON.stringify(t)}`))}function ct(s){s.warn(E(2001))}function ht(s){s.warn(E(1001))}function ut(s,e){e.warn(E(5001,s))}function ft(s,e){e.warn(E(5003,`${s}`))}function gt(s,e){e.warn(E(7002,s))}function D(s,e,t,i){i.warn(E(6001,`default variation used=${t}, flag=${s}, target=${JSON.stringify(e)}`))}function dt(s,e,t){t.warn(E(6002,`missing=${s}, using value=${e}`))}var ne=class{constructor(e,t,i,r,n,o){this.stopped=!0;this.initialized=!1;this.lastPollTime=0;this.api=i,this.options=r,this.environment=e,this.cluster=t,this.repository=o,this.eventBus=n,this.log=r.logger}poll(){if(this.stopped){this.log.info("PollingProcessor stopped"),Te(this.log);return}let e=new Date().getTime(),t=()=>{let i=new Date().getTime()-e,r=Math.max(this.options.pollInterval-i,0);this.timeout=setTimeout(()=>this.poll(),r)};if(this.lastPollTime>Date.now()-this.options.pollInterval){this.log.info(`Last poll was ${Math.round((Date.now()-this.lastPollTime)/1e3)} seconds ago, skipping flag refresh`),t();return}this.lastPollTime=Date.now(),Promise.all([this.retrieveFlags(),this.retrieveSegments()]).then(()=>{this.initialized||setTimeout(()=>{this.initialized=!0,this.eventBus.emit("poller_ready")},0)}).catch(i=>{this.eventBus.emit("poller_error",{error:i})}).finally(()=>{if(this.stopped){this.log.info("PollingProcessor stopped"),Te(this.log);return}t()})}async retrieveFlags(){try{this.log.debug("Fetching flags started");let e=await this.api.getFeatureConfig(this.environment,this.cluster);this.log.debug("Fetching flags finished"),e.data.forEach(t=>this.repository.setFlag(t.feature,t))}catch(e){throw this.log.error("Error loading flags",e),e}}async retrieveSegments(){try{this.log.debug("Fetching segments started");let e=await this.api.getAllSegments(this.environment,this.cluster);this.log.debug("Fetching segments finished"),e.data.forEach(t=>this.repository.setSegment(t.identifier,t))}catch(e){throw this.log.error("Error loading segments",e),e}}start(){if(!this.stopped){this.log.info("PollingProcessor already started");return}this.log.info("Starting PollingProcessor with request interval: ",this.options.pollInterval),this.stopped=!1,this.poll()}stop(){this.log.info("Stopping PollingProcessor"),this.stopped=!0}close(){this.log.info("Closing PollingProcessor"),this.stop(),clearTimeout(this.timeout),this.log.info("PollingProcessor closed")}};var pt=P(require("https")),mt=P(require("http"));var b=class b{constructor(e,t,i,r,n,o,a,c){this.retryAttempt=0;this.api=e,this.apiKey=t,this.environment=i,this.jwtToken=r,this.options=n,this.cluster=o,this.eventBus=a,this.repository=c,this.log=this.options.logger;let l=5e3,h=1e4;this.retryDelayMs=Math.floor(Math.random()*(h-l)+l)}start(){this.log.info("Starting new StreamProcessor");let e=`${this.options.baseUrl}/stream?cluster=${this.cluster}`,t={headers:{"Cache-Control":"no-cache",Accept:"text/event-stream",Authorization:`Bearer ${this.jwtToken}`,"API-Key":this.apiKey}},i=()=>{this.log.info(`SSE stream connected OK: ${e}`),this.retryAttempt=0,this.readyState=b.CONNECTED,this.eventBus.emit("stream_connected")},r=n=>{if(this.readyState!==b.CLOSED){this.retryAttempt+=1;let o=this.getRandomRetryDelayMs();ut(n,this.log),ft(o,this.log),this.readyState=b.RETRYING,this.eventBus.emit("stream_retrying"),setTimeout(()=>{this.log.info("SSE retrying to connect"),this.connect(e,t,i,r)},o)}};this.connect(e,t,i,r),this.eventBus.emit("stream_ready")}getRandomRetryDelayMs(){let e=this.retryDelayMs*this.retryAttempt;return Math.min(e,6e4)}connect(e,t,i,r){if(this.readyState===b.CONNECTED){this.log.debug("SSE already connected, skip retry");return}let n=e.startsWith("https:");this.log.debug("SSE HTTP start request",e),this.request=(n?pt.default:mt.default).request(e,t,o=>{if(this.log.debug("SSE got HTTP response code",o.statusCode),o.statusCode>=400&&o.statusCode<=599){r(`HTTP code ${o.statusCode}`);return}i(),o.on("data",a=>{st(this.log),this.processData(a)}).on("close",()=>{r("SSE stream closed")})}).on("error",o=>{r("SSE request failed "+o.message)}).on("timeout",()=>{r("SSE request timed out after "+b.SSE_TIMEOUT_MS+"ms")}).setTimeout(b.SSE_TIMEOUT_MS),this.request.end()}processData(e){e.toString().split(/\r?\n/).forEach(i=>this.processLine(i))}processLine(e){if(e.startsWith("data:")){this.log.debug("SSE GOT:",e.substring(5));let t=JSON.parse(e.substring(5));t.domain==="flag"?this.msgProcessor(t,this.api.getFeatureConfigByIdentifier.bind(this.api),this.repository.setFlag.bind(this.repository),this.repository.deleteFlag.bind(this.repository)):t.domain==="target-segment"&&this.msgProcessor(t,this.api.getSegmentByIdentifier.bind(this.api),this.repository.setSegment.bind(this.repository),this.repository.deleteSegment.bind(this.repository))}}async msgProcessor(e,t,i,r){this.log.info("Processing message",e);try{if(e.event==="create"||e.event==="patch"){let{data:n}=await t(e.identifier,this.environment,this.cluster);i(e.identifier,n)}else e.event==="delete"&&r(e.identifier)}catch(n){throw this.log.error("Error while fetching data with identifier:",e.identifier,n),n}this.log.info("Processing message finished",e)}connected(){return this.readyState===b.CONNECTED}close(){if(this.readyState===b.CLOSED){this.log.info("SteamProcessor already closed");return}this.readyState=b.CLOSED,this.log.info("Closing StreamProcessor"),this.request.destroy(),this.request=void 0,this.eventBus.emit("stream_disconnected"),this.log.info("StreamProcessor closed"),nt(this.log)}};b.CONNECTED=1,b.RETRYING=2,b.CLOSED=3,b.SSE_TIMEOUT_MS=3e4;var oe=b;var _e={};Le(_e,{default:()=>Pe});var X=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,pi=typeof AbortController=="function",ae=pi?AbortController:class{constructor(){this.signal=new vt}abort(e=new Error("This operation was aborted")){this.signal.reason=this.signal.reason||e,this.signal.aborted=!0,this.signal.dispatchEvent({type:"abort",target:this.signal})}},mi=typeof AbortSignal=="function",vi=typeof ae.AbortSignal=="function",vt=mi?AbortSignal:vi?ae.AbortController:class{constructor(){this.reason=void 0,this.aborted=!1,this._listeners=[]}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,this.onabort(e),this._listeners.forEach(t=>t(e),this))}onabort(){}addEventListener(e,t){e==="abort"&&this._listeners.push(t)}removeEventListener(e,t){e==="abort"&&(this._listeners=this._listeners.filter(i=>i!==t))}},we=new Set,Ae=(s,e)=>{let t=`LRU_CACHE_OPTION_${s}`;le(t)&&xe(t,`${s} option`,`options.${e}`,G)},be=(s,e)=>{let t=`LRU_CACHE_METHOD_${s}`;if(le(t)){let{prototype:i}=G,{get:r}=Object.getOwnPropertyDescriptor(i,s);xe(t,`${s} method`,`cache.${e}()`,r)}},yi=(s,e)=>{let t=`LRU_CACHE_PROPERTY_${s}`;if(le(t)){let{prototype:i}=G,{get:r}=Object.getOwnPropertyDescriptor(i,s);xe(t,`${s} property`,`cache.${e}`,r)}},yt=(...s)=>{typeof process=="object"&&process&&typeof process.emitWarning=="function"?process.emitWarning(...s):console.error(...s)},le=s=>!we.has(s),xe=(s,e,t,i)=>{we.add(s);let r=`The ${e} is deprecated. Please use ${t} instead.`;yt(r,"DeprecationWarning",s,i)},N=s=>s&&s===Math.floor(s)&&s>0&&isFinite(s),Et=s=>N(s)?s<=Math.pow(2,8)?Uint8Array:s<=Math.pow(2,16)?Uint16Array:s<=Math.pow(2,32)?Uint32Array:s<=Number.MAX_SAFE_INTEGER?j:null:null,j=class extends Array{constructor(e){super(e),this.fill(0)}},Re=class{constructor(e){if(e===0)return[];let t=Et(e);this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},G=class s{constructor(e={}){let{max:t=0,ttl:i,ttlResolution:r=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:c,dispose:l,disposeAfter:h,noDisposeOnSet:f,noUpdateTTL:d,maxSize:p=0,maxEntrySize:S=0,sizeCalculation:u,fetchMethod:g,fetchContext:v,noDeleteOnFetchRejection:T,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:y,allowStaleOnFetchAbort:w,ignoreFetchAbort:m}=e,{length:V,maxAge:z,stale:M}=e instanceof s?{}:e;if(t!==0&&!N(t))throw new TypeError("max option must be a nonnegative integer");let q=t?Et(t):Array;if(!q)throw new Error("invalid max value: "+t);if(this.max=t,this.maxSize=p,this.maxEntrySize=S||this.maxSize,this.sizeCalculation=u||V,this.sizeCalculation){if(!this.maxSize&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(this.fetchMethod=g||null,this.fetchMethod&&typeof this.fetchMethod!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.fetchContext=v,!this.fetchMethod&&v!==void 0)throw new TypeError("cannot set fetchContext without fetchMethod");if(this.keyMap=new Map,this.keyList=new Array(t).fill(null),this.valList=new Array(t).fill(null),this.next=new q(t),this.prev=new q(t),this.head=0,this.tail=0,this.free=new Re(t),this.initialFill=1,this.size=0,typeof l=="function"&&(this.dispose=l),typeof h=="function"?(this.disposeAfter=h,this.disposed=[]):(this.disposeAfter=null,this.disposed=null),this.noDisposeOnSet=!!f,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!T,this.allowStaleOnFetchRejection=!!y,this.allowStaleOnFetchAbort=!!w,this.ignoreFetchAbort=!!m,this.maxEntrySize!==0){if(this.maxSize!==0&&!N(this.maxSize))throw new TypeError("maxSize must be a positive integer if specified");if(!N(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.initializeSizeTracking()}if(this.allowStale=!!c||!!M,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=N(r)||r===0?r:1,this.ttlAutopurge=!!n,this.ttl=i||z||0,this.ttl){if(!N(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.initializeTTLTracking()}if(this.max===0&&this.ttl===0&&this.maxSize===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.max&&!this.maxSize){let W="LRU_CACHE_UNBOUNDED";le(W)&&(we.add(W),yt("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",W,s))}M&&Ae("stale","allowStale"),z&&Ae("maxAge","ttl"),V&&Ae("length","sizeCalculation")}getRemainingTTL(e){return this.has(e,{updateAgeOnHas:!1})?1/0:0}initializeTTLTracking(){this.ttls=new j(this.max),this.starts=new j(this.max),this.setItemTTL=(i,r,n=X.now())=>{if(this.starts[i]=r!==0?n:0,this.ttls[i]=r,r!==0&&this.ttlAutopurge){let o=setTimeout(()=>{this.isStale(i)&&this.delete(this.keyList[i])},r+1);o.unref&&o.unref()}},this.updateItemAge=i=>{this.starts[i]=this.ttls[i]!==0?X.now():0},this.statusTTL=(i,r)=>{i&&(i.ttl=this.ttls[r],i.start=this.starts[r],i.now=e||t(),i.remainingTTL=i.now+i.ttl-i.start)};let e=0,t=()=>{let i=X.now();if(this.ttlResolution>0){e=i;let r=setTimeout(()=>e=0,this.ttlResolution);r.unref&&r.unref()}return i};this.getRemainingTTL=i=>{let r=this.keyMap.get(i);return r===void 0?0:this.ttls[r]===0||this.starts[r]===0?1/0:this.starts[r]+this.ttls[r]-(e||t())},this.isStale=i=>this.ttls[i]!==0&&this.starts[i]!==0&&(e||t())-this.starts[i]>this.ttls[i]}updateItemAge(e){}statusTTL(e,t){}setItemTTL(e,t,i){}isStale(e){return!1}initializeSizeTracking(){this.calculatedSize=0,this.sizes=new j(this.max),this.removeItemSize=e=>{this.calculatedSize-=this.sizes[e],this.sizes[e]=0},this.requireSize=(e,t,i,r)=>{if(this.isBackgroundFetch(t))return 0;if(!N(i))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(i=r(t,e),!N(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.addItemSize=(e,t,i)=>{if(this.sizes[e]=t,this.maxSize){let r=this.maxSize-this.sizes[e];for(;this.calculatedSize>r;)this.evict(!0)}this.calculatedSize+=this.sizes[e],i&&(i.entrySize=t,i.totalCalculatedSize=this.calculatedSize)}}removeItemSize(e){}addItemSize(e,t){}requireSize(e,t,i,r){if(i||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache")}*indexes({allowStale:e=this.allowStale}={}){if(this.size)for(let t=this.tail;!(!this.isValidIndex(t)||((e||!this.isStale(t))&&(yield t),t===this.head));)t=this.prev[t]}*rindexes({allowStale:e=this.allowStale}={}){if(this.size)for(let t=this.head;!(!this.isValidIndex(t)||((e||!this.isStale(t))&&(yield t),t===this.tail));)t=this.next[t]}isValidIndex(e){return e!==void 0&&this.keyMap.get(this.keyList[e])===e}*entries(){for(let e of this.indexes())this.valList[e]!==void 0&&this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield[this.keyList[e],this.valList[e]])}*rentries(){for(let e of this.rindexes())this.valList[e]!==void 0&&this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield[this.keyList[e],this.valList[e]])}*keys(){for(let e of this.indexes())this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.keyList[e])}*rkeys(){for(let e of this.rindexes())this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.keyList[e])}*values(){for(let e of this.indexes())this.valList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.valList[e])}*rvalues(){for(let e of this.rindexes())this.valList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.valList[e])}[Symbol.iterator](){return this.entries()}find(e,t){for(let i of this.indexes()){let r=this.valList[i],n=this.isBackgroundFetch(r)?r.__staleWhileFetching:r;if(n!==void 0&&e(n,this.keyList[i],this))return this.get(this.keyList[i],t)}}forEach(e,t=this){for(let i of this.indexes()){let r=this.valList[i],n=this.isBackgroundFetch(r)?r.__staleWhileFetching:r;n!==void 0&&e.call(t,n,this.keyList[i],this)}}rforEach(e,t=this){for(let i of this.rindexes()){let r=this.valList[i],n=this.isBackgroundFetch(r)?r.__staleWhileFetching:r;n!==void 0&&e.call(t,n,this.keyList[i],this)}}get prune(){return be("prune","purgeStale"),this.purgeStale}purgeStale(){let e=!1;for(let t of this.rindexes({allowStale:!0}))this.isStale(t)&&(this.delete(this.keyList[t]),e=!0);return e}dump(){let e=[];for(let t of this.indexes({allowStale:!0})){let i=this.keyList[t],r=this.valList[t],n=this.isBackgroundFetch(r)?r.__staleWhileFetching:r;if(n===void 0)continue;let o={value:n};if(this.ttls){o.ttl=this.ttls[t];let a=X.now()-this.starts[t];o.start=Math.floor(Date.now()-a)}this.sizes&&(o.size=this.sizes[t]),e.unshift([i,o])}return e}load(e){this.clear();for(let[t,i]of e){if(i.start){let r=Date.now()-i.start;i.start=X.now()-r}this.set(t,i.value,i)}}dispose(e,t,i){}set(e,t,{ttl:i=this.ttl,start:r,noDisposeOnSet:n=this.noDisposeOnSet,size:o=0,sizeCalculation:a=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,status:l}={}){if(o=this.requireSize(e,t,o,a),this.maxEntrySize&&o>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.delete(e),this;let h=this.size===0?void 0:this.keyMap.get(e);if(h===void 0)h=this.newIndex(),this.keyList[h]=e,this.valList[h]=t,this.keyMap.set(e,h),this.next[this.tail]=h,this.prev[h]=this.tail,this.tail=h,this.size++,this.addItemSize(h,o,l),l&&(l.set="add"),c=!1;else{this.moveToTail(h);let f=this.valList[h];if(t!==f){if(this.isBackgroundFetch(f)?f.__abortController.abort(new Error("replaced")):n||(this.dispose(f,e,"set"),this.disposeAfter&&this.disposed.push([f,e,"set"])),this.removeItemSize(h),this.valList[h]=t,this.addItemSize(h,o,l),l){l.set="replace";let d=f&&this.isBackgroundFetch(f)?f.__staleWhileFetching:f;d!==void 0&&(l.oldValue=d)}}else l&&(l.set="update")}if(i!==0&&this.ttl===0&&!this.ttls&&this.initializeTTLTracking(),c||this.setItemTTL(h,i,r),this.statusTTL(l,h),this.disposeAfter)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return this}newIndex(){return this.size===0?this.tail:this.size===this.max&&this.max!==0?this.evict(!1):this.free.length!==0?this.free.pop():this.initialFill++}pop(){if(this.size){let e=this.valList[this.head];return this.evict(!0),e}}evict(e){let t=this.head,i=this.keyList[t],r=this.valList[t];return this.isBackgroundFetch(r)?r.__abortController.abort(new Error("evicted")):(this.dispose(r,i,"evict"),this.disposeAfter&&this.disposed.push([r,i,"evict"])),this.removeItemSize(t),e&&(this.keyList[t]=null,this.valList[t]=null,this.free.push(t)),this.head=this.next[t],this.keyMap.delete(i),this.size--,t}has(e,{updateAgeOnHas:t=this.updateAgeOnHas,status:i}={}){let r=this.keyMap.get(e);if(r!==void 0)if(this.isStale(r))i&&(i.has="stale",this.statusTTL(i,r));else return t&&this.updateItemAge(r),i&&(i.has="hit"),this.statusTTL(i,r),!0;else i&&(i.has="miss");return!1}peek(e,{allowStale:t=this.allowStale}={}){let i=this.keyMap.get(e);if(i!==void 0&&(t||!this.isStale(i))){let r=this.valList[i];return this.isBackgroundFetch(r)?r.__staleWhileFetching:r}}backgroundFetch(e,t,i,r){let n=t===void 0?void 0:this.valList[t];if(this.isBackgroundFetch(n))return n;let o=new ae;i.signal&&i.signal.addEventListener("abort",()=>o.abort(i.signal.reason));let a={signal:o.signal,options:i,context:r},c=(p,S=!1)=>{let{aborted:u}=o.signal,g=i.ignoreFetchAbort&&p!==void 0;return i.status&&(u&&!S?(i.status.fetchAborted=!0,i.status.fetchError=o.signal.reason,g&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),u&&!g&&!S?h(o.signal.reason):(this.valList[t]===d&&(p===void 0?d.__staleWhileFetching?this.valList[t]=d.__staleWhileFetching:this.delete(e):(i.status&&(i.status.fetchUpdated=!0),this.set(e,p,a.options))),p)},l=p=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=p),h(p)),h=p=>{let{aborted:S}=o.signal,u=S&&i.allowStaleOnFetchAbort,g=u||i.allowStaleOnFetchRejection,v=g||i.noDeleteOnFetchRejection;if(this.valList[t]===d&&(!v||d.__staleWhileFetching===void 0?this.delete(e):u||(this.valList[t]=d.__staleWhileFetching)),g)return i.status&&d.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),d.__staleWhileFetching;if(d.__returned===d)throw p},f=(p,S)=>{this.fetchMethod(e,n,a).then(u=>p(u),S),o.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(p(),i.allowStaleOnFetchAbort&&(p=u=>c(u,!0)))})};i.status&&(i.status.fetchDispatched=!0);let d=new Promise(f).then(c,l);return d.__abortController=o,d.__staleWhileFetching=n,d.__returned=null,t===void 0?(this.set(e,d,{...a.options,status:void 0}),t=this.keyMap.get(e)):this.valList[t]=d,d}isBackgroundFetch(e){return e&&typeof e=="object"&&typeof e.then=="function"&&Object.prototype.hasOwnProperty.call(e,"__staleWhileFetching")&&Object.prototype.hasOwnProperty.call(e,"__returned")&&(e.__returned===e||e.__returned===null)}async fetch(e,{allowStale:t=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:n=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,fetchContext:S=this.fetchContext,forceRefresh:u=!1,status:g,signal:v}={}){if(!this.fetchMethod)return g&&(g.fetch="get"),this.get(e,{allowStale:t,updateAgeOnGet:i,noDeleteOnStaleGet:r,status:g});let T={allowStale:t,updateAgeOnGet:i,noDeleteOnStaleGet:r,ttl:n,noDisposeOnSet:o,size:a,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:h,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:p,ignoreFetchAbort:d,status:g,signal:v},A=this.keyMap.get(e);if(A===void 0){g&&(g.fetch="miss");let y=this.backgroundFetch(e,A,T,S);return y.__returned=y}else{let y=this.valList[A];if(this.isBackgroundFetch(y)){let M=t&&y.__staleWhileFetching!==void 0;return g&&(g.fetch="inflight",M&&(g.returnedStale=!0)),M?y.__staleWhileFetching:y.__returned=y}let w=this.isStale(A);if(!u&&!w)return g&&(g.fetch="hit"),this.moveToTail(A),i&&this.updateItemAge(A),this.statusTTL(g,A),y;let m=this.backgroundFetch(e,A,T,S),V=m.__staleWhileFetching!==void 0,z=V&&t;return g&&(g.fetch=V&&w?"stale":"refresh",z&&w&&(g.returnedStale=!0)),z?m.__staleWhileFetching:m.__returned=m}}get(e,{allowStale:t=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:n}={}){let o=this.keyMap.get(e);if(o!==void 0){let a=this.valList[o],c=this.isBackgroundFetch(a);return this.statusTTL(n,o),this.isStale(o)?(n&&(n.get="stale"),c?(n&&(n.returnedStale=t&&a.__staleWhileFetching!==void 0),t?a.__staleWhileFetching:void 0):(r||this.delete(e),n&&(n.returnedStale=t),t?a:void 0)):(n&&(n.get="hit"),c?a.__staleWhileFetching:(this.moveToTail(o),i&&this.updateItemAge(o),a))}else n&&(n.get="miss")}connect(e,t){this.prev[t]=e,this.next[e]=t}moveToTail(e){e!==this.tail&&(e===this.head?this.head=this.next[e]:this.connect(this.prev[e],this.next[e]),this.connect(this.tail,e),this.tail=e)}get del(){return be("del","delete"),this.delete}delete(e){let t=!1;if(this.size!==0){let i=this.keyMap.get(e);if(i!==void 0)if(t=!0,this.size===1)this.clear();else{this.removeItemSize(i);let r=this.valList[i];this.isBackgroundFetch(r)?r.__abortController.abort(new Error("deleted")):(this.dispose(r,e,"delete"),this.disposeAfter&&this.disposed.push([r,e,"delete"])),this.keyMap.delete(e),this.keyList[i]=null,this.valList[i]=null,i===this.tail?this.tail=this.prev[i]:i===this.head?this.head=this.next[i]:(this.next[this.prev[i]]=this.next[i],this.prev[this.next[i]]=this.prev[i]),this.size--,this.free.push(i)}}if(this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return t}clear(){for(let e of this.rindexes({allowStale:!0})){let t=this.valList[e];if(this.isBackgroundFetch(t))t.__abortController.abort(new Error("deleted"));else{let i=this.keyList[e];this.dispose(t,i,"delete"),this.disposeAfter&&this.disposed.push([t,i,"delete"])}}if(this.keyMap.clear(),this.valList.fill(null),this.keyList.fill(null),this.ttls&&(this.ttls.fill(0),this.starts.fill(0)),this.sizes&&this.sizes.fill(0),this.head=0,this.tail=0,this.initialFill=1,this.free.length=0,this.calculatedSize=0,this.size=0,this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift())}get reset(){return be("reset","clear"),this.clear}get length(){return yi("length","size"),this.size}static get AbortController(){return ae}static get AbortSignal(){return vt}},Pe=G;var ce=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 St=P(require("keyv")),Tt=require("keyv-file"),$=class{constructor(e={}){this.keyvFile=new Tt.KeyvFile(e),this.keyv=new St.default({store:this.keyvFile})}set(e,t){return this.keyv.set(e,t)}get(e){return this.keyv.get(e)}del(e){return this.keyv.delete(e)}keys(){return Promise.resolve(function*(e){for(let t of e)yield t}(this.keyvFile.keys()))}};var At=100;var bt="featureIdentifier",Rt="featureName",wt="variationIdentifier";var xt="target",Pt="SDK_VERSION",_t="SDK_TYPE",Ct="server",Ot="SDK_LANGUAGE",It="javascript",Ft="global",Z="segmentMatch",Lt="in",Dt="equal",kt="gt",Mt="starts_with",Bt="ends_with",Nt="contains",Ut="equal_sensitive",Ei="https://config.ff.harness.io/api/1.0",Si="https://events.ff.harness.io/api/1.0",Ti=1e3,Vt=60*Ti,Ai=1*Vt,bi=1*Vt,U={baseUrl:Ei,eventsUrl:Si,pollInterval:Ai,eventsSyncInterval:bi,enableStream:!0,enableAnalytics:!0,cache:new Pe({max:100}),store:new $,logger:new ce};var qt=P(zt());var he=class{constructor(e,t){this.query=e,this.log=t}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 r=[e,t].join(":");return parseInt((0,qt.default)(r).toString())%i+1}getNormalizedNumber(e,t){return this.getNormalizedNumberWithNormalizer(e,t,At)}isEnabled(e,t,i){let r=t,n=this.getAttrValue(e,r);if(!n){if(r="identifier",n=this.getAttrValue(e,r),!n)return!1;dt(t,n==null?void 0:n.toString(),this.log)}let o=this.getNormalizedNumber(r,n);return i>0&&o<=i}evaluateDistribution(e,t){if(!e)return;let i="",r=0;for(let n of e.variations)if(i=n.variation,r+=n.weight,this.isEnabled(t,e.bucketBy,r))return n.variation;return i}async isTargetIncludedOrExcludedInSegment(e,t){var i,r;for(let n of e){let o=await this.query.getSegment(n);if(o){if((i=o.excluded)!=null&&i.find(a=>a.identifier===t.identifier))return this.log.debug(`Target %s excluded from segment %s via exclude list
"use strict";var Ht=Object.create;var ee=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var Qt=Object.getPrototypeOf,Jt=Object.prototype.hasOwnProperty;var ge=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Le=(s,e)=>{for(var t in e)ee(s,t,{get:e[t],enumerable:!0})},De=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Yt(e))!Jt.call(s,r)&&r!==t&&ee(s,r,{get:()=>e[r],enumerable:!(i=Wt(e,r))||i.enumerable});return s};var P=(s,e,t)=>(t=s!=null?Ht(Qt(s)):{},De(e||!s||!s.__esModule?ee(t,"default",{value:s,enumerable:!0}):t,s)),Xt=s=>De(ee({},"__esModule",{value:!0}),s);var Ne=ge((Pi,Be)=>{"use strict";function pe(s){this.message=s}pe.prototype=new Error,pe.prototype.name="InvalidCharacterError";var ke=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(s){var e=String(s).replace(/=+$/,"");if(e.length%4==1)throw new pe("'atob' failed: The string to be decoded is not correctly encoded.");for(var t,i,r=0,n=0,o="";i=e.charAt(n++);~i&&(t=r%4?64*t+i:i,r++%4)?o+=String.fromCharCode(255&t>>(-2*r&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o};function Zt(s){var e=s.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(ke(t).replace(/(.)/g,function(i,r){var n=r.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}(e)}catch{return ke(e)}}function Y(s){this.message=s}function Me(s,e){if(typeof s!="string")throw new Y("Invalid token specified");var t=(e=e||{}).header===!0?0:1;try{return JSON.parse(Zt(s.split(".")[t]))}catch(i){throw new Y("Invalid token specified: "+i.message)}}Y.prototype=new Error,Y.prototype.name="InvalidTokenError";var de=Me;de.default=Me,de.InvalidTokenError=Y,Be.exports=de});var Ve=ge((_i,Ue)=>{"use strict";var ei=new Set(["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","HOSTNAME_MISMATCH"]);Ue.exports=s=>!ei.has(s&&s.code)});var zt=ge((vr,Ce)=>{"use strict";(function(){let s=this,e=n=>new TextEncoder().encode(n);function t(n,o){typeof n=="string"&&(n=e(n));let a=n.length,c=o^a,l=0,h;for(;a>=4;)h=n[l]&255|(n[++l]&255)<<8|(n[++l]&255)<<16|(n[++l]&255)<<24,h=(h&65535)*1540483477+(((h>>>16)*1540483477&65535)<<16),h^=h>>>24,h=(h&65535)*1540483477+(((h>>>16)*1540483477&65535)<<16),c=(c&65535)*1540483477+(((c>>>16)*1540483477&65535)<<16)^h,a-=4,++l;switch(a){case 3:c^=(n[l+2]&255)<<16;case 2:c^=(n[l+1]&255)<<8;case 1:c^=n[l]&255,c=(c&65535)*1540483477+(((c>>>16)*1540483477&65535)<<16)}return c^=c>>>13,c=(c&65535)*1540483477+(((c>>>16)*1540483477&65535)<<16),c^=c>>>15,c>>>0}function i(n,o){typeof n=="string"&&(n=e(n));let a,c,l,h,f,d,p,E,u,g;for(a=n.length&3,c=n.length-a,l=o,f=3432918353,p=461845907,g=0;g<c;)u=n[g]&255|(n[++g]&255)<<8|(n[++g]&255)<<16|(n[++g]&255)<<24,++g,u=(u&65535)*f+(((u>>>16)*f&65535)<<16)&4294967295,u=u<<15|u>>>17,u=(u&65535)*p+(((u>>>16)*p&65535)<<16)&4294967295,l^=u,l=l<<13|l>>>19,h=(l&65535)*5+(((l>>>16)*5&65535)<<16)&4294967295,l=(h&65535)+27492+(((h>>>16)+58964&65535)<<16);switch(u=0,a){case 3:u^=(n[g+2]&255)<<16;case 2:u^=(n[g+1]&255)<<8;case 1:u^=n[g]&255,u=(u&65535)*f+(((u>>>16)*f&65535)<<16)&4294967295,u=u<<15|u>>>17,u=(u&65535)*p+(((u>>>16)*p&65535)<<16)&4294967295,l^=u}return l^=n.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}let r=i;if(r.v2=t,r.v3=i,typeof Ce<"u")Ce.exports=r;else{let n=s.murmur;r.noConflict=function(){return s.murmur=n,r},s.murmur=r}})()});var wi={};Le(wi,{Client:()=>H,Event:()=>fe,FileStore:()=>$,LRU:()=>_e,default:()=>Ri});module.exports=Xt(wi);var jt=P(require("events")),Gt=P(Ne()),Ie=P(require("axios"));var Ge=P(Ve(),1);function ze(s,e,t,i,r,n,o){try{var a=s[n](o),c=a.value}catch(l){t(l);return}a.done?e(c):Promise.resolve(c).then(i,r)}function je(s){return function(){var e=this,t=arguments;return new Promise(function(i,r){var n=s.apply(e,t);function o(c){ze(n,i,r,o,a,"next",c)}function a(c){ze(n,i,r,o,a,"throw",c)}o(void 0)})}}function qe(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i)}return t}function me(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?qe(Object(t),!0).forEach(function(i){ti(s,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):qe(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i))})}return s}function ti(s,e,t){return e in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}var $e="axios-retry";function He(s){var e=["ERR_CANCELED","ECONNABORTED"];return!s.response&&!!s.code&&!e.includes(s.code)&&(0,Ge.default)(s)}var We=["get","head","options"],ii=We.concat(["put","delete"]);function ye(s){return s.code!=="ECONNABORTED"&&(!s.response||s.response.status>=500&&s.response.status<=599)}function ri(s){return s.config?ye(s)&&We.indexOf(s.config.method)!==-1:!1}function Ye(s){return s.config?ye(s)&&ii.indexOf(s.config.method)!==-1:!1}function Qe(s){return He(s)||Ye(s)}function si(){return 0}function ni(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1?arguments[1]:void 0,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:100,i=Math.pow(2,s)*t,r=i*.2*Math.random();return i+r}var oi={retries:3,retryCondition:Qe,retryDelay:si,shouldResetTimeout:!1,onRetry:()=>{}};function ai(s,e){return me(me(me({},oi),e),s[$e])}function Ke(s,e){var t=ai(s,e);return t.retryCount=t.retryCount||0,s[$e]=t,t}function li(s,e){s.defaults.agent===e.agent&&delete e.agent,s.defaults.httpAgent===e.httpAgent&&delete e.httpAgent,s.defaults.httpsAgent===e.httpsAgent&&delete e.httpsAgent}function ci(s,e){return ve.apply(this,arguments)}function ve(){return ve=je(function*(s,e){var{retries:t,retryCondition:i}=s,r=s.retryCount<t&&i(e);if(typeof r=="object")try{var n=yield r;return n!==!1}catch{return!1}return r}),ve.apply(this,arguments)}function _(s,e){var t=s.interceptors.request.use(r=>{var n=Ke(r,e);return n.lastRequestTime=Date.now(),r}),i=s.interceptors.response.use(null,function(){var r=je(function*(n){var{config:o}=n;if(!o)return Promise.reject(n);var a=Ke(o,e);if(yield ci(a,n)){a.retryCount+=1;var{retryDelay:c,shouldResetTimeout:l,onRetry:h}=a,f=c(a.retryCount,n);if(li(s,o),!l&&o.timeout&&a.lastRequestTime){var d=Date.now()-a.lastRequestTime,p=o.timeout-d-f;if(p<=0)return Promise.reject(n);o.timeout=p}return o.transformRequest=[E=>E],yield h(a.retryCount,n,o),new Promise(E=>setTimeout(()=>E(s(o)),f))}return Promise.reject(n)});return function(n){return r.apply(this,arguments)}}());return{requestInterceptorId:t,responseInterceptorId:i}}_.isNetworkError=He;_.isSafeRequestError=ri;_.isIdempotentRequestError=Ye;_.isNetworkOrIdempotentRequestError=Qe;_.exponentialDelay=ni;_.isRetryableError=ye;var L=P(require("axios"));var Je=P(require("axios")),x="http://localhost/api/1.0".replace(/\/+$/,"");var Q=class{constructor(e,t=x,i=Je.default){this.basePath=t;this.axios=i;e&&(this.configuration=e,this.basePath=e.basePath||this.basePath)}},te=class extends Error{constructor(t,i){super(i);this.field=t;this.name="RequiredError"}};var C="https://example.com",R=function(s,e,t){if(t==null)throw new te(e,`Required parameter ${e} was null or undefined when calling ${s}.`)};var k=async function(s,e){if(e&&e.accessToken){let t=typeof e.accessToken=="function"?await e.accessToken():await e.accessToken;s.Authorization="Bearer "+t}};var O=function(s,...e){let t=new URLSearchParams(s.search);for(let i of e)for(let r in i)if(Array.isArray(i[r])){t.delete(r);for(let n of i[r])t.append(r,n)}else t.set(r,i[r]);s.search=t.toString()},Ee=function(s,e,t){let i=typeof s!="string";return(i&&t&&t.isJsonMime?t.isJsonMime(e.headers["Content-Type"]):i)?JSON.stringify(s!==void 0?s:{}):s||""},I=function(s){return s.pathname+s.search+s.hash},F=function(s,e,t,i){return(r=e,n=t)=>{let o={...s.options,url:((i==null?void 0:i.basePath)||n)+s.url};return r.request(o)}};var hi=function(s){return{authenticate:async(e,t={})=>{let i="/client/auth",r=new URL(i,C),n;s&&(n=s.baseOptions);let o={method:"POST",...n,...t},a={},c={};a["Content-Type"]="application/json",O(r,c,t.query);let l=n&&n.headers?n.headers:{};return o.headers={...a,...l,...t.headers},o.data=Ee(e,o,s),{url:I(r),options:o}},getAllSegments:async(e,t,i={})=>{R("getAllSegments","environmentUUID",e);let r="/client/env/{environmentUUID}/target-segments".replace("{environmentUUID}",encodeURIComponent(String(e))),n=new URL(r,C),o;s&&(o=s.baseOptions);let a={method:"GET",...o,...i},c={},l={};await k(c,s),t!==void 0&&(l.cluster=t),O(n,l,i.query);let h=o&&o.headers?o.headers:{};return a.headers={...c,...h,...i.headers},{url:I(n),options:a}},getEvaluationByIdentifier:async(e,t,i,r,n={})=>{R("getEvaluationByIdentifier","environmentUUID",e),R("getEvaluationByIdentifier","feature",t),R("getEvaluationByIdentifier","target",i);let o="/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(o,C),c;s&&(c=s.baseOptions);let l={method:"GET",...c,...n},h={},f={};await k(h,s),r!==void 0&&(f.cluster=r),O(a,f,n.query);let d=c&&c.headers?c.headers:{};return l.headers={...h,...d,...n.headers},{url:I(a),options:l}},getEvaluations:async(e,t,i,r={})=>{R("getEvaluations","environmentUUID",e),R("getEvaluations","target",t);let n="/client/env/{environmentUUID}/target/{target}/evaluations".replace("{environmentUUID}",encodeURIComponent(String(e))).replace("{target}",encodeURIComponent(String(t))),o=new URL(n,C),a;s&&(a=s.baseOptions);let c={method:"GET",...a,...r},l={},h={};await k(l,s),i!==void 0&&(h.cluster=i),O(o,h,r.query);let f=a&&a.headers?a.headers:{};return c.headers={...l,...f,...r.headers},{url:I(o),options:c}},getFeatureConfig:async(e,t,i={})=>{R("getFeatureConfig","environmentUUID",e);let r="/client/env/{environmentUUID}/feature-configs".replace("{environmentUUID}",encodeURIComponent(String(e))),n=new URL(r,C),o;s&&(o=s.baseOptions);let a={method:"GET",...o,...i},c={},l={};await k(c,s),t!==void 0&&(l.cluster=t),O(n,l,i.query);let h=o&&o.headers?o.headers:{};return a.headers={...c,...h,...i.headers},{url:I(n),options:a}},getFeatureConfigByIdentifier:async(e,t,i,r={})=>{R("getFeatureConfigByIdentifier","identifier",e),R("getFeatureConfigByIdentifier","environmentUUID",t);let n="/client/env/{environmentUUID}/feature-configs/{identifier}".replace("{identifier}",encodeURIComponent(String(e))).replace("{environmentUUID}",encodeURIComponent(String(t))),o=new URL(n,C),a;s&&(a=s.baseOptions);let c={method:"GET",...a,...r},l={},h={};await k(l,s),i!==void 0&&(h.cluster=i),O(o,h,r.query);let f=a&&a.headers?a.headers:{};return c.headers={...l,...f,...r.headers},{url:I(o),options:c}},getSegmentByIdentifier:async(e,t,i,r={})=>{R("getSegmentByIdentifier","identifier",e),R("getSegmentByIdentifier","environmentUUID",t);let n="/client/env/{environmentUUID}/target-segments/{identifier}".replace("{identifier}",encodeURIComponent(String(e))).replace("{environmentUUID}",encodeURIComponent(String(t))),o=new URL(n,C),a;s&&(a=s.baseOptions);let c={method:"GET",...a,...r},l={},h={};await k(l,s),i!==void 0&&(h.cluster=i),O(o,h,r.query);let f=a&&a.headers?a.headers:{};return c.headers={...l,...f,...r.headers},{url:I(o),options:c}},stream:async(e,t,i={})=>{R("stream","aPIKey",e);let r="/stream",n=new URL(r,C),o;s&&(o=s.baseOptions);let a={method:"GET",...o,...i},c={},l={};await k(c,s),t!==void 0&&(l.cluster=t),e!=null&&(c["API-Key"]=String(e)),O(n,l,i.query);let h=o&&o.headers?o.headers:{};return a.headers={...c,...h,...i.headers},{url:I(n),options:a}}}},B=function(s){let e=hi(s);return{async authenticate(t,i){let r=await e.authenticate(t,i);return F(r,L.default,x,s)},async getAllSegments(t,i,r){let n=await e.getAllSegments(t,i,r);return F(n,L.default,x,s)},async getEvaluationByIdentifier(t,i,r,n,o){let a=await e.getEvaluationByIdentifier(t,i,r,n,o);return F(a,L.default,x,s)},async getEvaluations(t,i,r,n){let o=await e.getEvaluations(t,i,r,n);return F(o,L.default,x,s)},async getFeatureConfig(t,i,r){let n=await e.getFeatureConfig(t,i,r);return F(n,L.default,x,s)},async getFeatureConfigByIdentifier(t,i,r,n){let o=await e.getFeatureConfigByIdentifier(t,i,r,n);return F(o,L.default,x,s)},async getSegmentByIdentifier(t,i,r,n){let o=await e.getSegmentByIdentifier(t,i,r,n);return F(o,L.default,x,s)},async stream(t,i,r){let n=await e.stream(t,i,r);return F(n,L.default,x,s)}}};var ie=class extends Q{authenticate(e,t){return B(this.configuration).authenticate(e,t).then(i=>i(this.axios,this.basePath))}getAllSegments(e,t,i){return B(this.configuration).getAllSegments(e,t,i).then(r=>r(this.axios,this.basePath))}getEvaluationByIdentifier(e,t,i,r,n){return B(this.configuration).getEvaluationByIdentifier(e,t,i,r,n).then(o=>o(this.axios,this.basePath))}getEvaluations(e,t,i,r){return B(this.configuration).getEvaluations(e,t,i,r).then(n=>n(this.axios,this.basePath))}getFeatureConfig(e,t,i){return B(this.configuration).getFeatureConfig(e,t,i).then(r=>r(this.axios,this.basePath))}getFeatureConfigByIdentifier(e,t,i,r){return B(this.configuration).getFeatureConfigByIdentifier(e,t,i,r).then(n=>n(this.axios,this.basePath))}getSegmentByIdentifier(e,t,i,r){return B(this.configuration).getSegmentByIdentifier(e,t,i,r).then(n=>n(this.axios,this.basePath))}stream(e,t,i){return B(this.configuration).stream(e,t,i).then(r=>r(this.axios,this.basePath))}},ui=function(s){return{postMetrics:async(e,t,i,r={})=>{R("postMetrics","environment",e);let n="/metrics/{environment}".replace("{environment}",encodeURIComponent(String(e))),o=new URL(n,C),a;s&&(a=s.baseOptions);let c={method:"POST",...a,...r},l={},h={};await k(l,s),t!==void 0&&(h.cluster=t),l["Content-Type"]="application/json",O(o,h,r.query);let f=a&&a.headers?a.headers:{};return c.headers={...l,...f,...r.headers},c.data=Ee(i,c,s),{url:I(o),options:c}}}},fi=function(s){let e=ui(s);return{async postMetrics(t,i,r,n){let o=await e.postMetrics(t,i,r,n);return F(o,L.default,x,s)}}};var re=class extends Q{postMetrics(e,t,i,r){return fi(this.configuration).postMetrics(e,t,i,r).then(n=>n(this.axios,this.basePath))}};var K=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 se="1.4.1-rc.1";var Xe={1e3:"The SDK has successfully initialized",1001:"The SDK has failed to initialize due to an authentication error - defaults will be served",1002:"The SDK has failed to initialize due to a missing or empty API key - defaults will be served",2e3:"Authentication was successful",2001:"Authentication failed with a non-recoverable error",2002:"Authentication attempt failed:",2003:"Authentication failed and max retries have been exceeded",3e3:"Closing SDK",3001:"SDK Closed successfully",4e3:"Polling started, interval:",4001:"Polling stopped",5e3:"SSE stream successfully connected",5001:"SSE stream disconnected, reason:",5002:"SSE event received",5003:"SSE retrying to connect in",5004:"SSE stopped",6e3:"Evaluation successful: ",6001:"Evaluation Failed, returning default variation: ",6002:"BucketBy attribute not found in target attributes, falling back to 'identifier':",7e3:"Metrics thread started with request interval:",7001:"Metrics stopped",7002:"Posting metrics failed, reason:",7003:"Metrics posted successfully"};function gi(s){return s in Xe?Xe[s]:"Unknown SDK code"}function y(s,e=""){return`SDKCODE:${s}: ${gi(s)} ${e}`}function Ze(s){s.warn(y(1002))}function et(s,e){e.info(y(4e3,s/1e3+" seconds"))}function Se(s){s.info(y(1e3))}function tt(s){s.info(y(3e3))}function it(s){s.info(y(3001))}function Te(s){s.info(y(4001))}function rt(s){s.info(y(5e3))}function st(s){s.debug(y(5002))}function nt(s){s.info(y(5004))}function ot(s,e){e.info(y(7e3,s/1e3+" seconds"))}function at(s){s.info(y(7003))}function lt(s){s.info(y(7001))}function J(s,e,t,i){i.debug(y(6e3,`result=${s}, flag identifier=${e}, target=${JSON.stringify(t)}`))}function ct(s){s.warn(y(2001))}function ht(s){s.warn(y(1001))}function ut(s,e){e.warn(y(5001,s))}function ft(s,e){e.warn(y(5003,`${s}`))}function gt(s,e){e.warn(y(7002,s))}function D(s,e,t,i){i.warn(y(6001,`default variation used=${t}, flag=${s}, target=${JSON.stringify(e)}`))}function dt(s,e,t){t.warn(y(6002,`missing=${s}, using value=${e}`))}var ne=class{constructor(e,t,i,r,n,o){this.stopped=!0;this.initialized=!1;this.lastPollTime=0;this.api=i,this.options=r,this.environment=e,this.cluster=t,this.repository=o,this.eventBus=n,this.log=r.logger}poll(){if(this.stopped){this.log.info("PollingProcessor stopped"),Te(this.log);return}let e=new Date().getTime(),t=()=>{let i=new Date().getTime()-e,r=Math.max(this.options.pollInterval-i,0);this.timeout=setTimeout(()=>this.poll(),r)};if(this.lastPollTime>Date.now()-this.options.pollInterval){this.log.info(`Last poll was ${Math.round((Date.now()-this.lastPollTime)/1e3)} seconds ago, skipping flag refresh`),t();return}this.lastPollTime=Date.now(),Promise.all([this.retrieveFlags(),this.retrieveSegments()]).then(()=>{this.initialized||setTimeout(()=>{this.initialized=!0,this.eventBus.emit("poller_ready")},0)}).catch(i=>{this.eventBus.emit("poller_error",{error:i})}).finally(()=>{if(this.stopped){this.log.info("PollingProcessor stopped"),Te(this.log);return}t()})}async retrieveFlags(){try{this.log.debug("Fetching flags started");let e=await this.api.getFeatureConfig(this.environment,this.cluster);this.log.debug("Fetching flags finished"),e.data.forEach(t=>this.repository.setFlag(t.feature,t))}catch(e){throw this.log.error("Error loading flags",e),e}}async retrieveSegments(){try{this.log.debug("Fetching segments started");let e=await this.api.getAllSegments(this.environment,this.cluster);this.log.debug("Fetching segments finished"),e.data.forEach(t=>this.repository.setSegment(t.identifier,t))}catch(e){throw this.log.error("Error loading segments",e),e}}start(){if(!this.stopped){this.log.info("PollingProcessor already started");return}this.log.info("Starting PollingProcessor with request interval: ",this.options.pollInterval),this.stopped=!1,this.poll()}stop(){this.log.info("Stopping PollingProcessor"),this.stopped=!0}close(){this.log.info("Closing PollingProcessor"),this.stop(),clearTimeout(this.timeout),this.log.info("PollingProcessor closed")}};var pt=P(require("https")),mt=P(require("http"));var b=class b{constructor(e,t,i,r,n,o,a,c){this.retryAttempt=0;this.api=e,this.apiKey=t,this.environment=i,this.jwtToken=r,this.options=n,this.cluster=o,this.eventBus=a,this.repository=c,this.log=this.options.logger;let l=5e3,h=1e4;this.retryDelayMs=Math.floor(Math.random()*(h-l)+l)}start(){this.log.info("Starting new StreamProcessor");let e=`${this.options.baseUrl}/stream?cluster=${this.cluster}`,t={headers:{"Cache-Control":"no-cache",Accept:"text/event-stream",Authorization:`Bearer ${this.jwtToken}`,"API-Key":this.apiKey}},i=()=>{this.log.info(`SSE stream connected OK: ${e}`),this.retryAttempt=0,this.readyState=b.CONNECTED,this.eventBus.emit("stream_connected")},r=n=>{if(this.readyState!==b.CLOSED){this.retryAttempt+=1;let o=this.getRandomRetryDelayMs();ut(n,this.log),ft(o,this.log),this.readyState=b.RETRYING,this.eventBus.emit("stream_retrying"),setTimeout(()=>{this.log.info("SSE retrying to connect"),this.connect(e,t,i,r)},o)}};this.connect(e,t,i,r),this.eventBus.emit("stream_ready")}getRandomRetryDelayMs(){let e=this.retryDelayMs*this.retryAttempt;return Math.min(e,6e4)}connect(e,t,i,r){if(this.readyState===b.CONNECTED){this.log.debug("SSE already connected, skip retry");return}let n=e.startsWith("https:");this.log.debug("SSE HTTP start request",e),this.request=(n?pt.default:mt.default).request(e,t,o=>{if(this.log.debug("SSE got HTTP response code",o.statusCode),o.statusCode>=400&&o.statusCode<=599){r(`HTTP code ${o.statusCode}`);return}i(),o.on("data",a=>{this.processData(a)}).on("close",()=>{r("SSE stream closed")})}).on("error",o=>{r("SSE request failed "+o.message)}).on("timeout",()=>{r("SSE request timed out after "+b.SSE_TIMEOUT_MS+"ms")}).setTimeout(b.SSE_TIMEOUT_MS),this.request.end()}processData(e){let t=e.toString().split(/\r?\n/);if(t[0].startsWith(":")){this.log.debug("SSE Heartbeat received");return}t.forEach(i=>this.processLine(i))}processLine(e){if(e.startsWith("data:")){st(this.log),this.log.debug("SSE GOT:",e.substring(5));let t=JSON.parse(e.substring(5));t.domain==="flag"?this.msgProcessor(t,this.api.getFeatureConfigByIdentifier.bind(this.api),this.repository.setFlag.bind(this.repository),this.repository.deleteFlag.bind(this.repository)):t.domain==="target-segment"&&this.msgProcessor(t,this.api.getSegmentByIdentifier.bind(this.api),this.repository.setSegment.bind(this.repository),this.repository.deleteSegment.bind(this.repository))}}async msgProcessor(e,t,i,r){this.log.info("Processing message",e);try{if(e.event==="create"||e.event==="patch"){let{data:n}=await t(e.identifier,this.environment,this.cluster);i(e.identifier,n)}else e.event==="delete"&&r(e.identifier)}catch(n){throw this.log.error("Error while fetching data with identifier:",e.identifier,n),n}this.log.info("Processing message finished",e)}connected(){return this.readyState===b.CONNECTED}close(){if(this.readyState===b.CLOSED){this.log.info("SteamProcessor already closed");return}this.readyState=b.CLOSED,this.log.info("Closing StreamProcessor"),this.request.destroy(),this.request=void 0,this.eventBus.emit("stream_disconnected"),this.log.info("StreamProcessor closed"),nt(this.log)}};b.CONNECTED=1,b.RETRYING=2,b.CLOSED=3,b.SSE_TIMEOUT_MS=3e4;var oe=b;var _e={};Le(_e,{default:()=>Pe});var X=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,pi=typeof AbortController=="function",ae=pi?AbortController:class{constructor(){this.signal=new vt}abort(e=new Error("This operation was aborted")){this.signal.reason=this.signal.reason||e,this.signal.aborted=!0,this.signal.dispatchEvent({type:"abort",target:this.signal})}},mi=typeof AbortSignal=="function",vi=typeof ae.AbortSignal=="function",vt=mi?AbortSignal:vi?ae.AbortController:class{constructor(){this.reason=void 0,this.aborted=!1,this._listeners=[]}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,this.onabort(e),this._listeners.forEach(t=>t(e),this))}onabort(){}addEventListener(e,t){e==="abort"&&this._listeners.push(t)}removeEventListener(e,t){e==="abort"&&(this._listeners=this._listeners.filter(i=>i!==t))}},we=new Set,Ae=(s,e)=>{let t=`LRU_CACHE_OPTION_${s}`;le(t)&&xe(t,`${s} option`,`options.${e}`,G)},be=(s,e)=>{let t=`LRU_CACHE_METHOD_${s}`;if(le(t)){let{prototype:i}=G,{get:r}=Object.getOwnPropertyDescriptor(i,s);xe(t,`${s} method`,`cache.${e}()`,r)}},yi=(s,e)=>{let t=`LRU_CACHE_PROPERTY_${s}`;if(le(t)){let{prototype:i}=G,{get:r}=Object.getOwnPropertyDescriptor(i,s);xe(t,`${s} property`,`cache.${e}`,r)}},yt=(...s)=>{typeof process=="object"&&process&&typeof process.emitWarning=="function"?process.emitWarning(...s):console.error(...s)},le=s=>!we.has(s),xe=(s,e,t,i)=>{we.add(s);let r=`The ${e} is deprecated. Please use ${t} instead.`;yt(r,"DeprecationWarning",s,i)},N=s=>s&&s===Math.floor(s)&&s>0&&isFinite(s),Et=s=>N(s)?s<=Math.pow(2,8)?Uint8Array:s<=Math.pow(2,16)?Uint16Array:s<=Math.pow(2,32)?Uint32Array:s<=Number.MAX_SAFE_INTEGER?j:null:null,j=class extends Array{constructor(e){super(e),this.fill(0)}},Re=class{constructor(e){if(e===0)return[];let t=Et(e);this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},G=class s{constructor(e={}){let{max:t=0,ttl:i,ttlResolution:r=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:c,dispose:l,disposeAfter:h,noDisposeOnSet:f,noUpdateTTL:d,maxSize:p=0,maxEntrySize:E=0,sizeCalculation:u,fetchMethod:g,fetchContext:T,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:v,allowStaleOnFetchAbort:w,ignoreFetchAbort:m}=e,{length:V,maxAge:z,stale:M}=e instanceof s?{}:e;if(t!==0&&!N(t))throw new TypeError("max option must be a nonnegative integer");let q=t?Et(t):Array;if(!q)throw new Error("invalid max value: "+t);if(this.max=t,this.maxSize=p,this.maxEntrySize=E||this.maxSize,this.sizeCalculation=u||V,this.sizeCalculation){if(!this.maxSize&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(this.fetchMethod=g||null,this.fetchMethod&&typeof this.fetchMethod!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.fetchContext=T,!this.fetchMethod&&T!==void 0)throw new TypeError("cannot set fetchContext without fetchMethod");if(this.keyMap=new Map,this.keyList=new Array(t).fill(null),this.valList=new Array(t).fill(null),this.next=new q(t),this.prev=new q(t),this.head=0,this.tail=0,this.free=new Re(t),this.initialFill=1,this.size=0,typeof l=="function"&&(this.dispose=l),typeof h=="function"?(this.disposeAfter=h,this.disposed=[]):(this.disposeAfter=null,this.disposed=null),this.noDisposeOnSet=!!f,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!v,this.allowStaleOnFetchAbort=!!w,this.ignoreFetchAbort=!!m,this.maxEntrySize!==0){if(this.maxSize!==0&&!N(this.maxSize))throw new TypeError("maxSize must be a positive integer if specified");if(!N(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.initializeSizeTracking()}if(this.allowStale=!!c||!!M,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=N(r)||r===0?r:1,this.ttlAutopurge=!!n,this.ttl=i||z||0,this.ttl){if(!N(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.initializeTTLTracking()}if(this.max===0&&this.ttl===0&&this.maxSize===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.max&&!this.maxSize){let W="LRU_CACHE_UNBOUNDED";le(W)&&(we.add(W),yt("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",W,s))}M&&Ae("stale","allowStale"),z&&Ae("maxAge","ttl"),V&&Ae("length","sizeCalculation")}getRemainingTTL(e){return this.has(e,{updateAgeOnHas:!1})?1/0:0}initializeTTLTracking(){this.ttls=new j(this.max),this.starts=new j(this.max),this.setItemTTL=(i,r,n=X.now())=>{if(this.starts[i]=r!==0?n:0,this.ttls[i]=r,r!==0&&this.ttlAutopurge){let o=setTimeout(()=>{this.isStale(i)&&this.delete(this.keyList[i])},r+1);o.unref&&o.unref()}},this.updateItemAge=i=>{this.starts[i]=this.ttls[i]!==0?X.now():0},this.statusTTL=(i,r)=>{i&&(i.ttl=this.ttls[r],i.start=this.starts[r],i.now=e||t(),i.remainingTTL=i.now+i.ttl-i.start)};let e=0,t=()=>{let i=X.now();if(this.ttlResolution>0){e=i;let r=setTimeout(()=>e=0,this.ttlResolution);r.unref&&r.unref()}return i};this.getRemainingTTL=i=>{let r=this.keyMap.get(i);return r===void 0?0:this.ttls[r]===0||this.starts[r]===0?1/0:this.starts[r]+this.ttls[r]-(e||t())},this.isStale=i=>this.ttls[i]!==0&&this.starts[i]!==0&&(e||t())-this.starts[i]>this.ttls[i]}updateItemAge(e){}statusTTL(e,t){}setItemTTL(e,t,i){}isStale(e){return!1}initializeSizeTracking(){this.calculatedSize=0,this.sizes=new j(this.max),this.removeItemSize=e=>{this.calculatedSize-=this.sizes[e],this.sizes[e]=0},this.requireSize=(e,t,i,r)=>{if(this.isBackgroundFetch(t))return 0;if(!N(i))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(i=r(t,e),!N(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.addItemSize=(e,t,i)=>{if(this.sizes[e]=t,this.maxSize){let r=this.maxSize-this.sizes[e];for(;this.calculatedSize>r;)this.evict(!0)}this.calculatedSize+=this.sizes[e],i&&(i.entrySize=t,i.totalCalculatedSize=this.calculatedSize)}}removeItemSize(e){}addItemSize(e,t){}requireSize(e,t,i,r){if(i||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache")}*indexes({allowStale:e=this.allowStale}={}){if(this.size)for(let t=this.tail;!(!this.isValidIndex(t)||((e||!this.isStale(t))&&(yield t),t===this.head));)t=this.prev[t]}*rindexes({allowStale:e=this.allowStale}={}){if(this.size)for(let t=this.head;!(!this.isValidIndex(t)||((e||!this.isStale(t))&&(yield t),t===this.tail));)t=this.next[t]}isValidIndex(e){return e!==void 0&&this.keyMap.get(this.keyList[e])===e}*entries(){for(let e of this.indexes())this.valList[e]!==void 0&&this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield[this.keyList[e],this.valList[e]])}*rentries(){for(let e of this.rindexes())this.valList[e]!==void 0&&this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield[this.keyList[e],this.valList[e]])}*keys(){for(let e of this.indexes())this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.keyList[e])}*rkeys(){for(let e of this.rindexes())this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.keyList[e])}*values(){for(let e of this.indexes())this.valList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.valList[e])}*rvalues(){for(let e of this.rindexes())this.valList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.valList[e])}[Symbol.iterator](){return this.entries()}find(e,t){for(let i of this.indexes()){let r=this.valList[i],n=this.isBackgroundFetch(r)?r.__staleWhileFetching:r;if(n!==void 0&&e(n,this.keyList[i],this))return this.get(this.keyList[i],t)}}forEach(e,t=this){for(let i of this.indexes()){let r=this.valList[i],n=this.isBackgroundFetch(r)?r.__staleWhileFetching:r;n!==void 0&&e.call(t,n,this.keyList[i],this)}}rforEach(e,t=this){for(let i of this.rindexes()){let r=this.valList[i],n=this.isBackgroundFetch(r)?r.__staleWhileFetching:r;n!==void 0&&e.call(t,n,this.keyList[i],this)}}get prune(){return be("prune","purgeStale"),this.purgeStale}purgeStale(){let e=!1;for(let t of this.rindexes({allowStale:!0}))this.isStale(t)&&(this.delete(this.keyList[t]),e=!0);return e}dump(){let e=[];for(let t of this.indexes({allowStale:!0})){let i=this.keyList[t],r=this.valList[t],n=this.isBackgroundFetch(r)?r.__staleWhileFetching:r;if(n===void 0)continue;let o={value:n};if(this.ttls){o.ttl=this.ttls[t];let a=X.now()-this.starts[t];o.start=Math.floor(Date.now()-a)}this.sizes&&(o.size=this.sizes[t]),e.unshift([i,o])}return e}load(e){this.clear();for(let[t,i]of e){if(i.start){let r=Date.now()-i.start;i.start=X.now()-r}this.set(t,i.value,i)}}dispose(e,t,i){}set(e,t,{ttl:i=this.ttl,start:r,noDisposeOnSet:n=this.noDisposeOnSet,size:o=0,sizeCalculation:a=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,status:l}={}){if(o=this.requireSize(e,t,o,a),this.maxEntrySize&&o>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.delete(e),this;let h=this.size===0?void 0:this.keyMap.get(e);if(h===void 0)h=this.newIndex(),this.keyList[h]=e,this.valList[h]=t,this.keyMap.set(e,h),this.next[this.tail]=h,this.prev[h]=this.tail,this.tail=h,this.size++,this.addItemSize(h,o,l),l&&(l.set="add"),c=!1;else{this.moveToTail(h);let f=this.valList[h];if(t!==f){if(this.isBackgroundFetch(f)?f.__abortController.abort(new Error("replaced")):n||(this.dispose(f,e,"set"),this.disposeAfter&&this.disposed.push([f,e,"set"])),this.removeItemSize(h),this.valList[h]=t,this.addItemSize(h,o,l),l){l.set="replace";let d=f&&this.isBackgroundFetch(f)?f.__staleWhileFetching:f;d!==void 0&&(l.oldValue=d)}}else l&&(l.set="update")}if(i!==0&&this.ttl===0&&!this.ttls&&this.initializeTTLTracking(),c||this.setItemTTL(h,i,r),this.statusTTL(l,h),this.disposeAfter)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return this}newIndex(){return this.size===0?this.tail:this.size===this.max&&this.max!==0?this.evict(!1):this.free.length!==0?this.free.pop():this.initialFill++}pop(){if(this.size){let e=this.valList[this.head];return this.evict(!0),e}}evict(e){let t=this.head,i=this.keyList[t],r=this.valList[t];return this.isBackgroundFetch(r)?r.__abortController.abort(new Error("evicted")):(this.dispose(r,i,"evict"),this.disposeAfter&&this.disposed.push([r,i,"evict"])),this.removeItemSize(t),e&&(this.keyList[t]=null,this.valList[t]=null,this.free.push(t)),this.head=this.next[t],this.keyMap.delete(i),this.size--,t}has(e,{updateAgeOnHas:t=this.updateAgeOnHas,status:i}={}){let r=this.keyMap.get(e);if(r!==void 0)if(this.isStale(r))i&&(i.has="stale",this.statusTTL(i,r));else return t&&this.updateItemAge(r),i&&(i.has="hit"),this.statusTTL(i,r),!0;else i&&(i.has="miss");return!1}peek(e,{allowStale:t=this.allowStale}={}){let i=this.keyMap.get(e);if(i!==void 0&&(t||!this.isStale(i))){let r=this.valList[i];return this.isBackgroundFetch(r)?r.__staleWhileFetching:r}}backgroundFetch(e,t,i,r){let n=t===void 0?void 0:this.valList[t];if(this.isBackgroundFetch(n))return n;let o=new ae;i.signal&&i.signal.addEventListener("abort",()=>o.abort(i.signal.reason));let a={signal:o.signal,options:i,context:r},c=(p,E=!1)=>{let{aborted:u}=o.signal,g=i.ignoreFetchAbort&&p!==void 0;return i.status&&(u&&!E?(i.status.fetchAborted=!0,i.status.fetchError=o.signal.reason,g&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),u&&!g&&!E?h(o.signal.reason):(this.valList[t]===d&&(p===void 0?d.__staleWhileFetching?this.valList[t]=d.__staleWhileFetching:this.delete(e):(i.status&&(i.status.fetchUpdated=!0),this.set(e,p,a.options))),p)},l=p=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=p),h(p)),h=p=>{let{aborted:E}=o.signal,u=E&&i.allowStaleOnFetchAbort,g=u||i.allowStaleOnFetchRejection,T=g||i.noDeleteOnFetchRejection;if(this.valList[t]===d&&(!T||d.__staleWhileFetching===void 0?this.delete(e):u||(this.valList[t]=d.__staleWhileFetching)),g)return i.status&&d.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),d.__staleWhileFetching;if(d.__returned===d)throw p},f=(p,E)=>{this.fetchMethod(e,n,a).then(u=>p(u),E),o.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(p(),i.allowStaleOnFetchAbort&&(p=u=>c(u,!0)))})};i.status&&(i.status.fetchDispatched=!0);let d=new Promise(f).then(c,l);return d.__abortController=o,d.__staleWhileFetching=n,d.__returned=null,t===void 0?(this.set(e,d,{...a.options,status:void 0}),t=this.keyMap.get(e)):this.valList[t]=d,d}isBackgroundFetch(e){return e&&typeof e=="object"&&typeof e.then=="function"&&Object.prototype.hasOwnProperty.call(e,"__staleWhileFetching")&&Object.prototype.hasOwnProperty.call(e,"__returned")&&(e.__returned===e||e.__returned===null)}async fetch(e,{allowStale:t=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:n=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,fetchContext:E=this.fetchContext,forceRefresh:u=!1,status:g,signal:T}={}){if(!this.fetchMethod)return g&&(g.fetch="get"),this.get(e,{allowStale:t,updateAgeOnGet:i,noDeleteOnStaleGet:r,status:g});let S={allowStale:t,updateAgeOnGet:i,noDeleteOnStaleGet:r,ttl:n,noDisposeOnSet:o,size:a,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:h,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:p,ignoreFetchAbort:d,status:g,signal:T},A=this.keyMap.get(e);if(A===void 0){g&&(g.fetch="miss");let v=this.backgroundFetch(e,A,S,E);return v.__returned=v}else{let v=this.valList[A];if(this.isBackgroundFetch(v)){let M=t&&v.__staleWhileFetching!==void 0;return g&&(g.fetch="inflight",M&&(g.returnedStale=!0)),M?v.__staleWhileFetching:v.__returned=v}let w=this.isStale(A);if(!u&&!w)return g&&(g.fetch="hit"),this.moveToTail(A),i&&this.updateItemAge(A),this.statusTTL(g,A),v;let m=this.backgroundFetch(e,A,S,E),V=m.__staleWhileFetching!==void 0,z=V&&t;return g&&(g.fetch=V&&w?"stale":"refresh",z&&w&&(g.returnedStale=!0)),z?m.__staleWhileFetching:m.__returned=m}}get(e,{allowStale:t=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:n}={}){let o=this.keyMap.get(e);if(o!==void 0){let a=this.valList[o],c=this.isBackgroundFetch(a);return this.statusTTL(n,o),this.isStale(o)?(n&&(n.get="stale"),c?(n&&(n.returnedStale=t&&a.__staleWhileFetching!==void 0),t?a.__staleWhileFetching:void 0):(r||this.delete(e),n&&(n.returnedStale=t),t?a:void 0)):(n&&(n.get="hit"),c?a.__staleWhileFetching:(this.moveToTail(o),i&&this.updateItemAge(o),a))}else n&&(n.get="miss")}connect(e,t){this.prev[t]=e,this.next[e]=t}moveToTail(e){e!==this.tail&&(e===this.head?this.head=this.next[e]:this.connect(this.prev[e],this.next[e]),this.connect(this.tail,e),this.tail=e)}get del(){return be("del","delete"),this.delete}delete(e){let t=!1;if(this.size!==0){let i=this.keyMap.get(e);if(i!==void 0)if(t=!0,this.size===1)this.clear();else{this.removeItemSize(i);let r=this.valList[i];this.isBackgroundFetch(r)?r.__abortController.abort(new Error("deleted")):(this.dispose(r,e,"delete"),this.disposeAfter&&this.disposed.push([r,e,"delete"])),this.keyMap.delete(e),this.keyList[i]=null,this.valList[i]=null,i===this.tail?this.tail=this.prev[i]:i===this.head?this.head=this.next[i]:(this.next[this.prev[i]]=this.next[i],this.prev[this.next[i]]=this.prev[i]),this.size--,this.free.push(i)}}if(this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return t}clear(){for(let e of this.rindexes({allowStale:!0})){let t=this.valList[e];if(this.isBackgroundFetch(t))t.__abortController.abort(new Error("deleted"));else{let i=this.keyList[e];this.dispose(t,i,"delete"),this.disposeAfter&&this.disposed.push([t,i,"delete"])}}if(this.keyMap.clear(),this.valList.fill(null),this.keyList.fill(null),this.ttls&&(this.ttls.fill(0),this.starts.fill(0)),this.sizes&&this.sizes.fill(0),this.head=0,this.tail=0,this.initialFill=1,this.free.length=0,this.calculatedSize=0,this.size=0,this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift())}get reset(){return be("reset","clear"),this.clear}get length(){return yi("length","size"),this.size}static get AbortController(){return ae}static get AbortSignal(){return vt}},Pe=G;var ce=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 St=P(require("keyv")),Tt=require("keyv-file"),$=class{constructor(e={}){this.keyvFile=new Tt.KeyvFile(e),this.keyv=new St.default({store:this.keyvFile})}set(e,t){return this.keyv.set(e,t)}get(e){return this.keyv.get(e)}del(e){return this.keyv.delete(e)}keys(){return Promise.resolve(function*(e){for(let t of e)yield t}(this.keyvFile.keys()))}};var At=100;var bt="featureIdentifier",Rt="featureName",wt="variationIdentifier";var xt="target",Pt="SDK_VERSION",_t="SDK_TYPE",Ct="server",Ot="SDK_LANGUAGE",It="javascript",Ft="global",Z="segmentMatch",Lt="in",Dt="equal",kt="gt",Mt="starts_with",Bt="ends_with",Nt="contains",Ut="equal_sensitive",Ei="https://config.ff.harness.io/api/1.0",Si="https://events.ff.harness.io/api/1.0",Ti=1e3,Vt=60*Ti,Ai=1*Vt,bi=1*Vt,U={baseUrl:Ei,eventsUrl:Si,pollInterval:Ai,eventsSyncInterval:bi,enableStream:!0,enableAnalytics:!0,cache:new Pe({max:100}),store:new $,logger:new ce};var qt=P(zt());var he=class{constructor(e,t){this.query=e,this.log=t}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 r=[e,t].join(":");return parseInt((0,qt.default)(r).toString())%i+1}getNormalizedNumber(e,t){return this.getNormalizedNumberWithNormalizer(e,t,At)}isEnabled(e,t,i){let r=t,n=this.getAttrValue(e,r);if(!n){if(r="identifier",n=this.getAttrValue(e,r),!n)return!1;dt(t,n==null?void 0:n.toString(),this.log)}let o=this.getNormalizedNumber(r,n);return i>0&&o<=i}evaluateDistribution(e,t){if(!e)return;let i="",r=0;for(let n of e.variations)if(i=n.variation,r+=n.weight,this.isEnabled(t,e.bucketBy,r))return n.variation;return i}async isTargetIncludedOrExcludedInSegment(e,t){var i,r;for(let n of e){let o=await this.query.getSegment(n);if(o){if((i=o.excluded)!=null&&i.find(a=>a.identifier===t.identifier))return this.log.debug(`Target %s excluded from segment %s via exclude list
`,t.name,o.name),!1;if((r=o.included)!=null&&r.find(a=>a.identifier===t.identifier))return this.log.debug(`Target %s included in segment %s via include list
`,t.name,o.name),!0;if(o.rules&&await this.evaluateClauses(o.rules,t))return this.log.debug(`Target %s included in segment %s via rules
`,t.name,o.name),!0}}return!1}async evaluateClause(e,t){var o;if(!(e!=null&&e.op)||!((o=e==null?void 0:e.values)!=null&&o.length))return!1;let i=this.getAttrValue(t,e.attribute),r=i==null?void 0:i.toString();if(e.op!==Z&&!r)return!1;let n=e.values[0];switch(e.op){case Lt:for(let a of e.values)if(a==r)return!0;return!1;case Dt:return r.toLowerCase()==n.toLowerCase();case Ut:return r==n;case kt:return r>n;case Mt:return r.startsWith(n);case Bt:return r.endsWith(n);case Nt:return r.includes(n);case Z:return await this.isTargetIncludedOrExcludedInSegment(e.values,t)}return!1}async evaluateClauses(e,t){for(let i of e)if(await this.evaluateClause(i,t))return!0;return!1}evaluateRule(e,t){return this.evaluateClauses(e.clauses,t)}async evaluateRules(e,t){if(!t||!e)return;e.sort((r,n)=>r.priority>n.priority?1:-1);let i;for(let r of e)if(await this.evaluateRule(r,t))return r.serve.distribution&&(i=this.evaluateDistribution(r.serve.distribution,t)),r.serve.variation&&(i=r.serve.variation),i}async evaluateVariationMap(e,t){var i;if(!(!t||!e))for(let r of e){if((i=r.targets)==null?void 0:i.find(a=>a.identifier===t.identifier))return r.variation;let o=r.targetSegments;if(o&&await this.isTargetIncludedOrExcludedInSegment(o,t))return r.variation}}async evaluateFlag(e,t){let i=e.offVariation;return e.state==="on"&&(i=await 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){this.log.info("Checking pre requisites %s of parent feature %s",e.prerequisites,e.feature);for(let i of e.prerequisites){let r=await this.query.getFlag(i.feature);if(!r)return this.log.warn("Could not retrieve the pre requisite details of feature flag: %s",e.feature),!0;let n=await this.evaluateFlag(r,t);return this.log.info("Pre requisite flag %s has variation %s for target %s",r.feature,n,t),this.log.info("Pre requisite flag %s should have the variations %s",r.feature,i.variations),i.variations.includes(n.identifier)?await this.checkPreRequisite(r,t):!1}}return!0}async evaluate(e,t,i,r){let n=await this.query.getFlag(e);if(!n||n.kind!==i)return;if(n.prerequisites&&!await this.checkPreRequisite(n,t))return this.findVariation(n.variations,n.offVariation);let o=await this.evaluateFlag(n,t);if(o)return r&&r(n,t,o),o}async boolVariation(e,t,i=!1,r){let n=await this.evaluate(e,t,"boolean",r);if(n){let o=n.value.toLowerCase()==="true";return J(`${o}`,e,t,this.log),o}return D(e,t,i.toString(),this.log),i}async stringVariation(e,t,i="",r){let n=await this.evaluate(e,t,"string",r);return n?(J(`${n.value}`,e,t,this.log),n.value):(D(e,t,i.toString(),this.log),i)}async numberVariation(e,t,i=0,r){let n=await this.evaluate(e,t,"int",r);if(n){let o=parseFloat(n.value);return J(`${o}`,e,t,this.log),o}return D(e,t,i.toString(),this.log),i}async jsonVariation(e,t,i={},r){let n=await this.evaluate(e,t,"json",r);return n?(J(`${n.value}`,e,t,this.log),JSON.parse(n.value)):(D(e,t,i.toString(),this.log),i)}};var Oe=(r=>(r.FLAG_STORED="flag_stored",r.FLAG_DELETED="flag_deleted",r.SEGMENT_STORED="segment_stored",r.SEGMENT_DELETED="segment_deleted",r))(Oe||{}),ue=class{constructor(e,t,i){if(!e)throw new Error("Cache is required argument and cannot be undefined");this.eventBus=i,this.cache=e,this.store=t}async setFlag(e,t){if(await this.isFlagOutdated(e,t))return;let i=this.formatFlagKey(e);this.store?(await this.store.set(i,t),this.cache.delete(i)):this.cache.set(i,t),this.eventBus&&this.eventBus.emit("flag_stored",e)}async setSegment(e,t){if(await this.isSegmentOutdated(e,t))return;let i=this.formatSegmentKey(e);this.store?(await this.store.set(i,t),this.cache.delete(i)):this.cache.set(i,t),this.eventBus&&this.eventBus.emit("segment_stored",e)}async deleteFlag(e){let t=this.formatFlagKey(e);this.store&&await this.store.del(t),this.cache.delete(t),this.eventBus&&this.eventBus.emit("flag_deleted",e)}async deleteSegment(e){let t=this.formatSegmentKey(e);this.store&&await this.store.del(t),this.cache.delete(t),this.eventBus&&this.eventBus.emit("segment_deleted",e)}async getFlag(e,t=!0){let i=this.formatFlagKey(e),r=this.cache.get(i);if(r)return r;if(this.store)return r=await this.store.get(i),r&&t&&this.cache.set(i,r),r}async getSegment(e,t=!0){let i=this.formatSegmentKey(e),r=this.cache.get(i);if(r)return r;if(this.store)return r=await this.store.get(i),r&&t&&this.cache.set(i,r),r}async findFlagsBySegment(e){let t=[],i=this.cache.keys();this.store&&(i=await this.store.keys());for(let r of i){let n=await this.getFlag(r);if(!n)return[];for(let o of n==null?void 0:n.rules)for(let a of o==null?void 0:o.clauses)a.op===Z&&a.values.includes(e)&&t.push(n.feature)}return t}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 Kt=(s,e="1",t,i,r,n=!1)=>{let o=new Map,a,c=new K({...t,basePath:i.eventsUrl}),l=new re(c),h=i.logger,f=(v,T,A)=>{let y={target:v,featureConfig:T,variation:A,count:0},w=d(y),m=o.get(w);m?m.count++:(y.count=1,o.set(w,y))},d=v=>{let T=v.featureConfig.feature,A=v.variation.identifier,y=v.variation.value;return`${T}/${A}/${y}/${Ft}`},p=()=>{var y,w;if(!o){h.debug("No metrics data!");return}let v=[],T=[],A=new Map(o);o.clear();for(let m of A.values()){if(m.target&&!m.target.anonymous){let M=[];m.target.attributes&&(M=Object.entries(m.target.attributes).map(([Fe,$t])=>({key:Fe,value:$t})));let q=m.target.identifier;m.target.name&&(q=m.target.name);let W={identifier:m.target.identifier,name:q,attributes:M};v.push(W)}let V=[{key:bt,value:m.featureConfig.feature},{key:Rt,value:m.featureConfig.feature},{key:wt,value:m.variation.identifier},{key:_t,value:Ct},{key:Ot,value:It},{key:Pt,value:se},{key:xt,value:(w=(y=m==null?void 0:m.target)==null?void 0:y.identifier)!=null?w:null}],z={timestamp:Date.now(),count:m.count,metricsType:"FFMETRICS",attributes:V};T.push(z)}return{targetData:v,metricsData:T}},S=()=>{if(n)return;let v=p();v&&v.metricsData.length&&v.targetData.length&&(h.debug("Start sending metrics data"),l.postMetrics(s,e,v).then(T=>{h.debug("Metrics server returns: ",T.status),at(h),T.status>=400&&h.error("Error while sending metrics data with status code: ",T.status)}).catch(T=>{gt(`${T}`,h),h.debug("Metrics server returns error: ",T)}))};return{start:()=>{h.info("Starting MetricsProcessor with request interval: ",i.eventsSyncInterval),a=setInterval(S,i.eventsSyncInterval),r.emit("metrics_ready")},close:()=>{h.info("Closing MetricsProcessor"),clearInterval(a),S(),n=!0,h.info("MetricsProcessor closed"),lt(h)},enqueue:f}};Ie.default.defaults.timeout=3e4;_(Ie.default,{retries:3,retryDelay:_.exponentialDelay});var fe=(i=>(i.READY="ready",i.FAILED="failed",i.CHANGED="changed",i))(fe||{}),H=class{constructor(e,t={}){this.cluster="1";this.eventBus=new jt.default;this.initialized=!1;this.failure=!1;this.pollerReady=!1;this.streamReady=!1;this.metricReady=!1;this.closing=!1;this.sdkKey=e,this.options={...U,...t},this.log=this.options.logger,t.pollInterval<U.pollInterval&&(this.options.pollInterval=U.pollInterval,this.log.warn(`Polling interval cannot be lower than ${U.pollInterval} ms`)),t.eventsSyncInterval<U.eventsSyncInterval&&(this.options.eventsSyncInterval=U.eventsSyncInterval,this.log.warn(`Events sync interval cannot be lower than ${U.eventsSyncInterval} ms`)),this.configuration=new K({basePath:this.options.baseUrl,baseOptions:{headers:{"User-Agent":`NodeJsSDK/${se}`}}}),this.repository=new ue(this.options.cache,this.options.store,this.eventBus),this.evaluator=new he(this.repository,this.log),this.api=new ie(this.configuration),this.processEvents(),this.run()}processEvents(){this.eventBus.on("poller_ready",()=>{this.initialize(0)}),this.eventBus.on("poller_error",()=>{this.failure=!0,this.eventBus.emit("failed")}),this.eventBus.on("stream_ready",()=>{this.initialize(1)}),this.eventBus.on("stream_retrying",()=>{this.failure=!0,this.log.error("Issue with streaming: falling back to polling while the SDK attempts to reconnect"),this.closing||this.pollProcessor.start()}),this.eventBus.on("stream_error",()=>{this.failure=!0,this.log.error("Unrecoverable issue with streaming: falling back to polling"),this.closing||this.pollProcessor.start(),this.eventBus.emit("failed")}),this.eventBus.on("metrics_ready",()=>{this.initialize(2)}),this.eventBus.on("metrics_error",()=>{this.failure=!0,this.eventBus.emit("failed")}),this.eventBus.on("stream_connected",()=>{this.pollProcessor.stop()}),this.eventBus.on("stream_disconnected",()=>{this.closing||this.pollProcessor.start()});for(let e of Object.values(Oe))this.eventBus.on(e,t=>{switch(e){case"flag_stored":case"flag_deleted":this.eventBus.emit("changed",t);break;case"segment_stored":case"segment_deleted":this.repository.findFlagsBySegment(t).then(i=>{i.forEach(r=>this.eventBus.emit("changed",r))});break}})}on(e,t){let i=[];for(let r of Object.values(fe))i.push(r);i.includes(e)&&this.eventBus.on(e,t)}off(e,t){e?this.eventBus.off(e,t):this.close()}async authenticate(){if(!this.sdkKey){Ze(this.log),this.failure=!0;return}try{let e=await this.api.authenticate({apiKey:this.sdkKey});this.authToken=e.data.authToken,this.configuration.accessToken=this.authToken;let t=(0,Gt.default)(this.authToken);t.environment||(this.failure=!0,this.log.error('Error while authenticating, err: the JWT token has missing claim "environmentUUID" ')),this.environment=t.environment,this.cluster=t.clusterIdentifier||"1"}catch(e){this.failure=!0,this.log.error("Error while authenticating, err: ",e),ct(this.log),ht(this.log),this.eventBus.emit("failed",e)}}waitForInitialization(){return this.waitForInitializePromise||(this.initialized?(this.waitForInitializePromise=Promise.resolve(this),Se(this.log)):!this.initialized&&this.failure?this.waitForInitializePromise=Promise.resolve(this):this.waitForInitializePromise=new Promise((e,t)=>{this.eventBus.once("ready",()=>{setTimeout(()=>e(this),0)}),this.eventBus.once("failed",t)})),this.waitForInitializePromise}initialize(e){switch(e){case 0:this.pollerReady=!0,this.log.debug("PollingProcessor ready"),et(this.options.pollInterval,this.log);break;case 1:this.streamReady=!0,this.log.debug("StreamingProcessor ready"),rt(this.log);break;case 2:this.metricReady=!0,this.log.debug("MetricsProcessor ready"),ot(this.options.eventsSyncInterval,this.log);break}this.options.enableStream&&!this.streamReady||this.options.enableAnalytics&&!this.metricReady||this.pollerReady&&this.eventBus.emit("ready")}async run(){await this.authenticate(),!this.failure&&(this.pollProcessor=new ne(this.environment,this.cluster,this.api,this.options,this.eventBus,this.repository),this.pollProcessor.start(),this.options.enableStream&&(this.streamProcessor=new oe(this.api,this.sdkKey,this.environment,this.authToken,this.options,this.cluster,this.eventBus,this.repository),this.streamProcessor.start()),this.options.enableAnalytics&&(this.metricsProcessor=Kt(this.environment,this.cluster,this.configuration,this.options,this.eventBus),this.metricsProcessor.start()),this.log.info("finished setting up processors"),this.initialized=!0,Se(this.log))}boolVariation(e,t,i=!1){return this.initialized?this.evaluator.boolVariation(e,t,i,(r,n,o)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(n,r,o)}):(D(e,t,i.toString(),this.log),Promise.resolve(i))}stringVariation(e,t,i=""){return this.initialized?this.evaluator.stringVariation(e,t,i,(r,n,o)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(n,r,o)}):(D(e,t,i.toString(),this.log),Promise.resolve(i))}numberVariation(e,t,i=0){return this.initialized?this.evaluator.numberVariation(e,t,i,(r,n,o)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(n,r,o)}):(D(e,t,i.toString(),this.log),Promise.resolve(i))}jsonVariation(e,t,i={}){return this.initialized?this.evaluator.jsonVariation(e,t,i,(r,n,o)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(n,r,o)}):(D(e,t,i.toString(),this.log),Promise.resolve(i))}close(){tt(this.log),this.closing=!0,this.pollProcessor.close(),this.streamProcessor&&this.streamProcessor.close(),this.metricsProcessor&&this.metricsProcessor.close(),this.eventBus.removeAllListeners(),this.closing=!1,it(this.log)}};var Ri={instance:void 0,init:function(s,e){this.instance||(this.instance=new H(s,e))},waitForInitialization:function(){return this.instance.waitForInitialization()},boolVariation:function(s,e,t=!1){return this.instance.boolVariation(s,e,t)},stringVariation:function(s,e,t=""){return this.instance.stringVariation(s,e,t)},numberVariation:function(s,e,t=0){return this.instance.numberVariation(s,e,t)},jsonVariation:function(s,e,t=""){return this.instance.jsonVariation(s,e,t)},on:function(s,e){this.instance.on(s,e)},off:function(s,e){this.instance.off(s,e)},close:function(){return this.instance.close()}};0&&(module.exports={Client,Event,FileStore,LRU});
`,t.name,o.name),!0}}return!1}async evaluateClause(e,t){var o;if(!(e!=null&&e.op)||!((o=e==null?void 0:e.values)!=null&&o.length))return!1;let i=this.getAttrValue(t,e.attribute),r=i==null?void 0:i.toString();if(e.op!==Z&&!r)return!1;let n=e.values[0];switch(e.op){case Lt:for(let a of e.values)if(a==r)return!0;return!1;case Dt:return r.toLowerCase()==n.toLowerCase();case Ut:return r==n;case kt:return r>n;case Mt:return r.startsWith(n);case Bt:return r.endsWith(n);case Nt:return r.includes(n);case Z:return await this.isTargetIncludedOrExcludedInSegment(e.values,t)}return!1}async evaluateClauses(e,t){for(let i of e)if(await this.evaluateClause(i,t))return!0;return!1}evaluateRule(e,t){return this.evaluateClauses(e.clauses,t)}async evaluateRules(e,t){if(!t||!e)return;e.sort((r,n)=>r.priority>n.priority?1:-1);let i;for(let r of e)if(await this.evaluateRule(r,t))return r.serve.distribution&&(i=this.evaluateDistribution(r.serve.distribution,t)),r.serve.variation&&(i=r.serve.variation),i}async evaluateVariationMap(e,t){var i;if(!(!t||!e))for(let r of e){if((i=r.targets)==null?void 0:i.find(a=>a.identifier===t.identifier))return r.variation;let o=r.targetSegments;if(o&&await this.isTargetIncludedOrExcludedInSegment(o,t))return r.variation}}async evaluateFlag(e,t){let i=e.offVariation;return e.state==="on"&&(i=await 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){this.log.info("Checking pre requisites %s of parent feature %s",e.prerequisites,e.feature);for(let i of e.prerequisites){let r=await this.query.getFlag(i.feature);if(!r)return this.log.warn("Could not retrieve the pre requisite details of feature flag: %s",e.feature),!0;let n=await this.evaluateFlag(r,t);return this.log.info("Pre requisite flag %s has variation %s for target %s",r.feature,n,t),this.log.info("Pre requisite flag %s should have the variations %s",r.feature,i.variations),i.variations.includes(n.identifier)?await this.checkPreRequisite(r,t):!1}}return!0}async evaluate(e,t,i,r){let n=await this.query.getFlag(e);if(!n||n.kind!==i)return;if(n.prerequisites&&!await this.checkPreRequisite(n,t))return this.findVariation(n.variations,n.offVariation);let o=await this.evaluateFlag(n,t);if(o)return r&&r(n,t,o),o}async boolVariation(e,t,i=!1,r){let n=await this.evaluate(e,t,"boolean",r);if(n){let o=n.value.toLowerCase()==="true";return J(`${o}`,e,t,this.log),o}return D(e,t,i.toString(),this.log),i}async stringVariation(e,t,i="",r){let n=await this.evaluate(e,t,"string",r);return n?(J(`${n.value}`,e,t,this.log),n.value):(D(e,t,i.toString(),this.log),i)}async numberVariation(e,t,i=0,r){let n=await this.evaluate(e,t,"int",r);if(n){let o=parseFloat(n.value);return J(`${o}`,e,t,this.log),o}return D(e,t,i.toString(),this.log),i}async jsonVariation(e,t,i={},r){let n=await this.evaluate(e,t,"json",r);return n?(J(`${n.value}`,e,t,this.log),JSON.parse(n.value)):(D(e,t,i.toString(),this.log),i)}};var Oe=(r=>(r.FLAG_STORED="flag_stored",r.FLAG_DELETED="flag_deleted",r.SEGMENT_STORED="segment_stored",r.SEGMENT_DELETED="segment_deleted",r))(Oe||{}),ue=class{constructor(e,t,i){if(!e)throw new Error("Cache is required argument and cannot be undefined");this.eventBus=i,this.cache=e,this.store=t}async setFlag(e,t){if(await this.isFlagOutdated(e,t))return;let i=this.formatFlagKey(e);this.store?(await this.store.set(i,t),this.cache.delete(i)):this.cache.set(i,t),this.eventBus&&this.eventBus.emit("flag_stored",e)}async setSegment(e,t){if(await this.isSegmentOutdated(e,t))return;let i=this.formatSegmentKey(e);this.store?(await this.store.set(i,t),this.cache.delete(i)):this.cache.set(i,t),this.eventBus&&this.eventBus.emit("segment_stored",e)}async deleteFlag(e){let t=this.formatFlagKey(e);this.store&&await this.store.del(t),this.cache.delete(t),this.eventBus&&this.eventBus.emit("flag_deleted",e)}async deleteSegment(e){let t=this.formatSegmentKey(e);this.store&&await this.store.del(t),this.cache.delete(t),this.eventBus&&this.eventBus.emit("segment_deleted",e)}async getFlag(e,t=!0){let i=this.formatFlagKey(e),r=this.cache.get(i);if(r)return r;if(this.store)return r=await this.store.get(i),r&&t&&this.cache.set(i,r),r}async getSegment(e,t=!0){let i=this.formatSegmentKey(e),r=this.cache.get(i);if(r)return r;if(this.store)return r=await this.store.get(i),r&&t&&this.cache.set(i,r),r}async findFlagsBySegment(e){let t=[],i=this.cache.keys();this.store&&(i=await this.store.keys());for(let r of i){let n=await this.getFlag(r);if(!n)return[];for(let o of n==null?void 0:n.rules)for(let a of o==null?void 0:o.clauses)a.op===Z&&a.values.includes(e)&&t.push(n.feature)}return t}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 Kt=(s,e="1",t,i,r,n=!1)=>{let o=new Map,a,c=new K({...t,basePath:i.eventsUrl}),l=new re(c),h=i.logger,f=(T,S,A)=>{let v={target:T,featureConfig:S,variation:A,count:0},w=d(v),m=o.get(w);m?m.count++:(v.count=1,o.set(w,v))},d=T=>{let S=T.featureConfig.feature,A=T.variation.identifier,v=T.variation.value;return`${S}/${A}/${v}/${Ft}`},p=()=>{var v,w;let T=[],S=[],A=new Map(o);o.clear();for(let m of A.values()){if(m.target&&!m.target.anonymous){let M=[];m.target.attributes&&(M=Object.entries(m.target.attributes).map(([Fe,$t])=>({key:Fe,value:$t})));let q=m.target.identifier;m.target.name&&(q=m.target.name);let W={identifier:m.target.identifier,name:q,attributes:M};T.push(W)}let V=[{key:bt,value:m.featureConfig.feature},{key:Rt,value:m.featureConfig.feature},{key:wt,value:m.variation.identifier},{key:_t,value:Ct},{key:Ot,value:It},{key:Pt,value:se},{key:xt,value:(w=(v=m==null?void 0:m.target)==null?void 0:v.identifier)!=null?w:null}],z={timestamp:Date.now(),count:m.count,metricsType:"FFMETRICS",attributes:V};S.push(z)}return{targetData:T,metricsData:S}},E=()=>{if(n){h.debug("SDK has been closed before metrics can be sent");return}if(o.size==0){h.debug("No metrics to send in this interval");return}let T=p();h.debug("Start sending metrics data"),l.postMetrics(s,e,T).then(S=>{h.debug("Metrics server returns: ",S.status),at(h),S.status>=400&&h.error("Error while sending metrics data with status code: ",S.status)}).catch(S=>{gt(`${S}`,h),h.debug("Metrics server returns error: ",S)})};return{start:()=>{h.info("Starting MetricsProcessor with request interval: ",i.eventsSyncInterval),a=setInterval(E,i.eventsSyncInterval),r.emit("metrics_ready")},close:()=>{h.info("Closing MetricsProcessor"),clearInterval(a),E(),n=!0,h.info("MetricsProcessor closed"),lt(h)},enqueue:f}};Ie.default.defaults.timeout=3e4;_(Ie.default,{retries:3,retryDelay:_.exponentialDelay});var fe=(i=>(i.READY="ready",i.FAILED="failed",i.CHANGED="changed",i))(fe||{}),H=class{constructor(e,t={}){this.cluster="1";this.eventBus=new jt.default;this.initialized=!1;this.failure=!1;this.pollerReady=!1;this.streamReady=!1;this.metricReady=!1;this.closing=!1;this.sdkKey=e,this.options={...U,...t},this.log=this.options.logger,t.pollInterval<U.pollInterval&&(this.options.pollInterval=U.pollInterval,this.log.warn(`Polling interval cannot be lower than ${U.pollInterval} ms`)),t.eventsSyncInterval<U.eventsSyncInterval&&(this.options.eventsSyncInterval=U.eventsSyncInterval,this.log.warn(`Events sync interval cannot be lower than ${U.eventsSyncInterval} ms`)),this.configuration=new K({basePath:this.options.baseUrl,baseOptions:{headers:{"User-Agent":`NodeJsSDK/${se}`}}}),this.repository=new ue(this.options.cache,this.options.store,this.eventBus),this.evaluator=new he(this.repository,this.log),this.api=new ie(this.configuration),this.processEvents(),this.run()}processEvents(){this.eventBus.on("poller_ready",()=>{this.initialize(0)}),this.eventBus.on("poller_error",()=>{this.failure=!0,this.eventBus.emit("failed")}),this.eventBus.on("stream_ready",()=>{this.initialize(1)}),this.eventBus.on("stream_retrying",()=>{this.failure=!0,this.log.error("Issue with streaming: falling back to polling while the SDK attempts to reconnect"),this.closing||this.pollProcessor.start()}),this.eventBus.on("stream_error",()=>{this.failure=!0,this.log.error("Unrecoverable issue with streaming: falling back to polling"),this.closing||this.pollProcessor.start(),this.eventBus.emit("failed")}),this.eventBus.on("metrics_ready",()=>{this.initialize(2)}),this.eventBus.on("metrics_error",()=>{this.failure=!0,this.eventBus.emit("failed")}),this.eventBus.on("stream_connected",()=>{this.pollProcessor.stop()}),this.eventBus.on("stream_disconnected",()=>{this.closing||this.pollProcessor.start()});for(let e of Object.values(Oe))this.eventBus.on(e,t=>{switch(e){case"flag_stored":case"flag_deleted":this.eventBus.emit("changed",t);break;case"segment_stored":case"segment_deleted":this.repository.findFlagsBySegment(t).then(i=>{i.forEach(r=>this.eventBus.emit("changed",r))});break}})}on(e,t){let i=[];for(let r of Object.values(fe))i.push(r);i.includes(e)&&this.eventBus.on(e,t)}off(e,t){e?this.eventBus.off(e,t):this.close()}async authenticate(){if(!this.sdkKey){Ze(this.log),this.failure=!0;return}try{let e=await this.api.authenticate({apiKey:this.sdkKey});this.authToken=e.data.authToken,this.configuration.accessToken=this.authToken;let t=(0,Gt.default)(this.authToken);t.environment||(this.failure=!0,this.log.error('Error while authenticating, err: the JWT token has missing claim "environmentUUID" ')),this.environment=t.environment,this.cluster=t.clusterIdentifier||"1"}catch(e){this.failure=!0,this.log.error("Error while authenticating, err: ",e),ct(this.log),ht(this.log),this.eventBus.emit("failed",e)}}waitForInitialization(){return this.waitForInitializePromise||(this.initialized?(this.waitForInitializePromise=Promise.resolve(this),Se(this.log)):!this.initialized&&this.failure?this.waitForInitializePromise=Promise.resolve(this):this.waitForInitializePromise=new Promise((e,t)=>{this.eventBus.once("ready",()=>{setTimeout(()=>e(this),0)}),this.eventBus.once("failed",t)})),this.waitForInitializePromise}initialize(e){switch(e){case 0:this.pollerReady=!0,this.log.debug("PollingProcessor ready"),et(this.options.pollInterval,this.log);break;case 1:this.streamReady=!0,this.log.debug("StreamingProcessor ready"),rt(this.log);break;case 2:this.metricReady=!0,this.log.debug("MetricsProcessor ready"),ot(this.options.eventsSyncInterval,this.log);break}this.options.enableStream&&!this.streamReady||this.options.enableAnalytics&&!this.metricReady||this.pollerReady&&this.eventBus.emit("ready")}async run(){await this.authenticate(),!this.failure&&(this.pollProcessor=new ne(this.environment,this.cluster,this.api,this.options,this.eventBus,this.repository),this.pollProcessor.start(),this.options.enableStream&&(this.streamProcessor=new oe(this.api,this.sdkKey,this.environment,this.authToken,this.options,this.cluster,this.eventBus,this.repository),this.streamProcessor.start()),this.options.enableAnalytics&&(this.metricsProcessor=Kt(this.environment,this.cluster,this.configuration,this.options,this.eventBus),this.metricsProcessor.start()),this.log.info("finished setting up processors"),this.initialized=!0,Se(this.log))}boolVariation(e,t,i=!1){return this.initialized?this.evaluator.boolVariation(e,t,i,(r,n,o)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(n,r,o)}):(D(e,t,i.toString(),this.log),Promise.resolve(i))}stringVariation(e,t,i=""){return this.initialized?this.evaluator.stringVariation(e,t,i,(r,n,o)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(n,r,o)}):(D(e,t,i.toString(),this.log),Promise.resolve(i))}numberVariation(e,t,i=0){return this.initialized?this.evaluator.numberVariation(e,t,i,(r,n,o)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(n,r,o)}):(D(e,t,i.toString(),this.log),Promise.resolve(i))}jsonVariation(e,t,i={}){return this.initialized?this.evaluator.jsonVariation(e,t,i,(r,n,o)=>{this.metricsProcessor&&this.metricsProcessor.enqueue(n,r,o)}):(D(e,t,i.toString(),this.log),Promise.resolve(i))}close(){tt(this.log),this.closing=!0,this.pollProcessor.close(),this.streamProcessor&&this.streamProcessor.close(),this.metricsProcessor&&this.metricsProcessor.close(),this.eventBus.removeAllListeners(),this.closing=!1,it(this.log)}};var Ri={instance:void 0,init:function(s,e){this.instance||(this.instance=new H(s,e))},waitForInitialization:function(){return this.instance.waitForInitialization()},boolVariation:function(s,e,t=!1){return this.instance.boolVariation(s,e,t)},stringVariation:function(s,e,t=""){return this.instance.stringVariation(s,e,t)},numberVariation:function(s,e,t=0){return this.instance.numberVariation(s,e,t)},jsonVariation:function(s,e,t=""){return this.instance.jsonVariation(s,e,t)},on:function(s,e){this.instance.on(s,e)},off:function(s,e){this.instance.off(s,e)},close:function(){return this.instance.close()}};0&&(module.exports={Client,Event,FileStore,LRU});
//# sourceMappingURL=index.js.map

@@ -1,1 +0,1 @@

export declare const VERSION = "1.4.0";
export declare const VERSION = "1.4.1-rc.1";
{
"name": "@harnessio/ff-nodejs-server-sdk",
"version": "1.4.0",
"version": "1.4.1-rc.1",
"description": "Feature flags SDK for NodeJS environments",

@@ -5,0 +5,0 @@ "main": "dist/cjs/index.js",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc