@papa-sports/web-tracing-vue2
Version:
基于 JS 跨平台插件,为前端项目提供【 埋点、行为、性能、异常、请求、资源、路由、曝光、录屏 】监控手段 - vue2版本
15,349 lines • 523 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter$1(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
function isType(type) {
return function (value) {
return Object.prototype.toString.call(value) === "[object ".concat(type, "]");
};
}
var isRegExp$1 = isType("RegExp");
var isNumber = isType("Number");
var isString = isType("String");
var isBoolean = isType("Boolean");
var isFunction = isType("Function");
var isArray = isType("Array");
var isWindow = isType("Window");
var isFlase = function (val) {
return isBoolean(val) && String(val) === "false";
};
function isEmpty(wat) {
return isString(wat) && wat.trim() === "" || wat === void 0 || wat === null;
}
var _a, _b;
var isBrowserEnv = isWindow(typeof window !== "undefined" ? window : 0);
var isElectronEnv = !!((_b = (_a = window === null || window === void 0 ? void 0 : window.process) === null || _a === void 0 ? void 0 : _a.versions) === null || _b === void 0 ? void 0 : _b.electron);
var isTestEnv = typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom") ||
// @ts-expect-error: jsdom
typeof window !== "undefined" && window.jsdom;
function getGlobal() {
if (isBrowserEnv || isElectronEnv || isTestEnv) return window;
return {};
}
function getGlobalSupport() {
_global.__webTracing__ = _global.__webTracing__ || {};
return _global.__webTracing__;
}
function isInit() {
return !!_global.__webTracingInit__;
}
var _global = getGlobal();
var _support = getGlobalSupport();
var Dep = /** @class */
function () {
function Dep2() {
this.subs = /* @__PURE__ */new Set();
}
Dep2.prototype.addSub = function () {
if (Dep2.target) this.subs.add(Dep2.target);
};
Dep2.prototype.notify = function () {
var params = [];
for (var _i = 0; _i < arguments.length; _i++) {
params[_i] = arguments[_i];
}
this.subs.forEach(function (watcher) {
watcher.proxy.dirty = true;
watcher.update.apply(
// 标明数据脏了,当再次使用到这个值会重新计算
watcher, params);
});
};
return Dep2;
}();
var OBSERVERSIGNBOARD = "__webtracingobserver__";
function isRegExp(value) {
return Object.prototype.toString.call(value) === "[object RegExp]";
}
var Observer = /** @class */
function () {
function Observer2(target) {
this.target = target;
}
Observer2.prototype.defineReactive = function () {
var dep = new Dep();
var handlers = getHandlers(function () {
dep.addSub();
}, function (oldValue) {
dep.notify(oldValue);
});
return new Proxy(this.target, handlers);
};
return Observer2;
}();
function getHandlers(getCallBack, setCallBack) {
var proxyCache = /* @__PURE__ */new WeakMap();
var handlers = {
get: function (target, key, receiver) {
var value = Reflect.get(target, key, receiver);
getCallBack && getCallBack();
if (typeof value === "object" && value !== null && !isRegExp(value)) {
var proxy = proxyCache.get(value);
if (!proxy) {
proxy = new Proxy(value, handlers);
proxyCache.set(value, proxy);
}
return proxy;
}
return value;
},
set: function (target, key, value, receiver) {
var oldValue = Reflect.get(target, key, receiver);
if (oldValue === value) return oldValue;
var beforeTarget = JSON.parse(JSON.stringify(target));
var result = Reflect.set(target, key, value, receiver);
setCallBack && setCallBack(beforeTarget);
return result;
}
};
return handlers;
}
var refMap = /* @__PURE__ */new WeakMap();
function ref$1(target) {
var newObj = {
value: target
};
newObj[OBSERVERSIGNBOARD] = true;
var ob = new Observer(newObj);
var proxy = ob.defineReactive();
refMap.set(ob, proxy);
return proxy;
}
function isRef(ref2) {
return !!ref2[OBSERVERSIGNBOARD];
}
var targetStack = [];
function pushTarget(_target) {
if (Dep.target) targetStack.push(Dep.target);
Dep.target = _target;
}
function popTarget() {
Dep.target = targetStack.pop();
}
var Watcher = /** @class */
function () {
function Watcher2(vm, options, getter) {
var computed = options.computed,
watch = options.watch,
callback = options.callback;
this.getter = getter;
this.computed = computed || false;
this.watch = watch || false;
this.callback = callback;
this.proxy = {
value: "",
// 存储这个属性的值,在不需要更新的时候会直接取这个值
dirty: true
// 表示这个属性是否脏了(脏了代表需要重新运算更新这个值)
};
this.vm = vm;
if (computed) {
this.dep = new Dep();
} else if (watch) {
this.watchGet();
} else {
this.get();
}
}
Watcher2.prototype.update = function (oldValue) {
if (this.computed) {
this.dep.notify();
} else if (this.watch) {
if (oldValue !== this.proxy.value) {
this.callback && this.callback(this.proxy.value, oldValue);
}
} else {
this.get();
}
};
Watcher2.prototype.get = function () {
pushTarget(this);
var value = this.computed ? computedMap.get(this.vm).call(this.vm) : "";
if (value !== this.proxy.value) {
this.proxy.dirty = false;
this.proxy.value = value;
}
popTarget();
return value;
};
Watcher2.prototype.watchGet = function () {
pushTarget(this);
this.proxy.dirty = false;
if (this.getter) {
this.proxy.value = this.getter();
}
popTarget();
};
Watcher2.prototype.depend = function () {
this.dep.addSub();
};
return Watcher2;
}();
var Computed = /** @class */
function () {
function Computed2(target) {
this.target = target;
}
Computed2.prototype.defineReactive = function () {
var computedWatcher = new Watcher(this, {
computed: true
});
var handlers = {
get: function () {
if (computedWatcher.proxy.dirty) {
computedWatcher.depend();
return computedWatcher.get();
} else {
computedWatcher.depend();
return computedWatcher.proxy.value;
}
}
};
return new Proxy(this.target, handlers);
};
return Computed2;
}();
var computedMap = /* @__PURE__ */new WeakMap();
function computed$1(fun) {
var target = {
value: 0
};
target[OBSERVERSIGNBOARD] = true;
var ob = new Computed(target);
var proxy = ob.defineReactive();
computedMap.set(ob, fun);
return proxy;
}
function watchInit(callback, getter) {
new Watcher("", {
watch: true,
callback
}, getter);
}
function watch$1(target, fun) {
if (!isRef(target)) return;
watchInit(function (newValue, oldValue) {
fun(newValue, oldValue);
}, function () {
return target.value;
});
}
function hasProxy() {
return !!window.Proxy;
}
function ref(target) {
return hasProxy() ? ref$1(target) : {
value: target
};
}
function computed(fun) {
return hasProxy() ? computed$1(fun) : {
value: fun()
};
}
function watch(target, fun) {
return hasProxy() ? watch$1(target, fun) : function () {
return {};
};
}
var Options = /** @class */
function () {
function Options2(initOptions2) {
this.dsn = "";
this.appName = "";
this.appCode = "";
this.appVersion = "";
this.userUuid = "";
this.sdkUserUuid = "";
this.debug = false;
this.pv = {
core: false
// 页面跳转-是否自动发送页面跳转相关数据
};
this.performance = {
core: false,
// 性能数据-是否采集静态资源、接口的相关数据
firstResource: false,
// 性能数据-是否采集首次进入页面的数据(ps: tcp连接耗时,HTML加载完成时间,首次可交互时间)
server: false
// 接口请求-是否采集接口请求(成功的才会采集)
};
this.error = {
core: false,
// 是否采集异常数据(ps: 资源引入错误,promise错误,控制台输出错误)
server: false
// 接口请求-是否采集报错接口数据
};
this.event = {
core: false
// 页面点击-是否采集点击事件
};
this.recordScreen = true;
this.ext = {};
this.tracesSampleRate = 1;
this.cacheMaxLength = 5;
this.cacheWatingTime = 5e3;
this.ignoreErrors = [];
this.ignoreRequest = [];
this.scopeError = false;
this.localization = false;
this.sendTypeByXmlBody = false;
this.beforePushEventList = [];
this.beforeSendData = [];
this.afterSendData = [];
this.localizationOverFlow = function () {};
var _options = this.transitionOptions(initOptions2);
_options.ignoreRequest.push(new RegExp(_options.dsn));
deepAssign(this, _options);
}
Options2.prototype.transitionOptions = function (options2) {
var _options = deepAssign({}, this, options2);
var beforePushEventList = options2.beforePushEventList,
beforeSendData = options2.beforeSendData,
afterSendData = options2.afterSendData;
var pv = _options.pv,
performance = _options.performance,
error = _options.error,
event = _options.event;
if (typeof pv === "boolean") {
_options.pv = {
core: pv
};
}
if (typeof performance === "boolean") {
_options.performance = {
core: performance,
firstResource: performance,
server: performance
};
}
if (typeof error === "boolean") {
_options.error = {
core: error,
server: error
};
}
if (typeof event === "boolean") {
_options.event = {
core: event
};
}
if (beforePushEventList) {
_options.beforePushEventList = [beforePushEventList];
}
if (beforeSendData) {
_options.beforeSendData = [beforeSendData];
}
if (afterSendData) {
_options.afterSendData = [afterSendData];
}
return _options;
};
return Options2;
}();
function _validateInitOption(options2) {
var dsn = options2.dsn,
appName = options2.appName,
appCode = options2.appCode,
appVersion = options2.appVersion,
userUuid = options2.userUuid,
debug = options2.debug,
recordScreen = options2.recordScreen,
pv = options2.pv,
performance = options2.performance,
error = options2.error,
event = options2.event,
ext = options2.ext,
tracesSampleRate = options2.tracesSampleRate,
cacheMaxLength = options2.cacheMaxLength,
cacheWatingTime = options2.cacheWatingTime,
ignoreErrors = options2.ignoreErrors,
ignoreRequest = options2.ignoreRequest,
scopeError = options2.scopeError,
localization = options2.localization,
sendTypeByXmlBody = options2.sendTypeByXmlBody,
beforePushEventList = options2.beforePushEventList,
beforeSendData = options2.beforeSendData,
isParseDataCode = options2.isParseDataCode,
parseDataOption = options2.parseDataOption;
var validateFunList = [];
if (pv && typeof pv === "object") {
validateFunList.push(validateOption(pv.core, "pv.core", "boolean"));
} else {
validateFunList.push(validateOption(pv, "pv", "boolean"));
}
if (performance && typeof performance === "object") {
validateFunList.push(validateOption(performance.core, "performance.core", "boolean"), validateOption(performance.firstResource, "performance.firstResource", "boolean"), validateOption(performance.server, "performance.server", "boolean"));
} else {
validateFunList.push(validateOption(performance, "performance", "boolean"));
}
if (error && typeof error === "object") {
validateFunList.push(validateOption(error.core, "error.core", "boolean"), validateOption(error.server, "error.server", "boolean"));
} else {
validateFunList.push(validateOption(error, "error", "boolean"));
}
if (event && typeof event === "object") {
validateFunList.push(validateOption(event.core, "event.core", "boolean"));
} else {
validateFunList.push(validateOption(event, "event", "boolean"));
}
var validateList = [validateOption(dsn, "dsn", "string"), validateOption(appName, "appName", "string"), validateOption(appCode, "appCode", "string"), validateOption(appVersion, "appVersion", "string"), validateOption(userUuid, "userUuid", "string"), validateOption(debug, "debug", "boolean"), validateOption(recordScreen, "recordScreen", "boolean"), validateOption(ext, "ext", "object"), validateOption(tracesSampleRate, "tracesSampleRate", "number"), validateOption(cacheMaxLength, "cacheMaxLength", "number"), validateOption(cacheWatingTime, "cacheWatingTime", "number"), validateOption(ignoreErrors, "ignoreErrors", "array"), validateOptionArray(ignoreErrors, "ignoreErrors", ["string", "regexp"]), validateOption(ignoreRequest, "ignoreRequest", "array"), validateOptionArray(ignoreRequest, "ignoreRequest", ["string", "regexp"]), validateOption(scopeError, "scopeError", "boolean"), validateOption(localization, "localization", "boolean"), validateOption(sendTypeByXmlBody, "sendTypeByXmlBody", "boolean"),
// validateOption(whiteScreen, 'whiteScreen', 'boolean'),
validateOption(beforePushEventList, "beforePushEventList", "function"), validateOption(beforeSendData, "beforeSendData", "function"), validateOption(isParseDataCode, "isParseDataCode", "boolean"), validateOption(parseDataOption, "parseDataOption", "object")];
return validateList.every(function (res) {
return !!res;
});
}
function _validateMustFill(options2) {
var validateList = [validateOptionMustFill(options2.appName, "appName"), validateOptionMustFill(options2.dsn, "dsn")];
return validateList.every(function (res) {
return !!res;
});
}
function validateOptionMustFill(target, targetName) {
if (isEmpty(target)) {
logError("\u3010".concat(targetName, "\u3011\u53C2\u6570\u5FC5\u586B"));
return false;
}
return true;
}
function validateOption(target, targetName, expectType) {
if (!target || typeofAny(target) === expectType) return true;
logError("TypeError:\u3010".concat(targetName, "\u3011\u671F\u671B\u4F20\u5165").concat(expectType, "\u7C7B\u578B\uFF0C\u76EE\u524D\u662F").concat(typeofAny(target), "\u7C7B\u578B"));
return false;
}
function validateOptionArray(target, targetName, expectTypes) {
if (!target) return true;
var pass = true;
target.forEach(function (item) {
if (!expectTypes.includes(typeofAny(item))) {
logError("TypeError:\u3010".concat(targetName, "\u3011\u6570\u7EC4\u5185\u7684\u503C\u671F\u671B\u4F20\u5165").concat(expectTypes.join("|"), "\u7C7B\u578B\uFF0C\u76EE\u524D\u503C").concat(item, "\u662F").concat(typeofAny(item), "\u7C7B\u578B"));
pass = false;
}
});
return pass;
}
exports.options = void 0;
function initOptions(initOptions2) {
if (!_validateMustFill(initOptions2) || !_validateInitOption(initOptions2)) return false;
exports.options = ref(new Options(initOptions2));
_support.options = exports.options;
return true;
}
function debug() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (exports.options.value.debug) console.log.apply(console, __spreadArray(["@papa-sports: "], args, false));
}
function logError() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
console.error.apply(console, __spreadArray(["@papa-sports: "], args, false));
}
function on$1(target, eventName, handler, opitons) {
if (opitons === void 0) {
opitons = false;
}
target.addEventListener(eventName, handler, opitons);
}
function replaceAop(source, name, replacement, isForced) {
if (isForced === void 0) {
isForced = false;
}
if (source === void 0) return;
if (name in source || isForced) {
var original = source[name];
var wrapped = replacement(original);
if (isFunction(wrapped)) {
source[name] = wrapped;
}
}
}
function normalizeObj(source) {
Object.keys(source).forEach(function (p) {
var v = source[p];
if (isNumber(v)) {
source[p] = v === 0 ? void 0 : parseFloat(v.toFixed(2));
}
});
return source;
}
function getLocationHref() {
if (typeof document === "undefined" || document.location == null) return "";
return document.location.href;
}
function getTimestamp() {
return Date.now();
}
function throttle$1(func, wait, runFirst) {
if (runFirst === void 0) {
runFirst = false;
}
var timer = null;
var lastArgs;
return function () {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
lastArgs = args;
if (timer === null) {
if (runFirst) {
func.apply(this, lastArgs);
}
timer = setTimeout(function () {
timer = null;
func.apply(_this, lastArgs);
}, wait);
}
};
}
function debounce(func, wait, runFirst) {
if (runFirst === void 0) {
runFirst = false;
}
var timer = null;
return function () {
var _this = this;
var arg = [];
for (var _i = 0; _i < arguments.length; _i++) {
arg[_i] = arguments[_i];
}
if (runFirst) {
func.call.apply(func, __spreadArray([this], arg, false));
runFirst = false;
}
if (timer) clearTimeout(timer);
timer = setTimeout(function () {
func.call.apply(func, __spreadArray([_this], arg, false));
}, wait);
};
}
function groupArray(arr) {
var keys = [];
for (var _i = 1; _i < arguments.length; _i++) {
keys[_i - 1] = arguments[_i];
}
var groups = /* @__PURE__ */new Map();
var _loop_1 = function (obj2) {
var key = keys.filter(function (k) {
return obj2[k];
}).map(function (k) {
return obj2[k];
}).join(":");
if (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key).push(obj2);
};
for (var _a = 0, arr_1 = arr; _a < arr_1.length; _a++) {
var obj = arr_1[_a];
_loop_1(obj);
}
return Array.from(groups.values());
}
function deepAssign(target) {
var sources = [];
for (var _i = 1; _i < arguments.length; _i++) {
sources[_i - 1] = arguments[_i];
}
sources.forEach(function (source) {
for (var key in source) {
if (source[key] !== null && isRegExp$1(source[key])) {
target[key] = source[key];
} else if (source[key] !== null && typeof source[key] === "object") {
target[key] = deepAssign(target[key] || (isArray(source[key]) ? [] : {}), source[key]);
} else {
target[key] = source[key];
}
}
});
return target;
}
function validateMethods(methodsName) {
if (!isInit()) {
logError("".concat(methodsName, " \u9700\u8981\u5728SDK\u521D\u59CB\u5316\u4E4B\u540E\u4F7F\u7528"));
return false;
}
return true;
}
function typeofAny(target) {
return Object.prototype.toString.call(target).slice(8, -1).toLowerCase();
}
function isValidKey(key, object) {
return key in object;
}
function randomBoolean(randow) {
return Math.random() <= randow;
}
function pad(num, len, placeholder) {
if (placeholder === void 0) {
placeholder = "0";
}
var str = String(num);
if (str.length < len) {
var result = str;
for (var i = 0; i < len - str.length; i += 1) {
result = placeholder + result;
}
return result;
}
return str;
}
function getBaseUrl(url) {
return url.split("?")[0];
}
function uuid() {
var date = /* @__PURE__ */new Date();
var hexDate = parseInt("".concat(date.getFullYear()).concat(pad(date.getMonth() + 1, 2)).concat(pad(date.getDate(), 2)), 10).toString(16);
var hexTime = parseInt("".concat(pad(date.getHours(), 2)).concat(pad(date.getMinutes(), 2)).concat(pad(date.getSeconds(), 2)).concat(pad(date.getMilliseconds(), 3)), 10).toString(16);
var guid = hexDate + hexTime.length + hexTime;
while (guid.length < 32) {
guid += Math.floor(Math.random() * 16).toString(16);
}
return "".concat(guid.slice(0, 8), "-").concat(guid.slice(8, 16), "-").concat(guid.slice(16));
}
function getCookieByName(name) {
var result = document.cookie.match(new RegExp("".concat(name, "=([^;]+)(;|$)")));
return result ? result[1] : void 0;
}
function sendByBeacon(url, data) {
return navigator.sendBeacon(url, JSON.stringify(data));
}
var sendReaconImageList = [];
function sendByImage(url, data) {
return new Promise(function (resolve) {
var beacon = new Image();
beacon.src = "".concat(url, "?v=").concat(encodeURIComponent(JSON.stringify(data)));
sendReaconImageList.push(beacon);
beacon.onload = function () {
resolve();
};
beacon.onerror = function () {
resolve();
};
});
}
function sendByXML(url, data) {
return new Promise(function (resolve) {
var xhr = new XMLHttpRequest();
xhr.open("post", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
resolve();
}
};
});
}
function executeFunctions(funList, through, args) {
if (funList.length === 0) return args;
var result = void 0;
for (var i = 0; i < funList.length; i++) {
var func = funList[i];
if (i === 0 || through) {
result = func(args);
} else {
result = func(result);
}
}
return result;
}
function unKnowToArray(target) {
return isArray(target) ? target : [target];
}
var arrayMap = Array.prototype.map || function polyfillMap(fn) {
var result = [];
for (var i = 0; i < this.length; i += 1) {
result.push(fn(this[i], i, this));
}
return result;
};
function map(arr, fn) {
return arrayMap.call(arr, fn);
}
var arrayFilter = Array.prototype.filter || function filterPolyfill(fn) {
var result = [];
for (var i = 0; i < this.length; i += 1) {
if (fn(this[i], i, this)) {
result.push(this[i]);
}
}
return result;
};
function filter(arr, fn) {
return arrayFilter.call(arr, fn);
}
var nextTime = window.requestIdleCallback || window.requestAnimationFrame || function (callback) {
return setTimeout(callback, 17);
};
function isObjectOverSizeLimit(object, limitInKB) {
var serializedObject = JSON.stringify(object);
var sizeInBytes = new TextEncoder().encode(serializedObject).length;
var sizeInKB = sizeInBytes / 1024;
return sizeInKB > limitInKB;
}
function parseGetParams(url) {
var params = {};
var query = url.split("?")[1];
if (query) {
var pairs = query.split("&");
for (var _i = 0, pairs_1 = pairs; _i < pairs_1.length; _i++) {
var pair = pairs_1[_i];
var _a = pair.split("="),
key = _a[0],
value = _a[1];
params[decodeURIComponent(key)] = decodeURIComponent(value);
}
}
return params;
}
function deepCopy(target, map2) {
if (map2 === void 0) {
map2 = /* @__PURE__ */new Map();
}
if (target !== null && typeof target === "object") {
var res_1 = map2.get(target);
if (res_1) return res_1;
if (target instanceof Array) {
res_1 = [];
map2.set(target, res_1);
target.forEach(function (item, index) {
res_1[index] = deepCopy(item, map2);
});
} else {
res_1 = {};
map2.set(target, res_1);
Object.keys(target).forEach(function (key) {
if (isValidKey(key, target)) {
res_1[key] = deepCopy(target[key], map2);
}
});
}
return res_1;
}
return target;
}
var version$1 = "2.0.13";
var DEVICE_KEY = "_webtracing_device_id";
var SESSION_KEY = "_webtracing_session_id";
var SURVIVIE_MILLI_SECONDS = 18e5;
var SDK_LOCAL_KEY = "_webtracing_localization_key";
var SDK_VERSION = version$1;
var EVENTTYPES;
(function (EVENTTYPES2) {
EVENTTYPES2["ERROR"] = "error";
EVENTTYPES2["CONSOLEERROR"] = "consoleError";
EVENTTYPES2["UNHANDLEDREJECTION"] = "unhandledrejection";
EVENTTYPES2["CLICK"] = "click";
EVENTTYPES2["LOAD"] = "load";
EVENTTYPES2["BEFOREUNLOAD"] = "beforeunload";
EVENTTYPES2["FETCH"] = "fetch";
EVENTTYPES2["XHROPEN"] = "xhr-open";
EVENTTYPES2["XHRSEND"] = "xhr-send";
EVENTTYPES2["HASHCHANGE"] = "hashchange";
EVENTTYPES2["HISTORYPUSHSTATE"] = "history-pushState";
EVENTTYPES2["HISTORYREPLACESTATE"] = "history-replaceState";
EVENTTYPES2["POPSTATE"] = "popstate";
EVENTTYPES2["READYSTATECHANGE"] = "readystatechange";
EVENTTYPES2["ONLINE"] = "online";
EVENTTYPES2["OFFLINE"] = "offline";
})(EVENTTYPES || (EVENTTYPES = {}));
var SEDNEVENTTYPES;
(function (SEDNEVENTTYPES2) {
SEDNEVENTTYPES2["PV"] = "pv";
SEDNEVENTTYPES2["PVDURATION"] = "pv-duration";
SEDNEVENTTYPES2["ERROR"] = "error";
SEDNEVENTTYPES2["PERFORMANCE"] = "performance";
SEDNEVENTTYPES2["CLICK"] = "click";
SEDNEVENTTYPES2["DWELL"] = "dwell";
SEDNEVENTTYPES2["CUSTOM"] = "custom";
SEDNEVENTTYPES2["INTERSECTION"] = "intersection";
})(SEDNEVENTTYPES || (SEDNEVENTTYPES = {}));
exports.SENDID = void 0;
(function (SENDID2) {
SENDID2["PAGE"] = "page";
SENDID2["RESOURCE"] = "resource";
SENDID2["SERVER"] = "server";
SENDID2["CODE"] = "code";
SENDID2["REJECT"] = "reject";
SENDID2["CONSOLEERROR"] = "console.error";
})(exports.SENDID || (exports.SENDID = {}));
var WEBPAGELOAD = {
0: "navigate",
// 网页通过点击链接,地址栏输入,表单提交,脚本操作等方式加载
1: "reload",
// 网页通过“重新加载”按钮或者location.reload()方法加载
2: "back_forward",
// 网页通过“前进”或“后退”按钮加载
255: "reserved"
// 任何其他来源的加载
};
var EventBus = /** @class */
function () {
function EventBus2() {
this.handlers = {};
}
EventBus2.prototype.addEvent = function (handler) {
var _a;
!this.handlers[handler.type] && (this.handlers[handler.type] = []);
var funIndex = this._getCallbackIndex(handler);
if (funIndex === -1) {
(_a = this.handlers[handler.type]) === null || _a === void 0 ? void 0 : _a.push(handler.callback);
}
};
EventBus2.prototype.delEvent = function (handler) {
var _a;
var funIndex = this._getCallbackIndex(handler);
if (funIndex !== -1) {
(_a = this.handlers[handler.type]) === null || _a === void 0 ? void 0 : _a.splice(funIndex, 1);
}
};
EventBus2.prototype.changeEvent = function (handler, newCallback) {
var _a;
var funIndex = this._getCallbackIndex(handler);
if (funIndex !== -1) {
(_a = this.handlers[handler.type]) === null || _a === void 0 ? void 0 : _a.splice(funIndex, 1, newCallback);
}
};
EventBus2.prototype.getEvent = function (type) {
return this.handlers[type] || [];
};
EventBus2.prototype.runEvent = function (type) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var allEvent = this.getEvent(type);
allEvent.forEach(function (fun) {
fun.apply(void 0, args);
});
};
EventBus2.prototype._getCallbackIndex = function (handler) {
if (this.handlers[handler.type]) {
var callbackList = this.handlers[handler.type];
if (callbackList) {
return callbackList.findIndex(function (fun) {
return fun === handler.callback;
});
} else {
return -1;
}
} else {
return -1;
}
};
return EventBus2;
}();
var eventBus = _support.eventBus || (_support.eventBus = new EventBus());
function initReplace() {
for (var key in EVENTTYPES) {
if (isValidKey(key, EVENTTYPES)) {
replace(key);
}
}
}
function replace(type) {
if (!isValidKey(type, EVENTTYPES)) return;
var value = EVENTTYPES[type];
switch (value) {
case EVENTTYPES.ERROR:
listenError(EVENTTYPES.ERROR);
break;
case EVENTTYPES.UNHANDLEDREJECTION:
listenUnhandledrejection(EVENTTYPES.UNHANDLEDREJECTION);
break;
case EVENTTYPES.CONSOLEERROR:
replaceConsoleError(EVENTTYPES.CONSOLEERROR);
break;
case EVENTTYPES.CLICK:
listenClick(EVENTTYPES.CLICK);
break;
case EVENTTYPES.LOAD:
listenLoad(EVENTTYPES.LOAD);
break;
case EVENTTYPES.BEFOREUNLOAD:
listenBeforeunload(EVENTTYPES.BEFOREUNLOAD);
break;
case EVENTTYPES.XHROPEN:
replaceXHROpen(EVENTTYPES.XHROPEN);
break;
case EVENTTYPES.XHRSEND:
replaceXHRSend(EVENTTYPES.XHRSEND);
break;
case EVENTTYPES.FETCH:
replaceFetch(EVENTTYPES.FETCH);
break;
case EVENTTYPES.HASHCHANGE:
listenHashchange(EVENTTYPES.HASHCHANGE);
break;
case EVENTTYPES.HISTORYPUSHSTATE:
replaceHistoryPushState(EVENTTYPES.HISTORYPUSHSTATE);
break;
case EVENTTYPES.HISTORYREPLACESTATE:
replaceHistoryReplaceState(EVENTTYPES.HISTORYREPLACESTATE);
break;
case EVENTTYPES.POPSTATE:
listenPopState(EVENTTYPES.POPSTATE);
break;
case EVENTTYPES.OFFLINE:
listenOffline(EVENTTYPES.OFFLINE);
break;
case EVENTTYPES.ONLINE:
listenOnline(EVENTTYPES.ONLINE);
break;
}
}
function listenError(type) {
on$1(_global, "error", function (e) {
eventBus.runEvent(type, e);
}, true);
}
function listenUnhandledrejection(type) {
on$1(_global, "unhandledrejection", function (ev) {
eventBus.runEvent(type, ev);
});
}
function replaceConsoleError(type) {
replaceAop(console, "error", function (originalError) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!(args[0] && args[0].slice && args[0].slice(0, 12) === "@papa-sports")) {
eventBus.runEvent(type, args);
}
originalError.apply(this, args);
};
});
}
function listenClick(type) {
if (!("document" in _global)) return;
var clickThrottle = throttle$1(eventBus.runEvent, 100, true);
on$1(_global.document, "click", function (e) {
clickThrottle.call(eventBus, type, e);
}, true);
}
function listenLoad(type) {
on$1(_global, "load", function (e) {
eventBus.runEvent(type, e);
}, true);
}
function listenBeforeunload(type) {
on$1(_global, "beforeunload", function (e) {
eventBus.runEvent(type, e);
}, false);
}
function replaceXHROpen(type) {
if (!("XMLHttpRequest" in _global)) return;
replaceAop(XMLHttpRequest.prototype, "open", function (originalOpen) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
eventBus.runEvent.apply(eventBus, __spreadArray([type], args, false));
originalOpen.apply(this, args);
};
});
}
function replaceXHRSend(type) {
if (!("XMLHttpRequest" in _global)) return;
replaceAop(XMLHttpRequest.prototype, "send", function (originalSend) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
eventBus.runEvent.apply(eventBus, __spreadArray([type, this], args, false));
originalSend.apply(this, args);
};
});
}
function replaceFetch(type) {
if (!("fetch" in _global)) return;
replaceAop(_global, "fetch", function (originalFetch) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var fetchStart = getTimestamp();
var traceObj = {};
return originalFetch.apply(_global, args).then(function (res) {
eventBus.runEvent(type, args[0], args[1], res, fetchStart, traceObj);
return res;
});
};
});
}
function listenHashchange(type) {
on$1(_global, "hashchange", function (e) {
eventBus.runEvent(type, e);
});
}
function replaceHistoryReplaceState(type) {
if (!("history" in _global)) return;
if (!("pushState" in _global.history)) return;
replaceAop(_global.history, "replaceState", function (originalSend) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
eventBus.runEvent.apply(eventBus, __spreadArray([type], args, false));
originalSend.apply(this, args);
};
});
}
function replaceHistoryPushState(type) {
if (!("history" in _global)) return;
if (!("pushState" in _global.history)) return;
replaceAop(_global.history, "pushState", function (originalSend) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
eventBus.runEvent.apply(eventBus, __spreadArray([type], args, false));
originalSend.apply(this, args);
};
});
}
function listenPopState(type) {
on$1(_global, "popstate", function (e) {
eventBus.runEvent(type, e);
});
}
function listenOffline(type) {
on$1(_global, "offline", function (e) {
eventBus.runEvent(type, e);
}, true);
}
function listenOnline(type) {
on$1(_global, "online", function (e) {
eventBus.runEvent(type, e);
}, true);
}
var e = function () {
return e = Object.assign || function (e2) {
for (var n2, t2 = 1, r2 = arguments.length; t2 < r2; t2++) for (var o_1 in n2 = arguments[t2]) Object.prototype.hasOwnProperty.call(n2, o_1) && (e2[o_1] = n2[o_1]);
return e2;
}, e.apply(this, arguments);
};
function n(e2, n2, t2, r2) {
return new (t2 || (t2 = Promise))(function (o2, a2) {
function i2(e3) {
try {
u2(r2.next(e3));
} catch (n3) {
a2(n3);
}
}
function c2(e3) {
try {
u2(r2.throw(e3));
} catch (n3) {
a2(n3);
}
}
function u2(e3) {
var n3;
e3.done ? o2(e3.value) : (n3 = e3.value, n3 instanceof t2 ? n3 : new t2(function (e4) {
e4(n3);
})).then(i2, c2);
}
u2((r2 = r2.apply(e2, n2 || [])).next());
});
}
function t(e2, n2) {
var t2,
r2,
o2,
a2,
i2 = {
label: 0,
sent: function () {
if (1 & o2[0]) throw o2[1];
return o2[1];
},
trys: [],
ops: []
};
return a2 = {
next: c2(0),
throw: c2(1),
return: c2(2)
}, "function" == typeof Symbol && (a2[Symbol.iterator] = function () {
return this;
}), a2;
function c2(c3) {
return function (u2) {
return function (c4) {
if (t2) throw new TypeError("Generator is already executing.");
for (; a2 && (a2 = 0, c4[0] && (i2 = 0)), i2;) try {
if (t2 = 1, r2 && (o2 = 2 & c4[0] ? r2.return : c4[0] ? r2.throw || ((o2 = r2.return) && o2.call(r2), 0) : r2.next) && !(o2 = o2.call(r2, c4[1])).done) return o2;
switch (r2 = 0, o2 && (c4 = [2 & c4[0], o2.value]), c4[0]) {
case 0:
case 1:
o2 = c4;
break;
case 4:
return i2.label++, {
value: c4[1],
done: false
};
case 5:
i2.label++, r2 = c4[1], c4 = [0];
continue;
case 7:
;
c4 = i2.ops.pop(), i2.trys.pop();
continue;
default:
if (!(o2 = i2.trys, (o2 = o2.length > 0 && o2[o2.length - 1]) || 6 !== c4[0] && 2 !== c4[0])) {
i2 = 0;
continue;
}
if (3 === c4[0] && (!o2 || c4[1] > o2[0] && c4[1] < o2[3])) {
i2.label = c4[1];
break;
}
if (6 === c4[0] && i2.label < o2[1]) {
;
i2.label = o2[1], o2 = c4;
break;
}
if (o2 && i2.label < o2[2]) {
;
i2.label = o2[2], i2.ops.push(c4);
break;
}
o2[2] && i2.ops.pop(), i2.trys.pop();
continue;
}
c4 = n2.call(e2, i2);
} catch (u3) {
c4 = [6, u3], r2 = 0;
} finally {
t2 = o2 = 0;
}
if (5 & c4[0]) throw c4[1];
return {
value: c4[0] ? c4[1] : void 0,
done: true
};
}([c3, u2]);
};
}
}
function r(e2, n2, t2) {
if (t2 || 2 === arguments.length) for (var r2, o2 = 0, a2 = n2.length; o2 < a2; o2++) !r2 && o2 in n2 || (r2 || (r2 = Array.prototype.slice.call(n2, 0, o2)), r2[o2] = n2[o2]);
return e2.concat(r2 || Array.prototype.slice.call(n2));
}
function o(e2, n2) {
return new Promise(function (t2) {
return setTimeout(t2, e2, n2);
});
}
function a(e2) {
return !!e2 && "function" == typeof e2.then;
}
function i$1(e2, n2) {
try {
var t_1 = e2();
a(t_1) ? t_1.then(function (e3) {
return n2(true, e3);
}, function (e3) {
return n2(false, e3);
}) : n2(true, t_1);
} catch (r2) {
n2(false, r2);
}
}
function c(e2, r2, a2) {
return void 0 === a2 && (a2 = 16), n(this, void 0, void 0, function () {
var n2, i2, c2;
return t(this, function (t2) {
switch (t2.label) {
case 0:
n2 = Date.now(), i2 = 0, t2.label = 1;
case 1:
return i2 < e2.length ? (r2(e2[i2], i2), (c2 = Date.now()) >= n2 + a2 ? (n2 = c2, [4, o(0)]) : [3, 3]) : [3, 4];
case 2:
t2.sent(), t2.label = 3;
case 3:
return ++i2, [3, 1];
case 4:
return [2];
}
});
});
}
function u(e2) {
e2.then(void 0, function () {});
}
function l(e2, n2) {
e2 = [e2[0] >>> 16, 65535 & e2[0], e2[1] >>> 16, 65535 & e2[1]], n2 = [n2[0] >>> 16, 65535 & n2[0], n2[1] >>> 16, 65535 & n2[1]];
var t2 = [0, 0, 0, 0];
return t2[3] += e2[3] + n2[3], t2[2] += t2[3] >>> 16, t2[3] &= 65535, t2[2] += e2[2] + n2[2], t2[1] += t2[2] >>> 16, t2[2] &= 65535, t2[1] += e2[1] + n2[1], t2[0] += t2[1] >>> 16, t2[1] &= 65535, t2[0] += e2[0] + n2[0], t2[0] &= 65535, [t2[0] << 16 | t2[1], t2[2] << 16 | t2[3]];
}
function s(e2, n2) {
e2 = [e2[0] >>> 16, 65535 & e2[0], e2[1] >>> 16, 65535 & e2[1]], n2 = [n2[0] >>> 16, 65535 & n2[0], n2[1] >>> 16, 65535 & n2[1]];
var t2 = [0, 0, 0, 0];
return t2[3] += e2[3] * n2[3], t2[2] += t2[3] >>> 16, t2[3] &= 65535, t2[2] += e2[2] * n2[3], t2[1] += t2[2] >>> 16, t2[2] &= 65535, t2[2] += e2[3] * n2[2], t2[1] += t2[2] >>> 16, t2[2] &= 65535, t2[1] += e2[1] * n2[3], t2[0] += t2[1] >>> 16, t2[1] &= 65535, t2[1] += e2[2] * n2[2], t2[0] += t2[1] >>> 16, t2[1] &= 65535, t2[1] += e2[3] * n2[1], t2[0] += t2[1] >>> 16, t2[1] &= 65535, t2[0] += e2[0] * n2[3] + e2[1] * n2[2] + e2[2] * n2[1] + e2[3] * n2[0], t2[0] &= 65535, [t2[0] << 16 | t2[1], t2[2] << 16 | t2[3]];
}
function d(e2, n2) {
return 32 === (n2 %= 64) ? [e2[1], e2[0]] : n2 < 32 ? [e2[0] << n2 | e2[1] >>> 32 - n2, e2[1] << n2 | e2[0] >>> 32 - n2] : (n2 -= 32, [e2[1] << n2 | e2[0] >>> 32 - n2, e2[0] << n2 | e2[1] >>> 32 - n2]);
}
function m(e2, n2) {
return 0 === (n2 %= 64) ? e2 : n2 < 32 ? [e2[0] << n2 | e2[1] >>> 32 - n2, e2[1] << n2] : [e2[1] << n2 - 32, 0];
}
function f(e2, n2) {
return [e2[0] ^ n2[0], e2[1] ^ n2[1]];
}
function v(e2) {
return e2 = f(e2, [0, e2[0] >>> 1]), e2 = f(e2 = s(e2, [4283543511, 3981806797]), [0, e2[0] >>> 1]), e2 = f(e2 = s(e2, [3301882366, 444984403]), [0, e2[0] >>> 1]);
}
function h(e2, n2) {
n2 = n2 || 0;
var t2,
r2 = (e2 = e2 || "").length % 16,
o2 = e2.length - r2,
a2 = [0, n2],
i2 = [0, n2],
c2 = [0, 0],
u2 = [0, 0],
h2 = [2277735313, 289559509],
b2 = [1291169091, 658871167];
for (t2 = 0; t2 < o2; t2 += 16) c2 = [255 & e2.charCodeAt(t2 + 4) | (255 & e2.charCodeAt(t2 + 5)) << 8 | (255 & e2.charCodeAt(t2 + 6)) << 16 | (255 & e2.charCodeAt(t2 + 7)) << 24, 255 & e2.charCodeAt(t2) | (255 & e2.charCodeAt(t2 + 1)) << 8 | (255 & e2.charCodeAt(t2 + 2)) << 16 | (255 & e2.charCodeAt(t2 + 3)) << 24], u2 = [255 & e2.charCodeAt(t2 + 12) | (255 & e2.charCodeAt(t2 + 13)) << 8 | (255 & e2.charCodeAt(t2 + 14)) << 16 | (255 & e2.charCodeAt(t2 + 15)) << 24, 255 & e2.charCodeAt(t2 + 8) | (255 & e2.charCodeAt(t2 + 9)) << 8 | (255 & e2.charCodeAt(t2 + 10)) << 16 | (255 & e2.charCodeAt(t2 + 11)) << 24], c2 = d(c2 = s(c2, h2), 31), a2 = l(a2 = d(a2 = f(a2, c2 = s(c2, b2)), 27), i2), a2 = l(s(a2, [0, 5]), [0, 1390208809]), u2 = d(u2 = s(u2, b2), 33), i2 = l(i2 = d(i2 = f(i2, u2 = s(u2, h2)), 31), a2), i2 = l(s(i2, [0, 5]), [0, 944331445]);
switch (c2 = [0, 0], u2 = [0, 0], r2) {
case 15:
u2 = f(u2, m([0, e2.charCodeAt(t2 + 14)], 48));
case 14:
u2 = f(u2, m([0, e2.charCodeAt(t2 + 13)], 40));
case 13:
u2 = f(u2, m([0, e2.charCodeAt(t2 + 12)], 32));
case 12:
u2 = f(u2, m([0, e2.charCodeAt(t2 + 11)], 24));
case 11:
u2 = f(u2, m([0, e2.charCodeAt(t2 + 10)], 16));
case 10:
u2 = f(u2, m([0, e2.charCodeAt(t2 + 9)], 8));
case 9:
u2 = s(u2 = f(u2, [0, e2.charCodeAt(t2 + 8)]), b2), i2 = f(i2, u2 = s(u2 = d(u2, 33), h2));
case 8:
c2 = f(c2, m([0, e2.charCodeAt(t2 + 7)], 56));
case 7:
c2 = f(c2, m([0, e2.charCodeAt(t2 + 6)], 48));
case 6:
c2 = f(c2, m([0, e2.charCodeAt(t2 + 5)], 40));
case 5:
c2 = f(c2, m([0, e2.charCodeAt(t2 + 4)], 32));
case 4:
c2 = f(c2, m([0, e2.charCodeAt(t2 + 3)], 24));
case 3:
c2 = f(c2, m([0, e2.charCodeAt(t2 + 2)], 16));
case 2:
c2 = f(c2, m([0, e2.charCodeAt(t2 + 1)], 8));
case 1:
c2 = s(c2 = f(c2, [0, e2.charCodeAt(t2)]), h2), a2 = f(a2, c2 = s(c2 = d(c2, 31), b2));
}
return a2 = l(a2 = f(a2, [0, e2.length]), i2 = f(i2, [0, e2.length])), i2 = l(i2, a2), a2 = l(a2 = v(a2), i2 = v(i2)), i2 = l(i2, a2), ("00000000" + (a2[0] >>> 0).toString(16)).slice(-8) + ("00000000" + (a2[1] >>> 0).toString(16)).slice(-8) + ("00000000" + (i2[0] >>> 0).toString(16)).slice(-8) + ("00000000" + (i2[1] >>> 0).toString(16)).slice(-8);
}
function b(e2) {
return parseInt(e2);
}
function p(e2) {
return parseFloat(e2);
}
function y(e2, n2) {
return "number" == typeof e2 && isNaN(e2) ? n2 : e2;
}
function g(e2) {
return e2.reduce(function (e3, n2) {
return e3 + (n2 ? 1 : 0);
}, 0);
}
function w(e2, n2) {
if (void 0 === n2 && (n2 = 1), Math.abs(n2) >= 1) return Math.round(e2 / n2) * n2;
var t2 = 1 / n2;
return Math.round(e2 * t2) / t2;
}
function L(e2) {
return e2 && "object" == typeof e2 && "message" in e2 ? e2 : {
message: e2
};
}
function k(e2) {
return "function" != typeof e2;
}
function V(e2, r2, a2) {
var l2 = Object.keys(e2).filter(function (e3) {
return !function (e4, n2) {
for (var t_2 = 0, r_1 = e4.length; t_2 < r_1; ++t_2) if (e4[t_2] === n2) return true;
return false;
}(a2, e3);
}),
s2 = Array(l2.length);
return c(l2, function (n2, t2) {
s2[t2] = function (e3, n3) {
var t3 = new Promise(function (t4) {
var r3 = Date.now();
i$1(e3.bind(null, n3), function () {
for (var e4 = [], n4 = 0; n4 < arguments.length; n4++) e4[n4] = arguments[n4];
var o2 = Date.now() - r3;
if (!e4[0]) return t4(function () {
return {
error: L(e4[1]),
duration: o2
};
});
var a3 = e4[1];
if (k(a3)) return t4(function () {
return {
value: a3,
duration: o2
};
});
t4(function () {
return new Promise(function (e5) {
var n5 = Date.now();
i$1(a3, function () {
for (var t5 = [], r4 = 0; r4 < arguments.length; r4++) t5[r4] = arguments[r4];
var a4 = o2 + Date.now() - n5;
if (!t5[0]) return e5({
error: L(t5[1]),
duration: a4
});
e5({
value: t5[1],
duration: a4
});
});
});
});
});
});
return u(t3), function () {
return t3.then(function (e4) {
return e4();
});
};
}(e2[n2], r2);
}), function () {
return n(this, void 0, void 0, function () {
var e3, n2, r3, a3, i2, d2;
return t(this, function (m2) {
switch (m2.label) {
case 0:
for (e3 = {}, n2 = 0, r3 = l2; n2 < r3.length; n2++) a3 = r3[n2], e3[a3] = void 0;
i2 = Array(l2.length), d2 = function () {
var n3;
return t(this, function (t2) {
switch (t2.label) {
case 0:
return n3 = true, [4, c(l2, function (t3, r4) {
if (!i2[r4]) if (s2[r4]) {
var o_2 = s2[r4]().then(function (n4) {
return e3[t3] = n4;
});
u(o_2), i2[r4] = o_2;
} else n3 = false;
})];
case 1:
return t2.sent(), n3 ? [2, "break"] : [4, o(1)];
case 2:
return t2.sent(), [2];
}
});
}, m2.label = 1;
case 1:
return [5, d2()];
case 2:
if ("break" === m2.sent()) return [3, 4];
m2.label = 3;
case 3:
return [3, 1];
case 4:
return [4, Promise.all(i2)];
case 5:
return m2.sent(), [2, e3];
}
});
});
};
}
function Z() {
var e2 = window,
n2 = navigator;
return g(["MSCSSMatrix" in e2, "msSetImmediate" in e2, "msIndexedDB" in e2, "msMaxTouchPoints" in n2, "msPointerEnabled" in n2]) >= 4;
}
function S() {
var e2 = window,
n2 = navigator;
return g(["msWriteProfilerMark" in e2, "MSStream" in e2, "msLaunchUri" in n2, "msSaveBlob" in n2]) >= 3 && !Z();
}
function X() {
var e2 = window,
n2 = navigator;
return g(["webkitPersistentStorage" in n2, "webkitTemporaryStorage" in n2, 0 === n2.vendor.indexOf("Google"), "webkitResolveLocalFileSystemURL" in e2, "BatteryManager" in e2, "webkitMediaStream" in e2, "webkitSpeechGrammar" in e2]) >= 5;
}
function x() {
var e2 = window,
n2 = navigator;
return g(["ApplePayError" in e2, "CSSPrimitiveValue" in e2, "Counter" in e2, 0 === n2.vendor.indexOf("Apple"), "getStorageUpdates" in n2, "WebKitMediaKeys" in e2]) >= 4;
}
function F() {
var e2 = window;
return g(["safari" in e2, !("DeviceMotionEvent" in e2), !("ongestureend" in e2), !("standalone" in navigator)]) >= 3;
}
function Y() {
var e2,
n2,
t2 = window;
return g(["buildID" in navigator, "MozAppearance" in (null !== (n2 = null === (e2 = document.documentElement) || void 0 === e2 ? void 0 : e2.style) && void 0 !== n2 ? n2 : {}), "onmozfullscreenchange" in t2, "mozInnerScreenX" in t2, "CSSMozDocumentRule" in t2, "CanvasCaptureMediaStream" in t2]) >= 4;
}
function C() {
var e2 = document;
return e2.fullscreenElement || e2.msFullscreenElement || e2.mozFullScreenElement || e2.webkitFullscreenElement || null;
}
function R() {
var e2 = X(),
n2 = Y();
if (!e2 && !n2) return false;
var t2 = window;
return g(["onorientationchange" in t2, "orientation" in t2, e2 && !("SharedWorker" in t2), n2 && /android/i.test(navigator.appVersion)]) >= 2;
}
function G(e2) {
var n2 = new Error(e2);
return n2.name = e2, n2;
}
function M(e2, r2, a2) {
var i2, c2, u2;
return void 0 === a2 && (a2 = 50), n(this, void 0, void 0, function () {
var n2, l2;
return t(this, function (t2) {
switch (t2.label) {
case 0:
n2 = document, t2.label = 1;
case 1:
return n2.body ? [3, 3] : [4, o(a2)];
case 2:
return t2.sent(), [3, 1];
case 3:
l2 = n2.createElement("iframe"), t2.label = 4;
case 4:
return t2.trys.push([4,, 10, 11]), [4, new Promise(function (e3, t3) {
var o2 = false,
a3 = function () {
o2 = true, e3();
};
l2.onload = a3, l2.onerror = function (e4) {
o2 = true, t3(e4);
};
var i3 = l2.style;
i3.setProperty("display", "block", "important"), i3.position = "absolute", i3.top = "0", i3.left = "0", i3.visibility = "hidden", r2 && "srcdoc" in l2 ? l2.srcdoc = r2 : l2.src = "about:blank", n2.body.appendChild(l2);
var c3 = function () {
var e4, n3;
o2 || ("complete" === (null === (n3 = null === (e4 = l2.contentWindow) || void 0 === e4 ? void 0 : e4.document) || void 0 === n3 ? void 0 : n3.readyState) ? a3() : setTimeout(c3, 10));
};
c3();
})];
case 5:
t2.sent(), t2.label = 6;
case 6:
return (null === (c2 = null === (i2 = l2.contentWindow) || void 0 === i2 ? void 0 : i2.document) || void 0 === c2 ? void 0 : c2.body) ? [3, 8] : [4, o(a2)];
case 7:
return t2.sent(), [3, 6];
case 8:
return [4, e2(l2, l2.contentWindow)];
case 9:
return [2, t2.sent()];
case 10:
return null === (u2 = l2.parentNode) || void 0 === u2 || u2.removeChild(l2), [7];
case 11:
return [2];
}
});
});
}
function I(e2) {
for (var n2 = function (e3) {
for (var n3, t3, r3 = "Unexpected syntax '".concat(e3, "'"), o3 = /^\s*([a-z-]*)(.*)$/i.exec(e3), a3 = o3[1] || void 0, i3 = {}, c2 = /([.:#][\w-]+|\[.+?\])/gi, u2 = function (e4, n4) {
i3[e4] = i3[e4] || [], i3[e4].push(n4);
};;) {
var l_1 = c2.exec(o3[2]);
if (!l_1) break;
var s_1 = l_1[0];
switch (s_1[0]) {
case ".":
u2("class", s_1.slice(1));
break;
case "#":
u2("id", s_1.slice(1));
break;
case "[":
var d2 = /^\[([\w-]+)([~|^$*]?=("(.*?)"|([\w-]+)))?(\s+[is])?\]$/.exec(s_1);
if (!d2) throw new Error(r3);
u2(d2[1], null !== (t3 = null !== (n3 = d2[4]) && void 0 !== n3 ? n3 : d2[5]) && void 0 !== t3 ? t3 : "");
break;
default:
throw new Error(r3);
}
}
return [a3, i3];
}(e2), t2 = n2[0], r2 = n2[1], o2 = document.createElement(null != t2 ? t2 : "div"), a2 = 0, i2 = Object.keys(r2); a2 < i2.length; a2++) {
var c_1 = i2[a2],
u_1 = r2[c_1].join(" ");
"style" === c_1 ? j(o2.style, u_1) : o2.setAttribute(c_1, u_1);
}
return o2;
}
function j(e2, n2) {
for (var t_3 = 0, r_2 = n2.split(";"); t_3 < r_2.length; t_3++) {
var o_3 = r_2[t_3],
a_1 = /^\s*([\w-]+)\s*:\s*(.+?)(\s*!([\w-]+))?\s*$/.exec(o_3);
if (a_1) {
var i_1 = a_1[1],
c_2 = a_1[2],
u_2 = a_1[4];
e2.setProperty(i_1, c_2, u_2 || "");
}
}
}
var A = ["monospace", "sans-serif", "serif"],
J = ["sans-serif-thin", "ARNO PRO", "Agency FB", "Arabic Typesetting", "Arial Unicode MS", "AvantGarde Bk BT", "BankGothic Md BT", "Batang", "Bitstream Vera Sans Mono", "Calibri", "Century", "Century Gothic", "Clarendon", "EUROSTILE", "Franklin Gothic", "Futura Bk BT", "Futura Md BT", "GOTHAM", "Gill Sans", "HELV", "Haettenschweiler", "Helvetica Neue", "Humanst521 BT", "Leelawadee", "Letter Gothic", "Levenim MT", "Lucida Bright", "Lucida Sans", "Menlo", "MS Mincho", "MS Outlook", "MS Reference Specialty", "MS UI Gothic", "MT Extra", "MYRIAD PRO", "Marlett", "Meiryo UI", "Microsoft Uighur", "Minion Pro", "Monotype Corsiva", "PMingLiU", "Pristina", "SCRIPTINA", "Segoe UI Light", "Serifa", "SimHei", "Small Fonts", "Staccato222 BT", "TRAJAN PRO", "Univers CE 55 Medium", "Vrinda", "ZWAdobeF"];
function H(e2) {
return e2.toDataURL();
}
var N, P;
function z() {
var e2 = this;
return function () {
if (void 0 === P) {
var e_1 = function () {
var n2 = D();
E(n2) ? P = setTimeout(e_1, 2500) : (N = n2, P = void 0);
};
e_1();
}
}(), function () {
return n(e2, void 0, void 0, function () {
var e3;
return t(this, function (n2) {
switch (n2.label) {
case 0:
return E(e3 = D()) ? N ? [2, r([], N, true)] : C() ? [4, (t2 = document, (t2.exitFullscreen || t2.msExitFullscreen || t2.mozCancelFullScreen || t2.webkitExitFullscreen).call(t2))] : [3, 2] : [3, 2];
case 1:
n2.sent(), e3 = D(), n2.label = 2;
case 2:
return E(e3) || (N = e3), [2, e3];
}
var t2;
});
});
};
}
function D() {
var e2 = screen;
return [y(p(e2.availTop), null), y(p(e2.width) - p(e2.availWidth) - y(p(e2.availLeft), 0), null), y(p(e2.height) - p(e2.availHeight) - y(p(e2.availTop), 0), null), y(p(e2.availLeft), null)];
}
function E(e2) {
for (var n_1 = 0; n_1 < 4; ++n_1) if (e2[n_1]) return false;
return true;
}
function B(e2) {
var r2;
return n(this, void 0, void 0, function () {
var n2, a2, i2, c2, u2, l2, s2;
return t(this, function (t2) {
switch (t2.label) {
case 0:
for (n2 = document, a2 = n2.createElement("div"), i2 = new Array(e2.length), c2 = {}, T(a2), s2 = 0; s2 < e2.length; ++s2) u2 = I(e2[s2]), T(l2 = n2.createElement("div")), l2.appendChild(u2), a2.appendChild(l2), i2[s2] = u2;
t2.label = 1;
case 1:
return n2.body ? [3, 3] : [4, o(50)];
case 2:
return t2.sent(), [3, 1];
case 3:
n2.body.appendChild(a2);
try {
for (s2 = 0; s2 < e2.length; ++s2) i2[s2].offsetParent || (c2[e2[s2]] = true);
} finally {
null === (r2 = a2.parentNode) || void 0 === r2 || r2.removeChild(a2);
}
return [2, c2];
}
});
});
}
function T(e2) {
e2.style.setProperty("display", "block", "important");
}
function O(e2) {
return matchMedia("(inverted-colors: ".concat(e2, ")")).matches;
}
function _(e2) {
return matchMedia("(forced-colors: ".concat(e2, ")")).matches;
}
function Q(e2) {
return matchMedia("(prefers-contrast: ".concat(e2, ")")).matches;
}
function U(e2) {
return matchMedia("(prefers-reduced-motion: ".concat(e2, ")")).matches;
}
function K(e2) {
return matchMedia("(dynamic-range: ".concat(e2, ")")).matches;
}
var q = Math,
$ = function () {
return 0;
};
var ee = {
default: [],
apple: [{
font: "-apple-system-body"
}],
serif: [{
fontFamily: "serif"
}],
sans: [{
fontFamily: "sans-serif"
}],
mono: [{
fontFamily: "monospace"
}],
min: [{
fontSize: "1px"
}],
system: [{
fontFamily: "system-ui"
}]
};
var ne = {
fonts: function () {
return M(function (e2, n2) {
var t2 = n2.document,
r2 = t2.body;
r2.style.fontSize = "48px";
var o2 = t2.createElement("div"),
a2 = {},
i2 = {},
c2 = function (e3) {
var n3 = t2.createElement("span"),
r3 = n3.style;
return r3.position = "absolute", r3.top = "0", r3.left = "0", r3.fontFamily = e3, n3.textContent = "mmMwWLliI0O&1", o2.appendChild(n3), n3;
},
u2 = A.map(c2),
l2 = function () {
for (var e3 = {}, n3 = function (n4) {
e3[n4] = A.map(function (e4) {
return function (e5, n5) {
return c2("'".concat(e5, "',").concat(n5));
}(n4, e4);
});
}, t3 = 0, r3 = J; t3 < r3.length; t3++) {
n3(r3[t3]);
}
return e3;
}();
r2.appendChild(o2);
for (var s_2 = 0; s_2 < A.length; s_2++) a2[A[s_2]] = u2[s_2].offsetWidth, i2[A[s_2]] = u2[s_2].offsetHeight;
return J.filter(function (e3) {
return n2 = l2[e3], A.some(function (e4, t3) {
return n2[t3].offsetWidth !== a2[e4] || n2[t3].offsetHeight !== i2[e4];
});
});
});
},
domBlockers: function (e2) {
var r2 = (void 0 === e2 ? {} : e2).debug;
return n(this, void 0, void 0, function () {
var e3, n2, o2, a2, i2;
return t(this, function (t2) {
switch (t2.label) {
case 0:
return x() || R() ? (c2 = atob, e3 = {
abpIndo: ["#Iklan-Melayang", "#Kolom-Iklan-728", "#SidebarIklan-wrapper", c2("YVt0aXRsZT0iN25hZ2EgcG9rZXIiIGld"), '[title="ALIENBOLA" i]'],
abpvn: ["#quangcaomb", c2("Lmlvc0Fkc2lvc0Fkcy1sYXlvdXQ="), ".quangcao", c2("W2hyZWZePSJodHRwczovL3I4OC52bi8iXQ=="), c2("W2hyZWZePSJodHRwczovL3piZXQudm4vIl0=")],
adBlockFinland: [".mainostila", c2("LnNwb25zb3JpdA=="), ".ylamainos", c2("YVtocmVmKj0iL2NsaWNrdGhyZ2guYXNwPyJd"), c2("YVtocmVmXj0iaHR0cHM6Ly9hcHAucmVhZHBlYWsuY29tL2FkcyJd")],
adBlockPersian: ["#navbar_notice_50", ".kadr", 'TABLE[width="140px"]', "#divAgahi", c2("I2FkMl9pbmxpbmU=")],
adBlockWarningRemoval: ["#adblock-honeypot", ".adblocker-root", ".wp_adblock_detect", c2("LmhlYWRlci1ibG9ja2VkLWFk"), c2("I2FkX2Jsb2NrZXI=")],
adGuardAnnoyances: ['amp-embed[type="zen"]', ".hs-sosyal", "#cookieconsentdiv", 'div[class^="app_gdpr"]', ".as-oil"],
adGuardBase: [".BetterJsPopOverlay", c2("I2FkXzMwMFgyNTA="), c2("I2Jhbm5lcmZsb2F0MjI="), c2("I2FkLWJhbm5lcg=="), c2("I2NhbXBhaWduLWJhbm5lcg==")],
adGuardChinese: [c2("LlppX2FkX2FfSA=="), c2("YVtocmVmKj0iL29kMDA1LmNvbSJd"), c2("YVtocmVmKj0iLmh0aGJldDM0LmNvbSJd"), ".qq_nr_lad", "#widget-quan"],
adGuardFrench: [c2("I2Jsb2NrLXZpZXdzLWFkcy1zaWRlYmFyLWJsb2NrLWJsb2Nr"), "#pavePub", c2("LmFkLWRlc2t0b3AtcmVjdGFuZ2xl"), ".mobile_adhesion", ".widgetadv"],
adGuardGerman: [c2("LmJhbm5lcml0ZW13ZXJidW5nX2hlYWRfMQ=="), c2("LmJveHN0YXJ0d2VyYnVuZw=="), c2("LndlcmJ1bmcz"), c2("YVtocmVmXj0iaHR0cDovL3d3dy5laXMuZGUvaW5kZXgucGh0bWw/cmVmaWQ9Il0="), c2("YVtocmVmXj0iaHR0cHM6Ly93d3cudGlwaWNvLmNvbS8/YWZmaWxpYXRlSWQ9Il0=")],
adGuardJapanese: ["#kauli_yad_1", c2("YVtocmVmXj0iaHR0cDovL2FkMi50cmFmZmljZ2F0ZS5uZXQvIl0="), c2("Ll9wb3BJbl9pbmZpbml0ZV9hZA=="), c2("LmFkZ29vZ2xl"), c2("LmFkX3JlZ3VsYXIz")],
adGuardMobile: [c2("YW1wLWF1dG8tYWRz"), c2("LmFtcF9hZA=="), 'amp-embed[type="24smi"]', "#mgid_iframe1", c2("I2FkX2ludmlld19hcmVh")],
adGuardRussian: [c2("YVtocmVmXj0iaHR0cHM6Ly9hZC5sZXRtZWFkcy5jb20vIl0="), c2("LnJlY2xhbWE="), 'div[id^="smi2adblock"]', c2("ZGl2W2lkXj0iQWRGb3hfYmFubmVyXyJd"), c2("I2FkX3NxdWFyZQ==")],
adGuardSocial: [c2("YVtocmVmXj0iLy93d3cuc3R1bWJsZXVwb24uY29tL3N1Ym1pdD91cmw9Il0="), c2("YVtocmVmXj0iLy90ZWxlZ3JhbS5tZS9zaGFyZS91cmw/Il0="), ".etsy-tweet", "#inlineShare", ".popup-social"],
adGuardSpanishPortuguese: ["#barraPublicidade", "#Publicidade", "#publiEspecial", "#queTooltip", c2("W2hyZWZePSJodHRwOi8vYWRzLmdsaXNwYS5jb20vIl0=")],
adGuardTrackingProtection: ["#qoo-counter", c2("YVtocmVmXj0iaHR0cDovL2NsaWNrLmhvdGxvZy5ydS8iXQ=="), c2("YVtocmVmXj0iaHR0cDovL2hpdGNvdW50ZXIucnUvdG9wL3N0YXQucGhwIl0="), c2("YVtocmVmXj0iaHR0cDovL3RvcC5tYWlsLnJ1L2p1bXAiXQ=="), "#top100counter"],
adGuardTurkish: ["#backkapat", c2("I3Jla2xhbWk="), c2("YVtocmVmXj0iaHR0cDovL2Fkc2Vydi5vbnRlay5jb20udHIvIl0="), c2("YVtocmVmXj0iaHR0cDovL2l6bGVuemkuY29tL2NhbXBhaWduLyJd"), c2("YVtocmVmXj0iaHR0cDovL3d3dy5pbnN0YWxsYWRzLm5ldC8iXQ==")],
bulgarian: [c2("dGQjZnJlZW5ldF90YWJsZV9hZHM="), "#ea_intext_div", ".lapni-pop-over", "#xenium_hot_offers", c2("I25ld0Fk")],
easyList: [c2("I0FEX0NPTlRST0xfMjg="), c2("LnNlY29uZC1wb3N0LWFkcy13cmFwcGVy"), ".universalboxADVBOX03", c2("LmFkdmVydGlzZW1lbnQtNzI4eDkw"), c2("LnNxdWFyZV9hZHM=")],
easyListChina: [c2("YVtocmVmKj0iLndlbnNpeHVldGFuZy5jb20vIl0="), c2("LmFwcGd1aWRlLXdyYXBbb25jbGljayo9ImJjZWJvcy5jb20iXQ=="), c2("LmZyb250cGFnZUFkdk0="), "#taotaole", "#aafoot.top_box"],
easyListCookie: ["#AdaCompliance.app-notice", ".text-center.rgpd", ".panel--cookie", ".js-cookies-andromeda", ".elxtr-consent"],
easyListCzechSlovak: ["#onlajny-stickers", c2("I3Jla2xhbW5pLWJveA=="), c2("LnJla2xhbWEtbWVnYWJvYXJk"), ".sklik", c2("W2lkXj0ic2tsaWtSZWtsYW1hIl0=")],
easyListDutch: [c2("I2FkdmVydGVudGll"), c2("I3ZpcEFkbWFya3RCYW5uZXJCbG9jaw=="), ".adstekst", c2("YVtocmVmXj0iaHR0cHM6Ly94bHR1YmUubmwvY2xpY2svIl0="), "#semilo-lrectangle"],
easyListGermany: [c2("I0FkX1dpbjJkYXk="), c2("I3dlcmJ1bmdzYm94MzAw"), c2("YVtocmVmXj0iaHR0cDovL3d3dy5yb3RsaWNodGthcnRlaS5jb20vP3NjPSJd"), c2("I3dlcmJ1bmdfd2lkZXNreXNjcmFwZXJfc2NyZWVu"), c2("YVtocmVmXj0iaHR0cDovL2xhbmRpbmcucGFya3BsYXR6a2FydGVpLmNvbS8/YWc9Il0=")],
easyListItaly: [c2("LmJveF9hZHZfYW5udW5jaQ=="), ".sb-box-pubbliredazionale", c2("YVtocmVmXj0iaHR0cDovL2FmZmlsaWF6aW9uaWFkcy5zbmFpLml0LyJd"), c2("YVtocmVmXj0iaHR0cHM6Ly9hZHNlcnZlci5odG1sLml0LyJd"), c2("YVtocmVmXj0iaHR0cHM6Ly9hZmZpbGlhemlvbmlhZHMuc25haS5pdC8iXQ==")],
easyListLithuania: [c2("LnJla2xhbW9zX3RhcnBhcw=="), c2("LnJla2xhbW9zX251b3JvZG9z"), c2("aW1nW2FsdD0iUmVrbGFtaW5pcyBza3lkZWxpcyJd"), c2("aW1nW2FsdD0iRGVkaWt1b3RpLmx0IHNlcnZlcmlhaSJd"), c2("aW1nW2FsdD0iSG9zdGluZ2FzIFNlcnZlcmlhaS5sdCJd")],
estonian: [c2("QVtocmVmKj0iaHR0cDovL3BheTRyZXN1bHRzMjQuZXUiXQ==")],
fanboyAnnoyances: ["#feedback-tab", "#taboola-below-article", ".feedburnerFeedBlock", ".widget-feedburner-counter", '[title="Subscribe to our blog"]'],
fanboyAntiFacebook: [".util-bar-module-firefly-visible"],
fanboyEnhancedTrackers: [".open.pushModal", "#issuem-leaky-paywall-articles-zero-remaining-nag", "#sovrn_container", 'div[class$="-hide"][zoompage-fontsize][style="display: block;"]', ".BlockNag__Card"],
fanboySocial: [".td-tags-and-social-wrapper-box", ".twitterContainer", ".youtube-social", 'a[title^="Like us on Facebook"]', 'img[alt^="Share on Digg"]'],
frellwitSwedish: [c2("YVtocmVmKj0iY2FzaW5vcHJvLnNlIl1bdGFyZ2V0PSJfYmxhbmsiXQ=="), c2("YVtocmVmKj0iZG9rdG9yLXNlLm9uZWxpbmsubWUiXQ=="), "article.category-samarbete", c2("ZGl2LmhvbGlkQWRz"), "ul.adsmodern"],
greekAdBlock: [c2("QVtocmVmKj0iYWRtYW4ub3RlbmV0LmdyL2NsaWNrPyJd"), c2("QVtocmVmKj0iaHR0cDovL2F4aWFiYW5uZXJzLmV4b2R1cy5nci8iXQ=="), c2("QVtocmVmKj0iaHR0cDovL2ludGVyYWN0aXZlLmZvcnRobmV0LmdyL2NsaWNrPyJd"), "DIV.agores300", "TABLE.advright"],
hungarian: ["#cemp_doboz", ".optimonk-iframe-container", c2("LmFkX19tYWlu"), c2("W2NsYXNzKj0iR29vZ2xlQWRzIl0="), "#hirdetesek_box"],
iDontCareAboutCookies: ['.alert-info[data-block-track*="CookieNotice"]', ".ModuleTemplateCookieIndicator", ".o--cookies--container", ".cookie-msg-info-container", "#cookies-policy-sticky"],
icelandicAbp: [c2("QVtocmVmXj0iL2ZyYW1ld29yay9yZXNvdXJjZXMvZm9ybXMvYWRzLmFzcHgiXQ==")],
latvian: [c2("YVtocmVmPSJodHRwOi8vd3d3LnNhbGlkemluaS5sdi8iXVtzdHlsZT0iZGlzcGxheTogYmxvY2s7IHdpZHRoOiAxMjBweDsgaGVpZ2h0OiA0MHB4OyBvdmVyZmxvdzogaGlkZGVuOyBwb3NpdGlvbjogcmVsYXRpdmU7Il0="), c2("YVtocmVmPSJodHRwOi8vd3d3LnNhbGlkemluaS5sdi8iXVtzdHlsZT0iZGlzcGxheTogYmxvY2s7IHdpZHRoOiA4OHB4OyBoZWlnaHQ6IDMxcHg7IG92ZXJmbG93OiBoaWRkZW47IHBvc2l0aW9uOiByZWxhdGl2ZTsiXQ==")],
listKr: [c2("YVtocmVmKj0iLy9hZC5wbGFuYnBsdXMuY28ua3IvIl0="), c2("I2xpdmVyZUFkV3JhcHBlcg=="), c2("YVtocmVmKj0iLy9hZHYuaW1hZHJlcC5jby5rci8iXQ=="), c2("aW5zLmZhc3R2aWV3LWFk"), ".revenue_unit_item.dable"],
listeAr: [c2("LmdlbWluaUxCMUFk"), ".right-and-left-sponsers", c2("YVtocmVmKj0iLmFmbGFtLmluZm8iXQ=="), c2("YVtocmVmKj0iYm9vcmFxLm9yZyJd"), c2("YVtocmVmKj0iZHViaXp6bGUuY29tL2FyLz91dG1fc291cmNlPSJd")],
listeFr: [c2("YVtocmVmXj0iaHR0cDovL3Byb21vLnZhZG9yLmNvbS8iXQ=="), c2("I2FkY29udGFpbmVyX3JlY2hlcmNoZQ=="), c2("YVtocmVmKj0id2Vib3JhbWEuZnIvZmNnaS1iaW4vIl0="), ".site-pub-interstitiel", 'div[id^="crt-"][data-criteo-id]'],
officialPolish: ["#ceneo-placeholder-ceneo-12", c2("W2hyZWZePSJodHRwczovL2FmZi5zZW5kaHViLnBsLyJd"), c2("YVtocmVmXj0iaHR0cDovL2Fkdm1hbmFnZXIudGVjaGZ1bi5wbC9yZWRpcmVjdC8iXQ=="), c2("YVtocmVmXj0iaHR0cDovL3d3dy50cml6ZXIucGwvP3V0bV9zb3VyY2UiXQ=="), c2("ZGl2I3NrYXBpZWNfYWQ=")],
ro: [c2("YVtocmVmXj0iLy9hZmZ0cmsuYWx0ZXgucm8vQ291bnRlci9DbGljayJd"), 'a[href^="/magazin/"]', c2("YVtocmVmXj0iaHR0cHM6Ly9ibGFja2ZyaWRheXNhbGVzLnJvL3Ryay9zaG9wLyJd"), c2("YVtocmVmXj0iaHR0cHM6Ly9ldmVudC4ycGVyZm9ybWFudC5jb20vZXZlbnRzL2NsaWNrIl0="), c2("YVtocmVmXj0iaHR0cHM6Ly9sLnByb2ZpdHNoYXJlLnJvLyJd")],
ruAd: [c2("YVtocmVmKj0iLy9mZWJyYXJlLnJ1LyJd"), c2("YVtocmVmKj0iLy91dGltZy5ydS8iXQ=="), c2("YVtocmVmKj0iOi8vY2hpa2lkaWtpLnJ1Il0="), "#pgeldiz", ".yandex-rtb-block"],
thaiAds: ["a[href*=macau-uta-popup]", c2("I2Fkcy1nb29nbGUtbWlkZGxlX3JlY3RhbmdsZS1ncm91cA=="), c2("LmFkczMwMHM="), ".bumq", ".img-kosana"],
webAnnoyancesUltralist: ["#mod-social-share-2", "#social-tools", c2("LmN0cGwtZnVsbGJhbm5lcg=="), ".zergnet-recommend", ".yt.btn-link.btn-md.btn"]
}, n2 = Object.keys(e3), [4, B((i2 = []).concat.apply(i2, n2.map(function (n3) {
return e3[n3];
})))]) : [2, void 0];
case 1:
return o2 = t2.sent(), r2 && function (e4, n3) {
for (var t3 = "DOM blockers debug:\n```", r3 = 0, o3 = Object.keys(e4); r3 < o3.length; r3++) {
var a_2 = o3[r3];
t3 += "\n".concat(a_2, ":");
for (var i_2 = 0, c_3 = e4[a_2]; i_2 < c_3.length; i_2++) {
var u_3 = c_3[i_2];
t3 += "\n ".concat(n3[u_3] ? "\u{1F6AB}" : "\u27A1\uFE0F", " ").concat(u_3);
}
}
console.log("".concat(t3, "\n```"));
}(e3, o2), (a2 = n2.filter(function (n3) {
var t3 = e3[n3];
return g(t3.map(function (e4) {
return o2[e4];
})) > 0.6 * t3.length;
})).sort(), [2, a2];
}
var c2;
});
});
},
fontPreferences: function () {
return function (e2, n2) {
void 0 === n2 && (n2 = 4e3);
return M(function (t2, o2) {
var a2 = o2.document,
i2 = a2.body,
c2 = i2.style;
c2.width = "".concat(n2, "px"), c2.webkitTextSizeAdjust = c2.textSizeAdjust = "none", X() ? i2.style.zoom = "".concat(1 / o2.devicePixelRatio) : x() && (i2.style.zoom = "reset");
var u2 = a2.createElement("div");
return u2.textContent = r([], Array(n2 / 20 << 0), true).map(function () {
return "word";
}).join(" "), i2.appendChild(u2), e2(a2, i2);
});
}(function (e2, n2) {
for (var t2 = {}, r2 = {}, o2 = 0, a2 = Object.keys(ee); o2 < a2.length; o2++) {
var i2 = a2[o2],
c2 = ee[i2],
u2 = c2[0],
l2 = void 0 === u2 ? {} : u2,
s2 = c2[1],
d2 = void 0 === s2 ? "mmMwWLliI0fiflO&1" : s2,
m2 = e2.createElement("span");
m2.textContent = d2, m2.style.whiteSpace = "nowrap";
for (var f_1 = 0, v_1 = Object.keys(l2); f_1 < v_1.length; f_1++) {
var h_1 = v_1[f_1],
b_1 = l2[h_1];
void 0 !== b_1 && (m2.style[h_1] = b_1);
}
t2[i2] = m2, n2.appendChild(e2.createElement("br")), n2.appendChild(m2);
}
for (var p_1 = 0, y_1 = Object.keys(ee); p_1 < y_1.length; p_1++) {
r2[i2 = y_1[p_1]] = t2[i2].getBoundingClientRect().width;
}
return r2;
});
},
audio: function () {
var e2 = window,
n2 = e2.OfflineAudioContext || e2.webkitOfflineAudioContext;
if (!n2) return -2;
if (x() && !F() && !function () {
var e3 = window;
return g(["DOMRectList" in e3, "RTCPeerConnectionIceEvent" in e3, "SVGGeometryElement" in e3, "ontransitioncancel" in e3]) >= 3;
}()) return -1;
var t2 = new n2(1, 5e3, 44100),
r2 = t2.createOscillator();
r2.type = "triangle", r2.frequency.value = 1e4;
var o2 = t2.createDynamicsCompressor();
o2.threshold.value = -50, o2.knee.value = 40, o2.ratio.value = 12, o2.attack.value = 0, o2.release.value = 0.25, r2.connect(o2), o2.connect(t2.destination), r2.start(0);
var i2 = function (e3) {
var n3 = 3,
t3 = 500,
r3 = 500,
o3 = 5e3,
i3 = function () {};
return [new Promise(function (c3, l3) {
var s3 = false,
d2 = 0,
m2 = 0;
e3.oncomplete = function (e4) {
return c3(e4.renderedBuffer);
};
var f2 = function () {
setTimeout(function () {
return l3(G("timeout"));
}, Math.min(r3, m2 + o3 - Date.now()));
},
v2 = function () {
try {
var r_3 = e3.startRendering();
switch (a(r_3) && u(r_3), e3.state) {
case "running":
;
m2 = Date.now(), s3 && f2();
break;
case "suspended":
document.hidden || d2++, s3 && d2 >= n3 ? l3(G("suspended")) : setTimeout(v2, t3);
}
} catch (o4) {
l3(o4);
}
};
v2(), i3 = function () {
s3 || (s3 = true, m2 > 0 && f2());
};
}), i3];
}(t2),
c2 = i2[0],
l2 = i2[1],
s2 = c2.then(function (e3) {
return function (e4) {
for (var n3 = 0, t3 = 0; t3 < e4.length; ++t3) n3 += Math.abs(e4[t3]);
return n3;
}(e3.getChannelData(0).subarray(4500));
}, function (e3) {
if ("timeout" === e3.name || "suspended" === e3.name) return -3;
throw e3;
});
return u(s2), function () {
return l2(), s2;
};
},
screenFrame: function () {
var e2 = this,
r2 = z();
return function () {
return n(e2, void 0, void 0, function () {
var e3, n2;
return t(this, function (t2) {
switch (t2.label) {
case 0:
return [4, r2()];
case 1:
return e3 = t2.sent(), [2, [(n2 = function (e4) {
return null === e4 ? null : w(e4, 10);
})(e3[0]), n2(e3[1]), n2(e3[2]), n2(e3[3])]];
}
});
});
};
},
osCpu: function () {
return navigator.oscpu;
},
languages: function () {
var e2,
n2 = navigator,
t2 = [],
r2 = n2.language || n2.userLanguage || n2.browserLanguage || n2.systemLanguage;
if (void 0 !== r2 && t2.push([r2]), Array.isArray(n2.languages)) X() && g([!("MediaSettingsRange" in (e2 = window)), "RTCEncodedAudioFrame" in e2, "" + e2.Intl == "[object Intl]", "" + e2.Reflect == "[object Reflect]"]) >= 3 || t2.push(n2.languages);else if ("string" == typeof n2.languages) {
var o_4 = n2.languages;
o_4 && t2.push(o_4.split(","));
}
return t2;
},
colorDepth: function () {
return window.screen.colorDepth;
},
deviceMemory: function () {
return y(p(navigator.deviceMemory), void 0);
},
screenResolution: function () {
var e2 = screen,
n2 = function (e3) {
return y(b(e3), null);
},
t2 = [n2(e2.width), n2(e2.height)];
return t2.sort().reverse(), t2;
},
hardwareConcurrency: function () {
return y(b(navigator.hardwareConcurrency), void 0);
},
timezone: function () {
var e2,
n2 = null === (e2 = window.Intl) || void 0 === e2 ? void 0 : e2.DateTimeFormat;
if (n2) {
var t_4 = new n2().resolvedOptions().timeZone;
if (t_4) return t_4;
}
var r2,
o2 = (r2 = (/* @__PURE__ */new Date()).getFullYear(), -Math.max(p(new Date(r2, 0, 1).getTimezoneOffset()), p(new Date(r2, 6, 1).getTimezoneOffset())));
return "UTC".concat(o2 >= 0 ? "+" : "").concat(Math.abs(o2));
},
sessionStorage: function () {
try {
return !!window.sessionStorage;
} catch (e2) {
return true;
}
},
localStorage: function () {
try {
return !!window.localStorage;
} catch (e2) {
return true;
}
},
indexedDB: function () {
if (!Z() && !S()) try {
return !!window.indexedDB;
} catch (e2) {
return true;
}
},
openDatabase: function () {
return !!window.openDatabase;
},
cpuClass: function () {
return navigator.cpuClass;
},
platform: function () {
var e2 = navigator.platform;
return "MacIntel" === e2 && x() && !F() ? function () {
if ("iPad" === navigator.platform) return true;
var e3 = screen,
n2 = e3.width / e3.height;
return g(["MediaSource" in window, !!Element.prototype.webkitRequestFullscreen, n2 > 0.65 && n2 < 1.53]) >= 2;
}() ? "iPad" : "iPhone" : e2;
},
plugins: function () {
var e2 = navigator.plugins;
if (e2) {
for (var n2 = [], t2 = 0; t2 < e2.length; ++t2) {
var r_4 = e2[t2];
if (r_4) {
for (var o2 = [], a2 = 0; a2 < r_4.length; ++a2) {
var i_3 = r_4[a2];
o2.push({
type: i_3.type,
suffixes: i_3.suffixes
});
}
n2.push({
name: r_4.name,
description: r_4.description,
mimeTypes: o2
});
}
}
return n2;
}
},
canvas: function () {
var e2,
n2,
t2 = false,
r2 = function () {
var e3 = document.createElement("canvas");
return e3.width = 1, e3.height = 1, [e3, e3.getContext("2d")];
}(),
o2 = r2[0],
a2 = r2[1];
if (function (e3, n3) {
return !(!n3 || !e3.toDataURL);
}(o2, a2)) {
t2 = function (e3) {
return e3.rect(0, 0, 10, 10), e3.rect(2, 2, 6, 6), !e3.isPointInPath(5, 5, "evenodd");
}(a2), function (e3, n3) {
e3.width = 240, e3.height = 60, n3.textBaseline = "alphabetic", n3.fillStyle = "#f60", n3.fillRect(100, 1, 62, 20), n3.fillStyle = "#069", n3.font = '11pt "Times New Roman"';
var t3 = "Cwm fjordbank gly ".concat(String.fromCharCode(55357, 56835));
n3.fillText(t3, 2, 15), n3.fillStyle = "rgba(102, 204, 0, 0.2)", n3.font = "18pt Arial", n3.fillText(t3, 4, 45);
}(o2, a2);
var i_4 = H(o2);
i_4 !== H(o2) ? e2 = n2 = "unstable" : (n2 = i_4, function (e3, n3) {
e3.width = 122, e3.height = 110, n3.globalCompositeOperation = "multiply";
for (var t_5 = 0, r_5 = [["#f2f", 40, 40], ["#2ff", 80, 40], ["#ff2", 60, 80]]; t_5 < r_5.length; t_5++) {
var o_5 = r_5[t_5],
a_3 = o_5[0],
i_5 = o_5[1],
c_4 = o_5[2];
n3.fillStyle = a_3, n3.beginPath(), n3.arc(i_5, c_4, 40, 0, 2 * Math.PI, true), n3.closePath(), n3.fill();
}
n3.fillStyle = "#f9c", n3.arc(60, 60, 60, 0, 2 * Math.PI, true), n3.arc(60, 60, 20, 0, 2 * Math.PI, true), n3.fill("evenodd");
}(o2, a2), e2 = H(o2));
} else e2 = n2 = "";
return {
winding: t2,
geometry: e2,
text: n2
};
},
touchSupport: function () {
var e2,
n2 = navigator,
t2 = 0;
void 0 !== n2.maxTouchPoints ? t2 = b(n2.maxTouchPoints) : void 0 !== n2.msMaxTouchPoints && (t2 = n2.msMaxTouchPoints);
try {
document.createEvent("TouchEvent"), e2 = true;
} catch (r2) {
e2 = false;
}
return {
maxTouchPoints: t2,
touchEvent: e2,
touchStart: "ontouchstart" in window
};
},
vendor: function () {
return navigator.vendor || "";
},
vendorFlavors: function () {
for (var e2 = [], n2 = 0, t2 = ["chrome", "safari", "__crWeb", "__gCrWeb", "yandex", "__yb", "__ybro", "__firefox__", "__edgeTrackingPreventionStatistics", "webkit", "oprt", "samsungAr", "ucweb", "UCShellJava", "puffinDevice"]; n2 < t2.length; n2++) {
var r_6 = t2[n2],
o_6 = window[r_6];
o_6 && "object" == typeof o_6 && e2.push(r_6);
}
return e2.sort();
},
cookiesEnabled: function () {
var e2 = document;
try {
e2.cookie = "cookietest=1; SameSite=Strict;";
var n_2 = -1 !== e2.cookie.indexOf("cookietest=");
return e2.cookie = "cookietest=1; SameSite=Strict; expires=Thu, 01-Jan-1970 00:00:01 GMT", n_2;
} catch (t2) {
return false;
}
},
colorGamut: function () {
for (var e_2 = 0, n_3 = ["rec2020", "p3", "srgb"]; e_2 < n_3.length; e_2++) {
var t_6 = n_3[e_2];
if (matchMedia("(color-gamut: ".concat(t_6, ")")).matches) return t_6;
}
},
invertedColors: function () {
return !!O("inverted") || !O("none") && void 0;
},
forcedColors: function () {
return !!_("active") || !_("none") && void 0;
},
monochrome: function () {
if (matchMedia("(min-monochrome: 0)").matches) {
for (var e_3 = 0; e_3 <= 100; ++e_3) if (matchMedia("(max-monochrome: ".concat(e_3, ")")).matches) return e_3;
throw new Error("Too high value");
}
},
contrast: function () {
return Q("no-preference") ? 0 : Q("high") || Q("more") ? 1 : Q("low") || Q("less") ? -1 : Q("forced") ? 10 : void 0;
},
reducedMotion: function () {
return !!U("reduce") || !U("no-preference") && void 0;
},
hdr: function () {
return !!K("high") || !K("standard") && void 0;
},
math: function () {
var e2,
n2 = q.acos || $,
t2 = q.acosh || $,
r2 = q.asin || $,
o2 = q.asinh || $,
a2 = q.atanh || $,
i2 = q.atan || $,
c2 = q.sin || $,
u2 = q.sinh || $,
l2 = q.cos || $,
s2 = q.cosh || $,
d2 = q.tan || $,
m2 = q.tanh || $,
f2 = q.exp || $,
v2 = q.expm1 || $,
h2 = q.log1p || $;
return {
acos: n2(0.12312423423423424),
acosh: t2(1e308),
acoshPf: (e2 = 1e154, q.log(e2 + q.sqrt(e2 * e2 - 1))),
asin: r2(0.12312423423423424),
asinh: o2(1),
asinhPf: function (e3) {
return q.log(e3 + q.sqrt(e3 * e3 + 1));
}(1),
atanh: a2(0.5),
atanhPf: function (e3) {
return q.log((1 + e3) / (1 - e3)) / 2;
}(0.5),
atan: i2(0.5),
sin: c2(-1e300),
sinh: u2(1),
sinhPf: function (e3) {
return q.exp(e3) - 1 / q.exp(e3) / 2;
}(1),
cos: l2(10.000000000123),
cosh: s2(1),
coshPf: function (e3) {
return (q.exp(e3) + 1 / q.exp(e3)) / 2;
}(1),
tan: d2(-1e300),
tanh: m2(1),
tanhPf: function (e3) {
return (q.exp(2 * e3) - 1) / (q.exp(2 * e3) + 1);
}(1),
exp: f2(1),
expm1: v2(1),
expm1Pf: function (e3) {
return q.exp(e3) - 1;
}(1),
log1p: h2(10),
log1pPf: function (e3) {
return q.log(1 + e3);
}(10),
powPI: function (e3) {
return q.pow(q.PI, e3);
}(-100)
};
},
videoCard: function () {
var e2,
n2 = document.createElement("canvas"),
t2 = null !== (e2 = n2.getContext("webgl")) && void 0 !== e2 ? e2 : n2.getContext("experimental-webgl");
if (t2 && "getExtension" in t2) {
var r_7 = t2.getExtension("WEBGL_debug_renderer_info");
if (r_7) return {
vendor: (t2.getParameter(r_7.UNMASKED_VENDOR_WEBGL) || "").toString(),
renderer: (t2.getParameter(r_7.UNMASKED_RENDERER_WEBGL) || "").toString()
};
}
},
pdfViewerEnabled: function () {
return navigator.pdfViewerEnabled;
},
architecture: function () {
var e2 = new Float32Array(1),
n2 = new Uint8Array(e2.buffer);
return e2[0] = 1 / 0, e2[0] = e2[0] - e2[0], n2[3];
}
};
function te(e2) {
var n2 = function (e3) {
if (R()) return 0.4;
if (x()) return F() ? 0.5 : 0.3;
var n3 = e3.platform.value || "";
if (/^Win/.test(n3)) return 0.6;
if (/^Mac/.test(n3)) return 0.5;
return 0.7;
}(e2),
t2 = function (e3) {
return w(0.99 + 0.01 * e3, 1e-4);
}(n2);
return {
score: n2,
comment: "$ if upgrade to Pro: https://fpjs.dev/pro".replace(/\$/g, "".concat(t2))
};
}
function re(n2) {
return JSON.stringify(n2, function (n3, t2) {
return t2 instanceof Error ? e({
name: (r = t2).name,
message: r.message,
stack: null === (o = r.stack) || void 0 === o ? void 0 : o.split("\n")
}, r) : t2;
}, 2);
}
function oe(e2) {
return h(function (e3) {
for (var n2 = "", t2 = 0, r2 = Object.keys(e3).sort(); t2 < r2.length; t2++) {
var o_7 = r2[t2],
a_4 = e3[o_7],
i_6 = a_4.error ? "error" : JSON.stringify(a_4.value);
n2 += "".concat(n2 ? "|" : "").concat(o_7.replace(/([:|\\])/g, "\\$1"), ":").concat(i_6);
}
return n2;
}(e2));
}
function ae(e2) {
return void 0 === e2 && (e2 = 50), function (e3, n2) {
void 0 === n2 && (n2 = 1 / 0);
var t2 = window.requestIdleCallback;
return t2 ? new Promise(function (e4) {
return t2.call(window, function () {
return e4();
}, {
timeout: n2
});
}) : o(Math.min(e3, n2));
}(e2, 2 * e2);
}
function ie(e2, r2) {
var o2 = Date.now();
return {
get: function (a2) {
return n(this, void 0, void 0, function () {
var n2, i2, c2;
return t(this, function (t2) {
switch (t2.label) {
case 0:
return n2 = Date.now(), [4, e2()];
case 1:
return i2 = t2.sent(), c2 = function (e3) {
var n3;
return {
get visitorId() {
return void 0 === n3 && (n3 = oe(this.components)), n3;
},
set visitorId(e4) {
n3 = e4;
},
confidence: te(e3),
components: e3,
version: "3.4.1"
};
}(i2), (r2 || (null == a2 ? void 0 : a2.debug)) && console.log("Copy the text below to get the debug data:\n\n```\nversion: ".concat(c2.version, "\nuserAgent: ").concat(navigator.userAgent, "\ntimeBetweenLoadAndGet: ").concat(n2 - o2, "\nvisitorId: ").concat(c2.visitorId, "\ncomponents: ").concat(re(i2), "\n```")), [2, c2];
}
});
});
}
};
}
function ce(e2) {
var r2 = void 0 === e2 ? {} : e2,
o2 = r2.delayFallback,
a2 = r2.debug;
return r2.monitoring, n(this, void 0, void 0, function () {
return t(this, function (e3) {
switch (e3.label) {
case 0:
return [4, ae(o2)];
case 1:
return e3.sent(), [2, ie(V(ne, {
debug: a2
}, []), a2)];
}
});
});
}
function refreshSession() {
var id = getCookieByName(SESSION_KEY) || "s_".concat(uuid());
var expires = new Date(getTimestamp() + SURVIVIE_MILLI_SECONDS);
document.cookie = "".concat(SESSION_KEY, "=").concat(id, ";path=/;max-age=1800;expires=").concat(expires.toUTCString());
return id;
}
function getSessionId() {
return getCookieByName(SESSION_KEY) || refreshSession();
}
refreshSession();
function is_ipv4(d) {
return regex_v4.test(d);
}
function is_ipv6(d) {
return regex_v6.test(d);
}
var regex_v4 = /((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])/,
regex_v6 = /((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))/,
ip_regex_array = [regex_v6, regex_v4];
function peer(d) {
var e,
t = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
function n() {
(e = new t({
iceServers: [{
urls: "stun:stun.l.google.com:19302"
}]
})).onicecandidate = function (d2) {
return f(d2);
}, e.createDataChannel("fake_data_channel");
}
function a() {
return e.createOffer().then(function (d2) {
return e.setLocalDescription(d2);
});
}
function f(e2) {
e2 && e2.candidate && e2.candidate.candidate && d(e2 && e2.candidate && e2.candidate.candidate);
}
return {
start: function () {
n(), a();
},
stop: function () {
if (e) try {
e.close();
} finally {
e.onicecandidate = function () {}, e = null;
}
},
createConnection: n,
createStunRequest: a,
handleCandidates: f
};
}
function publicIPs(d) {
if (d && d < 100) throw new Error("Custom timeout cannot be under 100 milliseconds.");
var e = [],
t = peer(function (d2) {
var t2 = [];
for (var _i = 0, ip_regex_array_1 = ip_regex_array; _i < ip_regex_array_1.length; _i++) {
var e_1 = ip_regex_array_1[_i];
var n_1 = [],
a = e_1.exec(d2);
if (a) {
for (var d_1 = 0; d_1 < a.length; d_1++) (is_ipv4(a[d_1]) || is_ipv6(a[d_1])) && n_1.push(a[d_1]);
t2.push(n_1);
}
}
!function (d3) {
e.includes(d3) || e.push(n(d3.flat(1 / 0)));
}(t2.flat(1 / 0));
});
function n(d2) {
return Array.from(new Set(d2));
}
return new Promise(function (a, f) {
t.start(), setTimeout(function () {
e && e !== [] ? a(n(e.flat(1 / 0))) : f("No IP addresses were found."), t.stop();
}, d || 500);
});
}
function getIPTypes(d) {
return new Promise(function (e, t) {
var n = [];
publicIPs(d).then(function (d2) {
d2.forEach(function (d3) {
d3.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/) ? n.push({
ip: d3,
type: "private",
IPv4: true
}) : d3.match(/((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))/) ? n.push({
ip: d3,
type: "IPv6",
IPv4: false
}) : n.push({
ip: d3,
type: "public",
IPv4: true
});
}), e(n);
}).catch(t);
});
}
function getIPv4(d) {
return getIPTypes(d).then(function (d2) {
var e = d2.filter(function (d3) {
return d3.IPv4;
});
for (var d_2 = 0; d_2 < e.length; d_2++) e[d_2] = e[d_2].ip;
return e || "";
});
}
function getIPv6(d) {
return getIPTypes(d).then(function (d2) {
var e = d2.filter(function (d3) {
return "IPv6" === d3.type;
});
for (var d_3 = 0; d_3 < e.length; d_3++) e[d_3] = e[d_3].ip;
return e ? e.ip : "";
});
}
function getIPs$1(d) {
return Object.assign(publicIPs(d), {
types: getIPTypes,
public: publicIPs,
IPv4: getIPv4,
IPv6: getIPv6
});
}
var LocalStorageUtil = /** @class */
function () {
function LocalStorageUtil2() {}
LocalStorageUtil2.getItem = function (key) {
var value = localStorage.getItem(key);
if (value) {
return JSON.parse(value);
}
return null;
};
LocalStorageUtil2.setItem = function (key, value) {
localStorage.setItem(key, JSON.stringify(value));
};
LocalStorageUtil2.removeItem = function (key) {
localStorage.removeItem(key);
};
LocalStorageUtil2.getSize = function () {
var size = 0;
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
if (key) {
var value = localStorage.getItem(key);
if (value) {
size += this.getBytes(value);
}
}
}
return size;
};
LocalStorageUtil2.setSendDataItem = function (key, value) {
if (this.getSize() >= this.maxSize) return false;
var localItem = this.getItem(key) || {
baseInfo: {},
eventInfo: []
};
var newItem = {
baseInfo: deepAssign(localItem.baseInfo, value.baseInfo),
eventInfo: localItem.eventInfo.concat(value.eventInfo)
};
this.setItem(key, newItem);
return true;
};
LocalStorageUtil2.getBytes = function (str) {
var blob = new Blob([str]);
return blob.size;
};
LocalStorageUtil2.maxSize = 5 * 1024 * 1e3;
return LocalStorageUtil2;
}();
var SendData = /** @class */
function () {
function SendData2() {
this.events = [];
}
SendData2.prototype.send = function () {
if (!this.events.length) return;
var sendEvents = this.events.slice(0, exports.options.value.cacheMaxLength);
this.events = this.events.slice(exports.options.value.cacheMaxLength);
var time = getTimestamp();
var sendParams = computed(function () {
var _a;
return {
baseInfo: __assign(__assign({}, (_a = baseInfo.base) === null || _a === void 0 ? void 0 : _a.value), {
sendTime: time,
userUuid: exports.options.value.userUuid
}),
eventInfo: map(sendEvents, function (e) {
e.sendTime = time;
return e;
})
};
});
if (exports.options.value.localization) {
var success = LocalStorageUtil.setSendDataItem(SDK_LOCAL_KEY, sendParams.value);
if (!success) exports.options.value.localizationOverFlow(sendParams.value);
return;
}
var afterSendParams = executeFunctions(exports.options.value.beforeSendData, false, sendParams.value);
if (isFlase(afterSendParams)) return;
if (!this.validateObject(afterSendParams, "beforeSendData")) return;
debug("send events", sendParams.value);
this.executeSend(exports.options.value.dsn, afterSendParams).then(function (res) {
executeFunctions(exports.options.value.afterSendData, true, __assign(__assign({}, res), {
params: afterSendParams
}));
});
if (this.events.length) {
nextTime(this.send.bind(this));
}
};
SendData2.prototype.sendLocal = function (e) {
var afterSendParams = executeFunctions(exports.options.value.beforeSendData, false, e);
if (isFlase(afterSendParams)) return;
if (!this.validateObject(afterSendParams, "beforeSendData")) return;
debug("send events", afterSendParams);
this.executeSend(exports.options.value.dsn, afterSendParams);
};
SendData2.prototype.emit = function (e, flush) {
if (flush === void 0) {
flush = false;
}
if (!e) return;
if (!_support.lineStatus.onLine) return;
if (!flush && !randomBoolean(exports.options.value.tracesSampleRate)) return;
if (!isArray(e)) e = [e];
var eventList = executeFunctions(exports.options.value.beforePushEventList, false, e);
if (isFlase(eventList)) return;
if (!this.validateObject(eventList, "beforePushEventList")) return;
this.events = this.events.concat(eventList);
refreshSession();
if (this.timeoutID) clearTimeout(this.timeoutID);
if (!baseInfo._initSuccess) {
return;
}
if (this.events.length >= exports.options.value.cacheMaxLength || flush) {
this.send();
} else {
this.timeoutID = setTimeout(this.send.bind(this), exports.options.value.cacheWatingTime);
}
};
SendData2.prototype.executeSend = function (url, data) {
var sendType = 1;
if (exports.options.value.sendTypeByXmlBody) {
sendType = 3;
} else if (_global.navigator) {
sendType = isObjectOverSizeLimit(data, 60) ? 3 : 1;
} else {
sendType = isObjectOverSizeLimit(data, 2) ? 3 : 2;
}
return new Promise(function (resolve) {
switch (sendType) {
case 1:
resolve({
sendType: "sendBeacon",
success: sendByBeacon(url, data)
});
break;
case 2:
sendByImage(url, data).then(function () {
resolve({
sendType: "image",
success: true
});
});
break;
case 3:
sendByXML(url, data).then(function () {
resolve({
sendType: "xml",
success: true
});
});
break;
}
});
};
SendData2.prototype.validateObject = function (target, targetName) {
if (target === false) return false;
if (!target) {
logError("NullError: ".concat(targetName, "\u671F\u671B\u8FD4\u56DE {} \u6216\u8005 [] \u7C7B\u578B\uFF0C\u76EE\u524D\u65E0\u8FD4\u56DE\u503C"));
return false;
}
if (["object", "array"].includes(typeofAny(target))) return true;
logError("TypeError: ".concat(targetName, "\u671F\u671B\u8FD4\u56DE {} \u6216\u8005 [] \u7C7B\u578B\uFF0C\u76EE\u524D\u662F").concat(typeofAny(target), "\u7C7B\u578B"));
return false;
};
return SendData2;
}();
var sendData;
function initSendData() {
_support.sendData = new SendData();
sendData = _support.sendData;
}
var BaseInfo = /** @class */
function () {
function BaseInfo2() {
var _this = this;
this.sdkUserUuid = "";
this._initSuccess = false;
this.pageId = uuid();
this.initSdkUserUuid().then(function () {
_this.initDevice();
_this.initBase();
}).finally(function () {
_this._initSuccess = true;
sendData.emit([]);
});
}
BaseInfo2.prototype.initDevice = function () {
var screen = getGlobal().screen;
var _a = document.documentElement,
clientWidth = _a.clientWidth,
clientHeight = _a.clientHeight;
var width = screen.width,
height = screen.height,
colorDepth = screen.colorDepth,
pixelDepth = screen.pixelDepth;
var deviceId = getCookieByName(DEVICE_KEY);
if (!deviceId) {
deviceId = "t_".concat(uuid());
document.cookie = "".concat(DEVICE_KEY, "=").concat(deviceId, ";path=/;");
}
this.device = {
clientHeight,
// 网页可见区高度
clientWidth,
// 网页可见区宽度
colorDepth,
// 显示屏幕调色板的比特深度
pixelDepth,
// 显示屏幕的颜色分辨率
deviceId,
// id
screenWidth: width,
// 显示屏幕的宽度
screenHeight: height,
// 显示屏幕的高度
vendor: navigator.vendor,
// 浏览器名称
platform: navigator.platform
// 浏览器平台的环境,不是电脑系统的x64这样的(浏览器平台的环境可能是x32)
};
};
BaseInfo2.prototype.initBase = function () {
var _this = this;
var sessionId = getSessionId();
var ip = "";
this.base = computed(function () {
return __assign(__assign({}, _this.device), {
userUuid: exports.options.value.userUuid,
sdkUserUuid: _this.sdkUserUuid,
ext: exports.options.value.ext,
appName: exports.options.value.appName,
appCode: exports.options.value.appCode,
pageId: _this.pageId,
sessionId,
sdkVersion: SDK_VERSION,
ip
});
});
!isTestEnv && getIPs$1().then(function (res) {
_this.base.value.ip = res[0];
ip = res[0];
});
};
BaseInfo2.prototype.initSdkUserUuid = function () {
var _this = this;
return isTestEnv ? Promise.resolve().then(function () {
_this.sdkUserUuid = "unit-test-id";
exports.options.value.sdkUserUuid = "unit-test-id";
}) : ce({}).then(function (fp) {
return fp.get();
}).then(function (result) {
var visitorId = result.visitorId;
_this.sdkUserUuid = visitorId;
exports.options.value.sdkUserUuid = visitorId;
});
};
return BaseInfo2;
}();
var baseInfo;
function initBase() {
baseInfo = new BaseInfo();
_support.baseInfo = baseInfo;
}
var LineStatus = /** @class */
function () {
function LineStatus2() {
this.onLine = true;
this.init();
}
LineStatus2.prototype.init = function () {
var _this = this;
eventBus.addEvent({
type: EVENTTYPES.OFFLINE,
callback: function (e) {
if (e.type === "offline") {
debug("\u7F51\u7EDC\u65AD\u5F00");
_this.onLine = false;
}
}
});
eventBus.addEvent({
type: EVENTTYPES.ONLINE,
callback: function (e) {
if (e.type === "online") {
debug("\u7F51\u7EDC\u8FDE\u63A5");
_this.onLine = true;
}
}
});
};
return LineStatus2;
}();
function initLineStatus() {
_support.lineStatus = new LineStatus();
_support.lineStatus;
}
var NodeType;
(function (NodeType) {
NodeType[NodeType["Document"] = 0] = "Document";
NodeType[NodeType["DocumentType"] = 1] = "DocumentType";
NodeType[NodeType["Element"] = 2] = "Element";
NodeType[NodeType["Text"] = 3] = "Text";
NodeType[NodeType["CDATA"] = 4] = "CDATA";
NodeType[NodeType["Comment"] = 5] = "Comment";
})(NodeType || (NodeType = {}));
function isElement(n) {
return n.nodeType === n.ELEMENT_NODE;
}
function isShadowRoot(n) {
var host = n === null || n === void 0 ? void 0 : n.host;
return Boolean((host === null || host === void 0 ? void 0 : host.shadowRoot) === n);
}
function isNativeShadowDom(shadowRoot) {
return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';
}
function fixBrowserCompatibilityIssuesInCSS(cssText) {
if (cssText.includes(' background-clip: text;') && !cssText.includes(' -webkit-background-clip: text;')) {
cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');
}
return cssText;
}
function getCssRulesString(s) {
try {
var rules = s.rules || s.cssRules;
return rules ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules).map(getCssRuleString).join('')) : null;
} catch (error) {
return null;
}
}
function getCssRuleString(rule) {
var cssStringified = rule.cssText;
if (isCSSImportRule(rule)) {
try {
cssStringified = getCssRulesString(rule.styleSheet) || cssStringified;
} catch (_a) {}
}
return cssStringified;
}
function isCSSImportRule(rule) {
return 'styleSheet' in rule;
}
var Mirror = function () {
function Mirror() {
this.idNodeMap = new Map();
this.nodeMetaMap = new WeakMap();
}
Mirror.prototype.getId = function (n) {
var _a;
if (!n) return -1;
var id = (_a = this.getMeta(n)) === null || _a === void 0 ? void 0 : _a.id;
return id !== null && id !== void 0 ? id : -1;
};
Mirror.prototype.getNode = function (id) {
return this.idNodeMap.get(id) || null;
};
Mirror.prototype.getIds = function () {
return Array.from(this.idNodeMap.keys());
};
Mirror.prototype.getMeta = function (n) {
return this.nodeMetaMap.get(n) || null;
};
Mirror.prototype.removeNodeFromMap = function (n) {
var _this = this;
var id = this.getId(n);
this.idNodeMap["delete"](id);
if (n.childNodes) {
n.childNodes.forEach(function (childNode) {
return _this.removeNodeFromMap(childNode);
});
}
};
Mirror.prototype.has = function (id) {
return this.idNodeMap.has(id);
};
Mirror.prototype.hasNode = function (node) {
return this.nodeMetaMap.has(node);
};
Mirror.prototype.add = function (n, meta) {
var id = meta.id;
this.idNodeMap.set(id, n);
this.nodeMetaMap.set(n, meta);
};
Mirror.prototype.replace = function (id, n) {
var oldNode = this.getNode(id);
if (oldNode) {
var meta = this.nodeMetaMap.get(oldNode);
if (meta) this.nodeMetaMap.set(n, meta);
}
this.idNodeMap.set(id, n);
};
Mirror.prototype.reset = function () {
this.idNodeMap = new Map();
this.nodeMetaMap = new WeakMap();
};
return Mirror;
}();
function createMirror() {
return new Mirror();
}
function maskInputValue(_a) {
var maskInputOptions = _a.maskInputOptions,
tagName = _a.tagName,
type = _a.type,
value = _a.value,
maskInputFn = _a.maskInputFn;
var text = value || '';
if (maskInputOptions[tagName.toLowerCase()] || maskInputOptions[type]) {
if (maskInputFn) {
text = maskInputFn(text);
} else {
text = '*'.repeat(text.length);
}
}
return text;
}
var ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';
function is2DCanvasBlank(canvas) {
var ctx = canvas.getContext('2d');
if (!ctx) return true;
var chunkSize = 50;
for (var x = 0; x < canvas.width; x += chunkSize) {
for (var y = 0; y < canvas.height; y += chunkSize) {
var getImageData = ctx.getImageData;
var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;
var pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);
if (pixelBuffer.some(function (pixel) {
return pixel !== 0;
})) return false;
}
}
return true;
}
var _id = 1;
var tagNameRegex = new RegExp('[^a-z0-9-_:]');
var IGNORED_NODE = -2;
function genId() {
return _id++;
}
function getValidTagName(element) {
if (element instanceof HTMLFormElement) {
return 'form';
}
var processedTagName = element.tagName.toLowerCase().trim();
if (tagNameRegex.test(processedTagName)) {
return 'div';
}
return processedTagName;
}
function stringifyStyleSheet(sheet) {
return sheet.cssRules ? Array.from(sheet.cssRules).map(function (rule) {
return rule.cssText || '';
}).join('') : '';
}
function extractOrigin(url) {
var origin = '';
if (url.indexOf('//') > -1) {
origin = url.split('/').slice(0, 3).join('/');
} else {
origin = url.split('/')[0];
}
origin = origin.split('?')[0];
return origin;
}
var canvasService;
var canvasCtx;
var URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
var RELATIVE_PATH = /^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/;
var DATA_URI = /^(data:)([^,]*),(.*)/i;
function absoluteToStylesheet(cssText, href) {
return (cssText || '').replace(URL_IN_CSS_REF, function (origin, quote1, path1, quote2, path2, path3) {
var filePath = path1 || path2 || path3;
var maybeQuote = quote1 || quote2 || '';
if (!filePath) {
return origin;
}
if (!RELATIVE_PATH.test(filePath)) {
return "url(".concat(maybeQuote).concat(filePath).concat(maybeQuote, ")");
}
if (DATA_URI.test(filePath)) {
return "url(".concat(maybeQuote).concat(filePath).concat(maybeQuote, ")");
}
if (filePath[0] === '/') {
return "url(".concat(maybeQuote).concat(extractOrigin(href) + filePath).concat(maybeQuote, ")");
}
var stack = href.split('/');
var parts = filePath.split('/');
stack.pop();
for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
var part = parts_1[_i];
if (part === '.') {
continue;
} else if (part === '..') {
stack.pop();
} else {
stack.push(part);
}
}
return "url(".concat(maybeQuote).concat(stack.join('/')).concat(maybeQuote, ")");
});
}
var SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
var SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
function getAbsoluteSrcsetString(doc, attributeValue) {
if (attributeValue.trim() === '') {
return attributeValue;
}
var pos = 0;
function collectCharacters(regEx) {
var chars;
var match = regEx.exec(attributeValue.substring(pos));
if (match) {
chars = match[0];
pos += chars.length;
return chars;
}
return '';
}
var output = [];
while (true) {
collectCharacters(SRCSET_COMMAS_OR_SPACES);
if (pos >= attributeValue.length) {
break;
}
var url = collectCharacters(SRCSET_NOT_SPACES);
if (url.slice(-1) === ',') {
url = absoluteToDoc(doc, url.substring(0, url.length - 1));
output.push(url);
} else {
var descriptorsStr = '';
url = absoluteToDoc(doc, url);
var inParens = false;
while (true) {
var c = attributeValue.charAt(pos);
if (c === '') {
output.push((url + descriptorsStr).trim());
break;
} else if (!inParens) {
if (c === ',') {
pos += 1;
output.push((url + descriptorsStr).trim());
break;
} else if (c === '(') {
inParens = true;
}
} else {
if (c === ')') {
inParens = false;
}
}
descriptorsStr += c;
pos += 1;
}
}
}
return output.join(', ');
}
function absoluteToDoc(doc, attributeValue) {
if (!attributeValue || attributeValue.trim() === '') {
return attributeValue;
}
var a = doc.createElement('a');
a.href = attributeValue;
return a.href;
}
function isSVGElement(el) {
return Boolean(el.tagName === 'svg' || el.ownerSVGElement);
}
function getHref() {
var a = document.createElement('a');
a.href = '';
return a.href;
}
function transformAttribute(doc, tagName, name, value) {
if (name === 'src' || name === 'href' && value && !(tagName === 'use' && value[0] === '#')) {
return absoluteToDoc(doc, value);
} else if (name === 'xlink:href' && value && value[0] !== '#') {
return absoluteToDoc(doc, value);
} else if (name === 'background' && value && (tagName === 'table' || tagName === 'td' || tagName === 'th')) {
return absoluteToDoc(doc, value);
} else if (name === 'srcset' && value) {
return getAbsoluteSrcsetString(doc, value);
} else if (name === 'style' && value) {
return absoluteToStylesheet(value, getHref());
} else if (tagName === 'object' && name === 'data' && value) {
return absoluteToDoc(doc, value);
} else {
return value;
}
}
function _isBlockedElement(element, blockClass, blockSelector) {
if (typeof blockClass === 'string') {
if (element.classList.contains(blockClass)) {
return true;
}
} else {
for (var eIndex = element.classList.length; eIndex--;) {
var className = element.classList[eIndex];
if (blockClass.test(className)) {
return true;
}
}
}
if (blockSelector) {
return element.matches(blockSelector);
}
return false;
}
function classMatchesRegex(node, regex, checkAncestors) {
if (!node) return false;
if (node.nodeType !== node.ELEMENT_NODE) {
if (!checkAncestors) return false;
return classMatchesRegex(node.parentNode, regex, checkAncestors);
}
for (var eIndex = node.classList.length; eIndex--;) {
var className = node.classList[eIndex];
if (regex.test(className)) {
return true;
}
}
if (!checkAncestors) return false;
return classMatchesRegex(node.parentNode, regex, checkAncestors);
}
function needMaskingText(node, maskTextClass, maskTextSelector) {
var el = node.nodeType === node.ELEMENT_NODE ? node : node.parentElement;
if (el === null) return false;
if (typeof maskTextClass === 'string') {
if (el.classList.contains(maskTextClass)) return true;
if (el.closest(".".concat(maskTextClass))) return true;
} else {
if (classMatchesRegex(el, maskTextClass, true)) return true;
}
if (maskTextSelector) {
if (el.matches(maskTextSelector)) return true;
if (el.closest(maskTextSelector)) return true;
}
return false;
}
function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
var win = iframeEl.contentWindow;
if (!win) {
return;
}
var fired = false;
var readyState;
try {
readyState = win.document.readyState;
} catch (error) {
return;
}
if (readyState !== 'complete') {
var timer_1 = setTimeout(function () {
if (!fired) {
listener();
fired = true;
}
}, iframeLoadTimeout);
iframeEl.addEventListener('load', function () {
clearTimeout(timer_1);
fired = true;
listener();
});
return;
}
var blankUrl = 'about:blank';
if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === '') {
setTimeout(listener, 0);
return iframeEl.addEventListener('load', listener);
}
iframeEl.addEventListener('load', listener);
}
function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
var fired = false;
var styleSheetLoaded;
try {
styleSheetLoaded = link.sheet;
} catch (error) {
return;
}
if (styleSheetLoaded) return;
var timer = setTimeout(function () {
if (!fired) {
listener();
fired = true;
}
}, styleSheetLoadTimeout);
link.addEventListener('load', function () {
clearTimeout(timer);
fired = true;
listener();
});
}
function serializeNode(n, options) {
var doc = options.doc,
mirror = options.mirror,
blockClass = options.blockClass,
blockSelector = options.blockSelector,
maskTextClass = options.maskTextClass,
maskTextSelector = options.maskTextSelector,
inlineStylesheet = options.inlineStylesheet,
_a = options.maskInputOptions,
maskInputOptions = _a === void 0 ? {} : _a,
maskTextFn = options.maskTextFn,
maskInputFn = options.maskInputFn,
_b = options.dataURLOptions,
dataURLOptions = _b === void 0 ? {} : _b,
inlineImages = options.inlineImages,
recordCanvas = options.recordCanvas,
keepIframeSrcFn = options.keepIframeSrcFn,
_c = options.newlyAddedElement,
newlyAddedElement = _c === void 0 ? false : _c;
var rootId = getRootId(doc, mirror);
switch (n.nodeType) {
case n.DOCUMENT_NODE:
if (n.compatMode !== 'CSS1Compat') {
return {
type: NodeType.Document,
childNodes: [],
compatMode: n.compatMode
};
} else {
return {
type: NodeType.Document,
childNodes: []
};
}
case n.DOCUMENT_TYPE_NODE:
return {
type: NodeType.DocumentType,
name: n.name,
publicId: n.publicId,
systemId: n.systemId,
rootId: rootId
};
case n.ELEMENT_NODE:
return serializeElementNode(n, {
doc: doc,
blockClass: blockClass,
blockSelector: blockSelector,
inlineStylesheet: inlineStylesheet,
maskInputOptions: maskInputOptions,
maskInputFn: maskInputFn,
dataURLOptions: dataURLOptions,
inlineImages: inlineImages,
recordCanvas: recordCanvas,
keepIframeSrcFn: keepIframeSrcFn,
newlyAddedElement: newlyAddedElement,
rootId: rootId
});
case n.TEXT_NODE:
return serializeTextNode(n, {
maskTextClass: maskTextClass,
maskTextSelector: maskTextSelector,
maskTextFn: maskTextFn,
rootId: rootId
});
case n.CDATA_SECTION_NODE:
return {
type: NodeType.CDATA,
textContent: '',
rootId: rootId
};
case n.COMMENT_NODE:
return {
type: NodeType.Comment,
textContent: n.textContent || '',
rootId: rootId
};
default:
return false;
}
}
function getRootId(doc, mirror) {
if (!mirror.hasNode(doc)) return undefined;
var docId = mirror.getId(doc);
return docId === 1 ? undefined : docId;
}
function serializeTextNode(n, options) {
var _a;
var maskTextClass = options.maskTextClass,
maskTextSelector = options.maskTextSelector,
maskTextFn = options.maskTextFn,
rootId = options.rootId;
var parentTagName = n.parentNode && n.parentNode.tagName;
var textContent = n.textContent;
var isStyle = parentTagName === 'STYLE' ? true : undefined;
var isScript = parentTagName === 'SCRIPT' ? true : undefined;
if (isStyle && textContent) {
try {
if (n.nextSibling || n.previousSibling) {} else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {
textContent = stringifyStyleSheet(n.parentNode.sheet);
}
} catch (err) {
console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(err), n);
}
textContent = absoluteToStylesheet(textContent, getHref());
}
if (isScript) {
textContent = 'SCRIPT_PLACEHOLDER';
}
if (!isStyle && !isScript && textContent && needMaskingText(n, maskTextClass, maskTextSelector)) {
textContent = maskTextFn ? maskTextFn(textContent) : textContent.replace(/[\S]/g, '*');
}
return {
type: NodeType.Text,
textContent: textContent || '',
isStyle: isStyle,
rootId: rootId
};
}
function serializeElementNode(n, options) {
var doc = options.doc,
blockClass = options.blockClass,
blockSelector = options.blockSelector,
inlineStylesheet = options.inlineStylesheet,
_a = options.maskInputOptions,
maskInputOptions = _a === void 0 ? {} : _a,
maskInputFn = options.maskInputFn,
_b = options.dataURLOptions,
dataURLOptions = _b === void 0 ? {} : _b,
inlineImages = options.inlineImages,
recordCanvas = options.recordCanvas,
keepIframeSrcFn = options.keepIframeSrcFn,
_c = options.newlyAddedElement,
newlyAddedElement = _c === void 0 ? false : _c,
rootId = options.rootId;
var needBlock = _isBlockedElement(n, blockClass, blockSelector);
var tagName = getValidTagName(n);
var attributes = {};
var len = n.attributes.length;
for (var i = 0; i < len; i++) {
var attr = n.attributes[i];
attributes[attr.name] = transformAttribute(doc, tagName, attr.name, attr.value);
}
if (tagName === 'link' && inlineStylesheet) {
var stylesheet = Array.from(doc.styleSheets).find(function (s) {
return s.href === n.href;
});
var cssText = null;
if (stylesheet) {
cssText = getCssRulesString(stylesheet);
}
if (cssText) {
delete attributes.rel;
delete attributes.href;
attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);
}
}
if (tagName === 'style' && n.sheet && !(n.innerText || n.textContent || '').trim().length) {
var cssText = getCssRulesString(n.sheet);
if (cssText) {
attributes._cssText = absoluteToStylesheet(cssText, getHref());
}
}
if (tagName === 'input' || tagName === 'textarea' || tagName === 'select') {
var value = n.value;
var checked = n.checked;
if (attributes.type !== 'radio' && attributes.type !== 'checkbox' && attributes.type !== 'submit' && attributes.type !== 'button' && value) {
attributes.value = maskInputValue({
type: attributes.type,
tagName: tagName,
value: value,
maskInputOptions: maskInputOptions,
maskInputFn: maskInputFn
});
} else if (checked) {
attributes.checked = checked;
}
}
if (tagName === 'option') {
if (n.selected && !maskInputOptions['select']) {
attributes.selected = true;
} else {
delete attributes.selected;
}
}
if (tagName === 'canvas' && recordCanvas) {
if (n.__context === '2d') {
if (!is2DCanvasBlank(n)) {
attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);
}
} else if (!('__context' in n)) {
var canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);
var blankCanvas = document.createElement('canvas');
blankCanvas.width = n.width;
blankCanvas.height = n.height;
var blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);
if (canvasDataURL !== blankCanvasDataURL) {
attributes.rr_dataURL = canvasDataURL;
}
}
}
if (tagName === 'img' && inlineImages) {
if (!canvasService) {
canvasService = doc.createElement('canvas');
canvasCtx = canvasService.getContext('2d');
}
var image_1 = n;
var oldValue_1 = image_1.crossOrigin;
image_1.crossOrigin = 'anonymous';
var recordInlineImage = function () {
try {
canvasService.width = image_1.naturalWidth;
canvasService.height = image_1.naturalHeight;
canvasCtx.drawImage(image_1, 0, 0);
attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
} catch (err) {
console.warn("Cannot inline img src=".concat(image_1.currentSrc, "! Error: ").concat(err));
}
oldValue_1 ? attributes.crossOrigin = oldValue_1 : image_1.removeAttribute('crossorigin');
};
if (image_1.complete && image_1.naturalWidth !== 0) recordInlineImage();else image_1.onload = recordInlineImage;
}
if (tagName === 'audio' || tagName === 'video') {
attributes.rr_mediaState = n.paused ? 'paused' : 'played';
attributes.rr_mediaCurrentTime = n.currentTime;
}
if (!newlyAddedElement) {
if (n.scrollLeft) {
attributes.rr_scrollLeft = n.scrollLeft;
}
if (n.scrollTop) {
attributes.rr_scrollTop = n.scrollTop;
}
}
if (needBlock) {
var _d = n.getBoundingClientRect(),
width = _d.width,
height = _d.height;
attributes = {
"class": attributes["class"],
rr_width: "".concat(width, "px"),
rr_height: "".concat(height, "px")
};
}
if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {
if (!n.contentDocument) {
attributes.rr_src = attributes.src;
}
delete attributes.src;
}
return {
type: NodeType.Element,
tagName: tagName,
attributes: attributes,
childNodes: [],
isSVG: isSVGElement(n) || undefined,
needBlock: needBlock,
rootId: rootId
};
}
function lowerIfExists(maybeAttr) {
if (maybeAttr === undefined) {
return '';
} else {
return maybeAttr.toLowerCase();
}
}
function slimDOMExcluded(sn, slimDOMOptions) {
if (slimDOMOptions.comment && sn.type === NodeType.Comment) {
return true;
} else if (sn.type === NodeType.Element) {
if (slimDOMOptions.script && (sn.tagName === 'script' || sn.tagName === 'link' && (sn.attributes.rel === 'preload' || sn.attributes.rel === 'modulepreload') && sn.attributes.as === 'script' || sn.tagName === 'link' && sn.attributes.rel === 'prefetch' && typeof sn.attributes.href === 'string' && sn.attributes.href.endsWith('.js'))) {
return true;
} else if (slimDOMOptions.headFavicon && (sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon' || sn.tagName === 'meta' && (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) || lowerIfExists(sn.attributes.name) === 'application-name' || lowerIfExists(sn.attributes.rel) === 'icon' || lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' || lowerIfExists(sn.attributes.rel) === 'shortcut icon'))) {
return true;
} else if (sn.tagName === 'meta') {
if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {
return true;
} else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === 'pinterest')) {
return true;
} else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === 'robots' || lowerIfExists(sn.attributes.name) === 'googlebot' || lowerIfExists(sn.attributes.name) === 'bingbot')) {
return true;
} else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes['http-equiv'] !== undefined) {
return true;
} else if (slimDOMOptions.headMetaAuthorship && (lowerIfExists(sn.attributes.name) === 'author' || lowerIfExists(sn.attributes.name) === 'generator' || lowerIfExists(sn.attributes.name) === 'framework' || lowerIfExists(sn.attributes.name) === 'publisher' || lowerIfExists(sn.attributes.name) === 'progid' || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) {
return true;
} else if (slimDOMOptions.headMetaVerification && (lowerIfExists(sn.attributes.name) === 'google-site-verification' || lowerIfExists(sn.attributes.name) === 'yandex-verification' || lowerIfExists(sn.attributes.name) === 'csrf-token' || lowerIfExists(sn.attributes.name) === 'p:domain_verify' || lowerIfExists(sn.attributes.name) === 'verify-v1' || lowerIfExists(sn.attributes.name) === 'verification' || lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {
return true;
}
}
}
return false;
}
function serializeNodeWithId(n, options) {
var doc = options.doc,
mirror = options.mirror,
blockClass = options.blockClass,
blockSelector = options.blockSelector,
maskTextClass = options.maskTextClass,
maskTextSelector = options.maskTextSelector,
_a = options.skipChild,
skipChild = _a === void 0 ? false : _a,
_b = options.inlineStylesheet,
inlineStylesheet = _b === void 0 ? true : _b,
_c = options.maskInputOptions,
maskInputOptions = _c === void 0 ? {} : _c,
maskTextFn = options.maskTextFn,
maskInputFn = options.maskInputFn,
slimDOMOptions = options.slimDOMOptions,
_d = options.dataURLOptions,
dataURLOptions = _d === void 0 ? {} : _d,
_e = options.inlineImages,
inlineImages = _e === void 0 ? false : _e,
_f = options.recordCanvas,
recordCanvas = _f === void 0 ? false : _f,
onSerialize = options.onSerialize,
onIframeLoad = options.onIframeLoad,
_g = options.iframeLoadTimeout,
iframeLoadTimeout = _g === void 0 ? 5000 : _g,
onStylesheetLoad = options.onStylesheetLoad,
_h = options.stylesheetLoadTimeout,
stylesheetLoadTimeout = _h === void 0 ? 5000 : _h,
_j = options.keepIframeSrcFn,
keepIframeSrcFn = _j === void 0 ? function () {
return false;
} : _j,
_k = options.newlyAddedElement,
newlyAddedElement = _k === void 0 ? false : _k;
var _l = options.preserveWhiteSpace,
preserveWhiteSpace = _l === void 0 ? true : _l;
var _serializedNode = serializeNode(n, {
doc: doc,
mirror: mirror,
blockClass: blockClass,
blockSelector: blockSelector,
maskTextClass: maskTextClass,
maskTextSelector: maskTextSelector,
inlineStylesheet: inlineStylesheet,
maskInputOptions: maskInputOptions,
maskTextFn: maskTextFn,
maskInputFn: maskInputFn,
dataURLOptions: dataURLOptions,
inlineImages: inlineImages,
recordCanvas: recordCanvas,
keepIframeSrcFn: keepIframeSrcFn,
newlyAddedElement: newlyAddedElement
});
if (!_serializedNode) {
console.warn(n, 'not serialized');
return null;
}
var id;
if (mirror.hasNode(n)) {
id = mirror.getId(n);
} else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType.Text && !_serializedNode.isStyle && !_serializedNode.textContent.replace(/^\s+|\s+$/gm, '').length) {
id = IGNORED_NODE;
} else {
id = genId();
}
var serializedNode = Object.assign(_serializedNode, {
id: id
});
mirror.add(n, serializedNode);
if (id === IGNORED_NODE) {
return null;
}
if (onSerialize) {
onSerialize(n);
}
var recordChild = !skipChild;
if (serializedNode.type === NodeType.Element) {
recordChild = recordChild && !serializedNode.needBlock;
delete serializedNode.needBlock;
var shadowRoot = n.shadowRoot;
if (shadowRoot && isNativeShadowDom(shadowRoot)) serializedNode.isShadowHost = true;
}
if ((serializedNode.type === NodeType.Document || serializedNode.type === NodeType.Element) && recordChild) {
if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType.Element && serializedNode.tagName === 'head') {
preserveWhiteSpace = false;
}
var bypassOptions = {
doc: doc,
mirror: mirror,
blockClass: blockClass,
blockSelector: blockSelector,
maskTextClass: maskTextClass,
maskTextSelector: maskTextSelector,
skipChild: skipChild,
inlineStylesheet: inlineStylesheet,
maskInputOptions: maskInputOptions,
maskTextFn: maskTextFn,
maskInputFn: maskInputFn,
slimDOMOptions: slimDOMOptions,
dataURLOptions: dataURLOptions,
inlineImages: inlineImages,
recordCanvas: recordCanvas,
preserveWhiteSpace: preserveWhiteSpace,
onSerialize: onSerialize,
onIframeLoad: onIframeLoad,
iframeLoadTimeout: iframeLoadTimeout,
onStylesheetLoad: onStylesheetLoad,
stylesheetLoadTimeout: stylesheetLoadTimeout,
keepIframeSrcFn: keepIframeSrcFn
};
for (var _i = 0, _m = Array.from(n.childNodes); _i < _m.length; _i++) {
var childN = _m[_i];
var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
if (serializedChildNode) {
serializedNode.childNodes.push(serializedChildNode);
}
}
if (isElement(n) && n.shadowRoot) {
for (var _o = 0, _p = Array.from(n.shadowRoot.childNodes); _o < _p.length; _o++) {
var childN = _p[_o];
var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
if (serializedChildNode) {
isNativeShadowDom(n.shadowRoot) && (serializedChildNode.isShadow = true);
serializedNode.childNodes.push(serializedChildNode);
}
}
}
}
if (n.parentNode && isShadowRoot(n.parentNode) && isNativeShadowDom(n.parentNode)) {
serializedNode.isShadow = true;
}
if (serializedNode.type === NodeType.Element && serializedNode.tagName === 'iframe') {
onceIframeLoaded(n, function () {
var iframeDoc = n.contentDocument;
if (iframeDoc && onIframeLoad) {
var serializedIframeNode = serializeNodeWithId(iframeDoc, {
doc: iframeDoc,
mirror: mirror,
blockClass: blockClass,
blockSelector: blockSelector,
maskTextClass: maskTextClass,
maskTextSelector: maskTextSelector,
skipChild: false,
inlineStylesheet: inlineStylesheet,
maskInputOptions: maskInputOptions,
maskTextFn: maskTextFn,
maskInputFn: maskInputFn,
slimDOMOptions: slimDOMOptions,
dataURLOptions: dataURLOptions,
inlineImages: inlineImages,
recordCanvas: recordCanvas,
preserveWhiteSpace: preserveWhiteSpace,
onSerialize: onSerialize,
onIframeLoad: onIframeLoad,
iframeLoadTimeout: iframeLoadTimeout,
onStylesheetLoad: onStylesheetLoad,
stylesheetLoadTimeout: stylesheetLoadTimeout,
keepIframeSrcFn: keepIframeSrcFn
});
if (serializedIframeNode) {
onIframeLoad(n, serializedIframeNode);
}
}
}, iframeLoadTimeout);
}
if (serializedNode.type === NodeType.Element && serializedNode.tagName === 'link' && serializedNode.attributes.rel === 'stylesheet') {
onceStylesheetLoaded(n, function () {
if (onStylesheetLoad) {
var serializedLinkNode = serializeNodeWithId(n, {
doc: doc,
mirror: mirror,
blockClass: blockClass,
blockSelector: blockSelector,
maskTextClass: maskTextClass,
maskTextSelector: maskTextSelector,
skipChild: false,
inlineStylesheet: inlineStylesheet,
maskInputOptions: maskInputOptions,
maskTextFn: maskTextFn,
maskInputFn: maskInputFn,
slimDOMOptions: slimDOMOptions,
dataURLOptions: dataURLOptions,
inlineImages: inlineImages,
recordCanvas: recordCanvas,
preserveWhiteSpace: preserveWhiteSpace,
onSerialize: onSerialize,
onIframeLoad: onIframeLoad,
iframeLoadTimeout: iframeLoadTimeout,
onStylesheetLoad: onStylesheetLoad,
stylesheetLoadTimeout: stylesheetLoadTimeout,
keepIframeSrcFn: keepIframeSrcFn
});
if (serializedLinkNode) {
onStylesheetLoad(n, serializedLinkNode);
}
}
}, stylesheetLoadTimeout);
}
return serializedNode;
}
function snapshot(n, options) {
var _a = options || {},
_b = _a.mirror,
mirror = _b === void 0 ? new Mirror() : _b,
_c = _a.blockClass,
blockClass = _c === void 0 ? 'rr-block' : _c,
_d = _a.blockSelector,
blockSelector = _d === void 0 ? null : _d,
_e = _a.maskTextClass,
maskTextClass = _e === void 0 ? 'rr-mask' : _e,
_f = _a.maskTextSelector,
maskTextSelector = _f === void 0 ? null : _f,
_g = _a.inlineStylesheet,
inlineStylesheet = _g === void 0 ? true : _g,
_h = _a.inlineImages,
inlineImages = _h === void 0 ? false : _h,
_j = _a.recordCanvas,
recordCanvas = _j === void 0 ? false : _j,
_k = _a.maskAllInputs,
maskAllInputs = _k === void 0 ? false : _k,
maskTextFn = _a.maskTextFn,
maskInputFn = _a.maskInputFn,
_l = _a.slimDOM,
slimDOM = _l === void 0 ? false : _l,
dataURLOptions = _a.dataURLOptions,
preserveWhiteSpace = _a.preserveWhiteSpace,
onSerialize = _a.onSerialize,
onIframeLoad = _a.onIframeLoad,
iframeLoadTimeout = _a.iframeLoadTimeout,
onStylesheetLoad = _a.onStylesheetLoad,
stylesheetLoadTimeout = _a.stylesheetLoadTimeout,
_m = _a.keepIframeSrcFn,
keepIframeSrcFn = _m === void 0 ? function () {
return false;
} : _m;
var maskInputOptions = maskAllInputs === true ? {
color: true,
date: true,
'datetime-local': true,
email: true,
month: true,
number: true,
range: true,
search: true,
tel: true,
text: true,
time: true,
url: true,
week: true,
textarea: true,
select: true,
password: true
} : maskAllInputs === false ? {
password: true
} : maskAllInputs;
var slimDOMOptions = slimDOM === true || slimDOM === 'all' ? {
script: true,
comment: true,
headFavicon: true,
headWhitespace: true,
headMetaDescKeywords: slimDOM === 'all',
headMetaSocial: true,
headMetaRobots: true,
headMetaHttpEquiv: true,
headMetaAuthorship: true,
headMetaVerification: true
} : slimDOM === false ? {} : slimDOM;
return serializeNodeWithId(n, {
doc: n,
mirror: mirror,
blockClass: blockClass,
blockSelector: blockSelector,
maskTextClass: maskTextClass,
maskTextSelector: maskTextSelector,
skipChild: false,
inlineStylesheet: inlineStylesheet,
maskInputOptions: maskInputOptions,
maskTextFn: maskTextFn,
maskInputFn: maskInputFn,
slimDOMOptions: slimDOMOptions,
dataURLOptions: dataURLOptions,
inlineImages: inlineImages,
recordCanvas: recordCanvas,
preserveWhiteSpace: preserveWhiteSpace,
onSerialize: onSerialize,
onIframeLoad: onIframeLoad,
iframeLoadTimeout: iframeLoadTimeout,
onStylesheetLoad: onStylesheetLoad,
stylesheetLoadTimeout: stylesheetLoadTimeout,
keepIframeSrcFn: keepIframeSrcFn,
newlyAddedElement: false
});
}
function on(type, fn) {
let target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document;
const options = {
capture: true,
passive: true
};
target.addEventListener(type, fn, options);
return () => target.removeEventListener(type, fn, options);
}
const DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' + '\r\n' + 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' + '\r\n' + 'or you can use record.mirror to access the mirror instance during recording.';
let _mirror = {
map: {},
getId() {
console.error(DEPARTED_MIRROR_ACCESS_WARNING);
return -1;
},
getNode() {
console.error(DEPARTED_MIRROR_ACCESS_WARNING);
return null;
},
removeNodeFromMap() {
console.error(DEPARTED_MIRROR_ACCESS_WARNING);
},
has() {
console.error(DEPARTED_MIRROR_ACCESS_WARNING);
return false;
},
reset() {
console.error(DEPARTED_MIRROR_ACCESS_WARNING);
}
};
if (typeof window !== 'undefined' && window.Proxy && window.Reflect) {
_mirror = new Proxy(_mirror, {
get(target, prop, receiver) {
if (prop === 'map') {
console.error(DEPARTED_MIRROR_ACCESS_WARNING);
}
return Reflect.get(target, prop, receiver);
}
});
}
function throttle(func, wait) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
let timeout = null;
let previous = 0;
return function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
const now = Date.now();
if (!previous && options.leading === false) {
previous = now;
}
const remaining = wait - (now - previous);
const context = this;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
func.apply(context, args);
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(() => {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
func.apply(context, args);
}, remaining);
}
};
}
function hookSetter(target, key, d, isRevoked) {
let win = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : window;
const original = win.Object.getOwnPropertyDescriptor(target, key);
win.Object.defineProperty(target, key, isRevoked ? d : {
set(value) {
setTimeout(() => {
d.set.call(this, value);
}, 0);
if (original && original.set) {
original.set.call(this, value);
}
}
});
return () => hookSetter(target, key, original || {}, true);
}
function patch(source, name, replacement) {
try {
if (!(name in source)) {
return () => {};
}
const original = source[name];
const wrapped = replacement(original);
if (typeof wrapped === 'function') {
wrapped.prototype = wrapped.prototype || {};
Object.defineProperties(wrapped, {
__rrweb_original__: {
enumerable: false,
value: original
}
});
}
source[name] = wrapped;
return () => {
source[name] = original;
};
} catch (_a) {
return () => {};
}
}
function getWindowScroll(win) {
var _a, _b, _c, _d, _e, _f;
const doc = win.document;
return {
left: doc.scrollingElement ? doc.scrollingElement.scrollLeft : win.pageXOffset !== undefined ? win.pageXOffset : (doc === null || doc === void 0 ? void 0 : doc.documentElement.scrollLeft) || ((_b = (_a = doc === null || doc === void 0 ? void 0 : doc.body) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.scrollLeft) || ((_c = doc === null || doc === void 0 ? void 0 : doc.body) === null || _c === void 0 ? void 0 : _c.scrollLeft) || 0,
top: doc.scrollingElement ? doc.scrollingElement.scrollTop : win.pageYOffset !== undefined ? win.pageYOffset : (doc === null || doc === void 0 ? void 0 : doc.documentElement.scrollTop) || ((_e = (_d = doc === null || doc === void 0 ? void 0 : doc.body) === null || _d === void 0 ? void 0 : _d.parentElement) === null || _e === void 0 ? void 0 : _e.scrollTop) || ((_f = doc === null || doc === void 0 ? void 0 : doc.body) === null || _f === void 0 ? void 0 : _f.scrollTop) || 0
};
}
function getWindowHeight() {
return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;
}
function getWindowWidth() {
return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;
}
function isBlocked(node, blockClass, blockSelector, checkAncestors) {
if (!node) {
return false;
}
const el = node.nodeType === node.ELEMENT_NODE ? node : node.parentElement;
if (!el) return false;
if (typeof blockClass === 'string') {
if (el.classList.contains(blockClass)) return true;
if (checkAncestors && el.closest('.' + blockClass) !== null) return true;
} else {
if (classMatchesRegex(el, blockClass, checkAncestors)) return true;
}
if (blockSelector) {
if (el.matches(blockSelector)) return true;
if (checkAncestors && el.closest(blockSelector) !== null) return true;
}
return false;
}
function isSerialized(n, mirror) {
return mirror.getId(n) !== -1;
}
function isIgnored(n, mirror) {
return mirror.getId(n) === IGNORED_NODE;
}
function isAncestorRemoved(target, mirror) {
if (isShadowRoot(target)) {
return false;
}
const id = mirror.getId(target);
if (!mirror.has(id)) {
return true;
}
if (target.parentNode && target.parentNode.nodeType === target.DOCUMENT_NODE) {
return false;
}
if (!target.parentNode) {
return true;
}
return isAncestorRemoved(target.parentNode, mirror);
}
function isTouchEvent(event) {
return Boolean(event.changedTouches);
}
function polyfill() {
var _this = this;
let win = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window;
if ('NodeList' in win && !win.NodeList.prototype.forEach) {
win.NodeList.prototype.forEach = Array.prototype.forEach;
}
if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {
win.DOMTokenList.prototype.forEach = Array.prototype.forEach;
}
if (!Node.prototype.contains) {
Node.prototype.contains = function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
let node = args[0];
if (!(0 in args)) {
throw new TypeError('1 argument is required');
}
do {
if (_this === node) {
return true;
}
} while (node = node && node.parentNode);
return false;
};
}
}
function isSerializedIframe(n, mirror) {
return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));
}
function isSerializedStylesheet(n, mirror) {
return Boolean(n.nodeName === 'LINK' && n.nodeType === n.ELEMENT_NODE && n.getAttribute && n.getAttribute('rel') === 'stylesheet' && mirror.getMeta(n));
}
function hasShadowRoot(n) {
return Boolean(n === null || n === void 0 ? void 0 : n.shadowRoot);
}
class StyleSheetMirror {
constructor() {
this.id = 1;
this.styleIDMap = new WeakMap();
this.idStyleMap = new Map();
}
getId(stylesheet) {
var _a;
return (_a = this.styleIDMap.get(stylesheet)) !== null && _a !== void 0 ? _a : -1;
}
has(stylesheet) {
return this.styleIDMap.has(stylesheet);
}
add(stylesheet, id) {
if (this.has(stylesheet)) return this.getId(stylesheet);
let newId;
if (id === undefined) {
newId = this.id++;
} else newId = id;
this.styleIDMap.set(stylesheet, newId);
this.idStyleMap.set(newId, stylesheet);
return newId;
}
getStyle(id) {
return this.idStyleMap.get(id) || null;
}
reset() {
this.styleIDMap = new WeakMap();
this.idStyleMap = new Map();
this.id = 1;
}
generateId() {
return this.id++;
}
}
function getShadowHost(n) {
var _a, _b;
let shadowHost = null;
if (((_b = (_a = n.getRootNode) === null || _a === void 0 ? void 0 : _a.call(n)) === null || _b === void 0 ? void 0 : _b.nodeType) === Node.DOCUMENT_FRAGMENT_NODE && n.getRootNode().host) shadowHost = n.getRootNode().host;
return shadowHost;
}
function getRootShadowHost(n) {
let rootShadowHost = n;
let shadowHost;
while (shadowHost = getShadowHost(rootShadowHost)) rootShadowHost = shadowHost;
return rootShadowHost;
}
function shadowHostInDom(n) {
const doc = n.ownerDocument;
if (!doc) return false;
const shadowHost = getRootShadowHost(n);
return doc.contains(shadowHost);
}
function inDom(n) {
const doc = n.ownerDocument;
if (!doc) return false;
return doc.contains(n) || shadowHostInDom(n);
}
var EventType = /* @__PURE__ */(EventType2 => {
EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
EventType2[EventType2["Load"] = 1] = "Load";
EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
EventType2[EventType2["Meta"] = 4] = "Meta";
EventType2[EventType2["Custom"] = 5] = "Custom";
EventType2[EventType2["Plugin"] = 6] = "Plugin";
return EventType2;
})(EventType || {});
var IncrementalSource = /* @__PURE__ */(IncrementalSource2 => {
IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
return IncrementalSource2;
})(IncrementalSource || {});
var MouseInteractions = /* @__PURE__ */(MouseInteractions2 => {
MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
return MouseInteractions2;
})(MouseInteractions || {});
var CanvasContext = /* @__PURE__ */(CanvasContext2 => {
CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
return CanvasContext2;
})(CanvasContext || {});
function isNodeInLinkedList(n) {
return '__ln' in n;
}
class DoubleLinkedList {
constructor() {
this.length = 0;
this.head = null;
}
get(position) {
if (position >= this.length) {
throw new Error('Position outside of list range');
}
let current = this.head;
for (let index = 0; index < position; index++) {
current = (current === null || current === void 0 ? void 0 : current.next) || null;
}
return current;
}
addNode(n) {
const node = {
value: n,
previous: null,
next: null
};
n.__ln = node;
if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {
const current = n.previousSibling.__ln.next;
node.next = current;
node.previous = n.previousSibling.__ln;
n.previousSibling.__ln.next = node;
if (current) {
current.previous = node;
}
} else if (n.nextSibling && isNodeInLinkedList(n.nextSibling) && n.nextSibling.__ln.previous) {
const current = n.nextSibling.__ln.previous;
node.previous = current;
node.next = n.nextSibling.__ln;
n.nextSibling.__ln.previous = node;
if (current) {
current.next = node;
}
} else {
if (this.head) {
this.head.previous = node;
}
node.next = this.head;
this.head = node;
}
this.length++;
}
removeNode(n) {
const current = n.__ln;
if (!this.head) {
return;
}
if (!current.previous) {
this.head = current.next;
if (this.head) {
this.head.previous = null;
}
} else {
current.previous.next = current.next;
if (current.next) {
current.next.previous = current.previous;
}
}
if (n.__ln) {
delete n.__ln;
}
this.length--;
}
}
const moveKey = (id, parentId) => `${id}@${parentId}`;
class MutationBuffer {
constructor() {
this.frozen = false;
this.locked = false;
this.texts = [];
this.attributes = [];
this.removes = [];
this.mapRemoves = [];
this.movedMap = {};
this.addedSet = new Set();
this.movedSet = new Set();
this.droppedSet = new Set();
this.processMutations = mutations => {
mutations.forEach(this.processMutation);
this.emit();
};
this.emit = () => {
if (this.frozen || this.locked) {
return;
}
const adds = [];
const addList = new DoubleLinkedList();
const getNextId = n => {
let ns = n;
let nextId = IGNORED_NODE;
while (nextId === IGNORED_NODE) {
ns = ns && ns.nextSibling;
nextId = ns && this.mirror.getId(ns);
}
return nextId;
};
const pushAdd = n => {
if (!n.parentNode || !inDom(n)) {
return;
}
const parentId = isShadowRoot(n.parentNode) ? this.mirror.getId(getShadowHost(n)) : this.mirror.getId(n.parentNode);
const nextId = getNextId(n);
if (parentId === -1 || nextId === -1) {
return addList.addNode(n);
}
const sn = serializeNodeWithId(n, {
doc: this.doc,
mirror: this.mirror,
blockClass: this.blockClass,
blockSelector: this.blockSelector,
maskTextClass: this.maskTextClass,
maskTextSelector: this.maskTextSelector,
skipChild: true,
newlyAddedElement: true,
inlineStylesheet: this.inlineStylesheet,
maskInputOptions: this.maskInputOptions,
maskTextFn: this.maskTextFn,
maskInputFn: this.maskInputFn,
slimDOMOptions: this.slimDOMOptions,
dataURLOptions: this.dataURLOptions,
recordCanvas: this.recordCanvas,
inlineImages: this.inlineImages,
onSerialize: currentN => {
if (isSerializedIframe(currentN, this.mirror)) {
this.iframeManager.addIframe(currentN);
}
if (isSerializedStylesheet(currentN, this.mirror)) {
this.stylesheetManager.trackLinkElement(currentN);
}
if (hasShadowRoot(n)) {
this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);
}
},
onIframeLoad: (iframe, childSn) => {
this.iframeManager.attachIframe(iframe, childSn);
this.shadowDomManager.observeAttachShadow(iframe);
},
onStylesheetLoad: (link, childSn) => {
this.stylesheetManager.attachLinkElement(link, childSn);
}
});
if (sn) {
adds.push({
parentId,
nextId,
node: sn
});
}
};
while (this.mapRemoves.length) {
this.mirror.removeNodeFromMap(this.mapRemoves.shift());
}
for (const n of Array.from(this.movedSet.values())) {
if (isParentRemoved(this.removes, n, this.mirror) && !this.movedSet.has(n.parentNode)) {
continue;
}
pushAdd(n);
}
for (const n of Array.from(this.addedSet.values())) {
if (!isAncestorInSet(this.droppedSet, n) && !isParentRemoved(this.removes, n, this.mirror)) {
pushAdd(n);
} else if (isAncestorInSet(this.movedSet, n)) {
pushAdd(n);
} else {
this.droppedSet.add(n);
}
}
let candidate = null;
while (addList.length) {
let node = null;
if (candidate) {
const parentId = this.mirror.getId(candidate.value.parentNode);
const nextId = getNextId(candidate.value);
if (parentId !== -1 && nextId !== -1) {
node = candidate;
}
}
if (!node) {
for (let index = addList.length - 1; index >= 0; index--) {
const _node = addList.get(index);
if (_node) {
const parentId = this.mirror.getId(_node.value.parentNode);
const nextId = getNextId(_node.value);
if (nextId === -1) continue;else if (parentId !== -1) {
node = _node;
break;
} else {
const unhandledNode = _node.value;
if (unhandledNode.parentNode && unhandledNode.parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
const shadowHost = unhandledNode.parentNode.host;
const parentId = this.mirror.getId(shadowHost);
if (parentId !== -1) {
node = _node;
break;
}
}
}
}
}
}
if (!node) {
while (addList.head) {
addList.removeNode(addList.head.value);
}
break;
}
candidate = node.previous;
addList.removeNode(node.value);
pushAdd(node.value);
}
const payload = {
texts: this.texts.map(text => ({
id: this.mirror.getId(text.node),
value: text.value
})).filter(text => this.mirror.has(text.id)),
attributes: this.attributes.map(attribute => ({
id: this.mirror.getId(attribute.node),
attributes: attribute.attributes
})).filter(attribute => this.mirror.has(attribute.id)),
removes: this.removes,
adds
};
if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {
return;
}
this.texts = [];
this.attributes = [];
this.removes = [];
this.addedSet = new Set();
this.movedSet = new Set();
this.droppedSet = new Set();
this.movedMap = {};
this.mutationCb(payload);
};
this.processMutation = m => {
if (isIgnored(m.target, this.mirror)) {
return;
}
switch (m.type) {
case 'characterData':
{
const value = m.target.textContent;
if (!isBlocked(m.target, this.blockClass, this.blockSelector, false) && value !== m.oldValue) {
this.texts.push({
value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector) && value ? this.maskTextFn ? this.maskTextFn(value) : value.replace(/[\S]/g, '*') : value,
node: m.target
});
}
break;
}
case 'attributes':
{
const target = m.target;
let value = m.target.getAttribute(m.attributeName);
if (m.attributeName === 'value') {
value = maskInputValue({
maskInputOptions: this.maskInputOptions,
tagName: m.target.tagName,
type: m.target.getAttribute('type'),
value,
maskInputFn: this.maskInputFn
});
}
if (isBlocked(m.target, this.blockClass, this.blockSelector, false) || value === m.oldValue) {
return;
}
let item = this.attributes.find(a => a.node === m.target);
if (target.tagName === 'IFRAME' && m.attributeName === 'src' && !this.keepIframeSrcFn(value)) {
if (!target.contentDocument) {
m.attributeName = 'rr_src';
} else {
return;
}
}
if (!item) {
item = {
node: m.target,
attributes: {}
};
this.attributes.push(item);
}
if (m.attributeName === 'style') {
const old = this.doc.createElement('span');
if (m.oldValue) {
old.setAttribute('style', m.oldValue);
}
if (item.attributes.style === undefined || item.attributes.style === null) {
item.attributes.style = {};
}
const styleObj = item.attributes.style;
for (const pname of Array.from(target.style)) {
const newValue = target.style.getPropertyValue(pname);
const newPriority = target.style.getPropertyPriority(pname);
if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {
if (newPriority === '') {
styleObj[pname] = newValue;
} else {
styleObj[pname] = [newValue, newPriority];
}
}
}
for (const pname of Array.from(old.style)) {
if (target.style.getPropertyValue(pname) === '') {
styleObj[pname] = false;
}
}
} else {
item.attributes[m.attributeName] = transformAttribute(this.doc, target.tagName, m.attributeName, value);
}
break;
}
case 'childList':
{
if (isBlocked(m.target, this.blockClass, this.blockSelector, true)) return;
m.addedNodes.forEach(n => this.genAdds(n, m.target));
m.removedNodes.forEach(n => {
const nodeId = this.mirror.getId(n);
const parentId = isShadowRoot(m.target) ? this.mirror.getId(m.target.host) : this.mirror.getId(m.target);
if (isBlocked(m.target, this.blockClass, this.blockSelector, false) || isIgnored(n, this.mirror) || !isSerialized(n, this.mirror)) {
return;
}
if (this.addedSet.has(n)) {
deepDelete(this.addedSet, n);
this.droppedSet.add(n);
} else if (this.addedSet.has(m.target) && nodeId === -1) ;else if (isAncestorRemoved(m.target, this.mirror)) ;else if (this.movedSet.has(n) && this.movedMap[moveKey(nodeId, parentId)]) {
deepDelete(this.movedSet, n);
} else {
this.removes.push({
parentId,
id: nodeId,
isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : undefined
});
}
this.mapRemoves.push(n);
});
break;
}
}
};
this.genAdds = (n, target) => {
if (this.processedNodeManager.inOtherBuffer(n, this)) return;
if (this.mirror.hasNode(n)) {
if (isIgnored(n, this.mirror)) {
return;
}
this.movedSet.add(n);
let targetId = null;
if (target && this.mirror.hasNode(target)) {
targetId = this.mirror.getId(target);
}
if (targetId && targetId !== -1) {
this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;
}
} else {
this.addedSet.add(n);
this.droppedSet.delete(n);
}
if (!isBlocked(n, this.blockClass, this.blockSelector, false)) {
n.childNodes.forEach(childN => this.genAdds(childN));
if (hasShadowRoot(n)) {
n.shadowRoot.childNodes.forEach(childN => {
this.processedNodeManager.add(childN, this);
this.genAdds(childN, n);
});
}
}
};
}
init(options) {
['mutationCb', 'blockClass', 'blockSelector', 'maskTextClass', 'maskTextSelector', 'inlineStylesheet', 'maskInputOptions', 'maskTextFn', 'maskInputFn', 'keepIframeSrcFn', 'recordCanvas', 'inlineImages', 'slimDOMOptions', 'dataURLOptions', 'doc', 'mirror', 'iframeManager', 'stylesheetManager', 'shadowDomManager', 'canvasManager', 'processedNodeManager'].forEach(key => {
this[key] = options[key];
});
}
freeze() {
this.frozen = true;
this.canvasManager.freeze();
}
unfreeze() {
this.frozen = false;
this.canvasManager.unfreeze();
this.emit();
}
isFrozen() {
return this.frozen;
}
lock() {
this.locked = true;
this.canvasManager.lock();
}
unlock() {
this.locked = false;
this.canvasManager.unlock();
this.emit();
}
reset() {
this.shadowDomManager.reset();
this.canvasManager.reset();
}
}
function deepDelete(addsSet, n) {
addsSet.delete(n);
n.childNodes.forEach(childN => deepDelete(addsSet, childN));
}
function isParentRemoved(removes, n, mirror) {
if (removes.length === 0) return false;
return _isParentRemoved(removes, n, mirror);
}
function _isParentRemoved(removes, n, mirror) {
const {
parentNode
} = n;
if (!parentNode) {
return false;
}
const parentId = mirror.getId(parentNode);
if (removes.some(r => r.id === parentId)) {
return true;
}
return _isParentRemoved(removes, parentNode, mirror);
}
function isAncestorInSet(set, n) {
if (set.size === 0) return false;
return _isAncestorInSet(set, n);
}
function _isAncestorInSet(set, n) {
const {
parentNode
} = n;
if (!parentNode) {
return false;
}
if (set.has(parentNode)) {
return true;
}
return _isAncestorInSet(set, parentNode);
}
class ProcessedNodeManager {
constructor() {
this.nodeMap = new WeakMap();
this.periodicallyClear();
}
periodicallyClear() {
requestAnimationFrame(() => {
this.clear();
this.periodicallyClear();
});
}
inOtherBuffer(node, thisBuffer) {
const buffers = this.nodeMap.get(node);
return buffers && Array.from(buffers).some(buffer => buffer !== thisBuffer);
}
add(node, buffer) {
this.nodeMap.set(node, (this.nodeMap.get(node) || new Set()).add(buffer));
}
clear() {
this.nodeMap = new WeakMap();
}
}
const mutationBuffers = [];
const processedNodeManager = new ProcessedNodeManager();
function getEventTarget(event) {
try {
if ('composedPath' in event) {
const path = event.composedPath();
if (path.length) {
return path[0];
}
} else if ('path' in event && event.path.length) {
return event.path[0];
}
return event.target;
} catch (_a) {
return event.target;
}
}
function initMutationObserver(options, rootEl) {
var _a, _b;
const mutationBuffer = new MutationBuffer();
mutationBuffers.push(mutationBuffer);
mutationBuffer.init(options);
let mutationObserverCtor = window.MutationObserver || window.__rrMutationObserver;
const angularZoneSymbol = (_b = (_a = window === null || window === void 0 ? void 0 : window.Zone) === null || _a === void 0 ? void 0 : _a.__symbol__) === null || _b === void 0 ? void 0 : _b.call(_a, 'MutationObserver');
if (angularZoneSymbol && window[angularZoneSymbol]) {
mutationObserverCtor = window[angularZoneSymbol];
}
const observer = new mutationObserverCtor(mutationBuffer.processMutations.bind(mutationBuffer));
observer.observe(rootEl, {
attributes: true,
attributeOldValue: true,
characterData: true,
characterDataOldValue: true,
childList: true,
subtree: true
});
return observer;
}
function initMoveObserver(_ref) {
let {
mousemoveCb,
sampling,
doc,
mirror
} = _ref;
if (sampling.mousemove === false) {
return () => {};
}
const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;
const callbackThreshold = typeof sampling.mousemoveCallback === 'number' ? sampling.mousemoveCallback : 500;
let positions = [];
let timeBaseline;
const wrappedCb = throttle(source => {
const totalOffset = Date.now() - timeBaseline;
mousemoveCb(positions.map(p => {
p.timeOffset -= totalOffset;
return p;
}), source);
positions = [];
timeBaseline = null;
}, callbackThreshold);
const updatePosition = throttle(evt => {
const target = getEventTarget(evt);
const {
clientX,
clientY
} = isTouchEvent(evt) ? evt.changedTouches[0] : evt;
if (!timeBaseline) {
timeBaseline = Date.now();
}
positions.push({
x: clientX,
y: clientY,
id: mirror.getId(target),
timeOffset: Date.now() - timeBaseline
});
wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent ? IncrementalSource.Drag : evt instanceof MouseEvent ? IncrementalSource.MouseMove : IncrementalSource.TouchMove);
}, threshold, {
trailing: false
});
const handlers = [on('mousemove', updatePosition, doc), on('touchmove', updatePosition, doc), on('drag', updatePosition, doc)];
return () => {
handlers.forEach(h => h());
};
}
function initMouseInteractionObserver(_ref2) {
let {
mouseInteractionCb,
doc,
mirror,
blockClass,
blockSelector,
sampling
} = _ref2;
if (sampling.mouseInteraction === false) {
return () => {};
}
const disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === undefined ? {} : sampling.mouseInteraction;
const handlers = [];
const getHandler = eventKey => {
return event => {
const target = getEventTarget(event);
if (isBlocked(target, blockClass, blockSelector, true)) {
return;
}
const e = isTouchEvent(event) ? event.changedTouches[0] : event;
if (!e) {
return;
}
const id = mirror.getId(target);
const {
clientX,
clientY
} = e;
mouseInteractionCb({
type: MouseInteractions[eventKey],
id,
x: clientX,
y: clientY
});
};
};
Object.keys(MouseInteractions).filter(key => Number.isNaN(Number(key)) && !key.endsWith('_Departed') && disableMap[key] !== false).forEach(eventKey => {
const eventName = eventKey.toLowerCase();
const handler = getHandler(eventKey);
handlers.push(on(eventName, handler, doc));
});
return () => {
handlers.forEach(h => h());
};
}
function initScrollObserver(_ref3) {
let {
scrollCb,
doc,
mirror,
blockClass,
blockSelector,
sampling
} = _ref3;
const updatePosition = throttle(evt => {
const target = getEventTarget(evt);
if (!target || isBlocked(target, blockClass, blockSelector, true)) {
return;
}
const id = mirror.getId(target);
if (target === doc && doc.defaultView) {
const scrollLeftTop = getWindowScroll(doc.defaultView);
scrollCb({
id,
x: scrollLeftTop.left,
y: scrollLeftTop.top
});
} else {
scrollCb({
id,
x: target.scrollLeft,
y: target.scrollTop
});
}
}, sampling.scroll || 100);
return on('scroll', updatePosition, doc);
}
function initViewportResizeObserver(_ref4) {
let {
viewportResizeCb
} = _ref4;
let lastH = -1;
let lastW = -1;
const updateDimension = throttle(() => {
const height = getWindowHeight();
const width = getWindowWidth();
if (lastH !== height || lastW !== width) {
viewportResizeCb({
width: Number(width),
height: Number(height)
});
lastH = height;
lastW = width;
}
}, 200);
return on('resize', updateDimension, window);
}
function wrapEventWithUserTriggeredFlag(v, enable) {
const value = Object.assign({}, v);
if (!enable) delete value.userTriggered;
return value;
}
const INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];
const lastInputValueMap = new WeakMap();
function initInputObserver(_ref5) {
let {
inputCb,
doc,
mirror,
blockClass,
blockSelector,
ignoreClass,
maskInputOptions,
maskInputFn,
sampling,
userTriggeredOnInput
} = _ref5;
function eventHandler(event) {
let target = getEventTarget(event);
const userTriggered = event.isTrusted;
if (target && target.tagName === 'OPTION') target = target.parentElement;
if (!target || !target.tagName || INPUT_TAGS.indexOf(target.tagName) < 0 || isBlocked(target, blockClass, blockSelector, true)) {
return;
}
const type = target.type;
if (target.classList.contains(ignoreClass)) {
return;
}
let text = target.value;
let isChecked = false;
if (type === 'radio' || type === 'checkbox') {
isChecked = target.checked;
} else if (maskInputOptions[target.tagName.toLowerCase()] || maskInputOptions[type]) {
text = maskInputValue({
maskInputOptions,
tagName: target.tagName,
type,
value: text,
maskInputFn
});
}
cbWithDedup(target, wrapEventWithUserTriggeredFlag({
text,
isChecked,
userTriggered
}, userTriggeredOnInput));
const name = target.name;
if (type === 'radio' && name && isChecked) {
doc.querySelectorAll(`input[type="radio"][name="${name}"]`).forEach(el => {
if (el !== target) {
cbWithDedup(el, wrapEventWithUserTriggeredFlag({
text: el.value,
isChecked: !isChecked,
userTriggered: false
}, userTriggeredOnInput));
}
});
}
}
function cbWithDedup(target, v) {
const lastInputValue = lastInputValueMap.get(target);
if (!lastInputValue || lastInputValue.text !== v.text || lastInputValue.isChecked !== v.isChecked) {
lastInputValueMap.set(target, v);
const id = mirror.getId(target);
inputCb(Object.assign(Object.assign({}, v), {
id
}));
}
}
const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];
const handlers = events.map(eventName => on(eventName, eventHandler, doc));
const currentWindow = doc.defaultView;
if (!currentWindow) {
return () => {
handlers.forEach(h => h());
};
}
const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');
const hookProperties = [[currentWindow.HTMLInputElement.prototype, 'value'], [currentWindow.HTMLInputElement.prototype, 'checked'], [currentWindow.HTMLSelectElement.prototype, 'value'], [currentWindow.HTMLTextAreaElement.prototype, 'value'], [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'], [currentWindow.HTMLOptionElement.prototype, 'selected']];
if (propertyDescriptor && propertyDescriptor.set) {
handlers.push(...hookProperties.map(p => hookSetter(p[0], p[1], {
set() {
eventHandler({
target: this
});
}
}, false, currentWindow)));
}
return () => {
handlers.forEach(h => h());
};
}
function getNestedCSSRulePositions(rule) {
const positions = [];
function recurse(childRule, pos) {
if (hasNestedCSSRule('CSSGroupingRule') && childRule.parentRule instanceof CSSGroupingRule || hasNestedCSSRule('CSSMediaRule') && childRule.parentRule instanceof CSSMediaRule || hasNestedCSSRule('CSSSupportsRule') && childRule.parentRule instanceof CSSSupportsRule || hasNestedCSSRule('CSSConditionRule') && childRule.parentRule instanceof CSSConditionRule) {
const rules = Array.from(childRule.parentRule.cssRules);
const index = rules.indexOf(childRule);
pos.unshift(index);
} else if (childRule.parentStyleSheet) {
const rules = Array.from(childRule.parentStyleSheet.cssRules);
const index = rules.indexOf(childRule);
pos.unshift(index);
}
return pos;
}
return recurse(rule, positions);
}
function getIdAndStyleId(sheet, mirror, styleMirror) {
let id, styleId;
if (!sheet) return {};
if (sheet.ownerNode) id = mirror.getId(sheet.ownerNode);else styleId = styleMirror.getId(sheet);
return {
styleId,
id
};
}
function initStyleSheetObserver(_ref6, _ref7) {
let {
styleSheetRuleCb,
mirror,
stylesheetManager
} = _ref6;
let {
win
} = _ref7;
if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {
return () => {};
}
const insertRule = win.CSSStyleSheet.prototype.insertRule;
win.CSSStyleSheet.prototype.insertRule = function (rule, index) {
const {
id,
styleId
} = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
if (id && id !== -1 || styleId && styleId !== -1) {
styleSheetRuleCb({
id,
styleId,
adds: [{
rule,
index
}]
});
}
return insertRule.apply(this, [rule, index]);
};
const deleteRule = win.CSSStyleSheet.prototype.deleteRule;
win.CSSStyleSheet.prototype.deleteRule = function (index) {
const {
id,
styleId
} = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
if (id && id !== -1 || styleId && styleId !== -1) {
styleSheetRuleCb({
id,
styleId,
removes: [{
index
}]
});
}
return deleteRule.apply(this, [index]);
};
let replace;
if (win.CSSStyleSheet.prototype.replace) {
replace = win.CSSStyleSheet.prototype.replace;
win.CSSStyleSheet.prototype.replace = function (text) {
const {
id,
styleId
} = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
if (id && id !== -1 || styleId && styleId !== -1) {
styleSheetRuleCb({
id,
styleId,
replace: text
});
}
return replace.apply(this, [text]);
};
}
let replaceSync;
if (win.CSSStyleSheet.prototype.replaceSync) {
replaceSync = win.CSSStyleSheet.prototype.replaceSync;
win.CSSStyleSheet.prototype.replaceSync = function (text) {
const {
id,
styleId
} = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
if (id && id !== -1 || styleId && styleId !== -1) {
styleSheetRuleCb({
id,
styleId,
replaceSync: text
});
}
return replaceSync.apply(this, [text]);
};
}
const supportedNestedCSSRuleTypes = {};
if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {
supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
} else {
if (canMonkeyPatchNestedCSSRule('CSSMediaRule')) {
supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
}
if (canMonkeyPatchNestedCSSRule('CSSConditionRule')) {
supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
}
if (canMonkeyPatchNestedCSSRule('CSSSupportsRule')) {
supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
}
}
const unmodifiedFunctions = {};
Object.entries(supportedNestedCSSRuleTypes).forEach(_ref8 => {
let [typeKey, type] = _ref8;
unmodifiedFunctions[typeKey] = {
insertRule: type.prototype.insertRule,
deleteRule: type.prototype.deleteRule
};
type.prototype.insertRule = function (rule, index) {
const {
id,
styleId
} = getIdAndStyleId(this.parentStyleSheet, mirror, stylesheetManager.styleMirror);
if (id && id !== -1 || styleId && styleId !== -1) {
styleSheetRuleCb({
id,
styleId,
adds: [{
rule,
index: [...getNestedCSSRulePositions(this), index || 0]
}]
});
}
return unmodifiedFunctions[typeKey].insertRule.apply(this, [rule, index]);
};
type.prototype.deleteRule = function (index) {
const {
id,
styleId
} = getIdAndStyleId(this.parentStyleSheet, mirror, stylesheetManager.styleMirror);
if (id && id !== -1 || styleId && styleId !== -1) {
styleSheetRuleCb({
id,
styleId,
removes: [{
index: [...getNestedCSSRulePositions(this), index]
}]
});
}
return unmodifiedFunctions[typeKey].deleteRule.apply(this, [index]);
};
});
return () => {
win.CSSStyleSheet.prototype.insertRule = insertRule;
win.CSSStyleSheet.prototype.deleteRule = deleteRule;
replace && (win.CSSStyleSheet.prototype.replace = replace);
replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
Object.entries(supportedNestedCSSRuleTypes).forEach(_ref9 => {
let [typeKey, type] = _ref9;
type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
});
};
}
function initAdoptedStyleSheetObserver(_ref0, host) {
let {
mirror,
stylesheetManager
} = _ref0;
var _a, _b, _c;
let hostId = null;
if (host.nodeName === '#document') hostId = mirror.getId(host);else hostId = mirror.getId(host.host);
const patchTarget = host.nodeName === '#document' ? (_a = host.defaultView) === null || _a === void 0 ? void 0 : _a.Document : (_c = (_b = host.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView) === null || _c === void 0 ? void 0 : _c.ShadowRoot;
const originalPropertyDescriptor = Object.getOwnPropertyDescriptor(patchTarget === null || patchTarget === void 0 ? void 0 : patchTarget.prototype, 'adoptedStyleSheets');
if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor) return () => {};
Object.defineProperty(host, 'adoptedStyleSheets', {
configurable: originalPropertyDescriptor.configurable,
enumerable: originalPropertyDescriptor.enumerable,
get() {
var _a;
return (_a = originalPropertyDescriptor.get) === null || _a === void 0 ? void 0 : _a.call(this);
},
set(sheets) {
var _a;
const result = (_a = originalPropertyDescriptor.set) === null || _a === void 0 ? void 0 : _a.call(this, sheets);
if (hostId !== null && hostId !== -1) {
try {
stylesheetManager.adoptStyleSheets(sheets, hostId);
} catch (e) {}
}
return result;
}
});
return () => {
Object.defineProperty(host, 'adoptedStyleSheets', {
configurable: originalPropertyDescriptor.configurable,
enumerable: originalPropertyDescriptor.enumerable,
get: originalPropertyDescriptor.get,
set: originalPropertyDescriptor.set
});
};
}
function initStyleDeclarationObserver(_ref1, _ref10) {
let {
styleDeclarationCb,
mirror,
ignoreCSSAttributes,
stylesheetManager
} = _ref1;
let {
win
} = _ref10;
const setProperty = win.CSSStyleDeclaration.prototype.setProperty;
win.CSSStyleDeclaration.prototype.setProperty = function (property, value, priority) {
var _a;
if (ignoreCSSAttributes.has(property)) {
return setProperty.apply(this, [property, value, priority]);
}
const {
id,
styleId
} = getIdAndStyleId((_a = this.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);
if (id && id !== -1 || styleId && styleId !== -1) {
styleDeclarationCb({
id,
styleId,
set: {
property,
value,
priority
},
index: getNestedCSSRulePositions(this.parentRule)
});
}
return setProperty.apply(this, [property, value, priority]);
};
const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
win.CSSStyleDeclaration.prototype.removeProperty = function (property) {
var _a;
if (ignoreCSSAttributes.has(property)) {
return removeProperty.apply(this, [property]);
}
const {
id,
styleId
} = getIdAndStyleId((_a = this.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);
if (id && id !== -1 || styleId && styleId !== -1) {
styleDeclarationCb({
id,
styleId,
remove: {
property
},
index: getNestedCSSRulePositions(this.parentRule)
});
}
return removeProperty.apply(this, [property]);
};
return () => {
win.CSSStyleDeclaration.prototype.setProperty = setProperty;
win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
};
}
function initMediaInteractionObserver(_ref11) {
let {
mediaInteractionCb,
blockClass,
blockSelector,
mirror,
sampling
} = _ref11;
const handler = type => throttle(event => {
const target = getEventTarget(event);
if (!target || isBlocked(target, blockClass, blockSelector, true)) {
return;
}
const {
currentTime,
volume,
muted,
playbackRate
} = target;
mediaInteractionCb({
type,
id: mirror.getId(target),
currentTime,
volume,
muted,
playbackRate
});
}, sampling.media || 500);
const handlers = [on('play', handler(0)), on('pause', handler(1)), on('seeked', handler(2)), on('volumechange', handler(3)), on('ratechange', handler(4))];
return () => {
handlers.forEach(h => h());
};
}
function initFontObserver(_ref12) {
let {
fontCb,
doc
} = _ref12;
const win = doc.defaultView;
if (!win) {
return () => {};
}
const handlers = [];
const fontMap = new WeakMap();
const originalFontFace = win.FontFace;
win.FontFace = function FontFace(family, source, descriptors) {
const fontFace = new originalFontFace(family, source, descriptors);
fontMap.set(fontFace, {
family,
buffer: typeof source !== 'string',
descriptors,
fontSource: typeof source === 'string' ? source : JSON.stringify(Array.from(new Uint8Array(source)))
});
return fontFace;
};
const restoreHandler = patch(doc.fonts, 'add', function (original) {
return function (fontFace) {
setTimeout(() => {
const p = fontMap.get(fontFace);
if (p) {
fontCb(p);
fontMap.delete(fontFace);
}
}, 0);
return original.apply(this, [fontFace]);
};
});
handlers.push(() => {
win.FontFace = originalFontFace;
});
handlers.push(restoreHandler);
return () => {
handlers.forEach(h => h());
};
}
function initSelectionObserver(param) {
const {
doc,
mirror,
blockClass,
blockSelector,
selectionCb
} = param;
let collapsed = true;
const updateSelection = () => {
const selection = doc.getSelection();
if (!selection || collapsed && (selection === null || selection === void 0 ? void 0 : selection.isCollapsed)) return;
collapsed = selection.isCollapsed || false;
const ranges = [];
const count = selection.rangeCount || 0;
for (let i = 0; i < count; i++) {
const range = selection.getRangeAt(i);
const {
startContainer,
startOffset,
endContainer,
endOffset
} = range;
const blocked = isBlocked(startContainer, blockClass, blockSelector, true) || isBlocked(endContainer, blockClass, blockSelector, true);
if (blocked) continue;
ranges.push({
start: mirror.getId(startContainer),
startOffset,
end: mirror.getId(endContainer),
endOffset
});
}
selectionCb({
ranges
});
};
updateSelection();
return on('selectionchange', updateSelection);
}
function mergeHooks(o, hooks) {
const {
mutationCb,
mousemoveCb,
mouseInteractionCb,
scrollCb,
viewportResizeCb,
inputCb,
mediaInteractionCb,
styleSheetRuleCb,
styleDeclarationCb,
canvasMutationCb,
fontCb,
selectionCb
} = o;
o.mutationCb = function () {
if (hooks.mutation) {
hooks.mutation(...arguments);
}
mutationCb(...arguments);
};
o.mousemoveCb = function () {
if (hooks.mousemove) {
hooks.mousemove(...arguments);
}
mousemoveCb(...arguments);
};
o.mouseInteractionCb = function () {
if (hooks.mouseInteraction) {
hooks.mouseInteraction(...arguments);
}
mouseInteractionCb(...arguments);
};
o.scrollCb = function () {
if (hooks.scroll) {
hooks.scroll(...arguments);
}
scrollCb(...arguments);
};
o.viewportResizeCb = function () {
if (hooks.viewportResize) {
hooks.viewportResize(...arguments);
}
viewportResizeCb(...arguments);
};
o.inputCb = function () {
if (hooks.input) {
hooks.input(...arguments);
}
inputCb(...arguments);
};
o.mediaInteractionCb = function () {
if (hooks.mediaInteaction) {
hooks.mediaInteaction(...arguments);
}
mediaInteractionCb(...arguments);
};
o.styleSheetRuleCb = function () {
if (hooks.styleSheetRule) {
hooks.styleSheetRule(...arguments);
}
styleSheetRuleCb(...arguments);
};
o.styleDeclarationCb = function () {
if (hooks.styleDeclaration) {
hooks.styleDeclaration(...arguments);
}
styleDeclarationCb(...arguments);
};
o.canvasMutationCb = function () {
if (hooks.canvasMutation) {
hooks.canvasMutation(...arguments);
}
canvasMutationCb(...arguments);
};
o.fontCb = function () {
if (hooks.font) {
hooks.font(...arguments);
}
fontCb(...arguments);
};
o.selectionCb = function () {
if (hooks.selection) {
hooks.selection(...arguments);
}
selectionCb(...arguments);
};
}
function initObservers(o) {
let hooks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const currentWindow = o.doc.defaultView;
if (!currentWindow) {
return () => {};
}
mergeHooks(o, hooks);
const mutationObserver = initMutationObserver(o, o.doc);
const mousemoveHandler = initMoveObserver(o);
const mouseInteractionHandler = initMouseInteractionObserver(o);
const scrollHandler = initScrollObserver(o);
const viewportResizeHandler = initViewportResizeObserver(o);
const inputHandler = initInputObserver(o);
const mediaInteractionHandler = initMediaInteractionObserver(o);
const styleSheetObserver = initStyleSheetObserver(o, {
win: currentWindow
});
const adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);
const styleDeclarationObserver = initStyleDeclarationObserver(o, {
win: currentWindow
});
const fontObserver = o.collectFonts ? initFontObserver(o) : () => {};
const selectionObserver = initSelectionObserver(o);
const pluginHandlers = [];
for (const plugin of o.plugins) {
pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));
}
return () => {
mutationBuffers.forEach(b => b.reset());
mutationObserver.disconnect();
mousemoveHandler();
mouseInteractionHandler();
scrollHandler();
viewportResizeHandler();
inputHandler();
mediaInteractionHandler();
styleSheetObserver();
adoptedStyleSheetObserver();
styleDeclarationObserver();
fontObserver();
selectionObserver();
pluginHandlers.forEach(h => h());
};
}
function hasNestedCSSRule(prop) {
return typeof window[prop] !== 'undefined';
}
function canMonkeyPatchNestedCSSRule(prop) {
return Boolean(typeof window[prop] !== 'undefined' && window[prop].prototype && 'insertRule' in window[prop].prototype && 'deleteRule' in window[prop].prototype);
}
class CrossOriginIframeMirror {
constructor(generateIdFn) {
this.generateIdFn = generateIdFn;
this.iframeIdToRemoteIdMap = new WeakMap();
this.iframeRemoteIdToIdMap = new WeakMap();
}
getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
let id = idToRemoteIdMap.get(remoteId);
if (!id) {
id = this.generateIdFn();
idToRemoteIdMap.set(remoteId, id);
remoteIdToIdMap.set(id, remoteId);
}
return id;
}
getIds(iframe, remoteId) {
const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
return remoteId.map(id => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));
}
getRemoteId(iframe, id, map) {
const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);
if (typeof id !== 'number') return id;
const remoteId = remoteIdToIdMap.get(id);
if (!remoteId) return -1;
return remoteId;
}
getRemoteIds(iframe, ids) {
const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
return ids.map(id => this.getRemoteId(iframe, id, remoteIdToIdMap));
}
reset(iframe) {
if (!iframe) {
this.iframeIdToRemoteIdMap = new WeakMap();
this.iframeRemoteIdToIdMap = new WeakMap();
return;
}
this.iframeIdToRemoteIdMap.delete(iframe);
this.iframeRemoteIdToIdMap.delete(iframe);
}
getIdToRemoteIdMap(iframe) {
let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
if (!idToRemoteIdMap) {
idToRemoteIdMap = new Map();
this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
}
return idToRemoteIdMap;
}
getRemoteIdToIdMap(iframe) {
let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
if (!remoteIdToIdMap) {
remoteIdToIdMap = new Map();
this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
}
return remoteIdToIdMap;
}
}
class IframeManager {
constructor(options) {
this.iframes = new WeakMap();
this.crossOriginIframeMap = new WeakMap();
this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);
this.crossOriginIframeRootIdMap = new WeakMap();
this.mutationCb = options.mutationCb;
this.wrappedEmit = options.wrappedEmit;
this.stylesheetManager = options.stylesheetManager;
this.recordCrossOriginIframes = options.recordCrossOriginIframes;
this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
this.mirror = options.mirror;
if (this.recordCrossOriginIframes) {
window.addEventListener('message', this.handleMessage.bind(this));
}
}
addIframe(iframeEl) {
this.iframes.set(iframeEl, true);
if (iframeEl.contentWindow) this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
}
addLoadListener(cb) {
this.loadListener = cb;
}
attachIframe(iframeEl, childSn) {
var _a;
this.mutationCb({
adds: [{
parentId: this.mirror.getId(iframeEl),
nextId: null,
node: childSn
}],
removes: [],
texts: [],
attributes: [],
isAttachIframe: true
});
(_a = this.loadListener) === null || _a === void 0 ? void 0 : _a.call(this, iframeEl);
if (iframeEl.contentDocument && iframeEl.contentDocument.adoptedStyleSheets && iframeEl.contentDocument.adoptedStyleSheets.length > 0) this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));
}
handleMessage(message) {
const crossOriginMessageEvent = message;
if (crossOriginMessageEvent.data.type !== 'rrweb' || crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin) return;
const iframeSourceWindow = message.source;
if (!iframeSourceWindow) return;
const iframeEl = this.crossOriginIframeMap.get(message.source);
if (!iframeEl) return;
const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);
if (transformedEvent) this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);
}
transformCrossOriginEvent(iframeEl, e) {
var _a;
switch (e.type) {
case EventType.FullSnapshot:
{
this.crossOriginIframeMirror.reset(iframeEl);
this.crossOriginIframeStyleMirror.reset(iframeEl);
this.replaceIdOnNode(e.data.node, iframeEl);
const rootId = e.data.node.id;
this.crossOriginIframeRootIdMap.set(iframeEl, rootId);
this.patchRootIdOnNode(e.data.node, rootId);
return {
timestamp: e.timestamp,
type: EventType.IncrementalSnapshot,
data: {
source: IncrementalSource.Mutation,
adds: [{
parentId: this.mirror.getId(iframeEl),
nextId: null,
node: e.data.node
}],
removes: [],
texts: [],
attributes: [],
isAttachIframe: true
}
};
}
case EventType.Meta:
case EventType.Load:
case EventType.DomContentLoaded:
{
return false;
}
case EventType.Plugin:
{
return e;
}
case EventType.Custom:
{
this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);
return e;
}
case EventType.IncrementalSnapshot:
{
switch (e.data.source) {
case IncrementalSource.Mutation:
{
e.data.adds.forEach(n => {
this.replaceIds(n, iframeEl, ['parentId', 'nextId', 'previousId']);
this.replaceIdOnNode(n.node, iframeEl);
const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);
rootId && this.patchRootIdOnNode(n.node, rootId);
});
e.data.removes.forEach(n => {
this.replaceIds(n, iframeEl, ['parentId', 'id']);
});
e.data.attributes.forEach(n => {
this.replaceIds(n, iframeEl, ['id']);
});
e.data.texts.forEach(n => {
this.replaceIds(n, iframeEl, ['id']);
});
return e;
}
case IncrementalSource.Drag:
case IncrementalSource.TouchMove:
case IncrementalSource.MouseMove:
{
e.data.positions.forEach(p => {
this.replaceIds(p, iframeEl, ['id']);
});
return e;
}
case IncrementalSource.ViewportResize:
{
return false;
}
case IncrementalSource.MediaInteraction:
case IncrementalSource.MouseInteraction:
case IncrementalSource.Scroll:
case IncrementalSource.CanvasMutation:
case IncrementalSource.Input:
{
this.replaceIds(e.data, iframeEl, ['id']);
return e;
}
case IncrementalSource.StyleSheetRule:
case IncrementalSource.StyleDeclaration:
{
this.replaceIds(e.data, iframeEl, ['id']);
this.replaceStyleIds(e.data, iframeEl, ['styleId']);
return e;
}
case IncrementalSource.Font:
{
return e;
}
case IncrementalSource.Selection:
{
e.data.ranges.forEach(range => {
this.replaceIds(range, iframeEl, ['start', 'end']);
});
return e;
}
case IncrementalSource.AdoptedStyleSheet:
{
this.replaceIds(e.data, iframeEl, ['id']);
this.replaceStyleIds(e.data, iframeEl, ['styleIds']);
(_a = e.data.styles) === null || _a === void 0 ? void 0 : _a.forEach(style => {
this.replaceStyleIds(style, iframeEl, ['styleId']);
});
return e;
}
}
}
}
}
replace(iframeMirror, obj, iframeEl, keys) {
for (const key of keys) {
if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number') continue;
if (Array.isArray(obj[key])) {
obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
} else {
obj[key] = iframeMirror.getId(iframeEl, obj[key]);
}
}
return obj;
}
replaceIds(obj, iframeEl, keys) {
return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);
}
replaceStyleIds(obj, iframeEl, keys) {
return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);
}
replaceIdOnNode(node, iframeEl) {
this.replaceIds(node, iframeEl, ['id', 'rootId']);
if ('childNodes' in node) {
node.childNodes.forEach(child => {
this.replaceIdOnNode(child, iframeEl);
});
}
}
patchRootIdOnNode(node, rootId) {
if (node.type !== NodeType.Document && !node.rootId) node.rootId = rootId;
if ('childNodes' in node) {
node.childNodes.forEach(child => {
this.patchRootIdOnNode(child, rootId);
});
}
}
}
class ShadowDomManager {
constructor(options) {
this.shadowDoms = new WeakSet();
this.restoreHandlers = [];
this.mutationCb = options.mutationCb;
this.scrollCb = options.scrollCb;
this.bypassOptions = options.bypassOptions;
this.mirror = options.mirror;
this.init();
}
init() {
this.reset();
this.patchAttachShadow(Element, document);
}
addShadowRoot(shadowRoot, doc) {
if (!isNativeShadowDom(shadowRoot)) return;
if (this.shadowDoms.has(shadowRoot)) return;
this.shadowDoms.add(shadowRoot);
const observer = initMutationObserver(Object.assign(Object.assign({}, this.bypassOptions), {
doc,
mutationCb: this.mutationCb,
mirror: this.mirror,
shadowDomManager: this
}), shadowRoot);
this.restoreHandlers.push(() => observer.disconnect());
this.restoreHandlers.push(initScrollObserver(Object.assign(Object.assign({}, this.bypassOptions), {
scrollCb: this.scrollCb,
doc: shadowRoot,
mirror: this.mirror
})));
setTimeout(() => {
if (shadowRoot.adoptedStyleSheets && shadowRoot.adoptedStyleSheets.length > 0) this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));
this.restoreHandlers.push(initAdoptedStyleSheetObserver({
mirror: this.mirror,
stylesheetManager: this.bypassOptions.stylesheetManager
}, shadowRoot));
}, 0);
}
observeAttachShadow(iframeElement) {
if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;
this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);
}
patchAttachShadow(element, doc) {
const manager = this;
this.restoreHandlers.push(patch(element.prototype, 'attachShadow', function (original) {
return function (option) {
const shadowRoot = original.call(this, option);
if (this.shadowRoot && inDom(this)) manager.addShadowRoot(this.shadowRoot, doc);
return shadowRoot;
};
}));
}
reset() {
this.restoreHandlers.forEach(handler => {
try {
handler();
} catch (e) {}
});
this.restoreHandlers = [];
this.shadowDoms = new WeakSet();
}
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function (resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
/*
* base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
* Copyright (c) 2021 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (var i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
var encode$1 = function (arraybuffer) {
var bytes = new Uint8Array(arraybuffer),
i,
len = bytes.length,
base64 = '';
for (i = 0; i < len; i += 3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64 += chars[bytes[i + 2] & 63];
}
if (len % 3 === 2) {
base64 = base64.substring(0, base64.length - 1) + '=';
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + '==';
}
return base64;
};
const canvasVarMap = new Map();
function variableListFor(ctx, ctor) {
let contextMap = canvasVarMap.get(ctx);
if (!contextMap) {
contextMap = new Map();
canvasVarMap.set(ctx, contextMap);
}
if (!contextMap.has(ctor)) {
contextMap.set(ctor, []);
}
return contextMap.get(ctor);
}
const saveWebGLVar = (value, win, ctx) => {
if (!value || !(isInstanceOfWebGLObject(value, win) || typeof value === 'object')) return;
const name = value.constructor.name;
const list = variableListFor(ctx, name);
let index = list.indexOf(value);
if (index === -1) {
index = list.length;
list.push(value);
}
return index;
};
function serializeArg(value, win, ctx) {
if (value instanceof Array) {
return value.map(arg => serializeArg(arg, win, ctx));
} else if (value === null) {
return value;
} else if (value instanceof Float32Array || value instanceof Float64Array || value instanceof Int32Array || value instanceof Uint32Array || value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Int16Array || value instanceof Int8Array || value instanceof Uint8ClampedArray) {
const name = value.constructor.name;
return {
rr_type: name,
args: [Object.values(value)]
};
} else if (value instanceof ArrayBuffer) {
const name = value.constructor.name;
const base64 = encode$1(value);
return {
rr_type: name,
base64
};
} else if (value instanceof DataView) {
const name = value.constructor.name;
return {
rr_type: name,
args: [serializeArg(value.buffer, win, ctx), value.byteOffset, value.byteLength]
};
} else if (value instanceof HTMLImageElement) {
const name = value.constructor.name;
const {
src
} = value;
return {
rr_type: name,
src
};
} else if (value instanceof HTMLCanvasElement) {
const name = 'HTMLImageElement';
const src = value.toDataURL();
return {
rr_type: name,
src
};
} else if (value instanceof ImageData) {
const name = value.constructor.name;
return {
rr_type: name,
args: [serializeArg(value.data, win, ctx), value.width, value.height]
};
} else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {
const name = value.constructor.name;
const index = saveWebGLVar(value, win, ctx);
return {
rr_type: name,
index: index
};
}
return value;
}
const serializeArgs = (args, win, ctx) => {
return [...args].map(arg => serializeArg(arg, win, ctx));
};
const isInstanceOfWebGLObject = (value, win) => {
const webGLConstructorNames = ['WebGLActiveInfo', 'WebGLBuffer', 'WebGLFramebuffer', 'WebGLProgram', 'WebGLRenderbuffer', 'WebGLShader', 'WebGLShaderPrecisionFormat', 'WebGLTexture', 'WebGLUniformLocation', 'WebGLVertexArrayObject', 'WebGLVertexArrayObjectOES'];
const supportedWebGLConstructorNames = webGLConstructorNames.filter(name => typeof win[name] === 'function');
return Boolean(supportedWebGLConstructorNames.find(name => value instanceof win[name]));
};
function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {
const handlers = [];
const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);
for (const prop of props2D) {
try {
if (typeof win.CanvasRenderingContext2D.prototype[prop] !== 'function') {
continue;
}
const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function (original) {
return function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
setTimeout(() => {
const recordArgs = serializeArgs([...args], win, this);
cb(this.canvas, {
type: CanvasContext['2D'],
property: prop,
args: recordArgs
});
}, 0);
}
return original.apply(this, args);
};
});
handlers.push(restoreHandler);
} catch (_a) {
const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {
set(v) {
cb(this.canvas, {
type: CanvasContext['2D'],
property: prop,
args: [v],
setter: true
});
}
});
handlers.push(hookHandler);
}
}
return () => {
handlers.forEach(h => h());
};
}
function initCanvasContextObserver(win, blockClass, blockSelector) {
const handlers = [];
try {
const restoreHandler = patch(win.HTMLCanvasElement.prototype, 'getContext', function (original) {
return function (contextType) {
if (!isBlocked(this, blockClass, blockSelector, true)) {
if (!('__context' in this)) this.__context = contextType;
}
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return original.apply(this, [contextType, ...args]);
};
});
handlers.push(restoreHandler);
} catch (_a) {
console.error('failed to patch HTMLCanvasElement.prototype.getContext');
}
return () => {
handlers.forEach(h => h());
};
}
function patchGLPrototype(prototype, type, cb, blockClass, blockSelector, mirror, win) {
const handlers = [];
const props = Object.getOwnPropertyNames(prototype);
for (const prop of props) {
if (['isContextLost', 'canvas', 'drawingBufferWidth', 'drawingBufferHeight'].includes(prop)) {
continue;
}
try {
if (typeof prototype[prop] !== 'function') {
continue;
}
const restoreHandler = patch(prototype, prop, function (original) {
return function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
const result = original.apply(this, args);
saveWebGLVar(result, win, this);
if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
const recordArgs = serializeArgs([...args], win, this);
const mutation = {
type,
property: prop,
args: recordArgs
};
cb(this.canvas, mutation);
}
return result;
};
});
handlers.push(restoreHandler);
} catch (_a) {
const hookHandler = hookSetter(prototype, prop, {
set(v) {
cb(this.canvas, {
type,
property: prop,
args: [v],
setter: true
});
}
});
handlers.push(hookHandler);
}
}
return handlers;
}
function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, mirror) {
const handlers = [];
handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, mirror, win));
if (typeof win.WebGL2RenderingContext !== 'undefined') {
handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, mirror, win));
}
return () => {
handlers.forEach(h => h());
};
}
var WorkerClass = null;
try {
var WorkerThreads = typeof module !== 'undefined' && typeof module.require === 'function' && module.require('worker_threads') || typeof __non_webpack_require__ === 'function' && __non_webpack_require__('worker_threads') || typeof require === 'function' && require('worker_threads');
WorkerClass = WorkerThreads.Worker;
} catch (e) {} // eslint-disable-line
function decodeBase64$1(base64, enableUnicode) {
return Buffer.from(base64, 'base64').toString(enableUnicode ? 'utf16' : 'utf8');
}
function createBase64WorkerFactory$2(base64, sourcemapArg, enableUnicodeArg) {
var sourcemap = sourcemapArg === undefined ? null : sourcemapArg;
var enableUnicode = enableUnicodeArg === undefined ? false : enableUnicodeArg;
var source = decodeBase64$1(base64, enableUnicode);
var start = source.indexOf('\n', 10) + 1;
var body = source.substring(start) + (sourcemap ? '\/\/# sourceMappingURL=' + sourcemap : '');
return function WorkerFactory(options) {
return new WorkerClass(body, Object.assign({}, options, {
eval: true
}));
};
}
function decodeBase64(base64, enableUnicode) {
var binaryString = atob(base64);
if (enableUnicode) {
var binaryView = new Uint8Array(binaryString.length);
for (var i = 0, n = binaryString.length; i < n; ++i) {
binaryView[i] = binaryString.charCodeAt(i);
}
return String.fromCharCode.apply(null, new Uint16Array(binaryView.buffer));
}
return binaryString;
}
function createURL(base64, sourcemapArg, enableUnicodeArg) {
var sourcemap = sourcemapArg === undefined ? null : sourcemapArg;
var enableUnicode = enableUnicodeArg === undefined ? false : enableUnicodeArg;
var source = decodeBase64(base64, enableUnicode);
var start = source.indexOf('\n', 10) + 1;
var body = source.substring(start) + (sourcemap ? '\/\/# sourceMappingURL=' + sourcemap : '');
var blob = new Blob([body], {
type: 'application/javascript'
});
return URL.createObjectURL(blob);
}
function createBase64WorkerFactory$1(base64, sourcemapArg, enableUnicodeArg) {
var url;
return function WorkerFactory(options) {
url = url || createURL(base64, sourcemapArg, enableUnicodeArg);
return new Worker(url, options);
};
}
var kIsNodeJS = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
function isNodeJS() {
return kIsNodeJS;
}
function createBase64WorkerFactory(base64, sourcemapArg, enableUnicodeArg) {
if (isNodeJS()) {
return createBase64WorkerFactory$2(base64, sourcemapArg, enableUnicodeArg);
}
return createBase64WorkerFactory$1(base64, sourcemapArg, enableUnicodeArg);
}
var WorkerFactory = createBase64WorkerFactory('Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICAgJ3VzZSBzdHJpY3QnOwoKICAgIC8qISAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KICAgIENvcHlyaWdodCAoYykgTWljcm9zb2Z0IENvcnBvcmF0aW9uLg0KDQogICAgUGVybWlzc2lvbiB0byB1c2UsIGNvcHksIG1vZGlmeSwgYW5kL29yIGRpc3RyaWJ1dGUgdGhpcyBzb2Z0d2FyZSBmb3IgYW55DQogICAgcHVycG9zZSB3aXRoIG9yIHdpdGhvdXQgZmVlIGlzIGhlcmVieSBncmFudGVkLg0KDQogICAgVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEICJBUyBJUyIgQU5EIFRIRSBBVVRIT1IgRElTQ0xBSU1TIEFMTCBXQVJSQU5USUVTIFdJVEgNCiAgICBSRUdBUkQgVE8gVEhJUyBTT0ZUV0FSRSBJTkNMVURJTkcgQUxMIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkNCiAgICBBTkQgRklUTkVTUy4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIEFVVEhPUiBCRSBMSUFCTEUgRk9SIEFOWSBTUEVDSUFMLCBESVJFQ1QsDQogICAgSU5ESVJFQ1QsIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyBPUiBBTlkgREFNQUdFUyBXSEFUU09FVkVSIFJFU1VMVElORyBGUk9NDQogICAgTE9TUyBPRiBVU0UsIERBVEEgT1IgUFJPRklUUywgV0hFVEhFUiBJTiBBTiBBQ1RJT04gT0YgQ09OVFJBQ1QsIE5FR0xJR0VOQ0UgT1INCiAgICBPVEhFUiBUT1JUSU9VUyBBQ1RJT04sIEFSSVNJTkcgT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgVVNFIE9SDQogICAgUEVSRk9STUFOQ0UgT0YgVEhJUyBTT0ZUV0FSRS4NCiAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiAqLw0KDQogICAgZnVuY3Rpb24gX19hd2FpdGVyKHRoaXNBcmcsIF9hcmd1bWVudHMsIFAsIGdlbmVyYXRvcikgew0KICAgICAgICBmdW5jdGlvbiBhZG9wdCh2YWx1ZSkgeyByZXR1cm4gdmFsdWUgaW5zdGFuY2VvZiBQID8gdmFsdWUgOiBuZXcgUChmdW5jdGlvbiAocmVzb2x2ZSkgeyByZXNvbHZlKHZhbHVlKTsgfSk7IH0NCiAgICAgICAgcmV0dXJuIG5ldyAoUCB8fCAoUCA9IFByb21pc2UpKShmdW5jdGlvbiAocmVzb2x2ZSwgcmVqZWN0KSB7DQogICAgICAgICAgICBmdW5jdGlvbiBmdWxmaWxsZWQodmFsdWUpIHsgdHJ5IHsgc3RlcChnZW5lcmF0b3IubmV4dCh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiByZWplY3RlZCh2YWx1ZSkgeyB0cnkgeyBzdGVwKGdlbmVyYXRvclsidGhyb3ciXSh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiBzdGVwKHJlc3VsdCkgeyByZXN1bHQuZG9uZSA/IHJlc29sdmUocmVzdWx0LnZhbHVlKSA6IGFkb3B0KHJlc3VsdC52YWx1ZSkudGhlbihmdWxmaWxsZWQsIHJlamVjdGVkKTsgfQ0KICAgICAgICAgICAgc3RlcCgoZ2VuZXJhdG9yID0gZ2VuZXJhdG9yLmFwcGx5KHRoaXNBcmcsIF9hcmd1bWVudHMgfHwgW10pKS5uZXh0KCkpOw0KICAgICAgICB9KTsNCiAgICB9CgogICAgLyoKICAgICAqIGJhc2U2NC1hcnJheWJ1ZmZlciAxLjAuMSA8aHR0cHM6Ly9naXRodWIuY29tL25pa2xhc3ZoL2Jhc2U2NC1hcnJheWJ1ZmZlcj4KICAgICAqIENvcHlyaWdodCAoYykgMjAyMSBOaWtsYXMgdm9uIEhlcnR6ZW4gPGh0dHBzOi8vaGVydHplbi5jb20+CiAgICAgKiBSZWxlYXNlZCB1bmRlciBNSVQgTGljZW5zZQogICAgICovCiAgICB2YXIgY2hhcnMgPSAnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyc7CiAgICAvLyBVc2UgYSBsb29rdXAgdGFibGUgdG8gZmluZCB0aGUgaW5kZXguCiAgICB2YXIgbG9va3VwID0gdHlwZW9mIFVpbnQ4QXJyYXkgPT09ICd1bmRlZmluZWQnID8gW10gOiBuZXcgVWludDhBcnJheSgyNTYpOwogICAgZm9yICh2YXIgaSA9IDA7IGkgPCBjaGFycy5sZW5ndGg7IGkrKykgewogICAgICAgIGxvb2t1cFtjaGFycy5jaGFyQ29kZUF0KGkpXSA9IGk7CiAgICB9CiAgICB2YXIgZW5jb2RlID0gZnVuY3Rpb24gKGFycmF5YnVmZmVyKSB7CiAgICAgICAgdmFyIGJ5dGVzID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlidWZmZXIpLCBpLCBsZW4gPSBieXRlcy5sZW5ndGgsIGJhc2U2NCA9ICcnOwogICAgICAgIGZvciAoaSA9IDA7IGkgPCBsZW47IGkgKz0gMykgewogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaV0gPj4gMl07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1soKGJ5dGVzW2ldICYgMykgPDwgNCkgfCAoYnl0ZXNbaSArIDFdID4+IDQpXTsKICAgICAgICAgICAgYmFzZTY0ICs9IGNoYXJzWygoYnl0ZXNbaSArIDFdICYgMTUpIDw8IDIpIHwgKGJ5dGVzW2kgKyAyXSA+PiA2KV07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1tieXRlc1tpICsgMl0gJiA2M107CiAgICAgICAgfQogICAgICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgJz0nOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgJz09JzsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGJhc2U2NDsKICAgIH07CgogICAgY29uc3QgbGFzdEJsb2JNYXAgPSBuZXcgTWFwKCk7DQogICAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gbmV3IE1hcCgpOw0KICAgIGZ1bmN0aW9uIGdldFRyYW5zcGFyZW50QmxvYkZvcih3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucykgew0KICAgICAgICByZXR1cm4gX19hd2FpdGVyKHRoaXMsIHZvaWQgMCwgdm9pZCAwLCBmdW5jdGlvbiogKCkgew0KICAgICAgICAgICAgY29uc3QgaWQgPSBgJHt3aWR0aH0tJHtoZWlnaHR9YDsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgaWYgKHRyYW5zcGFyZW50QmxvYk1hcC5oYXMoaWQpKQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJhbnNwYXJlbnRCbG9iTWFwLmdldChpZCk7DQogICAgICAgICAgICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsNCiAgICAgICAgICAgICAgICBvZmZzY3JlZW4uZ2V0Q29udGV4dCgnMmQnKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0geWllbGQgYmxvYi5hcnJheUJ1ZmZlcigpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7DQogICAgICAgICAgICAgICAgdHJhbnNwYXJlbnRCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICByZXR1cm4gYmFzZTY0Ow0KICAgICAgICAgICAgfQ0KICAgICAgICAgICAgZWxzZSB7DQogICAgICAgICAgICAgICAgcmV0dXJuICcnOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9KTsNCiAgICB9DQogICAgY29uc3Qgd29ya2VyID0gc2VsZjsNCiAgICB3b3JrZXIub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsNCiAgICAgICAgcmV0dXJuIF9fYXdhaXRlcih0aGlzLCB2b2lkIDAsIHZvaWQgMCwgZnVuY3Rpb24qICgpIHsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgY29uc3QgeyBpZCwgYml0bWFwLCB3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucyB9ID0gZS5kYXRhOw0KICAgICAgICAgICAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zKTsNCiAgICAgICAgICAgICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGN0eCA9IG9mZnNjcmVlbi5nZXRDb250ZXh0KCcyZCcpOw0KICAgICAgICAgICAgICAgIGN0eC5kcmF3SW1hZ2UoYml0bWFwLCAwLCAwKTsNCiAgICAgICAgICAgICAgICBiaXRtYXAuY2xvc2UoKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IHR5cGUgPSBibG9iLnR5cGU7DQogICAgICAgICAgICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSB5aWVsZCBibG9iLmFycmF5QnVmZmVyKCk7DQogICAgICAgICAgICAgICAgY29uc3QgYmFzZTY0ID0gZW5jb2RlKGFycmF5QnVmZmVyKTsNCiAgICAgICAgICAgICAgICBpZiAoIWxhc3RCbG9iTWFwLmhhcyhpZCkgJiYgKHlpZWxkIHRyYW5zcGFyZW50QmFzZTY0KSA9PT0gYmFzZTY0KSB7DQogICAgICAgICAgICAgICAgICAgIGxhc3RCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7DQogICAgICAgICAgICAgICAgd29ya2VyLnBvc3RNZXNzYWdlKHsNCiAgICAgICAgICAgICAgICAgICAgaWQsDQogICAgICAgICAgICAgICAgICAgIHR5cGUsDQogICAgICAgICAgICAgICAgICAgIGJhc2U2NCwNCiAgICAgICAgICAgICAgICAgICAgd2lkdGgsDQogICAgICAgICAgICAgICAgICAgIGhlaWdodCwNCiAgICAgICAgICAgICAgICB9KTsNCiAgICAgICAgICAgICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7DQogICAgICAgICAgICB9DQogICAgICAgICAgICBlbHNlIHsNCiAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSk7DQogICAgfTsKCn0pKCk7Cgo=', null, false);
class CanvasManager {
constructor(options) {
this.pendingCanvasMutations = new Map();
this.rafStamps = {
latestId: 0,
invokeId: null
};
this.frozen = false;
this.locked = false;
this.processMutation = (target, mutation) => {
const newFrame = this.rafStamps.invokeId && this.rafStamps.latestId !== this.rafStamps.invokeId;
if (newFrame || !this.rafStamps.invokeId) this.rafStamps.invokeId = this.rafStamps.latestId;
if (!this.pendingCanvasMutations.has(target)) {
this.pendingCanvasMutations.set(target, []);
}
this.pendingCanvasMutations.get(target).push(mutation);
};
const {
sampling = 'all',
win,
blockClass,
blockSelector,
recordCanvas,
dataURLOptions
} = options;
this.mutationCb = options.mutationCb;
this.mirror = options.mirror;
if (recordCanvas && sampling === 'all') this.initCanvasMutationObserver(win, blockClass, blockSelector);
if (recordCanvas && typeof sampling === 'number') this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {
dataURLOptions
});
}
reset() {
this.pendingCanvasMutations.clear();
this.resetObservers && this.resetObservers();
}
freeze() {
this.frozen = true;
}
unfreeze() {
this.frozen = false;
}
lock() {
this.locked = true;
}
unlock() {
this.locked = false;
}
initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {
const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector);
const snapshotInProgressMap = new Map();
const worker = new WorkerFactory();
worker.onmessage = e => {
const {
id
} = e.data;
snapshotInProgressMap.set(id, false);
if (!('base64' in e.data)) return;
const {
base64,
type,
width,
height
} = e.data;
this.mutationCb({
id,
type: CanvasContext['2D'],
commands: [{
property: 'clearRect',
args: [0, 0, width, height]
}, {
property: 'drawImage',
args: [{
rr_type: 'ImageBitmap',
args: [{
rr_type: 'Blob',
data: [{
rr_type: 'ArrayBuffer',
base64
}],
type
}]
}, 0, 0]
}]
});
};
const timeBetweenSnapshots = 1000 / fps;
let lastSnapshotTime = 0;
let rafId;
const getCanvas = () => {
const matchedCanvas = [];
win.document.querySelectorAll('canvas').forEach(canvas => {
if (!isBlocked(canvas, blockClass, blockSelector, true)) {
matchedCanvas.push(canvas);
}
});
return matchedCanvas;
};
const takeCanvasSnapshots = timestamp => {
if (lastSnapshotTime && timestamp - lastSnapshotTime < timeBetweenSnapshots) {
rafId = requestAnimationFrame(takeCanvasSnapshots);
return;
}
lastSnapshotTime = timestamp;
getCanvas().forEach(canvas => __awaiter(this, void 0, void 0, function* () {
var _a;
const id = this.mirror.getId(canvas);
if (snapshotInProgressMap.get(id)) return;
snapshotInProgressMap.set(id, true);
if (['webgl', 'webgl2'].includes(canvas.__context)) {
const context = canvas.getContext(canvas.__context);
if (((_a = context === null || context === void 0 ? void 0 : context.getContextAttributes()) === null || _a === void 0 ? void 0 : _a.preserveDrawingBuffer) === false) {
context === null || context === void 0 ? void 0 : context.clear(context.COLOR_BUFFER_BIT);
}
}
const bitmap = yield createImageBitmap(canvas);
worker.postMessage({
id,
bitmap,
width: canvas.width,
height: canvas.height,
dataURLOptions: options.dataURLOptions
}, [bitmap]);
}));
rafId = requestAnimationFrame(takeCanvasSnapshots);
};
rafId = requestAnimationFrame(takeCanvasSnapshots);
this.resetObservers = () => {
canvasContextReset();
cancelAnimationFrame(rafId);
};
}
initCanvasMutationObserver(win, blockClass, blockSelector) {
this.startRAFTimestamping();
this.startPendingCanvasMutationFlusher();
const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector);
const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, this.mirror);
this.resetObservers = () => {
canvasContextReset();
canvas2DReset();
canvasWebGL1and2Reset();
};
}
startPendingCanvasMutationFlusher() {
requestAnimationFrame(() => this.flushPendingCanvasMutations());
}
startRAFTimestamping() {
const setLatestRAFTimestamp = timestamp => {
this.rafStamps.latestId = timestamp;
requestAnimationFrame(setLatestRAFTimestamp);
};
requestAnimationFrame(setLatestRAFTimestamp);
}
flushPendingCanvasMutations() {
this.pendingCanvasMutations.forEach((values, canvas) => {
const id = this.mirror.getId(canvas);
this.flushPendingCanvasMutationFor(canvas, id);
});
requestAnimationFrame(() => this.flushPendingCanvasMutations());
}
flushPendingCanvasMutationFor(canvas, id) {
if (this.frozen || this.locked) {
return;
}
const valuesWithType = this.pendingCanvasMutations.get(canvas);
if (!valuesWithType || id === -1) return;
const values = valuesWithType.map(value => {
const rest = __rest(value, ["type"]);
return rest;
});
const {
type
} = valuesWithType[0];
this.mutationCb({
id,
type,
commands: values
});
this.pendingCanvasMutations.delete(canvas);
}
}
class StylesheetManager {
constructor(options) {
this.trackedLinkElements = new WeakSet();
this.styleMirror = new StyleSheetMirror();
this.mutationCb = options.mutationCb;
this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;
}
attachLinkElement(linkEl, childSn) {
if ('_cssText' in childSn.attributes) this.mutationCb({
adds: [],
removes: [],
texts: [],
attributes: [{
id: childSn.id,
attributes: childSn.attributes
}]
});
this.trackLinkElement(linkEl);
}
trackLinkElement(linkEl) {
if (this.trackedLinkElements.has(linkEl)) return;
this.trackedLinkElements.add(linkEl);
this.trackStylesheetInLinkElement(linkEl);
}
adoptStyleSheets(sheets, hostId) {
if (sheets.length === 0) return;
const adoptedStyleSheetData = {
id: hostId,
styleIds: []
};
const styles = [];
for (const sheet of sheets) {
let styleId;
if (!this.styleMirror.has(sheet)) {
styleId = this.styleMirror.add(sheet);
const rules = Array.from(sheet.rules || CSSRule);
styles.push({
styleId,
rules: rules.map((r, index) => {
return {
rule: getCssRuleString(r),
index
};
})
});
} else styleId = this.styleMirror.getId(sheet);
adoptedStyleSheetData.styleIds.push(styleId);
}
if (styles.length > 0) adoptedStyleSheetData.styles = styles;
this.adoptedStyleSheetCb(adoptedStyleSheetData);
}
reset() {
this.styleMirror.reset();
this.trackedLinkElements = new WeakSet();
}
trackStylesheetInLinkElement(linkEl) {}
}
function wrapEvent(e) {
return Object.assign(Object.assign({}, e), {
timestamp: Date.now()
});
}
let wrappedEmit;
let takeFullSnapshot;
let canvasManager;
let recording = false;
const mirror = createMirror();
function record() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
emit,
checkoutEveryNms,
checkoutEveryNth,
blockClass = 'rr-block',
blockSelector = null,
ignoreClass = 'rr-ignore',
maskTextClass = 'rr-mask',
maskTextSelector = null,
inlineStylesheet = true,
maskAllInputs,
maskInputOptions: _maskInputOptions,
slimDOMOptions: _slimDOMOptions,
maskInputFn,
maskTextFn,
hooks,
packFn,
sampling = {},
dataURLOptions = {},
mousemoveWait,
recordCanvas = false,
recordCrossOriginIframes = false,
recordAfter = options.recordAfter === 'DOMContentLoaded' ? options.recordAfter : 'load',
userTriggeredOnInput = false,
collectFonts = false,
inlineImages = false,
plugins,
keepIframeSrcFn = () => false,
ignoreCSSAttributes = new Set([])
} = options;
const inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;
let passEmitsToParent = false;
if (!inEmittingFrame) {
try {
window.parent.document;
passEmitsToParent = false;
} catch (e) {
passEmitsToParent = true;
}
}
if (inEmittingFrame && !emit) {
throw new Error('emit function is required');
}
if (mousemoveWait !== undefined && sampling.mousemove === undefined) {
sampling.mousemove = mousemoveWait;
}
mirror.reset();
const maskInputOptions = maskAllInputs === true ? {
color: true,
date: true,
'datetime-local': true,
email: true,
month: true,
number: true,
range: true,
search: true,
tel: true,
text: true,
time: true,
url: true,
week: true,
textarea: true,
select: true,
password: true
} : _maskInputOptions !== undefined ? _maskInputOptions : {
password: true
};
const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all' ? {
script: true,
comment: true,
headFavicon: true,
headWhitespace: true,
headMetaSocial: true,
headMetaRobots: true,
headMetaHttpEquiv: true,
headMetaVerification: true,
headMetaAuthorship: _slimDOMOptions === 'all',
headMetaDescKeywords: _slimDOMOptions === 'all'
} : _slimDOMOptions ? _slimDOMOptions : {};
polyfill();
let lastFullSnapshotEvent;
let incrementalSnapshotCount = 0;
const eventProcessor = e => {
for (const plugin of plugins || []) {
if (plugin.eventProcessor) {
e = plugin.eventProcessor(e);
}
}
if (packFn && !passEmitsToParent) {
e = packFn(e);
}
return e;
};
wrappedEmit = (e, isCheckout) => {
var _a;
if (((_a = mutationBuffers[0]) === null || _a === void 0 ? void 0 : _a.isFrozen()) && e.type !== EventType.FullSnapshot && !(e.type === EventType.IncrementalSnapshot && e.data.source === IncrementalSource.Mutation)) {
mutationBuffers.forEach(buf => buf.unfreeze());
}
if (inEmittingFrame) {
emit === null || emit === void 0 ? void 0 : emit(eventProcessor(e), isCheckout);
} else if (passEmitsToParent) {
const message = {
type: 'rrweb',
event: eventProcessor(e),
origin: window.location.origin,
isCheckout
};
window.parent.postMessage(message, '*');
}
if (e.type === EventType.FullSnapshot) {
lastFullSnapshotEvent = e;
incrementalSnapshotCount = 0;
} else if (e.type === EventType.IncrementalSnapshot) {
if (e.data.source === IncrementalSource.Mutation && e.data.isAttachIframe) {
return;
}
incrementalSnapshotCount++;
const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
const exceedTime = checkoutEveryNms && e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
if (exceedCount || exceedTime) {
takeFullSnapshot(true);
}
}
};
const wrappedMutationEmit = m => {
wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: Object.assign({
source: IncrementalSource.Mutation
}, m)
}));
};
const wrappedScrollEmit = p => wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: Object.assign({
source: IncrementalSource.Scroll
}, p)
}));
const wrappedCanvasMutationEmit = p => wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: Object.assign({
source: IncrementalSource.CanvasMutation
}, p)
}));
const wrappedAdoptedStyleSheetEmit = a => wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: Object.assign({
source: IncrementalSource.AdoptedStyleSheet
}, a)
}));
const stylesheetManager = new StylesheetManager({
mutationCb: wrappedMutationEmit,
adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit
});
const iframeManager = new IframeManager({
mirror,
mutationCb: wrappedMutationEmit,
stylesheetManager: stylesheetManager,
recordCrossOriginIframes,
wrappedEmit
});
for (const plugin of plugins || []) {
if (plugin.getMirror) plugin.getMirror({
nodeMirror: mirror,
crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror
});
}
canvasManager = new CanvasManager({
recordCanvas,
mutationCb: wrappedCanvasMutationEmit,
win: window,
blockClass,
blockSelector,
mirror,
sampling: sampling.canvas,
dataURLOptions
});
const shadowDomManager = new ShadowDomManager({
mutationCb: wrappedMutationEmit,
scrollCb: wrappedScrollEmit,
bypassOptions: {
blockClass,
blockSelector,
maskTextClass,
maskTextSelector,
inlineStylesheet,
maskInputOptions,
dataURLOptions,
maskTextFn,
maskInputFn,
recordCanvas,
inlineImages,
sampling,
slimDOMOptions,
iframeManager,
stylesheetManager,
canvasManager,
keepIframeSrcFn,
processedNodeManager
},
mirror
});
takeFullSnapshot = function () {
let isCheckout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
wrappedEmit(wrapEvent({
type: EventType.Meta,
data: {
href: window.location.href,
width: getWindowWidth(),
height: getWindowHeight()
}
}), isCheckout);
stylesheetManager.reset();
shadowDomManager.init();
mutationBuffers.forEach(buf => buf.lock());
const node = snapshot(document, {
mirror,
blockClass,
blockSelector,
maskTextClass,
maskTextSelector,
inlineStylesheet,
maskAllInputs: maskInputOptions,
maskTextFn,
slimDOM: slimDOMOptions,
dataURLOptions,
recordCanvas,
inlineImages,
onSerialize: n => {
if (isSerializedIframe(n, mirror)) {
iframeManager.addIframe(n);
}
if (isSerializedStylesheet(n, mirror)) {
stylesheetManager.trackLinkElement(n);
}
if (hasShadowRoot(n)) {
shadowDomManager.addShadowRoot(n.shadowRoot, document);
}
},
onIframeLoad: (iframe, childSn) => {
iframeManager.attachIframe(iframe, childSn);
shadowDomManager.observeAttachShadow(iframe);
},
onStylesheetLoad: (linkEl, childSn) => {
stylesheetManager.attachLinkElement(linkEl, childSn);
},
keepIframeSrcFn
});
if (!node) {
return console.warn('Failed to snapshot the document');
}
wrappedEmit(wrapEvent({
type: EventType.FullSnapshot,
data: {
node,
initialOffset: getWindowScroll(window)
}
}));
mutationBuffers.forEach(buf => buf.unlock());
if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0) stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
};
try {
const handlers = [];
const observe = doc => {
var _a;
return initObservers({
mutationCb: wrappedMutationEmit,
mousemoveCb: (positions, source) => wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: {
source,
positions
}
})),
mouseInteractionCb: d => wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: Object.assign({
source: IncrementalSource.MouseInteraction
}, d)
})),
scrollCb: wrappedScrollEmit,
viewportResizeCb: d => wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: Object.assign({
source: IncrementalSource.ViewportResize
}, d)
})),
inputCb: v => wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: Object.assign({
source: IncrementalSource.Input
}, v)
})),
mediaInteractionCb: p => wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: Object.assign({
source: IncrementalSource.MediaInteraction
}, p)
})),
styleSheetRuleCb: r => wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: Object.assign({
source: IncrementalSource.StyleSheetRule
}, r)
})),
styleDeclarationCb: r => wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: Object.assign({
source: IncrementalSource.StyleDeclaration
}, r)
})),
canvasMutationCb: wrappedCanvasMutationEmit,
fontCb: p => wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: Object.assign({
source: IncrementalSource.Font
}, p)
})),
selectionCb: p => {
wrappedEmit(wrapEvent({
type: EventType.IncrementalSnapshot,
data: Object.assign({
source: IncrementalSource.Selection
}, p)
}));
},
blockClass,
ignoreClass,
maskTextClass,
maskTextSelector,
maskInputOptions,
inlineStylesheet,
sampling,
recordCanvas,
inlineImages,
userTriggeredOnInput,
collectFonts,
doc,
maskInputFn,
maskTextFn,
keepIframeSrcFn,
blockSelector,
slimDOMOptions,
dataURLOptions,
mirror,
iframeManager,
stylesheetManager,
shadowDomManager,
processedNodeManager,
canvasManager,
ignoreCSSAttributes,
plugins: ((_a = plugins === null || plugins === void 0 ? void 0 : plugins.filter(p => p.observer)) === null || _a === void 0 ? void 0 : _a.map(p => ({
observer: p.observer,
options: p.options,
callback: payload => wrappedEmit(wrapEvent({
type: EventType.Plugin,
data: {
plugin: p.name,
payload
}
}))
}))) || []
}, hooks);
};
iframeManager.addLoadListener(iframeEl => {
try {
handlers.push(observe(iframeEl.contentDocument));
} catch (error) {
console.warn(error);
}
});
const init = () => {
takeFullSnapshot();
handlers.push(observe(document));
recording = true;
};
if (document.readyState === 'interactive' || document.readyState === 'complete') {
init();
} else {
handlers.push(on('DOMContentLoaded', () => {
wrappedEmit(wrapEvent({
type: EventType.DomContentLoaded,
data: {}
}));
if (recordAfter === 'DOMContentLoaded') init();
}));
handlers.push(on('load', () => {
wrappedEmit(wrapEvent({
type: EventType.Load,
data: {}
}));
if (recordAfter === 'load') init();
}, window));
}
return () => {
handlers.forEach(h => h());
recording = false;
};
} catch (error) {
console.warn(error);
}
}
record.addCustomEvent = (tag, payload) => {
if (!recording) {
throw new Error('please add custom event after start recording');
}
wrappedEmit(wrapEvent({
type: EventType.Custom,
data: {
tag,
payload
}
}));
};
record.freezePage = () => {
mutationBuffers.forEach(buf => buf.freeze());
};
record.takeFullSnapshot = isCheckout => {
if (!recording) {
throw new Error('please take full snapshot after start recording');
}
takeFullSnapshot(isCheckout);
};
record.mirror = mirror;
/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
/* eslint-disable space-unary-ops */
/* Public constants ==========================================================*/
/* ===========================================================================*/
//const Z_FILTERED = 1;
//const Z_HUFFMAN_ONLY = 2;
//const Z_RLE = 3;
const Z_FIXED$1 = 4;
//const Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
const Z_BINARY = 0;
const Z_TEXT = 1;
//const Z_ASCII = 1; // = Z_TEXT
const Z_UNKNOWN$1 = 2;
/*============================================================================*/
function zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
const STORED_BLOCK = 0;
const STATIC_TREES = 1;
const DYN_TREES = 2;
/* The three kinds of block type */
const MIN_MATCH$1 = 3;
const MAX_MATCH$1 = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
const LENGTH_CODES$1 = 29;
/* number of length codes, not counting the special END_BLOCK code */
const LITERALS$1 = 256;
/* number of literal bytes 0..255 */
const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;
/* number of Literal or Length codes, including the END_BLOCK code */
const D_CODES$1 = 30;
/* number of distance codes */
const BL_CODES$1 = 19;
/* number of codes used to transfer the bit lengths */
const HEAP_SIZE$1 = 2 * L_CODES$1 + 1;
/* maximum heap size */
const MAX_BITS$1 = 15;
/* All codes must not exceed MAX_BITS bits */
const Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
const MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
const END_BLOCK = 256;
/* end of block literal code */
const REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
const REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
const REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
/* eslint-disable comma-spacing,array-bracket-spacing */
const extra_lbits = /* extra bits for each length code */
new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);
const extra_dbits = /* extra bits for each distance code */
new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);
const extra_blbits = /* extra bits for each bit length code */
new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);
const bl_order =
new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);
/* eslint-enable comma-spacing,array-bracket-spacing */
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
const DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
const static_ltree = new Array((L_CODES$1 + 2) * 2);
zero$1(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
const static_dtree = new Array(D_CODES$1 * 2);
zero$1(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
const _dist_code = new Array(DIST_CODE_LEN);
zero$1(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
const _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);
zero$1(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
const base_length = new Array(LENGTH_CODES$1);
zero$1(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
const base_dist = new Array(D_CODES$1);
zero$1(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
}
let static_l_desc;
let static_d_desc;
let static_bl_desc;
function TreeDesc(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
}
const d_code = (dist) => {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
};
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
const put_short = (s, w) => {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
};
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
const send_bits = (s, value, length) => {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
};
const send_code = (s, c, tree) => {
send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
};
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
const bi_reverse = (code, len) => {
let res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
};
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
const bi_flush = (s) => {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
};
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
const gen_bitlen = (s, desc) => {
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
const tree = desc.dyn_tree;
const max_code = desc.max_code;
const stree = desc.stat_desc.static_tree;
const has_stree = desc.stat_desc.has_stree;
const extra = desc.stat_desc.extra_bits;
const base = desc.stat_desc.extra_base;
const max_length = desc.stat_desc.max_length;
let h; /* heap index */
let n, m; /* iterate over the tree elements */
let bits; /* bit length */
let xbits; /* extra bits */
let f; /* frequency */
let overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS$1; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) {
n = s.heap[h];
bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n * 2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n - base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Tracev((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length - 1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m * 2 + 1]/*.Len*/ !== bits) {
// Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
tree[m * 2 + 1]/*.Len*/ = bits;
}
n--;
}
}
};
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
const gen_codes = (tree, max_code, bl_count) => {
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */
let code = 0; /* running code value */
let bits; /* bit index */
let n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS$1; bits++) {
code = (code + bl_count[bits - 1]) << 1;
next_code[bits] = code;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
let len = tree[n * 2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
};
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
const tr_static_init = () => {
let n; /* iterates over tree elements */
let bits; /* bit counter */
let length; /* length value */
let code; /* code value */
let dist; /* distance index */
const bl_count = new Array(MAX_BITS$1 + 1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES$1 - 1; code++) {
base_length[code] = length;
for (n = 0; n < (1 << extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length - 1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1 << extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES$1; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS$1; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n * 2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n * 2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n * 2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n * 2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES$1 + 1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES$1; n++) {
static_dtree[n * 2 + 1]/*.Len*/ = 5;
static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1);
static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS);
//static_init_done = true;
};
/* ===========================================================================
* Initialize a new block.
*/
const init_block = (s) => {
let n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.sym_next = s.matches = 0;
};
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
const bi_windup = (s) =>
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
};
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
const smaller = (tree, n, m, depth) => {
const _n2 = n * 2;
const _m2 = m * 2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
};
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
const pqdownheap = (s, tree, k) => {
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
const v = s.heap[k];
let j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
};
// inlined manually
// const SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
const compress_block = (s, ltree, dtree) => {
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
let dist; /* distance of matched string */
let lc; /* match length or unmatched char (if dist == 0) */
let sx = 0; /* running index in sym_buf */
let code; /* the code to send */
let extra; /* number of extra bits to send */
if (s.sym_next !== 0) {
do {
dist = s.pending_buf[s.sym_buf + sx++] & 0xff;
dist += (s.pending_buf[s.sym_buf + sx++] & 0xff) << 8;
lc = s.pending_buf[s.sym_buf + sx++];
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and sym_buf is ok: */
//Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
} while (sx < s.sym_next);
}
send_code(s, END_BLOCK, ltree);
};
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
const build_tree = (s, desc) => {
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
const tree = desc.dyn_tree;
const stree = desc.stat_desc.static_tree;
const has_stree = desc.stat_desc.has_stree;
const elems = desc.stat_desc.elems;
let n, m; /* iterate over heap elements */
let max_code = -1; /* largest code with non zero frequency */
let node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE$1;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n * 2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node * 2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
};
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
const scan_tree = (s, tree, max_code) => {
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
let n; /* iterates over all tree elements */
let prevlen = -1; /* last emitted length */
let curlen; /* length of current code */
let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
let count = 0; /* repeat count of the current code */
let max_count = 7; /* max repeat count */
let min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
};
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
const send_tree = (s, tree, max_code) => {
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
let n; /* iterates over all tree elements */
let prevlen = -1; /* last emitted length */
let curlen; /* length of current code */
let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
let count = 0; /* repeat count of the current code */
let max_count = 7; /* max repeat count */
let min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count - 3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count - 3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count - 11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
};
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
const build_bl_tree = (s) => {
let max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
};
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
const send_all_trees = (s, lcodes, dcodes, blcodes) => {
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
let rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes - 1, 5);
send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
};
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "block list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
const detect_data_type = (s) => {
/* block_mask is the bit mask of block-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
let block_mask = 0xf3ffc07f;
let n;
/* Check for non-textual ("block-listed") bytes. */
for (n = 0; n <= 31; n++, block_mask >>>= 1) {
if ((block_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("allow-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS$1; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "block-listed" or "allow-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
};
let static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
const _tr_init$1 = (s) =>
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
};
/* ===========================================================================
* Send a stored block
*/
const _tr_stored_block$1 = (s, buf, stored_len, last) => {
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
bi_windup(s); /* align on byte boundary */
put_short(s, stored_len);
put_short(s, ~stored_len);
if (stored_len) {
s.pending_buf.set(s.window.subarray(buf, buf + stored_len), s.pending);
}
s.pending += stored_len;
};
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
const _tr_align$1 = (s) => {
send_bits(s, STATIC_TREES << 1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
};
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and write out the encoded block.
*/
const _tr_flush_block$1 = (s, buf, stored_len, last) => {
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
let opt_lenb, static_lenb; /* opt_len and static_len in bytes */
let max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN$1) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len + 3 + 7) >>> 3;
static_lenb = (s.static_len + 3 + 7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->sym_next / 3));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block$1(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
};
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
const _tr_tally$1 = (s, dist, lc) => {
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
s.pending_buf[s.sym_buf + s.sym_next++] = dist;
s.pending_buf[s.sym_buf + s.sym_next++] = dist >> 8;
s.pending_buf[s.sym_buf + s.sym_next++] = lc;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc * 2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
return (s.sym_next === s.sym_end);
};
var _tr_init_1 = _tr_init$1;
var _tr_stored_block_1 = _tr_stored_block$1;
var _tr_flush_block_1 = _tr_flush_block$1;
var _tr_tally_1 = _tr_tally$1;
var _tr_align_1 = _tr_align$1;
var trees = {
_tr_init: _tr_init_1,
_tr_stored_block: _tr_stored_block_1,
_tr_flush_block: _tr_flush_block_1,
_tr_tally: _tr_tally_1,
_tr_align: _tr_align_1
};
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It isn't worth it to make additional optimizations as in original.
// Small size is preferable.
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
const adler32 = (adler, buf, len, pos) => {
let s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
};
var adler32_1 = adler32;
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
// Use ordinary array, since untyped makes no boost here
const makeTable = () => {
let c, table = [];
for (var n = 0; n < 256; n++) {
c = n;
for (var k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
};
// Create table on load. Just 255 signed longs. Not a problem.
const crcTable = new Uint32Array(makeTable());
const crc32 = (crc, buf, len, pos) => {
const t = crcTable;
const end = pos + len;
crc ^= -1;
for (let i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
};
var crc32_1 = crc32;
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
var messages = {
2: 'need dictionary', /* Z_NEED_DICT 2 */
1: 'stream end', /* Z_STREAM_END 1 */
0: '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
var constants$2 = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
const { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees;
/* Public constants ==========================================================*/
/* ===========================================================================*/
const {
Z_NO_FLUSH: Z_NO_FLUSH$2, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$3, Z_BLOCK: Z_BLOCK$1,
Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_BUF_ERROR: Z_BUF_ERROR$1,
Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,
Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,
Z_UNKNOWN,
Z_DEFLATED: Z_DEFLATED$2
} = constants$2;
/*============================================================================*/
const MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
const MAX_WBITS$1 = 15;
/* 32K LZ77 window */
const DEF_MEM_LEVEL = 8;
const LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
const LITERALS = 256;
/* number of literal bytes 0..255 */
const L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
const D_CODES = 30;
/* number of distance codes */
const BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
const HEAP_SIZE = 2 * L_CODES + 1;
/* maximum heap size */
const MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
const MIN_MATCH = 3;
const MAX_MATCH = 258;
const MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
const PRESET_DICT = 0x20;
const INIT_STATE = 42; /* zlib header -> BUSY_STATE */
//#ifdef GZIP
const GZIP_STATE = 57; /* gzip header -> BUSY_STATE | EXTRA_STATE */
//#endif
const EXTRA_STATE = 69; /* gzip extra block -> NAME_STATE */
const NAME_STATE = 73; /* gzip file name -> COMMENT_STATE */
const COMMENT_STATE = 91; /* gzip comment -> HCRC_STATE */
const HCRC_STATE = 103; /* gzip header CRC -> BUSY_STATE */
const BUSY_STATE = 113; /* deflate -> FINISH_STATE */
const FINISH_STATE = 666; /* stream complete */
const BS_NEED_MORE = 1; /* block not completed, need more input or more output */
const BS_BLOCK_DONE = 2; /* block flush performed */
const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
const OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
const err = (strm, errorCode) => {
strm.msg = messages[errorCode];
return errorCode;
};
const rank = (f) => {
return ((f) * 2) - ((f) > 4 ? 9 : 0);
};
const zero = (buf) => {
let len = buf.length; while (--len >= 0) { buf[len] = 0; }
};
/* ===========================================================================
* Slide the hash table when sliding the window down (could be avoided with 32
* bit values at the expense of memory usage). We slide even when level == 0 to
* keep the hash table consistent if we switch back to level > 0 later.
*/
const slide_hash = (s) => {
let n, m;
let p;
let wsize = s.w_size;
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= wsize ? m - wsize : 0);
} while (--n);
n = wsize;
//#ifndef FASTEST
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= wsize ? m - wsize : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
//#endif
};
/* eslint-disable new-cap */
let HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;
// This hash causes less collisions, https://github.com/nodeca/pako/issues/135
// But breaks binary compatibility
//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;
let HASH = HASH_ZLIB;
/* =========================================================================
* Flush as much pending output as possible. All deflate() output, except for
* some deflate_stored() output, goes through this function so some
* applications may wish to modify it to avoid allocating a large
* strm->next_out buffer and copying into it. (See also read_buf()).
*/
const flush_pending = (strm) => {
const s = strm.state;
//_tr_flush_bits(s);
let len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
};
const flush_block_only = (s, last) => {
_tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
};
const put_byte = (s, b) => {
s.pending_buf[s.pending++] = b;
};
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
const putShortMSB = (s, b) => {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
};
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
const read_buf = (strm, buf, start, size) => {
let len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
// zmemcpy(buf, strm->next_in, len);
buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);
if (strm.state.wrap === 1) {
strm.adler = adler32_1(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32_1(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
};
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
const longest_match = (s, cur_match) => {
let chain_length = s.max_chain_length; /* max hash chain length */
let scan = s.strstart; /* current string */
let match; /* matched string */
let len; /* length of current match */
let best_len = s.prev_length; /* best match length so far */
let nice_match = s.nice_match; /* stop if match long enough */
const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
const _win = s.window; // shortcut
const wmask = s.w_mask;
const prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
const strend = s.strstart + MAX_MATCH;
let scan_end1 = _win[scan + best_len - 1];
let scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
};
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
const fill_window = (s) => {
const _w_size = s.w_size;
let n, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
if (s.insert > s.strstart) {
s.insert = s.strstart;
}
slide_hash(s);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// const curr = s.strstart + s.lookahead;
// let init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
};
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
*
* In case deflateParams() is used to later switch to a non-zero compression
* level, s->matches (otherwise unused when storing) keeps track of the number
* of hash table slides to perform. If s->matches is 1, then one hash table
* slide will be done when switching. If s->matches is 2, the maximum value
* allowed here, then the hash table will be cleared, since two or more slides
* is the same as a clear.
*
* deflate_stored() is written to minimize the number of times an input byte is
* copied. It is most efficient with large input and output buffers, which
* maximizes the opportunites to have a single copy from next_in to next_out.
*/
const deflate_stored = (s, flush) => {
/* Smallest worthy block size when not flushing or finishing. By default
* this is 32K. This can be as small as 507 bytes for memLevel == 1. For
* large input and output buffers, the stored block size will be larger.
*/
let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5;
/* Copy as many min_block or larger stored blocks directly to next_out as
* possible. If flushing, copy the remaining available input to next_out as
* stored blocks, if there is enough space.
*/
let len, left, have, last = 0;
let used = s.strm.avail_in;
do {
/* Set len to the maximum size block that we can copy directly with the
* available input data and output space. Set left to how much of that
* would be copied from what's left in the window.
*/
len = 65535/* MAX_STORED */; /* maximum deflate stored block length */
have = (s.bi_valid + 42) >> 3; /* number of header bytes */
if (s.strm.avail_out < have) { /* need room for header */
break;
}
/* maximum stored block length that will fit in avail_out: */
have = s.strm.avail_out - have;
left = s.strstart - s.block_start; /* bytes left in window */
if (len > left + s.strm.avail_in) {
len = left + s.strm.avail_in; /* limit len to the input */
}
if (len > have) {
len = have; /* limit len to the output */
}
/* If the stored block would be less than min_block in length, or if
* unable to copy all of the available input when flushing, then try
* copying to the window and the pending buffer instead. Also don't
* write an empty block when flushing -- deflate() does that.
*/
if (len < min_block && ((len === 0 && flush !== Z_FINISH$3) ||
flush === Z_NO_FLUSH$2 ||
len !== left + s.strm.avail_in)) {
break;
}
/* Make a dummy stored block in pending to get the header bytes,
* including any pending bits. This also updates the debugging counts.
*/
last = flush === Z_FINISH$3 && len === left + s.strm.avail_in ? 1 : 0;
_tr_stored_block(s, 0, 0, last);
/* Replace the lengths in the dummy stored block with len. */
s.pending_buf[s.pending - 4] = len;
s.pending_buf[s.pending - 3] = len >> 8;
s.pending_buf[s.pending - 2] = ~len;
s.pending_buf[s.pending - 1] = ~len >> 8;
/* Write the stored block header bytes. */
flush_pending(s.strm);
//#ifdef ZLIB_DEBUG
// /* Update debugging counts for the data about to be copied. */
// s->compressed_len += len << 3;
// s->bits_sent += len << 3;
//#endif
/* Copy uncompressed bytes from the window to next_out. */
if (left) {
if (left > len) {
left = len;
}
//zmemcpy(s->strm->next_out, s->window + s->block_start, left);
s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);
s.strm.next_out += left;
s.strm.avail_out -= left;
s.strm.total_out += left;
s.block_start += left;
len -= left;
}
/* Copy uncompressed bytes directly from next_in to next_out, updating
* the check value.
*/
if (len) {
read_buf(s.strm, s.strm.output, s.strm.next_out, len);
s.strm.next_out += len;
s.strm.avail_out -= len;
s.strm.total_out += len;
}
} while (last === 0);
/* Update the sliding window with the last s->w_size bytes of the copied
* data, or append all of the copied data to the existing window if less
* than s->w_size bytes were copied. Also update the number of bytes to
* insert in the hash tables, in the event that deflateParams() switches to
* a non-zero compression level.
*/
used -= s.strm.avail_in; /* number of input bytes directly copied */
if (used) {
/* If any input was used, then no unused input remains in the window,
* therefore s->block_start == s->strstart.
*/
if (used >= s.w_size) { /* supplant the previous history */
s.matches = 2; /* clear hash */
//zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0);
s.strstart = s.w_size;
s.insert = s.strstart;
}
else {
if (s.window_size - s.strstart <= used) {
/* Slide the window down. */
s.strstart -= s.w_size;
//zmemcpy(s->window, s->window + s->w_size, s->strstart);
s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);
if (s.matches < 2) {
s.matches++; /* add a pending slide_hash() */
}
if (s.insert > s.strstart) {
s.insert = s.strstart;
}
}
//zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart);
s.strstart += used;
s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used;
}
s.block_start = s.strstart;
}
if (s.high_water < s.strstart) {
s.high_water = s.strstart;
}
/* If the last block was written to next_out, then done. */
if (last) {
return BS_FINISH_DONE;
}
/* If flushing and all input has been consumed, then done. */
if (flush !== Z_NO_FLUSH$2 && flush !== Z_FINISH$3 &&
s.strm.avail_in === 0 && s.strstart === s.block_start) {
return BS_BLOCK_DONE;
}
/* Fill the window with any remaining input. */
have = s.window_size - s.strstart;
if (s.strm.avail_in > have && s.block_start >= s.w_size) {
/* Slide the window down. */
s.block_start -= s.w_size;
s.strstart -= s.w_size;
//zmemcpy(s->window, s->window + s->w_size, s->strstart);
s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);
if (s.matches < 2) {
s.matches++; /* add a pending slide_hash() */
}
have += s.w_size; /* more space now */
if (s.insert > s.strstart) {
s.insert = s.strstart;
}
}
if (have > s.strm.avail_in) {
have = s.strm.avail_in;
}
if (have) {
read_buf(s.strm, s.window, s.strstart, have);
s.strstart += have;
s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have;
}
if (s.high_water < s.strstart) {
s.high_water = s.strstart;
}
/* There was not enough avail_out to write a complete worthy or flushed
* stored block to next_out. Write a stored block to pending instead, if we
* have enough input for a worthy block, or if flushing and there is enough
* room for the remaining input as a stored block in the pending buffer.
*/
have = (s.bi_valid + 42) >> 3; /* number of header bytes */
/* maximum stored block length that will fit in pending: */
have = s.pending_buf_size - have > 65535/* MAX_STORED */ ? 65535/* MAX_STORED */ : s.pending_buf_size - have;
min_block = have > s.w_size ? s.w_size : have;
left = s.strstart - s.block_start;
if (left >= min_block ||
((left || flush === Z_FINISH$3) && flush !== Z_NO_FLUSH$2 &&
s.strm.avail_in === 0 && left <= have)) {
len = left > have ? have : left;
last = flush === Z_FINISH$3 && s.strm.avail_in === 0 &&
len === left ? 1 : 0;
_tr_stored_block(s, s.block_start, len, last);
s.block_start += len;
flush_pending(s.strm);
}
/* We've done all we can with the available input and output. */
return last ? BS_FINISH_STARTED : BS_NEED_MORE;
};
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
const deflate_fast = (s, flush) => {
let hash_head; /* head of the hash chain */
let bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = _tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
if (flush === Z_FINISH$3) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.sym_next) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
};
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
const deflate_slow = (s, flush) => {
let hash_head; /* head of hash chain */
let bflush; /* set if current block must be flushed */
let max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH - 1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH - 1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length - 1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH - 1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
if (flush === Z_FINISH$3) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.sym_next) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
};
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
const deflate_rle = (s, flush) => {
let bflush; /* set if current block must be flushed */
let prev; /* byte at distance one to match */
let scan, strend; /* scan goes up to strend for length of run */
const _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$2) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = _tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH$3) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.sym_next) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
};
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
const deflate_huff = (s, flush) => {
let bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH$2) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = _tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH$3) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.sym_next) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
};
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
function Config(good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
}
const configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
const lm_init = (s) => {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
};
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED$2; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2);
this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2);
this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new Uint16Array(MAX_BITS + 1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.sym_buf = 0; /* buffer for distances and literals/lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.sym_next = 0; /* running index in sym_buf */
this.sym_end = 0; /* symbol table full when sym_next reaches this */
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
/* =========================================================================
* Check for a valid deflate stream state. Return 0 if ok, 1 if not.
*/
const deflateStateCheck = (strm) => {
if (!strm) {
return 1;
}
const s = strm.state;
if (!s || s.strm !== strm || (s.status !== INIT_STATE &&
//#ifdef GZIP
s.status !== GZIP_STATE &&
//#endif
s.status !== EXTRA_STATE &&
s.status !== NAME_STATE &&
s.status !== COMMENT_STATE &&
s.status !== HCRC_STATE &&
s.status !== BUSY_STATE &&
s.status !== FINISH_STATE)) {
return 1;
}
return 0;
};
const deflateResetKeep = (strm) => {
if (deflateStateCheck(strm)) {
return err(strm, Z_STREAM_ERROR$2);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
const s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status =
//#ifdef GZIP
s.wrap === 2 ? GZIP_STATE :
//#endif
s.wrap ? INIT_STATE : BUSY_STATE;
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = -2;
_tr_init(s);
return Z_OK$3;
};
const deflateReset = (strm) => {
const ret = deflateResetKeep(strm);
if (ret === Z_OK$3) {
lm_init(strm.state);
}
return ret;
};
const deflateSetHeader = (strm, head) => {
if (deflateStateCheck(strm) || strm.state.wrap !== 2) {
return Z_STREAM_ERROR$2;
}
strm.state.gzhead = head;
return Z_OK$3;
};
const deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR$2;
}
let wrap = 1;
if (level === Z_DEFAULT_COMPRESSION$1) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED || (windowBits === 8 && wrap !== 1)) {
return err(strm, Z_STREAM_ERROR$2);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
const s = new DeflateState();
strm.state = s;
s.strm = strm;
s.status = INIT_STATE; /* to pass state test in deflateReset() */
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new Uint8Array(s.w_size * 2);
s.head = new Uint16Array(s.hash_size);
s.prev = new Uint16Array(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
/* We overlay pending_buf and sym_buf. This works since the average size
* for length/distance pairs over any compressed block is assured to be 31
* bits or less.
*
* Analysis: The longest fixed codes are a length code of 8 bits plus 5
* extra bits, for lengths 131 to 257. The longest fixed distance codes are
* 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
* possible fixed-codes length/distance pair is then 31 bits total.
*
* sym_buf starts one-fourth of the way into pending_buf. So there are
* three bytes in sym_buf for every four bytes in pending_buf. Each symbol
* in sym_buf is three bytes -- two for the distance and one for the
* literal/length. As each symbol is consumed, the pointer to the next
* sym_buf value to read moves forward three bytes. From that symbol, up to
* 31 bits are written to pending_buf. The closest the written pending_buf
* bits gets to the next sym_buf symbol to read is just before the last
* code is written. At that time, 31*(n-2) bits have been written, just
* after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
* 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
* symbols are written.) The closest the writing gets to what is unread is
* then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
* can range from 128 to 32768.
*
* Therefore, at a minimum, there are 142 bits of space between what is
* written and what is read in the overlain buffers, so the symbols cannot
* be overwritten by the compressed data. That space is actually 139 bits,
* due to the three-bit fixed-code block header.
*
* That covers the case where either Z_FIXED is specified, forcing fixed
* codes, or when the use of fixed codes is chosen, because that choice
* results in a smaller compressed block than dynamic codes. That latter
* condition then assures that the above analysis also covers all dynamic
* blocks. A dynamic-code block will only be chosen to be emitted if it has
* fewer bits than a fixed-code block would for the same set of symbols.
* Therefore its average symbol length is assured to be less than 31. So
* the compressed data for a dynamic block also cannot overwrite the
* symbols from which it is being constructed.
*/
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new Uint8Array(s.pending_buf_size);
// It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
//s->sym_buf = s->pending_buf + s->lit_bufsize;
s.sym_buf = s.lit_bufsize;
//s->sym_end = (s->lit_bufsize - 1) * 3;
s.sym_end = (s.lit_bufsize - 1) * 3;
/* We avoid equality with lit_bufsize*3 because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
};
const deflateInit = (strm, level) => {
return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);
};
/* ========================================================================= */
const deflate$2 = (strm, flush) => {
if (deflateStateCheck(strm) || flush > Z_BLOCK$1 || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2;
}
const s = strm.state;
if (!strm.output ||
(strm.avail_in !== 0 && !strm.input) ||
(s.status === FINISH_STATE && flush !== Z_FINISH$3)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2);
}
const old_flush = s.last_flush;
s.last_flush = flush;
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK$3;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH$3) {
return err(strm, Z_BUF_ERROR$1);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR$1);
}
/* Write the header */
if (s.status === INIT_STATE && s.wrap === 0) {
s.status = BUSY_STATE;
}
if (s.status === INIT_STATE) {
/* zlib header */
let header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8;
let level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
/* Compression must start with an empty pending buffer */
flush_pending(strm);
if (s.pending !== 0) {
s.last_flush = -1;
return Z_OK$3;
}
}
//#ifdef GZIP
if (s.status === GZIP_STATE) {
/* gzip header */
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
/* Compression must start with an empty pending buffer */
flush_pending(strm);
if (s.pending !== 0) {
s.last_flush = -1;
return Z_OK$3;
}
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
let beg = s.pending; /* start of bytes to update crc */
let left = (s.gzhead.extra.length & 0xffff) - s.gzindex;
while (s.pending + left > s.pending_buf_size) {
let copy = s.pending_buf_size - s.pending;
// zmemcpy(s.pending_buf + s.pending,
// s.gzhead.extra + s.gzindex, copy);
s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending);
s.pending = s.pending_buf_size;
//--- HCRC_UPDATE(beg) ---//
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
}
//---//
s.gzindex += copy;
flush_pending(strm);
if (s.pending !== 0) {
s.last_flush = -1;
return Z_OK$3;
}
beg = 0;
left -= copy;
}
// JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility
// TypedArray.slice and TypedArray.from don't exist in IE10-IE11
let gzhead_extra = new Uint8Array(s.gzhead.extra);
// zmemcpy(s->pending_buf + s->pending,
// s->gzhead->extra + s->gzindex, left);
s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending);
s.pending += left;
//--- HCRC_UPDATE(beg) ---//
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
}
//---//
s.gzindex = 0;
}
s.status = NAME_STATE;
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
let beg = s.pending; /* start of bytes to update crc */
let val;
do {
if (s.pending === s.pending_buf_size) {
//--- HCRC_UPDATE(beg) ---//
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
}
//---//
flush_pending(strm);
if (s.pending !== 0) {
s.last_flush = -1;
return Z_OK$3;
}
beg = 0;
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
//--- HCRC_UPDATE(beg) ---//
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
}
//---//
s.gzindex = 0;
}
s.status = COMMENT_STATE;
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
let beg = s.pending; /* start of bytes to update crc */
let val;
do {
if (s.pending === s.pending_buf_size) {
//--- HCRC_UPDATE(beg) ---//
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
}
//---//
flush_pending(strm);
if (s.pending !== 0) {
s.last_flush = -1;
return Z_OK$3;
}
beg = 0;
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
//--- HCRC_UPDATE(beg) ---//
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
}
//---//
}
s.status = HCRC_STATE;
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
if (s.pending !== 0) {
s.last_flush = -1;
return Z_OK$3;
}
}
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
}
s.status = BUSY_STATE;
/* Compression must start with an empty pending buffer */
flush_pending(strm);
if (s.pending !== 0) {
s.last_flush = -1;
return Z_OK$3;
}
}
//#endif
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE)) {
let bstate = s.level === 0 ? deflate_stored(s, flush) :
s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush);
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK$3;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
_tr_align(s);
}
else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */
_tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH$1) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK$3;
}
}
}
if (flush !== Z_FINISH$3) { return Z_OK$3; }
if (s.wrap <= 0) { return Z_STREAM_END$3; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3;
};
const deflateEnd = (strm) => {
if (deflateStateCheck(strm)) {
return Z_STREAM_ERROR$2;
}
const status = strm.state.status;
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3;
};
/* =========================================================================
* Initializes the compression dictionary from the given byte
* sequence without producing any compressed output.
*/
const deflateSetDictionary = (strm, dictionary) => {
let dictLength = dictionary.length;
if (deflateStateCheck(strm)) {
return Z_STREAM_ERROR$2;
}
const s = strm.state;
const wrap = s.wrap;
if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
return Z_STREAM_ERROR$2;
}
/* when using zlib wrappers, compute Adler-32 for provided dictionary */
if (wrap === 1) {
/* adler32(strm->adler, dictionary, dictLength); */
strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);
}
s.wrap = 0; /* avoid computing Adler-32 in read_buf */
/* if dictionary would fill window, just replace the history */
if (dictLength >= s.w_size) {
if (wrap === 0) { /* already empty otherwise */
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
/* use the tail */
// dictionary = dictionary.slice(dictLength - s.w_size);
let tmpDict = new Uint8Array(s.w_size);
tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);
dictionary = tmpDict;
dictLength = s.w_size;
}
/* insert dictionary into window and hash */
const avail = strm.avail_in;
const next = strm.next_in;
const input = strm.input;
strm.avail_in = dictLength;
strm.next_in = 0;
strm.input = dictionary;
fill_window(s);
while (s.lookahead >= MIN_MATCH) {
let str = s.strstart;
let n = s.lookahead - (MIN_MATCH - 1);
do {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
} while (--n);
s.strstart = str;
s.lookahead = MIN_MATCH - 1;
fill_window(s);
}
s.strstart += s.lookahead;
s.block_start = s.strstart;
s.insert = s.lookahead;
s.lookahead = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
strm.next_in = next;
strm.input = input;
strm.avail_in = avail;
s.wrap = wrap;
return Z_OK$3;
};
var deflateInit_1 = deflateInit;
var deflateInit2_1 = deflateInit2;
var deflateReset_1 = deflateReset;
var deflateResetKeep_1 = deflateResetKeep;
var deflateSetHeader_1 = deflateSetHeader;
var deflate_2$1 = deflate$2;
var deflateEnd_1 = deflateEnd;
var deflateSetDictionary_1 = deflateSetDictionary;
var deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
module.exports.deflateBound = deflateBound;
module.exports.deflateCopy = deflateCopy;
module.exports.deflateGetDictionary = deflateGetDictionary;
module.exports.deflateParams = deflateParams;
module.exports.deflatePending = deflatePending;
module.exports.deflatePrime = deflatePrime;
module.exports.deflateTune = deflateTune;
*/
var deflate_1$2 = {
deflateInit: deflateInit_1,
deflateInit2: deflateInit2_1,
deflateReset: deflateReset_1,
deflateResetKeep: deflateResetKeep_1,
deflateSetHeader: deflateSetHeader_1,
deflate: deflate_2$1,
deflateEnd: deflateEnd_1,
deflateSetDictionary: deflateSetDictionary_1,
deflateInfo: deflateInfo
};
const _has = (obj, key) => {
return Object.prototype.hasOwnProperty.call(obj, key);
};
var assign = function (obj /*from1, from2, from3, ...*/) {
const sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
const source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (const p in source) {
if (_has(source, p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// Join array of chunks to single array.
var flattenChunks = (chunks) => {
// calculate data length
let len = 0;
for (let i = 0, l = chunks.length; i < l; i++) {
len += chunks[i].length;
}
// join chunks
const result = new Uint8Array(len);
for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {
let chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
};
var common = {
assign: assign,
flattenChunks: flattenChunks
};
// String encode/decode helpers
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safari
//
let STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
const _utf8len = new Uint8Array(256);
for (let q = 0; q < 256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
// convert string to array (typed, when possible)
var string2buf = (str) => {
if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {
return new TextEncoder().encode(str);
}
let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new Uint8Array(buf_len);
// convert
for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper
const buf2binstring = (buf, len) => {
// On Chrome, the arguments in a function call that are allowed is `65534`.
// If the length of the buffer is smaller than that, we can use this optimization,
// otherwise we will take a slower path.
if (len < 65534) {
if (buf.subarray && STR_APPLY_UIA_OK) {
return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));
}
}
let result = '';
for (let i = 0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
};
// convert array to string
var buf2string = (buf, max) => {
const len = max || buf.length;
if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {
return new TextDecoder().decode(buf.subarray(0, max));
}
let i, out;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
const utf16buf = new Array(len * 2);
for (out = 0, i = 0; i < len;) {
let c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
let c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
var utf8border = (buf, max) => {
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
let pos = max - 1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means buffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
var strings = {
string2buf: string2buf,
buf2string: buf2string,
utf8border: utf8border
};
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
var zstream = ZStream;
const toString$1 = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
const {
Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH: Z_FINISH$2,
Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2,
Z_DEFAULT_COMPRESSION,
Z_DEFAULT_STRATEGY,
Z_DEFLATED: Z_DEFLATED$1
} = constants$2;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overridden.
**/
/**
* Deflate.result -> Uint8Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
* - `dictionary`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* const pako = require('pako')
* , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* const deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
function Deflate$1(options) {
this.options = common.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED$1,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY
}, options || {});
let opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
let status = deflate_1$2.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK$2) {
throw new Error(messages[status]);
}
if (opt.header) {
deflate_1$2.deflateSetHeader(this.strm, opt.header);
}
if (opt.dictionary) {
let dict;
// Convert data if needed
if (typeof opt.dictionary === 'string') {
// If we need to compress text, change encoding to utf8.
dict = strings.string2buf(opt.dictionary);
} else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {
dict = new Uint8Array(opt.dictionary);
} else {
dict = opt.dictionary;
}
status = deflate_1$2.deflateSetDictionary(this.strm, dict);
if (status !== Z_OK$2) {
throw new Error(messages[status]);
}
this._dict_set = true;
}
}
/**
* Deflate#push(data[, flush_mode]) -> Boolean
* - data (Uint8Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must
* have `flush_mode` Z_FINISH (or `true`). That will flush internal pending
* buffers and call [[Deflate#onEnd]].
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate$1.prototype.push = function (data, flush_mode) {
const strm = this.strm;
const chunkSize = this.options.chunkSize;
let status, _flush_mode;
if (this.ended) { return false; }
if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;
else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1;
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString$1.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
for (;;) {
if (strm.avail_out === 0) {
strm.output = new Uint8Array(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
// Make sure avail_out > 6 to avoid repeating markers
if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {
this.onData(strm.output.subarray(0, strm.next_out));
strm.avail_out = 0;
continue;
}
status = deflate_1$2.deflate(strm, _flush_mode);
// Ended => flush and finish
if (status === Z_STREAM_END$2) {
if (strm.next_out > 0) {
this.onData(strm.output.subarray(0, strm.next_out));
}
status = deflate_1$2.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK$2;
}
// Flush if out buffer full
if (strm.avail_out === 0) {
this.onData(strm.output);
continue;
}
// Flush if requested and has data
if (_flush_mode > 0 && strm.next_out > 0) {
this.onData(strm.output.subarray(0, strm.next_out));
strm.avail_out = 0;
continue;
}
if (strm.avail_in === 0) break;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array): output data.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate$1.prototype.onData = function (chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH). By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate$1.prototype.onEnd = function (status) {
// On success - join
if (status === Z_OK$2) {
this.result = common.flattenChunks(this.chunks);
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array
* - data (Uint8Array|ArrayBuffer|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate algorithm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
* - dictionary
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
*
* ##### Example:
*
* ```javascript
* const pako = require('pako')
* const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate$1(input, options) {
const deflator = new Deflate$1(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg || messages[deflator.err]; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array
* - data (Uint8Array|ArrayBuffer|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw$1(input, options) {
options = options || {};
options.raw = true;
return deflate$1(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array
* - data (Uint8Array|ArrayBuffer|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip$1(input, options) {
options = options || {};
options.gzip = true;
return deflate$1(input, options);
}
var Deflate_1$1 = Deflate$1;
var deflate_2 = deflate$1;
var deflateRaw_1$1 = deflateRaw$1;
var gzip_1$1 = gzip$1;
var constants$1 = constants$2;
var deflate_1$1 = {
Deflate: Deflate_1$1,
deflate: deflate_2,
deflateRaw: deflateRaw_1$1,
gzip: gzip_1$1,
constants: constants$1
};
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
// See state defs from inflate.js
const BAD$1 = 16209; /* got a data error -- remain here until reset */
const TYPE$1 = 16191; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
var inffast = function inflate_fast(strm, start) {
let _in; /* local strm.input */
let last; /* have enough input while in < last */
let _out; /* local strm.output */
let beg; /* inflate()'s initial strm.output */
let end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
let dmax; /* maximum distance from zlib header */
//#endif
let wsize; /* window size or zero if not using window */
let whave; /* valid bytes in the window */
let wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
let s_window; /* allocated sliding window, if wsize != 0 */
let hold; /* local strm.hold */
let bits; /* local strm.bits */
let lcode; /* local strm.lencode */
let dcode; /* local strm.distcode */
let lmask; /* mask for first level of length codes */
let dmask; /* mask for first level of distance codes */
let here; /* retrieved table entry */
let op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
let len; /* match length, unused bytes */
let dist; /* match distance */
let from; /* where to copy match from */
let from_source;
let input, output; // JS specific, because we have no pointers
/* copy state to local variables */
const state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD$1;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD$1;
break top;
}
// (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD$1;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE$1;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD$1;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
const MAXBITS = 15;
const ENOUGH_LENS$1 = 852;
const ENOUGH_DISTS$1 = 592;
//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
const CODES$1 = 0;
const LENS$1 = 1;
const DISTS$1 = 2;
const lbase = new Uint16Array([ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
]);
const lext = new Uint8Array([ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
]);
const dbase = new Uint16Array([ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
]);
const dext = new Uint8Array([ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
]);
const inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>
{
const bits = opts.bits;
//here = opts.here; /* table entry for duplication */
let len = 0; /* a code's length in bits */
let sym = 0; /* index of code symbols */
let min = 0, max = 0; /* minimum and maximum code lengths */
let root = 0; /* number of index bits for root table */
let curr = 0; /* number of index bits for current table */
let drop = 0; /* code bits to drop for sub-table */
let left = 0; /* number of prefix codes available */
let used = 0; /* code entries in table used */
let huff = 0; /* Huffman code */
let incr; /* for incrementing code, index */
let fill; /* index for replicating entries */
let low; /* low bits for current root entry */
let mask; /* mask for low root bits */
let next; /* next available space in table */
let base = null; /* base value table to use */
// let shoextra; /* extra bits table to use */
let match; /* use base and extra for symbol >= match */
const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
let extra = null;
let here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES$1 || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES$1) {
base = extra = work; /* dummy value--not used */
match = 20;
} else if (type === LENS$1) {
base = lbase;
extra = lext;
match = 257;
} else { /* DISTS */
base = dbase;
extra = dext;
match = 0;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS$1 && used > ENOUGH_LENS$1) ||
(type === DISTS$1 && used > ENOUGH_DISTS$1)) {
return 1;
}
/* process all codes and make table entries */
for (;;) {
/* create table entry */
here_bits = len - drop;
if (work[sym] + 1 < match) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] >= match) {
here_op = extra[work[sym] - match];
here_val = base[work[sym] - match];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS$1 && used > ENOUGH_LENS$1) ||
(type === DISTS$1 && used > ENOUGH_DISTS$1)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
var inftrees = inflate_table;
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
const CODES = 0;
const LENS = 1;
const DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
const {
Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES,
Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR,
Z_DEFLATED
} = constants$2;
/* STATES ====================================================================*/
/* ===========================================================================*/
const HEAD = 16180; /* i: waiting for magic header */
const FLAGS = 16181; /* i: waiting for method and flags (gzip) */
const TIME = 16182; /* i: waiting for modification time (gzip) */
const OS = 16183; /* i: waiting for extra flags and operating system (gzip) */
const EXLEN = 16184; /* i: waiting for extra length (gzip) */
const EXTRA = 16185; /* i: waiting for extra bytes (gzip) */
const NAME = 16186; /* i: waiting for end of file name (gzip) */
const COMMENT = 16187; /* i: waiting for end of comment (gzip) */
const HCRC = 16188; /* i: waiting for header crc (gzip) */
const DICTID = 16189; /* i: waiting for dictionary check value */
const DICT = 16190; /* waiting for inflateSetDictionary() call */
const TYPE = 16191; /* i: waiting for type bits, including last-flag bit */
const TYPEDO = 16192; /* i: same, but skip check to exit inflate on new block */
const STORED = 16193; /* i: waiting for stored size (length and complement) */
const COPY_ = 16194; /* i/o: same as COPY below, but only first time in */
const COPY = 16195; /* i/o: waiting for input or output to copy stored block */
const TABLE = 16196; /* i: waiting for dynamic block table lengths */
const LENLENS = 16197; /* i: waiting for code length code lengths */
const CODELENS = 16198; /* i: waiting for length/lit and distance code lengths */
const LEN_ = 16199; /* i: same as LEN below, but only first time in */
const LEN = 16200; /* i: waiting for length/lit/eob code */
const LENEXT = 16201; /* i: waiting for length extra bits */
const DIST = 16202; /* i: waiting for distance code */
const DISTEXT = 16203; /* i: waiting for distance extra bits */
const MATCH = 16204; /* o: waiting for output space to copy string */
const LIT = 16205; /* o: waiting for output space to write literal */
const CHECK = 16206; /* i: waiting for 32-bit check value */
const LENGTH = 16207; /* i: waiting for 32-bit length (gzip) */
const DONE = 16208; /* finished check, done -- remain here until reset */
const BAD = 16209; /* got a data error -- remain here until reset */
const MEM = 16210; /* got an inflate() memory error -- remain here until reset */
const SYNC = 16211; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
const ENOUGH_LENS = 852;
const ENOUGH_DISTS = 592;
//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
const MAX_WBITS = 15;
/* 32K LZ77 window */
const DEF_WBITS = MAX_WBITS;
const zswap32 = (q) => {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
};
function InflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip,
bit 2 true to validate check value */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib), or
-1 if raw or no header yet */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new Uint16Array(320); /* temporary storage for code lengths */
this.work = new Uint16Array(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new Int32Array(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
const inflateStateCheck = (strm) => {
if (!strm) {
return 1;
}
const state = strm.state;
if (!state || state.strm !== strm ||
state.mode < HEAD || state.mode > SYNC) {
return 1;
}
return 0;
};
const inflateResetKeep = (strm) => {
if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
const state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.flags = -1;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS);
state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK$1;
};
const inflateReset = (strm) => {
if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
const state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
};
const inflateReset2 = (strm, windowBits) => {
let wrap;
/* get the state */
if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
const state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 5;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR$1;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
};
const inflateInit2 = (strm, windowBits) => {
if (!strm) { return Z_STREAM_ERROR$1; }
//strm.msg = Z_NULL; /* in case we return an error */
const state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.strm = strm;
state.window = null/*Z_NULL*/;
state.mode = HEAD; /* to pass state test in inflateReset2() */
const ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK$1) {
strm.state = null/*Z_NULL*/;
}
return ret;
};
const inflateInit = (strm) => {
return inflateInit2(strm, DEF_WBITS);
};
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
let virgin = true;
let lenfix, distfix; // We have no pointers in JS, so keep tables separate
const fixedtables = (state) => {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
lenfix = new Int32Array(512);
distfix = new Int32Array(32);
/* literal/length table */
let sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inftrees(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inftrees(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
};
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
const updatewindow = (strm, src, end, copy) => {
let dist;
const state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new Uint8Array(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
state.window.set(src.subarray(end - state.wsize, end), 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
state.window.set(src.subarray(end - copy, end), 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
};
const inflate$2 = (strm, flush) => {
let state;
let input, output; // input/output buffers
let next; /* next input INDEX */
let put; /* next output INDEX */
let have, left; /* available input and output */
let hold; /* bit buffer */
let bits; /* bits in bit buffer */
let _in, _out; /* save starting available input and output */
let copy; /* number of stored or match bytes to copy */
let from; /* where to copy match bytes from */
let from_source;
let here = 0; /* current decoding table entry */
let here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//let last; /* parent table entry */
let last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
let len; /* length to copy for repeats, bits to drop */
let ret; /* return code */
const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */
let opts;
let n; // temporary variable for NEED_BITS
const order = /* permutation of code lengths */
new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);
if (inflateStateCheck(strm) || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR$1;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK$1;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
if (state.wbits === 0) {
state.wbits = 15;
}
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32_1(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
if (len > 15 || len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
// !!! pako patch. Force use `options.windowBits` if passed.
// Required to always use max window size by default.
state.dmax = 1 << state.wbits;
//state.dmax = 1 << len;
state.flags = 0; /* indicate zlib header */
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if ((state.flags & 0x0200) && (state.wrap & 4)) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32_1(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if ((state.flags & 0x0200) && (state.wrap & 4)) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32_1(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if ((state.flags & 0x0200) && (state.wrap & 4)) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32_1(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if ((state.flags & 0x0200) && (state.wrap & 4)) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32_1(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more convenient processing later
state.head.extra = new Uint8Array(state.head.extra_len);
}
state.head.extra.set(
input.subarray(
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
next + copy
),
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if ((state.flags & 0x0200) && (state.wrap & 4)) {
state.check = crc32_1(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if ((state.flags & 0x0200) && (state.wrap & 4)) {
state.check = crc32_1(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if ((state.flags & 0x0200) && (state.wrap & 4)) {
state.check = crc32_1(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 4) && hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = zswap32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT$1;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
output.set(input.subarray(next, next + copy), put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = { bits: state.lenbits };
ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = { bits: state.lenbits };
ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = { bits: state.distbits };
ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inffast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' instead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if ((state.wrap & 4) && _out) {
strm.adler = state.check =
/*UPDATE_CHECK(state.check, put - _out, _out);*/
(state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
if ((state.wrap & 4) && (state.flags ? hold : zswap32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 4) && hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END$1;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR$1;
break inf_leave;
case MEM:
return Z_MEM_ERROR$1;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR$1;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH$1))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if ((state.wrap & 4) && _out) {
strm.adler = state.check = /*UPDATE_CHECK(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {
ret = Z_BUF_ERROR;
}
return ret;
};
const inflateEnd = (strm) => {
if (inflateStateCheck(strm)) {
return Z_STREAM_ERROR$1;
}
let state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK$1;
};
const inflateGetHeader = (strm, head) => {
/* check state */
if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
const state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK$1;
};
const inflateSetDictionary = (strm, dictionary) => {
const dictLength = dictionary.length;
let state;
let dictid;
let ret;
/* check state */
if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
state = strm.state;
if (state.wrap !== 0 && state.mode !== DICT) {
return Z_STREAM_ERROR$1;
}
/* check for correct dictionary identifier */
if (state.mode === DICT) {
dictid = 1; /* adler32(0, null, 0)*/
/* dictid = adler32(dictid, dictionary, dictLength); */
dictid = adler32_1(dictid, dictionary, dictLength, 0);
if (dictid !== state.check) {
return Z_DATA_ERROR$1;
}
}
/* copy dictionary to window using updatewindow(), which will amend the
existing dictionary if appropriate */
ret = updatewindow(strm, dictionary, dictLength, dictLength);
if (ret) {
state.mode = MEM;
return Z_MEM_ERROR$1;
}
state.havedict = 1;
// Tracev((stderr, "inflate: dictionary set\n"));
return Z_OK$1;
};
var inflateReset_1 = inflateReset;
var inflateReset2_1 = inflateReset2;
var inflateResetKeep_1 = inflateResetKeep;
var inflateInit_1 = inflateInit;
var inflateInit2_1 = inflateInit2;
var inflate_2$1 = inflate$2;
var inflateEnd_1 = inflateEnd;
var inflateGetHeader_1 = inflateGetHeader;
var inflateSetDictionary_1 = inflateSetDictionary;
var inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
module.exports.inflateCodesUsed = inflateCodesUsed;
module.exports.inflateCopy = inflateCopy;
module.exports.inflateGetDictionary = inflateGetDictionary;
module.exports.inflateMark = inflateMark;
module.exports.inflatePrime = inflatePrime;
module.exports.inflateSync = inflateSync;
module.exports.inflateSyncPoint = inflateSyncPoint;
module.exports.inflateUndermine = inflateUndermine;
module.exports.inflateValidate = inflateValidate;
*/
var inflate_1$2 = {
inflateReset: inflateReset_1,
inflateReset2: inflateReset2_1,
inflateResetKeep: inflateResetKeep_1,
inflateInit: inflateInit_1,
inflateInit2: inflateInit2_1,
inflate: inflate_2$1,
inflateEnd: inflateEnd_1,
inflateGetHeader: inflateGetHeader_1,
inflateSetDictionary: inflateSetDictionary_1,
inflateInfo: inflateInfo
};
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
var gzheader = GZheader;
const toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
const {
Z_NO_FLUSH, Z_FINISH,
Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR
} = constants$2;
/* ===========================================================================*/
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overridden.
**/
/**
* Inflate.result -> Uint8Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
* - `dictionary`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* const pako = require('pako')
* const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
* const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* const inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
function Inflate$1(options) {
this.options = common.assign({
chunkSize: 1024 * 64,
windowBits: 15,
to: ''
}, options || {});
const opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
let status = inflate_1$2.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== Z_OK) {
throw new Error(messages[status]);
}
this.header = new gzheader();
inflate_1$2.inflateGetHeader(this.strm, this.header);
// Setup dictionary
if (opt.dictionary) {
// Convert data if needed
if (typeof opt.dictionary === 'string') {
opt.dictionary = strings.string2buf(opt.dictionary);
} else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
opt.dictionary = new Uint8Array(opt.dictionary);
}
if (opt.raw) { //In raw mode we need to set the dictionary early
status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary);
if (status !== Z_OK) {
throw new Error(messages[status]);
}
}
}
}
/**
* Inflate#push(data[, flush_mode]) -> Boolean
* - data (Uint8Array|ArrayBuffer): input data
* - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE
* flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,
* `true` means Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. If end of stream detected,
* [[Inflate#onEnd]] will be called.
*
* `flush_mode` is not needed for normal operation, because end of stream
* detected automatically. You may try to use it for advanced things, but
* this functionality was not tested.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate$1.prototype.push = function (data, flush_mode) {
const strm = this.strm;
const chunkSize = this.options.chunkSize;
const dictionary = this.options.dictionary;
let status, _flush_mode, last_avail_out;
if (this.ended) return false;
if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;
else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;
// Convert data if needed
if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
for (;;) {
if (strm.avail_out === 0) {
strm.output = new Uint8Array(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = inflate_1$2.inflate(strm, _flush_mode);
if (status === Z_NEED_DICT && dictionary) {
status = inflate_1$2.inflateSetDictionary(strm, dictionary);
if (status === Z_OK) {
status = inflate_1$2.inflate(strm, _flush_mode);
} else if (status === Z_DATA_ERROR) {
// Replace code with more verbose
status = Z_NEED_DICT;
}
}
// Skip snyc markers if more data follows and not raw mode
while (strm.avail_in > 0 &&
status === Z_STREAM_END &&
strm.state.wrap > 0 &&
data[strm.next_in] !== 0)
{
inflate_1$2.inflateReset(strm);
status = inflate_1$2.inflate(strm, _flush_mode);
}
switch (status) {
case Z_STREAM_ERROR:
case Z_DATA_ERROR:
case Z_NEED_DICT:
case Z_MEM_ERROR:
this.onEnd(status);
this.ended = true;
return false;
}
// Remember real `avail_out` value, because we may patch out buffer content
// to align utf8 strings boundaries.
last_avail_out = strm.avail_out;
if (strm.next_out) {
if (strm.avail_out === 0 || status === Z_STREAM_END) {
if (this.options.to === 'string') {
let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
let tail = strm.next_out - next_out_utf8;
let utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail & realign counters
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);
this.onData(utf8str);
} else {
this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));
}
}
}
// Must repeat iteration if out buffer is full
if (status === Z_OK && last_avail_out === 0) continue;
// Finalize if end of stream reached.
if (status === Z_STREAM_END) {
status = inflate_1$2.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return true;
}
if (strm.avail_in === 0) break;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|String): output data. When string output requested,
* each chunk will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate$1.prototype.onData = function (chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH). By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate$1.prototype.onEnd = function (status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = common.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|String
* - data (Uint8Array|ArrayBuffer): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* const pako = require('pako');
* const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));
* let output;
*
* try {
* output = pako.inflate(input);
* } catch (err) {
* console.log(err);
* }
* ```
**/
function inflate$1(input, options) {
const inflator = new Inflate$1(options);
inflator.push(input);
// That will never happens, if you don't cheat with options :)
if (inflator.err) throw inflator.msg || messages[inflator.err];
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|String
* - data (Uint8Array|ArrayBuffer): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw$1(input, options) {
options = options || {};
options.raw = true;
return inflate$1(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|String
* - data (Uint8Array|ArrayBuffer): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
var Inflate_1$1 = Inflate$1;
var inflate_2 = inflate$1;
var inflateRaw_1$1 = inflateRaw$1;
var ungzip$1 = inflate$1;
var constants = constants$2;
var inflate_1$1 = {
Inflate: Inflate_1$1,
inflate: inflate_2,
inflateRaw: inflateRaw_1$1,
ungzip: ungzip$1,
constants: constants
};
const { Deflate, deflate, deflateRaw, gzip } = deflate_1$1;
const { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1;
var Deflate_1 = Deflate;
var deflate_1 = deflate;
var deflateRaw_1 = deflateRaw;
var gzip_1 = gzip;
var Inflate_1 = Inflate;
var inflate_1 = inflate;
var inflateRaw_1 = inflateRaw;
var ungzip_1 = ungzip;
var constants_1 = constants$2;
var pako = {
Deflate: Deflate_1,
deflate: deflate_1,
deflateRaw: deflateRaw_1,
gzip: gzip_1,
Inflate: Inflate_1,
inflate: inflate_1,
inflateRaw: inflateRaw_1,
ungzip: ungzip_1,
constants: constants_1
};
/**
* base64.ts
*
* Licensed under the BSD 3-Clause License.
* http://opensource.org/licenses/BSD-3-Clause
*
* References:
* http://en.wikipedia.org/wiki/Base64
*
* @author Dan Kogai (https://github.com/dankogai)
*/
const version = '3.7.7';
/**
* @deprecated use lowercase `version`.
*/
const VERSION = version;
const _hasBuffer = typeof Buffer === 'function';
const _TD = typeof TextDecoder === 'function' ? new TextDecoder() : undefined;
const _TE = typeof TextEncoder === 'function' ? new TextEncoder() : undefined;
const b64ch = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
const b64chs = Array.prototype.slice.call(b64ch);
const b64tab = ((a) => {
let tab = {};
a.forEach((c, i) => tab[c] = i);
return tab;
})(b64chs);
const b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
const _fromCC = String.fromCharCode.bind(String);
const _U8Afrom = typeof Uint8Array.from === 'function'
? Uint8Array.from.bind(Uint8Array)
: (it) => new Uint8Array(Array.prototype.slice.call(it, 0));
const _mkUriSafe = (src) => src
.replace(/=/g, '').replace(/[+\/]/g, (m0) => m0 == '+' ? '-' : '_');
const _tidyB64 = (s) => s.replace(/[^A-Za-z0-9\+\/]/g, '');
/**
* polyfill version of `btoa`
*/
const btoaPolyfill = (bin) => {
// console.log('polyfilled');
let u32, c0, c1, c2, asc = '';
const pad = bin.length % 3;
for (let i = 0; i < bin.length;) {
if ((c0 = bin.charCodeAt(i++)) > 255 ||
(c1 = bin.charCodeAt(i++)) > 255 ||
(c2 = bin.charCodeAt(i++)) > 255)
throw new TypeError('invalid character found');
u32 = (c0 << 16) | (c1 << 8) | c2;
asc += b64chs[u32 >> 18 & 63]
+ b64chs[u32 >> 12 & 63]
+ b64chs[u32 >> 6 & 63]
+ b64chs[u32 & 63];
}
return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
};
/**
* does what `window.btoa` of web browsers do.
* @param {String} bin binary string
* @returns {string} Base64-encoded string
*/
const _btoa = typeof btoa === 'function' ? (bin) => btoa(bin)
: _hasBuffer ? (bin) => Buffer.from(bin, 'binary').toString('base64')
: btoaPolyfill;
const _fromUint8Array = _hasBuffer
? (u8a) => Buffer.from(u8a).toString('base64')
: (u8a) => {
// cf. https://stackoverflow.com/questions/12710001/how-to-convert-uint8-array-to-base64-encoded-string/12713326#12713326
const maxargs = 0x1000;
let strs = [];
for (let i = 0, l = u8a.length; i < l; i += maxargs) {
strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
}
return _btoa(strs.join(''));
};
/**
* converts a Uint8Array to a Base64 string.
* @param {boolean} [urlsafe] URL-and-filename-safe a la RFC4648 §5
* @returns {string} Base64 string
*/
const fromUint8Array = (u8a, urlsafe = false) => urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a);
// This trick is found broken https://github.com/dankogai/js-base64/issues/130
// const utob = (src: string) => unescape(encodeURIComponent(src));
// reverting good old fationed regexp
const cb_utob = (c) => {
if (c.length < 2) {
var cc = c.charCodeAt(0);
return cc < 0x80 ? c
: cc < 0x800 ? (_fromCC(0xc0 | (cc >>> 6))
+ _fromCC(0x80 | (cc & 0x3f)))
: (_fromCC(0xe0 | ((cc >>> 12) & 0x0f))
+ _fromCC(0x80 | ((cc >>> 6) & 0x3f))
+ _fromCC(0x80 | (cc & 0x3f)));
}
else {
var cc = 0x10000
+ (c.charCodeAt(0) - 0xD800) * 0x400
+ (c.charCodeAt(1) - 0xDC00);
return (_fromCC(0xf0 | ((cc >>> 18) & 0x07))
+ _fromCC(0x80 | ((cc >>> 12) & 0x3f))
+ _fromCC(0x80 | ((cc >>> 6) & 0x3f))
+ _fromCC(0x80 | (cc & 0x3f)));
}
};
const re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
/**
* @deprecated should have been internal use only.
* @param {string} src UTF-8 string
* @returns {string} UTF-16 string
*/
const utob = (u) => u.replace(re_utob, cb_utob);
//
const _encode = _hasBuffer
? (s) => Buffer.from(s, 'utf8').toString('base64')
: _TE
? (s) => _fromUint8Array(_TE.encode(s))
: (s) => _btoa(utob(s));
/**
* converts a UTF-8-encoded string to a Base64 string.
* @param {boolean} [urlsafe] if `true` make the result URL-safe
* @returns {string} Base64 string
*/
const encode = (src, urlsafe = false) => urlsafe
? _mkUriSafe(_encode(src))
: _encode(src);
/**
* converts a UTF-8-encoded string to URL-safe Base64 RFC4648 §5.
* @returns {string} Base64 string
*/
const encodeURI = (src) => encode(src, true);
// This trick is found broken https://github.com/dankogai/js-base64/issues/130
// const btou = (src: string) => decodeURIComponent(escape(src));
// reverting good old fationed regexp
const re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;
const cb_btou = (cccc) => {
switch (cccc.length) {
case 4:
var cp = ((0x07 & cccc.charCodeAt(0)) << 18)
| ((0x3f & cccc.charCodeAt(1)) << 12)
| ((0x3f & cccc.charCodeAt(2)) << 6)
| (0x3f & cccc.charCodeAt(3)), offset = cp - 0x10000;
return (_fromCC((offset >>> 10) + 0xD800)
+ _fromCC((offset & 0x3FF) + 0xDC00));
case 3:
return _fromCC(((0x0f & cccc.charCodeAt(0)) << 12)
| ((0x3f & cccc.charCodeAt(1)) << 6)
| (0x3f & cccc.charCodeAt(2)));
default:
return _fromCC(((0x1f & cccc.charCodeAt(0)) << 6)
| (0x3f & cccc.charCodeAt(1)));
}
};
/**
* @deprecated should have been internal use only.
* @param {string} src UTF-16 string
* @returns {string} UTF-8 string
*/
const btou = (b) => b.replace(re_btou, cb_btou);
/**
* polyfill version of `atob`
*/
const atobPolyfill = (asc) => {
// console.log('polyfilled');
asc = asc.replace(/\s+/g, '');
if (!b64re.test(asc))
throw new TypeError('malformed base64.');
asc += '=='.slice(2 - (asc.length & 3));
let u24, bin = '', r1, r2;
for (let i = 0; i < asc.length;) {
u24 = b64tab[asc.charAt(i++)] << 18
| b64tab[asc.charAt(i++)] << 12
| (r1 = b64tab[asc.charAt(i++)]) << 6
| (r2 = b64tab[asc.charAt(i++)]);
bin += r1 === 64 ? _fromCC(u24 >> 16 & 255)
: r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255)
: _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255);
}
return bin;
};
/**
* does what `window.atob` of web browsers do.
* @param {String} asc Base64-encoded string
* @returns {string} binary string
*/
const _atob = typeof atob === 'function' ? (asc) => atob(_tidyB64(asc))
: _hasBuffer ? (asc) => Buffer.from(asc, 'base64').toString('binary')
: atobPolyfill;
//
const _toUint8Array = _hasBuffer
? (a) => _U8Afrom(Buffer.from(a, 'base64'))
: (a) => _U8Afrom(_atob(a).split('').map(c => c.charCodeAt(0)));
/**
* converts a Base64 string to a Uint8Array.
*/
const toUint8Array = (a) => _toUint8Array(_unURI(a));
//
const _decode = _hasBuffer
? (a) => Buffer.from(a, 'base64').toString('utf8')
: _TD
? (a) => _TD.decode(_toUint8Array(a))
: (a) => btou(_atob(a));
const _unURI = (a) => _tidyB64(a.replace(/[-_]/g, (m0) => m0 == '-' ? '+' : '/'));
/**
* converts a Base64 string to a UTF-8 string.
* @param {String} src Base64 string. Both normal and URL-safe are supported
* @returns {string} UTF-8 string
*/
const decode = (src) => _decode(_unURI(src));
/**
* check if a value is a valid Base64 string
* @param {String} src a value to check
*/
const isValid = (src) => {
if (typeof src !== 'string')
return false;
const s = src.replace(/\s+/g, '').replace(/={0,2}$/, '');
return !/[^\s0-9a-zA-Z\+/]/.test(s) || !/[^\s0-9a-zA-Z\-_]/.test(s);
};
//
const _noEnum = (v) => {
return {
value: v, enumerable: false, writable: true, configurable: true
};
};
/**
* extend String.prototype with relevant methods
*/
const extendString = function () {
const _add = (name, body) => Object.defineProperty(String.prototype, name, _noEnum(body));
_add('fromBase64', function () { return decode(this); });
_add('toBase64', function (urlsafe) { return encode(this, urlsafe); });
_add('toBase64URI', function () { return encode(this, true); });
_add('toBase64URL', function () { return encode(this, true); });
_add('toUint8Array', function () { return toUint8Array(this); });
};
/**
* extend Uint8Array.prototype with relevant methods
*/
const extendUint8Array = function () {
const _add = (name, body) => Object.defineProperty(Uint8Array.prototype, name, _noEnum(body));
_add('toBase64', function (urlsafe) { return fromUint8Array(this, urlsafe); });
_add('toBase64URI', function () { return fromUint8Array(this, true); });
_add('toBase64URL', function () { return fromUint8Array(this, true); });
};
/**
* extend Builtin prototypes with relevant methods
*/
const extendBuiltins = () => {
extendString();
extendUint8Array();
};
const gBase64 = {
version: version,
VERSION: VERSION,
atob: _atob,
atobPolyfill: atobPolyfill,
btoa: _btoa,
btoaPolyfill: btoaPolyfill,
fromBase64: decode,
toBase64: encode,
encode: encode,
encodeURI: encodeURI,
encodeURL: encodeURI,
utob: utob,
btou: btou,
decode: decode,
isValid: isValid,
fromUint8Array: fromUint8Array,
toUint8Array: toUint8Array,
extendString: extendString,
extendUint8Array: extendUint8Array,
extendBuiltins: extendBuiltins
};
var MAXSCOPETIME = 5e3;
var MAXSCOPELENGTH = 3;
var recordScreen;
var RecordScreen = /** @class */
function () {
function RecordScreen2() {
this.eventList = [{
scope: "".concat(getTimestamp(), "-"),
eventList: []
}];
this.init();
}
RecordScreen2.prototype.init = function () {
var _this = this;
this.closeCallback = record({
emit: function (event, isCheckout) {
var lastEvents = _this.eventList[_this.eventList.length - 1];
lastEvents.eventList.push(event);
if (isCheckout) {
if (_this.eventList.length > 0) {
_this.eventList[_this.eventList.length - 1].scope = lastEvents.scope + getTimestamp();
}
if (_this.eventList.length > MAXSCOPELENGTH) {
_this.eventList.shift();
}
_this.eventList.push({
scope: "".concat(getTimestamp(), "-"),
eventList: []
});
}
},
recordCanvas: true,
checkoutEveryNms: MAXSCOPETIME
// 每5s重新制作快照
});
};
RecordScreen2.prototype.close = function () {
var _a;
(_a = this.closeCallback) === null || _a === void 0 ? void 0 : _a.call(this);
this.closeCallback = void 0;
};
return RecordScreen2;
}();
function initRecordScreen() {
watch(exports.options, function (newValue, oldValue) {
if (newValue.recordScreen === oldValue.recordScreen) return;
if (newValue.recordScreen) recordScreen = new RecordScreen();else {
recordScreen === null || recordScreen === void 0 ? void 0 : recordScreen.close();
recordScreen = void 0;
}
});
recordScreen = exports.options.value.recordScreen ? new RecordScreen() : void 0;
}
function getEventList() {
var _a;
return (_a = recordScreen === null || recordScreen === void 0 ? void 0 : recordScreen.eventList) !== null && _a !== void 0 ? _a : [];
}
function zip(data) {
if (!data) return data;
var dataJson = typeof data !== "string" && typeof data !== "number" ? JSON.stringify(data) : data;
var str = gBase64.encode(dataJson);
var binaryString = pako.gzip(str);
var arr = Array.from(binaryString);
var s = "";
arr.forEach(function (item) {
s += String.fromCharCode(item);
});
return gBase64.btoa(s);
}
function unzip(b64Data) {
var strData = gBase64.atob(b64Data);
var charData = strData.split("").map(function (x) {
return x.charCodeAt(0);
});
var binData = new Uint8Array(charData);
var data = pako.ungzip(binData);
var str = "";
var chunk = 8 * 1024;
var i;
for (i = 0; i < data.length / chunk; i++) {
str += String.fromCharCode.apply(null, data.slice(i * chunk, (i + 1) * chunk));
}
str += String.fromCharCode.apply(null, data.slice(i * chunk));
var unzipStr = gBase64.decode(str);
var result = "";
try {
result = JSON.parse(unzipStr);
} catch (error) {
if (/Unexpected token o in JSON at position 0/.test(error)) {
result = unzipStr;
}
}
return result;
}
var SETTIMEA = 2e3;
var SETTIMEB = 2e4;
var MAXLENGTHA = 5;
var GROUPARRAYKEY = ["errMessage", "eventId", "requestUrl"];
var BatchError = /** @class */
function () {
function BatchError2() {
this.cacheErrorA = [];
this.cacheErrorB = [];
this.throttleProxyAddCacheErrorA = debounce(this.proxyAddCacheErrorA, SETTIMEA);
this.throttleProxyAddCacheErrorB = throttle$1(this.proxyAddCacheErrorB, SETTIMEB);
}
BatchError2.prototype.proxyAddCacheErrorA = function () {
var _a;
var len = this.cacheErrorA.length;
if (!len) return;
var arr = groupArray.apply(void 0, __spreadArray([this.cacheErrorA], GROUPARRAYKEY, false));
var arrA = arr.filter(function (item) {
return item.length < MAXLENGTHA;
});
var arrB = arr.filter(function (item) {
return item.length >= MAXLENGTHA;
});
if (arrA.length) {
sendData.emit(arrA.flat(Infinity));
}
if (arrB.length) {
var arrBsum_1 = [];
arrB.forEach(function (item) {
var sumItem = item[0];
sumItem.batchError = true;
sumItem.batchErrorLength = item.length;
sumItem.batchErrorLastHappenTime = item[item.length - 1].triggerTime;
arrBsum_1.push(sumItem);
});
(_a = this.cacheErrorB).push.apply(_a, arrBsum_1);
this.throttleProxyAddCacheErrorB();
}
while (len--) {
this.cacheErrorA.shift();
}
};
BatchError2.prototype.proxyAddCacheErrorB = function () {
var len = this.cacheErrorB.length;
if (!len) return;
var arr = groupArray.apply(void 0, __spreadArray([this.cacheErrorB], GROUPARRAYKEY, false));
while (len--) {
this.cacheErrorB.shift();
}
var emitList = [];
arr.forEach(function (itemList) {
var sumItem = itemList[0];
if (itemList.length > 1) {
sumItem.batchErrorLength = itemList.reduce(function (p, item) {
return p += item.batchErrorLength;
}, 0);
sumItem.batchErrorLastHappenTime = itemList[itemList.length - 1].triggerTime;
}
emitList.push(sumItem);
});
sendData.emit(emitList);
};
BatchError2.prototype.sendAllCacheError = function () {
var errInfoList = this.cacheErrorA.concat(this.cacheErrorB);
var arr = groupArray.apply(void 0, __spreadArray([errInfoList], GROUPARRAYKEY, false));
var arrA = arr.filter(function (item) {
return item.length < MAXLENGTHA;
});
var arrB = arr.filter(function (item) {
return item.length >= MAXLENGTHA;
});
if (arrA.length) {
sendData.emit(arrA.flat(Infinity), true);
}
if (arrB.length) {
var arrBsum_2 = [];
arrB.forEach(function (item) {
var sumItem = item[0];
sumItem.batchError = true;
sumItem.batchErrorLength = item.length;
sumItem.batchErrorLastHappenTime = item[item.length - 1].triggerTime;
arrBsum_2.push(sumItem);
});
sendData.emit(arrBsum_2, true);
}
};
BatchError2.prototype.pushCacheErrorA = function (errorInfo) {
this.cacheErrorA.push(errorInfo);
this.throttleProxyAddCacheErrorA();
if (this.cacheErrorA.length >= 50) {
this.proxyAddCacheErrorA();
this.proxyAddCacheErrorB();
}
};
return BatchError2;
}();
var batchError;
function initBatchError() {
batchError = new BatchError();
}
function serializeConsoleArgs(args) {
var serializedArgs = args.map(function (arg) {
if (arg === null) return "null";
if (arg === void 0) return "undefined";
if (typeof arg === "string") return arg;
if (typeof arg === "number" || typeof arg === "boolean") return String(arg);
if (typeof arg === "function") return "[Function: ".concat(arg.name || "anonymous", "]");
if (arg instanceof Error) {
return "".concat(arg.name, ": ").concat(arg.message).concat(arg.stack ? "\n" + arg.stack : "");
}
if (typeof arg === "object") {
try {
return JSON.stringify(arg, null, 2);
} catch (error) {
return arg.toString();
}
}
return String(arg);
});
return serializedArgs.join(" | ");
}
function parseStack(err) {
var _a = err.stack,
stack = _a === void 0 ? "" : _a,
_b = err.message,
message = _b === void 0 ? "" : _b;
var result = {
eventId: exports.SENDID.CODE,
errMessage: message,
errStack: stack
};
if (stack) {
var rChromeCallStack_1 = /^\s*at\s*([^(]+)\s*\((.+?):(\d+):(\d+)\)$/;
var rMozlliaCallStack_1 = /^\s*([^@]*)@(.+?):(\d+):(\d+)$/;
var callStackStr = stack.replace(new RegExp("^[\\w\\s:]*".concat(message, "\n")), "");
var callStackFrameList = map(filter(callStackStr.split("\n"), function (item2) {
return item2;
}), function (str) {
var chromeErrResult = str.match(rChromeCallStack_1);
if (chromeErrResult) {
return {
triggerPageUrl: chromeErrResult[2],
line: chromeErrResult[3],
// 错误发生位置的行数
col: chromeErrResult[4]
// 错误发生位置的列数
};
}
var mozlliaErrResult = str.match(rMozlliaCallStack_1);
if (mozlliaErrResult) {
return {
triggerPageUrl: mozlliaErrResult[2],
line: mozlliaErrResult[3],
col: mozlliaErrResult[4]
};
}
return {};
});
var item = callStackFrameList[0] || {};
return __assign(__assign({}, result), item);
}
return result;
}
function parseError(e) {
if (e instanceof Error) {
var _a = e,
message = _a.message,
stack = _a.stack,
lineNumber = _a.lineNumber,
fileName = _a.fileName,
columnNumber = _a.columnNumber;
if (fileName) {
return {
errMessage: message,
errStack: stack,
eventId: exports.SENDID.CODE,
line: lineNumber,
// 不稳定属性 - 在某些浏览器可能是undefined,被废弃了
col: columnNumber,
// 不稳定属性 - 非标准,有些浏览器可能不支持
triggerPageUrl: fileName
// 不稳定属性 - 非标准,有些浏览器可能不支持
};
}
return parseStack(e);
}
if (e.message) return parseStack(e);
if (typeof e === "string") return {
eventId: exports.SENDID.REJECT,
errMessage: e
};
if (isArray(e)) {
return {
eventId: exports.SENDID.CONSOLEERROR,
errMessage: serializeConsoleArgs(e)
};
}
return {};
}
function isPromiseRejectedResult(event) {
return event.reason !== void 0;
}
function parseErrorEvent(event) {
if (isPromiseRejectedResult(event)) {
return __assign({
eventId: exports.SENDID.CODE
}, parseError(event.reason));
}
var target = event.target;
if (target instanceof HTMLElement) {
if (target.nodeType === 1) {
var result = {
initiatorType: target.nodeName.toLowerCase(),
eventId: exports.SENDID.RESOURCE,
requestUrl: ""
};
switch (target.nodeName.toLowerCase()) {
case "link":
result.requestUrl = target.href;
break;
default:
result.requestUrl = target.currentSrc || target.src;
}
return result;
}
}
if (event.error) {
var e = event.error;
e.fileName = e.filename || event.filename;
e.columnNumber = e.colno || event.colno;
e.lineNumber = e.lineno || event.lineno;
return __assign({
eventId: exports.SENDID.CODE
}, parseError(e));
}
return {
eventId: exports.SENDID.CODE,
line: _global.event.errorLine,
col: _global.event.errorCharacter,
errMessage: _global.event.errorMessage,
triggerPageUrl: _global.event.errorUrl
};
}
function isIgnoreErrors(error) {
if (!exports.options.value.ignoreErrors.length) return false;
var errMessage = error.errMessage || error.message;
if (!errMessage) return false;
errMessage = String(errMessage);
return exports.options.value.ignoreErrors.some(function (item) {
if (isRegExp$1(item)) {
if (item.test(errMessage)) {
debug("ignoreErrors\u62E6\u622A\u6210\u529F - \u622A\u6761\u4EF6:".concat(item, " \u9519\u8BEF\u4FE1\u606F:").concat(errMessage));
return true;
} else {
return false;
}
} else {
if (errMessage === item) {
debug("ignoreErrors\u62E6\u622A\u6210\u529F - \u622A\u6761\u4EF6:".concat(item, " \u9519\u8BEF\u4FE1\u606F:").concat(errMessage));
return true;
} else {
return false;
}
}
});
}
function getRecordEvent() {
var _recordscreenList = JSON.parse(JSON.stringify(getEventList()));
return _recordscreenList.slice(-2).map(function (item) {
return item.eventList;
}).flat();
}
function emit(errorInfo, flush) {
if (flush === void 0) {
flush = false;
}
var info = __assign(__assign({}, errorInfo), {
eventType: SEDNEVENTTYPES.ERROR,
recordscreen: exports.options.value.recordScreen ? zip(getRecordEvent()) : null,
triggerPageUrl: getLocationHref(),
triggerTime: getTimestamp()
});
exports.options.value.scopeError ? batchError.pushCacheErrorA(info) : sendData.emit(info, flush);
}
function initError() {
if (!exports.options.value.error.core) return;
if (exports.options.value.scopeError) {
initBatchError();
eventBus.addEvent({
type: EVENTTYPES.BEFOREUNLOAD,
callback: function () {
batchError.sendAllCacheError();
}
});
}
eventBus.addEvent({
type: EVENTTYPES.ERROR,
callback: function (e) {
var errorInfo = parseErrorEvent(e);
if (isIgnoreErrors(errorInfo)) return;
emit(errorInfo);
}
});
eventBus.addEvent({
type: EVENTTYPES.UNHANDLEDREJECTION,
callback: function (e) {
var errorInfo = parseErrorEvent(e);
if (isIgnoreErrors(errorInfo)) return;
emit(errorInfo);
}
});
eventBus.addEvent({
type: EVENTTYPES.CONSOLEERROR,
callback: function (e) {
var errorInfo = parseError(e);
if (isIgnoreErrors(errorInfo)) return;
emit(__assign({
eventId: exports.SENDID.CODE
}, errorInfo));
}
});
}
function handleSendError(options2, flush) {
if (options2 === void 0) {
options2 = {};
}
if (flush === void 0) {
flush = false;
}
emit(options2, flush);
}
function getElByAttr(list, key) {
return list.find(function (item) {
return item.hasAttribute && item.hasAttribute(key);
});
}
function isSimpleEl(children) {
if (children.length > 0) {
var arr_1 = ["em", "b", "strong", "span", "img", "i", "code"];
var a = children.filter(function (_a) {
var tagName = _a.tagName;
return arr_1.indexOf(tagName.toLowerCase()) >= 0;
});
return a.length === children.length;
}
return true;
}
function getNodeXPath(node, curPath) {
if (curPath === void 0) {
curPath = "";
}
if (!node) return curPath;
var parent = node.parentElement;
var id = node.id;
var tagName = node.tagName.toLowerCase();
var path = curPath ? ">".concat(curPath) : "";
if (!parent || parent === document.documentElement || parent === document.body) {
return "".concat(tagName).concat(path);
}
if (id) {
return "#".concat(id).concat(path);
}
return getNodeXPath(parent, "".concat(tagName).concat(path));
}
var RequestTemplateClick = /** @class */
function () {
function RequestTemplateClick2(config) {
if (config === void 0) {
config = {};
}
var _this = this;
this.eventId = "";
this.eventType = "";
this.title = "";
this.triggerPageUrl = "";
this.x = -1;
this.y = -1;
this.params = {};
this.elementPath = "";
this.triggerTime = -1;
Object.keys(config).forEach(function (key) {
if (isValidKey(key, config)) {
_this[key] = config[key] || null;
}
});
}
return RequestTemplateClick2;
}();
function clickCollection() {
eventBus.addEvent({
type: EVENTTYPES.CLICK,
callback: function (e) {
var _config = new RequestTemplateClick({
eventType: SEDNEVENTTYPES.CLICK
});
var path = e.composedPath() ? e.composedPath() : e.target ? getNodePath(e.target) : [];
var target = path.find(function (el) {
return el.hasAttribute && (el.hasAttribute("data-warden-container") || el.hasAttribute("data-warden-event-id") || el.hasAttribute("data-warden-title"));
});
if (!target) return;
var _a = document.documentElement,
scrollTop = _a.scrollTop,
scrollLeft = _a.scrollLeft;
var _b = e.target.getBoundingClientRect(),
top = _b.top,
left = _b.left;
_config.x = left + scrollLeft;
_config.y = top + scrollTop;
_config.triggerTime = getTimestamp();
_config.triggerPageUrl = getLocationHref();
_config.title = extractTitleByTarget(target);
_config.eventId = extractDataByPath(path);
_config.params = extractParamsByPath(path);
_config.elementPath = getNodeXPath(target).slice(-128);
sendData.emit(_config);
}
});
}
function getNodePath(node, options2) {
if (options2 === void 0) {
options2 = {
includeSelf: true,
order: "asc"
};
}
if (!node) return [];
var includeSelf = options2.includeSelf,
order = options2.order;
var parent = includeSelf ? node : node.parentElement;
var result = [];
while (parent) {
result = order === "asc" ? result.concat(parent) : [parent].concat(result);
parent = parent.parentElement;
}
return result;
}
function extractTitleByTarget(target) {
var selfTitle = getNodeTitle(target);
if (selfTitle) return selfTitle;
var container = target.parentElement;
while (container && container !== document.body) {
if (container.hasAttribute("data-warden-container")) break;
container = container.parentElement;
}
var superTitle = getNodeTitle(container);
if (superTitle) return superTitle;
var tagName = target.tagName;
return !target.hasChildNodes() || tagName.toLowerCase() === "svg" ? handleLeafNode(target) : handleNoLeafNode(target);
}
function getNodeTitle(node) {
if (node) {
return node.hasAttribute("data-warden-title") ? node.getAttribute("data-warden-title") : node.title;
}
return "";
}
function handleLeafNode(target) {
var tagName = target.tagName,
textContent = target.textContent;
if (tagName === "IMG") return target.getAttribute("alt") || null;
if (tagName === "svg") {
var a = __spreadArray([], Array(target.children), true).find(function (item) {
return item.tagName === "use";
});
if (a) return a.getAttribute("xlink:href") || null;
}
return textContent;
}
function handleNoLeafNode(target) {
var tagName = target.tagName,
textContent = target.textContent;
if (tagName === "A") {
var res = isSimpleEl(__spreadArray([], Array.from(target.children), true));
return res ? textContent : target.getAttribute("href") || null;
}
if (tagName === "BUTTON") {
var name_1 = target.getAttribute("name");
var res = isSimpleEl(__spreadArray([], Array.from(target.children), true));
return name_1 || res ? textContent : target.getAttribute("href") || null;
}
var length = __spreadArray([], Array.from(target.children), true).filter(function () {
return target.hasChildNodes();
}).length;
return length > 0 ? null : textContent;
}
function extractDataByPath(list) {
if (list === void 0) {
list = [];
}
var hasIdEl = getElByAttr(list, "data-warden-event-id");
if (hasIdEl) return hasIdEl.getAttribute("data-warden-event-id");
var hasTitleEl = getElByAttr(list, "title");
if (hasTitleEl) return hasTitleEl.getAttribute("title");
var container = getElByAttr(list, "data-warden-container");
if (container) {
if (container.getAttribute("data-warden-event-id")) {
return container.getAttribute("data-warden-event-id");
}
if (container.getAttribute("title")) {
return container.getAttribute("title");
}
var id2 = container.getAttribute("data-warden-container");
if (typeof id2 === "string" && id2) return id2;
}
return list[0].tagName.toLowerCase();
}
function extractParamsByPath(list) {
if (list === void 0) {
list = [];
}
var regex = /^data-warden-/;
var target;
var targetIndex = -1;
for (var index = 0; index < list.length; index++) {
var el = list[index];
var attributes = el && el.attributes && Array.from(el.attributes) || [];
target = attributes.find(function (item) {
return item.nodeName.match(regex) ? item.nodeName.match(regex) : item.nodeName.indexOf("data-warden-container") !== -1;
});
if (target) {
targetIndex = index;
break;
}
}
if (targetIndex < 0) return {};
var container = list[targetIndex];
var attrList = Array.from(container.attributes) || [];
var params = {};
var defaultKey = ["container", "title", "event-id"];
attrList.forEach(function (item) {
if (item.nodeName.indexOf("data-warden") < 0) return;
var key = item.nodeName.replace(regex, "");
if (defaultKey.includes(key)) return;
params[key] = item.nodeValue;
});
return params;
}
function initEvent() {
exports.options.value.event.core && clickCollection();
}
function handleSendEvent(options2, flush) {
if (options2 === void 0) {
options2 = {};
}
if (flush === void 0) {
flush = false;
}
sendData.emit(__assign(__assign({}, options2), {
eventType: SEDNEVENTTYPES.CUSTOM,
triggerTime: getTimestamp(),
triggerPageUrl: getLocationHref()
}), flush);
}
var supported = {
performance: !!_global.performance,
getEntriesByType: !!(_global.performance && _global.performance.getEntriesByType),
PerformanceObserver: "PerformanceObserver" in _global,
MutationObserver: "MutationObserver" in _global,
PerformanceNavigationTiming: "PerformanceNavigationTiming" in _global
};
var performanceEntryAttrs = {
initiatorType: "",
transferSize: 0,
encodedBodySize: 0,
decodedBodySize: 0,
duration: 0,
redirectStart: 0,
redirectEnd: 0,
startTime: 0,
fetchStart: 0,
domainLookupStart: 0,
domainLookupEnd: 0,
connectStart: 0,
connectEnd: 0,
requestStart: 0,
responseStart: 0,
responseEnd: 0,
workerStart: 0
};
function traceResourcePerformance(performance) {
var observerTypeList = ["img", "script", "link", "audio", "video", "css"];
var entries = performance.getEntriesByType("resource");
var records = [];
entries.forEach(function (entry) {
var _a = entry.initiatorType,
initiatorType = _a === void 0 ? "" : _a;
if (observerTypeList.indexOf(initiatorType.toLowerCase()) < 0) return;
if (sendReaconImageList.length) {
var index = sendReaconImageList.findIndex(function (item) {
return item.src === entry.name;
});
if (index !== -1) {
sendReaconImageList.splice(index, 1);
return;
}
}
var value = {};
Object.keys(performanceEntryAttrs).forEach(function (attr) {
if (isValidKey(attr, entry)) {
value[attr] = entry[attr];
}
});
records.push(normalizeObj(__assign(__assign({}, value), {
eventType: SEDNEVENTTYPES.PERFORMANCE,
eventId: exports.SENDID.RESOURCE,
requestUrl: entry.name,
triggerTime: getTimestamp(),
triggerPageUrl: getLocationHref()
})));
});
if (records.length) sendData.emit(records);
return records;
}
function observeSourceInsert() {
var tags = ["img", "script", "link"];
var observer = new MutationObserver(function (mutationsList) {
var _loop_1 = function (i2) {
var startTime = getTimestamp();
var _a = mutationsList[i2].addedNodes,
addedNodes = _a === void 0 ? [] : _a;
addedNodes.forEach(function (node) {
var nodeName = node.nodeName;
if (tags.indexOf(nodeName.toLowerCase()) !== -1) {
on$1(node, EVENTTYPES.LOAD, function () {
sendData.emit(normalizeObj({
eventType: SEDNEVENTTYPES.PERFORMANCE,
eventId: exports.SENDID.RESOURCE,
requestUrl: node.src || node.href,
duration: getTimestamp() - startTime,
triggerTime: getTimestamp(),
triggerPageUrl: getLocationHref()
}));
});
on$1(node, EVENTTYPES.ERROR, function () {
sendData.emit(normalizeObj({
eventType: SEDNEVENTTYPES.PERFORMANCE,
eventId: exports.SENDID.RESOURCE,
requestUrl: node.src || node.href,
responseStatus: "error",
duration: getTimestamp() - startTime,
triggerTime: getTimestamp(),
triggerPageUrl: getLocationHref()
}));
});
}
});
};
for (var i = 0; i < mutationsList.length; i += 1) {
_loop_1(i);
}
});
observer.observe(_global.document, {
subtree: true,
// 目标以及目标的后代改变都会观察
childList: true
// 表示观察目标子节点的变化,比如添加或者删除目标子节点,不包括修改子节点以及子节点后代的变化
// attributes: true, // 观察属性变动
// attributeFilter: ['src', 'href'] // 要观察的属性
});
}
function observeNavigationTiming() {
var times = {};
var performance = _global.performance;
var t = performance.timing;
times.fmp = 0;
if (supported.getEntriesByType) {
var paintEntries = performance.getEntriesByType("paint");
if (paintEntries.length) {
times.fmp = paintEntries[paintEntries.length - 1].startTime;
}
if (supported.PerformanceNavigationTiming) {
var nt2Timing = performance.getEntriesByType("navigation")[0];
if (nt2Timing) t = nt2Timing;
}
}
if (times.fmp && supported.PerformanceNavigationTiming) {
times.fmp -= t.fetchStart;
}
times.tti = t.domInteractive - t.fetchStart;
times.ready = t.domContentLoadedEventEnd - t.fetchStart;
times.loadon = t.loadEventStart - t.fetchStart;
times.firstbyte = t.responseStart - t.domainLookupStart;
times.dns = t.domainLookupEnd - t.domainLookupStart;
times.appcache = t.domainLookupStart - t.fetchStart;
times.tcp = t.connectEnd - t.connectStart;
times.ttfb = t.responseStart - t.requestStart;
times.trans = t.responseEnd - t.responseStart;
times.dom = t.domInteractive - t.responseEnd;
times.res = t.loadEventStart - t.domContentLoadedEventEnd;
times.ssllink = t.connectEnd - t.secureConnectionStart;
times.redirect = t.redirectEnd - t.redirectStart;
times.unloadTime = t.unloadEventEnd - t.unloadEventStart;
var resultInfo = __assign(__assign({}, times), {
triggerPageUrl: getLocationHref()
});
_support.firstScreen = __assign({}, resultInfo);
sendData.emit(normalizeObj(__assign(__assign({}, resultInfo), {
eventType: SEDNEVENTTYPES.PERFORMANCE,
eventId: exports.SENDID.PAGE
})));
}
function observeResource() {
if (supported.performance && exports.options.value.performance.firstResource) {
observeNavigationTiming();
}
if (supported.performance && exports.options.value.performance.core) {
traceResourcePerformance(_global.performance);
if (supported.PerformanceObserver) {
var observer = new PerformanceObserver(traceResourcePerformance);
observer.observe({
entryTypes: ["resource"]
});
} else if (supported.MutationObserver) {
observeSourceInsert();
}
}
}
function initPerformance() {
if (!exports.options.value.performance.firstResource && !exports.options.value.performance.core) return;
if (document.readyState === "complete") {
observeResource();
} else {
eventBus.addEvent({
type: EVENTTYPES.LOAD,
callback: function () {
observeResource();
}
});
}
}
function handleSendPerformance(options2, flush) {
if (options2 === void 0) {
options2 = {};
}
if (flush === void 0) {
flush = false;
}
var record = __assign(__assign({}, options2), {
triggerTime: getTimestamp(),
triggerPageUrl: getLocationHref(),
eventType: SEDNEVENTTYPES.PERFORMANCE
});
sendData.emit(normalizeObj(record), flush);
}
function interceptFetch() {
var _this = this;
eventBus.addEvent({
type: EVENTTYPES.FETCH,
callback: function (reqUrl_1) {
var args_1 = [];
for (var _i = 1; _i < arguments.length; _i++) {
args_1[_i - 1] = arguments[_i];
}
return __awaiter$1(_this, __spreadArray([reqUrl_1], args_1, true), void 0, function (reqUrl, _options, res, fetchStart, traceObj) {
var _a, method, _b, body, url, status, statusText, clonedResponse, requestMethod, responseData, parseXhrContentResult;
if (_options === void 0) {
_options = {};
}
if (traceObj === void 0) {
traceObj = {};
}
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_a = _options.method, method = _a === void 0 ? "GET" : _a, _b = _options.body, body = _b === void 0 ? {} : _b;
url = res.url, status = res.status, statusText = res.statusText;
clonedResponse = res.clone();
requestMethod = String(method).toLocaleLowerCase();
if (isIgnoreHttp(url)) return [2
/*return*/];
if (!(status === 200 || status === 304)) return [3, 3];
if (!exports.options.value.performance.server) return [3, 2];
return [4, clonedResponse.json()];
case 1:
responseData = _c.sent();
parseXhrContentResult = parseXhrContent(responseData);
if (exports.options.value.isParseDataCode && !parseXhrContentResult.isSuccess) {
handleSendError({
eventId: exports.SENDID.SERVER,
errMessage: parseXhrContentResult.message,
requestUrl: getBaseUrl(url),
requestMethod,
requestType: "xhr",
responseStatus: parseXhrContentResult.code,
params: method.toUpperCase() === "POST" ? body : parseGetParams(url)
});
} else {
handleSendPerformance(__assign(__assign({
eventId: exports.SENDID.SERVER,
requestUrl: url,
triggerTime: fetchStart,
duration: getTimestamp() - fetchStart,
responseStatus: status,
requestMethod,
requestType: "fetch"
}, traceObj), {
params: method.toUpperCase() === "POST" ? body : parseGetParams(url)
}));
}
_c.label = 2;
case 2:
return [3, 4];
case 3:
if (exports.options.value.error.server) {
handleSendError(__assign(__assign({
eventId: exports.SENDID.SERVER,
triggerTime: fetchStart,
duration: getTimestamp() - fetchStart,
errMessage: statusText,
requestUrl: getBaseUrl(url),
responseStatus: status,
requestMethod,
requestType: "fetch"
}, traceObj), {
params: method.toUpperCase() === "POST" ? body : parseGetParams(url)
}));
}
_c.label = 4;
case 4:
return [2
/*return*/];
}
});
});
}
});
}
var RequestTemplate = /** @class */
function () {
function RequestTemplate2(config) {
if (config === void 0) {
config = {};
}
var _this = this;
this.requestUrl = "";
this.requestMethod = "";
this.requestParams = {};
this.triggerTime = -1;
Object.keys(config).forEach(function (key) {
if (isValidKey(key, config)) {
_this[key] = config[key] || null;
}
});
}
return RequestTemplate2;
}();
function interceptXHR() {
var _config = new RequestTemplate();
eventBus.addEvent({
type: EVENTTYPES.XHROPEN,
callback: function (method, url) {
_config.requestMethod = String(method).toLocaleLowerCase();
_config.requestUrl = url;
_config.requestParams = parseGetParams(url);
}
});
eventBus.addEvent({
type: EVENTTYPES.XHRSEND,
callback: function (that, body) {
on$1(that, EVENTTYPES.READYSTATECHANGE, function () {
var readyState = that.readyState,
status = that.status,
responseURL = that.responseURL,
statusText = that.statusText;
var responseText = that.responseType === "" || that.responseType === "text" ? that.responseText : "";
if (readyState === 4) {
var requestUrl = responseURL || _config.requestUrl;
if (isIgnoreHttp(requestUrl)) return;
if (status === 200 || status === 304) {
if (exports.options.value.performance.server || exports.options.value.error.server) {
var parseXhrContentResult = parseXhrContent(responseText);
if (exports.options.value.isParseDataCode && !parseXhrContentResult.isSuccess) {
handleSendError({
eventId: exports.SENDID.SERVER,
errMessage: parseXhrContentResult.message,
requestUrl,
requestMethod: _config.requestMethod,
requestType: "xhr",
responseStatus: parseXhrContentResult.code,
duration: getTimestamp() - _config.triggerTime,
params: _config.requestMethod === "post" ? body : _config.requestParams
});
} else if (exports.options.value.performance.server) {
handleSendPerformance({
eventId: exports.SENDID.SERVER,
requestUrl,
requestMethod: _config.requestMethod,
requestType: "xhr",
responseStatus: status,
duration: getTimestamp() - _config.triggerTime,
params: _config.requestMethod === "post" ? body : _config.requestParams
});
}
}
} else if (exports.options.value.error.server) {
handleSendError({
eventId: exports.SENDID.SERVER,
errMessage: statusText || responseText,
requestUrl,
requestMethod: _config.requestMethod,
requestType: "xhr",
responseStatus: status,
params: _config.requestMethod === "post" ? body : _config.requestParams,
duration: getTimestamp() - _config.triggerTime
});
}
}
});
_config.triggerTime = getTimestamp();
}
});
}
function parseXhrContent(response) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
var result = {
code: "",
message: "",
isSuccess: true
};
try {
var _response = JSON.parse(response);
if (typeof _response === "object" && _response[((_b = (_a = exports.options.value) === null || _a === void 0 ? void 0 : _a.parseDataOption) === null || _b === void 0 ? void 0 : _b.codeName) || "code"]) {
result = {
code: _response[((_d = (_c = exports.options.value) === null || _c === void 0 ? void 0 : _c.parseDataOption) === null || _d === void 0 ? void 0 : _d.codeName) || "code"] || _response.code,
message: _response[((_f = (_e = exports.options.value) === null || _e === void 0 ? void 0 : _e.parseDataOption) === null || _f === void 0 ? void 0 : _f.messageName) || "message"] || _response.message,
isSuccess: _response[((_h = (_g = exports.options.value) === null || _g === void 0 ? void 0 : _g.parseDataOption) === null || _h === void 0 ? void 0 : _h.codeName) || "code"] === ((_k = (_j = exports.options.value) === null || _j === void 0 ? void 0 : _j.parseDataOption) === null || _k === void 0 ? void 0 : _k.successCode)
};
}
} catch (error) {
result.isSuccess = true;
return result;
}
return result;
}
function isIgnoreHttp(url) {
if (!exports.options.value.ignoreRequest.length) return false;
if (!url) return false;
return exports.options.value.ignoreRequest.some(function (item) {
if (isRegExp$1(item)) {
if (item.test(url)) {
return true;
} else {
return false;
}
} else {
if (url === item) {
return true;
} else {
return false;
}
}
});
}
function initHttp() {
if (!exports.options.value.performance.server && !exports.options.value.error.server) return;
interceptXHR();
interceptFetch();
}
var oldURL = getLocationHref();
function initPv() {
if (!exports.options.value.pv.core) return;
var lastIsPop = false;
var repetitionRoute = false;
sendPageView({
referer: document.referrer
});
eventBus.addEvent({
type: EVENTTYPES.HISTORYPUSHSTATE,
callback: function () {
if (repetitionRoute) return;
lastIsPop = false;
sendPageView({
action: "navigation"
});
}
});
eventBus.addEvent({
type: EVENTTYPES.HISTORYREPLACESTATE,
callback: function () {
repetitionRoute = true;
lastIsPop = false;
sendPageView({
action: "navigation"
});
setTimeout(function () {
repetitionRoute = false;
}, 100);
}
});
eventBus.addEvent({
type: EVENTTYPES.HASHCHANGE,
callback: function () {
if (repetitionRoute) return;
if (!lastIsPop) sendPageView();
lastIsPop = false;
}
});
eventBus.addEvent({
type: EVENTTYPES.POPSTATE,
callback: function () {
if (repetitionRoute) return;
if (_global.location.hash !== "") {
var oldHost = oldURL.indexOf("#") > 0 ? oldURL.slice(0, oldURL.indexOf("#")) : oldURL;
if (_global.location.href.slice(0, _global.location.href.indexOf("#")) === oldHost) return;
}
lastIsPop = true;
sendPageView();
}
});
eventBus.addEvent({
type: EVENTTYPES.BEFOREUNLOAD,
callback: function () {
var durationTime = getTimestamp() - durationStartTime;
if (Object.values(lastSendObj).length > 0 && durationTime > 100) {
sendData.emit(__assign(__assign({}, lastSendObj), {
durationTime
}), true);
}
}
});
}
var durationStartTime = getTimestamp();
var lastSendObj = {};
function sendPageView(option) {
if (option === void 0) {
option = {};
}
var _a = option.referer,
referer = _a === void 0 ? oldURL : _a,
action = option.action,
params = option.params,
title = option.title;
var _action = action;
if (!_action) {
_action = WEBPAGELOAD[performance.navigation.type] || "";
}
setTimeout(function () {
oldURL = getLocationHref();
var sendObj = {
eventType: SEDNEVENTTYPES.PV,
eventId: baseInfo.pageId,
triggerPageUrl: getLocationHref(),
referer,
params,
title: title || document.title,
action: _action,
triggerTime: getTimestamp()
};
sendData.emit(sendObj);
var durationTime = getTimestamp() - durationStartTime;
durationStartTime = getTimestamp();
if (Object.values(lastSendObj).length > 0 && durationTime > 100) {
sendData.emit(__assign(__assign({}, lastSendObj), {
durationTime
}));
}
lastSendObj = __assign(__assign({}, sendObj), {
eventType: SEDNEVENTTYPES.PVDURATION
});
}, title ? 0 : 17);
}
function handleSendPageView(options2, flush) {
if (options2 === void 0) {
options2 = {};
}
if (flush === void 0) {
flush = false;
}
sendData.emit(__assign(__assign({
referer: oldURL,
title: document.title
}, options2), {
eventType: SEDNEVENTTYPES.PV,
eventId: baseInfo.pageId,
triggerPageUrl: getLocationHref(),
triggerTime: getTimestamp()
}), flush);
}
var Intersection = /** @class */
function () {
function Intersection2() {
this.ioMap = {};
this.targetMap = [];
this.options = {
root: null,
rootMargin: "0px",
threshold: 0.5
// 阀值设为0.5,当只有比例达到一半时才触发回调函数
};
}
Intersection2.prototype.initObserver = function (threshold) {
var _this = this;
return new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
var targetObj = _this.targetMap.find(function (mapTarget) {
return mapTarget.target === entry.target;
});
if (targetObj) {
targetObj.showTime = getTimestamp();
}
} else {
var targetObj = _this.targetMap.find(function (mapTarget) {
return mapTarget.target === entry.target;
});
if (targetObj) {
if (!targetObj.showTime) return;
targetObj.showEndTime = getTimestamp();
_this.sendEvent(targetObj);
}
}
});
}, __assign(__assign({}, this.options), {
threshold
}));
};
Intersection2.prototype.sendEvent = function (targetObj) {
sendData.emit(__assign({
eventType: SEDNEVENTTYPES.INTERSECTION,
triggerPageUrl: getLocationHref()
}, targetObj));
};
Intersection2.prototype.observe = function (gather) {
var _this = this;
var _gather = unKnowToArray(gather);
_gather.forEach(function (item) {
var _targetList = unKnowToArray(item.target);
if (!Object.prototype.hasOwnProperty.call(_this.ioMap, item.threshold)) {
_this.ioMap[item.threshold] = _this.initObserver(item.threshold || 0.5);
}
_targetList.forEach(function (target) {
var index = _this.targetMap.findIndex(function (mapTarget) {
return mapTarget.target === target;
});
if (index === -1) {
_this.ioMap[item.threshold].observe(target);
_this.targetMap.push({
target,
threshold: item.threshold,
observeTime: getTimestamp(),
// 开始监听的时间
params: item.params
});
}
});
});
};
Intersection2.prototype.unobserve = function (target) {
var _this = this;
var _targetList = unKnowToArray(target);
_targetList.forEach(function (_target) {
var targetIndex = _this.targetMap.findIndex(function (mapTarget) {
return mapTarget.target === _target;
});
if (targetIndex === -1) return;
var io = _this.ioMap[_this.targetMap[targetIndex].threshold];
if (!io) return;
_this.targetMap.splice(targetIndex, 1);
io.unobserve(_target);
});
};
Intersection2.prototype.disconnect = function () {
for (var key in this.ioMap) {
if (Object.prototype.hasOwnProperty.call(this.ioMap, key)) {
var io = this.ioMap[key];
io.disconnect();
}
}
this.targetMap = [];
this.ioMap = {};
};
return Intersection2;
}();
var intersection;
function initIntersection() {
_support.intersection = new Intersection();
intersection = _support.intersection;
}
function unzipRecordscreen(recordscreen) {
return unzip(recordscreen);
}
function beforePushEventList(fun) {
if (!validateMethods("beforePushEventList")) return;
exports.options.value.beforePushEventList.push(fun);
}
function beforeSendData(fun) {
if (!validateMethods("beforeSendData")) return;
exports.options.value.beforeSendData.push(fun);
}
function afterSendData(fun) {
if (!validateMethods("afterSendData")) return;
exports.options.value.afterSendData.push(fun);
}
function setUserUuid(id) {
if (!validateMethods("setUserUuid")) return;
exports.options.value.userUuid = id;
}
function getUserUuid() {
if (!validateMethods("getUserUuid")) return;
return exports.options.value.userUuid;
}
function getSDKUserUuid() {
if (!validateMethods("getSDKUserUuid")) return;
return exports.options.value.sdkUserUuid;
}
function getBaseInfo() {
if (!validateMethods("getBaseInfo")) return;
return __assign(__assign({}, _support.baseInfo.base), {
userUuid: exports.options.value.userUuid
});
}
function getFirstScreen() {
if (!validateMethods("getFirstScreen")) return;
return __assign({}, _support.firstScreen);
}
function traceError(options2, flush) {
if (options2 === void 0) {
options2 = {};
}
if (flush === void 0) {
flush = false;
}
if (!validateMethods("traceError")) return;
return handleSendError(options2, flush);
}
function tracePerformance(options2, flush) {
if (options2 === void 0) {
options2 = {};
}
if (flush === void 0) {
flush = false;
}
if (!validateMethods("tracePerformance")) return;
return handleSendPerformance(options2, flush);
}
function traceCustomEvent(options2, flush) {
if (options2 === void 0) {
options2 = {};
}
if (flush === void 0) {
flush = false;
}
if (!validateMethods("traceCustomEvent")) return;
return handleSendEvent(options2, flush);
}
function tracePageView(option, flush) {
if (option === void 0) {
option = {};
}
if (flush === void 0) {
flush = false;
}
if (!validateMethods("tracePageView")) return;
return handleSendPageView(option, flush);
}
function getIPs() {
return getIPs$1().then(function (res) {
return res[0];
});
}
function intersectionObserver(gather) {
if (!validateMethods("intersectionObserver")) return;
intersection.observe(gather);
}
function intersectionUnobserve(target) {
if (!validateMethods("intersectionUnobserve")) return;
intersection.unobserve(target);
}
function intersectionDisconnect() {
if (!validateMethods("intersectionDisconnect")) return;
intersection.disconnect();
}
function sendLocal() {
if (!validateMethods("sendData") && !exports.options.value.localization) return;
var localItem = LocalStorageUtil.getItem(SDK_LOCAL_KEY);
if (localItem) {
sendData.sendLocal(localItem);
LocalStorageUtil.removeItem(SDK_LOCAL_KEY);
}
}
function setLocalizationOverFlow(overFlowFun) {
if (!validateMethods("localizationOverFlow") && !exports.options.value.localization) return;
exports.options.value.localizationOverFlow = overFlowFun;
}
function getOptions() {
return deepCopy(exports.options.value);
}
var exportMethods = /*#__PURE__*/Object.freeze({
__proto__: null,
afterSendData: afterSendData,
beforePushEventList: beforePushEventList,
beforeSendData: beforeSendData,
getBaseInfo: getBaseInfo,
getFirstScreen: getFirstScreen,
getIPs: getIPs,
getOptions: getOptions,
getSDKUserUuid: getSDKUserUuid,
getUserUuid: getUserUuid,
intersectionDisconnect: intersectionDisconnect,
intersectionObserver: intersectionObserver,
intersectionUnobserve: intersectionUnobserve,
sendLocal: sendLocal,
setLocalizationOverFlow: setLocalizationOverFlow,
setUserUuid: setUserUuid,
traceCustomEvent: traceCustomEvent,
traceError: traceError,
tracePageView: tracePageView,
tracePerformance: tracePerformance,
unzipRecordscreen: unzipRecordscreen
});
function init(options) {
if (_global.__webTracingInit__) return;
if (!initOptions(options)) return;
initReplace();
initBase();
initSendData();
initLineStatus();
initError();
initEvent();
initHttp();
initPerformance();
initPv();
initIntersection();
if (exports.options.value.recordScreen) initRecordScreen();
_global.__webTracingInit__ = true;
}
__assign(__assign({
init
}, exportMethods), {
options: exports.options
});
function install(Vue, options) {
var handler = Vue.config.errorHandler;
Vue.config.errorHandler = function (err, vm, info) {
logError(err);
var errorInfo = __assign({
eventId: exports.SENDID.CODE
}, parseError(err));
traceError(errorInfo);
if (handler) handler.apply(null, [err, vm, info]);
};
init(options);
}
var index = {
install
};
exports.afterSendData = afterSendData;
exports.beforePushEventList = beforePushEventList;
exports.beforeSendData = beforeSendData;
exports.default = index;
exports.exportMethods = exportMethods;
exports.getBaseInfo = getBaseInfo;
exports.getFirstScreen = getFirstScreen;
exports.getIPs = getIPs;
exports.getOptions = getOptions;
exports.getSDKUserUuid = getSDKUserUuid;
exports.getUserUuid = getUserUuid;
exports.init = init;
exports.intersectionDisconnect = intersectionDisconnect;
exports.intersectionObserver = intersectionObserver;
exports.intersectionUnobserve = intersectionUnobserve;
exports.logError = logError;
exports.parseError = parseError;
exports.sendLocal = sendLocal;
exports.setLocalizationOverFlow = setLocalizationOverFlow;
exports.setUserUuid = setUserUuid;
exports.traceCustomEvent = traceCustomEvent;
exports.traceError = traceError;
exports.tracePageView = tracePageView;
exports.tracePerformance = tracePerformance;
exports.unzipRecordscreen = unzipRecordscreen;