unleash-proxy-client
Advanced tools
Comparing version 3.3.1 to 3.3.2
@@ -90,2 +90,3 @@ import { TinyEmitter } from 'tiny-emitter'; | ||
getVariant(toggleName: string): IVariant; | ||
private updateToggles; | ||
updateContext(context: IMutableContext): Promise<void>; | ||
@@ -104,2 +105,3 @@ getContext(): { | ||
setContextField(field: string, value: string): void; | ||
removeContextField(field: string): void; | ||
private init; | ||
@@ -106,0 +108,0 @@ start(): Promise<void>; |
@@ -1,2 +0,2 @@ | ||
var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};var e=function(){return e=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},e.apply(this,arguments)};function r(t,e,r,n){return new(r||(r=Promise))((function(o,i){function s(t){try{c(n.next(t))}catch(t){i(t)}}function a(t){try{c(n.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}c((n=n.apply(t,e||[])).next())}))}function n(t,e){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}catch(t){a=[6,t],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}"function"==typeof SuppressedError&&SuppressedError;var o={exports:{}};function i(){}i.prototype={on:function(t,e,r){var n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:r}),this},once:function(t,e,r){var n=this;function o(){n.off(t,o),e.apply(r,arguments)}return o._=e,this.on(t,o,r)},emit:function(t){for(var e=[].slice.call(arguments,1),r=((this.e||(this.e={}))[t]||[]).slice(),n=0,o=r.length;n<o;n++)r[n].fn.apply(r[n].ctx,e);return this},off:function(t,e){var r=this.e||(this.e={}),n=r[t],o=[];if(n&&e)for(var i=0,s=n.length;i<s;i++)n[i].fn!==e&&n[i].fn._!==e&&o.push(n[i]);return o.length?r[t]=o:delete r[t],this}},o.exports=i;var s=o.exports.TinyEmitter=i,a=function(t){var e=t[1];return null!=e},c=function(){},u=function(){function t(t){var e=t.onError,r=t.onSent,n=t.appName,o=t.metricsInterval,i=t.disableMetrics,s=void 0!==i&&i,a=t.url,u=t.clientKey,h=t.fetch,l=t.headerName,f=t.customHeaders,p=void 0===f?{}:f;this.onError=e,this.onSent=r||c,this.disabled=s,this.metricsInterval=1e3*o,this.appName=n,this.url=a instanceof URL?a:new URL(a),this.clientKey=u,this.bucket=this.createEmptyBucket(),this.fetch=h,this.headerName=l,this.customHeaders=p}return t.prototype.start=function(){var t=this;if(this.disabled)return!1;"number"==typeof this.metricsInterval&&this.metricsInterval>0&&setTimeout((function(){t.startTimer(),t.sendMetrics()}),2e3)},t.prototype.stop=function(){this.timer&&(clearTimeout(this.timer),delete this.timer)},t.prototype.createEmptyBucket=function(){return{start:new Date,stop:null,toggles:{}}},t.prototype.getHeaders=function(){var t,e=((t={})[this.headerName]=this.clientKey,t.Accept="application/json",t["Content-Type"]="application/json",t);return Object.entries(this.customHeaders).filter(a).forEach((function(t){var r=t[0],n=t[1];return e[r]=n})),e},t.prototype.sendMetrics=function(){return r(this,void 0,void 0,(function(){var t,e,r;return n(this,(function(n){switch(n.label){case 0:if(t="".concat(this.url,"/client/metrics"),e=this.getPayload(),this.bucketIsEmpty(e))return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.fetch(t,{cache:"no-cache",method:"POST",headers:this.getHeaders(),body:JSON.stringify(e)})];case 2:return n.sent(),this.onSent(e),[3,4];case 3:return r=n.sent(),console.error("Unleash: unable to send feature metrics",r),this.onError(r),[3,4];case 4:return[2]}}))}))},t.prototype.count=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t][e?"yes":"no"]++,!0)},t.prototype.countVariant=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t].variants[e]?this.bucket.toggles[t].variants[e]+=1:this.bucket.toggles[t].variants[e]=1,!0)},t.prototype.assertBucket=function(t){if(this.disabled||!this.bucket)return!1;this.bucket.toggles[t]||(this.bucket.toggles[t]={yes:0,no:0,variants:{}})},t.prototype.startTimer=function(){var t=this;this.timer=setInterval((function(){t.sendMetrics()}),this.metricsInterval)},t.prototype.bucketIsEmpty=function(t){return 0===Object.keys(t.bucket.toggles).length},t.prototype.getPayload=function(){var t=e(e({},this.bucket),{stop:new Date});return this.bucket=this.createEmptyBucket(),{bucket:t,appName:this.appName,instanceId:"browser"}},t}(),h=function(){function t(){this.store=new Map}return t.prototype.save=function(t,e){return r(this,void 0,void 0,(function(){return n(this,(function(r){return this.store.set(t,e),[2]}))}))},t.prototype.get=function(t){return r(this,void 0,void 0,(function(){return n(this,(function(e){return[2,this.store.get(t)]}))}))},t}(),l=function(){function t(){this.prefix="unleash:repository"}return t.prototype.save=function(t,e){return r(this,void 0,void 0,(function(){var r,o;return n(this,(function(n){r=JSON.stringify(e),o="".concat(this.prefix,":").concat(t);try{window.localStorage.setItem(o,r)}catch(t){console.error(t)}return[2]}))}))},t.prototype.get=function(t){try{var e="".concat(this.prefix,":").concat(t),r=window.localStorage.getItem(e);return r?JSON.parse(r):void 0}catch(t){console.error(t)}},t}();let f;const p=new Uint8Array(16);function d(){if(!f&&(f="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!f))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return f(p)}const v=[];for(let t=0;t<256;++t)v.push((t+256).toString(16).slice(1));var m={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function y(t,e,r){if(m.randomUUID&&!e&&!t)return m.randomUUID();const n=(t=t||{}).random||(t.rng||d)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,e){r=r||0;for(let t=0;t<16;++t)e[r+t]=n[t];return e}return function(t,e=0){return v[t[e+0]]+v[t[e+1]]+v[t[e+2]]+v[t[e+3]]+"-"+v[t[e+4]]+v[t[e+5]]+"-"+v[t[e+6]]+v[t[e+7]]+"-"+v[t[e+8]]+v[t[e+9]]+"-"+v[t[e+10]]+v[t[e+11]]+v[t[e+12]]+v[t[e+13]]+v[t[e+14]]+v[t[e+15]]}(n)}var g=function(){function t(){}return t.prototype.generateEventId=function(){return y()},t.prototype.createImpressionEvent=function(t,r,n,o,i,s){var a=this.createBaseEvent(t,r,n,o,i);return s?e(e({},a),{variant:s}):a},t.prototype.createBaseEvent=function(t,e,r,n,o){return{eventType:n,eventId:this.generateEventId(),context:t,enabled:e,featureName:r,impressionData:o}},t}(),b=["userId","sessionId","remoteAddress","currentTime"],w={INIT:"initialized",ERROR:"error",READY:"ready",UPDATE:"update",IMPRESSION:"impression",SENT:"sent",RECOVERED:"recovered"},E="isEnabled",I="getVariant",S={name:"disabled",enabled:!1,feature_enabled:!1},R="repo",x=function(){try{if("undefined"!=typeof window&&"fetch"in window)return fetch.bind(window);if("fetch"in globalThis)return fetch.bind(globalThis)}catch(t){console.error('Unleash failed to resolve "fetch"',t)}},k=function(o){function i(t){var r=t.storageProvider,n=t.url,i=t.clientKey,s=t.disableRefresh,a=void 0!==s&&s,c=t.refreshInterval,f=void 0===c?30:c,p=t.metricsInterval,d=void 0===p?30:p,v=t.disableMetrics,m=void 0!==v&&v,y=t.appName,b=t.environment,E=void 0===b?"default":b,I=t.context,S=t.fetch,R=void 0===S?x():S,k=t.createAbortController,T=void 0===k?function(){try{if("undefined"!=typeof window&&"AbortController"in window)return function(){return new window.AbortController};if("fetch"in globalThis)return function(){return new globalThis.AbortController}}catch(t){console.error('Unleash failed to resolve "AbortController" factory',t)}}():k,O=t.bootstrap,N=t.bootstrapOverride,A=void 0===N||N,D=t.headerName,U=void 0===D?"Authorization":D,C=t.customHeaders,P=void 0===C?{}:C,j=t.impressionDataAll,H=void 0!==j&&j,M=t.usePOSTrequests,_=void 0!==M&&M,K=o.call(this)||this;if(K.toggles=[],K.etag="",K.readyEventEmitted=!1,K.usePOSTrequests=!1,K.started=!1,!n)throw new Error("url is required");if(!i)throw new Error("clientKey is required");if(!y)throw new Error("appName is required.");return K.eventsHandler=new g,K.impressionDataAll=H,K.toggles=O&&O.length>0?O:[],K.url=n instanceof URL?n:new URL(n),K.clientKey=i,K.headerName=U,K.customHeaders=P,K.storage=r||("undefined"!=typeof window?new l:new h),K.refreshInterval=a?0:1e3*f,K.context=e({appName:y,environment:E},I),K.usePOSTrequests=_,K.sdkState="initializing",K.ready=new Promise((function(t){K.init().then(t).catch((function(e){console.error(e),K.sdkState="error",K.emit(w.ERROR,e),t()}))})),R||console.error('Unleash: You must either provide your own "fetch" implementation or run in an environment where "fetch" is available.'),T||console.error('Unleash: You must either provide your own "AbortController" implementation or run in an environment where "AbortController" is available.'),K.fetch=R,K.createAbortController=T,K.bootstrap=O&&O.length>0?O:void 0,K.bootstrapOverride=A,K.metrics=new u({onError:K.emit.bind(K,w.ERROR),onSent:K.emit.bind(K,w.SENT),appName:y,metricsInterval:d,disableMetrics:m,url:K.url,clientKey:i,fetch:R,headerName:U,customHeaders:P}),K}return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}(i,o),i.prototype.getAllToggles=function(){return function(t,e,r){if(r||2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}([],this.toggles,!0)},i.prototype.isEnabled=function(t){var e,r=this.toggles.find((function(e){return e.name===t})),n=!!r&&r.enabled;if(this.metrics.count(t,n),(null==r?void 0:r.impressionData)||this.impressionDataAll){var o=this.eventsHandler.createImpressionEvent(this.context,n,t,E,null!==(e=null==r?void 0:r.impressionData)&&void 0!==e?e:void 0);this.emit(w.IMPRESSION,o)}return n},i.prototype.getVariant=function(t){var r,n=this.toggles.find((function(e){return e.name===t})),o=(null==n?void 0:n.enabled)||!1,i=n?n.variant:S;if(i.name&&this.metrics.countVariant(t,i.name),this.metrics.count(t,o),(null==n?void 0:n.impressionData)||this.impressionDataAll){var s=this.eventsHandler.createImpressionEvent(this.context,o,t,I,null!==(r=null==n?void 0:n.impressionData)&&void 0!==r?r:void 0,i.name);this.emit(w.IMPRESSION,s)}return e(e({},i),{feature_enabled:o})},i.prototype.updateContext=function(t){return r(this,void 0,void 0,(function(){var r,o=this;return n(this,(function(n){switch(n.label){case 0:return(t.appName||t.environment)&&console.warn("appName and environment are static. They can't be updated with updateContext."),r={environment:this.context.environment,appName:this.context.appName,sessionId:this.context.sessionId},this.context=e(e({},r),t),this.timerRef||this.readyEventEmitted?[4,this.fetchToggles()]:[3,2];case 1:return n.sent(),[3,4];case 2:return this.started?[4,new Promise((function(t){var e=function(){o.fetchToggles().then((function(){o.off(w.READY,e),t()}))};o.once(w.READY,e)}))]:[3,4];case 3:n.sent(),n.label=4;case 4:return[2]}}))}))},i.prototype.getContext=function(){return e({},this.context)},i.prototype.setContextField=function(t,r){var n,o;if(b.includes(t))this.context=e(e({},this.context),((n={})[t]=r,n));else{var i=e(e({},this.context.properties),((o={})[t]=r,o));this.context=e(e({},this.context),{properties:i})}this.timerRef&&this.fetchToggles()},i.prototype.init=function(){return r(this,void 0,void 0,(function(){var t,r;return n(this,(function(n){switch(n.label){case 0:return[4,this.resolveSessionId()];case 1:return t=n.sent(),this.context=e({sessionId:t},this.context),r=this,[4,this.storage.get(R)];case 2:return r.toggles=n.sent()||[],!this.bootstrap||!this.bootstrapOverride&&0!==this.toggles.length?[3,4]:[4,this.storage.save(R,this.bootstrap)];case 3:n.sent(),this.toggles=this.bootstrap,this.emit(w.READY),n.label=4;case 4:return this.sdkState="healthy",this.emit(w.INIT),[2]}}))}))},i.prototype.start=function(){return r(this,void 0,void 0,(function(){var t,e=this;return n(this,(function(r){switch(r.label){case 0:return this.started=!0,this.timerRef?(console.error("Unleash SDK has already started, if you want to restart the SDK you should call client.stop() before starting again."),[2]):[4,this.ready];case 1:return r.sent(),this.metrics.start(),t=this.refreshInterval,[4,this.fetchToggles()];case 2:return r.sent(),t>0&&(this.timerRef=setInterval((function(){return e.fetchToggles()}),t)),[2]}}))}))},i.prototype.stop=function(){this.timerRef&&(clearInterval(this.timerRef),this.timerRef=void 0),this.metrics.stop()},i.prototype.resolveSessionId=function(){return r(this,void 0,void 0,(function(){var t;return n(this,(function(e){switch(e.label){case 0:return this.context.sessionId?[2,this.context.sessionId]:[4,this.storage.get("sessionId")];case 1:return(t=e.sent())?[3,3]:(t=Math.floor(1e9*Math.random()),[4,this.storage.save("sessionId",t)]);case 2:e.sent(),e.label=3;case 3:return[2,t]}}))}))},i.prototype.getHeaders=function(){var t,e=((t={})[this.headerName]=this.clientKey,t.Accept="application/json",t["Content-Type"]="application/json",t);return this.etag&&(e["If-None-Match"]=this.etag),Object.entries(this.customHeaders).filter(a).forEach((function(t){var r=t[0],n=t[1];return e[r]=n})),e},i.prototype.storeToggles=function(t){return r(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return this.toggles=t,this.emit(w.UPDATE),[4,this.storage.save(R,t)];case 1:return e.sent(),[2]}}))}))},i.prototype.fetchToggles=function(){return r(this,void 0,void 0,(function(){var t,e,r,o,i,s,c,u;return n(this,(function(n){switch(n.label){case 0:if(!this.fetch)return[3,9];this.abortController&&this.abortController.abort(),this.abortController=this.createAbortController&&this.createAbortController(),t=this.abortController?this.abortController.signal:void 0,n.label=1;case 1:return n.trys.push([1,7,8,9]),e=this.usePOSTrequests,r=e?this.url:function(t,e){var r=new URL(t.toString());return Object.entries(e).filter(a).forEach((function(t){var e=t[0],n=t[1];"properties"===e&&n?Object.entries(n).filter(a).forEach((function(t){var e=t[0],n=t[1];return r.searchParams.append("properties[".concat(e,"]"),n)})):r.searchParams.append(e,n)})),r}(this.url,this.context),o=e?"POST":"GET",i=e?JSON.stringify({context:this.context}):void 0,[4,this.fetch(r.toString(),{method:o,cache:"no-cache",headers:this.getHeaders(),body:i,signal:t})];case 2:return s=n.sent(),"error"===this.sdkState&&s.status<400&&(this.sdkState="healthy",this.emit(w.RECOVERED)),s.ok&&304!==s.status?(this.etag=s.headers.get("ETag")||"",[4,s.json()]):[3,5];case 3:return c=n.sent(),[4,this.storeToggles(c.toggles)];case 4:return n.sent(),"healthy"!==this.sdkState&&(this.sdkState="healthy"),this.bootstrap||this.readyEventEmitted||(this.emit(w.READY),this.readyEventEmitted=!0),[3,6];case 5:s.ok||304===s.status||(console.error("Unleash: Fetching feature toggles did not have an ok response"),this.sdkState="error",this.emit(w.ERROR,{type:"HttpError",code:s.status})),n.label=6;case 6:return[3,9];case 7:return u=n.sent(),console.error("Unleash: unable to fetch feature toggles",u),this.sdkState="error",this.emit(w.ERROR,u),[3,9];case 8:return this.abortController=null,[7];case 9:return[2]}}))}))},i}(s);export{w as EVENTS,h as InMemoryStorageProvider,l as LocalStorageProvider,k as UnleashClient,x as resolveFetch}; | ||
var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};var e=function(){return e=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},e.apply(this,arguments)};function r(t,e,r,n){return new(r||(r=Promise))((function(o,i){function s(t){try{c(n.next(t))}catch(t){i(t)}}function a(t){try{c(n.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}c((n=n.apply(t,e||[])).next())}))}function n(t,e){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}catch(t){a=[6,t],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}"function"==typeof SuppressedError&&SuppressedError;var o={exports:{}};function i(){}i.prototype={on:function(t,e,r){var n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:r}),this},once:function(t,e,r){var n=this;function o(){n.off(t,o),e.apply(r,arguments)}return o._=e,this.on(t,o,r)},emit:function(t){for(var e=[].slice.call(arguments,1),r=((this.e||(this.e={}))[t]||[]).slice(),n=0,o=r.length;n<o;n++)r[n].fn.apply(r[n].ctx,e);return this},off:function(t,e){var r=this.e||(this.e={}),n=r[t],o=[];if(n&&e)for(var i=0,s=n.length;i<s;i++)n[i].fn!==e&&n[i].fn._!==e&&o.push(n[i]);return o.length?r[t]=o:delete r[t],this}},o.exports=i;var s=o.exports.TinyEmitter=i,a=function(t){var e=t[1];return null!=e},c=function(){},u=function(){function t(t){var e=t.onError,r=t.onSent,n=t.appName,o=t.metricsInterval,i=t.disableMetrics,s=void 0!==i&&i,a=t.url,u=t.clientKey,h=t.fetch,l=t.headerName,p=t.customHeaders,f=void 0===p?{}:p;this.onError=e,this.onSent=r||c,this.disabled=s,this.metricsInterval=1e3*o,this.appName=n,this.url=a instanceof URL?a:new URL(a),this.clientKey=u,this.bucket=this.createEmptyBucket(),this.fetch=h,this.headerName=l,this.customHeaders=f}return t.prototype.start=function(){var t=this;if(this.disabled)return!1;"number"==typeof this.metricsInterval&&this.metricsInterval>0&&setTimeout((function(){t.startTimer(),t.sendMetrics()}),2e3)},t.prototype.stop=function(){this.timer&&(clearTimeout(this.timer),delete this.timer)},t.prototype.createEmptyBucket=function(){return{start:new Date,stop:null,toggles:{}}},t.prototype.getHeaders=function(){var t,e=((t={})[this.headerName]=this.clientKey,t.Accept="application/json",t["Content-Type"]="application/json",t);return Object.entries(this.customHeaders).filter(a).forEach((function(t){var r=t[0],n=t[1];return e[r]=n})),e},t.prototype.sendMetrics=function(){return r(this,void 0,void 0,(function(){var t,e,r;return n(this,(function(n){switch(n.label){case 0:if(t="".concat(this.url,"/client/metrics"),e=this.getPayload(),this.bucketIsEmpty(e))return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.fetch(t,{cache:"no-cache",method:"POST",headers:this.getHeaders(),body:JSON.stringify(e)})];case 2:return n.sent(),this.onSent(e),[3,4];case 3:return r=n.sent(),console.error("Unleash: unable to send feature metrics",r),this.onError(r),[3,4];case 4:return[2]}}))}))},t.prototype.count=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t][e?"yes":"no"]++,!0)},t.prototype.countVariant=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t].variants[e]?this.bucket.toggles[t].variants[e]+=1:this.bucket.toggles[t].variants[e]=1,!0)},t.prototype.assertBucket=function(t){if(this.disabled||!this.bucket)return!1;this.bucket.toggles[t]||(this.bucket.toggles[t]={yes:0,no:0,variants:{}})},t.prototype.startTimer=function(){var t=this;this.timer=setInterval((function(){t.sendMetrics()}),this.metricsInterval)},t.prototype.bucketIsEmpty=function(t){return 0===Object.keys(t.bucket.toggles).length},t.prototype.getPayload=function(){var t=e(e({},this.bucket),{stop:new Date});return this.bucket=this.createEmptyBucket(),{bucket:t,appName:this.appName,instanceId:"browser"}},t}(),h=function(){function t(){this.store=new Map}return t.prototype.save=function(t,e){return r(this,void 0,void 0,(function(){return n(this,(function(r){return this.store.set(t,e),[2]}))}))},t.prototype.get=function(t){return r(this,void 0,void 0,(function(){return n(this,(function(e){return[2,this.store.get(t)]}))}))},t}(),l=function(){function t(){this.prefix="unleash:repository"}return t.prototype.save=function(t,e){return r(this,void 0,void 0,(function(){var r,o;return n(this,(function(n){r=JSON.stringify(e),o="".concat(this.prefix,":").concat(t);try{window.localStorage.setItem(o,r)}catch(t){console.error(t)}return[2]}))}))},t.prototype.get=function(t){try{var e="".concat(this.prefix,":").concat(t),r=window.localStorage.getItem(e);return r?JSON.parse(r):void 0}catch(t){console.error(t)}},t}();let p;const f=new Uint8Array(16);function d(){if(!p&&(p="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!p))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return p(f)}const v=[];for(let t=0;t<256;++t)v.push((t+256).toString(16).slice(1));var m={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function y(t,e,r){if(m.randomUUID&&!e&&!t)return m.randomUUID();const n=(t=t||{}).random||(t.rng||d)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,e){r=r||0;for(let t=0;t<16;++t)e[r+t]=n[t];return e}return function(t,e=0){return v[t[e+0]]+v[t[e+1]]+v[t[e+2]]+v[t[e+3]]+"-"+v[t[e+4]]+v[t[e+5]]+"-"+v[t[e+6]]+v[t[e+7]]+"-"+v[t[e+8]]+v[t[e+9]]+"-"+v[t[e+10]]+v[t[e+11]]+v[t[e+12]]+v[t[e+13]]+v[t[e+14]]+v[t[e+15]]}(n)}var g=function(){function t(){}return t.prototype.generateEventId=function(){return y()},t.prototype.createImpressionEvent=function(t,r,n,o,i,s){var a=this.createBaseEvent(t,r,n,o,i);return s?e(e({},a),{variant:s}):a},t.prototype.createBaseEvent=function(t,e,r,n,o){return{eventType:n,eventId:this.generateEventId(),context:t,enabled:e,featureName:r,impressionData:o}},t}(),b=["userId","sessionId","remoteAddress","currentTime"],w=function(t){return b.includes(t)},E={INIT:"initialized",ERROR:"error",READY:"ready",UPDATE:"update",IMPRESSION:"impression",SENT:"sent",RECOVERED:"recovered"},I="isEnabled",S="getVariant",x={name:"disabled",enabled:!1,feature_enabled:!1},T="repo",R=function(){try{if("undefined"!=typeof window&&"fetch"in window)return fetch.bind(window);if("fetch"in globalThis)return fetch.bind(globalThis)}catch(t){console.error('Unleash failed to resolve "fetch"',t)}},k=function(o){function i(t){var r=t.storageProvider,n=t.url,i=t.clientKey,s=t.disableRefresh,a=void 0!==s&&s,c=t.refreshInterval,p=void 0===c?30:c,f=t.metricsInterval,d=void 0===f?30:f,v=t.disableMetrics,m=void 0!==v&&v,y=t.appName,b=t.environment,w=void 0===b?"default":b,I=t.context,S=t.fetch,x=void 0===S?R():S,T=t.createAbortController,k=void 0===T?function(){try{if("undefined"!=typeof window&&"AbortController"in window)return function(){return new window.AbortController};if("fetch"in globalThis)return function(){return new globalThis.AbortController}}catch(t){console.error('Unleash failed to resolve "AbortController" factory',t)}}():T,O=t.bootstrap,N=t.bootstrapOverride,A=void 0===N||N,D=t.headerName,C=void 0===D?"Authorization":D,U=t.customHeaders,P=void 0===U?{}:U,j=t.impressionDataAll,H=void 0!==j&&j,M=t.usePOSTrequests,_=void 0!==M&&M,K=o.call(this)||this;if(K.toggles=[],K.etag="",K.readyEventEmitted=!1,K.usePOSTrequests=!1,K.started=!1,!n)throw new Error("url is required");if(!i)throw new Error("clientKey is required");if(!y)throw new Error("appName is required.");return K.eventsHandler=new g,K.impressionDataAll=H,K.toggles=O&&O.length>0?O:[],K.url=n instanceof URL?n:new URL(n),K.clientKey=i,K.headerName=C,K.customHeaders=P,K.storage=r||("undefined"!=typeof window?new l:new h),K.refreshInterval=a?0:1e3*p,K.context=e({appName:y,environment:w},I),K.usePOSTrequests=_,K.sdkState="initializing",K.ready=new Promise((function(t){K.init().then(t).catch((function(e){console.error(e),K.sdkState="error",K.emit(E.ERROR,e),t()}))})),x||console.error('Unleash: You must either provide your own "fetch" implementation or run in an environment where "fetch" is available.'),k||console.error('Unleash: You must either provide your own "AbortController" implementation or run in an environment where "AbortController" is available.'),K.fetch=x,K.createAbortController=k,K.bootstrap=O&&O.length>0?O:void 0,K.bootstrapOverride=A,K.metrics=new u({onError:K.emit.bind(K,E.ERROR),onSent:K.emit.bind(K,E.SENT),appName:y,metricsInterval:d,disableMetrics:m,url:K.url,clientKey:i,fetch:x,headerName:C,customHeaders:P}),K}return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}(i,o),i.prototype.getAllToggles=function(){return function(t,e,r){if(r||2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}([],this.toggles,!0)},i.prototype.isEnabled=function(t){var e,r=this.toggles.find((function(e){return e.name===t})),n=!!r&&r.enabled;if(this.metrics.count(t,n),(null==r?void 0:r.impressionData)||this.impressionDataAll){var o=this.eventsHandler.createImpressionEvent(this.context,n,t,I,null!==(e=null==r?void 0:r.impressionData)&&void 0!==e?e:void 0);this.emit(E.IMPRESSION,o)}return n},i.prototype.getVariant=function(t){var r,n=this.toggles.find((function(e){return e.name===t})),o=(null==n?void 0:n.enabled)||!1,i=n?n.variant:x;if(i.name&&this.metrics.countVariant(t,i.name),this.metrics.count(t,o),(null==n?void 0:n.impressionData)||this.impressionDataAll){var s=this.eventsHandler.createImpressionEvent(this.context,o,t,S,null!==(r=null==n?void 0:n.impressionData)&&void 0!==r?r:void 0,i.name);this.emit(E.IMPRESSION,s)}return e(e({},i),{feature_enabled:o})},i.prototype.updateToggles=function(){return r(this,void 0,void 0,(function(){var t=this;return n(this,(function(e){switch(e.label){case 0:return this.timerRef||this.readyEventEmitted?[4,this.fetchToggles()]:[3,2];case 1:return e.sent(),[3,4];case 2:return this.started?[4,new Promise((function(e){var r=function(){t.fetchToggles().then((function(){t.off(E.READY,r),e()}))};t.once(E.READY,r)}))]:[3,4];case 3:e.sent(),e.label=4;case 4:return[2]}}))}))},i.prototype.updateContext=function(t){return r(this,void 0,void 0,(function(){var r;return n(this,(function(n){switch(n.label){case 0:return(t.appName||t.environment)&&console.warn("appName and environment are static. They can't be updated with updateContext."),r={environment:this.context.environment,appName:this.context.appName,sessionId:this.context.sessionId},this.context=e(e({},r),t),[4,this.updateToggles()];case 1:return n.sent(),[2]}}))}))},i.prototype.getContext=function(){return e({},this.context)},i.prototype.setContextField=function(t,r){var n,o;if(w(t))this.context=e(e({},this.context),((n={})[t]=r,n));else{var i=e(e({},this.context.properties),((o={})[t]=r,o));this.context=e(e({},this.context),{properties:i})}this.updateToggles()},i.prototype.removeContextField=function(t){var r;w(t)?this.context=e(e({},this.context),((r={})[t]=void 0,r)):"object"==typeof this.context.properties&&delete this.context.properties[t],this.updateToggles()},i.prototype.init=function(){return r(this,void 0,void 0,(function(){var t,r;return n(this,(function(n){switch(n.label){case 0:return[4,this.resolveSessionId()];case 1:return t=n.sent(),this.context=e({sessionId:t},this.context),r=this,[4,this.storage.get(T)];case 2:return r.toggles=n.sent()||[],!this.bootstrap||!this.bootstrapOverride&&0!==this.toggles.length?[3,4]:[4,this.storage.save(T,this.bootstrap)];case 3:n.sent(),this.toggles=this.bootstrap,this.emit(E.READY),n.label=4;case 4:return this.sdkState="healthy",this.emit(E.INIT),[2]}}))}))},i.prototype.start=function(){return r(this,void 0,void 0,(function(){var t,e=this;return n(this,(function(r){switch(r.label){case 0:return this.started=!0,this.timerRef?(console.error("Unleash SDK has already started, if you want to restart the SDK you should call client.stop() before starting again."),[2]):[4,this.ready];case 1:return r.sent(),this.metrics.start(),t=this.refreshInterval,[4,this.fetchToggles()];case 2:return r.sent(),t>0&&(this.timerRef=setInterval((function(){return e.fetchToggles()}),t)),[2]}}))}))},i.prototype.stop=function(){this.timerRef&&(clearInterval(this.timerRef),this.timerRef=void 0),this.metrics.stop()},i.prototype.resolveSessionId=function(){return r(this,void 0,void 0,(function(){var t;return n(this,(function(e){switch(e.label){case 0:return this.context.sessionId?[2,this.context.sessionId]:[4,this.storage.get("sessionId")];case 1:return(t=e.sent())?[3,3]:(t=Math.floor(1e9*Math.random()),[4,this.storage.save("sessionId",t)]);case 2:e.sent(),e.label=3;case 3:return[2,t]}}))}))},i.prototype.getHeaders=function(){var t,e=this.usePOSTrequests,r=((t={})[this.headerName]=this.clientKey,t.Accept="application/json",t);return e&&(r["Content-Type"]="application/json"),this.etag&&(r["If-None-Match"]=this.etag),Object.entries(this.customHeaders).filter(a).forEach((function(t){var e=t[0],n=t[1];return r[e]=n})),r},i.prototype.storeToggles=function(t){return r(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return this.toggles=t,this.emit(E.UPDATE),[4,this.storage.save(T,t)];case 1:return e.sent(),[2]}}))}))},i.prototype.fetchToggles=function(){return r(this,void 0,void 0,(function(){var t,e,r,o,i,s,c,u;return n(this,(function(n){switch(n.label){case 0:if(!this.fetch)return[3,9];this.abortController&&this.abortController.abort(),this.abortController=this.createAbortController&&this.createAbortController(),t=this.abortController?this.abortController.signal:void 0,n.label=1;case 1:return n.trys.push([1,7,8,9]),e=this.usePOSTrequests,r=e?this.url:function(t,e){var r=new URL(t.toString());return Object.entries(e).filter(a).forEach((function(t){var e=t[0],n=t[1];"properties"===e&&n?Object.entries(n).filter(a).forEach((function(t){var e=t[0],n=t[1];return r.searchParams.append("properties[".concat(e,"]"),n)})):r.searchParams.append(e,n)})),r}(this.url,this.context),o=e?"POST":"GET",i=e?JSON.stringify({context:this.context}):void 0,[4,this.fetch(r.toString(),{method:o,cache:"no-cache",headers:this.getHeaders(),body:i,signal:t})];case 2:return s=n.sent(),"error"===this.sdkState&&s.status<400&&(this.sdkState="healthy",this.emit(E.RECOVERED)),s.ok&&304!==s.status?(this.etag=s.headers.get("ETag")||"",[4,s.json()]):[3,5];case 3:return c=n.sent(),[4,this.storeToggles(c.toggles)];case 4:return n.sent(),"healthy"!==this.sdkState&&(this.sdkState="healthy"),this.bootstrap||this.readyEventEmitted||(this.emit(E.READY),this.readyEventEmitted=!0),[3,6];case 5:s.ok||304===s.status||(console.error("Unleash: Fetching feature toggles did not have an ok response"),this.sdkState="error",this.emit(E.ERROR,{type:"HttpError",code:s.status})),n.label=6;case 6:return[3,9];case 7:return u=n.sent(),console.error("Unleash: unable to fetch feature toggles",u),this.sdkState="error",this.emit(E.ERROR,u),[3,9];case 8:return this.abortController=null,[7];case 9:return[2]}}))}))},i}(s);export{E as EVENTS,h as InMemoryStorageProvider,l as LocalStorageProvider,k as UnleashClient,R as resolveFetch}; | ||
//# sourceMappingURL=main.esm.js.map |
@@ -1,2 +0,2 @@ | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).unleash={})}(this,(function(t){"use strict";var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},e(t,r)};var r=function(){return r=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},r.apply(this,arguments)};function n(t,e,r,n){return new(r||(r=Promise))((function(o,i){function s(t){try{c(n.next(t))}catch(t){i(t)}}function a(t){try{c(n.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}c((n=n.apply(t,e||[])).next())}))}function o(t,e){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}catch(t){a=[6,t],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}"function"==typeof SuppressedError&&SuppressedError;var i={exports:{}};function s(){}s.prototype={on:function(t,e,r){var n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:r}),this},once:function(t,e,r){var n=this;function o(){n.off(t,o),e.apply(r,arguments)}return o._=e,this.on(t,o,r)},emit:function(t){for(var e=[].slice.call(arguments,1),r=((this.e||(this.e={}))[t]||[]).slice(),n=0,o=r.length;n<o;n++)r[n].fn.apply(r[n].ctx,e);return this},off:function(t,e){var r=this.e||(this.e={}),n=r[t],o=[];if(n&&e)for(var i=0,s=n.length;i<s;i++)n[i].fn!==e&&n[i].fn._!==e&&o.push(n[i]);return o.length?r[t]=o:delete r[t],this}},i.exports=s;var a=i.exports.TinyEmitter=s,c=function(t){var e=t[1];return null!=e},u=function(){},l=function(){function t(t){var e=t.onError,r=t.onSent,n=t.appName,o=t.metricsInterval,i=t.disableMetrics,s=void 0!==i&&i,a=t.url,c=t.clientKey,l=t.fetch,h=t.headerName,f=t.customHeaders,p=void 0===f?{}:f;this.onError=e,this.onSent=r||u,this.disabled=s,this.metricsInterval=1e3*o,this.appName=n,this.url=a instanceof URL?a:new URL(a),this.clientKey=c,this.bucket=this.createEmptyBucket(),this.fetch=l,this.headerName=h,this.customHeaders=p}return t.prototype.start=function(){var t=this;if(this.disabled)return!1;"number"==typeof this.metricsInterval&&this.metricsInterval>0&&setTimeout((function(){t.startTimer(),t.sendMetrics()}),2e3)},t.prototype.stop=function(){this.timer&&(clearTimeout(this.timer),delete this.timer)},t.prototype.createEmptyBucket=function(){return{start:new Date,stop:null,toggles:{}}},t.prototype.getHeaders=function(){var t,e=((t={})[this.headerName]=this.clientKey,t.Accept="application/json",t["Content-Type"]="application/json",t);return Object.entries(this.customHeaders).filter(c).forEach((function(t){var r=t[0],n=t[1];return e[r]=n})),e},t.prototype.sendMetrics=function(){return n(this,void 0,void 0,(function(){var t,e,r;return o(this,(function(n){switch(n.label){case 0:if(t="".concat(this.url,"/client/metrics"),e=this.getPayload(),this.bucketIsEmpty(e))return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.fetch(t,{cache:"no-cache",method:"POST",headers:this.getHeaders(),body:JSON.stringify(e)})];case 2:return n.sent(),this.onSent(e),[3,4];case 3:return r=n.sent(),console.error("Unleash: unable to send feature metrics",r),this.onError(r),[3,4];case 4:return[2]}}))}))},t.prototype.count=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t][e?"yes":"no"]++,!0)},t.prototype.countVariant=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t].variants[e]?this.bucket.toggles[t].variants[e]+=1:this.bucket.toggles[t].variants[e]=1,!0)},t.prototype.assertBucket=function(t){if(this.disabled||!this.bucket)return!1;this.bucket.toggles[t]||(this.bucket.toggles[t]={yes:0,no:0,variants:{}})},t.prototype.startTimer=function(){var t=this;this.timer=setInterval((function(){t.sendMetrics()}),this.metricsInterval)},t.prototype.bucketIsEmpty=function(t){return 0===Object.keys(t.bucket.toggles).length},t.prototype.getPayload=function(){var t=r(r({},this.bucket),{stop:new Date});return this.bucket=this.createEmptyBucket(),{bucket:t,appName:this.appName,instanceId:"browser"}},t}(),h=function(){function t(){this.store=new Map}return t.prototype.save=function(t,e){return n(this,void 0,void 0,(function(){return o(this,(function(r){return this.store.set(t,e),[2]}))}))},t.prototype.get=function(t){return n(this,void 0,void 0,(function(){return o(this,(function(e){return[2,this.store.get(t)]}))}))},t}(),f=function(){function t(){this.prefix="unleash:repository"}return t.prototype.save=function(t,e){return n(this,void 0,void 0,(function(){var r,n;return o(this,(function(o){r=JSON.stringify(e),n="".concat(this.prefix,":").concat(t);try{window.localStorage.setItem(n,r)}catch(t){console.error(t)}return[2]}))}))},t.prototype.get=function(t){try{var e="".concat(this.prefix,":").concat(t),r=window.localStorage.getItem(e);return r?JSON.parse(r):void 0}catch(t){console.error(t)}},t}();let p;const d=new Uint8Array(16);function v(){if(!p&&(p="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!p))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return p(d)}const m=[];for(let t=0;t<256;++t)m.push((t+256).toString(16).slice(1));var y={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function g(t,e,r){if(y.randomUUID&&!e&&!t)return y.randomUUID();const n=(t=t||{}).random||(t.rng||v)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,e){r=r||0;for(let t=0;t<16;++t)e[r+t]=n[t];return e}return function(t,e=0){return m[t[e+0]]+m[t[e+1]]+m[t[e+2]]+m[t[e+3]]+"-"+m[t[e+4]]+m[t[e+5]]+"-"+m[t[e+6]]+m[t[e+7]]+"-"+m[t[e+8]]+m[t[e+9]]+"-"+m[t[e+10]]+m[t[e+11]]+m[t[e+12]]+m[t[e+13]]+m[t[e+14]]+m[t[e+15]]}(n)}var b=function(){function t(){}return t.prototype.generateEventId=function(){return g()},t.prototype.createImpressionEvent=function(t,e,n,o,i,s){var a=this.createBaseEvent(t,e,n,o,i);return s?r(r({},a),{variant:s}):a},t.prototype.createBaseEvent=function(t,e,r,n,o){return{eventType:n,eventId:this.generateEventId(),context:t,enabled:e,featureName:r,impressionData:o}},t}(),w=["userId","sessionId","remoteAddress","currentTime"],E={INIT:"initialized",ERROR:"error",READY:"ready",UPDATE:"update",IMPRESSION:"impression",SENT:"sent",RECOVERED:"recovered"},I="isEnabled",S="getVariant",x={name:"disabled",enabled:!1,feature_enabled:!1},R="repo",T=function(){try{if("undefined"!=typeof window&&"fetch"in window)return fetch.bind(window);if("fetch"in globalThis)return fetch.bind(globalThis)}catch(t){console.error('Unleash failed to resolve "fetch"',t)}},k=function(t){function i(e){var n=e.storageProvider,o=e.url,i=e.clientKey,s=e.disableRefresh,a=void 0!==s&&s,c=e.refreshInterval,u=void 0===c?30:c,p=e.metricsInterval,d=void 0===p?30:p,v=e.disableMetrics,m=void 0!==v&&v,y=e.appName,g=e.environment,w=void 0===g?"default":g,I=e.context,S=e.fetch,x=void 0===S?T():S,R=e.createAbortController,k=void 0===R?function(){try{if("undefined"!=typeof window&&"AbortController"in window)return function(){return new window.AbortController};if("fetch"in globalThis)return function(){return new globalThis.AbortController}}catch(t){console.error('Unleash failed to resolve "AbortController" factory',t)}}():R,O=e.bootstrap,N=e.bootstrapOverride,A=void 0===N||N,D=e.headerName,U=void 0===D?"Authorization":D,C=e.customHeaders,P=void 0===C?{}:C,j=e.impressionDataAll,H=void 0!==j&&j,M=e.usePOSTrequests,_=void 0!==M&&M,K=t.call(this)||this;if(K.toggles=[],K.etag="",K.readyEventEmitted=!1,K.usePOSTrequests=!1,K.started=!1,!o)throw new Error("url is required");if(!i)throw new Error("clientKey is required");if(!y)throw new Error("appName is required.");return K.eventsHandler=new b,K.impressionDataAll=H,K.toggles=O&&O.length>0?O:[],K.url=o instanceof URL?o:new URL(o),K.clientKey=i,K.headerName=U,K.customHeaders=P,K.storage=n||("undefined"!=typeof window?new f:new h),K.refreshInterval=a?0:1e3*u,K.context=r({appName:y,environment:w},I),K.usePOSTrequests=_,K.sdkState="initializing",K.ready=new Promise((function(t){K.init().then(t).catch((function(e){console.error(e),K.sdkState="error",K.emit(E.ERROR,e),t()}))})),x||console.error('Unleash: You must either provide your own "fetch" implementation or run in an environment where "fetch" is available.'),k||console.error('Unleash: You must either provide your own "AbortController" implementation or run in an environment where "AbortController" is available.'),K.fetch=x,K.createAbortController=k,K.bootstrap=O&&O.length>0?O:void 0,K.bootstrapOverride=A,K.metrics=new l({onError:K.emit.bind(K,E.ERROR),onSent:K.emit.bind(K,E.SENT),appName:y,metricsInterval:d,disableMetrics:m,url:K.url,clientKey:i,fetch:x,headerName:U,customHeaders:P}),K}return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}(i,t),i.prototype.getAllToggles=function(){return function(t,e,r){if(r||2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}([],this.toggles,!0)},i.prototype.isEnabled=function(t){var e,r=this.toggles.find((function(e){return e.name===t})),n=!!r&&r.enabled;if(this.metrics.count(t,n),(null==r?void 0:r.impressionData)||this.impressionDataAll){var o=this.eventsHandler.createImpressionEvent(this.context,n,t,I,null!==(e=null==r?void 0:r.impressionData)&&void 0!==e?e:void 0);this.emit(E.IMPRESSION,o)}return n},i.prototype.getVariant=function(t){var e,n=this.toggles.find((function(e){return e.name===t})),o=(null==n?void 0:n.enabled)||!1,i=n?n.variant:x;if(i.name&&this.metrics.countVariant(t,i.name),this.metrics.count(t,o),(null==n?void 0:n.impressionData)||this.impressionDataAll){var s=this.eventsHandler.createImpressionEvent(this.context,o,t,S,null!==(e=null==n?void 0:n.impressionData)&&void 0!==e?e:void 0,i.name);this.emit(E.IMPRESSION,s)}return r(r({},i),{feature_enabled:o})},i.prototype.updateContext=function(t){return n(this,void 0,void 0,(function(){var e,n=this;return o(this,(function(o){switch(o.label){case 0:return(t.appName||t.environment)&&console.warn("appName and environment are static. They can't be updated with updateContext."),e={environment:this.context.environment,appName:this.context.appName,sessionId:this.context.sessionId},this.context=r(r({},e),t),this.timerRef||this.readyEventEmitted?[4,this.fetchToggles()]:[3,2];case 1:return o.sent(),[3,4];case 2:return this.started?[4,new Promise((function(t){var e=function(){n.fetchToggles().then((function(){n.off(E.READY,e),t()}))};n.once(E.READY,e)}))]:[3,4];case 3:o.sent(),o.label=4;case 4:return[2]}}))}))},i.prototype.getContext=function(){return r({},this.context)},i.prototype.setContextField=function(t,e){var n,o;if(w.includes(t))this.context=r(r({},this.context),((n={})[t]=e,n));else{var i=r(r({},this.context.properties),((o={})[t]=e,o));this.context=r(r({},this.context),{properties:i})}this.timerRef&&this.fetchToggles()},i.prototype.init=function(){return n(this,void 0,void 0,(function(){var t,e;return o(this,(function(n){switch(n.label){case 0:return[4,this.resolveSessionId()];case 1:return t=n.sent(),this.context=r({sessionId:t},this.context),e=this,[4,this.storage.get(R)];case 2:return e.toggles=n.sent()||[],!this.bootstrap||!this.bootstrapOverride&&0!==this.toggles.length?[3,4]:[4,this.storage.save(R,this.bootstrap)];case 3:n.sent(),this.toggles=this.bootstrap,this.emit(E.READY),n.label=4;case 4:return this.sdkState="healthy",this.emit(E.INIT),[2]}}))}))},i.prototype.start=function(){return n(this,void 0,void 0,(function(){var t,e=this;return o(this,(function(r){switch(r.label){case 0:return this.started=!0,this.timerRef?(console.error("Unleash SDK has already started, if you want to restart the SDK you should call client.stop() before starting again."),[2]):[4,this.ready];case 1:return r.sent(),this.metrics.start(),t=this.refreshInterval,[4,this.fetchToggles()];case 2:return r.sent(),t>0&&(this.timerRef=setInterval((function(){return e.fetchToggles()}),t)),[2]}}))}))},i.prototype.stop=function(){this.timerRef&&(clearInterval(this.timerRef),this.timerRef=void 0),this.metrics.stop()},i.prototype.resolveSessionId=function(){return n(this,void 0,void 0,(function(){var t;return o(this,(function(e){switch(e.label){case 0:return this.context.sessionId?[2,this.context.sessionId]:[4,this.storage.get("sessionId")];case 1:return(t=e.sent())?[3,3]:(t=Math.floor(1e9*Math.random()),[4,this.storage.save("sessionId",t)]);case 2:e.sent(),e.label=3;case 3:return[2,t]}}))}))},i.prototype.getHeaders=function(){var t,e=((t={})[this.headerName]=this.clientKey,t.Accept="application/json",t["Content-Type"]="application/json",t);return this.etag&&(e["If-None-Match"]=this.etag),Object.entries(this.customHeaders).filter(c).forEach((function(t){var r=t[0],n=t[1];return e[r]=n})),e},i.prototype.storeToggles=function(t){return n(this,void 0,void 0,(function(){return o(this,(function(e){switch(e.label){case 0:return this.toggles=t,this.emit(E.UPDATE),[4,this.storage.save(R,t)];case 1:return e.sent(),[2]}}))}))},i.prototype.fetchToggles=function(){return n(this,void 0,void 0,(function(){var t,e,r,n,i,s,a,u;return o(this,(function(o){switch(o.label){case 0:if(!this.fetch)return[3,9];this.abortController&&this.abortController.abort(),this.abortController=this.createAbortController&&this.createAbortController(),t=this.abortController?this.abortController.signal:void 0,o.label=1;case 1:return o.trys.push([1,7,8,9]),e=this.usePOSTrequests,r=e?this.url:function(t,e){var r=new URL(t.toString());return Object.entries(e).filter(c).forEach((function(t){var e=t[0],n=t[1];"properties"===e&&n?Object.entries(n).filter(c).forEach((function(t){var e=t[0],n=t[1];return r.searchParams.append("properties[".concat(e,"]"),n)})):r.searchParams.append(e,n)})),r}(this.url,this.context),n=e?"POST":"GET",i=e?JSON.stringify({context:this.context}):void 0,[4,this.fetch(r.toString(),{method:n,cache:"no-cache",headers:this.getHeaders(),body:i,signal:t})];case 2:return s=o.sent(),"error"===this.sdkState&&s.status<400&&(this.sdkState="healthy",this.emit(E.RECOVERED)),s.ok&&304!==s.status?(this.etag=s.headers.get("ETag")||"",[4,s.json()]):[3,5];case 3:return a=o.sent(),[4,this.storeToggles(a.toggles)];case 4:return o.sent(),"healthy"!==this.sdkState&&(this.sdkState="healthy"),this.bootstrap||this.readyEventEmitted||(this.emit(E.READY),this.readyEventEmitted=!0),[3,6];case 5:s.ok||304===s.status||(console.error("Unleash: Fetching feature toggles did not have an ok response"),this.sdkState="error",this.emit(E.ERROR,{type:"HttpError",code:s.status})),o.label=6;case 6:return[3,9];case 7:return u=o.sent(),console.error("Unleash: unable to fetch feature toggles",u),this.sdkState="error",this.emit(E.ERROR,u),[3,9];case 8:return this.abortController=null,[7];case 9:return[2]}}))}))},i}(a);t.EVENTS=E,t.InMemoryStorageProvider=h,t.LocalStorageProvider=f,t.UnleashClient=k,t.resolveFetch=T})); | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).unleash={})}(this,(function(t){"use strict";var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},e(t,r)};var r=function(){return r=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},r.apply(this,arguments)};function n(t,e,r,n){return new(r||(r=Promise))((function(o,i){function s(t){try{c(n.next(t))}catch(t){i(t)}}function a(t){try{c(n.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}c((n=n.apply(t,e||[])).next())}))}function o(t,e){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}catch(t){a=[6,t],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}"function"==typeof SuppressedError&&SuppressedError;var i={exports:{}};function s(){}s.prototype={on:function(t,e,r){var n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:r}),this},once:function(t,e,r){var n=this;function o(){n.off(t,o),e.apply(r,arguments)}return o._=e,this.on(t,o,r)},emit:function(t){for(var e=[].slice.call(arguments,1),r=((this.e||(this.e={}))[t]||[]).slice(),n=0,o=r.length;n<o;n++)r[n].fn.apply(r[n].ctx,e);return this},off:function(t,e){var r=this.e||(this.e={}),n=r[t],o=[];if(n&&e)for(var i=0,s=n.length;i<s;i++)n[i].fn!==e&&n[i].fn._!==e&&o.push(n[i]);return o.length?r[t]=o:delete r[t],this}},i.exports=s;var a=i.exports.TinyEmitter=s,c=function(t){var e=t[1];return null!=e},u=function(){},l=function(){function t(t){var e=t.onError,r=t.onSent,n=t.appName,o=t.metricsInterval,i=t.disableMetrics,s=void 0!==i&&i,a=t.url,c=t.clientKey,l=t.fetch,h=t.headerName,f=t.customHeaders,p=void 0===f?{}:f;this.onError=e,this.onSent=r||u,this.disabled=s,this.metricsInterval=1e3*o,this.appName=n,this.url=a instanceof URL?a:new URL(a),this.clientKey=c,this.bucket=this.createEmptyBucket(),this.fetch=l,this.headerName=h,this.customHeaders=p}return t.prototype.start=function(){var t=this;if(this.disabled)return!1;"number"==typeof this.metricsInterval&&this.metricsInterval>0&&setTimeout((function(){t.startTimer(),t.sendMetrics()}),2e3)},t.prototype.stop=function(){this.timer&&(clearTimeout(this.timer),delete this.timer)},t.prototype.createEmptyBucket=function(){return{start:new Date,stop:null,toggles:{}}},t.prototype.getHeaders=function(){var t,e=((t={})[this.headerName]=this.clientKey,t.Accept="application/json",t["Content-Type"]="application/json",t);return Object.entries(this.customHeaders).filter(c).forEach((function(t){var r=t[0],n=t[1];return e[r]=n})),e},t.prototype.sendMetrics=function(){return n(this,void 0,void 0,(function(){var t,e,r;return o(this,(function(n){switch(n.label){case 0:if(t="".concat(this.url,"/client/metrics"),e=this.getPayload(),this.bucketIsEmpty(e))return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.fetch(t,{cache:"no-cache",method:"POST",headers:this.getHeaders(),body:JSON.stringify(e)})];case 2:return n.sent(),this.onSent(e),[3,4];case 3:return r=n.sent(),console.error("Unleash: unable to send feature metrics",r),this.onError(r),[3,4];case 4:return[2]}}))}))},t.prototype.count=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t][e?"yes":"no"]++,!0)},t.prototype.countVariant=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t].variants[e]?this.bucket.toggles[t].variants[e]+=1:this.bucket.toggles[t].variants[e]=1,!0)},t.prototype.assertBucket=function(t){if(this.disabled||!this.bucket)return!1;this.bucket.toggles[t]||(this.bucket.toggles[t]={yes:0,no:0,variants:{}})},t.prototype.startTimer=function(){var t=this;this.timer=setInterval((function(){t.sendMetrics()}),this.metricsInterval)},t.prototype.bucketIsEmpty=function(t){return 0===Object.keys(t.bucket.toggles).length},t.prototype.getPayload=function(){var t=r(r({},this.bucket),{stop:new Date});return this.bucket=this.createEmptyBucket(),{bucket:t,appName:this.appName,instanceId:"browser"}},t}(),h=function(){function t(){this.store=new Map}return t.prototype.save=function(t,e){return n(this,void 0,void 0,(function(){return o(this,(function(r){return this.store.set(t,e),[2]}))}))},t.prototype.get=function(t){return n(this,void 0,void 0,(function(){return o(this,(function(e){return[2,this.store.get(t)]}))}))},t}(),f=function(){function t(){this.prefix="unleash:repository"}return t.prototype.save=function(t,e){return n(this,void 0,void 0,(function(){var r,n;return o(this,(function(o){r=JSON.stringify(e),n="".concat(this.prefix,":").concat(t);try{window.localStorage.setItem(n,r)}catch(t){console.error(t)}return[2]}))}))},t.prototype.get=function(t){try{var e="".concat(this.prefix,":").concat(t),r=window.localStorage.getItem(e);return r?JSON.parse(r):void 0}catch(t){console.error(t)}},t}();let p;const d=new Uint8Array(16);function v(){if(!p&&(p="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!p))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return p(d)}const m=[];for(let t=0;t<256;++t)m.push((t+256).toString(16).slice(1));var y={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function g(t,e,r){if(y.randomUUID&&!e&&!t)return y.randomUUID();const n=(t=t||{}).random||(t.rng||v)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,e){r=r||0;for(let t=0;t<16;++t)e[r+t]=n[t];return e}return function(t,e=0){return m[t[e+0]]+m[t[e+1]]+m[t[e+2]]+m[t[e+3]]+"-"+m[t[e+4]]+m[t[e+5]]+"-"+m[t[e+6]]+m[t[e+7]]+"-"+m[t[e+8]]+m[t[e+9]]+"-"+m[t[e+10]]+m[t[e+11]]+m[t[e+12]]+m[t[e+13]]+m[t[e+14]]+m[t[e+15]]}(n)}var b=function(){function t(){}return t.prototype.generateEventId=function(){return g()},t.prototype.createImpressionEvent=function(t,e,n,o,i,s){var a=this.createBaseEvent(t,e,n,o,i);return s?r(r({},a),{variant:s}):a},t.prototype.createBaseEvent=function(t,e,r,n,o){return{eventType:n,eventId:this.generateEventId(),context:t,enabled:e,featureName:r,impressionData:o}},t}(),w=["userId","sessionId","remoteAddress","currentTime"],E=function(t){return w.includes(t)},I={INIT:"initialized",ERROR:"error",READY:"ready",UPDATE:"update",IMPRESSION:"impression",SENT:"sent",RECOVERED:"recovered"},S="isEnabled",x="getVariant",T={name:"disabled",enabled:!1,feature_enabled:!1},R="repo",k=function(){try{if("undefined"!=typeof window&&"fetch"in window)return fetch.bind(window);if("fetch"in globalThis)return fetch.bind(globalThis)}catch(t){console.error('Unleash failed to resolve "fetch"',t)}},O=function(t){function i(e){var n=e.storageProvider,o=e.url,i=e.clientKey,s=e.disableRefresh,a=void 0!==s&&s,c=e.refreshInterval,u=void 0===c?30:c,p=e.metricsInterval,d=void 0===p?30:p,v=e.disableMetrics,m=void 0!==v&&v,y=e.appName,g=e.environment,w=void 0===g?"default":g,E=e.context,S=e.fetch,x=void 0===S?k():S,T=e.createAbortController,R=void 0===T?function(){try{if("undefined"!=typeof window&&"AbortController"in window)return function(){return new window.AbortController};if("fetch"in globalThis)return function(){return new globalThis.AbortController}}catch(t){console.error('Unleash failed to resolve "AbortController" factory',t)}}():T,O=e.bootstrap,N=e.bootstrapOverride,A=void 0===N||N,C=e.headerName,D=void 0===C?"Authorization":C,U=e.customHeaders,P=void 0===U?{}:U,j=e.impressionDataAll,H=void 0!==j&&j,M=e.usePOSTrequests,_=void 0!==M&&M,K=t.call(this)||this;if(K.toggles=[],K.etag="",K.readyEventEmitted=!1,K.usePOSTrequests=!1,K.started=!1,!o)throw new Error("url is required");if(!i)throw new Error("clientKey is required");if(!y)throw new Error("appName is required.");return K.eventsHandler=new b,K.impressionDataAll=H,K.toggles=O&&O.length>0?O:[],K.url=o instanceof URL?o:new URL(o),K.clientKey=i,K.headerName=D,K.customHeaders=P,K.storage=n||("undefined"!=typeof window?new f:new h),K.refreshInterval=a?0:1e3*u,K.context=r({appName:y,environment:w},E),K.usePOSTrequests=_,K.sdkState="initializing",K.ready=new Promise((function(t){K.init().then(t).catch((function(e){console.error(e),K.sdkState="error",K.emit(I.ERROR,e),t()}))})),x||console.error('Unleash: You must either provide your own "fetch" implementation or run in an environment where "fetch" is available.'),R||console.error('Unleash: You must either provide your own "AbortController" implementation or run in an environment where "AbortController" is available.'),K.fetch=x,K.createAbortController=R,K.bootstrap=O&&O.length>0?O:void 0,K.bootstrapOverride=A,K.metrics=new l({onError:K.emit.bind(K,I.ERROR),onSent:K.emit.bind(K,I.SENT),appName:y,metricsInterval:d,disableMetrics:m,url:K.url,clientKey:i,fetch:x,headerName:D,customHeaders:P}),K}return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}(i,t),i.prototype.getAllToggles=function(){return function(t,e,r){if(r||2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}([],this.toggles,!0)},i.prototype.isEnabled=function(t){var e,r=this.toggles.find((function(e){return e.name===t})),n=!!r&&r.enabled;if(this.metrics.count(t,n),(null==r?void 0:r.impressionData)||this.impressionDataAll){var o=this.eventsHandler.createImpressionEvent(this.context,n,t,S,null!==(e=null==r?void 0:r.impressionData)&&void 0!==e?e:void 0);this.emit(I.IMPRESSION,o)}return n},i.prototype.getVariant=function(t){var e,n=this.toggles.find((function(e){return e.name===t})),o=(null==n?void 0:n.enabled)||!1,i=n?n.variant:T;if(i.name&&this.metrics.countVariant(t,i.name),this.metrics.count(t,o),(null==n?void 0:n.impressionData)||this.impressionDataAll){var s=this.eventsHandler.createImpressionEvent(this.context,o,t,x,null!==(e=null==n?void 0:n.impressionData)&&void 0!==e?e:void 0,i.name);this.emit(I.IMPRESSION,s)}return r(r({},i),{feature_enabled:o})},i.prototype.updateToggles=function(){return n(this,void 0,void 0,(function(){var t=this;return o(this,(function(e){switch(e.label){case 0:return this.timerRef||this.readyEventEmitted?[4,this.fetchToggles()]:[3,2];case 1:return e.sent(),[3,4];case 2:return this.started?[4,new Promise((function(e){var r=function(){t.fetchToggles().then((function(){t.off(I.READY,r),e()}))};t.once(I.READY,r)}))]:[3,4];case 3:e.sent(),e.label=4;case 4:return[2]}}))}))},i.prototype.updateContext=function(t){return n(this,void 0,void 0,(function(){var e;return o(this,(function(n){switch(n.label){case 0:return(t.appName||t.environment)&&console.warn("appName and environment are static. They can't be updated with updateContext."),e={environment:this.context.environment,appName:this.context.appName,sessionId:this.context.sessionId},this.context=r(r({},e),t),[4,this.updateToggles()];case 1:return n.sent(),[2]}}))}))},i.prototype.getContext=function(){return r({},this.context)},i.prototype.setContextField=function(t,e){var n,o;if(E(t))this.context=r(r({},this.context),((n={})[t]=e,n));else{var i=r(r({},this.context.properties),((o={})[t]=e,o));this.context=r(r({},this.context),{properties:i})}this.updateToggles()},i.prototype.removeContextField=function(t){var e;E(t)?this.context=r(r({},this.context),((e={})[t]=void 0,e)):"object"==typeof this.context.properties&&delete this.context.properties[t],this.updateToggles()},i.prototype.init=function(){return n(this,void 0,void 0,(function(){var t,e;return o(this,(function(n){switch(n.label){case 0:return[4,this.resolveSessionId()];case 1:return t=n.sent(),this.context=r({sessionId:t},this.context),e=this,[4,this.storage.get(R)];case 2:return e.toggles=n.sent()||[],!this.bootstrap||!this.bootstrapOverride&&0!==this.toggles.length?[3,4]:[4,this.storage.save(R,this.bootstrap)];case 3:n.sent(),this.toggles=this.bootstrap,this.emit(I.READY),n.label=4;case 4:return this.sdkState="healthy",this.emit(I.INIT),[2]}}))}))},i.prototype.start=function(){return n(this,void 0,void 0,(function(){var t,e=this;return o(this,(function(r){switch(r.label){case 0:return this.started=!0,this.timerRef?(console.error("Unleash SDK has already started, if you want to restart the SDK you should call client.stop() before starting again."),[2]):[4,this.ready];case 1:return r.sent(),this.metrics.start(),t=this.refreshInterval,[4,this.fetchToggles()];case 2:return r.sent(),t>0&&(this.timerRef=setInterval((function(){return e.fetchToggles()}),t)),[2]}}))}))},i.prototype.stop=function(){this.timerRef&&(clearInterval(this.timerRef),this.timerRef=void 0),this.metrics.stop()},i.prototype.resolveSessionId=function(){return n(this,void 0,void 0,(function(){var t;return o(this,(function(e){switch(e.label){case 0:return this.context.sessionId?[2,this.context.sessionId]:[4,this.storage.get("sessionId")];case 1:return(t=e.sent())?[3,3]:(t=Math.floor(1e9*Math.random()),[4,this.storage.save("sessionId",t)]);case 2:e.sent(),e.label=3;case 3:return[2,t]}}))}))},i.prototype.getHeaders=function(){var t,e=this.usePOSTrequests,r=((t={})[this.headerName]=this.clientKey,t.Accept="application/json",t);return e&&(r["Content-Type"]="application/json"),this.etag&&(r["If-None-Match"]=this.etag),Object.entries(this.customHeaders).filter(c).forEach((function(t){var e=t[0],n=t[1];return r[e]=n})),r},i.prototype.storeToggles=function(t){return n(this,void 0,void 0,(function(){return o(this,(function(e){switch(e.label){case 0:return this.toggles=t,this.emit(I.UPDATE),[4,this.storage.save(R,t)];case 1:return e.sent(),[2]}}))}))},i.prototype.fetchToggles=function(){return n(this,void 0,void 0,(function(){var t,e,r,n,i,s,a,u;return o(this,(function(o){switch(o.label){case 0:if(!this.fetch)return[3,9];this.abortController&&this.abortController.abort(),this.abortController=this.createAbortController&&this.createAbortController(),t=this.abortController?this.abortController.signal:void 0,o.label=1;case 1:return o.trys.push([1,7,8,9]),e=this.usePOSTrequests,r=e?this.url:function(t,e){var r=new URL(t.toString());return Object.entries(e).filter(c).forEach((function(t){var e=t[0],n=t[1];"properties"===e&&n?Object.entries(n).filter(c).forEach((function(t){var e=t[0],n=t[1];return r.searchParams.append("properties[".concat(e,"]"),n)})):r.searchParams.append(e,n)})),r}(this.url,this.context),n=e?"POST":"GET",i=e?JSON.stringify({context:this.context}):void 0,[4,this.fetch(r.toString(),{method:n,cache:"no-cache",headers:this.getHeaders(),body:i,signal:t})];case 2:return s=o.sent(),"error"===this.sdkState&&s.status<400&&(this.sdkState="healthy",this.emit(I.RECOVERED)),s.ok&&304!==s.status?(this.etag=s.headers.get("ETag")||"",[4,s.json()]):[3,5];case 3:return a=o.sent(),[4,this.storeToggles(a.toggles)];case 4:return o.sent(),"healthy"!==this.sdkState&&(this.sdkState="healthy"),this.bootstrap||this.readyEventEmitted||(this.emit(I.READY),this.readyEventEmitted=!0),[3,6];case 5:s.ok||304===s.status||(console.error("Unleash: Fetching feature toggles did not have an ok response"),this.sdkState="error",this.emit(I.ERROR,{type:"HttpError",code:s.status})),o.label=6;case 6:return[3,9];case 7:return u=o.sent(),console.error("Unleash: unable to fetch feature toggles",u),this.sdkState="error",this.emit(I.ERROR,u),[3,9];case 8:return this.abortController=null,[7];case 9:return[2]}}))}))},i}(a);t.EVENTS=I,t.InMemoryStorageProvider=h,t.LocalStorageProvider=f,t.UnleashClient=O,t.resolveFetch=k})); | ||
//# sourceMappingURL=main.min.js.map |
{ | ||
"name": "unleash-proxy-client", | ||
"version": "3.3.1", | ||
"version": "3.3.2", | ||
"description": "A browser client that can be used together with the unleash-proxy.", | ||
@@ -5,0 +5,0 @@ "type": "module", |
@@ -91,3 +91,3 @@ # Unleash Proxy Client for the browser (JS) | ||
The [Unleash context](https://docs.getunleash.io/reference/unleash-context) is used to evaluate features against attributes of a the current user. To update and configure the Unleash context in this SDK, use the `updateContext` and `setContextField` methods. | ||
The [Unleash context](https://docs.getunleash.io/reference/unleash-context) is used to evaluate features against attributes of a the current user. To update and configure the Unleash context in this SDK, use the `updateContext`, `setContextField` and `removeContextField` methods. | ||
@@ -107,2 +107,10 @@ The context you set in your app will be passed along to the Unleash proxy or the front-end API as query parameters for feature evaluation. | ||
The `removeContextField` method only acts on the property that you choose. It does not affect any other properties of the Unleash context. | ||
```js | ||
unleash.updateContext({ userId: '1233', sessionId: 'sessionNotAffected' }); | ||
unleash.removeContextField('userId'); | ||
``` | ||
### Available options | ||
@@ -109,0 +117,0 @@ |
@@ -63,2 +63,5 @@ import { FetchMock } from 'jest-fetch-mock'; | ||
expect(body.context.appName).toBe('webAsPOST'); | ||
expect(request.headers).toMatchObject({ | ||
'Content-Type': 'application/json', | ||
}); | ||
}); | ||
@@ -79,2 +82,5 @@ | ||
expect(request.method).toBe('GET'); | ||
expect(request.headers).not.toMatchObject({ | ||
'Content-Type': 'application/json', | ||
}); | ||
}); | ||
@@ -1061,2 +1067,25 @@ | ||
test('Should removeContextField', async () => { | ||
const userId = 'some-id-123'; | ||
const customValue = 'customValue'; | ||
const config: IConfig = { | ||
url: 'http://localhost/test', | ||
clientKey: '12', | ||
appName: 'web', | ||
}; | ||
const client = new UnleashClient(config); | ||
client.setContextField('userId', userId); | ||
client.setContextField('customField', customValue); | ||
client.removeContextField('userId'); | ||
client.removeContextField('customField'); | ||
const context = client.getContext(); | ||
expect(context).toEqual({ | ||
appName: 'web', | ||
environment: 'default', | ||
properties: {}, | ||
}); | ||
}); | ||
test('Should setContextField with sessionId', async () => { | ||
@@ -1063,0 +1092,0 @@ const sessionId = 'some-session-id-123'; |
@@ -9,3 +9,9 @@ import { TinyEmitter } from 'tiny-emitter'; | ||
const DEFINED_FIELDS = ['userId', 'sessionId', 'remoteAddress', 'currentTime']; | ||
const DEFINED_FIELDS = [ | ||
'userId', | ||
'sessionId', | ||
'remoteAddress', | ||
'currentTime', | ||
] as const; | ||
type DefinedField = (typeof DEFINED_FIELDS)[number]; | ||
@@ -29,2 +35,6 @@ interface IStaticContext { | ||
const isDefinedContextField = (field: string): field is DefinedField => { | ||
return DEFINED_FIELDS.includes(field as DefinedField); | ||
}; | ||
interface IConfig extends IStaticContext { | ||
@@ -276,2 +286,18 @@ url: URL | string; | ||
private async updateToggles() { | ||
if (this.timerRef || this.readyEventEmitted) { | ||
await this.fetchToggles(); | ||
} else if (this.started) { | ||
await new Promise<void>((resolve) => { | ||
const listener = () => { | ||
this.fetchToggles().then(() => { | ||
this.off(EVENTS.READY, listener); | ||
resolve(); | ||
}); | ||
}; | ||
this.once(EVENTS.READY, listener); | ||
}); | ||
} | ||
} | ||
public async updateContext(context: IMutableContext): Promise<void> { | ||
@@ -292,15 +318,3 @@ // @ts-expect-error Give the user a nicer error message when | ||
if (this.timerRef || this.readyEventEmitted) { | ||
await this.fetchToggles(); | ||
} else if (this.started) { | ||
await new Promise<void>((resolve) => { | ||
const listener = () => { | ||
this.fetchToggles().then(() => { | ||
this.off(EVENTS.READY, listener); | ||
resolve(); | ||
}); | ||
}; | ||
this.once(EVENTS.READY, listener); | ||
}); | ||
} | ||
await this.updateToggles(); | ||
} | ||
@@ -313,3 +327,3 @@ | ||
public setContextField(field: string, value: string) { | ||
if (DEFINED_FIELDS.includes(field)) { | ||
if (isDefinedContextField(field)) { | ||
this.context = { ...this.context, [field]: value }; | ||
@@ -320,5 +334,14 @@ } else { | ||
} | ||
if (this.timerRef) { | ||
this.fetchToggles(); | ||
this.updateToggles(); | ||
} | ||
public removeContextField(field: string): void { | ||
if (isDefinedContextField(field)) { | ||
this.context = { ...this.context, [field]: undefined }; | ||
} else if (typeof this.context.properties === 'object') { | ||
delete this.context.properties[field]; | ||
} | ||
this.updateToggles(); | ||
} | ||
@@ -386,7 +409,10 @@ | ||
private getHeaders() { | ||
const isPOST = this.usePOSTrequests; | ||
const headers = { | ||
[this.headerName]: this.clientKey, | ||
Accept: 'application/json', | ||
'Content-Type': 'application/json', | ||
}; | ||
if (isPOST) { | ||
headers['Content-Type'] = 'application/json'; | ||
} | ||
if (this.etag) { | ||
@@ -393,0 +419,0 @@ headers['If-None-Match'] = this.etag; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
309098
2942
291