@configdirector/client-sdk 0.1.0 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};function e(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n=function(){return n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},n.apply(this,arguments)};function r(t,e,n,r){return new(n||(n=Promise))(function(o,i){function a(t){try{u(r.next(t))}catch(t){i(t)}}function s(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(a,s)}u((r=r.apply(t,e||[])).next())})}function o(t,e){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(u){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=e.call(t,i)}catch(t){s=[6,t],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}}function i(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var a=function(){function t(){this.handlerMap=new Map}return t.prototype.on=function(t,e){var n=this.handlerMap.get(t);n?n.push(e):this.handlerMap.set(t,[e])},t.prototype.once=function(t,e){var n=this;this.on(t,function r(o){n.off(t,r),e.apply(n,o)})},t.prototype.off=function(t,e){var n=this.handlerMap.get(t);if(n)if(e){var r=n.indexOf(e);r>=0&&n.splice(r,1)}else this.handlerMap.set(t,[])},t.prototype.clear=function(){this.handlerMap.clear()},t.prototype.emit=function(t,e){var n=this.handlerMap.get(t);n&&n.slice().map(function(t){return t(e)})},t}();class s extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}}function u(t){}function c(t){if("function"==typeof t)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=u,onError:n=u,onRetry:r=u,onComment:o}=t;let i,a="",c=!0,l="",f="";function d(t){if(""===t)return l.length>0&&e({id:i,event:f||void 0,data:l.endsWith("\n")?l.slice(0,-1):l}),i=void 0,l="",void(f="");if(t.startsWith(":"))return void(o&&o(t.slice(t.startsWith(": ")?2:1)));const n=t.indexOf(":");if(-1!==n){const e=t.slice(0,n),r=" "===t[n+1]?2:1;return void h(e,t.slice(n+r),t)}h(t,"",t)}function h(t,e,o){switch(t){case"event":f=e;break;case"data":l=`${l}${e}\n`;break;case"id":i=e.includes("\0")?void 0:e;break;case"retry":/^\d+$/.test(e)?r(parseInt(e,10)):n(new s(`Invalid \`retry\` value: "${e}"`,{type:"invalid-retry",value:e,line:o}));break;default:n(new s(`Unknown field "${t.length>20?`${t.slice(0,20)}…`:t}"`,{type:"unknown-field",field:t,value:e,line:o}))}}return{feed:function(t){const e=c?t.replace(/^\xEF\xBB\xBF/,""):t,[n,r]=function(t){const e=[];let n="",r=0;for(;r<t.length;){const o=t.indexOf("\r",r),i=t.indexOf("\n",r);let a=-1;if(-1!==o&&-1!==i?a=Math.min(o,i):-1!==o?a=o===t.length-1?-1:o:-1!==i&&(a=i),-1===a){n=t.slice(r);break}{const n=t.slice(r,a);e.push(n),r=a+1,"\r"===t[r-1]&&"\n"===t[r]&&r++}}return[e,n]}(`${a}${e}`);for(const t of n)d(t);a=r,c=!1},reset:function(t={}){a&&t.consume&&d(a),c=!0,i=void 0,l="",f="",a=""}}}const l="connecting",f="closed",d=()=>{};function h(t,{getStream:e}){const n="string"==typeof t||t instanceof URL?{url:t}:t,{onMessage:r,onComment:o=d,onConnect:i=d,onDisconnect:a=d,onScheduleReconnect:s=d}=n,{fetch:u,url:h,initialLastEventId:p}=function(t){const e=t.fetch||globalThis.fetch;if(!function(t){return"function"==typeof t}(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if("function"!=typeof AbortController)throw new Error("Missing AbortController implementation");const{url:n,initialLastEventId:r}=t;if("string"!=typeof n&&!(n instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if("string"!=typeof r&&void 0!==r)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:n,initialLastEventId:r}}(n),v={...n.headers},g=[],y=r?[r]:[],m=c({onEvent:function(t){"string"==typeof t.id&&(T=t.id),e=t,y.forEach(t=>t(e));var e},onRetry:function(t){S=t},onComment:o});let w,b,E=h.toString(),C=new AbortController,T=p,S=2e3,x=f;return k(),{close:D,connect:k,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:function(){const t=[],e=[];const n=function(n){const r=t.shift();r?r({value:n,done:!1}):e.push(n)};function r(){for(y.splice(y.indexOf(n),1);t.shift(););for(;e.shift(););}return g.push(function(){const e=t.shift();e&&(e({done:!0,value:void 0}),r())}),y.push(n),{next(){return x===f?this.return():new Promise(n=>{const r=e.shift();r?n({value:r,done:!1}):t.push(n)})},return:()=>(r(),Promise.resolve({done:!0,value:void 0})),throw:t=>(r(),Promise.reject(t)),[Symbol.asyncIterator](){return this}}},get lastEventId(){return T},get url(){return E},get readyState(){return x}};function k(){w||(x=l,C=new AbortController,w=u(h,function(){const{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s}=n,u={Accept:"text/event-stream",...v,...T?{"Last-Event-ID":T}:void 0};return{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s,headers:u,cache:"no-store",signal:C.signal}}()).then(O).catch(t=>{w=null,"AbortError"!==t.name&&"aborted"!==t.type&&!C.signal.aborted&&R()}))}function D(){x=f,C.abort(),m.reset(),clearTimeout(b),g.forEach(t=>t())}function R(){s({delay:S}),!C.signal.aborted&&(x=l,b=setTimeout(k,S))}async function O(t){i(),m.reset();const{body:n,redirected:r,status:o}=t;if(204===o)return a(),void D();if(!n)throw new Error("Missing response body");r&&(E=t.url);const s=e(n),u=new TextDecoder,c=s.getReader();let l=!0;x="open";do{const{done:t,value:e}=await c.read();e&&m.feed(u.decode(e,{stream:!t})),t&&(l=!1,w=null,m.reset(),R(),a())}while(l)}}const p={getStream:function(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}};var v=function(t){function n(e,r){var o=t.call(this,e)||this;return o.name="ConfigDirectorConnectionError",o.status=r,Object.setPrototypeOf(o,n.prototype),o}return e(n,t),n}(Error),g=function(t){function n(e){var r=t.call(this,e)||this;return r.name="ConfigDirectorValidationError",Object.setPrototypeOf(r,n.prototype),r}return e(n,t),n}(Error),y=function(){function t(t){this.options=t,this.eventEmitter=new a,this.options=t,this.logger=t.logger,this.url=new URL("sse/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return r(this,void 0,void 0,function(){var n,i,a,s,u=this;return o(this,function(c){return this.eventSource&&this.close(),n=void 0,i=void 0,a=function(t,e){return r(u,void 0,void 0,function(){var r;return o(this,function(o){switch(o.label){case 0:return[4,fetch(t,e)];case 1:return r=o.sent(),n=r.status,r.ok?[3,3]:[4,r.text()];case 2:i=o.sent(),o.label=3;case 3:return[2,r]}})})},s=new Promise(function(e,r){var o;u.eventSource=(o={url:u.url,fetch:a,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:u.options.metaContext,clientSdkKey:u.options.clientSdkKey}),onMessage:function(t){var e=t.data;u.dispatchMessage(e)},onConnect:function(){n&&u.isStatusFatal(n)?(u.close(),r(u.prepareFatalError(n,i))):(u.logger.debug("[EventSourceTransport] Connected, status: %s",n),e(u))},onScheduleReconnect:function(t){n&&u.isStatusFatal(n)?(u.close(),r(u.prepareFatalError(n,i))):u.logger.warn("[EventSourceTransport] Scheduling reconnect in ".concat(t.delay,". Response status: ").concat(n))},onDisconnect:function(){u.logger.debug("[EventSourceTransport] Disconnected")}},h(o,p))}),[2,Promise.race([s,new Promise(function(t){setTimeout(function(){return t(u)},e)})])]})})},t.prototype.dispatchMessage=function(t){try{var e=JSON.parse(t);this.eventEmitter.emit("configSetReceived",e)}catch(t){this.logger.error("[EventSourceTransport] Error parsing and dispatching config data update: ",t)}},t.prototype.prepareFatalError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, will not attempt to reconnect.");return new v(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){var t;null===(t=this.eventSource)||void 0===t||t.close()},t.prototype.dispose=function(){this.close(),this.clear()},t}(),m=function(t){var e,n,r=typeof t;if("object"===r)try{return null!==(n=null===(e=t.constructor)||void 0===e?void 0:e.name)&&void 0!==n?n:r}catch(t){return r}else if("function"===r)try{var o=t.name;return o?"function: ".concat(o):r}catch(t){return r}return r};function w(t,e){var n=t.value,r=m(e);if(!n)return{parsedValue:e,requestedType:r,usedDefault:!0,reason:"value-missing"};if("string"===r)return{parsedValue:n,requestedType:r,usedDefault:!1,reason:"found-match"};if("boolean"===r&&"boolean"===t.type){var o=function(t){if(!t)return;var e=t.toLowerCase();if("true"!=e&&"false"!=e)return;return"true"===e}(n),i="boolean"==typeof o;return{parsedValue:i?o:e,requestedType:r,usedDefault:!i,reason:i?"found-match":"invalid-boolean"}}if("number"===r&&"number"===t.type){var a=function(t){if(!t)return;var e=Number.parseFloat(t);if(isNaN(e)||!isFinite(e))return;return e}(n),s="number"==typeof a;return{parsedValue:s?a:e,requestedType:r,usedDefault:!s,reason:s?"found-match":"invalid-number"}}return{parsedValue:n,requestedType:r,usedDefault:!1,reason:"found-match"}}var b={off:-1,error:0,warn:1,info:2,debug:3},E=function(){function t(t,e){this.level=t,this.decorator=e,this.level=t,this.decorator=e,this.dateFormatter=function(){var t={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:"short"};try{return new Intl.DateTimeFormat(void 0,n(n({},t),{fractionalSecondDigits:3}))}catch(e){return new Intl.DateTimeFormat(void 0,t)}}()}return t.prototype.debug=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.debug,"debug",t],e,!1))},t.prototype.info=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.info,"info",t],e,!1))},t.prototype.warn=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.warn,"warn",t],e,!1))},t.prototype.error=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.error,"error",t],e,!1))},t.prototype.log=function(t,e,n){for(var r,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];b[this.level]>=b[e]&&t.apply(void 0,i(["[".concat(this.dateFormatter.format(new Date),"] ").concat(null===(r=this.decorator)||void 0===r?void 0:r.decorateMessage(n))],o,!1))},t}(),C=function(){function t(){}return t.prototype.decorateMessage=function(t){return"[ConfigDirector:js-client-sdk] ".concat(t)},t}(),T=function(t,e){return new E(null!=t?t:"warn",null!=e?e:new C)},S=function(){function t(){}return t.prototype.aggregate=function(t){var e;if(0==t.events.length)return[];for(var n=new Map,r=0,o=t.events;r<o.length;r++){var i=o[r],a=JSON.stringify(i),s=(null===(e=n.get(a))||void 0===e?void 0:e.count)||0;n.set(a,{event:i,count:s+1})}return Array.from(n).map(function(e){var n=e[1];return{startTime:t.startTime,endTime:t.endTime,count:n.count,event:n.event}})},t}(),x=function(){function t(t){this._events=[],this._droppedEventCount=0,this.limit=null!=t?t:1e3}return Object.defineProperty(t.prototype,"events",{get:function(){return this._events},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reachedLimit",{get:function(){return this._events.length>=this.limit},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"droppedEventCount",{get:function(){return this._droppedEventCount},enumerable:!1,configurable:!0}),t.prototype.push=function(){for(var t,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.startTime||(this.startTime=new Date);var r=Math.max(0,e.length-this.limit),o=e.slice(r,e.length);if(this._droppedEventCount+=r,this._events.length+o.length>this.limit){var i=this._events.length+o.length-this.limit;this._events.splice(0,i),this._droppedEventCount+=i}return(t=this._events).push.apply(t,o)},t.prototype.takeSnapshot=function(){var t,e=new Date,n=null!==(t=this.startTime)&&void 0!==t?t:e,r=this._events.splice(0),o=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:n,endTime:e,events:r,droppedCount:o}},t.prototype.clear=function(){this._events=[],this.startTime=void 0,this._droppedEventCount=0},t}(),k=function(){function t(t){this.executeRequests=!0,this.sdkKey=t.sdkKey,this.logger=t.logger,this.url=new URL("telemetry/v1",t.baseUrl)}return t.prototype.report=function(t){var e=t.discreteEvents,n=t.aggregatedEvents,r=t.droppedEvents;if(!this.executeRequests)return{success:!1,fatalError:!0};var o={clientSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(o))return{success:!0,fatalError:!1};var i=this.sendReport(o);return i.fatalError&&(this.executeRequests=!1),i},t.prototype.isReportEmpty=function(t){return this.isEventListEmpty(t.discreteEvents)&&this.isEventListEmpty(t.aggregatedEvents)&&this.isDroppedEventsEmpty(t.droppedEvents)},t.prototype.isDroppedEventsEmpty=function(t){var e;if(!t)return!0;var n=Object.keys(t);if(0==n.length)return!0;for(var r=0,o=n;r<o.length;r++){if((null!==(e=t[o[r]])&&void 0!==e?e:0)>0)return!1}return!0},t.prototype.isEventListEmpty=function(t){var e,n,r=Object.keys(t);if(0==r.length)return!0;for(var o=0,i=r;o<i.length;o++){if((null!==(n=null===(e=t[i[o]])||void 0===e?void 0:e.length)&&void 0!==n?n:0)>0)return!1}return!0},t.prototype.sendReport=function(t){try{return{success:navigator.sendBeacon(this.url,JSON.stringify(t)),fatalError:!1}}catch(t){return this.logger.warn("[EventReporter] Fatal error attempting to send telemetry data: ".concat(t,". No more telemetry data will be sent.")),{success:!1,fatalError:!0}}},t}(),D=function(t){for(var e=5381,n=0;n<t.length;n++)e=(e<<5)+e+t[n],e>>>=0;return e},R=function(){function t(t){var e=this;this.evaluationEventQueue=new x,this.aggregator=new S,this.collectEvents=!0,this.logger=t.logger,this.reporter=new k(t),this.flushIntervalDelay=3e4;this.flushTimeout=setTimeout(function(){return e.flushAndScheduleNext()},5e3);try{document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.flush()})}catch(t){this.logger.warn("[TelemetryEventCollector] Could not configure 'visibilitychange' listener: ",t)}}return t.prototype.evaluatedConfig=function(t){this.collectEvents&&this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))},t.prototype.sanitizeEvaluatedConfigEvent=function(t){return{key:t.key,type:t.type,defaultValue:this.sanitizeValue(t.defaultValue,t.type),requestedType:t.requestedType,evaluatedValue:this.sanitizeValue(t.evaluatedValue,t.type),usedDefault:t.usedDefault,evaluationReason:t.evaluationReason}},t.prototype.sanitizeValue=function(t,e){if("json"===e)try{var n=JSON.stringify(t);return r=n,D((new TextEncoder).encode(r)).toString(16).padStart(8,"0")}catch(e){return t.toString().slice(0,500)}var r;return t.toString().slice(0,500)},t.prototype.flushAndScheduleNext=function(){var t=this;this.flush().fatalError?(this.collectEvents=!1,this.close(),this.logger.warn("[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.")):this.flushTimeout=setTimeout(function(){return t.flushAndScheduleNext()},this.flushIntervalDelay)},t.prototype.flush=function(){var t=this.evaluationEventQueue.takeSnapshot();return this.reporter.report({discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(t)},droppedEvents:{evaluatedConfig:t.droppedCount}})},t.prototype.close=function(){this.collectEvents=!1,clearTimeout(this.flushTimeout),this.flush(),this.evaluationEventQueue.clear()},t.prototype.dispose=function(){this.close()},t}(),O=function(t,e,i,a){return r(void 0,void 0,void 0,function(){var r,s,u,c;return o(this,function(o){switch(o.label){case 0:r=new AbortController,s=setTimeout(function(){a.debug("[fetchWithTimeout] Reached timeout, aborting request"),r.abort()},t),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,fetch(e,n(n({},i),{signal:r.signal}))];case 2:return u=o.sent(),clearTimeout(s),[2,u];case 3:throw c=o.sent(),a.warn("[fetchWithTimeout] Fetch error: ",c),clearTimeout(s),c;case 4:return[2]}})})},V=function(){function t(t){this.options=t,this.eventEmitter=new a,this.fatalError=!1,this.options=t,this.logger=t.logger,this.url=new URL("pull/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return r(this,void 0,void 0,function(){var n,r,i,a,s,u,c;return o(this,function(o){switch(o.label){case 0:if(this.fatalError)return this.logger.warn("[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect."),[2,this];o.label=1;case 1:return o.trys.push([1,7,,8]),[4,O(e,this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey})},this.logger)];case 2:return(n=o.sent()).ok?[3,5]:this.isStatusFatal(n.status)?(this.fatalError=!0,r=this.prepareFatalResponseStatusError,i=[n.status],[4,n.text()]):[3,4];case 3:throw r.apply(this,i.concat([o.sent()]));case 4:throw new v("Connection failed with status: ".concat(n.status),n.status);case 5:return u=(s=JSON).parse,[4,n.text()];case 6:return a=u.apply(s,[o.sent()]),this.eventEmitter.emit("configSetReceived",a),[2,this];case 7:throw function(t){if(t instanceof DOMException){if("NotAllowedError"===t.name)return!0}else if(t instanceof TypeError)return!0;return!1}(c=o.sent())?(this.fatalError=!0,new v("Connection failed with fatal error: ".concat(c,". This is an unrecoverable error, retry attempts will be ignored."))):c instanceof SyntaxError?new v("Failed to parse the response from the server: ".concat(c)):new v("Connection failed with error: ".concat(c,"."));case 8:return[2]}})})},t.prototype.prepareFatalResponseStatusError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, retry attempts will be ignored.");return new v(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){},t.prototype.dispose=function(){this.close(),this.clear()},t}(),M=new URL("https://client-sdk-api.configdirector.com"),P=function(){function t(t,e){var r,o,i,s,u,c,l=this;this.handlersMap=new Map,this.eventEmitter=new a,this.ready=!1,this.logger=null!==(r=null==e?void 0:e.logger)&&void 0!==r?r:T(),this.timeout=null!==(i=null===(o=null==e?void 0:e.connection)||void 0===o?void 0:o.timeout)&&void 0!==i?i:3e3;var f=null!==(u=this.parseUrl(null===(s=null==e?void 0:e.connection)||void 0===s?void 0:s.url))&&void 0!==u?u:M;this.streaming=!1!==(null===(c=null==e?void 0:e.connection)||void 0===c?void 0:c.streaming);var d=this.streaming?y:V;this.usageEventCollector=new R({sdkKey:t,logger:this.logger,baseUrl:f}),this.transport=new d({clientSdkKey:t,baseUrl:f,metaContext:n(n({},null==e?void 0:e.metadata),{sdkVersion:"0.1.0",userAgent:null===navigator||void 0===navigator?void 0:navigator.userAgent}),logger:this.logger}),this.transport.on("configSetReceived",function(t){var e;null===(e=l.readyResolve)||void 0===e||e.call(l);var r=Object.keys(t.configs);l.configSet&&"full"!=t.kind?(l.configSet.configs=n(n({},l.configSet.configs),t.configs),l.eventEmitter.emit("configsUpdated",{keys:r}),l.updateWatchers(t.configs)):(l.configSet=t,l.eventEmitter.emit("configsUpdated",{keys:r}),l.updateWatchers(t.configs)),l.logger.debug("[ConfigDirectorClient] ConfigSet updated from server:",{keys:r})})}return t.prototype.initialize=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"initialization")];case 1:return e.sent(),[2]}})})},t.prototype.updateContext=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"context update")];case 1:return e.sent(),[2]}})})},t.prototype.connectToTransport=function(t,e){return r(this,void 0,void 0,function(){var n,r,i,a,s,u=this;return o(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),this.ready=!1,this.readyPromise=new Promise(function(t){u.readyResolve=t}).then(function(){u.ready=!0,u.eventEmitter.emit("clientReady",{action:e}),u.logger.debug("[ConfigDirectorClient] Received initial payload from the server, client is ready")}),n=(new Date).getTime(),[4,this.transport.connect(null!=t?t:{},this.timeout)];case 1:return o.sent(),this.currentContext=t,r=(new Date).getTime()-n,(i=this.timeout-r)>0?[4,Promise.race([this.readyPromise,new Promise(function(t){setTimeout(function(){return t()},i)})])]:[3,3];case 2:o.sent(),o.label=3;case 3:return this.ready||(a=this.streaming?"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.":"Since the client was configured without streaming, configs may not update and always return the default value.",this.logger.warn("[ConfigDirectorClient] Timed out waiting for ".concat(e," after ").concat(this.timeout,"ms. ").concat(a))),[3,5];case 4:return s=o.sent(),this.logger.error("[ConfigDirectorClient] An error occurred during ".concat(e,": "),s),[3,5];case 5:return[2]}})})},t.prototype.updateWatchers=function(t){var e=this;Object.values(t).forEach(function(t){return e.updateWatchersForConfig(t)})},t.prototype.updateWatchersForConfig=function(t){var e,n=this;null===(e=this.handlersMap.get(t.key))||void 0===e||e.forEach(function(e){var r=n.getValueFromConfigState(t.key,t,e.defaultValue);e.handler(r)})},t.prototype.watch=function(t,e,n){var r=this;this.validateDefaultValue(e);var o=this.handlersMap.get(t),i={handler:n,defaultValue:e,requestedType:typeof e};return o?o.push(i):this.handlersMap.set(t,[i]),function(){return r.unwatch(t,n)}},t.prototype.unwatch=function(t,e){var n=this.handlersMap.get(t);if(n)if(e){var r=n.findIndex(function(t){return t.handler==e});r>=0&&(null==n||n.splice(r,1))}else n.splice(0)},t.prototype.getValue=function(t,e){var n;this.validateDefaultValue(e);var r=null===(n=this.configSet)||void 0===n?void 0:n.configs[t];return this.getValueFromConfigState(t,r,e)},t.prototype.getValueFromConfigState=function(t,e,n){var r,o;if(!e)return this.logger.debug("[ConfigDirectorClient] No config state found for '".concat(t,"', returning default value '").concat(n,"'")),this.usageEventCollector.evaluatedConfig({contextId:null===(r=this.currentContext)||void 0===r?void 0:r.id,key:t,defaultValue:n,requestedType:m(n),evaluatedValue:n,usedDefault:!0,evaluationReason:"config-state-missing"}),n;var i=w(e,n);return this.usageEventCollector.evaluatedConfig({contextId:null===(o=this.currentContext)||void 0===o?void 0:o.id,key:t,defaultValue:n,requestedType:i.requestedType,evaluatedValue:i.parsedValue,usedDefault:i.usedDefault,evaluationReason:i.reason}),this.logger.debug("[ConfigDirectorClient] Evaluated '".concat(t,"' to '").concat(i.parsedValue,"'")),i.parsedValue},t.prototype.parseUrl=function(t){if(t)try{return new URL(t)}catch(e){throw new g("Invalid base URL '".concat(t,"'. Parsing failed: ").concat(e))}},t.prototype.validateDefaultValue=function(t){if(null==t)throw new g("Invalid default value. The default value for a config must be defined and non-null.");if("function"==typeof t)throw new g("Invalid default value. The default value for a config cannot be a function.")},Object.defineProperty(t.prototype,"isReady",{get:function(){return this.ready},enumerable:!1,configurable:!0}),t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.logger.debug("[ConfigDirectorClient] clear() has been called, removing all observers"),this.eventEmitter.clear(),this.handlersMap.clear()},t.prototype.unwatchAll=function(){this.handlersMap.clear()},t.prototype.close=function(){this.logger.debug("[ConfigDirectorClient] close() has been called, closing connection to server"),this.transport.close(),this.ready=!1},t.prototype.dispose=function(){this.clear(),this.close()},t}();exports.createClient=function(t,e){return new P(t,e)},exports.createConsoleLogger=function(t,e){return T(t,e)};
1
+ "use strict";var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};function e(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n=function(){return n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},n.apply(this,arguments)};function r(t,e,n,r){return new(n||(n=Promise))(function(e,o){function i(t){try{s(r.next(t))}catch(t){o(t)}}function a(t){try{s(r.throw(t))}catch(t){o(t)}}function s(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(t){t(r)})).then(i,a)}s((r=r.apply(t,[])).next())})}function o(t,e){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(u){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=e.call(t,i)}catch(t){s=[6,t],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}}function i(t,e,n){if(2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var a=function(){function t(){this.handlerMap=new Map}return t.prototype.on=function(t,e){var n=this.handlerMap.get(t);n?n.push(e):this.handlerMap.set(t,[e])},t.prototype.once=function(t,e){var n=this;this.on(t,function r(o){n.off(t,r),e.apply(n,o)})},t.prototype.off=function(t,e){var n=this.handlerMap.get(t);if(n)if(e){var r=n.indexOf(e);r>=0&&n.splice(r,1)}else this.handlerMap.set(t,[])},t.prototype.clear=function(){this.handlerMap.clear()},t.prototype.emit=function(t,e){var n=this.handlerMap.get(t);n&&n.slice().map(function(t){return t(e)})},t}();class s extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}}function u(t){}function c(t){if("function"==typeof t)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=u,onError:n=u,onRetry:r=u,onComment:o}=t;let i,a="",c=!0,l="",f="";function d(t){if(""===t)return l.length>0&&e({id:i,event:f||void 0,data:l.endsWith("\n")?l.slice(0,-1):l}),i=void 0,l="",void(f="");if(t.startsWith(":"))return void(o&&o(t.slice(t.startsWith(": ")?2:1)));const n=t.indexOf(":");if(-1!==n){const e=t.slice(0,n),r=" "===t[n+1]?2:1;return void p(e,t.slice(n+r),t)}p(t,"",t)}function p(t,e,o){switch(t){case"event":f=e;break;case"data":l=`${l}${e}\n`;break;case"id":i=e.includes("\0")?void 0:e;break;case"retry":/^\d+$/.test(e)?r(parseInt(e,10)):n(new s(`Invalid \`retry\` value: "${e}"`,{type:"invalid-retry",value:e,line:o}));break;default:n(new s(`Unknown field "${t.length>20?`${t.slice(0,20)}…`:t}"`,{type:"unknown-field",field:t,value:e,line:o}))}}return{feed:function(t){const e=c?t.replace(/^\xEF\xBB\xBF/,""):t,[n,r]=function(t){const e=[];let n="",r=0;for(;r<t.length;){const o=t.indexOf("\r",r),i=t.indexOf("\n",r);let a=-1;if(-1!==o&&-1!==i?a=Math.min(o,i):-1!==o?a=o===t.length-1?-1:o:-1!==i&&(a=i),-1===a){n=t.slice(r);break}{const n=t.slice(r,a);e.push(n),r=a+1,"\r"===t[r-1]&&"\n"===t[r]&&r++}}return[e,n]}(`${a}${e}`);for(const t of n)d(t);a=r,c=!1},reset:function(t={}){a&&t.consume&&d(a),c=!0,i=void 0,l="",f="",a=""}}}const l="connecting",f="closed",d=()=>{};function p(t,{getStream:e}){const n="string"==typeof t||t instanceof URL?{url:t}:t,{onMessage:r,onComment:o=d,onConnect:i=d,onDisconnect:a=d,onScheduleReconnect:s=d}=n,{fetch:u,url:p,initialLastEventId:h}=function(t){const e=t.fetch||globalThis.fetch;if(!function(t){return"function"==typeof t}(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if("function"!=typeof AbortController)throw new Error("Missing AbortController implementation");const{url:n,initialLastEventId:r}=t;if("string"!=typeof n&&!(n instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if("string"!=typeof r&&void 0!==r)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:n,initialLastEventId:r}}(n),v={...n.headers},g=[],y=r?[r]:[],m=c({onEvent:function(t){var e;"string"==typeof t.id&&(T=t.id),e=t,y.forEach(t=>t(e))},onRetry:function(t){S=t},onComment:o});let w,b,E=p.toString(),C=new AbortController,T=h,S=2e3,k=f;return x(),{close:D,connect:x,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:function(){const t=[],e=[],n=function(n){const r=t.shift();r?r({value:n,done:!1}):e.push(n)};function r(){for(y.splice(y.indexOf(n),1);t.shift(););for(;e.shift(););}return g.push(function(){const e=t.shift();e&&(e({done:!0,value:void 0}),r())}),y.push(n),{next(){return k===f?this.return():new Promise(n=>{const r=e.shift();r?n({value:r,done:!1}):t.push(n)})},return:()=>(r(),Promise.resolve({done:!0,value:void 0})),throw:t=>(r(),Promise.reject(t)),[Symbol.asyncIterator](){return this}}},get lastEventId(){return T},get url(){return E},get readyState(){return k}};function x(){w||(k=l,C=new AbortController,w=u(p,function(){const{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s}=n;return{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s,headers:{Accept:"text/event-stream",...v,...T?{"Last-Event-ID":T}:void 0},cache:"no-store",signal:C.signal}}()).then(O).catch(t=>{w=null,"AbortError"!==t.name&&"aborted"!==t.type&&!C.signal.aborted&&R()}))}function D(){k=f,C.abort(),m.reset(),clearTimeout(b),g.forEach(t=>t())}function R(){s({delay:S}),!C.signal.aborted&&(k=l,b=setTimeout(x,S))}async function O(t){i(),m.reset();const{body:n,redirected:r,status:o}=t;if(204===o)return a(),void D();if(!n)throw new Error("Missing response body");r&&(E=t.url);const s=e(n),u=new TextDecoder,c=s.getReader();let l=!0;k="open";do{const{done:t,value:e}=await c.read();e&&m.feed(u.decode(e,{stream:!t})),t&&(l=!1,w=null,m.reset(),R(),a())}while(l)}}const h={getStream:function(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}};var v=function(t){function n(e,r){var o=t.call(this,e)||this;return o.name="ConfigDirectorConnectionError",o.status=r,Object.setPrototypeOf(o,n.prototype),o}return e(n,t),n}(Error),g=function(t){function n(e){var r=t.call(this,e)||this;return r.name="ConfigDirectorValidationError",Object.setPrototypeOf(r,n.prototype),r}return e(n,t),n}(Error),y=function(){function t(t){this.options=t,this.eventEmitter=new a,this.options=t,this.logger=t.logger,this.url=new URL("sse/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return r(this,0,void 0,function(){var n,i,a,s,u=this;return o(this,function(c){return this.eventSource&&this.close(),n=void 0,i=void 0,a=function(t,e){return r(u,0,void 0,function(){var r;return o(this,function(o){switch(o.label){case 0:return[4,fetch(t,e)];case 1:return r=o.sent(),n=r.status,r.ok?[3,3]:[4,r.text()];case 2:i=o.sent(),o.label=3;case 3:return[2,r]}})})},s=new Promise(function(e,r){var o;u.eventSource=(o={url:u.url,fetch:a,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:u.options.metaContext,clientSdkKey:u.options.clientSdkKey}),onMessage:function(t){var e=t.data;u.dispatchMessage(e)},onConnect:function(){n&&u.isStatusFatal(n)?(u.close(),r(u.prepareFatalError(n,i))):(u.logger.debug("[EventSourceTransport] Connected, status: %s",n),e(u))},onScheduleReconnect:function(t){n&&u.isStatusFatal(n)?(u.close(),r(u.prepareFatalError(n,i))):u.logger.warn("[EventSourceTransport] Scheduling reconnect in ".concat(t.delay,". Response status: ").concat(n))},onDisconnect:function(){u.logger.debug("[EventSourceTransport] Disconnected")}},p(o,h))}),[2,Promise.race([s,new Promise(function(t){setTimeout(function(){return t(u)},e)})])]})})},t.prototype.dispatchMessage=function(t){try{var e=JSON.parse(t);this.eventEmitter.emit("configSetReceived",e)}catch(t){this.logger.error("[EventSourceTransport] Error parsing and dispatching config data update: ",t)}},t.prototype.prepareFatalError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, will not attempt to reconnect.");return new v(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){var t;null===(t=this.eventSource)||void 0===t||t.close()},t.prototype.dispose=function(){this.close(),this.clear()},t}(),m=function(t){var e,n,r=typeof t;if("object"===r)try{return null!==(n=null===(e=t.constructor)||void 0===e?void 0:e.name)&&void 0!==n?n:r}catch(t){return r}else if("function"===r)try{var o=t.name;return o?"function: ".concat(o):r}catch(t){return r}return r},w=function(t){return"number"===t||"bigint"===t},b=function(t){if(t){var e=Number.parseInt(t);if(!isNaN(e)&&isFinite(e))return e}},E=function(t){if(t){var e=Number.parseFloat(t);if(!isNaN(e)&&isFinite(e))return e}},C={off:-1,error:0,warn:1,info:2,debug:3},T=function(){function t(t,e){this.level=t,this.decorator=e,this.level=t,this.decorator=e,this.dateFormatter=function(){var t={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:"short"};try{return new Intl.DateTimeFormat(void 0,n(n({},t),{fractionalSecondDigits:3}))}catch(e){return new Intl.DateTimeFormat(void 0,t)}}()}return t.prototype.debug=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.debug,"debug",t],e,!1))},t.prototype.info=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.info,"info",t],e,!1))},t.prototype.warn=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.warn,"warn",t],e,!1))},t.prototype.error=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.error,"error",t],e,!1))},t.prototype.log=function(t,e,n){for(var r,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];C[this.level]>=C[e]&&t.apply(void 0,i(["[".concat(this.dateFormatter.format(new Date),"] ").concat(null===(r=this.decorator)||void 0===r?void 0:r.decorateMessage(n))],o,!1))},t}(),S=function(){function t(){}return t.prototype.decorateMessage=function(t){return"[ConfigDirector:js-client-sdk] ".concat(t)},t}(),k=function(t,e){return new T(null!=t?t:"warn",null!=e?e:new S)},x=function(){function t(){}return t.prototype.aggregate=function(t){var e;if(0==t.events.length)return[];for(var n=new Map,r=0,o=t.events;r<o.length;r++){var i=o[r],a=JSON.stringify(i),s=(null===(e=n.get(a))||void 0===e?void 0:e.count)||0;n.set(a,{event:i,count:s+1})}return Array.from(n).map(function(e){var n=e[1];return{startTime:t.startTime,endTime:t.endTime,count:n.count,event:n.event}})},t}(),D=function(){function t(t){this._events=[],this._droppedEventCount=0,this.limit=null!=t?t:1e3}return Object.defineProperty(t.prototype,"events",{get:function(){return this._events},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reachedLimit",{get:function(){return this._events.length>=this.limit},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"droppedEventCount",{get:function(){return this._droppedEventCount},enumerable:!1,configurable:!0}),t.prototype.push=function(){for(var t,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.startTime||(this.startTime=new Date);var r=Math.max(0,e.length-this.limit),o=e.slice(r,e.length);if(this._droppedEventCount+=r,this._events.length+o.length>this.limit){var i=this._events.length+o.length-this.limit;this._events.splice(0,i),this._droppedEventCount+=i}return(t=this._events).push.apply(t,o)},t.prototype.takeSnapshot=function(){var t,e=new Date,n=null!==(t=this.startTime)&&void 0!==t?t:e,r=this._events.splice(0),o=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:n,endTime:e,events:r,droppedCount:o}},t.prototype.clear=function(){this._events=[],this.startTime=void 0,this._droppedEventCount=0},t}(),R=function(){function t(t){this.executeRequests=!0,this.sdkKey=t.sdkKey,this.logger=t.logger,this.url=new URL("telemetry/v1",t.baseUrl)}return t.prototype.report=function(t){var e=t.discreteEvents,n=t.aggregatedEvents,r=t.droppedEvents;if(!this.executeRequests)return{success:!1,fatalError:!0};var o={clientSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(o))return{success:!0,fatalError:!1};var i=this.sendReport(o);return i.fatalError&&(this.executeRequests=!1),i},t.prototype.isReportEmpty=function(t){return this.isEventListEmpty(t.discreteEvents)&&this.isEventListEmpty(t.aggregatedEvents)&&this.isDroppedEventsEmpty(t.droppedEvents)},t.prototype.isDroppedEventsEmpty=function(t){var e;if(!t)return!0;var n=Object.keys(t);if(0==n.length)return!0;for(var r=0,o=n;r<o.length;r++)if((null!==(e=t[o[r]])&&void 0!==e?e:0)>0)return!1;return!0},t.prototype.isEventListEmpty=function(t){var e,n,r=Object.keys(t);if(0==r.length)return!0;for(var o=0,i=r;o<i.length;o++)if((null!==(n=null===(e=t[i[o]])||void 0===e?void 0:e.length)&&void 0!==n?n:0)>0)return!1;return!0},t.prototype.sendReport=function(t){try{return{success:navigator.sendBeacon(this.url,JSON.stringify(t)),fatalError:!1}}catch(t){return this.logger.warn("[EventReporter] Fatal error attempting to send telemetry data: ".concat(t,". No more telemetry data will be sent.")),{success:!1,fatalError:!0}}},t}(),O=function(){function t(t){var e=this;this.evaluationEventQueue=new D,this.aggregator=new x,this.collectEvents=!0,this.logger=t.logger,this.reporter=new R(t),this.flushIntervalDelay=3e4,this.flushTimeout=setTimeout(function(){return e.flushAndScheduleNext()},5e3);try{document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.flush()})}catch(t){this.logger.warn("[TelemetryEventCollector] Could not configure 'visibilitychange' listener: ",t)}}return t.prototype.evaluatedConfig=function(t){this.collectEvents&&this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))},t.prototype.sanitizeEvaluatedConfigEvent=function(t){return{key:t.key,type:t.type,defaultValue:this.sanitizeValue(t.defaultValue,t.type),requestedType:t.requestedType,evaluatedValue:this.sanitizeValue(t.evaluatedValue,t.type),usedDefault:t.usedDefault,evaluationReason:t.evaluationReason}},t.prototype.sanitizeValue=function(t,e){if("json"===e)try{return n=JSON.stringify(t),function(t){for(var e=5381,n=0;n<t.length;n++)e=(e<<5)+e+t[n],e>>>=0;return e}((new TextEncoder).encode(n)).toString(16).padStart(8,"0")}catch(e){return t.toString().slice(0,500)}var n;return t.toString().slice(0,500)},t.prototype.flushAndScheduleNext=function(){var t=this;this.flush().fatalError?(this.collectEvents=!1,this.close(),this.logger.warn("[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.")):this.flushTimeout=setTimeout(function(){return t.flushAndScheduleNext()},this.flushIntervalDelay)},t.prototype.flush=function(){var t=this.evaluationEventQueue.takeSnapshot();return this.reporter.report({discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(t)},droppedEvents:{evaluatedConfig:t.droppedCount}})},t.prototype.close=function(){this.collectEvents=!1,clearTimeout(this.flushTimeout),this.flush(),this.evaluationEventQueue.clear()},t.prototype.dispose=function(){this.close()},t}(),V=function(t,e,i,a){return r(void 0,0,void 0,function(){var r,s,u,c;return o(this,function(o){switch(o.label){case 0:r=new AbortController,s=setTimeout(function(){a.debug("[fetchWithTimeout] Reached timeout, aborting request"),r.abort()},t),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,fetch(e,n(n({},i),{signal:r.signal}))];case 2:return u=o.sent(),clearTimeout(s),[2,u];case 3:throw c=o.sent(),a.warn("[fetchWithTimeout] Fetch error: ",c),clearTimeout(s),c;case 4:return[2]}})})},M=function(){function t(t){this.options=t,this.eventEmitter=new a,this.fatalError=!1,this.options=t,this.logger=t.logger,this.url=new URL("pull/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return r(this,0,void 0,function(){var n,r,i,a,s,u,c;return o(this,function(o){switch(o.label){case 0:if(this.fatalError)return this.logger.warn("[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect."),[2,this];o.label=1;case 1:return o.trys.push([1,7,,8]),[4,V(e,this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey})},this.logger)];case 2:return(n=o.sent()).ok?[3,5]:this.isStatusFatal(n.status)?(this.fatalError=!0,r=this.prepareFatalResponseStatusError,i=[n.status],[4,n.text()]):[3,4];case 3:throw r.apply(this,i.concat([o.sent()]));case 4:throw new v("Connection failed with status: ".concat(n.status),n.status);case 5:return u=(s=JSON).parse,[4,n.text()];case 6:return a=u.apply(s,[o.sent()]),this.eventEmitter.emit("configSetReceived",a),[2,this];case 7:throw function(t){if(t instanceof DOMException){if("NotAllowedError"===t.name)return!0}else if(t instanceof TypeError)return!0;return!1}(c=o.sent())?(this.fatalError=!0,new v("Connection failed with fatal error: ".concat(c,". This is an unrecoverable error, retry attempts will be ignored."))):c instanceof SyntaxError?new v("Failed to parse the response from the server: ".concat(c)):new v("Connection failed with error: ".concat(c,"."));case 8:return[2]}})})},t.prototype.prepareFatalResponseStatusError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, retry attempts will be ignored.");return new v(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){},t.prototype.dispose=function(){this.close(),this.clear()},t}(),P=new URL("https://client-sdk-api.configdirector.com"),F=function(){function t(t,e,r){var o,i,s,u,c,l,f=this;this.handlersMap=new Map,this.eventEmitter=new a,this.ready=!1,this.logger=null!==(o=null==r?void 0:r.logger)&&void 0!==o?o:k(),this.timeout=null!==(s=null===(i=null==r?void 0:r.connection)||void 0===i?void 0:i.timeout)&&void 0!==s?s:3e3;var d=null!==(c=this.parseUrl(null===(u=null==r?void 0:r.connection)||void 0===u?void 0:u.url))&&void 0!==c?c:P;this.streaming=!1!==(null===(l=null==r?void 0:r.connection)||void 0===l?void 0:l.streaming);var p=this.streaming?y:M;this.usageEventCollector=new O({sdkKey:t,logger:this.logger,baseUrl:d}),this.transport=new p({clientSdkKey:t,baseUrl:d,metaContext:n(n({},null==r?void 0:r.metadata),{sdkName:e.sdkName,sdkVersion:e.sdkVersion,userAgent:null===navigator||void 0===navigator?void 0:navigator.userAgent}),logger:this.logger}),this.transport.on("configSetReceived",function(t){var e;null===(e=f.readyResolve)||void 0===e||e.call(f);var r=Object.keys(t.configs);f.configSet&&"full"!=t.kind?(f.configSet.configs=n(n({},f.configSet.configs),t.configs),f.eventEmitter.emit("configsUpdated",{keys:r}),f.updateWatchers(t.configs)):(f.configSet=t,f.eventEmitter.emit("configsUpdated",{keys:r}),f.updateWatchers(t.configs)),f.logger.debug("[ConfigDirectorClient] ConfigSet updated from server:",{keys:r})})}return t.prototype.initialize=function(t){return r(this,0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"initialization")];case 1:return e.sent(),[2]}})})},t.prototype.updateContext=function(t){return r(this,0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"context update")];case 1:return e.sent(),[2]}})})},t.prototype.connectToTransport=function(t,e){return r(this,0,void 0,function(){var n,r,i,a,s,u=this;return o(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),this.ready=!1,this.readyPromise=new Promise(function(t){u.readyResolve=t}).then(function(){u.ready=!0,u.eventEmitter.emit("clientReady",{action:e}),u.logger.debug("[ConfigDirectorClient] Received initial payload from the server, client is ready")}),n=(new Date).getTime(),[4,this.transport.connect(null!=t?t:{},this.timeout)];case 1:return o.sent(),this.currentContext=t,r=(new Date).getTime()-n,(i=this.timeout-r)>0?[4,Promise.race([this.readyPromise,new Promise(function(t){setTimeout(function(){return t()},i)})])]:[3,3];case 2:o.sent(),o.label=3;case 3:return this.ready||(a=this.streaming?"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.":"Since the client was configured without streaming, configs may not update and always return the default value.",this.logger.warn("[ConfigDirectorClient] Timed out waiting for ".concat(e," after ").concat(this.timeout,"ms. ").concat(a))),[3,5];case 4:return s=o.sent(),this.logger.error("[ConfigDirectorClient] An error occurred during ".concat(e,": "),s),[3,5];case 5:return[2]}})})},t.prototype.updateWatchers=function(t){var e=this;Object.values(t).forEach(function(t){return e.updateWatchersForConfig(t)})},t.prototype.updateWatchersForConfig=function(t){var e,n=this;null===(e=this.handlersMap.get(t.key))||void 0===e||e.forEach(function(e){var r=n.getValueFromConfigState(t.key,t,e.defaultValue);e.handler(r)})},t.prototype.watch=function(t,e,n){var r=this;this.validateDefaultValue(e);var o=this.handlersMap.get(t),i={handler:n,defaultValue:e,requestedType:typeof e};return o?o.push(i):this.handlersMap.set(t,[i]),function(){return r.unwatch(t,n)}},t.prototype.unwatch=function(t,e){var n=this.handlersMap.get(t);if(n)if(e){var r=n.findIndex(function(t){return t.handler==e});r>=0&&(null==n||n.splice(r,1))}else n.splice(0)},t.prototype.getValue=function(t,e){var n;this.validateDefaultValue(e);var r=null===(n=this.configSet)||void 0===n?void 0:n.configs[t];return this.getValueFromConfigState(t,r,e)},t.prototype.getValueFromConfigState=function(t,e,n){var r,o;if(!e)return this.logger.debug("[ConfigDirectorClient] No config state found for '".concat(t,"', returning default value '").concat(n,"'")),this.usageEventCollector.evaluatedConfig({contextId:null===(r=this.currentContext)||void 0===r?void 0:r.id,key:t,defaultValue:n,requestedType:m(n),evaluatedValue:n,usedDefault:!0,evaluationReason:"config-state-missing"}),n;var i=function(t,e){var n,r,o=t.value,i=m(e);if(!o)return{parsedValue:e,requestedType:i,usedDefault:!0,reason:"value-missing"};if("string"==typeof e)return{parsedValue:o,requestedType:i,usedDefault:!1,reason:"found-match"};if("boolean"==typeof e&&"boolean"===t.type){var a=function(t){if(t){var e=t.toLowerCase();if("true"==e||"false"==e)return"true"===e}}(o),s="boolean"==typeof a;return{parsedValue:s?a:e,requestedType:i,usedDefault:!s,reason:s?"found-match":"invalid-boolean"}}return w(typeof e)&&"integer"===t.type?{parsedValue:(r="number"==typeof(n=b(o)))?n:e,requestedType:i,usedDefault:!r,reason:r?"found-match":"invalid-number"}:!w(typeof e)||"float"!==t.type&&"enum"!==t.type?{parsedValue:o,requestedType:i,usedDefault:!1,reason:"found-match"}:{parsedValue:(r="number"==typeof(n=E(o)))?n:e,requestedType:i,usedDefault:!r,reason:r?"found-match":"invalid-number"}}(e,n);return this.usageEventCollector.evaluatedConfig({contextId:null===(o=this.currentContext)||void 0===o?void 0:o.id,key:t,defaultValue:n,requestedType:i.requestedType,evaluatedValue:i.parsedValue,usedDefault:i.usedDefault,evaluationReason:i.reason}),this.logger.debug("[ConfigDirectorClient] Evaluated '".concat(t,"' to '").concat(i.parsedValue,"'")),i.parsedValue},t.prototype.parseUrl=function(t){if(t)try{return new URL(t)}catch(e){throw new g("Invalid base URL '".concat(t,"'. Parsing failed: ").concat(e))}},t.prototype.validateDefaultValue=function(t){if(null==t)throw new g("Invalid default value. The default value for a config must be defined and non-null.");if("function"==typeof t)throw new g("Invalid default value. The default value for a config cannot be a function.")},Object.defineProperty(t.prototype,"isReady",{get:function(){return this.ready},enumerable:!1,configurable:!0}),t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.logger.debug("[ConfigDirectorClient] clear() has been called, removing all observers"),this.eventEmitter.clear(),this.handlersMap.clear()},t.prototype.unwatchAll=function(){this.handlersMap.clear()},t.prototype.close=function(){this.logger.debug("[ConfigDirectorClient] close() has been called, closing connection to server"),this.transport.close(),this.ready=!1},t.prototype.dispose=function(){this.clear(),this.close()},t}();exports.createClient=function(t,e){return new F(t,{sdkName:"js-client-sdk",sdkVersion:"0.1.3"},e)},exports.createConsoleLogger=function(t,e){return k(t,e)};
2
2
  //# sourceMappingURL=configdirector-client.cjs.js.map
@@ -48,16 +48,59 @@ type ConfigDirectorContext = {
48
48
  [key: string]: unknown;
49
49
  };
50
50
  };
51
+ /**
52
+ * Configuration options for the {@link ConfigDirectorClient}
53
+ */
51
54
  type ConfigDirectorClientOptions = {
55
+ /**
56
+ * Application metadata that remains constant through the lifetime of the connection
57
+ */
52
58
  metadata?: {
53
59
  appVersion?: string;
54
60
  appName?: string;
55
61
  };
62
+ /**
63
+ * Connection options
64
+ */
56
65
  connection?: {
66
+ /**
67
+ * Whether to open a streaming connection or use a one-time pull of configuration state.
68
+ * If set to true, the streaming connection will remain open and receive updates whenever
69
+ * config state is updated on the ConfigDirector dashboard.
70
+ * When set to false, there will be an initial request to retrieve config state during
71
+ * initialization, and an additional request whenever {@link ConfigDirectorClient.updateContext}
72
+ * is called. But not updates will be received after those requests.
73
+ *
74
+ * Defaults to true (streaming connection)
75
+ */
76
+ streaming?: boolean;
77
+ /**
78
+ * The timeout, in milliseconds, to be used in initialization and when updating the context.
79
+ * If streaming is enabled, the operation (initialization or context update) may still succeed
80
+ * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
81
+ * If streaming is disabled, if the operation times out, it will not be retried.
82
+ */
57
83
  timeout?: number;
84
+ /**
85
+ * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
86
+ * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
87
+ * a proxy for the client SDK.
88
+ */
58
89
  url?: string;
59
- streaming?: boolean;
60
90
  };
91
+ /**
92
+ * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
93
+ * logger set to 'warn' level.
94
+ *
95
+ * The log level of the default logger can be adjusted by creating a default logger with the desired
96
+ * level and providing it in this property:
97
+ * @example
98
+ * import { createClient, createConsoleLogger } from "@configdirector/client-sdk";
99
+ * const client = createClient(
100
+ * "YOUR-SDK-KEY",
101
+ * { logger: createConsoleLogger("debug") },
102
+ * );
103
+ */
61
104
  logger?: ConfigDirectorLogger;
62
105
  };
63
106
  type ClientConnectAction = "initialization" | "context update";
@@ -73,7 +116,7 @@ type WatchHandler<T extends ConfigValueType> = (message: T) => void;
73
116
  /**
74
117
  * The ConfigDirector SDK client object.
75
118
  *
76
- * Applications should create a single instance of {@link DefaultConfigDirectorClient}, and call
119
+ * Applications should create a single instance of `ConfigDirectorClient`, and call
77
120
  * {@link initialize} during application initialization.
78
121
  *
79
122
  * After initialization, to update the user's context, so that targeting rules are evaluated
@@ -100,26 +143,57 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
100
143
  * @param context The current user's context to be used for evaluating targeting rules (required).
101
144
  */
102
145
  updateContext(context: ConfigDirectorContext): Promise<void>;
146
+ /**
147
+ * Returns whether or not the client is ready after calling {@link initialize} or {@link updateContext}
148
+ *
149
+ * The definition of ready is that the connection to the server was successful, and config state
150
+ * was received.
151
+ */
103
152
  get isReady(): boolean;
153
+ /**
154
+ * Evaluates a config and returns its value based on the current context and targeting rules
155
+ *
156
+ * @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
157
+ * @param configKey The config key to evaluate
158
+ * @param defaultValue The default value to be returned if the config state is unavailable. For
159
+ * example, if the client cannot connect to the server due to network conditions, or if getValue
160
+ * is called before initialization is done.
161
+ */
104
162
  getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
163
+ /**
164
+ * Watches for changes to a a config evaluation value. Whenever the config value changes, the
165
+ * provided callback function will be called with the new value. Changes can happen due to updates
166
+ * to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
167
+ *
168
+ * @returns An 'unwatch' function that can be called to remove the subscriber
169
+ *
170
+ * @param configKey The config key to watch
171
+ * @param defaultValue The default value to be referenced if the config state is unavailable
172
+ * @param callback The callback function to be called whenever the config value is updated
173
+ */
105
174
  watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>): () => void;
175
+ /**
176
+ * Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
177
+ * is provided.
178
+ *
179
+ * @param configKey The config key to remove subscribers from
180
+ * @param callback The subscriber to be removed. If not provided, all subscribers are removed for
181
+ * the given `configKey`.
182
+ */
106
183
  unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
184
+ /**
185
+ * Removes all subscribers from all config keys
186
+ */
107
187
  unwatchAll(): void;
188
+ /**
189
+ * Disposes of the client. All connections are closed, and all event and config key subscribers
190
+ * are removed.
191
+ *
192
+ * Intended to be called when your application shuts down
193
+ */
108
194
  dispose(): void;
109
195
  }
110
196
 
111
- declare class DefaultConsoleLogger implements ConfigDirectorLogger {
112
- private readonly level;
113
- private readonly decorator;
114
- private readonly dateFormatter;
115
- constructor(level: ConfigDirectorLoggingLevel, decorator: ConfigDirectorLogMessageDecorator);
116
- debug(message: string, ...args: any): void;
117
- info(message: string, ...args: any): void;
118
- warn(message: string, ...args: any): void;
119
- error(message: string, ...args: any): void;
120
- private log;
121
- }
122
-
123
197
  declare class ConfigDirectorConnectionError extends Error {
124
198
  readonly name: string;
125
199
  readonly status?: number;
@@ -130,8 +204,5 @@ declare class ConfigDirectorValidationError extends Error {
130
204
  constructor(message: string);
131
205
  }
132
206
 
133
- declare const createClient: (clientSdkKey: string, clientOptions?: ConfigDirectorClientOptions) => ConfigDirectorClient;
134
- declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel, messageDecorator?: ConfigDirectorLogMessageDecorator) => DefaultConsoleLogger;
135
-
136
- export { ConfigDirectorConnectionError, ConfigDirectorValidationError, createClient, createConsoleLogger };
207
+ export { ConfigDirectorConnectionError, ConfigDirectorValidationError };
137
208
  export type { ConfigDirectorClient, ConfigDirectorClientOptions, ConfigDirectorContext, ConfigDirectorLogMessageDecorator, ConfigDirectorLogger, ConfigDirectorLoggingLevel, ConfigValueType };
@@ -1,2 +1,2 @@
1
- var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};function e(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n=function(){return n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},n.apply(this,arguments)};function r(t,e,n,r){return new(n||(n=Promise))(function(o,i){function a(t){try{u(r.next(t))}catch(t){i(t)}}function s(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(a,s)}u((r=r.apply(t,e||[])).next())})}function o(t,e){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(u){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=e.call(t,i)}catch(t){s=[6,t],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}}function i(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var a=function(){function t(){this.handlerMap=new Map}return t.prototype.on=function(t,e){var n=this.handlerMap.get(t);n?n.push(e):this.handlerMap.set(t,[e])},t.prototype.once=function(t,e){var n=this;this.on(t,function r(o){n.off(t,r),e.apply(n,o)})},t.prototype.off=function(t,e){var n=this.handlerMap.get(t);if(n)if(e){var r=n.indexOf(e);r>=0&&n.splice(r,1)}else this.handlerMap.set(t,[])},t.prototype.clear=function(){this.handlerMap.clear()},t.prototype.emit=function(t,e){var n=this.handlerMap.get(t);n&&n.slice().map(function(t){return t(e)})},t}();class s extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}}function u(t){}function c(t){if("function"==typeof t)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=u,onError:n=u,onRetry:r=u,onComment:o}=t;let i,a="",c=!0,l="",f="";function d(t){if(""===t)return l.length>0&&e({id:i,event:f||void 0,data:l.endsWith("\n")?l.slice(0,-1):l}),i=void 0,l="",void(f="");if(t.startsWith(":"))return void(o&&o(t.slice(t.startsWith(": ")?2:1)));const n=t.indexOf(":");if(-1!==n){const e=t.slice(0,n),r=" "===t[n+1]?2:1;return void h(e,t.slice(n+r),t)}h(t,"",t)}function h(t,e,o){switch(t){case"event":f=e;break;case"data":l=`${l}${e}\n`;break;case"id":i=e.includes("\0")?void 0:e;break;case"retry":/^\d+$/.test(e)?r(parseInt(e,10)):n(new s(`Invalid \`retry\` value: "${e}"`,{type:"invalid-retry",value:e,line:o}));break;default:n(new s(`Unknown field "${t.length>20?`${t.slice(0,20)}…`:t}"`,{type:"unknown-field",field:t,value:e,line:o}))}}return{feed:function(t){const e=c?t.replace(/^\xEF\xBB\xBF/,""):t,[n,r]=function(t){const e=[];let n="",r=0;for(;r<t.length;){const o=t.indexOf("\r",r),i=t.indexOf("\n",r);let a=-1;if(-1!==o&&-1!==i?a=Math.min(o,i):-1!==o?a=o===t.length-1?-1:o:-1!==i&&(a=i),-1===a){n=t.slice(r);break}{const n=t.slice(r,a);e.push(n),r=a+1,"\r"===t[r-1]&&"\n"===t[r]&&r++}}return[e,n]}(`${a}${e}`);for(const t of n)d(t);a=r,c=!1},reset:function(t={}){a&&t.consume&&d(a),c=!0,i=void 0,l="",f="",a=""}}}const l="connecting",f="closed",d=()=>{};function h(t,{getStream:e}){const n="string"==typeof t||t instanceof URL?{url:t}:t,{onMessage:r,onComment:o=d,onConnect:i=d,onDisconnect:a=d,onScheduleReconnect:s=d}=n,{fetch:u,url:h,initialLastEventId:p}=function(t){const e=t.fetch||globalThis.fetch;if(!function(t){return"function"==typeof t}(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if("function"!=typeof AbortController)throw new Error("Missing AbortController implementation");const{url:n,initialLastEventId:r}=t;if("string"!=typeof n&&!(n instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if("string"!=typeof r&&void 0!==r)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:n,initialLastEventId:r}}(n),v={...n.headers},g=[],y=r?[r]:[],m=c({onEvent:function(t){"string"==typeof t.id&&(T=t.id),e=t,y.forEach(t=>t(e));var e},onRetry:function(t){S=t},onComment:o});let w,b,E=h.toString(),C=new AbortController,T=p,S=2e3,x=f;return k(),{close:D,connect:k,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:function(){const t=[],e=[];const n=function(n){const r=t.shift();r?r({value:n,done:!1}):e.push(n)};function r(){for(y.splice(y.indexOf(n),1);t.shift(););for(;e.shift(););}return g.push(function(){const e=t.shift();e&&(e({done:!0,value:void 0}),r())}),y.push(n),{next(){return x===f?this.return():new Promise(n=>{const r=e.shift();r?n({value:r,done:!1}):t.push(n)})},return:()=>(r(),Promise.resolve({done:!0,value:void 0})),throw:t=>(r(),Promise.reject(t)),[Symbol.asyncIterator](){return this}}},get lastEventId(){return T},get url(){return E},get readyState(){return x}};function k(){w||(x=l,C=new AbortController,w=u(h,function(){const{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s}=n,u={Accept:"text/event-stream",...v,...T?{"Last-Event-ID":T}:void 0};return{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s,headers:u,cache:"no-store",signal:C.signal}}()).then(O).catch(t=>{w=null,"AbortError"!==t.name&&"aborted"!==t.type&&!C.signal.aborted&&R()}))}function D(){x=f,C.abort(),m.reset(),clearTimeout(b),g.forEach(t=>t())}function R(){s({delay:S}),!C.signal.aborted&&(x=l,b=setTimeout(k,S))}async function O(t){i(),m.reset();const{body:n,redirected:r,status:o}=t;if(204===o)return a(),void D();if(!n)throw new Error("Missing response body");r&&(E=t.url);const s=e(n),u=new TextDecoder,c=s.getReader();let l=!0;x="open";do{const{done:t,value:e}=await c.read();e&&m.feed(u.decode(e,{stream:!t})),t&&(l=!1,w=null,m.reset(),R(),a())}while(l)}}const p={getStream:function(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}};var v=function(t){function n(e,r){var o=t.call(this,e)||this;return o.name="ConfigDirectorConnectionError",o.status=r,Object.setPrototypeOf(o,n.prototype),o}return e(n,t),n}(Error),g=function(t){function n(e){var r=t.call(this,e)||this;return r.name="ConfigDirectorValidationError",Object.setPrototypeOf(r,n.prototype),r}return e(n,t),n}(Error),y=function(){function t(t){this.options=t,this.eventEmitter=new a,this.options=t,this.logger=t.logger,this.url=new URL("sse/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return r(this,void 0,void 0,function(){var n,i,a,s,u=this;return o(this,function(c){return this.eventSource&&this.close(),n=void 0,i=void 0,a=function(t,e){return r(u,void 0,void 0,function(){var r;return o(this,function(o){switch(o.label){case 0:return[4,fetch(t,e)];case 1:return r=o.sent(),n=r.status,r.ok?[3,3]:[4,r.text()];case 2:i=o.sent(),o.label=3;case 3:return[2,r]}})})},s=new Promise(function(e,r){var o;u.eventSource=(o={url:u.url,fetch:a,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:u.options.metaContext,clientSdkKey:u.options.clientSdkKey}),onMessage:function(t){var e=t.data;u.dispatchMessage(e)},onConnect:function(){n&&u.isStatusFatal(n)?(u.close(),r(u.prepareFatalError(n,i))):(u.logger.debug("[EventSourceTransport] Connected, status: %s",n),e(u))},onScheduleReconnect:function(t){n&&u.isStatusFatal(n)?(u.close(),r(u.prepareFatalError(n,i))):u.logger.warn("[EventSourceTransport] Scheduling reconnect in ".concat(t.delay,". Response status: ").concat(n))},onDisconnect:function(){u.logger.debug("[EventSourceTransport] Disconnected")}},h(o,p))}),[2,Promise.race([s,new Promise(function(t){setTimeout(function(){return t(u)},e)})])]})})},t.prototype.dispatchMessage=function(t){try{var e=JSON.parse(t);this.eventEmitter.emit("configSetReceived",e)}catch(t){this.logger.error("[EventSourceTransport] Error parsing and dispatching config data update: ",t)}},t.prototype.prepareFatalError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, will not attempt to reconnect.");return new v(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){var t;null===(t=this.eventSource)||void 0===t||t.close()},t.prototype.dispose=function(){this.close(),this.clear()},t}(),m=function(t){var e,n,r=typeof t;if("object"===r)try{return null!==(n=null===(e=t.constructor)||void 0===e?void 0:e.name)&&void 0!==n?n:r}catch(t){return r}else if("function"===r)try{var o=t.name;return o?"function: ".concat(o):r}catch(t){return r}return r};function w(t,e){var n=t.value,r=m(e);if(!n)return{parsedValue:e,requestedType:r,usedDefault:!0,reason:"value-missing"};if("string"===r)return{parsedValue:n,requestedType:r,usedDefault:!1,reason:"found-match"};if("boolean"===r&&"boolean"===t.type){var o=function(t){if(!t)return;var e=t.toLowerCase();if("true"!=e&&"false"!=e)return;return"true"===e}(n),i="boolean"==typeof o;return{parsedValue:i?o:e,requestedType:r,usedDefault:!i,reason:i?"found-match":"invalid-boolean"}}if("number"===r&&"number"===t.type){var a=function(t){if(!t)return;var e=Number.parseFloat(t);if(isNaN(e)||!isFinite(e))return;return e}(n),s="number"==typeof a;return{parsedValue:s?a:e,requestedType:r,usedDefault:!s,reason:s?"found-match":"invalid-number"}}return{parsedValue:n,requestedType:r,usedDefault:!1,reason:"found-match"}}var b={off:-1,error:0,warn:1,info:2,debug:3},E=function(){function t(t,e){this.level=t,this.decorator=e,this.level=t,this.decorator=e,this.dateFormatter=function(){var t={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:"short"};try{return new Intl.DateTimeFormat(void 0,n(n({},t),{fractionalSecondDigits:3}))}catch(e){return new Intl.DateTimeFormat(void 0,t)}}()}return t.prototype.debug=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.debug,"debug",t],e,!1))},t.prototype.info=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.info,"info",t],e,!1))},t.prototype.warn=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.warn,"warn",t],e,!1))},t.prototype.error=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.error,"error",t],e,!1))},t.prototype.log=function(t,e,n){for(var r,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];b[this.level]>=b[e]&&t.apply(void 0,i(["[".concat(this.dateFormatter.format(new Date),"] ").concat(null===(r=this.decorator)||void 0===r?void 0:r.decorateMessage(n))],o,!1))},t}(),C=function(){function t(){}return t.prototype.decorateMessage=function(t){return"[ConfigDirector:js-client-sdk] ".concat(t)},t}(),T=function(t,e){return new E(null!=t?t:"warn",null!=e?e:new C)},S=function(){function t(){}return t.prototype.aggregate=function(t){var e;if(0==t.events.length)return[];for(var n=new Map,r=0,o=t.events;r<o.length;r++){var i=o[r],a=JSON.stringify(i),s=(null===(e=n.get(a))||void 0===e?void 0:e.count)||0;n.set(a,{event:i,count:s+1})}return Array.from(n).map(function(e){var n=e[1];return{startTime:t.startTime,endTime:t.endTime,count:n.count,event:n.event}})},t}(),x=function(){function t(t){this._events=[],this._droppedEventCount=0,this.limit=null!=t?t:1e3}return Object.defineProperty(t.prototype,"events",{get:function(){return this._events},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reachedLimit",{get:function(){return this._events.length>=this.limit},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"droppedEventCount",{get:function(){return this._droppedEventCount},enumerable:!1,configurable:!0}),t.prototype.push=function(){for(var t,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.startTime||(this.startTime=new Date);var r=Math.max(0,e.length-this.limit),o=e.slice(r,e.length);if(this._droppedEventCount+=r,this._events.length+o.length>this.limit){var i=this._events.length+o.length-this.limit;this._events.splice(0,i),this._droppedEventCount+=i}return(t=this._events).push.apply(t,o)},t.prototype.takeSnapshot=function(){var t,e=new Date,n=null!==(t=this.startTime)&&void 0!==t?t:e,r=this._events.splice(0),o=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:n,endTime:e,events:r,droppedCount:o}},t.prototype.clear=function(){this._events=[],this.startTime=void 0,this._droppedEventCount=0},t}(),k=function(){function t(t){this.executeRequests=!0,this.sdkKey=t.sdkKey,this.logger=t.logger,this.url=new URL("telemetry/v1",t.baseUrl)}return t.prototype.report=function(t){var e=t.discreteEvents,n=t.aggregatedEvents,r=t.droppedEvents;if(!this.executeRequests)return{success:!1,fatalError:!0};var o={clientSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(o))return{success:!0,fatalError:!1};var i=this.sendReport(o);return i.fatalError&&(this.executeRequests=!1),i},t.prototype.isReportEmpty=function(t){return this.isEventListEmpty(t.discreteEvents)&&this.isEventListEmpty(t.aggregatedEvents)&&this.isDroppedEventsEmpty(t.droppedEvents)},t.prototype.isDroppedEventsEmpty=function(t){var e;if(!t)return!0;var n=Object.keys(t);if(0==n.length)return!0;for(var r=0,o=n;r<o.length;r++){if((null!==(e=t[o[r]])&&void 0!==e?e:0)>0)return!1}return!0},t.prototype.isEventListEmpty=function(t){var e,n,r=Object.keys(t);if(0==r.length)return!0;for(var o=0,i=r;o<i.length;o++){if((null!==(n=null===(e=t[i[o]])||void 0===e?void 0:e.length)&&void 0!==n?n:0)>0)return!1}return!0},t.prototype.sendReport=function(t){try{return{success:navigator.sendBeacon(this.url,JSON.stringify(t)),fatalError:!1}}catch(t){return this.logger.warn("[EventReporter] Fatal error attempting to send telemetry data: ".concat(t,". No more telemetry data will be sent.")),{success:!1,fatalError:!0}}},t}(),D=function(t){for(var e=5381,n=0;n<t.length;n++)e=(e<<5)+e+t[n],e>>>=0;return e},R=function(){function t(t){var e=this;this.evaluationEventQueue=new x,this.aggregator=new S,this.collectEvents=!0,this.logger=t.logger,this.reporter=new k(t),this.flushIntervalDelay=3e4;this.flushTimeout=setTimeout(function(){return e.flushAndScheduleNext()},5e3);try{document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.flush()})}catch(t){this.logger.warn("[TelemetryEventCollector] Could not configure 'visibilitychange' listener: ",t)}}return t.prototype.evaluatedConfig=function(t){this.collectEvents&&this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))},t.prototype.sanitizeEvaluatedConfigEvent=function(t){return{key:t.key,type:t.type,defaultValue:this.sanitizeValue(t.defaultValue,t.type),requestedType:t.requestedType,evaluatedValue:this.sanitizeValue(t.evaluatedValue,t.type),usedDefault:t.usedDefault,evaluationReason:t.evaluationReason}},t.prototype.sanitizeValue=function(t,e){if("json"===e)try{var n=JSON.stringify(t);return r=n,D((new TextEncoder).encode(r)).toString(16).padStart(8,"0")}catch(e){return t.toString().slice(0,500)}var r;return t.toString().slice(0,500)},t.prototype.flushAndScheduleNext=function(){var t=this;this.flush().fatalError?(this.collectEvents=!1,this.close(),this.logger.warn("[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.")):this.flushTimeout=setTimeout(function(){return t.flushAndScheduleNext()},this.flushIntervalDelay)},t.prototype.flush=function(){var t=this.evaluationEventQueue.takeSnapshot();return this.reporter.report({discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(t)},droppedEvents:{evaluatedConfig:t.droppedCount}})},t.prototype.close=function(){this.collectEvents=!1,clearTimeout(this.flushTimeout),this.flush(),this.evaluationEventQueue.clear()},t.prototype.dispose=function(){this.close()},t}(),O=function(t,e,i,a){return r(void 0,void 0,void 0,function(){var r,s,u,c;return o(this,function(o){switch(o.label){case 0:r=new AbortController,s=setTimeout(function(){a.debug("[fetchWithTimeout] Reached timeout, aborting request"),r.abort()},t),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,fetch(e,n(n({},i),{signal:r.signal}))];case 2:return u=o.sent(),clearTimeout(s),[2,u];case 3:throw c=o.sent(),a.warn("[fetchWithTimeout] Fetch error: ",c),clearTimeout(s),c;case 4:return[2]}})})},V=function(){function t(t){this.options=t,this.eventEmitter=new a,this.fatalError=!1,this.options=t,this.logger=t.logger,this.url=new URL("pull/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return r(this,void 0,void 0,function(){var n,r,i,a,s,u,c;return o(this,function(o){switch(o.label){case 0:if(this.fatalError)return this.logger.warn("[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect."),[2,this];o.label=1;case 1:return o.trys.push([1,7,,8]),[4,O(e,this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey})},this.logger)];case 2:return(n=o.sent()).ok?[3,5]:this.isStatusFatal(n.status)?(this.fatalError=!0,r=this.prepareFatalResponseStatusError,i=[n.status],[4,n.text()]):[3,4];case 3:throw r.apply(this,i.concat([o.sent()]));case 4:throw new v("Connection failed with status: ".concat(n.status),n.status);case 5:return u=(s=JSON).parse,[4,n.text()];case 6:return a=u.apply(s,[o.sent()]),this.eventEmitter.emit("configSetReceived",a),[2,this];case 7:throw function(t){if(t instanceof DOMException){if("NotAllowedError"===t.name)return!0}else if(t instanceof TypeError)return!0;return!1}(c=o.sent())?(this.fatalError=!0,new v("Connection failed with fatal error: ".concat(c,". This is an unrecoverable error, retry attempts will be ignored."))):c instanceof SyntaxError?new v("Failed to parse the response from the server: ".concat(c)):new v("Connection failed with error: ".concat(c,"."));case 8:return[2]}})})},t.prototype.prepareFatalResponseStatusError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, retry attempts will be ignored.");return new v(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){},t.prototype.dispose=function(){this.close(),this.clear()},t}(),M=new URL("https://client-sdk-api.configdirector.com"),P=function(){function t(t,e){var r,o,i,s,u,c,l=this;this.handlersMap=new Map,this.eventEmitter=new a,this.ready=!1,this.logger=null!==(r=null==e?void 0:e.logger)&&void 0!==r?r:T(),this.timeout=null!==(i=null===(o=null==e?void 0:e.connection)||void 0===o?void 0:o.timeout)&&void 0!==i?i:3e3;var f=null!==(u=this.parseUrl(null===(s=null==e?void 0:e.connection)||void 0===s?void 0:s.url))&&void 0!==u?u:M;this.streaming=!1!==(null===(c=null==e?void 0:e.connection)||void 0===c?void 0:c.streaming);var d=this.streaming?y:V;this.usageEventCollector=new R({sdkKey:t,logger:this.logger,baseUrl:f}),this.transport=new d({clientSdkKey:t,baseUrl:f,metaContext:n(n({},null==e?void 0:e.metadata),{sdkVersion:"0.1.0",userAgent:null===navigator||void 0===navigator?void 0:navigator.userAgent}),logger:this.logger}),this.transport.on("configSetReceived",function(t){var e;null===(e=l.readyResolve)||void 0===e||e.call(l);var r=Object.keys(t.configs);l.configSet&&"full"!=t.kind?(l.configSet.configs=n(n({},l.configSet.configs),t.configs),l.eventEmitter.emit("configsUpdated",{keys:r}),l.updateWatchers(t.configs)):(l.configSet=t,l.eventEmitter.emit("configsUpdated",{keys:r}),l.updateWatchers(t.configs)),l.logger.debug("[ConfigDirectorClient] ConfigSet updated from server:",{keys:r})})}return t.prototype.initialize=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"initialization")];case 1:return e.sent(),[2]}})})},t.prototype.updateContext=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"context update")];case 1:return e.sent(),[2]}})})},t.prototype.connectToTransport=function(t,e){return r(this,void 0,void 0,function(){var n,r,i,a,s,u=this;return o(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),this.ready=!1,this.readyPromise=new Promise(function(t){u.readyResolve=t}).then(function(){u.ready=!0,u.eventEmitter.emit("clientReady",{action:e}),u.logger.debug("[ConfigDirectorClient] Received initial payload from the server, client is ready")}),n=(new Date).getTime(),[4,this.transport.connect(null!=t?t:{},this.timeout)];case 1:return o.sent(),this.currentContext=t,r=(new Date).getTime()-n,(i=this.timeout-r)>0?[4,Promise.race([this.readyPromise,new Promise(function(t){setTimeout(function(){return t()},i)})])]:[3,3];case 2:o.sent(),o.label=3;case 3:return this.ready||(a=this.streaming?"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.":"Since the client was configured without streaming, configs may not update and always return the default value.",this.logger.warn("[ConfigDirectorClient] Timed out waiting for ".concat(e," after ").concat(this.timeout,"ms. ").concat(a))),[3,5];case 4:return s=o.sent(),this.logger.error("[ConfigDirectorClient] An error occurred during ".concat(e,": "),s),[3,5];case 5:return[2]}})})},t.prototype.updateWatchers=function(t){var e=this;Object.values(t).forEach(function(t){return e.updateWatchersForConfig(t)})},t.prototype.updateWatchersForConfig=function(t){var e,n=this;null===(e=this.handlersMap.get(t.key))||void 0===e||e.forEach(function(e){var r=n.getValueFromConfigState(t.key,t,e.defaultValue);e.handler(r)})},t.prototype.watch=function(t,e,n){var r=this;this.validateDefaultValue(e);var o=this.handlersMap.get(t),i={handler:n,defaultValue:e,requestedType:typeof e};return o?o.push(i):this.handlersMap.set(t,[i]),function(){return r.unwatch(t,n)}},t.prototype.unwatch=function(t,e){var n=this.handlersMap.get(t);if(n)if(e){var r=n.findIndex(function(t){return t.handler==e});r>=0&&(null==n||n.splice(r,1))}else n.splice(0)},t.prototype.getValue=function(t,e){var n;this.validateDefaultValue(e);var r=null===(n=this.configSet)||void 0===n?void 0:n.configs[t];return this.getValueFromConfigState(t,r,e)},t.prototype.getValueFromConfigState=function(t,e,n){var r,o;if(!e)return this.logger.debug("[ConfigDirectorClient] No config state found for '".concat(t,"', returning default value '").concat(n,"'")),this.usageEventCollector.evaluatedConfig({contextId:null===(r=this.currentContext)||void 0===r?void 0:r.id,key:t,defaultValue:n,requestedType:m(n),evaluatedValue:n,usedDefault:!0,evaluationReason:"config-state-missing"}),n;var i=w(e,n);return this.usageEventCollector.evaluatedConfig({contextId:null===(o=this.currentContext)||void 0===o?void 0:o.id,key:t,defaultValue:n,requestedType:i.requestedType,evaluatedValue:i.parsedValue,usedDefault:i.usedDefault,evaluationReason:i.reason}),this.logger.debug("[ConfigDirectorClient] Evaluated '".concat(t,"' to '").concat(i.parsedValue,"'")),i.parsedValue},t.prototype.parseUrl=function(t){if(t)try{return new URL(t)}catch(e){throw new g("Invalid base URL '".concat(t,"'. Parsing failed: ").concat(e))}},t.prototype.validateDefaultValue=function(t){if(null==t)throw new g("Invalid default value. The default value for a config must be defined and non-null.");if("function"==typeof t)throw new g("Invalid default value. The default value for a config cannot be a function.")},Object.defineProperty(t.prototype,"isReady",{get:function(){return this.ready},enumerable:!1,configurable:!0}),t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.logger.debug("[ConfigDirectorClient] clear() has been called, removing all observers"),this.eventEmitter.clear(),this.handlersMap.clear()},t.prototype.unwatchAll=function(){this.handlersMap.clear()},t.prototype.close=function(){this.logger.debug("[ConfigDirectorClient] close() has been called, closing connection to server"),this.transport.close(),this.ready=!1},t.prototype.dispose=function(){this.clear(),this.close()},t}(),F=function(t,e){return new P(t,e)},I=function(t,e){return T(t,e)};export{F as createClient,I as createConsoleLogger};
1
+ var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};function e(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n=function(){return n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},n.apply(this,arguments)};function r(t,e,n,r){return new(n||(n=Promise))(function(e,o){function i(t){try{s(r.next(t))}catch(t){o(t)}}function a(t){try{s(r.throw(t))}catch(t){o(t)}}function s(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(t){t(r)})).then(i,a)}s((r=r.apply(t,[])).next())})}function o(t,e){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(u){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=e.call(t,i)}catch(t){s=[6,t],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}}function i(t,e,n){if(2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var a=function(){function t(){this.handlerMap=new Map}return t.prototype.on=function(t,e){var n=this.handlerMap.get(t);n?n.push(e):this.handlerMap.set(t,[e])},t.prototype.once=function(t,e){var n=this;this.on(t,function r(o){n.off(t,r),e.apply(n,o)})},t.prototype.off=function(t,e){var n=this.handlerMap.get(t);if(n)if(e){var r=n.indexOf(e);r>=0&&n.splice(r,1)}else this.handlerMap.set(t,[])},t.prototype.clear=function(){this.handlerMap.clear()},t.prototype.emit=function(t,e){var n=this.handlerMap.get(t);n&&n.slice().map(function(t){return t(e)})},t}();class s extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}}function u(t){}function c(t){if("function"==typeof t)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=u,onError:n=u,onRetry:r=u,onComment:o}=t;let i,a="",c=!0,l="",f="";function d(t){if(""===t)return l.length>0&&e({id:i,event:f||void 0,data:l.endsWith("\n")?l.slice(0,-1):l}),i=void 0,l="",void(f="");if(t.startsWith(":"))return void(o&&o(t.slice(t.startsWith(": ")?2:1)));const n=t.indexOf(":");if(-1!==n){const e=t.slice(0,n),r=" "===t[n+1]?2:1;return void p(e,t.slice(n+r),t)}p(t,"",t)}function p(t,e,o){switch(t){case"event":f=e;break;case"data":l=`${l}${e}\n`;break;case"id":i=e.includes("\0")?void 0:e;break;case"retry":/^\d+$/.test(e)?r(parseInt(e,10)):n(new s(`Invalid \`retry\` value: "${e}"`,{type:"invalid-retry",value:e,line:o}));break;default:n(new s(`Unknown field "${t.length>20?`${t.slice(0,20)}…`:t}"`,{type:"unknown-field",field:t,value:e,line:o}))}}return{feed:function(t){const e=c?t.replace(/^\xEF\xBB\xBF/,""):t,[n,r]=function(t){const e=[];let n="",r=0;for(;r<t.length;){const o=t.indexOf("\r",r),i=t.indexOf("\n",r);let a=-1;if(-1!==o&&-1!==i?a=Math.min(o,i):-1!==o?a=o===t.length-1?-1:o:-1!==i&&(a=i),-1===a){n=t.slice(r);break}{const n=t.slice(r,a);e.push(n),r=a+1,"\r"===t[r-1]&&"\n"===t[r]&&r++}}return[e,n]}(`${a}${e}`);for(const t of n)d(t);a=r,c=!1},reset:function(t={}){a&&t.consume&&d(a),c=!0,i=void 0,l="",f="",a=""}}}const l="connecting",f="closed",d=()=>{};function p(t,{getStream:e}){const n="string"==typeof t||t instanceof URL?{url:t}:t,{onMessage:r,onComment:o=d,onConnect:i=d,onDisconnect:a=d,onScheduleReconnect:s=d}=n,{fetch:u,url:p,initialLastEventId:h}=function(t){const e=t.fetch||globalThis.fetch;if(!function(t){return"function"==typeof t}(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if("function"!=typeof AbortController)throw new Error("Missing AbortController implementation");const{url:n,initialLastEventId:r}=t;if("string"!=typeof n&&!(n instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if("string"!=typeof r&&void 0!==r)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:n,initialLastEventId:r}}(n),v={...n.headers},g=[],y=r?[r]:[],m=c({onEvent:function(t){var e;"string"==typeof t.id&&(T=t.id),e=t,y.forEach(t=>t(e))},onRetry:function(t){S=t},onComment:o});let w,b,E=p.toString(),C=new AbortController,T=h,S=2e3,k=f;return x(),{close:D,connect:x,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:function(){const t=[],e=[],n=function(n){const r=t.shift();r?r({value:n,done:!1}):e.push(n)};function r(){for(y.splice(y.indexOf(n),1);t.shift(););for(;e.shift(););}return g.push(function(){const e=t.shift();e&&(e({done:!0,value:void 0}),r())}),y.push(n),{next(){return k===f?this.return():new Promise(n=>{const r=e.shift();r?n({value:r,done:!1}):t.push(n)})},return:()=>(r(),Promise.resolve({done:!0,value:void 0})),throw:t=>(r(),Promise.reject(t)),[Symbol.asyncIterator](){return this}}},get lastEventId(){return T},get url(){return E},get readyState(){return k}};function x(){w||(k=l,C=new AbortController,w=u(p,function(){const{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s}=n;return{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s,headers:{Accept:"text/event-stream",...v,...T?{"Last-Event-ID":T}:void 0},cache:"no-store",signal:C.signal}}()).then(O).catch(t=>{w=null,"AbortError"!==t.name&&"aborted"!==t.type&&!C.signal.aborted&&R()}))}function D(){k=f,C.abort(),m.reset(),clearTimeout(b),g.forEach(t=>t())}function R(){s({delay:S}),!C.signal.aborted&&(k=l,b=setTimeout(x,S))}async function O(t){i(),m.reset();const{body:n,redirected:r,status:o}=t;if(204===o)return a(),void D();if(!n)throw new Error("Missing response body");r&&(E=t.url);const s=e(n),u=new TextDecoder,c=s.getReader();let l=!0;k="open";do{const{done:t,value:e}=await c.read();e&&m.feed(u.decode(e,{stream:!t})),t&&(l=!1,w=null,m.reset(),R(),a())}while(l)}}const h={getStream:function(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}};var v=function(t){function n(e,r){var o=t.call(this,e)||this;return o.name="ConfigDirectorConnectionError",o.status=r,Object.setPrototypeOf(o,n.prototype),o}return e(n,t),n}(Error),g=function(t){function n(e){var r=t.call(this,e)||this;return r.name="ConfigDirectorValidationError",Object.setPrototypeOf(r,n.prototype),r}return e(n,t),n}(Error),y=function(){function t(t){this.options=t,this.eventEmitter=new a,this.options=t,this.logger=t.logger,this.url=new URL("sse/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return r(this,0,void 0,function(){var n,i,a,s,u=this;return o(this,function(c){return this.eventSource&&this.close(),n=void 0,i=void 0,a=function(t,e){return r(u,0,void 0,function(){var r;return o(this,function(o){switch(o.label){case 0:return[4,fetch(t,e)];case 1:return r=o.sent(),n=r.status,r.ok?[3,3]:[4,r.text()];case 2:i=o.sent(),o.label=3;case 3:return[2,r]}})})},s=new Promise(function(e,r){var o;u.eventSource=(o={url:u.url,fetch:a,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:u.options.metaContext,clientSdkKey:u.options.clientSdkKey}),onMessage:function(t){var e=t.data;u.dispatchMessage(e)},onConnect:function(){n&&u.isStatusFatal(n)?(u.close(),r(u.prepareFatalError(n,i))):(u.logger.debug("[EventSourceTransport] Connected, status: %s",n),e(u))},onScheduleReconnect:function(t){n&&u.isStatusFatal(n)?(u.close(),r(u.prepareFatalError(n,i))):u.logger.warn("[EventSourceTransport] Scheduling reconnect in ".concat(t.delay,". Response status: ").concat(n))},onDisconnect:function(){u.logger.debug("[EventSourceTransport] Disconnected")}},p(o,h))}),[2,Promise.race([s,new Promise(function(t){setTimeout(function(){return t(u)},e)})])]})})},t.prototype.dispatchMessage=function(t){try{var e=JSON.parse(t);this.eventEmitter.emit("configSetReceived",e)}catch(t){this.logger.error("[EventSourceTransport] Error parsing and dispatching config data update: ",t)}},t.prototype.prepareFatalError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, will not attempt to reconnect.");return new v(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){var t;null===(t=this.eventSource)||void 0===t||t.close()},t.prototype.dispose=function(){this.close(),this.clear()},t}(),m=function(t){var e,n,r=typeof t;if("object"===r)try{return null!==(n=null===(e=t.constructor)||void 0===e?void 0:e.name)&&void 0!==n?n:r}catch(t){return r}else if("function"===r)try{var o=t.name;return o?"function: ".concat(o):r}catch(t){return r}return r},w=function(t){return"number"===t||"bigint"===t},b=function(t){if(t){var e=Number.parseInt(t);if(!isNaN(e)&&isFinite(e))return e}},E=function(t){if(t){var e=Number.parseFloat(t);if(!isNaN(e)&&isFinite(e))return e}},C={off:-1,error:0,warn:1,info:2,debug:3},T=function(){function t(t,e){this.level=t,this.decorator=e,this.level=t,this.decorator=e,this.dateFormatter=function(){var t={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:"short"};try{return new Intl.DateTimeFormat(void 0,n(n({},t),{fractionalSecondDigits:3}))}catch(e){return new Intl.DateTimeFormat(void 0,t)}}()}return t.prototype.debug=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.debug,"debug",t],e,!1))},t.prototype.info=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.info,"info",t],e,!1))},t.prototype.warn=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.warn,"warn",t],e,!1))},t.prototype.error=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.error,"error",t],e,!1))},t.prototype.log=function(t,e,n){for(var r,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];C[this.level]>=C[e]&&t.apply(void 0,i(["[".concat(this.dateFormatter.format(new Date),"] ").concat(null===(r=this.decorator)||void 0===r?void 0:r.decorateMessage(n))],o,!1))},t}(),S=function(){function t(){}return t.prototype.decorateMessage=function(t){return"[ConfigDirector:js-client-sdk] ".concat(t)},t}(),k=function(t,e){return new T(null!=t?t:"warn",null!=e?e:new S)},x=function(){function t(){}return t.prototype.aggregate=function(t){var e;if(0==t.events.length)return[];for(var n=new Map,r=0,o=t.events;r<o.length;r++){var i=o[r],a=JSON.stringify(i),s=(null===(e=n.get(a))||void 0===e?void 0:e.count)||0;n.set(a,{event:i,count:s+1})}return Array.from(n).map(function(e){var n=e[1];return{startTime:t.startTime,endTime:t.endTime,count:n.count,event:n.event}})},t}(),D=function(){function t(t){this._events=[],this._droppedEventCount=0,this.limit=null!=t?t:1e3}return Object.defineProperty(t.prototype,"events",{get:function(){return this._events},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reachedLimit",{get:function(){return this._events.length>=this.limit},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"droppedEventCount",{get:function(){return this._droppedEventCount},enumerable:!1,configurable:!0}),t.prototype.push=function(){for(var t,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.startTime||(this.startTime=new Date);var r=Math.max(0,e.length-this.limit),o=e.slice(r,e.length);if(this._droppedEventCount+=r,this._events.length+o.length>this.limit){var i=this._events.length+o.length-this.limit;this._events.splice(0,i),this._droppedEventCount+=i}return(t=this._events).push.apply(t,o)},t.prototype.takeSnapshot=function(){var t,e=new Date,n=null!==(t=this.startTime)&&void 0!==t?t:e,r=this._events.splice(0),o=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:n,endTime:e,events:r,droppedCount:o}},t.prototype.clear=function(){this._events=[],this.startTime=void 0,this._droppedEventCount=0},t}(),R=function(){function t(t){this.executeRequests=!0,this.sdkKey=t.sdkKey,this.logger=t.logger,this.url=new URL("telemetry/v1",t.baseUrl)}return t.prototype.report=function(t){var e=t.discreteEvents,n=t.aggregatedEvents,r=t.droppedEvents;if(!this.executeRequests)return{success:!1,fatalError:!0};var o={clientSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(o))return{success:!0,fatalError:!1};var i=this.sendReport(o);return i.fatalError&&(this.executeRequests=!1),i},t.prototype.isReportEmpty=function(t){return this.isEventListEmpty(t.discreteEvents)&&this.isEventListEmpty(t.aggregatedEvents)&&this.isDroppedEventsEmpty(t.droppedEvents)},t.prototype.isDroppedEventsEmpty=function(t){var e;if(!t)return!0;var n=Object.keys(t);if(0==n.length)return!0;for(var r=0,o=n;r<o.length;r++)if((null!==(e=t[o[r]])&&void 0!==e?e:0)>0)return!1;return!0},t.prototype.isEventListEmpty=function(t){var e,n,r=Object.keys(t);if(0==r.length)return!0;for(var o=0,i=r;o<i.length;o++)if((null!==(n=null===(e=t[i[o]])||void 0===e?void 0:e.length)&&void 0!==n?n:0)>0)return!1;return!0},t.prototype.sendReport=function(t){try{return{success:navigator.sendBeacon(this.url,JSON.stringify(t)),fatalError:!1}}catch(t){return this.logger.warn("[EventReporter] Fatal error attempting to send telemetry data: ".concat(t,". No more telemetry data will be sent.")),{success:!1,fatalError:!0}}},t}(),O=function(){function t(t){var e=this;this.evaluationEventQueue=new D,this.aggregator=new x,this.collectEvents=!0,this.logger=t.logger,this.reporter=new R(t),this.flushIntervalDelay=3e4,this.flushTimeout=setTimeout(function(){return e.flushAndScheduleNext()},5e3);try{document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.flush()})}catch(t){this.logger.warn("[TelemetryEventCollector] Could not configure 'visibilitychange' listener: ",t)}}return t.prototype.evaluatedConfig=function(t){this.collectEvents&&this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))},t.prototype.sanitizeEvaluatedConfigEvent=function(t){return{key:t.key,type:t.type,defaultValue:this.sanitizeValue(t.defaultValue,t.type),requestedType:t.requestedType,evaluatedValue:this.sanitizeValue(t.evaluatedValue,t.type),usedDefault:t.usedDefault,evaluationReason:t.evaluationReason}},t.prototype.sanitizeValue=function(t,e){if("json"===e)try{return n=JSON.stringify(t),function(t){for(var e=5381,n=0;n<t.length;n++)e=(e<<5)+e+t[n],e>>>=0;return e}((new TextEncoder).encode(n)).toString(16).padStart(8,"0")}catch(e){return t.toString().slice(0,500)}var n;return t.toString().slice(0,500)},t.prototype.flushAndScheduleNext=function(){var t=this;this.flush().fatalError?(this.collectEvents=!1,this.close(),this.logger.warn("[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.")):this.flushTimeout=setTimeout(function(){return t.flushAndScheduleNext()},this.flushIntervalDelay)},t.prototype.flush=function(){var t=this.evaluationEventQueue.takeSnapshot();return this.reporter.report({discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(t)},droppedEvents:{evaluatedConfig:t.droppedCount}})},t.prototype.close=function(){this.collectEvents=!1,clearTimeout(this.flushTimeout),this.flush(),this.evaluationEventQueue.clear()},t.prototype.dispose=function(){this.close()},t}(),V=function(t,e,i,a){return r(void 0,0,void 0,function(){var r,s,u,c;return o(this,function(o){switch(o.label){case 0:r=new AbortController,s=setTimeout(function(){a.debug("[fetchWithTimeout] Reached timeout, aborting request"),r.abort()},t),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,fetch(e,n(n({},i),{signal:r.signal}))];case 2:return u=o.sent(),clearTimeout(s),[2,u];case 3:throw c=o.sent(),a.warn("[fetchWithTimeout] Fetch error: ",c),clearTimeout(s),c;case 4:return[2]}})})},M=function(){function t(t){this.options=t,this.eventEmitter=new a,this.fatalError=!1,this.options=t,this.logger=t.logger,this.url=new URL("pull/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return r(this,0,void 0,function(){var n,r,i,a,s,u,c;return o(this,function(o){switch(o.label){case 0:if(this.fatalError)return this.logger.warn("[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect."),[2,this];o.label=1;case 1:return o.trys.push([1,7,,8]),[4,V(e,this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey})},this.logger)];case 2:return(n=o.sent()).ok?[3,5]:this.isStatusFatal(n.status)?(this.fatalError=!0,r=this.prepareFatalResponseStatusError,i=[n.status],[4,n.text()]):[3,4];case 3:throw r.apply(this,i.concat([o.sent()]));case 4:throw new v("Connection failed with status: ".concat(n.status),n.status);case 5:return u=(s=JSON).parse,[4,n.text()];case 6:return a=u.apply(s,[o.sent()]),this.eventEmitter.emit("configSetReceived",a),[2,this];case 7:throw function(t){if(t instanceof DOMException){if("NotAllowedError"===t.name)return!0}else if(t instanceof TypeError)return!0;return!1}(c=o.sent())?(this.fatalError=!0,new v("Connection failed with fatal error: ".concat(c,". This is an unrecoverable error, retry attempts will be ignored."))):c instanceof SyntaxError?new v("Failed to parse the response from the server: ".concat(c)):new v("Connection failed with error: ".concat(c,"."));case 8:return[2]}})})},t.prototype.prepareFatalResponseStatusError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, retry attempts will be ignored.");return new v(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){},t.prototype.dispose=function(){this.close(),this.clear()},t}(),P=new URL("https://client-sdk-api.configdirector.com"),F=function(){function t(t,e,r){var o,i,s,u,c,l,f=this;this.handlersMap=new Map,this.eventEmitter=new a,this.ready=!1,this.logger=null!==(o=null==r?void 0:r.logger)&&void 0!==o?o:k(),this.timeout=null!==(s=null===(i=null==r?void 0:r.connection)||void 0===i?void 0:i.timeout)&&void 0!==s?s:3e3;var d=null!==(c=this.parseUrl(null===(u=null==r?void 0:r.connection)||void 0===u?void 0:u.url))&&void 0!==c?c:P;this.streaming=!1!==(null===(l=null==r?void 0:r.connection)||void 0===l?void 0:l.streaming);var p=this.streaming?y:M;this.usageEventCollector=new O({sdkKey:t,logger:this.logger,baseUrl:d}),this.transport=new p({clientSdkKey:t,baseUrl:d,metaContext:n(n({},null==r?void 0:r.metadata),{sdkName:e.sdkName,sdkVersion:e.sdkVersion,userAgent:null===navigator||void 0===navigator?void 0:navigator.userAgent}),logger:this.logger}),this.transport.on("configSetReceived",function(t){var e;null===(e=f.readyResolve)||void 0===e||e.call(f);var r=Object.keys(t.configs);f.configSet&&"full"!=t.kind?(f.configSet.configs=n(n({},f.configSet.configs),t.configs),f.eventEmitter.emit("configsUpdated",{keys:r}),f.updateWatchers(t.configs)):(f.configSet=t,f.eventEmitter.emit("configsUpdated",{keys:r}),f.updateWatchers(t.configs)),f.logger.debug("[ConfigDirectorClient] ConfigSet updated from server:",{keys:r})})}return t.prototype.initialize=function(t){return r(this,0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"initialization")];case 1:return e.sent(),[2]}})})},t.prototype.updateContext=function(t){return r(this,0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"context update")];case 1:return e.sent(),[2]}})})},t.prototype.connectToTransport=function(t,e){return r(this,0,void 0,function(){var n,r,i,a,s,u=this;return o(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),this.ready=!1,this.readyPromise=new Promise(function(t){u.readyResolve=t}).then(function(){u.ready=!0,u.eventEmitter.emit("clientReady",{action:e}),u.logger.debug("[ConfigDirectorClient] Received initial payload from the server, client is ready")}),n=(new Date).getTime(),[4,this.transport.connect(null!=t?t:{},this.timeout)];case 1:return o.sent(),this.currentContext=t,r=(new Date).getTime()-n,(i=this.timeout-r)>0?[4,Promise.race([this.readyPromise,new Promise(function(t){setTimeout(function(){return t()},i)})])]:[3,3];case 2:o.sent(),o.label=3;case 3:return this.ready||(a=this.streaming?"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.":"Since the client was configured without streaming, configs may not update and always return the default value.",this.logger.warn("[ConfigDirectorClient] Timed out waiting for ".concat(e," after ").concat(this.timeout,"ms. ").concat(a))),[3,5];case 4:return s=o.sent(),this.logger.error("[ConfigDirectorClient] An error occurred during ".concat(e,": "),s),[3,5];case 5:return[2]}})})},t.prototype.updateWatchers=function(t){var e=this;Object.values(t).forEach(function(t){return e.updateWatchersForConfig(t)})},t.prototype.updateWatchersForConfig=function(t){var e,n=this;null===(e=this.handlersMap.get(t.key))||void 0===e||e.forEach(function(e){var r=n.getValueFromConfigState(t.key,t,e.defaultValue);e.handler(r)})},t.prototype.watch=function(t,e,n){var r=this;this.validateDefaultValue(e);var o=this.handlersMap.get(t),i={handler:n,defaultValue:e,requestedType:typeof e};return o?o.push(i):this.handlersMap.set(t,[i]),function(){return r.unwatch(t,n)}},t.prototype.unwatch=function(t,e){var n=this.handlersMap.get(t);if(n)if(e){var r=n.findIndex(function(t){return t.handler==e});r>=0&&(null==n||n.splice(r,1))}else n.splice(0)},t.prototype.getValue=function(t,e){var n;this.validateDefaultValue(e);var r=null===(n=this.configSet)||void 0===n?void 0:n.configs[t];return this.getValueFromConfigState(t,r,e)},t.prototype.getValueFromConfigState=function(t,e,n){var r,o;if(!e)return this.logger.debug("[ConfigDirectorClient] No config state found for '".concat(t,"', returning default value '").concat(n,"'")),this.usageEventCollector.evaluatedConfig({contextId:null===(r=this.currentContext)||void 0===r?void 0:r.id,key:t,defaultValue:n,requestedType:m(n),evaluatedValue:n,usedDefault:!0,evaluationReason:"config-state-missing"}),n;var i=function(t,e){var n,r,o=t.value,i=m(e);if(!o)return{parsedValue:e,requestedType:i,usedDefault:!0,reason:"value-missing"};if("string"==typeof e)return{parsedValue:o,requestedType:i,usedDefault:!1,reason:"found-match"};if("boolean"==typeof e&&"boolean"===t.type){var a=function(t){if(t){var e=t.toLowerCase();if("true"==e||"false"==e)return"true"===e}}(o),s="boolean"==typeof a;return{parsedValue:s?a:e,requestedType:i,usedDefault:!s,reason:s?"found-match":"invalid-boolean"}}return w(typeof e)&&"integer"===t.type?{parsedValue:(r="number"==typeof(n=b(o)))?n:e,requestedType:i,usedDefault:!r,reason:r?"found-match":"invalid-number"}:!w(typeof e)||"float"!==t.type&&"enum"!==t.type?{parsedValue:o,requestedType:i,usedDefault:!1,reason:"found-match"}:{parsedValue:(r="number"==typeof(n=E(o)))?n:e,requestedType:i,usedDefault:!r,reason:r?"found-match":"invalid-number"}}(e,n);return this.usageEventCollector.evaluatedConfig({contextId:null===(o=this.currentContext)||void 0===o?void 0:o.id,key:t,defaultValue:n,requestedType:i.requestedType,evaluatedValue:i.parsedValue,usedDefault:i.usedDefault,evaluationReason:i.reason}),this.logger.debug("[ConfigDirectorClient] Evaluated '".concat(t,"' to '").concat(i.parsedValue,"'")),i.parsedValue},t.prototype.parseUrl=function(t){if(t)try{return new URL(t)}catch(e){throw new g("Invalid base URL '".concat(t,"'. Parsing failed: ").concat(e))}},t.prototype.validateDefaultValue=function(t){if(null==t)throw new g("Invalid default value. The default value for a config must be defined and non-null.");if("function"==typeof t)throw new g("Invalid default value. The default value for a config cannot be a function.")},Object.defineProperty(t.prototype,"isReady",{get:function(){return this.ready},enumerable:!1,configurable:!0}),t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.logger.debug("[ConfigDirectorClient] clear() has been called, removing all observers"),this.eventEmitter.clear(),this.handlersMap.clear()},t.prototype.unwatchAll=function(){this.handlersMap.clear()},t.prototype.close=function(){this.logger.debug("[ConfigDirectorClient] close() has been called, closing connection to server"),this.transport.close(),this.ready=!1},t.prototype.dispose=function(){this.clear(),this.close()},t}(),I=function(t,e){return new F(t,{sdkName:"js-client-sdk",sdkVersion:"0.1.3"},e)},j=function(t,e){return k(t,e)};export{I as createClient,j as createConsoleLogger};
2
2
  //# sourceMappingURL=configdirector-client.es.js.map
@@ -1,2 +1,2 @@
1
- !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).ConfigDirectorClient={})}(this,function(t){"use strict";var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r=function(){return r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},r.apply(this,arguments)};function o(t,e,n,r){return new(n||(n=Promise))(function(o,i){function a(t){try{u(r.next(t))}catch(t){i(t)}}function s(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(a,s)}u((r=r.apply(t,e||[])).next())})}function i(t,e){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(u){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=e.call(t,i)}catch(t){s=[6,t],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}}function a(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var s=function(){function t(){this.handlerMap=new Map}return t.prototype.on=function(t,e){var n=this.handlerMap.get(t);n?n.push(e):this.handlerMap.set(t,[e])},t.prototype.once=function(t,e){var n=this;this.on(t,function r(o){n.off(t,r),e.apply(n,o)})},t.prototype.off=function(t,e){var n=this.handlerMap.get(t);if(n)if(e){var r=n.indexOf(e);r>=0&&n.splice(r,1)}else this.handlerMap.set(t,[])},t.prototype.clear=function(){this.handlerMap.clear()},t.prototype.emit=function(t,e){var n=this.handlerMap.get(t);n&&n.slice().map(function(t){return t(e)})},t}();class u extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}}function c(t){}function l(t){if("function"==typeof t)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=c,onError:n=c,onRetry:r=c,onComment:o}=t;let i,a="",s=!0,l="",f="";function d(t){if(""===t)return l.length>0&&e({id:i,event:f||void 0,data:l.endsWith("\n")?l.slice(0,-1):l}),i=void 0,l="",void(f="");if(t.startsWith(":"))return void(o&&o(t.slice(t.startsWith(": ")?2:1)));const n=t.indexOf(":");if(-1!==n){const e=t.slice(0,n),r=" "===t[n+1]?2:1;return void h(e,t.slice(n+r),t)}h(t,"",t)}function h(t,e,o){switch(t){case"event":f=e;break;case"data":l=`${l}${e}\n`;break;case"id":i=e.includes("\0")?void 0:e;break;case"retry":/^\d+$/.test(e)?r(parseInt(e,10)):n(new u(`Invalid \`retry\` value: "${e}"`,{type:"invalid-retry",value:e,line:o}));break;default:n(new u(`Unknown field "${t.length>20?`${t.slice(0,20)}…`:t}"`,{type:"unknown-field",field:t,value:e,line:o}))}}return{feed:function(t){const e=s?t.replace(/^\xEF\xBB\xBF/,""):t,[n,r]=function(t){const e=[];let n="",r=0;for(;r<t.length;){const o=t.indexOf("\r",r),i=t.indexOf("\n",r);let a=-1;if(-1!==o&&-1!==i?a=Math.min(o,i):-1!==o?a=o===t.length-1?-1:o:-1!==i&&(a=i),-1===a){n=t.slice(r);break}{const n=t.slice(r,a);e.push(n),r=a+1,"\r"===t[r-1]&&"\n"===t[r]&&r++}}return[e,n]}(`${a}${e}`);for(const t of n)d(t);a=r,s=!1},reset:function(t={}){a&&t.consume&&d(a),s=!0,i=void 0,l="",f="",a=""}}}const f="connecting",d="closed",h=()=>{};function p(t,{getStream:e}){const n="string"==typeof t||t instanceof URL?{url:t}:t,{onMessage:r,onComment:o=h,onConnect:i=h,onDisconnect:a=h,onScheduleReconnect:s=h}=n,{fetch:u,url:c,initialLastEventId:p}=function(t){const e=t.fetch||globalThis.fetch;if(!function(t){return"function"==typeof t}(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if("function"!=typeof AbortController)throw new Error("Missing AbortController implementation");const{url:n,initialLastEventId:r}=t;if("string"!=typeof n&&!(n instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if("string"!=typeof r&&void 0!==r)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:n,initialLastEventId:r}}(n),v={...n.headers},g=[],y=r?[r]:[],m=l({onEvent:function(t){"string"==typeof t.id&&(T=t.id),e=t,y.forEach(t=>t(e));var e},onRetry:function(t){S=t},onComment:o});let w,b,E=c.toString(),C=new AbortController,T=p,S=2e3,x=d;return k(),{close:D,connect:k,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:function(){const t=[],e=[];const n=function(n){const r=t.shift();r?r({value:n,done:!1}):e.push(n)};function r(){for(y.splice(y.indexOf(n),1);t.shift(););for(;e.shift(););}return g.push(function(){const e=t.shift();e&&(e({done:!0,value:void 0}),r())}),y.push(n),{next(){return x===d?this.return():new Promise(n=>{const r=e.shift();r?n({value:r,done:!1}):t.push(n)})},return:()=>(r(),Promise.resolve({done:!0,value:void 0})),throw:t=>(r(),Promise.reject(t)),[Symbol.asyncIterator](){return this}}},get lastEventId(){return T},get url(){return E},get readyState(){return x}};function k(){w||(x=f,C=new AbortController,w=u(c,function(){const{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s}=n,u={Accept:"text/event-stream",...v,...T?{"Last-Event-ID":T}:void 0};return{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s,headers:u,cache:"no-store",signal:C.signal}}()).then(O).catch(t=>{w=null,"AbortError"!==t.name&&"aborted"!==t.type&&!C.signal.aborted&&R()}))}function D(){x=d,C.abort(),m.reset(),clearTimeout(b),g.forEach(t=>t())}function R(){s({delay:S}),!C.signal.aborted&&(x=f,b=setTimeout(k,S))}async function O(t){i(),m.reset();const{body:n,redirected:r,status:o}=t;if(204===o)return a(),void D();if(!n)throw new Error("Missing response body");r&&(E=t.url);const s=e(n),u=new TextDecoder,c=s.getReader();let l=!0;x="open";do{const{done:t,value:e}=await c.read();e&&m.feed(u.decode(e,{stream:!t})),t&&(l=!1,w=null,m.reset(),R(),a())}while(l)}}const v={getStream:function(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}};var g=function(t){function e(n,r){var o=t.call(this,n)||this;return o.name="ConfigDirectorConnectionError",o.status=r,Object.setPrototypeOf(o,e.prototype),o}return n(e,t),e}(Error),y=function(t){function e(n){var r=t.call(this,n)||this;return r.name="ConfigDirectorValidationError",Object.setPrototypeOf(r,e.prototype),r}return n(e,t),e}(Error),m=function(){function t(t){this.options=t,this.eventEmitter=new s,this.options=t,this.logger=t.logger,this.url=new URL("sse/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return o(this,void 0,void 0,function(){var n,r,a,s,u=this;return i(this,function(c){return this.eventSource&&this.close(),n=void 0,r=void 0,a=function(t,e){return o(u,void 0,void 0,function(){var o;return i(this,function(i){switch(i.label){case 0:return[4,fetch(t,e)];case 1:return o=i.sent(),n=o.status,o.ok?[3,3]:[4,o.text()];case 2:r=i.sent(),i.label=3;case 3:return[2,o]}})})},s=new Promise(function(e,o){var i;u.eventSource=(i={url:u.url,fetch:a,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:u.options.metaContext,clientSdkKey:u.options.clientSdkKey}),onMessage:function(t){var e=t.data;u.dispatchMessage(e)},onConnect:function(){n&&u.isStatusFatal(n)?(u.close(),o(u.prepareFatalError(n,r))):(u.logger.debug("[EventSourceTransport] Connected, status: %s",n),e(u))},onScheduleReconnect:function(t){n&&u.isStatusFatal(n)?(u.close(),o(u.prepareFatalError(n,r))):u.logger.warn("[EventSourceTransport] Scheduling reconnect in ".concat(t.delay,". Response status: ").concat(n))},onDisconnect:function(){u.logger.debug("[EventSourceTransport] Disconnected")}},p(i,v))}),[2,Promise.race([s,new Promise(function(t){setTimeout(function(){return t(u)},e)})])]})})},t.prototype.dispatchMessage=function(t){try{var e=JSON.parse(t);this.eventEmitter.emit("configSetReceived",e)}catch(t){this.logger.error("[EventSourceTransport] Error parsing and dispatching config data update: ",t)}},t.prototype.prepareFatalError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, will not attempt to reconnect.");return new g(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){var t;null===(t=this.eventSource)||void 0===t||t.close()},t.prototype.dispose=function(){this.close(),this.clear()},t}(),w=function(t){var e,n,r=typeof t;if("object"===r)try{return null!==(n=null===(e=t.constructor)||void 0===e?void 0:e.name)&&void 0!==n?n:r}catch(t){return r}else if("function"===r)try{var o=t.name;return o?"function: ".concat(o):r}catch(t){return r}return r};function b(t,e){var n=t.value,r=w(e);if(!n)return{parsedValue:e,requestedType:r,usedDefault:!0,reason:"value-missing"};if("string"===r)return{parsedValue:n,requestedType:r,usedDefault:!1,reason:"found-match"};if("boolean"===r&&"boolean"===t.type){var o=function(t){if(!t)return;var e=t.toLowerCase();if("true"!=e&&"false"!=e)return;return"true"===e}(n),i="boolean"==typeof o;return{parsedValue:i?o:e,requestedType:r,usedDefault:!i,reason:i?"found-match":"invalid-boolean"}}if("number"===r&&"number"===t.type){var a=function(t){if(!t)return;var e=Number.parseFloat(t);if(isNaN(e)||!isFinite(e))return;return e}(n),s="number"==typeof a;return{parsedValue:s?a:e,requestedType:r,usedDefault:!s,reason:s?"found-match":"invalid-number"}}return{parsedValue:n,requestedType:r,usedDefault:!1,reason:"found-match"}}var E={off:-1,error:0,warn:1,info:2,debug:3},C=function(){function t(t,e){this.level=t,this.decorator=e,this.level=t,this.decorator=e,this.dateFormatter=function(){var t={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:"short"};try{return new Intl.DateTimeFormat(void 0,r(r({},t),{fractionalSecondDigits:3}))}catch(e){return new Intl.DateTimeFormat(void 0,t)}}()}return t.prototype.debug=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,a([console.debug,"debug",t],e,!1))},t.prototype.info=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,a([console.info,"info",t],e,!1))},t.prototype.warn=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,a([console.warn,"warn",t],e,!1))},t.prototype.error=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,a([console.error,"error",t],e,!1))},t.prototype.log=function(t,e,n){for(var r,o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];E[this.level]>=E[e]&&t.apply(void 0,a(["[".concat(this.dateFormatter.format(new Date),"] ").concat(null===(r=this.decorator)||void 0===r?void 0:r.decorateMessage(n))],o,!1))},t}(),T=function(){function t(){}return t.prototype.decorateMessage=function(t){return"[ConfigDirector:js-client-sdk] ".concat(t)},t}(),S=function(t,e){return new C(null!=t?t:"warn",null!=e?e:new T)},x=function(){function t(){}return t.prototype.aggregate=function(t){var e;if(0==t.events.length)return[];for(var n=new Map,r=0,o=t.events;r<o.length;r++){var i=o[r],a=JSON.stringify(i),s=(null===(e=n.get(a))||void 0===e?void 0:e.count)||0;n.set(a,{event:i,count:s+1})}return Array.from(n).map(function(e){var n=e[1];return{startTime:t.startTime,endTime:t.endTime,count:n.count,event:n.event}})},t}(),k=function(){function t(t){this._events=[],this._droppedEventCount=0,this.limit=null!=t?t:1e3}return Object.defineProperty(t.prototype,"events",{get:function(){return this._events},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reachedLimit",{get:function(){return this._events.length>=this.limit},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"droppedEventCount",{get:function(){return this._droppedEventCount},enumerable:!1,configurable:!0}),t.prototype.push=function(){for(var t,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.startTime||(this.startTime=new Date);var r=Math.max(0,e.length-this.limit),o=e.slice(r,e.length);if(this._droppedEventCount+=r,this._events.length+o.length>this.limit){var i=this._events.length+o.length-this.limit;this._events.splice(0,i),this._droppedEventCount+=i}return(t=this._events).push.apply(t,o)},t.prototype.takeSnapshot=function(){var t,e=new Date,n=null!==(t=this.startTime)&&void 0!==t?t:e,r=this._events.splice(0),o=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:n,endTime:e,events:r,droppedCount:o}},t.prototype.clear=function(){this._events=[],this.startTime=void 0,this._droppedEventCount=0},t}(),D=function(){function t(t){this.executeRequests=!0,this.sdkKey=t.sdkKey,this.logger=t.logger,this.url=new URL("telemetry/v1",t.baseUrl)}return t.prototype.report=function(t){var e=t.discreteEvents,n=t.aggregatedEvents,r=t.droppedEvents;if(!this.executeRequests)return{success:!1,fatalError:!0};var o={clientSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(o))return{success:!0,fatalError:!1};var i=this.sendReport(o);return i.fatalError&&(this.executeRequests=!1),i},t.prototype.isReportEmpty=function(t){return this.isEventListEmpty(t.discreteEvents)&&this.isEventListEmpty(t.aggregatedEvents)&&this.isDroppedEventsEmpty(t.droppedEvents)},t.prototype.isDroppedEventsEmpty=function(t){var e;if(!t)return!0;var n=Object.keys(t);if(0==n.length)return!0;for(var r=0,o=n;r<o.length;r++){if((null!==(e=t[o[r]])&&void 0!==e?e:0)>0)return!1}return!0},t.prototype.isEventListEmpty=function(t){var e,n,r=Object.keys(t);if(0==r.length)return!0;for(var o=0,i=r;o<i.length;o++){if((null!==(n=null===(e=t[i[o]])||void 0===e?void 0:e.length)&&void 0!==n?n:0)>0)return!1}return!0},t.prototype.sendReport=function(t){try{return{success:navigator.sendBeacon(this.url,JSON.stringify(t)),fatalError:!1}}catch(t){return this.logger.warn("[EventReporter] Fatal error attempting to send telemetry data: ".concat(t,". No more telemetry data will be sent.")),{success:!1,fatalError:!0}}},t}(),R=function(t){for(var e=5381,n=0;n<t.length;n++)e=(e<<5)+e+t[n],e>>>=0;return e},O=function(){function t(t){var e=this;this.evaluationEventQueue=new k,this.aggregator=new x,this.collectEvents=!0,this.logger=t.logger,this.reporter=new D(t),this.flushIntervalDelay=3e4;this.flushTimeout=setTimeout(function(){return e.flushAndScheduleNext()},5e3);try{document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.flush()})}catch(t){this.logger.warn("[TelemetryEventCollector] Could not configure 'visibilitychange' listener: ",t)}}return t.prototype.evaluatedConfig=function(t){this.collectEvents&&this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))},t.prototype.sanitizeEvaluatedConfigEvent=function(t){return{key:t.key,type:t.type,defaultValue:this.sanitizeValue(t.defaultValue,t.type),requestedType:t.requestedType,evaluatedValue:this.sanitizeValue(t.evaluatedValue,t.type),usedDefault:t.usedDefault,evaluationReason:t.evaluationReason}},t.prototype.sanitizeValue=function(t,e){if("json"===e)try{var n=JSON.stringify(t);return r=n,R((new TextEncoder).encode(r)).toString(16).padStart(8,"0")}catch(e){return t.toString().slice(0,500)}var r;return t.toString().slice(0,500)},t.prototype.flushAndScheduleNext=function(){var t=this;this.flush().fatalError?(this.collectEvents=!1,this.close(),this.logger.warn("[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.")):this.flushTimeout=setTimeout(function(){return t.flushAndScheduleNext()},this.flushIntervalDelay)},t.prototype.flush=function(){var t=this.evaluationEventQueue.takeSnapshot();return this.reporter.report({discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(t)},droppedEvents:{evaluatedConfig:t.droppedCount}})},t.prototype.close=function(){this.collectEvents=!1,clearTimeout(this.flushTimeout),this.flush(),this.evaluationEventQueue.clear()},t.prototype.dispose=function(){this.close()},t}(),V=function(t,e,n,a){return o(void 0,void 0,void 0,function(){var o,s,u,c;return i(this,function(i){switch(i.label){case 0:o=new AbortController,s=setTimeout(function(){a.debug("[fetchWithTimeout] Reached timeout, aborting request"),o.abort()},t),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,fetch(e,r(r({},n),{signal:o.signal}))];case 2:return u=i.sent(),clearTimeout(s),[2,u];case 3:throw c=i.sent(),a.warn("[fetchWithTimeout] Fetch error: ",c),clearTimeout(s),c;case 4:return[2]}})})},M=function(){function t(t){this.options=t,this.eventEmitter=new s,this.fatalError=!1,this.options=t,this.logger=t.logger,this.url=new URL("pull/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return o(this,void 0,void 0,function(){var n,r,o,a,s,u,c;return i(this,function(i){switch(i.label){case 0:if(this.fatalError)return this.logger.warn("[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect."),[2,this];i.label=1;case 1:return i.trys.push([1,7,,8]),[4,V(e,this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey})},this.logger)];case 2:return(n=i.sent()).ok?[3,5]:this.isStatusFatal(n.status)?(this.fatalError=!0,r=this.prepareFatalResponseStatusError,o=[n.status],[4,n.text()]):[3,4];case 3:throw r.apply(this,o.concat([i.sent()]));case 4:throw new g("Connection failed with status: ".concat(n.status),n.status);case 5:return u=(s=JSON).parse,[4,n.text()];case 6:return a=u.apply(s,[i.sent()]),this.eventEmitter.emit("configSetReceived",a),[2,this];case 7:throw function(t){if(t instanceof DOMException){if("NotAllowedError"===t.name)return!0}else if(t instanceof TypeError)return!0;return!1}(c=i.sent())?(this.fatalError=!0,new g("Connection failed with fatal error: ".concat(c,". This is an unrecoverable error, retry attempts will be ignored."))):c instanceof SyntaxError?new g("Failed to parse the response from the server: ".concat(c)):new g("Connection failed with error: ".concat(c,"."));case 8:return[2]}})})},t.prototype.prepareFatalResponseStatusError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, retry attempts will be ignored.");return new g(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){},t.prototype.dispose=function(){this.close(),this.clear()},t}(),P=new URL("https://client-sdk-api.configdirector.com"),j=function(){function t(t,e){var n,o,i,a,u,c,l=this;this.handlersMap=new Map,this.eventEmitter=new s,this.ready=!1,this.logger=null!==(n=null==e?void 0:e.logger)&&void 0!==n?n:S(),this.timeout=null!==(i=null===(o=null==e?void 0:e.connection)||void 0===o?void 0:o.timeout)&&void 0!==i?i:3e3;var f=null!==(u=this.parseUrl(null===(a=null==e?void 0:e.connection)||void 0===a?void 0:a.url))&&void 0!==u?u:P;this.streaming=!1!==(null===(c=null==e?void 0:e.connection)||void 0===c?void 0:c.streaming);var d=this.streaming?m:M;this.usageEventCollector=new O({sdkKey:t,logger:this.logger,baseUrl:f}),this.transport=new d({clientSdkKey:t,baseUrl:f,metaContext:r(r({},null==e?void 0:e.metadata),{sdkVersion:"0.1.0",userAgent:null===navigator||void 0===navigator?void 0:navigator.userAgent}),logger:this.logger}),this.transport.on("configSetReceived",function(t){var e;null===(e=l.readyResolve)||void 0===e||e.call(l);var n=Object.keys(t.configs);l.configSet&&"full"!=t.kind?(l.configSet.configs=r(r({},l.configSet.configs),t.configs),l.eventEmitter.emit("configsUpdated",{keys:n}),l.updateWatchers(t.configs)):(l.configSet=t,l.eventEmitter.emit("configsUpdated",{keys:n}),l.updateWatchers(t.configs)),l.logger.debug("[ConfigDirectorClient] ConfigSet updated from server:",{keys:n})})}return t.prototype.initialize=function(t){return o(this,void 0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"initialization")];case 1:return e.sent(),[2]}})})},t.prototype.updateContext=function(t){return o(this,void 0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"context update")];case 1:return e.sent(),[2]}})})},t.prototype.connectToTransport=function(t,e){return o(this,void 0,void 0,function(){var n,r,o,a,s,u=this;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,4,,5]),this.ready=!1,this.readyPromise=new Promise(function(t){u.readyResolve=t}).then(function(){u.ready=!0,u.eventEmitter.emit("clientReady",{action:e}),u.logger.debug("[ConfigDirectorClient] Received initial payload from the server, client is ready")}),n=(new Date).getTime(),[4,this.transport.connect(null!=t?t:{},this.timeout)];case 1:return i.sent(),this.currentContext=t,r=(new Date).getTime()-n,(o=this.timeout-r)>0?[4,Promise.race([this.readyPromise,new Promise(function(t){setTimeout(function(){return t()},o)})])]:[3,3];case 2:i.sent(),i.label=3;case 3:return this.ready||(a=this.streaming?"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.":"Since the client was configured without streaming, configs may not update and always return the default value.",this.logger.warn("[ConfigDirectorClient] Timed out waiting for ".concat(e," after ").concat(this.timeout,"ms. ").concat(a))),[3,5];case 4:return s=i.sent(),this.logger.error("[ConfigDirectorClient] An error occurred during ".concat(e,": "),s),[3,5];case 5:return[2]}})})},t.prototype.updateWatchers=function(t){var e=this;Object.values(t).forEach(function(t){return e.updateWatchersForConfig(t)})},t.prototype.updateWatchersForConfig=function(t){var e,n=this;null===(e=this.handlersMap.get(t.key))||void 0===e||e.forEach(function(e){var r=n.getValueFromConfigState(t.key,t,e.defaultValue);e.handler(r)})},t.prototype.watch=function(t,e,n){var r=this;this.validateDefaultValue(e);var o=this.handlersMap.get(t),i={handler:n,defaultValue:e,requestedType:typeof e};return o?o.push(i):this.handlersMap.set(t,[i]),function(){return r.unwatch(t,n)}},t.prototype.unwatch=function(t,e){var n=this.handlersMap.get(t);if(n)if(e){var r=n.findIndex(function(t){return t.handler==e});r>=0&&(null==n||n.splice(r,1))}else n.splice(0)},t.prototype.getValue=function(t,e){var n;this.validateDefaultValue(e);var r=null===(n=this.configSet)||void 0===n?void 0:n.configs[t];return this.getValueFromConfigState(t,r,e)},t.prototype.getValueFromConfigState=function(t,e,n){var r,o;if(!e)return this.logger.debug("[ConfigDirectorClient] No config state found for '".concat(t,"', returning default value '").concat(n,"'")),this.usageEventCollector.evaluatedConfig({contextId:null===(r=this.currentContext)||void 0===r?void 0:r.id,key:t,defaultValue:n,requestedType:w(n),evaluatedValue:n,usedDefault:!0,evaluationReason:"config-state-missing"}),n;var i=b(e,n);return this.usageEventCollector.evaluatedConfig({contextId:null===(o=this.currentContext)||void 0===o?void 0:o.id,key:t,defaultValue:n,requestedType:i.requestedType,evaluatedValue:i.parsedValue,usedDefault:i.usedDefault,evaluationReason:i.reason}),this.logger.debug("[ConfigDirectorClient] Evaluated '".concat(t,"' to '").concat(i.parsedValue,"'")),i.parsedValue},t.prototype.parseUrl=function(t){if(t)try{return new URL(t)}catch(e){throw new y("Invalid base URL '".concat(t,"'. Parsing failed: ").concat(e))}},t.prototype.validateDefaultValue=function(t){if(null==t)throw new y("Invalid default value. The default value for a config must be defined and non-null.");if("function"==typeof t)throw new y("Invalid default value. The default value for a config cannot be a function.")},Object.defineProperty(t.prototype,"isReady",{get:function(){return this.ready},enumerable:!1,configurable:!0}),t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.logger.debug("[ConfigDirectorClient] clear() has been called, removing all observers"),this.eventEmitter.clear(),this.handlersMap.clear()},t.prototype.unwatchAll=function(){this.handlersMap.clear()},t.prototype.close=function(){this.logger.debug("[ConfigDirectorClient] close() has been called, closing connection to server"),this.transport.close(),this.ready=!1},t.prototype.dispose=function(){this.clear(),this.close()},t}();t.createClient=function(t,e){return new j(t,e)},t.createConsoleLogger=function(t,e){return S(t,e)}});
1
+ !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).ConfigDirectorClient={})}(this,function(t){"use strict";var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r=function(){return r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},r.apply(this,arguments)};function o(t,e,n,r){return new(n||(n=Promise))(function(e,o){function i(t){try{s(r.next(t))}catch(t){o(t)}}function a(t){try{s(r.throw(t))}catch(t){o(t)}}function s(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(t){t(r)})).then(i,a)}s((r=r.apply(t,[])).next())})}function i(t,e){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(u){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=e.call(t,i)}catch(t){s=[6,t],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}}function a(t,e,n){if(2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var s=function(){function t(){this.handlerMap=new Map}return t.prototype.on=function(t,e){var n=this.handlerMap.get(t);n?n.push(e):this.handlerMap.set(t,[e])},t.prototype.once=function(t,e){var n=this;this.on(t,function r(o){n.off(t,r),e.apply(n,o)})},t.prototype.off=function(t,e){var n=this.handlerMap.get(t);if(n)if(e){var r=n.indexOf(e);r>=0&&n.splice(r,1)}else this.handlerMap.set(t,[])},t.prototype.clear=function(){this.handlerMap.clear()},t.prototype.emit=function(t,e){var n=this.handlerMap.get(t);n&&n.slice().map(function(t){return t(e)})},t}();class u extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}}function c(t){}function l(t){if("function"==typeof t)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=c,onError:n=c,onRetry:r=c,onComment:o}=t;let i,a="",s=!0,l="",f="";function d(t){if(""===t)return l.length>0&&e({id:i,event:f||void 0,data:l.endsWith("\n")?l.slice(0,-1):l}),i=void 0,l="",void(f="");if(t.startsWith(":"))return void(o&&o(t.slice(t.startsWith(": ")?2:1)));const n=t.indexOf(":");if(-1!==n){const e=t.slice(0,n),r=" "===t[n+1]?2:1;return void p(e,t.slice(n+r),t)}p(t,"",t)}function p(t,e,o){switch(t){case"event":f=e;break;case"data":l=`${l}${e}\n`;break;case"id":i=e.includes("\0")?void 0:e;break;case"retry":/^\d+$/.test(e)?r(parseInt(e,10)):n(new u(`Invalid \`retry\` value: "${e}"`,{type:"invalid-retry",value:e,line:o}));break;default:n(new u(`Unknown field "${t.length>20?`${t.slice(0,20)}…`:t}"`,{type:"unknown-field",field:t,value:e,line:o}))}}return{feed:function(t){const e=s?t.replace(/^\xEF\xBB\xBF/,""):t,[n,r]=function(t){const e=[];let n="",r=0;for(;r<t.length;){const o=t.indexOf("\r",r),i=t.indexOf("\n",r);let a=-1;if(-1!==o&&-1!==i?a=Math.min(o,i):-1!==o?a=o===t.length-1?-1:o:-1!==i&&(a=i),-1===a){n=t.slice(r);break}{const n=t.slice(r,a);e.push(n),r=a+1,"\r"===t[r-1]&&"\n"===t[r]&&r++}}return[e,n]}(`${a}${e}`);for(const t of n)d(t);a=r,s=!1},reset:function(t={}){a&&t.consume&&d(a),s=!0,i=void 0,l="",f="",a=""}}}const f="connecting",d="closed",p=()=>{};function h(t,{getStream:e}){const n="string"==typeof t||t instanceof URL?{url:t}:t,{onMessage:r,onComment:o=p,onConnect:i=p,onDisconnect:a=p,onScheduleReconnect:s=p}=n,{fetch:u,url:c,initialLastEventId:h}=function(t){const e=t.fetch||globalThis.fetch;if(!function(t){return"function"==typeof t}(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if("function"!=typeof AbortController)throw new Error("Missing AbortController implementation");const{url:n,initialLastEventId:r}=t;if("string"!=typeof n&&!(n instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if("string"!=typeof r&&void 0!==r)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:n,initialLastEventId:r}}(n),v={...n.headers},g=[],y=r?[r]:[],m=l({onEvent:function(t){var e;"string"==typeof t.id&&(T=t.id),e=t,y.forEach(t=>t(e))},onRetry:function(t){S=t},onComment:o});let w,b,E=c.toString(),C=new AbortController,T=h,S=2e3,k=d;return x(),{close:D,connect:x,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:function(){const t=[],e=[],n=function(n){const r=t.shift();r?r({value:n,done:!1}):e.push(n)};function r(){for(y.splice(y.indexOf(n),1);t.shift(););for(;e.shift(););}return g.push(function(){const e=t.shift();e&&(e({done:!0,value:void 0}),r())}),y.push(n),{next(){return k===d?this.return():new Promise(n=>{const r=e.shift();r?n({value:r,done:!1}):t.push(n)})},return:()=>(r(),Promise.resolve({done:!0,value:void 0})),throw:t=>(r(),Promise.reject(t)),[Symbol.asyncIterator](){return this}}},get lastEventId(){return T},get url(){return E},get readyState(){return k}};function x(){w||(k=f,C=new AbortController,w=u(c,function(){const{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s}=n;return{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s,headers:{Accept:"text/event-stream",...v,...T?{"Last-Event-ID":T}:void 0},cache:"no-store",signal:C.signal}}()).then(O).catch(t=>{w=null,"AbortError"!==t.name&&"aborted"!==t.type&&!C.signal.aborted&&R()}))}function D(){k=d,C.abort(),m.reset(),clearTimeout(b),g.forEach(t=>t())}function R(){s({delay:S}),!C.signal.aborted&&(k=f,b=setTimeout(x,S))}async function O(t){i(),m.reset();const{body:n,redirected:r,status:o}=t;if(204===o)return a(),void D();if(!n)throw new Error("Missing response body");r&&(E=t.url);const s=e(n),u=new TextDecoder,c=s.getReader();let l=!0;k="open";do{const{done:t,value:e}=await c.read();e&&m.feed(u.decode(e,{stream:!t})),t&&(l=!1,w=null,m.reset(),R(),a())}while(l)}}const v={getStream:function(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}};var g=function(t){function e(n,r){var o=t.call(this,n)||this;return o.name="ConfigDirectorConnectionError",o.status=r,Object.setPrototypeOf(o,e.prototype),o}return n(e,t),e}(Error),y=function(t){function e(n){var r=t.call(this,n)||this;return r.name="ConfigDirectorValidationError",Object.setPrototypeOf(r,e.prototype),r}return n(e,t),e}(Error),m=function(){function t(t){this.options=t,this.eventEmitter=new s,this.options=t,this.logger=t.logger,this.url=new URL("sse/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return o(this,0,void 0,function(){var n,r,a,s,u=this;return i(this,function(c){return this.eventSource&&this.close(),n=void 0,r=void 0,a=function(t,e){return o(u,0,void 0,function(){var o;return i(this,function(i){switch(i.label){case 0:return[4,fetch(t,e)];case 1:return o=i.sent(),n=o.status,o.ok?[3,3]:[4,o.text()];case 2:r=i.sent(),i.label=3;case 3:return[2,o]}})})},s=new Promise(function(e,o){var i;u.eventSource=(i={url:u.url,fetch:a,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:u.options.metaContext,clientSdkKey:u.options.clientSdkKey}),onMessage:function(t){var e=t.data;u.dispatchMessage(e)},onConnect:function(){n&&u.isStatusFatal(n)?(u.close(),o(u.prepareFatalError(n,r))):(u.logger.debug("[EventSourceTransport] Connected, status: %s",n),e(u))},onScheduleReconnect:function(t){n&&u.isStatusFatal(n)?(u.close(),o(u.prepareFatalError(n,r))):u.logger.warn("[EventSourceTransport] Scheduling reconnect in ".concat(t.delay,". Response status: ").concat(n))},onDisconnect:function(){u.logger.debug("[EventSourceTransport] Disconnected")}},h(i,v))}),[2,Promise.race([s,new Promise(function(t){setTimeout(function(){return t(u)},e)})])]})})},t.prototype.dispatchMessage=function(t){try{var e=JSON.parse(t);this.eventEmitter.emit("configSetReceived",e)}catch(t){this.logger.error("[EventSourceTransport] Error parsing and dispatching config data update: ",t)}},t.prototype.prepareFatalError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, will not attempt to reconnect.");return new g(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){var t;null===(t=this.eventSource)||void 0===t||t.close()},t.prototype.dispose=function(){this.close(),this.clear()},t}(),w=function(t){var e,n,r=typeof t;if("object"===r)try{return null!==(n=null===(e=t.constructor)||void 0===e?void 0:e.name)&&void 0!==n?n:r}catch(t){return r}else if("function"===r)try{var o=t.name;return o?"function: ".concat(o):r}catch(t){return r}return r},b=function(t){return"number"===t||"bigint"===t},E=function(t){if(t){var e=Number.parseInt(t);if(!isNaN(e)&&isFinite(e))return e}},C=function(t){if(t){var e=Number.parseFloat(t);if(!isNaN(e)&&isFinite(e))return e}},T={off:-1,error:0,warn:1,info:2,debug:3},S=function(){function t(t,e){this.level=t,this.decorator=e,this.level=t,this.decorator=e,this.dateFormatter=function(){var t={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:"short"};try{return new Intl.DateTimeFormat(void 0,r(r({},t),{fractionalSecondDigits:3}))}catch(e){return new Intl.DateTimeFormat(void 0,t)}}()}return t.prototype.debug=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,a([console.debug,"debug",t],e,!1))},t.prototype.info=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,a([console.info,"info",t],e,!1))},t.prototype.warn=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,a([console.warn,"warn",t],e,!1))},t.prototype.error=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,a([console.error,"error",t],e,!1))},t.prototype.log=function(t,e,n){for(var r,o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];T[this.level]>=T[e]&&t.apply(void 0,a(["[".concat(this.dateFormatter.format(new Date),"] ").concat(null===(r=this.decorator)||void 0===r?void 0:r.decorateMessage(n))],o,!1))},t}(),k=function(){function t(){}return t.prototype.decorateMessage=function(t){return"[ConfigDirector:js-client-sdk] ".concat(t)},t}(),x=function(t,e){return new S(null!=t?t:"warn",null!=e?e:new k)},D=function(){function t(){}return t.prototype.aggregate=function(t){var e;if(0==t.events.length)return[];for(var n=new Map,r=0,o=t.events;r<o.length;r++){var i=o[r],a=JSON.stringify(i),s=(null===(e=n.get(a))||void 0===e?void 0:e.count)||0;n.set(a,{event:i,count:s+1})}return Array.from(n).map(function(e){var n=e[1];return{startTime:t.startTime,endTime:t.endTime,count:n.count,event:n.event}})},t}(),R=function(){function t(t){this._events=[],this._droppedEventCount=0,this.limit=null!=t?t:1e3}return Object.defineProperty(t.prototype,"events",{get:function(){return this._events},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reachedLimit",{get:function(){return this._events.length>=this.limit},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"droppedEventCount",{get:function(){return this._droppedEventCount},enumerable:!1,configurable:!0}),t.prototype.push=function(){for(var t,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.startTime||(this.startTime=new Date);var r=Math.max(0,e.length-this.limit),o=e.slice(r,e.length);if(this._droppedEventCount+=r,this._events.length+o.length>this.limit){var i=this._events.length+o.length-this.limit;this._events.splice(0,i),this._droppedEventCount+=i}return(t=this._events).push.apply(t,o)},t.prototype.takeSnapshot=function(){var t,e=new Date,n=null!==(t=this.startTime)&&void 0!==t?t:e,r=this._events.splice(0),o=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:n,endTime:e,events:r,droppedCount:o}},t.prototype.clear=function(){this._events=[],this.startTime=void 0,this._droppedEventCount=0},t}(),O=function(){function t(t){this.executeRequests=!0,this.sdkKey=t.sdkKey,this.logger=t.logger,this.url=new URL("telemetry/v1",t.baseUrl)}return t.prototype.report=function(t){var e=t.discreteEvents,n=t.aggregatedEvents,r=t.droppedEvents;if(!this.executeRequests)return{success:!1,fatalError:!0};var o={clientSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(o))return{success:!0,fatalError:!1};var i=this.sendReport(o);return i.fatalError&&(this.executeRequests=!1),i},t.prototype.isReportEmpty=function(t){return this.isEventListEmpty(t.discreteEvents)&&this.isEventListEmpty(t.aggregatedEvents)&&this.isDroppedEventsEmpty(t.droppedEvents)},t.prototype.isDroppedEventsEmpty=function(t){var e;if(!t)return!0;var n=Object.keys(t);if(0==n.length)return!0;for(var r=0,o=n;r<o.length;r++)if((null!==(e=t[o[r]])&&void 0!==e?e:0)>0)return!1;return!0},t.prototype.isEventListEmpty=function(t){var e,n,r=Object.keys(t);if(0==r.length)return!0;for(var o=0,i=r;o<i.length;o++)if((null!==(n=null===(e=t[i[o]])||void 0===e?void 0:e.length)&&void 0!==n?n:0)>0)return!1;return!0},t.prototype.sendReport=function(t){try{return{success:navigator.sendBeacon(this.url,JSON.stringify(t)),fatalError:!1}}catch(t){return this.logger.warn("[EventReporter] Fatal error attempting to send telemetry data: ".concat(t,". No more telemetry data will be sent.")),{success:!1,fatalError:!0}}},t}(),V=function(){function t(t){var e=this;this.evaluationEventQueue=new R,this.aggregator=new D,this.collectEvents=!0,this.logger=t.logger,this.reporter=new O(t),this.flushIntervalDelay=3e4,this.flushTimeout=setTimeout(function(){return e.flushAndScheduleNext()},5e3);try{document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.flush()})}catch(t){this.logger.warn("[TelemetryEventCollector] Could not configure 'visibilitychange' listener: ",t)}}return t.prototype.evaluatedConfig=function(t){this.collectEvents&&this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))},t.prototype.sanitizeEvaluatedConfigEvent=function(t){return{key:t.key,type:t.type,defaultValue:this.sanitizeValue(t.defaultValue,t.type),requestedType:t.requestedType,evaluatedValue:this.sanitizeValue(t.evaluatedValue,t.type),usedDefault:t.usedDefault,evaluationReason:t.evaluationReason}},t.prototype.sanitizeValue=function(t,e){if("json"===e)try{return n=JSON.stringify(t),function(t){for(var e=5381,n=0;n<t.length;n++)e=(e<<5)+e+t[n],e>>>=0;return e}((new TextEncoder).encode(n)).toString(16).padStart(8,"0")}catch(e){return t.toString().slice(0,500)}var n;return t.toString().slice(0,500)},t.prototype.flushAndScheduleNext=function(){var t=this;this.flush().fatalError?(this.collectEvents=!1,this.close(),this.logger.warn("[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.")):this.flushTimeout=setTimeout(function(){return t.flushAndScheduleNext()},this.flushIntervalDelay)},t.prototype.flush=function(){var t=this.evaluationEventQueue.takeSnapshot();return this.reporter.report({discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(t)},droppedEvents:{evaluatedConfig:t.droppedCount}})},t.prototype.close=function(){this.collectEvents=!1,clearTimeout(this.flushTimeout),this.flush(),this.evaluationEventQueue.clear()},t.prototype.dispose=function(){this.close()},t}(),M=function(t,e,n,a){return o(void 0,0,void 0,function(){var o,s,u,c;return i(this,function(i){switch(i.label){case 0:o=new AbortController,s=setTimeout(function(){a.debug("[fetchWithTimeout] Reached timeout, aborting request"),o.abort()},t),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,fetch(e,r(r({},n),{signal:o.signal}))];case 2:return u=i.sent(),clearTimeout(s),[2,u];case 3:throw c=i.sent(),a.warn("[fetchWithTimeout] Fetch error: ",c),clearTimeout(s),c;case 4:return[2]}})})},P=function(){function t(t){this.options=t,this.eventEmitter=new s,this.fatalError=!1,this.options=t,this.logger=t.logger,this.url=new URL("pull/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return o(this,0,void 0,function(){var n,r,o,a,s,u,c;return i(this,function(i){switch(i.label){case 0:if(this.fatalError)return this.logger.warn("[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect."),[2,this];i.label=1;case 1:return i.trys.push([1,7,,8]),[4,M(e,this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey})},this.logger)];case 2:return(n=i.sent()).ok?[3,5]:this.isStatusFatal(n.status)?(this.fatalError=!0,r=this.prepareFatalResponseStatusError,o=[n.status],[4,n.text()]):[3,4];case 3:throw r.apply(this,o.concat([i.sent()]));case 4:throw new g("Connection failed with status: ".concat(n.status),n.status);case 5:return u=(s=JSON).parse,[4,n.text()];case 6:return a=u.apply(s,[i.sent()]),this.eventEmitter.emit("configSetReceived",a),[2,this];case 7:throw function(t){if(t instanceof DOMException){if("NotAllowedError"===t.name)return!0}else if(t instanceof TypeError)return!0;return!1}(c=i.sent())?(this.fatalError=!0,new g("Connection failed with fatal error: ".concat(c,". This is an unrecoverable error, retry attempts will be ignored."))):c instanceof SyntaxError?new g("Failed to parse the response from the server: ".concat(c)):new g("Connection failed with error: ".concat(c,"."));case 8:return[2]}})})},t.prototype.prepareFatalResponseStatusError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, retry attempts will be ignored.");return new g(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){},t.prototype.dispose=function(){this.close(),this.clear()},t}(),j=new URL("https://client-sdk-api.configdirector.com"),F=function(){function t(t,e,n){var o,i,a,u,c,l,f=this;this.handlersMap=new Map,this.eventEmitter=new s,this.ready=!1,this.logger=null!==(o=null==n?void 0:n.logger)&&void 0!==o?o:x(),this.timeout=null!==(a=null===(i=null==n?void 0:n.connection)||void 0===i?void 0:i.timeout)&&void 0!==a?a:3e3;var d=null!==(c=this.parseUrl(null===(u=null==n?void 0:n.connection)||void 0===u?void 0:u.url))&&void 0!==c?c:j;this.streaming=!1!==(null===(l=null==n?void 0:n.connection)||void 0===l?void 0:l.streaming);var p=this.streaming?m:P;this.usageEventCollector=new V({sdkKey:t,logger:this.logger,baseUrl:d}),this.transport=new p({clientSdkKey:t,baseUrl:d,metaContext:r(r({},null==n?void 0:n.metadata),{sdkName:e.sdkName,sdkVersion:e.sdkVersion,userAgent:null===navigator||void 0===navigator?void 0:navigator.userAgent}),logger:this.logger}),this.transport.on("configSetReceived",function(t){var e;null===(e=f.readyResolve)||void 0===e||e.call(f);var n=Object.keys(t.configs);f.configSet&&"full"!=t.kind?(f.configSet.configs=r(r({},f.configSet.configs),t.configs),f.eventEmitter.emit("configsUpdated",{keys:n}),f.updateWatchers(t.configs)):(f.configSet=t,f.eventEmitter.emit("configsUpdated",{keys:n}),f.updateWatchers(t.configs)),f.logger.debug("[ConfigDirectorClient] ConfigSet updated from server:",{keys:n})})}return t.prototype.initialize=function(t){return o(this,0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"initialization")];case 1:return e.sent(),[2]}})})},t.prototype.updateContext=function(t){return o(this,0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"context update")];case 1:return e.sent(),[2]}})})},t.prototype.connectToTransport=function(t,e){return o(this,0,void 0,function(){var n,r,o,a,s,u=this;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,4,,5]),this.ready=!1,this.readyPromise=new Promise(function(t){u.readyResolve=t}).then(function(){u.ready=!0,u.eventEmitter.emit("clientReady",{action:e}),u.logger.debug("[ConfigDirectorClient] Received initial payload from the server, client is ready")}),n=(new Date).getTime(),[4,this.transport.connect(null!=t?t:{},this.timeout)];case 1:return i.sent(),this.currentContext=t,r=(new Date).getTime()-n,(o=this.timeout-r)>0?[4,Promise.race([this.readyPromise,new Promise(function(t){setTimeout(function(){return t()},o)})])]:[3,3];case 2:i.sent(),i.label=3;case 3:return this.ready||(a=this.streaming?"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.":"Since the client was configured without streaming, configs may not update and always return the default value.",this.logger.warn("[ConfigDirectorClient] Timed out waiting for ".concat(e," after ").concat(this.timeout,"ms. ").concat(a))),[3,5];case 4:return s=i.sent(),this.logger.error("[ConfigDirectorClient] An error occurred during ".concat(e,": "),s),[3,5];case 5:return[2]}})})},t.prototype.updateWatchers=function(t){var e=this;Object.values(t).forEach(function(t){return e.updateWatchersForConfig(t)})},t.prototype.updateWatchersForConfig=function(t){var e,n=this;null===(e=this.handlersMap.get(t.key))||void 0===e||e.forEach(function(e){var r=n.getValueFromConfigState(t.key,t,e.defaultValue);e.handler(r)})},t.prototype.watch=function(t,e,n){var r=this;this.validateDefaultValue(e);var o=this.handlersMap.get(t),i={handler:n,defaultValue:e,requestedType:typeof e};return o?o.push(i):this.handlersMap.set(t,[i]),function(){return r.unwatch(t,n)}},t.prototype.unwatch=function(t,e){var n=this.handlersMap.get(t);if(n)if(e){var r=n.findIndex(function(t){return t.handler==e});r>=0&&(null==n||n.splice(r,1))}else n.splice(0)},t.prototype.getValue=function(t,e){var n;this.validateDefaultValue(e);var r=null===(n=this.configSet)||void 0===n?void 0:n.configs[t];return this.getValueFromConfigState(t,r,e)},t.prototype.getValueFromConfigState=function(t,e,n){var r,o;if(!e)return this.logger.debug("[ConfigDirectorClient] No config state found for '".concat(t,"', returning default value '").concat(n,"'")),this.usageEventCollector.evaluatedConfig({contextId:null===(r=this.currentContext)||void 0===r?void 0:r.id,key:t,defaultValue:n,requestedType:w(n),evaluatedValue:n,usedDefault:!0,evaluationReason:"config-state-missing"}),n;var i=function(t,e){var n,r,o=t.value,i=w(e);if(!o)return{parsedValue:e,requestedType:i,usedDefault:!0,reason:"value-missing"};if("string"==typeof e)return{parsedValue:o,requestedType:i,usedDefault:!1,reason:"found-match"};if("boolean"==typeof e&&"boolean"===t.type){var a=function(t){if(t){var e=t.toLowerCase();if("true"==e||"false"==e)return"true"===e}}(o),s="boolean"==typeof a;return{parsedValue:s?a:e,requestedType:i,usedDefault:!s,reason:s?"found-match":"invalid-boolean"}}return b(typeof e)&&"integer"===t.type?{parsedValue:(r="number"==typeof(n=E(o)))?n:e,requestedType:i,usedDefault:!r,reason:r?"found-match":"invalid-number"}:!b(typeof e)||"float"!==t.type&&"enum"!==t.type?{parsedValue:o,requestedType:i,usedDefault:!1,reason:"found-match"}:{parsedValue:(r="number"==typeof(n=C(o)))?n:e,requestedType:i,usedDefault:!r,reason:r?"found-match":"invalid-number"}}(e,n);return this.usageEventCollector.evaluatedConfig({contextId:null===(o=this.currentContext)||void 0===o?void 0:o.id,key:t,defaultValue:n,requestedType:i.requestedType,evaluatedValue:i.parsedValue,usedDefault:i.usedDefault,evaluationReason:i.reason}),this.logger.debug("[ConfigDirectorClient] Evaluated '".concat(t,"' to '").concat(i.parsedValue,"'")),i.parsedValue},t.prototype.parseUrl=function(t){if(t)try{return new URL(t)}catch(e){throw new y("Invalid base URL '".concat(t,"'. Parsing failed: ").concat(e))}},t.prototype.validateDefaultValue=function(t){if(null==t)throw new y("Invalid default value. The default value for a config must be defined and non-null.");if("function"==typeof t)throw new y("Invalid default value. The default value for a config cannot be a function.")},Object.defineProperty(t.prototype,"isReady",{get:function(){return this.ready},enumerable:!1,configurable:!0}),t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.logger.debug("[ConfigDirectorClient] clear() has been called, removing all observers"),this.eventEmitter.clear(),this.handlersMap.clear()},t.prototype.unwatchAll=function(){this.handlersMap.clear()},t.prototype.close=function(){this.logger.debug("[ConfigDirectorClient] close() has been called, closing connection to server"),this.transport.close(),this.ready=!1},t.prototype.dispose=function(){this.clear(),this.close()},t}();t.createClient=function(t,e){return new F(t,{sdkName:"js-client-sdk",sdkVersion:"0.1.3"},e)},t.createConsoleLogger=function(t,e){return x(t,e)}});
2
2
  //# sourceMappingURL=configdirector-client.min.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@configdirector/client-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.3",
4
4
  "description": "Javascript client SDK for ConfigDirector. ConfigDirector is a remote configuration and feature flag service.",
5
5
  "license": "MIT",
6
6
  "author": "ConfigDirector",
@@ -17,7 +17,7 @@
17
17
  "homepage": "https://www.configdirector.com",
18
18
  "repository": {
19
19
  "type": "git",
20
- "url": "https://github.com/configdirector/js-client-sdk"
20
+ "url": "https://github.com/ConfigDirector/js-sdks/tree/main/packages/js-client-sdk"
21
21
  },
22
22
  "type": "module",
23
23
  "exports": {
@@ -34,21 +34,20 @@
34
34
  },
35
35
  "files": [
36
36
  "dist/*.js",
37
- "dist/*.js.map",
38
- "dist/*client.d.ts"
37
+ "dist/*-client.d.ts"
39
38
  ],
40
39
  "types": "dist/configdirector-client.d.ts",
41
40
  "browser": "dist/configdirector-client.es.js",
42
41
  "module": "dist/configdirector-client.es.js",
43
42
  "scripts": {
44
- "build": "rimraf dist/** && rollup -c rollup.config.js",
43
+ "build": "rollup -c rollup.config.js",
45
44
  "clean": "rimraf dist/**",
46
45
  "lint": "eslint .",
47
46
  "test": "vitest",
48
47
  "ci:test": "vitest run"
49
48
  },
50
49
  "dependencies": {
51
- "eventsource-client": "^1.2.0"
50
+ "@configdirector/client-core": "^0.1.3"
52
51
  },
53
52
  "devDependencies": {
54
53
  "@eslint/js": "^9.39.2",