UNPKG

@hackler/js-client-sdk

Version:

JavaScript Client(Web Browser) SDK

383 lines (338 loc) 320 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Hackle = {})); })(this, (function (exports) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; var index_umd_min = {exports: {}}; (function (module, exports) { !function(t,e){e(exports);}(commonjsGlobal,(function(t){var e={DISABLE:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},r=function(){function t(){}return t.setLogLevel=function(t){void 0===t&&(t=e.INFO),this.logLevel=t;},t._log=function(t,e){var r;switch(t){case"WARN":r="orange";break;case"ERROR":r="red";break;default:r="#AAAAAA";}try{console.log("%c[".concat(t,"] Hackle: ").concat(e),"color: ".concat(r));}catch(t){}},t.logLevel=e.INFO,t.log={error:function(r){t.logLevel>=e.ERROR&&t._log("ERROR",r);},warn:function(r){t.logLevel>=e.WARN&&t._log("WARN",r);},info:function(r){t.logLevel>=e.INFO&&t._log("INFO",r);},debug:function(r){t.logLevel>=e.DEBUG&&t._log("DEBUG",r);}},t}(),n=3e3,i=function(t,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e;}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);},i(t,e)};function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t;}i(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r);}var u=function(){return u=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var i in e=arguments[r])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t},u.apply(this,arguments)};function s(t,e,r,n){return new(r||(r=Promise))((function(i,o){function u(t){try{a(n.next(t));}catch(t){o(t);}}function s(t){try{a(n.throw(t));}catch(t){o(t);}}function a(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(u,s);}a((n=n.apply(t,e||[])).next());}))}function a(t,e){var r,n,i,o,u={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;u;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return u.label++,{value:o[1],done:!1};case 5:u.label++,n=o[1],o=[0];continue;case 7:o=u.ops.pop(),u.trys.pop();continue;default:if(!(i=u.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){u=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){u.label=o[1];break}if(6===o[0]&&u.label<i[1]){u.label=i[1],i=o;break}if(i&&u.label<i[2]){u.label=i[2],u.ops.push(o);break}i[2]&&u.ops.pop(),u.trys.pop();continue}o=e.call(t,u);}catch(t){o=[6,t],n=0;}finally{r=i=0;}if(5&o[0])throw o[1];return {value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function c(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return {next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}var f=r.log,p=function(){function t(t,e){this.variation=t,this.reason=e;}return t.of=function(e,r){return new t(e,r)},t}(),h=function(){function t(t,e){this.isOn=t,this.reason=e;}return t.on=function(e){return new t(!0,e)},t.off=function(e){return new t(!1,e)},t}(),l=function(){function t(){}return t.SDK_NOT_READY="SDK_NOT_READY",t.EXCEPTION="EXCEPTION",t.INVALID_INPUT="INVALID_INPUT",t.EXPERIMENT_NOT_FOUND="EXPERIMENT_NOT_FOUND",t.EXPERIMENT_DRAFT="EXPERIMENT_DRAFT",t.EXPERIMENT_PAUSED="EXPERIMENT_PAUSED",t.EXPERIMENT_COMPLETED="EXPERIMENT_COMPLETED",t.OVERRIDDEN="OVERRIDDEN",t.TRAFFIC_NOT_ALLOCATED="TRAFFIC_NOT_ALLOCATED",t.NOT_IN_MUTUAL_EXCLUSION_EXPERIMENT="NOT_IN_MUTUAL_EXCLUSION_EXPERIMENT",t.IDENTIFIER_NOT_FOUND="IDENTIFIER_NOT_FOUND",t.VARIATION_DROPPED="VARIATION_DROPPED",t.TRAFFIC_ALLOCATED="TRAFFIC_ALLOCATED",t.NOT_IN_EXPERIMENT_TARGET="NOT_IN_EXPERIMENT_TARGET",t.FEATURE_FLAG_NOT_FOUND="FEATURE_FLAG_NOT_FOUND",t.FEATURE_FLAG_INACTIVE="FEATURE_FLAG_INACTIVE",t.INDIVIDUAL_TARGET_MATCH="INDIVIDUAL_TARGET_MATCH",t.TARGET_RULE_MATCH="TARGET_RULE_MATCH",t.DEFAULT_RULE="DEFAULT_RULE",t}(),T=function(){function t(t,e,r,n,i,o,u,s,a,c,f,p,h,l){this.id=t,this.key=e,this.type=r,this.identifierType=n,this.status=i,this.version=o,this.variations=u,this.userOverrides=s,this.segmentOverrides=a,this.targetAudiences=c,this.targetRules=f,this.defaultRule=p,this.containerId=h,this._winnerVariationId=l;}return t.prototype._winnerVariationOrNull=function(){if(this._winnerVariationId)return this._getVariationByIdOrNull(this._winnerVariationId)},t.prototype._getVariationByIdOrNull=function(t){return this.variations.find((function(e){return e.id===t}))},t.prototype._getVariationByKeyOrNull=function(t){return this.variations.find((function(e){return e.key===t}))},t}(),E=function(t,e,r){this.id=t,this.key=e,this.isDropped=r;},y=function(t,e,r){this.seed=t,this.slotSize=e,this.slots=r;},d=function(){function t(t,e,r){this.startInclusive=t,this.endExclusive=e,this.variationId=r;}return t.prototype.contains=function(t){return this.startInclusive<=t&&t<this.endExclusive},t}(),v=function(t,e){this.id=t,this.key=e;},N=function(){function t(){}return t.ID="$id",t.USER="$userId",t.DEVICE="$deviceId",t}(),_=function(){function t(){this.identifiers={};}return t.prototype.addIdentifiers=function(t){for(var e in t)this.add(e,t[e]);return this},t.prototype.add=function(t,e){return e&&this._isValid(t,e)?this.identifiers[t]=e:f.warn("Invalid user identifier [type=".concat(t,", value=").concat(e,"]")),this},t.prototype._isValid=function(t,e){return !!t&&("string"==typeof t&&(!(t.length>128)&&(!!e&&("string"==typeof e&&!(e.length>512)))))},t.prototype.build=function(){return this.identifiers},t}(),m=function(t){this.conditions=t;},R=function(t,e){this.key=t,this.match=e;},I=function(t,e){this.type=t,this.name=e;},A=function(t,e,r,n){this.type=t,this.operator=e,this.valueType=r,this.values=n;},O=function(t,e,r){this.type=t,this.variationId=e,this.bucketId=r;},g=function(t,e){this.target=t,this.action=e;},w=function(t,e,r,n){this.id=t,this.key=e,this.type=r,this.targets=n;},M=function(){function t(t,e,r){this.id=t,this.bucketId=e,this.groups=r;}return t.prototype.getGroupOrNull=function(t){return this.groups.find((function(e){return e.id===t}))},t}(),b=function(t,e){this.id=t,this.experiments=e;};function F(t,e){return t-e}var P=function(){function t(t,e,r){this.coreVersion=t,this.prerelease=e,this.build=r;}return t.tryParse=function(e){var r=t.regExp.exec(e);if(r){var n=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),u=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)u.push(n.value);}catch(t){i={error:t};}finally{try{n&&!n.done&&(r=o.return)&&r.call(o);}finally{if(i)throw i.error}}return u}(r,6);n[0];var i=n[1],o=n[2],u=void 0===o?"0":o,s=n[3],a=void 0===s?"0":s,c=n[4],f=n[5];return new t(new D(parseInt(i,10),parseInt(u,10),parseInt(a,10)),C.parse(c),C.parse(f))}},t.prototype.compareTo=function(t){return this.coreVersion.compareTo(t.coreVersion)||this.prerelease.compareTo(t.prerelease)},t.prototype.isEqualTo=function(t){return 0===this.compareTo(t)},t.prototype.isGreaterThan=function(t){return this.compareTo(t)>0},t.prototype.isGreaterThanOrEqualTo=function(t){return this.compareTo(t)>=0},t.prototype.isLessThan=function(t){return this.compareTo(t)<0},t.prototype.isLessThanOrEqualTo=function(t){return this.compareTo(t)<=0},t.regExp=/^(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?(?:\.(0|[1-9]\d*))?(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,t}(),D=function(){function t(t,e,r){this.major=t,this.minor=e,this.patch=r;}return t.prototype.compareTo=function(t){return F(this.major,t.major)||F(this.minor,t.minor)||F(this.patch,t.patch)},t}(),C=function(){function t(t){this.identifiers=t;}return t.parse=function(e){return e?new t(e.split(".")):t.EMPTY},t.prototype.isEmpty=function(){return 0===this.identifiers.length},t.prototype.isNotEmpty=function(){return !this.isEmpty()},t.prototype.compareTo=function(t){return this.isEmpty()&&t.isEmpty()?0:this.isEmpty()&&t.isNotEmpty()?1:this.isNotEmpty()&&t.isEmpty()?-1:this.compareIdentifiers(t)},t.prototype.compareIdentifiers=function(e){for(var r=Math.min(this.identifiers.length,e.identifiers.length),n=0;n<r;n++){var i=t.compareIdentifiers(this.identifiers[n],e.identifiers[n]);if(0!==i)return i}return F(this.identifiers.length,e.identifiers.length)},t.compareIdentifiers=function(e,r){return t.numericIdentifierRegExp.test(e)&&t.numericIdentifierRegExp.test(r)?F(+e,+r):e===r?0:e<r?-1:1},t.EMPTY=new t([]),t.numericIdentifierRegExp=/^(0|[1-9]\d*)$/,t}(),U=["MATCH","NOT_MATCH"],S=["STRING","NUMBER","BOOLEAN","VERSION"],L=["IN","CONTAINS","STARTS_WITH","ENDS_WITH","GT","GTE","LT","LTE"],k=["VARIATION","BUCKET"],x=["USER_ID","USER_PROPERTY","HACKLE_PROPERTY","SEGMENT"],G=["USER_ID","USER_PROPERTY"],H=function(){function t(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.supportedKeyTypes=t;}return t.prototype.supports=function(t){return this.supportedKeyTypes.includes(t)},t.IDENTIFIER=new t("SEGMENT"),t.PROPERTY=new t("SEGMENT","USER_PROPERTY","HACKLE_PROPERTY"),t.SEGMENT=new t("USER_ID","USER_PROPERTY","HACKLE_PROPERTY"),t}(),V=function(){function t(){}return t.validate=function(t){if(t){if("object"!=typeof t)return !1;for(var e in t)if(!this.validProperty(e,t[e]))return !1}return !0},t.filteredProperties=function(t){var e=this;return Object.keys(t).filter((function(r){return e.validProperty(r,t[r])})).reduce((function(r,n){var i;return u(u({},r),((i={})[n]=e.filteredPropertiesValue(t[n]),i))}),{})},t.filteredPropertiesValue=function(t){return "string"==typeof t&&t.length>1024?t.slice(0,1024):t},t.validProperty=function(t,e){return !!t&&("string"==typeof t&&(!(t.length>128)&&("string"==typeof e||("boolean"==typeof e||"number"==typeof e&&(!isNaN(e)&&isFinite(e))))))},t}(),B=function(){function t(t,e){this.timestamp=t,this.user=e;}return t.exposure=function(t,e,r){return new K((new Date).getTime(),e,t,r.variationId,r.variationKey,r.reason)},t.track=function(t,e,r){return new Y((new Date).getTime(),r,t,e)},t.isExposure=function(t){return void 0!==t.experiment},t.isTrack=function(t){return void 0!==t.eventType},t}(),K=function(t){function e(e,r,n,i,o,u){var s=t.call(this,e,r)||this;return s.experiment=n,s.variationId=i,s.variationKey=o,s.decisionReason=u,s}return o(e,t),e.prototype.toDto=function(){return {timestamp:this.timestamp,userId:this.user.identifiers[N.ID],identifiers:this.user.identifiers,userProperties:V.filteredProperties(this.user.properties||{}),hackleProperties:V.filteredProperties(this.user.hackleProperties||{}),experimentId:this.experiment.id,experimentKey:this.experiment.key,experimentType:this.experiment.type,experimentVersion:this.experiment.version,variationId:this.variationId,variationKey:this.variationKey,decisionReason:this.decisionReason.toString()}},e}(B),Y=function(t){function e(e,r,n,i){var o=t.call(this,e,r)||this;return o.eventType=n,o.event=i,o}return o(e,t),e.prototype.toDto=function(){return {timestamp:this.timestamp,userId:this.user.identifiers[N.ID],identifiers:this.user.identifiers,userProperties:V.filteredProperties(this.user.properties||{}),hackleProperties:V.filteredProperties(this.user.hackleProperties||{}),eventTypeId:this.eventType.id,eventTypeKey:this.eventType.key,value:this.event.value||0,properties:V.filteredProperties(this.event.properties||{})}},e}(B),X=function(){function t(t,e,r){this.variationId=t,this.variationKey=e,this.reason=r;}return t.withVariation=function(e,r){return new t(e.id,e.key,r)},t.withKey=function(e,r){return new t(void 0,e,r)},t.of=function(e,r,n){var i=e._getVariationByKeyOrNull(r);return i?t.withVariation(i,n):t.withKey(r,n)},t}(),z=function(){function t(t){this.evaluationFlowFactory=t;}return t.prototype.evaluate=function(t,e,r,n){return this.evaluationFlowFactory.getFlow(e.type).evaluate(t,e,r,n)},t}(),j=function(){function t(t){this.conditionMatcherFactory=t;}return t.prototype.matches=function(t,e,r){var n=this;return t.conditions.every((function(t){return n._matches(t,e,r)}))},t.prototype._matches=function(t,e,r){return this.conditionMatcherFactory.getMatcher(t.key.type).matches(t,e,r)},t}(),W=function(){function t(t,e){this.valueMatcherFactory=t,this.operatorMatcherFactory=e;}return t.prototype.matches=function(t,e){var r=this.valueMatcherFactory.getMatcher(e.valueType),n=this.operatorMatcherFactory.getMatcher(e.operator),i=e.values.some((function(e){return r.matches(n,t,e)}));return this._matches(e.type,i)},t.prototype._matches=function(t,e){switch(t){case"MATCH":return e;case"NOT_MATCH":return !e}},t}(),q=function(){function t(){}return t.prototype.booleanMatches=function(t,e){return t===e},t.prototype.numberMatches=function(t,e){return t===e},t.prototype.stringMatches=function(t,e){return t===e},t.prototype.versionMatches=function(t,e){return t.isEqualTo(e)},t}(),Z=function(){function t(){}return t.prototype.booleanMatches=function(t,e){return !1},t.prototype.numberMatches=function(t,e){return !1},t.prototype.stringMatches=function(t,e){return t.includes(e)},t.prototype.versionMatches=function(t,e){return !1},t}(),Q=function(){function t(){}return t.prototype.booleanMatches=function(t,e){return !1},t.prototype.numberMatches=function(t,e){return !1},t.prototype.stringMatches=function(t,e){return t.startsWith(e)},t.prototype.versionMatches=function(t,e){return !1},t}(),$=function(){function t(){}return t.prototype.booleanMatches=function(t,e){return !1},t.prototype.numberMatches=function(t,e){return !1},t.prototype.stringMatches=function(t,e){return t.endsWith(e)},t.prototype.versionMatches=function(t,e){return !1},t}(),J=function(){function t(){}return t.prototype.booleanMatches=function(t,e){return !1},t.prototype.numberMatches=function(t,e){return t>e},t.prototype.stringMatches=function(t,e){return !1},t.prototype.versionMatches=function(t,e){return t.isGreaterThan(e)},t}(),tt=function(){function t(){}return t.prototype.booleanMatches=function(t,e){return !1},t.prototype.numberMatches=function(t,e){return t>=e},t.prototype.stringMatches=function(t,e){return !1},t.prototype.versionMatches=function(t,e){return t.isGreaterThanOrEqualTo(e)},t}(),et=function(){function t(){}return t.prototype.booleanMatches=function(t,e){return !1},t.prototype.numberMatches=function(t,e){return t<e},t.prototype.stringMatches=function(t,e){return !1},t.prototype.versionMatches=function(t,e){return t.isLessThan(e)},t}(),rt=function(){function t(){}return t.prototype.booleanMatches=function(t,e){return !1},t.prototype.numberMatches=function(t,e){return t<=e},t.prototype.stringMatches=function(t,e){return !1},t.prototype.versionMatches=function(t,e){return t.isLessThanOrEqualTo(e)},t}(),nt=function(){function t(){}return t.prototype.getMatcher=function(e){switch(e){case"IN":return t.IN_MATCHER;case"CONTAINS":return t.CONTAINS_MATCHER;case"STARTS_WITH":return t.STARTS_WITH_MATCHER;case"ENDS_WITH":return t.ENDS_WITH_MATCHER;case"GT":return t.GT_MATCHER;case"GTE":return t.GTE_MATCHER;case"LT":return t.LT_MATCHER;case"LTE":return t.LTE_MATCHER}},t.IN_MATCHER=new q,t.CONTAINS_MATCHER=new Z,t.STARTS_WITH_MATCHER=new Q,t.ENDS_WITH_MATCHER=new $,t.GT_MATCHER=new J,t.GTE_MATCHER=new tt,t.LT_MATCHER=new et,t.LTE_MATCHER=new rt,t}(),it=function(){function t(){}return t.prototype.matches=function(t,e,r){return "string"==typeof e&&"string"==typeof r&&t.stringMatches(e,r)},t}(),ot=function(){function t(){}return t.prototype.matches=function(t,e,r){return "number"==typeof e&&"number"==typeof r&&t.numberMatches(e,r)},t}(),ut=function(){function t(){}return t.prototype.matches=function(t,e,r){return "boolean"==typeof e&&"boolean"==typeof r&&t.booleanMatches(e,r)},t}(),st=function(){function t(){}return t.prototype.matches=function(t,e,r){var n=P.tryParse(e),i=P.tryParse(r);return !(!n||!i)&&t.versionMatches(n,i)},t}(),at=function(){function t(){}return t.prototype.getMatcher=function(e){switch(e){case"STRING":return t.STRING_MATCHER;case"NUMBER":return t.NUMBER_MATCHER;case"BOOLEAN":return t.BOOLEAN_MATCHER;case"VERSION":return t.VERSION_MATCHER}},t.STRING_MATCHER=new it,t.NUMBER_MATCHER=new ot,t.BOOLEAN_MATCHER=new ut,t.VERSION_MATCHER=new st,t}(),ct=function(){function t(){}return t.isNullOrUndefined=function(t){return null==t},t}(),ft=function(){function t(t,e){this.userValueResolver=t,this.valueOperatorMatcher=e;}return t.prototype.matches=function(t,e,r){var n=this.userValueResolver.resolveOrNull(r,t.key);return !ct.isNullOrUndefined(n)&&this.valueOperatorMatcher.matches(n,t.match)},t}(),pt=function(){function t(){}return t.prototype.resolveOrNull=function(t,e){switch(e.type){case"USER_ID":return t.identifiers[e.name];case"USER_PROPERTY":return t.properties[e.name];case"HACKLE_PROPERTY":return t.hackleProperties[e.name];case"SEGMENT":throw new Error("Unsupported TargetKeyType [".concat(e.type,"]"))}},t}(),ht=function(){function t(t){this.segmentMatcher=t;}return t.prototype.matches=function(t,e,r){var n=this;if("SEGMENT"!=t.key.type)throw new Error("Unsupported TargetKeyType [".concat(t.key.type,"]"));var i=t.match.values.some((function(t){return n._matches(t,e,r)}));switch(t.match.type){case"MATCH":return i;case"NOT_MATCH":return !i}},t.prototype._matches=function(t,e,r){if("string"!=typeof t)throw new Error("SegmentKey[".concat(t,"]"));var n=e.getSegmentOrNull(t);if(!n)throw new Error("Segment[".concat(t,"]"));return this.segmentMatcher.matches(n,e,r)},t}(),lt=function(){function t(t){this.userConditionMatcher=t;}return t.prototype.matches=function(t,e,r){var n=this;return t.targets.some((function(t){return n._matches(t,e,r)}))},t.prototype._matches=function(t,e,r){var n=this;return t.conditions.every((function(t){return n.userConditionMatcher.matches(t,e,r)}))},t}(),Tt=function(){function t(){}return t.prototype.getMatcher=function(e){switch(e){case"USER_ID":case"USER_PROPERTY":case"HACKLE_PROPERTY":return t.USER_CONDITION_MATCHER;case"SEGMENT":return t.SEGMENT_CONDITION_MATCHER}},t.USER_CONDITION_MATCHER=new ft(new pt,new W(new at,new nt)),t.SEGMENT_CONDITION_MATCHER=new ht(new lt(t.USER_CONDITION_MATCHER)),t}(),Et=function(){function t(t){this.bucketer=t;}return t.prototype.resolveOrNull=function(t,e,r,n){switch(t.type){case"VARIATION":return this._resolveVariation(t,r);case"BUCKET":return this._resolveBucket(t,e,r,n)}},t.prototype._resolveVariation=function(t,e){return e._getVariationByIdOrNull(t.variationId)},t.prototype._resolveBucket=function(t,e,r,n){var i=e.getBucketOrNull(t.bucketId),o=n.identifiers[r.identifierType];if(o){var u=this.bucketer.bucketing(i,o);if(u)return r._getVariationByIdOrNull(u.variationId)}},t}(),yt={murmurhash3_x86_32:function(t,e,r,n){void 0===n&&(n=t.length);for(var i,o=3432918353,u=461845907,s=-4&n,a=e,c=0;c<s;c+=4)i=255&t.charCodeAt(c)|(255&t.charCodeAt(c+1))<<8|(255&t.charCodeAt(c+2))<<16|(255&t.charCodeAt(c+3))<<24,i=(131071&(i=this.mul32(i,o)))<<15|i>>>17,a=5*(a=(524287&(a^=i=this.mul32(i,u)))<<13|a>>>19)+3864292196|0;switch(i=0,n%4){case 3:i=(255&t.charCodeAt(s+2))<<16;case 2:i|=(255&t.charCodeAt(s+1))<<8;case 1:i|=255&t.charCodeAt(s),i=(131071&(i=this.mul32(i,o)))<<15|i>>>17,a^=i=this.mul32(i,u);}return a^=n,a^=a>>>16,a=this.mul32(a,2246822507),a^=a>>>13,a=this.mul32(a,3266489909),a^=a>>>16},mul32:function(t,e){var r=65535&e;return ((e-r)*t|0)+(r*t|0)|0}},dt=function(){function t(){}return t.prototype.bucketing=function(t,e){var r=this.calculateSlotNumber(t.seed,t.slotSize,e);return t.slots.find((function(t){return t.contains(r)}))},t.prototype.calculateSlotNumber=function(t,e,r){var n=yt.murmurhash3_x86_32(r,t);return Math.abs(n)%Math.abs(e)},t}(),vt=function(){function t(t,e){void 0===t&&(t=void 0),void 0===e&&(e=void 0),this.flowEvaluator=t,this.nextFlow=e;}return t.prototype.evaluate=function(t,e,r,n){return this.flowEvaluator&&this.nextFlow?this.flowEvaluator.evaluate(t,e,r,n,this.nextFlow):X.of(e,n,l.TRAFFIC_NOT_ALLOCATED)},t.of=function(){for(var e,r,n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var o=new t;try{for(var u=c(n.reverse()),s=u.next();!s.done;s=u.next()){var a=s.value;o=new t(a,o);}}catch(t){e={error:t};}finally{try{s&&!s.done&&(r=u.return)&&r.call(u);}finally{if(e)throw e.error}}return o},t}(),Nt=function(){function t(t){this.overrideResolver=t;}return t.prototype.evaluate=function(t,e,r,n,i){var o=this.overrideResolver.resolveOrNull(t,e,r);if(!o)return i.evaluate(t,e,r,n);switch(e.type){case"AB_TEST":return X.withVariation(o,l.OVERRIDDEN);case"FEATURE_FLAG":return X.withVariation(o,l.INDIVIDUAL_TARGET_MATCH)}},t}(),_t=function(){function t(){}return t.prototype.evaluate=function(t,e,r,n,i){return "DRAFT"===e.status?X.of(e,n,l.EXPERIMENT_DRAFT):i.evaluate(t,e,r,n)},t}(),mt=function(){function t(){}return t.prototype.evaluate=function(t,e,r,n,i){if("PAUSED"!==e.status)return i.evaluate(t,e,r,n);switch(e.type){case"AB_TEST":return X.of(e,n,l.EXPERIMENT_PAUSED);case"FEATURE_FLAG":return X.of(e,n,l.FEATURE_FLAG_INACTIVE)}},t}(),Rt=function(){function t(){}return t.prototype.evaluate=function(t,e,r,n,i){if("COMPLETED"===e.status){var o=e._winnerVariationOrNull();if(!o)throw new Error("winner variation [".concat(e.id,"]"));return X.withVariation(o,l.EXPERIMENT_COMPLETED)}return i.evaluate(t,e,r,n)},t}(),It=function(){function t(t){this.experimentTargetDeterminer=t;}return t.prototype.evaluate=function(t,e,r,n,i){if("AB_TEST"!==e.type)throw new Error("experiment type bust be AB_TEST [".concat(e.id,"]"));return this.experimentTargetDeterminer.isUserInExperimentTarget(t,e,r)?i.evaluate(t,e,r,n):X.of(e,n,l.NOT_IN_EXPERIMENT_TARGET)},t}(),At=function(){function t(t){this.actionResolver=t;}return t.prototype.evaluate=function(t,e,r,n,i){if("RUNNING"!==e.status)throw new Error("experiment status must be RUNNING [".concat(e.id,"]"));if("AB_TEST"!==e.type)throw new Error("experiment type bust be AB_TEST [".concat(e.id,"]"));var o=this.actionResolver.resolveOrNull(e.defaultRule,t,e,r);return o?o.isDropped?X.of(e,n,l.VARIATION_DROPPED):X.withVariation(o,l.TRAFFIC_ALLOCATED):X.of(e,n,l.TRAFFIC_NOT_ALLOCATED)},t}(),Ot=function(){function t(t,e){this.targetRuleDeterminer=t,this.actionResolver=e;}return t.prototype.evaluate=function(t,e,r,n,i){if("RUNNING"!==e.status)throw new Error("experiment status must be RUNNING [".concat(e.id,"]"));if("FEATURE_FLAG"!==e.type)throw new Error("experiment type bust be FEATURE_FLAG [".concat(e.id,"]"));if(!r.identifiers[e.identifierType])return i.evaluate(t,e,r,n);var o=this.targetRuleDeterminer.determineTargetRuleOrNull(t,e,r);if(!o)return i.evaluate(t,e,r,n);var u=this.actionResolver.resolveOrNull(o.action,t,e,r);if(!u)throw new Error("FeatureFlag must decide the Variation [".concat(e.id,"]"));return X.withVariation(u,l.TARGET_RULE_MATCH)},t}(),gt=function(){function t(t){this.actionResolver=t;}return t.prototype.evaluate=function(t,e,r,n,i){if("RUNNING"!==e.status)throw new Error("experiment status must be RUNNING [".concat(e.id,"]"));if("FEATURE_FLAG"!==e.type)throw new Error("experiment type bust be FEATURE_FLAG [".concat(e.id,"]"));if(!r.identifiers[e.identifierType])return X.of(e,n,l.DEFAULT_RULE);var o=this.actionResolver.resolveOrNull(e.defaultRule,t,e,r);if(!o)throw new Error("FeatureFlag must decide the Variation [".concat(e.id,"]"));return X.withVariation(o,l.DEFAULT_RULE)},t}(),wt=function(){function t(t){this.containerResolver=t;}return t.prototype.evaluate=function(t,e,r,n,i){var o=e.containerId;if(!o)return i.evaluate(t,e,r,n);var u=t.getContainerOrNull(o);if(!u)throw new Error("container[".concat(o,"]"));var s=t.getBucketOrNull(u.bucketId);if(!s)throw new Error("bucket[".concat(u.bucketId,"]"));return this.containerResolver.isUserInContainerGroup(u,s,e,r)?i.evaluate(t,e,r,n):X.of(e,n,l.NOT_IN_MUTUAL_EXCLUSION_EXPERIMENT)},t}(),Mt=function(){function t(){}return t.prototype.evaluate=function(t,e,r,n,i){return r.identifiers[e.identifierType]?i.evaluate(t,e,r,n):X.of(e,n,l.IDENTIFIER_NOT_FOUND)},t}(),bt=function(){function t(t){this.targetMatcher=t;}return t.prototype.isUserInExperimentTarget=function(t,e,r){var n=this;return 0===e.targetAudiences.length||e.targetAudiences.some((function(e){return n.targetMatcher.matches(e,t,r)}))},t}(),Ft=function(){function t(t){this.targetMatcher=t;}return t.prototype.determineTargetRuleOrNull=function(t,e,r){var n=this;return e.targetRules.find((function(e){return n.targetMatcher.matches(e.target,t,r)}))},t}(),Pt=function(){function t(t,e){this.targetMatcher=t,this.actionResolver=e;}return t.prototype.resolveOrNull=function(t,e,r){var n=this._resolveUserOverride(e,r);return n||this._resolveSegmentOverride(t,e,r)},t.prototype._resolveUserOverride=function(t,e){var r=e.identifiers[t.identifierType];if(r){var n=t.userOverrides.get(r);if(n)return t._getVariationByIdOrNull(n)}},t.prototype._resolveSegmentOverride=function(t,e,r){var n=this,i=e.segmentOverrides.find((function(e){return n.targetMatcher.matches(e.target,t,r)}));if(i)return this.actionResolver.resolveOrNull(i.action,t,e,r)},t}(),Dt=function(){function t(t){this.bucketer=t;}return t.prototype.isUserInContainerGroup=function(t,e,r,n){var i=n.identifiers[r.identifierType];if(!i)return !1;var o=this.bucketer.bucketing(e,i);if(!o)return !1;var u=t.getGroupOrNull(o.variationId);if(!u)throw new Error("ContainerGroup[".concat(o.variationId,"]"));return u.experiments.includes(r.id)},t}(),Ct=function(){function t(){var t=new dt,e=new j(new Tt),r=new Et(t),n=new Pt(e,r),i=new Dt(t);this.abTestFlow=vt.of(new Nt(n),new Mt,new wt(i),new It(new bt(e)),new _t,new mt,new Rt,new At(r)),this.featureFlagFlow=vt.of(new _t,new mt,new Rt,new Nt(n),new Mt,new Ot(new Ft(e),r),new gt(r));}return t.prototype.getFlow=function(t){switch(t){case"AB_TEST":return this.abTestFlow;case"FEATURE_FLAG":return this.featureFlagFlow}},t}(),Ut=r.log,St=function(){function t(t,e,r){this.evaluator=new z(new Ct),this.workspaceFetcher=t,this.eventProcessor=e,this.eventEmitter=r,this.workspaceFetcher.start(),this.eventProcessor.start(),this.readyPromise=this.workspaceFetcher.onReady().then((function(){return {success:!0}}),(function(t){return {success:!1,error:t}}));}return t.prototype._experiment=function(t,e,r){if(!t)return Ut.error("experimentKey must not be empty"),p.of(r,l.INVALID_INPUT);var n=this.workspaceFetcher.get();if(!n)return Ut.warn("SDK not ready."),p.of(r,l.SDK_NOT_READY);var i=n.getExperimentOrNull(t);if(!i)return Ut.warn("Experiment does not exist."),p.of(r,l.EXPERIMENT_NOT_FOUND);var o=this.evaluator.evaluate(n,i,e,r);return this.eventProcessor.process(B.exposure(i,e,o)),p.of(o.variationKey,o.reason)},t.prototype._featureFlag=function(t,e){if(!t)return Ut.error("featureKey must not be empty"),h.off(l.INVALID_INPUT);var r=this.workspaceFetcher.get();if(!r)return Ut.warn("SDK not ready."),h.off(l.SDK_NOT_READY);var n=r.getFeatureFlagOrNull(t);if(!n)return Ut.warn("FeatureFlag does not exist."),h.off(l.FEATURE_FLAG_NOT_FOUND);var i=this.evaluator.evaluate(r,n,e,"A");return this.eventProcessor.process(B.exposure(n,e,i)),"A"===i.variationKey?h.off(i.reason):h.on(i.reason)},t.prototype._track=function(t,e){var r;if(t)if("object"==typeof t)if("object"!=typeof t||t.key&&"string"==typeof t.key){var n=(null===(r=this.workspaceFetcher.get())||void 0===r?void 0:r.getEventTypeOrNull(t.key))||new v(0,t.key);this.eventProcessor.process(B.track(n,t,e));}else Ut.warn("Event key must be not null. or event key must be string type.");else Ut.warn("Event must be event type.");else Ut.warn("event must not be null.");},t.prototype._onReady=function(t,e){void 0===e&&(e=n),this._onInitialized({timeout:e}).then((function(){return t()}));},t.prototype._onInitialized=function(t){var e,r=t.timeout,i=void 0===r?n:r;Ut.debug("Start HackleClient initializing");var o=new Promise((function(t){e=t;})),u=setTimeout((function(){e({success:!1});}),i);return this.readyPromise.then((function(){clearTimeout(u),e({success:!0});}),(function(t){clearTimeout(u),e({success:!1,error:t});})),Promise.race([this.readyPromise,o]).then((function(t){return t.success?Ut.debug("HackleClient onInitialized Success"):t.error instanceof Error?Ut.error("HackleClient onInitialized Failed. ".concat(t.error.message)):Ut.error("HackleClient onInitialized Failed. ".concat(t.error)),Promise.resolve({success:t.success})}))},t.prototype._close=function(){this.workspaceFetcher.close(),this.eventProcessor.close();},t}();var Lt=function(){function t(t){var e=t.timeout,r=t.callback;this.timeout=Math.max(e,0),this.callback=r;}return t.prototype.start=function(){this.timeoutId=setTimeout(this.callback,this.timeout);},t.prototype.refresh=function(){this.stop(),this.start();},t.prototype.stop=function(){this.timeoutId&&clearTimeout(this.timeoutId);},t}(),kt=function(){function t(t,e,r,n){void 0===r&&(r=1e3),void 0===n&&(n=1e4),this.buffer=[],this.sink=t,this.maxQueueSize=r,this.batchComparator=e,this.timer=new Lt({callback:this.flush.bind(this),timeout:n}),this.started=!1;}return t.prototype.start=function(){this.started=!0;},t.prototype.stop=function(){this.started=!1;var t=this.sink(this.buffer,!0);return this.buffer=[],this.timer.stop(),t},t.prototype.enqueue=function(t){this.started&&(0===this.buffer.length&&this.timer.refresh(),this.buffer.push(t),this.buffer.length>=this.maxQueueSize&&this.flush());},t.prototype.flush=function(){this.sink(this.buffer),this.buffer=[],this.timer.stop();},t.prototype.close=function(){this.stop();},t}(),xt=function(){function t(e,r,n){void 0===r&&(r=1e3),void 0===n&&(n=t.DEFAULT_FLUSH_INTERVAL),this.flushInterval=t.DEFAULT_FLUSH_INTERVAL,this.eventDispatcher=e,this.flushInterval=n,this.queue=new kt(this.drainQueue.bind(this),Gt,r,n);}return t.prototype.drainQueue=function(t,e){var r=this;return new Promise((function(n){0!==t.length?e?r.eventDispatcher.dispatchXhrOrBeacon(t,(function(){n();})):r.eventDispatcher.dispatch(t,(function(){n();})):n();}))},t.prototype.process=function(t){this.queue.enqueue(t);},t.prototype.start=function(){return s(this,void 0,void 0,(function(){return a(this,(function(t){return this.queue.start(),[2]}))}))},t.prototype.stop=function(){try{this.queue.close();}catch(t){}return Promise.resolve()},t.prototype.close=function(){this.stop();},t.DEFAULT_FLUSH_INTERVAL=1e4,t}();function Gt(t,e){return t.timestamp==e.timestamp&&t.user.identifiers==e.user.identifiers&&t.user.properties==e.user.properties}var Ht=r.log,Vt=function(){function t(t,e,r,n,i,o){this.experiments=t,this.featureFlags=e,this.buckets=r,this.eventTypes=n,this.segments=i,this.containers=o;}return t.prototype.getExperimentOrNull=function(t){return this.experiments.get(t)},t.prototype.getFeatureFlagOrNull=function(t){return this.featureFlags.get(t)},t.prototype.getBucketOrNull=function(t){return this.buckets.get(t)},t.prototype.getEventTypeOrNull=function(t){return this.eventTypes.get(t)},t.prototype.getSegmentOrNull=function(t){return this.segments.get(t)},t.prototype.getContainerOrNull=function(t){return this.containers.get(t)},t.from=function(e){var r=this,n=t.associate(e.buckets,(function(t){return [t.id,r.toBucket(t)]})),i=t.associateBy(t.mapNotUndefined(e.experiments,(function(t){return r.toExperimentOrNull("AB_TEST",t)})),(function(t){return t.key})),o=t.associateBy(t.mapNotUndefined(e.featureFlags,(function(t){return r.toExperimentOrNull("FEATURE_FLAG",t)})),(function(t){return t.key})),u=t.associate(e.events,(function(t){return [t.key,new v(t.id,t.key)]})),s=t.associateBy(t.mapNotUndefined(e.segments,(function(t){return r.toSegmentOrNull(t)})),(function(t){return t.key})),a=t.associate(e.containers,(function(t){return [t.id,r.toContainer(t)]}));return new t(i,o,n,u,s,a)},t.toBucket=function(t){return new y(t.seed,t.slotSize,t.slots.map((function(t){var e=t.startInclusive,r=t.endExclusive,n=t.variationId;return new d(e,r,n)})))},t.toExperimentOrNull=function(e,r){var n=this,i=this.experimentStatusOrNull(r.execution.status),o=r.variations.map((function(t){return new E(t.id,t.key,"DROPPED"===t.status)})),u=t.associate(r.execution.userOverrides,(function(t){return [t.userId,t.variationId]})),s=t.mapNotUndefined(r.execution.segmentOverrides,(function(t){return n.toTargetRuleOrNull(t,H.IDENTIFIER)})),a=t.mapNotUndefined(r.execution.targetAudiences,(function(t){return n.toTargetOrNull(t,H.PROPERTY)})),c=t.mapNotUndefined(r.execution.targetRules,(function(t){return n.toTargetRuleOrNull(t,H.PROPERTY)})),f=this.toTargetActionOrNull(r.execution.defaultRule);return i&&f&&new T(r.id,r.key,e,r.identifierType,i,r.version,o,u,s,a,c,f,r.containerId,r.winnerVariationId)},t.experimentStatusOrNull=function(t){switch(t){case"READY":return "DRAFT";case"RUNNING":return "RUNNING";case"PAUSED":return "PAUSED";case"STOPPED":return "COMPLETED";default:return void Ht.debug("Unsupported status [".concat(t,"]"))}},t.toTargetRuleOrNull=function(t,e){var r=this.toTargetOrNull(t.target,e),n=this.toTargetActionOrNull(t.action);return r&&n&&new g(r,n)},t.toTargetActionOrNull=function(t){var e=this.parseOrNull(k,t.type);return e&&new O(e,t.variationId,t.bucketId)},t.toTargetOrNull=function(e,r){var n=this,i=t.mapNotUndefined(e.conditions,(function(t){return n.toConditionOrNull(t,r)}));return new m(i)},t.toConditionOrNull=function(t,e){var r=this.toTargetKeyOrNull(t.key);if(r&&e.supports(r.type)){var n=this.toTargetMatchOrNull(t.match);return n&&new R(r,n)}},t.toTargetKeyOrNull=function(t){var e=this.parseOrNull(x,t.type);return e&&new I(e,t.name)},t.toTargetMatchOrNull=function(t){var e=this.parseOrNull(U,t.type),r=this.parseOrNull(L,t.operator),n=this.parseOrNull(S,t.valueType);return e&&r&&n&&new A(e,r,n,t.values)},t.toSegmentOrNull=function(t){var e=this,r=this.parseOrNull(G,t.type);return r&&new w(t.id,t.key,r,this.mapNotUndefined(t.targets,(function(t){return e.toTargetOrNull(t,H.SEGMENT)})))},t.toContainer=function(t){var e=this;return new M(t.id,t.bucketId,t.groups.map((function(t){return e.toContainerGroup(t)})))},t.toContainerGroup=function(t){return new b(t.id,t.experiments)},t.parseOrNull=function(t,e){var r=t.find((function(t){return t===e}));return r||Ht.debug("Unsupported type [".concat(e,"]. Please use the latest version of sdk.")),r},t.mapNotUndefined=function(t,e){return t.reduce((function(t,r){var n=e(r);return n&&t.push(n),t}),Array())},t.associateTo=function(t,e,r){return t.reduce((function(t,e){var n=r(e);return t.set(n[0],n[1]),t}),e)},t.associate=function(e,r){return t.associateTo(e,new Map,r)},t.associateBy=function(t,e){return this.associateTo(t,new Map,(function(t){return [e(t),t]}))},t}();t.Bucket=y,t.Container=M,t.ContainerGroup=b,t.CoreVersion=D,t.DEFAULT_ON_READY_TIMEOUT=n,t.Decision=p,t.DecisionReason=l,t.DefaultEventQueue=kt,t.Event=B,t.EventProcessor=xt,t.EventType=v,t.Experiment=T,t.Exposure=K,t.FeatureFlagDecision=h,t.HackleInternalClient=St,t.IdentifierType=N,t.IdentifiersBuilder=_,t.Logger=r,t.MATCH_OPERATORS=L,t.MATCH_TYPES=U,t.MATCH_VALUE_TYPES=S,t.MetaVersion=C,t.SEGMENT_TYPES=G,t.Segment=w,t.Slot=d,t.TARGET_ACTION_TYPES=k,t.TARGET_KEY_TYPES=x,t.Target=m,t.TargetAction=O,t.TargetCondition=R,t.TargetKey=I,t.TargetMatch=A,t.TargetRule=g,t.TargetingType=H,t.Track=Y,t.Variation=E,t.Version=P,t.Workspace=Vt,t.logLevels=e,t.toPayload=function(t){var e=new Array,r=new Array;return t.forEach((function(t){B.isExposure(t)?e.push(t.toDto()):B.isTrack(t)&&r.push(t.toDto());})),{exposureEvents:e,trackEvents:r}},Object.defineProperty(t,"__esModule",{value:!0});})); }(index_umd_min, index_umd_min.exports)); var WORKSPACE_FETCH_URL_PREFIX = "https://sdk.hackle.io/api/v2/w/"; var WORKSPACE_FETCH_URL_POSTFIX = "/w"; var EVENT_DISPATCH_URL = "https://event.hackle.io/api/v2/w/events"; var EVENT_DISPATCH_URL_PREFIX = "https://event.hackle.io/api/v2/w/"; var EVENT_DISPATCH_URL_POSTFIX = "/events"; var SDK_KEY_HEADER = "X-HACKLE-SDK-KEY"; var SDK_NAME_HEADER = "X-HACKLE-SDK-NAME"; var SDK_VERSION_HEADER = "X-HACKLE-SDK-VERSION"; var SDK_TIME_HEADER = "X-HACKLE-SDK-TIME"; var SDK_VERSION = "3.5.0"; var BATCH_SIZE = 100; var DEFAULT_FLUSH_INTERVAL = 500; // milliseconds var ERROR_RETRY_BASE_WAIT_SECONDS_BY_ERROR_COUNT = [0, 8, 16, 32, 64, 128, 256, 512]; var COOKIE_EXPIRE_DAYS = 365 * 10; var COOKIE_HID_KEY = "_hackle_hid"; var COOKIE_USER_ID_KEY = "_hackle_id"; var log$2 = index_umd_min.exports.Logger.log; function getRequest(requestUrl, headers) { var responsePromise = new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open("GET", requestUrl); xhr.onreadystatechange = function () { if (xhr.readyState === xhr.DONE) { if (xhr.status === 0) { reject(new Error("Request error")); return; } resolve({ statusCode: xhr.status, body: xhr.responseText }); } }; xhr.setRequestHeader("content-type", "application/json"); xhr.withCredentials = true; setHeaders(xhr, headers); xhr.send(); }); return { abort: function () { //request.abort() }, responsePromise: responsePromise, }; } function postRequest(requestUrl, data, headers, callback) { var dataString = JSON.stringify(data); var xhr = new XMLHttpRequest(); xhr.open("POST", requestUrl); xhr.onreadystatechange = function () { if (xhr.readyState === xhr.DONE) { if (xhr.status >= 200 && xhr.status < 400) { callback(xhr); } } }; xhr.setRequestHeader("content-type", "application/json"); xhr.withCredentials = true; setHeaders(xhr, headers); xhr.send(dataString); } function setHeaders(xhr, headers) { for (var name_1 in headers) { if (headers.hasOwnProperty(name_1)) { xhr.setRequestHeader(name_1, headers[name_1]); } } } function sendBeacon(requestUrl, data, headers, callback) { var beaconSupport = false; // @ts-ignore if ((typeof window) !== "undefined") { // @ts-ignore beaconSupport = window && window.navigator && window.navigator.sendBeacon && true; } if (beaconSupport) { var dataString = JSON.stringify(data); var params = new URLSearchParams(); params.append("sdkName", headers[SDK_NAME_HEADER]); params.append("sdkVersion", headers[SDK_VERSION_HEADER]); params.append("sdkTime", headers[SDK_TIME_HEADER]); params.append("data", dataString); window.navigator.sendBeacon(requestUrl, params); callback(); } else { log$2.error("Does not support sendBeacon"); callback(); } } var EventDispatcher = /** @class */ (function () { function EventDispatcher(sdkKey, config) { this.sdkKey = sdkKey; this.headers = config.headers; this.dispatchUrl = config.dispatchUrl; this.beaconDispatchUrl = config.beaconDispatchUrl || ""; this.useBeacon = config.useBeacon; } EventDispatcher.prototype.dispatch = function (events, callback) { this._post(events, callback); // this._beacon(events, callback) }; EventDispatcher.prototype.dispatchXhrOrBeacon = function (events, callback) { if (this.useBeacon) { this._beacon(events, callback); } else { this._post(events, callback); } }; EventDispatcher.prototype._post = function (events, callback) { var _a = this._createRequest(events), payload = _a.payload, headers = _a.headers; postRequest(this.dispatchUrl, payload, headers, callback); }; EventDispatcher.prototype._beacon = function (events, callback) { var _a = this._createRequest(events), payload = _a.payload, headers = _a.headers; sendBeacon(this.beaconDispatchUrl, payload, headers, callback); }; EventDispatcher.prototype._createRequest = function (events) { var _a; var payload = index_umd_min.exports.toPayload(events); var headers = __assign((_a = {}, _a[SDK_KEY_HEADER] = this.sdkKey, _a[SDK_TIME_HEADER] = new Date().getTime().toString(), _a), this.headers); return { payload: payload, headers: headers }; }; return EventDispatcher; }()); var events = {exports: {}}; var R = typeof Reflect === 'object' ? Reflect : null; var ReflectApply = R && typeof R.apply === 'function' ? R.apply : function ReflectApply(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); }; var ReflectOwnKeys; if (R && typeof R.ownKeys === 'function') { ReflectOwnKeys = R.ownKeys; } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target) .concat(Object.getOwnPropertySymbols(target)); }; } else { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target); }; } function ProcessEmitWarning(warning) { if (console && console.warn) console.warn(warning); } var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { return value !== value; }; function EventEmitter() { EventEmitter.init.call(this); } events.exports = EventEmitter; events.exports.once = once; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; function checkListener(listener) { if (typeof listener !== 'function') { throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); } } Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); } defaultMaxListeners = arg; } }); EventEmitter.init = function() { if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { this._events = Object.create(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); } this._maxListeners = n; return this; }; function _getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; EventEmitter.prototype.emit = function emit(type) { var args = []; for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); var doError = (type === 'error'); var events = this._events; if (events !== undefined) doError = (doError && events.error === undefined); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { var er; if (args.length > 0) er = args[0]; if (er instanceof Error) { // Note: The comments on the `throw` lines are intentional, they show // up in Node's output if this results in an unhandled exception. throw er; // Unhandled 'error' event } // At least give some kind of context to the user var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); err.context = er; throw err; // Unhandled 'error' event } var handler = events[type]; if (handler === undefined) return false; if (typeof handler === 'function') { ReflectApply(handler, this, args); } else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; checkListener(listener); events = target._events; if (events === undefined) { events = target._events = Object.create(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener !== undefined) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (existing === undefined) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; // If we've already got an array, just append. } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } // Check for listener leak m = _getMaxListeners(target); if (m > 0 && existing.length > m && !existing.warned) { existing.warned = true; // No error code for this since it is a Warning // eslint-disable-next-line no-restricted-syntax var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + String(type) + ' listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; ProcessEmitWarning(w); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener