@analytics/aws-pinpoint
Advanced tools
Comparing version 0.5.2 to 0.5.3
@@ -6,2 +6,10 @@ # Change Log | ||
## [0.5.3](https://github.com/DavidWells/analytics/compare/@analytics/aws-pinpoint@0.5.2...@analytics/aws-pinpoint@0.5.3) (2021-04-19) | ||
**Note:** Version bump only for package @analytics/aws-pinpoint | ||
## [0.5.2](https://github.com/DavidWells/analytics/compare/@analytics/aws-pinpoint@0.5.1...@analytics/aws-pinpoint@0.5.2) (2021-04-19) | ||
@@ -8,0 +16,0 @@ |
@@ -1,1 +0,1 @@ | ||
var analyticsAWSPinpoint=function(e){"use strict";function t(e,t,n,r,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,s)}function n(e){return function(){var n=this,r=arguments;return new Promise(function(s,i){var o=e.apply(n,r);function a(e){t(o,s,i,a,c,"next",e)}function c(e){t(o,s,i,a,c,"throw",e)}a(void 0)})}}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?s(n,!0).forEach(function(t){r(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):s(n).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var o=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===a}(e)}(e)};var a="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function c(e,t){return!1!==t.clone&&t.isMergeableObject(e)?h((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function u(e,t,n){return e.concat(t).map(function(e){return c(e,n)})}function d(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return e.propertyIsEnumerable(t)}):[]}(e))}function p(e,t){try{return t in e}catch(e){return!1}}function l(e,t,n){var r={};return n.isMergeableObject(e)&&d(e).forEach(function(t){r[t]=c(e[t],n)}),d(t).forEach(function(s){(function(e,t){return p(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,s)||(p(e,s)&&n.isMergeableObject(t[s])?r[s]=function(e,t){if(!t.customMerge)return h;var n=t.customMerge(e);return"function"==typeof n?n:h}(s,n)(e[s],t[s],n):r[s]=c(t[s],n))}),r}function h(e,t,n){(n=n||{}).arrayMerge=n.arrayMerge||u,n.isMergeableObject=n.isMergeableObject||o,n.cloneUnlessOtherwiseSpecified=c;var r=Array.isArray(t);return r===Array.isArray(e)?r?n.arrayMerge(e,t,n):l(e,t,n):c(t,n)}h.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,n){return h(e,n,t)},{})};var f=h;function g(e,t,n,r,s,i){if("undefined"!=typeof window)return arguments.length>1?document.cookie=e+"="+encodeURIComponent(t)+(n?"; expires="+new Date(+new Date+1e3*n).toUTCString()+(r?"; path="+r:"")+(s?"; domain="+s:"")+(i?"; secure":""):""):decodeURIComponent((("; "+document.cookie).split("; "+e+"=")[1]||"").split(";")[0])}function m(e){return(m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}"object"===("undefined"==typeof self?"undefined":m(self))&&self.self===self&&self||"object"===("undefined"==typeof global?"undefined":m(global))&&global.global===global&&global,function(){try{g("_c_","1");var e=-1!==document.cookie.indexOf("_c_");g("_c_","",-1)}catch(e){return!1}}();function y(){for(var e="",t=0,n=4294967295*Math.random()|0;t++<36;){var r="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[t-1],s=15&n;e+="-"==r||"4"==r?r:("x"==r?s:3&s|8).toString(16),n=t%8==0?4294967295*Math.random()|0:n>>4}return e}const v=new TextEncoder,b={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},w=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"];class S{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:n,service:r,region:s,cache:i,retries:o,initRetryMs:a}){if(null==e)throw new TypeError("accessKeyId is a required option");if(null==t)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=n,this.service=r,this.region=s,this.cache=i||new Map,this.retries=null!=o?o:10,this.initRetryMs=a||50}async sign(e,t){if(e instanceof Request){const{method:n,url:r,headers:s,body:i}=e;null==(t=Object.assign({method:n,url:r,headers:s},t)).body&&s.has("Content-Type")&&(t.body=null!=i&&s.has("X-Amz-Content-Sha256")?i:await e.clone().arrayBuffer()),e=r}const n=new A(Object.assign({url:e},t,this,t&&t.aws)),r=Object.assign({},t,await n.sign());return delete r.aws,new Request(r.url.toString(),r)}async fetch(e,t){for(let n=0;n<=this.retries;n++){const r=fetch(await this.sign(e,t));if(n===this.retries)return r;const s=await r;if(s.status<500&&429!==s.status)return s;await new Promise(e=>setTimeout(e,Math.random()*this.initRetryMs*Math.pow(2,n)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class A{constructor({method:e,url:t,headers:n,body:r,accessKeyId:s,secretAccessKey:i,sessionToken:o,service:a,region:c,cache:u,datetime:d,signQuery:p,appendSessionToken:l,allHeaders:h,singleEncode:f}){if(null==t)throw new TypeError("url is a required option");if(null==s)throw new TypeError("accessKeyId is a required option");if(null==i)throw new TypeError("secretAccessKey is a required option");let g,m;this.method=e||(r?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(n||{}),this.body=r,this.accessKeyId=s,this.secretAccessKey=i,this.sessionToken=o,a&&c||([g,m]=function(e,t){const{hostname:n,pathname:r}=e,s=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/);let[i,o]=(s||["",""]).slice(1,3);if("us-gov"===o)o="us-gov-west-1";else if("s3"===o||"s3-accelerate"===o)o="us-east-1",i="s3";else if("iot"===i)i=n.startsWith("iot.")?"execute-api":n.startsWith("data.jobs.iot.")?"iot-jobs-data":"/mqtt"===r?"iotdevicegateway":"iotdata";else if("autoscaling"===i){const e=(t.get("X-Amz-Target")||"").split(".")[0];"AnyScaleFrontendService"===e?i="application-autoscaling":"AnyScaleScalingPlannerFrontendService"===e&&(i="autoscaling-plans")}else null==o&&i.startsWith("s3-")?(o=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):o&&/-\d$/.test(i)&&!/-\d$/.test(o)&&([i,o]=[o,i]);return[b[i]||i,o]}(this.url,this.headers)),this.service=a||g||"",this.region=c||m||"us-east-1",this.cache=u||new Map,this.datetime=d||(new Date).toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=p,this.appendSessionToken=l||"iotdevicegateway"===this.service,this.headers.delete("Host");const y=this.signQuery?this.url.searchParams:this.headers;if("s3"!==this.service||this.headers.has("X-Amz-Content-Sha256")||this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),y.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&y.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(e=>h||!w.includes(e)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(e=>e+":"+("host"===e?this.url.host:(this.headers.get(e)||"").replace(/\s+/g," "))).join("\n"),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&("s3"!==this.service||y.has("X-Amz-Expires")||y.set("X-Amz-Expires","86400"),y.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),y.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),y.set("X-Amz-SignedHeaders",this.signedHeaders)),"s3"===this.service)try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(e){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");f||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=k(this.encodedPath);const v=new Set;this.encodedSearch=[...this.url.searchParams].filter(([e])=>{if(!e)return!1;if("s3"===this.service){if(v.has(e))return!1;v.add(e)}return!0}).map(e=>e.map(e=>k(encodeURIComponent(e)))).sort(([e,t],[n,r])=>e<n?-1:e>n?1:t<r?-1:t>r?1:0).map(e=>e.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){const e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join();let n=this.cache.get(t);if(!n){const r=await x("AWS4"+this.secretAccessKey,e),s=await x(r,this.region),i=await x(s,this.service);n=await x(i,"aws4_request"),this.cache.set(t,n)}return E(await x(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,E(await I(await this.canonicalString()))].join("\n")}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+"\n",this.signedHeaders,await this.hexBodyHash()].join("\n")}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(null==e){if(this.body&&"string"!=typeof this.body&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=E(await I(this.body||""))}return e}}async function x(e,t){const n=await crypto.subtle.importKey("raw","string"==typeof e?v.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,v.encode(t))}async function I(e){return crypto.subtle.digest("SHA-256","string"==typeof e?v.encode(e):e)}function E(e){return Array.prototype.map.call(new Uint8Array(e),e=>("0"+e.toString(16)).slice(-2)).join("")}function k(e){return e.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}function O(e){return(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})[e]||e}var P=["PUSH","GCM","APNS","APNS_SANDBOX","APNS_VOIP","APNS_VOIP_SANDBOX","ADM","SMS","VOICE","EMAIL","BAIDU","CUSTOM"].reduce(function(e,t){return e[t]=t,e},{}),T="_session.start",M="_session.stop",j="pageView",C=Object.freeze({SESSION_START:T,SESSION_STOP:M,SESSION_PAUSE:"_session.pause",SESSION_RESUME:"_session.resume",AUTH_SIGN_IN:"_userauth.sign_in",AUTH_SIGN_UP:"_userauth.sign_up",AUTH_FAIL:"_userauth.auth_fail",ECOM_PURCHASE:"_monetization.purchase",PAGE_VIEW:j}),U=("undefined"!=typeof navigator&&navigator&&navigator.sendBeacon,"__endpoint"),_=[429,500],R=[202],D=400,H="undefined"!=typeof window,N=function(){if("undefined"==typeof window)return{};if(!window.navigator)return{};var e,t,n,r,s,i=window.navigator,o=i.platform,a=i.product,c=i.vendor,u=function(e){var t=/.+(Opera[\s[A-Z]*|OPR[\sA-Z]*)\/([0-9\.]+).*/i.exec(e);if(t)return{type:t[1],version:t[2]};var n=/.+(Trident|Edge)\/([0-9\.]+).*/i.exec(e);if(n)return{type:n[1],version:n[2]};var r=/.+(Chrome|Firefox|FxiOS)\/([0-9\.]+).*/i.exec(e);if(r)return{type:r[1],version:r[2]};var s=/.+(Safari)\/([0-9\.]+).*/i.exec(e);if(s)return{type:s[1],version:s[2]};var i=/.+(AppleWebKit)\/([0-9\.]+).*/i.exec(e);if(i)return{type:i[1],version:i[2]};var o=/.*([A-Z]+)\/([0-9\.]+).*/i.exec(e);return o?{type:o[1],version:o[2]}:{type:"",version:""}}(i.userAgent);return{platform:o,make:c||a,model:u.type,version:u.version,appVersion:[u.type,u.version].join("/"),language:(t=window.navigator,n=t.language,r=t.browserLanguage,s=t.languages,(n||r||(s||["en_US"])[0]).toLowerCase().replace("-","_")),timezone:(e=/\(([A-Za-z\s].*)\)/.exec((new Date).toString()),e&&e[1]||"")}}(),K=[];function z(){return{}}var V=/.+\@.+\..+/;function X(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=i({getContext:e.getContext||z,enrichEventAttributes:e.enrichEventAttributes||z,enrichEventMetrics:e.enrichEventMetrics||z,credentials:e.credentials||{},getEndpointId:e.getEndpointId},e),r=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.getEndpointId,r=e.debug;return function(){var s=n(regeneratorRuntime.mark(function n(){var s,o,a,c,u,d,p,l=arguments;return regeneratorRuntime.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:if(s=l.length>0&&void 0!==l[0]?l[0]:{},K.length||Object.keys(s).length){n.next=4;break}return r&&console.log("No events, return early"),n.abrupt("return");case 4:return o=s,n.next=7,t();case 7:if(a=n.sent,r&&console.log("resolved endpointId",a),a){n.next=12;break}return console.error("No User ID found. Call Auth()"),n.abrupt("return");case 12:if(!Object.entries(s).length){n.next=18;break}return n.next=15,Y(s,e);case 15:o=n.sent,n.next=19;break;case 18:o=q(a)||{};case 19:return r&&console.log("endpointData",o),c=o.ChannelType,o.Address&&(h=o.Address,V.test(h))&&(c=P.EMAIL),!c&&o.Address&&(c="android"===N.platform?c||P.GCM:c||P.APNS),r&&console.log("CHANNEL_TYPE",c),u=K.reduce(function(e,t){return i({},t,{},e)},{}),(d=o).RequestId=y(),d.ChannelType=c,d.Address&&(d.OptOut=o.OptOut||"NONE"),p=B(a,d,u),n.prev=30,n.next=33,Q(p,e);case 33:n.sent,n.next=39;break;case 36:n.prev=36,n.t0=n.catch(30),console.log("callPinPoint err",n.t0);case 39:return K=[],n.abrupt("return",o);case 41:case"end":return n.stop()}var h},n,null,[[30,36]])}));return function(){return s.apply(this,arguments)}}()}(t),s=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.sentDataToPinpoint;return function(){var s=n(regeneratorRuntime.mark(function n(s){var i,o,a,c,u=arguments;return regeneratorRuntime.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return i=u.length>1&&void 0!==u[1]?u[1]:{},o=u.length>2&&void 0!==u[2]?u[2]:{},a=!(u.length>3&&void 0!==u[3])||u[3],"boolean"==typeof i&&(a=i,i={}),"boolean"==typeof o&&(a=o,o={}),n.next=7,F(s,i,t);case 7:if(c=n.sent,!Object.entries(o).length&&s!==j){n.next=12;break}return n.next=11,Y(o,t);case 11:o=n.sent;case 12:K.push(c),n.next=15;break;case 15:if(a){n.next=17;break}return n.abrupt("return",r());case 17:e&&clearTimeout(e),e=setTimeout(r,3e3);case 19:case"end":return n.stop()}},n)}));return function(e){return s.apply(this,arguments)}}()}(i({sentDataToPinpoint:r},t));Y({},e);var o=function(e){if(!H)return z;var t=function(e){return function(){console.log("Fire stop session"),e(M,!1)}}(e);return window.addEventListener("beforeunload",t),function(){return window.removeEventListener("beforeunload",t)}}(s);return{updateEndpoint:r,recordEvent:s,disable:function(){o()}}}function L(e){return"".concat(U,".").concat(e)}function q(e){var t={};try{t=JSON.parse(localStorage.getItem(L(e)))||{}}catch(e){}return t}function W(e,t){var n=L(e),r="string"==typeof t?t:JSON.stringify(t);localStorage.setItem(n,r)}function B(e,t,n){return{BatchItem:r({},e,{Endpoint:t,Events:n})}}function F(e){return G.apply(this,arguments)}function G(){return(G=n(regeneratorRuntime.mark(function e(t){var n,s,o,a,c,u,d,p,l,h,f,g,m,v,b,w,S,A,x,I,E,k,P,T,j,C,U,_,R,D,H,N=arguments;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=N.length>1&&void 0!==N[1]?N[1]:{},s=N.length>2&&void 0!==N[2]?N[2]:{},o=s.appTitle,a=s.appPackageName,c=s.appVersionCode,u=s.eventMapping,d=s.getSessionID,p=s.enrichEventAttributes,l=s.enrichEventMetrics,h=s.debug,f=O(t,u),g=ne(s),m=g.pageSession,v=g.subSessionId,b=g.subSessionStart,w=g.elapsed,S=n.attributes||{},A=n.eventId||y(),x=n.time?new Date(n.time):new Date,I=x.toISOString(),E=n.sessionId||d(),k={date:I,session:E,pageSession:m},e.next=14,p();case 14:return P=e.sent,T=i({},k,{},P,{},S),j=w+(x.getTime()-b),C=n.metrics||{},U={sessionTime:j,hour:x.getHours(),day:x.getDay()+1,month:x.getMonth()+1,year:x.getFullYear()},e.next=21,l();case 21:return _=e.sent,R=i({},U,{},_,{},C),e.next=25,oe(T);case 25:return e.t0=e.sent,e.next=28,ue(R);case 28:return e.t1=e.sent,D={attributes:e.t0,metrics:e.t1},h&&(console.log("".concat(A,":").concat(f)),console.log("eventAttributes",D.attributes),console.log("eventMetrics",D.metrics)),H=r({},A,{EventType:f,Timestamp:I,AppPackageName:a,AppTitle:o,AppVersionCode:c,Attributes:D.attributes,Metrics:D.metrics,Session:{Id:v,StartTimestamp:new Date(b).toISOString()}}),t===M&&(H[A].Session.Duration=Date.now()-b,H[A].Session.StopTimestamp=I),e.abrupt("return",H);case 34:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Q(e,t){return $.apply(this,arguments)}function $(){return($=n(regeneratorRuntime.mark(function e(t,n){var r,s,i,o,a,c,u,d,p,l,h,f,g,m,y,v;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=n.pinpointRegion,n.pinpointEndpoint,s=n.pinpointAppId,i=n.lambdaArn,o=n.lambdaRegion,a=n.credentials,c=n.getCredentials,u=n.debug,d=a,Object.keys(d).length||!c){e.next=12;break}return e.prev=3,e.next=6,c();case 6:d=e.sent,e.next=12;break;case 9:throw e.prev=9,e.t0=e.catch(3),new Error(e.t0);case 12:return p=new S({accessKeyId:d.accessKeyId||d.AccessKeyId,secretAccessKey:d.secretAccessKey||d.SecretKey,sessionToken:d.sessionToken||d.SessionToken,retries:5}),l=o||r,h=r||o,f=!0===n.fips?"-fips":"",g="https://lambda.".concat(l,".amazonaws.com/2015-03-31/functions/").concat(i,"/invocations"),m="https://pinpoint".concat(f,".").concat(h,".amazonaws.com/v1/apps/").concat(s,"/events"),y=i?g:m,e.next=21,p.fetch(y,{body:JSON.stringify(t)}).then(function(e){return e.json()});case 21:return(v=e.sent)&&v.Results&&Object.keys(v.Results).map(function(e){return v.Results[e]}).forEach(function(e){var t=e.EndpointItemResponse||{},n=e.EventsItemResponse||{};Object.keys(t).length&&(u&&console.log("EndpointItemResponse",t),R.includes(t.StatusCode)||_.includes(t.StatusCode)||Z(t,Endpoint));var r=Object.keys(n);r.length&&(u&&console.log("EventsResponse",n),r.forEach(function(e){}))}),e.abrupt("return",v);case 24:case"end":return e.stop()}},e,null,[[3,9]])}))).apply(this,arguments)}function Z(e,t){var n=e.StatusCode,r=e.Message;if(n===D){if(r.startsWith("Missing ChannelType"))throw new Error("Missing ChannelType");if(r.startsWith("Exceeded maximum endpoint per user count"))throw new Error("Exceeded maximum endpoint per user count")}}var J=!1;function Y(){return ee.apply(this,arguments)}function ee(){return(ee=n(regeneratorRuntime.mark(function e(){var t,n,r,s,o,a,c,u,d,p,l,h,g,m,y,v,b,w=arguments;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=w.length>0&&void 0!==w[0]?w[0]:{},n=w.length>1&&void 0!==w[1]?w[1]:{},r=n.getUserId,s=n.getEndpointId,o=n.getSessionID,a=ne(n),e.next=6,s();case 6:if(c=e.sent,J||(J=!0,(u=localStorage.getItem(U))&&(W(c,u),localStorage.removeItem(U))),d=q(c),p=a.pageSession,l={},h={AppVersion:N.appVersion,Make:N.make,Model:N.model,ModelVersion:N.version,Platform:N.platform,Locale:N.language},g={Attributes:{},Demographic:i({AppVersion:N.appVersion||""},h,{},l.demographic),Location:{},Metrics:{}},N.device&&N.device.vendor&&(g.Attributes.DeviceMake=[N.device.vendor]),N.device&&N.device.model&&(g.Attributes.DeviceModel=[N.device.model]),N.device&&N.device.type&&(g.Attributes.DeviceType=[N.device.type]),N.engine&&N.engine.name&&(g.Demographic.Make=N.engine.name),N.browser&&N.browser.name&&(g.Demographic.Model=N.browser.name),N.browser&&N.browser.version&&(g.Demographic.ModelVersion=N.browser.version),N.os&&N.os.name&&(g.Demographic.Platform=N.os.name),N.os&&N.os.version&&(g.Demographic.PlatformVersion=N.os.version),!(t=f.all([g,d,t],{arrayMerge:te})).User||!t.User.UserId){e.next=27;break}return e.next=25,r();case 25:m=e.sent,t.User.UserId!==m&&(t.User.UserId=m);case 27:if(t.User&&t.User.UserId){e.next=32;break}return e.next=30,r();case 30:(y=e.sent)&&(t.User||(t.User={}),t.User.UserId=y);case 32:if(!t.User||!t.User.UserAttributes){e.next=36;break}return e.next=35,oe(t.User.UserAttributes,!0);case 35:t.User.UserAttributes=e.sent;case 36:return e.next=38,oe(t.Attributes,!0);case 38:return t.Attributes=e.sent,e.next=41,ue(t.Metrics);case 41:return t.Metrics=e.sent,v="sessions",a.sessionKey&&(v=a.sessionKey()),b="pageViews",a.pageViewKey&&(b=a.pageViewKey()),t.Attributes.lastSession?(t.Attributes.lastSession[0]!==o()&&(t.Attributes.lastSession=[o()],t.Metrics[v]+=1),t.Attributes.lastPageSession[0]!==p&&(t.Attributes.lastPageSession=[p],t.Metrics[b]+=1)):(t.Attributes.lastSession=[o()],t.Attributes.lastPageSession=[p],t.Metrics[v]=1,t.Metrics[b]=1),W(c,t),e.abrupt("return",t);case 49:case"end":return e.stop()}},e)}))).apply(this,arguments)}function te(e,t){return t}function ne(e){return"function"==typeof e.getContext?e.getContext():e.getContext}function re(e,t){return se.apply(this,arguments)}function se(){return(se=n(regeneratorRuntime.mark(function e(t,n){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("function"!=typeof t){e.next=4;break}return e.next=3,t();case 3:t=e.sent;case 4:return e.abrupt("return",n(t));case 5:case"end":return e.stop()}},e)}))).apply(this,arguments)}function ie(e){return Array.isArray(e)?e.map(function(e){return e.toString()}):e.toString()}function oe(e){return ae.apply(this,arguments)}function ae(){return(ae=n(regeneratorRuntime.mark(function e(t){var n,r,s,i,o=arguments;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n=o.length>1&&void 0!==o[1]&&o[1],r={},e.t0=regeneratorRuntime.keys(t);case 3:if((e.t1=e.t0()).done){e.next=17;break}if(s=e.t1.value,i=Array.isArray(t[s])?t[s]:[t[s]],!n){e.next=12;break}return e.next=9,re(i,ie);case 9:r[s]=e.sent,e.next=15;break;case 12:return e.next=14,re(i[0],ie);case 14:r[s]=e.sent;case 15:e.next=3;break;case 17:return e.abrupt("return",r);case 18:case"end":return e.stop()}},e)}))).apply(this,arguments)}function ce(e){return parseFloat(Number(Array.isArray(e)?e[0]:e))}function ue(e){return de.apply(this,arguments)}function de(){return(de=n(regeneratorRuntime.mark(function e(t){var n,r;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n={},e.t0=regeneratorRuntime.keys(t);case 2:if((e.t1=e.t0()).done){e.next=9;break}return r=e.t1.value,e.next=6,re(t[r],ce);case 6:n[r]=e.sent,e.next=2;break;case 9:return e.abrupt("return",n);case 10:case"end":return e.stop()}},e)}))).apply(this,arguments)}var pe=function(){var e=window.sessionStorage;try{return e.setItem("__test","x"),e.removeItem("__test"),!0}catch(e){return!1}}();function le(e){if("undefined"==typeof window)return!1;var t="hidden"in document?"hidden":["webkit","moz","ms","o"].reduce(function(e,t){return!e&&"".concat(t,"Hidden")in document?"".concat(t,"Hidden"):e},null);if(!t)return!1;var n="".concat(t.replace(/[H|h]idden/,""),"visibilitychange"),r=function(){return document[t]?e(!0):e(!1)};return document.addEventListener(n,r),function(){return document.removeEventListener(n,r)}}var he={disableAnonymousTraffic:!1,pinpointRegion:"us-east-1",eventMapping:{}};var fe="__session_id";function ge(){if(!pe){var e=window[fe];if(e)return e;var t=y();return window[fe]=t,t}var n=window.sessionStorage.getItem(fe);if(n)return n;var r=y();return window.sessionStorage.setItem(fe,r),r}var me=function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=0,s=y(),o=y(),a=Date.now();return{name:"aws-pinpoint",config:i({},he,{},n),bootstrap:function(e){var t=e.config,n=e.instance;t.disableAnonymousTraffic&&!n.user("userId")&&n.once("identifyStart",function(e){e.plugins["aws-pinpoint"].loaded()||n.loadPlugin("aws-pinpoint")})},initialize:function(n){var c=n.config,u=n.instance,d=c.disableAnonymousTraffic,p=u.getState(),l=(p.user||{}).userId,h=p.context||{},f=h.app,g=h.version;if(!l&&d)return!1;var m=X(i({},c,{appTitle:c.appTitle||f,appPackageName:c.appPackageName||f,appVersionCode:c.appVersionCode||g,getEndpointId:function(){return u.user("anonymousId")},getUserId:function(){return u.user("userId")},getSessionID:ge,getContext:function(){return{elapsed:r,pageSession:s,subSessionId:o,subSessionStart:a,sessionKey:c.sessionKey,pageViewKey:c.pageViewKey}},enrichEventAttributes:function(){return{hash:window.location.hash,path:window.location.pathname,referrer:document.referrer,search:window.location.search,title:document.title,host:window.location.hostname,url:window.location.origin+window.location.pathname}},enrichEventMetrics:function(){return{}},eventMapping:c.eventMapping}));e=m.recordEvent,t=m.updateEndpoint,e(T),le(function(t){t?(r+=Date.now()-a,e(M,!1)):(o=y(),a=Date.now(),e(T))})},page:function(t){t.payload,t.config,e?e(j,!0).then(function(){s=y()}):console.log("Pinpoint not loaded")},reset:function(e){var t=L(e.instance.user("anonymousId"));storage.removeItem(t)},track:function(t){var n=t.payload,r=t.config;if(t.instance,e){if(!r.disableAnonymousTraffic||n.userId){var s,i=(s=n.properties,Object.keys(s).reduce(function(e,t){var n=s[t];return"number"==typeof n&&(e.metrics[t]=n),"string"!=typeof n&&"boolean"!=typeof n||(e.attributes[t]=n),e},{attributes:{},metrics:{}}));e(n.event,i)}}else console.log("Pinpoint not loaded")},identify:function(e){var n=e.payload,r=n.userId,s=n.traits;if(t){var o={};r&&(o.UserId=r),s&&Object.keys(s).length&&(o.UserAttributes=s),t(i({},s.email?{Address:s.email,ChannelType:P.EMAIL}:{},{},Object.keys(o).length?{User:o}:{}))}else console.log("Pinpoint not loaded")},loaded:function(){return!!e}}};return e.default=me,e.PINPOINT_EVENTS=C,e.formatEvent=F,e}({}); | ||
var analyticsAWSPinpoint=function(e){"use strict";function t(e,t,n,r,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,s)}function n(e){return function(){var n=this,r=arguments;return new Promise(function(s,i){var o=e.apply(n,r);function a(e){t(o,s,i,a,c,"next",e)}function c(e){t(o,s,i,a,c,"throw",e)}a(void 0)})}}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?s(n,!0).forEach(function(t){r(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):s(n).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var o=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===a}(e)}(e)};var a="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function c(e,t){return!1!==t.clone&&t.isMergeableObject(e)?h((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function u(e,t,n){return e.concat(t).map(function(e){return c(e,n)})}function d(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return e.propertyIsEnumerable(t)}):[]}(e))}function p(e,t){try{return t in e}catch(e){return!1}}function l(e,t,n){var r={};return n.isMergeableObject(e)&&d(e).forEach(function(t){r[t]=c(e[t],n)}),d(t).forEach(function(s){(function(e,t){return p(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,s)||(p(e,s)&&n.isMergeableObject(t[s])?r[s]=function(e,t){if(!t.customMerge)return h;var n=t.customMerge(e);return"function"==typeof n?n:h}(s,n)(e[s],t[s],n):r[s]=c(t[s],n))}),r}function h(e,t,n){(n=n||{}).arrayMerge=n.arrayMerge||u,n.isMergeableObject=n.isMergeableObject||o,n.cloneUnlessOtherwiseSpecified=c;var r=Array.isArray(t);return r===Array.isArray(e)?r?n.arrayMerge(e,t,n):l(e,t,n):c(t,n)}h.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,n){return h(e,n,t)},{})};var f=h;function g(e,t,n,r,s,i){if("undefined"!=typeof window)return arguments.length>1?document.cookie=e+"="+encodeURIComponent(t)+(n?"; expires="+new Date(+new Date+1e3*n).toUTCString()+(r?"; path="+r:"")+(s?"; domain="+s:"")+(i?"; secure":""):""):decodeURIComponent((("; "+document.cookie).split("; "+e+"=")[1]||"").split(";")[0])}function m(e){return(m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}"object"===("undefined"==typeof self?"undefined":m(self))&&self.self===self&&self||"object"===("undefined"==typeof global?"undefined":m(global))&&global.global===global&&global,function(){try{g("_c_","1");var e=-1!==document.cookie.indexOf("_c_");g("_c_","",-1)}catch(e){return!1}}();function y(){for(var e="",t=0,n=4294967295*Math.random()|0;t++<36;){var r="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[t-1],s=15&n;e+="-"==r||"4"==r?r:("x"==r?s:3&s|8).toString(16),n=t%8==0?4294967295*Math.random()|0:n>>4}return e}const v=new TextEncoder,b={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},w=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"];class S{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:n,service:r,region:s,cache:i,retries:o,initRetryMs:a}){if(null==e)throw new TypeError("accessKeyId is a required option");if(null==t)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=n,this.service=r,this.region=s,this.cache=i||new Map,this.retries=null!=o?o:10,this.initRetryMs=a||50}async sign(e,t){if(e instanceof Request){const{method:n,url:r,headers:s,body:i}=e;null==(t=Object.assign({method:n,url:r,headers:s},t)).body&&s.has("Content-Type")&&(t.body=null!=i&&s.has("X-Amz-Content-Sha256")?i:await e.clone().arrayBuffer()),e=r}const n=new A(Object.assign({url:e},t,this,t&&t.aws)),r=Object.assign({},t,await n.sign());return delete r.aws,new Request(r.url.toString(),r)}async fetch(e,t){for(let n=0;n<=this.retries;n++){const r=fetch(await this.sign(e,t));if(n===this.retries)return r;const s=await r;if(s.status<500&&429!==s.status)return s;await new Promise(e=>setTimeout(e,Math.random()*this.initRetryMs*Math.pow(2,n)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class A{constructor({method:e,url:t,headers:n,body:r,accessKeyId:s,secretAccessKey:i,sessionToken:o,service:a,region:c,cache:u,datetime:d,signQuery:p,appendSessionToken:l,allHeaders:h,singleEncode:f}){if(null==t)throw new TypeError("url is a required option");if(null==s)throw new TypeError("accessKeyId is a required option");if(null==i)throw new TypeError("secretAccessKey is a required option");let g,m;this.method=e||(r?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(n||{}),this.body=r,this.accessKeyId=s,this.secretAccessKey=i,this.sessionToken=o,a&&c||([g,m]=function(e,t){const{hostname:n,pathname:r}=e,s=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/);let[i,o]=(s||["",""]).slice(1,3);if("us-gov"===o)o="us-gov-west-1";else if("s3"===o||"s3-accelerate"===o)o="us-east-1",i="s3";else if("iot"===i)i=n.startsWith("iot.")?"execute-api":n.startsWith("data.jobs.iot.")?"iot-jobs-data":"/mqtt"===r?"iotdevicegateway":"iotdata";else if("autoscaling"===i){const e=(t.get("X-Amz-Target")||"").split(".")[0];"AnyScaleFrontendService"===e?i="application-autoscaling":"AnyScaleScalingPlannerFrontendService"===e&&(i="autoscaling-plans")}else null==o&&i.startsWith("s3-")?(o=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):o&&/-\d$/.test(i)&&!/-\d$/.test(o)&&([i,o]=[o,i]);return[b[i]||i,o]}(this.url,this.headers)),this.service=a||g||"",this.region=c||m||"us-east-1",this.cache=u||new Map,this.datetime=d||(new Date).toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=p,this.appendSessionToken=l||"iotdevicegateway"===this.service,this.headers.delete("Host");const y=this.signQuery?this.url.searchParams:this.headers;if("s3"!==this.service||this.headers.has("X-Amz-Content-Sha256")||this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),y.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&y.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(e=>h||!w.includes(e)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(e=>e+":"+("host"===e?this.url.host:(this.headers.get(e)||"").replace(/\s+/g," "))).join("\n"),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&("s3"!==this.service||y.has("X-Amz-Expires")||y.set("X-Amz-Expires","86400"),y.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),y.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),y.set("X-Amz-SignedHeaders",this.signedHeaders)),"s3"===this.service)try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(e){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");f||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=k(this.encodedPath);const v=new Set;this.encodedSearch=[...this.url.searchParams].filter(([e])=>{if(!e)return!1;if("s3"===this.service){if(v.has(e))return!1;v.add(e)}return!0}).map(e=>e.map(e=>k(encodeURIComponent(e)))).sort(([e,t],[n,r])=>e<n?-1:e>n?1:t<r?-1:t>r?1:0).map(e=>e.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){const e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join();let n=this.cache.get(t);if(!n){const r=await x("AWS4"+this.secretAccessKey,e),s=await x(r,this.region),i=await x(s,this.service);n=await x(i,"aws4_request"),this.cache.set(t,n)}return E(await x(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,E(await I(await this.canonicalString()))].join("\n")}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+"\n",this.signedHeaders,await this.hexBodyHash()].join("\n")}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(null==e){if(this.body&&"string"!=typeof this.body&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=E(await I(this.body||""))}return e}}async function x(e,t){const n=await crypto.subtle.importKey("raw","string"==typeof e?v.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,v.encode(t))}async function I(e){return crypto.subtle.digest("SHA-256","string"==typeof e?v.encode(e):e)}function E(e){return Array.prototype.map.call(new Uint8Array(e),e=>("0"+e.toString(16)).slice(-2)).join("")}function k(e){return e.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}function O(e){return(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})[e]||e}var P=["PUSH","GCM","APNS","APNS_SANDBOX","APNS_VOIP","APNS_VOIP_SANDBOX","ADM","SMS","VOICE","EMAIL","BAIDU","CUSTOM"].reduce(function(e,t){return e[t]=t,e},{}),T="_session.start",M="_session.stop",j="pageView",C=Object.freeze({SESSION_START:T,SESSION_STOP:M,SESSION_PAUSE:"_session.pause",SESSION_RESUME:"_session.resume",AUTH_SIGN_IN:"_userauth.sign_in",AUTH_SIGN_UP:"_userauth.sign_up",AUTH_FAIL:"_userauth.auth_fail",ECOM_PURCHASE:"_monetization.purchase",PAGE_VIEW:j}),U="undefined"!=typeof window,_=("undefined"!=typeof navigator&&navigator&&navigator.sendBeacon,"__endpoint"),R=[429,500],D=[202],H=400,N=function(){if("undefined"==typeof window)return{};if(!window.navigator)return{};var e,t,n,r,s,i=window.navigator,o=i.platform,a=i.product,c=i.vendor,u=function(e){var t=/.+(Opera[\s[A-Z]*|OPR[\sA-Z]*)\/([0-9\.]+).*/i.exec(e);if(t)return{type:t[1],version:t[2]};var n=/.+(Trident|Edge)\/([0-9\.]+).*/i.exec(e);if(n)return{type:n[1],version:n[2]};var r=/.+(Chrome|Firefox|FxiOS)\/([0-9\.]+).*/i.exec(e);if(r)return{type:r[1],version:r[2]};var s=/.+(Safari)\/([0-9\.]+).*/i.exec(e);if(s)return{type:s[1],version:s[2]};var i=/.+(AppleWebKit)\/([0-9\.]+).*/i.exec(e);if(i)return{type:i[1],version:i[2]};var o=/.*([A-Z]+)\/([0-9\.]+).*/i.exec(e);return o?{type:o[1],version:o[2]}:{type:"",version:""}}(i.userAgent);return{platform:o,make:c||a,model:u.type,version:u.version,appVersion:[u.type,u.version].join("/"),language:(t=window.navigator,n=t.language,r=t.browserLanguage,s=t.languages,(n||r||(s||["en_US"])[0]).toLowerCase().replace("-","_")),timezone:(e=/\(([A-Za-z\s].*)\)/.exec((new Date).toString()),e&&e[1]||"")}}(),K=[];function z(){return{}}var V=/.+\@.+\..+/;function X(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=i({getContext:e.getContext||z,enrichEventAttributes:e.enrichEventAttributes||z,enrichEventMetrics:e.enrichEventMetrics||z,credentials:e.credentials||{},getEndpointId:e.getEndpointId},e),r=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.getEndpointId,r=e.debug;return function(){var s=n(regeneratorRuntime.mark(function n(){var s,o,a,c,u,d,p,l=arguments;return regeneratorRuntime.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:if(s=l.length>0&&void 0!==l[0]?l[0]:{},K.length||Object.keys(s).length){n.next=4;break}return r&&console.log("No events, return early"),n.abrupt("return");case 4:return o=s,n.next=7,t();case 7:if(a=n.sent,r&&console.log("resolved endpointId",a),a){n.next=12;break}return console.error("No User ID found. Call Auth()"),n.abrupt("return");case 12:if(!Object.entries(s).length){n.next=18;break}return n.next=15,Y(s,e);case 15:o=n.sent,n.next=19;break;case 18:o=q(a)||{};case 19:return r&&console.log("endpointData",o),c=o.ChannelType,o.Address&&(h=o.Address,V.test(h))&&(c=P.EMAIL),!c&&o.Address&&(c="android"===N.platform?c||P.GCM:c||P.APNS),r&&console.log("CHANNEL_TYPE",c),u=K.reduce(function(e,t){return i({},t,{},e)},{}),(d=o).RequestId=y(),d.ChannelType=c,d.Address&&(d.OptOut=o.OptOut||"NONE"),p=B(a,d,u),n.prev=30,n.next=33,Q(p,e);case 33:n.sent,n.next=39;break;case 36:n.prev=36,n.t0=n.catch(30),console.log("callPinPoint err",n.t0);case 39:return K=[],n.abrupt("return",o);case 41:case"end":return n.stop()}var h},n,null,[[30,36]])}));return function(){return s.apply(this,arguments)}}()}(t),s=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.sentDataToPinpoint;return function(){var s=n(regeneratorRuntime.mark(function n(s){var i,o,a,c,u=arguments;return regeneratorRuntime.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return i=u.length>1&&void 0!==u[1]?u[1]:{},o=u.length>2&&void 0!==u[2]?u[2]:{},a=!(u.length>3&&void 0!==u[3])||u[3],"boolean"==typeof i&&(a=i,i={}),"boolean"==typeof o&&(a=o,o={}),n.next=7,F(s,i,t);case 7:if(c=n.sent,!Object.entries(o).length&&s!==j){n.next=12;break}return n.next=11,Y(o,t);case 11:o=n.sent;case 12:K.push(c),n.next=15;break;case 15:if(a){n.next=17;break}return n.abrupt("return",r());case 17:e&&clearTimeout(e),e=setTimeout(r,3e3);case 19:case"end":return n.stop()}},n)}));return function(e){return s.apply(this,arguments)}}()}(i({sentDataToPinpoint:r},t));Y({},e);var o=function(e){if(!U)return z;var t=function(e){return function(){console.log("Fire stop session"),e(M,!1)}}(e);return window.addEventListener("beforeunload",t),function(){return window.removeEventListener("beforeunload",t)}}(s);return{updateEndpoint:r,recordEvent:s,disable:function(){o()}}}function L(e){return"".concat(_,".").concat(e)}function q(e){var t={};try{t=JSON.parse(localStorage.getItem(L(e)))||{}}catch(e){}return t}function W(e,t){var n=L(e),r="string"==typeof t?t:JSON.stringify(t);localStorage.setItem(n,r)}function B(e,t,n){return{BatchItem:r({},e,{Endpoint:t,Events:n})}}function F(e){return G.apply(this,arguments)}function G(){return(G=n(regeneratorRuntime.mark(function e(t){var n,s,o,a,c,u,d,p,l,h,f,g,m,v,b,w,S,A,x,I,E,k,P,T,j,C,U,_,R,D,H,N=arguments;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=N.length>1&&void 0!==N[1]?N[1]:{},s=N.length>2&&void 0!==N[2]?N[2]:{},o=s.appTitle,a=s.appPackageName,c=s.appVersionCode,u=s.eventMapping,d=s.getSessionID,p=s.enrichEventAttributes,l=s.enrichEventMetrics,h=s.debug,f=O(t,u),g=ne(s),m=g.pageSession,v=g.subSessionId,b=g.subSessionStart,w=g.elapsed,S=n.attributes||{},A=n.eventId||y(),x=n.time?new Date(n.time):new Date,I=x.toISOString(),E=n.sessionId||d(),k={date:I,session:E,pageSession:m},e.next=14,p();case 14:return P=e.sent,T=i({},k,{},P,{},S),j=w+(x.getTime()-b),C=n.metrics||{},U={sessionTime:j,hour:x.getHours(),day:x.getDay()+1,month:x.getMonth()+1,year:x.getFullYear()},e.next=21,l();case 21:return _=e.sent,R=i({},U,{},_,{},C),e.next=25,oe(T);case 25:return e.t0=e.sent,e.next=28,ue(R);case 28:return e.t1=e.sent,D={attributes:e.t0,metrics:e.t1},h&&(console.log("".concat(A,":").concat(f)),console.log("eventAttributes",D.attributes),console.log("eventMetrics",D.metrics)),H=r({},A,{EventType:f,Timestamp:I,AppPackageName:a,AppTitle:o,AppVersionCode:c,Attributes:D.attributes,Metrics:D.metrics,Session:{Id:v,StartTimestamp:new Date(b).toISOString()}}),t===M&&(H[A].Session.Duration=Date.now()-b,H[A].Session.StopTimestamp=I),e.abrupt("return",H);case 34:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Q(e,t){return $.apply(this,arguments)}function $(){return($=n(regeneratorRuntime.mark(function e(t,n){var r,s,i,o,a,c,u,d,p,l,h,f,g,m,y,v;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=n.pinpointRegion,n.pinpointEndpoint,s=n.pinpointAppId,i=n.lambdaArn,o=n.lambdaRegion,a=n.credentials,c=n.getCredentials,u=n.debug,d=a,Object.keys(d).length||!c){e.next=12;break}return e.prev=3,e.next=6,c();case 6:d=e.sent,e.next=12;break;case 9:throw e.prev=9,e.t0=e.catch(3),new Error(e.t0);case 12:return p=new S({accessKeyId:d.accessKeyId||d.AccessKeyId,secretAccessKey:d.secretAccessKey||d.SecretKey,sessionToken:d.sessionToken||d.SessionToken,retries:5}),l=o||r,h=r||o,f=!0===n.fips?"-fips":"",g="https://lambda.".concat(l,".amazonaws.com/2015-03-31/functions/").concat(i,"/invocations"),m="https://pinpoint".concat(f,".").concat(h,".amazonaws.com/v1/apps/").concat(s,"/events"),y=i?g:m,e.next=21,p.fetch(y,{body:JSON.stringify(t)}).then(function(e){return e.json()});case 21:return(v=e.sent)&&v.Results&&Object.keys(v.Results).map(function(e){return v.Results[e]}).forEach(function(e){var t=e.EndpointItemResponse||{},n=e.EventsItemResponse||{};Object.keys(t).length&&(u&&console.log("EndpointItemResponse",t),D.includes(t.StatusCode)||R.includes(t.StatusCode)||Z(t,Endpoint));var r=Object.keys(n);r.length&&(u&&console.log("EventsResponse",n),r.forEach(function(e){}))}),e.abrupt("return",v);case 24:case"end":return e.stop()}},e,null,[[3,9]])}))).apply(this,arguments)}function Z(e,t){var n=e.StatusCode,r=e.Message;if(n===H){if(r.startsWith("Missing ChannelType"))throw new Error("Missing ChannelType");if(r.startsWith("Exceeded maximum endpoint per user count"))throw new Error("Exceeded maximum endpoint per user count")}}var J=!1;function Y(){return ee.apply(this,arguments)}function ee(){return(ee=n(regeneratorRuntime.mark(function e(){var t,n,r,s,o,a,c,u,d,p,l,h,g,m,y,v,b,w=arguments;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=w.length>0&&void 0!==w[0]?w[0]:{},n=w.length>1&&void 0!==w[1]?w[1]:{},r=n.getUserId,s=n.getEndpointId,o=n.getSessionID,a=ne(n),e.next=6,s();case 6:if(c=e.sent,J||(J=!0,(u=localStorage.getItem(_))&&(W(c,u),localStorage.removeItem(_))),d=q(c),p=a.pageSession,l={},h={AppVersion:N.appVersion,Make:N.make,Model:N.model,ModelVersion:N.version,Platform:N.platform,Locale:N.language},g={Attributes:{},Demographic:i({AppVersion:N.appVersion||""},h,{},l.demographic),Location:{},Metrics:{}},N.device&&N.device.vendor&&(g.Attributes.DeviceMake=[N.device.vendor]),N.device&&N.device.model&&(g.Attributes.DeviceModel=[N.device.model]),N.device&&N.device.type&&(g.Attributes.DeviceType=[N.device.type]),N.engine&&N.engine.name&&(g.Demographic.Make=N.engine.name),N.browser&&N.browser.name&&(g.Demographic.Model=N.browser.name),N.browser&&N.browser.version&&(g.Demographic.ModelVersion=N.browser.version),N.os&&N.os.name&&(g.Demographic.Platform=N.os.name),N.os&&N.os.version&&(g.Demographic.PlatformVersion=N.os.version),!(t=f.all([g,d,t],{arrayMerge:te})).User||!t.User.UserId){e.next=27;break}return e.next=25,r();case 25:m=e.sent,t.User.UserId!==m&&(t.User.UserId=m);case 27:if(t.User&&t.User.UserId){e.next=32;break}return e.next=30,r();case 30:(y=e.sent)&&(t.User||(t.User={}),t.User.UserId=y);case 32:if(!t.User||!t.User.UserAttributes){e.next=36;break}return e.next=35,oe(t.User.UserAttributes,!0);case 35:t.User.UserAttributes=e.sent;case 36:return e.next=38,oe(t.Attributes,!0);case 38:return t.Attributes=e.sent,e.next=41,ue(t.Metrics);case 41:return t.Metrics=e.sent,v="sessions",a.sessionKey&&(v=a.sessionKey()),b="pageViews",a.pageViewKey&&(b=a.pageViewKey()),t.Attributes.lastSession?(t.Attributes.lastSession[0]!==o()&&(t.Attributes.lastSession=[o()],t.Metrics[v]+=1),t.Attributes.lastPageSession[0]!==p&&(t.Attributes.lastPageSession=[p],t.Metrics[b]+=1)):(t.Attributes.lastSession=[o()],t.Attributes.lastPageSession=[p],t.Metrics[v]=1,t.Metrics[b]=1),W(c,t),e.abrupt("return",t);case 49:case"end":return e.stop()}},e)}))).apply(this,arguments)}function te(e,t){return t}function ne(e){return"function"==typeof e.getContext?e.getContext():e.getContext}function re(e,t){return se.apply(this,arguments)}function se(){return(se=n(regeneratorRuntime.mark(function e(t,n){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("function"!=typeof t){e.next=4;break}return e.next=3,t();case 3:t=e.sent;case 4:return e.abrupt("return",n(t));case 5:case"end":return e.stop()}},e)}))).apply(this,arguments)}function ie(e){return Array.isArray(e)?e.map(function(e){return e.toString()}):e.toString()}function oe(e){return ae.apply(this,arguments)}function ae(){return(ae=n(regeneratorRuntime.mark(function e(t){var n,r,s,i,o=arguments;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n=o.length>1&&void 0!==o[1]&&o[1],r={},e.t0=regeneratorRuntime.keys(t);case 3:if((e.t1=e.t0()).done){e.next=17;break}if(s=e.t1.value,i=Array.isArray(t[s])?t[s]:[t[s]],!n){e.next=12;break}return e.next=9,re(i,ie);case 9:r[s]=e.sent,e.next=15;break;case 12:return e.next=14,re(i[0],ie);case 14:r[s]=e.sent;case 15:e.next=3;break;case 17:return e.abrupt("return",r);case 18:case"end":return e.stop()}},e)}))).apply(this,arguments)}function ce(e){return parseFloat(Number(Array.isArray(e)?e[0]:e))}function ue(e){return de.apply(this,arguments)}function de(){return(de=n(regeneratorRuntime.mark(function e(t){var n,r;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n={},e.t0=regeneratorRuntime.keys(t);case 2:if((e.t1=e.t0()).done){e.next=9;break}return r=e.t1.value,e.next=6,re(t[r],ce);case 6:n[r]=e.sent,e.next=2;break;case 9:return e.abrupt("return",n);case 10:case"end":return e.stop()}},e)}))).apply(this,arguments)}var pe=function(){if(!U)return!1;var e=window.sessionStorage;try{return e.setItem("__test","x"),e.removeItem("__test"),!0}catch(e){return!1}}();function le(e){if("undefined"==typeof window)return!1;var t="hidden"in document?"hidden":["webkit","moz","ms","o"].reduce(function(e,t){return!e&&"".concat(t,"Hidden")in document?"".concat(t,"Hidden"):e},null);if(!t)return!1;var n="".concat(t.replace(/[H|h]idden/,""),"visibilitychange"),r=function(){return document[t]?e(!0):e(!1)};return document.addEventListener(n,r),function(){return document.removeEventListener(n,r)}}var he={disableAnonymousTraffic:!1,pinpointRegion:"us-east-1",eventMapping:{}};var fe="__session_id",ge={};function me(){if(!pe){var e=ge[fe];if(e)return e;var t=y();return ge[fe]=t,t}var n=window.sessionStorage.getItem(fe);if(n)return n;var r=y();return window.sessionStorage.setItem(fe,r),r}var ye=function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=0,s=y(),o=y(),a=Date.now();return{name:"aws-pinpoint",config:i({},he,{},n),bootstrap:function(e){var t=e.config,n=e.instance;t.disableAnonymousTraffic&&!n.user("userId")&&n.once("identifyStart",function(e){e.plugins["aws-pinpoint"].loaded()||n.loadPlugin("aws-pinpoint")})},initialize:function(n){var c=n.config,u=n.instance,d=c.disableAnonymousTraffic,p=u.getState(),l=(p.user||{}).userId,h=p.context||{},f=h.app,g=h.version;if(!l&&d)return!1;var m=X(i({},c,{appTitle:c.appTitle||f,appPackageName:c.appPackageName||f,appVersionCode:c.appVersionCode||g,getEndpointId:function(){return u.user("anonymousId")},getUserId:function(){return u.user("userId")},getSessionID:me,getContext:function(){return{elapsed:r,pageSession:s,subSessionId:o,subSessionStart:a,sessionKey:c.sessionKey,pageViewKey:c.pageViewKey}},enrichEventAttributes:function(){return{hash:window.location.hash,path:window.location.pathname,referrer:document.referrer,search:window.location.search,title:document.title,host:window.location.hostname,url:window.location.origin+window.location.pathname}},enrichEventMetrics:function(){return{}},eventMapping:c.eventMapping}));e=m.recordEvent,t=m.updateEndpoint,e(T),le(function(t){t?(r+=Date.now()-a,e(M,!1)):(o=y(),a=Date.now(),e(T))})},page:function(t){t.payload,t.config,e?e(j,!0).then(function(){s=y()}):console.log("Pinpoint not loaded")},reset:function(e){var t=L(e.instance.user("anonymousId"));storage.removeItem(t)},track:function(t){var n=t.payload,r=t.config;if(t.instance,e){if(!r.disableAnonymousTraffic||n.userId){var s,i=(s=n.properties,Object.keys(s).reduce(function(e,t){var n=s[t];return"number"==typeof n&&(e.metrics[t]=n),"string"!=typeof n&&"boolean"!=typeof n||(e.attributes[t]=n),e},{attributes:{},metrics:{}}));e(n.event,i)}}else console.log("Pinpoint not loaded")},identify:function(e){var n=e.payload,r=n.userId,s=n.traits;if(t){var o={};r&&(o.UserId=r),s&&Object.keys(s).length&&(o.UserAttributes=s),t(i({},s.email?{Address:s.email,ChannelType:P.EMAIL}:{},{},Object.keys(o).length?{User:o}:{}))}else console.log("Pinpoint not loaded")},loaded:function(){return!!e}}};return e.default=ye,e.PINPOINT_EVENTS=C,e.formatEvent=F,e}({}); |
@@ -247,2 +247,4 @@ 'use strict'; | ||
var inBrowser = typeof window !== 'undefined'; | ||
// import 'navigator.sendbeacon' | ||
@@ -255,3 +257,2 @@ | ||
var BAD_REQUEST_CODE = 400; | ||
var inBrowser = typeof window !== 'undefined'; | ||
var clientInfo = browserClientInfo(); // TODO localize queue | ||
@@ -1389,2 +1390,3 @@ | ||
function isSessionStorageSupported() { | ||
if (!inBrowser) return false; | ||
var sessionStorage = window.sessionStorage; | ||
@@ -1679,6 +1681,7 @@ | ||
var SESSION_KEY = '__session_id'; | ||
var tempStorageFallback = {}; | ||
function getSessionID() { | ||
if (!hasSessionStorage) { | ||
var windowSession = window[SESSION_KEY]; | ||
var windowSession = tempStorageFallback[SESSION_KEY]; | ||
if (windowSession) return windowSession; | ||
@@ -1688,3 +1691,3 @@ | ||
window[SESSION_KEY] = _sessionID; | ||
tempStorageFallback[SESSION_KEY] = _sessionID; | ||
return _sessionID; | ||
@@ -1691,0 +1694,0 @@ } // Get stored session. |
@@ -241,2 +241,4 @@ import deepmerge from 'deepmerge'; | ||
var inBrowser = typeof window !== 'undefined'; | ||
// import 'navigator.sendbeacon' | ||
@@ -249,3 +251,2 @@ | ||
var BAD_REQUEST_CODE = 400; | ||
var inBrowser = typeof window !== 'undefined'; | ||
var clientInfo = browserClientInfo(); // TODO localize queue | ||
@@ -1383,2 +1384,3 @@ | ||
function isSessionStorageSupported() { | ||
if (!inBrowser) return false; | ||
var sessionStorage = window.sessionStorage; | ||
@@ -1673,6 +1675,7 @@ | ||
var SESSION_KEY = '__session_id'; | ||
var tempStorageFallback = {}; | ||
function getSessionID() { | ||
if (!hasSessionStorage) { | ||
var windowSession = window[SESSION_KEY]; | ||
var windowSession = tempStorageFallback[SESSION_KEY]; | ||
if (windowSession) return windowSession; | ||
@@ -1682,3 +1685,3 @@ | ||
window[SESSION_KEY] = _sessionID; | ||
tempStorageFallback[SESSION_KEY] = _sessionID; | ||
return _sessionID; | ||
@@ -1685,0 +1688,0 @@ } // Get stored session. |
@@ -255,2 +255,4 @@ 'use strict'; | ||
var inBrowser = typeof window !== 'undefined'; | ||
// import 'navigator.sendbeacon' | ||
@@ -689,2 +691,3 @@ | ||
function isSessionStorageSupported() { | ||
if (!inBrowser) return false; | ||
var sessionStorage = window.sessionStorage; | ||
@@ -691,0 +694,0 @@ |
@@ -251,2 +251,4 @@ import 'deepmerge'; | ||
var inBrowser = typeof window !== 'undefined'; | ||
// import 'navigator.sendbeacon' | ||
@@ -685,2 +687,3 @@ | ||
function isSessionStorageSupported() { | ||
if (!inBrowser) return false; | ||
var sessionStorage = window.sessionStorage; | ||
@@ -687,0 +690,0 @@ |
{ | ||
"name": "@analytics/aws-pinpoint", | ||
"version": "0.5.2", | ||
"version": "0.5.3", | ||
"description": "AWS Pinpoint integration for 'analytics' module", | ||
@@ -59,3 +59,3 @@ "projectMeta": { | ||
}, | ||
"gitHead": "459797698a7064c6484a19b7acede3dd01a97a57" | ||
"gitHead": "6cf9a20600b1ccce81964fd696e1bea44b63c525" | ||
} |
Sorry, the diff of this file is too big to display
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
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
250084
5891