-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathsdk.client.js
12 lines (12 loc) · 20.6 KB
/
sdk.client.js
1
2
3
4
5
6
7
8
9
10
11
12
var et=Object.create,Ve=Object.defineProperty,tt=Object.getPrototypeOf,nt=Object.prototype.hasOwnProperty,rt=Object.getOwnPropertyNames,it=Object.getOwnPropertyDescriptor;var re=Object.assign,at=r=>Ve(r,"__esModule",{value:!0});var ot=(r,o)=>()=>(o||(o={exports:{}},r(o.exports,o)),o.exports);var st=(r,o,p)=>{if(o&&typeof o=="object"||typeof o=="function")for(let c of rt(o))!nt.call(r,c)&&c!=="default"&&Ve(r,c,{get:()=>o[c],enumerable:!(p=it(o,c))||p.enumerable});return r},ft=r=>st(at(Ve(r!=null?et(tt(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var Re=(r,o,p)=>new Promise((c,V)=>{var x=B=>{try{O(p.next(B))}catch(F){V(F)}},b=B=>{try{O(p.throw(B))}catch(F){V(F)}},O=B=>B.done?c(B.value):Promise.resolve(B.value).then(x,b);O((p=p.apply(r,o)).next())});var $e=ot((ke,Ae)=>{(function(r){"use strict";var o=r.setTimeout,p=r.clearTimeout,c=r.XMLHttpRequest,V=r.XDomainRequest,x=r.ActiveXObject,b=r.EventSource,O=r.document,B=r.Promise,F=r.fetch,ue=r.Response,ie=r.TextDecoder,D=r.TextEncoder,T=r.AbortController;if(typeof window!="undefined"&&typeof O!="undefined"&&!("readyState"in O)&&O.body==null&&(O.readyState="loading",window.addEventListener("load",function(e){O.readyState="complete"},!1)),c==null&&x!=null&&(c=function(){return new x("Microsoft.XMLHTTP")}),Object.create==null&&(Object.create=function(e){function n(){}return n.prototype=e,new n}),Date.now||(Date.now=function(){return new Date().getTime()}),T==null){var W=F;F=function(e,n){var i=n.signal;return W(e,{headers:n.headers,credentials:n.credentials,cache:n.cache}).then(function(t){var u=t.body.getReader();return i._reader=u,i._aborted&&i._reader.cancel(),{status:t.status,statusText:t.statusText,headers:t.headers,body:{getReader:function(){return u}}}})},T=function(){this.signal={_reader:null,_aborted:!1},this.abort=function(){this.signal._reader!=null&&this.signal._reader.cancel(),this.signal._aborted=!0}}}function C(){this.bitsNeeded=0,this.codePoint=0}C.prototype.decode=function(e){function n(E,y,l){if(l===1)return E>=128>>y&&E<<y<=2047;if(l===2)return E>=2048>>y&&E<<y<=55295||E>=57344>>y&&E<<y<=65535;if(l===3)return E>=65536>>y&&E<<y<=1114111;throw new Error}function i(E,y){if(E===6*1)return y>>6>15?3:y>31?2:1;if(E===6*2)return y>15?3:2;if(E===6*3)return 3;throw new Error}for(var t=65533,u="",d=this.bitsNeeded,v=this.codePoint,w=0;w<e.length;w+=1){var g=e[w];d!==0&&(g<128||g>191||!n(v<<6|g&63,d-6,i(d,v)))&&(d=0,v=t,u+=String.fromCharCode(v)),d===0?(g>=0&&g<=127?(d=0,v=g):g>=192&&g<=223?(d=6*1,v=g&31):g>=224&&g<=239?(d=6*2,v=g&15):g>=240&&g<=247?(d=6*3,v=g&7):(d=0,v=t),d!==0&&!n(v,d,i(d,v))&&(d=0,v=t)):(d-=6,v=v<<6|g&63),d===0&&(v<=65535?u+=String.fromCharCode(v):(u+=String.fromCharCode(55296+(v-65535-1>>10)),u+=String.fromCharCode(56320+(v-65535-1&1023))))}return this.bitsNeeded=d,this.codePoint=v,u};var oe=function(){try{return new ie().decode(new D().encode("test"),{stream:!0})==="test"}catch(e){console.debug("TextDecoder does not support streaming option. Using polyfill instead: "+e)}return!1};(ie==null||D==null||!oe())&&(ie=C);var $=function(){};function J(e){this.withCredentials=!1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.onprogress=$,this.onload=$,this.onerror=$,this.onreadystatechange=$,this._contentType="",this._xhr=e,this._sendTimeout=0,this._abort=$}J.prototype.open=function(e,n){this._abort(!0);var i=this,t=this._xhr,u=1,d=0;this._abort=function(l){i._sendTimeout!==0&&(p(i._sendTimeout),i._sendTimeout=0),(u===1||u===2||u===3)&&(u=4,t.onload=$,t.onerror=$,t.onabort=$,t.onprogress=$,t.onreadystatechange=$,t.abort(),d!==0&&(p(d),d=0),l||(i.readyState=4,i.onabort(null),i.onreadystatechange())),u=0};var v=function(){if(u===1){var l=0,S="",Y=void 0;if("contentType"in t)l=200,S="OK",Y=t.contentType;else try{l=t.status,S=t.statusText,Y=t.getResponseHeader("Content-Type")}catch(Ee){l=0,S="",Y=void 0}l!==0&&(u=2,i.readyState=2,i.status=l,i.statusText=S,i._contentType=Y,i.onreadystatechange())}},w=function(){if(v(),u===2||u===3){u=3;var l="";try{l=t.responseText}catch(S){}i.readyState=3,i.responseText=l,i.onprogress()}},g=function(l,S){if((S==null||S.preventDefault==null)&&(S={preventDefault:$}),w(),u===1||u===2||u===3){if(u=4,d!==0&&(p(d),d=0),i.readyState=4,l==="load")i.onload(S);else if(l==="error")i.onerror(S);else if(l==="abort")i.onabort(S);else throw new TypeError;i.onreadystatechange()}},E=function(l){t!=null&&(t.readyState===4?(!("onload"in t)||!("onerror"in t)||!("onabort"in t))&&g(t.responseText===""?"error":"load",l):t.readyState===3?"onprogress"in t||w():t.readyState===2&&v())},y=function(){d=o(function(){y()},500),t.readyState===3&&w()};"onload"in t&&(t.onload=function(l){g("load",l)}),"onerror"in t&&(t.onerror=function(l){g("error",l)}),"onabort"in t&&(t.onabort=function(l){g("abort",l)}),"onprogress"in t&&(t.onprogress=w),"onreadystatechange"in t&&(t.onreadystatechange=function(l){E(l)}),("contentType"in t||!("ontimeout"in c.prototype))&&(n+=(n.indexOf("?")===-1?"?":"&")+"padding=true"),t.open(e,n,!0),"readyState"in t&&(d=o(function(){y()},0))},J.prototype.abort=function(){this._abort(!1)},J.prototype.getResponseHeader=function(e){return this._contentType},J.prototype.setRequestHeader=function(e,n){var i=this._xhr;"setRequestHeader"in i&&i.setRequestHeader(e,n)},J.prototype.getAllResponseHeaders=function(){return this._xhr.getAllResponseHeaders!=null&&this._xhr.getAllResponseHeaders()||""},J.prototype.send=function(){if((!("ontimeout"in c.prototype)||!("sendAsBinary"in c.prototype)&&!("mozAnon"in c.prototype))&&O!=null&&O.readyState!=null&&O.readyState!=="complete"){var e=this;e._sendTimeout=o(function(){e._sendTimeout=0,e.send()},4);return}var n=this._xhr;"withCredentials"in n&&(n.withCredentials=this.withCredentials);try{n.send(void 0)}catch(i){throw i}};function _(e){return e.replace(/[A-Z]/g,function(n){return String.fromCharCode(n.charCodeAt(0)+32)})}function le(e){for(var n=Object.create(null),i=e.split(`\r
`),t=0;t<i.length;t+=1){var u=i[t],d=u.split(": "),v=d.shift(),w=d.join(": ");n[_(v)]=w}this._map=n}le.prototype.get=function(e){return this._map[_(e)]},c!=null&&c.HEADERS_RECEIVED==null&&(c.HEADERS_RECEIVED=2);function ve(){}ve.prototype.open=function(e,n,i,t,u,d,v){e.open("GET",u);var w=0;e.onprogress=function(){var E=e.responseText,y=E.slice(w);w+=y.length,i(y)},e.onerror=function(E){E.preventDefault(),t(new Error("NetworkError"))},e.onload=function(){t(null)},e.onabort=function(){t(null)},e.onreadystatechange=function(){if(e.readyState===c.HEADERS_RECEIVED){var E=e.status,y=e.statusText,l=e.getResponseHeader("Content-Type"),S=e.getAllResponseHeaders();n(E,y,l,new le(S))}},e.withCredentials=d;for(var g in v)Object.prototype.hasOwnProperty.call(v,g)&&e.setRequestHeader(g,v[g]);return e.send(),e};function k(e){this._headers=e}k.prototype.get=function(e){return this._headers.get(e)};function he(){}he.prototype.open=function(e,n,i,t,u,d,v){var w=null,g=new T,E=g.signal,y=new ie;return F(u,{headers:v,credentials:d?"include":"same-origin",signal:E,cache:"no-store"}).then(function(l){return w=l.body.getReader(),n(l.status,l.statusText,l.headers.get("Content-Type"),new k(l.headers)),new B(function(S,Y){var Ee=function(){w.read().then(function(K){if(K.done)S(void 0);else{var P=y.decode(K.value,{stream:!0});i(P),Ee()}}).catch(function(K){Y(K)})};Ee()})}).catch(function(l){if(l.name!=="AbortError")return l}).then(function(l){t(l)}),{abort:function(){w!=null&&w.cancel(),g.abort()}}};function te(){this._listeners=Object.create(null)}function we(e){o(function(){throw e},0)}te.prototype.dispatchEvent=function(e){e.target=this;var n=this._listeners[e.type];if(n!=null)for(var i=n.length,t=0;t<i;t+=1){var u=n[t];try{typeof u.handleEvent=="function"?u.handleEvent(e):u.call(this,e)}catch(d){we(d)}}},te.prototype.addEventListener=function(e,n){e=String(e);var i=this._listeners,t=i[e];t==null&&(t=[],i[e]=t);for(var u=!1,d=0;d<t.length;d+=1)t[d]===n&&(u=!0);u||t.push(n)},te.prototype.removeEventListener=function(e,n){e=String(e);var i=this._listeners,t=i[e];if(t!=null){for(var u=[],d=0;d<t.length;d+=1)t[d]!==n&&u.push(t[d]);u.length===0?delete i[e]:i[e]=u}};function ne(e){this.type=e,this.target=void 0}function Se(e,n){ne.call(this,e),this.data=n.data,this.lastEventId=n.lastEventId}Se.prototype=Object.create(ne.prototype);function pe(e,n){ne.call(this,e),this.status=n.status,this.statusText=n.statusText,this.headers=n.headers}pe.prototype=Object.create(ne.prototype);function ge(e,n){ne.call(this,e),this.error=n.error}ge.prototype=Object.create(ne.prototype);var s=-1,f=0,a=1,h=2,R=-1,m=0,I=1,L=2,be=3,Xe=/^text\/event\-stream(;.*)?$/i,qe=1e3,Je=18e6,xe=function(e,n){var i=e==null?n:parseInt(e,10);return i!==i&&(i=n),Fe(i)},Fe=function(e){return Math.min(Math.max(e,qe),Je)},se=function(e,n,i){try{typeof n=="function"&&n.call(e,i)}catch(t){we(t)}};function z(e,n){te.call(this),n=n||{},this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,this.url=void 0,this.readyState=void 0,this.withCredentials=void 0,this.headers=void 0,this._close=void 0,Ye(this,e,n)}function ze(){return c!=null&&"withCredentials"in c.prototype||V==null?new c:new V}var We=F!=null&&ue!=null&&"body"in ue.prototype;function Ye(e,n,i){n=String(n);var t=Boolean(i.withCredentials),u=i.lastEventIdQueryParameterName||"lastEventId",d=Fe(1e3),v=xe(i.heartbeatTimeout,45e3),w="",g=d,E=!1,y=0,l=i.headers||{},S=i.Transport,Y=We&&S==null?void 0:new J(S!=null?new S:ze()),Ee=S!=null&&typeof S!="string"?new S:Y==null?new he:new ve,K=void 0,P=0,q=s,fe="",Te="",Q="",Ce="",j=m,_e=0,ae=0,Qe=function(N,A,G,X){if(q===f)if(N===200&&G!=null&&Xe.test(G)){q=a,E=Date.now(),g=d,e.readyState=a;var U=new pe("open",{status:N,statusText:A,headers:X});e.dispatchEvent(U),se(e,e.onopen,U)}else{var M="";N!==200?(A&&(A=A.replace(/\s+/g," ")),M="EventSource's response has a status "+N+" "+A+" that is not 200. Aborting the connection."):M="EventSource's response has a Content-Type specifying an unsupported type: "+(G==null?"-":G.replace(/\s+/g," "))+". Aborting the connection.",Me();var U=new pe("error",{status:N,statusText:A,headers:X});e.dispatchEvent(U),se(e,e.onerror,U),console.error(M)}},Ze=function(N){if(q===a){for(var A=-1,G=0;G<N.length;G+=1){var X=N.charCodeAt(G);(X===`
`.charCodeAt(0)||X==="\r".charCodeAt(0))&&(A=G)}var U=(A!==-1?Ce:"")+N.slice(0,A+1);Ce=(A===-1?Ce:"")+N.slice(A+1),N!==""&&(E=Date.now(),y+=N.length);for(var M=0;M<U.length;M+=1){var X=U.charCodeAt(M);if(j===R&&X===`
`.charCodeAt(0))j=m;else if(j===R&&(j=m),X==="\r".charCodeAt(0)||X===`
`.charCodeAt(0)){if(j!==m){j===I&&(ae=M+1);var Z=U.slice(_e,ae-1),ee=U.slice(ae+(ae<M&&U.charCodeAt(ae)===" ".charCodeAt(0)?1:0),M);Z==="data"?(fe+=`
`,fe+=ee):Z==="id"?Te=ee:Z==="event"?Q=ee:Z==="retry"?(d=xe(ee,d),g=d):Z==="heartbeatTimeout"&&(v=xe(ee,v),P!==0&&(p(P),P=o(function(){ye()},v)))}if(j===m){if(fe!==""){w=Te,Q===""&&(Q="message");var de=new Se(Q,{data:fe.slice(1),lastEventId:Te});if(e.dispatchEvent(de),Q==="open"?se(e,e.onopen,de):Q==="message"?se(e,e.onmessage,de):Q==="error"&&se(e,e.onerror,de),q===h)return}fe="",Q=""}j=X==="\r".charCodeAt(0)?R:m}else j===m&&(_e=M,j=I),j===I?X===":".charCodeAt(0)&&(ae=M+1,j=L):j===L&&(j=be)}}},Pe=function(N){if(q===a||q===f)q=s,P!==0&&(p(P),P=0),P=o(function(){ye()},g),g=Fe(Math.min(d*16,g*2)),e.readyState=f;else if(q===h&&N!=null){console.error(N);var A=new ge("error",{error:N});e.dispatchEvent(A),se(e,e.onerror,A)}},Me=function(){q=h,K!=null&&(K.abort(),K=void 0),P!==0&&(p(P),P=0),e.readyState=h},ye=function(){if(P=0,q!==s){if(!E&&K!=null)Pe(new Error("No activity within "+v+" milliseconds. "+(q===f?"No response received.":y+" chars received.")+" Reconnecting.")),K!=null&&(K.abort(),K=void 0);else{var N=Math.max((E||Date.now())+v-Date.now(),1);E=!1,P=o(function(){ye()},N)}return}E=!1,y=0,P=o(function(){ye()},v),q=f,fe="",Q="",Te=w,Ce="",_e=0,ae=0,j=m;var A=n;if(n.slice(0,5)!=="data:"&&n.slice(0,5)!=="blob:"&&w!==""){var G=n.indexOf("?");A=G===-1?n:n.slice(0,G+1)+n.slice(G+1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g,function(ee,de){return de===u?"":ee}),A+=(n.indexOf("?")===-1?"?":"&")+u+"="+encodeURIComponent(w)}var X=e.withCredentials,U={};U.Accept="text/event-stream";var M=e.headers;if(M!=null)for(var Z in M)Object.prototype.hasOwnProperty.call(M,Z)&&(U[Z]=M[Z]);try{K=Ee.open(Y,Qe,Ze,Pe,A,X,U)}catch(ee){throw Me(),ee}};e.url=n,e.readyState=f,e.withCredentials=t,e.headers=l,e._close=Me,ye()}z.prototype=Object.create(te.prototype),z.prototype.CONNECTING=f,z.prototype.OPEN=a,z.prototype.CLOSED=h,z.prototype.close=function(){this._close()},z.CONNECTING=f,z.OPEN=a,z.CLOSED=h,z.prototype.withCredentials=void 0;var Le=b;c!=null&&(b==null||!("withCredentials"in b.prototype))&&(Le=z),function(e){if(typeof Ae=="object"&&typeof Ae.exports=="object"){var n=e(ke);n!==void 0&&(Ae.exports=n)}else typeof define=="function"&&define.amd?define(["exports"],e):e(r)}(function(e){e.EventSourcePolyfill=z,e.NativeEventSource=b,e.EventSource=Le})})(typeof globalThis=="undefined"?typeof window!="undefined"?window:typeof self!="undefined"?self:ke:globalThis)});function He(r){this.message=r}He.prototype=new Error,He.prototype.name="InvalidCharacterError";var je=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(r){var o=String(r).replace(/=+$/,"");if(o.length%4==1)throw new He("'atob' failed: The string to be decoded is not correctly encoded.");for(var p,c,V=0,x=0,b="";c=o.charAt(x++);~c&&(p=V%4?64*p+c:c,V++%4)?b+=String.fromCharCode(255&p>>(-2*V&6)):0)c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(c);return b};function dt(r){var o=r.replace(/-/g,"+").replace(/_/g,"/");switch(o.length%4){case 0:break;case 2:o+="==";break;case 3:o+="=";break;default:throw"Illegal base64url string!"}try{return function(p){return decodeURIComponent(je(p).replace(/(.)/g,function(c,V){var x=V.charCodeAt(0).toString(16).toUpperCase();return x.length<2&&(x="0"+x),"%"+x}))}(o)}catch(p){return je(o)}}function Ie(r){this.message=r}function ct(r,o){if(typeof r!="string")throw new Ie("Invalid token specified");var p=(o=o||{}).header===!0?0:1;try{return JSON.parse(dt(r.split(".")[p]))}catch(c){throw new Ie("Invalid token specified: "+c.message)}}Ie.prototype=new Error,Ie.prototype.name="InvalidTokenError";var Ue=ct;function Be(r){return{all:r=r||new Map,on:function(o,p){var c=r.get(o);c&&c.push(p)||r.set(o,[p])},off:function(o,p){var c=r.get(o);c&&c.splice(c.indexOf(p)>>>0,1)},emit:function(o,p){(r.get(o)||[]).slice().map(function(c){c(p)}),(r.get("*")||[]).slice().map(function(c){c(o,p)})}}}var Ge=ft($e());var H;(function(r){r.READY="ready",r.CONNECTED="connected",r.DISCONNECTED="disconnected",r.CHANGED="changed",r.ERROR="error"})(H||(H={}));var Ke={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",streamEnabled:!0,allAttributesPrivate:!1,privateAttributeNames:[]},ce=(r,...o)=>console.error(`[FF-SDK] ${r}`,...o),Oe=30*1e3;var ut="1.4.11",lt=500,De=globalThis.fetch,vt=Ge.EventSourcePolyfill,me=!!globalThis.Proxy,Ne=r=>{let{value:o}=r;try{switch(r.kind.toLowerCase()){case"int":case"number":o=Number(o);break;case"boolean":o=o.toString().toLowerCase()==="true";break;case"json":o=JSON.parse(o);break}}catch(p){ce(p)}return o},ht=(r,o,p)=>{let c=!1,V,x,b,O,B,F=!0,ue=()=>{F=!1},ie=()=>{F=!0},D=[],T=Be(),W=re(re({},Ke),p),C=(s,...f)=>{W.debug&&console.debug(`[FF-SDK] ${s}`,...f)},oe=s=>{if(F){let f=Date.now();f-s.lastAccessed>lt&&(s.count++,s.lastAccessed=f)}};globalThis.onbeforeunload=()=>{D.length&&globalThis.localStorage&&(ue(),globalThis.localStorage.HARNESS_FF_METRICS=JSON.stringify(D),ie())};let $=(s,f)=>Re(void 0,null,function*(){return(yield(yield De(`${f.baseUrl}/client/auth`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:s,target:o})})).json()).authToken}),J=()=>{if(D.length){C("Sending metrics...",{metrics:D,evaluations:_});let s={metricsData:D.map(f=>({timestamp:Date.now(),count:f.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:f.featureIdentifier},{key:"featureName",value:f.featureIdentifier},{key:"variationIdentifier",value:f.variationIdentifier},{key:"target",value:o.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:ut}]}))};De(`${W.eventUrl}/metrics/${V}?cluster=${x}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${O}`},body:JSON.stringify(s)}).then(()=>{D=[]}).catch(f=>{C(f)}).finally(()=>{B=window.setTimeout(J,Oe)})}else B=window.setTimeout(J,Oe)},_={},le=s=>{C("Sending event for",s.flag),me?T.emit(H.CHANGED,new Proxy(s,{get(f,a){var h;if(f.hasOwnProperty(a)&&a==="value"){let R=f.flag,m=s.value,I=D.find(L=>L.featureIdentifier===R&&L.featureValue===m);I?(oe(I),I.variationIdentifier=((h=_[R])==null?void 0:h.identifier)||""):D.push({featureIdentifier:R,featureValue:String(m),variationIdentifier:_[R].identifier||"",count:F?1:0,lastAccessed:Date.now()}),C("Metrics event: Flag",a,"has been read with value via stream update",m)}return a==="value"?Ne(s):s[a]}})):T.emit(H.CHANGED,{deleted:s.deleted,flag:s.flag,value:Ne(s)})},ve=function(){return me?new Proxy({},{get(s,f){var h,R,m;let a=s[f];if(s.hasOwnProperty(f)){let I=s[f],L=D.find(be=>be.featureIdentifier===f&&I===be.featureValue);L?(L.variationIdentifier=((h=_[f])==null?void 0:h.identifier)||"",oe(L)):D.push({featureIdentifier:f,featureValue:I,variationIdentifier:((R=_[f])==null?void 0:R.identifier)||"",count:F?1:0,lastAccessed:Date.now()}),C("Metrics event: Flag:",f,"has been read with value:",I,"variationIdentifier:",(m=_[f])==null?void 0:m.identifier)}return a}}):{}},k=ve();$(r,W).then(s=>{if(c)return;O=s;let f=Ue(s);if(C("Authenticated",f),globalThis.localStorage&&globalThis.localStorage.HARNESS_FF_METRICS)try{delete globalThis.localStorage.HARNESS_FF_METRICS,C("Picking up metrics from previous session")}catch(a){}B=window.setTimeout(J,Oe),V=f.environment,x=f.clusterIdentifier,he().then(()=>{C("Fetch all flags ok",k)}).then(()=>{c||we()}).then(()=>{c||(C("Event stream ready",{storage:k}),T.emit(H.READY,re({},k)),me||Object.keys(k).forEach(a=>{var h;D.push({featureIdentifier:a,featureValue:k[a],variationIdentifier:((h=_[a])==null?void 0:h.identifier)||"",count:F?1:0,lastAccessed:Date.now()})}))}).catch(a=>{T.emit(H.ERROR,a)})}).catch(s=>{ce("Authentication error: ",s),T.emit(H.ERROR,s)});let he=()=>Re(void 0,null,function*(){try{(yield(yield De(`${W.baseUrl}/client/env/${V}/target/${o.identifier}/evaluations?cluster=${x}`,{headers:{Authorization:`Bearer ${O}`}})).json()).forEach(a=>{let h=Ne(a),R=k[a.flag];h!==R&&(C("Flag variation has changed for ",a.identifier),k[a.flag]=h,_[a.flag]=re(re({},a),{value:h}),le(a))})}catch(s){return ce("Features fetch operation error: ",s),T.emit(H.ERROR,s),s}}),te=s=>Re(void 0,null,function*(){var f;try{let a=yield De(`${W.baseUrl}/client/env/${V}/target/${o.identifier}/evaluations/${s}?cluster=${x}`,{headers:{Authorization:`Bearer ${O}`}});if(a.ok){let h=yield a.json(),R=Ne(h);if(ue(),k[s]=R,_[s]=re(re({},h),{value:R}),ie(),le(h),!me){let m=h.flag,I=D.find(L=>L.featureIdentifier===m&&L.featureValue===h.value);I?(oe(I),I.variationIdentifier=((f=_[m])==null?void 0:f.identifier)||""):D.push({featureIdentifier:m,featureValue:String(h.value),variationIdentifier:_[m].identifier||"",count:F?1:0,lastAccessed:Date.now()})}}else T.emit(H.ERROR,a)}catch(a){ce("Feature fetch operation error: ",a),T.emit(H.ERROR,a)}}),we=()=>{if(!W.streamEnabled){C("Stream is disabled by configuration. Note: Polling is not yet supported");return}b=new vt(`${W.baseUrl}/stream?cluster=${x}`,{headers:{Authorization:`Bearer ${O}`,"API-Key":r}}),b.onopen=a=>{C("Stream connected",a),T.emit(H.CONNECTED)},b.onclose=a=>{C("Stream disconnected"),T.emit(H.DISCONNECTED)},b.onerror=a=>{ce("Stream has issue",a),T.emit(H.ERROR,a)};let s=a=>{switch(a.event){case"create":setTimeout(()=>te(a.identifier),1e3);break;case"patch":te(a.identifier);break;case"delete":delete k[a.identifier],T.emit(H.CHANGED,{flag:a.identifier,value:void 0,deleted:!0}),C("Evaluation deleted",{message:a,storage:k});break}},f=a=>{a.event==="patch"&&he()};b.addEventListener("*",a=>{let h=JSON.parse(a.data);C("Received event from stream: ",h),h.domain==="flag"?s(h):h.domain==="target-segment"&&f(h)})},ne=(s,f)=>T.on(s,f),Se=(s,f)=>{s?T.off(s,f):ge()},pe=(s,f)=>{var h;let a=k[s];if(!me&&a!==void 0){let R=a,m=s,I=D.find(L=>L.featureIdentifier===m&&L.featureValue===R);I?(oe(I),I.variationIdentifier=((h=_[m])==null?void 0:h.identifier)||""):D.push({featureIdentifier:m,featureValue:R,count:F?1:0,variationIdentifier:_[m].identifier||"",lastAccessed:Date.now()})}return a!==void 0?a:f},ge=()=>{c=!0,C("Closing event stream"),k=ve(),_={},clearTimeout(B),T.all.clear(),typeof(b==null?void 0:b.close)=="function"&&b.close()};return{on:ne,off:Se,variation:pe,close:ge}};export{H as Event,ht as initialize};
/** @license
* eventsource.js
* Available under MIT License (MIT)
* https://github.com/Yaffle/EventSource/
*/
//# sourceMappingURL=sdk.client.js.map