New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@harnessio/ff-javascript-client-sdk

Package Overview
Dependencies
Maintainers
0
Versions
114
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@harnessio/ff-javascript-client-sdk - npm Package Compare versions

Comparing version 1.29.0 to 1.30.0

3

dist/cache.d.ts

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

import type { CacheOptions, Evaluation } from './types';
import type { CacheOptions, Evaluation, Target } from './types';
export interface GetCacheResponse {

@@ -9,1 +9,2 @@ loadFromCache: () => Promise<Evaluation[]>;

export declare function getCache(seed: string, cacheOptions?: CacheOptions): Promise<GetCacheResponse>;
export declare function createCacheIdSeed(target: Target, apiKey: string, config?: CacheOptions): string;

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

var Ae=Object.create;var F=Object.defineProperty,Te=Object.defineProperties,we=Object.getOwnPropertyDescriptor,De=Object.getOwnPropertyDescriptors,Oe=Object.getOwnPropertyNames,ne=Object.getOwnPropertySymbols,Pe=Object.getPrototypeOf,re=Object.prototype.hasOwnProperty,Fe=Object.prototype.propertyIsEnumerable;var ae=(n,e,a)=>e in n?F(n,e,{enumerable:!0,configurable:!0,writable:!0,value:a}):n[e]=a,C=(n,e)=>{for(var a in e||(e={}))re.call(e,a)&&ae(n,a,e[a]);if(ne)for(var a of ne(e))Fe.call(e,a)&&ae(n,a,e[a]);return n},U=(n,e)=>Te(n,De(e));var xe=(n,e)=>{for(var a in e)F(n,a,{get:e[a],enumerable:!0})},oe=(n,e,a,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Oe(e))!re.call(n,r)&&r!==a&&F(n,r,{get:()=>e[r],enumerable:!(s=we(e,r))||s.enumerable});return n};var se=(n,e,a)=>(a=n!=null?Ae(Pe(n)):{},oe(e||!n||!n.__esModule?F(a,"default",{value:n,enumerable:!0}):a,n)),Me=n=>oe(F({},"__esModule",{value:!0}),n);var E=(n,e,a)=>new Promise((s,r)=>{var l=R=>{try{p(a.next(R))}catch(u){r(u)}},m=R=>{try{p(a.throw(R))}catch(u){r(u)}},p=R=>R.done?s(R.value):Promise.resolve(R.value).then(l,m);p((a=a.apply(n,e)).next())});var Ke={};xe(Ke,{Event:()=>P,initialize:()=>Ue});module.exports=Me(Ke);var he=se(require("jwt-decode")),me=se(require("mitt"));var P=(d=>(d.READY="ready",d.CONNECTED="connected",d.DISCONNECTED="disconnected",d.STOPPED="stopped",d.POLLING="polling",d.POLLING_STOPPED="polling stopped",d.FLAGS_LOADED="flags loaded",d.CACHE_LOADED="cache loaded",d.CHANGED="changed",d.ERROR="error",d.ERROR_CACHE="cache error",d.ERROR_METRICS="metrics error",d.ERROR_AUTH="auth error",d.ERROR_FETCH_FLAGS="fetch flags error",d.ERROR_FETCH_FLAG="fetch flag error",d.ERROR_STREAM="stream error",d.ERROR_DEFAULT_VARIATION_RETURNED="default variation returned",d))(P||{});var Ne={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},le=n=>{let e=C(C({},Ne),n);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},K=(n,e=!0)=>{e?setTimeout(n,0):n()},V=(n,e)=>Math.round(Math.random()*(e-n)+n),ce=n=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a="",s=0,r=Ve(JSON.stringify(n));for(;s<r.length;){let l=r.charCodeAt(s++),m=r.charCodeAt(s++),p=r.charCodeAt(s++),R=l>>2,u=(l&3)<<4|m>>4,S=(m&15)<<2|p>>6,A=p&63;isNaN(m)?S=A=64:isNaN(p)&&(A=64),a+=e.charAt(R)+e.charAt(u)+e.charAt(S)+e.charAt(A)}return a},Ve=n=>n.replace(/\r\n/g,`
`).split("").map(e=>{let a=e.charCodeAt(0);return a<128?String.fromCharCode(a):a>127&&a<2048?String.fromCharCode(a>>6|192)+String.fromCharCode(a&63|128):String.fromCharCode(a>>12|224)+String.fromCharCode(a>>6&63|128)+String.fromCharCode(a&63|128)}).join("");function j(n){return function(...a){let[s,r]=n(a);return fetch(s,r)}}var ue=3e4,_=class{constructor(e,a,s,r,l,m,p,R,u,S){this.eventBus=e;this.configurations=a;this.url=s;this.apiKey=r;this.standardHeaders=l;this.fallbackPoller=m;this.logDebug=p;this.logError=R;this.eventCallback=u;this.maxRetries=S;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1;this.reconnectAttempts=0;this.retriesExhausted=!1}start(){let e=u=>{u.toString().split(/\r?\n/).forEach(a)},a=u=>{if(u.startsWith("data:")){let S=JSON.parse(u.substring(5));this.logDebugMessage("Received event from stream: ",S),this.eventCallback(S)}},s=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected"),this.reconnectAttempts=0},r=()=>{clearInterval(this.readTimeoutCheckerId);let u=V(1e3,1e4);if(this.reconnectAttempts++,this.logDebugMessage("Stream disconnected, will reconnect in "+u+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),this.reconnectAttempts>=5&&this.reconnectAttempts%5===0&&this.logErrorMessage(`Reconnection failed after ${this.reconnectAttempts} attempts; attempting further reconnections.`),this.reconnectAttempts>=this.maxRetries){this.retriesExhausted=!0,this.configurations.pollingEnabled?this.logErrorMessage("Max streaming retries reached. Staying in polling mode."):this.logErrorMessage("Max streaming retries reached. Polling mode is disabled and will receive no further flag updates until SDK client is restarted.");return}setTimeout(()=>this.start(),u)},l=u=>{this.retriesExhausted||(u&&this.logDebugMessage("Stream has issue",u),this.fallBackToPolling(),this.eventBus.emit("stream error",u),this.eventBus.emit("error",u),r())},m=C({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[u,S]of Object.entries(m))this.xhr.setRequestHeader(u,S);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{l(`Received XMLHttpRequest onLoad event: ${this.xhr.status}`)};let p=0,R=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(s(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),R=Date.now();let u=this.xhr.responseText.slice(p);p+=u.length,this.logDebugMessage("SSE GOT: "+u),e(u)},this.readTimeoutCheckerId=setInterval(()=>{R<Date.now()-ue&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},ue),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...a){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...a)}logErrorMessage(e,...a){this.logError(`Streaming: ${e}`,...a)}};function de(n,e,a,s,r,l){let m=n in a,p=m?a[n]:e;if(m)s(n,p);else{let R={flag:n,defaultVariation:e};r.emit("default variation returned",R)}return l?{value:p,isDefaultValue:!m}:p}var x=class{constructor(e,a,s,r,l){this.fetchFlagsFn=e;this.configurations=a;this.eventBus=s;this.logDebug=r;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.isRunning&&this.attemptFetch().finally(()=>{this.isRunning&&(this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval))})}attemptFetch(){return E(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let a=yield this.fetchFlagsFn();if(a.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",a.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,a.error);let s=V(1e3,1e4);yield new Promise(r=>setTimeout(r,s))}})}stop(){this.timeoutId&&(this.isRunning=!1,clearTimeout(this.timeoutId),this.timeoutId=void 0,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...a){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...a)}logErrorMessage(e,...a){this.logError(`Poller: ${e}`,...a)}};function ge(a){return E(this,arguments,function*(n,e={}){let s=yield He(n),r=$e(e);return{loadFromCache:()=>W(s,r,e),saveToCache:l=>J(s,r,l),updateCachedEvaluation:l=>ke(s,r,l),removeCachedEvaluation:l=>Le(s,r,l)}})}function W(s,r){return E(this,arguments,function*(n,e,a={}){let l=parseInt(yield e.getItem(n+".ts"));if(a!=null&&a.ttl&&!isNaN(l)&&l+a.ttl<Date.now())return yield _e(n,e),[];let m=yield e.getItem(n);if(m)try{return JSON.parse(m)}catch(p){}return[]})}function _e(n,e){return E(this,null,function*(){yield e.removeItem(n),yield e.removeItem(n+".ts")})}function J(n,e,a){return E(this,null,function*(){yield e.setItem(n,JSON.stringify(a)),yield e.setItem(n+".ts",Date.now().toString())})}function ke(n,e,a){return E(this,null,function*(){let s=yield W(n,e),r=s.find(({flag:l})=>l===a.flag);r?Object.assign(r,a):s.push(a),yield J(n,e,s)})}function Le(n,e,a){return E(this,null,function*(){let s=yield W(n,e),r=s.findIndex(({flag:l})=>l===a);r>-1&&(s.splice(r,1),yield J(n,e,s))})}function He(n){return E(this,null,function*(){var a,s;let e=n;if(globalThis!=null&&globalThis.TextEncoder&&((s=(a=globalThis==null?void 0:globalThis.crypto)==null?void 0:a.subtle)!=null&&s.digest)){let l=new TextEncoder().encode(n),m=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(m)).map(R=>R.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(n));return"HARNESS_FF_CACHE_"+e})}function $e(n){let e;return!n.storage||typeof n.storage!="object"||!("getItem"in n.storage)||!("setItem"in n.storage)||!("removeItem"in n.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Ge:e=n.storage,{getItem(s){return E(this,null,function*(){let r=e.getItem(s);return r instanceof Promise?yield r:r})},setItem(s,r){return E(this,null,function*(){let l=e.setItem(s,r);l instanceof Promise&&(yield l)})},removeItem(s){return E(this,null,function*(){let r=e.removeItem(s);r instanceof Promise&&(yield r)})}}}var Ge={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var ve="1.26.1",fe=`Javascript ${ve} Client`,qe=500,Be=globalThis.fetch,Y=!!globalThis.Proxy,Ue=(n,e,a)=>{let s=!1,r,l,m,p,R,u,S=!0,A={},M=j(t=>t),X=0,z=!1,k=()=>{S=!1},L=()=>{S=!0},d=[],f=(0,me.default)(),v=le(a),b=(t,...i)=>{v.debug&&v.logger.debug(`[FF-SDK] ${t}`,...i)},T=(t,...i)=>{v.logger.error(`[FF-SDK] ${t}`,...i)},pe=(t,...i)=>{v.logger.warn(`[FF-SDK] ${t}`,...i)},H=t=>{let{value:i}=t;try{switch(t.kind.toLowerCase()){case"int":case"number":i=Number(i);break;case"boolean":i=i.toString().toLowerCase()==="true";break;case"json":i=JSON.parse(i);break}}catch(c){T(c)}return i},$=t=>{if(S){let i=Date.now();i-t.lastAccessed>qe&&(t.count++,t.lastAccessed=i)}},Ee=()=>E(void 0,null,function*(){if(v.cache){b("initializing cache");try{let t=!0,i=yield ge(e.identifier+n,typeof v.cache=="boolean"?{}:v.cache),c=yield i.loadFromCache();c!=null&&c.length&&K(()=>{b("loading from cache",c),te(c,!1),f.emit("cache loaded",c)}),B("flags loaded",h=>E(void 0,null,function*(){yield i.saveToCache(h),t=!1})),B("changed",h=>E(void 0,null,function*(){t||(h.deleted?yield i.removeCachedEvaluation(h.flag):yield i.updateCachedEvaluation(h))}))}catch(t){T("Cache error: ",t),f.emit("cache error",t),f.emit("error",t)}}}),Re=(t,i)=>E(void 0,null,function*(){let c=`${i.baseUrl}/client/auth`,h={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":fe},body:JSON.stringify({apiKey:t,target:U(C({},e),{identifier:String(e.identifier)})})},y,o;window.AbortController&&v.authRequestReadTimeout>0?(o=new AbortController,h.signal=o.signal,y=window.setTimeout(()=>o.abort(),i.authRequestReadTimeout)):i.authRequestReadTimeout>0&&pe("AbortController is not available, auth request will not timeout");try{let g=yield Be(c,h);if(!g.ok)throw new Error(`${g.status}: ${g.statusText}`);return(yield g.json()).authToken}catch(g){if(o&&o.signal.aborted)throw new Error(`Request to ${c} failed: Request timeout via configured authRequestTimeout of ${v.authRequestReadTimeout}`);let D=g instanceof Error?g.message:String(g);throw new Error(`Request to ${c} failed: ${D}`)}finally{y&&clearTimeout(y)}}),G=0,q=()=>{if(d.length){b("Sending metrics...",{metrics:d,evaluations:I});let t={metricsData:d.map(i=>({timestamp:Date.now(),count:i.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:i.featureIdentifier},{key:"featureName",value:i.featureIdentifier},{key:"variationIdentifier",value:i.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:ve}]}))};M(`${v.eventUrl}/metrics/${r}?cluster=${l}`,{method:"POST",headers:C({"Content-Type":"application/json"},A),body:JSON.stringify(t)}).then(()=>{d=[],G=0}).catch(i=>{G++&&(d=[],G=0),b(i),f.emit("metrics error",i)}).finally(()=>{u=window.setTimeout(q,v.eventsSyncInterval)})}else u=window.setTimeout(q,v.eventsSyncInterval)},I={},be=t=>{b("Sending event for",t.flag),Y?f.emit("changed",new Proxy(t,{get(i,c){var h;if(S&&i.hasOwnProperty(c)&&c==="value"){let y=i.flag,o=t.value,g=d.find(D=>D.featureIdentifier===y&&D.featureValue===o);g?($(g),g.variationIdentifier=((h=I[y])==null?void 0:h.identifier)||""):d.push({featureIdentifier:y,featureValue:String(o),variationIdentifier:I[y].identifier||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag",c,"has been read with value via stream update",o)}return c==="value"?H(t):t[c]}})):f.emit("changed",{deleted:t.deleted,flag:t.flag,value:H(t)})},Q=function(){return Y?new Proxy({},{get(t,i){var h,y,o;let c=t[i];if(S&&t.hasOwnProperty(i)){let g=t[i],D=d.find(ie=>ie.featureIdentifier===i&&g===ie.featureValue);D?(D.variationIdentifier=((h=I[i])==null?void 0:h.identifier)||"",$(D)):d.push({featureIdentifier:i,featureValue:g,variationIdentifier:((y=I[i])==null?void 0:y.identifier)||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag:",i,"has been read with value:",g,"variationIdentifier:",(o=I[i])==null?void 0:o.identifier)}return c}}):{}},w=Q();Ee().then(()=>Re(n,v).then(t=>E(void 0,null,function*(){if(s)return;R=t;let i=(0,he.default)(t);A={Authorization:`Bearer ${R}`,"Harness-AccountID":i.accountID,"Harness-EnvironmentID":i.environmentIdentifier,"Harness-SDK-Info":fe};let c=ce(e);c.length<262144&&(A["Harness-Target"]=c),b("Authenticated",i),u=window.setTimeout(q,v.eventsSyncInterval),r=i.environment,l=i.clusterIdentifier;let h=!!Object.keys(I).length;if((yield N()).type==="success"&&b("Fetch all flags ok",w),!s){if(v.streamEnabled?(b("Streaming mode enabled"),ye()):v.pollingEnabled?(b("Polling mode enabled"),Se()):b("Streaming and polling mode disabled"),!h){k();let o=C({},w);L(),f.emit("ready",o)}z=!0}})).catch(t=>{T("Authentication error: ",t),f.emit("auth error",t),f.emit("error",t)}));let N=()=>E(void 0,null,function*(){try{let t=yield M(`${v.baseUrl}/client/env/${r}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:A});if(t.ok){let i=yield t.json();return i.forEach(O),f.emit("flags loaded",i),{type:"success",data:i}}else return T("Features fetch operation error: ",t),f.emit("fetch flags error",t),f.emit("error",t),{type:"error",error:t}}catch(t){return T("Features fetch operation error: ",t),f.emit("fetch flags error",t),f.emit("error",t),{type:"error",error:t}}}),Z=t=>E(void 0,null,function*(){try{let i=yield M(`${v.baseUrl}/client/env/${r}/target/${e.identifier}/evaluations/${t}?cluster=${l}`,{headers:A});if(i.ok){let c=yield i.json();O(c)}else T("Feature fetch operation error: ",i),f.emit("fetch flag error",i),f.emit("error",i)}catch(i){T("Feature fetch operation error: ",i),f.emit("fetch flag error",i),f.emit("error",i)}}),O=t=>{k();let i=H(t);i!==w[t.flag]&&(b("Flag variation has changed for ",t.identifier),w[t.flag]=i,I[t.flag]=U(C({},t),{value:i}),be(t)),L()};p=new x(N,v,f,b,T);let ye=()=>{let t=o=>{switch(o.event){case"create":c(o.evaluations)?o.evaluations.forEach(g=>{O(g)}):setTimeout(()=>Z(o.identifier),1e3);break;case"patch":c(o.evaluations)?o.evaluations.forEach(g=>{O(g)}):Z(o.identifier);break;case"delete":delete w[o.identifier],f.emit("changed",{flag:o.identifier,value:void 0,deleted:!0}),b("Evaluation deleted",{message:o,storage:w});break}},i=o=>!(!o||!o.flag||!o.identifier||!o.kind||!o.value),c=o=>!(!o||o.length==0||!o.every(g=>i(g))),h=o=>{o.event==="patch"&&(c(o.evaluations)?o.evaluations.forEach(g=>{O(g)}):N())},y=`${v.baseUrl}/stream?cluster=${l}`;m=new _(f,v,y,n,A,p,b,T,o=>{o.domain==="flag"?t(o):o.domain==="target-segment"&&h(o)},v.maxStreamRetries),m.start()},Se=()=>{p.start()},B=(t,i)=>f.on(t,i),Ie=(t,i)=>{t?f.off(t,i):ee()},Ce=(t,i)=>{var o;if(!S||Y||i===void 0)return;let c=i,h=t,y=d.find(g=>g.featureIdentifier===h&&g.featureValue===c);y?($(y),y.variationIdentifier=((o=I[h])==null?void 0:o.identifier)||""):d.push({featureIdentifier:h,featureValue:c,count:1,variationIdentifier:I[h].identifier||"",lastAccessed:Date.now()})},ee=()=>{s=!0,v.streamEnabled&&(b("Closing event stream"),typeof(m==null?void 0:m.close)=="function"&&m.close(),f.all.clear()),v.pollingEnabled&&p.isPolling()&&(b("Closing Poller"),p.stop()),w=Q(),I={},clearTimeout(u)},te=(t,i=!0)=>{t.length&&K(()=>{let c=!!Object.keys(I).length;if(t.forEach(O),!c){k();let h=C({},w);L(),f.emit("ready",h)}},i)};return{on:B,off:Ie,close:ee,setEvaluations:te,registerAPIRequestMiddleware:t=>{M=j(t)},refreshEvaluations:()=>{z&&!s&&Date.now()-X>=6e4&&(N(),X=Date.now())},variation:(t,i,c=!1)=>de(t,i,w,Ce,f,c)}};0&&(module.exports={Event,initialize});
var we=Object.create;var F=Object.defineProperty,De=Object.defineProperties,Oe=Object.getOwnPropertyDescriptor,Pe=Object.getOwnPropertyDescriptors,Fe=Object.getOwnPropertyNames,ae=Object.getOwnPropertySymbols,xe=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty,Me=Object.prototype.propertyIsEnumerable;var re=(t,e,n)=>e in t?F(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,I=(t,e)=>{for(var n in e||(e={}))oe.call(e,n)&&re(t,n,e[n]);if(ae)for(var n of ae(e))Me.call(e,n)&&re(t,n,e[n]);return t},x=(t,e)=>De(t,Pe(e));var Ne=(t,e)=>{for(var n in e)F(t,n,{get:e[n],enumerable:!0})},se=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Fe(e))!oe.call(t,r)&&r!==n&&F(t,r,{get:()=>e[r],enumerable:!(o=Oe(e,r))||o.enumerable});return t};var le=(t,e,n)=>(n=t!=null?we(xe(t)):{},se(e||!t||!t.__esModule?F(n,"default",{value:t,enumerable:!0}):n,t)),Ve=t=>se(F({},"__esModule",{value:!0}),t);var R=(t,e,n)=>new Promise((o,r)=>{var l=b=>{try{E(n.next(b))}catch(u){r(u)}},m=b=>{try{E(n.throw(b))}catch(u){r(u)}},E=b=>b.done?o(b.value):Promise.resolve(b.value).then(l,m);E((n=n.apply(t,e)).next())});var We={};Ne(We,{Event:()=>P,initialize:()=>je});module.exports=Ve(We);var ve=le(require("jwt-decode")),pe=le(require("mitt"));var P=(d=>(d.READY="ready",d.CONNECTED="connected",d.DISCONNECTED="disconnected",d.STOPPED="stopped",d.POLLING="polling",d.POLLING_STOPPED="polling stopped",d.FLAGS_LOADED="flags loaded",d.CACHE_LOADED="cache loaded",d.CHANGED="changed",d.ERROR="error",d.ERROR_CACHE="cache error",d.ERROR_METRICS="metrics error",d.ERROR_AUTH="auth error",d.ERROR_FETCH_FLAGS="fetch flags error",d.ERROR_FETCH_FLAG="fetch flag error",d.ERROR_STREAM="stream error",d.ERROR_DEFAULT_VARIATION_RETURNED="default variation returned",d))(P||{});var _e={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},ce=t=>{let e=I(I({},_e),t);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},j=(t,e=!0)=>{e?setTimeout(t,0):t()},_=(t,e)=>Math.round(Math.random()*(e-t)+t),ue=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",n="",o=0,r=ke(JSON.stringify(t));for(;o<r.length;){let l=r.charCodeAt(o++),m=r.charCodeAt(o++),E=r.charCodeAt(o++),b=l>>2,u=(l&3)<<4|m>>4,S=(m&15)<<2|E>>6,C=E&63;isNaN(m)?S=C=64:isNaN(E)&&(C=64),n+=e.charAt(b)+e.charAt(u)+e.charAt(S)+e.charAt(C)}return n},ke=t=>t.replace(/\r\n/g,`
`).split("").map(e=>{let n=e.charCodeAt(0);return n<128?String.fromCharCode(n):n>127&&n<2048?String.fromCharCode(n>>6|192)+String.fromCharCode(n&63|128):String.fromCharCode(n>>12|224)+String.fromCharCode(n>>6&63|128)+String.fromCharCode(n&63|128)}).join("");function k(t){return[...t].sort(({flag:e},{flag:n})=>e<n?-1:1)}function W(t){return function(...n){let[o,r]=t(n);return fetch(o,r)}}var de=3e4,L=class{constructor(e,n,o,r,l,m,E,b,u,S){this.eventBus=e;this.configurations=n;this.url=o;this.apiKey=r;this.standardHeaders=l;this.fallbackPoller=m;this.logDebug=E;this.logError=b;this.eventCallback=u;this.maxRetries=S;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1;this.reconnectAttempts=0;this.retriesExhausted=!1}start(){let e=u=>{u.toString().split(/\r?\n/).forEach(n)},n=u=>{if(u.startsWith("data:")){let S=JSON.parse(u.substring(5));this.logDebugMessage("Received event from stream: ",S),this.eventCallback(S)}},o=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected"),this.reconnectAttempts=0},r=()=>{clearInterval(this.readTimeoutCheckerId);let u=_(1e3,1e4);if(this.reconnectAttempts++,this.logDebugMessage("Stream disconnected, will reconnect in "+u+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),this.reconnectAttempts>=5&&this.reconnectAttempts%5===0&&this.logErrorMessage(`Reconnection failed after ${this.reconnectAttempts} attempts; attempting further reconnections.`),this.reconnectAttempts>=this.maxRetries){this.retriesExhausted=!0,this.configurations.pollingEnabled?this.logErrorMessage("Max streaming retries reached. Staying in polling mode."):this.logErrorMessage("Max streaming retries reached. Polling mode is disabled and will receive no further flag updates until SDK client is restarted.");return}setTimeout(()=>this.start(),u)},l=u=>{this.retriesExhausted||(u&&this.logDebugMessage("Stream has issue",u),this.fallBackToPolling(),this.eventBus.emit("stream error",u),this.eventBus.emit("error",u),r())},m=I({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[u,S]of Object.entries(m))this.xhr.setRequestHeader(u,S);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{l(`Received XMLHttpRequest onLoad event: ${this.xhr.status}`)};let E=0,b=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(o(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),b=Date.now();let u=this.xhr.responseText.slice(E);E+=u.length,this.logDebugMessage("SSE GOT: "+u),e(u)},this.readTimeoutCheckerId=setInterval(()=>{b<Date.now()-de&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},de),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...n){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...n)}logErrorMessage(e,...n){this.logError(`Streaming: ${e}`,...n)}};function ge(t,e,n,o,r,l){let m=t in n,E=m?n[t]:e;if(m)o(t,E);else{let b={flag:t,defaultVariation:e};r.emit("default variation returned",b)}return l?{value:E,isDefaultValue:!m}:E}var M=class{constructor(e,n,o,r,l){this.fetchFlagsFn=e;this.configurations=n;this.eventBus=o;this.logDebug=r;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.isRunning&&this.attemptFetch().finally(()=>{this.isRunning&&(this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval))})}attemptFetch(){return R(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let n=yield this.fetchFlagsFn();if(n.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",n.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,n.error);let o=_(1e3,1e4);yield new Promise(r=>setTimeout(r,o))}})}stop(){this.timeoutId&&(this.isRunning=!1,clearTimeout(this.timeoutId),this.timeoutId=void 0,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...n){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...n)}logErrorMessage(e,...n){this.logError(`Poller: ${e}`,...n)}};function fe(n){return R(this,arguments,function*(t,e={}){let o=yield Ge(t),r=qe(e);return{loadFromCache:()=>J(o,r,e),saveToCache:l=>Y(o,r,l),updateCachedEvaluation:l=>He(o,r,l),removeCachedEvaluation:l=>$e(o,r,l)}})}function J(o,r){return R(this,arguments,function*(t,e,n={}){let l=parseInt(yield e.getItem(t+".ts"));if(n!=null&&n.ttl&&!isNaN(l)&&l+n.ttl<Date.now())return yield Le(t,e),[];let m=yield e.getItem(t);if(m)try{return JSON.parse(m)}catch(E){}return[]})}function Le(t,e){return R(this,null,function*(){yield e.removeItem(t),yield e.removeItem(t+".ts")})}function Y(t,e,n){return R(this,null,function*(){yield e.setItem(t,JSON.stringify(k(n))),yield e.setItem(t+".ts",Date.now().toString())})}function He(t,e,n){return R(this,null,function*(){let o=yield J(t,e),r=o.find(({flag:l})=>l===n.flag);r?Object.assign(r,n):o.push(n),yield Y(t,e,o)})}function $e(t,e,n){return R(this,null,function*(){let o=yield J(t,e),r=o.findIndex(({flag:l})=>l===n);r>-1&&(o.splice(r,1),yield Y(t,e,o))})}function he(t,e,n={}){return n.deriveKeyFromTargetAttributes?JSON.stringify(Object.keys(t.attributes||{}).sort().filter(o=>!Array.isArray(n.deriveKeyFromTargetAttributes)||n.deriveKeyFromTargetAttributes.includes(o)).reduce((o,r)=>x(I({},o),{[r]:t.attributes[r]}),{}))+t.identifier+e:t.identifier+e}function Ge(t){return R(this,null,function*(){var n,o;let e=t;if(globalThis!=null&&globalThis.TextEncoder&&((o=(n=globalThis==null?void 0:globalThis.crypto)==null?void 0:n.subtle)!=null&&o.digest)){let l=new TextEncoder().encode(t),m=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(m)).map(b=>b.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(t));return"HARNESS_FF_CACHE_"+e})}function qe(t){let e;return!t.storage||typeof t.storage!="object"||!("getItem"in t.storage)||!("setItem"in t.storage)||!("removeItem"in t.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Be:e=t.storage,{getItem(o){return R(this,null,function*(){let r=e.getItem(o);return r instanceof Promise?yield r:r})},setItem(o,r){return R(this,null,function*(){let l=e.setItem(o,r);l instanceof Promise&&(yield l)})},removeItem(o){return R(this,null,function*(){let r=e.removeItem(o);r instanceof Promise&&(yield r)})}}}var Be={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var Ee="1.26.1",me=`Javascript ${Ee} Client`,Ke=500,Ue=globalThis.fetch,X=!!globalThis.Proxy,je=(t,e,n)=>{let o=!1,r,l,m,E,b,u,S=!0,C={},N=W(i=>i),z=0,Q=!1,H=()=>{S=!1},$=()=>{S=!0},d=[],f=(0,pe.default)(),v=ce(n),y=(i,...a)=>{v.debug&&v.logger.debug(`[FF-SDK] ${i}`,...a)},T=(i,...a)=>{v.logger.error(`[FF-SDK] ${i}`,...a)},Re=(i,...a)=>{v.logger.warn(`[FF-SDK] ${i}`,...a)},G=i=>{let{value:a}=i;try{switch(i.kind.toLowerCase()){case"int":case"number":a=Number(a);break;case"boolean":a=a.toString().toLowerCase()==="true";break;case"json":a=JSON.parse(a);break}}catch(c){T(c)}return a},q=i=>{if(S){let a=Date.now();a-i.lastAccessed>Ke&&(i.count++,i.lastAccessed=a)}},be=()=>R(void 0,null,function*(){if(v.cache){y("initializing cache");try{let i=!0,a=typeof v.cache=="boolean"?{}:v.cache,c=yield fe(he(e,t,a),a),h=yield c.loadFromCache();h!=null&&h.length&&j(()=>{y("loading from cache",h),ie(h,!1),f.emit("cache loaded",h)}),U("flags loaded",p=>R(void 0,null,function*(){yield c.saveToCache(p),i=!1})),U("changed",p=>R(void 0,null,function*(){i||(p.deleted?yield c.removeCachedEvaluation(p.flag):yield c.updateCachedEvaluation(p))}))}catch(i){T("Cache error: ",i),f.emit("cache error",i),f.emit("error",i)}}}),ye=(i,a)=>R(void 0,null,function*(){let c=`${a.baseUrl}/client/auth`,h={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":me},body:JSON.stringify({apiKey:i,target:x(I({},e),{identifier:String(e.identifier)})})},p,s;window.AbortController&&v.authRequestReadTimeout>0?(s=new AbortController,h.signal=s.signal,p=window.setTimeout(()=>s.abort(),a.authRequestReadTimeout)):a.authRequestReadTimeout>0&&Re("AbortController is not available, auth request will not timeout");try{let g=yield Ue(c,h);if(!g.ok)throw new Error(`${g.status}: ${g.statusText}`);return(yield g.json()).authToken}catch(g){if(s&&s.signal.aborted)throw new Error(`Request to ${c} failed: Request timeout via configured authRequestTimeout of ${v.authRequestReadTimeout}`);let D=g instanceof Error?g.message:String(g);throw new Error(`Request to ${c} failed: ${D}`)}finally{p&&clearTimeout(p)}}),B=0,K=()=>{if(d.length){y("Sending metrics...",{metrics:d,evaluations:A});let i={metricsData:d.map(a=>({timestamp:Date.now(),count:a.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:a.featureIdentifier},{key:"featureName",value:a.featureIdentifier},{key:"variationIdentifier",value:a.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:Ee}]}))};N(`${v.eventUrl}/metrics/${r}?cluster=${l}`,{method:"POST",headers:I({"Content-Type":"application/json"},C),body:JSON.stringify(i)}).then(()=>{d=[],B=0}).catch(a=>{B++&&(d=[],B=0),y(a),f.emit("metrics error",a)}).finally(()=>{u=window.setTimeout(K,v.eventsSyncInterval)})}else u=window.setTimeout(K,v.eventsSyncInterval)},A={},Se=i=>{y("Sending event for",i.flag),X?f.emit("changed",new Proxy(i,{get(a,c){var h;if(S&&a.hasOwnProperty(c)&&c==="value"){let p=a.flag,s=i.value,g=d.find(D=>D.featureIdentifier===p&&D.featureValue===s);g?(q(g),g.variationIdentifier=((h=A[p])==null?void 0:h.identifier)||""):d.push({featureIdentifier:p,featureValue:String(s),variationIdentifier:A[p].identifier||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag",c,"has been read with value via stream update",s)}return c==="value"?G(i):i[c]}})):f.emit("changed",{deleted:i.deleted,flag:i.flag,value:G(i)})},Z=function(){return X?new Proxy({},{get(i,a){var h,p,s;let c=i[a];if(S&&i.hasOwnProperty(a)){let g=i[a],D=d.find(ne=>ne.featureIdentifier===a&&g===ne.featureValue);D?(D.variationIdentifier=((h=A[a])==null?void 0:h.identifier)||"",q(D)):d.push({featureIdentifier:a,featureValue:g,variationIdentifier:((p=A[a])==null?void 0:p.identifier)||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag:",a,"has been read with value:",g,"variationIdentifier:",(s=A[a])==null?void 0:s.identifier)}return c}}):{}},w=Z();be().then(()=>ye(t,v).then(i=>R(void 0,null,function*(){if(o)return;b=i;let a=(0,ve.default)(i);C={Authorization:`Bearer ${b}`,"Harness-AccountID":a.accountID,"Harness-EnvironmentID":a.environmentIdentifier,"Harness-SDK-Info":me};let c=ue(e);c.length<262144&&(C["Harness-Target"]=c),y("Authenticated",a),u=window.setTimeout(K,v.eventsSyncInterval),r=a.environment,l=a.clusterIdentifier;let h=!!Object.keys(A).length;if((yield V()).type==="success"&&y("Fetch all flags ok",w),!o){if(v.streamEnabled?(y("Streaming mode enabled"),Ie()):v.pollingEnabled?(y("Polling mode enabled"),Ae()):y("Streaming and polling mode disabled"),!h){H();let s=I({},w);$(),f.emit("ready",s)}Q=!0}})).catch(i=>{T("Authentication error: ",i),f.emit("auth error",i),f.emit("error",i)}));let V=()=>R(void 0,null,function*(){try{let i=yield N(`${v.baseUrl}/client/env/${r}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:C});if(i.ok){let a=k(yield i.json());return a.forEach(O),f.emit("flags loaded",a),{type:"success",data:a}}else return T("Features fetch operation error: ",i),f.emit("fetch flags error",i),f.emit("error",i),{type:"error",error:i}}catch(i){return T("Features fetch operation error: ",i),f.emit("fetch flags error",i),f.emit("error",i),{type:"error",error:i}}}),ee=i=>R(void 0,null,function*(){try{let a=yield N(`${v.baseUrl}/client/env/${r}/target/${e.identifier}/evaluations/${i}?cluster=${l}`,{headers:C});if(a.ok){let c=yield a.json();O(c)}else T("Feature fetch operation error: ",a),f.emit("fetch flag error",a),f.emit("error",a)}catch(a){T("Feature fetch operation error: ",a),f.emit("fetch flag error",a),f.emit("error",a)}}),O=i=>{H();let a=G(i);a!==w[i.flag]&&(y("Flag variation has changed for ",i.identifier),w[i.flag]=a,A[i.flag]=x(I({},i),{value:a}),Se(i)),$()};E=new M(V,v,f,y,T);let Ie=()=>{let i=s=>{switch(s.event){case"create":c(s.evaluations)?s.evaluations.forEach(g=>{O(g)}):setTimeout(()=>ee(s.identifier),1e3);break;case"patch":c(s.evaluations)?s.evaluations.forEach(g=>{O(g)}):ee(s.identifier);break;case"delete":delete w[s.identifier],f.emit("changed",{flag:s.identifier,value:void 0,deleted:!0}),y("Evaluation deleted",{message:s,storage:w});break}},a=s=>!(!s||!s.flag||!s.identifier||!s.kind||!s.value),c=s=>!(!s||s.length==0||!s.every(g=>a(g))),h=s=>{s.event==="patch"&&(c(s.evaluations)?s.evaluations.forEach(g=>{O(g)}):V())},p=`${v.baseUrl}/stream?cluster=${l}`;m=new L(f,v,p,t,C,E,y,T,s=>{s.domain==="flag"?i(s):s.domain==="target-segment"&&h(s)},v.maxStreamRetries),m.start()},Ae=()=>{E.start()},U=(i,a)=>f.on(i,a),Ce=(i,a)=>{i?f.off(i,a):te()},Te=(i,a)=>{var s;if(!S||X||a===void 0)return;let c=a,h=i,p=d.find(g=>g.featureIdentifier===h&&g.featureValue===c);p?(q(p),p.variationIdentifier=((s=A[h])==null?void 0:s.identifier)||""):d.push({featureIdentifier:h,featureValue:c,count:1,variationIdentifier:A[h].identifier||"",lastAccessed:Date.now()})},te=()=>{o=!0,v.streamEnabled&&(y("Closing event stream"),typeof(m==null?void 0:m.close)=="function"&&m.close(),f.all.clear()),v.pollingEnabled&&E.isPolling()&&(y("Closing Poller"),E.stop()),w=Z(),A={},clearTimeout(u)},ie=(i,a=!0)=>{i.length&&j(()=>{let c=!!Object.keys(A).length;if(i.forEach(O),!c){H();let h=I({},w);$(),f.emit("ready",h)}},a)};return{on:U,off:Ce,close:te,setEvaluations:ie,registerAPIRequestMiddleware:i=>{N=W(i)},refreshEvaluations:()=>{Q&&!o&&Date.now()-z>=6e4&&(V(),z=Date.now())},variation:(i,a,c=!1)=>ge(i,a,w,Te,f,c)}};0&&(module.exports={Event,initialize});

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

var HarnessFFSDK=(()=>{var N=Object.defineProperty,Ae=Object.defineProperties,Te=Object.getOwnPropertyDescriptor,De=Object.getOwnPropertyDescriptors,Oe=Object.getOwnPropertyNames,ae=Object.getOwnPropertySymbols;var se=Object.prototype.hasOwnProperty,Pe=Object.prototype.propertyIsEnumerable;var oe=(t,e,i)=>e in t?N(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,w=(t,e)=>{for(var i in e||(e={}))se.call(e,i)&&oe(t,i,e[i]);if(ae)for(var i of ae(e))Pe.call(e,i)&&oe(t,i,e[i]);return t},K=(t,e)=>Ae(t,De(e));var xe=(t,e)=>{for(var i in e)N(t,i,{get:e[i],enumerable:!0})},Fe=(t,e,i,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Oe(e))!se.call(t,o)&&o!==i&&N(t,o,{get:()=>e[o],enumerable:!(a=Te(e,o))||a.enumerable});return t};var Me=t=>Fe(N({},"__esModule",{value:!0}),t);var E=(t,e,i)=>new Promise((a,o)=>{var l=R=>{try{v(i.next(R))}catch(u){o(u)}},g=R=>{try{v(i.throw(R))}catch(u){o(u)}},v=R=>R.done?a(R.value):Promise.resolve(R.value).then(l,g);v((i=i.apply(t,e)).next())});var We={};xe(We,{Event:()=>P,initialize:()=>je});function j(t){this.message=t}j.prototype=new Error,j.prototype.name="InvalidCharacterError";var le=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new j("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,a,o=0,l=0,g="";a=e.charAt(l++);~a&&(i=o%4?64*i+a:a,o++%4)?g+=String.fromCharCode(255&i>>(-2*o&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return g};function Ne(t){var e=t.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(i){return decodeURIComponent(le(i).replace(/(.)/g,function(a,o){var l=o.charCodeAt(0).toString(16).toUpperCase();return l.length<2&&(l="0"+l),"%"+l}))}(e)}catch(i){return le(e)}}function V(t){this.message=t}function Ve(t,e){if(typeof t!="string")throw new V("Invalid token specified");var i=(e=e||{}).header===!0?0:1;try{return JSON.parse(Ne(t.split(".")[i]))}catch(a){throw new V("Invalid token specified: "+a.message)}}V.prototype=new Error,V.prototype.name="InvalidTokenError";var ce=Ve;function ue(t){return{all:t=t||new Map,on:function(e,i){var a=t.get(e);a&&a.push(i)||t.set(e,[i])},off:function(e,i){var a=t.get(e);a&&a.splice(a.indexOf(i)>>>0,1)},emit:function(e,i){(t.get(e)||[]).slice().map(function(a){a(i)}),(t.get("*")||[]).slice().map(function(a){a(e,i)})}}}var P=(d=>(d.READY="ready",d.CONNECTED="connected",d.DISCONNECTED="disconnected",d.STOPPED="stopped",d.POLLING="polling",d.POLLING_STOPPED="polling stopped",d.FLAGS_LOADED="flags loaded",d.CACHE_LOADED="cache loaded",d.CHANGED="changed",d.ERROR="error",d.ERROR_CACHE="cache error",d.ERROR_METRICS="metrics error",d.ERROR_AUTH="auth error",d.ERROR_FETCH_FLAGS="fetch flags error",d.ERROR_FETCH_FLAG="fetch flag error",d.ERROR_STREAM="stream error",d.ERROR_DEFAULT_VARIATION_RETURNED="default variation returned",d))(P||{});var ke={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},de=t=>{let e=w(w({},ke),t);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},W=(t,e=!0)=>{e?setTimeout(t,0):t()},k=(t,e)=>Math.round(Math.random()*(e-t)+t),ge=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i="",a=0,o=_e(JSON.stringify(t));for(;a<o.length;){let l=o.charCodeAt(a++),g=o.charCodeAt(a++),v=o.charCodeAt(a++),R=l>>2,u=(l&3)<<4|g>>4,S=(g&15)<<2|v>>6,C=v&63;isNaN(g)?S=C=64:isNaN(v)&&(C=64),i+=e.charAt(R)+e.charAt(u)+e.charAt(S)+e.charAt(C)}return i},_e=t=>t.replace(/\r\n/g,`
`).split("").map(e=>{let i=e.charCodeAt(0);return i<128?String.fromCharCode(i):i>127&&i<2048?String.fromCharCode(i>>6|192)+String.fromCharCode(i&63|128):String.fromCharCode(i>>12|224)+String.fromCharCode(i>>6&63|128)+String.fromCharCode(i&63|128)}).join("");function J(t){return function(...i){let[a,o]=t(i);return fetch(a,o)}}var fe=3e4,_=class{constructor(e,i,a,o,l,g,v,R,u,S){this.eventBus=e;this.configurations=i;this.url=a;this.apiKey=o;this.standardHeaders=l;this.fallbackPoller=g;this.logDebug=v;this.logError=R;this.eventCallback=u;this.maxRetries=S;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1;this.reconnectAttempts=0;this.retriesExhausted=!1}start(){let e=u=>{u.toString().split(/\r?\n/).forEach(i)},i=u=>{if(u.startsWith("data:")){let S=JSON.parse(u.substring(5));this.logDebugMessage("Received event from stream: ",S),this.eventCallback(S)}},a=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected"),this.reconnectAttempts=0},o=()=>{clearInterval(this.readTimeoutCheckerId);let u=k(1e3,1e4);if(this.reconnectAttempts++,this.logDebugMessage("Stream disconnected, will reconnect in "+u+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),this.reconnectAttempts>=5&&this.reconnectAttempts%5===0&&this.logErrorMessage(`Reconnection failed after ${this.reconnectAttempts} attempts; attempting further reconnections.`),this.reconnectAttempts>=this.maxRetries){this.retriesExhausted=!0,this.configurations.pollingEnabled?this.logErrorMessage("Max streaming retries reached. Staying in polling mode."):this.logErrorMessage("Max streaming retries reached. Polling mode is disabled and will receive no further flag updates until SDK client is restarted.");return}setTimeout(()=>this.start(),u)},l=u=>{this.retriesExhausted||(u&&this.logDebugMessage("Stream has issue",u),this.fallBackToPolling(),this.eventBus.emit("stream error",u),this.eventBus.emit("error",u),o())},g=w({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[u,S]of Object.entries(g))this.xhr.setRequestHeader(u,S);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{l(`Received XMLHttpRequest onLoad event: ${this.xhr.status}`)};let v=0,R=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(a(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),R=Date.now();let u=this.xhr.responseText.slice(v);v+=u.length,this.logDebugMessage("SSE GOT: "+u),e(u)},this.readTimeoutCheckerId=setInterval(()=>{R<Date.now()-fe&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},fe),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...i){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...i)}logErrorMessage(e,...i){this.logError(`Streaming: ${e}`,...i)}};function he(t,e,i,a,o,l){let g=t in i,v=g?i[t]:e;if(g)a(t,v);else{let R={flag:t,defaultVariation:e};o.emit("default variation returned",R)}return l?{value:v,isDefaultValue:!g}:v}var x=class{constructor(e,i,a,o,l){this.fetchFlagsFn=e;this.configurations=i;this.eventBus=a;this.logDebug=o;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.isRunning&&this.attemptFetch().finally(()=>{this.isRunning&&(this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval))})}attemptFetch(){return E(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let i=yield this.fetchFlagsFn();if(i.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",i.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,i.error);let a=k(1e3,1e4);yield new Promise(o=>setTimeout(o,a))}})}stop(){this.timeoutId&&(this.isRunning=!1,clearTimeout(this.timeoutId),this.timeoutId=void 0,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...i){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...i)}logErrorMessage(e,...i){this.logError(`Poller: ${e}`,...i)}};function me(i){return E(this,arguments,function*(t,e={}){let a=yield Ge(t),o=qe(e);return{loadFromCache:()=>Y(a,o,e),saveToCache:l=>X(a,o,l),updateCachedEvaluation:l=>He(a,o,l),removeCachedEvaluation:l=>$e(a,o,l)}})}function Y(a,o){return E(this,arguments,function*(t,e,i={}){let l=parseInt(yield e.getItem(t+".ts"));if(i!=null&&i.ttl&&!isNaN(l)&&l+i.ttl<Date.now())return yield Le(t,e),[];let g=yield e.getItem(t);if(g)try{return JSON.parse(g)}catch(v){}return[]})}function Le(t,e){return E(this,null,function*(){yield e.removeItem(t),yield e.removeItem(t+".ts")})}function X(t,e,i){return E(this,null,function*(){yield e.setItem(t,JSON.stringify(i)),yield e.setItem(t+".ts",Date.now().toString())})}function He(t,e,i){return E(this,null,function*(){let a=yield Y(t,e),o=a.find(({flag:l})=>l===i.flag);o?Object.assign(o,i):a.push(i),yield X(t,e,a)})}function $e(t,e,i){return E(this,null,function*(){let a=yield Y(t,e),o=a.findIndex(({flag:l})=>l===i);o>-1&&(a.splice(o,1),yield X(t,e,a))})}function Ge(t){return E(this,null,function*(){var i,a;let e=t;if(globalThis!=null&&globalThis.TextEncoder&&((a=(i=globalThis==null?void 0:globalThis.crypto)==null?void 0:i.subtle)!=null&&a.digest)){let l=new TextEncoder().encode(t),g=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(g)).map(R=>R.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(t));return"HARNESS_FF_CACHE_"+e})}function qe(t){let e;return!t.storage||typeof t.storage!="object"||!("getItem"in t.storage)||!("setItem"in t.storage)||!("removeItem"in t.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Be:e=t.storage,{getItem(a){return E(this,null,function*(){let o=e.getItem(a);return o instanceof Promise?yield o:o})},setItem(a,o){return E(this,null,function*(){let l=e.setItem(a,o);l instanceof Promise&&(yield l)})},removeItem(a){return E(this,null,function*(){let o=e.removeItem(a);o instanceof Promise&&(yield o)})}}}var Be={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var ve="1.26.1",pe=`Javascript ${ve} Client`,Ue=500,Ke=globalThis.fetch,z=!!globalThis.Proxy,je=(t,e,i)=>{let a=!1,o,l,g,v,R,u,S=!0,C={},F=J(n=>n),Q=0,Z=!1,L=()=>{S=!1},H=()=>{S=!0},d=[],h=ue(),p=de(i),b=(n,...r)=>{p.debug&&p.logger.debug(`[FF-SDK] ${n}`,...r)},A=(n,...r)=>{p.logger.error(`[FF-SDK] ${n}`,...r)},Ee=(n,...r)=>{p.logger.warn(`[FF-SDK] ${n}`,...r)},$=n=>{let{value:r}=n;try{switch(n.kind.toLowerCase()){case"int":case"number":r=Number(r);break;case"boolean":r=r.toString().toLowerCase()==="true";break;case"json":r=JSON.parse(r);break}}catch(c){A(c)}return r},G=n=>{if(S){let r=Date.now();r-n.lastAccessed>Ue&&(n.count++,n.lastAccessed=r)}},Re=()=>E(void 0,null,function*(){if(p.cache){b("initializing cache");try{let n=!0,r=yield me(e.identifier+t,typeof p.cache=="boolean"?{}:p.cache),c=yield r.loadFromCache();c!=null&&c.length&&W(()=>{b("loading from cache",c),ne(c,!1),h.emit("cache loaded",c)}),U("flags loaded",m=>E(void 0,null,function*(){yield r.saveToCache(m),n=!1})),U("changed",m=>E(void 0,null,function*(){n||(m.deleted?yield r.removeCachedEvaluation(m.flag):yield r.updateCachedEvaluation(m))}))}catch(n){A("Cache error: ",n),h.emit("cache error",n),h.emit("error",n)}}}),be=(n,r)=>E(void 0,null,function*(){let c=`${r.baseUrl}/client/auth`,m={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":pe},body:JSON.stringify({apiKey:n,target:K(w({},e),{identifier:String(e.identifier)})})},y,s;window.AbortController&&p.authRequestReadTimeout>0?(s=new AbortController,m.signal=s.signal,y=window.setTimeout(()=>s.abort(),r.authRequestReadTimeout)):r.authRequestReadTimeout>0&&Ee("AbortController is not available, auth request will not timeout");try{let f=yield Ke(c,m);if(!f.ok)throw new Error(`${f.status}: ${f.statusText}`);return(yield f.json()).authToken}catch(f){if(s&&s.signal.aborted)throw new Error(`Request to ${c} failed: Request timeout via configured authRequestTimeout of ${p.authRequestReadTimeout}`);let D=f instanceof Error?f.message:String(f);throw new Error(`Request to ${c} failed: ${D}`)}finally{y&&clearTimeout(y)}}),q=0,B=()=>{if(d.length){b("Sending metrics...",{metrics:d,evaluations:I});let n={metricsData:d.map(r=>({timestamp:Date.now(),count:r.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:r.featureIdentifier},{key:"featureName",value:r.featureIdentifier},{key:"variationIdentifier",value:r.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:ve}]}))};F(`${p.eventUrl}/metrics/${o}?cluster=${l}`,{method:"POST",headers:w({"Content-Type":"application/json"},C),body:JSON.stringify(n)}).then(()=>{d=[],q=0}).catch(r=>{q++&&(d=[],q=0),b(r),h.emit("metrics error",r)}).finally(()=>{u=window.setTimeout(B,p.eventsSyncInterval)})}else u=window.setTimeout(B,p.eventsSyncInterval)},I={},ye=n=>{b("Sending event for",n.flag),z?h.emit("changed",new Proxy(n,{get(r,c){var m;if(S&&r.hasOwnProperty(c)&&c==="value"){let y=r.flag,s=n.value,f=d.find(D=>D.featureIdentifier===y&&D.featureValue===s);f?(G(f),f.variationIdentifier=((m=I[y])==null?void 0:m.identifier)||""):d.push({featureIdentifier:y,featureValue:String(s),variationIdentifier:I[y].identifier||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag",c,"has been read with value via stream update",s)}return c==="value"?$(n):n[c]}})):h.emit("changed",{deleted:n.deleted,flag:n.flag,value:$(n)})},ee=function(){return z?new Proxy({},{get(n,r){var m,y,s;let c=n[r];if(S&&n.hasOwnProperty(r)){let f=n[r],D=d.find(re=>re.featureIdentifier===r&&f===re.featureValue);D?(D.variationIdentifier=((m=I[r])==null?void 0:m.identifier)||"",G(D)):d.push({featureIdentifier:r,featureValue:f,variationIdentifier:((y=I[r])==null?void 0:y.identifier)||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag:",r,"has been read with value:",f,"variationIdentifier:",(s=I[r])==null?void 0:s.identifier)}return c}}):{}},T=ee();Re().then(()=>be(t,p).then(n=>E(void 0,null,function*(){if(a)return;R=n;let r=ce(n);C={Authorization:`Bearer ${R}`,"Harness-AccountID":r.accountID,"Harness-EnvironmentID":r.environmentIdentifier,"Harness-SDK-Info":pe};let c=ge(e);c.length<262144&&(C["Harness-Target"]=c),b("Authenticated",r),u=window.setTimeout(B,p.eventsSyncInterval),o=r.environment,l=r.clusterIdentifier;let m=!!Object.keys(I).length;if((yield M()).type==="success"&&b("Fetch all flags ok",T),!a){if(p.streamEnabled?(b("Streaming mode enabled"),Se()):p.pollingEnabled?(b("Polling mode enabled"),Ie()):b("Streaming and polling mode disabled"),!m){L();let s=w({},T);H(),h.emit("ready",s)}Z=!0}})).catch(n=>{A("Authentication error: ",n),h.emit("auth error",n),h.emit("error",n)}));let M=()=>E(void 0,null,function*(){try{let n=yield F(`${p.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:C});if(n.ok){let r=yield n.json();return r.forEach(O),h.emit("flags loaded",r),{type:"success",data:r}}else return A("Features fetch operation error: ",n),h.emit("fetch flags error",n),h.emit("error",n),{type:"error",error:n}}catch(n){return A("Features fetch operation error: ",n),h.emit("fetch flags error",n),h.emit("error",n),{type:"error",error:n}}}),te=n=>E(void 0,null,function*(){try{let r=yield F(`${p.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations/${n}?cluster=${l}`,{headers:C});if(r.ok){let c=yield r.json();O(c)}else A("Feature fetch operation error: ",r),h.emit("fetch flag error",r),h.emit("error",r)}catch(r){A("Feature fetch operation error: ",r),h.emit("fetch flag error",r),h.emit("error",r)}}),O=n=>{L();let r=$(n);r!==T[n.flag]&&(b("Flag variation has changed for ",n.identifier),T[n.flag]=r,I[n.flag]=K(w({},n),{value:r}),ye(n)),H()};v=new x(M,p,h,b,A);let Se=()=>{let n=s=>{switch(s.event){case"create":c(s.evaluations)?s.evaluations.forEach(f=>{O(f)}):setTimeout(()=>te(s.identifier),1e3);break;case"patch":c(s.evaluations)?s.evaluations.forEach(f=>{O(f)}):te(s.identifier);break;case"delete":delete T[s.identifier],h.emit("changed",{flag:s.identifier,value:void 0,deleted:!0}),b("Evaluation deleted",{message:s,storage:T});break}},r=s=>!(!s||!s.flag||!s.identifier||!s.kind||!s.value),c=s=>!(!s||s.length==0||!s.every(f=>r(f))),m=s=>{s.event==="patch"&&(c(s.evaluations)?s.evaluations.forEach(f=>{O(f)}):M())},y=`${p.baseUrl}/stream?cluster=${l}`;g=new _(h,p,y,t,C,v,b,A,s=>{s.domain==="flag"?n(s):s.domain==="target-segment"&&m(s)},p.maxStreamRetries),g.start()},Ie=()=>{v.start()},U=(n,r)=>h.on(n,r),we=(n,r)=>{n?h.off(n,r):ie()},Ce=(n,r)=>{var s;if(!S||z||r===void 0)return;let c=r,m=n,y=d.find(f=>f.featureIdentifier===m&&f.featureValue===c);y?(G(y),y.variationIdentifier=((s=I[m])==null?void 0:s.identifier)||""):d.push({featureIdentifier:m,featureValue:c,count:1,variationIdentifier:I[m].identifier||"",lastAccessed:Date.now()})},ie=()=>{a=!0,p.streamEnabled&&(b("Closing event stream"),typeof(g==null?void 0:g.close)=="function"&&g.close(),h.all.clear()),p.pollingEnabled&&v.isPolling()&&(b("Closing Poller"),v.stop()),T=ee(),I={},clearTimeout(u)},ne=(n,r=!0)=>{n.length&&W(()=>{let c=!!Object.keys(I).length;if(n.forEach(O),!c){L();let m=w({},T);H(),h.emit("ready",m)}},r)};return{on:U,off:we,close:ie,setEvaluations:ne,registerAPIRequestMiddleware:n=>{F=J(n)},refreshEvaluations:()=>{Z&&!a&&Date.now()-Q>=6e4&&(M(),Q=Date.now())},variation:(n,r,c=!1)=>he(n,r,T,Ce,h,c)}};return Me(We);})();
var HarnessFFSDK=(()=>{var V=Object.defineProperty,Oe=Object.defineProperties,De=Object.getOwnPropertyDescriptor,Pe=Object.getOwnPropertyDescriptors,xe=Object.getOwnPropertyNames,oe=Object.getOwnPropertySymbols;var le=Object.prototype.hasOwnProperty,Fe=Object.prototype.propertyIsEnumerable;var se=(t,e,i)=>e in t?V(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,I=(t,e)=>{for(var i in e||(e={}))le.call(e,i)&&se(t,i,e[i]);if(oe)for(var i of oe(e))Fe.call(e,i)&&se(t,i,e[i]);return t},x=(t,e)=>Oe(t,Pe(e));var Me=(t,e)=>{for(var i in e)V(t,i,{get:e[i],enumerable:!0})},Ne=(t,e,i,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of xe(e))!le.call(t,o)&&o!==i&&V(t,o,{get:()=>e[o],enumerable:!(a=De(e,o))||a.enumerable});return t};var Ve=t=>Ne(V({},"__esModule",{value:!0}),t);var R=(t,e,i)=>new Promise((a,o)=>{var l=b=>{try{E(i.next(b))}catch(u){o(u)}},g=b=>{try{E(i.throw(b))}catch(u){o(u)}},E=b=>b.done?a(b.value):Promise.resolve(b.value).then(l,g);E((i=i.apply(t,e)).next())});var Ye={};Me(Ye,{Event:()=>P,initialize:()=>We});function J(t){this.message=t}J.prototype=new Error,J.prototype.name="InvalidCharacterError";var ce=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new J("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,a,o=0,l=0,g="";a=e.charAt(l++);~a&&(i=o%4?64*i+a:a,o++%4)?g+=String.fromCharCode(255&i>>(-2*o&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return g};function ke(t){var e=t.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(i){return decodeURIComponent(ce(i).replace(/(.)/g,function(a,o){var l=o.charCodeAt(0).toString(16).toUpperCase();return l.length<2&&(l="0"+l),"%"+l}))}(e)}catch(i){return ce(e)}}function k(t){this.message=t}function _e(t,e){if(typeof t!="string")throw new k("Invalid token specified");var i=(e=e||{}).header===!0?0:1;try{return JSON.parse(ke(t.split(".")[i]))}catch(a){throw new k("Invalid token specified: "+a.message)}}k.prototype=new Error,k.prototype.name="InvalidTokenError";var ue=_e;function de(t){return{all:t=t||new Map,on:function(e,i){var a=t.get(e);a&&a.push(i)||t.set(e,[i])},off:function(e,i){var a=t.get(e);a&&a.splice(a.indexOf(i)>>>0,1)},emit:function(e,i){(t.get(e)||[]).slice().map(function(a){a(i)}),(t.get("*")||[]).slice().map(function(a){a(e,i)})}}}var P=(d=>(d.READY="ready",d.CONNECTED="connected",d.DISCONNECTED="disconnected",d.STOPPED="stopped",d.POLLING="polling",d.POLLING_STOPPED="polling stopped",d.FLAGS_LOADED="flags loaded",d.CACHE_LOADED="cache loaded",d.CHANGED="changed",d.ERROR="error",d.ERROR_CACHE="cache error",d.ERROR_METRICS="metrics error",d.ERROR_AUTH="auth error",d.ERROR_FETCH_FLAGS="fetch flags error",d.ERROR_FETCH_FLAG="fetch flag error",d.ERROR_STREAM="stream error",d.ERROR_DEFAULT_VARIATION_RETURNED="default variation returned",d))(P||{});var Le={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},ge=t=>{let e=I(I({},Le),t);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},W=(t,e=!0)=>{e?setTimeout(t,0):t()},_=(t,e)=>Math.round(Math.random()*(e-t)+t),fe=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i="",a=0,o=He(JSON.stringify(t));for(;a<o.length;){let l=o.charCodeAt(a++),g=o.charCodeAt(a++),E=o.charCodeAt(a++),b=l>>2,u=(l&3)<<4|g>>4,S=(g&15)<<2|E>>6,w=E&63;isNaN(g)?S=w=64:isNaN(E)&&(w=64),i+=e.charAt(b)+e.charAt(u)+e.charAt(S)+e.charAt(w)}return i},He=t=>t.replace(/\r\n/g,`
`).split("").map(e=>{let i=e.charCodeAt(0);return i<128?String.fromCharCode(i):i>127&&i<2048?String.fromCharCode(i>>6|192)+String.fromCharCode(i&63|128):String.fromCharCode(i>>12|224)+String.fromCharCode(i>>6&63|128)+String.fromCharCode(i&63|128)}).join("");function L(t){return[...t].sort(({flag:e},{flag:i})=>e<i?-1:1)}function Y(t){return function(...i){let[a,o]=t(i);return fetch(a,o)}}var he=3e4,H=class{constructor(e,i,a,o,l,g,E,b,u,S){this.eventBus=e;this.configurations=i;this.url=a;this.apiKey=o;this.standardHeaders=l;this.fallbackPoller=g;this.logDebug=E;this.logError=b;this.eventCallback=u;this.maxRetries=S;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1;this.reconnectAttempts=0;this.retriesExhausted=!1}start(){let e=u=>{u.toString().split(/\r?\n/).forEach(i)},i=u=>{if(u.startsWith("data:")){let S=JSON.parse(u.substring(5));this.logDebugMessage("Received event from stream: ",S),this.eventCallback(S)}},a=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected"),this.reconnectAttempts=0},o=()=>{clearInterval(this.readTimeoutCheckerId);let u=_(1e3,1e4);if(this.reconnectAttempts++,this.logDebugMessage("Stream disconnected, will reconnect in "+u+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),this.reconnectAttempts>=5&&this.reconnectAttempts%5===0&&this.logErrorMessage(`Reconnection failed after ${this.reconnectAttempts} attempts; attempting further reconnections.`),this.reconnectAttempts>=this.maxRetries){this.retriesExhausted=!0,this.configurations.pollingEnabled?this.logErrorMessage("Max streaming retries reached. Staying in polling mode."):this.logErrorMessage("Max streaming retries reached. Polling mode is disabled and will receive no further flag updates until SDK client is restarted.");return}setTimeout(()=>this.start(),u)},l=u=>{this.retriesExhausted||(u&&this.logDebugMessage("Stream has issue",u),this.fallBackToPolling(),this.eventBus.emit("stream error",u),this.eventBus.emit("error",u),o())},g=I({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[u,S]of Object.entries(g))this.xhr.setRequestHeader(u,S);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{l(`Received XMLHttpRequest onLoad event: ${this.xhr.status}`)};let E=0,b=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(a(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),b=Date.now();let u=this.xhr.responseText.slice(E);E+=u.length,this.logDebugMessage("SSE GOT: "+u),e(u)},this.readTimeoutCheckerId=setInterval(()=>{b<Date.now()-he&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},he),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...i){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...i)}logErrorMessage(e,...i){this.logError(`Streaming: ${e}`,...i)}};function me(t,e,i,a,o,l){let g=t in i,E=g?i[t]:e;if(g)a(t,E);else{let b={flag:t,defaultVariation:e};o.emit("default variation returned",b)}return l?{value:E,isDefaultValue:!g}:E}var F=class{constructor(e,i,a,o,l){this.fetchFlagsFn=e;this.configurations=i;this.eventBus=a;this.logDebug=o;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.isRunning&&this.attemptFetch().finally(()=>{this.isRunning&&(this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval))})}attemptFetch(){return R(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let i=yield this.fetchFlagsFn();if(i.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",i.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,i.error);let a=_(1e3,1e4);yield new Promise(o=>setTimeout(o,a))}})}stop(){this.timeoutId&&(this.isRunning=!1,clearTimeout(this.timeoutId),this.timeoutId=void 0,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...i){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...i)}logErrorMessage(e,...i){this.logError(`Poller: ${e}`,...i)}};function ve(i){return R(this,arguments,function*(t,e={}){let a=yield Be(t),o=Ue(e);return{loadFromCache:()=>X(a,o,e),saveToCache:l=>z(a,o,l),updateCachedEvaluation:l=>Ge(a,o,l),removeCachedEvaluation:l=>qe(a,o,l)}})}function X(a,o){return R(this,arguments,function*(t,e,i={}){let l=parseInt(yield e.getItem(t+".ts"));if(i!=null&&i.ttl&&!isNaN(l)&&l+i.ttl<Date.now())return yield $e(t,e),[];let g=yield e.getItem(t);if(g)try{return JSON.parse(g)}catch(E){}return[]})}function $e(t,e){return R(this,null,function*(){yield e.removeItem(t),yield e.removeItem(t+".ts")})}function z(t,e,i){return R(this,null,function*(){yield e.setItem(t,JSON.stringify(L(i))),yield e.setItem(t+".ts",Date.now().toString())})}function Ge(t,e,i){return R(this,null,function*(){let a=yield X(t,e),o=a.find(({flag:l})=>l===i.flag);o?Object.assign(o,i):a.push(i),yield z(t,e,a)})}function qe(t,e,i){return R(this,null,function*(){let a=yield X(t,e),o=a.findIndex(({flag:l})=>l===i);o>-1&&(a.splice(o,1),yield z(t,e,a))})}function pe(t,e,i={}){return i.deriveKeyFromTargetAttributes?JSON.stringify(Object.keys(t.attributes||{}).sort().filter(a=>!Array.isArray(i.deriveKeyFromTargetAttributes)||i.deriveKeyFromTargetAttributes.includes(a)).reduce((a,o)=>x(I({},a),{[o]:t.attributes[o]}),{}))+t.identifier+e:t.identifier+e}function Be(t){return R(this,null,function*(){var i,a;let e=t;if(globalThis!=null&&globalThis.TextEncoder&&((a=(i=globalThis==null?void 0:globalThis.crypto)==null?void 0:i.subtle)!=null&&a.digest)){let l=new TextEncoder().encode(t),g=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(g)).map(b=>b.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(t));return"HARNESS_FF_CACHE_"+e})}function Ue(t){let e;return!t.storage||typeof t.storage!="object"||!("getItem"in t.storage)||!("setItem"in t.storage)||!("removeItem"in t.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Ke:e=t.storage,{getItem(a){return R(this,null,function*(){let o=e.getItem(a);return o instanceof Promise?yield o:o})},setItem(a,o){return R(this,null,function*(){let l=e.setItem(a,o);l instanceof Promise&&(yield l)})},removeItem(a){return R(this,null,function*(){let o=e.removeItem(a);o instanceof Promise&&(yield o)})}}}var Ke={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var Re="1.26.1",Ee=`Javascript ${Re} Client`,je=500,Je=globalThis.fetch,Q=!!globalThis.Proxy,We=(t,e,i)=>{let a=!1,o,l,g,E,b,u,S=!0,w={},M=Y(n=>n),Z=0,ee=!1,$=()=>{S=!1},G=()=>{S=!0},d=[],h=de(),v=ge(i),y=(n,...r)=>{v.debug&&v.logger.debug(`[FF-SDK] ${n}`,...r)},A=(n,...r)=>{v.logger.error(`[FF-SDK] ${n}`,...r)},be=(n,...r)=>{v.logger.warn(`[FF-SDK] ${n}`,...r)},q=n=>{let{value:r}=n;try{switch(n.kind.toLowerCase()){case"int":case"number":r=Number(r);break;case"boolean":r=r.toString().toLowerCase()==="true";break;case"json":r=JSON.parse(r);break}}catch(c){A(c)}return r},B=n=>{if(S){let r=Date.now();r-n.lastAccessed>je&&(n.count++,n.lastAccessed=r)}},ye=()=>R(void 0,null,function*(){if(v.cache){y("initializing cache");try{let n=!0,r=typeof v.cache=="boolean"?{}:v.cache,c=yield ve(pe(e,t,r),r),m=yield c.loadFromCache();m!=null&&m.length&&W(()=>{y("loading from cache",m),re(m,!1),h.emit("cache loaded",m)}),j("flags loaded",p=>R(void 0,null,function*(){yield c.saveToCache(p),n=!1})),j("changed",p=>R(void 0,null,function*(){n||(p.deleted?yield c.removeCachedEvaluation(p.flag):yield c.updateCachedEvaluation(p))}))}catch(n){A("Cache error: ",n),h.emit("cache error",n),h.emit("error",n)}}}),Se=(n,r)=>R(void 0,null,function*(){let c=`${r.baseUrl}/client/auth`,m={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":Ee},body:JSON.stringify({apiKey:n,target:x(I({},e),{identifier:String(e.identifier)})})},p,s;window.AbortController&&v.authRequestReadTimeout>0?(s=new AbortController,m.signal=s.signal,p=window.setTimeout(()=>s.abort(),r.authRequestReadTimeout)):r.authRequestReadTimeout>0&&be("AbortController is not available, auth request will not timeout");try{let f=yield Je(c,m);if(!f.ok)throw new Error(`${f.status}: ${f.statusText}`);return(yield f.json()).authToken}catch(f){if(s&&s.signal.aborted)throw new Error(`Request to ${c} failed: Request timeout via configured authRequestTimeout of ${v.authRequestReadTimeout}`);let O=f instanceof Error?f.message:String(f);throw new Error(`Request to ${c} failed: ${O}`)}finally{p&&clearTimeout(p)}}),U=0,K=()=>{if(d.length){y("Sending metrics...",{metrics:d,evaluations:C});let n={metricsData:d.map(r=>({timestamp:Date.now(),count:r.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:r.featureIdentifier},{key:"featureName",value:r.featureIdentifier},{key:"variationIdentifier",value:r.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:Re}]}))};M(`${v.eventUrl}/metrics/${o}?cluster=${l}`,{method:"POST",headers:I({"Content-Type":"application/json"},w),body:JSON.stringify(n)}).then(()=>{d=[],U=0}).catch(r=>{U++&&(d=[],U=0),y(r),h.emit("metrics error",r)}).finally(()=>{u=window.setTimeout(K,v.eventsSyncInterval)})}else u=window.setTimeout(K,v.eventsSyncInterval)},C={},Ie=n=>{y("Sending event for",n.flag),Q?h.emit("changed",new Proxy(n,{get(r,c){var m;if(S&&r.hasOwnProperty(c)&&c==="value"){let p=r.flag,s=n.value,f=d.find(O=>O.featureIdentifier===p&&O.featureValue===s);f?(B(f),f.variationIdentifier=((m=C[p])==null?void 0:m.identifier)||""):d.push({featureIdentifier:p,featureValue:String(s),variationIdentifier:C[p].identifier||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag",c,"has been read with value via stream update",s)}return c==="value"?q(n):n[c]}})):h.emit("changed",{deleted:n.deleted,flag:n.flag,value:q(n)})},te=function(){return Q?new Proxy({},{get(n,r){var m,p,s;let c=n[r];if(S&&n.hasOwnProperty(r)){let f=n[r],O=d.find(ae=>ae.featureIdentifier===r&&f===ae.featureValue);O?(O.variationIdentifier=((m=C[r])==null?void 0:m.identifier)||"",B(O)):d.push({featureIdentifier:r,featureValue:f,variationIdentifier:((p=C[r])==null?void 0:p.identifier)||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag:",r,"has been read with value:",f,"variationIdentifier:",(s=C[r])==null?void 0:s.identifier)}return c}}):{}},T=te();ye().then(()=>Se(t,v).then(n=>R(void 0,null,function*(){if(a)return;b=n;let r=ue(n);w={Authorization:`Bearer ${b}`,"Harness-AccountID":r.accountID,"Harness-EnvironmentID":r.environmentIdentifier,"Harness-SDK-Info":Ee};let c=fe(e);c.length<262144&&(w["Harness-Target"]=c),y("Authenticated",r),u=window.setTimeout(K,v.eventsSyncInterval),o=r.environment,l=r.clusterIdentifier;let m=!!Object.keys(C).length;if((yield N()).type==="success"&&y("Fetch all flags ok",T),!a){if(v.streamEnabled?(y("Streaming mode enabled"),Ce()):v.pollingEnabled?(y("Polling mode enabled"),we()):y("Streaming and polling mode disabled"),!m){$();let s=I({},T);G(),h.emit("ready",s)}ee=!0}})).catch(n=>{A("Authentication error: ",n),h.emit("auth error",n),h.emit("error",n)}));let N=()=>R(void 0,null,function*(){try{let n=yield M(`${v.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:w});if(n.ok){let r=L(yield n.json());return r.forEach(D),h.emit("flags loaded",r),{type:"success",data:r}}else return A("Features fetch operation error: ",n),h.emit("fetch flags error",n),h.emit("error",n),{type:"error",error:n}}catch(n){return A("Features fetch operation error: ",n),h.emit("fetch flags error",n),h.emit("error",n),{type:"error",error:n}}}),ie=n=>R(void 0,null,function*(){try{let r=yield M(`${v.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations/${n}?cluster=${l}`,{headers:w});if(r.ok){let c=yield r.json();D(c)}else A("Feature fetch operation error: ",r),h.emit("fetch flag error",r),h.emit("error",r)}catch(r){A("Feature fetch operation error: ",r),h.emit("fetch flag error",r),h.emit("error",r)}}),D=n=>{$();let r=q(n);r!==T[n.flag]&&(y("Flag variation has changed for ",n.identifier),T[n.flag]=r,C[n.flag]=x(I({},n),{value:r}),Ie(n)),G()};E=new F(N,v,h,y,A);let Ce=()=>{let n=s=>{switch(s.event){case"create":c(s.evaluations)?s.evaluations.forEach(f=>{D(f)}):setTimeout(()=>ie(s.identifier),1e3);break;case"patch":c(s.evaluations)?s.evaluations.forEach(f=>{D(f)}):ie(s.identifier);break;case"delete":delete T[s.identifier],h.emit("changed",{flag:s.identifier,value:void 0,deleted:!0}),y("Evaluation deleted",{message:s,storage:T});break}},r=s=>!(!s||!s.flag||!s.identifier||!s.kind||!s.value),c=s=>!(!s||s.length==0||!s.every(f=>r(f))),m=s=>{s.event==="patch"&&(c(s.evaluations)?s.evaluations.forEach(f=>{D(f)}):N())},p=`${v.baseUrl}/stream?cluster=${l}`;g=new H(h,v,p,t,w,E,y,A,s=>{s.domain==="flag"?n(s):s.domain==="target-segment"&&m(s)},v.maxStreamRetries),g.start()},we=()=>{E.start()},j=(n,r)=>h.on(n,r),Ae=(n,r)=>{n?h.off(n,r):ne()},Te=(n,r)=>{var s;if(!S||Q||r===void 0)return;let c=r,m=n,p=d.find(f=>f.featureIdentifier===m&&f.featureValue===c);p?(B(p),p.variationIdentifier=((s=C[m])==null?void 0:s.identifier)||""):d.push({featureIdentifier:m,featureValue:c,count:1,variationIdentifier:C[m].identifier||"",lastAccessed:Date.now()})},ne=()=>{a=!0,v.streamEnabled&&(y("Closing event stream"),typeof(g==null?void 0:g.close)=="function"&&g.close(),h.all.clear()),v.pollingEnabled&&E.isPolling()&&(y("Closing Poller"),E.stop()),T=te(),C={},clearTimeout(u)},re=(n,r=!0)=>{n.length&&W(()=>{let c=!!Object.keys(C).length;if(n.forEach(D),!c){$();let m=I({},T);G(),h.emit("ready",m)}},r)};return{on:j,off:Ae,close:ne,setEvaluations:re,registerAPIRequestMiddleware:n=>{M=Y(n)},refreshEvaluations:()=>{ee&&!a&&Date.now()-Z>=6e4&&(N(),Z=Date.now())},variation:(n,r,c=!1)=>me(n,r,T,Te,h,c)}};return Ve(Ye);})();

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

var we=Object.defineProperty,Ce=Object.defineProperties;var Ae=Object.getOwnPropertyDescriptors;var re=Object.getOwnPropertySymbols;var Te=Object.prototype.hasOwnProperty,De=Object.prototype.propertyIsEnumerable;var ae=(t,e,i)=>e in t?we(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,w=(t,e)=>{for(var i in e||(e={}))Te.call(e,i)&&ae(t,i,e[i]);if(re)for(var i of re(e))De.call(e,i)&&ae(t,i,e[i]);return t},U=(t,e)=>Ce(t,Ae(e));var E=(t,e,i)=>new Promise((a,o)=>{var l=R=>{try{v(i.next(R))}catch(u){o(u)}},g=R=>{try{v(i.throw(R))}catch(u){o(u)}},v=R=>R.done?a(R.value):Promise.resolve(R.value).then(l,g);v((i=i.apply(t,e)).next())});function K(t){this.message=t}K.prototype=new Error,K.prototype.name="InvalidCharacterError";var oe=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new K("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,a,o=0,l=0,g="";a=e.charAt(l++);~a&&(i=o%4?64*i+a:a,o++%4)?g+=String.fromCharCode(255&i>>(-2*o&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return g};function Oe(t){var e=t.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(i){return decodeURIComponent(oe(i).replace(/(.)/g,function(a,o){var l=o.charCodeAt(0).toString(16).toUpperCase();return l.length<2&&(l="0"+l),"%"+l}))}(e)}catch(i){return oe(e)}}function N(t){this.message=t}function Pe(t,e){if(typeof t!="string")throw new N("Invalid token specified");var i=(e=e||{}).header===!0?0:1;try{return JSON.parse(Oe(t.split(".")[i]))}catch(a){throw new N("Invalid token specified: "+a.message)}}N.prototype=new Error,N.prototype.name="InvalidTokenError";var se=Pe;function le(t){return{all:t=t||new Map,on:function(e,i){var a=t.get(e);a&&a.push(i)||t.set(e,[i])},off:function(e,i){var a=t.get(e);a&&a.splice(a.indexOf(i)>>>0,1)},emit:function(e,i){(t.get(e)||[]).slice().map(function(a){a(i)}),(t.get("*")||[]).slice().map(function(a){a(e,i)})}}}var P=(d=>(d.READY="ready",d.CONNECTED="connected",d.DISCONNECTED="disconnected",d.STOPPED="stopped",d.POLLING="polling",d.POLLING_STOPPED="polling stopped",d.FLAGS_LOADED="flags loaded",d.CACHE_LOADED="cache loaded",d.CHANGED="changed",d.ERROR="error",d.ERROR_CACHE="cache error",d.ERROR_METRICS="metrics error",d.ERROR_AUTH="auth error",d.ERROR_FETCH_FLAGS="fetch flags error",d.ERROR_FETCH_FLAG="fetch flag error",d.ERROR_STREAM="stream error",d.ERROR_DEFAULT_VARIATION_RETURNED="default variation returned",d))(P||{});var xe={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},ce=t=>{let e=w(w({},xe),t);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},j=(t,e=!0)=>{e?setTimeout(t,0):t()},V=(t,e)=>Math.round(Math.random()*(e-t)+t),ue=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i="",a=0,o=Fe(JSON.stringify(t));for(;a<o.length;){let l=o.charCodeAt(a++),g=o.charCodeAt(a++),v=o.charCodeAt(a++),R=l>>2,u=(l&3)<<4|g>>4,S=(g&15)<<2|v>>6,C=v&63;isNaN(g)?S=C=64:isNaN(v)&&(C=64),i+=e.charAt(R)+e.charAt(u)+e.charAt(S)+e.charAt(C)}return i},Fe=t=>t.replace(/\r\n/g,`
`).split("").map(e=>{let i=e.charCodeAt(0);return i<128?String.fromCharCode(i):i>127&&i<2048?String.fromCharCode(i>>6|192)+String.fromCharCode(i&63|128):String.fromCharCode(i>>12|224)+String.fromCharCode(i>>6&63|128)+String.fromCharCode(i&63|128)}).join("");function W(t){return function(...i){let[a,o]=t(i);return fetch(a,o)}}var de=3e4,k=class{constructor(e,i,a,o,l,g,v,R,u,S){this.eventBus=e;this.configurations=i;this.url=a;this.apiKey=o;this.standardHeaders=l;this.fallbackPoller=g;this.logDebug=v;this.logError=R;this.eventCallback=u;this.maxRetries=S;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1;this.reconnectAttempts=0;this.retriesExhausted=!1}start(){let e=u=>{u.toString().split(/\r?\n/).forEach(i)},i=u=>{if(u.startsWith("data:")){let S=JSON.parse(u.substring(5));this.logDebugMessage("Received event from stream: ",S),this.eventCallback(S)}},a=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected"),this.reconnectAttempts=0},o=()=>{clearInterval(this.readTimeoutCheckerId);let u=V(1e3,1e4);if(this.reconnectAttempts++,this.logDebugMessage("Stream disconnected, will reconnect in "+u+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),this.reconnectAttempts>=5&&this.reconnectAttempts%5===0&&this.logErrorMessage(`Reconnection failed after ${this.reconnectAttempts} attempts; attempting further reconnections.`),this.reconnectAttempts>=this.maxRetries){this.retriesExhausted=!0,this.configurations.pollingEnabled?this.logErrorMessage("Max streaming retries reached. Staying in polling mode."):this.logErrorMessage("Max streaming retries reached. Polling mode is disabled and will receive no further flag updates until SDK client is restarted.");return}setTimeout(()=>this.start(),u)},l=u=>{this.retriesExhausted||(u&&this.logDebugMessage("Stream has issue",u),this.fallBackToPolling(),this.eventBus.emit("stream error",u),this.eventBus.emit("error",u),o())},g=w({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[u,S]of Object.entries(g))this.xhr.setRequestHeader(u,S);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{l(`Received XMLHttpRequest onLoad event: ${this.xhr.status}`)};let v=0,R=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(a(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),R=Date.now();let u=this.xhr.responseText.slice(v);v+=u.length,this.logDebugMessage("SSE GOT: "+u),e(u)},this.readTimeoutCheckerId=setInterval(()=>{R<Date.now()-de&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},de),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...i){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...i)}logErrorMessage(e,...i){this.logError(`Streaming: ${e}`,...i)}};function ge(t,e,i,a,o,l){let g=t in i,v=g?i[t]:e;if(g)a(t,v);else{let R={flag:t,defaultVariation:e};o.emit("default variation returned",R)}return l?{value:v,isDefaultValue:!g}:v}var x=class{constructor(e,i,a,o,l){this.fetchFlagsFn=e;this.configurations=i;this.eventBus=a;this.logDebug=o;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.isRunning&&this.attemptFetch().finally(()=>{this.isRunning&&(this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval))})}attemptFetch(){return E(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let i=yield this.fetchFlagsFn();if(i.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",i.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,i.error);let a=V(1e3,1e4);yield new Promise(o=>setTimeout(o,a))}})}stop(){this.timeoutId&&(this.isRunning=!1,clearTimeout(this.timeoutId),this.timeoutId=void 0,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...i){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...i)}logErrorMessage(e,...i){this.logError(`Poller: ${e}`,...i)}};function fe(i){return E(this,arguments,function*(t,e={}){let a=yield ke(t),o=_e(e);return{loadFromCache:()=>J(a,o,e),saveToCache:l=>Y(a,o,l),updateCachedEvaluation:l=>Ne(a,o,l),removeCachedEvaluation:l=>Ve(a,o,l)}})}function J(a,o){return E(this,arguments,function*(t,e,i={}){let l=parseInt(yield e.getItem(t+".ts"));if(i!=null&&i.ttl&&!isNaN(l)&&l+i.ttl<Date.now())return yield Me(t,e),[];let g=yield e.getItem(t);if(g)try{return JSON.parse(g)}catch(v){}return[]})}function Me(t,e){return E(this,null,function*(){yield e.removeItem(t),yield e.removeItem(t+".ts")})}function Y(t,e,i){return E(this,null,function*(){yield e.setItem(t,JSON.stringify(i)),yield e.setItem(t+".ts",Date.now().toString())})}function Ne(t,e,i){return E(this,null,function*(){let a=yield J(t,e),o=a.find(({flag:l})=>l===i.flag);o?Object.assign(o,i):a.push(i),yield Y(t,e,a)})}function Ve(t,e,i){return E(this,null,function*(){let a=yield J(t,e),o=a.findIndex(({flag:l})=>l===i);o>-1&&(a.splice(o,1),yield Y(t,e,a))})}function ke(t){return E(this,null,function*(){var i,a;let e=t;if(globalThis!=null&&globalThis.TextEncoder&&((a=(i=globalThis==null?void 0:globalThis.crypto)==null?void 0:i.subtle)!=null&&a.digest)){let l=new TextEncoder().encode(t),g=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(g)).map(R=>R.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(t));return"HARNESS_FF_CACHE_"+e})}function _e(t){let e;return!t.storage||typeof t.storage!="object"||!("getItem"in t.storage)||!("setItem"in t.storage)||!("removeItem"in t.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Le:e=t.storage,{getItem(a){return E(this,null,function*(){let o=e.getItem(a);return o instanceof Promise?yield o:o})},setItem(a,o){return E(this,null,function*(){let l=e.setItem(a,o);l instanceof Promise&&(yield l)})},removeItem(a){return E(this,null,function*(){let o=e.removeItem(a);o instanceof Promise&&(yield o)})}}}var Le={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var me="1.26.1",he=`Javascript ${me} Client`,He=500,$e=globalThis.fetch,X=!!globalThis.Proxy,St=(t,e,i)=>{let a=!1,o,l,g,v,R,u,S=!0,C={},F=W(n=>n),z=0,Q=!1,_=()=>{S=!1},L=()=>{S=!0},d=[],h=le(),p=ce(i),b=(n,...r)=>{p.debug&&p.logger.debug(`[FF-SDK] ${n}`,...r)},A=(n,...r)=>{p.logger.error(`[FF-SDK] ${n}`,...r)},pe=(n,...r)=>{p.logger.warn(`[FF-SDK] ${n}`,...r)},H=n=>{let{value:r}=n;try{switch(n.kind.toLowerCase()){case"int":case"number":r=Number(r);break;case"boolean":r=r.toString().toLowerCase()==="true";break;case"json":r=JSON.parse(r);break}}catch(c){A(c)}return r},$=n=>{if(S){let r=Date.now();r-n.lastAccessed>He&&(n.count++,n.lastAccessed=r)}},ve=()=>E(void 0,null,function*(){if(p.cache){b("initializing cache");try{let n=!0,r=yield fe(e.identifier+t,typeof p.cache=="boolean"?{}:p.cache),c=yield r.loadFromCache();c!=null&&c.length&&j(()=>{b("loading from cache",c),ie(c,!1),h.emit("cache loaded",c)}),B("flags loaded",m=>E(void 0,null,function*(){yield r.saveToCache(m),n=!1})),B("changed",m=>E(void 0,null,function*(){n||(m.deleted?yield r.removeCachedEvaluation(m.flag):yield r.updateCachedEvaluation(m))}))}catch(n){A("Cache error: ",n),h.emit("cache error",n),h.emit("error",n)}}}),Ee=(n,r)=>E(void 0,null,function*(){let c=`${r.baseUrl}/client/auth`,m={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":he},body:JSON.stringify({apiKey:n,target:U(w({},e),{identifier:String(e.identifier)})})},y,s;window.AbortController&&p.authRequestReadTimeout>0?(s=new AbortController,m.signal=s.signal,y=window.setTimeout(()=>s.abort(),r.authRequestReadTimeout)):r.authRequestReadTimeout>0&&pe("AbortController is not available, auth request will not timeout");try{let f=yield $e(c,m);if(!f.ok)throw new Error(`${f.status}: ${f.statusText}`);return(yield f.json()).authToken}catch(f){if(s&&s.signal.aborted)throw new Error(`Request to ${c} failed: Request timeout via configured authRequestTimeout of ${p.authRequestReadTimeout}`);let D=f instanceof Error?f.message:String(f);throw new Error(`Request to ${c} failed: ${D}`)}finally{y&&clearTimeout(y)}}),G=0,q=()=>{if(d.length){b("Sending metrics...",{metrics:d,evaluations:I});let n={metricsData:d.map(r=>({timestamp:Date.now(),count:r.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:r.featureIdentifier},{key:"featureName",value:r.featureIdentifier},{key:"variationIdentifier",value:r.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:me}]}))};F(`${p.eventUrl}/metrics/${o}?cluster=${l}`,{method:"POST",headers:w({"Content-Type":"application/json"},C),body:JSON.stringify(n)}).then(()=>{d=[],G=0}).catch(r=>{G++&&(d=[],G=0),b(r),h.emit("metrics error",r)}).finally(()=>{u=window.setTimeout(q,p.eventsSyncInterval)})}else u=window.setTimeout(q,p.eventsSyncInterval)},I={},Re=n=>{b("Sending event for",n.flag),X?h.emit("changed",new Proxy(n,{get(r,c){var m;if(S&&r.hasOwnProperty(c)&&c==="value"){let y=r.flag,s=n.value,f=d.find(D=>D.featureIdentifier===y&&D.featureValue===s);f?($(f),f.variationIdentifier=((m=I[y])==null?void 0:m.identifier)||""):d.push({featureIdentifier:y,featureValue:String(s),variationIdentifier:I[y].identifier||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag",c,"has been read with value via stream update",s)}return c==="value"?H(n):n[c]}})):h.emit("changed",{deleted:n.deleted,flag:n.flag,value:H(n)})},Z=function(){return X?new Proxy({},{get(n,r){var m,y,s;let c=n[r];if(S&&n.hasOwnProperty(r)){let f=n[r],D=d.find(ne=>ne.featureIdentifier===r&&f===ne.featureValue);D?(D.variationIdentifier=((m=I[r])==null?void 0:m.identifier)||"",$(D)):d.push({featureIdentifier:r,featureValue:f,variationIdentifier:((y=I[r])==null?void 0:y.identifier)||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag:",r,"has been read with value:",f,"variationIdentifier:",(s=I[r])==null?void 0:s.identifier)}return c}}):{}},T=Z();ve().then(()=>Ee(t,p).then(n=>E(void 0,null,function*(){if(a)return;R=n;let r=se(n);C={Authorization:`Bearer ${R}`,"Harness-AccountID":r.accountID,"Harness-EnvironmentID":r.environmentIdentifier,"Harness-SDK-Info":he};let c=ue(e);c.length<262144&&(C["Harness-Target"]=c),b("Authenticated",r),u=window.setTimeout(q,p.eventsSyncInterval),o=r.environment,l=r.clusterIdentifier;let m=!!Object.keys(I).length;if((yield M()).type==="success"&&b("Fetch all flags ok",T),!a){if(p.streamEnabled?(b("Streaming mode enabled"),be()):p.pollingEnabled?(b("Polling mode enabled"),ye()):b("Streaming and polling mode disabled"),!m){_();let s=w({},T);L(),h.emit("ready",s)}Q=!0}})).catch(n=>{A("Authentication error: ",n),h.emit("auth error",n),h.emit("error",n)}));let M=()=>E(void 0,null,function*(){try{let n=yield F(`${p.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:C});if(n.ok){let r=yield n.json();return r.forEach(O),h.emit("flags loaded",r),{type:"success",data:r}}else return A("Features fetch operation error: ",n),h.emit("fetch flags error",n),h.emit("error",n),{type:"error",error:n}}catch(n){return A("Features fetch operation error: ",n),h.emit("fetch flags error",n),h.emit("error",n),{type:"error",error:n}}}),ee=n=>E(void 0,null,function*(){try{let r=yield F(`${p.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations/${n}?cluster=${l}`,{headers:C});if(r.ok){let c=yield r.json();O(c)}else A("Feature fetch operation error: ",r),h.emit("fetch flag error",r),h.emit("error",r)}catch(r){A("Feature fetch operation error: ",r),h.emit("fetch flag error",r),h.emit("error",r)}}),O=n=>{_();let r=H(n);r!==T[n.flag]&&(b("Flag variation has changed for ",n.identifier),T[n.flag]=r,I[n.flag]=U(w({},n),{value:r}),Re(n)),L()};v=new x(M,p,h,b,A);let be=()=>{let n=s=>{switch(s.event){case"create":c(s.evaluations)?s.evaluations.forEach(f=>{O(f)}):setTimeout(()=>ee(s.identifier),1e3);break;case"patch":c(s.evaluations)?s.evaluations.forEach(f=>{O(f)}):ee(s.identifier);break;case"delete":delete T[s.identifier],h.emit("changed",{flag:s.identifier,value:void 0,deleted:!0}),b("Evaluation deleted",{message:s,storage:T});break}},r=s=>!(!s||!s.flag||!s.identifier||!s.kind||!s.value),c=s=>!(!s||s.length==0||!s.every(f=>r(f))),m=s=>{s.event==="patch"&&(c(s.evaluations)?s.evaluations.forEach(f=>{O(f)}):M())},y=`${p.baseUrl}/stream?cluster=${l}`;g=new k(h,p,y,t,C,v,b,A,s=>{s.domain==="flag"?n(s):s.domain==="target-segment"&&m(s)},p.maxStreamRetries),g.start()},ye=()=>{v.start()},B=(n,r)=>h.on(n,r),Se=(n,r)=>{n?h.off(n,r):te()},Ie=(n,r)=>{var s;if(!S||X||r===void 0)return;let c=r,m=n,y=d.find(f=>f.featureIdentifier===m&&f.featureValue===c);y?($(y),y.variationIdentifier=((s=I[m])==null?void 0:s.identifier)||""):d.push({featureIdentifier:m,featureValue:c,count:1,variationIdentifier:I[m].identifier||"",lastAccessed:Date.now()})},te=()=>{a=!0,p.streamEnabled&&(b("Closing event stream"),typeof(g==null?void 0:g.close)=="function"&&g.close(),h.all.clear()),p.pollingEnabled&&v.isPolling()&&(b("Closing Poller"),v.stop()),T=Z(),I={},clearTimeout(u)},ie=(n,r=!0)=>{n.length&&j(()=>{let c=!!Object.keys(I).length;if(n.forEach(O),!c){_();let m=w({},T);L(),h.emit("ready",m)}},r)};return{on:B,off:Se,close:te,setEvaluations:ie,registerAPIRequestMiddleware:n=>{F=W(n)},refreshEvaluations:()=>{Q&&!a&&Date.now()-z>=6e4&&(M(),z=Date.now())},variation:(n,r,c=!1)=>ge(n,r,T,Ie,h,c)}};export{P as Event,St as initialize};
var Ae=Object.defineProperty,Te=Object.defineProperties;var Oe=Object.getOwnPropertyDescriptors;var ae=Object.getOwnPropertySymbols;var De=Object.prototype.hasOwnProperty,Pe=Object.prototype.propertyIsEnumerable;var oe=(t,e,i)=>e in t?Ae(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,I=(t,e)=>{for(var i in e||(e={}))De.call(e,i)&&oe(t,i,e[i]);if(ae)for(var i of ae(e))Pe.call(e,i)&&oe(t,i,e[i]);return t},P=(t,e)=>Te(t,Oe(e));var R=(t,e,i)=>new Promise((a,o)=>{var l=b=>{try{E(i.next(b))}catch(u){o(u)}},g=b=>{try{E(i.throw(b))}catch(u){o(u)}},E=b=>b.done?a(b.value):Promise.resolve(b.value).then(l,g);E((i=i.apply(t,e)).next())});function j(t){this.message=t}j.prototype=new Error,j.prototype.name="InvalidCharacterError";var se=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new j("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,a,o=0,l=0,g="";a=e.charAt(l++);~a&&(i=o%4?64*i+a:a,o++%4)?g+=String.fromCharCode(255&i>>(-2*o&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return g};function xe(t){var e=t.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(i){return decodeURIComponent(se(i).replace(/(.)/g,function(a,o){var l=o.charCodeAt(0).toString(16).toUpperCase();return l.length<2&&(l="0"+l),"%"+l}))}(e)}catch(i){return se(e)}}function V(t){this.message=t}function Fe(t,e){if(typeof t!="string")throw new V("Invalid token specified");var i=(e=e||{}).header===!0?0:1;try{return JSON.parse(xe(t.split(".")[i]))}catch(a){throw new V("Invalid token specified: "+a.message)}}V.prototype=new Error,V.prototype.name="InvalidTokenError";var le=Fe;function ce(t){return{all:t=t||new Map,on:function(e,i){var a=t.get(e);a&&a.push(i)||t.set(e,[i])},off:function(e,i){var a=t.get(e);a&&a.splice(a.indexOf(i)>>>0,1)},emit:function(e,i){(t.get(e)||[]).slice().map(function(a){a(i)}),(t.get("*")||[]).slice().map(function(a){a(e,i)})}}}var x=(d=>(d.READY="ready",d.CONNECTED="connected",d.DISCONNECTED="disconnected",d.STOPPED="stopped",d.POLLING="polling",d.POLLING_STOPPED="polling stopped",d.FLAGS_LOADED="flags loaded",d.CACHE_LOADED="cache loaded",d.CHANGED="changed",d.ERROR="error",d.ERROR_CACHE="cache error",d.ERROR_METRICS="metrics error",d.ERROR_AUTH="auth error",d.ERROR_FETCH_FLAGS="fetch flags error",d.ERROR_FETCH_FLAG="fetch flag error",d.ERROR_STREAM="stream error",d.ERROR_DEFAULT_VARIATION_RETURNED="default variation returned",d))(x||{});var Me={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},ue=t=>{let e=I(I({},Me),t);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},J=(t,e=!0)=>{e?setTimeout(t,0):t()},k=(t,e)=>Math.round(Math.random()*(e-t)+t),de=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i="",a=0,o=Ne(JSON.stringify(t));for(;a<o.length;){let l=o.charCodeAt(a++),g=o.charCodeAt(a++),E=o.charCodeAt(a++),b=l>>2,u=(l&3)<<4|g>>4,S=(g&15)<<2|E>>6,w=E&63;isNaN(g)?S=w=64:isNaN(E)&&(w=64),i+=e.charAt(b)+e.charAt(u)+e.charAt(S)+e.charAt(w)}return i},Ne=t=>t.replace(/\r\n/g,`
`).split("").map(e=>{let i=e.charCodeAt(0);return i<128?String.fromCharCode(i):i>127&&i<2048?String.fromCharCode(i>>6|192)+String.fromCharCode(i&63|128):String.fromCharCode(i>>12|224)+String.fromCharCode(i>>6&63|128)+String.fromCharCode(i&63|128)}).join("");function _(t){return[...t].sort(({flag:e},{flag:i})=>e<i?-1:1)}function W(t){return function(...i){let[a,o]=t(i);return fetch(a,o)}}var ge=3e4,L=class{constructor(e,i,a,o,l,g,E,b,u,S){this.eventBus=e;this.configurations=i;this.url=a;this.apiKey=o;this.standardHeaders=l;this.fallbackPoller=g;this.logDebug=E;this.logError=b;this.eventCallback=u;this.maxRetries=S;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1;this.reconnectAttempts=0;this.retriesExhausted=!1}start(){let e=u=>{u.toString().split(/\r?\n/).forEach(i)},i=u=>{if(u.startsWith("data:")){let S=JSON.parse(u.substring(5));this.logDebugMessage("Received event from stream: ",S),this.eventCallback(S)}},a=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected"),this.reconnectAttempts=0},o=()=>{clearInterval(this.readTimeoutCheckerId);let u=k(1e3,1e4);if(this.reconnectAttempts++,this.logDebugMessage("Stream disconnected, will reconnect in "+u+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),this.reconnectAttempts>=5&&this.reconnectAttempts%5===0&&this.logErrorMessage(`Reconnection failed after ${this.reconnectAttempts} attempts; attempting further reconnections.`),this.reconnectAttempts>=this.maxRetries){this.retriesExhausted=!0,this.configurations.pollingEnabled?this.logErrorMessage("Max streaming retries reached. Staying in polling mode."):this.logErrorMessage("Max streaming retries reached. Polling mode is disabled and will receive no further flag updates until SDK client is restarted.");return}setTimeout(()=>this.start(),u)},l=u=>{this.retriesExhausted||(u&&this.logDebugMessage("Stream has issue",u),this.fallBackToPolling(),this.eventBus.emit("stream error",u),this.eventBus.emit("error",u),o())},g=I({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[u,S]of Object.entries(g))this.xhr.setRequestHeader(u,S);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{l(`Received XMLHttpRequest onLoad event: ${this.xhr.status}`)};let E=0,b=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(a(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),b=Date.now();let u=this.xhr.responseText.slice(E);E+=u.length,this.logDebugMessage("SSE GOT: "+u),e(u)},this.readTimeoutCheckerId=setInterval(()=>{b<Date.now()-ge&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},ge),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...i){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...i)}logErrorMessage(e,...i){this.logError(`Streaming: ${e}`,...i)}};function fe(t,e,i,a,o,l){let g=t in i,E=g?i[t]:e;if(g)a(t,E);else{let b={flag:t,defaultVariation:e};o.emit("default variation returned",b)}return l?{value:E,isDefaultValue:!g}:E}var F=class{constructor(e,i,a,o,l){this.fetchFlagsFn=e;this.configurations=i;this.eventBus=a;this.logDebug=o;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.isRunning&&this.attemptFetch().finally(()=>{this.isRunning&&(this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval))})}attemptFetch(){return R(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let i=yield this.fetchFlagsFn();if(i.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",i.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,i.error);let a=k(1e3,1e4);yield new Promise(o=>setTimeout(o,a))}})}stop(){this.timeoutId&&(this.isRunning=!1,clearTimeout(this.timeoutId),this.timeoutId=void 0,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...i){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...i)}logErrorMessage(e,...i){this.logError(`Poller: ${e}`,...i)}};function he(i){return R(this,arguments,function*(t,e={}){let a=yield Le(t),o=He(e);return{loadFromCache:()=>Y(a,o,e),saveToCache:l=>X(a,o,l),updateCachedEvaluation:l=>ke(a,o,l),removeCachedEvaluation:l=>_e(a,o,l)}})}function Y(a,o){return R(this,arguments,function*(t,e,i={}){let l=parseInt(yield e.getItem(t+".ts"));if(i!=null&&i.ttl&&!isNaN(l)&&l+i.ttl<Date.now())return yield Ve(t,e),[];let g=yield e.getItem(t);if(g)try{return JSON.parse(g)}catch(E){}return[]})}function Ve(t,e){return R(this,null,function*(){yield e.removeItem(t),yield e.removeItem(t+".ts")})}function X(t,e,i){return R(this,null,function*(){yield e.setItem(t,JSON.stringify(_(i))),yield e.setItem(t+".ts",Date.now().toString())})}function ke(t,e,i){return R(this,null,function*(){let a=yield Y(t,e),o=a.find(({flag:l})=>l===i.flag);o?Object.assign(o,i):a.push(i),yield X(t,e,a)})}function _e(t,e,i){return R(this,null,function*(){let a=yield Y(t,e),o=a.findIndex(({flag:l})=>l===i);o>-1&&(a.splice(o,1),yield X(t,e,a))})}function me(t,e,i={}){return i.deriveKeyFromTargetAttributes?JSON.stringify(Object.keys(t.attributes||{}).sort().filter(a=>!Array.isArray(i.deriveKeyFromTargetAttributes)||i.deriveKeyFromTargetAttributes.includes(a)).reduce((a,o)=>P(I({},a),{[o]:t.attributes[o]}),{}))+t.identifier+e:t.identifier+e}function Le(t){return R(this,null,function*(){var i,a;let e=t;if(globalThis!=null&&globalThis.TextEncoder&&((a=(i=globalThis==null?void 0:globalThis.crypto)==null?void 0:i.subtle)!=null&&a.digest)){let l=new TextEncoder().encode(t),g=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(g)).map(b=>b.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(t));return"HARNESS_FF_CACHE_"+e})}function He(t){let e;return!t.storage||typeof t.storage!="object"||!("getItem"in t.storage)||!("setItem"in t.storage)||!("removeItem"in t.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=$e:e=t.storage,{getItem(a){return R(this,null,function*(){let o=e.getItem(a);return o instanceof Promise?yield o:o})},setItem(a,o){return R(this,null,function*(){let l=e.setItem(a,o);l instanceof Promise&&(yield l)})},removeItem(a){return R(this,null,function*(){let o=e.removeItem(a);o instanceof Promise&&(yield o)})}}}var $e={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var pe="1.26.1",ve=`Javascript ${pe} Client`,Ge=500,qe=globalThis.fetch,z=!!globalThis.Proxy,wt=(t,e,i)=>{let a=!1,o,l,g,E,b,u,S=!0,w={},M=W(n=>n),Q=0,Z=!1,H=()=>{S=!1},$=()=>{S=!0},d=[],h=ce(),v=ue(i),y=(n,...r)=>{v.debug&&v.logger.debug(`[FF-SDK] ${n}`,...r)},A=(n,...r)=>{v.logger.error(`[FF-SDK] ${n}`,...r)},Ee=(n,...r)=>{v.logger.warn(`[FF-SDK] ${n}`,...r)},G=n=>{let{value:r}=n;try{switch(n.kind.toLowerCase()){case"int":case"number":r=Number(r);break;case"boolean":r=r.toString().toLowerCase()==="true";break;case"json":r=JSON.parse(r);break}}catch(c){A(c)}return r},q=n=>{if(S){let r=Date.now();r-n.lastAccessed>Ge&&(n.count++,n.lastAccessed=r)}},Re=()=>R(void 0,null,function*(){if(v.cache){y("initializing cache");try{let n=!0,r=typeof v.cache=="boolean"?{}:v.cache,c=yield he(me(e,t,r),r),m=yield c.loadFromCache();m!=null&&m.length&&J(()=>{y("loading from cache",m),ne(m,!1),h.emit("cache loaded",m)}),K("flags loaded",p=>R(void 0,null,function*(){yield c.saveToCache(p),n=!1})),K("changed",p=>R(void 0,null,function*(){n||(p.deleted?yield c.removeCachedEvaluation(p.flag):yield c.updateCachedEvaluation(p))}))}catch(n){A("Cache error: ",n),h.emit("cache error",n),h.emit("error",n)}}}),be=(n,r)=>R(void 0,null,function*(){let c=`${r.baseUrl}/client/auth`,m={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":ve},body:JSON.stringify({apiKey:n,target:P(I({},e),{identifier:String(e.identifier)})})},p,s;window.AbortController&&v.authRequestReadTimeout>0?(s=new AbortController,m.signal=s.signal,p=window.setTimeout(()=>s.abort(),r.authRequestReadTimeout)):r.authRequestReadTimeout>0&&Ee("AbortController is not available, auth request will not timeout");try{let f=yield qe(c,m);if(!f.ok)throw new Error(`${f.status}: ${f.statusText}`);return(yield f.json()).authToken}catch(f){if(s&&s.signal.aborted)throw new Error(`Request to ${c} failed: Request timeout via configured authRequestTimeout of ${v.authRequestReadTimeout}`);let O=f instanceof Error?f.message:String(f);throw new Error(`Request to ${c} failed: ${O}`)}finally{p&&clearTimeout(p)}}),B=0,U=()=>{if(d.length){y("Sending metrics...",{metrics:d,evaluations:C});let n={metricsData:d.map(r=>({timestamp:Date.now(),count:r.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:r.featureIdentifier},{key:"featureName",value:r.featureIdentifier},{key:"variationIdentifier",value:r.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:pe}]}))};M(`${v.eventUrl}/metrics/${o}?cluster=${l}`,{method:"POST",headers:I({"Content-Type":"application/json"},w),body:JSON.stringify(n)}).then(()=>{d=[],B=0}).catch(r=>{B++&&(d=[],B=0),y(r),h.emit("metrics error",r)}).finally(()=>{u=window.setTimeout(U,v.eventsSyncInterval)})}else u=window.setTimeout(U,v.eventsSyncInterval)},C={},ye=n=>{y("Sending event for",n.flag),z?h.emit("changed",new Proxy(n,{get(r,c){var m;if(S&&r.hasOwnProperty(c)&&c==="value"){let p=r.flag,s=n.value,f=d.find(O=>O.featureIdentifier===p&&O.featureValue===s);f?(q(f),f.variationIdentifier=((m=C[p])==null?void 0:m.identifier)||""):d.push({featureIdentifier:p,featureValue:String(s),variationIdentifier:C[p].identifier||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag",c,"has been read with value via stream update",s)}return c==="value"?G(n):n[c]}})):h.emit("changed",{deleted:n.deleted,flag:n.flag,value:G(n)})},ee=function(){return z?new Proxy({},{get(n,r){var m,p,s;let c=n[r];if(S&&n.hasOwnProperty(r)){let f=n[r],O=d.find(re=>re.featureIdentifier===r&&f===re.featureValue);O?(O.variationIdentifier=((m=C[r])==null?void 0:m.identifier)||"",q(O)):d.push({featureIdentifier:r,featureValue:f,variationIdentifier:((p=C[r])==null?void 0:p.identifier)||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag:",r,"has been read with value:",f,"variationIdentifier:",(s=C[r])==null?void 0:s.identifier)}return c}}):{}},T=ee();Re().then(()=>be(t,v).then(n=>R(void 0,null,function*(){if(a)return;b=n;let r=le(n);w={Authorization:`Bearer ${b}`,"Harness-AccountID":r.accountID,"Harness-EnvironmentID":r.environmentIdentifier,"Harness-SDK-Info":ve};let c=de(e);c.length<262144&&(w["Harness-Target"]=c),y("Authenticated",r),u=window.setTimeout(U,v.eventsSyncInterval),o=r.environment,l=r.clusterIdentifier;let m=!!Object.keys(C).length;if((yield N()).type==="success"&&y("Fetch all flags ok",T),!a){if(v.streamEnabled?(y("Streaming mode enabled"),Se()):v.pollingEnabled?(y("Polling mode enabled"),Ie()):y("Streaming and polling mode disabled"),!m){H();let s=I({},T);$(),h.emit("ready",s)}Z=!0}})).catch(n=>{A("Authentication error: ",n),h.emit("auth error",n),h.emit("error",n)}));let N=()=>R(void 0,null,function*(){try{let n=yield M(`${v.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:w});if(n.ok){let r=_(yield n.json());return r.forEach(D),h.emit("flags loaded",r),{type:"success",data:r}}else return A("Features fetch operation error: ",n),h.emit("fetch flags error",n),h.emit("error",n),{type:"error",error:n}}catch(n){return A("Features fetch operation error: ",n),h.emit("fetch flags error",n),h.emit("error",n),{type:"error",error:n}}}),te=n=>R(void 0,null,function*(){try{let r=yield M(`${v.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations/${n}?cluster=${l}`,{headers:w});if(r.ok){let c=yield r.json();D(c)}else A("Feature fetch operation error: ",r),h.emit("fetch flag error",r),h.emit("error",r)}catch(r){A("Feature fetch operation error: ",r),h.emit("fetch flag error",r),h.emit("error",r)}}),D=n=>{H();let r=G(n);r!==T[n.flag]&&(y("Flag variation has changed for ",n.identifier),T[n.flag]=r,C[n.flag]=P(I({},n),{value:r}),ye(n)),$()};E=new F(N,v,h,y,A);let Se=()=>{let n=s=>{switch(s.event){case"create":c(s.evaluations)?s.evaluations.forEach(f=>{D(f)}):setTimeout(()=>te(s.identifier),1e3);break;case"patch":c(s.evaluations)?s.evaluations.forEach(f=>{D(f)}):te(s.identifier);break;case"delete":delete T[s.identifier],h.emit("changed",{flag:s.identifier,value:void 0,deleted:!0}),y("Evaluation deleted",{message:s,storage:T});break}},r=s=>!(!s||!s.flag||!s.identifier||!s.kind||!s.value),c=s=>!(!s||s.length==0||!s.every(f=>r(f))),m=s=>{s.event==="patch"&&(c(s.evaluations)?s.evaluations.forEach(f=>{D(f)}):N())},p=`${v.baseUrl}/stream?cluster=${l}`;g=new L(h,v,p,t,w,E,y,A,s=>{s.domain==="flag"?n(s):s.domain==="target-segment"&&m(s)},v.maxStreamRetries),g.start()},Ie=()=>{E.start()},K=(n,r)=>h.on(n,r),Ce=(n,r)=>{n?h.off(n,r):ie()},we=(n,r)=>{var s;if(!S||z||r===void 0)return;let c=r,m=n,p=d.find(f=>f.featureIdentifier===m&&f.featureValue===c);p?(q(p),p.variationIdentifier=((s=C[m])==null?void 0:s.identifier)||""):d.push({featureIdentifier:m,featureValue:c,count:1,variationIdentifier:C[m].identifier||"",lastAccessed:Date.now()})},ie=()=>{a=!0,v.streamEnabled&&(y("Closing event stream"),typeof(g==null?void 0:g.close)=="function"&&g.close(),h.all.clear()),v.pollingEnabled&&E.isPolling()&&(y("Closing Poller"),E.stop()),T=ee(),C={},clearTimeout(u)},ne=(n,r=!0)=>{n.length&&J(()=>{let c=!!Object.keys(C).length;if(n.forEach(D),!c){H();let m=I({},T);$(),h.emit("ready",m)}},r)};return{on:K,off:Ce,close:ie,setEvaluations:ne,registerAPIRequestMiddleware:n=>{M=W(n)},refreshEvaluations:()=>{Z&&!a&&Date.now()-Q>=6e4&&(N(),Q=Date.now())},variation:(n,r,c=!1)=>fe(n,r,T,we,h,c)}};export{x as Event,wt as initialize};

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

var Re=Object.defineProperty,be=Object.defineProperties;var ye=Object.getOwnPropertyDescriptors;var ie=Object.getOwnPropertySymbols;var Se=Object.prototype.hasOwnProperty,Ie=Object.prototype.propertyIsEnumerable;var ne=(a,e,n)=>e in a?Re(a,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):a[e]=n,C=(a,e)=>{for(var n in e||(e={}))Se.call(e,n)&&ne(a,n,e[n]);if(ie)for(var n of ie(e))Ie.call(e,n)&&ne(a,n,e[n]);return a},B=(a,e)=>be(a,ye(e));var E=(a,e,n)=>new Promise((o,s)=>{var l=R=>{try{p(n.next(R))}catch(u){s(u)}},m=R=>{try{p(n.throw(R))}catch(u){s(u)}},p=R=>R.done?o(R.value):Promise.resolve(R.value).then(l,m);p((n=n.apply(a,e)).next())});import xe from"jwt-decode";import Me from"mitt";var P=(d=>(d.READY="ready",d.CONNECTED="connected",d.DISCONNECTED="disconnected",d.STOPPED="stopped",d.POLLING="polling",d.POLLING_STOPPED="polling stopped",d.FLAGS_LOADED="flags loaded",d.CACHE_LOADED="cache loaded",d.CHANGED="changed",d.ERROR="error",d.ERROR_CACHE="cache error",d.ERROR_METRICS="metrics error",d.ERROR_AUTH="auth error",d.ERROR_FETCH_FLAGS="fetch flags error",d.ERROR_FETCH_FLAG="fetch flag error",d.ERROR_STREAM="stream error",d.ERROR_DEFAULT_VARIATION_RETURNED="default variation returned",d))(P||{});var Ce={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},ae=a=>{let e=C(C({},Ce),a);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},U=(a,e=!0)=>{e?setTimeout(a,0):a()},N=(a,e)=>Math.round(Math.random()*(e-a)+a),re=a=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",n="",o=0,s=Ae(JSON.stringify(a));for(;o<s.length;){let l=s.charCodeAt(o++),m=s.charCodeAt(o++),p=s.charCodeAt(o++),R=l>>2,u=(l&3)<<4|m>>4,S=(m&15)<<2|p>>6,A=p&63;isNaN(m)?S=A=64:isNaN(p)&&(A=64),n+=e.charAt(R)+e.charAt(u)+e.charAt(S)+e.charAt(A)}return n},Ae=a=>a.replace(/\r\n/g,`
`).split("").map(e=>{let n=e.charCodeAt(0);return n<128?String.fromCharCode(n):n>127&&n<2048?String.fromCharCode(n>>6|192)+String.fromCharCode(n&63|128):String.fromCharCode(n>>12|224)+String.fromCharCode(n>>6&63|128)+String.fromCharCode(n&63|128)}).join("");function K(a){return function(...n){let[o,s]=a(n);return fetch(o,s)}}var oe=3e4,V=class{constructor(e,n,o,s,l,m,p,R,u,S){this.eventBus=e;this.configurations=n;this.url=o;this.apiKey=s;this.standardHeaders=l;this.fallbackPoller=m;this.logDebug=p;this.logError=R;this.eventCallback=u;this.maxRetries=S;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1;this.reconnectAttempts=0;this.retriesExhausted=!1}start(){let e=u=>{u.toString().split(/\r?\n/).forEach(n)},n=u=>{if(u.startsWith("data:")){let S=JSON.parse(u.substring(5));this.logDebugMessage("Received event from stream: ",S),this.eventCallback(S)}},o=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected"),this.reconnectAttempts=0},s=()=>{clearInterval(this.readTimeoutCheckerId);let u=N(1e3,1e4);if(this.reconnectAttempts++,this.logDebugMessage("Stream disconnected, will reconnect in "+u+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),this.reconnectAttempts>=5&&this.reconnectAttempts%5===0&&this.logErrorMessage(`Reconnection failed after ${this.reconnectAttempts} attempts; attempting further reconnections.`),this.reconnectAttempts>=this.maxRetries){this.retriesExhausted=!0,this.configurations.pollingEnabled?this.logErrorMessage("Max streaming retries reached. Staying in polling mode."):this.logErrorMessage("Max streaming retries reached. Polling mode is disabled and will receive no further flag updates until SDK client is restarted.");return}setTimeout(()=>this.start(),u)},l=u=>{this.retriesExhausted||(u&&this.logDebugMessage("Stream has issue",u),this.fallBackToPolling(),this.eventBus.emit("stream error",u),this.eventBus.emit("error",u),s())},m=C({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[u,S]of Object.entries(m))this.xhr.setRequestHeader(u,S);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{l(`Received XMLHttpRequest onLoad event: ${this.xhr.status}`)};let p=0,R=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(o(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),R=Date.now();let u=this.xhr.responseText.slice(p);p+=u.length,this.logDebugMessage("SSE GOT: "+u),e(u)},this.readTimeoutCheckerId=setInterval(()=>{R<Date.now()-oe&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},oe),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...n){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...n)}logErrorMessage(e,...n){this.logError(`Streaming: ${e}`,...n)}};function se(a,e,n,o,s,l){let m=a in n,p=m?n[a]:e;if(m)o(a,p);else{let R={flag:a,defaultVariation:e};s.emit("default variation returned",R)}return l?{value:p,isDefaultValue:!m}:p}var F=class{constructor(e,n,o,s,l){this.fetchFlagsFn=e;this.configurations=n;this.eventBus=o;this.logDebug=s;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.isRunning&&this.attemptFetch().finally(()=>{this.isRunning&&(this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval))})}attemptFetch(){return E(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let n=yield this.fetchFlagsFn();if(n.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",n.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,n.error);let o=N(1e3,1e4);yield new Promise(s=>setTimeout(s,o))}})}stop(){this.timeoutId&&(this.isRunning=!1,clearTimeout(this.timeoutId),this.timeoutId=void 0,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...n){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...n)}logErrorMessage(e,...n){this.logError(`Poller: ${e}`,...n)}};function le(n){return E(this,arguments,function*(a,e={}){let o=yield Oe(a),s=Pe(e);return{loadFromCache:()=>j(o,s,e),saveToCache:l=>W(o,s,l),updateCachedEvaluation:l=>we(o,s,l),removeCachedEvaluation:l=>De(o,s,l)}})}function j(o,s){return E(this,arguments,function*(a,e,n={}){let l=parseInt(yield e.getItem(a+".ts"));if(n!=null&&n.ttl&&!isNaN(l)&&l+n.ttl<Date.now())return yield Te(a,e),[];let m=yield e.getItem(a);if(m)try{return JSON.parse(m)}catch(p){}return[]})}function Te(a,e){return E(this,null,function*(){yield e.removeItem(a),yield e.removeItem(a+".ts")})}function W(a,e,n){return E(this,null,function*(){yield e.setItem(a,JSON.stringify(n)),yield e.setItem(a+".ts",Date.now().toString())})}function we(a,e,n){return E(this,null,function*(){let o=yield j(a,e),s=o.find(({flag:l})=>l===n.flag);s?Object.assign(s,n):o.push(n),yield W(a,e,o)})}function De(a,e,n){return E(this,null,function*(){let o=yield j(a,e),s=o.findIndex(({flag:l})=>l===n);s>-1&&(o.splice(s,1),yield W(a,e,o))})}function Oe(a){return E(this,null,function*(){var n,o;let e=a;if(globalThis!=null&&globalThis.TextEncoder&&((o=(n=globalThis==null?void 0:globalThis.crypto)==null?void 0:n.subtle)!=null&&o.digest)){let l=new TextEncoder().encode(a),m=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(m)).map(R=>R.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(a));return"HARNESS_FF_CACHE_"+e})}function Pe(a){let e;return!a.storage||typeof a.storage!="object"||!("getItem"in a.storage)||!("setItem"in a.storage)||!("removeItem"in a.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Fe:e=a.storage,{getItem(o){return E(this,null,function*(){let s=e.getItem(o);return s instanceof Promise?yield s:s})},setItem(o,s){return E(this,null,function*(){let l=e.setItem(o,s);l instanceof Promise&&(yield l)})},removeItem(o){return E(this,null,function*(){let s=e.removeItem(o);s instanceof Promise&&(yield s)})}}}var Fe={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var ue="1.26.1",ce=`Javascript ${ue} Client`,Ne=500,Ve=globalThis.fetch,J=!!globalThis.Proxy,mt=(a,e,n)=>{let o=!1,s,l,m,p,R,u,S=!0,A={},x=K(t=>t),Y=0,X=!1,_=()=>{S=!1},k=()=>{S=!0},d=[],f=Me(),v=ae(n),b=(t,...i)=>{v.debug&&v.logger.debug(`[FF-SDK] ${t}`,...i)},T=(t,...i)=>{v.logger.error(`[FF-SDK] ${t}`,...i)},de=(t,...i)=>{v.logger.warn(`[FF-SDK] ${t}`,...i)},L=t=>{let{value:i}=t;try{switch(t.kind.toLowerCase()){case"int":case"number":i=Number(i);break;case"boolean":i=i.toString().toLowerCase()==="true";break;case"json":i=JSON.parse(i);break}}catch(c){T(c)}return i},H=t=>{if(S){let i=Date.now();i-t.lastAccessed>Ne&&(t.count++,t.lastAccessed=i)}},ge=()=>E(void 0,null,function*(){if(v.cache){b("initializing cache");try{let t=!0,i=yield le(e.identifier+a,typeof v.cache=="boolean"?{}:v.cache),c=yield i.loadFromCache();c!=null&&c.length&&U(()=>{b("loading from cache",c),ee(c,!1),f.emit("cache loaded",c)}),q("flags loaded",h=>E(void 0,null,function*(){yield i.saveToCache(h),t=!1})),q("changed",h=>E(void 0,null,function*(){t||(h.deleted?yield i.removeCachedEvaluation(h.flag):yield i.updateCachedEvaluation(h))}))}catch(t){T("Cache error: ",t),f.emit("cache error",t),f.emit("error",t)}}}),fe=(t,i)=>E(void 0,null,function*(){let c=`${i.baseUrl}/client/auth`,h={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":ce},body:JSON.stringify({apiKey:t,target:B(C({},e),{identifier:String(e.identifier)})})},y,r;window.AbortController&&v.authRequestReadTimeout>0?(r=new AbortController,h.signal=r.signal,y=window.setTimeout(()=>r.abort(),i.authRequestReadTimeout)):i.authRequestReadTimeout>0&&de("AbortController is not available, auth request will not timeout");try{let g=yield Ve(c,h);if(!g.ok)throw new Error(`${g.status}: ${g.statusText}`);return(yield g.json()).authToken}catch(g){if(r&&r.signal.aborted)throw new Error(`Request to ${c} failed: Request timeout via configured authRequestTimeout of ${v.authRequestReadTimeout}`);let D=g instanceof Error?g.message:String(g);throw new Error(`Request to ${c} failed: ${D}`)}finally{y&&clearTimeout(y)}}),$=0,G=()=>{if(d.length){b("Sending metrics...",{metrics:d,evaluations:I});let t={metricsData:d.map(i=>({timestamp:Date.now(),count:i.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:i.featureIdentifier},{key:"featureName",value:i.featureIdentifier},{key:"variationIdentifier",value:i.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:ue}]}))};x(`${v.eventUrl}/metrics/${s}?cluster=${l}`,{method:"POST",headers:C({"Content-Type":"application/json"},A),body:JSON.stringify(t)}).then(()=>{d=[],$=0}).catch(i=>{$++&&(d=[],$=0),b(i),f.emit("metrics error",i)}).finally(()=>{u=window.setTimeout(G,v.eventsSyncInterval)})}else u=window.setTimeout(G,v.eventsSyncInterval)},I={},he=t=>{b("Sending event for",t.flag),J?f.emit("changed",new Proxy(t,{get(i,c){var h;if(S&&i.hasOwnProperty(c)&&c==="value"){let y=i.flag,r=t.value,g=d.find(D=>D.featureIdentifier===y&&D.featureValue===r);g?(H(g),g.variationIdentifier=((h=I[y])==null?void 0:h.identifier)||""):d.push({featureIdentifier:y,featureValue:String(r),variationIdentifier:I[y].identifier||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag",c,"has been read with value via stream update",r)}return c==="value"?L(t):t[c]}})):f.emit("changed",{deleted:t.deleted,flag:t.flag,value:L(t)})},z=function(){return J?new Proxy({},{get(t,i){var h,y,r;let c=t[i];if(S&&t.hasOwnProperty(i)){let g=t[i],D=d.find(te=>te.featureIdentifier===i&&g===te.featureValue);D?(D.variationIdentifier=((h=I[i])==null?void 0:h.identifier)||"",H(D)):d.push({featureIdentifier:i,featureValue:g,variationIdentifier:((y=I[i])==null?void 0:y.identifier)||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag:",i,"has been read with value:",g,"variationIdentifier:",(r=I[i])==null?void 0:r.identifier)}return c}}):{}},w=z();ge().then(()=>fe(a,v).then(t=>E(void 0,null,function*(){if(o)return;R=t;let i=xe(t);A={Authorization:`Bearer ${R}`,"Harness-AccountID":i.accountID,"Harness-EnvironmentID":i.environmentIdentifier,"Harness-SDK-Info":ce};let c=re(e);c.length<262144&&(A["Harness-Target"]=c),b("Authenticated",i),u=window.setTimeout(G,v.eventsSyncInterval),s=i.environment,l=i.clusterIdentifier;let h=!!Object.keys(I).length;if((yield M()).type==="success"&&b("Fetch all flags ok",w),!o){if(v.streamEnabled?(b("Streaming mode enabled"),me()):v.pollingEnabled?(b("Polling mode enabled"),ve()):b("Streaming and polling mode disabled"),!h){_();let r=C({},w);k(),f.emit("ready",r)}X=!0}})).catch(t=>{T("Authentication error: ",t),f.emit("auth error",t),f.emit("error",t)}));let M=()=>E(void 0,null,function*(){try{let t=yield x(`${v.baseUrl}/client/env/${s}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:A});if(t.ok){let i=yield t.json();return i.forEach(O),f.emit("flags loaded",i),{type:"success",data:i}}else return T("Features fetch operation error: ",t),f.emit("fetch flags error",t),f.emit("error",t),{type:"error",error:t}}catch(t){return T("Features fetch operation error: ",t),f.emit("fetch flags error",t),f.emit("error",t),{type:"error",error:t}}}),Q=t=>E(void 0,null,function*(){try{let i=yield x(`${v.baseUrl}/client/env/${s}/target/${e.identifier}/evaluations/${t}?cluster=${l}`,{headers:A});if(i.ok){let c=yield i.json();O(c)}else T("Feature fetch operation error: ",i),f.emit("fetch flag error",i),f.emit("error",i)}catch(i){T("Feature fetch operation error: ",i),f.emit("fetch flag error",i),f.emit("error",i)}}),O=t=>{_();let i=L(t);i!==w[t.flag]&&(b("Flag variation has changed for ",t.identifier),w[t.flag]=i,I[t.flag]=B(C({},t),{value:i}),he(t)),k()};p=new F(M,v,f,b,T);let me=()=>{let t=r=>{switch(r.event){case"create":c(r.evaluations)?r.evaluations.forEach(g=>{O(g)}):setTimeout(()=>Q(r.identifier),1e3);break;case"patch":c(r.evaluations)?r.evaluations.forEach(g=>{O(g)}):Q(r.identifier);break;case"delete":delete w[r.identifier],f.emit("changed",{flag:r.identifier,value:void 0,deleted:!0}),b("Evaluation deleted",{message:r,storage:w});break}},i=r=>!(!r||!r.flag||!r.identifier||!r.kind||!r.value),c=r=>!(!r||r.length==0||!r.every(g=>i(g))),h=r=>{r.event==="patch"&&(c(r.evaluations)?r.evaluations.forEach(g=>{O(g)}):M())},y=`${v.baseUrl}/stream?cluster=${l}`;m=new V(f,v,y,a,A,p,b,T,r=>{r.domain==="flag"?t(r):r.domain==="target-segment"&&h(r)},v.maxStreamRetries),m.start()},ve=()=>{p.start()},q=(t,i)=>f.on(t,i),pe=(t,i)=>{t?f.off(t,i):Z()},Ee=(t,i)=>{var r;if(!S||J||i===void 0)return;let c=i,h=t,y=d.find(g=>g.featureIdentifier===h&&g.featureValue===c);y?(H(y),y.variationIdentifier=((r=I[h])==null?void 0:r.identifier)||""):d.push({featureIdentifier:h,featureValue:c,count:1,variationIdentifier:I[h].identifier||"",lastAccessed:Date.now()})},Z=()=>{o=!0,v.streamEnabled&&(b("Closing event stream"),typeof(m==null?void 0:m.close)=="function"&&m.close(),f.all.clear()),v.pollingEnabled&&p.isPolling()&&(b("Closing Poller"),p.stop()),w=z(),I={},clearTimeout(u)},ee=(t,i=!0)=>{t.length&&U(()=>{let c=!!Object.keys(I).length;if(t.forEach(O),!c){_();let h=C({},w);k(),f.emit("ready",h)}},i)};return{on:q,off:pe,close:Z,setEvaluations:ee,registerAPIRequestMiddleware:t=>{x=K(t)},refreshEvaluations:()=>{X&&!o&&Date.now()-Y>=6e4&&(M(),Y=Date.now())},variation:(t,i,c=!1)=>se(t,i,w,Ee,f,c)}};export{P as Event,mt as initialize};
var ye=Object.defineProperty,Se=Object.defineProperties;var Ie=Object.getOwnPropertyDescriptors;var ne=Object.getOwnPropertySymbols;var Ae=Object.prototype.hasOwnProperty,Ce=Object.prototype.propertyIsEnumerable;var ae=(a,e,n)=>e in a?ye(a,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):a[e]=n,I=(a,e)=>{for(var n in e||(e={}))Ae.call(e,n)&&ae(a,n,e[n]);if(ne)for(var n of ne(e))Ce.call(e,n)&&ae(a,n,e[n]);return a},P=(a,e)=>Se(a,Ie(e));var R=(a,e,n)=>new Promise((r,s)=>{var l=b=>{try{E(n.next(b))}catch(u){s(u)}},m=b=>{try{E(n.throw(b))}catch(u){s(u)}},E=b=>b.done?r(b.value):Promise.resolve(b.value).then(l,m);E((n=n.apply(a,e)).next())});import Ne from"jwt-decode";import Ve from"mitt";var F=(d=>(d.READY="ready",d.CONNECTED="connected",d.DISCONNECTED="disconnected",d.STOPPED="stopped",d.POLLING="polling",d.POLLING_STOPPED="polling stopped",d.FLAGS_LOADED="flags loaded",d.CACHE_LOADED="cache loaded",d.CHANGED="changed",d.ERROR="error",d.ERROR_CACHE="cache error",d.ERROR_METRICS="metrics error",d.ERROR_AUTH="auth error",d.ERROR_FETCH_FLAGS="fetch flags error",d.ERROR_FETCH_FLAG="fetch flag error",d.ERROR_STREAM="stream error",d.ERROR_DEFAULT_VARIATION_RETURNED="default variation returned",d))(F||{});var Te={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},re=a=>{let e=I(I({},Te),a);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},U=(a,e=!0)=>{e?setTimeout(a,0):a()},V=(a,e)=>Math.round(Math.random()*(e-a)+a),oe=a=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",n="",r=0,s=we(JSON.stringify(a));for(;r<s.length;){let l=s.charCodeAt(r++),m=s.charCodeAt(r++),E=s.charCodeAt(r++),b=l>>2,u=(l&3)<<4|m>>4,S=(m&15)<<2|E>>6,C=E&63;isNaN(m)?S=C=64:isNaN(E)&&(C=64),n+=e.charAt(b)+e.charAt(u)+e.charAt(S)+e.charAt(C)}return n},we=a=>a.replace(/\r\n/g,`
`).split("").map(e=>{let n=e.charCodeAt(0);return n<128?String.fromCharCode(n):n>127&&n<2048?String.fromCharCode(n>>6|192)+String.fromCharCode(n&63|128):String.fromCharCode(n>>12|224)+String.fromCharCode(n>>6&63|128)+String.fromCharCode(n&63|128)}).join("");function _(a){return[...a].sort(({flag:e},{flag:n})=>e<n?-1:1)}function j(a){return function(...n){let[r,s]=a(n);return fetch(r,s)}}var se=3e4,k=class{constructor(e,n,r,s,l,m,E,b,u,S){this.eventBus=e;this.configurations=n;this.url=r;this.apiKey=s;this.standardHeaders=l;this.fallbackPoller=m;this.logDebug=E;this.logError=b;this.eventCallback=u;this.maxRetries=S;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1;this.reconnectAttempts=0;this.retriesExhausted=!1}start(){let e=u=>{u.toString().split(/\r?\n/).forEach(n)},n=u=>{if(u.startsWith("data:")){let S=JSON.parse(u.substring(5));this.logDebugMessage("Received event from stream: ",S),this.eventCallback(S)}},r=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected"),this.reconnectAttempts=0},s=()=>{clearInterval(this.readTimeoutCheckerId);let u=V(1e3,1e4);if(this.reconnectAttempts++,this.logDebugMessage("Stream disconnected, will reconnect in "+u+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),this.reconnectAttempts>=5&&this.reconnectAttempts%5===0&&this.logErrorMessage(`Reconnection failed after ${this.reconnectAttempts} attempts; attempting further reconnections.`),this.reconnectAttempts>=this.maxRetries){this.retriesExhausted=!0,this.configurations.pollingEnabled?this.logErrorMessage("Max streaming retries reached. Staying in polling mode."):this.logErrorMessage("Max streaming retries reached. Polling mode is disabled and will receive no further flag updates until SDK client is restarted.");return}setTimeout(()=>this.start(),u)},l=u=>{this.retriesExhausted||(u&&this.logDebugMessage("Stream has issue",u),this.fallBackToPolling(),this.eventBus.emit("stream error",u),this.eventBus.emit("error",u),s())},m=I({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[u,S]of Object.entries(m))this.xhr.setRequestHeader(u,S);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{l(`Received XMLHttpRequest onLoad event: ${this.xhr.status}`)};let E=0,b=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(r(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),b=Date.now();let u=this.xhr.responseText.slice(E);E+=u.length,this.logDebugMessage("SSE GOT: "+u),e(u)},this.readTimeoutCheckerId=setInterval(()=>{b<Date.now()-se&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},se),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...n){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...n)}logErrorMessage(e,...n){this.logError(`Streaming: ${e}`,...n)}};function le(a,e,n,r,s,l){let m=a in n,E=m?n[a]:e;if(m)r(a,E);else{let b={flag:a,defaultVariation:e};s.emit("default variation returned",b)}return l?{value:E,isDefaultValue:!m}:E}var x=class{constructor(e,n,r,s,l){this.fetchFlagsFn=e;this.configurations=n;this.eventBus=r;this.logDebug=s;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.isRunning&&this.attemptFetch().finally(()=>{this.isRunning&&(this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval))})}attemptFetch(){return R(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let n=yield this.fetchFlagsFn();if(n.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",n.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,n.error);let r=V(1e3,1e4);yield new Promise(s=>setTimeout(s,r))}})}stop(){this.timeoutId&&(this.isRunning=!1,clearTimeout(this.timeoutId),this.timeoutId=void 0,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...n){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...n)}logErrorMessage(e,...n){this.logError(`Poller: ${e}`,...n)}};function ce(n){return R(this,arguments,function*(a,e={}){let r=yield Fe(a),s=xe(e);return{loadFromCache:()=>W(r,s,e),saveToCache:l=>J(r,s,l),updateCachedEvaluation:l=>Oe(r,s,l),removeCachedEvaluation:l=>Pe(r,s,l)}})}function W(r,s){return R(this,arguments,function*(a,e,n={}){let l=parseInt(yield e.getItem(a+".ts"));if(n!=null&&n.ttl&&!isNaN(l)&&l+n.ttl<Date.now())return yield De(a,e),[];let m=yield e.getItem(a);if(m)try{return JSON.parse(m)}catch(E){}return[]})}function De(a,e){return R(this,null,function*(){yield e.removeItem(a),yield e.removeItem(a+".ts")})}function J(a,e,n){return R(this,null,function*(){yield e.setItem(a,JSON.stringify(_(n))),yield e.setItem(a+".ts",Date.now().toString())})}function Oe(a,e,n){return R(this,null,function*(){let r=yield W(a,e),s=r.find(({flag:l})=>l===n.flag);s?Object.assign(s,n):r.push(n),yield J(a,e,r)})}function Pe(a,e,n){return R(this,null,function*(){let r=yield W(a,e),s=r.findIndex(({flag:l})=>l===n);s>-1&&(r.splice(s,1),yield J(a,e,r))})}function ue(a,e,n={}){return n.deriveKeyFromTargetAttributes?JSON.stringify(Object.keys(a.attributes||{}).sort().filter(r=>!Array.isArray(n.deriveKeyFromTargetAttributes)||n.deriveKeyFromTargetAttributes.includes(r)).reduce((r,s)=>P(I({},r),{[s]:a.attributes[s]}),{}))+a.identifier+e:a.identifier+e}function Fe(a){return R(this,null,function*(){var n,r;let e=a;if(globalThis!=null&&globalThis.TextEncoder&&((r=(n=globalThis==null?void 0:globalThis.crypto)==null?void 0:n.subtle)!=null&&r.digest)){let l=new TextEncoder().encode(a),m=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(m)).map(b=>b.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(a));return"HARNESS_FF_CACHE_"+e})}function xe(a){let e;return!a.storage||typeof a.storage!="object"||!("getItem"in a.storage)||!("setItem"in a.storage)||!("removeItem"in a.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Me:e=a.storage,{getItem(r){return R(this,null,function*(){let s=e.getItem(r);return s instanceof Promise?yield s:s})},setItem(r,s){return R(this,null,function*(){let l=e.setItem(r,s);l instanceof Promise&&(yield l)})},removeItem(r){return R(this,null,function*(){let s=e.removeItem(r);s instanceof Promise&&(yield s)})}}}var Me={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var ge="1.26.1",de=`Javascript ${ge} Client`,_e=500,ke=globalThis.fetch,Y=!!globalThis.Proxy,Et=(a,e,n)=>{let r=!1,s,l,m,E,b,u,S=!0,C={},M=j(t=>t),X=0,z=!1,L=()=>{S=!1},H=()=>{S=!0},d=[],f=Ve(),v=re(n),y=(t,...i)=>{v.debug&&v.logger.debug(`[FF-SDK] ${t}`,...i)},T=(t,...i)=>{v.logger.error(`[FF-SDK] ${t}`,...i)},fe=(t,...i)=>{v.logger.warn(`[FF-SDK] ${t}`,...i)},$=t=>{let{value:i}=t;try{switch(t.kind.toLowerCase()){case"int":case"number":i=Number(i);break;case"boolean":i=i.toString().toLowerCase()==="true";break;case"json":i=JSON.parse(i);break}}catch(c){T(c)}return i},G=t=>{if(S){let i=Date.now();i-t.lastAccessed>_e&&(t.count++,t.lastAccessed=i)}},he=()=>R(void 0,null,function*(){if(v.cache){y("initializing cache");try{let t=!0,i=typeof v.cache=="boolean"?{}:v.cache,c=yield ce(ue(e,a,i),i),h=yield c.loadFromCache();h!=null&&h.length&&U(()=>{y("loading from cache",h),te(h,!1),f.emit("cache loaded",h)}),K("flags loaded",p=>R(void 0,null,function*(){yield c.saveToCache(p),t=!1})),K("changed",p=>R(void 0,null,function*(){t||(p.deleted?yield c.removeCachedEvaluation(p.flag):yield c.updateCachedEvaluation(p))}))}catch(t){T("Cache error: ",t),f.emit("cache error",t),f.emit("error",t)}}}),me=(t,i)=>R(void 0,null,function*(){let c=`${i.baseUrl}/client/auth`,h={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":de},body:JSON.stringify({apiKey:t,target:P(I({},e),{identifier:String(e.identifier)})})},p,o;window.AbortController&&v.authRequestReadTimeout>0?(o=new AbortController,h.signal=o.signal,p=window.setTimeout(()=>o.abort(),i.authRequestReadTimeout)):i.authRequestReadTimeout>0&&fe("AbortController is not available, auth request will not timeout");try{let g=yield ke(c,h);if(!g.ok)throw new Error(`${g.status}: ${g.statusText}`);return(yield g.json()).authToken}catch(g){if(o&&o.signal.aborted)throw new Error(`Request to ${c} failed: Request timeout via configured authRequestTimeout of ${v.authRequestReadTimeout}`);let D=g instanceof Error?g.message:String(g);throw new Error(`Request to ${c} failed: ${D}`)}finally{p&&clearTimeout(p)}}),q=0,B=()=>{if(d.length){y("Sending metrics...",{metrics:d,evaluations:A});let t={metricsData:d.map(i=>({timestamp:Date.now(),count:i.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:i.featureIdentifier},{key:"featureName",value:i.featureIdentifier},{key:"variationIdentifier",value:i.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:ge}]}))};M(`${v.eventUrl}/metrics/${s}?cluster=${l}`,{method:"POST",headers:I({"Content-Type":"application/json"},C),body:JSON.stringify(t)}).then(()=>{d=[],q=0}).catch(i=>{q++&&(d=[],q=0),y(i),f.emit("metrics error",i)}).finally(()=>{u=window.setTimeout(B,v.eventsSyncInterval)})}else u=window.setTimeout(B,v.eventsSyncInterval)},A={},ve=t=>{y("Sending event for",t.flag),Y?f.emit("changed",new Proxy(t,{get(i,c){var h;if(S&&i.hasOwnProperty(c)&&c==="value"){let p=i.flag,o=t.value,g=d.find(D=>D.featureIdentifier===p&&D.featureValue===o);g?(G(g),g.variationIdentifier=((h=A[p])==null?void 0:h.identifier)||""):d.push({featureIdentifier:p,featureValue:String(o),variationIdentifier:A[p].identifier||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag",c,"has been read with value via stream update",o)}return c==="value"?$(t):t[c]}})):f.emit("changed",{deleted:t.deleted,flag:t.flag,value:$(t)})},Q=function(){return Y?new Proxy({},{get(t,i){var h,p,o;let c=t[i];if(S&&t.hasOwnProperty(i)){let g=t[i],D=d.find(ie=>ie.featureIdentifier===i&&g===ie.featureValue);D?(D.variationIdentifier=((h=A[i])==null?void 0:h.identifier)||"",G(D)):d.push({featureIdentifier:i,featureValue:g,variationIdentifier:((p=A[i])==null?void 0:p.identifier)||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag:",i,"has been read with value:",g,"variationIdentifier:",(o=A[i])==null?void 0:o.identifier)}return c}}):{}},w=Q();he().then(()=>me(a,v).then(t=>R(void 0,null,function*(){if(r)return;b=t;let i=Ne(t);C={Authorization:`Bearer ${b}`,"Harness-AccountID":i.accountID,"Harness-EnvironmentID":i.environmentIdentifier,"Harness-SDK-Info":de};let c=oe(e);c.length<262144&&(C["Harness-Target"]=c),y("Authenticated",i),u=window.setTimeout(B,v.eventsSyncInterval),s=i.environment,l=i.clusterIdentifier;let h=!!Object.keys(A).length;if((yield N()).type==="success"&&y("Fetch all flags ok",w),!r){if(v.streamEnabled?(y("Streaming mode enabled"),pe()):v.pollingEnabled?(y("Polling mode enabled"),Ee()):y("Streaming and polling mode disabled"),!h){L();let o=I({},w);H(),f.emit("ready",o)}z=!0}})).catch(t=>{T("Authentication error: ",t),f.emit("auth error",t),f.emit("error",t)}));let N=()=>R(void 0,null,function*(){try{let t=yield M(`${v.baseUrl}/client/env/${s}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:C});if(t.ok){let i=_(yield t.json());return i.forEach(O),f.emit("flags loaded",i),{type:"success",data:i}}else return T("Features fetch operation error: ",t),f.emit("fetch flags error",t),f.emit("error",t),{type:"error",error:t}}catch(t){return T("Features fetch operation error: ",t),f.emit("fetch flags error",t),f.emit("error",t),{type:"error",error:t}}}),Z=t=>R(void 0,null,function*(){try{let i=yield M(`${v.baseUrl}/client/env/${s}/target/${e.identifier}/evaluations/${t}?cluster=${l}`,{headers:C});if(i.ok){let c=yield i.json();O(c)}else T("Feature fetch operation error: ",i),f.emit("fetch flag error",i),f.emit("error",i)}catch(i){T("Feature fetch operation error: ",i),f.emit("fetch flag error",i),f.emit("error",i)}}),O=t=>{L();let i=$(t);i!==w[t.flag]&&(y("Flag variation has changed for ",t.identifier),w[t.flag]=i,A[t.flag]=P(I({},t),{value:i}),ve(t)),H()};E=new x(N,v,f,y,T);let pe=()=>{let t=o=>{switch(o.event){case"create":c(o.evaluations)?o.evaluations.forEach(g=>{O(g)}):setTimeout(()=>Z(o.identifier),1e3);break;case"patch":c(o.evaluations)?o.evaluations.forEach(g=>{O(g)}):Z(o.identifier);break;case"delete":delete w[o.identifier],f.emit("changed",{flag:o.identifier,value:void 0,deleted:!0}),y("Evaluation deleted",{message:o,storage:w});break}},i=o=>!(!o||!o.flag||!o.identifier||!o.kind||!o.value),c=o=>!(!o||o.length==0||!o.every(g=>i(g))),h=o=>{o.event==="patch"&&(c(o.evaluations)?o.evaluations.forEach(g=>{O(g)}):N())},p=`${v.baseUrl}/stream?cluster=${l}`;m=new k(f,v,p,a,C,E,y,T,o=>{o.domain==="flag"?t(o):o.domain==="target-segment"&&h(o)},v.maxStreamRetries),m.start()},Ee=()=>{E.start()},K=(t,i)=>f.on(t,i),Re=(t,i)=>{t?f.off(t,i):ee()},be=(t,i)=>{var o;if(!S||Y||i===void 0)return;let c=i,h=t,p=d.find(g=>g.featureIdentifier===h&&g.featureValue===c);p?(G(p),p.variationIdentifier=((o=A[h])==null?void 0:o.identifier)||""):d.push({featureIdentifier:h,featureValue:c,count:1,variationIdentifier:A[h].identifier||"",lastAccessed:Date.now()})},ee=()=>{r=!0,v.streamEnabled&&(y("Closing event stream"),typeof(m==null?void 0:m.close)=="function"&&m.close(),f.all.clear()),v.pollingEnabled&&E.isPolling()&&(y("Closing Poller"),E.stop()),w=Q(),A={},clearTimeout(u)},te=(t,i=!0)=>{t.length&&U(()=>{let c=!!Object.keys(A).length;if(t.forEach(O),!c){L();let h=I({},w);H(),f.emit("ready",h)}},i)};return{on:K,off:Re,close:ee,setEvaluations:te,registerAPIRequestMiddleware:t=>{M=j(t)},refreshEvaluations:()=>{z&&!r&&Date.now()-X>=6e4&&(N(),X=Date.now())},variation:(t,i,c=!1)=>le(t,i,w,be,f,c)}};export{F as Event,Et as initialize};

@@ -182,2 +182,10 @@ export interface Target {

storage?: AsyncStorage | SyncStorage;
/**
* Use target attributes when deriving the cache key
* When set to `false` or omitted, the key will be formed using only the target identifier and SDK key
* When set to `true`, all target attributes with be used in addition to the target identifier and SDK key
* Can be set to an array of target attributes to use a subset in addition to the target identifier and SDK key
* @default false
*/
deriveKeyFromTargetAttributes?: boolean | string[];
}

@@ -184,0 +192,0 @@ export interface Logger {

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

import type { Options, Target } from './types';
import type { Evaluation, Options, Target } from './types';
export declare const MIN_EVENTS_SYNC_INTERVAL = 60000;

@@ -9,1 +9,2 @@ export declare const MIN_POLLING_INTERVAL = 60000;

export declare const encodeTarget: (target: Target) => string;
export declare function sortEvaluations(evaluations: Evaluation[]): Evaluation[];
{
"name": "@harnessio/ff-javascript-client-sdk",
"version": "1.29.0",
"version": "1.30.0",
"author": "Harness",

@@ -5,0 +5,0 @@ "license": "Apache-2.0",

@@ -317,2 +317,10 @@ # Before you Begin

storage?: AsyncStorage | SyncStorage
/**
* use target attributes when deriving the cache key
* when set to `false` or omitted, the key will be formed using only the target identifier and SDK key
* when set to `true`, all target attributes with be used in addition to the target identifier and SDK key
* can be set to an array of target attributes to use a subset in addition to the target identifier and SDK key
* defaults to false
*/
deriveKeyFromTargetAttributes?: boolean | string[]
}

@@ -359,3 +367,3 @@ ```

**This only applies to the authentiaction request. If you wish to set a read timeout on the remaining requests made by the SDK, you may register [API Middleware](#api-middleware)
**This only applies to the authentication request. If you wish to set a read timeout on the remaining requests made by the SDK, you may register [API Middleware](#api-middleware)

@@ -447,3 +455,3 @@ ```typescript

```html
<script src="https://unpkg.com/@harnessio/ff-javascript-client-sdk/dist/sdk.client.js"></script>
<script src="https://unpkg.com/@harnessio/ff-javascript-client-sdk/dist/sdk.client-iife.js"></script>
<script>

@@ -450,0 +458,0 @@ var initialize = HarnessFFSDK.initialize

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