@bluedot-innovation/javascript-sdk
Advanced tools
Comparing version 1.3.3 to 1.3.4-alpha
@@ -160,3 +160,3 @@ 'use strict'; | ||
remoteConfig: /*#__PURE__*/tslib.__assign({}, defaultRemoteConfig), | ||
globalConfigUrl: 'https://globalconfig.bluedot.io/', | ||
globalConfigUrl: 'https://globalconfig.bluedot-gcp.com/', | ||
globalConfig: null, | ||
@@ -1313,3 +1313,3 @@ isInitialized: false, | ||
var GLOBAL_CONFIG_URL = 'https://globalconfig.bluedot.io/'; | ||
var GLOBAL_CONFIG_URL = 'https://globalconfig.bluedot-gcp.com/'; | ||
var config = { | ||
@@ -1316,0 +1316,0 @@ setConfigurationDomain: function setConfigurationDomain(BDGlobalConfigUrl) { |
@@ -1,2 +0,2 @@ | ||
"use strict";var t,e=require("tslib"),r=require("events"),o=require("uuid"),n=(t=require("axios"))&&"object"==typeof t&&"default"in t?t.default:t,i=function(){var t=new WeakMap;return function(e){return t.has(e)||t.set(e,{}),t.get(e)}},a=!1;function s(t,e,r){a&&(e&&r?t(e,r):t(e||r||new Error("Error logger called. See stack trace for details")))}var c=function(t,e){return s(console.error,t,e)},u=function(t,e){return s(console.warn,t,e)},l=function(t,e){return s(console.log,t,e)},d={ValidationError:"ValidationError",NetworkRetriesExceededError:"NetworkRetriesExceededError",UnexpectedServerError:"UnexpectedServerError",InvalidInputTypeError:"InvalidInputTypeError",RequiredValueMissingError:"RequiredValueMissingError",SdkNotInitializedError:"SdkNotInitializedError",ProjectIdNotFoundError:"ProjectIdNotFoundError",NotFoundError:"NotFoundError",InterruptedByResetError:"InterruptedByResetError",LocationAPINotAvailableError:"LocationAPINotAvailableError",RetryAttemptFailedError:"RetryAttemptFailedError"},f={createError:function(t,e,r){var o=new Error(e);o.name=t;var n=o;return n.errorObject=r,u(e,n),n},throwInvalidInputTypeError:function(t,e){throw this.createError(d.InvalidInputTypeError,null!=t?t:"Invalid input type error",e)},throwNetworkRetriesExceededError:function(t,e){throw this.createError(d.NetworkRetriesExceededError,t?"Failed to communicate via network after "+t+" attempts":"Failed to communicate via network",e)},throwProjectIdNotFoundError:function(t,e){throw this.createError(d.ProjectIdNotFoundError,t?"Project with ID: "+t+" not found":"Project ID not found",e)},throwRequiredValueMissingError:function(t,e){throw this.createError(d.RequiredValueMissingError,t?"Cannot trigger event. Missing required value: "+t:"Cannot trigger event. Missing required value",e)},throwSdkNotInitializedError:function(t,e){throw this.createError(d.SdkNotInitializedError,null!=t?t:"SDK is not initialized with a valid projectId",e)},throwUnexpectedServerError:function(t,e){throw this.createError(d.UnexpectedServerError,null!=t?t:"An unexpected server error occurred. Check the attached errorObject for more details",e)},throwValidationError:function(t,e){throw this.createError(d.ValidationError,null!=t?t:"Invalid input was detected",e)},throwNotFoundError:function(t,e){throw this.createError(d.NotFoundError,null!=t?t:"Not found",e)},throwInterruptedByResetError:function(t,e){throw this.createError(d.InterruptedByResetError,null!=t?t:"Interrupted by reset",e)},throwLocationAPINotAvailableError:function(t,e){throw this.createError(d.LocationAPINotAvailableError,null!=t?t:"Location API is not available",e)},createRetryAttemptFailedError:function(t,r){var o=this.createError(d.RetryAttemptFailedError,"Retry attempt "+t+" failed",r);return e.__assign(e.__assign({},o),{name:d.RetryAttemptFailedError,retryCount:t})}},h=new r.EventEmitter,v={remoteConfig:e.__assign({},{oneShot:{minAccuracy:50,targetAccuracy:20,maxAttempts:15,timeout:5e3}}),globalConfigUrl:"https://globalconfig.bluedot.io/",globalConfig:null,isInitialized:!1,initializeStatus:"notStarted",projectId:null,reset:m,addListener:E,removeListener:w,id:0,locationEnabled:!1,userPersistenceEnabled:!1,userToken:null},g=1,p=new Proxy(e.__assign({},v),{get:function(t,e){return t[e]},set:function(t,e,r){return t[e]=r,h.emit("stateUpdated",e),!0}});function m(){return Object.assign(p,v),p.reset=m,p.addListener=E,p.removeListener=w,p.id=g++,h.emit("stateReset"),h.removeAllListeners(),p}function E(t){return l("Adding state listener"),h.on("stateUpdated",t)}function w(t){h.removeListener("stateUpdated",t)}m();var b=function(t){return"string"==typeof t},y=function(t){return"number"==typeof t&&t>0},_=function(t,e){b(t)||f.throwInvalidInputTypeError(e+" must be a string")},I=function(t,e){_(t,"fieldName"),_(e,"fieldValue"),function(t){var e=["customername","orderid","eventtype","mobilenumber"],r=t.replace(/\s+/g,"");return t.toLowerCase().startsWith("hs_")?e.includes(r.slice(3).toLowerCase()):e.includes(r.toLowerCase())}(t)&&f.throwValidationError(t+" is a reserved keyword for Hello Screens. Use the helloModel method instead to set this value")},C=function(t,e){(function(t){return"boolean"==typeof t})(t)||f.throwInvalidInputTypeError(e+" must be a boolean")},S=i();function R(t){return _(t,"orderId"),S(this).orderId=t,this}function N(t){var e=function(t){var e;"string"==typeof t?e=t:"number"==typeof t&&(e=t.toString()),e||f.throwInvalidInputTypeError("mobileNumber must be a string");var r,o,n=e.replace(/ /g,"").replace(/-/g,"");return r=n,o=new RegExp(/^\+?[0-9]+$/),"string"==typeof r&&o.test(r)||f.throwValidationError("Invalid mobileNumber found. mobileNumber can only contain numerals or a leading + character"),n}(t);return S(this).mobileNumber=e,this}function A(t){return function(t){return!!b(t)&&["arrival","onTheWay"].includes(t)}(t)||f.throwValidationError("Invalid eventType found. eventType can only be 'arrival' or 'onTheWay'"),S(this).eventType=t,this}function k(t){return _(t,"customerName"),S(this).customerName=t,this}function T(t,e){I(t,e),function(t){t.toLowerCase().startsWith("hs_")&&f.throwValidationError("The hs_ prefix is reserved for fields that are displayed in Hello Screens. Use the setDisplayedCustomDataField method to set these values")}(t);var r=S(this).customFields;return void 0===r&&(r={},S(this).customFields=r),r[t]=e,this}function L(t,e){I(t,e);var r=S(this).displayedCustomFields;void 0===r&&(r={},S(this).displayedCustomFields=r);var o=r;return t.toLowerCase().startsWith("hs_")?o["hs_"+t.slice(3)]=e:o["hs_"+t]=e,this}function j(){var t=S(this),r=t.eventType,o=t.mobileNumber,n=t.customerName,i=t.orderId,a=t.customFields,s=t.displayedCustomFields;i||f.throwRequiredValueMissingError("orderId"),r||f.throwRequiredValueMissingError("eventType");var c=s,u=e.__assign(e.__assign({},a),c);return r&&(u.hs_eventType=r),i&&(u.hs_orderId=i),n&&(u.hs_customerName=n),o&&(u["hs_Mobile Number"]=o),u}n.interceptors.response.use(void 0,(function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,o;return e.__generator(this,(function(e){switch(e.label){case 0:if(!t.config.retries)throw t;if(o=t.response&&t.response.status>499&&t.response.status<600,!(r="ENOTFOUND"===t.code||"Network Error"===t.message)&&!o||t.config.isRetryRequest||(t.config.isRetryRequest=!0,t.config.retryCount=0),void 0===t.config.retryCount)throw t;return(r||o)&&t.config.retryCallback&&t.config.retryCallback(f.createRetryAttemptFailedError(t.config.retryCount,t)),(r||o)&&t.config.retryCount<t.config.retries?(l("Retry count: "+t.config.retryCount),[4,(i=Math.floor(100*Math.pow(t.config.retryCount,2))+Math.floor(100*Math.random()),new Promise((function(t){return setTimeout(t,i)})))]):[3,2];case 1:return e.sent(),t.config.retryCount+=1,[2,n(t.config)];case 2:throw t}var i}))}))}));var U=function(t,r,o){return e.__awaiter(void 0,void 0,void 0,(function(){var i;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,n.post(t,r,o)];case 1:return[2,e.sent()];case 2:if((i=e.sent()).config.retryCount&&i.config.retryCount>=i.config.retries)throw f.throwNetworkRetriesExceededError(i.config.retryCount,i);if(i.response&&400===i.response.status)throw f.throwValidationError("Bad request",i);throw f.throwUnexpectedServerError(void 0,i);case 3:return[2]}}))}))},F=function(t,r){return e.__awaiter(void 0,void 0,void 0,(function(){var o;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,n.get(t,r)];case 1:return[2,e.sent()];case 2:if((o=e.sent()).config.retryCount&&o.config.retryCount>=o.config.retries)throw f.throwNetworkRetriesExceededError(o.config.retryCount,o);throw f.throwUnexpectedServerError(void 0,o);case 3:return[2]}}))}))},P=function(t,r){return e.__awaiter(void 0,void 0,void 0,(function(){var o,n;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,F(""+p.globalConfigUrl+t+".json",{retries:p.remoteConfig.oneShot.maxAttempts,retryCallback:null==r?void 0:r.retryCallback,headers:{Origin:"force-cors-response"}})];case 1:return[2,e.sent()];case 2:if((o=e.sent()).name&&"UnexpectedServerError"===o.name&&(n=o.errorObject).response&&(404===n.response.status||403===n.response.status))throw f.throwProjectIdNotFoundError(void 0,o);throw o;case 3:return[2]}}))}))},x=function(){return!!global.localStorage},z=function(t,e){if(x()){var r=global.localStorage.getItem("installRefs"),o={};r&&(o=JSON.parse(r)),o[t]=e,global.localStorage.setItem("installRefs",JSON.stringify(o)),l("Storing installRef: "+e+" for projectId: "+t)}else u("localStorage object not found")},O=function(t,r){return e.__awaiter(void 0,void 0,void 0,(function(){var n,i,a,s;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),n=p.id,p.projectId=t,p.initializeStatus="inProgress",function(t){if(null!=t){"object"!=typeof t&&f.throwValidationError("InitializeOptions is not an object");var e=["retryCallback"],r=[];Object.keys(t).forEach((function(t){e.includes(t)||r.push(t)})),r.length>0&&f.throwValidationError("Invalid options parameters ["+r+"]")}}(r),[4,P(t,r)];case 1:if(i=e.sent(),n!==p.id)throw f.throwInterruptedByResetError();return p.isInitialized=!0,p.initializeStatus="completed",x()&&((a=function(t){if(!x())return u("localStorage object not found"),null;var e=global.localStorage.getItem("installRefs");return e?JSON.parse(e)[t]:null}(t))?(p.installRef=a,l("Using stored installRef: "+a)):(p.installRef=o.v4(),p.userPersistenceEnabled&&z(t,p.installRef))),p.globalConfig=i.data,[3,3];case 2:throw s=e.sent(),p.initializeStatus="failed",c("An error occurred during initialization",s),s;case 3:return[2]}}))}))},V=new(function(){function t(){var t=this;this.emitter=new r.EventEmitter,this.emitter.on("locationError",(function(t){c("Failed to get positon",t)})),this.emitter.on("removeListener",(function(e){"locationUpdate"===e&&0===t.emitter.listenerCount("locationUpdate")&&null!=t.handlerId&&(l("Remove locationUpdate"),navigator.geolocation.clearWatch(t.handlerId))}))}return t.prototype.getUpdatedPosition=function(t){var e=this;"locationUpdate"===t&&(this.handlerId=navigator.geolocation.watchPosition((function(t){l("Emitting",t),e.emitter.emit("locationUpdate",t)}),(function(t){e.emitter.emit("locationError",t),e.emitter.emit("locationUpdate")}),{enableHighAccuracy:!0,maximumAge:5e3}))},t.prototype.addListener=function(t){l("Adding locationUpdate listener."),this.emitter.on("locationUpdate",t),this.getUpdatedPosition("locationUpdate")},t.prototype.removeListener=function(t){this.emitter.removeListener("locationUpdate",t)},t}()),D=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,o,n,i;return e.__generator(this,(function(a){switch(a.label){case 0:return r=function(){if(p.globalConfig){var t=p.globalConfig.eventsApiUrl;if(t)return t;throw new Error("Project does not have Events Api Url")}throw f.throwSdkNotInitializedError()}(),o={headers:{"x-bluedot-api-key":p.projectId},retries:p.remoteConfig.oneShot.maxAttempts,retryCallback:t.retryCallback},n=e.__assign({},t.notification),p&&p.installRef&&(n.installRef=p.installRef),(null==p?void 0:p.userToken)&&(n.userToken=p.userToken),t.location&&t.location.longitude&&t.location.latitude&&(n.location=(c={longitude:(s=t.location).longitude,latitude:s.latitude,horizontalAccuracy:s.accuracy},s.speed&&(c.speed=s.speed),s.heading&&(c.bearing=s.heading),c)),[4,U(r+"wave",n,o)];case 1:return i=a.sent(),l("Event sent"),[2,i]}var s,c}))}))},M=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){return e.__generator(this,(function(e){return t.notificationType&&"wave"===t.notificationType?[2,D(t)]:[2]}))}))},q=function(){function t(t,r,o){this.attemptCount=0,this.bestEffort=null,this.isClosed=!1,this.notification=e.__assign({},t),this.notificationType=r,this.options=o}return t.prototype.trigger=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(t){return"failed"!==p.initializeStatus&&"notStarted"!==p.initializeStatus||f.throwSdkNotInitializedError(),p.locationEnabled?[2,this.trackAndSendLocation()]:[2,this.sendEvent()]}))}))},t.prototype.sendEvent=function(){var t;return e.__awaiter(this,void 0,void 0,(function(){var r=this;return e.__generator(this,(function(o){return++this.attemptCount>1?(l("Previous event is in progress. Ignoring retrigger"),[2,null]):p.globalConfig?(l("Target region identified"),l("Sending event"),[2,M({notification:this.notification,notificationType:this.notificationType,location:this.bestEffort,retryCallback:null===(t=this.options)||void 0===t?void 0:t.retryCallback})]):[2,new Promise((function(t,o){l("Target region identification in progress. Listening..."),p.addListener((function n(i){return e.__awaiter(r,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){return l("State event emitted "+i),p.globalConfig?(l("Target region found. Sending event"),p.removeListener(n),M({notification:this.notification,notificationType:this.notificationType,location:this.bestEffort,retryCallback:null===(r=this.options)||void 0===r?void 0:r.retryCallback}).then(t).catch(o)):"failed"===p.initializeStatus?(p.removeListener(n),o(f.createError(d.SdkNotInitializedError,"SDK failed to initialize"))):l("No target region found."),[2]}))}))}))}))]}))}))},t.prototype.attemptSendEvent=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(t){switch(t.label){case 0:return[4,this.sendEvent()];case 1:return t.sent(),this.closeLocationPolling(),[2]}}))}))},t.prototype.closeLocationPolling=function(){!this.isClosed&&this.listener&&V.removeListener(this.listener),this.isClosed=!0},t.prototype.trackAndSendLocation=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(r){return[2,new Promise((function(r){l("OneShotService: Adding location listener"),t.listener=function(o){return e.__awaiter(t,void 0,void 0,(function(){var t,n=this;return e.__generator(this,(function(e){return l("OneShotService: Received position",o),o&&o.coords&&o.coords.accuracy?null==this.bestEffort||this.bestEffort.accuracy&&this.bestEffort.accuracy<o.coords.accuracy?(o.coords.accuracy<p.remoteConfig.oneShot.minAccuracy&&(this.bestEffort=o.coords),p.isInitialized&&o.coords.accuracy<p.remoteConfig.oneShot.minAccuracy?r(this.attemptSendEvent()):(t=function(e){"isInitialized"===e&&(o.coords.accuracy&&o.coords.accuracy<p.remoteConfig.oneShot.minAccuracy&&r(n.attemptSendEvent()),p.removeListener(t))},p.addListener(t))):l("Lower accuracy than best effort, ignored."):r(this.attemptSendEvent()),[2]}))}))},V.addListener(t.listener),setTimeout((function(){return e.__awaiter(t,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isClosed?[3,2]:(l("Send event on location timeout"),this.closeLocationPolling(),t=r,[4,this.sendEvent()]);case 1:t.apply(void 0,[e.sent()]),e.label=2;case 2:return[2]}}))}))}),p.remoteConfig.oneShot.timeout)}))]}))}))},t}(),B=new(function(){function t(){}return t.prototype.triggerOneShot=function(t,r,o){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,new q(t,r,o).trigger()]}))}))},t}());exports.bluedot={wave:{send:function(t,r,o){return e.__awaiter(void 0,void 0,void 0,(function(){var n,i,a,s;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),_(t,"destinationId"),function(t){if(null!=t){"object"!=typeof t&&f.throwValidationError("WaveOptions is not an object");var e=["retryCallback"],r=[];Object.keys(t).forEach((function(t){e.includes(t)||r.push(t)})),r.length>0&&f.throwValidationError("Invalid options parameters ["+r+"]")}}(o),(n={destinationId:t,eventTime:new Date(Date.now()).toISOString()}).customEventMetaData=r&&Object.prototype.hasOwnProperty.call(r,"convertToDataObject")?r.convertToDataObject():r,[4,B.triggerOneShot(n,"wave",o)];case 1:return e.sent(),[3,3];case 2:if(i=e.sent(),!Object.values(d).includes(i.name))throw f.throwUnexpectedServerError(void 0,i);if(i.errorObject&&(a=i.errorObject).response&&404===a.response.status&&(s=new RegExp(/destinationId/i),a.response&&a.response.data&&a.response.data.errorCauses&&a.response.data.errorCauses.length&&a.response.data.errorCauses[0].message.match(s)))throw f.throwNotFoundError("Zone with destinationId: "+t+" not found",i);throw i;case 3:return[2]}}))}))}},config:{setConfigurationDomain:function(t){t?(function(t){if(b(t))try{var e=new URL(t);return Boolean(e)}catch(t){c(t)}return!1}(t)||f.throwValidationError("BDGlobalConfigUrl must be a valid URL"),p.globalConfigUrl=t):p.globalConfigUrl="https://globalconfig.bluedot.io/"},setUserPersistenceEnabled:function(t){C(t,"enabled"),x()?(p.userPersistenceEnabled=t,t?p.projectId&&p.installRef&&z(p.projectId,p.installRef):(x()?global.localStorage.removeItem("installRefs"):u("localStorage object not found"),delete p.installRef)):u("User persistence is not available in this environment")},setDebugModeEnabled:function(t){C(t,"enabled"),function(t){a=t}(t)},setLocationMinimumAccuracy:function(t){y(t)||f.throwValidationError("Location accuracy must be a positive number"),p.remoteConfig.oneShot.minAccuracy=t},setLocationTimeout:function(t){(function(t){return Number.isInteger(t)&&y(t)})(t)||f.throwValidationError("Location timeout must be a positive integer number"),p.remoteConfig.oneShot.timeout=t}},credentials:{setUserToken:function(t){(function(t){return!!b(t)&&new RegExp(/^[0-9A-Za-z]{7,20}$/i).test(t)})(t)||f.throwValidationError("userToken must be an alphanumeric string 7-20 characters long"),p.userToken=t},clearUserToken:function(){delete p.userToken}},initialize:function(t,r){return e.__awaiter(void 0,void 0,void 0,(function(){return e.__generator(this,(function(e){return function(t){return!!b(t)&&new RegExp(/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i).test(t)}(t)||f.throwValidationError("projectId must be a valid uuid"),"notStarted"!==p.initializeStatus&&f.throwValidationError("Bluedot SDK is already initialized with projectId: "+p.projectId+". You need to call reset before initializing again"),[2,O(t,r)]}))}))},reset:function(){p.reset()},setLocationEnabled:function(t){C(t,"locationEnabled"),p.locationEnabled=t,!0===t&&("undefined"==typeof navigator&&f.throwLocationAPINotAvailableError(),navigator.geolocation.getCurrentPosition((function(t){return l("Current location",t)})))}},exports.createHelloModel=function(){return{setCustomerName:k,setCustomDataField:T,setEventType:A,setMobileNumber:N,setOrderId:R,convertToDataObject:j,setDisplayedCustomDataField:L}}; | ||
"use strict";var t,e=require("tslib"),r=require("events"),o=require("uuid"),n=(t=require("axios"))&&"object"==typeof t&&"default"in t?t.default:t,i=function(){var t=new WeakMap;return function(e){return t.has(e)||t.set(e,{}),t.get(e)}},a=!1;function s(t,e,r){a&&(e&&r?t(e,r):t(e||r||new Error("Error logger called. See stack trace for details")))}var c=function(t,e){return s(console.error,t,e)},u=function(t,e){return s(console.warn,t,e)},l=function(t,e){return s(console.log,t,e)},d={ValidationError:"ValidationError",NetworkRetriesExceededError:"NetworkRetriesExceededError",UnexpectedServerError:"UnexpectedServerError",InvalidInputTypeError:"InvalidInputTypeError",RequiredValueMissingError:"RequiredValueMissingError",SdkNotInitializedError:"SdkNotInitializedError",ProjectIdNotFoundError:"ProjectIdNotFoundError",NotFoundError:"NotFoundError",InterruptedByResetError:"InterruptedByResetError",LocationAPINotAvailableError:"LocationAPINotAvailableError",RetryAttemptFailedError:"RetryAttemptFailedError"},f={createError:function(t,e,r){var o=new Error(e);o.name=t;var n=o;return n.errorObject=r,u(e,n),n},throwInvalidInputTypeError:function(t,e){throw this.createError(d.InvalidInputTypeError,null!=t?t:"Invalid input type error",e)},throwNetworkRetriesExceededError:function(t,e){throw this.createError(d.NetworkRetriesExceededError,t?"Failed to communicate via network after "+t+" attempts":"Failed to communicate via network",e)},throwProjectIdNotFoundError:function(t,e){throw this.createError(d.ProjectIdNotFoundError,t?"Project with ID: "+t+" not found":"Project ID not found",e)},throwRequiredValueMissingError:function(t,e){throw this.createError(d.RequiredValueMissingError,t?"Cannot trigger event. Missing required value: "+t:"Cannot trigger event. Missing required value",e)},throwSdkNotInitializedError:function(t,e){throw this.createError(d.SdkNotInitializedError,null!=t?t:"SDK is not initialized with a valid projectId",e)},throwUnexpectedServerError:function(t,e){throw this.createError(d.UnexpectedServerError,null!=t?t:"An unexpected server error occurred. Check the attached errorObject for more details",e)},throwValidationError:function(t,e){throw this.createError(d.ValidationError,null!=t?t:"Invalid input was detected",e)},throwNotFoundError:function(t,e){throw this.createError(d.NotFoundError,null!=t?t:"Not found",e)},throwInterruptedByResetError:function(t,e){throw this.createError(d.InterruptedByResetError,null!=t?t:"Interrupted by reset",e)},throwLocationAPINotAvailableError:function(t,e){throw this.createError(d.LocationAPINotAvailableError,null!=t?t:"Location API is not available",e)},createRetryAttemptFailedError:function(t,r){var o=this.createError(d.RetryAttemptFailedError,"Retry attempt "+t+" failed",r);return e.__assign(e.__assign({},o),{name:d.RetryAttemptFailedError,retryCount:t})}},h=new r.EventEmitter,v={remoteConfig:e.__assign({},{oneShot:{minAccuracy:50,targetAccuracy:20,maxAttempts:15,timeout:5e3}}),globalConfigUrl:"https://globalconfig.bluedot-gcp.com/",globalConfig:null,isInitialized:!1,initializeStatus:"notStarted",projectId:null,reset:m,addListener:E,removeListener:w,id:0,locationEnabled:!1,userPersistenceEnabled:!1,userToken:null},g=1,p=new Proxy(e.__assign({},v),{get:function(t,e){return t[e]},set:function(t,e,r){return t[e]=r,h.emit("stateUpdated",e),!0}});function m(){return Object.assign(p,v),p.reset=m,p.addListener=E,p.removeListener=w,p.id=g++,h.emit("stateReset"),h.removeAllListeners(),p}function E(t){return l("Adding state listener"),h.on("stateUpdated",t)}function w(t){h.removeListener("stateUpdated",t)}m();var b=function(t){return"string"==typeof t},y=function(t){return"number"==typeof t&&t>0},_=function(t,e){b(t)||f.throwInvalidInputTypeError(e+" must be a string")},I=function(t,e){_(t,"fieldName"),_(e,"fieldValue"),function(t){var e=["customername","orderid","eventtype","mobilenumber"],r=t.replace(/\s+/g,"");return t.toLowerCase().startsWith("hs_")?e.includes(r.slice(3).toLowerCase()):e.includes(r.toLowerCase())}(t)&&f.throwValidationError(t+" is a reserved keyword for Hello Screens. Use the helloModel method instead to set this value")},C=function(t,e){(function(t){return"boolean"==typeof t})(t)||f.throwInvalidInputTypeError(e+" must be a boolean")},S=i();function R(t){return _(t,"orderId"),S(this).orderId=t,this}function N(t){var e=function(t){var e;"string"==typeof t?e=t:"number"==typeof t&&(e=t.toString()),e||f.throwInvalidInputTypeError("mobileNumber must be a string");var r,o,n=e.replace(/ /g,"").replace(/-/g,"");return r=n,o=new RegExp(/^\+?[0-9]+$/),"string"==typeof r&&o.test(r)||f.throwValidationError("Invalid mobileNumber found. mobileNumber can only contain numerals or a leading + character"),n}(t);return S(this).mobileNumber=e,this}function A(t){return function(t){return!!b(t)&&["arrival","onTheWay"].includes(t)}(t)||f.throwValidationError("Invalid eventType found. eventType can only be 'arrival' or 'onTheWay'"),S(this).eventType=t,this}function k(t){return _(t,"customerName"),S(this).customerName=t,this}function T(t,e){I(t,e),function(t){t.toLowerCase().startsWith("hs_")&&f.throwValidationError("The hs_ prefix is reserved for fields that are displayed in Hello Screens. Use the setDisplayedCustomDataField method to set these values")}(t);var r=S(this).customFields;return void 0===r&&(r={},S(this).customFields=r),r[t]=e,this}function L(t,e){I(t,e);var r=S(this).displayedCustomFields;void 0===r&&(r={},S(this).displayedCustomFields=r);var o=r;return t.toLowerCase().startsWith("hs_")?o["hs_"+t.slice(3)]=e:o["hs_"+t]=e,this}function j(){var t=S(this),r=t.eventType,o=t.mobileNumber,n=t.customerName,i=t.orderId,a=t.customFields,s=t.displayedCustomFields;i||f.throwRequiredValueMissingError("orderId"),r||f.throwRequiredValueMissingError("eventType");var c=s,u=e.__assign(e.__assign({},a),c);return r&&(u.hs_eventType=r),i&&(u.hs_orderId=i),n&&(u.hs_customerName=n),o&&(u["hs_Mobile Number"]=o),u}n.interceptors.response.use(void 0,(function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,o;return e.__generator(this,(function(e){switch(e.label){case 0:if(!t.config.retries)throw t;if(o=t.response&&t.response.status>499&&t.response.status<600,!(r="ENOTFOUND"===t.code||"Network Error"===t.message)&&!o||t.config.isRetryRequest||(t.config.isRetryRequest=!0,t.config.retryCount=0),void 0===t.config.retryCount)throw t;return(r||o)&&t.config.retryCallback&&t.config.retryCallback(f.createRetryAttemptFailedError(t.config.retryCount,t)),(r||o)&&t.config.retryCount<t.config.retries?(l("Retry count: "+t.config.retryCount),[4,(i=Math.floor(100*Math.pow(t.config.retryCount,2))+Math.floor(100*Math.random()),new Promise((function(t){return setTimeout(t,i)})))]):[3,2];case 1:return e.sent(),t.config.retryCount+=1,[2,n(t.config)];case 2:throw t}var i}))}))}));var U=function(t,r,o){return e.__awaiter(void 0,void 0,void 0,(function(){var i;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,n.post(t,r,o)];case 1:return[2,e.sent()];case 2:if((i=e.sent()).config.retryCount&&i.config.retryCount>=i.config.retries)throw f.throwNetworkRetriesExceededError(i.config.retryCount,i);if(i.response&&400===i.response.status)throw f.throwValidationError("Bad request",i);throw f.throwUnexpectedServerError(void 0,i);case 3:return[2]}}))}))},F=function(t,r){return e.__awaiter(void 0,void 0,void 0,(function(){var o;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,n.get(t,r)];case 1:return[2,e.sent()];case 2:if((o=e.sent()).config.retryCount&&o.config.retryCount>=o.config.retries)throw f.throwNetworkRetriesExceededError(o.config.retryCount,o);throw f.throwUnexpectedServerError(void 0,o);case 3:return[2]}}))}))},P=function(t,r){return e.__awaiter(void 0,void 0,void 0,(function(){var o,n;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,F(""+p.globalConfigUrl+t+".json",{retries:p.remoteConfig.oneShot.maxAttempts,retryCallback:null==r?void 0:r.retryCallback,headers:{Origin:"force-cors-response"}})];case 1:return[2,e.sent()];case 2:if((o=e.sent()).name&&"UnexpectedServerError"===o.name&&(n=o.errorObject).response&&(404===n.response.status||403===n.response.status))throw f.throwProjectIdNotFoundError(void 0,o);throw o;case 3:return[2]}}))}))},x=function(){return!!global.localStorage},z=function(t,e){if(x()){var r=global.localStorage.getItem("installRefs"),o={};r&&(o=JSON.parse(r)),o[t]=e,global.localStorage.setItem("installRefs",JSON.stringify(o)),l("Storing installRef: "+e+" for projectId: "+t)}else u("localStorage object not found")},O=function(t,r){return e.__awaiter(void 0,void 0,void 0,(function(){var n,i,a,s;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),n=p.id,p.projectId=t,p.initializeStatus="inProgress",function(t){if(null!=t){"object"!=typeof t&&f.throwValidationError("InitializeOptions is not an object");var e=["retryCallback"],r=[];Object.keys(t).forEach((function(t){e.includes(t)||r.push(t)})),r.length>0&&f.throwValidationError("Invalid options parameters ["+r+"]")}}(r),[4,P(t,r)];case 1:if(i=e.sent(),n!==p.id)throw f.throwInterruptedByResetError();return p.isInitialized=!0,p.initializeStatus="completed",x()&&((a=function(t){if(!x())return u("localStorage object not found"),null;var e=global.localStorage.getItem("installRefs");return e?JSON.parse(e)[t]:null}(t))?(p.installRef=a,l("Using stored installRef: "+a)):(p.installRef=o.v4(),p.userPersistenceEnabled&&z(t,p.installRef))),p.globalConfig=i.data,[3,3];case 2:throw s=e.sent(),p.initializeStatus="failed",c("An error occurred during initialization",s),s;case 3:return[2]}}))}))},V=new(function(){function t(){var t=this;this.emitter=new r.EventEmitter,this.emitter.on("locationError",(function(t){c("Failed to get positon",t)})),this.emitter.on("removeListener",(function(e){"locationUpdate"===e&&0===t.emitter.listenerCount("locationUpdate")&&null!=t.handlerId&&(l("Remove locationUpdate"),navigator.geolocation.clearWatch(t.handlerId))}))}return t.prototype.getUpdatedPosition=function(t){var e=this;"locationUpdate"===t&&(this.handlerId=navigator.geolocation.watchPosition((function(t){l("Emitting",t),e.emitter.emit("locationUpdate",t)}),(function(t){e.emitter.emit("locationError",t),e.emitter.emit("locationUpdate")}),{enableHighAccuracy:!0,maximumAge:5e3}))},t.prototype.addListener=function(t){l("Adding locationUpdate listener."),this.emitter.on("locationUpdate",t),this.getUpdatedPosition("locationUpdate")},t.prototype.removeListener=function(t){this.emitter.removeListener("locationUpdate",t)},t}()),D=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,o,n,i;return e.__generator(this,(function(a){switch(a.label){case 0:return r=function(){if(p.globalConfig){var t=p.globalConfig.eventsApiUrl;if(t)return t;throw new Error("Project does not have Events Api Url")}throw f.throwSdkNotInitializedError()}(),o={headers:{"x-bluedot-api-key":p.projectId},retries:p.remoteConfig.oneShot.maxAttempts,retryCallback:t.retryCallback},n=e.__assign({},t.notification),p&&p.installRef&&(n.installRef=p.installRef),(null==p?void 0:p.userToken)&&(n.userToken=p.userToken),t.location&&t.location.longitude&&t.location.latitude&&(n.location=(c={longitude:(s=t.location).longitude,latitude:s.latitude,horizontalAccuracy:s.accuracy},s.speed&&(c.speed=s.speed),s.heading&&(c.bearing=s.heading),c)),[4,U(r+"wave",n,o)];case 1:return i=a.sent(),l("Event sent"),[2,i]}var s,c}))}))},M=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){return e.__generator(this,(function(e){return t.notificationType&&"wave"===t.notificationType?[2,D(t)]:[2]}))}))},q=function(){function t(t,r,o){this.attemptCount=0,this.bestEffort=null,this.isClosed=!1,this.notification=e.__assign({},t),this.notificationType=r,this.options=o}return t.prototype.trigger=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(t){return"failed"!==p.initializeStatus&&"notStarted"!==p.initializeStatus||f.throwSdkNotInitializedError(),p.locationEnabled?[2,this.trackAndSendLocation()]:[2,this.sendEvent()]}))}))},t.prototype.sendEvent=function(){var t;return e.__awaiter(this,void 0,void 0,(function(){var r=this;return e.__generator(this,(function(o){return++this.attemptCount>1?(l("Previous event is in progress. Ignoring retrigger"),[2,null]):p.globalConfig?(l("Target region identified"),l("Sending event"),[2,M({notification:this.notification,notificationType:this.notificationType,location:this.bestEffort,retryCallback:null===(t=this.options)||void 0===t?void 0:t.retryCallback})]):[2,new Promise((function(t,o){l("Target region identification in progress. Listening..."),p.addListener((function n(i){return e.__awaiter(r,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){return l("State event emitted "+i),p.globalConfig?(l("Target region found. Sending event"),p.removeListener(n),M({notification:this.notification,notificationType:this.notificationType,location:this.bestEffort,retryCallback:null===(r=this.options)||void 0===r?void 0:r.retryCallback}).then(t).catch(o)):"failed"===p.initializeStatus?(p.removeListener(n),o(f.createError(d.SdkNotInitializedError,"SDK failed to initialize"))):l("No target region found."),[2]}))}))}))}))]}))}))},t.prototype.attemptSendEvent=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(t){switch(t.label){case 0:return[4,this.sendEvent()];case 1:return t.sent(),this.closeLocationPolling(),[2]}}))}))},t.prototype.closeLocationPolling=function(){!this.isClosed&&this.listener&&V.removeListener(this.listener),this.isClosed=!0},t.prototype.trackAndSendLocation=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(r){return[2,new Promise((function(r){l("OneShotService: Adding location listener"),t.listener=function(o){return e.__awaiter(t,void 0,void 0,(function(){var t,n=this;return e.__generator(this,(function(e){return l("OneShotService: Received position",o),o&&o.coords&&o.coords.accuracy?null==this.bestEffort||this.bestEffort.accuracy&&this.bestEffort.accuracy<o.coords.accuracy?(o.coords.accuracy<p.remoteConfig.oneShot.minAccuracy&&(this.bestEffort=o.coords),p.isInitialized&&o.coords.accuracy<p.remoteConfig.oneShot.minAccuracy?r(this.attemptSendEvent()):(t=function(e){"isInitialized"===e&&(o.coords.accuracy&&o.coords.accuracy<p.remoteConfig.oneShot.minAccuracy&&r(n.attemptSendEvent()),p.removeListener(t))},p.addListener(t))):l("Lower accuracy than best effort, ignored."):r(this.attemptSendEvent()),[2]}))}))},V.addListener(t.listener),setTimeout((function(){return e.__awaiter(t,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isClosed?[3,2]:(l("Send event on location timeout"),this.closeLocationPolling(),t=r,[4,this.sendEvent()]);case 1:t.apply(void 0,[e.sent()]),e.label=2;case 2:return[2]}}))}))}),p.remoteConfig.oneShot.timeout)}))]}))}))},t}(),B=new(function(){function t(){}return t.prototype.triggerOneShot=function(t,r,o){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,new q(t,r,o).trigger()]}))}))},t}());exports.bluedot={wave:{send:function(t,r,o){return e.__awaiter(void 0,void 0,void 0,(function(){var n,i,a,s;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),_(t,"destinationId"),function(t){if(null!=t){"object"!=typeof t&&f.throwValidationError("WaveOptions is not an object");var e=["retryCallback"],r=[];Object.keys(t).forEach((function(t){e.includes(t)||r.push(t)})),r.length>0&&f.throwValidationError("Invalid options parameters ["+r+"]")}}(o),(n={destinationId:t,eventTime:new Date(Date.now()).toISOString()}).customEventMetaData=r&&Object.prototype.hasOwnProperty.call(r,"convertToDataObject")?r.convertToDataObject():r,[4,B.triggerOneShot(n,"wave",o)];case 1:return e.sent(),[3,3];case 2:if(i=e.sent(),!Object.values(d).includes(i.name))throw f.throwUnexpectedServerError(void 0,i);if(i.errorObject&&(a=i.errorObject).response&&404===a.response.status&&(s=new RegExp(/destinationId/i),a.response&&a.response.data&&a.response.data.errorCauses&&a.response.data.errorCauses.length&&a.response.data.errorCauses[0].message.match(s)))throw f.throwNotFoundError("Zone with destinationId: "+t+" not found",i);throw i;case 3:return[2]}}))}))}},config:{setConfigurationDomain:function(t){t?(function(t){if(b(t))try{var e=new URL(t);return Boolean(e)}catch(t){c(t)}return!1}(t)||f.throwValidationError("BDGlobalConfigUrl must be a valid URL"),p.globalConfigUrl=t):p.globalConfigUrl="https://globalconfig.bluedot-gcp.com/"},setUserPersistenceEnabled:function(t){C(t,"enabled"),x()?(p.userPersistenceEnabled=t,t?p.projectId&&p.installRef&&z(p.projectId,p.installRef):(x()?global.localStorage.removeItem("installRefs"):u("localStorage object not found"),delete p.installRef)):u("User persistence is not available in this environment")},setDebugModeEnabled:function(t){C(t,"enabled"),function(t){a=t}(t)},setLocationMinimumAccuracy:function(t){y(t)||f.throwValidationError("Location accuracy must be a positive number"),p.remoteConfig.oneShot.minAccuracy=t},setLocationTimeout:function(t){(function(t){return Number.isInteger(t)&&y(t)})(t)||f.throwValidationError("Location timeout must be a positive integer number"),p.remoteConfig.oneShot.timeout=t}},credentials:{setUserToken:function(t){(function(t){return!!b(t)&&new RegExp(/^[0-9A-Za-z]{7,20}$/i).test(t)})(t)||f.throwValidationError("userToken must be an alphanumeric string 7-20 characters long"),p.userToken=t},clearUserToken:function(){delete p.userToken}},initialize:function(t,r){return e.__awaiter(void 0,void 0,void 0,(function(){return e.__generator(this,(function(e){return function(t){return!!b(t)&&new RegExp(/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i).test(t)}(t)||f.throwValidationError("projectId must be a valid uuid"),"notStarted"!==p.initializeStatus&&f.throwValidationError("Bluedot SDK is already initialized with projectId: "+p.projectId+". You need to call reset before initializing again"),[2,O(t,r)]}))}))},reset:function(){p.reset()},setLocationEnabled:function(t){C(t,"locationEnabled"),p.locationEnabled=t,!0===t&&("undefined"==typeof navigator&&f.throwLocationAPINotAvailableError(),navigator.geolocation.getCurrentPosition((function(t){return l("Current location",t)})))}},exports.createHelloModel=function(){return{setCustomerName:k,setCustomDataField:T,setEventType:A,setMobileNumber:N,setOrderId:R,convertToDataObject:j,setDisplayedCustomDataField:L}}; | ||
//# sourceMappingURL=javascript-sdk.cjs.production.min.js.map |
@@ -156,3 +156,3 @@ import { __assign, __awaiter, __generator } from 'tslib'; | ||
remoteConfig: /*#__PURE__*/__assign({}, defaultRemoteConfig), | ||
globalConfigUrl: 'https://globalconfig.bluedot.io/', | ||
globalConfigUrl: 'https://globalconfig.bluedot-gcp.com/', | ||
globalConfig: null, | ||
@@ -1309,3 +1309,3 @@ isInitialized: false, | ||
var GLOBAL_CONFIG_URL = 'https://globalconfig.bluedot.io/'; | ||
var GLOBAL_CONFIG_URL = 'https://globalconfig.bluedot-gcp.com/'; | ||
var config = { | ||
@@ -1312,0 +1312,0 @@ setConfigurationDomain: function setConfigurationDomain(BDGlobalConfigUrl) { |
{ | ||
"name": "@bluedot-innovation/javascript-sdk", | ||
"version": "1.3.3", | ||
"version": "1.3.4-alpha", | ||
"description": "", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
299919
3