Skip to content

Instantly share code, notes, and snippets.

@iam-py-test
Created December 20, 2023 16:02
Show Gist options
  • Save iam-py-test/a33fae47eaf0df2af495b4fccecae596 to your computer and use it in GitHub Desktop.
Save iam-py-test/a33fae47eaf0df2af495b4fccecae596 to your computer and use it in GitHub Desktop.
"use strict";
var _slicedToArray = function() {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break
}
} catch (err) {
_d = true;
_e = err
} finally {
try {
if (!_n && _i["return"]) _i["return"]()
} finally {
if (_d) throw _e
}
}
return _arr
}
return function(arr, i) {
if (Array.isArray(arr)) {
return arr
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i)
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance")
}
}
}();
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
};
function _toConsumableArray(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i]
}
return arr2
} else {
return Array.from(arr)
}
}(function() {
if (window.dmnActive !== undefined) return;
window.dmnActive = true;
window.dmnversion = "1.0";
var scriptError = [];
window.jenniferFrontError = function(message) {
try {
throw Error(message)
} catch (error) {
scriptError.push({
message: "CustomError: " + message,
source: "demian.js",
lineNo: 0,
colNo: 0,
stack: error && error.stack ? error.stack : undefined,
type: "CustomError"
})
}
};
var allow_cookie = "True" !== "False";
var sampling_ratio = Number("1");
var can_fetch = sampling_ratio === 1 || isNaN(sampling_ratio) ? true : sampling_ratio > Math.random();
var isServerAlive = true;
function JSONStringify(value) {
var _jsonStringify = JSON.stringify;
var toJSONContext = [];
if (window.Prototype) {
toJSONContext.push(Object.prototype.toJSON || null);
toJSONContext.push(Array.prototype.toJSON || null);
toJSONContext.push(Hash.prototype.toJSON || null);
toJSONContext.push(String.prototype.toJSON || null);
delete Object.prototype.toJSON;
delete Array.prototype.toJSON;
delete Hash.prototype.toJSON;
delete String.prototype.toJSON
}
var ret = _jsonStringify(value);
if (window.Prototype) {
String.prototype.toJSON = toJSONContext.pop();
Hash.prototype.toJSON = toJSONContext.pop();
Array.prototype.toJSON = toJSONContext.pop();
Object.prototype.toJSON = toJSONContext.pop()
}
return ret
}
function logError(log) {
try {
var DOMAIN = location.protocol + "//d-api.jennifersoft.com";
var xhr = null;
if (window.XDomainRequest) xhr = new window.XDomainRequest;
else if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest;
xhr._demianNotCollect = true
} else if (window.ActiveXObject) xhr = new ActiveXObject("Microsoft.XMLHTTP");
else throw {};
xhr.open("POST", DOMAIN + "/api/collect-log", true);
xhr.send(log);
xhr.onerror = function() {
console.log(log)
}
} catch (e) {
if (console) console.log(e)
}
}
try {
var now = function now() {
return (new Date).getTime()
};
var fetchAPM = function fetchAPM(pageId, data, url, txid) {
var collect = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
var xhr = null;
xhr = new XMLHttpRequest;
xhr._demianNotCollect = !collect;
var timing = data.performance.timing;
var startTime = timing.navigationStart || timing.requestStart;
var responseEnd = Math.min(timing.responseEnd, timing.domInteractive);
var dnsLookup = timing.domainLookupEnd - timing.domainLookupStart;
var reqTime = timing.responseStart - startTime;
var respTime = responseEnd - timing.responseStart;
var domTime = timing.domInteractive - responseEnd;
var renderTime = timing.loadEventEnd - timing.domInteractive;
if (renderTime < 0) renderTime = 0;
var params = "txid=" + txid + "&dom=" + domTime + "&render=" + renderTime + "&dns=" + dnsLookup + "&req=" + reqTime + "&resp=" + respTime + "&appId=" + appId + "&pageLoadId=" + pageId;
xhr.open("GET", url + "?" + params, true);
xhr.setRequestHeader("aries-fem-enabled", "true");
xhr.send(data)
};
var fetch = function fetch(data) {
var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "json";
var collect = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!can_fetch) return;
var xhr = null;
if (window.XDomainRequest) xhr = new window.XDomainRequest;
else {
xhr = new XMLHttpRequest;
xhr._demianNotCollect = !collect
}
xhr.open("POST", DOMAIN + "/" + path, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status / 100 >= 5) {
isServerAlive = false
}
};
xhr.withCredentials = true;
xhr.onerror = function() {
isServerAlive = false
};
xhr.send(data)
};
var getUserSetting = function getUserSetting(category, key) {
var data = window.dmndata;
if (data != null && data instanceof Array && data.length != 0) {
for (var i = 0; i < data.length; i++) {
var d = data[i];
if (d[category] != null && _typeof(d[category]) == "object" && d[category][key] !== undefined) {
return d[category][key]
}
}
} else {
return undefined
}
};
var filterLocalhost = function filterLocalhost() {
return getUserSetting("filter", "localhost") === true && ["localhost", "127.0.0.1", "", "::1"].includes(window.location.hostname)
};
var guid = function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 65536).toString(16).substring(1)
}
return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4()
};
var getVisitorId = function getVisitorId() {
var value = document.cookie.match(new RegExp("(^|;) ?" + VISITOR_ID + "=([^;]*)(;|$)"));
var visitorId = null;
if (value && value[2] != "") visitorId = value[2];
else visitorId = guid();
if (allow_cookie) {
var date = new Date;
date.setTime(date.getTime() + 48 * 60 * 60 * 1e3);
document.cookie = VISITOR_ID + "=" + visitorId + ";expires=" + date.toUTCString() + ";path=/"
}
return visitorId
};
var sendWithImage = function sendWithImage() {
function sendImage() {
var end = window.dmnatime;
end = end instanceof Date ? end.getTime() : now();
var img = document.createElement("img");
img.width = 1;
img.height = 1;
img.src = DOMAIN + ("/img?applicationId=" + encodeURIComponent(appId) + "&visitorId=" + encodeURIComponent(getVisitorId()) + "&pageId=" + encodeURIComponent(guid()) + "&url=" + encodeURIComponent(location.href) + "&loadTime=" + encodeURIComponent(end - start));
if (document.body && document.body.appendChild) {
document.body.appendChild(img)
}
}
if (document.readyState == "complete") {
start = now();
sendImage()
} else {
if (window.addEventListener) window.addEventListener("load", sendImage);
else if (window.attachEvent) document.attachEvent("onreadystatechange", function() {
if (document.readyState === "complete") sendImage()
})
}
};
var getCpuIdle = function getCpuIdle() {
(function _get() {
if (typeof window.requestIdleCallback != "function") return;
window.requestIdleCallback(function(d) {
if (d.didTimeout || document.readyState == "loading") _get();
else cpuIdleTime = performance.now()
}, {
timeout: 1e4
})
})()
};
var scrapResources = function scrapResources() {
if (performance.getEntriesByType) {
var payload = [];
var resources = performance.getEntriesByType("resource");
if (resources.length == 0) return null;
for (; resourceCursor < resources.length; resourceCursor++) {
var resource = resources[resourceCursor];
if (resource == null || resource.duration == 0 || resource.initiatorType == "xmlhttprequest" || resource.initiatorType == "fetch" || resource.initiatorType == "xdomainrequest") continue;
payload.push([resource.name, parseInt(resource.duration || 0), resource.transferSize == 0 ? null : parseInt(resource.transferSize)])
}
if (payload.length == 0) return null;
return payload
}
return null
};
var sendResources = function sendResources(pageId) {
var resources = scrapResources();
if (resources) {
fetch(JSONStringify([pageId, resources]), appId + "/resource")
}
};
var sendAjaxRequests = function sendAjaxRequests(pageId) {
if (ajaxRequest.length > 0) {
var body = [pageId, [].concat(_toConsumableArray(ajaxRequest))];
ajaxRequest = [];
fetch(JSONStringify(body), appId + "/ajax-v2", false)
}
};
var scrapErrors = function scrapErrors() {
var scrap = function scrap(msg, url, lineNo, colNo, error) {
scriptError.push({
message: msg,
source: url,
lineNo: lineNo,
colNo: colNo,
stack: error && error.stack ? error.stack : undefined,
type: error && error.constructor ? error.constructor.name : undefined
})
};
if (window.addEventListener) {
window.addEventListener("error", function(event) {
var error = event.error;
scrap(event.message, event.filename, event.lineno, event.colno, error)
});
if (window.Promise && window.PromiseRejectionEvent) window.addEventListener("unhandledrejection", function(event) {
var error = event ? event.reason : null;
if (error && error instanceof Error) scrap(error.message, error.fileName, error.lineNumber, error.columnNumber, error)
})
}
};
var sendScriptErrors = function sendScriptErrors(pageId) {
if (scriptError.length <= 0) return;
var errors = [];
for (var i = 0; i < scriptError.length; i++) {
var e = scriptError[i];
errors.push([e.message, e.type, e.source, e.linNo, e.colNo, e.stack])
}
scriptError = [];
fetch(JSONStringify([pageId, errors]), appId + "/js-error")
};
var scrapAjax = function scrapAjax(pageId) {
if (window.XMLHttpRequest != null) {
var open = XMLHttpRequest.prototype.open;
var send = XMLHttpRequest.prototype.send;
var getDataSize = function getDataSize(data) {
if (data == null) {
return 0
}
var size = 0;
if (window.ArrayBuffer != null) {
if (data instanceof window.ArrayBuffer) size = data.byteLength
}
if (window.Blob != null) {
if (data instanceof window.Blob) size = data.size
}
if (typeof data.length == "number") size = data.length;
return size
};
var pushAjaxRequest = function pushAjaxRequest(xhr, sentSize) {
try {
var endTime = now();
var _url = xhr._demianURL;
var callbackTime = endTime - xhr._demianCallbackStartTime;
var serverTime = xhr._demianCallbackStartTime - xhr._demianStartTime;
var method = xhr._demianMethod;
var response = null;
try {
response = xhr.response || xhr.responseText || null
} catch (_) {
response = null
}
var status = xhr.status;
if (status == 0) status = 0;
var recvSize = getDataSize(response);
var body = [_url, [serverTime, callbackTime],
[sentSize, recvSize], status, method
];
if (xhr._demianPushed === false) {
ajaxRequest.push(body);
xhr._demianPushed = true
}
} catch (e) {
logError("PUSH AJAX: " + url + " " + e.toString())
}
};
var pushAjaxNetworkErrorRequest = function pushAjaxNetworkErrorRequest(xhr) {
try {
var _url2 = xhr._demianURL;
var method = xhr._demianMethod;
var body = [_url2, null, null, 0, method];
ajaxRequest.push(body)
} catch (e) {
logError("PUSH ERROR AJAX: " + url + " " + e.toString())
}
};
hasJqueryHooked = typeof window.$ !== "function";
XMLHttpRequest.prototype.open = function(method, url) {
var xhr = this;
try {
if (!xhr._demianNotCollect) {
xhr._demianURL = url;
xhr._demianStartTime = now();
xhr._demianMethod = method;
xhr._demianPushed = false
}
} catch (e) {
logError("OPEN AJAX: " + e.toString())
} finally {
open.apply(this, arguments)
}
};
XMLHttpRequest.prototype.send = function(data) {
var xhr = this;
var onloadendSuppport = "onloadend" in XMLHttpRequest.prototype;
try {
if (!xhr._demianNotCollect) {
xhr._demianTimeouted = false;
var sentSize = getDataSize(data);
if (xhr.addEventListener) {
if (onloadendSuppport) {
xhr.addEventListener("loadend", function() {
pushAjaxRequest(xhr, sentSize)
})
}
xhr.addEventListener("readystatechange", function() {
if (xhr.readyState == 4) {
xhr._demianCallbackStartTime = now();
if (!onloadendSuppport) {
setTimeout(function() {
pushAjaxRequest(xhr, sentSize)
}, 0)
}
}
})
}
}
} catch (e) {
logError("SEND AJAX: " + xhr._demianURL + " " + e.toString())
} finally {
try {
send.apply(this, arguments)
} catch (e) {
try {
pushAjaxNetworkErrorRequest(xhr)
} catch (e2) {
logError("SEND ERROR AJAX: " + xhr._demianURL + " " + e.toString())
}
throw e
}
}
}
}
if (window.fetch != null && window.Promise != null) {
var originThen = Promise.prototype.then;
Promise.prototype.then = function() {
if (this._demianOnTrace) {
var ret = originThen.apply(this, arguments);
ret["finally"](function() {
if (ret.next == undefined) {
ret._demianOnTrace(ret._demianTraceContext)
}
});
ret._demianOnTrace = this._demianOnTrace;
ret._demianTraceContext = this._demianTraceContext;
this.next = ret;
return ret
} else {
return originThen.apply(this, arguments)
}
};
var originFetch = window.fetch;
window.fetch = function(url, param) {
var _this = this,
_arguments = arguments;
try {
var startTime = now();
var method = "GET";
var sentSize = 0;
if (param != null) {
method = param.method || "GET";
var body = param.body;
if (body != null && method != "GET") {
if (body instanceof window.ArrayBuffer) sentSize = body.byteLength;
else if (body instanceof window.Blob) sentSize = body.size;
else if (body.length != null) sentSize = body.length
}
}
var ret = new Promise(function(resolve, reject) {
originFetch.apply(_this, _arguments).then(function(data) {
try {
var callbackStartTime = now();
var status = data.status;
var serverTime = callbackStartTime - startTime;
ret._demianTraceContext.content = {
url: url,
serverTime: serverTime,
callbackStartTime: callbackStartTime,
status: status,
method: method,
sentSize: sentSize
}
} catch (e) {
logError("PROMISE FETCH: " + e.toString())
} finally {
resolve.apply(this, arguments)
}
})["catch"](function() {
return reject.apply(this, arguments)
})
});
ret._demianTraceContext = {};
ret._demianOnTrace = function(context) {
try {
var content = context.content;
if (content == null) return;
var callbackEndTime = now();
var _url3 = content.url;
var serverTime = content.serverTime;
var callbackTime = callbackEndTime - content.callbackStartTime;
var status = content.status;
var _method = content.method;
var _sentSize = content.sentSize;
var _body = [_url3, [serverTime, callbackTime],
[_sentSize, 0], status, _method
];
ajaxRequest.push(_body)
} catch (e) {
logError("PUSH FETCH: " + e.toString())
}
};
return ret
} catch (e) {
logError("FETCH: " + e.toString());
return originFetch(url, param)
}
}
}
};
var sendData = function sendData(applicationId, pageId, url) {
var scriptTags = document.getElementsByTagName("script");
var scriptTag = [];
var hasJquery = false;
for (var i = 0; i < scriptTags.length; i++) {
if (scriptTags[i].src == "" || !scriptTags[i].src) continue;
scriptTag.push({
src: scriptTags[i].src,
async: scriptTags[i].async ? true : false
});
if (!hasJquery && scriptTags[i].src.indexOf("jquery") > 0) {
hasJquery = true
}
}
var performance = {};
if (window.performance.timing) {
var t = window.performance.timing;
performance.timing = {
navigationStart: t.navigationStart,
unloadEventStart: t.unloadEventStart,
unloadEventEnd: t.unloadEventEnd,
redirectStart: t.redirectStart,
redirectEnd: t.redirectEnd,
fetchStart: t.fetchStart,
domainLookupStart: t.domainLookupStart,
domainLookupEnd: t.domainLookupEnd,
connectStart: t.connectStart,
connectEnd: t.connectEnd,
secureConnectionStart: t.secureConnectionStart,
requestStart: t.requestStart,
responseStart: t.responseStart,
responseEnd: t.responseEnd,
domLoading: t.domLoading,
domInteractive: t.domInteractive,
domContentLoadedEventStart: t.domContentLoadedEventStart,
domContentLoadedEventEnd: t.domContentLoadedEventEnd,
domComplete: t.domComplete,
loadEventStart: t.loadEventStart,
loadEventEnd: t.loadEventEnd
}
}
if (window.performance.getEntriesByType && window.performance.timing) {
var isIE = window.navigator.msPointerEnabled;
if (isIE) {
performance.entries = window.performance.getEntriesByType("resource");
if (window.performance.timing && window.performance.timing.msFirstPaint) {
var _t = window.performance.timing;
performance.entries.push({
entryType: "paint",
name: "first-paint",
startTime: _t.msFirstPaint - _t.navigationStart,
duration: 0
})
}
} else {
performance.entries = [];
var _window$performance$g = window.performance.getEntriesByType("navigation"),
_window$performance$g2 = _slicedToArray(_window$performance$g, 1),
navigation = _window$performance$g2[0];
if (navigation) performance.entries.push(navigation.toJSON());
var resources = window.performance.getEntriesByType("resource");
for (var _i = 0; _i < resources.length; _i++) {
var r = resources[_i];
performance.entries.push({
entryType: r.entryType,
name: r.name,
startTime: r.startTime,
duration: r.duration,
initiatorType: r.initiatorType,
nextHopProtocol: r.nextHopProtocol,
workerStart: r.workerStart,
redirectStart: r.redirectStart,
redirectEnd: r.redirectEnd,
fetchStart: r.fetchStart,
domainLookupStart: r.domainLookupStart,
domainLookupEnd: r.domainLookupEnd,
connectStart: r.connectStart,
connectEnd: r.connectEnd,
secureConnectionStart: r.secureConnectionStart,
requestStart: r.requestStart,
responseStart: r.responseStart,
responseEnd: r.responseEnd,
transferSize: r.transferSize,
encodedBodySize: r.encodedBodySize,
decodedBodySize: r.decodedBodySize
})
}
var paints = window.performance.getEntriesByType("paint");
for (var _i2 = 0; _i2 < paints.length; _i2++) {
var p = paints[_i2];
performance.entries.push({
entryType: p.entryType,
name: p.name,
startTime: p.startTime,
duration: p.duration
})
}
}
}
var body = {
applicationId: applicationId,
samplingRatio: sampling_ratio,
hookedIfJquery: hasJquery ? hasJqueryHooked : undefined,
url: url,
performance: performance,
loadFinished: true,
pageId: pageId,
scriptTag: scriptTag,
scriptError: scriptError,
visitorId: getVisitorId(),
extra: {}
};
if (cpuIdleTime != null) body.cpuIdleTime = cpuIdleTime;
if (body == null) logError("body is empty");
if (navigator.connection != null) {
var c = navigator.connection;
body.extra.connection = {
downlink: c.downlink,
rtt: c.rtt,
type: c.type,
downlinkMax: c.downlinkMax,
effectiveType: c.effectiveType
}
}
if (window.performance.memory != null) {
var mem = window.performance.memory;
body.extra.memory = {
totalJSHeapSize: mem.totalJSHeapSize,
usedJSHeapSize: mem.usedJSHeapSize,
jsHeapSizeLimit: mem.jsHeapSizeLimit
}
}
if (navigator.hardwareConcurrency != null) {
body.extra.cpuCount = navigator.hardwareConcurrency
}
var jenniferIntg = null;
if (window.performance.getEntriesByType && window.performance.timing) {
var _navigation = window.performance.getEntriesByType("navigation");
if (_navigation && _navigation.length > 0 && window.PerformanceNavigationTiming != null && _navigation[0] instanceof window.PerformanceNavigationTiming && _navigation[0].serverTiming != undefined) {
var timings = _navigation[0].serverTiming;
for (var _i3 in timings) {
var timing = timings[_i3];
if (timing.name == "jennifer-front") {
jenniferIntg = timing.description
}
}
}
}
if (jenniferIntg == null && typeof window.dmnajennifer === "string" && window.dmnajennifer !== "JENNIFER_FRONT@INTG") {
var paramsText = window.dmnajennifer.split("@INTG");
if (paramsText.length == 2 && paramsText[1] != "") {
jenniferIntg = paramsText[1]
}
}
if (jenniferIntg !== null) {
try {
var params = jenniferIntg.split(",");
if (params != null && params.length == 4) {
if (params[3] != "NOT_SEND") {
fetchAPM(pageId, body, params[3], params[0])
}
body.jenniferAPM = {
transactionId: params[0],
collectTime: parseInt(params[1]),
domainId: params[2]
}
}
} catch (e) {
logError("PARSE TXID EXCEPTION: " + e.toString())
}
}
var userId = getUserSetting("set", "userId");
if (userId != null) {
body.capturedUserId = userId
}
fetch(JSONStringify(body));
if (performance.clearResourceTimings !== null) {
var originClearResource = performance.clearResourceTimings;
performance.clearResourceTimings = function() {
logError("CLEAR RESOURCES TIMINGS CALLED");
return originClearResource()
}
}
var sendScrap = function sendScrap() {
if (filterLocalhost()) return;
sendScriptErrors(pageId);
sendResources(pageId);
sendAjaxRequests(pageId);
if (isServerAlive === true) {
setTimeout(function() {
sendScrap()
}, 1e3)
}
};
sendScrap()
};
var main = function main(pageId) {
if (document.readyState != "complete") {
window.addEventListener("load", function() {
setTimeout(function() {
sendData(appId, pageId, url)
}, 0)
})
} else {
sendData(appId, pageId, url)
}
};
if (location.protocol != "http:" && location.protocol != "https:") return;
var start = now();
var appId = window.dmnaid;
var url = location.href;
var VISITOR_ID = "D_VISITOR_ID";
var DOMAIN = location.protocol + "//d-collector.jennifersoft.com";
if (appId == null) return;
if (url == null || url == "") return;
var cpuIdleTime = null;
var ajaxRequest = [];
var resourceCursor = 0;
var hasJqueryHooked = false;
if (window.JSON == null || window.JSON.stringify == null || window.performance == null || window.performance.timing == null || window.addEventListener == null) {
sendWithImage()
} else {
if (filterLocalhost()) return;
var pageId = guid();
getCpuIdle();
scrapErrors();
scrapAjax(pageId);
main(pageId)
}
} catch (e) {
logError("MAIN EXCEPTION: " + e.toString())
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment