You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

24456 lines
1.4 MiB

(global["webpackJsonp"] = global["webpackJsonp"] || []).push([["common/vendor"],[
/* 0 */,
/* 1 */
/*!*********************************************************!*\
!*** ./node_modules/@dcloudio/uni-mp-weixin/dist/wx.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var objectKeys = ['qy', 'env', 'error', 'version', 'lanDebug', 'cloud', 'serviceMarket', 'router', 'worklet', '__webpack_require_UNI_MP_PLUGIN__'];
var singlePageDisableKey = ['lanDebug', 'router', 'worklet'];
var target = typeof globalThis !== 'undefined' ? globalThis : function () {
return this;
}();
var key = ['w', 'x'].join('');
var oldWx = target[key];
var launchOption = oldWx.getLaunchOptionsSync ? oldWx.getLaunchOptionsSync() : null;
function isWxKey(key) {
if (launchOption && launchOption.scene === 1154 && singlePageDisableKey.includes(key)) {
return false;
}
return objectKeys.indexOf(key) > -1 || typeof oldWx[key] === 'function';
}
function initWx() {
var newWx = {};
for (var _key in oldWx) {
if (isWxKey(_key)) {
// TODO wrapper function
newWx[_key] = oldWx[_key];
}
}
return newWx;
}
target[key] = initWx();
var _default = target[key];
exports.default = _default;
/***/ }),
/* 2 */
/*!************************************************************!*\
!*** ./node_modules/@dcloudio/uni-mp-weixin/dist/index.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(wx, global) {
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ 4);
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createApp = createApp;
exports.createComponent = createComponent;
exports.createPage = createPage;
exports.createPlugin = createPlugin;
exports.createSubpackageApp = createSubpackageApp;
exports.default = void 0;
var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ 5));
var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ 11));
var _construct2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/construct */ 15));
var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/toConsumableArray */ 18));
var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ 13));
var _uniI18n = __webpack_require__(/*! @dcloudio/uni-i18n */ 22);
var _vue = _interopRequireDefault(__webpack_require__(/*! vue */ 25));
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
var realAtob;
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/;
if (typeof atob !== 'function') {
realAtob = function realAtob(str) {
str = String(str).replace(/[\t\n\f\r ]+/g, '');
if (!b64re.test(str)) {
throw new Error("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
}
// Adding the padding if missing, for semplicity
str += '=='.slice(2 - (str.length & 3));
var bitmap;
var result = '';
var r1;
var r2;
var i = 0;
for (; i < str.length;) {
bitmap = b64.indexOf(str.charAt(i++)) << 18 | b64.indexOf(str.charAt(i++)) << 12 | (r1 = b64.indexOf(str.charAt(i++))) << 6 | (r2 = b64.indexOf(str.charAt(i++)));
result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) : r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) : String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255);
}
return result;
};
} else {
// 注意atob只能在全局对象上调用,例如:`const Base64 = {atob};Base64.atob('xxxx')`是错误的用法
realAtob = atob;
}
function b64DecodeUnicode(str) {
return decodeURIComponent(realAtob(str).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
function getCurrentUserInfo() {
var token = wx.getStorageSync('uni_id_token') || '';
var tokenArr = token.split('.');
if (!token || tokenArr.length !== 3) {
return {
uid: null,
role: [],
permission: [],
tokenExpired: 0
};
}
var userInfo;
try {
userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1]));
} catch (error) {
throw new Error('获取当前用户信息出错,详细错误信息为:' + error.message);
}
userInfo.tokenExpired = userInfo.exp * 1000;
delete userInfo.exp;
delete userInfo.iat;
return userInfo;
}
function uniIdMixin(Vue) {
Vue.prototype.uniIDHasRole = function (roleId) {
var _getCurrentUserInfo = getCurrentUserInfo(),
role = _getCurrentUserInfo.role;
return role.indexOf(roleId) > -1;
};
Vue.prototype.uniIDHasPermission = function (permissionId) {
var _getCurrentUserInfo2 = getCurrentUserInfo(),
permission = _getCurrentUserInfo2.permission;
return this.uniIDHasRole('admin') || permission.indexOf(permissionId) > -1;
};
Vue.prototype.uniIDTokenValid = function () {
var _getCurrentUserInfo3 = getCurrentUserInfo(),
tokenExpired = _getCurrentUserInfo3.tokenExpired;
return tokenExpired > Date.now();
};
}
var _toString = Object.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isFn(fn) {
return typeof fn === 'function';
}
function isStr(str) {
return typeof str === 'string';
}
function isObject(obj) {
return obj !== null && (0, _typeof2.default)(obj) === 'object';
}
function isPlainObject(obj) {
return _toString.call(obj) === '[object Object]';
}
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
function noop() {}
/**
* Create a cached version of a pure function.
*/
function cached(fn) {
var cache = Object.create(null);
return function cachedFn(str) {
var hit = cache[str];
return hit || (cache[str] = fn(str));
};
}
/**
* Camelize a hyphen-delimited string.
*/
var camelizeRE = /-(\w)/g;
var camelize = cached(function (str) {
return str.replace(camelizeRE, function (_, c) {
return c ? c.toUpperCase() : '';
});
});
function sortObject(obj) {
var sortObj = {};
if (isPlainObject(obj)) {
Object.keys(obj).sort().forEach(function (key) {
sortObj[key] = obj[key];
});
}
return !Object.keys(sortObj) ? obj : sortObj;
}
var HOOKS = ['invoke', 'success', 'fail', 'complete', 'returnValue'];
var globalInterceptors = {};
var scopedInterceptors = {};
function mergeHook(parentVal, childVal) {
var res = childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal;
return res ? dedupeHooks(res) : res;
}
function dedupeHooks(hooks) {
var res = [];
for (var i = 0; i < hooks.length; i++) {
if (res.indexOf(hooks[i]) === -1) {
res.push(hooks[i]);
}
}
return res;
}
function removeHook(hooks, hook) {
var index = hooks.indexOf(hook);
if (index !== -1) {
hooks.splice(index, 1);
}
}
function mergeInterceptorHook(interceptor, option) {
Object.keys(option).forEach(function (hook) {
if (HOOKS.indexOf(hook) !== -1 && isFn(option[hook])) {
interceptor[hook] = mergeHook(interceptor[hook], option[hook]);
}
});
}
function removeInterceptorHook(interceptor, option) {
if (!interceptor || !option) {
return;
}
Object.keys(option).forEach(function (hook) {
if (HOOKS.indexOf(hook) !== -1 && isFn(option[hook])) {
removeHook(interceptor[hook], option[hook]);
}
});
}
function addInterceptor(method, option) {
if (typeof method === 'string' && isPlainObject(option)) {
mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), option);
} else if (isPlainObject(method)) {
mergeInterceptorHook(globalInterceptors, method);
}
}
function removeInterceptor(method, option) {
if (typeof method === 'string') {
if (isPlainObject(option)) {
removeInterceptorHook(scopedInterceptors[method], option);
} else {
delete scopedInterceptors[method];
}
} else if (isPlainObject(method)) {
removeInterceptorHook(globalInterceptors, method);
}
}
function wrapperHook(hook, params) {
return function (data) {
return hook(data, params) || data;
};
}
function isPromise(obj) {
return !!obj && ((0, _typeof2.default)(obj) === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}
function queue(hooks, data, params) {
var promise = false;
for (var i = 0; i < hooks.length; i++) {
var hook = hooks[i];
if (promise) {
promise = Promise.resolve(wrapperHook(hook, params));
} else {
var res = hook(data, params);
if (isPromise(res)) {
promise = Promise.resolve(res);
}
if (res === false) {
return {
then: function then() {}
};
}
}
}
return promise || {
then: function then(callback) {
return callback(data);
}
};
}
function wrapperOptions(interceptor) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
['success', 'fail', 'complete'].forEach(function (name) {
if (Array.isArray(interceptor[name])) {
var oldCallback = options[name];
options[name] = function callbackInterceptor(res) {
queue(interceptor[name], res, options).then(function (res) {
/* eslint-disable no-mixed-operators */
return isFn(oldCallback) && oldCallback(res) || res;
});
};
}
});
return options;
}
function wrapperReturnValue(method, returnValue) {
var returnValueHooks = [];
if (Array.isArray(globalInterceptors.returnValue)) {
returnValueHooks.push.apply(returnValueHooks, (0, _toConsumableArray2.default)(globalInterceptors.returnValue));
}
var interceptor = scopedInterceptors[method];
if (interceptor && Array.isArray(interceptor.returnValue)) {
returnValueHooks.push.apply(returnValueHooks, (0, _toConsumableArray2.default)(interceptor.returnValue));
}
returnValueHooks.forEach(function (hook) {
returnValue = hook(returnValue) || returnValue;
});
return returnValue;
}
function getApiInterceptorHooks(method) {
var interceptor = Object.create(null);
Object.keys(globalInterceptors).forEach(function (hook) {
if (hook !== 'returnValue') {
interceptor[hook] = globalInterceptors[hook].slice();
}
});
var scopedInterceptor = scopedInterceptors[method];
if (scopedInterceptor) {
Object.keys(scopedInterceptor).forEach(function (hook) {
if (hook !== 'returnValue') {
interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
}
});
}
return interceptor;
}
function invokeApi(method, api, options) {
for (var _len = arguments.length, params = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
params[_key - 3] = arguments[_key];
}
var interceptor = getApiInterceptorHooks(method);
if (interceptor && Object.keys(interceptor).length) {
if (Array.isArray(interceptor.invoke)) {
var res = queue(interceptor.invoke, options);
return res.then(function (options) {
// 重新访问 getApiInterceptorHooks, 允许 invoke 中再次调用 addInterceptor,removeInterceptor
return api.apply(void 0, [wrapperOptions(getApiInterceptorHooks(method), options)].concat(params));
});
} else {
return api.apply(void 0, [wrapperOptions(interceptor, options)].concat(params));
}
}
return api.apply(void 0, [options].concat(params));
}
var promiseInterceptor = {
returnValue: function returnValue(res) {
if (!isPromise(res)) {
return res;
}
return new Promise(function (resolve, reject) {
res.then(function (res) {
if (res[0]) {
reject(res[0]);
} else {
resolve(res[1]);
}
});
});
}
};
var SYNC_API_RE = /^\$|Window$|WindowStyle$|sendHostEvent|sendNativeEvent|restoreGlobal|requireGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64|getLocale|setLocale|invokePushCallback|getWindowInfo|getDeviceInfo|getAppBaseInfo|getSystemSetting|getAppAuthorizeSetting|initUTS|requireUTS|registerUTS/;
var CONTEXT_API_RE = /^create|Manager$/;
// Context例外情况
var CONTEXT_API_RE_EXC = ['createBLEConnection'];
// 同步例外情况
var ASYNC_API = ['createBLEConnection', 'createPushMessage'];
var CALLBACK_API_RE = /^on|^off/;
function isContextApi(name) {
return CONTEXT_API_RE.test(name) && CONTEXT_API_RE_EXC.indexOf(name) === -1;
}
function isSyncApi(name) {
return SYNC_API_RE.test(name) && ASYNC_API.indexOf(name) === -1;
}
function isCallbackApi(name) {
return CALLBACK_API_RE.test(name) && name !== 'onPush';
}
function handlePromise(promise) {
return promise.then(function (data) {
return [null, data];
}).catch(function (err) {
return [err];
});
}
function shouldPromise(name) {
if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
return false;
}
return true;
}
/* eslint-disable no-extend-native */
if (!Promise.prototype.finally) {
Promise.prototype.finally = function (callback) {
var promise = this.constructor;
return this.then(function (value) {
return promise.resolve(callback()).then(function () {
return value;
});
}, function (reason) {
return promise.resolve(callback()).then(function () {
throw reason;
});
});
};
}
function promisify(name, api) {
if (!shouldPromise(name) || !isFn(api)) {
return api;
}
return function promiseApi() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
params[_key2 - 1] = arguments[_key2];
}
if (isFn(options.success) || isFn(options.fail) || isFn(options.complete)) {
return wrapperReturnValue(name, invokeApi.apply(void 0, [name, api, options].concat(params)));
}
return wrapperReturnValue(name, handlePromise(new Promise(function (resolve, reject) {
invokeApi.apply(void 0, [name, api, Object.assign({}, options, {
success: resolve,
fail: reject
})].concat(params));
})));
};
}
var EPS = 1e-4;
var BASE_DEVICE_WIDTH = 750;
var isIOS = false;
var deviceWidth = 0;
var deviceDPR = 0;
function checkDeviceWidth() {
var _wx$getSystemInfoSync = wx.getSystemInfoSync(),
platform = _wx$getSystemInfoSync.platform,
pixelRatio = _wx$getSystemInfoSync.pixelRatio,
windowWidth = _wx$getSystemInfoSync.windowWidth; // uni=>wx runtime 编译目标是 uni 对象,内部不允许直接使用 uni
deviceWidth = windowWidth;
deviceDPR = pixelRatio;
isIOS = platform === 'ios';
}
function upx2px(number, newDeviceWidth) {
if (deviceWidth === 0) {
checkDeviceWidth();
}
number = Number(number);
if (number === 0) {
return 0;
}
var result = number / BASE_DEVICE_WIDTH * (newDeviceWidth || deviceWidth);
if (result < 0) {
result = -result;
}
result = Math.floor(result + EPS);
if (result === 0) {
if (deviceDPR === 1 || !isIOS) {
result = 1;
} else {
result = 0.5;
}
}
return number < 0 ? -result : result;
}
var LOCALE_ZH_HANS = 'zh-Hans';
var LOCALE_ZH_HANT = 'zh-Hant';
var LOCALE_EN = 'en';
var LOCALE_FR = 'fr';
var LOCALE_ES = 'es';
var messages = {};
var locale;
{
locale = normalizeLocale(wx.getSystemInfoSync().language) || LOCALE_EN;
}
function initI18nMessages() {
if (!isEnableLocale()) {
return;
}
var localeKeys = Object.keys(__uniConfig.locales);
if (localeKeys.length) {
localeKeys.forEach(function (locale) {
var curMessages = messages[locale];
var userMessages = __uniConfig.locales[locale];
if (curMessages) {
Object.assign(curMessages, userMessages);
} else {
messages[locale] = userMessages;
}
});
}
}
initI18nMessages();
var i18n = (0, _uniI18n.initVueI18n)(locale, {});
var t = i18n.t;
var i18nMixin = i18n.mixin = {
beforeCreate: function beforeCreate() {
var _this = this;
var unwatch = i18n.i18n.watchLocale(function () {
_this.$forceUpdate();
});
this.$once('hook:beforeDestroy', function () {
unwatch();
});
},
methods: {
$$t: function $$t(key, values) {
return t(key, values);
}
}
};
var setLocale = i18n.setLocale;
var getLocale = i18n.getLocale;
function initAppLocale(Vue, appVm, locale) {
var state = Vue.observable({
locale: locale || i18n.getLocale()
});
var localeWatchers = [];
appVm.$watchLocale = function (fn) {
localeWatchers.push(fn);
};
Object.defineProperty(appVm, '$locale', {
get: function get() {
return state.locale;
},
set: function set(v) {
state.locale = v;
localeWatchers.forEach(function (watch) {
return watch(v);
});
}
});
}
function isEnableLocale() {
return typeof __uniConfig !== 'undefined' && __uniConfig.locales && !!Object.keys(__uniConfig.locales).length;
}
function include(str, parts) {
return !!parts.find(function (part) {
return str.indexOf(part) !== -1;
});
}
function startsWith(str, parts) {
return parts.find(function (part) {
return str.indexOf(part) === 0;
});
}
function normalizeLocale(locale, messages) {
if (!locale) {
return;
}
locale = locale.trim().replace(/_/g, '-');
if (messages && messages[locale]) {
return locale;
}
locale = locale.toLowerCase();
if (locale === 'chinese') {
// 支付宝
return LOCALE_ZH_HANS;
}
if (locale.indexOf('zh') === 0) {
if (locale.indexOf('-hans') > -1) {
return LOCALE_ZH_HANS;
}
if (locale.indexOf('-hant') > -1) {
return LOCALE_ZH_HANT;
}
if (include(locale, ['-tw', '-hk', '-mo', '-cht'])) {
return LOCALE_ZH_HANT;
}
return LOCALE_ZH_HANS;
}
var lang = startsWith(locale, [LOCALE_EN, LOCALE_FR, LOCALE_ES]);
if (lang) {
return lang;
}
}
// export function initI18n() {
// const localeKeys = Object.keys(__uniConfig.locales || {})
// if (localeKeys.length) {
// localeKeys.forEach((locale) =>
// i18n.add(locale, __uniConfig.locales[locale])
// )
// }
// }
function getLocale$1() {
// 优先使用 $locale
if (isFn(getApp)) {
var app = getApp({
allowDefault: true
});
if (app && app.$vm) {
return app.$vm.$locale;
}
}
return normalizeLocale(wx.getSystemInfoSync().language) || LOCALE_EN;
}
function setLocale$1(locale) {
var app = isFn(getApp) ? getApp() : false;
if (!app) {
return false;
}
var oldLocale = app.$vm.$locale;
if (oldLocale !== locale) {
app.$vm.$locale = locale;
onLocaleChangeCallbacks.forEach(function (fn) {
return fn({
locale: locale
});
});
return true;
}
return false;
}
var onLocaleChangeCallbacks = [];
function onLocaleChange(fn) {
if (onLocaleChangeCallbacks.indexOf(fn) === -1) {
onLocaleChangeCallbacks.push(fn);
}
}
if (typeof global !== 'undefined') {
global.getLocale = getLocale$1;
}
var interceptors = {
promiseInterceptor: promiseInterceptor
};
var baseApi = /*#__PURE__*/Object.freeze({
__proto__: null,
upx2px: upx2px,
getLocale: getLocale$1,
setLocale: setLocale$1,
onLocaleChange: onLocaleChange,
addInterceptor: addInterceptor,
removeInterceptor: removeInterceptor,
interceptors: interceptors
});
function findExistsPageIndex(url) {
var pages = getCurrentPages();
var len = pages.length;
while (len--) {
var page = pages[len];
if (page.$page && page.$page.fullPath === url) {
return len;
}
}
return -1;
}
var redirectTo = {
name: function name(fromArgs) {
if (fromArgs.exists === 'back' && fromArgs.delta) {
return 'navigateBack';
}
return 'redirectTo';
},
args: function args(fromArgs) {
if (fromArgs.exists === 'back' && fromArgs.url) {
var existsPageIndex = findExistsPageIndex(fromArgs.url);
if (existsPageIndex !== -1) {
var delta = getCurrentPages().length - 1 - existsPageIndex;
if (delta > 0) {
fromArgs.delta = delta;
}
}
}
}
};
var previewImage = {
args: function args(fromArgs) {
var currentIndex = parseInt(fromArgs.current);
if (isNaN(currentIndex)) {
return;
}
var urls = fromArgs.urls;
if (!Array.isArray(urls)) {
return;
}
var len = urls.length;
if (!len) {
return;
}
if (currentIndex < 0) {
currentIndex = 0;
} else if (currentIndex >= len) {
currentIndex = len - 1;
}
if (currentIndex > 0) {
fromArgs.current = urls[currentIndex];
fromArgs.urls = urls.filter(function (item, index) {
return index < currentIndex ? item !== urls[currentIndex] : true;
});
} else {
fromArgs.current = urls[0];
}
return {
indicator: false,
loop: false
};
}
};
var UUID_KEY = '__DC_STAT_UUID';
var deviceId;
function useDeviceId(result) {
deviceId = deviceId || wx.getStorageSync(UUID_KEY);
if (!deviceId) {
deviceId = Date.now() + '' + Math.floor(Math.random() * 1e7);
wx.setStorage({
key: UUID_KEY,
data: deviceId
});
}
result.deviceId = deviceId;
}
function addSafeAreaInsets(result) {
if (result.safeArea) {
var safeArea = result.safeArea;
result.safeAreaInsets = {
top: safeArea.top,
left: safeArea.left,
right: result.windowWidth - safeArea.right,
bottom: result.screenHeight - safeArea.bottom
};
}
}
function populateParameters(result) {
var _result$brand = result.brand,
brand = _result$brand === void 0 ? '' : _result$brand,
_result$model = result.model,
model = _result$model === void 0 ? '' : _result$model,
_result$system = result.system,
system = _result$system === void 0 ? '' : _result$system,
_result$language = result.language,
language = _result$language === void 0 ? '' : _result$language,
theme = result.theme,
version = result.version,
platform = result.platform,
fontSizeSetting = result.fontSizeSetting,
SDKVersion = result.SDKVersion,
pixelRatio = result.pixelRatio,
deviceOrientation = result.deviceOrientation;
// const isQuickApp = "mp-weixin".indexOf('quickapp-webview') !== -1
var extraParam = {};
// osName osVersion
var osName = '';
var osVersion = '';
{
osName = system.split(' ')[0] || '';
osVersion = system.split(' ')[1] || '';
}
var hostVersion = version;
// deviceType
var deviceType = getGetDeviceType(result, model);
// deviceModel
var deviceBrand = getDeviceBrand(brand);
// hostName
var _hostName = getHostName(result);
// deviceOrientation
var _deviceOrientation = deviceOrientation; // 仅 微信 百度 支持
// devicePixelRatio
var _devicePixelRatio = pixelRatio;
// SDKVersion
var _SDKVersion = SDKVersion;
// hostLanguage
var hostLanguage = language.replace(/_/g, '-');
// wx.getAccountInfoSync
var parameters = {
appId: "__UNI__9BF1085",
appName: "daoyou",
appVersion: "1.0.0",
appVersionCode: "100",
appLanguage: getAppLanguage(hostLanguage),
uniCompileVersion: "4.15",
uniRuntimeVersion: "4.15",
uniPlatform: undefined || "mp-weixin",
deviceBrand: deviceBrand,
deviceModel: model,
deviceType: deviceType,
devicePixelRatio: _devicePixelRatio,
deviceOrientation: _deviceOrientation,
osName: osName.toLocaleLowerCase(),
osVersion: osVersion,
hostTheme: theme,
hostVersion: hostVersion,
hostLanguage: hostLanguage,
hostName: _hostName,
hostSDKVersion: _SDKVersion,
hostFontSizeSetting: fontSizeSetting,
windowTop: 0,
windowBottom: 0,
// TODO
osLanguage: undefined,
osTheme: undefined,
ua: undefined,
hostPackageName: undefined,
browserName: undefined,
browserVersion: undefined
};
Object.assign(result, parameters, extraParam);
}
function getGetDeviceType(result, model) {
var deviceType = result.deviceType || 'phone';
{
var deviceTypeMaps = {
ipad: 'pad',
windows: 'pc',
mac: 'pc'
};
var deviceTypeMapsKeys = Object.keys(deviceTypeMaps);
var _model = model.toLocaleLowerCase();
for (var index = 0; index < deviceTypeMapsKeys.length; index++) {
var _m = deviceTypeMapsKeys[index];
if (_model.indexOf(_m) !== -1) {
deviceType = deviceTypeMaps[_m];
break;
}
}
}
return deviceType;
}
function getDeviceBrand(brand) {
var deviceBrand = brand;
if (deviceBrand) {
deviceBrand = brand.toLocaleLowerCase();
}
return deviceBrand;
}
function getAppLanguage(defaultLanguage) {
return getLocale$1 ? getLocale$1() : defaultLanguage;
}
function getHostName(result) {
var _platform = 'WeChat';
var _hostName = result.hostName || _platform; // mp-jd
{
if (result.environment) {
_hostName = result.environment;
} else if (result.host && result.host.env) {
_hostName = result.host.env;
}
}
return _hostName;
}
var getSystemInfo = {
returnValue: function returnValue(result) {
useDeviceId(result);
addSafeAreaInsets(result);
populateParameters(result);
}
};
var showActionSheet = {
args: function args(fromArgs) {
if ((0, _typeof2.default)(fromArgs) === 'object') {
fromArgs.alertText = fromArgs.title;
}
}
};
var getAppBaseInfo = {
returnValue: function returnValue(result) {
var _result = result,
version = _result.version,
language = _result.language,
SDKVersion = _result.SDKVersion,
theme = _result.theme;
var _hostName = getHostName(result);
var hostLanguage = language.replace('_', '-');
result = sortObject(Object.assign(result, {
appId: "__UNI__9BF1085",
appName: "daoyou",
appVersion: "1.0.0",
appVersionCode: "100",
appLanguage: getAppLanguage(hostLanguage),
hostVersion: version,
hostLanguage: hostLanguage,
hostName: _hostName,
hostSDKVersion: SDKVersion,
hostTheme: theme
}));
}
};
var getDeviceInfo = {
returnValue: function returnValue(result) {
var _result2 = result,
brand = _result2.brand,
model = _result2.model;
var deviceType = getGetDeviceType(result, model);
var deviceBrand = getDeviceBrand(brand);
useDeviceId(result);
result = sortObject(Object.assign(result, {
deviceType: deviceType,
deviceBrand: deviceBrand,
deviceModel: model
}));
}
};
var getWindowInfo = {
returnValue: function returnValue(result) {
addSafeAreaInsets(result);
result = sortObject(Object.assign(result, {
windowTop: 0,
windowBottom: 0
}));
}
};
var getAppAuthorizeSetting = {
returnValue: function returnValue(result) {
var locationReducedAccuracy = result.locationReducedAccuracy;
result.locationAccuracy = 'unsupported';
if (locationReducedAccuracy === true) {
result.locationAccuracy = 'reduced';
} else if (locationReducedAccuracy === false) {
result.locationAccuracy = 'full';
}
}
};
// import navigateTo from 'uni-helpers/navigate-to'
var compressImage = {
args: function args(fromArgs) {
// https://developers.weixin.qq.com/community/develop/doc/000c08940c865011298e0a43256800?highLine=compressHeight
if (fromArgs.compressedHeight && !fromArgs.compressHeight) {
fromArgs.compressHeight = fromArgs.compressedHeight;
}
if (fromArgs.compressedWidth && !fromArgs.compressWidth) {
fromArgs.compressWidth = fromArgs.compressedWidth;
}
}
};
var protocols = {
redirectTo: redirectTo,
// navigateTo, // 由于在微信开发者工具的页面参数,会显示__id__参数,因此暂时关闭mp-weixin对于navigateTo的AOP
previewImage: previewImage,
getSystemInfo: getSystemInfo,
getSystemInfoSync: getSystemInfo,
showActionSheet: showActionSheet,
getAppBaseInfo: getAppBaseInfo,
getDeviceInfo: getDeviceInfo,
getWindowInfo: getWindowInfo,
getAppAuthorizeSetting: getAppAuthorizeSetting,
compressImage: compressImage
};
var todos = ['vibrate', 'preloadPage', 'unPreloadPage', 'loadSubPackage'];
var canIUses = [];
var CALLBACKS = ['success', 'fail', 'cancel', 'complete'];
function processCallback(methodName, method, returnValue) {
return function (res) {
return method(processReturnValue(methodName, res, returnValue));
};
}
function processArgs(methodName, fromArgs) {
var argsOption = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var returnValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var keepFromArgs = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
if (isPlainObject(fromArgs)) {
// 一般 api 的参数解析
var toArgs = keepFromArgs === true ? fromArgs : {}; // returnValue 为 false 时,说明是格式化返回值,直接在返回值对象上修改赋值
if (isFn(argsOption)) {
argsOption = argsOption(fromArgs, toArgs) || {};
}
for (var key in fromArgs) {
if (hasOwn(argsOption, key)) {
var keyOption = argsOption[key];
if (isFn(keyOption)) {
keyOption = keyOption(fromArgs[key], fromArgs, toArgs);
}
if (!keyOption) {
// 不支持的参数
console.warn("The '".concat(methodName, "' method of platform '\u5FAE\u4FE1\u5C0F\u7A0B\u5E8F' does not support option '").concat(key, "'"));
} else if (isStr(keyOption)) {
// 重写参数 key
toArgs[keyOption] = fromArgs[key];
} else if (isPlainObject(keyOption)) {
// {name:newName,value:value}可重新指定参数 key:value
toArgs[keyOption.name ? keyOption.name : key] = keyOption.value;
}
} else if (CALLBACKS.indexOf(key) !== -1) {
if (isFn(fromArgs[key])) {
toArgs[key] = processCallback(methodName, fromArgs[key], returnValue);
}
} else {
if (!keepFromArgs) {
toArgs[key] = fromArgs[key];
}
}
}
return toArgs;
} else if (isFn(fromArgs)) {
fromArgs = processCallback(methodName, fromArgs, returnValue);
}
return fromArgs;
}
function processReturnValue(methodName, res, returnValue) {
var keepReturnValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
if (isFn(protocols.returnValue)) {
// 处理通用 returnValue
res = protocols.returnValue(methodName, res);
}
return processArgs(methodName, res, returnValue, {}, keepReturnValue);
}
function wrapper(methodName, method) {
if (hasOwn(protocols, methodName)) {
var protocol = protocols[methodName];
if (!protocol) {
// 暂不支持的 api
return function () {
console.error("Platform '\u5FAE\u4FE1\u5C0F\u7A0B\u5E8F' does not support '".concat(methodName, "'."));
};
}
return function (arg1, arg2) {
// 目前 api 最多两个参数
var options = protocol;
if (isFn(protocol)) {
options = protocol(arg1);
}
arg1 = processArgs(methodName, arg1, options.args, options.returnValue);
var args = [arg1];
if (typeof arg2 !== 'undefined') {
args.push(arg2);
}
if (isFn(options.name)) {
methodName = options.name(arg1);
} else if (isStr(options.name)) {
methodName = options.name;
}
var returnValue = wx[methodName].apply(wx, args);
if (isSyncApi(methodName)) {
// 同步 api
return processReturnValue(methodName, returnValue, options.returnValue, isContextApi(methodName));
}
return returnValue;
};
}
return method;
}
var todoApis = Object.create(null);
var TODOS = ['onTabBarMidButtonTap', 'subscribePush', 'unsubscribePush', 'onPush', 'offPush', 'share'];
function createTodoApi(name) {
return function todoApi(_ref) {
var fail = _ref.fail,
complete = _ref.complete;
var res = {
errMsg: "".concat(name, ":fail method '").concat(name, "' not supported")
};
isFn(fail) && fail(res);
isFn(complete) && complete(res);
};
}
TODOS.forEach(function (name) {
todoApis[name] = createTodoApi(name);
});
var providers = {
oauth: ['weixin'],
share: ['weixin'],
payment: ['wxpay'],
push: ['weixin']
};
function getProvider(_ref2) {
var service = _ref2.service,
success = _ref2.success,
fail = _ref2.fail,
complete = _ref2.complete;
var res = false;
if (providers[service]) {
res = {
errMsg: 'getProvider:ok',
service: service,
provider: providers[service]
};
isFn(success) && success(res);
} else {
res = {
errMsg: 'getProvider:fail service not found'
};
isFn(fail) && fail(res);
}
isFn(complete) && complete(res);
}
var extraApi = /*#__PURE__*/Object.freeze({
__proto__: null,
getProvider: getProvider
});
var getEmitter = function () {
var Emitter;
return function getUniEmitter() {
if (!Emitter) {
Emitter = new _vue.default();
}
return Emitter;
};
}();
function apply(ctx, method, args) {
return ctx[method].apply(ctx, args);
}
function $on() {
return apply(getEmitter(), '$on', Array.prototype.slice.call(arguments));
}
function $off() {
return apply(getEmitter(), '$off', Array.prototype.slice.call(arguments));
}
function $once() {
return apply(getEmitter(), '$once', Array.prototype.slice.call(arguments));
}
function $emit() {
return apply(getEmitter(), '$emit', Array.prototype.slice.call(arguments));
}
var eventApi = /*#__PURE__*/Object.freeze({
__proto__: null,
$on: $on,
$off: $off,
$once: $once,
$emit: $emit
});
/**
* 框架内 try-catch
*/
/**
* 开发者 try-catch
*/
function tryCatch(fn) {
return function () {
try {
return fn.apply(fn, arguments);
} catch (e) {
// TODO
console.error(e);
}
};
}
function getApiCallbacks(params) {
var apiCallbacks = {};
for (var name in params) {
var param = params[name];
if (isFn(param)) {
apiCallbacks[name] = tryCatch(param);
delete params[name];
}
}
return apiCallbacks;
}
var cid;
var cidErrMsg;
var enabled;
function normalizePushMessage(message) {
try {
return JSON.parse(message);
} catch (e) {}
return message;
}
function invokePushCallback(args) {
if (args.type === 'enabled') {
enabled = true;
} else if (args.type === 'clientId') {
cid = args.cid;
cidErrMsg = args.errMsg;
invokeGetPushCidCallbacks(cid, args.errMsg);
} else if (args.type === 'pushMsg') {
var message = {
type: 'receive',
data: normalizePushMessage(args.message)
};
for (var i = 0; i < onPushMessageCallbacks.length; i++) {
var callback = onPushMessageCallbacks[i];
callback(message);
// 该消息已被阻止
if (message.stopped) {
break;
}
}
} else if (args.type === 'click') {
onPushMessageCallbacks.forEach(function (callback) {
callback({
type: 'click',
data: normalizePushMessage(args.message)
});
});
}
}
var getPushCidCallbacks = [];
function invokeGetPushCidCallbacks(cid, errMsg) {
getPushCidCallbacks.forEach(function (callback) {
callback(cid, errMsg);
});
getPushCidCallbacks.length = 0;
}
function getPushClientId(args) {
if (!isPlainObject(args)) {
args = {};
}
var _getApiCallbacks = getApiCallbacks(args),
success = _getApiCallbacks.success,
fail = _getApiCallbacks.fail,
complete = _getApiCallbacks.complete;
var hasSuccess = isFn(success);
var hasFail = isFn(fail);
var hasComplete = isFn(complete);
Promise.resolve().then(function () {
if (typeof enabled === 'undefined') {
enabled = false;
cid = '';
cidErrMsg = 'uniPush is not enabled';
}
getPushCidCallbacks.push(function (cid, errMsg) {
var res;
if (cid) {
res = {
errMsg: 'getPushClientId:ok',
cid: cid
};
hasSuccess && success(res);
} else {
res = {
errMsg: 'getPushClientId:fail' + (errMsg ? ' ' + errMsg : '')
};
hasFail && fail(res);
}
hasComplete && complete(res);
});
if (typeof cid !== 'undefined') {
invokeGetPushCidCallbacks(cid, cidErrMsg);
}
});
}
var onPushMessageCallbacks = [];
// 不使用 defineOnApi 实现,是因为 defineOnApi 依赖 UniServiceJSBridge ,该对象目前在小程序上未提供,故简单实现
var onPushMessage = function onPushMessage(fn) {
if (onPushMessageCallbacks.indexOf(fn) === -1) {
onPushMessageCallbacks.push(fn);
}
};
var offPushMessage = function offPushMessage(fn) {
if (!fn) {
onPushMessageCallbacks.length = 0;
} else {
var index = onPushMessageCallbacks.indexOf(fn);
if (index > -1) {
onPushMessageCallbacks.splice(index, 1);
}
}
};
var baseInfo = wx.getAppBaseInfo && wx.getAppBaseInfo();
if (!baseInfo) {
baseInfo = wx.getSystemInfoSync();
}
var host = baseInfo ? baseInfo.host : null;
var shareVideoMessage = host && host.env === 'SAAASDK' ? wx.miniapp.shareVideoMessage : wx.shareVideoMessage;
var api = /*#__PURE__*/Object.freeze({
__proto__: null,
shareVideoMessage: shareVideoMessage,
getPushClientId: getPushClientId,
onPushMessage: onPushMessage,
offPushMessage: offPushMessage,
invokePushCallback: invokePushCallback
});
var mocks = ['__route__', '__wxExparserNodeId__', '__wxWebviewId__'];
function findVmByVueId(vm, vuePid) {
var $children = vm.$children;
// 优先查找直属(反向查找:https://github.com/dcloudio/uni-app/issues/1200)
for (var i = $children.length - 1; i >= 0; i--) {
var childVm = $children[i];
if (childVm.$scope._$vueId === vuePid) {
return childVm;
}
}
// 反向递归查找
var parentVm;
for (var _i = $children.length - 1; _i >= 0; _i--) {
parentVm = findVmByVueId($children[_i], vuePid);
if (parentVm) {
return parentVm;
}
}
}
function initBehavior(options) {
return Behavior(options);
}
function isPage() {
return !!this.route;
}
function initRelation(detail) {
this.triggerEvent('__l', detail);
}
function selectAllComponents(mpInstance, selector, $refs) {
var components = mpInstance.selectAllComponents(selector) || [];
components.forEach(function (component) {
var ref = component.dataset.ref;
$refs[ref] = component.$vm || toSkip(component);
{
if (component.dataset.vueGeneric === 'scoped') {
component.selectAllComponents('.scoped-ref').forEach(function (scopedComponent) {
selectAllComponents(scopedComponent, selector, $refs);
});
}
}
});
}
function syncRefs(refs, newRefs) {
var oldKeys = (0, _construct2.default)(Set, (0, _toConsumableArray2.default)(Object.keys(refs)));
var newKeys = Object.keys(newRefs);
newKeys.forEach(function (key) {
var oldValue = refs[key];
var newValue = newRefs[key];
if (Array.isArray(oldValue) && Array.isArray(newValue) && oldValue.length === newValue.length && newValue.every(function (value) {
return oldValue.includes(value);
})) {
return;
}
refs[key] = newValue;
oldKeys.delete(key);
});
oldKeys.forEach(function (key) {
delete refs[key];
});
return refs;
}
function initRefs(vm) {
var mpInstance = vm.$scope;
var refs = {};
Object.defineProperty(vm, '$refs', {
get: function get() {
var $refs = {};
selectAllComponents(mpInstance, '.vue-ref', $refs);
// TODO 暂不考虑 for 中的 scoped
var forComponents = mpInstance.selectAllComponents('.vue-ref-in-for') || [];
forComponents.forEach(function (component) {
var ref = component.dataset.ref;
if (!$refs[ref]) {
$refs[ref] = [];
}
$refs[ref].push(component.$vm || toSkip(component));
});
return syncRefs(refs, $refs);
}
});
}
function handleLink(event) {
var _ref3 = event.detail || event.value,
vuePid = _ref3.vuePid,
vueOptions = _ref3.vueOptions; // detail 是微信,value 是百度(dipatch)
var parentVm;
if (vuePid) {
parentVm = findVmByVueId(this.$vm, vuePid);
}
if (!parentVm) {
parentVm = this.$vm;
}
vueOptions.parent = parentVm;
}
function markMPComponent(component) {
// 在 Vue 中标记为小程序组件
var IS_MP = '__v_isMPComponent';
Object.defineProperty(component, IS_MP, {
configurable: true,
enumerable: false,
value: true
});
return component;
}
function toSkip(obj) {
var OB = '__ob__';
var SKIP = '__v_skip';
if (isObject(obj) && Object.isExtensible(obj)) {
// 避免被 @vue/composition-api 观测
Object.defineProperty(obj, OB, {
configurable: true,
enumerable: false,
value: (0, _defineProperty2.default)({}, SKIP, true)
});
}
return obj;
}
var WORKLET_RE = /_(.*)_worklet_factory_/;
function initWorkletMethods(mpMethods, vueMethods) {
if (vueMethods) {
Object.keys(vueMethods).forEach(function (name) {
var matches = name.match(WORKLET_RE);
if (matches) {
var workletName = matches[1];
mpMethods[name] = vueMethods[name];
mpMethods[workletName] = vueMethods[workletName];
}
});
}
}
var MPPage = Page;
var MPComponent = Component;
var customizeRE = /:/g;
var customize = cached(function (str) {
return camelize(str.replace(customizeRE, '-'));
});
function initTriggerEvent(mpInstance) {
var oldTriggerEvent = mpInstance.triggerEvent;
var newTriggerEvent = function newTriggerEvent(event) {
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
// 事件名统一转驼峰格式,仅处理:当前组件为 vue 组件、当前组件为 vue 组件子组件
if (this.$vm || this.dataset && this.dataset.comType) {
event = customize(event);
} else {
// 针对微信/QQ小程序单独补充驼峰格式事件,以兼容历史项目
var newEvent = customize(event);
if (newEvent !== event) {
oldTriggerEvent.apply(this, [newEvent].concat(args));
}
}
return oldTriggerEvent.apply(this, [event].concat(args));
};
try {
// 京东小程序 triggerEvent 为只读
mpInstance.triggerEvent = newTriggerEvent;
} catch (error) {
mpInstance._triggerEvent = newTriggerEvent;
}
}
function initHook(name, options, isComponent) {
var oldHook = options[name];
options[name] = function () {
markMPComponent(this);
initTriggerEvent(this);
if (oldHook) {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return oldHook.apply(this, args);
}
};
}
if (!MPPage.__$wrappered) {
MPPage.__$wrappered = true;
Page = function Page() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
initHook('onLoad', options);
return MPPage(options);
};
Page.after = MPPage.after;
Component = function Component() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
initHook('created', options);
return MPComponent(options);
};
}
var PAGE_EVENT_HOOKS = ['onPullDownRefresh', 'onReachBottom', 'onAddToFavorites', 'onShareTimeline', 'onShareAppMessage', 'onPageScroll', 'onResize', 'onTabItemTap'];
function initMocks(vm, mocks) {
var mpInstance = vm.$mp[vm.mpType];
mocks.forEach(function (mock) {
if (hasOwn(mpInstance, mock)) {
vm[mock] = mpInstance[mock];
}
});
}
function hasHook(hook, vueOptions) {
if (!vueOptions) {
return true;
}
if (_vue.default.options && Array.isArray(_vue.default.options[hook])) {
return true;
}
vueOptions = vueOptions.default || vueOptions;
if (isFn(vueOptions)) {
if (isFn(vueOptions.extendOptions[hook])) {
return true;
}
if (vueOptions.super && vueOptions.super.options && Array.isArray(vueOptions.super.options[hook])) {
return true;
}
return false;
}
if (isFn(vueOptions[hook]) || Array.isArray(vueOptions[hook])) {
return true;
}
var mixins = vueOptions.mixins;
if (Array.isArray(mixins)) {
return !!mixins.find(function (mixin) {
return hasHook(hook, mixin);
});
}
}
function initHooks(mpOptions, hooks, vueOptions) {
hooks.forEach(function (hook) {
if (hasHook(hook, vueOptions)) {
mpOptions[hook] = function (args) {
return this.$vm && this.$vm.__call_hook(hook, args);
};
}
});
}
function initUnknownHooks(mpOptions, vueOptions) {
var excludes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
findHooks(vueOptions).forEach(function (hook) {
return initHook$1(mpOptions, hook, excludes);
});
}
function findHooks(vueOptions) {
var hooks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
if (vueOptions) {
Object.keys(vueOptions).forEach(function (name) {
if (name.indexOf('on') === 0 && isFn(vueOptions[name])) {
hooks.push(name);
}
});
}
return hooks;
}
function initHook$1(mpOptions, hook, excludes) {
if (excludes.indexOf(hook) === -1 && !hasOwn(mpOptions, hook)) {
mpOptions[hook] = function (args) {
return this.$vm && this.$vm.__call_hook(hook, args);
};
}
}
function initVueComponent(Vue, vueOptions) {
vueOptions = vueOptions.default || vueOptions;
var VueComponent;
if (isFn(vueOptions)) {
VueComponent = vueOptions;
} else {
VueComponent = Vue.extend(vueOptions);
}
vueOptions = VueComponent.options;
return [VueComponent, vueOptions];
}
function initSlots(vm, vueSlots) {
if (Array.isArray(vueSlots) && vueSlots.length) {
var $slots = Object.create(null);
vueSlots.forEach(function (slotName) {
$slots[slotName] = true;
});
vm.$scopedSlots = vm.$slots = $slots;
}
}
function initVueIds(vueIds, mpInstance) {
vueIds = (vueIds || '').split(',');
var len = vueIds.length;
if (len === 1) {
mpInstance._$vueId = vueIds[0];
} else if (len === 2) {
mpInstance._$vueId = vueIds[0];
mpInstance._$vuePid = vueIds[1];
}
}
function initData(vueOptions, context) {
var data = vueOptions.data || {};
var methods = vueOptions.methods || {};
if (typeof data === 'function') {
try {
data = data.call(context); // 支持 Vue.prototype 上挂的数据
} catch (e) {
if (Object({"VUE_APP_DARK_MODE":"false","VUE_APP_NAME":"daoyou","VUE_APP_PLATFORM":"mp-weixin","NODE_ENV":"development","BASE_URL":"/"}).VUE_APP_DEBUG) {
console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data);
}
}
} else {
try {
// 对 data 格式化
data = JSON.parse(JSON.stringify(data));
} catch (e) {}
}
if (!isPlainObject(data)) {
data = {};
}
Object.keys(methods).forEach(function (methodName) {
if (context.__lifecycle_hooks__.indexOf(methodName) === -1 && !hasOwn(data, methodName)) {
data[methodName] = methods[methodName];
}
});
return data;
}
var PROP_TYPES = [String, Number, Boolean, Object, Array, null];
function createObserver(name) {
return function observer(newVal, oldVal) {
if (this.$vm) {
this.$vm[name] = newVal; // 为了触发其他非 render watcher
}
};
}
function initBehaviors(vueOptions, initBehavior) {
var vueBehaviors = vueOptions.behaviors;
var vueExtends = vueOptions.extends;
var vueMixins = vueOptions.mixins;
var vueProps = vueOptions.props;
if (!vueProps) {
vueOptions.props = vueProps = [];
}
var behaviors = [];
if (Array.isArray(vueBehaviors)) {
vueBehaviors.forEach(function (behavior) {
behaviors.push(behavior.replace('uni://', "wx".concat("://")));
if (behavior === 'uni://form-field') {
if (Array.isArray(vueProps)) {
vueProps.push('name');
vueProps.push('value');
} else {
vueProps.name = {
type: String,
default: ''
};
vueProps.value = {
type: [String, Number, Boolean, Array, Object, Date],
default: ''
};
}
}
});
}
if (isPlainObject(vueExtends) && vueExtends.props) {
behaviors.push(initBehavior({
properties: initProperties(vueExtends.props, true)
}));
}
if (Array.isArray(vueMixins)) {
vueMixins.forEach(function (vueMixin) {
if (isPlainObject(vueMixin) && vueMixin.props) {
behaviors.push(initBehavior({
properties: initProperties(vueMixin.props, true)
}));
}
});
}
return behaviors;
}
function parsePropType(key, type, defaultValue, file) {
// [String]=>String
if (Array.isArray(type) && type.length === 1) {
return type[0];
}
return type;
}
function initProperties(props) {
var isBehavior = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var file = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
var options = arguments.length > 3 ? arguments[3] : undefined;
var properties = {};
if (!isBehavior) {
properties.vueId = {
type: String,
value: ''
};
{
if (options.virtualHost) {
properties.virtualHostStyle = {
type: null,
value: ''
};
properties.virtualHostClass = {
type: null,
value: ''
};
}
}
// scopedSlotsCompiler auto
properties.scopedSlotsCompiler = {
type: String,
value: ''
};
properties.vueSlots = {
// 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots
type: null,
value: [],
observer: function observer(newVal, oldVal) {
var $slots = Object.create(null);
newVal.forEach(function (slotName) {
$slots[slotName] = true;
});
this.setData({
$slots: $slots
});
}
};
}
if (Array.isArray(props)) {
// ['title']
props.forEach(function (key) {
properties[key] = {
type: null,
observer: createObserver(key)
};
});
} else if (isPlainObject(props)) {
// {title:{type:String,default:''},content:String}
Object.keys(props).forEach(function (key) {
var opts = props[key];
if (isPlainObject(opts)) {
// title:{type:String,default:''}
var value = opts.default;
if (isFn(value)) {
value = value();
}
opts.type = parsePropType(key, opts.type);
properties[key] = {
type: PROP_TYPES.indexOf(opts.type) !== -1 ? opts.type : null,
value: value,
observer: createObserver(key)
};
} else {
// content:String
var type = parsePropType(key, opts);
properties[key] = {
type: PROP_TYPES.indexOf(type) !== -1 ? type : null,
observer: createObserver(key)
};
}
});
}
return properties;
}
function wrapper$1(event) {
// TODO 又得兼容 mpvue 的 mp 对象
try {
event.mp = JSON.parse(JSON.stringify(event));
} catch (e) {}
event.stopPropagation = noop;
event.preventDefault = noop;
event.target = event.target || {};
if (!hasOwn(event, 'detail')) {
event.detail = {};
}
if (hasOwn(event, 'markerId')) {
event.detail = (0, _typeof2.default)(event.detail) === 'object' ? event.detail : {};
event.detail.markerId = event.markerId;
}
if (isPlainObject(event.detail)) {
event.target = Object.assign({}, event.target, event.detail);
}
return event;
}
function getExtraValue(vm, dataPathsArray) {
var context = vm;
dataPathsArray.forEach(function (dataPathArray) {
var dataPath = dataPathArray[0];
var value = dataPathArray[2];
if (dataPath || typeof value !== 'undefined') {
// ['','',index,'disable']
var propPath = dataPathArray[1];
var valuePath = dataPathArray[3];
var vFor;
if (Number.isInteger(dataPath)) {
vFor = dataPath;
} else if (!dataPath) {
vFor = context;
} else if (typeof dataPath === 'string' && dataPath) {
if (dataPath.indexOf('#s#') === 0) {
vFor = dataPath.substr(3);
} else {
vFor = vm.__get_value(dataPath, context);
}
}
if (Number.isInteger(vFor)) {
context = value;
} else if (!propPath) {
context = vFor[value];
} else {
if (Array.isArray(vFor)) {
context = vFor.find(function (vForItem) {
return vm.__get_value(propPath, vForItem) === value;
});
} else if (isPlainObject(vFor)) {
context = Object.keys(vFor).find(function (vForKey) {
return vm.__get_value(propPath, vFor[vForKey]) === value;
});
} else {
console.error('v-for 暂不支持循环数据:', vFor);
}
}
if (valuePath) {
context = vm.__get_value(valuePath, context);
}
}
});
return context;
}
function processEventExtra(vm, extra, event, __args__) {
var extraObj = {};
if (Array.isArray(extra) && extra.length) {
/**
*[
* ['data.items', 'data.id', item.data.id],
* ['metas', 'id', meta.id]
*],
*[
* ['data.items', 'data.id', item.data.id],
* ['metas', 'id', meta.id]
*],
*'test'
*/
extra.forEach(function (dataPath, index) {
if (typeof dataPath === 'string') {
if (!dataPath) {
// model,prop.sync
extraObj['$' + index] = vm;
} else {
if (dataPath === '$event') {
// $event
extraObj['$' + index] = event;
} else if (dataPath === 'arguments') {
extraObj['$' + index] = event.detail ? event.detail.__args__ || __args__ : __args__;
} else if (dataPath.indexOf('$event.') === 0) {
// $event.target.value
extraObj['$' + index] = vm.__get_value(dataPath.replace('$event.', ''), event);
} else {
extraObj['$' + index] = vm.__get_value(dataPath);
}
}
} else {
extraObj['$' + index] = getExtraValue(vm, dataPath);
}
});
}
return extraObj;
}
function getObjByArray(arr) {
var obj = {};
for (var i = 1; i < arr.length; i++) {
var element = arr[i];
obj[element[0]] = element[1];
}
return obj;
}
function processEventArgs(vm, event) {
var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var extra = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
var isCustom = arguments.length > 4 ? arguments[4] : undefined;
var methodName = arguments.length > 5 ? arguments[5] : undefined;
var isCustomMPEvent = false; // wxcomponent 组件,传递原始 event 对象
// fixed 用户直接触发 mpInstance.triggerEvent
var __args__ = isPlainObject(event.detail) ? event.detail.__args__ || [event.detail] : [event.detail];
if (isCustom) {
// 自定义事件
isCustomMPEvent = event.currentTarget && event.currentTarget.dataset && event.currentTarget.dataset.comType === 'wx';
if (!args.length) {
// 无参数,直接传入 event 或 detail 数组
if (isCustomMPEvent) {
return [event];
}
return __args__;
}
}
var extraObj = processEventExtra(vm, extra, event, __args__);
var ret = [];
args.forEach(function (arg) {
if (arg === '$event') {
if (methodName === '__set_model' && !isCustom) {
// input v-model value
ret.push(event.target.value);
} else {
if (isCustom && !isCustomMPEvent) {
ret.push(__args__[0]);
} else {
// wxcomponent 组件或内置组件
ret.push(event);
}
}
} else {
if (Array.isArray(arg) && arg[0] === 'o') {
ret.push(getObjByArray(arg));
} else if (typeof arg === 'string' && hasOwn(extraObj, arg)) {
ret.push(extraObj[arg]);
} else {
ret.push(arg);
}
}
});
return ret;
}
var ONCE = '~';
var CUSTOM = '^';
function isMatchEventType(eventType, optType) {
return eventType === optType || optType === 'regionchange' && (eventType === 'begin' || eventType === 'end');
}
function getContextVm(vm) {
var $parent = vm.$parent;
// 父组件是 scoped slots 或者其他自定义组件时继续查找
while ($parent && $parent.$parent && ($parent.$options.generic || $parent.$parent.$options.generic || $parent.$scope._$vuePid)) {
$parent = $parent.$parent;
}
return $parent && $parent.$parent;
}
function handleEvent(event) {
var _this2 = this;
event = wrapper$1(event);
// [['tap',[['handle',[1,2,a]],['handle1',[1,2,a]]]]]
var dataset = (event.currentTarget || event.target).dataset;
if (!dataset) {
return console.warn('事件信息不存在');
}
var eventOpts = dataset.eventOpts || dataset['event-opts']; // 支付宝 web-view 组件 dataset 非驼峰
if (!eventOpts) {
return console.warn('事件信息不存在');
}
// [['handle',[1,2,a]],['handle1',[1,2,a]]]
var eventType = event.type;
var ret = [];
eventOpts.forEach(function (eventOpt) {
var type = eventOpt[0];
var eventsArray = eventOpt[1];
var isCustom = type.charAt(0) === CUSTOM;
type = isCustom ? type.slice(1) : type;
var isOnce = type.charAt(0) === ONCE;
type = isOnce ? type.slice(1) : type;
if (eventsArray && isMatchEventType(eventType, type)) {
eventsArray.forEach(function (eventArray) {
var methodName = eventArray[0];
if (methodName) {
var handlerCtx = _this2.$vm;
if (handlerCtx.$options.generic) {
// mp-weixin,mp-toutiao 抽象节点模拟 scoped slots
handlerCtx = getContextVm(handlerCtx) || handlerCtx;
}
if (methodName === '$emit') {
handlerCtx.$emit.apply(handlerCtx, processEventArgs(_this2.$vm, event, eventArray[1], eventArray[2], isCustom, methodName));
return;
}
var handler = handlerCtx[methodName];
if (!isFn(handler)) {
var _type = _this2.$vm.mpType === 'page' ? 'Page' : 'Component';
var path = _this2.route || _this2.is;
throw new Error("".concat(_type, " \"").concat(path, "\" does not have a method \"").concat(methodName, "\""));
}
if (isOnce) {
if (handler.once) {
return;
}
handler.once = true;
}
var params = processEventArgs(_this2.$vm, event, eventArray[1], eventArray[2], isCustom, methodName);
params = Array.isArray(params) ? params : [];
// 参数尾部增加原始事件对象用于复杂表达式内获取额外数据
if (/=\s*\S+\.eventParams\s*\|\|\s*\S+\[['"]event-params['"]\]/.test(handler.toString())) {
// eslint-disable-next-line no-sparse-arrays
params = params.concat([,,,,,,,,,, event]);
}
ret.push(handler.apply(handlerCtx, params));
}
});
}
});
if (eventType === 'input' && ret.length === 1 && typeof ret[0] !== 'undefined') {
return ret[0];
}
}
var eventChannels = {};
function getEventChannel(id) {
var eventChannel = eventChannels[id];
delete eventChannels[id];
return eventChannel;
}
var hooks = ['onShow', 'onHide', 'onError', 'onPageNotFound', 'onThemeChange', 'onUnhandledRejection'];
function initEventChannel() {
_vue.default.prototype.getOpenerEventChannel = function () {
// 微信小程序使用自身getOpenerEventChannel
{
return this.$scope.getOpenerEventChannel();
}
};
var callHook = _vue.default.prototype.__call_hook;
_vue.default.prototype.__call_hook = function (hook, args) {
if (hook === 'onLoad' && args && args.__id__) {
this.__eventChannel__ = getEventChannel(args.__id__);
delete args.__id__;
}
return callHook.call(this, hook, args);
};
}
function initScopedSlotsParams() {
var center = {};
var parents = {};
function currentId(fn) {
var vueIds = this.$options.propsData.vueId;
if (vueIds) {
var vueId = vueIds.split(',')[0];
fn(vueId);
}
}
_vue.default.prototype.$hasSSP = function (vueId) {
var slot = center[vueId];
if (!slot) {
parents[vueId] = this;
this.$on('hook:destroyed', function () {
delete parents[vueId];
});
}
return slot;
};
_vue.default.prototype.$getSSP = function (vueId, name, needAll) {
var slot = center[vueId];
if (slot) {
var params = slot[name] || [];
if (needAll) {
return params;
}
return params[0];
}
};
_vue.default.prototype.$setSSP = function (name, value) {
var index = 0;
currentId.call(this, function (vueId) {
var slot = center[vueId];
var params = slot[name] = slot[name] || [];
params.push(value);
index = params.length - 1;
});
return index;
};
_vue.default.prototype.$initSSP = function () {
currentId.call(this, function (vueId) {
center[vueId] = {};
});
};
_vue.default.prototype.$callSSP = function () {
currentId.call(this, function (vueId) {
if (parents[vueId]) {
parents[vueId].$forceUpdate();
}
});
};
_vue.default.mixin({
destroyed: function destroyed() {
var propsData = this.$options.propsData;
var vueId = propsData && propsData.vueId;
if (vueId) {
delete center[vueId];
delete parents[vueId];
}
}
});
}
function parseBaseApp(vm, _ref4) {
var mocks = _ref4.mocks,
initRefs = _ref4.initRefs;
initEventChannel();
{
initScopedSlotsParams();
}
if (vm.$options.store) {
_vue.default.prototype.$store = vm.$options.store;
}
uniIdMixin(_vue.default);
_vue.default.prototype.mpHost = "mp-weixin";
_vue.default.mixin({
beforeCreate: function beforeCreate() {
if (!this.$options.mpType) {
return;
}
this.mpType = this.$options.mpType;
this.$mp = (0, _defineProperty2.default)({
data: {}
}, this.mpType, this.$options.mpInstance);
this.$scope = this.$options.mpInstance;
delete this.$options.mpType;
delete this.$options.mpInstance;
if (this.mpType === 'page' && typeof getApp === 'function') {
// hack vue-i18n
var app = getApp();
if (app.$vm && app.$vm.$i18n) {
this._i18n = app.$vm.$i18n;
}
}
if (this.mpType !== 'app') {
initRefs(this);
initMocks(this, mocks);
}
}
});
var appOptions = {
onLaunch: function onLaunch(args) {
if (this.$vm) {
// 已经初始化过了,主要是为了百度,百度 onShow 在 onLaunch 之前
return;
}
{
if (wx.canIUse && !wx.canIUse('nextTick')) {
// 事实 上2.2.3 即可,简单使用 2.3.0 的 nextTick 判断
console.error('当前微信基础库版本过低,请将 微信开发者工具-详情-项目设置-调试基础库版本 更换为`2.3.0`以上');
}
}
this.$vm = vm;
this.$vm.$mp = {
app: this
};
this.$vm.$scope = this;
// vm 上也挂载 globalData
this.$vm.globalData = this.globalData;
this.$vm._isMounted = true;
this.$vm.__call_hook('mounted', args);
this.$vm.__call_hook('onLaunch', args);
}
};
// 兼容旧版本 globalData
appOptions.globalData = vm.$options.globalData || {};
// 将 methods 中的方法挂在 getApp() 中
var methods = vm.$options.methods;
if (methods) {
Object.keys(methods).forEach(function (name) {
appOptions[name] = methods[name];
});
}
initAppLocale(_vue.default, vm, normalizeLocale(wx.getSystemInfoSync().language) || LOCALE_EN);
initHooks(appOptions, hooks);
initUnknownHooks(appOptions, vm.$options);
return appOptions;
}
function parseApp(vm) {
return parseBaseApp(vm, {
mocks: mocks,
initRefs: initRefs
});
}
function createApp(vm) {
App(parseApp(vm));
return vm;
}
var encodeReserveRE = /[!'()*]/g;
var encodeReserveReplacer = function encodeReserveReplacer(c) {
return '%' + c.charCodeAt(0).toString(16);
};
var commaRE = /%2C/g;
// fixed encodeURIComponent which is more conformant to RFC3986:
// - escapes [!'()*]
// - preserve commas
var encode = function encode(str) {
return encodeURIComponent(str).replace(encodeReserveRE, encodeReserveReplacer).replace(commaRE, ',');
};
function stringifyQuery(obj) {
var encodeStr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : encode;
var res = obj ? Object.keys(obj).map(function (key) {
var val = obj[key];
if (val === undefined) {
return '';
}
if (val === null) {
return encodeStr(key);
}
if (Array.isArray(val)) {
var result = [];
val.forEach(function (val2) {
if (val2 === undefined) {
return;
}
if (val2 === null) {
result.push(encodeStr(key));
} else {
result.push(encodeStr(key) + '=' + encodeStr(val2));
}
});
return result.join('&');
}
return encodeStr(key) + '=' + encodeStr(val);
}).filter(function (x) {
return x.length > 0;
}).join('&') : null;
return res ? "?".concat(res) : '';
}
function parseBaseComponent(vueComponentOptions) {
var _ref5 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
isPage = _ref5.isPage,
initRelation = _ref5.initRelation;
var needVueOptions = arguments.length > 2 ? arguments[2] : undefined;
var _initVueComponent = initVueComponent(_vue.default, vueComponentOptions),
_initVueComponent2 = (0, _slicedToArray2.default)(_initVueComponent, 2),
VueComponent = _initVueComponent2[0],
vueOptions = _initVueComponent2[1];
var options = _objectSpread({
multipleSlots: true,
// styleIsolation: 'apply-shared',
addGlobalClass: true
}, vueOptions.options || {});
{
// 微信 multipleSlots 部分情况有 bug,导致内容顺序错乱 如 u-list,提供覆盖选项
if (vueOptions['mp-weixin'] && vueOptions['mp-weixin'].options) {
Object.assign(options, vueOptions['mp-weixin'].options);
}
}
var componentOptions = {
options: options,
data: initData(vueOptions, _vue.default.prototype),
behaviors: initBehaviors(vueOptions, initBehavior),
properties: initProperties(vueOptions.props, false, vueOptions.__file, options),
lifetimes: {
attached: function attached() {
var properties = this.properties;
var options = {
mpType: isPage.call(this) ? 'page' : 'component',
mpInstance: this,
propsData: properties
};
initVueIds(properties.vueId, this);
// 处理父子关系
initRelation.call(this, {
vuePid: this._$vuePid,
vueOptions: options
});
// 初始化 vue 实例
this.$vm = new VueComponent(options);
// 处理$slots,$scopedSlots(暂不支持动态变化$slots)
initSlots(this.$vm, properties.vueSlots);
// 触发首次 setData
this.$vm.$mount();
},
ready: function ready() {
// 当组件 props 默认值为 true,初始化时传入 false 会导致 created,ready 触发, 但 attached 不触发
// https://developers.weixin.qq.com/community/develop/doc/00066ae2844cc0f8eb883e2a557800
if (this.$vm) {
this.$vm._isMounted = true;
this.$vm.__call_hook('mounted');
this.$vm.__call_hook('onReady');
}
},
detached: function detached() {
this.$vm && this.$vm.$destroy();
}
},
pageLifetimes: {
show: function show(args) {
this.$vm && this.$vm.__call_hook('onPageShow', args);
},
hide: function hide() {
this.$vm && this.$vm.__call_hook('onPageHide');
},
resize: function resize(size) {
this.$vm && this.$vm.__call_hook('onPageResize', size);
}
},
methods: {
__l: handleLink,
__e: handleEvent
}
};
// externalClasses
if (vueOptions.externalClasses) {
componentOptions.externalClasses = vueOptions.externalClasses;
}
if (Array.isArray(vueOptions.wxsCallMethods)) {
vueOptions.wxsCallMethods.forEach(function (callMethod) {
componentOptions.methods[callMethod] = function (args) {
return this.$vm[callMethod](args);
};
});
}
if (needVueOptions) {
return [componentOptions, vueOptions, VueComponent];
}
if (isPage) {
return componentOptions;
}
return [componentOptions, VueComponent];
}
function parseComponent(vueComponentOptions, needVueOptions) {
return parseBaseComponent(vueComponentOptions, {
isPage: isPage,
initRelation: initRelation
}, needVueOptions);
}
var hooks$1 = ['onShow', 'onHide', 'onUnload'];
hooks$1.push.apply(hooks$1, PAGE_EVENT_HOOKS);
function parseBasePage(vuePageOptions) {
var _parseComponent = parseComponent(vuePageOptions, true),
_parseComponent2 = (0, _slicedToArray2.default)(_parseComponent, 2),
pageOptions = _parseComponent2[0],
vueOptions = _parseComponent2[1];
initHooks(pageOptions.methods, hooks$1, vueOptions);
pageOptions.methods.onLoad = function (query) {
this.options = query;
var copyQuery = Object.assign({}, query);
delete copyQuery.__id__;
this.$page = {
fullPath: '/' + (this.route || this.is) + stringifyQuery(copyQuery)
};
this.$vm.$mp.query = query; // 兼容 mpvue
this.$vm.__call_hook('onLoad', query);
};
{
initUnknownHooks(pageOptions.methods, vuePageOptions, ['onReady']);
}
{
initWorkletMethods(pageOptions.methods, vueOptions.methods);
}
return pageOptions;
}
function parsePage(vuePageOptions) {
return parseBasePage(vuePageOptions);
}
function createPage(vuePageOptions) {
{
return Component(parsePage(vuePageOptions));
}
}
function createComponent(vueOptions) {
{
return Component(parseComponent(vueOptions));
}
}
function createSubpackageApp(vm) {
var appOptions = parseApp(vm);
var app = getApp({
allowDefault: true
});
vm.$scope = app;
var globalData = app.globalData;
if (globalData) {
Object.keys(appOptions.globalData).forEach(function (name) {
if (!hasOwn(globalData, name)) {
globalData[name] = appOptions.globalData[name];
}
});
}
Object.keys(appOptions).forEach(function (name) {
if (!hasOwn(app, name)) {
app[name] = appOptions[name];
}
});
if (isFn(appOptions.onShow) && wx.onAppShow) {
wx.onAppShow(function () {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
vm.__call_hook('onShow', args);
});
}
if (isFn(appOptions.onHide) && wx.onAppHide) {
wx.onAppHide(function () {
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
vm.__call_hook('onHide', args);
});
}
if (isFn(appOptions.onLaunch)) {
var args = wx.getLaunchOptionsSync && wx.getLaunchOptionsSync();
vm.__call_hook('onLaunch', args);
}
return vm;
}
function createPlugin(vm) {
var appOptions = parseApp(vm);
if (isFn(appOptions.onShow) && wx.onAppShow) {
wx.onAppShow(function () {
for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
args[_key7] = arguments[_key7];
}
vm.__call_hook('onShow', args);
});
}
if (isFn(appOptions.onHide) && wx.onAppHide) {
wx.onAppHide(function () {
for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
args[_key8] = arguments[_key8];
}
vm.__call_hook('onHide', args);
});
}
if (isFn(appOptions.onLaunch)) {
var args = wx.getLaunchOptionsSync && wx.getLaunchOptionsSync();
vm.__call_hook('onLaunch', args);
}
return vm;
}
todos.forEach(function (todoApi) {
protocols[todoApi] = false;
});
canIUses.forEach(function (canIUseApi) {
var apiName = protocols[canIUseApi] && protocols[canIUseApi].name ? protocols[canIUseApi].name : canIUseApi;
if (!wx.canIUse(apiName)) {
protocols[canIUseApi] = false;
}
});
var uni = {};
if (typeof Proxy !== 'undefined' && "mp-weixin" !== 'app-plus') {
uni = new Proxy({}, {
get: function get(target, name) {
if (hasOwn(target, name)) {
return target[name];
}
if (baseApi[name]) {
return baseApi[name];
}
if (api[name]) {
return promisify(name, api[name]);
}
{
if (extraApi[name]) {
return promisify(name, extraApi[name]);
}
if (todoApis[name]) {
return promisify(name, todoApis[name]);
}
}
if (eventApi[name]) {
return eventApi[name];
}
return promisify(name, wrapper(name, wx[name]));
},
set: function set(target, name, value) {
target[name] = value;
return true;
}
});
} else {
Object.keys(baseApi).forEach(function (name) {
uni[name] = baseApi[name];
});
{
Object.keys(todoApis).forEach(function (name) {
uni[name] = promisify(name, todoApis[name]);
});
Object.keys(extraApi).forEach(function (name) {
uni[name] = promisify(name, extraApi[name]);
});
}
Object.keys(eventApi).forEach(function (name) {
uni[name] = eventApi[name];
});
Object.keys(api).forEach(function (name) {
uni[name] = promisify(name, api[name]);
});
Object.keys(wx).forEach(function (name) {
if (hasOwn(wx, name) || hasOwn(protocols, name)) {
uni[name] = promisify(name, wrapper(name, wx[name]));
}
});
}
wx.createApp = createApp;
wx.createPage = createPage;
wx.createComponent = createComponent;
wx.createSubpackageApp = createSubpackageApp;
wx.createPlugin = createPlugin;
var uni$1 = uni;
var _default = uni$1;
exports.default = _default;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/wx.js */ 1)["default"], __webpack_require__(/*! ./../../../webpack/buildin/global.js */ 3)))
/***/ }),
/* 3 */
/*!***********************************!*\
!*** (webpack)/buildin/global.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 4 */
/*!**********************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/interopRequireDefault.js ***!
\**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 5 */
/*!**************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/slicedToArray.js ***!
\**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var arrayWithHoles = __webpack_require__(/*! ./arrayWithHoles.js */ 6);
var iterableToArrayLimit = __webpack_require__(/*! ./iterableToArrayLimit.js */ 7);
var unsupportedIterableToArray = __webpack_require__(/*! ./unsupportedIterableToArray.js */ 8);
var nonIterableRest = __webpack_require__(/*! ./nonIterableRest.js */ 10);
function _slicedToArray(arr, i) {
return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
}
module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 6 */
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/arrayWithHoles.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 7 */
/*!*********************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/iterableToArrayLimit.js ***!
\*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _iterableToArrayLimit(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = !0,
o = !1;
try {
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) return;
f = !1;
} else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {
;
}
} catch (r) {
o = !0, n = r;
} finally {
try {
if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
} finally {
if (o) throw n;
}
}
return a;
}
}
module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 8 */
/*!***************************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js ***!
\***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var arrayLikeToArray = __webpack_require__(/*! ./arrayLikeToArray.js */ 9);
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
}
module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 9 */
/*!*****************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/arrayLikeToArray.js ***!
\*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 10 */
/*!****************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/nonIterableRest.js ***!
\****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 11 */
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/defineProperty.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var toPropertyKey = __webpack_require__(/*! ./toPropertyKey.js */ 12);
function _defineProperty(obj, key, value) {
key = toPropertyKey(key);
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 12 */
/*!**************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/toPropertyKey.js ***!
\**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var _typeof = __webpack_require__(/*! ./typeof.js */ 13)["default"];
var toPrimitive = __webpack_require__(/*! ./toPrimitive.js */ 14);
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
module.exports = toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 13 */
/*!*******************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/typeof.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _typeof(o) {
"@babel/helpers - typeof";
return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(o);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 14 */
/*!************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/toPrimitive.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var _typeof = __webpack_require__(/*! ./typeof.js */ 13)["default"];
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
module.exports = toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 15 */
/*!**********************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/construct.js ***!
\**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ 16);
var isNativeReflectConstruct = __webpack_require__(/*! ./isNativeReflectConstruct.js */ 17);
function _construct(t, e, r) {
if (isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
var o = [null];
o.push.apply(o, e);
var p = new (t.bind.apply(t, o))();
return r && setPrototypeOf(p, r.prototype), p;
}
module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 16 */
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/setPrototypeOf.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 17 */
/*!*************************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js ***!
\*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _isNativeReflectConstruct() {
try {
var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
} catch (t) {}
return (module.exports = _isNativeReflectConstruct = function _isNativeReflectConstruct() {
return !!t;
}, module.exports.__esModule = true, module.exports["default"] = module.exports)();
}
module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 18 */
/*!******************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/toConsumableArray.js ***!
\******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var arrayWithoutHoles = __webpack_require__(/*! ./arrayWithoutHoles.js */ 19);
var iterableToArray = __webpack_require__(/*! ./iterableToArray.js */ 20);
var unsupportedIterableToArray = __webpack_require__(/*! ./unsupportedIterableToArray.js */ 8);
var nonIterableSpread = __webpack_require__(/*! ./nonIterableSpread.js */ 21);
function _toConsumableArray(arr) {
return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
}
module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 19 */
/*!******************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/arrayWithoutHoles.js ***!
\******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var arrayLikeToArray = __webpack_require__(/*! ./arrayLikeToArray.js */ 9);
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return arrayLikeToArray(arr);
}
module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 20 */
/*!****************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/iterableToArray.js ***!
\****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 21 */
/*!******************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/nonIterableSpread.js ***!
\******************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 22 */
/*!*************************************************************!*\
!*** ./node_modules/@dcloudio/uni-i18n/dist/uni-i18n.es.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(uni, global) {
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ 4);
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LOCALE_ZH_HANT = exports.LOCALE_ZH_HANS = exports.LOCALE_FR = exports.LOCALE_ES = exports.LOCALE_EN = exports.I18n = exports.Formatter = void 0;
exports.compileI18nJsonStr = compileI18nJsonStr;
exports.hasI18nJson = hasI18nJson;
exports.initVueI18n = initVueI18n;
exports.isI18nStr = isI18nStr;
exports.isString = void 0;
exports.normalizeLocale = normalizeLocale;
exports.parseI18nJson = parseI18nJson;
exports.resolveLocale = resolveLocale;
var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ 5));
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ 23));
var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ 24));
var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ 13));
var isObject = function isObject(val) {
return val !== null && (0, _typeof2.default)(val) === 'object';
};
var defaultDelimiters = ['{', '}'];
var BaseFormatter = /*#__PURE__*/function () {
function BaseFormatter() {
(0, _classCallCheck2.default)(this, BaseFormatter);
this._caches = Object.create(null);
}
(0, _createClass2.default)(BaseFormatter, [{
key: "interpolate",
value: function interpolate(message, values) {
var delimiters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultDelimiters;
if (!values) {
return [message];
}
var tokens = this._caches[message];
if (!tokens) {
tokens = parse(message, delimiters);
this._caches[message] = tokens;
}
return compile(tokens, values);
}
}]);
return BaseFormatter;
}();
exports.Formatter = BaseFormatter;
var RE_TOKEN_LIST_VALUE = /^(?:\d)+/;
var RE_TOKEN_NAMED_VALUE = /^(?:\w)+/;
function parse(format, _ref) {
var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
startDelimiter = _ref2[0],
endDelimiter = _ref2[1];
var tokens = [];
var position = 0;
var text = '';
while (position < format.length) {
var char = format[position++];
if (char === startDelimiter) {
if (text) {
tokens.push({
type: 'text',
value: text
});
}
text = '';
var sub = '';
char = format[position++];
while (char !== undefined && char !== endDelimiter) {
sub += char;
char = format[position++];
}
var isClosed = char === endDelimiter;
var type = RE_TOKEN_LIST_VALUE.test(sub) ? 'list' : isClosed && RE_TOKEN_NAMED_VALUE.test(sub) ? 'named' : 'unknown';
tokens.push({
value: sub,
type: type
});
}
// else if (char === '%') {
// // when found rails i18n syntax, skip text capture
// if (format[position] !== '{') {
// text += char
// }
// }
else {
text += char;
}
}
text && tokens.push({
type: 'text',
value: text
});
return tokens;
}
function compile(tokens, values) {
var compiled = [];
var index = 0;
var mode = Array.isArray(values) ? 'list' : isObject(values) ? 'named' : 'unknown';
if (mode === 'unknown') {
return compiled;
}
while (index < tokens.length) {
var token = tokens[index];
switch (token.type) {
case 'text':
compiled.push(token.value);
break;
case 'list':
compiled.push(values[parseInt(token.value, 10)]);
break;
case 'named':
if (mode === 'named') {
compiled.push(values[token.value]);
} else {
if (true) {
console.warn("Type of token '".concat(token.type, "' and format of value '").concat(mode, "' don't match!"));
}
}
break;
case 'unknown':
if (true) {
console.warn("Detect 'unknown' type of token!");
}
break;
}
index++;
}
return compiled;
}
var LOCALE_ZH_HANS = 'zh-Hans';
exports.LOCALE_ZH_HANS = LOCALE_ZH_HANS;
var LOCALE_ZH_HANT = 'zh-Hant';
exports.LOCALE_ZH_HANT = LOCALE_ZH_HANT;
var LOCALE_EN = 'en';
exports.LOCALE_EN = LOCALE_EN;
var LOCALE_FR = 'fr';
exports.LOCALE_FR = LOCALE_FR;
var LOCALE_ES = 'es';
exports.LOCALE_ES = LOCALE_ES;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var hasOwn = function hasOwn(val, key) {
return hasOwnProperty.call(val, key);
};
var defaultFormatter = new BaseFormatter();
function include(str, parts) {
return !!parts.find(function (part) {
return str.indexOf(part) !== -1;
});
}
function startsWith(str, parts) {
return parts.find(function (part) {
return str.indexOf(part) === 0;
});
}
function normalizeLocale(locale, messages) {
if (!locale) {
return;
}
locale = locale.trim().replace(/_/g, '-');
if (messages && messages[locale]) {
return locale;
}
locale = locale.toLowerCase();
if (locale === 'chinese') {
// 支付宝
return LOCALE_ZH_HANS;
}
if (locale.indexOf('zh') === 0) {
if (locale.indexOf('-hans') > -1) {
return LOCALE_ZH_HANS;
}
if (locale.indexOf('-hant') > -1) {
return LOCALE_ZH_HANT;
}
if (include(locale, ['-tw', '-hk', '-mo', '-cht'])) {
return LOCALE_ZH_HANT;
}
return LOCALE_ZH_HANS;
}
var locales = [LOCALE_EN, LOCALE_FR, LOCALE_ES];
if (messages && Object.keys(messages).length > 0) {
locales = Object.keys(messages);
}
var lang = startsWith(locale, locales);
if (lang) {
return lang;
}
}
var I18n = /*#__PURE__*/function () {
function I18n(_ref3) {
var locale = _ref3.locale,
fallbackLocale = _ref3.fallbackLocale,
messages = _ref3.messages,
watcher = _ref3.watcher,
formater = _ref3.formater;
(0, _classCallCheck2.default)(this, I18n);
this.locale = LOCALE_EN;
this.fallbackLocale = LOCALE_EN;
this.message = {};
this.messages = {};
this.watchers = [];
if (fallbackLocale) {
this.fallbackLocale = fallbackLocale;
}
this.formater = formater || defaultFormatter;
this.messages = messages || {};
this.setLocale(locale || LOCALE_EN);
if (watcher) {
this.watchLocale(watcher);
}
}
(0, _createClass2.default)(I18n, [{
key: "setLocale",
value: function setLocale(locale) {
var _this = this;
var oldLocale = this.locale;
this.locale = normalizeLocale(locale, this.messages) || this.fallbackLocale;
if (!this.messages[this.locale]) {
// 可能初始化时不存在
this.messages[this.locale] = {};
}
this.message = this.messages[this.locale];
// 仅发生变化时,通知
if (oldLocale !== this.locale) {
this.watchers.forEach(function (watcher) {
watcher(_this.locale, oldLocale);
});
}
}
}, {
key: "getLocale",
value: function getLocale() {
return this.locale;
}
}, {
key: "watchLocale",
value: function watchLocale(fn) {
var _this2 = this;
var index = this.watchers.push(fn) - 1;
return function () {
_this2.watchers.splice(index, 1);
};
}
}, {
key: "add",
value: function add(locale, message) {
var override = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var curMessages = this.messages[locale];
if (curMessages) {
if (override) {
Object.assign(curMessages, message);
} else {
Object.keys(message).forEach(function (key) {
if (!hasOwn(curMessages, key)) {
curMessages[key] = message[key];
}
});
}
} else {
this.messages[locale] = message;
}
}
}, {
key: "f",
value: function f(message, values, delimiters) {
return this.formater.interpolate(message, values, delimiters).join('');
}
}, {
key: "t",
value: function t(key, locale, values) {
var message = this.message;
if (typeof locale === 'string') {
locale = normalizeLocale(locale, this.messages);
locale && (message = this.messages[locale]);
} else {
values = locale;
}
if (!hasOwn(message, key)) {
console.warn("Cannot translate the value of keypath ".concat(key, ". Use the value of keypath as default."));
return key;
}
return this.formater.interpolate(message[key], values).join('');
}
}]);
return I18n;
}();
exports.I18n = I18n;
function watchAppLocale(appVm, i18n) {
// 需要保证 watch 的触发在组件渲染之前
if (appVm.$watchLocale) {
// vue2
appVm.$watchLocale(function (newLocale) {
i18n.setLocale(newLocale);
});
} else {
appVm.$watch(function () {
return appVm.$locale;
}, function (newLocale) {
i18n.setLocale(newLocale);
});
}
}
function getDefaultLocale() {
if (typeof uni !== 'undefined' && uni.getLocale) {
return uni.getLocale();
}
// 小程序平台,uni 和 uni-i18n 互相引用,导致访问不到 uni,故在 global 上挂了 getLocale
if (typeof global !== 'undefined' && global.getLocale) {
return global.getLocale();
}
return LOCALE_EN;
}
function initVueI18n(locale) {
var messages = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var fallbackLocale = arguments.length > 2 ? arguments[2] : undefined;
var watcher = arguments.length > 3 ? arguments[3] : undefined;
// 兼容旧版本入参
if (typeof locale !== 'string') {
var _ref4 = [messages, locale];
locale = _ref4[0];
messages = _ref4[1];
}
if (typeof locale !== 'string') {
// 因为小程序平台,uni-i18n 和 uni 互相引用,导致此时访问 uni 时,为 undefined
locale = getDefaultLocale();
}
if (typeof fallbackLocale !== 'string') {
fallbackLocale = typeof __uniConfig !== 'undefined' && __uniConfig.fallbackLocale || LOCALE_EN;
}
var i18n = new I18n({
locale: locale,
fallbackLocale: fallbackLocale,
messages: messages,
watcher: watcher
});
var _t = function t(key, values) {
if (typeof getApp !== 'function') {
// app view
/* eslint-disable no-func-assign */
_t = function t(key, values) {
return i18n.t(key, values);
};
} else {
var isWatchedAppLocale = false;
_t = function t(key, values) {
var appVm = getApp().$vm;
// 可能$vm还不存在,比如在支付宝小程序中,组件定义较早,在props的default里使用了t()函数(如uni-goods-nav),此时app还未初始化
// options: {
// type: Array,
// default () {
// return [{
// icon: 'shop',
// text: t("uni-goods-nav.options.shop"),
// }, {
// icon: 'cart',
// text: t("uni-goods-nav.options.cart")
// }]
// }
// },
if (appVm) {
// 触发响应式
appVm.$locale;
if (!isWatchedAppLocale) {
isWatchedAppLocale = true;
watchAppLocale(appVm, i18n);
}
}
return i18n.t(key, values);
};
}
return _t(key, values);
};
return {
i18n: i18n,
f: function f(message, values, delimiters) {
return i18n.f(message, values, delimiters);
},
t: function t(key, values) {
return _t(key, values);
},
add: function add(locale, message) {
var override = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
return i18n.add(locale, message, override);
},
watch: function watch(fn) {
return i18n.watchLocale(fn);
},
getLocale: function getLocale() {
return i18n.getLocale();
},
setLocale: function setLocale(newLocale) {
return i18n.setLocale(newLocale);
}
};
}
var isString = function isString(val) {
return typeof val === 'string';
};
exports.isString = isString;
var formater;
function hasI18nJson(jsonObj, delimiters) {
if (!formater) {
formater = new BaseFormatter();
}
return walkJsonObj(jsonObj, function (jsonObj, key) {
var value = jsonObj[key];
if (isString(value)) {
if (isI18nStr(value, delimiters)) {
return true;
}
} else {
return hasI18nJson(value, delimiters);
}
});
}
function parseI18nJson(jsonObj, values, delimiters) {
if (!formater) {
formater = new BaseFormatter();
}
walkJsonObj(jsonObj, function (jsonObj, key) {
var value = jsonObj[key];
if (isString(value)) {
if (isI18nStr(value, delimiters)) {
jsonObj[key] = compileStr(value, values, delimiters);
}
} else {
parseI18nJson(value, values, delimiters);
}
});
return jsonObj;
}
function compileI18nJsonStr(jsonStr, _ref5) {
var locale = _ref5.locale,
locales = _ref5.locales,
delimiters = _ref5.delimiters;
if (!isI18nStr(jsonStr, delimiters)) {
return jsonStr;
}
if (!formater) {
formater = new BaseFormatter();
}
var localeValues = [];
Object.keys(locales).forEach(function (name) {
if (name !== locale) {
localeValues.push({
locale: name,
values: locales[name]
});
}
});
localeValues.unshift({
locale: locale,
values: locales[locale]
});
try {
return JSON.stringify(compileJsonObj(JSON.parse(jsonStr), localeValues, delimiters), null, 2);
} catch (e) {}
return jsonStr;
}
function isI18nStr(value, delimiters) {
return value.indexOf(delimiters[0]) > -1;
}
function compileStr(value, values, delimiters) {
return formater.interpolate(value, values, delimiters).join('');
}
function compileValue(jsonObj, key, localeValues, delimiters) {
var value = jsonObj[key];
if (isString(value)) {
// 存在国际化
if (isI18nStr(value, delimiters)) {
jsonObj[key] = compileStr(value, localeValues[0].values, delimiters);
if (localeValues.length > 1) {
// 格式化国际化语言
var valueLocales = jsonObj[key + 'Locales'] = {};
localeValues.forEach(function (localValue) {
valueLocales[localValue.locale] = compileStr(value, localValue.values, delimiters);
});
}
}
} else {
compileJsonObj(value, localeValues, delimiters);
}
}
function compileJsonObj(jsonObj, localeValues, delimiters) {
walkJsonObj(jsonObj, function (jsonObj, key) {
compileValue(jsonObj, key, localeValues, delimiters);
});
return jsonObj;
}
function walkJsonObj(jsonObj, walk) {
if (Array.isArray(jsonObj)) {
for (var i = 0; i < jsonObj.length; i++) {
if (walk(jsonObj, i)) {
return true;
}
}
} else if (isObject(jsonObj)) {
for (var key in jsonObj) {
if (walk(jsonObj, key)) {
return true;
}
}
}
return false;
}
function resolveLocale(locales) {
return function (locale) {
if (!locale) {
return locale;
}
locale = normalizeLocale(locale) || locale;
return resolveLocaleChain(locale).find(function (locale) {
return locales.indexOf(locale) > -1;
});
};
}
function resolveLocaleChain(locale) {
var chain = [];
var tokens = locale.split('-');
while (tokens.length) {
chain.push(tokens.join('-'));
tokens.pop();
}
return chain;
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/index.js */ 2)["default"], __webpack_require__(/*! ./../../../webpack/buildin/global.js */ 3)))
/***/ }),
/* 23 */
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/classCallCheck.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 24 */
/*!************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/createClass.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var toPropertyKey = __webpack_require__(/*! ./toPropertyKey.js */ 12);
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 25 */
/*!******************************************************************************************!*\
!*** ./node_modules/@dcloudio/vue-cli-plugin-uni/packages/mp-vue/dist/mp.runtime.esm.js ***!
\******************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(global) {/*!
* Vue.js v2.6.11
* (c) 2014-2023 Evan You
* Released under the MIT License.
*/
/* */
var emptyObject = Object.freeze({});
// These helpers produce better VM code in JS engines due to their
// explicitness and function inlining.
function isUndef (v) {
return v === undefined || v === null
}
function isDef (v) {
return v !== undefined && v !== null
}
function isTrue (v) {
return v === true
}
function isFalse (v) {
return v === false
}
/**
* Check if value is primitive.
*/
function isPrimitive (value) {
return (
typeof value === 'string' ||
typeof value === 'number' ||
// $flow-disable-line
typeof value === 'symbol' ||
typeof value === 'boolean'
)
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
/**
* Get the raw type string of a value, e.g., [object Object].
*/
var _toString = Object.prototype.toString;
function toRawType (value) {
return _toString.call(value).slice(8, -1)
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
function isPlainObject (obj) {
return _toString.call(obj) === '[object Object]'
}
function isRegExp (v) {
return _toString.call(v) === '[object RegExp]'
}
/**
* Check if val is a valid array index.
*/
function isValidArrayIndex (val) {
var n = parseFloat(String(val));
return n >= 0 && Math.floor(n) === n && isFinite(val)
}
function isPromise (val) {
return (
isDef(val) &&
typeof val.then === 'function' &&
typeof val.catch === 'function'
)
}
/**
* Convert a value to a string that is actually rendered.
*/
function toString (val) {
return val == null
? ''
: Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)
? JSON.stringify(val, null, 2)
: String(val)
}
/**
* Convert an input value to a number for persistence.
* If the conversion fails, return original string.
*/
function toNumber (val) {
var n = parseFloat(val);
return isNaN(n) ? val : n
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
function makeMap (
str,
expectsLowerCase
) {
var map = Object.create(null);
var list = str.split(',');
for (var i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
/**
* Check if a tag is a built-in tag.
*/
var isBuiltInTag = makeMap('slot,component', true);
/**
* Check if an attribute is a reserved attribute.
*/
var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is');
/**
* Remove an item from an array.
*/
function remove (arr, item) {
if (arr.length) {
var index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1)
}
}
}
/**
* Check whether an object has the property.
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
/**
* Create a cached version of a pure function.
*/
function cached (fn) {
var cache = Object.create(null);
return (function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
})
}
/**
* Camelize a hyphen-delimited string.
*/
var camelizeRE = /-(\w)/g;
var camelize = cached(function (str) {
return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
});
/**
* Capitalize a string.
*/
var capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
});
/**
* Hyphenate a camelCase string.
*/
var hyphenateRE = /\B([A-Z])/g;
var hyphenate = cached(function (str) {
return str.replace(hyphenateRE, '-$1').toLowerCase()
});
/**
* Simple bind polyfill for environments that do not support it,
* e.g., PhantomJS 1.x. Technically, we don't need this anymore
* since native bind is now performant enough in most browsers.
* But removing it would mean breaking code that was able to run in
* PhantomJS 1.x, so this must be kept for backward compatibility.
*/
/* istanbul ignore next */
function polyfillBind (fn, ctx) {
function boundFn (a) {
var l = arguments.length;
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
boundFn._length = fn.length;
return boundFn
}
function nativeBind (fn, ctx) {
return fn.bind(ctx)
}
var bind = Function.prototype.bind
? nativeBind
: polyfillBind;
/**
* Convert an Array-like object to a real Array.
*/
function toArray (list, start) {
start = start || 0;
var i = list.length - start;
var ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret
}
/**
* Mix properties into target object.
*/
function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to
}
/**
* Merge an Array of Objects into a single Object.
*/
function toObject (arr) {
var res = {};
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i]);
}
}
return res
}
/* eslint-disable no-unused-vars */
/**
* Perform no operation.
* Stubbing args to make Flow happy without leaving useless transpiled code
* with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/).
*/
function noop (a, b, c) {}
/**
* Always return false.
*/
var no = function (a, b, c) { return false; };
/* eslint-enable no-unused-vars */
/**
* Return the same value.
*/
var identity = function (_) { return _; };
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/
function looseEqual (a, b) {
if (a === b) { return true }
var isObjectA = isObject(a);
var isObjectB = isObject(b);
if (isObjectA && isObjectB) {
try {
var isArrayA = Array.isArray(a);
var isArrayB = Array.isArray(b);
if (isArrayA && isArrayB) {
return a.length === b.length && a.every(function (e, i) {
return looseEqual(e, b[i])
})
} else if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime()
} else if (!isArrayA && !isArrayB) {
var keysA = Object.keys(a);
var keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every(function (key) {
return looseEqual(a[key], b[key])
})
} else {
/* istanbul ignore next */
return false
}
} catch (e) {
/* istanbul ignore next */
return false
}
} else if (!isObjectA && !isObjectB) {
return String(a) === String(b)
} else {
return false
}
}
/**
* Return the first index at which a loosely equal value can be
* found in the array (if value is a plain object, the array must
* contain an object of the same shape), or -1 if it is not present.
*/
function looseIndexOf (arr, val) {
for (var i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) { return i }
}
return -1
}
/**
* Ensure a function is called only once.
*/
function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn.apply(this, arguments);
}
}
}
var ASSET_TYPES = [
'component',
'directive',
'filter'
];
var LIFECYCLE_HOOKS = [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated',
'errorCaptured',
'serverPrefetch'
];
/* */
var config = ({
/**
* Option merge strategies (used in core/util/options)
*/
// $flow-disable-line
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Show production mode tip message on boot?
*/
productionTip: "development" !== 'production',
/**
* Whether to enable devtools
*/
devtools: "development" !== 'production',
/**
* Whether to record perf
*/
performance: false,
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Warn handler for watcher warns
*/
warnHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: [],
/**
* Custom user key aliases for v-on
*/
// $flow-disable-line
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if an attribute is reserved so that it cannot be used as a component
* prop. This is platform-dependent and may be overwritten.
*/
isReservedAttr: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Parse the real tag name for the specific platform.
*/
parsePlatformTagName: identity,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* Perform updates asynchronously. Intended to be used by Vue Test Utils
* This will significantly reduce performance if set to false.
*/
async: true,
/**
* Exposed for legacy reasons
*/
_lifecycleHooks: LIFECYCLE_HOOKS
});
/* */
/**
* unicode letters used for parsing html tags, component names and property paths.
* using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname
* skipping \u10000-\uEFFFF due to it freezing up PhantomJS
*/
var unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/;
/**
* Check if a string starts with $ or _
*/
function isReserved (str) {
var c = (str + '').charCodeAt(0);
return c === 0x24 || c === 0x5F
}
/**
* Define a property.
*/
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
});
}
/**
* Parse simple path.
*/
var bailRE = new RegExp(("[^" + (unicodeRegExp.source) + ".$_\\d]"));
function parsePath (path) {
if (bailRE.test(path)) {
return
}
var segments = path.split('.');
return function (obj) {
for (var i = 0; i < segments.length; i++) {
if (!obj) { return }
obj = obj[segments[i]];
}
return obj
}
}
/* */
// can we use __proto__?
var hasProto = '__proto__' in {};
// Browser environment sniffing
var inBrowser = typeof window !== 'undefined';
var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;
var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();
var UA = inBrowser && window.navigator.userAgent.toLowerCase();
var isIE = UA && /msie|trident/.test(UA);
var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
var isEdge = UA && UA.indexOf('edge/') > 0;
var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android');
var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios');
var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
var isPhantomJS = UA && /phantomjs/.test(UA);
var isFF = UA && UA.match(/firefox\/(\d+)/);
// Firefox has a "watch" function on Object.prototype...
var nativeWatch = ({}).watch;
if (inBrowser) {
try {
var opts = {};
Object.defineProperty(opts, 'passive', ({
get: function get () {
}
})); // https://github.com/facebook/flow/issues/285
window.addEventListener('test-passive', null, opts);
} catch (e) {}
}
// this needs to be lazy-evaled because vue may be required before
// vue-server-renderer can set VUE_ENV
var _isServer;
var isServerRendering = function () {
if (_isServer === undefined) {
/* istanbul ignore if */
if (!inBrowser && !inWeex && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = global['process'] && global['process'].env.VUE_ENV === 'server';
} else {
_isServer = false;
}
}
return _isServer
};
// detect devtools
var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
/* istanbul ignore next */
function isNative (Ctor) {
return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
}
var hasSymbol =
typeof Symbol !== 'undefined' && isNative(Symbol) &&
typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys);
var _Set;
/* istanbul ignore if */ // $flow-disable-line
if (typeof Set !== 'undefined' && isNative(Set)) {
// use native Set when available.
_Set = Set;
} else {
// a non-standard Set polyfill that only works with primitive keys.
_Set = /*@__PURE__*/(function () {
function Set () {
this.set = Object.create(null);
}
Set.prototype.has = function has (key) {
return this.set[key] === true
};
Set.prototype.add = function add (key) {
this.set[key] = true;
};
Set.prototype.clear = function clear () {
this.set = Object.create(null);
};
return Set;
}());
}
/* */
var warn = noop;
var tip = noop;
var generateComponentTrace = (noop); // work around flow check
var formatComponentName = (noop);
if (true) {
var hasConsole = typeof console !== 'undefined';
var classifyRE = /(?:^|[-_])(\w)/g;
var classify = function (str) { return str
.replace(classifyRE, function (c) { return c.toUpperCase(); })
.replace(/[-_]/g, ''); };
warn = function (msg, vm) {
var trace = vm ? generateComponentTrace(vm) : '';
if (config.warnHandler) {
config.warnHandler.call(null, msg, vm, trace);
} else if (hasConsole && (!config.silent)) {
console.error(("[Vue warn]: " + msg + trace));
}
};
tip = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.warn("[Vue tip]: " + msg + (
vm ? generateComponentTrace(vm) : ''
));
}
};
formatComponentName = function (vm, includeFile) {
if (vm.$root === vm) {
if (vm.$options && vm.$options.__file) { // fixed by xxxxxx
return ('') + vm.$options.__file
}
return '<Root>'
}
var options = typeof vm === 'function' && vm.cid != null
? vm.options
: vm._isVue
? vm.$options || vm.constructor.options
: vm;
var name = options.name || options._componentTag;
var file = options.__file;
if (!name && file) {
var match = file.match(/([^/\\]+)\.vue$/);
name = match && match[1];
}
return (
(name ? ("<" + (classify(name)) + ">") : "<Anonymous>") +
(file && includeFile !== false ? (" at " + file) : '')
)
};
var repeat = function (str, n) {
var res = '';
while (n) {
if (n % 2 === 1) { res += str; }
if (n > 1) { str += str; }
n >>= 1;
}
return res
};
generateComponentTrace = function (vm) {
if (vm._isVue && vm.$parent) {
var tree = [];
var currentRecursiveSequence = 0;
while (vm && vm.$options.name !== 'PageBody') {
if (tree.length > 0) {
var last = tree[tree.length - 1];
if (last.constructor === vm.constructor) {
currentRecursiveSequence++;
vm = vm.$parent;
continue
} else if (currentRecursiveSequence > 0) {
tree[tree.length - 1] = [last, currentRecursiveSequence];
currentRecursiveSequence = 0;
}
}
!vm.$options.isReserved && tree.push(vm);
vm = vm.$parent;
}
return '\n\nfound in\n\n' + tree
.map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm)
? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)")
: formatComponentName(vm))); })
.join('\n')
} else {
return ("\n\n(found in " + (formatComponentName(vm)) + ")")
}
};
}
/* */
var uid = 0;
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
var Dep = function Dep () {
this.id = uid++;
this.subs = [];
};
Dep.prototype.addSub = function addSub (sub) {
this.subs.push(sub);
};
Dep.prototype.removeSub = function removeSub (sub) {
remove(this.subs, sub);
};
Dep.prototype.depend = function depend () {
if (Dep.SharedObject.target) {
Dep.SharedObject.target.addDep(this);
}
};
Dep.prototype.notify = function notify () {
// stabilize the subscriber list first
var subs = this.subs.slice();
if ( true && !config.async) {
// subs aren't sorted in scheduler if not running async
// we need to sort them now to make sure they fire in correct
// order
subs.sort(function (a, b) { return a.id - b.id; });
}
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update();
}
};
// The current target watcher being evaluated.
// This is globally unique because only one watcher
// can be evaluated at a time.
// fixed by xxxxxx (nvue shared vuex)
/* eslint-disable no-undef */
Dep.SharedObject = {};
Dep.SharedObject.target = null;
Dep.SharedObject.targetStack = [];
function pushTarget (target) {
Dep.SharedObject.targetStack.push(target);
Dep.SharedObject.target = target;
Dep.target = target;
}
function popTarget () {
Dep.SharedObject.targetStack.pop();
Dep.SharedObject.target = Dep.SharedObject.targetStack[Dep.SharedObject.targetStack.length - 1];
Dep.target = Dep.SharedObject.target;
}
/* */
var VNode = function VNode (
tag,
data,
children,
text,
elm,
context,
componentOptions,
asyncFactory
) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
this.elm = elm;
this.ns = undefined;
this.context = context;
this.fnContext = undefined;
this.fnOptions = undefined;
this.fnScopeId = undefined;
this.key = data && data.key;
this.componentOptions = componentOptions;
this.componentInstance = undefined;
this.parent = undefined;
this.raw = false;
this.isStatic = false;
this.isRootInsert = true;
this.isComment = false;
this.isCloned = false;
this.isOnce = false;
this.asyncFactory = asyncFactory;
this.asyncMeta = undefined;
this.isAsyncPlaceholder = false;
};
var prototypeAccessors = { child: { configurable: true } };
// DEPRECATED: alias for componentInstance for backwards compat.
/* istanbul ignore next */
prototypeAccessors.child.get = function () {
return this.componentInstance
};
Object.defineProperties( VNode.prototype, prototypeAccessors );
var createEmptyVNode = function (text) {
if ( text === void 0 ) text = '';
var node = new VNode();
node.text = text;
node.isComment = true;
return node
};
function createTextVNode (val) {
return new VNode(undefined, undefined, undefined, String(val))
}
// optimized shallow clone
// used for static nodes and slot nodes because they may be reused across
// multiple renders, cloning them avoids errors when DOM manipulations rely
// on their elm reference.
function cloneVNode (vnode) {
var cloned = new VNode(
vnode.tag,
vnode.data,
// #7975
// clone children array to avoid mutating original in case of cloning
// a child.
vnode.children && vnode.children.slice(),
vnode.text,
vnode.elm,
vnode.context,
vnode.componentOptions,
vnode.asyncFactory
);
cloned.ns = vnode.ns;
cloned.isStatic = vnode.isStatic;
cloned.key = vnode.key;
cloned.isComment = vnode.isComment;
cloned.fnContext = vnode.fnContext;
cloned.fnOptions = vnode.fnOptions;
cloned.fnScopeId = vnode.fnScopeId;
cloned.asyncMeta = vnode.asyncMeta;
cloned.isCloned = true;
return cloned
}
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
var arrayProto = Array.prototype;
var arrayMethods = Object.create(arrayProto);
var methodsToPatch = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
];
/**
* Intercept mutating methods and emit events
*/
methodsToPatch.forEach(function (method) {
// cache original method
var original = arrayProto[method];
def(arrayMethods, method, function mutator () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
var result = original.apply(this, args);
var ob = this.__ob__;
var inserted;
switch (method) {
case 'push':
case 'unshift':
inserted = args;
break
case 'splice':
inserted = args.slice(2);
break
}
if (inserted) { ob.observeArray(inserted); }
// notify change
ob.dep.notify();
return result
});
});
/* */
var arrayKeys = Object.getOwnPropertyNames(arrayMethods);
/**
* In some cases we may want to disable observation inside a component's
* update computation.
*/
var shouldObserve = true;
function toggleObserving (value) {
shouldObserve = value;
}
/**
* Observer class that is attached to each observed
* object. Once attached, the observer converts the target
* object's property keys into getter/setters that
* collect dependencies and dispatch updates.
*/
var Observer = function Observer (value) {
this.value = value;
this.dep = new Dep();
this.vmCount = 0;
def(value, '__ob__', this);
if (Array.isArray(value)) {
if (hasProto) {
{// fixed by xxxxxx 微信小程序使用 plugins 之后,数组方法被直接挂载到了数组对象上,需要执行 copyAugment 逻辑
if(value.push !== value.__proto__.push){
copyAugment(value, arrayMethods, arrayKeys);
} else {
protoAugment(value, arrayMethods);
}
}
} else {
copyAugment(value, arrayMethods, arrayKeys);
}
this.observeArray(value);
} else {
this.walk(value);
}
};
/**
* Walk through all properties and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
Observer.prototype.walk = function walk (obj) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
defineReactive$$1(obj, keys[i]);
}
};
/**
* Observe a list of Array items.
*/
Observer.prototype.observeArray = function observeArray (items) {
for (var i = 0, l = items.length; i < l; i++) {
observe(items[i]);
}
};
// helpers
/**
* Augment a target Object or Array by intercepting
* the prototype chain using __proto__
*/
function protoAugment (target, src) {
/* eslint-disable no-proto */
target.__proto__ = src;
/* eslint-enable no-proto */
}
/**
* Augment a target Object or Array by defining
* hidden properties.
*/
/* istanbul ignore next */
function copyAugment (target, src, keys) {
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
def(target, key, src[key]);
}
}
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
function observe (value, asRootData) {
if (!isObject(value) || value instanceof VNode) {
return
}
var ob;
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__;
} else if (
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue &&
!value.__v_isMPComponent
) {
ob = new Observer(value);
}
if (asRootData && ob) {
ob.vmCount++;
}
return ob
}
/**
* Define a reactive property on an Object.
*/
function defineReactive$$1 (
obj,
key,
val,
customSetter,
shallow
) {
var dep = new Dep();
var property = Object.getOwnPropertyDescriptor(obj, key);
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
var getter = property && property.get;
var setter = property && property.set;
if ((!getter || setter) && arguments.length === 2) {
val = obj[key];
}
var childOb = !shallow && observe(val);
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
var value = getter ? getter.call(obj) : val;
if (Dep.SharedObject.target) { // fixed by xxxxxx
dep.depend();
if (childOb) {
childOb.dep.depend();
if (Array.isArray(value)) {
dependArray(value);
}
}
}
return value
},
set: function reactiveSetter (newVal) {
var value = getter ? getter.call(obj) : val;
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if ( true && customSetter) {
customSetter();
}
// #7981: for accessor properties without setter
if (getter && !setter) { return }
if (setter) {
setter.call(obj, newVal);
} else {
val = newVal;
}
childOb = !shallow && observe(newVal);
dep.notify();
}
});
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
function set (target, key, val) {
if ( true &&
(isUndef(target) || isPrimitive(target))
) {
warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target))));
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key);
target.splice(key, 1, val);
return val
}
if (key in target && !(key in Object.prototype)) {
target[key] = val;
return val
}
var ob = (target).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
true && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
);
return val
}
if (!ob) {
target[key] = val;
return val
}
defineReactive$$1(ob.value, key, val);
ob.dep.notify();
return val
}
/**
* Delete a property and trigger change if necessary.
*/
function del (target, key) {
if ( true &&
(isUndef(target) || isPrimitive(target))
) {
warn(("Cannot delete reactive property on undefined, null, or primitive value: " + ((target))));
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.splice(key, 1);
return
}
var ob = (target).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
true && warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
);
return
}
if (!hasOwn(target, key)) {
return
}
delete target[key];
if (!ob) {
return
}
ob.dep.notify();
}
/**
* Collect dependencies on array elements when the array is touched, since
* we cannot intercept array element access like property getters.
*/
function dependArray (value) {
for (var e = (void 0), i = 0, l = value.length; i < l; i++) {
e = value[i];
e && e.__ob__ && e.__ob__.dep.depend();
if (Array.isArray(e)) {
dependArray(e);
}
}
}
/* */
/**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/
var strats = config.optionMergeStrategies;
/**
* Options with restrictions
*/
if (true) {
strats.el = strats.propsData = function (parent, child, vm, key) {
if (!vm) {
warn(
"option \"" + key + "\" can only be used during instance " +
'creation with the `new` keyword.'
);
}
return defaultStrat(parent, child)
};
}
/**
* Helper that recursively merges two data objects together.
*/
function mergeData (to, from) {
if (!from) { return to }
var key, toVal, fromVal;
var keys = hasSymbol
? Reflect.ownKeys(from)
: Object.keys(from);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
// in case the object is already observed...
if (key === '__ob__') { continue }
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set(to, key, fromVal);
} else if (
toVal !== fromVal &&
isPlainObject(toVal) &&
isPlainObject(fromVal)
) {
mergeData(toVal, fromVal);
}
}
return to
}
/**
* Data
*/
function mergeDataOrFn (
parentVal,
childVal,
vm
) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
if (!parentVal) {
return childVal
}
// when parentVal & childVal are both present,
// we need to return a function that returns the
// merged result of both functions... no need to
// check if parentVal is a function here because
// it has to be a function to pass previous merges.
return function mergedDataFn () {
return mergeData(
typeof childVal === 'function' ? childVal.call(this, this) : childVal,
typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal
)
}
} else {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
? childVal.call(vm, vm)
: childVal;
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm, vm)
: parentVal;
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
}
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
if (childVal && typeof childVal !== 'function') {
true && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
);
return parentVal
}
return mergeDataOrFn(parentVal, childVal)
}
return mergeDataOrFn(parentVal, childVal, vm)
};
/**
* Hooks and props are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
var res = childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal;
return res
? dedupeHooks(res)
: res
}
function dedupeHooks (hooks) {
var res = [];
for (var i = 0; i < hooks.length; i++) {
if (res.indexOf(hooks[i]) === -1) {
res.push(hooks[i]);
}
}
return res
}
LIFECYCLE_HOOKS.forEach(function (hook) {
strats[hook] = mergeHook;
});
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/
function mergeAssets (
parentVal,
childVal,
vm,
key
) {
var res = Object.create(parentVal || null);
if (childVal) {
true && assertObjectType(key, childVal, vm);
return extend(res, childVal)
} else {
return res
}
}
ASSET_TYPES.forEach(function (type) {
strats[type + 's'] = mergeAssets;
});
/**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
strats.watch = function (
parentVal,
childVal,
vm,
key
) {
// work around Firefox's Object.prototype.watch...
if (parentVal === nativeWatch) { parentVal = undefined; }
if (childVal === nativeWatch) { childVal = undefined; }
/* istanbul ignore if */
if (!childVal) { return Object.create(parentVal || null) }
if (true) {
assertObjectType(key, childVal, vm);
}
if (!parentVal) { return childVal }
var ret = {};
extend(ret, parentVal);
for (var key$1 in childVal) {
var parent = ret[key$1];
var child = childVal[key$1];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
ret[key$1] = parent
? parent.concat(child)
: Array.isArray(child) ? child : [child];
}
return ret
};
/**
* Other object hashes.
*/
strats.props =
strats.methods =
strats.inject =
strats.computed = function (
parentVal,
childVal,
vm,
key
) {
if (childVal && "development" !== 'production') {
assertObjectType(key, childVal, vm);
}
if (!parentVal) { return childVal }
var ret = Object.create(null);
extend(ret, parentVal);
if (childVal) { extend(ret, childVal); }
return ret
};
strats.provide = mergeDataOrFn;
/**
* Default strategy.
*/
var defaultStrat = function (parentVal, childVal) {
return childVal === undefined
? parentVal
: childVal
};
/**
* Validate component names
*/
function checkComponents (options) {
for (var key in options.components) {
validateComponentName(key);
}
}
function validateComponentName (name) {
if (!new RegExp(("^[a-zA-Z][\\-\\.0-9_" + (unicodeRegExp.source) + "]*$")).test(name)) {
warn(
'Invalid component name: "' + name + '". Component names ' +
'should conform to valid custom element name in html5 specification.'
);
}
if (isBuiltInTag(name) || config.isReservedTag(name)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + name
);
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options, vm) {
var props = options.props;
if (!props) { return }
var res = {};
var i, val, name;
if (Array.isArray(props)) {
i = props.length;
while (i--) {
val = props[i];
if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: null };
} else if (true) {
warn('props must be strings when using array syntax.');
}
}
} else if (isPlainObject(props)) {
for (var key in props) {
val = props[key];
name = camelize(key);
res[name] = isPlainObject(val)
? val
: { type: val };
}
} else if (true) {
warn(
"Invalid value for option \"props\": expected an Array or an Object, " +
"but got " + (toRawType(props)) + ".",
vm
);
}
options.props = res;
}
/**
* Normalize all injections into Object-based format
*/
function normalizeInject (options, vm) {
var inject = options.inject;
if (!inject) { return }
var normalized = options.inject = {};
if (Array.isArray(inject)) {
for (var i = 0; i < inject.length; i++) {
normalized[inject[i]] = { from: inject[i] };
}
} else if (isPlainObject(inject)) {
for (var key in inject) {
var val = inject[key];
normalized[key] = isPlainObject(val)
? extend({ from: key }, val)
: { from: val };
}
} else if (true) {
warn(
"Invalid value for option \"inject\": expected an Array or an Object, " +
"but got " + (toRawType(inject)) + ".",
vm
);
}
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options) {
var dirs = options.directives;
if (dirs) {
for (var key in dirs) {
var def$$1 = dirs[key];
if (typeof def$$1 === 'function') {
dirs[key] = { bind: def$$1, update: def$$1 };
}
}
}
}
function assertObjectType (name, value, vm) {
if (!isPlainObject(value)) {
warn(
"Invalid value for option \"" + name + "\": expected an Object, " +
"but got " + (toRawType(value)) + ".",
vm
);
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
function mergeOptions (
parent,
child,
vm
) {
if (true) {
checkComponents(child);
}
if (typeof child === 'function') {
child = child.options;
}
normalizeProps(child, vm);
normalizeInject(child, vm);
normalizeDirectives(child);
// Apply extends and mixins on the child options,
// but only if it is a raw options object that isn't
// the result of another mergeOptions call.
// Only merged options has the _base property.
if (!child._base) {
if (child.extends) {
parent = mergeOptions(parent, child.extends, vm);
}
if (child.mixins) {
for (var i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], vm);
}
}
}
var options = {};
var key;
for (key in parent) {
mergeField(key);
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key);
}
}
function mergeField (key) {
var strat = strats[key] || defaultStrat;
options[key] = strat(parent[key], child[key], vm, key);
}
return options
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
function resolveAsset (
options,
type,
id,
warnMissing
) {
/* istanbul ignore if */
if (typeof id !== 'string') {
return
}
var assets = options[type];
// check local registration variations first
if (hasOwn(assets, id)) { return assets[id] }
var camelizedId = camelize(id);
if (hasOwn(assets, camelizedId)) { return assets[camelizedId] }
var PascalCaseId = capitalize(camelizedId);
if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] }
// fallback to prototype chain
var res = assets[id] || assets[camelizedId] || assets[PascalCaseId];
if ( true && warnMissing && !res) {
warn(
'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
options
);
}
return res
}
/* */
function validateProp (
key,
propOptions,
propsData,
vm
) {
var prop = propOptions[key];
var absent = !hasOwn(propsData, key);
var value = propsData[key];
// boolean casting
var booleanIndex = getTypeIndex(Boolean, prop.type);
if (booleanIndex > -1) {
if (absent && !hasOwn(prop, 'default')) {
value = false;
} else if (value === '' || value === hyphenate(key)) {
// only cast empty string / same name to boolean if
// boolean has higher priority
var stringIndex = getTypeIndex(String, prop.type);
if (stringIndex < 0 || booleanIndex < stringIndex) {
value = true;
}
}
}
// check default value
if (value === undefined) {
value = getPropDefaultValue(vm, prop, key);
// since the default value is a fresh copy,
// make sure to observe it.
var prevShouldObserve = shouldObserve;
toggleObserving(true);
observe(value);
toggleObserving(prevShouldObserve);
}
if (
true
) {
assertProp(prop, key, value, vm, absent);
}
return value
}
/**
* Get the default value of a prop.
*/
function getPropDefaultValue (vm, prop, key) {
// no default, return undefined
if (!hasOwn(prop, 'default')) {
return undefined
}
var def = prop.default;
// warn against non-factory defaults for Object & Array
if ( true && isObject(def)) {
warn(
'Invalid default value for prop "' + key + '": ' +
'Props with type Object/Array must use a factory function ' +
'to return the default value.',
vm
);
}
// the raw prop value was also undefined from previous render,
// return previous default value to avoid unnecessary watcher trigger
if (vm && vm.$options.propsData &&
vm.$options.propsData[key] === undefined &&
vm._props[key] !== undefined
) {
return vm._props[key]
}
// call factory function for non-Function types
// a value is Function if its prototype is function even across different execution context
return typeof def === 'function' && getType(prop.type) !== 'Function'
? def.call(vm)
: def
}
/**
* Assert whether a prop is valid.
*/
function assertProp (
prop,
name,
value,
vm,
absent
) {
if (prop.required && absent) {
warn(
'Missing required prop: "' + name + '"',
vm
);
return
}
if (value == null && !prop.required) {
return
}
var type = prop.type;
var valid = !type || type === true;
var expectedTypes = [];
if (type) {
if (!Array.isArray(type)) {
type = [type];
}
for (var i = 0; i < type.length && !valid; i++) {
var assertedType = assertType(value, type[i]);
expectedTypes.push(assertedType.expectedType || '');
valid = assertedType.valid;
}
}
if (!valid) {
warn(
getInvalidTypeMessage(name, value, expectedTypes),
vm
);
return
}
var validator = prop.validator;
if (validator) {
if (!validator(value)) {
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
);
}
}
}
var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;
function assertType (value, type) {
var valid;
var expectedType = getType(type);
if (simpleCheckRE.test(expectedType)) {
var t = typeof value;
valid = t === expectedType.toLowerCase();
// for primitive wrapper objects
if (!valid && t === 'object') {
valid = value instanceof type;
}
} else if (expectedType === 'Object') {
valid = isPlainObject(value);
} else if (expectedType === 'Array') {
valid = Array.isArray(value);
} else {
valid = value instanceof type;
}
return {
valid: valid,
expectedType: expectedType
}
}
/**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.
*/
function getType (fn) {
var match = fn && fn.toString().match(/^\s*function (\w+)/);
return match ? match[1] : ''
}
function isSameType (a, b) {
return getType(a) === getType(b)
}
function getTypeIndex (type, expectedTypes) {
if (!Array.isArray(expectedTypes)) {
return isSameType(expectedTypes, type) ? 0 : -1
}
for (var i = 0, len = expectedTypes.length; i < len; i++) {
if (isSameType(expectedTypes[i], type)) {
return i
}
}
return -1
}
function getInvalidTypeMessage (name, value, expectedTypes) {
var message = "Invalid prop: type check failed for prop \"" + name + "\"." +
" Expected " + (expectedTypes.map(capitalize).join(', '));
var expectedType = expectedTypes[0];
var receivedType = toRawType(value);
var expectedValue = styleValue(value, expectedType);
var receivedValue = styleValue(value, receivedType);
// check if we need to specify expected value
if (expectedTypes.length === 1 &&
isExplicable(expectedType) &&
!isBoolean(expectedType, receivedType)) {
message += " with value " + expectedValue;
}
message += ", got " + receivedType + " ";
// check if we need to specify received value
if (isExplicable(receivedType)) {
message += "with value " + receivedValue + ".";
}
return message
}
function styleValue (value, type) {
if (type === 'String') {
return ("\"" + value + "\"")
} else if (type === 'Number') {
return ("" + (Number(value)))
} else {
return ("" + value)
}
}
function isExplicable (value) {
var explicitTypes = ['string', 'number', 'boolean'];
return explicitTypes.some(function (elem) { return value.toLowerCase() === elem; })
}
function isBoolean () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return args.some(function (elem) { return elem.toLowerCase() === 'boolean'; })
}
/* */
function handleError (err, vm, info) {
// Deactivate deps tracking while processing error handler to avoid possible infinite rendering.
// See: https://github.com/vuejs/vuex/issues/1505
pushTarget();
try {
if (vm) {
var cur = vm;
while ((cur = cur.$parent)) {
var hooks = cur.$options.errorCaptured;
if (hooks) {
for (var i = 0; i < hooks.length; i++) {
try {
var capture = hooks[i].call(cur, err, vm, info) === false;
if (capture) { return }
} catch (e) {
globalHandleError(e, cur, 'errorCaptured hook');
}
}
}
}
}
globalHandleError(err, vm, info);
} finally {
popTarget();
}
}
function invokeWithErrorHandling (
handler,
context,
args,
vm,
info
) {
var res;
try {
res = args ? handler.apply(context, args) : handler.call(context);
if (res && !res._isVue && isPromise(res) && !res._handled) {
res.catch(function (e) { return handleError(e, vm, info + " (Promise/async)"); });
// issue #9511
// avoid catch triggering multiple times when nested calls
res._handled = true;
}
} catch (e) {
handleError(e, vm, info);
}
return res
}
function globalHandleError (err, vm, info) {
if (config.errorHandler) {
try {
return config.errorHandler.call(null, err, vm, info)
} catch (e) {
// if the user intentionally throws the original error in the handler,
// do not log it twice
if (e !== err) {
logError(e, null, 'config.errorHandler');
}
}
}
logError(err, vm, info);
}
function logError (err, vm, info) {
if (true) {
warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm);
}
/* istanbul ignore else */
if ((inBrowser || inWeex) && typeof console !== 'undefined') {
console.error(err);
} else {
throw err
}
}
/* */
var callbacks = [];
var pending = false;
function flushCallbacks () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
var timerFunc;
// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
timerFunc = function () {
p.then(flushCallbacks);
// In problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) { setTimeout(noop); }
};
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// Use MutationObserver where native Promise is not available,
// e.g. PhantomJS, iOS7, Android 4.4
// (#6466 MutationObserver is unreliable in IE11)
var counter = 1;
var observer = new MutationObserver(flushCallbacks);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
// Fallback to setImmediate.
// Technically it leverages the (macro) task queue,
// but it is still a better choice than setTimeout.
timerFunc = function () {
setImmediate(flushCallbacks);
};
} else {
// Fallback to setTimeout.
timerFunc = function () {
setTimeout(flushCallbacks, 0);
};
}
function nextTick (cb, ctx) {
var _resolve;
callbacks.push(function () {
if (cb) {
try {
cb.call(ctx);
} catch (e) {
handleError(e, ctx, 'nextTick');
}
} else if (_resolve) {
_resolve(ctx);
}
});
if (!pending) {
pending = true;
timerFunc();
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve) {
_resolve = resolve;
})
}
}
/* */
/* not type checking this file because flow doesn't play well with Proxy */
var initProxy;
if (true) {
var allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
);
var warnNonPresent = function (target, key) {
warn(
"Property or method \"" + key + "\" is not defined on the instance but " +
'referenced during render. Make sure that this property is reactive, ' +
'either in the data option, or for class-based components, by ' +
'initializing the property. ' +
'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.',
target
);
};
var warnReservedPrefix = function (target, key) {
warn(
"Property \"" + key + "\" must be accessed with \"$data." + key + "\" because " +
'properties starting with "$" or "_" are not proxied in the Vue instance to ' +
'prevent conflicts with Vue internals. ' +
'See: https://vuejs.org/v2/api/#data',
target
);
};
var hasProxy =
typeof Proxy !== 'undefined' && isNative(Proxy);
if (hasProxy) {
var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact');
config.keyCodes = new Proxy(config.keyCodes, {
set: function set (target, key, value) {
if (isBuiltInModifier(key)) {
warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key));
return false
} else {
target[key] = value;
return true
}
}
});
}
var hasHandler = {
has: function has (target, key) {
var has = key in target;
var isAllowed = allowedGlobals(key) ||
(typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data));
if (!has && !isAllowed) {
if (key in target.$data) { warnReservedPrefix(target, key); }
else { warnNonPresent(target, key); }
}
return has || !isAllowed
}
};
var getHandler = {
get: function get (target, key) {
if (typeof key === 'string' && !(key in target)) {
if (key in target.$data) { warnReservedPrefix(target, key); }
else { warnNonPresent(target, key); }
}
return target[key]
}
};
initProxy = function initProxy (vm) {
if (hasProxy) {
// determine which proxy handler to use
var options = vm.$options;
var handlers = options.render && options.render._withStripped
? getHandler
: hasHandler;
vm._renderProxy = new Proxy(vm, handlers);
} else {
vm._renderProxy = vm;
}
};
}
/* */
var seenObjects = new _Set();
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
function traverse (val) {
_traverse(val, seenObjects);
seenObjects.clear();
}
function _traverse (val, seen) {
var i, keys;
var isA = Array.isArray(val);
if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) {
return
}
if (val.__ob__) {
var depId = val.__ob__.dep.id;
if (seen.has(depId)) {
return
}
seen.add(depId);
}
if (isA) {
i = val.length;
while (i--) { _traverse(val[i], seen); }
} else {
keys = Object.keys(val);
i = keys.length;
while (i--) { _traverse(val[keys[i]], seen); }
}
}
var mark;
var measure;
if (true) {
var perf = inBrowser && window.performance;
/* istanbul ignore if */
if (
perf &&
perf.mark &&
perf.measure &&
perf.clearMarks &&
perf.clearMeasures
) {
mark = function (tag) { return perf.mark(tag); };
measure = function (name, startTag, endTag) {
perf.measure(name, startTag, endTag);
perf.clearMarks(startTag);
perf.clearMarks(endTag);
// perf.clearMeasures(name)
};
}
}
/* */
var normalizeEvent = cached(function (name) {
var passive = name.charAt(0) === '&';
name = passive ? name.slice(1) : name;
var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first
name = once$$1 ? name.slice(1) : name;
var capture = name.charAt(0) === '!';
name = capture ? name.slice(1) : name;
return {
name: name,
once: once$$1,
capture: capture,
passive: passive
}
});
function createFnInvoker (fns, vm) {
function invoker () {
var arguments$1 = arguments;
var fns = invoker.fns;
if (Array.isArray(fns)) {
var cloned = fns.slice();
for (var i = 0; i < cloned.length; i++) {
invokeWithErrorHandling(cloned[i], null, arguments$1, vm, "v-on handler");
}
} else {
// return handler return value for single handlers
return invokeWithErrorHandling(fns, null, arguments, vm, "v-on handler")
}
}
invoker.fns = fns;
return invoker
}
function updateListeners (
on,
oldOn,
add,
remove$$1,
createOnceHandler,
vm
) {
var name, def$$1, cur, old, event;
for (name in on) {
def$$1 = cur = on[name];
old = oldOn[name];
event = normalizeEvent(name);
if (isUndef(cur)) {
true && warn(
"Invalid handler for event \"" + (event.name) + "\": got " + String(cur),
vm
);
} else if (isUndef(old)) {
if (isUndef(cur.fns)) {
cur = on[name] = createFnInvoker(cur, vm);
}
if (isTrue(event.once)) {
cur = on[name] = createOnceHandler(event.name, cur, event.capture);
}
add(event.name, cur, event.capture, event.passive, event.params);
} else if (cur !== old) {
old.fns = cur;
on[name] = old;
}
}
for (name in oldOn) {
if (isUndef(on[name])) {
event = normalizeEvent(name);
remove$$1(event.name, oldOn[name], event.capture);
}
}
}
/* */
/* */
// fixed by xxxxxx (mp properties)
function extractPropertiesFromVNodeData(data, Ctor, res, context) {
var propOptions = Ctor.options.mpOptions && Ctor.options.mpOptions.properties;
if (isUndef(propOptions)) {
return res
}
var externalClasses = Ctor.options.mpOptions.externalClasses || [];
var attrs = data.attrs;
var props = data.props;
if (isDef(attrs) || isDef(props)) {
for (var key in propOptions) {
var altKey = hyphenate(key);
var result = checkProp(res, props, key, altKey, true) ||
checkProp(res, attrs, key, altKey, false);
// externalClass
if (
result &&
res[key] &&
externalClasses.indexOf(altKey) !== -1 &&
context[camelize(res[key])]
) {
// 赋值 externalClass 真正的值(模板里 externalClass 的值可能是字符串)
res[key] = context[camelize(res[key])];
}
}
}
return res
}
function extractPropsFromVNodeData (
data,
Ctor,
tag,
context// fixed by xxxxxx
) {
// we are only extracting raw values here.
// validation and default values are handled in the child
// component itself.
var propOptions = Ctor.options.props;
if (isUndef(propOptions)) {
// fixed by xxxxxx
return extractPropertiesFromVNodeData(data, Ctor, {}, context)
}
var res = {};
var attrs = data.attrs;
var props = data.props;
if (isDef(attrs) || isDef(props)) {
for (var key in propOptions) {
var altKey = hyphenate(key);
if (true) {
var keyInLowerCase = key.toLowerCase();
if (
key !== keyInLowerCase &&
attrs && hasOwn(attrs, keyInLowerCase)
) {
tip(
"Prop \"" + keyInLowerCase + "\" is passed to component " +
(formatComponentName(tag || Ctor)) + ", but the declared prop name is" +
" \"" + key + "\". " +
"Note that HTML attributes are case-insensitive and camelCased " +
"props need to use their kebab-case equivalents when using in-DOM " +
"templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"."
);
}
}
checkProp(res, props, key, altKey, true) ||
checkProp(res, attrs, key, altKey, false);
}
}
// fixed by xxxxxx
return extractPropertiesFromVNodeData(data, Ctor, res, context)
}
function checkProp (
res,
hash,
key,
altKey,
preserve
) {
if (isDef(hash)) {
if (hasOwn(hash, key)) {
res[key] = hash[key];
if (!preserve) {
delete hash[key];
}
return true
} else if (hasOwn(hash, altKey)) {
res[key] = hash[altKey];
if (!preserve) {
delete hash[altKey];
}
return true
}
}
return false
}
/* */
// The template compiler attempts to minimize the need for normalization by
// statically analyzing the template at compile time.
//
// For plain HTML markup, normalization can be completely skipped because the
// generated render function is guaranteed to return Array<VNode>. There are
// two cases where extra normalization is needed:
// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
function simpleNormalizeChildren (children) {
for (var i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children)
}
}
return children
}
// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
function normalizeChildren (children) {
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
function isTextNode (node) {
return isDef(node) && isDef(node.text) && isFalse(node.isComment)
}
function normalizeArrayChildren (children, nestedIndex) {
var res = [];
var i, c, lastIndex, last;
for (i = 0; i < children.length; i++) {
c = children[i];
if (isUndef(c) || typeof c === 'boolean') { continue }
lastIndex = res.length - 1;
last = res[lastIndex];
// nested
if (Array.isArray(c)) {
if (c.length > 0) {
c = normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i));
// merge adjacent text nodes
if (isTextNode(c[0]) && isTextNode(last)) {
res[lastIndex] = createTextVNode(last.text + (c[0]).text);
c.shift();
}
res.push.apply(res, c);
}
} else if (isPrimitive(c)) {
if (isTextNode(last)) {
// merge adjacent text nodes
// this is necessary for SSR hydration because text nodes are
// essentially merged when rendered to HTML strings
res[lastIndex] = createTextVNode(last.text + c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
}
} else {
if (isTextNode(c) && isTextNode(last)) {
// merge adjacent text nodes
res[lastIndex] = createTextVNode(last.text + c.text);
} else {
// default key for nested array children (likely generated by v-for)
if (isTrue(children._isVList) &&
isDef(c.tag) &&
isUndef(c.key) &&
isDef(nestedIndex)) {
c.key = "__vlist" + nestedIndex + "_" + i + "__";
}
res.push(c);
}
}
}
return res
}
/* */
function initProvide (vm) {
var provide = vm.$options.provide;
if (provide) {
vm._provided = typeof provide === 'function'
? provide.call(vm)
: provide;
}
}
function initInjections (vm) {
var result = resolveInject(vm.$options.inject, vm);
if (result) {
toggleObserving(false);
Object.keys(result).forEach(function (key) {
/* istanbul ignore else */
if (true) {
defineReactive$$1(vm, key, result[key], function () {
warn(
"Avoid mutating an injected value directly since the changes will be " +
"overwritten whenever the provided component re-renders. " +
"injection being mutated: \"" + key + "\"",
vm
);
});
} else {}
});
toggleObserving(true);
}
}
function resolveInject (inject, vm) {
if (inject) {
// inject is :any because flow is not smart enough to figure out cached
var result = Object.create(null);
var keys = hasSymbol
? Reflect.ownKeys(inject)
: Object.keys(inject);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
// #6574 in case the inject object is observed...
if (key === '__ob__') { continue }
var provideKey = inject[key].from;
var source = vm;
while (source) {
if (source._provided && hasOwn(source._provided, provideKey)) {
result[key] = source._provided[provideKey];
break
}
source = source.$parent;
}
if (!source) {
if ('default' in inject[key]) {
var provideDefault = inject[key].default;
result[key] = typeof provideDefault === 'function'
? provideDefault.call(vm)
: provideDefault;
} else if (true) {
warn(("Injection \"" + key + "\" not found"), vm);
}
}
}
return result
}
}
/* */
/**
* Runtime helper for resolving raw children VNodes into a slot object.
*/
function resolveSlots (
children,
context
) {
if (!children || !children.length) {
return {}
}
var slots = {};
for (var i = 0, l = children.length; i < l; i++) {
var child = children[i];
var data = child.data;
// remove slot attribute if the node is resolved as a Vue slot node
if (data && data.attrs && data.attrs.slot) {
delete data.attrs.slot;
}
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.fnContext === context) &&
data && data.slot != null
) {
var name = data.slot;
var slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
slot.push.apply(slot, child.children || []);
} else {
slot.push(child);
}
} else {
// fixed by xxxxxx 临时 hack 掉 uni-app 中的异步 name slot page
if(child.asyncMeta && child.asyncMeta.data && child.asyncMeta.data.slot === 'page'){
(slots['page'] || (slots['page'] = [])).push(child);
}else{
(slots.default || (slots.default = [])).push(child);
}
}
}
// ignore slots that contains only whitespace
for (var name$1 in slots) {
if (slots[name$1].every(isWhitespace)) {
delete slots[name$1];
}
}
return slots
}
function isWhitespace (node) {
return (node.isComment && !node.asyncFactory) || node.text === ' '
}
/* */
function normalizeScopedSlots (
slots,
normalSlots,
prevSlots
) {
var res;
var hasNormalSlots = Object.keys(normalSlots).length > 0;
var isStable = slots ? !!slots.$stable : !hasNormalSlots;
var key = slots && slots.$key;
if (!slots) {
res = {};
} else if (slots._normalized) {
// fast path 1: child component re-render only, parent did not change
return slots._normalized
} else if (
isStable &&
prevSlots &&
prevSlots !== emptyObject &&
key === prevSlots.$key &&
!hasNormalSlots &&
!prevSlots.$hasNormal
) {
// fast path 2: stable scoped slots w/ no normal slots to proxy,
// only need to normalize once
return prevSlots
} else {
res = {};
for (var key$1 in slots) {
if (slots[key$1] && key$1[0] !== '$') {
res[key$1] = normalizeScopedSlot(normalSlots, key$1, slots[key$1]);
}
}
}
// expose normal slots on scopedSlots
for (var key$2 in normalSlots) {
if (!(key$2 in res)) {
res[key$2] = proxyNormalSlot(normalSlots, key$2);
}
}
// avoriaz seems to mock a non-extensible $scopedSlots object
// and when that is passed down this would cause an error
if (slots && Object.isExtensible(slots)) {
(slots)._normalized = res;
}
def(res, '$stable', isStable);
def(res, '$key', key);
def(res, '$hasNormal', hasNormalSlots);
return res
}
function normalizeScopedSlot(normalSlots, key, fn) {
var normalized = function () {
var res = arguments.length ? fn.apply(null, arguments) : fn({});
res = res && typeof res === 'object' && !Array.isArray(res)
? [res] // single vnode
: normalizeChildren(res);
return res && (
res.length === 0 ||
(res.length === 1 && res[0].isComment) // #9658
) ? undefined
: res
};
// this is a slot using the new v-slot syntax without scope. although it is
// compiled as a scoped slot, render fn users would expect it to be present
// on this.$slots because the usage is semantically a normal slot.
if (fn.proxy) {
Object.defineProperty(normalSlots, key, {
get: normalized,
enumerable: true,
configurable: true
});
}
return normalized
}
function proxyNormalSlot(slots, key) {
return function () { return slots[key]; }
}
/* */
/**
* Runtime helper for rendering v-for lists.
*/
function renderList (
val,
render
) {
var ret, i, l, keys, key;
if (Array.isArray(val) || typeof val === 'string') {
ret = new Array(val.length);
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i, i, i); // fixed by xxxxxx
}
} else if (typeof val === 'number') {
ret = new Array(val);
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i, i, i); // fixed by xxxxxx
}
} else if (isObject(val)) {
if (hasSymbol && val[Symbol.iterator]) {
ret = [];
var iterator = val[Symbol.iterator]();
var result = iterator.next();
while (!result.done) {
ret.push(render(result.value, ret.length, i, i++)); // fixed by xxxxxx
result = iterator.next();
}
} else {
keys = Object.keys(val);
ret = new Array(keys.length);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[i] = render(val[key], key, i, i); // fixed by xxxxxx
}
}
}
if (!isDef(ret)) {
ret = [];
}
(ret)._isVList = true;
return ret
}
/* */
/**
* Runtime helper for rendering <slot>
*/
function renderSlot (
name,
fallback,
props,
bindObject
) {
var scopedSlotFn = this.$scopedSlots[name];
var nodes;
if (scopedSlotFn) { // scoped slot
props = props || {};
if (bindObject) {
if ( true && !isObject(bindObject)) {
warn(
'slot v-bind without argument expects an Object',
this
);
}
props = extend(extend({}, bindObject), props);
}
// fixed by xxxxxx app-plus scopedSlot
nodes = scopedSlotFn(props, this, props._i) || fallback;
} else {
nodes = this.$slots[name] || fallback;
}
var target = props && props.slot;
if (target) {
return this.$createElement('template', { slot: target }, nodes)
} else {
return nodes
}
}
/* */
/**
* Runtime helper for resolving filters
*/
function resolveFilter (id) {
return resolveAsset(this.$options, 'filters', id, true) || identity
}
/* */
function isKeyNotMatch (expect, actual) {
if (Array.isArray(expect)) {
return expect.indexOf(actual) === -1
} else {
return expect !== actual
}
}
/**
* Runtime helper for checking keyCodes from config.
* exposed as Vue.prototype._k
* passing in eventKeyName as last argument separately for backwards compat
*/
function checkKeyCodes (
eventKeyCode,
key,
builtInKeyCode,
eventKeyName,
builtInKeyName
) {
var mappedKeyCode = config.keyCodes[key] || builtInKeyCode;
if (builtInKeyName && eventKeyName && !config.keyCodes[key]) {
return isKeyNotMatch(builtInKeyName, eventKeyName)
} else if (mappedKeyCode) {
return isKeyNotMatch(mappedKeyCode, eventKeyCode)
} else if (eventKeyName) {
return hyphenate(eventKeyName) !== key
}
}
/* */
/**
* Runtime helper for merging v-bind="object" into a VNode's data.
*/
function bindObjectProps (
data,
tag,
value,
asProp,
isSync
) {
if (value) {
if (!isObject(value)) {
true && warn(
'v-bind without argument expects an Object or Array value',
this
);
} else {
if (Array.isArray(value)) {
value = toObject(value);
}
var hash;
var loop = function ( key ) {
if (
key === 'class' ||
key === 'style' ||
isReservedAttribute(key)
) {
hash = data;
} else {
var type = data.attrs && data.attrs.type;
hash = asProp || config.mustUseProp(tag, type, key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {});
}
var camelizedKey = camelize(key);
var hyphenatedKey = hyphenate(key);
if (!(camelizedKey in hash) && !(hyphenatedKey in hash)) {
hash[key] = value[key];
if (isSync) {
var on = data.on || (data.on = {});
on[("update:" + key)] = function ($event) {
value[key] = $event;
};
}
}
};
for (var key in value) loop( key );
}
}
return data
}
/* */
/**
* Runtime helper for rendering static trees.
*/
function renderStatic (
index,
isInFor
) {
var cached = this._staticTrees || (this._staticTrees = []);
var tree = cached[index];
// if has already-rendered static tree and not inside v-for,
// we can reuse the same tree.
if (tree && !isInFor) {
return tree
}
// otherwise, render a fresh tree.
tree = cached[index] = this.$options.staticRenderFns[index].call(
this._renderProxy,
null,
this // for render fns generated for functional component templates
);
markStatic(tree, ("__static__" + index), false);
return tree
}
/**
* Runtime helper for v-once.
* Effectively it means marking the node as static with a unique key.
*/
function markOnce (
tree,
index,
key
) {
markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true);
return tree
}
function markStatic (
tree,
key,
isOnce
) {
if (Array.isArray(tree)) {
for (var i = 0; i < tree.length; i++) {
if (tree[i] && typeof tree[i] !== 'string') {
markStaticNode(tree[i], (key + "_" + i), isOnce);
}
}
} else {
markStaticNode(tree, key, isOnce);
}
}
function markStaticNode (node, key, isOnce) {
node.isStatic = true;
node.key = key;
node.isOnce = isOnce;
}
/* */
function bindObjectListeners (data, value) {
if (value) {
if (!isPlainObject(value)) {
true && warn(
'v-on without argument expects an Object value',
this
);
} else {
var on = data.on = data.on ? extend({}, data.on) : {};
for (var key in value) {
var existing = on[key];
var ours = value[key];
on[key] = existing ? [].concat(existing, ours) : ours;
}
}
}
return data
}
/* */
function resolveScopedSlots (
fns, // see flow/vnode
res,
// the following are added in 2.6
hasDynamicKeys,
contentHashKey
) {
res = res || { $stable: !hasDynamicKeys };
for (var i = 0; i < fns.length; i++) {
var slot = fns[i];
if (Array.isArray(slot)) {
resolveScopedSlots(slot, res, hasDynamicKeys);
} else if (slot) {
// marker for reverse proxying v-slot without scope on this.$slots
if (slot.proxy) {
slot.fn.proxy = true;
}
res[slot.key] = slot.fn;
}
}
if (contentHashKey) {
(res).$key = contentHashKey;
}
return res
}
/* */
function bindDynamicKeys (baseObj, values) {
for (var i = 0; i < values.length; i += 2) {
var key = values[i];
if (typeof key === 'string' && key) {
baseObj[values[i]] = values[i + 1];
} else if ( true && key !== '' && key !== null) {
// null is a special value for explicitly removing a binding
warn(
("Invalid value for dynamic directive argument (expected string or null): " + key),
this
);
}
}
return baseObj
}
// helper to dynamically append modifier runtime markers to event names.
// ensure only append when value is already string, otherwise it will be cast
// to string and cause the type check to miss.
function prependModifier (value, symbol) {
return typeof value === 'string' ? symbol + value : value
}
/* */
function installRenderHelpers (target) {
target._o = markOnce;
target._n = toNumber;
target._s = toString;
target._l = renderList;
target._t = renderSlot;
target._q = looseEqual;
target._i = looseIndexOf;
target._m = renderStatic;
target._f = resolveFilter;
target._k = checkKeyCodes;
target._b = bindObjectProps;
target._v = createTextVNode;
target._e = createEmptyVNode;
target._u = resolveScopedSlots;
target._g = bindObjectListeners;
target._d = bindDynamicKeys;
target._p = prependModifier;
}
/* */
function FunctionalRenderContext (
data,
props,
children,
parent,
Ctor
) {
var this$1 = this;
var options = Ctor.options;
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
var contextVm;
if (hasOwn(parent, '_uid')) {
contextVm = Object.create(parent);
// $flow-disable-line
contextVm._original = parent;
} else {
// the context vm passed in is a functional context as well.
// in this case we want to make sure we are able to get a hold to the
// real context instance.
contextVm = parent;
// $flow-disable-line
parent = parent._original;
}
var isCompiled = isTrue(options._compiled);
var needNormalization = !isCompiled;
this.data = data;
this.props = props;
this.children = children;
this.parent = parent;
this.listeners = data.on || emptyObject;
this.injections = resolveInject(options.inject, parent);
this.slots = function () {
if (!this$1.$slots) {
normalizeScopedSlots(
data.scopedSlots,
this$1.$slots = resolveSlots(children, parent)
);
}
return this$1.$slots
};
Object.defineProperty(this, 'scopedSlots', ({
enumerable: true,
get: function get () {
return normalizeScopedSlots(data.scopedSlots, this.slots())
}
}));
// support for compiled functional template
if (isCompiled) {
// exposing $options for renderStatic()
this.$options = options;
// pre-resolve slots for renderSlot()
this.$slots = this.slots();
this.$scopedSlots = normalizeScopedSlots(data.scopedSlots, this.$slots);
}
if (options._scopeId) {
this._c = function (a, b, c, d) {
var vnode = createElement(contextVm, a, b, c, d, needNormalization);
if (vnode && !Array.isArray(vnode)) {
vnode.fnScopeId = options._scopeId;
vnode.fnContext = parent;
}
return vnode
};
} else {
this._c = function (a, b, c, d) { return createElement(contextVm, a, b, c, d, needNormalization); };
}
}
installRenderHelpers(FunctionalRenderContext.prototype);
function createFunctionalComponent (
Ctor,
propsData,
data,
contextVm,
children
) {
var options = Ctor.options;
var props = {};
var propOptions = options.props;
if (isDef(propOptions)) {
for (var key in propOptions) {
props[key] = validateProp(key, propOptions, propsData || emptyObject);
}
} else {
if (isDef(data.attrs)) { mergeProps(props, data.attrs); }
if (isDef(data.props)) { mergeProps(props, data.props); }
}
var renderContext = new FunctionalRenderContext(
data,
props,
children,
contextVm,
Ctor
);
var vnode = options.render.call(null, renderContext._c, renderContext);
if (vnode instanceof VNode) {
return cloneAndMarkFunctionalResult(vnode, data, renderContext.parent, options, renderContext)
} else if (Array.isArray(vnode)) {
var vnodes = normalizeChildren(vnode) || [];
var res = new Array(vnodes.length);
for (var i = 0; i < vnodes.length; i++) {
res[i] = cloneAndMarkFunctionalResult(vnodes[i], data, renderContext.parent, options, renderContext);
}
return res
}
}
function cloneAndMarkFunctionalResult (vnode, data, contextVm, options, renderContext) {
// #7817 clone node before setting fnContext, otherwise if the node is reused
// (e.g. it was from a cached normal slot) the fnContext causes named slots
// that should not be matched to match.
var clone = cloneVNode(vnode);
clone.fnContext = contextVm;
clone.fnOptions = options;
if (true) {
(clone.devtoolsMeta = clone.devtoolsMeta || {}).renderContext = renderContext;
}
if (data.slot) {
(clone.data || (clone.data = {})).slot = data.slot;
}
return clone
}
function mergeProps (to, from) {
for (var key in from) {
to[camelize(key)] = from[key];
}
}
/* */
/* */
/* */
/* */
// inline hooks to be invoked on component VNodes during patch
var componentVNodeHooks = {
init: function init (vnode, hydrating) {
if (
vnode.componentInstance &&
!vnode.componentInstance._isDestroyed &&
vnode.data.keepAlive
) {
// kept-alive components, treat as a patch
var mountedNode = vnode; // work around flow
componentVNodeHooks.prepatch(mountedNode, mountedNode);
} else {
var child = vnode.componentInstance = createComponentInstanceForVnode(
vnode,
activeInstance
);
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
}
},
prepatch: function prepatch (oldVnode, vnode) {
var options = vnode.componentOptions;
var child = vnode.componentInstance = oldVnode.componentInstance;
updateChildComponent(
child,
options.propsData, // updated props
options.listeners, // updated listeners
vnode, // new parent vnode
options.children // new children
);
},
insert: function insert (vnode) {
var context = vnode.context;
var componentInstance = vnode.componentInstance;
if (!componentInstance._isMounted) {
callHook(componentInstance, 'onServiceCreated');
callHook(componentInstance, 'onServiceAttached');
componentInstance._isMounted = true;
callHook(componentInstance, 'mounted');
}
if (vnode.data.keepAlive) {
if (context._isMounted) {
// vue-router#1212
// During updates, a kept-alive component's child components may
// change, so directly walking the tree here may call activated hooks
// on incorrect children. Instead we push them into a queue which will
// be processed after the whole patch process ended.
queueActivatedComponent(componentInstance);
} else {
activateChildComponent(componentInstance, true /* direct */);
}
}
},
destroy: function destroy (vnode) {
var componentInstance = vnode.componentInstance;
if (!componentInstance._isDestroyed) {
if (!vnode.data.keepAlive) {
componentInstance.$destroy();
} else {
deactivateChildComponent(componentInstance, true /* direct */);
}
}
}
};
var hooksToMerge = Object.keys(componentVNodeHooks);
function createComponent (
Ctor,
data,
context,
children,
tag
) {
if (isUndef(Ctor)) {
return
}
var baseCtor = context.$options._base;
// plain options object: turn it into a constructor
if (isObject(Ctor)) {
Ctor = baseCtor.extend(Ctor);
}
// if at this stage it's not a constructor or an async component factory,
// reject.
if (typeof Ctor !== 'function') {
if (true) {
warn(("Invalid Component definition: " + (String(Ctor))), context);
}
return
}
// async component
var asyncFactory;
if (isUndef(Ctor.cid)) {
asyncFactory = Ctor;
Ctor = resolveAsyncComponent(asyncFactory, baseCtor);
if (Ctor === undefined) {
// return a placeholder node for async component, which is rendered
// as a comment node but preserves all the raw information for the node.
// the information will be used for async server-rendering and hydration.
return createAsyncPlaceholder(
asyncFactory,
data,
context,
children,
tag
)
}
}
data = data || {};
// resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor);
// transform component v-model data into props & events
if (isDef(data.model)) {
transformModel(Ctor.options, data);
}
// extract props
var propsData = extractPropsFromVNodeData(data, Ctor, tag, context); // fixed by xxxxxx
// functional component
if (isTrue(Ctor.options.functional)) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
var listeners = data.on;
// replace with listeners with .native modifier
// so it gets processed during parent component patch.
data.on = data.nativeOn;
if (isTrue(Ctor.options.abstract)) {
// abstract components do not keep anything
// other than props & listeners & slot
// work around flow
var slot = data.slot;
data = {};
if (slot) {
data.slot = slot;
}
}
// install component management hooks onto the placeholder node
installComponentHooks(data);
// return a placeholder vnode
var name = Ctor.options.name || tag;
var vnode = new VNode(
("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
data, undefined, undefined, undefined, context,
{ Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children },
asyncFactory
);
return vnode
}
function createComponentInstanceForVnode (
vnode, // we know it's MountedComponentVNode but flow doesn't
parent // activeInstance in lifecycle state
) {
var options = {
_isComponent: true,
_parentVnode: vnode,
parent: parent
};
// check inline-template render functions
var inlineTemplate = vnode.data.inlineTemplate;
if (isDef(inlineTemplate)) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnode.componentOptions.Ctor(options)
}
function installComponentHooks (data) {
var hooks = data.hook || (data.hook = {});
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i];
var existing = hooks[key];
var toMerge = componentVNodeHooks[key];
if (existing !== toMerge && !(existing && existing._merged)) {
hooks[key] = existing ? mergeHook$1(toMerge, existing) : toMerge;
}
}
}
function mergeHook$1 (f1, f2) {
var merged = function (a, b) {
// flow complains about extra args which is why we use any
f1(a, b);
f2(a, b);
};
merged._merged = true;
return merged
}
// transform component v-model info (value and callback) into
// prop and event handler respectively.
function transformModel (options, data) {
var prop = (options.model && options.model.prop) || 'value';
var event = (options.model && options.model.event) || 'input'
;(data.attrs || (data.attrs = {}))[prop] = data.model.value;
var on = data.on || (data.on = {});
var existing = on[event];
var callback = data.model.callback;
if (isDef(existing)) {
if (
Array.isArray(existing)
? existing.indexOf(callback) === -1
: existing !== callback
) {
on[event] = [callback].concat(existing);
}
} else {
on[event] = callback;
}
}
/* */
var SIMPLE_NORMALIZE = 1;
var ALWAYS_NORMALIZE = 2;
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
function createElement (
context,
tag,
data,
children,
normalizationType,
alwaysNormalize
) {
if (Array.isArray(data) || isPrimitive(data)) {
normalizationType = children;
children = data;
data = undefined;
}
if (isTrue(alwaysNormalize)) {
normalizationType = ALWAYS_NORMALIZE;
}
return _createElement(context, tag, data, children, normalizationType)
}
function _createElement (
context,
tag,
data,
children,
normalizationType
) {
if (isDef(data) && isDef((data).__ob__)) {
true && warn(
"Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" +
'Always create fresh vnode data objects in each render!',
context
);
return createEmptyVNode()
}
// object syntax in v-bind
if (isDef(data) && isDef(data.is)) {
tag = data.is;
}
if (!tag) {
// in case of component :is set to falsy value
return createEmptyVNode()
}
// warn against non-primitive key
if ( true &&
isDef(data) && isDef(data.key) && !isPrimitive(data.key)
) {
{
warn(
'Avoid using non-primitive value as key, ' +
'use string/number value instead.',
context
);
}
}
// support single function children as default scoped slot
if (Array.isArray(children) &&
typeof children[0] === 'function'
) {
data = data || {};
data.scopedSlots = { default: children[0] };
children.length = 0;
}
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children);
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children);
}
var vnode, ns;
if (typeof tag === 'string') {
var Ctor;
ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// platform built-in elements
if ( true && isDef(data) && isDef(data.nativeOn)) {
warn(
("The .native modifier for v-on is only valid on components but it was used on <" + tag + ">."),
context
);
}
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
);
} else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
vnode = createComponent(Ctor, data, context, children, tag);
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
vnode = new VNode(
tag, data, children,
undefined, undefined, context
);
}
} else {
// direct component options / constructor
vnode = createComponent(tag, data, context, children);
}
if (Array.isArray(vnode)) {
return vnode
} else if (isDef(vnode)) {
if (isDef(ns)) { applyNS(vnode, ns); }
if (isDef(data)) { registerDeepBindings(data); }
return vnode
} else {
return createEmptyVNode()
}
}
function applyNS (vnode, ns, force) {
vnode.ns = ns;
if (vnode.tag === 'foreignObject') {
// use default namespace inside foreignObject
ns = undefined;
force = true;
}
if (isDef(vnode.children)) {
for (var i = 0, l = vnode.children.length; i < l; i++) {
var child = vnode.children[i];
if (isDef(child.tag) && (
isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) {
applyNS(child, ns, force);
}
}
}
}
// ref #5318
// necessary to ensure parent re-render when deep bindings like :style and
// :class are used on slot nodes
function registerDeepBindings (data) {
if (isObject(data.style)) {
traverse(data.style);
}
if (isObject(data.class)) {
traverse(data.class);
}
}
/* */
function initRender (vm) {
vm._vnode = null; // the root of the child tree
vm._staticTrees = null; // v-once cached trees
var options = vm.$options;
var parentVnode = vm.$vnode = options._parentVnode; // the placeholder node in parent tree
var renderContext = parentVnode && parentVnode.context;
vm.$slots = resolveSlots(options._renderChildren, renderContext);
vm.$scopedSlots = emptyObject;
// bind the createElement fn to this instance
// so that we get proper render context inside it.
// args order: tag, data, children, normalizationType, alwaysNormalize
// internal version is used by render functions compiled from templates
vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); };
// normalization is always applied for the public version, used in
// user-written render functions.
vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
// $attrs & $listeners are exposed for easier HOC creation.
// they need to be reactive so that HOCs using them are always updated
var parentData = parentVnode && parentVnode.data;
/* istanbul ignore else */
if (true) {
defineReactive$$1(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () {
!isUpdatingChildComponent && warn("$attrs is readonly.", vm);
}, true);
defineReactive$$1(vm, '$listeners', options._parentListeners || emptyObject, function () {
!isUpdatingChildComponent && warn("$listeners is readonly.", vm);
}, true);
} else {}
}
var currentRenderingInstance = null;
function renderMixin (Vue) {
// install runtime convenience helpers
installRenderHelpers(Vue.prototype);
Vue.prototype.$nextTick = function (fn) {
return nextTick(fn, this)
};
Vue.prototype._render = function () {
var vm = this;
var ref = vm.$options;
var render = ref.render;
var _parentVnode = ref._parentVnode;
if (_parentVnode) {
vm.$scopedSlots = normalizeScopedSlots(
_parentVnode.data.scopedSlots,
vm.$slots,
vm.$scopedSlots
);
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode;
// render self
var vnode;
try {
// There's no need to maintain a stack because all render fns are called
// separately from one another. Nested component's render fns are called
// when parent component is patched.
currentRenderingInstance = vm;
vnode = render.call(vm._renderProxy, vm.$createElement);
} catch (e) {
handleError(e, vm, "render");
// return error render result,
// or previous vnode to prevent render error causing blank component
/* istanbul ignore else */
if ( true && vm.$options.renderError) {
try {
vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e);
} catch (e) {
handleError(e, vm, "renderError");
vnode = vm._vnode;
}
} else {
vnode = vm._vnode;
}
} finally {
currentRenderingInstance = null;
}
// if the returned array contains only a single node, allow it
if (Array.isArray(vnode) && vnode.length === 1) {
vnode = vnode[0];
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if ( true && Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
);
}
vnode = createEmptyVNode();
}
// set parent
vnode.parent = _parentVnode;
return vnode
};
}
/* */
function ensureCtor (comp, base) {
if (
comp.__esModule ||
(hasSymbol && comp[Symbol.toStringTag] === 'Module')
) {
comp = comp.default;
}
return isObject(comp)
? base.extend(comp)
: comp
}
function createAsyncPlaceholder (
factory,
data,
context,
children,
tag
) {
var node = createEmptyVNode();
node.asyncFactory = factory;
node.asyncMeta = { data: data, context: context, children: children, tag: tag };
return node
}
function resolveAsyncComponent (
factory,
baseCtor
) {
if (isTrue(factory.error) && isDef(factory.errorComp)) {
return factory.errorComp
}
if (isDef(factory.resolved)) {
return factory.resolved
}
var owner = currentRenderingInstance;
if (owner && isDef(factory.owners) && factory.owners.indexOf(owner) === -1) {
// already pending
factory.owners.push(owner);
}
if (isTrue(factory.loading) && isDef(factory.loadingComp)) {
return factory.loadingComp
}
if (owner && !isDef(factory.owners)) {
var owners = factory.owners = [owner];
var sync = true;
var timerLoading = null;
var timerTimeout = null
;(owner).$on('hook:destroyed', function () { return remove(owners, owner); });
var forceRender = function (renderCompleted) {
for (var i = 0, l = owners.length; i < l; i++) {
(owners[i]).$forceUpdate();
}
if (renderCompleted) {
owners.length = 0;
if (timerLoading !== null) {
clearTimeout(timerLoading);
timerLoading = null;
}
if (timerTimeout !== null) {
clearTimeout(timerTimeout);
timerTimeout = null;
}
}
};
var resolve = once(function (res) {
// cache resolved
factory.resolved = ensureCtor(res, baseCtor);
// invoke callbacks only if this is not a synchronous resolve
// (async resolves are shimmed as synchronous during SSR)
if (!sync) {
forceRender(true);
} else {
owners.length = 0;
}
});
var reject = once(function (reason) {
true && warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
);
if (isDef(factory.errorComp)) {
factory.error = true;
forceRender(true);
}
});
var res = factory(resolve, reject);
if (isObject(res)) {
if (isPromise(res)) {
// () => Promise
if (isUndef(factory.resolved)) {
res.then(resolve, reject);
}
} else if (isPromise(res.component)) {
res.component.then(resolve, reject);
if (isDef(res.error)) {
factory.errorComp = ensureCtor(res.error, baseCtor);
}
if (isDef(res.loading)) {
factory.loadingComp = ensureCtor(res.loading, baseCtor);
if (res.delay === 0) {
factory.loading = true;
} else {
timerLoading = setTimeout(function () {
timerLoading = null;
if (isUndef(factory.resolved) && isUndef(factory.error)) {
factory.loading = true;
forceRender(false);
}
}, res.delay || 200);
}
}
if (isDef(res.timeout)) {
timerTimeout = setTimeout(function () {
timerTimeout = null;
if (isUndef(factory.resolved)) {
reject(
true
? ("timeout (" + (res.timeout) + "ms)")
: undefined
);
}
}, res.timeout);
}
}
}
sync = false;
// return in case resolved synchronously
return factory.loading
? factory.loadingComp
: factory.resolved
}
}
/* */
function isAsyncPlaceholder (node) {
return node.isComment && node.asyncFactory
}
/* */
function getFirstComponentChild (children) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var c = children[i];
if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) {
return c
}
}
}
}
/* */
/* */
function initEvents (vm) {
vm._events = Object.create(null);
vm._hasHookEvent = false;
// init parent attached events
var listeners = vm.$options._parentListeners;
if (listeners) {
updateComponentListeners(vm, listeners);
}
}
var target;
function add (event, fn) {
target.$on(event, fn);
}
function remove$1 (event, fn) {
target.$off(event, fn);
}
function createOnceHandler (event, fn) {
var _target = target;
return function onceHandler () {
var res = fn.apply(null, arguments);
if (res !== null) {
_target.$off(event, onceHandler);
}
}
}
function updateComponentListeners (
vm,
listeners,
oldListeners
) {
target = vm;
updateListeners(listeners, oldListeners || {}, add, remove$1, createOnceHandler, vm);
target = undefined;
}
function eventsMixin (Vue) {
var hookRE = /^hook:/;
Vue.prototype.$on = function (event, fn) {
var vm = this;
if (Array.isArray(event)) {
for (var i = 0, l = event.length; i < l; i++) {
vm.$on(event[i], fn);
}
} else {
(vm._events[event] || (vm._events[event] = [])).push(fn);
// optimize hook:event cost by using a boolean flag marked at registration
// instead of a hash lookup
if (hookRE.test(event)) {
vm._hasHookEvent = true;
}
}
return vm
};
Vue.prototype.$once = function (event, fn) {
var vm = this;
function on () {
vm.$off(event, on);
fn.apply(vm, arguments);
}
on.fn = fn;
vm.$on(event, on);
return vm
};
Vue.prototype.$off = function (event, fn) {
var vm = this;
// all
if (!arguments.length) {
vm._events = Object.create(null);
return vm
}
// array of events
if (Array.isArray(event)) {
for (var i$1 = 0, l = event.length; i$1 < l; i$1++) {
vm.$off(event[i$1], fn);
}
return vm
}
// specific event
var cbs = vm._events[event];
if (!cbs) {
return vm
}
if (!fn) {
vm._events[event] = null;
return vm
}
// specific handler
var cb;
var i = cbs.length;
while (i--) {
cb = cbs[i];
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1);
break
}
}
return vm
};
Vue.prototype.$emit = function (event) {
var vm = this;
if (true) {
var lowerCaseEvent = event.toLowerCase();
if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
tip(
"Event \"" + lowerCaseEvent + "\" is emitted in component " +
(formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " +
"Note that HTML attributes are case-insensitive and you cannot use " +
"v-on to listen to camelCase events when using in-DOM templates. " +
"You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"."
);
}
}
var cbs = vm._events[event];
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs;
var args = toArray(arguments, 1);
var info = "event handler for \"" + event + "\"";
for (var i = 0, l = cbs.length; i < l; i++) {
invokeWithErrorHandling(cbs[i], vm, args, vm, info);
}
}
return vm
};
}
/* */
var activeInstance = null;
var isUpdatingChildComponent = false;
function setActiveInstance(vm) {
var prevActiveInstance = activeInstance;
activeInstance = vm;
return function () {
activeInstance = prevActiveInstance;
}
}
function initLifecycle (vm) {
var options = vm.$options;
// locate first non-abstract parent
var parent = options.parent;
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent;
}
parent.$children.push(vm);
}
vm.$parent = parent;
vm.$root = parent ? parent.$root : vm;
vm.$children = [];
vm.$refs = {};
vm._watcher = null;
vm._inactive = null;
vm._directInactive = false;
vm._isMounted = false;
vm._isDestroyed = false;
vm._isBeingDestroyed = false;
}
function lifecycleMixin (Vue) {
Vue.prototype._update = function (vnode, hydrating) {
var vm = this;
var prevEl = vm.$el;
var prevVnode = vm._vnode;
var restoreActiveInstance = setActiveInstance(vm);
vm._vnode = vnode;
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */);
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode);
}
restoreActiveInstance();
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null;
}
if (vm.$el) {
vm.$el.__vue__ = vm;
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el;
}
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
};
Vue.prototype.$forceUpdate = function () {
var vm = this;
if (vm._watcher) {
vm._watcher.update();
}
};
Vue.prototype.$destroy = function () {
var vm = this;
if (vm._isBeingDestroyed) {
return
}
callHook(vm, 'beforeDestroy');
vm._isBeingDestroyed = true;
// remove self from parent
var parent = vm.$parent;
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
remove(parent.$children, vm);
}
// teardown watchers
if (vm._watcher) {
vm._watcher.teardown();
}
var i = vm._watchers.length;
while (i--) {
vm._watchers[i].teardown();
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
vm._data.__ob__.vmCount--;
}
// call the last hook...
vm._isDestroyed = true;
// invoke destroy hooks on current rendered tree
vm.__patch__(vm._vnode, null);
// fire destroyed hook
callHook(vm, 'destroyed');
// turn off all instance listeners.
vm.$off();
// remove __vue__ reference
if (vm.$el) {
vm.$el.__vue__ = null;
}
// release circular reference (#6759)
if (vm.$vnode) {
vm.$vnode.parent = null;
}
};
}
function updateChildComponent (
vm,
propsData,
listeners,
parentVnode,
renderChildren
) {
if (true) {
isUpdatingChildComponent = true;
}
// determine whether component has slot children
// we need to do this before overwriting $options._renderChildren.
// check if there are dynamic scopedSlots (hand-written or compiled but with
// dynamic slot names). Static scoped slots compiled from template has the
// "$stable" marker.
var newScopedSlots = parentVnode.data.scopedSlots;
var oldScopedSlots = vm.$scopedSlots;
var hasDynamicScopedSlot = !!(
(newScopedSlots && !newScopedSlots.$stable) ||
(oldScopedSlots !== emptyObject && !oldScopedSlots.$stable) ||
(newScopedSlots && vm.$scopedSlots.$key !== newScopedSlots.$key)
);
// Any static slot children from the parent may have changed during parent's
// update. Dynamic scoped slots may also have changed. In such cases, a forced
// update is necessary to ensure correctness.
var needsForceUpdate = !!(
renderChildren || // has new static slots
vm.$options._renderChildren || // has old static slots
hasDynamicScopedSlot
);
vm.$options._parentVnode = parentVnode;
vm.$vnode = parentVnode; // update vm's placeholder node without re-render
if (vm._vnode) { // update child tree's parent
vm._vnode.parent = parentVnode;
}
vm.$options._renderChildren = renderChildren;
// update $attrs and $listeners hash
// these are also reactive so they may trigger child update if the child
// used them during render
vm.$attrs = parentVnode.data.attrs || emptyObject;
vm.$listeners = listeners || emptyObject;
// update props
if (propsData && vm.$options.props) {
toggleObserving(false);
var props = vm._props;
var propKeys = vm.$options._propKeys || [];
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i];
var propOptions = vm.$options.props; // wtf flow?
props[key] = validateProp(key, propOptions, propsData, vm);
}
toggleObserving(true);
// keep a copy of raw propsData
vm.$options.propsData = propsData;
}
// fixed by xxxxxx update properties(mp runtime)
vm._$updateProperties && vm._$updateProperties(vm);
// update listeners
listeners = listeners || emptyObject;
var oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners;
updateComponentListeners(vm, listeners, oldListeners);
// resolve slots + force update if has children
if (needsForceUpdate) {
vm.$slots = resolveSlots(renderChildren, parentVnode.context);
vm.$forceUpdate();
}
if (true) {
isUpdatingChildComponent = false;
}
}
function isInInactiveTree (vm) {
while (vm && (vm = vm.$parent)) {
if (vm._inactive) { return true }
}
return false
}
function activateChildComponent (vm, direct) {
if (direct) {
vm._directInactive = false;
if (isInInactiveTree(vm)) {
return
}
} else if (vm._directInactive) {
return
}
if (vm._inactive || vm._inactive === null) {
vm._inactive = false;
for (var i = 0; i < vm.$children.length; i++) {
activateChildComponent(vm.$children[i]);
}
callHook(vm, 'activated');
}
}
function deactivateChildComponent (vm, direct) {
if (direct) {
vm._directInactive = true;
if (isInInactiveTree(vm)) {
return
}
}
if (!vm._inactive) {
vm._inactive = true;
for (var i = 0; i < vm.$children.length; i++) {
deactivateChildComponent(vm.$children[i]);
}
callHook(vm, 'deactivated');
}
}
function callHook (vm, hook) {
// #7573 disable dep collection when invoking lifecycle hooks
pushTarget();
var handlers = vm.$options[hook];
var info = hook + " hook";
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
invokeWithErrorHandling(handlers[i], vm, null, vm, info);
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook);
}
popTarget();
}
/* */
var MAX_UPDATE_COUNT = 100;
var queue = [];
var activatedChildren = [];
var has = {};
var circular = {};
var waiting = false;
var flushing = false;
var index = 0;
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
index = queue.length = activatedChildren.length = 0;
has = {};
if (true) {
circular = {};
}
waiting = flushing = false;
}
// Async edge case #6566 requires saving the timestamp when event listeners are
// attached. However, calling performance.now() has a perf overhead especially
// if the page has thousands of event listeners. Instead, we take a timestamp
// every time the scheduler flushes and use that for all event listeners
// attached during that flush.
var currentFlushTimestamp = 0;
// Async edge case fix requires storing an event listener's attach timestamp.
var getNow = Date.now;
// Determine what event timestamp the browser is using. Annoyingly, the
// timestamp can either be hi-res (relative to page load) or low-res
// (relative to UNIX epoch), so in order to compare time we have to use the
// same timestamp type when saving the flush timestamp.
// All IE versions use low-res event timestamps, and have problematic clock
// implementations (#9632)
if (inBrowser && !isIE) {
var performance = window.performance;
if (
performance &&
typeof performance.now === 'function' &&
getNow() > document.createEvent('Event').timeStamp
) {
// if the event timestamp, although evaluated AFTER the Date.now(), is
// smaller than it, it means the event is using a hi-res timestamp,
// and we need to use the hi-res version for event listener timestamps as
// well.
getNow = function () { return performance.now(); };
}
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
currentFlushTimestamp = getNow();
flushing = true;
var watcher, id;
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort(function (a, b) { return a.id - b.id; });
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
watcher = queue[index];
if (watcher.before) {
watcher.before();
}
id = watcher.id;
has[id] = null;
watcher.run();
// in dev build, check and stop circular updates.
if ( true && has[id] != null) {
circular[id] = (circular[id] || 0) + 1;
if (circular[id] > MAX_UPDATE_COUNT) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? ("in watcher with expression \"" + (watcher.expression) + "\"")
: "in a component render function."
),
watcher.vm
);
break
}
}
}
// keep copies of post queues before resetting state
var activatedQueue = activatedChildren.slice();
var updatedQueue = queue.slice();
resetSchedulerState();
// call component updated and activated hooks
callActivatedHooks(activatedQueue);
callUpdatedHooks(updatedQueue);
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush');
}
}
function callUpdatedHooks (queue) {
var i = queue.length;
while (i--) {
var watcher = queue[i];
var vm = watcher.vm;
if (vm._watcher === watcher && vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'updated');
}
}
}
/**
* Queue a kept-alive component that was activated during patch.
* The queue will be processed after the entire tree has been patched.
*/
function queueActivatedComponent (vm) {
// setting _inactive to false here so that a render function can
// rely on checking whether it's in an inactive tree (e.g. router-view)
vm._inactive = false;
activatedChildren.push(vm);
}
function callActivatedHooks (queue) {
for (var i = 0; i < queue.length; i++) {
queue[i]._inactive = true;
activateChildComponent(queue[i], true /* true */);
}
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
function queueWatcher (watcher) {
var id = watcher.id;
if (has[id] == null) {
has[id] = true;
if (!flushing) {
queue.push(watcher);
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
var i = queue.length - 1;
while (i > index && queue[i].id > watcher.id) {
i--;
}
queue.splice(i + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
if ( true && !config.async) {
flushSchedulerQueue();
return
}
nextTick(flushSchedulerQueue);
}
}
}
/* */
var uid$2 = 0;
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
var Watcher = function Watcher (
vm,
expOrFn,
cb,
options,
isRenderWatcher
) {
this.vm = vm;
if (isRenderWatcher) {
vm._watcher = this;
}
vm._watchers.push(this);
// options
if (options) {
this.deep = !!options.deep;
this.user = !!options.user;
this.lazy = !!options.lazy;
this.sync = !!options.sync;
this.before = options.before;
} else {
this.deep = this.user = this.lazy = this.sync = false;
}
this.cb = cb;
this.id = ++uid$2; // uid for batching
this.active = true;
this.dirty = this.lazy; // for lazy watchers
this.deps = [];
this.newDeps = [];
this.depIds = new _Set();
this.newDepIds = new _Set();
this.expression = true
? expOrFn.toString()
: undefined;
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = parsePath(expOrFn);
if (!this.getter) {
this.getter = noop;
true && warn(
"Failed watching path: \"" + expOrFn + "\" " +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
);
}
}
this.value = this.lazy
? undefined
: this.get();
};
/**
* Evaluate the getter, and re-collect dependencies.
*/
Watcher.prototype.get = function get () {
pushTarget(this);
var value;
var vm = this.vm;
try {
value = this.getter.call(vm, vm);
} catch (e) {
if (this.user) {
handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\""));
} else {
throw e
}
} finally {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value);
}
popTarget();
this.cleanupDeps();
}
return value
};
/**
* Add a dependency to this directive.
*/
Watcher.prototype.addDep = function addDep (dep) {
var id = dep.id;
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id);
this.newDeps.push(dep);
if (!this.depIds.has(id)) {
dep.addSub(this);
}
}
};
/**
* Clean up for dependency collection.
*/
Watcher.prototype.cleanupDeps = function cleanupDeps () {
var i = this.deps.length;
while (i--) {
var dep = this.deps[i];
if (!this.newDepIds.has(dep.id)) {
dep.removeSub(this);
}
}
var tmp = this.depIds;
this.depIds = this.newDepIds;
this.newDepIds = tmp;
this.newDepIds.clear();
tmp = this.deps;
this.deps = this.newDeps;
this.newDeps = tmp;
this.newDeps.length = 0;
};
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
Watcher.prototype.update = function update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true;
} else if (this.sync) {
this.run();
} else {
queueWatcher(this);
}
};
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
Watcher.prototype.run = function run () {
if (this.active) {
var value = this.get();
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
var oldValue = this.value;
this.value = value;
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue);
} catch (e) {
handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\""));
}
} else {
this.cb.call(this.vm, value, oldValue);
}
}
}
};
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
Watcher.prototype.evaluate = function evaluate () {
this.value = this.get();
this.dirty = false;
};
/**
* Depend on all deps collected by this watcher.
*/
Watcher.prototype.depend = function depend () {
var i = this.deps.length;
while (i--) {
this.deps[i].depend();
}
};
/**
* Remove self from all dependencies' subscriber list.
*/
Watcher.prototype.teardown = function teardown () {
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed.
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this);
}
var i = this.deps.length;
while (i--) {
this.deps[i].removeSub(this);
}
this.active = false;
}
};
/* */
var sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
};
function proxy (target, sourceKey, key) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
};
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val;
};
Object.defineProperty(target, key, sharedPropertyDefinition);
}
function initState (vm) {
vm._watchers = [];
var opts = vm.$options;
if (opts.props) { initProps(vm, opts.props); }
if (opts.methods) { initMethods(vm, opts.methods); }
if (opts.data) {
initData(vm);
} else {
observe(vm._data = {}, true /* asRootData */);
}
if (opts.computed) { initComputed(vm, opts.computed); }
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch);
}
}
function initProps (vm, propsOptions) {
var propsData = vm.$options.propsData || {};
var props = vm._props = {};
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
var keys = vm.$options._propKeys = [];
var isRoot = !vm.$parent;
// root instance props should be converted
if (!isRoot) {
toggleObserving(false);
}
var loop = function ( key ) {
keys.push(key);
var value = validateProp(key, propsOptions, propsData, vm);
/* istanbul ignore else */
if (true) {
var hyphenatedKey = hyphenate(key);
if (isReservedAttribute(hyphenatedKey) ||
config.isReservedAttr(hyphenatedKey)) {
warn(
("\"" + hyphenatedKey + "\" is a reserved attribute and cannot be used as component prop."),
vm
);
}
defineReactive$$1(props, key, value, function () {
if (!isRoot && !isUpdatingChildComponent) {
{
if(vm.mpHost === 'mp-baidu' || vm.mpHost === 'mp-kuaishou' || vm.mpHost === 'mp-xhs'){//百度、快手、小红书 observer 在 setData callback 之后触发,直接忽略该 warn
return
}
//fixed by xxxxxx __next_tick_pending,uni://form-field 时不告警
if(
key === 'value' &&
Array.isArray(vm.$options.behaviors) &&
vm.$options.behaviors.indexOf('uni://form-field') !== -1
){
return
}
if(vm._getFormData){
return
}
var $parent = vm.$parent;
while($parent){
if($parent.__next_tick_pending){
return
}
$parent = $parent.$parent;
}
}
warn(
"Avoid mutating a prop directly since the value will be " +
"overwritten whenever the parent component re-renders. " +
"Instead, use a data or computed property based on the prop's " +
"value. Prop being mutated: \"" + key + "\"",
vm
);
}
});
} else {}
// static props are already proxied on the component's prototype
// during Vue.extend(). We only need to proxy props defined at
// instantiation here.
if (!(key in vm)) {
proxy(vm, "_props", key);
}
};
for (var key in propsOptions) loop( key );
toggleObserving(true);
}
function initData (vm) {
var data = vm.$options.data;
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {};
if (!isPlainObject(data)) {
data = {};
true && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
);
}
// proxy data on instance
var keys = Object.keys(data);
var props = vm.$options.props;
var methods = vm.$options.methods;
var i = keys.length;
while (i--) {
var key = keys[i];
if (true) {
if (methods && hasOwn(methods, key)) {
warn(
("Method \"" + key + "\" has already been defined as a data property."),
vm
);
}
}
if (props && hasOwn(props, key)) {
true && warn(
"The data property \"" + key + "\" is already declared as a prop. " +
"Use prop default value instead.",
vm
);
} else if (!isReserved(key)) {
proxy(vm, "_data", key);
}
}
// observe data
observe(data, true /* asRootData */);
}
function getData (data, vm) {
// #7573 disable dep collection when invoking data getters
pushTarget();
try {
return data.call(vm, vm)
} catch (e) {
handleError(e, vm, "data()");
return {}
} finally {
popTarget();
}
}
var computedWatcherOptions = { lazy: true };
function initComputed (vm, computed) {
// $flow-disable-line
var watchers = vm._computedWatchers = Object.create(null);
// computed properties are just getters during SSR
var isSSR = isServerRendering();
for (var key in computed) {
var userDef = computed[key];
var getter = typeof userDef === 'function' ? userDef : userDef.get;
if ( true && getter == null) {
warn(
("Getter is missing for computed property \"" + key + "\"."),
vm
);
}
if (!isSSR) {
// create internal watcher for the computed property.
watchers[key] = new Watcher(
vm,
getter || noop,
noop,
computedWatcherOptions
);
}
// component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
// at instantiation here.
if (!(key in vm)) {
defineComputed(vm, key, userDef);
} else if (true) {
if (key in vm.$data) {
warn(("The computed property \"" + key + "\" is already defined in data."), vm);
} else if (vm.$options.props && key in vm.$options.props) {
warn(("The computed property \"" + key + "\" is already defined as a prop."), vm);
}
}
}
}
function defineComputed (
target,
key,
userDef
) {
var shouldCache = !isServerRendering();
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = shouldCache
? createComputedGetter(key)
: createGetterInvoker(userDef);
sharedPropertyDefinition.set = noop;
} else {
sharedPropertyDefinition.get = userDef.get
? shouldCache && userDef.cache !== false
? createComputedGetter(key)
: createGetterInvoker(userDef.get)
: noop;
sharedPropertyDefinition.set = userDef.set || noop;
}
if ( true &&
sharedPropertyDefinition.set === noop) {
sharedPropertyDefinition.set = function () {
warn(
("Computed property \"" + key + "\" was assigned to but it has no setter."),
this
);
};
}
Object.defineProperty(target, key, sharedPropertyDefinition);
}
function createComputedGetter (key) {
return function computedGetter () {
var watcher = this._computedWatchers && this._computedWatchers[key];
if (watcher) {
if (watcher.dirty) {
watcher.evaluate();
}
if (Dep.SharedObject.target) {// fixed by xxxxxx
watcher.depend();
}
return watcher.value
}
}
}
function createGetterInvoker(fn) {
return function computedGetter () {
return fn.call(this, this)
}
}
function initMethods (vm, methods) {
var props = vm.$options.props;
for (var key in methods) {
if (true) {
if (typeof methods[key] !== 'function') {
warn(
"Method \"" + key + "\" has type \"" + (typeof methods[key]) + "\" in the component definition. " +
"Did you reference the function correctly?",
vm
);
}
if (props && hasOwn(props, key)) {
warn(
("Method \"" + key + "\" has already been defined as a prop."),
vm
);
}
if ((key in vm) && isReserved(key)) {
warn(
"Method \"" + key + "\" conflicts with an existing Vue instance method. " +
"Avoid defining component methods that start with _ or $."
);
}
}
vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm);
}
}
function initWatch (vm, watch) {
for (var key in watch) {
var handler = watch[key];
if (Array.isArray(handler)) {
for (var i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i]);
}
} else {
createWatcher(vm, key, handler);
}
}
}
function createWatcher (
vm,
expOrFn,
handler,
options
) {
if (isPlainObject(handler)) {
options = handler;
handler = handler.handler;
}
if (typeof handler === 'string') {
handler = vm[handler];
}
return vm.$watch(expOrFn, handler, options)
}
function stateMixin (Vue) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
var dataDef = {};
dataDef.get = function () { return this._data };
var propsDef = {};
propsDef.get = function () { return this._props };
if (true) {
dataDef.set = function () {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
);
};
propsDef.set = function () {
warn("$props is readonly.", this);
};
}
Object.defineProperty(Vue.prototype, '$data', dataDef);
Object.defineProperty(Vue.prototype, '$props', propsDef);
Vue.prototype.$set = set;
Vue.prototype.$delete = del;
Vue.prototype.$watch = function (
expOrFn,
cb,
options
) {
var vm = this;
if (isPlainObject(cb)) {
return createWatcher(vm, expOrFn, cb, options)
}
options = options || {};
options.user = true;
var watcher = new Watcher(vm, expOrFn, cb, options);
if (options.immediate) {
try {
cb.call(vm, watcher.value);
} catch (error) {
handleError(error, vm, ("callback for immediate watcher \"" + (watcher.expression) + "\""));
}
}
return function unwatchFn () {
watcher.teardown();
}
};
}
/* */
var uid$3 = 0;
function initMixin (Vue) {
Vue.prototype._init = function (options) {
var vm = this;
// a uid
vm._uid = uid$3++;
var startTag, endTag;
/* istanbul ignore if */
if ( true && config.performance && mark) {
startTag = "vue-perf-start:" + (vm._uid);
endTag = "vue-perf-end:" + (vm._uid);
mark(startTag);
}
// a flag to avoid this being observed
vm._isVue = true;
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options);
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
);
}
/* istanbul ignore else */
if (true) {
initProxy(vm);
} else {}
// expose real self
vm._self = vm;
initLifecycle(vm);
initEvents(vm);
initRender(vm);
callHook(vm, 'beforeCreate');
!vm._$fallback && initInjections(vm); // resolve injections before data/props
initState(vm);
!vm._$fallback && initProvide(vm); // resolve provide after data/props
!vm._$fallback && callHook(vm, 'created');
/* istanbul ignore if */
if ( true && config.performance && mark) {
vm._name = formatComponentName(vm, false);
mark(endTag);
measure(("vue " + (vm._name) + " init"), startTag, endTag);
}
if (vm.$options.el) {
vm.$mount(vm.$options.el);
}
};
}
function initInternalComponent (vm, options) {
var opts = vm.$options = Object.create(vm.constructor.options);
// doing this because it's faster than dynamic enumeration.
var parentVnode = options._parentVnode;
opts.parent = options.parent;
opts._parentVnode = parentVnode;
var vnodeComponentOptions = parentVnode.componentOptions;
opts.propsData = vnodeComponentOptions.propsData;
opts._parentListeners = vnodeComponentOptions.listeners;
opts._renderChildren = vnodeComponentOptions.children;
opts._componentTag = vnodeComponentOptions.tag;
if (options.render) {
opts.render = options.render;
opts.staticRenderFns = options.staticRenderFns;
}
}
function resolveConstructorOptions (Ctor) {
var options = Ctor.options;
if (Ctor.super) {
var superOptions = resolveConstructorOptions(Ctor.super);
var cachedSuperOptions = Ctor.superOptions;
if (superOptions !== cachedSuperOptions) {
// super option changed,
// need to resolve new options.
Ctor.superOptions = superOptions;
// check if there are any late-modified/attached options (#4976)
var modifiedOptions = resolveModifiedOptions(Ctor);
// update base extend options
if (modifiedOptions) {
extend(Ctor.extendOptions, modifiedOptions);
}
options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions);
if (options.name) {
options.components[options.name] = Ctor;
}
}
}
return options
}
function resolveModifiedOptions (Ctor) {
var modified;
var latest = Ctor.options;
var sealed = Ctor.sealedOptions;
for (var key in latest) {
if (latest[key] !== sealed[key]) {
if (!modified) { modified = {}; }
modified[key] = latest[key];
}
}
return modified
}
function Vue (options) {
if ( true &&
!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword');
}
this._init(options);
}
initMixin(Vue);
stateMixin(Vue);
eventsMixin(Vue);
lifecycleMixin(Vue);
renderMixin(Vue);
/* */
function initUse (Vue) {
Vue.use = function (plugin) {
var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters
var args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else if (typeof plugin === 'function') {
plugin.apply(null, args);
}
installedPlugins.push(plugin);
return this
};
}
/* */
function initMixin$1 (Vue) {
Vue.mixin = function (mixin) {
this.options = mergeOptions(this.options, mixin);
return this
};
}
/* */
function initExtend (Vue) {
/**
* Each instance constructor, including Vue, has a unique
* cid. This enables us to create wrapped "child
* constructors" for prototypal inheritance and cache them.
*/
Vue.cid = 0;
var cid = 1;
/**
* Class inheritance
*/
Vue.extend = function (extendOptions) {
extendOptions = extendOptions || {};
var Super = this;
var SuperId = Super.cid;
var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});
if (cachedCtors[SuperId]) {
return cachedCtors[SuperId]
}
var name = extendOptions.name || Super.options.name;
if ( true && name) {
validateComponentName(name);
}
var Sub = function VueComponent (options) {
this._init(options);
};
Sub.prototype = Object.create(Super.prototype);
Sub.prototype.constructor = Sub;
Sub.cid = cid++;
Sub.options = mergeOptions(
Super.options,
extendOptions
);
Sub['super'] = Super;
// For props and computed properties, we define the proxy getters on
// the Vue instances at extension time, on the extended prototype. This
// avoids Object.defineProperty calls for each instance created.
if (Sub.options.props) {
initProps$1(Sub);
}
if (Sub.options.computed) {
initComputed$1(Sub);
}
// allow further extension/mixin/plugin usage
Sub.extend = Super.extend;
Sub.mixin = Super.mixin;
Sub.use = Super.use;
// create asset registers, so extended classes
// can have their private assets too.
ASSET_TYPES.forEach(function (type) {
Sub[type] = Super[type];
});
// enable recursive self-lookup
if (name) {
Sub.options.components[name] = Sub;
}
// keep a reference to the super options at extension time.
// later at instantiation we can check if Super's options have
// been updated.
Sub.superOptions = Super.options;
Sub.extendOptions = extendOptions;
Sub.sealedOptions = extend({}, Sub.options);
// cache constructor
cachedCtors[SuperId] = Sub;
return Sub
};
}
function initProps$1 (Comp) {
var props = Comp.options.props;
for (var key in props) {
proxy(Comp.prototype, "_props", key);
}
}
function initComputed$1 (Comp) {
var computed = Comp.options.computed;
for (var key in computed) {
defineComputed(Comp.prototype, key, computed[key]);
}
}
/* */
function initAssetRegisters (Vue) {
/**
* Create asset registration methods.
*/
ASSET_TYPES.forEach(function (type) {
Vue[type] = function (
id,
definition
) {
if (!definition) {
return this.options[type + 's'][id]
} else {
/* istanbul ignore if */
if ( true && type === 'component') {
validateComponentName(id);
}
if (type === 'component' && isPlainObject(definition)) {
definition.name = definition.name || id;
definition = this.options._base.extend(definition);
}
if (type === 'directive' && typeof definition === 'function') {
definition = { bind: definition, update: definition };
}
this.options[type + 's'][id] = definition;
return definition
}
};
});
}
/* */
function getComponentName (opts) {
return opts && (opts.Ctor.options.name || opts.tag)
}
function matches (pattern, name) {
if (Array.isArray(pattern)) {
return pattern.indexOf(name) > -1
} else if (typeof pattern === 'string') {
return pattern.split(',').indexOf(name) > -1
} else if (isRegExp(pattern)) {
return pattern.test(name)
}
/* istanbul ignore next */
return false
}
function pruneCache (keepAliveInstance, filter) {
var cache = keepAliveInstance.cache;
var keys = keepAliveInstance.keys;
var _vnode = keepAliveInstance._vnode;
for (var key in cache) {
var cachedNode = cache[key];
if (cachedNode) {
var name = getComponentName(cachedNode.componentOptions);
if (name && !filter(name)) {
pruneCacheEntry(cache, key, keys, _vnode);
}
}
}
}
function pruneCacheEntry (
cache,
key,
keys,
current
) {
var cached$$1 = cache[key];
if (cached$$1 && (!current || cached$$1.tag !== current.tag)) {
cached$$1.componentInstance.$destroy();
}
cache[key] = null;
remove(keys, key);
}
var patternTypes = [String, RegExp, Array];
var KeepAlive = {
name: 'keep-alive',
abstract: true,
props: {
include: patternTypes,
exclude: patternTypes,
max: [String, Number]
},
created: function created () {
this.cache = Object.create(null);
this.keys = [];
},
destroyed: function destroyed () {
for (var key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys);
}
},
mounted: function mounted () {
var this$1 = this;
this.$watch('include', function (val) {
pruneCache(this$1, function (name) { return matches(val, name); });
});
this.$watch('exclude', function (val) {
pruneCache(this$1, function (name) { return !matches(val, name); });
});
},
render: function render () {
var slot = this.$slots.default;
var vnode = getFirstComponentChild(slot);
var componentOptions = vnode && vnode.componentOptions;
if (componentOptions) {
// check pattern
var name = getComponentName(componentOptions);
var ref = this;
var include = ref.include;
var exclude = ref.exclude;
if (
// not included
(include && (!name || !matches(include, name))) ||
// excluded
(exclude && name && matches(exclude, name))
) {
return vnode
}
var ref$1 = this;
var cache = ref$1.cache;
var keys = ref$1.keys;
var key = vnode.key == null
// same constructor may get registered as different local components
// so cid alone is not enough (#3269)
? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '')
: vnode.key;
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance;
// make current key freshest
remove(keys, key);
keys.push(key);
} else {
cache[key] = vnode;
keys.push(key);
// prune oldest entry
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode);
}
}
vnode.data.keepAlive = true;
}
return vnode || (slot && slot[0])
}
};
var builtInComponents = {
KeepAlive: KeepAlive
};
/* */
function initGlobalAPI (Vue) {
// config
var configDef = {};
configDef.get = function () { return config; };
if (true) {
configDef.set = function () {
warn(
'Do not replace the Vue.config object, set individual fields instead.'
);
};
}
Object.defineProperty(Vue, 'config', configDef);
// exposed util methods.
// NOTE: these are not considered part of the public API - avoid relying on
// them unless you are aware of the risk.
Vue.util = {
warn: warn,
extend: extend,
mergeOptions: mergeOptions,
defineReactive: defineReactive$$1
};
Vue.set = set;
Vue.delete = del;
Vue.nextTick = nextTick;
// 2.6 explicit observable API
Vue.observable = function (obj) {
observe(obj);
return obj
};
Vue.options = Object.create(null);
ASSET_TYPES.forEach(function (type) {
Vue.options[type + 's'] = Object.create(null);
});
// this is used to identify the "base" constructor to extend all plain-object
// components with in Weex's multi-instance scenarios.
Vue.options._base = Vue;
extend(Vue.options.components, builtInComponents);
initUse(Vue);
initMixin$1(Vue);
initExtend(Vue);
initAssetRegisters(Vue);
}
initGlobalAPI(Vue);
Object.defineProperty(Vue.prototype, '$isServer', {
get: isServerRendering
});
Object.defineProperty(Vue.prototype, '$ssrContext', {
get: function get () {
/* istanbul ignore next */
return this.$vnode && this.$vnode.ssrContext
}
});
// expose FunctionalRenderContext for ssr runtime helper installation
Object.defineProperty(Vue, 'FunctionalRenderContext', {
value: FunctionalRenderContext
});
Vue.version = '2.6.11';
/**
* https://raw.githubusercontent.com/Tencent/westore/master/packages/westore/utils/diff.js
*/
var ARRAYTYPE = '[object Array]';
var OBJECTTYPE = '[object Object]';
var NULLTYPE = '[object Null]';
var UNDEFINEDTYPE = '[object Undefined]';
// const FUNCTIONTYPE = '[object Function]'
function diff(current, pre) {
var result = {};
syncKeys(current, pre);
_diff(current, pre, '', result);
return result
}
function syncKeys(current, pre) {
if (current === pre) { return }
var rootCurrentType = type(current);
var rootPreType = type(pre);
if (rootCurrentType == OBJECTTYPE && rootPreType == OBJECTTYPE) {
if(Object.keys(current).length >= Object.keys(pre).length){
for (var key in pre) {
var currentValue = current[key];
if (currentValue === undefined) {
current[key] = null;
} else {
syncKeys(currentValue, pre[key]);
}
}
}
} else if (rootCurrentType == ARRAYTYPE && rootPreType == ARRAYTYPE) {
if (current.length >= pre.length) {
pre.forEach(function (item, index) {
syncKeys(current[index], item);
});
}
}
}
function nullOrUndefined(currentType, preType) {
if(
(currentType === NULLTYPE || currentType === UNDEFINEDTYPE) &&
(preType === NULLTYPE || preType === UNDEFINEDTYPE)
) {
return false
}
return true
}
function _diff(current, pre, path, result) {
if (current === pre) { return }
var rootCurrentType = type(current);
var rootPreType = type(pre);
if (rootCurrentType == OBJECTTYPE) {
if (rootPreType != OBJECTTYPE || Object.keys(current).length < Object.keys(pre).length) {
setResult(result, path, current);
} else {
var loop = function ( key ) {
var currentValue = current[key];
var preValue = pre[key];
var currentType = type(currentValue);
var preType = type(preValue);
if (currentType != ARRAYTYPE && currentType != OBJECTTYPE) {
if (currentValue !== pre[key] && nullOrUndefined(currentType, preType)) {
setResult(result, (path == '' ? '' : path + ".") + key, currentValue);
}
} else if (currentType == ARRAYTYPE) {
if (preType != ARRAYTYPE) {
setResult(result, (path == '' ? '' : path + ".") + key, currentValue);
} else {
if (currentValue.length < preValue.length) {
setResult(result, (path == '' ? '' : path + ".") + key, currentValue);
} else {
currentValue.forEach(function (item, index) {
_diff(item, preValue[index], (path == '' ? '' : path + ".") + key + '[' + index + ']', result);
});
}
}
} else if (currentType == OBJECTTYPE) {
if (preType != OBJECTTYPE || Object.keys(currentValue).length < Object.keys(preValue).length) {
setResult(result, (path == '' ? '' : path + ".") + key, currentValue);
} else {
for (var subKey in currentValue) {
_diff(currentValue[subKey], preValue[subKey], (path == '' ? '' : path + ".") + key + '.' + subKey, result);
}
}
}
};
for (var key in current) loop( key );
}
} else if (rootCurrentType == ARRAYTYPE) {
if (rootPreType != ARRAYTYPE) {
setResult(result, path, current);
} else {
if (current.length < pre.length) {
setResult(result, path, current);
} else {
current.forEach(function (item, index) {
_diff(item, pre[index], path + '[' + index + ']', result);
});
}
}
} else {
setResult(result, path, current);
}
}
function setResult(result, k, v) {
// if (type(v) != FUNCTIONTYPE) {
result[k] = v;
// }
}
function type(obj) {
return Object.prototype.toString.call(obj)
}
/* */
function flushCallbacks$1(vm) {
if (vm.__next_tick_callbacks && vm.__next_tick_callbacks.length) {
if (Object({"VUE_APP_DARK_MODE":"false","VUE_APP_NAME":"daoyou","VUE_APP_PLATFORM":"mp-weixin","NODE_ENV":"development","BASE_URL":"/"}).VUE_APP_DEBUG) {
var mpInstance = vm.$scope;
console.log('[' + (+new Date) + '][' + (mpInstance.is || mpInstance.route) + '][' + vm._uid +
']:flushCallbacks[' + vm.__next_tick_callbacks.length + ']');
}
var copies = vm.__next_tick_callbacks.slice(0);
vm.__next_tick_callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
}
function hasRenderWatcher(vm) {
return queue.find(function (watcher) { return vm._watcher === watcher; })
}
function nextTick$1(vm, cb) {
//1.nextTick 之前 已 setData 且 setData 还未回调完成
//2.nextTick 之前存在 render watcher
if (!vm.__next_tick_pending && !hasRenderWatcher(vm)) {
if(Object({"VUE_APP_DARK_MODE":"false","VUE_APP_NAME":"daoyou","VUE_APP_PLATFORM":"mp-weixin","NODE_ENV":"development","BASE_URL":"/"}).VUE_APP_DEBUG){
var mpInstance = vm.$scope;
console.log('[' + (+new Date) + '][' + (mpInstance.is || mpInstance.route) + '][' + vm._uid +
']:nextVueTick');
}
return nextTick(cb, vm)
}else{
if(Object({"VUE_APP_DARK_MODE":"false","VUE_APP_NAME":"daoyou","VUE_APP_PLATFORM":"mp-weixin","NODE_ENV":"development","BASE_URL":"/"}).VUE_APP_DEBUG){
var mpInstance$1 = vm.$scope;
console.log('[' + (+new Date) + '][' + (mpInstance$1.is || mpInstance$1.route) + '][' + vm._uid +
']:nextMPTick');
}
}
var _resolve;
if (!vm.__next_tick_callbacks) {
vm.__next_tick_callbacks = [];
}
vm.__next_tick_callbacks.push(function () {
if (cb) {
try {
cb.call(vm);
} catch (e) {
handleError(e, vm, 'nextTick');
}
} else if (_resolve) {
_resolve(vm);
}
});
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve) {
_resolve = resolve;
})
}
}
/* */
function clearInstance(key, value) {
// 简易去除 Vue 和小程序组件实例
if (value) {
if (value._isVue || value.__v_isMPComponent) {
return {}
}
}
return value
}
function cloneWithData(vm) {
// 确保当前 vm 所有数据被同步
var ret = Object.create(null);
var dataKeys = [].concat(
Object.keys(vm._data || {}),
Object.keys(vm._computedWatchers || {}));
dataKeys.reduce(function(ret, key) {
ret[key] = vm[key];
return ret
}, ret);
// vue-composition-api
var compositionApiState = vm.__composition_api_state__ || vm.__secret_vfa_state__;
var rawBindings = compositionApiState && compositionApiState.rawBindings;
if (rawBindings) {
Object.keys(rawBindings).forEach(function (key) {
ret[key] = vm[key];
});
}
//TODO 需要把无用数据处理掉,比如 list=>l0 则 list 需要移除,否则多传输一份数据
Object.assign(ret, vm.$mp.data || {});
if (
Array.isArray(vm.$options.behaviors) &&
vm.$options.behaviors.indexOf('uni://form-field') !== -1
) { //form-field
ret['name'] = vm.name;
ret['value'] = vm.value;
}
return JSON.parse(JSON.stringify(ret, clearInstance))
}
var patch = function(oldVnode, vnode) {
var this$1 = this;
if (vnode === null) { //destroy
return
}
if (this.mpType === 'page' || this.mpType === 'component') {
var mpInstance = this.$scope;
var data = Object.create(null);
try {
data = cloneWithData(this);
} catch (err) {
console.error(err);
}
data.__webviewId__ = mpInstance.data.__webviewId__;
var mpData = Object.create(null);
Object.keys(data).forEach(function (key) { //仅同步 data 中有的数据
mpData[key] = mpInstance.data[key];
});
var diffData = this.$shouldDiffData === false ? data : diff(data, mpData);
if (Object.keys(diffData).length) {
if (Object({"VUE_APP_DARK_MODE":"false","VUE_APP_NAME":"daoyou","VUE_APP_PLATFORM":"mp-weixin","NODE_ENV":"development","BASE_URL":"/"}).VUE_APP_DEBUG) {
console.log('[' + (+new Date) + '][' + (mpInstance.is || mpInstance.route) + '][' + this._uid +
']差量更新',
JSON.stringify(diffData));
}
this.__next_tick_pending = true;
mpInstance.setData(diffData, function () {
this$1.__next_tick_pending = false;
flushCallbacks$1(this$1);
});
} else {
flushCallbacks$1(this);
}
}
};
/* */
function createEmptyRender() {
}
function mountComponent$1(
vm,
el,
hydrating
) {
if (!vm.mpType) {//main.js 中的 new Vue
return vm
}
if (vm.mpType === 'app') {
vm.$options.render = createEmptyRender;
}
if (!vm.$options.render) {
vm.$options.render = createEmptyRender;
if (true) {
/* istanbul ignore if */
if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
vm.$options.el || el) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'compiler is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
);
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
);
}
}
}
!vm._$fallback && callHook(vm, 'beforeMount');
var updateComponent = function () {
vm._update(vm._render(), hydrating);
};
// we set this to vm._watcher inside the watcher's constructor
// since the watcher's initial patch may call $forceUpdate (e.g. inside child
// component's mounted hook), which relies on vm._watcher being already defined
new Watcher(vm, updateComponent, noop, {
before: function before() {
if (vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'beforeUpdate');
}
}
}, true /* isRenderWatcher */);
hydrating = false;
return vm
}
/* */
function renderClass (
staticClass,
dynamicClass
) {
if (isDef(staticClass) || isDef(dynamicClass)) {
return concat(staticClass, stringifyClass(dynamicClass))
}
/* istanbul ignore next */
return ''
}
function concat (a, b) {
return a ? b ? (a + ' ' + b) : a : (b || '')
}
function stringifyClass (value) {
if (Array.isArray(value)) {
return stringifyArray(value)
}
if (isObject(value)) {
return stringifyObject(value)
}
if (typeof value === 'string') {
return value
}
/* istanbul ignore next */
return ''
}
function stringifyArray (value) {
var res = '';
var stringified;
for (var i = 0, l = value.length; i < l; i++) {
if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') {
if (res) { res += ' '; }
res += stringified;
}
}
return res
}
function stringifyObject (value) {
var res = '';
for (var key in value) {
if (value[key]) {
if (res) { res += ' '; }
res += key;
}
}
return res
}
/* */
var parseStyleText = cached(function (cssText) {
var res = {};
var listDelimiter = /;(?![^(]*\))/g;
var propertyDelimiter = /:(.+)/;
cssText.split(listDelimiter).forEach(function (item) {
if (item) {
var tmp = item.split(propertyDelimiter);
tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim());
}
});
return res
});
// normalize possible array / string values into Object
function normalizeStyleBinding (bindingStyle) {
if (Array.isArray(bindingStyle)) {
return toObject(bindingStyle)
}
if (typeof bindingStyle === 'string') {
return parseStyleText(bindingStyle)
}
return bindingStyle
}
/* */
var MP_METHODS = ['createSelectorQuery', 'createIntersectionObserver', 'selectAllComponents', 'selectComponent'];
function getTarget(obj, path) {
var parts = path.split('.');
var key = parts[0];
if (key.indexOf('__$n') === 0) { //number index
key = parseInt(key.replace('__$n', ''));
}
if (parts.length === 1) {
return obj[key]
}
return getTarget(obj[key], parts.slice(1).join('.'))
}
function internalMixin(Vue) {
Vue.config.errorHandler = function(err, vm, info) {
Vue.util.warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm);
console.error(err);
/* eslint-disable no-undef */
var app = typeof getApp === 'function' && getApp();
if (app && app.onError) {
app.onError(err);
}
};
var oldEmit = Vue.prototype.$emit;
Vue.prototype.$emit = function(event) {
if (this.$scope && event) {
var triggerEvent = this.$scope['_triggerEvent'] || this.$scope['triggerEvent'];
if (triggerEvent) {
try {
triggerEvent.call(this.$scope, event, {
__args__: toArray(arguments, 1)
});
} catch (error) {
}
}
}
return oldEmit.apply(this, arguments)
};
Vue.prototype.$nextTick = function(fn) {
return nextTick$1(this, fn)
};
MP_METHODS.forEach(function (method) {
Vue.prototype[method] = function(args) {
if (this.$scope && this.$scope[method]) {
return this.$scope[method](args)
}
// mp-alipay
if (typeof my === 'undefined') {
return
}
if (method === 'createSelectorQuery') {
/* eslint-disable no-undef */
return my.createSelectorQuery(args)
} else if (method === 'createIntersectionObserver') {
/* eslint-disable no-undef */
return my.createIntersectionObserver(args)
}
// TODO mp-alipay 暂不支持 selectAllComponents,selectComponent
};
});
Vue.prototype.__init_provide = initProvide;
Vue.prototype.__init_injections = initInjections;
Vue.prototype.__call_hook = function(hook, args) {
var vm = this;
// #7573 disable dep collection when invoking lifecycle hooks
pushTarget();
var handlers = vm.$options[hook];
var info = hook + " hook";
var ret;
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
ret = invokeWithErrorHandling(handlers[i], vm, args ? [args] : null, vm, info);
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook, args);
}
popTarget();
return ret
};
Vue.prototype.__set_model = function(target, key, value, modifiers) {
if (Array.isArray(modifiers)) {
if (modifiers.indexOf('trim') !== -1) {
value = value.trim();
}
if (modifiers.indexOf('number') !== -1) {
value = this._n(value);
}
}
if (!target) {
target = this;
}
// 解决动态属性添加
Vue.set(target, key, value);
};
Vue.prototype.__set_sync = function(target, key, value) {
if (!target) {
target = this;
}
// 解决动态属性添加
Vue.set(target, key, value);
};
Vue.prototype.__get_orig = function(item) {
if (isPlainObject(item)) {
return item['$orig'] || item
}
return item
};
Vue.prototype.__get_value = function(dataPath, target) {
return getTarget(target || this, dataPath)
};
Vue.prototype.__get_class = function(dynamicClass, staticClass) {
return renderClass(staticClass, dynamicClass)
};
Vue.prototype.__get_style = function(dynamicStyle, staticStyle) {
if (!dynamicStyle && !staticStyle) {
return ''
}
var dynamicStyleObj = normalizeStyleBinding(dynamicStyle);
var styleObj = staticStyle ? extend(staticStyle, dynamicStyleObj) : dynamicStyleObj;
return Object.keys(styleObj).map(function (name) { return ((hyphenate(name)) + ":" + (styleObj[name])); }).join(';')
};
Vue.prototype.__map = function(val, iteratee) {
//TODO 暂不考虑 string
var ret, i, l, keys, key;
if (Array.isArray(val)) {
ret = new Array(val.length);
for (i = 0, l = val.length; i < l; i++) {
ret[i] = iteratee(val[i], i);
}
return ret
} else if (isObject(val)) {
keys = Object.keys(val);
ret = Object.create(null);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[key] = iteratee(val[key], key, i);
}
return ret
} else if (typeof val === 'number') {
ret = new Array(val);
for (i = 0, l = val; i < l; i++) {
// 第一个参数暂时仍和小程序一致
ret[i] = iteratee(i, i);
}
return ret
}
return []
};
}
/* */
var LIFECYCLE_HOOKS$1 = [
//App
'onLaunch',
'onShow',
'onHide',
'onUniNViewMessage',
'onPageNotFound',
'onThemeChange',
'onError',
'onUnhandledRejection',
//Page
'onInit',
'onLoad',
// 'onShow',
'onReady',
// 'onHide',
'onUnload',
'onPullDownRefresh',
'onReachBottom',
'onTabItemTap',
'onAddToFavorites',
'onShareTimeline',
'onShareAppMessage',
'onResize',
'onPageScroll',
'onNavigationBarButtonTap',
'onBackPress',
'onNavigationBarSearchInputChanged',
'onNavigationBarSearchInputConfirmed',
'onNavigationBarSearchInputClicked',
'onUploadDouyinVideo',
'onNFCReadMessage',
//Component
// 'onReady', // 兼容旧版本,应该移除该事件
'onPageShow',
'onPageHide',
'onPageResize'
];
function lifecycleMixin$1(Vue) {
//fixed vue-class-component
var oldExtend = Vue.extend;
Vue.extend = function(extendOptions) {
extendOptions = extendOptions || {};
var methods = extendOptions.methods;
if (methods) {
Object.keys(methods).forEach(function (methodName) {
if (LIFECYCLE_HOOKS$1.indexOf(methodName)!==-1) {
extendOptions[methodName] = methods[methodName];
delete methods[methodName];
}
});
}
return oldExtend.call(this, extendOptions)
};
var strategies = Vue.config.optionMergeStrategies;
var mergeHook = strategies.created;
LIFECYCLE_HOOKS$1.forEach(function (hook) {
strategies[hook] = mergeHook;
});
Vue.prototype.__lifecycle_hooks__ = LIFECYCLE_HOOKS$1;
}
/* */
// install platform patch function
Vue.prototype.__patch__ = patch;
// public mount method
Vue.prototype.$mount = function(
el ,
hydrating
) {
return mountComponent$1(this, el, hydrating)
};
lifecycleMixin$1(Vue);
internalMixin(Vue);
/* */
/* harmony default export */ __webpack_exports__["default"] = (Vue);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../../webpack/buildin/global.js */ 3)))
/***/ }),
/* 26 */
/*!*****************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/pages.json ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
/***/ }),
/* 27 */,
/* 28 */,
/* 29 */,
/* 30 */,
/* 31 */,
/* 32 */
/*!**********************************************************************************************************!*\
!*** ./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/runtime/componentNormalizer.js ***!
\**********************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return normalizeComponent; });
/* globals __VUE_SSR_CONTEXT__ */
// IMPORTANT: Do NOT use ES2015 features in this file (except for modules).
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.
function normalizeComponent (
scriptExports,
render,
staticRenderFns,
functionalTemplate,
injectStyles,
scopeId,
moduleIdentifier, /* server only */
shadowMode, /* vue-cli only */
components, // fixed by xxxxxx auto components
renderjs // fixed by xxxxxx renderjs
) {
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// fixed by xxxxxx auto components
if (components) {
if (!options.components) {
options.components = {}
}
var hasOwn = Object.prototype.hasOwnProperty
for (var name in components) {
if (hasOwn.call(components, name) && !hasOwn.call(options.components, name)) {
options.components[name] = components[name]
}
}
}
// fixed by xxxxxx renderjs
if (renderjs) {
if(typeof renderjs.beforeCreate === 'function'){
renderjs.beforeCreate = [renderjs.beforeCreate]
}
(renderjs.beforeCreate || (renderjs.beforeCreate = [])).unshift(function() {
this[renderjs.__module] = this
});
(options.mixins || (options.mixins = [])).push(renderjs)
}
// render functions
if (render) {
options.render = render
options.staticRenderFns = staticRenderFns
options._compiled = true
}
// functional template
if (functionalTemplate) {
options.functional = true
}
// scopedId
if (scopeId) {
options._scopeId = 'data-v-' + scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = shadowMode
? function () { injectStyles.call(this, this.$root.$options.shadowRoot) }
: injectStyles
}
if (hook) {
if (options.functional) {
// for template-only hot-reload because in that case the render fn doesn't
// go through the normalizer
options._injectStyles = hook
// register for functioal component in vue file
var originalRender = options.render
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return originalRender(h, context)
}
} else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
}
}
return {
exports: scriptExports,
options: options
}
}
/***/ }),
/* 33 */
/*!*********************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/store/index.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ 4);
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _vue = _interopRequireDefault(__webpack_require__(/*! vue */ 25));
var _vuex = _interopRequireDefault(__webpack_require__(/*! vuex */ 34));
var _user = _interopRequireDefault(__webpack_require__(/*! ./modules/user */ 35));
_vue.default.use(_vuex.default);
var _default = new _vuex.default.Store({
modules: {
user: _user.default
}
});
exports.default = _default;
/***/ }),
/* 34 */
/*!**************************************************************************************!*\
!*** ./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vuex3/dist/vuex.common.js ***!
\**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
* vuex v3.6.2
* (c) 2021 Evan You
* @license MIT
*/
function applyMixin (Vue) {
var version = Number(Vue.version.split('.')[0]);
if (version >= 2) {
Vue.mixin({ beforeCreate: vuexInit });
} else {
// override init and inject vuex init procedure
// for 1.x backwards compatibility.
var _init = Vue.prototype._init;
Vue.prototype._init = function (options) {
if ( options === void 0 ) options = {};
options.init = options.init
? [vuexInit].concat(options.init)
: vuexInit;
_init.call(this, options);
};
}
/**
* Vuex init hook, injected into each instances init hooks list.
*/
function vuexInit () {
var options = this.$options;
// store injection
if (options.store) {
this.$store = typeof options.store === 'function'
? options.store()
: options.store;
} else if (options.parent && options.parent.$store) {
this.$store = options.parent.$store;
}
}
}
var target = typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {};
var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__;
function devtoolPlugin (store) {
if (!devtoolHook) { return }
store._devtoolHook = devtoolHook;
devtoolHook.emit('vuex:init', store);
devtoolHook.on('vuex:travel-to-state', function (targetState) {
store.replaceState(targetState);
});
store.subscribe(function (mutation, state) {
devtoolHook.emit('vuex:mutation', mutation, state);
}, { prepend: true });
store.subscribeAction(function (action, state) {
devtoolHook.emit('vuex:action', action, state);
}, { prepend: true });
}
/**
* Get the first item that pass the test
* by second argument function
*
* @param {Array} list
* @param {Function} f
* @return {*}
*/
function find (list, f) {
return list.filter(f)[0]
}
/**
* Deep copy the given object considering circular structure.
* This function caches all nested objects and its copies.
* If it detects circular structure, use cached copy to avoid infinite loop.
*
* @param {*} obj
* @param {Array<Object>} cache
* @return {*}
*/
function deepCopy (obj, cache) {
if ( cache === void 0 ) cache = [];
// just return if obj is immutable value
if (obj === null || typeof obj !== 'object') {
return obj
}
// if obj is hit, it is in circular structure
var hit = find(cache, function (c) { return c.original === obj; });
if (hit) {
return hit.copy
}
var copy = Array.isArray(obj) ? [] : {};
// put the copy into cache at first
// because we want to refer it in recursive deepCopy
cache.push({
original: obj,
copy: copy
});
Object.keys(obj).forEach(function (key) {
copy[key] = deepCopy(obj[key], cache);
});
return copy
}
/**
* forEach for object
*/
function forEachValue (obj, fn) {
Object.keys(obj).forEach(function (key) { return fn(obj[key], key); });
}
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
function isPromise (val) {
return val && typeof val.then === 'function'
}
function assert (condition, msg) {
if (!condition) { throw new Error(("[vuex] " + msg)) }
}
function partial (fn, arg) {
return function () {
return fn(arg)
}
}
// Base data struct for store's module, package with some attribute and method
var Module = function Module (rawModule, runtime) {
this.runtime = runtime;
// Store some children item
this._children = Object.create(null);
// Store the origin module object which passed by programmer
this._rawModule = rawModule;
var rawState = rawModule.state;
// Store the origin module's state
this.state = (typeof rawState === 'function' ? rawState() : rawState) || {};
};
var prototypeAccessors = { namespaced: { configurable: true } };
prototypeAccessors.namespaced.get = function () {
return !!this._rawModule.namespaced
};
Module.prototype.addChild = function addChild (key, module) {
this._children[key] = module;
};
Module.prototype.removeChild = function removeChild (key) {
delete this._children[key];
};
Module.prototype.getChild = function getChild (key) {
return this._children[key]
};
Module.prototype.hasChild = function hasChild (key) {
return key in this._children
};
Module.prototype.update = function update (rawModule) {
this._rawModule.namespaced = rawModule.namespaced;
if (rawModule.actions) {
this._rawModule.actions = rawModule.actions;
}
if (rawModule.mutations) {
this._rawModule.mutations = rawModule.mutations;
}
if (rawModule.getters) {
this._rawModule.getters = rawModule.getters;
}
};
Module.prototype.forEachChild = function forEachChild (fn) {
forEachValue(this._children, fn);
};
Module.prototype.forEachGetter = function forEachGetter (fn) {
if (this._rawModule.getters) {
forEachValue(this._rawModule.getters, fn);
}
};
Module.prototype.forEachAction = function forEachAction (fn) {
if (this._rawModule.actions) {
forEachValue(this._rawModule.actions, fn);
}
};
Module.prototype.forEachMutation = function forEachMutation (fn) {
if (this._rawModule.mutations) {
forEachValue(this._rawModule.mutations, fn);
}
};
Object.defineProperties( Module.prototype, prototypeAccessors );
var ModuleCollection = function ModuleCollection (rawRootModule) {
// register root module (Vuex.Store options)
this.register([], rawRootModule, false);
};
ModuleCollection.prototype.get = function get (path) {
return path.reduce(function (module, key) {
return module.getChild(key)
}, this.root)
};
ModuleCollection.prototype.getNamespace = function getNamespace (path) {
var module = this.root;
return path.reduce(function (namespace, key) {
module = module.getChild(key);
return namespace + (module.namespaced ? key + '/' : '')
}, '')
};
ModuleCollection.prototype.update = function update$1 (rawRootModule) {
update([], this.root, rawRootModule);
};
ModuleCollection.prototype.register = function register (path, rawModule, runtime) {
var this$1 = this;
if ( runtime === void 0 ) runtime = true;
if ((true)) {
assertRawModule(path, rawModule);
}
var newModule = new Module(rawModule, runtime);
if (path.length === 0) {
this.root = newModule;
} else {
var parent = this.get(path.slice(0, -1));
parent.addChild(path[path.length - 1], newModule);
}
// register nested modules
if (rawModule.modules) {
forEachValue(rawModule.modules, function (rawChildModule, key) {
this$1.register(path.concat(key), rawChildModule, runtime);
});
}
};
ModuleCollection.prototype.unregister = function unregister (path) {
var parent = this.get(path.slice(0, -1));
var key = path[path.length - 1];
var child = parent.getChild(key);
if (!child) {
if ((true)) {
console.warn(
"[vuex] trying to unregister module '" + key + "', which is " +
"not registered"
);
}
return
}
if (!child.runtime) {
return
}
parent.removeChild(key);
};
ModuleCollection.prototype.isRegistered = function isRegistered (path) {
var parent = this.get(path.slice(0, -1));
var key = path[path.length - 1];
if (parent) {
return parent.hasChild(key)
}
return false
};
function update (path, targetModule, newModule) {
if ((true)) {
assertRawModule(path, newModule);
}
// update target module
targetModule.update(newModule);
// update nested modules
if (newModule.modules) {
for (var key in newModule.modules) {
if (!targetModule.getChild(key)) {
if ((true)) {
console.warn(
"[vuex] trying to add a new module '" + key + "' on hot reloading, " +
'manual reload is needed'
);
}
return
}
update(
path.concat(key),
targetModule.getChild(key),
newModule.modules[key]
);
}
}
}
var functionAssert = {
assert: function (value) { return typeof value === 'function'; },
expected: 'function'
};
var objectAssert = {
assert: function (value) { return typeof value === 'function' ||
(typeof value === 'object' && typeof value.handler === 'function'); },
expected: 'function or object with "handler" function'
};
var assertTypes = {
getters: functionAssert,
mutations: functionAssert,
actions: objectAssert
};
function assertRawModule (path, rawModule) {
Object.keys(assertTypes).forEach(function (key) {
if (!rawModule[key]) { return }
var assertOptions = assertTypes[key];
forEachValue(rawModule[key], function (value, type) {
assert(
assertOptions.assert(value),
makeAssertionMessage(path, key, type, value, assertOptions.expected)
);
});
});
}
function makeAssertionMessage (path, key, type, value, expected) {
var buf = key + " should be " + expected + " but \"" + key + "." + type + "\"";
if (path.length > 0) {
buf += " in module \"" + (path.join('.')) + "\"";
}
buf += " is " + (JSON.stringify(value)) + ".";
return buf
}
var Vue; // bind on install
var Store = function Store (options) {
var this$1 = this;
if ( options === void 0 ) options = {};
// Auto install if it is not done yet and `window` has `Vue`.
// To allow users to avoid auto-installation in some cases,
// this code should be placed here. See #731
if (!Vue && typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
if ((true)) {
assert(Vue, "must call Vue.use(Vuex) before creating a store instance.");
assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser.");
assert(this instanceof Store, "store must be called with the new operator.");
}
var plugins = options.plugins; if ( plugins === void 0 ) plugins = [];
var strict = options.strict; if ( strict === void 0 ) strict = false;
// store internal state
this._committing = false;
this._actions = Object.create(null);
this._actionSubscribers = [];
this._mutations = Object.create(null);
this._wrappedGetters = Object.create(null);
this._modules = new ModuleCollection(options);
this._modulesNamespaceMap = Object.create(null);
this._subscribers = [];
this._watcherVM = new Vue();
this._makeLocalGettersCache = Object.create(null);
// bind commit and dispatch to self
var store = this;
var ref = this;
var dispatch = ref.dispatch;
var commit = ref.commit;
this.dispatch = function boundDispatch (type, payload) {
return dispatch.call(store, type, payload)
};
this.commit = function boundCommit (type, payload, options) {
return commit.call(store, type, payload, options)
};
// strict mode
this.strict = strict;
var state = this._modules.root.state;
// init root module.
// this also recursively registers all sub-modules
// and collects all module getters inside this._wrappedGetters
installModule(this, state, [], this._modules.root);
// initialize the store vm, which is responsible for the reactivity
// (also registers _wrappedGetters as computed properties)
resetStoreVM(this, state);
// apply plugins
plugins.forEach(function (plugin) { return plugin(this$1); });
var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools;
if (useDevtools) {
devtoolPlugin(this);
}
};
var prototypeAccessors$1 = { state: { configurable: true } };
prototypeAccessors$1.state.get = function () {
return this._vm._data.$$state
};
prototypeAccessors$1.state.set = function (v) {
if ((true)) {
assert(false, "use store.replaceState() to explicit replace store state.");
}
};
Store.prototype.commit = function commit (_type, _payload, _options) {
var this$1 = this;
// check object-style commit
var ref = unifyObjectStyle(_type, _payload, _options);
var type = ref.type;
var payload = ref.payload;
var options = ref.options;
var mutation = { type: type, payload: payload };
var entry = this._mutations[type];
if (!entry) {
if ((true)) {
console.error(("[vuex] unknown mutation type: " + type));
}
return
}
this._withCommit(function () {
entry.forEach(function commitIterator (handler) {
handler(payload);
});
});
this._subscribers
.slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
.forEach(function (sub) { return sub(mutation, this$1.state); });
if (
( true) &&
options && options.silent
) {
console.warn(
"[vuex] mutation type: " + type + ". Silent option has been removed. " +
'Use the filter functionality in the vue-devtools'
);
}
};
Store.prototype.dispatch = function dispatch (_type, _payload) {
var this$1 = this;
// check object-style dispatch
var ref = unifyObjectStyle(_type, _payload);
var type = ref.type;
var payload = ref.payload;
var action = { type: type, payload: payload };
var entry = this._actions[type];
if (!entry) {
if ((true)) {
console.error(("[vuex] unknown action type: " + type));
}
return
}
try {
this._actionSubscribers
.slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
.filter(function (sub) { return sub.before; })
.forEach(function (sub) { return sub.before(action, this$1.state); });
} catch (e) {
if ((true)) {
console.warn("[vuex] error in before action subscribers: ");
console.error(e);
}
}
var result = entry.length > 1
? Promise.all(entry.map(function (handler) { return handler(payload); }))
: entry[0](payload);
return new Promise(function (resolve, reject) {
result.then(function (res) {
try {
this$1._actionSubscribers
.filter(function (sub) { return sub.after; })
.forEach(function (sub) { return sub.after(action, this$1.state); });
} catch (e) {
if ((true)) {
console.warn("[vuex] error in after action subscribers: ");
console.error(e);
}
}
resolve(res);
}, function (error) {
try {
this$1._actionSubscribers
.filter(function (sub) { return sub.error; })
.forEach(function (sub) { return sub.error(action, this$1.state, error); });
} catch (e) {
if ((true)) {
console.warn("[vuex] error in error action subscribers: ");
console.error(e);
}
}
reject(error);
});
})
};
Store.prototype.subscribe = function subscribe (fn, options) {
return genericSubscribe(fn, this._subscribers, options)
};
Store.prototype.subscribeAction = function subscribeAction (fn, options) {
var subs = typeof fn === 'function' ? { before: fn } : fn;
return genericSubscribe(subs, this._actionSubscribers, options)
};
Store.prototype.watch = function watch (getter, cb, options) {
var this$1 = this;
if ((true)) {
assert(typeof getter === 'function', "store.watch only accepts a function.");
}
return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options)
};
Store.prototype.replaceState = function replaceState (state) {
var this$1 = this;
this._withCommit(function () {
this$1._vm._data.$$state = state;
});
};
Store.prototype.registerModule = function registerModule (path, rawModule, options) {
if ( options === void 0 ) options = {};
if (typeof path === 'string') { path = [path]; }
if ((true)) {
assert(Array.isArray(path), "module path must be a string or an Array.");
assert(path.length > 0, 'cannot register the root module by using registerModule.');
}
this._modules.register(path, rawModule);
installModule(this, this.state, path, this._modules.get(path), options.preserveState);
// reset store to update getters...
resetStoreVM(this, this.state);
};
Store.prototype.unregisterModule = function unregisterModule (path) {
var this$1 = this;
if (typeof path === 'string') { path = [path]; }
if ((true)) {
assert(Array.isArray(path), "module path must be a string or an Array.");
}
this._modules.unregister(path);
this._withCommit(function () {
var parentState = getNestedState(this$1.state, path.slice(0, -1));
Vue.delete(parentState, path[path.length - 1]);
});
resetStore(this);
};
Store.prototype.hasModule = function hasModule (path) {
if (typeof path === 'string') { path = [path]; }
if ((true)) {
assert(Array.isArray(path), "module path must be a string or an Array.");
}
return this._modules.isRegistered(path)
};
Store.prototype[[104,111,116,85,112,100,97,116,101].map(function (item) {return String.fromCharCode(item)}).join('')] = function (newOptions) {
this._modules.update(newOptions);
resetStore(this, true);
};
Store.prototype._withCommit = function _withCommit (fn) {
var committing = this._committing;
this._committing = true;
fn();
this._committing = committing;
};
Object.defineProperties( Store.prototype, prototypeAccessors$1 );
function genericSubscribe (fn, subs, options) {
if (subs.indexOf(fn) < 0) {
options && options.prepend
? subs.unshift(fn)
: subs.push(fn);
}
return function () {
var i = subs.indexOf(fn);
if (i > -1) {
subs.splice(i, 1);
}
}
}
function resetStore (store, hot) {
store._actions = Object.create(null);
store._mutations = Object.create(null);
store._wrappedGetters = Object.create(null);
store._modulesNamespaceMap = Object.create(null);
var state = store.state;
// init all modules
installModule(store, state, [], store._modules.root, true);
// reset vm
resetStoreVM(store, state, hot);
}
function resetStoreVM (store, state, hot) {
var oldVm = store._vm;
// bind store public getters
store.getters = {};
// reset local getters cache
store._makeLocalGettersCache = Object.create(null);
var wrappedGetters = store._wrappedGetters;
var computed = {};
forEachValue(wrappedGetters, function (fn, key) {
// use computed to leverage its lazy-caching mechanism
// direct inline function use will lead to closure preserving oldVm.
// using partial to return function with only arguments preserved in closure environment.
computed[key] = partial(fn, store);
Object.defineProperty(store.getters, key, {
get: function () { return store._vm[key]; },
enumerable: true // for local getters
});
});
// use a Vue instance to store the state tree
// suppress warnings just in case the user has added
// some funky global mixins
var silent = Vue.config.silent;
Vue.config.silent = true;
store._vm = new Vue({
data: {
$$state: state
},
computed: computed
});
Vue.config.silent = silent;
// enable strict mode for new vm
if (store.strict) {
enableStrictMode(store);
}
if (oldVm) {
if (hot) {
// dispatch changes in all subscribed watchers
// to force getter re-evaluation for hot reloading.
store._withCommit(function () {
oldVm._data.$$state = null;
});
}
Vue.nextTick(function () { return oldVm.$destroy(); });
}
}
function installModule (store, rootState, path, module, hot) {
var isRoot = !path.length;
var namespace = store._modules.getNamespace(path);
// register in namespace map
if (module.namespaced) {
if (store._modulesNamespaceMap[namespace] && ("development" !== 'production')) {
console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/'))));
}
store._modulesNamespaceMap[namespace] = module;
}
// set state
if (!isRoot && !hot) {
var parentState = getNestedState(rootState, path.slice(0, -1));
var moduleName = path[path.length - 1];
store._withCommit(function () {
if ((true)) {
if (moduleName in parentState) {
console.warn(
("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"")
);
}
}
Vue.set(parentState, moduleName, module.state);
});
}
var local = module.context = makeLocalContext(store, namespace, path);
module.forEachMutation(function (mutation, key) {
var namespacedType = namespace + key;
registerMutation(store, namespacedType, mutation, local);
});
module.forEachAction(function (action, key) {
var type = action.root ? key : namespace + key;
var handler = action.handler || action;
registerAction(store, type, handler, local);
});
module.forEachGetter(function (getter, key) {
var namespacedType = namespace + key;
registerGetter(store, namespacedType, getter, local);
});
module.forEachChild(function (child, key) {
installModule(store, rootState, path.concat(key), child, hot);
});
}
/**
* make localized dispatch, commit, getters and state
* if there is no namespace, just use root ones
*/
function makeLocalContext (store, namespace, path) {
var noNamespace = namespace === '';
var local = {
dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) {
var args = unifyObjectStyle(_type, _payload, _options);
var payload = args.payload;
var options = args.options;
var type = args.type;
if (!options || !options.root) {
type = namespace + type;
if (( true) && !store._actions[type]) {
console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type));
return
}
}
return store.dispatch(type, payload)
},
commit: noNamespace ? store.commit : function (_type, _payload, _options) {
var args = unifyObjectStyle(_type, _payload, _options);
var payload = args.payload;
var options = args.options;
var type = args.type;
if (!options || !options.root) {
type = namespace + type;
if (( true) && !store._mutations[type]) {
console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type));
return
}
}
store.commit(type, payload, options);
}
};
// getters and state object must be gotten lazily
// because they will be changed by vm update
Object.defineProperties(local, {
getters: {
get: noNamespace
? function () { return store.getters; }
: function () { return makeLocalGetters(store, namespace); }
},
state: {
get: function () { return getNestedState(store.state, path); }
}
});
return local
}
function makeLocalGetters (store, namespace) {
if (!store._makeLocalGettersCache[namespace]) {
var gettersProxy = {};
var splitPos = namespace.length;
Object.keys(store.getters).forEach(function (type) {
// skip if the target getter is not match this namespace
if (type.slice(0, splitPos) !== namespace) { return }
// extract local getter type
var localType = type.slice(splitPos);
// Add a port to the getters proxy.
// Define as getter property because
// we do not want to evaluate the getters in this time.
Object.defineProperty(gettersProxy, localType, {
get: function () { return store.getters[type]; },
enumerable: true
});
});
store._makeLocalGettersCache[namespace] = gettersProxy;
}
return store._makeLocalGettersCache[namespace]
}
function registerMutation (store, type, handler, local) {
var entry = store._mutations[type] || (store._mutations[type] = []);
entry.push(function wrappedMutationHandler (payload) {
handler.call(store, local.state, payload);
});
}
function registerAction (store, type, handler, local) {
var entry = store._actions[type] || (store._actions[type] = []);
entry.push(function wrappedActionHandler (payload) {
var res = handler.call(store, {
dispatch: local.dispatch,
commit: local.commit,
getters: local.getters,
state: local.state,
rootGetters: store.getters,
rootState: store.state
}, payload);
if (!isPromise(res)) {
res = Promise.resolve(res);
}
if (store._devtoolHook) {
return res.catch(function (err) {
store._devtoolHook.emit('vuex:error', err);
throw err
})
} else {
return res
}
});
}
function registerGetter (store, type, rawGetter, local) {
if (store._wrappedGetters[type]) {
if ((true)) {
console.error(("[vuex] duplicate getter key: " + type));
}
return
}
store._wrappedGetters[type] = function wrappedGetter (store) {
return rawGetter(
local.state, // local state
local.getters, // local getters
store.state, // root state
store.getters // root getters
)
};
}
function enableStrictMode (store) {
store._vm.$watch(function () { return this._data.$$state }, function () {
if ((true)) {
assert(store._committing, "do not mutate vuex store state outside mutation handlers.");
}
}, { deep: true, sync: true });
}
function getNestedState (state, path) {
return path.reduce(function (state, key) { return state[key]; }, state)
}
function unifyObjectStyle (type, payload, options) {
if (isObject(type) && type.type) {
options = payload;
payload = type;
type = type.type;
}
if ((true)) {
assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + "."));
}
return { type: type, payload: payload, options: options }
}
function install (_Vue) {
if (Vue && _Vue === Vue) {
if ((true)) {
console.error(
'[vuex] already installed. Vue.use(Vuex) should be called only once.'
);
}
return
}
Vue = _Vue;
applyMixin(Vue);
}
/**
* Reduce the code which written in Vue.js for getting the state.
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it.
* @param {Object}
*/
var mapState = normalizeNamespace(function (namespace, states) {
var res = {};
if (( true) && !isValidMap(states)) {
console.error('[vuex] mapState: mapper parameter must be either an Array or an Object');
}
normalizeMap(states).forEach(function (ref) {
var key = ref.key;
var val = ref.val;
res[key] = function mappedState () {
var state = this.$store.state;
var getters = this.$store.getters;
if (namespace) {
var module = getModuleByNamespace(this.$store, 'mapState', namespace);
if (!module) {
return
}
state = module.context.state;
getters = module.context.getters;
}
return typeof val === 'function'
? val.call(this, state, getters)
: state[val]
};
// mark vuex getter for devtools
res[key].vuex = true;
});
return res
});
/**
* Reduce the code which written in Vue.js for committing the mutation
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept another params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function.
* @return {Object}
*/
var mapMutations = normalizeNamespace(function (namespace, mutations) {
var res = {};
if (( true) && !isValidMap(mutations)) {
console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object');
}
normalizeMap(mutations).forEach(function (ref) {
var key = ref.key;
var val = ref.val;
res[key] = function mappedMutation () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
// Get the commit method from store
var commit = this.$store.commit;
if (namespace) {
var module = getModuleByNamespace(this.$store, 'mapMutations', namespace);
if (!module) {
return
}
commit = module.context.commit;
}
return typeof val === 'function'
? val.apply(this, [commit].concat(args))
: commit.apply(this.$store, [val].concat(args))
};
});
return res
});
/**
* Reduce the code which written in Vue.js for getting the getters
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} getters
* @return {Object}
*/
var mapGetters = normalizeNamespace(function (namespace, getters) {
var res = {};
if (( true) && !isValidMap(getters)) {
console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object');
}
normalizeMap(getters).forEach(function (ref) {
var key = ref.key;
var val = ref.val;
// The namespace has been mutated by normalizeNamespace
val = namespace + val;
res[key] = function mappedGetter () {
if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
return
}
if (( true) && !(val in this.$store.getters)) {
console.error(("[vuex] unknown getter: " + val));
return
}
return this.$store.getters[val]
};
// mark vuex getter for devtools
res[key].vuex = true;
});
return res
});
/**
* Reduce the code which written in Vue.js for dispatch the action
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function.
* @return {Object}
*/
var mapActions = normalizeNamespace(function (namespace, actions) {
var res = {};
if (( true) && !isValidMap(actions)) {
console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object');
}
normalizeMap(actions).forEach(function (ref) {
var key = ref.key;
var val = ref.val;
res[key] = function mappedAction () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
// get dispatch function from store
var dispatch = this.$store.dispatch;
if (namespace) {
var module = getModuleByNamespace(this.$store, 'mapActions', namespace);
if (!module) {
return
}
dispatch = module.context.dispatch;
}
return typeof val === 'function'
? val.apply(this, [dispatch].concat(args))
: dispatch.apply(this.$store, [val].concat(args))
};
});
return res
});
/**
* Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
* @param {String} namespace
* @return {Object}
*/
var createNamespacedHelpers = function (namespace) { return ({
mapState: mapState.bind(null, namespace),
mapGetters: mapGetters.bind(null, namespace),
mapMutations: mapMutations.bind(null, namespace),
mapActions: mapActions.bind(null, namespace)
}); };
/**
* Normalize the map
* normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
* normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ]
* @param {Array|Object} map
* @return {Object}
*/
function normalizeMap (map) {
if (!isValidMap(map)) {
return []
}
return Array.isArray(map)
? map.map(function (key) { return ({ key: key, val: key }); })
: Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); })
}
/**
* Validate whether given map is valid or not
* @param {*} map
* @return {Boolean}
*/
function isValidMap (map) {
return Array.isArray(map) || isObject(map)
}
/**
* Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map.
* @param {Function} fn
* @return {Function}
*/
function normalizeNamespace (fn) {
return function (namespace, map) {
if (typeof namespace !== 'string') {
map = namespace;
namespace = '';
} else if (namespace.charAt(namespace.length - 1) !== '/') {
namespace += '/';
}
return fn(namespace, map)
}
}
/**
* Search a special module from store by namespace. if module not exist, print error message.
* @param {Object} store
* @param {String} helper
* @param {String} namespace
* @return {Object}
*/
function getModuleByNamespace (store, helper, namespace) {
var module = store._modulesNamespaceMap[namespace];
if (( true) && !module) {
console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace));
}
return module
}
// Credits: borrowed code from fcomb/redux-logger
function createLogger (ref) {
if ( ref === void 0 ) ref = {};
var collapsed = ref.collapsed; if ( collapsed === void 0 ) collapsed = true;
var filter = ref.filter; if ( filter === void 0 ) filter = function (mutation, stateBefore, stateAfter) { return true; };
var transformer = ref.transformer; if ( transformer === void 0 ) transformer = function (state) { return state; };
var mutationTransformer = ref.mutationTransformer; if ( mutationTransformer === void 0 ) mutationTransformer = function (mut) { return mut; };
var actionFilter = ref.actionFilter; if ( actionFilter === void 0 ) actionFilter = function (action, state) { return true; };
var actionTransformer = ref.actionTransformer; if ( actionTransformer === void 0 ) actionTransformer = function (act) { return act; };
var logMutations = ref.logMutations; if ( logMutations === void 0 ) logMutations = true;
var logActions = ref.logActions; if ( logActions === void 0 ) logActions = true;
var logger = ref.logger; if ( logger === void 0 ) logger = console;
return function (store) {
var prevState = deepCopy(store.state);
if (typeof logger === 'undefined') {
return
}
if (logMutations) {
store.subscribe(function (mutation, state) {
var nextState = deepCopy(state);
if (filter(mutation, prevState, nextState)) {
var formattedTime = getFormattedTime();
var formattedMutation = mutationTransformer(mutation);
var message = "mutation " + (mutation.type) + formattedTime;
startMessage(logger, message, collapsed);
logger.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState));
logger.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation);
logger.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState));
endMessage(logger);
}
prevState = nextState;
});
}
if (logActions) {
store.subscribeAction(function (action, state) {
if (actionFilter(action, state)) {
var formattedTime = getFormattedTime();
var formattedAction = actionTransformer(action);
var message = "action " + (action.type) + formattedTime;
startMessage(logger, message, collapsed);
logger.log('%c action', 'color: #03A9F4; font-weight: bold', formattedAction);
endMessage(logger);
}
});
}
}
}
function startMessage (logger, message, collapsed) {
var startMessage = collapsed
? logger.groupCollapsed
: logger.group;
// render
try {
startMessage.call(logger, message);
} catch (e) {
logger.log(message);
}
}
function endMessage (logger) {
try {
logger.groupEnd();
} catch (e) {
logger.log('—— log end ——');
}
}
function getFormattedTime () {
var time = new Date();
return (" @ " + (pad(time.getHours(), 2)) + ":" + (pad(time.getMinutes(), 2)) + ":" + (pad(time.getSeconds(), 2)) + "." + (pad(time.getMilliseconds(), 3)))
}
function repeat (str, times) {
return (new Array(times + 1)).join(str)
}
function pad (num, maxLength) {
return repeat('0', maxLength - num.toString().length) + num
}
var index_cjs = {
Store: Store,
install: install,
version: '3.6.2',
mapState: mapState,
mapMutations: mapMutations,
mapGetters: mapGetters,
mapActions: mapActions,
createNamespacedHelpers: createNamespacedHelpers,
createLogger: createLogger
};
module.exports = index_cjs;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../../webpack/buildin/global.js */ 3)))
/***/ }),
/* 35 */
/*!****************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/store/modules/user.js ***!
\****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(uni) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = {
// 类似 vue 的 data
state: {
location: {
lat: '',
lon: ''
},
userInfo: {
token: ""
},
//保存用户登录信息,
toPath: "",
//要跳转过去的页面,
products: "",
//订单数据
linkProducts: "",
//用来支付的订单数据
coupon: "",
//景点下单选择优惠券
eshoppingCart: [],
//自提产品购物车下单数据
sshoppingCart: [],
//邮寄产品购物车下单数据
meetRoomReserve: {
date: null,
//使用日期信息
coupon: null,
// 优惠券信息
people: null //预定人信息
},
// 会议预定信息
lingoIds: [],
// 语言列表
scenicIds: [] // 景区列表
},
// 类似 vue 里的 mothods(同步方法)
mutations: {
//改变用户信息,自动保存到本地的COOKIE
changeUserInfo: function changeUserInfo(state, data) {
state.userInfo = data;
uni.setStorageSync('userInfo', JSON.stringify(data));
},
changeLoationInfo: function changeLoationInfo(state, data) {
uni.setStorageSync('locationInfo', JSON.stringify(data));
state.location = data;
},
changeLoginPath: function changeLoginPath(state) {
var pages = getCurrentPages(); //获取加载的页面
var currentPage = pages[pages.length - 1]; //获取当前页面的对象
state.toPath = currentPage.$page.fullPath;
if (state.toPath == '/pages/login/login') return;
// 登录
uni.navigateTo({
url: '/pages/login/login'
});
},
//订单数据
changeOrderInfo: function changeOrderInfo(state, data) {
state.products = data;
},
//获取支付订单数据
changelinkProducts: function changelinkProducts(state, data) {
state.linkProducts = data;
},
// 选择优惠券
choseCoupon: function choseCoupon(state, data) {
state.coupon = data;
},
// 自提产品购物车下单
changeOrderECart: function changeOrderECart(state, data) {
state.eshoppingCart = data;
},
// 邮寄产品购物车下单
changeOrderSCart: function changeOrderSCart(state, data) {
state.sshoppingCart = data;
},
//meetRoomReserve修改会议预定信息
changeMeetRoomReserve: function changeMeetRoomReserve(state, data) {
state.meetRoomReserve = data;
},
changeLingoIds: function changeLingoIds(state, data) {
state.lingoIds = data;
},
changeScenicIds: function changeScenicIds(state, data) {
state.scenicIds = data;
}
}
};
exports.default = _default;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/index.js */ 2)["default"]))
/***/ }),
/* 36 */
/*!***************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/static/js/request.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(uni) {
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ 4);
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _vue = _interopRequireDefault(__webpack_require__(/*! vue */ 25));
var _store = _interopRequireDefault(__webpack_require__(/*! @/store */ 33));
var NEWAPIURL = true ? 'http://47.103.142.123:1010' : undefined;
_vue.default.prototype.NEWAPIURL = NEWAPIURL;
_vue.default.prototype.Post = function (params, apiurl) {
if (uni.getStorageSync('userInfo') && JSON.parse(uni.getStorageSync('userInfo')).token) params.merchants_token = JSON.parse(uni.getStorageSync('userInfo')).token;else if (_store.default.state.user.userInfo.token) params.merchants_token = _store.default.state.user.userInfo.token;
return new Promise(function (resolve, reject) {
uni.showLoading({
title: '加载中'
});
uni.request({
method: params.method || 'GET',
url: NEWAPIURL + apiurl,
data: params || {},
header: params.header || {
'content-type': 'application/json',
'merchants_token': params.merchants_token || ''
},
success: function success(res) {
uni.hideLoading();
console.log('success', res.data);
if (res.data.code === 200 || res.data.code === 1) {
resolve(res.data);
} else {
setTimeout(function () {
uni.showToast({
title: res.data.msg,
icon: 'none'
});
reject(null);
}, 0);
if (res.data.code === 401) {
_store.default.commit('changeLoginPath');
}
}
},
fail: function fail(err) {
console.log('err', err);
uni.hideLoading();
setTimeout(function () {
uni.showToast({
title: err.msg || err.data.msg,
icon: 'none'
});
}, 0);
if (err.data.code === 401) {
_store.default.commit('changeLoginPath');
}
reject(err);
}
});
});
};
var _default = NEWAPIURL;
exports.default = _default;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/index.js */ 2)["default"]))
/***/ }),
/* 37 */
/*!**********************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/static/js/CommonFunction.js ***!
\**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(uni) {
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ 4);
var _vue = _interopRequireDefault(__webpack_require__(/*! vue */ 25));
// 获取路径参数
// 格式化富文本
_vue.default.prototype.formateRichText = function (str) {
if (!str) return "";
var reg = new RegExp("<img", "g");
str = str.replace(reg, "<img class='sz-xcx-fwb-img' width='100%'");
reg = new RegExp("<IMG", "g");
str = str.replace(reg, "<img class='sz-xcx-fwb-img' width='100%'");
reg = new RegExp("&nbsp;", "g");
str = str.replace(reg, '<span style="width: 8rpx;display: inline-block;"></span>');
reg = new RegExp("section", "g");
str = str.replace(reg, 'div');
reg = new RegExp("↵", "g");
str = str.replace(reg, '<br />');
return str;
};
// 获取路径参数
_vue.default.prototype.getUrlPara = function (url) {
var arrUrl = url.split("?");
var para = arrUrl[1];
return para ? para.split('&') : false;
};
// 中文姓名规则
_vue.default.prototype.idChinaName = function (val) {
var pattern = /^[\u4E00-\u9FA5]{2,4}$/;
return pattern.test(val);
};
// 身份证验证规则
_vue.default.prototype.idCardNumber = function (val) {
var pattern = /^\d{17}(\d{1}|[X|x])$/;
return pattern.test(val);
};
//判断电话号码格式
_vue.default.prototype.IsTel = function (tel) {
var pattern = /^1\d{10}$/;
return pattern.test(tel);
};
//判断澳门电话号码格式
_vue.default.prototype.IsTelMacau = function (tel) {
var pattern = /^\d{8}$/;
return pattern.test(tel);
};
//验证码格式
_vue.default.prototype.IsCode = function (code) {
var pattern = /^\d{6}$/;
return pattern.test(code);
};
//判断邮箱
_vue.default.prototype.IsMail = function (code) {
var pattern = /^\w+@[a-z0-9]+\.[a-z]+$/i;
return pattern.test(code);
};
// 图片显示判断
_vue.default.prototype.showImg = function (img) {
if (!img) return;
if (img.indexOf('https://') != -1 || img.indexOf('http://') != -1) {
return img;
} else {
return 'http://47.103.142.123:1010' + img;
}
};
// 获取经纬度
_vue.default.prototype.getLocation = function () {
uni.startLocationUpdate({
success: function success(res) {
uni.onLocationChange(function (data) {
uni.setStorageSync('location', {
lat: data.latitude,
lon: data.longitude
});
});
}
});
};
// 金刚区头图
_vue.default.prototype.getHeadImg = function (type) {
return _vue.default.prototype.Post({
type: type
}, '/api/public_service/getKumgangHeadImgList').then(function (res) {
return res.data[0].image;
});
};
// 路由页面跳转
_vue.default.prototype.gotoPath = function (path) {
uni.navigateTo({
url: path
});
};
// 返回上一页
_vue.default.prototype.goBack = function () {
console.log(getCurrentPages());
var pages = getCurrentPages();
var page = pages[pages.length - 1];
if (page.route == 'subPackages/techan/techanList') {
uni.switchTab({
url: '/pages/index/index'
});
return;
}
getCurrentPages().length > 1 ? uni.navigateBack({}) : uni.switchTab({
url: '/pages/index/index'
});
};
// 打开地图
_vue.default.prototype.openLocation = function (lat, lon) {
uni.openLocation({
latitude: Number(lat),
longitude: Number(lon),
success: function success() {
console.log('success');
}
});
};
// 拨打电话
_vue.default.prototype.clickPhone = function (phone) {
uni.makePhoneCall({
phoneNumber: phone
});
};
// 周几
_vue.default.prototype.ShowDateDay = function (day) {
var stateTxt = "";
switch (day) {
case 0:
stateTxt = '周日';
break;
case 1:
stateTxt = '周一';
break;
case 2:
stateTxt = '周二';
break;
case 3:
stateTxt = '周三';
break;
case 4:
stateTxt = '周四';
break;
case 5:
stateTxt = '周五';
break;
case 6:
stateTxt = '周六';
break;
}
return stateTxt;
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/index.js */ 2)["default"]))
/***/ }),
/* 38 */,
/* 39 */,
/* 40 */,
/* 41 */,
/* 42 */,
/* 43 */,
/* 44 */,
/* 45 */,
/* 46 */,
/* 47 */,
/* 48 */,
/* 49 */,
/* 50 */,
/* 51 */,
/* 52 */,
/* 53 */,
/* 54 */,
/* 55 */,
/* 56 */,
/* 57 */,
/* 58 */,
/* 59 */,
/* 60 */
/*!*********************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/index.js ***!
\*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "Html5Qrcode", {
enumerable: true,
get: function get() {
return _html5Qrcode.Html5Qrcode;
}
});
Object.defineProperty(exports, "Html5QrcodeScanType", {
enumerable: true,
get: function get() {
return _core.Html5QrcodeScanType;
}
});
Object.defineProperty(exports, "Html5QrcodeScanner", {
enumerable: true,
get: function get() {
return _html5QrcodeScanner.Html5QrcodeScanner;
}
});
Object.defineProperty(exports, "Html5QrcodeScannerState", {
enumerable: true,
get: function get() {
return _stateManager.Html5QrcodeScannerState;
}
});
Object.defineProperty(exports, "Html5QrcodeSupportedFormats", {
enumerable: true,
get: function get() {
return _core.Html5QrcodeSupportedFormats;
}
});
var _html5Qrcode = __webpack_require__(/*! ./html5-qrcode */ 61);
var _html5QrcodeScanner = __webpack_require__(/*! ./html5-qrcode-scanner */ 81);
var _core = __webpack_require__(/*! ./core */ 62);
var _stateManager = __webpack_require__(/*! ./state-manager */ 80);
/***/ }),
/* 61 */
/*!****************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/html5-qrcode.js ***!
\****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ 4);
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Html5Qrcode = void 0;
var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ 13));
var _core = __webpack_require__(/*! ./core */ 62);
var _strings = __webpack_require__(/*! ./strings */ 63);
var _utils = __webpack_require__(/*! ./utils */ 64);
var _codeDecoder = __webpack_require__(/*! ./code-decoder */ 65);
var _factories = __webpack_require__(/*! ./camera/factories */ 77);
var _retriever = __webpack_require__(/*! ./camera/retriever */ 79);
var _stateManager = __webpack_require__(/*! ./state-manager */ 80);
var __extends = void 0 && (void 0).__extends || function () {
var _extendStatics = function extendStatics(d, b) {
_extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) {
if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
}
};
return _extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
_extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
}();
var Constants = function (_super) {
__extends(Constants, _super);
function Constants() {
return _super !== null && _super.apply(this, arguments) || this;
}
Constants.DEFAULT_WIDTH = 300;
Constants.DEFAULT_WIDTH_OFFSET = 2;
Constants.FILE_SCAN_MIN_HEIGHT = 300;
Constants.FILE_SCAN_HIDDEN_CANVAS_PADDING = 100;
Constants.MIN_QR_BOX_SIZE = 50;
Constants.SHADED_LEFT = 1;
Constants.SHADED_RIGHT = 2;
Constants.SHADED_TOP = 3;
Constants.SHADED_BOTTOM = 4;
Constants.SHADED_REGION_ELEMENT_ID = "qr-shaded-region";
Constants.VERBOSE = false;
Constants.BORDER_SHADER_DEFAULT_COLOR = "#ffffff";
Constants.BORDER_SHADER_MATCH_COLOR = "rgb(90, 193, 56)";
return Constants;
}(_core.Html5QrcodeConstants);
var InternalHtml5QrcodeConfig = function () {
function InternalHtml5QrcodeConfig(config, logger) {
this.logger = logger;
this.fps = Constants.SCAN_DEFAULT_FPS;
if (!config) {
this.disableFlip = Constants.DEFAULT_DISABLE_FLIP;
} else {
if (config.fps) {
this.fps = config.fps;
}
this.disableFlip = config.disableFlip === true;
this.qrbox = config.qrbox;
this.aspectRatio = config.aspectRatio;
this.videoConstraints = config.videoConstraints;
}
}
InternalHtml5QrcodeConfig.prototype.isMediaStreamConstraintsValid = function () {
if (!this.videoConstraints) {
this.logger.logError("Empty videoConstraints", true);
return false;
}
return _utils.VideoConstraintsUtil.isMediaStreamConstraintsValid(this.videoConstraints, this.logger);
};
InternalHtml5QrcodeConfig.prototype.isShadedBoxEnabled = function () {
return !(0, _core.isNullOrUndefined)(this.qrbox);
};
InternalHtml5QrcodeConfig.create = function (config, logger) {
return new InternalHtml5QrcodeConfig(config, logger);
};
return InternalHtml5QrcodeConfig;
}();
var Html5Qrcode = function () {
function Html5Qrcode(elementId, configOrVerbosityFlag) {
this.element = null;
this.canvasElement = null;
this.scannerPausedUiElement = null;
this.hasBorderShaders = null;
this.borderShaders = null;
this.qrMatch = null;
this.renderedCamera = null;
this.qrRegion = null;
this.context = null;
this.lastScanImageFile = null;
this.isScanning = false;
if (!document.getElementById(elementId)) {
throw "HTML Element with id=".concat(elementId, " not found");
}
this.elementId = elementId;
this.verbose = false;
var experimentalFeatureConfig;
var configObject;
if (typeof configOrVerbosityFlag == "boolean") {
this.verbose = configOrVerbosityFlag === true;
} else if (configOrVerbosityFlag) {
configObject = configOrVerbosityFlag;
this.verbose = configObject.verbose === true;
experimentalFeatureConfig = configObject.experimentalFeatures;
}
this.logger = new _core.BaseLoggger(this.verbose);
this.qrcode = new _codeDecoder.Html5QrcodeShim(this.getSupportedFormats(configOrVerbosityFlag), this.getUseBarCodeDetectorIfSupported(configObject), this.verbose, this.logger);
this.foreverScanTimeout;
this.shouldScan = true;
this.stateManagerProxy = _stateManager.StateManagerFactory.create();
}
Html5Qrcode.prototype.start = function (cameraIdOrConfig, configuration, qrCodeSuccessCallback, qrCodeErrorCallback) {
var _this = this;
if (!cameraIdOrConfig) {
throw "cameraIdOrConfig is required";
}
if (!qrCodeSuccessCallback || typeof qrCodeSuccessCallback != "function") {
throw "qrCodeSuccessCallback is required and should be a function.";
}
var qrCodeErrorCallbackInternal;
if (qrCodeErrorCallback) {
qrCodeErrorCallbackInternal = qrCodeErrorCallback;
} else {
qrCodeErrorCallbackInternal = this.verbose ? this.logger.log : function () {};
}
var internalConfig = InternalHtml5QrcodeConfig.create(configuration, this.logger);
this.clearElement();
var videoConstraintsAvailableAndValid = false;
if (internalConfig.videoConstraints) {
if (!internalConfig.isMediaStreamConstraintsValid()) {
this.logger.logError("'videoConstraints' is not valid 'MediaStreamConstraints, " + "it will be ignored.'", true);
} else {
videoConstraintsAvailableAndValid = true;
}
}
var areVideoConstraintsEnabled = videoConstraintsAvailableAndValid;
var element = document.getElementById(this.elementId);
var rootElementWidth = element.clientWidth ? element.clientWidth : Constants.DEFAULT_WIDTH;
element.style.position = "relative";
this.shouldScan = true;
this.element = element;
var $this = this;
var toScanningStateChangeTransaction = this.stateManagerProxy.startTransition(_stateManager.Html5QrcodeScannerState.SCANNING);
return new Promise(function (resolve, reject) {
var videoConstraints = areVideoConstraintsEnabled ? internalConfig.videoConstraints : $this.createVideoConstraints(cameraIdOrConfig);
if (!videoConstraints) {
toScanningStateChangeTransaction.cancel();
reject("videoConstraints should be defined");
return;
}
var cameraRenderingOptions = {};
if (!areVideoConstraintsEnabled || internalConfig.aspectRatio) {
cameraRenderingOptions.aspectRatio = internalConfig.aspectRatio;
}
var renderingCallbacks = {
onRenderSurfaceReady: function onRenderSurfaceReady(viewfinderWidth, viewfinderHeight) {
$this.setupUi(viewfinderWidth, viewfinderHeight, internalConfig);
$this.isScanning = true;
$this.foreverScan(internalConfig, qrCodeSuccessCallback, qrCodeErrorCallbackInternal);
}
};
_factories.CameraFactory.failIfNotSupported().then(function (factory) {
factory.create(videoConstraints).then(function (camera) {
return camera.render(_this.element, cameraRenderingOptions, renderingCallbacks).then(function (renderedCamera) {
$this.renderedCamera = renderedCamera;
toScanningStateChangeTransaction.execute();
resolve(null);
}).catch(function (error) {
toScanningStateChangeTransaction.cancel();
reject(error);
});
}).catch(function (error) {
toScanningStateChangeTransaction.cancel();
reject(_strings.Html5QrcodeStrings.errorGettingUserMedia(error));
});
}).catch(function (_) {
toScanningStateChangeTransaction.cancel();
reject(_strings.Html5QrcodeStrings.cameraStreamingNotSupported());
});
});
};
Html5Qrcode.prototype.pause = function (shouldPauseVideo) {
if (!this.stateManagerProxy.isStrictlyScanning()) {
throw "Cannot pause, scanner is not scanning.";
}
this.stateManagerProxy.directTransition(_stateManager.Html5QrcodeScannerState.PAUSED);
this.showPausedState();
if ((0, _core.isNullOrUndefined)(shouldPauseVideo) || shouldPauseVideo !== true) {
shouldPauseVideo = false;
}
if (shouldPauseVideo && this.renderedCamera) {
this.renderedCamera.pause();
}
};
Html5Qrcode.prototype.resume = function () {
if (!this.stateManagerProxy.isPaused()) {
throw "Cannot result, scanner is not paused.";
}
if (!this.renderedCamera) {
throw "renderedCamera doesn't exist while trying resume()";
}
var $this = this;
var transitionToScanning = function transitionToScanning() {
$this.stateManagerProxy.directTransition(_stateManager.Html5QrcodeScannerState.SCANNING);
$this.hidePausedState();
};
if (!this.renderedCamera.isPaused()) {
transitionToScanning();
return;
}
this.renderedCamera.resume(function () {
transitionToScanning();
});
};
Html5Qrcode.prototype.getState = function () {
return this.stateManagerProxy.getState();
};
Html5Qrcode.prototype.stop = function () {
var _this = this;
if (!this.stateManagerProxy.isScanning()) {
throw "Cannot stop, scanner is not running or paused.";
}
var toStoppedStateTransaction = this.stateManagerProxy.startTransition(_stateManager.Html5QrcodeScannerState.NOT_STARTED);
this.shouldScan = false;
if (this.foreverScanTimeout) {
clearTimeout(this.foreverScanTimeout);
}
var removeQrRegion = function removeQrRegion() {
if (!_this.element) {
return;
}
var childElement = document.getElementById(Constants.SHADED_REGION_ELEMENT_ID);
if (childElement) {
_this.element.removeChild(childElement);
}
};
var $this = this;
return this.renderedCamera.close().then(function () {
$this.renderedCamera = null;
if ($this.element) {
$this.element.removeChild($this.canvasElement);
$this.canvasElement = null;
}
removeQrRegion();
if ($this.qrRegion) {
$this.qrRegion = null;
}
if ($this.context) {
$this.context = null;
}
toStoppedStateTransaction.execute();
$this.hidePausedState();
$this.isScanning = false;
return Promise.resolve();
});
};
Html5Qrcode.prototype.scanFile = function (imageFile, showImage) {
return this.scanFileV2(imageFile, showImage).then(function (html5qrcodeResult) {
return html5qrcodeResult.decodedText;
});
};
Html5Qrcode.prototype.scanFileV2 = function (imageFile, showImage) {
var _this = this;
if (!imageFile || !(imageFile instanceof File)) {
throw "imageFile argument is mandatory and should be instance " + "of File. Use 'event.target.files[0]'.";
}
if ((0, _core.isNullOrUndefined)(showImage)) {
showImage = true;
}
if (!this.stateManagerProxy.canScanFile()) {
throw "Cannot start file scan - ongoing camera scan";
}
return new Promise(function (resolve, reject) {
_this.possiblyCloseLastScanImageFile();
_this.clearElement();
_this.lastScanImageFile = URL.createObjectURL(imageFile);
var inputImage = new Image();
inputImage.onload = function () {
var imageWidth = inputImage.width;
var imageHeight = inputImage.height;
var element = document.getElementById(_this.elementId);
var containerWidth = element.clientWidth ? element.clientWidth : Constants.DEFAULT_WIDTH;
var containerHeight = Math.max(element.clientHeight ? element.clientHeight : imageHeight, Constants.FILE_SCAN_MIN_HEIGHT);
var config = _this.computeCanvasDrawConfig(imageWidth, imageHeight, containerWidth, containerHeight);
if (showImage) {
var visibleCanvas = _this.createCanvasElement(containerWidth, containerHeight, "qr-canvas-visible");
visibleCanvas.style.display = "inline-block";
element.appendChild(visibleCanvas);
var context_1 = visibleCanvas.getContext("2d");
if (!context_1) {
throw "Unable to get 2d context from canvas";
}
context_1.canvas.width = containerWidth;
context_1.canvas.height = containerHeight;
context_1.drawImage(inputImage, 0, 0, imageWidth, imageHeight, config.x, config.y, config.width, config.height);
}
var padding = Constants.FILE_SCAN_HIDDEN_CANVAS_PADDING;
var hiddenImageWidth = Math.max(inputImage.width, config.width);
var hiddenImageHeight = Math.max(inputImage.height, config.height);
var hiddenCanvasWidth = hiddenImageWidth + 2 * padding;
var hiddenCanvasHeight = hiddenImageHeight + 2 * padding;
var hiddenCanvas = _this.createCanvasElement(hiddenCanvasWidth, hiddenCanvasHeight);
element.appendChild(hiddenCanvas);
var context = hiddenCanvas.getContext("2d");
if (!context) {
throw "Unable to get 2d context from canvas";
}
context.canvas.width = hiddenCanvasWidth;
context.canvas.height = hiddenCanvasHeight;
context.drawImage(inputImage, 0, 0, imageWidth, imageHeight, padding, padding, hiddenImageWidth, hiddenImageHeight);
try {
_this.qrcode.decodeRobustlyAsync(hiddenCanvas).then(function (result) {
resolve(_core.Html5QrcodeResultFactory.createFromQrcodeResult(result));
}).catch(reject);
} catch (exception) {
reject("QR code parse error, error = ".concat(exception));
}
};
inputImage.onerror = reject;
inputImage.onabort = reject;
inputImage.onstalled = reject;
inputImage.onsuspend = reject;
inputImage.src = URL.createObjectURL(imageFile);
});
};
Html5Qrcode.prototype.clear = function () {
this.clearElement();
};
Html5Qrcode.getCameras = function () {
return _retriever.CameraRetriever.retrieve();
};
Html5Qrcode.prototype.getRunningTrackCapabilities = function () {
return this.getRenderedCameraOrFail().getRunningTrackCapabilities();
};
Html5Qrcode.prototype.getRunningTrackSettings = function () {
return this.getRenderedCameraOrFail().getRunningTrackSettings();
};
Html5Qrcode.prototype.getRunningTrackCameraCapabilities = function () {
return this.getRenderedCameraOrFail().getCapabilities();
};
Html5Qrcode.prototype.applyVideoConstraints = function (videoConstaints) {
if (!videoConstaints) {
throw "videoConstaints is required argument.";
} else if (!_utils.VideoConstraintsUtil.isMediaStreamConstraintsValid(videoConstaints, this.logger)) {
throw "invalid videoConstaints passed, check logs for more details";
}
return this.getRenderedCameraOrFail().applyVideoConstraints(videoConstaints);
};
Html5Qrcode.prototype.getRenderedCameraOrFail = function () {
if (this.renderedCamera == null) {
throw "Scanning is not in running state, call this API only when" + " QR code scanning using camera is in running state.";
}
return this.renderedCamera;
};
Html5Qrcode.prototype.getSupportedFormats = function (configOrVerbosityFlag) {
var allFormats = [_core.Html5QrcodeSupportedFormats.QR_CODE, _core.Html5QrcodeSupportedFormats.AZTEC, _core.Html5QrcodeSupportedFormats.CODABAR, _core.Html5QrcodeSupportedFormats.CODE_39, _core.Html5QrcodeSupportedFormats.CODE_93, _core.Html5QrcodeSupportedFormats.CODE_128, _core.Html5QrcodeSupportedFormats.DATA_MATRIX, _core.Html5QrcodeSupportedFormats.MAXICODE, _core.Html5QrcodeSupportedFormats.ITF, _core.Html5QrcodeSupportedFormats.EAN_13, _core.Html5QrcodeSupportedFormats.EAN_8, _core.Html5QrcodeSupportedFormats.PDF_417, _core.Html5QrcodeSupportedFormats.RSS_14, _core.Html5QrcodeSupportedFormats.RSS_EXPANDED, _core.Html5QrcodeSupportedFormats.UPC_A, _core.Html5QrcodeSupportedFormats.UPC_E, _core.Html5QrcodeSupportedFormats.UPC_EAN_EXTENSION];
if (!configOrVerbosityFlag || typeof configOrVerbosityFlag == "boolean") {
return allFormats;
}
if (!configOrVerbosityFlag.formatsToSupport) {
return allFormats;
}
if (!Array.isArray(configOrVerbosityFlag.formatsToSupport)) {
throw "configOrVerbosityFlag.formatsToSupport should be undefined " + "or an array.";
}
if (configOrVerbosityFlag.formatsToSupport.length === 0) {
throw "Atleast 1 formatsToSupport is needed.";
}
var supportedFormats = [];
for (var _i = 0, _a = configOrVerbosityFlag.formatsToSupport; _i < _a.length; _i++) {
var format = _a[_i];
if ((0, _core.isValidHtml5QrcodeSupportedFormats)(format)) {
supportedFormats.push(format);
} else {
this.logger.warn("Invalid format: ".concat(format, " passed in config, ignoring."));
}
}
if (supportedFormats.length === 0) {
throw "None of formatsToSupport match supported values.";
}
return supportedFormats;
};
Html5Qrcode.prototype.getUseBarCodeDetectorIfSupported = function (config) {
if ((0, _core.isNullOrUndefined)(config)) {
return true;
}
if (!(0, _core.isNullOrUndefined)(config.useBarCodeDetectorIfSupported)) {
return config.useBarCodeDetectorIfSupported !== false;
}
if ((0, _core.isNullOrUndefined)(config.experimentalFeatures)) {
return true;
}
var experimentalFeatures = config.experimentalFeatures;
if ((0, _core.isNullOrUndefined)(experimentalFeatures.useBarCodeDetectorIfSupported)) {
return true;
}
return experimentalFeatures.useBarCodeDetectorIfSupported !== false;
};
Html5Qrcode.prototype.validateQrboxSize = function (viewfinderWidth, viewfinderHeight, internalConfig) {
var _this = this;
var qrboxSize = internalConfig.qrbox;
this.validateQrboxConfig(qrboxSize);
var qrDimensions = this.toQrdimensions(viewfinderWidth, viewfinderHeight, qrboxSize);
var validateMinSize = function validateMinSize(size) {
if (size < Constants.MIN_QR_BOX_SIZE) {
throw "minimum size of 'config.qrbox' dimension value is" + " ".concat(Constants.MIN_QR_BOX_SIZE, "px.");
}
};
var correctWidthBasedOnRootElementSize = function correctWidthBasedOnRootElementSize(configWidth) {
if (configWidth > viewfinderWidth) {
_this.logger.warn("`qrbox.width` or `qrbox` is larger than the" + " width of the root element. The width will be truncated" + " to the width of root element.");
configWidth = viewfinderWidth;
}
return configWidth;
};
validateMinSize(qrDimensions.width);
validateMinSize(qrDimensions.height);
qrDimensions.width = correctWidthBasedOnRootElementSize(qrDimensions.width);
};
Html5Qrcode.prototype.validateQrboxConfig = function (qrboxSize) {
if (typeof qrboxSize === "number") {
return;
}
if (typeof qrboxSize === "function") {
return;
}
if (qrboxSize.width === undefined || qrboxSize.height === undefined) {
throw "Invalid instance of QrDimensions passed for " + "'config.qrbox'. Both 'width' and 'height' should be set.";
}
};
Html5Qrcode.prototype.toQrdimensions = function (viewfinderWidth, viewfinderHeight, qrboxSize) {
if (typeof qrboxSize === "number") {
return {
width: qrboxSize,
height: qrboxSize
};
} else if (typeof qrboxSize === "function") {
try {
return qrboxSize(viewfinderWidth, viewfinderHeight);
} catch (error) {
throw new Error("qrbox config was passed as a function but it failed with " + "unknown error" + error);
}
}
return qrboxSize;
};
Html5Qrcode.prototype.setupUi = function (viewfinderWidth, viewfinderHeight, internalConfig) {
if (internalConfig.isShadedBoxEnabled()) {
this.validateQrboxSize(viewfinderWidth, viewfinderHeight, internalConfig);
}
var qrboxSize = (0, _core.isNullOrUndefined)(internalConfig.qrbox) ? {
width: viewfinderWidth,
height: viewfinderHeight
} : internalConfig.qrbox;
this.validateQrboxConfig(qrboxSize);
var qrDimensions = this.toQrdimensions(viewfinderWidth, viewfinderHeight, qrboxSize);
if (qrDimensions.height > viewfinderHeight) {
this.logger.warn("[Html5Qrcode] config.qrbox has height that is" + "greater than the height of the video stream. Shading will be" + " ignored");
}
var shouldShadingBeApplied = internalConfig.isShadedBoxEnabled() && qrDimensions.height <= viewfinderHeight;
var defaultQrRegion = {
x: 0,
y: 0,
width: viewfinderWidth,
height: viewfinderHeight
};
var qrRegion = shouldShadingBeApplied ? this.getShadedRegionBounds(viewfinderWidth, viewfinderHeight, qrDimensions) : defaultQrRegion;
var canvasElement = this.createCanvasElement(qrRegion.width, qrRegion.height);
var contextAttributes = {
willReadFrequently: true
};
var context = canvasElement.getContext("2d", contextAttributes);
context.canvas.width = qrRegion.width;
context.canvas.height = qrRegion.height;
this.element.append(canvasElement);
if (shouldShadingBeApplied) {
this.possiblyInsertShadingElement(this.element, viewfinderWidth, viewfinderHeight, qrDimensions);
}
this.createScannerPausedUiElement(this.element);
this.qrRegion = qrRegion;
this.context = context;
this.canvasElement = canvasElement;
};
Html5Qrcode.prototype.createScannerPausedUiElement = function (rootElement) {
var scannerPausedUiElement = document.createElement("div");
scannerPausedUiElement.innerText = _strings.Html5QrcodeStrings.scannerPaused();
scannerPausedUiElement.style.display = "none";
scannerPausedUiElement.style.position = "absolute";
scannerPausedUiElement.style.top = "0px";
scannerPausedUiElement.style.zIndex = "1";
scannerPausedUiElement.style.background = "rgba(9, 9, 9, 0.46)";
scannerPausedUiElement.style.color = "#FFECEC";
scannerPausedUiElement.style.textAlign = "center";
scannerPausedUiElement.style.width = "100%";
rootElement.appendChild(scannerPausedUiElement);
this.scannerPausedUiElement = scannerPausedUiElement;
};
Html5Qrcode.prototype.scanContext = function (qrCodeSuccessCallback, qrCodeErrorCallback) {
var _this = this;
if (this.stateManagerProxy.isPaused()) {
return Promise.resolve(false);
}
return this.qrcode.decodeAsync(this.canvasElement).then(function (result) {
qrCodeSuccessCallback(result.text, _core.Html5QrcodeResultFactory.createFromQrcodeResult(result));
_this.possiblyUpdateShaders(true);
return true;
}).catch(function (error) {
_this.possiblyUpdateShaders(false);
var errorMessage = _strings.Html5QrcodeStrings.codeParseError(error);
qrCodeErrorCallback(errorMessage, _core.Html5QrcodeErrorFactory.createFrom(errorMessage));
return false;
});
};
Html5Qrcode.prototype.foreverScan = function (internalConfig, qrCodeSuccessCallback, qrCodeErrorCallback) {
var _this = this;
if (!this.shouldScan) {
return;
}
if (!this.renderedCamera) {
return;
}
var videoElement = this.renderedCamera.getSurface();
var widthRatio = videoElement.videoWidth / videoElement.clientWidth;
var heightRatio = videoElement.videoHeight / videoElement.clientHeight;
if (!this.qrRegion) {
throw "qrRegion undefined when localMediaStream is ready.";
}
var sWidthOffset = this.qrRegion.width * widthRatio;
var sHeightOffset = this.qrRegion.height * heightRatio;
var sxOffset = this.qrRegion.x * widthRatio;
var syOffset = this.qrRegion.y * heightRatio;
this.context.drawImage(videoElement, sxOffset, syOffset, sWidthOffset, sHeightOffset, 0, 0, this.qrRegion.width, this.qrRegion.height);
var triggerNextScan = function triggerNextScan() {
_this.foreverScanTimeout = setTimeout(function () {
_this.foreverScan(internalConfig, qrCodeSuccessCallback, qrCodeErrorCallback);
}, _this.getTimeoutFps(internalConfig.fps));
};
this.scanContext(qrCodeSuccessCallback, qrCodeErrorCallback).then(function (isSuccessfull) {
if (!isSuccessfull && internalConfig.disableFlip !== true) {
_this.context.translate(_this.context.canvas.width, 0);
_this.context.scale(-1, 1);
_this.scanContext(qrCodeSuccessCallback, qrCodeErrorCallback).finally(function () {
triggerNextScan();
});
} else {
triggerNextScan();
}
}).catch(function (error) {
_this.logger.logError("Error happend while scanning context", error);
triggerNextScan();
});
};
Html5Qrcode.prototype.createVideoConstraints = function (cameraIdOrConfig) {
if (typeof cameraIdOrConfig == "string") {
return {
deviceId: {
exact: cameraIdOrConfig
}
};
} else if ((0, _typeof2.default)(cameraIdOrConfig) == "object") {
var facingModeKey = "facingMode";
var deviceIdKey = "deviceId";
var allowedFacingModeValues_1 = {
"user": true,
"environment": true
};
var exactKey = "exact";
var isValidFacingModeValue = function isValidFacingModeValue(value) {
if (value in allowedFacingModeValues_1) {
return true;
} else {
throw "config has invalid 'facingMode' value = " + "'".concat(value, "'");
}
};
var keys = Object.keys(cameraIdOrConfig);
if (keys.length !== 1) {
throw "'cameraIdOrConfig' object should have exactly 1 key," + " if passed as an object, found ".concat(keys.length, " keys");
}
var key = Object.keys(cameraIdOrConfig)[0];
if (key !== facingModeKey && key !== deviceIdKey) {
throw "Only '".concat(facingModeKey, "' and '").concat(deviceIdKey, "' ") + " are supported for 'cameraIdOrConfig'";
}
if (key === facingModeKey) {
var facingMode = cameraIdOrConfig.facingMode;
if (typeof facingMode == "string") {
if (isValidFacingModeValue(facingMode)) {
return {
facingMode: facingMode
};
}
} else if ((0, _typeof2.default)(facingMode) == "object") {
if (exactKey in facingMode) {
if (isValidFacingModeValue(facingMode["".concat(exactKey)])) {
return {
facingMode: {
exact: facingMode["".concat(exactKey)]
}
};
}
} else {
throw "'facingMode' should be string or object with" + " ".concat(exactKey, " as key.");
}
} else {
var type_1 = (0, _typeof2.default)(facingMode);
throw "Invalid type of 'facingMode' = ".concat(type_1);
}
} else {
var deviceId = cameraIdOrConfig.deviceId;
if (typeof deviceId == "string") {
return {
deviceId: deviceId
};
} else if ((0, _typeof2.default)(deviceId) == "object") {
if (exactKey in deviceId) {
return {
deviceId: {
exact: deviceId["".concat(exactKey)]
}
};
} else {
throw "'deviceId' should be string or object with" + " ".concat(exactKey, " as key.");
}
} else {
var type_2 = (0, _typeof2.default)(deviceId);
throw "Invalid type of 'deviceId' = ".concat(type_2);
}
}
}
var type = (0, _typeof2.default)(cameraIdOrConfig);
throw "Invalid type of 'cameraIdOrConfig' = ".concat(type);
};
Html5Qrcode.prototype.computeCanvasDrawConfig = function (imageWidth, imageHeight, containerWidth, containerHeight) {
if (imageWidth <= containerWidth && imageHeight <= containerHeight) {
var xoffset = (containerWidth - imageWidth) / 2;
var yoffset = (containerHeight - imageHeight) / 2;
return {
x: xoffset,
y: yoffset,
width: imageWidth,
height: imageHeight
};
} else {
var formerImageWidth = imageWidth;
var formerImageHeight = imageHeight;
if (imageWidth > containerWidth) {
imageHeight = containerWidth / imageWidth * imageHeight;
imageWidth = containerWidth;
}
if (imageHeight > containerHeight) {
imageWidth = containerHeight / imageHeight * imageWidth;
imageHeight = containerHeight;
}
this.logger.log("Image downsampled from " + "".concat(formerImageWidth, "X").concat(formerImageHeight) + " to ".concat(imageWidth, "X").concat(imageHeight, "."));
return this.computeCanvasDrawConfig(imageWidth, imageHeight, containerWidth, containerHeight);
}
};
Html5Qrcode.prototype.clearElement = function () {
if (this.stateManagerProxy.isScanning()) {
throw "Cannot clear while scan is ongoing, close it first.";
}
var element = document.getElementById(this.elementId);
if (element) {
element.innerHTML = "";
}
};
Html5Qrcode.prototype.possiblyUpdateShaders = function (qrMatch) {
if (this.qrMatch === qrMatch) {
return;
}
if (this.hasBorderShaders && this.borderShaders && this.borderShaders.length) {
this.borderShaders.forEach(function (shader) {
shader.style.backgroundColor = qrMatch ? Constants.BORDER_SHADER_MATCH_COLOR : Constants.BORDER_SHADER_DEFAULT_COLOR;
});
}
this.qrMatch = qrMatch;
};
Html5Qrcode.prototype.possiblyCloseLastScanImageFile = function () {
if (this.lastScanImageFile) {
URL.revokeObjectURL(this.lastScanImageFile);
this.lastScanImageFile = null;
}
};
Html5Qrcode.prototype.createCanvasElement = function (width, height, customId) {
var canvasWidth = width;
var canvasHeight = height;
var canvasElement = document.createElement("canvas");
canvasElement.style.width = "".concat(canvasWidth, "px");
canvasElement.style.height = "".concat(canvasHeight, "px");
canvasElement.style.display = "none";
canvasElement.id = (0, _core.isNullOrUndefined)(customId) ? "qr-canvas" : customId;
return canvasElement;
};
Html5Qrcode.prototype.getShadedRegionBounds = function (width, height, qrboxSize) {
if (qrboxSize.width > width || qrboxSize.height > height) {
throw "'config.qrbox' dimensions should not be greater than the " + "dimensions of the root HTML element.";
}
return {
x: (width - qrboxSize.width) / 2,
y: (height - qrboxSize.height) / 2,
width: qrboxSize.width,
height: qrboxSize.height
};
};
Html5Qrcode.prototype.possiblyInsertShadingElement = function (element, width, height, qrboxSize) {
if (width - qrboxSize.width < 1 || height - qrboxSize.height < 1) {
return;
}
var shadingElement = document.createElement("div");
shadingElement.style.position = "absolute";
var rightLeftBorderSize = (width - qrboxSize.width) / 2;
var topBottomBorderSize = (height - qrboxSize.height) / 2;
shadingElement.style.borderLeft = "".concat(rightLeftBorderSize, "px solid rgba(0, 0, 0, 0.48)");
shadingElement.style.borderRight = "".concat(rightLeftBorderSize, "px solid rgba(0, 0, 0, 0.48)");
shadingElement.style.borderTop = "".concat(topBottomBorderSize, "px solid rgba(0, 0, 0, 0.48)");
shadingElement.style.borderBottom = "".concat(topBottomBorderSize, "px solid rgba(0, 0, 0, 0.48)");
shadingElement.style.boxSizing = "border-box";
shadingElement.style.top = "0px";
shadingElement.style.bottom = "0px";
shadingElement.style.left = "0px";
shadingElement.style.right = "0px";
shadingElement.id = "".concat(Constants.SHADED_REGION_ELEMENT_ID);
if (width - qrboxSize.width < 11 || height - qrboxSize.height < 11) {
this.hasBorderShaders = false;
} else {
var smallSize = 5;
var largeSize = 40;
this.insertShaderBorders(shadingElement, largeSize, smallSize, -smallSize, null, 0, true);
this.insertShaderBorders(shadingElement, largeSize, smallSize, -smallSize, null, 0, false);
this.insertShaderBorders(shadingElement, largeSize, smallSize, null, -smallSize, 0, true);
this.insertShaderBorders(shadingElement, largeSize, smallSize, null, -smallSize, 0, false);
this.insertShaderBorders(shadingElement, smallSize, largeSize + smallSize, -smallSize, null, -smallSize, true);
this.insertShaderBorders(shadingElement, smallSize, largeSize + smallSize, null, -smallSize, -smallSize, true);
this.insertShaderBorders(shadingElement, smallSize, largeSize + smallSize, -smallSize, null, -smallSize, false);
this.insertShaderBorders(shadingElement, smallSize, largeSize + smallSize, null, -smallSize, -smallSize, false);
this.hasBorderShaders = true;
}
element.append(shadingElement);
};
Html5Qrcode.prototype.insertShaderBorders = function (shaderElem, width, height, top, bottom, side, isLeft) {
var elem = document.createElement("div");
elem.style.position = "absolute";
elem.style.backgroundColor = Constants.BORDER_SHADER_DEFAULT_COLOR;
elem.style.width = "".concat(width, "px");
elem.style.height = "".concat(height, "px");
if (top !== null) {
elem.style.top = "".concat(top, "px");
}
if (bottom !== null) {
elem.style.bottom = "".concat(bottom, "px");
}
if (isLeft) {
elem.style.left = "".concat(side, "px");
} else {
elem.style.right = "".concat(side, "px");
}
if (!this.borderShaders) {
this.borderShaders = [];
}
this.borderShaders.push(elem);
shaderElem.appendChild(elem);
};
Html5Qrcode.prototype.showPausedState = function () {
if (!this.scannerPausedUiElement) {
throw "[internal error] scanner paused UI element not found";
}
this.scannerPausedUiElement.style.display = "block";
};
Html5Qrcode.prototype.hidePausedState = function () {
if (!this.scannerPausedUiElement) {
throw "[internal error] scanner paused UI element not found";
}
this.scannerPausedUiElement.style.display = "none";
};
Html5Qrcode.prototype.getTimeoutFps = function (fps) {
return 1000 / fps;
};
return Html5Qrcode;
}();
exports.Html5Qrcode = Html5Qrcode;
/***/ }),
/* 62 */
/*!********************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/core.js ***!
\********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.QrcodeResultFormat = exports.Html5QrcodeSupportedFormats = exports.Html5QrcodeScanType = exports.Html5QrcodeResultFactory = exports.Html5QrcodeErrorTypes = exports.Html5QrcodeErrorFactory = exports.Html5QrcodeConstants = exports.DecodedTextType = exports.BaseLoggger = void 0;
exports.clip = clip;
exports.isNullOrUndefined = isNullOrUndefined;
exports.isValidHtml5QrcodeSupportedFormats = isValidHtml5QrcodeSupportedFormats;
var Html5QrcodeSupportedFormats;
exports.Html5QrcodeSupportedFormats = Html5QrcodeSupportedFormats;
(function (Html5QrcodeSupportedFormats) {
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["QR_CODE"] = 0] = "QR_CODE";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["AZTEC"] = 1] = "AZTEC";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["CODABAR"] = 2] = "CODABAR";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["CODE_39"] = 3] = "CODE_39";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["CODE_93"] = 4] = "CODE_93";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["CODE_128"] = 5] = "CODE_128";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["DATA_MATRIX"] = 6] = "DATA_MATRIX";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["MAXICODE"] = 7] = "MAXICODE";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["ITF"] = 8] = "ITF";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["EAN_13"] = 9] = "EAN_13";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["EAN_8"] = 10] = "EAN_8";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["PDF_417"] = 11] = "PDF_417";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["RSS_14"] = 12] = "RSS_14";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["RSS_EXPANDED"] = 13] = "RSS_EXPANDED";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["UPC_A"] = 14] = "UPC_A";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["UPC_E"] = 15] = "UPC_E";
Html5QrcodeSupportedFormats[Html5QrcodeSupportedFormats["UPC_EAN_EXTENSION"] = 16] = "UPC_EAN_EXTENSION";
})(Html5QrcodeSupportedFormats || (exports.Html5QrcodeSupportedFormats = Html5QrcodeSupportedFormats = {}));
var html5QrcodeSupportedFormatsTextMap = new Map([[Html5QrcodeSupportedFormats.QR_CODE, "QR_CODE"], [Html5QrcodeSupportedFormats.AZTEC, "AZTEC"], [Html5QrcodeSupportedFormats.CODABAR, "CODABAR"], [Html5QrcodeSupportedFormats.CODE_39, "CODE_39"], [Html5QrcodeSupportedFormats.CODE_93, "CODE_93"], [Html5QrcodeSupportedFormats.CODE_128, "CODE_128"], [Html5QrcodeSupportedFormats.DATA_MATRIX, "DATA_MATRIX"], [Html5QrcodeSupportedFormats.MAXICODE, "MAXICODE"], [Html5QrcodeSupportedFormats.ITF, "ITF"], [Html5QrcodeSupportedFormats.EAN_13, "EAN_13"], [Html5QrcodeSupportedFormats.EAN_8, "EAN_8"], [Html5QrcodeSupportedFormats.PDF_417, "PDF_417"], [Html5QrcodeSupportedFormats.RSS_14, "RSS_14"], [Html5QrcodeSupportedFormats.RSS_EXPANDED, "RSS_EXPANDED"], [Html5QrcodeSupportedFormats.UPC_A, "UPC_A"], [Html5QrcodeSupportedFormats.UPC_E, "UPC_E"], [Html5QrcodeSupportedFormats.UPC_EAN_EXTENSION, "UPC_EAN_EXTENSION"]]);
var DecodedTextType;
exports.DecodedTextType = DecodedTextType;
(function (DecodedTextType) {
DecodedTextType[DecodedTextType["UNKNOWN"] = 0] = "UNKNOWN";
DecodedTextType[DecodedTextType["URL"] = 1] = "URL";
})(DecodedTextType || (exports.DecodedTextType = DecodedTextType = {}));
function isValidHtml5QrcodeSupportedFormats(format) {
return Object.values(Html5QrcodeSupportedFormats).includes(format);
}
var Html5QrcodeScanType;
exports.Html5QrcodeScanType = Html5QrcodeScanType;
(function (Html5QrcodeScanType) {
Html5QrcodeScanType[Html5QrcodeScanType["SCAN_TYPE_CAMERA"] = 0] = "SCAN_TYPE_CAMERA";
Html5QrcodeScanType[Html5QrcodeScanType["SCAN_TYPE_FILE"] = 1] = "SCAN_TYPE_FILE";
})(Html5QrcodeScanType || (exports.Html5QrcodeScanType = Html5QrcodeScanType = {}));
var Html5QrcodeConstants = function () {
function Html5QrcodeConstants() {}
Html5QrcodeConstants.GITHUB_PROJECT_URL = "https://github.com/mebjas/html5-qrcode";
Html5QrcodeConstants.SCAN_DEFAULT_FPS = 2;
Html5QrcodeConstants.DEFAULT_DISABLE_FLIP = false;
Html5QrcodeConstants.DEFAULT_REMEMBER_LAST_CAMERA_USED = true;
Html5QrcodeConstants.DEFAULT_SUPPORTED_SCAN_TYPE = [Html5QrcodeScanType.SCAN_TYPE_CAMERA, Html5QrcodeScanType.SCAN_TYPE_FILE];
return Html5QrcodeConstants;
}();
exports.Html5QrcodeConstants = Html5QrcodeConstants;
var QrcodeResultFormat = function () {
function QrcodeResultFormat(format, formatName) {
this.format = format;
this.formatName = formatName;
}
QrcodeResultFormat.prototype.toString = function () {
return this.formatName;
};
QrcodeResultFormat.create = function (format) {
if (!html5QrcodeSupportedFormatsTextMap.has(format)) {
throw "".concat(format, " not in html5QrcodeSupportedFormatsTextMap");
}
return new QrcodeResultFormat(format, html5QrcodeSupportedFormatsTextMap.get(format));
};
return QrcodeResultFormat;
}();
exports.QrcodeResultFormat = QrcodeResultFormat;
var Html5QrcodeResultFactory = function () {
function Html5QrcodeResultFactory() {}
Html5QrcodeResultFactory.createFromText = function (decodedText) {
var qrcodeResult = {
text: decodedText
};
return {
decodedText: decodedText,
result: qrcodeResult
};
};
Html5QrcodeResultFactory.createFromQrcodeResult = function (qrcodeResult) {
return {
decodedText: qrcodeResult.text,
result: qrcodeResult
};
};
return Html5QrcodeResultFactory;
}();
exports.Html5QrcodeResultFactory = Html5QrcodeResultFactory;
var Html5QrcodeErrorTypes;
exports.Html5QrcodeErrorTypes = Html5QrcodeErrorTypes;
(function (Html5QrcodeErrorTypes) {
Html5QrcodeErrorTypes[Html5QrcodeErrorTypes["UNKWOWN_ERROR"] = 0] = "UNKWOWN_ERROR";
Html5QrcodeErrorTypes[Html5QrcodeErrorTypes["IMPLEMENTATION_ERROR"] = 1] = "IMPLEMENTATION_ERROR";
Html5QrcodeErrorTypes[Html5QrcodeErrorTypes["NO_CODE_FOUND_ERROR"] = 2] = "NO_CODE_FOUND_ERROR";
})(Html5QrcodeErrorTypes || (exports.Html5QrcodeErrorTypes = Html5QrcodeErrorTypes = {}));
var Html5QrcodeErrorFactory = function () {
function Html5QrcodeErrorFactory() {}
Html5QrcodeErrorFactory.createFrom = function (error) {
return {
errorMessage: error,
type: Html5QrcodeErrorTypes.UNKWOWN_ERROR
};
};
return Html5QrcodeErrorFactory;
}();
exports.Html5QrcodeErrorFactory = Html5QrcodeErrorFactory;
var BaseLoggger = function () {
function BaseLoggger(verbose) {
this.verbose = verbose;
}
BaseLoggger.prototype.log = function (message) {
if (this.verbose) {
console.log(message);
}
};
BaseLoggger.prototype.warn = function (message) {
if (this.verbose) {
console.warn(message);
}
};
BaseLoggger.prototype.logError = function (message, isExperimental) {
if (this.verbose || isExperimental === true) {
console.error(message);
}
};
BaseLoggger.prototype.logErrors = function (errors) {
if (errors.length === 0) {
throw "Logger#logError called without arguments";
}
if (this.verbose) {
console.error(errors);
}
};
return BaseLoggger;
}();
exports.BaseLoggger = BaseLoggger;
function isNullOrUndefined(obj) {
return typeof obj === "undefined" || obj === null;
}
function clip(value, minValue, maxValue) {
if (value > maxValue) {
return maxValue;
}
if (value < minValue) {
return minValue;
}
return value;
}
/***/ }),
/* 63 */
/*!***********************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/strings.js ***!
\***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LibraryInfoStrings = exports.Html5QrcodeStrings = exports.Html5QrcodeScannerStrings = void 0;
var Html5QrcodeStrings = function () {
function Html5QrcodeStrings() {}
Html5QrcodeStrings.codeParseError = function (exception) {
return "QR code parse error, error = ".concat(exception);
};
Html5QrcodeStrings.errorGettingUserMedia = function (error) {
return "Error getting userMedia, error = ".concat(error);
};
Html5QrcodeStrings.onlyDeviceSupportedError = function () {
return "The device doesn't support navigator.mediaDevices , only " + "supported cameraIdOrConfig in this case is deviceId parameter " + "(string).";
};
Html5QrcodeStrings.cameraStreamingNotSupported = function () {
return "Camera streaming not supported by the browser.";
};
Html5QrcodeStrings.unableToQuerySupportedDevices = function () {
return "Unable to query supported devices, unknown error.";
};
Html5QrcodeStrings.insecureContextCameraQueryError = function () {
return "Camera access is only supported in secure context like https " + "or localhost.";
};
Html5QrcodeStrings.scannerPaused = function () {
return "Scanner paused";
};
return Html5QrcodeStrings;
}();
exports.Html5QrcodeStrings = Html5QrcodeStrings;
var Html5QrcodeScannerStrings = function () {
function Html5QrcodeScannerStrings() {}
Html5QrcodeScannerStrings.scanningStatus = function () {
return "Scanning";
};
Html5QrcodeScannerStrings.idleStatus = function () {
return "Idle";
};
Html5QrcodeScannerStrings.errorStatus = function () {
return "Error";
};
Html5QrcodeScannerStrings.permissionStatus = function () {
return "Permission";
};
Html5QrcodeScannerStrings.noCameraFoundErrorStatus = function () {
return "No Cameras";
};
Html5QrcodeScannerStrings.lastMatch = function (decodedText) {
return "Last Match: ".concat(decodedText);
};
Html5QrcodeScannerStrings.codeScannerTitle = function () {
return "Code Scanner";
};
Html5QrcodeScannerStrings.cameraPermissionTitle = function () {
return "Request Camera Permissions";
};
Html5QrcodeScannerStrings.cameraPermissionRequesting = function () {
return "Requesting camera permissions...";
};
Html5QrcodeScannerStrings.noCameraFound = function () {
return "No camera found";
};
Html5QrcodeScannerStrings.scanButtonStopScanningText = function () {
return "Stop Scanning";
};
Html5QrcodeScannerStrings.scanButtonStartScanningText = function () {
return "Start Scanning";
};
Html5QrcodeScannerStrings.torchOnButton = function () {
return "Switch On Torch";
};
Html5QrcodeScannerStrings.torchOffButton = function () {
return "Switch Off Torch";
};
Html5QrcodeScannerStrings.torchOnFailedMessage = function () {
return "Failed to turn on torch";
};
Html5QrcodeScannerStrings.torchOffFailedMessage = function () {
return "Failed to turn off torch";
};
Html5QrcodeScannerStrings.scanButtonScanningStarting = function () {
return "Launching Camera...";
};
Html5QrcodeScannerStrings.textIfCameraScanSelected = function () {
return "Scan an Image File";
};
Html5QrcodeScannerStrings.textIfFileScanSelected = function () {
return "Scan using camera directly";
};
Html5QrcodeScannerStrings.selectCamera = function () {
return "Select Camera";
};
Html5QrcodeScannerStrings.fileSelectionChooseImage = function () {
return "Choose Image";
};
Html5QrcodeScannerStrings.fileSelectionChooseAnother = function () {
return "Choose Another";
};
Html5QrcodeScannerStrings.fileSelectionNoImageSelected = function () {
return "No image choosen";
};
Html5QrcodeScannerStrings.anonymousCameraPrefix = function () {
return "Anonymous Camera";
};
Html5QrcodeScannerStrings.dragAndDropMessage = function () {
return "Or drop an image to scan";
};
Html5QrcodeScannerStrings.dragAndDropMessageOnlyImages = function () {
return "Or drop an image to scan (other files not supported)";
};
Html5QrcodeScannerStrings.zoom = function () {
return "zoom";
};
Html5QrcodeScannerStrings.loadingImage = function () {
return "Loading image...";
};
Html5QrcodeScannerStrings.cameraScanAltText = function () {
return "Camera based scan";
};
Html5QrcodeScannerStrings.fileScanAltText = function () {
return "Fule based scan";
};
return Html5QrcodeScannerStrings;
}();
exports.Html5QrcodeScannerStrings = Html5QrcodeScannerStrings;
var LibraryInfoStrings = function () {
function LibraryInfoStrings() {}
LibraryInfoStrings.poweredBy = function () {
return "Powered by ";
};
LibraryInfoStrings.reportIssues = function () {
return "Report issues";
};
return LibraryInfoStrings;
}();
exports.LibraryInfoStrings = LibraryInfoStrings;
/***/ }),
/* 64 */
/*!*********************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/utils.js ***!
\*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ 4);
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.VideoConstraintsUtil = void 0;
var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ 13));
var VideoConstraintsUtil = function () {
function VideoConstraintsUtil() {}
VideoConstraintsUtil.isMediaStreamConstraintsValid = function (videoConstraints, logger) {
if ((0, _typeof2.default)(videoConstraints) !== "object") {
var typeofVideoConstraints = (0, _typeof2.default)(videoConstraints);
logger.logError("videoConstraints should be of type object, the " + "object passed is of type ".concat(typeofVideoConstraints, "."), true);
return false;
}
var bannedKeys = ["autoGainControl", "channelCount", "echoCancellation", "latency", "noiseSuppression", "sampleRate", "sampleSize", "volume"];
var bannedkeysSet = new Set(bannedKeys);
var keysInVideoConstraints = Object.keys(videoConstraints);
for (var _i = 0, keysInVideoConstraints_1 = keysInVideoConstraints; _i < keysInVideoConstraints_1.length; _i++) {
var key = keysInVideoConstraints_1[_i];
if (bannedkeysSet.has(key)) {
logger.logError("".concat(key, " is not supported videoConstaints."), true);
return false;
}
}
return true;
};
return VideoConstraintsUtil;
}();
exports.VideoConstraintsUtil = VideoConstraintsUtil;
/***/ }),
/* 65 */
/*!****************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/code-decoder.js ***!
\****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Html5QrcodeShim = void 0;
var _zxingHtml5QrcodeDecoder = __webpack_require__(/*! ./zxing-html5-qrcode-decoder */ 66);
var _nativeBarCodeDetector = __webpack_require__(/*! ./native-bar-code-detector */ 76);
var __awaiter = void 0 && (void 0).__awaiter || function (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());
});
};
var __generator = void 0 && (void 0).__generator || function (thisArg, body) {
var _ = {
label: 0,
sent: function sent() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"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
};
}
};
var Html5QrcodeShim = function () {
function Html5QrcodeShim(requestedFormats, useBarCodeDetectorIfSupported, verbose, logger) {
this.EXECUTIONS_TO_REPORT_PERFORMANCE = 100;
this.executions = 0;
this.executionResults = [];
this.wasPrimaryDecoderUsedInLastDecode = false;
this.verbose = verbose;
if (useBarCodeDetectorIfSupported && _nativeBarCodeDetector.BarcodeDetectorDelegate.isSupported()) {
this.primaryDecoder = new _nativeBarCodeDetector.BarcodeDetectorDelegate(requestedFormats, verbose, logger);
this.secondaryDecoder = new _zxingHtml5QrcodeDecoder.ZXingHtml5QrcodeDecoder(requestedFormats, verbose, logger);
} else {
this.primaryDecoder = new _zxingHtml5QrcodeDecoder.ZXingHtml5QrcodeDecoder(requestedFormats, verbose, logger);
}
}
Html5QrcodeShim.prototype.decodeAsync = function (canvas) {
return __awaiter(this, void 0, void 0, function () {
var startTime;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
startTime = performance.now();
_a.label = 1;
case 1:
_a.trys.push([1,, 3, 4]);
return [4, this.getDecoder().decodeAsync(canvas)];
case 2:
return [2, _a.sent()];
case 3:
this.possiblyLogPerformance(startTime);
return [7];
case 4:
return [2];
}
});
});
};
Html5QrcodeShim.prototype.decodeRobustlyAsync = function (canvas) {
return __awaiter(this, void 0, void 0, function () {
var startTime, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
startTime = performance.now();
_a.label = 1;
case 1:
_a.trys.push([1, 3, 4, 5]);
return [4, this.primaryDecoder.decodeAsync(canvas)];
case 2:
return [2, _a.sent()];
case 3:
error_1 = _a.sent();
if (this.secondaryDecoder) {
return [2, this.secondaryDecoder.decodeAsync(canvas)];
}
throw error_1;
case 4:
this.possiblyLogPerformance(startTime);
return [7];
case 5:
return [2];
}
});
});
};
Html5QrcodeShim.prototype.getDecoder = function () {
if (!this.secondaryDecoder) {
return this.primaryDecoder;
}
if (this.wasPrimaryDecoderUsedInLastDecode === false) {
this.wasPrimaryDecoderUsedInLastDecode = true;
return this.primaryDecoder;
}
this.wasPrimaryDecoderUsedInLastDecode = false;
return this.secondaryDecoder;
};
Html5QrcodeShim.prototype.possiblyLogPerformance = function (startTime) {
if (!this.verbose) {
return;
}
var executionTime = performance.now() - startTime;
this.executionResults.push(executionTime);
this.executions++;
this.possiblyFlushPerformanceReport();
};
Html5QrcodeShim.prototype.possiblyFlushPerformanceReport = function () {
if (this.executions < this.EXECUTIONS_TO_REPORT_PERFORMANCE) {
return;
}
var sum = 0;
for (var _i = 0, _a = this.executionResults; _i < _a.length; _i++) {
var executionTime = _a[_i];
sum += executionTime;
}
var mean = sum / this.executionResults.length;
console.log("".concat(mean, " ms for ").concat(this.executionResults.length, " last runs."));
this.executions = 0;
this.executionResults = [];
};
return Html5QrcodeShim;
}();
exports.Html5QrcodeShim = Html5QrcodeShim;
/***/ }),
/* 66 */
/*!******************************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/zxing-html5-qrcode-decoder.js ***!
\******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ 13);
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ZXingHtml5QrcodeDecoder = void 0;
var ZXing = _interopRequireWildcard(__webpack_require__(/*! ../third_party/zxing-js.umd */ 67));
var _core = __webpack_require__(/*! ./core */ 62);
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var ZXingHtml5QrcodeDecoder = function () {
function ZXingHtml5QrcodeDecoder(requestedFormats, verbose, logger) {
this.formatMap = new Map([[_core.Html5QrcodeSupportedFormats.QR_CODE, ZXing.BarcodeFormat.QR_CODE], [_core.Html5QrcodeSupportedFormats.AZTEC, ZXing.BarcodeFormat.AZTEC], [_core.Html5QrcodeSupportedFormats.CODABAR, ZXing.BarcodeFormat.CODABAR], [_core.Html5QrcodeSupportedFormats.CODE_39, ZXing.BarcodeFormat.CODE_39], [_core.Html5QrcodeSupportedFormats.CODE_93, ZXing.BarcodeFormat.CODE_93], [_core.Html5QrcodeSupportedFormats.CODE_128, ZXing.BarcodeFormat.CODE_128], [_core.Html5QrcodeSupportedFormats.DATA_MATRIX, ZXing.BarcodeFormat.DATA_MATRIX], [_core.Html5QrcodeSupportedFormats.MAXICODE, ZXing.BarcodeFormat.MAXICODE], [_core.Html5QrcodeSupportedFormats.ITF, ZXing.BarcodeFormat.ITF], [_core.Html5QrcodeSupportedFormats.EAN_13, ZXing.BarcodeFormat.EAN_13], [_core.Html5QrcodeSupportedFormats.EAN_8, ZXing.BarcodeFormat.EAN_8], [_core.Html5QrcodeSupportedFormats.PDF_417, ZXing.BarcodeFormat.PDF_417], [_core.Html5QrcodeSupportedFormats.RSS_14, ZXing.BarcodeFormat.RSS_14], [_core.Html5QrcodeSupportedFormats.RSS_EXPANDED, ZXing.BarcodeFormat.RSS_EXPANDED], [_core.Html5QrcodeSupportedFormats.UPC_A, ZXing.BarcodeFormat.UPC_A], [_core.Html5QrcodeSupportedFormats.UPC_E, ZXing.BarcodeFormat.UPC_E], [_core.Html5QrcodeSupportedFormats.UPC_EAN_EXTENSION, ZXing.BarcodeFormat.UPC_EAN_EXTENSION]]);
this.reverseFormatMap = this.createReverseFormatMap();
if (!ZXing) {
throw "Use html5qrcode.min.js without edit, ZXing not found.";
}
this.verbose = verbose;
this.logger = logger;
var formats = this.createZXingFormats(requestedFormats);
var hints = new Map();
hints.set(ZXing.DecodeHintType.POSSIBLE_FORMATS, formats);
hints.set(ZXing.DecodeHintType.TRY_HARDER, false);
this.hints = hints;
}
ZXingHtml5QrcodeDecoder.prototype.decodeAsync = function (canvas) {
var _this = this;
return new Promise(function (resolve, reject) {
try {
resolve(_this.decode(canvas));
} catch (error) {
reject(error);
}
});
};
ZXingHtml5QrcodeDecoder.prototype.decode = function (canvas) {
var zxingDecoder = new ZXing.MultiFormatReader(this.verbose, this.hints);
var luminanceSource = new ZXing.HTMLCanvasElementLuminanceSource(canvas);
var binaryBitmap = new ZXing.BinaryBitmap(new ZXing.HybridBinarizer(luminanceSource));
var result = zxingDecoder.decode(binaryBitmap);
return {
text: result.text,
format: _core.QrcodeResultFormat.create(this.toHtml5QrcodeSupportedFormats(result.format)),
debugData: this.createDebugData()
};
};
ZXingHtml5QrcodeDecoder.prototype.createReverseFormatMap = function () {
var result = new Map();
this.formatMap.forEach(function (value, key, _) {
result.set(value, key);
});
return result;
};
ZXingHtml5QrcodeDecoder.prototype.toHtml5QrcodeSupportedFormats = function (zxingFormat) {
if (!this.reverseFormatMap.has(zxingFormat)) {
throw "reverseFormatMap doesn't have ".concat(zxingFormat);
}
return this.reverseFormatMap.get(zxingFormat);
};
ZXingHtml5QrcodeDecoder.prototype.createZXingFormats = function (requestedFormats) {
var zxingFormats = [];
for (var _i = 0, requestedFormats_1 = requestedFormats; _i < requestedFormats_1.length; _i++) {
var requestedFormat = requestedFormats_1[_i];
if (this.formatMap.has(requestedFormat)) {
zxingFormats.push(this.formatMap.get(requestedFormat));
} else {
this.logger.logError("".concat(requestedFormat, " is not supported by") + "ZXingHtml5QrcodeShim");
}
}
return zxingFormats;
};
ZXingHtml5QrcodeDecoder.prototype.createDebugData = function () {
return {
decoderName: "zxing-js"
};
};
return ZXingHtml5QrcodeDecoder;
}();
exports.ZXingHtml5QrcodeDecoder = ZXingHtml5QrcodeDecoder;
/***/ }),
/* 67 */
/*!************************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/third_party/zxing-js.umd.js ***!
\************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;var _slicedToArray=__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ 5);var _assertThisInitialized=__webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ 68);var _regeneratorRuntime=__webpack_require__(/*! @babel/runtime/regenerator */ 69);var _get=__webpack_require__(/*! @babel/runtime/helpers/get */ 71);var _classCallCheck=__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ 23);var _createClass=__webpack_require__(/*! @babel/runtime/helpers/createClass */ 24);var _inherits=__webpack_require__(/*! @babel/runtime/helpers/inherits */ 74);var _possibleConstructorReturn=__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ 75);var _getPrototypeOf=__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ 73);var _typeof=__webpack_require__(/*! @babel/runtime/helpers/typeof */ 13);function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol!=="undefined"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0;var F=function F(){};return{s:F,n:function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]};},e:function e(_e){throw _e;},f:F};}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var normalCompletion=true,didErr=false,err;return{s:function s(){it=it.call(o);},n:function n(){var step=it.next();normalCompletion=step.done;return step;},e:function e(_e2){didErr=true;err=_e2;},f:function f(){try{if(!normalCompletion&&it.return!=null)it.return();}finally{if(didErr)throw err;}}};}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i];}return arr2;}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget);}else{result=Super.apply(this,arguments);}return _possibleConstructorReturn(this,result);};}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));return true;}catch(e){return false;}}(function(global,factory){( false?undefined:_typeof(exports))==='object'&&typeof module!=='undefined'?factory(exports): true?!(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)):(undefined);})(this,function(exports){'use strict';function isNullOrUndefined(obj){return obj===null||obj===undefined;}/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /* global Reflect, Promise */var extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b;}||function(d,b){for(var p in b){if(b.hasOwnProperty(p))d[p]=b[p];}};function __extends(d,b){extendStatics(d,b);function __(){this.constructor=d;}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __());}function fixProto(target,prototype){var setPrototypeOf=Object.setPrototypeOf;setPrototypeOf?setPrototypeOf(target,prototype):target.__proto__=prototype;}function fixStack(target,fn){if(fn===void 0){fn=target.constructor;}var captureStackTrace=Error.captureStackTrace;captureStackTrace&&captureStackTrace(target,fn);}var CustomError=function(_super){__extends(CustomError,_super);function CustomError(message){var _newTarget=this.constructor;var _this=_super.call(this,message)||this;Object.defineProperty(_this,'name',{value:_newTarget.name,enumerable:false});fixProto(_this,_newTarget.prototype);fixStack(_this);return _this;}return CustomError;}(Error);/**
* Custom Error class of type Exception.
*/var Exception=/*#__PURE__*/function(_CustomError){_inherits(Exception,_CustomError);var _super2=_createSuper(Exception);/**
* Allows Exception to be constructed directly
* with some message and prototype definition.
*/function Exception(){var _this2;var message=arguments.length>0&&arguments[0]!==undefined?arguments[0]:undefined;_classCallCheck(this,Exception);_this2=_super2.call(this,message);_this2.message=message;return _this2;}_createClass(Exception,[{key:"getKind",value:function getKind(){var ex=this.constructor;return ex.kind;}}]);return Exception;}(CustomError);/**
* It's typed as string so it can be extended and overriden.
*/Exception.kind='Exception';/**
* Custom Error class of type Exception.
*/var ArgumentException=/*#__PURE__*/function(_Exception){_inherits(ArgumentException,_Exception);var _super3=_createSuper(ArgumentException);function ArgumentException(){_classCallCheck(this,ArgumentException);return _super3.apply(this,arguments);}return _createClass(ArgumentException);}(Exception);ArgumentException.kind='ArgumentException';/**
* Custom Error class of type Exception.
*/var IllegalArgumentException=/*#__PURE__*/function(_Exception2){_inherits(IllegalArgumentException,_Exception2);var _super4=_createSuper(IllegalArgumentException);function IllegalArgumentException(){_classCallCheck(this,IllegalArgumentException);return _super4.apply(this,arguments);}return _createClass(IllegalArgumentException);}(Exception);IllegalArgumentException.kind='IllegalArgumentException';/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/var BinaryBitmap=/*#__PURE__*/function(){function BinaryBitmap(binarizer){_classCallCheck(this,BinaryBitmap);this.binarizer=binarizer;if(binarizer===null){throw new IllegalArgumentException('Binarizer must be non-null.');}}/**
* @return The width of the bitmap.
*/_createClass(BinaryBitmap,[{key:"getWidth",value:function getWidth(){return this.binarizer.getWidth();}/**
* @return The height of the bitmap.
*/},{key:"getHeight",value:function getHeight(){return this.binarizer.getHeight();}/**
* Converts one row of luminance data to 1 bit data. May actually do the conversion, or return
* cached data. Callers should assume this method is expensive and call it as seldom as possible.
* This method is intended for decoding 1D barcodes and may choose to apply sharpening.
*
* @param y The row to fetch, which must be in [0, bitmap height)
* @param row An optional preallocated array. If null or too small, it will be ignored.
* If used, the Binarizer will call BitArray.clear(). Always use the returned object.
* @return The array of bits for this row (true means black).
* @throws NotFoundException if row can't be binarized
*/},{key:"getBlackRow",value:function getBlackRow(y/*int*/,row){return this.binarizer.getBlackRow(y,row);}/**
* Converts a 2D array of luminance data to 1 bit. As above, assume this method is expensive
* and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or
* may not apply sharpening. Therefore, a row from this matrix may not be identical to one
* fetched using getBlackRow(), so don't mix and match between them.
*
* @return The 2D array of bits for the image (true means black).
* @throws NotFoundException if image can't be binarized to make a matrix
*/},{key:"getBlackMatrix",value:function getBlackMatrix(){// The matrix is created on demand the first time it is requested, then cached. There are two
// reasons for this:
// 1. This work will never be done if the caller only installs 1D Reader objects, or if a
// 1D Reader finds a barcode before the 2D Readers run.
// 2. This work will only be done once even if the caller installs multiple 2D Readers.
if(this.matrix===null||this.matrix===undefined){this.matrix=this.binarizer.getBlackMatrix();}return this.matrix;}/**
* @return Whether this bitmap can be cropped.
*/},{key:"isCropSupported",value:function isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported();}/**
* Returns a new object with cropped image data. Implementations may keep a reference to the
* original data rather than a copy. Only callable if isCropSupported() is true.
*
* @param left The left coordinate, which must be in [0,getWidth())
* @param top The top coordinate, which must be in [0,getHeight())
* @param width The width of the rectangle to crop.
* @param height The height of the rectangle to crop.
* @return A cropped version of this object.
*/},{key:"crop",value:function crop(left/*int*/,top/*int*/,width/*int*/,height/*int*/){var newSource=this.binarizer.getLuminanceSource().crop(left,top,width,height);return new BinaryBitmap(this.binarizer.createBinarizer(newSource));}/**
* @return Whether this bitmap supports counter-clockwise rotation.
*/},{key:"isRotateSupported",value:function isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported();}/**
* Returns a new object with rotated image data by 90 degrees counterclockwise.
* Only callable if {@link #isRotateSupported()} is true.
*
* @return A rotated version of this object.
*/},{key:"rotateCounterClockwise",value:function rotateCounterClockwise(){var newSource=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new BinaryBitmap(this.binarizer.createBinarizer(newSource));}/**
* Returns a new object with rotated image data by 45 degrees counterclockwise.
* Only callable if {@link #isRotateSupported()} is true.
*
* @return A rotated version of this object.
*/},{key:"rotateCounterClockwise45",value:function rotateCounterClockwise45(){var newSource=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new BinaryBitmap(this.binarizer.createBinarizer(newSource));}/*@Override*/},{key:"toString",value:function toString(){try{return this.getBlackMatrix().toString();}catch(e/*: NotFoundException*/){return'';}}}]);return BinaryBitmap;}();/**
* Custom Error class of type Exception.
*/var ChecksumException=/*#__PURE__*/function(_Exception3){_inherits(ChecksumException,_Exception3);var _super5=_createSuper(ChecksumException);function ChecksumException(){_classCallCheck(this,ChecksumException);return _super5.apply(this,arguments);}_createClass(ChecksumException,null,[{key:"getChecksumInstance",value:function getChecksumInstance(){return new ChecksumException();}}]);return ChecksumException;}(Exception);ChecksumException.kind='ChecksumException';/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* This class hierarchy provides a set of methods to convert luminance data to 1 bit data.
* It allows the algorithm to vary polymorphically, for example allowing a very expensive
* thresholding technique for servers and a fast one for mobile. It also permits the implementation
* to vary, e.g. a JNI version for Android and a Java fallback version for other platforms.
*
* @author dswitkin@google.com (Daniel Switkin)
*/var Binarizer=/*#__PURE__*/function(){function Binarizer(source){_classCallCheck(this,Binarizer);this.source=source;}_createClass(Binarizer,[{key:"getLuminanceSource",value:function getLuminanceSource(){return this.source;}},{key:"getWidth",value:function getWidth(){return this.source.getWidth();}},{key:"getHeight",value:function getHeight(){return this.source.getHeight();}}]);return Binarizer;}();var System=/*#__PURE__*/function(){function System(){_classCallCheck(this,System);}_createClass(System,null,[{key:"arraycopy",value:// public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
/**
* Makes a copy of a array.
*/function arraycopy(src,srcPos,dest,destPos,length){// TODO: better use split or set?
while(length--){dest[destPos++]=src[srcPos++];}}/**
* Returns the current time in milliseconds.
*/},{key:"currentTimeMillis",value:function currentTimeMillis(){return Date.now();}}]);return System;}();/**
* Custom Error class of type Exception.
*/var IndexOutOfBoundsException=/*#__PURE__*/function(_Exception4){_inherits(IndexOutOfBoundsException,_Exception4);var _super6=_createSuper(IndexOutOfBoundsException);function IndexOutOfBoundsException(){_classCallCheck(this,IndexOutOfBoundsException);return _super6.apply(this,arguments);}return _createClass(IndexOutOfBoundsException);}(Exception);IndexOutOfBoundsException.kind='IndexOutOfBoundsException';/**
* Custom Error class of type Exception.
*/var ArrayIndexOutOfBoundsException=/*#__PURE__*/function(_IndexOutOfBoundsExce){_inherits(ArrayIndexOutOfBoundsException,_IndexOutOfBoundsExce);var _super7=_createSuper(ArrayIndexOutOfBoundsException);function ArrayIndexOutOfBoundsException(){var _this3;var index=arguments.length>0&&arguments[0]!==undefined?arguments[0]:undefined;var message=arguments.length>1&&arguments[1]!==undefined?arguments[1]:undefined;_classCallCheck(this,ArrayIndexOutOfBoundsException);_this3=_super7.call(this,message);_this3.index=index;_this3.message=message;return _this3;}return _createClass(ArrayIndexOutOfBoundsException);}(IndexOutOfBoundsException);ArrayIndexOutOfBoundsException.kind='ArrayIndexOutOfBoundsException';var Arrays=/*#__PURE__*/function(){function Arrays(){_classCallCheck(this,Arrays);}_createClass(Arrays,null,[{key:"fill",value:/**
* Assigns the specified int value to each element of the specified array
* of ints.
*
* @param a the array to be filled
* @param val the value to be stored in all elements of the array
*/function fill(a,val){for(var i=0,len=a.length;i<len;i++){a[i]=val;}}/**
* Assigns the specified int value to each element of the specified
* range of the specified array of ints. The range to be filled
* extends from index {@code fromIndex}, inclusive, to index
* {@code toIndex}, exclusive. (If {@code fromIndex==toIndex}, the
* range to be filled is empty.)
*
* @param a the array to be filled
* @param fromIndex the index of the first element (inclusive) to be
* filled with the specified value
* @param toIndex the index of the last element (exclusive) to be
* filled with the specified value
* @param val the value to be stored in all elements of the array
* @throws IllegalArgumentException if {@code fromIndex > toIndex}
* @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
* {@code toIndex > a.length}
*/},{key:"fillWithin",value:function fillWithin(a,fromIndex,toIndex,val){Arrays.rangeCheck(a.length,fromIndex,toIndex);for(var i=fromIndex;i<toIndex;i++){a[i]=val;}}/**
* Checks that {@code fromIndex} and {@code toIndex} are in
* the range and throws an exception if they aren't.
*/},{key:"rangeCheck",value:function rangeCheck(arrayLength,fromIndex,toIndex){if(fromIndex>toIndex){throw new IllegalArgumentException('fromIndex('+fromIndex+') > toIndex('+toIndex+')');}if(fromIndex<0){throw new ArrayIndexOutOfBoundsException(fromIndex);}if(toIndex>arrayLength){throw new ArrayIndexOutOfBoundsException(toIndex);}}},{key:"asList",value:function asList(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}return args;}},{key:"create",value:function create(rows,cols,value){var arr=Array.from({length:rows});return arr.map(function(x){return Array.from({length:cols}).fill(value);});}},{key:"createInt32Array",value:function createInt32Array(rows,cols,value){var arr=Array.from({length:rows});return arr.map(function(x){return Int32Array.from({length:cols}).fill(value);});}},{key:"equals",value:function equals(first,second){if(!first){return false;}if(!second){return false;}if(!first.length){return false;}if(!second.length){return false;}if(first.length!==second.length){return false;}for(var i=0,length=first.length;i<length;i++){if(first[i]!==second[i]){return false;}}return true;}},{key:"hashCode",value:function hashCode(a){if(a===null){return 0;}var result=1;var _iterator=_createForOfIteratorHelper(a),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var element=_step.value;result=31*result+element;}}catch(err){_iterator.e(err);}finally{_iterator.f();}return result;}},{key:"fillUint8Array",value:function fillUint8Array(a,value){for(var i=0;i!==a.length;i++){a[i]=value;}}},{key:"copyOf",value:function copyOf(original,newLength){return original.slice(0,newLength);}},{key:"copyOfUint8Array",value:function copyOfUint8Array(original,newLength){if(original.length<=newLength){var newArray=new Uint8Array(newLength);newArray.set(original);return newArray;}return original.slice(0,newLength);}},{key:"copyOfRange",value:function copyOfRange(original,from,to){var newLength=to-from;var copy=new Int32Array(newLength);System.arraycopy(original,from,copy,0,newLength);return copy;}/*
* Returns the index of of the element in a sorted array or (-n-1) where n is the insertion point
* for the new element.
* Parameters:
* ar - A sorted array
* el - An element to search for
* comparator - A comparator function. The function takes two arguments: (a, b) and returns:
* a negative number if a is less than b;
* 0 if a is equal to b;
* a positive number of a is greater than b.
* The array may contain duplicate elements. If there are more than one equal elements in the array,
* the returned value can be the index of any one of the equal elements.
*
* http://jsfiddle.net/aryzhov/pkfst550/
*/},{key:"binarySearch",value:function binarySearch(ar,el,comparator){if(undefined===comparator){comparator=Arrays.numberComparator;}var m=0;var n=ar.length-1;while(m<=n){var k=n+m>>1;var cmp=comparator(el,ar[k]);if(cmp>0){m=k+1;}else if(cmp<0){n=k-1;}else{return k;}}return-m-1;}},{key:"numberComparator",value:function numberComparator(a,b){return a-b;}}]);return Arrays;}();/**
* Ponyfill for Java's Integer class.
*/var Integer=/*#__PURE__*/function(){function Integer(){_classCallCheck(this,Integer);}_createClass(Integer,null,[{key:"numberOfTrailingZeros",value:function numberOfTrailingZeros(i){var y;if(i===0)return 32;var n=31;y=i<<16;if(y!==0){n-=16;i=y;}y=i<<8;if(y!==0){n-=8;i=y;}y=i<<4;if(y!==0){n-=4;i=y;}y=i<<2;if(y!==0){n-=2;i=y;}return n-(i<<1>>>31);}},{key:"numberOfLeadingZeros",value:function numberOfLeadingZeros(i){// HD, Figure 5-6
if(i===0){return 32;}var n=1;if(i>>>16===0){n+=16;i<<=16;}if(i>>>24===0){n+=8;i<<=8;}if(i>>>28===0){n+=4;i<<=4;}if(i>>>30===0){n+=2;i<<=2;}n-=i>>>31;return n;}},{key:"toHexString",value:function toHexString(i){return i.toString(16);}},{key:"toBinaryString",value:function toBinaryString(intNumber){return String(parseInt(String(intNumber),2));}// Returns the number of one-bits in the two's complement binary representation of the specified int value. This function is sometimes referred to as the population count.
// Returns:
// the number of one-bits in the two's complement binary representation of the specified int value.
},{key:"bitCount",value:function bitCount(i){// HD, Figure 5-2
i=i-(i>>>1&0x55555555);i=(i&0x33333333)+(i>>>2&0x33333333);i=i+(i>>>4)&0x0f0f0f0f;i=i+(i>>>8);i=i+(i>>>16);return i&0x3f;}},{key:"truncDivision",value:function truncDivision(dividend,divisor){return Math.trunc(dividend/divisor);}/**
* Converts A string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString. If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. All other strings are considered decimal.
*/},{key:"parseInt",value:function(_parseInt){function parseInt(_x){return _parseInt.apply(this,arguments);}parseInt.toString=function(){return _parseInt.toString();};return parseInt;}(function(num){var radix=arguments.length>1&&arguments[1]!==undefined?arguments[1]:undefined;return parseInt(num,radix);})}]);return Integer;}();Integer.MIN_VALUE_32_BITS=-2147483648;Integer.MAX_VALUE=Number.MAX_SAFE_INTEGER;/**
* <p>A simple, fast array of bits, represented compactly by an array of ints internally.</p>
*
* @author Sean Owen
*/var BitArray/*implements Cloneable*/=/*#__PURE__*/function(){// For testing only
function BitArray(size/*int*/,bits){_classCallCheck(this,BitArray);if(undefined===size){this.size=0;this.bits=new Int32Array(1);}else{this.size=size;if(undefined===bits||null===bits){this.bits=BitArray.makeArray(size);}else{this.bits=bits;}}}_createClass(BitArray,[{key:"getSize",value:function getSize(){return this.size;}},{key:"getSizeInBytes",value:function getSizeInBytes(){return Math.floor((this.size+7)/8);}},{key:"ensureCapacity",value:function ensureCapacity(size/*int*/){if(size>this.bits.length*32){var newBits=BitArray.makeArray(size);System.arraycopy(this.bits,0,newBits,0,this.bits.length);this.bits=newBits;}}/**
* @param i bit to get
* @return true iff bit i is set
*/},{key:"get",value:function get(i/*int*/){return(this.bits[Math.floor(i/32)]&1<<(i&0x1F))!==0;}/**
* Sets bit i.
*
* @param i bit to set
*/},{key:"set",value:function set(i/*int*/){this.bits[Math.floor(i/32)]|=1<<(i&0x1F);}/**
* Flips bit i.
*
* @param i bit to set
*/},{key:"flip",value:function flip(i/*int*/){this.bits[Math.floor(i/32)]^=1<<(i&0x1F);}/**
* @param from first bit to check
* @return index of first bit that is set, starting from the given index, or size if none are set
* at or beyond this given index
* @see #getNextUnset(int)
*/},{key:"getNextSet",value:function getNextSet(from/*int*/){var size=this.size;if(from>=size){return size;}var bits=this.bits;var bitsOffset=Math.floor(from/32);var currentBits=bits[bitsOffset];// mask off lesser bits first
currentBits&=~((1<<(from&0x1F))-1);var length=bits.length;while(currentBits===0){if(++bitsOffset===length){return size;}currentBits=bits[bitsOffset];}var result=bitsOffset*32+Integer.numberOfTrailingZeros(currentBits);return result>size?size:result;}/**
* @param from index to start looking for unset bit
* @return index of next unset bit, or {@code size} if none are unset until the end
* @see #getNextSet(int)
*/},{key:"getNextUnset",value:function getNextUnset(from/*int*/){var size=this.size;if(from>=size){return size;}var bits=this.bits;var bitsOffset=Math.floor(from/32);var currentBits=~bits[bitsOffset];// mask off lesser bits first
currentBits&=~((1<<(from&0x1F))-1);var length=bits.length;while(currentBits===0){if(++bitsOffset===length){return size;}currentBits=~bits[bitsOffset];}var result=bitsOffset*32+Integer.numberOfTrailingZeros(currentBits);return result>size?size:result;}/**
* Sets a block of 32 bits, starting at bit i.
*
* @param i first bit to set
* @param newBits the new value of the next 32 bits. Note again that the least-significant bit
* corresponds to bit i, the next-least-significant to i+1, and so on.
*/},{key:"setBulk",value:function setBulk(i/*int*/,newBits/*int*/){this.bits[Math.floor(i/32)]=newBits;}/**
* Sets a range of bits.
*
* @param start start of range, inclusive.
* @param end end of range, exclusive
*/},{key:"setRange",value:function setRange(start/*int*/,end/*int*/){if(end<start||start<0||end>this.size){throw new IllegalArgumentException();}if(end===start){return;}end--;// will be easier to treat this as the last actually set bit -- inclusive
var firstInt=Math.floor(start/32);var lastInt=Math.floor(end/32);var bits=this.bits;for(var i=firstInt;i<=lastInt;i++){var firstBit=i>firstInt?0:start&0x1F;var lastBit=i<lastInt?31:end&0x1F;// Ones from firstBit to lastBit, inclusive
var mask=(2<<lastBit)-(1<<firstBit);bits[i]|=mask;}}/**
* Clears all bits (sets to false).
*/},{key:"clear",value:function clear(){var max=this.bits.length;var bits=this.bits;for(var i=0;i<max;i++){bits[i]=0;}}/**
* Efficient method to check if a range of bits is set, or not set.
*
* @param start start of range, inclusive.
* @param end end of range, exclusive
* @param value if true, checks that bits in range are set, otherwise checks that they are not set
*
* @return true iff all bits are set or not set in range, according to value argument
* @throws IllegalArgumentException if end is less than start or the range is not contained in the array
*/},{key:"isRange",value:function isRange(start/*int*/,end/*int*/,value){if(end<start||start<0||end>this.size){throw new IllegalArgumentException();}if(end===start){return true;// empty range matches
}end--;// will be easier to treat this as the last actually set bit -- inclusive
var firstInt=Math.floor(start/32);var lastInt=Math.floor(end/32);var bits=this.bits;for(var i=firstInt;i<=lastInt;i++){var firstBit=i>firstInt?0:start&0x1F;var lastBit=i<lastInt?31:end&0x1F;// Ones from firstBit to lastBit, inclusive
var mask=(2<<lastBit)-(1<<firstBit)&0xFFFFFFFF;// TYPESCRIPTPORT: & 0xFFFFFFFF added to discard anything after 32 bits, as ES has 53 bits
// Return false if we're looking for 1s and the masked bits[i] isn't all 1s (is: that,
// equals the mask, or we're looking for 0s and the masked portion is not all 0s
if((bits[i]&mask)!==(value?mask:0)){return false;}}return true;}},{key:"appendBit",value:function appendBit(bit){this.ensureCapacity(this.size+1);if(bit){this.bits[Math.floor(this.size/32)]|=1<<(this.size&0x1F);}this.size++;}/**
* Appends the least-significant bits, from value, in order from most-significant to
* least-significant. For example, appending 6 bits from 0x000001E will append the bits
* 0, 1, 1, 1, 1, 0 in that order.
*
* @param value {@code int} containing bits to append
* @param numBits bits from value to append
*/},{key:"appendBits",value:function appendBits(value/*int*/,numBits/*int*/){if(numBits<0||numBits>32){throw new IllegalArgumentException('Num bits must be between 0 and 32');}this.ensureCapacity(this.size+numBits);// const appendBit = this.appendBit;
for(var numBitsLeft=numBits;numBitsLeft>0;numBitsLeft--){this.appendBit((value>>numBitsLeft-1&0x01)===1);}}},{key:"appendBitArray",value:function appendBitArray(other){var otherSize=other.size;this.ensureCapacity(this.size+otherSize);// const appendBit = this.appendBit;
for(var i=0;i<otherSize;i++){this.appendBit(other.get(i));}}},{key:"xor",value:function xor(other){if(this.size!==other.size){throw new IllegalArgumentException('Sizes don\'t match');}var bits=this.bits;for(var i=0,length=bits.length;i<length;i++){// The last int could be incomplete (i.e. not have 32 bits in
// it) but there is no problem since 0 XOR 0 == 0.
bits[i]^=other.bits[i];}}/**
*
* @param bitOffset first bit to start writing
* @param array array to write into. Bytes are written most-significant byte first. This is the opposite
* of the internal representation, which is exposed by {@link #getBitArray()}
* @param offset position in array to start writing
* @param numBytes how many bytes to write
*/},{key:"toBytes",value:function toBytes(bitOffset/*int*/,array,offset/*int*/,numBytes/*int*/){for(var i=0;i<numBytes;i++){var theByte=0;for(var j=0;j<8;j++){if(this.get(bitOffset)){theByte|=1<<7-j;}bitOffset++;}array[offset+i]=/*(byte)*/theByte;}}/**
* @return underlying array of ints. The first element holds the first 32 bits, and the least
* significant bit is bit 0.
*/},{key:"getBitArray",value:function getBitArray(){return this.bits;}/**
* Reverses all bits in the array.
*/},{key:"reverse",value:function reverse(){var newBits=new Int32Array(this.bits.length);// reverse all int's first
var len=Math.floor((this.size-1)/32);var oldBitsLen=len+1;var bits=this.bits;for(var i=0;i<oldBitsLen;i++){var x=bits[i];x=x>>1&0x55555555|(x&0x55555555)<<1;x=x>>2&0x33333333|(x&0x33333333)<<2;x=x>>4&0x0f0f0f0f|(x&0x0f0f0f0f)<<4;x=x>>8&0x00ff00ff|(x&0x00ff00ff)<<8;x=x>>16&0x0000ffff|(x&0x0000ffff)<<16;newBits[len-i]=/*(int)*/x;}// now correct the int's if the bit size isn't a multiple of 32
if(this.size!==oldBitsLen*32){var leftOffset=oldBitsLen*32-this.size;var currentInt=newBits[0]>>>leftOffset;for(var _i=1;_i<oldBitsLen;_i++){var nextInt=newBits[_i];currentInt|=nextInt<<32-leftOffset;newBits[_i-1]=currentInt;currentInt=nextInt>>>leftOffset;}newBits[oldBitsLen-1]=currentInt;}this.bits=newBits;}},{key:"equals",value:/*@Override*/function equals(o){if(!(o instanceof BitArray)){return false;}var other=o;return this.size===other.size&&Arrays.equals(this.bits,other.bits);}/*@Override*/},{key:"hashCode",value:function hashCode(){return 31*this.size+Arrays.hashCode(this.bits);}/*@Override*/},{key:"toString",value:function toString(){var result='';for(var i=0,size=this.size;i<size;i++){if((i&0x07)===0){result+=' ';}result+=this.get(i)?'X':'.';}return result;}/*@Override*/},{key:"clone",value:function clone(){return new BitArray(this.size,this.bits.slice());}}],[{key:"makeArray",value:function makeArray(size/*int*/){return new Int32Array(Math.floor((size+31)/32));}}]);return BitArray;}();/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*namespace com.google.zxing {*/ /**
* Encapsulates a type of hint that a caller may pass to a barcode reader to help it
* more quickly or accurately decode it. It is up to implementations to decide what,
* if anything, to do with the information that is supplied.
*
* @author Sean Owen
* @author dswitkin@google.com (Daniel Switkin)
* @see Reader#decode(BinaryBitmap,java.util.Map)
*/var DecodeHintType;(function(DecodeHintType){/**
* Unspecified, application-specific hint. Maps to an unspecified {@link Object}.
*/DecodeHintType[DecodeHintType["OTHER"]=0]="OTHER";/*(Object.class)*/ /**
* Image is a pure monochrome image of a barcode. Doesn't matter what it maps to;
* use {@link Boolean#TRUE}.
*/DecodeHintType[DecodeHintType["PURE_BARCODE"]=1]="PURE_BARCODE";/*(Void.class)*/ /**
* Image is known to be of one of a few possible formats.
* Maps to a {@link List} of {@link BarcodeFormat}s.
*/DecodeHintType[DecodeHintType["POSSIBLE_FORMATS"]=2]="POSSIBLE_FORMATS";/*(List.class)*/ /**
* Spend more time to try to find a barcode; optimize for accuracy, not speed.
* Doesn't matter what it maps to; use {@link Boolean#TRUE}.
*/DecodeHintType[DecodeHintType["TRY_HARDER"]=3]="TRY_HARDER";/*(Void.class)*/ /**
* Specifies what character encoding to use when decoding, where applicable (type String)
*/DecodeHintType[DecodeHintType["CHARACTER_SET"]=4]="CHARACTER_SET";/*(String.class)*/ /**
* Allowed lengths of encoded data -- reject anything else. Maps to an {@code Int32Array}.
*/DecodeHintType[DecodeHintType["ALLOWED_LENGTHS"]=5]="ALLOWED_LENGTHS";/*(Int32Array.class)*/ /**
* Assume Code 39 codes employ a check digit. Doesn't matter what it maps to;
* use {@link Boolean#TRUE}.
*/DecodeHintType[DecodeHintType["ASSUME_CODE_39_CHECK_DIGIT"]=6]="ASSUME_CODE_39_CHECK_DIGIT";/*(Void.class)*/ /**
* Assume the barcode is being processed as a GS1 barcode, and modify behavior as needed.
* For example this affects FNC1 handling for Code 128 (aka GS1-128). Doesn't matter what it maps to;
* use {@link Boolean#TRUE}.
*/DecodeHintType[DecodeHintType["ASSUME_GS1"]=7]="ASSUME_GS1";/*(Void.class)*/ /**
* If true, return the start and end digits in a Codabar barcode instead of stripping them. They
* are alpha, whereas the rest are numeric. By default, they are stripped, but this causes them
* to not be. Doesn't matter what it maps to; use {@link Boolean#TRUE}.
*/DecodeHintType[DecodeHintType["RETURN_CODABAR_START_END"]=8]="RETURN_CODABAR_START_END";/*(Void.class)*/ /**
* The caller needs to be notified via callback when a possible {@link ResultPoint}
* is found. Maps to a {@link ResultPointCallback}.
*/DecodeHintType[DecodeHintType["NEED_RESULT_POINT_CALLBACK"]=9]="NEED_RESULT_POINT_CALLBACK";/*(ResultPointCallback.class)*/ /**
* Allowed extension lengths for EAN or UPC barcodes. Other formats will ignore this.
* Maps to an {@code Int32Array} of the allowed extension lengths, for example [2], [5], or [2, 5].
* If it is optional to have an extension, do not set this hint. If this is set,
* and a UPC or EAN barcode is found but an extension is not, then no result will be returned
* at all.
*/DecodeHintType[DecodeHintType["ALLOWED_EAN_EXTENSIONS"]=10]="ALLOWED_EAN_EXTENSIONS";/*(Int32Array.class)*/ // End of enumeration values.
/**
* Data type the hint is expecting.
* Among the possible values the {@link Void} stands out as being used for
* hints that do not expect a value to be supplied (flag hints). Such hints
* will possibly have their value ignored, or replaced by a
* {@link Boolean#TRUE}. Hint suppliers should probably use
* {@link Boolean#TRUE} as directed by the actual hint documentation.
*/ // private valueType: Class<?>
// DecodeHintType(valueType: Class<?>) {
// this.valueType = valueType
// }
// public getValueType(): Class<?> {
// return valueType
// }
})(DecodeHintType||(DecodeHintType={}));var DecodeHintType$1=DecodeHintType;/**
* Custom Error class of type Exception.
*/var FormatException=/*#__PURE__*/function(_Exception5){_inherits(FormatException,_Exception5);var _super8=_createSuper(FormatException);function FormatException(){_classCallCheck(this,FormatException);return _super8.apply(this,arguments);}_createClass(FormatException,null,[{key:"getFormatInstance",value:function getFormatInstance(){return new FormatException();}}]);return FormatException;}(Exception);FormatException.kind='FormatException';/*import java.util.HashMap;*/ /*import java.util.Map;*/var CharacterSetValueIdentifiers;(function(CharacterSetValueIdentifiers){CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp437"]=0]="Cp437";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_1"]=1]="ISO8859_1";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_2"]=2]="ISO8859_2";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_3"]=3]="ISO8859_3";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_4"]=4]="ISO8859_4";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_5"]=5]="ISO8859_5";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_6"]=6]="ISO8859_6";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_7"]=7]="ISO8859_7";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_8"]=8]="ISO8859_8";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_9"]=9]="ISO8859_9";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_10"]=10]="ISO8859_10";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_11"]=11]="ISO8859_11";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_13"]=12]="ISO8859_13";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_14"]=13]="ISO8859_14";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_15"]=14]="ISO8859_15";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_16"]=15]="ISO8859_16";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["SJIS"]=16]="SJIS";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp1250"]=17]="Cp1250";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp1251"]=18]="Cp1251";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp1252"]=19]="Cp1252";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp1256"]=20]="Cp1256";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["UnicodeBigUnmarked"]=21]="UnicodeBigUnmarked";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["UTF8"]=22]="UTF8";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ASCII"]=23]="ASCII";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Big5"]=24]="Big5";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["GB18030"]=25]="GB18030";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["EUC_KR"]=26]="EUC_KR";})(CharacterSetValueIdentifiers||(CharacterSetValueIdentifiers={}));/**
* Encapsulates a Character Set ECI, according to "Extended Channel Interpretations" 5.3.1.1
* of ISO 18004.
*
* @author Sean Owen
*/var CharacterSetECI=/*#__PURE__*/function(){function CharacterSetECI(valueIdentifier,valuesParam,name){_classCallCheck(this,CharacterSetECI);this.valueIdentifier=valueIdentifier;this.name=name;if(typeof valuesParam==='number'){this.values=Int32Array.from([valuesParam]);}else{this.values=valuesParam;}for(var _len2=arguments.length,otherEncodingNames=new Array(_len2>3?_len2-3:0),_key2=3;_key2<_len2;_key2++){otherEncodingNames[_key2-3]=arguments[_key2];}this.otherEncodingNames=otherEncodingNames;CharacterSetECI.VALUE_IDENTIFIER_TO_ECI.set(valueIdentifier,this);CharacterSetECI.NAME_TO_ECI.set(name,this);var values=this.values;for(var i=0,length=values.length;i!==length;i++){var v=values[i];CharacterSetECI.VALUES_TO_ECI.set(v,this);}for(var _i2=0,_otherEncodingNames=otherEncodingNames;_i2<_otherEncodingNames.length;_i2++){var otherName=_otherEncodingNames[_i2];CharacterSetECI.NAME_TO_ECI.set(otherName,this);}}// CharacterSetECI(value: number /*int*/) {
// this(new Int32Array {value})
// }
// CharacterSetECI(value: number /*int*/, String... otherEncodingNames) {
// this.values = new Int32Array {value}
// this.otherEncodingNames = otherEncodingNames
// }
// CharacterSetECI(values: Int32Array, String... otherEncodingNames) {
// this.values = values
// this.otherEncodingNames = otherEncodingNames
// }
_createClass(CharacterSetECI,[{key:"getValueIdentifier",value:function getValueIdentifier(){return this.valueIdentifier;}},{key:"getName",value:function getName(){return this.name;}},{key:"getValue",value:function getValue(){return this.values[0];}/**
* @param value character set ECI value
* @return {@code CharacterSetECI} representing ECI of given value, or null if it is legal but
* unsupported
* @throws FormatException if ECI value is invalid
*/},{key:"equals",value:function equals(o){if(!(o instanceof CharacterSetECI)){return false;}var other=o;return this.getName()===other.getName();}}],[{key:"getCharacterSetECIByValue",value:function getCharacterSetECIByValue(value/*int*/){if(value<0||value>=900){throw new FormatException('incorect value');}var characterSet=CharacterSetECI.VALUES_TO_ECI.get(value);if(undefined===characterSet){throw new FormatException('incorect value');}return characterSet;}/**
* @param name character set ECI encoding name
* @return CharacterSetECI representing ECI for character encoding, or null if it is legal
* but unsupported
*/},{key:"getCharacterSetECIByName",value:function getCharacterSetECIByName(name){var characterSet=CharacterSetECI.NAME_TO_ECI.get(name);if(undefined===characterSet){throw new FormatException('incorect value');}return characterSet;}}]);return CharacterSetECI;}();CharacterSetECI.VALUE_IDENTIFIER_TO_ECI=new Map();CharacterSetECI.VALUES_TO_ECI=new Map();CharacterSetECI.NAME_TO_ECI=new Map();// Enum name is a Java encoding valid for java.lang and java.io
// TYPESCRIPTPORT: changed the main label for ISO as the TextEncoder did not recognized them in the form from java
// (eg ISO8859_1 must be ISO88591 or ISO8859-1 or ISO-8859-1)
// later on: well, except 16 wich does not work with ISO885916 so used ISO-8859-1 form for default
CharacterSetECI.Cp437=new CharacterSetECI(CharacterSetValueIdentifiers.Cp437,Int32Array.from([0,2]),'Cp437');CharacterSetECI.ISO8859_1=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_1,Int32Array.from([1,3]),'ISO-8859-1','ISO88591','ISO8859_1');CharacterSetECI.ISO8859_2=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_2,4,'ISO-8859-2','ISO88592','ISO8859_2');CharacterSetECI.ISO8859_3=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_3,5,'ISO-8859-3','ISO88593','ISO8859_3');CharacterSetECI.ISO8859_4=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_4,6,'ISO-8859-4','ISO88594','ISO8859_4');CharacterSetECI.ISO8859_5=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_5,7,'ISO-8859-5','ISO88595','ISO8859_5');CharacterSetECI.ISO8859_6=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_6,8,'ISO-8859-6','ISO88596','ISO8859_6');CharacterSetECI.ISO8859_7=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_7,9,'ISO-8859-7','ISO88597','ISO8859_7');CharacterSetECI.ISO8859_8=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_8,10,'ISO-8859-8','ISO88598','ISO8859_8');CharacterSetECI.ISO8859_9=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_9,11,'ISO-8859-9','ISO88599','ISO8859_9');CharacterSetECI.ISO8859_10=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_10,12,'ISO-8859-10','ISO885910','ISO8859_10');CharacterSetECI.ISO8859_11=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_11,13,'ISO-8859-11','ISO885911','ISO8859_11');CharacterSetECI.ISO8859_13=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_13,15,'ISO-8859-13','ISO885913','ISO8859_13');CharacterSetECI.ISO8859_14=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_14,16,'ISO-8859-14','ISO885914','ISO8859_14');CharacterSetECI.ISO8859_15=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_15,17,'ISO-8859-15','ISO885915','ISO8859_15');CharacterSetECI.ISO8859_16=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_16,18,'ISO-8859-16','ISO885916','ISO8859_16');CharacterSetECI.SJIS=new CharacterSetECI(CharacterSetValueIdentifiers.SJIS,20,'SJIS','Shift_JIS');CharacterSetECI.Cp1250=new CharacterSetECI(CharacterSetValueIdentifiers.Cp1250,21,'Cp1250','windows-1250');CharacterSetECI.Cp1251=new CharacterSetECI(CharacterSetValueIdentifiers.Cp1251,22,'Cp1251','windows-1251');CharacterSetECI.Cp1252=new CharacterSetECI(CharacterSetValueIdentifiers.Cp1252,23,'Cp1252','windows-1252');CharacterSetECI.Cp1256=new CharacterSetECI(CharacterSetValueIdentifiers.Cp1256,24,'Cp1256','windows-1256');CharacterSetECI.UnicodeBigUnmarked=new CharacterSetECI(CharacterSetValueIdentifiers.UnicodeBigUnmarked,25,'UnicodeBigUnmarked','UTF-16BE','UnicodeBig');CharacterSetECI.UTF8=new CharacterSetECI(CharacterSetValueIdentifiers.UTF8,26,'UTF8','UTF-8');CharacterSetECI.ASCII=new CharacterSetECI(CharacterSetValueIdentifiers.ASCII,Int32Array.from([27,170]),'ASCII','US-ASCII');CharacterSetECI.Big5=new CharacterSetECI(CharacterSetValueIdentifiers.Big5,28,'Big5');CharacterSetECI.GB18030=new CharacterSetECI(CharacterSetValueIdentifiers.GB18030,29,'GB18030','GB2312','EUC_CN','GBK');CharacterSetECI.EUC_KR=new CharacterSetECI(CharacterSetValueIdentifiers.EUC_KR,30,'EUC_KR','EUC-KR');/**
* Custom Error class of type Exception.
*/var UnsupportedOperationException=/*#__PURE__*/function(_Exception6){_inherits(UnsupportedOperationException,_Exception6);var _super9=_createSuper(UnsupportedOperationException);function UnsupportedOperationException(){_classCallCheck(this,UnsupportedOperationException);return _super9.apply(this,arguments);}return _createClass(UnsupportedOperationException);}(Exception);UnsupportedOperationException.kind='UnsupportedOperationException';/**
* Responsible for en/decoding strings.
*/var StringEncoding=/*#__PURE__*/function(){function StringEncoding(){_classCallCheck(this,StringEncoding);}_createClass(StringEncoding,null,[{key:"decode",value:/**
* Decodes some Uint8Array to a string format.
*/function decode(bytes,encoding){var encodingName=this.encodingName(encoding);if(this.customDecoder){return this.customDecoder(bytes,encodingName);}// Increases browser support.
if(typeof TextDecoder==='undefined'||this.shouldDecodeOnFallback(encodingName)){return this.decodeFallback(bytes,encodingName);}return new TextDecoder(encodingName).decode(bytes);}/**
* Checks if the decoding method should use the fallback for decoding
* once Node TextDecoder doesn't support all encoding formats.
*
* @param encodingName
*/},{key:"shouldDecodeOnFallback",value:function shouldDecodeOnFallback(encodingName){return!StringEncoding.isBrowser()&&encodingName==='ISO-8859-1';}/**
* Encodes some string into a Uint8Array.
*/},{key:"encode",value:function encode(s,encoding){var encodingName=this.encodingName(encoding);if(this.customEncoder){return this.customEncoder(s,encodingName);}// Increases browser support.
if(typeof TextEncoder==='undefined'){return this.encodeFallback(s);}// TextEncoder only encodes to UTF8 by default as specified by encoding.spec.whatwg.org
return new TextEncoder().encode(s);}},{key:"isBrowser",value:function isBrowser(){return typeof window!=='undefined'&&{}.toString.call(window)==='[object Window]';}/**
* Returns the string value from some encoding character set.
*/},{key:"encodingName",value:function encodingName(encoding){return typeof encoding==='string'?encoding:encoding.getName();}/**
* Returns character set from some encoding character set.
*/},{key:"encodingCharacterSet",value:function encodingCharacterSet(encoding){if(encoding instanceof CharacterSetECI){return encoding;}return CharacterSetECI.getCharacterSetECIByName(encoding);}/**
* Runs a fallback for the native decoding funcion.
*/},{key:"decodeFallback",value:function decodeFallback(bytes,encoding){var characterSet=this.encodingCharacterSet(encoding);if(StringEncoding.isDecodeFallbackSupported(characterSet)){var s='';for(var i=0,length=bytes.length;i<length;i++){var h=bytes[i].toString(16);if(h.length<2){h='0'+h;}s+='%'+h;}return decodeURIComponent(s);}if(characterSet.equals(CharacterSetECI.UnicodeBigUnmarked)){return String.fromCharCode.apply(null,new Uint16Array(bytes.buffer));}throw new UnsupportedOperationException("Encoding ".concat(this.encodingName(encoding)," not supported by fallback."));}},{key:"isDecodeFallbackSupported",value:function isDecodeFallbackSupported(characterSet){return characterSet.equals(CharacterSetECI.UTF8)||characterSet.equals(CharacterSetECI.ISO8859_1)||characterSet.equals(CharacterSetECI.ASCII);}/**
* Runs a fallback for the native encoding funcion.
*
* @see https://stackoverflow.com/a/17192845/4367683
*/},{key:"encodeFallback",value:function encodeFallback(s){var encodedURIstring=btoa(unescape(encodeURIComponent(s)));var charList=encodedURIstring.split('');var uintArray=[];for(var i=0;i<charList.length;i++){uintArray.push(charList[i].charCodeAt(0));}return new Uint8Array(uintArray);}}]);return StringEncoding;}();/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* Common string-related functions.
*
* @author Sean Owen
* @author Alex Dupre
*/var StringUtils=/*#__PURE__*/function(){function StringUtils(){_classCallCheck(this,StringUtils);}_createClass(StringUtils,null,[{key:"castAsNonUtf8Char",value:// SHIFT_JIS.equalsIgnoreCase(PLATFORM_DEFAULT_ENCODING) ||
// EUC_JP.equalsIgnoreCase(PLATFORM_DEFAULT_ENCODING);
function castAsNonUtf8Char(code){var encoding=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;// ISO 8859-1 is the Java default as UTF-8 is JavaScripts
// you can see this method as a Java version of String.fromCharCode
var e=encoding?encoding.getName():this.ISO88591;// use passed format (fromCharCode will return UTF8 encoding)
return StringEncoding.decode(new Uint8Array([code]),e);}/**
* @param bytes bytes encoding a string, whose encoding should be guessed
* @param hints decode hints if applicable
* @return name of guessed encoding; at the moment will only guess one of:
* {@link #SHIFT_JIS}, {@link #UTF8}, {@link #ISO88591}, or the platform
* default encoding if none of these can possibly be correct
*/},{key:"guessEncoding",value:function guessEncoding(bytes,hints){if(hints!==null&&hints!==undefined&&undefined!==hints.get(DecodeHintType$1.CHARACTER_SET)){return hints.get(DecodeHintType$1.CHARACTER_SET).toString();}// For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
// which should be by far the most common encodings.
var length=bytes.length;var canBeISO88591=true;var canBeShiftJIS=true;var canBeUTF8=true;var utf8BytesLeft=0;// int utf8LowChars = 0
var utf2BytesChars=0;var utf3BytesChars=0;var utf4BytesChars=0;var sjisBytesLeft=0;// int sjisLowChars = 0
var sjisKatakanaChars=0;// int sjisDoubleBytesChars = 0
var sjisCurKatakanaWordLength=0;var sjisCurDoubleBytesWordLength=0;var sjisMaxKatakanaWordLength=0;var sjisMaxDoubleBytesWordLength=0;// int isoLowChars = 0
// int isoHighChars = 0
var isoHighOther=0;var utf8bom=bytes.length>3&&bytes[0]===/*(byte) */0xEF&&bytes[1]===/*(byte) */0xBB&&bytes[2]===/*(byte) */0xBF;for(var i=0;i<length&&(canBeISO88591||canBeShiftJIS||canBeUTF8);i++){var value=bytes[i]&0xFF;// UTF-8 stuff
if(canBeUTF8){if(utf8BytesLeft>0){if((value&0x80)===0){canBeUTF8=false;}else{utf8BytesLeft--;}}else if((value&0x80)!==0){if((value&0x40)===0){canBeUTF8=false;}else{utf8BytesLeft++;if((value&0x20)===0){utf2BytesChars++;}else{utf8BytesLeft++;if((value&0x10)===0){utf3BytesChars++;}else{utf8BytesLeft++;if((value&0x08)===0){utf4BytesChars++;}else{canBeUTF8=false;}}}}}// else {
// utf8LowChars++
// }
}// ISO-8859-1 stuff
if(canBeISO88591){if(value>0x7F&&value<0xA0){canBeISO88591=false;}else if(value>0x9F){if(value<0xC0||value===0xD7||value===0xF7){isoHighOther++;}// else {
// isoHighChars++
// }
}// else {
// isoLowChars++
// }
}// Shift_JIS stuff
if(canBeShiftJIS){if(sjisBytesLeft>0){if(value<0x40||value===0x7F||value>0xFC){canBeShiftJIS=false;}else{sjisBytesLeft--;}}else if(value===0x80||value===0xA0||value>0xEF){canBeShiftJIS=false;}else if(value>0xA0&&value<0xE0){sjisKatakanaChars++;sjisCurDoubleBytesWordLength=0;sjisCurKatakanaWordLength++;if(sjisCurKatakanaWordLength>sjisMaxKatakanaWordLength){sjisMaxKatakanaWordLength=sjisCurKatakanaWordLength;}}else if(value>0x7F){sjisBytesLeft++;// sjisDoubleBytesChars++
sjisCurKatakanaWordLength=0;sjisCurDoubleBytesWordLength++;if(sjisCurDoubleBytesWordLength>sjisMaxDoubleBytesWordLength){sjisMaxDoubleBytesWordLength=sjisCurDoubleBytesWordLength;}}else{// sjisLowChars++
sjisCurKatakanaWordLength=0;sjisCurDoubleBytesWordLength=0;}}}if(canBeUTF8&&utf8BytesLeft>0){canBeUTF8=false;}if(canBeShiftJIS&&sjisBytesLeft>0){canBeShiftJIS=false;}// Easy -- if there is BOM or at least 1 valid not-single byte character (and no evidence it can't be UTF-8), done
if(canBeUTF8&&(utf8bom||utf2BytesChars+utf3BytesChars+utf4BytesChars>0)){return StringUtils.UTF8;}// Easy -- if assuming Shift_JIS or at least 3 valid consecutive not-ascii characters (and no evidence it can't be), done
if(canBeShiftJIS&&(StringUtils.ASSUME_SHIFT_JIS||sjisMaxKatakanaWordLength>=3||sjisMaxDoubleBytesWordLength>=3)){return StringUtils.SHIFT_JIS;}// Distinguishing Shift_JIS and ISO-8859-1 can be a little tough for short words. The crude heuristic is:
// - If we saw
// - only two consecutive katakana chars in the whole text, or
// - at least 10% of bytes that could be "upper" not-alphanumeric Latin1,
// - then we conclude Shift_JIS, else ISO-8859-1
if(canBeISO88591&&canBeShiftJIS){return sjisMaxKatakanaWordLength===2&&sjisKatakanaChars===2||isoHighOther*10>=length?StringUtils.SHIFT_JIS:StringUtils.ISO88591;}// Otherwise, try in order ISO-8859-1, Shift JIS, UTF-8 and fall back to default platform encoding
if(canBeISO88591){return StringUtils.ISO88591;}if(canBeShiftJIS){return StringUtils.SHIFT_JIS;}if(canBeUTF8){return StringUtils.UTF8;}// Otherwise, we take a wild guess with platform encoding
return StringUtils.PLATFORM_DEFAULT_ENCODING;}/**
*
* @see https://stackoverflow.com/a/13439711/4367683
*
* @param append The new string to append.
* @param args Argumets values to be formated.
*/},{key:"format",value:function format(append){for(var _len3=arguments.length,args=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++){args[_key3-1]=arguments[_key3];}var i=-1;function callback(exp,p0,p1,p2,p3,p4){if(exp==='%%')return'%';if(args[++i]===undefined)return undefined;exp=p2?parseInt(p2.substr(1)):undefined;var base=p3?parseInt(p3.substr(1)):undefined;var val;switch(p4){case's':val=args[i];break;case'c':val=args[i][0];break;case'f':val=parseFloat(args[i]).toFixed(exp);break;case'p':val=parseFloat(args[i]).toPrecision(exp);break;case'e':val=parseFloat(args[i]).toExponential(exp);break;case'x':val=parseInt(args[i]).toString(base?base:16);break;case'd':val=parseFloat(parseInt(args[i],base?base:10).toPrecision(exp)).toFixed(0);break;}val=_typeof(val)==='object'?JSON.stringify(val):(+val).toString(base);var size=parseInt(p1);/* padding size */var ch=p1&&p1[0]+''==='0'?'0':' ';/* isnull? */while(val.length<size){val=p0!==undefined?val+ch:ch+val;}/* isminus? */return val;}var regex=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return append.replace(regex,callback);}/**
*
*/},{key:"getBytes",value:function getBytes(str,encoding){return StringEncoding.encode(str,encoding);}/**
* Returns the charcode at the specified index or at index zero.
*/},{key:"getCharCode",value:function getCharCode(str){var index=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;return str.charCodeAt(index);}/**
* Returns char for given charcode
*/},{key:"getCharAt",value:function getCharAt(charCode){return String.fromCharCode(charCode);}}]);return StringUtils;}();StringUtils.SHIFT_JIS=CharacterSetECI.SJIS.getName();// "SJIS"
StringUtils.GB2312='GB2312';StringUtils.ISO88591=CharacterSetECI.ISO8859_1.getName();// "ISO8859_1"
StringUtils.EUC_JP='EUC_JP';StringUtils.UTF8=CharacterSetECI.UTF8.getName();// "UTF8"
StringUtils.PLATFORM_DEFAULT_ENCODING=StringUtils.UTF8;// "UTF8"//Charset.defaultCharset().name()
StringUtils.ASSUME_SHIFT_JIS=false;var StringBuilder=/*#__PURE__*/function(){function StringBuilder(){var value=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';_classCallCheck(this,StringBuilder);this.value=value;}_createClass(StringBuilder,[{key:"enableDecoding",value:function enableDecoding(encoding){this.encoding=encoding;return this;}},{key:"append",value:function append(s){if(typeof s==='string'){this.value+=s.toString();}else if(this.encoding){// use passed format (fromCharCode will return UTF8 encoding)
this.value+=StringUtils.castAsNonUtf8Char(s,this.encoding);}else{// correctly converts from UTF-8, but not other encodings
this.value+=String.fromCharCode(s);}return this;}},{key:"appendChars",value:function appendChars(str,offset,len){for(var i=offset;offset<offset+len;i++){this.append(str[i]);}return this;}},{key:"length",value:function length(){return this.value.length;}},{key:"charAt",value:function charAt(n){return this.value.charAt(n);}},{key:"deleteCharAt",value:function deleteCharAt(n){this.value=this.value.substr(0,n)+this.value.substring(n+1);}},{key:"setCharAt",value:function setCharAt(n,c){this.value=this.value.substr(0,n)+c+this.value.substr(n+1);}},{key:"substring",value:function substring(start,end){return this.value.substring(start,end);}/**
* @note helper method for RSS Expanded
*/},{key:"setLengthToZero",value:function setLengthToZero(){this.value='';}},{key:"toString",value:function toString(){return this.value;}},{key:"insert",value:function insert(n,c){this.value=this.value.substr(0,n)+c+this.value.substr(n+c.length);}}]);return StringBuilder;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Represents a 2D matrix of bits. In function arguments below, and throughout the common
* module, x is the column position, and y is the row position. The ordering is always x, y.
* The origin is at the top-left.</p>
*
* <p>Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins
* with a new int. This is done intentionally so that we can copy out a row into a BitArray very
* efficiently.</p>
*
* <p>The ordering of bits is row-major. Within each int, the least significant bits are used first,
* meaning they represent lower x values. This is compatible with BitArray's implementation.</p>
*
* @author Sean Owen
* @author dswitkin@google.com (Daniel Switkin)
*/var BitMatrix/*implements Cloneable*/=/*#__PURE__*/function(){/**
* Creates an empty square {@link BitMatrix}.
*
* @param dimension height and width
*/ // public constructor(dimension: number /*int*/) {
// this(dimension, dimension)
// }
/**
* Creates an empty {@link BitMatrix}.
*
* @param width bit matrix width
* @param height bit matrix height
*/ // public constructor(width: number /*int*/, height: number /*int*/) {
// if (width < 1 || height < 1) {
// throw new IllegalArgumentException("Both dimensions must be greater than 0")
// }
// this.width = width
// this.height = height
// this.rowSize = (width + 31) / 32
// bits = new int[rowSize * height];
// }
function BitMatrix(width/*int*/,height/*int*/,rowSize/*int*/,bits){_classCallCheck(this,BitMatrix);this.width=width;this.height=height;this.rowSize=rowSize;this.bits=bits;if(undefined===height||null===height){height=width;}this.height=height;if(width<1||height<1){throw new IllegalArgumentException('Both dimensions must be greater than 0');}if(undefined===rowSize||null===rowSize){rowSize=Math.floor((width+31)/32);}this.rowSize=rowSize;if(undefined===bits||null===bits){this.bits=new Int32Array(this.rowSize*this.height);}}/**
* Interprets a 2D array of booleans as a {@link BitMatrix}, where "true" means an "on" bit.
*
* @function parse
* @param image bits of the image, as a row-major 2D array. Elements are arrays representing rows
* @return {@link BitMatrix} representation of image
*/_createClass(BitMatrix,[{key:"get",value:/**
* <p>Gets the requested bit, where true means black.</p>
*
* @param x The horizontal component (i.e. which column)
* @param y The vertical component (i.e. which row)
* @return value of given bit in matrix
*/function get(x/*int*/,y/*int*/){var offset=y*this.rowSize+Math.floor(x/32);return(this.bits[offset]>>>(x&0x1f)&1)!==0;}/**
* <p>Sets the given bit to true.</p>
*
* @param x The horizontal component (i.e. which column)
* @param y The vertical component (i.e. which row)
*/},{key:"set",value:function set(x/*int*/,y/*int*/){var offset=y*this.rowSize+Math.floor(x/32);this.bits[offset]|=1<<(x&0x1f)&0xFFFFFFFF;}},{key:"unset",value:function unset(x/*int*/,y/*int*/){var offset=y*this.rowSize+Math.floor(x/32);this.bits[offset]&=~(1<<(x&0x1f)&0xFFFFFFFF);}/**
* <p>Flips the given bit.</p>
*
* @param x The horizontal component (i.e. which column)
* @param y The vertical component (i.e. which row)
*/},{key:"flip",value:function flip(x/*int*/,y/*int*/){var offset=y*this.rowSize+Math.floor(x/32);this.bits[offset]^=1<<(x&0x1f)&0xFFFFFFFF;}/**
* Exclusive-or (XOR): Flip the bit in this {@code BitMatrix} if the corresponding
* mask bit is set.
*
* @param mask XOR mask
*/},{key:"xor",value:function xor(mask){if(this.width!==mask.getWidth()||this.height!==mask.getHeight()||this.rowSize!==mask.getRowSize()){throw new IllegalArgumentException('input matrix dimensions do not match');}var rowArray=new BitArray(Math.floor(this.width/32)+1);var rowSize=this.rowSize;var bits=this.bits;for(var y=0,height=this.height;y<height;y++){var offset=y*rowSize;var row=mask.getRow(y,rowArray).getBitArray();for(var x=0;x<rowSize;x++){bits[offset+x]^=row[x];}}}/**
* Clears all bits (sets to false).
*/},{key:"clear",value:function clear(){var bits=this.bits;var max=bits.length;for(var i=0;i<max;i++){bits[i]=0;}}/**
* <p>Sets a square region of the bit matrix to true.</p>
*
* @param left The horizontal position to begin at (inclusive)
* @param top The vertical position to begin at (inclusive)
* @param width The width of the region
* @param height The height of the region
*/},{key:"setRegion",value:function setRegion(left/*int*/,top/*int*/,width/*int*/,height/*int*/){if(top<0||left<0){throw new IllegalArgumentException('Left and top must be nonnegative');}if(height<1||width<1){throw new IllegalArgumentException('Height and width must be at least 1');}var right=left+width;var bottom=top+height;if(bottom>this.height||right>this.width){throw new IllegalArgumentException('The region must fit inside the matrix');}var rowSize=this.rowSize;var bits=this.bits;for(var y=top;y<bottom;y++){var offset=y*rowSize;for(var x=left;x<right;x++){bits[offset+Math.floor(x/32)]|=1<<(x&0x1f)&0xFFFFFFFF;}}}/**
* A fast method to retrieve one row of data from the matrix as a BitArray.
*
* @param y The row to retrieve
* @param row An optional caller-allocated BitArray, will be allocated if null or too small
* @return The resulting BitArray - this reference should always be used even when passing
* your own row
*/},{key:"getRow",value:function getRow(y/*int*/,row){if(row===null||row===undefined||row.getSize()<this.width){row=new BitArray(this.width);}else{row.clear();}var rowSize=this.rowSize;var bits=this.bits;var offset=y*rowSize;for(var x=0;x<rowSize;x++){row.setBulk(x*32,bits[offset+x]);}return row;}/**
* @param y row to set
* @param row {@link BitArray} to copy from
*/},{key:"setRow",value:function setRow(y/*int*/,row){System.arraycopy(row.getBitArray(),0,this.bits,y*this.rowSize,this.rowSize);}/**
* Modifies this {@code BitMatrix} to represent the same but rotated 180 degrees
*/},{key:"rotate180",value:function rotate180(){var width=this.getWidth();var height=this.getHeight();var topRow=new BitArray(width);var bottomRow=new BitArray(width);for(var i=0,length=Math.floor((height+1)/2);i<length;i++){topRow=this.getRow(i,topRow);bottomRow=this.getRow(height-1-i,bottomRow);topRow.reverse();bottomRow.reverse();this.setRow(i,bottomRow);this.setRow(height-1-i,topRow);}}/**
* This is useful in detecting the enclosing rectangle of a 'pure' barcode.
*
* @return {@code left,top,width,height} enclosing rectangle of all 1 bits, or null if it is all white
*/},{key:"getEnclosingRectangle",value:function getEnclosingRectangle(){var width=this.width;var height=this.height;var rowSize=this.rowSize;var bits=this.bits;var left=width;var top=height;var right=-1;var bottom=-1;for(var y=0;y<height;y++){for(var x32=0;x32<rowSize;x32++){var theBits=bits[y*rowSize+x32];if(theBits!==0){if(y<top){top=y;}if(y>bottom){bottom=y;}if(x32*32<left){var bit=0;while((theBits<<31-bit&0xFFFFFFFF)===0){bit++;}if(x32*32+bit<left){left=x32*32+bit;}}if(x32*32+31>right){var _bit=31;while(theBits>>>_bit===0){_bit--;}if(x32*32+_bit>right){right=x32*32+_bit;}}}}}if(right<left||bottom<top){return null;}return Int32Array.from([left,top,right-left+1,bottom-top+1]);}/**
* This is useful in detecting a corner of a 'pure' barcode.
*
* @return {@code x,y} coordinate of top-left-most 1 bit, or null if it is all white
*/},{key:"getTopLeftOnBit",value:function getTopLeftOnBit(){var rowSize=this.rowSize;var bits=this.bits;var bitsOffset=0;while(bitsOffset<bits.length&&bits[bitsOffset]===0){bitsOffset++;}if(bitsOffset===bits.length){return null;}var y=bitsOffset/rowSize;var x=bitsOffset%rowSize*32;var theBits=bits[bitsOffset];var bit=0;while((theBits<<31-bit&0xFFFFFFFF)===0){bit++;}x+=bit;return Int32Array.from([x,y]);}},{key:"getBottomRightOnBit",value:function getBottomRightOnBit(){var rowSize=this.rowSize;var bits=this.bits;var bitsOffset=bits.length-1;while(bitsOffset>=0&&bits[bitsOffset]===0){bitsOffset--;}if(bitsOffset<0){return null;}var y=Math.floor(bitsOffset/rowSize);var x=Math.floor(bitsOffset%rowSize)*32;var theBits=bits[bitsOffset];var bit=31;while(theBits>>>bit===0){bit--;}x+=bit;return Int32Array.from([x,y]);}/**
* @return The width of the matrix
*/},{key:"getWidth",value:function getWidth(){return this.width;}/**
* @return The height of the matrix
*/},{key:"getHeight",value:function getHeight(){return this.height;}/**
* @return The row size of the matrix
*/},{key:"getRowSize",value:function getRowSize(){return this.rowSize;}/*@Override*/},{key:"equals",value:function equals(o){if(!(o instanceof BitMatrix)){return false;}var other=o;return this.width===other.width&&this.height===other.height&&this.rowSize===other.rowSize&&Arrays.equals(this.bits,other.bits);}/*@Override*/},{key:"hashCode",value:function hashCode(){var hash=this.width;hash=31*hash+this.width;hash=31*hash+this.height;hash=31*hash+this.rowSize;hash=31*hash+Arrays.hashCode(this.bits);return hash;}/**
* @return string representation using "X" for set and " " for unset bits
*/ /*@Override*/ // public toString(): string {
// return toString(": "X, " ")
// }
/**
* @param setString representation of a set bit
* @param unsetString representation of an unset bit
* @return string representation of entire matrix utilizing given strings
*/ // public toString(setString: string = "X ", unsetString: string = " "): string {
// return this.buildToString(setString, unsetString, "\n")
// }
/**
* @param setString representation of a set bit
* @param unsetString representation of an unset bit
* @param lineSeparator newline character in string representation
* @return string representation of entire matrix utilizing given strings and line separator
* @deprecated call {@link #toString(String,String)} only, which uses \n line separator always
*/ // @Deprecated
},{key:"toString",value:function toString(){var setString=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'X ';var unsetString=arguments.length>1&&arguments[1]!==undefined?arguments[1]:' ';var lineSeparator=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'\n';return this.buildToString(setString,unsetString,lineSeparator);}},{key:"buildToString",value:function buildToString(setString,unsetString,lineSeparator){var result=new StringBuilder();// result.append(lineSeparator);
for(var y=0,height=this.height;y<height;y++){for(var x=0,width=this.width;x<width;x++){result.append(this.get(x,y)?setString:unsetString);}result.append(lineSeparator);}return result.toString();}/*@Override*/},{key:"clone",value:function clone(){return new BitMatrix(this.width,this.height,this.rowSize,this.bits.slice());}}],[{key:"parseFromBooleanArray",value:function parseFromBooleanArray(image){var height=image.length;var width=image[0].length;var bits=new BitMatrix(width,height);for(var i=0;i<height;i++){var imageI=image[i];for(var j=0;j<width;j++){if(imageI[j]){bits.set(j,i);}}}return bits;}/**
*
* @function parse
* @param stringRepresentation
* @param setString
* @param unsetString
*/},{key:"parseFromString",value:function parseFromString(stringRepresentation,setString,unsetString){if(stringRepresentation===null){throw new IllegalArgumentException('stringRepresentation cannot be null');}var bits=new Array(stringRepresentation.length);var bitsPos=0;var rowStartPos=0;var rowLength=-1;var nRows=0;var pos=0;while(pos<stringRepresentation.length){if(stringRepresentation.charAt(pos)==='\n'||stringRepresentation.charAt(pos)==='\r'){if(bitsPos>rowStartPos){if(rowLength===-1){rowLength=bitsPos-rowStartPos;}else if(bitsPos-rowStartPos!==rowLength){throw new IllegalArgumentException('row lengths do not match');}rowStartPos=bitsPos;nRows++;}pos++;}else if(stringRepresentation.substring(pos,pos+setString.length)===setString){pos+=setString.length;bits[bitsPos]=true;bitsPos++;}else if(stringRepresentation.substring(pos,pos+unsetString.length)===unsetString){pos+=unsetString.length;bits[bitsPos]=false;bitsPos++;}else{throw new IllegalArgumentException('illegal character encountered: '+stringRepresentation.substring(pos));}}// no EOL at end?
if(bitsPos>rowStartPos){if(rowLength===-1){rowLength=bitsPos-rowStartPos;}else if(bitsPos-rowStartPos!==rowLength){throw new IllegalArgumentException('row lengths do not match');}nRows++;}var matrix=new BitMatrix(rowLength,nRows);for(var i=0;i<bitsPos;i++){if(bits[i]){matrix.set(Math.floor(i%rowLength),Math.floor(i/rowLength));}}return matrix;}}]);return BitMatrix;}();/**
* Custom Error class of type Exception.
*/var NotFoundException=/*#__PURE__*/function(_Exception7){_inherits(NotFoundException,_Exception7);var _super10=_createSuper(NotFoundException);function NotFoundException(){_classCallCheck(this,NotFoundException);return _super10.apply(this,arguments);}_createClass(NotFoundException,null,[{key:"getNotFoundInstance",value:function getNotFoundInstance(){return new NotFoundException();}}]);return NotFoundException;}(Exception);NotFoundException.kind='NotFoundException';/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* This Binarizer implementation uses the old ZXing global histogram approach. It is suitable
* for low-end mobile devices which don't have enough CPU or memory to use a local thresholding
* algorithm. However, because it picks a global black point, it cannot handle difficult shadows
* and gradients.
*
* Faster mobile devices and all desktop applications should probably use HybridBinarizer instead.
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
*/var GlobalHistogramBinarizer=/*#__PURE__*/function(_Binarizer){_inherits(GlobalHistogramBinarizer,_Binarizer);var _super11=_createSuper(GlobalHistogramBinarizer);function GlobalHistogramBinarizer(source){var _this4;_classCallCheck(this,GlobalHistogramBinarizer);_this4=_super11.call(this,source);_this4.luminances=GlobalHistogramBinarizer.EMPTY;_this4.buckets=new Int32Array(GlobalHistogramBinarizer.LUMINANCE_BUCKETS);return _this4;}// Applies simple sharpening to the row data to improve performance of the 1D Readers.
/*@Override*/_createClass(GlobalHistogramBinarizer,[{key:"getBlackRow",value:function getBlackRow(y/*int*/,row){var source=this.getLuminanceSource();var width=source.getWidth();if(row===undefined||row===null||row.getSize()<width){row=new BitArray(width);}else{row.clear();}this.initArrays(width);var localLuminances=source.getRow(y,this.luminances);var localBuckets=this.buckets;for(var x=0;x<width;x++){localBuckets[(localLuminances[x]&0xff)>>GlobalHistogramBinarizer.LUMINANCE_SHIFT]++;}var blackPoint=GlobalHistogramBinarizer.estimateBlackPoint(localBuckets);if(width<3){// Special case for very small images
for(var _x2=0;_x2<width;_x2++){if((localLuminances[_x2]&0xff)<blackPoint){row.set(_x2);}}}else{var left=localLuminances[0]&0xff;var center=localLuminances[1]&0xff;for(var _x3=1;_x3<width-1;_x3++){var right=localLuminances[_x3+1]&0xff;// A simple -1 4 -1 box filter with a weight of 2.
if((center*4-left-right)/2<blackPoint){row.set(_x3);}left=center;center=right;}}return row;}// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
/*@Override*/},{key:"getBlackMatrix",value:function getBlackMatrix(){var source=this.getLuminanceSource();var width=source.getWidth();var height=source.getHeight();var matrix=new BitMatrix(width,height);// Quickly calculates the histogram by sampling four rows from the image. This proved to be
// more robust on the blackbox tests than sampling a diagonal as we used to do.
this.initArrays(width);var localBuckets=this.buckets;for(var y=1;y<5;y++){var row=Math.floor(height*y/5);var _localLuminances=source.getRow(row,this.luminances);var right=Math.floor(width*4/5);for(var x=Math.floor(width/5);x<right;x++){var pixel=_localLuminances[x]&0xff;localBuckets[pixel>>GlobalHistogramBinarizer.LUMINANCE_SHIFT]++;}}var blackPoint=GlobalHistogramBinarizer.estimateBlackPoint(localBuckets);// We delay reading the entire image luminance until the black point estimation succeeds.
// Although we end up reading four rows twice, it is consistent with our motto of
// "fail quickly" which is necessary for continuous scanning.
var localLuminances=source.getMatrix();for(var _y=0;_y<height;_y++){var offset=_y*width;for(var _x4=0;_x4<width;_x4++){var _pixel=localLuminances[offset+_x4]&0xff;if(_pixel<blackPoint){matrix.set(_x4,_y);}}}return matrix;}/*@Override*/},{key:"createBinarizer",value:function createBinarizer(source){return new GlobalHistogramBinarizer(source);}},{key:"initArrays",value:function initArrays(luminanceSize/*int*/){if(this.luminances.length<luminanceSize){this.luminances=new Uint8ClampedArray(luminanceSize);}var buckets=this.buckets;for(var x=0;x<GlobalHistogramBinarizer.LUMINANCE_BUCKETS;x++){buckets[x]=0;}}}],[{key:"estimateBlackPoint",value:function estimateBlackPoint(buckets){// Find the tallest peak in the histogram.
var numBuckets=buckets.length;var maxBucketCount=0;var firstPeak=0;var firstPeakSize=0;for(var x=0;x<numBuckets;x++){if(buckets[x]>firstPeakSize){firstPeak=x;firstPeakSize=buckets[x];}if(buckets[x]>maxBucketCount){maxBucketCount=buckets[x];}}// Find the second-tallest peak which is somewhat far from the tallest peak.
var secondPeak=0;var secondPeakScore=0;for(var _x5=0;_x5<numBuckets;_x5++){var distanceToBiggest=_x5-firstPeak;// Encourage more distant second peaks by multiplying by square of distance.
var score=buckets[_x5]*distanceToBiggest*distanceToBiggest;if(score>secondPeakScore){secondPeak=_x5;secondPeakScore=score;}}// Make sure firstPeak corresponds to the black peak.
if(firstPeak>secondPeak){var temp=firstPeak;firstPeak=secondPeak;secondPeak=temp;}// If there is too little contrast in the image to pick a meaningful black point, throw rather
// than waste time trying to decode the image, and risk false positives.
if(secondPeak-firstPeak<=numBuckets/16){throw new NotFoundException();}// Find a valley between them that is low and closer to the white peak.
var bestValley=secondPeak-1;var bestValleyScore=-1;for(var _x6=secondPeak-1;_x6>firstPeak;_x6--){var fromFirst=_x6-firstPeak;var _score=fromFirst*fromFirst*(secondPeak-_x6)*(maxBucketCount-buckets[_x6]);if(_score>bestValleyScore){bestValley=_x6;bestValleyScore=_score;}}return bestValley<<GlobalHistogramBinarizer.LUMINANCE_SHIFT;}}]);return GlobalHistogramBinarizer;}(Binarizer);GlobalHistogramBinarizer.LUMINANCE_BITS=5;GlobalHistogramBinarizer.LUMINANCE_SHIFT=8-GlobalHistogramBinarizer.LUMINANCE_BITS;GlobalHistogramBinarizer.LUMINANCE_BUCKETS=1<<GlobalHistogramBinarizer.LUMINANCE_BITS;GlobalHistogramBinarizer.EMPTY=Uint8ClampedArray.from([0]);/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* This class implements a local thresholding algorithm, which while slower than the
* GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for
* high frequency images of barcodes with black data on white backgrounds. For this application,
* it does a much better job than a global blackpoint with severe shadows and gradients.
* However it tends to produce artifacts on lower frequency images and is therefore not
* a good general purpose binarizer for uses outside ZXing.
*
* This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers,
* and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already
* inherently local, and only fails for horizontal gradients. We can revisit that problem later,
* but for now it was not a win to use local blocks for 1D.
*
* This Binarizer is the default for the unit tests and the recommended class for library users.
*
* @author dswitkin@google.com (Daniel Switkin)
*/var HybridBinarizer=/*#__PURE__*/function(_GlobalHistogramBinar){_inherits(HybridBinarizer,_GlobalHistogramBinar);var _super12=_createSuper(HybridBinarizer);function HybridBinarizer(source){var _this5;_classCallCheck(this,HybridBinarizer);_this5=_super12.call(this,source);_this5.matrix=null;return _this5;}/**
* Calculates the final BitMatrix once for all requests. This could be called once from the
* constructor instead, but there are some advantages to doing it lazily, such as making
* profiling easier, and not doing heavy lifting when callers don't expect it.
*/ /*@Override*/_createClass(HybridBinarizer,[{key:"getBlackMatrix",value:function getBlackMatrix(){if(this.matrix!==null){return this.matrix;}var source=this.getLuminanceSource();var width=source.getWidth();var height=source.getHeight();if(width>=HybridBinarizer.MINIMUM_DIMENSION&&height>=HybridBinarizer.MINIMUM_DIMENSION){var luminances=source.getMatrix();var subWidth=width>>HybridBinarizer.BLOCK_SIZE_POWER;if((width&HybridBinarizer.BLOCK_SIZE_MASK)!==0){subWidth++;}var subHeight=height>>HybridBinarizer.BLOCK_SIZE_POWER;if((height&HybridBinarizer.BLOCK_SIZE_MASK)!==0){subHeight++;}var blackPoints=HybridBinarizer.calculateBlackPoints(luminances,subWidth,subHeight,width,height);var newMatrix=new BitMatrix(width,height);HybridBinarizer.calculateThresholdForBlock(luminances,subWidth,subHeight,width,height,blackPoints,newMatrix);this.matrix=newMatrix;}else{// If the image is too small, fall back to the global histogram approach.
this.matrix=_get(_getPrototypeOf(HybridBinarizer.prototype),"getBlackMatrix",this).call(this);}return this.matrix;}/*@Override*/},{key:"createBinarizer",value:function createBinarizer(source){return new HybridBinarizer(source);}/**
* For each block in the image, calculate the average black point using a 5x5 grid
* of the blocks around it. Also handles the corner cases (fractional blocks are computed based
* on the last pixels in the row/column which are also used in the previous block).
*/}],[{key:"calculateThresholdForBlock",value:function calculateThresholdForBlock(luminances,subWidth/*int*/,subHeight/*int*/,width/*int*/,height/*int*/,blackPoints,matrix){var maxYOffset=height-HybridBinarizer.BLOCK_SIZE;var maxXOffset=width-HybridBinarizer.BLOCK_SIZE;for(var y=0;y<subHeight;y++){var yoffset=y<<HybridBinarizer.BLOCK_SIZE_POWER;if(yoffset>maxYOffset){yoffset=maxYOffset;}var top=HybridBinarizer.cap(y,2,subHeight-3);for(var x=0;x<subWidth;x++){var xoffset=x<<HybridBinarizer.BLOCK_SIZE_POWER;if(xoffset>maxXOffset){xoffset=maxXOffset;}var left=HybridBinarizer.cap(x,2,subWidth-3);var sum=0;for(var z=-2;z<=2;z++){var blackRow=blackPoints[top+z];sum+=blackRow[left-2]+blackRow[left-1]+blackRow[left]+blackRow[left+1]+blackRow[left+2];}var average=sum/25;HybridBinarizer.thresholdBlock(luminances,xoffset,yoffset,average,width,matrix);}}}},{key:"cap",value:function cap(value/*int*/,min/*int*/,max/*int*/){return value<min?min:value>max?max:value;}/**
* Applies a single threshold to a block of pixels.
*/},{key:"thresholdBlock",value:function thresholdBlock(luminances,xoffset/*int*/,yoffset/*int*/,threshold/*int*/,stride/*int*/,matrix){for(var y=0,offset=yoffset*stride+xoffset;y<HybridBinarizer.BLOCK_SIZE;y++,offset+=stride){for(var x=0;x<HybridBinarizer.BLOCK_SIZE;x++){// Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0.
if((luminances[offset+x]&0xFF)<=threshold){matrix.set(xoffset+x,yoffset+y);}}}}/**
* Calculates a single black point for each block of pixels and saves it away.
* See the following thread for a discussion of this algorithm:
* http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0
*/},{key:"calculateBlackPoints",value:function calculateBlackPoints(luminances,subWidth/*int*/,subHeight/*int*/,width/*int*/,height/*int*/){var maxYOffset=height-HybridBinarizer.BLOCK_SIZE;var maxXOffset=width-HybridBinarizer.BLOCK_SIZE;// tslint:disable-next-line:whitespace
var blackPoints=new Array(subHeight);// subWidth
for(var y=0;y<subHeight;y++){blackPoints[y]=new Int32Array(subWidth);var yoffset=y<<HybridBinarizer.BLOCK_SIZE_POWER;if(yoffset>maxYOffset){yoffset=maxYOffset;}for(var x=0;x<subWidth;x++){var xoffset=x<<HybridBinarizer.BLOCK_SIZE_POWER;if(xoffset>maxXOffset){xoffset=maxXOffset;}var sum=0;var min=0xFF;var max=0;for(var yy=0,offset=yoffset*width+xoffset;yy<HybridBinarizer.BLOCK_SIZE;yy++,offset+=width){for(var xx=0;xx<HybridBinarizer.BLOCK_SIZE;xx++){var pixel=luminances[offset+xx]&0xFF;sum+=pixel;// still looking for good contrast
if(pixel<min){min=pixel;}if(pixel>max){max=pixel;}}// short-circuit min/max tests once dynamic range is met
if(max-min>HybridBinarizer.MIN_DYNAMIC_RANGE){// finish the rest of the rows quickly
for(yy++,offset+=width;yy<HybridBinarizer.BLOCK_SIZE;yy++,offset+=width){for(var _xx=0;_xx<HybridBinarizer.BLOCK_SIZE;_xx++){sum+=luminances[offset+_xx]&0xFF;}}}}// The default estimate is the average of the values in the block.
var average=sum>>HybridBinarizer.BLOCK_SIZE_POWER*2;if(max-min<=HybridBinarizer.MIN_DYNAMIC_RANGE){// If variation within the block is low, assume this is a block with only light or only
// dark pixels. In that case we do not want to use the average, as it would divide this
// low contrast area into black and white pixels, essentially creating data out of noise.
//
// The default assumption is that the block is light/background. Since no estimate for
// the level of dark pixels exists locally, use half the min for the block.
average=min/2;if(y>0&&x>0){// Correct the "white background" assumption for blocks that have neighbors by comparing
// the pixels in this block to the previously calculated black points. This is based on
// the fact that dark barcode symbology is always surrounded by some amount of light
// background for which reasonable black point estimates were made. The bp estimated at
// the boundaries is used for the interior.
// The (min < bp) is arbitrary but works better than other heuristics that were tried.
var averageNeighborBlackPoint=(blackPoints[y-1][x]+2*blackPoints[y][x-1]+blackPoints[y-1][x-1])/4;if(min<averageNeighborBlackPoint){average=averageNeighborBlackPoint;}}}blackPoints[y][x]=average;}}return blackPoints;}}]);return HybridBinarizer;}(GlobalHistogramBinarizer);// This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels.
// So this is the smallest dimension in each axis we can accept.
HybridBinarizer.BLOCK_SIZE_POWER=3;HybridBinarizer.BLOCK_SIZE=1<<HybridBinarizer.BLOCK_SIZE_POWER;// ...0100...00
HybridBinarizer.BLOCK_SIZE_MASK=HybridBinarizer.BLOCK_SIZE-1;// ...0011...11
HybridBinarizer.MINIMUM_DIMENSION=HybridBinarizer.BLOCK_SIZE*5;HybridBinarizer.MIN_DYNAMIC_RANGE=24;/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*namespace com.google.zxing {*/ /**
* The purpose of this class hierarchy is to abstract different bitmap implementations across
* platforms into a standard interface for requesting greyscale luminance values. The interface
* only provides immutable methods; therefore crop and rotation create copies. This is to ensure
* that one Reader does not modify the original luminance source and leave it in an unknown state
* for other Readers in the chain.
*
* @author dswitkin@google.com (Daniel Switkin)
*/var LuminanceSource=/*#__PURE__*/function(){function LuminanceSource(width/*int*/,height/*int*/){_classCallCheck(this,LuminanceSource);this.width=width;this.height=height;}/**
* @return The width of the bitmap.
*/_createClass(LuminanceSource,[{key:"getWidth",value:function getWidth(){return this.width;}/**
* @return The height of the bitmap.
*/},{key:"getHeight",value:function getHeight(){return this.height;}/**
* @return Whether this subclass supports cropping.
*/},{key:"isCropSupported",value:function isCropSupported(){return false;}/**
* Returns a new object with cropped image data. Implementations may keep a reference to the
* original data rather than a copy. Only callable if isCropSupported() is true.
*
* @param left The left coordinate, which must be in [0,getWidth())
* @param top The top coordinate, which must be in [0,getHeight())
* @param width The width of the rectangle to crop.
* @param height The height of the rectangle to crop.
* @return A cropped version of this object.
*/},{key:"crop",value:function crop(left/*int*/,top/*int*/,width/*int*/,height/*int*/){throw new UnsupportedOperationException('This luminance source does not support cropping.');}/**
* @return Whether this subclass supports counter-clockwise rotation.
*/},{key:"isRotateSupported",value:function isRotateSupported(){return false;}/**
* Returns a new object with rotated image data by 90 degrees counterclockwise.
* Only callable if {@link #isRotateSupported()} is true.
*
* @return A rotated version of this object.
*/},{key:"rotateCounterClockwise",value:function rotateCounterClockwise(){throw new UnsupportedOperationException('This luminance source does not support rotation by 90 degrees.');}/**
* Returns a new object with rotated image data by 45 degrees counterclockwise.
* Only callable if {@link #isRotateSupported()} is true.
*
* @return A rotated version of this object.
*/},{key:"rotateCounterClockwise45",value:function rotateCounterClockwise45(){throw new UnsupportedOperationException('This luminance source does not support rotation by 45 degrees.');}/*@Override*/},{key:"toString",value:function toString(){var row=new Uint8ClampedArray(this.width);var result=new StringBuilder();for(var y=0;y<this.height;y++){var sourceRow=this.getRow(y,row);for(var x=0;x<this.width;x++){var luminance=sourceRow[x]&0xFF;var c=void 0;if(luminance<0x40){c='#';}else if(luminance<0x80){c='+';}else if(luminance<0xC0){c='.';}else{c=' ';}result.append(c);}result.append('\n');}return result.toString();}}]);return LuminanceSource;}();/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*namespace com.google.zxing {*/ /**
* A wrapper implementation of {@link LuminanceSource} which inverts the luminances it returns -- black becomes
* white and vice versa, and each value becomes (255-value).
*
* @author Sean Owen
*/var InvertedLuminanceSource=/*#__PURE__*/function(_LuminanceSource){_inherits(InvertedLuminanceSource,_LuminanceSource);var _super13=_createSuper(InvertedLuminanceSource);function InvertedLuminanceSource(delegate){var _this6;_classCallCheck(this,InvertedLuminanceSource);_this6=_super13.call(this,delegate.getWidth(),delegate.getHeight());_this6.delegate=delegate;return _this6;}/*@Override*/_createClass(InvertedLuminanceSource,[{key:"getRow",value:function getRow(y/*int*/,row){var sourceRow=this.delegate.getRow(y,row);var width=this.getWidth();for(var i=0;i<width;i++){sourceRow[i]=/*(byte)*/255-(sourceRow[i]&0xFF);}return sourceRow;}/*@Override*/},{key:"getMatrix",value:function getMatrix(){var matrix=this.delegate.getMatrix();var length=this.getWidth()*this.getHeight();var invertedMatrix=new Uint8ClampedArray(length);for(var i=0;i<length;i++){invertedMatrix[i]=/*(byte)*/255-(matrix[i]&0xFF);}return invertedMatrix;}/*@Override*/},{key:"isCropSupported",value:function isCropSupported(){return this.delegate.isCropSupported();}/*@Override*/},{key:"crop",value:function crop(left/*int*/,top/*int*/,width/*int*/,height/*int*/){return new InvertedLuminanceSource(this.delegate.crop(left,top,width,height));}/*@Override*/},{key:"isRotateSupported",value:function isRotateSupported(){return this.delegate.isRotateSupported();}/**
* @return original delegate {@link LuminanceSource} since invert undoes itself
*/ /*@Override*/},{key:"invert",value:function invert(){return this.delegate;}/*@Override*/},{key:"rotateCounterClockwise",value:function rotateCounterClockwise(){return new InvertedLuminanceSource(this.delegate.rotateCounterClockwise());}/*@Override*/},{key:"rotateCounterClockwise45",value:function rotateCounterClockwise45(){return new InvertedLuminanceSource(this.delegate.rotateCounterClockwise45());}}]);return InvertedLuminanceSource;}(LuminanceSource);/**
* @deprecated Moving to @zxing/browser
*/var HTMLCanvasElementLuminanceSource=/*#__PURE__*/function(_LuminanceSource2){_inherits(HTMLCanvasElementLuminanceSource,_LuminanceSource2);var _super14=_createSuper(HTMLCanvasElementLuminanceSource);function HTMLCanvasElementLuminanceSource(canvas){var _this7;_classCallCheck(this,HTMLCanvasElementLuminanceSource);_this7=_super14.call(this,canvas.width,canvas.height);_this7.canvas=canvas;_this7.tempCanvasElement=null;_this7.buffer=HTMLCanvasElementLuminanceSource.makeBufferFromCanvasImageData(canvas);return _this7;}_createClass(HTMLCanvasElementLuminanceSource,[{key:"getRow",value:function getRow(y/*int*/,row){if(y<0||y>=this.getHeight()){throw new IllegalArgumentException('Requested row is outside the image: '+y);}var width=this.getWidth();var start=y*width;if(row===null){row=this.buffer.slice(start,start+width);}else{if(row.length<width){row=new Uint8ClampedArray(width);}// The underlying raster of image consists of bytes with the luminance values
// TODO: can avoid set/slice?
row.set(this.buffer.slice(start,start+width));}return row;}},{key:"getMatrix",value:function getMatrix(){return this.buffer;}},{key:"isCropSupported",value:function isCropSupported(){return true;}},{key:"crop",value:function crop(left/*int*/,top/*int*/,width/*int*/,height/*int*/){_get(_getPrototypeOf(HTMLCanvasElementLuminanceSource.prototype),"crop",this).call(this,left,top,width,height);return this;}/**
* This is always true, since the image is a gray-scale image.
*
* @return true
*/},{key:"isRotateSupported",value:function isRotateSupported(){return true;}},{key:"rotateCounterClockwise",value:function rotateCounterClockwise(){this.rotate(-90);return this;}},{key:"rotateCounterClockwise45",value:function rotateCounterClockwise45(){this.rotate(-45);return this;}},{key:"getTempCanvasElement",value:function getTempCanvasElement(){if(null===this.tempCanvasElement){var tempCanvasElement=this.canvas.ownerDocument.createElement('canvas');tempCanvasElement.width=this.canvas.width;tempCanvasElement.height=this.canvas.height;this.tempCanvasElement=tempCanvasElement;}return this.tempCanvasElement;}},{key:"rotate",value:function rotate(angle){var tempCanvasElement=this.getTempCanvasElement();var tempContext=tempCanvasElement.getContext('2d');var angleRadians=angle*HTMLCanvasElementLuminanceSource.DEGREE_TO_RADIANS;// Calculate and set new dimensions for temp canvas
var width=this.canvas.width;var height=this.canvas.height;var newWidth=Math.ceil(Math.abs(Math.cos(angleRadians))*width+Math.abs(Math.sin(angleRadians))*height);var newHeight=Math.ceil(Math.abs(Math.sin(angleRadians))*width+Math.abs(Math.cos(angleRadians))*height);tempCanvasElement.width=newWidth;tempCanvasElement.height=newHeight;// Draw at center of temp canvas to prevent clipping of image data
tempContext.translate(newWidth/2,newHeight/2);tempContext.rotate(angleRadians);tempContext.drawImage(this.canvas,width/-2,height/-2);this.buffer=HTMLCanvasElementLuminanceSource.makeBufferFromCanvasImageData(tempCanvasElement);return this;}},{key:"invert",value:function invert(){return new InvertedLuminanceSource(this);}}],[{key:"makeBufferFromCanvasImageData",value:function makeBufferFromCanvasImageData(canvas){var imageData=canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height);return HTMLCanvasElementLuminanceSource.toGrayscaleBuffer(imageData.data,canvas.width,canvas.height);}},{key:"toGrayscaleBuffer",value:function toGrayscaleBuffer(imageBuffer,width,height){var grayscaleBuffer=new Uint8ClampedArray(width*height);for(var i=0,j=0,length=imageBuffer.length;i<length;i+=4,j++){var gray=void 0;var alpha=imageBuffer[i+3];// The color of fully-transparent pixels is irrelevant. They are often, technically, fully-transparent
// black (0 alpha, and then 0 RGB). They are often used, of course as the "white" area in a
// barcode image. Force any such pixel to be white:
if(alpha===0){gray=0xFF;}else{var pixelR=imageBuffer[i];var pixelG=imageBuffer[i+1];var pixelB=imageBuffer[i+2];// .299R + 0.587G + 0.114B (YUV/YIQ for PAL and NTSC),
// (306*R) >> 10 is approximately equal to R*0.299, and so on.
// 0x200 >> 10 is 0.5, it implements rounding.
gray=306*pixelR+601*pixelG+117*pixelB+0x200>>10;}grayscaleBuffer[j]=gray;}return grayscaleBuffer;}}]);return HTMLCanvasElementLuminanceSource;}(LuminanceSource);HTMLCanvasElementLuminanceSource.DEGREE_TO_RADIANS=Math.PI/180;/**
* @deprecated Moving to @zxing/browser
*
* Video input device metadata containing the id and label of the device if available.
*/var VideoInputDevice=/*#__PURE__*/function(){/**
* Creates an instance of VideoInputDevice.
*
* @param {string} deviceId the video input device id
* @param {string} label the label of the device if available
*/function VideoInputDevice(deviceId,label,groupId){_classCallCheck(this,VideoInputDevice);this.deviceId=deviceId;this.label=label;/** @inheritdoc */this.kind='videoinput';this.groupId=groupId||undefined;}/** @inheritdoc */_createClass(VideoInputDevice,[{key:"toJSON",value:function toJSON(){return{kind:this.kind,groupId:this.groupId,deviceId:this.deviceId,label:this.label};}}]);return VideoInputDevice;}();var __awaiter=(globalThis||global||self||window||undefined)&&(globalThis||global||self||window||undefined).__awaiter||function(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());});};/**
* @deprecated Moving to @zxing/browser
*
* Base class for browser code reader.
*/var BrowserCodeReader=/*#__PURE__*/function(){/**
* Creates an instance of BrowserCodeReader.
* @param {Reader} reader The reader instance to decode the barcode
* @param {number} [timeBetweenScansMillis=500] the time delay between subsequent successful decode tries
*
* @memberOf BrowserCodeReader
*/function BrowserCodeReader(reader){var timeBetweenScansMillis=arguments.length>1&&arguments[1]!==undefined?arguments[1]:500;var _hints=arguments.length>2?arguments[2]:undefined;_classCallCheck(this,BrowserCodeReader);this.reader=reader;this.timeBetweenScansMillis=timeBetweenScansMillis;this._hints=_hints;/**
* This will break the loop.
*/this._stopContinuousDecode=false;/**
* This will break the loop.
*/this._stopAsyncDecode=false;/**
* Delay time between decode attempts made by the scanner.
*/this._timeBetweenDecodingAttempts=0;}/**
* If navigator is present.
*/_createClass(BrowserCodeReader,[{key:"hasNavigator",get:function get(){return typeof navigator!=='undefined';}/**
* If mediaDevices under navigator is supported.
*/},{key:"isMediaDevicesSuported",get:function get(){return this.hasNavigator&&!!navigator.mediaDevices;}/**
* If enumerateDevices under navigator is supported.
*/},{key:"canEnumerateDevices",get:function get(){return!!(this.isMediaDevicesSuported&&navigator.mediaDevices.enumerateDevices);}/** Time between two decoding tries in milli seconds. */},{key:"timeBetweenDecodingAttempts",get:function get(){return this._timeBetweenDecodingAttempts;}/**
* Change the time span the decoder waits between two decoding tries.
*
* @param {number} millis Time between two decoding tries in milli seconds.
*/,set:function set(millis){this._timeBetweenDecodingAttempts=millis<0?0:millis;}/**
* Sets the hints.
*/},{key:"hints",get:/**
* Sets the hints.
*/function get(){return this._hints;}/**
* Lists all the available video input devices.
*/,set:function set(hints){this._hints=hints||null;}},{key:"listVideoInputDevices",value:function listVideoInputDevices(){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var devices,videoDevices,_iterator2,_step2,device,kind,deviceId,label,groupId,videoDevice;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:if(this.hasNavigator){_context.next=2;break;}throw new Error('Can\'t enumerate devices, navigator is not present.');case 2:if(this.canEnumerateDevices){_context.next=4;break;}throw new Error('Can\'t enumerate devices, method not supported.');case 4:_context.next=6;return navigator.mediaDevices.enumerateDevices();case 6:devices=_context.sent;videoDevices=[];_iterator2=_createForOfIteratorHelper(devices);_context.prev=9;_iterator2.s();case 11:if((_step2=_iterator2.n()).done){_context.next=23;break;}device=_step2.value;kind=device.kind==='video'?'videoinput':device.kind;if(!(kind!=='videoinput')){_context.next=16;break;}return _context.abrupt("continue",21);case 16:deviceId=device.deviceId||device.id;label=device.label||"Video device ".concat(videoDevices.length+1);groupId=device.groupId;videoDevice={deviceId:deviceId,label:label,kind:kind,groupId:groupId};videoDevices.push(videoDevice);case 21:_context.next=11;break;case 23:_context.next=28;break;case 25:_context.prev=25;_context.t0=_context["catch"](9);_iterator2.e(_context.t0);case 28:_context.prev=28;_iterator2.f();return _context.finish(28);case 31:return _context.abrupt("return",videoDevices);case 32:case"end":return _context.stop();}}},_callee,this,[[9,25,28,31]]);}));}/**
* Obtain the list of available devices with type 'videoinput'.
*
* @returns {Promise<VideoInputDevice[]>} an array of available video input devices
*
* @memberOf BrowserCodeReader
*
* @deprecated Use `listVideoInputDevices` instead.
*/},{key:"getVideoInputDevices",value:function getVideoInputDevices(){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var devices;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return this.listVideoInputDevices();case 2:devices=_context2.sent;return _context2.abrupt("return",devices.map(function(d){return new VideoInputDevice(d.deviceId,d.label);}));case 4:case"end":return _context2.stop();}}},_callee2,this);}));}/**
* Let's you find a device using it's Id.
*/},{key:"findDeviceById",value:function findDeviceById(deviceId){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var devices;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:_context3.next=2;return this.listVideoInputDevices();case 2:devices=_context3.sent;if(devices){_context3.next=5;break;}return _context3.abrupt("return",null);case 5:return _context3.abrupt("return",devices.find(function(x){return x.deviceId===deviceId;}));case 6:case"end":return _context3.stop();}}},_callee3,this);}));}/**
* Decodes the barcode from the device specified by deviceId while showing the video in the specified video element.
*
* @param deviceId the id of one of the devices obtained after calling getVideoInputDevices. Can be undefined, in this case it will decode from one of the available devices, preffering the main camera (environment facing) if available.
* @param video the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
* @returns The decoding result.
*
* @memberOf BrowserCodeReader
*
* @deprecated Use `decodeOnceFromVideoDevice` instead.
*/},{key:"decodeFromInputVideoDevice",value:function decodeFromInputVideoDevice(deviceId,videoSource){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:_context4.next=2;return this.decodeOnceFromVideoDevice(deviceId,videoSource);case 2:return _context4.abrupt("return",_context4.sent);case 3:case"end":return _context4.stop();}}},_callee4,this);}));}/**
* In one attempt, tries to decode the barcode from the device specified by deviceId while showing the video in the specified video element.
*
* @param deviceId the id of one of the devices obtained after calling getVideoInputDevices. Can be undefined, in this case it will decode from one of the available devices, preffering the main camera (environment facing) if available.
* @param video the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
* @returns The decoding result.
*
* @memberOf BrowserCodeReader
*/},{key:"decodeOnceFromVideoDevice",value:function decodeOnceFromVideoDevice(deviceId,videoSource){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){var videoConstraints,constraints;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:this.reset();if(!deviceId){videoConstraints={facingMode:'environment'};}else{videoConstraints={deviceId:{exact:deviceId}};}constraints={video:videoConstraints};_context5.next=5;return this.decodeOnceFromConstraints(constraints,videoSource);case 5:return _context5.abrupt("return",_context5.sent);case 6:case"end":return _context5.stop();}}},_callee5,this);}));}/**
* In one attempt, tries to decode the barcode from a stream obtained from the given constraints while showing the video in the specified video element.
*
* @param constraints the media stream constraints to get s valid media stream to decode from
* @param video the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
* @returns The decoding result.
*
* @memberOf BrowserCodeReader
*/},{key:"decodeOnceFromConstraints",value:function decodeOnceFromConstraints(constraints,videoSource){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(){var stream;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:_context6.next=2;return navigator.mediaDevices.getUserMedia(constraints);case 2:stream=_context6.sent;_context6.next=5;return this.decodeOnceFromStream(stream,videoSource);case 5:return _context6.abrupt("return",_context6.sent);case 6:case"end":return _context6.stop();}}},_callee6,this);}));}/**
* In one attempt, tries to decode the barcode from a stream obtained from the given constraints while showing the video in the specified video element.
*
* @param {MediaStream} [constraints] the media stream constraints to get s valid media stream to decode from
* @param {string|HTMLVideoElement} [video] the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
* @returns {Promise<Result>} The decoding result.
*
* @memberOf BrowserCodeReader
*/},{key:"decodeOnceFromStream",value:function decodeOnceFromStream(stream,videoSource){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(){var video,result;return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:this.reset();_context7.next=3;return this.attachStreamToVideo(stream,videoSource);case 3:video=_context7.sent;_context7.next=6;return this.decodeOnce(video);case 6:result=_context7.sent;return _context7.abrupt("return",result);case 8:case"end":return _context7.stop();}}},_callee7,this);}));}/**
* Continuously decodes the barcode from the device specified by device while showing the video in the specified video element.
*
* @param {string|null} [deviceId] the id of one of the devices obtained after calling getVideoInputDevices. Can be undefined, in this case it will decode from one of the available devices, preffering the main camera (environment facing) if available.
* @param {string|HTMLVideoElement|null} [video] the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
* @returns {Promise<void>}
*
* @memberOf BrowserCodeReader
*
* @deprecated Use `decodeFromVideoDevice` instead.
*/},{key:"decodeFromInputVideoDeviceContinuously",value:function decodeFromInputVideoDeviceContinuously(deviceId,videoSource,callbackFn){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(){return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:_context8.next=2;return this.decodeFromVideoDevice(deviceId,videoSource,callbackFn);case 2:return _context8.abrupt("return",_context8.sent);case 3:case"end":return _context8.stop();}}},_callee8,this);}));}/**
* Continuously tries to decode the barcode from the device specified by device while showing the video in the specified video element.
*
* @param {string|null} [deviceId] the id of one of the devices obtained after calling getVideoInputDevices. Can be undefined, in this case it will decode from one of the available devices, preffering the main camera (environment facing) if available.
* @param {string|HTMLVideoElement|null} [video] the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
* @returns {Promise<void>}
*
* @memberOf BrowserCodeReader
*/},{key:"decodeFromVideoDevice",value:function decodeFromVideoDevice(deviceId,videoSource,callbackFn){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee9(){var videoConstraints,constraints;return _regeneratorRuntime.wrap(function _callee9$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:if(!deviceId){videoConstraints={facingMode:'environment'};}else{videoConstraints={deviceId:{exact:deviceId}};}constraints={video:videoConstraints};_context9.next=4;return this.decodeFromConstraints(constraints,videoSource,callbackFn);case 4:return _context9.abrupt("return",_context9.sent);case 5:case"end":return _context9.stop();}}},_callee9,this);}));}/**
* Continuously tries to decode the barcode from a stream obtained from the given constraints while showing the video in the specified video element.
*
* @param {MediaStream} [constraints] the media stream constraints to get s valid media stream to decode from
* @param {string|HTMLVideoElement} [video] the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
* @returns {Promise<Result>} The decoding result.
*
* @memberOf BrowserCodeReader
*/},{key:"decodeFromConstraints",value:function decodeFromConstraints(constraints,videoSource,callbackFn){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee10(){var stream;return _regeneratorRuntime.wrap(function _callee10$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:_context10.next=2;return navigator.mediaDevices.getUserMedia(constraints);case 2:stream=_context10.sent;_context10.next=5;return this.decodeFromStream(stream,videoSource,callbackFn);case 5:return _context10.abrupt("return",_context10.sent);case 6:case"end":return _context10.stop();}}},_callee10,this);}));}/**
* In one attempt, tries to decode the barcode from a stream obtained from the given constraints while showing the video in the specified video element.
*
* @param {MediaStream} [constraints] the media stream constraints to get s valid media stream to decode from
* @param {string|HTMLVideoElement} [video] the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
* @returns {Promise<Result>} The decoding result.
*
* @memberOf BrowserCodeReader
*/},{key:"decodeFromStream",value:function decodeFromStream(stream,videoSource,callbackFn){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee11(){var video;return _regeneratorRuntime.wrap(function _callee11$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:this.reset();_context11.next=3;return this.attachStreamToVideo(stream,videoSource);case 3:video=_context11.sent;_context11.next=6;return this.decodeContinuously(video,callbackFn);case 6:return _context11.abrupt("return",_context11.sent);case 7:case"end":return _context11.stop();}}},_callee11,this);}));}/**
* Breaks the decoding loop.
*/},{key:"stopAsyncDecode",value:function stopAsyncDecode(){this._stopAsyncDecode=true;}/**
* Breaks the decoding loop.
*/},{key:"stopContinuousDecode",value:function stopContinuousDecode(){this._stopContinuousDecode=true;}/**
* Sets the new stream and request a new decoding-with-delay.
*
* @param stream The stream to be shown in the video element.
* @param decodeFn A callback for the decode method.
*/},{key:"attachStreamToVideo",value:function attachStreamToVideo(stream,videoSource){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee12(){var videoElement;return _regeneratorRuntime.wrap(function _callee12$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:videoElement=this.prepareVideoElement(videoSource);this.addVideoSource(videoElement,stream);this.videoElement=videoElement;this.stream=stream;_context12.next=6;return this.playVideoOnLoadAsync(videoElement);case 6:return _context12.abrupt("return",videoElement);case 7:case"end":return _context12.stop();}}},_callee12,this);}));}/**
*
* @param videoElement
*/},{key:"playVideoOnLoadAsync",value:function playVideoOnLoadAsync(videoElement){var _this8=this;return new Promise(function(resolve,reject){return _this8.playVideoOnLoad(videoElement,function(){return resolve();});});}/**
* Binds listeners and callbacks to the videoElement.
*
* @param element
* @param callbackFn
*/},{key:"playVideoOnLoad",value:function playVideoOnLoad(element,callbackFn){var _this9=this;this.videoEndedListener=function(){return _this9.stopStreams();};this.videoCanPlayListener=function(){return _this9.tryPlayVideo(element);};element.addEventListener('ended',this.videoEndedListener);element.addEventListener('canplay',this.videoCanPlayListener);element.addEventListener('playing',callbackFn);// if canplay was already fired, we won't know when to play, so just give it a try
this.tryPlayVideo(element);}/**
* Checks if the given video element is currently playing.
*/},{key:"isVideoPlaying",value:function isVideoPlaying(video){return video.currentTime>0&&!video.paused&&!video.ended&&video.readyState>2;}/**
* Just tries to play the video and logs any errors.
* The play call is only made is the video is not already playing.
*/},{key:"tryPlayVideo",value:function tryPlayVideo(videoElement){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee13(){return _regeneratorRuntime.wrap(function _callee13$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:if(!this.isVideoPlaying(videoElement)){_context13.next=3;break;}console.warn('Trying to play video that is already playing.');return _context13.abrupt("return");case 3:_context13.prev=3;_context13.next=6;return videoElement.play();case 6:_context13.next=11;break;case 8:_context13.prev=8;_context13.t0=_context13["catch"](3);console.warn('It was not possible to play the video.');case 11:case"end":return _context13.stop();}}},_callee13,this,[[3,8]]);}));}/**
* Searches and validates a media element.
*/},{key:"getMediaElement",value:function getMediaElement(mediaElementId,type){var mediaElement=document.getElementById(mediaElementId);if(!mediaElement){throw new ArgumentException("element with id '".concat(mediaElementId,"' not found"));}if(mediaElement.nodeName.toLowerCase()!==type.toLowerCase()){throw new ArgumentException("element with id '".concat(mediaElementId,"' must be an ").concat(type," element"));}return mediaElement;}/**
* Decodes the barcode from an image.
*
* @param {(string|HTMLImageElement)} [source] The image element that can be either an element id or the element itself. Can be undefined in which case the decoding will be done from the imageUrl parameter.
* @param {string} [url]
* @returns {Promise<Result>} The decoding result.
*
* @memberOf BrowserCodeReader
*/},{key:"decodeFromImage",value:function decodeFromImage(source,url){if(!source&&!url){throw new ArgumentException('either imageElement with a src set or an url must be provided');}if(url&&!source){return this.decodeFromImageUrl(url);}return this.decodeFromImageElement(source);}/**
* Decodes the barcode from a video.
*
* @param {(string|HTMLImageElement)} [source] The image element that can be either an element id or the element itself. Can be undefined in which case the decoding will be done from the imageUrl parameter.
* @param {string} [url]
* @returns {Promise<Result>} The decoding result.
*
* @memberOf BrowserCodeReader
*/},{key:"decodeFromVideo",value:function decodeFromVideo(source,url){if(!source&&!url){throw new ArgumentException('Either an element with a src set or an URL must be provided');}if(url&&!source){return this.decodeFromVideoUrl(url);}return this.decodeFromVideoElement(source);}/**
* Decodes continuously the barcode from a video.
*
* @param {(string|HTMLImageElement)} [source] The image element that can be either an element id or the element itself. Can be undefined in which case the decoding will be done from the imageUrl parameter.
* @param {string} [url]
* @returns {Promise<Result>} The decoding result.
*
* @memberOf BrowserCodeReader
*
* @experimental
*/},{key:"decodeFromVideoContinuously",value:function decodeFromVideoContinuously(source,url,callbackFn){if(undefined===source&&undefined===url){throw new ArgumentException('Either an element with a src set or an URL must be provided');}if(url&&!source){return this.decodeFromVideoUrlContinuously(url,callbackFn);}return this.decodeFromVideoElementContinuously(source,callbackFn);}/**
* Decodes something from an image HTML element.
*/},{key:"decodeFromImageElement",value:function decodeFromImageElement(source){if(!source){throw new ArgumentException('An image element must be provided.');}this.reset();var element=this.prepareImageElement(source);this.imageElement=element;var task;if(this.isImageLoaded(element)){task=this.decodeOnce(element,false,true);}else{task=this._decodeOnLoadImage(element);}return task;}/**
* Decodes something from an image HTML element.
*/},{key:"decodeFromVideoElement",value:function decodeFromVideoElement(source){var element=this._decodeFromVideoElementSetup(source);return this._decodeOnLoadVideo(element);}/**
* Decodes something from an image HTML element.
*/},{key:"decodeFromVideoElementContinuously",value:function decodeFromVideoElementContinuously(source,callbackFn){var element=this._decodeFromVideoElementSetup(source);return this._decodeOnLoadVideoContinuously(element,callbackFn);}/**
* Sets up the video source so it can be decoded when loaded.
*
* @param source The video source element.
*/},{key:"_decodeFromVideoElementSetup",value:function _decodeFromVideoElementSetup(source){if(!source){throw new ArgumentException('A video element must be provided.');}this.reset();var element=this.prepareVideoElement(source);// defines the video element before starts decoding
this.videoElement=element;return element;}/**
* Decodes an image from a URL.
*/},{key:"decodeFromImageUrl",value:function decodeFromImageUrl(url){if(!url){throw new ArgumentException('An URL must be provided.');}this.reset();var element=this.prepareImageElement();this.imageElement=element;var decodeTask=this._decodeOnLoadImage(element);element.src=url;return decodeTask;}/**
* Decodes an image from a URL.
*/},{key:"decodeFromVideoUrl",value:function decodeFromVideoUrl(url){if(!url){throw new ArgumentException('An URL must be provided.');}this.reset();// creates a new element
var element=this.prepareVideoElement();var decodeTask=this.decodeFromVideoElement(element);element.src=url;return decodeTask;}/**
* Decodes an image from a URL.
*
* @experimental
*/},{key:"decodeFromVideoUrlContinuously",value:function decodeFromVideoUrlContinuously(url,callbackFn){if(!url){throw new ArgumentException('An URL must be provided.');}this.reset();// creates a new element
var element=this.prepareVideoElement();var decodeTask=this.decodeFromVideoElementContinuously(element,callbackFn);element.src=url;return decodeTask;}},{key:"_decodeOnLoadImage",value:function _decodeOnLoadImage(element){var _this10=this;return new Promise(function(resolve,reject){_this10.imageLoadedListener=function(){return _this10.decodeOnce(element,false,true).then(resolve,reject);};element.addEventListener('load',_this10.imageLoadedListener);});}},{key:"_decodeOnLoadVideo",value:function _decodeOnLoadVideo(videoElement){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee14(){return _regeneratorRuntime.wrap(function _callee14$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:_context14.next=2;return this.playVideoOnLoadAsync(videoElement);case 2:_context14.next=4;return this.decodeOnce(videoElement);case 4:return _context14.abrupt("return",_context14.sent);case 5:case"end":return _context14.stop();}}},_callee14,this);}));}},{key:"_decodeOnLoadVideoContinuously",value:function _decodeOnLoadVideoContinuously(videoElement,callbackFn){return __awaiter(this,void 0,void 0,/*#__PURE__*/_regeneratorRuntime.mark(function _callee15(){return _regeneratorRuntime.wrap(function _callee15$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:_context15.next=2;return this.playVideoOnLoadAsync(videoElement);case 2:// starts decoding after played the video
this.decodeContinuously(videoElement,callbackFn);case 3:case"end":return _context15.stop();}}},_callee15,this);}));}},{key:"isImageLoaded",value:function isImageLoaded(img){// During the onload event, IE correctly identifies any images that
// weren’t downloaded as not complete. Others should too. Gecko-based
// browsers act like NS4 in that they report this incorrectly.
if(!img.complete){return false;}// However, they do have two very useful properties: naturalWidth and
// naturalHeight. These give the true size of the image. If it failed
// to load, either of these should be zero.
if(img.naturalWidth===0){return false;}// No other way of checking: assume it’s ok.
return true;}},{key:"prepareImageElement",value:function prepareImageElement(imageSource){var imageElement;if(typeof imageSource==='undefined'){imageElement=document.createElement('img');imageElement.width=200;imageElement.height=200;}if(typeof imageSource==='string'){imageElement=this.getMediaElement(imageSource,'img');}if(imageSource instanceof HTMLImageElement){imageElement=imageSource;}return imageElement;}/**
* Sets a HTMLVideoElement for scanning or creates a new one.
*
* @param videoSource The HTMLVideoElement to be set.
*/},{key:"prepareVideoElement",value:function prepareVideoElement(videoSource){var videoElement;if(!videoSource&&typeof document!=='undefined'){videoElement=document.createElement('video');videoElement.width=200;videoElement.height=200;}if(typeof videoSource==='string'){videoElement=this.getMediaElement(videoSource,'video');}if(videoSource instanceof HTMLVideoElement){videoElement=videoSource;}// Needed for iOS 11
videoElement.setAttribute('autoplay','true');videoElement.setAttribute('muted','true');videoElement.setAttribute('playsinline','true');return videoElement;}/**
* Tries to decode from the video input until it finds some value.
*/},{key:"decodeOnce",value:function decodeOnce(element){var _this11=this;var retryIfNotFound=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var retryIfChecksumOrFormatError=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;this._stopAsyncDecode=false;var loop=function loop(resolve,reject){if(_this11._stopAsyncDecode){reject(new NotFoundException('Video stream has ended before any code could be detected.'));_this11._stopAsyncDecode=undefined;return;}try{var result=_this11.decode(element);resolve(result);}catch(e){var ifNotFound=retryIfNotFound&&e instanceof NotFoundException;var isChecksumOrFormatError=e instanceof ChecksumException||e instanceof FormatException;var ifChecksumOrFormat=isChecksumOrFormatError&&retryIfChecksumOrFormatError;if(ifNotFound||ifChecksumOrFormat){// trying again
return setTimeout(loop,_this11._timeBetweenDecodingAttempts,resolve,reject);}reject(e);}};return new Promise(function(resolve,reject){return loop(resolve,reject);});}/**
* Continuously decodes from video input.
*/},{key:"decodeContinuously",value:function decodeContinuously(element,callbackFn){var _this12=this;this._stopContinuousDecode=false;var loop=function loop(){if(_this12._stopContinuousDecode){_this12._stopContinuousDecode=undefined;return;}try{var result=_this12.decode(element);callbackFn(result,null);setTimeout(loop,_this12.timeBetweenScansMillis);}catch(e){callbackFn(null,e);var isChecksumOrFormatError=e instanceof ChecksumException||e instanceof FormatException;var isNotFound=e instanceof NotFoundException;if(isChecksumOrFormatError||isNotFound){// trying again
setTimeout(loop,_this12._timeBetweenDecodingAttempts);}}};loop();}/**
* Gets the BinaryBitmap for ya! (and decodes it)
*/},{key:"decode",value:function decode(element){// get binary bitmap for decode function
var binaryBitmap=this.createBinaryBitmap(element);return this.decodeBitmap(binaryBitmap);}/**
* Returns true if media element is indeed a {@link HtmlVideoElement}.
*/},{key:"_isHTMLVideoElement",value:function _isHTMLVideoElement(mediaElement){var potentialVideo=mediaElement;return potentialVideo.videoWidth!==0;}/**
* Overwriting this allows you to manipulate the next frame in anyway
* you want before decode.
*/},{key:"drawFrameOnCanvas",value:function drawFrameOnCanvas(srcElement,dimensions,canvasElementContext){if(!dimensions){dimensions={sx:0,sy:0,sWidth:srcElement.videoWidth,sHeight:srcElement.videoHeight,dx:0,dy:0,dWidth:srcElement.videoWidth,dHeight:srcElement.videoHeight};}if(!canvasElementContext){canvasElementContext=this.captureCanvasContext;}canvasElementContext.drawImage(srcElement,dimensions.sx,dimensions.sy,dimensions.sWidth,dimensions.sHeight,dimensions.dx,dimensions.dy,dimensions.dWidth,dimensions.dHeight);}/**
* Ovewriting this allows you to manipulate the snapshot image in anyway
* you want before decode.
*/},{key:"drawImageOnCanvas",value:function drawImageOnCanvas(srcElement,dimensions){var canvasElementContext=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this.captureCanvasContext;if(!dimensions){dimensions={sx:0,sy:0,sWidth:srcElement.naturalWidth,sHeight:srcElement.naturalHeight,dx:0,dy:0,dWidth:srcElement.naturalWidth,dHeight:srcElement.naturalHeight};}if(!canvasElementContext){canvasElementContext=this.captureCanvasContext;}canvasElementContext.drawImage(srcElement,dimensions.sx,dimensions.sy,dimensions.sWidth,dimensions.sHeight,dimensions.dx,dimensions.dy,dimensions.dWidth,dimensions.dHeight);}/**
* Creates a binaryBitmap based in some image source.
*
* @param mediaElement HTML element containing drawable image source.
*/},{key:"createBinaryBitmap",value:function createBinaryBitmap(mediaElement){var ctx=this.getCaptureCanvasContext(mediaElement);if(this._isHTMLVideoElement(mediaElement)){this.drawFrameOnCanvas(mediaElement);}else{this.drawImageOnCanvas(mediaElement);}var canvas=this.getCaptureCanvas(mediaElement);var luminanceSource=new HTMLCanvasElementLuminanceSource(canvas);var hybridBinarizer=new HybridBinarizer(luminanceSource);return new BinaryBitmap(hybridBinarizer);}},{key:"getCaptureCanvasContext",value:function getCaptureCanvasContext(mediaElement){if(!this.captureCanvasContext){var elem=this.getCaptureCanvas(mediaElement);var ctx=elem.getContext('2d');this.captureCanvasContext=ctx;}return this.captureCanvasContext;}},{key:"getCaptureCanvas",value:function getCaptureCanvas(mediaElement){if(!this.captureCanvas){var elem=this.createCaptureCanvas(mediaElement);this.captureCanvas=elem;}return this.captureCanvas;}/**
* Call the encapsulated readers decode
*/},{key:"decodeBitmap",value:function decodeBitmap(binaryBitmap){return this.reader.decode(binaryBitmap,this._hints);}/**
* 🖌 Prepares the canvas for capture and scan frames.
*/},{key:"createCaptureCanvas",value:function createCaptureCanvas(mediaElement){if(typeof document==='undefined'){this._destroyCaptureCanvas();return null;}var canvasElement=document.createElement('canvas');var width;var height;if(typeof mediaElement!=='undefined'){if(mediaElement instanceof HTMLVideoElement){width=mediaElement.videoWidth;height=mediaElement.videoHeight;}else if(mediaElement instanceof HTMLImageElement){width=mediaElement.naturalWidth||mediaElement.width;height=mediaElement.naturalHeight||mediaElement.height;}}canvasElement.style.width=width+'px';canvasElement.style.height=height+'px';canvasElement.width=width;canvasElement.height=height;return canvasElement;}/**
* Stops the continuous scan and cleans the stream.
*/},{key:"stopStreams",value:function stopStreams(){if(this.stream){this.stream.getVideoTracks().forEach(function(t){return t.stop();});this.stream=undefined;}if(this._stopAsyncDecode===false){this.stopAsyncDecode();}if(this._stopContinuousDecode===false){this.stopContinuousDecode();}}/**
* Resets the code reader to the initial state. Cancels any ongoing barcode scanning from video or camera.
*
* @memberOf BrowserCodeReader
*/},{key:"reset",value:function reset(){// stops the camera, preview and scan 🔴
this.stopStreams();// clean and forget about HTML elements
this._destroyVideoElement();this._destroyImageElement();this._destroyCaptureCanvas();}},{key:"_destroyVideoElement",value:function _destroyVideoElement(){if(!this.videoElement){return;}// first gives freedon to the element 🕊
if(typeof this.videoEndedListener!=='undefined'){this.videoElement.removeEventListener('ended',this.videoEndedListener);}if(typeof this.videoPlayingEventListener!=='undefined'){this.videoElement.removeEventListener('playing',this.videoPlayingEventListener);}if(typeof this.videoCanPlayListener!=='undefined'){this.videoElement.removeEventListener('loadedmetadata',this.videoCanPlayListener);}// then forgets about that element 😢
this.cleanVideoSource(this.videoElement);this.videoElement=undefined;}},{key:"_destroyImageElement",value:function _destroyImageElement(){if(!this.imageElement){return;}// first gives freedon to the element 🕊
if(undefined!==this.imageLoadedListener){this.imageElement.removeEventListener('load',this.imageLoadedListener);}// then forget about that element 😢
this.imageElement.src=undefined;this.imageElement.removeAttribute('src');this.imageElement=undefined;}/**
* Cleans canvas references 🖌
*/},{key:"_destroyCaptureCanvas",value:function _destroyCaptureCanvas(){// then forget about that element 😢
this.captureCanvasContext=undefined;this.captureCanvas=undefined;}/**
* Defines what the videoElement src will be.
*
* @param videoElement
* @param stream
*/},{key:"addVideoSource",value:function addVideoSource(videoElement,stream){// Older browsers may not have `srcObject`
try{// @note Throws Exception if interrupted by a new loaded request
videoElement.srcObject=stream;}catch(err){// @note Avoid using this in new browsers, as it is going away.
videoElement.src=URL.createObjectURL(stream);}}/**
* Unbinds a HTML video src property.
*
* @param videoElement
*/},{key:"cleanVideoSource",value:function cleanVideoSource(videoElement){try{videoElement.srcObject=null;}catch(err){videoElement.src='';}this.videoElement.removeAttribute('src');}}]);return BrowserCodeReader;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Encapsulates the result of decoding a barcode within an image.</p>
*
* @author Sean Owen
*/var Result=/*#__PURE__*/function(){// public constructor(private text: string,
// Uint8Array rawBytes,
// ResultPoconst resultPoints: Int32Array,
// BarcodeFormat format) {
// this(text, rawBytes, resultPoints, format, System.currentTimeMillis())
// }
// public constructor(text: string,
// Uint8Array rawBytes,
// ResultPoconst resultPoints: Int32Array,
// BarcodeFormat format,
// long timestamp) {
// this(text, rawBytes, rawBytes == null ? 0 : 8 * rawBytes.length,
// resultPoints, format, timestamp)
// }
function Result(text,rawBytes){var numBits=arguments.length>2&&arguments[2]!==undefined?arguments[2]:rawBytes==null?0:8*rawBytes.length;var resultPoints=arguments.length>3?arguments[3]:undefined;var format=arguments.length>4?arguments[4]:undefined;var timestamp=arguments.length>5&&arguments[5]!==undefined?arguments[5]:System.currentTimeMillis();_classCallCheck(this,Result);this.text=text;this.rawBytes=rawBytes;this.numBits=numBits;this.resultPoints=resultPoints;this.format=format;this.timestamp=timestamp;this.text=text;this.rawBytes=rawBytes;if(undefined===numBits||null===numBits){this.numBits=rawBytes===null||rawBytes===undefined?0:8*rawBytes.length;}else{this.numBits=numBits;}this.resultPoints=resultPoints;this.format=format;this.resultMetadata=null;if(undefined===timestamp||null===timestamp){this.timestamp=System.currentTimeMillis();}else{this.timestamp=timestamp;}}/**
* @return raw text encoded by the barcode
*/_createClass(Result,[{key:"getText",value:function getText(){return this.text;}/**
* @return raw bytes encoded by the barcode, if applicable, otherwise {@code null}
*/},{key:"getRawBytes",value:function getRawBytes(){return this.rawBytes;}/**
* @return how many bits of {@link #getRawBytes()} are valid; typically 8 times its length
* @since 3.3.0
*/},{key:"getNumBits",value:function getNumBits(){return this.numBits;}/**
* @return points related to the barcode in the image. These are typically points
* identifying finder patterns or the corners of the barcode. The exact meaning is
* specific to the type of barcode that was decoded.
*/},{key:"getResultPoints",value:function getResultPoints(){return this.resultPoints;}/**
* @return {@link BarcodeFormat} representing the format of the barcode that was decoded
*/},{key:"getBarcodeFormat",value:function getBarcodeFormat(){return this.format;}/**
* @return {@link Map} mapping {@link ResultMetadataType} keys to values. May be
* {@code null}. This contains optional metadata about what was detected about the barcode,
* like orientation.
*/},{key:"getResultMetadata",value:function getResultMetadata(){return this.resultMetadata;}},{key:"putMetadata",value:function putMetadata(type,value){if(this.resultMetadata===null){this.resultMetadata=new Map();}this.resultMetadata.set(type,value);}},{key:"putAllMetadata",value:function putAllMetadata(metadata){if(metadata!==null){if(this.resultMetadata===null){this.resultMetadata=metadata;}else{this.resultMetadata=new Map(metadata);}}}},{key:"addResultPoints",value:function addResultPoints(newPoints){var oldPoints=this.resultPoints;if(oldPoints===null){this.resultPoints=newPoints;}else if(newPoints!==null&&newPoints.length>0){var allPoints=new Array(oldPoints.length+newPoints.length);System.arraycopy(oldPoints,0,allPoints,0,oldPoints.length);System.arraycopy(newPoints,0,allPoints,oldPoints.length,newPoints.length);this.resultPoints=allPoints;}}},{key:"getTimestamp",value:function getTimestamp(){return this.timestamp;}/*@Override*/},{key:"toString",value:function toString(){return this.text;}}]);return Result;}();/*
* Direct port to TypeScript of ZXing by Adrian Toșcă
*/ /*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*namespace com.google.zxing {*/ /**
* Enumerates barcode formats known to this package. Please keep alphabetized.
*
* @author Sean Owen
*/var BarcodeFormat;(function(BarcodeFormat){/** Aztec 2D barcode format. */BarcodeFormat[BarcodeFormat["AZTEC"]=0]="AZTEC";/** CODABAR 1D format. */BarcodeFormat[BarcodeFormat["CODABAR"]=1]="CODABAR";/** Code 39 1D format. */BarcodeFormat[BarcodeFormat["CODE_39"]=2]="CODE_39";/** Code 93 1D format. */BarcodeFormat[BarcodeFormat["CODE_93"]=3]="CODE_93";/** Code 128 1D format. */BarcodeFormat[BarcodeFormat["CODE_128"]=4]="CODE_128";/** Data Matrix 2D barcode format. */BarcodeFormat[BarcodeFormat["DATA_MATRIX"]=5]="DATA_MATRIX";/** EAN-8 1D format. */BarcodeFormat[BarcodeFormat["EAN_8"]=6]="EAN_8";/** EAN-13 1D format. */BarcodeFormat[BarcodeFormat["EAN_13"]=7]="EAN_13";/** ITF (Interleaved Two of Five) 1D format. */BarcodeFormat[BarcodeFormat["ITF"]=8]="ITF";/** MaxiCode 2D barcode format. */BarcodeFormat[BarcodeFormat["MAXICODE"]=9]="MAXICODE";/** PDF417 format. */BarcodeFormat[BarcodeFormat["PDF_417"]=10]="PDF_417";/** QR Code 2D barcode format. */BarcodeFormat[BarcodeFormat["QR_CODE"]=11]="QR_CODE";/** RSS 14 */BarcodeFormat[BarcodeFormat["RSS_14"]=12]="RSS_14";/** RSS EXPANDED */BarcodeFormat[BarcodeFormat["RSS_EXPANDED"]=13]="RSS_EXPANDED";/** UPC-A 1D format. */BarcodeFormat[BarcodeFormat["UPC_A"]=14]="UPC_A";/** UPC-E 1D format. */BarcodeFormat[BarcodeFormat["UPC_E"]=15]="UPC_E";/** UPC/EAN extension format. Not a stand-alone format. */BarcodeFormat[BarcodeFormat["UPC_EAN_EXTENSION"]=16]="UPC_EAN_EXTENSION";})(BarcodeFormat||(BarcodeFormat={}));var BarcodeFormat$1=BarcodeFormat;/*namespace com.google.zxing {*/ /**
* Represents some type of metadata about the result of the decoding that the decoder
* wishes to communicate back to the caller.
*
* @author Sean Owen
*/var ResultMetadataType;(function(ResultMetadataType){/**
* Unspecified, application-specific metadata. Maps to an unspecified {@link Object}.
*/ResultMetadataType[ResultMetadataType["OTHER"]=0]="OTHER";/**
* Denotes the likely approximate orientation of the barcode in the image. This value
* is given as degrees rotated clockwise from the normal, upright orientation.
* For example a 1D barcode which was found by reading top-to-bottom would be
* said to have orientation "90". This key maps to an {@link Integer} whose
* value is in the range [0,360).
*/ResultMetadataType[ResultMetadataType["ORIENTATION"]=1]="ORIENTATION";/**
* <p>2D barcode formats typically encode text, but allow for a sort of 'byte mode'
* which is sometimes used to encode binary data. While {@link Result} makes available
* the complete raw bytes in the barcode for these formats, it does not offer the bytes
* from the byte segments alone.</p>
*
* <p>This maps to a {@link java.util.List} of byte arrays corresponding to the
* raw bytes in the byte segments in the barcode, in order.</p>
*/ResultMetadataType[ResultMetadataType["BYTE_SEGMENTS"]=2]="BYTE_SEGMENTS";/**
* Error correction level used, if applicable. The value type depends on the
* format, but is typically a String.
*/ResultMetadataType[ResultMetadataType["ERROR_CORRECTION_LEVEL"]=3]="ERROR_CORRECTION_LEVEL";/**
* For some periodicals, indicates the issue number as an {@link Integer}.
*/ResultMetadataType[ResultMetadataType["ISSUE_NUMBER"]=4]="ISSUE_NUMBER";/**
* For some products, indicates the suggested retail price in the barcode as a
* formatted {@link String}.
*/ResultMetadataType[ResultMetadataType["SUGGESTED_PRICE"]=5]="SUGGESTED_PRICE";/**
* For some products, the possible country of manufacture as a {@link String} denoting the
* ISO country code. Some map to multiple possible countries, like "US/CA".
*/ResultMetadataType[ResultMetadataType["POSSIBLE_COUNTRY"]=6]="POSSIBLE_COUNTRY";/**
* For some products, the extension text
*/ResultMetadataType[ResultMetadataType["UPC_EAN_EXTENSION"]=7]="UPC_EAN_EXTENSION";/**
* PDF417-specific metadata
*/ResultMetadataType[ResultMetadataType["PDF417_EXTRA_METADATA"]=8]="PDF417_EXTRA_METADATA";/**
* If the code format supports structured append and the current scanned code is part of one then the
* sequence number is given with it.
*/ResultMetadataType[ResultMetadataType["STRUCTURED_APPEND_SEQUENCE"]=9]="STRUCTURED_APPEND_SEQUENCE";/**
* If the code format supports structured append and the current scanned code is part of one then the
* parity is given with it.
*/ResultMetadataType[ResultMetadataType["STRUCTURED_APPEND_PARITY"]=10]="STRUCTURED_APPEND_PARITY";})(ResultMetadataType||(ResultMetadataType={}));var ResultMetadataType$1=ResultMetadataType;/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*namespace com.google.zxing.common {*/ /*import java.util.List;*/ /**
* <p>Encapsulates the result of decoding a matrix of bits. This typically
* applies to 2D barcode formats. For now it contains the raw bytes obtained,
* as well as a String interpretation of those bytes, if applicable.</p>
*
* @author Sean Owen
*/var DecoderResult=/*#__PURE__*/function(){// public constructor(rawBytes: Uint8Array,
// text: string,
// List<Uint8Array> byteSegments,
// String ecLevel) {
// this(rawBytes, text, byteSegments, ecLevel, -1, -1)
// }
function DecoderResult(rawBytes,text,byteSegments,ecLevel){var structuredAppendSequenceNumber=arguments.length>4&&arguments[4]!==undefined?arguments[4]:-1;var structuredAppendParity=arguments.length>5&&arguments[5]!==undefined?arguments[5]:-1;_classCallCheck(this,DecoderResult);this.rawBytes=rawBytes;this.text=text;this.byteSegments=byteSegments;this.ecLevel=ecLevel;this.structuredAppendSequenceNumber=structuredAppendSequenceNumber;this.structuredAppendParity=structuredAppendParity;this.numBits=rawBytes===undefined||rawBytes===null?0:8*rawBytes.length;}/**
* @return raw bytes representing the result, or {@code null} if not applicable
*/_createClass(DecoderResult,[{key:"getRawBytes",value:function getRawBytes(){return this.rawBytes;}/**
* @return how many bits of {@link #getRawBytes()} are valid; typically 8 times its length
* @since 3.3.0
*/},{key:"getNumBits",value:function getNumBits(){return this.numBits;}/**
* @param numBits overrides the number of bits that are valid in {@link #getRawBytes()}
* @since 3.3.0
*/},{key:"setNumBits",value:function setNumBits(numBits/*int*/){this.numBits=numBits;}/**
* @return text representation of the result
*/},{key:"getText",value:function getText(){return this.text;}/**
* @return list of byte segments in the result, or {@code null} if not applicable
*/},{key:"getByteSegments",value:function getByteSegments(){return this.byteSegments;}/**
* @return name of error correction level used, or {@code null} if not applicable
*/},{key:"getECLevel",value:function getECLevel(){return this.ecLevel;}/**
* @return number of errors corrected, or {@code null} if not applicable
*/},{key:"getErrorsCorrected",value:function getErrorsCorrected(){return this.errorsCorrected;}},{key:"setErrorsCorrected",value:function setErrorsCorrected(errorsCorrected/*Integer*/){this.errorsCorrected=errorsCorrected;}/**
* @return number of erasures corrected, or {@code null} if not applicable
*/},{key:"getErasures",value:function getErasures(){return this.erasures;}},{key:"setErasures",value:function setErasures(erasures/*Integer*/){this.erasures=erasures;}/**
* @return arbitrary additional metadata
*/},{key:"getOther",value:function getOther(){return this.other;}},{key:"setOther",value:function setOther(other){this.other=other;}},{key:"hasStructuredAppend",value:function hasStructuredAppend(){return this.structuredAppendParity>=0&&this.structuredAppendSequenceNumber>=0;}},{key:"getStructuredAppendParity",value:function getStructuredAppendParity(){return this.structuredAppendParity;}},{key:"getStructuredAppendSequenceNumber",value:function getStructuredAppendSequenceNumber(){return this.structuredAppendSequenceNumber;}}]);return DecoderResult;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>This class contains utility methods for performing mathematical operations over
* the Galois Fields. Operations use a given primitive polynomial in calculations.</p>
*
* <p>Throughout this package, elements of the GF are represented as an {@code int}
* for convenience and speed (but at the cost of memory).
* </p>
*
* @author Sean Owen
* @author David Olivier
*/var AbstractGenericGF=/*#__PURE__*/function(){function AbstractGenericGF(){_classCallCheck(this,AbstractGenericGF);}_createClass(AbstractGenericGF,[{key:"exp",value:/**
* @return 2 to the power of a in GF(size)
*/function exp(a){return this.expTable[a];}/**
* @return base 2 log of a in GF(size)
*/},{key:"log",value:function log(a/*int*/){if(a===0){throw new IllegalArgumentException();}return this.logTable[a];}/**
* Implements both addition and subtraction -- they are the same in GF(size).
*
* @return sum/difference of a and b
*/}],[{key:"addOrSubtract",value:function addOrSubtract(a/*int*/,b/*int*/){return a^b;}}]);return AbstractGenericGF;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Represents a polynomial whose coefficients are elements of a GF.
* Instances of this class are immutable.</p>
*
* <p>Much credit is due to William Rucklidge since portions of this code are an indirect
* port of his C++ Reed-Solomon implementation.</p>
*
* @author Sean Owen
*/var GenericGFPoly=/*#__PURE__*/function(){/**
* @param field the {@link GenericGF} instance representing the field to use
* to perform computations
* @param coefficients coefficients as ints representing elements of GF(size), arranged
* from most significant (highest-power term) coefficient to least significant
* @throws IllegalArgumentException if argument is null or empty,
* or if leading coefficient is 0 and this is not a
* constant polynomial (that is, it is not the monomial "0")
*/function GenericGFPoly(field,coefficients){_classCallCheck(this,GenericGFPoly);if(coefficients.length===0){throw new IllegalArgumentException();}this.field=field;var coefficientsLength=coefficients.length;if(coefficientsLength>1&&coefficients[0]===0){// Leading term must be non-zero for anything except the constant polynomial "0"
var firstNonZero=1;while(firstNonZero<coefficientsLength&&coefficients[firstNonZero]===0){firstNonZero++;}if(firstNonZero===coefficientsLength){this.coefficients=Int32Array.from([0]);}else{this.coefficients=new Int32Array(coefficientsLength-firstNonZero);System.arraycopy(coefficients,firstNonZero,this.coefficients,0,this.coefficients.length);}}else{this.coefficients=coefficients;}}_createClass(GenericGFPoly,[{key:"getCoefficients",value:function getCoefficients(){return this.coefficients;}/**
* @return degree of this polynomial
*/},{key:"getDegree",value:function getDegree(){return this.coefficients.length-1;}/**
* @return true iff this polynomial is the monomial "0"
*/},{key:"isZero",value:function isZero(){return this.coefficients[0]===0;}/**
* @return coefficient of x^degree term in this polynomial
*/},{key:"getCoefficient",value:function getCoefficient(degree/*int*/){return this.coefficients[this.coefficients.length-1-degree];}/**
* @return evaluation of this polynomial at a given point
*/},{key:"evaluateAt",value:function evaluateAt(a/*int*/){if(a===0){// Just return the x^0 coefficient
return this.getCoefficient(0);}var coefficients=this.coefficients;var result;if(a===1){// Just the sum of the coefficients
result=0;for(var i=0,length=coefficients.length;i!==length;i++){var coefficient=coefficients[i];result=AbstractGenericGF.addOrSubtract(result,coefficient);}return result;}result=coefficients[0];var size=coefficients.length;var field=this.field;for(var _i3=1;_i3<size;_i3++){result=AbstractGenericGF.addOrSubtract(field.multiply(a,result),coefficients[_i3]);}return result;}},{key:"addOrSubtract",value:function addOrSubtract(other){if(!this.field.equals(other.field)){throw new IllegalArgumentException('GenericGFPolys do not have same GenericGF field');}if(this.isZero()){return other;}if(other.isZero()){return this;}var smallerCoefficients=this.coefficients;var largerCoefficients=other.coefficients;if(smallerCoefficients.length>largerCoefficients.length){var temp=smallerCoefficients;smallerCoefficients=largerCoefficients;largerCoefficients=temp;}var sumDiff=new Int32Array(largerCoefficients.length);var lengthDiff=largerCoefficients.length-smallerCoefficients.length;// Copy high-order terms only found in higher-degree polynomial's coefficients
System.arraycopy(largerCoefficients,0,sumDiff,0,lengthDiff);for(var i=lengthDiff;i<largerCoefficients.length;i++){sumDiff[i]=AbstractGenericGF.addOrSubtract(smallerCoefficients[i-lengthDiff],largerCoefficients[i]);}return new GenericGFPoly(this.field,sumDiff);}},{key:"multiply",value:function multiply(other){if(!this.field.equals(other.field)){throw new IllegalArgumentException('GenericGFPolys do not have same GenericGF field');}if(this.isZero()||other.isZero()){return this.field.getZero();}var aCoefficients=this.coefficients;var aLength=aCoefficients.length;var bCoefficients=other.coefficients;var bLength=bCoefficients.length;var product=new Int32Array(aLength+bLength-1);var field=this.field;for(var i=0;i<aLength;i++){var aCoeff=aCoefficients[i];for(var j=0;j<bLength;j++){product[i+j]=AbstractGenericGF.addOrSubtract(product[i+j],field.multiply(aCoeff,bCoefficients[j]));}}return new GenericGFPoly(field,product);}},{key:"multiplyScalar",value:function multiplyScalar(scalar/*int*/){if(scalar===0){return this.field.getZero();}if(scalar===1){return this;}var size=this.coefficients.length;var field=this.field;var product=new Int32Array(size);var coefficients=this.coefficients;for(var i=0;i<size;i++){product[i]=field.multiply(coefficients[i],scalar);}return new GenericGFPoly(field,product);}},{key:"multiplyByMonomial",value:function multiplyByMonomial(degree/*int*/,coefficient/*int*/){if(degree<0){throw new IllegalArgumentException();}if(coefficient===0){return this.field.getZero();}var coefficients=this.coefficients;var size=coefficients.length;var product=new Int32Array(size+degree);var field=this.field;for(var i=0;i<size;i++){product[i]=field.multiply(coefficients[i],coefficient);}return new GenericGFPoly(field,product);}},{key:"divide",value:function divide(other){if(!this.field.equals(other.field)){throw new IllegalArgumentException('GenericGFPolys do not have same GenericGF field');}if(other.isZero()){throw new IllegalArgumentException('Divide by 0');}var field=this.field;var quotient=field.getZero();var remainder=this;var denominatorLeadingTerm=other.getCoefficient(other.getDegree());var inverseDenominatorLeadingTerm=field.inverse(denominatorLeadingTerm);while(remainder.getDegree()>=other.getDegree()&&!remainder.isZero()){var degreeDifference=remainder.getDegree()-other.getDegree();var scale=field.multiply(remainder.getCoefficient(remainder.getDegree()),inverseDenominatorLeadingTerm);var term=other.multiplyByMonomial(degreeDifference,scale);var iterationQuotient=field.buildMonomial(degreeDifference,scale);quotient=quotient.addOrSubtract(iterationQuotient);remainder=remainder.addOrSubtract(term);}return[quotient,remainder];}/*@Override*/},{key:"toString",value:function toString(){var result='';for(var degree=this.getDegree();degree>=0;degree--){var coefficient=this.getCoefficient(degree);if(coefficient!==0){if(coefficient<0){result+=' - ';coefficient=-coefficient;}else{if(result.length>0){result+=' + ';}}if(degree===0||coefficient!==1){var alphaPower=this.field.log(coefficient);if(alphaPower===0){result+='1';}else if(alphaPower===1){result+='a';}else{result+='a^';result+=alphaPower;}}if(degree!==0){if(degree===1){result+='x';}else{result+='x^';result+=degree;}}}}return result;}}]);return GenericGFPoly;}();/**
* Custom Error class of type Exception.
*/var ArithmeticException=/*#__PURE__*/function(_Exception8){_inherits(ArithmeticException,_Exception8);var _super15=_createSuper(ArithmeticException);function ArithmeticException(){_classCallCheck(this,ArithmeticException);return _super15.apply(this,arguments);}return _createClass(ArithmeticException);}(Exception);ArithmeticException.kind='ArithmeticException';/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>This class contains utility methods for performing mathematical operations over
* the Galois Fields. Operations use a given primitive polynomial in calculations.</p>
*
* <p>Throughout this package, elements of the GF are represented as an {@code int}
* for convenience and speed (but at the cost of memory).
* </p>
*
* @author Sean Owen
* @author David Olivier
*/var GenericGF=/*#__PURE__*/function(_AbstractGenericGF){_inherits(GenericGF,_AbstractGenericGF);var _super16=_createSuper(GenericGF);/**
* Create a representation of GF(size) using the given primitive polynomial.
*
* @param primitive irreducible polynomial whose coefficients are represented by
* the bits of an int, where the least-significant bit represents the constant
* coefficient
* @param size the size of the field
* @param b the factor b in the generator polynomial can be 0- or 1-based
* (g(x) = (x+a^b)(x+a^(b+1))...(x+a^(b+2t-1))).
* In most cases it should be 1, but for QR code it is 0.
*/function GenericGF(primitive/*int*/,size/*int*/,generatorBase/*int*/){var _this13;_classCallCheck(this,GenericGF);_this13=_super16.call(this);_this13.primitive=primitive;_this13.size=size;_this13.generatorBase=generatorBase;var expTable=new Int32Array(size);var x=1;for(var i=0;i<size;i++){expTable[i]=x;x*=2;// we're assuming the generator alpha is 2
if(x>=size){x^=primitive;x&=size-1;}}_this13.expTable=expTable;var logTable=new Int32Array(size);for(var _i4=0;_i4<size-1;_i4++){logTable[expTable[_i4]]=_i4;}_this13.logTable=logTable;// logTable[0] == 0 but this should never be used
_this13.zero=new GenericGFPoly(_assertThisInitialized(_this13),Int32Array.from([0]));_this13.one=new GenericGFPoly(_assertThisInitialized(_this13),Int32Array.from([1]));return _this13;}_createClass(GenericGF,[{key:"getZero",value:function getZero(){return this.zero;}},{key:"getOne",value:function getOne(){return this.one;}/**
* @return the monomial representing coefficient * x^degree
*/},{key:"buildMonomial",value:function buildMonomial(degree/*int*/,coefficient/*int*/){if(degree<0){throw new IllegalArgumentException();}if(coefficient===0){return this.zero;}var coefficients=new Int32Array(degree+1);coefficients[0]=coefficient;return new GenericGFPoly(this,coefficients);}/**
* @return multiplicative inverse of a
*/},{key:"inverse",value:function inverse(a/*int*/){if(a===0){throw new ArithmeticException();}return this.expTable[this.size-this.logTable[a]-1];}/**
* @return product of a and b in GF(size)
*/},{key:"multiply",value:function multiply(a/*int*/,b/*int*/){if(a===0||b===0){return 0;}return this.expTable[(this.logTable[a]+this.logTable[b])%(this.size-1)];}},{key:"getSize",value:function getSize(){return this.size;}},{key:"getGeneratorBase",value:function getGeneratorBase(){return this.generatorBase;}/*@Override*/},{key:"toString",value:function toString(){return'GF(0x'+Integer.toHexString(this.primitive)+','+this.size+')';}},{key:"equals",value:function equals(o){return o===this;}}]);return GenericGF;}(AbstractGenericGF);GenericGF.AZTEC_DATA_12=new GenericGF(0x1069,4096,1);// x^12 + x^6 + x^5 + x^3 + 1
GenericGF.AZTEC_DATA_10=new GenericGF(0x409,1024,1);// x^10 + x^3 + 1
GenericGF.AZTEC_DATA_6=new GenericGF(0x43,64,1);// x^6 + x + 1
GenericGF.AZTEC_PARAM=new GenericGF(0x13,16,1);// x^4 + x + 1
GenericGF.QR_CODE_FIELD_256=new GenericGF(0x011d,256,0);// x^8 + x^4 + x^3 + x^2 + 1
GenericGF.DATA_MATRIX_FIELD_256=new GenericGF(0x012d,256,1);// x^8 + x^5 + x^3 + x^2 + 1
GenericGF.AZTEC_DATA_8=GenericGF.DATA_MATRIX_FIELD_256;GenericGF.MAXICODE_FIELD_64=GenericGF.AZTEC_DATA_6;/**
* Custom Error class of type Exception.
*/var ReedSolomonException=/*#__PURE__*/function(_Exception9){_inherits(ReedSolomonException,_Exception9);var _super17=_createSuper(ReedSolomonException);function ReedSolomonException(){_classCallCheck(this,ReedSolomonException);return _super17.apply(this,arguments);}return _createClass(ReedSolomonException);}(Exception);ReedSolomonException.kind='ReedSolomonException';/**
* Custom Error class of type Exception.
*/var IllegalStateException=/*#__PURE__*/function(_Exception10){_inherits(IllegalStateException,_Exception10);var _super18=_createSuper(IllegalStateException);function IllegalStateException(){_classCallCheck(this,IllegalStateException);return _super18.apply(this,arguments);}return _createClass(IllegalStateException);}(Exception);IllegalStateException.kind='IllegalStateException';/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Implements Reed-Solomon decoding, as the name implies.</p>
*
* <p>The algorithm will not be explained here, but the following references were helpful
* in creating this implementation:</p>
*
* <ul>
* <li>Bruce Maggs.
* <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps">
* "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li>
* <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf">
* "Chapter 5. Generalized Reed-Solomon Codes"</a>
* (see discussion of Euclidean algorithm)</li>
* </ul>
*
* <p>Much credit is due to William Rucklidge since portions of this code are an indirect
* port of his C++ Reed-Solomon implementation.</p>
*
* @author Sean Owen
* @author William Rucklidge
* @author sanfordsquires
*/var ReedSolomonDecoder=/*#__PURE__*/function(){function ReedSolomonDecoder(field){_classCallCheck(this,ReedSolomonDecoder);this.field=field;}/**
* <p>Decodes given set of received codewords, which include both data and error-correction
* codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
* in the input.</p>
*
* @param received data and error-correction codewords
* @param twoS number of error-correction codewords available
* @throws ReedSolomonException if decoding fails for any reason
*/_createClass(ReedSolomonDecoder,[{key:"decode",value:function decode(received,twoS/*int*/){var field=this.field;var poly=new GenericGFPoly(field,received);var syndromeCoefficients=new Int32Array(twoS);var noError=true;for(var i=0;i<twoS;i++){var evalResult=poly.evaluateAt(field.exp(i+field.getGeneratorBase()));syndromeCoefficients[syndromeCoefficients.length-1-i]=evalResult;if(evalResult!==0){noError=false;}}if(noError){return;}var syndrome=new GenericGFPoly(field,syndromeCoefficients);var sigmaOmega=this.runEuclideanAlgorithm(field.buildMonomial(twoS,1),syndrome,twoS);var sigma=sigmaOmega[0];var omega=sigmaOmega[1];var errorLocations=this.findErrorLocations(sigma);var errorMagnitudes=this.findErrorMagnitudes(omega,errorLocations);for(var _i5=0;_i5<errorLocations.length;_i5++){var position=received.length-1-field.log(errorLocations[_i5]);if(position<0){throw new ReedSolomonException('Bad error location');}received[position]=GenericGF.addOrSubtract(received[position],errorMagnitudes[_i5]);}}},{key:"runEuclideanAlgorithm",value:function runEuclideanAlgorithm(a,b,R/*int*/){// Assume a's degree is >= b's
if(a.getDegree()<b.getDegree()){var temp=a;a=b;b=temp;}var field=this.field;var rLast=a;var r=b;var tLast=field.getZero();var t=field.getOne();// Run Euclidean algorithm until r's degree is less than R/2
while(r.getDegree()>=(R/2|0)){var rLastLast=rLast;var tLastLast=tLast;rLast=r;tLast=t;// Divide rLastLast by rLast, with quotient in q and remainder in r
if(rLast.isZero()){// Oops, Euclidean algorithm already terminated?
throw new ReedSolomonException('r_{i-1} was zero');}r=rLastLast;var q=field.getZero();var denominatorLeadingTerm=rLast.getCoefficient(rLast.getDegree());var dltInverse=field.inverse(denominatorLeadingTerm);while(r.getDegree()>=rLast.getDegree()&&!r.isZero()){var degreeDiff=r.getDegree()-rLast.getDegree();var scale=field.multiply(r.getCoefficient(r.getDegree()),dltInverse);q=q.addOrSubtract(field.buildMonomial(degreeDiff,scale));r=r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff,scale));}t=q.multiply(tLast).addOrSubtract(tLastLast);if(r.getDegree()>=rLast.getDegree()){throw new IllegalStateException('Division algorithm failed to reduce polynomial?');}}var sigmaTildeAtZero=t.getCoefficient(0);if(sigmaTildeAtZero===0){throw new ReedSolomonException('sigmaTilde(0) was zero');}var inverse=field.inverse(sigmaTildeAtZero);var sigma=t.multiplyScalar(inverse);var omega=r.multiplyScalar(inverse);return[sigma,omega];}},{key:"findErrorLocations",value:function findErrorLocations(errorLocator){// This is a direct application of Chien's search
var numErrors=errorLocator.getDegree();if(numErrors===1){// shortcut
return Int32Array.from([errorLocator.getCoefficient(1)]);}var result=new Int32Array(numErrors);var e=0;var field=this.field;for(var i=1;i<field.getSize()&&e<numErrors;i++){if(errorLocator.evaluateAt(i)===0){result[e]=field.inverse(i);e++;}}if(e!==numErrors){throw new ReedSolomonException('Error locator degree does not match number of roots');}return result;}},{key:"findErrorMagnitudes",value:function findErrorMagnitudes(errorEvaluator,errorLocations){// This is directly applying Forney's Formula
var s=errorLocations.length;var result=new Int32Array(s);var field=this.field;for(var i=0;i<s;i++){var xiInverse=field.inverse(errorLocations[i]);var denominator=1;for(var j=0;j<s;j++){if(i!==j){// denominator = field.multiply(denominator,
// GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)))
// Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
// Below is a funny-looking workaround from Steven Parkes
var term=field.multiply(errorLocations[j],xiInverse);var termPlus1=(term&0x1)===0?term|1:term&~1;denominator=field.multiply(denominator,termPlus1);}}result[i]=field.multiply(errorEvaluator.evaluateAt(xiInverse),field.inverse(denominator));if(field.getGeneratorBase()!==0){result[i]=field.multiply(result[i],xiInverse);}}return result;}}]);return ReedSolomonDecoder;}();/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ // import java.util.Arrays;
var Table;(function(Table){Table[Table["UPPER"]=0]="UPPER";Table[Table["LOWER"]=1]="LOWER";Table[Table["MIXED"]=2]="MIXED";Table[Table["DIGIT"]=3]="DIGIT";Table[Table["PUNCT"]=4]="PUNCT";Table[Table["BINARY"]=5]="BINARY";})(Table||(Table={}));/**
* <p>The main class which implements Aztec Code decoding -- as opposed to locating and extracting
* the Aztec Code from an image.</p>
*
* @author David Olivier
*/var Decoder=/*#__PURE__*/function(){function Decoder(){_classCallCheck(this,Decoder);}_createClass(Decoder,[{key:"decode",value:function decode(detectorResult){this.ddata=detectorResult;var matrix=detectorResult.getBits();var rawbits=this.extractBits(matrix);var correctedBits=this.correctBits(rawbits);var rawBytes=Decoder.convertBoolArrayToByteArray(correctedBits);var result=Decoder.getEncodedData(correctedBits);var decoderResult=new DecoderResult(rawBytes,result,null,null);decoderResult.setNumBits(correctedBits.length);return decoderResult;}// This method is used for testing the high-level encoder
},{key:"correctBits",value:/**
* <p>Performs RS error correction on an array of bits.</p>
*
* @return the corrected array
* @throws FormatException if the input contains too many errors
*/function correctBits(rawbits){var gf;var codewordSize;if(this.ddata.getNbLayers()<=2){codewordSize=6;gf=GenericGF.AZTEC_DATA_6;}else if(this.ddata.getNbLayers()<=8){codewordSize=8;gf=GenericGF.AZTEC_DATA_8;}else if(this.ddata.getNbLayers()<=22){codewordSize=10;gf=GenericGF.AZTEC_DATA_10;}else{codewordSize=12;gf=GenericGF.AZTEC_DATA_12;}var numDataCodewords=this.ddata.getNbDatablocks();var numCodewords=rawbits.length/codewordSize;if(numCodewords<numDataCodewords){throw new FormatException();}var offset=rawbits.length%codewordSize;var dataWords=new Int32Array(numCodewords);for(var i=0;i<numCodewords;i++,offset+=codewordSize){dataWords[i]=Decoder.readCode(rawbits,offset,codewordSize);}try{var rsDecoder=new ReedSolomonDecoder(gf);rsDecoder.decode(dataWords,numCodewords-numDataCodewords);}catch(ex){throw new FormatException(ex);}// Now perform the unstuffing operation.
// First, count how many bits are going to be thrown out as stuffing
var mask=(1<<codewordSize)-1;var stuffedBits=0;for(var _i6=0;_i6<numDataCodewords;_i6++){var dataWord=dataWords[_i6];if(dataWord===0||dataWord===mask){throw new FormatException();}else if(dataWord===1||dataWord===mask-1){stuffedBits++;}}// Now, actually unpack the bits and remove the stuffing
var correctedBits=new Array(numDataCodewords*codewordSize-stuffedBits);var index=0;for(var _i7=0;_i7<numDataCodewords;_i7++){var _dataWord=dataWords[_i7];if(_dataWord===1||_dataWord===mask-1){// next codewordSize-1 bits are all zeros or all ones
correctedBits.fill(_dataWord>1,index,index+codewordSize-1);// Arrays.fill(correctedBits, index, index + codewordSize - 1, dataWord > 1);
index+=codewordSize-1;}else{for(var bit=codewordSize-1;bit>=0;--bit){correctedBits[index++]=(_dataWord&1<<bit)!==0;}}}return correctedBits;}/**
* Gets the array of bits from an Aztec Code matrix
*
* @return the array of bits
*/},{key:"extractBits",value:function extractBits(matrix){var compact=this.ddata.isCompact();var layers=this.ddata.getNbLayers();var baseMatrixSize=(compact?11:14)+layers*4;// not including alignment lines
var alignmentMap=new Int32Array(baseMatrixSize);var rawbits=new Array(this.totalBitsInLayer(layers,compact));if(compact){for(var i=0;i<alignmentMap.length;i++){alignmentMap[i]=i;}}else{var matrixSize=baseMatrixSize+1+2*Integer.truncDivision(Integer.truncDivision(baseMatrixSize,2)-1,15);var origCenter=baseMatrixSize/2;var center=Integer.truncDivision(matrixSize,2);for(var _i8=0;_i8<origCenter;_i8++){var newOffset=_i8+Integer.truncDivision(_i8,15);alignmentMap[origCenter-_i8-1]=center-newOffset-1;alignmentMap[origCenter+_i8]=center+newOffset+1;}}for(var _i9=0,rowOffset=0;_i9<layers;_i9++){var rowSize=(layers-_i9)*4+(compact?9:12);// The top-left most point of this layer is <low, low> (not including alignment lines)
var low=_i9*2;// The bottom-right most point of this layer is <high, high> (not including alignment lines)
var high=baseMatrixSize-1-low;// We pull bits from the two 2 x rowSize columns and two rowSize x 2 rows
for(var j=0;j<rowSize;j++){var columnOffset=j*2;for(var k=0;k<2;k++){// left column
rawbits[rowOffset+columnOffset+k]=matrix.get(alignmentMap[low+k],alignmentMap[low+j]);// bottom row
rawbits[rowOffset+2*rowSize+columnOffset+k]=matrix.get(alignmentMap[low+j],alignmentMap[high-k]);// right column
rawbits[rowOffset+4*rowSize+columnOffset+k]=matrix.get(alignmentMap[high-k],alignmentMap[high-j]);// top row
rawbits[rowOffset+6*rowSize+columnOffset+k]=matrix.get(alignmentMap[high-j],alignmentMap[low+k]);}}rowOffset+=rowSize*8;}return rawbits;}/**
* Reads a code of given length and at given index in an array of bits
*/},{key:"totalBitsInLayer",value:function totalBitsInLayer(layers,compact){return((compact?88:112)+16*layers)*layers;}}],[{key:"highLevelDecode",value:function highLevelDecode(correctedBits){return this.getEncodedData(correctedBits);}/**
* Gets the string encoded in the aztec code bits
*
* @return the decoded string
*/},{key:"getEncodedData",value:function getEncodedData(correctedBits){var endIndex=correctedBits.length;var latchTable=Table.UPPER;// table most recently latched to
var shiftTable=Table.UPPER;// table to use for the next read
var result='';var index=0;while(index<endIndex){if(shiftTable===Table.BINARY){if(endIndex-index<5){break;}var length=Decoder.readCode(correctedBits,index,5);index+=5;if(length===0){if(endIndex-index<11){break;}length=Decoder.readCode(correctedBits,index,11)+31;index+=11;}for(var charCount=0;charCount<length;charCount++){if(endIndex-index<8){index=endIndex;// Force outer loop to exit
break;}var code=Decoder.readCode(correctedBits,index,8);result+=/*(char)*/StringUtils.castAsNonUtf8Char(code);index+=8;}// Go back to whatever mode we had been in
shiftTable=latchTable;}else{var size=shiftTable===Table.DIGIT?4:5;if(endIndex-index<size){break;}var _code=Decoder.readCode(correctedBits,index,size);index+=size;var str=Decoder.getCharacter(shiftTable,_code);if(str.startsWith('CTRL_')){// Table changes
// ISO/IEC 24778:2008 prescribes ending a shift sequence in the mode from which it was invoked.
// That's including when that mode is a shift.
// Our test case dlusbs.png for issue #642 exercises that.
latchTable=shiftTable;// Latch the current mode, so as to return to Upper after U/S B/S
shiftTable=Decoder.getTable(str.charAt(5));if(str.charAt(6)==='L'){latchTable=shiftTable;}}else{result+=str;// Go back to whatever mode we had been in
shiftTable=latchTable;}}}return result;}/**
* gets the table corresponding to the char passed
*/},{key:"getTable",value:function getTable(t){switch(t){case'L':return Table.LOWER;case'P':return Table.PUNCT;case'M':return Table.MIXED;case'D':return Table.DIGIT;case'B':return Table.BINARY;case'U':default:return Table.UPPER;}}/**
* Gets the character (or string) corresponding to the passed code in the given table
*
* @param table the table used
* @param code the code of the character
*/},{key:"getCharacter",value:function getCharacter(table,code){switch(table){case Table.UPPER:return Decoder.UPPER_TABLE[code];case Table.LOWER:return Decoder.LOWER_TABLE[code];case Table.MIXED:return Decoder.MIXED_TABLE[code];case Table.PUNCT:return Decoder.PUNCT_TABLE[code];case Table.DIGIT:return Decoder.DIGIT_TABLE[code];default:// Should not reach here.
throw new IllegalStateException('Bad table');}}},{key:"readCode",value:function readCode(rawbits,startIndex,length){var res=0;for(var i=startIndex;i<startIndex+length;i++){res<<=1;if(rawbits[i]){res|=0x01;}}return res;}/**
* Reads a code of length 8 in an array of bits, padding with zeros
*/},{key:"readByte",value:function readByte(rawbits,startIndex){var n=rawbits.length-startIndex;if(n>=8){return Decoder.readCode(rawbits,startIndex,8);}return Decoder.readCode(rawbits,startIndex,n)<<8-n;}/**
* Packs a bit array into bytes, most significant bit first
*/},{key:"convertBoolArrayToByteArray",value:function convertBoolArrayToByteArray(boolArr){var byteArr=new Uint8Array((boolArr.length+7)/8);for(var i=0;i<byteArr.length;i++){byteArr[i]=Decoder.readByte(boolArr,8*i);}return byteArr;}}]);return Decoder;}();Decoder.UPPER_TABLE=['CTRL_PS',' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','CTRL_LL','CTRL_ML','CTRL_DL','CTRL_BS'];Decoder.LOWER_TABLE=['CTRL_PS',' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','CTRL_US','CTRL_ML','CTRL_DL','CTRL_BS'];Decoder.MIXED_TABLE=[// Module parse failed: Octal literal in strict mode (50:29)
// so number string were scaped
'CTRL_PS',' ','\\1','\\2','\\3','\\4','\\5','\\6','\\7','\b','\t','\n','\\13','\f','\r','\\33','\\34','\\35','\\36','\\37','@','\\','^','_','`','|','~','\\177','CTRL_LL','CTRL_UL','CTRL_PL','CTRL_BS'];Decoder.PUNCT_TABLE=['','\r','\r\n','. ',', ',': ','!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/',':',';','<','=','>','?','[',']','{','}','CTRL_UL'];Decoder.DIGIT_TABLE=['CTRL_PS',' ','0','1','2','3','4','5','6','7','8','9',',','.','CTRL_UL','CTRL_US'];/*
* Copyright 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*namespace com.google.zxing.common.detector {*/ /**
* General math-related and numeric utility functions.
*/var MathUtils=/*#__PURE__*/function(){function MathUtils(){_classCallCheck(this,MathUtils);}/**
* Ends up being a bit faster than {@link Math#round(float)}. This merely rounds its
* argument to the nearest int, where x.5 rounds up to x+1. Semantics of this shortcut
* differ slightly from {@link Math#round(float)} in that half rounds down for negative
* values. -2.5 rounds to -3, not -2. For purposes here it makes no difference.
*
* @param d real value to round
* @return nearest {@code int}
*/_createClass(MathUtils,null,[{key:"round",value:function round(d/*float*/){if(NaN===d)return 0;if(d<=Number.MIN_SAFE_INTEGER)return Number.MIN_SAFE_INTEGER;if(d>=Number.MAX_SAFE_INTEGER)return Number.MAX_SAFE_INTEGER;return(/*(int) */d+(d<0.0?-0.5:0.5)|0);}// TYPESCRIPTPORT: maybe remove round method and call directly Math.round, it looks like it doesn't make sense for js
/**
* @param aX point A x coordinate
* @param aY point A y coordinate
* @param bX point B x coordinate
* @param bY point B y coordinate
* @return Euclidean distance between points A and B
*/},{key:"distance",value:function distance(aX/*float|int*/,aY/*float|int*/,bX/*float|int*/,bY/*float|int*/){var xDiff=aX-bX;var yDiff=aY-bY;return(/*(float) */Math.sqrt(xDiff*xDiff+yDiff*yDiff));}/**
* @param aX point A x coordinate
* @param aY point A y coordinate
* @param bX point B x coordinate
* @param bY point B y coordinate
* @return Euclidean distance between points A and B
*/ // public static distance(aX: number /*int*/, aY: number /*int*/, bX: number /*int*/, bY: number /*int*/): float {
// const xDiff = aX - bX
// const yDiff = aY - bY
// return (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff);
// }
/**
* @param array values to sum
* @return sum of values in array
*/},{key:"sum",value:function sum(array){var count=0;for(var i=0,length=array.length;i!==length;i++){var a=array[i];count+=a;}return count;}}]);return MathUtils;}();/**
* Ponyfill for Java's Float class.
*/var Float=/*#__PURE__*/function(){function Float(){_classCallCheck(this,Float);}_createClass(Float,null,[{key:"floatToIntBits",value:/**
* SincTS has no difference between int and float, there's all numbers,
* this is used only to polyfill Java code.
*/function floatToIntBits(f){return f;}}]);return Float;}();/**
* The float max value in JS is the number max value.
*/Float.MAX_VALUE=Number.MAX_SAFE_INTEGER;/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Encapsulates a point of interest in an image containing a barcode. Typically, this
* would be the location of a finder pattern or the corner of the barcode, for example.</p>
*
* @author Sean Owen
*/var ResultPoint=/*#__PURE__*/function(){function ResultPoint(x,y){_classCallCheck(this,ResultPoint);this.x=x;this.y=y;}_createClass(ResultPoint,[{key:"getX",value:function getX(){return this.x;}},{key:"getY",value:function getY(){return this.y;}/*@Override*/},{key:"equals",value:function equals(other){if(other instanceof ResultPoint){var otherPoint=other;return this.x===otherPoint.x&&this.y===otherPoint.y;}return false;}/*@Override*/},{key:"hashCode",value:function hashCode(){return 31*Float.floatToIntBits(this.x)+Float.floatToIntBits(this.y);}/*@Override*/},{key:"toString",value:function toString(){return'('+this.x+','+this.y+')';}/**
* Orders an array of three ResultPoints in an order [A,B,C] such that AB is less than AC
* and BC is less than AC, and the angle between BC and BA is less than 180 degrees.
*
* @param patterns array of three {@code ResultPoint} to order
*/}],[{key:"orderBestPatterns",value:function orderBestPatterns(patterns){// Find distances between pattern centers
var zeroOneDistance=this.distance(patterns[0],patterns[1]);var oneTwoDistance=this.distance(patterns[1],patterns[2]);var zeroTwoDistance=this.distance(patterns[0],patterns[2]);var pointA;var pointB;var pointC;// Assume one closest to other two is B; A and C will just be guesses at first
if(oneTwoDistance>=zeroOneDistance&&oneTwoDistance>=zeroTwoDistance){pointB=patterns[0];pointA=patterns[1];pointC=patterns[2];}else if(zeroTwoDistance>=oneTwoDistance&&zeroTwoDistance>=zeroOneDistance){pointB=patterns[1];pointA=patterns[0];pointC=patterns[2];}else{pointB=patterns[2];pointA=patterns[0];pointC=patterns[1];}// Use cross product to figure out whether A and C are correct or flipped.
// This asks whether BC x BA has a positive z component, which is the arrangement
// we want for A, B, C. If it's negative, then we've got it flipped around and
// should swap A and C.
if(this.crossProductZ(pointA,pointB,pointC)<0.0){var temp=pointA;pointA=pointC;pointC=temp;}patterns[0]=pointA;patterns[1]=pointB;patterns[2]=pointC;}/**
* @param pattern1 first pattern
* @param pattern2 second pattern
* @return distance between two points
*/},{key:"distance",value:function distance(pattern1,pattern2){return MathUtils.distance(pattern1.x,pattern1.y,pattern2.x,pattern2.y);}/**
* Returns the z component of the cross product between vectors BC and BA.
*/},{key:"crossProductZ",value:function crossProductZ(pointA,pointB,pointC){var bX=pointB.x;var bY=pointB.y;return(pointC.x-bX)*(pointA.y-bY)-(pointC.y-bY)*(pointA.x-bX);}}]);return ResultPoint;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Encapsulates the result of detecting a barcode in an image. This includes the raw
* matrix of black/white pixels corresponding to the barcode, and possibly points of interest
* in the image, like the location of finder patterns or corners of the barcode in the image.</p>
*
* @author Sean Owen
*/var DetectorResult=/*#__PURE__*/function(){function DetectorResult(bits,points){_classCallCheck(this,DetectorResult);this.bits=bits;this.points=points;}_createClass(DetectorResult,[{key:"getBits",value:function getBits(){return this.bits;}},{key:"getPoints",value:function getPoints(){return this.points;}}]);return DetectorResult;}();/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Extends {@link DetectorResult} with more information specific to the Aztec format,
* like the number of layers and whether it's compact.</p>
*
* @author Sean Owen
*/var AztecDetectorResult=/*#__PURE__*/function(_DetectorResult){_inherits(AztecDetectorResult,_DetectorResult);var _super19=_createSuper(AztecDetectorResult);function AztecDetectorResult(bits,points,compact,nbDatablocks,nbLayers){var _this14;_classCallCheck(this,AztecDetectorResult);_this14=_super19.call(this,bits,points);_this14.compact=compact;_this14.nbDatablocks=nbDatablocks;_this14.nbLayers=nbLayers;return _this14;}_createClass(AztecDetectorResult,[{key:"getNbLayers",value:function getNbLayers(){return this.nbLayers;}},{key:"getNbDatablocks",value:function getNbDatablocks(){return this.nbDatablocks;}},{key:"isCompact",value:function isCompact(){return this.compact;}}]);return AztecDetectorResult;}(DetectorResult);/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>
* Detects a candidate barcode-like rectangular region within an image. It
* starts around the center of the image, increases the size of the candidate
* region until it finds a white rectangular region. By keeping track of the
* last black points it encountered, it determines the corners of the barcode.
* </p>
*
* @author David Olivier
*/var WhiteRectangleDetector=/*#__PURE__*/function(){// public constructor(private image: BitMatrix) /*throws NotFoundException*/ {
// this(image, INIT_SIZE, image.getWidth() / 2, image.getHeight() / 2)
// }
/**
* @param image barcode image to find a rectangle in
* @param initSize initial size of search area around center
* @param x x position of search center
* @param y y position of search center
* @throws NotFoundException if image is too small to accommodate {@code initSize}
*/function WhiteRectangleDetector(image,initSize/*int*/,x/*int*/,y/*int*/){_classCallCheck(this,WhiteRectangleDetector);this.image=image;this.height=image.getHeight();this.width=image.getWidth();if(undefined===initSize||null===initSize){initSize=WhiteRectangleDetector.INIT_SIZE;}if(undefined===x||null===x){x=image.getWidth()/2|0;}if(undefined===y||null===y){y=image.getHeight()/2|0;}var halfsize=initSize/2|0;this.leftInit=x-halfsize;this.rightInit=x+halfsize;this.upInit=y-halfsize;this.downInit=y+halfsize;if(this.upInit<0||this.leftInit<0||this.downInit>=this.height||this.rightInit>=this.width){throw new NotFoundException();}}/**
* <p>
* Detects a candidate barcode-like rectangular region within an image. It
* starts around the center of the image, increases the size of the candidate
* region until it finds a white rectangular region.
* </p>
*
* @return {@link ResultPoint}[] describing the corners of the rectangular
* region. The first and last points are opposed on the diagonal, as
* are the second and third. The first point will be the topmost
* point and the last, the bottommost. The second point will be
* leftmost and the third, the rightmost
* @throws NotFoundException if no Data Matrix Code can be found
*/_createClass(WhiteRectangleDetector,[{key:"detect",value:function detect(){var left=this.leftInit;var right=this.rightInit;var up=this.upInit;var down=this.downInit;var sizeExceeded=false;var aBlackPointFoundOnBorder=true;var atLeastOneBlackPointFoundOnBorder=false;var atLeastOneBlackPointFoundOnRight=false;var atLeastOneBlackPointFoundOnBottom=false;var atLeastOneBlackPointFoundOnLeft=false;var atLeastOneBlackPointFoundOnTop=false;var width=this.width;var height=this.height;while(aBlackPointFoundOnBorder){aBlackPointFoundOnBorder=false;// .....
// . |
// .....
var rightBorderNotWhite=true;while((rightBorderNotWhite||!atLeastOneBlackPointFoundOnRight)&&right<width){rightBorderNotWhite=this.containsBlackPoint(up,down,right,false);if(rightBorderNotWhite){right++;aBlackPointFoundOnBorder=true;atLeastOneBlackPointFoundOnRight=true;}else if(!atLeastOneBlackPointFoundOnRight){right++;}}if(right>=width){sizeExceeded=true;break;}// .....
// . .
// .___.
var bottomBorderNotWhite=true;while((bottomBorderNotWhite||!atLeastOneBlackPointFoundOnBottom)&&down<height){bottomBorderNotWhite=this.containsBlackPoint(left,right,down,true);if(bottomBorderNotWhite){down++;aBlackPointFoundOnBorder=true;atLeastOneBlackPointFoundOnBottom=true;}else if(!atLeastOneBlackPointFoundOnBottom){down++;}}if(down>=height){sizeExceeded=true;break;}// .....
// | .
// .....
var leftBorderNotWhite=true;while((leftBorderNotWhite||!atLeastOneBlackPointFoundOnLeft)&&left>=0){leftBorderNotWhite=this.containsBlackPoint(up,down,left,false);if(leftBorderNotWhite){left--;aBlackPointFoundOnBorder=true;atLeastOneBlackPointFoundOnLeft=true;}else if(!atLeastOneBlackPointFoundOnLeft){left--;}}if(left<0){sizeExceeded=true;break;}// .___.
// . .
// .....
var topBorderNotWhite=true;while((topBorderNotWhite||!atLeastOneBlackPointFoundOnTop)&&up>=0){topBorderNotWhite=this.containsBlackPoint(left,right,up,true);if(topBorderNotWhite){up--;aBlackPointFoundOnBorder=true;atLeastOneBlackPointFoundOnTop=true;}else if(!atLeastOneBlackPointFoundOnTop){up--;}}if(up<0){sizeExceeded=true;break;}if(aBlackPointFoundOnBorder){atLeastOneBlackPointFoundOnBorder=true;}}if(!sizeExceeded&&atLeastOneBlackPointFoundOnBorder){var maxSize=right-left;var z=null;for(var i=1;z===null&&i<maxSize;i++){z=this.getBlackPointOnSegment(left,down-i,left+i,down);}if(z==null){throw new NotFoundException();}var t=null;// go down right
for(var _i10=1;t===null&&_i10<maxSize;_i10++){t=this.getBlackPointOnSegment(left,up+_i10,left+_i10,up);}if(t==null){throw new NotFoundException();}var x=null;// go down left
for(var _i11=1;x===null&&_i11<maxSize;_i11++){x=this.getBlackPointOnSegment(right,up+_i11,right-_i11,up);}if(x==null){throw new NotFoundException();}var y=null;// go up left
for(var _i12=1;y===null&&_i12<maxSize;_i12++){y=this.getBlackPointOnSegment(right,down-_i12,right-_i12,down);}if(y==null){throw new NotFoundException();}return this.centerEdges(y,z,x,t);}else{throw new NotFoundException();}}},{key:"getBlackPointOnSegment",value:function getBlackPointOnSegment(aX/*float*/,aY/*float*/,bX/*float*/,bY/*float*/){var dist=MathUtils.round(MathUtils.distance(aX,aY,bX,bY));var xStep=(bX-aX)/dist;var yStep=(bY-aY)/dist;var image=this.image;for(var i=0;i<dist;i++){var x=MathUtils.round(aX+i*xStep);var y=MathUtils.round(aY+i*yStep);if(image.get(x,y)){return new ResultPoint(x,y);}}return null;}/**
* recenters the points of a constant distance towards the center
*
* @param y bottom most point
* @param z left most point
* @param x right most point
* @param t top most point
* @return {@link ResultPoint}[] describing the corners of the rectangular
* region. The first and last points are opposed on the diagonal, as
* are the second and third. The first point will be the topmost
* point and the last, the bottommost. The second point will be
* leftmost and the third, the rightmost
*/},{key:"centerEdges",value:function centerEdges(y,z,x,t){//
// t t
// z x
// x OR z
// y y
//
var yi=y.getX();var yj=y.getY();var zi=z.getX();var zj=z.getY();var xi=x.getX();var xj=x.getY();var ti=t.getX();var tj=t.getY();var CORR=WhiteRectangleDetector.CORR;if(yi<this.width/2.0){return[new ResultPoint(ti-CORR,tj+CORR),new ResultPoint(zi+CORR,zj+CORR),new ResultPoint(xi-CORR,xj-CORR),new ResultPoint(yi+CORR,yj-CORR)];}else{return[new ResultPoint(ti+CORR,tj+CORR),new ResultPoint(zi+CORR,zj-CORR),new ResultPoint(xi-CORR,xj+CORR),new ResultPoint(yi-CORR,yj-CORR)];}}/**
* Determines whether a segment contains a black point
*
* @param a min value of the scanned coordinate
* @param b max value of the scanned coordinate
* @param fixed value of fixed coordinate
* @param horizontal set to true if scan must be horizontal, false if vertical
* @return true if a black point has been found, else false.
*/},{key:"containsBlackPoint",value:function containsBlackPoint(a/*int*/,b/*int*/,fixed/*int*/,horizontal){var image=this.image;if(horizontal){for(var x=a;x<=b;x++){if(image.get(x,fixed)){return true;}}}else{for(var y=a;y<=b;y++){if(image.get(fixed,y)){return true;}}}return false;}}]);return WhiteRectangleDetector;}();WhiteRectangleDetector.INIT_SIZE=10;WhiteRectangleDetector.CORR=1;/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* Implementations of this class can, given locations of finder patterns for a QR code in an
* image, sample the right points in the image to reconstruct the QR code, accounting for
* perspective distortion. It is abstracted since it is relatively expensive and should be allowed
* to take advantage of platform-specific optimized implementations, like Sun's Java Advanced
* Imaging library, but which may not be available in other environments such as J2ME, and vice
* versa.
*
* The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)}
* with an instance of a class which implements this interface.
*
* @author Sean Owen
*/var GridSampler=/*#__PURE__*/function(){function GridSampler(){_classCallCheck(this,GridSampler);}_createClass(GridSampler,null,[{key:"checkAndNudgePoints",value:/**
* <p>Checks a set of points that have been transformed to sample points on an image against
* the image's dimensions to see if the point are even within the image.</p>
*
* <p>This method will actually "nudge" the endpoints back onto the image if they are found to be
* barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder
* patterns in an image where the QR Code runs all the way to the image border.</p>
*
* <p>For efficiency, the method will check points from either end of the line until one is found
* to be within the image. Because the set of points are assumed to be linear, this is valid.</p>
*
* @param image image into which the points should map
* @param points actual points in x1,y1,...,xn,yn form
* @throws NotFoundException if an endpoint is lies outside the image boundaries
*/function checkAndNudgePoints(image,points){var width=image.getWidth();var height=image.getHeight();// Check and nudge points from start until we see some that are OK:
var nudged=true;for(var offset=0;offset<points.length&&nudged;offset+=2){var x=Math.floor(points[offset]);var y=Math.floor(points[offset+1]);if(x<-1||x>width||y<-1||y>height){throw new NotFoundException();}nudged=false;if(x===-1){points[offset]=0.0;nudged=true;}else if(x===width){points[offset]=width-1;nudged=true;}if(y===-1){points[offset+1]=0.0;nudged=true;}else if(y===height){points[offset+1]=height-1;nudged=true;}}// Check and nudge points from end:
nudged=true;for(var _offset=points.length-2;_offset>=0&&nudged;_offset-=2){var _x7=Math.floor(points[_offset]);var _y2=Math.floor(points[_offset+1]);if(_x7<-1||_x7>width||_y2<-1||_y2>height){throw new NotFoundException();}nudged=false;if(_x7===-1){points[_offset]=0.0;nudged=true;}else if(_x7===width){points[_offset]=width-1;nudged=true;}if(_y2===-1){points[_offset+1]=0.0;nudged=true;}else if(_y2===height){points[_offset+1]=height-1;nudged=true;}}}}]);return GridSampler;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*namespace com.google.zxing.common {*/ /**
* <p>This class implements a perspective transform in two dimensions. Given four source and four
* destination points, it will compute the transformation implied between them. The code is based
* directly upon section 3.4.2 of George Wolberg's "Digital Image Warping"; see pages 54-56.</p>
*
* @author Sean Owen
*/var PerspectiveTransform=/*#__PURE__*/function(){function PerspectiveTransform(a11/*float*/,a21/*float*/,a31/*float*/,a12/*float*/,a22/*float*/,a32/*float*/,a13/*float*/,a23/*float*/,a33/*float*/){_classCallCheck(this,PerspectiveTransform);this.a11=a11;this.a21=a21;this.a31=a31;this.a12=a12;this.a22=a22;this.a32=a32;this.a13=a13;this.a23=a23;this.a33=a33;}_createClass(PerspectiveTransform,[{key:"transformPoints",value:function transformPoints(points){var max=points.length;var a11=this.a11;var a12=this.a12;var a13=this.a13;var a21=this.a21;var a22=this.a22;var a23=this.a23;var a31=this.a31;var a32=this.a32;var a33=this.a33;for(var i=0;i<max;i+=2){var x=points[i];var y=points[i+1];var denominator=a13*x+a23*y+a33;points[i]=(a11*x+a21*y+a31)/denominator;points[i+1]=(a12*x+a22*y+a32)/denominator;}}},{key:"transformPointsWithValues",value:function transformPointsWithValues(xValues,yValues){var a11=this.a11;var a12=this.a12;var a13=this.a13;var a21=this.a21;var a22=this.a22;var a23=this.a23;var a31=this.a31;var a32=this.a32;var a33=this.a33;var n=xValues.length;for(var i=0;i<n;i++){var x=xValues[i];var y=yValues[i];var denominator=a13*x+a23*y+a33;xValues[i]=(a11*x+a21*y+a31)/denominator;yValues[i]=(a12*x+a22*y+a32)/denominator;}}},{key:"buildAdjoint",value:function buildAdjoint(){// Adjoint is the transpose of the cofactor matrix:
return new PerspectiveTransform(this.a22*this.a33-this.a23*this.a32,this.a23*this.a31-this.a21*this.a33,this.a21*this.a32-this.a22*this.a31,this.a13*this.a32-this.a12*this.a33,this.a11*this.a33-this.a13*this.a31,this.a12*this.a31-this.a11*this.a32,this.a12*this.a23-this.a13*this.a22,this.a13*this.a21-this.a11*this.a23,this.a11*this.a22-this.a12*this.a21);}},{key:"times",value:function times(other){return new PerspectiveTransform(this.a11*other.a11+this.a21*other.a12+this.a31*other.a13,this.a11*other.a21+this.a21*other.a22+this.a31*other.a23,this.a11*other.a31+this.a21*other.a32+this.a31*other.a33,this.a12*other.a11+this.a22*other.a12+this.a32*other.a13,this.a12*other.a21+this.a22*other.a22+this.a32*other.a23,this.a12*other.a31+this.a22*other.a32+this.a32*other.a33,this.a13*other.a11+this.a23*other.a12+this.a33*other.a13,this.a13*other.a21+this.a23*other.a22+this.a33*other.a23,this.a13*other.a31+this.a23*other.a32+this.a33*other.a33);}}],[{key:"quadrilateralToQuadrilateral",value:function quadrilateralToQuadrilateral(x0/*float*/,y0/*float*/,x1/*float*/,y1/*float*/,x2/*float*/,y2/*float*/,x3/*float*/,y3/*float*/,x0p/*float*/,y0p/*float*/,x1p/*float*/,y1p/*float*/,x2p/*float*/,y2p/*float*/,x3p/*float*/,y3p/*float*/){var qToS=PerspectiveTransform.quadrilateralToSquare(x0,y0,x1,y1,x2,y2,x3,y3);var sToQ=PerspectiveTransform.squareToQuadrilateral(x0p,y0p,x1p,y1p,x2p,y2p,x3p,y3p);return sToQ.times(qToS);}},{key:"squareToQuadrilateral",value:function squareToQuadrilateral(x0/*float*/,y0/*float*/,x1/*float*/,y1/*float*/,x2/*float*/,y2/*float*/,x3/*float*/,y3/*float*/){var dx3=x0-x1+x2-x3;var dy3=y0-y1+y2-y3;if(dx3===0.0&&dy3===0.0){// Affine
return new PerspectiveTransform(x1-x0,x2-x1,x0,y1-y0,y2-y1,y0,0.0,0.0,1.0);}else{var dx1=x1-x2;var dx2=x3-x2;var dy1=y1-y2;var dy2=y3-y2;var denominator=dx1*dy2-dx2*dy1;var a13=(dx3*dy2-dx2*dy3)/denominator;var a23=(dx1*dy3-dx3*dy1)/denominator;return new PerspectiveTransform(x1-x0+a13*x1,x3-x0+a23*x3,x0,y1-y0+a13*y1,y3-y0+a23*y3,y0,a13,a23,1.0);}}},{key:"quadrilateralToSquare",value:function quadrilateralToSquare(x0/*float*/,y0/*float*/,x1/*float*/,y1/*float*/,x2/*float*/,y2/*float*/,x3/*float*/,y3/*float*/){// Here, the adjoint serves as the inverse:
return PerspectiveTransform.squareToQuadrilateral(x0,y0,x1,y1,x2,y2,x3,y3).buildAdjoint();}}]);return PerspectiveTransform;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* @author Sean Owen
*/var DefaultGridSampler=/*#__PURE__*/function(_GridSampler){_inherits(DefaultGridSampler,_GridSampler);var _super20=_createSuper(DefaultGridSampler);function DefaultGridSampler(){_classCallCheck(this,DefaultGridSampler);return _super20.apply(this,arguments);}_createClass(DefaultGridSampler,[{key:"sampleGrid",value:/*@Override*/function sampleGrid(image,dimensionX/*int*/,dimensionY/*int*/,p1ToX/*float*/,p1ToY/*float*/,p2ToX/*float*/,p2ToY/*float*/,p3ToX/*float*/,p3ToY/*float*/,p4ToX/*float*/,p4ToY/*float*/,p1FromX/*float*/,p1FromY/*float*/,p2FromX/*float*/,p2FromY/*float*/,p3FromX/*float*/,p3FromY/*float*/,p4FromX/*float*/,p4FromY/*float*/){var transform=PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX,p1ToY,p2ToX,p2ToY,p3ToX,p3ToY,p4ToX,p4ToY,p1FromX,p1FromY,p2FromX,p2FromY,p3FromX,p3FromY,p4FromX,p4FromY);return this.sampleGridWithTransform(image,dimensionX,dimensionY,transform);}/*@Override*/},{key:"sampleGridWithTransform",value:function sampleGridWithTransform(image,dimensionX/*int*/,dimensionY/*int*/,transform){if(dimensionX<=0||dimensionY<=0){throw new NotFoundException();}var bits=new BitMatrix(dimensionX,dimensionY);var points=new Float32Array(2*dimensionX);for(var y=0;y<dimensionY;y++){var max=points.length;var iValue=y+0.5;for(var x=0;x<max;x+=2){points[x]=x/2+0.5;points[x+1]=iValue;}transform.transformPoints(points);// Quick check to see if points transformed to something inside the image
// sufficient to check the endpoints
GridSampler.checkAndNudgePoints(image,points);try{for(var _x8=0;_x8<max;_x8+=2){if(image.get(Math.floor(points[_x8]),Math.floor(points[_x8+1]))){// Black(-ish) pixel
bits.set(_x8/2,y);}}}catch(aioobe/*: ArrayIndexOutOfBoundsException*/){// This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
// transform gets "twisted" such that it maps a straight line of points to a set of points
// whose endpoints are in bounds, but others are not. There is probably some mathematical
// way to detect this about the transformation that I don't know yet.
// This results in an ugly runtime exception despite our clever checks above -- can't have
// that. We could check each point's coordinates but that feels duplicative. We settle for
// catching and wrapping ArrayIndexOutOfBoundsException.
throw new NotFoundException();}}return bits;}}]);return DefaultGridSampler;}(GridSampler);var GridSamplerInstance=/*#__PURE__*/function(){function GridSamplerInstance(){_classCallCheck(this,GridSamplerInstance);}_createClass(GridSamplerInstance,null,[{key:"setGridSampler",value:/**
* Sets the implementation of GridSampler used by the library. One global
* instance is stored, which may sound problematic. But, the implementation provided
* ought to be appropriate for the entire platform, and all uses of this library
* in the whole lifetime of the JVM. For instance, an Android activity can swap in
* an implementation that takes advantage of native platform libraries.
*
* @param newGridSampler The platform-specific object to install.
*/function setGridSampler(newGridSampler){GridSamplerInstance.gridSampler=newGridSampler;}/**
* @return the current implementation of GridSampler
*/},{key:"getInstance",value:function getInstance(){return GridSamplerInstance.gridSampler;}}]);return GridSamplerInstance;}();GridSamplerInstance.gridSampler=new DefaultGridSampler();/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/var Point=/*#__PURE__*/function(){function Point(x,y){_classCallCheck(this,Point);this.x=x;this.y=y;}_createClass(Point,[{key:"toResultPoint",value:function toResultPoint(){return new ResultPoint(this.getX(),this.getY());}},{key:"getX",value:function getX(){return this.x;}},{key:"getY",value:function getY(){return this.y;}}]);return Point;}();/**
* Encapsulates logic that can detect an Aztec Code in an image, even if the Aztec Code
* is rotated or skewed, or partially obscured.
*
* @author David Olivier
* @author Frank Yellin
*/var Detector=/*#__PURE__*/function(){function Detector(image){_classCallCheck(this,Detector);this.EXPECTED_CORNER_BITS=new Int32Array([0xee0,0x1dc,0x83b,0x707]);this.image=image;}_createClass(Detector,[{key:"detect",value:function detect(){return this.detectMirror(false);}/**
* Detects an Aztec Code in an image.
*
* @param isMirror if true, image is a mirror-image of original
* @return {@link AztecDetectorResult} encapsulating results of detecting an Aztec Code
* @throws NotFoundException if no Aztec Code can be found
*/},{key:"detectMirror",value:function detectMirror(isMirror){// 1. Get the center of the aztec matrix
var pCenter=this.getMatrixCenter();// 2. Get the center points of the four diagonal points just outside the bull's eye
// [topRight, bottomRight, bottomLeft, topLeft]
var bullsEyeCorners=this.getBullsEyeCorners(pCenter);if(isMirror){var temp=bullsEyeCorners[0];bullsEyeCorners[0]=bullsEyeCorners[2];bullsEyeCorners[2]=temp;}// 3. Get the size of the matrix and other parameters from the bull's eye
this.extractParameters(bullsEyeCorners);// 4. Sample the grid
var bits=this.sampleGrid(this.image,bullsEyeCorners[this.shift%4],bullsEyeCorners[(this.shift+1)%4],bullsEyeCorners[(this.shift+2)%4],bullsEyeCorners[(this.shift+3)%4]);// 5. Get the corners of the matrix.
var corners=this.getMatrixCornerPoints(bullsEyeCorners);return new AztecDetectorResult(bits,corners,this.compact,this.nbDataBlocks,this.nbLayers);}/**
* Extracts the number of data layers and data blocks from the layer around the bull's eye.
*
* @param bullsEyeCorners the array of bull's eye corners
* @throws NotFoundException in case of too many errors or invalid parameters
*/},{key:"extractParameters",value:function extractParameters(bullsEyeCorners){if(!this.isValidPoint(bullsEyeCorners[0])||!this.isValidPoint(bullsEyeCorners[1])||!this.isValidPoint(bullsEyeCorners[2])||!this.isValidPoint(bullsEyeCorners[3])){throw new NotFoundException();}var length=2*this.nbCenterLayers;// Get the bits around the bull's eye
var sides=new Int32Array([this.sampleLine(bullsEyeCorners[0],bullsEyeCorners[1],length),this.sampleLine(bullsEyeCorners[1],bullsEyeCorners[2],length),this.sampleLine(bullsEyeCorners[2],bullsEyeCorners[3],length),this.sampleLine(bullsEyeCorners[3],bullsEyeCorners[0],length)// Top
]);// bullsEyeCorners[shift] is the corner of the bulls'eye that has three
// orientation marks.
// sides[shift] is the row/column that goes from the corner with three
// orientation marks to the corner with two.
this.shift=this.getRotation(sides,length);// Flatten the parameter bits into a single 28- or 40-bit long
var parameterData=0;for(var i=0;i<4;i++){var side=sides[(this.shift+i)%4];if(this.compact){// Each side of the form ..XXXXXXX. where Xs are parameter data
parameterData<<=7;parameterData+=side>>1&0x7F;}else{// Each side of the form ..XXXXX.XXXXX. where Xs are parameter data
parameterData<<=10;parameterData+=(side>>2&0x1f<<5)+(side>>1&0x1F);}}// Corrects parameter data using RS. Returns just the data portion
// without the error correction.
var correctedData=this.getCorrectedParameterData(parameterData,this.compact);if(this.compact){// 8 bits: 2 bits layers and 6 bits data blocks
this.nbLayers=(correctedData>>6)+1;this.nbDataBlocks=(correctedData&0x3F)+1;}else{// 16 bits: 5 bits layers and 11 bits data blocks
this.nbLayers=(correctedData>>11)+1;this.nbDataBlocks=(correctedData&0x7FF)+1;}}},{key:"getRotation",value:function getRotation(sides,length){// In a normal pattern, we expect to See
// ** .* D A
// * *
//
// . *
// .. .. C B
//
// Grab the 3 bits from each of the sides the form the locator pattern and concatenate
// into a 12-bit integer. Start with the bit at A
var cornerBits=0;sides.forEach(function(side,idx,arr){// XX......X where X's are orientation marks
var t=(side>>length-2<<1)+(side&1);cornerBits=(cornerBits<<3)+t;});// for (var side in sides) {
// // XX......X where X's are orientation marks
// var t = ((side >> (length - 2)) << 1) + (side & 1);
// cornerBits = (cornerBits << 3) + t;
// }
// Mov the bottom bit to the top, so that the three bits of the locator pattern at A are
// together. cornerBits is now:
// 3 orientation bits at A || 3 orientation bits at B || ... || 3 orientation bits at D
cornerBits=((cornerBits&1)<<11)+(cornerBits>>1);// The result shift indicates which element of BullsEyeCorners[] goes into the top-left
// corner. Since the four rotation values have a Hamming distance of 8, we
// can easily tolerate two errors.
for(var shift=0;shift<4;shift++){if(Integer.bitCount(cornerBits^this.EXPECTED_CORNER_BITS[shift])<=2){return shift;}}throw new NotFoundException();}/**
* Corrects the parameter bits using Reed-Solomon algorithm.
*
* @param parameterData parameter bits
* @param compact true if this is a compact Aztec code
* @throws NotFoundException if the array contains too many errors
*/},{key:"getCorrectedParameterData",value:function getCorrectedParameterData(parameterData,compact){var numCodewords;var numDataCodewords;if(compact){numCodewords=7;numDataCodewords=2;}else{numCodewords=10;numDataCodewords=4;}var numECCodewords=numCodewords-numDataCodewords;var parameterWords=new Int32Array(numCodewords);for(var i=numCodewords-1;i>=0;--i){parameterWords[i]=parameterData&0xF;parameterData>>=4;}try{var rsDecoder=new ReedSolomonDecoder(GenericGF.AZTEC_PARAM);rsDecoder.decode(parameterWords,numECCodewords);}catch(ignored){throw new NotFoundException();}// Toss the error correction. Just return the data as an integer
var result=0;for(var _i13=0;_i13<numDataCodewords;_i13++){result=(result<<4)+parameterWords[_i13];}return result;}/**
* Finds the corners of a bull-eye centered on the passed point.
* This returns the centers of the diagonal points just outside the bull's eye
* Returns [topRight, bottomRight, bottomLeft, topLeft]
*
* @param pCenter Center point
* @return The corners of the bull-eye
* @throws NotFoundException If no valid bull-eye can be found
*/},{key:"getBullsEyeCorners",value:function getBullsEyeCorners(pCenter){var pina=pCenter;var pinb=pCenter;var pinc=pCenter;var pind=pCenter;var color=true;for(this.nbCenterLayers=1;this.nbCenterLayers<9;this.nbCenterLayers++){var pouta=this.getFirstDifferent(pina,color,1,-1);var poutb=this.getFirstDifferent(pinb,color,1,1);var poutc=this.getFirstDifferent(pinc,color,-1,1);var poutd=this.getFirstDifferent(pind,color,-1,-1);// d a
//
// c b
if(this.nbCenterLayers>2){var q=this.distancePoint(poutd,pouta)*this.nbCenterLayers/(this.distancePoint(pind,pina)*(this.nbCenterLayers+2));if(q<0.75||q>1.25||!this.isWhiteOrBlackRectangle(pouta,poutb,poutc,poutd)){break;}}pina=pouta;pinb=poutb;pinc=poutc;pind=poutd;color=!color;}if(this.nbCenterLayers!==5&&this.nbCenterLayers!==7){throw new NotFoundException();}this.compact=this.nbCenterLayers===5;// Expand the square by .5 pixel in each direction so that we're on the border
// between the white square and the black square
var pinax=new ResultPoint(pina.getX()+0.5,pina.getY()-0.5);var pinbx=new ResultPoint(pinb.getX()+0.5,pinb.getY()+0.5);var pincx=new ResultPoint(pinc.getX()-0.5,pinc.getY()+0.5);var pindx=new ResultPoint(pind.getX()-0.5,pind.getY()-0.5);// Expand the square so that its corners are the centers of the points
// just outside the bull's eye.
return this.expandSquare([pinax,pinbx,pincx,pindx],2*this.nbCenterLayers-3,2*this.nbCenterLayers);}/**
* Finds a candidate center point of an Aztec code from an image
*
* @return the center point
*/},{key:"getMatrixCenter",value:function getMatrixCenter(){var pointA;var pointB;var pointC;var pointD;// Get a white rectangle that can be the border of the matrix in center bull's eye or
try{var cornerPoints=new WhiteRectangleDetector(this.image).detect();pointA=cornerPoints[0];pointB=cornerPoints[1];pointC=cornerPoints[2];pointD=cornerPoints[3];}catch(e){// This exception can be in case the initial rectangle is white
// In that case, surely in the bull's eye, we try to expand the rectangle.
var _cx=this.image.getWidth()/2;var _cy=this.image.getHeight()/2;pointA=this.getFirstDifferent(new Point(_cx+7,_cy-7),false,1,-1).toResultPoint();pointB=this.getFirstDifferent(new Point(_cx+7,_cy+7),false,1,1).toResultPoint();pointC=this.getFirstDifferent(new Point(_cx-7,_cy+7),false,-1,1).toResultPoint();pointD=this.getFirstDifferent(new Point(_cx-7,_cy-7),false,-1,-1).toResultPoint();}// Compute the center of the rectangle
var cx=MathUtils.round((pointA.getX()+pointD.getX()+pointB.getX()+pointC.getX())/4.0);var cy=MathUtils.round((pointA.getY()+pointD.getY()+pointB.getY()+pointC.getY())/4.0);// Redetermine the white rectangle starting from previously computed center.
// This will ensure that we end up with a white rectangle in center bull's eye
// in order to compute a more accurate center.
try{var _cornerPoints=new WhiteRectangleDetector(this.image,15,cx,cy).detect();pointA=_cornerPoints[0];pointB=_cornerPoints[1];pointC=_cornerPoints[2];pointD=_cornerPoints[3];}catch(e){// This exception can be in case the initial rectangle is white
// In that case we try to expand the rectangle.
pointA=this.getFirstDifferent(new Point(cx+7,cy-7),false,1,-1).toResultPoint();pointB=this.getFirstDifferent(new Point(cx+7,cy+7),false,1,1).toResultPoint();pointC=this.getFirstDifferent(new Point(cx-7,cy+7),false,-1,1).toResultPoint();pointD=this.getFirstDifferent(new Point(cx-7,cy-7),false,-1,-1).toResultPoint();}// Recompute the center of the rectangle
cx=MathUtils.round((pointA.getX()+pointD.getX()+pointB.getX()+pointC.getX())/4.0);cy=MathUtils.round((pointA.getY()+pointD.getY()+pointB.getY()+pointC.getY())/4.0);return new Point(cx,cy);}/**
* Gets the Aztec code corners from the bull's eye corners and the parameters.
*
* @param bullsEyeCorners the array of bull's eye corners
* @return the array of aztec code corners
*/},{key:"getMatrixCornerPoints",value:function getMatrixCornerPoints(bullsEyeCorners){return this.expandSquare(bullsEyeCorners,2*this.nbCenterLayers,this.getDimension());}/**
* Creates a BitMatrix by sampling the provided image.
* topLeft, topRight, bottomRight, and bottomLeft are the centers of the squares on the
* diagonal just outside the bull's eye.
*/},{key:"sampleGrid",value:function sampleGrid(image,topLeft,topRight,bottomRight,bottomLeft){var sampler=GridSamplerInstance.getInstance();var dimension=this.getDimension();var low=dimension/2-this.nbCenterLayers;var high=dimension/2+this.nbCenterLayers;return sampler.sampleGrid(image,dimension,dimension,low,low,// topleft
high,low,// topright
high,high,// bottomright
low,high,// bottomleft
topLeft.getX(),topLeft.getY(),topRight.getX(),topRight.getY(),bottomRight.getX(),bottomRight.getY(),bottomLeft.getX(),bottomLeft.getY());}/**
* Samples a line.
*
* @param p1 start point (inclusive)
* @param p2 end point (exclusive)
* @param size number of bits
* @return the array of bits as an int (first bit is high-order bit of result)
*/},{key:"sampleLine",value:function sampleLine(p1,p2,size){var result=0;var d=this.distanceResultPoint(p1,p2);var moduleSize=d/size;var px=p1.getX();var py=p1.getY();var dx=moduleSize*(p2.getX()-p1.getX())/d;var dy=moduleSize*(p2.getY()-p1.getY())/d;for(var i=0;i<size;i++){if(this.image.get(MathUtils.round(px+i*dx),MathUtils.round(py+i*dy))){result|=1<<size-i-1;}}return result;}/**
* @return true if the border of the rectangle passed in parameter is compound of white points only
* or black points only
*/},{key:"isWhiteOrBlackRectangle",value:function isWhiteOrBlackRectangle(p1,p2,p3,p4){var corr=3;p1=new Point(p1.getX()-corr,p1.getY()+corr);p2=new Point(p2.getX()-corr,p2.getY()-corr);p3=new Point(p3.getX()+corr,p3.getY()-corr);p4=new Point(p4.getX()+corr,p4.getY()+corr);var cInit=this.getColor(p4,p1);if(cInit===0){return false;}var c=this.getColor(p1,p2);if(c!==cInit){return false;}c=this.getColor(p2,p3);if(c!==cInit){return false;}c=this.getColor(p3,p4);return c===cInit;}/**
* Gets the color of a segment
*
* @return 1 if segment more than 90% black, -1 if segment is more than 90% white, 0 else
*/},{key:"getColor",value:function getColor(p1,p2){var d=this.distancePoint(p1,p2);var dx=(p2.getX()-p1.getX())/d;var dy=(p2.getY()-p1.getY())/d;var error=0;var px=p1.getX();var py=p1.getY();var colorModel=this.image.get(p1.getX(),p1.getY());var iMax=Math.ceil(d);for(var i=0;i<iMax;i++){px+=dx;py+=dy;if(this.image.get(MathUtils.round(px),MathUtils.round(py))!==colorModel){error++;}}var errRatio=error/d;if(errRatio>0.1&&errRatio<0.9){return 0;}return errRatio<=0.1===colorModel?1:-1;}/**
* Gets the coordinate of the first point with a different color in the given direction
*/},{key:"getFirstDifferent",value:function getFirstDifferent(init,color,dx,dy){var x=init.getX()+dx;var y=init.getY()+dy;while(this.isValid(x,y)&&this.image.get(x,y)===color){x+=dx;y+=dy;}x-=dx;y-=dy;while(this.isValid(x,y)&&this.image.get(x,y)===color){x+=dx;}x-=dx;while(this.isValid(x,y)&&this.image.get(x,y)===color){y+=dy;}y-=dy;return new Point(x,y);}/**
* Expand the square represented by the corner points by pushing out equally in all directions
*
* @param cornerPoints the corners of the square, which has the bull's eye at its center
* @param oldSide the original length of the side of the square in the target bit matrix
* @param newSide the new length of the size of the square in the target bit matrix
* @return the corners of the expanded square
*/},{key:"expandSquare",value:function expandSquare(cornerPoints,oldSide,newSide){var ratio=newSide/(2.0*oldSide);var dx=cornerPoints[0].getX()-cornerPoints[2].getX();var dy=cornerPoints[0].getY()-cornerPoints[2].getY();var centerx=(cornerPoints[0].getX()+cornerPoints[2].getX())/2.0;var centery=(cornerPoints[0].getY()+cornerPoints[2].getY())/2.0;var result0=new ResultPoint(centerx+ratio*dx,centery+ratio*dy);var result2=new ResultPoint(centerx-ratio*dx,centery-ratio*dy);dx=cornerPoints[1].getX()-cornerPoints[3].getX();dy=cornerPoints[1].getY()-cornerPoints[3].getY();centerx=(cornerPoints[1].getX()+cornerPoints[3].getX())/2.0;centery=(cornerPoints[1].getY()+cornerPoints[3].getY())/2.0;var result1=new ResultPoint(centerx+ratio*dx,centery+ratio*dy);var result3=new ResultPoint(centerx-ratio*dx,centery-ratio*dy);var results=[result0,result1,result2,result3];return results;}},{key:"isValid",value:function isValid(x,y){return x>=0&&x<this.image.getWidth()&&y>0&&y<this.image.getHeight();}},{key:"isValidPoint",value:function isValidPoint(point){var x=MathUtils.round(point.getX());var y=MathUtils.round(point.getY());return this.isValid(x,y);}},{key:"distancePoint",value:function distancePoint(a,b){return MathUtils.distance(a.getX(),a.getY(),b.getX(),b.getY());}},{key:"distanceResultPoint",value:function distanceResultPoint(a,b){return MathUtils.distance(a.getX(),a.getY(),b.getX(),b.getY());}},{key:"getDimension",value:function getDimension(){if(this.compact){return 4*this.nbLayers+11;}if(this.nbLayers<=4){return 4*this.nbLayers+15;}return 4*this.nbLayers+2*(Integer.truncDivision(this.nbLayers-4,8)+1)+15;}}]);return Detector;}();/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ // import java.util.List;
// import java.util.Map;
/**
* This implementation can detect and decode Aztec codes in an image.
*
* @author David Olivier
*/var AztecReader=/*#__PURE__*/function(){function AztecReader(){_classCallCheck(this,AztecReader);}_createClass(AztecReader,[{key:"decode",value:/**
* Locates and decodes a Data Matrix code in an image.
*
* @return a String representing the content encoded by the Data Matrix code
* @throws NotFoundException if a Data Matrix code cannot be found
* @throws FormatException if a Data Matrix code cannot be decoded
*/function decode(image){var hints=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var exception=null;var detector=new Detector(image.getBlackMatrix());var points=null;var decoderResult=null;try{var detectorResult=detector.detectMirror(false);points=detectorResult.getPoints();this.reportFoundResultPoints(hints,points);decoderResult=new Decoder().decode(detectorResult);}catch(e){exception=e;}if(decoderResult==null){try{var _detectorResult=detector.detectMirror(true);points=_detectorResult.getPoints();this.reportFoundResultPoints(hints,points);decoderResult=new Decoder().decode(_detectorResult);}catch(e){if(exception!=null){throw exception;}throw e;}}var result=new Result(decoderResult.getText(),decoderResult.getRawBytes(),decoderResult.getNumBits(),points,BarcodeFormat$1.AZTEC,System.currentTimeMillis());var byteSegments=decoderResult.getByteSegments();if(byteSegments!=null){result.putMetadata(ResultMetadataType$1.BYTE_SEGMENTS,byteSegments);}var ecLevel=decoderResult.getECLevel();if(ecLevel!=null){result.putMetadata(ResultMetadataType$1.ERROR_CORRECTION_LEVEL,ecLevel);}return result;}},{key:"reportFoundResultPoints",value:function reportFoundResultPoints(hints,points){if(hints!=null){var rpcb=hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);if(rpcb!=null){points.forEach(function(point,idx,arr){rpcb.foundPossibleResultPoint(point);});}}}// @Override
},{key:"reset",value:function reset(){// do nothing
}}]);return AztecReader;}();/**
* Aztec Code reader to use from browser.
*
* @class BrowserAztecCodeReader
* @extends {BrowserCodeReader}
*/var BrowserAztecCodeReader=/*#__PURE__*/function(_BrowserCodeReader){_inherits(BrowserAztecCodeReader,_BrowserCodeReader);var _super21=_createSuper(BrowserAztecCodeReader);/**
* Creates an instance of BrowserAztecCodeReader.
* @param {number} [timeBetweenScansMillis=500] the time delay between subsequent decode tries
*
* @memberOf BrowserAztecCodeReader
*/function BrowserAztecCodeReader(){var timeBetweenScansMillis=arguments.length>0&&arguments[0]!==undefined?arguments[0]:500;_classCallCheck(this,BrowserAztecCodeReader);return _super21.call(this,new AztecReader(),timeBetweenScansMillis);}return _createClass(BrowserAztecCodeReader);}(BrowserCodeReader);/**
* Encapsulates functionality and implementation that is common to all families
* of one-dimensional barcodes.
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
*/var OneDReader=/*#__PURE__*/function(){function OneDReader(){_classCallCheck(this,OneDReader);}_createClass(OneDReader,[{key:"decode",value:/*
@Override
public Result decode(BinaryBitmap image) throws NotFoundException, FormatException {
return decode(image, null);
}
*/ // Note that we don't try rotation without the try harder flag, even if rotation was supported.
// @Override
function decode(image,hints){try{return this.doDecode(image,hints);}catch(nfe){var tryHarder=hints&&hints.get(DecodeHintType$1.TRY_HARDER)===true;if(tryHarder&&image.isRotateSupported()){var rotatedImage=image.rotateCounterClockwise();var result=this.doDecode(rotatedImage,hints);// Record that we found it rotated 90 degrees CCW / 270 degrees CW
var metadata=result.getResultMetadata();var orientation=270;if(metadata!==null&&metadata.get(ResultMetadataType$1.ORIENTATION)===true){// But if we found it reversed in doDecode(), add in that result here:
orientation=orientation+metadata.get(ResultMetadataType$1.ORIENTATION)%360;}result.putMetadata(ResultMetadataType$1.ORIENTATION,orientation);// Update result points
var points=result.getResultPoints();if(points!==null){var height=rotatedImage.getHeight();for(var i=0;i<points.length;i++){points[i]=new ResultPoint(height-points[i].getY()-1,points[i].getX());}}return result;}else{throw new NotFoundException();}}}// @Override
},{key:"reset",value:function reset(){// do nothing
}/**
* We're going to examine rows from the middle outward, searching alternately above and below the
* middle, and farther out each time. rowStep is the number of rows between each successive
* attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
* middle + rowStep, then middle - (2 * rowStep), etc.
* rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
* decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
* image if "trying harder".
*
* @param image The image to decode
* @param hints Any hints that were requested
* @return The contents of the decoded barcode
* @throws NotFoundException Any spontaneous errors which occur
*/},{key:"doDecode",value:function doDecode(image,hints){var width=image.getWidth();var height=image.getHeight();var row=new BitArray(width);var tryHarder=hints&&hints.get(DecodeHintType$1.TRY_HARDER)===true;var rowStep=Math.max(1,height>>(tryHarder?8:5));var maxLines;if(tryHarder){maxLines=height;// Look at the whole image, not just the center
}else{maxLines=15;// 15 rows spaced 1/32 apart is roughly the middle half of the image
}var middle=Math.trunc(height/2);for(var x=0;x<maxLines;x++){// Scanning from the middle out. Determine which row we're looking at next:
var rowStepsAboveOrBelow=Math.trunc((x+1)/2);var isAbove=(x&0x01)===0;// i.e. is x even?
var rowNumber=middle+rowStep*(isAbove?rowStepsAboveOrBelow:-rowStepsAboveOrBelow);if(rowNumber<0||rowNumber>=height){// Oops, if we run off the top or bottom, stop
break;}// Estimate black point for this row and load it:
try{row=image.getBlackRow(rowNumber,row);}catch(ignored){continue;}// While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
// handle decoding upside down barcodes.
for(var attempt=0;attempt<2;attempt++){if(attempt===1){// trying again?
row.reverse();// reverse the row and continue
// This means we will only ever draw result points *once* in the life of this method
// since we want to avoid drawing the wrong points after flipping the row, and,
// don't want to clutter with noise from every single row scan -- just the scans
// that start on the center line.
if(hints&&hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK)===true){(function(){var newHints=new Map();hints.forEach(function(hint,key){return newHints.set(key,hint);});newHints.delete(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);hints=newHints;})();}}try{// Look for a barcode
var result=this.decodeRow(rowNumber,row,hints);// We found our barcode
if(attempt===1){// But it was upside down, so note that
result.putMetadata(ResultMetadataType$1.ORIENTATION,180);// And remember to flip the result points horizontally.
var points=result.getResultPoints();if(points!==null){points[0]=new ResultPoint(width-points[0].getX()-1,points[0].getY());points[1]=new ResultPoint(width-points[1].getX()-1,points[1].getY());}}return result;}catch(re){// continue -- just couldn't decode this row
}}}throw new NotFoundException();}/**
* Records the size of successive runs of white and black pixels in a row, starting at a given point.
* The values are recorded in the given array, and the number of runs recorded is equal to the size
* of the array. If the row starts on a white pixel at the given start point, then the first count
* recorded is the run of white pixels starting from that point; likewise it is the count of a run
* of black pixels if the row begin on a black pixels at that point.
*
* @param row row to count from
* @param start offset into row to start at
* @param counters array into which to record counts
* @throws NotFoundException if counters cannot be filled entirely from row before running out
* of pixels
*/}],[{key:"recordPattern",value:function recordPattern(row,start,counters){var numCounters=counters.length;for(var index=0;index<numCounters;index++){counters[index]=0;}var end=row.getSize();if(start>=end){throw new NotFoundException();}var isWhite=!row.get(start);var counterPosition=0;var i=start;while(i<end){if(row.get(i)!==isWhite){counters[counterPosition]++;}else{if(++counterPosition===numCounters){break;}else{counters[counterPosition]=1;isWhite=!isWhite;}}i++;}// If we read fully the last section of pixels and filled up our counters -- or filled
// the last counter but ran off the side of the image, OK. Otherwise, a problem.
if(!(counterPosition===numCounters||counterPosition===numCounters-1&&i===end)){throw new NotFoundException();}}},{key:"recordPatternInReverse",value:function recordPatternInReverse(row,start,counters){// This could be more efficient I guess
var numTransitionsLeft=counters.length;var last=row.get(start);while(start>0&&numTransitionsLeft>=0){if(row.get(--start)!==last){numTransitionsLeft--;last=!last;}}if(numTransitionsLeft>=0){throw new NotFoundException();}OneDReader.recordPattern(row,start+1,counters);}/**
* Determines how closely a set of observed counts of runs of black/white values matches a given
* target pattern. This is reported as the ratio of the total variance from the expected pattern
* proportions across all pattern elements, to the length of the pattern.
*
* @param counters observed counters
* @param pattern expected pattern
* @param maxIndividualVariance The most any counter can differ before we give up
* @return ratio of total variance between counters and pattern compared to total pattern size
*/},{key:"patternMatchVariance",value:function patternMatchVariance(counters,pattern,maxIndividualVariance){var numCounters=counters.length;var total=0;var patternLength=0;for(var i=0;i<numCounters;i++){total+=counters[i];patternLength+=pattern[i];}if(total<patternLength){// If we don't even have one pixel per unit of bar width, assume this is too small
// to reliably match, so fail:
return Number.POSITIVE_INFINITY;}var unitBarWidth=total/patternLength;maxIndividualVariance*=unitBarWidth;var totalVariance=0.0;for(var x=0;x<numCounters;x++){var counter=counters[x];var scaledPattern=pattern[x]*unitBarWidth;var variance=counter>scaledPattern?counter-scaledPattern:scaledPattern-counter;if(variance>maxIndividualVariance){return Number.POSITIVE_INFINITY;}totalVariance+=variance;}return totalVariance/total;}}]);return OneDReader;}();/**
* <p>Decodes Code 128 barcodes.</p>
*
* @author Sean Owen
*/var Code128Reader=/*#__PURE__*/function(_OneDReader){_inherits(Code128Reader,_OneDReader);var _super22=_createSuper(Code128Reader);function Code128Reader(){_classCallCheck(this,Code128Reader);return _super22.apply(this,arguments);}_createClass(Code128Reader,[{key:"decodeRow",value:function decodeRow(rowNumber,row,hints){var convertFNC1=hints&&hints.get(DecodeHintType$1.ASSUME_GS1)===true;var startPatternInfo=Code128Reader.findStartPattern(row);var startCode=startPatternInfo[2];var currentRawCodesIndex=0;var rawCodes=new Uint8Array(20);rawCodes[currentRawCodesIndex++]=startCode;var codeSet;switch(startCode){case Code128Reader.CODE_START_A:codeSet=Code128Reader.CODE_CODE_A;break;case Code128Reader.CODE_START_B:codeSet=Code128Reader.CODE_CODE_B;break;case Code128Reader.CODE_START_C:codeSet=Code128Reader.CODE_CODE_C;break;default:throw new FormatException();}var done=false;var isNextShifted=false;var result='';var lastStart=startPatternInfo[0];var nextStart=startPatternInfo[1];var counters=Int32Array.from([0,0,0,0,0,0]);var lastCode=0;var code=0;var checksumTotal=startCode;var multiplier=0;var lastCharacterWasPrintable=true;var upperMode=false;var shiftUpperMode=false;while(!done){var unshift=isNextShifted;isNextShifted=false;// Save off last code
lastCode=code;// Decode another code from image
code=Code128Reader.decodeCode(row,counters,nextStart);rawCodes[currentRawCodesIndex++]=code;// Remember whether the last code was printable or not (excluding CODE_STOP)
if(code!==Code128Reader.CODE_STOP){lastCharacterWasPrintable=true;}// Add to checksum computation (if not CODE_STOP of course)
if(code!==Code128Reader.CODE_STOP){multiplier++;checksumTotal+=multiplier*code;}// Advance to where the next code will to start
lastStart=nextStart;nextStart+=counters.reduce(function(previous,current){return previous+current;},0);// Take care of illegal start codes
switch(code){case Code128Reader.CODE_START_A:case Code128Reader.CODE_START_B:case Code128Reader.CODE_START_C:throw new FormatException();}switch(codeSet){case Code128Reader.CODE_CODE_A:if(code<64){if(shiftUpperMode===upperMode){result+=String.fromCharCode(' '.charCodeAt(0)+code);}else{result+=String.fromCharCode(' '.charCodeAt(0)+code+128);}shiftUpperMode=false;}else if(code<96){if(shiftUpperMode===upperMode){result+=String.fromCharCode(code-64);}else{result+=String.fromCharCode(code+64);}shiftUpperMode=false;}else{// Don't let CODE_STOP, which always appears, affect whether whether we think the last
// code was printable or not.
if(code!==Code128Reader.CODE_STOP){lastCharacterWasPrintable=false;}switch(code){case Code128Reader.CODE_FNC_1:if(convertFNC1){if(result.length===0){// GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
// is FNC1 then this is GS1-128. We add the symbology identifier.
result+=']C1';}else{// GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
result+=String.fromCharCode(29);}}break;case Code128Reader.CODE_FNC_2:case Code128Reader.CODE_FNC_3:// do nothing?
break;case Code128Reader.CODE_FNC_4_A:if(!upperMode&&shiftUpperMode){upperMode=true;shiftUpperMode=false;}else if(upperMode&&shiftUpperMode){upperMode=false;shiftUpperMode=false;}else{shiftUpperMode=true;}break;case Code128Reader.CODE_SHIFT:isNextShifted=true;codeSet=Code128Reader.CODE_CODE_B;break;case Code128Reader.CODE_CODE_B:codeSet=Code128Reader.CODE_CODE_B;break;case Code128Reader.CODE_CODE_C:codeSet=Code128Reader.CODE_CODE_C;break;case Code128Reader.CODE_STOP:done=true;break;}}break;case Code128Reader.CODE_CODE_B:if(code<96){if(shiftUpperMode===upperMode){result+=String.fromCharCode(' '.charCodeAt(0)+code);}else{result+=String.fromCharCode(' '.charCodeAt(0)+code+128);}shiftUpperMode=false;}else{if(code!==Code128Reader.CODE_STOP){lastCharacterWasPrintable=false;}switch(code){case Code128Reader.CODE_FNC_1:if(convertFNC1){if(result.length===0){// GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
// is FNC1 then this is GS1-128. We add the symbology identifier.
result+=']C1';}else{// GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
result+=String.fromCharCode(29);}}break;case Code128Reader.CODE_FNC_2:case Code128Reader.CODE_FNC_3:// do nothing?
break;case Code128Reader.CODE_FNC_4_B:if(!upperMode&&shiftUpperMode){upperMode=true;shiftUpperMode=false;}else if(upperMode&&shiftUpperMode){upperMode=false;shiftUpperMode=false;}else{shiftUpperMode=true;}break;case Code128Reader.CODE_SHIFT:isNextShifted=true;codeSet=Code128Reader.CODE_CODE_A;break;case Code128Reader.CODE_CODE_A:codeSet=Code128Reader.CODE_CODE_A;break;case Code128Reader.CODE_CODE_C:codeSet=Code128Reader.CODE_CODE_C;break;case Code128Reader.CODE_STOP:done=true;break;}}break;case Code128Reader.CODE_CODE_C:if(code<100){if(code<10){result+='0';}result+=code;}else{if(code!==Code128Reader.CODE_STOP){lastCharacterWasPrintable=false;}switch(code){case Code128Reader.CODE_FNC_1:if(convertFNC1){if(result.length===0){// GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
// is FNC1 then this is GS1-128. We add the symbology identifier.
result+=']C1';}else{// GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
result+=String.fromCharCode(29);}}break;case Code128Reader.CODE_CODE_A:codeSet=Code128Reader.CODE_CODE_A;break;case Code128Reader.CODE_CODE_B:codeSet=Code128Reader.CODE_CODE_B;break;case Code128Reader.CODE_STOP:done=true;break;}}break;}// Unshift back to another code set if we were shifted
if(unshift){codeSet=codeSet===Code128Reader.CODE_CODE_A?Code128Reader.CODE_CODE_B:Code128Reader.CODE_CODE_A;}}var lastPatternSize=nextStart-lastStart;// Check for ample whitespace following pattern, but, to do this we first need to remember that
// we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left
// to read off. Would be slightly better to properly read. Here we just skip it:
nextStart=row.getNextUnset(nextStart);if(!row.isRange(nextStart,Math.min(row.getSize(),nextStart+(nextStart-lastStart)/2),false)){throw new NotFoundException();}// Pull out from sum the value of the penultimate check code
checksumTotal-=multiplier*lastCode;// lastCode is the checksum then:
if(checksumTotal%103!==lastCode){throw new ChecksumException();}// Need to pull out the check digits from string
var resultLength=result.length;if(resultLength===0){// false positive
throw new NotFoundException();}// Only bother if the result had at least one character, and if the checksum digit happened to
// be a printable character. If it was just interpreted as a control code, nothing to remove.
if(resultLength>0&&lastCharacterWasPrintable){if(codeSet===Code128Reader.CODE_CODE_C){result=result.substring(0,resultLength-2);}else{result=result.substring(0,resultLength-1);}}var left=(startPatternInfo[1]+startPatternInfo[0])/2.0;var right=lastStart+lastPatternSize/2.0;var rawCodesSize=rawCodes.length;var rawBytes=new Uint8Array(rawCodesSize);for(var i=0;i<rawCodesSize;i++){rawBytes[i]=rawCodes[i];}var points=[new ResultPoint(left,rowNumber),new ResultPoint(right,rowNumber)];return new Result(result,rawBytes,0,points,BarcodeFormat$1.CODE_128,new Date().getTime());}}],[{key:"findStartPattern",value:function findStartPattern(row){var width=row.getSize();var rowOffset=row.getNextSet(0);var counterPosition=0;var counters=Int32Array.from([0,0,0,0,0,0]);var patternStart=rowOffset;var isWhite=false;var patternLength=6;for(var i=rowOffset;i<width;i++){if(row.get(i)!==isWhite){counters[counterPosition]++;}else{if(counterPosition===patternLength-1){var bestVariance=Code128Reader.MAX_AVG_VARIANCE;var bestMatch=-1;for(var startCode=Code128Reader.CODE_START_A;startCode<=Code128Reader.CODE_START_C;startCode++){var variance=OneDReader.patternMatchVariance(counters,Code128Reader.CODE_PATTERNS[startCode],Code128Reader.MAX_INDIVIDUAL_VARIANCE);if(variance<bestVariance){bestVariance=variance;bestMatch=startCode;}}// Look for whitespace before start pattern, >= 50% of width of start pattern
if(bestMatch>=0&&row.isRange(Math.max(0,patternStart-(i-patternStart)/2),patternStart,false)){return Int32Array.from([patternStart,i,bestMatch]);}patternStart+=counters[0]+counters[1];counters=counters.slice(2,counters.length-1);counters[counterPosition-1]=0;counters[counterPosition]=0;counterPosition--;}else{counterPosition++;}counters[counterPosition]=1;isWhite=!isWhite;}}throw new NotFoundException();}},{key:"decodeCode",value:function decodeCode(row,counters,rowOffset){OneDReader.recordPattern(row,rowOffset,counters);var bestVariance=Code128Reader.MAX_AVG_VARIANCE;// worst variance we'll accept
var bestMatch=-1;for(var d=0;d<Code128Reader.CODE_PATTERNS.length;d++){var pattern=Code128Reader.CODE_PATTERNS[d];var variance=this.patternMatchVariance(counters,pattern,Code128Reader.MAX_INDIVIDUAL_VARIANCE);if(variance<bestVariance){bestVariance=variance;bestMatch=d;}}// TODO We're overlooking the fact that the STOP pattern has 7 values, not 6.
if(bestMatch>=0){return bestMatch;}else{throw new NotFoundException();}}}]);return Code128Reader;}(OneDReader);Code128Reader.CODE_PATTERNS=[Int32Array.from([2,1,2,2,2,2]),Int32Array.from([2,2,2,1,2,2]),Int32Array.from([2,2,2,2,2,1]),Int32Array.from([1,2,1,2,2,3]),Int32Array.from([1,2,1,3,2,2]),Int32Array.from([1,3,1,2,2,2]),Int32Array.from([1,2,2,2,1,3]),Int32Array.from([1,2,2,3,1,2]),Int32Array.from([1,3,2,2,1,2]),Int32Array.from([2,2,1,2,1,3]),Int32Array.from([2,2,1,3,1,2]),Int32Array.from([2,3,1,2,1,2]),Int32Array.from([1,1,2,2,3,2]),Int32Array.from([1,2,2,1,3,2]),Int32Array.from([1,2,2,2,3,1]),Int32Array.from([1,1,3,2,2,2]),Int32Array.from([1,2,3,1,2,2]),Int32Array.from([1,2,3,2,2,1]),Int32Array.from([2,2,3,2,1,1]),Int32Array.from([2,2,1,1,3,2]),Int32Array.from([2,2,1,2,3,1]),Int32Array.from([2,1,3,2,1,2]),Int32Array.from([2,2,3,1,1,2]),Int32Array.from([3,1,2,1,3,1]),Int32Array.from([3,1,1,2,2,2]),Int32Array.from([3,2,1,1,2,2]),Int32Array.from([3,2,1,2,2,1]),Int32Array.from([3,1,2,2,1,2]),Int32Array.from([3,2,2,1,1,2]),Int32Array.from([3,2,2,2,1,1]),Int32Array.from([2,1,2,1,2,3]),Int32Array.from([2,1,2,3,2,1]),Int32Array.from([2,3,2,1,2,1]),Int32Array.from([1,1,1,3,2,3]),Int32Array.from([1,3,1,1,2,3]),Int32Array.from([1,3,1,3,2,1]),Int32Array.from([1,1,2,3,1,3]),Int32Array.from([1,3,2,1,1,3]),Int32Array.from([1,3,2,3,1,1]),Int32Array.from([2,1,1,3,1,3]),Int32Array.from([2,3,1,1,1,3]),Int32Array.from([2,3,1,3,1,1]),Int32Array.from([1,1,2,1,3,3]),Int32Array.from([1,1,2,3,3,1]),Int32Array.from([1,3,2,1,3,1]),Int32Array.from([1,1,3,1,2,3]),Int32Array.from([1,1,3,3,2,1]),Int32Array.from([1,3,3,1,2,1]),Int32Array.from([3,1,3,1,2,1]),Int32Array.from([2,1,1,3,3,1]),Int32Array.from([2,3,1,1,3,1]),Int32Array.from([2,1,3,1,1,3]),Int32Array.from([2,1,3,3,1,1]),Int32Array.from([2,1,3,1,3,1]),Int32Array.from([3,1,1,1,2,3]),Int32Array.from([3,1,1,3,2,1]),Int32Array.from([3,3,1,1,2,1]),Int32Array.from([3,1,2,1,1,3]),Int32Array.from([3,1,2,3,1,1]),Int32Array.from([3,3,2,1,1,1]),Int32Array.from([3,1,4,1,1,1]),Int32Array.from([2,2,1,4,1,1]),Int32Array.from([4,3,1,1,1,1]),Int32Array.from([1,1,1,2,2,4]),Int32Array.from([1,1,1,4,2,2]),Int32Array.from([1,2,1,1,2,4]),Int32Array.from([1,2,1,4,2,1]),Int32Array.from([1,4,1,1,2,2]),Int32Array.from([1,4,1,2,2,1]),Int32Array.from([1,1,2,2,1,4]),Int32Array.from([1,1,2,4,1,2]),Int32Array.from([1,2,2,1,1,4]),Int32Array.from([1,2,2,4,1,1]),Int32Array.from([1,4,2,1,1,2]),Int32Array.from([1,4,2,2,1,1]),Int32Array.from([2,4,1,2,1,1]),Int32Array.from([2,2,1,1,1,4]),Int32Array.from([4,1,3,1,1,1]),Int32Array.from([2,4,1,1,1,2]),Int32Array.from([1,3,4,1,1,1]),Int32Array.from([1,1,1,2,4,2]),Int32Array.from([1,2,1,1,4,2]),Int32Array.from([1,2,1,2,4,1]),Int32Array.from([1,1,4,2,1,2]),Int32Array.from([1,2,4,1,1,2]),Int32Array.from([1,2,4,2,1,1]),Int32Array.from([4,1,1,2,1,2]),Int32Array.from([4,2,1,1,1,2]),Int32Array.from([4,2,1,2,1,1]),Int32Array.from([2,1,2,1,4,1]),Int32Array.from([2,1,4,1,2,1]),Int32Array.from([4,1,2,1,2,1]),Int32Array.from([1,1,1,1,4,3]),Int32Array.from([1,1,1,3,4,1]),Int32Array.from([1,3,1,1,4,1]),Int32Array.from([1,1,4,1,1,3]),Int32Array.from([1,1,4,3,1,1]),Int32Array.from([4,1,1,1,1,3]),Int32Array.from([4,1,1,3,1,1]),Int32Array.from([1,1,3,1,4,1]),Int32Array.from([1,1,4,1,3,1]),Int32Array.from([3,1,1,1,4,1]),Int32Array.from([4,1,1,1,3,1]),Int32Array.from([2,1,1,4,1,2]),Int32Array.from([2,1,1,2,1,4]),Int32Array.from([2,1,1,2,3,2]),Int32Array.from([2,3,3,1,1,1,2])];Code128Reader.MAX_AVG_VARIANCE=0.25;Code128Reader.MAX_INDIVIDUAL_VARIANCE=0.7;Code128Reader.CODE_SHIFT=98;Code128Reader.CODE_CODE_C=99;Code128Reader.CODE_CODE_B=100;Code128Reader.CODE_CODE_A=101;Code128Reader.CODE_FNC_1=102;Code128Reader.CODE_FNC_2=97;Code128Reader.CODE_FNC_3=96;Code128Reader.CODE_FNC_4_A=101;Code128Reader.CODE_FNC_4_B=100;Code128Reader.CODE_START_A=103;Code128Reader.CODE_START_B=104;Code128Reader.CODE_START_C=105;Code128Reader.CODE_STOP=106;/**
* <p>Decodes Code 39 barcodes. Supports "Full ASCII Code 39" if USE_CODE_39_EXTENDED_MODE is set.</p>
*
* @author Sean Owen
* @see Code93Reader
*/var Code39Reader=/*#__PURE__*/function(_OneDReader2){_inherits(Code39Reader,_OneDReader2);var _super23=_createSuper(Code39Reader);/**
* Creates a reader that assumes all encoded data is data, and does not treat the final
* character as a check digit. It will not decoded "extended Code 39" sequences.
*/ // public Code39Reader() {
// this(false);
// }
/**
* Creates a reader that can be configured to check the last character as a check digit.
* It will not decoded "extended Code 39" sequences.
*
* @param usingCheckDigit if true, treat the last data character as a check digit, not
* data, and verify that the checksum passes.
*/ // public Code39Reader(boolean usingCheckDigit) {
// this(usingCheckDigit, false);
// }
/**
* Creates a reader that can be configured to check the last character as a check digit,
* or optionally attempt to decode "extended Code 39" sequences that are used to encode
* the full ASCII character set.
*
* @param usingCheckDigit if true, treat the last data character as a check digit, not
* data, and verify that the checksum passes.
* @param extendedMode if true, will attempt to decode extended Code 39 sequences in the
* text.
*/function Code39Reader(){var _this15;var usingCheckDigit=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var extendedMode=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;_classCallCheck(this,Code39Reader);_this15=_super23.call(this);_this15.usingCheckDigit=usingCheckDigit;_this15.extendedMode=extendedMode;_this15.decodeRowResult='';_this15.counters=new Int32Array(9);return _this15;}_createClass(Code39Reader,[{key:"decodeRow",value:function decodeRow(rowNumber,row,hints){var theCounters=this.counters;theCounters.fill(0);this.decodeRowResult='';var start=Code39Reader.findAsteriskPattern(row,theCounters);// Read off white space
var nextStart=row.getNextSet(start[1]);var end=row.getSize();var decodedChar;var lastStart;do{Code39Reader.recordPattern(row,nextStart,theCounters);var pattern=Code39Reader.toNarrowWidePattern(theCounters);if(pattern<0){throw new NotFoundException();}decodedChar=Code39Reader.patternToChar(pattern);this.decodeRowResult+=decodedChar;lastStart=nextStart;var _iterator3=_createForOfIteratorHelper(theCounters),_step3;try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var counter=_step3.value;nextStart+=counter;}// Read off white space
}catch(err){_iterator3.e(err);}finally{_iterator3.f();}nextStart=row.getNextSet(nextStart);}while(decodedChar!=='*');this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-1);// remove asterisk
// Look for whitespace after pattern:
var lastPatternSize=0;var _iterator4=_createForOfIteratorHelper(theCounters),_step4;try{for(_iterator4.s();!(_step4=_iterator4.n()).done;){var _counter=_step4.value;lastPatternSize+=_counter;}}catch(err){_iterator4.e(err);}finally{_iterator4.f();}var whiteSpaceAfterEnd=nextStart-lastStart-lastPatternSize;// If 50% of last pattern size, following last pattern, is not whitespace, fail
// (but if it's whitespace to the very end of the image, that's OK)
if(nextStart!==end&&whiteSpaceAfterEnd*2<lastPatternSize){throw new NotFoundException();}if(this.usingCheckDigit){var max=this.decodeRowResult.length-1;var total=0;for(var i=0;i<max;i++){total+=Code39Reader.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(i));}if(this.decodeRowResult.charAt(max)!==Code39Reader.ALPHABET_STRING.charAt(total%43)){throw new ChecksumException();}this.decodeRowResult=this.decodeRowResult.substring(0,max);}if(this.decodeRowResult.length===0){// false positive
throw new NotFoundException();}var resultString;if(this.extendedMode){resultString=Code39Reader.decodeExtended(this.decodeRowResult);}else{resultString=this.decodeRowResult;}var left=(start[1]+start[0])/2.0;var right=lastStart+lastPatternSize/2.0;return new Result(resultString,null,0,[new ResultPoint(left,rowNumber),new ResultPoint(right,rowNumber)],BarcodeFormat$1.CODE_39,new Date().getTime());}}],[{key:"findAsteriskPattern",value:function findAsteriskPattern(row,counters){var width=row.getSize();var rowOffset=row.getNextSet(0);var counterPosition=0;var patternStart=rowOffset;var isWhite=false;var patternLength=counters.length;for(var i=rowOffset;i<width;i++){if(row.get(i)!==isWhite){counters[counterPosition]++;}else{if(counterPosition===patternLength-1){// Look for whitespace before start pattern, >= 50% of width of start pattern
if(this.toNarrowWidePattern(counters)===Code39Reader.ASTERISK_ENCODING&&row.isRange(Math.max(0,patternStart-Math.floor((i-patternStart)/2)),patternStart,false)){return[patternStart,i];}patternStart+=counters[0]+counters[1];counters.copyWithin(0,2,2+counterPosition-1);counters[counterPosition-1]=0;counters[counterPosition]=0;counterPosition--;}else{counterPosition++;}counters[counterPosition]=1;isWhite=!isWhite;}}throw new NotFoundException();}// For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions
// per image when using some of our blackbox images.
},{key:"toNarrowWidePattern",value:function toNarrowWidePattern(counters){var numCounters=counters.length;var maxNarrowCounter=0;var wideCounters;do{var minCounter=0x7fffffff;var _iterator5=_createForOfIteratorHelper(counters),_step5;try{for(_iterator5.s();!(_step5=_iterator5.n()).done;){var _counter3=_step5.value;if(_counter3<minCounter&&_counter3>maxNarrowCounter){minCounter=_counter3;}}}catch(err){_iterator5.e(err);}finally{_iterator5.f();}maxNarrowCounter=minCounter;wideCounters=0;var totalWideCountersWidth=0;var pattern=0;for(var i=0;i<numCounters;i++){var counter=counters[i];if(counter>maxNarrowCounter){pattern|=1<<numCounters-1-i;wideCounters++;totalWideCountersWidth+=counter;}}if(wideCounters===3){// Found 3 wide counters, but are they close enough in width?
// We can perform a cheap, conservative check to see if any individual
// counter is more than 1.5 times the average:
for(var _i14=0;_i14<numCounters&&wideCounters>0;_i14++){var _counter2=counters[_i14];if(_counter2>maxNarrowCounter){wideCounters--;// totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
if(_counter2*2>=totalWideCountersWidth){return-1;}}}return pattern;}}while(wideCounters>3);return-1;}},{key:"patternToChar",value:function patternToChar(pattern){for(var i=0;i<Code39Reader.CHARACTER_ENCODINGS.length;i++){if(Code39Reader.CHARACTER_ENCODINGS[i]===pattern){return Code39Reader.ALPHABET_STRING.charAt(i);}}if(pattern===Code39Reader.ASTERISK_ENCODING){return'*';}throw new NotFoundException();}},{key:"decodeExtended",value:function decodeExtended(encoded){var length=encoded.length;var decoded='';for(var i=0;i<length;i++){var c=encoded.charAt(i);if(c==='+'||c==='$'||c==='%'||c==='/'){var next=encoded.charAt(i+1);var decodedChar='\0';switch(c){case'+':// +A to +Z map to a to z
if(next>='A'&&next<='Z'){decodedChar=String.fromCharCode(next.charCodeAt(0)+32);}else{throw new FormatException();}break;case'$':// $A to $Z map to control codes SH to SB
if(next>='A'&&next<='Z'){decodedChar=String.fromCharCode(next.charCodeAt(0)-64);}else{throw new FormatException();}break;case'%':// %A to %E map to control codes ESC to US
if(next>='A'&&next<='E'){decodedChar=String.fromCharCode(next.charCodeAt(0)-38);}else if(next>='F'&&next<='J'){decodedChar=String.fromCharCode(next.charCodeAt(0)-11);}else if(next>='K'&&next<='O'){decodedChar=String.fromCharCode(next.charCodeAt(0)+16);}else if(next>='P'&&next<='T'){decodedChar=String.fromCharCode(next.charCodeAt(0)+43);}else if(next==='U'){decodedChar='\0';}else if(next==='V'){decodedChar='@';}else if(next==='W'){decodedChar='`';}else if(next==='X'||next==='Y'||next==='Z'){decodedChar='\x7f';}else{throw new FormatException();}break;case'/':// /A to /O map to ! to , and /Z maps to :
if(next>='A'&&next<='O'){decodedChar=String.fromCharCode(next.charCodeAt(0)-32);}else if(next==='Z'){decodedChar=':';}else{throw new FormatException();}break;}decoded+=decodedChar;// bump up i again since we read two characters
i++;}else{decoded+=c;}}return decoded;}}]);return Code39Reader;}(OneDReader);Code39Reader.ALPHABET_STRING='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%';/**
* These represent the encodings of characters, as patterns of wide and narrow bars.
* The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
* with 1s representing "wide" and 0s representing narrow.
*/Code39Reader.CHARACTER_ENCODINGS=[0x034,0x121,0x061,0x160,0x031,0x130,0x070,0x025,0x124,0x064,0x109,0x049,0x148,0x019,0x118,0x058,0x00D,0x10C,0x04C,0x01C,0x103,0x043,0x142,0x013,0x112,0x052,0x007,0x106,0x046,0x016,0x181,0x0C1,0x1C0,0x091,0x190,0x0D0,0x085,0x184,0x0C4,0x0A8,0x0A2,0x08A,0x02A// /-%
];Code39Reader.ASTERISK_ENCODING=0x094;/**
* <p>Decodes ITF barcodes.</p>
*
* @author Tjieco
*/var ITFReader=/*#__PURE__*/function(_OneDReader3){_inherits(ITFReader,_OneDReader3);var _super24=_createSuper(ITFReader);function ITFReader(){var _this16;_classCallCheck(this,ITFReader);// private static W = 3; // Pixel width of a 3x wide line
// private static w = 2; // Pixel width of a 2x wide line
// private static N = 1; // Pixed width of a narrow line
_this16=_super24.apply(this,arguments);// Stores the actual narrow line width of the image being decoded.
_this16.narrowLineWidth=-1;return _this16;}// See ITFWriter.PATTERNS
/*
/!**
* Patterns of Wide / Narrow lines to indicate each digit
*!/
*/_createClass(ITFReader,[{key:"decodeRow",value:function decodeRow(rowNumber,row,hints){// Find out where the Middle section (payload) starts & ends
var startRange=this.decodeStart(row);var endRange=this.decodeEnd(row);var result=new StringBuilder();ITFReader.decodeMiddle(row,startRange[1],endRange[0],result);var resultString=result.toString();var allowedLengths=null;if(hints!=null){allowedLengths=hints.get(DecodeHintType$1.ALLOWED_LENGTHS);}if(allowedLengths==null){allowedLengths=ITFReader.DEFAULT_ALLOWED_LENGTHS;}// To avoid false positives with 2D barcodes (and other patterns), make
// an assumption that the decoded string must be a 'standard' length if it's short
var length=resultString.length;var lengthOK=false;var maxAllowedLength=0;var _iterator6=_createForOfIteratorHelper(allowedLengths),_step6;try{for(_iterator6.s();!(_step6=_iterator6.n()).done;){var value=_step6.value;if(length===value){lengthOK=true;break;}if(value>maxAllowedLength){maxAllowedLength=value;}}}catch(err){_iterator6.e(err);}finally{_iterator6.f();}if(!lengthOK&&length>maxAllowedLength){lengthOK=true;}if(!lengthOK){throw new FormatException();}var points=[new ResultPoint(startRange[1],rowNumber),new ResultPoint(endRange[0],rowNumber)];var resultReturn=new Result(resultString,null,// no natural byte representation for these barcodes
0,points,BarcodeFormat$1.ITF,new Date().getTime());return resultReturn;}/*
/!**
* @param row row of black/white values to search
* @param payloadStart offset of start pattern
* @param resultString {@link StringBuilder} to append decoded chars to
* @throws NotFoundException if decoding could not complete successfully
*!/*/},{key:"decodeStart",value:/*/!**
* Identify where the start of the middle / payload section starts.
*
* @param row row of black/white values to search
* @return Array, containing index of start of 'start block' and end of
* 'start block'
*!/*/function decodeStart(row){var endStart=ITFReader.skipWhiteSpace(row);var startPattern=ITFReader.findGuardPattern(row,endStart,ITFReader.START_PATTERN);// Determine the width of a narrow line in pixels. We can do this by
// getting the width of the start pattern and dividing by 4 because its
// made up of 4 narrow lines.
this.narrowLineWidth=(startPattern[1]-startPattern[0])/4;this.validateQuietZone(row,startPattern[0]);return startPattern;}/*/!**
* The start & end patterns must be pre/post fixed by a quiet zone. This
* zone must be at least 10 times the width of a narrow line. Scan back until
* we either get to the start of the barcode or match the necessary number of
* quiet zone pixels.
*
* Note: Its assumed the row is reversed when using this method to find
* quiet zone after the end pattern.
*
* ref: http://www.barcode-1.net/i25code.html
*
* @param row bit array representing the scanned barcode.
* @param startPattern index into row of the start or end pattern.
* @throws NotFoundException if the quiet zone cannot be found
*!/*/},{key:"validateQuietZone",value:function validateQuietZone(row,startPattern){var quietCount=this.narrowLineWidth*10;// expect to find this many pixels of quiet zone
// if there are not so many pixel at all let's try as many as possible
quietCount=quietCount<startPattern?quietCount:startPattern;for(var i=startPattern-1;quietCount>0&&i>=0;i--){if(row.get(i)){break;}quietCount--;}if(quietCount!==0){// Unable to find the necessary number of quiet zone pixels.
throw new NotFoundException();}}/*
/!**
* Skip all whitespace until we get to the first black line.
*
* @param row row of black/white values to search
* @return index of the first black line.
* @throws NotFoundException Throws exception if no black lines are found in the row
*!/*/},{key:"decodeEnd",value:/*/!**
* Identify where the end of the middle / payload section ends.
*
* @param row row of black/white values to search
* @return Array, containing index of start of 'end block' and end of 'end
* block'
*!/*/function decodeEnd(row){// For convenience, reverse the row and then
// search from 'the start' for the end block
row.reverse();try{var endStart=ITFReader.skipWhiteSpace(row);var endPattern;try{endPattern=ITFReader.findGuardPattern(row,endStart,ITFReader.END_PATTERN_REVERSED[0]);}catch(error){if(error instanceof NotFoundException){endPattern=ITFReader.findGuardPattern(row,endStart,ITFReader.END_PATTERN_REVERSED[1]);}}// The start & end patterns must be pre/post fixed by a quiet zone. This
// zone must be at least 10 times the width of a narrow line.
// ref: http://www.barcode-1.net/i25code.html
this.validateQuietZone(row,endPattern[0]);// Now recalculate the indices of where the 'endblock' starts & stops to
// accommodate
// the reversed nature of the search
var temp=endPattern[0];endPattern[0]=row.getSize()-endPattern[1];endPattern[1]=row.getSize()-temp;return endPattern;}finally{// Put the row back the right way.
row.reverse();}}/*
/!**
* @param row row of black/white values to search
* @param rowOffset position to start search
* @param pattern pattern of counts of number of black and white pixels that are
* being searched for as a pattern
* @return start/end horizontal offset of guard pattern, as an array of two
* ints
* @throws NotFoundException if pattern is not found
*!/*/}],[{key:"decodeMiddle",value:function decodeMiddle(row,payloadStart,payloadEnd,resultString){// Digits are interleaved in pairs - 5 black lines for one digit, and the
// 5
// interleaved white lines for the second digit.
// Therefore, need to scan 10 lines and then
// split these into two arrays
var counterDigitPair=new Int32Array(10);// 10
var counterBlack=new Int32Array(5);// 5
var counterWhite=new Int32Array(5);// 5
counterDigitPair.fill(0);counterBlack.fill(0);counterWhite.fill(0);while(payloadStart<payloadEnd){// Get 10 runs of black/white.
OneDReader.recordPattern(row,payloadStart,counterDigitPair);// Split them into each array
for(var k=0;k<5;k++){var twoK=2*k;counterBlack[k]=counterDigitPair[twoK];counterWhite[k]=counterDigitPair[twoK+1];}var bestMatch=ITFReader.decodeDigit(counterBlack);resultString.append(bestMatch.toString());bestMatch=this.decodeDigit(counterWhite);resultString.append(bestMatch.toString());counterDigitPair.forEach(function(counterDigit){payloadStart+=counterDigit;});}}},{key:"skipWhiteSpace",value:function skipWhiteSpace(row){var width=row.getSize();var endStart=row.getNextSet(0);if(endStart===width){throw new NotFoundException();}return endStart;}},{key:"findGuardPattern",value:function findGuardPattern(row,rowOffset,pattern){var patternLength=pattern.length;var counters=new Int32Array(patternLength);var width=row.getSize();var isWhite=false;var counterPosition=0;var patternStart=rowOffset;counters.fill(0);for(var x=rowOffset;x<width;x++){if(row.get(x)!==isWhite){counters[counterPosition]++;}else{if(counterPosition===patternLength-1){if(OneDReader.patternMatchVariance(counters,pattern,ITFReader.MAX_INDIVIDUAL_VARIANCE)<ITFReader.MAX_AVG_VARIANCE){return[patternStart,x];}patternStart+=counters[0]+counters[1];System.arraycopy(counters,2,counters,0,counterPosition-1);counters[counterPosition-1]=0;counters[counterPosition]=0;counterPosition--;}else{counterPosition++;}counters[counterPosition]=1;isWhite=!isWhite;}}throw new NotFoundException();}/*/!**
* Attempts to decode a sequence of ITF black/white lines into single
* digit.
*
* @param counters the counts of runs of observed black/white/black/... values
* @return The decoded digit
* @throws NotFoundException if digit cannot be decoded
*!/*/},{key:"decodeDigit",value:function decodeDigit(counters){var bestVariance=ITFReader.MAX_AVG_VARIANCE;// worst variance we'll accept
var bestMatch=-1;var max=ITFReader.PATTERNS.length;for(var i=0;i<max;i++){var pattern=ITFReader.PATTERNS[i];var variance=OneDReader.patternMatchVariance(counters,pattern,ITFReader.MAX_INDIVIDUAL_VARIANCE);if(variance<bestVariance){bestVariance=variance;bestMatch=i;}else if(variance===bestVariance){// if we find a second 'best match' with the same variance, we can not reliably report to have a suitable match
bestMatch=-1;}}if(bestMatch>=0){return bestMatch%10;}else{throw new NotFoundException();}}}]);return ITFReader;}(OneDReader);ITFReader.PATTERNS=[Int32Array.from([1,1,2,2,1]),Int32Array.from([2,1,1,1,2]),Int32Array.from([1,2,1,1,2]),Int32Array.from([2,2,1,1,1]),Int32Array.from([1,1,2,1,2]),Int32Array.from([2,1,2,1,1]),Int32Array.from([1,2,2,1,1]),Int32Array.from([1,1,1,2,2]),Int32Array.from([2,1,1,2,1]),Int32Array.from([1,2,1,2,1]),Int32Array.from([1,1,3,3,1]),Int32Array.from([3,1,1,1,3]),Int32Array.from([1,3,1,1,3]),Int32Array.from([3,3,1,1,1]),Int32Array.from([1,1,3,1,3]),Int32Array.from([3,1,3,1,1]),Int32Array.from([1,3,3,1,1]),Int32Array.from([1,1,1,3,3]),Int32Array.from([3,1,1,3,1]),Int32Array.from([1,3,1,3,1])// 9
];ITFReader.MAX_AVG_VARIANCE=0.38;ITFReader.MAX_INDIVIDUAL_VARIANCE=0.5;/* /!** Valid ITF lengths. Anything longer than the largest value is also allowed. *!/*/ITFReader.DEFAULT_ALLOWED_LENGTHS=[6,8,10,12,14];/*/!**
* Start/end guard pattern.
*
* Note: The end pattern is reversed because the row is reversed before
* searching for the END_PATTERN
*!/*/ITFReader.START_PATTERN=Int32Array.from([1,1,1,1]);ITFReader.END_PATTERN_REVERSED=[Int32Array.from([1,1,2]),Int32Array.from([1,1,3])// 3x
];/**
* <p>Encapsulates functionality and implementation that is common to UPC and EAN families
* of one-dimensional barcodes.</p>
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
* @author alasdair@google.com (Alasdair Mackintosh)
*/var AbstractUPCEANReader=/*#__PURE__*/function(_OneDReader4){_inherits(AbstractUPCEANReader,_OneDReader4);var _super25=_createSuper(AbstractUPCEANReader);function AbstractUPCEANReader(){var _this17;_classCallCheck(this,AbstractUPCEANReader);_this17=_super25.apply(this,arguments);_this17.decodeRowStringBuffer='';return _this17;}_createClass(AbstractUPCEANReader,null,[{key:"findStartGuardPattern",value:function findStartGuardPattern(row){var foundStart=false;var startRange;var nextStart=0;var counters=Int32Array.from([0,0,0]);while(!foundStart){counters=Int32Array.from([0,0,0]);startRange=AbstractUPCEANReader.findGuardPattern(row,nextStart,false,this.START_END_PATTERN,counters);var start=startRange[0];nextStart=startRange[1];var quietStart=start-(nextStart-start);if(quietStart>=0){foundStart=row.isRange(quietStart,start,false);}}return startRange;}},{key:"checkChecksum",value:function checkChecksum(s){return AbstractUPCEANReader.checkStandardUPCEANChecksum(s);}},{key:"checkStandardUPCEANChecksum",value:function checkStandardUPCEANChecksum(s){var length=s.length;if(length===0)return false;var check=parseInt(s.charAt(length-1),10);return AbstractUPCEANReader.getStandardUPCEANChecksum(s.substring(0,length-1))===check;}},{key:"getStandardUPCEANChecksum",value:function getStandardUPCEANChecksum(s){var length=s.length;var sum=0;for(var i=length-1;i>=0;i-=2){var digit=s.charAt(i).charCodeAt(0)-'0'.charCodeAt(0);if(digit<0||digit>9){throw new FormatException();}sum+=digit;}sum*=3;for(var _i15=length-2;_i15>=0;_i15-=2){var _digit=s.charAt(_i15).charCodeAt(0)-'0'.charCodeAt(0);if(_digit<0||_digit>9){throw new FormatException();}sum+=_digit;}return(1000-sum)%10;}},{key:"decodeEnd",value:function decodeEnd(row,endStart){return AbstractUPCEANReader.findGuardPattern(row,endStart,false,AbstractUPCEANReader.START_END_PATTERN,new Int32Array(AbstractUPCEANReader.START_END_PATTERN.length).fill(0));}/**
* @throws NotFoundException
*/},{key:"findGuardPatternWithoutCounters",value:function findGuardPatternWithoutCounters(row,rowOffset,whiteFirst,pattern){return this.findGuardPattern(row,rowOffset,whiteFirst,pattern,new Int32Array(pattern.length));}/**
* @param row row of black/white values to search
* @param rowOffset position to start search
* @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
* pixel counts, otherwise, it is interpreted as black/white/black/...
* @param pattern pattern of counts of number of black and white pixels that are being
* searched for as a pattern
* @param counters array of counters, as long as pattern, to re-use
* @return start/end horizontal offset of guard pattern, as an array of two ints
* @throws NotFoundException if pattern is not found
*/},{key:"findGuardPattern",value:function findGuardPattern(row,rowOffset,whiteFirst,pattern,counters){var width=row.getSize();rowOffset=whiteFirst?row.getNextUnset(rowOffset):row.getNextSet(rowOffset);var counterPosition=0;var patternStart=rowOffset;var patternLength=pattern.length;var isWhite=whiteFirst;for(var x=rowOffset;x<width;x++){if(row.get(x)!==isWhite){counters[counterPosition]++;}else{if(counterPosition===patternLength-1){if(OneDReader.patternMatchVariance(counters,pattern,AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE)<AbstractUPCEANReader.MAX_AVG_VARIANCE){return Int32Array.from([patternStart,x]);}patternStart+=counters[0]+counters[1];var slice=counters.slice(2,counters.length-1);for(var i=0;i<counterPosition-1;i++){counters[i]=slice[i];}counters[counterPosition-1]=0;counters[counterPosition]=0;counterPosition--;}else{counterPosition++;}counters[counterPosition]=1;isWhite=!isWhite;}}throw new NotFoundException();}},{key:"decodeDigit",value:function decodeDigit(row,counters,rowOffset,patterns){this.recordPattern(row,rowOffset,counters);var bestVariance=this.MAX_AVG_VARIANCE;var bestMatch=-1;var max=patterns.length;for(var i=0;i<max;i++){var pattern=patterns[i];var variance=OneDReader.patternMatchVariance(counters,pattern,AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE);if(variance<bestVariance){bestVariance=variance;bestMatch=i;}}if(bestMatch>=0){return bestMatch;}else{throw new NotFoundException();}}}]);return AbstractUPCEANReader;}(OneDReader);// These two values are critical for determining how permissive the decoding will be.
// We've arrived at these values through a lot of trial and error. Setting them any higher
// lets false positives creep in quickly.
AbstractUPCEANReader.MAX_AVG_VARIANCE=0.48;AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE=0.7;/**
* Start/end guard pattern.
*/AbstractUPCEANReader.START_END_PATTERN=Int32Array.from([1,1,1]);/**
* Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
*/AbstractUPCEANReader.MIDDLE_PATTERN=Int32Array.from([1,1,1,1,1]);/**
* end guard pattern.
*/AbstractUPCEANReader.END_PATTERN=Int32Array.from([1,1,1,1,1,1]);/**
* "Odd", or "L" patterns used to encode UPC/EAN digits.
*/AbstractUPCEANReader.L_PATTERNS=[Int32Array.from([3,2,1,1]),Int32Array.from([2,2,2,1]),Int32Array.from([2,1,2,2]),Int32Array.from([1,4,1,1]),Int32Array.from([1,1,3,2]),Int32Array.from([1,2,3,1]),Int32Array.from([1,1,1,4]),Int32Array.from([1,3,1,2]),Int32Array.from([1,2,1,3]),Int32Array.from([3,1,1,2])];/**
* @see UPCEANExtension2Support
*/var UPCEANExtension5Support=/*#__PURE__*/function(){function UPCEANExtension5Support(){_classCallCheck(this,UPCEANExtension5Support);this.CHECK_DIGIT_ENCODINGS=[0x18,0x14,0x12,0x11,0x0C,0x06,0x03,0x0A,0x09,0x05];this.decodeMiddleCounters=Int32Array.from([0,0,0,0]);this.decodeRowStringBuffer='';}_createClass(UPCEANExtension5Support,[{key:"decodeRow",value:function decodeRow(rowNumber,row,extensionStartRange){var result=this.decodeRowStringBuffer;var end=this.decodeMiddle(row,extensionStartRange,result);var resultString=result.toString();var extensionData=UPCEANExtension5Support.parseExtensionString(resultString);var resultPoints=[new ResultPoint((extensionStartRange[0]+extensionStartRange[1])/2.0,rowNumber),new ResultPoint(end,rowNumber)];var extensionResult=new Result(resultString,null,0,resultPoints,BarcodeFormat$1.UPC_EAN_EXTENSION,new Date().getTime());if(extensionData!=null){extensionResult.putAllMetadata(extensionData);}return extensionResult;}},{key:"decodeMiddle",value:function decodeMiddle(row,startRange,resultString){var counters=this.decodeMiddleCounters;counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;var end=row.getSize();var rowOffset=startRange[1];var lgPatternFound=0;for(var x=0;x<5&&rowOffset<end;x++){var bestMatch=AbstractUPCEANReader.decodeDigit(row,counters,rowOffset,AbstractUPCEANReader.L_AND_G_PATTERNS);resultString+=String.fromCharCode('0'.charCodeAt(0)+bestMatch%10);var _iterator7=_createForOfIteratorHelper(counters),_step7;try{for(_iterator7.s();!(_step7=_iterator7.n()).done;){var counter=_step7.value;rowOffset+=counter;}}catch(err){_iterator7.e(err);}finally{_iterator7.f();}if(bestMatch>=10){lgPatternFound|=1<<4-x;}if(x!==4){// Read off separator if not last
rowOffset=row.getNextSet(rowOffset);rowOffset=row.getNextUnset(rowOffset);}}if(resultString.length!==5){throw new NotFoundException();}var checkDigit=this.determineCheckDigit(lgPatternFound);if(UPCEANExtension5Support.extensionChecksum(resultString.toString())!==checkDigit){throw new NotFoundException();}return rowOffset;}},{key:"determineCheckDigit",value:function determineCheckDigit(lgPatternFound){for(var d=0;d<10;d++){if(lgPatternFound===this.CHECK_DIGIT_ENCODINGS[d]){return d;}}throw new NotFoundException();}}],[{key:"extensionChecksum",value:function extensionChecksum(s){var length=s.length;var sum=0;for(var i=length-2;i>=0;i-=2){sum+=s.charAt(i).charCodeAt(0)-'0'.charCodeAt(0);}sum*=3;for(var _i16=length-1;_i16>=0;_i16-=2){sum+=s.charAt(_i16).charCodeAt(0)-'0'.charCodeAt(0);}sum*=3;return sum%10;}},{key:"parseExtensionString",value:function parseExtensionString(raw){if(raw.length!==5){return null;}var value=UPCEANExtension5Support.parseExtension5String(raw);if(value==null){return null;}return new Map([[ResultMetadataType$1.SUGGESTED_PRICE,value]]);}},{key:"parseExtension5String",value:function parseExtension5String(raw){var currency;switch(raw.charAt(0)){case'0':currency='£';break;case'5':currency='$';break;case'9':// Reference: http://www.jollytech.com
switch(raw){case'90000':// No suggested retail price
return null;case'99991':// Complementary
return'0.00';case'99990':return'Used';}// Otherwise... unknown currency?
currency='';break;default:currency='';break;}var rawAmount=parseInt(raw.substring(1));var unitsString=(rawAmount/100).toString();var hundredths=rawAmount%100;var hundredthsString=hundredths<10?'0'+hundredths:hundredths.toString();// fixme
return currency+unitsString+'.'+hundredthsString;}}]);return UPCEANExtension5Support;}();/**
* @see UPCEANExtension5Support
*/var UPCEANExtension2Support=/*#__PURE__*/function(){function UPCEANExtension2Support(){_classCallCheck(this,UPCEANExtension2Support);this.decodeMiddleCounters=Int32Array.from([0,0,0,0]);this.decodeRowStringBuffer='';}_createClass(UPCEANExtension2Support,[{key:"decodeRow",value:function decodeRow(rowNumber,row,extensionStartRange){var result=this.decodeRowStringBuffer;var end=this.decodeMiddle(row,extensionStartRange,result);var resultString=result.toString();var extensionData=UPCEANExtension2Support.parseExtensionString(resultString);var resultPoints=[new ResultPoint((extensionStartRange[0]+extensionStartRange[1])/2.0,rowNumber),new ResultPoint(end,rowNumber)];var extensionResult=new Result(resultString,null,0,resultPoints,BarcodeFormat$1.UPC_EAN_EXTENSION,new Date().getTime());if(extensionData!=null){extensionResult.putAllMetadata(extensionData);}return extensionResult;}},{key:"decodeMiddle",value:function decodeMiddle(row,startRange,resultString){var counters=this.decodeMiddleCounters;counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;var end=row.getSize();var rowOffset=startRange[1];var checkParity=0;for(var x=0;x<2&&rowOffset<end;x++){var bestMatch=AbstractUPCEANReader.decodeDigit(row,counters,rowOffset,AbstractUPCEANReader.L_AND_G_PATTERNS);resultString+=String.fromCharCode('0'.charCodeAt(0)+bestMatch%10);var _iterator8=_createForOfIteratorHelper(counters),_step8;try{for(_iterator8.s();!(_step8=_iterator8.n()).done;){var counter=_step8.value;rowOffset+=counter;}}catch(err){_iterator8.e(err);}finally{_iterator8.f();}if(bestMatch>=10){checkParity|=1<<1-x;}if(x!==1){// Read off separator if not last
rowOffset=row.getNextSet(rowOffset);rowOffset=row.getNextUnset(rowOffset);}}if(resultString.length!==2){throw new NotFoundException();}if(parseInt(resultString.toString())%4!==checkParity){throw new NotFoundException();}return rowOffset;}}],[{key:"parseExtensionString",value:function parseExtensionString(raw){if(raw.length!==2){return null;}return new Map([[ResultMetadataType$1.ISSUE_NUMBER,parseInt(raw)]]);}}]);return UPCEANExtension2Support;}();var UPCEANExtensionSupport=/*#__PURE__*/function(){function UPCEANExtensionSupport(){_classCallCheck(this,UPCEANExtensionSupport);}_createClass(UPCEANExtensionSupport,null,[{key:"decodeRow",value:function decodeRow(rowNumber,row,rowOffset){var extensionStartRange=AbstractUPCEANReader.findGuardPattern(row,rowOffset,false,this.EXTENSION_START_PATTERN,new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));try{// return null;
var fiveSupport=new UPCEANExtension5Support();return fiveSupport.decodeRow(rowNumber,row,extensionStartRange);}catch(err){// return null;
var twoSupport=new UPCEANExtension2Support();return twoSupport.decodeRow(rowNumber,row,extensionStartRange);}}}]);return UPCEANExtensionSupport;}();UPCEANExtensionSupport.EXTENSION_START_PATTERN=Int32Array.from([1,1,2]);/**
* <p>Encapsulates functionality and implementation that is common to UPC and EAN families
* of one-dimensional barcodes.</p>
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
* @author alasdair@google.com (Alasdair Mackintosh)
*/var UPCEANReader=/*#__PURE__*/function(_AbstractUPCEANReader){_inherits(UPCEANReader,_AbstractUPCEANReader);var _super26=_createSuper(UPCEANReader);function UPCEANReader(){var _this18;_classCallCheck(this,UPCEANReader);_this18=_super26.call(this);_this18.decodeRowStringBuffer='';UPCEANReader.L_AND_G_PATTERNS=UPCEANReader.L_PATTERNS.map(function(arr){return Int32Array.from(arr);});for(var i=10;i<20;i++){var widths=UPCEANReader.L_PATTERNS[i-10];var reversedWidths=new Int32Array(widths.length);for(var j=0;j<widths.length;j++){reversedWidths[j]=widths[widths.length-j-1];}UPCEANReader.L_AND_G_PATTERNS[i]=reversedWidths;}return _this18;}_createClass(UPCEANReader,[{key:"decodeRow",value:function decodeRow(rowNumber,row,hints){var startGuardRange=UPCEANReader.findStartGuardPattern(row);var resultPointCallback=hints==null?null:hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);if(resultPointCallback!=null){var _resultPoint=new ResultPoint((startGuardRange[0]+startGuardRange[1])/2.0,rowNumber);resultPointCallback.foundPossibleResultPoint(_resultPoint);}var budello=this.decodeMiddle(row,startGuardRange,this.decodeRowStringBuffer);var endStart=budello.rowOffset;var result=budello.resultString;if(resultPointCallback!=null){var _resultPoint2=new ResultPoint(endStart,rowNumber);resultPointCallback.foundPossibleResultPoint(_resultPoint2);}var endRange=this.decodeEnd(row,endStart);if(resultPointCallback!=null){var _resultPoint3=new ResultPoint((endRange[0]+endRange[1])/2.0,rowNumber);resultPointCallback.foundPossibleResultPoint(_resultPoint3);}// Make sure there is a quiet zone at least as big as the end pattern after the barcode. The
// spec might want more whitespace, but in practice this is the maximum we can count on.
var end=endRange[1];var quietEnd=end+(end-endRange[0]);if(quietEnd>=row.getSize()||!row.isRange(end,quietEnd,false)){throw new NotFoundException();}var resultString=result.toString();// UPC/EAN should never be less than 8 chars anyway
if(resultString.length<8){throw new FormatException();}if(!UPCEANReader.checkChecksum(resultString)){throw new ChecksumException();}var left=(startGuardRange[1]+startGuardRange[0])/2.0;var right=(endRange[1]+endRange[0])/2.0;var format=this.getBarcodeFormat();var resultPoint=[new ResultPoint(left,rowNumber),new ResultPoint(right,rowNumber)];var decodeResult=new Result(resultString,null,0,resultPoint,format,new Date().getTime());var extensionLength=0;try{var extensionResult=UPCEANExtensionSupport.decodeRow(rowNumber,row,endRange[1]);decodeResult.putMetadata(ResultMetadataType$1.UPC_EAN_EXTENSION,extensionResult.getText());decodeResult.putAllMetadata(extensionResult.getResultMetadata());decodeResult.addResultPoints(extensionResult.getResultPoints());extensionLength=extensionResult.getText().length;}catch(ignoreError){}var allowedExtensions=hints==null?null:hints.get(DecodeHintType$1.ALLOWED_EAN_EXTENSIONS);if(allowedExtensions!=null){var valid=false;for(var length in allowedExtensions){if(extensionLength.toString()===length){// check me
valid=true;break;}}if(!valid){throw new NotFoundException();}}return decodeResult;}},{key:"decodeEnd",value:function decodeEnd(row,endStart){return UPCEANReader.findGuardPattern(row,endStart,false,UPCEANReader.START_END_PATTERN,new Int32Array(UPCEANReader.START_END_PATTERN.length).fill(0));}}],[{key:"checkChecksum",value:function checkChecksum(s){return UPCEANReader.checkStandardUPCEANChecksum(s);}},{key:"checkStandardUPCEANChecksum",value:function checkStandardUPCEANChecksum(s){var length=s.length;if(length===0)return false;var check=parseInt(s.charAt(length-1),10);return UPCEANReader.getStandardUPCEANChecksum(s.substring(0,length-1))===check;}},{key:"getStandardUPCEANChecksum",value:function getStandardUPCEANChecksum(s){var length=s.length;var sum=0;for(var i=length-1;i>=0;i-=2){var digit=s.charAt(i).charCodeAt(0)-'0'.charCodeAt(0);if(digit<0||digit>9){throw new FormatException();}sum+=digit;}sum*=3;for(var _i17=length-2;_i17>=0;_i17-=2){var _digit2=s.charAt(_i17).charCodeAt(0)-'0'.charCodeAt(0);if(_digit2<0||_digit2>9){throw new FormatException();}sum+=_digit2;}return(1000-sum)%10;}}]);return UPCEANReader;}(AbstractUPCEANReader);/**
* <p>Implements decoding of the EAN-13 format.</p>
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
* @author alasdair@google.com (Alasdair Mackintosh)
*/var EAN13Reader=/*#__PURE__*/function(_UPCEANReader){_inherits(EAN13Reader,_UPCEANReader);var _super27=_createSuper(EAN13Reader);function EAN13Reader(){var _this19;_classCallCheck(this,EAN13Reader);_this19=_super27.call(this);_this19.decodeMiddleCounters=Int32Array.from([0,0,0,0]);return _this19;}_createClass(EAN13Reader,[{key:"decodeMiddle",value:function decodeMiddle(row,startRange,resultString){var counters=this.decodeMiddleCounters;counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;var end=row.getSize();var rowOffset=startRange[1];var lgPatternFound=0;for(var x=0;x<6&&rowOffset<end;x++){var bestMatch=UPCEANReader.decodeDigit(row,counters,rowOffset,UPCEANReader.L_AND_G_PATTERNS);resultString+=String.fromCharCode('0'.charCodeAt(0)+bestMatch%10);var _iterator9=_createForOfIteratorHelper(counters),_step9;try{for(_iterator9.s();!(_step9=_iterator9.n()).done;){var counter=_step9.value;rowOffset+=counter;}}catch(err){_iterator9.e(err);}finally{_iterator9.f();}if(bestMatch>=10){lgPatternFound|=1<<5-x;}}resultString=EAN13Reader.determineFirstDigit(resultString,lgPatternFound);var middleRange=UPCEANReader.findGuardPattern(row,rowOffset,true,UPCEANReader.MIDDLE_PATTERN,new Int32Array(UPCEANReader.MIDDLE_PATTERN.length).fill(0));rowOffset=middleRange[1];for(var _x9=0;_x9<6&&rowOffset<end;_x9++){var _bestMatch=UPCEANReader.decodeDigit(row,counters,rowOffset,UPCEANReader.L_PATTERNS);resultString+=String.fromCharCode('0'.charCodeAt(0)+_bestMatch);var _iterator10=_createForOfIteratorHelper(counters),_step10;try{for(_iterator10.s();!(_step10=_iterator10.n()).done;){var _counter4=_step10.value;rowOffset+=_counter4;}}catch(err){_iterator10.e(err);}finally{_iterator10.f();}}return{rowOffset:rowOffset,resultString:resultString};}},{key:"getBarcodeFormat",value:function getBarcodeFormat(){return BarcodeFormat$1.EAN_13;}}],[{key:"determineFirstDigit",value:function determineFirstDigit(resultString,lgPatternFound){for(var d=0;d<10;d++){if(lgPatternFound===this.FIRST_DIGIT_ENCODINGS[d]){resultString=String.fromCharCode('0'.charCodeAt(0)+d)+resultString;return resultString;}}throw new NotFoundException();}}]);return EAN13Reader;}(UPCEANReader);EAN13Reader.FIRST_DIGIT_ENCODINGS=[0x00,0x0B,0x0D,0xE,0x13,0x19,0x1C,0x15,0x16,0x1A];/**
* <p>Implements decoding of the EAN-8 format.</p>
*
* @author Sean Owen
*/var EAN8Reader=/*#__PURE__*/function(_UPCEANReader2){_inherits(EAN8Reader,_UPCEANReader2);var _super28=_createSuper(EAN8Reader);function EAN8Reader(){var _this20;_classCallCheck(this,EAN8Reader);_this20=_super28.call(this);_this20.decodeMiddleCounters=Int32Array.from([0,0,0,0]);return _this20;}_createClass(EAN8Reader,[{key:"decodeMiddle",value:function decodeMiddle(row,startRange,resultString){var counters=this.decodeMiddleCounters;counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;var end=row.getSize();var rowOffset=startRange[1];for(var x=0;x<4&&rowOffset<end;x++){var bestMatch=UPCEANReader.decodeDigit(row,counters,rowOffset,UPCEANReader.L_PATTERNS);resultString+=String.fromCharCode('0'.charCodeAt(0)+bestMatch);var _iterator11=_createForOfIteratorHelper(counters),_step11;try{for(_iterator11.s();!(_step11=_iterator11.n()).done;){var counter=_step11.value;rowOffset+=counter;}}catch(err){_iterator11.e(err);}finally{_iterator11.f();}}var middleRange=UPCEANReader.findGuardPattern(row,rowOffset,true,UPCEANReader.MIDDLE_PATTERN,new Int32Array(UPCEANReader.MIDDLE_PATTERN.length).fill(0));rowOffset=middleRange[1];for(var _x10=0;_x10<4&&rowOffset<end;_x10++){var _bestMatch2=UPCEANReader.decodeDigit(row,counters,rowOffset,UPCEANReader.L_PATTERNS);resultString+=String.fromCharCode('0'.charCodeAt(0)+_bestMatch2);var _iterator12=_createForOfIteratorHelper(counters),_step12;try{for(_iterator12.s();!(_step12=_iterator12.n()).done;){var _counter5=_step12.value;rowOffset+=_counter5;}}catch(err){_iterator12.e(err);}finally{_iterator12.f();}}return{rowOffset:rowOffset,resultString:resultString};}},{key:"getBarcodeFormat",value:function getBarcodeFormat(){return BarcodeFormat$1.EAN_8;}}]);return EAN8Reader;}(UPCEANReader);/**
* Encapsulates functionality and implementation that is common to all families
* of one-dimensional barcodes.
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
* @author sam2332 (Sam Rudloff)
*
* @source https://github.com/zxing/zxing/blob/3c96923276dd5785d58eb970b6ba3f80d36a9505/core/src/main/java/com/google/zxing/oned/UPCAReader.java
*
* @experimental
*/var UPCAReader=/*#__PURE__*/function(_UPCEANReader3){_inherits(UPCAReader,_UPCEANReader3);var _super29=_createSuper(UPCAReader);function UPCAReader(){var _this21;_classCallCheck(this,UPCAReader);_this21=_super29.apply(this,arguments);_this21.ean13Reader=new EAN13Reader();return _this21;}// @Override
_createClass(UPCAReader,[{key:"getBarcodeFormat",value:function getBarcodeFormat(){return BarcodeFormat$1.UPC_A;}// Note that we don't try rotation without the try harder flag, even if rotation was supported.
// @Override
},{key:"decode",value:function decode(image,hints){return this.maybeReturnResult(this.ean13Reader.decode(image));}// @Override
},{key:"decodeRow",value:function decodeRow(rowNumber,row,hints){return this.maybeReturnResult(this.ean13Reader.decodeRow(rowNumber,row,hints));}// @Override
},{key:"decodeMiddle",value:function decodeMiddle(row,startRange,resultString){return this.ean13Reader.decodeMiddle(row,startRange,resultString);}},{key:"maybeReturnResult",value:function maybeReturnResult(result){var text=result.getText();if(text.charAt(0)==='0'){var upcaResult=new Result(text.substring(1),null,null,result.getResultPoints(),BarcodeFormat$1.UPC_A);if(result.getResultMetadata()!=null){upcaResult.putAllMetadata(result.getResultMetadata());}return upcaResult;}else{throw new NotFoundException();}}},{key:"reset",value:function reset(){this.ean13Reader.reset();}}]);return UPCAReader;}(UPCEANReader);/**
* <p>Implements decoding of the UPC-E format.</p>
* <p><a href="http://www.barcodeisland.com/upce.phtml">This</a> is a great reference for
* UPC-E information.</p>
*
* @author Sean Owen
*
* @source https://github.com/zxing/zxing/blob/3c96923276dd5785d58eb970b6ba3f80d36a9505/core/src/main/java/com/google/zxing/oned/UPCEReader.java
*
* @experimental
*/ /* final */var UPCEReader=/*#__PURE__*/function(_UPCEANReader4){_inherits(UPCEReader,_UPCEANReader4);var _super30=_createSuper(UPCEReader);function UPCEReader(){var _this22;_classCallCheck(this,UPCEReader);_this22=_super30.call(this);_this22.decodeMiddleCounters=new Int32Array(4);return _this22;}/**
* @throws NotFoundException
*/ // @Override
_createClass(UPCEReader,[{key:"decodeMiddle",value:function decodeMiddle(row,startRange,result){var counters=this.decodeMiddleCounters.map(function(x){return x;});counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;var end=row.getSize();var rowOffset=startRange[1];var lgPatternFound=0;for(var x=0;x<6&&rowOffset<end;x++){var bestMatch=UPCEReader.decodeDigit(row,counters,rowOffset,UPCEReader.L_AND_G_PATTERNS);result+=String.fromCharCode('0'.charCodeAt(0)+bestMatch%10);var _iterator13=_createForOfIteratorHelper(counters),_step13;try{for(_iterator13.s();!(_step13=_iterator13.n()).done;){var counter=_step13.value;rowOffset+=counter;}}catch(err){_iterator13.e(err);}finally{_iterator13.f();}if(bestMatch>=10){lgPatternFound|=1<<5-x;}}var resultString=UPCEReader.determineNumSysAndCheckDigit(result,lgPatternFound);return{rowOffset:rowOffset,resultString:resultString};}/**
* @throws NotFoundException
*/ // @Override
},{key:"decodeEnd",value:function decodeEnd(row,endStart){return UPCEReader.findGuardPatternWithoutCounters(row,endStart,true,UPCEReader.MIDDLE_END_PATTERN);}/**
* @throws FormatException
*/ // @Override
},{key:"checkChecksum",value:function checkChecksum(s){return UPCEANReader.checkChecksum(UPCEReader.convertUPCEtoUPCA(s));}/**
* @throws NotFoundException
*/},{key:"getBarcodeFormat",value:// @Override
function getBarcodeFormat(){return BarcodeFormat$1.UPC_E;}/**
* Expands a UPC-E value back into its full, equivalent UPC-A code value.
*
* @param upce UPC-E code as string of digits
* @return equivalent UPC-A code as string of digits
*/}],[{key:"determineNumSysAndCheckDigit",value:function determineNumSysAndCheckDigit(resultString,lgPatternFound){for(var numSys=0;numSys<=1;numSys++){for(var d=0;d<10;d++){if(lgPatternFound===this.NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d]){var prefix=String.fromCharCode('0'.charCodeAt(0)+numSys);var suffix=String.fromCharCode('0'.charCodeAt(0)+d);return prefix+resultString+suffix;}}}throw NotFoundException.getNotFoundInstance();}},{key:"convertUPCEtoUPCA",value:function convertUPCEtoUPCA(upce){// the following line is equivalent to upce.getChars(1, 7, upceChars, 0);
var upceChars=upce.slice(1,7).split('').map(function(x){return x.charCodeAt(0);});var result=new StringBuilder(/*12*/);result.append(upce.charAt(0));var lastChar=upceChars[5];switch(lastChar){case 0:case 1:case 2:result.appendChars(upceChars,0,2);result.append(lastChar);result.append('0000');result.appendChars(upceChars,2,3);break;case 3:result.appendChars(upceChars,0,3);result.append('00000');result.appendChars(upceChars,3,2);break;case 4:result.appendChars(upceChars,0,4);result.append('00000');result.append(upceChars[4]);break;default:result.appendChars(upceChars,0,5);result.append('0000');result.append(lastChar);break;}// Only append check digit in conversion if supplied
if(upce.length>=8){result.append(upce.charAt(7));}return result.toString();}}]);return UPCEReader;}(UPCEANReader);/**
* The pattern that marks the middle, and end, of a UPC-E pattern.
* There is no "second half" to a UPC-E barcode.
*/UPCEReader.MIDDLE_END_PATTERN=Int32Array.from([1,1,1,1,1,1]);// For an UPC-E barcode, the final digit is represented by the parities used
// to encode the middle six digits, according to the table below.
//
// Parity of next 6 digits
// Digit 0 1 2 3 4 5
// 0 Even Even Even Odd Odd Odd
// 1 Even Even Odd Even Odd Odd
// 2 Even Even Odd Odd Even Odd
// 3 Even Even Odd Odd Odd Even
// 4 Even Odd Even Even Odd Odd
// 5 Even Odd Odd Even Even Odd
// 6 Even Odd Odd Odd Even Even
// 7 Even Odd Even Odd Even Odd
// 8 Even Odd Even Odd Odd Even
// 9 Even Odd Odd Even Odd Even
//
// The encoding is represented by the following array, which is a bit pattern
// using Odd = 0 and Even = 1. For example, 5 is represented by:
//
// Odd Even Even Odd Odd Even
// in binary:
// 0 1 1 0 0 1 == 0x19
//
/**
* See {@link #L_AND_G_PATTERNS}; these values similarly represent patterns of
* even-odd parity encodings of digits that imply both the number system (0 or 1)
* used, and the check digit.
*/UPCEReader.NUMSYS_AND_CHECK_DIGIT_PATTERNS=[Int32Array.from([0x38,0x34,0x32,0x31,0x2C,0x26,0x23,0x2A,0x29,0x25]),Int32Array.from([0x07,0x0B,0x0D,0x0E,0x13,0x19,0x1C,0x15,0x16,0x1A])];/**
* <p>A reader that can read all available UPC/EAN formats. If a caller wants to try to
* read all such formats, it is most efficient to use this implementation rather than invoke
* individual readers.</p>
*
* @author Sean Owen
*/var MultiFormatUPCEANReader=/*#__PURE__*/function(_OneDReader5){_inherits(MultiFormatUPCEANReader,_OneDReader5);var _super31=_createSuper(MultiFormatUPCEANReader);function MultiFormatUPCEANReader(hints){var _this23;_classCallCheck(this,MultiFormatUPCEANReader);_this23=_super31.call(this);var possibleFormats=hints==null?null:hints.get(DecodeHintType$1.POSSIBLE_FORMATS);var readers=[];if(!isNullOrUndefined(possibleFormats)){if(possibleFormats.indexOf(BarcodeFormat$1.EAN_13)>-1){readers.push(new EAN13Reader());}if(possibleFormats.indexOf(BarcodeFormat$1.UPC_A)>-1){readers.push(new UPCAReader());}if(possibleFormats.indexOf(BarcodeFormat$1.EAN_8)>-1){readers.push(new EAN8Reader());}if(possibleFormats.indexOf(BarcodeFormat$1.UPC_E)>-1){readers.push(new UPCEReader());}}else{// No hints provided.
readers.push(new EAN13Reader());readers.push(new UPCAReader());readers.push(new EAN8Reader());readers.push(new UPCEReader());}_this23.readers=readers;return _this23;}_createClass(MultiFormatUPCEANReader,[{key:"decodeRow",value:function decodeRow(rowNumber,row,hints){var _iterator14=_createForOfIteratorHelper(this.readers),_step14;try{for(_iterator14.s();!(_step14=_iterator14.n()).done;){var reader=_step14.value;try{// const result: Result = reader.decodeRow(rowNumber, row, startGuardPattern, hints);
var result=reader.decodeRow(rowNumber,row,hints);// Special case: a 12-digit code encoded in UPC-A is identical to a "0"
// followed by those 12 digits encoded as EAN-13. Each will recognize such a code,
// UPC-A as a 12-digit string and EAN-13 as a 13-digit string starting with "0".
// Individually these are correct and their readers will both read such a code
// and correctly call it EAN-13, or UPC-A, respectively.
//
// In this case, if we've been looking for both types, we'd like to call it
// a UPC-A code. But for efficiency we only run the EAN-13 decoder to also read
// UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A
// result if appropriate.
//
// But, don't return UPC-A if UPC-A was not a requested format!
var ean13MayBeUPCA=result.getBarcodeFormat()===BarcodeFormat$1.EAN_13&&result.getText().charAt(0)==='0';// @SuppressWarnings("unchecked")
var possibleFormats=hints==null?null:hints.get(DecodeHintType$1.POSSIBLE_FORMATS);var canReturnUPCA=possibleFormats==null||possibleFormats.includes(BarcodeFormat$1.UPC_A);if(ean13MayBeUPCA&&canReturnUPCA){var _rawBytes=result.getRawBytes();// Transfer the metadata across
var resultUPCA=new Result(result.getText().substring(1),_rawBytes,_rawBytes?_rawBytes.length:null,result.getResultPoints(),BarcodeFormat$1.UPC_A);resultUPCA.putAllMetadata(result.getResultMetadata());return resultUPCA;}return result;}catch(err){// continue;
}}}catch(err){_iterator14.e(err);}finally{_iterator14.f();}throw new NotFoundException();}},{key:"reset",value:function reset(){var _iterator15=_createForOfIteratorHelper(this.readers),_step15;try{for(_iterator15.s();!(_step15=_iterator15.n()).done;){var reader=_step15.value;reader.reset();}}catch(err){_iterator15.e(err);}finally{_iterator15.f();}}}]);return MultiFormatUPCEANReader;}(OneDReader);// import Integer from '../../util/Integer';
// import Float from '../../util/Float';
var AbstractRSSReader=/*#__PURE__*/function(_OneDReader6){_inherits(AbstractRSSReader,_OneDReader6);var _super32=_createSuper(AbstractRSSReader);function AbstractRSSReader(){var _this24;_classCallCheck(this,AbstractRSSReader);_this24=_super32.call(this);_this24.decodeFinderCounters=new Int32Array(4);_this24.dataCharacterCounters=new Int32Array(8);_this24.oddRoundingErrors=new Array(4);_this24.evenRoundingErrors=new Array(4);_this24.oddCounts=new Array(_this24.dataCharacterCounters.length/2);_this24.evenCounts=new Array(_this24.dataCharacterCounters.length/2);return _this24;}_createClass(AbstractRSSReader,[{key:"getDecodeFinderCounters",value:function getDecodeFinderCounters(){return this.decodeFinderCounters;}},{key:"getDataCharacterCounters",value:function getDataCharacterCounters(){return this.dataCharacterCounters;}},{key:"getOddRoundingErrors",value:function getOddRoundingErrors(){return this.oddRoundingErrors;}},{key:"getEvenRoundingErrors",value:function getEvenRoundingErrors(){return this.evenRoundingErrors;}},{key:"getOddCounts",value:function getOddCounts(){return this.oddCounts;}},{key:"getEvenCounts",value:function getEvenCounts(){return this.evenCounts;}},{key:"parseFinderValue",value:function parseFinderValue(counters,finderPatterns){for(var value=0;value<finderPatterns.length;value++){if(OneDReader.patternMatchVariance(counters,finderPatterns[value],AbstractRSSReader.MAX_INDIVIDUAL_VARIANCE)<AbstractRSSReader.MAX_AVG_VARIANCE){return value;}}throw new NotFoundException();}/**
* @param array values to sum
* @return sum of values
* @deprecated call {@link MathUtils#sum(int[])}
*/}],[{key:"count",value:function count(array){return MathUtils.sum(new Int32Array(array));}},{key:"increment",value:function increment(array,errors){var index=0;var biggestError=errors[0];for(var i=1;i<array.length;i++){if(errors[i]>biggestError){biggestError=errors[i];index=i;}}array[index]++;}},{key:"decrement",value:function decrement(array,errors){var index=0;var biggestError=errors[0];for(var i=1;i<array.length;i++){if(errors[i]<biggestError){biggestError=errors[i];index=i;}}array[index]--;}},{key:"isFinderPattern",value:function isFinderPattern(counters){var firstTwoSum=counters[0]+counters[1];var sum=firstTwoSum+counters[2]+counters[3];var ratio=firstTwoSum/sum;if(ratio>=AbstractRSSReader.MIN_FINDER_PATTERN_RATIO&&ratio<=AbstractRSSReader.MAX_FINDER_PATTERN_RATIO){// passes ratio test in spec, but see if the counts are unreasonable
var minCounter=Number.MAX_SAFE_INTEGER;var maxCounter=Number.MIN_SAFE_INTEGER;var _iterator16=_createForOfIteratorHelper(counters),_step16;try{for(_iterator16.s();!(_step16=_iterator16.n()).done;){var counter=_step16.value;if(counter>maxCounter){maxCounter=counter;}if(counter<minCounter){minCounter=counter;}}}catch(err){_iterator16.e(err);}finally{_iterator16.f();}return maxCounter<10*minCounter;}return false;}}]);return AbstractRSSReader;}(OneDReader);AbstractRSSReader.MAX_AVG_VARIANCE=0.2;AbstractRSSReader.MAX_INDIVIDUAL_VARIANCE=0.45;AbstractRSSReader.MIN_FINDER_PATTERN_RATIO=9.5/12.0;AbstractRSSReader.MAX_FINDER_PATTERN_RATIO=12.5/14.0;var DataCharacter=/*#__PURE__*/function(){function DataCharacter(value,checksumPortion){_classCallCheck(this,DataCharacter);this.value=value;this.checksumPortion=checksumPortion;}_createClass(DataCharacter,[{key:"getValue",value:function getValue(){return this.value;}},{key:"getChecksumPortion",value:function getChecksumPortion(){return this.checksumPortion;}},{key:"toString",value:function toString(){return this.value+'('+this.checksumPortion+')';}},{key:"equals",value:function equals(o){if(!(o instanceof DataCharacter)){return false;}var that=o;return this.value===that.value&&this.checksumPortion===that.checksumPortion;}},{key:"hashCode",value:function hashCode(){return this.value^this.checksumPortion;}}]);return DataCharacter;}();var FinderPattern=/*#__PURE__*/function(){function FinderPattern(value,startEnd,start,end,rowNumber){_classCallCheck(this,FinderPattern);this.value=value;this.startEnd=startEnd;this.value=value;this.startEnd=startEnd;this.resultPoints=new Array();this.resultPoints.push(new ResultPoint(start,rowNumber));this.resultPoints.push(new ResultPoint(end,rowNumber));}_createClass(FinderPattern,[{key:"getValue",value:function getValue(){return this.value;}},{key:"getStartEnd",value:function getStartEnd(){return this.startEnd;}},{key:"getResultPoints",value:function getResultPoints(){return this.resultPoints;}},{key:"equals",value:function equals(o){if(!(o instanceof FinderPattern)){return false;}var that=o;return this.value===that.value;}},{key:"hashCode",value:function hashCode(){return this.value;}}]);return FinderPattern;}();/**
* RSS util functions.
*/var RSSUtils=/*#__PURE__*/function(){function RSSUtils(){_classCallCheck(this,RSSUtils);}_createClass(RSSUtils,null,[{key:"getRSSvalue",value:function getRSSvalue(widths,maxWidth,noNarrow){var n=0;var _iterator17=_createForOfIteratorHelper(widths),_step17;try{for(_iterator17.s();!(_step17=_iterator17.n()).done;){var width=_step17.value;n+=width;}}catch(err){_iterator17.e(err);}finally{_iterator17.f();}var val=0;var narrowMask=0;var elements=widths.length;for(var bar=0;bar<elements-1;bar++){var elmWidth=void 0;for(elmWidth=1,narrowMask|=1<<bar;elmWidth<widths[bar];elmWidth++,narrowMask&=~(1<<bar)){var subVal=RSSUtils.combins(n-elmWidth-1,elements-bar-2);if(noNarrow&&narrowMask===0&&n-elmWidth-(elements-bar-1)>=elements-bar-1){subVal-=RSSUtils.combins(n-elmWidth-(elements-bar),elements-bar-2);}if(elements-bar-1>1){var lessVal=0;for(var mxwElement=n-elmWidth-(elements-bar-2);mxwElement>maxWidth;mxwElement--){lessVal+=RSSUtils.combins(n-elmWidth-mxwElement-1,elements-bar-3);}subVal-=lessVal*(elements-1-bar);}else if(n-elmWidth>maxWidth){subVal--;}val+=subVal;}n-=elmWidth;}return val;}},{key:"combins",value:function combins(n,r){var maxDenom;var minDenom;if(n-r>r){minDenom=r;maxDenom=n-r;}else{minDenom=n-r;maxDenom=r;}var val=1;var j=1;for(var i=n;i>maxDenom;i--){val*=i;if(j<=minDenom){val/=j;j++;}}while(j<=minDenom){val/=j;j++;}return val;}}]);return RSSUtils;}();var BitArrayBuilder=/*#__PURE__*/function(){function BitArrayBuilder(){_classCallCheck(this,BitArrayBuilder);}_createClass(BitArrayBuilder,null,[{key:"buildBitArray",value:function buildBitArray(pairs){var charNumber=pairs.length*2-1;if(pairs[pairs.length-1].getRightChar()==null){charNumber-=1;}var size=12*charNumber;var binary=new BitArray(size);var accPos=0;var firstPair=pairs[0];var firstValue=firstPair.getRightChar().getValue();for(var i=11;i>=0;--i){if((firstValue&1<<i)!=0){binary.set(accPos);}accPos++;}for(var _i18=1;_i18<pairs.length;++_i18){var currentPair=pairs[_i18];var leftValue=currentPair.getLeftChar().getValue();for(var j=11;j>=0;--j){if((leftValue&1<<j)!=0){binary.set(accPos);}accPos++;}if(currentPair.getRightChar()!=null){var rightValue=currentPair.getRightChar().getValue();for(var _j=11;_j>=0;--_j){if((rightValue&1<<_j)!=0){binary.set(accPos);}accPos++;}}}return binary;}}]);return BitArrayBuilder;}();var BlockParsedResult=/*#__PURE__*/function(){function BlockParsedResult(finished,decodedInformation){_classCallCheck(this,BlockParsedResult);if(decodedInformation){this.decodedInformation=null;}else{this.finished=finished;this.decodedInformation=decodedInformation;}}_createClass(BlockParsedResult,[{key:"getDecodedInformation",value:function getDecodedInformation(){return this.decodedInformation;}},{key:"isFinished",value:function isFinished(){return this.finished;}}]);return BlockParsedResult;}();var DecodedObject=/*#__PURE__*/function(){function DecodedObject(newPosition){_classCallCheck(this,DecodedObject);this.newPosition=newPosition;}_createClass(DecodedObject,[{key:"getNewPosition",value:function getNewPosition(){return this.newPosition;}}]);return DecodedObject;}();var DecodedChar=/*#__PURE__*/function(_DecodedObject){_inherits(DecodedChar,_DecodedObject);var _super33=_createSuper(DecodedChar);function DecodedChar(newPosition,value){var _this25;_classCallCheck(this,DecodedChar);_this25=_super33.call(this,newPosition);_this25.value=value;return _this25;}_createClass(DecodedChar,[{key:"getValue",value:function getValue(){return this.value;}},{key:"isFNC1",value:function isFNC1(){return this.value===DecodedChar.FNC1;}}]);return DecodedChar;}(DecodedObject);DecodedChar.FNC1='$';var DecodedInformation=/*#__PURE__*/function(_DecodedObject2){_inherits(DecodedInformation,_DecodedObject2);var _super34=_createSuper(DecodedInformation);function DecodedInformation(newPosition,newString,remainingValue){var _this26;_classCallCheck(this,DecodedInformation);_this26=_super34.call(this,newPosition);if(remainingValue){_this26.remaining=true;_this26.remainingValue=_this26.remainingValue;}else{_this26.remaining=false;_this26.remainingValue=0;}_this26.newString=newString;return _this26;}_createClass(DecodedInformation,[{key:"getNewString",value:function getNewString(){return this.newString;}},{key:"isRemaining",value:function isRemaining(){return this.remaining;}},{key:"getRemainingValue",value:function getRemainingValue(){return this.remainingValue;}}]);return DecodedInformation;}(DecodedObject);var DecodedNumeric=/*#__PURE__*/function(_DecodedObject3){_inherits(DecodedNumeric,_DecodedObject3);var _super35=_createSuper(DecodedNumeric);function DecodedNumeric(newPosition,firstDigit,secondDigit){var _this27;_classCallCheck(this,DecodedNumeric);_this27=_super35.call(this,newPosition);if(firstDigit<0||firstDigit>10||secondDigit<0||secondDigit>10){throw new FormatException();}_this27.firstDigit=firstDigit;_this27.secondDigit=secondDigit;return _this27;}_createClass(DecodedNumeric,[{key:"getFirstDigit",value:function getFirstDigit(){return this.firstDigit;}},{key:"getSecondDigit",value:function getSecondDigit(){return this.secondDigit;}},{key:"getValue",value:function getValue(){return this.firstDigit*10+this.secondDigit;}},{key:"isFirstDigitFNC1",value:function isFirstDigitFNC1(){return this.firstDigit===DecodedNumeric.FNC1;}},{key:"isSecondDigitFNC1",value:function isSecondDigitFNC1(){return this.secondDigit===DecodedNumeric.FNC1;}},{key:"isAnyFNC1",value:function isAnyFNC1(){return this.firstDigit===DecodedNumeric.FNC1||this.secondDigit===DecodedNumeric.FNC1;}}]);return DecodedNumeric;}(DecodedObject);DecodedNumeric.FNC1=10;var FieldParser=/*#__PURE__*/function(){function FieldParser(){_classCallCheck(this,FieldParser);}_createClass(FieldParser,null,[{key:"parseFieldsInGeneralPurpose",value:function parseFieldsInGeneralPurpose(rawInformation){if(!rawInformation){return null;}// Processing 2-digit AIs
if(rawInformation.length<2){throw new NotFoundException();}var firstTwoDigits=rawInformation.substring(0,2);var _iterator18=_createForOfIteratorHelper(FieldParser.TWO_DIGIT_DATA_LENGTH),_step18;try{for(_iterator18.s();!(_step18=_iterator18.n()).done;){var dataLength=_step18.value;if(dataLength[0]===firstTwoDigits){if(dataLength[1]===FieldParser.VARIABLE_LENGTH){return FieldParser.processVariableAI(2,dataLength[2],rawInformation);}return FieldParser.processFixedAI(2,dataLength[1],rawInformation);}}}catch(err){_iterator18.e(err);}finally{_iterator18.f();}if(rawInformation.length<3){throw new NotFoundException();}var firstThreeDigits=rawInformation.substring(0,3);var _iterator19=_createForOfIteratorHelper(FieldParser.THREE_DIGIT_DATA_LENGTH),_step19;try{for(_iterator19.s();!(_step19=_iterator19.n()).done;){var _dataLength=_step19.value;if(_dataLength[0]===firstThreeDigits){if(_dataLength[1]===FieldParser.VARIABLE_LENGTH){return FieldParser.processVariableAI(3,_dataLength[2],rawInformation);}return FieldParser.processFixedAI(3,_dataLength[1],rawInformation);}}}catch(err){_iterator19.e(err);}finally{_iterator19.f();}var _iterator20=_createForOfIteratorHelper(FieldParser.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH),_step20;try{for(_iterator20.s();!(_step20=_iterator20.n()).done;){var _dataLength2=_step20.value;if(_dataLength2[0]===firstThreeDigits){if(_dataLength2[1]===FieldParser.VARIABLE_LENGTH){return FieldParser.processVariableAI(4,_dataLength2[2],rawInformation);}return FieldParser.processFixedAI(4,_dataLength2[1],rawInformation);}}}catch(err){_iterator20.e(err);}finally{_iterator20.f();}if(rawInformation.length<4){throw new NotFoundException();}var firstFourDigits=rawInformation.substring(0,4);var _iterator21=_createForOfIteratorHelper(FieldParser.FOUR_DIGIT_DATA_LENGTH),_step21;try{for(_iterator21.s();!(_step21=_iterator21.n()).done;){var _dataLength3=_step21.value;if(_dataLength3[0]===firstFourDigits){if(_dataLength3[1]===FieldParser.VARIABLE_LENGTH){return FieldParser.processVariableAI(4,_dataLength3[2],rawInformation);}return FieldParser.processFixedAI(4,_dataLength3[1],rawInformation);}}}catch(err){_iterator21.e(err);}finally{_iterator21.f();}throw new NotFoundException();}},{key:"processFixedAI",value:function processFixedAI(aiSize,fieldSize,rawInformation){if(rawInformation.length<aiSize){throw new NotFoundException();}var ai=rawInformation.substring(0,aiSize);if(rawInformation.length<aiSize+fieldSize){throw new NotFoundException();}var field=rawInformation.substring(aiSize,aiSize+fieldSize);var remaining=rawInformation.substring(aiSize+fieldSize);var result='('+ai+')'+field;var parsedAI=FieldParser.parseFieldsInGeneralPurpose(remaining);return parsedAI==null?result:result+parsedAI;}},{key:"processVariableAI",value:function processVariableAI(aiSize,variableFieldSize,rawInformation){var ai=rawInformation.substring(0,aiSize);var maxSize;if(rawInformation.length<aiSize+variableFieldSize){maxSize=rawInformation.length;}else{maxSize=aiSize+variableFieldSize;}var field=rawInformation.substring(aiSize,maxSize);var remaining=rawInformation.substring(maxSize);var result='('+ai+')'+field;var parsedAI=FieldParser.parseFieldsInGeneralPurpose(remaining);return parsedAI==null?result:result+parsedAI;}}]);return FieldParser;}();FieldParser.VARIABLE_LENGTH=[];FieldParser.TWO_DIGIT_DATA_LENGTH=[['00',18],['01',14],['02',14],['10',FieldParser.VARIABLE_LENGTH,20],['11',6],['12',6],['13',6],['15',6],['17',6],['20',2],['21',FieldParser.VARIABLE_LENGTH,20],['22',FieldParser.VARIABLE_LENGTH,29],['30',FieldParser.VARIABLE_LENGTH,8],['37',FieldParser.VARIABLE_LENGTH,8],// internal company codes
['90',FieldParser.VARIABLE_LENGTH,30],['91',FieldParser.VARIABLE_LENGTH,30],['92',FieldParser.VARIABLE_LENGTH,30],['93',FieldParser.VARIABLE_LENGTH,30],['94',FieldParser.VARIABLE_LENGTH,30],['95',FieldParser.VARIABLE_LENGTH,30],['96',FieldParser.VARIABLE_LENGTH,30],['97',FieldParser.VARIABLE_LENGTH,3],['98',FieldParser.VARIABLE_LENGTH,30],['99',FieldParser.VARIABLE_LENGTH,30]];FieldParser.THREE_DIGIT_DATA_LENGTH=[// Same format as above
['240',FieldParser.VARIABLE_LENGTH,30],['241',FieldParser.VARIABLE_LENGTH,30],['242',FieldParser.VARIABLE_LENGTH,6],['250',FieldParser.VARIABLE_LENGTH,30],['251',FieldParser.VARIABLE_LENGTH,30],['253',FieldParser.VARIABLE_LENGTH,17],['254',FieldParser.VARIABLE_LENGTH,20],['400',FieldParser.VARIABLE_LENGTH,30],['401',FieldParser.VARIABLE_LENGTH,30],['402',17],['403',FieldParser.VARIABLE_LENGTH,30],['410',13],['411',13],['412',13],['413',13],['414',13],['420',FieldParser.VARIABLE_LENGTH,20],['421',FieldParser.VARIABLE_LENGTH,15],['422',3],['423',FieldParser.VARIABLE_LENGTH,15],['424',3],['425',3],['426',3]];FieldParser.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH=[// Same format as above
['310',6],['311',6],['312',6],['313',6],['314',6],['315',6],['316',6],['320',6],['321',6],['322',6],['323',6],['324',6],['325',6],['326',6],['327',6],['328',6],['329',6],['330',6],['331',6],['332',6],['333',6],['334',6],['335',6],['336',6],['340',6],['341',6],['342',6],['343',6],['344',6],['345',6],['346',6],['347',6],['348',6],['349',6],['350',6],['351',6],['352',6],['353',6],['354',6],['355',6],['356',6],['357',6],['360',6],['361',6],['362',6],['363',6],['364',6],['365',6],['366',6],['367',6],['368',6],['369',6],['390',FieldParser.VARIABLE_LENGTH,15],['391',FieldParser.VARIABLE_LENGTH,18],['392',FieldParser.VARIABLE_LENGTH,15],['393',FieldParser.VARIABLE_LENGTH,18],['703',FieldParser.VARIABLE_LENGTH,30]];FieldParser.FOUR_DIGIT_DATA_LENGTH=[// Same format as above
['7001',13],['7002',FieldParser.VARIABLE_LENGTH,30],['7003',10],['8001',14],['8002',FieldParser.VARIABLE_LENGTH,20],['8003',FieldParser.VARIABLE_LENGTH,30],['8004',FieldParser.VARIABLE_LENGTH,30],['8005',6],['8006',18],['8007',FieldParser.VARIABLE_LENGTH,30],['8008',FieldParser.VARIABLE_LENGTH,12],['8018',18],['8020',FieldParser.VARIABLE_LENGTH,25],['8100',6],['8101',10],['8102',2],['8110',FieldParser.VARIABLE_LENGTH,70],['8200',FieldParser.VARIABLE_LENGTH,70]];var GeneralAppIdDecoder=/*#__PURE__*/function(){function GeneralAppIdDecoder(information){_classCallCheck(this,GeneralAppIdDecoder);this.buffer=new StringBuilder();this.information=information;}_createClass(GeneralAppIdDecoder,[{key:"decodeAllCodes",value:function decodeAllCodes(buff,initialPosition){var currentPosition=initialPosition;var remaining=null;do{var info=this.decodeGeneralPurposeField(currentPosition,remaining);var parsedFields=FieldParser.parseFieldsInGeneralPurpose(info.getNewString());if(parsedFields!=null){buff.append(parsedFields);}if(info.isRemaining()){remaining=''+info.getRemainingValue();}else{remaining=null;}if(currentPosition===info.getNewPosition()){// No step forward!
break;}currentPosition=info.getNewPosition();}while(true);return buff.toString();}},{key:"isStillNumeric",value:function isStillNumeric(pos){// It's numeric if it still has 7 positions
// and one of the first 4 bits is "1".
if(pos+7>this.information.getSize()){return pos+4<=this.information.getSize();}for(var i=pos;i<pos+3;++i){if(this.information.get(i)){return true;}}return this.information.get(pos+3);}},{key:"decodeNumeric",value:function decodeNumeric(pos){if(pos+7>this.information.getSize()){var _numeric=this.extractNumericValueFromBitArray(pos,4);if(_numeric===0){return new DecodedNumeric(this.information.getSize(),DecodedNumeric.FNC1,DecodedNumeric.FNC1);}return new DecodedNumeric(this.information.getSize(),_numeric-1,DecodedNumeric.FNC1);}var numeric=this.extractNumericValueFromBitArray(pos,7);var digit1=(numeric-8)/11;var digit2=(numeric-8)%11;return new DecodedNumeric(pos+7,digit1,digit2);}},{key:"extractNumericValueFromBitArray",value:function extractNumericValueFromBitArray(pos,bits){return GeneralAppIdDecoder.extractNumericValueFromBitArray(this.information,pos,bits);}},{key:"decodeGeneralPurposeField",value:function decodeGeneralPurposeField(pos,remaining){// this.buffer.setLength(0);
this.buffer.setLengthToZero();if(remaining!=null){this.buffer.append(remaining);}this.current.setPosition(pos);var lastDecoded=this.parseBlocks();if(lastDecoded!=null&&lastDecoded.isRemaining()){return new DecodedInformation(this.current.getPosition(),this.buffer.toString(),lastDecoded.getRemainingValue());}return new DecodedInformation(this.current.getPosition(),this.buffer.toString());}},{key:"parseBlocks",value:function parseBlocks(){var isFinished;var result;do{var initialPosition=this.current.getPosition();if(this.current.isAlpha()){result=this.parseAlphaBlock();isFinished=result.isFinished();}else if(this.current.isIsoIec646()){result=this.parseIsoIec646Block();isFinished=result.isFinished();}else{// it must be numeric
result=this.parseNumericBlock();isFinished=result.isFinished();}var positionChanged=initialPosition!==this.current.getPosition();if(!positionChanged&&!isFinished){break;}}while(!isFinished);return result.getDecodedInformation();}},{key:"parseNumericBlock",value:function parseNumericBlock(){while(this.isStillNumeric(this.current.getPosition())){var numeric=this.decodeNumeric(this.current.getPosition());this.current.setPosition(numeric.getNewPosition());if(numeric.isFirstDigitFNC1()){var information=void 0;if(numeric.isSecondDigitFNC1()){information=new DecodedInformation(this.current.getPosition(),this.buffer.toString());}else{information=new DecodedInformation(this.current.getPosition(),this.buffer.toString(),numeric.getSecondDigit());}return new BlockParsedResult(true,information);}this.buffer.append(numeric.getFirstDigit());if(numeric.isSecondDigitFNC1()){var _information=new DecodedInformation(this.current.getPosition(),this.buffer.toString());return new BlockParsedResult(true,_information);}this.buffer.append(numeric.getSecondDigit());}if(this.isNumericToAlphaNumericLatch(this.current.getPosition())){this.current.setAlpha();this.current.incrementPosition(4);}return new BlockParsedResult(false);}},{key:"parseIsoIec646Block",value:function parseIsoIec646Block(){while(this.isStillIsoIec646(this.current.getPosition())){var iso=this.decodeIsoIec646(this.current.getPosition());this.current.setPosition(iso.getNewPosition());if(iso.isFNC1()){var information=new DecodedInformation(this.current.getPosition(),this.buffer.toString());return new BlockParsedResult(true,information);}this.buffer.append(iso.getValue());}if(this.isAlphaOr646ToNumericLatch(this.current.getPosition())){this.current.incrementPosition(3);this.current.setNumeric();}else if(this.isAlphaTo646ToAlphaLatch(this.current.getPosition())){if(this.current.getPosition()+5<this.information.getSize()){this.current.incrementPosition(5);}else{this.current.setPosition(this.information.getSize());}this.current.setAlpha();}return new BlockParsedResult(false);}},{key:"parseAlphaBlock",value:function parseAlphaBlock(){while(this.isStillAlpha(this.current.getPosition())){var alpha=this.decodeAlphanumeric(this.current.getPosition());this.current.setPosition(alpha.getNewPosition());if(alpha.isFNC1()){var information=new DecodedInformation(this.current.getPosition(),this.buffer.toString());return new BlockParsedResult(true,information);// end of the char block
}this.buffer.append(alpha.getValue());}if(this.isAlphaOr646ToNumericLatch(this.current.getPosition())){this.current.incrementPosition(3);this.current.setNumeric();}else if(this.isAlphaTo646ToAlphaLatch(this.current.getPosition())){if(this.current.getPosition()+5<this.information.getSize()){this.current.incrementPosition(5);}else{this.current.setPosition(this.information.getSize());}this.current.setIsoIec646();}return new BlockParsedResult(false);}},{key:"isStillIsoIec646",value:function isStillIsoIec646(pos){if(pos+5>this.information.getSize()){return false;}var fiveBitValue=this.extractNumericValueFromBitArray(pos,5);if(fiveBitValue>=5&&fiveBitValue<16){return true;}if(pos+7>this.information.getSize()){return false;}var sevenBitValue=this.extractNumericValueFromBitArray(pos,7);if(sevenBitValue>=64&&sevenBitValue<116){return true;}if(pos+8>this.information.getSize()){return false;}var eightBitValue=this.extractNumericValueFromBitArray(pos,8);return eightBitValue>=232&&eightBitValue<253;}},{key:"decodeIsoIec646",value:function decodeIsoIec646(pos){var fiveBitValue=this.extractNumericValueFromBitArray(pos,5);if(fiveBitValue===15){return new DecodedChar(pos+5,DecodedChar.FNC1);}if(fiveBitValue>=5&&fiveBitValue<15){return new DecodedChar(pos+5,'0'+(fiveBitValue-5));}var sevenBitValue=this.extractNumericValueFromBitArray(pos,7);if(sevenBitValue>=64&&sevenBitValue<90){return new DecodedChar(pos+7,''+(sevenBitValue+1));}if(sevenBitValue>=90&&sevenBitValue<116){return new DecodedChar(pos+7,''+(sevenBitValue+7));}var eightBitValue=this.extractNumericValueFromBitArray(pos,8);var c;switch(eightBitValue){case 232:c='!';break;case 233:c='"';break;case 234:c='%';break;case 235:c='&';break;case 236:c='\'';break;case 237:c='(';break;case 238:c=')';break;case 239:c='*';break;case 240:c='+';break;case 241:c=',';break;case 242:c='-';break;case 243:c='.';break;case 244:c='/';break;case 245:c=':';break;case 246:c=';';break;case 247:c='<';break;case 248:c='=';break;case 249:c='>';break;case 250:c='?';break;case 251:c='_';break;case 252:c=' ';break;default:throw new FormatException();}return new DecodedChar(pos+8,c);}},{key:"isStillAlpha",value:function isStillAlpha(pos){if(pos+5>this.information.getSize()){return false;}// We now check if it's a valid 5-bit value (0..9 and FNC1)
var fiveBitValue=this.extractNumericValueFromBitArray(pos,5);if(fiveBitValue>=5&&fiveBitValue<16){return true;}if(pos+6>this.information.getSize()){return false;}var sixBitValue=this.extractNumericValueFromBitArray(pos,6);return sixBitValue>=16&&sixBitValue<63;// 63 not included
}},{key:"decodeAlphanumeric",value:function decodeAlphanumeric(pos){var fiveBitValue=this.extractNumericValueFromBitArray(pos,5);if(fiveBitValue===15){return new DecodedChar(pos+5,DecodedChar.FNC1);}if(fiveBitValue>=5&&fiveBitValue<15){return new DecodedChar(pos+5,'0'+(fiveBitValue-5));}var sixBitValue=this.extractNumericValueFromBitArray(pos,6);if(sixBitValue>=32&&sixBitValue<58){return new DecodedChar(pos+6,''+(sixBitValue+33));}var c;switch(sixBitValue){case 58:c='*';break;case 59:c=',';break;case 60:c='-';break;case 61:c='.';break;case 62:c='/';break;default:throw new IllegalStateException('Decoding invalid alphanumeric value: '+sixBitValue);}return new DecodedChar(pos+6,c);}},{key:"isAlphaTo646ToAlphaLatch",value:function isAlphaTo646ToAlphaLatch(pos){if(pos+1>this.information.getSize()){return false;}for(var i=0;i<5&&i+pos<this.information.getSize();++i){if(i===2){if(!this.information.get(pos+2)){return false;}}else if(this.information.get(pos+i)){return false;}}return true;}},{key:"isAlphaOr646ToNumericLatch",value:function isAlphaOr646ToNumericLatch(pos){// Next is alphanumeric if there are 3 positions and they are all zeros
if(pos+3>this.information.getSize()){return false;}for(var i=pos;i<pos+3;++i){if(this.information.get(i)){return false;}}return true;}},{key:"isNumericToAlphaNumericLatch",value:function isNumericToAlphaNumericLatch(pos){// Next is alphanumeric if there are 4 positions and they are all zeros, or
// if there is a subset of this just before the end of the symbol
if(pos+1>this.information.getSize()){return false;}for(var i=0;i<4&&i+pos<this.information.getSize();++i){if(this.information.get(pos+i)){return false;}}return true;}}],[{key:"extractNumericValueFromBitArray",value:function extractNumericValueFromBitArray(information,pos,bits){var value=0;for(var i=0;i<bits;++i){if(information.get(pos+i)){value|=1<<bits-i-1;}}return value;}}]);return GeneralAppIdDecoder;}();var AbstractExpandedDecoder=/*#__PURE__*/function(){function AbstractExpandedDecoder(information){_classCallCheck(this,AbstractExpandedDecoder);this.information=information;this.generalDecoder=new GeneralAppIdDecoder(information);}_createClass(AbstractExpandedDecoder,[{key:"getInformation",value:function getInformation(){return this.information;}},{key:"getGeneralDecoder",value:function getGeneralDecoder(){return this.generalDecoder;}}]);return AbstractExpandedDecoder;}();var AI01decoder=/*#__PURE__*/function(_AbstractExpandedDeco){_inherits(AI01decoder,_AbstractExpandedDeco);var _super36=_createSuper(AI01decoder);function AI01decoder(information){_classCallCheck(this,AI01decoder);return _super36.call(this,information);}_createClass(AI01decoder,[{key:"encodeCompressedGtin",value:function encodeCompressedGtin(buf,currentPos){buf.append('(01)');var initialPosition=buf.length();buf.append('9');this.encodeCompressedGtinWithoutAI(buf,currentPos,initialPosition);}},{key:"encodeCompressedGtinWithoutAI",value:function encodeCompressedGtinWithoutAI(buf,currentPos,initialBufferPosition){for(var i=0;i<4;++i){var currentBlock=this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos+10*i,10);if(currentBlock/100===0){buf.append('0');}if(currentBlock/10===0){buf.append('0');}buf.append(currentBlock);}AI01decoder.appendCheckDigit(buf,initialBufferPosition);}}],[{key:"appendCheckDigit",value:function appendCheckDigit(buf,currentPos){var checkDigit=0;for(var i=0;i<13;i++){// let digit = buf.charAt(i + currentPos) - '0';
// To be checked
var digit=buf.charAt(i+currentPos).charCodeAt(0)-'0'.charCodeAt(0);checkDigit+=(i&0x01)===0?3*digit:digit;}checkDigit=10-checkDigit%10;if(checkDigit===10){checkDigit=0;}buf.append(checkDigit);}}]);return AI01decoder;}(AbstractExpandedDecoder);AI01decoder.GTIN_SIZE=40;var AI01AndOtherAIs=/*#__PURE__*/function(_AI01decoder){_inherits(AI01AndOtherAIs,_AI01decoder);var _super37=_createSuper(AI01AndOtherAIs);// the second one is the encodation method, and the other two are for the variable length
function AI01AndOtherAIs(information){_classCallCheck(this,AI01AndOtherAIs);return _super37.call(this,information);}_createClass(AI01AndOtherAIs,[{key:"parseInformation",value:function parseInformation(){var buff=new StringBuilder();buff.append('(01)');var initialGtinPosition=buff.length();var firstGtinDigit=this.getGeneralDecoder().extractNumericValueFromBitArray(AI01AndOtherAIs.HEADER_SIZE,4);buff.append(firstGtinDigit);this.encodeCompressedGtinWithoutAI(buff,AI01AndOtherAIs.HEADER_SIZE+4,initialGtinPosition);return this.getGeneralDecoder().decodeAllCodes(buff,AI01AndOtherAIs.HEADER_SIZE+44);}}]);return AI01AndOtherAIs;}(AI01decoder);AI01AndOtherAIs.HEADER_SIZE=1+1+2;// first bit encodes the linkage flag,
var AnyAIDecoder=/*#__PURE__*/function(_AbstractExpandedDeco2){_inherits(AnyAIDecoder,_AbstractExpandedDeco2);var _super38=_createSuper(AnyAIDecoder);function AnyAIDecoder(information){_classCallCheck(this,AnyAIDecoder);return _super38.call(this,information);}_createClass(AnyAIDecoder,[{key:"parseInformation",value:function parseInformation(){var buf=new StringBuilder();return this.getGeneralDecoder().decodeAllCodes(buf,AnyAIDecoder.HEADER_SIZE);}}]);return AnyAIDecoder;}(AbstractExpandedDecoder);AnyAIDecoder.HEADER_SIZE=2+1+2;var AI01weightDecoder=/*#__PURE__*/function(_AI01decoder2){_inherits(AI01weightDecoder,_AI01decoder2);var _super39=_createSuper(AI01weightDecoder);function AI01weightDecoder(information){_classCallCheck(this,AI01weightDecoder);return _super39.call(this,information);}_createClass(AI01weightDecoder,[{key:"encodeCompressedWeight",value:function encodeCompressedWeight(buf,currentPos,weightSize){var originalWeightNumeric=this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos,weightSize);this.addWeightCode(buf,originalWeightNumeric);var weightNumeric=this.checkWeight(originalWeightNumeric);var currentDivisor=100000;for(var i=0;i<5;++i){if(weightNumeric/currentDivisor===0){buf.append('0');}currentDivisor/=10;}buf.append(weightNumeric);}}]);return AI01weightDecoder;}(AI01decoder);var AI013x0xDecoder=/*#__PURE__*/function(_AI01weightDecoder){_inherits(AI013x0xDecoder,_AI01weightDecoder);var _super40=_createSuper(AI013x0xDecoder);function AI013x0xDecoder(information){_classCallCheck(this,AI013x0xDecoder);return _super40.call(this,information);}_createClass(AI013x0xDecoder,[{key:"parseInformation",value:function parseInformation(){if(this.getInformation().getSize()!=AI013x0xDecoder.HEADER_SIZE+AI01weightDecoder.GTIN_SIZE+AI013x0xDecoder.WEIGHT_SIZE){throw new NotFoundException();}var buf=new StringBuilder();this.encodeCompressedGtin(buf,AI013x0xDecoder.HEADER_SIZE);this.encodeCompressedWeight(buf,AI013x0xDecoder.HEADER_SIZE+AI01weightDecoder.GTIN_SIZE,AI013x0xDecoder.WEIGHT_SIZE);return buf.toString();}}]);return AI013x0xDecoder;}(AI01weightDecoder);AI013x0xDecoder.HEADER_SIZE=4+1;AI013x0xDecoder.WEIGHT_SIZE=15;var AI013103decoder=/*#__PURE__*/function(_AI013x0xDecoder){_inherits(AI013103decoder,_AI013x0xDecoder);var _super41=_createSuper(AI013103decoder);function AI013103decoder(information){_classCallCheck(this,AI013103decoder);return _super41.call(this,information);}_createClass(AI013103decoder,[{key:"addWeightCode",value:function addWeightCode(buf,weight){buf.append('(3103)');}},{key:"checkWeight",value:function checkWeight(weight){return weight;}}]);return AI013103decoder;}(AI013x0xDecoder);var AI01320xDecoder=/*#__PURE__*/function(_AI013x0xDecoder2){_inherits(AI01320xDecoder,_AI013x0xDecoder2);var _super42=_createSuper(AI01320xDecoder);function AI01320xDecoder(information){_classCallCheck(this,AI01320xDecoder);return _super42.call(this,information);}_createClass(AI01320xDecoder,[{key:"addWeightCode",value:function addWeightCode(buf,weight){if(weight<10000){buf.append('(3202)');}else{buf.append('(3203)');}}},{key:"checkWeight",value:function checkWeight(weight){if(weight<10000){return weight;}return weight-10000;}}]);return AI01320xDecoder;}(AI013x0xDecoder);var AI01392xDecoder=/*#__PURE__*/function(_AI01decoder3){_inherits(AI01392xDecoder,_AI01decoder3);var _super43=_createSuper(AI01392xDecoder);function AI01392xDecoder(information){_classCallCheck(this,AI01392xDecoder);return _super43.call(this,information);}_createClass(AI01392xDecoder,[{key:"parseInformation",value:function parseInformation(){if(this.getInformation().getSize()<AI01392xDecoder.HEADER_SIZE+AI01decoder.GTIN_SIZE){throw new NotFoundException();}var buf=new StringBuilder();this.encodeCompressedGtin(buf,AI01392xDecoder.HEADER_SIZE);var lastAIdigit=this.getGeneralDecoder().extractNumericValueFromBitArray(AI01392xDecoder.HEADER_SIZE+AI01decoder.GTIN_SIZE,AI01392xDecoder.LAST_DIGIT_SIZE);buf.append('(392');buf.append(lastAIdigit);buf.append(')');var decodedInformation=this.getGeneralDecoder().decodeGeneralPurposeField(AI01392xDecoder.HEADER_SIZE+AI01decoder.GTIN_SIZE+AI01392xDecoder.LAST_DIGIT_SIZE,null);buf.append(decodedInformation.getNewString());return buf.toString();}}]);return AI01392xDecoder;}(AI01decoder);AI01392xDecoder.HEADER_SIZE=5+1+2;AI01392xDecoder.LAST_DIGIT_SIZE=2;var AI01393xDecoder=/*#__PURE__*/function(_AI01decoder4){_inherits(AI01393xDecoder,_AI01decoder4);var _super44=_createSuper(AI01393xDecoder);function AI01393xDecoder(information){_classCallCheck(this,AI01393xDecoder);return _super44.call(this,information);}_createClass(AI01393xDecoder,[{key:"parseInformation",value:function parseInformation(){if(this.getInformation().getSize()<AI01393xDecoder.HEADER_SIZE+AI01decoder.GTIN_SIZE){throw new NotFoundException();}var buf=new StringBuilder();this.encodeCompressedGtin(buf,AI01393xDecoder.HEADER_SIZE);var lastAIdigit=this.getGeneralDecoder().extractNumericValueFromBitArray(AI01393xDecoder.HEADER_SIZE+AI01decoder.GTIN_SIZE,AI01393xDecoder.LAST_DIGIT_SIZE);buf.append('(393');buf.append(lastAIdigit);buf.append(')');var firstThreeDigits=this.getGeneralDecoder().extractNumericValueFromBitArray(AI01393xDecoder.HEADER_SIZE+AI01decoder.GTIN_SIZE+AI01393xDecoder.LAST_DIGIT_SIZE,AI01393xDecoder.FIRST_THREE_DIGITS_SIZE);if(firstThreeDigits/100==0){buf.append('0');}if(firstThreeDigits/10==0){buf.append('0');}buf.append(firstThreeDigits);var generalInformation=this.getGeneralDecoder().decodeGeneralPurposeField(AI01393xDecoder.HEADER_SIZE+AI01decoder.GTIN_SIZE+AI01393xDecoder.LAST_DIGIT_SIZE+AI01393xDecoder.FIRST_THREE_DIGITS_SIZE,null);buf.append(generalInformation.getNewString());return buf.toString();}}]);return AI01393xDecoder;}(AI01decoder);AI01393xDecoder.HEADER_SIZE=5+1+2;AI01393xDecoder.LAST_DIGIT_SIZE=2;AI01393xDecoder.FIRST_THREE_DIGITS_SIZE=10;var AI013x0x1xDecoder=/*#__PURE__*/function(_AI01weightDecoder2){_inherits(AI013x0x1xDecoder,_AI01weightDecoder2);var _super45=_createSuper(AI013x0x1xDecoder);function AI013x0x1xDecoder(information,firstAIdigits,dateCode){var _this28;_classCallCheck(this,AI013x0x1xDecoder);_this28=_super45.call(this,information);_this28.dateCode=dateCode;_this28.firstAIdigits=firstAIdigits;return _this28;}_createClass(AI013x0x1xDecoder,[{key:"parseInformation",value:function parseInformation(){if(this.getInformation().getSize()!=AI013x0x1xDecoder.HEADER_SIZE+AI013x0x1xDecoder.GTIN_SIZE+AI013x0x1xDecoder.WEIGHT_SIZE+AI013x0x1xDecoder.DATE_SIZE){throw new NotFoundException();}var buf=new StringBuilder();this.encodeCompressedGtin(buf,AI013x0x1xDecoder.HEADER_SIZE);this.encodeCompressedWeight(buf,AI013x0x1xDecoder.HEADER_SIZE+AI013x0x1xDecoder.GTIN_SIZE,AI013x0x1xDecoder.WEIGHT_SIZE);this.encodeCompressedDate(buf,AI013x0x1xDecoder.HEADER_SIZE+AI013x0x1xDecoder.GTIN_SIZE+AI013x0x1xDecoder.WEIGHT_SIZE);return buf.toString();}},{key:"encodeCompressedDate",value:function encodeCompressedDate(buf,currentPos){var numericDate=this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos,AI013x0x1xDecoder.DATE_SIZE);if(numericDate==38400){return;}buf.append('(');buf.append(this.dateCode);buf.append(')');var day=numericDate%32;numericDate/=32;var month=numericDate%12+1;numericDate/=12;var year=numericDate;if(year/10==0){buf.append('0');}buf.append(year);if(month/10==0){buf.append('0');}buf.append(month);if(day/10==0){buf.append('0');}buf.append(day);}},{key:"addWeightCode",value:function addWeightCode(buf,weight){buf.append('(');buf.append(this.firstAIdigits);buf.append(weight/100000);buf.append(')');}},{key:"checkWeight",value:function checkWeight(weight){return weight%100000;}}]);return AI013x0x1xDecoder;}(AI01weightDecoder);AI013x0x1xDecoder.HEADER_SIZE=7+1;AI013x0x1xDecoder.WEIGHT_SIZE=20;AI013x0x1xDecoder.DATE_SIZE=16;function createDecoder(information){try{if(information.get(1)){return new AI01AndOtherAIs(information);}if(!information.get(2)){return new AnyAIDecoder(information);}var fourBitEncodationMethod=GeneralAppIdDecoder.extractNumericValueFromBitArray(information,1,4);switch(fourBitEncodationMethod){case 4:return new AI013103decoder(information);case 5:return new AI01320xDecoder(information);}var fiveBitEncodationMethod=GeneralAppIdDecoder.extractNumericValueFromBitArray(information,1,5);switch(fiveBitEncodationMethod){case 12:return new AI01392xDecoder(information);case 13:return new AI01393xDecoder(information);}var sevenBitEncodationMethod=GeneralAppIdDecoder.extractNumericValueFromBitArray(information,1,7);switch(sevenBitEncodationMethod){case 56:return new AI013x0x1xDecoder(information,'310','11');case 57:return new AI013x0x1xDecoder(information,'320','11');case 58:return new AI013x0x1xDecoder(information,'310','13');case 59:return new AI013x0x1xDecoder(information,'320','13');case 60:return new AI013x0x1xDecoder(information,'310','15');case 61:return new AI013x0x1xDecoder(information,'320','15');case 62:return new AI013x0x1xDecoder(information,'310','17');case 63:return new AI013x0x1xDecoder(information,'320','17');}}catch(e){console.log(e);throw new IllegalStateException('unknown decoder: '+information);}}var ExpandedPair=/*#__PURE__*/function(){function ExpandedPair(leftChar,rightChar,finderPatter,mayBeLast){_classCallCheck(this,ExpandedPair);this.leftchar=leftChar;this.rightchar=rightChar;this.finderpattern=finderPatter;this.maybeLast=mayBeLast;}_createClass(ExpandedPair,[{key:"mayBeLast",value:function mayBeLast(){return this.maybeLast;}},{key:"getLeftChar",value:function getLeftChar(){return this.leftchar;}},{key:"getRightChar",value:function getRightChar(){return this.rightchar;}},{key:"getFinderPattern",value:function getFinderPattern(){return this.finderpattern;}},{key:"mustBeLast",value:function mustBeLast(){return this.rightchar==null;}},{key:"toString",value:function toString(){return'[ '+this.leftchar+', '+this.rightchar+' : '+(this.finderpattern==null?'null':this.finderpattern.getValue())+' ]';}},{key:"hashCode",value:function hashCode(){// return ExpandedPair.hashNotNull(leftChar) ^ hashNotNull(rightChar) ^ hashNotNull(finderPattern);
var value=this.leftchar.getValue()^this.rightchar.getValue()^this.finderpattern.getValue();return value;}}],[{key:"equals",value:function equals(o1,o2){if(!(o1 instanceof ExpandedPair)){return false;}return ExpandedPair.equalsOrNull(o1.leftchar,o2.leftchar)&&ExpandedPair.equalsOrNull(o1.rightchar,o2.rightchar)&&ExpandedPair.equalsOrNull(o1.finderpattern,o2.finderpattern);}},{key:"equalsOrNull",value:function equalsOrNull(o1,o2){return o1===null?o2===null:ExpandedPair.equals(o1,o2);}}]);return ExpandedPair;}();var ExpandedRow=/*#__PURE__*/function(){function ExpandedRow(pairs,rowNumber,wasReversed){_classCallCheck(this,ExpandedRow);this.pairs=pairs;this.rowNumber=rowNumber;this.wasReversed=wasReversed;}_createClass(ExpandedRow,[{key:"getPairs",value:function getPairs(){return this.pairs;}},{key:"getRowNumber",value:function getRowNumber(){return this.rowNumber;}},{key:"isReversed",value:function isReversed(){return this.wasReversed;}// check implementation
},{key:"isEquivalent",value:function isEquivalent(otherPairs){return this.checkEqualitity(this,otherPairs);}// @Override
},{key:"toString",value:function toString(){return'{ '+this.pairs+' }';}/**
* Two rows are equal if they contain the same pairs in the same order.
*/ // @Override
// check implementation
},{key:"equals",value:function equals(o1,o2){if(!(o1 instanceof ExpandedRow)){return false;}return this.checkEqualitity(o1,o2)&&o1.wasReversed===o2.wasReversed;}},{key:"checkEqualitity",value:function checkEqualitity(pair1,pair2){if(!pair1||!pair2)return;var result;pair1.forEach(function(e1,i){pair2.forEach(function(e2){if(e1.getLeftChar().getValue()===e2.getLeftChar().getValue()&&e1.getRightChar().getValue()===e2.getRightChar().getValue()&&e1.getFinderPatter().getValue()===e2.getFinderPatter().getValue()){result=true;}});});return result;}}]);return ExpandedRow;}();// import java.util.ArrayList;
// import java.util.Iterator;
// import java.util.List;
// import java.util.Map;
// import java.util.Collections;
var RSSExpandedReader=/*#__PURE__*/function(_AbstractRSSReader){_inherits(RSSExpandedReader,_AbstractRSSReader);var _super46=_createSuper(RSSExpandedReader);function RSSExpandedReader(verbose){var _this29;_classCallCheck(this,RSSExpandedReader);_this29=_super46.apply(this,arguments);_this29.pairs=new Array(RSSExpandedReader.MAX_PAIRS);_this29.rows=new Array();_this29.startEnd=[2];_this29.verbose=verbose===true;return _this29;}_createClass(RSSExpandedReader,[{key:"decodeRow",value:function decodeRow(rowNumber,row,hints){// Rows can start with even pattern in case in prev rows there where odd number of patters.
// So lets try twice
// this.pairs.clear();
this.pairs.length=0;this.startFromEven=false;try{return RSSExpandedReader.constructResult(this.decodeRow2pairs(rowNumber,row));}catch(e){// OK
if(this.verbose){console.log(e);}}this.pairs.length=0;this.startFromEven=true;return RSSExpandedReader.constructResult(this.decodeRow2pairs(rowNumber,row));}},{key:"reset",value:function reset(){this.pairs.length=0;this.rows.length=0;}// Not private for testing
},{key:"decodeRow2pairs",value:function decodeRow2pairs(rowNumber,row){var done=false;while(!done){try{this.pairs.push(this.retrieveNextPair(row,this.pairs,rowNumber));}catch(error){if(error instanceof NotFoundException){if(!this.pairs.length){throw new NotFoundException();}// exit this loop when retrieveNextPair() fails and throws
done=true;}}}// TODO: verify sequence of finder patterns as in checkPairSequence()
if(this.checkChecksum()){return this.pairs;}var tryStackedDecode;if(this.rows.length){tryStackedDecode=true;}else{tryStackedDecode=false;}// let tryStackedDecode = !this.rows.isEmpty();
this.storeRow(rowNumber,false);// TODO: deal with reversed rows
if(tryStackedDecode){// When the image is 180-rotated, then rows are sorted in wrong direction.
// Try twice with both the directions.
var ps=this.checkRowsBoolean(false);if(ps!=null){return ps;}ps=this.checkRowsBoolean(true);if(ps!=null){return ps;}}throw new NotFoundException();}// Need to Verify
},{key:"checkRowsBoolean",value:function checkRowsBoolean(reverse){// Limit number of rows we are checking
// We use recursive algorithm with pure complexity and don't want it to take forever
// Stacked barcode can have up to 11 rows, so 25 seems reasonable enough
if(this.rows.length>25){this.rows.length=0;// We will never have a chance to get result, so clear it
return null;}this.pairs.length=0;if(reverse){this.rows=this.rows.reverse();// Collections.reverse(this.rows);
}var ps=null;try{ps=this.checkRows(new Array(),0);}catch(e){// OK
if(this.verbose){console.log(e);}}if(reverse){this.rows=this.rows.reverse();// Collections.reverse(this.rows);
}return ps;}// Try to construct a valid rows sequence
// Recursion is used to implement backtracking
},{key:"checkRows",value:function checkRows(collectedRows,currentRow){for(var i=currentRow;i<this.rows.length;i++){var row=this.rows[i];this.pairs.length=0;var _iterator22=_createForOfIteratorHelper(collectedRows),_step22;try{for(_iterator22.s();!(_step22=_iterator22.n()).done;){var collectedRow=_step22.value;this.pairs.push(collectedRow.getPairs());}}catch(err){_iterator22.e(err);}finally{_iterator22.f();}this.pairs.push(row.getPairs());if(!RSSExpandedReader.isValidSequence(this.pairs)){continue;}if(this.checkChecksum()){return this.pairs;}var rs=new Array(collectedRows);rs.push(row);try{// Recursion: try to add more rows
return this.checkRows(rs,i+1);}catch(e){// We failed, try the next candidate
if(this.verbose){console.log(e);}}}throw new NotFoundException();}// Whether the pairs form a valid find pattern sequence,
// either complete or a prefix
},{key:"storeRow",value:function storeRow(rowNumber,wasReversed){// Discard if duplicate above or below; otherwise insert in order by row number.
var insertPos=0;var prevIsSame=false;var nextIsSame=false;while(insertPos<this.rows.length){var erow=this.rows[insertPos];if(erow.getRowNumber()>rowNumber){nextIsSame=erow.isEquivalent(this.pairs);break;}prevIsSame=erow.isEquivalent(this.pairs);insertPos++;}if(nextIsSame||prevIsSame){return;}// When the row was partially decoded (e.g. 2 pairs found instead of 3),
// it will prevent us from detecting the barcode.
// Try to merge partial rows
// Check whether the row is part of an allready detected row
if(RSSExpandedReader.isPartialRow(this.pairs,this.rows)){return;}this.rows.push(insertPos,new ExpandedRow(this.pairs,rowNumber,wasReversed));this.removePartialRows(this.pairs,this.rows);}// Remove all the rows that contains only specified pairs
},{key:"removePartialRows",value:function removePartialRows(pairs,rows){// for (Iterator<ExpandedRow> iterator = rows.iterator(); iterator.hasNext();) {
// ExpandedRow r = iterator.next();
// if (r.getPairs().size() == pairs.size()) {
// continue;
// }
// boolean allFound = true;
// for (ExpandedPair p : r.getPairs()) {
// boolean found = false;
// for (ExpandedPair pp : pairs) {
// if (p.equals(pp)) {
// found = true;
// break;
// }
// }
// if (!found) {
// allFound = false;
// break;
// }
// }
// if (allFound) {
// // 'pairs' contains all the pairs from the row 'r'
// iterator.remove();
// }
// }
var _iterator23=_createForOfIteratorHelper(rows),_step23;try{for(_iterator23.s();!(_step23=_iterator23.n()).done;){var row=_step23.value;if(row.getPairs().length===pairs.length){continue;}var _iterator24=_createForOfIteratorHelper(row.getPairs()),_step24;try{for(_iterator24.s();!(_step24=_iterator24.n()).done;){var p=_step24.value;var _iterator25=_createForOfIteratorHelper(pairs),_step25;try{for(_iterator25.s();!(_step25=_iterator25.n()).done;){var pp=_step25.value;if(ExpandedPair.equals(p,pp)){break;}}}catch(err){_iterator25.e(err);}finally{_iterator25.f();}}}catch(err){_iterator24.e(err);}finally{_iterator24.f();}}}catch(err){_iterator23.e(err);}finally{_iterator23.f();}}// Returns true when one of the rows already contains all the pairs
},{key:"getRows",value:// Only used for unit testing
function getRows(){return this.rows;}// Not private for unit testing
},{key:"checkChecksum",value:function checkChecksum(){var firstPair=this.pairs.get(0);var checkCharacter=firstPair.getLeftChar();var firstCharacter=firstPair.getRightChar();if(firstCharacter==null){return false;}var checksum=firstCharacter.getChecksumPortion();var s=2;for(var i=1;i<this.pairs.size();++i){var currentPair=this.pairs.get(i);checksum+=currentPair.getLeftChar().getChecksumPortion();s++;var currentRightChar=currentPair.getRightChar();if(currentRightChar!=null){checksum+=currentRightChar.getChecksumPortion();s++;}}checksum%=211;var checkCharacterValue=211*(s-4)+checksum;return checkCharacterValue==checkCharacter.getValue();}},{key:"retrieveNextPair",value:// not private for testing
function retrieveNextPair(row,previousPairs,rowNumber){var isOddPattern=previousPairs.length%2==0;if(this.startFromEven){isOddPattern=!isOddPattern;}var pattern;var keepFinding=true;var forcedOffset=-1;do{this.findNextPair(row,previousPairs,forcedOffset);pattern=this.parseFoundFinderPattern(row,rowNumber,isOddPattern);if(pattern==null){forcedOffset=RSSExpandedReader.getNextSecondBar(row,this.startEnd[0]);}else{keepFinding=false;}}while(keepFinding);// When stacked symbol is split over multiple rows, there's no way to guess if this pair can be last or not.
// boolean mayBeLast = checkPairSequence(previousPairs, pattern);
var leftChar=this.decodeDataCharacter(row,pattern,isOddPattern,true);if(!this.isEmptyPair(previousPairs)&&previousPairs[previousPairs.length-1].mustBeLast()){throw new NotFoundException();}var rightChar;try{rightChar=this.decodeDataCharacter(row,pattern,isOddPattern,false);}catch(e){rightChar=null;if(this.verbose){console.log(e);}}return new ExpandedPair(leftChar,rightChar,pattern,true);}},{key:"isEmptyPair",value:function isEmptyPair(pairs){if(pairs.length===0){return true;}return false;}},{key:"findNextPair",value:function findNextPair(row,previousPairs,forcedOffset){var counters=this.getDecodeFinderCounters();counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;var width=row.getSize();var rowOffset;if(forcedOffset>=0){rowOffset=forcedOffset;}else if(this.isEmptyPair(previousPairs)){rowOffset=0;}else{var lastPair=previousPairs[previousPairs.length-1];rowOffset=lastPair.getFinderPattern().getStartEnd()[1];}var searchingEvenPair=previousPairs.length%2!=0;if(this.startFromEven){searchingEvenPair=!searchingEvenPair;}var isWhite=false;while(rowOffset<width){isWhite=!row.get(rowOffset);if(!isWhite){break;}rowOffset++;}var counterPosition=0;var patternStart=rowOffset;for(var x=rowOffset;x<width;x++){if(row.get(x)!=isWhite){counters[counterPosition]++;}else{if(counterPosition==3){if(searchingEvenPair){RSSExpandedReader.reverseCounters(counters);}if(RSSExpandedReader.isFinderPattern(counters)){this.startEnd[0]=patternStart;this.startEnd[1]=x;return;}if(searchingEvenPair){RSSExpandedReader.reverseCounters(counters);}patternStart+=counters[0]+counters[1];counters[0]=counters[2];counters[1]=counters[3];counters[2]=0;counters[3]=0;counterPosition--;}else{counterPosition++;}counters[counterPosition]=1;isWhite=!isWhite;}}throw new NotFoundException();}},{key:"parseFoundFinderPattern",value:function parseFoundFinderPattern(row,rowNumber,oddPattern){// Actually we found elements 2-5.
var firstCounter;var start;var end;if(oddPattern){// If pattern number is odd, we need to locate element 1 *before* the current block.
var firstElementStart=this.startEnd[0]-1;// Locate element 1
while(firstElementStart>=0&&!row.get(firstElementStart)){firstElementStart--;}firstElementStart++;firstCounter=this.startEnd[0]-firstElementStart;start=firstElementStart;end=this.startEnd[1];}else{// If pattern number is even, the pattern is reversed, so we need to locate element 1 *after* the current block.
start=this.startEnd[0];end=row.getNextUnset(this.startEnd[1]+1);firstCounter=end-this.startEnd[1];}// Make 'counters' hold 1-4
var counters=this.getDecodeFinderCounters();System.arraycopy(counters,0,counters,1,counters.length-1);counters[0]=firstCounter;var value;try{value=this.parseFinderValue(counters,RSSExpandedReader.FINDER_PATTERNS);}catch(e){return null;}// return new FinderPattern(value, new int[] { start, end }, start, end, rowNumber});
return new FinderPattern(value,[start,end],start,end,rowNumber);}},{key:"decodeDataCharacter",value:function decodeDataCharacter(row,pattern,isOddPattern,leftChar){var counters=this.getDataCharacterCounters();for(var x=0;x<counters.length;x++){counters[x]=0;}if(leftChar){RSSExpandedReader.recordPatternInReverse(row,pattern.getStartEnd()[0],counters);}else{RSSExpandedReader.recordPattern(row,pattern.getStartEnd()[1],counters);// reverse it
for(var i=0,j=counters.length-1;i<j;i++,j--){var temp=counters[i];counters[i]=counters[j];counters[j]=temp;}}// counters[] has the pixels of the module
var numModules=17;// left and right data characters have all the same length
var elementWidth=MathUtils.sum(new Int32Array(counters))/numModules;// Sanity check: element width for pattern and the character should match
var expectedElementWidth=(pattern.getStartEnd()[1]-pattern.getStartEnd()[0])/15.0;if(Math.abs(elementWidth-expectedElementWidth)/expectedElementWidth>0.3){throw new NotFoundException();}var oddCounts=this.getOddCounts();var evenCounts=this.getEvenCounts();var oddRoundingErrors=this.getOddRoundingErrors();var evenRoundingErrors=this.getEvenRoundingErrors();for(var _i19=0;_i19<counters.length;_i19++){var _value=1.0*counters[_i19]/elementWidth;var count=_value+0.5;// Round
if(count<1){if(_value<0.3){throw new NotFoundException();}count=1;}else if(count>8){if(_value>8.7){throw new NotFoundException();}count=8;}var offset=_i19/2;if((_i19&0x01)==0){oddCounts[offset]=count;oddRoundingErrors[offset]=_value-count;}else{evenCounts[offset]=count;evenRoundingErrors[offset]=_value-count;}}this.adjustOddEvenCounts(numModules);var weightRowNumber=4*pattern.getValue()+(isOddPattern?0:2)+(leftChar?0:1)-1;var oddSum=0;var oddChecksumPortion=0;for(var _i20=oddCounts.length-1;_i20>=0;_i20--){if(RSSExpandedReader.isNotA1left(pattern,isOddPattern,leftChar)){var weight=RSSExpandedReader.WEIGHTS[weightRowNumber][2*_i20];oddChecksumPortion+=oddCounts[_i20]*weight;}oddSum+=oddCounts[_i20];}var evenChecksumPortion=0;// int evenSum = 0;
for(var _i21=evenCounts.length-1;_i21>=0;_i21--){if(RSSExpandedReader.isNotA1left(pattern,isOddPattern,leftChar)){var _weight=RSSExpandedReader.WEIGHTS[weightRowNumber][2*_i21+1];evenChecksumPortion+=evenCounts[_i21]*_weight;}// evenSum += evenCounts[i];
}var checksumPortion=oddChecksumPortion+evenChecksumPortion;if((oddSum&0x01)!=0||oddSum>13||oddSum<4){throw new NotFoundException();}var group=(13-oddSum)/2;var oddWidest=RSSExpandedReader.SYMBOL_WIDEST[group];var evenWidest=9-oddWidest;var vOdd=RSSUtils.getRSSvalue(oddCounts,oddWidest,true);var vEven=RSSUtils.getRSSvalue(evenCounts,evenWidest,false);var tEven=RSSExpandedReader.EVEN_TOTAL_SUBSET[group];var gSum=RSSExpandedReader.GSUM[group];var value=vOdd*tEven+vEven+gSum;return new DataCharacter(value,checksumPortion);}},{key:"adjustOddEvenCounts",value:function adjustOddEvenCounts(numModules){var oddSum=MathUtils.sum(new Int32Array(this.getOddCounts()));var evenSum=MathUtils.sum(new Int32Array(this.getEvenCounts()));var incrementOdd=false;var decrementOdd=false;if(oddSum>13){decrementOdd=true;}else if(oddSum<4){incrementOdd=true;}var incrementEven=false;var decrementEven=false;if(evenSum>13){decrementEven=true;}else if(evenSum<4){incrementEven=true;}var mismatch=oddSum+evenSum-numModules;var oddParityBad=(oddSum&0x01)==1;var evenParityBad=(evenSum&0x01)==0;if(mismatch==1){if(oddParityBad){if(evenParityBad){throw new NotFoundException();}decrementOdd=true;}else{if(!evenParityBad){throw new NotFoundException();}decrementEven=true;}}else if(mismatch==-1){if(oddParityBad){if(evenParityBad){throw new NotFoundException();}incrementOdd=true;}else{if(!evenParityBad){throw new NotFoundException();}incrementEven=true;}}else if(mismatch==0){if(oddParityBad){if(!evenParityBad){throw new NotFoundException();}// Both bad
if(oddSum<evenSum){incrementOdd=true;decrementEven=true;}else{decrementOdd=true;incrementEven=true;}}else{if(evenParityBad){throw new NotFoundException();}// Nothing to do!
}}else{throw new NotFoundException();}if(incrementOdd){if(decrementOdd){throw new NotFoundException();}RSSExpandedReader.increment(this.getOddCounts(),this.getOddRoundingErrors());}if(decrementOdd){RSSExpandedReader.decrement(this.getOddCounts(),this.getOddRoundingErrors());}if(incrementEven){if(decrementEven){throw new NotFoundException();}RSSExpandedReader.increment(this.getEvenCounts(),this.getOddRoundingErrors());}if(decrementEven){RSSExpandedReader.decrement(this.getEvenCounts(),this.getEvenRoundingErrors());}}}],[{key:"isValidSequence",value:function isValidSequence(pairs){var _iterator26=_createForOfIteratorHelper(RSSExpandedReader.FINDER_PATTERN_SEQUENCES),_step26;try{for(_iterator26.s();!(_step26=_iterator26.n()).done;){var sequence=_step26.value;if(pairs.length>sequence.length){continue;}var stop=true;for(var j=0;j<pairs.length;j++){if(pairs[j].getFinderPattern().getValue()!=sequence[j]){stop=false;break;}}if(stop){return true;}}}catch(err){_iterator26.e(err);}finally{_iterator26.f();}return false;}},{key:"isPartialRow",value:function isPartialRow(pairs,rows){var _iterator27=_createForOfIteratorHelper(rows),_step27;try{for(_iterator27.s();!(_step27=_iterator27.n()).done;){var r=_step27.value;var allFound=true;var _iterator28=_createForOfIteratorHelper(pairs),_step28;try{for(_iterator28.s();!(_step28=_iterator28.n()).done;){var p=_step28.value;var found=false;var _iterator29=_createForOfIteratorHelper(r.getPairs()),_step29;try{for(_iterator29.s();!(_step29=_iterator29.n()).done;){var pp=_step29.value;if(p.equals(pp)){found=true;break;}}}catch(err){_iterator29.e(err);}finally{_iterator29.f();}if(!found){allFound=false;break;}}}catch(err){_iterator28.e(err);}finally{_iterator28.f();}if(allFound){// the row 'r' contain all the pairs from 'pairs'
return true;}}}catch(err){_iterator27.e(err);}finally{_iterator27.f();}return false;}},{key:"constructResult",value:function constructResult(pairs){var binary=BitArrayBuilder.buildBitArray(pairs);var decoder=createDecoder(binary);var resultingString=decoder.parseInformation();var firstPoints=pairs[0].getFinderPattern().getResultPoints();var lastPoints=pairs[pairs.length-1].getFinderPattern().getResultPoints();var points=[firstPoints[0],firstPoints[1],lastPoints[0],lastPoints[1]];return new Result(resultingString,null,null,points,BarcodeFormat$1.RSS_EXPANDED,null);}},{key:"getNextSecondBar",value:function getNextSecondBar(row,initialPos){var currentPos;if(row.get(initialPos)){currentPos=row.getNextUnset(initialPos);currentPos=row.getNextSet(currentPos);}else{currentPos=row.getNextSet(initialPos);currentPos=row.getNextUnset(currentPos);}return currentPos;}},{key:"reverseCounters",value:function reverseCounters(counters){var length=counters.length;for(var i=0;i<length/2;++i){var tmp=counters[i];counters[i]=counters[length-i-1];counters[length-i-1]=tmp;}}},{key:"isNotA1left",value:function isNotA1left(pattern,isOddPattern,leftChar){// A1: pattern.getValue is 0 (A), and it's an oddPattern, and it is a left char
return!(pattern.getValue()==0&&isOddPattern&&leftChar);}}]);return RSSExpandedReader;}(AbstractRSSReader);RSSExpandedReader.SYMBOL_WIDEST=[7,5,4,3,1];RSSExpandedReader.EVEN_TOTAL_SUBSET=[4,20,52,104,204];RSSExpandedReader.GSUM=[0,348,1388,2948,3988];RSSExpandedReader.FINDER_PATTERNS=[Int32Array.from([1,8,4,1]),Int32Array.from([3,6,4,1]),Int32Array.from([3,4,6,1]),Int32Array.from([3,2,8,1]),Int32Array.from([2,6,5,1]),Int32Array.from([2,2,9,1])// F
];RSSExpandedReader.WEIGHTS=[[1,3,9,27,81,32,96,77],[20,60,180,118,143,7,21,63],[189,145,13,39,117,140,209,205],[193,157,49,147,19,57,171,91],[62,186,136,197,169,85,44,132],[185,133,188,142,4,12,36,108],[113,128,173,97,80,29,87,50],[150,28,84,41,123,158,52,156],[46,138,203,187,139,206,196,166],[76,17,51,153,37,111,122,155],[43,129,176,106,107,110,119,146],[16,48,144,10,30,90,59,177],[109,116,137,200,178,112,125,164],[70,210,208,202,184,130,179,115],[134,191,151,31,93,68,204,190],[148,22,66,198,172,94,71,2],[6,18,54,162,64,192,154,40],[120,149,25,75,14,42,126,167],[79,26,78,23,69,207,199,175],[103,98,83,38,114,131,182,124],[161,61,183,127,170,88,53,159],[55,165,73,8,24,72,5,15],[45,135,194,160,58,174,100,89]];RSSExpandedReader.FINDER_PAT_A=0;RSSExpandedReader.FINDER_PAT_B=1;RSSExpandedReader.FINDER_PAT_C=2;RSSExpandedReader.FINDER_PAT_D=3;RSSExpandedReader.FINDER_PAT_E=4;RSSExpandedReader.FINDER_PAT_F=5;RSSExpandedReader.FINDER_PATTERN_SEQUENCES=[[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_A],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_B],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_D],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_C],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_F],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_F,RSSExpandedReader.FINDER_PAT_F],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_D],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_E],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_F,RSSExpandedReader.FINDER_PAT_F],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_F,RSSExpandedReader.FINDER_PAT_F]];RSSExpandedReader.MAX_PAIRS=11;var Pair=/*#__PURE__*/function(_DataCharacter){_inherits(Pair,_DataCharacter);var _super47=_createSuper(Pair);function Pair(value,checksumPortion,finderPattern){var _this30;_classCallCheck(this,Pair);_this30=_super47.call(this,value,checksumPortion);_this30.count=0;_this30.finderPattern=finderPattern;return _this30;}_createClass(Pair,[{key:"getFinderPattern",value:function getFinderPattern(){return this.finderPattern;}},{key:"getCount",value:function getCount(){return this.count;}},{key:"incrementCount",value:function incrementCount(){this.count++;}}]);return Pair;}(DataCharacter);var RSS14Reader=/*#__PURE__*/function(_AbstractRSSReader2){_inherits(RSS14Reader,_AbstractRSSReader2);var _super48=_createSuper(RSS14Reader);function RSS14Reader(){var _this31;_classCallCheck(this,RSS14Reader);_this31=_super48.apply(this,arguments);_this31.possibleLeftPairs=[];_this31.possibleRightPairs=[];return _this31;}_createClass(RSS14Reader,[{key:"decodeRow",value:function decodeRow(rowNumber,row,hints){var leftPair=this.decodePair(row,false,rowNumber,hints);RSS14Reader.addOrTally(this.possibleLeftPairs,leftPair);row.reverse();var rightPair=this.decodePair(row,true,rowNumber,hints);RSS14Reader.addOrTally(this.possibleRightPairs,rightPair);row.reverse();var _iterator30=_createForOfIteratorHelper(this.possibleLeftPairs),_step30;try{for(_iterator30.s();!(_step30=_iterator30.n()).done;){var left=_step30.value;if(left.getCount()>1){var _iterator31=_createForOfIteratorHelper(this.possibleRightPairs),_step31;try{for(_iterator31.s();!(_step31=_iterator31.n()).done;){var right=_step31.value;if(right.getCount()>1&&RSS14Reader.checkChecksum(left,right)){return RSS14Reader.constructResult(left,right);}}}catch(err){_iterator31.e(err);}finally{_iterator31.f();}}}}catch(err){_iterator30.e(err);}finally{_iterator30.f();}throw new NotFoundException();}},{key:"reset",value:function reset(){this.possibleLeftPairs.length=0;this.possibleRightPairs.length=0;}},{key:"decodePair",value:function decodePair(row,right,rowNumber,hints){try{var startEnd=this.findFinderPattern(row,right);var pattern=this.parseFoundFinderPattern(row,rowNumber,right,startEnd);var resultPointCallback=hints==null?null:hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);if(resultPointCallback!=null){var center=(startEnd[0]+startEnd[1])/2.0;if(right){// row is actually reversed
center=row.getSize()-1-center;}resultPointCallback.foundPossibleResultPoint(new ResultPoint(center,rowNumber));}var outside=this.decodeDataCharacter(row,pattern,true);var inside=this.decodeDataCharacter(row,pattern,false);return new Pair(1597*outside.getValue()+inside.getValue(),outside.getChecksumPortion()+4*inside.getChecksumPortion(),pattern);}catch(err){return null;}}},{key:"decodeDataCharacter",value:function decodeDataCharacter(row,pattern,outsideChar){var counters=this.getDataCharacterCounters();for(var x=0;x<counters.length;x++){counters[x]=0;}if(outsideChar){OneDReader.recordPatternInReverse(row,pattern.getStartEnd()[0],counters);}else{OneDReader.recordPattern(row,pattern.getStartEnd()[1]+1,counters);// reverse it
for(var i=0,j=counters.length-1;i<j;i++,j--){var temp=counters[i];counters[i]=counters[j];counters[j]=temp;}}var numModules=outsideChar?16:15;var elementWidth=MathUtils.sum(new Int32Array(counters))/numModules;var oddCounts=this.getOddCounts();var evenCounts=this.getEvenCounts();var oddRoundingErrors=this.getOddRoundingErrors();var evenRoundingErrors=this.getEvenRoundingErrors();for(var _i22=0;_i22<counters.length;_i22++){var value=counters[_i22]/elementWidth;var count=Math.floor(value+0.5);if(count<1){count=1;}else if(count>8){count=8;}var offset=Math.floor(_i22/2);if((_i22&0x01)===0){oddCounts[offset]=count;oddRoundingErrors[offset]=value-count;}else{evenCounts[offset]=count;evenRoundingErrors[offset]=value-count;}}this.adjustOddEvenCounts(outsideChar,numModules);var oddSum=0;var oddChecksumPortion=0;for(var _i23=oddCounts.length-1;_i23>=0;_i23--){oddChecksumPortion*=9;oddChecksumPortion+=oddCounts[_i23];oddSum+=oddCounts[_i23];}var evenChecksumPortion=0;var evenSum=0;for(var _i24=evenCounts.length-1;_i24>=0;_i24--){evenChecksumPortion*=9;evenChecksumPortion+=evenCounts[_i24];evenSum+=evenCounts[_i24];}var checksumPortion=oddChecksumPortion+3*evenChecksumPortion;if(outsideChar){if((oddSum&0x01)!==0||oddSum>12||oddSum<4){throw new NotFoundException();}var group=(12-oddSum)/2;var oddWidest=RSS14Reader.OUTSIDE_ODD_WIDEST[group];var evenWidest=9-oddWidest;var vOdd=RSSUtils.getRSSvalue(oddCounts,oddWidest,false);var vEven=RSSUtils.getRSSvalue(evenCounts,evenWidest,true);var tEven=RSS14Reader.OUTSIDE_EVEN_TOTAL_SUBSET[group];var gSum=RSS14Reader.OUTSIDE_GSUM[group];return new DataCharacter(vOdd*tEven+vEven+gSum,checksumPortion);}else{if((evenSum&0x01)!==0||evenSum>10||evenSum<4){throw new NotFoundException();}var _group=(10-evenSum)/2;var _oddWidest=RSS14Reader.INSIDE_ODD_WIDEST[_group];var _evenWidest=9-_oddWidest;var _vOdd=RSSUtils.getRSSvalue(oddCounts,_oddWidest,true);var _vEven=RSSUtils.getRSSvalue(evenCounts,_evenWidest,false);var tOdd=RSS14Reader.INSIDE_ODD_TOTAL_SUBSET[_group];var _gSum=RSS14Reader.INSIDE_GSUM[_group];return new DataCharacter(_vEven*tOdd+_vOdd+_gSum,checksumPortion);}}},{key:"findFinderPattern",value:function findFinderPattern(row,rightFinderPattern){var counters=this.getDecodeFinderCounters();counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;var width=row.getSize();var isWhite=false;var rowOffset=0;while(rowOffset<width){isWhite=!row.get(rowOffset);if(rightFinderPattern===isWhite){// Will encounter white first when searching for right finder pattern
break;}rowOffset++;}var counterPosition=0;var patternStart=rowOffset;for(var x=rowOffset;x<width;x++){if(row.get(x)!==isWhite){counters[counterPosition]++;}else{if(counterPosition===3){if(AbstractRSSReader.isFinderPattern(counters)){return[patternStart,x];}patternStart+=counters[0]+counters[1];counters[0]=counters[2];counters[1]=counters[3];counters[2]=0;counters[3]=0;counterPosition--;}else{counterPosition++;}counters[counterPosition]=1;isWhite=!isWhite;}}throw new NotFoundException();}},{key:"parseFoundFinderPattern",value:function parseFoundFinderPattern(row,rowNumber,right,startEnd){// Actually we found elements 2-5
var firstIsBlack=row.get(startEnd[0]);var firstElementStart=startEnd[0]-1;// Locate element 1
while(firstElementStart>=0&&firstIsBlack!==row.get(firstElementStart)){firstElementStart--;}firstElementStart++;var firstCounter=startEnd[0]-firstElementStart;// Make 'counters' hold 1-4
var counters=this.getDecodeFinderCounters();var copy=new Int32Array(counters.length);System.arraycopy(counters,0,copy,1,counters.length-1);copy[0]=firstCounter;var value=this.parseFinderValue(copy,RSS14Reader.FINDER_PATTERNS);var start=firstElementStart;var end=startEnd[1];if(right){// row is actually reversed
start=row.getSize()-1-start;end=row.getSize()-1-end;}return new FinderPattern(value,[firstElementStart,startEnd[1]],start,end,rowNumber);}},{key:"adjustOddEvenCounts",value:function adjustOddEvenCounts(outsideChar,numModules){var oddSum=MathUtils.sum(new Int32Array(this.getOddCounts()));var evenSum=MathUtils.sum(new Int32Array(this.getEvenCounts()));var incrementOdd=false;var decrementOdd=false;var incrementEven=false;var decrementEven=false;if(outsideChar){if(oddSum>12){decrementOdd=true;}else if(oddSum<4){incrementOdd=true;}if(evenSum>12){decrementEven=true;}else if(evenSum<4){incrementEven=true;}}else{if(oddSum>11){decrementOdd=true;}else if(oddSum<5){incrementOdd=true;}if(evenSum>10){decrementEven=true;}else if(evenSum<4){incrementEven=true;}}var mismatch=oddSum+evenSum-numModules;var oddParityBad=(oddSum&0x01)===(outsideChar?1:0);var evenParityBad=(evenSum&0x01)===1;if(mismatch===1){if(oddParityBad){if(evenParityBad){throw new NotFoundException();}decrementOdd=true;}else{if(!evenParityBad){throw new NotFoundException();}decrementEven=true;}}else if(mismatch===-1){if(oddParityBad){if(evenParityBad){throw new NotFoundException();}incrementOdd=true;}else{if(!evenParityBad){throw new NotFoundException();}incrementEven=true;}}else if(mismatch===0){if(oddParityBad){if(!evenParityBad){throw new NotFoundException();}// Both bad
if(oddSum<evenSum){incrementOdd=true;decrementEven=true;}else{decrementOdd=true;incrementEven=true;}}else{if(evenParityBad){throw new NotFoundException();}// Nothing to do!
}}else{throw new NotFoundException();}if(incrementOdd){if(decrementOdd){throw new NotFoundException();}AbstractRSSReader.increment(this.getOddCounts(),this.getOddRoundingErrors());}if(decrementOdd){AbstractRSSReader.decrement(this.getOddCounts(),this.getOddRoundingErrors());}if(incrementEven){if(decrementEven){throw new NotFoundException();}AbstractRSSReader.increment(this.getEvenCounts(),this.getOddRoundingErrors());}if(decrementEven){AbstractRSSReader.decrement(this.getEvenCounts(),this.getEvenRoundingErrors());}}}],[{key:"addOrTally",value:function addOrTally(possiblePairs,pair){if(pair==null){return;}var found=false;var _iterator32=_createForOfIteratorHelper(possiblePairs),_step32;try{for(_iterator32.s();!(_step32=_iterator32.n()).done;){var other=_step32.value;if(other.getValue()===pair.getValue()){other.incrementCount();found=true;break;}}}catch(err){_iterator32.e(err);}finally{_iterator32.f();}if(!found){possiblePairs.push(pair);}}},{key:"constructResult",value:function constructResult(leftPair,rightPair){var symbolValue=4537077*leftPair.getValue()+rightPair.getValue();var text=new String(symbolValue).toString();var buffer=new StringBuilder();for(var i=13-text.length;i>0;i--){buffer.append('0');}buffer.append(text);var checkDigit=0;for(var _i25=0;_i25<13;_i25++){var digit=buffer.charAt(_i25).charCodeAt(0)-'0'.charCodeAt(0);checkDigit+=(_i25&0x01)===0?3*digit:digit;}checkDigit=10-checkDigit%10;if(checkDigit===10){checkDigit=0;}buffer.append(checkDigit.toString());var leftPoints=leftPair.getFinderPattern().getResultPoints();var rightPoints=rightPair.getFinderPattern().getResultPoints();return new Result(buffer.toString(),null,0,[leftPoints[0],leftPoints[1],rightPoints[0],rightPoints[1]],BarcodeFormat$1.RSS_14,new Date().getTime());}},{key:"checkChecksum",value:function checkChecksum(leftPair,rightPair){var checkValue=(leftPair.getChecksumPortion()+16*rightPair.getChecksumPortion())%79;var targetCheckValue=9*leftPair.getFinderPattern().getValue()+rightPair.getFinderPattern().getValue();if(targetCheckValue>72){targetCheckValue--;}if(targetCheckValue>8){targetCheckValue--;}return checkValue===targetCheckValue;}}]);return RSS14Reader;}(AbstractRSSReader);RSS14Reader.OUTSIDE_EVEN_TOTAL_SUBSET=[1,10,34,70,126];RSS14Reader.INSIDE_ODD_TOTAL_SUBSET=[4,20,48,81];RSS14Reader.OUTSIDE_GSUM=[0,161,961,2015,2715];RSS14Reader.INSIDE_GSUM=[0,336,1036,1516];RSS14Reader.OUTSIDE_ODD_WIDEST=[8,6,4,3,1];RSS14Reader.INSIDE_ODD_WIDEST=[2,4,6,8];RSS14Reader.FINDER_PATTERNS=[Int32Array.from([3,8,2,1]),Int32Array.from([3,5,5,1]),Int32Array.from([3,3,7,1]),Int32Array.from([3,1,9,1]),Int32Array.from([2,7,4,1]),Int32Array.from([2,5,6,1]),Int32Array.from([2,3,8,1]),Int32Array.from([1,5,7,1]),Int32Array.from([1,3,9,1])];/**
* @author Daniel Switkin <dswitkin@google.com>
* @author Sean Owen
*/var MultiFormatOneDReader=/*#__PURE__*/function(_OneDReader7){_inherits(MultiFormatOneDReader,_OneDReader7);var _super49=_createSuper(MultiFormatOneDReader);function MultiFormatOneDReader(hints,verbose){var _this32;_classCallCheck(this,MultiFormatOneDReader);_this32=_super49.call(this);_this32.readers=[];_this32.verbose=verbose===true;var possibleFormats=!hints?null:hints.get(DecodeHintType$1.POSSIBLE_FORMATS);var useCode39CheckDigit=hints&&hints.get(DecodeHintType$1.ASSUME_CODE_39_CHECK_DIGIT)!==undefined;if(possibleFormats){if(possibleFormats.includes(BarcodeFormat$1.EAN_13)||possibleFormats.includes(BarcodeFormat$1.UPC_A)||possibleFormats.includes(BarcodeFormat$1.EAN_8)||possibleFormats.includes(BarcodeFormat$1.UPC_E)){_this32.readers.push(new MultiFormatUPCEANReader(hints));}if(possibleFormats.includes(BarcodeFormat$1.CODE_39)){_this32.readers.push(new Code39Reader(useCode39CheckDigit));}// if (possibleFormats.includes(BarcodeFormat.CODE_93)) {
// this.readers.push(new Code93Reader());
// }
if(possibleFormats.includes(BarcodeFormat$1.CODE_128)){_this32.readers.push(new Code128Reader());}if(possibleFormats.includes(BarcodeFormat$1.ITF)){_this32.readers.push(new ITFReader());}// if (possibleFormats.includes(BarcodeFormat.CODABAR)) {
// this.readers.push(new CodaBarReader());
// }
if(possibleFormats.includes(BarcodeFormat$1.RSS_14)){_this32.readers.push(new RSS14Reader());}if(possibleFormats.includes(BarcodeFormat$1.RSS_EXPANDED)){_this32.readers.push(new RSSExpandedReader(_this32.verbose));}}else{// Case when no hints were provided -> add all.
_this32.readers.push(new MultiFormatUPCEANReader(hints));_this32.readers.push(new Code39Reader());// this.readers.push(new CodaBarReader());
// this.readers.push(new Code93Reader());
_this32.readers.push(new MultiFormatUPCEANReader(hints));_this32.readers.push(new Code128Reader());_this32.readers.push(new ITFReader());_this32.readers.push(new RSS14Reader());_this32.readers.push(new RSSExpandedReader(_this32.verbose));}return _this32;}// @Override
_createClass(MultiFormatOneDReader,[{key:"decodeRow",value:function decodeRow(rowNumber,row,hints){for(var i=0;i<this.readers.length;i++){try{return this.readers[i].decodeRow(rowNumber,row,hints);}catch(re){// continue
}}throw new NotFoundException();}// @Override
},{key:"reset",value:function reset(){this.readers.forEach(function(reader){return reader.reset();});}}]);return MultiFormatOneDReader;}(OneDReader);/**
* @deprecated Moving to @zxing/browser
*
* Barcode reader reader to use from browser.
*/var BrowserBarcodeReader=/*#__PURE__*/function(_BrowserCodeReader2){_inherits(BrowserBarcodeReader,_BrowserCodeReader2);var _super50=_createSuper(BrowserBarcodeReader);/**
* Creates an instance of BrowserBarcodeReader.
* @param {number} [timeBetweenScansMillis=500] the time delay between subsequent decode tries
* @param {Map<DecodeHintType, any>} hints
*/function BrowserBarcodeReader(){var timeBetweenScansMillis=arguments.length>0&&arguments[0]!==undefined?arguments[0]:500;var hints=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,BrowserBarcodeReader);return _super50.call(this,new MultiFormatOneDReader(hints),timeBetweenScansMillis,hints);}return _createClass(BrowserBarcodeReader);}(BrowserCodeReader);/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will
* use blocks of differing sizes within one version, so, this encapsulates the parameters for
* each set of blocks. It also holds the number of error-correction codewords per block since it
* will be the same across all blocks within one version.</p>
*/var ECBlocks=/*#__PURE__*/function(){function ECBlocks(ecCodewords,ecBlocks1,ecBlocks2){_classCallCheck(this,ECBlocks);this.ecCodewords=ecCodewords;this.ecBlocks=[ecBlocks1];ecBlocks2&&this.ecBlocks.push(ecBlocks2);}_createClass(ECBlocks,[{key:"getECCodewords",value:function getECCodewords(){return this.ecCodewords;}},{key:"getECBlocks",value:function getECBlocks(){return this.ecBlocks;}}]);return ECBlocks;}();/**
* <p>Encapsulates the parameters for one error-correction block in one symbol version.
* This includes the number of data codewords, and the number of times a block with these
* parameters is used consecutively in the Data Matrix code version's format.</p>
*/var ECB=/*#__PURE__*/function(){function ECB(count,dataCodewords){_classCallCheck(this,ECB);this.count=count;this.dataCodewords=dataCodewords;}_createClass(ECB,[{key:"getCount",value:function getCount(){return this.count;}},{key:"getDataCodewords",value:function getDataCodewords(){return this.dataCodewords;}}]);return ECB;}();/**
* The Version object encapsulates attributes about a particular
* size Data Matrix Code.
*
* @author bbrown@google.com (Brian Brown)
*/var Version=/*#__PURE__*/function(){function Version(versionNumber,symbolSizeRows,symbolSizeColumns,dataRegionSizeRows,dataRegionSizeColumns,ecBlocks){_classCallCheck(this,Version);this.versionNumber=versionNumber;this.symbolSizeRows=symbolSizeRows;this.symbolSizeColumns=symbolSizeColumns;this.dataRegionSizeRows=dataRegionSizeRows;this.dataRegionSizeColumns=dataRegionSizeColumns;this.ecBlocks=ecBlocks;// Calculate the total number of codewords
var total=0;var ecCodewords=ecBlocks.getECCodewords();var ecbArray=ecBlocks.getECBlocks();var _iterator33=_createForOfIteratorHelper(ecbArray),_step33;try{for(_iterator33.s();!(_step33=_iterator33.n()).done;){var ecBlock=_step33.value;total+=ecBlock.getCount()*(ecBlock.getDataCodewords()+ecCodewords);}}catch(err){_iterator33.e(err);}finally{_iterator33.f();}this.totalCodewords=total;}_createClass(Version,[{key:"getVersionNumber",value:function getVersionNumber(){return this.versionNumber;}},{key:"getSymbolSizeRows",value:function getSymbolSizeRows(){return this.symbolSizeRows;}},{key:"getSymbolSizeColumns",value:function getSymbolSizeColumns(){return this.symbolSizeColumns;}},{key:"getDataRegionSizeRows",value:function getDataRegionSizeRows(){return this.dataRegionSizeRows;}},{key:"getDataRegionSizeColumns",value:function getDataRegionSizeColumns(){return this.dataRegionSizeColumns;}},{key:"getTotalCodewords",value:function getTotalCodewords(){return this.totalCodewords;}},{key:"getECBlocks",value:function getECBlocks(){return this.ecBlocks;}/**
* <p>Deduces version information from Data Matrix dimensions.</p>
*
* @param numRows Number of rows in modules
* @param numColumns Number of columns in modules
* @return Version for a Data Matrix Code of those dimensions
* @throws FormatException if dimensions do correspond to a valid Data Matrix size
*/},{key:"toString",value:// @Override
function toString(){return''+this.versionNumber;}/**
* See ISO 16022:2006 5.5.1 Table 7
*/}],[{key:"getVersionForDimensions",value:function getVersionForDimensions(numRows,numColumns){if((numRows&0x01)!==0||(numColumns&0x01)!==0){throw new FormatException();}var _iterator34=_createForOfIteratorHelper(Version.VERSIONS),_step34;try{for(_iterator34.s();!(_step34=_iterator34.n()).done;){var version=_step34.value;if(version.symbolSizeRows===numRows&&version.symbolSizeColumns===numColumns){return version;}}}catch(err){_iterator34.e(err);}finally{_iterator34.f();}throw new FormatException();}},{key:"buildVersions",value:function buildVersions(){return[new Version(1,10,10,8,8,new ECBlocks(5,new ECB(1,3))),new Version(2,12,12,10,10,new ECBlocks(7,new ECB(1,5))),new Version(3,14,14,12,12,new ECBlocks(10,new ECB(1,8))),new Version(4,16,16,14,14,new ECBlocks(12,new ECB(1,12))),new Version(5,18,18,16,16,new ECBlocks(14,new ECB(1,18))),new Version(6,20,20,18,18,new ECBlocks(18,new ECB(1,22))),new Version(7,22,22,20,20,new ECBlocks(20,new ECB(1,30))),new Version(8,24,24,22,22,new ECBlocks(24,new ECB(1,36))),new Version(9,26,26,24,24,new ECBlocks(28,new ECB(1,44))),new Version(10,32,32,14,14,new ECBlocks(36,new ECB(1,62))),new Version(11,36,36,16,16,new ECBlocks(42,new ECB(1,86))),new Version(12,40,40,18,18,new ECBlocks(48,new ECB(1,114))),new Version(13,44,44,20,20,new ECBlocks(56,new ECB(1,144))),new Version(14,48,48,22,22,new ECBlocks(68,new ECB(1,174))),new Version(15,52,52,24,24,new ECBlocks(42,new ECB(2,102))),new Version(16,64,64,14,14,new ECBlocks(56,new ECB(2,140))),new Version(17,72,72,16,16,new ECBlocks(36,new ECB(4,92))),new Version(18,80,80,18,18,new ECBlocks(48,new ECB(4,114))),new Version(19,88,88,20,20,new ECBlocks(56,new ECB(4,144))),new Version(20,96,96,22,22,new ECBlocks(68,new ECB(4,174))),new Version(21,104,104,24,24,new ECBlocks(56,new ECB(6,136))),new Version(22,120,120,18,18,new ECBlocks(68,new ECB(6,175))),new Version(23,132,132,20,20,new ECBlocks(62,new ECB(8,163))),new Version(24,144,144,22,22,new ECBlocks(62,new ECB(8,156),new ECB(2,155))),new Version(25,8,18,6,16,new ECBlocks(7,new ECB(1,5))),new Version(26,8,32,6,14,new ECBlocks(11,new ECB(1,10))),new Version(27,12,26,10,24,new ECBlocks(14,new ECB(1,16))),new Version(28,12,36,10,16,new ECBlocks(18,new ECB(1,22))),new Version(29,16,36,14,16,new ECBlocks(24,new ECB(1,32))),new Version(30,16,48,14,22,new ECBlocks(28,new ECB(1,49)))];}}]);return Version;}();Version.VERSIONS=Version.buildVersions();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* @author bbrown@google.com (Brian Brown)
*/var BitMatrixParser=/*#__PURE__*/function(){/**
* @param bitMatrix {@link BitMatrix} to parse
* @throws FormatException if dimension is < 8 or > 144 or not 0 mod 2
*/function BitMatrixParser(bitMatrix){_classCallCheck(this,BitMatrixParser);var dimension=bitMatrix.getHeight();if(dimension<8||dimension>144||(dimension&0x01)!==0){throw new FormatException();}this.version=BitMatrixParser.readVersion(bitMatrix);this.mappingBitMatrix=this.extractDataRegion(bitMatrix);this.readMappingMatrix=new BitMatrix(this.mappingBitMatrix.getWidth(),this.mappingBitMatrix.getHeight());}_createClass(BitMatrixParser,[{key:"getVersion",value:function getVersion(){return this.version;}/**
* <p>Creates the version object based on the dimension of the original bit matrix from
* the datamatrix code.</p>
*
* <p>See ISO 16022:2006 Table 7 - ECC 200 symbol attributes</p>
*
* @param bitMatrix Original {@link BitMatrix} including alignment patterns
* @return {@link Version} encapsulating the Data Matrix Code's "version"
* @throws FormatException if the dimensions of the mapping matrix are not valid
* Data Matrix dimensions.
*/},{key:"readCodewords",value:/**
* <p>Reads the bits in the {@link BitMatrix} representing the mapping matrix (No alignment patterns)
* in the correct order in order to reconstitute the codewords bytes contained within the
* Data Matrix Code.</p>
*
* @return bytes encoded within the Data Matrix Code
* @throws FormatException if the exact number of bytes expected is not read
*/function readCodewords(){var result=new Int8Array(this.version.getTotalCodewords());var resultOffset=0;var row=4;var column=0;var numRows=this.mappingBitMatrix.getHeight();var numColumns=this.mappingBitMatrix.getWidth();var corner1Read=false;var corner2Read=false;var corner3Read=false;var corner4Read=false;// Read all of the codewords
do{// Check the four corner cases
if(row===numRows&&column===0&&!corner1Read){result[resultOffset++]=this.readCorner1(numRows,numColumns)&0xff;row-=2;column+=2;corner1Read=true;}else if(row===numRows-2&&column===0&&(numColumns&0x03)!==0&&!corner2Read){result[resultOffset++]=this.readCorner2(numRows,numColumns)&0xff;row-=2;column+=2;corner2Read=true;}else if(row===numRows+4&&column===2&&(numColumns&0x07)===0&&!corner3Read){result[resultOffset++]=this.readCorner3(numRows,numColumns)&0xff;row-=2;column+=2;corner3Read=true;}else if(row===numRows-2&&column===0&&(numColumns&0x07)===4&&!corner4Read){result[resultOffset++]=this.readCorner4(numRows,numColumns)&0xff;row-=2;column+=2;corner4Read=true;}else{// Sweep upward diagonally to the right
do{if(row<numRows&&column>=0&&!this.readMappingMatrix.get(column,row)){result[resultOffset++]=this.readUtah(row,column,numRows,numColumns)&0xff;}row-=2;column+=2;}while(row>=0&&column<numColumns);row+=1;column+=3;// Sweep downward diagonally to the left
do{if(row>=0&&column<numColumns&&!this.readMappingMatrix.get(column,row)){result[resultOffset++]=this.readUtah(row,column,numRows,numColumns)&0xff;}row+=2;column-=2;}while(row<numRows&&column>=0);row+=3;column+=1;}}while(row<numRows||column<numColumns);if(resultOffset!==this.version.getTotalCodewords()){throw new FormatException();}return result;}/**
* <p>Reads a bit of the mapping matrix accounting for boundary wrapping.</p>
*
* @param row Row to read in the mapping matrix
* @param column Column to read in the mapping matrix
* @param numRows Number of rows in the mapping matrix
* @param numColumns Number of columns in the mapping matrix
* @return value of the given bit in the mapping matrix
*/},{key:"readModule",value:function readModule(row,column,numRows,numColumns){// Adjust the row and column indices based on boundary wrapping
if(row<0){row+=numRows;column+=4-(numRows+4&0x07);}if(column<0){column+=numColumns;row+=4-(numColumns+4&0x07);}this.readMappingMatrix.set(column,row);return this.mappingBitMatrix.get(column,row);}/**
* <p>Reads the 8 bits of the standard Utah-shaped pattern.</p>
*
* <p>See ISO 16022:2006, 5.8.1 Figure 6</p>
*
* @param row Current row in the mapping matrix, anchored at the 8th bit (LSB) of the pattern
* @param column Current column in the mapping matrix, anchored at the 8th bit (LSB) of the pattern
* @param numRows Number of rows in the mapping matrix
* @param numColumns Number of columns in the mapping matrix
* @return byte from the utah shape
*/},{key:"readUtah",value:function readUtah(row,column,numRows,numColumns){var currentByte=0;if(this.readModule(row-2,column-2,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(row-2,column-1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(row-1,column-2,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(row-1,column-1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(row-1,column,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(row,column-2,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(row,column-1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(row,column,numRows,numColumns)){currentByte|=1;}return currentByte;}/**
* <p>Reads the 8 bits of the special corner condition 1.</p>
*
* <p>See ISO 16022:2006, Figure F.3</p>
*
* @param numRows Number of rows in the mapping matrix
* @param numColumns Number of columns in the mapping matrix
* @return byte from the Corner condition 1
*/},{key:"readCorner1",value:function readCorner1(numRows,numColumns){var currentByte=0;if(this.readModule(numRows-1,0,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(numRows-1,1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(numRows-1,2,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(0,numColumns-2,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(0,numColumns-1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(1,numColumns-1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(2,numColumns-1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(3,numColumns-1,numRows,numColumns)){currentByte|=1;}return currentByte;}/**
* <p>Reads the 8 bits of the special corner condition 2.</p>
*
* <p>See ISO 16022:2006, Figure F.4</p>
*
* @param numRows Number of rows in the mapping matrix
* @param numColumns Number of columns in the mapping matrix
* @return byte from the Corner condition 2
*/},{key:"readCorner2",value:function readCorner2(numRows,numColumns){var currentByte=0;if(this.readModule(numRows-3,0,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(numRows-2,0,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(numRows-1,0,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(0,numColumns-4,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(0,numColumns-3,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(0,numColumns-2,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(0,numColumns-1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(1,numColumns-1,numRows,numColumns)){currentByte|=1;}return currentByte;}/**
* <p>Reads the 8 bits of the special corner condition 3.</p>
*
* <p>See ISO 16022:2006, Figure F.5</p>
*
* @param numRows Number of rows in the mapping matrix
* @param numColumns Number of columns in the mapping matrix
* @return byte from the Corner condition 3
*/},{key:"readCorner3",value:function readCorner3(numRows,numColumns){var currentByte=0;if(this.readModule(numRows-1,0,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(numRows-1,numColumns-1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(0,numColumns-3,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(0,numColumns-2,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(0,numColumns-1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(1,numColumns-3,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(1,numColumns-2,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(1,numColumns-1,numRows,numColumns)){currentByte|=1;}return currentByte;}/**
* <p>Reads the 8 bits of the special corner condition 4.</p>
*
* <p>See ISO 16022:2006, Figure F.6</p>
*
* @param numRows Number of rows in the mapping matrix
* @param numColumns Number of columns in the mapping matrix
* @return byte from the Corner condition 4
*/},{key:"readCorner4",value:function readCorner4(numRows,numColumns){var currentByte=0;if(this.readModule(numRows-3,0,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(numRows-2,0,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(numRows-1,0,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(0,numColumns-2,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(0,numColumns-1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(1,numColumns-1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(2,numColumns-1,numRows,numColumns)){currentByte|=1;}currentByte<<=1;if(this.readModule(3,numColumns-1,numRows,numColumns)){currentByte|=1;}return currentByte;}/**
* <p>Extracts the data region from a {@link BitMatrix} that contains
* alignment patterns.</p>
*
* @param bitMatrix Original {@link BitMatrix} with alignment patterns
* @return BitMatrix that has the alignment patterns removed
*/},{key:"extractDataRegion",value:function extractDataRegion(bitMatrix){var symbolSizeRows=this.version.getSymbolSizeRows();var symbolSizeColumns=this.version.getSymbolSizeColumns();if(bitMatrix.getHeight()!==symbolSizeRows){throw new IllegalArgumentException('Dimension of bitMatrix must match the version size');}var dataRegionSizeRows=this.version.getDataRegionSizeRows();var dataRegionSizeColumns=this.version.getDataRegionSizeColumns();var numDataRegionsRow=symbolSizeRows/dataRegionSizeRows|0;var numDataRegionsColumn=symbolSizeColumns/dataRegionSizeColumns|0;var sizeDataRegionRow=numDataRegionsRow*dataRegionSizeRows;var sizeDataRegionColumn=numDataRegionsColumn*dataRegionSizeColumns;var bitMatrixWithoutAlignment=new BitMatrix(sizeDataRegionColumn,sizeDataRegionRow);for(var dataRegionRow=0;dataRegionRow<numDataRegionsRow;++dataRegionRow){var dataRegionRowOffset=dataRegionRow*dataRegionSizeRows;for(var dataRegionColumn=0;dataRegionColumn<numDataRegionsColumn;++dataRegionColumn){var dataRegionColumnOffset=dataRegionColumn*dataRegionSizeColumns;for(var i=0;i<dataRegionSizeRows;++i){var readRowOffset=dataRegionRow*(dataRegionSizeRows+2)+1+i;var writeRowOffset=dataRegionRowOffset+i;for(var j=0;j<dataRegionSizeColumns;++j){var readColumnOffset=dataRegionColumn*(dataRegionSizeColumns+2)+1+j;if(bitMatrix.get(readColumnOffset,readRowOffset)){var writeColumnOffset=dataRegionColumnOffset+j;bitMatrixWithoutAlignment.set(writeColumnOffset,writeRowOffset);}}}}}return bitMatrixWithoutAlignment;}}],[{key:"readVersion",value:function readVersion(bitMatrix){var numRows=bitMatrix.getHeight();var numColumns=bitMatrix.getWidth();return Version.getVersionForDimensions(numRows,numColumns);}}]);return BitMatrixParser;}();/**
* <p>Encapsulates a block of data within a Data Matrix Code. Data Matrix Codes may split their data into
* multiple blocks, each of which is a unit of data and error-correction codewords. Each
* is represented by an instance of this class.</p>
*
* @author bbrown@google.com (Brian Brown)
*/var DataBlock=/*#__PURE__*/function(){function DataBlock(numDataCodewords,codewords){_classCallCheck(this,DataBlock);this.numDataCodewords=numDataCodewords;this.codewords=codewords;}/**
* <p>When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them.
* That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This
* method will separate the data into original blocks.</p>
*
* @param rawCodewords bytes as read directly from the Data Matrix Code
* @param version version of the Data Matrix Code
* @return DataBlocks containing original bytes, "de-interleaved" from representation in the
* Data Matrix Code
*/_createClass(DataBlock,[{key:"getNumDataCodewords",value:function getNumDataCodewords(){return this.numDataCodewords;}},{key:"getCodewords",value:function getCodewords(){return this.codewords;}}],[{key:"getDataBlocks",value:function getDataBlocks(rawCodewords,version){// Figure out the number and size of data blocks used by this version
var ecBlocks=version.getECBlocks();// First count the total number of data blocks
var totalBlocks=0;var ecBlockArray=ecBlocks.getECBlocks();var _iterator35=_createForOfIteratorHelper(ecBlockArray),_step35;try{for(_iterator35.s();!(_step35=_iterator35.n()).done;){var ecBlock=_step35.value;totalBlocks+=ecBlock.getCount();}// Now establish DataBlocks of the appropriate size and number of data codewords
}catch(err){_iterator35.e(err);}finally{_iterator35.f();}var result=new Array(totalBlocks);var numResultBlocks=0;var _iterator36=_createForOfIteratorHelper(ecBlockArray),_step36;try{for(_iterator36.s();!(_step36=_iterator36.n()).done;){var _ecBlock=_step36.value;for(var _i27=0;_i27<_ecBlock.getCount();_i27++){var numDataCodewords=_ecBlock.getDataCodewords();var numBlockCodewords=ecBlocks.getECCodewords()+numDataCodewords;result[numResultBlocks++]=new DataBlock(numDataCodewords,new Uint8Array(numBlockCodewords));}}// All blocks have the same amount of data, except that the last n
// (where n may be 0) have 1 less byte. Figure out where these start.
// TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144
}catch(err){_iterator36.e(err);}finally{_iterator36.f();}var longerBlocksTotalCodewords=result[0].codewords.length;// int shorterBlocksTotalCodewords = longerBlocksTotalCodewords - 1;
var longerBlocksNumDataCodewords=longerBlocksTotalCodewords-ecBlocks.getECCodewords();var shorterBlocksNumDataCodewords=longerBlocksNumDataCodewords-1;// The last elements of result may be 1 element shorter for 144 matrix
// first fill out as many elements as all of them have minus 1
var rawCodewordsOffset=0;for(var i=0;i<shorterBlocksNumDataCodewords;i++){for(var j=0;j<numResultBlocks;j++){result[j].codewords[i]=rawCodewords[rawCodewordsOffset++];}}// Fill out the last data block in the longer ones
var specialVersion=version.getVersionNumber()===24;var numLongerBlocks=specialVersion?8:numResultBlocks;for(var _j2=0;_j2<numLongerBlocks;_j2++){result[_j2].codewords[longerBlocksNumDataCodewords-1]=rawCodewords[rawCodewordsOffset++];}// Now add in error correction blocks
var max=result[0].codewords.length;for(var _i26=longerBlocksNumDataCodewords;_i26<max;_i26++){for(var _j3=0;_j3<numResultBlocks;_j3++){var jOffset=specialVersion?(_j3+8)%numResultBlocks:_j3;var iOffset=specialVersion&&jOffset>7?_i26-1:_i26;result[jOffset].codewords[iOffset]=rawCodewords[rawCodewordsOffset++];}}if(rawCodewordsOffset!==rawCodewords.length){throw new IllegalArgumentException();}return result;}}]);return DataBlock;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>This provides an easy abstraction to read bits at a time from a sequence of bytes, where the
* number of bits read is not often a multiple of 8.</p>
*
* <p>This class is thread-safe but not reentrant -- unless the caller modifies the bytes array
* it passed in, in which case all bets are off.</p>
*
* @author Sean Owen
*/var BitSource=/*#__PURE__*/function(){/**
* @param bytes bytes from which this will read bits. Bits will be read from the first byte first.
* Bits are read within a byte from most-significant to least-significant bit.
*/function BitSource(bytes){_classCallCheck(this,BitSource);this.bytes=bytes;this.byteOffset=0;this.bitOffset=0;}/**
* @return index of next bit in current byte which would be read by the next call to {@link #readBits(int)}.
*/_createClass(BitSource,[{key:"getBitOffset",value:function getBitOffset(){return this.bitOffset;}/**
* @return index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}.
*/},{key:"getByteOffset",value:function getByteOffset(){return this.byteOffset;}/**
* @param numBits number of bits to read
* @return int representing the bits read. The bits will appear as the least-significant
* bits of the int
* @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available
*/},{key:"readBits",value:function readBits(numBits/*int*/){if(numBits<1||numBits>32||numBits>this.available()){throw new IllegalArgumentException(''+numBits);}var result=0;var bitOffset=this.bitOffset;var byteOffset=this.byteOffset;var bytes=this.bytes;// First, read remainder from current byte
if(bitOffset>0){var bitsLeft=8-bitOffset;var toRead=numBits<bitsLeft?numBits:bitsLeft;var bitsToNotRead=bitsLeft-toRead;var mask=0xFF>>8-toRead<<bitsToNotRead;result=(bytes[byteOffset]&mask)>>bitsToNotRead;numBits-=toRead;bitOffset+=toRead;if(bitOffset===8){bitOffset=0;byteOffset++;}}// Next read whole bytes
if(numBits>0){while(numBits>=8){result=result<<8|bytes[byteOffset]&0xFF;byteOffset++;numBits-=8;}// Finally read a partial byte
if(numBits>0){var _bitsToNotRead=8-numBits;var _mask=0xFF>>_bitsToNotRead<<_bitsToNotRead;result=result<<numBits|(bytes[byteOffset]&_mask)>>_bitsToNotRead;bitOffset+=numBits;}}this.bitOffset=bitOffset;this.byteOffset=byteOffset;return result;}/**
* @return number of bits that can be read successfully
*/},{key:"available",value:function available(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset;}}]);return BitSource;}();var Mode;(function(Mode){Mode[Mode["PAD_ENCODE"]=0]="PAD_ENCODE";Mode[Mode["ASCII_ENCODE"]=1]="ASCII_ENCODE";Mode[Mode["C40_ENCODE"]=2]="C40_ENCODE";Mode[Mode["TEXT_ENCODE"]=3]="TEXT_ENCODE";Mode[Mode["ANSIX12_ENCODE"]=4]="ANSIX12_ENCODE";Mode[Mode["EDIFACT_ENCODE"]=5]="EDIFACT_ENCODE";Mode[Mode["BASE256_ENCODE"]=6]="BASE256_ENCODE";})(Mode||(Mode={}));/**
* <p>Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes
* in one Data Matrix Code. This class decodes the bits back into text.</p>
*
* <p>See ISO 16022:2006, 5.2.1 - 5.2.9.2</p>
*
* @author bbrown@google.com (Brian Brown)
* @author Sean Owen
*/var DecodedBitStreamParser=/*#__PURE__*/function(){function DecodedBitStreamParser(){_classCallCheck(this,DecodedBitStreamParser);}_createClass(DecodedBitStreamParser,null,[{key:"decode",value:function decode(bytes){var bits=new BitSource(bytes);var result=new StringBuilder();var resultTrailer=new StringBuilder();var byteSegments=new Array();var mode=Mode.ASCII_ENCODE;do{if(mode===Mode.ASCII_ENCODE){mode=this.decodeAsciiSegment(bits,result,resultTrailer);}else{switch(mode){case Mode.C40_ENCODE:this.decodeC40Segment(bits,result);break;case Mode.TEXT_ENCODE:this.decodeTextSegment(bits,result);break;case Mode.ANSIX12_ENCODE:this.decodeAnsiX12Segment(bits,result);break;case Mode.EDIFACT_ENCODE:this.decodeEdifactSegment(bits,result);break;case Mode.BASE256_ENCODE:this.decodeBase256Segment(bits,result,byteSegments);break;default:throw new FormatException();}mode=Mode.ASCII_ENCODE;}}while(mode!==Mode.PAD_ENCODE&&bits.available()>0);if(resultTrailer.length()>0){result.append(resultTrailer.toString());}return new DecoderResult(bytes,result.toString(),byteSegments.length===0?null:byteSegments,null);}/**
* See ISO 16022:2006, 5.2.3 and Annex C, Table C.2
*/},{key:"decodeAsciiSegment",value:function decodeAsciiSegment(bits,result,resultTrailer){var upperShift=false;do{var oneByte=bits.readBits(8);if(oneByte===0){throw new FormatException();}else if(oneByte<=128){// ASCII data (ASCII value + 1)
if(upperShift){oneByte+=128;// upperShift = false;
}result.append(String.fromCharCode(oneByte-1));return Mode.ASCII_ENCODE;}else if(oneByte===129){// Pad
return Mode.PAD_ENCODE;}else if(oneByte<=229){// 2-digit data 00-99 (Numeric Value + 130)
var value=oneByte-130;if(value<10){// pad with '0' for single digit values
result.append('0');}result.append(''+value);}else{switch(oneByte){case 230:// Latch to C40 encodation
return Mode.C40_ENCODE;case 231:// Latch to Base 256 encodation
return Mode.BASE256_ENCODE;case 232:// FNC1
result.append(String.fromCharCode(29));// translate as ASCII 29
break;case 233:// Structured Append
case 234:// Reader Programming
// Ignore these symbols for now
// throw ReaderException.getInstance();
break;case 235:// Upper Shift (shift to Extended ASCII)
upperShift=true;break;case 236:// 05 Macro
result.append("[)>\x1E05\x1D");resultTrailer.insert(0,"\x1E\x04");break;case 237:// 06 Macro
result.append("[)>\x1E06\x1D");resultTrailer.insert(0,"\x1E\x04");break;case 238:// Latch to ANSI X12 encodation
return Mode.ANSIX12_ENCODE;case 239:// Latch to Text encodation
return Mode.TEXT_ENCODE;case 240:// Latch to EDIFACT encodation
return Mode.EDIFACT_ENCODE;case 241:// ECI Character
// TODO(bbrown): I think we need to support ECI
// throw ReaderException.getInstance();
// Ignore this symbol for now
break;default:// Not to be used in ASCII encodation
// but work around encoders that end with 254, latch back to ASCII
if(oneByte!==254||bits.available()!==0){throw new FormatException();}break;}}}while(bits.available()>0);return Mode.ASCII_ENCODE;}/**
* See ISO 16022:2006, 5.2.5 and Annex C, Table C.1
*/},{key:"decodeC40Segment",value:function decodeC40Segment(bits,result){// Three C40 values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1
// TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time
var upperShift=false;var cValues=[];var shift=0;do{// If there is only one byte left then it will be encoded as ASCII
if(bits.available()===8){return;}var firstByte=bits.readBits(8);if(firstByte===254){// Unlatch codeword
return;}this.parseTwoBytes(firstByte,bits.readBits(8),cValues);for(var i=0;i<3;i++){var cValue=cValues[i];switch(shift){case 0:if(cValue<3){shift=cValue+1;}else if(cValue<this.C40_BASIC_SET_CHARS.length){var c40char=this.C40_BASIC_SET_CHARS[cValue];if(upperShift){result.append(String.fromCharCode(c40char.charCodeAt(0)+128));upperShift=false;}else{result.append(c40char);}}else{throw new FormatException();}break;case 1:if(upperShift){result.append(String.fromCharCode(cValue+128));upperShift=false;}else{result.append(String.fromCharCode(cValue));}shift=0;break;case 2:if(cValue<this.C40_SHIFT2_SET_CHARS.length){var _c40char=this.C40_SHIFT2_SET_CHARS[cValue];if(upperShift){result.append(String.fromCharCode(_c40char.charCodeAt(0)+128));upperShift=false;}else{result.append(_c40char);}}else{switch(cValue){case 27:// FNC1
result.append(String.fromCharCode(29));// translate as ASCII 29
break;case 30:// Upper Shift
upperShift=true;break;default:throw new FormatException();}}shift=0;break;case 3:if(upperShift){result.append(String.fromCharCode(cValue+224));upperShift=false;}else{result.append(String.fromCharCode(cValue+96));}shift=0;break;default:throw new FormatException();}}}while(bits.available()>0);}/**
* See ISO 16022:2006, 5.2.6 and Annex C, Table C.2
*/},{key:"decodeTextSegment",value:function decodeTextSegment(bits,result){// Three Text values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1
// TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time
var upperShift=false;var cValues=[];var shift=0;do{// If there is only one byte left then it will be encoded as ASCII
if(bits.available()===8){return;}var firstByte=bits.readBits(8);if(firstByte===254){// Unlatch codeword
return;}this.parseTwoBytes(firstByte,bits.readBits(8),cValues);for(var i=0;i<3;i++){var cValue=cValues[i];switch(shift){case 0:if(cValue<3){shift=cValue+1;}else if(cValue<this.TEXT_BASIC_SET_CHARS.length){var textChar=this.TEXT_BASIC_SET_CHARS[cValue];if(upperShift){result.append(String.fromCharCode(textChar.charCodeAt(0)+128));upperShift=false;}else{result.append(textChar);}}else{throw new FormatException();}break;case 1:if(upperShift){result.append(String.fromCharCode(cValue+128));upperShift=false;}else{result.append(String.fromCharCode(cValue));}shift=0;break;case 2:// Shift 2 for Text is the same encoding as C40
if(cValue<this.TEXT_SHIFT2_SET_CHARS.length){var _textChar=this.TEXT_SHIFT2_SET_CHARS[cValue];if(upperShift){result.append(String.fromCharCode(_textChar.charCodeAt(0)+128));upperShift=false;}else{result.append(_textChar);}}else{switch(cValue){case 27:// FNC1
result.append(String.fromCharCode(29));// translate as ASCII 29
break;case 30:// Upper Shift
upperShift=true;break;default:throw new FormatException();}}shift=0;break;case 3:if(cValue<this.TEXT_SHIFT3_SET_CHARS.length){var _textChar2=this.TEXT_SHIFT3_SET_CHARS[cValue];if(upperShift){result.append(String.fromCharCode(_textChar2.charCodeAt(0)+128));upperShift=false;}else{result.append(_textChar2);}shift=0;}else{throw new FormatException();}break;default:throw new FormatException();}}}while(bits.available()>0);}/**
* See ISO 16022:2006, 5.2.7
*/},{key:"decodeAnsiX12Segment",value:function decodeAnsiX12Segment(bits,result){// Three ANSI X12 values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1
var cValues=[];do{// If there is only one byte left then it will be encoded as ASCII
if(bits.available()===8){return;}var firstByte=bits.readBits(8);if(firstByte===254){// Unlatch codeword
return;}this.parseTwoBytes(firstByte,bits.readBits(8),cValues);for(var i=0;i<3;i++){var cValue=cValues[i];switch(cValue){case 0:// X12 segment terminator <CR>
result.append('\r');break;case 1:// X12 segment separator *
result.append('*');break;case 2:// X12 sub-element separator >
result.append('>');break;case 3:// space
result.append(' ');break;default:if(cValue<14){// 0 - 9
result.append(String.fromCharCode(cValue+44));}else if(cValue<40){// A - Z
result.append(String.fromCharCode(cValue+51));}else{throw new FormatException();}break;}}}while(bits.available()>0);}},{key:"parseTwoBytes",value:function parseTwoBytes(firstByte,secondByte,result){var fullBitValue=(firstByte<<8)+secondByte-1;var temp=Math.floor(fullBitValue/1600);result[0]=temp;fullBitValue-=temp*1600;temp=Math.floor(fullBitValue/40);result[1]=temp;result[2]=fullBitValue-temp*40;}/**
* See ISO 16022:2006, 5.2.8 and Annex C Table C.3
*/},{key:"decodeEdifactSegment",value:function decodeEdifactSegment(bits,result){do{// If there is only two or less bytes left then it will be encoded as ASCII
if(bits.available()<=16){return;}for(var i=0;i<4;i++){var edifactValue=bits.readBits(6);// Check for the unlatch character
if(edifactValue===0x1F){// 011111
// Read rest of byte, which should be 0, and stop
var bitsLeft=8-bits.getBitOffset();if(bitsLeft!==8){bits.readBits(bitsLeft);}return;}if((edifactValue&0x20)===0){// no 1 in the leading (6th) bit
edifactValue|=0x40;// Add a leading 01 to the 6 bit binary value
}result.append(String.fromCharCode(edifactValue));}}while(bits.available()>0);}/**
* See ISO 16022:2006, 5.2.9 and Annex B, B.2
*/},{key:"decodeBase256Segment",value:function decodeBase256Segment(bits,result,byteSegments){// Figure out how long the Base 256 Segment is.
var codewordPosition=1+bits.getByteOffset();// position is 1-indexed
var d1=this.unrandomize255State(bits.readBits(8),codewordPosition++);var count;if(d1===0){// Read the remainder of the symbol
count=bits.available()/8|0;}else if(d1<250){count=d1;}else{count=250*(d1-249)+this.unrandomize255State(bits.readBits(8),codewordPosition++);}// We're seeing NegativeArraySizeException errors from users.
if(count<0){throw new FormatException();}var bytes=new Uint8Array(count);for(var i=0;i<count;i++){// Have seen this particular error in the wild, such as at
// http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2
if(bits.available()<8){throw new FormatException();}bytes[i]=this.unrandomize255State(bits.readBits(8),codewordPosition++);}byteSegments.push(bytes);try{result.append(StringEncoding.decode(bytes,StringUtils.ISO88591));}catch(uee){throw new IllegalStateException('Platform does not support required encoding: '+uee.message);}}/**
* See ISO 16022:2006, Annex B, B.2
*/},{key:"unrandomize255State",value:function unrandomize255State(randomizedBase256Codeword,base256CodewordPosition){var pseudoRandomNumber=149*base256CodewordPosition%255+1;var tempVariable=randomizedBase256Codeword-pseudoRandomNumber;return tempVariable>=0?tempVariable:tempVariable+256;}}]);return DecodedBitStreamParser;}();/**
* See ISO 16022:2006, Annex C Table C.1
* The C40 Basic Character Set (*'s used for placeholders for the shift values)
*/DecodedBitStreamParser.C40_BASIC_SET_CHARS=['*','*','*',' ','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];DecodedBitStreamParser.C40_SHIFT2_SET_CHARS=['!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/',':',';','<','=','>','?','@','[','\\',']','^','_'];/**
* See ISO 16022:2006, Annex C Table C.2
* The Text Basic Character Set (*'s used for placeholders for the shift values)
*/DecodedBitStreamParser.TEXT_BASIC_SET_CHARS=['*','*','*',' ','0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];// Shift 2 for Text is the same encoding as C40
DecodedBitStreamParser.TEXT_SHIFT2_SET_CHARS=DecodedBitStreamParser.C40_SHIFT2_SET_CHARS;DecodedBitStreamParser.TEXT_SHIFT3_SET_CHARS=['`','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','{','|','}','~',String.fromCharCode(127)];/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>The main class which implements Data Matrix Code decoding -- as opposed to locating and extracting
* the Data Matrix Code from an image.</p>
*
* @author bbrown@google.com (Brian Brown)
*/var Decoder$1=/*#__PURE__*/function(){function Decoder$1(){_classCallCheck(this,Decoder$1);this.rsDecoder=new ReedSolomonDecoder(GenericGF.DATA_MATRIX_FIELD_256);}/**
* <p>Decodes a Data Matrix Code represented as a {@link BitMatrix}. A 1 or "true" is taken
* to mean a black module.</p>
*
* @param bits booleans representing white/black Data Matrix Code modules
* @return text and bytes encoded within the Data Matrix Code
* @throws FormatException if the Data Matrix Code cannot be decoded
* @throws ChecksumException if error correction fails
*/_createClass(Decoder$1,[{key:"decode",value:function decode(bits){// Construct a parser and read version, error-correction level
var parser=new BitMatrixParser(bits);var version=parser.getVersion();// Read codewords
var codewords=parser.readCodewords();// Separate into data blocks
var dataBlocks=DataBlock.getDataBlocks(codewords,version);// Count total number of data bytes
var totalBytes=0;var _iterator37=_createForOfIteratorHelper(dataBlocks),_step37;try{for(_iterator37.s();!(_step37=_iterator37.n()).done;){var db=_step37.value;totalBytes+=db.getNumDataCodewords();}}catch(err){_iterator37.e(err);}finally{_iterator37.f();}var resultBytes=new Uint8Array(totalBytes);var dataBlocksCount=dataBlocks.length;// Error-correct and copy data blocks together into a stream of bytes
for(var j=0;j<dataBlocksCount;j++){var dataBlock=dataBlocks[j];var codewordBytes=dataBlock.getCodewords();var numDataCodewords=dataBlock.getNumDataCodewords();this.correctErrors(codewordBytes,numDataCodewords);for(var i=0;i<numDataCodewords;i++){// De-interlace data blocks.
resultBytes[i*dataBlocksCount+j]=codewordBytes[i];}}// Decode the contents of that stream of bytes
return DecodedBitStreamParser.decode(resultBytes);}/**
* <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
* correct the errors in-place using Reed-Solomon error correction.</p>
*
* @param codewordBytes data and error correction codewords
* @param numDataCodewords number of codewords that are data bytes
* @throws ChecksumException if error correction fails
*/},{key:"correctErrors",value:function correctErrors(codewordBytes,numDataCodewords){// const numCodewords = codewordBytes.length;
// First read into an array of ints
var codewordsInts=new Int32Array(codewordBytes);// for (let i = 0; i < numCodewords; i++) {
// codewordsInts[i] = codewordBytes[i] & 0xFF;
// }
try{this.rsDecoder.decode(codewordsInts,codewordBytes.length-numDataCodewords);}catch(ignored/* ReedSolomonException */){throw new ChecksumException();}// Copy back into array of bytes -- only need to worry about the bytes that were data
// We don't care about errors in the error-correction codewords
for(var i=0;i<numDataCodewords;i++){codewordBytes[i]=codewordsInts[i];}}}]);return Decoder$1;}();/**
* <p>Encapsulates logic that can detect a Data Matrix Code in an image, even if the Data Matrix Code
* is rotated or skewed, or partially obscured.</p>
*
* @author Sean Owen
*/var Detector$1=/*#__PURE__*/function(){function Detector$1(image){_classCallCheck(this,Detector$1);this.image=image;this.rectangleDetector=new WhiteRectangleDetector(this.image);}/**
* <p>Detects a Data Matrix Code in an image.</p>
*
* @return {@link DetectorResult} encapsulating results of detecting a Data Matrix Code
* @throws NotFoundException if no Data Matrix Code can be found
*/_createClass(Detector$1,[{key:"detect",value:function detect(){var cornerPoints=this.rectangleDetector.detect();var points=this.detectSolid1(cornerPoints);points=this.detectSolid2(points);points[3]=this.correctTopRight(points);if(!points[3]){throw new NotFoundException();}points=this.shiftToModuleCenter(points);var topLeft=points[0];var bottomLeft=points[1];var bottomRight=points[2];var topRight=points[3];var dimensionTop=this.transitionsBetween(topLeft,topRight)+1;var dimensionRight=this.transitionsBetween(bottomRight,topRight)+1;if((dimensionTop&0x01)===1){dimensionTop+=1;}if((dimensionRight&0x01)===1){dimensionRight+=1;}if(4*dimensionTop<7*dimensionRight&&4*dimensionRight<7*dimensionTop){// The matrix is square
dimensionTop=dimensionRight=Math.max(dimensionTop,dimensionRight);}var bits=Detector$1.sampleGrid(this.image,topLeft,bottomLeft,bottomRight,topRight,dimensionTop,dimensionRight);return new DetectorResult(bits,[topLeft,bottomLeft,bottomRight,topRight]);}},{key:"detectSolid1",value:/**
* Detect a solid side which has minimum transition.
*/function detectSolid1(cornerPoints){// 0 2
// 1 3
var pointA=cornerPoints[0];var pointB=cornerPoints[1];var pointC=cornerPoints[3];var pointD=cornerPoints[2];var trAB=this.transitionsBetween(pointA,pointB);var trBC=this.transitionsBetween(pointB,pointC);var trCD=this.transitionsBetween(pointC,pointD);var trDA=this.transitionsBetween(pointD,pointA);// 0..3
// : :
// 1--2
var min=trAB;var points=[pointD,pointA,pointB,pointC];if(min>trBC){min=trBC;points[0]=pointA;points[1]=pointB;points[2]=pointC;points[3]=pointD;}if(min>trCD){min=trCD;points[0]=pointB;points[1]=pointC;points[2]=pointD;points[3]=pointA;}if(min>trDA){points[0]=pointC;points[1]=pointD;points[2]=pointA;points[3]=pointB;}return points;}/**
* Detect a second solid side next to first solid side.
*/},{key:"detectSolid2",value:function detectSolid2(points){// A..D
// : :
// B--C
var pointA=points[0];var pointB=points[1];var pointC=points[2];var pointD=points[3];// Transition detection on the edge is not stable.
// To safely detect, shift the points to the module center.
var tr=this.transitionsBetween(pointA,pointD);var pointBs=Detector$1.shiftPoint(pointB,pointC,(tr+1)*4);var pointCs=Detector$1.shiftPoint(pointC,pointB,(tr+1)*4);var trBA=this.transitionsBetween(pointBs,pointA);var trCD=this.transitionsBetween(pointCs,pointD);// 0..3
// | :
// 1--2
if(trBA<trCD){// solid sides: A-B-C
points[0]=pointA;points[1]=pointB;points[2]=pointC;points[3]=pointD;}else{// solid sides: B-C-D
points[0]=pointB;points[1]=pointC;points[2]=pointD;points[3]=pointA;}return points;}/**
* Calculates the corner position of the white top right module.
*/},{key:"correctTopRight",value:function correctTopRight(points){// A..D
// | :
// B--C
var pointA=points[0];var pointB=points[1];var pointC=points[2];var pointD=points[3];// shift points for safe transition detection.
var trTop=this.transitionsBetween(pointA,pointD);var trRight=this.transitionsBetween(pointB,pointD);var pointAs=Detector$1.shiftPoint(pointA,pointB,(trRight+1)*4);var pointCs=Detector$1.shiftPoint(pointC,pointB,(trTop+1)*4);trTop=this.transitionsBetween(pointAs,pointD);trRight=this.transitionsBetween(pointCs,pointD);var candidate1=new ResultPoint(pointD.getX()+(pointC.getX()-pointB.getX())/(trTop+1),pointD.getY()+(pointC.getY()-pointB.getY())/(trTop+1));var candidate2=new ResultPoint(pointD.getX()+(pointA.getX()-pointB.getX())/(trRight+1),pointD.getY()+(pointA.getY()-pointB.getY())/(trRight+1));if(!this.isValid(candidate1)){if(this.isValid(candidate2)){return candidate2;}return null;}if(!this.isValid(candidate2)){return candidate1;}var sumc1=this.transitionsBetween(pointAs,candidate1)+this.transitionsBetween(pointCs,candidate1);var sumc2=this.transitionsBetween(pointAs,candidate2)+this.transitionsBetween(pointCs,candidate2);if(sumc1>sumc2){return candidate1;}else{return candidate2;}}/**
* Shift the edge points to the module center.
*/},{key:"shiftToModuleCenter",value:function shiftToModuleCenter(points){// A..D
// | :
// B--C
var pointA=points[0];var pointB=points[1];var pointC=points[2];var pointD=points[3];// calculate pseudo dimensions
var dimH=this.transitionsBetween(pointA,pointD)+1;var dimV=this.transitionsBetween(pointC,pointD)+1;// shift points for safe dimension detection
var pointAs=Detector$1.shiftPoint(pointA,pointB,dimV*4);var pointCs=Detector$1.shiftPoint(pointC,pointB,dimH*4);// calculate more precise dimensions
dimH=this.transitionsBetween(pointAs,pointD)+1;dimV=this.transitionsBetween(pointCs,pointD)+1;if((dimH&0x01)===1){dimH+=1;}if((dimV&0x01)===1){dimV+=1;}// WhiteRectangleDetector returns points inside of the rectangle.
// I want points on the edges.
var centerX=(pointA.getX()+pointB.getX()+pointC.getX()+pointD.getX())/4;var centerY=(pointA.getY()+pointB.getY()+pointC.getY()+pointD.getY())/4;pointA=Detector$1.moveAway(pointA,centerX,centerY);pointB=Detector$1.moveAway(pointB,centerX,centerY);pointC=Detector$1.moveAway(pointC,centerX,centerY);pointD=Detector$1.moveAway(pointD,centerX,centerY);var pointBs;var pointDs;// shift points to the center of each modules
pointAs=Detector$1.shiftPoint(pointA,pointB,dimV*4);pointAs=Detector$1.shiftPoint(pointAs,pointD,dimH*4);pointBs=Detector$1.shiftPoint(pointB,pointA,dimV*4);pointBs=Detector$1.shiftPoint(pointBs,pointC,dimH*4);pointCs=Detector$1.shiftPoint(pointC,pointD,dimV*4);pointCs=Detector$1.shiftPoint(pointCs,pointB,dimH*4);pointDs=Detector$1.shiftPoint(pointD,pointC,dimV*4);pointDs=Detector$1.shiftPoint(pointDs,pointA,dimH*4);return[pointAs,pointBs,pointCs,pointDs];}},{key:"isValid",value:function isValid(p){return p.getX()>=0&&p.getX()<this.image.getWidth()&&p.getY()>0&&p.getY()<this.image.getHeight();}},{key:"transitionsBetween",value:/**
* Counts the number of black/white transitions between two points, using something like Bresenham's algorithm.
*/function transitionsBetween(from,to){// See QR Code Detector, sizeOfBlackWhiteBlackRun()
var fromX=Math.trunc(from.getX());var fromY=Math.trunc(from.getY());var toX=Math.trunc(to.getX());var toY=Math.trunc(to.getY());var steep=Math.abs(toY-fromY)>Math.abs(toX-fromX);if(steep){var temp=fromX;fromX=fromY;fromY=temp;temp=toX;toX=toY;toY=temp;}var dx=Math.abs(toX-fromX);var dy=Math.abs(toY-fromY);var error=-dx/2;var ystep=fromY<toY?1:-1;var xstep=fromX<toX?1:-1;var transitions=0;var inBlack=this.image.get(steep?fromY:fromX,steep?fromX:fromY);for(var x=fromX,y=fromY;x!==toX;x+=xstep){var isBlack=this.image.get(steep?y:x,steep?x:y);if(isBlack!==inBlack){transitions++;inBlack=isBlack;}error+=dy;if(error>0){if(y===toY){break;}y+=ystep;error-=dx;}}return transitions;}}],[{key:"shiftPoint",value:function shiftPoint(point,to,div){var x=(to.getX()-point.getX())/(div+1);var y=(to.getY()-point.getY())/(div+1);return new ResultPoint(point.getX()+x,point.getY()+y);}},{key:"moveAway",value:function moveAway(point,fromX,fromY){var x=point.getX();var y=point.getY();if(x<fromX){x-=1;}else{x+=1;}if(y<fromY){y-=1;}else{y+=1;}return new ResultPoint(x,y);}},{key:"sampleGrid",value:function sampleGrid(image,topLeft,bottomLeft,bottomRight,topRight,dimensionX,dimensionY){var sampler=GridSamplerInstance.getInstance();return sampler.sampleGrid(image,dimensionX,dimensionY,0.5,0.5,dimensionX-0.5,0.5,dimensionX-0.5,dimensionY-0.5,0.5,dimensionY-0.5,topLeft.getX(),topLeft.getY(),topRight.getX(),topRight.getY(),bottomRight.getX(),bottomRight.getY(),bottomLeft.getX(),bottomLeft.getY());}}]);return Detector$1;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* This implementation can detect and decode Data Matrix codes in an image.
*
* @author bbrown@google.com (Brian Brown)
*/var DataMatrixReader=/*#__PURE__*/function(){function DataMatrixReader(){_classCallCheck(this,DataMatrixReader);this.decoder=new Decoder$1();}/**
* Locates and decodes a Data Matrix code in an image.
*
* @return a String representing the content encoded by the Data Matrix code
* @throws NotFoundException if a Data Matrix code cannot be found
* @throws FormatException if a Data Matrix code cannot be decoded
* @throws ChecksumException if error correction fails
*/ // @Override
// public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException {
// return decode(image, null);
// }
// @Override
_createClass(DataMatrixReader,[{key:"decode",value:function decode(image){var hints=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var decoderResult;var points;if(hints!=null&&hints.has(DecodeHintType$1.PURE_BARCODE)){var bits=DataMatrixReader.extractPureBits(image.getBlackMatrix());decoderResult=this.decoder.decode(bits);points=DataMatrixReader.NO_POINTS;}else{var detectorResult=new Detector$1(image.getBlackMatrix()).detect();decoderResult=this.decoder.decode(detectorResult.getBits());points=detectorResult.getPoints();}var rawBytes=decoderResult.getRawBytes();var result=new Result(decoderResult.getText(),rawBytes,8*rawBytes.length,points,BarcodeFormat$1.DATA_MATRIX,System.currentTimeMillis());var byteSegments=decoderResult.getByteSegments();if(byteSegments!=null){result.putMetadata(ResultMetadataType$1.BYTE_SEGMENTS,byteSegments);}var ecLevel=decoderResult.getECLevel();if(ecLevel!=null){result.putMetadata(ResultMetadataType$1.ERROR_CORRECTION_LEVEL,ecLevel);}return result;}// @Override
},{key:"reset",value:function reset(){// do nothing
}/**
* This method detects a code in a "pure" image -- that is, pure monochrome image
* which contains only an unrotated, unskewed, image of a code, with some white border
* around it. This is a specialized method that works exceptionally fast in this special
* case.
*
* @see com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix)
*/}],[{key:"extractPureBits",value:function extractPureBits(image){var leftTopBlack=image.getTopLeftOnBit();var rightBottomBlack=image.getBottomRightOnBit();if(leftTopBlack==null||rightBottomBlack==null){throw new NotFoundException();}var moduleSize=this.moduleSize(leftTopBlack,image);var top=leftTopBlack[1];var bottom=rightBottomBlack[1];var left=leftTopBlack[0];var right=rightBottomBlack[0];var matrixWidth=(right-left+1)/moduleSize;var matrixHeight=(bottom-top+1)/moduleSize;if(matrixWidth<=0||matrixHeight<=0){throw new NotFoundException();}// Push in the "border" by half the module width so that we start
// sampling in the middle of the module. Just in case the image is a
// little off, this will help recover.
var nudge=moduleSize/2;top+=nudge;left+=nudge;// Now just read off the bits
var bits=new BitMatrix(matrixWidth,matrixHeight);for(var y=0;y<matrixHeight;y++){var iOffset=top+y*moduleSize;for(var x=0;x<matrixWidth;x++){if(image.get(left+x*moduleSize,iOffset)){bits.set(x,y);}}}return bits;}},{key:"moduleSize",value:function moduleSize(leftTopBlack,image){var width=image.getWidth();var x=leftTopBlack[0];var y=leftTopBlack[1];while(x<width&&image.get(x,y)){x++;}if(x===width){throw new NotFoundException();}var moduleSize=x-leftTopBlack[0];if(moduleSize===0){throw new NotFoundException();}return moduleSize;}}]);return DataMatrixReader;}();DataMatrixReader.NO_POINTS=[];/**
* @deprecated Moving to @zxing/browser
*
* QR Code reader to use from browser.
*/var BrowserDatamatrixCodeReader=/*#__PURE__*/function(_BrowserCodeReader3){_inherits(BrowserDatamatrixCodeReader,_BrowserCodeReader3);var _super51=_createSuper(BrowserDatamatrixCodeReader);/**
* Creates an instance of BrowserQRCodeReader.
* @param {number} [timeBetweenScansMillis=500] the time delay between subsequent decode tries
*/function BrowserDatamatrixCodeReader(){var timeBetweenScansMillis=arguments.length>0&&arguments[0]!==undefined?arguments[0]:500;_classCallCheck(this,BrowserDatamatrixCodeReader);return _super51.call(this,new DataMatrixReader(),timeBetweenScansMillis);}return _createClass(BrowserDatamatrixCodeReader);}(BrowserCodeReader);/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/var ErrorCorrectionLevelValues;(function(ErrorCorrectionLevelValues){ErrorCorrectionLevelValues[ErrorCorrectionLevelValues["L"]=0]="L";ErrorCorrectionLevelValues[ErrorCorrectionLevelValues["M"]=1]="M";ErrorCorrectionLevelValues[ErrorCorrectionLevelValues["Q"]=2]="Q";ErrorCorrectionLevelValues[ErrorCorrectionLevelValues["H"]=3]="H";})(ErrorCorrectionLevelValues||(ErrorCorrectionLevelValues={}));/**
* <p>See ISO 18004:2006, 6.5.1. This enum encapsulates the four error correction levels
* defined by the QR code standard.</p>
*
* @author Sean Owen
*/var ErrorCorrectionLevel=/*#__PURE__*/function(){function ErrorCorrectionLevel(value,stringValue,bits/*int*/){_classCallCheck(this,ErrorCorrectionLevel);this.value=value;this.stringValue=stringValue;this.bits=bits;ErrorCorrectionLevel.FOR_BITS.set(bits,this);ErrorCorrectionLevel.FOR_VALUE.set(value,this);}_createClass(ErrorCorrectionLevel,[{key:"getValue",value:function getValue(){return this.value;}},{key:"getBits",value:function getBits(){return this.bits;}},{key:"toString",value:function toString(){return this.stringValue;}},{key:"equals",value:function equals(o){if(!(o instanceof ErrorCorrectionLevel)){return false;}var other=o;return this.value===other.value;}/**
* @param bits int containing the two bits encoding a QR Code's error correction level
* @return ErrorCorrectionLevel representing the encoded error correction level
*/}],[{key:"fromString",value:function fromString(s){switch(s){case'L':return ErrorCorrectionLevel.L;case'M':return ErrorCorrectionLevel.M;case'Q':return ErrorCorrectionLevel.Q;case'H':return ErrorCorrectionLevel.H;default:throw new ArgumentException(s+'not available');}}},{key:"forBits",value:function forBits(bits/*int*/){if(bits<0||bits>=ErrorCorrectionLevel.FOR_BITS.size){throw new IllegalArgumentException();}return ErrorCorrectionLevel.FOR_BITS.get(bits);}}]);return ErrorCorrectionLevel;}();ErrorCorrectionLevel.FOR_BITS=new Map();ErrorCorrectionLevel.FOR_VALUE=new Map();/** L = ~7% correction */ErrorCorrectionLevel.L=new ErrorCorrectionLevel(ErrorCorrectionLevelValues.L,'L',0x01);/** M = ~15% correction */ErrorCorrectionLevel.M=new ErrorCorrectionLevel(ErrorCorrectionLevelValues.M,'M',0x00);/** Q = ~25% correction */ErrorCorrectionLevel.Q=new ErrorCorrectionLevel(ErrorCorrectionLevelValues.Q,'Q',0x03);/** H = ~30% correction */ErrorCorrectionLevel.H=new ErrorCorrectionLevel(ErrorCorrectionLevelValues.H,'H',0x02);/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Encapsulates a QR Code's format information, including the data mask used and
* error correction level.</p>
*
* @author Sean Owen
* @see DataMask
* @see ErrorCorrectionLevel
*/var FormatInformation=/*#__PURE__*/function(){function FormatInformation(formatInfo/*int*/){_classCallCheck(this,FormatInformation);// Bits 3,4
this.errorCorrectionLevel=ErrorCorrectionLevel.forBits(formatInfo>>3&0x03);// Bottom 3 bits
this.dataMask=/*(byte) */formatInfo&0x07;}_createClass(FormatInformation,[{key:"getErrorCorrectionLevel",value:function getErrorCorrectionLevel(){return this.errorCorrectionLevel;}},{key:"getDataMask",value:function getDataMask(){return this.dataMask;}/*@Override*/},{key:"hashCode",value:function hashCode(){return this.errorCorrectionLevel.getBits()<<3|this.dataMask;}/*@Override*/},{key:"equals",value:function equals(o){if(!(o instanceof FormatInformation)){return false;}var other=o;return this.errorCorrectionLevel===other.errorCorrectionLevel&&this.dataMask===other.dataMask;}}],[{key:"numBitsDiffering",value:function numBitsDiffering(a/*int*/,b/*int*/){return Integer.bitCount(a^b);}/**
* @param maskedFormatInfo1 format info indicator, with mask still applied
* @param maskedFormatInfo2 second copy of same info; both are checked at the same time
* to establish best match
* @return information about the format it specifies, or {@code null}
* if doesn't seem to match any known pattern
*/},{key:"decodeFormatInformation",value:function decodeFormatInformation(maskedFormatInfo1/*int*/,maskedFormatInfo2/*int*/){var formatInfo=FormatInformation.doDecodeFormatInformation(maskedFormatInfo1,maskedFormatInfo2);if(formatInfo!==null){return formatInfo;}// Should return null, but, some QR codes apparently
// do not mask this info. Try again by actually masking the pattern
// first
return FormatInformation.doDecodeFormatInformation(maskedFormatInfo1^FormatInformation.FORMAT_INFO_MASK_QR,maskedFormatInfo2^FormatInformation.FORMAT_INFO_MASK_QR);}},{key:"doDecodeFormatInformation",value:function doDecodeFormatInformation(maskedFormatInfo1/*int*/,maskedFormatInfo2/*int*/){// Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing
var bestDifference=Number.MAX_SAFE_INTEGER;var bestFormatInfo=0;var _iterator38=_createForOfIteratorHelper(FormatInformation.FORMAT_INFO_DECODE_LOOKUP),_step38;try{for(_iterator38.s();!(_step38=_iterator38.n()).done;){var decodeInfo=_step38.value;var targetInfo=decodeInfo[0];if(targetInfo===maskedFormatInfo1||targetInfo===maskedFormatInfo2){// Found an exact match
return new FormatInformation(decodeInfo[1]);}var bitsDifference=FormatInformation.numBitsDiffering(maskedFormatInfo1,targetInfo);if(bitsDifference<bestDifference){bestFormatInfo=decodeInfo[1];bestDifference=bitsDifference;}if(maskedFormatInfo1!==maskedFormatInfo2){// also try the other option
bitsDifference=FormatInformation.numBitsDiffering(maskedFormatInfo2,targetInfo);if(bitsDifference<bestDifference){bestFormatInfo=decodeInfo[1];bestDifference=bitsDifference;}}}// Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits
// differing means we found a match
}catch(err){_iterator38.e(err);}finally{_iterator38.f();}if(bestDifference<=3){return new FormatInformation(bestFormatInfo);}return null;}}]);return FormatInformation;}();FormatInformation.FORMAT_INFO_MASK_QR=0x5412;/**
* See ISO 18004:2006, Annex C, Table C.1
*/FormatInformation.FORMAT_INFO_DECODE_LOOKUP=[Int32Array.from([0x5412,0x00]),Int32Array.from([0x5125,0x01]),Int32Array.from([0x5E7C,0x02]),Int32Array.from([0x5B4B,0x03]),Int32Array.from([0x45F9,0x04]),Int32Array.from([0x40CE,0x05]),Int32Array.from([0x4F97,0x06]),Int32Array.from([0x4AA0,0x07]),Int32Array.from([0x77C4,0x08]),Int32Array.from([0x72F3,0x09]),Int32Array.from([0x7DAA,0x0A]),Int32Array.from([0x789D,0x0B]),Int32Array.from([0x662F,0x0C]),Int32Array.from([0x6318,0x0D]),Int32Array.from([0x6C41,0x0E]),Int32Array.from([0x6976,0x0F]),Int32Array.from([0x1689,0x10]),Int32Array.from([0x13BE,0x11]),Int32Array.from([0x1CE7,0x12]),Int32Array.from([0x19D0,0x13]),Int32Array.from([0x0762,0x14]),Int32Array.from([0x0255,0x15]),Int32Array.from([0x0D0C,0x16]),Int32Array.from([0x083B,0x17]),Int32Array.from([0x355F,0x18]),Int32Array.from([0x3068,0x19]),Int32Array.from([0x3F31,0x1A]),Int32Array.from([0x3A06,0x1B]),Int32Array.from([0x24B4,0x1C]),Int32Array.from([0x2183,0x1D]),Int32Array.from([0x2EDA,0x1E]),Int32Array.from([0x2BED,0x1F])];/**
* <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will
* use blocks of differing sizes within one version, so, this encapsulates the parameters for
* each set of blocks. It also holds the number of error-correction codewords per block since it
* will be the same across all blocks within one version.</p>
*/var ECBlocks$1=/*#__PURE__*/function(){function ECBlocks$1(ecCodewordsPerBlock/*int*/){_classCallCheck(this,ECBlocks$1);this.ecCodewordsPerBlock=ecCodewordsPerBlock;for(var _len4=arguments.length,ecBlocks=new Array(_len4>1?_len4-1:0),_key4=1;_key4<_len4;_key4++){ecBlocks[_key4-1]=arguments[_key4];}this.ecBlocks=ecBlocks;}_createClass(ECBlocks$1,[{key:"getECCodewordsPerBlock",value:function getECCodewordsPerBlock(){return this.ecCodewordsPerBlock;}},{key:"getNumBlocks",value:function getNumBlocks(){var total=0;var ecBlocks=this.ecBlocks;var _iterator39=_createForOfIteratorHelper(ecBlocks),_step39;try{for(_iterator39.s();!(_step39=_iterator39.n()).done;){var ecBlock=_step39.value;total+=ecBlock.getCount();}}catch(err){_iterator39.e(err);}finally{_iterator39.f();}return total;}},{key:"getTotalECCodewords",value:function getTotalECCodewords(){return this.ecCodewordsPerBlock*this.getNumBlocks();}},{key:"getECBlocks",value:function getECBlocks(){return this.ecBlocks;}}]);return ECBlocks$1;}();/**
* <p>Encapsulates the parameters for one error-correction block in one symbol version.
* This includes the number of data codewords, and the number of times a block with these
* parameters is used consecutively in the QR code version's format.</p>
*/var ECB$1=/*#__PURE__*/function(){function ECB$1(count/*int*/,dataCodewords/*int*/){_classCallCheck(this,ECB$1);this.count=count;this.dataCodewords=dataCodewords;}_createClass(ECB$1,[{key:"getCount",value:function getCount(){return this.count;}},{key:"getDataCodewords",value:function getDataCodewords(){return this.dataCodewords;}}]);return ECB$1;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* See ISO 18004:2006 Annex D
*
* @author Sean Owen
*/var Version$1=/*#__PURE__*/function(){function Version$1(versionNumber/*int*/,alignmentPatternCenters){_classCallCheck(this,Version$1);this.versionNumber=versionNumber;this.alignmentPatternCenters=alignmentPatternCenters;for(var _len5=arguments.length,ecBlocks=new Array(_len5>2?_len5-2:0),_key5=2;_key5<_len5;_key5++){ecBlocks[_key5-2]=arguments[_key5];}this.ecBlocks=ecBlocks;var total=0;var ecCodewords=ecBlocks[0].getECCodewordsPerBlock();var ecbArray=ecBlocks[0].getECBlocks();var _iterator40=_createForOfIteratorHelper(ecbArray),_step40;try{for(_iterator40.s();!(_step40=_iterator40.n()).done;){var ecBlock=_step40.value;total+=ecBlock.getCount()*(ecBlock.getDataCodewords()+ecCodewords);}}catch(err){_iterator40.e(err);}finally{_iterator40.f();}this.totalCodewords=total;}_createClass(Version$1,[{key:"getVersionNumber",value:function getVersionNumber(){return this.versionNumber;}},{key:"getAlignmentPatternCenters",value:function getAlignmentPatternCenters(){return this.alignmentPatternCenters;}},{key:"getTotalCodewords",value:function getTotalCodewords(){return this.totalCodewords;}},{key:"getDimensionForVersion",value:function getDimensionForVersion(){return 17+4*this.versionNumber;}},{key:"getECBlocksForLevel",value:function getECBlocksForLevel(ecLevel){return this.ecBlocks[ecLevel.getValue()];// TYPESCRIPTPORT: original was using ordinal, and using the order of levels as defined in ErrorCorrectionLevel enum (LMQH)
// I will use the direct value from ErrorCorrectionLevelValues enum which in typescript goes to a number
}/**
* <p>Deduces version information purely from QR Code dimensions.</p>
*
* @param dimension dimension in modules
* @return Version for a QR Code of that dimension
* @throws FormatException if dimension is not 1 mod 4
*/},{key:"buildFunctionPattern",value:/**
* See ISO 18004:2006 Annex E
*/function buildFunctionPattern(){var dimension=this.getDimensionForVersion();var bitMatrix=new BitMatrix(dimension);// Top left finder pattern + separator + format
bitMatrix.setRegion(0,0,9,9);// Top right finder pattern + separator + format
bitMatrix.setRegion(dimension-8,0,8,9);// Bottom left finder pattern + separator + format
bitMatrix.setRegion(0,dimension-8,9,8);// Alignment patterns
var max=this.alignmentPatternCenters.length;for(var x=0;x<max;x++){var i=this.alignmentPatternCenters[x]-2;for(var y=0;y<max;y++){if(x===0&&(y===0||y===max-1)||x===max-1&&y===0){// No alignment patterns near the three finder patterns
continue;}bitMatrix.setRegion(this.alignmentPatternCenters[y]-2,i,5,5);}}// Vertical timing pattern
bitMatrix.setRegion(6,9,1,dimension-17);// Horizontal timing pattern
bitMatrix.setRegion(9,6,dimension-17,1);if(this.versionNumber>6){// Version info, top right
bitMatrix.setRegion(dimension-11,0,3,6);// Version info, bottom left
bitMatrix.setRegion(0,dimension-11,6,3);}return bitMatrix;}/*@Override*/},{key:"toString",value:function toString(){return''+this.versionNumber;}}],[{key:"getProvisionalVersionForDimension",value:function getProvisionalVersionForDimension(dimension/*int*/){if(dimension%4!==1){throw new FormatException();}try{return this.getVersionForNumber((dimension-17)/4);}catch(ignored/*: IllegalArgumentException*/){throw new FormatException();}}},{key:"getVersionForNumber",value:function getVersionForNumber(versionNumber/*int*/){if(versionNumber<1||versionNumber>40){throw new IllegalArgumentException();}return Version$1.VERSIONS[versionNumber-1];}},{key:"decodeVersionInformation",value:function decodeVersionInformation(versionBits/*int*/){var bestDifference=Number.MAX_SAFE_INTEGER;var bestVersion=0;for(var i=0;i<Version$1.VERSION_DECODE_INFO.length;i++){var targetVersion=Version$1.VERSION_DECODE_INFO[i];// Do the version info bits match exactly? done.
if(targetVersion===versionBits){return Version$1.getVersionForNumber(i+7);}// Otherwise see if this is the closest to a real version info bit string
// we have seen so far
var bitsDifference=FormatInformation.numBitsDiffering(versionBits,targetVersion);if(bitsDifference<bestDifference){bestVersion=i+7;bestDifference=bitsDifference;}}// We can tolerate up to 3 bits of error since no two version info codewords will
// differ in less than 8 bits.
if(bestDifference<=3){return Version$1.getVersionForNumber(bestVersion);}// If we didn't find a close enough match, fail
return null;}}]);return Version$1;}();/**
* See ISO 18004:2006 Annex D.
* Element i represents the raw version bits that specify version i + 7
*/Version$1.VERSION_DECODE_INFO=Int32Array.from([0x07C94,0x085BC,0x09A99,0x0A4D3,0x0BBF6,0x0C762,0x0D847,0x0E60D,0x0F928,0x10B78,0x1145D,0x12A17,0x13532,0x149A6,0x15683,0x168C9,0x177EC,0x18EC4,0x191E1,0x1AFAB,0x1B08E,0x1CC1A,0x1D33F,0x1ED75,0x1F250,0x209D5,0x216F0,0x228BA,0x2379F,0x24B0B,0x2542E,0x26A64,0x27541,0x28C69]);/**
* See ISO 18004:2006 6.5.1 Table 9
*/Version$1.VERSIONS=[new Version$1(1,new Int32Array(0),new ECBlocks$1(7,new ECB$1(1,19)),new ECBlocks$1(10,new ECB$1(1,16)),new ECBlocks$1(13,new ECB$1(1,13)),new ECBlocks$1(17,new ECB$1(1,9))),new Version$1(2,Int32Array.from([6,18]),new ECBlocks$1(10,new ECB$1(1,34)),new ECBlocks$1(16,new ECB$1(1,28)),new ECBlocks$1(22,new ECB$1(1,22)),new ECBlocks$1(28,new ECB$1(1,16))),new Version$1(3,Int32Array.from([6,22]),new ECBlocks$1(15,new ECB$1(1,55)),new ECBlocks$1(26,new ECB$1(1,44)),new ECBlocks$1(18,new ECB$1(2,17)),new ECBlocks$1(22,new ECB$1(2,13))),new Version$1(4,Int32Array.from([6,26]),new ECBlocks$1(20,new ECB$1(1,80)),new ECBlocks$1(18,new ECB$1(2,32)),new ECBlocks$1(26,new ECB$1(2,24)),new ECBlocks$1(16,new ECB$1(4,9))),new Version$1(5,Int32Array.from([6,30]),new ECBlocks$1(26,new ECB$1(1,108)),new ECBlocks$1(24,new ECB$1(2,43)),new ECBlocks$1(18,new ECB$1(2,15),new ECB$1(2,16)),new ECBlocks$1(22,new ECB$1(2,11),new ECB$1(2,12))),new Version$1(6,Int32Array.from([6,34]),new ECBlocks$1(18,new ECB$1(2,68)),new ECBlocks$1(16,new ECB$1(4,27)),new ECBlocks$1(24,new ECB$1(4,19)),new ECBlocks$1(28,new ECB$1(4,15))),new Version$1(7,Int32Array.from([6,22,38]),new ECBlocks$1(20,new ECB$1(2,78)),new ECBlocks$1(18,new ECB$1(4,31)),new ECBlocks$1(18,new ECB$1(2,14),new ECB$1(4,15)),new ECBlocks$1(26,new ECB$1(4,13),new ECB$1(1,14))),new Version$1(8,Int32Array.from([6,24,42]),new ECBlocks$1(24,new ECB$1(2,97)),new ECBlocks$1(22,new ECB$1(2,38),new ECB$1(2,39)),new ECBlocks$1(22,new ECB$1(4,18),new ECB$1(2,19)),new ECBlocks$1(26,new ECB$1(4,14),new ECB$1(2,15))),new Version$1(9,Int32Array.from([6,26,46]),new ECBlocks$1(30,new ECB$1(2,116)),new ECBlocks$1(22,new ECB$1(3,36),new ECB$1(2,37)),new ECBlocks$1(20,new ECB$1(4,16),new ECB$1(4,17)),new ECBlocks$1(24,new ECB$1(4,12),new ECB$1(4,13))),new Version$1(10,Int32Array.from([6,28,50]),new ECBlocks$1(18,new ECB$1(2,68),new ECB$1(2,69)),new ECBlocks$1(26,new ECB$1(4,43),new ECB$1(1,44)),new ECBlocks$1(24,new ECB$1(6,19),new ECB$1(2,20)),new ECBlocks$1(28,new ECB$1(6,15),new ECB$1(2,16))),new Version$1(11,Int32Array.from([6,30,54]),new ECBlocks$1(20,new ECB$1(4,81)),new ECBlocks$1(30,new ECB$1(1,50),new ECB$1(4,51)),new ECBlocks$1(28,new ECB$1(4,22),new ECB$1(4,23)),new ECBlocks$1(24,new ECB$1(3,12),new ECB$1(8,13))),new Version$1(12,Int32Array.from([6,32,58]),new ECBlocks$1(24,new ECB$1(2,92),new ECB$1(2,93)),new ECBlocks$1(22,new ECB$1(6,36),new ECB$1(2,37)),new ECBlocks$1(26,new ECB$1(4,20),new ECB$1(6,21)),new ECBlocks$1(28,new ECB$1(7,14),new ECB$1(4,15))),new Version$1(13,Int32Array.from([6,34,62]),new ECBlocks$1(26,new ECB$1(4,107)),new ECBlocks$1(22,new ECB$1(8,37),new ECB$1(1,38)),new ECBlocks$1(24,new ECB$1(8,20),new ECB$1(4,21)),new ECBlocks$1(22,new ECB$1(12,11),new ECB$1(4,12))),new Version$1(14,Int32Array.from([6,26,46,66]),new ECBlocks$1(30,new ECB$1(3,115),new ECB$1(1,116)),new ECBlocks$1(24,new ECB$1(4,40),new ECB$1(5,41)),new ECBlocks$1(20,new ECB$1(11,16),new ECB$1(5,17)),new ECBlocks$1(24,new ECB$1(11,12),new ECB$1(5,13))),new Version$1(15,Int32Array.from([6,26,48,70]),new ECBlocks$1(22,new ECB$1(5,87),new ECB$1(1,88)),new ECBlocks$1(24,new ECB$1(5,41),new ECB$1(5,42)),new ECBlocks$1(30,new ECB$1(5,24),new ECB$1(7,25)),new ECBlocks$1(24,new ECB$1(11,12),new ECB$1(7,13))),new Version$1(16,Int32Array.from([6,26,50,74]),new ECBlocks$1(24,new ECB$1(5,98),new ECB$1(1,99)),new ECBlocks$1(28,new ECB$1(7,45),new ECB$1(3,46)),new ECBlocks$1(24,new ECB$1(15,19),new ECB$1(2,20)),new ECBlocks$1(30,new ECB$1(3,15),new ECB$1(13,16))),new Version$1(17,Int32Array.from([6,30,54,78]),new ECBlocks$1(28,new ECB$1(1,107),new ECB$1(5,108)),new ECBlocks$1(28,new ECB$1(10,46),new ECB$1(1,47)),new ECBlocks$1(28,new ECB$1(1,22),new ECB$1(15,23)),new ECBlocks$1(28,new ECB$1(2,14),new ECB$1(17,15))),new Version$1(18,Int32Array.from([6,30,56,82]),new ECBlocks$1(30,new ECB$1(5,120),new ECB$1(1,121)),new ECBlocks$1(26,new ECB$1(9,43),new ECB$1(4,44)),new ECBlocks$1(28,new ECB$1(17,22),new ECB$1(1,23)),new ECBlocks$1(28,new ECB$1(2,14),new ECB$1(19,15))),new Version$1(19,Int32Array.from([6,30,58,86]),new ECBlocks$1(28,new ECB$1(3,113),new ECB$1(4,114)),new ECBlocks$1(26,new ECB$1(3,44),new ECB$1(11,45)),new ECBlocks$1(26,new ECB$1(17,21),new ECB$1(4,22)),new ECBlocks$1(26,new ECB$1(9,13),new ECB$1(16,14))),new Version$1(20,Int32Array.from([6,34,62,90]),new ECBlocks$1(28,new ECB$1(3,107),new ECB$1(5,108)),new ECBlocks$1(26,new ECB$1(3,41),new ECB$1(13,42)),new ECBlocks$1(30,new ECB$1(15,24),new ECB$1(5,25)),new ECBlocks$1(28,new ECB$1(15,15),new ECB$1(10,16))),new Version$1(21,Int32Array.from([6,28,50,72,94]),new ECBlocks$1(28,new ECB$1(4,116),new ECB$1(4,117)),new ECBlocks$1(26,new ECB$1(17,42)),new ECBlocks$1(28,new ECB$1(17,22),new ECB$1(6,23)),new ECBlocks$1(30,new ECB$1(19,16),new ECB$1(6,17))),new Version$1(22,Int32Array.from([6,26,50,74,98]),new ECBlocks$1(28,new ECB$1(2,111),new ECB$1(7,112)),new ECBlocks$1(28,new ECB$1(17,46)),new ECBlocks$1(30,new ECB$1(7,24),new ECB$1(16,25)),new ECBlocks$1(24,new ECB$1(34,13))),new Version$1(23,Int32Array.from([6,30,54,78,102]),new ECBlocks$1(30,new ECB$1(4,121),new ECB$1(5,122)),new ECBlocks$1(28,new ECB$1(4,47),new ECB$1(14,48)),new ECBlocks$1(30,new ECB$1(11,24),new ECB$1(14,25)),new ECBlocks$1(30,new ECB$1(16,15),new ECB$1(14,16))),new Version$1(24,Int32Array.from([6,28,54,80,106]),new ECBlocks$1(30,new ECB$1(6,117),new ECB$1(4,118)),new ECBlocks$1(28,new ECB$1(6,45),new ECB$1(14,46)),new ECBlocks$1(30,new ECB$1(11,24),new ECB$1(16,25)),new ECBlocks$1(30,new ECB$1(30,16),new ECB$1(2,17))),new Version$1(25,Int32Array.from([6,32,58,84,110]),new ECBlocks$1(26,new ECB$1(8,106),new ECB$1(4,107)),new ECBlocks$1(28,new ECB$1(8,47),new ECB$1(13,48)),new ECBlocks$1(30,new ECB$1(7,24),new ECB$1(22,25)),new ECBlocks$1(30,new ECB$1(22,15),new ECB$1(13,16))),new Version$1(26,Int32Array.from([6,30,58,86,114]),new ECBlocks$1(28,new ECB$1(10,114),new ECB$1(2,115)),new ECBlocks$1(28,new ECB$1(19,46),new ECB$1(4,47)),new ECBlocks$1(28,new ECB$1(28,22),new ECB$1(6,23)),new ECBlocks$1(30,new ECB$1(33,16),new ECB$1(4,17))),new Version$1(27,Int32Array.from([6,34,62,90,118]),new ECBlocks$1(30,new ECB$1(8,122),new ECB$1(4,123)),new ECBlocks$1(28,new ECB$1(22,45),new ECB$1(3,46)),new ECBlocks$1(30,new ECB$1(8,23),new ECB$1(26,24)),new ECBlocks$1(30,new ECB$1(12,15),new ECB$1(28,16))),new Version$1(28,Int32Array.from([6,26,50,74,98,122]),new ECBlocks$1(30,new ECB$1(3,117),new ECB$1(10,118)),new ECBlocks$1(28,new ECB$1(3,45),new ECB$1(23,46)),new ECBlocks$1(30,new ECB$1(4,24),new ECB$1(31,25)),new ECBlocks$1(30,new ECB$1(11,15),new ECB$1(31,16))),new Version$1(29,Int32Array.from([6,30,54,78,102,126]),new ECBlocks$1(30,new ECB$1(7,116),new ECB$1(7,117)),new ECBlocks$1(28,new ECB$1(21,45),new ECB$1(7,46)),new ECBlocks$1(30,new ECB$1(1,23),new ECB$1(37,24)),new ECBlocks$1(30,new ECB$1(19,15),new ECB$1(26,16))),new Version$1(30,Int32Array.from([6,26,52,78,104,130]),new ECBlocks$1(30,new ECB$1(5,115),new ECB$1(10,116)),new ECBlocks$1(28,new ECB$1(19,47),new ECB$1(10,48)),new ECBlocks$1(30,new ECB$1(15,24),new ECB$1(25,25)),new ECBlocks$1(30,new ECB$1(23,15),new ECB$1(25,16))),new Version$1(31,Int32Array.from([6,30,56,82,108,134]),new ECBlocks$1(30,new ECB$1(13,115),new ECB$1(3,116)),new ECBlocks$1(28,new ECB$1(2,46),new ECB$1(29,47)),new ECBlocks$1(30,new ECB$1(42,24),new ECB$1(1,25)),new ECBlocks$1(30,new ECB$1(23,15),new ECB$1(28,16))),new Version$1(32,Int32Array.from([6,34,60,86,112,138]),new ECBlocks$1(30,new ECB$1(17,115)),new ECBlocks$1(28,new ECB$1(10,46),new ECB$1(23,47)),new ECBlocks$1(30,new ECB$1(10,24),new ECB$1(35,25)),new ECBlocks$1(30,new ECB$1(19,15),new ECB$1(35,16))),new Version$1(33,Int32Array.from([6,30,58,86,114,142]),new ECBlocks$1(30,new ECB$1(17,115),new ECB$1(1,116)),new ECBlocks$1(28,new ECB$1(14,46),new ECB$1(21,47)),new ECBlocks$1(30,new ECB$1(29,24),new ECB$1(19,25)),new ECBlocks$1(30,new ECB$1(11,15),new ECB$1(46,16))),new Version$1(34,Int32Array.from([6,34,62,90,118,146]),new ECBlocks$1(30,new ECB$1(13,115),new ECB$1(6,116)),new ECBlocks$1(28,new ECB$1(14,46),new ECB$1(23,47)),new ECBlocks$1(30,new ECB$1(44,24),new ECB$1(7,25)),new ECBlocks$1(30,new ECB$1(59,16),new ECB$1(1,17))),new Version$1(35,Int32Array.from([6,30,54,78,102,126,150]),new ECBlocks$1(30,new ECB$1(12,121),new ECB$1(7,122)),new ECBlocks$1(28,new ECB$1(12,47),new ECB$1(26,48)),new ECBlocks$1(30,new ECB$1(39,24),new ECB$1(14,25)),new ECBlocks$1(30,new ECB$1(22,15),new ECB$1(41,16))),new Version$1(36,Int32Array.from([6,24,50,76,102,128,154]),new ECBlocks$1(30,new ECB$1(6,121),new ECB$1(14,122)),new ECBlocks$1(28,new ECB$1(6,47),new ECB$1(34,48)),new ECBlocks$1(30,new ECB$1(46,24),new ECB$1(10,25)),new ECBlocks$1(30,new ECB$1(2,15),new ECB$1(64,16))),new Version$1(37,Int32Array.from([6,28,54,80,106,132,158]),new ECBlocks$1(30,new ECB$1(17,122),new ECB$1(4,123)),new ECBlocks$1(28,new ECB$1(29,46),new ECB$1(14,47)),new ECBlocks$1(30,new ECB$1(49,24),new ECB$1(10,25)),new ECBlocks$1(30,new ECB$1(24,15),new ECB$1(46,16))),new Version$1(38,Int32Array.from([6,32,58,84,110,136,162]),new ECBlocks$1(30,new ECB$1(4,122),new ECB$1(18,123)),new ECBlocks$1(28,new ECB$1(13,46),new ECB$1(32,47)),new ECBlocks$1(30,new ECB$1(48,24),new ECB$1(14,25)),new ECBlocks$1(30,new ECB$1(42,15),new ECB$1(32,16))),new Version$1(39,Int32Array.from([6,26,54,82,110,138,166]),new ECBlocks$1(30,new ECB$1(20,117),new ECB$1(4,118)),new ECBlocks$1(28,new ECB$1(40,47),new ECB$1(7,48)),new ECBlocks$1(30,new ECB$1(43,24),new ECB$1(22,25)),new ECBlocks$1(30,new ECB$1(10,15),new ECB$1(67,16))),new Version$1(40,Int32Array.from([6,30,58,86,114,142,170]),new ECBlocks$1(30,new ECB$1(19,118),new ECB$1(6,119)),new ECBlocks$1(28,new ECB$1(18,47),new ECB$1(31,48)),new ECBlocks$1(30,new ECB$1(34,24),new ECB$1(34,25)),new ECBlocks$1(30,new ECB$1(20,15),new ECB$1(61,16)))];/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/var DataMaskValues;(function(DataMaskValues){DataMaskValues[DataMaskValues["DATA_MASK_000"]=0]="DATA_MASK_000";DataMaskValues[DataMaskValues["DATA_MASK_001"]=1]="DATA_MASK_001";DataMaskValues[DataMaskValues["DATA_MASK_010"]=2]="DATA_MASK_010";DataMaskValues[DataMaskValues["DATA_MASK_011"]=3]="DATA_MASK_011";DataMaskValues[DataMaskValues["DATA_MASK_100"]=4]="DATA_MASK_100";DataMaskValues[DataMaskValues["DATA_MASK_101"]=5]="DATA_MASK_101";DataMaskValues[DataMaskValues["DATA_MASK_110"]=6]="DATA_MASK_110";DataMaskValues[DataMaskValues["DATA_MASK_111"]=7]="DATA_MASK_111";})(DataMaskValues||(DataMaskValues={}));/**
* <p>Encapsulates data masks for the data bits in a QR code, per ISO 18004:2006 6.8. Implementations
* of this class can un-mask a raw BitMatrix. For simplicity, they will unmask the entire BitMatrix,
* including areas used for finder patterns, timing patterns, etc. These areas should be unused
* after the point they are unmasked anyway.</p>
*
* <p>Note that the diagram in section 6.8.1 is misleading since it indicates that i is column position
* and j is row position. In fact, as the text says, i is row position and j is column position.</p>
*
* @author Sean Owen
*/var DataMask=/*#__PURE__*/function(){// See ISO 18004:2006 6.8.1
function DataMask(value,isMasked){_classCallCheck(this,DataMask);this.value=value;this.isMasked=isMasked;}// End of enum constants.
/**
* <p>Implementations of this method reverse the data masking process applied to a QR Code and
* make its bits ready to read.</p>
*
* @param bits representation of QR Code bits
* @param dimension dimension of QR Code, represented by bits, being unmasked
*/_createClass(DataMask,[{key:"unmaskBitMatrix",value:function unmaskBitMatrix(bits,dimension/*int*/){for(var i=0;i<dimension;i++){for(var j=0;j<dimension;j++){if(this.isMasked(i,j)){bits.flip(j,i);}}}}}]);return DataMask;}();DataMask.values=new Map([/**
* 000: mask bits for which (x + y) mod 2 == 0
*/[DataMaskValues.DATA_MASK_000,new DataMask(DataMaskValues.DATA_MASK_000,function(i/*int*/,j/*int*/){return(i+j&0x01)===0;})],/**
* 001: mask bits for which x mod 2 == 0
*/[DataMaskValues.DATA_MASK_001,new DataMask(DataMaskValues.DATA_MASK_001,function(i/*int*/,j/*int*/){return(i&0x01)===0;})],/**
* 010: mask bits for which y mod 3 == 0
*/[DataMaskValues.DATA_MASK_010,new DataMask(DataMaskValues.DATA_MASK_010,function(i/*int*/,j/*int*/){return j%3===0;})],/**
* 011: mask bits for which (x + y) mod 3 == 0
*/[DataMaskValues.DATA_MASK_011,new DataMask(DataMaskValues.DATA_MASK_011,function(i/*int*/,j/*int*/){return(i+j)%3===0;})],/**
* 100: mask bits for which (x/2 + y/3) mod 2 == 0
*/[DataMaskValues.DATA_MASK_100,new DataMask(DataMaskValues.DATA_MASK_100,function(i/*int*/,j/*int*/){return(Math.floor(i/2)+Math.floor(j/3)&0x01)===0;})],/**
* 101: mask bits for which xy mod 2 + xy mod 3 == 0
* equivalently, such that xy mod 6 == 0
*/[DataMaskValues.DATA_MASK_101,new DataMask(DataMaskValues.DATA_MASK_101,function(i/*int*/,j/*int*/){return i*j%6===0;})],/**
* 110: mask bits for which (xy mod 2 + xy mod 3) mod 2 == 0
* equivalently, such that xy mod 6 < 3
*/[DataMaskValues.DATA_MASK_110,new DataMask(DataMaskValues.DATA_MASK_110,function(i/*int*/,j/*int*/){return i*j%6<3;})],/**
* 111: mask bits for which ((x+y)mod 2 + xy mod 3) mod 2 == 0
* equivalently, such that (x + y + xy mod 3) mod 2 == 0
*/[DataMaskValues.DATA_MASK_111,new DataMask(DataMaskValues.DATA_MASK_111,function(i/*int*/,j/*int*/){return(i+j+i*j%3&0x01)===0;})]]);/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* @author Sean Owen
*/var BitMatrixParser$1=/*#__PURE__*/function(){/**
* @param bitMatrix {@link BitMatrix} to parse
* @throws FormatException if dimension is not >= 21 and 1 mod 4
*/function BitMatrixParser$1(bitMatrix){_classCallCheck(this,BitMatrixParser$1);var dimension=bitMatrix.getHeight();if(dimension<21||(dimension&0x03)!==1){throw new FormatException();}this.bitMatrix=bitMatrix;}/**
* <p>Reads format information from one of its two locations within the QR Code.</p>
*
* @return {@link FormatInformation} encapsulating the QR Code's format info
* @throws FormatException if both format information locations cannot be parsed as
* the valid encoding of format information
*/_createClass(BitMatrixParser$1,[{key:"readFormatInformation",value:function readFormatInformation(){if(this.parsedFormatInfo!==null&&this.parsedFormatInfo!==undefined){return this.parsedFormatInfo;}// Read top-left format info bits
var formatInfoBits1=0;for(var i=0;i<6;i++){formatInfoBits1=this.copyBit(i,8,formatInfoBits1);}// .. and skip a bit in the timing pattern ...
formatInfoBits1=this.copyBit(7,8,formatInfoBits1);formatInfoBits1=this.copyBit(8,8,formatInfoBits1);formatInfoBits1=this.copyBit(8,7,formatInfoBits1);// .. and skip a bit in the timing pattern ...
for(var j=5;j>=0;j--){formatInfoBits1=this.copyBit(8,j,formatInfoBits1);}// Read the top-right/bottom-left pattern too
var dimension=this.bitMatrix.getHeight();var formatInfoBits2=0;var jMin=dimension-7;for(var _j4=dimension-1;_j4>=jMin;_j4--){formatInfoBits2=this.copyBit(8,_j4,formatInfoBits2);}for(var _i28=dimension-8;_i28<dimension;_i28++){formatInfoBits2=this.copyBit(_i28,8,formatInfoBits2);}this.parsedFormatInfo=FormatInformation.decodeFormatInformation(formatInfoBits1,formatInfoBits2);if(this.parsedFormatInfo!==null){return this.parsedFormatInfo;}throw new FormatException();}/**
* <p>Reads version information from one of its two locations within the QR Code.</p>
*
* @return {@link Version} encapsulating the QR Code's version
* @throws FormatException if both version information locations cannot be parsed as
* the valid encoding of version information
*/},{key:"readVersion",value:function readVersion(){if(this.parsedVersion!==null&&this.parsedVersion!==undefined){return this.parsedVersion;}var dimension=this.bitMatrix.getHeight();var provisionalVersion=Math.floor((dimension-17)/4);if(provisionalVersion<=6){return Version$1.getVersionForNumber(provisionalVersion);}// Read top-right version info: 3 wide by 6 tall
var versionBits=0;var ijMin=dimension-11;for(var j=5;j>=0;j--){for(var i=dimension-9;i>=ijMin;i--){versionBits=this.copyBit(i,j,versionBits);}}var theParsedVersion=Version$1.decodeVersionInformation(versionBits);if(theParsedVersion!==null&&theParsedVersion.getDimensionForVersion()===dimension){this.parsedVersion=theParsedVersion;return theParsedVersion;}// Hmm, failed. Try bottom left: 6 wide by 3 tall
versionBits=0;for(var _i29=5;_i29>=0;_i29--){for(var _j5=dimension-9;_j5>=ijMin;_j5--){versionBits=this.copyBit(_i29,_j5,versionBits);}}theParsedVersion=Version$1.decodeVersionInformation(versionBits);if(theParsedVersion!==null&&theParsedVersion.getDimensionForVersion()===dimension){this.parsedVersion=theParsedVersion;return theParsedVersion;}throw new FormatException();}},{key:"copyBit",value:function copyBit(i/*int*/,j/*int*/,versionBits/*int*/){var bit=this.isMirror?this.bitMatrix.get(j,i):this.bitMatrix.get(i,j);return bit?versionBits<<1|0x1:versionBits<<1;}/**
* <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the
* correct order in order to reconstruct the codewords bytes contained within the
* QR Code.</p>
*
* @return bytes encoded within the QR Code
* @throws FormatException if the exact number of bytes expected is not read
*/},{key:"readCodewords",value:function readCodewords(){var formatInfo=this.readFormatInformation();var version=this.readVersion();// Get the data mask for the format used in this QR Code. This will exclude
// some bits from reading as we wind through the bit matrix.
var dataMask=DataMask.values.get(formatInfo.getDataMask());var dimension=this.bitMatrix.getHeight();dataMask.unmaskBitMatrix(this.bitMatrix,dimension);var functionPattern=version.buildFunctionPattern();var readingUp=true;var result=new Uint8Array(version.getTotalCodewords());var resultOffset=0;var currentByte=0;var bitsRead=0;// Read columns in pairs, from right to left
for(var j=dimension-1;j>0;j-=2){if(j===6){// Skip whole column with vertical alignment pattern
// saves time and makes the other code proceed more cleanly
j--;}// Read alternatingly from bottom to top then top to bottom
for(var count=0;count<dimension;count++){var i=readingUp?dimension-1-count:count;for(var col=0;col<2;col++){// Ignore bits covered by the function pattern
if(!functionPattern.get(j-col,i)){// Read a bit
bitsRead++;currentByte<<=1;if(this.bitMatrix.get(j-col,i)){currentByte|=1;}// If we've made a whole byte, save it off
if(bitsRead===8){result[resultOffset++]=/*(byte) */currentByte;bitsRead=0;currentByte=0;}}}}readingUp=!readingUp;// readingUp ^= true; // readingUp = !readingUp; // switch directions
}if(resultOffset!==version.getTotalCodewords()){throw new FormatException();}return result;}/**
* Revert the mask removal done while reading the code words. The bit matrix should revert to its original state.
*/},{key:"remask",value:function remask(){if(this.parsedFormatInfo===null){return;// We have no format information, and have no data mask
}var dataMask=DataMask.values[this.parsedFormatInfo.getDataMask()];var dimension=this.bitMatrix.getHeight();dataMask.unmaskBitMatrix(this.bitMatrix,dimension);}/**
* Prepare the parser for a mirrored operation.
* This flag has effect only on the {@link #readFormatInformation()} and the
* {@link #readVersion()}. Before proceeding with {@link #readCodewords()} the
* {@link #mirror()} method should be called.
*
* @param mirror Whether to read version and format information mirrored.
*/},{key:"setMirror",value:function setMirror(isMirror){this.parsedVersion=null;this.parsedFormatInfo=null;this.isMirror=isMirror;}/** Mirror the bit matrix in order to attempt a second reading. */},{key:"mirror",value:function mirror(){var bitMatrix=this.bitMatrix;for(var x=0,width=bitMatrix.getWidth();x<width;x++){for(var y=x+1,height=bitMatrix.getHeight();y<height;y++){if(bitMatrix.get(x,y)!==bitMatrix.get(y,x)){bitMatrix.flip(y,x);bitMatrix.flip(x,y);}}}}}]);return BitMatrixParser$1;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Encapsulates a block of data within a QR Code. QR Codes may split their data into
* multiple blocks, each of which is a unit of data and error-correction codewords. Each
* is represented by an instance of this class.</p>
*
* @author Sean Owen
*/var DataBlock$1=/*#__PURE__*/function(){function DataBlock$1(numDataCodewords/*int*/,codewords){_classCallCheck(this,DataBlock$1);this.numDataCodewords=numDataCodewords;this.codewords=codewords;}/**
* <p>When QR Codes use multiple data blocks, they are actually interleaved.
* That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This
* method will separate the data into original blocks.</p>
*
* @param rawCodewords bytes as read directly from the QR Code
* @param version version of the QR Code
* @param ecLevel error-correction level of the QR Code
* @return DataBlocks containing original bytes, "de-interleaved" from representation in the
* QR Code
*/_createClass(DataBlock$1,[{key:"getNumDataCodewords",value:function getNumDataCodewords(){return this.numDataCodewords;}},{key:"getCodewords",value:function getCodewords(){return this.codewords;}}],[{key:"getDataBlocks",value:function getDataBlocks(rawCodewords,version,ecLevel){if(rawCodewords.length!==version.getTotalCodewords()){throw new IllegalArgumentException();}// Figure out the number and size of data blocks used by this version and
// error correction level
var ecBlocks=version.getECBlocksForLevel(ecLevel);// First count the total number of data blocks
var totalBlocks=0;var ecBlockArray=ecBlocks.getECBlocks();var _iterator41=_createForOfIteratorHelper(ecBlockArray),_step41;try{for(_iterator41.s();!(_step41=_iterator41.n()).done;){var ecBlock=_step41.value;totalBlocks+=ecBlock.getCount();}// Now establish DataBlocks of the appropriate size and number of data codewords
}catch(err){_iterator41.e(err);}finally{_iterator41.f();}var result=new Array(totalBlocks);var numResultBlocks=0;var _iterator42=_createForOfIteratorHelper(ecBlockArray),_step42;try{for(_iterator42.s();!(_step42=_iterator42.n()).done;){var _ecBlock2=_step42.value;for(var _i31=0;_i31<_ecBlock2.getCount();_i31++){var numDataCodewords=_ecBlock2.getDataCodewords();var numBlockCodewords=ecBlocks.getECCodewordsPerBlock()+numDataCodewords;result[numResultBlocks++]=new DataBlock$1(numDataCodewords,new Uint8Array(numBlockCodewords));}}// All blocks have the same amount of data, except that the last n
// (where n may be 0) have 1 more byte. Figure out where these start.
}catch(err){_iterator42.e(err);}finally{_iterator42.f();}var shorterBlocksTotalCodewords=result[0].codewords.length;var longerBlocksStartAt=result.length-1;// TYPESCRIPTPORT: check length is correct here
while(longerBlocksStartAt>=0){var numCodewords=result[longerBlocksStartAt].codewords.length;if(numCodewords===shorterBlocksTotalCodewords){break;}longerBlocksStartAt--;}longerBlocksStartAt++;var shorterBlocksNumDataCodewords=shorterBlocksTotalCodewords-ecBlocks.getECCodewordsPerBlock();// The last elements of result may be 1 element longer
// first fill out as many elements as all of them have
var rawCodewordsOffset=0;for(var i=0;i<shorterBlocksNumDataCodewords;i++){for(var j=0;j<numResultBlocks;j++){result[j].codewords[i]=rawCodewords[rawCodewordsOffset++];}}// Fill out the last data block in the longer ones
for(var _j6=longerBlocksStartAt;_j6<numResultBlocks;_j6++){result[_j6].codewords[shorterBlocksNumDataCodewords]=rawCodewords[rawCodewordsOffset++];}// Now add in error correction blocks
var max=result[0].codewords.length;for(var _i30=shorterBlocksNumDataCodewords;_i30<max;_i30++){for(var _j7=0;_j7<numResultBlocks;_j7++){var iOffset=_j7<longerBlocksStartAt?_i30:_i30+1;result[_j7].codewords[iOffset]=rawCodewords[rawCodewordsOffset++];}}return result;}}]);return DataBlock$1;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/var ModeValues;(function(ModeValues){ModeValues[ModeValues["TERMINATOR"]=0]="TERMINATOR";ModeValues[ModeValues["NUMERIC"]=1]="NUMERIC";ModeValues[ModeValues["ALPHANUMERIC"]=2]="ALPHANUMERIC";ModeValues[ModeValues["STRUCTURED_APPEND"]=3]="STRUCTURED_APPEND";ModeValues[ModeValues["BYTE"]=4]="BYTE";ModeValues[ModeValues["ECI"]=5]="ECI";ModeValues[ModeValues["KANJI"]=6]="KANJI";ModeValues[ModeValues["FNC1_FIRST_POSITION"]=7]="FNC1_FIRST_POSITION";ModeValues[ModeValues["FNC1_SECOND_POSITION"]=8]="FNC1_SECOND_POSITION";/** See GBT 18284-2000; "Hanzi" is a transliteration of this mode name. */ModeValues[ModeValues["HANZI"]=9]="HANZI";})(ModeValues||(ModeValues={}));/**
* <p>See ISO 18004:2006, 6.4.1, Tables 2 and 3. This enum encapsulates the various modes in which
* data can be encoded to bits in the QR code standard.</p>
*
* @author Sean Owen
*/var Mode$1=/*#__PURE__*/function(){function Mode$1(value,stringValue,characterCountBitsForVersions,bits/*int*/){_classCallCheck(this,Mode$1);this.value=value;this.stringValue=stringValue;this.characterCountBitsForVersions=characterCountBitsForVersions;this.bits=bits;Mode$1.FOR_BITS.set(bits,this);Mode$1.FOR_VALUE.set(value,this);}/**
* @param bits four bits encoding a QR Code data mode
* @return Mode encoded by these bits
* @throws IllegalArgumentException if bits do not correspond to a known mode
*/_createClass(Mode$1,[{key:"getCharacterCountBits",value:/**
* @param version version in question
* @return number of bits used, in this QR Code symbol {@link Version}, to encode the
* count of characters that will follow encoded in this Mode
*/function getCharacterCountBits(version){var versionNumber=version.getVersionNumber();var offset;if(versionNumber<=9){offset=0;}else if(versionNumber<=26){offset=1;}else{offset=2;}return this.characterCountBitsForVersions[offset];}},{key:"getValue",value:function getValue(){return this.value;}},{key:"getBits",value:function getBits(){return this.bits;}},{key:"equals",value:function equals(o){if(!(o instanceof Mode$1)){return false;}var other=o;return this.value===other.value;}},{key:"toString",value:function toString(){return this.stringValue;}}],[{key:"forBits",value:function forBits(bits/*int*/){var mode=Mode$1.FOR_BITS.get(bits);if(undefined===mode){throw new IllegalArgumentException();}return mode;}}]);return Mode$1;}();Mode$1.FOR_BITS=new Map();Mode$1.FOR_VALUE=new Map();Mode$1.TERMINATOR=new Mode$1(ModeValues.TERMINATOR,'TERMINATOR',Int32Array.from([0,0,0]),0x00);// Not really a mode...
Mode$1.NUMERIC=new Mode$1(ModeValues.NUMERIC,'NUMERIC',Int32Array.from([10,12,14]),0x01);Mode$1.ALPHANUMERIC=new Mode$1(ModeValues.ALPHANUMERIC,'ALPHANUMERIC',Int32Array.from([9,11,13]),0x02);Mode$1.STRUCTURED_APPEND=new Mode$1(ModeValues.STRUCTURED_APPEND,'STRUCTURED_APPEND',Int32Array.from([0,0,0]),0x03);// Not supported
Mode$1.BYTE=new Mode$1(ModeValues.BYTE,'BYTE',Int32Array.from([8,16,16]),0x04);Mode$1.ECI=new Mode$1(ModeValues.ECI,'ECI',Int32Array.from([0,0,0]),0x07);// character counts don't apply
Mode$1.KANJI=new Mode$1(ModeValues.KANJI,'KANJI',Int32Array.from([8,10,12]),0x08);Mode$1.FNC1_FIRST_POSITION=new Mode$1(ModeValues.FNC1_FIRST_POSITION,'FNC1_FIRST_POSITION',Int32Array.from([0,0,0]),0x05);Mode$1.FNC1_SECOND_POSITION=new Mode$1(ModeValues.FNC1_SECOND_POSITION,'FNC1_SECOND_POSITION',Int32Array.from([0,0,0]),0x09);/** See GBT 18284-2000; "Hanzi" is a transliteration of this mode name. */Mode$1.HANZI=new Mode$1(ModeValues.HANZI,'HANZI',Int32Array.from([8,10,12]),0x0D);/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*import java.io.UnsupportedEncodingException;*/ /*import java.util.ArrayList;*/ /*import java.util.Collection;*/ /*import java.util.List;*/ /*import java.util.Map;*/ /**
* <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
* in one QR Code. This class decodes the bits back into text.</p>
*
* <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
*
* @author Sean Owen
*/var DecodedBitStreamParser$1=/*#__PURE__*/function(){function DecodedBitStreamParser$1(){_classCallCheck(this,DecodedBitStreamParser$1);}_createClass(DecodedBitStreamParser$1,null,[{key:"decode",value:function decode(bytes,version,ecLevel,hints){var bits=new BitSource(bytes);var result=new StringBuilder();var byteSegments=new Array();// 1
// TYPESCRIPTPORT: I do not use constructor with size 1 as in original Java means capacity and the array length is checked below
var symbolSequence=-1;var parityData=-1;try{var currentCharacterSetECI=null;var fc1InEffect=false;var mode;do{// While still another segment to read...
if(bits.available()<4){// OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
mode=Mode$1.TERMINATOR;}else{var modeBits=bits.readBits(4);mode=Mode$1.forBits(modeBits);// mode is encoded by 4 bits
}switch(mode){case Mode$1.TERMINATOR:break;case Mode$1.FNC1_FIRST_POSITION:case Mode$1.FNC1_SECOND_POSITION:// We do little with FNC1 except alter the parsed result a bit according to the spec
fc1InEffect=true;break;case Mode$1.STRUCTURED_APPEND:if(bits.available()<16){throw new FormatException();}// sequence number and parity is added later to the result metadata
// Read next 8 bits (symbol sequence #) and 8 bits (data: parity), then continue
symbolSequence=bits.readBits(8);parityData=bits.readBits(8);break;case Mode$1.ECI:// Count doesn't apply to ECI
var value=DecodedBitStreamParser$1.parseECIValue(bits);currentCharacterSetECI=CharacterSetECI.getCharacterSetECIByValue(value);if(currentCharacterSetECI===null){throw new FormatException();}break;case Mode$1.HANZI:// First handle Hanzi mode which does not start with character count
// Chinese mode contains a sub set indicator right after mode indicator
var subset=bits.readBits(4);var countHanzi=bits.readBits(mode.getCharacterCountBits(version));if(subset===DecodedBitStreamParser$1.GB2312_SUBSET){DecodedBitStreamParser$1.decodeHanziSegment(bits,result,countHanzi);}break;default:// "Normal" QR code modes:
// How many characters will follow, encoded in this mode?
var count=bits.readBits(mode.getCharacterCountBits(version));switch(mode){case Mode$1.NUMERIC:DecodedBitStreamParser$1.decodeNumericSegment(bits,result,count);break;case Mode$1.ALPHANUMERIC:DecodedBitStreamParser$1.decodeAlphanumericSegment(bits,result,count,fc1InEffect);break;case Mode$1.BYTE:DecodedBitStreamParser$1.decodeByteSegment(bits,result,count,currentCharacterSetECI,byteSegments,hints);break;case Mode$1.KANJI:DecodedBitStreamParser$1.decodeKanjiSegment(bits,result,count);break;default:throw new FormatException();}break;}}while(mode!==Mode$1.TERMINATOR);}catch(iae/*: IllegalArgumentException*/){// from readBits() calls
throw new FormatException();}return new DecoderResult(bytes,result.toString(),byteSegments.length===0?null:byteSegments,ecLevel===null?null:ecLevel.toString(),symbolSequence,parityData);}/**
* See specification GBT 18284-2000
*/},{key:"decodeHanziSegment",value:function decodeHanziSegment(bits,result,count/*int*/){// Don't crash trying to read more bits than we have available.
if(count*13>bits.available()){throw new FormatException();}// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as GB2312 afterwards
var buffer=new Uint8Array(2*count);var offset=0;while(count>0){// Each 13 bits encodes a 2-byte character
var twoBytes=bits.readBits(13);var assembledTwoBytes=twoBytes/0x060<<8&0xFFFFFFFF|twoBytes%0x060;if(assembledTwoBytes<0x003BF){// In the 0xA1A1 to 0xAAFE range
assembledTwoBytes+=0x0A1A1;}else{// In the 0xB0A1 to 0xFAFE range
assembledTwoBytes+=0x0A6A1;}buffer[offset]=/*(byte) */assembledTwoBytes>>8&0xFF;buffer[offset+1]=/*(byte) */assembledTwoBytes&0xFF;offset+=2;count--;}try{result.append(StringEncoding.decode(buffer,StringUtils.GB2312));// TYPESCRIPTPORT: TODO: implement GB2312 decode. StringView from MDN could be a starting point
}catch(ignored/*: UnsupportedEncodingException*/){throw new FormatException(ignored);}}},{key:"decodeKanjiSegment",value:function decodeKanjiSegment(bits,result,count/*int*/){// Don't crash trying to read more bits than we have available.
if(count*13>bits.available()){throw new FormatException();}// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as Shift_JIS afterwards
var buffer=new Uint8Array(2*count);var offset=0;while(count>0){// Each 13 bits encodes a 2-byte character
var twoBytes=bits.readBits(13);var assembledTwoBytes=twoBytes/0x0C0<<8&0xFFFFFFFF|twoBytes%0x0C0;if(assembledTwoBytes<0x01F00){// In the 0x8140 to 0x9FFC range
assembledTwoBytes+=0x08140;}else{// In the 0xE040 to 0xEBBF range
assembledTwoBytes+=0x0C140;}buffer[offset]=/*(byte) */assembledTwoBytes>>8;buffer[offset+1]=/*(byte) */assembledTwoBytes;offset+=2;count--;}// Shift_JIS may not be supported in some environments:
try{result.append(StringEncoding.decode(buffer,StringUtils.SHIFT_JIS));// TYPESCRIPTPORT: TODO: implement SHIFT_JIS decode. StringView from MDN could be a starting point
}catch(ignored/*: UnsupportedEncodingException*/){throw new FormatException(ignored);}}},{key:"decodeByteSegment",value:function decodeByteSegment(bits,result,count/*int*/,currentCharacterSetECI,byteSegments,hints){// Don't crash trying to read more bits than we have available.
if(8*count>bits.available()){throw new FormatException();}var readBytes=new Uint8Array(count);for(var i=0;i<count;i++){readBytes[i]=/*(byte) */bits.readBits(8);}var encoding;if(currentCharacterSetECI===null){// The spec isn't clear on this mode; see
// section 6.4.5: t does not say which encoding to assuming
// upon decoding. I have seen ISO-8859-1 used as well as
// Shift_JIS -- without anything like an ECI designator to
// give a hint.
encoding=StringUtils.guessEncoding(readBytes,hints);}else{encoding=currentCharacterSetECI.getName();}try{result.append(StringEncoding.decode(readBytes,encoding));}catch(ignored/*: UnsupportedEncodingException*/){throw new FormatException(ignored);}byteSegments.push(readBytes);}},{key:"toAlphaNumericChar",value:function toAlphaNumericChar(value/*int*/){if(value>=DecodedBitStreamParser$1.ALPHANUMERIC_CHARS.length){throw new FormatException();}return DecodedBitStreamParser$1.ALPHANUMERIC_CHARS[value];}},{key:"decodeAlphanumericSegment",value:function decodeAlphanumericSegment(bits,result,count/*int*/,fc1InEffect){// Read two characters at a time
var start=result.length();while(count>1){if(bits.available()<11){throw new FormatException();}var nextTwoCharsBits=bits.readBits(11);result.append(DecodedBitStreamParser$1.toAlphaNumericChar(Math.floor(nextTwoCharsBits/45)));result.append(DecodedBitStreamParser$1.toAlphaNumericChar(nextTwoCharsBits%45));count-=2;}if(count===1){// special case: one character left
if(bits.available()<6){throw new FormatException();}result.append(DecodedBitStreamParser$1.toAlphaNumericChar(bits.readBits(6)));}// See section 6.4.8.1, 6.4.8.2
if(fc1InEffect){// We need to massage the result a bit if in an FNC1 mode:
for(var i=start;i<result.length();i++){if(result.charAt(i)==='%'){if(i<result.length()-1&&result.charAt(i+1)==='%'){// %% is rendered as %
result.deleteCharAt(i+1);}else{// In alpha mode, % should be converted to FNC1 separator 0x1D
result.setCharAt(i,String.fromCharCode(0x1D));}}}}}},{key:"decodeNumericSegment",value:function decodeNumericSegment(bits,result,count/*int*/){// Read three digits at a time
while(count>=3){// Each 10 bits encodes three digits
if(bits.available()<10){throw new FormatException();}var threeDigitsBits=bits.readBits(10);if(threeDigitsBits>=1000){throw new FormatException();}result.append(DecodedBitStreamParser$1.toAlphaNumericChar(Math.floor(threeDigitsBits/100)));result.append(DecodedBitStreamParser$1.toAlphaNumericChar(Math.floor(threeDigitsBits/10)%10));result.append(DecodedBitStreamParser$1.toAlphaNumericChar(threeDigitsBits%10));count-=3;}if(count===2){// Two digits left over to read, encoded in 7 bits
if(bits.available()<7){throw new FormatException();}var twoDigitsBits=bits.readBits(7);if(twoDigitsBits>=100){throw new FormatException();}result.append(DecodedBitStreamParser$1.toAlphaNumericChar(Math.floor(twoDigitsBits/10)));result.append(DecodedBitStreamParser$1.toAlphaNumericChar(twoDigitsBits%10));}else if(count===1){// One digit left over to read
if(bits.available()<4){throw new FormatException();}var digitBits=bits.readBits(4);if(digitBits>=10){throw new FormatException();}result.append(DecodedBitStreamParser$1.toAlphaNumericChar(digitBits));}}},{key:"parseECIValue",value:function parseECIValue(bits){var firstByte=bits.readBits(8);if((firstByte&0x80)===0){// just one byte
return firstByte&0x7F;}if((firstByte&0xC0)===0x80){// two bytes
var secondByte=bits.readBits(8);return(firstByte&0x3F)<<8&0xFFFFFFFF|secondByte;}if((firstByte&0xE0)===0xC0){// three bytes
var secondThirdBytes=bits.readBits(16);return(firstByte&0x1F)<<16&0xFFFFFFFF|secondThirdBytes;}throw new FormatException();}}]);return DecodedBitStreamParser$1;}();/**
* See ISO 18004:2006, 6.4.4 Table 5
*/DecodedBitStreamParser$1.ALPHANUMERIC_CHARS='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:';DecodedBitStreamParser$1.GB2312_SUBSET=1;// function Uint8ArrayToString(a: Uint8Array): string {
// const CHUNK_SZ = 0x8000;
// const c = new StringBuilder();
// for (let i = 0, length = a.length; i < length; i += CHUNK_SZ) {
// c.append(String.fromCharCode.apply(null, a.subarray(i, i + CHUNK_SZ)));
// }
// return c.toString();
// }
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* Meta-data container for QR Code decoding. Instances of this class may be used to convey information back to the
* decoding caller. Callers are expected to process this.
*
* @see com.google.zxing.common.DecoderResult#getOther()
*/var QRCodeDecoderMetaData=/*#__PURE__*/function(){function QRCodeDecoderMetaData(mirrored){_classCallCheck(this,QRCodeDecoderMetaData);this.mirrored=mirrored;}/**
* @return true if the QR Code was mirrored.
*/_createClass(QRCodeDecoderMetaData,[{key:"isMirrored",value:function isMirrored(){return this.mirrored;}/**
* Apply the result points' order correction due to mirroring.
*
* @param points Array of points to apply mirror correction to.
*/},{key:"applyMirroredCorrection",value:function applyMirroredCorrection(points){if(!this.mirrored||points===null||points.length<3){return;}var bottomLeft=points[0];points[0]=points[2];points[2]=bottomLeft;// No need to 'fix' top-left and alignment pattern.
}}]);return QRCodeDecoderMetaData;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*import java.util.Map;*/ /**
* <p>The main class which implements QR Code decoding -- as opposed to locating and extracting
* the QR Code from an image.</p>
*
* @author Sean Owen
*/var Decoder$2=/*#__PURE__*/function(){function Decoder$2(){_classCallCheck(this,Decoder$2);this.rsDecoder=new ReedSolomonDecoder(GenericGF.QR_CODE_FIELD_256);}// public decode(image: boolean[][]): DecoderResult /*throws ChecksumException, FormatException*/ {
// return decode(image, null)
// }
/**
* <p>Convenience method that can decode a QR Code represented as a 2D array of booleans.
* "true" is taken to mean a black module.</p>
*
* @param image booleans representing white/black QR Code modules
* @param hints decoding hints that should be used to influence decoding
* @return text and bytes encoded within the QR Code
* @throws FormatException if the QR Code cannot be decoded
* @throws ChecksumException if error correction fails
*/_createClass(Decoder$2,[{key:"decodeBooleanArray",value:function decodeBooleanArray(image,hints){return this.decodeBitMatrix(BitMatrix.parseFromBooleanArray(image),hints);}// public decodeBitMatrix(bits: BitMatrix): DecoderResult /*throws ChecksumException, FormatException*/ {
// return decode(bits, null)
// }
/**
* <p>Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.</p>
*
* @param bits booleans representing white/black QR Code modules
* @param hints decoding hints that should be used to influence decoding
* @return text and bytes encoded within the QR Code
* @throws FormatException if the QR Code cannot be decoded
* @throws ChecksumException if error correction fails
*/},{key:"decodeBitMatrix",value:function decodeBitMatrix(bits,hints){// Construct a parser and read version, error-correction level
var parser=new BitMatrixParser$1(bits);var ex=null;try{return this.decodeBitMatrixParser(parser,hints);}catch(e/*: FormatException, ChecksumException*/){ex=e;}try{// Revert the bit matrix
parser.remask();// Will be attempting a mirrored reading of the version and format info.
parser.setMirror(true);// Preemptively read the version.
parser.readVersion();// Preemptively read the format information.
parser.readFormatInformation();/*
* Since we're here, this means we have successfully detected some kind
* of version and format information when mirrored. This is a good sign,
* that the QR code may be mirrored, and we should try once more with a
* mirrored content.
*/ // Prepare for a mirrored reading.
parser.mirror();var result=this.decodeBitMatrixParser(parser,hints);// Success! Notify the caller that the code was mirrored.
result.setOther(new QRCodeDecoderMetaData(true));return result;}catch(e/*FormatException | ChecksumException*/){// Throw the exception from the original reading
if(ex!==null){throw ex;}throw e;}}},{key:"decodeBitMatrixParser",value:function decodeBitMatrixParser(parser,hints){var version=parser.readVersion();var ecLevel=parser.readFormatInformation().getErrorCorrectionLevel();// Read codewords
var codewords=parser.readCodewords();// Separate into data blocks
var dataBlocks=DataBlock$1.getDataBlocks(codewords,version,ecLevel);// Count total number of data bytes
var totalBytes=0;var _iterator43=_createForOfIteratorHelper(dataBlocks),_step43;try{for(_iterator43.s();!(_step43=_iterator43.n()).done;){var dataBlock=_step43.value;totalBytes+=dataBlock.getNumDataCodewords();}}catch(err){_iterator43.e(err);}finally{_iterator43.f();}var resultBytes=new Uint8Array(totalBytes);var resultOffset=0;// Error-correct and copy data blocks together into a stream of bytes
var _iterator44=_createForOfIteratorHelper(dataBlocks),_step44;try{for(_iterator44.s();!(_step44=_iterator44.n()).done;){var _dataBlock=_step44.value;var codewordBytes=_dataBlock.getCodewords();var numDataCodewords=_dataBlock.getNumDataCodewords();this.correctErrors(codewordBytes,numDataCodewords);for(var i=0;i<numDataCodewords;i++){resultBytes[resultOffset++]=codewordBytes[i];}}// Decode the contents of that stream of bytes
}catch(err){_iterator44.e(err);}finally{_iterator44.f();}return DecodedBitStreamParser$1.decode(resultBytes,version,ecLevel,hints);}/**
* <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
* correct the errors in-place using Reed-Solomon error correction.</p>
*
* @param codewordBytes data and error correction codewords
* @param numDataCodewords number of codewords that are data bytes
* @throws ChecksumException if error correction fails
*/},{key:"correctErrors",value:function correctErrors(codewordBytes,numDataCodewords/*int*/){// const numCodewords = codewordBytes.length;
// First read into an array of ints
var codewordsInts=new Int32Array(codewordBytes);// TYPESCRIPTPORT: not realy necessary to transform to ints? could redesign everything to work with unsigned bytes?
// const codewordsInts = new Int32Array(numCodewords)
// for (let i = 0; i < numCodewords; i++) {
// codewordsInts[i] = codewordBytes[i] & 0xFF
// }
try{this.rsDecoder.decode(codewordsInts,codewordBytes.length-numDataCodewords);}catch(ignored/*: ReedSolomonException*/){throw new ChecksumException();}// Copy back into array of bytes -- only need to worry about the bytes that were data
// We don't care about errors in the error-correction codewords
for(var i=0;i<numDataCodewords;i++){codewordBytes[i]=/*(byte) */codewordsInts[i];}}}]);return Decoder$2;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Encapsulates an alignment pattern, which are the smaller square patterns found in
* all but the simplest QR Codes.</p>
*
* @author Sean Owen
*/var AlignmentPattern=/*#__PURE__*/function(_ResultPoint){_inherits(AlignmentPattern,_ResultPoint);var _super52=_createSuper(AlignmentPattern);function AlignmentPattern(posX/*float*/,posY/*float*/,estimatedModuleSize/*float*/){var _this33;_classCallCheck(this,AlignmentPattern);_this33=_super52.call(this,posX,posY);_this33.estimatedModuleSize=estimatedModuleSize;return _this33;}/**
* <p>Determines if this alignment pattern "about equals" an alignment pattern at the stated
* position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
*/_createClass(AlignmentPattern,[{key:"aboutEquals",value:function aboutEquals(moduleSize/*float*/,i/*float*/,j/*float*/){if(Math.abs(i-this.getY())<=moduleSize&&Math.abs(j-this.getX())<=moduleSize){var moduleSizeDiff=Math.abs(moduleSize-this.estimatedModuleSize);return moduleSizeDiff<=1.0||moduleSizeDiff<=this.estimatedModuleSize;}return false;}/**
* Combines this object's current estimate of a finder pattern position and module size
* with a new estimate. It returns a new {@code FinderPattern} containing an average of the two.
*/},{key:"combineEstimate",value:function combineEstimate(i/*float*/,j/*float*/,newModuleSize/*float*/){var combinedX=(this.getX()+j)/2.0;var combinedY=(this.getY()+i)/2.0;var combinedModuleSize=(this.estimatedModuleSize+newModuleSize)/2.0;return new AlignmentPattern(combinedX,combinedY,combinedModuleSize);}}]);return AlignmentPattern;}(ResultPoint);/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*import java.util.ArrayList;*/ /*import java.util.List;*/ /**
* <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder
* patterns but are smaller and appear at regular intervals throughout the image.</p>
*
* <p>At the moment this only looks for the bottom-right alignment pattern.</p>
*
* <p>This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied,
* pasted and stripped down here for maximum performance but does unfortunately duplicate
* some code.</p>
*
* <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.</p>
*
* @author Sean Owen
*/var AlignmentPatternFinder=/*#__PURE__*/function(){/**
* <p>Creates a finder that will look in a portion of the whole image.</p>
*
* @param image image to search
* @param startX left column from which to start searching
* @param startY top row from which to start searching
* @param width width of region to search
* @param height height of region to search
* @param moduleSize estimated module size so far
*/function AlignmentPatternFinder(image,startX/*int*/,startY/*int*/,width/*int*/,height/*int*/,moduleSize/*float*/,resultPointCallback){_classCallCheck(this,AlignmentPatternFinder);this.image=image;this.startX=startX;this.startY=startY;this.width=width;this.height=height;this.moduleSize=moduleSize;this.resultPointCallback=resultPointCallback;this.possibleCenters=[];// new Array<any>(5))
// TYPESCRIPTPORT: array initialization without size as the length is checked below
this.crossCheckStateCount=new Int32Array(3);}/**
* <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since
* it's pretty performance-critical and so is written to be fast foremost.</p>
*
* @return {@link AlignmentPattern} if found
* @throws NotFoundException if not found
*/_createClass(AlignmentPatternFinder,[{key:"find",value:function find(){var startX=this.startX;var height=this.height;var width=this.width;var maxJ=startX+width;var middleI=this.startY+height/2;// We are looking for black/white/black modules in 1:1:1 ratio
// this tracks the number of black/white/black modules seen so far
var stateCount=new Int32Array(3);var image=this.image;for(var iGen=0;iGen<height;iGen++){// Search from middle outwards
var i=middleI+((iGen&0x01)===0?Math.floor((iGen+1)/2):-Math.floor((iGen+1)/2));stateCount[0]=0;stateCount[1]=0;stateCount[2]=0;var j=startX;// Burn off leading white pixels before anything else; if we start in the middle of
// a white run, it doesn't make sense to count its length, since we don't know if the
// white run continued to the left of the start point
while(j<maxJ&&!image.get(j,i)){j++;}var currentState=0;while(j<maxJ){if(image.get(j,i)){// Black pixel
if(currentState===1){// Counting black pixels
stateCount[1]++;}else{// Counting white pixels
if(currentState===2){// A winner?
if(this.foundPatternCross(stateCount)){// Yes
var confirmed=this.handlePossibleCenter(stateCount,i,j);if(confirmed!==null){return confirmed;}}stateCount[0]=stateCount[2];stateCount[1]=1;stateCount[2]=0;currentState=1;}else{stateCount[++currentState]++;}}}else{// White pixel
if(currentState===1){// Counting black pixels
currentState++;}stateCount[currentState]++;}j++;}if(this.foundPatternCross(stateCount)){var _confirmed=this.handlePossibleCenter(stateCount,i,maxJ);if(_confirmed!==null){return _confirmed;}}}// Hmm, nothing we saw was observed and confirmed twice. If we had
// any guess at all, return it.
if(this.possibleCenters.length!==0){return this.possibleCenters[0];}throw new NotFoundException();}/**
* Given a count of black/white/black pixels just seen and an end position,
* figures the location of the center of this black/white/black run.
*/},{key:"foundPatternCross",value:/**
* @param stateCount count of black/white/black pixels just read
* @return true iff the proportions of the counts is close enough to the 1/1/1 ratios
* used by alignment patterns to be considered a match
*/function foundPatternCross(stateCount){var moduleSize=this.moduleSize;var maxVariance=moduleSize/2.0;for(var i=0;i<3;i++){if(Math.abs(moduleSize-stateCount[i])>=maxVariance){return false;}}return true;}/**
* <p>After a horizontal scan finds a potential alignment pattern, this method
* "cross-checks" by scanning down vertically through the center of the possible
* alignment pattern to see if the same proportion is detected.</p>
*
* @param startI row where an alignment pattern was detected
* @param centerJ center of the section that appears to cross an alignment pattern
* @param maxCount maximum reasonable number of modules that should be
* observed in any reading state, based on the results of the horizontal scan
* @return vertical center of alignment pattern, or {@link Float#NaN} if not found
*/},{key:"crossCheckVertical",value:function crossCheckVertical(startI/*int*/,centerJ/*int*/,maxCount/*int*/,originalStateCountTotal/*int*/){var image=this.image;var maxI=image.getHeight();var stateCount=this.crossCheckStateCount;stateCount[0]=0;stateCount[1]=0;stateCount[2]=0;// Start counting up from center
var i=startI;while(i>=0&&image.get(centerJ,i)&&stateCount[1]<=maxCount){stateCount[1]++;i--;}// If already too many modules in this state or ran off the edge:
if(i<0||stateCount[1]>maxCount){return NaN;}while(i>=0&&!image.get(centerJ,i)&&stateCount[0]<=maxCount){stateCount[0]++;i--;}if(stateCount[0]>maxCount){return NaN;}// Now also count down from center
i=startI+1;while(i<maxI&&image.get(centerJ,i)&&stateCount[1]<=maxCount){stateCount[1]++;i++;}if(i===maxI||stateCount[1]>maxCount){return NaN;}while(i<maxI&&!image.get(centerJ,i)&&stateCount[2]<=maxCount){stateCount[2]++;i++;}if(stateCount[2]>maxCount){return NaN;}var stateCountTotal=stateCount[0]+stateCount[1]+stateCount[2];if(5*Math.abs(stateCountTotal-originalStateCountTotal)>=2*originalStateCountTotal){return NaN;}return this.foundPatternCross(stateCount)?AlignmentPatternFinder.centerFromEnd(stateCount,i):NaN;}/**
* <p>This is called when a horizontal scan finds a possible alignment pattern. It will
* cross check with a vertical scan, and if successful, will see if this pattern had been
* found on a previous horizontal scan. If so, we consider it confirmed and conclude we have
* found the alignment pattern.</p>
*
* @param stateCount reading state module counts from horizontal scan
* @param i row where alignment pattern may be found
* @param j end of possible alignment pattern in row
* @return {@link AlignmentPattern} if we have found the same pattern twice, or null if not
*/},{key:"handlePossibleCenter",value:function handlePossibleCenter(stateCount,i/*int*/,j/*int*/){var stateCountTotal=stateCount[0]+stateCount[1]+stateCount[2];var centerJ=AlignmentPatternFinder.centerFromEnd(stateCount,j);var centerI=this.crossCheckVertical(i,/*(int) */centerJ,2*stateCount[1],stateCountTotal);if(!isNaN(centerI)){var estimatedModuleSize=(stateCount[0]+stateCount[1]+stateCount[2])/3.0;var _iterator45=_createForOfIteratorHelper(this.possibleCenters),_step45;try{for(_iterator45.s();!(_step45=_iterator45.n()).done;){var center=_step45.value;// Look for about the same center and module size:
if(center.aboutEquals(estimatedModuleSize,centerI,centerJ)){return center.combineEstimate(centerI,centerJ,estimatedModuleSize);}}// Hadn't found this before; save it
}catch(err){_iterator45.e(err);}finally{_iterator45.f();}var point=new AlignmentPattern(centerJ,centerI,estimatedModuleSize);this.possibleCenters.push(point);if(this.resultPointCallback!==null&&this.resultPointCallback!==undefined){this.resultPointCallback.foundPossibleResultPoint(point);}}return null;}}],[{key:"centerFromEnd",value:function centerFromEnd(stateCount,end/*int*/){return end-stateCount[2]-stateCount[1]/2.0;}}]);return AlignmentPatternFinder;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Encapsulates a finder pattern, which are the three square patterns found in
* the corners of QR Codes. It also encapsulates a count of similar finder patterns,
* as a convenience to the finder's bookkeeping.</p>
*
* @author Sean Owen
*/var FinderPattern$1=/*#__PURE__*/function(_ResultPoint2){_inherits(FinderPattern$1,_ResultPoint2);var _super53=_createSuper(FinderPattern$1);// FinderPattern(posX: number/*float*/, posY: number/*float*/, estimatedModuleSize: number/*float*/) {
// this(posX, posY, estimatedModuleSize, 1)
// }
function FinderPattern$1(posX/*float*/,posY/*float*/,estimatedModuleSize/*float*/,count/*int*/){var _this34;_classCallCheck(this,FinderPattern$1);_this34=_super53.call(this,posX,posY);_this34.estimatedModuleSize=estimatedModuleSize;_this34.count=count;if(undefined===count){_this34.count=1;}return _this34;}_createClass(FinderPattern$1,[{key:"getEstimatedModuleSize",value:function getEstimatedModuleSize(){return this.estimatedModuleSize;}},{key:"getCount",value:function getCount(){return this.count;}/*
void incrementCount() {
this.count++
}
*/ /**
* <p>Determines if this finder pattern "about equals" a finder pattern at the stated
* position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
*/},{key:"aboutEquals",value:function aboutEquals(moduleSize/*float*/,i/*float*/,j/*float*/){if(Math.abs(i-this.getY())<=moduleSize&&Math.abs(j-this.getX())<=moduleSize){var moduleSizeDiff=Math.abs(moduleSize-this.estimatedModuleSize);return moduleSizeDiff<=1.0||moduleSizeDiff<=this.estimatedModuleSize;}return false;}/**
* Combines this object's current estimate of a finder pattern position and module size
* with a new estimate. It returns a new {@code FinderPattern} containing a weighted average
* based on count.
*/},{key:"combineEstimate",value:function combineEstimate(i/*float*/,j/*float*/,newModuleSize/*float*/){var combinedCount=this.count+1;var combinedX=(this.count*this.getX()+j)/combinedCount;var combinedY=(this.count*this.getY()+i)/combinedCount;var combinedModuleSize=(this.count*this.estimatedModuleSize+newModuleSize)/combinedCount;return new FinderPattern$1(combinedX,combinedY,combinedModuleSize,combinedCount);}}]);return FinderPattern$1;}(ResultPoint);/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>Encapsulates information about finder patterns in an image, including the location of
* the three finder patterns, and their estimated module size.</p>
*
* @author Sean Owen
*/var FinderPatternInfo=/*#__PURE__*/function(){function FinderPatternInfo(patternCenters){_classCallCheck(this,FinderPatternInfo);this.bottomLeft=patternCenters[0];this.topLeft=patternCenters[1];this.topRight=patternCenters[2];}_createClass(FinderPatternInfo,[{key:"getBottomLeft",value:function getBottomLeft(){return this.bottomLeft;}},{key:"getTopLeft",value:function getTopLeft(){return this.topLeft;}},{key:"getTopRight",value:function getTopRight(){return this.topRight;}}]);return FinderPatternInfo;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*import java.io.Serializable;*/ /*import java.util.ArrayList;*/ /*import java.util.Collections;*/ /*import java.util.Comparator;*/ /*import java.util.List;*/ /*import java.util.Map;*/ /**
* <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
* markers at three corners of a QR Code.</p>
*
* <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
*
* @author Sean Owen
*/var FinderPatternFinder=/*#__PURE__*/function(){/**
* <p>Creates a finder that will search the image for three finder patterns.</p>
*
* @param image image to search
*/ // public constructor(image: BitMatrix) {
// this(image, null)
// }
function FinderPatternFinder(image,resultPointCallback){_classCallCheck(this,FinderPatternFinder);this.image=image;this.resultPointCallback=resultPointCallback;this.possibleCenters=[];this.crossCheckStateCount=new Int32Array(5);this.resultPointCallback=resultPointCallback;}_createClass(FinderPatternFinder,[{key:"getImage",value:function getImage(){return this.image;}},{key:"getPossibleCenters",value:function getPossibleCenters(){return this.possibleCenters;}},{key:"find",value:function find(hints){var tryHarder=hints!==null&&hints!==undefined&&undefined!==hints.get(DecodeHintType$1.TRY_HARDER);var pureBarcode=hints!==null&&hints!==undefined&&undefined!==hints.get(DecodeHintType$1.PURE_BARCODE);var image=this.image;var maxI=image.getHeight();var maxJ=image.getWidth();// We are looking for black/white/black/white/black modules in
// 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
// Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
// image, and then account for the center being 3 modules in size. This gives the smallest
// number of pixels the center could be, so skip this often. When trying harder, look for all
// QR versions regardless of how dense they are.
var iSkip=Math.floor(3*maxI/(4*FinderPatternFinder.MAX_MODULES));if(iSkip<FinderPatternFinder.MIN_SKIP||tryHarder){iSkip=FinderPatternFinder.MIN_SKIP;}var done=false;var stateCount=new Int32Array(5);for(var i=iSkip-1;i<maxI&&!done;i+=iSkip){// Get a row of black/white values
stateCount[0]=0;stateCount[1]=0;stateCount[2]=0;stateCount[3]=0;stateCount[4]=0;var currentState=0;for(var j=0;j<maxJ;j++){if(image.get(j,i)){// Black pixel
if((currentState&1)===1){// Counting white pixels
currentState++;}stateCount[currentState]++;}else{// White pixel
if((currentState&1)===0){// Counting black pixels
if(currentState===4){// A winner?
if(FinderPatternFinder.foundPatternCross(stateCount)){// Yes
var confirmed=this.handlePossibleCenter(stateCount,i,j,pureBarcode);if(confirmed===true){// Start examining every other line. Checking each line turned out to be too
// expensive and didn't improve performance.
iSkip=2;if(this.hasSkipped===true){done=this.haveMultiplyConfirmedCenters();}else{var rowSkip=this.findRowSkip();if(rowSkip>stateCount[2]){// Skip rows between row of lower confirmed center
// and top of presumed third confirmed center
// but back up a bit to get a full chance of detecting
// it, entire width of center of finder pattern
// Skip by rowSkip, but back off by stateCount[2] (size of last center
// of pattern we saw) to be conservative, and also back off by iSkip which
// is about to be re-added
i+=rowSkip-stateCount[2]-iSkip;j=maxJ-1;}}}else{stateCount[0]=stateCount[2];stateCount[1]=stateCount[3];stateCount[2]=stateCount[4];stateCount[3]=1;stateCount[4]=0;currentState=3;continue;}// Clear state to start looking again
currentState=0;stateCount[0]=0;stateCount[1]=0;stateCount[2]=0;stateCount[3]=0;stateCount[4]=0;}else{// No, shift counts back by two
stateCount[0]=stateCount[2];stateCount[1]=stateCount[3];stateCount[2]=stateCount[4];stateCount[3]=1;stateCount[4]=0;currentState=3;}}else{stateCount[++currentState]++;}}else{// Counting white pixels
stateCount[currentState]++;}}}if(FinderPatternFinder.foundPatternCross(stateCount)){var _confirmed2=this.handlePossibleCenter(stateCount,i,maxJ,pureBarcode);if(_confirmed2===true){iSkip=stateCount[0];if(this.hasSkipped){// Found a third one
done=this.haveMultiplyConfirmedCenters();}}}}var patternInfo=this.selectBestPatterns();ResultPoint.orderBestPatterns(patternInfo);return new FinderPatternInfo(patternInfo);}/**
* Given a count of black/white/black/white/black pixels just seen and an end position,
* figures the location of the center of this run.
*/},{key:"getCrossCheckStateCount",value:function getCrossCheckStateCount(){var crossCheckStateCount=this.crossCheckStateCount;crossCheckStateCount[0]=0;crossCheckStateCount[1]=0;crossCheckStateCount[2]=0;crossCheckStateCount[3]=0;crossCheckStateCount[4]=0;return crossCheckStateCount;}/**
* After a vertical and horizontal scan finds a potential finder pattern, this method
* "cross-cross-cross-checks" by scanning down diagonally through the center of the possible
* finder pattern to see if the same proportion is detected.
*
* @param startI row where a finder pattern was detected
* @param centerJ center of the section that appears to cross a finder pattern
* @param maxCount maximum reasonable number of modules that should be
* observed in any reading state, based on the results of the horizontal scan
* @param originalStateCountTotal The original state count total.
* @return true if proportions are withing expected limits
*/},{key:"crossCheckDiagonal",value:function crossCheckDiagonal(startI/*int*/,centerJ/*int*/,maxCount/*int*/,originalStateCountTotal/*int*/){var stateCount=this.getCrossCheckStateCount();// Start counting up, left from center finding black center mass
var i=0;var image=this.image;while(startI>=i&&centerJ>=i&&image.get(centerJ-i,startI-i)){stateCount[2]++;i++;}if(startI<i||centerJ<i){return false;}// Continue up, left finding white space
while(startI>=i&&centerJ>=i&&!image.get(centerJ-i,startI-i)&&stateCount[1]<=maxCount){stateCount[1]++;i++;}// If already too many modules in this state or ran off the edge:
if(startI<i||centerJ<i||stateCount[1]>maxCount){return false;}// Continue up, left finding black border
while(startI>=i&&centerJ>=i&&image.get(centerJ-i,startI-i)&&stateCount[0]<=maxCount){stateCount[0]++;i++;}if(stateCount[0]>maxCount){return false;}var maxI=image.getHeight();var maxJ=image.getWidth();// Now also count down, right from center
i=1;while(startI+i<maxI&&centerJ+i<maxJ&&image.get(centerJ+i,startI+i)){stateCount[2]++;i++;}// Ran off the edge?
if(startI+i>=maxI||centerJ+i>=maxJ){return false;}while(startI+i<maxI&&centerJ+i<maxJ&&!image.get(centerJ+i,startI+i)&&stateCount[3]<maxCount){stateCount[3]++;i++;}if(startI+i>=maxI||centerJ+i>=maxJ||stateCount[3]>=maxCount){return false;}while(startI+i<maxI&&centerJ+i<maxJ&&image.get(centerJ+i,startI+i)&&stateCount[4]<maxCount){stateCount[4]++;i++;}if(stateCount[4]>=maxCount){return false;}// If we found a finder-pattern-like section, but its size is more than 100% different than
// the original, assume it's a false positive
var stateCountTotal=stateCount[0]+stateCount[1]+stateCount[2]+stateCount[3]+stateCount[4];return Math.abs(stateCountTotal-originalStateCountTotal)<2*originalStateCountTotal&&FinderPatternFinder.foundPatternCross(stateCount);}/**
* <p>After a horizontal scan finds a potential finder pattern, this method
* "cross-checks" by scanning down vertically through the center of the possible
* finder pattern to see if the same proportion is detected.</p>
*
* @param startI row where a finder pattern was detected
* @param centerJ center of the section that appears to cross a finder pattern
* @param maxCount maximum reasonable number of modules that should be
* observed in any reading state, based on the results of the horizontal scan
* @return vertical center of finder pattern, or {@link Float#NaN} if not found
*/},{key:"crossCheckVertical",value:function crossCheckVertical(startI/*int*/,centerJ/*int*/,maxCount/*int*/,originalStateCountTotal/*int*/){var image=this.image;var maxI=image.getHeight();var stateCount=this.getCrossCheckStateCount();// Start counting up from center
var i=startI;while(i>=0&&image.get(centerJ,i)){stateCount[2]++;i--;}if(i<0){return NaN;}while(i>=0&&!image.get(centerJ,i)&&stateCount[1]<=maxCount){stateCount[1]++;i--;}// If already too many modules in this state or ran off the edge:
if(i<0||stateCount[1]>maxCount){return NaN;}while(i>=0&&image.get(centerJ,i)&&stateCount[0]<=maxCount){stateCount[0]++;i--;}if(stateCount[0]>maxCount){return NaN;}// Now also count down from center
i=startI+1;while(i<maxI&&image.get(centerJ,i)){stateCount[2]++;i++;}if(i===maxI){return NaN;}while(i<maxI&&!image.get(centerJ,i)&&stateCount[3]<maxCount){stateCount[3]++;i++;}if(i===maxI||stateCount[3]>=maxCount){return NaN;}while(i<maxI&&image.get(centerJ,i)&&stateCount[4]<maxCount){stateCount[4]++;i++;}if(stateCount[4]>=maxCount){return NaN;}// If we found a finder-pattern-like section, but its size is more than 40% different than
// the original, assume it's a false positive
var stateCountTotal=stateCount[0]+stateCount[1]+stateCount[2]+stateCount[3]+stateCount[4];if(5*Math.abs(stateCountTotal-originalStateCountTotal)>=2*originalStateCountTotal){return NaN;}return FinderPatternFinder.foundPatternCross(stateCount)?FinderPatternFinder.centerFromEnd(stateCount,i):NaN;}/**
* <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
* except it reads horizontally instead of vertically. This is used to cross-cross
* check a vertical cross check and locate the real center of the alignment pattern.</p>
*/},{key:"crossCheckHorizontal",value:function crossCheckHorizontal(startJ/*int*/,centerI/*int*/,maxCount/*int*/,originalStateCountTotal/*int*/){var image=this.image;var maxJ=image.getWidth();var stateCount=this.getCrossCheckStateCount();var j=startJ;while(j>=0&&image.get(j,centerI)){stateCount[2]++;j--;}if(j<0){return NaN;}while(j>=0&&!image.get(j,centerI)&&stateCount[1]<=maxCount){stateCount[1]++;j--;}if(j<0||stateCount[1]>maxCount){return NaN;}while(j>=0&&image.get(j,centerI)&&stateCount[0]<=maxCount){stateCount[0]++;j--;}if(stateCount[0]>maxCount){return NaN;}j=startJ+1;while(j<maxJ&&image.get(j,centerI)){stateCount[2]++;j++;}if(j===maxJ){return NaN;}while(j<maxJ&&!image.get(j,centerI)&&stateCount[3]<maxCount){stateCount[3]++;j++;}if(j===maxJ||stateCount[3]>=maxCount){return NaN;}while(j<maxJ&&image.get(j,centerI)&&stateCount[4]<maxCount){stateCount[4]++;j++;}if(stateCount[4]>=maxCount){return NaN;}// If we found a finder-pattern-like section, but its size is significantly different than
// the original, assume it's a false positive
var stateCountTotal=stateCount[0]+stateCount[1]+stateCount[2]+stateCount[3]+stateCount[4];if(5*Math.abs(stateCountTotal-originalStateCountTotal)>=originalStateCountTotal){return NaN;}return FinderPatternFinder.foundPatternCross(stateCount)?FinderPatternFinder.centerFromEnd(stateCount,j):NaN;}/**
* <p>This is called when a horizontal scan finds a possible alignment pattern. It will
* cross check with a vertical scan, and if successful, will, ah, cross-cross-check
* with another horizontal scan. This is needed primarily to locate the real horizontal
* center of the pattern in cases of extreme skew.
* And then we cross-cross-cross check with another diagonal scan.</p>
*
* <p>If that succeeds the finder pattern location is added to a list that tracks
* the number of times each location has been nearly-matched as a finder pattern.
* Each additional find is more evidence that the location is in fact a finder
* pattern center
*
* @param stateCount reading state module counts from horizontal scan
* @param i row where finder pattern may be found
* @param j end of possible finder pattern in row
* @param pureBarcode true if in "pure barcode" mode
* @return true if a finder pattern candidate was found this time
*/},{key:"handlePossibleCenter",value:function handlePossibleCenter(stateCount,i/*int*/,j/*int*/,pureBarcode){var stateCountTotal=stateCount[0]+stateCount[1]+stateCount[2]+stateCount[3]+stateCount[4];var centerJ=FinderPatternFinder.centerFromEnd(stateCount,j);var centerI=this.crossCheckVertical(i,/*(int) */Math.floor(centerJ),stateCount[2],stateCountTotal);if(!isNaN(centerI)){// Re-cross check
centerJ=this.crossCheckHorizontal(/*(int) */Math.floor(centerJ),/*(int) */Math.floor(centerI),stateCount[2],stateCountTotal);if(!isNaN(centerJ)&&(!pureBarcode||this.crossCheckDiagonal(/*(int) */Math.floor(centerI),/*(int) */Math.floor(centerJ),stateCount[2],stateCountTotal))){var estimatedModuleSize=stateCountTotal/7.0;var found=false;var possibleCenters=this.possibleCenters;for(var index=0,length=possibleCenters.length;index<length;index++){var center=possibleCenters[index];// Look for about the same center and module size:
if(center.aboutEquals(estimatedModuleSize,centerI,centerJ)){possibleCenters[index]=center.combineEstimate(centerI,centerJ,estimatedModuleSize);found=true;break;}}if(!found){var point=new FinderPattern$1(centerJ,centerI,estimatedModuleSize);possibleCenters.push(point);if(this.resultPointCallback!==null&&this.resultPointCallback!==undefined){this.resultPointCallback.foundPossibleResultPoint(point);}}return true;}}return false;}/**
* @return number of rows we could safely skip during scanning, based on the first
* two finder patterns that have been located. In some cases their position will
* allow us to infer that the third pattern must lie below a certain point farther
* down in the image.
*/},{key:"findRowSkip",value:function findRowSkip(){var max=this.possibleCenters.length;if(max<=1){return 0;}var firstConfirmedCenter=null;var _iterator46=_createForOfIteratorHelper(this.possibleCenters),_step46;try{for(_iterator46.s();!(_step46=_iterator46.n()).done;){var center=_step46.value;if(center.getCount()>=FinderPatternFinder.CENTER_QUORUM){if(firstConfirmedCenter==null){firstConfirmedCenter=center;}else{// We have two confirmed centers
// How far down can we skip before resuming looking for the next
// pattern? In the worst case, only the difference between the
// difference in the x / y coordinates of the two centers.
// This is the case where you find top left last.
this.hasSkipped=true;return(/*(int) */Math.floor((Math.abs(firstConfirmedCenter.getX()-center.getX())-Math.abs(firstConfirmedCenter.getY()-center.getY()))/2));}}}}catch(err){_iterator46.e(err);}finally{_iterator46.f();}return 0;}/**
* @return true iff we have found at least 3 finder patterns that have been detected
* at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the
* candidates is "pretty similar"
*/},{key:"haveMultiplyConfirmedCenters",value:function haveMultiplyConfirmedCenters(){var confirmedCount=0;var totalModuleSize=0.0;var max=this.possibleCenters.length;var _iterator47=_createForOfIteratorHelper(this.possibleCenters),_step47;try{for(_iterator47.s();!(_step47=_iterator47.n()).done;){var pattern=_step47.value;if(pattern.getCount()>=FinderPatternFinder.CENTER_QUORUM){confirmedCount++;totalModuleSize+=pattern.getEstimatedModuleSize();}}}catch(err){_iterator47.e(err);}finally{_iterator47.f();}if(confirmedCount<3){return false;}// OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
// and that we need to keep looking. We detect this by asking if the estimated module sizes
// vary too much. We arbitrarily say that when the total deviation from average exceeds
// 5% of the total module size estimates, it's too much.
var average=totalModuleSize/max;var totalDeviation=0.0;var _iterator48=_createForOfIteratorHelper(this.possibleCenters),_step48;try{for(_iterator48.s();!(_step48=_iterator48.n()).done;){var _pattern=_step48.value;totalDeviation+=Math.abs(_pattern.getEstimatedModuleSize()-average);}}catch(err){_iterator48.e(err);}finally{_iterator48.f();}return totalDeviation<=0.05*totalModuleSize;}/**
* @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are
* those that have been detected at least {@link #CENTER_QUORUM} times, and whose module
* size differs from the average among those patterns the least
* @throws NotFoundException if 3 such finder patterns do not exist
*/},{key:"selectBestPatterns",value:function selectBestPatterns(){var startSize=this.possibleCenters.length;if(startSize<3){// Couldn't find enough finder patterns
throw new NotFoundException();}var possibleCenters=this.possibleCenters;var average;// Filter outlier possibilities whose module size is too different
if(startSize>3){// But we can only afford to do so if we have at least 4 possibilities to choose from
var totalModuleSize=0.0;var square=0.0;var _iterator49=_createForOfIteratorHelper(this.possibleCenters),_step49;try{for(_iterator49.s();!(_step49=_iterator49.n()).done;){var center=_step49.value;var size=center.getEstimatedModuleSize();totalModuleSize+=size;square+=size*size;}}catch(err){_iterator49.e(err);}finally{_iterator49.f();}average=totalModuleSize/startSize;var stdDev=Math.sqrt(square/startSize-average*average);possibleCenters.sort(/**
* <p>Orders by furthest from average</p>
*/ // FurthestFromAverageComparator implements Comparator<FinderPattern>
function(center1,center2){var dA=Math.abs(center2.getEstimatedModuleSize()-average);var dB=Math.abs(center1.getEstimatedModuleSize()-average);return dA<dB?-1:dA>dB?1:0;});var limit=Math.max(0.2*average,stdDev);for(var i=0;i<possibleCenters.length&&possibleCenters.length>3;i++){var pattern=possibleCenters[i];if(Math.abs(pattern.getEstimatedModuleSize()-average)>limit){possibleCenters.splice(i,1);i--;}}}if(possibleCenters.length>3){// Throw away all but those first size candidate points we found.
var _totalModuleSize=0.0;var _iterator50=_createForOfIteratorHelper(possibleCenters),_step50;try{for(_iterator50.s();!(_step50=_iterator50.n()).done;){var possibleCenter=_step50.value;_totalModuleSize+=possibleCenter.getEstimatedModuleSize();}}catch(err){_iterator50.e(err);}finally{_iterator50.f();}average=_totalModuleSize/possibleCenters.length;possibleCenters.sort(/**
* <p>Orders by {@link FinderPattern#getCount()}, descending.</p>
*/ // CenterComparator implements Comparator<FinderPattern>
function(center1,center2){if(center2.getCount()===center1.getCount()){var dA=Math.abs(center2.getEstimatedModuleSize()-average);var dB=Math.abs(center1.getEstimatedModuleSize()-average);return dA<dB?1:dA>dB?-1:0;}else{return center2.getCount()-center1.getCount();}});possibleCenters.splice(3);// this is not realy necessary as we only return first 3 anyway
}return[possibleCenters[0],possibleCenters[1],possibleCenters[2]];}}],[{key:"centerFromEnd",value:function centerFromEnd(stateCount,end/*int*/){return end-stateCount[4]-stateCount[3]-stateCount[2]/2.0;}/**
* @param stateCount count of black/white/black/white/black pixels just read
* @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios
* used by finder patterns to be considered a match
*/},{key:"foundPatternCross",value:function foundPatternCross(stateCount){var totalModuleSize=0;for(var i=0;i<5;i++){var count=stateCount[i];if(count===0){return false;}totalModuleSize+=count;}if(totalModuleSize<7){return false;}var moduleSize=totalModuleSize/7.0;var maxVariance=moduleSize/2.0;// Allow less than 50% variance from 1-1-3-1-1 proportions
return Math.abs(moduleSize-stateCount[0])<maxVariance&&Math.abs(moduleSize-stateCount[1])<maxVariance&&Math.abs(3.0*moduleSize-stateCount[2])<3*maxVariance&&Math.abs(moduleSize-stateCount[3])<maxVariance&&Math.abs(moduleSize-stateCount[4])<maxVariance;}}]);return FinderPatternFinder;}();FinderPatternFinder.CENTER_QUORUM=2;FinderPatternFinder.MIN_SKIP=3;// 1 pixel/module times 3 modules/center
FinderPatternFinder.MAX_MODULES=57;// support up to version 10 for mobile clients
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*import java.util.Map;*/ /**
* <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
* is rotated or skewed, or partially obscured.</p>
*
* @author Sean Owen
*/var Detector$2=/*#__PURE__*/function(){function Detector$2(image){_classCallCheck(this,Detector$2);this.image=image;}_createClass(Detector$2,[{key:"getImage",value:function getImage(){return this.image;}},{key:"getResultPointCallback",value:function getResultPointCallback(){return this.resultPointCallback;}/**
* <p>Detects a QR Code in an image.</p>
*
* @return {@link DetectorResult} encapsulating results of detecting a QR Code
* @throws NotFoundException if QR Code cannot be found
* @throws FormatException if a QR Code cannot be decoded
*/ // public detect(): DetectorResult /*throws NotFoundException, FormatException*/ {
// return detect(null)
// }
/**
* <p>Detects a QR Code in an image.</p>
*
* @param hints optional hints to detector
* @return {@link DetectorResult} encapsulating results of detecting a QR Code
* @throws NotFoundException if QR Code cannot be found
* @throws FormatException if a QR Code cannot be decoded
*/},{key:"detect",value:function detect(hints){this.resultPointCallback=hints===null||hints===undefined?null:/*(ResultPointCallback) */hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);var finder=new FinderPatternFinder(this.image,this.resultPointCallback);var info=finder.find(hints);return this.processFinderPatternInfo(info);}},{key:"processFinderPatternInfo",value:function processFinderPatternInfo(info){var topLeft=info.getTopLeft();var topRight=info.getTopRight();var bottomLeft=info.getBottomLeft();var moduleSize=this.calculateModuleSize(topLeft,topRight,bottomLeft);if(moduleSize<1.0){throw new NotFoundException('No pattern found in proccess finder.');}var dimension=Detector$2.computeDimension(topLeft,topRight,bottomLeft,moduleSize);var provisionalVersion=Version$1.getProvisionalVersionForDimension(dimension);var modulesBetweenFPCenters=provisionalVersion.getDimensionForVersion()-7;var alignmentPattern=null;// Anything above version 1 has an alignment pattern
if(provisionalVersion.getAlignmentPatternCenters().length>0){// Guess where a "bottom right" finder pattern would have been
var bottomRightX=topRight.getX()-topLeft.getX()+bottomLeft.getX();var bottomRightY=topRight.getY()-topLeft.getY()+bottomLeft.getY();// Estimate that alignment pattern is closer by 3 modules
// from "bottom right" to known top left location
var correctionToTopLeft=1.0-3.0/modulesBetweenFPCenters;var estAlignmentX=/*(int) */Math.floor(topLeft.getX()+correctionToTopLeft*(bottomRightX-topLeft.getX()));var estAlignmentY=/*(int) */Math.floor(topLeft.getY()+correctionToTopLeft*(bottomRightY-topLeft.getY()));// Kind of arbitrary -- expand search radius before giving up
for(var i=4;i<=16;i<<=1){try{alignmentPattern=this.findAlignmentInRegion(moduleSize,estAlignmentX,estAlignmentY,i);break;}catch(re/*NotFoundException*/){if(!(re instanceof NotFoundException)){throw re;}// try next round
}}// If we didn't find alignment pattern... well try anyway without it
}var transform=Detector$2.createTransform(topLeft,topRight,bottomLeft,alignmentPattern,dimension);var bits=Detector$2.sampleGrid(this.image,transform,dimension);var points;if(alignmentPattern===null){points=[bottomLeft,topLeft,topRight];}else{points=[bottomLeft,topLeft,topRight,alignmentPattern];}return new DetectorResult(bits,points);}},{key:"calculateModuleSize",value:/**
* <p>Computes an average estimated module size based on estimated derived from the positions
* of the three finder patterns.</p>
*
* @param topLeft detected top-left finder pattern center
* @param topRight detected top-right finder pattern center
* @param bottomLeft detected bottom-left finder pattern center
* @return estimated module size
*/function calculateModuleSize(topLeft,topRight,bottomLeft){// Take the average
return(this.calculateModuleSizeOneWay(topLeft,topRight)+this.calculateModuleSizeOneWay(topLeft,bottomLeft))/2.0;}/**
* <p>Estimates module size based on two finder patterns -- it uses
* {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
* width of each, measuring along the axis between their centers.</p>
*/},{key:"calculateModuleSizeOneWay",value:function calculateModuleSizeOneWay(pattern,otherPattern){var moduleSizeEst1=this.sizeOfBlackWhiteBlackRunBothWays(/*(int) */Math.floor(pattern.getX()),/*(int) */Math.floor(pattern.getY()),/*(int) */Math.floor(otherPattern.getX()),/*(int) */Math.floor(otherPattern.getY()));var moduleSizeEst2=this.sizeOfBlackWhiteBlackRunBothWays(/*(int) */Math.floor(otherPattern.getX()),/*(int) */Math.floor(otherPattern.getY()),/*(int) */Math.floor(pattern.getX()),/*(int) */Math.floor(pattern.getY()));if(isNaN(moduleSizeEst1)){return moduleSizeEst2/7.0;}if(isNaN(moduleSizeEst2)){return moduleSizeEst1/7.0;}// Average them, and divide by 7 since we've counted the width of 3 black modules,
// and 1 white and 1 black module on either side. Ergo, divide sum by 14.
return(moduleSizeEst1+moduleSizeEst2)/14.0;}/**
* See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
* a finder pattern by looking for a black-white-black run from the center in the direction
* of another point (another finder pattern center), and in the opposite direction too.
*/},{key:"sizeOfBlackWhiteBlackRunBothWays",value:function sizeOfBlackWhiteBlackRunBothWays(fromX/*int*/,fromY/*int*/,toX/*int*/,toY/*int*/){var result=this.sizeOfBlackWhiteBlackRun(fromX,fromY,toX,toY);// Now count other way -- don't run off image though of course
var scale=1.0;var otherToX=fromX-(toX-fromX);if(otherToX<0){scale=fromX/(/*(float) */fromX-otherToX);otherToX=0;}else if(otherToX>=this.image.getWidth()){scale=(this.image.getWidth()-1-fromX)/(/*(float) */otherToX-fromX);otherToX=this.image.getWidth()-1;}var otherToY=/*(int) */Math.floor(fromY-(toY-fromY)*scale);scale=1.0;if(otherToY<0){scale=fromY/(/*(float) */fromY-otherToY);otherToY=0;}else if(otherToY>=this.image.getHeight()){scale=(this.image.getHeight()-1-fromY)/(/*(float) */otherToY-fromY);otherToY=this.image.getHeight()-1;}otherToX=/*(int) */Math.floor(fromX+(otherToX-fromX)*scale);result+=this.sizeOfBlackWhiteBlackRun(fromX,fromY,otherToX,otherToY);// Middle pixel is double-counted this way; subtract 1
return result-1.0;}/**
* <p>This method traces a line from a point in the image, in the direction towards another point.
* It begins in a black region, and keeps going until it finds white, then black, then white again.
* It reports the distance from the start to this point.</p>
*
* <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
* may be skewed or rotated.</p>
*/},{key:"sizeOfBlackWhiteBlackRun",value:function sizeOfBlackWhiteBlackRun(fromX/*int*/,fromY/*int*/,toX/*int*/,toY/*int*/){// Mild variant of Bresenham's algorithm
// see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
var steep=Math.abs(toY-fromY)>Math.abs(toX-fromX);if(steep){var temp=fromX;fromX=fromY;fromY=temp;temp=toX;toX=toY;toY=temp;}var dx=Math.abs(toX-fromX);var dy=Math.abs(toY-fromY);var error=-dx/2;var xstep=fromX<toX?1:-1;var ystep=fromY<toY?1:-1;// In black pixels, looking for white, first or second time.
var state=0;// Loop up until x == toX, but not beyond
var xLimit=toX+xstep;for(var x=fromX,y=fromY;x!==xLimit;x+=xstep){var realX=steep?y:x;var realY=steep?x:y;// Does current pixel mean we have moved white to black or vice versa?
// Scanning black in state 0,2 and white in state 1, so if we find the wrong
// color, advance to next state or end if we are in state 2 already
if(state===1===this.image.get(realX,realY)){if(state===2){return MathUtils.distance(x,y,fromX,fromY);}state++;}error+=dy;if(error>0){if(y===toY){break;}y+=ystep;error-=dx;}}// Found black-white-black; give the benefit of the doubt that the next pixel outside the image
// is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a
// small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
if(state===2){return MathUtils.distance(toX+xstep,toY,fromX,fromY);}// else we didn't find even black-white-black; no estimate is really possible
return NaN;}/**
* <p>Attempts to locate an alignment pattern in a limited region of the image, which is
* guessed to contain it. This method uses {@link AlignmentPattern}.</p>
*
* @param overallEstModuleSize estimated module size so far
* @param estAlignmentX x coordinate of center of area probably containing alignment pattern
* @param estAlignmentY y coordinate of above
* @param allowanceFactor number of pixels in all directions to search from the center
* @return {@link AlignmentPattern} if found, or null otherwise
* @throws NotFoundException if an unexpected error occurs during detection
*/},{key:"findAlignmentInRegion",value:function findAlignmentInRegion(overallEstModuleSize/*float*/,estAlignmentX/*int*/,estAlignmentY/*int*/,allowanceFactor/*float*/){// Look for an alignment pattern (3 modules in size) around where it
// should be
var allowance=/*(int) */Math.floor(allowanceFactor*overallEstModuleSize);var alignmentAreaLeftX=Math.max(0,estAlignmentX-allowance);var alignmentAreaRightX=Math.min(this.image.getWidth()-1,estAlignmentX+allowance);if(alignmentAreaRightX-alignmentAreaLeftX<overallEstModuleSize*3){throw new NotFoundException('Alignment top exceeds estimated module size.');}var alignmentAreaTopY=Math.max(0,estAlignmentY-allowance);var alignmentAreaBottomY=Math.min(this.image.getHeight()-1,estAlignmentY+allowance);if(alignmentAreaBottomY-alignmentAreaTopY<overallEstModuleSize*3){throw new NotFoundException('Alignment bottom exceeds estimated module size.');}var alignmentFinder=new AlignmentPatternFinder(this.image,alignmentAreaLeftX,alignmentAreaTopY,alignmentAreaRightX-alignmentAreaLeftX,alignmentAreaBottomY-alignmentAreaTopY,overallEstModuleSize,this.resultPointCallback);return alignmentFinder.find();}}],[{key:"createTransform",value:function createTransform(topLeft,topRight,bottomLeft,alignmentPattern,dimension/*int*/){var dimMinusThree=dimension-3.5;var bottomRightX;/*float*/var bottomRightY;/*float*/var sourceBottomRightX;/*float*/var sourceBottomRightY;/*float*/if(alignmentPattern!==null){bottomRightX=alignmentPattern.getX();bottomRightY=alignmentPattern.getY();sourceBottomRightX=dimMinusThree-3.0;sourceBottomRightY=sourceBottomRightX;}else{// Don't have an alignment pattern, just make up the bottom-right point
bottomRightX=topRight.getX()-topLeft.getX()+bottomLeft.getX();bottomRightY=topRight.getY()-topLeft.getY()+bottomLeft.getY();sourceBottomRightX=dimMinusThree;sourceBottomRightY=dimMinusThree;}return PerspectiveTransform.quadrilateralToQuadrilateral(3.5,3.5,dimMinusThree,3.5,sourceBottomRightX,sourceBottomRightY,3.5,dimMinusThree,topLeft.getX(),topLeft.getY(),topRight.getX(),topRight.getY(),bottomRightX,bottomRightY,bottomLeft.getX(),bottomLeft.getY());}},{key:"sampleGrid",value:function sampleGrid(image,transform,dimension/*int*/){var sampler=GridSamplerInstance.getInstance();return sampler.sampleGridWithTransform(image,dimension,dimension,transform);}/**
* <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
* of the finder patterns and estimated module size.</p>
*/},{key:"computeDimension",value:function computeDimension(topLeft,topRight,bottomLeft,moduleSize/*float*/){var tltrCentersDimension=MathUtils.round(ResultPoint.distance(topLeft,topRight)/moduleSize);var tlblCentersDimension=MathUtils.round(ResultPoint.distance(topLeft,bottomLeft)/moduleSize);var dimension=Math.floor((tltrCentersDimension+tlblCentersDimension)/2)+7;switch(dimension&0x03){// mod 4
case 0:dimension++;break;// 1? do nothing
case 2:dimension--;break;case 3:throw new NotFoundException('Dimensions could be not found.');}return dimension;}}]);return Detector$2;}();/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*import java.util.List;*/ /*import java.util.Map;*/ /**
* This implementation can detect and decode QR Codes in an image.
*
* @author Sean Owen
*/var QRCodeReader=/*#__PURE__*/function(){function QRCodeReader(){_classCallCheck(this,QRCodeReader);this.decoder=new Decoder$2();}_createClass(QRCodeReader,[{key:"getDecoder",value:function getDecoder(){return this.decoder;}/**
* Locates and decodes a QR code in an image.
*
* @return a representing: string the content encoded by the QR code
* @throws NotFoundException if a QR code cannot be found
* @throws FormatException if a QR code cannot be decoded
* @throws ChecksumException if error correction fails
*/ /*@Override*/ // public decode(image: BinaryBitmap): Result /*throws NotFoundException, ChecksumException, FormatException */ {
// return this.decode(image, null)
// }
/*@Override*/},{key:"decode",value:function decode(image,hints){var decoderResult;var points;if(hints!==undefined&&hints!==null&&undefined!==hints.get(DecodeHintType$1.PURE_BARCODE)){var bits=QRCodeReader.extractPureBits(image.getBlackMatrix());decoderResult=this.decoder.decodeBitMatrix(bits,hints);points=QRCodeReader.NO_POINTS;}else{var detectorResult=new Detector$2(image.getBlackMatrix()).detect(hints);decoderResult=this.decoder.decodeBitMatrix(detectorResult.getBits(),hints);points=detectorResult.getPoints();}// If the code was mirrored: swap the bottom-left and the top-right points.
if(decoderResult.getOther()instanceof QRCodeDecoderMetaData){decoderResult.getOther().applyMirroredCorrection(points);}var result=new Result(decoderResult.getText(),decoderResult.getRawBytes(),undefined,points,BarcodeFormat$1.QR_CODE,undefined);var byteSegments=decoderResult.getByteSegments();if(byteSegments!==null){result.putMetadata(ResultMetadataType$1.BYTE_SEGMENTS,byteSegments);}var ecLevel=decoderResult.getECLevel();if(ecLevel!==null){result.putMetadata(ResultMetadataType$1.ERROR_CORRECTION_LEVEL,ecLevel);}if(decoderResult.hasStructuredAppend()){result.putMetadata(ResultMetadataType$1.STRUCTURED_APPEND_SEQUENCE,decoderResult.getStructuredAppendSequenceNumber());result.putMetadata(ResultMetadataType$1.STRUCTURED_APPEND_PARITY,decoderResult.getStructuredAppendParity());}return result;}/*@Override*/},{key:"reset",value:function reset(){// do nothing
}/**
* This method detects a code in a "pure" image -- that is, pure monochrome image
* which contains only an unrotated, unskewed, image of a code, with some white border
* around it. This is a specialized method that works exceptionally fast in this special
* case.
*
* @see com.google.zxing.datamatrix.DataMatrixReader#extractPureBits(BitMatrix)
*/}],[{key:"extractPureBits",value:function extractPureBits(image){var leftTopBlack=image.getTopLeftOnBit();var rightBottomBlack=image.getBottomRightOnBit();if(leftTopBlack===null||rightBottomBlack===null){throw new NotFoundException();}var moduleSize=this.moduleSize(leftTopBlack,image);var top=leftTopBlack[1];var bottom=rightBottomBlack[1];var left=leftTopBlack[0];var right=rightBottomBlack[0];// Sanity check!
if(left>=right||top>=bottom){throw new NotFoundException();}if(bottom-top!==right-left){// Special case, where bottom-right module wasn't black so we found something else in the last row
// Assume it's a square, so use height as the width
right=left+(bottom-top);if(right>=image.getWidth()){// Abort if that would not make sense -- off image
throw new NotFoundException();}}var matrixWidth=Math.round((right-left+1)/moduleSize);var matrixHeight=Math.round((bottom-top+1)/moduleSize);if(matrixWidth<=0||matrixHeight<=0){throw new NotFoundException();}if(matrixHeight!==matrixWidth){// Only possibly decode square regions
throw new NotFoundException();}// Push in the "border" by half the module width so that we start
// sampling in the middle of the module. Just in case the image is a
// little off, this will help recover.
var nudge=/*(int) */Math.floor(moduleSize/2.0);top+=nudge;left+=nudge;// But careful that this does not sample off the edge
// "right" is the farthest-right valid pixel location -- right+1 is not necessarily
// This is positive by how much the inner x loop below would be too large
var nudgedTooFarRight=left+/*(int) */Math.floor((matrixWidth-1)*moduleSize)-right;if(nudgedTooFarRight>0){if(nudgedTooFarRight>nudge){// Neither way fits; abort
throw new NotFoundException();}left-=nudgedTooFarRight;}// See logic above
var nudgedTooFarDown=top+/*(int) */Math.floor((matrixHeight-1)*moduleSize)-bottom;if(nudgedTooFarDown>0){if(nudgedTooFarDown>nudge){// Neither way fits; abort
throw new NotFoundException();}top-=nudgedTooFarDown;}// Now just read off the bits
var bits=new BitMatrix(matrixWidth,matrixHeight);for(var y=0;y<matrixHeight;y++){var iOffset=top+/*(int) */Math.floor(y*moduleSize);for(var x=0;x<matrixWidth;x++){if(image.get(left+/*(int) */Math.floor(x*moduleSize),iOffset)){bits.set(x,y);}}}return bits;}},{key:"moduleSize",value:function moduleSize(leftTopBlack,image){var height=image.getHeight();var width=image.getWidth();var x=leftTopBlack[0];var y=leftTopBlack[1];var inBlack=true;var transitions=0;while(x<width&&y<height){if(inBlack!==image.get(x,y)){if(++transitions===5){break;}inBlack=!inBlack;}x++;y++;}if(x===width||y===height){throw new NotFoundException();}return(x-leftTopBlack[0])/7.0;}}]);return QRCodeReader;}();QRCodeReader.NO_POINTS=new Array();/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* @author SITA Lab (kevin.osullivan@sita.aero)
* @author Guenther Grau
*/ /*public final*/var PDF417Common=/*#__PURE__*/function(){function PDF417Common(){_classCallCheck(this,PDF417Common);}_createClass(PDF417Common,[{key:"PDF417Common",value:function PDF417Common(){}/**
* @param moduleBitCount values to sum
* @return sum of values
* @deprecated call {@link MathUtils#sum(int[])}
*/ // @Deprecated
}],[{key:"getBitCountSum",value:function getBitCountSum(moduleBitCount){return MathUtils.sum(moduleBitCount);}},{key:"toIntArray",value:function toIntArray(list){if(list==null||!list.length){return PDF417Common.EMPTY_INT_ARRAY;}var result=new Int32Array(list.length);var i=0;var _iterator51=_createForOfIteratorHelper(list),_step51;try{for(_iterator51.s();!(_step51=_iterator51.n()).done;){var integer=_step51.value;result[i++]=integer;}}catch(err){_iterator51.e(err);}finally{_iterator51.f();}return result;}/**
* @param symbol encoded symbol to translate to a codeword
* @return the codeword corresponding to the symbol.
*/},{key:"getCodeword",value:function getCodeword(symbol/*int*/){var i=Arrays.binarySearch(PDF417Common.SYMBOL_TABLE,symbol&0x3FFFF);if(i<0){return-1;}return(PDF417Common.CODEWORD_TABLE[i]-1)%PDF417Common.NUMBER_OF_CODEWORDS;}}]);return PDF417Common;}();PDF417Common.NUMBER_OF_CODEWORDS=929;// Maximum Codewords (Data + Error).
PDF417Common.MAX_CODEWORDS_IN_BARCODE=PDF417Common.NUMBER_OF_CODEWORDS-1;PDF417Common.MIN_ROWS_IN_BARCODE=3;PDF417Common.MAX_ROWS_IN_BARCODE=90;// One left row indication column + max 30 data columns + one right row indicator column
// public static /*final*/ MAX_CODEWORDS_IN_ROW: /*int*/ number = 32;
PDF417Common.MODULES_IN_CODEWORD=17;PDF417Common.MODULES_IN_STOP_PATTERN=18;PDF417Common.BARS_IN_MODULE=8;PDF417Common.EMPTY_INT_ARRAY=new Int32Array([]);/**
* The sorted table of all possible symbols. Extracted from the PDF417
* specification. The index of a symbol in this table corresponds to the
* index into the codeword table.
*/PDF417Common.SYMBOL_TABLE=Int32Array.from([0x1025e,0x1027a,0x1029e,0x102bc,0x102f2,0x102f4,0x1032e,0x1034e,0x1035c,0x10396,0x103a6,0x103ac,0x10422,0x10428,0x10436,0x10442,0x10444,0x10448,0x10450,0x1045e,0x10466,0x1046c,0x1047a,0x10482,0x1049e,0x104a0,0x104bc,0x104c6,0x104d8,0x104ee,0x104f2,0x104f4,0x10504,0x10508,0x10510,0x1051e,0x10520,0x1053c,0x10540,0x10578,0x10586,0x1058c,0x10598,0x105b0,0x105be,0x105ce,0x105dc,0x105e2,0x105e4,0x105e8,0x105f6,0x1062e,0x1064e,0x1065c,0x1068e,0x1069c,0x106b8,0x106de,0x106fa,0x10716,0x10726,0x1072c,0x10746,0x1074c,0x10758,0x1076e,0x10792,0x10794,0x107a2,0x107a4,0x107a8,0x107b6,0x10822,0x10828,0x10842,0x10848,0x10850,0x1085e,0x10866,0x1086c,0x1087a,0x10882,0x10884,0x10890,0x1089e,0x108a0,0x108bc,0x108c6,0x108cc,0x108d8,0x108ee,0x108f2,0x108f4,0x10902,0x10908,0x1091e,0x10920,0x1093c,0x10940,0x10978,0x10986,0x10998,0x109b0,0x109be,0x109ce,0x109dc,0x109e2,0x109e4,0x109e8,0x109f6,0x10a08,0x10a10,0x10a1e,0x10a20,0x10a3c,0x10a40,0x10a78,0x10af0,0x10b06,0x10b0c,0x10b18,0x10b30,0x10b3e,0x10b60,0x10b7c,0x10b8e,0x10b9c,0x10bb8,0x10bc2,0x10bc4,0x10bc8,0x10bd0,0x10bde,0x10be6,0x10bec,0x10c2e,0x10c4e,0x10c5c,0x10c62,0x10c64,0x10c68,0x10c76,0x10c8e,0x10c9c,0x10cb8,0x10cc2,0x10cc4,0x10cc8,0x10cd0,0x10cde,0x10ce6,0x10cec,0x10cfa,0x10d0e,0x10d1c,0x10d38,0x10d70,0x10d7e,0x10d82,0x10d84,0x10d88,0x10d90,0x10d9e,0x10da0,0x10dbc,0x10dc6,0x10dcc,0x10dd8,0x10dee,0x10df2,0x10df4,0x10e16,0x10e26,0x10e2c,0x10e46,0x10e58,0x10e6e,0x10e86,0x10e8c,0x10e98,0x10eb0,0x10ebe,0x10ece,0x10edc,0x10f0a,0x10f12,0x10f14,0x10f22,0x10f28,0x10f36,0x10f42,0x10f44,0x10f48,0x10f50,0x10f5e,0x10f66,0x10f6c,0x10fb2,0x10fb4,0x11022,0x11028,0x11042,0x11048,0x11050,0x1105e,0x1107a,0x11082,0x11084,0x11090,0x1109e,0x110a0,0x110bc,0x110c6,0x110cc,0x110d8,0x110ee,0x110f2,0x110f4,0x11102,0x1111e,0x11120,0x1113c,0x11140,0x11178,0x11186,0x11198,0x111b0,0x111be,0x111ce,0x111dc,0x111e2,0x111e4,0x111e8,0x111f6,0x11208,0x1121e,0x11220,0x11278,0x112f0,0x1130c,0x11330,0x1133e,0x11360,0x1137c,0x1138e,0x1139c,0x113b8,0x113c2,0x113c8,0x113d0,0x113de,0x113e6,0x113ec,0x11408,0x11410,0x1141e,0x11420,0x1143c,0x11440,0x11478,0x114f0,0x115e0,0x1160c,0x11618,0x11630,0x1163e,0x11660,0x1167c,0x116c0,0x116f8,0x1171c,0x11738,0x11770,0x1177e,0x11782,0x11784,0x11788,0x11790,0x1179e,0x117a0,0x117bc,0x117c6,0x117cc,0x117d8,0x117ee,0x1182e,0x11834,0x1184e,0x1185c,0x11862,0x11864,0x11868,0x11876,0x1188e,0x1189c,0x118b8,0x118c2,0x118c8,0x118d0,0x118de,0x118e6,0x118ec,0x118fa,0x1190e,0x1191c,0x11938,0x11970,0x1197e,0x11982,0x11984,0x11990,0x1199e,0x119a0,0x119bc,0x119c6,0x119cc,0x119d8,0x119ee,0x119f2,0x119f4,0x11a0e,0x11a1c,0x11a38,0x11a70,0x11a7e,0x11ae0,0x11afc,0x11b08,0x11b10,0x11b1e,0x11b20,0x11b3c,0x11b40,0x11b78,0x11b8c,0x11b98,0x11bb0,0x11bbe,0x11bce,0x11bdc,0x11be2,0x11be4,0x11be8,0x11bf6,0x11c16,0x11c26,0x11c2c,0x11c46,0x11c4c,0x11c58,0x11c6e,0x11c86,0x11c98,0x11cb0,0x11cbe,0x11cce,0x11cdc,0x11ce2,0x11ce4,0x11ce8,0x11cf6,0x11d06,0x11d0c,0x11d18,0x11d30,0x11d3e,0x11d60,0x11d7c,0x11d8e,0x11d9c,0x11db8,0x11dc4,0x11dc8,0x11dd0,0x11dde,0x11de6,0x11dec,0x11dfa,0x11e0a,0x11e12,0x11e14,0x11e22,0x11e24,0x11e28,0x11e36,0x11e42,0x11e44,0x11e50,0x11e5e,0x11e66,0x11e6c,0x11e82,0x11e84,0x11e88,0x11e90,0x11e9e,0x11ea0,0x11ebc,0x11ec6,0x11ecc,0x11ed8,0x11eee,0x11f1a,0x11f2e,0x11f32,0x11f34,0x11f4e,0x11f5c,0x11f62,0x11f64,0x11f68,0x11f76,0x12048,0x1205e,0x12082,0x12084,0x12090,0x1209e,0x120a0,0x120bc,0x120d8,0x120f2,0x120f4,0x12108,0x1211e,0x12120,0x1213c,0x12140,0x12178,0x12186,0x12198,0x121b0,0x121be,0x121e2,0x121e4,0x121e8,0x121f6,0x12204,0x12210,0x1221e,0x12220,0x12278,0x122f0,0x12306,0x1230c,0x12330,0x1233e,0x12360,0x1237c,0x1238e,0x1239c,0x123b8,0x123c2,0x123c8,0x123d0,0x123e6,0x123ec,0x1241e,0x12420,0x1243c,0x124f0,0x125e0,0x12618,0x1263e,0x12660,0x1267c,0x126c0,0x126f8,0x12738,0x12770,0x1277e,0x12782,0x12784,0x12790,0x1279e,0x127a0,0x127bc,0x127c6,0x127cc,0x127d8,0x127ee,0x12820,0x1283c,0x12840,0x12878,0x128f0,0x129e0,0x12bc0,0x12c18,0x12c30,0x12c3e,0x12c60,0x12c7c,0x12cc0,0x12cf8,0x12df0,0x12e1c,0x12e38,0x12e70,0x12e7e,0x12ee0,0x12efc,0x12f04,0x12f08,0x12f10,0x12f20,0x12f3c,0x12f40,0x12f78,0x12f86,0x12f8c,0x12f98,0x12fb0,0x12fbe,0x12fce,0x12fdc,0x1302e,0x1304e,0x1305c,0x13062,0x13068,0x1308e,0x1309c,0x130b8,0x130c2,0x130c8,0x130d0,0x130de,0x130ec,0x130fa,0x1310e,0x13138,0x13170,0x1317e,0x13182,0x13184,0x13190,0x1319e,0x131a0,0x131bc,0x131c6,0x131cc,0x131d8,0x131f2,0x131f4,0x1320e,0x1321c,0x13270,0x1327e,0x132e0,0x132fc,0x13308,0x1331e,0x13320,0x1333c,0x13340,0x13378,0x13386,0x13398,0x133b0,0x133be,0x133ce,0x133dc,0x133e2,0x133e4,0x133e8,0x133f6,0x1340e,0x1341c,0x13438,0x13470,0x1347e,0x134e0,0x134fc,0x135c0,0x135f8,0x13608,0x13610,0x1361e,0x13620,0x1363c,0x13640,0x13678,0x136f0,0x1370c,0x13718,0x13730,0x1373e,0x13760,0x1377c,0x1379c,0x137b8,0x137c2,0x137c4,0x137c8,0x137d0,0x137de,0x137e6,0x137ec,0x13816,0x13826,0x1382c,0x13846,0x1384c,0x13858,0x1386e,0x13874,0x13886,0x13898,0x138b0,0x138be,0x138ce,0x138dc,0x138e2,0x138e4,0x138e8,0x13906,0x1390c,0x13930,0x1393e,0x13960,0x1397c,0x1398e,0x1399c,0x139b8,0x139c8,0x139d0,0x139de,0x139e6,0x139ec,0x139fa,0x13a06,0x13a0c,0x13a18,0x13a30,0x13a3e,0x13a60,0x13a7c,0x13ac0,0x13af8,0x13b0e,0x13b1c,0x13b38,0x13b70,0x13b7e,0x13b88,0x13b90,0x13b9e,0x13ba0,0x13bbc,0x13bcc,0x13bd8,0x13bee,0x13bf2,0x13bf4,0x13c12,0x13c14,0x13c22,0x13c24,0x13c28,0x13c36,0x13c42,0x13c48,0x13c50,0x13c5e,0x13c66,0x13c6c,0x13c82,0x13c84,0x13c90,0x13c9e,0x13ca0,0x13cbc,0x13cc6,0x13ccc,0x13cd8,0x13cee,0x13d02,0x13d04,0x13d08,0x13d10,0x13d1e,0x13d20,0x13d3c,0x13d40,0x13d78,0x13d86,0x13d8c,0x13d98,0x13db0,0x13dbe,0x13dce,0x13ddc,0x13de4,0x13de8,0x13df6,0x13e1a,0x13e2e,0x13e32,0x13e34,0x13e4e,0x13e5c,0x13e62,0x13e64,0x13e68,0x13e76,0x13e8e,0x13e9c,0x13eb8,0x13ec2,0x13ec4,0x13ec8,0x13ed0,0x13ede,0x13ee6,0x13eec,0x13f26,0x13f2c,0x13f3a,0x13f46,0x13f4c,0x13f58,0x13f6e,0x13f72,0x13f74,0x14082,0x1409e,0x140a0,0x140bc,0x14104,0x14108,0x14110,0x1411e,0x14120,0x1413c,0x14140,0x14178,0x1418c,0x14198,0x141b0,0x141be,0x141e2,0x141e4,0x141e8,0x14208,0x14210,0x1421e,0x14220,0x1423c,0x14240,0x14278,0x142f0,0x14306,0x1430c,0x14318,0x14330,0x1433e,0x14360,0x1437c,0x1438e,0x143c2,0x143c4,0x143c8,0x143d0,0x143e6,0x143ec,0x14408,0x14410,0x1441e,0x14420,0x1443c,0x14440,0x14478,0x144f0,0x145e0,0x1460c,0x14618,0x14630,0x1463e,0x14660,0x1467c,0x146c0,0x146f8,0x1471c,0x14738,0x14770,0x1477e,0x14782,0x14784,0x14788,0x14790,0x147a0,0x147bc,0x147c6,0x147cc,0x147d8,0x147ee,0x14810,0x14820,0x1483c,0x14840,0x14878,0x148f0,0x149e0,0x14bc0,0x14c30,0x14c3e,0x14c60,0x14c7c,0x14cc0,0x14cf8,0x14df0,0x14e38,0x14e70,0x14e7e,0x14ee0,0x14efc,0x14f04,0x14f08,0x14f10,0x14f1e,0x14f20,0x14f3c,0x14f40,0x14f78,0x14f86,0x14f8c,0x14f98,0x14fb0,0x14fce,0x14fdc,0x15020,0x15040,0x15078,0x150f0,0x151e0,0x153c0,0x15860,0x1587c,0x158c0,0x158f8,0x159f0,0x15be0,0x15c70,0x15c7e,0x15ce0,0x15cfc,0x15dc0,0x15df8,0x15e08,0x15e10,0x15e20,0x15e40,0x15e78,0x15ef0,0x15f0c,0x15f18,0x15f30,0x15f60,0x15f7c,0x15f8e,0x15f9c,0x15fb8,0x1604e,0x1605c,0x1608e,0x1609c,0x160b8,0x160c2,0x160c4,0x160c8,0x160de,0x1610e,0x1611c,0x16138,0x16170,0x1617e,0x16184,0x16188,0x16190,0x1619e,0x161a0,0x161bc,0x161c6,0x161cc,0x161d8,0x161f2,0x161f4,0x1620e,0x1621c,0x16238,0x16270,0x1627e,0x162e0,0x162fc,0x16304,0x16308,0x16310,0x1631e,0x16320,0x1633c,0x16340,0x16378,0x16386,0x1638c,0x16398,0x163b0,0x163be,0x163ce,0x163dc,0x163e2,0x163e4,0x163e8,0x163f6,0x1640e,0x1641c,0x16438,0x16470,0x1647e,0x164e0,0x164fc,0x165c0,0x165f8,0x16610,0x1661e,0x16620,0x1663c,0x16640,0x16678,0x166f0,0x16718,0x16730,0x1673e,0x16760,0x1677c,0x1678e,0x1679c,0x167b8,0x167c2,0x167c4,0x167c8,0x167d0,0x167de,0x167e6,0x167ec,0x1681c,0x16838,0x16870,0x168e0,0x168fc,0x169c0,0x169f8,0x16bf0,0x16c10,0x16c1e,0x16c20,0x16c3c,0x16c40,0x16c78,0x16cf0,0x16de0,0x16e18,0x16e30,0x16e3e,0x16e60,0x16e7c,0x16ec0,0x16ef8,0x16f1c,0x16f38,0x16f70,0x16f7e,0x16f84,0x16f88,0x16f90,0x16f9e,0x16fa0,0x16fbc,0x16fc6,0x16fcc,0x16fd8,0x17026,0x1702c,0x17046,0x1704c,0x17058,0x1706e,0x17086,0x1708c,0x17098,0x170b0,0x170be,0x170ce,0x170dc,0x170e8,0x17106,0x1710c,0x17118,0x17130,0x1713e,0x17160,0x1717c,0x1718e,0x1719c,0x171b8,0x171c2,0x171c4,0x171c8,0x171d0,0x171de,0x171e6,0x171ec,0x171fa,0x17206,0x1720c,0x17218,0x17230,0x1723e,0x17260,0x1727c,0x172c0,0x172f8,0x1730e,0x1731c,0x17338,0x17370,0x1737e,0x17388,0x17390,0x1739e,0x173a0,0x173bc,0x173cc,0x173d8,0x173ee,0x173f2,0x173f4,0x1740c,0x17418,0x17430,0x1743e,0x17460,0x1747c,0x174c0,0x174f8,0x175f0,0x1760e,0x1761c,0x17638,0x17670,0x1767e,0x176e0,0x176fc,0x17708,0x17710,0x1771e,0x17720,0x1773c,0x17740,0x17778,0x17798,0x177b0,0x177be,0x177dc,0x177e2,0x177e4,0x177e8,0x17822,0x17824,0x17828,0x17836,0x17842,0x17844,0x17848,0x17850,0x1785e,0x17866,0x1786c,0x17882,0x17884,0x17888,0x17890,0x1789e,0x178a0,0x178bc,0x178c6,0x178cc,0x178d8,0x178ee,0x178f2,0x178f4,0x17902,0x17904,0x17908,0x17910,0x1791e,0x17920,0x1793c,0x17940,0x17978,0x17986,0x1798c,0x17998,0x179b0,0x179be,0x179ce,0x179dc,0x179e2,0x179e4,0x179e8,0x179f6,0x17a04,0x17a08,0x17a10,0x17a1e,0x17a20,0x17a3c,0x17a40,0x17a78,0x17af0,0x17b06,0x17b0c,0x17b18,0x17b30,0x17b3e,0x17b60,0x17b7c,0x17b8e,0x17b9c,0x17bb8,0x17bc4,0x17bc8,0x17bd0,0x17bde,0x17be6,0x17bec,0x17c2e,0x17c32,0x17c34,0x17c4e,0x17c5c,0x17c62,0x17c64,0x17c68,0x17c76,0x17c8e,0x17c9c,0x17cb8,0x17cc2,0x17cc4,0x17cc8,0x17cd0,0x17cde,0x17ce6,0x17cec,0x17d0e,0x17d1c,0x17d38,0x17d70,0x17d82,0x17d84,0x17d88,0x17d90,0x17d9e,0x17da0,0x17dbc,0x17dc6,0x17dcc,0x17dd8,0x17dee,0x17e26,0x17e2c,0x17e3a,0x17e46,0x17e4c,0x17e58,0x17e6e,0x17e72,0x17e74,0x17e86,0x17e8c,0x17e98,0x17eb0,0x17ece,0x17edc,0x17ee2,0x17ee4,0x17ee8,0x17ef6,0x1813a,0x18172,0x18174,0x18216,0x18226,0x1823a,0x1824c,0x18258,0x1826e,0x18272,0x18274,0x18298,0x182be,0x182e2,0x182e4,0x182e8,0x182f6,0x1835e,0x1837a,0x183ae,0x183d6,0x18416,0x18426,0x1842c,0x1843a,0x18446,0x18458,0x1846e,0x18472,0x18474,0x18486,0x184b0,0x184be,0x184ce,0x184dc,0x184e2,0x184e4,0x184e8,0x184f6,0x18506,0x1850c,0x18518,0x18530,0x1853e,0x18560,0x1857c,0x1858e,0x1859c,0x185b8,0x185c2,0x185c4,0x185c8,0x185d0,0x185de,0x185e6,0x185ec,0x185fa,0x18612,0x18614,0x18622,0x18628,0x18636,0x18642,0x18650,0x1865e,0x1867a,0x18682,0x18684,0x18688,0x18690,0x1869e,0x186a0,0x186bc,0x186c6,0x186cc,0x186d8,0x186ee,0x186f2,0x186f4,0x1872e,0x1874e,0x1875c,0x18796,0x187a6,0x187ac,0x187d2,0x187d4,0x18826,0x1882c,0x1883a,0x18846,0x1884c,0x18858,0x1886e,0x18872,0x18874,0x18886,0x18898,0x188b0,0x188be,0x188ce,0x188dc,0x188e2,0x188e4,0x188e8,0x188f6,0x1890c,0x18930,0x1893e,0x18960,0x1897c,0x1898e,0x189b8,0x189c2,0x189c8,0x189d0,0x189de,0x189e6,0x189ec,0x189fa,0x18a18,0x18a30,0x18a3e,0x18a60,0x18a7c,0x18ac0,0x18af8,0x18b1c,0x18b38,0x18b70,0x18b7e,0x18b82,0x18b84,0x18b88,0x18b90,0x18b9e,0x18ba0,0x18bbc,0x18bc6,0x18bcc,0x18bd8,0x18bee,0x18bf2,0x18bf4,0x18c22,0x18c24,0x18c28,0x18c36,0x18c42,0x18c48,0x18c50,0x18c5e,0x18c66,0x18c7a,0x18c82,0x18c84,0x18c90,0x18c9e,0x18ca0,0x18cbc,0x18ccc,0x18cf2,0x18cf4,0x18d04,0x18d08,0x18d10,0x18d1e,0x18d20,0x18d3c,0x18d40,0x18d78,0x18d86,0x18d98,0x18dce,0x18de2,0x18de4,0x18de8,0x18e2e,0x18e32,0x18e34,0x18e4e,0x18e5c,0x18e62,0x18e64,0x18e68,0x18e8e,0x18e9c,0x18eb8,0x18ec2,0x18ec4,0x18ec8,0x18ed0,0x18efa,0x18f16,0x18f26,0x18f2c,0x18f46,0x18f4c,0x18f58,0x18f6e,0x18f8a,0x18f92,0x18f94,0x18fa2,0x18fa4,0x18fa8,0x18fb6,0x1902c,0x1903a,0x19046,0x1904c,0x19058,0x19072,0x19074,0x19086,0x19098,0x190b0,0x190be,0x190ce,0x190dc,0x190e2,0x190e8,0x190f6,0x19106,0x1910c,0x19130,0x1913e,0x19160,0x1917c,0x1918e,0x1919c,0x191b8,0x191c2,0x191c8,0x191d0,0x191de,0x191e6,0x191ec,0x191fa,0x19218,0x1923e,0x19260,0x1927c,0x192c0,0x192f8,0x19338,0x19370,0x1937e,0x19382,0x19384,0x19390,0x1939e,0x193a0,0x193bc,0x193c6,0x193cc,0x193d8,0x193ee,0x193f2,0x193f4,0x19430,0x1943e,0x19460,0x1947c,0x194c0,0x194f8,0x195f0,0x19638,0x19670,0x1967e,0x196e0,0x196fc,0x19702,0x19704,0x19708,0x19710,0x19720,0x1973c,0x19740,0x19778,0x19786,0x1978c,0x19798,0x197b0,0x197be,0x197ce,0x197dc,0x197e2,0x197e4,0x197e8,0x19822,0x19824,0x19842,0x19848,0x19850,0x1985e,0x19866,0x1987a,0x19882,0x19884,0x19890,0x1989e,0x198a0,0x198bc,0x198cc,0x198f2,0x198f4,0x19902,0x19908,0x1991e,0x19920,0x1993c,0x19940,0x19978,0x19986,0x19998,0x199ce,0x199e2,0x199e4,0x199e8,0x19a08,0x19a10,0x19a1e,0x19a20,0x19a3c,0x19a40,0x19a78,0x19af0,0x19b18,0x19b3e,0x19b60,0x19b9c,0x19bc2,0x19bc4,0x19bc8,0x19bd0,0x19be6,0x19c2e,0x19c34,0x19c4e,0x19c5c,0x19c62,0x19c64,0x19c68,0x19c8e,0x19c9c,0x19cb8,0x19cc2,0x19cc8,0x19cd0,0x19ce6,0x19cfa,0x19d0e,0x19d1c,0x19d38,0x19d70,0x19d7e,0x19d82,0x19d84,0x19d88,0x19d90,0x19da0,0x19dcc,0x19df2,0x19df4,0x19e16,0x19e26,0x19e2c,0x19e46,0x19e4c,0x19e58,0x19e74,0x19e86,0x19e8c,0x19e98,0x19eb0,0x19ebe,0x19ece,0x19ee2,0x19ee4,0x19ee8,0x19f0a,0x19f12,0x19f14,0x19f22,0x19f24,0x19f28,0x19f42,0x19f44,0x19f48,0x19f50,0x19f5e,0x19f6c,0x19f9a,0x19fae,0x19fb2,0x19fb4,0x1a046,0x1a04c,0x1a072,0x1a074,0x1a086,0x1a08c,0x1a098,0x1a0b0,0x1a0be,0x1a0e2,0x1a0e4,0x1a0e8,0x1a0f6,0x1a106,0x1a10c,0x1a118,0x1a130,0x1a13e,0x1a160,0x1a17c,0x1a18e,0x1a19c,0x1a1b8,0x1a1c2,0x1a1c4,0x1a1c8,0x1a1d0,0x1a1de,0x1a1e6,0x1a1ec,0x1a218,0x1a230,0x1a23e,0x1a260,0x1a27c,0x1a2c0,0x1a2f8,0x1a31c,0x1a338,0x1a370,0x1a37e,0x1a382,0x1a384,0x1a388,0x1a390,0x1a39e,0x1a3a0,0x1a3bc,0x1a3c6,0x1a3cc,0x1a3d8,0x1a3ee,0x1a3f2,0x1a3f4,0x1a418,0x1a430,0x1a43e,0x1a460,0x1a47c,0x1a4c0,0x1a4f8,0x1a5f0,0x1a61c,0x1a638,0x1a670,0x1a67e,0x1a6e0,0x1a6fc,0x1a702,0x1a704,0x1a708,0x1a710,0x1a71e,0x1a720,0x1a73c,0x1a740,0x1a778,0x1a786,0x1a78c,0x1a798,0x1a7b0,0x1a7be,0x1a7ce,0x1a7dc,0x1a7e2,0x1a7e4,0x1a7e8,0x1a830,0x1a860,0x1a87c,0x1a8c0,0x1a8f8,0x1a9f0,0x1abe0,0x1ac70,0x1ac7e,0x1ace0,0x1acfc,0x1adc0,0x1adf8,0x1ae04,0x1ae08,0x1ae10,0x1ae20,0x1ae3c,0x1ae40,0x1ae78,0x1aef0,0x1af06,0x1af0c,0x1af18,0x1af30,0x1af3e,0x1af60,0x1af7c,0x1af8e,0x1af9c,0x1afb8,0x1afc4,0x1afc8,0x1afd0,0x1afde,0x1b042,0x1b05e,0x1b07a,0x1b082,0x1b084,0x1b088,0x1b090,0x1b09e,0x1b0a0,0x1b0bc,0x1b0cc,0x1b0f2,0x1b0f4,0x1b102,0x1b104,0x1b108,0x1b110,0x1b11e,0x1b120,0x1b13c,0x1b140,0x1b178,0x1b186,0x1b198,0x1b1ce,0x1b1e2,0x1b1e4,0x1b1e8,0x1b204,0x1b208,0x1b210,0x1b21e,0x1b220,0x1b23c,0x1b240,0x1b278,0x1b2f0,0x1b30c,0x1b33e,0x1b360,0x1b39c,0x1b3c2,0x1b3c4,0x1b3c8,0x1b3d0,0x1b3e6,0x1b410,0x1b41e,0x1b420,0x1b43c,0x1b440,0x1b478,0x1b4f0,0x1b5e0,0x1b618,0x1b660,0x1b67c,0x1b6c0,0x1b738,0x1b782,0x1b784,0x1b788,0x1b790,0x1b79e,0x1b7a0,0x1b7cc,0x1b82e,0x1b84e,0x1b85c,0x1b88e,0x1b89c,0x1b8b8,0x1b8c2,0x1b8c4,0x1b8c8,0x1b8d0,0x1b8e6,0x1b8fa,0x1b90e,0x1b91c,0x1b938,0x1b970,0x1b97e,0x1b982,0x1b984,0x1b988,0x1b990,0x1b99e,0x1b9a0,0x1b9cc,0x1b9f2,0x1b9f4,0x1ba0e,0x1ba1c,0x1ba38,0x1ba70,0x1ba7e,0x1bae0,0x1bafc,0x1bb08,0x1bb10,0x1bb20,0x1bb3c,0x1bb40,0x1bb98,0x1bbce,0x1bbe2,0x1bbe4,0x1bbe8,0x1bc16,0x1bc26,0x1bc2c,0x1bc46,0x1bc4c,0x1bc58,0x1bc72,0x1bc74,0x1bc86,0x1bc8c,0x1bc98,0x1bcb0,0x1bcbe,0x1bcce,0x1bce2,0x1bce4,0x1bce8,0x1bd06,0x1bd0c,0x1bd18,0x1bd30,0x1bd3e,0x1bd60,0x1bd7c,0x1bd9c,0x1bdc2,0x1bdc4,0x1bdc8,0x1bdd0,0x1bde6,0x1bdfa,0x1be12,0x1be14,0x1be22,0x1be24,0x1be28,0x1be42,0x1be44,0x1be48,0x1be50,0x1be5e,0x1be66,0x1be82,0x1be84,0x1be88,0x1be90,0x1be9e,0x1bea0,0x1bebc,0x1becc,0x1bef4,0x1bf1a,0x1bf2e,0x1bf32,0x1bf34,0x1bf4e,0x1bf5c,0x1bf62,0x1bf64,0x1bf68,0x1c09a,0x1c0b2,0x1c0b4,0x1c11a,0x1c132,0x1c134,0x1c162,0x1c164,0x1c168,0x1c176,0x1c1ba,0x1c21a,0x1c232,0x1c234,0x1c24e,0x1c25c,0x1c262,0x1c264,0x1c268,0x1c276,0x1c28e,0x1c2c2,0x1c2c4,0x1c2c8,0x1c2d0,0x1c2de,0x1c2e6,0x1c2ec,0x1c2fa,0x1c316,0x1c326,0x1c33a,0x1c346,0x1c34c,0x1c372,0x1c374,0x1c41a,0x1c42e,0x1c432,0x1c434,0x1c44e,0x1c45c,0x1c462,0x1c464,0x1c468,0x1c476,0x1c48e,0x1c49c,0x1c4b8,0x1c4c2,0x1c4c8,0x1c4d0,0x1c4de,0x1c4e6,0x1c4ec,0x1c4fa,0x1c51c,0x1c538,0x1c570,0x1c57e,0x1c582,0x1c584,0x1c588,0x1c590,0x1c59e,0x1c5a0,0x1c5bc,0x1c5c6,0x1c5cc,0x1c5d8,0x1c5ee,0x1c5f2,0x1c5f4,0x1c616,0x1c626,0x1c62c,0x1c63a,0x1c646,0x1c64c,0x1c658,0x1c66e,0x1c672,0x1c674,0x1c686,0x1c68c,0x1c698,0x1c6b0,0x1c6be,0x1c6ce,0x1c6dc,0x1c6e2,0x1c6e4,0x1c6e8,0x1c712,0x1c714,0x1c722,0x1c728,0x1c736,0x1c742,0x1c744,0x1c748,0x1c750,0x1c75e,0x1c766,0x1c76c,0x1c77a,0x1c7ae,0x1c7d6,0x1c7ea,0x1c81a,0x1c82e,0x1c832,0x1c834,0x1c84e,0x1c85c,0x1c862,0x1c864,0x1c868,0x1c876,0x1c88e,0x1c89c,0x1c8b8,0x1c8c2,0x1c8c8,0x1c8d0,0x1c8de,0x1c8e6,0x1c8ec,0x1c8fa,0x1c90e,0x1c938,0x1c970,0x1c97e,0x1c982,0x1c984,0x1c990,0x1c99e,0x1c9a0,0x1c9bc,0x1c9c6,0x1c9cc,0x1c9d8,0x1c9ee,0x1c9f2,0x1c9f4,0x1ca38,0x1ca70,0x1ca7e,0x1cae0,0x1cafc,0x1cb02,0x1cb04,0x1cb08,0x1cb10,0x1cb20,0x1cb3c,0x1cb40,0x1cb78,0x1cb86,0x1cb8c,0x1cb98,0x1cbb0,0x1cbbe,0x1cbce,0x1cbdc,0x1cbe2,0x1cbe4,0x1cbe8,0x1cbf6,0x1cc16,0x1cc26,0x1cc2c,0x1cc3a,0x1cc46,0x1cc58,0x1cc72,0x1cc74,0x1cc86,0x1ccb0,0x1ccbe,0x1ccce,0x1cce2,0x1cce4,0x1cce8,0x1cd06,0x1cd0c,0x1cd18,0x1cd30,0x1cd3e,0x1cd60,0x1cd7c,0x1cd9c,0x1cdc2,0x1cdc4,0x1cdc8,0x1cdd0,0x1cdde,0x1cde6,0x1cdfa,0x1ce22,0x1ce28,0x1ce42,0x1ce50,0x1ce5e,0x1ce66,0x1ce7a,0x1ce82,0x1ce84,0x1ce88,0x1ce90,0x1ce9e,0x1cea0,0x1cebc,0x1cecc,0x1cef2,0x1cef4,0x1cf2e,0x1cf32,0x1cf34,0x1cf4e,0x1cf5c,0x1cf62,0x1cf64,0x1cf68,0x1cf96,0x1cfa6,0x1cfac,0x1cfca,0x1cfd2,0x1cfd4,0x1d02e,0x1d032,0x1d034,0x1d04e,0x1d05c,0x1d062,0x1d064,0x1d068,0x1d076,0x1d08e,0x1d09c,0x1d0b8,0x1d0c2,0x1d0c4,0x1d0c8,0x1d0d0,0x1d0de,0x1d0e6,0x1d0ec,0x1d0fa,0x1d11c,0x1d138,0x1d170,0x1d17e,0x1d182,0x1d184,0x1d188,0x1d190,0x1d19e,0x1d1a0,0x1d1bc,0x1d1c6,0x1d1cc,0x1d1d8,0x1d1ee,0x1d1f2,0x1d1f4,0x1d21c,0x1d238,0x1d270,0x1d27e,0x1d2e0,0x1d2fc,0x1d302,0x1d304,0x1d308,0x1d310,0x1d31e,0x1d320,0x1d33c,0x1d340,0x1d378,0x1d386,0x1d38c,0x1d398,0x1d3b0,0x1d3be,0x1d3ce,0x1d3dc,0x1d3e2,0x1d3e4,0x1d3e8,0x1d3f6,0x1d470,0x1d47e,0x1d4e0,0x1d4fc,0x1d5c0,0x1d5f8,0x1d604,0x1d608,0x1d610,0x1d620,0x1d640,0x1d678,0x1d6f0,0x1d706,0x1d70c,0x1d718,0x1d730,0x1d73e,0x1d760,0x1d77c,0x1d78e,0x1d79c,0x1d7b8,0x1d7c2,0x1d7c4,0x1d7c8,0x1d7d0,0x1d7de,0x1d7e6,0x1d7ec,0x1d826,0x1d82c,0x1d83a,0x1d846,0x1d84c,0x1d858,0x1d872,0x1d874,0x1d886,0x1d88c,0x1d898,0x1d8b0,0x1d8be,0x1d8ce,0x1d8e2,0x1d8e4,0x1d8e8,0x1d8f6,0x1d90c,0x1d918,0x1d930,0x1d93e,0x1d960,0x1d97c,0x1d99c,0x1d9c2,0x1d9c4,0x1d9c8,0x1d9d0,0x1d9e6,0x1d9fa,0x1da0c,0x1da18,0x1da30,0x1da3e,0x1da60,0x1da7c,0x1dac0,0x1daf8,0x1db38,0x1db82,0x1db84,0x1db88,0x1db90,0x1db9e,0x1dba0,0x1dbcc,0x1dbf2,0x1dbf4,0x1dc22,0x1dc42,0x1dc44,0x1dc48,0x1dc50,0x1dc5e,0x1dc66,0x1dc7a,0x1dc82,0x1dc84,0x1dc88,0x1dc90,0x1dc9e,0x1dca0,0x1dcbc,0x1dccc,0x1dcf2,0x1dcf4,0x1dd04,0x1dd08,0x1dd10,0x1dd1e,0x1dd20,0x1dd3c,0x1dd40,0x1dd78,0x1dd86,0x1dd98,0x1ddce,0x1dde2,0x1dde4,0x1dde8,0x1de2e,0x1de32,0x1de34,0x1de4e,0x1de5c,0x1de62,0x1de64,0x1de68,0x1de8e,0x1de9c,0x1deb8,0x1dec2,0x1dec4,0x1dec8,0x1ded0,0x1dee6,0x1defa,0x1df16,0x1df26,0x1df2c,0x1df46,0x1df4c,0x1df58,0x1df72,0x1df74,0x1df8a,0x1df92,0x1df94,0x1dfa2,0x1dfa4,0x1dfa8,0x1e08a,0x1e092,0x1e094,0x1e0a2,0x1e0a4,0x1e0a8,0x1e0b6,0x1e0da,0x1e10a,0x1e112,0x1e114,0x1e122,0x1e124,0x1e128,0x1e136,0x1e142,0x1e144,0x1e148,0x1e150,0x1e166,0x1e16c,0x1e17a,0x1e19a,0x1e1b2,0x1e1b4,0x1e20a,0x1e212,0x1e214,0x1e222,0x1e224,0x1e228,0x1e236,0x1e242,0x1e248,0x1e250,0x1e25e,0x1e266,0x1e26c,0x1e27a,0x1e282,0x1e284,0x1e288,0x1e290,0x1e2a0,0x1e2bc,0x1e2c6,0x1e2cc,0x1e2d8,0x1e2ee,0x1e2f2,0x1e2f4,0x1e31a,0x1e332,0x1e334,0x1e35c,0x1e362,0x1e364,0x1e368,0x1e3ba,0x1e40a,0x1e412,0x1e414,0x1e422,0x1e428,0x1e436,0x1e442,0x1e448,0x1e450,0x1e45e,0x1e466,0x1e46c,0x1e47a,0x1e482,0x1e484,0x1e490,0x1e49e,0x1e4a0,0x1e4bc,0x1e4c6,0x1e4cc,0x1e4d8,0x1e4ee,0x1e4f2,0x1e4f4,0x1e502,0x1e504,0x1e508,0x1e510,0x1e51e,0x1e520,0x1e53c,0x1e540,0x1e578,0x1e586,0x1e58c,0x1e598,0x1e5b0,0x1e5be,0x1e5ce,0x1e5dc,0x1e5e2,0x1e5e4,0x1e5e8,0x1e5f6,0x1e61a,0x1e62e,0x1e632,0x1e634,0x1e64e,0x1e65c,0x1e662,0x1e668,0x1e68e,0x1e69c,0x1e6b8,0x1e6c2,0x1e6c4,0x1e6c8,0x1e6d0,0x1e6e6,0x1e6fa,0x1e716,0x1e726,0x1e72c,0x1e73a,0x1e746,0x1e74c,0x1e758,0x1e772,0x1e774,0x1e792,0x1e794,0x1e7a2,0x1e7a4,0x1e7a8,0x1e7b6,0x1e812,0x1e814,0x1e822,0x1e824,0x1e828,0x1e836,0x1e842,0x1e844,0x1e848,0x1e850,0x1e85e,0x1e866,0x1e86c,0x1e87a,0x1e882,0x1e884,0x1e888,0x1e890,0x1e89e,0x1e8a0,0x1e8bc,0x1e8c6,0x1e8cc,0x1e8d8,0x1e8ee,0x1e8f2,0x1e8f4,0x1e902,0x1e904,0x1e908,0x1e910,0x1e920,0x1e93c,0x1e940,0x1e978,0x1e986,0x1e98c,0x1e998,0x1e9b0,0x1e9be,0x1e9ce,0x1e9dc,0x1e9e2,0x1e9e4,0x1e9e8,0x1e9f6,0x1ea04,0x1ea08,0x1ea10,0x1ea20,0x1ea40,0x1ea78,0x1eaf0,0x1eb06,0x1eb0c,0x1eb18,0x1eb30,0x1eb3e,0x1eb60,0x1eb7c,0x1eb8e,0x1eb9c,0x1ebb8,0x1ebc2,0x1ebc4,0x1ebc8,0x1ebd0,0x1ebde,0x1ebe6,0x1ebec,0x1ec1a,0x1ec2e,0x1ec32,0x1ec34,0x1ec4e,0x1ec5c,0x1ec62,0x1ec64,0x1ec68,0x1ec8e,0x1ec9c,0x1ecb8,0x1ecc2,0x1ecc4,0x1ecc8,0x1ecd0,0x1ece6,0x1ecfa,0x1ed0e,0x1ed1c,0x1ed38,0x1ed70,0x1ed7e,0x1ed82,0x1ed84,0x1ed88,0x1ed90,0x1ed9e,0x1eda0,0x1edcc,0x1edf2,0x1edf4,0x1ee16,0x1ee26,0x1ee2c,0x1ee3a,0x1ee46,0x1ee4c,0x1ee58,0x1ee6e,0x1ee72,0x1ee74,0x1ee86,0x1ee8c,0x1ee98,0x1eeb0,0x1eebe,0x1eece,0x1eedc,0x1eee2,0x1eee4,0x1eee8,0x1ef12,0x1ef22,0x1ef24,0x1ef28,0x1ef36,0x1ef42,0x1ef44,0x1ef48,0x1ef50,0x1ef5e,0x1ef66,0x1ef6c,0x1ef7a,0x1efae,0x1efb2,0x1efb4,0x1efd6,0x1f096,0x1f0a6,0x1f0ac,0x1f0ba,0x1f0ca,0x1f0d2,0x1f0d4,0x1f116,0x1f126,0x1f12c,0x1f13a,0x1f146,0x1f14c,0x1f158,0x1f16e,0x1f172,0x1f174,0x1f18a,0x1f192,0x1f194,0x1f1a2,0x1f1a4,0x1f1a8,0x1f1da,0x1f216,0x1f226,0x1f22c,0x1f23a,0x1f246,0x1f258,0x1f26e,0x1f272,0x1f274,0x1f286,0x1f28c,0x1f298,0x1f2b0,0x1f2be,0x1f2ce,0x1f2dc,0x1f2e2,0x1f2e4,0x1f2e8,0x1f2f6,0x1f30a,0x1f312,0x1f314,0x1f322,0x1f328,0x1f342,0x1f344,0x1f348,0x1f350,0x1f35e,0x1f366,0x1f37a,0x1f39a,0x1f3ae,0x1f3b2,0x1f3b4,0x1f416,0x1f426,0x1f42c,0x1f43a,0x1f446,0x1f44c,0x1f458,0x1f46e,0x1f472,0x1f474,0x1f486,0x1f48c,0x1f498,0x1f4b0,0x1f4be,0x1f4ce,0x1f4dc,0x1f4e2,0x1f4e4,0x1f4e8,0x1f4f6,0x1f506,0x1f50c,0x1f518,0x1f530,0x1f53e,0x1f560,0x1f57c,0x1f58e,0x1f59c,0x1f5b8,0x1f5c2,0x1f5c4,0x1f5c8,0x1f5d0,0x1f5de,0x1f5e6,0x1f5ec,0x1f5fa,0x1f60a,0x1f612,0x1f614,0x1f622,0x1f624,0x1f628,0x1f636,0x1f642,0x1f644,0x1f648,0x1f650,0x1f65e,0x1f666,0x1f67a,0x1f682,0x1f684,0x1f688,0x1f690,0x1f69e,0x1f6a0,0x1f6bc,0x1f6cc,0x1f6f2,0x1f6f4,0x1f71a,0x1f72e,0x1f732,0x1f734,0x1f74e,0x1f75c,0x1f762,0x1f764,0x1f768,0x1f776,0x1f796,0x1f7a6,0x1f7ac,0x1f7ba,0x1f7d2,0x1f7d4,0x1f89a,0x1f8ae,0x1f8b2,0x1f8b4,0x1f8d6,0x1f8ea,0x1f91a,0x1f92e,0x1f932,0x1f934,0x1f94e,0x1f95c,0x1f962,0x1f964,0x1f968,0x1f976,0x1f996,0x1f9a6,0x1f9ac,0x1f9ba,0x1f9ca,0x1f9d2,0x1f9d4,0x1fa1a,0x1fa2e,0x1fa32,0x1fa34,0x1fa4e,0x1fa5c,0x1fa62,0x1fa64,0x1fa68,0x1fa76,0x1fa8e,0x1fa9c,0x1fab8,0x1fac2,0x1fac4,0x1fac8,0x1fad0,0x1fade,0x1fae6,0x1faec,0x1fb16,0x1fb26,0x1fb2c,0x1fb3a,0x1fb46,0x1fb4c,0x1fb58,0x1fb6e,0x1fb72,0x1fb74,0x1fb8a,0x1fb92,0x1fb94,0x1fba2,0x1fba4,0x1fba8,0x1fbb6,0x1fbda]);/**
* This table contains to codewords for all symbols.
*/PDF417Common.CODEWORD_TABLE=Int32Array.from([2627,1819,2622,2621,1813,1812,2729,2724,2723,2779,2774,2773,902,896,908,868,865,861,859,2511,873,871,1780,835,2493,825,2491,842,837,844,1764,1762,811,810,809,2483,807,2482,806,2480,815,814,813,812,2484,817,816,1745,1744,1742,1746,2655,2637,2635,2626,2625,2623,2628,1820,2752,2739,2737,2728,2727,2725,2730,2785,2783,2778,2777,2775,2780,787,781,747,739,736,2413,754,752,1719,692,689,681,2371,678,2369,700,697,694,703,1688,1686,642,638,2343,631,2341,627,2338,651,646,643,2345,654,652,1652,1650,1647,1654,601,599,2322,596,2321,594,2319,2317,611,610,608,606,2324,603,2323,615,614,612,1617,1616,1614,1612,616,1619,1618,2575,2538,2536,905,901,898,909,2509,2507,2504,870,867,864,860,2512,875,872,1781,2490,2489,2487,2485,1748,836,834,832,830,2494,827,2492,843,841,839,845,1765,1763,2701,2676,2674,2653,2648,2656,2634,2633,2631,2629,1821,2638,2636,2770,2763,2761,2750,2745,2753,2736,2735,2733,2731,1848,2740,2738,2786,2784,591,588,576,569,566,2296,1590,537,534,526,2276,522,2274,545,542,539,548,1572,1570,481,2245,466,2242,462,2239,492,485,482,2249,496,494,1534,1531,1528,1538,413,2196,406,2191,2188,425,419,2202,415,2199,432,430,427,1472,1467,1464,433,1476,1474,368,367,2160,365,2159,362,2157,2155,2152,378,377,375,2166,372,2165,369,2162,383,381,379,2168,1419,1418,1416,1414,385,1411,384,1423,1422,1420,1424,2461,802,2441,2439,790,786,783,794,2409,2406,2403,750,742,738,2414,756,753,1720,2367,2365,2362,2359,1663,693,691,684,2373,680,2370,702,699,696,704,1690,1687,2337,2336,2334,2332,1624,2329,1622,640,637,2344,634,2342,630,2340,650,648,645,2346,655,653,1653,1651,1649,1655,2612,2597,2595,2571,2568,2565,2576,2534,2529,2526,1787,2540,2537,907,904,900,910,2503,2502,2500,2498,1768,2495,1767,2510,2508,2506,869,866,863,2513,876,874,1782,2720,2713,2711,2697,2694,2691,2702,2672,2670,2664,1828,2678,2675,2647,2646,2644,2642,1823,2639,1822,2654,2652,2650,2657,2771,1855,2765,2762,1850,1849,2751,2749,2747,2754,353,2148,344,342,336,2142,332,2140,345,1375,1373,306,2130,299,2128,295,2125,319,314,311,2132,1354,1352,1349,1356,262,257,2101,253,2096,2093,274,273,267,2107,263,2104,280,278,275,1316,1311,1308,1320,1318,2052,202,2050,2044,2040,219,2063,212,2060,208,2055,224,221,2066,1260,1258,1252,231,1248,229,1266,1264,1261,1268,155,1998,153,1996,1994,1991,1988,165,164,2007,162,2006,159,2003,2000,172,171,169,2012,166,2010,1186,1184,1182,1179,175,1176,173,1192,1191,1189,1187,176,1194,1193,2313,2307,2305,592,589,2294,2292,2289,578,572,568,2297,580,1591,2272,2267,2264,1547,538,536,529,2278,525,2275,547,544,541,1574,1571,2237,2235,2229,1493,2225,1489,478,2247,470,2244,465,2241,493,488,484,2250,498,495,1536,1533,1530,1539,2187,2186,2184,2182,1432,2179,1430,2176,1427,414,412,2197,409,2195,405,2193,2190,426,424,421,2203,418,2201,431,429,1473,1471,1469,1466,434,1477,1475,2478,2472,2470,2459,2457,2454,2462,803,2437,2432,2429,1726,2443,2440,792,789,785,2401,2399,2393,1702,2389,1699,2411,2408,2405,745,741,2415,758,755,1721,2358,2357,2355,2353,1661,2350,1660,2347,1657,2368,2366,2364,2361,1666,690,687,2374,683,2372,701,698,705,1691,1689,2619,2617,2610,2608,2605,2613,2593,2588,2585,1803,2599,2596,2563,2561,2555,1797,2551,1795,2573,2570,2567,2577,2525,2524,2522,2520,1786,2517,1785,2514,1783,2535,2533,2531,2528,1788,2541,2539,906,903,911,2721,1844,2715,2712,1838,1836,2699,2696,2693,2703,1827,1826,1824,2673,2671,2669,2666,1829,2679,2677,1858,1857,2772,1854,1853,1851,1856,2766,2764,143,1987,139,1986,135,133,131,1984,128,1983,125,1981,138,137,136,1985,1133,1132,1130,112,110,1974,107,1973,104,1971,1969,122,121,119,117,1977,114,1976,124,1115,1114,1112,1110,1117,1116,84,83,1953,81,1952,78,1950,1948,1945,94,93,91,1959,88,1958,85,1955,99,97,95,1961,1086,1085,1083,1081,1078,100,1090,1089,1087,1091,49,47,1917,44,1915,1913,1910,1907,59,1926,56,1925,53,1922,1919,66,64,1931,61,1929,1042,1040,1038,71,1035,70,1032,68,1048,1047,1045,1043,1050,1049,12,10,1869,1867,1864,1861,21,1880,19,1877,1874,1871,28,1888,25,1886,22,1883,982,980,977,974,32,30,991,989,987,984,34,995,994,992,2151,2150,2147,2146,2144,356,355,354,2149,2139,2138,2136,2134,1359,343,341,338,2143,335,2141,348,347,346,1376,1374,2124,2123,2121,2119,1326,2116,1324,310,308,305,2131,302,2129,298,2127,320,318,316,313,2133,322,321,1355,1353,1351,1357,2092,2091,2089,2087,1276,2084,1274,2081,1271,259,2102,256,2100,252,2098,2095,272,269,2108,266,2106,281,279,277,1317,1315,1313,1310,282,1321,1319,2039,2037,2035,2032,1203,2029,1200,1197,207,2053,205,2051,201,2049,2046,2043,220,218,2064,215,2062,211,2059,228,226,223,2069,1259,1257,1254,232,1251,230,1267,1265,1263,2316,2315,2312,2311,2309,2314,2304,2303,2301,2299,1593,2308,2306,590,2288,2287,2285,2283,1578,2280,1577,2295,2293,2291,579,577,574,571,2298,582,581,1592,2263,2262,2260,2258,1545,2255,1544,2252,1541,2273,2271,2269,2266,1550,535,532,2279,528,2277,546,543,549,1575,1573,2224,2222,2220,1486,2217,1485,2214,1482,1479,2238,2236,2234,2231,1496,2228,1492,480,477,2248,473,2246,469,2243,490,487,2251,497,1537,1535,1532,2477,2476,2474,2479,2469,2468,2466,2464,1730,2473,2471,2453,2452,2450,2448,1729,2445,1728,2460,2458,2456,2463,805,804,2428,2427,2425,2423,1725,2420,1724,2417,1722,2438,2436,2434,2431,1727,2444,2442,793,791,788,795,2388,2386,2384,1697,2381,1696,2378,1694,1692,2402,2400,2398,2395,1703,2392,1701,2412,2410,2407,751,748,744,2416,759,757,1807,2620,2618,1806,1805,2611,2609,2607,2614,1802,1801,1799,2594,2592,2590,2587,1804,2600,2598,1794,1793,1791,1789,2564,2562,2560,2557,1798,2554,1796,2574,2572,2569,2578,1847,1846,2722,1843,1842,1840,1845,2716,2714,1835,1834,1832,1830,1839,1837,2700,2698,2695,2704,1817,1811,1810,897,862,1777,829,826,838,1760,1758,808,2481,1741,1740,1738,1743,2624,1818,2726,2776,782,740,737,1715,686,679,695,1682,1680,639,628,2339,647,644,1645,1643,1640,1648,602,600,597,595,2320,593,2318,609,607,604,1611,1610,1608,1606,613,1615,1613,2328,926,924,892,886,899,857,850,2505,1778,824,823,821,819,2488,818,2486,833,831,828,840,1761,1759,2649,2632,2630,2746,2734,2732,2782,2781,570,567,1587,531,527,523,540,1566,1564,476,467,463,2240,486,483,1524,1521,1518,1529,411,403,2192,399,2189,423,416,1462,1457,1454,428,1468,1465,2210,366,363,2158,360,2156,357,2153,376,373,370,2163,1410,1409,1407,1405,382,1402,380,1417,1415,1412,1421,2175,2174,777,774,771,784,732,725,722,2404,743,1716,676,674,668,2363,665,2360,685,1684,1681,626,624,622,2335,620,2333,617,2330,641,635,649,1646,1644,1642,2566,928,925,2530,2527,894,891,888,2501,2499,2496,858,856,854,851,1779,2692,2668,2665,2645,2643,2640,2651,2768,2759,2757,2744,2743,2741,2748,352,1382,340,337,333,1371,1369,307,300,296,2126,315,312,1347,1342,1350,261,258,250,2097,246,2094,271,268,264,1306,1301,1298,276,1312,1309,2115,203,2048,195,2045,191,2041,213,209,2056,1246,1244,1238,225,1234,222,1256,1253,1249,1262,2080,2079,154,1997,150,1995,147,1992,1989,163,160,2004,156,2001,1175,1174,1172,1170,1167,170,1164,167,1185,1183,1180,1177,174,1190,1188,2025,2024,2022,587,586,564,559,556,2290,573,1588,520,518,512,2268,508,2265,530,1568,1565,461,457,2233,450,2230,446,2226,479,471,489,1526,1523,1520,397,395,2185,392,2183,389,2180,2177,410,2194,402,422,1463,1461,1459,1456,1470,2455,799,2433,2430,779,776,773,2397,2394,2390,734,728,724,746,1717,2356,2354,2351,2348,1658,677,675,673,670,667,688,1685,1683,2606,2589,2586,2559,2556,2552,927,2523,2521,2518,2515,1784,2532,895,893,890,2718,2709,2707,2689,2687,2684,2663,2662,2660,2658,1825,2667,2769,1852,2760,2758,142,141,1139,1138,134,132,129,126,1982,1129,1128,1126,1131,113,111,108,105,1972,101,1970,120,118,115,1109,1108,1106,1104,123,1113,1111,82,79,1951,75,1949,72,1946,92,89,86,1956,1077,1076,1074,1072,98,1069,96,1084,1082,1079,1088,1968,1967,48,45,1916,42,1914,39,1911,1908,60,57,54,1923,50,1920,1031,1030,1028,1026,67,1023,65,1020,62,1041,1039,1036,1033,69,1046,1044,1944,1943,1941,11,9,1868,7,1865,1862,1859,20,1878,16,1875,13,1872,970,968,966,963,29,960,26,23,983,981,978,975,33,971,31,990,988,985,1906,1904,1902,993,351,2145,1383,331,330,328,326,2137,323,2135,339,1372,1370,294,293,291,289,2122,286,2120,283,2117,309,303,317,1348,1346,1344,245,244,242,2090,239,2088,236,2085,2082,260,2099,249,270,1307,1305,1303,1300,1314,189,2038,186,2036,183,2033,2030,2026,206,198,2047,194,216,1247,1245,1243,1240,227,1237,1255,2310,2302,2300,2286,2284,2281,565,563,561,558,575,1589,2261,2259,2256,2253,1542,521,519,517,514,2270,511,533,1569,1567,2223,2221,2218,2215,1483,2211,1480,459,456,453,2232,449,474,491,1527,1525,1522,2475,2467,2465,2451,2449,2446,801,800,2426,2424,2421,2418,1723,2435,780,778,775,2387,2385,2382,2379,1695,2375,1693,2396,735,733,730,727,749,1718,2616,2615,2604,2603,2601,2584,2583,2581,2579,1800,2591,2550,2549,2547,2545,1792,2542,1790,2558,929,2719,1841,2710,2708,1833,1831,2690,2688,2686,1815,1809,1808,1774,1756,1754,1737,1736,1734,1739,1816,1711,1676,1674,633,629,1638,1636,1633,1641,598,1605,1604,1602,1600,605,1609,1607,2327,887,853,1775,822,820,1757,1755,1584,524,1560,1558,468,464,1514,1511,1508,1519,408,404,400,1452,1447,1444,417,1458,1455,2208,364,361,358,2154,1401,1400,1398,1396,374,1393,371,1408,1406,1403,1413,2173,2172,772,726,723,1712,672,669,666,682,1678,1675,625,623,621,618,2331,636,632,1639,1637,1635,920,918,884,880,889,849,848,847,846,2497,855,852,1776,2641,2742,2787,1380,334,1367,1365,301,297,1340,1338,1335,1343,255,251,247,1296,1291,1288,265,1302,1299,2113,204,196,192,2042,1232,1230,1224,214,1220,210,1242,1239,1235,1250,2077,2075,151,148,1993,144,1990,1163,1162,1160,1158,1155,161,1152,157,1173,1171,1168,1165,168,1181,1178,2021,2020,2018,2023,585,560,557,1585,516,509,1562,1559,458,447,2227,472,1516,1513,1510,398,396,393,390,2181,386,2178,407,1453,1451,1449,1446,420,1460,2209,769,764,720,712,2391,729,1713,664,663,661,659,2352,656,2349,671,1679,1677,2553,922,919,2519,2516,885,883,881,2685,2661,2659,2767,2756,2755,140,1137,1136,130,127,1125,1124,1122,1127,109,106,102,1103,1102,1100,1098,116,1107,1105,1980,80,76,73,1947,1068,1067,1065,1063,90,1060,87,1075,1073,1070,1080,1966,1965,46,43,40,1912,36,1909,1019,1018,1016,1014,58,1011,55,1008,51,1029,1027,1024,1021,63,1037,1034,1940,1939,1937,1942,8,1866,4,1863,1,1860,956,954,952,949,946,17,14,969,967,964,961,27,957,24,979,976,972,1901,1900,1898,1896,986,1905,1903,350,349,1381,329,327,324,1368,1366,292,290,287,284,2118,304,1341,1339,1337,1345,243,240,237,2086,233,2083,254,1297,1295,1293,1290,1304,2114,190,187,184,2034,180,2031,177,2027,199,1233,1231,1229,1226,217,1223,1241,2078,2076,584,555,554,552,550,2282,562,1586,507,506,504,502,2257,499,2254,515,1563,1561,445,443,441,2219,438,2216,435,2212,460,454,475,1517,1515,1512,2447,798,797,2422,2419,770,768,766,2383,2380,2376,721,719,717,714,731,1714,2602,2582,2580,2548,2546,2543,923,921,2717,2706,2705,2683,2682,2680,1771,1752,1750,1733,1732,1731,1735,1814,1707,1670,1668,1631,1629,1626,1634,1599,1598,1596,1594,1603,1601,2326,1772,1753,1751,1581,1554,1552,1504,1501,1498,1509,1442,1437,1434,401,1448,1445,2206,1392,1391,1389,1387,1384,359,1399,1397,1394,1404,2171,2170,1708,1672,1669,619,1632,1630,1628,1773,1378,1363,1361,1333,1328,1336,1286,1281,1278,248,1292,1289,2111,1218,1216,1210,197,1206,193,1228,1225,1221,1236,2073,2071,1151,1150,1148,1146,152,1143,149,1140,145,1161,1159,1156,1153,158,1169,1166,2017,2016,2014,2019,1582,510,1556,1553,452,448,1506,1500,394,391,387,1443,1441,1439,1436,1450,2207,765,716,713,1709,662,660,657,1673,1671,916,914,879,878,877,882,1135,1134,1121,1120,1118,1123,1097,1096,1094,1092,103,1101,1099,1979,1059,1058,1056,1054,77,1051,74,1066,1064,1061,1071,1964,1963,1007,1006,1004,1002,999,41,996,37,1017,1015,1012,1009,52,1025,1022,1936,1935,1933,1938,942,940,938,935,932,5,2,955,953,950,947,18,943,15,965,962,958,1895,1894,1892,1890,973,1899,1897,1379,325,1364,1362,288,285,1334,1332,1330,241,238,234,1287,1285,1283,1280,1294,2112,188,185,181,178,2028,1219,1217,1215,1212,200,1209,1227,2074,2072,583,553,551,1583,505,503,500,513,1557,1555,444,442,439,436,2213,455,451,1507,1505,1502,796,763,762,760,767,711,710,708,706,2377,718,715,1710,2544,917,915,2681,1627,1597,1595,2325,1769,1749,1747,1499,1438,1435,2204,1390,1388,1385,1395,2169,2167,1704,1665,1662,1625,1623,1620,1770,1329,1282,1279,2109,1214,1207,1222,2068,2065,1149,1147,1144,1141,146,1157,1154,2013,2011,2008,2015,1579,1549,1546,1495,1487,1433,1431,1428,1425,388,1440,2205,1705,658,1667,1664,1119,1095,1093,1978,1057,1055,1052,1062,1962,1960,1005,1003,1000,997,38,1013,1010,1932,1930,1927,1934,941,939,936,933,6,930,3,951,948,944,1889,1887,1884,1881,959,1893,1891,35,1377,1360,1358,1327,1325,1322,1331,1277,1275,1272,1269,235,1284,2110,1205,1204,1201,1198,182,1195,179,1213,2070,2067,1580,501,1551,1548,440,437,1497,1494,1490,1503,761,709,707,1706,913,912,2198,1386,2164,2161,1621,1766,2103,1208,2058,2054,1145,1142,2005,2002,1999,2009,1488,1429,1426,2200,1698,1659,1656,1975,1053,1957,1954,1001,998,1924,1921,1918,1928,937,934,931,1879,1876,1873,1870,945,1885,1882,1323,1273,1270,2105,1202,1199,1196,1211,2061,2057,1576,1543,1540,1484,1481,1478,1491,1700]);/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ // import java.util.List;
/**
* @author Guenther Grau
*/ /*public final*/var PDF417DetectorResult=/*#__PURE__*/function(){function PDF417DetectorResult(bits,points){_classCallCheck(this,PDF417DetectorResult);this.bits=bits;this.points=points;}_createClass(PDF417DetectorResult,[{key:"getBits",value:function getBits(){return this.bits;}},{key:"getPoints",value:function getPoints(){return this.points;}}]);return PDF417DetectorResult;}();/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ // import java.util.ArrayList;
// import java.util.Arrays;
// import java.util.List;
// import java.util.Map;
/**
* <p>Encapsulates logic that can detect a PDF417 Code in an image, even if the
* PDF417 Code is rotated or skewed, or partially obscured.</p>
*
* @author SITA Lab (kevin.osullivan@sita.aero)
* @author dswitkin@google.com (Daniel Switkin)
* @author Guenther Grau
*/ /*public*/ /*final*/var Detector$3=/*#__PURE__*/function(){function Detector$3(){_classCallCheck(this,Detector$3);}_createClass(Detector$3,null,[{key:"detectMultiple",value:/**
* <p>Detects a PDF417 Code in an image. Only checks 0 and 180 degree rotations.</p>
*
* @param image barcode image to decode
* @param hints optional hints to detector
* @param multiple if true, then the image is searched for multiple codes. If false, then at most one code will
* be found and returned
* @return {@link PDF417DetectorResult} encapsulating results of detecting a PDF417 code
* @throws NotFoundException if no PDF417 Code can be found
*/function detectMultiple(image,hints,multiple){// TODO detection improvement, tryHarder could try several different luminance thresholds/blackpoints or even
// different binarizers
// boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
var bitMatrix=image.getBlackMatrix();var barcodeCoordinates=Detector$3.detect(multiple,bitMatrix);if(!barcodeCoordinates.length){bitMatrix=bitMatrix.clone();bitMatrix.rotate180();barcodeCoordinates=Detector$3.detect(multiple,bitMatrix);}return new PDF417DetectorResult(bitMatrix,barcodeCoordinates);}/**
* Detects PDF417 codes in an image. Only checks 0 degree rotation
* @param multiple if true, then the image is searched for multiple codes. If false, then at most one code will
* be found and returned
* @param bitMatrix bit matrix to detect barcodes in
* @return List of ResultPoint arrays containing the coordinates of found barcodes
*/},{key:"detect",value:function detect(multiple,bitMatrix){var barcodeCoordinates=new Array();var row=0;var column=0;var foundBarcodeInRow=false;while(row<bitMatrix.getHeight()){var vertices=Detector$3.findVertices(bitMatrix,row,column);if(vertices[0]==null&&vertices[3]==null){if(!foundBarcodeInRow){// we didn't find any barcode so that's the end of searching
break;}// we didn't find a barcode starting at the given column and row. Try again from the first column and slightly
// below the lowest barcode we found so far.
foundBarcodeInRow=false;column=0;var _iterator52=_createForOfIteratorHelper(barcodeCoordinates),_step52;try{for(_iterator52.s();!(_step52=_iterator52.n()).done;){var barcodeCoordinate=_step52.value;if(barcodeCoordinate[1]!=null){row=Math.trunc(Math.max(row,barcodeCoordinate[1].getY()));}if(barcodeCoordinate[3]!=null){row=Math.max(row,Math.trunc(barcodeCoordinate[3].getY()));}}}catch(err){_iterator52.e(err);}finally{_iterator52.f();}row+=Detector$3.ROW_STEP;continue;}foundBarcodeInRow=true;barcodeCoordinates.push(vertices);if(!multiple){break;}// if we didn't find a right row indicator column, then continue the search for the next barcode after the
// start pattern of the barcode just found.
if(vertices[2]!=null){column=Math.trunc(vertices[2].getX());row=Math.trunc(vertices[2].getY());}else{column=Math.trunc(vertices[4].getX());row=Math.trunc(vertices[4].getY());}}return barcodeCoordinates;}/**
* Locate the vertices and the codewords area of a black blob using the Start
* and Stop patterns as locators.
*
* @param matrix the scanned barcode image.
* @return an array containing the vertices:
* vertices[0] x, y top left barcode
* vertices[1] x, y bottom left barcode
* vertices[2] x, y top right barcode
* vertices[3] x, y bottom right barcode
* vertices[4] x, y top left codeword area
* vertices[5] x, y bottom left codeword area
* vertices[6] x, y top right codeword area
* vertices[7] x, y bottom right codeword area
*/},{key:"findVertices",value:function findVertices(matrix,startRow,startColumn){var height=matrix.getHeight();var width=matrix.getWidth();// const result = new ResultPoint[8];
var result=new Array(8);Detector$3.copyToResult(result,Detector$3.findRowsWithPattern(matrix,height,width,startRow,startColumn,Detector$3.START_PATTERN),Detector$3.INDEXES_START_PATTERN);if(result[4]!=null){startColumn=Math.trunc(result[4].getX());startRow=Math.trunc(result[4].getY());}Detector$3.copyToResult(result,Detector$3.findRowsWithPattern(matrix,height,width,startRow,startColumn,Detector$3.STOP_PATTERN),Detector$3.INDEXES_STOP_PATTERN);return result;}},{key:"copyToResult",value:function copyToResult(result,tmpResult,destinationIndexes){for(var i=0;i<destinationIndexes.length;i++){result[destinationIndexes[i]]=tmpResult[i];}}},{key:"findRowsWithPattern",value:function findRowsWithPattern(matrix,height,width,startRow,startColumn,pattern){// const result = new ResultPoint[4];
var result=new Array(4);var found=false;var counters=new Int32Array(pattern.length);for(;startRow<height;startRow+=Detector$3.ROW_STEP){var loc=Detector$3.findGuardPattern(matrix,startColumn,startRow,width,false,pattern,counters);if(loc!=null){while(startRow>0){var previousRowLoc=Detector$3.findGuardPattern(matrix,startColumn,--startRow,width,false,pattern,counters);if(previousRowLoc!=null){loc=previousRowLoc;}else{startRow++;break;}}result[0]=new ResultPoint(loc[0],startRow);result[1]=new ResultPoint(loc[1],startRow);found=true;break;}}var stopRow=startRow+1;// Last row of the current symbol that contains pattern
if(found){var skippedRowCount=0;var _previousRowLoc=Int32Array.from([Math.trunc(result[0].getX()),Math.trunc(result[1].getX())]);for(;stopRow<height;stopRow++){var _loc=Detector$3.findGuardPattern(matrix,_previousRowLoc[0],stopRow,width,false,pattern,counters);// a found pattern is only considered to belong to the same barcode if the start and end positions
// don't differ too much. Pattern drift should be not bigger than two for consecutive rows. With
// a higher number of skipped rows drift could be larger. To keep it simple for now, we allow a slightly
// larger drift and don't check for skipped rows.
if(_loc!=null&&Math.abs(_previousRowLoc[0]-_loc[0])<Detector$3.MAX_PATTERN_DRIFT&&Math.abs(_previousRowLoc[1]-_loc[1])<Detector$3.MAX_PATTERN_DRIFT){_previousRowLoc=_loc;skippedRowCount=0;}else{if(skippedRowCount>Detector$3.SKIPPED_ROW_COUNT_MAX){break;}else{skippedRowCount++;}}}stopRow-=skippedRowCount+1;result[2]=new ResultPoint(_previousRowLoc[0],stopRow);result[3]=new ResultPoint(_previousRowLoc[1],stopRow);}if(stopRow-startRow<Detector$3.BARCODE_MIN_HEIGHT){Arrays.fill(result,null);}return result;}/**
* @param matrix row of black/white values to search
* @param column x position to start search
* @param row y position to start search
* @param width the number of pixels to search on this row
* @param pattern pattern of counts of number of black and white pixels that are
* being searched for as a pattern
* @param counters array of counters, as long as pattern, to re-use
* @return start/end horizontal offset of guard pattern, as an array of two ints.
*/},{key:"findGuardPattern",value:function findGuardPattern(matrix,column,row,width,whiteFirst,pattern,counters){Arrays.fillWithin(counters,0,counters.length,0);var patternStart=column;var pixelDrift=0;// if there are black pixels left of the current pixel shift to the left, but only for MAX_PIXEL_DRIFT pixels
while(matrix.get(patternStart,row)&&patternStart>0&&pixelDrift++<Detector$3.MAX_PIXEL_DRIFT){patternStart--;}var x=patternStart;var counterPosition=0;var patternLength=pattern.length;for(var isWhite=whiteFirst;x<width;x++){var pixel=matrix.get(x,row);if(pixel!==isWhite){counters[counterPosition]++;}else{if(counterPosition===patternLength-1){if(Detector$3.patternMatchVariance(counters,pattern,Detector$3.MAX_INDIVIDUAL_VARIANCE)<Detector$3.MAX_AVG_VARIANCE){return new Int32Array([patternStart,x]);}patternStart+=counters[0]+counters[1];System.arraycopy(counters,2,counters,0,counterPosition-1);counters[counterPosition-1]=0;counters[counterPosition]=0;counterPosition--;}else{counterPosition++;}counters[counterPosition]=1;isWhite=!isWhite;}}if(counterPosition===patternLength-1&&Detector$3.patternMatchVariance(counters,pattern,Detector$3.MAX_INDIVIDUAL_VARIANCE)<Detector$3.MAX_AVG_VARIANCE){return new Int32Array([patternStart,x-1]);}return null;}/**
* Determines how closely a set of observed counts of runs of black/white
* values matches a given target pattern. This is reported as the ratio of
* the total variance from the expected pattern proportions across all
* pattern elements, to the length of the pattern.
*
* @param counters observed counters
* @param pattern expected pattern
* @param maxIndividualVariance The most any counter can differ before we give up
* @return ratio of total variance between counters and pattern compared to total pattern size
*/},{key:"patternMatchVariance",value:function patternMatchVariance(counters,pattern,maxIndividualVariance){var numCounters=counters.length;var total=0;var patternLength=0;for(var i=0;i<numCounters;i++){total+=counters[i];patternLength+=pattern[i];}if(total<patternLength){// If we don't even have one pixel per unit of bar width, assume this
// is too small to reliably match, so fail:
return(/*Float.POSITIVE_INFINITY*/Infinity);}// We're going to fake floating-point math in integers. We just need to use more bits.
// Scale up patternLength so that intermediate values below like scaledCounter will have
// more "significant digits".
var unitBarWidth=total/patternLength;maxIndividualVariance*=unitBarWidth;var totalVariance=0.0;for(var x=0;x<numCounters;x++){var counter=counters[x];var scaledPattern=pattern[x]*unitBarWidth;var variance=counter>scaledPattern?counter-scaledPattern:scaledPattern-counter;if(variance>maxIndividualVariance){return(/*Float.POSITIVE_INFINITY*/Infinity);}totalVariance+=variance;}return totalVariance/total;}}]);return Detector$3;}();Detector$3.INDEXES_START_PATTERN=Int32Array.from([0,4,1,5]);Detector$3.INDEXES_STOP_PATTERN=Int32Array.from([6,2,7,3]);Detector$3.MAX_AVG_VARIANCE=0.42;Detector$3.MAX_INDIVIDUAL_VARIANCE=0.8;// B S B S B S B S Bar/Space pattern
// 11111111 0 1 0 1 0 1 000
Detector$3.START_PATTERN=Int32Array.from([8,1,1,1,1,1,1,3]);// 1111111 0 1 000 1 0 1 00 1
Detector$3.STOP_PATTERN=Int32Array.from([7,1,1,3,1,1,1,2,1]);Detector$3.MAX_PIXEL_DRIFT=3;Detector$3.MAX_PATTERN_DRIFT=5;// if we set the value too low, then we don't detect the correct height of the bar if the start patterns are damaged.
// if we set the value too high, then we might detect the start pattern from a neighbor barcode.
Detector$3.SKIPPED_ROW_COUNT_MAX=25;// A PDF471 barcode should have at least 3 rows, with each row being >= 3 times the module width. Therefore it should be at least
// 9 pixels tall. To be conservative, we use about half the size to ensure we don't miss it.
Detector$3.ROW_STEP=5;Detector$3.BARCODE_MIN_HEIGHT=10;/*
* Copyright 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* @author Sean Owen
* @see com.google.zxing.common.reedsolomon.GenericGFPoly
*/ /*final*/var ModulusPoly=/*#__PURE__*/function(){function ModulusPoly(field,coefficients){_classCallCheck(this,ModulusPoly);if(coefficients.length===0){throw new IllegalArgumentException();}this.field=field;var coefficientsLength=/*int*/coefficients.length;if(coefficientsLength>1&&coefficients[0]===0){// Leading term must be non-zero for anything except the constant polynomial "0"
var firstNonZero=/*int*/1;while(firstNonZero<coefficientsLength&&coefficients[firstNonZero]===0){firstNonZero++;}if(firstNonZero===coefficientsLength){this.coefficients=new Int32Array([0]);}else{this.coefficients=new Int32Array(coefficientsLength-firstNonZero);System.arraycopy(coefficients,firstNonZero,this.coefficients,0,this.coefficients.length);}}else{this.coefficients=coefficients;}}_createClass(ModulusPoly,[{key:"getCoefficients",value:function getCoefficients(){return this.coefficients;}/**
* @return degree of this polynomial
*/},{key:"getDegree",value:function getDegree(){return this.coefficients.length-1;}/**
* @return true iff this polynomial is the monomial "0"
*/},{key:"isZero",value:function isZero(){return this.coefficients[0]===0;}/**
* @return coefficient of x^degree term in this polynomial
*/},{key:"getCoefficient",value:function getCoefficient(degree){return this.coefficients[this.coefficients.length-1-degree];}/**
* @return evaluation of this polynomial at a given point
*/},{key:"evaluateAt",value:function evaluateAt(a){if(a===0){// Just return the x^0 coefficient
return this.getCoefficient(0);}if(a===1){// Just the sum of the coefficients
var sum=/*int*/0;var _iterator53=_createForOfIteratorHelper(this.coefficients),_step53;try{for(_iterator53.s();!(_step53=_iterator53.n()).done;){var coefficient=_step53.value;sum=this.field.add(sum,coefficient);}}catch(err){_iterator53.e(err);}finally{_iterator53.f();}return sum;}var result=/*int*/this.coefficients[0];var size=/*int*/this.coefficients.length;for(var i/*int*/=1;i<size;i++){result=this.field.add(this.field.multiply(a,result),this.coefficients[i]);}return result;}},{key:"add",value:function add(other){if(!this.field.equals(other.field)){throw new IllegalArgumentException('ModulusPolys do not have same ModulusGF field');}if(this.isZero()){return other;}if(other.isZero()){return this;}var smallerCoefficients=this.coefficients;var largerCoefficients=other.coefficients;if(smallerCoefficients.length>largerCoefficients.length){var temp=smallerCoefficients;smallerCoefficients=largerCoefficients;largerCoefficients=temp;}var sumDiff=new Int32Array(largerCoefficients.length);var lengthDiff=/*int*/largerCoefficients.length-smallerCoefficients.length;// Copy high-order terms only found in higher-degree polynomial's coefficients
System.arraycopy(largerCoefficients,0,sumDiff,0,lengthDiff);for(var i/*int*/=lengthDiff;i<largerCoefficients.length;i++){sumDiff[i]=this.field.add(smallerCoefficients[i-lengthDiff],largerCoefficients[i]);}return new ModulusPoly(this.field,sumDiff);}},{key:"subtract",value:function subtract(other){if(!this.field.equals(other.field)){throw new IllegalArgumentException('ModulusPolys do not have same ModulusGF field');}if(other.isZero()){return this;}return this.add(other.negative());}},{key:"multiply",value:function multiply(other){if(other instanceof ModulusPoly){return this.multiplyOther(other);}return this.multiplyScalar(other);}},{key:"multiplyOther",value:function multiplyOther(other){if(!this.field.equals(other.field)){throw new IllegalArgumentException('ModulusPolys do not have same ModulusGF field');}if(this.isZero()||other.isZero()){// return this.field.getZero();
return new ModulusPoly(this.field,new Int32Array([0]));}var aCoefficients=this.coefficients;var aLength=/*int*/aCoefficients.length;var bCoefficients=other.coefficients;var bLength=/*int*/bCoefficients.length;var product=new Int32Array(aLength+bLength-1);for(var i/*int*/=0;i<aLength;i++){var aCoeff=/*int*/aCoefficients[i];for(var j/*int*/=0;j<bLength;j++){product[i+j]=this.field.add(product[i+j],this.field.multiply(aCoeff,bCoefficients[j]));}}return new ModulusPoly(this.field,product);}},{key:"negative",value:function negative(){var size=/*int*/this.coefficients.length;var negativeCoefficients=new Int32Array(size);for(var i/*int*/=0;i<size;i++){negativeCoefficients[i]=this.field.subtract(0,this.coefficients[i]);}return new ModulusPoly(this.field,negativeCoefficients);}},{key:"multiplyScalar",value:function multiplyScalar(scalar){if(scalar===0){return new ModulusPoly(this.field,new Int32Array([0]));}if(scalar===1){return this;}var size=/*int*/this.coefficients.length;var product=new Int32Array(size);for(var i/*int*/=0;i<size;i++){product[i]=this.field.multiply(this.coefficients[i],scalar);}return new ModulusPoly(this.field,product);}},{key:"multiplyByMonomial",value:function multiplyByMonomial(degree,coefficient){if(degree<0){throw new IllegalArgumentException();}if(coefficient===0){return new ModulusPoly(this.field,new Int32Array([0]));}var size=/*int*/this.coefficients.length;var product=new Int32Array(size+degree);for(var i/*int*/=0;i<size;i++){product[i]=this.field.multiply(this.coefficients[i],coefficient);}return new ModulusPoly(this.field,product);}/*
ModulusPoly[] divide(other: ModulusPoly) {
if (!field.equals(other.field)) {
throw new IllegalArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (other.isZero()) {
throw new IllegalArgumentException("Divide by 0");
}
let quotient: ModulusPoly = field.getZero();
let remainder: ModulusPoly = this;
let denominatorLeadingTerm: /*int/ number = other.getCoefficient(other.getDegree());
let inverseDenominatorLeadingTerm: /*int/ number = field.inverse(denominatorLeadingTerm);
while (remainder.getDegree() >= other.getDegree() && !remainder.isZero()) {
let degreeDifference: /*int/ number = remainder.getDegree() - other.getDegree();
let scale: /*int/ number = field.multiply(remainder.getCoefficient(remainder.getDegree()), inverseDenominatorLeadingTerm);
let term: ModulusPoly = other.multiplyByMonomial(degreeDifference, scale);
let iterationQuotient: ModulusPoly = field.buildMonomial(degreeDifference, scale);
quotient = quotient.add(iterationQuotient);
remainder = remainder.subtract(term);
}
return new ModulusPoly[] { quotient, remainder };
}
*/ // @Override
},{key:"toString",value:function toString(){var result=new StringBuilder(/*8 * this.getDegree()*/);// dynamic string size in JS
for(var degree/*int*/=this.getDegree();degree>=0;degree--){var coefficient=/*int*/this.getCoefficient(degree);if(coefficient!==0){if(coefficient<0){result.append(' - ');coefficient=-coefficient;}else{if(result.length()>0){result.append(' + ');}}if(degree===0||coefficient!==1){result.append(coefficient);}if(degree!==0){if(degree===1){result.append('x');}else{result.append('x^');result.append(degree);}}}}return result.toString();}}]);return ModulusPoly;}();var ModulusBase=/*#__PURE__*/function(){function ModulusBase(){_classCallCheck(this,ModulusBase);}_createClass(ModulusBase,[{key:"add",value:function add(a,b){return(a+b)%this.modulus;}},{key:"subtract",value:function subtract(a,b){return(this.modulus+a-b)%this.modulus;}},{key:"exp",value:function exp(a){return this.expTable[a];}},{key:"log",value:function log(a){if(a===0){throw new IllegalArgumentException();}return this.logTable[a];}},{key:"inverse",value:function inverse(a){if(a===0){throw new ArithmeticException();}return this.expTable[this.modulus-this.logTable[a]-1];}},{key:"multiply",value:function multiply(a,b){if(a===0||b===0){return 0;}return this.expTable[(this.logTable[a]+this.logTable[b])%(this.modulus-1)];}},{key:"getSize",value:function getSize(){return this.modulus;}},{key:"equals",value:function equals(o){return o===this;}}]);return ModulusBase;}();/*
* Copyright 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>A field based on powers of a generator integer, modulo some modulus.</p>
*
* @author Sean Owen
* @see com.google.zxing.common.reedsolomon.GenericGF
*/ /*public final*/var ModulusGF=/*#__PURE__*/function(_ModulusBase){_inherits(ModulusGF,_ModulusBase);var _super54=_createSuper(ModulusGF);// private /*final*/ modulus: /*int*/ number;
function ModulusGF(modulus,generator){var _this35;_classCallCheck(this,ModulusGF);_this35=_super54.call(this);_this35.modulus=modulus;_this35.expTable=new Int32Array(modulus);_this35.logTable=new Int32Array(modulus);var x=/*int*/1;for(var i/*int*/=0;i<modulus;i++){_this35.expTable[i]=x;x=x*generator%modulus;}for(var _i32/*int*/=0;_i32<modulus-1;_i32++){_this35.logTable[_this35.expTable[_i32]]=_i32;}// logTable[0] == 0 but this should never be used
_this35.zero=new ModulusPoly(_assertThisInitialized(_this35),new Int32Array([0]));_this35.one=new ModulusPoly(_assertThisInitialized(_this35),new Int32Array([1]));return _this35;}_createClass(ModulusGF,[{key:"getZero",value:function getZero(){return this.zero;}},{key:"getOne",value:function getOne(){return this.one;}},{key:"buildMonomial",value:function buildMonomial(degree,coefficient){if(degree<0){throw new IllegalArgumentException();}if(coefficient===0){return this.zero;}var coefficients=new Int32Array(degree+1);coefficients[0]=coefficient;return new ModulusPoly(this,coefficients);}}]);return ModulusGF;}(ModulusBase);ModulusGF.PDF417_GF=new ModulusGF(PDF417Common.NUMBER_OF_CODEWORDS,3);/*
* Copyright 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* <p>PDF417 error correction implementation.</p>
*
* <p>This <a href="http://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction#Example">example</a>
* is quite useful in understanding the algorithm.</p>
*
* @author Sean Owen
* @see com.google.zxing.common.reedsolomon.ReedSolomonDecoder
*/ /*public final*/var ErrorCorrection=/*#__PURE__*/function(){function ErrorCorrection(){_classCallCheck(this,ErrorCorrection);this.field=ModulusGF.PDF417_GF;}/**
* @param received received codewords
* @param numECCodewords number of those codewords used for EC
* @param erasures location of erasures
* @return number of errors
* @throws ChecksumException if errors cannot be corrected, maybe because of too many errors
*/_createClass(ErrorCorrection,[{key:"decode",value:function decode(received,numECCodewords,erasures){var poly=new ModulusPoly(this.field,received);var S=new Int32Array(numECCodewords);var error=false;for(var i/*int*/=numECCodewords;i>0;i--){var evaluation=poly.evaluateAt(this.field.exp(i));S[numECCodewords-i]=evaluation;if(evaluation!==0){error=true;}}if(!error){return 0;}var knownErrors=this.field.getOne();if(erasures!=null){var _iterator54=_createForOfIteratorHelper(erasures),_step54;try{for(_iterator54.s();!(_step54=_iterator54.n()).done;){var erasure=_step54.value;var b=this.field.exp(received.length-1-erasure);// Add (1 - bx) term:
var term=new ModulusPoly(this.field,new Int32Array([this.field.subtract(0,b),1]));knownErrors=knownErrors.multiply(term);}}catch(err){_iterator54.e(err);}finally{_iterator54.f();}}var syndrome=new ModulusPoly(this.field,S);// syndrome = syndrome.multiply(knownErrors);
var sigmaOmega=this.runEuclideanAlgorithm(this.field.buildMonomial(numECCodewords,1),syndrome,numECCodewords);var sigma=sigmaOmega[0];var omega=sigmaOmega[1];// sigma = sigma.multiply(knownErrors);
var errorLocations=this.findErrorLocations(sigma);var errorMagnitudes=this.findErrorMagnitudes(omega,sigma,errorLocations);for(var _i33/*int*/=0;_i33<errorLocations.length;_i33++){var position=received.length-1-this.field.log(errorLocations[_i33]);if(position<0){throw ChecksumException.getChecksumInstance();}received[position]=this.field.subtract(received[position],errorMagnitudes[_i33]);}return errorLocations.length;}/**
*
* @param ModulusPoly
* @param a
* @param ModulusPoly
* @param b
* @param int
* @param R
* @throws ChecksumException
*/},{key:"runEuclideanAlgorithm",value:function runEuclideanAlgorithm(a,b,R){// Assume a's degree is >= b's
if(a.getDegree()<b.getDegree()){var temp=a;a=b;b=temp;}var rLast=a;var r=b;var tLast=this.field.getZero();var t=this.field.getOne();// Run Euclidean algorithm until r's degree is less than R/2
while(r.getDegree()>=Math.round(R/2)){var rLastLast=rLast;var tLastLast=tLast;rLast=r;tLast=t;// Divide rLastLast by rLast, with quotient in q and remainder in r
if(rLast.isZero()){// Oops, Euclidean algorithm already terminated?
throw ChecksumException.getChecksumInstance();}r=rLastLast;var q=this.field.getZero();var denominatorLeadingTerm=rLast.getCoefficient(rLast.getDegree());var dltInverse=this.field.inverse(denominatorLeadingTerm);while(r.getDegree()>=rLast.getDegree()&&!r.isZero()){var degreeDiff=r.getDegree()-rLast.getDegree();var scale=this.field.multiply(r.getCoefficient(r.getDegree()),dltInverse);q=q.add(this.field.buildMonomial(degreeDiff,scale));r=r.subtract(rLast.multiplyByMonomial(degreeDiff,scale));}t=q.multiply(tLast).subtract(tLastLast).negative();}var sigmaTildeAtZero=t.getCoefficient(0);if(sigmaTildeAtZero===0){throw ChecksumException.getChecksumInstance();}var inverse=this.field.inverse(sigmaTildeAtZero);var sigma=t.multiply(inverse);var omega=r.multiply(inverse);return[sigma,omega];}/**
*
* @param errorLocator
* @throws ChecksumException
*/},{key:"findErrorLocations",value:function findErrorLocations(errorLocator){// This is a direct application of Chien's search
var numErrors=errorLocator.getDegree();var result=new Int32Array(numErrors);var e=0;for(var i/*int*/=1;i<this.field.getSize()&&e<numErrors;i++){if(errorLocator.evaluateAt(i)===0){result[e]=this.field.inverse(i);e++;}}if(e!==numErrors){throw ChecksumException.getChecksumInstance();}return result;}},{key:"findErrorMagnitudes",value:function findErrorMagnitudes(errorEvaluator,errorLocator,errorLocations){var errorLocatorDegree=errorLocator.getDegree();var formalDerivativeCoefficients=new Int32Array(errorLocatorDegree);for(var i/*int*/=1;i<=errorLocatorDegree;i++){formalDerivativeCoefficients[errorLocatorDegree-i]=this.field.multiply(i,errorLocator.getCoefficient(i));}var formalDerivative=new ModulusPoly(this.field,formalDerivativeCoefficients);// This is directly applying Forney's Formula
var s=errorLocations.length;var result=new Int32Array(s);for(var _i34/*int*/=0;_i34<s;_i34++){var xiInverse=this.field.inverse(errorLocations[_i34]);var numerator=this.field.subtract(0,errorEvaluator.evaluateAt(xiInverse));var denominator=this.field.inverse(formalDerivative.evaluateAt(xiInverse));result[_i34]=this.field.multiply(numerator,denominator);}return result;}}]);return ErrorCorrection;}();/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* @author Guenther Grau
*/ /*final*/var BoundingBox=/*#__PURE__*/function(){function BoundingBox(image,topLeft,bottomLeft,topRight,bottomRight){_classCallCheck(this,BoundingBox);if(image instanceof BoundingBox){this.constructor_2(image);}else{this.constructor_1(image,topLeft,bottomLeft,topRight,bottomRight);}}/**
*
* @param image
* @param topLeft
* @param bottomLeft
* @param topRight
* @param bottomRight
*
* @throws NotFoundException
*/_createClass(BoundingBox,[{key:"constructor_1",value:function constructor_1(image,topLeft,bottomLeft,topRight,bottomRight){var leftUnspecified=topLeft==null||bottomLeft==null;var rightUnspecified=topRight==null||bottomRight==null;if(leftUnspecified&&rightUnspecified){throw new NotFoundException();}if(leftUnspecified){topLeft=new ResultPoint(0,topRight.getY());bottomLeft=new ResultPoint(0,bottomRight.getY());}else if(rightUnspecified){topRight=new ResultPoint(image.getWidth()-1,topLeft.getY());bottomRight=new ResultPoint(image.getWidth()-1,bottomLeft.getY());}this.image=image;this.topLeft=topLeft;this.bottomLeft=bottomLeft;this.topRight=topRight;this.bottomRight=bottomRight;this.minX=Math.trunc(Math.min(topLeft.getX(),bottomLeft.getX()));this.maxX=Math.trunc(Math.max(topRight.getX(),bottomRight.getX()));this.minY=Math.trunc(Math.min(topLeft.getY(),topRight.getY()));this.maxY=Math.trunc(Math.max(bottomLeft.getY(),bottomRight.getY()));}},{key:"constructor_2",value:function constructor_2(boundingBox){this.image=boundingBox.image;this.topLeft=boundingBox.getTopLeft();this.bottomLeft=boundingBox.getBottomLeft();this.topRight=boundingBox.getTopRight();this.bottomRight=boundingBox.getBottomRight();this.minX=boundingBox.getMinX();this.maxX=boundingBox.getMaxX();this.minY=boundingBox.getMinY();this.maxY=boundingBox.getMaxY();}/**
* @throws NotFoundException
*/},{key:"addMissingRows",value:/**
* @throws NotFoundException
*/function addMissingRows(missingStartRows,missingEndRows,isLeft){var newTopLeft=this.topLeft;var newBottomLeft=this.bottomLeft;var newTopRight=this.topRight;var newBottomRight=this.bottomRight;if(missingStartRows>0){var top=isLeft?this.topLeft:this.topRight;var newMinY=Math.trunc(top.getY()-missingStartRows);if(newMinY<0){newMinY=0;}var newTop=new ResultPoint(top.getX(),newMinY);if(isLeft){newTopLeft=newTop;}else{newTopRight=newTop;}}if(missingEndRows>0){var bottom=isLeft?this.bottomLeft:this.bottomRight;var newMaxY=Math.trunc(bottom.getY()+missingEndRows);if(newMaxY>=this.image.getHeight()){newMaxY=this.image.getHeight()-1;}var newBottom=new ResultPoint(bottom.getX(),newMaxY);if(isLeft){newBottomLeft=newBottom;}else{newBottomRight=newBottom;}}return new BoundingBox(this.image,newTopLeft,newBottomLeft,newTopRight,newBottomRight);}},{key:"getMinX",value:function getMinX(){return this.minX;}},{key:"getMaxX",value:function getMaxX(){return this.maxX;}},{key:"getMinY",value:function getMinY(){return this.minY;}},{key:"getMaxY",value:function getMaxY(){return this.maxY;}},{key:"getTopLeft",value:function getTopLeft(){return this.topLeft;}},{key:"getTopRight",value:function getTopRight(){return this.topRight;}},{key:"getBottomLeft",value:function getBottomLeft(){return this.bottomLeft;}},{key:"getBottomRight",value:function getBottomRight(){return this.bottomRight;}}],[{key:"merge",value:function merge(leftBox,rightBox){if(leftBox==null){return rightBox;}if(rightBox==null){return leftBox;}return new BoundingBox(leftBox.image,leftBox.topLeft,leftBox.bottomLeft,rightBox.topRight,rightBox.bottomRight);}}]);return BoundingBox;}();/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ // package com.google.zxing.pdf417.decoder;
/**
* @author Guenther Grau
*/ /*final*/var BarcodeMetadata=/*#__PURE__*/function(){function BarcodeMetadata(columnCount,rowCountUpperPart,rowCountLowerPart,errorCorrectionLevel){_classCallCheck(this,BarcodeMetadata);this.columnCount=columnCount;this.errorCorrectionLevel=errorCorrectionLevel;this.rowCountUpperPart=rowCountUpperPart;this.rowCountLowerPart=rowCountLowerPart;this.rowCount=rowCountUpperPart+rowCountLowerPart;}_createClass(BarcodeMetadata,[{key:"getColumnCount",value:function getColumnCount(){return this.columnCount;}},{key:"getErrorCorrectionLevel",value:function getErrorCorrectionLevel(){return this.errorCorrectionLevel;}},{key:"getRowCount",value:function getRowCount(){return this.rowCount;}},{key:"getRowCountUpperPart",value:function getRowCountUpperPart(){return this.rowCountUpperPart;}},{key:"getRowCountLowerPart",value:function getRowCountLowerPart(){return this.rowCountLowerPart;}}]);return BarcodeMetadata;}();/**
* Java Formatter class polyfill that works in the JS way.
*/var Formatter=/*#__PURE__*/function(){function Formatter(){_classCallCheck(this,Formatter);this.buffer='';}/**
*
* @see https://stackoverflow.com/a/13439711/4367683
*
* @param str
* @param arr
*/_createClass(Formatter,[{key:"format",value:/**
*
* @param append The new string to append.
* @param args Argumets values to be formated.
*/function format(append){for(var _len6=arguments.length,args=new Array(_len6>1?_len6-1:0),_key6=1;_key6<_len6;_key6++){args[_key6-1]=arguments[_key6];}this.buffer+=Formatter.form(append,args);}/**
* Returns the Formatter string value.
*/},{key:"toString",value:function toString(){return this.buffer;}}],[{key:"form",value:function form(str,arr){var i=-1;function callback(exp,p0,p1,p2,p3,p4){if(exp==='%%')return'%';if(arr[++i]===undefined)return undefined;exp=p2?parseInt(p2.substr(1)):undefined;var base=p3?parseInt(p3.substr(1)):undefined;var val;switch(p4){case's':val=arr[i];break;case'c':val=arr[i][0];break;case'f':val=parseFloat(arr[i]).toFixed(exp);break;case'p':val=parseFloat(arr[i]).toPrecision(exp);break;case'e':val=parseFloat(arr[i]).toExponential(exp);break;case'x':val=parseInt(arr[i]).toString(base?base:16);break;case'd':val=parseFloat(parseInt(arr[i],base?base:10).toPrecision(exp)).toFixed(0);break;}val=_typeof(val)==='object'?JSON.stringify(val):(+val).toString(base);var size=parseInt(p1);/* padding size */var ch=p1&&p1[0]+''==='0'?'0':' ';/* isnull? */while(val.length<size){val=p0!==undefined?val+ch:ch+val;}/* isminus? */return val;}var regex=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return str.replace(regex,callback);}}]);return Formatter;}();/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* @author Guenther Grau
*/var DetectionResultColumn=/*#__PURE__*/function(){function DetectionResultColumn(boundingBox){_classCallCheck(this,DetectionResultColumn);this.boundingBox=new BoundingBox(boundingBox);// this.codewords = new Codeword[boundingBox.getMaxY() - boundingBox.getMinY() + 1];
this.codewords=new Array(boundingBox.getMaxY()-boundingBox.getMinY()+1);}/*final*/_createClass(DetectionResultColumn,[{key:"getCodewordNearby",value:function getCodewordNearby(imageRow){var codeword=this.getCodeword(imageRow);if(codeword!=null){return codeword;}for(var i=1;i<DetectionResultColumn.MAX_NEARBY_DISTANCE;i++){var nearImageRow=this.imageRowToCodewordIndex(imageRow)-i;if(nearImageRow>=0){codeword=this.codewords[nearImageRow];if(codeword!=null){return codeword;}}nearImageRow=this.imageRowToCodewordIndex(imageRow)+i;if(nearImageRow<this.codewords.length){codeword=this.codewords[nearImageRow];if(codeword!=null){return codeword;}}}return null;}/*final int*/},{key:"imageRowToCodewordIndex",value:function imageRowToCodewordIndex(imageRow){return imageRow-this.boundingBox.getMinY();}/*final void*/},{key:"setCodeword",value:function setCodeword(imageRow,codeword){this.codewords[this.imageRowToCodewordIndex(imageRow)]=codeword;}/*final*/},{key:"getCodeword",value:function getCodeword(imageRow){return this.codewords[this.imageRowToCodewordIndex(imageRow)];}/*final*/},{key:"getBoundingBox",value:function getBoundingBox(){return this.boundingBox;}/*final*/},{key:"getCodewords",value:function getCodewords(){return this.codewords;}// @Override
},{key:"toString",value:function toString(){var formatter=new Formatter();var row=0;var _iterator55=_createForOfIteratorHelper(this.codewords),_step55;try{for(_iterator55.s();!(_step55=_iterator55.n()).done;){var codeword=_step55.value;if(codeword==null){formatter.format('%3d: | %n',row++);continue;}formatter.format('%3d: %3d|%3d%n',row++,codeword.getRowNumber(),codeword.getValue());}}catch(err){_iterator55.e(err);}finally{_iterator55.f();}return formatter.toString();}}]);return DetectionResultColumn;}();DetectionResultColumn.MAX_NEARBY_DISTANCE=5;/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ // import java.util.ArrayList;
// import java.util.Collection;
// import java.util.HashMap;
// import java.util.Map;
// import java.util.Map.Entry;
/**
* @author Guenther Grau
*/ /*final*/var BarcodeValue=/*#__PURE__*/function(){function BarcodeValue(){_classCallCheck(this,BarcodeValue);this.values=new Map();}/**
* Add an occurrence of a value
*/_createClass(BarcodeValue,[{key:"setValue",value:function setValue(value){value=Math.trunc(value);var confidence=this.values.get(value);if(confidence==null){confidence=0;}confidence++;this.values.set(value,confidence);}/**
* Determines the maximum occurrence of a set value and returns all values which were set with this occurrence.
* @return an array of int, containing the values with the highest occurrence, or null, if no value was set
*/},{key:"getValue",value:function getValue(){var maxConfidence=-1;var result=new Array();var _iterator56=_createForOfIteratorHelper(this.values.entries()),_step56;try{var _loop=function _loop(){var _step56$value=_slicedToArray(_step56.value,2),key=_step56$value[0],value=_step56$value[1];var entry={getKey:function getKey(){return key;},getValue:function getValue(){return value;}};if(entry.getValue()>maxConfidence){maxConfidence=entry.getValue();result=[];result.push(entry.getKey());}else if(entry.getValue()===maxConfidence){result.push(entry.getKey());}};for(_iterator56.s();!(_step56=_iterator56.n()).done;){_loop();}}catch(err){_iterator56.e(err);}finally{_iterator56.f();}return PDF417Common.toIntArray(result);}},{key:"getConfidence",value:function getConfidence(value){return this.values.get(value);}}]);return BarcodeValue;}();/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* @author Guenther Grau
*/ /*final*/var DetectionResultRowIndicatorColumn=/*#__PURE__*/function(_DetectionResultColum){_inherits(DetectionResultRowIndicatorColumn,_DetectionResultColum);var _super55=_createSuper(DetectionResultRowIndicatorColumn);function DetectionResultRowIndicatorColumn(boundingBox,isLeft){var _this36;_classCallCheck(this,DetectionResultRowIndicatorColumn);_this36=_super55.call(this,boundingBox);_this36._isLeft=isLeft;return _this36;}_createClass(DetectionResultRowIndicatorColumn,[{key:"setRowNumbers",value:function setRowNumbers(){var _iterator57=_createForOfIteratorHelper(this.getCodewords()),_step57;try{for(_iterator57.s();!(_step57=_iterator57.n()).done;){var codeword=_step57.value;if(codeword!=null){codeword.setRowNumberAsRowIndicatorColumn();}}}catch(err){_iterator57.e(err);}finally{_iterator57.f();}}// TODO implement properly
// TODO maybe we should add missing codewords to store the correct row number to make
// finding row numbers for other columns easier
// use row height count to make detection of invalid row numbers more reliable
},{key:"adjustCompleteIndicatorColumnRowNumbers",value:function adjustCompleteIndicatorColumnRowNumbers(barcodeMetadata){var codewords=this.getCodewords();this.setRowNumbers();this.removeIncorrectCodewords(codewords,barcodeMetadata);var boundingBox=this.getBoundingBox();var top=this._isLeft?boundingBox.getTopLeft():boundingBox.getTopRight();var bottom=this._isLeft?boundingBox.getBottomLeft():boundingBox.getBottomRight();var firstRow=this.imageRowToCodewordIndex(Math.trunc(top.getY()));var lastRow=this.imageRowToCodewordIndex(Math.trunc(bottom.getY()));// We need to be careful using the average row height. Barcode could be skewed so that we have smaller and
// taller rows
// float averageRowHeight = (lastRow - firstRow) / /*(float)*/ barcodeMetadata.getRowCount();
var barcodeRow=-1;var maxRowHeight=1;var currentRowHeight=0;for(var codewordsRow/*int*/=firstRow;codewordsRow<lastRow;codewordsRow++){if(codewords[codewordsRow]==null){continue;}var codeword=codewords[codewordsRow];// float expectedRowNumber = (codewordsRow - firstRow) / averageRowHeight;
// if (Math.abs(codeword.getRowNumber() - expectedRowNumber) > 2) {
// SimpleLog.log(LEVEL.WARNING,
// "Removing codeword, rowNumberSkew too high, codeword[" + codewordsRow + "]: Expected Row: " +
// expectedRowNumber + ", RealRow: " + codeword.getRowNumber() + ", value: " + codeword.getValue());
// codewords[codewordsRow] = null;
// }
var rowDifference=codeword.getRowNumber()-barcodeRow;// TODO improve handling with case where first row indicator doesn't start with 0
if(rowDifference===0){currentRowHeight++;}else if(rowDifference===1){maxRowHeight=Math.max(maxRowHeight,currentRowHeight);currentRowHeight=1;barcodeRow=codeword.getRowNumber();}else if(rowDifference<0||codeword.getRowNumber()>=barcodeMetadata.getRowCount()||rowDifference>codewordsRow){codewords[codewordsRow]=null;}else{var checkedRows=void 0;if(maxRowHeight>2){checkedRows=(maxRowHeight-2)*rowDifference;}else{checkedRows=rowDifference;}var closePreviousCodewordFound=checkedRows>=codewordsRow;for(var i/*int*/=1;i<=checkedRows&&!closePreviousCodewordFound;i++){// there must be (height * rowDifference) number of codewords missing. For now we assume height = 1.
// This should hopefully get rid of most problems already.
closePreviousCodewordFound=codewords[codewordsRow-i]!=null;}if(closePreviousCodewordFound){codewords[codewordsRow]=null;}else{barcodeRow=codeword.getRowNumber();currentRowHeight=1;}}}// return (int) (averageRowHeight + 0.5);
}},{key:"getRowHeights",value:function getRowHeights(){var barcodeMetadata=this.getBarcodeMetadata();if(barcodeMetadata==null){return null;}this.adjustIncompleteIndicatorColumnRowNumbers(barcodeMetadata);var result=new Int32Array(barcodeMetadata.getRowCount());var _iterator58=_createForOfIteratorHelper(this.getCodewords()),_step58;try{for(_iterator58.s();!(_step58=_iterator58.n()).done;){var codeword=_step58.value;if(codeword!=null){var rowNumber=codeword.getRowNumber();if(rowNumber>=result.length){// We have more rows than the barcode metadata allows for, ignore them.
continue;}result[rowNumber]++;}// else throw exception?
}}catch(err){_iterator58.e(err);}finally{_iterator58.f();}return result;}// TODO maybe we should add missing codewords to store the correct row number to make
// finding row numbers for other columns easier
// use row height count to make detection of invalid row numbers more reliable
},{key:"adjustIncompleteIndicatorColumnRowNumbers",value:function adjustIncompleteIndicatorColumnRowNumbers(barcodeMetadata){var boundingBox=this.getBoundingBox();var top=this._isLeft?boundingBox.getTopLeft():boundingBox.getTopRight();var bottom=this._isLeft?boundingBox.getBottomLeft():boundingBox.getBottomRight();var firstRow=this.imageRowToCodewordIndex(Math.trunc(top.getY()));var lastRow=this.imageRowToCodewordIndex(Math.trunc(bottom.getY()));// float averageRowHeight = (lastRow - firstRow) / /*(float)*/ barcodeMetadata.getRowCount();
var codewords=this.getCodewords();var barcodeRow=-1;for(var codewordsRow/*int*/=firstRow;codewordsRow<lastRow;codewordsRow++){if(codewords[codewordsRow]==null){continue;}var codeword=codewords[codewordsRow];codeword.setRowNumberAsRowIndicatorColumn();var rowDifference=codeword.getRowNumber()-barcodeRow;// TODO improve handling with case where first row indicator doesn't start with 0
if(rowDifference===0);else if(rowDifference===1){barcodeRow=codeword.getRowNumber();}else if(codeword.getRowNumber()>=barcodeMetadata.getRowCount()){codewords[codewordsRow]=null;}else{barcodeRow=codeword.getRowNumber();}}// return (int) (averageRowHeight + 0.5);
}},{key:"getBarcodeMetadata",value:function getBarcodeMetadata(){var codewords=this.getCodewords();var barcodeColumnCount=new BarcodeValue();var barcodeRowCountUpperPart=new BarcodeValue();var barcodeRowCountLowerPart=new BarcodeValue();var barcodeECLevel=new BarcodeValue();var _iterator59=_createForOfIteratorHelper(codewords),_step59;try{for(_iterator59.s();!(_step59=_iterator59.n()).done;){var codeword=_step59.value;if(codeword==null){continue;}codeword.setRowNumberAsRowIndicatorColumn();var rowIndicatorValue=codeword.getValue()%30;var codewordRowNumber=codeword.getRowNumber();if(!this._isLeft){codewordRowNumber+=2;}switch(codewordRowNumber%3){case 0:barcodeRowCountUpperPart.setValue(rowIndicatorValue*3+1);break;case 1:barcodeECLevel.setValue(rowIndicatorValue/3);barcodeRowCountLowerPart.setValue(rowIndicatorValue%3);break;case 2:barcodeColumnCount.setValue(rowIndicatorValue+1);break;}}// Maybe we should check if we have ambiguous values?
}catch(err){_iterator59.e(err);}finally{_iterator59.f();}if(barcodeColumnCount.getValue().length===0||barcodeRowCountUpperPart.getValue().length===0||barcodeRowCountLowerPart.getValue().length===0||barcodeECLevel.getValue().length===0||barcodeColumnCount.getValue()[0]<1||barcodeRowCountUpperPart.getValue()[0]+barcodeRowCountLowerPart.getValue()[0]<PDF417Common.MIN_ROWS_IN_BARCODE||barcodeRowCountUpperPart.getValue()[0]+barcodeRowCountLowerPart.getValue()[0]>PDF417Common.MAX_ROWS_IN_BARCODE){return null;}var barcodeMetadata=new BarcodeMetadata(barcodeColumnCount.getValue()[0],barcodeRowCountUpperPart.getValue()[0],barcodeRowCountLowerPart.getValue()[0],barcodeECLevel.getValue()[0]);this.removeIncorrectCodewords(codewords,barcodeMetadata);return barcodeMetadata;}},{key:"removeIncorrectCodewords",value:function removeIncorrectCodewords(codewords,barcodeMetadata){// Remove codewords which do not match the metadata
// TODO Maybe we should keep the incorrect codewords for the start and end positions?
for(var codewordRow/*int*/=0;codewordRow<codewords.length;codewordRow++){var codeword=codewords[codewordRow];if(codewords[codewordRow]==null){continue;}var rowIndicatorValue=codeword.getValue()%30;var codewordRowNumber=codeword.getRowNumber();if(codewordRowNumber>barcodeMetadata.getRowCount()){codewords[codewordRow]=null;continue;}if(!this._isLeft){codewordRowNumber+=2;}switch(codewordRowNumber%3){case 0:if(rowIndicatorValue*3+1!==barcodeMetadata.getRowCountUpperPart()){codewords[codewordRow]=null;}break;case 1:if(Math.trunc(rowIndicatorValue/3)!==barcodeMetadata.getErrorCorrectionLevel()||rowIndicatorValue%3!==barcodeMetadata.getRowCountLowerPart()){codewords[codewordRow]=null;}break;case 2:if(rowIndicatorValue+1!==barcodeMetadata.getColumnCount()){codewords[codewordRow]=null;}break;}}}},{key:"isLeft",value:function isLeft(){return this._isLeft;}// @Override
},{key:"toString",value:function toString(){return'IsLeft: '+this._isLeft+'\n'+_get(_getPrototypeOf(DetectionResultRowIndicatorColumn.prototype),"toString",this).call(this);}}]);return DetectionResultRowIndicatorColumn;}(DetectionResultColumn);/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* @author Guenther Grau
*/ /*final*/var DetectionResult=/*#__PURE__*/function(){function DetectionResult(barcodeMetadata,boundingBox){_classCallCheck(this,DetectionResult);/*final*/this.ADJUST_ROW_NUMBER_SKIP=2;this.barcodeMetadata=barcodeMetadata;this.barcodeColumnCount=barcodeMetadata.getColumnCount();this.boundingBox=boundingBox;// this.detectionResultColumns = new DetectionResultColumn[this.barcodeColumnCount + 2];
this.detectionResultColumns=new Array(this.barcodeColumnCount+2);}_createClass(DetectionResult,[{key:"getDetectionResultColumns",value:function getDetectionResultColumns(){this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[0]);this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[this.barcodeColumnCount+1]);var unadjustedCodewordCount=PDF417Common.MAX_CODEWORDS_IN_BARCODE;var previousUnadjustedCount;do{previousUnadjustedCount=unadjustedCodewordCount;unadjustedCodewordCount=this.adjustRowNumbersAndGetCount();}while(unadjustedCodewordCount>0&&unadjustedCodewordCount<previousUnadjustedCount);return this.detectionResultColumns;}},{key:"adjustIndicatorColumnRowNumbers",value:function adjustIndicatorColumnRowNumbers(detectionResultColumn){if(detectionResultColumn!=null){detectionResultColumn.adjustCompleteIndicatorColumnRowNumbers(this.barcodeMetadata);}}// TODO ensure that no detected codewords with unknown row number are left
// we should be able to estimate the row height and use it as a hint for the row number
// we should also fill the rows top to bottom and bottom to top
/**
* @return number of codewords which don't have a valid row number. Note that the count is not accurate as codewords
* will be counted several times. It just serves as an indicator to see when we can stop adjusting row numbers
*/},{key:"adjustRowNumbersAndGetCount",value:function adjustRowNumbersAndGetCount(){var unadjustedCount=this.adjustRowNumbersByRow();if(unadjustedCount===0){return 0;}for(var barcodeColumn/*int*/=1;barcodeColumn<this.barcodeColumnCount+1;barcodeColumn++){var codewords=this.detectionResultColumns[barcodeColumn].getCodewords();for(var codewordsRow/*int*/=0;codewordsRow<codewords.length;codewordsRow++){if(codewords[codewordsRow]==null){continue;}if(!codewords[codewordsRow].hasValidRowNumber()){this.adjustRowNumbers(barcodeColumn,codewordsRow,codewords);}}}return unadjustedCount;}},{key:"adjustRowNumbersByRow",value:function adjustRowNumbersByRow(){this.adjustRowNumbersFromBothRI();// TODO we should only do full row adjustments if row numbers of left and right row indicator column match.
// Maybe it's even better to calculated the height (rows: d) and divide it by the number of barcode
// rows. This, together with the LRI and RRI row numbers should allow us to get a good estimate where a row
// number starts and ends.
var unadjustedCount=this.adjustRowNumbersFromLRI();return unadjustedCount+this.adjustRowNumbersFromRRI();}},{key:"adjustRowNumbersFromBothRI",value:function adjustRowNumbersFromBothRI(){if(this.detectionResultColumns[0]==null||this.detectionResultColumns[this.barcodeColumnCount+1]==null){return;}var LRIcodewords=this.detectionResultColumns[0].getCodewords();var RRIcodewords=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(var codewordsRow/*int*/=0;codewordsRow<LRIcodewords.length;codewordsRow++){if(LRIcodewords[codewordsRow]!=null&&RRIcodewords[codewordsRow]!=null&&LRIcodewords[codewordsRow].getRowNumber()===RRIcodewords[codewordsRow].getRowNumber()){for(var barcodeColumn/*int*/=1;barcodeColumn<=this.barcodeColumnCount;barcodeColumn++){var codeword=this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];if(codeword==null){continue;}codeword.setRowNumber(LRIcodewords[codewordsRow].getRowNumber());if(!codeword.hasValidRowNumber()){this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow]=null;}}}}}},{key:"adjustRowNumbersFromRRI",value:function adjustRowNumbersFromRRI(){if(this.detectionResultColumns[this.barcodeColumnCount+1]==null){return 0;}var unadjustedCount=0;var codewords=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(var codewordsRow/*int*/=0;codewordsRow<codewords.length;codewordsRow++){if(codewords[codewordsRow]==null){continue;}var rowIndicatorRowNumber=codewords[codewordsRow].getRowNumber();var invalidRowCounts=0;for(var barcodeColumn/*int*/=this.barcodeColumnCount+1;barcodeColumn>0&&invalidRowCounts<this.ADJUST_ROW_NUMBER_SKIP;barcodeColumn--){var codeword=this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];if(codeword!=null){invalidRowCounts=DetectionResult.adjustRowNumberIfValid(rowIndicatorRowNumber,invalidRowCounts,codeword);if(!codeword.hasValidRowNumber()){unadjustedCount++;}}}}return unadjustedCount;}},{key:"adjustRowNumbersFromLRI",value:function adjustRowNumbersFromLRI(){if(this.detectionResultColumns[0]==null){return 0;}var unadjustedCount=0;var codewords=this.detectionResultColumns[0].getCodewords();for(var codewordsRow/*int*/=0;codewordsRow<codewords.length;codewordsRow++){if(codewords[codewordsRow]==null){continue;}var rowIndicatorRowNumber=codewords[codewordsRow].getRowNumber();var invalidRowCounts=0;for(var barcodeColumn/*int*/=1;barcodeColumn<this.barcodeColumnCount+1&&invalidRowCounts<this.ADJUST_ROW_NUMBER_SKIP;barcodeColumn++){var codeword=this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];if(codeword!=null){invalidRowCounts=DetectionResult.adjustRowNumberIfValid(rowIndicatorRowNumber,invalidRowCounts,codeword);if(!codeword.hasValidRowNumber()){unadjustedCount++;}}}}return unadjustedCount;}},{key:"adjustRowNumbers",value:function adjustRowNumbers(barcodeColumn,codewordsRow,codewords){if(!this.detectionResultColumns[barcodeColumn-1]){return;}var codeword=codewords[codewordsRow];var previousColumnCodewords=this.detectionResultColumns[barcodeColumn-1].getCodewords();var nextColumnCodewords=previousColumnCodewords;if(this.detectionResultColumns[barcodeColumn+1]!=null){nextColumnCodewords=this.detectionResultColumns[barcodeColumn+1].getCodewords();}// let otherCodewords: Codeword[] = new Codeword[14];
var otherCodewords=new Array(14);otherCodewords[2]=previousColumnCodewords[codewordsRow];otherCodewords[3]=nextColumnCodewords[codewordsRow];if(codewordsRow>0){otherCodewords[0]=codewords[codewordsRow-1];otherCodewords[4]=previousColumnCodewords[codewordsRow-1];otherCodewords[5]=nextColumnCodewords[codewordsRow-1];}if(codewordsRow>1){otherCodewords[8]=codewords[codewordsRow-2];otherCodewords[10]=previousColumnCodewords[codewordsRow-2];otherCodewords[11]=nextColumnCodewords[codewordsRow-2];}if(codewordsRow<codewords.length-1){otherCodewords[1]=codewords[codewordsRow+1];otherCodewords[6]=previousColumnCodewords[codewordsRow+1];otherCodewords[7]=nextColumnCodewords[codewordsRow+1];}if(codewordsRow<codewords.length-2){otherCodewords[9]=codewords[codewordsRow+2];otherCodewords[12]=previousColumnCodewords[codewordsRow+2];otherCodewords[13]=nextColumnCodewords[codewordsRow+2];}for(var _i35=0,_otherCodewords=otherCodewords;_i35<_otherCodewords.length;_i35++){var otherCodeword=_otherCodewords[_i35];if(DetectionResult.adjustRowNumber(codeword,otherCodeword)){return;}}}/**
* @return true, if row number was adjusted, false otherwise
*/},{key:"getBarcodeColumnCount",value:function getBarcodeColumnCount(){return this.barcodeColumnCount;}},{key:"getBarcodeRowCount",value:function getBarcodeRowCount(){return this.barcodeMetadata.getRowCount();}},{key:"getBarcodeECLevel",value:function getBarcodeECLevel(){return this.barcodeMetadata.getErrorCorrectionLevel();}},{key:"setBoundingBox",value:function setBoundingBox(boundingBox){this.boundingBox=boundingBox;}},{key:"getBoundingBox",value:function getBoundingBox(){return this.boundingBox;}},{key:"setDetectionResultColumn",value:function setDetectionResultColumn(barcodeColumn,detectionResultColumn){this.detectionResultColumns[barcodeColumn]=detectionResultColumn;}},{key:"getDetectionResultColumn",value:function getDetectionResultColumn(barcodeColumn){return this.detectionResultColumns[barcodeColumn];}// @Override
},{key:"toString",value:function toString(){var rowIndicatorColumn=this.detectionResultColumns[0];if(rowIndicatorColumn==null){rowIndicatorColumn=this.detectionResultColumns[this.barcodeColumnCount+1];}// try (
var formatter=new Formatter();// ) {
for(var codewordsRow/*int*/=0;codewordsRow<rowIndicatorColumn.getCodewords().length;codewordsRow++){formatter.format('CW %3d:',codewordsRow);for(var barcodeColumn/*int*/=0;barcodeColumn<this.barcodeColumnCount+2;barcodeColumn++){if(this.detectionResultColumns[barcodeColumn]==null){formatter.format(' | ');continue;}var codeword=this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];if(codeword==null){formatter.format(' | ');continue;}formatter.format(' %3d|%3d',codeword.getRowNumber(),codeword.getValue());}formatter.format('%n');}return formatter.toString();// }
}}],[{key:"adjustRowNumberIfValid",value:function adjustRowNumberIfValid(rowIndicatorRowNumber,invalidRowCounts,codeword){if(codeword==null){return invalidRowCounts;}if(!codeword.hasValidRowNumber()){if(codeword.isValidRowNumber(rowIndicatorRowNumber)){codeword.setRowNumber(rowIndicatorRowNumber);invalidRowCounts=0;}else{++invalidRowCounts;}}return invalidRowCounts;}},{key:"adjustRowNumber",value:function adjustRowNumber(codeword,otherCodeword){if(otherCodeword==null){return false;}if(otherCodeword.hasValidRowNumber()&&otherCodeword.getBucket()===codeword.getBucket()){codeword.setRowNumber(otherCodeword.getRowNumber());return true;}return false;}}]);return DetectionResult;}();/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ // package com.google.zxing.pdf417.decoder;
/**
* @author Guenther Grau
*/ /*final*/var Codeword=/*#__PURE__*/function(){function Codeword(startX,endX,bucket,value){_classCallCheck(this,Codeword);this.rowNumber=Codeword.BARCODE_ROW_UNKNOWN;this.startX=Math.trunc(startX);this.endX=Math.trunc(endX);this.bucket=Math.trunc(bucket);this.value=Math.trunc(value);}_createClass(Codeword,[{key:"hasValidRowNumber",value:function hasValidRowNumber(){return this.isValidRowNumber(this.rowNumber);}},{key:"isValidRowNumber",value:function isValidRowNumber(rowNumber){return rowNumber!==Codeword.BARCODE_ROW_UNKNOWN&&this.bucket===rowNumber%3*3;}},{key:"setRowNumberAsRowIndicatorColumn",value:function setRowNumberAsRowIndicatorColumn(){this.rowNumber=Math.trunc(Math.trunc(this.value/30)*3+Math.trunc(this.bucket/3));}},{key:"getWidth",value:function getWidth(){return this.endX-this.startX;}},{key:"getStartX",value:function getStartX(){return this.startX;}},{key:"getEndX",value:function getEndX(){return this.endX;}},{key:"getBucket",value:function getBucket(){return this.bucket;}},{key:"getValue",value:function getValue(){return this.value;}},{key:"getRowNumber",value:function getRowNumber(){return this.rowNumber;}},{key:"setRowNumber",value:function setRowNumber(rowNumber){this.rowNumber=rowNumber;}// @Override
},{key:"toString",value:function toString(){return this.rowNumber+'|'+this.value;}}]);return Codeword;}();Codeword.BARCODE_ROW_UNKNOWN=-1;/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* @author Guenther Grau
* @author creatale GmbH (christoph.schulz@creatale.de)
*/ /*final*/var PDF417CodewordDecoder=/*#__PURE__*/function(){function PDF417CodewordDecoder(){_classCallCheck(this,PDF417CodewordDecoder);}_createClass(PDF417CodewordDecoder,null,[{key:"initialize",value:/* @note
* this action have to be performed before first use of class
* - static constructor
* working with 32bit float (based from Java logic)
*/function initialize(){// Pre-computes the symbol ratio table.
for(/*int*/var i=0;i<PDF417Common.SYMBOL_TABLE.length;i++){var currentSymbol=PDF417Common.SYMBOL_TABLE[i];var currentBit=currentSymbol&0x1;for(/*int*/var j=0;j<PDF417Common.BARS_IN_MODULE;j++){var size=0.0;while((currentSymbol&0x1)===currentBit){size+=1.0;currentSymbol>>=1;}currentBit=currentSymbol&0x1;if(!PDF417CodewordDecoder.RATIOS_TABLE[i]){PDF417CodewordDecoder.RATIOS_TABLE[i]=new Array(PDF417Common.BARS_IN_MODULE);}PDF417CodewordDecoder.RATIOS_TABLE[i][PDF417Common.BARS_IN_MODULE-j-1]=Math.fround(size/PDF417Common.MODULES_IN_CODEWORD);}}this.bSymbolTableReady=true;}},{key:"getDecodedValue",value:function getDecodedValue(moduleBitCount){var decodedValue=PDF417CodewordDecoder.getDecodedCodewordValue(PDF417CodewordDecoder.sampleBitCounts(moduleBitCount));if(decodedValue!==-1){return decodedValue;}return PDF417CodewordDecoder.getClosestDecodedValue(moduleBitCount);}},{key:"sampleBitCounts",value:function sampleBitCounts(moduleBitCount){var bitCountSum=MathUtils.sum(moduleBitCount);var result=new Int32Array(PDF417Common.BARS_IN_MODULE);var bitCountIndex=0;var sumPreviousBits=0;for(/*int*/var i=0;i<PDF417Common.MODULES_IN_CODEWORD;i++){var sampleIndex=bitCountSum/(2*PDF417Common.MODULES_IN_CODEWORD)+i*bitCountSum/PDF417Common.MODULES_IN_CODEWORD;if(sumPreviousBits+moduleBitCount[bitCountIndex]<=sampleIndex){sumPreviousBits+=moduleBitCount[bitCountIndex];bitCountIndex++;}result[bitCountIndex]++;}return result;}},{key:"getDecodedCodewordValue",value:function getDecodedCodewordValue(moduleBitCount){var decodedValue=PDF417CodewordDecoder.getBitValue(moduleBitCount);return PDF417Common.getCodeword(decodedValue)===-1?-1:decodedValue;}},{key:"getBitValue",value:function getBitValue(moduleBitCount){var result=/*long*/0;for(var/*int*/i=0;i<moduleBitCount.length;i++){for(/*int*/var bit=0;bit<moduleBitCount[i];bit++){result=result<<1|(i%2===0?1:0);}}return Math.trunc(result);}// working with 32bit float (as in Java)
},{key:"getClosestDecodedValue",value:function getClosestDecodedValue(moduleBitCount){var bitCountSum=MathUtils.sum(moduleBitCount);var bitCountRatios=new Array(PDF417Common.BARS_IN_MODULE);if(bitCountSum>1){for(var/*int*/i=0;i<bitCountRatios.length;i++){bitCountRatios[i]=Math.fround(moduleBitCount[i]/bitCountSum);}}var bestMatchError=Float.MAX_VALUE;var bestMatch=-1;if(!this.bSymbolTableReady){PDF417CodewordDecoder.initialize();}for(/*int*/var j=0;j<PDF417CodewordDecoder.RATIOS_TABLE.length;j++){var error=0.0;var ratioTableRow=PDF417CodewordDecoder.RATIOS_TABLE[j];for(/*int*/var k=0;k<PDF417Common.BARS_IN_MODULE;k++){var diff=Math.fround(ratioTableRow[k]-bitCountRatios[k]);error+=Math.fround(diff*diff);if(error>=bestMatchError){break;}}if(error<bestMatchError){bestMatchError=error;bestMatch=PDF417Common.SYMBOL_TABLE[j];}}return bestMatch;}}]);return PDF417CodewordDecoder;}();// flag that the table is ready for use
PDF417CodewordDecoder.bSymbolTableReady=false;PDF417CodewordDecoder.RATIOS_TABLE=new Array(PDF417Common.SYMBOL_TABLE.length).map(function(x){return x=new Array(PDF417Common.BARS_IN_MODULE);});/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ // package com.google.zxing.pdf417;
/**
* @author Guenther Grau
*/ /*public final*/var PDF417ResultMetadata=/*#__PURE__*/function(){function PDF417ResultMetadata(){_classCallCheck(this,PDF417ResultMetadata);this.segmentCount=-1;this.fileSize=-1;this.timestamp=-1;this.checksum=-1;}/**
* The Segment ID represents the segment of the whole file distributed over different symbols.
*
* @return File segment index
*/_createClass(PDF417ResultMetadata,[{key:"getSegmentIndex",value:function getSegmentIndex(){return this.segmentIndex;}},{key:"setSegmentIndex",value:function setSegmentIndex(segmentIndex){this.segmentIndex=segmentIndex;}/**
* Is the same for each related PDF417 symbol
*
* @return File ID
*/},{key:"getFileId",value:function getFileId(){return this.fileId;}},{key:"setFileId",value:function setFileId(fileId){this.fileId=fileId;}/**
* @return always null
* @deprecated use dedicated already parsed fields
*/ // @Deprecated
},{key:"getOptionalData",value:function getOptionalData(){return this.optionalData;}/**
* @param optionalData old optional data format as int array
* @deprecated parse and use new fields
*/ // @Deprecated
},{key:"setOptionalData",value:function setOptionalData(optionalData){this.optionalData=optionalData;}/**
* @return true if it is the last segment
*/},{key:"isLastSegment",value:function isLastSegment(){return this.lastSegment;}},{key:"setLastSegment",value:function setLastSegment(lastSegment){this.lastSegment=lastSegment;}/**
* @return count of segments, -1 if not set
*/},{key:"getSegmentCount",value:function getSegmentCount(){return this.segmentCount;}},{key:"setSegmentCount",value:function setSegmentCount(segmentCount/*int*/){this.segmentCount=segmentCount;}},{key:"getSender",value:function getSender(){return this.sender||null;}},{key:"setSender",value:function setSender(sender){this.sender=sender;}},{key:"getAddressee",value:function getAddressee(){return this.addressee||null;}},{key:"setAddressee",value:function setAddressee(addressee){this.addressee=addressee;}/**
* Filename of the encoded file
*
* @return filename
*/},{key:"getFileName",value:function getFileName(){return this.fileName;}},{key:"setFileName",value:function setFileName(fileName){this.fileName=fileName;}/**
* filesize in bytes of the encoded file
*
* @return filesize in bytes, -1 if not set
*/},{key:"getFileSize",value:function getFileSize(){return this.fileSize;}},{key:"setFileSize",value:function setFileSize(fileSize/*long*/){this.fileSize=fileSize;}/**
* 16-bit CRC checksum using CCITT-16
*
* @return crc checksum, -1 if not set
*/},{key:"getChecksum",value:function getChecksum(){return this.checksum;}},{key:"setChecksum",value:function setChecksum(checksum/*int*/){this.checksum=checksum;}/**
* unix epock timestamp, elapsed seconds since 1970-01-01
*
* @return elapsed seconds, -1 if not set
*/},{key:"getTimestamp",value:function getTimestamp(){return this.timestamp;}},{key:"setTimestamp",value:function setTimestamp(timestamp/*long*/){this.timestamp=timestamp;}}]);return PDF417ResultMetadata;}();/**
* Ponyfill for Java's Long class.
*/var Long=/*#__PURE__*/function(){function Long(){_classCallCheck(this,Long);}_createClass(Long,null,[{key:"parseLong",value:/**
* Parses a string to a number, since JS has no really Int64.
*
* @param num Numeric string.
* @param radix Destination radix.
*/function parseLong(num){var radix=arguments.length>1&&arguments[1]!==undefined?arguments[1]:undefined;return parseInt(num,radix);}}]);return Long;}();/**
* Custom Error class of type Exception.
*/var NullPointerException=/*#__PURE__*/function(_Exception11){_inherits(NullPointerException,_Exception11);var _super56=_createSuper(NullPointerException);function NullPointerException(){_classCallCheck(this,NullPointerException);return _super56.apply(this,arguments);}return _createClass(NullPointerException);}(Exception);NullPointerException.kind='NullPointerException';/*
* Copyright (c) 1994, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/ // package java.io;
/**
* This abstract class is the superclass of all classes representing
* an output stream of bytes. An output stream accepts output bytes
* and sends them to some sink.
* <p>
* Applications that need to define a subclass of
* <code>OutputStream</code> must always provide at least a method
* that writes one byte of output.
*
* @author Arthur van Hoff
* @see java.io.BufferedOutputStream
* @see java.io.ByteArrayOutputStream
* @see java.io.DataOutputStream
* @see java.io.FilterOutputStream
* @see java.io.InputStream
* @see java.io.OutputStream#write(int)
* @since JDK1.0
*/ /*public*/var OutputStream/*implements Closeable, Flushable*/=/*#__PURE__*/function(){function OutputStream(){_classCallCheck(this,OutputStream);}_createClass(OutputStream,[{key:"writeBytes",value:/**
* Writes <code>b.length</code> bytes from the specified byte array
* to this output stream. The general contract for <code>write(b)</code>
* is that it should have exactly the same effect as the call
* <code>write(b, 0, b.length)</code>.
*
* @param b the data.
* @exception IOException if an I/O error occurs.
* @see java.io.OutputStream#write(byte[], int, int)
*/function writeBytes(b){this.writeBytesOffset(b,0,b.length);}/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this output stream.
* The general contract for <code>write(b, off, len)</code> is that
* some of the bytes in the array <code>b</code> are written to the
* output stream in order; element <code>b[off]</code> is the first
* byte written and <code>b[off+len-1]</code> is the last byte written
* by this operation.
* <p>
* The <code>write</code> method of <code>OutputStream</code> calls
* the write method of one argument on each of the bytes to be
* written out. Subclasses are encouraged to override this method and
* provide a more efficient implementation.
* <p>
* If <code>b</code> is <code>null</code>, a
* <code>NullPointerException</code> is thrown.
* <p>
* If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, then an <tt>IndexOutOfBoundsException</tt> is thrown.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs. In particular,
* an <code>IOException</code> is thrown if the output
* stream is closed.
*/},{key:"writeBytesOffset",value:function writeBytesOffset(b,off,len){if(b==null){throw new NullPointerException();}else if(off<0||off>b.length||len<0||off+len>b.length||off+len<0){throw new IndexOutOfBoundsException();}else if(len===0){return;}for(var i=0;i<len;i++){this.write(b[off+i]);}}/**
* Flushes this output stream and forces any buffered output bytes
* to be written out. The general contract of <code>flush</code> is
* that calling it is an indication that, if any bytes previously
* written have been buffered by the implementation of the output
* stream, such bytes should immediately be written to their
* intended destination.
* <p>
* If the intended destination of this stream is an abstraction provided by
* the underlying operating system, for example a file, then flushing the
* stream guarantees only that bytes previously written to the stream are
* passed to the operating system for writing; it does not guarantee that
* they are actually written to a physical device such as a disk drive.
* <p>
* The <code>flush</code> method of <code>OutputStream</code> does nothing.
*
* @exception IOException if an I/O error occurs.
*/},{key:"flush",value:function flush(){}/**
* Closes this output stream and releases any system resources
* associated with this stream. The general contract of <code>close</code>
* is that it closes the output stream. A closed stream cannot perform
* output operations and cannot be reopened.
* <p>
* The <code>close</code> method of <code>OutputStream</code> does nothing.
*
* @exception IOException if an I/O error occurs.
*/},{key:"close",value:function close(){}}]);return OutputStream;}();/**
* Custom Error class of type Exception.
*/var OutOfMemoryError=/*#__PURE__*/function(_Exception12){_inherits(OutOfMemoryError,_Exception12);var _super57=_createSuper(OutOfMemoryError);function OutOfMemoryError(){_classCallCheck(this,OutOfMemoryError);return _super57.apply(this,arguments);}return _createClass(OutOfMemoryError);}(Exception);/*
* Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/ /**
* This class implements an output stream in which the data is
* written into a byte array. The buffer automatically grows as data
* is written to it.
* The data can be retrieved using <code>toByteArray()</code> and
* <code>toString()</code>.
* <p>
* Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
* this class can be called after the stream has been closed without
* generating an <tt>IOException</tt>.
*
* @author Arthur van Hoff
* @since JDK1.0
*/ /*public*/var ByteArrayOutputStream=/*#__PURE__*/function(_OutputStream){_inherits(ByteArrayOutputStream,_OutputStream);var _super58=_createSuper(ByteArrayOutputStream);/**
* Creates a new byte array output stream. The buffer capacity is
* initially 32 bytes, though its size increases if necessary.
*/ // public constructor() {
// this(32);
// }
/**
* Creates a new byte array output stream, with a buffer capacity of
* the specified size, in bytes.
*
* @param size the initial size.
* @exception IllegalArgumentException if size is negative.
*/function ByteArrayOutputStream(){var _this37;var size=arguments.length>0&&arguments[0]!==undefined?arguments[0]:32;_classCallCheck(this,ByteArrayOutputStream);_this37=_super58.call(this);/**
* The number of valid bytes in the buffer.
*/_this37.count=0;if(size<0){throw new IllegalArgumentException('Negative initial size: '+size);}_this37.buf=new Uint8Array(size);return _this37;}/**
* Increases the capacity if necessary to ensure that it can hold
* at least the number of elements specified by the minimum
* capacity argument.
*
* @param minCapacity the desired minimum capacity
* @throws OutOfMemoryError if {@code minCapacity < 0}. This is
* interpreted as a request for the unsatisfiably large capacity
* {@code (long) Integer.MAX_VALUE + (minCapacity - Integer.MAX_VALUE)}.
*/_createClass(ByteArrayOutputStream,[{key:"ensureCapacity",value:function ensureCapacity(minCapacity){// overflow-conscious code
if(minCapacity-this.buf.length>0)this.grow(minCapacity);}/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/},{key:"grow",value:function grow(minCapacity){// overflow-conscious code
var oldCapacity=this.buf.length;var newCapacity=oldCapacity<<1;if(newCapacity-minCapacity<0)newCapacity=minCapacity;if(newCapacity<0){if(minCapacity<0)// overflow
throw new OutOfMemoryError();newCapacity=Integer.MAX_VALUE;}this.buf=Arrays.copyOfUint8Array(this.buf,newCapacity);}/**
* Writes the specified byte to this byte array output stream.
*
* @param b the byte to be written.
*/},{key:"write",value:function write(b){this.ensureCapacity(this.count+1);this.buf[this.count]=/*(byte)*/b;this.count+=1;}/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this byte array output stream.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
*/},{key:"writeBytesOffset",value:function writeBytesOffset(b,off,len){if(off<0||off>b.length||len<0||off+len-b.length>0){throw new IndexOutOfBoundsException();}this.ensureCapacity(this.count+len);System.arraycopy(b,off,this.buf,this.count,len);this.count+=len;}/**
* Writes the complete contents of this byte array output stream to
* the specified output stream argument, as if by calling the output
* stream's write method using <code>out.write(buf, 0, count)</code>.
*
* @param out the output stream to which to write the data.
* @exception IOException if an I/O error occurs.
*/},{key:"writeTo",value:function writeTo(out){out.writeBytesOffset(this.buf,0,this.count);}/**
* Resets the <code>count</code> field of this byte array output
* stream to zero, so that all currently accumulated output in the
* output stream is discarded. The output stream can be used again,
* reusing the already allocated buffer space.
*
* @see java.io.ByteArrayInputStream#count
*/},{key:"reset",value:function reset(){this.count=0;}/**
* Creates a newly allocated byte array. Its size is the current
* size of this output stream and the valid contents of the buffer
* have been copied into it.
*
* @return the current contents of this output stream, as a byte array.
* @see java.io.ByteArrayOutputStream#size()
*/},{key:"toByteArray",value:function toByteArray(){return Arrays.copyOfUint8Array(this.buf,this.count);}/**
* Returns the current size of the buffer.
*
* @return the value of the <code>count</code> field, which is the number
* of valid bytes in this output stream.
* @see java.io.ByteArrayOutputStream#count
*/},{key:"size",value:function size(){return this.count;}},{key:"toString",value:function toString(param){if(!param){return this.toString_void();}if(typeof param==='string'){return this.toString_string(param);}return this.toString_number(param);}/**
* Converts the buffer's contents into a string decoding bytes using the
* platform's default character set. The length of the new <tt>String</tt>
* is a function of the character set, and hence may not be equal to the
* size of the buffer.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with the default replacement string for the platform's
* default character set. The {@linkplain java.nio.charset.CharsetDecoder}
* class should be used when more control over the decoding process is
* required.
*
* @return String decoded from the buffer's contents.
* @since JDK1.1
*/},{key:"toString_void",value:function toString_void(){return new String(this.buf/*, 0, this.count*/).toString();}/**
* Converts the buffer's contents into a string by decoding the bytes using
* the specified {@link java.nio.charset.Charset charsetName}. The length of
* the new <tt>String</tt> is a function of the charset, and hence may not be
* equal to the length of the byte array.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* @param charsetName the name of a supported
* {@linkplain java.nio.charset.Charset </code>charset<code>}
* @return String decoded from the buffer's contents.
* @exception UnsupportedEncodingException
* If the named charset is not supported
* @since JDK1.1
*/},{key:"toString_string",value:function toString_string(charsetName){return new String(this.buf/*, 0, this.count, charsetName*/).toString();}/**
* Creates a newly allocated string. Its size is the current size of
* the output stream and the valid contents of the buffer have been
* copied into it. Each character <i>c</i> in the resulting string is
* constructed from the corresponding element <i>b</i> in the byte
* array such that:
* <blockquote><pre>
* c == (char)(((hibyte &amp; 0xff) &lt;&lt; 8) | (b &amp; 0xff))
* </pre></blockquote>
*
* @deprecated This method does not properly convert bytes into characters.
* As of JDK&nbsp;1.1, the preferred way to do this is via the
* <code>toString(String enc)</code> method, which takes an encoding-name
* argument, or the <code>toString()</code> method, which uses the
* platform's default character encoding.
*
* @param hibyte the high byte of each resulting Unicode character.
* @return the current contents of the output stream, as a string.
* @see java.io.ByteArrayOutputStream#size()
* @see java.io.ByteArrayOutputStream#toString(String)
* @see java.io.ByteArrayOutputStream#toString()
*/ // @Deprecated
},{key:"toString_number",value:function toString_number(hibyte){return new String(this.buf/*, hibyte, 0, this.count*/).toString();}/**
* Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
* this class can be called after the stream has been closed without
* generating an <tt>IOException</tt>.
* <p>
*
* @throws IOException
*/},{key:"close",value:function close(){}}]);return ByteArrayOutputStream;}(OutputStream);/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*private*/var Mode$2;(function(Mode){Mode[Mode["ALPHA"]=0]="ALPHA";Mode[Mode["LOWER"]=1]="LOWER";Mode[Mode["MIXED"]=2]="MIXED";Mode[Mode["PUNCT"]=3]="PUNCT";Mode[Mode["ALPHA_SHIFT"]=4]="ALPHA_SHIFT";Mode[Mode["PUNCT_SHIFT"]=5]="PUNCT_SHIFT";})(Mode$2||(Mode$2={}));/**
* Indirectly access the global BigInt constructor, it
* allows browsers that doesn't support BigInt to run
* the library without breaking due to "undefined BigInt"
* errors.
*/function getBigIntConstructor(){if(typeof window!=='undefined'){return window['BigInt']||null;}if(typeof global!=='undefined'){return global['BigInt']||null;}if(typeof self!=='undefined'){return self['BigInt']||null;}throw new Error('Can\'t search globals for BigInt!');}/**
* Used to store the BigInt constructor.
*/var BigInteger;/**
* This function creates a bigint value. It allows browsers
* that doesn't support BigInt to run the rest of the library
* by not directly accessing the BigInt constructor.
*/function createBigInt(num){if(typeof BigInteger==='undefined'){BigInteger=getBigIntConstructor();}if(BigInteger===null){throw new Error('BigInt is not supported!');}return BigInteger(num);}function getEXP900(){// in Java - array with length = 16
var EXP900=[];EXP900[0]=createBigInt(1);var nineHundred=createBigInt(900);EXP900[1]=nineHundred;// in Java - array with length = 16
for(var i/*int*/=2;i<16;i++){EXP900[i]=EXP900[i-1]*nineHundred;}return EXP900;}/**
* <p>This class contains the methods for decoding the PDF417 codewords.</p>
*
* @author SITA Lab (kevin.osullivan@sita.aero)
* @author Guenther Grau
*/ /*final*/var DecodedBitStreamParser$2=/*#__PURE__*/function(){function DecodedBitStreamParser$2(){_classCallCheck(this,DecodedBitStreamParser$2);}_createClass(DecodedBitStreamParser$2,null,[{key:"decode",value:// private DecodedBitStreamParser() {
// }
/**
*
* @param codewords
* @param ecLevel
*
* @throws FormatException
*/function decode(codewords,ecLevel){// pass encoding to result (will be used for decode symbols in byte mode)
var result=new StringBuilder('');// let encoding: Charset = StandardCharsets.ISO_8859_1;
var encoding=CharacterSetECI.ISO8859_1;/**
* @note the next command is specific from this TypeScript library
* because TS can't properly cast some values to char and
* convert it to string later correctly due to encoding
* differences from Java version. As reported here:
* https://github.com/zxing-js/library/pull/264/files#r382831593
*/result.enableDecoding(encoding);// Get compaction mode
var codeIndex=1;var code=codewords[codeIndex++];var resultMetadata=new PDF417ResultMetadata();while(codeIndex<codewords[0]){switch(code){case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:codeIndex=DecodedBitStreamParser$2.textCompaction(codewords,codeIndex,result);break;case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:codeIndex=DecodedBitStreamParser$2.byteCompaction(code,codewords,encoding,codeIndex,result);break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:result.append(/*(char)*/codewords[codeIndex++]);break;case DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH:codeIndex=DecodedBitStreamParser$2.numericCompaction(codewords,codeIndex,result);break;case DecodedBitStreamParser$2.ECI_CHARSET:var charsetECI=CharacterSetECI.getCharacterSetECIByValue(codewords[codeIndex++]);// encoding = Charset.forName(charsetECI.getName());
break;case DecodedBitStreamParser$2.ECI_GENERAL_PURPOSE:// Can't do anything with generic ECI; skip its 2 characters
codeIndex+=2;break;case DecodedBitStreamParser$2.ECI_USER_DEFINED:// Can't do anything with user ECI; skip its 1 character
codeIndex++;break;case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:codeIndex=DecodedBitStreamParser$2.decodeMacroBlock(codewords,codeIndex,resultMetadata);break;case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:// Should not see these outside a macro block
throw new FormatException();default:// Default to text compaction. During testing numerous barcodes
// appeared to be missing the starting mode. In these cases defaulting
// to text compaction seems to work.
codeIndex--;codeIndex=DecodedBitStreamParser$2.textCompaction(codewords,codeIndex,result);break;}if(codeIndex<codewords.length){code=codewords[codeIndex++];}else{throw FormatException.getFormatInstance();}}if(result.length()===0){throw FormatException.getFormatInstance();}var decoderResult=new DecoderResult(null,result.toString(),null,ecLevel);decoderResult.setOther(resultMetadata);return decoderResult;}/**
*
* @param int
* @param param1
* @param codewords
* @param int
* @param codeIndex
* @param PDF417ResultMetadata
* @param resultMetadata
*
* @throws FormatException
*/ // @SuppressWarnings("deprecation")
},{key:"decodeMacroBlock",value:function decodeMacroBlock(codewords,codeIndex,resultMetadata){if(codeIndex+DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS>codewords[0]){// we must have at least two bytes left for the segment index
throw FormatException.getFormatInstance();}var segmentIndexArray=new Int32Array(DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS);for(var i/*int*/=0;i<DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS;i++,codeIndex++){segmentIndexArray[i]=codewords[codeIndex];}resultMetadata.setSegmentIndex(Integer.parseInt(DecodedBitStreamParser$2.decodeBase900toBase10(segmentIndexArray,DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS)));var fileId=new StringBuilder();codeIndex=DecodedBitStreamParser$2.textCompaction(codewords,codeIndex,fileId);resultMetadata.setFileId(fileId.toString());var optionalFieldsStart=-1;if(codewords[codeIndex]===DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD){optionalFieldsStart=codeIndex+1;}while(codeIndex<codewords[0]){switch(codewords[codeIndex]){case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:codeIndex++;switch(codewords[codeIndex]){case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME:var fileName=new StringBuilder();codeIndex=DecodedBitStreamParser$2.textCompaction(codewords,codeIndex+1,fileName);resultMetadata.setFileName(fileName.toString());break;case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_SENDER:var sender=new StringBuilder();codeIndex=DecodedBitStreamParser$2.textCompaction(codewords,codeIndex+1,sender);resultMetadata.setSender(sender.toString());break;case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:var addressee=new StringBuilder();codeIndex=DecodedBitStreamParser$2.textCompaction(codewords,codeIndex+1,addressee);resultMetadata.setAddressee(addressee.toString());break;case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:var segmentCount=new StringBuilder();codeIndex=DecodedBitStreamParser$2.numericCompaction(codewords,codeIndex+1,segmentCount);resultMetadata.setSegmentCount(Integer.parseInt(segmentCount.toString()));break;case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:var timestamp=new StringBuilder();codeIndex=DecodedBitStreamParser$2.numericCompaction(codewords,codeIndex+1,timestamp);resultMetadata.setTimestamp(Long.parseLong(timestamp.toString()));break;case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:var checksum=new StringBuilder();codeIndex=DecodedBitStreamParser$2.numericCompaction(codewords,codeIndex+1,checksum);resultMetadata.setChecksum(Integer.parseInt(checksum.toString()));break;case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:var fileSize=new StringBuilder();codeIndex=DecodedBitStreamParser$2.numericCompaction(codewords,codeIndex+1,fileSize);resultMetadata.setFileSize(Long.parseLong(fileSize.toString()));break;default:throw FormatException.getFormatInstance();}break;case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:codeIndex++;resultMetadata.setLastSegment(true);break;default:throw FormatException.getFormatInstance();}}// copy optional fields to additional options
if(optionalFieldsStart!==-1){var optionalFieldsLength=codeIndex-optionalFieldsStart;if(resultMetadata.isLastSegment()){// do not include terminator
optionalFieldsLength--;}resultMetadata.setOptionalData(Arrays.copyOfRange(codewords,optionalFieldsStart,optionalFieldsStart+optionalFieldsLength));}return codeIndex;}/**
* Text Compaction mode (see 5.4.1.5) permits all printable ASCII characters to be
* encoded, i.e. values 32 - 126 inclusive in accordance with ISO/IEC 646 (IRV), as
* well as selected control characters.
*
* @param codewords The array of codewords (data + error)
* @param codeIndex The current index into the codeword array.
* @param result The decoded data is appended to the result.
* @return The next index into the codeword array.
*/},{key:"textCompaction",value:function textCompaction(codewords,codeIndex,result){// 2 character per codeword
var textCompactionData=new Int32Array((codewords[0]-codeIndex)*2);// Used to hold the byte compaction value if there is a mode shift
var byteCompactionData=new Int32Array((codewords[0]-codeIndex)*2);var index=0;var end=false;while(codeIndex<codewords[0]&&!end){var code=codewords[codeIndex++];if(code<DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH){textCompactionData[index]=code/30;textCompactionData[index+1]=code%30;index+=2;}else{switch(code){case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:// reinitialize text compaction mode to alpha sub mode
textCompactionData[index++]=DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH;break;case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:case DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:codeIndex--;end=true;break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:// The Mode Shift codeword 913 shall cause a temporary
// switch from Text Compaction mode to Byte Compaction mode.
// This switch shall be in effect for only the next codeword,
// after which the mode shall revert to the prevailing sub-mode
// of the Text Compaction mode. Codeword 913 is only available
// in Text Compaction mode; its use is described in 5.4.2.4.
textCompactionData[index]=DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE;code=codewords[codeIndex++];byteCompactionData[index]=code;index++;break;}}}DecodedBitStreamParser$2.decodeTextCompaction(textCompactionData,byteCompactionData,index,result);return codeIndex;}/**
* The Text Compaction mode includes all the printable ASCII characters
* (i.e. values from 32 to 126) and three ASCII control characters: HT or tab
* (9: e), LF or line feed (10: e), and CR or carriage
* return (13: e). The Text Compaction mode also includes various latch
* and shift characters which are used exclusively within the mode. The Text
* Compaction mode encodes up to 2 characters per codeword. The compaction rules
* for converting data into PDF417 codewords are defined in 5.4.2.2. The sub-mode
* switches are defined in 5.4.2.3.
*
* @param textCompactionData The text compaction data.
* @param byteCompactionData The byte compaction data if there
* was a mode shift.
* @param length The size of the text compaction and byte compaction data.
* @param result The decoded data is appended to the result.
*/},{key:"decodeTextCompaction",value:function decodeTextCompaction(textCompactionData,byteCompactionData,length,result){// Beginning from an initial state of the Alpha sub-mode
// The default compaction mode for PDF417 in effect at the start of each symbol shall always be Text
// Compaction mode Alpha sub-mode (alphabetic: uppercase). A latch codeword from another mode to the Text
// Compaction mode shall always switch to the Text Compaction Alpha sub-mode.
var subMode=Mode$2.ALPHA;var priorToShiftMode=Mode$2.ALPHA;var i=0;while(i<length){var subModeCh=textCompactionData[i];var ch=/*char*/'';switch(subMode){case Mode$2.ALPHA:// Alpha (alphabetic: uppercase)
if(subModeCh<26){// Upper case Alpha Character
// Note: 65 = 'A' ASCII -> there is byte code of symbol
ch=/*(char)('A' + subModeCh) */String.fromCharCode(65+subModeCh);}else{switch(subModeCh){case 26:ch=' ';break;case DecodedBitStreamParser$2.LL:subMode=Mode$2.LOWER;break;case DecodedBitStreamParser$2.ML:subMode=Mode$2.MIXED;break;case DecodedBitStreamParser$2.PS:// Shift to punctuation
priorToShiftMode=subMode;subMode=Mode$2.PUNCT_SHIFT;break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:result.append(/*(char)*/byteCompactionData[i]);break;case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:subMode=Mode$2.ALPHA;break;}}break;case Mode$2.LOWER:// Lower (alphabetic: lowercase)
if(subModeCh<26){ch=/*(char)('a' + subModeCh)*/String.fromCharCode(97+subModeCh);}else{switch(subModeCh){case 26:ch=' ';break;case DecodedBitStreamParser$2.AS:// Shift to alpha
priorToShiftMode=subMode;subMode=Mode$2.ALPHA_SHIFT;break;case DecodedBitStreamParser$2.ML:subMode=Mode$2.MIXED;break;case DecodedBitStreamParser$2.PS:// Shift to punctuation
priorToShiftMode=subMode;subMode=Mode$2.PUNCT_SHIFT;break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:// TODO Does this need to use the current character encoding? See other occurrences below
result.append(/*(char)*/byteCompactionData[i]);break;case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:subMode=Mode$2.ALPHA;break;}}break;case Mode$2.MIXED:// Mixed (punctuation: e)
if(subModeCh<DecodedBitStreamParser$2.PL){ch=DecodedBitStreamParser$2.MIXED_CHARS[subModeCh];}else{switch(subModeCh){case DecodedBitStreamParser$2.PL:subMode=Mode$2.PUNCT;break;case 26:ch=' ';break;case DecodedBitStreamParser$2.LL:subMode=Mode$2.LOWER;break;case DecodedBitStreamParser$2.AL:subMode=Mode$2.ALPHA;break;case DecodedBitStreamParser$2.PS:// Shift to punctuation
priorToShiftMode=subMode;subMode=Mode$2.PUNCT_SHIFT;break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:result.append(/*(char)*/byteCompactionData[i]);break;case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:subMode=Mode$2.ALPHA;break;}}break;case Mode$2.PUNCT:// Punctuation
if(subModeCh<DecodedBitStreamParser$2.PAL){ch=DecodedBitStreamParser$2.PUNCT_CHARS[subModeCh];}else{switch(subModeCh){case DecodedBitStreamParser$2.PAL:subMode=Mode$2.ALPHA;break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:result.append(/*(char)*/byteCompactionData[i]);break;case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:subMode=Mode$2.ALPHA;break;}}break;case Mode$2.ALPHA_SHIFT:// Restore sub-mode
subMode=priorToShiftMode;if(subModeCh<26){ch=/*(char)('A' + subModeCh)*/String.fromCharCode(65+subModeCh);}else{switch(subModeCh){case 26:ch=' ';break;case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:subMode=Mode$2.ALPHA;break;}}break;case Mode$2.PUNCT_SHIFT:// Restore sub-mode
subMode=priorToShiftMode;if(subModeCh<DecodedBitStreamParser$2.PAL){ch=DecodedBitStreamParser$2.PUNCT_CHARS[subModeCh];}else{switch(subModeCh){case DecodedBitStreamParser$2.PAL:subMode=Mode$2.ALPHA;break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:// PS before Shift-to-Byte is used as a padding character,
// see 5.4.2.4 of the specification
result.append(/*(char)*/byteCompactionData[i]);break;case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:subMode=Mode$2.ALPHA;break;}}break;}// if (ch !== 0) {
if(ch!==''){// Append decoded character to result
result.append(ch);}i++;}}/**
* Byte Compaction mode (see 5.4.3) permits all 256 possible 8-bit byte values to be encoded.
* This includes all ASCII characters value 0 to 127 inclusive and provides for international
* character set support.
*
* @param mode The byte compaction mode i.e. 901 or 924
* @param codewords The array of codewords (data + error)
* @param encoding Currently active character encoding
* @param codeIndex The current index into the codeword array.
* @param result The decoded data is appended to the result.
* @return The next index into the codeword array.
*/},{key:"byteCompaction",value:function byteCompaction(mode,codewords,encoding,codeIndex,result){var decodedBytes=new ByteArrayOutputStream();var count=0;var value=/*long*/0;var end=false;switch(mode){case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:// Total number of Byte Compaction characters to be encoded
// is not a multiple of 6
var byteCompactedCodewords=new Int32Array(6);var nextCode=codewords[codeIndex++];while(codeIndex<codewords[0]&&!end){byteCompactedCodewords[count++]=nextCode;// Base 900
value=900*value+nextCode;nextCode=codewords[codeIndex++];// perhaps it should be ok to check only nextCode >= TEXT_COMPACTION_MODE_LATCH
switch(nextCode){case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:codeIndex--;end=true;break;default:if(count%5===0&&count>0){// Decode every 5 codewords
// Convert to Base 256
for(var j/*int*/=0;j<6;++j){/* @note
* JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers.
* So the next bitwise operation could not be done with simple numbers
*/decodedBytes.write(/*(byte)*/Number(createBigInt(value)>>createBigInt(8*(5-j))));}value=0;count=0;}break;}}// if the end of all codewords is reached the last codeword needs to be added
if(codeIndex===codewords[0]&&nextCode<DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH){byteCompactedCodewords[count++]=nextCode;}// If Byte Compaction mode is invoked with codeword 901,
// the last group of codewords is interpreted directly
// as one byte per codeword, without compaction.
for(var i/*int*/=0;i<count;i++){decodedBytes.write(/*(byte)*/byteCompactedCodewords[i]);}break;case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:// Total number of Byte Compaction characters to be encoded
// is an integer multiple of 6
while(codeIndex<codewords[0]&&!end){var code=codewords[codeIndex++];if(code<DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH){count++;// Base 900
value=900*value+code;}else{switch(code){case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:codeIndex--;end=true;break;}}if(count%5===0&&count>0){// Decode every 5 codewords
// Convert to Base 256
/* @note
* JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers.
* So the next bitwise operation could not be done with simple numbers
*/for(var _j8/*int*/=0;_j8<6;++_j8){decodedBytes.write(/*(byte)*/Number(createBigInt(value)>>createBigInt(8*(5-_j8))));}value=0;count=0;}}break;}result.append(StringEncoding.decode(decodedBytes.toByteArray(),encoding));return codeIndex;}/**
* Numeric Compaction mode (see 5.4.4) permits efficient encoding of numeric data strings.
*
* @param codewords The array of codewords (data + error)
* @param codeIndex The current index into the codeword array.
* @param result The decoded data is appended to the result.
* @return The next index into the codeword array.
*
* @throws FormatException
*/},{key:"numericCompaction",value:function numericCompaction(codewords,codeIndex/*int*/,result){var count=0;var end=false;var numericCodewords=new Int32Array(DecodedBitStreamParser$2.MAX_NUMERIC_CODEWORDS);while(codeIndex<codewords[0]&&!end){var code=codewords[codeIndex++];if(codeIndex===codewords[0]){end=true;}if(code<DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH){numericCodewords[count]=code;count++;}else{switch(code){case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:codeIndex--;end=true;break;}}if((count%DecodedBitStreamParser$2.MAX_NUMERIC_CODEWORDS===0||code===DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH||end)&&count>0){// Re-invoking Numeric Compaction mode (by using codeword 902
// while in Numeric Compaction mode) serves to terminate the
// current Numeric Compaction mode grouping as described in 5.4.4.2,
// and then to start a new one grouping.
result.append(DecodedBitStreamParser$2.decodeBase900toBase10(numericCodewords,count));count=0;}}return codeIndex;}/**
* Convert a list of Numeric Compacted codewords from Base 900 to Base 10.
*
* @param codewords The array of codewords
* @param count The number of codewords
* @return The decoded string representing the Numeric data.
*
* EXAMPLE
* Encode the fifteen digit numeric string 000213298174000
* Prefix the numeric string with a 1 and set the initial value of
* t = 1 000 213 298 174 000
* Calculate codeword 0
* d0 = 1 000 213 298 174 000 mod 900 = 200
*
* t = 1 000 213 298 174 000 div 900 = 1 111 348 109 082
* Calculate codeword 1
* d1 = 1 111 348 109 082 mod 900 = 282
*
* t = 1 111 348 109 082 div 900 = 1 234 831 232
* Calculate codeword 2
* d2 = 1 234 831 232 mod 900 = 632
*
* t = 1 234 831 232 div 900 = 1 372 034
* Calculate codeword 3
* d3 = 1 372 034 mod 900 = 434
*
* t = 1 372 034 div 900 = 1 524
* Calculate codeword 4
* d4 = 1 524 mod 900 = 624
*
* t = 1 524 div 900 = 1
* Calculate codeword 5
* d5 = 1 mod 900 = 1
* t = 1 div 900 = 0
* Codeword sequence is: 1, 624, 434, 632, 282, 200
*
* Decode the above codewords involves
* 1 x 900 power of 5 + 624 x 900 power of 4 + 434 x 900 power of 3 +
* 632 x 900 power of 2 + 282 x 900 power of 1 + 200 x 900 power of 0 = 1000213298174000
*
* Remove leading 1 => Result is 000213298174000
*
* @throws FormatException
*/},{key:"decodeBase900toBase10",value:function decodeBase900toBase10(codewords,count){var result=createBigInt(0);for(var i/*int*/=0;i<count;i++){result+=DecodedBitStreamParser$2.EXP900[count-i-1]*createBigInt(codewords[i]);}var resultString=result.toString();if(resultString.charAt(0)!=='1'){throw new FormatException();}return resultString.substring(1);}}]);return DecodedBitStreamParser$2;}();DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH=900;DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH=901;DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH=902;DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6=924;DecodedBitStreamParser$2.ECI_USER_DEFINED=925;DecodedBitStreamParser$2.ECI_GENERAL_PURPOSE=926;DecodedBitStreamParser$2.ECI_CHARSET=927;DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK=928;DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD=923;DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR=922;DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE=913;DecodedBitStreamParser$2.MAX_NUMERIC_CODEWORDS=15;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME=0;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT=1;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP=2;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_SENDER=3;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE=4;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE=5;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM=6;DecodedBitStreamParser$2.PL=25;DecodedBitStreamParser$2.LL=27;DecodedBitStreamParser$2.AS=27;DecodedBitStreamParser$2.ML=28;DecodedBitStreamParser$2.AL=28;DecodedBitStreamParser$2.PS=29;DecodedBitStreamParser$2.PAL=29;DecodedBitStreamParser$2.PUNCT_CHARS=';<>@[\\]_`~!\r\t,:\n-.$/"|*()?{}\'';DecodedBitStreamParser$2.MIXED_CHARS='0123456789&\r\t,:#-.$/+%*=^';/**
* Table containing values for the exponent of 900.
* This is used in the numeric compaction decode algorithm.
*/DecodedBitStreamParser$2.EXP900=getBigIntConstructor()?getEXP900():[];DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS=2;/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ // import java.util.ArrayList;
// import java.util.Collection;
// import java.util.Formatter;
// import java.util.List;
/**
* @author Guenther Grau
*/ /*public final*/var PDF417ScanningDecoder=/*#__PURE__*/function(){function PDF417ScanningDecoder(){_classCallCheck(this,PDF417ScanningDecoder);}/**
* @TODO don't pass in minCodewordWidth and maxCodewordWidth, pass in barcode columns for start and stop pattern
*
* columns. That way width can be deducted from the pattern column.
* This approach also allows to detect more details about the barcode, e.g. if a bar type (white or black) is wider
* than it should be. This can happen if the scanner used a bad blackpoint.
*
* @param BitMatrix
* @param image
* @param ResultPoint
* @param imageTopLeft
* @param ResultPoint
* @param imageBottomLeft
* @param ResultPoint
* @param imageTopRight
* @param ResultPoint
* @param imageBottomRight
* @param int
* @param minCodewordWidth
* @param int
* @param maxCodewordWidth
*
* @throws NotFoundException
* @throws FormatException
* @throws ChecksumException
*/_createClass(PDF417ScanningDecoder,null,[{key:"decode",value:function decode(image,imageTopLeft,imageBottomLeft,imageTopRight,imageBottomRight,minCodewordWidth,maxCodewordWidth){var boundingBox=new BoundingBox(image,imageTopLeft,imageBottomLeft,imageTopRight,imageBottomRight);var leftRowIndicatorColumn=null;var rightRowIndicatorColumn=null;var detectionResult;for(var firstPass/*boolean*/=true;;firstPass=false){if(imageTopLeft!=null){leftRowIndicatorColumn=PDF417ScanningDecoder.getRowIndicatorColumn(image,boundingBox,imageTopLeft,true,minCodewordWidth,maxCodewordWidth);}if(imageTopRight!=null){rightRowIndicatorColumn=PDF417ScanningDecoder.getRowIndicatorColumn(image,boundingBox,imageTopRight,false,minCodewordWidth,maxCodewordWidth);}detectionResult=PDF417ScanningDecoder.merge(leftRowIndicatorColumn,rightRowIndicatorColumn);if(detectionResult==null){throw NotFoundException.getNotFoundInstance();}var resultBox=detectionResult.getBoundingBox();if(firstPass&&resultBox!=null&&(resultBox.getMinY()<boundingBox.getMinY()||resultBox.getMaxY()>boundingBox.getMaxY())){boundingBox=resultBox;}else{break;}}detectionResult.setBoundingBox(boundingBox);var maxBarcodeColumn=detectionResult.getBarcodeColumnCount()+1;detectionResult.setDetectionResultColumn(0,leftRowIndicatorColumn);detectionResult.setDetectionResultColumn(maxBarcodeColumn,rightRowIndicatorColumn);var leftToRight=leftRowIndicatorColumn!=null;for(var barcodeColumnCount/*int*/=1;barcodeColumnCount<=maxBarcodeColumn;barcodeColumnCount++){var barcodeColumn=leftToRight?barcodeColumnCount:maxBarcodeColumn-barcodeColumnCount;if(detectionResult.getDetectionResultColumn(barcodeColumn)!==/* null */undefined){// This will be the case for the opposite row indicator column, which doesn't need to be decoded again.
continue;}var detectionResultColumn=void 0;if(barcodeColumn===0||barcodeColumn===maxBarcodeColumn){detectionResultColumn=new DetectionResultRowIndicatorColumn(boundingBox,barcodeColumn===0);}else{detectionResultColumn=new DetectionResultColumn(boundingBox);}detectionResult.setDetectionResultColumn(barcodeColumn,detectionResultColumn);var startColumn=-1;var previousStartColumn=startColumn;// TODO start at a row for which we know the start position, then detect upwards and downwards from there.
for(var imageRow/*int*/=boundingBox.getMinY();imageRow<=boundingBox.getMaxY();imageRow++){startColumn=PDF417ScanningDecoder.getStartColumn(detectionResult,barcodeColumn,imageRow,leftToRight);if(startColumn<0||startColumn>boundingBox.getMaxX()){if(previousStartColumn===-1){continue;}startColumn=previousStartColumn;}var codeword=PDF417ScanningDecoder.detectCodeword(image,boundingBox.getMinX(),boundingBox.getMaxX(),leftToRight,startColumn,imageRow,minCodewordWidth,maxCodewordWidth);if(codeword!=null){detectionResultColumn.setCodeword(imageRow,codeword);previousStartColumn=startColumn;minCodewordWidth=Math.min(minCodewordWidth,codeword.getWidth());maxCodewordWidth=Math.max(maxCodewordWidth,codeword.getWidth());}}}return PDF417ScanningDecoder.createDecoderResult(detectionResult);}/**
*
* @param leftRowIndicatorColumn
* @param rightRowIndicatorColumn
*
* @throws NotFoundException
*/},{key:"merge",value:function merge(leftRowIndicatorColumn,rightRowIndicatorColumn){if(leftRowIndicatorColumn==null&&rightRowIndicatorColumn==null){return null;}var barcodeMetadata=PDF417ScanningDecoder.getBarcodeMetadata(leftRowIndicatorColumn,rightRowIndicatorColumn);if(barcodeMetadata==null){return null;}var boundingBox=BoundingBox.merge(PDF417ScanningDecoder.adjustBoundingBox(leftRowIndicatorColumn),PDF417ScanningDecoder.adjustBoundingBox(rightRowIndicatorColumn));return new DetectionResult(barcodeMetadata,boundingBox);}/**
*
* @param rowIndicatorColumn
*
* @throws NotFoundException
*/},{key:"adjustBoundingBox",value:function adjustBoundingBox(rowIndicatorColumn){if(rowIndicatorColumn==null){return null;}var rowHeights=rowIndicatorColumn.getRowHeights();if(rowHeights==null){return null;}var maxRowHeight=PDF417ScanningDecoder.getMax(rowHeights);var missingStartRows=0;var _iterator60=_createForOfIteratorHelper(rowHeights),_step60;try{for(_iterator60.s();!(_step60=_iterator60.n()).done;){var rowHeight=_step60.value;missingStartRows+=maxRowHeight-rowHeight;if(rowHeight>0){break;}}}catch(err){_iterator60.e(err);}finally{_iterator60.f();}var codewords=rowIndicatorColumn.getCodewords();for(var row/*int*/=0;missingStartRows>0&&codewords[row]==null;row++){missingStartRows--;}var missingEndRows=0;for(var _row/*int*/=rowHeights.length-1;_row>=0;_row--){missingEndRows+=maxRowHeight-rowHeights[_row];if(rowHeights[_row]>0){break;}}for(var _row2/*int*/=codewords.length-1;missingEndRows>0&&codewords[_row2]==null;_row2--){missingEndRows--;}return rowIndicatorColumn.getBoundingBox().addMissingRows(missingStartRows,missingEndRows,rowIndicatorColumn.isLeft());}},{key:"getMax",value:function getMax(values){var maxValue=-1;var _iterator61=_createForOfIteratorHelper(values),_step61;try{for(_iterator61.s();!(_step61=_iterator61.n()).done;){var value=_step61.value;maxValue=Math.max(maxValue,value);}}catch(err){_iterator61.e(err);}finally{_iterator61.f();}return maxValue;}},{key:"getBarcodeMetadata",value:function getBarcodeMetadata(leftRowIndicatorColumn,rightRowIndicatorColumn){var leftBarcodeMetadata;if(leftRowIndicatorColumn==null||(leftBarcodeMetadata=leftRowIndicatorColumn.getBarcodeMetadata())==null){return rightRowIndicatorColumn==null?null:rightRowIndicatorColumn.getBarcodeMetadata();}var rightBarcodeMetadata;if(rightRowIndicatorColumn==null||(rightBarcodeMetadata=rightRowIndicatorColumn.getBarcodeMetadata())==null){return leftBarcodeMetadata;}if(leftBarcodeMetadata.getColumnCount()!==rightBarcodeMetadata.getColumnCount()&&leftBarcodeMetadata.getErrorCorrectionLevel()!==rightBarcodeMetadata.getErrorCorrectionLevel()&&leftBarcodeMetadata.getRowCount()!==rightBarcodeMetadata.getRowCount()){return null;}return leftBarcodeMetadata;}},{key:"getRowIndicatorColumn",value:function getRowIndicatorColumn(image,boundingBox,startPoint,leftToRight,minCodewordWidth,maxCodewordWidth){var rowIndicatorColumn=new DetectionResultRowIndicatorColumn(boundingBox,leftToRight);for(var i/*int*/=0;i<2;i++){var increment=i===0?1:-1;var startColumn=Math.trunc(Math.trunc(startPoint.getX()));for(var imageRow/*int*/=Math.trunc(Math.trunc(startPoint.getY()));imageRow<=boundingBox.getMaxY()&&imageRow>=boundingBox.getMinY();imageRow+=increment){var codeword=PDF417ScanningDecoder.detectCodeword(image,0,image.getWidth(),leftToRight,startColumn,imageRow,minCodewordWidth,maxCodewordWidth);if(codeword!=null){rowIndicatorColumn.setCodeword(imageRow,codeword);if(leftToRight){startColumn=codeword.getStartX();}else{startColumn=codeword.getEndX();}}}}return rowIndicatorColumn;}/**
*
* @param detectionResult
* @param BarcodeValue
* @param param2
* @param param3
* @param barcodeMatrix
*
* @throws NotFoundException
*/},{key:"adjustCodewordCount",value:function adjustCodewordCount(detectionResult,barcodeMatrix){var barcodeMatrix01=barcodeMatrix[0][1];var numberOfCodewords=barcodeMatrix01.getValue();var calculatedNumberOfCodewords=detectionResult.getBarcodeColumnCount()*detectionResult.getBarcodeRowCount()-PDF417ScanningDecoder.getNumberOfECCodeWords(detectionResult.getBarcodeECLevel());if(numberOfCodewords.length===0){if(calculatedNumberOfCodewords<1||calculatedNumberOfCodewords>PDF417Common.MAX_CODEWORDS_IN_BARCODE){throw NotFoundException.getNotFoundInstance();}barcodeMatrix01.setValue(calculatedNumberOfCodewords);}else if(numberOfCodewords[0]!==calculatedNumberOfCodewords){// The calculated one is more reliable as it is derived from the row indicator columns
barcodeMatrix01.setValue(calculatedNumberOfCodewords);}}/**
*
* @param detectionResult
*
* @throws FormatException
* @throws ChecksumException
* @throws NotFoundException
*/},{key:"createDecoderResult",value:function createDecoderResult(detectionResult){var barcodeMatrix=PDF417ScanningDecoder.createBarcodeMatrix(detectionResult);PDF417ScanningDecoder.adjustCodewordCount(detectionResult,barcodeMatrix);var erasures/*Collection<Integer>*/=new Array();var codewords=new Int32Array(detectionResult.getBarcodeRowCount()*detectionResult.getBarcodeColumnCount());var ambiguousIndexValuesList=/*List<int[]>*/[];var ambiguousIndexesList=/*Collection<Integer>*/new Array();for(var row/*int*/=0;row<detectionResult.getBarcodeRowCount();row++){for(var column/*int*/=0;column<detectionResult.getBarcodeColumnCount();column++){var values=barcodeMatrix[row][column+1].getValue();var codewordIndex=row*detectionResult.getBarcodeColumnCount()+column;if(values.length===0){erasures.push(codewordIndex);}else if(values.length===1){codewords[codewordIndex]=values[0];}else{ambiguousIndexesList.push(codewordIndex);ambiguousIndexValuesList.push(values);}}}var ambiguousIndexValues=new Array(ambiguousIndexValuesList.length);for(var i/*int*/=0;i<ambiguousIndexValues.length;i++){ambiguousIndexValues[i]=ambiguousIndexValuesList[i];}return PDF417ScanningDecoder.createDecoderResultFromAmbiguousValues(detectionResult.getBarcodeECLevel(),codewords,PDF417Common.toIntArray(erasures),PDF417Common.toIntArray(ambiguousIndexesList),ambiguousIndexValues);}/**
* This method deals with the fact, that the decoding process doesn't always yield a single most likely value. The
* current error correction implementation doesn't deal with erasures very well, so it's better to provide a value
* for these ambiguous codewords instead of treating it as an erasure. The problem is that we don't know which of
* the ambiguous values to choose. We try decode using the first value, and if that fails, we use another of the
* ambiguous values and try to decode again. This usually only happens on very hard to read and decode barcodes,
* so decoding the normal barcodes is not affected by this.
*
* @param erasureArray contains the indexes of erasures
* @param ambiguousIndexes array with the indexes that have more than one most likely value
* @param ambiguousIndexValues two dimensional array that contains the ambiguous values. The first dimension must
* be the same length as the ambiguousIndexes array
*
* @throws FormatException
* @throws ChecksumException
*/},{key:"createDecoderResultFromAmbiguousValues",value:function createDecoderResultFromAmbiguousValues(ecLevel,codewords,erasureArray,ambiguousIndexes,ambiguousIndexValues){var ambiguousIndexCount=new Int32Array(ambiguousIndexes.length);var tries=100;while(tries-->0){for(var i/*int*/=0;i<ambiguousIndexCount.length;i++){codewords[ambiguousIndexes[i]]=ambiguousIndexValues[i][ambiguousIndexCount[i]];}try{return PDF417ScanningDecoder.decodeCodewords(codewords,ecLevel,erasureArray);}catch(err){var ignored=err instanceof ChecksumException;if(!ignored){throw err;}}if(ambiguousIndexCount.length===0){throw ChecksumException.getChecksumInstance();}for(var _i36/*int*/=0;_i36<ambiguousIndexCount.length;_i36++){if(ambiguousIndexCount[_i36]<ambiguousIndexValues[_i36].length-1){ambiguousIndexCount[_i36]++;break;}else{ambiguousIndexCount[_i36]=0;if(_i36===ambiguousIndexCount.length-1){throw ChecksumException.getChecksumInstance();}}}}throw ChecksumException.getChecksumInstance();}},{key:"createBarcodeMatrix",value:function createBarcodeMatrix(detectionResult){// let barcodeMatrix: BarcodeValue[][] =
// new BarcodeValue[detectionResult.getBarcodeRowCount()][detectionResult.getBarcodeColumnCount() + 2];
var barcodeMatrix=Array.from({length:detectionResult.getBarcodeRowCount()},function(){return new Array(detectionResult.getBarcodeColumnCount()+2);});for(var row/*int*/=0;row<barcodeMatrix.length;row++){for(var _column/*int*/=0;_column<barcodeMatrix[row].length;_column++){barcodeMatrix[row][_column]=new BarcodeValue();}}var column=0;var _iterator62=_createForOfIteratorHelper(detectionResult.getDetectionResultColumns()),_step62;try{for(_iterator62.s();!(_step62=_iterator62.n()).done;){var detectionResultColumn=_step62.value;if(detectionResultColumn!=null){var _iterator63=_createForOfIteratorHelper(detectionResultColumn.getCodewords()),_step63;try{for(_iterator63.s();!(_step63=_iterator63.n()).done;){var codeword=_step63.value;if(codeword!=null){var rowNumber=codeword.getRowNumber();if(rowNumber>=0){if(rowNumber>=barcodeMatrix.length){// We have more rows than the barcode metadata allows for, ignore them.
continue;}barcodeMatrix[rowNumber][column].setValue(codeword.getValue());}}}}catch(err){_iterator63.e(err);}finally{_iterator63.f();}}column++;}}catch(err){_iterator62.e(err);}finally{_iterator62.f();}return barcodeMatrix;}},{key:"isValidBarcodeColumn",value:function isValidBarcodeColumn(detectionResult,barcodeColumn){return barcodeColumn>=0&&barcodeColumn<=detectionResult.getBarcodeColumnCount()+1;}},{key:"getStartColumn",value:function getStartColumn(detectionResult,barcodeColumn,imageRow,leftToRight){var offset=leftToRight?1:-1;var codeword=null;if(PDF417ScanningDecoder.isValidBarcodeColumn(detectionResult,barcodeColumn-offset)){codeword=detectionResult.getDetectionResultColumn(barcodeColumn-offset).getCodeword(imageRow);}if(codeword!=null){return leftToRight?codeword.getEndX():codeword.getStartX();}codeword=detectionResult.getDetectionResultColumn(barcodeColumn).getCodewordNearby(imageRow);if(codeword!=null){return leftToRight?codeword.getStartX():codeword.getEndX();}if(PDF417ScanningDecoder.isValidBarcodeColumn(detectionResult,barcodeColumn-offset)){codeword=detectionResult.getDetectionResultColumn(barcodeColumn-offset).getCodewordNearby(imageRow);}if(codeword!=null){return leftToRight?codeword.getEndX():codeword.getStartX();}var skippedColumns=0;while(PDF417ScanningDecoder.isValidBarcodeColumn(detectionResult,barcodeColumn-offset)){barcodeColumn-=offset;var _iterator64=_createForOfIteratorHelper(detectionResult.getDetectionResultColumn(barcodeColumn).getCodewords()),_step64;try{for(_iterator64.s();!(_step64=_iterator64.n()).done;){var previousRowCodeword=_step64.value;if(previousRowCodeword!=null){return(leftToRight?previousRowCodeword.getEndX():previousRowCodeword.getStartX())+offset*skippedColumns*(previousRowCodeword.getEndX()-previousRowCodeword.getStartX());}}}catch(err){_iterator64.e(err);}finally{_iterator64.f();}skippedColumns++;}return leftToRight?detectionResult.getBoundingBox().getMinX():detectionResult.getBoundingBox().getMaxX();}},{key:"detectCodeword",value:function detectCodeword(image,minColumn,maxColumn,leftToRight,startColumn,imageRow,minCodewordWidth,maxCodewordWidth){startColumn=PDF417ScanningDecoder.adjustCodewordStartColumn(image,minColumn,maxColumn,leftToRight,startColumn,imageRow);// we usually know fairly exact now how long a codeword is. We should provide minimum and maximum expected length
// and try to adjust the read pixels, e.g. remove single pixel errors or try to cut off exceeding pixels.
// min and maxCodewordWidth should not be used as they are calculated for the whole barcode an can be inaccurate
// for the current position
var moduleBitCount=PDF417ScanningDecoder.getModuleBitCount(image,minColumn,maxColumn,leftToRight,startColumn,imageRow);if(moduleBitCount==null){return null;}var endColumn;var codewordBitCount=MathUtils.sum(moduleBitCount);if(leftToRight){endColumn=startColumn+codewordBitCount;}else{for(var i/*int*/=0;i<moduleBitCount.length/2;i++){var tmpCount=moduleBitCount[i];moduleBitCount[i]=moduleBitCount[moduleBitCount.length-1-i];moduleBitCount[moduleBitCount.length-1-i]=tmpCount;}endColumn=startColumn;startColumn=endColumn-codewordBitCount;}// TODO implement check for width and correction of black and white bars
// use start (and maybe stop pattern) to determine if black bars are wider than white bars. If so, adjust.
// should probably done only for codewords with a lot more than 17 bits.
// The following fixes 10-1.png, which has wide black bars and small white bars
// for (let i /*int*/ = 0; i < moduleBitCount.length; i++) {
// if (i % 2 === 0) {
// moduleBitCount[i]--;
// } else {
// moduleBitCount[i]++;
// }
// }
// We could also use the width of surrounding codewords for more accurate results, but this seems
// sufficient for now
if(!PDF417ScanningDecoder.checkCodewordSkew(codewordBitCount,minCodewordWidth,maxCodewordWidth)){// We could try to use the startX and endX position of the codeword in the same column in the previous row,
// create the bit count from it and normalize it to 8. This would help with single pixel errors.
return null;}var decodedValue=PDF417CodewordDecoder.getDecodedValue(moduleBitCount);var codeword=PDF417Common.getCodeword(decodedValue);if(codeword===-1){return null;}return new Codeword(startColumn,endColumn,PDF417ScanningDecoder.getCodewordBucketNumber(decodedValue),codeword);}},{key:"getModuleBitCount",value:function getModuleBitCount(image,minColumn,maxColumn,leftToRight,startColumn,imageRow){var imageColumn=startColumn;var moduleBitCount=new Int32Array(8);var moduleNumber=0;var increment=leftToRight?1:-1;var previousPixelValue=leftToRight;while((leftToRight?imageColumn<maxColumn:imageColumn>=minColumn)&&moduleNumber<moduleBitCount.length){if(image.get(imageColumn,imageRow)===previousPixelValue){moduleBitCount[moduleNumber]++;imageColumn+=increment;}else{moduleNumber++;previousPixelValue=!previousPixelValue;}}if(moduleNumber===moduleBitCount.length||imageColumn===(leftToRight?maxColumn:minColumn)&&moduleNumber===moduleBitCount.length-1){return moduleBitCount;}return null;}},{key:"getNumberOfECCodeWords",value:function getNumberOfECCodeWords(barcodeECLevel){return 2<<barcodeECLevel;}},{key:"adjustCodewordStartColumn",value:function adjustCodewordStartColumn(image,minColumn,maxColumn,leftToRight,codewordStartColumn,imageRow){var correctedStartColumn=codewordStartColumn;var increment=leftToRight?-1:1;// there should be no black pixels before the start column. If there are, then we need to start earlier.
for(var i/*int*/=0;i<2;i++){while((leftToRight?correctedStartColumn>=minColumn:correctedStartColumn<maxColumn)&&leftToRight===image.get(correctedStartColumn,imageRow)){if(Math.abs(codewordStartColumn-correctedStartColumn)>PDF417ScanningDecoder.CODEWORD_SKEW_SIZE){return codewordStartColumn;}correctedStartColumn+=increment;}increment=-increment;leftToRight=!leftToRight;}return correctedStartColumn;}},{key:"checkCodewordSkew",value:function checkCodewordSkew(codewordSize,minCodewordWidth,maxCodewordWidth){return minCodewordWidth-PDF417ScanningDecoder.CODEWORD_SKEW_SIZE<=codewordSize&&codewordSize<=maxCodewordWidth+PDF417ScanningDecoder.CODEWORD_SKEW_SIZE;}/**
* @throws FormatException,
* @throws ChecksumException
*/},{key:"decodeCodewords",value:function decodeCodewords(codewords,ecLevel,erasures){if(codewords.length===0){throw FormatException.getFormatInstance();}var numECCodewords=1<<ecLevel+1;var correctedErrorsCount=PDF417ScanningDecoder.correctErrors(codewords,erasures,numECCodewords);PDF417ScanningDecoder.verifyCodewordCount(codewords,numECCodewords);// Decode the codewords
var decoderResult=DecodedBitStreamParser$2.decode(codewords,''+ecLevel);decoderResult.setErrorsCorrected(correctedErrorsCount);decoderResult.setErasures(erasures.length);return decoderResult;}/**
* <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
* correct the errors in-place.</p>
*
* @param codewords data and error correction codewords
* @param erasures positions of any known erasures
* @param numECCodewords number of error correction codewords that are available in codewords
* @throws ChecksumException if error correction fails
*/},{key:"correctErrors",value:function correctErrors(codewords,erasures,numECCodewords){if(erasures!=null&&erasures.length>numECCodewords/2+PDF417ScanningDecoder.MAX_ERRORS||numECCodewords<0||numECCodewords>PDF417ScanningDecoder.MAX_EC_CODEWORDS){// Too many errors or EC Codewords is corrupted
throw ChecksumException.getChecksumInstance();}return PDF417ScanningDecoder.errorCorrection.decode(codewords,numECCodewords,erasures);}/**
* Verify that all is OK with the codeword array.
* @throws FormatException
*/},{key:"verifyCodewordCount",value:function verifyCodewordCount(codewords,numECCodewords){if(codewords.length<4){// Codeword array size should be at least 4 allowing for
// Count CW, At least one Data CW, Error Correction CW, Error Correction CW
throw FormatException.getFormatInstance();}// The first codeword, the Symbol Length Descriptor, shall always encode the total number of data
// codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad
// codewords, but excluding the number of error correction codewords.
var numberOfCodewords=codewords[0];if(numberOfCodewords>codewords.length){throw FormatException.getFormatInstance();}if(numberOfCodewords===0){// Reset to the length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords)
if(numECCodewords<codewords.length){codewords[0]=codewords.length-numECCodewords;}else{throw FormatException.getFormatInstance();}}}},{key:"getBitCountForCodeword",value:function getBitCountForCodeword(codeword){var result=new Int32Array(8);var previousValue=0;var i=result.length-1;while(true){if((codeword&0x1)!==previousValue){previousValue=codeword&0x1;i--;if(i<0){break;}}result[i]++;codeword>>=1;}return result;}},{key:"getCodewordBucketNumber",value:function getCodewordBucketNumber(codeword){if(codeword instanceof Int32Array){return this.getCodewordBucketNumber_Int32Array(codeword);}return this.getCodewordBucketNumber_number(codeword);}},{key:"getCodewordBucketNumber_number",value:function getCodewordBucketNumber_number(codeword){return PDF417ScanningDecoder.getCodewordBucketNumber(PDF417ScanningDecoder.getBitCountForCodeword(codeword));}},{key:"getCodewordBucketNumber_Int32Array",value:function getCodewordBucketNumber_Int32Array(moduleBitCount){return(moduleBitCount[0]-moduleBitCount[2]+moduleBitCount[4]-moduleBitCount[6]+9)%9;}},{key:"toString",value:function toString(barcodeMatrix){var formatter=new Formatter();// try (let formatter = new Formatter()) {
for(var row/*int*/=0;row<barcodeMatrix.length;row++){formatter.format('Row %2d: ',row);for(var column/*int*/=0;column<barcodeMatrix[row].length;column++){var barcodeValue=barcodeMatrix[row][column];if(barcodeValue.getValue().length===0){formatter.format(' ',null);}else{formatter.format('%4d(%2d)',barcodeValue.getValue()[0],barcodeValue.getConfidence(barcodeValue.getValue()[0]));}}formatter.format('%n');}return formatter.toString();// }
}}]);return PDF417ScanningDecoder;}();/*final*/PDF417ScanningDecoder.CODEWORD_SKEW_SIZE=2;/*final*/PDF417ScanningDecoder.MAX_ERRORS=3;/*final*/PDF417ScanningDecoder.MAX_EC_CODEWORDS=512;/*final*/PDF417ScanningDecoder.errorCorrection=new ErrorCorrection();/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ // import java.util.ArrayList;
// import java.util.List;
// import java.util.Map;
/**
* This implementation can detect and decode PDF417 codes in an image.
*
* @author Guenther Grau
*/ /*public final*/var PDF417Reader=/*#__PURE__*/function(){function PDF417Reader(){_classCallCheck(this,PDF417Reader);}_createClass(PDF417Reader,[{key:"decode",value:// private static /*final Result[]*/ EMPTY_RESULT_ARRAY: Result[] = new Result([0]);
/**
* Locates and decodes a PDF417 code in an image.
*
* @return a String representing the content encoded by the PDF417 code
* @throws NotFoundException if a PDF417 code cannot be found,
* @throws FormatException if a PDF417 cannot be decoded
* @throws ChecksumException
*/ // @Override
function decode(image){var hints=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var result=PDF417Reader.decode(image,hints,false);if(result==null||result.length===0||result[0]==null){throw NotFoundException.getNotFoundInstance();}return result[0];}/**
*
* @param BinaryBitmap
* @param image
* @throws NotFoundException
*/ // @Override
},{key:"decodeMultiple",value:function decodeMultiple(image){var hints=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;try{return PDF417Reader.decode(image,hints,true);}catch(ignored){if(ignored instanceof FormatException||ignored instanceof ChecksumException){throw NotFoundException.getNotFoundInstance();}throw ignored;}}/**
*
* @param image
* @param hints
* @param multiple
*
* @throws NotFoundException
* @throws FormatExceptionß
* @throws ChecksumException
*/},{key:"reset",value:// @Override
function reset(){// nothing needs to be reset
}}],[{key:"decode",value:function decode(image,hints,multiple){var results=new Array();var detectorResult=Detector$3.detectMultiple(image,hints,multiple);var _iterator65=_createForOfIteratorHelper(detectorResult.getPoints()),_step65;try{for(_iterator65.s();!(_step65=_iterator65.n()).done;){var points=_step65.value;var decoderResult=PDF417ScanningDecoder.decode(detectorResult.getBits(),points[4],points[5],points[6],points[7],PDF417Reader.getMinCodewordWidth(points),PDF417Reader.getMaxCodewordWidth(points));var result=new Result(decoderResult.getText(),decoderResult.getRawBytes(),undefined,points,BarcodeFormat$1.PDF_417);result.putMetadata(ResultMetadataType$1.ERROR_CORRECTION_LEVEL,decoderResult.getECLevel());var pdf417ResultMetadata=decoderResult.getOther();if(pdf417ResultMetadata!=null){result.putMetadata(ResultMetadataType$1.PDF417_EXTRA_METADATA,pdf417ResultMetadata);}results.push(result);}}catch(err){_iterator65.e(err);}finally{_iterator65.f();}return results.map(function(x){return x;});}},{key:"getMaxWidth",value:function getMaxWidth(p1,p2){if(p1==null||p2==null){return 0;}return Math.trunc(Math.abs(p1.getX()-p2.getX()));}},{key:"getMinWidth",value:function getMinWidth(p1,p2){if(p1==null||p2==null){return Integer.MAX_VALUE;}return Math.trunc(Math.abs(p1.getX()-p2.getX()));}},{key:"getMaxCodewordWidth",value:function getMaxCodewordWidth(p){return Math.floor(Math.max(Math.max(PDF417Reader.getMaxWidth(p[0],p[4]),PDF417Reader.getMaxWidth(p[6],p[2])*PDF417Common.MODULES_IN_CODEWORD/PDF417Common.MODULES_IN_STOP_PATTERN),Math.max(PDF417Reader.getMaxWidth(p[1],p[5]),PDF417Reader.getMaxWidth(p[7],p[3])*PDF417Common.MODULES_IN_CODEWORD/PDF417Common.MODULES_IN_STOP_PATTERN)));}},{key:"getMinCodewordWidth",value:function getMinCodewordWidth(p){return Math.floor(Math.min(Math.min(PDF417Reader.getMinWidth(p[0],p[4]),PDF417Reader.getMinWidth(p[6],p[2])*PDF417Common.MODULES_IN_CODEWORD/PDF417Common.MODULES_IN_STOP_PATTERN),Math.min(PDF417Reader.getMinWidth(p[1],p[5]),PDF417Reader.getMinWidth(p[7],p[3])*PDF417Common.MODULES_IN_CODEWORD/PDF417Common.MODULES_IN_STOP_PATTERN)));}}]);return PDF417Reader;}();/**
* Custom Error class of type Exception.
*/var ReaderException=/*#__PURE__*/function(_Exception13){_inherits(ReaderException,_Exception13);var _super59=_createSuper(ReaderException);function ReaderException(){_classCallCheck(this,ReaderException);return _super59.apply(this,arguments);}return _createClass(ReaderException);}(Exception);ReaderException.kind='ReaderException';/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*namespace com.google.zxing {*/ /**
* MultiFormatReader is a convenience class and the main entry point into the library for most uses.
* By default it attempts to decode all barcode formats that the library supports. Optionally, you
* can provide a hints object to request different behavior, for example only decoding QR codes.
*
* @author Sean Owen
* @author dswitkin@google.com (Daniel Switkin)
*/var MultiFormatReader=/*#__PURE__*/function(){/**
* Creates an instance of this class
*
* @param {Boolean} verbose if 'true' logs will be dumped to console, otherwise hidden.
* @param hints The hints to use, clearing the previous state.
*/function MultiFormatReader(verbose,hints){_classCallCheck(this,MultiFormatReader);this.verbose=verbose===true;if(hints){this.setHints(hints);}}/**
* This version of decode honors the intent of Reader.decode(BinaryBitmap) in that it
* passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly.
* Use setHints() followed by decodeWithState() for continuous scan applications.
*
* @param image The pixel data to decode
* @return The contents of the image
*
* @throws NotFoundException Any errors which occurred
*/ /*@Override*/ // public decode(image: BinaryBitmap): Result {
// setHints(null)
// return decodeInternal(image)
// }
/**
* Decode an image using the hints provided. Does not honor existing state.
*
* @param image The pixel data to decode
* @param hints The hints to use, clearing the previous state.
* @return The contents of the image
*
* @throws NotFoundException Any errors which occurred
*/ /*@Override*/_createClass(MultiFormatReader,[{key:"decode",value:function decode(image,hints){if(hints){this.setHints(hints);}return this.decodeInternal(image);}/**
* Decode an image using the state set up by calling setHints() previously. Continuous scan
* clients will get a <b>large</b> speed increase by using this instead of decode().
*
* @param image The pixel data to decode
* @return The contents of the image
*
* @throws NotFoundException Any errors which occurred
*/},{key:"decodeWithState",value:function decodeWithState(image){// Make sure to set up the default state so we don't crash
if(this.readers===null||this.readers===undefined){this.setHints(null);}return this.decodeInternal(image);}/**
* This method adds state to the MultiFormatReader. By setting the hints once, subsequent calls
* to decodeWithState(image) can reuse the same set of readers without reallocating memory. This
* is important for performance in continuous scan clients.
*
* @param hints The set of hints to use for subsequent calls to decode(image)
*/},{key:"setHints",value:function setHints(hints){this.hints=hints;var tryHarder=!isNullOrUndefined(hints)&&hints.get(DecodeHintType$1.TRY_HARDER)===true;var formats=isNullOrUndefined(hints)?null:hints.get(DecodeHintType$1.POSSIBLE_FORMATS);var readers=new Array();if(!isNullOrUndefined(formats)){var addOneDReader=formats.some(function(f){return f===BarcodeFormat$1.UPC_A||f===BarcodeFormat$1.UPC_E||f===BarcodeFormat$1.EAN_13||f===BarcodeFormat$1.EAN_8||f===BarcodeFormat$1.CODABAR||f===BarcodeFormat$1.CODE_39||f===BarcodeFormat$1.CODE_93||f===BarcodeFormat$1.CODE_128||f===BarcodeFormat$1.ITF||f===BarcodeFormat$1.RSS_14||f===BarcodeFormat$1.RSS_EXPANDED;});// Put 1D readers upfront in "normal" mode
if(addOneDReader&&!tryHarder){readers.push(new MultiFormatOneDReader(hints,this.verbose));}if(formats.includes(BarcodeFormat$1.QR_CODE)){readers.push(new QRCodeReader());}if(formats.includes(BarcodeFormat$1.DATA_MATRIX)){readers.push(new DataMatrixReader());}if(formats.includes(BarcodeFormat$1.AZTEC)){readers.push(new AztecReader());}if(formats.includes(BarcodeFormat$1.PDF_417)){readers.push(new PDF417Reader());}// if (formats.includes(BarcodeFormat.MAXICODE)) {
// readers.push(new MaxiCodeReader())
// }
// At end in "try harder" mode
if(addOneDReader&&tryHarder){readers.push(new MultiFormatOneDReader(hints,this.verbose));}}if(readers.length===0){if(!tryHarder){readers.push(new MultiFormatOneDReader(hints,this.verbose));}readers.push(new QRCodeReader());readers.push(new DataMatrixReader());readers.push(new AztecReader());readers.push(new PDF417Reader());// readers.push(new MaxiCodeReader())
if(tryHarder){readers.push(new MultiFormatOneDReader(hints,this.verbose));}}this.readers=readers;// .toArray(new Reader[readers.size()])
}/*@Override*/},{key:"reset",value:function reset(){if(this.readers!==null){var _iterator66=_createForOfIteratorHelper(this.readers),_step66;try{for(_iterator66.s();!(_step66=_iterator66.n()).done;){var reader=_step66.value;reader.reset();}}catch(err){_iterator66.e(err);}finally{_iterator66.f();}}}/**
* @throws NotFoundException
*/},{key:"decodeInternal",value:function decodeInternal(image){if(this.readers===null){throw new ReaderException('No readers where selected, nothing can be read.');}var _iterator67=_createForOfIteratorHelper(this.readers),_step67;try{for(_iterator67.s();!(_step67=_iterator67.n()).done;){var reader=_step67.value;// Trying to decode with ${reader} reader.
try{return reader.decode(image,this.hints);}catch(ex){if(ex instanceof ReaderException){continue;}// Bad Exception.
}}}catch(err){_iterator67.e(err);}finally{_iterator67.f();}throw new NotFoundException('No MultiFormat Readers were able to detect the code.');}}]);return MultiFormatReader;}();var BrowserMultiFormatReader=/*#__PURE__*/function(_BrowserCodeReader4){_inherits(BrowserMultiFormatReader,_BrowserCodeReader4);var _super60=_createSuper(BrowserMultiFormatReader);function BrowserMultiFormatReader(){var hints=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var timeBetweenScansMillis=arguments.length>1&&arguments[1]!==undefined?arguments[1]:500;_classCallCheck(this,BrowserMultiFormatReader);var reader=new MultiFormatReader();reader.setHints(hints);return _super60.call(this,reader,timeBetweenScansMillis);}/**
* Overwrite decodeBitmap to call decodeWithState, which will pay
* attention to the hints set in the constructor function
*/_createClass(BrowserMultiFormatReader,[{key:"decodeBitmap",value:function decodeBitmap(binaryBitmap){return this.reader.decodeWithState(binaryBitmap);}}]);return BrowserMultiFormatReader;}(BrowserCodeReader);/**
* @deprecated Moving to @zxing/browser
*
* QR Code reader to use from browser.
*/var BrowserPDF417Reader=/*#__PURE__*/function(_BrowserCodeReader5){_inherits(BrowserPDF417Reader,_BrowserCodeReader5);var _super61=_createSuper(BrowserPDF417Reader);/**
* Creates an instance of BrowserPDF417Reader.
* @param {number} [timeBetweenScansMillis=500] the time delay between subsequent decode tries
*/function BrowserPDF417Reader(){var timeBetweenScansMillis=arguments.length>0&&arguments[0]!==undefined?arguments[0]:500;_classCallCheck(this,BrowserPDF417Reader);return _super61.call(this,new PDF417Reader(),timeBetweenScansMillis);}return _createClass(BrowserPDF417Reader);}(BrowserCodeReader);/**
* @deprecated Moving to @zxing/browser
*
* QR Code reader to use from browser.
*/var BrowserQRCodeReader=/*#__PURE__*/function(_BrowserCodeReader6){_inherits(BrowserQRCodeReader,_BrowserCodeReader6);var _super62=_createSuper(BrowserQRCodeReader);/**
* Creates an instance of BrowserQRCodeReader.
* @param {number} [timeBetweenScansMillis=500] the time delay between subsequent decode tries
*/function BrowserQRCodeReader(){var timeBetweenScansMillis=arguments.length>0&&arguments[0]!==undefined?arguments[0]:500;_classCallCheck(this,BrowserQRCodeReader);return _super62.call(this,new QRCodeReader(),timeBetweenScansMillis);}return _createClass(BrowserQRCodeReader);}(BrowserCodeReader);/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*namespace com.google.zxing {*/ /**
* These are a set of hints that you may pass to Writers to specify their behavior.
*
* @author dswitkin@google.com (Daniel Switkin)
*/var EncodeHintType;(function(EncodeHintType){/**
* Specifies what degree of error correction to use, for example in QR Codes.
* Type depends on the encoder. For example for QR codes it's type
* {@link com.google.zxing.qrcode.decoder.ErrorCorrectionLevel ErrorCorrectionLevel}.
* For Aztec it is of type {@link Integer}, representing the minimal percentage of error correction words.
* For PDF417 it is of type {@link Integer}, valid values being 0 to 8.
* In all cases, it can also be a {@link String} representation of the desired value as well.
* Note: an Aztec symbol should have a minimum of 25% EC words.
*/EncodeHintType[EncodeHintType["ERROR_CORRECTION"]=0]="ERROR_CORRECTION";/**
* Specifies what character encoding to use where applicable (type {@link String})
*/EncodeHintType[EncodeHintType["CHARACTER_SET"]=1]="CHARACTER_SET";/**
* Specifies the matrix shape for Data Matrix (type {@link com.google.zxing.datamatrix.encoder.SymbolShapeHint})
*/EncodeHintType[EncodeHintType["DATA_MATRIX_SHAPE"]=2]="DATA_MATRIX_SHAPE";/**
* Specifies a minimum barcode size (type {@link Dimension}). Only applicable to Data Matrix now.
*
* @deprecated use width/height params in
* {@link com.google.zxing.datamatrix.DataMatrixWriter#encode(String, BarcodeFormat, int, int)}
*/ /*@Deprecated*/EncodeHintType[EncodeHintType["MIN_SIZE"]=3]="MIN_SIZE";/**
* Specifies a maximum barcode size (type {@link Dimension}). Only applicable to Data Matrix now.
*
* @deprecated without replacement
*/ /*@Deprecated*/EncodeHintType[EncodeHintType["MAX_SIZE"]=4]="MAX_SIZE";/**
* Specifies margin, in pixels, to use when generating the barcode. The meaning can vary
* by format; for example it controls margin before and after the barcode horizontally for
* most 1D formats. (Type {@link Integer}, or {@link String} representation of the integer value).
*/EncodeHintType[EncodeHintType["MARGIN"]=5]="MARGIN";/**
* Specifies whether to use compact mode for PDF417 (type {@link Boolean}, or "true" or "false"
* {@link String} value).
*/EncodeHintType[EncodeHintType["PDF417_COMPACT"]=6]="PDF417_COMPACT";/**
* Specifies what compaction mode to use for PDF417 (type
* {@link com.google.zxing.pdf417.encoder.Compaction Compaction} or {@link String} value of one of its
* enum values).
*/EncodeHintType[EncodeHintType["PDF417_COMPACTION"]=7]="PDF417_COMPACTION";/**
* Specifies the minimum and maximum number of rows and columns for PDF417 (type
* {@link com.google.zxing.pdf417.encoder.Dimensions Dimensions}).
*/EncodeHintType[EncodeHintType["PDF417_DIMENSIONS"]=8]="PDF417_DIMENSIONS";/**
* Specifies the required number of layers for an Aztec code.
* A negative number (-1, -2, -3, -4) specifies a compact Aztec code.
* 0 indicates to use the minimum number of layers (the default).
* A positive number (1, 2, .. 32) specifies a normal (non-compact) Aztec code.
* (Type {@link Integer}, or {@link String} representation of the integer value).
*/EncodeHintType[EncodeHintType["AZTEC_LAYERS"]=9]="AZTEC_LAYERS";/**
* Specifies the exact version of QR code to be encoded.
* (Type {@link Integer}, or {@link String} representation of the integer value).
*/EncodeHintType[EncodeHintType["QR_VERSION"]=10]="QR_VERSION";})(EncodeHintType||(EncodeHintType={}));var EncodeHintType$1=EncodeHintType;/**
* <p>Implements Reed-Solomon encoding, as the name implies.</p>
*
* @author Sean Owen
* @author William Rucklidge
*/var ReedSolomonEncoder=/*#__PURE__*/function(){/**
* A reed solomon error-correcting encoding constructor is created by
* passing as Galois Field with of size equal to the number of code
* words (symbols) in the alphabet (the number of values in each
* element of arrays that are encoded/decoded).
* @param field A galois field with a number of elements equal to the size
* of the alphabet of symbols to encode.
*/function ReedSolomonEncoder(field){_classCallCheck(this,ReedSolomonEncoder);this.field=field;this.cachedGenerators=[];this.cachedGenerators.push(new GenericGFPoly(field,Int32Array.from([1])));}_createClass(ReedSolomonEncoder,[{key:"buildGenerator",value:function buildGenerator(degree/*int*/){var cachedGenerators=this.cachedGenerators;if(degree>=cachedGenerators.length){var lastGenerator=cachedGenerators[cachedGenerators.length-1];var field=this.field;for(var d=cachedGenerators.length;d<=degree;d++){var nextGenerator=lastGenerator.multiply(new GenericGFPoly(field,Int32Array.from([1,field.exp(d-1+field.getGeneratorBase())])));cachedGenerators.push(nextGenerator);lastGenerator=nextGenerator;}}return cachedGenerators[degree];}/**
* <p>Encode a sequence of code words (symbols) using Reed-Solomon to allow decoders
* to detect and correct errors that may have been introduced when the resulting
* data is stored or transmitted.</p>
*
* @param toEncode array used for both and output. Caller initializes the array with
* the code words (symbols) to be encoded followed by empty elements allocated to make
* space for error-correction code words in the encoded output. The array contains
* the encdoded output when encode returns. Code words are encoded as numbers from
* 0 to n-1, where n is the number of possible code words (symbols), as determined
* by the size of the Galois Field passed in the constructor of this object.
* @param ecBytes the number of elements reserved in the array (first parameter)
* to store error-correction code words. Thus, the number of code words (symbols)
* to encode in the first parameter is thus toEncode.length - ecBytes.
* Note, the use of "bytes" in the name of this parameter is misleading, as there may
* be more or fewer than 256 symbols being encoded, as determined by the number of
* elements in the Galois Field passed as a constructor to this object.
* @throws IllegalArgumentException thrown in response to validation errros.
*/},{key:"encode",value:function encode(toEncode,ecBytes/*int*/){if(ecBytes===0){throw new IllegalArgumentException('No error correction bytes');}var dataBytes=toEncode.length-ecBytes;if(dataBytes<=0){throw new IllegalArgumentException('No data bytes provided');}var generator=this.buildGenerator(ecBytes);var infoCoefficients=new Int32Array(dataBytes);System.arraycopy(toEncode,0,infoCoefficients,0,dataBytes);var info=new GenericGFPoly(this.field,infoCoefficients);info=info.multiplyByMonomial(ecBytes,1);var remainder=info.divide(generator)[1];var coefficients=remainder.getCoefficients();var numZeroCoefficients=ecBytes-coefficients.length;for(var i=0;i<numZeroCoefficients;i++){toEncode[dataBytes+i]=0;}System.arraycopy(coefficients,0,toEncode,dataBytes+numZeroCoefficients,coefficients.length);}}]);return ReedSolomonEncoder;}();/**
* @author Satoru Takabayashi
* @author Daniel Switkin
* @author Sean Owen
*/var MaskUtil=/*#__PURE__*/function(){function MaskUtil(){_classCallCheck(this,MaskUtil);}// do nothing
/**
* Apply mask penalty rule 1 and return the penalty. Find repetitive cells with the same color and
* give penalty to them. Example: 00000 or 11111.
*/_createClass(MaskUtil,null,[{key:"applyMaskPenaltyRule1",value:function applyMaskPenaltyRule1(matrix){return MaskUtil.applyMaskPenaltyRule1Internal(matrix,true)+MaskUtil.applyMaskPenaltyRule1Internal(matrix,false);}/**
* Apply mask penalty rule 2 and return the penalty. Find 2x2 blocks with the same color and give
* penalty to them. This is actually equivalent to the spec's rule, which is to find MxN blocks and give a
* penalty proportional to (M-1)x(N-1), because this is the number of 2x2 blocks inside such a block.
*/},{key:"applyMaskPenaltyRule2",value:function applyMaskPenaltyRule2(matrix){var penalty=0;var array=matrix.getArray();var width=matrix.getWidth();var height=matrix.getHeight();for(var y=0;y<height-1;y++){var arrayY=array[y];for(var x=0;x<width-1;x++){var value=arrayY[x];if(value===arrayY[x+1]&&value===array[y+1][x]&&value===array[y+1][x+1]){penalty++;}}}return MaskUtil.N2*penalty;}/**
* Apply mask penalty rule 3 and return the penalty. Find consecutive runs of 1:1:3:1:1:4
* starting with black, or 4:1:1:3:1:1 starting with white, and give penalty to them. If we
* find patterns like 000010111010000, we give penalty once.
*/},{key:"applyMaskPenaltyRule3",value:function applyMaskPenaltyRule3(matrix){var numPenalties=0;var array=matrix.getArray();var width=matrix.getWidth();var height=matrix.getHeight();for(var y=0;y<height;y++){for(var x=0;x<width;x++){var arrayY=array[y];// We can at least optimize this access
if(x+6<width&&arrayY[x]===1&&arrayY[x+1]===0&&arrayY[x+2]===1&&arrayY[x+3]===1&&arrayY[x+4]===1&&arrayY[x+5]===0&&arrayY[x+6]===1&&(MaskUtil.isWhiteHorizontal(arrayY,x-4,x)||MaskUtil.isWhiteHorizontal(arrayY,x+7,x+11))){numPenalties++;}if(y+6<height&&array[y][x]===1&&array[y+1][x]===0&&array[y+2][x]===1&&array[y+3][x]===1&&array[y+4][x]===1&&array[y+5][x]===0&&array[y+6][x]===1&&(MaskUtil.isWhiteVertical(array,x,y-4,y)||MaskUtil.isWhiteVertical(array,x,y+7,y+11))){numPenalties++;}}}return numPenalties*MaskUtil.N3;}},{key:"isWhiteHorizontal",value:function isWhiteHorizontal(rowArray,from/*int*/,to/*int*/){from=Math.max(from,0);to=Math.min(to,rowArray.length);for(var i=from;i<to;i++){if(rowArray[i]===1){return false;}}return true;}},{key:"isWhiteVertical",value:function isWhiteVertical(array,col/*int*/,from/*int*/,to/*int*/){from=Math.max(from,0);to=Math.min(to,array.length);for(var i=from;i<to;i++){if(array[i][col]===1){return false;}}return true;}/**
* Apply mask penalty rule 4 and return the penalty. Calculate the ratio of dark cells and give
* penalty if the ratio is far from 50%. It gives 10 penalty for 5% distance.
*/},{key:"applyMaskPenaltyRule4",value:function applyMaskPenaltyRule4(matrix){var numDarkCells=0;var array=matrix.getArray();var width=matrix.getWidth();var height=matrix.getHeight();for(var y=0;y<height;y++){var arrayY=array[y];for(var x=0;x<width;x++){if(arrayY[x]===1){numDarkCells++;}}}var numTotalCells=matrix.getHeight()*matrix.getWidth();var fivePercentVariances=Math.floor(Math.abs(numDarkCells*2-numTotalCells)*10/numTotalCells);return fivePercentVariances*MaskUtil.N4;}/**
* Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask
* pattern conditions.
*/},{key:"getDataMaskBit",value:function getDataMaskBit(maskPattern/*int*/,x/*int*/,y/*int*/){var intermediate;/*int*/var temp;/*int*/switch(maskPattern){case 0:intermediate=y+x&0x1;break;case 1:intermediate=y&0x1;break;case 2:intermediate=x%3;break;case 3:intermediate=(y+x)%3;break;case 4:intermediate=Math.floor(y/2)+Math.floor(x/3)&0x1;break;case 5:temp=y*x;intermediate=(temp&0x1)+temp%3;break;case 6:temp=y*x;intermediate=(temp&0x1)+temp%3&0x1;break;case 7:temp=y*x;intermediate=temp%3+(y+x&0x1)&0x1;break;default:throw new IllegalArgumentException('Invalid mask pattern: '+maskPattern);}return intermediate===0;}/**
* Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both
* vertical and horizontal orders respectively.
*/},{key:"applyMaskPenaltyRule1Internal",value:function applyMaskPenaltyRule1Internal(matrix,isHorizontal){var penalty=0;var iLimit=isHorizontal?matrix.getHeight():matrix.getWidth();var jLimit=isHorizontal?matrix.getWidth():matrix.getHeight();var array=matrix.getArray();for(var i=0;i<iLimit;i++){var numSameBitCells=0;var prevBit=-1;for(var j=0;j<jLimit;j++){var bit=isHorizontal?array[i][j]:array[j][i];if(bit===prevBit){numSameBitCells++;}else{if(numSameBitCells>=5){penalty+=MaskUtil.N1+(numSameBitCells-5);}numSameBitCells=1;// Include the cell itself.
prevBit=bit;}}if(numSameBitCells>=5){penalty+=MaskUtil.N1+(numSameBitCells-5);}}return penalty;}}]);return MaskUtil;}();// Penalty weights from section 6.8.2.1
MaskUtil.N1=3;MaskUtil.N2=3;MaskUtil.N3=40;MaskUtil.N4=10;/**
* JAVAPORT: The original code was a 2D array of ints, but since it only ever gets assigned
* -1, 0, and 1, I'm going to use less memory and go with bytes.
*
* @author dswitkin@google.com (Daniel Switkin)
*/var ByteMatrix=/*#__PURE__*/function(){function ByteMatrix(width/*int*/,height/*int*/){_classCallCheck(this,ByteMatrix);this.width=width;this.height=height;var bytes=new Array(height);// [height][width]
for(var i=0;i!==height;i++){bytes[i]=new Uint8Array(width);}this.bytes=bytes;}_createClass(ByteMatrix,[{key:"getHeight",value:function getHeight(){return this.height;}},{key:"getWidth",value:function getWidth(){return this.width;}},{key:"get",value:function get(x/*int*/,y/*int*/){return this.bytes[y][x];}/**
* @return an internal representation as bytes, in row-major order. array[y][x] represents point (x,y)
*/},{key:"getArray",value:function getArray(){return this.bytes;}// TYPESCRIPTPORT: preffer to let two methods instead of override to avoid type comparison inside
},{key:"setNumber",value:function setNumber(x/*int*/,y/*int*/,value/*byte|int*/){this.bytes[y][x]=value;}// public set(x: number /*int*/, y: number /*int*/, value: number /*int*/): void {
// bytes[y][x] = (byte) value
// }
},{key:"setBoolean",value:function setBoolean(x/*int*/,y/*int*/,value){this.bytes[y][x]=/*(byte) */value?1:0;}},{key:"clear",value:function clear(value/*byte*/){var _iterator68=_createForOfIteratorHelper(this.bytes),_step68;try{for(_iterator68.s();!(_step68=_iterator68.n()).done;){var aByte=_step68.value;Arrays.fill(aByte,value);}}catch(err){_iterator68.e(err);}finally{_iterator68.f();}}},{key:"equals",value:function equals(o){if(!(o instanceof ByteMatrix)){return false;}var other=o;if(this.width!==other.width){return false;}if(this.height!==other.height){return false;}for(var y=0,height=this.height;y<height;++y){var bytesY=this.bytes[y];var otherBytesY=other.bytes[y];for(var x=0,width=this.width;x<width;++x){if(bytesY[x]!==otherBytesY[x]){return false;}}}return true;}/*@Override*/},{key:"toString",value:function toString(){var result=new StringBuilder();// (2 * width * height + 2)
for(var y=0,height=this.height;y<height;++y){var bytesY=this.bytes[y];for(var x=0,width=this.width;x<width;++x){switch(bytesY[x]){case 0:result.append(' 0');break;case 1:result.append(' 1');break;default:result.append(' ');break;}}result.append('\n');}return result.toString();}}]);return ByteMatrix;}();/**
* @author satorux@google.com (Satoru Takabayashi) - creator
* @author dswitkin@google.com (Daniel Switkin) - ported from C++
*/var QRCode=/*#__PURE__*/function(){function QRCode(){_classCallCheck(this,QRCode);this.maskPattern=-1;}_createClass(QRCode,[{key:"getMode",value:function getMode(){return this.mode;}},{key:"getECLevel",value:function getECLevel(){return this.ecLevel;}},{key:"getVersion",value:function getVersion(){return this.version;}},{key:"getMaskPattern",value:function getMaskPattern(){return this.maskPattern;}},{key:"getMatrix",value:function getMatrix(){return this.matrix;}/*@Override*/},{key:"toString",value:function toString(){var result=new StringBuilder();// (200)
result.append('<<\n');result.append(' mode: ');result.append(this.mode?this.mode.toString():'null');result.append('\n ecLevel: ');result.append(this.ecLevel?this.ecLevel.toString():'null');result.append('\n version: ');result.append(this.version?this.version.toString():'null');result.append('\n maskPattern: ');result.append(this.maskPattern.toString());if(this.matrix){result.append('\n matrix:\n');result.append(this.matrix.toString());}else{result.append('\n matrix: null\n');}result.append('>>\n');return result.toString();}},{key:"setMode",value:function setMode(value){this.mode=value;}},{key:"setECLevel",value:function setECLevel(value){this.ecLevel=value;}},{key:"setVersion",value:function setVersion(version){this.version=version;}},{key:"setMaskPattern",value:function setMaskPattern(value/*int*/){this.maskPattern=value;}},{key:"setMatrix",value:function setMatrix(value){this.matrix=value;}// Check if "mask_pattern" is valid.
}],[{key:"isValidMaskPattern",value:function isValidMaskPattern(maskPattern/*int*/){return maskPattern>=0&&maskPattern<QRCode.NUM_MASK_PATTERNS;}}]);return QRCode;}();QRCode.NUM_MASK_PATTERNS=8;/**
* Custom Error class of type Exception.
*/var WriterException=/*#__PURE__*/function(_Exception14){_inherits(WriterException,_Exception14);var _super63=_createSuper(WriterException);function WriterException(){_classCallCheck(this,WriterException);return _super63.apply(this,arguments);}return _createClass(WriterException);}(Exception);WriterException.kind='WriterException';/**
* @author satorux@google.com (Satoru Takabayashi) - creator
* @author dswitkin@google.com (Daniel Switkin) - ported from C++
*/var MatrixUtil=/*#__PURE__*/function(){function MatrixUtil(){_classCallCheck(this,MatrixUtil);}// do nothing
// Set all cells to -1 (TYPESCRIPTPORT: 255). -1 (TYPESCRIPTPORT: 255) means that the cell is empty (not set yet).
//
// JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding
// with the ByteMatrix initialized all to zero.
_createClass(MatrixUtil,null,[{key:"clearMatrix",value:function clearMatrix(matrix){// TYPESCRIPTPORT: we use UintArray se changed here from -1 to 255
matrix.clear(/*(byte) */ /*-1*/255);}// Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On
// success, store the result in "matrix" and return true.
},{key:"buildMatrix",value:function buildMatrix(dataBits,ecLevel,version,maskPattern/*int*/,matrix){MatrixUtil.clearMatrix(matrix);MatrixUtil.embedBasicPatterns(version,matrix);// Type information appear with any version.
MatrixUtil.embedTypeInfo(ecLevel,maskPattern,matrix);// Version info appear if version >= 7.
MatrixUtil.maybeEmbedVersionInfo(version,matrix);// Data should be embedded at end.
MatrixUtil.embedDataBits(dataBits,maskPattern,matrix);}// Embed basic patterns. On success, modify the matrix and return true.
// The basic patterns are:
// - Position detection patterns
// - Timing patterns
// - Dark dot at the left bottom corner
// - Position adjustment patterns, if need be
},{key:"embedBasicPatterns",value:function embedBasicPatterns(version,matrix){// Let's get started with embedding big squares at corners.
MatrixUtil.embedPositionDetectionPatternsAndSeparators(matrix);// Then, embed the dark dot at the left bottom corner.
MatrixUtil.embedDarkDotAtLeftBottomCorner(matrix);// Position adjustment patterns appear if version >= 2.
MatrixUtil.maybeEmbedPositionAdjustmentPatterns(version,matrix);// Timing patterns should be embedded after position adj. patterns.
MatrixUtil.embedTimingPatterns(matrix);}// Embed type information. On success, modify the matrix.
},{key:"embedTypeInfo",value:function embedTypeInfo(ecLevel,maskPattern/*int*/,matrix){var typeInfoBits=new BitArray();MatrixUtil.makeTypeInfoBits(ecLevel,maskPattern,typeInfoBits);for(var i=0,size=typeInfoBits.getSize();i<size;++i){// Place bits in LSB to MSB order. LSB (least significant bit) is the last value in
// "typeInfoBits".
var bit=typeInfoBits.get(typeInfoBits.getSize()-1-i);// Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46).
var coordinates=MatrixUtil.TYPE_INFO_COORDINATES[i];var x1=coordinates[0];var y1=coordinates[1];matrix.setBoolean(x1,y1,bit);if(i<8){// Right top corner.
var x2=matrix.getWidth()-i-1;var y2=8;matrix.setBoolean(x2,y2,bit);}else{// Left bottom corner.
var _x11=8;var _y3=matrix.getHeight()-7+(i-8);matrix.setBoolean(_x11,_y3,bit);}}}// Embed version information if need be. On success, modify the matrix and return true.
// See 8.10 of JISX0510:2004 (p.47) for how to embed version information.
},{key:"maybeEmbedVersionInfo",value:function maybeEmbedVersionInfo(version,matrix){if(version.getVersionNumber()<7){// Version info is necessary if version >= 7.
return;// Don't need version info.
}var versionInfoBits=new BitArray();MatrixUtil.makeVersionInfoBits(version,versionInfoBits);var bitIndex=6*3-1;// It will decrease from 17 to 0.
for(var i=0;i<6;++i){for(var j=0;j<3;++j){// Place bits in LSB (least significant bit) to MSB order.
var bit=versionInfoBits.get(bitIndex);bitIndex--;// Left bottom corner.
matrix.setBoolean(i,matrix.getHeight()-11+j,bit);// Right bottom corner.
matrix.setBoolean(matrix.getHeight()-11+j,i,bit);}}}// Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true.
// For debugging purposes, it skips masking process if "getMaskPattern" is -1(TYPESCRIPTPORT: 255).
// See 8.7 of JISX0510:2004 (p.38) for how to embed data bits.
},{key:"embedDataBits",value:function embedDataBits(dataBits,maskPattern/*int*/,matrix){var bitIndex=0;var direction=-1;// Start from the right bottom cell.
var x=matrix.getWidth()-1;var y=matrix.getHeight()-1;while(x>0){// Skip the vertical timing pattern.
if(x===6){x-=1;}while(y>=0&&y<matrix.getHeight()){for(var i=0;i<2;++i){var xx=x-i;// Skip the cell if it's not empty.
if(!MatrixUtil.isEmpty(matrix.get(xx,y))){continue;}var bit=void 0;if(bitIndex<dataBits.getSize()){bit=dataBits.get(bitIndex);++bitIndex;}else{// Padding bit. If there is no bit left, we'll fill the left cells with 0, as described
// in 8.4.9 of JISX0510:2004 (p. 24).
bit=false;}// Skip masking if mask_pattern is -1 (TYPESCRIPTPORT: 255).
if(maskPattern!==255&&MaskUtil.getDataMaskBit(maskPattern,xx,y)){bit=!bit;}matrix.setBoolean(xx,y,bit);}y+=direction;}direction=-direction;// Reverse the direction.
y+=direction;x-=2;// Move to the left.
}// All bits should be consumed.
if(bitIndex!==dataBits.getSize()){throw new WriterException('Not all bits consumed: '+bitIndex+'/'+dataBits.getSize());}}// Return the position of the most significant bit set (one: to) in the "value". The most
// significant bit is position 32. If there is no bit set, return 0. Examples:
// - findMSBSet(0) => 0
// - findMSBSet(1) => 1
// - findMSBSet(255) => 8
},{key:"findMSBSet",value:function findMSBSet(value/*int*/){return 32-Integer.numberOfLeadingZeros(value);}// Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH
// code is used for encoding type information and version information.
// Example: Calculation of version information of 7.
// f(x) is created from 7.
// - 7 = 000111 in 6 bits
// - f(x) = x^2 + x^1 + x^0
// g(x) is given by the standard (p. 67)
// - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
// Multiply f(x) by x^(18 - 6)
// - f'(x) = f(x) * x^(18 - 6)
// - f'(x) = x^14 + x^13 + x^12
// Calculate the remainder of f'(x) / g(x)
// x^2
// __________________________________________________
// g(x) )x^14 + x^13 + x^12
// x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
// --------------------------------------------------
// x^11 + x^10 + x^7 + x^4 + x^2
//
// The remainder is x^11 + x^10 + x^7 + x^4 + x^2
// Encode it in binary: 110010010100
// The return value is 0xc94 (1100 1001 0100)
//
// Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit
// operations. We don't care if coefficients are positive or negative.
},{key:"calculateBCHCode",value:function calculateBCHCode(value/*int*/,poly/*int*/){if(poly===0){throw new IllegalArgumentException('0 polynomial');}// If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
// from 13 to make it 12.
var msbSetInPoly=MatrixUtil.findMSBSet(poly);value<<=msbSetInPoly-1;// Do the division business using exclusive-or operations.
while(MatrixUtil.findMSBSet(value)>=msbSetInPoly){value^=poly<<MatrixUtil.findMSBSet(value)-msbSetInPoly;}// Now the "value" is the remainder (i.e. the BCH code)
return value;}// Make bit vector of type information. On success, store the result in "bits" and return true.
// Encode error correction level and mask pattern. See 8.9 of
// JISX0510:2004 (p.45) for details.
},{key:"makeTypeInfoBits",value:function makeTypeInfoBits(ecLevel,maskPattern/*int*/,bits){if(!QRCode.isValidMaskPattern(maskPattern)){throw new WriterException('Invalid mask pattern');}var typeInfo=ecLevel.getBits()<<3|maskPattern;bits.appendBits(typeInfo,5);var bchCode=MatrixUtil.calculateBCHCode(typeInfo,MatrixUtil.TYPE_INFO_POLY);bits.appendBits(bchCode,10);var maskBits=new BitArray();maskBits.appendBits(MatrixUtil.TYPE_INFO_MASK_PATTERN,15);bits.xor(maskBits);if(bits.getSize()!==15){// Just in case.
throw new WriterException('should not happen but we got: '+bits.getSize());}}// Make bit vector of version information. On success, store the result in "bits" and return true.
// See 8.10 of JISX0510:2004 (p.45) for details.
},{key:"makeVersionInfoBits",value:function makeVersionInfoBits(version,bits){bits.appendBits(version.getVersionNumber(),6);var bchCode=MatrixUtil.calculateBCHCode(version.getVersionNumber(),MatrixUtil.VERSION_INFO_POLY);bits.appendBits(bchCode,12);if(bits.getSize()!==18){// Just in case.
throw new WriterException('should not happen but we got: '+bits.getSize());}}// Check if "value" is empty.
},{key:"isEmpty",value:function isEmpty(value/*int*/){return value===255;// -1
}},{key:"embedTimingPatterns",value:function embedTimingPatterns(matrix){// -8 is for skipping position detection patterns (7: size), and two horizontal/vertical
// separation patterns (1: size). Thus, 8 = 7 + 1.
for(var i=8;i<matrix.getWidth()-8;++i){var bit=(i+1)%2;// Horizontal line.
if(MatrixUtil.isEmpty(matrix.get(i,6))){matrix.setNumber(i,6,bit);}// Vertical line.
if(MatrixUtil.isEmpty(matrix.get(6,i))){matrix.setNumber(6,i,bit);}}}// Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
},{key:"embedDarkDotAtLeftBottomCorner",value:function embedDarkDotAtLeftBottomCorner(matrix){if(matrix.get(8,matrix.getHeight()-8)===0){throw new WriterException();}matrix.setNumber(8,matrix.getHeight()-8,1);}},{key:"embedHorizontalSeparationPattern",value:function embedHorizontalSeparationPattern(xStart/*int*/,yStart/*int*/,matrix){for(var x=0;x<8;++x){if(!MatrixUtil.isEmpty(matrix.get(xStart+x,yStart))){throw new WriterException();}matrix.setNumber(xStart+x,yStart,0);}}},{key:"embedVerticalSeparationPattern",value:function embedVerticalSeparationPattern(xStart/*int*/,yStart/*int*/,matrix){for(var y=0;y<7;++y){if(!MatrixUtil.isEmpty(matrix.get(xStart,yStart+y))){throw new WriterException();}matrix.setNumber(xStart,yStart+y,0);}}},{key:"embedPositionAdjustmentPattern",value:function embedPositionAdjustmentPattern(xStart/*int*/,yStart/*int*/,matrix){for(var y=0;y<5;++y){var patternY=MatrixUtil.POSITION_ADJUSTMENT_PATTERN[y];for(var x=0;x<5;++x){matrix.setNumber(xStart+x,yStart+y,patternY[x]);}}}},{key:"embedPositionDetectionPattern",value:function embedPositionDetectionPattern(xStart/*int*/,yStart/*int*/,matrix){for(var y=0;y<7;++y){var patternY=MatrixUtil.POSITION_DETECTION_PATTERN[y];for(var x=0;x<7;++x){matrix.setNumber(xStart+x,yStart+y,patternY[x]);}}}// Embed position detection patterns and surrounding vertical/horizontal separators.
},{key:"embedPositionDetectionPatternsAndSeparators",value:function embedPositionDetectionPatternsAndSeparators(matrix){// Embed three big squares at corners.
var pdpWidth=MatrixUtil.POSITION_DETECTION_PATTERN[0].length;// Left top corner.
MatrixUtil.embedPositionDetectionPattern(0,0,matrix);// Right top corner.
MatrixUtil.embedPositionDetectionPattern(matrix.getWidth()-pdpWidth,0,matrix);// Left bottom corner.
MatrixUtil.embedPositionDetectionPattern(0,matrix.getWidth()-pdpWidth,matrix);// Embed horizontal separation patterns around the squares.
var hspWidth=8;// Left top corner.
MatrixUtil.embedHorizontalSeparationPattern(0,hspWidth-1,matrix);// Right top corner.
MatrixUtil.embedHorizontalSeparationPattern(matrix.getWidth()-hspWidth,hspWidth-1,matrix);// Left bottom corner.
MatrixUtil.embedHorizontalSeparationPattern(0,matrix.getWidth()-hspWidth,matrix);// Embed vertical separation patterns around the squares.
var vspSize=7;// Left top corner.
MatrixUtil.embedVerticalSeparationPattern(vspSize,0,matrix);// Right top corner.
MatrixUtil.embedVerticalSeparationPattern(matrix.getHeight()-vspSize-1,0,matrix);// Left bottom corner.
MatrixUtil.embedVerticalSeparationPattern(vspSize,matrix.getHeight()-vspSize,matrix);}// Embed position adjustment patterns if need be.
},{key:"maybeEmbedPositionAdjustmentPatterns",value:function maybeEmbedPositionAdjustmentPatterns(version,matrix){if(version.getVersionNumber()<2){// The patterns appear if version >= 2
return;}var index=version.getVersionNumber()-1;var coordinates=MatrixUtil.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index];for(var i=0,length=coordinates.length;i!==length;i++){var y=coordinates[i];if(y>=0){for(var j=0;j!==length;j++){var x=coordinates[j];if(x>=0&&MatrixUtil.isEmpty(matrix.get(x,y))){// If the cell is unset, we embed the position adjustment pattern here.
// -2 is necessary since the x/y coordinates point to the center of the pattern, not the
// left top corner.
MatrixUtil.embedPositionAdjustmentPattern(x-2,y-2,matrix);}}}}}}]);return MatrixUtil;}();MatrixUtil.POSITION_DETECTION_PATTERN=Array.from([Int32Array.from([1,1,1,1,1,1,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,1,1,1,1,1,1])]);MatrixUtil.POSITION_ADJUSTMENT_PATTERN=Array.from([Int32Array.from([1,1,1,1,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,0,1,0,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,1,1,1,1])]);// From Appendix E. Table 1, JIS0510X:2004 (71: p). The table was double-checked by komatsu.
MatrixUtil.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE=Array.from([Int32Array.from([-1,-1,-1,-1,-1,-1,-1]),Int32Array.from([6,18,-1,-1,-1,-1,-1]),Int32Array.from([6,22,-1,-1,-1,-1,-1]),Int32Array.from([6,26,-1,-1,-1,-1,-1]),Int32Array.from([6,30,-1,-1,-1,-1,-1]),Int32Array.from([6,34,-1,-1,-1,-1,-1]),Int32Array.from([6,22,38,-1,-1,-1,-1]),Int32Array.from([6,24,42,-1,-1,-1,-1]),Int32Array.from([6,26,46,-1,-1,-1,-1]),Int32Array.from([6,28,50,-1,-1,-1,-1]),Int32Array.from([6,30,54,-1,-1,-1,-1]),Int32Array.from([6,32,58,-1,-1,-1,-1]),Int32Array.from([6,34,62,-1,-1,-1,-1]),Int32Array.from([6,26,46,66,-1,-1,-1]),Int32Array.from([6,26,48,70,-1,-1,-1]),Int32Array.from([6,26,50,74,-1,-1,-1]),Int32Array.from([6,30,54,78,-1,-1,-1]),Int32Array.from([6,30,56,82,-1,-1,-1]),Int32Array.from([6,30,58,86,-1,-1,-1]),Int32Array.from([6,34,62,90,-1,-1,-1]),Int32Array.from([6,28,50,72,94,-1,-1]),Int32Array.from([6,26,50,74,98,-1,-1]),Int32Array.from([6,30,54,78,102,-1,-1]),Int32Array.from([6,28,54,80,106,-1,-1]),Int32Array.from([6,32,58,84,110,-1,-1]),Int32Array.from([6,30,58,86,114,-1,-1]),Int32Array.from([6,34,62,90,118,-1,-1]),Int32Array.from([6,26,50,74,98,122,-1]),Int32Array.from([6,30,54,78,102,126,-1]),Int32Array.from([6,26,52,78,104,130,-1]),Int32Array.from([6,30,56,82,108,134,-1]),Int32Array.from([6,34,60,86,112,138,-1]),Int32Array.from([6,30,58,86,114,142,-1]),Int32Array.from([6,34,62,90,118,146,-1]),Int32Array.from([6,30,54,78,102,126,150]),Int32Array.from([6,24,50,76,102,128,154]),Int32Array.from([6,28,54,80,106,132,158]),Int32Array.from([6,32,58,84,110,136,162]),Int32Array.from([6,26,54,82,110,138,166]),Int32Array.from([6,30,58,86,114,142,170])]);// Type info cells at the left top corner.
MatrixUtil.TYPE_INFO_COORDINATES=Array.from([Int32Array.from([8,0]),Int32Array.from([8,1]),Int32Array.from([8,2]),Int32Array.from([8,3]),Int32Array.from([8,4]),Int32Array.from([8,5]),Int32Array.from([8,7]),Int32Array.from([8,8]),Int32Array.from([7,8]),Int32Array.from([5,8]),Int32Array.from([4,8]),Int32Array.from([3,8]),Int32Array.from([2,8]),Int32Array.from([1,8]),Int32Array.from([0,8])]);// From Appendix D in JISX0510:2004 (p. 67)
MatrixUtil.VERSION_INFO_POLY=0x1f25;// 1 1111 0010 0101
// From Appendix C in JISX0510:2004 (p.65).
MatrixUtil.TYPE_INFO_POLY=0x537;MatrixUtil.TYPE_INFO_MASK_PATTERN=0x5412;/*namespace com.google.zxing.qrcode.encoder {*/var BlockPair=/*#__PURE__*/function(){function BlockPair(dataBytes,errorCorrectionBytes){_classCallCheck(this,BlockPair);this.dataBytes=dataBytes;this.errorCorrectionBytes=errorCorrectionBytes;}_createClass(BlockPair,[{key:"getDataBytes",value:function getDataBytes(){return this.dataBytes;}},{key:"getErrorCorrectionBytes",value:function getErrorCorrectionBytes(){return this.errorCorrectionBytes;}}]);return BlockPair;}();/*import java.io.UnsupportedEncodingException;*/ /*import java.util.ArrayList;*/ /*import java.util.Collection;*/ /*import java.util.Map;*/ /**
* @author satorux@google.com (Satoru Takabayashi) - creator
* @author dswitkin@google.com (Daniel Switkin) - ported from C++
*/var Encoder=/*#__PURE__*/function(){// TYPESCRIPTPORT: changed to UTF8, the default for js
function Encoder(){_classCallCheck(this,Encoder);}// The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details.
// Basically it applies four rules and summate all penalties.
_createClass(Encoder,null,[{key:"calculateMaskPenalty",value:function calculateMaskPenalty(matrix){return MaskUtil.applyMaskPenaltyRule1(matrix)+MaskUtil.applyMaskPenaltyRule2(matrix)+MaskUtil.applyMaskPenaltyRule3(matrix)+MaskUtil.applyMaskPenaltyRule4(matrix);}/**
* @param content text to encode
* @param ecLevel error correction level to use
* @return {@link QRCode} representing the encoded QR code
* @throws WriterException if encoding can't succeed, because of for example invalid content
* or configuration
*/ // public static encode(content: string, ecLevel: ErrorCorrectionLevel): QRCode /*throws WriterException*/ {
// return encode(content, ecLevel, null)
// }
},{key:"encode",value:function encode(content,ecLevel){var hints=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;// Determine what character encoding has been specified by the caller, if any
var encoding=Encoder.DEFAULT_BYTE_MODE_ENCODING;var hasEncodingHint=hints!==null&&undefined!==hints.get(EncodeHintType$1.CHARACTER_SET);if(hasEncodingHint){encoding=hints.get(EncodeHintType$1.CHARACTER_SET).toString();}// Pick an encoding mode appropriate for the content. Note that this will not attempt to use
// multiple modes / segments even if that were more efficient. Twould be nice.
var mode=this.chooseMode(content,encoding);// This will store the header information, like mode and
// length, as well as "header" segments like an ECI segment.
var headerBits=new BitArray();// Append ECI segment if applicable
if(mode===Mode$1.BYTE&&(hasEncodingHint||Encoder.DEFAULT_BYTE_MODE_ENCODING!==encoding)){var eci=CharacterSetECI.getCharacterSetECIByName(encoding);if(eci!==undefined){this.appendECI(eci,headerBits);}}// (With ECI in place,) Write the mode marker
this.appendModeInfo(mode,headerBits);// Collect data within the main segment, separately, to count its size if needed. Don't add it to
// main payload yet.
var dataBits=new BitArray();this.appendBytes(content,mode,dataBits,encoding);var version;if(hints!==null&&undefined!==hints.get(EncodeHintType$1.QR_VERSION)){var versionNumber=Number.parseInt(hints.get(EncodeHintType$1.QR_VERSION).toString(),10);version=Version$1.getVersionForNumber(versionNumber);var bitsNeeded=this.calculateBitsNeeded(mode,headerBits,dataBits,version);if(!this.willFit(bitsNeeded,version,ecLevel)){throw new WriterException('Data too big for requested version');}}else{version=this.recommendVersion(ecLevel,mode,headerBits,dataBits);}var headerAndDataBits=new BitArray();headerAndDataBits.appendBitArray(headerBits);// Find "length" of main segment and write it
var numLetters=mode===Mode$1.BYTE?dataBits.getSizeInBytes():content.length;this.appendLengthInfo(numLetters,version,mode,headerAndDataBits);// Put data together into the overall payload
headerAndDataBits.appendBitArray(dataBits);var ecBlocks=version.getECBlocksForLevel(ecLevel);var numDataBytes=version.getTotalCodewords()-ecBlocks.getTotalECCodewords();// Terminate the bits properly.
this.terminateBits(numDataBytes,headerAndDataBits);// Interleave data bits with error correction code.
var finalBits=this.interleaveWithECBytes(headerAndDataBits,version.getTotalCodewords(),numDataBytes,ecBlocks.getNumBlocks());var qrCode=new QRCode();qrCode.setECLevel(ecLevel);qrCode.setMode(mode);qrCode.setVersion(version);// Choose the mask pattern and set to "qrCode".
var dimension=version.getDimensionForVersion();var matrix=new ByteMatrix(dimension,dimension);var maskPattern=this.chooseMaskPattern(finalBits,ecLevel,version,matrix);qrCode.setMaskPattern(maskPattern);// Build the matrix and set it to "qrCode".
MatrixUtil.buildMatrix(finalBits,ecLevel,version,maskPattern,matrix);qrCode.setMatrix(matrix);return qrCode;}/**
* Decides the smallest version of QR code that will contain all of the provided data.
*
* @throws WriterException if the data cannot fit in any version
*/},{key:"recommendVersion",value:function recommendVersion(ecLevel,mode,headerBits,dataBits){// Hard part: need to know version to know how many bits length takes. But need to know how many
// bits it takes to know version. First we take a guess at version by assuming version will be
// the minimum, 1:
var provisionalBitsNeeded=this.calculateBitsNeeded(mode,headerBits,dataBits,Version$1.getVersionForNumber(1));var provisionalVersion=this.chooseVersion(provisionalBitsNeeded,ecLevel);// Use that guess to calculate the right version. I am still not sure this works in 100% of cases.
var bitsNeeded=this.calculateBitsNeeded(mode,headerBits,dataBits,provisionalVersion);return this.chooseVersion(bitsNeeded,ecLevel);}},{key:"calculateBitsNeeded",value:function calculateBitsNeeded(mode,headerBits,dataBits,version){return headerBits.getSize()+mode.getCharacterCountBits(version)+dataBits.getSize();}/**
* @return the code point of the table used in alphanumeric mode or
* -1 if there is no corresponding code in the table.
*/},{key:"getAlphanumericCode",value:function getAlphanumericCode(code/*int*/){if(code<Encoder.ALPHANUMERIC_TABLE.length){return Encoder.ALPHANUMERIC_TABLE[code];}return-1;}// public static chooseMode(content: string): Mode {
// return chooseMode(content, null);
// }
/**
* Choose the best mode by examining the content. Note that 'encoding' is used as a hint;
* if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}.
*/},{key:"chooseMode",value:function chooseMode(content){var encoding=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(CharacterSetECI.SJIS.getName()===encoding&&this.isOnlyDoubleByteKanji(content)){// Choose Kanji mode if all input are double-byte characters
return Mode$1.KANJI;}var hasNumeric=false;var hasAlphanumeric=false;for(var i=0,length=content.length;i<length;++i){var c=content.charAt(i);if(Encoder.isDigit(c)){hasNumeric=true;}else if(this.getAlphanumericCode(c.charCodeAt(0))!==-1){hasAlphanumeric=true;}else{return Mode$1.BYTE;}}if(hasAlphanumeric){return Mode$1.ALPHANUMERIC;}if(hasNumeric){return Mode$1.NUMERIC;}return Mode$1.BYTE;}},{key:"isOnlyDoubleByteKanji",value:function isOnlyDoubleByteKanji(content){var bytes;try{bytes=StringEncoding.encode(content,CharacterSetECI.SJIS);// content.getBytes("Shift_JIS"))
}catch(ignored/*: UnsupportedEncodingException*/){return false;}var length=bytes.length;if(length%2!==0){return false;}for(var i=0;i<length;i+=2){var byte1=bytes[i]&0xFF;if((byte1<0x81||byte1>0x9F)&&(byte1<0xE0||byte1>0xEB)){return false;}}return true;}},{key:"chooseMaskPattern",value:function chooseMaskPattern(bits,ecLevel,version,matrix){var minPenalty=Number.MAX_SAFE_INTEGER;// Lower penalty is better.
var bestMaskPattern=-1;// We try all mask patterns to choose the best one.
for(var maskPattern=0;maskPattern<QRCode.NUM_MASK_PATTERNS;maskPattern++){MatrixUtil.buildMatrix(bits,ecLevel,version,maskPattern,matrix);var penalty=this.calculateMaskPenalty(matrix);if(penalty<minPenalty){minPenalty=penalty;bestMaskPattern=maskPattern;}}return bestMaskPattern;}},{key:"chooseVersion",value:function chooseVersion(numInputBits/*int*/,ecLevel){for(var versionNum=1;versionNum<=40;versionNum++){var version=Version$1.getVersionForNumber(versionNum);if(Encoder.willFit(numInputBits,version,ecLevel)){return version;}}throw new WriterException('Data too big');}/**
* @return true if the number of input bits will fit in a code with the specified version and
* error correction level.
*/},{key:"willFit",value:function willFit(numInputBits/*int*/,version,ecLevel){// In the following comments, we use numbers of Version 7-H.
// numBytes = 196
var numBytes=version.getTotalCodewords();// getNumECBytes = 130
var ecBlocks=version.getECBlocksForLevel(ecLevel);var numEcBytes=ecBlocks.getTotalECCodewords();// getNumDataBytes = 196 - 130 = 66
var numDataBytes=numBytes-numEcBytes;var totalInputBytes=(numInputBits+7)/8;return numDataBytes>=totalInputBytes;}/**
* Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
*/},{key:"terminateBits",value:function terminateBits(numDataBytes/*int*/,bits){var capacity=numDataBytes*8;if(bits.getSize()>capacity){throw new WriterException('data bits cannot fit in the QR Code'+bits.getSize()+' > '+capacity);}for(var i=0;i<4&&bits.getSize()<capacity;++i){bits.appendBit(false);}// Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
// If the last byte isn't 8-bit aligned, we'll add padding bits.
var numBitsInLastByte=bits.getSize()&0x07;if(numBitsInLastByte>0){for(var _i37=numBitsInLastByte;_i37<8;_i37++){bits.appendBit(false);}}// If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
var numPaddingBytes=numDataBytes-bits.getSizeInBytes();for(var _i38=0;_i38<numPaddingBytes;++_i38){bits.appendBits((_i38&0x01)===0?0xEC:0x11,8);}if(bits.getSize()!==capacity){throw new WriterException('Bits size does not equal capacity');}}/**
* Get number of data bytes and number of error correction bytes for block id "blockID". Store
* the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
* JISX0510:2004 (p.30)
*/},{key:"getNumDataBytesAndNumECBytesForBlockID",value:function getNumDataBytesAndNumECBytesForBlockID(numTotalBytes/*int*/,numDataBytes/*int*/,numRSBlocks/*int*/,blockID/*int*/,numDataBytesInBlock,numECBytesInBlock){if(blockID>=numRSBlocks){throw new WriterException('Block ID too large');}// numRsBlocksInGroup2 = 196 % 5 = 1
var numRsBlocksInGroup2=numTotalBytes%numRSBlocks;// numRsBlocksInGroup1 = 5 - 1 = 4
var numRsBlocksInGroup1=numRSBlocks-numRsBlocksInGroup2;// numTotalBytesInGroup1 = 196 / 5 = 39
var numTotalBytesInGroup1=Math.floor(numTotalBytes/numRSBlocks);// numTotalBytesInGroup2 = 39 + 1 = 40
var numTotalBytesInGroup2=numTotalBytesInGroup1+1;// numDataBytesInGroup1 = 66 / 5 = 13
var numDataBytesInGroup1=Math.floor(numDataBytes/numRSBlocks);// numDataBytesInGroup2 = 13 + 1 = 14
var numDataBytesInGroup2=numDataBytesInGroup1+1;// numEcBytesInGroup1 = 39 - 13 = 26
var numEcBytesInGroup1=numTotalBytesInGroup1-numDataBytesInGroup1;// numEcBytesInGroup2 = 40 - 14 = 26
var numEcBytesInGroup2=numTotalBytesInGroup2-numDataBytesInGroup2;// Sanity checks.
// 26 = 26
if(numEcBytesInGroup1!==numEcBytesInGroup2){throw new WriterException('EC bytes mismatch');}// 5 = 4 + 1.
if(numRSBlocks!==numRsBlocksInGroup1+numRsBlocksInGroup2){throw new WriterException('RS blocks mismatch');}// 196 = (13 + 26) * 4 + (14 + 26) * 1
if(numTotalBytes!==(numDataBytesInGroup1+numEcBytesInGroup1)*numRsBlocksInGroup1+(numDataBytesInGroup2+numEcBytesInGroup2)*numRsBlocksInGroup2){throw new WriterException('Total bytes mismatch');}if(blockID<numRsBlocksInGroup1){numDataBytesInBlock[0]=numDataBytesInGroup1;numECBytesInBlock[0]=numEcBytesInGroup1;}else{numDataBytesInBlock[0]=numDataBytesInGroup2;numECBytesInBlock[0]=numEcBytesInGroup2;}}/**
* Interleave "bits" with corresponding error correction bytes. On success, store the result in
* "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
*/},{key:"interleaveWithECBytes",value:function interleaveWithECBytes(bits,numTotalBytes/*int*/,numDataBytes/*int*/,numRSBlocks/*int*/){// "bits" must have "getNumDataBytes" bytes of data.
if(bits.getSizeInBytes()!==numDataBytes){throw new WriterException('Number of bits and data bytes does not match');}// Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
// store the divided data bytes blocks and error correction bytes blocks into "blocks".
var dataBytesOffset=0;var maxNumDataBytes=0;var maxNumEcBytes=0;// Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
var blocks=new Array();// new Array<BlockPair>(numRSBlocks)
for(var i=0;i<numRSBlocks;++i){var numDataBytesInBlock=new Int32Array(1);var numEcBytesInBlock=new Int32Array(1);Encoder.getNumDataBytesAndNumECBytesForBlockID(numTotalBytes,numDataBytes,numRSBlocks,i,numDataBytesInBlock,numEcBytesInBlock);var size=numDataBytesInBlock[0];var dataBytes=new Uint8Array(size);bits.toBytes(8*dataBytesOffset,dataBytes,0,size);var ecBytes=Encoder.generateECBytes(dataBytes,numEcBytesInBlock[0]);blocks.push(new BlockPair(dataBytes,ecBytes));maxNumDataBytes=Math.max(maxNumDataBytes,size);maxNumEcBytes=Math.max(maxNumEcBytes,ecBytes.length);dataBytesOffset+=numDataBytesInBlock[0];}if(numDataBytes!==dataBytesOffset){throw new WriterException('Data bytes does not match offset');}var result=new BitArray();// First, place data blocks.
for(var _i39=0;_i39<maxNumDataBytes;++_i39){var _iterator69=_createForOfIteratorHelper(blocks),_step69;try{for(_iterator69.s();!(_step69=_iterator69.n()).done;){var block=_step69.value;var _dataBytes=block.getDataBytes();if(_i39<_dataBytes.length){result.appendBits(_dataBytes[_i39],8);}}}catch(err){_iterator69.e(err);}finally{_iterator69.f();}}// Then, place error correction blocks.
for(var _i40=0;_i40<maxNumEcBytes;++_i40){var _iterator70=_createForOfIteratorHelper(blocks),_step70;try{for(_iterator70.s();!(_step70=_iterator70.n()).done;){var _block=_step70.value;var _ecBytes=_block.getErrorCorrectionBytes();if(_i40<_ecBytes.length){result.appendBits(_ecBytes[_i40],8);}}}catch(err){_iterator70.e(err);}finally{_iterator70.f();}}if(numTotalBytes!==result.getSizeInBytes()){// Should be same.
throw new WriterException('Interleaving error: '+numTotalBytes+' and '+result.getSizeInBytes()+' differ.');}return result;}},{key:"generateECBytes",value:function generateECBytes(dataBytes,numEcBytesInBlock/*int*/){var numDataBytes=dataBytes.length;var toEncode=new Int32Array(numDataBytes+numEcBytesInBlock);// int[numDataBytes + numEcBytesInBlock]
for(var i=0;i<numDataBytes;i++){toEncode[i]=dataBytes[i]&0xFF;}new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256).encode(toEncode,numEcBytesInBlock);var ecBytes=new Uint8Array(numEcBytesInBlock);for(var _i41=0;_i41<numEcBytesInBlock;_i41++){ecBytes[_i41]=/*(byte) */toEncode[numDataBytes+_i41];}return ecBytes;}/**
* Append mode info. On success, store the result in "bits".
*/},{key:"appendModeInfo",value:function appendModeInfo(mode,bits){bits.appendBits(mode.getBits(),4);}/**
* Append length info. On success, store the result in "bits".
*/},{key:"appendLengthInfo",value:function appendLengthInfo(numLetters/*int*/,version,mode,bits){var numBits=mode.getCharacterCountBits(version);if(numLetters>=1<<numBits){throw new WriterException(numLetters+' is bigger than '+((1<<numBits)-1));}bits.appendBits(numLetters,numBits);}/**
* Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
*/},{key:"appendBytes",value:function appendBytes(content,mode,bits,encoding){switch(mode){case Mode$1.NUMERIC:Encoder.appendNumericBytes(content,bits);break;case Mode$1.ALPHANUMERIC:Encoder.appendAlphanumericBytes(content,bits);break;case Mode$1.BYTE:Encoder.append8BitBytes(content,bits,encoding);break;case Mode$1.KANJI:Encoder.appendKanjiBytes(content,bits);break;default:throw new WriterException('Invalid mode: '+mode);}}},{key:"getDigit",value:function getDigit(singleCharacter){return singleCharacter.charCodeAt(0)-48;}},{key:"isDigit",value:function isDigit(singleCharacter){var cn=Encoder.getDigit(singleCharacter);return cn>=0&&cn<=9;}},{key:"appendNumericBytes",value:function appendNumericBytes(content,bits){var length=content.length;var i=0;while(i<length){var num1=Encoder.getDigit(content.charAt(i));if(i+2<length){// Encode three numeric letters in ten bits.
var num2=Encoder.getDigit(content.charAt(i+1));var num3=Encoder.getDigit(content.charAt(i+2));bits.appendBits(num1*100+num2*10+num3,10);i+=3;}else if(i+1<length){// Encode two numeric letters in seven bits.
var _num=Encoder.getDigit(content.charAt(i+1));bits.appendBits(num1*10+_num,7);i+=2;}else{// Encode one numeric letter in four bits.
bits.appendBits(num1,4);i++;}}}},{key:"appendAlphanumericBytes",value:function appendAlphanumericBytes(content,bits){var length=content.length;var i=0;while(i<length){var code1=Encoder.getAlphanumericCode(content.charCodeAt(i));if(code1===-1){throw new WriterException();}if(i+1<length){var code2=Encoder.getAlphanumericCode(content.charCodeAt(i+1));if(code2===-1){throw new WriterException();}// Encode two alphanumeric letters in 11 bits.
bits.appendBits(code1*45+code2,11);i+=2;}else{// Encode one alphanumeric letter in six bits.
bits.appendBits(code1,6);i++;}}}},{key:"append8BitBytes",value:function append8BitBytes(content,bits,encoding){var bytes;try{bytes=StringEncoding.encode(content,encoding);}catch(uee/*: UnsupportedEncodingException*/){throw new WriterException(uee);}for(var i=0,length=bytes.length;i!==length;i++){var b=bytes[i];bits.appendBits(b,8);}}/**
* @throws WriterException
*/},{key:"appendKanjiBytes",value:function appendKanjiBytes(content,bits){var bytes;try{bytes=StringEncoding.encode(content,CharacterSetECI.SJIS);}catch(uee/*: UnsupportedEncodingException*/){throw new WriterException(uee);}var length=bytes.length;for(var i=0;i<length;i+=2){var byte1=bytes[i]&0xFF;var byte2=bytes[i+1]&0xFF;var code=byte1<<8&0xFFFFFFFF|byte2;var subtracted=-1;if(code>=0x8140&&code<=0x9ffc){subtracted=code-0x8140;}else if(code>=0xe040&&code<=0xebbf){subtracted=code-0xc140;}if(subtracted===-1){throw new WriterException('Invalid byte sequence');}var encoded=(subtracted>>8)*0xc0+(subtracted&0xff);bits.appendBits(encoded,13);}}},{key:"appendECI",value:function appendECI(eci,bits){bits.appendBits(Mode$1.ECI.getBits(),4);// This is correct for values up to 127, which is all we need now.
bits.appendBits(eci.getValue(),8);}}]);return Encoder;}();// The original table is defined in the table 5 of JISX0510:2004 (p.19).
Encoder.ALPHANUMERIC_TABLE=Int32Array.from([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,36,-1,-1,-1,37,38,-1,-1,-1,-1,39,40,-1,41,42,43,0,1,2,3,4,5,6,7,8,9,44,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1]);Encoder.DEFAULT_BYTE_MODE_ENCODING=CharacterSetECI.UTF8.getName();// "ISO-8859-1"
/**
* @deprecated Moving to @zxing/browser
*/var BrowserQRCodeSvgWriter=/*#__PURE__*/function(){function BrowserQRCodeSvgWriter(){_classCallCheck(this,BrowserQRCodeSvgWriter);}_createClass(BrowserQRCodeSvgWriter,[{key:"write",value:/**
* Writes and renders a QRCode SVG element.
*
* @param contents
* @param width
* @param height
* @param hints
*/function write(contents,width,height){var hints=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;if(contents.length===0){throw new IllegalArgumentException('Found empty contents');}// if (format != BarcodeFormat.QR_CODE) {
// throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format)
// }
if(width<0||height<0){throw new IllegalArgumentException('Requested dimensions are too small: '+width+'x'+height);}var errorCorrectionLevel=ErrorCorrectionLevel.L;var quietZone=BrowserQRCodeSvgWriter.QUIET_ZONE_SIZE;if(hints!==null){if(undefined!==hints.get(EncodeHintType$1.ERROR_CORRECTION)){errorCorrectionLevel=ErrorCorrectionLevel.fromString(hints.get(EncodeHintType$1.ERROR_CORRECTION).toString());}if(undefined!==hints.get(EncodeHintType$1.MARGIN)){quietZone=Number.parseInt(hints.get(EncodeHintType$1.MARGIN).toString(),10);}}var code=Encoder.encode(contents,errorCorrectionLevel,hints);return this.renderResult(code,width,height,quietZone);}/**
* Renders the result and then appends it to the DOM.
*/},{key:"writeToDom",value:function writeToDom(containerElement,contents,width,height){var hints=arguments.length>4&&arguments[4]!==undefined?arguments[4]:null;if(typeof containerElement==='string'){containerElement=document.querySelector(containerElement);}var svgElement=this.write(contents,width,height,hints);if(containerElement)containerElement.appendChild(svgElement);}/**
* Note that the input matrix uses 0 == white, 1 == black.
* The output matrix uses 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
*/},{key:"renderResult",value:function renderResult(code,width/*int*/,height/*int*/,quietZone/*int*/){var input=code.getMatrix();if(input===null){throw new IllegalStateException();}var inputWidth=input.getWidth();var inputHeight=input.getHeight();var qrWidth=inputWidth+quietZone*2;var qrHeight=inputHeight+quietZone*2;var outputWidth=Math.max(width,qrWidth);var outputHeight=Math.max(height,qrHeight);var multiple=Math.min(Math.floor(outputWidth/qrWidth),Math.floor(outputHeight/qrHeight));// Padding includes both the quiet zone and the extra white pixels to accommodate the requested
// dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.
// If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will
// handle all the padding from 100x100 (the actual QR) up to 200x160.
var leftPadding=Math.floor((outputWidth-inputWidth*multiple)/2);var topPadding=Math.floor((outputHeight-inputHeight*multiple)/2);var svgElement=this.createSVGElement(outputWidth,outputHeight);for(var inputY=0,outputY=topPadding;inputY<inputHeight;inputY++,outputY+=multiple){// Write the contents of this row of the barcode
for(var inputX=0,outputX=leftPadding;inputX<inputWidth;inputX++,outputX+=multiple){if(input.get(inputX,inputY)===1){var svgRectElement=this.createSvgRectElement(outputX,outputY,multiple,multiple);svgElement.appendChild(svgRectElement);}}}return svgElement;}/**
* Creates a SVG element.
*
* @param w SVG's width attribute
* @param h SVG's height attribute
*/},{key:"createSVGElement",value:function createSVGElement(w,h){var svgElement=document.createElementNS(BrowserQRCodeSvgWriter.SVG_NS,'svg');svgElement.setAttributeNS(null,'height',w.toString());svgElement.setAttributeNS(null,'width',h.toString());return svgElement;}/**
* Creates a SVG rect element.
*
* @param x Element's x coordinate
* @param y Element's y coordinate
* @param w Element's width attribute
* @param h Element's height attribute
*/},{key:"createSvgRectElement",value:function createSvgRectElement(x,y,w,h){var rect=document.createElementNS(BrowserQRCodeSvgWriter.SVG_NS,'rect');rect.setAttributeNS(null,'x',x.toString());rect.setAttributeNS(null,'y',y.toString());rect.setAttributeNS(null,'height',w.toString());rect.setAttributeNS(null,'width',h.toString());rect.setAttributeNS(null,'fill','#000000');return rect;}}]);return BrowserQRCodeSvgWriter;}();BrowserQRCodeSvgWriter.QUIET_ZONE_SIZE=4;/**
* SVG markup NameSpace
*/BrowserQRCodeSvgWriter.SVG_NS='http://www.w3.org/2000/svg';/*import java.util.Map;*/ /**
* This object renders a QR Code as a BitMatrix 2D array of greyscale values.
*
* @author dswitkin@google.com (Daniel Switkin)
*/var QRCodeWriter=/*#__PURE__*/function(){function QRCodeWriter(){_classCallCheck(this,QRCodeWriter);}_createClass(QRCodeWriter,[{key:"encode",value:/*@Override*/ // public encode(contents: string, format: BarcodeFormat, width: number /*int*/, height: number /*int*/): BitMatrix
// /*throws WriterException */ {
// return encode(contents, format, width, height, null)
// }
/*@Override*/function encode(contents,format,width/*int*/,height/*int*/,hints){if(contents.length===0){throw new IllegalArgumentException('Found empty contents');}if(format!==BarcodeFormat$1.QR_CODE){throw new IllegalArgumentException('Can only encode QR_CODE, but got '+format);}if(width<0||height<0){throw new IllegalArgumentException("Requested dimensions are too small: ".concat(width,"x").concat(height));}var errorCorrectionLevel=ErrorCorrectionLevel.L;var quietZone=QRCodeWriter.QUIET_ZONE_SIZE;if(hints!==null){if(undefined!==hints.get(EncodeHintType$1.ERROR_CORRECTION)){errorCorrectionLevel=ErrorCorrectionLevel.fromString(hints.get(EncodeHintType$1.ERROR_CORRECTION).toString());}if(undefined!==hints.get(EncodeHintType$1.MARGIN)){quietZone=Number.parseInt(hints.get(EncodeHintType$1.MARGIN).toString(),10);}}var code=Encoder.encode(contents,errorCorrectionLevel,hints);return QRCodeWriter.renderResult(code,width,height,quietZone);}// Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses
// 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
}],[{key:"renderResult",value:function renderResult(code,width/*int*/,height/*int*/,quietZone/*int*/){var input=code.getMatrix();if(input===null){throw new IllegalStateException();}var inputWidth=input.getWidth();var inputHeight=input.getHeight();var qrWidth=inputWidth+quietZone*2;var qrHeight=inputHeight+quietZone*2;var outputWidth=Math.max(width,qrWidth);var outputHeight=Math.max(height,qrHeight);var multiple=Math.min(Math.floor(outputWidth/qrWidth),Math.floor(outputHeight/qrHeight));// Padding includes both the quiet zone and the extra white pixels to accommodate the requested
// dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.
// If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will
// handle all the padding from 100x100 (the actual QR) up to 200x160.
var leftPadding=Math.floor((outputWidth-inputWidth*multiple)/2);var topPadding=Math.floor((outputHeight-inputHeight*multiple)/2);var output=new BitMatrix(outputWidth,outputHeight);for(var inputY=0,outputY=topPadding;inputY<inputHeight;inputY++,outputY+=multiple){// Write the contents of this row of the barcode
for(var inputX=0,outputX=leftPadding;inputX<inputWidth;inputX++,outputX+=multiple){if(input.get(inputX,inputY)===1){output.setRegion(outputX,outputY,multiple,multiple);}}}return output;}}]);return QRCodeWriter;}();QRCodeWriter.QUIET_ZONE_SIZE=4;/*import java.util.Map;*/ /**
* This is a factory class which finds the appropriate Writer subclass for the BarcodeFormat
* requested and encodes the barcode with the supplied contents.
*
* @author dswitkin@google.com (Daniel Switkin)
*/var MultiFormatWriter=/*#__PURE__*/function(){function MultiFormatWriter(){_classCallCheck(this,MultiFormatWriter);}_createClass(MultiFormatWriter,[{key:"encode",value:/*@Override*/ // public encode(contents: string,
// format: BarcodeFormat,
// width: number /*int*/,
// height: number /*int*/): BitMatrix /*throws WriterException */ {
// return encode(contents, format, width, height, null)
// }
/*@Override*/function encode(contents,format,width/*int*/,height/*int*/,hints){var writer;switch(format){// case BarcodeFormat.EAN_8:
// writer = new EAN8Writer()
// break
// case BarcodeFormat.UPC_E:
// writer = new UPCEWriter()
// break
// case BarcodeFormat.EAN_13:
// writer = new EAN13Writer()
// break
// case BarcodeFormat.UPC_A:
// writer = new UPCAWriter()
// break
case BarcodeFormat$1.QR_CODE:writer=new QRCodeWriter();break;// case BarcodeFormat.CODE_39:
// writer = new Code39Writer()
// break
// case BarcodeFormat.CODE_93:
// writer = new Code93Writer()
// break
// case BarcodeFormat.CODE_128:
// writer = new Code128Writer()
// break
// case BarcodeFormat.ITF:
// writer = new ITFWriter()
// break
// case BarcodeFormat.PDF_417:
// writer = new PDF417Writer()
// break
// case BarcodeFormat.CODABAR:
// writer = new CodaBarWriter()
// break
// case BarcodeFormat.DATA_MATRIX:
// writer = new DataMatrixWriter()
// break
// case BarcodeFormat.AZTEC:
// writer = new AztecWriter()
// break
default:throw new IllegalArgumentException('No encoder available for format '+format);}return writer.encode(contents,format,width,height,hints);}}]);return MultiFormatWriter;}();/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* This object extends LuminanceSource around an array of YUV data returned from the camera driver,
* with the option to crop to a rectangle within the full data. This can be used to exclude
* superfluous pixels around the perimeter and speed up decoding.
*
* It works for any pixel format where the Y channel is planar and appears first, including
* YCbCr_420_SP and YCbCr_422_SP.
*
* @author dswitkin@google.com (Daniel Switkin)
*/var PlanarYUVLuminanceSource=/*#__PURE__*/function(_LuminanceSource3){_inherits(PlanarYUVLuminanceSource,_LuminanceSource3);var _super64=_createSuper(PlanarYUVLuminanceSource);function PlanarYUVLuminanceSource(yuvData,dataWidth/*int*/,dataHeight/*int*/,left/*int*/,top/*int*/,width/*int*/,height/*int*/,reverseHorizontal){var _this38;_classCallCheck(this,PlanarYUVLuminanceSource);_this38=_super64.call(this,width,height);_this38.yuvData=yuvData;_this38.dataWidth=dataWidth;_this38.dataHeight=dataHeight;_this38.left=left;_this38.top=top;if(left+width>dataWidth||top+height>dataHeight){throw new IllegalArgumentException('Crop rectangle does not fit within image data.');}if(reverseHorizontal){_this38.reverseHorizontal(width,height);}return _this38;}/*@Override*/_createClass(PlanarYUVLuminanceSource,[{key:"getRow",value:function getRow(y/*int*/,row){if(y<0||y>=this.getHeight()){throw new IllegalArgumentException('Requested row is outside the image: '+y);}var width=this.getWidth();if(row===null||row===undefined||row.length<width){row=new Uint8ClampedArray(width);}var offset=(y+this.top)*this.dataWidth+this.left;System.arraycopy(this.yuvData,offset,row,0,width);return row;}/*@Override*/},{key:"getMatrix",value:function getMatrix(){var width=this.getWidth();var height=this.getHeight();// If the caller asks for the entire underlying image, save the copy and give them the
// original data. The docs specifically warn that result.length must be ignored.
if(width===this.dataWidth&&height===this.dataHeight){return this.yuvData;}var area=width*height;var matrix=new Uint8ClampedArray(area);var inputOffset=this.top*this.dataWidth+this.left;// If the width matches the full width of the underlying data, perform a single copy.
if(width===this.dataWidth){System.arraycopy(this.yuvData,inputOffset,matrix,0,area);return matrix;}// Otherwise copy one cropped row at a time.
for(var y=0;y<height;y++){var outputOffset=y*width;System.arraycopy(this.yuvData,inputOffset,matrix,outputOffset,width);inputOffset+=this.dataWidth;}return matrix;}/*@Override*/},{key:"isCropSupported",value:function isCropSupported(){return true;}/*@Override*/},{key:"crop",value:function crop(left/*int*/,top/*int*/,width/*int*/,height/*int*/){return new PlanarYUVLuminanceSource(this.yuvData,this.dataWidth,this.dataHeight,this.left+left,this.top+top,width,height,false);}},{key:"renderThumbnail",value:function renderThumbnail(){var width=this.getWidth()/PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;var height=this.getHeight()/PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;var pixels=new Int32Array(width*height);var yuv=this.yuvData;var inputOffset=this.top*this.dataWidth+this.left;for(var y=0;y<height;y++){var outputOffset=y*width;for(var x=0;x<width;x++){var grey=yuv[inputOffset+x*PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR]&0xff;pixels[outputOffset+x]=0xFF000000|grey*0x00010101;}inputOffset+=this.dataWidth*PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;}return pixels;}/**
* @return width of image from {@link #renderThumbnail()}
*/},{key:"getThumbnailWidth",value:function getThumbnailWidth(){return this.getWidth()/PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;}/**
* @return height of image from {@link #renderThumbnail()}
*/},{key:"getThumbnailHeight",value:function getThumbnailHeight(){return this.getHeight()/PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;}},{key:"reverseHorizontal",value:function reverseHorizontal(width/*int*/,height/*int*/){var yuvData=this.yuvData;for(var y=0,rowStart=this.top*this.dataWidth+this.left;y<height;y++,rowStart+=this.dataWidth){var middle=rowStart+width/2;for(var x1=rowStart,x2=rowStart+width-1;x1<middle;x1++,x2--){var temp=yuvData[x1];yuvData[x1]=yuvData[x2];yuvData[x2]=temp;}}}},{key:"invert",value:function invert(){return new InvertedLuminanceSource(this);}}]);return PlanarYUVLuminanceSource;}(LuminanceSource);PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR=2;/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* This class is used to help decode images from files which arrive as RGB data from
* an ARGB pixel array. It does not support rotation.
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Betaminos
*/var RGBLuminanceSource=/*#__PURE__*/function(_LuminanceSource4){_inherits(RGBLuminanceSource,_LuminanceSource4);var _super65=_createSuper(RGBLuminanceSource);function RGBLuminanceSource(luminances,width/*int*/,height/*int*/,dataWidth/*int*/,dataHeight/*int*/,left/*int*/,top/*int*/){var _this39;_classCallCheck(this,RGBLuminanceSource);_this39=_super65.call(this,width,height);_this39.dataWidth=dataWidth;_this39.dataHeight=dataHeight;_this39.left=left;_this39.top=top;if(luminances.BYTES_PER_ELEMENT===4){// Int32Array
var size=width*height;var luminancesUint8Array=new Uint8ClampedArray(size);for(var offset=0;offset<size;offset++){var pixel=luminances[offset];var r=pixel>>16&0xff;// red
var g2=pixel>>7&0x1fe;// 2 * green
var b=pixel&0xff;// blue
// Calculate green-favouring average cheaply
luminancesUint8Array[offset]=/*(byte) */(r+g2+b)/4&0xFF;}_this39.luminances=luminancesUint8Array;}else{_this39.luminances=luminances;}if(undefined===dataWidth){_this39.dataWidth=width;}if(undefined===dataHeight){_this39.dataHeight=height;}if(undefined===left){_this39.left=0;}if(undefined===top){_this39.top=0;}if(_this39.left+width>_this39.dataWidth||_this39.top+height>_this39.dataHeight){throw new IllegalArgumentException('Crop rectangle does not fit within image data.');}return _this39;}/*@Override*/_createClass(RGBLuminanceSource,[{key:"getRow",value:function getRow(y/*int*/,row){if(y<0||y>=this.getHeight()){throw new IllegalArgumentException('Requested row is outside the image: '+y);}var width=this.getWidth();if(row===null||row===undefined||row.length<width){row=new Uint8ClampedArray(width);}var offset=(y+this.top)*this.dataWidth+this.left;System.arraycopy(this.luminances,offset,row,0,width);return row;}/*@Override*/},{key:"getMatrix",value:function getMatrix(){var width=this.getWidth();var height=this.getHeight();// If the caller asks for the entire underlying image, save the copy and give them the
// original data. The docs specifically warn that result.length must be ignored.
if(width===this.dataWidth&&height===this.dataHeight){return this.luminances;}var area=width*height;var matrix=new Uint8ClampedArray(area);var inputOffset=this.top*this.dataWidth+this.left;// If the width matches the full width of the underlying data, perform a single copy.
if(width===this.dataWidth){System.arraycopy(this.luminances,inputOffset,matrix,0,area);return matrix;}// Otherwise copy one cropped row at a time.
for(var y=0;y<height;y++){var outputOffset=y*width;System.arraycopy(this.luminances,inputOffset,matrix,outputOffset,width);inputOffset+=this.dataWidth;}return matrix;}/*@Override*/},{key:"isCropSupported",value:function isCropSupported(){return true;}/*@Override*/},{key:"crop",value:function crop(left/*int*/,top/*int*/,width/*int*/,height/*int*/){return new RGBLuminanceSource(this.luminances,width,height,this.dataWidth,this.dataHeight,this.left+left,this.top+top);}},{key:"invert",value:function invert(){return new InvertedLuminanceSource(this);}}]);return RGBLuminanceSource;}(LuminanceSource);/**
* Just to make a shortcut between Java code and TS code.
*/var Charset=/*#__PURE__*/function(_CharacterSetECI){_inherits(Charset,_CharacterSetECI);var _super66=_createSuper(Charset);function Charset(){_classCallCheck(this,Charset);return _super66.apply(this,arguments);}_createClass(Charset,null,[{key:"forName",value:function forName(name){return this.getCharacterSetECIByName(name);}}]);return Charset;}(CharacterSetECI);/**
* Just to make a shortcut between Java code and TS code.
*/var StandardCharsets=/*#__PURE__*/_createClass(function StandardCharsets(){_classCallCheck(this,StandardCharsets);});StandardCharsets.ISO_8859_1=CharacterSetECI.ISO8859_1;/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* Aztec 2D code representation
*
* @author Rustam Abdullaev
*/ /*public final*/var AztecCode=/*#__PURE__*/function(){function AztecCode(){_classCallCheck(this,AztecCode);}_createClass(AztecCode,[{key:"isCompact",value:/**
* @return {@code true} if compact instead of full mode
*/function isCompact(){return this.compact;}},{key:"setCompact",value:function setCompact(compact){this.compact=compact;}/**
* @return size in pixels (width and height)
*/},{key:"getSize",value:function getSize(){return this.size;}},{key:"setSize",value:function setSize(size){this.size=size;}/**
* @return number of levels
*/},{key:"getLayers",value:function getLayers(){return this.layers;}},{key:"setLayers",value:function setLayers(layers){this.layers=layers;}/**
* @return number of data codewords
*/},{key:"getCodeWords",value:function getCodeWords(){return this.codeWords;}},{key:"setCodeWords",value:function setCodeWords(codeWords){this.codeWords=codeWords;}/**
* @return the symbol image
*/},{key:"getMatrix",value:function getMatrix(){return this.matrix;}},{key:"setMatrix",value:function setMatrix(matrix){this.matrix=matrix;}}]);return AztecCode;}();var Collections=/*#__PURE__*/function(){function Collections(){_classCallCheck(this,Collections);}_createClass(Collections,null,[{key:"singletonList",value:/**
* The singletonList(T) method is used to return an immutable list containing only the specified object.
*/function singletonList(item){return[item];}/**
* The min(Collection<? extends T>, Comparator<? super T>) method is used to return the minimum element of the given collection, according to the order induced by the specified comparator.
*/},{key:"min",value:function min(collection,comparator){return collection.sort(comparator)[0];}}]);return Collections;}();/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/var Token=/*#__PURE__*/function(){function Token(previous){_classCallCheck(this,Token);this.previous=previous;}_createClass(Token,[{key:"getPrevious",value:function getPrevious(){return this.previous;}}]);return Token;}();/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*final*/var SimpleToken=/*#__PURE__*/function(_Token){_inherits(SimpleToken,_Token);var _super67=_createSuper(SimpleToken);function SimpleToken(previous,value,bitCount){var _this40;_classCallCheck(this,SimpleToken);_this40=_super67.call(this,previous);_this40.value=value;_this40.bitCount=bitCount;return _this40;}/**
* @Override
*/_createClass(SimpleToken,[{key:"appendTo",value:function appendTo(bitArray,text){bitArray.appendBits(this.value,this.bitCount);}},{key:"add",value:function add(value,bitCount){return new SimpleToken(this,value,bitCount);}},{key:"addBinaryShift",value:function addBinaryShift(start,byteCount){// no-op can't binary shift a simple token
console.warn('addBinaryShift on SimpleToken, this simply returns a copy of this token');return new SimpleToken(this,start,byteCount);}/**
* @Override
*/},{key:"toString",value:function toString(){var value=this.value&(1<<this.bitCount)-1;value|=1<<this.bitCount;return'<'+Integer.toBinaryString(value|1<<this.bitCount).substring(1)+'>';}}]);return SimpleToken;}(Token);/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /*final*/var BinaryShiftToken=/*#__PURE__*/function(_SimpleToken){_inherits(BinaryShiftToken,_SimpleToken);var _super68=_createSuper(BinaryShiftToken);function BinaryShiftToken(previous,binaryShiftStart,binaryShiftByteCount){var _this41;_classCallCheck(this,BinaryShiftToken);_this41=_super68.call(this,previous,0,0);_this41.binaryShiftStart=binaryShiftStart;_this41.binaryShiftByteCount=binaryShiftByteCount;return _this41;}/**
* @Override
*/_createClass(BinaryShiftToken,[{key:"appendTo",value:function appendTo(bitArray,text){for(var i=0;i<this.binaryShiftByteCount;i++){if(i===0||i===31&&this.binaryShiftByteCount<=62){// We need a header before the first character, and before
// character 31 when the total byte code is <= 62
bitArray.appendBits(31,5);// BINARY_SHIFT
if(this.binaryShiftByteCount>62){bitArray.appendBits(this.binaryShiftByteCount-31,16);}else if(i===0){// 1 <= binaryShiftByteCode <= 62
bitArray.appendBits(Math.min(this.binaryShiftByteCount,31),5);}else{// 32 <= binaryShiftCount <= 62 and i == 31
bitArray.appendBits(this.binaryShiftByteCount-31,5);}}bitArray.appendBits(text[this.binaryShiftStart+i],8);}}},{key:"addBinaryShift",value:function addBinaryShift(start,byteCount){// int bitCount = (byteCount * 8) + (byteCount <= 31 ? 10 : byteCount <= 62 ? 20 : 21);
return new BinaryShiftToken(this,start,byteCount);}/**
* @Override
*/},{key:"toString",value:function toString(){return'<'+this.binaryShiftStart+'::'+(this.binaryShiftStart+this.binaryShiftByteCount-1)+'>';}}]);return BinaryShiftToken;}(SimpleToken);function addBinaryShift(token,start,byteCount){// int bitCount = (byteCount * 8) + (byteCount <= 31 ? 10 : byteCount <= 62 ? 20 : 21);
return new BinaryShiftToken(token,start,byteCount);}function add(token,value,bitCount){return new SimpleToken(token,value,bitCount);}var/*final*/MODE_NAMES=['UPPER','LOWER','DIGIT','MIXED','PUNCT'];var/*final*/MODE_UPPER=0;// 5 bits
var/*final*/MODE_LOWER=1;// 5 bits
var/*final*/MODE_DIGIT=2;// 4 bits
var/*final*/MODE_MIXED=3;// 5 bits
var/*final*/MODE_PUNCT=4;// 5 bits
var EMPTY_TOKEN=new SimpleToken(null,0,0);// The Latch Table shows, for each pair of Modes, the optimal method for
// getting from one mode to another. In the worst possible case, this can
// be up to 14 bits. In the best possible case, we are already there!
// The high half-word of each entry gives the number of bits.
// The low half-word of each entry are the actual bits necessary to change
var LATCH_TABLE=[Int32Array.from([0,(5<<16)+28,(5<<16)+30,(5<<16)+29,(10<<16)+(29<<5)+30// UPPER -> MIXED -> PUNCT
]),Int32Array.from([(9<<16)+(30<<4)+14,0,(5<<16)+30,(5<<16)+29,(10<<16)+(29<<5)+30// LOWER -> MIXED -> PUNCT
]),Int32Array.from([(4<<16)+14,(9<<16)+(14<<5)+28,0,(9<<16)+(14<<5)+29,(14<<16)+(14<<10)+(29<<5)+30// DIGIT -> UPPER -> MIXED -> PUNCT
]),Int32Array.from([(5<<16)+29,(5<<16)+28,(10<<16)+(29<<5)+30,0,(5<<16)+30// MIXED -> PUNCT
]),Int32Array.from([(5<<16)+31,(10<<16)+(31<<5)+28,(10<<16)+(31<<5)+30,(10<<16)+(31<<5)+29,0])];function static_SHIFT_TABLE(SHIFT_TABLE){var _iterator71=_createForOfIteratorHelper(SHIFT_TABLE),_step71;try{for(_iterator71.s();!(_step71=_iterator71.n()).done;){var table=_step71.value;Arrays.fill(table,-1);}}catch(err){_iterator71.e(err);}finally{_iterator71.f();}SHIFT_TABLE[MODE_UPPER][MODE_PUNCT]=0;SHIFT_TABLE[MODE_LOWER][MODE_PUNCT]=0;SHIFT_TABLE[MODE_LOWER][MODE_UPPER]=28;SHIFT_TABLE[MODE_MIXED][MODE_PUNCT]=0;SHIFT_TABLE[MODE_DIGIT][MODE_PUNCT]=0;SHIFT_TABLE[MODE_DIGIT][MODE_UPPER]=15;return SHIFT_TABLE;}var/*final*/SHIFT_TABLE=static_SHIFT_TABLE(Arrays.createInt32Array(6,6));// mode shift codes, per table
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* State represents all information about a sequence necessary to generate the current output.
* Note that a state is immutable.
*/ /*final*/var State=/*#__PURE__*/function(){function State(token,mode,binaryBytes,bitCount){_classCallCheck(this,State);this.token=token;this.mode=mode;this.binaryShiftByteCount=binaryBytes;this.bitCount=bitCount;// Make sure we match the token
// int binaryShiftBitCount = (binaryShiftByteCount * 8) +
// (binaryShiftByteCount === 0 ? 0 :
// binaryShiftByteCount <= 31 ? 10 :
// binaryShiftByteCount <= 62 ? 20 : 21);
// assert this.bitCount === token.getTotalBitCount() + binaryShiftBitCount;
}_createClass(State,[{key:"getMode",value:function getMode(){return this.mode;}},{key:"getToken",value:function getToken(){return this.token;}},{key:"getBinaryShiftByteCount",value:function getBinaryShiftByteCount(){return this.binaryShiftByteCount;}},{key:"getBitCount",value:function getBitCount(){return this.bitCount;}// Create a new state representing this state with a latch to a (not
// necessary different) mode, and then a code.
},{key:"latchAndAppend",value:function latchAndAppend(mode,value){// assert binaryShiftByteCount === 0;
var bitCount=this.bitCount;var token=this.token;if(mode!==this.mode){var latch=LATCH_TABLE[this.mode][mode];token=add(token,latch&0xffff,latch>>16);bitCount+=latch>>16;}var latchModeBitCount=mode===MODE_DIGIT?4:5;token=add(token,value,latchModeBitCount);return new State(token,mode,0,bitCount+latchModeBitCount);}// Create a new state representing this state, with a temporary shift
// to a different mode to output a single value.
},{key:"shiftAndAppend",value:function shiftAndAppend(mode,value){// assert binaryShiftByteCount === 0 && this.mode !== mode;
var token=this.token;var thisModeBitCount=this.mode===MODE_DIGIT?4:5;// Shifts exist only to UPPER and PUNCT, both with tokens size 5.
token=add(token,SHIFT_TABLE[this.mode][mode],thisModeBitCount);token=add(token,value,5);return new State(token,this.mode,0,this.bitCount+thisModeBitCount+5);}// Create a new state representing this state, but an additional character
// output in Binary Shift mode.
},{key:"addBinaryShiftChar",value:function addBinaryShiftChar(index){var token=this.token;var mode=this.mode;var bitCount=this.bitCount;if(this.mode===MODE_PUNCT||this.mode===MODE_DIGIT){// assert binaryShiftByteCount === 0;
var latch=LATCH_TABLE[mode][MODE_UPPER];token=add(token,latch&0xffff,latch>>16);bitCount+=latch>>16;mode=MODE_UPPER;}var deltaBitCount=this.binaryShiftByteCount===0||this.binaryShiftByteCount===31?18:this.binaryShiftByteCount===62?9:8;var result=new State(token,mode,this.binaryShiftByteCount+1,bitCount+deltaBitCount);if(result.binaryShiftByteCount===2047+31){// The string is as long as it's allowed to be. We should end it.
result=result.endBinaryShift(index+1);}return result;}// Create the state identical to this one, but we are no longer in
// Binary Shift mode.
},{key:"endBinaryShift",value:function endBinaryShift(index){if(this.binaryShiftByteCount===0){return this;}var token=this.token;token=addBinaryShift(token,index-this.binaryShiftByteCount,this.binaryShiftByteCount);// assert token.getTotalBitCount() === this.bitCount;
return new State(token,this.mode,0,this.bitCount);}// Returns true if "this" state is better (equal: or) to be in than "that"
// state under all possible circumstances.
},{key:"isBetterThanOrEqualTo",value:function isBetterThanOrEqualTo(other){var newModeBitCount=this.bitCount+(LATCH_TABLE[this.mode][other.mode]>>16);if(this.binaryShiftByteCount<other.binaryShiftByteCount){// add additional B/S encoding cost of other, if any
newModeBitCount+=State.calculateBinaryShiftCost(other)-State.calculateBinaryShiftCost(this);}else if(this.binaryShiftByteCount>other.binaryShiftByteCount&&other.binaryShiftByteCount>0){// maximum possible additional cost (it: h)
newModeBitCount+=10;}return newModeBitCount<=other.bitCount;}},{key:"toBitArray",value:function toBitArray(text){// Reverse the tokens, so that they are in the order that they should
// be output
var symbols=[];for(var token=this.endBinaryShift(text.length).token;token!==null;token=token.getPrevious()){symbols.unshift(token);}var bitArray=new BitArray();// Add each token to the result.
for(var _i42=0,_symbols=symbols;_i42<_symbols.length;_i42++){var symbol=_symbols[_i42];symbol.appendTo(bitArray,text);}// assert bitArray.getSize() === this.bitCount;
return bitArray;}/**
* @Override
*/},{key:"toString",value:function toString(){return StringUtils.format('%s bits=%d bytes=%d',MODE_NAMES[this.mode],this.bitCount,this.binaryShiftByteCount);}}],[{key:"calculateBinaryShiftCost",value:function calculateBinaryShiftCost(state){if(state.binaryShiftByteCount>62){return 21;// B/S with extended length
}if(state.binaryShiftByteCount>31){return 20;// two B/S
}if(state.binaryShiftByteCount>0){return 10;// one B/S
}return 0;}}]);return State;}();State.INITIAL_STATE=new State(EMPTY_TOKEN,MODE_UPPER,0,0);function static_CHAR_MAP(CHAR_MAP){var spaceCharCode=StringUtils.getCharCode(' ');var pointCharCode=StringUtils.getCharCode('.');var commaCharCode=StringUtils.getCharCode(',');CHAR_MAP[MODE_UPPER][spaceCharCode]=1;var zUpperCharCode=StringUtils.getCharCode('Z');var aUpperCharCode=StringUtils.getCharCode('A');for(var c=aUpperCharCode;c<=zUpperCharCode;c++){CHAR_MAP[MODE_UPPER][c]=c-aUpperCharCode+2;}CHAR_MAP[MODE_LOWER][spaceCharCode]=1;var zLowerCharCode=StringUtils.getCharCode('z');var aLowerCharCode=StringUtils.getCharCode('a');for(var _c=aLowerCharCode;_c<=zLowerCharCode;_c++){CHAR_MAP[MODE_LOWER][_c]=_c-aLowerCharCode+2;}CHAR_MAP[MODE_DIGIT][spaceCharCode]=1;var nineCharCode=StringUtils.getCharCode('9');var zeroCharCode=StringUtils.getCharCode('0');for(var _c2=zeroCharCode;_c2<=nineCharCode;_c2++){CHAR_MAP[MODE_DIGIT][_c2]=_c2-zeroCharCode+2;}CHAR_MAP[MODE_DIGIT][commaCharCode]=12;CHAR_MAP[MODE_DIGIT][pointCharCode]=13;var mixedTable=['\x00',' ','\x01','\x02','\x03','\x04','\x05','\x06','\x07','\b','\t','\n','\x0b','\f','\r','\x1b','\x1c','\x1d','\x1e','\x1f','@','\\','^','_','`','|','~','\x7f'];for(var i=0;i<mixedTable.length;i++){CHAR_MAP[MODE_MIXED][StringUtils.getCharCode(mixedTable[i])]=i;}var punctTable=['\x00','\r','\x00','\x00','\x00','\x00','!','\'','#','$','%','&','\'','(',')','*','+',',','-','.','/',':',';','<','=','>','?','[',']','{','}'];for(var _i43=0;_i43<punctTable.length;_i43++){if(StringUtils.getCharCode(punctTable[_i43])>0){CHAR_MAP[MODE_PUNCT][StringUtils.getCharCode(punctTable[_i43])]=_i43;}}return CHAR_MAP;}var CHAR_MAP=static_CHAR_MAP(Arrays.createInt32Array(5,256));/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* This produces nearly optimal encodings of text into the first-level of
* encoding used by Aztec code.
*
* It uses a dynamic algorithm. For each prefix of the string, it determines
* a set of encodings that could lead to this prefix. We repeatedly add a
* character and generate a new set of optimal encodings until we have read
* through the entire input.
*
* @author Frank Yellin
* @author Rustam Abdullaev
*/ /*public final*/var HighLevelEncoder=/*#__PURE__*/function(){function HighLevelEncoder(text){_classCallCheck(this,HighLevelEncoder);this.text=text;}/**
* @return text represented by this encoder encoded as a {@link BitArray}
*/_createClass(HighLevelEncoder,[{key:"encode",value:function encode(){var spaceCharCode=StringUtils.getCharCode(' ');var lineBreakCharCode=StringUtils.getCharCode('\n');var states=Collections.singletonList(State.INITIAL_STATE);for(var index=0;index<this.text.length;index++){var pairCode=void 0;var nextChar=index+1<this.text.length?this.text[index+1]:0;switch(this.text[index]){case StringUtils.getCharCode('\r'):pairCode=nextChar===lineBreakCharCode?2:0;break;case StringUtils.getCharCode('.'):pairCode=nextChar===spaceCharCode?3:0;break;case StringUtils.getCharCode(','):pairCode=nextChar===spaceCharCode?4:0;break;case StringUtils.getCharCode(':'):pairCode=nextChar===spaceCharCode?5:0;break;default:pairCode=0;}if(pairCode>0){// We have one of the four special PUNCT pairs. Treat them specially.
// Get a new set of states for the two new characters.
states=HighLevelEncoder.updateStateListForPair(states,index,pairCode);index++;}else{// Get a new set of states for the new character.
states=this.updateStateListForChar(states,index);}}// We are left with a set of states. Find the shortest one.
var minState=Collections.min(states,function(a,b){return a.getBitCount()-b.getBitCount();});// Convert it to a bit array, and return.
return minState.toBitArray(this.text);}// We update a set of states for a new character by updating each state
// for the new character, merging the results, and then removing the
// non-optimal states.
},{key:"updateStateListForChar",value:function updateStateListForChar(states,index){var result=[];var _iterator72=_createForOfIteratorHelper(states),_step72;try{for(_iterator72.s();!(_step72=_iterator72.n()).done;){var state=_step72.value;this.updateStateForChar(state,index,result);}}catch(err){_iterator72.e(err);}finally{_iterator72.f();}return HighLevelEncoder.simplifyStates(result);}// Return a set of states that represent the possible ways of updating this
// state for the next character. The resulting set of states are added to
// the "result" list.
},{key:"updateStateForChar",value:function updateStateForChar(state,index,result){var ch=this.text[index]&0xff;var charInCurrentTable=CHAR_MAP[state.getMode()][ch]>0;var stateNoBinary=null;for(var mode/*int*/=0;mode<=MODE_PUNCT;mode++){var charInMode=CHAR_MAP[mode][ch];if(charInMode>0){if(stateNoBinary==null){// Only create stateNoBinary the first time it's required.
stateNoBinary=state.endBinaryShift(index);}// Try generating the character by latching to its mode
if(!charInCurrentTable||mode===state.getMode()||mode===MODE_DIGIT){// If the character is in the current table, we don't want to latch to
// any other mode except possibly digit (which uses only 4 bits). Any
// other latch would be equally successful *after* this character, and
// so wouldn't save any bits.
var latchState=stateNoBinary.latchAndAppend(mode,charInMode);result.push(latchState);}// Try generating the character by switching to its mode.
if(!charInCurrentTable&&SHIFT_TABLE[state.getMode()][mode]>=0){// It never makes sense to temporarily shift to another mode if the
// character exists in the current mode. That can never save bits.
var shiftState=stateNoBinary.shiftAndAppend(mode,charInMode);result.push(shiftState);}}}if(state.getBinaryShiftByteCount()>0||CHAR_MAP[state.getMode()][ch]===0){// It's never worthwhile to go into binary shift mode if you're not already
// in binary shift mode, and the character exists in your current mode.
// That can never save bits over just outputting the char in the current mode.
var binaryState=state.addBinaryShiftChar(index);result.push(binaryState);}}}],[{key:"updateStateListForPair",value:function updateStateListForPair(states,index,pairCode){var result=[];var _iterator73=_createForOfIteratorHelper(states),_step73;try{for(_iterator73.s();!(_step73=_iterator73.n()).done;){var state=_step73.value;this.updateStateForPair(state,index,pairCode,result);}}catch(err){_iterator73.e(err);}finally{_iterator73.f();}return this.simplifyStates(result);}},{key:"updateStateForPair",value:function updateStateForPair(state,index,pairCode,result){var stateNoBinary=state.endBinaryShift(index);// Possibility 1. Latch to C.MODE_PUNCT, and then append this code
result.push(stateNoBinary.latchAndAppend(MODE_PUNCT,pairCode));if(state.getMode()!==MODE_PUNCT){// Possibility 2. Shift to C.MODE_PUNCT, and then append this code.
// Every state except C.MODE_PUNCT (handled above) can shift
result.push(stateNoBinary.shiftAndAppend(MODE_PUNCT,pairCode));}if(pairCode===3||pairCode===4){// both characters are in DIGITS. Sometimes better to just add two digits
var digitState=stateNoBinary.latchAndAppend(MODE_DIGIT,16-pairCode)// period or comma in DIGIT
.latchAndAppend(MODE_DIGIT,1);// space in DIGIT
result.push(digitState);}if(state.getBinaryShiftByteCount()>0){// It only makes sense to do the characters as binary if we're already
// in binary mode.
var binaryState=state.addBinaryShiftChar(index).addBinaryShiftChar(index+1);result.push(binaryState);}}},{key:"simplifyStates",value:function simplifyStates(states){var result=[];var _iterator74=_createForOfIteratorHelper(states),_step74;try{for(_iterator74.s();!(_step74=_iterator74.n()).done;){var newState=_step74.value;var _add=true;var _iterator75=_createForOfIteratorHelper(result),_step75;try{var _loop2=function _loop2(){var oldState=_step75.value;if(oldState.isBetterThanOrEqualTo(newState)){_add=false;return"break";}if(newState.isBetterThanOrEqualTo(oldState)){// iterator.remove();
result=result.filter(function(x){return x!==oldState;});// remove old state
}};for(_iterator75.s();!(_step75=_iterator75.n()).done;){var _ret=_loop2();if(_ret==="break")break;}}catch(err){_iterator75.e(err);}finally{_iterator75.f();}if(_add){result.push(newState);}}}catch(err){_iterator74.e(err);}finally{_iterator74.f();}return result;}}]);return HighLevelEncoder;}();/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ // package com.google.zxing.aztec.encoder;
// import com.google.zxing.common.BitArray;
// import com.google.zxing.common.BitMatrix;
// import com.google.zxing.common.reedsolomon.GenericGF;
// import com.google.zxing.common.reedsolomon.ReedSolomonEncoder;
/**
* Generates Aztec 2D barcodes.
*
* @author Rustam Abdullaev
*/ /*public final*/var Encoder$1=/*#__PURE__*/function(){function Encoder$1(){_classCallCheck(this,Encoder$1);}/**
* Encodes the given binary content as an Aztec symbol
*
* @param data input data string
* @return Aztec symbol matrix with metadata
*/_createClass(Encoder$1,null,[{key:"encodeBytes",value:function encodeBytes(data){return Encoder$1.encode(data,Encoder$1.DEFAULT_EC_PERCENT,Encoder$1.DEFAULT_AZTEC_LAYERS);}/**
* Encodes the given binary content as an Aztec symbol
*
* @param data input data string
* @param minECCPercent minimal percentage of error check words (According to ISO/IEC 24778:2008,
* a minimum of 23% + 3 words is recommended)
* @param userSpecifiedLayers if non-zero, a user-specified value for the number of layers
* @return Aztec symbol matrix with metadata
*/},{key:"encode",value:function encode(data,minECCPercent,userSpecifiedLayers){// High-level encode
var bits=new HighLevelEncoder(data).encode();// stuff bits and choose symbol size
var eccBits=Integer.truncDivision(bits.getSize()*minECCPercent,100)+11;var totalSizeBits=bits.getSize()+eccBits;var compact;var layers;var totalBitsInLayer;var wordSize;var stuffedBits;if(userSpecifiedLayers!==Encoder$1.DEFAULT_AZTEC_LAYERS){compact=userSpecifiedLayers<0;layers=Math.abs(userSpecifiedLayers);if(layers>(compact?Encoder$1.MAX_NB_BITS_COMPACT:Encoder$1.MAX_NB_BITS)){throw new IllegalArgumentException(StringUtils.format('Illegal value %s for layers',userSpecifiedLayers));}totalBitsInLayer=Encoder$1.totalBitsInLayer(layers,compact);wordSize=Encoder$1.WORD_SIZE[layers];var usableBitsInLayers=totalBitsInLayer-totalBitsInLayer%wordSize;stuffedBits=Encoder$1.stuffBits(bits,wordSize);if(stuffedBits.getSize()+eccBits>usableBitsInLayers){throw new IllegalArgumentException('Data to large for user specified layer');}if(compact&&stuffedBits.getSize()>wordSize*64){// Compact format only allows 64 data words, though C4 can hold more words than that
throw new IllegalArgumentException('Data to large for user specified layer');}}else{wordSize=0;stuffedBits=null;// We look at the possible table sizes in the order Compact1, Compact2, Compact3,
// Compact4, Normal4,... Normal(i) for i < 4 isn't typically used since Compact(i+1)
// is the same size, but has more data.
for(var i/*int*/=0;;i++){if(i>Encoder$1.MAX_NB_BITS){throw new IllegalArgumentException('Data too large for an Aztec code');}compact=i<=3;layers=compact?i+1:i;totalBitsInLayer=Encoder$1.totalBitsInLayer(layers,compact);if(totalSizeBits>totalBitsInLayer){continue;}// [Re]stuff the bits if this is the first opportunity, or if the
// wordSize has changed
if(stuffedBits==null||wordSize!==Encoder$1.WORD_SIZE[layers]){wordSize=Encoder$1.WORD_SIZE[layers];stuffedBits=Encoder$1.stuffBits(bits,wordSize);}var _usableBitsInLayers=totalBitsInLayer-totalBitsInLayer%wordSize;if(compact&&stuffedBits.getSize()>wordSize*64){// Compact format only allows 64 data words, though C4 can hold more words than that
continue;}if(stuffedBits.getSize()+eccBits<=_usableBitsInLayers){break;}}}var messageBits=Encoder$1.generateCheckWords(stuffedBits,totalBitsInLayer,wordSize);// generate mode message
var messageSizeInWords=stuffedBits.getSize()/wordSize;var modeMessage=Encoder$1.generateModeMessage(compact,layers,messageSizeInWords);// allocate symbol
var baseMatrixSize=(compact?11:14)+layers*4;// not including alignment lines
var alignmentMap=new Int32Array(baseMatrixSize);var matrixSize;if(compact){// no alignment marks in compact mode, alignmentMap is a no-op
matrixSize=baseMatrixSize;for(var _i44/*int*/=0;_i44<alignmentMap.length;_i44++){alignmentMap[_i44]=_i44;}}else{matrixSize=baseMatrixSize+1+2*Integer.truncDivision(Integer.truncDivision(baseMatrixSize,2)-1,15);var origCenter=Integer.truncDivision(baseMatrixSize,2);var center=Integer.truncDivision(matrixSize,2);for(var _i45/*int*/=0;_i45<origCenter;_i45++){var newOffset=_i45+Integer.truncDivision(_i45,15);alignmentMap[origCenter-_i45-1]=center-newOffset-1;alignmentMap[origCenter+_i45]=center+newOffset+1;}}var matrix=new BitMatrix(matrixSize);// draw data bits
for(var _i46/*int*/=0,rowOffset=0;_i46<layers;_i46++){var rowSize=(layers-_i46)*4+(compact?9:12);for(var j/*int*/=0;j<rowSize;j++){var columnOffset=j*2;for(var k/*int*/=0;k<2;k++){if(messageBits.get(rowOffset+columnOffset+k)){matrix.set(alignmentMap[_i46*2+k],alignmentMap[_i46*2+j]);}if(messageBits.get(rowOffset+rowSize*2+columnOffset+k)){matrix.set(alignmentMap[_i46*2+j],alignmentMap[baseMatrixSize-1-_i46*2-k]);}if(messageBits.get(rowOffset+rowSize*4+columnOffset+k)){matrix.set(alignmentMap[baseMatrixSize-1-_i46*2-k],alignmentMap[baseMatrixSize-1-_i46*2-j]);}if(messageBits.get(rowOffset+rowSize*6+columnOffset+k)){matrix.set(alignmentMap[baseMatrixSize-1-_i46*2-j],alignmentMap[_i46*2+k]);}}}rowOffset+=rowSize*8;}// draw mode message
Encoder$1.drawModeMessage(matrix,compact,matrixSize,modeMessage);// draw alignment marks
if(compact){Encoder$1.drawBullsEye(matrix,Integer.truncDivision(matrixSize,2),5);}else{Encoder$1.drawBullsEye(matrix,Integer.truncDivision(matrixSize,2),7);for(var _i47/*int*/=0,_j9=0;_i47<Integer.truncDivision(baseMatrixSize,2)-1;_i47+=15,_j9+=16){for(var _k/*int*/=Integer.truncDivision(matrixSize,2)&1;_k<matrixSize;_k+=2){matrix.set(Integer.truncDivision(matrixSize,2)-_j9,_k);matrix.set(Integer.truncDivision(matrixSize,2)+_j9,_k);matrix.set(_k,Integer.truncDivision(matrixSize,2)-_j9);matrix.set(_k,Integer.truncDivision(matrixSize,2)+_j9);}}}var aztec=new AztecCode();aztec.setCompact(compact);aztec.setSize(matrixSize);aztec.setLayers(layers);aztec.setCodeWords(messageSizeInWords);aztec.setMatrix(matrix);return aztec;}},{key:"drawBullsEye",value:function drawBullsEye(matrix,center,size){for(var i/*int*/=0;i<size;i+=2){for(var j/*int*/=center-i;j<=center+i;j++){matrix.set(j,center-i);matrix.set(j,center+i);matrix.set(center-i,j);matrix.set(center+i,j);}}matrix.set(center-size,center-size);matrix.set(center-size+1,center-size);matrix.set(center-size,center-size+1);matrix.set(center+size,center-size);matrix.set(center+size,center-size+1);matrix.set(center+size,center+size-1);}},{key:"generateModeMessage",value:function generateModeMessage(compact,layers,messageSizeInWords){var modeMessage=new BitArray();if(compact){modeMessage.appendBits(layers-1,2);modeMessage.appendBits(messageSizeInWords-1,6);modeMessage=Encoder$1.generateCheckWords(modeMessage,28,4);}else{modeMessage.appendBits(layers-1,5);modeMessage.appendBits(messageSizeInWords-1,11);modeMessage=Encoder$1.generateCheckWords(modeMessage,40,4);}return modeMessage;}},{key:"drawModeMessage",value:function drawModeMessage(matrix,compact,matrixSize,modeMessage){var center=Integer.truncDivision(matrixSize,2);if(compact){for(var i/*int*/=0;i<7;i++){var offset=center-3+i;if(modeMessage.get(i)){matrix.set(offset,center-5);}if(modeMessage.get(i+7)){matrix.set(center+5,offset);}if(modeMessage.get(20-i)){matrix.set(offset,center+5);}if(modeMessage.get(27-i)){matrix.set(center-5,offset);}}}else{for(var _i48/*int*/=0;_i48<10;_i48++){var _offset2=center-5+_i48+Integer.truncDivision(_i48,5);if(modeMessage.get(_i48)){matrix.set(_offset2,center-7);}if(modeMessage.get(_i48+10)){matrix.set(center+7,_offset2);}if(modeMessage.get(29-_i48)){matrix.set(_offset2,center+7);}if(modeMessage.get(39-_i48)){matrix.set(center-7,_offset2);}}}}},{key:"generateCheckWords",value:function generateCheckWords(bitArray,totalBits,wordSize){// bitArray is guaranteed to be a multiple of the wordSize, so no padding needed
var messageSizeInWords=bitArray.getSize()/wordSize;var rs=new ReedSolomonEncoder(Encoder$1.getGF(wordSize));var totalWords=Integer.truncDivision(totalBits,wordSize);var messageWords=Encoder$1.bitsToWords(bitArray,wordSize,totalWords);rs.encode(messageWords,totalWords-messageSizeInWords);var startPad=totalBits%wordSize;var messageBits=new BitArray();messageBits.appendBits(0,startPad);for(var _i49=0,_Array$from=Array.from(messageWords);_i49<_Array$from.length;_i49++){var messageWord=_Array$from[_i49];/*: int*/messageBits.appendBits(messageWord,wordSize);}return messageBits;}},{key:"bitsToWords",value:function bitsToWords(stuffedBits,wordSize,totalWords){var message=new Int32Array(totalWords);var i;var n;for(i=0,n=stuffedBits.getSize()/wordSize;i<n;i++){var value=0;for(var j/*int*/=0;j<wordSize;j++){value|=stuffedBits.get(i*wordSize+j)?1<<wordSize-j-1:0;}message[i]=value;}return message;}},{key:"getGF",value:function getGF(wordSize){switch(wordSize){case 4:return GenericGF.AZTEC_PARAM;case 6:return GenericGF.AZTEC_DATA_6;case 8:return GenericGF.AZTEC_DATA_8;case 10:return GenericGF.AZTEC_DATA_10;case 12:return GenericGF.AZTEC_DATA_12;default:throw new IllegalArgumentException('Unsupported word size '+wordSize);}}},{key:"stuffBits",value:function stuffBits(bits,wordSize){var out=new BitArray();var n=bits.getSize();var mask=(1<<wordSize)-2;for(var i/*int*/=0;i<n;i+=wordSize){var word=0;for(var j/*int*/=0;j<wordSize;j++){if(i+j>=n||bits.get(i+j)){word|=1<<wordSize-1-j;}}if((word&mask)===mask){out.appendBits(word&mask,wordSize);i--;}else if((word&mask)===0){out.appendBits(word|1,wordSize);i--;}else{out.appendBits(word,wordSize);}}return out;}},{key:"totalBitsInLayer",value:function totalBitsInLayer(layers,compact){return((compact?88:112)+16*layers)*layers;}}]);return Encoder$1;}();Encoder$1.DEFAULT_EC_PERCENT=33;// default minimal percentage of error check words
Encoder$1.DEFAULT_AZTEC_LAYERS=0;Encoder$1.MAX_NB_BITS=32;Encoder$1.MAX_NB_BITS_COMPACT=4;Encoder$1.WORD_SIZE=Int32Array.from([4,6,6,8,8,8,8,8,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,12,12,12,12,12,12,12,12,12,12]);/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* Renders an Aztec code as a {@link BitMatrix}.
*/ /*public final*/var AztecWriter=/*#__PURE__*/function(){function AztecWriter(){_classCallCheck(this,AztecWriter);}_createClass(AztecWriter,[{key:"encode",value:// @Override
function encode(contents,format,width,height){return this.encodeWithHints(contents,format,width,height,null);}// @Override
},{key:"encodeWithHints",value:function encodeWithHints(contents,format,width,height,hints){var charset=StandardCharsets.ISO_8859_1;var eccPercent=Encoder$1.DEFAULT_EC_PERCENT;var layers=Encoder$1.DEFAULT_AZTEC_LAYERS;if(hints!=null){if(hints.has(EncodeHintType$1.CHARACTER_SET)){charset=Charset.forName(hints.get(EncodeHintType$1.CHARACTER_SET).toString());}if(hints.has(EncodeHintType$1.ERROR_CORRECTION)){eccPercent=Integer.parseInt(hints.get(EncodeHintType$1.ERROR_CORRECTION).toString());}if(hints.has(EncodeHintType$1.AZTEC_LAYERS)){layers=Integer.parseInt(hints.get(EncodeHintType$1.AZTEC_LAYERS).toString());}}return AztecWriter.encodeLayers(contents,format,width,height,charset,eccPercent,layers);}}],[{key:"encodeLayers",value:function encodeLayers(contents,format,width,height,charset,eccPercent,layers){if(format!==BarcodeFormat$1.AZTEC){throw new IllegalArgumentException('Can only encode AZTEC, but got '+format);}var aztec=Encoder$1.encode(StringUtils.getBytes(contents,charset),eccPercent,layers);return AztecWriter.renderResult(aztec,width,height);}},{key:"renderResult",value:function renderResult(code,width,height){var input=code.getMatrix();if(input==null){throw new IllegalStateException();}var inputWidth=input.getWidth();var inputHeight=input.getHeight();var outputWidth=Math.max(width,inputWidth);var outputHeight=Math.max(height,inputHeight);var multiple=Math.min(outputWidth/inputWidth,outputHeight/inputHeight);var leftPadding=(outputWidth-inputWidth*multiple)/2;var topPadding=(outputHeight-inputHeight*multiple)/2;var output=new BitMatrix(outputWidth,outputHeight);for(var inputY/*int*/=0,outputY=topPadding;inputY<inputHeight;inputY++,outputY+=multiple){// Write the contents of this row of the barcode
for(var inputX/*int*/=0,outputX=leftPadding;inputX<inputWidth;inputX++,outputX+=multiple){if(input.get(inputX,inputY)){output.setRegion(outputX,outputY,multiple,multiple);}}}return output;}}]);return AztecWriter;}();exports.AbstractExpandedDecoder=AbstractExpandedDecoder;exports.ArgumentException=ArgumentException;exports.ArithmeticException=ArithmeticException;exports.AztecCode=AztecCode;exports.AztecCodeReader=AztecReader;exports.AztecCodeWriter=AztecWriter;exports.AztecDecoder=Decoder;exports.AztecDetector=Detector;exports.AztecDetectorResult=AztecDetectorResult;exports.AztecEncoder=Encoder$1;exports.AztecHighLevelEncoder=HighLevelEncoder;exports.AztecPoint=Point;exports.BarcodeFormat=BarcodeFormat$1;exports.Binarizer=Binarizer;exports.BinaryBitmap=BinaryBitmap;exports.BitArray=BitArray;exports.BitMatrix=BitMatrix;exports.BitSource=BitSource;exports.BrowserAztecCodeReader=BrowserAztecCodeReader;exports.BrowserBarcodeReader=BrowserBarcodeReader;exports.BrowserCodeReader=BrowserCodeReader;exports.BrowserDatamatrixCodeReader=BrowserDatamatrixCodeReader;exports.BrowserMultiFormatReader=BrowserMultiFormatReader;exports.BrowserPDF417Reader=BrowserPDF417Reader;exports.BrowserQRCodeReader=BrowserQRCodeReader;exports.BrowserQRCodeSvgWriter=BrowserQRCodeSvgWriter;exports.CharacterSetECI=CharacterSetECI;exports.ChecksumException=ChecksumException;exports.Code128Reader=Code128Reader;exports.Code39Reader=Code39Reader;exports.DataMatrixDecodedBitStreamParser=DecodedBitStreamParser;exports.DataMatrixReader=DataMatrixReader;exports.DecodeHintType=DecodeHintType$1;exports.DecoderResult=DecoderResult;exports.DefaultGridSampler=DefaultGridSampler;exports.DetectorResult=DetectorResult;exports.EAN13Reader=EAN13Reader;exports.EncodeHintType=EncodeHintType$1;exports.Exception=Exception;exports.FormatException=FormatException;exports.GenericGF=GenericGF;exports.GenericGFPoly=GenericGFPoly;exports.GlobalHistogramBinarizer=GlobalHistogramBinarizer;exports.GridSampler=GridSampler;exports.GridSamplerInstance=GridSamplerInstance;exports.HTMLCanvasElementLuminanceSource=HTMLCanvasElementLuminanceSource;exports.HybridBinarizer=HybridBinarizer;exports.ITFReader=ITFReader;exports.IllegalArgumentException=IllegalArgumentException;exports.IllegalStateException=IllegalStateException;exports.InvertedLuminanceSource=InvertedLuminanceSource;exports.LuminanceSource=LuminanceSource;exports.MathUtils=MathUtils;exports.MultiFormatOneDReader=MultiFormatOneDReader;exports.MultiFormatReader=MultiFormatReader;exports.MultiFormatWriter=MultiFormatWriter;exports.NotFoundException=NotFoundException;exports.OneDReader=OneDReader;exports.PDF417DecodedBitStreamParser=DecodedBitStreamParser$2;exports.PDF417DecoderErrorCorrection=ErrorCorrection;exports.PDF417Reader=PDF417Reader;exports.PDF417ResultMetadata=PDF417ResultMetadata;exports.PerspectiveTransform=PerspectiveTransform;exports.PlanarYUVLuminanceSource=PlanarYUVLuminanceSource;exports.QRCodeByteMatrix=ByteMatrix;exports.QRCodeDataMask=DataMask;exports.QRCodeDecodedBitStreamParser=DecodedBitStreamParser$1;exports.QRCodeDecoderErrorCorrectionLevel=ErrorCorrectionLevel;exports.QRCodeDecoderFormatInformation=FormatInformation;exports.QRCodeEncoder=Encoder;exports.QRCodeEncoderQRCode=QRCode;exports.QRCodeMaskUtil=MaskUtil;exports.QRCodeMatrixUtil=MatrixUtil;exports.QRCodeMode=Mode$1;exports.QRCodeReader=QRCodeReader;exports.QRCodeVersion=Version$1;exports.QRCodeWriter=QRCodeWriter;exports.RGBLuminanceSource=RGBLuminanceSource;exports.RSS14Reader=RSS14Reader;exports.RSSExpandedReader=RSSExpandedReader;exports.ReaderException=ReaderException;exports.ReedSolomonDecoder=ReedSolomonDecoder;exports.ReedSolomonEncoder=ReedSolomonEncoder;exports.ReedSolomonException=ReedSolomonException;exports.Result=Result;exports.ResultMetadataType=ResultMetadataType$1;exports.ResultPoint=ResultPoint;exports.StringUtils=StringUtils;exports.UnsupportedOperationException=UnsupportedOperationException;exports.VideoInputDevice=VideoInputDevice;exports.WhiteRectangleDetector=WhiteRectangleDetector;exports.WriterException=WriterException;exports.ZXingArrays=Arrays;exports.ZXingCharset=Charset;exports.ZXingInteger=Integer;exports.ZXingStandardCharsets=StandardCharsets;exports.ZXingStringBuilder=StringBuilder;exports.ZXingStringEncoding=StringEncoding;exports.ZXingSystem=System;exports.createAbstractExpandedDecoder=createDecoder;Object.defineProperty(exports,'__esModule',{value:true});});
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../../../Program/HBuilderX/plugins/uniapp-cli/node_modules/webpack/buildin/global.js */ 3)))
/***/ }),
/* 68 */
/*!**********************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/assertThisInitialized.js ***!
\**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 69 */
/*!************************************************************************************************!*\
!*** ./node_modules/@dcloudio/vue-cli-plugin-uni/packages/@babel/runtime/regenerator/index.js ***!
\************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// TODO(Babel 8): Remove this file.
var runtime = __webpack_require__(/*! @babel/runtime/helpers/regeneratorRuntime */ 70)();
module.exports = runtime;
/***/ }),
/* 70 */
/*!*******************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/regeneratorRuntime.js ***!
\*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var _typeof = __webpack_require__(/*! ./typeof.js */ 13)["default"];
function _regeneratorRuntime() {
"use strict";
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
return e;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
var t,
e = {},
r = Object.prototype,
n = r.hasOwnProperty,
o = Object.defineProperty || function (t, e, r) {
t[e] = r.value;
},
i = "function" == typeof Symbol ? Symbol : {},
a = i.iterator || "@@iterator",
c = i.asyncIterator || "@@asyncIterator",
u = i.toStringTag || "@@toStringTag";
function define(t, e, r) {
return Object.defineProperty(t, e, {
value: r,
enumerable: !0,
configurable: !0,
writable: !0
}), t[e];
}
try {
define({}, "");
} catch (t) {
define = function define(t, e, r) {
return t[e] = r;
};
}
function wrap(t, e, r, n) {
var i = e && e.prototype instanceof Generator ? e : Generator,
a = Object.create(i.prototype),
c = new Context(n || []);
return o(a, "_invoke", {
value: makeInvokeMethod(t, r, c)
}), a;
}
function tryCatch(t, e, r) {
try {
return {
type: "normal",
arg: t.call(e, r)
};
} catch (t) {
return {
type: "throw",
arg: t
};
}
}
e.wrap = wrap;
var h = "suspendedStart",
l = "suspendedYield",
f = "executing",
s = "completed",
y = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var p = {};
define(p, a, function () {
return this;
});
var d = Object.getPrototypeOf,
v = d && d(d(values([])));
v && v !== r && n.call(v, a) && (p = v);
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
function defineIteratorMethods(t) {
["next", "throw", "return"].forEach(function (e) {
define(t, e, function (t) {
return this._invoke(e, t);
});
});
}
function AsyncIterator(t, e) {
function invoke(r, o, i, a) {
var c = tryCatch(t[r], t, o);
if ("throw" !== c.type) {
var u = c.arg,
h = u.value;
return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
invoke("next", t, i, a);
}, function (t) {
invoke("throw", t, i, a);
}) : e.resolve(h).then(function (t) {
u.value = t, i(u);
}, function (t) {
return invoke("throw", t, i, a);
});
}
a(c.arg);
}
var r;
o(this, "_invoke", {
value: function value(t, n) {
function callInvokeWithMethodAndArg() {
return new e(function (e, r) {
invoke(t, n, e, r);
});
}
return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
}
});
}
function makeInvokeMethod(e, r, n) {
var o = h;
return function (i, a) {
if (o === f) throw Error("Generator is already running");
if (o === s) {
if ("throw" === i) throw a;
return {
value: t,
done: !0
};
}
for (n.method = i, n.arg = a;;) {
var c = n.delegate;
if (c) {
var u = maybeInvokeDelegate(c, n);
if (u) {
if (u === y) continue;
return u;
}
}
if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
if (o === h) throw o = s, n.arg;
n.dispatchException(n.arg);
} else "return" === n.method && n.abrupt("return", n.arg);
o = f;
var p = tryCatch(e, r, n);
if ("normal" === p.type) {
if (o = n.done ? s : l, p.arg === y) continue;
return {
value: p.arg,
done: n.done
};
}
"throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
}
};
}
function maybeInvokeDelegate(e, r) {
var n = r.method,
o = e.iterator[n];
if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
var i = tryCatch(o, e.iterator, r.arg);
if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
var a = i.arg;
return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
}
function pushTryEntry(t) {
var e = {
tryLoc: t[0]
};
1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
}
function resetTryEntry(t) {
var e = t.completion || {};
e.type = "normal", delete e.arg, t.completion = e;
}
function Context(t) {
this.tryEntries = [{
tryLoc: "root"
}], t.forEach(pushTryEntry, this), this.reset(!0);
}
function values(e) {
if (e || "" === e) {
var r = e[a];
if (r) return r.call(e);
if ("function" == typeof e.next) return e;
if (!isNaN(e.length)) {
var o = -1,
i = function next() {
for (; ++o < e.length;) {
if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
}
return next.value = t, next.done = !0, next;
};
return i.next = i;
}
}
throw new TypeError(_typeof(e) + " is not iterable");
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
value: GeneratorFunctionPrototype,
configurable: !0
}), o(GeneratorFunctionPrototype, "constructor", {
value: GeneratorFunction,
configurable: !0
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
var e = "function" == typeof t && t.constructor;
return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
}, e.mark = function (t) {
return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
}, e.awrap = function (t) {
return {
__await: t
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
return this;
}), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
void 0 === i && (i = Promise);
var a = new AsyncIterator(wrap(t, r, n, o), i);
return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
return t.done ? t.value : a.next();
});
}, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
return this;
}), define(g, "toString", function () {
return "[object Generator]";
}), e.keys = function (t) {
var e = Object(t),
r = [];
for (var n in e) {
r.push(n);
}
return r.reverse(), function next() {
for (; r.length;) {
var t = r.pop();
if (t in e) return next.value = t, next.done = !1, next;
}
return next.done = !0, next;
};
}, e.values = values, Context.prototype = {
constructor: Context,
reset: function reset(e) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) {
"t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
}
},
stop: function stop() {
this.done = !0;
var t = this.tryEntries[0].completion;
if ("throw" === t.type) throw t.arg;
return this.rval;
},
dispatchException: function dispatchException(e) {
if (this.done) throw e;
var r = this;
function handle(n, o) {
return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
}
for (var o = this.tryEntries.length - 1; o >= 0; --o) {
var i = this.tryEntries[o],
a = i.completion;
if ("root" === i.tryLoc) return handle("end");
if (i.tryLoc <= this.prev) {
var c = n.call(i, "catchLoc"),
u = n.call(i, "finallyLoc");
if (c && u) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
} else if (c) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
} else {
if (!u) throw Error("try statement without catch or finally");
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
}
}
}
},
abrupt: function abrupt(t, e) {
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
var o = this.tryEntries[r];
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
var i = o;
break;
}
}
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
var a = i ? i.completion : {};
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
},
complete: function complete(t, e) {
if ("throw" === t.type) throw t.arg;
return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
},
finish: function finish(t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
}
},
"catch": function _catch(t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.tryLoc === t) {
var n = r.completion;
if ("throw" === n.type) {
var o = n.arg;
resetTryEntry(r);
}
return o;
}
}
throw Error("illegal catch attempt");
},
delegateYield: function delegateYield(e, r, n) {
return this.delegate = {
iterator: values(e),
resultName: r,
nextLoc: n
}, "next" === this.method && (this.arg = t), y;
}
}, e;
}
module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 71 */
/*!****************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/get.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var superPropBase = __webpack_require__(/*! ./superPropBase.js */ 72);
function _get() {
if (typeof Reflect !== "undefined" && Reflect.get) {
module.exports = _get = Reflect.get.bind(), module.exports.__esModule = true, module.exports["default"] = module.exports;
} else {
module.exports = _get = function _get(target, property, receiver) {
var base = superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(arguments.length < 3 ? target : receiver);
}
return desc.value;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
}
return _get.apply(this, arguments);
}
module.exports = _get, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 72 */
/*!**************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/superPropBase.js ***!
\**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var getPrototypeOf = __webpack_require__(/*! ./getPrototypeOf.js */ 73);
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = getPrototypeOf(object);
if (object === null) break;
}
return object;
}
module.exports = _superPropBase, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 73 */
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/getPrototypeOf.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 74 */
/*!*********************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/inherits.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ 16);
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) setPrototypeOf(subClass, superClass);
}
module.exports = _inherits, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 75 */
/*!**************************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js ***!
\**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var _typeof = __webpack_require__(/*! ./typeof.js */ 13)["default"];
var assertThisInitialized = __webpack_require__(/*! ./assertThisInitialized.js */ 68);
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return assertThisInitialized(self);
}
module.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 76 */
/*!****************************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/native-bar-code-detector.js ***!
\****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BarcodeDetectorDelegate = void 0;
var _core = __webpack_require__(/*! ./core */ 62);
var __awaiter = void 0 && (void 0).__awaiter || function (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());
});
};
var __generator = void 0 && (void 0).__generator || function (thisArg, body) {
var _ = {
label: 0,
sent: function sent() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"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
};
}
};
var BarcodeDetectorDelegate = function () {
function BarcodeDetectorDelegate(requestedFormats, verbose, logger) {
this.formatMap = new Map([[_core.Html5QrcodeSupportedFormats.QR_CODE, "qr_code"], [_core.Html5QrcodeSupportedFormats.AZTEC, "aztec"], [_core.Html5QrcodeSupportedFormats.CODABAR, "codabar"], [_core.Html5QrcodeSupportedFormats.CODE_39, "code_39"], [_core.Html5QrcodeSupportedFormats.CODE_93, "code_93"], [_core.Html5QrcodeSupportedFormats.CODE_128, "code_128"], [_core.Html5QrcodeSupportedFormats.DATA_MATRIX, "data_matrix"], [_core.Html5QrcodeSupportedFormats.ITF, "itf"], [_core.Html5QrcodeSupportedFormats.EAN_13, "ean_13"], [_core.Html5QrcodeSupportedFormats.EAN_8, "ean_8"], [_core.Html5QrcodeSupportedFormats.PDF_417, "pdf417"], [_core.Html5QrcodeSupportedFormats.UPC_A, "upc_a"], [_core.Html5QrcodeSupportedFormats.UPC_E, "upc_e"]]);
this.reverseFormatMap = this.createReverseFormatMap();
if (!BarcodeDetectorDelegate.isSupported()) {
throw "Use html5qrcode.min.js without edit, Use " + "BarcodeDetectorDelegate only if it isSupported();";
}
this.verbose = verbose;
this.logger = logger;
var formats = this.createBarcodeDetectorFormats(requestedFormats);
this.detector = new BarcodeDetector(formats);
if (!this.detector) {
throw "BarcodeDetector detector not supported";
}
}
BarcodeDetectorDelegate.isSupported = function () {
if (!("BarcodeDetector" in window)) {
return false;
}
var dummyDetector = new BarcodeDetector({
formats: ["qr_code"]
});
return typeof dummyDetector !== "undefined";
};
BarcodeDetectorDelegate.prototype.decodeAsync = function (canvas) {
return __awaiter(this, void 0, void 0, function () {
var barcodes, largestBarcode;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
return [4, this.detector.detect(canvas)];
case 1:
barcodes = _a.sent();
if (!barcodes || barcodes.length === 0) {
throw "No barcode or QR code detected.";
}
largestBarcode = this.selectLargestBarcode(barcodes);
return [2, {
text: largestBarcode.rawValue,
format: _core.QrcodeResultFormat.create(this.toHtml5QrcodeSupportedFormats(largestBarcode.format)),
debugData: this.createDebugData()
}];
}
});
});
};
BarcodeDetectorDelegate.prototype.selectLargestBarcode = function (barcodes) {
var largestBarcode = null;
var maxArea = 0;
for (var _i = 0, barcodes_1 = barcodes; _i < barcodes_1.length; _i++) {
var barcode = barcodes_1[_i];
var area = barcode.boundingBox.width * barcode.boundingBox.height;
if (area > maxArea) {
maxArea = area;
largestBarcode = barcode;
}
}
if (!largestBarcode) {
throw "No largest barcode found";
}
return largestBarcode;
};
BarcodeDetectorDelegate.prototype.createBarcodeDetectorFormats = function (requestedFormats) {
var formats = [];
for (var _i = 0, requestedFormats_1 = requestedFormats; _i < requestedFormats_1.length; _i++) {
var requestedFormat = requestedFormats_1[_i];
if (this.formatMap.has(requestedFormat)) {
formats.push(this.formatMap.get(requestedFormat));
} else {
this.logger.warn("".concat(requestedFormat, " is not supported by") + "BarcodeDetectorDelegate");
}
}
return {
formats: formats
};
};
BarcodeDetectorDelegate.prototype.toHtml5QrcodeSupportedFormats = function (barcodeDetectorFormat) {
if (!this.reverseFormatMap.has(barcodeDetectorFormat)) {
throw "reverseFormatMap doesn't have ".concat(barcodeDetectorFormat);
}
return this.reverseFormatMap.get(barcodeDetectorFormat);
};
BarcodeDetectorDelegate.prototype.createReverseFormatMap = function () {
var result = new Map();
this.formatMap.forEach(function (value, key, _) {
result.set(value, key);
});
return result;
};
BarcodeDetectorDelegate.prototype.createDebugData = function () {
return {
decoderName: "BarcodeDetector"
};
};
return BarcodeDetectorDelegate;
}();
exports.BarcodeDetectorDelegate = BarcodeDetectorDelegate;
/***/ }),
/* 77 */
/*!********************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/camera/factories.js ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CameraFactory = void 0;
var _coreImpl = __webpack_require__(/*! ./core-impl */ 78);
var __awaiter = void 0 && (void 0).__awaiter || function (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());
});
};
var __generator = void 0 && (void 0).__generator || function (thisArg, body) {
var _ = {
label: 0,
sent: function sent() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"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
};
}
};
var CameraFactory = function () {
function CameraFactory() {}
CameraFactory.failIfNotSupported = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (!navigator.mediaDevices) {
throw "navigator.mediaDevices not supported";
}
return [2, new CameraFactory()];
});
});
};
CameraFactory.prototype.create = function (videoConstraints) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2, _coreImpl.CameraImpl.create(videoConstraints)];
});
});
};
return CameraFactory;
}();
exports.CameraFactory = CameraFactory;
/***/ }),
/* 78 */
/*!********************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/camera/core-impl.js ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CameraImpl = void 0;
var __extends = void 0 && (void 0).__extends || function () {
var _extendStatics = function extendStatics(d, b) {
_extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) {
if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
}
};
return _extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
_extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
}();
var __awaiter = void 0 && (void 0).__awaiter || function (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());
});
};
var __generator = void 0 && (void 0).__generator || function (thisArg, body) {
var _ = {
label: 0,
sent: function sent() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"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
};
}
};
var AbstractCameraCapability = function () {
function AbstractCameraCapability(name, track) {
this.name = name;
this.track = track;
}
AbstractCameraCapability.prototype.isSupported = function () {
if (!this.track.getCapabilities) {
return false;
}
return this.name in this.track.getCapabilities();
};
AbstractCameraCapability.prototype.apply = function (value) {
var constraint = {};
constraint[this.name] = value;
var constraints = {
advanced: [constraint]
};
return this.track.applyConstraints(constraints);
};
AbstractCameraCapability.prototype.value = function () {
var settings = this.track.getSettings();
if (this.name in settings) {
var settingValue = settings[this.name];
return settingValue;
}
return null;
};
return AbstractCameraCapability;
}();
var AbstractRangeCameraCapability = function (_super) {
__extends(AbstractRangeCameraCapability, _super);
function AbstractRangeCameraCapability(name, track) {
return _super.call(this, name, track) || this;
}
AbstractRangeCameraCapability.prototype.min = function () {
return this.getCapabilities().min;
};
AbstractRangeCameraCapability.prototype.max = function () {
return this.getCapabilities().max;
};
AbstractRangeCameraCapability.prototype.step = function () {
return this.getCapabilities().step;
};
AbstractRangeCameraCapability.prototype.apply = function (value) {
var constraint = {};
constraint[this.name] = value;
var constraints = {
advanced: [constraint]
};
return this.track.applyConstraints(constraints);
};
AbstractRangeCameraCapability.prototype.getCapabilities = function () {
this.failIfNotSupported();
var capabilities = this.track.getCapabilities();
var capability = capabilities[this.name];
return {
min: capability.min,
max: capability.max,
step: capability.step
};
};
AbstractRangeCameraCapability.prototype.failIfNotSupported = function () {
if (!this.isSupported()) {
throw new Error("".concat(this.name, " capability not supported"));
}
};
return AbstractRangeCameraCapability;
}(AbstractCameraCapability);
var ZoomFeatureImpl = function (_super) {
__extends(ZoomFeatureImpl, _super);
function ZoomFeatureImpl(track) {
return _super.call(this, "zoom", track) || this;
}
return ZoomFeatureImpl;
}(AbstractRangeCameraCapability);
var TorchFeatureImpl = function (_super) {
__extends(TorchFeatureImpl, _super);
function TorchFeatureImpl(track) {
return _super.call(this, "torch", track) || this;
}
return TorchFeatureImpl;
}(AbstractCameraCapability);
var CameraCapabilitiesImpl = function () {
function CameraCapabilitiesImpl(track) {
this.track = track;
}
CameraCapabilitiesImpl.prototype.zoomFeature = function () {
return new ZoomFeatureImpl(this.track);
};
CameraCapabilitiesImpl.prototype.torchFeature = function () {
return new TorchFeatureImpl(this.track);
};
return CameraCapabilitiesImpl;
}();
var RenderedCameraImpl = function () {
function RenderedCameraImpl(parentElement, mediaStream, callbacks) {
this.isClosed = false;
this.parentElement = parentElement;
this.mediaStream = mediaStream;
this.callbacks = callbacks;
this.surface = this.createVideoElement(this.parentElement.clientWidth);
parentElement.append(this.surface);
}
RenderedCameraImpl.prototype.createVideoElement = function (width) {
var videoElement = document.createElement("video");
videoElement.style.width = "".concat(width, "px");
videoElement.style.display = "block";
videoElement.muted = true;
videoElement.setAttribute("muted", "true");
videoElement.playsInline = true;
return videoElement;
};
RenderedCameraImpl.prototype.setupSurface = function () {
var _this = this;
this.surface.onabort = function () {
throw "RenderedCameraImpl video surface onabort() called";
};
this.surface.onerror = function () {
throw "RenderedCameraImpl video surface onerror() called";
};
var onVideoStart = function onVideoStart() {
var videoWidth = _this.surface.clientWidth;
var videoHeight = _this.surface.clientHeight;
_this.callbacks.onRenderSurfaceReady(videoWidth, videoHeight);
_this.surface.removeEventListener("playing", onVideoStart);
};
this.surface.addEventListener("playing", onVideoStart);
this.surface.srcObject = this.mediaStream;
this.surface.play();
};
RenderedCameraImpl.create = function (parentElement, mediaStream, options, callbacks) {
return __awaiter(this, void 0, void 0, function () {
var renderedCamera, aspectRatioConstraint;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
renderedCamera = new RenderedCameraImpl(parentElement, mediaStream, callbacks);
if (!options.aspectRatio) return [3, 2];
aspectRatioConstraint = {
aspectRatio: options.aspectRatio
};
return [4, renderedCamera.getFirstTrackOrFail().applyConstraints(aspectRatioConstraint)];
case 1:
_a.sent();
_a.label = 2;
case 2:
renderedCamera.setupSurface();
return [2, renderedCamera];
}
});
});
};
RenderedCameraImpl.prototype.failIfClosed = function () {
if (this.isClosed) {
throw "The RenderedCamera has already been closed.";
}
};
RenderedCameraImpl.prototype.getFirstTrackOrFail = function () {
this.failIfClosed();
if (this.mediaStream.getVideoTracks().length === 0) {
throw "No video tracks found";
}
return this.mediaStream.getVideoTracks()[0];
};
RenderedCameraImpl.prototype.pause = function () {
this.failIfClosed();
this.surface.pause();
};
RenderedCameraImpl.prototype.resume = function (onResumeCallback) {
this.failIfClosed();
var $this = this;
var onVideoResume = function onVideoResume() {
setTimeout(onResumeCallback, 200);
$this.surface.removeEventListener("playing", onVideoResume);
};
this.surface.addEventListener("playing", onVideoResume);
this.surface.play();
};
RenderedCameraImpl.prototype.isPaused = function () {
this.failIfClosed();
return this.surface.paused;
};
RenderedCameraImpl.prototype.getSurface = function () {
this.failIfClosed();
return this.surface;
};
RenderedCameraImpl.prototype.getRunningTrackCapabilities = function () {
return this.getFirstTrackOrFail().getCapabilities();
};
RenderedCameraImpl.prototype.getRunningTrackSettings = function () {
return this.getFirstTrackOrFail().getSettings();
};
RenderedCameraImpl.prototype.applyVideoConstraints = function (constraints) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if ("aspectRatio" in constraints) {
throw "Changing 'aspectRatio' in run-time is not yet supported.";
}
return [2, this.getFirstTrackOrFail().applyConstraints(constraints)];
});
});
};
RenderedCameraImpl.prototype.close = function () {
if (this.isClosed) {
return Promise.resolve();
}
var $this = this;
return new Promise(function (resolve, _) {
var tracks = $this.mediaStream.getVideoTracks();
var tracksToClose = tracks.length;
var tracksClosed = 0;
$this.mediaStream.getVideoTracks().forEach(function (videoTrack) {
$this.mediaStream.removeTrack(videoTrack);
videoTrack.stop();
++tracksClosed;
if (tracksClosed >= tracksToClose) {
$this.isClosed = true;
$this.parentElement.removeChild($this.surface);
resolve();
}
});
});
};
RenderedCameraImpl.prototype.getCapabilities = function () {
return new CameraCapabilitiesImpl(this.getFirstTrackOrFail());
};
return RenderedCameraImpl;
}();
var CameraImpl = function () {
function CameraImpl(mediaStream) {
this.mediaStream = mediaStream;
}
CameraImpl.prototype.render = function (parentElement, options, callbacks) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2, RenderedCameraImpl.create(parentElement, this.mediaStream, options, callbacks)];
});
});
};
CameraImpl.create = function (videoConstraints) {
return __awaiter(this, void 0, void 0, function () {
var constraints, mediaStream;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!navigator.mediaDevices) {
throw "navigator.mediaDevices not supported";
}
constraints = {
audio: false,
video: videoConstraints
};
return [4, navigator.mediaDevices.getUserMedia(constraints)];
case 1:
mediaStream = _a.sent();
return [2, new CameraImpl(mediaStream)];
}
});
});
};
return CameraImpl;
}();
exports.CameraImpl = CameraImpl;
/***/ }),
/* 79 */
/*!********************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/camera/retriever.js ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CameraRetriever = void 0;
var _strings = __webpack_require__(/*! ../strings */ 63);
var __awaiter = void 0 && (void 0).__awaiter || function (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());
});
};
var __generator = void 0 && (void 0).__generator || function (thisArg, body) {
var _ = {
label: 0,
sent: function sent() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"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
};
}
};
var CameraRetriever = function () {
function CameraRetriever() {}
CameraRetriever.retrieve = function () {
if (navigator.mediaDevices) {
return CameraRetriever.getCamerasFromMediaDevices();
}
var mst = MediaStreamTrack;
if (MediaStreamTrack && mst.getSources) {
return CameraRetriever.getCamerasFromMediaStreamTrack();
}
return CameraRetriever.rejectWithError();
};
CameraRetriever.rejectWithError = function () {
var errorMessage = _strings.Html5QrcodeStrings.unableToQuerySupportedDevices();
if (!CameraRetriever.isHttpsOrLocalhost()) {
errorMessage = _strings.Html5QrcodeStrings.insecureContextCameraQueryError();
}
return Promise.reject(errorMessage);
};
CameraRetriever.isHttpsOrLocalhost = function () {
if (location.protocol === "https:") {
return true;
}
var host = location.host.split(":")[0];
return host === "127.0.0.1" || host === "localhost";
};
CameraRetriever.getCamerasFromMediaDevices = function () {
return __awaiter(this, void 0, void 0, function () {
var closeActiveStreams, mediaStream, devices, results, _i, devices_1, device;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
closeActiveStreams = function closeActiveStreams(stream) {
var tracks = stream.getVideoTracks();
for (var _i = 0, tracks_1 = tracks; _i < tracks_1.length; _i++) {
var track = tracks_1[_i];
track.enabled = false;
track.stop();
stream.removeTrack(track);
}
};
return [4, navigator.mediaDevices.getUserMedia({
audio: false,
video: true
})];
case 1:
mediaStream = _a.sent();
return [4, navigator.mediaDevices.enumerateDevices()];
case 2:
devices = _a.sent();
results = [];
for (_i = 0, devices_1 = devices; _i < devices_1.length; _i++) {
device = devices_1[_i];
if (device.kind === "videoinput") {
results.push({
id: device.deviceId,
label: device.label
});
}
}
closeActiveStreams(mediaStream);
return [2, results];
}
});
});
};
CameraRetriever.getCamerasFromMediaStreamTrack = function () {
return new Promise(function (resolve, _) {
var callback = function callback(sourceInfos) {
var results = [];
for (var _i = 0, sourceInfos_1 = sourceInfos; _i < sourceInfos_1.length; _i++) {
var sourceInfo = sourceInfos_1[_i];
if (sourceInfo.kind === "video") {
results.push({
id: sourceInfo.id,
label: sourceInfo.label
});
}
}
resolve(results);
};
var mst = MediaStreamTrack;
mst.getSources(callback);
});
};
return CameraRetriever;
}();
exports.CameraRetriever = CameraRetriever;
/***/ }),
/* 80 */
/*!*****************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/state-manager.js ***!
\*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.StateManagerProxy = exports.StateManagerFactory = exports.Html5QrcodeScannerState = void 0;
var Html5QrcodeScannerState;
exports.Html5QrcodeScannerState = Html5QrcodeScannerState;
(function (Html5QrcodeScannerState) {
Html5QrcodeScannerState[Html5QrcodeScannerState["UNKNOWN"] = 0] = "UNKNOWN";
Html5QrcodeScannerState[Html5QrcodeScannerState["NOT_STARTED"] = 1] = "NOT_STARTED";
Html5QrcodeScannerState[Html5QrcodeScannerState["SCANNING"] = 2] = "SCANNING";
Html5QrcodeScannerState[Html5QrcodeScannerState["PAUSED"] = 3] = "PAUSED";
})(Html5QrcodeScannerState || (exports.Html5QrcodeScannerState = Html5QrcodeScannerState = {}));
var StateManagerImpl = function () {
function StateManagerImpl() {
this.state = Html5QrcodeScannerState.NOT_STARTED;
this.onGoingTransactionNewState = Html5QrcodeScannerState.UNKNOWN;
}
StateManagerImpl.prototype.directTransition = function (newState) {
this.failIfTransitionOngoing();
this.validateTransition(newState);
this.state = newState;
};
StateManagerImpl.prototype.startTransition = function (newState) {
this.failIfTransitionOngoing();
this.validateTransition(newState);
this.onGoingTransactionNewState = newState;
return this;
};
StateManagerImpl.prototype.execute = function () {
if (this.onGoingTransactionNewState === Html5QrcodeScannerState.UNKNOWN) {
throw "Transaction is already cancelled, cannot execute().";
}
var tempNewState = this.onGoingTransactionNewState;
this.onGoingTransactionNewState = Html5QrcodeScannerState.UNKNOWN;
this.directTransition(tempNewState);
};
StateManagerImpl.prototype.cancel = function () {
if (this.onGoingTransactionNewState === Html5QrcodeScannerState.UNKNOWN) {
throw "Transaction is already cancelled, cannot cancel().";
}
this.onGoingTransactionNewState = Html5QrcodeScannerState.UNKNOWN;
};
StateManagerImpl.prototype.getState = function () {
return this.state;
};
StateManagerImpl.prototype.failIfTransitionOngoing = function () {
if (this.onGoingTransactionNewState !== Html5QrcodeScannerState.UNKNOWN) {
throw "Cannot transition to a new state, already under transition";
}
};
StateManagerImpl.prototype.validateTransition = function (newState) {
switch (this.state) {
case Html5QrcodeScannerState.UNKNOWN:
throw "Transition from unknown is not allowed";
case Html5QrcodeScannerState.NOT_STARTED:
this.failIfNewStateIs(newState, [Html5QrcodeScannerState.PAUSED]);
break;
case Html5QrcodeScannerState.SCANNING:
break;
case Html5QrcodeScannerState.PAUSED:
break;
}
};
StateManagerImpl.prototype.failIfNewStateIs = function (newState, disallowedStatesToTransition) {
for (var _i = 0, disallowedStatesToTransition_1 = disallowedStatesToTransition; _i < disallowedStatesToTransition_1.length; _i++) {
var disallowedState = disallowedStatesToTransition_1[_i];
if (newState === disallowedState) {
throw "Cannot transition from ".concat(this.state, " to ").concat(newState);
}
}
};
return StateManagerImpl;
}();
var StateManagerProxy = function () {
function StateManagerProxy(stateManager) {
this.stateManager = stateManager;
}
StateManagerProxy.prototype.startTransition = function (newState) {
return this.stateManager.startTransition(newState);
};
StateManagerProxy.prototype.directTransition = function (newState) {
this.stateManager.directTransition(newState);
};
StateManagerProxy.prototype.getState = function () {
return this.stateManager.getState();
};
StateManagerProxy.prototype.canScanFile = function () {
return this.stateManager.getState() === Html5QrcodeScannerState.NOT_STARTED;
};
StateManagerProxy.prototype.isScanning = function () {
return this.stateManager.getState() !== Html5QrcodeScannerState.NOT_STARTED;
};
StateManagerProxy.prototype.isStrictlyScanning = function () {
return this.stateManager.getState() === Html5QrcodeScannerState.SCANNING;
};
StateManagerProxy.prototype.isPaused = function () {
return this.stateManager.getState() === Html5QrcodeScannerState.PAUSED;
};
return StateManagerProxy;
}();
exports.StateManagerProxy = StateManagerProxy;
var StateManagerFactory = function () {
function StateManagerFactory() {}
StateManagerFactory.create = function () {
return new StateManagerProxy(new StateManagerImpl());
};
return StateManagerFactory;
}();
exports.StateManagerFactory = StateManagerFactory;
/***/ }),
/* 81 */
/*!************************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/html5-qrcode-scanner.js ***!
\************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Html5QrcodeScanner = void 0;
var _core = __webpack_require__(/*! ./core */ 62);
var _html5Qrcode = __webpack_require__(/*! ./html5-qrcode */ 61);
var _strings = __webpack_require__(/*! ./strings */ 63);
var _imageAssets = __webpack_require__(/*! ./image-assets */ 82);
var _storage = __webpack_require__(/*! ./storage */ 83);
var _ui = __webpack_require__(/*! ./ui */ 84);
var _permissions = __webpack_require__(/*! ./camera/permissions */ 85);
var _scanTypeSelector = __webpack_require__(/*! ./ui/scanner/scan-type-selector */ 86);
var _torchButton = __webpack_require__(/*! ./ui/scanner/torch-button */ 87);
var _fileSelectionUi = __webpack_require__(/*! ./ui/scanner/file-selection-ui */ 89);
var _base = __webpack_require__(/*! ./ui/scanner/base */ 88);
var _cameraSelectionUi = __webpack_require__(/*! ./ui/scanner/camera-selection-ui */ 90);
var _cameraZoomUi = __webpack_require__(/*! ./ui/scanner/camera-zoom-ui */ 91);
var Html5QrcodeScannerStatus;
(function (Html5QrcodeScannerStatus) {
Html5QrcodeScannerStatus[Html5QrcodeScannerStatus["STATUS_DEFAULT"] = 0] = "STATUS_DEFAULT";
Html5QrcodeScannerStatus[Html5QrcodeScannerStatus["STATUS_SUCCESS"] = 1] = "STATUS_SUCCESS";
Html5QrcodeScannerStatus[Html5QrcodeScannerStatus["STATUS_WARNING"] = 2] = "STATUS_WARNING";
Html5QrcodeScannerStatus[Html5QrcodeScannerStatus["STATUS_REQUESTING_PERMISSION"] = 3] = "STATUS_REQUESTING_PERMISSION";
})(Html5QrcodeScannerStatus || (Html5QrcodeScannerStatus = {}));
function toHtml5QrcodeCameraScanConfig(config) {
return {
fps: config.fps,
qrbox: config.qrbox,
aspectRatio: config.aspectRatio,
disableFlip: config.disableFlip,
videoConstraints: config.videoConstraints
};
}
function toHtml5QrcodeFullConfig(config, verbose) {
return {
formatsToSupport: config.formatsToSupport,
useBarCodeDetectorIfSupported: config.useBarCodeDetectorIfSupported,
experimentalFeatures: config.experimentalFeatures,
verbose: verbose
};
}
var Html5QrcodeScanner = function () {
function Html5QrcodeScanner(elementId, config, verbose) {
this.lastMatchFound = null;
this.cameraScanImage = null;
this.fileScanImage = null;
this.fileSelectionUi = null;
this.elementId = elementId;
this.config = this.createConfig(config);
this.verbose = verbose === true;
if (!document.getElementById(elementId)) {
throw "HTML Element with id=".concat(elementId, " not found");
}
this.scanTypeSelector = new _scanTypeSelector.ScanTypeSelector(this.config.supportedScanTypes);
this.currentScanType = this.scanTypeSelector.getDefaultScanType();
this.sectionSwapAllowed = true;
this.logger = new _core.BaseLoggger(this.verbose);
this.persistedDataManager = new _storage.PersistedDataManager();
if (config.rememberLastUsedCamera !== true) {
this.persistedDataManager.reset();
}
}
Html5QrcodeScanner.prototype.render = function (qrCodeSuccessCallback, qrCodeErrorCallback) {
var _this = this;
this.lastMatchFound = null;
this.qrCodeSuccessCallback = function (decodedText, result) {
if (qrCodeSuccessCallback) {
qrCodeSuccessCallback(decodedText, result);
} else {
if (_this.lastMatchFound === decodedText) {
return;
}
_this.lastMatchFound = decodedText;
_this.setHeaderMessage(_strings.Html5QrcodeScannerStrings.lastMatch(decodedText), Html5QrcodeScannerStatus.STATUS_SUCCESS);
}
};
this.qrCodeErrorCallback = function (errorMessage, error) {
if (qrCodeErrorCallback) {
qrCodeErrorCallback(errorMessage, error);
}
};
var container = document.getElementById(this.elementId);
if (!container) {
throw "HTML Element with id=".concat(this.elementId, " not found");
}
container.innerHTML = "";
this.createBasicLayout(container);
this.html5Qrcode = new _html5Qrcode.Html5Qrcode(this.getScanRegionId(), toHtml5QrcodeFullConfig(this.config, this.verbose));
};
Html5QrcodeScanner.prototype.pause = function (shouldPauseVideo) {
if ((0, _core.isNullOrUndefined)(shouldPauseVideo) || shouldPauseVideo !== true) {
shouldPauseVideo = false;
}
this.getHtml5QrcodeOrFail().pause(shouldPauseVideo);
};
Html5QrcodeScanner.prototype.resume = function () {
this.getHtml5QrcodeOrFail().resume();
};
Html5QrcodeScanner.prototype.getState = function () {
return this.getHtml5QrcodeOrFail().getState();
};
Html5QrcodeScanner.prototype.clear = function () {
var _this = this;
var emptyHtmlContainer = function emptyHtmlContainer() {
var mainContainer = document.getElementById(_this.elementId);
if (mainContainer) {
mainContainer.innerHTML = "";
_this.resetBasicLayout(mainContainer);
}
};
if (this.html5Qrcode) {
return new Promise(function (resolve, reject) {
if (!_this.html5Qrcode) {
resolve();
return;
}
if (_this.html5Qrcode.isScanning) {
_this.html5Qrcode.stop().then(function (_) {
if (!_this.html5Qrcode) {
resolve();
return;
}
_this.html5Qrcode.clear();
emptyHtmlContainer();
resolve();
}).catch(function (error) {
if (_this.verbose) {
_this.logger.logError("Unable to stop qrcode scanner", error);
}
reject(error);
});
} else {
_this.html5Qrcode.clear();
emptyHtmlContainer();
resolve();
}
});
}
return Promise.resolve();
};
Html5QrcodeScanner.prototype.getRunningTrackCapabilities = function () {
return this.getHtml5QrcodeOrFail().getRunningTrackCapabilities();
};
Html5QrcodeScanner.prototype.getRunningTrackSettings = function () {
return this.getHtml5QrcodeOrFail().getRunningTrackSettings();
};
Html5QrcodeScanner.prototype.applyVideoConstraints = function (videoConstaints) {
return this.getHtml5QrcodeOrFail().applyVideoConstraints(videoConstaints);
};
Html5QrcodeScanner.prototype.getHtml5QrcodeOrFail = function () {
if (!this.html5Qrcode) {
throw "Code scanner not initialized.";
}
return this.html5Qrcode;
};
Html5QrcodeScanner.prototype.createConfig = function (config) {
if (config) {
if (!config.fps) {
config.fps = _core.Html5QrcodeConstants.SCAN_DEFAULT_FPS;
}
if (config.rememberLastUsedCamera !== !_core.Html5QrcodeConstants.DEFAULT_REMEMBER_LAST_CAMERA_USED) {
config.rememberLastUsedCamera = _core.Html5QrcodeConstants.DEFAULT_REMEMBER_LAST_CAMERA_USED;
}
if (!config.supportedScanTypes) {
config.supportedScanTypes = _core.Html5QrcodeConstants.DEFAULT_SUPPORTED_SCAN_TYPE;
}
return config;
}
return {
fps: _core.Html5QrcodeConstants.SCAN_DEFAULT_FPS,
rememberLastUsedCamera: _core.Html5QrcodeConstants.DEFAULT_REMEMBER_LAST_CAMERA_USED,
supportedScanTypes: _core.Html5QrcodeConstants.DEFAULT_SUPPORTED_SCAN_TYPE
};
};
Html5QrcodeScanner.prototype.createBasicLayout = function (parent) {
parent.style.position = "relative";
parent.style.padding = "0px";
parent.style.border = "1px solid silver";
this.createHeader(parent);
var qrCodeScanRegion = document.createElement("div");
var scanRegionId = this.getScanRegionId();
qrCodeScanRegion.id = scanRegionId;
qrCodeScanRegion.style.width = "100%";
qrCodeScanRegion.style.minHeight = "100px";
qrCodeScanRegion.style.textAlign = "center";
parent.appendChild(qrCodeScanRegion);
if (_scanTypeSelector.ScanTypeSelector.isCameraScanType(this.currentScanType)) {
this.insertCameraScanImageToScanRegion();
} else {
this.insertFileScanImageToScanRegion();
}
var qrCodeDashboard = document.createElement("div");
var dashboardId = this.getDashboardId();
qrCodeDashboard.id = dashboardId;
qrCodeDashboard.style.width = "100%";
parent.appendChild(qrCodeDashboard);
this.setupInitialDashboard(qrCodeDashboard);
};
Html5QrcodeScanner.prototype.resetBasicLayout = function (mainContainer) {
mainContainer.style.border = "none";
};
Html5QrcodeScanner.prototype.setupInitialDashboard = function (dashboard) {
this.createSection(dashboard);
this.createSectionControlPanel();
if (this.scanTypeSelector.hasMoreThanOneScanType()) {
this.createSectionSwap();
}
};
Html5QrcodeScanner.prototype.createHeader = function (dashboard) {
var header = document.createElement("div");
header.style.textAlign = "left";
header.style.margin = "0px";
dashboard.appendChild(header);
var libraryInfo = new _ui.LibraryInfoContainer();
libraryInfo.renderInto(header);
var headerMessageContainer = document.createElement("div");
headerMessageContainer.id = this.getHeaderMessageContainerId();
headerMessageContainer.style.display = "none";
headerMessageContainer.style.textAlign = "center";
headerMessageContainer.style.fontSize = "14px";
headerMessageContainer.style.padding = "2px 10px";
headerMessageContainer.style.margin = "4px";
headerMessageContainer.style.borderTop = "1px solid #f6f6f6";
header.appendChild(headerMessageContainer);
};
Html5QrcodeScanner.prototype.createSection = function (dashboard) {
var section = document.createElement("div");
section.id = this.getDashboardSectionId();
section.style.width = "100%";
section.style.padding = "10px 0px 10px 0px";
section.style.textAlign = "left";
dashboard.appendChild(section);
};
Html5QrcodeScanner.prototype.createCameraListUi = function (scpCameraScanRegion, requestPermissionContainer, requestPermissionButton) {
var $this = this;
$this.showHideScanTypeSwapLink(false);
$this.setHeaderMessage(_strings.Html5QrcodeScannerStrings.cameraPermissionRequesting());
var createPermissionButtonIfNotExists = function createPermissionButtonIfNotExists() {
if (!requestPermissionButton) {
$this.createPermissionButton(scpCameraScanRegion, requestPermissionContainer);
}
};
_html5Qrcode.Html5Qrcode.getCameras().then(function (cameras) {
$this.persistedDataManager.setHasPermission(true);
$this.showHideScanTypeSwapLink(true);
$this.resetHeaderMessage();
if (cameras && cameras.length > 0) {
scpCameraScanRegion.removeChild(requestPermissionContainer);
$this.renderCameraSelection(cameras);
} else {
$this.setHeaderMessage(_strings.Html5QrcodeScannerStrings.noCameraFound(), Html5QrcodeScannerStatus.STATUS_WARNING);
createPermissionButtonIfNotExists();
}
}).catch(function (error) {
$this.persistedDataManager.setHasPermission(false);
if (requestPermissionButton) {
requestPermissionButton.disabled = false;
} else {
createPermissionButtonIfNotExists();
}
$this.setHeaderMessage(error, Html5QrcodeScannerStatus.STATUS_WARNING);
$this.showHideScanTypeSwapLink(true);
});
};
Html5QrcodeScanner.prototype.createPermissionButton = function (scpCameraScanRegion, requestPermissionContainer) {
var $this = this;
var requestPermissionButton = _base.BaseUiElementFactory.createElement("button", this.getCameraPermissionButtonId());
requestPermissionButton.innerText = _strings.Html5QrcodeScannerStrings.cameraPermissionTitle();
requestPermissionButton.addEventListener("click", function () {
requestPermissionButton.disabled = true;
$this.createCameraListUi(scpCameraScanRegion, requestPermissionContainer, requestPermissionButton);
});
requestPermissionContainer.appendChild(requestPermissionButton);
};
Html5QrcodeScanner.prototype.createPermissionsUi = function (scpCameraScanRegion, requestPermissionContainer) {
var $this = this;
if (_scanTypeSelector.ScanTypeSelector.isCameraScanType(this.currentScanType) && this.persistedDataManager.hasCameraPermissions()) {
_permissions.CameraPermissions.hasPermissions().then(function (hasPermissions) {
if (hasPermissions) {
$this.createCameraListUi(scpCameraScanRegion, requestPermissionContainer);
} else {
$this.persistedDataManager.setHasPermission(false);
$this.createPermissionButton(scpCameraScanRegion, requestPermissionContainer);
}
}).catch(function (_) {
$this.persistedDataManager.setHasPermission(false);
$this.createPermissionButton(scpCameraScanRegion, requestPermissionContainer);
});
return;
}
this.createPermissionButton(scpCameraScanRegion, requestPermissionContainer);
};
Html5QrcodeScanner.prototype.createSectionControlPanel = function () {
var section = document.getElementById(this.getDashboardSectionId());
var sectionControlPanel = document.createElement("div");
section.appendChild(sectionControlPanel);
var scpCameraScanRegion = document.createElement("div");
scpCameraScanRegion.id = this.getDashboardSectionCameraScanRegionId();
scpCameraScanRegion.style.display = _scanTypeSelector.ScanTypeSelector.isCameraScanType(this.currentScanType) ? "block" : "none";
sectionControlPanel.appendChild(scpCameraScanRegion);
var requestPermissionContainer = document.createElement("div");
requestPermissionContainer.style.textAlign = "center";
scpCameraScanRegion.appendChild(requestPermissionContainer);
if (this.scanTypeSelector.isCameraScanRequired()) {
this.createPermissionsUi(scpCameraScanRegion, requestPermissionContainer);
}
this.renderFileScanUi(sectionControlPanel);
};
Html5QrcodeScanner.prototype.renderFileScanUi = function (parent) {
var showOnRender = _scanTypeSelector.ScanTypeSelector.isFileScanType(this.currentScanType);
var $this = this;
var onFileSelected = function onFileSelected(file) {
if (!$this.html5Qrcode) {
throw "html5Qrcode not defined";
}
if (!_scanTypeSelector.ScanTypeSelector.isFileScanType($this.currentScanType)) {
return;
}
$this.setHeaderMessage(_strings.Html5QrcodeScannerStrings.loadingImage());
$this.html5Qrcode.scanFileV2(file, true).then(function (html5qrcodeResult) {
$this.resetHeaderMessage();
$this.qrCodeSuccessCallback(html5qrcodeResult.decodedText, html5qrcodeResult);
}).catch(function (error) {
$this.setHeaderMessage(error, Html5QrcodeScannerStatus.STATUS_WARNING);
$this.qrCodeErrorCallback(error, _core.Html5QrcodeErrorFactory.createFrom(error));
});
};
this.fileSelectionUi = _fileSelectionUi.FileSelectionUi.create(parent, showOnRender, onFileSelected);
};
Html5QrcodeScanner.prototype.renderCameraSelection = function (cameras) {
var _this = this;
var $this = this;
var scpCameraScanRegion = document.getElementById(this.getDashboardSectionCameraScanRegionId());
scpCameraScanRegion.style.textAlign = "center";
var cameraZoomUi = _cameraZoomUi.CameraZoomUi.create(scpCameraScanRegion, false);
var renderCameraZoomUiIfSupported = function renderCameraZoomUiIfSupported(cameraCapabilities) {
var zoomCapability = cameraCapabilities.zoomFeature();
if (!zoomCapability.isSupported()) {
return;
}
cameraZoomUi.setOnCameraZoomValueChangeCallback(function (zoomValue) {
zoomCapability.apply(zoomValue);
});
var defaultZoom = 1;
if (_this.config.defaultZoomValueIfSupported) {
defaultZoom = _this.config.defaultZoomValueIfSupported;
}
defaultZoom = (0, _core.clip)(defaultZoom, zoomCapability.min(), zoomCapability.max());
cameraZoomUi.setValues(zoomCapability.min(), zoomCapability.max(), defaultZoom, zoomCapability.step());
cameraZoomUi.show();
};
var cameraSelectUi = _cameraSelectionUi.CameraSelectionUi.create(scpCameraScanRegion, cameras);
var cameraActionContainer = document.createElement("span");
var cameraActionStartButton = _base.BaseUiElementFactory.createElement("button", _base.PublicUiElementIdAndClasses.CAMERA_START_BUTTON_ID);
cameraActionStartButton.innerText = _strings.Html5QrcodeScannerStrings.scanButtonStartScanningText();
cameraActionContainer.appendChild(cameraActionStartButton);
var cameraActionStopButton = _base.BaseUiElementFactory.createElement("button", _base.PublicUiElementIdAndClasses.CAMERA_STOP_BUTTON_ID);
cameraActionStopButton.innerText = _strings.Html5QrcodeScannerStrings.scanButtonStopScanningText();
cameraActionStopButton.style.display = "none";
cameraActionStopButton.disabled = true;
cameraActionContainer.appendChild(cameraActionStopButton);
var torchButton;
var createAndShowTorchButtonIfSupported = function createAndShowTorchButtonIfSupported(cameraCapabilities) {
if (!cameraCapabilities.torchFeature().isSupported()) {
if (torchButton) {
torchButton.hide();
}
return;
}
if (!torchButton) {
torchButton = _torchButton.TorchButton.create(cameraActionContainer, cameraCapabilities.torchFeature(), {
display: "none",
marginLeft: "5px"
}, function (errorMessage) {
$this.setHeaderMessage(errorMessage, Html5QrcodeScannerStatus.STATUS_WARNING);
});
} else {
torchButton.updateTorchCapability(cameraCapabilities.torchFeature());
}
torchButton.show();
};
scpCameraScanRegion.appendChild(cameraActionContainer);
var resetCameraActionStartButton = function resetCameraActionStartButton(shouldShow) {
if (!shouldShow) {
cameraActionStartButton.style.display = "none";
}
cameraActionStartButton.innerText = _strings.Html5QrcodeScannerStrings.scanButtonStartScanningText();
cameraActionStartButton.style.opacity = "1";
cameraActionStartButton.disabled = false;
if (shouldShow) {
cameraActionStartButton.style.display = "inline-block";
}
};
cameraActionStartButton.addEventListener("click", function (_) {
cameraActionStartButton.innerText = _strings.Html5QrcodeScannerStrings.scanButtonScanningStarting();
cameraSelectUi.disable();
cameraActionStartButton.disabled = true;
cameraActionStartButton.style.opacity = "0.5";
if (_this.scanTypeSelector.hasMoreThanOneScanType()) {
$this.showHideScanTypeSwapLink(false);
}
$this.resetHeaderMessage();
var cameraId = cameraSelectUi.getValue();
$this.persistedDataManager.setLastUsedCameraId(cameraId);
$this.html5Qrcode.start(cameraId, toHtml5QrcodeCameraScanConfig($this.config), $this.qrCodeSuccessCallback, $this.qrCodeErrorCallback).then(function (_) {
cameraActionStopButton.disabled = false;
cameraActionStopButton.style.display = "inline-block";
resetCameraActionStartButton(false);
var cameraCapabilities = $this.html5Qrcode.getRunningTrackCameraCapabilities();
if (_this.config.showTorchButtonIfSupported === true) {
createAndShowTorchButtonIfSupported(cameraCapabilities);
}
if (_this.config.showZoomSliderIfSupported === true) {
renderCameraZoomUiIfSupported(cameraCapabilities);
}
}).catch(function (error) {
$this.showHideScanTypeSwapLink(true);
cameraSelectUi.enable();
resetCameraActionStartButton(true);
$this.setHeaderMessage(error, Html5QrcodeScannerStatus.STATUS_WARNING);
});
});
if (cameraSelectUi.hasSingleItem()) {
cameraActionStartButton.click();
}
cameraActionStopButton.addEventListener("click", function (_) {
if (!$this.html5Qrcode) {
throw "html5Qrcode not defined";
}
cameraActionStopButton.disabled = true;
$this.html5Qrcode.stop().then(function (_) {
if (_this.scanTypeSelector.hasMoreThanOneScanType()) {
$this.showHideScanTypeSwapLink(true);
}
cameraSelectUi.enable();
cameraActionStartButton.disabled = false;
cameraActionStopButton.style.display = "none";
cameraActionStartButton.style.display = "inline-block";
if (torchButton) {
torchButton.reset();
torchButton.hide();
}
cameraZoomUi.removeOnCameraZoomValueChangeCallback();
cameraZoomUi.hide();
$this.insertCameraScanImageToScanRegion();
}).catch(function (error) {
cameraActionStopButton.disabled = false;
$this.setHeaderMessage(error, Html5QrcodeScannerStatus.STATUS_WARNING);
});
});
if ($this.persistedDataManager.getLastUsedCameraId()) {
var cameraId = $this.persistedDataManager.getLastUsedCameraId();
if (cameraSelectUi.hasValue(cameraId)) {
cameraSelectUi.setValue(cameraId);
cameraActionStartButton.click();
} else {
$this.persistedDataManager.resetLastUsedCameraId();
}
}
};
Html5QrcodeScanner.prototype.createSectionSwap = function () {
var $this = this;
var TEXT_IF_CAMERA_SCAN_SELECTED = _strings.Html5QrcodeScannerStrings.textIfCameraScanSelected();
var TEXT_IF_FILE_SCAN_SELECTED = _strings.Html5QrcodeScannerStrings.textIfFileScanSelected();
var section = document.getElementById(this.getDashboardSectionId());
var switchContainer = document.createElement("div");
switchContainer.style.textAlign = "center";
var switchScanTypeLink = _base.BaseUiElementFactory.createElement("span", this.getDashboardSectionSwapLinkId());
switchScanTypeLink.style.textDecoration = "underline";
switchScanTypeLink.style.cursor = "pointer";
switchScanTypeLink.innerText = _scanTypeSelector.ScanTypeSelector.isCameraScanType(this.currentScanType) ? TEXT_IF_CAMERA_SCAN_SELECTED : TEXT_IF_FILE_SCAN_SELECTED;
switchScanTypeLink.addEventListener("click", function () {
if (!$this.sectionSwapAllowed) {
if ($this.verbose) {
$this.logger.logError("Section swap called when not allowed");
}
return;
}
$this.resetHeaderMessage();
$this.fileSelectionUi.resetValue();
$this.sectionSwapAllowed = false;
if (_scanTypeSelector.ScanTypeSelector.isCameraScanType($this.currentScanType)) {
$this.clearScanRegion();
$this.getCameraScanRegion().style.display = "none";
$this.fileSelectionUi.show();
switchScanTypeLink.innerText = TEXT_IF_FILE_SCAN_SELECTED;
$this.currentScanType = _core.Html5QrcodeScanType.SCAN_TYPE_FILE;
$this.insertFileScanImageToScanRegion();
} else {
$this.clearScanRegion();
$this.getCameraScanRegion().style.display = "block";
$this.fileSelectionUi.hide();
switchScanTypeLink.innerText = TEXT_IF_CAMERA_SCAN_SELECTED;
$this.currentScanType = _core.Html5QrcodeScanType.SCAN_TYPE_CAMERA;
$this.insertCameraScanImageToScanRegion();
$this.startCameraScanIfPermissionExistsOnSwap();
}
$this.sectionSwapAllowed = true;
});
switchContainer.appendChild(switchScanTypeLink);
section.appendChild(switchContainer);
};
Html5QrcodeScanner.prototype.startCameraScanIfPermissionExistsOnSwap = function () {
var _this = this;
var $this = this;
if (this.persistedDataManager.hasCameraPermissions()) {
_permissions.CameraPermissions.hasPermissions().then(function (hasPermissions) {
if (hasPermissions) {
var permissionButton = document.getElementById($this.getCameraPermissionButtonId());
if (!permissionButton) {
_this.logger.logError("Permission button not found, fail;");
throw "Permission button not found";
}
permissionButton.click();
} else {
$this.persistedDataManager.setHasPermission(false);
}
}).catch(function (_) {
$this.persistedDataManager.setHasPermission(false);
});
return;
}
};
Html5QrcodeScanner.prototype.resetHeaderMessage = function () {
var messageDiv = document.getElementById(this.getHeaderMessageContainerId());
messageDiv.style.display = "none";
};
Html5QrcodeScanner.prototype.setHeaderMessage = function (messageText, scannerStatus) {
if (!scannerStatus) {
scannerStatus = Html5QrcodeScannerStatus.STATUS_DEFAULT;
}
var messageDiv = this.getHeaderMessageDiv();
messageDiv.innerText = messageText;
messageDiv.style.display = "block";
switch (scannerStatus) {
case Html5QrcodeScannerStatus.STATUS_SUCCESS:
messageDiv.style.background = "rgba(106, 175, 80, 0.26)";
messageDiv.style.color = "#477735";
break;
case Html5QrcodeScannerStatus.STATUS_WARNING:
messageDiv.style.background = "rgba(203, 36, 49, 0.14)";
messageDiv.style.color = "#cb2431";
break;
case Html5QrcodeScannerStatus.STATUS_DEFAULT:
default:
messageDiv.style.background = "rgba(0, 0, 0, 0)";
messageDiv.style.color = "rgb(17, 17, 17)";
break;
}
};
Html5QrcodeScanner.prototype.showHideScanTypeSwapLink = function (shouldDisplay) {
if (this.scanTypeSelector.hasMoreThanOneScanType()) {
if (shouldDisplay !== true) {
shouldDisplay = false;
}
this.sectionSwapAllowed = shouldDisplay;
this.getDashboardSectionSwapLink().style.display = shouldDisplay ? "inline-block" : "none";
}
};
Html5QrcodeScanner.prototype.insertCameraScanImageToScanRegion = function () {
var $this = this;
var qrCodeScanRegion = document.getElementById(this.getScanRegionId());
if (this.cameraScanImage) {
qrCodeScanRegion.innerHTML = "<br>";
qrCodeScanRegion.appendChild(this.cameraScanImage);
return;
}
this.cameraScanImage = new Image();
this.cameraScanImage.onload = function (_) {
qrCodeScanRegion.innerHTML = "<br>";
qrCodeScanRegion.appendChild($this.cameraScanImage);
};
this.cameraScanImage.width = 64;
this.cameraScanImage.style.opacity = "0.8";
this.cameraScanImage.src = _imageAssets.ASSET_CAMERA_SCAN;
this.cameraScanImage.alt = _strings.Html5QrcodeScannerStrings.cameraScanAltText();
};
Html5QrcodeScanner.prototype.insertFileScanImageToScanRegion = function () {
var $this = this;
var qrCodeScanRegion = document.getElementById(this.getScanRegionId());
if (this.fileScanImage) {
qrCodeScanRegion.innerHTML = "<br>";
qrCodeScanRegion.appendChild(this.fileScanImage);
return;
}
this.fileScanImage = new Image();
this.fileScanImage.onload = function (_) {
qrCodeScanRegion.innerHTML = "<br>";
qrCodeScanRegion.appendChild($this.fileScanImage);
};
this.fileScanImage.width = 64;
this.fileScanImage.style.opacity = "0.8";
this.fileScanImage.src = _imageAssets.ASSET_FILE_SCAN;
this.fileScanImage.alt = _strings.Html5QrcodeScannerStrings.fileScanAltText();
};
Html5QrcodeScanner.prototype.clearScanRegion = function () {
var qrCodeScanRegion = document.getElementById(this.getScanRegionId());
qrCodeScanRegion.innerHTML = "";
};
Html5QrcodeScanner.prototype.getDashboardSectionId = function () {
return "".concat(this.elementId, "__dashboard_section");
};
Html5QrcodeScanner.prototype.getDashboardSectionCameraScanRegionId = function () {
return "".concat(this.elementId, "__dashboard_section_csr");
};
Html5QrcodeScanner.prototype.getDashboardSectionSwapLinkId = function () {
return _base.PublicUiElementIdAndClasses.SCAN_TYPE_CHANGE_ANCHOR_ID;
};
Html5QrcodeScanner.prototype.getScanRegionId = function () {
return "".concat(this.elementId, "__scan_region");
};
Html5QrcodeScanner.prototype.getDashboardId = function () {
return "".concat(this.elementId, "__dashboard");
};
Html5QrcodeScanner.prototype.getHeaderMessageContainerId = function () {
return "".concat(this.elementId, "__header_message");
};
Html5QrcodeScanner.prototype.getCameraPermissionButtonId = function () {
return _base.PublicUiElementIdAndClasses.CAMERA_PERMISSION_BUTTON_ID;
};
Html5QrcodeScanner.prototype.getCameraScanRegion = function () {
return document.getElementById(this.getDashboardSectionCameraScanRegionId());
};
Html5QrcodeScanner.prototype.getDashboardSectionSwapLink = function () {
return document.getElementById(this.getDashboardSectionSwapLinkId());
};
Html5QrcodeScanner.prototype.getHeaderMessageDiv = function () {
return document.getElementById(this.getHeaderMessageContainerId());
};
return Html5QrcodeScanner;
}();
exports.Html5QrcodeScanner = Html5QrcodeScanner;
/***/ }),
/* 82 */
/*!****************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/image-assets.js ***!
\****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ASSET_INFO_ICON_16PX = exports.ASSET_FILE_SCAN = exports.ASSET_CLOSE_ICON_16PX = exports.ASSET_CAMERA_SCAN = void 0;
var SVG_XML_PREFIX = "data:image/svg+xml;base64,";
var ASSET_CAMERA_SCAN = SVG_XML_PREFIX + "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzNzEuNjQzIDM3MS42NDMiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDM3MS42NDMgMzcxLjY0MyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+PHBhdGggZD0iTTEwNS4wODQgMzguMjcxaDE2My43Njh2MjBIMTA1LjA4NHoiLz48cGF0aCBkPSJNMzExLjU5NiAxOTAuMTg5Yy03LjQ0MS05LjM0Ny0xOC40MDMtMTYuMjA2LTMyLjc0My0yMC41MjJWMzBjMC0xNi41NDItMTMuNDU4LTMwLTMwLTMwSDEyNS4wODRjLTE2LjU0MiAwLTMwIDEzLjQ1OC0zMCAzMHYxMjAuMTQzaC04LjI5NmMtMTYuNTQyIDAtMzAgMTMuNDU4LTMwIDMwdjEuMzMzYTI5LjgwNCAyOS44MDQgMCAwIDAgNC42MDMgMTUuOTM5Yy03LjM0IDUuNDc0LTEyLjEwMyAxNC4yMjEtMTIuMTAzIDI0LjA2MXYxLjMzM2MwIDkuODQgNC43NjMgMTguNTg3IDEyLjEwMyAyNC4wNjJhMjkuODEgMjkuODEgMCAwIDAtNC42MDMgMTUuOTM4djEuMzMzYzAgMTYuNTQyIDEzLjQ1OCAzMCAzMCAzMGg4LjMyNGMuNDI3IDExLjYzMSA3LjUwMyAyMS41ODcgMTcuNTM0IDI2LjE3Ny45MzEgMTAuNTAzIDQuMDg0IDMwLjE4NyAxNC43NjggNDUuNTM3YTkuOTg4IDkuOTg4IDAgMCAwIDguMjE2IDQuMjg4IDkuOTU4IDkuOTU4IDAgMCAwIDUuNzA0LTEuNzkzYzQuNTMzLTMuMTU1IDUuNjUtOS4zODggMi40OTUtMTMuOTIxLTYuNzk4LTkuNzY3LTkuNjAyLTIyLjYwOC0xMC43Ni0zMS40aDgyLjY4NWMuMjcyLjQxNC41NDUuODE4LjgxNSAxLjIxIDMuMTQyIDQuNTQxIDkuMzcyIDUuNjc5IDEzLjkxMyAyLjUzNCA0LjU0Mi0zLjE0MiA1LjY3Ny05LjM3MSAyLjUzNS0xMy45MTMtMTEuOTE5LTE3LjIyOS04Ljc4Ny0zNS44ODQgOS41ODEtNTcuMDEyIDMuMDY3LTIuNjUyIDEyLjMwNy0xMS43MzIgMTEuMjE3LTI0LjAzMy0uODI4LTkuMzQzLTcuMTA5LTE3LjE5NC0xOC42NjktMjMuMzM3YTkuODU3IDkuODU3IDAgMCAwLTEuMDYxLS40ODZjLS40NjYtLjE4Mi0xMS40MDMtNC41NzktOS43NDEtMTUuNzA2IDEuMDA3LTYuNzM3IDE0Ljc2OC04LjI3MyAyMy43NjYtNy42NjYgMjMuMTU2IDEuNTY5IDM5LjY5OCA3LjgwMyA0Ny44MzYgMTguMDI2IDUuNzUyIDcuMjI1IDcuNjA3IDE2LjYyMyA1LjY3MyAyOC43MzMtLjQxMyAyLjU4NS0uODI0IDUuMjQxLTEuMjQ1IDcuOTU5LTUuNzU2IDM3LjE5NC0xMi45MTkgODMuNDgzLTQ5Ljg3IDExNC42NjEtNC4yMjEgMy41NjEtNC43NTYgOS44Ny0xLjE5NCAxNC4wOTJhOS45OCA5Ljk4IDAgMCAwIDcuNjQ4IDMuNTUxIDkuOTU1IDkuOTU1IDAgMCAwIDYuNDQ0LTIuMzU4YzQyLjY3Mi0zNi4wMDUgNTAuODAyLTg4LjUzMyA1Ni43MzctMTI2Ljg4OC40MTUtMi42ODQuODIxLTUuMzA5IDEuMjI5LTcuODYzIDIuODM0LTE3LjcyMS0uNDU1LTMyLjY0MS05Ljc3Mi00NC4zNDV6bS0yMzIuMzA4IDQyLjYyYy01LjUxNCAwLTEwLTQuNDg2LTEwLTEwdi0xLjMzM2MwLTUuNTE0IDQuNDg2LTEwIDEwLTEwaDE1djIxLjMzM2gtMTV6bS0yLjUtNTIuNjY2YzAtNS41MTQgNC40ODYtMTAgMTAtMTBoNy41djIxLjMzM2gtNy41Yy01LjUxNCAwLTEwLTQuNDg2LTEwLTEwdi0xLjMzM3ptMTcuNSA5My45OTloLTcuNWMtNS41MTQgMC0xMC00LjQ4Ni0xMC0xMHYtMS4zMzNjMC01LjUxNCA0LjQ4Ni0xMCAxMC0xMGg3LjV2MjEuMzMzem0zMC43OTYgMjguODg3Yy01LjUxNCAwLTEwLTQuNDg2LTEwLTEwdi04LjI3MWg5MS40NTdjLS44NTEgNi42NjgtLjQzNyAxMi43ODcuNzMxIDE4LjI3MWgtODIuMTg4em03OS40ODItMTEzLjY5OGMtMy4xMjQgMjAuOTA2IDEyLjQyNyAzMy4xODQgMjEuNjI1IDM3LjA0IDUuNDQxIDIuOTY4IDcuNTUxIDUuNjQ3IDcuNzAxIDcuMTg4LjIxIDIuMTUtMi41NTMgNS42ODQtNC40NzcgNy4yNTEtLjQ4Mi4zNzgtLjkyOS44LTEuMzM1IDEuMjYxLTYuOTg3IDcuOTM2LTExLjk4MiAxNS41Mi0xNS40MzIgMjIuNjg4aC05Ny41NjRWMzBjMC01LjUxNCA0LjQ4Ni0xMCAxMC0xMGgxMjMuNzY5YzUuNTE0IDAgMTAgNC40ODYgMTAgMTB2MTM1LjU3OWMtMy4wMzItLjM4MS02LjE1LS42OTQtOS4zODktLjkxNC0yNS4xNTktMS42OTQtNDIuMzcgNy43NDgtNDQuODk4IDI0LjY2NnoiLz48cGF0aCBkPSJNMTc5LjEyOSA4My4xNjdoLTI0LjA2YTUgNSAwIDAgMC01IDV2MjQuMDYxYTUgNSAwIDAgMCA1IDVoMjQuMDZhNSA1IDAgMCAwIDUtNVY4OC4xNjdhNSA1IDAgMCAwLTUtNXpNMTcyLjYyOSAxNDIuODZoLTEyLjU2VjEzMC44YTUgNSAwIDEgMC0xMCAwdjE3LjA2MWE1IDUgMCAwIDAgNSA1aDE3LjU2YTUgNSAwIDEgMCAwLTEwLjAwMXpNMjE2LjU2OCA4My4xNjdoLTI0LjA2YTUgNSAwIDAgMC01IDV2MjQuMDYxYTUgNSAwIDAgMCA1IDVoMjQuMDZhNSA1IDAgMCAwIDUtNVY4OC4xNjdhNSA1IDAgMCAwLTUtNXptLTUgMjQuMDYxaC0xNC4wNlY5My4xNjdoMTQuMDZ2MTQuMDYxek0yMTEuNjY5IDEyNS45MzZIMTk3LjQxYTUgNSAwIDAgMC01IDV2MTQuMjU3YTUgNSAwIDAgMCA1IDVoMTQuMjU5YTUgNSAwIDAgMCA1LTV2LTE0LjI1N2E1IDUgMCAwIDAtNS01eiIvPjwvc3ZnPg==";
exports.ASSET_CAMERA_SCAN = ASSET_CAMERA_SCAN;
var ASSET_FILE_SCAN = SVG_XML_PREFIX + "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1OS4wMTggNTkuMDE4IiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA1OS4wMTggNTkuMDE4IiB4bWw6c3BhY2U9InByZXNlcnZlIj48cGF0aCBkPSJtNTguNzQxIDU0LjgwOS01Ljk2OS02LjI0NGExMC43NCAxMC43NCAwIDAgMCAyLjgyLTcuMjVjMC01Ljk1My00Ljg0My0xMC43OTYtMTAuNzk2LTEwLjc5NlMzNCAzNS4zNjEgMzQgNDEuMzE0IDM4Ljg0MyA1Mi4xMSA0NC43OTYgNTIuMTFjMi40NDEgMCA0LjY4OC0uODI0IDYuNDk5LTIuMTk2bDYuMDAxIDYuMjc3YS45OTguOTk4IDAgMCAwIDEuNDE0LjAzMiAxIDEgMCAwIDAgLjAzMS0xLjQxNHpNMzYgNDEuMzE0YzAtNC44NSAzLjk0Ni04Ljc5NiA4Ljc5Ni04Ljc5NnM4Ljc5NiAzLjk0NiA4Ljc5NiA4Ljc5Ni0zLjk0NiA4Ljc5Ni04Ljc5NiA4Ljc5NlMzNiA0Ni4xNjQgMzYgNDEuMzE0ek0xMC40MzEgMTYuMDg4YzAgMy4wNyAyLjQ5OCA1LjU2OCA1LjU2OSA1LjU2OHM1LjU2OS0yLjQ5OCA1LjU2OS01LjU2OGMwLTMuMDcxLTIuNDk4LTUuNTY5LTUuNTY5LTUuNTY5cy01LjU2OSAyLjQ5OC01LjU2OSA1LjU2OXptOS4xMzggMGMwIDEuOTY4LTEuNjAyIDMuNTY4LTMuNTY5IDMuNTY4cy0zLjU2OS0xLjYwMS0zLjU2OS0zLjU2OCAxLjYwMi0zLjU2OSAzLjU2OS0zLjU2OSAzLjU2OSAxLjYwMSAzLjU2OSAzLjU2OXoiLz48cGF0aCBkPSJtMzAuODgyIDI4Ljk4NyA5LjE4LTEwLjA1NCAxMS4yNjIgMTAuMzIzYTEgMSAwIDAgMCAxLjM1MS0xLjQ3NWwtMTItMTFhMSAxIDAgMCAwLTEuNDE0LjA2M2wtOS43OTQgMTAuNzI3LTQuNzQzLTQuNzQzYTEuMDAzIDEuMDAzIDAgMCAwLTEuMzY4LS4wNDRMNi4zMzkgMzcuNzY4YTEgMSAwIDEgMCAxLjMyMiAxLjUwMWwxNi4zMTMtMTQuMzYyIDcuMzE5IDcuMzE4YS45OTkuOTk5IDAgMSAwIDEuNDE0LTEuNDE0bC0xLjgyNS0xLjgyNHoiLz48cGF0aCBkPSJNMzAgNDYuNTE4SDJ2LTQyaDU0djI4YTEgMSAwIDEgMCAyIDB2LTI5YTEgMSAwIDAgMC0xLTFIMWExIDEgMCAwIDAtMSAxdjQ0YTEgMSAwIDAgMCAxIDFoMjlhMSAxIDAgMSAwIDAtMnoiLz48L3N2Zz4=";
exports.ASSET_FILE_SCAN = ASSET_FILE_SCAN;
var ASSET_INFO_ICON_16PX = SVG_XML_PREFIX + "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0NjAgNDYwIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA0NjAgNDYwIiB4bWw6c3BhY2U9InByZXNlcnZlIj48cGF0aCBkPSJNMjMwIDBDMTAyLjk3NSAwIDAgMTAyLjk3NSAwIDIzMHMxMDIuOTc1IDIzMCAyMzAgMjMwIDIzMC0xMDIuOTc0IDIzMC0yMzBTMzU3LjAyNSAwIDIzMCAwem0zOC4zMzMgMzc3LjM2YzAgOC42NzYtNy4wMzQgMTUuNzEtMTUuNzEgMTUuNzFoLTQzLjEwMWMtOC42NzYgMC0xNS43MS03LjAzNC0xNS43MS0xNS43MVYyMDIuNDc3YzAtOC42NzYgNy4wMzMtMTUuNzEgMTUuNzEtMTUuNzFoNDMuMTAxYzguNjc2IDAgMTUuNzEgNy4wMzMgMTUuNzEgMTUuNzFWMzc3LjM2ek0yMzAgMTU3Yy0yMS41MzkgMC0zOS0xNy40NjEtMzktMzlzMTcuNDYxLTM5IDM5LTM5IDM5IDE3LjQ2MSAzOSAzOS0xNy40NjEgMzktMzkgMzl6Ii8+PC9zdmc+";
exports.ASSET_INFO_ICON_16PX = ASSET_INFO_ICON_16PX;
var ASSET_CLOSE_ICON_16PX = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAAQgAAAEIBarqQRAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAE1SURBVDiNfdI7S0NBEAXgLya1otFgpbYSbISAgpXYi6CmiH9KCAiChaVga6OiWPgfRDQ+0itaGVNosXtluWwcuMzePfM4M3sq8lbHBubwg1dc4m1E/J/N4ghDPOIsfk/4xiEao5KX0McFljN4C9d4QTPXuY99jP3DsIoDPGM6BY5i5yI5R7O4q+ImFkJY2DCh3cAH2klyB+9J1xUMMAG7eCh1a+Mr+k48b5diXrFVwwLuS+BJ9MfR7+G0FHOHhTHhnXNWS87VDF4pcnfQK4Ep7XScNLmPTZgURNKKYENYWDpzW1BhscS1WHS8CDgURFJQrWcoF3c13KKbgg1BYQfy8xZWEzTTw1QZbAoKu8FqJnktdu5hcVSHmchiILzzuaDQvjBzV2m8yohCE1jHfPx/xhU+y4G/D75ELlRJsSYAAAAASUVORK5CYII=";
exports.ASSET_CLOSE_ICON_16PX = ASSET_CLOSE_ICON_16PX;
/***/ }),
/* 83 */
/*!***********************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/storage.js ***!
\***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PersistedDataManager = void 0;
var PersistedDataFactory = function () {
function PersistedDataFactory() {}
PersistedDataFactory.createDefault = function () {
return {
hasPermission: false,
lastUsedCameraId: null
};
};
return PersistedDataFactory;
}();
var PersistedDataManager = function () {
function PersistedDataManager() {
this.data = PersistedDataFactory.createDefault();
var data = localStorage.getItem(PersistedDataManager.LOCAL_STORAGE_KEY);
if (!data) {
this.reset();
} else {
this.data = JSON.parse(data);
}
}
PersistedDataManager.prototype.hasCameraPermissions = function () {
return this.data.hasPermission;
};
PersistedDataManager.prototype.getLastUsedCameraId = function () {
return this.data.lastUsedCameraId;
};
PersistedDataManager.prototype.setHasPermission = function (hasPermission) {
this.data.hasPermission = hasPermission;
this.flush();
};
PersistedDataManager.prototype.setLastUsedCameraId = function (lastUsedCameraId) {
this.data.lastUsedCameraId = lastUsedCameraId;
this.flush();
};
PersistedDataManager.prototype.resetLastUsedCameraId = function () {
this.data.lastUsedCameraId = null;
this.flush();
};
PersistedDataManager.prototype.reset = function () {
this.data = PersistedDataFactory.createDefault();
this.flush();
};
PersistedDataManager.prototype.flush = function () {
localStorage.setItem(PersistedDataManager.LOCAL_STORAGE_KEY, JSON.stringify(this.data));
};
PersistedDataManager.LOCAL_STORAGE_KEY = "HTML5_QRCODE_DATA";
return PersistedDataManager;
}();
exports.PersistedDataManager = PersistedDataManager;
/***/ }),
/* 84 */
/*!******************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/ui.js ***!
\******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LibraryInfoContainer = void 0;
var _imageAssets = __webpack_require__(/*! ./image-assets */ 82);
var _strings = __webpack_require__(/*! ./strings */ 63);
var LibraryInfoDiv = function () {
function LibraryInfoDiv() {
this.infoDiv = document.createElement("div");
}
LibraryInfoDiv.prototype.renderInto = function (parent) {
this.infoDiv.style.position = "absolute";
this.infoDiv.style.top = "10px";
this.infoDiv.style.right = "10px";
this.infoDiv.style.zIndex = "2";
this.infoDiv.style.display = "none";
this.infoDiv.style.padding = "5pt";
this.infoDiv.style.border = "1px solid #171717";
this.infoDiv.style.fontSize = "10pt";
this.infoDiv.style.background = "rgb(0 0 0 / 69%)";
this.infoDiv.style.borderRadius = "5px";
this.infoDiv.style.textAlign = "center";
this.infoDiv.style.fontWeight = "400";
this.infoDiv.style.color = "white";
this.infoDiv.innerText = _strings.LibraryInfoStrings.poweredBy();
var projectLink = document.createElement("a");
projectLink.innerText = "ScanApp";
projectLink.href = "https://scanapp.org";
projectLink.target = "new";
projectLink.style.color = "white";
this.infoDiv.appendChild(projectLink);
var breakElemFirst = document.createElement("br");
var breakElemSecond = document.createElement("br");
this.infoDiv.appendChild(breakElemFirst);
this.infoDiv.appendChild(breakElemSecond);
var reportIssueLink = document.createElement("a");
reportIssueLink.innerText = _strings.LibraryInfoStrings.reportIssues();
reportIssueLink.href = "https://github.com/mebjas/html5-qrcode/issues";
reportIssueLink.target = "new";
reportIssueLink.style.color = "white";
this.infoDiv.appendChild(reportIssueLink);
parent.appendChild(this.infoDiv);
};
LibraryInfoDiv.prototype.show = function () {
this.infoDiv.style.display = "block";
};
LibraryInfoDiv.prototype.hide = function () {
this.infoDiv.style.display = "none";
};
return LibraryInfoDiv;
}();
var LibraryInfoIcon = function () {
function LibraryInfoIcon(onTapIn, onTapOut) {
this.isShowingInfoIcon = true;
this.onTapIn = onTapIn;
this.onTapOut = onTapOut;
this.infoIcon = document.createElement("img");
}
LibraryInfoIcon.prototype.renderInto = function (parent) {
var _this = this;
this.infoIcon.alt = "Info icon";
this.infoIcon.src = _imageAssets.ASSET_INFO_ICON_16PX;
this.infoIcon.style.position = "absolute";
this.infoIcon.style.top = "4px";
this.infoIcon.style.right = "4px";
this.infoIcon.style.opacity = "0.6";
this.infoIcon.style.cursor = "pointer";
this.infoIcon.style.zIndex = "2";
this.infoIcon.style.width = "16px";
this.infoIcon.style.height = "16px";
this.infoIcon.onmouseover = function (_) {
return _this.onHoverIn();
};
this.infoIcon.onmouseout = function (_) {
return _this.onHoverOut();
};
this.infoIcon.onclick = function (_) {
return _this.onClick();
};
parent.appendChild(this.infoIcon);
};
LibraryInfoIcon.prototype.onHoverIn = function () {
if (this.isShowingInfoIcon) {
this.infoIcon.style.opacity = "1";
}
};
LibraryInfoIcon.prototype.onHoverOut = function () {
if (this.isShowingInfoIcon) {
this.infoIcon.style.opacity = "0.6";
}
};
LibraryInfoIcon.prototype.onClick = function () {
if (this.isShowingInfoIcon) {
this.isShowingInfoIcon = false;
this.onTapIn();
this.infoIcon.src = _imageAssets.ASSET_CLOSE_ICON_16PX;
this.infoIcon.style.opacity = "1";
} else {
this.isShowingInfoIcon = true;
this.onTapOut();
this.infoIcon.src = _imageAssets.ASSET_INFO_ICON_16PX;
this.infoIcon.style.opacity = "0.6";
}
};
return LibraryInfoIcon;
}();
var LibraryInfoContainer = function () {
function LibraryInfoContainer() {
var _this = this;
this.infoDiv = new LibraryInfoDiv();
this.infoIcon = new LibraryInfoIcon(function () {
_this.infoDiv.show();
}, function () {
_this.infoDiv.hide();
});
}
LibraryInfoContainer.prototype.renderInto = function (parent) {
this.infoDiv.renderInto(parent);
this.infoIcon.renderInto(parent);
};
return LibraryInfoContainer;
}();
exports.LibraryInfoContainer = LibraryInfoContainer;
/***/ }),
/* 85 */
/*!**********************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/camera/permissions.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CameraPermissions = void 0;
var __awaiter = void 0 && (void 0).__awaiter || function (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());
});
};
var __generator = void 0 && (void 0).__generator || function (thisArg, body) {
var _ = {
label: 0,
sent: function sent() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"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
};
}
};
var CameraPermissions = function () {
function CameraPermissions() {}
CameraPermissions.hasPermissions = function () {
return __awaiter(this, void 0, void 0, function () {
var devices, _i, devices_1, device;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
return [4, navigator.mediaDevices.enumerateDevices()];
case 1:
devices = _a.sent();
for (_i = 0, devices_1 = devices; _i < devices_1.length; _i++) {
device = devices_1[_i];
if (device.kind === "videoinput" && device.label) {
return [2, true];
}
}
return [2, false];
}
});
});
};
return CameraPermissions;
}();
exports.CameraPermissions = CameraPermissions;
/***/ }),
/* 86 */
/*!*********************************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/ui/scanner/scan-type-selector.js ***!
\*********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ScanTypeSelector = void 0;
var _core = __webpack_require__(/*! ../../core */ 62);
var ScanTypeSelector = function () {
function ScanTypeSelector(supportedScanTypes) {
this.supportedScanTypes = this.validateAndReturnScanTypes(supportedScanTypes);
}
ScanTypeSelector.prototype.getDefaultScanType = function () {
return this.supportedScanTypes[0];
};
ScanTypeSelector.prototype.hasMoreThanOneScanType = function () {
return this.supportedScanTypes.length > 1;
};
ScanTypeSelector.prototype.isCameraScanRequired = function () {
for (var _i = 0, _a = this.supportedScanTypes; _i < _a.length; _i++) {
var scanType = _a[_i];
if (ScanTypeSelector.isCameraScanType(scanType)) {
return true;
}
}
return false;
};
ScanTypeSelector.isCameraScanType = function (scanType) {
return scanType === _core.Html5QrcodeScanType.SCAN_TYPE_CAMERA;
};
ScanTypeSelector.isFileScanType = function (scanType) {
return scanType === _core.Html5QrcodeScanType.SCAN_TYPE_FILE;
};
ScanTypeSelector.prototype.validateAndReturnScanTypes = function (supportedScanTypes) {
if (!supportedScanTypes || supportedScanTypes.length === 0) {
return _core.Html5QrcodeConstants.DEFAULT_SUPPORTED_SCAN_TYPE;
}
var maxExpectedValues = _core.Html5QrcodeConstants.DEFAULT_SUPPORTED_SCAN_TYPE.length;
if (supportedScanTypes.length > maxExpectedValues) {
throw "Max ".concat(maxExpectedValues, " values expected for ") + "supportedScanTypes";
}
for (var _i = 0, supportedScanTypes_1 = supportedScanTypes; _i < supportedScanTypes_1.length; _i++) {
var scanType = supportedScanTypes_1[_i];
if (!_core.Html5QrcodeConstants.DEFAULT_SUPPORTED_SCAN_TYPE.includes(scanType)) {
throw "Unsupported scan type ".concat(scanType);
}
}
return supportedScanTypes;
};
return ScanTypeSelector;
}();
exports.ScanTypeSelector = ScanTypeSelector;
/***/ }),
/* 87 */
/*!***************************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/ui/scanner/torch-button.js ***!
\***************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TorchButton = void 0;
var _strings = __webpack_require__(/*! ../../strings */ 63);
var _base = __webpack_require__(/*! ./base */ 88);
var __awaiter = void 0 && (void 0).__awaiter || function (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());
});
};
var __generator = void 0 && (void 0).__generator || function (thisArg, body) {
var _ = {
label: 0,
sent: function sent() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"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
};
}
};
var TorchController = function () {
function TorchController(torchCapability, buttonController, onTorchActionFailureCallback) {
this.isTorchOn = false;
this.torchCapability = torchCapability;
this.buttonController = buttonController;
this.onTorchActionFailureCallback = onTorchActionFailureCallback;
}
TorchController.prototype.isTorchEnabled = function () {
return this.isTorchOn;
};
TorchController.prototype.flipState = function () {
return __awaiter(this, void 0, void 0, function () {
var isTorchOnExpected, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.buttonController.disable();
isTorchOnExpected = !this.isTorchOn;
_a.label = 1;
case 1:
_a.trys.push([1, 3,, 4]);
return [4, this.torchCapability.apply(isTorchOnExpected)];
case 2:
_a.sent();
this.updateUiBasedOnLatestSettings(this.torchCapability.value(), isTorchOnExpected);
return [3, 4];
case 3:
error_1 = _a.sent();
this.propagateFailure(isTorchOnExpected, error_1);
this.buttonController.enable();
return [3, 4];
case 4:
return [2];
}
});
});
};
TorchController.prototype.updateUiBasedOnLatestSettings = function (isTorchOn, isTorchOnExpected) {
if (isTorchOn === isTorchOnExpected) {
this.buttonController.setText(isTorchOnExpected ? _strings.Html5QrcodeScannerStrings.torchOffButton() : _strings.Html5QrcodeScannerStrings.torchOnButton());
this.isTorchOn = isTorchOnExpected;
} else {
this.propagateFailure(isTorchOnExpected);
}
this.buttonController.enable();
};
TorchController.prototype.propagateFailure = function (isTorchOnExpected, error) {
var errorMessage = isTorchOnExpected ? _strings.Html5QrcodeScannerStrings.torchOnFailedMessage() : _strings.Html5QrcodeScannerStrings.torchOffFailedMessage();
if (error) {
errorMessage += "; Error = " + error;
}
this.onTorchActionFailureCallback(errorMessage);
};
TorchController.prototype.reset = function () {
this.isTorchOn = false;
};
return TorchController;
}();
var TorchButton = function () {
function TorchButton(torchCapability, onTorchActionFailureCallback) {
this.onTorchActionFailureCallback = onTorchActionFailureCallback;
this.torchButton = _base.BaseUiElementFactory.createElement("button", _base.PublicUiElementIdAndClasses.TORCH_BUTTON_ID);
this.torchController = new TorchController(torchCapability, this, onTorchActionFailureCallback);
}
TorchButton.prototype.render = function (parentElement, torchButtonOptions) {
var _this = this;
this.torchButton.innerText = _strings.Html5QrcodeScannerStrings.torchOnButton();
this.torchButton.style.display = torchButtonOptions.display;
this.torchButton.style.marginLeft = torchButtonOptions.marginLeft;
var $this = this;
this.torchButton.addEventListener("click", function (_) {
return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
return [4, $this.torchController.flipState()];
case 1:
_a.sent();
if ($this.torchController.isTorchEnabled()) {
$this.torchButton.classList.remove(_base.PublicUiElementIdAndClasses.TORCH_BUTTON_CLASS_TORCH_OFF);
$this.torchButton.classList.add(_base.PublicUiElementIdAndClasses.TORCH_BUTTON_CLASS_TORCH_ON);
} else {
$this.torchButton.classList.remove(_base.PublicUiElementIdAndClasses.TORCH_BUTTON_CLASS_TORCH_ON);
$this.torchButton.classList.add(_base.PublicUiElementIdAndClasses.TORCH_BUTTON_CLASS_TORCH_OFF);
}
return [2];
}
});
});
});
parentElement.appendChild(this.torchButton);
};
TorchButton.prototype.updateTorchCapability = function (torchCapability) {
this.torchController = new TorchController(torchCapability, this, this.onTorchActionFailureCallback);
};
TorchButton.prototype.getTorchButton = function () {
return this.torchButton;
};
TorchButton.prototype.hide = function () {
this.torchButton.style.display = "none";
};
TorchButton.prototype.show = function () {
this.torchButton.style.display = "inline-block";
};
TorchButton.prototype.disable = function () {
this.torchButton.disabled = true;
};
TorchButton.prototype.enable = function () {
this.torchButton.disabled = false;
};
TorchButton.prototype.setText = function (text) {
this.torchButton.innerText = text;
};
TorchButton.prototype.reset = function () {
this.torchButton.innerText = _strings.Html5QrcodeScannerStrings.torchOnButton();
this.torchController.reset();
};
TorchButton.create = function (parentElement, torchCapability, torchButtonOptions, onTorchActionFailureCallback) {
var button = new TorchButton(torchCapability, onTorchActionFailureCallback);
button.render(parentElement, torchButtonOptions);
return button;
};
return TorchButton;
}();
exports.TorchButton = TorchButton;
/***/ }),
/* 88 */
/*!*******************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/ui/scanner/base.js ***!
\*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PublicUiElementIdAndClasses = exports.BaseUiElementFactory = void 0;
var PublicUiElementIdAndClasses = function () {
function PublicUiElementIdAndClasses() {}
PublicUiElementIdAndClasses.ALL_ELEMENT_CLASS = "html5-qrcode-element";
PublicUiElementIdAndClasses.CAMERA_PERMISSION_BUTTON_ID = "html5-qrcode-button-camera-permission";
PublicUiElementIdAndClasses.CAMERA_START_BUTTON_ID = "html5-qrcode-button-camera-start";
PublicUiElementIdAndClasses.CAMERA_STOP_BUTTON_ID = "html5-qrcode-button-camera-stop";
PublicUiElementIdAndClasses.TORCH_BUTTON_ID = "html5-qrcode-button-torch";
PublicUiElementIdAndClasses.CAMERA_SELECTION_SELECT_ID = "html5-qrcode-select-camera";
PublicUiElementIdAndClasses.FILE_SELECTION_BUTTON_ID = "html5-qrcode-button-file-selection";
PublicUiElementIdAndClasses.ZOOM_SLIDER_ID = "html5-qrcode-input-range-zoom";
PublicUiElementIdAndClasses.SCAN_TYPE_CHANGE_ANCHOR_ID = "html5-qrcode-anchor-scan-type-change";
PublicUiElementIdAndClasses.TORCH_BUTTON_CLASS_TORCH_ON = "html5-qrcode-button-torch-on";
PublicUiElementIdAndClasses.TORCH_BUTTON_CLASS_TORCH_OFF = "html5-qrcode-button-torch-off";
return PublicUiElementIdAndClasses;
}();
exports.PublicUiElementIdAndClasses = PublicUiElementIdAndClasses;
var BaseUiElementFactory = function () {
function BaseUiElementFactory() {}
BaseUiElementFactory.createElement = function (elementType, elementId) {
var element = document.createElement(elementType);
element.id = elementId;
element.classList.add(PublicUiElementIdAndClasses.ALL_ELEMENT_CLASS);
if (elementType === "button") {
element.setAttribute("type", "button");
}
return element;
};
return BaseUiElementFactory;
}();
exports.BaseUiElementFactory = BaseUiElementFactory;
/***/ }),
/* 89 */
/*!********************************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/ui/scanner/file-selection-ui.js ***!
\********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.FileSelectionUi = void 0;
var _strings = __webpack_require__(/*! ../../strings */ 63);
var _base = __webpack_require__(/*! ./base */ 88);
var FileSelectionUi = function () {
function FileSelectionUi(parentElement, showOnRender, onFileSelected) {
this.fileBasedScanRegion = this.createFileBasedScanRegion();
this.fileBasedScanRegion.style.display = showOnRender ? "block" : "none";
parentElement.appendChild(this.fileBasedScanRegion);
var fileScanLabel = document.createElement("label");
fileScanLabel.setAttribute("for", this.getFileScanInputId());
fileScanLabel.style.display = "inline-block";
this.fileBasedScanRegion.appendChild(fileScanLabel);
this.fileSelectionButton = _base.BaseUiElementFactory.createElement("button", _base.PublicUiElementIdAndClasses.FILE_SELECTION_BUTTON_ID);
this.setInitialValueToButton();
this.fileSelectionButton.addEventListener("click", function (_) {
fileScanLabel.click();
});
fileScanLabel.append(this.fileSelectionButton);
this.fileScanInput = _base.BaseUiElementFactory.createElement("input", this.getFileScanInputId());
this.fileScanInput.type = "file";
this.fileScanInput.accept = "image/*";
this.fileScanInput.style.display = "none";
fileScanLabel.appendChild(this.fileScanInput);
var $this = this;
this.fileScanInput.addEventListener("change", function (e) {
if (e == null || e.target == null) {
return;
}
var target = e.target;
if (target.files && target.files.length === 0) {
return;
}
var fileList = target.files;
var file = fileList[0];
var fileName = file.name;
$this.setImageNameToButton(fileName);
onFileSelected(file);
});
var dragAndDropMessage = this.createDragAndDropMessage();
this.fileBasedScanRegion.appendChild(dragAndDropMessage);
this.fileBasedScanRegion.addEventListener("dragenter", function (event) {
$this.fileBasedScanRegion.style.border = $this.fileBasedScanRegionActiveBorder();
event.stopPropagation();
event.preventDefault();
});
this.fileBasedScanRegion.addEventListener("dragleave", function (event) {
$this.fileBasedScanRegion.style.border = $this.fileBasedScanRegionDefaultBorder();
event.stopPropagation();
event.preventDefault();
});
this.fileBasedScanRegion.addEventListener("dragover", function (event) {
$this.fileBasedScanRegion.style.border = $this.fileBasedScanRegionActiveBorder();
event.stopPropagation();
event.preventDefault();
});
this.fileBasedScanRegion.addEventListener("drop", function (event) {
event.stopPropagation();
event.preventDefault();
$this.fileBasedScanRegion.style.border = $this.fileBasedScanRegionDefaultBorder();
var dataTransfer = event.dataTransfer;
if (dataTransfer) {
var files = dataTransfer.files;
if (!files || files.length === 0) {
return;
}
var isAnyFileImage = false;
for (var i = 0; i < files.length; ++i) {
var file = files.item(i);
if (!file) {
continue;
}
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
isAnyFileImage = true;
var fileName = file.name;
$this.setImageNameToButton(fileName);
onFileSelected(file);
dragAndDropMessage.innerText = _strings.Html5QrcodeScannerStrings.dragAndDropMessage();
break;
}
if (!isAnyFileImage) {
dragAndDropMessage.innerText = _strings.Html5QrcodeScannerStrings.dragAndDropMessageOnlyImages();
}
}
});
}
FileSelectionUi.prototype.hide = function () {
this.fileBasedScanRegion.style.display = "none";
this.fileScanInput.disabled = true;
};
FileSelectionUi.prototype.show = function () {
this.fileBasedScanRegion.style.display = "block";
this.fileScanInput.disabled = false;
};
FileSelectionUi.prototype.isShowing = function () {
return this.fileBasedScanRegion.style.display === "block";
};
FileSelectionUi.prototype.resetValue = function () {
this.fileScanInput.value = "";
this.setInitialValueToButton();
};
FileSelectionUi.prototype.createFileBasedScanRegion = function () {
var fileBasedScanRegion = document.createElement("div");
fileBasedScanRegion.style.textAlign = "center";
fileBasedScanRegion.style.margin = "auto";
fileBasedScanRegion.style.width = "80%";
fileBasedScanRegion.style.maxWidth = "600px";
fileBasedScanRegion.style.border = this.fileBasedScanRegionDefaultBorder();
fileBasedScanRegion.style.padding = "10px";
fileBasedScanRegion.style.marginBottom = "10px";
return fileBasedScanRegion;
};
FileSelectionUi.prototype.fileBasedScanRegionDefaultBorder = function () {
return "6px dashed #ebebeb";
};
FileSelectionUi.prototype.fileBasedScanRegionActiveBorder = function () {
return "6px dashed rgb(153 151 151)";
};
FileSelectionUi.prototype.createDragAndDropMessage = function () {
var dragAndDropMessage = document.createElement("div");
dragAndDropMessage.innerText = _strings.Html5QrcodeScannerStrings.dragAndDropMessage();
dragAndDropMessage.style.fontWeight = "400";
return dragAndDropMessage;
};
FileSelectionUi.prototype.setImageNameToButton = function (imageFileName) {
var MAX_CHARS = 20;
if (imageFileName.length > MAX_CHARS) {
var start8Chars = imageFileName.substring(0, 8);
var length_1 = imageFileName.length;
var last8Chars = imageFileName.substring(length_1 - 8, length_1);
imageFileName = "".concat(start8Chars, "....").concat(last8Chars);
}
var newText = _strings.Html5QrcodeScannerStrings.fileSelectionChooseAnother() + " - " + imageFileName;
this.fileSelectionButton.innerText = newText;
};
FileSelectionUi.prototype.setInitialValueToButton = function () {
var initialText = _strings.Html5QrcodeScannerStrings.fileSelectionChooseImage() + " - " + _strings.Html5QrcodeScannerStrings.fileSelectionNoImageSelected();
this.fileSelectionButton.innerText = initialText;
};
FileSelectionUi.prototype.getFileScanInputId = function () {
return "html5-qrcode-private-filescan-input";
};
FileSelectionUi.create = function (parentElement, showOnRender, onFileSelected) {
var button = new FileSelectionUi(parentElement, showOnRender, onFileSelected);
return button;
};
return FileSelectionUi;
}();
exports.FileSelectionUi = FileSelectionUi;
/***/ }),
/* 90 */
/*!**********************************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/ui/scanner/camera-selection-ui.js ***!
\**********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CameraSelectionUi = void 0;
var _base = __webpack_require__(/*! ./base */ 88);
var _strings = __webpack_require__(/*! ../../strings */ 63);
var CameraSelectionUi = function () {
function CameraSelectionUi(cameras) {
this.selectElement = _base.BaseUiElementFactory.createElement("select", _base.PublicUiElementIdAndClasses.CAMERA_SELECTION_SELECT_ID);
this.cameras = cameras;
this.options = [];
}
CameraSelectionUi.prototype.render = function (parentElement) {
var cameraSelectionContainer = document.createElement("span");
cameraSelectionContainer.style.marginRight = "10px";
var numCameras = this.cameras.length;
if (numCameras === 0) {
throw new Error("No cameras found");
}
if (numCameras === 1) {
cameraSelectionContainer.style.display = "none";
} else {
var selectCameraString = _strings.Html5QrcodeScannerStrings.selectCamera();
cameraSelectionContainer.innerText = "".concat(selectCameraString, " (").concat(this.cameras.length, ") ");
}
var anonymousCameraId = 1;
for (var _i = 0, _a = this.cameras; _i < _a.length; _i++) {
var camera = _a[_i];
var value = camera.id;
var name_1 = camera.label == null ? value : camera.label;
if (!name_1 || name_1 === "") {
name_1 = [_strings.Html5QrcodeScannerStrings.anonymousCameraPrefix(), anonymousCameraId++].join(" ");
}
var option = document.createElement("option");
option.value = value;
option.innerText = name_1;
this.options.push(option);
this.selectElement.appendChild(option);
}
cameraSelectionContainer.appendChild(this.selectElement);
parentElement.appendChild(cameraSelectionContainer);
};
CameraSelectionUi.prototype.disable = function () {
this.selectElement.disabled = true;
};
CameraSelectionUi.prototype.isDisabled = function () {
return this.selectElement.disabled === true;
};
CameraSelectionUi.prototype.enable = function () {
this.selectElement.disabled = false;
};
CameraSelectionUi.prototype.getValue = function () {
return this.selectElement.value;
};
CameraSelectionUi.prototype.hasValue = function (value) {
for (var _i = 0, _a = this.options; _i < _a.length; _i++) {
var option = _a[_i];
if (option.value === value) {
return true;
}
}
return false;
};
CameraSelectionUi.prototype.setValue = function (value) {
if (!this.hasValue(value)) {
throw new Error("".concat(value, " is not present in the camera list."));
}
this.selectElement.value = value;
};
CameraSelectionUi.prototype.hasSingleItem = function () {
return this.cameras.length === 1;
};
CameraSelectionUi.prototype.numCameras = function () {
return this.cameras.length;
};
CameraSelectionUi.create = function (parentElement, cameras) {
var cameraSelectUi = new CameraSelectionUi(cameras);
cameraSelectUi.render(parentElement);
return cameraSelectUi;
};
return CameraSelectionUi;
}();
exports.CameraSelectionUi = CameraSelectionUi;
/***/ }),
/* 91 */
/*!*****************************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/node_modules/html5-qrcode/esm/ui/scanner/camera-zoom-ui.js ***!
\*****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CameraZoomUi = void 0;
var _base = __webpack_require__(/*! ./base */ 88);
var _strings = __webpack_require__(/*! ../../strings */ 63);
var CameraZoomUi = function () {
function CameraZoomUi() {
this.onChangeCallback = null;
this.zoomElementContainer = document.createElement("div");
this.rangeInput = _base.BaseUiElementFactory.createElement("input", _base.PublicUiElementIdAndClasses.ZOOM_SLIDER_ID);
this.rangeInput.type = "range";
this.rangeText = document.createElement("span");
this.rangeInput.min = "1";
this.rangeInput.max = "5";
this.rangeInput.value = "1";
this.rangeInput.step = "0.1";
}
CameraZoomUi.prototype.render = function (parentElement, renderOnCreate) {
this.zoomElementContainer.style.display = renderOnCreate ? "block" : "none";
this.zoomElementContainer.style.padding = "5px 10px";
this.zoomElementContainer.style.textAlign = "center";
parentElement.appendChild(this.zoomElementContainer);
this.rangeInput.style.display = "inline-block";
this.rangeInput.style.width = "50%";
this.rangeInput.style.height = "5px";
this.rangeInput.style.background = "#d3d3d3";
this.rangeInput.style.outline = "none";
this.rangeInput.style.opacity = "0.7";
var zoomString = _strings.Html5QrcodeScannerStrings.zoom();
this.rangeText.innerText = "".concat(this.rangeInput.value, "x ").concat(zoomString);
this.rangeText.style.marginRight = "10px";
var $this = this;
this.rangeInput.addEventListener("input", function () {
return $this.onValueChange();
});
this.rangeInput.addEventListener("change", function () {
return $this.onValueChange();
});
this.zoomElementContainer.appendChild(this.rangeInput);
this.zoomElementContainer.appendChild(this.rangeText);
};
CameraZoomUi.prototype.onValueChange = function () {
var zoomString = _strings.Html5QrcodeScannerStrings.zoom();
this.rangeText.innerText = "".concat(this.rangeInput.value, "x ").concat(zoomString);
if (this.onChangeCallback) {
this.onChangeCallback(parseFloat(this.rangeInput.value));
}
};
CameraZoomUi.prototype.setValues = function (minValue, maxValue, defaultValue, step) {
this.rangeInput.min = minValue.toString();
this.rangeInput.max = maxValue.toString();
this.rangeInput.step = step.toString();
this.rangeInput.value = defaultValue.toString();
this.onValueChange();
};
CameraZoomUi.prototype.show = function () {
this.zoomElementContainer.style.display = "block";
};
CameraZoomUi.prototype.hide = function () {
this.zoomElementContainer.style.display = "none";
};
CameraZoomUi.prototype.setOnCameraZoomValueChangeCallback = function (onChangeCallback) {
this.onChangeCallback = onChangeCallback;
};
CameraZoomUi.prototype.removeOnCameraZoomValueChangeCallback = function () {
this.onChangeCallback = null;
};
CameraZoomUi.create = function (parentElement, renderOnCreate) {
var cameraZoomUi = new CameraZoomUi();
cameraZoomUi.render(parentElement, renderOnCreate);
return cameraZoomUi;
};
return CameraZoomUi;
}();
exports.CameraZoomUi = CameraZoomUi;
/***/ }),
/* 92 */,
/* 93 */,
/* 94 */,
/* 95 */,
/* 96 */,
/* 97 */,
/* 98 */,
/* 99 */,
/* 100 */,
/* 101 */,
/* 102 */,
/* 103 */,
/* 104 */,
/* 105 */,
/* 106 */,
/* 107 */,
/* 108 */,
/* 109 */,
/* 110 */,
/* 111 */,
/* 112 */,
/* 113 */,
/* 114 */,
/* 115 */,
/* 116 */,
/* 117 */,
/* 118 */,
/* 119 */,
/* 120 */,
/* 121 */,
/* 122 */,
/* 123 */,
/* 124 */,
/* 125 */,
/* 126 */,
/* 127 */,
/* 128 */,
/* 129 */,
/* 130 */,
/* 131 */,
/* 132 */,
/* 133 */,
/* 134 */,
/* 135 */,
/* 136 */,
/* 137 */,
/* 138 */
/*!******************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/static/js/mmmm-image-tools/index.js ***!
\******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(wx) {
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ 4);
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.base64ToPath = base64ToPath;
exports.pathToBase64 = pathToBase64;
var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ 13));
function getLocalFilePath(path) {
if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf('_downloads') === 0) {
return path;
}
if (path.indexOf('file://') === 0) {
return path;
}
if (path.indexOf('/storage/emulated/0/') === 0) {
return path;
}
if (path.indexOf('/') === 0) {
var localFilePath = plus.io.convertAbsoluteFileSystem(path);
if (localFilePath !== path) {
return localFilePath;
} else {
path = path.substr(1);
}
}
return '_www/' + path;
}
function dataUrlToBase64(str) {
var array = str.split(',');
return array[array.length - 1];
}
var index = 0;
function getNewFileId() {
return Date.now() + String(index++);
}
function biggerThan(v1, v2) {
var v1Array = v1.split('.');
var v2Array = v2.split('.');
var update = false;
for (var index = 0; index < v2Array.length; index++) {
var diff = v1Array[index] - v2Array[index];
if (diff !== 0) {
update = diff > 0;
break;
}
}
return update;
}
function pathToBase64(path) {
return new Promise(function (resolve, reject) {
if ((typeof window === "undefined" ? "undefined" : (0, _typeof2.default)(window)) === 'object' && 'document' in window) {
if (typeof FileReader === 'function') {
var xhr = new XMLHttpRequest();
xhr.open('GET', path, true);
xhr.responseType = 'blob';
xhr.onload = function () {
if (this.status === 200) {
var fileReader = new FileReader();
fileReader.onload = function (e) {
resolve(e.target.result);
};
fileReader.onerror = reject;
fileReader.readAsDataURL(this.response);
}
};
xhr.onerror = reject;
xhr.send();
return;
}
var canvas = document.createElement('canvas');
var c2x = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
c2x.drawImage(img, 0, 0);
resolve(canvas.toDataURL());
canvas.height = canvas.width = 0;
};
img.onerror = reject;
img.src = path;
return;
}
if ((typeof plus === "undefined" ? "undefined" : (0, _typeof2.default)(plus)) === 'object') {
plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function (entry) {
entry.file(function (file) {
var fileReader = new plus.io.FileReader();
fileReader.onload = function (data) {
resolve(data.target.result);
};
fileReader.onerror = function (error) {
reject(error);
};
fileReader.readAsDataURL(file);
}, function (error) {
reject(error);
});
}, function (error) {
reject(error);
});
return;
}
if ((typeof wx === "undefined" ? "undefined" : (0, _typeof2.default)(wx)) === 'object' && wx.canIUse('getFileSystemManager')) {
wx.getFileSystemManager().readFile({
filePath: path,
encoding: 'base64',
success: function success(res) {
resolve('data:image/png;base64,' + res.data);
},
fail: function fail(error) {
reject(error);
}
});
return;
}
reject(new Error('not support'));
});
}
function base64ToPath(base64) {
return new Promise(function (resolve, reject) {
if ((typeof window === "undefined" ? "undefined" : (0, _typeof2.default)(window)) === 'object' && 'document' in window) {
base64 = base64.split(',');
var type = base64[0].match(/:(.*?);/)[1];
var str = atob(base64[1]);
var n = str.length;
var array = new Uint8Array(n);
while (n--) {
array[n] = str.charCodeAt(n);
}
return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], {
type: type
})));
}
var extName = base64.split(',')[0].match(/data\:\S+\/(\S+);/);
if (extName) {
extName = extName[1];
} else {
reject(new Error('base64 error'));
}
var fileName = getNewFileId() + '.' + extName;
if ((typeof plus === "undefined" ? "undefined" : (0, _typeof2.default)(plus)) === 'object') {
var basePath = '_doc';
var dirPath = 'uniapp_temp';
var filePath = basePath + '/' + dirPath + '/' + fileName;
if (!biggerThan(plus.os.name === 'Android' ? '1.9.9.80627' : '1.9.9.80472', plus.runtime.innerVersion)) {
plus.io.resolveLocalFileSystemURL(basePath, function (entry) {
entry.getDirectory(dirPath, {
create: true,
exclusive: false
}, function (entry) {
entry.getFile(fileName, {
create: true,
exclusive: false
}, function (entry) {
entry.createWriter(function (writer) {
writer.onwrite = function () {
resolve(filePath);
};
writer.onerror = reject;
writer.seek(0);
writer.writeAsBinary(dataUrlToBase64(base64));
}, reject);
}, reject);
}, reject);
}, reject);
return;
}
var bitmap = new plus.nativeObj.Bitmap(fileName);
bitmap.loadBase64Data(base64, function () {
bitmap.save(filePath, {}, function () {
bitmap.clear();
resolve(filePath);
}, function (error) {
bitmap.clear();
reject(error);
});
}, function (error) {
bitmap.clear();
reject(error);
});
return;
}
if ((typeof wx === "undefined" ? "undefined" : (0, _typeof2.default)(wx)) === 'object' && wx.canIUse('getFileSystemManager')) {
var filePath = wx.env.USER_DATA_PATH + '/' + fileName;
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: dataUrlToBase64(base64),
encoding: 'base64',
success: function success() {
resolve(filePath);
},
fail: function fail(error) {
reject(error);
}
});
return;
}
reject(new Error('not support'));
});
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/wx.js */ 1)["default"]))
/***/ }),
/* 139 */,
/* 140 */,
/* 141 */,
/* 142 */,
/* 143 */,
/* 144 */,
/* 145 */,
/* 146 */,
/* 147 */,
/* 148 */,
/* 149 */,
/* 150 */,
/* 151 */,
/* 152 */,
/* 153 */,
/* 154 */,
/* 155 */,
/* 156 */,
/* 157 */,
/* 158 */,
/* 159 */,
/* 160 */,
/* 161 */,
/* 162 */,
/* 163 */,
/* 164 */,
/* 165 */,
/* 166 */,
/* 167 */,
/* 168 */,
/* 169 */,
/* 170 */,
/* 171 */,
/* 172 */,
/* 173 */,
/* 174 */,
/* 175 */,
/* 176 */,
/* 177 */,
/* 178 */,
/* 179 */
/*!*****************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/asyncToGenerator.js ***!
\*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/* 180 */,
/* 181 */,
/* 182 */,
/* 183 */,
/* 184 */,
/* 185 */,
/* 186 */,
/* 187 */
/*!*************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/static/js/lunar.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.lunar = void 0;
var lunar = {
/**
* 农历1900-2100的润大小信息表
* @Array Of Property
* @return Hex
*/
lunarInfo: [0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,
//1900-1909
0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977,
//1910-1919
0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970,
//1920-1929
0x06566, 0x0d4a0, 0x0ea50, 0x16a95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950,
//1930-1939
0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557,
//1940-1949
0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5b0, 0x14573, 0x052b0, 0x0a9a8, 0x0e950, 0x06aa0,
//1950-1959
0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0,
//1960-1969
0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b6a0, 0x195a6,
//1970-1979
0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570,
//1980-1989
0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x05ac0, 0x0ab60, 0x096d5, 0x092e0,
//1990-1999
0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5,
//2000-2009
0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930,
//2010-2019
0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530,
//2020-2029
0x05aa0, 0x076a3, 0x096d0, 0x04afb, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45,
//2030-2039
0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0,
//2040-2049
/**Add By JJonline@JJonline.Cn**/
0x14b63, 0x09370, 0x049f8, 0x04970, 0x064b0, 0x168a6, 0x0ea50, 0x06b20, 0x1a6c4, 0x0aae0,
//2050-2059
0x092e0, 0x0d2e3, 0x0c960, 0x0d557, 0x0d4a0, 0x0da50, 0x05d55, 0x056a0, 0x0a6d0, 0x055d4,
//2060-2069
0x052d0, 0x0a9b8, 0x0a950, 0x0b4a0, 0x0b6a6, 0x0ad50, 0x055a0, 0x0aba4, 0x0a5b0, 0x052b0,
//2070-2079
0x0b273, 0x06930, 0x07337, 0x06aa0, 0x0ad50, 0x14b55, 0x04b60, 0x0a570, 0x054e4, 0x0d160,
//2080-2089
0x0e968, 0x0d520, 0x0daa0, 0x16aa6, 0x056d0, 0x04ae0, 0x0a9d4, 0x0a2d0, 0x0d150, 0x0f252,
//2090-2099
0x0d520],
//2100
/**
* 公历每个月份的天数普通表
* @Array Of Property
* @return Number
*/
solarMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
/**
* 天干地支之天干速查表
* @Array Of Property trans["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"]
* @return Cn string
*/
Gan: ["\u7532", "\u4E59", "\u4E19", "\u4E01", "\u620A", "\u5DF1", "\u5E9A", "\u8F9B", "\u58EC", "\u7678"],
/**
* 天干地支之地支速查表
* @Array Of Property
* @trans["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"]
* @return Cn string
*/
Zhi: ["\u5B50", "\u4E11", "\u5BC5", "\u536F", "\u8FB0", "\u5DF3", "\u5348", "\u672A", "\u7533", "\u9149", "\u620C", "\u4EA5"],
/**
* 天干地支之地支速查表<=>生肖
* @Array Of Property
* @trans["鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"]
* @return Cn string
*/
Animals: ["\u9F20", "\u725B", "\u864E", "\u5154", "\u9F99", "\u86C7", "\u9A6C", "\u7F8A", "\u7334", "\u9E21", "\u72D7", "\u732A"],
/**
* 阳历节日
*/
festival: {
"1-1": {
title: "元旦"
},
"2-14": {
title: "情人节"
},
"5-1": {
title: "劳动节"
},
"5-4": {
title: "青年节"
},
"6-1": {
title: "儿童节"
},
"9-10": {
title: "教师节"
},
"10-1": {
title: "国庆节"
},
"12-25": {
title: "圣诞节"
},
"3-8": {
title: "妇女节"
},
"3-12": {
title: "植树节"
},
"4-1": {
title: "愚人节"
},
"4-4": {
title: "清明节"
},
"5-12": {
title: "护士节"
},
"7-1": {
title: "建党节"
},
"8-1": {
title: "建军节"
},
"12-24": {
title: "平安夜"
}
},
/**
* 农历节日
*/
lFestival: {
"12-30": {
title: "除夕"
},
"1-1": {
title: "春节"
},
"1-15": {
title: "元宵节"
},
"2-2": {
title: "龙抬头"
},
"5-5": {
title: "端午节"
},
"7-7": {
title: "七夕节"
},
"7-15": {
title: "中元节"
},
"8-15": {
title: "中秋节"
},
"9-9": {
title: "重阳节"
},
"10-1": {
title: "寒衣节"
},
"10-15": {
title: "下元节"
},
"12-8": {
title: "腊八节"
},
"12-23": {
title: "北方小年"
},
"12-24": {
title: "南方小年"
}
},
/**
* 返回默认定义的阳历节日
*/
getFestival: function getFestival() {
return this.festival;
},
/**
* 返回默认定义的内容里节日
*/
getLunarFestival: function getLunarFestival() {
return this.lFestival;
},
/**
*
* @param param {Object} 按照festival的格式输入数据,设置阳历节日
*/
setFestival: function setFestival() {
var param = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.festival = param;
},
/**
*
* @param param {Object} 按照lFestival的格式输入数据,设置农历节日
*/
setLunarFestival: function setLunarFestival() {
var param = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.lFestival = param;
},
/**
* 24节气速查表
* @Array Of Property
* @trans["小寒","大寒","立春","雨水","惊蛰","春分","清明","谷雨","立夏","小满","芒种","夏至","小暑","大暑","立秋","处暑","白露","秋分","寒露","霜降","立冬","小雪","大雪","冬至"]
* @return Cn string
*/
solarTerm: ["\u5C0F\u5BD2", "\u5927\u5BD2", "\u7ACB\u6625", "\u96E8\u6C34", "\u60CA\u86F0", "\u6625\u5206", "\u6E05\u660E", "\u8C37\u96E8", "\u7ACB\u590F", "\u5C0F\u6EE1", "\u8292\u79CD", "\u590F\u81F3", "\u5C0F\u6691", "\u5927\u6691", "\u7ACB\u79CB", "\u5904\u6691", "\u767D\u9732", "\u79CB\u5206", "\u5BD2\u9732", "\u971C\u964D", "\u7ACB\u51AC", "\u5C0F\u96EA", "\u5927\u96EA", "\u51AC\u81F3"],
/**
* 1900-2100各年的24节气日期速查表
* @Array Of Property
* @return 0x string For splice
*/
sTermInfo: ["9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf97c3598082c95f8c965cc920f", "97bd0b06bdb0722c965ce1cfcc920f", "b027097bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf97c359801ec95f8c965cc920f", "97bd0b06bdb0722c965ce1cfcc920f", "b027097bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf97c359801ec95f8c965cc920f", "97bd0b06bdb0722c965ce1cfcc920f", "b027097bd097c36b0b6fc9274c91aa", "9778397bd19801ec9210c965cc920e", "97b6b97bd19801ec95f8c965cc920f", "97bd09801d98082c95f8e1cfcc920f", "97bd097bd097c36b0b6fc9210c8dc2", "9778397bd197c36c9210c9274c91aa", "97b6b97bd19801ec95f8c965cc920e", "97bd09801d98082c95f8e1cfcc920f", "97bd097bd097c36b0b6fc9210c8dc2", "9778397bd097c36c9210c9274c91aa", "97b6b97bd19801ec95f8c965cc920e", "97bcf97c3598082c95f8e1cfcc920f", "97bd097bd097c36b0b6fc9210c8dc2", "9778397bd097c36c9210c9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf97c3598082c95f8c965cc920f", "97bd097bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf97c3598082c95f8c965cc920f", "97bd097bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf97c359801ec95f8c965cc920f", "97bd097bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf97c359801ec95f8c965cc920f", "97bd097bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf97c359801ec95f8c965cc920f", "97bd097bd07f595b0b6fc920fb0722", "9778397bd097c36b0b6fc9210c8dc2", "9778397bd19801ec9210c9274c920e", "97b6b97bd19801ec95f8c965cc920f", "97bd07f5307f595b0b0bc920fb0722", "7f0e397bd097c36b0b6fc9210c8dc2", "9778397bd097c36c9210c9274c920e", "97b6b97bd19801ec95f8c965cc920f", "97bd07f5307f595b0b0bc920fb0722", "7f0e397bd097c36b0b6fc9210c8dc2", "9778397bd097c36c9210c9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bd07f1487f595b0b0bc920fb0722", "7f0e397bd097c36b0b6fc9210c8dc2", "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf7f1487f595b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf7f1487f595b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf7f1487f531b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf7f1487f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c9274c920e", "97bcf7f0e47f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", "9778397bd097c36b0b6fc9210c91aa", "97b6b97bd197c36c9210c9274c920e", "97bcf7f0e47f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", "9778397bd097c36b0b6fc9210c8dc2", "9778397bd097c36c9210c9274c920e", "97b6b7f0e47f531b0723b0b6fb0722", "7f0e37f5307f595b0b0bc920fb0722", "7f0e397bd097c36b0b6fc9210c8dc2", "9778397bd097c36b0b70c9274c91aa", "97b6b7f0e47f531b0723b0b6fb0721", "7f0e37f1487f595b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc9210c8dc2", "9778397bd097c36b0b6fc9274c91aa", "97b6b7f0e47f531b0723b0b6fb0721", "7f0e27f1487f595b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b7f0e47f531b0723b0787b0721", "7f0e27f0e47f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", "9778397bd097c36b0b6fc9210c91aa", "97b6b7f0e47f149b0723b0787b0721", "7f0e27f0e47f531b0723b0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", "9778397bd097c36b0b6fc9210c8dc2", "977837f0e37f149b0723b0787b0721", "7f07e7f0e47f531b0723b0b6fb0722", "7f0e37f5307f595b0b0bc920fb0722", "7f0e397bd097c35b0b6fc9210c8dc2", "977837f0e37f14998082b0787b0721", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e37f1487f595b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc9210c8dc2", "977837f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", "977837f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", "977837f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", "977837f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", "977837f0e37f14998082b0787b06bd", "7f07e7f0e47f149b0723b0787b0721", "7f0e27f0e47f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", "977837f0e37f14998082b0723b06bd", "7f07e7f0e37f149b0723b0787b0721", "7f0e27f0e47f531b0723b0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", "977837f0e37f14898082b0723b02d5", "7ec967f0e37f14998082b0787b0721", "7f07e7f0e47f531b0723b0b6fb0722", "7f0e37f1487f595b0b0bb0b6fb0722", "7f0e37f0e37f14898082b0723b02d5", "7ec967f0e37f14998082b0787b0721", "7f07e7f0e47f531b0723b0b6fb0722", "7f0e37f1487f531b0b0bb0b6fb0722", "7f0e37f0e37f14898082b0723b02d5", "7ec967f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e37f1487f531b0b0bb0b6fb0722", "7f0e37f0e37f14898082b072297c35", "7ec967f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e37f0e37f14898082b072297c35", "7ec967f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e37f0e366aa89801eb072297c35", "7ec967f0e37f14998082b0787b06bd", "7f07e7f0e47f149b0723b0787b0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e37f0e366aa89801eb072297c35", "7ec967f0e37f14998082b0723b06bd", "7f07e7f0e47f149b0723b0787b0721", "7f0e27f0e47f531b0723b0b6fb0722", "7f0e37f0e366aa89801eb072297c35", "7ec967f0e37f14998082b0723b06bd", "7f07e7f0e37f14998083b0787b0721", "7f0e27f0e47f531b0723b0b6fb0722", "7f0e37f0e366aa89801eb072297c35", "7ec967f0e37f14898082b0723b02d5", "7f07e7f0e37f14998082b0787b0721", "7f07e7f0e47f531b0723b0b6fb0722", "7f0e36665b66aa89801e9808297c35", "665f67f0e37f14898082b0723b02d5", "7ec967f0e37f14998082b0787b0721", "7f07e7f0e47f531b0723b0b6fb0722", "7f0e36665b66a449801e9808297c35", "665f67f0e37f14898082b0723b02d5", "7ec967f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e36665b66a449801e9808297c35", "665f67f0e37f14898082b072297c35", "7ec967f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e26665b66a449801e9808297c35", "665f67f0e37f1489801eb072297c35", "7ec967f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722"],
/**
* 数字转中文速查表
* @Array Of Property
* @trans ['日','一','二','三','四','五','六','七','八','九','十']
* @return Cn string
*/
nStr1: ["\u65E5", "\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D", "\u4E03", "\u516B", "\u4E5D", "\u5341"],
/**
* 日期转农历称呼速查表
* @Array Of Property
* @trans ['初','十','廿','卅']
* @return Cn string
*/
nStr2: ["\u521D", "\u5341", "\u5EFF", "\u5345"],
/**
* 月份转农历称呼速查表
* @Array Of Property
* @trans ['正','一','二','三','四','五','六','七','八','九','十','冬','腊']
* @return Cn string
*/
nStr3: ["\u6B63", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D", "\u4E03", "\u516B", "\u4E5D", "\u5341", "\u51AC", "\u814A"],
/**
* 返回农历y年一整年的总天数
* @param y lunar Year
* @return Number
* @eg:var count = calendar.lYearDays(1987) ;//count=387
*/
lYearDays: function lYearDays(y) {
var i,
sum = 348;
for (i = 0x8000; i > 0x8; i >>= 1) {
sum += this.lunarInfo[y - 1900] & i ? 1 : 0;
}
return sum + this.leapDays(y);
},
/**
* 返回农历y年闰月是哪个月;若y年没有闰月 则返回0
* @param y lunar Year
* @return Number (0-12)
* @eg:var leapMonth = calendar.leapMonth(1987) ;//leapMonth=6
*/
leapMonth: function leapMonth(y) {
//闰字编码 \u95f0
return this.lunarInfo[y - 1900] & 0xf;
},
/**
* 返回农历y年闰月的天数 若该年没有闰月则返回0
* @param y lunar Year
* @return Number (0、29、30)
* @eg:var leapMonthDay = calendar.leapDays(1987) ;//leapMonthDay=29
*/
leapDays: function leapDays(y) {
if (this.leapMonth(y)) {
return this.lunarInfo[y - 1900] & 0x10000 ? 30 : 29;
}
return 0;
},
/**
* 返回农历y年m月(非闰月)的总天数,计算m为闰月时的天数请使用leapDays方法
* @param y lunar Year
* @param m lunar Month
* @return Number (-1、29、30)
* @eg:var MonthDay = calendar.monthDays(1987,9) ;//MonthDay=29
*/
monthDays: function monthDays(y, m) {
if (m > 12 || m < 1) {
return -1;
} //月份参数从1至12,参数错误返回-1
return this.lunarInfo[y - 1900] & 0x10000 >> m ? 30 : 29;
},
/**
* 返回公历(!)y年m月的天数
* @param y solar Year
* @param m solar Month
* @return Number (-1、28、29、30、31)
* @eg:var solarMonthDay = calendar.leapDays(1987) ;//solarMonthDay=30
*/
solarDays: function solarDays(y, m) {
if (m > 12 || m < 1) {
return -1;
} //若参数错误 返回-1
var ms = m - 1;
if (ms === 1) {
//2月份的闰平规律测算后确认返回28或29
return y % 4 === 0 && y % 100 !== 0 || y % 400 === 0 ? 29 : 28;
} else {
return this.solarMonth[ms];
}
},
/**
* 农历年份转换为干支纪年
* @param lYear 农历年的年份数
* @return Cn string
*/
toGanZhiYear: function toGanZhiYear(lYear) {
var ganKey = (lYear - 3) % 10;
var zhiKey = (lYear - 3) % 12;
if (ganKey === 0) ganKey = 10; //如果余数为0则为最后一个天干
if (zhiKey === 0) zhiKey = 12; //如果余数为0则为最后一个地支
return this.Gan[ganKey - 1] + this.Zhi[zhiKey - 1];
},
/**
* 公历月、日判断所属星座
* @param cMonth [description]
* @param cDay [description]
* @return Cn string
*/
toAstro: function toAstro(cMonth, cDay) {
var s = "\u9B54\u7FAF\u6C34\u74F6\u53CC\u9C7C\u767D\u7F8A\u91D1\u725B\u53CC\u5B50\u5DE8\u87F9\u72EE\u5B50\u5904\u5973\u5929\u79E4\u5929\u874E\u5C04\u624B\u9B54\u7FAF";
var arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22];
return s.substr(cMonth * 2 - (cDay < arr[cMonth - 1] ? 2 : 0), 2) + "\u5EA7"; //座
},
/**
* 传入offset偏移量返回干支
* @param offset 相对甲子的偏移量
* @return Cn string
*/
toGanZhi: function toGanZhi(offset) {
return this.Gan[offset % 10] + this.Zhi[offset % 12];
},
/**
* 传入公历(!)y年获得该年第n个节气的公历日期
* @param y y公历年(1900-2100)
* @param n n二十四节气中的第几个节气(1~24);从n=1(小寒)算起
* @return day Number
* @eg:var _24 = calendar.getTerm(1987,3) ;//_24=4;意即1987年2月4日立春
*/
getTerm: function getTerm(y, n) {
if (y < 1900 || y > 2100 || n < 1 || n > 24) {
return -1;
}
var _table = this.sTermInfo[y - 1900];
var _calcDay = [];
for (var index = 0; index < _table.length; index += 5) {
var chunk = parseInt("0x" + _table.substr(index, 5)).toString();
_calcDay.push(chunk[0], chunk.substr(1, 2), chunk[3], chunk.substr(4, 2));
}
return parseInt(_calcDay[n - 1]);
},
/**
* 传入农历数字月份返回汉语通俗表示法
* @param m lunar month
* @return Cn string
* @eg:var cnMonth = calendar.toChinaMonth(12) ;//cnMonth='腊月'
*/
toChinaMonth: function toChinaMonth(m) {
// 月 => \u6708
if (m > 12 || m < 1) {
return -1;
} //若参数错误 返回-1
var s = this.nStr3[m - 1];
s += "\u6708"; //加上月字
return s;
},
/**
* 传入农历日期数字返回汉字表示法
* @param d lunar day
* @return Cn string
* @eg:var cnDay = calendar.toChinaDay(21) ;//cnMonth='廿一'
*/
toChinaDay: function toChinaDay(d) {
//日 => \u65e5
var s;
switch (d) {
case 10:
s = "\u521D\u5341";
break;
case 20:
s = "\u4E8C\u5341";
break;
case 30:
s = "\u4E09\u5341";
break;
default:
s = this.nStr2[Math.floor(d / 10)];
s += this.nStr1[d % 10];
}
return s;
},
/**
* 年份转生肖[!仅能大致转换] => 精确划分生肖分界线是“立春”
* @param y year
* @return Cn string
* @eg:var animal = calendar.getAnimal(1987) ;//animal='兔'
*/
getAnimal: function getAnimal(y) {
return this.Animals[(y - 4) % 12];
},
/**
* 传入阳历年月日获得详细的公历、农历object信息 <=>JSON
* !important! 公历参数区间1900.1.31~2100.12.31
* @param yPara solar year
* @param mPara solar month
* @param dPara solar day
* @return JSON object
* @eg:console.log(calendar.solar2lunar(1987,11,01));
*/
solar2lunar: function solar2lunar(yPara, mPara, dPara) {
var y = parseInt(yPara);
var m = parseInt(mPara);
var d = parseInt(dPara);
//年份限定、上限
if (y < 1900 || y > 2100) {
return -1; // undefined转换为数字变为NaN
}
//公历传参最下限
if (y === 1900 && m === 1 && d < 31) {
return -1;
}
//未传参 获得当天
var objDate;
if (!y) {
objDate = new Date();
} else {
objDate = new Date(y, parseInt(m) - 1, d);
}
var i,
leap = 0,
temp = 0;
//修正ymd参数
y = objDate.getFullYear();
m = objDate.getMonth() + 1;
d = objDate.getDate();
var offset = (Date.UTC(objDate.getFullYear(), objDate.getMonth(), objDate.getDate()) - Date.UTC(1900, 0, 31)) / 86400000;
for (i = 1900; i < 2101 && offset > 0; i++) {
temp = this.lYearDays(i);
offset -= temp;
}
if (offset < 0) {
offset += temp;
i--;
}
//是否今天
var isTodayObj = new Date(),
isToday = false;
if (isTodayObj.getFullYear() === y && isTodayObj.getMonth() + 1 === m && isTodayObj.getDate() === d) {
isToday = true;
}
//星期几
var nWeek = objDate.getDay(),
cWeek = this.nStr1[nWeek];
//数字表示周几顺应天朝周一开始的惯例
if (nWeek === 0) {
nWeek = 7;
}
//农历年
var year = i;
leap = this.leapMonth(i); //闰哪个月
var isLeap = false;
//效验闰月
for (i = 1; i < 13 && offset > 0; i++) {
//闰月
if (leap > 0 && i === leap + 1 && isLeap === false) {
--i;
isLeap = true;
temp = this.leapDays(year); //计算农历闰月天数
} else {
temp = this.monthDays(year, i); //计算农历普通月天数
}
//解除闰月
if (isLeap === true && i === leap + 1) {
isLeap = false;
}
offset -= temp;
}
// 闰月导致数组下标重叠取反
if (offset === 0 && leap > 0 && i === leap + 1) {
if (isLeap) {
isLeap = false;
} else {
isLeap = true;
--i;
}
}
if (offset < 0) {
offset += temp;
--i;
}
//农历月
var month = i;
//农历日
var day = offset + 1;
//天干地支处理
var sm = m - 1;
var gzY = this.toGanZhiYear(year);
// 当月的两个节气
// bugfix-2017-7-24 11:03:38 use lunar Year Param `y` Not `year`
var firstNode = this.getTerm(y, m * 2 - 1); //返回当月「节」为几日开始
var secondNode = this.getTerm(y, m * 2); //返回当月「节」为几日开始
// 依据12节气修正干支月
var gzM = this.toGanZhi((y - 1900) * 12 + m + 11);
if (d >= firstNode) {
gzM = this.toGanZhi((y - 1900) * 12 + m + 12);
}
//传入的日期的节气与否
var isTerm = false;
var Term = null;
if (firstNode === d) {
isTerm = true;
Term = this.solarTerm[m * 2 - 2];
}
if (secondNode === d) {
isTerm = true;
Term = this.solarTerm[m * 2 - 1];
}
//日柱 当月一日与 1900/1/1 相差天数
var dayCyclical = Date.UTC(y, sm, 1, 0, 0, 0, 0) / 86400000 + 25567 + 10;
var gzD = this.toGanZhi(dayCyclical + d - 1);
//该日期所属的星座
var astro = this.toAstro(m, d);
var solarDate = y + "-" + m + "-" + d;
var lunarDate = year + "-" + month + "-" + day;
var festival = this.festival;
var lFestival = this.lFestival;
var festivalDate = m + "-" + d;
var lunarFestivalDate = month + "-" + day;
// bugfix https://github.com/jjonline/calendar.js/issues/29
// 农历节日修正:农历12月小月则29号除夕,大月则30号除夕
// 此处取巧修正:当前为农历12月29号时增加一次判断并且把lunarFestivalDate设置为12-30以正确取得除夕
// 天朝农历节日遇闰月过前不过后的原则,此处取农历12月天数不考虑闰月
// 农历润12月在本工具支持的200年区间内仅1574年出现
if (month === 12 && day === 29 && this.monthDays(year, month) === 29) {
lunarFestivalDate = "12-30";
}
return {
date: solarDate,
lunarDate: lunarDate,
festival: festival[festivalDate] ? festival[festivalDate].title : null,
lunarFestival: lFestival[lunarFestivalDate] ? lFestival[lunarFestivalDate].title : null,
lYear: year,
lMonth: month,
lDay: day,
Animal: this.getAnimal(year),
IMonthCn: (isLeap ? "\u95F0" : "") + this.toChinaMonth(month),
IDayCn: this.toChinaDay(day),
cYear: y,
cMonth: m,
cDay: d,
gzYear: gzY,
gzMonth: gzM,
gzDay: gzD,
isToday: isToday,
isLeap: isLeap,
nWeek: nWeek,
ncWeek: "\u661F\u671F" + cWeek,
isTerm: isTerm,
Term: Term,
astro: astro
};
},
/**
* 传入农历年月日以及传入的月份是否闰月获得详细的公历、农历object信息 <=>JSON
* !important! 参数区间1900.1.31~2100.12.1
* @param y lunar year
* @param m lunar month
* @param d lunar day
* @param isLeapMonth lunar month is leap or not.[如果是农历闰月第四个参数赋值true即可]
* @return JSON object
* @eg:console.log(calendar.lunar2solar(1987,9,10));
*/
lunar2solar: function lunar2solar(y, m, d, isLeapMonth) {
y = parseInt(y);
m = parseInt(m);
d = parseInt(d);
isLeapMonth = !!isLeapMonth;
var leapOffset = 0;
var leapMonth = this.leapMonth(y);
var leapDay = this.leapDays(y);
if (isLeapMonth && leapMonth !== m) {
return -1;
} //传参要求计算该闰月公历 但该年得出的闰月与传参的月份并不同
if (y === 2100 && m === 12 && d > 1 || y === 1900 && m === 1 && d < 31) {
return -1;
} //超出了最大极限值
var day = this.monthDays(y, m);
var _day = day;
//bugFix 2016-9-25
//if month is leap, _day use leapDays method
if (isLeapMonth) {
_day = this.leapDays(y, m);
}
if (y < 1900 || y > 2100 || d > _day) {
return -1;
} //参数合法性效验
//计算农历的时间差
var offset = 0;
var i;
for (i = 1900; i < y; i++) {
offset += this.lYearDays(i);
}
var leap = 0,
isAdd = false;
for (i = 1; i < m; i++) {
leap = this.leapMonth(y);
if (!isAdd) {
//处理闰月
if (leap <= i && leap > 0) {
offset += this.leapDays(y);
isAdd = true;
}
}
offset += this.monthDays(y, i);
}
//转换闰月农历 需补充该年闰月的前一个月的时差
if (isLeapMonth) {
offset += day;
}
//1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点)
var strap = Date.UTC(1900, 1, 30, 0, 0, 0);
var calObj = new Date((offset + d - 31) * 86400000 + strap);
var cY = calObj.getUTCFullYear();
var cM = calObj.getUTCMonth() + 1;
var cD = calObj.getUTCDate();
return this.solar2lunar(cY, cM, cD);
}
};
exports.lunar = lunar;
/***/ }),
/* 188 */,
/* 189 */,
/* 190 */,
/* 191 */,
/* 192 */,
/* 193 */,
/* 194 */,
/* 195 */,
/* 196 */,
/* 197 */,
/* 198 */,
/* 199 */,
/* 200 */,
/* 201 */,
/* 202 */
/*!**********************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/uni_modules/uni-icons/components/uni-icons/icons.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = {
"id": "2852637",
"name": "uniui图标库",
"font_family": "uniicons",
"css_prefix_text": "uniui-",
"description": "",
"glyphs": [{
"icon_id": "25027049",
"name": "yanse",
"font_class": "color",
"unicode": "e6cf",
"unicode_decimal": 59087
}, {
"icon_id": "25027048",
"name": "wallet",
"font_class": "wallet",
"unicode": "e6b1",
"unicode_decimal": 59057
}, {
"icon_id": "25015720",
"name": "settings-filled",
"font_class": "settings-filled",
"unicode": "e6ce",
"unicode_decimal": 59086
}, {
"icon_id": "25015434",
"name": "shimingrenzheng-filled",
"font_class": "auth-filled",
"unicode": "e6cc",
"unicode_decimal": 59084
}, {
"icon_id": "24934246",
"name": "shop-filled",
"font_class": "shop-filled",
"unicode": "e6cd",
"unicode_decimal": 59085
}, {
"icon_id": "24934159",
"name": "staff-filled-01",
"font_class": "staff-filled",
"unicode": "e6cb",
"unicode_decimal": 59083
}, {
"icon_id": "24932461",
"name": "VIP-filled",
"font_class": "vip-filled",
"unicode": "e6c6",
"unicode_decimal": 59078
}, {
"icon_id": "24932462",
"name": "plus_circle_fill",
"font_class": "plus-filled",
"unicode": "e6c7",
"unicode_decimal": 59079
}, {
"icon_id": "24932463",
"name": "folder_add-filled",
"font_class": "folder-add-filled",
"unicode": "e6c8",
"unicode_decimal": 59080
}, {
"icon_id": "24932464",
"name": "yanse-filled",
"font_class": "color-filled",
"unicode": "e6c9",
"unicode_decimal": 59081
}, {
"icon_id": "24932465",
"name": "tune-filled",
"font_class": "tune-filled",
"unicode": "e6ca",
"unicode_decimal": 59082
}, {
"icon_id": "24932455",
"name": "a-rilidaka-filled",
"font_class": "calendar-filled",
"unicode": "e6c0",
"unicode_decimal": 59072
}, {
"icon_id": "24932456",
"name": "notification-filled",
"font_class": "notification-filled",
"unicode": "e6c1",
"unicode_decimal": 59073
}, {
"icon_id": "24932457",
"name": "wallet-filled",
"font_class": "wallet-filled",
"unicode": "e6c2",
"unicode_decimal": 59074
}, {
"icon_id": "24932458",
"name": "paihangbang-filled",
"font_class": "medal-filled",
"unicode": "e6c3",
"unicode_decimal": 59075
}, {
"icon_id": "24932459",
"name": "gift-filled",
"font_class": "gift-filled",
"unicode": "e6c4",
"unicode_decimal": 59076
}, {
"icon_id": "24932460",
"name": "fire-filled",
"font_class": "fire-filled",
"unicode": "e6c5",
"unicode_decimal": 59077
}, {
"icon_id": "24928001",
"name": "refreshempty",
"font_class": "refreshempty",
"unicode": "e6bf",
"unicode_decimal": 59071
}, {
"icon_id": "24926853",
"name": "location-ellipse",
"font_class": "location-filled",
"unicode": "e6af",
"unicode_decimal": 59055
}, {
"icon_id": "24926735",
"name": "person-filled",
"font_class": "person-filled",
"unicode": "e69d",
"unicode_decimal": 59037
}, {
"icon_id": "24926703",
"name": "personadd-filled",
"font_class": "personadd-filled",
"unicode": "e698",
"unicode_decimal": 59032
}, {
"icon_id": "24923351",
"name": "back",
"font_class": "back",
"unicode": "e6b9",
"unicode_decimal": 59065
}, {
"icon_id": "24923352",
"name": "forward",
"font_class": "forward",
"unicode": "e6ba",
"unicode_decimal": 59066
}, {
"icon_id": "24923353",
"name": "arrowthinright",
"font_class": "arrow-right",
"unicode": "e6bb",
"unicode_decimal": 59067
}, {
"icon_id": "24923353",
"name": "arrowthinright",
"font_class": "arrowthinright",
"unicode": "e6bb",
"unicode_decimal": 59067
}, {
"icon_id": "24923354",
"name": "arrowthinleft",
"font_class": "arrow-left",
"unicode": "e6bc",
"unicode_decimal": 59068
}, {
"icon_id": "24923354",
"name": "arrowthinleft",
"font_class": "arrowthinleft",
"unicode": "e6bc",
"unicode_decimal": 59068
}, {
"icon_id": "24923355",
"name": "arrowthinup",
"font_class": "arrow-up",
"unicode": "e6bd",
"unicode_decimal": 59069
}, {
"icon_id": "24923355",
"name": "arrowthinup",
"font_class": "arrowthinup",
"unicode": "e6bd",
"unicode_decimal": 59069
}, {
"icon_id": "24923356",
"name": "arrowthindown",
"font_class": "arrow-down",
"unicode": "e6be",
"unicode_decimal": 59070
}, {
"icon_id": "24923356",
"name": "arrowthindown",
"font_class": "arrowthindown",
"unicode": "e6be",
"unicode_decimal": 59070
}, {
"icon_id": "24923349",
"name": "arrowdown",
"font_class": "bottom",
"unicode": "e6b8",
"unicode_decimal": 59064
}, {
"icon_id": "24923349",
"name": "arrowdown",
"font_class": "arrowdown",
"unicode": "e6b8",
"unicode_decimal": 59064
}, {
"icon_id": "24923346",
"name": "arrowright",
"font_class": "right",
"unicode": "e6b5",
"unicode_decimal": 59061
}, {
"icon_id": "24923346",
"name": "arrowright",
"font_class": "arrowright",
"unicode": "e6b5",
"unicode_decimal": 59061
}, {
"icon_id": "24923347",
"name": "arrowup",
"font_class": "top",
"unicode": "e6b6",
"unicode_decimal": 59062
}, {
"icon_id": "24923347",
"name": "arrowup",
"font_class": "arrowup",
"unicode": "e6b6",
"unicode_decimal": 59062
}, {
"icon_id": "24923348",
"name": "arrowleft",
"font_class": "left",
"unicode": "e6b7",
"unicode_decimal": 59063
}, {
"icon_id": "24923348",
"name": "arrowleft",
"font_class": "arrowleft",
"unicode": "e6b7",
"unicode_decimal": 59063
}, {
"icon_id": "24923334",
"name": "eye",
"font_class": "eye",
"unicode": "e651",
"unicode_decimal": 58961
}, {
"icon_id": "24923335",
"name": "eye-filled",
"font_class": "eye-filled",
"unicode": "e66a",
"unicode_decimal": 58986
}, {
"icon_id": "24923336",
"name": "eye-slash",
"font_class": "eye-slash",
"unicode": "e6b3",
"unicode_decimal": 59059
}, {
"icon_id": "24923337",
"name": "eye-slash-filled",
"font_class": "eye-slash-filled",
"unicode": "e6b4",
"unicode_decimal": 59060
}, {
"icon_id": "24923305",
"name": "info-filled",
"font_class": "info-filled",
"unicode": "e649",
"unicode_decimal": 58953
}, {
"icon_id": "24923299",
"name": "reload-01",
"font_class": "reload",
"unicode": "e6b2",
"unicode_decimal": 59058
}, {
"icon_id": "24923195",
"name": "mic_slash_fill",
"font_class": "micoff-filled",
"unicode": "e6b0",
"unicode_decimal": 59056
}, {
"icon_id": "24923165",
"name": "map-pin-ellipse",
"font_class": "map-pin-ellipse",
"unicode": "e6ac",
"unicode_decimal": 59052
}, {
"icon_id": "24923166",
"name": "map-pin",
"font_class": "map-pin",
"unicode": "e6ad",
"unicode_decimal": 59053
}, {
"icon_id": "24923167",
"name": "location",
"font_class": "location",
"unicode": "e6ae",
"unicode_decimal": 59054
}, {
"icon_id": "24923064",
"name": "starhalf",
"font_class": "starhalf",
"unicode": "e683",
"unicode_decimal": 59011
}, {
"icon_id": "24923065",
"name": "star",
"font_class": "star",
"unicode": "e688",
"unicode_decimal": 59016
}, {
"icon_id": "24923066",
"name": "star-filled",
"font_class": "star-filled",
"unicode": "e68f",
"unicode_decimal": 59023
}, {
"icon_id": "24899646",
"name": "a-rilidaka",
"font_class": "calendar",
"unicode": "e6a0",
"unicode_decimal": 59040
}, {
"icon_id": "24899647",
"name": "fire",
"font_class": "fire",
"unicode": "e6a1",
"unicode_decimal": 59041
}, {
"icon_id": "24899648",
"name": "paihangbang",
"font_class": "medal",
"unicode": "e6a2",
"unicode_decimal": 59042
}, {
"icon_id": "24899649",
"name": "font",
"font_class": "font",
"unicode": "e6a3",
"unicode_decimal": 59043
}, {
"icon_id": "24899650",
"name": "gift",
"font_class": "gift",
"unicode": "e6a4",
"unicode_decimal": 59044
}, {
"icon_id": "24899651",
"name": "link",
"font_class": "link",
"unicode": "e6a5",
"unicode_decimal": 59045
}, {
"icon_id": "24899652",
"name": "notification",
"font_class": "notification",
"unicode": "e6a6",
"unicode_decimal": 59046
}, {
"icon_id": "24899653",
"name": "staff",
"font_class": "staff",
"unicode": "e6a7",
"unicode_decimal": 59047
}, {
"icon_id": "24899654",
"name": "VIP",
"font_class": "vip",
"unicode": "e6a8",
"unicode_decimal": 59048
}, {
"icon_id": "24899655",
"name": "folder_add",
"font_class": "folder-add",
"unicode": "e6a9",
"unicode_decimal": 59049
}, {
"icon_id": "24899656",
"name": "tune",
"font_class": "tune",
"unicode": "e6aa",
"unicode_decimal": 59050
}, {
"icon_id": "24899657",
"name": "shimingrenzheng",
"font_class": "auth",
"unicode": "e6ab",
"unicode_decimal": 59051
}, {
"icon_id": "24899565",
"name": "person",
"font_class": "person",
"unicode": "e699",
"unicode_decimal": 59033
}, {
"icon_id": "24899566",
"name": "email-filled",
"font_class": "email-filled",
"unicode": "e69a",
"unicode_decimal": 59034
}, {
"icon_id": "24899567",
"name": "phone-filled",
"font_class": "phone-filled",
"unicode": "e69b",
"unicode_decimal": 59035
}, {
"icon_id": "24899568",
"name": "phone",
"font_class": "phone",
"unicode": "e69c",
"unicode_decimal": 59036
}, {
"icon_id": "24899570",
"name": "email",
"font_class": "email",
"unicode": "e69e",
"unicode_decimal": 59038
}, {
"icon_id": "24899571",
"name": "personadd",
"font_class": "personadd",
"unicode": "e69f",
"unicode_decimal": 59039
}, {
"icon_id": "24899558",
"name": "chatboxes-filled",
"font_class": "chatboxes-filled",
"unicode": "e692",
"unicode_decimal": 59026
}, {
"icon_id": "24899559",
"name": "contact",
"font_class": "contact",
"unicode": "e693",
"unicode_decimal": 59027
}, {
"icon_id": "24899560",
"name": "chatbubble-filled",
"font_class": "chatbubble-filled",
"unicode": "e694",
"unicode_decimal": 59028
}, {
"icon_id": "24899561",
"name": "contact-filled",
"font_class": "contact-filled",
"unicode": "e695",
"unicode_decimal": 59029
}, {
"icon_id": "24899562",
"name": "chatboxes",
"font_class": "chatboxes",
"unicode": "e696",
"unicode_decimal": 59030
}, {
"icon_id": "24899563",
"name": "chatbubble",
"font_class": "chatbubble",
"unicode": "e697",
"unicode_decimal": 59031
}, {
"icon_id": "24881290",
"name": "upload-filled",
"font_class": "upload-filled",
"unicode": "e68e",
"unicode_decimal": 59022
}, {
"icon_id": "24881292",
"name": "upload",
"font_class": "upload",
"unicode": "e690",
"unicode_decimal": 59024
}, {
"icon_id": "24881293",
"name": "weixin",
"font_class": "weixin",
"unicode": "e691",
"unicode_decimal": 59025
}, {
"icon_id": "24881274",
"name": "compose",
"font_class": "compose",
"unicode": "e67f",
"unicode_decimal": 59007
}, {
"icon_id": "24881275",
"name": "qq",
"font_class": "qq",
"unicode": "e680",
"unicode_decimal": 59008
}, {
"icon_id": "24881276",
"name": "download-filled",
"font_class": "download-filled",
"unicode": "e681",
"unicode_decimal": 59009
}, {
"icon_id": "24881277",
"name": "pengyouquan",
"font_class": "pyq",
"unicode": "e682",
"unicode_decimal": 59010
}, {
"icon_id": "24881279",
"name": "sound",
"font_class": "sound",
"unicode": "e684",
"unicode_decimal": 59012
}, {
"icon_id": "24881280",
"name": "trash-filled",
"font_class": "trash-filled",
"unicode": "e685",
"unicode_decimal": 59013
}, {
"icon_id": "24881281",
"name": "sound-filled",
"font_class": "sound-filled",
"unicode": "e686",
"unicode_decimal": 59014
}, {
"icon_id": "24881282",
"name": "trash",
"font_class": "trash",
"unicode": "e687",
"unicode_decimal": 59015
}, {
"icon_id": "24881284",
"name": "videocam-filled",
"font_class": "videocam-filled",
"unicode": "e689",
"unicode_decimal": 59017
}, {
"icon_id": "24881285",
"name": "spinner-cycle",
"font_class": "spinner-cycle",
"unicode": "e68a",
"unicode_decimal": 59018
}, {
"icon_id": "24881286",
"name": "weibo",
"font_class": "weibo",
"unicode": "e68b",
"unicode_decimal": 59019
}, {
"icon_id": "24881288",
"name": "videocam",
"font_class": "videocam",
"unicode": "e68c",
"unicode_decimal": 59020
}, {
"icon_id": "24881289",
"name": "download",
"font_class": "download",
"unicode": "e68d",
"unicode_decimal": 59021
}, {
"icon_id": "24879601",
"name": "help",
"font_class": "help",
"unicode": "e679",
"unicode_decimal": 59001
}, {
"icon_id": "24879602",
"name": "navigate-filled",
"font_class": "navigate-filled",
"unicode": "e67a",
"unicode_decimal": 59002
}, {
"icon_id": "24879603",
"name": "plusempty",
"font_class": "plusempty",
"unicode": "e67b",
"unicode_decimal": 59003
}, {
"icon_id": "24879604",
"name": "smallcircle",
"font_class": "smallcircle",
"unicode": "e67c",
"unicode_decimal": 59004
}, {
"icon_id": "24879605",
"name": "minus-filled",
"font_class": "minus-filled",
"unicode": "e67d",
"unicode_decimal": 59005
}, {
"icon_id": "24879606",
"name": "micoff",
"font_class": "micoff",
"unicode": "e67e",
"unicode_decimal": 59006
}, {
"icon_id": "24879588",
"name": "closeempty",
"font_class": "closeempty",
"unicode": "e66c",
"unicode_decimal": 58988
}, {
"icon_id": "24879589",
"name": "clear",
"font_class": "clear",
"unicode": "e66d",
"unicode_decimal": 58989
}, {
"icon_id": "24879590",
"name": "navigate",
"font_class": "navigate",
"unicode": "e66e",
"unicode_decimal": 58990
}, {
"icon_id": "24879591",
"name": "minus",
"font_class": "minus",
"unicode": "e66f",
"unicode_decimal": 58991
}, {
"icon_id": "24879592",
"name": "image",
"font_class": "image",
"unicode": "e670",
"unicode_decimal": 58992
}, {
"icon_id": "24879593",
"name": "mic",
"font_class": "mic",
"unicode": "e671",
"unicode_decimal": 58993
}, {
"icon_id": "24879594",
"name": "paperplane",
"font_class": "paperplane",
"unicode": "e672",
"unicode_decimal": 58994
}, {
"icon_id": "24879595",
"name": "close",
"font_class": "close",
"unicode": "e673",
"unicode_decimal": 58995
}, {
"icon_id": "24879596",
"name": "help-filled",
"font_class": "help-filled",
"unicode": "e674",
"unicode_decimal": 58996
}, {
"icon_id": "24879597",
"name": "plus-filled",
"font_class": "paperplane-filled",
"unicode": "e675",
"unicode_decimal": 58997
}, {
"icon_id": "24879598",
"name": "plus",
"font_class": "plus",
"unicode": "e676",
"unicode_decimal": 58998
}, {
"icon_id": "24879599",
"name": "mic-filled",
"font_class": "mic-filled",
"unicode": "e677",
"unicode_decimal": 58999
}, {
"icon_id": "24879600",
"name": "image-filled",
"font_class": "image-filled",
"unicode": "e678",
"unicode_decimal": 59000
}, {
"icon_id": "24855900",
"name": "locked-filled",
"font_class": "locked-filled",
"unicode": "e668",
"unicode_decimal": 58984
}, {
"icon_id": "24855901",
"name": "info",
"font_class": "info",
"unicode": "e669",
"unicode_decimal": 58985
}, {
"icon_id": "24855903",
"name": "locked",
"font_class": "locked",
"unicode": "e66b",
"unicode_decimal": 58987
}, {
"icon_id": "24855884",
"name": "camera-filled",
"font_class": "camera-filled",
"unicode": "e658",
"unicode_decimal": 58968
}, {
"icon_id": "24855885",
"name": "chat-filled",
"font_class": "chat-filled",
"unicode": "e659",
"unicode_decimal": 58969
}, {
"icon_id": "24855886",
"name": "camera",
"font_class": "camera",
"unicode": "e65a",
"unicode_decimal": 58970
}, {
"icon_id": "24855887",
"name": "circle",
"font_class": "circle",
"unicode": "e65b",
"unicode_decimal": 58971
}, {
"icon_id": "24855888",
"name": "checkmarkempty",
"font_class": "checkmarkempty",
"unicode": "e65c",
"unicode_decimal": 58972
}, {
"icon_id": "24855889",
"name": "chat",
"font_class": "chat",
"unicode": "e65d",
"unicode_decimal": 58973
}, {
"icon_id": "24855890",
"name": "circle-filled",
"font_class": "circle-filled",
"unicode": "e65e",
"unicode_decimal": 58974
}, {
"icon_id": "24855891",
"name": "flag",
"font_class": "flag",
"unicode": "e65f",
"unicode_decimal": 58975
}, {
"icon_id": "24855892",
"name": "flag-filled",
"font_class": "flag-filled",
"unicode": "e660",
"unicode_decimal": 58976
}, {
"icon_id": "24855893",
"name": "gear-filled",
"font_class": "gear-filled",
"unicode": "e661",
"unicode_decimal": 58977
}, {
"icon_id": "24855894",
"name": "home",
"font_class": "home",
"unicode": "e662",
"unicode_decimal": 58978
}, {
"icon_id": "24855895",
"name": "home-filled",
"font_class": "home-filled",
"unicode": "e663",
"unicode_decimal": 58979
}, {
"icon_id": "24855896",
"name": "gear",
"font_class": "gear",
"unicode": "e664",
"unicode_decimal": 58980
}, {
"icon_id": "24855897",
"name": "smallcircle-filled",
"font_class": "smallcircle-filled",
"unicode": "e665",
"unicode_decimal": 58981
}, {
"icon_id": "24855898",
"name": "map-filled",
"font_class": "map-filled",
"unicode": "e666",
"unicode_decimal": 58982
}, {
"icon_id": "24855899",
"name": "map",
"font_class": "map",
"unicode": "e667",
"unicode_decimal": 58983
}, {
"icon_id": "24855825",
"name": "refresh-filled",
"font_class": "refresh-filled",
"unicode": "e656",
"unicode_decimal": 58966
}, {
"icon_id": "24855826",
"name": "refresh",
"font_class": "refresh",
"unicode": "e657",
"unicode_decimal": 58967
}, {
"icon_id": "24855808",
"name": "cloud-upload",
"font_class": "cloud-upload",
"unicode": "e645",
"unicode_decimal": 58949
}, {
"icon_id": "24855809",
"name": "cloud-download-filled",
"font_class": "cloud-download-filled",
"unicode": "e646",
"unicode_decimal": 58950
}, {
"icon_id": "24855810",
"name": "cloud-download",
"font_class": "cloud-download",
"unicode": "e647",
"unicode_decimal": 58951
}, {
"icon_id": "24855811",
"name": "cloud-upload-filled",
"font_class": "cloud-upload-filled",
"unicode": "e648",
"unicode_decimal": 58952
}, {
"icon_id": "24855813",
"name": "redo",
"font_class": "redo",
"unicode": "e64a",
"unicode_decimal": 58954
}, {
"icon_id": "24855814",
"name": "images-filled",
"font_class": "images-filled",
"unicode": "e64b",
"unicode_decimal": 58955
}, {
"icon_id": "24855815",
"name": "undo-filled",
"font_class": "undo-filled",
"unicode": "e64c",
"unicode_decimal": 58956
}, {
"icon_id": "24855816",
"name": "more",
"font_class": "more",
"unicode": "e64d",
"unicode_decimal": 58957
}, {
"icon_id": "24855817",
"name": "more-filled",
"font_class": "more-filled",
"unicode": "e64e",
"unicode_decimal": 58958
}, {
"icon_id": "24855818",
"name": "undo",
"font_class": "undo",
"unicode": "e64f",
"unicode_decimal": 58959
}, {
"icon_id": "24855819",
"name": "images",
"font_class": "images",
"unicode": "e650",
"unicode_decimal": 58960
}, {
"icon_id": "24855821",
"name": "paperclip",
"font_class": "paperclip",
"unicode": "e652",
"unicode_decimal": 58962
}, {
"icon_id": "24855822",
"name": "settings",
"font_class": "settings",
"unicode": "e653",
"unicode_decimal": 58963
}, {
"icon_id": "24855823",
"name": "search",
"font_class": "search",
"unicode": "e654",
"unicode_decimal": 58964
}, {
"icon_id": "24855824",
"name": "redo-filled",
"font_class": "redo-filled",
"unicode": "e655",
"unicode_decimal": 58965
}, {
"icon_id": "24841702",
"name": "list",
"font_class": "list",
"unicode": "e644",
"unicode_decimal": 58948
}, {
"icon_id": "24841489",
"name": "mail-open-filled",
"font_class": "mail-open-filled",
"unicode": "e63a",
"unicode_decimal": 58938
}, {
"icon_id": "24841491",
"name": "hand-thumbsdown-filled",
"font_class": "hand-down-filled",
"unicode": "e63c",
"unicode_decimal": 58940
}, {
"icon_id": "24841492",
"name": "hand-thumbsdown",
"font_class": "hand-down",
"unicode": "e63d",
"unicode_decimal": 58941
}, {
"icon_id": "24841493",
"name": "hand-thumbsup-filled",
"font_class": "hand-up-filled",
"unicode": "e63e",
"unicode_decimal": 58942
}, {
"icon_id": "24841494",
"name": "hand-thumbsup",
"font_class": "hand-up",
"unicode": "e63f",
"unicode_decimal": 58943
}, {
"icon_id": "24841496",
"name": "heart-filled",
"font_class": "heart-filled",
"unicode": "e641",
"unicode_decimal": 58945
}, {
"icon_id": "24841498",
"name": "mail-open",
"font_class": "mail-open",
"unicode": "e643",
"unicode_decimal": 58947
}, {
"icon_id": "24841488",
"name": "heart",
"font_class": "heart",
"unicode": "e639",
"unicode_decimal": 58937
}, {
"icon_id": "24839963",
"name": "loop",
"font_class": "loop",
"unicode": "e633",
"unicode_decimal": 58931
}, {
"icon_id": "24839866",
"name": "pulldown",
"font_class": "pulldown",
"unicode": "e632",
"unicode_decimal": 58930
}, {
"icon_id": "24813798",
"name": "scan",
"font_class": "scan",
"unicode": "e62a",
"unicode_decimal": 58922
}, {
"icon_id": "24813786",
"name": "bars",
"font_class": "bars",
"unicode": "e627",
"unicode_decimal": 58919
}, {
"icon_id": "24813788",
"name": "cart-filled",
"font_class": "cart-filled",
"unicode": "e629",
"unicode_decimal": 58921
}, {
"icon_id": "24813790",
"name": "checkbox",
"font_class": "checkbox",
"unicode": "e62b",
"unicode_decimal": 58923
}, {
"icon_id": "24813791",
"name": "checkbox-filled",
"font_class": "checkbox-filled",
"unicode": "e62c",
"unicode_decimal": 58924
}, {
"icon_id": "24813794",
"name": "shop",
"font_class": "shop",
"unicode": "e62f",
"unicode_decimal": 58927
}, {
"icon_id": "24813795",
"name": "headphones",
"font_class": "headphones",
"unicode": "e630",
"unicode_decimal": 58928
}, {
"icon_id": "24813796",
"name": "cart",
"font_class": "cart",
"unicode": "e631",
"unicode_decimal": 58929
}]
};
exports.default = _default;
/***/ }),
/* 203 */,
/* 204 */,
/* 205 */,
/* 206 */,
/* 207 */,
/* 208 */,
/* 209 */,
/* 210 */,
/* 211 */,
/* 212 */,
/* 213 */,
/* 214 */,
/* 215 */,
/* 216 */,
/* 217 */
/*!******************************************************************************************************************!*\
!*** D:/Project/project_wenlv/tourGuide/uni_modules/uni-transition/components/uni-transition/createAnimation.js ***!
\******************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(uni) {
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ 4);
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createAnimation = createAnimation;
var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ 11));
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ 23));
var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ 24));
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
// const defaultOption = {
// duration: 300,
// timingFunction: 'linear',
// delay: 0,
// transformOrigin: '50% 50% 0'
// }
var MPAnimation = /*#__PURE__*/function () {
function MPAnimation(options, _this) {
(0, _classCallCheck2.default)(this, MPAnimation);
this.options = options;
this.animation = uni.createAnimation(options);
this.currentStepAnimates = {};
this.next = 0;
this.$ = _this;
}
(0, _createClass2.default)(MPAnimation, [{
key: "_nvuePushAnimates",
value: function _nvuePushAnimates(type, args) {
var aniObj = this.currentStepAnimates[this.next];
var styles = {};
if (!aniObj) {
styles = {
styles: {},
config: {}
};
} else {
styles = aniObj;
}
if (animateTypes1.includes(type)) {
if (!styles.styles.transform) {
styles.styles.transform = '';
}
var unit = '';
if (type === 'rotate') {
unit = 'deg';
}
styles.styles.transform += "".concat(type, "(").concat(args + unit, ") ");
} else {
styles.styles[type] = "".concat(args);
}
this.currentStepAnimates[this.next] = styles;
}
}, {
key: "_animateRun",
value: function _animateRun() {
var styles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var ref = this.$.$refs['ani'].ref;
if (!ref) return;
return new Promise(function (resolve, reject) {
nvueAnimation.transition(ref, _objectSpread({
styles: styles
}, config), function (res) {
resolve();
});
});
}
}, {
key: "_nvueNextAnimate",
value: function _nvueNextAnimate(animates) {
var _this2 = this;
var step = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var fn = arguments.length > 2 ? arguments[2] : undefined;
var obj = animates[step];
if (obj) {
var styles = obj.styles,
config = obj.config;
this._animateRun(styles, config).then(function () {
step += 1;
_this2._nvueNextAnimate(animates, step, fn);
});
} else {
this.currentStepAnimates = {};
typeof fn === 'function' && fn();
this.isEnd = true;
}
}
}, {
key: "step",
value: function step() {
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.animation.step(config);
return this;
}
}, {
key: "run",
value: function run(fn) {
this.$.animationData = this.animation.export();
this.$.timer = setTimeout(function () {
typeof fn === 'function' && fn();
}, this.$.durationTime);
}
}]);
return MPAnimation;
}();
var animateTypes1 = ['matrix', 'matrix3d', 'rotate', 'rotate3d', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scale3d', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'translate', 'translate3d', 'translateX', 'translateY', 'translateZ'];
var animateTypes2 = ['opacity', 'backgroundColor'];
var animateTypes3 = ['width', 'height', 'left', 'right', 'top', 'bottom'];
animateTypes1.concat(animateTypes2, animateTypes3).forEach(function (type) {
MPAnimation.prototype[type] = function () {
var _this$animation;
(_this$animation = this.animation)[type].apply(_this$animation, arguments);
return this;
};
});
function createAnimation(option, _this) {
if (!_this) return;
clearTimeout(_this.timer);
return new MPAnimation(option, _this);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/index.js */ 2)["default"]))
/***/ })
]]);
//# sourceMappingURL=../../.sourcemap/mp-weixin/common/vendor.js.map