UNPKG

@harnessio/ff-javascript-client-sdk

Version:

Basic library for integrating CF into javascript applications.

3 lines (2 loc) 19.4 kB
var HarnessFFSDK=(()=>{var k=Object.defineProperty,Pe=Object.defineProperties,xe=Object.getOwnPropertyDescriptor,Fe=Object.getOwnPropertyDescriptors,Me=Object.getOwnPropertyNames,le=Object.getOwnPropertySymbols;var ue=Object.prototype.hasOwnProperty,Ne=Object.prototype.propertyIsEnumerable;var ce=(t,e,i)=>e in t?k(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,I=(t,e)=>{for(var i in e||(e={}))ue.call(e,i)&&ce(t,i,e[i]);if(le)for(var i of le(e))Ne.call(e,i)&&ce(t,i,e[i]);return t},M=(t,e)=>Pe(t,Fe(e));var Ve=(t,e)=>{for(var i in e)k(t,i,{get:e[i],enumerable:!0})},ke=(t,e,i,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Me(e))!ue.call(t,o)&&o!==i&&k(t,o,{get:()=>e[o],enumerable:!(a=xe(e,o))||a.enumerable});return t};var _e=t=>ke(k({},"__esModule",{value:!0}),t);var E=(t,e,i)=>new Promise((a,o)=>{var l=R=>{try{p(i.next(R))}catch(u){o(u)}},d=R=>{try{p(i.throw(R))}catch(u){o(u)}},p=R=>R.done?a(R.value):Promise.resolve(R.value).then(l,d);p((i=i.apply(t,e)).next())});var ze={};Ve(ze,{Event:()=>F,initialize:()=>Xe});function Y(t){this.message=t}Y.prototype=new Error,Y.prototype.name="InvalidCharacterError";var de=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new Y("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,a,o=0,l=0,d="";a=e.charAt(l++);~a&&(i=o%4?64*i+a:a,o++%4)?d+=String.fromCharCode(255&i>>(-2*o&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return d};function Le(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(de(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 de(e)}}function _(t){this.message=t}function He(t,e){if(typeof t!="string")throw new _("Invalid token specified");var i=(e=e||{}).header===!0?0:1;try{return JSON.parse(Le(t.split(".")[i]))}catch(a){throw new _("Invalid token specified: "+a.message)}}_.prototype=new Error,_.prototype.name="InvalidTokenError";var ge=He;function fe(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 F=(b=>(b.READY="ready",b.CONNECTED="connected",b.DISCONNECTED="disconnected",b.STOPPED="stopped",b.POLLING="polling",b.POLLING_STOPPED="polling stopped",b.FLAGS_LOADED="flags loaded",b.CACHE_LOADED="cache loaded",b.CHANGED="changed",b.ERROR="error",b.ERROR_CACHE="cache error",b.ERROR_METRICS="metrics error",b.ERROR_AUTH="auth error",b.ERROR_FETCH_FLAGS="fetch flags error",b.ERROR_FETCH_FLAG="fetch flag error",b.ERROR_STREAM="stream error",b.ERROR_DEFAULT_VARIATION_RETURNED="default variation returned",b))(F||{});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,enableAnalytics:!0,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},he=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},X=(t,e=!0)=>{e?setTimeout(t,0):t()},L=(t,e)=>Math.round(Math.random()*(e-t)+t),me=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i="",a=0,o=Ge(JSON.stringify(t));for(;a<o.length;){let l=o.charCodeAt(a++),d=o.charCodeAt(a++),p=o.charCodeAt(a++),R=l>>2,u=(l&3)<<4|d>>4,S=(d&15)<<2|p>>6,D=p&63;isNaN(d)?S=D=64:isNaN(p)&&(D=64),i+=e.charAt(R)+e.charAt(u)+e.charAt(S)+e.charAt(D)}return i},Ge=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 H(t){return[...t].sort(({flag:e},{flag:i})=>e<i?-1:1)}function z(t){return function(...i){let[a,o]=t(i);return fetch(a,o)}}var ve=3e4,$=class{constructor(e,i,a,o,l,d,p,R,u,S){this.eventBus=e;this.configurations=i;this.url=a;this.apiKey=o;this.standardHeaders=l;this.fallbackPoller=d;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(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=L(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())},d=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(d))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||(a(),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()-ve&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},ve),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 pe(t,e,i,a,o,l){let d=t in i,p=d?i[t]:e;if(d)a(t,p);else{let R={flag:t,defaultVariation:e};o.emit("default variation returned",R)}return l?{value:p,isDefaultValue:!d}:p}var N=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=L(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 Ee(i){return E(this,arguments,function*(t,e={}){let a=yield Ke(t),o=je(e);return{loadFromCache:()=>Q(a,o,e),saveToCache:l=>Z(a,o,l),updateCachedEvaluation:l=>Be(a,o,l),removeCachedEvaluation:l=>Ue(a,o,l)}})}function Q(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 qe(t,e),[];let d=yield e.getItem(t);if(d)try{return JSON.parse(d)}catch(p){}return[]})}function qe(t,e){return E(this,null,function*(){yield e.removeItem(t),yield e.removeItem(t+".ts")})}function Z(t,e,i){return E(this,null,function*(){yield e.setItem(t,JSON.stringify(H(i))),yield e.setItem(t+".ts",Date.now().toString())})}function Be(t,e,i){return E(this,null,function*(){let a=yield Q(t,e),o=a.find(({flag:l})=>l===i.flag);o?Object.assign(o,i):a.push(i),yield Z(t,e,a)})}function Ue(t,e,i){return E(this,null,function*(){let a=yield Q(t,e),o=a.findIndex(({flag:l})=>l===i);o>-1&&(a.splice(o,1),yield Z(t,e,a))})}function Re(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)=>M(I({},a),{[o]:t.attributes[o]}),{}))+t.identifier+e:t.identifier+e}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),d=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(d)).map(R=>R.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(t));return"HARNESS_FF_CACHE_"+e})}function je(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=Je: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 Je={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var ye="1.31.0",be=`Javascript ${ye} Client`,We=500,Ye=globalThis.fetch,ee=!!globalThis.Proxy,Xe=(t,e,i)=>{let a=!1,o,l,d,p,R,u,S={},D=z(n=>n),te=0,ie=!1,G=!1,C=[],m=he(i),b=m.enableAnalytics,f=fe(),q=()=>{G=!0},B=()=>{G=!1},P=()=>b&&!G,y=(n,...r)=>{m.debug&&m.logger.debug(`[FF-SDK] ${n}`,...r)},w=(n,...r)=>{m.logger.error(`[FF-SDK] ${n}`,...r)},Se=(n,...r)=>{m.logger.warn(`[FF-SDK] ${n}`,...r)},U=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){w(c)}return r},K=n=>{if(P()){let r=Date.now();r-n.lastAccessed>We&&(n.count++,n.lastAccessed=r)}},Ie=()=>E(void 0,null,function*(){if(m.cache){y("initializing cache");try{let n=!0,r=typeof m.cache=="boolean"?{}:m.cache,c=yield Ee(Re(e,t,r),r),h=yield c.loadFromCache();h!=null&&h.length&&X(()=>{y("loading from cache",h),oe(h,!1),f.emit("cache loaded",h)}),W("flags loaded",v=>E(void 0,null,function*(){yield c.saveToCache(v),n=!1})),W("changed",v=>E(void 0,null,function*(){n||(v.deleted?yield c.removeCachedEvaluation(v.flag):yield c.updateCachedEvaluation(v))}))}catch(n){w("Cache error: ",n),f.emit("cache error",n),f.emit("error",n)}}}),Ae=(n,r)=>E(void 0,null,function*(){let c=`${r.baseUrl}/client/auth`,h={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":be},body:JSON.stringify({apiKey:n,target:M(I({},e),{identifier:String(e.identifier)})})},v,s;window.AbortController&&m.authRequestReadTimeout>0?(s=new AbortController,h.signal=s.signal,v=window.setTimeout(()=>s.abort(),r.authRequestReadTimeout)):r.authRequestReadTimeout>0&&Se("AbortController is not available, auth request will not timeout");try{let g=yield Ye(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 ${m.authRequestReadTimeout}`);let O=g instanceof Error?g.message:String(g);throw new Error(`Request to ${c} failed: ${O}`)}finally{v&&clearTimeout(v)}}),j=0,J=()=>{if(P())if(C.length){y("Sending metrics...",{metrics:C,evaluations:A});let n={metricsData:C.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:ye}]}))};D(`${m.eventUrl}/metrics/${o}?cluster=${l}`,{method:"POST",headers:I({"Content-Type":"application/json"},S),body:JSON.stringify(n)}).then(()=>{C=[],j=0}).catch(r=>{j++&&(C=[],j=0),y(r),f.emit("metrics error",r)}).finally(()=>{u=window.setTimeout(J,m.eventsSyncInterval)})}else u=window.setTimeout(J,m.eventsSyncInterval)},A={},Ce=n=>{y("Sending event for",n.flag),ee?f.emit("changed",new Proxy(n,{get(r,c){var h;if(P()&&r.hasOwnProperty(c)&&c==="value"){let v=r.flag,s=n.value,g=C.find(O=>O.featureIdentifier===v&&O.featureValue===s);g?(K(g),g.variationIdentifier=((h=A[v])==null?void 0:h.identifier)||""):C.push({featureIdentifier:v,featureValue:String(s),variationIdentifier:A[v].identifier||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag",c,"has been read with value via stream update",s)}return c==="value"?U(n):n[c]}})):f.emit("changed",{deleted:n.deleted,flag:n.flag,value:U(n)})},ne=function(){return ee?new Proxy({},{get(n,r){var h,v,s;let c=n[r];if(P()&&n.hasOwnProperty(r)){let g=n[r],O=C.find(se=>se.featureIdentifier===r&&g===se.featureValue);O?(O.variationIdentifier=((h=A[r])==null?void 0:h.identifier)||"",K(O)):C.push({featureIdentifier:r,featureValue:g,variationIdentifier:((v=A[r])==null?void 0:v.identifier)||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag:",r,"has been read with value:",g,"variationIdentifier:",(s=A[r])==null?void 0:s.identifier)}return c}}):{}},T=ne();Ie().then(()=>Ae(t,m).then(n=>E(void 0,null,function*(){if(a)return;R=n;let r=ge(n);S={Authorization:`Bearer ${R}`,"Harness-AccountID":r.accountID,"Harness-EnvironmentID":r.environmentIdentifier,"Harness-SDK-Info":be};let c=me(e);c.length<262144&&(S["Harness-Target"]=c),y("Authenticated",r),P()&&(u=window.setTimeout(J,m.eventsSyncInterval)),o=r.environment,l=r.clusterIdentifier;let h=!!Object.keys(A).length;if((yield V()).type==="success"&&y("Fetch all flags ok",T),!a){if(m.streamEnabled?(y("Streaming mode enabled"),we()):m.pollingEnabled?(y("Polling mode enabled"),Te()):y("Streaming and polling mode disabled"),!h){q();let s=I({},T);B(),f.emit("ready",s)}ie=!0}})).catch(n=>{w("Authentication error: ",n),f.emit("auth error",n),f.emit("error",n)}));let V=()=>E(void 0,null,function*(){try{let n=yield D(`${m.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:S});if(n.ok){let r=H(yield n.json());return r.forEach(x),f.emit("flags loaded",r),{type:"success",data:r}}else return w("Features fetch operation error: ",n),f.emit("fetch flags error",n),f.emit("error",n),{type:"error",error:n}}catch(n){return w("Features fetch operation error: ",n),f.emit("fetch flags error",n),f.emit("error",n),{type:"error",error:n}}}),re=n=>E(void 0,null,function*(){try{let r=yield D(`${m.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations/${n}?cluster=${l}`,{headers:S});if(r.ok){let c=yield r.json();x(c)}else w("Feature fetch operation error: ",r),f.emit("fetch flag error",r),f.emit("error",r)}catch(r){w("Feature fetch operation error: ",r),f.emit("fetch flag error",r),f.emit("error",r)}}),x=n=>{q();let r=U(n);r!==T[n.flag]&&(y("Flag variation has changed for ",n.identifier),T[n.flag]=r,A[n.flag]=M(I({},n),{value:r}),Ce(n)),B()};p=new N(V,m,f,y,w);let we=()=>{let n=s=>{switch(s.event){case"create":c(s.evaluations)?s.evaluations.forEach(g=>{x(g)}):setTimeout(()=>re(s.identifier),1e3);break;case"patch":c(s.evaluations)?s.evaluations.forEach(g=>{x(g)}):re(s.identifier);break;case"delete":delete T[s.identifier],f.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(g=>r(g))),h=s=>{s.event==="patch"&&(c(s.evaluations)?s.evaluations.forEach(g=>{x(g)}):V())},v=`${m.baseUrl}/stream?cluster=${l}`;d=new $(f,m,v,t,S,p,y,w,s=>{s.domain==="flag"?n(s):s.domain==="target-segment"&&h(s)},m.maxStreamRetries),d.start()},Te=()=>{p.start()},W=(n,r)=>f.on(n,r),Oe=(n,r)=>{n?f.off(n,r):ae()},De=(n,r)=>{var s;if(!P()||ee||r===void 0)return;let c=r,h=n,v=C.find(g=>g.featureIdentifier===h&&g.featureValue===c);v?(K(v),v.variationIdentifier=((s=A[h])==null?void 0:s.identifier)||""):C.push({featureIdentifier:h,featureValue:c,count:1,variationIdentifier:A[h].identifier||"",lastAccessed:Date.now()})},ae=()=>{a=!0,m.streamEnabled&&(y("Closing event stream"),typeof(d==null?void 0:d.close)=="function"&&d.close(),f.all.clear()),m.pollingEnabled&&p.isPolling()&&(y("Closing Poller"),p.stop()),T=ne(),A={},clearTimeout(u)},oe=(n,r=!0)=>{n.length&&X(()=>{let c=!!Object.keys(A).length;if(n.forEach(x),!c){q();let h=I({},T);B(),f.emit("ready",h)}},r)};return{on:W,off:Oe,close:ae,setEvaluations:oe,registerAPIRequestMiddleware:n=>{D=z(n)},refreshEvaluations:()=>{ie&&!a&&Date.now()-te>=6e4&&(V(),te=Date.now())},variation:(n,r,c=!1)=>pe(n,r,T,De,f,c)}};return _e(ze);})();