@configdirector/client-sdk 0.1.3 → 0.1.4
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(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)};
|
|
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.4"},e)},exports.createConsoleLogger=function(t,e){return k(t,e)};
|
|
2
2
|
//# sourceMappingURL=configdirector-client.cjs.js.map
|
|
@@ -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(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};
|
|
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.4"},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(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)}});
|
|
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.4"},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.
|
|
3
|
+
"version": "0.1.4",
|
|
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-sdks
|
|
20
|
+
"url": "https://github.com/ConfigDirector/js-sdks"
|
|
21
21
|
},
|
|
22
22
|
"type": "module",
|
|
23
23
|
"exports": {
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"ci:test": "vitest run"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@configdirector/client-core": "
|
|
50
|
+
"@configdirector/client-core": "workspace:^"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@eslint/js": "^9.39.2",
|