@esri/telemetry
Advanced tools
Comparing version 1.0.0 to 1.0.1
@@ -7,3 +7,9 @@ # Change Log | ||
## 1.0.0 - 04/27/2016 | ||
## [1.0.1] - 04/28/2017 | ||
### Changed | ||
- Replace Fetch with XHR | ||
## 1.0.0 - 04/27/2017 | ||
- Initial Release | ||
[1.0.1]: https://github.com/arcgis/telemetry.js/compare/v1.0.0...v1.0.1 |
{ | ||
"name": "arcgis-telemetry", | ||
"name": "@esri/telemetry", | ||
"version": "1.0.0", | ||
@@ -8,3 +8,3 @@ "description": "A JavaScript Implementation of the ArcGIS Telemetry Specification", | ||
"type": "git", | ||
"url": "git+https://github.com/ArcGIS/telemetry-service.git" | ||
"url": "git+https://github.com/ArcGIS/telemetry.js.git" | ||
}, | ||
@@ -29,4 +29,4 @@ "keywords": [ | ||
"window", | ||
"fetch", | ||
"document" | ||
"document", | ||
"XMLHttpRequest" | ||
], | ||
@@ -33,0 +33,0 @@ "ignore": [ |
define('telemetry', function () { 'use strict'; | ||
function request(options, callback) { | ||
var req = new XMLHttpRequest(); | ||
req.addEventListener('load', function () { | ||
callback(req.responseText); | ||
}); | ||
req.open(options.method, options.url); | ||
Object.keys(options.headers).forEach(function (header) { | ||
req.setRequestHeader(header, options.headers[header]); | ||
}); | ||
req.send(options.body); | ||
} | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { | ||
return typeof obj; | ||
} : function (obj) { | ||
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; | ||
}; | ||
var classCallCheck = function (instance, Constructor) { | ||
if (!(instance instanceof Constructor)) { | ||
throw new TypeError("Cannot call a class as a function"); | ||
} | ||
}; | ||
var createClass = function () { | ||
function defineProperties(target, props) { | ||
for (var i = 0; i < props.length; i++) { | ||
var descriptor = props[i]; | ||
descriptor.enumerable = descriptor.enumerable || false; | ||
descriptor.configurable = true; | ||
if ("value" in descriptor) descriptor.writable = true; | ||
Object.defineProperty(target, descriptor.key, descriptor); | ||
} | ||
} | ||
return function (Constructor, protoProps, staticProps) { | ||
if (protoProps) defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) defineProperties(Constructor, staticProps); | ||
return Constructor; | ||
}; | ||
}(); | ||
var _extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
var COGNITO_KEY = 'TELEMETRY_COGNITO_CREDENTIALS'; | ||
var COGNITO_URL = 'https://cognito-identity.us-east-1.amazonaws.com/'; | ||
function getCredentials(IdentityPoolId) { | ||
function getCredentials(IdentityPoolId, callback) { | ||
var cached = window.localStorage.getItem(COGNITO_KEY); | ||
if (cached) cached = JSON.parse(cached); | ||
if (cached && Date.now() / 1000 < cached.Expiration) return Promise.resolve(cached); | ||
if (cached && Date.now() / 1000 < cached.Expiration) return callback(cached); | ||
return authWithCognito(IdentityPoolId).then(function (credentials) { | ||
authWithCognito(IdentityPoolId, function (credentials) { | ||
window.localStorage.setItem(COGNITO_KEY, JSON.stringify(credentials)); | ||
return credentials; | ||
callback(credentials); | ||
}); | ||
} | ||
function authWithCognito(IdentityPoolId) { | ||
return fetch('https://cognito-identity.us-east-1.amazonaws.com/', { | ||
method: 'POST', | ||
headers: { | ||
'Content-type': 'application/x-amz-json-1.1', | ||
'X-Amz-Target': 'AWSCognitoIdentityService.GetId' | ||
}, | ||
body: JSON.stringify({ IdentityPoolId: IdentityPoolId }) | ||
}).then(function (r) { | ||
return r.json(); | ||
}).then(function (json) { | ||
return fetch('https://cognito-identity.us-east-1.amazonaws.com/', { | ||
method: 'POST', | ||
headers: { | ||
'Content-type': 'application/x-amz-json-1.1', | ||
'X-Amz-Target': 'AWSCognitoIdentityService.GetCredentialsForIdentity' | ||
}, | ||
body: JSON.stringify({ IdentityId: json.IdentityId }) | ||
}); | ||
}).then(function (r) { | ||
return r.json(); | ||
}).then(function (json) { | ||
return json.Credentials; | ||
}).catch(function (e) { | ||
throw new Error('Authentication with cognito failed, check your user pool settings'); | ||
function authWithCognito(IdentityPoolId, callback) { | ||
var options = _extends({}, defaults$$1); | ||
options.headers['X-Amz-Target'] = 'AWSCognitoIdentityService.GetId'; | ||
options.body = JSON.stringify({ IdentityPoolId: IdentityPoolId }); | ||
request(options, function (response) { | ||
requestCredentials(JSON.parse(response), callback); | ||
}); | ||
} | ||
function requestCredentials(json, callback) { | ||
var options = _extends({}, defaults$$1); | ||
options.headers['X-Amz-Target'] = 'AWSCognitoIdentityService.GetCredentialsForIdentity'; | ||
options.body = JSON.stringify({ IdentityId: json.IdentityId }); | ||
request(options, function (response) { | ||
var json = JSON.parse(response); | ||
callback(json.Credentials); | ||
}); | ||
} | ||
var defaults$$1 = { | ||
method: 'POST', | ||
url: COGNITO_URL, | ||
headers: { | ||
'Content-type': 'application/x-amz-json-1.1' | ||
} | ||
}; | ||
var SESSION_LENGTH = 30 * 60 * 1000; | ||
@@ -275,62 +352,2 @@ var SESSION_KEY = 'TELEMETRY_SESSION'; | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { | ||
return typeof obj; | ||
} : function (obj) { | ||
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; | ||
}; | ||
var classCallCheck = function (instance, Constructor) { | ||
if (!(instance instanceof Constructor)) { | ||
throw new TypeError("Cannot call a class as a function"); | ||
} | ||
}; | ||
var createClass = function () { | ||
function defineProperties(target, props) { | ||
for (var i = 0; i < props.length; i++) { | ||
var descriptor = props[i]; | ||
descriptor.enumerable = descriptor.enumerable || false; | ||
descriptor.configurable = true; | ||
if ("value" in descriptor) descriptor.writable = true; | ||
Object.defineProperty(target, descriptor.key, descriptor); | ||
} | ||
} | ||
return function (Constructor, protoProps, staticProps) { | ||
if (protoProps) defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) defineProperties(Constructor, staticProps); | ||
return Constructor; | ||
}; | ||
}(); | ||
var _extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
// | ||
@@ -635,2 +652,3 @@ // AWS Signature v4 Implementation for Web Browsers | ||
var METRICS = ['size', 'duration']; | ||
var DEFAULT_ENDPOINT = 'https://mobileanalytics.us-east-1.amazonaws.com/2014-06-05/events'; | ||
@@ -760,9 +778,9 @@ var Amazon = function () { | ||
var options = createTelemetryOptions(events); | ||
return getCredentials(userPoolID).then(function (credentials) { | ||
getCredentials(userPoolID, function (credentials) { | ||
options.headers = createHeaders(credentials, options); | ||
options.headers['x-amz-Client-Context'] = createClientContext(user.id, app); | ||
fetch(options.url, options).then(function (r) { | ||
return console.log(r); | ||
}).catch(function (e) { | ||
return console.error(e); | ||
request(options, function (response) { | ||
if (response) { | ||
console.error(JSON.parse(response)); | ||
} | ||
}); | ||
@@ -773,3 +791,3 @@ }); | ||
function createTelemetryOptions(events) { | ||
var url = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'https://mobileanalytics.us-east-1.amazonaws.com/2014-06-05/events'; | ||
var url = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ENDPOINT; | ||
@@ -776,0 +794,0 @@ return { |
@@ -1,2 +0,2 @@ | ||
define("telemetry",function(){"use strict";function e(e){var n=window.localStorage.getItem(C);return n&&(n=JSON.parse(n)),n&&Date.now()/1e3<n.Expiration?Promise.resolve(n):t(e).then(function(e){return window.localStorage.setItem(C,JSON.stringify(e)),e})}function t(e){return fetch("https://cognito-identity.us-east-1.amazonaws.com/",{method:"POST",headers:{"Content-type":"application/x-amz-json-1.1","X-Amz-Target":"AWSCognitoIdentityService.GetId"},body:JSON.stringify({IdentityPoolId:e})}).then(function(e){return e.json()}).then(function(e){return fetch("https://cognito-identity.us-east-1.amazonaws.com/",{method:"POST",headers:{"Content-type":"application/x-amz-json-1.1","X-Amz-Target":"AWSCognitoIdentityService.GetCredentialsForIdentity"},body:JSON.stringify({IdentityId:e.IdentityId})})}).then(function(e){return e.json()}).then(function(e){return e.Credentials}).catch(function(e){throw new Error("Authentication with cognito failed, check your user pool settings")})}function n(){return{session:r(),id:i()}}function r(){var e=void 0,t=void 0,n=window.localStorage.getItem(q);return n&&(n=JSON.parse(n),Date.now()<n.expiration&&(e=n)),e||(t=!0,e=o()),e.expiration=Date.now()+H,window.localStorage.setItem(q,JSON.stringify(e)),t&&(e.new=!0),e}function i(){var e=window.localStorage.getItem(P);return e||(e=s(),window.localStorage.setItem(P,e)),e}function o(){return{id:Math.floor(17592186044416*(1+Math.random())).toString(16),startTimestamp:(new Date).toISOString()}}function s(){return a()+a()+"-"+a()+"-"+a()+"-"+a()+"-"+a()+a()+a()}function a(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function c(e,t){var n={host:t.uri.host,"content-type":e.config.defaultContentType,accept:e.config.defaultAcceptType,"x-amz-date":d(t.signDate)};t.request.method=t.request.method.toUpperCase(),t.request.body?t.payload=t.request.body:t.request.data&&e.payloadSerializer?t.payload=e.payloadSerializer(t.request.data):delete n["content-type"],t.request.headers=v(n,Object.keys(t.request.headers||{}).reduce(function(e,n){return e[n.toLowerCase()]=t.request.headers[n],e},{})),t.sortedHeaderKeys=Object.keys(t.request.headers).sort(),t.request.headers["content-type"]&&(t.request.headers["content-type"]=t.request.headers["content-type"].split(";")[0]),"object"===j(t.request.params)&&v(t.uri.queryParams,t.request.params)}function u(e,t){t.signedHeaders=t.sortedHeaderKeys.map(function(e){return e.toLowerCase()}).join(";"),t.canonicalRequest=String(t.request.method).toUpperCase()+"\n"+encodeURI(t.uri.path)+"\n"+Object.keys(t.uri.queryParams).sort().map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(t.uri.queryParams[e])}).join("&")+"\n"+t.sortedHeaderKeys.map(function(e){return e.toLocaleLowerCase()+":"+t.request.headers[e]}).join("\n")+"\n\n"+t.signedHeaders+"\n"+e.hasher.hash(t.payload?t.payload:"")}function h(e,t){t.credentialScope=[d(t.signDate,!0),e.config.region,e.config.service,"aws4_request"].join("/"),t.stringToSign="AWS4-HMAC-SHA256\n"+d(t.signDate)+"\n"+t.credentialScope+"\n"+e.hasher.hash(t.canonicalRequest)}function f(e,t){var n=e.hasher.hmac,r=n(n(n(n("AWS4"+e.config.secretAccessKey,d(t.signDate,!0),{hexOutput:!1}),e.config.region,{hexOutput:!1,textInput:!1}),e.config.service,{hexOutput:!1,textInput:!1}),"aws4_request",{hexOutput:!1,textInput:!1});t.signature=n(r,t.stringToSign,{textInput:!1})}function l(e,t){t.authorization="AWS4-HMAC-SHA256 Credential="+e.config.accessKeyId+"/"+t.credentialScope+", SignedHeaders="+t.signedHeaders+", Signature="+t.signature}function d(e,t){var n=e.toISOString().replace(/[:\-]|\.\d{3}/g,"").substr(0,17);return t?n.substr(0,8):n}function p(){return function(e){return JSON.stringify(e)}}function g(){function e(e){return/^\??(.*)$/.exec(e)[1].split("&").reduce(function(e,t){return t=/^(.+)=(.*)$/.exec(t),t&&(e[t[1]]=t[2]),e},{})}var t=document?document.createElement("a"):{};return function(n){return t.href=n,{protocol:t.protocol,host:t.host.replace(/^(.*):((80)|(443))$/,"$1"),path:("/"!==t.pathname.charAt(0)?"/":"")+t.pathname,queryParams:e(t.search)}}}function y(){return{hash:function(e,t){t=v({hexOutput:!0,textInput:!0},t);var n=B.SHA256(e);return t.hexOutput?n.toString(B.enc.Hex):n},hmac:function(e,t,n){n=v({hexOutput:!0,textInput:!0},n);var r=B.HmacSHA256(t,e,{asBytes:!0});return n.hexOutput?r.toString(B.enc.Hex):r}}}function v(e){return[].slice.call(arguments,1).forEach(function(t){t&&"object"===(void 0===t?"undefined":j(t))&&Object.keys(t).forEach(function(n){var r=t[n];void 0!==r&&(null!==r&&"object"===(void 0===r?"undefined":j(r))?(e[n]=Array.isArray(r)?[]:{},v(e[n],r)):e[n]=r)})}),e}function m(e,t){if(void 0===e||!e)throw new Error(t)}function w(e){var t=n().session;return{eventType:"pageView",timestamp:(new Date).toISOString(),session:{id:t.id,startTimestamp:t.startTimestamp},attributes:{referrer:document.referrer,hostname:window.location.hostname,path:window.location.pathname||e},metrics:{}}}function S(e){var t=n().session;return{eventType:_(e),timestamp:(new Date).toISOString(),session:{id:t.id,startTimestamp:t.startTimestamp},attributes:M({referrer:document.referrer,hostname:window.location.hostname,path:window.location.pathname},b(e)),metrics:A(e)}}function _(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.workflow||e.process||e.category;return t||(e.error?"error":"other")}function b(e){var t=M({},e);return L.forEach(function(e){return delete t[e]}),t}function A(e){var t={};return L.forEach(function(n){t[n]=e[n]}),t}function I(e,t){var n={region:"us-east-1",service:"mobileanalytics",accessKeyId:e.AccessKeyId,secretAccessKey:e.SecretKey,sessionToken:e.SessionToken};return new R(n).sign(t)}function x(e,t){return JSON.stringify({client:{client_id:e,app_title:t.name,app_version_name:t.version||"unknown"},services:{mobile_analytics:{app_id:t.id}}})}function k(t,r,i){var o=n();t=Array.isArray(t)?t:[t];var s=O(t);return e(r).then(function(e){s.headers=I(e,s),s.headers["x-amz-Client-Context"]=x(o.id,i),fetch(s.url,s).then(function(e){return console.log(e)}).catch(function(e){return console.error(e)})})}function O(e){return{url:arguments.length>1&&void 0!==arguments[1]?arguments[1]:"https://mobileanalytics.us-east-1.amazonaws.com/2014-06-05/events",method:"POST",body:JSON.stringify({events:e})}}function E(){return new Promise(function(e,t){window.ga?window.ga(function(){e(window.ga.getAll())}):t(new Error("Google Analytics trackers not available"))})}function z(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={hitType:"event",eventCategory:e.category||"none",eventAction:e.action,eventLabel:e.label};return Object.keys(t).forEach(function(n){r["dimension"+t[n]]=e[n]}),Object.keys(n).forEach(function(t){r["metric"+n[t]]=e[t]}),r}function T(e){var t=M({},e);return t.user&&(t.user=J(t.user)),t}var C="TELEMETRY_COGNITO_CREDENTIALS",H=18e5,q="TELEMETRY_SESSION",P="TELEMETRY_CLIENT_ID",B=function(e,t){var n={},r=n.lib={},i=function(){},o=r.Base={extend:function(e){i.prototype=this;var t=new i;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=r.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=void 0!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,n=e.words,r=this.sigBytes;if(e=e.sigBytes,this.clamp(),r%4)for(var i=0;i<e;i++)t[r+i>>>2]|=(n[i>>>2]>>>24-i%4*8&255)<<24-(r+i)%4*8;else if(n.length>65535)for(i=0;i<e;i+=4)t[r+i>>>2]=n[i>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],r=0;r<t;r+=4)n.push(4294967296*e.random()|0);return new s.init(n,t)}}),a=n.enc={},c=a.Hex={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r<e;r++){var i=t[r>>>2]>>>24-r%4*8&255;n.push((i>>>4).toString(16)),n.push((15&i).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r<t;r+=2)n[r>>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},u=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r<e;r++)n.push(String.fromCharCode(t[r>>>2]>>>24-r%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r<t;r++)n[r>>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},h=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},f=r.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=h.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,i=n.sigBytes,o=this.blockSize,a=i/(4*o),a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0);if(t=a*o,i=e.min(4*t,i),t){for(var c=0;c<t;c+=o)this._doProcessBlock(r,c);c=r.splice(0,t),n.sigBytes-=i}return new s.init(c,i)},clone:function(){var e=o.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});r.Hasher=f.extend({cfg:o.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){f.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,n){return new e.init(n).finalize(t)}},_createHmacHelper:function(e){return function(t,n){return new l.HMAC.init(e,n).finalize(t)}}});var l=n.algo={};return n}(Math);!function(e){for(var t=B,n=t.lib,r=n.WordArray,i=n.Hasher,n=t.algo,o=[],s=[],a=function(e){return 4294967296*(e-(0|e))|0},c=2,u=0;u<64;){var h;e:{h=c;for(var f=e.sqrt(h),l=2;l<=f;l++)if(!(h%l)){h=!1;break e}h=!0}h&&(u<8&&(o[u]=a(e.pow(c,.5))),s[u]=a(e.pow(c,1/3)),u++),c++}var d=[],n=n.SHA256=i.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,r=n[0],i=n[1],o=n[2],a=n[3],c=n[4],u=n[5],h=n[6],f=n[7],l=0;l<64;l++){if(l<16)d[l]=0|e[t+l];else{var p=d[l-15],g=d[l-2];d[l]=((p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3)+d[l-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+d[l-16]}p=f+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&h)+s[l]+d[l],g=((r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22))+(r&i^r&o^i&o),f=h,h=u,u=c,c=a+p|0,a=o,o=i,i=r,r=p+g|0}n[0]=n[0]+r|0,n[1]=n[1]+i|0,n[2]=n[2]+o|0,n[3]=n[3]+a|0,n[4]=n[4]+c|0,n[5]=n[5]+u|0,n[6]=n[6]+h|0,n[7]=n[7]+f|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;return n[i>>>5]|=128<<24-i%32,n[14+(i+64>>>9<<4)]=e.floor(r/4294967296),n[15+(i+64>>>9<<4)]=r,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=i._createHelper(n),t.HmacSHA256=i._createHmacHelper(n)}(Math),function(){var e=B,t=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,n){e=this._hasher=new e.init,"string"==typeof n&&(n=t.parse(n));var r=e.blockSize,i=4*r;n.sigBytes>i&&(n=e.finalize(n)),n.clamp();for(var o=this._oKey=n.clone(),s=this._iKey=n.clone(),a=o.words,c=s.words,u=0;u<r;u++)a[u]^=1549556828,c[u]^=909522486;o.sigBytes=s.sigBytes=i,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var t=this._hasher;return e=t.finalize(e),t.reset(),t.finalize(this._oKey.clone().concat(e))}})}();var j="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},D=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},K=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),M=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},N={region:"eu-west-1",service:"execute-api",defaultContentType:"application/json",defaultAcceptType:"application/json",payloadSerializerFactory:p,uriParserFactory:g,hasherFactory:y},R=function(){function e(t){D(this,e),this.config=v({},N,t),this.payloadSerializer=this.config.payloadSerializer||this.config.payloadSerializerFactory(),this.uriParser=this.config.uriParserFactory(),this.hasher=this.config.hasherFactory(),m(this.config.accessKeyId,"AwsSigner requires AWS AccessKeyID"),m(this.config.secretAccessKey,"AwsSigner requires AWS SecretAccessKey")}return K(e,[{key:"sign",value:function(e,t){var n={request:v({},e),signDate:t||new Date,uri:this.uriParser(e.url)};return c(this,n),u(this,n),h(this,n),f(this,n),l(this,n),{Accept:n.request.headers.accept,Authorization:n.authorization,"Content-Type":n.request.headers["content-type"],"x-amz-date":n.request.headers["x-amz-date"],"x-amz-security-token":this.config.sessionToken||void 0}}}]),e}(),L=["size","duration"],F=function(){function e(t){D(this,e),M(this,t),n().session.new&&this.logEvent({category:"_session.start"})}return K(e,[{key:"logPageView",value:function(e){k(w(e),this.userPoolID,this.app)}},{key:"logEvent",value:function(e){k(S(e),this.userPoolID,this.app)}}]),e}(),U=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};D(this,e),M(this,t)}return K(e,[{key:"logPageView",value:function(e){E().then(function(t){t.forEach(function(t){t.send("pageview",e||window.location.pathname)})}).catch(function(e){return console.error(e)})}},{key:"logEvent",value:function(e){var t=z(e,this.dimensions,this.metrics);E().then(function(e){e.forEach(function(e){e.send(t)})}).catch(function(e){return console.error(e)})}}]),e}(),J=function(e){return B.SHA256(e).toString(B.enc.Hex)};return function(){function e(t){if(D(this,e),this.trackers=[],t.amazon){var n=new F(t.amazon);this.trackers.push(n)}if(t.google){var r=new U(t.google);this.trackers.push(r)}this.trackers.length||console.error(new Error("No trackers configured"))}return K(e,[{key:"logPageView",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=T(t);return this.trackers.length||this.disabled?(this.trackers.forEach(function(t){return t.logPageView(e,n)}),!0):(this.disabled||console.error(new Error("Page view was not logged because no trackers are configured.")),!1)}},{key:"logEvent",value:function(e){var t=T(e);return this.trackers.length||this.disabled?(this.trackers.forEach(function(e){return e.logEvent(t)}),!0):(this.disabled||console.error(new Error("Event was not logged because no trackers are configured.")),!1)}}]),e}()}); | ||
define("telemetry",function(){"use strict";function e(e,t){var n=new XMLHttpRequest;n.addEventListener("load",function(){t(n.responseText)}),n.open(e.method,e.url),Object.keys(e.headers).forEach(function(t){n.setRequestHeader(t,e.headers[t])}),n.send(e.body)}function t(e,t){var r=window.localStorage.getItem(D);if(r&&(r=JSON.parse(r)),r&&Date.now()/1e3<r.Expiration)return t(r);n(e,function(e){window.localStorage.setItem(D,JSON.stringify(e)),t(e)})}function n(t,n){var i=j({},K);i.headers["X-Amz-Target"]="AWSCognitoIdentityService.GetId",i.body=JSON.stringify({IdentityPoolId:t}),e(i,function(e){r(JSON.parse(e),n)})}function r(t,n){var r=j({},K);r.headers["X-Amz-Target"]="AWSCognitoIdentityService.GetCredentialsForIdentity",r.body=JSON.stringify({IdentityId:t.IdentityId}),e(r,function(e){var t=JSON.parse(e);n(t.Credentials)})}function i(){return{session:o(),id:s()}}function o(){var e=void 0,t=void 0,n=window.localStorage.getItem(M);return n&&(n=JSON.parse(n),Date.now()<n.expiration&&(e=n)),e||(t=!0,e=a()),e.expiration=Date.now()+N,window.localStorage.setItem(M,JSON.stringify(e)),t&&(e.new=!0),e}function s(){var e=window.localStorage.getItem(R);return e||(e=c(),window.localStorage.setItem(R,e)),e}function a(){return{id:Math.floor(17592186044416*(1+Math.random())).toString(16),startTimestamp:(new Date).toISOString()}}function c(){return u()+u()+"-"+u()+"-"+u()+"-"+u()+"-"+u()+u()+u()}function u(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function h(e,t){var n={host:t.uri.host,"content-type":e.config.defaultContentType,accept:e.config.defaultAcceptType,"x-amz-date":g(t.signDate)};t.request.method=t.request.method.toUpperCase(),t.request.body?t.payload=t.request.body:t.request.data&&e.payloadSerializer?t.payload=e.payloadSerializer(t.request.data):delete n["content-type"],t.request.headers=w(n,Object.keys(t.request.headers||{}).reduce(function(e,n){return e[n.toLowerCase()]=t.request.headers[n],e},{})),t.sortedHeaderKeys=Object.keys(t.request.headers).sort(),t.request.headers["content-type"]&&(t.request.headers["content-type"]=t.request.headers["content-type"].split(";")[0]),"object"===C(t.request.params)&&w(t.uri.queryParams,t.request.params)}function f(e,t){t.signedHeaders=t.sortedHeaderKeys.map(function(e){return e.toLowerCase()}).join(";"),t.canonicalRequest=String(t.request.method).toUpperCase()+"\n"+encodeURI(t.uri.path)+"\n"+Object.keys(t.uri.queryParams).sort().map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(t.uri.queryParams[e])}).join("&")+"\n"+t.sortedHeaderKeys.map(function(e){return e.toLocaleLowerCase()+":"+t.request.headers[e]}).join("\n")+"\n\n"+t.signedHeaders+"\n"+e.hasher.hash(t.payload?t.payload:"")}function l(e,t){t.credentialScope=[g(t.signDate,!0),e.config.region,e.config.service,"aws4_request"].join("/"),t.stringToSign="AWS4-HMAC-SHA256\n"+g(t.signDate)+"\n"+t.credentialScope+"\n"+e.hasher.hash(t.canonicalRequest)}function d(e,t){var n=e.hasher.hmac,r=n(n(n(n("AWS4"+e.config.secretAccessKey,g(t.signDate,!0),{hexOutput:!1}),e.config.region,{hexOutput:!1,textInput:!1}),e.config.service,{hexOutput:!1,textInput:!1}),"aws4_request",{hexOutput:!1,textInput:!1});t.signature=n(r,t.stringToSign,{textInput:!1})}function p(e,t){t.authorization="AWS4-HMAC-SHA256 Credential="+e.config.accessKeyId+"/"+t.credentialScope+", SignedHeaders="+t.signedHeaders+", Signature="+t.signature}function g(e,t){var n=e.toISOString().replace(/[:\-]|\.\d{3}/g,"").substr(0,17);return t?n.substr(0,8):n}function y(){return function(e){return JSON.stringify(e)}}function v(){function e(e){return/^\??(.*)$/.exec(e)[1].split("&").reduce(function(e,t){return t=/^(.+)=(.*)$/.exec(t),t&&(e[t[1]]=t[2]),e},{})}var t=document?document.createElement("a"):{};return function(n){return t.href=n,{protocol:t.protocol,host:t.host.replace(/^(.*):((80)|(443))$/,"$1"),path:("/"!==t.pathname.charAt(0)?"/":"")+t.pathname,queryParams:e(t.search)}}}function m(){return{hash:function(e,t){t=w({hexOutput:!0,textInput:!0},t);var n=L.SHA256(e);return t.hexOutput?n.toString(L.enc.Hex):n},hmac:function(e,t,n){n=w({hexOutput:!0,textInput:!0},n);var r=L.HmacSHA256(t,e,{asBytes:!0});return n.hexOutput?r.toString(L.enc.Hex):r}}}function w(e){return[].slice.call(arguments,1).forEach(function(t){t&&"object"===(void 0===t?"undefined":C(t))&&Object.keys(t).forEach(function(n){var r=t[n];void 0!==r&&(null!==r&&"object"===(void 0===r?"undefined":C(r))?(e[n]=Array.isArray(r)?[]:{},w(e[n],r)):e[n]=r)})}),e}function S(e,t){if(void 0===e||!e)throw new Error(t)}function b(e){var t=i().session;return{eventType:"pageView",timestamp:(new Date).toISOString(),session:{id:t.id,startTimestamp:t.startTimestamp},attributes:{referrer:document.referrer,hostname:window.location.hostname,path:window.location.pathname||e},metrics:{}}}function _(e){var t=i().session;return{eventType:A(e),timestamp:(new Date).toISOString(),session:{id:t.id,startTimestamp:t.startTimestamp},attributes:j({referrer:document.referrer,hostname:window.location.hostname,path:window.location.pathname},I(e)),metrics:x(e)}}function A(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.workflow||e.process||e.category;return t||(e.error?"error":"other")}function I(e){var t=j({},e);return U.forEach(function(e){return delete t[e]}),t}function x(e){var t={};return U.forEach(function(n){t[n]=e[n]}),t}function O(e,t){var n={region:"us-east-1",service:"mobileanalytics",accessKeyId:e.AccessKeyId,secretAccessKey:e.SecretKey,sessionToken:e.SessionToken};return new F(n).sign(t)}function k(e,t){return JSON.stringify({client:{client_id:e,app_title:t.name,app_version_name:t.version||"unknown"},services:{mobile_analytics:{app_id:t.id}}})}function E(n,r,o){var s=i();n=Array.isArray(n)?n:[n];var a=z(n);t(r,function(t){a.headers=O(t,a),a.headers["x-amz-Client-Context"]=k(s.id,o),e(a,function(e){e&&console.error(JSON.parse(e))})})}function z(e){return{url:arguments.length>1&&void 0!==arguments[1]?arguments[1]:W,method:"POST",body:JSON.stringify({events:e})}}function H(){return new Promise(function(e,t){window.ga?window.ga(function(){e(window.ga.getAll())}):t(new Error("Google Analytics trackers not available"))})}function q(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={hitType:"event",eventCategory:e.category||"none",eventAction:e.action,eventLabel:e.label};return Object.keys(t).forEach(function(n){r["dimension"+t[n]]=e[n]}),Object.keys(n).forEach(function(t){r["metric"+n[t]]=e[t]}),r}function T(e){var t=j({},e);return t.user&&(t.user=G(t.user)),t}var C="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},B=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},P=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),j=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},D="TELEMETRY_COGNITO_CREDENTIALS",K={method:"POST",url:"https://cognito-identity.us-east-1.amazonaws.com/",headers:{"Content-type":"application/x-amz-json-1.1"}},N=18e5,M="TELEMETRY_SESSION",R="TELEMETRY_CLIENT_ID",L=function(e,t){var n={},r=n.lib={},i=function(){},o=r.Base={extend:function(e){i.prototype=this;var t=new i;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=r.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=void 0!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,n=e.words,r=this.sigBytes;if(e=e.sigBytes,this.clamp(),r%4)for(var i=0;i<e;i++)t[r+i>>>2]|=(n[i>>>2]>>>24-i%4*8&255)<<24-(r+i)%4*8;else if(n.length>65535)for(i=0;i<e;i+=4)t[r+i>>>2]=n[i>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],r=0;r<t;r+=4)n.push(4294967296*e.random()|0);return new s.init(n,t)}}),a=n.enc={},c=a.Hex={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r<e;r++){var i=t[r>>>2]>>>24-r%4*8&255;n.push((i>>>4).toString(16)),n.push((15&i).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r<t;r+=2)n[r>>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},u=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r<e;r++)n.push(String.fromCharCode(t[r>>>2]>>>24-r%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r<t;r++)n[r>>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},h=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},f=r.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=h.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,i=n.sigBytes,o=this.blockSize,a=i/(4*o),a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0);if(t=a*o,i=e.min(4*t,i),t){for(var c=0;c<t;c+=o)this._doProcessBlock(r,c);c=r.splice(0,t),n.sigBytes-=i}return new s.init(c,i)},clone:function(){var e=o.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});r.Hasher=f.extend({cfg:o.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){f.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,n){return new e.init(n).finalize(t)}},_createHmacHelper:function(e){return function(t,n){return new l.HMAC.init(e,n).finalize(t)}}});var l=n.algo={};return n}(Math);!function(e){for(var t=L,n=t.lib,r=n.WordArray,i=n.Hasher,n=t.algo,o=[],s=[],a=function(e){return 4294967296*(e-(0|e))|0},c=2,u=0;u<64;){var h;e:{h=c;for(var f=e.sqrt(h),l=2;l<=f;l++)if(!(h%l)){h=!1;break e}h=!0}h&&(u<8&&(o[u]=a(e.pow(c,.5))),s[u]=a(e.pow(c,1/3)),u++),c++}var d=[],n=n.SHA256=i.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,r=n[0],i=n[1],o=n[2],a=n[3],c=n[4],u=n[5],h=n[6],f=n[7],l=0;l<64;l++){if(l<16)d[l]=0|e[t+l];else{var p=d[l-15],g=d[l-2];d[l]=((p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3)+d[l-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+d[l-16]}p=f+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&h)+s[l]+d[l],g=((r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22))+(r&i^r&o^i&o),f=h,h=u,u=c,c=a+p|0,a=o,o=i,i=r,r=p+g|0}n[0]=n[0]+r|0,n[1]=n[1]+i|0,n[2]=n[2]+o|0,n[3]=n[3]+a|0,n[4]=n[4]+c|0,n[5]=n[5]+u|0,n[6]=n[6]+h|0,n[7]=n[7]+f|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;return n[i>>>5]|=128<<24-i%32,n[14+(i+64>>>9<<4)]=e.floor(r/4294967296),n[15+(i+64>>>9<<4)]=r,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=i._createHelper(n),t.HmacSHA256=i._createHmacHelper(n)}(Math),function(){var e=L,t=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,n){e=this._hasher=new e.init,"string"==typeof n&&(n=t.parse(n));var r=e.blockSize,i=4*r;n.sigBytes>i&&(n=e.finalize(n)),n.clamp();for(var o=this._oKey=n.clone(),s=this._iKey=n.clone(),a=o.words,c=s.words,u=0;u<r;u++)a[u]^=1549556828,c[u]^=909522486;o.sigBytes=s.sigBytes=i,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var t=this._hasher;return e=t.finalize(e),t.reset(),t.finalize(this._oKey.clone().concat(e))}})}();var J={region:"eu-west-1",service:"execute-api",defaultContentType:"application/json",defaultAcceptType:"application/json",payloadSerializerFactory:y,uriParserFactory:v,hasherFactory:m},F=function(){function e(t){B(this,e),this.config=w({},J,t),this.payloadSerializer=this.config.payloadSerializer||this.config.payloadSerializerFactory(),this.uriParser=this.config.uriParserFactory(),this.hasher=this.config.hasherFactory(),S(this.config.accessKeyId,"AwsSigner requires AWS AccessKeyID"),S(this.config.secretAccessKey,"AwsSigner requires AWS SecretAccessKey")}return P(e,[{key:"sign",value:function(e,t){var n={request:w({},e),signDate:t||new Date,uri:this.uriParser(e.url)};return h(this,n),f(this,n),l(this,n),d(this,n),p(this,n),{Accept:n.request.headers.accept,Authorization:n.authorization,"Content-Type":n.request.headers["content-type"],"x-amz-date":n.request.headers["x-amz-date"],"x-amz-security-token":this.config.sessionToken||void 0}}}]),e}(),U=["size","duration"],W="https://mobileanalytics.us-east-1.amazonaws.com/2014-06-05/events",$=function(){function e(t){B(this,e),j(this,t),i().session.new&&this.logEvent({category:"_session.start"})}return P(e,[{key:"logPageView",value:function(e){E(b(e),this.userPoolID,this.app)}},{key:"logEvent",value:function(e){E(_(e),this.userPoolID,this.app)}}]),e}(),V=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),j(this,t)}return P(e,[{key:"logPageView",value:function(e){H().then(function(t){t.forEach(function(t){t.send("pageview",e||window.location.pathname)})}).catch(function(e){return console.error(e)})}},{key:"logEvent",value:function(e){var t=q(e,this.dimensions,this.metrics);H().then(function(e){e.forEach(function(e){e.send(t)})}).catch(function(e){return console.error(e)})}}]),e}(),G=function(e){return L.SHA256(e).toString(L.enc.Hex)};return function(){function e(t){if(B(this,e),this.trackers=[],t.amazon){var n=new $(t.amazon);this.trackers.push(n)}if(t.google){var r=new V(t.google);this.trackers.push(r)}this.trackers.length||console.error(new Error("No trackers configured"))}return P(e,[{key:"logPageView",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=T(t);return this.trackers.length||this.disabled?(this.trackers.forEach(function(t){return t.logPageView(e,n)}),!0):(this.disabled||console.error(new Error("Page view was not logged because no trackers are configured.")),!1)}},{key:"logEvent",value:function(e){var t=T(e);return this.trackers.length||this.disabled?(this.trackers.forEach(function(e){return e.logEvent(t)}),!0):(this.disabled||console.error(new Error("Event was not logged because no trackers are configured.")),!1)}}]),e}()}); | ||
//# sourceMappingURL=telemetry.amd.min.js.map |
@@ -7,43 +7,120 @@ (function (global, factory) { | ||
function request(options, callback) { | ||
var req = new XMLHttpRequest(); | ||
req.addEventListener('load', function () { | ||
callback(req.responseText); | ||
}); | ||
req.open(options.method, options.url); | ||
Object.keys(options.headers).forEach(function (header) { | ||
req.setRequestHeader(header, options.headers[header]); | ||
}); | ||
req.send(options.body); | ||
} | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { | ||
return typeof obj; | ||
} : function (obj) { | ||
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; | ||
}; | ||
var classCallCheck = function (instance, Constructor) { | ||
if (!(instance instanceof Constructor)) { | ||
throw new TypeError("Cannot call a class as a function"); | ||
} | ||
}; | ||
var createClass = function () { | ||
function defineProperties(target, props) { | ||
for (var i = 0; i < props.length; i++) { | ||
var descriptor = props[i]; | ||
descriptor.enumerable = descriptor.enumerable || false; | ||
descriptor.configurable = true; | ||
if ("value" in descriptor) descriptor.writable = true; | ||
Object.defineProperty(target, descriptor.key, descriptor); | ||
} | ||
} | ||
return function (Constructor, protoProps, staticProps) { | ||
if (protoProps) defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) defineProperties(Constructor, staticProps); | ||
return Constructor; | ||
}; | ||
}(); | ||
var _extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
var COGNITO_KEY = 'TELEMETRY_COGNITO_CREDENTIALS'; | ||
var COGNITO_URL = 'https://cognito-identity.us-east-1.amazonaws.com/'; | ||
function getCredentials(IdentityPoolId) { | ||
function getCredentials(IdentityPoolId, callback) { | ||
var cached = window.localStorage.getItem(COGNITO_KEY); | ||
if (cached) cached = JSON.parse(cached); | ||
if (cached && Date.now() / 1000 < cached.Expiration) return Promise.resolve(cached); | ||
if (cached && Date.now() / 1000 < cached.Expiration) return callback(cached); | ||
return authWithCognito(IdentityPoolId).then(function (credentials) { | ||
authWithCognito(IdentityPoolId, function (credentials) { | ||
window.localStorage.setItem(COGNITO_KEY, JSON.stringify(credentials)); | ||
return credentials; | ||
callback(credentials); | ||
}); | ||
} | ||
function authWithCognito(IdentityPoolId) { | ||
return fetch('https://cognito-identity.us-east-1.amazonaws.com/', { | ||
method: 'POST', | ||
headers: { | ||
'Content-type': 'application/x-amz-json-1.1', | ||
'X-Amz-Target': 'AWSCognitoIdentityService.GetId' | ||
}, | ||
body: JSON.stringify({ IdentityPoolId: IdentityPoolId }) | ||
}).then(function (r) { | ||
return r.json(); | ||
}).then(function (json) { | ||
return fetch('https://cognito-identity.us-east-1.amazonaws.com/', { | ||
method: 'POST', | ||
headers: { | ||
'Content-type': 'application/x-amz-json-1.1', | ||
'X-Amz-Target': 'AWSCognitoIdentityService.GetCredentialsForIdentity' | ||
}, | ||
body: JSON.stringify({ IdentityId: json.IdentityId }) | ||
}); | ||
}).then(function (r) { | ||
return r.json(); | ||
}).then(function (json) { | ||
return json.Credentials; | ||
}).catch(function (e) { | ||
throw new Error('Authentication with cognito failed, check your user pool settings'); | ||
function authWithCognito(IdentityPoolId, callback) { | ||
var options = _extends({}, defaults$$1); | ||
options.headers['X-Amz-Target'] = 'AWSCognitoIdentityService.GetId'; | ||
options.body = JSON.stringify({ IdentityPoolId: IdentityPoolId }); | ||
request(options, function (response) { | ||
requestCredentials(JSON.parse(response), callback); | ||
}); | ||
} | ||
function requestCredentials(json, callback) { | ||
var options = _extends({}, defaults$$1); | ||
options.headers['X-Amz-Target'] = 'AWSCognitoIdentityService.GetCredentialsForIdentity'; | ||
options.body = JSON.stringify({ IdentityId: json.IdentityId }); | ||
request(options, function (response) { | ||
var json = JSON.parse(response); | ||
callback(json.Credentials); | ||
}); | ||
} | ||
var defaults$$1 = { | ||
method: 'POST', | ||
url: COGNITO_URL, | ||
headers: { | ||
'Content-type': 'application/x-amz-json-1.1' | ||
} | ||
}; | ||
var SESSION_LENGTH = 30 * 60 * 1000; | ||
@@ -280,62 +357,2 @@ var SESSION_KEY = 'TELEMETRY_SESSION'; | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { | ||
return typeof obj; | ||
} : function (obj) { | ||
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; | ||
}; | ||
var classCallCheck = function (instance, Constructor) { | ||
if (!(instance instanceof Constructor)) { | ||
throw new TypeError("Cannot call a class as a function"); | ||
} | ||
}; | ||
var createClass = function () { | ||
function defineProperties(target, props) { | ||
for (var i = 0; i < props.length; i++) { | ||
var descriptor = props[i]; | ||
descriptor.enumerable = descriptor.enumerable || false; | ||
descriptor.configurable = true; | ||
if ("value" in descriptor) descriptor.writable = true; | ||
Object.defineProperty(target, descriptor.key, descriptor); | ||
} | ||
} | ||
return function (Constructor, protoProps, staticProps) { | ||
if (protoProps) defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) defineProperties(Constructor, staticProps); | ||
return Constructor; | ||
}; | ||
}(); | ||
var _extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
// | ||
@@ -640,2 +657,3 @@ // AWS Signature v4 Implementation for Web Browsers | ||
var METRICS = ['size', 'duration']; | ||
var DEFAULT_ENDPOINT = 'https://mobileanalytics.us-east-1.amazonaws.com/2014-06-05/events'; | ||
@@ -765,9 +783,9 @@ var Amazon = function () { | ||
var options = createTelemetryOptions(events); | ||
return getCredentials(userPoolID).then(function (credentials) { | ||
getCredentials(userPoolID, function (credentials) { | ||
options.headers = createHeaders(credentials, options); | ||
options.headers['x-amz-Client-Context'] = createClientContext(user.id, app); | ||
fetch(options.url, options).then(function (r) { | ||
return console.log(r); | ||
}).catch(function (e) { | ||
return console.error(e); | ||
request(options, function (response) { | ||
if (response) { | ||
console.error(JSON.parse(response)); | ||
} | ||
}); | ||
@@ -778,3 +796,3 @@ }); | ||
function createTelemetryOptions(events) { | ||
var url = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'https://mobileanalytics.us-east-1.amazonaws.com/2014-06-05/events'; | ||
var url = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ENDPOINT; | ||
@@ -781,0 +799,0 @@ return { |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define("telemetry",t):e.Telemetry=t()}(this,function(){"use strict";function e(e){var n=window.localStorage.getItem(C);return n&&(n=JSON.parse(n)),n&&Date.now()/1e3<n.Expiration?Promise.resolve(n):t(e).then(function(e){return window.localStorage.setItem(C,JSON.stringify(e)),e})}function t(e){return fetch("https://cognito-identity.us-east-1.amazonaws.com/",{method:"POST",headers:{"Content-type":"application/x-amz-json-1.1","X-Amz-Target":"AWSCognitoIdentityService.GetId"},body:JSON.stringify({IdentityPoolId:e})}).then(function(e){return e.json()}).then(function(e){return fetch("https://cognito-identity.us-east-1.amazonaws.com/",{method:"POST",headers:{"Content-type":"application/x-amz-json-1.1","X-Amz-Target":"AWSCognitoIdentityService.GetCredentialsForIdentity"},body:JSON.stringify({IdentityId:e.IdentityId})})}).then(function(e){return e.json()}).then(function(e){return e.Credentials}).catch(function(e){throw new Error("Authentication with cognito failed, check your user pool settings")})}function n(){return{session:r(),id:i()}}function r(){var e=void 0,t=void 0,n=window.localStorage.getItem(q);return n&&(n=JSON.parse(n),Date.now()<n.expiration&&(e=n)),e||(t=!0,e=o()),e.expiration=Date.now()+H,window.localStorage.setItem(q,JSON.stringify(e)),t&&(e.new=!0),e}function i(){var e=window.localStorage.getItem(P);return e||(e=s(),window.localStorage.setItem(P,e)),e}function o(){return{id:Math.floor(17592186044416*(1+Math.random())).toString(16),startTimestamp:(new Date).toISOString()}}function s(){return a()+a()+"-"+a()+"-"+a()+"-"+a()+"-"+a()+a()+a()}function a(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function c(e,t){var n={host:t.uri.host,"content-type":e.config.defaultContentType,accept:e.config.defaultAcceptType,"x-amz-date":d(t.signDate)};t.request.method=t.request.method.toUpperCase(),t.request.body?t.payload=t.request.body:t.request.data&&e.payloadSerializer?t.payload=e.payloadSerializer(t.request.data):delete n["content-type"],t.request.headers=m(n,Object.keys(t.request.headers||{}).reduce(function(e,n){return e[n.toLowerCase()]=t.request.headers[n],e},{})),t.sortedHeaderKeys=Object.keys(t.request.headers).sort(),t.request.headers["content-type"]&&(t.request.headers["content-type"]=t.request.headers["content-type"].split(";")[0]),"object"===j(t.request.params)&&m(t.uri.queryParams,t.request.params)}function u(e,t){t.signedHeaders=t.sortedHeaderKeys.map(function(e){return e.toLowerCase()}).join(";"),t.canonicalRequest=String(t.request.method).toUpperCase()+"\n"+encodeURI(t.uri.path)+"\n"+Object.keys(t.uri.queryParams).sort().map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(t.uri.queryParams[e])}).join("&")+"\n"+t.sortedHeaderKeys.map(function(e){return e.toLocaleLowerCase()+":"+t.request.headers[e]}).join("\n")+"\n\n"+t.signedHeaders+"\n"+e.hasher.hash(t.payload?t.payload:"")}function h(e,t){t.credentialScope=[d(t.signDate,!0),e.config.region,e.config.service,"aws4_request"].join("/"),t.stringToSign="AWS4-HMAC-SHA256\n"+d(t.signDate)+"\n"+t.credentialScope+"\n"+e.hasher.hash(t.canonicalRequest)}function f(e,t){var n=e.hasher.hmac,r=n(n(n(n("AWS4"+e.config.secretAccessKey,d(t.signDate,!0),{hexOutput:!1}),e.config.region,{hexOutput:!1,textInput:!1}),e.config.service,{hexOutput:!1,textInput:!1}),"aws4_request",{hexOutput:!1,textInput:!1});t.signature=n(r,t.stringToSign,{textInput:!1})}function l(e,t){t.authorization="AWS4-HMAC-SHA256 Credential="+e.config.accessKeyId+"/"+t.credentialScope+", SignedHeaders="+t.signedHeaders+", Signature="+t.signature}function d(e,t){var n=e.toISOString().replace(/[:\-]|\.\d{3}/g,"").substr(0,17);return t?n.substr(0,8):n}function p(){return function(e){return JSON.stringify(e)}}function g(){function e(e){return/^\??(.*)$/.exec(e)[1].split("&").reduce(function(e,t){return t=/^(.+)=(.*)$/.exec(t),t&&(e[t[1]]=t[2]),e},{})}var t=document?document.createElement("a"):{};return function(n){return t.href=n,{protocol:t.protocol,host:t.host.replace(/^(.*):((80)|(443))$/,"$1"),path:("/"!==t.pathname.charAt(0)?"/":"")+t.pathname,queryParams:e(t.search)}}}function y(){return{hash:function(e,t){t=m({hexOutput:!0,textInput:!0},t);var n=B.SHA256(e);return t.hexOutput?n.toString(B.enc.Hex):n},hmac:function(e,t,n){n=m({hexOutput:!0,textInput:!0},n);var r=B.HmacSHA256(t,e,{asBytes:!0});return n.hexOutput?r.toString(B.enc.Hex):r}}}function m(e){return[].slice.call(arguments,1).forEach(function(t){t&&"object"===(void 0===t?"undefined":j(t))&&Object.keys(t).forEach(function(n){var r=t[n];void 0!==r&&(null!==r&&"object"===(void 0===r?"undefined":j(r))?(e[n]=Array.isArray(r)?[]:{},m(e[n],r)):e[n]=r)})}),e}function v(e,t){if(void 0===e||!e)throw new Error(t)}function w(e){var t=n().session;return{eventType:"pageView",timestamp:(new Date).toISOString(),session:{id:t.id,startTimestamp:t.startTimestamp},attributes:{referrer:document.referrer,hostname:window.location.hostname,path:window.location.pathname||e},metrics:{}}}function S(e){var t=n().session;return{eventType:b(e),timestamp:(new Date).toISOString(),session:{id:t.id,startTimestamp:t.startTimestamp},attributes:M({referrer:document.referrer,hostname:window.location.hostname,path:window.location.pathname},_(e)),metrics:x(e)}}function b(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.workflow||e.process||e.category;return t||(e.error?"error":"other")}function _(e){var t=M({},e);return L.forEach(function(e){return delete t[e]}),t}function x(e){var t={};return L.forEach(function(n){t[n]=e[n]}),t}function A(e,t){var n={region:"us-east-1",service:"mobileanalytics",accessKeyId:e.AccessKeyId,secretAccessKey:e.SecretKey,sessionToken:e.SessionToken};return new R(n).sign(t)}function I(e,t){return JSON.stringify({client:{client_id:e,app_title:t.name,app_version_name:t.version||"unknown"},services:{mobile_analytics:{app_id:t.id}}})}function k(t,r,i){var o=n();t=Array.isArray(t)?t:[t];var s=O(t);return e(r).then(function(e){s.headers=A(e,s),s.headers["x-amz-Client-Context"]=I(o.id,i),fetch(s.url,s).then(function(e){return console.log(e)}).catch(function(e){return console.error(e)})})}function O(e){return{url:arguments.length>1&&void 0!==arguments[1]?arguments[1]:"https://mobileanalytics.us-east-1.amazonaws.com/2014-06-05/events",method:"POST",body:JSON.stringify({events:e})}}function E(){return new Promise(function(e,t){window.ga?window.ga(function(){e(window.ga.getAll())}):t(new Error("Google Analytics trackers not available"))})}function z(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={hitType:"event",eventCategory:e.category||"none",eventAction:e.action,eventLabel:e.label};return Object.keys(t).forEach(function(n){r["dimension"+t[n]]=e[n]}),Object.keys(n).forEach(function(t){r["metric"+n[t]]=e[t]}),r}function T(e){var t=M({},e);return t.user&&(t.user=J(t.user)),t}var C="TELEMETRY_COGNITO_CREDENTIALS",H=18e5,q="TELEMETRY_SESSION",P="TELEMETRY_CLIENT_ID",B=function(e,t){var n={},r=n.lib={},i=function(){},o=r.Base={extend:function(e){i.prototype=this;var t=new i;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=r.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=void 0!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,n=e.words,r=this.sigBytes;if(e=e.sigBytes,this.clamp(),r%4)for(var i=0;i<e;i++)t[r+i>>>2]|=(n[i>>>2]>>>24-i%4*8&255)<<24-(r+i)%4*8;else if(n.length>65535)for(i=0;i<e;i+=4)t[r+i>>>2]=n[i>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],r=0;r<t;r+=4)n.push(4294967296*e.random()|0);return new s.init(n,t)}}),a=n.enc={},c=a.Hex={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r<e;r++){var i=t[r>>>2]>>>24-r%4*8&255;n.push((i>>>4).toString(16)),n.push((15&i).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r<t;r+=2)n[r>>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},u=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r<e;r++)n.push(String.fromCharCode(t[r>>>2]>>>24-r%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r<t;r++)n[r>>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},h=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},f=r.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=h.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,i=n.sigBytes,o=this.blockSize,a=i/(4*o),a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0);if(t=a*o,i=e.min(4*t,i),t){for(var c=0;c<t;c+=o)this._doProcessBlock(r,c);c=r.splice(0,t),n.sigBytes-=i}return new s.init(c,i)},clone:function(){var e=o.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});r.Hasher=f.extend({cfg:o.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){f.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,n){return new e.init(n).finalize(t)}},_createHmacHelper:function(e){return function(t,n){return new l.HMAC.init(e,n).finalize(t)}}});var l=n.algo={};return n}(Math);!function(e){for(var t=B,n=t.lib,r=n.WordArray,i=n.Hasher,n=t.algo,o=[],s=[],a=function(e){return 4294967296*(e-(0|e))|0},c=2,u=0;u<64;){var h;e:{h=c;for(var f=e.sqrt(h),l=2;l<=f;l++)if(!(h%l)){h=!1;break e}h=!0}h&&(u<8&&(o[u]=a(e.pow(c,.5))),s[u]=a(e.pow(c,1/3)),u++),c++}var d=[],n=n.SHA256=i.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,r=n[0],i=n[1],o=n[2],a=n[3],c=n[4],u=n[5],h=n[6],f=n[7],l=0;l<64;l++){if(l<16)d[l]=0|e[t+l];else{var p=d[l-15],g=d[l-2];d[l]=((p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3)+d[l-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+d[l-16]}p=f+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&h)+s[l]+d[l],g=((r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22))+(r&i^r&o^i&o),f=h,h=u,u=c,c=a+p|0,a=o,o=i,i=r,r=p+g|0}n[0]=n[0]+r|0,n[1]=n[1]+i|0,n[2]=n[2]+o|0,n[3]=n[3]+a|0,n[4]=n[4]+c|0,n[5]=n[5]+u|0,n[6]=n[6]+h|0,n[7]=n[7]+f|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;return n[i>>>5]|=128<<24-i%32,n[14+(i+64>>>9<<4)]=e.floor(r/4294967296),n[15+(i+64>>>9<<4)]=r,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=i._createHelper(n),t.HmacSHA256=i._createHmacHelper(n)}(Math),function(){var e=B,t=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,n){e=this._hasher=new e.init,"string"==typeof n&&(n=t.parse(n));var r=e.blockSize,i=4*r;n.sigBytes>i&&(n=e.finalize(n)),n.clamp();for(var o=this._oKey=n.clone(),s=this._iKey=n.clone(),a=o.words,c=s.words,u=0;u<r;u++)a[u]^=1549556828,c[u]^=909522486;o.sigBytes=s.sigBytes=i,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var t=this._hasher;return e=t.finalize(e),t.reset(),t.finalize(this._oKey.clone().concat(e))}})}();var j="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},D=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},K=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),M=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},N={region:"eu-west-1",service:"execute-api",defaultContentType:"application/json",defaultAcceptType:"application/json",payloadSerializerFactory:p,uriParserFactory:g,hasherFactory:y},R=function(){function e(t){D(this,e),this.config=m({},N,t),this.payloadSerializer=this.config.payloadSerializer||this.config.payloadSerializerFactory(),this.uriParser=this.config.uriParserFactory(),this.hasher=this.config.hasherFactory(),v(this.config.accessKeyId,"AwsSigner requires AWS AccessKeyID"),v(this.config.secretAccessKey,"AwsSigner requires AWS SecretAccessKey")}return K(e,[{key:"sign",value:function(e,t){var n={request:m({},e),signDate:t||new Date,uri:this.uriParser(e.url)};return c(this,n),u(this,n),h(this,n),f(this,n),l(this,n),{Accept:n.request.headers.accept,Authorization:n.authorization,"Content-Type":n.request.headers["content-type"],"x-amz-date":n.request.headers["x-amz-date"],"x-amz-security-token":this.config.sessionToken||void 0}}}]),e}(),L=["size","duration"],F=function(){function e(t){D(this,e),M(this,t),n().session.new&&this.logEvent({category:"_session.start"})}return K(e,[{key:"logPageView",value:function(e){k(w(e),this.userPoolID,this.app)}},{key:"logEvent",value:function(e){k(S(e),this.userPoolID,this.app)}}]),e}(),U=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};D(this,e),M(this,t)}return K(e,[{key:"logPageView",value:function(e){E().then(function(t){t.forEach(function(t){t.send("pageview",e||window.location.pathname)})}).catch(function(e){return console.error(e)})}},{key:"logEvent",value:function(e){var t=z(e,this.dimensions,this.metrics);E().then(function(e){e.forEach(function(e){e.send(t)})}).catch(function(e){return console.error(e)})}}]),e}(),J=function(e){return B.SHA256(e).toString(B.enc.Hex)};return function(){function e(t){if(D(this,e),this.trackers=[],t.amazon){var n=new F(t.amazon);this.trackers.push(n)}if(t.google){var r=new U(t.google);this.trackers.push(r)}this.trackers.length||console.error(new Error("No trackers configured"))}return K(e,[{key:"logPageView",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=T(t);return this.trackers.length||this.disabled?(this.trackers.forEach(function(t){return t.logPageView(e,n)}),!0):(this.disabled||console.error(new Error("Page view was not logged because no trackers are configured.")),!1)}},{key:"logEvent",value:function(e){var t=T(e);return this.trackers.length||this.disabled?(this.trackers.forEach(function(e){return e.logEvent(t)}),!0):(this.disabled||console.error(new Error("Event was not logged because no trackers are configured.")),!1)}}]),e}()}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define("telemetry",t):e.Telemetry=t()}(this,function(){"use strict";function e(e,t){var n=new XMLHttpRequest;n.addEventListener("load",function(){t(n.responseText)}),n.open(e.method,e.url),Object.keys(e.headers).forEach(function(t){n.setRequestHeader(t,e.headers[t])}),n.send(e.body)}function t(e,t){var r=window.localStorage.getItem(D);if(r&&(r=JSON.parse(r)),r&&Date.now()/1e3<r.Expiration)return t(r);n(e,function(e){window.localStorage.setItem(D,JSON.stringify(e)),t(e)})}function n(t,n){var i=j({},K);i.headers["X-Amz-Target"]="AWSCognitoIdentityService.GetId",i.body=JSON.stringify({IdentityPoolId:t}),e(i,function(e){r(JSON.parse(e),n)})}function r(t,n){var r=j({},K);r.headers["X-Amz-Target"]="AWSCognitoIdentityService.GetCredentialsForIdentity",r.body=JSON.stringify({IdentityId:t.IdentityId}),e(r,function(e){var t=JSON.parse(e);n(t.Credentials)})}function i(){return{session:o(),id:s()}}function o(){var e=void 0,t=void 0,n=window.localStorage.getItem(M);return n&&(n=JSON.parse(n),Date.now()<n.expiration&&(e=n)),e||(t=!0,e=a()),e.expiration=Date.now()+N,window.localStorage.setItem(M,JSON.stringify(e)),t&&(e.new=!0),e}function s(){var e=window.localStorage.getItem(R);return e||(e=c(),window.localStorage.setItem(R,e)),e}function a(){return{id:Math.floor(17592186044416*(1+Math.random())).toString(16),startTimestamp:(new Date).toISOString()}}function c(){return u()+u()+"-"+u()+"-"+u()+"-"+u()+"-"+u()+u()+u()}function u(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function f(e,t){var n={host:t.uri.host,"content-type":e.config.defaultContentType,accept:e.config.defaultAcceptType,"x-amz-date":g(t.signDate)};t.request.method=t.request.method.toUpperCase(),t.request.body?t.payload=t.request.body:t.request.data&&e.payloadSerializer?t.payload=e.payloadSerializer(t.request.data):delete n["content-type"],t.request.headers=w(n,Object.keys(t.request.headers||{}).reduce(function(e,n){return e[n.toLowerCase()]=t.request.headers[n],e},{})),t.sortedHeaderKeys=Object.keys(t.request.headers).sort(),t.request.headers["content-type"]&&(t.request.headers["content-type"]=t.request.headers["content-type"].split(";")[0]),"object"===C(t.request.params)&&w(t.uri.queryParams,t.request.params)}function h(e,t){t.signedHeaders=t.sortedHeaderKeys.map(function(e){return e.toLowerCase()}).join(";"),t.canonicalRequest=String(t.request.method).toUpperCase()+"\n"+encodeURI(t.uri.path)+"\n"+Object.keys(t.uri.queryParams).sort().map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(t.uri.queryParams[e])}).join("&")+"\n"+t.sortedHeaderKeys.map(function(e){return e.toLocaleLowerCase()+":"+t.request.headers[e]}).join("\n")+"\n\n"+t.signedHeaders+"\n"+e.hasher.hash(t.payload?t.payload:"")}function d(e,t){t.credentialScope=[g(t.signDate,!0),e.config.region,e.config.service,"aws4_request"].join("/"),t.stringToSign="AWS4-HMAC-SHA256\n"+g(t.signDate)+"\n"+t.credentialScope+"\n"+e.hasher.hash(t.canonicalRequest)}function l(e,t){var n=e.hasher.hmac,r=n(n(n(n("AWS4"+e.config.secretAccessKey,g(t.signDate,!0),{hexOutput:!1}),e.config.region,{hexOutput:!1,textInput:!1}),e.config.service,{hexOutput:!1,textInput:!1}),"aws4_request",{hexOutput:!1,textInput:!1});t.signature=n(r,t.stringToSign,{textInput:!1})}function p(e,t){t.authorization="AWS4-HMAC-SHA256 Credential="+e.config.accessKeyId+"/"+t.credentialScope+", SignedHeaders="+t.signedHeaders+", Signature="+t.signature}function g(e,t){var n=e.toISOString().replace(/[:\-]|\.\d{3}/g,"").substr(0,17);return t?n.substr(0,8):n}function y(){return function(e){return JSON.stringify(e)}}function v(){function e(e){return/^\??(.*)$/.exec(e)[1].split("&").reduce(function(e,t){return t=/^(.+)=(.*)$/.exec(t),t&&(e[t[1]]=t[2]),e},{})}var t=document?document.createElement("a"):{};return function(n){return t.href=n,{protocol:t.protocol,host:t.host.replace(/^(.*):((80)|(443))$/,"$1"),path:("/"!==t.pathname.charAt(0)?"/":"")+t.pathname,queryParams:e(t.search)}}}function m(){return{hash:function(e,t){t=w({hexOutput:!0,textInput:!0},t);var n=L.SHA256(e);return t.hexOutput?n.toString(L.enc.Hex):n},hmac:function(e,t,n){n=w({hexOutput:!0,textInput:!0},n);var r=L.HmacSHA256(t,e,{asBytes:!0});return n.hexOutput?r.toString(L.enc.Hex):r}}}function w(e){return[].slice.call(arguments,1).forEach(function(t){t&&"object"===(void 0===t?"undefined":C(t))&&Object.keys(t).forEach(function(n){var r=t[n];void 0!==r&&(null!==r&&"object"===(void 0===r?"undefined":C(r))?(e[n]=Array.isArray(r)?[]:{},w(e[n],r)):e[n]=r)})}),e}function S(e,t){if(void 0===e||!e)throw new Error(t)}function b(e){var t=i().session;return{eventType:"pageView",timestamp:(new Date).toISOString(),session:{id:t.id,startTimestamp:t.startTimestamp},attributes:{referrer:document.referrer,hostname:window.location.hostname,path:window.location.pathname||e},metrics:{}}}function _(e){var t=i().session;return{eventType:x(e),timestamp:(new Date).toISOString(),session:{id:t.id,startTimestamp:t.startTimestamp},attributes:j({referrer:document.referrer,hostname:window.location.hostname,path:window.location.pathname},A(e)),metrics:I(e)}}function x(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.workflow||e.process||e.category;return t||(e.error?"error":"other")}function A(e){var t=j({},e);return U.forEach(function(e){return delete t[e]}),t}function I(e){var t={};return U.forEach(function(n){t[n]=e[n]}),t}function O(e,t){var n={region:"us-east-1",service:"mobileanalytics",accessKeyId:e.AccessKeyId,secretAccessKey:e.SecretKey,sessionToken:e.SessionToken};return new F(n).sign(t)}function k(e,t){return JSON.stringify({client:{client_id:e,app_title:t.name,app_version_name:t.version||"unknown"},services:{mobile_analytics:{app_id:t.id}}})}function E(n,r,o){var s=i();n=Array.isArray(n)?n:[n];var a=z(n);t(r,function(t){a.headers=O(t,a),a.headers["x-amz-Client-Context"]=k(s.id,o),e(a,function(e){e&&console.error(JSON.parse(e))})})}function z(e){return{url:arguments.length>1&&void 0!==arguments[1]?arguments[1]:W,method:"POST",body:JSON.stringify({events:e})}}function H(){return new Promise(function(e,t){window.ga?window.ga(function(){e(window.ga.getAll())}):t(new Error("Google Analytics trackers not available"))})}function T(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={hitType:"event",eventCategory:e.category||"none",eventAction:e.action,eventLabel:e.label};return Object.keys(t).forEach(function(n){r["dimension"+t[n]]=e[n]}),Object.keys(n).forEach(function(t){r["metric"+n[t]]=e[t]}),r}function q(e){var t=j({},e);return t.user&&(t.user=G(t.user)),t}var C="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},B=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},P=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),j=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},D="TELEMETRY_COGNITO_CREDENTIALS",K={method:"POST",url:"https://cognito-identity.us-east-1.amazonaws.com/",headers:{"Content-type":"application/x-amz-json-1.1"}},N=18e5,M="TELEMETRY_SESSION",R="TELEMETRY_CLIENT_ID",L=function(e,t){var n={},r=n.lib={},i=function(){},o=r.Base={extend:function(e){i.prototype=this;var t=new i;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=r.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=void 0!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,n=e.words,r=this.sigBytes;if(e=e.sigBytes,this.clamp(),r%4)for(var i=0;i<e;i++)t[r+i>>>2]|=(n[i>>>2]>>>24-i%4*8&255)<<24-(r+i)%4*8;else if(n.length>65535)for(i=0;i<e;i+=4)t[r+i>>>2]=n[i>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],r=0;r<t;r+=4)n.push(4294967296*e.random()|0);return new s.init(n,t)}}),a=n.enc={},c=a.Hex={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r<e;r++){var i=t[r>>>2]>>>24-r%4*8&255;n.push((i>>>4).toString(16)),n.push((15&i).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r<t;r+=2)n[r>>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},u=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r<e;r++)n.push(String.fromCharCode(t[r>>>2]>>>24-r%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r<t;r++)n[r>>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},f=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},h=r.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=f.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,i=n.sigBytes,o=this.blockSize,a=i/(4*o),a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0);if(t=a*o,i=e.min(4*t,i),t){for(var c=0;c<t;c+=o)this._doProcessBlock(r,c);c=r.splice(0,t),n.sigBytes-=i}return new s.init(c,i)},clone:function(){var e=o.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});r.Hasher=h.extend({cfg:o.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){h.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,n){return new e.init(n).finalize(t)}},_createHmacHelper:function(e){return function(t,n){return new d.HMAC.init(e,n).finalize(t)}}});var d=n.algo={};return n}(Math);!function(e){for(var t=L,n=t.lib,r=n.WordArray,i=n.Hasher,n=t.algo,o=[],s=[],a=function(e){return 4294967296*(e-(0|e))|0},c=2,u=0;u<64;){var f;e:{f=c;for(var h=e.sqrt(f),d=2;d<=h;d++)if(!(f%d)){f=!1;break e}f=!0}f&&(u<8&&(o[u]=a(e.pow(c,.5))),s[u]=a(e.pow(c,1/3)),u++),c++}var l=[],n=n.SHA256=i.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,r=n[0],i=n[1],o=n[2],a=n[3],c=n[4],u=n[5],f=n[6],h=n[7],d=0;d<64;d++){if(d<16)l[d]=0|e[t+d];else{var p=l[d-15],g=l[d-2];l[d]=((p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3)+l[d-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+l[d-16]}p=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&f)+s[d]+l[d],g=((r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22))+(r&i^r&o^i&o),h=f,f=u,u=c,c=a+p|0,a=o,o=i,i=r,r=p+g|0}n[0]=n[0]+r|0,n[1]=n[1]+i|0,n[2]=n[2]+o|0,n[3]=n[3]+a|0,n[4]=n[4]+c|0,n[5]=n[5]+u|0,n[6]=n[6]+f|0,n[7]=n[7]+h|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;return n[i>>>5]|=128<<24-i%32,n[14+(i+64>>>9<<4)]=e.floor(r/4294967296),n[15+(i+64>>>9<<4)]=r,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=i._createHelper(n),t.HmacSHA256=i._createHmacHelper(n)}(Math),function(){var e=L,t=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,n){e=this._hasher=new e.init,"string"==typeof n&&(n=t.parse(n));var r=e.blockSize,i=4*r;n.sigBytes>i&&(n=e.finalize(n)),n.clamp();for(var o=this._oKey=n.clone(),s=this._iKey=n.clone(),a=o.words,c=s.words,u=0;u<r;u++)a[u]^=1549556828,c[u]^=909522486;o.sigBytes=s.sigBytes=i,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var t=this._hasher;return e=t.finalize(e),t.reset(),t.finalize(this._oKey.clone().concat(e))}})}();var J={region:"eu-west-1",service:"execute-api",defaultContentType:"application/json",defaultAcceptType:"application/json",payloadSerializerFactory:y,uriParserFactory:v,hasherFactory:m},F=function(){function e(t){B(this,e),this.config=w({},J,t),this.payloadSerializer=this.config.payloadSerializer||this.config.payloadSerializerFactory(),this.uriParser=this.config.uriParserFactory(),this.hasher=this.config.hasherFactory(),S(this.config.accessKeyId,"AwsSigner requires AWS AccessKeyID"),S(this.config.secretAccessKey,"AwsSigner requires AWS SecretAccessKey")}return P(e,[{key:"sign",value:function(e,t){var n={request:w({},e),signDate:t||new Date,uri:this.uriParser(e.url)};return f(this,n),h(this,n),d(this,n),l(this,n),p(this,n),{Accept:n.request.headers.accept,Authorization:n.authorization,"Content-Type":n.request.headers["content-type"],"x-amz-date":n.request.headers["x-amz-date"],"x-amz-security-token":this.config.sessionToken||void 0}}}]),e}(),U=["size","duration"],W="https://mobileanalytics.us-east-1.amazonaws.com/2014-06-05/events",$=function(){function e(t){B(this,e),j(this,t),i().session.new&&this.logEvent({category:"_session.start"})}return P(e,[{key:"logPageView",value:function(e){E(b(e),this.userPoolID,this.app)}},{key:"logEvent",value:function(e){E(_(e),this.userPoolID,this.app)}}]),e}(),V=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),j(this,t)}return P(e,[{key:"logPageView",value:function(e){H().then(function(t){t.forEach(function(t){t.send("pageview",e||window.location.pathname)})}).catch(function(e){return console.error(e)})}},{key:"logEvent",value:function(e){var t=T(e,this.dimensions,this.metrics);H().then(function(e){e.forEach(function(e){e.send(t)})}).catch(function(e){return console.error(e)})}}]),e}(),G=function(e){return L.SHA256(e).toString(L.enc.Hex)};return function(){function e(t){if(B(this,e),this.trackers=[],t.amazon){var n=new $(t.amazon);this.trackers.push(n)}if(t.google){var r=new V(t.google);this.trackers.push(r)}this.trackers.length||console.error(new Error("No trackers configured"))}return P(e,[{key:"logPageView",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=q(t);return this.trackers.length||this.disabled?(this.trackers.forEach(function(t){return t.logPageView(e,n)}),!0):(this.disabled||console.error(new Error("Page view was not logged because no trackers are configured.")),!1)}},{key:"logEvent",value:function(e){var t=q(e);return this.trackers.length||this.disabled?(this.trackers.forEach(function(e){return e.logEvent(t)}),!0):(this.disabled||console.error(new Error("Event was not logged because no trackers are configured.")),!1)}}]),e}()}); | ||
//# sourceMappingURL=telemetry.min.js.map |
{ | ||
"name": "@esri/telemetry", | ||
"version": "1.0.0", | ||
"version": "1.0.1", | ||
"description": "A JavaScript Implementation of the ArcGIS Telemetry Specification", | ||
@@ -8,3 +8,3 @@ "main": "dist/telemetry.js", | ||
"build": "node build.js", | ||
"test": "echo \"Error: no test specified\" && exit 1" | ||
"test": "standard src" | ||
}, | ||
@@ -51,4 +51,4 @@ "repository": { | ||
"window", | ||
"fetch", | ||
"document" | ||
"document", | ||
"XMLHttpRequest" | ||
], | ||
@@ -55,0 +55,0 @@ "ignore": [ |
# Telemetry.js | ||
[![npm version][npm-img]][npm-url] | ||
[![build status][travis-img]][travis-url] | ||
[![js-standard-style][standard-img]][standard-url] | ||
This is a vanilla JavaScript implementation of the new ArcGIS telemetry specification. It currently supports Amazon Mobile Analytics and Google Analytics | ||
@@ -37,3 +41,8 @@ | ||
## How to use | ||
### Include in your app | ||
### Via npm | ||
`npm install -S @esri/telemetry` | ||
### In the browser | ||
```js | ||
@@ -123,1 +132,8 @@ <script src="dist/Telemetry.js"></script> | ||
- Use fewer HTTP calls and improve performance by sending near-simultaneous events in groups | ||
[npm-img]: https://badge.fury.io/js/%40esri%2Ftelemetry.svg | ||
[npm-url]: https://www.npmjs.com/package/@esri/telemetry | ||
[travis-img]: https://travis-ci.com/ArcGIS/telemetry.js.svg?token=qsWyrTUYpGircPax8dot&branch=master | ||
[travis-url]: https://travis-ci.com/ArcGIS/telemetry.js | ||
[standard-img]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg | ||
[standard-url]: http://standardjs.com/ |
@@ -0,38 +1,43 @@ | ||
import request from '../request' | ||
const COGNITO_KEY = 'TELEMETRY_COGNITO_CREDENTIALS' | ||
const COGNITO_URL = 'https://cognito-identity.us-east-1.amazonaws.com/' | ||
export function getCredentials (IdentityPoolId) { | ||
export function getCredentials (IdentityPoolId, callback) { | ||
let cached = window.localStorage.getItem(COGNITO_KEY) | ||
if (cached) cached = JSON.parse(cached) | ||
if (cached && (Date.now() / 1000 < cached.Expiration)) return Promise.resolve(cached) | ||
if (cached && (Date.now() / 1000 < cached.Expiration)) return callback(cached) | ||
return authWithCognito(IdentityPoolId) | ||
.then(credentials => { | ||
authWithCognito(IdentityPoolId, credentials => { | ||
window.localStorage.setItem(COGNITO_KEY, JSON.stringify(credentials)) | ||
return credentials | ||
callback(credentials) | ||
}) | ||
} | ||
function authWithCognito (IdentityPoolId) { | ||
return fetch('https://cognito-identity.us-east-1.amazonaws.com/', { | ||
method: 'POST', | ||
headers: { | ||
'Content-type': 'application/x-amz-json-1.1', | ||
'X-Amz-Target': 'AWSCognitoIdentityService.GetId' | ||
}, | ||
body: JSON.stringify({ IdentityPoolId }) | ||
function authWithCognito (IdentityPoolId, callback) { | ||
const options = Object.assign({}, defaults) | ||
options.headers['X-Amz-Target'] = 'AWSCognitoIdentityService.GetId' | ||
options.body = JSON.stringify({ IdentityPoolId }) | ||
request(options, response => { | ||
requestCredentials(JSON.parse(response), callback) | ||
}) | ||
.then(r => { return r.json() }) | ||
.then(json => { | ||
return fetch('https://cognito-identity.us-east-1.amazonaws.com/', { | ||
method: 'POST', | ||
headers: { | ||
'Content-type': 'application/x-amz-json-1.1', | ||
'X-Amz-Target': 'AWSCognitoIdentityService.GetCredentialsForIdentity' | ||
}, | ||
body: JSON.stringify({IdentityId: json.IdentityId}) | ||
}) | ||
} | ||
function requestCredentials (json, callback) { | ||
const options = Object.assign({}, defaults) | ||
options.headers['X-Amz-Target'] = 'AWSCognitoIdentityService.GetCredentialsForIdentity' | ||
options.body = JSON.stringify({IdentityId: json.IdentityId}) | ||
request(options, response => { | ||
const json = JSON.parse(response) | ||
callback(json.Credentials) | ||
}) | ||
.then(r => { return r.json() }) | ||
.then(json => { return json.Credentials }) | ||
.catch(e => { throw new Error('Authentication with cognito failed, check your user pool settings') }) | ||
} | ||
const defaults = { | ||
method: 'POST', | ||
url: COGNITO_URL, | ||
headers: { | ||
'Content-type': 'application/x-amz-json-1.1' | ||
} | ||
} |
import { getCredentials } from './auth' | ||
import { getUser } from './user' | ||
import AwsSigner from './signer' | ||
import request from '../request' | ||
const METRICS = ['size', 'duration'] | ||
const DEFAULT_ENDPOINT = 'https://mobileanalytics.us-east-1.amazonaws.com/2014-06-05/events' | ||
@@ -116,13 +119,14 @@ export default class Amazon { | ||
const options = createTelemetryOptions(events) | ||
return getCredentials(userPoolID) | ||
.then(credentials => { | ||
getCredentials(userPoolID, credentials => { | ||
options.headers = createHeaders(credentials, options) | ||
options.headers['x-amz-Client-Context'] = createClientContext(user.id, app) | ||
fetch(options.url, options) | ||
.then(r => console.log(r)) | ||
.catch(e => console.error(e)) | ||
request(options, response => { | ||
if (response) { | ||
console.error(JSON.parse(response)) | ||
} | ||
}) | ||
}) | ||
} | ||
function createTelemetryOptions (events, url = 'https://mobileanalytics.us-east-1.amazonaws.com/2014-06-05/events') { | ||
function createTelemetryOptions (events, url = DEFAULT_ENDPOINT) { | ||
return { | ||
@@ -129,0 +133,0 @@ url, |
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
Sorry, the diff of this file is not supported yet
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
No tests
QualityPackage does not have any tests. This is a strong signal of a poorly maintained or low quality package.
Found 1 instance in 1 package
448313
31
2660
1
138
0