Comparing version 0.1.1 to 0.1.2
@@ -94,3 +94,3 @@ (function webpackUniversalModuleDefinition(root, factory) { | ||
/******/ // Load entry module and return exports | ||
/******/ return __webpack_require__(__webpack_require__.s = 5); | ||
/******/ return __webpack_require__(__webpack_require__.s = 4); | ||
/******/ }) | ||
@@ -102,14 +102,2 @@ /************************************************************************/ | ||
function _interopRequireDefault(obj) { | ||
return obj && obj.__esModule ? obj : { | ||
"default": obj | ||
}; | ||
} | ||
module.exports = _interopRequireDefault; | ||
/***/ }), | ||
/* 1 */ | ||
/***/ (function(module, exports) { | ||
function _classCallCheck(instance, Constructor) { | ||
@@ -124,3 +112,3 @@ if (!(instance instanceof Constructor)) { | ||
/***/ }), | ||
/* 2 */ | ||
/* 1 */ | ||
/***/ (function(module, exports) { | ||
@@ -147,48 +135,5 @@ | ||
/***/ }), | ||
/* 3 */ | ||
/* 2 */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
"use strict"; | ||
var debugMode = false; | ||
var outputElement; | ||
function activate(id) { | ||
debugMode = true; | ||
if (id) { | ||
outputElement = window.document.getElementById(id); | ||
if (!outputElement) { | ||
console.log("Fail to find the output element."); | ||
} | ||
} | ||
} | ||
function write(info) { | ||
if (debugMode) { | ||
if (outputElement) { | ||
var p = document.createElement("p"); | ||
p.style.display = "block"; | ||
p.style.fontSize = "10px"; | ||
p.style.margin = "2px"; | ||
var t = document.createTextNode(info); | ||
p.appendChild(t); | ||
outputElement.appendChild(p); | ||
} | ||
console.log(info); | ||
} | ||
} | ||
module.exports = { | ||
activate: activate, | ||
write: write | ||
}; | ||
/***/ }), | ||
/* 4 */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (name, context, definition) { | ||
@@ -279,379 +224,585 @@ if ( true && module.exports) module.exports = definition(); | ||
/***/ }), | ||
/* 3 */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
var rng = __webpack_require__(7); | ||
var bytesToUuid = __webpack_require__(8); | ||
function v4(options, buf, offset) { | ||
var i = buf && offset || 0; | ||
if (typeof(options) == 'string') { | ||
buf = options === 'binary' ? new Array(16) : null; | ||
options = null; | ||
} | ||
options = options || {}; | ||
var rnds = options.random || (options.rng || rng)(); | ||
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved` | ||
rnds[6] = (rnds[6] & 0x0f) | 0x40; | ||
rnds[8] = (rnds[8] & 0x3f) | 0x80; | ||
// Copy bytes to buffer, if provided | ||
if (buf) { | ||
for (var ii = 0; ii < 16; ++ii) { | ||
buf[i + ii] = rnds[ii]; | ||
} | ||
} | ||
return buf || bytesToUuid(rnds); | ||
} | ||
module.exports = v4; | ||
/***/ }), | ||
/* 4 */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
__webpack_require__(5); | ||
module.exports = __webpack_require__(9); | ||
/***/ }), | ||
/* 5 */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
"use strict"; | ||
// the whatwg-fetch polyfill installs the fetch() function | ||
// on the global object (window or self) | ||
// | ||
// Return that as the export for use in Webpack, Browserify etc. | ||
__webpack_require__(6); | ||
module.exports = self.fetch.bind(self); | ||
var _interopRequireDefault = __webpack_require__(0); | ||
/***/ }), | ||
/* 6 */ | ||
/***/ (function(module, __webpack_exports__, __webpack_require__) { | ||
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | ||
"use strict"; | ||
__webpack_require__.r(__webpack_exports__); | ||
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Headers", function() { return Headers; }); | ||
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Request", function() { return Request; }); | ||
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Response", function() { return Response; }); | ||
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DOMException", function() { return DOMException; }); | ||
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fetch", function() { return fetch; }); | ||
var support = { | ||
searchParams: 'URLSearchParams' in self, | ||
iterable: 'Symbol' in self && 'iterator' in Symbol, | ||
blob: | ||
'FileReader' in self && | ||
'Blob' in self && | ||
(function() { | ||
try { | ||
new Blob() | ||
return true | ||
} catch (e) { | ||
return false | ||
} | ||
})(), | ||
formData: 'FormData' in self, | ||
arrayBuffer: 'ArrayBuffer' in self | ||
} | ||
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | ||
function isDataView(obj) { | ||
return obj && DataView.prototype.isPrototypeOf(obj) | ||
} | ||
var uuidv4 = __webpack_require__(6); | ||
if (support.arrayBuffer) { | ||
var viewClasses = [ | ||
'[object Int8Array]', | ||
'[object Uint8Array]', | ||
'[object Uint8ClampedArray]', | ||
'[object Int16Array]', | ||
'[object Uint16Array]', | ||
'[object Int32Array]', | ||
'[object Uint32Array]', | ||
'[object Float32Array]', | ||
'[object Float64Array]' | ||
] | ||
var Uploader = __webpack_require__(9); | ||
var isArrayBufferView = | ||
ArrayBuffer.isView || | ||
function(obj) { | ||
return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 | ||
} | ||
} | ||
var _require = __webpack_require__(10), | ||
Config = _require.Config; | ||
function normalizeName(name) { | ||
if (typeof name !== 'string') { | ||
name = String(name) | ||
} | ||
if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) { | ||
throw new TypeError('Invalid character in header field name') | ||
} | ||
return name.toLowerCase() | ||
} | ||
var _debug = __webpack_require__(3); | ||
function normalizeValue(value) { | ||
if (typeof value !== 'string') { | ||
value = String(value) | ||
} | ||
return value | ||
} | ||
var targetEvents = ["mousemove", "mousedown", "mouseup", "mouseclick", "dblclick", "contextmenu", "wheel", "torchstart", "touchmove", "touchend"]; | ||
var pageLoadTime = new Date(); | ||
var hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : 'mozHidden' in document ? 'mozHidden' : null; | ||
var visibilityChangeEvent = hiddenProperty ? hiddenProperty.replace(/hidden/i, 'visibilitychange') : null; | ||
// Build a destructive iterator for the value list | ||
function iteratorFor(items) { | ||
var iterator = { | ||
next: function() { | ||
var value = items.shift() | ||
return {done: value === undefined, value: value} | ||
} | ||
} | ||
function maxNumber() { | ||
for (var _len = arguments.length, nums = new Array(_len), _key = 0; _key < _len; _key++) { | ||
nums[_key] = arguments[_key]; | ||
if (support.iterable) { | ||
iterator[Symbol.iterator] = function() { | ||
return iterator | ||
} | ||
} | ||
var res = nums[0]; | ||
return iterator | ||
} | ||
for (var i = 1; i < nums.length; ++i) { | ||
res = res > nums[i] ? res : nums[i]; | ||
function Headers(headers) { | ||
this.map = {} | ||
if (headers instanceof Headers) { | ||
headers.forEach(function(value, name) { | ||
this.append(name, value) | ||
}, this) | ||
} else if (Array.isArray(headers)) { | ||
headers.forEach(function(header) { | ||
this.append(header[0], header[1]) | ||
}, this) | ||
} else if (headers) { | ||
Object.getOwnPropertyNames(headers).forEach(function(name) { | ||
this.append(name, headers[name]) | ||
}, this) | ||
} | ||
} | ||
return res; | ||
Headers.prototype.append = function(name, value) { | ||
name = normalizeName(name) | ||
value = normalizeValue(value) | ||
var oldValue = this.map[name] | ||
this.map[name] = oldValue ? oldValue + ', ' + value : value | ||
} | ||
function getRelativeTimestampInSeconds() { | ||
var diff = new Date() - pageLoadTime; | ||
return Math.trunc(diff) / 1000; | ||
Headers.prototype['delete'] = function(name) { | ||
delete this.map[normalizeName(name)] | ||
} | ||
function getButton(btn) { | ||
if (btn === '2') { | ||
return 'Right'; | ||
} else { | ||
return ""; | ||
Headers.prototype.get = function(name) { | ||
name = normalizeName(name) | ||
return this.has(name) ? this.map[name] : null | ||
} | ||
Headers.prototype.has = function(name) { | ||
return this.map.hasOwnProperty(normalizeName(name)) | ||
} | ||
Headers.prototype.set = function(name, value) { | ||
this.map[normalizeName(name)] = normalizeValue(value) | ||
} | ||
Headers.prototype.forEach = function(callback, thisArg) { | ||
for (var name in this.map) { | ||
if (this.map.hasOwnProperty(name)) { | ||
callback.call(thisArg, this.map[name], name, this) | ||
} | ||
} | ||
} | ||
var Mouselog = | ||
/*#__PURE__*/ | ||
function () { | ||
function Mouselog() { | ||
(0, _classCallCheck2["default"])(this, Mouselog); | ||
this.config = new Config(); | ||
this.impressionId = uuidv4(); | ||
this.mouselogLoadTime = new Date(); | ||
this.uploader = new Uploader(); | ||
this.eventsList = []; | ||
this.eventsCount = 0; | ||
this.uploadInterval; // For "periodic" upload mode | ||
Headers.prototype.keys = function() { | ||
var items = [] | ||
this.forEach(function(value, name) { | ||
items.push(name) | ||
}) | ||
return iteratorFor(items) | ||
} | ||
this.uploadTimeout; // For "mixed" upload mode | ||
Headers.prototype.values = function() { | ||
var items = [] | ||
this.forEach(function(value) { | ||
items.push(value) | ||
}) | ||
return iteratorFor(items) | ||
} | ||
Headers.prototype.entries = function() { | ||
var items = [] | ||
this.forEach(function(value, name) { | ||
items.push([name, value]) | ||
}) | ||
return iteratorFor(items) | ||
} | ||
if (support.iterable) { | ||
Headers.prototype[Symbol.iterator] = Headers.prototype.entries | ||
} | ||
function consumed(body) { | ||
if (body.bodyUsed) { | ||
return Promise.reject(new TypeError('Already read')) | ||
} | ||
body.bodyUsed = true | ||
} | ||
(0, _createClass2["default"])(Mouselog, [{ | ||
key: "_clearBuffer", | ||
value: function _clearBuffer() { | ||
this.eventsList = []; | ||
function fileReaderReady(reader) { | ||
return new Promise(function(resolve, reject) { | ||
reader.onload = function() { | ||
resolve(reader.result) | ||
} | ||
}, { | ||
key: "_newTrace", | ||
value: function _newTrace() { | ||
var trace = { | ||
id: '0', | ||
idx: this.uploadIdx, | ||
url: window.location.hostname ? window.location.hostname : "localhost", | ||
path: window.location.pathname, | ||
width: maxNumber(document.body.scrollWidth, window.innerWidth), | ||
height: maxNumber(document.body.scrollHeight, window.innerHeight), | ||
pageLoadTime: pageLoadTime, | ||
events: [] | ||
}; | ||
this.uploadIdx += 1; | ||
return trace; | ||
reader.onerror = function() { | ||
reject(reader.error) | ||
} | ||
}, { | ||
key: "_onVisibilityChange", | ||
value: function _onVisibilityChange(evt) { | ||
if (window.document[hiddenProperty]) { | ||
// the page is not activated | ||
this._pause(); | ||
} else { | ||
// the page is activated | ||
this._resume(); | ||
} | ||
} | ||
}, { | ||
key: "_mouseHandler", | ||
value: function _mouseHandler(evt) { | ||
// PC's Chrome on Mobile mode can still receive "contextmenu" event with zero X, Y, so we ignore these events. | ||
if (evt.type === 'contextmenu' && evt.pageX === 0 && evt.pageY === 0) { | ||
return; | ||
} | ||
}) | ||
} | ||
var x = evt.pageX; | ||
var y = evt.pageY; | ||
function readBlobAsArrayBuffer(blob) { | ||
var reader = new FileReader() | ||
var promise = fileReaderReady(reader) | ||
reader.readAsArrayBuffer(blob) | ||
return promise | ||
} | ||
if (x === undefined) { | ||
x = evt.changedTouches[0].pageX; | ||
y = evt.changedTouches[0].pageY; | ||
} | ||
function readBlobAsText(blob) { | ||
var reader = new FileReader() | ||
var promise = fileReaderReady(reader) | ||
reader.readAsText(blob) | ||
return promise | ||
} | ||
var tmpEvt = { | ||
id: this.eventsCount, | ||
timestamp: getRelativeTimestampInSeconds(), | ||
type: evt.type, | ||
x: x, | ||
y: y, | ||
button: getButton(evt.button) | ||
}; | ||
function readArrayBufferAsText(buf) { | ||
var view = new Uint8Array(buf) | ||
var chars = new Array(view.length) | ||
if (evt.type == "wheel") { | ||
tmpEvt.deltaX = evt.deltaX; | ||
tmpEvt.deltaY = evt.deltaY; | ||
} | ||
for (var i = 0; i < view.length; i++) { | ||
chars[i] = String.fromCharCode(view[i]) | ||
} | ||
return chars.join('') | ||
} | ||
this.eventsList.push(tmpEvt); | ||
this.eventsCount += 1; | ||
function bufferClone(buf) { | ||
if (buf.slice) { | ||
return buf.slice(0) | ||
} else { | ||
var view = new Uint8Array(buf.byteLength) | ||
view.set(new Uint8Array(buf)) | ||
return view.buffer | ||
} | ||
} | ||
if (this.config.uploadMode == "event-triggered" && this.eventsList.length % this.config.frequency == 0) { | ||
this._uploadTrace(); | ||
function Body() { | ||
this.bodyUsed = false | ||
this._initBody = function(body) { | ||
this._bodyInit = body | ||
if (!body) { | ||
this._bodyText = '' | ||
} else if (typeof body === 'string') { | ||
this._bodyText = body | ||
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) { | ||
this._bodyBlob = body | ||
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) { | ||
this._bodyFormData = body | ||
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { | ||
this._bodyText = body.toString() | ||
} else if (support.arrayBuffer && support.blob && isDataView(body)) { | ||
this._bodyArrayBuffer = bufferClone(body.buffer) | ||
// IE 10-11 can't handle a DataView body. | ||
this._bodyInit = new Blob([this._bodyArrayBuffer]) | ||
} else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { | ||
this._bodyArrayBuffer = bufferClone(body) | ||
} else { | ||
this._bodyText = body = Object.prototype.toString.call(body) | ||
} | ||
if (!this.headers.get('content-type')) { | ||
if (typeof body === 'string') { | ||
this.headers.set('content-type', 'text/plain;charset=UTF-8') | ||
} else if (this._bodyBlob && this._bodyBlob.type) { | ||
this.headers.set('content-type', this._bodyBlob.type) | ||
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { | ||
this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8') | ||
} | ||
} | ||
} | ||
if (this.config.uploadMode == "mixed" && this.eventsList.length % this.config.frequency == 0) { | ||
this._periodUploadTimeout(); | ||
if (support.blob) { | ||
this.blob = function() { | ||
var rejected = consumed(this) | ||
if (rejected) { | ||
return rejected | ||
} | ||
this._uploadTrace(); | ||
if (this._bodyBlob) { | ||
return Promise.resolve(this._bodyBlob) | ||
} else if (this._bodyArrayBuffer) { | ||
return Promise.resolve(new Blob([this._bodyArrayBuffer])) | ||
} else if (this._bodyFormData) { | ||
throw new Error('could not read FormData body as blob') | ||
} else { | ||
return Promise.resolve(new Blob([this._bodyText])) | ||
} | ||
} | ||
}, { | ||
key: "_fetchConfigFromServer", | ||
value: function _fetchConfigFromServer() { | ||
// Upload an empty trace to fetch config from server | ||
var trace = this._newTrace(); | ||
return this.uploader.upload(trace); // This is a promise | ||
this.arrayBuffer = function() { | ||
if (this._bodyArrayBuffer) { | ||
return consumed(this) || Promise.resolve(this._bodyArrayBuffer) | ||
} else { | ||
return this.blob().then(readBlobAsArrayBuffer) | ||
} | ||
} | ||
}, { | ||
key: "_uploadTrace", | ||
value: function _uploadTrace() { | ||
var trace = this._newTrace(); | ||
} | ||
trace.events = this.eventsList; | ||
this.eventsList = []; | ||
return this.uploader.upload(trace); // This is a promise | ||
this.text = function() { | ||
var rejected = consumed(this) | ||
if (rejected) { | ||
return rejected | ||
} | ||
}, { | ||
key: "_periodUploadTimeout", | ||
value: function _periodUploadTimeout() { | ||
var _this = this; | ||
clearTimeout(this.uploadTimeout); | ||
this.uploadTimeout = setTimeout(function () { | ||
if (_this.eventsList.length > 0) { | ||
_this._uploadTrace(); | ||
} | ||
}, this.config.uploadPeriod); | ||
if (this._bodyBlob) { | ||
return readBlobAsText(this._bodyBlob) | ||
} else if (this._bodyArrayBuffer) { | ||
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) | ||
} else if (this._bodyFormData) { | ||
throw new Error('could not read FormData body as text') | ||
} else { | ||
return Promise.resolve(this._bodyText) | ||
} | ||
}, { | ||
key: "_periodUploadInterval", | ||
value: function _periodUploadInterval() { | ||
var _this2 = this; | ||
} | ||
clearInterval(this.uploadInterval); | ||
this.uploadInterval = setInterval(function () { | ||
if (_this2.eventsList.length > 0) { | ||
_this2._uploadTrace(); | ||
} | ||
}, this.config.uploadPeriod); | ||
if (support.formData) { | ||
this.formData = function() { | ||
return this.text().then(decode) | ||
} | ||
}, { | ||
key: "_runCollector", | ||
value: function _runCollector() { | ||
var _this3 = this; | ||
} | ||
targetEvents.forEach(function (s) { | ||
_this3.config.scope.addEventListener(s, function (evt) { | ||
return _this3._mouseHandler(evt); | ||
}); | ||
}); | ||
this.json = function() { | ||
return this.text().then(JSON.parse) | ||
} | ||
if (this.config.uploadMode === "periodic") { | ||
this._periodUploadInterval(); | ||
} | ||
return this | ||
} | ||
if (this.config.uploadMode === "mixed") { | ||
this._periodUploadTimeout(); | ||
} | ||
} | ||
}, { | ||
key: "_stopCollector", | ||
value: function _stopCollector() { | ||
var _this4 = this; | ||
// HTTP methods whose capitalization should be normalized | ||
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] | ||
targetEvents.forEach(function (s) { | ||
_this4.config.scope.removeEventListener(s, function (evt) { | ||
return _this4._mouseHandler(evt); | ||
}); | ||
}); | ||
clearInterval(this.uploadInterval); | ||
clearTimeout(this.uploadTimeout); | ||
} | ||
}, { | ||
key: "_resetCollector", | ||
value: function _resetCollector() { | ||
this._stopCollector(); | ||
function normalizeMethod(method) { | ||
var upcased = method.toUpperCase() | ||
return methods.indexOf(upcased) > -1 ? upcased : method | ||
} | ||
this._runCollector(); | ||
function Request(input, options) { | ||
options = options || {} | ||
var body = options.body | ||
if (input instanceof Request) { | ||
if (input.bodyUsed) { | ||
throw new TypeError('Already read') | ||
} | ||
}, { | ||
key: "_init", | ||
value: function _init(config) { | ||
var _this5 = this; | ||
this.url = input.url | ||
this.credentials = input.credentials | ||
if (!options.headers) { | ||
this.headers = new Headers(input.headers) | ||
} | ||
this.method = input.method | ||
this.mode = input.mode | ||
this.signal = input.signal | ||
if (!body && input._bodyInit != null) { | ||
body = input._bodyInit | ||
input.bodyUsed = true | ||
} | ||
} else { | ||
this.url = String(input) | ||
} | ||
this.impressionId = uuidv4(); | ||
this.credentials = options.credentials || this.credentials || 'same-origin' | ||
if (options.headers || !this.headers) { | ||
this.headers = new Headers(options.headers) | ||
} | ||
this.method = normalizeMethod(options.method || this.method || 'GET') | ||
this.mode = options.mode || this.mode || null | ||
this.signal = options.signal || this.signal | ||
this.referrer = null | ||
this._clearBuffer(); | ||
if ((this.method === 'GET' || this.method === 'HEAD') && body) { | ||
throw new TypeError('Body not allowed for GET or HEAD requests') | ||
} | ||
this._initBody(body) | ||
} | ||
this.uploadIdx = 0; | ||
this.uploader = new Uploader(this.impressionId, this.config); | ||
this.uploader.setImpressionId(this.impressionId); | ||
Request.prototype.clone = function() { | ||
return new Request(this, {body: this._bodyInit}) | ||
} | ||
if (this.config.build(config)) { | ||
// Async: Upload an empty data to fetch config from server | ||
this._fetchConfigFromServer().then(function (result) { | ||
if (result.status == 1) { | ||
if (_this5.config.update(result.config)) { | ||
_this5._resetCollector(); | ||
function decode(body) { | ||
var form = new FormData() | ||
body | ||
.trim() | ||
.split('&') | ||
.forEach(function(bytes) { | ||
if (bytes) { | ||
var split = bytes.split('=') | ||
var name = split.shift().replace(/\+/g, ' ') | ||
var value = split.join('=').replace(/\+/g, ' ') | ||
form.append(decodeURIComponent(name), decodeURIComponent(value)) | ||
} | ||
}) | ||
return form | ||
} | ||
_this5.uploader.setConfig(_this5.config); | ||
function parseHeaders(rawHeaders) { | ||
var headers = new Headers() | ||
// Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space | ||
// https://tools.ietf.org/html/rfc7230#section-3.2 | ||
var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ') | ||
preProcessedHeaders.split(/\r?\n/).forEach(function(line) { | ||
var parts = line.split(':') | ||
var key = parts.shift().trim() | ||
if (key) { | ||
var value = parts.join(':').trim() | ||
headers.append(key, value) | ||
} | ||
}) | ||
return headers | ||
} | ||
_debug.write("Successfully update config from backend."); | ||
} else { | ||
throw new Error("Unable to update config with server config."); | ||
} | ||
} else { | ||
throw new Error("Fail to get config from server."); | ||
} | ||
})["catch"](function (err) { | ||
_debug.write(err); | ||
}); | ||
Body.call(Request.prototype) | ||
window.onbeforeunload = function (evt) { | ||
if (_this5.eventsList.length != 0) { | ||
_this5._uploadTrace(); | ||
} | ||
}; | ||
function Response(bodyInit, options) { | ||
if (!options) { | ||
options = {} | ||
} | ||
return { | ||
status: 0 | ||
}; | ||
} else { | ||
return { | ||
status: -1, | ||
msg: "Invalid configuration." | ||
}; | ||
} | ||
} | ||
}, { | ||
key: "_pause", | ||
value: function _pause() { | ||
this._stopCollector(); | ||
} | ||
}, { | ||
key: "_resume", | ||
value: function _resume() { | ||
this._runCollector(); | ||
} | ||
}, { | ||
key: "run", | ||
value: function run(config) { | ||
var _this6 = this; | ||
this.type = 'default' | ||
this.status = options.status === undefined ? 200 : options.status | ||
this.ok = this.status >= 200 && this.status < 300 | ||
this.statusText = 'statusText' in options ? options.statusText : 'OK' | ||
this.headers = new Headers(options.headers) | ||
this.url = options.url || '' | ||
this._initBody(bodyInit) | ||
} | ||
var res = this._init(config); | ||
Body.call(Response.prototype) | ||
if (res.status == 0) { | ||
if (visibilityChangeEvent) { | ||
document.addEventListener(visibilityChangeEvent, function (evt) { | ||
return _this6._onVisibilityChange(evt); | ||
}); | ||
} | ||
Response.prototype.clone = function() { | ||
return new Response(this._bodyInit, { | ||
status: this.status, | ||
statusText: this.statusText, | ||
headers: new Headers(this.headers), | ||
url: this.url | ||
}) | ||
} | ||
this._runCollector(); | ||
Response.error = function() { | ||
var response = new Response(null, {status: 0, statusText: ''}) | ||
response.type = 'error' | ||
return response | ||
} | ||
this.uploader.start(this.impressionId); | ||
var redirectStatuses = [301, 302, 303, 307, 308] | ||
_debug.write("Mouselog agent is activated!"); | ||
Response.redirect = function(url, status) { | ||
if (redirectStatuses.indexOf(status) === -1) { | ||
throw new RangeError('Invalid status code') | ||
} | ||
_debug.write("Website ID: ".concat(this.config.websiteId)); | ||
return new Response(null, {status: status, headers: {location: url}}) | ||
} | ||
_debug.write("Impression ID: ".concat(this.impressionId)); | ||
var DOMException = self.DOMException | ||
try { | ||
new DOMException() | ||
} catch (err) { | ||
DOMException = function(message, name) { | ||
this.message = message | ||
this.name = name | ||
var error = Error(message) | ||
this.stack = error.stack | ||
} | ||
DOMException.prototype = Object.create(Error.prototype) | ||
DOMException.prototype.constructor = DOMException | ||
} | ||
_debug.write("User-Agent: ".concat(navigator.userAgent)); | ||
function fetch(input, init) { | ||
return new Promise(function(resolve, reject) { | ||
var request = new Request(input, init) | ||
_debug.write("Page load time: ".concat(pageLoadTime)); | ||
} else { | ||
_debug.write(res.msg); | ||
if (request.signal && request.signal.aborted) { | ||
return reject(new DOMException('Aborted', 'AbortError')) | ||
} | ||
_debug.write("Fail to initialize Mouselog agent."); | ||
var xhr = new XMLHttpRequest() | ||
function abortXhr() { | ||
xhr.abort() | ||
} | ||
xhr.onload = function() { | ||
var options = { | ||
status: xhr.status, | ||
statusText: xhr.statusText, | ||
headers: parseHeaders(xhr.getAllResponseHeaders() || '') | ||
} | ||
options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL') | ||
var body = 'response' in xhr ? xhr.response : xhr.responseText | ||
resolve(new Response(body, options)) | ||
} | ||
}, { | ||
key: "debug", | ||
value: function debug(config, debugOutputElementId) { | ||
_debug.activate(debugOutputElementId); | ||
this.run(config); | ||
xhr.onerror = function() { | ||
reject(new TypeError('Network request failed')) | ||
} | ||
}, { | ||
key: "stop", | ||
value: function stop() { | ||
this.uploader.stop(); | ||
this._stopCollector(); | ||
xhr.ontimeout = function() { | ||
reject(new TypeError('Network request failed')) | ||
} | ||
this._clearBuffer(); | ||
_debug.write("Mouselog agent ".concat(this.impressionId, " is stopped!")); | ||
xhr.onabort = function() { | ||
reject(new DOMException('Aborted', 'AbortError')) | ||
} | ||
}]); | ||
return Mouselog; | ||
}(); | ||
module.exports = { | ||
Mouselog: Mouselog | ||
}; | ||
xhr.open(request.method, request.url, true) | ||
/***/ }), | ||
/* 6 */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
if (request.credentials === 'include') { | ||
xhr.withCredentials = true | ||
} else if (request.credentials === 'omit') { | ||
xhr.withCredentials = false | ||
} | ||
var rng = __webpack_require__(7); | ||
var bytesToUuid = __webpack_require__(8); | ||
if ('responseType' in xhr && support.blob) { | ||
xhr.responseType = 'blob' | ||
} | ||
function v4(options, buf, offset) { | ||
var i = buf && offset || 0; | ||
request.headers.forEach(function(value, name) { | ||
xhr.setRequestHeader(name, value) | ||
}) | ||
if (typeof(options) == 'string') { | ||
buf = options === 'binary' ? new Array(16) : null; | ||
options = null; | ||
} | ||
options = options || {}; | ||
if (request.signal) { | ||
request.signal.addEventListener('abort', abortXhr) | ||
var rnds = options.random || (options.rng || rng)(); | ||
xhr.onreadystatechange = function() { | ||
// DONE (success or failure) | ||
if (xhr.readyState === 4) { | ||
request.signal.removeEventListener('abort', abortXhr) | ||
} | ||
} | ||
} | ||
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved` | ||
rnds[6] = (rnds[6] & 0x0f) | 0x40; | ||
rnds[8] = (rnds[8] & 0x3f) | 0x80; | ||
xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit) | ||
}) | ||
} | ||
// Copy bytes to buffer, if provided | ||
if (buf) { | ||
for (var ii = 0; ii < 16; ++ii) { | ||
buf[i + ii] = rnds[ii]; | ||
} | ||
} | ||
fetch.polyfill = true | ||
return buf || bytesToUuid(rnds); | ||
if (!self.fetch) { | ||
self.fetch = fetch | ||
self.Headers = Headers | ||
self.Request = Request | ||
self.Response = Response | ||
} | ||
module.exports = v4; | ||
/***/ }), | ||
@@ -731,17 +882,61 @@ /* 7 */ | ||
/* 9 */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
/***/ (function(module, __webpack_exports__, __webpack_require__) { | ||
"use strict"; | ||
__webpack_require__.r(__webpack_exports__); | ||
// EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/classCallCheck.js | ||
var classCallCheck = __webpack_require__(0); | ||
var classCallCheck_default = /*#__PURE__*/__webpack_require__.n(classCallCheck); | ||
var _interopRequireDefault = __webpack_require__(0); | ||
// EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/createClass.js | ||
var createClass = __webpack_require__(1); | ||
var createClass_default = /*#__PURE__*/__webpack_require__.n(createClass); | ||
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | ||
// EXTERNAL MODULE: ../node_modules/uuid/v4.js | ||
var v4 = __webpack_require__(3); | ||
var v4_default = /*#__PURE__*/__webpack_require__.n(v4); | ||
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | ||
// EXTERNAL MODULE: ../node_modules/url-join/lib/url-join.js | ||
var url_join = __webpack_require__(2); | ||
var url_join_default = /*#__PURE__*/__webpack_require__.n(url_join); | ||
var urljoin = __webpack_require__(4); | ||
// CONCATENATED MODULE: ../src/debugger.js | ||
var debugMode = false; | ||
var outputElement; | ||
var debug = __webpack_require__(3); | ||
function activate(id) { | ||
debugMode = true; | ||
if (id) { | ||
outputElement = window.document.getElementById(id); | ||
if (!outputElement) { | ||
console.log("Fail to find the output element."); | ||
} | ||
} | ||
} | ||
function write(info) { | ||
if (debugMode) { | ||
if (outputElement) { | ||
var p = document.createElement("p"); | ||
p.style.display = "block"; | ||
p.style.fontSize = "10px"; | ||
p.style.margin = "2px"; | ||
var t = document.createTextNode(info); | ||
p.appendChild(t); | ||
outputElement.appendChild(p); | ||
} | ||
console.log(info); | ||
} | ||
} | ||
// CONCATENATED MODULE: ../src/uploader.js | ||
var StatusEnum = { | ||
@@ -753,7 +948,8 @@ WAITING: 0, | ||
var Uploader = | ||
var uploader_Uploader = | ||
/*#__PURE__*/ | ||
function () { | ||
function Uploader(impressionId, config) { | ||
(0, _classCallCheck2["default"])(this, Uploader); | ||
classCallCheck_default()(this, Uploader); | ||
this.impressionId = impressionId; | ||
@@ -764,3 +960,3 @@ this.config = config; | ||
(0, _createClass2["default"])(Uploader, [{ | ||
createClass_default()(Uploader, [{ | ||
key: "start", | ||
@@ -786,6 +982,10 @@ value: function start() { | ||
// reject(ErrorMessage): Errors occur when updating the config. | ||
return new Promise(function (resolve, reject) { | ||
return new Promise(function (resolve) { | ||
var encodedData = JSON.stringify(data); | ||
debug.write("Uploading Pkg ".concat(data.idx, ", window size: ").concat(data.width, "*").concat(data.height, ", events count: ").concat(data.events.length)); | ||
write("Uploading Pkg ".concat(data.idx, ", window size: ").concat(data.width, "*").concat(data.height, ", events count: ").concat(data.events.length)); | ||
for (var i = 0; i < 3 && i < data.events.length; ++i) { | ||
write(" ".concat(JSON.stringify(data.events[i]))); | ||
} | ||
_this2._upload(encodedData).then(function (res) { | ||
@@ -798,3 +998,3 @@ if (res.status == 200) { | ||
}).then(function (resObj) { | ||
debug.write("Pkg ".concat(data.idx, " response=").concat(JSON.stringify(resObj))); | ||
write("Pkg ".concat(data.idx, " response=").concat(JSON.stringify(resObj))); | ||
@@ -817,3 +1017,3 @@ if (resObj.status !== "ok") { | ||
})["catch"](function (err) { | ||
debug.write("Pkg ".concat(data.idx, " failed, wait for resending. Error message: ").concat(err.message)); | ||
write("Pkg ".concat(data.idx, " failed, wait for resending. Error message: ").concat(err.message)); | ||
@@ -849,3 +1049,3 @@ _this2._appendFailedData(data); | ||
if (this.resendQueue.length > 0) { | ||
debug.write("Resending data..."); | ||
write("Resending data..."); | ||
} | ||
@@ -861,3 +1061,3 @@ | ||
i += 1; | ||
debug.write("Resending Pkg ".concat(obj.data.idx)); | ||
write("Resending Pkg ".concat(obj.data.idx)); | ||
@@ -886,3 +1086,3 @@ if (obj.status == StatusEnum.WAITING) { | ||
value: function _upload(encodedData) { | ||
var url = urljoin(this.config.absoluteUrl, '/api/upload-trace', "?websiteId=".concat(this.config.websiteId, "&impressionId=").concat(this.impressionId)); | ||
var url = url_join_default()(this.config.absoluteUrl, "?websiteId=".concat(this.config.websiteId, "&impressionId=").concat(this.impressionId)); | ||
@@ -911,25 +1111,14 @@ if (this.config.enableGet) { | ||
}]); | ||
return Uploader; | ||
}(); | ||
module.exports = Uploader; | ||
/* harmony default export */ var uploader = (uploader_Uploader); | ||
// CONCATENATED MODULE: ../src/config.js | ||
/***/ }), | ||
/* 10 */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
"use strict"; | ||
var _interopRequireDefault = __webpack_require__(0); | ||
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | ||
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | ||
var urljoin = __webpack_require__(4); | ||
var debug = __webpack_require__(3); | ||
var Config = | ||
var config_Config = | ||
/*#__PURE__*/ | ||
@@ -939,3 +1128,4 @@ function () { | ||
function Config() { | ||
(0, _classCallCheck2["default"])(this, Config); | ||
classCallCheck_default()(this, Config); | ||
// Type: string, REQUIRED | ||
@@ -974,3 +1164,3 @@ // Endpoint Url | ||
(0, _createClass2["default"])(Config, [{ | ||
createClass_default()(Config, [{ | ||
key: "build", | ||
@@ -984,3 +1174,3 @@ value: function build(config) { | ||
this._requiredParams.forEach(function (key) { | ||
if (!config.hasOwnProperty(key)) { | ||
if (!Object.prototype.hasOwnProperty.call(config, key)) { | ||
throw new Error("Param ".concat(key, " is required but not declared.")); | ||
@@ -993,3 +1183,3 @@ } | ||
// Overwriting Class private members / function method is not allowed | ||
if (_this[key] && !key.startsWith("_") && typeof _this[key] != "function") { | ||
if (_this[key] && !(key.indexOf("_") === 0) && typeof _this[key] != "function") { | ||
// Do not update some `ignored` parameter | ||
@@ -1004,3 +1194,3 @@ if (!(isUpdating && key in _this._ignoredParams)) { | ||
} catch (err) { | ||
debug.write(err); | ||
write(err); | ||
return false; | ||
@@ -1020,5 +1210,5 @@ } | ||
if (this.endpointType == "relative") { | ||
this.absoluteUrl = urljoin(window.location.origin, this.uploadEndpoint); | ||
this.absoluteUrl = url_join_default()(window.location.origin, this.uploadEndpoint); | ||
} else if (this.endpointType == "absolute") { | ||
this.absoluteUrl = this.uploadEndpoint; | ||
this.absoluteUrl = url_join_default()(this.uploadEndpoint, "/api/upload-trace"); | ||
} else { | ||
@@ -1029,11 +1219,343 @@ throw new Error('`endpointType` can only be "absolute" or "relative"'); | ||
}]); | ||
return Config; | ||
}(); | ||
module.exports = { | ||
Config: Config | ||
}; | ||
/* harmony default export */ var src_config = (config_Config); | ||
// CONCATENATED MODULE: ../src/index.js | ||
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Mouselog", function() { return src_Mouselog; }); | ||
var targetEvents = ["mousemove", "mousedown", "mouseup", "mouseclick", "dblclick", "contextmenu", "wheel", "torchstart", "touchmove", "touchend"]; | ||
var pageLoadTime = new Date(); | ||
var hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : 'mozHidden' in document ? 'mozHidden' : null; | ||
var visibilityChangeEvent = hiddenProperty ? hiddenProperty.replace(/hidden/i, 'visibilitychange') : null; | ||
function maxNumber() { | ||
for (var _len = arguments.length, nums = new Array(_len), _key = 0; _key < _len; _key++) { | ||
nums[_key] = arguments[_key]; | ||
} | ||
var res = nums[0]; | ||
for (var i = 1; i < nums.length; ++i) { | ||
res = res > nums[i] ? res : nums[i]; | ||
} | ||
return res; | ||
} | ||
function getRelativeTimestampInSeconds() { | ||
var diff = new Date() - pageLoadTime; | ||
return Math.floor(diff) / 1000; | ||
} | ||
function getButton(btn) { | ||
if (btn === '2') { | ||
return 'Right'; | ||
} else { | ||
return ""; | ||
} | ||
} | ||
function src_parseInt(x) { | ||
var res = typeof x === 'number' ? x : Number(x); | ||
return Math.round(res); | ||
} | ||
var src_Mouselog = | ||
/*#__PURE__*/ | ||
function () { | ||
function Mouselog() { | ||
classCallCheck_default()(this, Mouselog); | ||
this.impressionId = v4_default()(); | ||
this.config = new src_config(); | ||
this.mouselogLoadTime = new Date(); | ||
this.uploader = new uploader(); | ||
this.eventsList = []; | ||
this.eventsCount = 0; | ||
this.uploadInterval; // For "periodic" upload mode | ||
this.uploadTimeout; // For "mixed" upload mode | ||
} | ||
createClass_default()(Mouselog, [{ | ||
key: "_clearBuffer", | ||
value: function _clearBuffer() { | ||
this.eventsList = []; | ||
} | ||
}, { | ||
key: "_newTrace", | ||
value: function _newTrace() { | ||
var trace = { | ||
id: '0', | ||
idx: this.uploadIdx, | ||
url: window.location.hostname ? window.location.hostname : "localhost", | ||
path: window.location.pathname, | ||
width: maxNumber(document.body.scrollWidth, window.innerWidth), | ||
height: maxNumber(document.body.scrollHeight, window.innerHeight), | ||
pageLoadTime: pageLoadTime, | ||
events: [] | ||
}; | ||
this.uploadIdx += 1; | ||
return trace; | ||
} | ||
}, { | ||
key: "_onVisibilityChange", | ||
value: function _onVisibilityChange() { | ||
if (window.document[hiddenProperty]) { | ||
// the page is not activated | ||
this._pause(); | ||
} else { | ||
// the page is activated | ||
this._resume(); | ||
} | ||
} | ||
}, { | ||
key: "_mouseHandler", | ||
value: function _mouseHandler(evt) { | ||
// PC's Chrome on Mobile mode can still receive "contextmenu" event with zero X, Y, so we ignore these events. | ||
if (evt.type === 'contextmenu' && evt.pageX === 0 && evt.pageY === 0) { | ||
return; | ||
} // In IE, evt.pageX/Y is float | ||
var x = src_parseInt(evt.pageX); | ||
var y = src_parseInt(evt.pageY); | ||
if (x === undefined) { | ||
// evt.changedTouches[0].pageX/Y is floats | ||
x = src_parseInt(evt.changedTouches[0].pageX); | ||
y = src_parseInt(evt.changedTouches[0].pageY); | ||
} | ||
var tmpEvt = { | ||
id: this.eventsCount, | ||
timestamp: getRelativeTimestampInSeconds(), | ||
type: evt.type, | ||
x: x, | ||
y: y, | ||
button: getButton(evt.button) | ||
}; | ||
if (evt.type == "wheel") { | ||
tmpEvt.deltaX = evt.deltaX; | ||
tmpEvt.deltaY = evt.deltaY; | ||
} | ||
this.eventsList.push(tmpEvt); | ||
this.eventsCount += 1; | ||
if (this.config.uploadMode == "event-triggered" && this.eventsList.length % this.config.frequency == 0) { | ||
this._uploadTrace(); | ||
} | ||
if (this.config.uploadMode == "mixed" && this.eventsList.length % this.config.frequency == 0) { | ||
this._periodUploadTimeout(); | ||
this._uploadTrace(); | ||
} | ||
} | ||
}, { | ||
key: "_fetchConfigFromServer", | ||
value: function _fetchConfigFromServer() { | ||
// Upload an empty trace to fetch config from server | ||
var trace = this._newTrace(); | ||
return this.uploader.upload(trace); // This is a promise | ||
} | ||
}, { | ||
key: "_uploadTrace", | ||
value: function _uploadTrace() { | ||
var trace = this._newTrace(); | ||
trace.events = this.eventsList; | ||
this.eventsList = []; | ||
return this.uploader.upload(trace); // This is a promise | ||
} | ||
}, { | ||
key: "_periodUploadTimeout", | ||
value: function _periodUploadTimeout() { | ||
var _this = this; | ||
clearTimeout(this.uploadTimeout); | ||
this.uploadTimeout = setTimeout(function () { | ||
if (_this.eventsList.length > 0) { | ||
_this._uploadTrace(); | ||
} | ||
}, this.config.uploadPeriod); | ||
} | ||
}, { | ||
key: "_periodUploadInterval", | ||
value: function _periodUploadInterval() { | ||
var _this2 = this; | ||
clearInterval(this.uploadInterval); | ||
this.uploadInterval = setInterval(function () { | ||
if (_this2.eventsList.length > 0) { | ||
_this2._uploadTrace(); | ||
} | ||
}, this.config.uploadPeriod); | ||
} | ||
}, { | ||
key: "_runCollector", | ||
value: function _runCollector() { | ||
var _this3 = this; | ||
targetEvents.forEach(function (s) { | ||
_this3.config.scope.addEventListener(s, function (evt) { | ||
return _this3._mouseHandler(evt); | ||
}); | ||
}); | ||
if (this.config.uploadMode === "periodic") { | ||
this._periodUploadInterval(); | ||
} | ||
if (this.config.uploadMode === "mixed") { | ||
this._periodUploadTimeout(); | ||
} | ||
} | ||
}, { | ||
key: "_stopCollector", | ||
value: function _stopCollector() { | ||
var _this4 = this; | ||
targetEvents.forEach(function (s) { | ||
_this4.config.scope.removeEventListener(s, function (evt) { | ||
return _this4._mouseHandler(evt); | ||
}); | ||
}); | ||
clearInterval(this.uploadInterval); | ||
clearTimeout(this.uploadTimeout); | ||
} | ||
}, { | ||
key: "_resetCollector", | ||
value: function _resetCollector() { | ||
this._stopCollector(); | ||
this._runCollector(); | ||
} | ||
}, { | ||
key: "_init", | ||
value: function _init(config) { | ||
var _this5 = this; | ||
this._clearBuffer(); | ||
this.uploadIdx = 0; | ||
this.uploader = new uploader(this.impressionId, this.config); | ||
this.uploader.setImpressionId(this.impressionId); | ||
if (this.config.build(config)) { | ||
// Async: Upload an empty data to fetch config from server | ||
this._fetchConfigFromServer().then(function (result) { | ||
if (result.status == 1) { | ||
if (_this5.config.update(result.config)) { | ||
_this5._resetCollector(); | ||
_this5.uploader.setConfig(_this5.config); | ||
write("Successfully update config from backend."); | ||
} else { | ||
throw new Error("Unable to update config with server config."); | ||
} | ||
} else { | ||
throw new Error("Fail to get config from server."); | ||
} | ||
})["catch"](function (err) { | ||
write(err); | ||
}); | ||
window.onbeforeunload = function () { | ||
if (_this5.eventsList.length != 0) { | ||
_this5._uploadTrace(); | ||
} | ||
}; | ||
return { | ||
status: 0 | ||
}; | ||
} else { | ||
return { | ||
status: -1, | ||
msg: "Invalid configuration." | ||
}; | ||
} | ||
} | ||
}, { | ||
key: "_pause", | ||
value: function _pause() { | ||
this._stopCollector(); | ||
} | ||
}, { | ||
key: "_resume", | ||
value: function _resume() { | ||
this._runCollector(); | ||
} | ||
}, { | ||
key: "run", | ||
value: function run(config) { | ||
var _this6 = this; | ||
var res = this._init(config); | ||
if (res.status == 0) { | ||
if (visibilityChangeEvent) { | ||
document.addEventListener(visibilityChangeEvent, function (evt) { | ||
return _this6._onVisibilityChange(evt); | ||
}); | ||
} | ||
this._runCollector(); | ||
this.uploader.start(this.impressionId); | ||
write("Mouselog agent is activated!"); | ||
write("Website ID: ".concat(this.config.websiteId)); | ||
write("Impression ID: ".concat(this.impressionId)); | ||
write("User-Agent: ".concat(navigator.userAgent)); | ||
write("Page load time: ".concat(pageLoadTime)); | ||
} else { | ||
write(res.msg); | ||
write("Fail to initialize Mouselog agent."); | ||
} | ||
} | ||
}, { | ||
key: "debug", | ||
value: function debug(config, debugOutputElementId) { | ||
activate(debugOutputElementId); | ||
this.run(config); | ||
} | ||
}, { | ||
key: "stop", | ||
value: function stop() { | ||
this.uploader.stop(); | ||
this._stopCollector(); | ||
this._clearBuffer(); | ||
write("Mouselog agent ".concat(this.impressionId, " is stopped!")); | ||
} | ||
}]); | ||
return Mouselog; | ||
}(); | ||
/***/ }) | ||
/******/ ]); | ||
}); |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.mouselog=t():e.mouselog=t()}(window,(function(){return function(e){var t={};function n(o){if(t[o])return t[o].exports;var i=t[o]={i:o,l:!1,exports:{}};return e[o].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,o){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(n.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(o,i,function(t){return e[t]}.bind(null,i));return o},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=5)}([function(e,t){e.exports=function(e){return e&&e.__esModule?e:{default:e}}},function(e,t){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t){function n(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}e.exports=function(e,t,o){return t&&n(e.prototype,t),o&&n(e,o),e}},function(e,t,n){"use strict";var o,i=!1;e.exports={activate:function(e){i=!0,e&&((o=window.document.getElementById(e))||console.log("Fail to find the output element."))},write:function(e){if(i){if(o){var t=document.createElement("p");t.style.display="block",t.style.fontSize="10px",t.style.margin="2px";var n=document.createTextNode(e);t.appendChild(n),o.appendChild(t)}console.log(e)}}}},function(e,t,n){var o,i,r;r=function(){function e(e){var t=[];if(0===e.length)return"";if("string"!=typeof e[0])throw new TypeError("Url must be a string. Received "+e[0]);if(e[0].match(/^[^/:]+:\/*$/)&&e.length>1){var n=e.shift();e[0]=n+e[0]}e[0].match(/^file:\/\/\//)?e[0]=e[0].replace(/^([^/:]+):\/*/,"$1:///"):e[0]=e[0].replace(/^([^/:]+):\/*/,"$1://");for(var o=0;o<e.length;o++){var i=e[o];if("string"!=typeof i)throw new TypeError("Url must be a string. Received "+i);""!==i&&(o>0&&(i=i.replace(/^[\/]+/,"")),i=o<e.length-1?i.replace(/[\/]+$/,""):i.replace(/[\/]+$/,"/"),t.push(i))}var r=t.join("/"),a=(r=r.replace(/\/(\?|&|#[^!])/g,"$1")).split("?");return r=a.shift()+(a.length>0?"?":"")+a.join("&")}return function(){return e("object"==typeof arguments[0]?arguments[0]:[].slice.call(arguments))}},e.exports?e.exports=r():void 0===(i="function"==typeof(o=r)?o.call(t,n,t,e):o)||(e.exports=i)},function(e,t,n){"use strict";var o=n(0),i=o(n(1)),r=o(n(2)),a=n(6),s=n(9),u=n(10).Config,c=n(3),l=["mousemove","mousedown","mouseup","mouseclick","dblclick","contextmenu","wheel","torchstart","touchmove","touchend"],d=new Date,f="hidden"in document?"hidden":"webkitHidden"in document?"webkitHidden":"mozHidden"in document?"mozHidden":null,h=f?f.replace(/hidden/i,"visibilitychange"):null;function p(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var o=t[0],i=1;i<t.length;++i)o=o>t[i]?o:t[i];return o}var v=function(){function e(){(0,i.default)(this,e),this.config=new u,this.impressionId=a(),this.mouselogLoadTime=new Date,this.uploader=new s,this.eventsList=[],this.eventsCount=0,this.uploadInterval,this.uploadTimeout}return(0,r.default)(e,[{key:"_clearBuffer",value:function(){this.eventsList=[]}},{key:"_newTrace",value:function(){var e={id:"0",idx:this.uploadIdx,url:window.location.hostname?window.location.hostname:"localhost",path:window.location.pathname,width:p(document.body.scrollWidth,window.innerWidth),height:p(document.body.scrollHeight,window.innerHeight),pageLoadTime:d,events:[]};return this.uploadIdx+=1,e}},{key:"_onVisibilityChange",value:function(e){window.document[f]?this._pause():this._resume()}},{key:"_mouseHandler",value:function(e){if("contextmenu"!==e.type||0!==e.pageX||0!==e.pageY){var t=e.pageX,n=e.pageY;void 0===t&&(t=e.changedTouches[0].pageX,n=e.changedTouches[0].pageY);var o,i,r={id:this.eventsCount,timestamp:(i=new Date-d,Math.trunc(i)/1e3),type:e.type,x:t,y:n,button:(o=e.button,"2"===o?"Right":"")};"wheel"==e.type&&(r.deltaX=e.deltaX,r.deltaY=e.deltaY),this.eventsList.push(r),this.eventsCount+=1,"event-triggered"==this.config.uploadMode&&this.eventsList.length%this.config.frequency==0&&this._uploadTrace(),"mixed"==this.config.uploadMode&&this.eventsList.length%this.config.frequency==0&&(this._periodUploadTimeout(),this._uploadTrace())}}},{key:"_fetchConfigFromServer",value:function(){var e=this._newTrace();return this.uploader.upload(e)}},{key:"_uploadTrace",value:function(){var e=this._newTrace();return e.events=this.eventsList,this.eventsList=[],this.uploader.upload(e)}},{key:"_periodUploadTimeout",value:function(){var e=this;clearTimeout(this.uploadTimeout),this.uploadTimeout=setTimeout((function(){e.eventsList.length>0&&e._uploadTrace()}),this.config.uploadPeriod)}},{key:"_periodUploadInterval",value:function(){var e=this;clearInterval(this.uploadInterval),this.uploadInterval=setInterval((function(){e.eventsList.length>0&&e._uploadTrace()}),this.config.uploadPeriod)}},{key:"_runCollector",value:function(){var e=this;l.forEach((function(t){e.config.scope.addEventListener(t,(function(t){return e._mouseHandler(t)}))})),"periodic"===this.config.uploadMode&&this._periodUploadInterval(),"mixed"===this.config.uploadMode&&this._periodUploadTimeout()}},{key:"_stopCollector",value:function(){var e=this;l.forEach((function(t){e.config.scope.removeEventListener(t,(function(t){return e._mouseHandler(t)}))})),clearInterval(this.uploadInterval),clearTimeout(this.uploadTimeout)}},{key:"_resetCollector",value:function(){this._stopCollector(),this._runCollector()}},{key:"_init",value:function(e){var t=this;return this.impressionId=a(),this._clearBuffer(),this.uploadIdx=0,this.uploader=new s(this.impressionId,this.config),this.uploader.setImpressionId(this.impressionId),this.config.build(e)?(this._fetchConfigFromServer().then((function(e){if(1!=e.status)throw new Error("Fail to get config from server.");if(!t.config.update(e.config))throw new Error("Unable to update config with server config.");t._resetCollector(),t.uploader.setConfig(t.config),c.write("Successfully update config from backend.")})).catch((function(e){c.write(e)})),window.onbeforeunload=function(e){0!=t.eventsList.length&&t._uploadTrace()},{status:0}):{status:-1,msg:"Invalid configuration."}}},{key:"_pause",value:function(){this._stopCollector()}},{key:"_resume",value:function(){this._runCollector()}},{key:"run",value:function(e){var t=this,n=this._init(e);0==n.status?(h&&document.addEventListener(h,(function(e){return t._onVisibilityChange(e)})),this._runCollector(),this.uploader.start(this.impressionId),c.write("Mouselog agent is activated!"),c.write("Website ID: ".concat(this.config.websiteId)),c.write("Impression ID: ".concat(this.impressionId)),c.write("User-Agent: ".concat(navigator.userAgent)),c.write("Page load time: ".concat(d))):(c.write(n.msg),c.write("Fail to initialize Mouselog agent."))}},{key:"debug",value:function(e,t){c.activate(t),this.run(e)}},{key:"stop",value:function(){this.uploader.stop(),this._stopCollector(),this._clearBuffer(),c.write("Mouselog agent ".concat(this.impressionId," is stopped!"))}}]),e}();e.exports={Mouselog:v}},function(e,t,n){var o=n(7),i=n(8);e.exports=function(e,t,n){var r=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var a=(e=e||{}).random||(e.rng||o)();if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t)for(var s=0;s<16;++s)t[r+s]=a[s];return t||i(a)}},function(e,t){var n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(n){var o=new Uint8Array(16);e.exports=function(){return n(o),o}}else{var i=new Array(16);e.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),i[t]=e>>>((3&t)<<3)&255;return i}}},function(e,t){for(var n=[],o=0;o<256;++o)n[o]=(o+256).toString(16).substr(1);e.exports=function(e,t){var o=t||0,i=n;return[i[e[o++]],i[e[o++]],i[e[o++]],i[e[o++]],"-",i[e[o++]],i[e[o++]],"-",i[e[o++]],i[e[o++]],"-",i[e[o++]],i[e[o++]],"-",i[e[o++]],i[e[o++]],i[e[o++]],i[e[o++]],i[e[o++]],i[e[o++]]].join("")}},function(e,t,n){"use strict";var o=n(0),i=o(n(1)),r=o(n(2)),a=n(4),s=n(3),u=0,c=1,l=2,d=function(){function e(t,n){(0,i.default)(this,e),this.impressionId=t,this.config=n,this.resendQueue=[]}return(0,r.default)(e,[{key:"start",value:function(){var e=this;this.resendInterval=setInterval((function(){e._resendFailedData.call(e)}),this.config.resendInterval)}},{key:"stop",value:function(){clearInterval(this.resendInterval)}},{key:"upload",value:function(e){var t=this;return new Promise((function(n,o){var i=JSON.stringify(e);s.write("Uploading Pkg ".concat(e.idx,", window size: ").concat(e.width,"*").concat(e.height,", events count: ").concat(e.events.length)),t._upload(i).then((function(e){if(200==e.status)return e.json();throw new Error("Response status code is not 200.")})).then((function(t){if(s.write("Pkg ".concat(e.idx," response=").concat(JSON.stringify(t))),"ok"!==t.status)throw new Error("Response object status is not ok.");"config"==t.msg&&n({status:1,msg:"Get config from server",config:t.data}),n({status:0})})).catch((function(o){s.write("Pkg ".concat(e.idx," failed, wait for resending. Error message: ").concat(o.message)),t._appendFailedData(e),n({status:-1,msg:"Fail to upload data bunch #".concat(e.idx,", ").concat(o.message)})}))}))}},{key:"setImpressionId",value:function(e){this.impressionId=e}},{key:"setConfig",value:function(e){this.stop(),this.config=e,this.start()}},{key:"_resendFailedData",value:function(){var e=this,t=0;this.resendQueue.length>0&&s.write("Resending data...");for(var n=function(){var n=e.resendQueue[t];n.status==l?e.resendQueue.splice(t,1):(t+=1,s.write("Resending Pkg ".concat(n.data.idx)),n.status==u&&(n.status=c,e.upload(n.data).then((function(e){n.status=e?l:u}))))};t<this.resendQueue.length;)n()}},{key:"_upload",value:function(e){var t=a(this.config.absoluteUrl,"/api/upload-trace","?websiteId=".concat(this.config.websiteId,"&impressionId=").concat(this.impressionId));return this.config.enableGet?fetch("".concat(t,"&data=").concat(e),{method:"GET",credentials:"include"}):fetch(t,{method:"POST",credentials:"include",body:e})}},{key:"_appendFailedData",value:function(e){this.resendQueue.push({status:u,data:e})}}]),e}();e.exports=d},function(e,t,n){"use strict";var o=n(0),i=o(n(1)),r=o(n(2)),a=n(4),s=n(3),u=function(){function e(){(0,i.default)(this,e),this.uploadEndpoint="http://localhost:9000",this.websiteId="unknown",this.endpointType="absolute",this.uploadMode="mixed",this.uploadPeriod=5e3,this.frequency=50,this.enableGet=!1,this.resendInterval=3e3,this.scope=window.document,this._requiredParams=["uploadEndpoint"],this._ignoredParams=["scope"]}return(0,r.default)(e,[{key:"build",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];try{this._requiredParams.forEach((function(t){if(!e.hasOwnProperty(t))throw new Error("Param ".concat(t," is required but not declared."))})),Object.keys(e).forEach((function(o){t[o]&&!o.startsWith("_")&&"function"!=typeof t[o]&&(n&&o in t._ignoredParams||(t[o]=e[o]))})),this._formatUrl()}catch(e){return s.write(e),!1}return!0}},{key:"update",value:function(e){return this.build(e,!0)}},{key:"_formatUrl",value:function(){if("relative"==this.endpointType)this.absoluteUrl=a(window.location.origin,this.uploadEndpoint);else{if("absolute"!=this.endpointType)throw new Error('`endpointType` can only be "absolute" or "relative"');this.absoluteUrl=this.uploadEndpoint}}}]),e}();e.exports={Config:u}}])})); | ||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.mouselog=e():t.mouselog=e()}(window,(function(){return function(t){var e={};function n(o){if(e[o])return e[o].exports;var r=e[o]={i:o,l:!1,exports:{}};return t[o].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=t,n.c=e,n.d=function(t,e,o){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:o})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var o=Object.create(null);if(n.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(o,r,function(e){return t[e]}.bind(null,r));return o},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=4)}([function(t,e){t.exports=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}},function(t,e){function n(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}t.exports=function(t,e,o){return e&&n(t.prototype,e),o&&n(t,o),t}},function(t,e,n){var o,r,i;i=function(){function t(t){var e=[];if(0===t.length)return"";if("string"!=typeof t[0])throw new TypeError("Url must be a string. Received "+t[0]);if(t[0].match(/^[^/:]+:\/*$/)&&t.length>1){var n=t.shift();t[0]=n+t[0]}t[0].match(/^file:\/\/\//)?t[0]=t[0].replace(/^([^/:]+):\/*/,"$1:///"):t[0]=t[0].replace(/^([^/:]+):\/*/,"$1://");for(var o=0;o<t.length;o++){var r=t[o];if("string"!=typeof r)throw new TypeError("Url must be a string. Received "+r);""!==r&&(o>0&&(r=r.replace(/^[\/]+/,"")),r=o<t.length-1?r.replace(/[\/]+$/,""):r.replace(/[\/]+$/,"/"),e.push(r))}var i=e.join("/"),s=(i=i.replace(/\/(\?|&|#[^!])/g,"$1")).split("?");return i=s.shift()+(s.length>0?"?":"")+s.join("&")}return function(){return t("object"==typeof arguments[0]?arguments[0]:[].slice.call(arguments))}},t.exports?t.exports=i():void 0===(r="function"==typeof(o=i)?o.call(e,n,e,t):o)||(t.exports=r)},function(t,e,n){var o=n(7),r=n(8);t.exports=function(t,e,n){var i=e&&n||0;"string"==typeof t&&(e="binary"===t?new Array(16):null,t=null);var s=(t=t||{}).random||(t.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var a=0;a<16;++a)e[i+a]=s[a];return e||r(s)}},function(t,e,n){n(5),t.exports=n(9)},function(t,e,n){n(6),t.exports=self.fetch.bind(self)},function(t,e,n){"use strict";n.r(e),n.d(e,"Headers",(function(){return h})),n.d(e,"Request",(function(){return w})),n.d(e,"Response",(function(){return T})),n.d(e,"DOMException",(function(){return E})),n.d(e,"fetch",(function(){return I}));var o="URLSearchParams"in self,r="Symbol"in self&&"iterator"in Symbol,i="FileReader"in self&&"Blob"in self&&function(){try{return new Blob,!0}catch(t){return!1}}(),s="FormData"in self,a="ArrayBuffer"in self;if(a)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(t){return t&&u.indexOf(Object.prototype.toString.call(t))>-1};function l(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function d(t){return"string"!=typeof t&&(t=String(t)),t}function f(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return r&&(e[Symbol.iterator]=function(){return e}),e}function h(t){this.map={},t instanceof h?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function p(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function y(t){return new Promise((function(e,n){t.onload=function(){e(t.result)},t.onerror=function(){n(t.error)}}))}function v(t){var e=new FileReader,n=y(e);return e.readAsArrayBuffer(t),n}function m(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function g(){return this.bodyUsed=!1,this._initBody=function(t){var e;this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:i&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:s&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:o&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():a&&i&&((e=t)&&DataView.prototype.isPrototypeOf(e))?(this._bodyArrayBuffer=m(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a&&(ArrayBuffer.prototype.isPrototypeOf(t)||c(t))?this._bodyArrayBuffer=m(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):o&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var t=p(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?p(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(v)}),this.text=function(){var t,e,n,o=p(this);if(o)return o;if(this._bodyBlob)return t=this._bodyBlob,e=new FileReader,n=y(e),e.readAsText(t),n;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),n=new Array(e.length),o=0;o<e.length;o++)n[o]=String.fromCharCode(e[o]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},s&&(this.formData=function(){return this.text().then(_)}),this.json=function(){return this.text().then(JSON.parse)},this}h.prototype.append=function(t,e){t=l(t),e=d(e);var n=this.map[t];this.map[t]=n?n+", "+e:e},h.prototype.delete=function(t){delete this.map[l(t)]},h.prototype.get=function(t){return t=l(t),this.has(t)?this.map[t]:null},h.prototype.has=function(t){return this.map.hasOwnProperty(l(t))},h.prototype.set=function(t,e){this.map[l(t)]=d(e)},h.prototype.forEach=function(t,e){for(var n in this.map)this.map.hasOwnProperty(n)&&t.call(e,this.map[n],n,this)},h.prototype.keys=function(){var t=[];return this.forEach((function(e,n){t.push(n)})),f(t)},h.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),f(t)},h.prototype.entries=function(){var t=[];return this.forEach((function(e,n){t.push([n,e])})),f(t)},r&&(h.prototype[Symbol.iterator]=h.prototype.entries);var b=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function w(t,e){var n,o,r=(e=e||{}).body;if(t instanceof w){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new h(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,r||null==t._bodyInit||(r=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",!e.headers&&this.headers||(this.headers=new h(e.headers)),this.method=(n=e.method||this.method||"GET",o=n.toUpperCase(),b.indexOf(o)>-1?o:n),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(r)}function _(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var n=t.split("="),o=n.shift().replace(/\+/g," "),r=n.join("=").replace(/\+/g," ");e.append(decodeURIComponent(o),decodeURIComponent(r))}})),e}function T(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new h(e.headers),this.url=e.url||"",this._initBody(t)}w.prototype.clone=function(){return new w(this,{body:this._bodyInit})},g.call(w.prototype),g.call(T.prototype),T.prototype.clone=function(){return new T(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new h(this.headers),url:this.url})},T.error=function(){var t=new T(null,{status:0,statusText:""});return t.type="error",t};var x=[301,302,303,307,308];T.redirect=function(t,e){if(-1===x.indexOf(e))throw new RangeError("Invalid status code");return new T(null,{status:e,headers:{location:t}})};var E=self.DOMException;try{new E}catch(t){(E=function(t,e){this.message=t,this.name=e;var n=Error(t);this.stack=n.stack}).prototype=Object.create(Error.prototype),E.prototype.constructor=E}function I(t,e){return new Promise((function(n,o){var r=new w(t,e);if(r.signal&&r.signal.aborted)return o(new E("Aborted","AbortError"));var s=new XMLHttpRequest;function a(){s.abort()}s.onload=function(){var t,e,o={status:s.status,statusText:s.statusText,headers:(t=s.getAllResponseHeaders()||"",e=new h,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(t){var n=t.split(":"),o=n.shift().trim();if(o){var r=n.join(":").trim();e.append(o,r)}})),e)};o.url="responseURL"in s?s.responseURL:o.headers.get("X-Request-URL");var r="response"in s?s.response:s.responseText;n(new T(r,o))},s.onerror=function(){o(new TypeError("Network request failed"))},s.ontimeout=function(){o(new TypeError("Network request failed"))},s.onabort=function(){o(new E("Aborted","AbortError"))},s.open(r.method,r.url,!0),"include"===r.credentials?s.withCredentials=!0:"omit"===r.credentials&&(s.withCredentials=!1),"responseType"in s&&i&&(s.responseType="blob"),r.headers.forEach((function(t,e){s.setRequestHeader(e,t)})),r.signal&&(r.signal.addEventListener("abort",a),s.onreadystatechange=function(){4===s.readyState&&r.signal.removeEventListener("abort",a)}),s.send(void 0===r._bodyInit?null:r._bodyInit)}))}I.polyfill=!0,self.fetch||(self.fetch=I,self.Headers=h,self.Request=w,self.Response=T)},function(t,e){var n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(n){var o=new Uint8Array(16);t.exports=function(){return n(o),o}}else{var r=new Array(16);t.exports=function(){for(var t,e=0;e<16;e++)0==(3&e)&&(t=4294967296*Math.random()),r[e]=t>>>((3&e)<<3)&255;return r}}},function(t,e){for(var n=[],o=0;o<256;++o)n[o]=(o+256).toString(16).substr(1);t.exports=function(t,e){var o=e||0,r=n;return[r[t[o++]],r[t[o++]],r[t[o++]],r[t[o++]],"-",r[t[o++]],r[t[o++]],"-",r[t[o++]],r[t[o++]],"-",r[t[o++]],r[t[o++]],"-",r[t[o++]],r[t[o++]],r[t[o++]],r[t[o++]],r[t[o++]],r[t[o++]]].join("")}},function(t,e,n){"use strict";n.r(e);var o,r=n(0),i=n.n(r),s=n(1),a=n.n(s),u=n(3),c=n.n(u),l=n(2),d=n.n(l),f=!1;function h(t){if(f){if(o){var e=document.createElement("p");e.style.display="block",e.style.fontSize="10px",e.style.margin="2px";var n=document.createTextNode(t);e.appendChild(n),o.appendChild(e)}console.log(t)}}var p=0,y=1,v=2,m=function(){function t(e,n){i()(this,t),this.impressionId=e,this.config=n,this.resendQueue=[]}return a()(t,[{key:"start",value:function(){var t=this;this.resendInterval=setInterval((function(){t._resendFailedData.call(t)}),this.config.resendInterval)}},{key:"stop",value:function(){clearInterval(this.resendInterval)}},{key:"upload",value:function(t){var e=this;return new Promise((function(n){var o=JSON.stringify(t);h("Uploading Pkg ".concat(t.idx,", window size: ").concat(t.width,"*").concat(t.height,", events count: ").concat(t.events.length));for(var r=0;r<3&&r<t.events.length;++r)h(" ".concat(JSON.stringify(t.events[r])));e._upload(o).then((function(t){if(200==t.status)return t.json();throw new Error("Response status code is not 200.")})).then((function(e){if(h("Pkg ".concat(t.idx," response=").concat(JSON.stringify(e))),"ok"!==e.status)throw new Error("Response object status is not ok.");"config"==e.msg&&n({status:1,msg:"Get config from server",config:e.data}),n({status:0})})).catch((function(o){h("Pkg ".concat(t.idx," failed, wait for resending. Error message: ").concat(o.message)),e._appendFailedData(t),n({status:-1,msg:"Fail to upload data bunch #".concat(t.idx,", ").concat(o.message)})}))}))}},{key:"setImpressionId",value:function(t){this.impressionId=t}},{key:"setConfig",value:function(t){this.stop(),this.config=t,this.start()}},{key:"_resendFailedData",value:function(){var t=this,e=0;this.resendQueue.length>0&&h("Resending data...");for(var n=function(){var n=t.resendQueue[e];n.status==v?t.resendQueue.splice(e,1):(e+=1,h("Resending Pkg ".concat(n.data.idx)),n.status==p&&(n.status=y,t.upload(n.data).then((function(t){n.status=t?v:p}))))};e<this.resendQueue.length;)n()}},{key:"_upload",value:function(t){var e=d()(this.config.absoluteUrl,"?websiteId=".concat(this.config.websiteId,"&impressionId=").concat(this.impressionId));return this.config.enableGet?fetch("".concat(e,"&data=").concat(t),{method:"GET",credentials:"include"}):fetch(e,{method:"POST",credentials:"include",body:t})}},{key:"_appendFailedData",value:function(t){this.resendQueue.push({status:p,data:t})}}]),t}(),g=function(){function t(){i()(this,t),this.uploadEndpoint="http://localhost:9000",this.websiteId="unknown",this.endpointType="absolute",this.uploadMode="mixed",this.uploadPeriod=5e3,this.frequency=50,this.enableGet=!1,this.resendInterval=3e3,this.scope=window.document,this._requiredParams=["uploadEndpoint"],this._ignoredParams=["scope"]}return a()(t,[{key:"build",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];try{this._requiredParams.forEach((function(e){if(!Object.prototype.hasOwnProperty.call(t,e))throw new Error("Param ".concat(e," is required but not declared."))})),Object.keys(t).forEach((function(o){e[o]&&0!==o.indexOf("_")&&"function"!=typeof e[o]&&(n&&o in e._ignoredParams||(e[o]=t[o]))})),this._formatUrl()}catch(t){return h(t),!1}return!0}},{key:"update",value:function(t){return this.build(t,!0)}},{key:"_formatUrl",value:function(){if("relative"==this.endpointType)this.absoluteUrl=d()(window.location.origin,this.uploadEndpoint);else{if("absolute"!=this.endpointType)throw new Error('`endpointType` can only be "absolute" or "relative"');this.absoluteUrl=d()(this.uploadEndpoint,"/api/upload-trace")}}}]),t}();n.d(e,"Mouselog",(function(){return I}));var b=["mousemove","mousedown","mouseup","mouseclick","dblclick","contextmenu","wheel","torchstart","touchmove","touchend"],w=new Date,_="hidden"in document?"hidden":"webkitHidden"in document?"webkitHidden":"mozHidden"in document?"mozHidden":null,T=_?_.replace(/hidden/i,"visibilitychange"):null;function x(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];for(var o=e[0],r=1;r<e.length;++r)o=o>e[r]?o:e[r];return o}function E(t){var e="number"==typeof t?t:Number(t);return Math.round(e)}var I=function(){function t(){i()(this,t),this.impressionId=c()(),this.config=new g,this.mouselogLoadTime=new Date,this.uploader=new m,this.eventsList=[],this.eventsCount=0,this.uploadInterval,this.uploadTimeout}return a()(t,[{key:"_clearBuffer",value:function(){this.eventsList=[]}},{key:"_newTrace",value:function(){var t={id:"0",idx:this.uploadIdx,url:window.location.hostname?window.location.hostname:"localhost",path:window.location.pathname,width:x(document.body.scrollWidth,window.innerWidth),height:x(document.body.scrollHeight,window.innerHeight),pageLoadTime:w,events:[]};return this.uploadIdx+=1,t}},{key:"_onVisibilityChange",value:function(){window.document[_]?this._pause():this._resume()}},{key:"_mouseHandler",value:function(t){if("contextmenu"!==t.type||0!==t.pageX||0!==t.pageY){var e=E(t.pageX),n=E(t.pageY);void 0===e&&(e=E(t.changedTouches[0].pageX),n=E(t.changedTouches[0].pageY));var o,r,i={id:this.eventsCount,timestamp:(r=new Date-w,Math.floor(r)/1e3),type:t.type,x:e,y:n,button:(o=t.button,"2"===o?"Right":"")};"wheel"==t.type&&(i.deltaX=t.deltaX,i.deltaY=t.deltaY),this.eventsList.push(i),this.eventsCount+=1,"event-triggered"==this.config.uploadMode&&this.eventsList.length%this.config.frequency==0&&this._uploadTrace(),"mixed"==this.config.uploadMode&&this.eventsList.length%this.config.frequency==0&&(this._periodUploadTimeout(),this._uploadTrace())}}},{key:"_fetchConfigFromServer",value:function(){var t=this._newTrace();return this.uploader.upload(t)}},{key:"_uploadTrace",value:function(){var t=this._newTrace();return t.events=this.eventsList,this.eventsList=[],this.uploader.upload(t)}},{key:"_periodUploadTimeout",value:function(){var t=this;clearTimeout(this.uploadTimeout),this.uploadTimeout=setTimeout((function(){t.eventsList.length>0&&t._uploadTrace()}),this.config.uploadPeriod)}},{key:"_periodUploadInterval",value:function(){var t=this;clearInterval(this.uploadInterval),this.uploadInterval=setInterval((function(){t.eventsList.length>0&&t._uploadTrace()}),this.config.uploadPeriod)}},{key:"_runCollector",value:function(){var t=this;b.forEach((function(e){t.config.scope.addEventListener(e,(function(e){return t._mouseHandler(e)}))})),"periodic"===this.config.uploadMode&&this._periodUploadInterval(),"mixed"===this.config.uploadMode&&this._periodUploadTimeout()}},{key:"_stopCollector",value:function(){var t=this;b.forEach((function(e){t.config.scope.removeEventListener(e,(function(e){return t._mouseHandler(e)}))})),clearInterval(this.uploadInterval),clearTimeout(this.uploadTimeout)}},{key:"_resetCollector",value:function(){this._stopCollector(),this._runCollector()}},{key:"_init",value:function(t){var e=this;return this._clearBuffer(),this.uploadIdx=0,this.uploader=new m(this.impressionId,this.config),this.uploader.setImpressionId(this.impressionId),this.config.build(t)?(this._fetchConfigFromServer().then((function(t){if(1!=t.status)throw new Error("Fail to get config from server.");if(!e.config.update(t.config))throw new Error("Unable to update config with server config.");e._resetCollector(),e.uploader.setConfig(e.config),h("Successfully update config from backend.")})).catch((function(t){h(t)})),window.onbeforeunload=function(){0!=e.eventsList.length&&e._uploadTrace()},{status:0}):{status:-1,msg:"Invalid configuration."}}},{key:"_pause",value:function(){this._stopCollector()}},{key:"_resume",value:function(){this._runCollector()}},{key:"run",value:function(t){var e=this,n=this._init(t);0==n.status?(T&&document.addEventListener(T,(function(t){return e._onVisibilityChange(t)})),this._runCollector(),this.uploader.start(this.impressionId),h("Mouselog agent is activated!"),h("Website ID: ".concat(this.config.websiteId)),h("Impression ID: ".concat(this.impressionId)),h("User-Agent: ".concat(navigator.userAgent)),h("Page load time: ".concat(w))):(h(n.msg),h("Fail to initialize Mouselog agent."))}},{key:"debug",value:function(t,e){var n;f=!0,(n=e)&&((o=window.document.getElementById(n))||console.log("Fail to find the output element.")),this.run(t)}},{key:"stop",value:function(){this.uploader.stop(),this._stopCollector(),this._clearBuffer(),h("Mouselog agent ".concat(this.impressionId," is stopped!"))}}]),t}()}])})); |
{ | ||
"name": "mouselog", | ||
"version": "0.1.1", | ||
"version": "0.1.2", | ||
"description": "The mouse tracking agent for Mouselog.", | ||
"main": "./src/index.js", | ||
"main": "./lib/index.js", | ||
"homepage": "https://github.com/microsoft/mouselog.js", | ||
"scripts": { | ||
"test": "echo \"Error: no test specified\" && exit 1", | ||
"build": "cd webpack-build && webpack && webpack --config comp.js && cd .." | ||
"build": "rimraf -rf build/ && cd webpack-build && webpack && webpack --config comp.js && cd ..", | ||
"lint": "eslint src/**.js", | ||
"compile": "babel -d lib/ src/", | ||
"prepublish": "npm run compile && npm run build" | ||
}, | ||
@@ -21,2 +24,4 @@ "keywords": [], | ||
"@babel/runtime": "^7.8.4", | ||
"isomorphic-fetch": "^2.2.1", | ||
"promise-polyfill": "8.1.3", | ||
"url-join": "^4.0.1", | ||
@@ -31,2 +36,5 @@ "uuid": "^3.3.3" | ||
"babel-loader": "^8.0.6", | ||
"babel-plugin-starts-with-ends-with": "^1.0.2", | ||
"eslint": "^6.8.0", | ||
"rimraf": "^3.0.2", | ||
"webpack": "^4.41.5", | ||
@@ -33,0 +41,0 @@ "webpack-cli": "^3.3.10" |
@@ -28,3 +28,3 @@ [![NPM version](https://img.shields.io/npm/v/mouselog)](https://www.npmjs.com/package/mouselog) | ||
script.src = "https://cdn.jsdelivr.net/npm/mouselog@latest/build/mouselog.js"; | ||
script.onload = () => { | ||
script.onload = function() { | ||
var agent = new mouselog.Mouselog(); | ||
@@ -42,2 +42,6 @@ agent.run({ | ||
``` | ||
### | ||
To achieve high compatability for IE9, you should refer to [promise-polyfill](https://github.com/taylorhakes/promise-polyfill) before refering Mouselog agent. | ||
## Build Manually | ||
@@ -44,0 +48,0 @@ You can also bundle Mouselog.js manually via |
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
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
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
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
90252
13
1821
130
5
10
10
+ Addedisomorphic-fetch@^2.2.1
+ Addedpromise-polyfill@8.1.3
+ Addedencoding@0.1.13(transitive)
+ Addediconv-lite@0.6.3(transitive)
+ Addedis-stream@1.1.0(transitive)
+ Addedisomorphic-fetch@2.2.1(transitive)
+ Addednode-fetch@1.7.3(transitive)
+ Addedpromise-polyfill@8.1.3(transitive)
+ Addedsafer-buffer@2.1.2(transitive)
+ Addedwhatwg-fetch@3.6.20(transitive)