From 06ce0ef39894f15e9ae26be6702cf3c945b3930a Mon Sep 17 00:00:00 2001 From: DCloud_LXH <283700113@qq.com> Date: Wed, 24 Nov 2021 15:19:21 +0800 Subject: [PATCH] fix: canvas use pako --- packages/uni-api/package.json | 4 +- .../uni-api/src/service/context/canvas.ts | 7 +- .../uni-app-plus/dist/uni-app-service.es.js | 32228 ++++++++-------- .../uni-app-plus/dist/uni-app-view.umd.js | 6 +- packages/uni-app-plus/package.json | 2 + packages/uni-app-plus/src/platform/index.ts | 2 + packages/uni-components/package.json | 3 +- .../src/components/canvas/index.tsx | 7 +- packages/uni-h5/dist/uni-h5.cjs.js | 10 +- packages/uni-h5/dist/uni-h5.es.js | 15 +- packages/uni-h5/package.json | 1 - packages/uni-h5/src/platform/index.ts | 3 + packages/uni-h5/vite.config.ts | 2 - packages/uni-stat/dist/uni-stat.cjs.js | 1888 +- packages/uni-stat/dist/uni-stat.es.js | 1888 +- pnpm-lock.yaml | 16 +- 16 files changed, 18101 insertions(+), 17981 deletions(-) diff --git a/packages/uni-api/package.json b/packages/uni-api/package.json index f555b9e13..9d16fea7c 100644 --- a/packages/uni-api/package.json +++ b/packages/uni-api/package.json @@ -14,8 +14,6 @@ "url": "https://github.com/dcloudio/uni-app/issues" }, "devDependencies": { - "@dcloudio/uni-shared": "3.0.0-alpha-3021320211123002", - "@types/pako": "^1.0.2", - "pako": "^1.0.11" + "@dcloudio/uni-shared": "3.0.0-alpha-3021320211123002" } } diff --git a/packages/uni-api/src/service/context/canvas.ts b/packages/uni-api/src/service/context/canvas.ts index 7bcd99c10..95d601699 100644 --- a/packages/uni-api/src/service/context/canvas.ts +++ b/packages/uni-api/src/service/context/canvas.ts @@ -31,9 +31,8 @@ import { once, ON_ERROR } from '@dcloudio/uni-shared' import { getPageIdByVm, getCurrentPageVm } from '@dcloudio/uni-core' -import { TEMP_PATH } from '@dcloudio/uni-platform' +import { TEMP_PATH, inflateRaw, deflateRaw } from '@dcloudio/uni-platform' -import pako from 'pako' //#endregion //#region UniServiceJSBridge @@ -1049,7 +1048,7 @@ export const canvasGetImageData = let imgData = data.data if (imgData && imgData.length) { if (__PLATFORM__ === 'app' && data.compressed) { - imgData = pako.inflateRaw(imgData) as any + imgData = inflateRaw(imgData) as any } data.data = new Uint8ClampedArray(imgData) as any } @@ -1110,7 +1109,7 @@ export const canvasPutImageData = __PLATFORM__ === 'app' && (plus.os.name !== 'iOS' || typeof __WEEX_DEVTOOL__ === 'boolean') ) { - data = pako.deflateRaw(data as any, { to: 'string' }) as any + data = deflateRaw(data as any, { to: 'string' }) as any compressed = true } else { // fix ... 操作符 diff --git a/packages/uni-app-plus/dist/uni-app-service.es.js b/packages/uni-app-plus/dist/uni-app-service.es.js index ef3865854..53b4b7372 100644 --- a/packages/uni-app-plus/dist/uni-app-service.es.js +++ b/packages/uni-app-plus/dist/uni-app-service.es.js @@ -10,79 +10,79 @@ const __uniRoutes = instanceContext.__uniRoutes; var serviceContext = (function (vue) { 'use strict'; - /* - * base64-arraybuffer - * https://github.com/niklasvh/base64-arraybuffer - * - * Copyright (c) 2012 Niklas von Hertzen - * Licensed under the MIT license. - */ - - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - - // Use a lookup table to find the index. - var lookup = /*#__PURE__*/ (function () { - const lookup = new Uint8Array(256); - for (var i = 0; i < chars.length; i++) { - lookup[chars.charCodeAt(i)] = i; - } - return lookup - })(); - - function encode$3(arraybuffer) { - var bytes = new Uint8Array(arraybuffer), - i, - len = bytes.length, - base64 = ''; - - for (i = 0; i < len; i += 3) { - base64 += chars[bytes[i] >> 2]; - base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; - base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; - base64 += chars[bytes[i + 2] & 63]; - } - - if (len % 3 === 2) { - base64 = base64.substring(0, base64.length - 1) + '='; - } else if (len % 3 === 1) { - base64 = base64.substring(0, base64.length - 2) + '=='; - } - - return base64 - } - - function decode$1(base64) { - var bufferLength = base64.length * 0.75, - len = base64.length, - i, - p = 0, - encoded1, - encoded2, - encoded3, - encoded4; - - if (base64[base64.length - 1] === '=') { - bufferLength--; - if (base64[base64.length - 2] === '=') { - bufferLength--; - } - } - - var arraybuffer = new ArrayBuffer(bufferLength), - bytes = new Uint8Array(arraybuffer); - - for (i = 0; i < len; i += 4) { - encoded1 = lookup[base64.charCodeAt(i)]; - encoded2 = lookup[base64.charCodeAt(i + 1)]; - encoded3 = lookup[base64.charCodeAt(i + 2)]; - encoded4 = lookup[base64.charCodeAt(i + 3)]; - - bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); - bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); - bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); - } - - return arraybuffer + /* + * base64-arraybuffer + * https://github.com/niklasvh/base64-arraybuffer + * + * Copyright (c) 2012 Niklas von Hertzen + * Licensed under the MIT license. + */ + + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + // Use a lookup table to find the index. + var lookup = /*#__PURE__*/ (function () { + const lookup = new Uint8Array(256); + for (var i = 0; i < chars.length; i++) { + lookup[chars.charCodeAt(i)] = i; + } + return lookup + })(); + + function encode$3(arraybuffer) { + var bytes = new Uint8Array(arraybuffer), + i, + len = bytes.length, + base64 = ''; + + for (i = 0; i < len; i += 3) { + base64 += chars[bytes[i] >> 2]; + base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; + base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; + base64 += chars[bytes[i + 2] & 63]; + } + + if (len % 3 === 2) { + base64 = base64.substring(0, base64.length - 1) + '='; + } else if (len % 3 === 1) { + base64 = base64.substring(0, base64.length - 2) + '=='; + } + + return base64 + } + + function decode$1(base64) { + var bufferLength = base64.length * 0.75, + len = base64.length, + i, + p = 0, + encoded1, + encoded2, + encoded3, + encoded4; + + if (base64[base64.length - 1] === '=') { + bufferLength--; + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + + var arraybuffer = new ArrayBuffer(bufferLength), + bytes = new Uint8Array(arraybuffer); + + for (i = 0; i < len; i += 4) { + encoded1 = lookup[base64.charCodeAt(i)]; + encoded2 = lookup[base64.charCodeAt(i + 1)]; + encoded3 = lookup[base64.charCodeAt(i + 2)]; + encoded4 = lookup[base64.charCodeAt(i + 3)]; + + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + + return arraybuffer } /** @@ -2659,10404 +2659,1547 @@ var serviceContext = (function (vue) { UniServiceJSBridge.unsubscribe(getEventName(reqId)); } - const isIOS$1 = plus.os.name === 'iOS'; - let config; - /** - * tabbar显示状态 - */ - let visible = true; - let tabBar; - /** - * 设置角标 - * @param {string} type - * @param {number} index - * @param {string} text - */ - function setTabBarBadge$1(type, index, text) { - if (!tabBar) { - return; - } - if (type === 'none') { - tabBar.hideTabBarRedDot({ - index, - }); - tabBar.removeTabBarBadge({ - index, - }); - } - else if (type === 'text') { - tabBar.setTabBarBadge({ - index, - text, - }); - } - else if (type === 'redDot') { - tabBar.showTabBarRedDot({ - index, - }); - } + const EVENT_BACKBUTTON = 'backbutton'; + function backbuttonListener() { + uni.navigateBack({ + from: 'backbutton', + success() { }, // 传入空方法,避免返回Promise,因为onBackPress可能导致fail + }); } - /** - * 动态设置 tabBar 某一项的内容 - */ - function setTabBarItem$1(index, text, iconPath, selectedIconPath, visible) { - const item = { - index, - }; - if (text !== undefined) { - item.text = text; - } - if (iconPath) { - item.iconPath = getRealPath(iconPath); - } - if (selectedIconPath) { - item.selectedIconPath = getRealPath(selectedIconPath); - } - if (visible !== undefined) { - item.visible = config.list[index].visible = visible; - delete item.index; - const tabbarItems = config.list.map((item) => ({ - visible: item.visible, - })); - tabbarItems[index] = item; - tabBar && tabBar.setTabBarItems({ list: tabbarItems }); - } - else { - tabBar && tabBar.setTabBarItem(item); - } + const enterOptions = createLaunchOptions(); + const launchOptions = createLaunchOptions(); + function getLaunchOptions() { + return launchOptions; } - /** - * 动态设置 tabBar 的整体样式 - * @param {Object} style 样式 - */ - function setTabBarStyle$1(style) { - tabBar && tabBar.setTabBarStyle(style); + function getEnterOptions() { + return enterOptions; } - /** - * 隐藏 tabBar - * @param {boolean} animation 是否需要动画效果 - */ - function hideTabBar$1(animation) { - visible = false; - tabBar && - tabBar.hideTabBar({ - animation, - }); + function initEnterOptions({ path, query, referrerInfo, }) { + extend(enterOptions, { + path, + query: query ? parseQuery(query) : {}, + referrerInfo: referrerInfo || {}, + }); } - /** - * 显示 tabBar - * @param {boolean} animation 是否需要动画效果 - */ - function showTabBar$1(animation) { - visible = true; - tabBar && - tabBar.showTabBar({ - animation, - }); + function initLaunchOptions({ path, query, referrerInfo, }) { + extend(launchOptions, { + path, + query: query ? parseQuery(query) : {}, + referrerInfo: referrerInfo || {}, + }); + extend(enterOptions, launchOptions); + return launchOptions; } - const maskClickCallback = []; - var tabBar$1 = { - id: '0', - init(options, clickCallback) { - if (options && options.list.length) { - config = options; - } - try { - tabBar = weex.requireModule('uni-tabview'); - } - catch (error) { - console.log(`uni.requireNativePlugin("uni-tabview") error ${error}`); - } - tabBar.onMaskClick(() => { - maskClickCallback.forEach((callback) => { - callback(); - }); - }); - tabBar && - tabBar.onClick(({ index }) => { - clickCallback(config.list[index], index); - }); - tabBar && - tabBar.onMidButtonClick(() => { - // publish('onTabBarMidButtonTap', {}) - }); - }, - indexOf(page) { - const itemLength = config && config.list && config.list.length; - if (itemLength) { - for (let i = 0; i < itemLength; i++) { - if (config.list[i].pagePath === page || - config.list[i].pagePath === `${page}.html`) { - return i; - } - } - } - return -1; - }, - switchTab(page) { - const index = this.indexOf(page); - if (index >= 0) { - tabBar && - tabBar.switchSelect({ - index, - }); - return true; + function parseRedirectInfo() { + const weexPlus = weex.requireModule('plus'); + if (weexPlus.getRedirectInfo) { + const { path, query, extraData, userAction, fromAppid } = weexPlus.getRedirectInfo() || {}; + const referrerInfo = { + appId: fromAppid, + extraData: {}, + }; + if (extraData) { + referrerInfo.extraData = extraData; } - return false; - }, - setTabBarBadge: setTabBarBadge$1, - setTabBarItem: setTabBarItem$1, - setTabBarStyle: setTabBarStyle$1, - hideTabBar: hideTabBar$1, - showTabBar: showTabBar$1, - append(webview) { - tabBar && - tabBar.append({ - id: webview.id, - }, ({ code }) => { - if (code !== 0) { - setTimeout(() => { - this.append(webview); - }, 20); - } - }); - }, - get visible() { - return visible; - }, - get height() { - return ((config && config.height ? parseFloat(config.height) : TABBAR_HEIGHT) + - plus.navigator.getSafeAreaInsets().deviceBottom); - }, - // tabBar是否遮挡内容区域 - get cover() { - const array = ['extralight', 'light', 'dark']; - return isIOS$1 && array.indexOf(config.blurEffect) >= 0; - }, - setStyle({ mask }) { - tabBar.setMask({ - color: mask, - }); - }, - addEventListener(_name, callback) { - maskClickCallback.push(callback); - }, - removeEventListener(_name, callback) { - const callbackIndex = maskClickCallback.indexOf(callback); - maskClickCallback.splice(callbackIndex, 1); - }, - }; + return { + path, + query: query ? '?' + query : '', + referrerInfo, + userAction, + }; + } + } - const VD_SYNC = 'vdSync'; - const APP_SERVICE_ID = '__uniapp__service'; - const ON_WEBVIEW_READY = 'onWebviewReady'; - const ACTION_TYPE_DICT = 0; - const WEBVIEW_INSERTED = 'webviewInserted'; - const WEBVIEW_REMOVED = 'webviewRemoved'; + function createCommonjsModule(fn) { + var module = { exports: {} }; + return fn(module, module.exports), module.exports; + } - let vueApp; - function getVueApp() { - return vueApp; - } - function initVueApp(appVm) { - const appContext = appVm.$.appContext; - vueApp = extend(appContext.app, { - mountPage(pageComponent, pageProps, pageContainer) { - const vnode = vue.createVNode(pageComponent, pageProps); - // store app context on the root VNode. - // this will be set on the root instance on initial mount. - vnode.appContext = appContext; - vnode.__page_container__ = pageContainer; - vue.render(vnode, pageContainer); - const publicThis = vnode.component.proxy; - publicThis.__page_container__ = pageContainer; - return publicThis; - }, - unmountPage: (pageInstance) => { - const { __page_container__ } = pageInstance; - if (__page_container__) { - __page_container__.isUnmounted = true; - vue.render(null, __page_container__); - } - }, - }); + var common = createCommonjsModule(function (module, exports) { + + + var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + + function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); } - const pages = []; - function addCurrentPage(page) { - pages.push(page); - } - function getPageById(id) { - return pages.find((page) => page.$page.id === id); - } - function getAllPages() { - return pages; - } - function getCurrentPages$1() { - const curPages = []; - pages.forEach((page) => { - if (page.$.__isTabBar) { - if (page.$.__isActive) { - curPages.push(page); - } - } - else { - curPages.push(page); - } - }); - return curPages; - } - function removeCurrentPage() { - const page = getCurrentPage(); - if (!page) { - return; - } - removePage(page); - } - function removePage(curPage) { - const index = pages.findIndex((page) => page === curPage); - if (index === -1) { - return; - } - if (!curPage.$page.meta.isNVue) { - getVueApp().unmountPage(curPage); - } - pages.splice(index, 1); - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('removePage', curPage.$page)); - } + exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; + }; + + + // reduce buffer size, avoiding mem copy + exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; + }; + + + var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } + }; + + var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } + }; + + + // Enable/Disable typed arrays use, for testing + // + exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } + }; + + exports.setTyped(TYPED_OK); + }); + + var require$$0 = common; + + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + /* eslint-disable space-unary-ops */ + + + + /* Public constants ==========================================================*/ + /* ===========================================================================*/ + + + //var Z_FILTERED = 1; + //var Z_HUFFMAN_ONLY = 2; + //var Z_RLE = 3; + var Z_FIXED$1 = 4; + //var Z_DEFAULT_STRATEGY = 0; + + /* Possible values of the data_type field (though see inflate()) */ + var Z_BINARY = 0; + var Z_TEXT = 1; + //var Z_ASCII = 1; // = Z_TEXT + var Z_UNKNOWN$1 = 2; + + /*============================================================================*/ + + + function zero$1(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + // From zutil.h + + var STORED_BLOCK = 0; + var STATIC_TREES = 1; + var DYN_TREES = 2; + /* The three kinds of block type */ + + var MIN_MATCH$1 = 3; + var MAX_MATCH$1 = 258; + /* The minimum and maximum match lengths */ + + // From deflate.h + /* =========================================================================== + * Internal compression state. + */ + + var LENGTH_CODES$1 = 29; + /* number of length codes, not counting the special END_BLOCK code */ + + var LITERALS$1 = 256; + /* number of literal bytes 0..255 */ + + var L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1; + /* number of Literal or Length codes, including the END_BLOCK code */ + + var D_CODES$1 = 30; + /* number of distance codes */ + + var BL_CODES$1 = 19; + /* number of codes used to transfer the bit lengths */ + + var HEAP_SIZE$1 = 2 * L_CODES$1 + 1; + /* maximum heap size */ + + var MAX_BITS$1 = 15; + /* All codes must not exceed MAX_BITS bits */ + + var Buf_size = 16; + /* size of bit buffer in bi_buf */ + + + /* =========================================================================== + * Constants + */ + + var MAX_BL_BITS = 7; + /* Bit length codes must not exceed MAX_BL_BITS bits */ + + var END_BLOCK = 256; + /* end of block literal code */ + + var REP_3_6 = 16; + /* repeat previous bit length 3-6 times (2 bits of repeat count) */ + + var REPZ_3_10 = 17; + /* repeat a zero length 3-10 times (3 bits of repeat count) */ + + var REPZ_11_138 = 18; + /* repeat a zero length 11-138 times (7 bits of repeat count) */ + + /* eslint-disable comma-spacing,array-bracket-spacing */ + var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + + var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + + var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + + var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; + /* eslint-enable comma-spacing,array-bracket-spacing */ + + /* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + + /* =========================================================================== + * Local data. These are initialized only once. + */ + + // We pre-fill arrays with 0 to avoid uninitialized gaps + + var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + + // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 + var static_ltree = new Array((L_CODES$1 + 2) * 2); + zero$1(static_ltree); + /* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + + var static_dtree = new Array(D_CODES$1 * 2); + zero$1(static_dtree); + /* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + + var _dist_code = new Array(DIST_CODE_LEN); + zero$1(_dist_code); + /* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + + var _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1); + zero$1(_length_code); + /* length code for each normalized match length (0 == MIN_MATCH) */ + + var base_length = new Array(LENGTH_CODES$1); + zero$1(base_length); + /* First normalized length for each code (0 = MIN_MATCH) */ + + var base_dist = new Array(D_CODES$1); + zero$1(base_dist); + /* First normalized distance for each code (0 = distance of 1) */ + + + function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; } - class UniPageNode extends UniNode { - constructor(pageId, options, setup = false) { - super(NODE_TYPE_PAGE, '#page', null); - this._id = 1; - this._created = false; - this._updating = false; - this._createActionMap = new Map(); - this.updateActions = []; - this.dicts = []; - this.nodeId = 0; - this.pageId = pageId; - this.pageNode = this; - this.options = options; - this.isUnmounted = false; - this.createAction = [ACTION_TYPE_PAGE_CREATE, options]; - this.createdAction = [ACTION_TYPE_PAGE_CREATED]; - this.normalizeDict = this._normalizeDict.bind(this); - this._update = this.update.bind(this); - setup && this.setup(); - } - _normalizeDict(value, normalizeValue = true) { - if (!isPlainObject(value)) { - return this.addDict(value); - } - const dictArray = []; - Object.keys(value).forEach((n) => { - const dict = [this.addDict(n)]; - const v = value[n]; - if (normalizeValue) { - dict.push(this.addDict(v)); - } - else { - dict.push(v); - } - dictArray.push(dict); - }); - return dictArray; - } - addDict(value) { - const { dicts } = this; - const index = dicts.indexOf(value); - if (index > -1) { - return index; - } - return dicts.push(value) - 1; - } - onInjectHook(hook) { - if ((hook === ON_PAGE_SCROLL || hook === ON_REACH_BOTTOM) && - !this.scrollAction) { - this.scrollAction = [ - ACTION_TYPE_PAGE_SCROLL, - this.options.onReachBottomDistance, - ]; - this.push(this.scrollAction); - } - } - onCreate(thisNode, nodeName) { - pushCreateAction(this, thisNode.nodeId, nodeName); - return thisNode; - } - onInsertBefore(thisNode, newChild, refChild) { - pushInsertAction(this, newChild, thisNode.nodeId, (refChild && refChild.nodeId) || -1); - return newChild; - } - onRemoveChild(oldChild) { - pushRemoveAction(this, oldChild.nodeId); - return oldChild; - } - onAddEvent(thisNode, name, flag) { - if (thisNode.parentNode) { - pushAddEventAction(this, thisNode.nodeId, name, flag); - } - } - onAddWxsEvent(thisNode, name, wxsEvent, flag) { - if (thisNode.parentNode) { - pushAddWxsEventAction(this, thisNode.nodeId, name, wxsEvent, flag); - } - } - onRemoveEvent(thisNode, name) { - if (thisNode.parentNode) { - pushRemoveEventAction(this, thisNode.nodeId, name); - } - } - onSetAttribute(thisNode, qualifiedName, value) { - if (thisNode.parentNode) { - pushSetAttributeAction(this, thisNode.nodeId, qualifiedName, value); - } - } - onRemoveAttribute(thisNode, qualifiedName) { - if (thisNode.parentNode) { - pushRemoveAttributeAction(this, thisNode.nodeId, qualifiedName); - } - } - onTextContent(thisNode, text) { - if (thisNode.parentNode) { - pushSetTextAction(this, thisNode.nodeId, text); - } - } - onNodeValue(thisNode, val) { - if (thisNode.parentNode) { - pushSetTextAction(this, thisNode.nodeId, val); - } - } - genId() { - return this._id++; - } - push(action, extras) { - if (this.isUnmounted) { - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('PageNode', 'push.prevent', action)); - } - return; - } - switch (action[0]) { - case ACTION_TYPE_CREATE: - this._createActionMap.set(action[1], action); - break; - case ACTION_TYPE_INSERT: - const createAction = this._createActionMap.get(action[1]); - if (createAction) { - createAction[3] = action[2]; // parentNodeId - createAction[4] = action[3]; // anchorId - if (extras) { - createAction[5] = extras; - } - } - else { - if ((process.env.NODE_ENV !== 'production')) { - console.error(formatLog(`Insert`, action, 'not found createAction')); - } - } - break; - } - // insert 被合并进 create - if (action[0] !== ACTION_TYPE_INSERT) { - this.updateActions.push(action); - } - if (!this._updating) { - this._updating = true; - vue.queuePostFlushCb(this._update); - } - } - restore() { - this.clear(); - this.push(this.createAction); - if (this.scrollAction) { - this.push(this.scrollAction); - } - const restoreNode = (node) => { - this.onCreate(node, node.nodeName); - this.onInsertBefore(node.parentNode, node, null); - node.childNodes.forEach((childNode) => { - restoreNode(childNode); - }); - }; - this.childNodes.forEach((childNode) => restoreNode(childNode)); - this.push(this.createdAction); - } - setup() { - this.send([this.createAction]); - } - update() { - const { dicts, updateActions, _createActionMap } = this; - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('PageNode', 'update', updateActions.length, _createActionMap.size)); - } - // 首次 - if (!this._created) { - this._created = true; - updateActions.push(this.createdAction); - } - if (updateActions.length) { - if (dicts.length) { - updateActions.unshift([ACTION_TYPE_DICT, dicts]); - } - this.send(updateActions); - } - this.clear(); - } - clear() { - this.dicts.length = 0; - this.updateActions.length = 0; - this._updating = false; - this._createActionMap.clear(); - } - send(action) { - UniServiceJSBridge.publishHandler(VD_SYNC, action, this.pageId); - } - fireEvent(id, evt) { - const node = findNodeById(id, this); - if (node) { - node.dispatchEvent(evt); - } - else if ((process.env.NODE_ENV !== 'production')) { - console.error(formatLog('PageNode', 'fireEvent', id, 'not found', evt)); - } - } - } - function getPageNode(pageId) { - const page = getPageById(pageId); - if (!page) - return null; - return page.__page_container__; - } - function findNode(name, value, uniNode) { - if (typeof uniNode === 'number') { - uniNode = getPageNode(uniNode); - } - if (uniNode[name] === value) { - return uniNode; - } - const { childNodes } = uniNode; - for (let i = 0; i < childNodes.length; i++) { - const uniNode = findNode(name, value, childNodes[i]); - if (uniNode) { - return uniNode; - } - } - return null; - } - function findNodeById(nodeId, uniNode) { - return findNode('nodeId', nodeId, uniNode); - } - function findNodeByTagName(tagName, uniNode) { - return findNode('nodeName', tagName.toUpperCase(), uniNode); - } - function pushCreateAction(pageNode, nodeId, nodeName) { - pageNode.push([ - ACTION_TYPE_CREATE, - nodeId, - pageNode.addDict(nodeName), - -1, - -1, - ]); - } - function pushInsertAction(pageNode, newChild, parentNodeId, refChildId) { - const nodeJson = newChild.toJSON({ - attr: true, - normalize: pageNode.normalizeDict, - }); - pageNode.push([ACTION_TYPE_INSERT, newChild.nodeId, parentNodeId, refChildId], Object.keys(nodeJson).length ? nodeJson : undefined); - } - function pushRemoveAction(pageNode, nodeId) { - pageNode.push([ACTION_TYPE_REMOVE, nodeId]); - } - function pushAddEventAction(pageNode, nodeId, name, value) { - pageNode.push([ACTION_TYPE_ADD_EVENT, nodeId, pageNode.addDict(name), value]); - } - function pushAddWxsEventAction(pageNode, nodeId, name, wxsEvent, value) { - pageNode.push([ - ACTION_TYPE_ADD_WXS_EVENT, - nodeId, - pageNode.addDict(name), - pageNode.addDict(wxsEvent), - value, - ]); - } - function pushRemoveEventAction(pageNode, nodeId, name) { - pageNode.push([ACTION_TYPE_REMOVE_EVENT, nodeId, pageNode.addDict(name)]); - } - function normalizeAttrValue(pageNode, name, value) { - return name === 'style' && isPlainObject(value) - ? pageNode.normalizeDict(value) - : pageNode.addDict(value); - } - function pushSetAttributeAction(pageNode, nodeId, name, value) { - pageNode.push([ - ACTION_TYPE_SET_ATTRIBUTE, - nodeId, - pageNode.addDict(name), - normalizeAttrValue(pageNode, name, value), - ]); - } - function pushRemoveAttributeAction(pageNode, nodeId, name) { - pageNode.push([ACTION_TYPE_REMOVE_ATTRIBUTE, nodeId, pageNode.addDict(name)]); - } - function pushSetTextAction(pageNode, nodeId, text) { - pageNode.push([ACTION_TYPE_SET_TEXT, nodeId, pageNode.addDict(text)]); - } - function createPageNode(pageId, pageOptions, setup) { - return new UniPageNode(pageId, pageOptions, setup); - } - - function setupPage(component) { - const oldSetup = component.setup; - component.inheritAttrs = false; // 禁止继承 __pageId 等属性,避免告警 - component.setup = (_, ctx) => { - const { attrs: { __pageId, __pagePath, __pageQuery, __pageInstance }, } = ctx; - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog(__pagePath, 'setup')); - } - const instance = vue.getCurrentInstance(); - const pageVm = instance.proxy; - initPageVm(pageVm, __pageInstance); - addCurrentPage(initScope(__pageId, pageVm, __pageInstance)); - vue.onMounted(() => { - vue.nextTick(() => { - // onShow被延迟,故onReady也同时延迟 - invokeHook(pageVm, ON_READY); - }); - // TODO preloadSubPackages - }); - vue.onBeforeUnmount(() => { - invokeHook(pageVm, ON_UNLOAD); - }); - if (oldSetup) { - return oldSetup(__pageQuery, ctx); - } - }; - return component; - } - function initScope(pageId, vm, pageInstance) { - const $getAppWebview = () => { - return plus.webview.getWebviewById(pageId + ''); - }; - vm.$getAppWebview = $getAppWebview; - vm.$.ctx.$scope = { - $getAppWebview, - }; - vm.getOpenerEventChannel = () => { - if (!pageInstance.eventChannel) { - pageInstance.eventChannel = new EventChannel(pageId); - } - return pageInstance.eventChannel; - }; - return vm; - } - - function isVuePageAsyncComponent(component) { - return isFunction(component); - } - const pagesMap = new Map(); - function definePage(pagePath, asyncComponent) { - pagesMap.set(pagePath, once(createFactory(asyncComponent))); - } - function createPage(__pageId, __pagePath, __pageQuery, __pageInstance, pageOptions) { - const pageNode = createPageNode(__pageId, pageOptions, true); - const app = getVueApp(); - const component = pagesMap.get(__pagePath)(); - const mountPage = (component) => app.mountPage(component, { - __pageId, - __pagePath, - __pageQuery, - __pageInstance, - }, pageNode); - if (isPromise(component)) { - return component.then((component) => mountPage(component)); - } - return mountPage(component); - } - function createFactory(component) { - return () => { - if (isVuePageAsyncComponent(component)) { - return component().then((component) => setupPage(component)); - } - return setupPage(component); - }; - } - - let isInitEntryPage = false; - function initEntry() { - if (isInitEntryPage) { - return; - } - isInitEntryPage = true; - let entryPagePath; - let entryPageQuery; - const weexPlus = weex.requireModule('plus'); - if (weexPlus.getRedirectInfo) { - const { path, query, referrerInfo } = parseRedirectInfo(); - entryPagePath = path; - entryPageQuery = query; - __uniConfig.referrerInfo = referrerInfo; - } - else { - const argsJsonStr = plus.runtime.arguments; - if (!argsJsonStr) { - return; - } - try { - const args = JSON.parse(argsJsonStr); - entryPagePath = args.path || args.pathName; - entryPageQuery = args.query ? '?' + args.query : ''; - } - catch (e) { } - } - if (!entryPagePath || entryPagePath === __uniConfig.entryPagePath) { - if (entryPageQuery) { - __uniConfig.entryPageQuery = entryPageQuery; - } - return; - } - const entryRoute = addLeadingSlash(entryPagePath); - const routeOptions = getRouteOptions(entryRoute); - if (!routeOptions) { - return; - } - if (!routeOptions.meta.isTabBar) { - __uniConfig.realEntryPagePath = - __uniConfig.realEntryPagePath || __uniConfig.entryPagePath; - } - __uniConfig.entryPagePath = entryPagePath; - __uniConfig.entryPageQuery = entryPageQuery; - } - - function initRouteOptions(path, openType) { - // 需要序列化一遍 - const routeOptions = JSON.parse(JSON.stringify(getRouteOptions(path))); - routeOptions.meta = initRouteMeta(routeOptions.meta); - if (openType === 'reLaunch' || - (!__uniConfig.realEntryPagePath && getCurrentPages().length === 0) // redirectTo - ) { - routeOptions.meta.isQuit = true; - } - else if (!routeOptions.meta.isTabBar) { - routeOptions.meta.isQuit = false; - } - // TODO - // if (routeOptions.meta.isTabBar) { - // routeOptions.meta.visible = true - // } - return routeOptions; - } - - function initNVue(webviewStyle, routeMeta, path) { - if (path && routeMeta.isNVue) { - webviewStyle.uniNView = { - path, - defaultFontSize: __uniConfig.defaultFontSize, - viewport: __uniConfig.viewport, - }; - } - } - - const colorRE = /^#[a-z0-9]{6}$/i; - function isColor(color) { - return color && (colorRE.test(color) || color === 'transparent'); - } - - function initBackgroundColor(webviewStyle, routeMeta) { - const { backgroundColor } = routeMeta; - if (!backgroundColor) { - return; - } - if (!isColor(backgroundColor)) { - return; - } - if (!webviewStyle.background) { - webviewStyle.background = backgroundColor; - } - if (!webviewStyle.backgroundColorTop) { - webviewStyle.backgroundColorTop = backgroundColor; - } - } - - function initPopGesture(webviewStyle, routeMeta) { - // 不支持 hide - if (webviewStyle.popGesture === 'hide') { - delete webviewStyle.popGesture; - } - // 似乎没用了吧?记得是之前流应用时,需要 appback 的逻辑 - if (routeMeta.isQuit) { - webviewStyle.popGesture = (plus.os.name === 'iOS' ? 'appback' : 'none'); - } - } - - function initPullToRefresh(webviewStyle, routeMeta) { - if (!routeMeta.enablePullDownRefresh) { - return; - } - const pullToRefresh = normalizePullToRefreshRpx(extend({}, plus.os.name === 'Android' - ? defaultAndroidPullToRefresh - : defaultPullToRefresh, routeMeta.pullToRefresh)); - webviewStyle.pullToRefresh = initWebviewPullToRefreshI18n(pullToRefresh, routeMeta); - } - function initWebviewPullToRefreshI18n(pullToRefresh, routeMeta) { - const i18nResult = initPullToRefreshI18n(pullToRefresh); - if (!i18nResult) { - return pullToRefresh; - } - const [contentdownI18n, contentoverI18n, contentrefreshI18n] = i18nResult; - if (contentdownI18n || contentoverI18n || contentrefreshI18n) { - uni.onLocaleChange(() => { - const webview = plus.webview.getWebviewById(routeMeta.id + ''); - if (!webview) { - return; - } - const newPullToRefresh = { - support: true, - }; - if (contentdownI18n) { - newPullToRefresh.contentdown = { - caption: pullToRefresh.contentdown.caption, - }; - } - if (contentoverI18n) { - newPullToRefresh.contentover = { - caption: pullToRefresh.contentover.caption, - }; - } - if (contentrefreshI18n) { - newPullToRefresh.contentrefresh = { - caption: pullToRefresh.contentrefresh.caption, - }; - } - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('updateWebview', webview.id, newPullToRefresh)); - } - webview.setStyle({ - pullToRefresh: newPullToRefresh, - }); - }); - } - return pullToRefresh; - } - const defaultAndroidPullToRefresh = { support: true, style: 'circle' }; - const defaultPullToRefresh = { - support: true, - style: 'default', - height: '50px', - range: '200px', - contentdown: { - caption: '', - }, - contentover: { - caption: '', - }, - contentrefresh: { - caption: '', - }, - }; - - function initTitleNView(webviewStyle, routeMeta) { - const { navigationBar } = routeMeta; - if (navigationBar.style === 'custom') { - return false; - } - let autoBackButton = true; - if (routeMeta.isQuit) { - autoBackButton = false; - } - const titleNView = { - autoBackButton, - }; - Object.keys(navigationBar).forEach((name) => { - const value = navigationBar[name]; - if (name === 'backgroundColor') { - titleNView.backgroundColor = isColor(value) - ? value - : BACKGROUND_COLOR; - } - else if (name === 'titleImage' && value) { - titleNView.tags = createTitleImageTags(value); - } - else if (name === 'buttons' && isArray$1(value)) { - titleNView.buttons = value.map((button, index) => { - button.onclick = createTitleNViewBtnClick(index); - return button; - }); - } - else { - titleNView[name] = - value; - } - }); - webviewStyle.titleNView = initTitleNViewI18n(titleNView, routeMeta); - } - function initTitleNViewI18n(titleNView, routeMeta) { - const i18nResult = initNavigationBarI18n(titleNView); - if (!i18nResult) { - return titleNView; - } - const [titleTextI18n, searchInputPlaceholderI18n] = i18nResult; - if (titleTextI18n || searchInputPlaceholderI18n) { - uni.onLocaleChange(() => { - const webview = plus.webview.getWebviewById(routeMeta.id + ''); - if (!webview) { - return; - } - const newTitleNView = {}; - if (titleTextI18n) { - newTitleNView.titleText = titleNView.titleText; - } - if (searchInputPlaceholderI18n) { - newTitleNView.searchInput = { - placeholder: titleNView.searchInput.placeholder, - }; - } - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('updateWebview', webview.id, newTitleNView)); - } - webview.setStyle({ - titleNView: newTitleNView, - }); - }); - } - return titleNView; - } - function createTitleImageTags(titleImage) { - return [ - { - tag: 'img', - src: titleImage, - position: { - left: 'auto', - top: 'auto', - width: 'auto', - height: '26px', - }, - }, - ]; - } - function createTitleNViewBtnClick(index) { - return function onClick(btn) { - btn.index = index; - invokeHook(ON_NAVIGATION_BAR_BUTTON_TAP, btn); - }; - } - - function parseWebviewStyle(path, routeMeta) { - const webviewStyle = { - bounce: 'vertical', - }; - Object.keys(routeMeta).forEach((name) => { - if (WEBVIEW_STYLE_BLACKLIST.indexOf(name) === -1) { - webviewStyle[name] = - routeMeta[name]; - } - }); - initNVue(webviewStyle, routeMeta, path); - initPopGesture(webviewStyle, routeMeta); - initBackgroundColor(webviewStyle, routeMeta); - initTitleNView(webviewStyle, routeMeta); - initPullToRefresh(webviewStyle, routeMeta); - return webviewStyle; - } - const WEBVIEW_STYLE_BLACKLIST = [ - 'id', - 'route', - 'isNVue', - 'isQuit', - 'isEntry', - 'isTabBar', - 'tabBarIndex', - 'windowTop', - 'topWindow', - 'leftWindow', - 'rightWindow', - 'maxWidth', - 'usingComponents', - 'disableScroll', - 'enablePullDownRefresh', - 'navigationBar', - 'pullToRefresh', - 'onReachBottomDistance', - 'pageOrientation', - 'backgroundColor', - ]; - - let id = 2; - function getWebviewId() { - return id; - } - function genWebviewId() { - return id++; - } - function encode$1(val) { - return val; - } - function initUniPageUrl(path, query) { - const queryString = query ? stringifyQuery$1(query, encode$1) : ''; - return { - path: path.substr(1), - query: queryString ? queryString.substr(1) : queryString, - }; - } - function initDebugRefresh(isTab, path, query) { - const queryString = query ? stringifyQuery$1(query, encode$1) : ''; - return { - isTab, - arguments: JSON.stringify({ - path: path.substr(1), - query: queryString ? queryString.substr(1) : queryString, - }), - }; - } - - function createNVueWebview({ path, query, routeOptions, webviewStyle, }) { - const curWebviewId = genWebviewId(); - const curWebviewStyle = parseWebviewStyle(path, routeOptions.meta); - curWebviewStyle.uniPageUrl = initUniPageUrl(path, query); - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('createNVueWebview', curWebviewId, path, curWebviewStyle)); - } - curWebviewStyle.isTab = !!routeOptions.meta.isTabBar; - return plus.webview.create('', String(curWebviewId), curWebviewStyle, extend({ - nvue: true, - }, webviewStyle)); - } - - const downgrade = plus.os.name === 'Android' && parseInt(plus.os.version) < 6; - const ANI_SHOW = downgrade ? 'slide-in-right' : 'pop-in'; - const ANI_DURATION = 300; - const ANI_CLOSE = downgrade ? 'slide-out-right' : 'pop-out'; - const VIEW_WEBVIEW_PATH = '_www/__uniappview.html'; - const WEBVIEW_ID_PREFIX = 'webviewId'; - - let preloadWebview$1; - function setPreloadWebview(webview) { - preloadWebview$1 = webview; - } - function getPreloadWebview() { - return preloadWebview$1; - } - function createPreloadWebview() { - if (!preloadWebview$1 || preloadWebview$1.__uniapp_route) { - // 不存在,或已被使用 - preloadWebview$1 = plus.webview.create(VIEW_WEBVIEW_PATH, String(genWebviewId()), - // @ts-expect-error - { contentAdjust: false }); - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('createPreloadWebview', preloadWebview$1.id)); - } - } - return preloadWebview$1; - } - - function getCurrentWebview() { - const page = getCurrentPage(); - if (page) { - return page.$getAppWebview(); - } - return null; - } - function getWebview(page) { - if (page) { - return page.$getAppWebview(); - } - return getCurrentWebview(); - } - let pullDownRefreshWebview = null; - function getPullDownRefreshWebview() { - return pullDownRefreshWebview; - } - function setPullDownRefreshWebview(webview) { - pullDownRefreshWebview = webview; - } - function isTabBarPage$1(path = '') { - if (!(__uniConfig.tabBar && Array.isArray(__uniConfig.tabBar.list))) { - return false; - } - try { - if (!path) { - const pages = getCurrentPages(); - if (!pages.length) { - return false; - } - const page = pages[pages.length - 1]; - if (!page) { - return false; - } - return page.$page.meta.isTabBar; - } - if (!/^\//.test(path)) { - path = addLeadingSlash(path); - } - const route = __uniRoutes.find((route) => route.path === path); - return route && route.meta.isTabBar; - } - catch (e) { - if (process.env.NODE_ENV !== 'production') { - console.log('getCurrentPages is not ready'); - } - } - return false; - } - - function onWebviewClose(webview) { - const { popupSubNVueWebviews } = webview; - if (!popupSubNVueWebviews) { - return; - } - webview.addEventListener('close', () => { - Object.keys(popupSubNVueWebviews).forEach((id) => { - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('onWebviewClose', webview.id, 'popupSubNVueWebview', id, 'close')); - } - popupSubNVueWebviews[id].close('none'); - }); - }); - } - - let lastStatusBarStyle; - let oldSetStatusBarStyle = plus.navigator.setStatusBarStyle; - function restoreOldSetStatusBarStyle(setStatusBarStyle) { - oldSetStatusBarStyle = setStatusBarStyle; - } - function newSetStatusBarStyle(style) { - lastStatusBarStyle = style; - oldSetStatusBarStyle(style); - } - plus.navigator.setStatusBarStyle = newSetStatusBarStyle; - function setStatusBarStyle(statusBarStyle) { - if (!statusBarStyle) { - const page = getCurrentPage(); - if (!page) { - return; - } - statusBarStyle = page.$page.statusBarStyle; - if (!statusBarStyle || statusBarStyle === lastStatusBarStyle) { - return; - } - } - if (statusBarStyle === lastStatusBarStyle) { - return; - } - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('setStatusBarStyle', statusBarStyle)); - } - lastStatusBarStyle = statusBarStyle; - plus.navigator.setStatusBarStyle(statusBarStyle); - } - - function onWebviewPopGesture(webview) { - let popStartStatusBarStyle; - webview.addEventListener('popGesture', (e) => { - if (e.type === 'start') { - // 设置下一个页面的 statusBarStyle - const pages = getCurrentPages(); - const page = pages[pages.length - 2]; - popStartStatusBarStyle = lastStatusBarStyle; - const statusBarStyle = page && page.$page.statusBarStyle; - statusBarStyle && setStatusBarStyle(statusBarStyle); - } - else if (e.type === 'end' && !e.result) { - // 拖拽未完成,设置为当前状态栏前景色 - setStatusBarStyle(popStartStatusBarStyle); - } - else if (e.type === 'end' && e.result) { - removeCurrentPage(); - setStatusBarStyle(); - // 触发前一个页面 onShow - invokeHook(ON_SHOW); - } - }); - } - - function onWebviewRecovery(webview) { - if (webview.nvue) { - return; - } - const webviewId = webview.id; - const { subscribe, unsubscribe } = UniServiceJSBridge; - const onWebviewRecoveryReady = (_, pageId) => { - if (webviewId !== pageId) { - return; - } - unsubscribe(ON_WEBVIEW_READY, onWebviewRecoveryReady); - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog(`Recovery`, webviewId, 'ready')); - } - const page = getPageById(parseInt(pageId)); - if (page) { - const pageNode = page.__page_container__; - pageNode.restore(); - } - }; - // @ts-expect-error - webview.addEventListener('recovery', () => { - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('Recovery', webview.id)); - } - subscribe(ON_WEBVIEW_READY, onWebviewRecoveryReady); - }); - } - - function onWebviewResize(webview) { - const { emit } = UniServiceJSBridge; - const onResize = function ({ width, height, }) { - const landscape = Math.abs(plus.navigator.getOrientation()) === 90; - const res = { - deviceOrientation: landscape ? 'landscape' : 'portrait', - size: { - windowWidth: Math.ceil(width), - windowHeight: Math.ceil(height), - }, - }; - emit(ON_RESIZE, res, parseInt(webview.id)); // Page lifecycle - }; - webview.addEventListener('resize', debounce(onResize, 50)); - } - - const WEBVIEW_LISTENERS = { - pullToRefresh: ON_PULL_DOWN_REFRESH, - titleNViewSearchInputChanged: ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, - titleNViewSearchInputConfirmed: ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, - titleNViewSearchInputClicked: ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, - titleNViewSearchInputFocusChanged: ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, - }; - function initWebviewEvent(webview) { - const id = parseInt(webview.id); - Object.keys(WEBVIEW_LISTENERS).forEach((name) => { - const hook = WEBVIEW_LISTENERS[name]; - webview.addEventListener(name, (e) => { - if (hook === ON_PULL_DOWN_REFRESH) { - // 设置当前正在下拉刷新的webview - setPullDownRefreshWebview(webview); - } - invokeHook(id, hook, e); - }); - }); - onWebviewClose(webview); - onWebviewResize(webview); - if (plus.os.name === 'iOS') { - onWebviewRecovery(webview); - onWebviewPopGesture(webview); - } - } - - function initWebviewStyle(webview, path, query, routeMeta) { - const webviewStyle = parseWebviewStyle(path, routeMeta); - webviewStyle.uniPageUrl = initUniPageUrl(path, query); - const isTabBar = !!routeMeta.isTabBar; - if (!routeMeta.isNVue) { - webviewStyle.debugRefresh = initDebugRefresh(isTabBar, path, query); - } - else { - // android 需要使用 - webviewStyle.isTab = isTabBar; - } - webviewStyle.locale = weex.requireModule('plus').getLanguage(); - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('updateWebview', webviewStyle)); - } - webview.setStyle(webviewStyle); - } - - function getStatusbarHeight() { - // 横屏时 iOS 获取的状态栏高度错误,进行纠正 - return plus.navigator.isImmersedStatusbar() - ? Math.round(plus.os.name === 'iOS' - ? plus.navigator.getSafeAreaInsets().top - : plus.navigator.getStatusbarHeight()) - : 0; - } - function getStatusBarStyle() { - let style = plus.navigator.getStatusBarStyle(); - if (style === 'UIStatusBarStyleBlackTranslucent' || - style === 'UIStatusBarStyleBlackOpaque' || - style === 'null') { - style = 'light'; - } - else if (style === 'UIStatusBarStyleDefault') { - style = 'dark'; - } - return style; - } - - function warpPlusSuccessCallback(resolve, after) { - return function successCallback(data) { - delete data.code; - delete data.message; - if (typeof after === 'function') { - data = after(data); - } - resolve(data); - }; - } - function warpPlusErrorCallback(reject, errMsg) { - return function errorCallback(error) { - error = error || {}; - // 一键登录errorCallback新增 appid、metadata、uid 参数返回 - errMsg = error.message || errMsg || ''; - delete error.message; - reject(errMsg, extend({ code: 0 }, error)); - }; - } - function warpPlusEvent(plusObject, event) { - return function () { - const object = plusObject(); - object(function (data) { - if (data) { - delete data.code; - delete data.message; - } - UniServiceJSBridge.invokeOnCallback(event, data); - }); - }; - } - function warpPlusMethod(plusObject, before, after) { - return function (options, { resolve, reject }) { - const object = plusObject(); - object(extend({}, typeof before === 'function' ? before(options) : options, { - success: warpPlusSuccessCallback(resolve, after), - fail: warpPlusErrorCallback(reject), - })); - }; - } - function isTabBarPage(path = '') { - if (!(__uniConfig.tabBar && Array.isArray(__uniConfig.tabBar.list))) { - return false; - } - try { - if (!path) { - const pages = getCurrentPages(); - if (!pages.length) { - return false; - } - const page = pages[pages.length - 1]; - if (!page) { - return false; - } - return page.$page.meta.isTabBar; - } - if (!/^\//.test(path)) { - path = addLeadingSlash(path); - } - const route = getRouteOptions(path); - return route && route.meta.isTabBar; - } - catch (e) { - if ((process.env.NODE_ENV !== 'production')) { - console.error(formatLog('isTabBarPage', e)); - } - } - return false; - } - - function initSubNVues(webview, path, routeMeta) { - const subNVues = routeMeta.subNVues || []; - subNVues.forEach((subNVue) => { - if (!subNVue.path) { - return; - } - const style = subNVue.style || {}; - const isNavigationBar = subNVue.type === 'navigationBar'; - const isPopup = subNVue.type === 'popup'; - style.uniNView = { - path: subNVue.path.replace('.nvue', '.js'), - defaultFontSize: __uniConfig.defaultFontSize, - viewport: __uniConfig.viewport, - }; - const extras = { - __uniapp_host: path, - __uniapp_origin: style.uniNView.path.split('?')[0].replace('.js', ''), - __uniapp_origin_id: webview.id, - __uniapp_origin_type: webview.__uniapp_type, - }; - let maskWebview; - if (isNavigationBar) { - style.position = 'dock'; - style.dock = 'top'; - style.top = '0'; - style.width = '100%'; - style.height = String(NAVBAR_HEIGHT + getStatusbarHeight()); - delete style.left; - delete style.right; - delete style.bottom; - delete style.margin; - } - else if (isPopup) { - style.position = 'absolute'; - if (isTabBarPage(path)) { - maskWebview = tabBar$1; - } - else { - maskWebview = webview; - } - extras.__uniapp_mask = style.mask || 'rgba(0,0,0,0.5)'; - extras.__uniapp_mask_id = maskWebview.id; - } - delete style.mask; - const subNVueWebview = plus.webview.create('', subNVue.id, style, extras); - if (isPopup) { - if (!maskWebview.popupSubNVueWebviews) { - maskWebview.popupSubNVueWebviews = {}; - } - maskWebview.popupSubNVueWebviews[subNVueWebview.id] = subNVueWebview; - const hideSubNVue = function () { - maskWebview.setStyle({ - mask: 'none', - }); - subNVueWebview.hide('auto'); - }; - maskWebview.addEventListener('maskClick', hideSubNVue); - let isRemoved = false; // 增加个 remove 标记,防止出错 - subNVueWebview.addEventListener('show', () => { - if (!isRemoved) { - plus.key.removeEventListener('backbutton', backbuttonListener); - plus.key.addEventListener('backbutton', hideSubNVue); - isRemoved = true; - } - }); - subNVueWebview.addEventListener('hide', () => { - if (isRemoved) { - plus.key.removeEventListener('backbutton', hideSubNVue); - plus.key.addEventListener('backbutton', backbuttonListener); - isRemoved = false; - } - }); - subNVueWebview.addEventListener('close', () => { - delete maskWebview.popupSubNVueWebviews[subNVueWebview.id]; - if (isRemoved) { - plus.key.removeEventListener('backbutton', hideSubNVue); - plus.key.addEventListener('backbutton', backbuttonListener); - isRemoved = false; - } - }); - } - else { - webview.append(subNVueWebview); - } - }); - } - - function initWebview(webview, path, query, routeMeta) { - // 首页或非 nvue 页面 - if (webview.id === '1' || !routeMeta.isNVue) { - // path 必须参数为空,因为首页已经在 manifest.json 中设置了 uniNView,不能再次设置,否则会二次加载 - initWebviewStyle(webview, '', query, routeMeta); - } - initSubNVues(webview, path, routeMeta); - initWebviewEvent(webview); - } - - function createWebview(options) { - if (options.routeOptions.meta.isNVue) { - return createNVueWebview(options); - } - if (getWebviewId() === 2) { - // 如果首页非 nvue,则直接返回 Launch Webview - return plus.webview.getLaunchWebview(); - } - return getPreloadWebview(); - } - function onWebviewReady(pageId, callback) { - UniServiceJSBridge.once(ON_WEBVIEW_READY + '.' + pageId, callback); - } - - const preloadWebviews = {}; - function removePreloadWebview(webview) { - const url = Object.keys(preloadWebviews).find((url) => preloadWebviews[url].id === webview.id); - if (url) { - if (process.env.NODE_ENV !== 'production') { - console.log(`[uni-app] removePreloadWebview(${webview.id})`); - } - delete preloadWebviews[url]; - } - } - function closePreloadWebview({ url }) { - const webview = preloadWebviews[url]; - if (webview) { - if (webview.__page__) { - if (!getCurrentPages().find((page) => page === webview.__page__)) { - // 未使用 - webview.close('none'); - } - else { - // 被使用 - webview.__preload__ = false; - } - } - else { - // 未使用 - webview.close('none'); - } - delete preloadWebviews[url]; - } - return webview; - } - function preloadWebview({ url, path, query, }) { - if (!preloadWebviews[url]) { - const routeOptions = JSON.parse(JSON.stringify(__uniRoutes.find((route) => route.path === path))); - preloadWebviews[url] = createWebview({ - path, - routeOptions, - query, - webviewStyle: { - __preload__: true, - __query__: JSON.stringify(query), - }, - }); - } - return preloadWebviews[url]; - } - - function closeWebview(webview, animationType, animationDuration) { - webview[webview.__preload__ ? 'hide' : 'close'](animationType, animationDuration); - } - function showWebview(webview, animationType, animationDuration, showCallback, delay) { - if (typeof delay === 'undefined') { - delay = webview.nvue ? 0 : 100; - } - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('showWebview', 'delay', delay)); - } - const execShowCallback = function () { - if (execShowCallback._called) { - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('execShowCallback', 'prevent')); - } - return; - } - execShowCallback._called = true; - showCallback && showCallback(); - navigateFinish(); - }; - execShowCallback._called = false; - setTimeout(() => { - const timer = setTimeout(() => { - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('showWebview', 'callback', 'timer')); - } - execShowCallback(); - }, animationDuration + 150); - webview.show(animationType, animationDuration, () => { - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('showWebview', 'callback')); - } - if (!execShowCallback._called) { - clearTimeout(timer); - } - execShowCallback(); - }); - }, delay); - } - function backWebview(webview, callback) { - const children = webview.children(); - if (!children || !children.length) { - // 有子 webview - return callback(); - } - // 如果页面有subNvues,切使用了webview组件,则返回时子webview会取错,因此需要做id匹配 - const childWebview = children.find((webview) => webview.id.indexOf(WEBVIEW_ID_PREFIX) === 0) || - children[0]; - childWebview.canBack(({ canBack }) => { - if (canBack) { - childWebview.back(); // webview 返回 - } - else { - callback(); - } - }); - } - - let pendingNavigator = false; - function setPendingNavigator(path, callback, msg) { - pendingNavigator = { - path, - nvue: getRouteMeta(path).isNVue, - callback, - }; - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('setPendingNavigator', path, msg)); - } - } - function closePage(page, animationType, animationDuration) { - removePage(page); - closeWebview(page.$getAppWebview(), animationType, animationDuration); - } - function navigate(path, callback, isAppLaunch = false) { - if (!isAppLaunch && pendingNavigator) { - return console.error(`Waiting to navigate to: ${pendingNavigator.path}, do not operate continuously: ${path}.`); - } - if (__uniConfig.renderer === 'native') { - // 纯原生无需wait逻辑 - // 如果是首页还未初始化,需要等一等,其他无需等待 - if (getCurrentPages().length === 0) { - return setPendingNavigator(path, callback, 'waitForReady'); - } - return callback(); - } - // 未创建 preloadWebview 或 preloadWebview 已被使用 - const waitPreloadWebview = !preloadWebview$1 || (preloadWebview$1 && preloadWebview$1.__uniapp_route); - // 已创建未 loaded - const waitPreloadWebviewReady = preloadWebview$1 && !preloadWebview$1.loaded; - if (waitPreloadWebview || waitPreloadWebviewReady) { - setPendingNavigator(path, callback, waitPreloadWebview ? 'waitForCreate' : 'waitForReady'); - } - else { - callback(); - } - if (waitPreloadWebviewReady) { - onWebviewReady(preloadWebview$1.id, pendingNavigate); - } - } - function pendingNavigate() { - if (!pendingNavigator) { - return; - } - const { callback } = pendingNavigator; - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('pendingNavigate', pendingNavigator.path)); - } - pendingNavigator = false; - return callback(); - } - function navigateFinish() { - if (__uniConfig.renderer === 'native') { - if (!pendingNavigator) { - return; - } - if (pendingNavigator.nvue) { - return pendingNavigate(); - } - return; - } - // 创建预加载 - const preloadWebview = createPreloadWebview(); - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('navigateFinish', 'preloadWebview', preloadWebview.id)); - } - if (!pendingNavigator) { - return; - } - if (pendingNavigator.nvue) { - return pendingNavigate(); - } - preloadWebview.loaded - ? pendingNavigator.callback() - : onWebviewReady(preloadWebview.id, pendingNavigate); - } - - function registerPage({ url, path, query, openType, webview, eventChannel, }) { - // fast 模式,nvue 首页时,会在nvue中主动调用registerPage并传入首页webview,此时初始化一下首页(因为此时可能还未调用registerApp) - if (webview) { - initEntry(); - } - if (preloadWebviews[url]) { - webview = preloadWebviews[url]; - const _webview = webview; - if (_webview.__page__) { - // 该预载页面已处于显示状态,不再使用该预加载页面,直接新开 - if (getCurrentPages().find((page) => page === _webview.__page__)) { - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('uni-app', `preloadWebview(${path},${_webview.id}) already in use`)); - } - webview = undefined; - } - else { - if (eventChannel) { - _webview.__page__.$page.eventChannel = eventChannel; - } - addCurrentPage(_webview.__page__); - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('uni-app', `reuse preloadWebview(${path},${_webview.id})`)); - } - return _webview; - } - } - } - const routeOptions = initRouteOptions(path, openType); - if (!webview) { - webview = createWebview({ path, routeOptions, query }); - } - else { - webview = plus.webview.getWebviewById(webview.id); - webview.nvue = routeOptions.meta.isNVue; - } - routeOptions.meta.id = parseInt(webview.id); - const isTabBar = !!routeOptions.meta.isTabBar; - if (isTabBar) { - tabBar$1.append(webview); - } - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('registerPage', path, webview.id)); - } - initWebview(webview, path, query, routeOptions.meta); - const route = path.substr(1); - webview.__uniapp_route = route; - const pageInstance = initPageInternalInstance(openType, url, query, routeOptions.meta, eventChannel); - initNVueEntryPage(webview); - if (webview.nvue) { - // nvue 时,先启用一个占位 vm - const fakeNVueVm = createNVueVm(parseInt(webview.id), webview, pageInstance); - initPageVm(fakeNVueVm, pageInstance); - addCurrentPage(fakeNVueVm); - } - else { - createPage(parseInt(webview.id), route, query, pageInstance, initPageOptions(routeOptions)); - } - return webview; - } - function initPageOptions({ meta }) { - const statusbarHeight = getStatusbarHeight(); - const { platform, pixelRatio, windowWidth } = getBaseSystemInfo(); - return { - css: true, - route: meta.route, - version: 1, - locale: '', - platform, - pixelRatio, - windowWidth, - disableScroll: meta.disableScroll === true, - onPageScroll: false, - onPageReachBottom: false, - onReachBottomDistance: hasOwn$1(meta, 'onReachBottomDistance') - ? meta.onReachBottomDistance - : ON_REACH_BOTTOM_DISTANCE, - statusbarHeight, - windowTop: meta.navigationBar.type === 'float' ? statusbarHeight + NAVBAR_HEIGHT : 0, - windowBottom: tabBar$1.indexOf(meta.route) >= 0 && tabBar$1.cover ? tabBar$1.height : 0, - }; - } - function initNVueEntryPage(webview) { - const isLaunchNVuePage = webview.id === '1' && webview.nvue; - // 首页是 nvue 时,在 registerPage 时,执行路由堆栈 - if (isLaunchNVuePage) { - if (__uniConfig.splashscreen && - __uniConfig.splashscreen.autoclose && - !__uniConfig.splashscreen.alwaysShowBeforeRender) { - plus.navigator.closeSplashscreen(); - } - __uniConfig.onReady(function () { - navigateFinish(); - }); - } - } - function createNVueVm(pageId, webview, pageInstance) { - return { - $: {}, - onNVuePageCreated(vm, curNVuePage) { - vm.$ = {}; // 补充一个 nvue 的 $ 对象,模拟 vue3 的,不然有部分地方访问了 $ - vm.$getAppWebview = () => webview; - vm.getOpenerEventChannel = curNVuePage.getOpenerEventChannel; - // 替换真实的 nvue 的 vm - initPageVm(vm, pageInstance); - const pages = getAllPages(); - const index = pages.findIndex((p) => p === curNVuePage); - if (index > -1) { - pages.splice(index, 1, vm); - } - if (webview.__preload__) { - webview.__page__ = vm; - } - }, - $getAppWebview() { - return webview; - }, - getOpenerEventChannel() { - if (!pageInstance.eventChannel) { - pageInstance.eventChannel = new EventChannel(pageId); - } - return pageInstance.eventChannel; - }, - }; - } - - const $reLaunch = ({ url }, { resolve, reject }) => { - const { path, query } = parseUrl(url); - navigate(path, () => { - _reLaunch({ - url, - path, - query, - }) - .then(resolve) - .catch(reject); - }); - }; - const reLaunch = defineAsyncApi(API_RE_LAUNCH, $reLaunch, ReLaunchProtocol, ReLaunchOptions); - function _reLaunch({ url, path, query }) { - return new Promise((resolve) => { - // 获取目前所有页面 - const pages = getAllPages().slice(0); - const routeOptions = __uniRoutes.find((route) => route.path === path); - if (routeOptions.meta.isTabBar) { - tabBar$1.switchTab(path.slice(1)); - } - showWebview(registerPage({ - url, - path, - query, - openType: 'reLaunch', - }), 'none', 0, () => { - pages.forEach((page) => closePage(page, 'none')); - resolve(undefined); - }); - setStatusBarStyle(); - }); - } - - const EVENT_BACKBUTTON = 'backbutton'; - function backbuttonListener() { - uni.navigateBack({ - from: 'backbutton', - success() { }, // 传入空方法,避免返回Promise,因为onBackPress可能导致fail - }); - } - const enterOptions = createLaunchOptions(); - const launchOptions = createLaunchOptions(); - function getLaunchOptions() { - return launchOptions; - } - function getEnterOptions() { - return enterOptions; - } - function initEnterOptions({ path, query, referrerInfo, }) { - extend(enterOptions, { - path, - query: query ? parseQuery(query) : {}, - referrerInfo: referrerInfo || {}, - }); - } - function initEnterReLaunch(info) { - __uniConfig.realEntryPagePath = - __uniConfig.realEntryPagePath || __uniConfig.entryPagePath; - __uniConfig.entryPagePath = info.path; - __uniConfig.entryPageQuery = info.query; - $reLaunch({ url: addLeadingSlash(info.path) + info.query }, { resolve() { }, reject() { } }); - } - function initLaunchOptions({ path, query, referrerInfo, }) { - extend(launchOptions, { - path, - query: query ? parseQuery(query) : {}, - referrerInfo: referrerInfo || {}, - }); - extend(enterOptions, launchOptions); - return launchOptions; - } - function parseRedirectInfo() { - const weexPlus = weex.requireModule('plus'); - if (weexPlus.getRedirectInfo) { - const { path, query, extraData, userAction, fromAppid } = weexPlus.getRedirectInfo() || {}; - const referrerInfo = { - appId: fromAppid, - extraData: {}, - }; - if (extraData) { - referrerInfo.extraData = extraData; - } - return { - path, - query: query ? '?' + query : '', - referrerInfo, - userAction, - }; - } - } - - const TEMP_PATH$1 = ''; - - const API_UPX2PX = 'upx2px'; - const Upx2pxProtocol = [ - { - name: 'upx', - type: [Number, String], - required: true, - }, - ]; - - const EPS = 1e-4; - const BASE_DEVICE_WIDTH = 750; - let isIOS = false; - let deviceWidth = 0; - let deviceDPR = 0; - function checkDeviceWidth() { - const { platform, pixelRatio, windowWidth } = getBaseSystemInfo(); - deviceWidth = windowWidth; - deviceDPR = pixelRatio; - isIOS = platform === 'ios'; - } - function checkValue(value, defaultValue) { - const newValue = Number(value); - return isNaN(newValue) ? defaultValue : newValue; - } - const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => { - if (deviceWidth === 0) { - checkDeviceWidth(); - } - number = Number(number); - if (number === 0) { - return 0; - } - let width = newDeviceWidth || deviceWidth; - { - const config = __uniConfig.globalStyle || {}; - // ignore rpxCalcIncludeWidth - const maxWidth = checkValue(config.rpxCalcMaxDeviceWidth, 960); - const baseWidth = checkValue(config.rpxCalcBaseDeviceWidth, 375); - width = width <= maxWidth ? width : baseWidth; - } - let result = (number / BASE_DEVICE_WIDTH) * width; - 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; - }, Upx2pxProtocol); - - const API_ADD_INTERCEPTOR = 'addInterceptor'; - const API_REMOVE_INTERCEPTOR = 'removeInterceptor'; - const AddInterceptorProtocol = [ - { - name: 'method', - type: [String, Object], - required: true, - }, - ]; - const RemoveInterceptorProtocol = AddInterceptorProtocol; - - function mergeInterceptorHook(interceptors, interceptor) { - Object.keys(interceptor).forEach((hook) => { - if (isFunction(interceptor[hook])) { - interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]); - } - }); - } - function removeInterceptorHook(interceptors, interceptor) { - if (!interceptors || !interceptor) { - return; - } - Object.keys(interceptor).forEach((hook) => { - if (isFunction(interceptor[hook])) { - removeHook(interceptors[hook], interceptor[hook]); - } - }); - } - function mergeHook(parentVal, childVal) { - const res = childVal - ? parentVal - ? parentVal.concat(childVal) - : isArray$1(childVal) - ? childVal - : [childVal] - : parentVal; - return res ? dedupeHooks(res) : res; - } - function dedupeHooks(hooks) { - const res = []; - for (let i = 0; i < hooks.length; i++) { - if (res.indexOf(hooks[i]) === -1) { - res.push(hooks[i]); - } - } - return res; - } - function removeHook(hooks, hook) { - if (!hooks) { - return; - } - const index = hooks.indexOf(hook); - if (index !== -1) { - hooks.splice(index, 1); - } - } - const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => { - if (typeof method === 'string' && isPlainObject(interceptor)) { - mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); - } - else if (isPlainObject(method)) { - mergeInterceptorHook(globalInterceptors, method); - } - }, AddInterceptorProtocol); - const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => { - if (typeof method === 'string') { - if (isPlainObject(interceptor)) { - removeInterceptorHook(scopedInterceptors[method], interceptor); - } - else { - delete scopedInterceptors[method]; - } - } - else if (isPlainObject(method)) { - removeInterceptorHook(globalInterceptors, method); - } - }, RemoveInterceptorProtocol); - const interceptors = {}; - - const API_ON = '$on'; - const OnProtocol = [ - { - name: 'event', - type: String, - required: true, - }, - { - name: 'callback', - type: Function, - required: true, - }, - ]; - const API_ONCE = '$once'; - const OnceProtocol = OnProtocol; - const API_OFF = '$off'; - const OffProtocol = [ - { - name: 'event', - type: [String, Array], - }, - { - name: 'callback', - type: Function, - }, - ]; - const API_EMIT = '$emit'; - const EmitProtocol = [ - { - name: 'event', - type: String, - required: true, - }, - ]; - - const emitter = new Emitter(); - const $on = defineSyncApi(API_ON, (name, callback) => { - emitter.on(name, callback); - return () => emitter.off(name, callback); - }, OnProtocol); - const $once = defineSyncApi(API_ONCE, (name, callback) => { - emitter.once(name, callback); - return () => emitter.off(name, callback); - }, OnceProtocol); - const $off = defineSyncApi(API_OFF, (name, callback) => { - if (!name) { - emitter.e = {}; - return; - } - if (!Array.isArray(name)) - name = [name]; - name.forEach((n) => emitter.off(n, callback)); - }, OffProtocol); - const $emit = defineSyncApi(API_EMIT, (name, ...args) => { - emitter.emit(name, ...args); - }, EmitProtocol); - - const validator = [ - { - name: 'id', - type: String, - required: true, - }, - ]; - /* export const API_CREATE_AUDIO_CONTEXT = 'createAudioContext' - export type API_TYPE_CREATE_AUDIO_CONTEXT = typeof uni.createAudioContext - export const CreateAudioContextProtocol = validator */ - const API_CREATE_VIDEO_CONTEXT = 'createVideoContext'; - const API_CREATE_MAP_CONTEXT = 'createMapContext'; - const CreateMapContextProtocol = validator; - const API_CREATE_CANVAS_CONTEXT = 'createCanvasContext'; - const CreateCanvasContextProtocol = [ - { - name: 'canvasId', - type: String, - required: true, - }, - { - name: 'componentInstance', - type: Object, - }, - ]; - const API_CREATE_INNER_AUDIO_CONTEXT = 'createInnerAudioContext'; - const API_CREATE_LIVE_PUSHER_CONTEXT = 'createLivePusherContext'; - const CreateLivePusherContextProtocol = validator.concat({ - name: 'componentInstance', - type: Object, - }); - - const RATES = [0.5, 0.8, 1.0, 1.25, 1.5, 2.0]; - class VideoContext { - constructor(id, pageId) { - this.id = id; - this.pageId = pageId; - } - play() { - operateVideoPlayer(this.id, this.pageId, 'play'); - } - pause() { - operateVideoPlayer(this.id, this.pageId, 'pause'); - } - stop() { - operateVideoPlayer(this.id, this.pageId, 'stop'); - } - seek(position) { - operateVideoPlayer(this.id, this.pageId, 'seek', { - position, - }); - } - sendDanmu(args) { - operateVideoPlayer(this.id, this.pageId, 'sendDanmu', args); - } - playbackRate(rate) { - if (!~RATES.indexOf(rate)) { - rate = 1.0; - } - operateVideoPlayer(this.id, this.pageId, 'playbackRate', { - rate, - }); - } - requestFullScreen(args = {}) { - operateVideoPlayer(this.id, this.pageId, 'requestFullScreen', args); - } - exitFullScreen() { - operateVideoPlayer(this.id, this.pageId, 'exitFullScreen'); - } - showStatusBar() { - operateVideoPlayer(this.id, this.pageId, 'showStatusBar'); - } - hideStatusBar() { - operateVideoPlayer(this.id, this.pageId, 'hideStatusBar'); - } - } - const createVideoContext = defineSyncApi(API_CREATE_VIDEO_CONTEXT, (id, context) => { - if (context) { - return new VideoContext(id, getPageIdByVm(context)); - } - return new VideoContext(id, getPageIdByVm(getCurrentPageVm())); - }); - - const operateMapCallback = (options, res) => { - const errMsg = res.errMsg || ''; - if (new RegExp('\\:\\s*fail').test(errMsg)) { - options.fail && options.fail(res); - } - else { - options.success && options.success(res); - } - options.complete && options.complete(res); - }; - const operateMapWrap = (id, pageId, type, options) => { - operateMap(id, pageId, type, options, (res) => { - options && operateMapCallback(options, res); - }); - }; - class MapContext { - constructor(id, pageId) { - this.id = id; - this.pageId = pageId; - } - getCenterLocation(options) { - operateMapWrap(this.id, this.pageId, 'getCenterLocation', options); - } - moveToLocation(options) { - operateMapWrap(this.id, this.pageId, 'moveToLocation', options); - } - getScale(options) { - operateMapWrap(this.id, this.pageId, 'getScale', options); - } - getRegion(options) { - operateMapWrap(this.id, this.pageId, 'getRegion', options); - } - includePoints(options) { - operateMapWrap(this.id, this.pageId, 'includePoints', options); - } - translateMarker(options) { - operateMapWrap(this.id, this.pageId, 'translateMarker', options); - } - $getAppMap() { - { - return plus.maps.getMapById(this.pageId + '-map-' + this.id); - } - } - addCustomLayer() { } - removeCustomLayer() { } - addGroundOverlay() { } - removeGroundOverlay() { } - updateGroundOverlay() { } - initMarkerCluster() { } - addMarkers() { } - removeMarkers() { } - moveAlong() { } - openMapApp() { } - } - const createMapContext = defineSyncApi(API_CREATE_MAP_CONTEXT, (id, context) => { - if (context) { - return new MapContext(id, getPageIdByVm(context)); - } - return new MapContext(id, getPageIdByVm(getCurrentPageVm())); - }, CreateMapContextProtocol); - - function getInt(name, defaultValue) { - return function (value, params) { - if (value) { - params[name] = Math.round(value); - } - else if (typeof defaultValue !== 'undefined') { - params[name] = defaultValue; - } - }; - } - const formatWidth = getInt('width'); - const formatHeight = getInt('height'); - //#region getImageDataOptions - const API_CANVAS_GET_IMAGE_DATA = 'canvasGetImageData'; - const CanvasGetImageDataOptions = { - formatArgs: { - x: getInt('x'), - y: getInt('y'), - width: formatWidth, - height: formatHeight, - }, - }; - const CanvasGetImageDataProtocol = { - canvasId: { - type: String, - required: true, - }, - x: { - type: Number, - required: true, - }, - y: { - type: Number, - required: true, - }, - width: { - type: Number, - required: true, - }, - height: { - type: Number, - required: true, - }, - }; - //#endregion - //#region putImageData - const API_CANVAS_PUT_IMAGE_DATA = 'canvasPutImageData'; - const CanvasPutImageDataOptions = CanvasGetImageDataOptions; - const CanvasPutImageDataProtocol = - /*#__PURE__*/ extend({ - data: { - type: Uint8ClampedArray, - required: true, - }, - }, CanvasGetImageDataProtocol, { - height: { - type: Number, - }, - }); - //#endregion - //#region toTempFilePath - const fileTypes = { - PNG: 'png', - JPG: 'jpg', - JPEG: 'jpg', - }; - const API_CANVAS_TO_TEMP_FILE_PATH = 'canvasToTempFilePath'; - const CanvasToTempFilePathOptions = { - formatArgs: { - x: getInt('x', 0), - y: getInt('y', 0), - width: formatWidth, - height: formatHeight, - destWidth: getInt('destWidth'), - destHeight: getInt('destHeight'), - fileType(value, params) { - value = (value || '').toUpperCase(); - let type = fileTypes[value]; - if (!type) { - type = fileTypes.PNG; - } - params.fileType = type; - }, - quality(value, params) { - params.quality = value && value > 0 && value < 1 ? value : 1; - }, - }, - }; - const CanvasToTempFilePathProtocol = { - x: Number, - y: Number, - width: Number, - height: Number, - destWidth: Number, - destHeight: Number, - canvasId: { - type: String, - required: true, - }, - fileType: String, - quality: Number, - }; - - //#region import - // import pako from 'pako' - //#endregion - //#region UniServiceJSBridge - function operateCanvas(canvasId, pageId, type, data, callback) { - UniServiceJSBridge.invokeViewMethod(`canvas.${canvasId}`, { - type, - data, - }, pageId, (data) => { - if (callback) - callback(data); - }); - } - //#endregion - //#region methods - var methods1 = ['scale', 'rotate', 'translate', 'setTransform', 'transform']; - var methods2 = [ - 'drawImage', - 'fillText', - 'fill', - 'stroke', - 'fillRect', - 'strokeRect', - 'clearRect', - 'strokeText', - ]; - var methods3 = [ - 'setFillStyle', - 'setTextAlign', - 'setStrokeStyle', - 'setGlobalAlpha', - 'setShadow', - 'setFontSize', - 'setLineCap', - 'setLineJoin', - 'setLineWidth', - 'setMiterLimit', - 'setTextBaseline', - 'setLineDash', - ]; - function measureText(text, font) { - const canvas = document.createElement('canvas'); - const c2d = canvas.getContext('2d'); - c2d.font = font; - return c2d.measureText(text).width || 0; - } - //#endregion - //#region checkColor - const predefinedColor = { - aliceblue: '#f0f8ff', - antiquewhite: '#faebd7', - aqua: '#00ffff', - aquamarine: '#7fffd4', - azure: '#f0ffff', - beige: '#f5f5dc', - bisque: '#ffe4c4', - black: '#000000', - blanchedalmond: '#ffebcd', - blue: '#0000ff', - blueviolet: '#8a2be2', - brown: '#a52a2a', - burlywood: '#deb887', - cadetblue: '#5f9ea0', - chartreuse: '#7fff00', - chocolate: '#d2691e', - coral: '#ff7f50', - cornflowerblue: '#6495ed', - cornsilk: '#fff8dc', - crimson: '#dc143c', - cyan: '#00ffff', - darkblue: '#00008b', - darkcyan: '#008b8b', - darkgoldenrod: '#b8860b', - darkgray: '#a9a9a9', - darkgrey: '#a9a9a9', - darkgreen: '#006400', - darkkhaki: '#bdb76b', - darkmagenta: '#8b008b', - darkolivegreen: '#556b2f', - darkorange: '#ff8c00', - darkorchid: '#9932cc', - darkred: '#8b0000', - darksalmon: '#e9967a', - darkseagreen: '#8fbc8f', - darkslateblue: '#483d8b', - darkslategray: '#2f4f4f', - darkslategrey: '#2f4f4f', - darkturquoise: '#00ced1', - darkviolet: '#9400d3', - deeppink: '#ff1493', - deepskyblue: '#00bfff', - dimgray: '#696969', - dimgrey: '#696969', - dodgerblue: '#1e90ff', - firebrick: '#b22222', - floralwhite: '#fffaf0', - forestgreen: '#228b22', - fuchsia: '#ff00ff', - gainsboro: '#dcdcdc', - ghostwhite: '#f8f8ff', - gold: '#ffd700', - goldenrod: '#daa520', - gray: '#808080', - grey: '#808080', - green: '#008000', - greenyellow: '#adff2f', - honeydew: '#f0fff0', - hotpink: '#ff69b4', - indianred: '#cd5c5c', - indigo: '#4b0082', - ivory: '#fffff0', - khaki: '#f0e68c', - lavender: '#e6e6fa', - lavenderblush: '#fff0f5', - lawngreen: '#7cfc00', - lemonchiffon: '#fffacd', - lightblue: '#add8e6', - lightcoral: '#f08080', - lightcyan: '#e0ffff', - lightgoldenrodyellow: '#fafad2', - lightgray: '#d3d3d3', - lightgrey: '#d3d3d3', - lightgreen: '#90ee90', - lightpink: '#ffb6c1', - lightsalmon: '#ffa07a', - lightseagreen: '#20b2aa', - lightskyblue: '#87cefa', - lightslategray: '#778899', - lightslategrey: '#778899', - lightsteelblue: '#b0c4de', - lightyellow: '#ffffe0', - lime: '#00ff00', - limegreen: '#32cd32', - linen: '#faf0e6', - magenta: '#ff00ff', - maroon: '#800000', - mediumaquamarine: '#66cdaa', - mediumblue: '#0000cd', - mediumorchid: '#ba55d3', - mediumpurple: '#9370db', - mediumseagreen: '#3cb371', - mediumslateblue: '#7b68ee', - mediumspringgreen: '#00fa9a', - mediumturquoise: '#48d1cc', - mediumvioletred: '#c71585', - midnightblue: '#191970', - mintcream: '#f5fffa', - mistyrose: '#ffe4e1', - moccasin: '#ffe4b5', - navajowhite: '#ffdead', - navy: '#000080', - oldlace: '#fdf5e6', - olive: '#808000', - olivedrab: '#6b8e23', - orange: '#ffa500', - orangered: '#ff4500', - orchid: '#da70d6', - palegoldenrod: '#eee8aa', - palegreen: '#98fb98', - paleturquoise: '#afeeee', - palevioletred: '#db7093', - papayawhip: '#ffefd5', - peachpuff: '#ffdab9', - peru: '#cd853f', - pink: '#ffc0cb', - plum: '#dda0dd', - powderblue: '#b0e0e6', - purple: '#800080', - rebeccapurple: '#663399', - red: '#ff0000', - rosybrown: '#bc8f8f', - royalblue: '#4169e1', - saddlebrown: '#8b4513', - salmon: '#fa8072', - sandybrown: '#f4a460', - seagreen: '#2e8b57', - seashell: '#fff5ee', - sienna: '#a0522d', - silver: '#c0c0c0', - skyblue: '#87ceeb', - slateblue: '#6a5acd', - slategray: '#708090', - slategrey: '#708090', - snow: '#fffafa', - springgreen: '#00ff7f', - steelblue: '#4682b4', - tan: '#d2b48c', - teal: '#008080', - thistle: '#d8bfd8', - tomato: '#ff6347', - turquoise: '#40e0d0', - violet: '#ee82ee', - wheat: '#f5deb3', - white: '#ffffff', - whitesmoke: '#f5f5f5', - yellow: '#ffff00', - yellowgreen: '#9acd32', - transparent: '#00000000', - }; - function checkColor(e) { - // 其他开发者适配的echarts会传入一个undefined到这里 - e = e || '#000000'; - var t = null; - if ((t = /^#([0-9|A-F|a-f]{6})$/.exec(e)) != null) { - const n = parseInt(t[1].slice(0, 2), 16); - const o = parseInt(t[1].slice(2, 4), 16); - const r = parseInt(t[1].slice(4), 16); - return [n, o, r, 255]; - } - if ((t = /^#([0-9|A-F|a-f]{3})$/.exec(e)) != null) { - let n = t[1].slice(0, 1); - let o = t[1].slice(1, 2); - let r = t[1].slice(2, 3); - n = parseInt(n + n, 16); - o = parseInt(o + o, 16); - r = parseInt(r + r, 16); - return [n, o, r, 255]; - } - if ((t = /^rgb\((.+)\)$/.exec(e)) != null) { - return t[1] - .split(',') - .map(function (e) { - return Math.min(255, parseInt(e.trim())); - }) - .concat(255); - } - if ((t = /^rgba\((.+)\)$/.exec(e)) != null) { - return t[1].split(',').map(function (e, t) { - return t === 3 - ? Math.floor(255 * parseFloat(e.trim())) - : Math.min(255, parseInt(e.trim())); - }); - } - var i = e.toLowerCase(); - if (hasOwn$1(predefinedColor, i)) { - t = /^#([0-9|A-F|a-f]{6,8})$/.exec(predefinedColor[i]); - const n = parseInt(t[1].slice(0, 2), 16); - const o = parseInt(t[1].slice(2, 4), 16); - const r = parseInt(t[1].slice(4, 6), 16); - let a = parseInt(t[1].slice(6, 8), 16); - a = a >= 0 ? a : 255; - return [n, o, r, a]; - } - console.error('unsupported color:' + e); - return [0, 0, 0, 255]; - } - //#endregion - //#region Class - class CanvasGradient { - constructor(type, data) { - this.type = type; - this.data = data; - this.colorStop = []; - } - addColorStop(position, color) { - this.colorStop.push([position, checkColor(color)]); - } - } - class Pattern { - constructor(image, repetition) { - this.type = 'pattern'; - this.data = image; - this.colorStop = repetition; - } - } - class TextMetrics { - constructor(width) { - this.width = width; - } - } - class CanvasContext { - constructor(id, pageId) { - this.id = id; - this.pageId = pageId; - this.actions = []; - this.path = []; - this.subpath = []; - // this.currentTransform = [] - // this.currentStepAnimates = [] - this.drawingState = []; - this.state = { - lineDash: [0, 0], - shadowOffsetX: 0, - shadowOffsetY: 0, - shadowBlur: 0, - shadowColor: [0, 0, 0, 0], - font: '10px sans-serif', - fontSize: 10, - fontWeight: 'normal', - fontStyle: 'normal', - fontFamily: 'sans-serif', - }; - } - draw(reserve = false, callback) { - var actions = [...this.actions]; - this.actions = []; - this.path = []; - operateCanvas(this.id, this.pageId, 'actionsChanged', { - actions, - reserve, - }, callback); - } - createLinearGradient(x0, y0, x1, y1) { - return new CanvasGradient('linear', [x0, y0, x1, y1]); - } - createCircularGradient(x, y, r) { - return new CanvasGradient('radial', [x, y, r]); - } - createPattern(image, repetition) { - if (undefined === repetition) { - console.error("Failed to execute 'createPattern' on 'CanvasContext': 2 arguments required, but only 1 present."); - } - else if (['repeat', 'repeat-x', 'repeat-y', 'no-repeat'].indexOf(repetition) < 0) { - console.error("Failed to execute 'createPattern' on 'CanvasContext': The provided type ('" + - repetition + - "') is not one of 'repeat', 'no-repeat', 'repeat-x', or 'repeat-y'."); - } - else { - return new Pattern(image, repetition); - } - } - measureText(text) { - const font = this.state.font; - let width = 0; - { - const webview = plus.webview - .all() - .find((webview) => webview.getURL().endsWith('www/__uniappview.html')); - if (webview) { - width = Number(webview.evalJSSync(`(${measureText.toString()})(${JSON.stringify(text)},${JSON.stringify(font)})`)); - } - } - return new TextMetrics(width); - } - save() { - this.actions.push({ - method: 'save', - data: [], - }); - this.drawingState.push(this.state); - } - restore() { - this.actions.push({ - method: 'restore', - data: [], - }); - this.state = this.drawingState.pop() || { - lineDash: [0, 0], - shadowOffsetX: 0, - shadowOffsetY: 0, - shadowBlur: 0, - shadowColor: [0, 0, 0, 0], - font: '10px sans-serif', - fontSize: 10, - fontWeight: 'normal', - fontStyle: 'normal', - fontFamily: 'sans-serif', - }; - } - beginPath() { - this.path = []; - this.subpath = []; - } - moveTo(x, y) { - this.path.push({ - method: 'moveTo', - data: [x, y], - }); - this.subpath = [[x, y]]; - } - lineTo(x, y) { - if (this.path.length === 0 && this.subpath.length === 0) { - this.path.push({ - method: 'moveTo', - data: [x, y], - }); - } - else { - this.path.push({ - method: 'lineTo', - data: [x, y], - }); - } - this.subpath.push([x, y]); - } - quadraticCurveTo(cpx, cpy, x, y) { - this.path.push({ - method: 'quadraticCurveTo', - data: [cpx, cpy, x, y], - }); - this.subpath.push([x, y]); - } - bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) { - this.path.push({ - method: 'bezierCurveTo', - data: [cp1x, cp1y, cp2x, cp2y, x, y], - }); - this.subpath.push([x, y]); - } - arc(x, y, r, sAngle, eAngle, counterclockwise = false) { - this.path.push({ - method: 'arc', - data: [x, y, r, sAngle, eAngle, counterclockwise], - }); - this.subpath.push([x, y]); - } - rect(x, y, width, height) { - this.path.push({ - method: 'rect', - data: [x, y, width, height], - }); - this.subpath = [[x, y]]; - } - arcTo(x1, y1, x2, y2, radius) { - this.path.push({ - method: 'arcTo', - data: [x1, y1, x2, y2, radius], - }); - this.subpath.push([x2, y2]); - } - clip() { - this.actions.push({ - method: 'clip', - data: [...this.path], - }); - } - closePath() { - this.path.push({ - method: 'closePath', - data: [], - }); - if (this.subpath.length) { - this.subpath = [this.subpath.shift()]; - } - } - clearActions() { - this.actions = []; - this.path = []; - this.subpath = []; - } - getActions() { - var actions = [...this.actions]; - this.clearActions(); - return actions; - } - set lineDashOffset(value) { - this.actions.push({ - method: 'setLineDashOffset', - data: [value], - }); - } - set globalCompositeOperation(type) { - this.actions.push({ - method: 'setGlobalCompositeOperation', - data: [type], - }); - } - set shadowBlur(level) { - this.actions.push({ - method: 'setShadowBlur', - data: [level], - }); - } - set shadowColor(color) { - this.actions.push({ - method: 'setShadowColor', - data: [color], - }); - } - set shadowOffsetX(x) { - this.actions.push({ - method: 'setShadowOffsetX', - data: [x], - }); - } - set shadowOffsetY(y) { - this.actions.push({ - method: 'setShadowOffsetY', - data: [y], - }); - } - set font(value) { - var self = this; - this.state.font = value; - // eslint-disable-next-line - var fontFormat = value.match(/^(([\w\-]+\s)*)(\d+r?px)(\/(\d+\.?\d*(r?px)?))?\s+(.*)/); - if (fontFormat) { - var style = fontFormat[1].trim().split(/\s/); - var fontSize = parseFloat(fontFormat[3]); - var fontFamily = fontFormat[7]; - var actions = []; - style.forEach(function (value, index) { - if (['italic', 'oblique', 'normal'].indexOf(value) > -1) { - actions.push({ - method: 'setFontStyle', - data: [value], - }); - self.state.fontStyle = value; - } - else if (['bold', 'normal'].indexOf(value) > -1) { - actions.push({ - method: 'setFontWeight', - data: [value], - }); - self.state.fontWeight = value; - } - else if (index === 0) { - actions.push({ - method: 'setFontStyle', - data: ['normal'], - }); - self.state.fontStyle = 'normal'; - } - else if (index === 1) { - pushAction(); - } - }); - if (style.length === 1) { - pushAction(); - } - style = actions - .map(function (action) { - return action.data[0]; - }) - .join(' '); - this.state.fontSize = fontSize; - this.state.fontFamily = fontFamily; - this.actions.push({ - method: 'setFont', - data: [`${style} ${fontSize}px ${fontFamily}`], - }); - } - else { - console.warn("Failed to set 'font' on 'CanvasContext': invalid format."); - } - function pushAction() { - actions.push({ - method: 'setFontWeight', - data: ['normal'], - }); - self.state.fontWeight = 'normal'; - } - } - get font() { - return this.state.font; - } - set fillStyle(color) { - this.setFillStyle(color); - } - set strokeStyle(color) { - this.setStrokeStyle(color); - } - set globalAlpha(value) { - value = Math.floor(255 * parseFloat(value)); - this.actions.push({ - method: 'setGlobalAlpha', - data: [value], - }); - } - set textAlign(align) { - this.actions.push({ - method: 'setTextAlign', - data: [align], - }); - } - set lineCap(type) { - this.actions.push({ - method: 'setLineCap', - data: [type], - }); - } - set lineJoin(type) { - this.actions.push({ - method: 'setLineJoin', - data: [type], - }); - } - set lineWidth(value) { - this.actions.push({ - method: 'setLineWidth', - data: [value], - }); - } - set miterLimit(value) { - this.actions.push({ - method: 'setMiterLimit', - data: [value], - }); - } - set textBaseline(type) { - this.actions.push({ - method: 'setTextBaseline', - data: [type], - }); - } - } - const initCanvasContextProperty = /*#__PURE__*/ once(() => { - [...methods1, ...methods2].forEach(function (method) { - function get(method) { - switch (method) { - case 'fill': - case 'stroke': - return function () { - // @ts-ignore - this.actions.push({ - method: method + 'Path', - // @ts-ignore - data: [...this.path], - }); - }; - case 'fillRect': - return function (x, y, width, height) { - // @ts-ignore - this.actions.push({ - method: 'fillPath', - data: [ - { - method: 'rect', - data: [x, y, width, height], - }, - ], - }); - }; - case 'strokeRect': - return function (x, y, width, height) { - // @ts-ignore - this.actions.push({ - method: 'strokePath', - data: [ - { - method: 'rect', - data: [x, y, width, height], - }, - ], - }); - }; - case 'fillText': - case 'strokeText': - return function (text, x, y, maxWidth) { - var data = [text.toString(), x, y]; - if (typeof maxWidth === 'number') { - data.push(maxWidth); - } - // @ts-ignore - this.actions.push({ - method, - data, - }); - }; - case 'drawImage': - return function (imageResource, dx, dy, dWidth, dHeight, sx, sy, sWidth, sHeight) { - if (sHeight === undefined) { - sx = dx; - sy = dy; - sWidth = dWidth; - sHeight = dHeight; - dx = undefined; - dy = undefined; - dWidth = undefined; - dHeight = undefined; - } - var data; - function isNumber(e) { - return typeof e === 'number'; - } - data = - isNumber(dx) && - isNumber(dy) && - isNumber(dWidth) && - isNumber(dHeight) - ? [ - imageResource, - sx, - sy, - sWidth, - sHeight, - dx, - dy, - dWidth, - dHeight, - ] - : isNumber(sWidth) && isNumber(sHeight) - ? [imageResource, sx, sy, sWidth, sHeight] - : [imageResource, sx, sy]; - // @ts-ignore - this.actions.push({ - method, - data, - }); - }; - default: - return function (...data) { - // @ts-ignore - this.actions.push({ - method, - data, - }); - }; - } - } - CanvasContext.prototype[method] = get(method); - }); - methods3.forEach(function (method) { - function get(method) { - switch (method) { - case 'setFillStyle': - case 'setStrokeStyle': - return function (color) { - if (typeof color !== 'object') { - // @ts-ignore - this.actions.push({ - method, - data: ['normal', checkColor(color)], - }); - } - else { - // @ts-ignore - this.actions.push({ - method, - data: [color.type, color.data, color.colorStop], - }); - } - }; - case 'setGlobalAlpha': - return function (alpha) { - alpha = Math.floor(255 * parseFloat(alpha)); - // @ts-ignore - this.actions.push({ - method, - data: [alpha], - }); - }; - case 'setShadow': - return function (offsetX, offsetY, blur, color) { - color = checkColor(color); - // @ts-ignore - this.actions.push({ - method, - data: [offsetX, offsetY, blur, color], - }); - // @ts-ignore - this.state.shadowBlur = blur; - // @ts-ignore - this.state.shadowColor = color; - // @ts-ignore - this.state.shadowOffsetX = offsetX; - // @ts-ignore - this.state.shadowOffsetY = offsetY; - }; - case 'setLineDash': - return function (pattern, offset) { - pattern = pattern || [0, 0]; - offset = offset || 0; - // @ts-ignore - this.actions.push({ - method, - data: [pattern, offset], - }); - // @ts-ignore - this.state.lineDash = pattern; - }; - case 'setFontSize': - return function (fontSize) { - // @ts-ignore - this.state.font = this.state.font.replace(/\d+\.?\d*px/, fontSize + 'px'); - // @ts-ignore - this.state.fontSize = fontSize; - // @ts-ignore - this.actions.push({ - method, - data: [fontSize], - }); - }; - default: - return function (...data) { - // @ts-ignore - this.actions.push({ - method, - data, - }); - }; - } - } - CanvasContext.prototype[method] = get(method); - }); - }); - const createCanvasContext = defineSyncApi(API_CREATE_CANVAS_CONTEXT, (canvasId, componentInstance) => { - initCanvasContextProperty(); - if (componentInstance) { - return new CanvasContext(canvasId, getPageIdByVm(componentInstance)); - } - const pageId = getPageIdByVm(getCurrentPageVm()); - if (pageId) { - return new CanvasContext(canvasId, pageId); - } - else { - UniServiceJSBridge.emit(ON_ERROR, 'createCanvasContext:fail'); - } - }, CreateCanvasContextProtocol); - const canvasGetImageData = defineAsyncApi(API_CANVAS_GET_IMAGE_DATA, ({ canvasId, x, y, width, height }, { resolve, reject }) => { - const pageId = getPageIdByVm(getCurrentPageVm()); - if (!pageId) { - reject(); - return; - } - function callback(data) { - if (data.errMsg && data.errMsg.indexOf('fail') !== -1) { - reject('', data); - return; - } - let imgData = data.data; - if (imgData && imgData.length) { - if (data.compressed) { - Promise.resolve().then(function () { return pako_esm; }).then((pako) => { - imgData = pako.inflateRaw(imgData); - delete data.compressed; - data.data = new Uint8ClampedArray(imgData); - resolve(data); - }); - } - data.data = new Uint8ClampedArray(imgData); - } - resolve(data); - } - operateCanvas(canvasId, pageId, 'getImageData', { - x, - y, - width, - height, - }, callback); - }, CanvasGetImageDataProtocol, CanvasGetImageDataOptions); - const canvasPutImageData = defineAsyncApi(API_CANVAS_PUT_IMAGE_DATA, ({ canvasId, data, x, y, width, height }, { resolve, reject }) => { - var pageId = getPageIdByVm(getCurrentPageVm()); - if (!pageId) { - reject(); - return; - } - let compressed; - const operate = () => { - operateCanvas(canvasId, pageId, 'putImageData', { - data, - x, - y, - width, - height, - compressed, - }, (data) => { - if (data.errMsg && data.errMsg.indexOf('fail') !== -1) { - reject(); - return; - } - resolve(data); - }); - }; - // iOS真机非调试模式压缩太慢暂时排除 - if ((plus.os.name !== 'iOS' || typeof __WEEX_DEVTOOL__ === 'boolean')) { - return Promise.resolve().then(function () { return pako_esm; }).then((pako) => { - data = pako.deflateRaw(data, { to: 'string' }); - compressed = true; - operate(); - }); - } - // fix ... fix what? - data = Array.prototype.slice.call(data); - operate(); - }, CanvasPutImageDataProtocol, CanvasPutImageDataOptions); - const canvasToTempFilePath = defineAsyncApi(API_CANVAS_TO_TEMP_FILE_PATH, ({ x = 0, y = 0, width, height, destWidth, destHeight, canvasId, fileType, quality, }, { resolve, reject }) => { - var pageId = getPageIdByVm(getCurrentPageVm()); - if (!pageId) { - reject(); - return; - } - const dirname = `${TEMP_PATH$1}/canvas`; - operateCanvas(canvasId, pageId, 'toTempFilePath', { - x, - y, - width, - height, - destWidth, - destHeight, - fileType, - quality, - dirname, - }, (res) => { - if (res.errMsg && res.errMsg.indexOf('fail') !== -1) { - reject('', res); - return; - } - resolve(res); - }); - }, CanvasToTempFilePathProtocol, CanvasToTempFilePathOptions); - - //#endregion - /** - * 可以批量设置的监听事件 - */ - const innerAudioContextEventNames = [ - 'onCanplay', - 'onPlay', - 'onPause', - 'onStop', - 'onEnded', - 'onTimeUpdate', - 'onError', - 'onWaiting', - 'onSeeking', - 'onSeeked', - ]; - const innerAudioContextOffEventNames = [ - 'offCanplay', - 'offPlay', - 'offPause', - 'offStop', - 'offEnded', - 'offTimeUpdate', - 'offError', - 'offWaiting', - 'offSeeking', - 'offSeeked', - ]; - - const defaultOptions = { - thresholds: [0], - initialRatio: 0, - observeAll: false, - }; - const MARGINS = ['top', 'right', 'bottom', 'left']; - let reqComponentObserverId$1 = 1; - function normalizeRootMargin(margins = {}) { - return MARGINS.map((name) => `${Number(margins[name]) || 0}px`).join(' '); - } - class ServiceIntersectionObserver { - constructor(component, options) { - this._pageId = getPageIdByVm(component); - this._component = component; - this._options = extend({}, defaultOptions, options); - } - relativeTo(selector, margins) { - this._options.relativeToSelector = selector; - this._options.rootMargin = normalizeRootMargin(margins); - return this; - } - relativeToViewport(margins) { - this._options.relativeToSelector = undefined; - this._options.rootMargin = normalizeRootMargin(margins); - return this; - } - observe(selector, callback) { - if (!isFunction(callback)) { - return; - } - this._options.selector = selector; - this._reqId = reqComponentObserverId$1++; - addIntersectionObserver({ - reqId: this._reqId, - component: this._component, - options: this._options, - callback, - }, this._pageId); - } - disconnect() { - this._reqId && - removeIntersectionObserver({ reqId: this._reqId, component: this._component }, this._pageId); - } - } - const createIntersectionObserver = defineSyncApi('createIntersectionObserver', (context, options) => { - if (context && !getPageIdByVm(context)) { - options = context; - context = null; - } - if (context) { - return new ServiceIntersectionObserver(context, options); - } - return new ServiceIntersectionObserver(getCurrentPageVm(), options); - }); - - let reqComponentObserverId = 1; - class ServiceMediaQueryObserver { - constructor(component) { - this._pageId = component.$page && component.$page.id; - this._component = component; - } - observe(options, callback) { - if (!isFunction(callback)) { - return; - } - this._reqId = reqComponentObserverId++; - addMediaQueryObserver({ - reqId: this._reqId, - component: this._component, - options, - callback, - }, this._pageId); - } - disconnect() { - this._reqId && - removeMediaQueryObserver({ - reqId: this._reqId, - component: this._component, - }, this._pageId); - } - } - const createMediaQueryObserver = defineSyncApi('createMediaQueryObserver', (context) => { - if (context && !getPageIdByVm(context)) { - context = null; - } - if (context) { - return new ServiceMediaQueryObserver(context); - } - return new ServiceMediaQueryObserver(getCurrentPageVm()); - }); - - // let eventReady = false - let index$3 = 0; - let optionsCache = {}; - function operateEditor(componentId, pageId, type, options) { - const data = { options }; - const needCallOptions = options && - ('success' in options || 'fail' in options || 'complete' in options); - if (needCallOptions) { - const callbackId = String(index$3++); - data.callbackId = callbackId; - optionsCache[callbackId] = options; - } - UniServiceJSBridge.invokeViewMethod(`editor.${componentId}`, { - type, - data, - }, pageId, ({ callbackId, data }) => { - if (needCallOptions) { - callOptions(optionsCache[callbackId], data); - delete optionsCache[callbackId]; - } - }); - } - class EditorContext { - constructor(id, pageId) { - this.id = id; - this.pageId = pageId; - } - format(name, value) { - this._exec('format', { - name, - value, - }); - } - insertDivider() { - this._exec('insertDivider'); - } - insertImage(options) { - this._exec('insertImage', options); - } - insertText(options) { - this._exec('insertText', options); - } - setContents(options) { - this._exec('setContents', options); - } - getContents(options) { - this._exec('getContents', options); - } - clear(options) { - this._exec('clear', options); - } - removeFormat(options) { - this._exec('removeFormat', options); - } - undo(options) { - this._exec('undo', options); - } - redo(options) { - this._exec('redo', options); - } - blur(options) { - this._exec('blur', options); - } - getSelectionText(options) { - this._exec('getSelectionText', options); - } - scrollIntoView(options) { - this._exec('scrollIntoView', options); - } - _exec(method, options) { - operateEditor(this.id, this.pageId, method, options); - } - } - - const ContextClasss = { - canvas: CanvasContext, - map: MapContext, - video: VideoContext, - editor: EditorContext, - }; - function convertContext(result) { - if (result && result.contextInfo) { - const { id, type, page } = result.contextInfo; - const ContextClass = ContextClasss[type]; - result.context = new ContextClass(id, page); - delete result.contextInfo; - } - } - class NodesRef { - constructor(selectorQuery, component, selector, single) { - this._selectorQuery = selectorQuery; - this._component = component; - this._selector = selector; - this._single = single; - } - boundingClientRect(callback) { - this._selectorQuery._push(this._selector, this._component, this._single, { - id: true, - dataset: true, - rect: true, - size: true, - }, callback); - return this._selectorQuery; - } - fields(fields, callback) { - this._selectorQuery._push(this._selector, this._component, this._single, fields, callback); - return this._selectorQuery; - } - scrollOffset(callback) { - this._selectorQuery._push(this._selector, this._component, this._single, { - id: true, - dataset: true, - scrollOffset: true, - }, callback); - return this._selectorQuery; - } - context(callback) { - this._selectorQuery._push(this._selector, this._component, this._single, { - context: true, - }, callback); - return this._selectorQuery; - } - } - class SelectorQuery { - constructor(page) { - this._component = undefined; - this._page = page; - this._queue = []; - this._queueCb = []; - } - exec(callback) { - requestComponentInfo(this._page, this._queue, (res) => { - const queueCbs = this._queueCb; - res.forEach((result, index) => { - if (Array.isArray(result)) { - result.forEach(convertContext); - } - else { - convertContext(result); - } - const queueCb = queueCbs[index]; - if (typeof queueCb === 'function') { - queueCb.call(this, result); - } - }); - // isFn(callback) && - if (typeof callback === 'function') { - callback.call(this, res); - } - }); - // TODO - return this._nodesRef; - } - in(component) { - this._component = component || undefined; - return this; - } - select(selector) { - return (this._nodesRef = new NodesRef(this, this._component, selector, true)); - } - selectAll(selector) { - return (this._nodesRef = new NodesRef(this, this._component, selector, false)); - } - selectViewport() { - return (this._nodesRef = new NodesRef(this, null, '', true)); - } - _push(selector, component, single, fields, callback) { - this._queue.push({ - component, - selector, - single, - fields, - }); - this._queueCb.push(callback); - } - } - const createSelectorQuery = (defineSyncApi('createSelectorQuery', (context) => { - if (context && !getPageIdByVm(context)) { - context = null; - } - return new SelectorQuery(context || getCurrentPageVm()); - })); - - // import { elemInArray } from '../../helpers/protocol' - const API_CREATE_ANIMATION = 'createAnimation'; - // const timingFunctions: API_TYPE_CREATE_ANIMATION_Timing_Function[] = [ - // 'linear', - // 'ease', - // 'ease-in', - // 'ease-in-out', - // 'ease-out', - // 'step-start', - // 'step-end', - // ] - const CreateAnimationOptions = { - // 目前参数校验不支持此api校验 - formatArgs: { - /* duration: 400, - timingFunction(timingFunction, params) { - params.timingFunction = elemInArray(timingFunction, timingFunctions) - }, - delay: 0, - transformOrigin: '50% 50% 0', */ - }, - }; - const CreateAnimationProtocol = { - duration: Number, - timingFunction: String, - delay: Number, - transformOrigin: String, - }; - - const defaultOption = { - duration: 400, - timingFunction: 'linear', - delay: 0, - transformOrigin: '50% 50% 0', - }; - class MPAnimation { - constructor(option) { - this.actions = []; - this.currentTransform = {}; - this.currentStepAnimates = []; - this.option = extend({}, defaultOption, option); - } - _getOption(option) { - const _option = { - transition: extend({}, this.option, option), - transformOrigin: '', - }; - _option.transformOrigin = _option.transition.transformOrigin; - delete _option.transition.transformOrigin; - return _option; - } - _pushAnimates(type, args) { - this.currentStepAnimates.push({ - type: type, - args: args, - }); - } - _converType(type) { - return type.replace(/[A-Z]/g, (text) => { - return `-${text.toLowerCase()}`; - }); - } - _getValue(value) { - return typeof value === 'number' ? `${value}px` : value; - } - export() { - const actions = this.actions; - this.actions = []; - return { - actions, - }; - } - step(option) { - this.currentStepAnimates.forEach((animate) => { - if (animate.type !== 'style') { - this.currentTransform[animate.type] = animate; - } - else { - this.currentTransform[`${animate.type}.${animate.args[0]}`] = animate; - } - }); - this.actions.push({ - animates: Object.values(this.currentTransform), - option: this._getOption(option), - }); - this.currentStepAnimates = []; - return this; - } - } - const initAnimationProperty = /*#__PURE__*/ once(() => { - const animateTypes1 = [ - 'matrix', - 'matrix3d', - 'rotate', - 'rotate3d', - 'rotateX', - 'rotateY', - 'rotateZ', - 'scale', - 'scale3d', - 'scaleX', - 'scaleY', - 'scaleZ', - 'skew', - 'skewX', - 'skewY', - 'translate', - 'translate3d', - 'translateX', - 'translateY', - 'translateZ', - ]; - const animateTypes2 = ['opacity', 'backgroundColor']; - const animateTypes3 = ['width', 'height', 'left', 'right', 'top', 'bottom']; - animateTypes1.concat(animateTypes2, animateTypes3).forEach((type) => { - MPAnimation.prototype[type] = function (...args) { - if (animateTypes2.concat(animateTypes3).includes(type)) { - this._pushAnimates('style', [ - this._converType(type), - animateTypes3.includes(type) ? this._getValue(args[0]) : args[0], - ]); - } - else { - this._pushAnimates(type, args); - } - return this; - }; - }); - }); - const createAnimation = defineSyncApi(API_CREATE_ANIMATION, (option) => { - initAnimationProperty(); - return new MPAnimation(option); - }, CreateAnimationProtocol, CreateAnimationOptions); - - const API_ON_TAB_BAR_MID_BUTTON_TAP = 'onTabBarMidButtonTap'; - const onTabBarMidButtonTap = defineOnApi(API_ON_TAB_BAR_MID_BUTTON_TAP, () => { - // noop - }); - - const API_ON_WINDOW_RESIZE = 'onWindowResize'; - const API_OFF_WINDOW_RESIZE = 'offWindowResize'; - - /** - * 监听窗口大小变化 - */ - const onWindowResize = defineOnApi(API_ON_WINDOW_RESIZE, () => { - // 生命周期包括onResize,框架直接监听resize - // window.addEventListener('resize', onResize) - }); - /** - * 取消监听窗口大小变化 - */ - const offWindowResize = defineOffApi(API_OFF_WINDOW_RESIZE, () => { - // window.removeEventListener('resize', onResize) - }); - - const API_SET_LOCALE = 'setLocale'; - const API_GET_LOCALE = 'getLocale'; - const API_ON_LOCALE_CHANGE = 'onLocaleChange'; - const getLocale = defineSyncApi(API_GET_LOCALE, () => { - // 优先使用 $locale - const app = getApp({ allowDefault: true }); - if (app && app.$vm) { - return app.$vm.$locale; - } - return useI18n().getLocale(); - }); - const onLocaleChange = defineOnApi(API_ON_LOCALE_CHANGE, () => { }); - const setLocale = defineSyncApi(API_SET_LOCALE, (locale) => { - const app = getApp(); - if (!app) { - return false; - } - const oldLocale = app.$vm.$locale; - if (oldLocale !== locale) { - app.$vm.$locale = locale; - { - const pages = getCurrentPages(); - pages.forEach((page) => { - UniServiceJSBridge.publishHandler(API_SET_LOCALE, locale, page.$page.id); - }); - weex.requireModule('plus').setLanguage(locale); - } - // 执行 uni.onLocaleChange - UniServiceJSBridge.invokeOnCallback(API_ON_LOCALE_CHANGE, { locale }); - return true; - } - return false; - }); - - const API_SET_PAGE_META = 'setPageMeta'; - const setPageMeta = defineAsyncApi(API_SET_PAGE_META, (options, { resolve }) => { - resolve(setCurrentPageMeta(getCurrentPageVm(), options)); - }); - - const API_GET_SELECTED_TEXT_RANGE = 'getSelectedTextRange'; - - const getSelectedTextRange = defineAsyncApi(API_GET_SELECTED_TEXT_RANGE, (_, { resolve, reject }) => { - UniServiceJSBridge.invokeViewMethod('getSelectedTextRange', {}, getCurrentPageId(), (res) => { - if (typeof res.end === 'undefined' && - typeof res.start === 'undefined') { - reject('no focused'); - } - else { - resolve(res); - } - }); - }); - - const appLaunchHooks = []; - function onAppLaunch(hook) { - const app = getApp({ allowDefault: true }); - if (app && app.$vm) { - return vue.injectHook(ON_LAUNCH, hook, app.$vm.$); - } - appLaunchHooks.push(hook); - } - function injectAppLaunchHooks(appInstance) { - appLaunchHooks.forEach((hook) => { - vue.injectHook(ON_LAUNCH, hook, appInstance); - }); - } - const API_GET_ENTER_OPTIONS_SYNC = 'getEnterOptionsSync'; - const getEnterOptionsSync = defineSyncApi(API_GET_ENTER_OPTIONS_SYNC, () => { - return getEnterOptions(); - }); - const API_GET_LAUNCH_OPTIONS_SYNC = 'getLaunchOptionsSync'; - const getLaunchOptionsSync = defineSyncApi(API_GET_LAUNCH_OPTIONS_SYNC, () => { - return getLaunchOptions(); - }); - - const API_GET_BACKGROUND_AUDIO_MANAGER = 'getBackgroundAudioManager'; - - const API_MAKE_PHONE_CALL = 'makePhoneCall'; - const MakePhoneCallProtocol = { - phoneNumber: String, - }; - - const API_ADD_PHONE_CONTACT = 'addPhoneContact'; - - const API_GET_CLIPBOARD_DATA = 'getClipboardData'; - const API_SET_CLIPBOARD_DATA = 'setClipboardData'; - const SetClipboardDataOptions = { - formatArgs: { - showToast: true, - }, - beforeInvoke() { - initI18nSetClipboardDataMsgsOnce(); - }, - beforeSuccess(res, params) { - if (!params.showToast) - return; - const { t } = useI18n(); - const title = t('uni.setClipboardData.success'); - if (title) { - uni.showToast({ - title: title, - icon: 'success', - mask: false, - }); - } - }, - }; - const SetClipboardDataProtocol = { - data: { - type: String, - required: true, - }, - showToast: { - type: Boolean, - }, - }; - - const API_ON_ACCELEROMETER = 'onAccelerometer'; - const API_OFF_ACCELEROMETER = 'offAccelerometer'; - const API_START_ACCELEROMETER = 'startAccelerometer'; - const API_STOP_ACCELEROMETER = 'stopAccelerometer'; - - const API_ON_COMPASS = 'onCompass'; - const API_OFF_COMPASS = 'offCompass'; - const API_START_COMPASS = 'startCompass'; - const API_STOP_COMPASS = 'stopCompass'; - - const API_VIBRATE_SHORT = 'vibrateShort'; - const API_VIBRATE_LONG = 'vibrateLong'; - - const API_ON_BLUETOOTH_DEVICE_FOUND = 'onBluetoothDeviceFound'; - const API_ON_BLUETOOTH_ADAPTER_STATE_CHANGE = 'onBluetoothAdapterStateChange'; - const API_ON_BLE_CONNECTION_STATE_CHANGE = 'onBLEConnectionStateChange'; - const API_ON_BLE_CHARACTERISTIC_VALUE_CHANGE = 'onBLECharacteristicValueChange'; - const API_START_BLUETOOTH_DEVICES_DISCOVERY = 'startBluetoothDevicesDiscovery'; - const StartBluetoothDevicesDiscoveryProtocol = { - services: Array, - allowDuplicatesKey: Boolean, - interval: Number, - }; - const API_GET_CONNECTED_BLUETOOTH_DEVICES = 'getConnectedBluetoothDevices'; - const GetConnectedBluetoothDevicesProtocol = { - services: { - type: Array, - required: true, - }, - }; - const API_CREATE_BLE_CONNECTION = 'createBLEConnection'; - const CreateBLEConnectionProtocol = { - deviceId: { - type: String, - required: true, - }, - }; - const API_CLOSE_BLE_CONNECTION = 'closeBLEConnection'; - const CloseBLEConnectionProtocol = { - deviceId: { - type: String, - required: true, - }, - }; - const API_GET_BLE_DEVICE_SERVICES = 'getBLEDeviceServices'; - const GetBLEDeviceServicesProtocol = { - deviceId: { - type: String, - required: true, - }, - }; - const API_GET_BLE_DEVICE_CHARACTERISTICS = 'getBLEDeviceCharacteristics'; - const GetBLEDeviceCharacteristicsProtocol = { - deviceId: { - type: String, - required: true, - }, - serviceId: { - type: String, - required: true, - }, - }; - const API_NOTIFY_BLE_CHARACTERISTIC_VALUE_CHANGE = 'notifyBLECharacteristicValueChange'; - const NotifyBLECharacteristicValueChangeProtocol = { - deviceId: { - type: String, - required: true, - }, - serviceId: { - type: String, - required: true, - }, - characteristicId: { - type: String, - required: true, - }, - state: { - type: Boolean, - required: true, - }, - }; - const API_READ_BLE_CHARACTERISTIC_VALUE = 'readBLECharacteristicValue'; - const ReadBLECharacteristicValueProtocol = { - deviceId: { - type: String, - required: true, - }, - serviceId: { - type: String, - required: true, - }, - characteristicId: { - type: String, - required: true, - }, - }; - const API_WRITE_BLE_CHARACTERISTIC_VALUE = 'writeBLECharacteristicValue'; - const WriteBLECharacteristicValueProtocol = { - deviceId: { - type: String, - required: true, - }, - serviceId: { - type: String, - required: true, - }, - characteristicId: { - type: String, - required: true, - }, - value: { - type: Array, - required: true, - }, - }; - const API_SET_BLE_MTU = 'setBLEMTU'; - const SetBLEMTUProtocol = { - deviceId: { - type: String, - required: true, - }, - mtu: { - type: Number, - required: true, - }, - }; - const API_GET_BLE_DEVICE_RSSI = 'getBLEDeviceRSSI'; - const GetBLEDeviceRSSIProtocol = { - deviceId: { - type: String, - required: true, - }, - }; - - const API_ON_BEACON_UPDATE = 'onBeaconUpdate'; - const API_ON_BEACON_SERVICE_CHANGE = 'onBeaconServiceChange'; - const API_GET_BEACONS = 'getBeacons'; - const API_START_BEACON_DISCOVERY = 'startBeaconDiscovery'; - const StartBeaconDiscoveryProtocol = { - uuids: { - type: Array, - required: true, - }, - }; - const API_STOP_BEACON_DISCOVERY = 'stopBeaconDiscovery'; - - const API_GET_SCREEN_BRIGHTNESS = 'getScreenBrightness'; - const API_SET_SCREEN_BRIGHTNESS = 'setScreenBrightness'; - const API_SET_KEEP_SCREEN_ON = 'setKeepScreenOn'; - - const API_CHECK_IS_SUPPORT_SOTER_AUTHENTICATION = 'soterAuthentication'; - const API_CHECK_IS_SOTER_ENROLLED_IN_DEVICE = 'checkIsSoterEnrolledInDevice'; - const CheckAuthModes = [ - 'fingerPrint', - 'facial', - 'speech', - ]; - const CheckIsSoterEnrolledInDeviceOptions = { - formatArgs: { - checkAuthMode(value, params) { - if (!value || !CheckAuthModes.includes(value)) - return 'checkAuthMode 填写错误'; - }, - }, - }; - const CheckIsSoterEnrolledInDeviceProtocols = { - checkAuthMode: String, - }; - const API_START_SOTER_AUTHENTICATION = 'checkIsSoterEnrolledInDevice'; - const StartSoterAuthenticationOptions = { - formatArgs: { - requestAuthModes(value, params) { - if (!value.includes('fingerPrint') && !value.includes('facial')) - return 'requestAuthModes 填写错误'; - }, - }, - }; - const StartSoterAuthenticationProtocols = { - requestAuthModes: { - type: Array, - required: true, - }, - challenge: String, - authContent: String, - }; - - const API_SCAN_CODE = 'scanCode'; - const ScanCodeProtocol = { - onlyFromCamera: Boolean, - scanType: Array, - autoDecodeCharSet: Boolean, - }; - - const API_GET_STORAGE = 'getStorage'; - const GetStorageProtocol = { - key: { - type: String, - required: true, - }, - }; - const API_GET_STORAGE_SYNC = 'getStorageSync'; - const GetStorageSyncProtocol = [ - { - name: 'key', - type: String, - required: true, - }, - ]; - const API_SET_STORAGE = 'setStorage'; - const SetStorageProtocol = { - key: { - type: String, - required: true, - }, - data: { - required: true, - }, - }; - const API_SET_STORAGE_SYNC = 'setStorageSync'; - const SetStorageSyncProtocol = [ - { - name: 'key', - type: String, - required: true, - }, - { - name: 'data', - required: true, - }, - ]; - const API_REMOVE_STORAGE = 'removeStorage'; - const RemoveStorageProtocol = GetStorageProtocol; - const RemoveStorageSyncProtocol = GetStorageSyncProtocol; - - const API_SAVE_FILE = 'saveFile'; - const SaveFileOptions = { - formatArgs: { - tempFilePath(savedFilePath, params) { - params.tempFilePath = getRealPath(savedFilePath); - }, - }, - }; - const SaveFileProtocol = { - tempFilePath: { - type: String, - required: true, - }, - }; - - const API_GET_FILE_INFO = 'getFileInfo'; - const GetFileInfoOptions = { - formatArgs: { - filePath(filePath, params) { - params.filePath = getRealPath(filePath); - }, - }, - }; - const GetFileInfoProtocol = { - filePath: { - type: String, - required: true, - }, - }; - - const API_OPEN_DOCUMENT = 'openDocument'; - const OpenDocumentOptions = { - formatArgs: { - filePath(filePath, params) { - params.filePath = getRealPath(filePath); - }, - }, - }; - const OpenDocumentProtocol = { - filePath: { - type: String, - required: true, - }, - fileType: String, - }; - - const API_HIDE_KEYBOARD = 'hideKeyboard'; - const API_SHOW_KEYBOARD = 'showKeyboard'; - - const API_CHOOSE_LOCATION = 'chooseLocation'; - const ChooseLocationProtocol = { - keyword: String, - latitude: Number, - longitude: Number, - }; - - const API_GET_LOCATION = 'getLocation'; - const coordTypes = ['WGS84', 'GCJ02']; - const GetLocationOptions = { - formatArgs: { - type(value, params) { - value = (value || '').toUpperCase(); - if (coordTypes.indexOf(value) === -1) { - params.type = coordTypes[0]; - } - else { - params.type = value; - } - }, - altitude(value, params) { - params.altitude = value ? value : false; - }, - }, - }; - const GetLocationProtocol = { - type: String, - altitude: Boolean, - }; - - const API_OPEN_LOCATION = 'openLocation'; - const OpenLocationOptions = { - formatArgs: { - scale(value, params) { - value = Math.floor(value); - params.scale = value >= 5 && value <= 18 ? value : 18; - }, - }, - }; - const OpenLocationProtocol = { - latitude: { - type: Number, - required: true, - }, - longitude: { - type: Number, - required: true, - }, - scale: Number, - name: String, - address: String, - }; - - const API_CHOOSE_IMAGE = 'chooseImage'; - const ChooseImageOptions = { - formatArgs: { - count(value, params) { - if (!value || value <= 0) { - params.count = 9; - } - }, - sizeType(sizeType, params) { - params.sizeType = elemsInArray(sizeType, CHOOSE_SIZE_TYPES); - }, - sourceType(sourceType, params) { - params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES); - }, - extension(extension, params) { - if (extension instanceof Array && extension.length === 0) { - return 'param extension should not be empty.'; - } - if (!extension) - params.extension = ['*']; - }, - }, - }; - const ChooseImageProtocol = { - count: Number, - sizeType: [Array, String], - sourceType: Array, - extension: Array, - }; - - const API_CHOOSE_VIDEO = 'chooseVideo'; - const ChooseVideoOptions = { - formatArgs: { - sourceType(sourceType, params) { - params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES); - }, - compressed: true, - maxDuration: 60, - camera: 'back', - extension(extension, params) { - if (extension instanceof Array && extension.length === 0) { - return 'param extension should not be empty.'; - } - if (!extension) - params.extension = ['*']; - }, - }, - }; - const ChooseVideoProtocol = { - sourceType: Array, - compressed: Boolean, - maxDuration: Number, - camera: String, - extension: Array, - }; - - const API_GET_IMAGE_INFO = 'getImageInfo'; - const GetImageInfoOptions = { - formatArgs: { - src(src, params) { - params.src = getRealPath(src); - }, - }, - }; - const GetImageInfoProtocol = { - src: { - type: String, - required: true, - }, - }; - - const API_PREVIEW_IMAGE = 'previewImage'; - const PreviewImageOptions = { - formatArgs: { - urls(urls, params) { - params.urls = urls.map((url) => typeof url === 'string' && url ? getRealPath(url) : ''); - }, - current(current, params) { - if (typeof current === 'number') { - params.current = - current > 0 && current < params.urls.length ? current : 0; - } - else if (typeof current === 'string' && current) { - params.current = getRealPath(current); - } - }, - }, - }; - const PreviewImageProtocol = { - urls: { - type: Array, - required: true, - }, - current: { - type: [Number, String], - }, - }; - const API_CLOSE_PREVIEW_IMAGE = 'closePreviewImage'; - - const API_GET_VIDEO_INFO = 'getVideoInfo'; - const GetVideoInfoOptions = { - formatArgs: { - src(src, params) { - params.src = getRealPath(src); - }, - }, - }; - const GetVideoInfoProtocol = { - src: { - type: String, - required: true, - }, - }; - - const API_SAVE_IMAGE_TO_PHOTOS_ALBUM = 'saveImageToPhotosAlbum'; - const SaveImageToPhotosAlbumOptions = { - formatArgs: { - filePath(filePath, params) { - params.filePath = getRealPath(filePath); - }, - }, - }; - const SaveImageToPhotosAlbumProtocol = { - filePath: { - type: String, - required: true, - }, - }; - - const API_SAVE_VIDEO_TO_PHOTOS_ALBUM = 'saveVideoToPhotosAlbum'; - const SaveVideoToPhotosAlbumOptions = { - formatArgs: { - filePath(filePath, params) { - params.filePath = getRealPath(filePath); - }, - }, - }; - const SaveVideoToPhotosAlbumProtocol = { - filePath: { - type: String, - required: true, - }, - }; - - const API_GET_RECORDER_MANAGER = 'getRecorderManager'; - - const API_COMPRESS_IMAGE = 'compressImage'; - const CompressImageOptions = { - formatArgs: { - src(src, params) { - params.src = getRealPath(src); - }, - }, - }; - const CompressImageProtocol = { - src: { - type: String, - required: true, - }, - }; - - const API_COMPRESS_VIDEO = 'compressVideo'; - const CompressVideoOptions = { - formatArgs: { - src(src, params) { - params.src = getRealPath(src); - }, - }, - }; - const CompressVideoProtocol = { - src: { - type: String, - required: true, - }, - quality: String, - bitrate: Number, - fps: Number, - resolution: Number, - }; - - const API_REQUEST = 'request'; - const dataType = { - JSON: 'json', - }; - const RESPONSE_TYPE = ['text', 'arraybuffer']; - const DEFAULT_RESPONSE_TYPE = 'text'; - const encode = encodeURIComponent; - function stringifyQuery(url, data) { - let str = url.split('#'); - const hash = str[1] || ''; - str = str[0].split('?'); - let query = str[1] || ''; - url = str[0]; - const search = query.split('&').filter((item) => item); - const params = {}; - search.forEach((item) => { - const part = item.split('='); - params[part[0]] = part[1]; - }); - for (const key in data) { - if (hasOwn$1(data, key)) { - let v = data[key]; - if (typeof v === 'undefined' || v === null) { - v = ''; - } - else if (isPlainObject(v)) { - v = JSON.stringify(v); - } - params[encode(key)] = encode(v); - } - } - query = Object.keys(params) - .map((item) => `${item}=${params[item]}`) - .join('&'); - return url + (query ? '?' + query : '') + (hash ? '#' + hash : ''); - } - const RequestProtocol = { - method: String, - data: [Object, String, Array, ArrayBuffer], - url: { - type: String, - required: true, - }, - header: Object, - dataType: String, - responseType: String, - withCredentials: Boolean, - }; - const RequestOptions = { - formatArgs: { - method(value, params) { - params.method = elemInArray((value || '').toUpperCase(), HTTP_METHODS); - }, - data(value, params) { - params.data = value || ''; - }, - url(value, params) { - if (params.method === HTTP_METHODS[0] && - isPlainObject(params.data) && - Object.keys(params.data).length) { - // 将 method,data 校验提前,保证 url 校验时,method,data 已被格式化 - params.url = stringifyQuery(value, params.data); - } - }, - header(value, params) { - const header = (params.header = value || {}); - if (params.method !== HTTP_METHODS[0]) { - if (!Object.keys(header).find((key) => key.toLowerCase() === 'content-type')) { - header['Content-Type'] = 'application/json'; - } - } - }, - dataType(value, params) { - params.dataType = (value || dataType.JSON).toLowerCase(); - }, - responseType(value, params) { - params.responseType = (value || '').toLowerCase(); - if (RESPONSE_TYPE.indexOf(params.responseType) === -1) { - params.responseType = DEFAULT_RESPONSE_TYPE; - } - }, - }, - }; - const API_CONFIG_MTLS = 'configMTLS'; - const ConfigMTLSProtocol = { - certificates: { - type: Array, - required: true, - }, - }; - const ConfigMTLSOptions = { - formatArgs: { - certificates(value) { - if (value.some((item) => toRawType(item.host) !== 'String')) { - return '参数配置错误,请确认后重试'; - } - }, - }, - }; - - const API_DOWNLOAD_FILE = 'downloadFile'; - const DownloadFileOptions = { - formatArgs: { - header(value, params) { - params.header = value || {}; - }, - }, - }; - const DownloadFileProtocol = { - url: { - type: String, - required: true, - }, - header: Object, - timeout: Number, - }; - - const API_UPLOAD_FILE = 'uploadFile'; - const UploadFileOptions = { - formatArgs: { - filePath(filePath, params) { - if (filePath) { - params.filePath = getRealPath(filePath); - } - }, - header(value, params) { - params.header = value || {}; - }, - formData(value, params) { - params.formData = value || {}; - }, - }, - }; - const UploadFileProtocol = { - url: { - type: String, - required: true, - }, - files: Array, - filePath: String, - name: String, - header: Object, - formData: Object, - timeout: Number, - }; - - const API_CONNECT_SOCKET = 'connectSocket'; - const ConnectSocketOptions = { - formatArgs: { - header(value, params) { - params.header = value || {}; - }, - method(value, params) { - params.method = elemInArray((value || '').toUpperCase(), HTTP_METHODS); - }, - protocols(protocols, params) { - if (typeof protocols === 'string') { - params.protocols = [protocols]; - } - }, - }, - }; - const ConnectSocketProtocol = { - url: { - type: String, - required: true, - }, - header: { - type: Object, - }, - method: String, - protocols: [Array, String], - }; - const API_SEND_SOCKET_MESSAGE = 'sendSocketMessage'; - const SendSocketMessageProtocol = { - data: [String, ArrayBuffer], - }; - const API_CLOSE_SOCKET = 'closeSocket'; - const CloseSocketProtocol = { - code: Number, - reason: String, - }; - - function encodeQueryString(url) { - if (typeof url !== 'string') { - return url; - } - const index = url.indexOf('?'); - if (index === -1) { - return url; - } - const query = url - .substr(index + 1) - .trim() - .replace(/^(\?|#|&)/, ''); - if (!query) { - return url; - } - url = url.substr(0, index); - const params = []; - query.split('&').forEach((param) => { - const parts = param.replace(/\+/g, ' ').split('='); - const key = parts.shift(); - const val = parts.length > 0 ? parts.join('=') : ''; - params.push(key + '=' + encodeURIComponent(val)); - }); - return params.length ? url + '?' + params.join('&') : url; - } - - const ANIMATION_IN = [ - 'slide-in-right', - 'slide-in-left', - 'slide-in-top', - 'slide-in-bottom', - 'fade-in', - 'zoom-out', - 'zoom-fade-out', - 'pop-in', - 'none', - ]; - const ANIMATION_OUT = [ - 'slide-out-right', - 'slide-out-left', - 'slide-out-top', - 'slide-out-bottom', - 'fade-out', - 'zoom-in', - 'zoom-fade-in', - 'pop-out', - 'none', - ]; - const BaseRouteProtocol = { - url: { - type: String, - required: true, - }, - }; - const API_NAVIGATE_TO = 'navigateTo'; - const API_REDIRECT_TO = 'redirectTo'; - const API_RE_LAUNCH = 'reLaunch'; - const API_SWITCH_TAB = 'switchTab'; - const API_NAVIGATE_BACK = 'navigateBack'; - const API_PRELOAD_PAGE = 'preloadPage'; - const API_UN_PRELOAD_PAGE = 'unPreloadPage'; - const NavigateToProtocol = - /*#__PURE__*/ extend({}, BaseRouteProtocol, createAnimationProtocol(ANIMATION_IN)); - const NavigateBackProtocol = - /*#__PURE__*/ extend({ - delta: { - type: Number, - }, - }, createAnimationProtocol(ANIMATION_OUT)); - const RedirectToProtocol = BaseRouteProtocol; - const ReLaunchProtocol = BaseRouteProtocol; - const SwitchTabProtocol = BaseRouteProtocol; - const PreloadPageProtocol = BaseRouteProtocol; - const UnPreloadPageProtocol = BaseRouteProtocol; - const NavigateToOptions = - /*#__PURE__*/ createRouteOptions(API_NAVIGATE_TO); - const RedirectToOptions = - /*#__PURE__*/ createRouteOptions(API_REDIRECT_TO); - const ReLaunchOptions = - /*#__PURE__*/ createRouteOptions(API_RE_LAUNCH); - const SwitchTabOptions = - /*#__PURE__*/ createRouteOptions(API_SWITCH_TAB); - const NavigateBackOptions = { - formatArgs: { - delta(value, params) { - value = parseInt(value + '') || 1; - params.delta = Math.min(getCurrentPages().length - 1, value); - }, - }, - }; - function createAnimationProtocol(animationTypes) { - return { - animationType: { - type: String, - validator(type) { - if (type && animationTypes.indexOf(type) === -1) { - return ('`' + - type + - '` is not supported for `animationType` (supported values are: `' + - animationTypes.join('`|`') + - '`)'); - } - }, - }, - animationDuration: { - type: Number, - }, - }; - } - let navigatorLock; - function beforeRoute() { - navigatorLock = ''; - } - function createRouteOptions(type) { - return { - formatArgs: { - url: createNormalizeUrl(type), - }, - beforeAll: beforeRoute, - }; - } - function createNormalizeUrl(type) { - return function normalizeUrl(url, params) { - if (!url) { - return `Missing required args: "url"`; - } - // 格式化为绝对路径路由 - url = normalizeRoute(url); - const pagePath = url.split('?')[0]; - // 匹配路由是否存在 - const routeOptions = getRouteOptions(pagePath, true); - if (!routeOptions) { - return 'page `' + url + '` is not found'; - } - // 检测不同类型跳转 - if (type === API_NAVIGATE_TO || type === API_REDIRECT_TO) { - if (routeOptions.meta.isTabBar) { - return `can not ${type} a tabbar page`; - } - } - else if (type === API_SWITCH_TAB) { - if (!routeOptions.meta.isTabBar) { - return 'can not switch to no-tabBar page'; - } - } - // switchTab不允许传递参数,reLaunch到一个tabBar页面是可以的 - if ((type === API_SWITCH_TAB || type === API_PRELOAD_PAGE) && - routeOptions.meta.isTabBar && - params.openType !== 'appLaunch') { - url = pagePath; - } - // 首页自动格式化为`/` - if (routeOptions.meta.isEntry) { - url = url.replace(routeOptions.alias, '/'); - } - // 参数格式化 - params.url = encodeQueryString(url); - if (type === API_UN_PRELOAD_PAGE) { - return; - } - else if (type === API_PRELOAD_PAGE) { - { - if (!routeOptions.meta.isNVue) { - return 'can not preload vue page'; - } - } - if (routeOptions.meta.isTabBar) { - const pages = getCurrentPages(); - const tabBarPagePath = routeOptions.path.substr(1); - if (pages.find((page) => page.route === tabBarPagePath)) { - return 'tabBar page `' + tabBarPagePath + '` already exists'; - } - } - return; - } - // 主要拦截目标为用户快速点击时触发的多次跳转,该情况,通常前后 url 是一样的 - if (navigatorLock === url && params.openType !== 'appLaunch') { - return `${navigatorLock} locked`; - } - // 至少 onLaunch 之后,再启用lock逻辑(onLaunch之前可能开发者手动调用路由API,来提前跳转) - // enableNavigatorLock 临时开关(不对外开放),避免该功能上线后,有部分情况异常,可以让开发者临时关闭 lock 功能 - if (__uniConfig.ready) { - navigatorLock = url; - } - }; - } - - const API_HIDE_LOADING = 'hideLoading'; - - const API_HIDE_TOAST = 'hideToast'; - - const API_LOAD_FONT_FACE = 'loadFontFace'; - const LoadFontFaceProtocol = { - family: { - type: String, - required: true, - }, - source: { - type: String, - required: true, - }, - desc: Object, - }; - - const FRONT_COLORS = ['#ffffff', '#000000']; - const API_SET_NAVIGATION_BAR_COLOR = 'setNavigationBarColor'; - const SetNavigationBarColorOptions = { - formatArgs: { - animation(animation, params) { - if (!animation) { - animation = { duration: 0, timingFunc: 'linear' }; - } - params.animation = { - duration: animation.duration || 0, - timingFunc: animation.timingFunc || 'linear', - }; - }, - }, - }; - const SetNavigationBarColorProtocol = { - frontColor: { - type: String, - required: true, - validator(frontColor) { - if (FRONT_COLORS.indexOf(frontColor) === -1) { - return `invalid frontColor "${frontColor}"`; - } - }, - }, - backgroundColor: { - type: String, - required: true, - }, - animation: Object, - }; - const API_SET_NAVIGATION_BAR_TITLE = 'setNavigationBarTitle'; - const SetNavigationBarTitleProtocol = { - title: { - type: String, - required: true, - }, - }; - const API_SHOW_NAVIGATION_BAR_LOADING = 'showNavigationBarLoading'; - const API_HIDE_NAVIGATION_BAR_LOADING = 'hideNavigationBarLoading'; - - const API_PAGE_SCROLL_TO = 'pageScrollTo'; - const PageScrollToProtocol = { - scrollTop: Number, - selector: String, - duration: Number, - }; - const DEFAULT_DURATION = 300; - const PageScrollToOptions = { - formatArgs: { - duration(value, params) { - params.duration = Math.max(0, parseInt(value + '') || DEFAULT_DURATION); - }, - }, - }; - - const API_SHOW_ACTION_SHEET = 'showActionSheet'; - const ShowActionSheetProtocol = { - itemList: { - type: Array, - required: true, - }, - title: String, - alertText: String, - itemColor: String, - popover: Object, - }; - const ShowActionSheetOptions = { - formatArgs: { - itemColor: '#000', - }, - }; - - const API_SHOW_LOADING = 'showLoading'; - const ShowLoadingProtocol = { - title: String, - mask: Boolean, - }; - const ShowLoadingOptions = { - formatArgs: { - title: '', - mask: false, - }, - }; - - const API_SHOW_MODAL = 'showModal'; - const ShowModalProtocol = { - title: String, - content: String, - showCancel: Boolean, - cancelText: String, - cancelColor: String, - confirmText: String, - confirmColor: String, - }; - const ShowModalOptions = { - beforeInvoke() { - // dynamic init (tree shaking) - initI18nShowModalMsgsOnce(); - }, - formatArgs: { - title: '', - content: '', - showCancel: true, - cancelText(_value, params) { - if (!hasOwn$1(params, 'cancelText')) { - const { t } = useI18n(); - params.cancelText = t('uni.showModal.cancel'); - } - }, - cancelColor: '#000', - confirmText(_value, params) { - if (!hasOwn$1(params, 'confirmText')) { - const { t } = useI18n(); - params.confirmText = t('uni.showModal.confirm'); - } - }, - confirmColor: PRIMARY_COLOR, - }, - }; - - const API_SHOW_TOAST = 'showToast'; - const SHOW_TOAST_ICON = [ - 'success', - 'loading', - 'none', - 'error', - ]; - const ShowToastProtocol = { - title: String, - icon: String, - image: String, - duration: Number, - mask: Boolean, - }; - const ShowToastOptions = { - formatArgs: { - title: '', - icon(type, params) { - params.icon = elemInArray(type, SHOW_TOAST_ICON); - }, - image(value, params) { - if (value) { - params.image = getRealPath(value); - } - else { - params.image = ''; - } - }, - duration: 1500, - mask: false, - }, - }; - - const API_START_PULL_DOWN_REFRESH = 'startPullDownRefresh'; - - const API_STOP_PULL_DOWN_REFRESH = 'stopPullDownRefresh'; - - const IndexProtocol = { - index: { - type: Number, - required: true, - }, - }; - const IndexOptions = { - beforeInvoke() { - const pageMeta = getCurrentPageMeta(); - if (pageMeta && !pageMeta.isTabBar) { - return 'not TabBar page'; - } - }, - formatArgs: { - index(value) { - if (!__uniConfig.tabBar.list[value]) { - return 'tabbar item not found'; - } - }, - }, - }; - const API_SET_TAB_BAR_ITEM = 'setTabBarItem'; - const SetTabBarItemProtocol = - /*#__PURE__*/ extend({ - text: String, - iconPath: String, - selectedIconPath: String, - pagePath: String, - }, IndexProtocol); - const SetTabBarItemOptions = { - beforeInvoke: IndexOptions.beforeInvoke, - formatArgs: /*#__PURE__*/ extend({ - pagePath(value, params) { - if (value) { - params.pagePath = removeLeadingSlash(value); - } - }, - }, IndexOptions.formatArgs), - }; - const API_SET_TAB_BAR_STYLE = 'setTabBarStyle'; - const SetTabBarStyleProtocol = { - color: String, - selectedColor: String, - backgroundColor: String, - backgroundImage: String, - backgroundRepeat: String, - borderStyle: String, - }; - const GRADIENT_RE = /^(linear|radial)-gradient\(.+?\);?$/; - const SetTabBarStyleOptions = { - beforeInvoke: IndexOptions.beforeInvoke, - formatArgs: { - backgroundImage(value, params) { - if (value && !GRADIENT_RE.test(value)) { - params.backgroundImage = getRealPath(value); - } - }, - borderStyle(value, params) { - if (value) { - params.borderStyle = value === 'white' ? 'white' : 'black'; - } - }, - }, - }; - const API_HIDE_TAB_BAR = 'hideTabBar'; - const HideTabBarProtocol = { - animation: Boolean, - }; - const API_SHOW_TAB_BAR = 'showTabBar'; - const ShowTabBarProtocol = HideTabBarProtocol; - const API_HIDE_TAB_BAR_RED_DOT = 'hideTabBarRedDot'; - const HideTabBarRedDotProtocol = IndexProtocol; - const HideTabBarRedDotOptions = IndexOptions; - const API_SHOW_TAB_BAR_RED_DOT = 'showTabBarRedDot'; - const ShowTabBarRedDotProtocol = IndexProtocol; - const ShowTabBarRedDotOptions = IndexOptions; - const API_REMOVE_TAB_BAR_BADGE = 'removeTabBarBadge'; - const RemoveTabBarBadgeProtocol = IndexProtocol; - const RemoveTabBarBadgeOptions = IndexOptions; - const API_SET_TAB_BAR_BADGE = 'setTabBarBadge'; - const SetTabBarBadgeProtocol = - /*#__PURE__*/ extend({ - text: { - type: String, - required: true, - }, - }, IndexProtocol); - const SetTabBarBadgeOptions = { - beforeInvoke: IndexOptions.beforeInvoke, - formatArgs: /*#__PURE__*/ extend({ - text(value, params) { - if (getLen(value) >= 4) { - params.text = '...'; - } - }, - }, IndexOptions.formatArgs), - }; - - const API_GET_PROVIDER = 'getProvider'; - const GetProviderProtocol = { - service: { - type: String, - required: true, - }, - }; - - const API_LOGIN = 'login'; - const LoginProtocol = { - provider: String, - scopes: [String, Array], - timeout: Number, - univerifyStyle: Object, - onlyAuthorize: Boolean, - }; - const API_GET_USER_INFO = 'getUserInfo'; - const GetUserInfoProtocol = { - provider: String, - withCredentials: Boolean, - timeout: Number, - lang: String, - }; - const API_GET_USER_PROFILE = 'ggetUserProfilegetUserProfile'; - const GgetUserProfileProtocol = { - provider: String, - withCredentials: Boolean, - timeout: Number, - lang: String, - }; - const API_PRE_LOGIN = 'preLogin'; - const provider = { - UNIVERIFY: 'univerify', - }; - const PreLoginOptions = { - formatArgs: { - provider(value, parmas) { - if (Object.values(provider).indexOf(String(value)) < 0) { - return 'provider error'; - } - }, - }, - }; - const PreLoginProtocol = { - provider: { - type: String, - required: true, - }, - }; - const API_CLOSE_AUTH_VIEW = 'closeAuthView'; - const API_GET_CHECK_BOX_STATE = 'getCheckBoxState'; - const API_GET_UNIVERIFY_MANAGER = 'getUniverifyManager'; - - const API_SHREA = 'share'; - const SCENE = [ - 'WXSceneSession', - 'WXSenceTimeline', - 'WXSceneFavorite', - ]; - const SahreOptions = { - formatArgs: { - scene(value, params) { - if (params.provider === 'weixin' && (!value || !SCENE.includes(value))) { - return `分享到微信时,scene必须为以下其中一个:${SCENE.join('、')}`; - } - }, - summary(value, params) { - if (params.type === 1 && !value) { - return '分享纯文本时,summary必填'; - } - }, - href(value, params) { - if (params.type === 0 && !value) { - return '分享图文时,href必填'; - } - }, - imageUrl(value, params) { - if ([0, 2, 5].includes(Number(params.type)) && !value) { - return '分享图文、纯图片、小程序时,imageUrl必填,推荐使用小于20Kb的图片'; - } - }, - mediaUrl(value, params) { - if ([3, 4].includes(Number(params.type)) && !value) { - return '分享音乐、视频时,mediaUrl必填'; - } - }, - miniProgram(value, params) { - if (params.type === 5 && !value) { - return '分享小程序时,miniProgram必填'; - } - }, - }, - }; - const ShareProtocols = { - provider: { - type: String, - required: true, - }, - type: Number, - title: String, - scene: String, - summary: String, - href: String, - imageUrl: String, - mediaUrl: String, - miniProgram: Object, - }; - const API_SHARE_WITH_SYSTEM = 'shareWithSystem'; - const TYPE$2 = [ - 'text', - 'image', - ]; - const ShareWithSystemOptions = { - formatArgs: { - type(value, params) { - if (value && !TYPE$2.includes(value)) - return '分享参数 type 不正确。只支持text、image'; - params.type = elemInArray(value, TYPE$2); - }, - }, - }; - const ShareWithSystemProtocols = { - type: String, - summary: String, - href: String, - imageUrl: String, - }; - - const API_REQUEST_PAYMENT = 'requestPayment'; - const RequestPaymentProtocol = { - provider: { - type: String, - required: true, - }, - orderInfo: { - type: [String, Object], - required: true, - }, - timeStamp: String, - nonceStr: String, - package: String, - signType: String, - paySign: String, - }; - - const API_CREATE_REWARDED_VIDEO_AD = 'createRewardedVideoAd'; - const CreateRewardedVideoAdOptions = { - formatArgs: { - adpid: '', - adUnitId: '', - }, - }; - const CreateRewardedVideoAdProtocol = { - adpid: String, - adUnitId: String, - }; - - const API_CREATE_FULL_SCREEN_VIDEO_AD = 'createFullScreenVideoAd'; - const CreateFullScreenVideoAdOptions = { - formatArgs: { - adpid: '', - }, - }; - const CreateFullScreenVideoAdProtocol = { - adpid: String, - }; - - const API_CREATE_INTERSTITIAL_AD = 'createInterstitialAd'; - const CreateInterstitialAdOptions = { - formatArgs: { - adpid: '', - adUnitId: '', - }, - }; - const CreateInterstitialAdProtocol = { - adpid: String, - adUnitId: String, - }; - - const API_CREATE_INTERACTIVE_AD = 'createInteractiveAd'; - const CreateInteractiveAdOptions = { - formatArgs: { - adpid(value, params) { - if (!value) { - return 'adpid should not be empty.'; - } - if (value) - params.adpid = value; - }, - provider(value, params) { - if (!value) { - return 'provider should not be empty.'; - } - if (value) - params.provider = value; - }, - }, - }; - const CreateInteractiveAdProtocol = { - adpid: { - type: String, - required: true, - }, - provider: { - type: String, - required: true, - }, - }; - - const STORAGE_DATA_TYPE = '__TYPE'; - const STORAGE_KEYS = 'uni-storage-keys'; - function parseValue(value) { - const types = ['object', 'string', 'number', 'boolean', 'undefined']; - try { - const object = typeof value === 'string' ? JSON.parse(value) : value; - const type = object.type; - if (types.indexOf(type) >= 0) { - const keys = Object.keys(object); - if (keys.length === 2 && 'data' in object) { - // eslint-disable-next-line valid-typeof - if (typeof object.data === type) { - return object.data; - } - // eslint-disable-next-line no-useless-escape - if (type === 'object' && - /^\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d{3}Z$/.test(object.data)) { - // ISO 8601 格式返回 Date - return new Date(object.data); - } - } - else if (keys.length === 1) { - return ''; - } - } - } - catch (error) { } - } - const setStorageSync = defineSyncApi(API_SET_STORAGE_SYNC, (key, data) => { - const type = typeof data; - const value = type === 'string' - ? data - : JSON.stringify({ - type, - data: data, - }); - try { - if (type === 'string' && parseValue(value) !== undefined) { - plus.storage.setItem(key + STORAGE_DATA_TYPE, type); - } - else { - plus.storage.removeItem(key + STORAGE_DATA_TYPE); - } - plus.storage.setItem(key, value); - } - catch (error) { } - }, SetStorageSyncProtocol); - const setStorage = defineAsyncApi(API_SET_STORAGE, ({ key, data }, { resolve, reject }) => { - const type = typeof data; - const value = type === 'string' - ? data - : JSON.stringify({ - type, - data: data, - }); - try { - const storage = plus.storage; - if (type === 'string' && parseValue(value) !== undefined) { - storage.setItemAsync(key + STORAGE_DATA_TYPE, type); - } - else { - storage.removeItemAsync(key + STORAGE_DATA_TYPE); - } - storage.setItemAsync(key, value, resolve, warpPlusErrorCallback(reject)); - } - catch (error) { - reject(error.message); - } - }, SetStorageProtocol); - function parseGetStorage(type, value) { - let data = value; - if (type !== 'string' || - (type === 'string' && value === '{"type":"undefined"}')) { - try { - // 兼容H5和V3初期历史格式 - let object = JSON.parse(value); - const result = parseValue(object); - if (result !== undefined) { - data = result; - } - else if (type) { - // 兼容App端历史格式 - data = object; - if (typeof object === 'string') { - object = JSON.parse(object); - const objectType = typeof object; - if (objectType === 'number' && type === 'date') { - data = new Date(object); - } - else if (objectType === - (['null', 'array'].indexOf(type) < 0 ? type : 'object')) { - data = object; - } - } - } - } - catch (error) { } - } - return data; - } - const getStorageSync = defineSyncApi(API_GET_STORAGE_SYNC, (key, t) => { - const value = plus.storage.getItem(key); - const typeOrigin = plus.storage.getItem(key + STORAGE_DATA_TYPE) || ''; - const type = typeOrigin.toLowerCase(); - if (typeof value !== 'string') { - return ''; - } - return parseGetStorage(type, value); - }, GetStorageSyncProtocol); - const getStorage = defineAsyncApi(API_GET_STORAGE, ({ key }, { resolve, reject }) => { - const storage = plus.storage; - storage.getItemAsync(key, function (res) { - storage.getItemAsync(key + STORAGE_DATA_TYPE, function (typeRes) { - const typeOrigin = typeRes.data || ''; - const type = typeOrigin.toLowerCase(); - resolve({ - data: parseGetStorage(type, res.data), - }); - }, function () { - const type = ''; - resolve({ - data: parseGetStorage(type, res.data), - }); - }); - }, warpPlusErrorCallback(reject)); - }, GetStorageProtocol); - const removeStorageSync = defineSyncApi(API_REMOVE_STORAGE, (key) => { - plus.storage.removeItem(key + STORAGE_DATA_TYPE); - plus.storage.removeItem(key); - }, RemoveStorageSyncProtocol); - const removeStorage = defineAsyncApi(API_REMOVE_STORAGE, ({ key }, { resolve, reject }) => { - // 兼容App端历史格式 - plus.storage.removeItemAsync(key + STORAGE_DATA_TYPE); - plus.storage.removeItemAsync(key, resolve, warpPlusErrorCallback(reject)); - }, RemoveStorageProtocol); - const clearStorageSync = (defineSyncApi('clearStorageSync', () => { - plus.storage.clear(); - })); - const clearStorage = (defineAsyncApi('clearStorage', (_, { resolve, reject }) => { - plus.storage.clearAsync(resolve, warpPlusErrorCallback(reject)); - })); - const getStorageInfoSync = (defineSyncApi('getStorageInfoSync', () => { - const length = plus.storage.getLength() || 0; - const keys = []; - let currentSize = 0; - for (let index = 0; index < length; index++) { - const key = plus.storage.key(index); - if (key !== STORAGE_KEYS && - (key.indexOf(STORAGE_DATA_TYPE) < 0 || - key.indexOf(STORAGE_DATA_TYPE) + STORAGE_DATA_TYPE.length !== - key.length)) { - const value = plus.storage.getItem(key); - currentSize += key.length + value.length; - keys.push(key); - } - } - return { - keys, - currentSize: Math.ceil((currentSize * 2) / 1024), - limitSize: Number.MAX_VALUE, - }; - })); - const getStorageInfo = (defineAsyncApi('getStorageInfo', (_, { resolve }) => { - resolve(getStorageInfoSync()); - })); - - const getFileInfo$1 = defineAsyncApi(API_GET_FILE_INFO, (options, { resolve, reject }) => { - plus.io.getFileInfo(extend(options, { - success: warpPlusSuccessCallback(resolve), - fail: warpPlusErrorCallback(reject), - })); - }, GetFileInfoProtocol, GetFileInfoOptions); - - const openDocument = defineAsyncApi(API_OPEN_DOCUMENT, ({ filePath, fileType }, { resolve, reject }) => { - const errorCallback = warpPlusErrorCallback(reject); - plus.runtime.openDocument(getRealPath(filePath), undefined, resolve, errorCallback); - }, OpenDocumentProtocol, OpenDocumentOptions); - - function getFileName(path) { - const array = path.split('/'); - return array[array.length - 1]; - } - function getExtName(path) { - const array = path.split('.'); - return array.length > 1 ? '.' + array[array.length - 1] : ''; - } - - let index$2 = 0; - const SAVED_DIR = 'uniapp_save'; - const SAVE_PATH = `_doc/${SAVED_DIR}`; - function getSavedFileDir(success, fail) { - fail = fail || function () { }; - plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => { - // 请求_doc fs - fs.root.getDirectory(SAVED_DIR, { - // 获取文件保存目录对象 - create: true, - }, success, fail); - }, fail); - } - const saveFile = defineAsyncApi(API_SAVE_FILE, ({ tempFilePath }, { resolve, reject }) => { - const errorCallback = warpPlusErrorCallback(reject); - const fileName = `${Date.now()}${index$2++}${getExtName(tempFilePath)}`; - plus.io.resolveLocalFileSystemURL(tempFilePath, (entry) => { - // 读取临时文件 FileEntry - getSavedFileDir((dir) => { - entry.copyTo(dir, fileName, () => { - // 复制临时文件 FileEntry,为了避免把相册里的文件删除,使用 copy,微信中是要删除临时文件的 - const savedFilePath = SAVE_PATH + '/' + fileName; - resolve({ - savedFilePath, - }); - }, errorCallback); - }, errorCallback); - }, errorCallback); - }, SaveFileProtocol, SaveFileOptions); - - let deviceId; - function deviceId$1 () { - deviceId = deviceId || plus.device.uuid; - return deviceId; - } - - function getScreenInfo() { - const { resolutionWidth, resolutionHeight } = plus.screen.getCurrentSize(); - return { - screenWidth: Math.round(resolutionWidth), - screenHeight: Math.round(resolutionHeight), - }; - } - const getSystemInfoSync = defineSyncApi('getSystemInfoSync', () => { - const platform = plus.os.name.toLowerCase(); - const ios = platform === 'ios'; - const isAndroid = platform === 'android'; - const { screenWidth, screenHeight } = getScreenInfo(); - const statusBarHeight = getStatusbarHeight(); - let safeAreaInsets; - const titleNView = { - height: 0, - cover: false, - }; - const webview = getCurrentWebview(); - if (webview) { - const webStyle = webview.getStyle(); - const style = webStyle && webStyle.titleNView; - if (style && style.type && style.type !== 'none') { - titleNView.height = - style.type === 'transparent' ? 0 : statusBarHeight + NAVBAR_HEIGHT; - titleNView.cover = - style.type === 'transparent' || style.type === 'float'; - } - safeAreaInsets = webview.getSafeAreaInsets(); - } - else { - safeAreaInsets = plus.navigator.getSafeAreaInsets(); - } - const tabBarView = { - height: 0, - cover: false, - }; - if (isTabBarPage()) { - tabBarView.height = tabBar$1.visible ? tabBar$1.height : 0; - tabBarView.cover = tabBar$1.cover; - } - const windowTop = titleNView.cover ? titleNView.height : 0; - const windowBottom = tabBarView.cover ? tabBarView.height : 0; - let windowHeight = screenHeight - titleNView.height - tabBarView.height; - let windowHeightReal = screenHeight - - (titleNView.cover ? 0 : titleNView.height) - - (tabBarView.cover ? 0 : tabBarView.height); - const windowWidth = screenWidth; - if ((!tabBarView.height || tabBarView.cover) && - !safeAreaInsets.bottom && - safeAreaInsets.deviceBottom) { - windowHeight -= safeAreaInsets.deviceBottom; - windowHeightReal -= safeAreaInsets.deviceBottom; - } - safeAreaInsets = ios - ? safeAreaInsets - : { - left: 0, - right: 0, - top: titleNView.height && !titleNView.cover ? 0 : statusBarHeight, - bottom: 0, - }; - const safeArea = { - left: safeAreaInsets.left, - right: windowWidth - safeAreaInsets.right, - top: safeAreaInsets.top, - bottom: windowHeightReal - safeAreaInsets.bottom, - width: windowWidth - safeAreaInsets.left - safeAreaInsets.right, - height: windowHeightReal - safeAreaInsets.top - safeAreaInsets.bottom, - }; - return { - brand: plus.device.vendor, - model: plus.device.model, - pixelRatio: plus.screen.scale, - screenWidth, - screenHeight, - windowWidth, - windowHeight, - statusBarHeight, - language: plus.os.language, - system: `${ios ? 'iOS' : isAndroid ? 'Android' : ''} ${plus.os.version}`, - version: plus.runtime.innerVersion, - platform, - SDKVersion: '', - windowTop, - windowBottom, - safeArea, - safeAreaInsets: { - top: safeAreaInsets.top, - right: safeAreaInsets.right, - bottom: safeAreaInsets.bottom, - left: safeAreaInsets.left, - }, - deviceId: deviceId$1(), - }; - }); - const getSystemInfo = defineAsyncApi('getSystemInfo', (_, { resolve }) => { - return resolve(getSystemInfoSync()); - }); - - const DEVICE_FREQUENCY = 200; - const NETWORK_TYPES = [ - 'unknown', - 'none', - 'ethernet', - 'wifi', - '2g', - '3g', - '4g', - '5g', - ]; - const TEMP_PATH_BASE = '_doc/uniapp_temp'; - const TEMP_PATH = `${TEMP_PATH_BASE}_${Date.now()}`; - - let listener$1 = null; - const onCompassChange = (defineOnApi(API_ON_COMPASS, () => { - startCompass(); - })); - const offCompassChange = (defineOffApi(API_OFF_COMPASS, () => { - stopCompass(); - })); - const startCompass = (defineAsyncApi(API_START_COMPASS, (_, { resolve, reject }) => { - if (!listener$1) { - listener$1 = plus.orientation.watchOrientation((res) => { - UniServiceJSBridge.invokeOnCallback(API_ON_COMPASS, { - direction: res.magneticHeading, - }); - }, (err) => { - reject(err.message); - listener$1 = null; - }, { - frequency: DEVICE_FREQUENCY, - }); - } - setTimeout(resolve, DEVICE_FREQUENCY); - })); - const stopCompass = (defineAsyncApi(API_STOP_COMPASS, (_, { resolve }) => { - if (listener$1) { - plus.orientation.clearWatch(listener$1); - listener$1 = null; - } - resolve(); - })); - - const vibrateShort = defineAsyncApi(API_VIBRATE_SHORT, (_, { resolve }) => { - plus.device.vibrate(15); - resolve(); - }); - const vibrateLong = defineAsyncApi(API_VIBRATE_LONG, (_, { resolve }) => { - plus.device.vibrate(400); - resolve(); - }); - - let listener = null; - const onAccelerometerChange = (defineOnApi(API_ON_ACCELEROMETER, () => { - startAccelerometer(); - })); - const offAccelerometerChange = (defineOffApi(API_OFF_ACCELEROMETER, () => { - stopAccelerometer(); - })); - const startAccelerometer = (defineAsyncApi(API_START_ACCELEROMETER, (_, { resolve, reject }) => { - if (!listener) { - listener = plus.accelerometer.watchAcceleration((res) => { - UniServiceJSBridge.invokeOnCallback(API_ON_ACCELEROMETER, { - x: (res && res.xAxis) || 0, - y: (res && res.yAxis) || 0, - z: (res && res.zAxis) || 0, - }); - }, (err) => { - listener = null; - reject(`startAccelerometer:fail ${err.message}`); - }, { - frequency: DEVICE_FREQUENCY, - }); - } - setTimeout(resolve, DEVICE_FREQUENCY); - })); - const stopAccelerometer = (defineAsyncApi(API_STOP_ACCELEROMETER, (_, { resolve }) => { - if (listener) { - plus.accelerometer.clearWatch(listener); - listener = null; - } - resolve(); - })); - - const onBluetoothDeviceFound = defineOnApi(API_ON_BLUETOOTH_DEVICE_FOUND, warpPlusEvent(() => plus.bluetooth.onBluetoothDeviceFound.bind(plus.bluetooth), API_ON_BLUETOOTH_DEVICE_FOUND)); - const onBluetoothAdapterStateChange = defineOnApi(API_ON_BLUETOOTH_ADAPTER_STATE_CHANGE, warpPlusEvent(() => plus.bluetooth.onBluetoothAdapterStateChange.bind(plus.bluetooth), API_ON_BLUETOOTH_ADAPTER_STATE_CHANGE)); - const onBLEConnectionStateChange = defineOnApi(API_ON_BLE_CONNECTION_STATE_CHANGE, warpPlusEvent(() => plus.bluetooth.onBLEConnectionStateChange.bind(plus.bluetooth), API_ON_BLE_CONNECTION_STATE_CHANGE)); - const onBLECharacteristicValueChange = defineOnApi(API_ON_BLE_CHARACTERISTIC_VALUE_CHANGE, warpPlusEvent(() => plus.bluetooth.onBLECharacteristicValueChange.bind(plus.bluetooth), API_ON_BLE_CHARACTERISTIC_VALUE_CHANGE)); - const openBluetoothAdapter = defineAsyncApi('openBluetoothAdapter', warpPlusMethod(() => plus.bluetooth.openBluetoothAdapter.bind(plus.bluetooth))); - const closeBluetoothAdapter = defineAsyncApi('closeBluetoothAdapter', warpPlusMethod(() => plus.bluetooth.closeBluetoothAdapter.bind(plus.bluetooth))); - const getBluetoothAdapterState = defineAsyncApi('getBluetoothAdapterState', warpPlusMethod(() => plus.bluetooth.getBluetoothAdapterState)); - const startBluetoothDevicesDiscovery = defineAsyncApi(API_START_BLUETOOTH_DEVICES_DISCOVERY, warpPlusMethod(() => plus.bluetooth.startBluetoothDevicesDiscovery.bind(plus.bluetooth)), StartBluetoothDevicesDiscoveryProtocol); - const stopBluetoothDevicesDiscovery = defineAsyncApi('stopBluetoothDevicesDiscovery', warpPlusMethod(() => plus.bluetooth.stopBluetoothDevicesDiscovery.bind(plus.bluetooth))); - const getBluetoothDevices = defineAsyncApi('getBluetoothDevices', warpPlusMethod(() => plus.bluetooth.getBluetoothDevices.bind(plus.bluetooth))); - const getConnectedBluetoothDevices = defineAsyncApi(API_GET_CONNECTED_BLUETOOTH_DEVICES, warpPlusMethod(() => plus.bluetooth.getConnectedBluetoothDevices), GetConnectedBluetoothDevicesProtocol); - const createBLEConnection = defineAsyncApi(API_CREATE_BLE_CONNECTION, warpPlusMethod(() => plus.bluetooth.createBLEConnection.bind(plus.bluetooth)), CreateBLEConnectionProtocol); - const closeBLEConnection = defineAsyncApi(API_CLOSE_BLE_CONNECTION, warpPlusMethod(() => plus.bluetooth.closeBLEConnection.bind(plus.bluetooth)), CloseBLEConnectionProtocol); - const getBLEDeviceServices = defineAsyncApi(API_GET_BLE_DEVICE_SERVICES, warpPlusMethod(() => plus.bluetooth.getBLEDeviceServices.bind(plus.bluetooth)), GetBLEDeviceServicesProtocol); - const getBLEDeviceCharacteristics = defineAsyncApi(API_GET_BLE_DEVICE_CHARACTERISTICS, warpPlusMethod(() => plus.bluetooth.getBLEDeviceCharacteristics.bind(plus.bluetooth)), GetBLEDeviceCharacteristicsProtocol); - const notifyBLECharacteristicValueChange = defineAsyncApi(API_NOTIFY_BLE_CHARACTERISTIC_VALUE_CHANGE, warpPlusMethod(() => plus.bluetooth.notifyBLECharacteristicValueChange.bind(plus.bluetooth)), NotifyBLECharacteristicValueChangeProtocol); - const readBLECharacteristicValue = defineAsyncApi(API_READ_BLE_CHARACTERISTIC_VALUE, warpPlusMethod(() => plus.bluetooth.readBLECharacteristicValue.bind(plus.bluetooth)), ReadBLECharacteristicValueProtocol); - const writeBLECharacteristicValue = defineAsyncApi(API_WRITE_BLE_CHARACTERISTIC_VALUE, warpPlusMethod(() => plus.bluetooth.writeBLECharacteristicValue.bind(plus.bluetooth)), WriteBLECharacteristicValueProtocol); - const setBLEMTU = defineAsyncApi(API_SET_BLE_MTU, warpPlusMethod(() => plus.bluetooth.setBLEMTU.bind(plus.bluetooth)), SetBLEMTUProtocol); - const getBLEDeviceRSSI = defineAsyncApi(API_GET_BLE_DEVICE_RSSI, warpPlusMethod(() => plus.bluetooth.getBLEDeviceRSSI.bind(plus.bluetooth)), GetBLEDeviceRSSIProtocol); - - const onBeaconUpdate = defineOnApi(API_ON_BEACON_UPDATE, warpPlusEvent(() => plus.ibeacon.onBeaconUpdate.bind(plus.ibeacon), API_ON_BEACON_UPDATE)); - const onBeaconServiceChange = defineOnApi(API_ON_BEACON_SERVICE_CHANGE, warpPlusEvent(() => plus.ibeacon.onBeaconServiceChange.bind(plus.ibeacon), API_ON_BEACON_SERVICE_CHANGE)); - const getBeacons = defineAsyncApi(API_GET_BEACONS, warpPlusMethod(() => plus.ibeacon.getBeacons.bind(plus.ibeacon))); - const startBeaconDiscovery = defineAsyncApi(API_START_BEACON_DISCOVERY, warpPlusMethod(() => plus.ibeacon.startBeaconDiscovery.bind(plus.ibeacon)), StartBeaconDiscoveryProtocol); - const stopBeaconDiscovery = defineAsyncApi(API_STOP_BEACON_DISCOVERY, warpPlusMethod(() => plus.ibeacon.stopBeaconDiscovery.bind(plus.ibeacon))); - - const makePhoneCall = defineAsyncApi(API_MAKE_PHONE_CALL, ({ phoneNumber }, { resolve }) => { - plus.device.dial(phoneNumber); - return resolve(); - }, MakePhoneCallProtocol); - - const addPhoneContact = defineAsyncApi(API_ADD_PHONE_CONTACT, ({ photoFilePath = '', nickName, lastName, middleName, firstName, remark, mobilePhoneNumber, weChatNumber, addressCountry, addressState, addressCity, addressStreet, addressPostalCode, organization, title, workFaxNumber, workPhoneNumber, hostNumber, email, url, workAddressCountry, workAddressState, workAddressCity, workAddressStreet, workAddressPostalCode, homeFaxNumber, homePhoneNumber, homeAddressCountry, homeAddressState, homeAddressCity, homeAddressStreet, homeAddressPostalCode, }, { resolve, reject }) => { - plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE, (addressbook) => { - const contact = addressbook.create(); - const name = {}; - if (lastName) { - name.familyName = lastName; - } - if (firstName) { - name.givenName = firstName; - } - if (middleName) { - name.middleName = middleName; - } - contact.name = name; - if (nickName) { - contact.nickname = nickName; - } - if (photoFilePath) { - contact.photos = [ - { - type: 'url', - value: photoFilePath, - }, - ]; - } - if (remark) { - contact.note = remark; - } - const mobilePhone = { - type: 'mobile', - }; - const workPhone = { - type: 'work', - }; - const companyPhone = { - type: 'company', - }; - const homeFax = { - type: 'home fax', - }; - const workFax = { - type: 'work fax', - }; - if (mobilePhoneNumber) { - mobilePhone.value = mobilePhoneNumber; - } - if (workPhoneNumber) { - workPhone.value = workPhoneNumber; - } - if (hostNumber) { - companyPhone.value = hostNumber; - } - if (homeFaxNumber) { - homeFax.value = homeFaxNumber; - } - if (workFaxNumber) { - workFax.value = workFaxNumber; - } - contact.phoneNumbers = [ - mobilePhone, - workPhone, - companyPhone, - homeFax, - workFax, - ]; - if (email) { - contact.emails = [ - { - type: 'home', - value: email, - }, - ]; - } - if (url) { - contact.urls = [ - { - type: 'other', - value: url, - }, - ]; - } - if (weChatNumber) { - contact.ims = [ - { - type: 'other', - value: weChatNumber, - }, - ]; - } - const defaultAddress = { - type: 'other', - preferred: true, - }; - const homeAddress = { - type: 'home', - }; - const companyAddress = { - type: 'company', - }; - if (addressCountry) { - defaultAddress.country = addressCountry; - } - if (addressState) { - defaultAddress.region = addressState; - } - if (addressCity) { - defaultAddress.locality = addressCity; - } - if (addressStreet) { - defaultAddress.streetAddress = addressStreet; - } - if (addressPostalCode) { - defaultAddress.postalCode = addressPostalCode; - } - if (homeAddressCountry) { - homeAddress.country = homeAddressCountry; - } - if (homeAddressState) { - homeAddress.region = homeAddressState; - } - if (homeAddressCity) { - homeAddress.locality = homeAddressCity; - } - if (homeAddressStreet) { - homeAddress.streetAddress = homeAddressStreet; - } - if (homeAddressPostalCode) { - homeAddress.postalCode = homeAddressPostalCode; - } - if (workAddressCountry) { - companyAddress.country = workAddressCountry; - } - if (workAddressState) { - companyAddress.region = workAddressState; - } - if (workAddressCity) { - companyAddress.locality = workAddressCity; - } - if (workAddressStreet) { - companyAddress.streetAddress = workAddressStreet; - } - if (workAddressPostalCode) { - companyAddress.postalCode = workAddressPostalCode; - } - contact.addresses = [ - defaultAddress, - homeAddress, - companyAddress, - ]; - contact.save(() => { - resolve({ - errMsg: 'addPhoneContact:ok', - }); - }, (e) => { - reject('addPhoneContact:fail'); - }); - }, (e) => { - reject('addPhoneContact:fail'); - }); - }, MakePhoneCallProtocol); - - function requireNativePlugin(pluginName) { - if (typeof weex !== 'undefined') { - return weex.requireModule(pluginName); - } - return __requireNativePlugin__(pluginName); - } - function sendNativeEvent(event, data, callback) { - // 实时获取weex module(weex可能会变化,比如首页nvue加速显示时) - return requireNativePlugin('plus').sendNativeEvent(event, data, callback); - } - - const getClipboardData = defineAsyncApi(API_GET_CLIPBOARD_DATA, (_, { resolve, reject }) => { - const clipboard = requireNativePlugin('clipboard'); - clipboard.getString((ret) => { - if (ret.result === 'success') { - resolve({ - data: ret.data, - }); - } - else { - reject('getClipboardData:fail'); - } - }); - }); - const setClipboardData = defineAsyncApi(API_SET_CLIPBOARD_DATA, (options, { resolve }) => { - const clipboard = requireNativePlugin('clipboard'); - clipboard.setString(options.data); - resolve(); - }, SetClipboardDataProtocol, SetClipboardDataOptions); - - const API_ON_NETWORK_STATUS_CHANGE = 'onNetworkStatusChange'; - function networkListener() { - getNetworkType().then(({ networkType }) => { - UniServiceJSBridge.invokeOnCallback(API_ON_NETWORK_STATUS_CHANGE, { - isConnected: networkType !== 'none', - networkType, - }); - }); - } - // 注意:框架对on类的API已做了统一的前置处理(仅首次调用on方法时,会调用具体的平台on实现,后续调用,框架不会再调用,实现时,直接监听平台事件即可) - const onNetworkStatusChange = defineOnApi(API_ON_NETWORK_STATUS_CHANGE, () => { - plus.globalEvent.addEventListener('netchange', networkListener); - }); - // 注意:框架对off类的API已做了统一的前置处理(仅当框架内不存在对应的on监听时,会调用具体的平台off实现,若还存在事件,框架不会再调用,具体实现时,直接移除平台事件即可) - const offNetworkStatusChange = defineOffApi('offNetworkStatusChange', () => { - plus.globalEvent.removeEventListener('netchange', networkListener); - }); - const getNetworkType = defineAsyncApi('getNetworkType', (_args, { resolve }) => { - let networkType = NETWORK_TYPES[plus.networkinfo.getCurrentType()] || 'unknown'; - return resolve({ networkType }); - }); - - function checkIsSupportFaceID() { - const platform = plus.os.name.toLowerCase(); - if (platform !== 'ios') { - return false; - } - const faceID = requireNativePlugin('faceID'); - return !!(faceID && faceID.isSupport()); - } - function checkIsSupportFingerPrint() { - return !!(plus.fingerprint && plus.fingerprint.isSupport()); - } - const baseCheckIsSupportSoterAuthentication = (resolve) => { - const supportMode = []; - if (checkIsSupportFingerPrint()) { - supportMode.push('fingerPrint'); - } - if (checkIsSupportFaceID()) { - supportMode.push('facial'); - } - resolve && - resolve({ - supportMode, - }); - return { - supportMode, - errMsg: 'checkIsSupportSoterAuthentication:ok', - }; - }; - const checkIsSupportSoterAuthentication = defineAsyncApi(API_CHECK_IS_SUPPORT_SOTER_AUTHENTICATION, (_, { resolve, reject }) => { - baseCheckIsSupportSoterAuthentication(resolve); - }); - const basecheckIsSoterEnrolledInDevice = ({ checkAuthMode, resolve, reject, }) => { - const wrapReject = (errMsg, errRes) => reject && reject(errMsg, errRes); - const wrapResolve = (res) => resolve && resolve(res); - if (checkAuthMode === 'fingerPrint') { - if (checkIsSupportFingerPrint()) { - const isEnrolled = plus.fingerprint.isKeyguardSecure() && - plus.fingerprint.isEnrolledFingerprints(); - wrapResolve({ isEnrolled }); - return { - isEnrolled, - errMsg: 'checkIsSoterEnrolledInDevice:ok', - }; - } - wrapReject('not support', { isEnrolled: false }); - return { - isEnrolled: false, - errMsg: 'checkIsSoterEnrolledInDevice:fail not support', - }; - } - else if (checkAuthMode === 'facial') { - if (checkIsSupportFaceID()) { - const faceID = requireNativePlugin('faceID'); - const isEnrolled = faceID && faceID.isKeyguardSecure() && faceID.isEnrolledFaceID(); - wrapResolve({ isEnrolled }); - return { - isEnrolled, - errMsg: 'checkIsSoterEnrolledInDevice:ok', - }; - } - wrapReject('not support', { isEnrolled: false }); - return { - isEnrolled: false, - errMsg: 'checkIsSoterEnrolledInDevice:fail not support', - }; - } - wrapReject('not support', { isEnrolled: false }); - return { - isEnrolled: false, - errMsg: 'checkIsSoterEnrolledInDevice:fail not support', - }; - }; - const checkIsSoterEnrolledInDevice = defineAsyncApi(API_CHECK_IS_SOTER_ENROLLED_IN_DEVICE, ({ checkAuthMode }, { resolve, reject }) => { - basecheckIsSoterEnrolledInDevice({ checkAuthMode, resolve, reject }); - }, CheckIsSoterEnrolledInDeviceProtocols, CheckIsSoterEnrolledInDeviceOptions); - const startSoterAuthentication = defineAsyncApi(API_START_SOTER_AUTHENTICATION, ({ requestAuthModes, challenge = false, authContent }, { resolve, reject }) => { - /* - 以手机不支持facial未录入fingerPrint为例 - requestAuthModes:['facial','fingerPrint']时,微信小程序返回值里的authMode为"fingerPrint" - requestAuthModes:['fingerPrint','facial']时,微信小程序返回值里的authMode为"fingerPrint" - 即先过滤不支持的方式之后再判断是否录入 - 微信小程序errCode(从企业号开发者中心查到如下文档): - 0:识别成功 'startSoterAuthentication:ok' - 90001:本设备不支持SOTER 'startSoterAuthentication:fail not support soter' - 90002:用户未授权微信使用该生物认证接口 注:APP端暂不支持 - 90003:请求使用的生物认证方式不支持 'startSoterAuthentication:fail no corresponding mode' - 90004:未传入challenge或challenge长度过长(最长512字符)注:APP端暂不支持 - 90005:auth_content长度超过限制(最长42个字符)注:微信小程序auth_content指纹识别时无效果,faceID暂未测试 - 90007:内部错误 'startSoterAuthentication:fail auth key update error' - 90008:用户取消授权 'startSoterAuthentication:fail cancel' - 90009:识别失败 'startSoterAuthentication:fail' - 90010:重试次数过多被冻结 'startSoterAuthentication:fail authenticate freeze. please try again later' - 90011:用户未录入所选识别方式 'startSoterAuthentication:fail no fingerprint enrolled' - */ - initI18nStartSoterAuthenticationMsgsOnce(); - const { t } = useI18n(); - const supportMode = baseCheckIsSupportSoterAuthentication().supportMode; - if (supportMode.length === 0) { - return { - authMode: 'fingerPrint', - errCode: 90001, - errMsg: 'startSoterAuthentication:fail', - }; - } - const supportRequestAuthMode = []; - requestAuthModes.map((item, index) => { - if (supportMode.indexOf(item) > -1) { - supportRequestAuthMode.push(item); - } - }); - if (supportRequestAuthMode.length === 0) { - return { - authMode: 'fingerPrint', - errCode: 90003, - errMsg: 'startSoterAuthentication:fail no corresponding mode', - }; - } - const enrolledRequestAuthMode = []; - supportRequestAuthMode.map((item, index) => { - const checked = basecheckIsSoterEnrolledInDevice({ - checkAuthMode: item, - }).isEnrolled; - if (checked) { - enrolledRequestAuthMode.push(item); - } - }); - if (enrolledRequestAuthMode.length === 0) { - return { - authMode: supportRequestAuthMode[0], - errCode: 90011, - errMsg: `startSoterAuthentication:fail no ${supportRequestAuthMode[0]} enrolled`, - }; - } - const realAuthMode = enrolledRequestAuthMode[0]; - if (realAuthMode === 'fingerPrint') { - if (plus.os.name.toLowerCase() === 'android') { - plus.nativeUI.showWaiting(authContent || t('uni.startSoterAuthentication.authContent')).onclose = function () { - plus.fingerprint.cancel(); - }; - } - plus.fingerprint.authenticate(() => { - plus.nativeUI.closeWaiting(); - resolve({ - authMode: realAuthMode, - errCode: 0, - }); - }, (e) => { - const res = { - authMode: realAuthMode, - }; - switch (e.code) { - case e.AUTHENTICATE_MISMATCH: - // 微信小程序没有这个回调,如果要实现此处回调需要多次触发需要用事件publish实现 - // invoke(callbackId, { - // authMode: realAuthMode, - // errCode: 90009, - // errMsg: 'startSoterAuthentication:fail' - // }) - break; - case e.AUTHENTICATE_OVERLIMIT: - // 微信小程序在第一次重试次数超限时安卓IOS返回不一致,安卓端会返回次数超过限制(errCode: 90010),IOS端会返回认证失败(errCode: 90009)。APP-IOS实际运行时不会次数超限,超过指定次数之后会弹出输入密码的界面 - plus.nativeUI.closeWaiting(); - reject('authenticate freeze. please try again later', extend(res, { - errCode: 90010, - })); - break; - case e.CANCEL: - plus.nativeUI.closeWaiting(); - reject('cancel', extend(res, { - errCode: 90008, - })); - break; - default: - plus.nativeUI.closeWaiting(); - reject('', extend(res, { - errCode: 90007, - })); - break; - } - }, { - message: authContent, - }); - } - else if (realAuthMode === 'facial') { - const faceID = requireNativePlugin('faceID'); - faceID.authenticate({ - message: authContent, - }, (e) => { - const res = { - authMode: realAuthMode, - }; - if (e.type === 'success' && e.code === 0) { - resolve({ - authMode: realAuthMode, - errCode: 0, - }); - } - else { - switch (e.code) { - case 4: - reject('', extend(res, { - errCode: 90009, - })); - break; - case 5: - reject('authenticate freeze. please try again later', extend(res, { - errCode: 90010, - })); - break; - case 6: - reject('', extend(res, { - errCode: 90008, - })); - break; - default: - reject('', extend(res, { - errCode: 90007, - })); - break; - } - } - }); - } - }, StartSoterAuthenticationProtocols, StartSoterAuthenticationOptions); - - let plus_; - let weex_; - let BroadcastChannel_; - function getRuntime() { - return typeof window === 'object' && - typeof navigator === 'object' && - typeof document === 'object' - ? 'webview' - : 'v8'; - } - function getPageId() { - return plus_.webview.currentWebview().id; - } - let channel; - let globalEvent$1; - const callbacks$2 = {}; - function onPlusMessage$1(res) { - const message = res.data && res.data.__message; - if (!message || !message.__page) { - return; - } - const pageId = message.__page; - const callback = callbacks$2[pageId]; - callback && callback(message); - if (!message.keep) { - delete callbacks$2[pageId]; - } - } - function addEventListener(pageId, callback) { - if (getRuntime() === 'v8') { - if (BroadcastChannel_) { - channel && channel.close(); - channel = new BroadcastChannel_(getPageId()); - channel.onmessage = onPlusMessage$1; - } - else if (!globalEvent$1) { - globalEvent$1 = weex_.requireModule('globalEvent'); - globalEvent$1.addEventListener('plusMessage', onPlusMessage$1); - } - } - else { - // @ts-ignore - window.__plusMessage = onPlusMessage$1; - } - callbacks$2[pageId] = callback; - } - class Page { - constructor(webview) { - this.webview = webview; - } - sendMessage(data) { - const message = JSON.parse(JSON.stringify({ - __message: { - data, - }, - })); - const id = this.webview.id; - if (BroadcastChannel_) { - const channel = new BroadcastChannel_(id); - channel.postMessage(message); - } - else { - plus_.webview.postMessageToUniNView && - plus_.webview.postMessageToUniNView(message, id); - } - } - close() { - this.webview.close(); - } - } - function showPage({ context = {}, url, data = {}, style = {}, onMessage, onClose, }) { - // eslint-disable-next-line - plus_ = context.plus || plus; - // eslint-disable-next-line - weex_ = context.weex || (typeof weex === 'object' ? weex : null); - // eslint-disable-next-line - BroadcastChannel_ = - context.BroadcastChannel || - (typeof BroadcastChannel === 'object' ? BroadcastChannel : null); - const titleNView = { - autoBackButton: true, - titleSize: '17px', - }; - const pageId = `page${Date.now()}`; - style = extend({}, style); - if (style.titleNView !== false && style.titleNView !== 'none') { - style.titleNView = extend(titleNView, style.titleNView); - } - const defaultStyle = { - top: 0, - bottom: 0, - usingComponents: {}, - popGesture: 'close', - scrollIndicator: 'none', - animationType: 'pop-in', - animationDuration: 200, - uniNView: { - path: `${(typeof process === 'object' && - process.env && - process.env.VUE_APP_TEMPLATE_PATH) || - ''}/${url}.js`, - defaultFontSize: plus_.screen.resolutionWidth / 20, - viewport: plus_.screen.resolutionWidth, - }, - }; - style = extend(defaultStyle, style); - const page = plus_.webview.create('', pageId, style, { - extras: { - from: getPageId(), - runtime: getRuntime(), - data, - useGlobalEvent: !BroadcastChannel_, - }, - }); - page.addEventListener('close', onClose); - addEventListener(pageId, (message) => { - if (typeof onMessage === 'function') { - onMessage(message.data); - } - if (!message.keep) { - page.close('auto'); - } - }); - page.show(style.animationType, style.animationDuration); - return new Page(page); - } - - const scanCode = defineAsyncApi(API_SCAN_CODE, (options, { resolve, reject }) => { - initI18nScanCodeMsgsOnce(); - const { t } = useI18n(); - const statusBarStyle = getStatusBarStyle(); - const isDark = statusBarStyle !== 'light'; - let result; - let success = false; - const page = showPage({ - url: '__uniappscan', - data: Object.assign({}, options, { - messages: { - fail: t('uni.scanCode.fail'), - 'flash.on': t('uni.scanCode.flash.on'), - 'flash.off': t('uni.scanCode.flash.off'), - }, - }), - style: { - // @ts-expect-error - animationType: options.animationType || 'pop-in', - titleNView: { - autoBackButton: true, - type: 'float', - // @ts-expect-error - titleText: options.titleText || t('uni.scanCode.title'), - titleColor: '#ffffff', - backgroundColor: 'rgba(0,0,0,0)', - buttons: !options.onlyFromCamera - ? [ - { - // @ts-expect-error - text: options.albumText || t('uni.scanCode.album'), - fontSize: '17px', - width: '60px', - onclick: () => { - page.sendMessage({ - type: 'gallery', - }); - }, - }, - ] - : [], - }, - popGesture: 'close', - background: '#000000', - backButtonAutoControl: 'close', - }, - onMessage({ event, detail, }) { - result = detail; - success = event === 'marked'; - }, - onClose() { - if (isDark) { - plus.navigator.setStatusBarStyle('dark'); - } - result - ? success - ? (delete result.message, resolve(result)) - : reject(result.message) - : reject('cancel'); - }, - }); - if (isDark) { - plus.navigator.setStatusBarStyle('light'); - page.webview.addEventListener('popGesture', ({ type, result }) => { - if (type === 'start') { - plus.navigator.setStatusBarStyle('dark'); - } - else if (type === 'end' && !result) { - plus.navigator.setStatusBarStyle('light'); - } - }); - } - }, ScanCodeProtocol); - - const onThemeChange = defineOnApi(ON_THEME_CHANGE, () => { - UniServiceJSBridge.on(ON_THEME_CHANGE, (res) => { - UniServiceJSBridge.invokeOnCallback(ON_THEME_CHANGE, res); - }); - }); - - const getScreenBrightness = defineAsyncApi(API_GET_SCREEN_BRIGHTNESS, (_, { resolve }) => { - const value = plus.screen.getBrightness(false); - resolve({ value }); - }); - const setScreenBrightness = defineAsyncApi(API_SET_SCREEN_BRIGHTNESS, (options, { resolve }) => { - plus.screen.setBrightness(options.value, false); - resolve(); - }); - const setKeepScreenOn = defineAsyncApi(API_SET_KEEP_SCREEN_ON, (options, { resolve }) => { - plus.device.setWakelock(!!options.keepScreenOn); - resolve(); - }); - - const getImageInfo = defineAsyncApi(API_GET_IMAGE_INFO, (options, { resolve, reject }) => { - const path = TEMP_PATH + '/download/'; - plus.io.getImageInfo(extend(options, { - savePath: path, - filename: path, - success: warpPlusSuccessCallback(resolve), - fail: warpPlusErrorCallback(reject), - })); - }, GetImageInfoProtocol, GetImageInfoOptions); - - const getVideoInfo = defineAsyncApi(API_GET_VIDEO_INFO, (options, { resolve, reject }) => { - plus.io.getVideoInfo({ - filePath: options.src, - success: (data) => { - return { - orientation: data.orientation, - type: data.type, - duration: data.duration, - size: data.size, - height: data.height, - width: data.width, - fps: data.fps || 30, - bitrate: data.bitrate, - }; - }, - fail: warpPlusErrorCallback(reject), - }); - }, GetVideoInfoProtocol, GetVideoInfoOptions); - - const previewImage = defineAsyncApi(API_PREVIEW_IMAGE, ({ current = 0, indicator = 'number', loop = false, urls, longPressActions }, { resolve, reject }) => { - initI18nChooseImageMsgsOnce(); - const { t } = useI18n(); - urls = urls.map((url) => getRealPath(url)); - const index = Number(current); - if (isNaN(index)) { - current = urls.indexOf(getRealPath(current)); - current = current < 0 ? 0 : current; - } - else { - current = index; - } - plus.nativeUI.previewImage(urls, { - current, - indicator, - loop, - onLongPress: function (res) { - let itemList = []; - let itemColor = ''; - const hasLongPressActions = longPressActions && isPlainObject(longPressActions); - if (!hasLongPressActions) { - itemList = [t('uni.previewImage.button.save')]; - itemColor = '#000000'; - } - else { - itemList = longPressActions.itemList - ? longPressActions.itemList - : []; - itemColor = longPressActions.itemColor - ? longPressActions.itemColor - : '#000000'; - } - const options = { - buttons: itemList.map((item) => ({ - title: item, - color: itemColor, - })), - cancel: t('uni.previewImage.cancel'), - }; - plus.nativeUI.actionSheet(options, (e) => { - if (e.index > 0) { - if (hasLongPressActions) { - typeof longPressActions.success === 'function' && - longPressActions.success({ - tapIndex: e.index - 1, - index: res.index, - }); - return; - } - plus.gallery.save(res.url, () => { - plus.nativeUI.toast(t('uni.previewImage.save.success')); - }, function () { - plus.nativeUI.toast(t('uni.previewImage.save.fail')); - }); - } - else if (hasLongPressActions) { - typeof longPressActions.fail === 'function' && - longPressActions.fail({ - errMsg: 'showActionSheet:fail cancel', - }); - } - }); - }, - }); - resolve(); - }, PreviewImageProtocol, PreviewImageOptions); - const closePreviewImage = defineAsyncApi(API_CLOSE_PREVIEW_IMAGE, (_, { resolve, reject }) => { - try { - // @ts-expect-error - plus.nativeUI.closePreviewImage(); - resolve(); - } - catch (error) { - reject(); - } - }); - - let recorder; - let recording = false; - let recordTimeout; - const publishRecorderStateChange = (state, res = {}) => { - onRecorderStateChange(extend({ - state, - }, res)); - }; - const Recorder = { - start({ duration = 60000, sampleRate, numberOfChannels, encodeBitRate, format = 'mp3', frameSize, - // audioSource = 'auto', - }) { - if (recording) { - return publishRecorderStateChange('start'); - } - recorder = plus.audio.getRecorder(); - recorder.record({ - format, - samplerate: sampleRate ? String(sampleRate) : '', - filename: TEMP_PATH + '/recorder/', - }, (res) => publishRecorderStateChange('stop', { - tempFilePath: res, - }), (err) => publishRecorderStateChange('error', { - errMsg: err.message, - })); - recordTimeout = setTimeout(() => { - Recorder.stop(); - }, duration); - publishRecorderStateChange('start'); - recording = true; - }, - stop() { - if (recording) { - recorder.stop(); - recording = false; - recordTimeout && clearTimeout(recordTimeout); - } - }, - pause() { - if (recording) { - publishRecorderStateChange('error', { - errMsg: 'Unsupported operation: pause', - }); - } - }, - resume() { - if (recording) { - publishRecorderStateChange('error', { - errMsg: 'Unsupported operation: resume', - }); - } - }, - }; - const callbacks$1 = { - pause: null, - resume: null, - start: null, - stop: null, - error: null, - }; - function onRecorderStateChange(res) { - const state = res.state; - delete res.state; - delete res.errMsg; - if (state && typeof callbacks$1[state] === 'function') { - callbacks$1[state](res); - } - } - class RecorderManager { - constructor() { } - onError(callback) { - callbacks$1.error = callback; - } - onFrameRecorded(callback) { } - onInterruptionBegin(callback) { } - onInterruptionEnd(callback) { } - onPause(callback) { - callbacks$1.pause = callback; - } - onResume(callback) { - callbacks$1.resume = callback; - } - onStart(callback) { - callbacks$1.start = callback; - } - onStop(callback) { - callbacks$1.stop = callback; - } - pause() { - Recorder.pause(); - } - resume() { - Recorder.resume(); - } - start(options) { - Recorder.start(options); - } - stop() { - Recorder.stop(); - } - } - let recorderManager; - const getRecorderManager = defineSyncApi(API_GET_RECORDER_MANAGER, () => recorderManager || (recorderManager = new RecorderManager())); - - const saveVideoToPhotosAlbum = defineAsyncApi(API_SAVE_VIDEO_TO_PHOTOS_ALBUM, (options, { resolve, reject }) => { - plus.gallery.save(options.filePath, warpPlusSuccessCallback(resolve), warpPlusErrorCallback(reject)); - }, SaveVideoToPhotosAlbumProtocol, SaveVideoToPhotosAlbumOptions); - - const saveImageToPhotosAlbum = defineAsyncApi(API_SAVE_IMAGE_TO_PHOTOS_ALBUM, (options, { resolve, reject }) => { - plus.gallery.save(options.filePath, warpPlusSuccessCallback(resolve), warpPlusErrorCallback(reject)); - }, SaveImageToPhotosAlbumProtocol, SaveImageToPhotosAlbumOptions); - - const compressImage = defineAsyncApi(API_COMPRESS_IMAGE, (options, { resolve, reject }) => { - const dst = `${TEMP_PATH}/compressed/${Date.now()}_${getFileName(options.src)}`; - plus.zip.compressImage(extend({}, options, { - dst, - }), () => { - resolve({ - tempFilePath: dst, - }); - }, reject); - }, CompressImageProtocol, CompressImageOptions); - - const compressVideo = defineAsyncApi(API_COMPRESS_VIDEO, (options, { resolve, reject }) => { - const filename = `${TEMP_PATH}/compressed/${Date.now()}_${getFileName(options.src)}`; - plus.zip.compressVideo(extend({}, options, { - filename, - }), () => { - resolve({ - tempFilePath: filename, - }); - }, reject); - }, CompressVideoProtocol, CompressVideoOptions); - - /** - * 获取文件信息 - * @param {string} filePath 文件路径 - * @returns {Promise} 文件信息Promise - */ - function getFileInfo(filePath) { - return new Promise((resolve, reject) => { - plus.io.resolveLocalFileSystemURL(filePath, function (entry) { - entry.getMetadata(resolve, reject, false); - }, reject); - }); - } - const chooseImage = defineAsyncApi(API_CHOOSE_IMAGE, ({ count, sizeType, sourceType, crop } = {}, { resolve, reject }) => { - initI18nChooseImageMsgsOnce(); - const { t } = useI18n(); - const errorCallback = warpPlusErrorCallback(reject); - function successCallback(paths) { - const tempFiles = []; - const tempFilePaths = []; - Promise.all(paths.map((path) => getFileInfo(path))) - .then((filesInfo) => { - filesInfo.forEach((file, index) => { - const path = paths[index]; - tempFilePaths.push(path); - tempFiles.push({ path, size: file.size }); - }); - resolve({ - tempFilePaths, - tempFiles, - }); - }) - .catch(errorCallback); - } - function openCamera() { - const camera = plus.camera.getCamera(); - camera.captureImage((path) => successCallback([path]), errorCallback, { - filename: TEMP_PATH + '/camera/', - resolution: 'high', - crop, - // @ts-expect-error - sizeType, - }); - } - function openAlbum() { - // @ts-ignore 5+此API分单选和多选,多选返回files:string[] - plus.gallery.pick(({ files }) => successCallback(files), errorCallback, { - maximum: count, - multiple: true, - system: false, - filename: TEMP_PATH + '/gallery/', - permissionAlert: true, - crop, - // @ts-expect-error - sizeType, - }); - } - if (sourceType.length === 1) { - if (sourceType.includes('album')) { - openAlbum(); - return; - } - else if (sourceType.includes('camera')) { - openCamera(); - return; - } - } - plus.nativeUI.actionSheet({ - cancel: t('uni.chooseImage.cancel'), - buttons: [ - { - title: t('uni.chooseImage.sourceType.camera'), - }, - { - title: t('uni.chooseImage.sourceType.album'), - }, - ], - }, (e) => { - switch (e.index) { - case 1: - openCamera(); - break; - case 2: - openAlbum(); - break; - default: - errorCallback(); - break; - } - }); - }, ChooseImageProtocol, ChooseImageOptions); - - const chooseVideo = defineAsyncApi(API_CHOOSE_VIDEO, ({ sourceType, compressed, maxDuration, camera }, { resolve, reject }) => { - initI18nChooseVideoMsgsOnce(); - const { t } = useI18n(); - const errorCallback = warpPlusErrorCallback(reject); - function successCallback(tempFilePath) { - plus.io.getVideoInfo({ - filePath: tempFilePath, - success(videoInfo) { - const result = { - errMsg: 'chooseVideo:ok', - tempFilePath: tempFilePath, - size: videoInfo.size, - duration: videoInfo.duration, - width: videoInfo.width, - height: videoInfo.height, - }; - // @ts-expect-error tempFile、name 仅H5支持 - resolve(result); - }, - fail: errorCallback, - }); - } - function openAlbum() { - plus.gallery.pick( - // @ts-ignore 5+此API分单选和多选,多选返回files:string[] - ({ files }) => successCallback(files[0]), errorCallback, { - filter: 'video', - system: false, - // 不启用 multiple 时 system 无效 - multiple: true, - maximum: 1, - filename: TEMP_PATH + '/gallery/', - permissionAlert: true, - // @ts-expect-error 新增参数,用于视频压缩 - videoCompress: compressed, - }); - } - function openCamera() { - const plusCamera = plus.camera.getCamera(); - plusCamera.startVideoCapture(successCallback, errorCallback, { - index: camera === 'front' ? '2' : '1', - videoMaximumDuration: maxDuration, - filename: TEMP_PATH + '/camera/', - // @ts-expect-error 新增参数,用于视频压缩 - videoCompress: compressed, - }); - } - if (sourceType.length === 1) { - if (sourceType.includes('album')) { - openAlbum(); - return; - } - else if (sourceType.includes('camera')) { - openCamera(); - return; - } - } - plus.nativeUI.actionSheet({ - cancel: t('uni.chooseVideo.cancel'), - buttons: [ - { - title: t('uni.chooseVideo.sourceType.camera'), - }, - { - title: t('uni.chooseVideo.sourceType.album'), - }, - ], - }, (e) => { - switch (e.index) { - case 1: - openCamera(); - break; - case 2: - openAlbum(); - break; - default: - errorCallback(); - break; - } - }); - }, ChooseVideoProtocol, ChooseVideoOptions); - - const showKeyboard = defineAsyncApi(API_SHOW_KEYBOARD, (_, { resolve }) => { - plus.key.showSoftKeybord(); - resolve(); - }); - const hideKeyboard = defineAsyncApi(API_HIDE_KEYBOARD, (_, { resolve }) => { - plus.key.hideSoftKeybord(); - resolve(); - }); - function onKeyboardHeightChangeCallback(res) { - UniServiceJSBridge.invokeOnCallback(ON_KEYBOARD_HEIGHT_CHANGE, res); - } - const onKeyboardHeightChange = defineOnApi(ON_KEYBOARD_HEIGHT_CHANGE, () => { - UniServiceJSBridge.on(ON_KEYBOARD_HEIGHT_CHANGE, onKeyboardHeightChangeCallback); - }); - const offKeyboardHeightChange = defineOffApi(ON_KEYBOARD_HEIGHT_CHANGE, () => { - UniServiceJSBridge.off(ON_KEYBOARD_HEIGHT_CHANGE, onKeyboardHeightChangeCallback); - }); - - class DownloadTask { - constructor(downloader) { - this._callbacks = []; - this._downloader = downloader; - downloader.addEventListener('statechanged', (download, status) => { - if (download.downloadedSize && download.totalSize) { - this._callbacks.forEach((callback) => { - callback({ - progress: Math.round((download.downloadedSize / download.totalSize) * 100), - totalBytesWritten: download.downloadedSize, - totalBytesExpectedToWrite: download.totalSize, - }); - }); - } - }); - } - abort() { - this._downloader.abort(); - } - onProgressUpdate(callback) { - if (typeof callback !== 'function') { - return; - } - this._callbacks.push(callback); - } - offProgressUpdate(callback) { - const index = this._callbacks.indexOf(callback); - if (index >= 0) { - this._callbacks.splice(index, 1); - } - } - onHeadersReceived(callback) { - throw new Error('Method not implemented.'); - } - offHeadersReceived(callback) { - throw new Error('Method not implemented.'); - } - } - const downloadFile = defineTaskApi(API_DOWNLOAD_FILE, ({ url, header, timeout }, { resolve, reject }) => { - timeout = - (timeout || - (__uniConfig.networkTimeout && __uniConfig.networkTimeout.request) || - 60 * 1000) / 1000; - const downloader = plus.downloader.createDownload(url, { - timeout, - filename: TEMP_PATH + '/download/', - // 需要与其它平台上的表现保持一致,不走重试的逻辑。 - retry: 0, - retryInterval: 0, - }, (download, statusCode) => { - if (statusCode) { - resolve({ - tempFilePath: download.filename, - statusCode, - }); - } - else { - reject(`statusCode: ${statusCode}`); - } - }); - const downloadTask = new DownloadTask(downloader); - for (const name in header) { - if (hasOwn$1(header, name)) { - downloader.setRequestHeader(name, header[name]); - } - } - downloader.start(); - return downloadTask; - }, DownloadFileProtocol, DownloadFileOptions); - - const cookiesParse = (header) => { - let cookiesStr = header['Set-Cookie'] || header['set-cookie']; - let cookiesArr = []; - if (!cookiesStr) { - return []; - } - if (cookiesStr[0] === '[' && cookiesStr[cookiesStr.length - 1] === ']') { - cookiesStr = cookiesStr.slice(1, -1); - } - const handleCookiesArr = cookiesStr.split(';'); - for (let i = 0; i < handleCookiesArr.length; i++) { - if (handleCookiesArr[i].indexOf('Expires=') !== -1 || - handleCookiesArr[i].indexOf('expires=') !== -1) { - cookiesArr.push(handleCookiesArr[i].replace(',', '')); - } - else { - cookiesArr.push(handleCookiesArr[i]); - } - } - cookiesArr = cookiesArr.join(';').split(','); - return cookiesArr; - }; - function formatResponse(res, args) { - if (typeof res.data === 'string' && res.data.charCodeAt(0) === 65279) { - res.data = res.data.substr(1); - } - res.statusCode = parseInt(String(res.statusCode), 10); - if (isPlainObject(res.header)) { - res.header = Object.keys(res.header).reduce(function (ret, key) { - const value = res.header[key]; - if (Array.isArray(value)) { - ret[key] = value.join(','); - } - else if (typeof value === 'string') { - ret[key] = value; - } - return ret; - }, {}); - } - if (args.dataType && args.dataType.toLowerCase() === 'json') { - try { - res.data = JSON.parse(res.data); - } - catch (e) { } - } - return res; - } - /** - * 请求任务类 - */ - class RequestTask { - constructor(requestTask) { - this._requestTask = requestTask; - } - abort() { - this._requestTask.abort(); - } - offHeadersReceived() { } - onHeadersReceived() { } - } - const request = defineTaskApi(API_REQUEST, (args, { resolve, reject }) => { - let { header, method, data, timeout, url, responseType, sslVerify, firstIpv4, - // NOTE 属性有但是types没有 - // @ts-ignore - tls, } = args; - let contentType; - for (const name in header) { - if (name.toLowerCase() === 'content-type') { - contentType = header[name]; - break; - } - } - if (method !== 'GET' && - contentType.indexOf('application/json') === 0 && - isPlainObject(data)) { - data = JSON.stringify(data); - } - const stream = requireNativePlugin('stream'); - const headers = {}; - let abortTimeout; - let aborted; - let hasContentType = false; - for (const name in header) { - if (!hasContentType && name.toLowerCase() === 'content-type') { - hasContentType = true; - headers['Content-Type'] = header[name]; - // TODO 需要重构 - if (method !== 'GET' && - header[name].indexOf('application/x-www-form-urlencoded') === 0 && - typeof data !== 'string' && - !(data instanceof ArrayBuffer)) { - const bodyArray = []; - for (const key in data) { - if (hasOwn$1(data, key)) { - bodyArray.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); - } - } - data = bodyArray.join('&'); - } - } - else { - headers[name] = header[name]; - } - } - if (!hasContentType && method === 'POST') { - headers['Content-Type'] = - 'application/x-www-form-urlencoded; charset=UTF-8'; - } - if (timeout) { - abortTimeout = setTimeout(() => { - aborted = true; - reject('timeout'); - }, timeout + 200); // TODO +200 发消息到原生层有时间开销,以后考虑由原生层回调超时 - } - const options = { - method, - url: url.trim(), - // weex 官方文档有误,headers 类型实际 object,用 string 类型会无响应 - headers, - type: responseType === 'arraybuffer' ? 'base64' : 'text', - // weex 官方文档未说明实际支持 timeout,单位:ms - timeout: timeout || 6e5, - // 配置和weex模块内相反 - sslVerify: !sslVerify, - firstIpv4: firstIpv4, - tls, - }; - if (method !== 'GET') { - options.body = typeof data === 'string' ? data : JSON.stringify(data); - } - stream.fetch(options, ({ ok, status, data, headers, errorMsg, }) => { - if (aborted) { - return; - } - if (abortTimeout) { - clearTimeout(abortTimeout); - } - const statusCode = status; - if (statusCode > 0) { - resolve(formatResponse({ - data: ok && responseType === 'arraybuffer' - ? base64ToArrayBuffer(data) - : data, - statusCode, - header: headers, - cookies: cookiesParse(headers), - }, args)); - } - else { - let errMsg = 'abort statusCode:' + statusCode; - if (errorMsg) { - errMsg = errMsg + ' ' + errorMsg; - } - reject(errMsg); - } - }); - return new RequestTask({ - abort() { - aborted = true; - if (abortTimeout) { - clearTimeout(abortTimeout); - } - reject('abort'); - }, - }); - }, RequestProtocol, RequestOptions); - const configMTLS = defineAsyncApi(API_CONFIG_MTLS, ({ certificates }, { resolve, reject }) => { - const stream = requireNativePlugin('stream'); - stream.configMTLS(certificates, ({ type, code, message }) => { - switch (type) { - case 'success': - resolve({ code }); - break; - case 'fail': - reject(message, { code }); - break; - } - }); - }, ConfigMTLSProtocol, ConfigMTLSOptions); - - const socketTasks = []; - const socketsMap = {}; - const globalEvent = { - open: '', - close: '', - error: '', - message: '', - }; - let socket; - function createSocketTask(args) { - const socketId = String(Date.now()); - let errMsg; - try { - if (!socket) { - socket = requireNativePlugin('uni-webSocket'); - bindSocketCallBack(socket); - } - socket.WebSocket({ - id: socketId, - url: args.url, - protocol: Array.isArray(args.protocols) - ? args.protocols.join(',') - : args.protocols, - header: args.header, - }); - } - catch (error) { - errMsg = error; - } - return { socket, socketId, errMsg }; - } - function bindSocketCallBack(socket) { - socket.onopen((e) => { - const curSocket = socketsMap[e.id]; - if (!curSocket) - return; - curSocket._socketOnOpen(); - }); - socket.onmessage((e) => { - const curSocket = socketsMap[e.id]; - if (!curSocket) - return; - curSocket._socketOnMessage(e); - }); - socket.onerror((e) => { - const curSocket = socketsMap[e.id]; - if (!curSocket) - return; - curSocket._socketOnError(); - }); - socket.onclose((e) => { - const curSocket = socketsMap[e.id]; - if (!curSocket) - return; - curSocket._socketOnClose(); - }); - } - class SocketTask { - constructor(socket, socketId) { - this.id = socketId; - this._socket = socket; - this._callbacks = { - open: [], - close: [], - error: [], - message: [], - }; - this.CLOSED = 3; - this.CLOSING = 2; - this.CONNECTING = 0; - this.OPEN = 1; - this.readyState = this.CLOSED; - if (!this._socket) - return; - } - _socketOnOpen() { - this.readyState = this.OPEN; - this.socketStateChange('open'); - } - _socketOnMessage(e) { - this.socketStateChange('message', { - data: typeof e.data === 'object' - ? base64ToArrayBuffer(e.data.base64) - : e.data, - }); - } - _socketOnError() { - this.socketStateChange('error'); - this.onErrorOrClose(); - } - _socketOnClose() { - this.socketStateChange('close'); - this.onErrorOrClose(); - } - onErrorOrClose() { - this.readyState = this.CLOSED; - delete socketsMap[this.id]; - const index = socketTasks.indexOf(this); - if (index >= 0) { - socketTasks.splice(index, 1); - } - } - socketStateChange(name, res = {}) { - const data = name === 'message' ? res : {}; - if (this === socketTasks[0] && globalEvent[name]) { - UniServiceJSBridge.invokeOnCallback(globalEvent[name], data); - } - // WYQ fix: App平台修复websocket onOpen时发送数据报错的Bug - this._callbacks[name].forEach((callback) => { - if (typeof callback === 'function') { - callback(data); - } - }); - } - send(args, callopt = true) { - if (this.readyState !== this.OPEN) { - callOptions(args, 'sendSocketMessage:fail WebSocket is not connected'); - } - try { - this._socket.send({ - id: this.id, - data: typeof args.data === 'object' - ? { - '@type': 'binary', - base64: arrayBufferToBase64(args.data), - } - : args.data, - }); - callopt && callOptions(args, 'sendSocketMessage:ok'); - } - catch (error) { - callopt && callOptions(args, `sendSocketMessage:fail ${error}`); - } - } - close(args, callopt = true) { - this.readyState = this.CLOSING; - try { - this._socket.close(extend({ - id: this.id, - args, - })); - callopt && callOptions(args, 'closeSocket:ok'); - } - catch (error) { - callopt && callOptions(args, `closeSocket:fail ${error}`); - } - } - onOpen(callback) { - this._callbacks.open.push(callback); - } - onClose(callback) { - this._callbacks.close.push(callback); - } - onError(callback) { - this._callbacks.error.push(callback); - } - onMessage(callback) { - this._callbacks.message.push(callback); - } - } - const connectSocket = defineTaskApi(API_CONNECT_SOCKET, ({ url, protocols, header, method }, { resolve, reject }) => { - const { socket, socketId, errMsg } = createSocketTask({ - url, - protocols, - header, - method, - }); - const socketTask = new SocketTask(socket, socketId); - if (errMsg) { - setTimeout(() => { - reject(errMsg); - }, 0); - } - else { - socketTasks.push(socketTask); - socketsMap[socketId] = socketTask; - } - setTimeout(() => { - resolve(); - }, 0); - return socketTask; - }, ConnectSocketProtocol, ConnectSocketOptions); - const sendSocketMessage = defineAsyncApi(API_SEND_SOCKET_MESSAGE, (args, { resolve, reject }) => { - const socketTask = socketTasks[0]; - if (!socketTask || socketTask.readyState !== socketTask.OPEN) { - reject('WebSocket is not connected'); - return; - } - socketTask.send({ data: args.data }, false); - resolve(); - }, SendSocketMessageProtocol); - const closeSocket = defineAsyncApi(API_CLOSE_SOCKET, (args, { resolve, reject }) => { - const socketTask = socketTasks[0]; - if (!socketTask) { - reject('WebSocket is not connected'); - return; - } - socketTask.readyState = socketTask.CLOSING; - socketTask.close(args, false); - resolve(); - }, CloseSocketProtocol); - function on(event) { - const api = `onSocket${capitalize(event)}`; - return defineOnApi(api, () => { - globalEvent[event] = api; - }); - } - const onSocketOpen = /*#__PURE__*/ on('open'); - const onSocketError = /*#__PURE__*/ on('error'); - const onSocketMessage = /*#__PURE__*/ on('message'); - const onSocketClose = /*#__PURE__*/ on('close'); - - class UploadTask { - constructor(uploader) { - this._callbacks = []; - this._uploader = uploader; - uploader.addEventListener('statechanged', (upload, status) => { - if (upload.uploadedSize && upload.totalSize) { - this._callbacks.forEach((callback) => { - callback({ - progress: parseInt(String((upload.uploadedSize / upload.totalSize) * 100)), - totalBytesSent: upload.uploadedSize, - totalBytesExpectedToSend: upload.totalSize, - }); - }); - } - }); - } - abort() { - this._uploader.abort(); - } - onProgressUpdate(callback) { - if (typeof callback !== 'function') { - return; - } - this._callbacks.push(callback); - } - onHeadersReceived() { } - offProgressUpdate(callback) { - const index = this._callbacks.indexOf(callback); - if (index >= 0) { - this._callbacks.splice(index, 1); - } - } - offHeadersReceived() { } - } - const uploadFile = defineTaskApi(API_UPLOAD_FILE, ({ url, timeout, header, formData, files, filePath, name }, { resolve, reject }) => { - const uploader = plus.uploader.createUpload(url, { - timeout, - // 需要与其它平台上的表现保持一致,不走重试的逻辑。 - retry: 0, - retryInterval: 0, - }, (upload, statusCode) => { - if (statusCode) { - resolve({ - data: upload.responseText, - statusCode, - }); - } - else { - reject(`statusCode: ${statusCode}`); - } - }); - for (const name in header) { - if (hasOwn$1(header, name)) { - uploader.setRequestHeader(name, String(header[name])); - } - } - for (const name in formData) { - if (hasOwn$1(formData, name)) { - uploader.addData(name, String(formData[name])); - } - } - if (files && files.length) { - files.forEach((file) => { - uploader.addFile(getRealPath(file.uri), { - key: file.name || 'file', - }); - }); - } - else { - uploader.addFile(getRealPath(filePath), { - key: name, - }); - } - const uploadFileTask = new UploadTask(uploader); - uploader.start(); - return uploadFileTask; - }, UploadFileProtocol, UploadFileOptions); - - const audios = {}; - const evts = [ - 'play', - 'canplay', - 'ended', - 'stop', - 'waiting', - 'seeking', - 'seeked', - 'pause', - ]; - const initStateChage = (audioId) => { - const audio = audios[audioId]; - if (!audio) { - return; - } - if (!audio.initStateChage) { - audio.initStateChage = true; - audio.addEventListener('error', (error) => { - onAudioStateChange({ - state: 'error', - audioId, - errMsg: 'MediaError', - errCode: error.code, - }); - }); - evts.forEach((event) => { - audio.addEventListener(event, () => { - // 添加 isStopped 属性是为了解决 安卓设备停止播放后获取播放进度不正确的问题 - if (event === 'play') { - audio.isStopped = false; - } - else if (event === 'stop') { - audio.isStopped = true; - } - onAudioStateChange({ - state: event, - audioId, - }); - }); - }); - } - }; - function createAudioInstance() { - const audioId = `${Date.now()}${Math.random()}`; - const audio = (audios[audioId] = plus.audio.createPlayer('')); // 此处空字符串必填 - audio.src = ''; - audio.volume = 1; - audio.startTime = 0; - return { - errMsg: 'createAudioInstance:ok', - audioId, - }; - } - function setAudioState({ audioId, src, startTime, autoplay = false, loop = false, obeyMuteSwitch, volume, }) { - const audio = audios[audioId]; - if (audio) { - const style = { - loop, - autoplay, - }; - if (src) { - audio.src = style.src = getRealPath(src); - } - if (startTime) { - audio.startTime = style.startTime = startTime; - } - if (typeof volume === 'number') { - audio.volume = style.volume = volume; - } - audio.setStyles(style); - initStateChage(audioId); - } - return { - errMsg: 'setAudioState:ok', - }; - } - function getAudioState({ audioId }) { - const audio = audios[audioId]; - if (!audio) { - return { - errMsg: 'getAudioState:fail', - }; - } - const { src, startTime, volume } = audio; - return { - errMsg: 'getAudioState:ok', - duration: 1e3 * (audio.getDuration() || 0), - currentTime: audio.isStopped ? 0 : 1e3 * audio.getPosition(), - paused: audio.isPaused(), - src, - volume, - startTime: 1e3 * startTime, - buffered: 1e3 * audio.getBuffered(), - }; - } - function operateAudio({ operationType, audioId, currentTime, }) { - const audio = audios[audioId]; - switch (operationType) { - case 'play': - case 'pause': - case 'stop': - audio[operationType === 'play' && audio.isPaused() ? 'resume' : operationType](); - break; - case 'seek': - typeof currentTime != 'undefined' ? audio.seekTo(currentTime / 1e3) : ''; - break; - } - return { - errMsg: 'operateAudio:ok', - }; - } - const innerAudioContexts = Object.create(null); - const onAudioStateChange = ({ state, audioId, errMsg, errCode, }) => { - const audio = innerAudioContexts[audioId]; - if (audio) { - emit(audio, state, errMsg, errCode); - if (state === 'play') { - const oldCurrentTime = audio.currentTime; - audio.__timing = setInterval(() => { - const currentTime = audio.currentTime; - if (currentTime !== oldCurrentTime) { - emit(audio, 'timeUpdate'); - } - }, 200); - } - else if (state === 'pause' || state === 'stop' || state === 'error') { - clearInterval(audio.__timing); - } - } - }; - const props$1 = [ - { - name: 'src', - cache: true, - }, - { - name: 'startTime', - default: 0, - cache: true, - }, - { - name: 'autoplay', - default: false, - cache: true, - }, - { - name: 'loop', - default: false, - cache: true, - }, - { - name: 'obeyMuteSwitch', - default: true, - readonly: true, - cache: true, - }, - { - name: 'duration', - readonly: true, - }, - { - name: 'currentTime', - readonly: true, - }, - { - name: 'paused', - readonly: true, - }, - { - name: 'buffered', - readonly: true, - }, - { - name: 'volume', - }, - ]; - class InnerAudioContext { - constructor(id) { - this.id = id; - this._callbacks = {}; - this._options = {}; - // 初始化事件监听列表 - innerAudioContextEventNames.forEach((eventName) => { - this._callbacks[eventName] = []; - }); - props$1.forEach((item) => { - const name = item.name; - Object.defineProperty(this, name, { - get: () => { - const result = item.cache - ? this._options - : getAudioState({ - audioId: this.id, - }); - const value = name in result ? result[name] : item.default; - return typeof value === 'number' && name !== 'volume' - ? value / 1e3 - : value; - }, - set: item.readonly - ? undefined - : (value) => { - this._options[name] = value; - setAudioState(extend({}, this._options, { - audioId: this.id, - })); - }, - }); - }); - initInnerAudioContextEventOnce(); - } - play() { - this._operate('play'); - } - pause() { - this._operate('pause'); - } - stop() { - this._operate('stop'); - } - seek(position) { - this._operate('seek', { - currentTime: position * 1e3, - }); - } - destroy() { - clearInterval(this.__timing); - if (audios[this.id]) { - audios[this.id].close(); - delete audios[this.id]; - } - delete innerAudioContexts[this.id]; - } - _operate(type, options) { - operateAudio(extend({}, options, { - audioId: this.id, - operationType: type, - })); - } - } - const initInnerAudioContextEventOnce = /*#__PURE__*/ once(() => { - // 批量设置音频上下文事件监听方法 - innerAudioContextEventNames.forEach((eventName) => { - InnerAudioContext.prototype[eventName] = function (callback) { - if (typeof callback === 'function') { - this._callbacks[eventName].push(callback); - } - }; - }); - // 批量设置音频上下文事件取消监听方法 - innerAudioContextOffEventNames.forEach((eventName) => { - InnerAudioContext.prototype[eventName] = function (callback) { - const callbacks = this._callbacks[eventName]; - const index = callbacks.indexOf(callback); - if (index >= 0) { - callbacks.splice(index, 1); - } - }; - }); - }); - function emit(audio, state, errMsg, errCode) { - const name = `on${capitalize(state)}`; - audio._callbacks[name].forEach((callback) => { - if (typeof callback === 'function') { - callback(state === 'error' - ? { - errMsg, - errCode, - } - : {}); - } - }); - } - /** - * 创建音频上下文 - */ - const createInnerAudioContext = defineSyncApi(API_CREATE_INNER_AUDIO_CONTEXT, () => { - const { audioId } = createAudioInstance(); - const innerAudioContext = new InnerAudioContext(audioId); - innerAudioContexts[audioId] = innerAudioContext; - return innerAudioContext; - }); - - const eventNames = [ - 'canplay', - 'play', - 'pause', - 'stop', - 'ended', - 'timeUpdate', - 'prev', - 'next', - 'error', - 'waiting', - ]; - const callbacks = { - canplay: [], - play: [], - pause: [], - stop: [], - ended: [], - timeUpdate: [], - prev: [], - next: [], - error: [], - waiting: [], - }; - let audio; - let timeUpdateTimer = null; - const TIME_UPDATE = 250; - const events = ['play', 'pause', 'ended', 'stop', 'canplay']; - function startTimeUpdateTimer() { - stopTimeUpdateTimer(); - timeUpdateTimer = setInterval(() => { - onBackgroundAudioStateChange({ state: 'timeUpdate' }); - }, TIME_UPDATE); - } - function stopTimeUpdateTimer() { - if (timeUpdateTimer !== null) { - clearInterval(timeUpdateTimer); - } - } - function initMusic() { - if (audio) { - return; - } - const publish = UniServiceJSBridge.invokeOnCallback; - audio = plus.audio.createPlayer({ - autoplay: true, - backgroundControl: true, - }); - audio.src = - audio.title = - audio.epname = - audio.singer = - audio.coverImgUrl = - audio.webUrl = - ''; - audio.startTime = 0; - events.forEach((event) => { - audio.addEventListener(event, () => { - // 添加 isStopped 属性是为了解决 安卓设备停止播放后获取播放进度不正确的问题 - if (event === 'play') { - audio.isStopped = false; - startTimeUpdateTimer(); - } - else if (event === 'stop') { - audio.isStopped = true; - } - if (event === 'pause' || event === 'ended' || event === 'stop') { - stopTimeUpdateTimer(); - } - const eventName = `onMusic${event[0].toUpperCase() + event.substr(1)}`; - publish(eventName, { - dataUrl: audio.src, - errMsg: `${eventName}:ok`, - }); - onBackgroundAudioStateChange({ - state: event, - dataUrl: audio.src, - }); - }); - }); - audio.addEventListener('waiting', () => { - stopTimeUpdateTimer(); - onBackgroundAudioStateChange({ - state: 'waiting', - dataUrl: audio.src, - }); - }); - audio.addEventListener('error', (err) => { - stopTimeUpdateTimer(); - publish('onMusicError', { - dataUrl: audio.src, - errMsg: 'Error:' + err.message, - }); - onBackgroundAudioStateChange({ - state: 'error', - dataUrl: audio.src, - errMsg: err.message, - errCode: err.code, - }); - }); - // @ts-ignore - audio.addEventListener('prev', () => publish('onBackgroundAudioPrev')); - // @ts-ignore - audio.addEventListener('next', () => publish('onBackgroundAudioNext')); - } - function getBackgroundAudioState() { - let data = { - duration: 0, - currentTime: 0, - paused: false, - src: '', - buffered: 0, - title: '', - epname: '', - singer: '', - coverImgUrl: '', - webUrl: '', - startTime: 0, - errMsg: 'getBackgroundAudioState:ok', - }; - if (audio) { - const newData = { - duration: audio.getDuration() || 0, - currentTime: audio.isStopped ? 0 : audio.getPosition(), - paused: audio.isPaused(), - src: audio.src, - buffered: audio.getBuffered(), - title: audio.title, - epname: audio.epname, - singer: audio.singer, - coverImgUrl: audio.coverImgUrl, - webUrl: audio.webUrl, - startTime: audio.startTime, - }; - data = extend(data, newData); - } - return data; - } - function setMusicState(args) { - initMusic(); - const props = [ - 'src', - 'startTime', - 'coverImgUrl', - 'webUrl', - 'singer', - 'epname', - 'title', - ]; - const style = {}; - Object.keys(args).forEach((key) => { - if (props.indexOf(key) >= 0) { - let val = args[key]; - if (key === props[0] && val) { - val = getRealPath(val); - } - audio[key] = style[key] = val; - } - }); - audio.setStyles(style); - } - function operateMusicPlayer({ operationType, src, position, api = 'operateMusicPlayer', title, coverImgUrl, }) { - var operationTypes = ['resume', 'pause', 'stop']; - if (operationTypes.indexOf(operationType) > 0) { - audio && audio[operationType](); - } - else if (operationType === 'play') { - setMusicState({ - src, - startTime: position, - title, - coverImgUrl, - }); - audio.play(); - } - else if (operationType === 'seek') { - audio && audio.seekTo(position); - } - return { - errMsg: `${api}:ok`, - }; - } - function operateBackgroundAudio({ operationType, src, startTime, currentTime, }) { - return operateMusicPlayer({ - operationType, - src, - position: startTime || currentTime || 0, - api: 'operateBackgroundAudio', - }); - } - function onBackgroundAudioStateChange({ state, errMsg, errCode, dataUrl, }) { - callbacks[state].forEach((callback) => { - if (typeof callback === 'function') { - callback(state === 'error' - ? { - errMsg, - errCode, - } - : {}); - } - }); - } - const onInitBackgroundAudioManager = /*#__PURE__*/ once(() => { - eventNames.forEach((item) => { - BackgroundAudioManager.prototype[`on${capitalize(item)}`] = - function (callback) { - callbacks[item].push(callback); - }; - }); - }); - const props = [ - { - name: 'duration', - readonly: true, - }, - { - name: 'currentTime', - readonly: true, - }, - { - name: 'paused', - readonly: true, - }, - { - name: 'src', - cache: true, - }, - { - name: 'startTime', - default: 0, - cache: true, - }, - { - name: 'buffered', - readonly: true, - }, - { - name: 'title', - cache: true, - }, - { - name: 'epname', - cache: true, - }, - { - name: 'singer', - cache: true, - }, - { - name: 'coverImgUrl', - cache: true, - }, - { - name: 'webUrl', - cache: true, - }, - { - name: 'protocol', - readonly: true, - default: 'http', - }, - ]; - class BackgroundAudioManager { - constructor() { - this._options = {}; - props.forEach((item) => { - const name = item.name; - Object.defineProperty(this, name, { - get: () => { - const result = item.cache ? this._options : getBackgroundAudioState(); - return name in result ? result[name] : item.default; - }, - set: item.readonly - ? undefined - : (value) => { - this._options[name] = value; - setMusicState(this._options); - }, - }); - }); - onInitBackgroundAudioManager(); - } - play() { - this._operate('play'); - } - pause() { - this._operate('pause'); - } - stop() { - this._operate('stop'); - } - seek(position) { - this._operate('seek', { - currentTime: position, - }); - } - _operate(type, options) { - operateBackgroundAudio(extend({}, options, { - operationType: type, - })); - } - } - let backgroundAudioManager; - const getBackgroundAudioManager = defineSyncApi(API_GET_BACKGROUND_AUDIO_MANAGER, () => backgroundAudioManager || - (backgroundAudioManager = new BackgroundAudioManager())); - class LivePusherContext { - constructor(id, ctx) { - this.id = id; - this.ctx = ctx; - } - start(option) { - return invokeVmMethodWithoutArgs(this.ctx, 'start', option); - } - stop(option) { - return invokeVmMethodWithoutArgs(this.ctx, 'stop', option); - } - pause(option) { - return invokeVmMethodWithoutArgs(this.ctx, 'pause', option); - } - resume(option) { - return invokeVmMethodWithoutArgs(this.ctx, 'resume', option); - } - switchCamera(option) { - return invokeVmMethodWithoutArgs(this.ctx, 'switchCamera', option); - } - snapshot(option) { - return invokeVmMethodWithoutArgs(this.ctx, 'snapshot', option); - } - toggleTorch(option) { - return invokeVmMethodWithoutArgs(this.ctx, 'toggleTorch', option); - } - playBGM(option) { - return invokeVmMethod(this.ctx, 'playBGM', option); - } - stopBGM(option) { - return invokeVmMethodWithoutArgs(this.ctx, 'stopBGM', option); - } - pauseBGM(option) { - return invokeVmMethodWithoutArgs(this.ctx, 'pauseBGM', option); - } - resumeBGM(option) { - return invokeVmMethodWithoutArgs(this.ctx, 'resumeBGM', option); - } - setBGMVolume(option) { - return invokeVmMethod(this.ctx, 'setBGMVolume', option); - } - startPreview(option) { - return invokeVmMethodWithoutArgs(this.ctx, 'startPreview', option); - } - stopPreview(args) { - return invokeVmMethodWithoutArgs(this.ctx, 'stopPreview', args); - } - } - const createLivePusherContext = defineSyncApi(API_CREATE_LIVE_PUSHER_CONTEXT, (id, vm) => { - if (!vm) { - return console.warn('uni.createLivePusherContext: 2 arguments required, but only 1 present'); - } - const elm = findElmById(id, vm); - if (!elm) { - return console.warn('Can not find `' + id + '`'); - } - return new LivePusherContext(id, elm); - }, CreateLivePusherContextProtocol); + var static_l_desc; + var static_d_desc; + var static_bl_desc; - const PI = 3.1415926535897932384626; - const a = 6378245.0; - const ee = 0.00669342162296594323; - function gcj02towgs84(lng, lat) { - lat = +lat; - lng = +lng; - if (outOfChina(lng, lat)) { - return [lng, lat]; - } - let dlat = _transformlat(lng - 105.0, lat - 35.0); - let dlng = _transformlng(lng - 105.0, lat - 35.0); - const radlat = (lat / 180.0) * PI; - let magic = Math.sin(radlat); - magic = 1 - ee * magic * magic; - const sqrtmagic = Math.sqrt(magic); - dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI); - dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI); - const mglat = lat + dlat; - const mglng = lng + dlng; - return [lng * 2 - mglng, lat * 2 - mglat]; - } - function wgs84togcj02(lng, lat) { - lat = +lat; - lng = +lng; - if (outOfChina(lng, lat)) { - return [lng, lat]; - } - let dlat = _transformlat(lng - 105.0, lat - 35.0); - let dlng = _transformlng(lng - 105.0, lat - 35.0); - const radlat = (lat / 180.0) * PI; - let magic = Math.sin(radlat); - magic = 1 - ee * magic * magic; - const sqrtmagic = Math.sqrt(magic); - dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI); - dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI); - const mglat = lat + dlat; - const mglng = lng + dlng; - return [mglng, mglat]; - } - const outOfChina = function (lng, lat) { - return (lng < 72.004 || lng > 137.8347 || lat < 0.8293 || lat > 55.8271 || false); - }; - const _transformlat = function (lng, lat) { - let ret = -100.0 + - 2.0 * lng + - 3.0 * lat + - 0.2 * lat * lat + - 0.1 * lng * lat + - 0.2 * Math.sqrt(Math.abs(lng)); - ret += - ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * - 2.0) / - 3.0; - ret += - ((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) * 2.0) / - 3.0; - ret += - ((160.0 * Math.sin((lat / 12.0) * PI) + 320 * Math.sin((lat * PI) / 30.0)) * - 2.0) / - 3.0; - return ret; - }; - const _transformlng = function (lng, lat) { - let ret = 300.0 + - lng + - 2.0 * lat + - 0.1 * lng * lng + - 0.1 * lng * lat + - 0.1 * Math.sqrt(Math.abs(lng)); - ret += - ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * - 2.0) / - 3.0; - ret += - ((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) * 2.0) / - 3.0; - ret += - ((150.0 * Math.sin((lng / 12.0) * PI) + - 300.0 * Math.sin((lng / 30.0) * PI)) * - 2.0) / - 3.0; - return ret; - }; - function getLocationSuccess(type, position, resolve) { - const coords = position.coords; - if (type !== position.coordsType) { - let coordArray; - if (type === 'wgs84') { - coordArray = gcj02towgs84(coords.longitude, coords.latitude); - } - else if (type === 'gcj02') { - coordArray = wgs84togcj02(coords.longitude, coords.latitude); - } - if (coordArray) { - coords.longitude = coordArray[0]; - coords.latitude = coordArray[1]; - } - } - resolve({ - type, - altitude: coords.altitude || 0, - latitude: coords.latitude, - longitude: coords.longitude, - speed: coords.speed, - accuracy: coords.accuracy, - address: position.address, - errMsg: 'getLocation:ok', - }); - } - const getLocation = defineAsyncApi(API_GET_LOCATION, ({ type = 'wgs84', geocode = false, altitude = false, highAccuracyExpireTime, }, { resolve, reject }) => { - plus.geolocation.getCurrentPosition((position) => { - getLocationSuccess(type, position, resolve); - }, (e) => { - // 坐标地址解析失败 - if (e.code === 1501) { - getLocationSuccess(type, e, resolve); - return; - } - reject('getLocation:fail ' + e.message); - }, { - geocode: geocode, - enableHighAccuracy: altitude, - timeout: highAccuracyExpireTime, - }); - }, GetLocationProtocol, GetLocationOptions); + function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ + } + + + + function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; + } + + + /* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ + function put_short(s, w) { + // put_byte(s, (uch)((w) & 0xff)); + // put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; + } + + + /* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ + function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } + } + + + function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); + } + + + /* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ + function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; + } + + + /* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ + function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } + } + + + /* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ + function gen_bitlen(s, desc) + // deflate_state *s; + // tree_desc *desc; /* the tree descriptor */ + { + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS$1; bits++) { + s.bl_count[bits] = 0; + } - const chooseLocation = defineAsyncApi(API_CHOOSE_LOCATION, (options, { resolve, reject }) => { - const statusBarStyle = getStatusBarStyle(); - const isDark = statusBarStyle !== 'light'; - let result; - const page = showPage({ - url: '__uniappchooselocation', - data: options, - style: { - // @ts-expect-error - animationType: options.animationType || 'slide-in-bottom', - // @ts-expect-error - titleNView: false, - popGesture: 'close', - scrollIndicator: 'none', - }, - onMessage({ event, detail, }) { - if (event === 'selected') { - result = detail; - } - }, - onClose() { - if (isDark) { - plus.navigator.setStatusBarStyle('dark'); - } - result ? resolve(result) : reject('cancel'); - }, - }); - if (isDark) { - plus.navigator.setStatusBarStyle('light'); - page.webview.addEventListener('popGesture', ({ type, result }) => { - if (type === 'start') { - plus.navigator.setStatusBarStyle('dark'); - } - else if (type === 'end' && !result) { - plus.navigator.setStatusBarStyle('light'); - } - }); - } - }, ChooseLocationProtocol); + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ - const openLocation = defineAsyncApi(API_OPEN_LOCATION, (data, { resolve, reject }) => { - showPage({ - url: '__uniappopenlocation', - data, - style: { - titleNView: { - type: 'transparent', - }, - popGesture: 'close', - backButtonAutoControl: 'close', - }, - onClose() { - reject('cancel'); - }, - }); - return resolve(); - }, OpenLocationProtocol, OpenLocationOptions); + for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ - const showModal = defineAsyncApi(API_SHOW_MODAL, ({ title = '', content = '', showCancel = true, cancelText, cancelColor, confirmText, confirmColor, editable = false, placeholderText = '', } = {}, { resolve }) => { - const buttons = showCancel ? [cancelText, confirmText] : [confirmText]; - const tip = editable ? placeholderText : buttons; - content = content || ' '; - plus.nativeUI[editable ? 'prompt' : 'confirm'](content, (e) => { - if (showCancel) { - const isConfirm = e.index === 1; - const res = { - confirm: isConfirm, - cancel: e.index === 0 || e.index === -1, - }; - isConfirm && editable && (res.content = e.value); - resolve(res); - } - else { - const res = { - confirm: e.index === 0, - cancel: false, - }; - editable && (res.content = e.value); - resolve(res); - } - }, title, tip, buttons); - }, ShowModalProtocol, ShowModalOptions); + if (n > max_code) { continue; } /* not a leaf node */ - const showActionSheet = defineAsyncApi(API_SHOW_ACTION_SHEET, ({ itemList = [], itemColor = '#000000', title = '', alertText = '', popover, }, { resolve, reject }) => { - initI18nShowActionSheetMsgsOnce(); - const { t } = useI18n(); - const options = { - title, - cancel: t('uni.showActionSheet.cancel'), - buttons: itemList.map((item) => ({ - title: item, - color: itemColor, - })), - }; - if (title || alertText) { - options.title = alertText || title; - } - plus.nativeUI.actionSheet(extend(options, { - popover, - }), (e) => { - if (e.index > 0) { - resolve({ - tapIndex: e.index - 1, - }); - } - else { - reject('showActionSheet:fail cancel'); - } - }); - }, ShowActionSheetProtocol, ShowActionSheetOptions); + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } + } + + + /* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ + function gen_codes(tree, max_code, bl_count) + // ct_data *tree; /* the tree to decorate */ + // int max_code; /* largest code with non zero frequency */ + // ushf *bl_count; /* number of codes at each bit length */ + { + var next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS$1; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< _showToast(extend({}, args, { - type: 'loading', - icon: 'loading', - }), callbacks), ShowLoadingProtocol, ShowLoadingOptions); - const _showToast = ({ title = '', icon = 'success', image = '', duration = 1500, mask = false, position, - // @ts-ignore ToastType - type = 'toast', - // @ts-ignore PlusNativeUIWaitingStyles - style, }, { resolve, reject }) => { - hide(''); - toastType = type; - if (['top', 'center', 'bottom'].includes(String(position))) { - // 仅可以关闭 richtext 类型,但 iOS 部分情况换行显示有问题 - plus.nativeUI.toast(title, { - verticalAlign: position, - }); - isShowToast = true; - } - else { - if (icon && !~['success', 'loading', 'error', 'none'].indexOf(icon)) { - icon = 'success'; - } - const waitingOptions = { - modal: mask, - back: 'transmit', - padding: '10px', - size: '16px', // 固定字体大小 - }; - if (!image && (!icon || icon === 'none')) { - // 无图 - // waitingOptions.width = '120px' - // waitingOptions.height = '40px' - waitingOptions.loading = { - display: 'none', - }; - } - else { - waitingOptions.width = '140px'; - waitingOptions.height = '112px'; - } - if (image) { - waitingOptions.loading = { - display: 'block', - height: '55px', - icon: image, - interval: duration, - }; - } - else { - if (['success', 'error'].indexOf(icon) !== -1) { - waitingOptions.loading = { - display: 'block', - height: '55px', - icon: icon === 'success' ? '__uniappsuccess.png' : '__uniapperror.png', - interval: duration, - }; - } - } - try { - toast = plus.nativeUI.showWaiting(title, extend(waitingOptions, style)); - } - catch (error) { - reject(`${error}`); - } - } - timeout = setTimeout(() => { - hide(''); - }, duration); - return resolve(); - }; - const showToast = defineAsyncApi(API_SHOW_TOAST, _showToast, ShowToastProtocol, ShowToastOptions); - const hideToast = defineAsyncApi(API_HIDE_TOAST, (_, callbacks) => hide('toast', callbacks)); - const hideLoading = defineAsyncApi(API_HIDE_LOADING, (_, callbacks) => hide('loading', callbacks)); - function hide(type = 'toast', callbacks) { - if (type && type !== toastType) { - // 应该不需要失败回调,在页面后退时,会主动 hideToast 和 hideLoading,如果 reject 会出异常。 - return callbacks && callbacks.resolve(); - } - if (timeout) { - clearTimeout(timeout); - timeout = null; - } - if (isShowToast) { - plus.nativeUI.closeToast(); - } - else if (toast && toast.close) { - toast.close(); - } - toast = null; - isShowToast = false; - toastType = ''; - return callbacks && callbacks.resolve(); + //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", + // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); + } } - const startPullDownRefresh = defineAsyncApi(API_START_PULL_DOWN_REFRESH, (_args, { resolve, reject }) => { - let webview = getPullDownRefreshWebview(); - if (webview) { - webview.endPullToRefresh(); - } - webview = getCurrentWebview(); - if (!webview) { - return reject(); - } - webview.beginPullToRefresh(); - setPullDownRefreshWebview(webview); - resolve(); - }); - const stopPullDownRefresh = defineAsyncApi(API_STOP_PULL_DOWN_REFRESH, (_args, { resolve, reject }) => { - const webview = getPullDownRefreshWebview() || getCurrentWebview(); - if (!webview) { - return reject(); - } - webview.endPullToRefresh(); - setPullDownRefreshWebview(null); - resolve(); - }); + /* =========================================================================== + * Initialize the various 'constant' tables. + */ + function tr_static_init() { + var n; /* iterates over tree elements */ + var bits; /* bit counter */ + var length; /* length value */ + var code; /* code value */ + var dist; /* distance index */ + var bl_count = new Array(MAX_BITS$1 + 1); + /* number of codes at each bit length for an optimal tree */ - const loadFontFace = defineAsyncApi(API_LOAD_FONT_FACE, (options, { resolve, reject }) => { - const pageId = getPageIdByVm(getCurrentPageVm()); - UniServiceJSBridge.invokeViewMethod(API_LOAD_FONT_FACE, options, pageId, (err) => { - if (err) { - reject(err); - } - else { - resolve(); - } - }); - }, LoadFontFaceProtocol); + // do check in _tr_init() + //if (static_init_done) return; - const pageScrollTo = defineAsyncApi(API_PAGE_SCROLL_TO, (options, { resolve }) => { - const pageId = getPageIdByVm(getCurrentPageVm()); - UniServiceJSBridge.invokeViewMethod(API_PAGE_SCROLL_TO, options, pageId, resolve); - }, PageScrollToProtocol, PageScrollToOptions); + /* For some embedded targets, global variables are not initialized: */ + /*#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; + #endif*/ - const setNavigationBarTitle = defineAsyncApi(API_SET_NAVIGATION_BAR_TITLE, ({ __page__, title }, { resolve, reject }) => { - const webview = getWebview(__page__); - if (webview) { - const style = webview.getStyle(); - if (style && style.titleNView) { - webview.setStyle({ - titleNView: { - titleText: title, - }, - }); - } - resolve(); - } - else { - reject(); - } - }, SetNavigationBarTitleProtocol); - const showNavigationBarLoading = defineAsyncApi(API_SHOW_NAVIGATION_BAR_LOADING, (_, { resolve }) => { - plus.nativeUI.showWaiting('', { - modal: false, - }); - resolve(); - }); - const hideNavigationBarLoading = defineAsyncApi(API_HIDE_NAVIGATION_BAR_LOADING, (_, { resolve }) => { - plus.nativeUI.closeWaiting(); - resolve(); - }); - function setPageStatusBarStyle(statusBarStyle) { - const pages = getCurrentPages(); - if (!pages.length) { - return; - } - // 框架内部页面跳转会从这里获取style配置 - pages[pages.length - 1].$page.statusBarStyle = statusBarStyle; - } - const setNavigationBarColor = defineAsyncApi(API_SET_NAVIGATION_BAR_COLOR, ({ __page__, frontColor, backgroundColor }, { resolve, reject }) => { - const webview = getWebview(__page__); - if (webview) { - const styles = {}; - if (frontColor) { - styles.titleColor = frontColor; - } - if (backgroundColor) { - styles.backgroundColor = backgroundColor; - } - const statusBarStyle = frontColor === '#000000' ? 'dark' : 'light'; - plus.navigator.setStatusBarStyle(statusBarStyle); - // 用户调用api时同时改变当前页配置,这样在系统调用设置时,可以避免覆盖用户设置 - setPageStatusBarStyle(statusBarStyle); - const style = webview.getStyle(); - if (style && style.titleNView) { - if (style.titleNView.autoBackButton) { - styles.backButton = styles.backButton || {}; - styles.backButton.color = frontColor; - } - webview.setStyle({ - titleNView: styles, - }); - } - resolve(); - } - else { - reject(); - } - }, SetNavigationBarColorProtocol, SetNavigationBarColorOptions); + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES$1 - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES$1; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS$1; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES$1 + 1, bl_count); - const setTabBarBadge = defineAsyncApi(API_SET_TAB_BAR_BADGE, ({ index, text }, { resolve, reject }) => { - tabBar$1.setTabBarBadge('text', index, text); - resolve(); - }, SetTabBarBadgeProtocol, SetTabBarBadgeOptions); - const setTabBarItem = defineAsyncApi(API_SET_TAB_BAR_ITEM, ({ index, text, iconPath, selectedIconPath, pagePath, visible }, { resolve, reject }) => { - if (!isTabBarPage$1()) { - return reject('not TabBar page'); - } - tabBar$1.setTabBarItem(index, text, iconPath, selectedIconPath, visible); - const route = pagePath && __uniRoutes.find(({ path }) => path === pagePath); - if (route) { - const meta = route.meta; - meta.isTabBar = true; - meta.tabBarIndex = index; - meta.isQuit = true; - const tabBar = __uniConfig.tabBar; - if (tabBar && tabBar.list && tabBar.list[index] && pagePath) { - tabBar.list[index].pagePath = pagePath.startsWith('/') - ? pagePath.substring(1) - : pagePath; - } - } - resolve(); - }, SetTabBarItemProtocol, SetTabBarItemOptions); - const setTabBarStyle = defineAsyncApi(API_SET_TAB_BAR_STYLE, (style = {}, { resolve, reject }) => { - if (!isTabBarPage$1()) { - return reject('not TabBar page'); - } - const borderStyles = { - black: 'rgba(0,0,0,0.4)', - white: 'rgba(255,255,255,0.4)', - }; - const borderStyle = style.borderStyle; - if (borderStyle && borderStyle in borderStyles) { - style.borderStyle = borderStyles[borderStyle]; - } - tabBar$1.setTabBarStyle(style); - resolve(); - }, SetTabBarStyleProtocol, SetTabBarStyleOptions); - const hideTabBar = defineAsyncApi(API_HIDE_TAB_BAR, (args, { resolve, reject }) => { - const animation = args && args.animation; - if (!isTabBarPage$1()) { - return reject('not TabBar page'); - } - tabBar$1.hideTabBar(Boolean(animation)); - resolve(); - }, HideTabBarProtocol); - const showTabBar = defineAsyncApi(API_SHOW_TAB_BAR, (args, { resolve, reject }) => { - const animation = args && args.animation; - if (!isTabBarPage$1()) { - return reject('not TabBar page'); - } - tabBar$1.showTabBar(Boolean(animation)); - resolve(); - }, ShowTabBarProtocol); - const showTabBarRedDot = defineAsyncApi(API_SHOW_TAB_BAR_RED_DOT, ({ index }, { resolve, reject }) => { - tabBar$1.setTabBarBadge('redDot', index); - resolve(); - }, ShowTabBarRedDotProtocol, ShowTabBarRedDotOptions); - const setTabBarBadgeNone = (index) => tabBar$1.setTabBarBadge('none', index); - const removeTabBarBadge = defineAsyncApi(API_REMOVE_TAB_BAR_BADGE, ({ index }, { resolve, reject }) => { - setTabBarBadgeNone(index); - resolve(); - }, RemoveTabBarBadgeProtocol, RemoveTabBarBadgeOptions); - const hideTabBarRedDot = defineAsyncApi(API_HIDE_TAB_BAR_RED_DOT, ({ index }, { resolve, reject }) => { - setTabBarBadgeNone(index); - resolve(); - }, HideTabBarRedDotProtocol, HideTabBarRedDotOptions); + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES$1; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } - const EVENT_TYPE_NAME = 'UniAppSubNVue'; - class SubNvue { - constructor(id, isSub) { - this.callbacks = []; - const webview = (this.webview = plus.webview.getWebviewById(id)); - this.isSub = isSub || false; - if (webview.__uniapp_mask_id) { - const maskWebview = (this.maskWebview = - webview.__uniapp_mask_id === '0' - ? { - setStyle({ mask }) { - requireNativePlugin('uni-tabview').setMask({ - color: mask, - }); - }, - } - : plus.webview.getWebviewById(webview.__uniapp_mask_id)); - const closeMask = function () { - maskWebview.setStyle({ - mask: 'none', - }); - }; - webview.addEventListener('hide', closeMask); - webview.addEventListener('close', closeMask); - } - } - show(...args) { - if (this.maskWebview) { - const maskColor = this.webview.__uniapp_mask; - this.maskWebview.setStyle({ - mask: maskColor, - }); - } - this.webview.show(...args); - } - hide(...args) { - this.webview.hide(...args); - } - setStyle(style) { - this.webview.setStyle(style); - } - initMessage() { - if (this.messageReady) { - return; - } - this.messageReady = true; - const listener = (event) => { - if (event.data && event.data.type === EVENT_TYPE_NAME) { - const target = event.data.target; - if (target.id === this.webview.id && target.isSub === this.isSub) { - this.callbacks.forEach((callback) => { - callback({ - origin: this.webview.__uniapp_host, - data: event.data.data, - }); - }); - } - } - }; - const globalEvent = requireNativePlugin('globalEvent'); - globalEvent.addEventListener('plusMessage', listener); - this.webview.addEventListener('close', () => { - // TODO 暂时仅清空回调 - this.callbacks.length = 0; - // globalEvent.removeEventListener('plusMessage', listener) - }); - } - postMessage(data) { - const webviewExt = plus.webview; - webviewExt.postMessageToUniNView({ - type: EVENT_TYPE_NAME, - data, - target: { - id: this.webview.id, - isSub: !this.isSub, - }, - }, APP_SERVICE_ID); - } - onMessage(callback) { - this.initMessage(); - this.callbacks.push(callback); - } - } - const getSubNVueById = function (id, isSub) { - // TODO 暂时通过 isSub 区分来自 subNVue 页面 - return new SubNvue(id, isSub); - }; + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS); - const providers = { - oauth(callback) { - plus.oauth.getServices((services) => { - services = services; - const provider = []; - services.forEach(({ id }) => { - provider.push(id); - }); - callback(null, provider); - }, (err) => { - err = err; - callback(err); - }); - }, - share(callback) { - plus.share.getServices((services) => { - services = services; - const provider = []; - services.forEach(({ id }) => { - provider.push(id); - }); - callback(null, provider); - }, (err) => { - callback(err); - }); - }, - payment(callback) { - plus.payment.getChannels((services) => { - const provider = []; - services.forEach(({ id }) => { - provider.push(id); - }); - callback(null, provider); - }, (err) => { - callback(err); - }); - }, - push(callback) { - if (typeof weex !== 'undefined' || typeof plus !== 'undefined') { - callback(null, [plus.push.getClientInfo().id]); - } - else { - callback(null, []); - } - }, - }; - const getProvider = defineAsyncApi(API_GET_PROVIDER, ({ service }, { resolve, reject }) => { - if (providers[service]) { - providers[service]((err, provider) => { - if (err) { - reject(err.message); - } - else { - resolve({ - service, - provider: provider, - }); - } - }); - } - else { - reject('service not found'); - } - }, GetProviderProtocol); + //static_init_done = true; + } + + + /* =========================================================================== + * Initialize a new block. + */ + function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } - let univerifyManager; - function getService(provider) { - return new Promise((resolve, reject) => { - plus.oauth.getServices((services) => { - const service = services.find(({ id }) => id === provider); - service ? resolve(service) : reject(new Error('provider not find')); - }, reject); - }); - } - const login = defineAsyncApi(API_LOGIN, (params, { resolve, reject }) => { - const provider = params.provider || 'weixin'; - const errorCallback = warpPlusErrorCallback(reject); - const authOptions = provider === 'apple' - ? { scope: 'email' } - : params.univerifyStyle - ? { - univerifyStyle: univerifyButtonsClickHandling(params.univerifyStyle, errorCallback), - } - : {}; - getService(provider) - .then((service) => { - function login() { - if (params.onlyAuthorize && provider === 'weixin') { - service.authorize(({ code }) => { - resolve({ - code, - authResult: '', - }); - }, errorCallback); - return; - } - service.login((res) => { - const authResult = res.target.authResult; - resolve({ - code: authResult.code, - authResult: authResult, - }); - }, errorCallback, authOptions); - } - // 先注销再登录 - // apple登录logout之后无法重新触发获取email,fullname;一键登录无logout - if (provider === 'apple' || provider === 'univerify') { - login(); - } - else { - service.logout(login, login); - } - }) - .catch(errorCallback); - }, LoginProtocol); - const baseGetUserInfo = (params, { resolve, reject }) => { - const provider = params.provider || 'weixin'; - const errorCallback = warpPlusErrorCallback(reject); - getService(provider) - .then((loginService) => { - loginService.getUserInfo((res) => { - let userInfo = { nickName: '' }; - if (provider === 'weixin') { - const wechatUserInfo = loginService.userInfo; - if (wechatUserInfo) - userInfo = { - openId: wechatUserInfo.openid, - nickName: wechatUserInfo.nickname, - gender: wechatUserInfo.sex, - city: wechatUserInfo.city, - province: wechatUserInfo.province, - country: wechatUserInfo.country, - avatarUrl: wechatUserInfo.headimgurl, - unionId: wechatUserInfo.unionid, - }; - } - else if (provider === 'apple') { - const appleInfo = loginService.appleInfo; - if (appleInfo) - userInfo = { - openId: appleInfo.user, - fullName: appleInfo.fullName, - email: appleInfo.email, - authorizationCode: appleInfo.authorizationCode, - identityToken: appleInfo.identityToken, - realUserStatus: appleInfo.realUserStatus, - }; - } - else { - userInfo = loginService.userInfo; - if (userInfo) { - userInfo.openId = - userInfo.openId || - userInfo.openid || - loginService.authResult.openid; - userInfo.nickName = userInfo.nickName || userInfo.nickname; - userInfo.avatarUrl = userInfo.avatarUrl || userInfo.headimgurl; - } - } - let result = {}; - // @ts-ignore - if (params.data && params.data.api_name === 'webapi_getuserinfo') { - result.data = { - data: JSON.stringify(userInfo), - rawData: '', - signature: '', - encryptedData: '', - iv: '', - }; - } - else { - result.userInfo = userInfo; - } - resolve(result); - }, errorCallback); - }) - .catch(() => { - reject('请先调用 uni.login'); - }); - }; - const getUserInfo = defineAsyncApi(API_GET_USER_INFO, baseGetUserInfo, GetUserInfoProtocol); - /** - * 获取用户信息-兼容 - */ - const getUserProfile = defineAsyncApi(API_GET_USER_PROFILE, baseGetUserInfo, GgetUserProfileProtocol); - const preLogin = defineAsyncApi(API_PRE_LOGIN, ({ provider }, { resolve, reject }) => { - const successCallback = warpPlusSuccessCallback(resolve); - const errorCallback = warpPlusErrorCallback(reject); - getService(provider) - .then((service) => service.preLogin(successCallback, errorCallback)) - .catch(errorCallback); - }, PreLoginProtocol, PreLoginOptions); - const _closeAuthView = () => getService('univerify').then((service) => service.closeAuthView()); - const closeAuthView = defineSyncApi(API_CLOSE_AUTH_VIEW, _closeAuthView); - const getCheckBoxState = defineAsyncApi(API_GET_CHECK_BOX_STATE, (_, { resolve, reject }) => { - const successCallback = warpPlusSuccessCallback(resolve); - const errorCallback = warpPlusErrorCallback(reject); - try { - getService('univerify').then((service) => { - // @ts-expect-error - const state = service.getCheckBoxState(); - successCallback({ state }); - }); - } - catch (error) { - errorCallback(error); - } - }); - /** - * 一键登录自定义登陆按钮点击处理 - */ - function univerifyButtonsClickHandling(univerifyStyle, errorCallback) { - if (isPlainObject(univerifyStyle) && - isPlainObject(univerifyStyle.buttons) && - toTypeString(univerifyStyle.buttons.list) === '[object Array]') { - univerifyStyle.buttons.list.forEach((button, index) => { - univerifyStyle.buttons.list[index].onclick = function () { - const res = { - code: '30008', - message: '用户点击了自定义按钮', - index, - provider: button.provider, - }; - isPlainObject(univerifyManager) - ? univerifyManager._triggerUniverifyButtonsClick(res) - : _closeAuthView().then(() => { - errorCallback(res); - }); - }; - }); - } - return univerifyStyle; - } - class UniverifyManager { - constructor() { - this.provider = 'univerify'; - this.eventName = 'api.univerifyButtonsClick'; - } - close() { - closeAuthView(); - } - login(options) { - login(this._getOptions(options)); - } - getCheckBoxState(options) { - getCheckBoxState(options); - } - preLogin(options) { - preLogin(this._getOptions(options)); - } - onButtonsClick(callback) { - UniServiceJSBridge.on(this.eventName, callback); - } - offButtonsClick(callback) { - UniServiceJSBridge.off(this.eventName, callback); - } - _triggerUniverifyButtonsClick(res) { - UniServiceJSBridge.emit(this.eventName, res); - } - _getOptions(options = {}) { - return extend({}, options, { provider: this.provider }); - } - } - const getUniverifyManager = defineSyncApi(API_GET_UNIVERIFY_MANAGER, () => { - return univerifyManager || (univerifyManager = new UniverifyManager()); - }); + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; + } + + + /* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ + function bi_windup(s) + { + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; + } + + /* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ + function copy_block(s, buf, len, header) + //DeflateState *s; + //charf *buf; /* the input data */ + //unsigned len; /* its length */ + //int header; /* true if block header must be written */ + { + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } + // while (len--) { + // put_byte(s, *buf++); + // } + require$$0.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; + } + + /* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ + function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); + } + + /* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ + function pqdownheap(s, tree, k) + // deflate_state *s; + // ct_data *tree; /* the tree to restore */ + // int k; /* node to move down */ + { + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } - const registerRuntime = defineSyncApi('registerRuntime', (runtime) => { - // @ts-expect-error - extend(jsRuntime, runtime); - }); + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; - // 0:图文,1:纯文字,2:纯图片,3:音乐,4:视频,5:小程序 - const TYPES = { - 0: { - name: 'web', - title: '图文', - }, - 1: { - name: 'text', - title: '纯文字', - }, - 2: { - name: 'image', - title: '纯图片', - }, - 3: { - name: 'music', - title: '音乐', - }, - 4: { - name: 'video', - title: '视频', - }, - 5: { - name: 'miniProgram', - title: '小程序', - }, - }; - const parseParams = (args) => { - args.type = args.type || 0; - let { provider, type, title, summary: content, href, imageUrl, mediaUrl: media, scene, miniProgram, } = args; - if (typeof imageUrl === 'string' && imageUrl) { - imageUrl = getRealPath(imageUrl); - } - const shareType = TYPES[type]; - if (shareType) { - const sendMsg = { - provider, - type: shareType.name, - title, - content, - href, - pictures: [imageUrl], - thumbs: imageUrl ? [imageUrl] : undefined, - media, - miniProgram, - extra: { - scene, - }, - }; - if (provider === 'weixin' && (type === 1 || type === 2)) { - delete sendMsg.thumbs; - } - return sendMsg; - } - return '分享参数 type 不正确'; - }; - const sendShareMsg = function (service, params, resolve, reject, method = 'share') { - const errorCallback = warpPlusErrorCallback(reject); - service.send(params, () => { - resolve(); - }, errorCallback); - }; - const share = defineAsyncApi(API_SHREA, (params, { resolve, reject }) => { - const res = parseParams(params); - const errorCallback = warpPlusErrorCallback(reject); - if (typeof res === 'string') { - return reject(res); - } - else { - params = res; - } - plus.share.getServices((services) => { - const service = services.find(({ id }) => id === params.provider); - if (!service) { - reject('service not found'); - } - else { - if (service.authenticated) { - sendShareMsg(service, params, resolve, reject); - } - else { - service.authorize(() => sendShareMsg(service, params, resolve, reject), errorCallback); - } - } - }, errorCallback); - }, ShareProtocols, SahreOptions); - const shareWithSystem = defineAsyncApi(API_SHARE_WITH_SYSTEM, ({ type, imageUrl, summary, href }, { resolve, reject }) => { - const errorCallback = warpPlusErrorCallback(reject); - if (typeof imageUrl === 'string' && imageUrl) { - imageUrl = getRealPath(imageUrl); - } - plus.share.sendWithSystem({ - type, - pictures: imageUrl ? [imageUrl] : undefined, - content: summary, - href, - }, () => resolve(), errorCallback); - }, ShareWithSystemProtocols, ShareWithSystemOptions); + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; + } + + + // inlined manually + // var SMALLEST = 1; + + /* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ + function compress_block(s, ltree, dtree) + // deflate_state *s; + // const ct_data *ltree; /* literal tree */ + // const ct_data *dtree; /* distance tree */ + { + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); + } + + + /* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ + function build_tree(s, desc) + // deflate_state *s; + // tree_desc *desc; /* the tree descriptor */ + { + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE$1; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); - const requestPayment = defineAsyncApi(API_REQUEST_PAYMENT, (params, { resolve, reject }) => { - const provider = params.provider; - const errorCallback = warpPlusErrorCallback(reject); - plus.payment.getChannels((services) => { - const service = services.find(({ id }) => id === provider); - if (!service) { - reject('service not found'); - } - else { - plus.payment.request(service, params.orderInfo, (res) => { - resolve(res); - }, errorCallback); - } - }, errorCallback); - }, RequestPaymentProtocol); + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; - function injectLifecycleHook(name, hook, publicThis, instance) { - if (isFunction(hook)) { - vue.injectHook(name, hook.bind(publicThis), instance); - } - } - function initHooks(options, instance, publicThis) { - const mpType = options.mpType || publicThis.$mpType; - // 为了组件也可以监听部分生命周期,故不再判断mpType,统一添加on开头的生命周期 - Object.keys(options).forEach((name) => { - if (name.indexOf('on') === 0) { - const hooks = options[name]; - if (isArray$1(hooks)) { - hooks.forEach((hook) => injectLifecycleHook(name, hook, publicThis, instance)); - } - else { - injectLifecycleHook(name, hooks, publicThis, instance); - } - } - }); - if (mpType === 'page') { - instance.__isVisible = true; - try { - invokeHook(publicThis, ON_LOAD, instance.attrs.__pageQuery); - delete instance.attrs.__pageQuery; - } - catch (e) { - console.error(e.message + LINEFEED + e.stack); - } - vue.nextTick(() => { - // 延迟onShow,保证组件的onShow也可以监听到 - invokeHook(publicThis, ON_SHOW); - }); - } - } + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); - function initRenderjs(options, instance) { - initModules(instance, options.$renderjs, options['$' + RENDERJS_MODULES]); - } - function initModules(instance, modules, moduleIds = {}) { - if (!isArray$1(modules)) { - return; - } - const ownerId = instance.uid; - // 在vue的定制内核中,通过$wxsModules来判断事件函数源码中是否包含该模块调用 - // !$wxsModules.find(module => invokerSourceCode.indexOf('.' + module + '.') > -1) - const $wxsModules = (instance.$wxsModules || - (instance.$wxsModules = [])); - const ctx = instance.ctx; - modules.forEach((module) => { - if (moduleIds[module]) { - ctx[module] = proxyModule(ownerId, moduleIds[module], module); - $wxsModules.push(module); - } - else { - if ((process.env.NODE_ENV !== 'production')) { - console.error(formatLog('initModules', modules, moduleIds)); - } - } - }); - } - function proxyModule(ownerId, moduleId, module) { - const target = {}; - return new Proxy(target, { - get(_, p) { - return (target[p] || - (target[p] = createModuleFunction(ownerId, moduleId, module, p))); - }, - }); - } - function createModuleFunction(ownerId, moduleId, module, name) { - const target = () => { }; - const toJSON = () => WXS_PROTOCOL + JSON.stringify([ownerId, moduleId, module + '.' + name]); - return new Proxy(target, { - get(_, p) { - if (p === 'toJSON') { - return toJSON; - } - return (target[p] || - (target[p] = createModuleFunction(ownerId, moduleId, module + '.' + name, p))); - }, - apply(_target, _thisArg, args) { - return (WXS_PROTOCOL + - JSON.stringify([ownerId, moduleId, module + '.' + name, [...args]])); - }, - }); + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); } - function initWxs(options, instance) { - initModules(instance, options.$wxs, options['$' + WXS_MODULES]); - } - function applyOptions(options, instance, publicThis) { - { - initWxs(options, instance); - initRenderjs(options, instance); - } - initHooks(options, instance, publicThis); - } + /* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ + function scan_tree(s, tree, max_code) + // deflate_state *s; + // ct_data *tree; /* the tree to be scanned */ + // int max_code; /* and its largest code of non zero frequency */ + { + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ - function set(target, key, val) { - return (target[key] = val); - } + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - function errorHandler(err, instance, info) { - if (!instance) { - throw err; - } - const app = getApp(); - if (!app || !app.$vm) { - throw err; - } - { - invokeHook(app.$vm, ON_ERROR, err); - } - } - function mergeAsArray(to, from) { - return to ? [...new Set([].concat(to, from))] : from; - } - function initOptionMergeStrategies(optionMergeStrategies) { - UniLifecycleHooks.forEach((name) => { - optionMergeStrategies[name] = mergeAsArray; - }); - } + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ - let realAtob; - const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/; - if (typeof atob !== 'function') { - realAtob = function (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() { - const token = uni.getStorageSync('uni_id_token') || ''; - const tokenArr = token.split('.'); - if (!token || tokenArr.length !== 3) { - return { - uid: null, - role: [], - permission: [], - tokenExpired: 0, - }; - } - let 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(globalProperties) { - globalProperties.uniIDHasRole = function (roleId) { - const { role } = getCurrentUserInfo(); - return role.indexOf(roleId) > -1; - }; - globalProperties.uniIDHasPermission = function (permissionId) { - const { permission } = getCurrentUserInfo(); - return this.uniIDHasRole('admin') || permission.indexOf(permissionId) > -1; - }; - globalProperties.uniIDTokenValid = function () { - const { tokenExpired } = getCurrentUserInfo(); - return tokenExpired > Date.now(); - }; - } + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } - function initApp(app) { - const appConfig = app._context.config; - if (isFunction(app._component.onError)) { - appConfig.errorHandler = errorHandler; - } - initOptionMergeStrategies(appConfig.optionMergeStrategies); - const globalProperties = appConfig.globalProperties; - { - uniIdMixin(globalProperties); - } - { - globalProperties.$set = set; - globalProperties.$applyOptions = applyOptions; - } - } + count = 0; + prevlen = curlen; - function initTabBar() { - const { tabBar } = __uniConfig; - const len = tabBar && tabBar.list && tabBar.list.length; - if (!len) { - return; - } - const { entryPagePath } = __uniConfig; - tabBar.selectedIndex = 0; - const selected = tabBar.list.findIndex((page) => page.pagePath === entryPagePath); - tabBar$1.init(tabBar, (item, index) => { - uni.switchTab({ - url: addLeadingSlash(item.pagePath), - openType: 'switchTab', - from: 'tabBar', - success() { - invokeHook(ON_TAB_ITEM_TAP, { - index, - text: item.text, - pagePath: item.pagePath, - }); - }, - }); - }); - if (selected !== -1) { - // 取当前 tab 索引值 - tabBar.selectedIndex = selected; - selected !== 0 && tabBar$1.switchTab(entryPagePath); - } - } + if (nextlen === 0) { + max_count = 138; + min_count = 3; - function initGlobalEvent() { - const plusGlobalEvent = plus.globalEvent; - const weexGlobalEvent = weex.requireModule('globalEvent'); - const emit = UniServiceJSBridge.emit; - if (weex.config.preload) { - plus.key.addEventListener(EVENT_BACKBUTTON, backbuttonListener); - } - else { - plusGlobalEvent.addEventListener('splashclosed', () => { - plus.key.addEventListener(EVENT_BACKBUTTON, backbuttonListener); - }); - } - plusGlobalEvent.addEventListener('pause', () => { - emit(ON_APP_ENTER_BACKGROUND); - }); - plusGlobalEvent.addEventListener('resume', () => { - const info = parseRedirectInfo(); - if (info && info.userAction) { - initEnterOptions(info); - initEnterReLaunch(info); - } - emit(ON_APP_ENTER_FOREGROUND, getEnterOptions()); - }); - weexGlobalEvent.addEventListener('uistylechange', function (event) { - const args = { - theme: event.uistyle, - }; - emit(ON_THEME_CHANGE, args); - }); - let keyboardHeightChange = 0; - plusGlobalEvent.addEventListener('KeyboardHeightChange', function (event) { - // 安卓设备首次获取高度为 0 - if (keyboardHeightChange !== event.height) { - keyboardHeightChange = event.height; - emit(ON_KEYBOARD_HEIGHT_CHANGE, { - height: keyboardHeightChange, - }); - } - }); - plusGlobalEvent.addEventListener('plusMessage', subscribePlusMessage); - // nvue webview post message - plusGlobalEvent.addEventListener('WebviewPostMessage', subscribePlusMessage); - } - function subscribePlusMessage({ data, }) { - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('plusMessage', data)); - } - if (data && data.type) { - UniServiceJSBridge.subscribeHandler('plusMessage.' + data.type, data.args); - } - } - function onPlusMessage(type, callback, once = false) { - UniServiceJSBridge.subscribe('plusMessage.' + type, callback, once); - } + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; - function initAppLaunch(appVm) { - const { entryPagePath, entryPageQuery, referrerInfo } = __uniConfig; - const args = extend({ - // 为了让 uni-stat 在 uni.onLaunch 中可以 mixin - app: { mixin: appVm.$.appContext.app.mixin }, - }, initLaunchOptions({ - path: entryPagePath, - query: entryPageQuery, - referrerInfo: referrerInfo, - })); - injectAppLaunchHooks(appVm.$); - invokeHook(appVm, ON_LAUNCH, args); - invokeHook(appVm, ON_SHOW, args); - // https://tower.im/teams/226535/todos/16905/ - const getAppState = weex.requireModule('plus').getAppState; - const appState = getAppState && Number(getAppState()); - if (appState === 2) { - invokeHook(appVm, ON_HIDE, args); - } + } else { + max_count = 7; + min_count = 4; + } + } } - // 统一处理路径 - function getPath(path) { - path = path.replace(/\/$/, ''); - return path.indexOf('_') === 0 - ? plus.io.convertLocalFileSystemURL(path) - : path; - } - function clearTempFile() { - const basePath = getPath(TEMP_PATH_BASE); - const tempPath = getPath(TEMP_PATH); - // 获取父目录 - const dirParts = tempPath.split('/'); - dirParts.pop(); - const dirPath = dirParts.join('/'); - plus.io.resolveLocalFileSystemURL(plus.io.convertAbsoluteFileSystem(dirPath), (entry) => { - const reader = entry.createReader(); - reader.readEntries(function (entry) { - // plus.d.ts 类型不对 - const entries = entry; - if (entries && entries.length) { - entries.forEach(function (entry) { - if (entry.isDirectory && - entry.fullPath.indexOf(basePath) === 0 && - entry.fullPath.indexOf(tempPath) !== 0) { - entry.removeRecursively(); - } - }); - } - }); - }); - } - function onNodeEvent(nodeId, evt, pageNode) { - pageNode.fireEvent(nodeId, evt); - } + /* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ + function send_tree(s, tree, max_code) + // deflate_state *s; + // ct_data *tree; /* the tree to be scanned */ + // int max_code; /* and its largest code of non zero frequency */ + { + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ - function onVdSync(actions, pageId) { - // 从所有pages中获取 - const page = getPageById(parseInt(pageId)); - if (!page) { - if ((process.env.NODE_ENV !== 'production')) { - console.error(formatLog('onVdSync', 'page', pageId, 'not found')); - } - return; - } - const pageNode = page.__page_container__; - actions.forEach((action) => { - switch (action[0]) { - case ACTION_TYPE_EVENT: - onNodeEvent(action[1], action[2], pageNode); - break; - } - }); - } + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - const _adDataCache = {}; - function getAdData(data, onsuccess, onerror) { - const { adpid, width } = data; - const key = adpid + '-' + width; - const adDataList = _adDataCache[key]; - if (adDataList && adDataList.length > 0) { - onsuccess(adDataList.splice(0, 1)[0]); - return; - } - plus.ad.getAds(data, (res) => { - const list = res.ads; - onsuccess(list.splice(0, 1)[0]); - _adDataCache[key] = adDataList ? adDataList.concat(list) : list; - }, (err) => { - onerror({ - errCode: err.code, - errMsg: err.message, - }); - }); - } - function subscribeAd() { - registerServiceMethod('getAdData', (args, resolve) => { - getAdData(args, (res) => { - resolve({ - code: 0, - data: res, - }); - }, (err) => { - resolve({ - code: 1, - message: err, - }); - }); - }); - } + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } - const API_ROUTE = [ - 'switchTab', - 'reLaunch', - 'redirectTo', - 'navigateTo', - 'navigateBack', - ]; - function subscribeNavigator() { - API_ROUTE.forEach((name) => { - registerServiceMethod(name, (args) => { - uni[name](extend(args, { - fail(res) { - console.error(res.errMsg); - }, - })); - }); - }); - } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; - const $navigateTo = (args, { resolve, reject }) => { - const { url, events, animationType, animationDuration } = args; - const { path, query } = parseUrl(url); - const [aniType, aniDuration] = initAnimation(path, animationType, animationDuration); - navigate(path, () => { - _navigateTo({ - url, - path, - query, - events, - aniType, - aniDuration, - }) - .then(resolve) - .catch(reject); - }, args.openType === 'appLaunch'); - }; - const navigateTo = defineAsyncApi(API_NAVIGATE_TO, $navigateTo, NavigateToProtocol, NavigateToOptions); - function _navigateTo({ url, path, query, events, aniType, aniDuration, }) { - // 当前页面触发 onHide - invokeHook(ON_HIDE); - const eventChannel = new EventChannel(getWebviewId() + 1, events); - return new Promise((resolve) => { - showWebview(registerPage({ url, path, query, openType: 'navigateTo', eventChannel }), aniType, aniDuration, () => { - resolve({ eventChannel }); - }); - setStatusBarStyle(); - }); - } - function initAnimation(path, animationType, animationDuration) { - const { globalStyle } = __uniConfig; - const meta = getRouteMeta(path); - return [ - animationType || - meta.animationType || - globalStyle.animationType || - ANI_SHOW, - animationDuration || - meta.animationDuration || - globalStyle.animationDuration || - ANI_DURATION, - ]; - } + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; - const $switchTab = (args, { resolve, reject }) => { - const { url } = args; - const { path, query } = parseUrl(url); - navigate(path, () => { - _switchTab({ - url, - path, - query, - }) - .then(resolve) - .catch(reject); - }, args.openType === 'appLaunch'); - }; - const switchTab = defineAsyncApi(API_SWITCH_TAB, $switchTab, SwitchTabProtocol, SwitchTabOptions); - function _switchTab({ url, path, query, }) { - tabBar$1.switchTab(path.slice(1)); - const pages = getCurrentPages(); - const len = pages.length; - let callOnHide = false; - let callOnShow = false; - let currentPage; - if (len >= 1) { - // 前一个页面是非 tabBar 页面 - currentPage = pages[len - 1]; - if (currentPage && !currentPage.$.__isTabBar) { - // 前一个页面为非 tabBar 页面时,目标tabBar需要强制触发onShow - // 该情况下目标页tabBarPage的visible是不对的 - // 除非每次路由跳转都处理一遍tabBarPage的visible,目前仅switchTab会处理 - // 简单起见,暂时直接判断该情况,执行onShow - callOnShow = true; - pages.reverse().forEach((page) => { - if (!page.$.__isTabBar && page !== currentPage) { - closePage(page, 'none'); - } - }); - removePage(currentPage); - // 延迟执行避免iOS应用退出 - setTimeout(() => { - if (currentPage.$page.openType === 'redirectTo') { - closeWebview(currentPage.$getAppWebview(), ANI_CLOSE, ANI_DURATION); - } - else { - closeWebview(currentPage.$getAppWebview(), 'auto'); - } - }, 100); - } - else { - callOnHide = true; - } - } - let tabBarPage; - // 查找当前 tabBarPage,且设置 visible - getAllPages().forEach((page) => { - if (addLeadingSlash(page.route) === path) { - if (!page.$.__isActive) { - // 之前未显示 - callOnShow = true; - } - page.$.__isActive = true; - tabBarPage = page; - } - else { - if (page.$.__isTabBar) { - page.$.__isActive = false; - } - } - }); - // 相同tabBar页面 - if (currentPage === tabBarPage) { - callOnHide = false; - } - if (currentPage && callOnHide) { - invokeHook(currentPage, ON_HIDE); - } - return new Promise((resolve) => { - if (tabBarPage) { - const webview = tabBarPage.$getAppWebview(); - webview.show('none'); - // 等visible状态都切换完之后,再触发onShow,否则开发者在onShow里边 getCurrentPages 会不准确 - if (callOnShow && !webview.__preload__) { - invokeHook(tabBarPage, ON_SHOW); - } - setStatusBarStyle(); - resolve(undefined); - } - else { - showWebview(registerPage({ - url, - path, - query, - openType: 'switchTab', - }), 'none', 0, () => { - setStatusBarStyle(); - resolve(undefined); - }, 70); - } - }); + } else { + max_count = 7; + min_count = 4; + } + } } - let isLaunchWebviewReady = false; // 目前首页双向确定 ready,可能会导致触发两次 onWebviewReady(主要是 Android) - function subscribeWebviewReady(_data, pageId) { - const isLaunchWebview = pageId === '1'; - if (isLaunchWebview && isLaunchWebviewReady) { - if ((process.env.NODE_ENV !== 'production')) { - console.log('[uni-app] onLaunchWebviewReady.prevent'); - } - return; - } - if (isLaunchWebview) { - // 首页 - isLaunchWebviewReady = true; - setPreloadWebview(plus.webview.getLaunchWebview()); - } - else if (!preloadWebview$1) { - // preloadWebview 不存在,重新加载一下 - setPreloadWebview(plus.webview.getWebviewById(pageId)); - } - if (preloadWebview$1.id !== pageId) { - return console.error(`webviewReady[${preloadWebview$1.id}][${pageId}] not match`); - } - preloadWebview$1.loaded = true; // 标记已 ready - UniServiceJSBridge.emit(ON_WEBVIEW_READY + '.' + pageId); - isLaunchWebview && onLaunchWebviewReady(); - } - function onLaunchWebviewReady() { - const { autoclose, alwaysShowBeforeRender } = __uniConfig.splashscreen; - if (autoclose && !alwaysShowBeforeRender) { - plus.navigator.closeSplashscreen(); - } - const entryPagePath = addLeadingSlash(__uniConfig.entryPagePath); - const routeOptions = getRouteOptions(entryPagePath); - if (!routeOptions.meta.isNVue) { - // 非 nvue 首页,需要主动跳转 - const args = { - url: entryPagePath + (__uniConfig.entryPageQuery || ''), - openType: 'appLaunch', - }; - const handler = { resolve() { }, reject() { } }; - if (routeOptions.meta.isTabBar) { - return $switchTab(args, handler); - } - return $navigateTo(args, handler); - } + + /* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ + function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; } - function onWebviewInserted(_, pageId) { - const page = getPageById(parseInt(pageId)); - page && (page.__uniapp_webview = true); - } - function onWebviewRemoved(_, pageId) { - const page = getPageById(parseInt(pageId)); - page && delete page.__uniapp_webview; + + /* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ + function send_all_trees(s, lcodes, dcodes, blcodes) + // deflate_state *s; + // int lcodes, dcodes, blcodes; /* number of codes for each tree */ + { + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } - const onWebInvokeAppService = ({ name, arg }, pageIds) => { - if (name === 'postMessage') { - onMessage(pageIds[0], arg); - } - else { - uni[name](extend(arg, { - fail(res) { - console.error(res.errMsg); - }, - })); - } - }; - function onMessage(pageId, arg) { - const uniNode = findNodeByTagName('web-view', parseInt(pageId)); - uniNode && - uniNode.dispatchEvent(createUniEvent({ - type: 'onMessage', - target: Object.create(null), - currentTarget: Object.create(null), - detail: { - data: [arg], - }, - })); + + /* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ + function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS$1; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; } - function onWxsInvokeCallMethod({ nodeId, ownerId, method, args, }, pageId) { - const node = findNodeById(nodeId, parseInt(pageId)); - if (!node) { - if ((process.env.NODE_ENV !== 'production')) { - console.error(formatLog('Wxs', 'CallMethod', nodeId, 'not found')); - } - return; - } - const vm = resolveOwnerVm(ownerId, node.__vueParentComponent); - if (!vm) { - if ((process.env.NODE_ENV !== 'production')) { - console.error(formatLog('Wxs', 'CallMethod', 'vm not found')); - } - return; - } - if (!vm[method]) { - if ((process.env.NODE_ENV !== 'production')) { - console.error(formatLog('Wxs', 'CallMethod', method, ' not found')); - } - return; - } - vm[method](args); - } - function resolveOwnerVm(ownerId, vm) { - if (!vm) { - return null; - } - if (vm.uid === ownerId) { - return vm.proxy; - } - let parent = vm.parent; - while (parent) { - if (parent.uid === ownerId) { - return parent.proxy; - } - parent = parent.parent; - } - return vm.proxy; + + var static_init_done = false; + + /* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ + function _tr_init(s) + { + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); } - function initSubscribeHandlers() { - const { subscribe, subscribeHandler, publishHandler } = UniServiceJSBridge; - onPlusMessage('subscribeHandler', ({ type, data, pageId }) => { - subscribeHandler(type, data, pageId); - }); - onPlusMessage(WEB_INVOKE_APPSERVICE, ({ data, webviewIds }) => { - onWebInvokeAppService(data, webviewIds); - }); - if (__uniConfig.renderer !== 'native') { - // 非纯原生 - subscribe(ON_WEBVIEW_READY, subscribeWebviewReady); - subscribe(VD_SYNC, onVdSync); - subscribeServiceMethod(); - subscribeAd(); - subscribeNavigator(); - subscribe(WEBVIEW_INSERTED, onWebviewInserted); - subscribe(WEBVIEW_REMOVED, onWebviewRemoved); - subscribe(ON_WXS_INVOKE_CALL_METHOD, onWxsInvokeCallMethod); - const routeOptions = getRouteOptions(addLeadingSlash(__uniConfig.entryPagePath)); - if (routeOptions && !routeOptions.meta.isNVue) { - // 防止首页 webview 初始化过早, service 还未开始监听 - publishHandler(ON_WEBVIEW_READY, {}, 1); - } - } + + /* =========================================================================== + * Send a stored block + */ + function _tr_stored_block(s, buf, stored_len, last) + //DeflateState *s; + //charf *buf; /* input block */ + //ulg stored_len; /* length of input block */ + //int last; /* one if this is the last block for a file */ + { + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ } - let appCtx; - const defaultApp = { - globalData: {}, - }; - function getApp$1({ allowDefault = false } = {}) { - if (appCtx) { - // 真实的 App 已初始化 - return appCtx; - } - if (allowDefault) { - // 返回默认实现 - return defaultApp; - } - console.error('[warn]: getApp() failed. Learn more: https://uniapp.dcloud.io/collocation/frame/window?id=getapp.'); - } - function registerApp(appVm) { - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('registerApp')); - } - initVueApp(appVm); - appCtx = appVm; - initAppVm(appCtx); - extend(appCtx, defaultApp); // 拷贝默认实现 - const { $options } = appVm; - if ($options) { - appCtx.globalData = extend($options.globalData || {}, appCtx.globalData); - } - initService(); - initEntry(); - initTabBar(); - initGlobalEvent(); - initSubscribeHandlers(); - initAppLaunch(appVm); - // 10s后清理临时文件 - setTimeout(clearTempFile, 10000); - __uniConfig.ready = true; + + /* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ + function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); } - var index$1 = { - install(app) { - initMount(app); - initApp(app); - initServicePlugin(app); - }, - }; - function initMount(app) { - const oldMount = app.mount; - app.mount = (rootContainer) => { - const instance = oldMount.call(app, rootContainer); - if (rootContainer === '#app') { - registerApp(instance); - } - return instance; - }; - } - function restoreGlobal(newVue, newWeex, newPlus, newSetTimeout, newClearTimeout, newSetInterval, newClearInterval) { - // 确保部分全局变量 是 app-service 中的 - // 若首页 nvue 初始化比 app-service 快,导致框架处于该 nvue 环境下 - // plus 如果不用 app-service,资源路径会出问题 - // 若首页 nvue 被销毁,如 redirectTo 或 reLaunch,则这些全局功能会损坏 - // 设置 vue3 - // @ts-ignore 最终vue会被替换为vue - vue = newVue; - if (plus !== newPlus) { - if ((process.env.NODE_ENV !== 'production')) { - console.log(`[restoreGlobal][${Date.now()}]`); - } - weex = newWeex; - // @ts-ignore - plus = newPlus; - restoreOldSetStatusBarStyle(plus.navigator.setStatusBarStyle); - plus.navigator.setStatusBarStyle = newSetStatusBarStyle; - /* eslint-disable no-global-assign */ - // @ts-ignore - setTimeout = newSetTimeout; - // @ts-ignore - clearTimeout = newClearTimeout; - // @ts-ignore - setInterval = newSetInterval; - // @ts-ignore - clearInterval = newClearInterval; - } - __uniConfig.serviceReady = true; - } + /* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ + function _tr_flush_block(s, buf, stored_len, last) + //DeflateState *s; + //charf *buf; /* input block, or NULL if too old */ + //ulg stored_len; /* length of input block */ + //int last; /* one if this is the last block for a file */ + { + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN$1) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; - const sendHostEvent = sendNativeEvent; - const API_NAVIGATE_TO_MINI_PROGRAM = 'navigateToMiniProgram'; - const navigateToMiniProgram = defineAsyncApi(API_NAVIGATE_TO_MINI_PROGRAM, (data, { resolve, reject }) => { - sendHostEvent(API_NAVIGATE_TO_MINI_PROGRAM, data, (res) => { - if (res.errMsg && res.errMsg.indexOf(':ok') === -1) { - return reject(res.errMsg.split(' ')[1]); - } - resolve(); - }); - }); + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); - const EventType = { - load: 'load', - close: 'close', - error: 'error', - adClicked: 'adClicked', - }; - class AdEventHandler { - constructor() { - this._callbacks = {}; - } - onLoad(callback) { - this._addEventListener(EventType.load, callback); - } - onClose(callback) { - this._addEventListener(EventType.close, callback); - } - onError(callback) { - this._addEventListener(EventType.error, callback); - } - offLoad(callback) { - this._removeEventListener(EventType.load, callback); - } - offClose(callback) { - this._removeEventListener(EventType.close, callback); - } - offError(callback) { - this._removeEventListener(EventType.error, callback); - } - _addEventListener(type, callback) { - if (typeof callback !== 'function') { - return; - } - if (!this._callbacks[type]) { - this._callbacks[type] = []; - } - this._callbacks[type].push(callback); - } - _removeEventListener(type, callback) { - const arrayFunction = this._callbacks[type]; - const index = arrayFunction.indexOf(callback); - if (index > -1) { - arrayFunction.splice(index, 1); - } - } - _dispatchEvent(name, data) { - this._callbacks[name].forEach((callback) => { - callback(data || {}); - }); - } - } - class AdBase extends AdEventHandler { - constructor(adInstance, options) { - super(); - this.preload = true; - this._isLoaded = false; - this._isLoading = false; - this._loadPromiseResolve = null; - this._loadPromiseReject = null; - this._showPromiseResolve = null; - this._showPromiseReject = null; - this.preload = options.preload !== undefined ? options.preload : false; - const ad = (this._adInstance = adInstance); - ad.onLoad(() => { - this._isLoaded = true; - this._isLoading = false; - if (this._loadPromiseResolve != null) { - this._loadPromiseResolve(); - this._loadPromiseResolve = null; - } - if (this._showPromiseResolve != null) { - this._showPromiseResolve(); - this._showPromiseResolve = null; - this._showAd(); - } - this._dispatchEvent(EventType.load, {}); - }); - ad.onClose((e) => { - this._isLoaded = false; - this._isLoading = false; - this._dispatchEvent(EventType.close, e); - if (this.preload === true) { - this._loadAd(); - } - }); - ad.onError((e) => { - this._isLoading = false; - const data = { - code: e.code, - errMsg: e.message, - }; - this._dispatchEvent(EventType.error, data); - const error = new Error(JSON.stringify(data)); - if (this._loadPromiseReject != null) { - this._loadPromiseReject(error); - this._loadPromiseReject = null; - } - if (this._showPromiseReject != null) { - this._showPromiseReject(error); - this._showPromiseReject = null; - } - }); - ad.onAdClicked && - ad.onAdClicked(() => { - this._dispatchEvent(EventType.adClicked, {}); - }); - } - getProvider() { - return this._adInstance.getProvider(); - } - load() { - return new Promise((resolve, reject) => { - this._loadPromiseResolve = resolve; - this._loadPromiseReject = reject; - if (this._isLoading) { - return; - } - if (this._isLoaded) { - resolve(''); - } - else { - this._loadAd(); - } - }); - } - show() { - return new Promise((resolve, reject) => { - this._showPromiseResolve = resolve; - this._showPromiseReject = reject; - if (this._isLoading) { - return; - } - if (this._isLoaded) { - this._showAd(); - resolve(''); - } - else { - this._loadAd(); - } - }); - } - destroy() { - this._adInstance.destroy(); - } - _loadAd() { - this._isLoaded = false; - this._isLoading = true; - this._adInstance.load(); - } - _showAd() { - this._adInstance.show(); - } + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); } - class RewardedVideoAd extends AdBase { - constructor(options) { - super(plus.ad.createRewardedVideoAd(options), options); - this._loadAd(); - } - } - const createRewardedVideoAd = (defineSyncApi(API_CREATE_REWARDED_VIDEO_AD, (options) => { - return new RewardedVideoAd(options); - }, CreateRewardedVideoAdProtocol, CreateRewardedVideoAdOptions)); + /* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ + function _tr_tally(s, dist, lc) + // deflate_state *s; + // unsigned dist; /* distance of matched string */ + // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ + { + //var out_length, in_length, dcode; - class FullScreenVideoAd extends AdBase { - constructor(options) { - super(plus.ad.createFullScreenVideoAd(options), options); - this.preload = false; - } - } - const createFullScreenVideoAd = (defineSyncApi(API_CREATE_FULL_SCREEN_VIDEO_AD, (options) => { - return new FullScreenVideoAd(options); - }, CreateFullScreenVideoAdProtocol, CreateFullScreenVideoAdOptions)); + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; - class InterstitialAd extends AdBase { - constructor(options) { - super(plus.ad.createInterstitialAd(options), options); - this.preload = false; - this._loadAd(); - } - } - const createInterstitialAd = (defineSyncApi(API_CREATE_INTERSTITIAL_AD, (options) => { - return new InterstitialAd(options); - }, CreateInterstitialAdProtocol, CreateInterstitialAdOptions)); + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; - const sdkCache = {}; - const sdkQueue = {}; - function initSDK(options) { - const provider = options.provider; - if (!sdkCache[provider]) { - sdkCache[provider] = {}; - } - if (typeof sdkCache[provider].plugin === 'object') { - options.success(sdkCache[provider].plugin); - return; - } - if (!sdkQueue[provider]) { - sdkQueue[provider] = []; - } - sdkQueue[provider].push(options); - if (sdkCache[provider].status === true) { - options.__plugin = sdkCache[provider].plugin; - return; - } - sdkCache[provider].status = true; - const plugin = requireNativePlugin(provider); - if (!plugin || !plugin.initSDK) { - sdkQueue[provider].forEach((item) => { - item.fail({ - code: -1, - message: 'provider [' + provider + '] invalid', - }); - }); - sdkQueue[provider].length = 0; - sdkCache[provider].status = false; - return; - } - // TODO - sdkCache[provider].plugin = plugin; - options.__plugin = plugin; - plugin.initSDK((res) => { - const isSuccess = res.code === 1 || res.code === '1'; - if (isSuccess) { - sdkCache[provider].plugin = plugin; - } - else { - sdkCache[provider].status = false; - } - sdkQueue[provider].forEach((item) => { - if (isSuccess) { - item.success(item.__plugin); - } - else { - item.fail(res); - } - }); - sdkQueue[provider].length = 0; - }); - } - class InteractiveAd extends AdEventHandler { - constructor(options) { - super(); - this._adpid = ''; - this._provider = ''; - this._userData = null; - this._isLoaded = false; - this._isLoading = false; - this._loadPromiseResolve = null; - this._loadPromiseReject = null; - this._showPromiseResolve = null; - this._showPromiseReject = null; - this._adInstance = null; - this._adError = ''; - this._adpid = options.adpid; - this._provider = options.provider; - this._userData = options.userData; - setTimeout(() => { - this._init(); - }); - } - _init() { - this._adError = ''; - initSDK({ - provider: this._provider, - success: (res) => { - this._adInstance = res; - if (this._userData) { - this.bindUserData(this._userData); - } - this._loadAd(); - }, - fail: (err) => { - this._adError = err; - if (this._loadPromiseReject != null) { - this._loadPromiseReject(this._createError(err)); - this._loadPromiseReject = null; - } - this._dispatchEvent(EventType.error, err); - }, - }); - } - getProvider() { - return this._provider; - } - load() { - return new Promise((resolve, reject) => { - this._loadPromiseResolve = resolve; - this._loadPromiseReject = reject; - if (this._isLoading) { - return; - } - if (this._adError) { - this._init(); - return; - } - if (this._isLoaded) { - resolve(''); - } - else { - this._loadAd(); - } - }); - } - show() { - return new Promise((resolve, reject) => { - this._showPromiseResolve = resolve; - this._showPromiseReject = reject; - if (this._isLoading) { - return; - } - if (this._adError) { - this._init(); - return; - } - if (this._isLoaded) { - this._showAd(); - resolve(''); - } - else { - this._loadAd(); - } - }); - } - reportExposure() { - if (this._adInstance !== null) { - this._adInstance.reportExposure(); - } - } - bindUserData(data) { - if (this._adInstance !== null) { - this._adInstance.bindUserData(data); - } - } - destroy() { - if (this._adInstance !== null && this._adInstance.destroy) { - this._adInstance.destroy({ - adpid: this._adpid, - }); - } - } - _loadAd() { - if (this._adInstance !== null) { - if (this._isLoading === true) { - return; - } - this._isLoading = true; - this._adInstance.loadData({ - adpid: this._adpid, - }, (res) => { - this._isLoaded = true; - this._isLoading = false; - if (this._loadPromiseResolve != null) { - this._loadPromiseResolve(); - this._loadPromiseResolve = null; - } - if (this._showPromiseResolve != null) { - this._showPromiseResolve(); - this._showPromiseResolve = null; - this._showAd(); - } - this._dispatchEvent(EventType.load, res); - }, (err) => { - this._isLoading = false; - if (this._showPromiseReject != null) { - this._showPromiseReject(this._createError(err)); - this._showPromiseReject = null; - } - this._dispatchEvent(EventType.error, err); - }); - } - } - _showAd() { - if (this._adInstance !== null && this._isLoaded === true) { - this._adInstance.show({ - adpid: this._adpid, - }, () => { - this._isLoaded = false; - }, (err) => { - this._isLoaded = false; - if (this._showPromiseReject != null) { - this._showPromiseReject(this._createError(err)); - this._showPromiseReject = null; - } - this._dispatchEvent(EventType.error, err); - }); - } - } - _createError(err) { - return new Error(JSON.stringify(err)); - } - } - const createInteractiveAd = (defineSyncApi(API_CREATE_INTERACTIVE_AD, (options) => { - return new InteractiveAd(options); - }, CreateInteractiveAdProtocol, CreateInteractiveAdOptions)); + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, (args, { resolve, reject }) => { - const page = getCurrentPage(); - if (!page) { - return reject(`getCurrentPages is empty`); - } - if (invokeHook(page, ON_BACK_PRESS, { - from: args.from, - })) { - return resolve(); - } - uni.hideToast(); - uni.hideLoading(); - if (page.$page.meta.isQuit) { - quit(); - } - else if ( - // 处于直达页面 - page.$page.route === __uniConfig.entryPagePath && - __uniConfig.realEntryPagePath) { - // condition - __uniConfig.entryPagePath = __uniConfig.realEntryPagePath; - delete __uniConfig.realEntryPagePath; - uni.reLaunch({ - url: addLeadingSlash(__uniConfig.entryPagePath), - }); - } - else { - const { delta, animationType, animationDuration } = args; - back(delta, animationType, animationDuration); - } - return resolve(); - }, NavigateBackProtocol, NavigateBackOptions); - let firstBackTime = 0; - function quit() { - initI18nAppMsgsOnce(); - if (!firstBackTime) { - firstBackTime = Date.now(); - plus.nativeUI.toast(useI18n().t('uni.app.quit')); - setTimeout(() => { - firstBackTime = 0; - }, 2000); - } - else if (Date.now() - firstBackTime < 2000) { - plus.runtime.quit(); - } - } - function back(delta, animationType, animationDuration) { - const pages = getCurrentPages(); - const len = pages.length; - const currentPage = pages[len - 1]; - if (delta > 1) { - // 中间页隐藏 - pages - .slice(len - delta, len - 1) - .reverse() - .forEach((deltaPage) => { - closeWebview(plus.webview.getWebviewById(deltaPage.$page.id + ''), 'none', 0); - }); - } - const backPage = function (webview) { - if (animationType) { - closeWebview(webview, animationType, animationDuration || ANI_DURATION); - } - else { - if (currentPage.$page.openType === 'redirectTo') { - // 如果是 redirectTo 跳转的,需要指定 back 动画 - closeWebview(webview, ANI_CLOSE, ANI_DURATION); - } - else { - closeWebview(webview, 'auto'); - } - } - pages - .slice(len - delta, len) - .forEach((page) => removePage(page)); - setStatusBarStyle(); - // 前一个页面触发 onShow - invokeHook(ON_SHOW); - }; - const webview = plus.webview.getWebviewById(currentPage.$page.id + ''); - if (!currentPage.__uniapp_webview) { - return backPage(webview); - } - backWebview(webview, () => { - backPage(webview); - }); + s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + + // (!) This block is disabled in zlib defaults, + // don't enable it for binary compatibility + + //#ifdef TRUNCATE_BLOCK + // /* Try to guess if it is profitable to stop the current block here */ + // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { + // /* Compute an upper bound for the compressed length */ + // out_length = s.last_lit*8; + // in_length = s.strstart - s.block_start; + // + // for (dcode = 0; dcode < D_CODES; dcode++) { + // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); + // } + // out_length >>>= 3; + // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + // // s->last_lit, in_length, out_length, + // // 100L - out_length*100L/in_length)); + // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { + // return true; + // } + // } + //#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ } - const redirectTo = defineAsyncApi(API_REDIRECT_TO, ({ url }, { resolve, reject }) => { - const { path, query } = parseUrl(url); - navigate(path, () => { - _redirectTo({ - url, - path, - query, - }) - .then(resolve) - .catch(reject); - }); - }, RedirectToProtocol, RedirectToOptions); - function _redirectTo({ url, path, query, }) { - // TODO exists - // if (exists === 'back') { - // const existsPageIndex = findExistsPageIndex(url) - // if (existsPageIndex !== -1) { - // const delta = len - existsPageIndex - // if (delta > 0) { - // navigateBack({ - // delta, - // }) - // invoke(callbackId, { - // errMsg: 'redirectTo:ok', - // }) - // return - // } - // } - // } - const lastPage = getCurrentPage(); - lastPage && removePage(lastPage); - return new Promise((resolve) => { - showWebview(registerPage({ - url, - path, - query, - openType: 'redirectTo', - }), 'none', 0, () => { - if (lastPage) { - const webview = lastPage - .$getAppWebview(); - if (webview.__preload__) { - removePreloadWebview(webview); - } - webview.close('none'); - } - resolve(undefined); - }); - setStatusBarStyle(); - }); + var _tr_init_1 = _tr_init; + var _tr_stored_block_1 = _tr_stored_block; + var _tr_flush_block_1 = _tr_flush_block; + var _tr_tally_1 = _tr_tally; + var _tr_align_1 = _tr_align; + + var trees$1 = { + _tr_init: _tr_init_1, + _tr_stored_block: _tr_stored_block_1, + _tr_flush_block: _tr_flush_block_1, + _tr_tally: _tr_tally_1, + _tr_align: _tr_align_1 + }; + + // Note: adler32 takes 12% for level 0 and 2% for level 6. + // It isn't worth it to make additional optimizations as in original. + // Small size is preferable. + + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + function adler32$1(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; + } + + + var adler32_1 = adler32$1; + + // Note: we can't get significant speed boost here. + // So write code to minimize size - no pregenerated tables + // and array tools dependencies. + + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + // Use ordinary array, since untyped makes no boost here + function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; } - const unPreloadPage = defineSyncApi(API_UN_PRELOAD_PAGE, ({ url }) => { - const webview = closePreloadWebview({ - url, - }); - if (webview) { - return { - id: webview.id, - url, - errMsg: 'unPreloadPage:ok', - }; - } - return { - url, - errMsg: 'unPreloadPage:fail not found', - }; - }, UnPreloadPageProtocol); - const preloadPage = defineAsyncApi(API_PRELOAD_PAGE, ({ url }, { resolve, reject }) => { - const urls = url.split('?'); - const path = urls[0]; - const query = parseQuery(urls[1] || ''); - const webview = preloadWebview({ - url, - path, - query, - }); - resolve({ - id: webview.id, - url, - errMsg: 'preloadPage:ok', - }); - }, PreloadPageProtocol); + // Create table on load. Just 255 signed longs. Not a problem. + var crcTable = makeTable(); - var uni$1 = { - __proto__: null, - navigateTo: navigateTo, - reLaunch: reLaunch, - switchTab: switchTab, - upx2px: upx2px, - addInterceptor: addInterceptor, - removeInterceptor: removeInterceptor, - interceptors: interceptors, - arrayBufferToBase64: arrayBufferToBase64, - base64ToArrayBuffer: base64ToArrayBuffer, - createIntersectionObserver: createIntersectionObserver, - createMediaQueryObserver: createMediaQueryObserver, - createSelectorQuery: createSelectorQuery, - createVideoContext: createVideoContext, - createMapContext: createMapContext, - createAnimation: createAnimation, - onWindowResize: onWindowResize, - offWindowResize: offWindowResize, - onTabBarMidButtonTap: onTabBarMidButtonTap, - createCanvasContext: createCanvasContext, - canvasGetImageData: canvasGetImageData, - canvasPutImageData: canvasPutImageData, - canvasToTempFilePath: canvasToTempFilePath, - getSelectedTextRange: getSelectedTextRange, - getLocale: getLocale, - setLocale: setLocale, - $on: $on, - $off: $off, - $once: $once, - $emit: $emit, - onAppLaunch: onAppLaunch, - onLocaleChange: onLocaleChange, - setPageMeta: setPageMeta, - getEnterOptionsSync: getEnterOptionsSync, - getLaunchOptionsSync: getLaunchOptionsSync, - setStorageSync: setStorageSync, - setStorage: setStorage, - getStorageSync: getStorageSync, - getStorage: getStorage, - removeStorageSync: removeStorageSync, - removeStorage: removeStorage, - clearStorageSync: clearStorageSync, - clearStorage: clearStorage, - getStorageInfoSync: getStorageInfoSync, - getStorageInfo: getStorageInfo, - getFileInfo: getFileInfo$1, - openDocument: openDocument, - saveFile: saveFile, - getSystemInfoSync: getSystemInfoSync, - getSystemInfo: getSystemInfo, - onCompassChange: onCompassChange, - offCompassChange: offCompassChange, - startCompass: startCompass, - stopCompass: stopCompass, - vibrateShort: vibrateShort, - vibrateLong: vibrateLong, - onAccelerometerChange: onAccelerometerChange, - offAccelerometerChange: offAccelerometerChange, - startAccelerometer: startAccelerometer, - stopAccelerometer: stopAccelerometer, - onBluetoothDeviceFound: onBluetoothDeviceFound, - onBluetoothAdapterStateChange: onBluetoothAdapterStateChange, - onBLEConnectionStateChange: onBLEConnectionStateChange, - onBLECharacteristicValueChange: onBLECharacteristicValueChange, - openBluetoothAdapter: openBluetoothAdapter, - closeBluetoothAdapter: closeBluetoothAdapter, - getBluetoothAdapterState: getBluetoothAdapterState, - startBluetoothDevicesDiscovery: startBluetoothDevicesDiscovery, - stopBluetoothDevicesDiscovery: stopBluetoothDevicesDiscovery, - getBluetoothDevices: getBluetoothDevices, - getConnectedBluetoothDevices: getConnectedBluetoothDevices, - createBLEConnection: createBLEConnection, - closeBLEConnection: closeBLEConnection, - getBLEDeviceServices: getBLEDeviceServices, - getBLEDeviceCharacteristics: getBLEDeviceCharacteristics, - notifyBLECharacteristicValueChange: notifyBLECharacteristicValueChange, - readBLECharacteristicValue: readBLECharacteristicValue, - writeBLECharacteristicValue: writeBLECharacteristicValue, - setBLEMTU: setBLEMTU, - getBLEDeviceRSSI: getBLEDeviceRSSI, - onBeaconUpdate: onBeaconUpdate, - onBeaconServiceChange: onBeaconServiceChange, - getBeacons: getBeacons, - startBeaconDiscovery: startBeaconDiscovery, - stopBeaconDiscovery: stopBeaconDiscovery, - makePhoneCall: makePhoneCall, - addPhoneContact: addPhoneContact, - getClipboardData: getClipboardData, - setClipboardData: setClipboardData, - onNetworkStatusChange: onNetworkStatusChange, - offNetworkStatusChange: offNetworkStatusChange, - getNetworkType: getNetworkType, - checkIsSupportSoterAuthentication: checkIsSupportSoterAuthentication, - checkIsSoterEnrolledInDevice: checkIsSoterEnrolledInDevice, - startSoterAuthentication: startSoterAuthentication, - scanCode: scanCode, - onThemeChange: onThemeChange, - getScreenBrightness: getScreenBrightness, - setScreenBrightness: setScreenBrightness, - setKeepScreenOn: setKeepScreenOn, - getImageInfo: getImageInfo, - getVideoInfo: getVideoInfo, - previewImage: previewImage, - closePreviewImage: closePreviewImage, - getRecorderManager: getRecorderManager, - saveVideoToPhotosAlbum: saveVideoToPhotosAlbum, - saveImageToPhotosAlbum: saveImageToPhotosAlbum, - compressImage: compressImage, - compressVideo: compressVideo, - chooseImage: chooseImage, - chooseVideo: chooseVideo, - showKeyboard: showKeyboard, - hideKeyboard: hideKeyboard, - onKeyboardHeightChange: onKeyboardHeightChange, - offKeyboardHeightChange: offKeyboardHeightChange, - downloadFile: downloadFile, - request: request, - configMTLS: configMTLS, - connectSocket: connectSocket, - sendSocketMessage: sendSocketMessage, - closeSocket: closeSocket, - onSocketOpen: onSocketOpen, - onSocketError: onSocketError, - onSocketMessage: onSocketMessage, - onSocketClose: onSocketClose, - uploadFile: uploadFile, - createInnerAudioContext: createInnerAudioContext, - getBackgroundAudioManager: getBackgroundAudioManager, - createLivePusherContext: createLivePusherContext, - getLocation: getLocation, - chooseLocation: chooseLocation, - openLocation: openLocation, - showModal: showModal, - showActionSheet: showActionSheet, - showLoading: showLoading, - showToast: showToast, - hideToast: hideToast, - hideLoading: hideLoading, - startPullDownRefresh: startPullDownRefresh, - stopPullDownRefresh: stopPullDownRefresh, - loadFontFace: loadFontFace, - pageScrollTo: pageScrollTo, - setNavigationBarTitle: setNavigationBarTitle, - showNavigationBarLoading: showNavigationBarLoading, - hideNavigationBarLoading: hideNavigationBarLoading, - setNavigationBarColor: setNavigationBarColor, - setTabBarBadge: setTabBarBadge, - setTabBarItem: setTabBarItem, - setTabBarStyle: setTabBarStyle, - hideTabBar: hideTabBar, - showTabBar: showTabBar, - showTabBarRedDot: showTabBarRedDot, - removeTabBarBadge: removeTabBarBadge, - hideTabBarRedDot: hideTabBarRedDot, - getSubNVueById: getSubNVueById, - getProvider: getProvider, - login: login, - getUserInfo: getUserInfo, - getUserProfile: getUserProfile, - preLogin: preLogin, - closeAuthView: closeAuthView, - getCheckBoxState: getCheckBoxState, - getUniverifyManager: getUniverifyManager, - registerRuntime: registerRuntime, - share: share, - shareWithSystem: shareWithSystem, - requestPayment: requestPayment, - requireNativePlugin: requireNativePlugin, - sendNativeEvent: sendNativeEvent, - __vuePlugin: index$1, - restoreGlobal: restoreGlobal, - sendHostEvent: sendHostEvent, - navigateToMiniProgram: navigateToMiniProgram, - createRewardedVideoAd: createRewardedVideoAd, - createFullScreenVideoAd: createFullScreenVideoAd, - createInterstitialAd: createInterstitialAd, - createInteractiveAd: createInteractiveAd, - navigateBack: navigateBack, - redirectTo: redirectTo, - unPreloadPage: unPreloadPage, - preloadPage: preloadPage + + function crc32$1(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; + } + + + var crc32_1 = crc32$1; + + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + var messages = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; - const UniServiceJSBridge$1 = /*#__PURE__*/ extend(ServiceJSBridge, { - publishHandler, - }); - function publishHandler(event, args, pageIds) { - args = JSON.stringify(args); - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('publishHandler', event, args, pageIds)); - } - if (!isArray$1(pageIds)) { - pageIds = [pageIds]; - } - const evalJSCode = `typeof UniViewJSBridge !== 'undefined' && UniViewJSBridge.subscribeHandler("${event}",${args},__PAGE_ID__)`; - if ((process.env.NODE_ENV !== 'production')) { - console.log(formatLog('publishHandler', 'size', evalJSCode.length)); - } - pageIds.forEach((id) => { - const idStr = String(id); - const webview = plus.webview.getWebviewById(idStr); - webview && webview.evalJS(evalJSCode.replace('__PAGE_ID__', idStr)); - }); - } + var trees = trees$1; - var index = { - uni: uni$1, - getApp: getApp$1, - getCurrentPages: getCurrentPages$1, - __definePage: definePage, - __registerApp: registerApp, - __registerPage: registerPage, - UniServiceJSBridge: UniServiceJSBridge$1, - }; + var adler32 = adler32_1; + + var crc32 = crc32_1; + + var msg = messages; - /*! pako 2.0.4 https://github.com/nodeca/pako @license (MIT AND Zlib) */ // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // @@ -13076,3519 +4219,4832 @@ var serviceContext = (function (vue) { // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. - /* eslint-disable space-unary-ops */ + + + + + /* Public constants ==========================================================*/ /* ===========================================================================*/ - //const Z_FILTERED = 1; - //const Z_HUFFMAN_ONLY = 2; - //const Z_RLE = 3; - const Z_FIXED$1 = 4; - //const Z_DEFAULT_STRATEGY = 0; + /* Allowed flush values; see deflate() and inflate() below for details */ + var Z_NO_FLUSH$1 = 0; + var Z_PARTIAL_FLUSH = 1; + //var Z_SYNC_FLUSH = 2; + var Z_FULL_FLUSH = 3; + var Z_FINISH$2 = 4; + var Z_BLOCK$1 = 5; + //var Z_TREES = 6; - /* Possible values of the data_type field (though see inflate()) */ - const Z_BINARY = 0; - const Z_TEXT = 1; - //const Z_ASCII = 1; // = Z_TEXT - const Z_UNKNOWN$1 = 2; - /*============================================================================*/ + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + var Z_OK$2 = 0; + var Z_STREAM_END$2 = 1; + //var Z_NEED_DICT = 2; + //var Z_ERRNO = -1; + var Z_STREAM_ERROR$1 = -2; + var Z_DATA_ERROR$1 = -3; + //var Z_MEM_ERROR = -4; + var Z_BUF_ERROR$1 = -5; + //var Z_VERSION_ERROR = -6; + + + /* compression levels */ + //var Z_NO_COMPRESSION = 0; + //var Z_BEST_SPEED = 1; + //var Z_BEST_COMPRESSION = 9; + var Z_DEFAULT_COMPRESSION$1 = -1; + + + var Z_FILTERED = 1; + var Z_HUFFMAN_ONLY = 2; + var Z_RLE = 3; + var Z_FIXED = 4; + var Z_DEFAULT_STRATEGY$1 = 0; + /* Possible values of the data_type field (though see inflate()) */ + //var Z_BINARY = 0; + //var Z_TEXT = 1; + //var Z_ASCII = 1; // = Z_TEXT + var Z_UNKNOWN = 2; - function zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } } - // From zutil.h + /* The deflate compression method */ + var Z_DEFLATED$2 = 8; - const STORED_BLOCK = 0; - const STATIC_TREES = 1; - const DYN_TREES = 2; - /* The three kinds of block type */ + /*============================================================================*/ - const MIN_MATCH$1 = 3; - const MAX_MATCH$1 = 258; - /* The minimum and maximum match lengths */ - // From deflate.h - /* =========================================================================== - * Internal compression state. - */ + var MAX_MEM_LEVEL = 9; + /* Maximum value for memLevel in deflateInit2 */ + var MAX_WBITS$1 = 15; + /* 32K LZ77 window */ + var DEF_MEM_LEVEL = 8; - const LENGTH_CODES$1 = 29; - /* number of length codes, not counting the special END_BLOCK code */ - const LITERALS$1 = 256; + var LENGTH_CODES = 29; + /* number of length codes, not counting the special END_BLOCK code */ + var LITERALS = 256; /* number of literal bytes 0..255 */ - - const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1; + var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ - - const D_CODES$1 = 30; + var D_CODES = 30; /* number of distance codes */ - - const BL_CODES$1 = 19; + var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ - - const HEAP_SIZE$1 = 2 * L_CODES$1 + 1; + var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ - - const MAX_BITS$1 = 15; + var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ - const Buf_size = 16; - /* size of bit buffer in bi_buf */ + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + var PRESET_DICT = 0x20; - /* =========================================================================== - * Constants - */ + var INIT_STATE = 42; + var EXTRA_STATE = 69; + var NAME_STATE = 73; + var COMMENT_STATE = 91; + var HCRC_STATE = 103; + var BUSY_STATE = 113; + var FINISH_STATE = 666; - const MAX_BL_BITS = 7; - /* Bit length codes must not exceed MAX_BL_BITS bits */ + var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ + var BS_BLOCK_DONE = 2; /* block flush performed */ + var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ + var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ - const END_BLOCK = 256; - /* end of block literal code */ + var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. - const REP_3_6 = 16; - /* repeat previous bit length 3-6 times (2 bits of repeat count) */ + function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; + } - const REPZ_3_10 = 17; - /* repeat a zero length 3-10 times (3 bits of repeat count) */ + function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); + } - const REPZ_11_138 = 18; - /* repeat a zero length 11-138 times (7 bits of repeat count) */ + function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } - /* eslint-disable comma-spacing,array-bracket-spacing */ - const extra_lbits = /* extra bits for each length code */ - new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]); - const extra_dbits = /* extra bits for each distance code */ - new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]); + /* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ + function flush_pending(strm) { + var s = strm.state; - const extra_blbits = /* extra bits for each bit length code */ - new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]); + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } - const bl_order = - new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]); - /* eslint-enable comma-spacing,array-bracket-spacing */ + require$$0.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } + } - /* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - /* =========================================================================== - * Local data. These are initialized only once. - */ + function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); + } - // We pre-fill arrays with 0 to avoid uninitialized gaps - const DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + function put_byte(s, b) { + s.pending_buf[s.pending++] = b; + } - // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 - const static_ltree = new Array((L_CODES$1 + 2) * 2); - zero$1(static_ltree); - /* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - const static_dtree = new Array(D_CODES$1 * 2); - zero$1(static_dtree); - /* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) + /* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. */ + function putShortMSB(s, b) { + // put_byte(s, (Byte)(b >> 8)); + // put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; + } - const _dist_code = new Array(DIST_CODE_LEN); - zero$1(_dist_code); - /* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - const _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1); - zero$1(_length_code); - /* length code for each normalized match length (0 == MIN_MATCH) */ + /* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ + function read_buf(strm, buf, start, size) { + var len = strm.avail_in; - const base_length = new Array(LENGTH_CODES$1); - zero$1(base_length); - /* First normalized length for each code (0 = MIN_MATCH) */ + if (len > size) { len = size; } + if (len === 0) { return 0; } - const base_dist = new Array(D_CODES$1); - zero$1(base_dist); - /* First normalized distance for each code (0 = distance of 1) */ + strm.avail_in -= len; + // zmemcpy(buf, strm->next_in, len); + require$$0.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } - function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } - this.static_tree = static_tree; /* static tree or NULL */ - this.extra_bits = extra_bits; /* extra bits for each code or NULL */ - this.extra_base = extra_base; /* base index for extra_bits */ - this.elems = elems; /* max number of elements in the tree */ - this.max_length = max_length; /* max bit length for the codes */ + strm.next_in += len; + strm.total_in += len; - // show if `static_tree` has data or dummy - needed for monomorphic objects - this.has_stree = static_tree && static_tree.length; + return len; } - let static_l_desc; - let static_d_desc; - let static_bl_desc; - + /* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ + function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; - function TreeDesc(dyn_tree, stat_desc) { - this.dyn_tree = dyn_tree; /* the dynamic tree */ - this.max_code = 0; /* largest code with non zero frequency */ - this.stat_desc = stat_desc; /* the corresponding static tree */ - } + var _win = s.window; // shortcut + var wmask = s.w_mask; + var prev = s.prev; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ - const d_code = (dist) => { + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; - return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; - }; + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } - /* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ - const put_short = (s, w) => { - // put_byte(s, (uch)((w) & 0xff)); - // put_byte(s, (uch)((ush)(w) >> 8)); - s.pending_buf[s.pending++] = (w) & 0xff; - s.pending_buf[s.pending++] = (w >>> 8) & 0xff; - }; + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; - /* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ - const send_bits = (s, value, length) => { + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ - if (s.bi_valid > (Buf_size - length)) { - s.bi_buf |= (value << s.bi_valid) & 0xffff; - put_short(s, s.bi_buf); - s.bi_buf = value >> (Buf_size - s.bi_valid); - s.bi_valid += length - Buf_size; - } else { - s.bi_buf |= (value << s.bi_valid) & 0xffff; - s.bi_valid += length; - } - }; + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); - const send_code = (s, c, tree) => { + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); - send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); - }; + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; - /* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ - const bi_reverse = (code, len) => { + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); - let res = 0; - do { - res |= code & 1; - code >>>= 1; - res <<= 1; - } while (--len > 0); - return res >>> 1; - }; + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; + } /* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). */ - const bi_flush = (s) => { + function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; - if (s.bi_valid === 16) { - put_short(s, s.bi_buf); - s.bi_buf = 0; - s.bi_valid = 0; + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); - } else if (s.bi_valid >= 8) { - s.pending_buf[s.pending++] = s.bi_buf & 0xff; - s.bi_buf >>= 8; - s.bi_valid -= 8; - } - }; + do { + more = s.window_size - s.lookahead - s.strstart; + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} - /* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ - const gen_bitlen = (s, desc) => - // deflate_state *s; - // tree_desc *desc; /* the tree descriptor */ - { - const tree = desc.dyn_tree; - const max_code = desc.max_code; - const stree = desc.stat_desc.static_tree; - const has_stree = desc.stat_desc.has_stree; - const extra = desc.stat_desc.extra_bits; - const base = desc.stat_desc.extra_base; - const max_length = desc.stat_desc.max_length; - let h; /* heap index */ - let n, m; /* iterate over the tree elements */ - let bits; /* bit length */ - let xbits; /* extra bits */ - let f; /* frequency */ - let overflow = 0; /* number of elements with bit length too large */ - for (bits = 0; bits <= MAX_BITS$1; bits++) { - s.bl_count[bits] = 0; - } + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + require$$0.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; - for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) { - n = s.heap[h]; - bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; - if (bits > max_length) { - bits = max_length; - overflow++; - } - tree[n * 2 + 1]/*.Len*/ = bits; - /* We overwrite tree[n].Dad which is no longer needed */ + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ - if (n > max_code) { continue; } /* not a leaf node */ + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); - s.bl_count[bits]++; - xbits = 0; - if (n >= base) { - xbits = extra[n - base]; + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; } - f = tree[n * 2]/*.Freq*/; - s.opt_len += f * (bits + xbits); - if (has_stree) { - s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + if (s.strm.avail_in === 0) { + break; } - } - if (overflow === 0) { return; } - - // Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - /* Find the first bit length which could increase: */ - do { - bits = max_length - 1; - while (s.bl_count[bits] === 0) { bits--; } - s.bl_count[bits]--; /* move one leaf down the tree */ - s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ - s.bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ - overflow -= 2; - } while (overflow > 0); + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits !== 0; bits--) { - n = s.bl_count[bits]; - while (n !== 0) { - m = s.heap[--h]; - if (m > max_code) { continue; } - if (tree[m * 2 + 1]/*.Len*/ !== bits) { - // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; - tree[m * 2 + 1]/*.Len*/ = bits; + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; + //#if MIN_MATCH != 3 + // Call update_hash() MIN_MATCH-3 more times + //#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } } - n--; } - } - }; + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); - /* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ - const gen_codes = (tree, max_code, bl_count) => - // ct_data *tree; /* the tree to decorate */ - // int max_code; /* largest code with non zero frequency */ - // ushf *bl_count; /* number of codes at each bit length */ - { - const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */ - let code = 0; /* running code value */ - let bits; /* bit index */ - let n; /* code index */ + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + // if (s.high_water < s.window_size) { + // var curr = s.strstart + s.lookahead; + // var init = 0; + // + // if (s.high_water < curr) { + // /* Previous high water mark below current data -- zero WIN_INIT + // * bytes or up to end of window, whichever is less. + // */ + // init = s.window_size - curr; + // if (init > WIN_INIT) + // init = WIN_INIT; + // zmemzero(s->window + curr, (unsigned)init); + // s->high_water = curr + init; + // } + // else if (s->high_water < (ulg)curr + WIN_INIT) { + // /* High water mark at or above current data, but below current data + // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + // * to end of window, whichever is less. + // */ + // init = (ulg)curr + WIN_INIT - s->high_water; + // if (init > s->window_size - s->high_water) + // init = s->window_size - s->high_water; + // zmemzero(s->window + s->high_water, (unsigned)init); + // s->high_water += init; + // } + // } + // + // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + // "not enough room for search"); + } - /* The distribution counts are first used to generate the code values - * without bit reversal. + /* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ + function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: */ - for (bits = 1; bits <= MAX_BITS$1; bits++) { - next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - //Assert (code + bl_count[MAX_BITS]-1 == (1<strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); + // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || + // s.block_start >= s.w_size)) { + // throw new Error("slide too late"); + // } + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH$1) { + return BS_NEED_MORE; + } - /* =========================================================================== - * Initialize the various 'constant' tables. - */ - const tr_static_init = () => { - - let n; /* iterates over tree elements */ - let bits; /* bit counter */ - let length; /* length value */ - let code; /* code value */ - let dist; /* distance index */ - const bl_count = new Array(MAX_BITS$1 + 1); - /* number of codes at each bit length for an optimal tree */ + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); + // if (s.block_start < 0) throw new Error("block gone"); - // do check in _tr_init() - //if (static_init_done) return; + s.strstart += s.lookahead; + s.lookahead = 0; - /* For some embedded targets, global variables are not initialized: */ - /*#ifdef NO_INIT_GLOBAL_POINTERS - static_l_desc.static_tree = static_ltree; - static_l_desc.extra_bits = extra_lbits; - static_d_desc.static_tree = static_dtree; - static_d_desc.extra_bits = extra_dbits; - static_bl_desc.extra_bits = extra_blbits; - #endif*/ + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ - /* Initialize the mapping length (0..255) -> length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES$1 - 1; code++) { - base_length[code] = length; - for (n = 0; n < (1 << extra_lbits[code]); n++) { - _length_code[length++] = code; - } - } - //Assert (length == 256, "tr_static_init: length != 256"); - /* Note that the length 255 (match length 258) can be represented - * in two different ways: code 284 + 5 bits or code 285, so we - * overwrite length_code[255] to use the best encoding: - */ - _length_code[length - 1] = code; - /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ - dist = 0; - for (code = 0; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < (1 << extra_dbits[code]); n++) { - _dist_code[dist++] = code; } - } - //Assert (dist == 256, "tr_static_init: dist != 256"); - dist >>= 7; /* from now on, all distances are divided by 128 */ - for (; code < D_CODES$1; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { - _dist_code[256 + dist++] = code; + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ } } - //Assert (dist == 256, "tr_static_init: 256+dist != 512"); - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS$1; bits++) { - bl_count[bits] = 0; - } + s.insert = 0; - n = 0; - while (n <= 143) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - while (n <= 255) { - static_ltree[n * 2 + 1]/*.Len*/ = 9; - n++; - bl_count[9]++; - } - while (n <= 279) { - static_ltree[n * 2 + 1]/*.Len*/ = 7; - n++; - bl_count[7]++; - } - while (n <= 287) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; + if (flush === Z_FINISH$2) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; } - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes(static_ltree, L_CODES$1 + 1, bl_count); - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES$1; n++) { - static_dtree[n * 2 + 1]/*.Len*/ = 5; - static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ } - // Now data ready and we can init static trees - static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1); - static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1); - static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS); - - //static_init_done = true; - }; - + return BS_NEED_MORE; + } /* =========================================================================== - * Initialize a new block. + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. */ - const init_block = (s) => { + function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$1) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } - let n; /* iterates over tree elements */ + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } - /* Initialize the trees. */ - for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } - for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } - for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only - s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; - s.opt_len = s.static_len = 0; - s.last_lit = s.matches = 0; - }; + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + //#if MIN_MATCH != 3 + // Call UPDATE_HASH() MIN_MATCH-3 more times + //#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - /* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ - const bi_windup = (s) => - { - if (s.bi_valid > 8) { - put_short(s, s.bi_buf); - } else if (s.bi_valid > 0) { - //put_byte(s, (Byte)s->bi_buf); - s.pending_buf[s.pending++] = s.bi_buf; + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } } - s.bi_buf = 0; - s.bi_valid = 0; - }; - - /* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ - const copy_block = (s, buf, len, header) => - //DeflateState *s; - //charf *buf; /* the input data */ - //unsigned len; /* its length */ - //int header; /* true if block header must be written */ - { - bi_windup(s); /* align on byte boundary */ - - if (header) { - put_short(s, len); - put_short(s, ~len); + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH$2) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; } - // while (len--) { - // put_byte(s, *buf++); - // } - s.pending_buf.set(s.window.subarray(buf, buf + len), s.pending); - s.pending += len; - }; + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; + } /* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. */ - const smaller = (tree, n, m, depth) => { + function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ - const _n2 = n * 2; - const _m2 = m * 2; - return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || - (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); - }; + var max_insert; - /* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ - const pqdownheap = (s, tree, k) => - // deflate_state *s; - // ct_data *tree; /* the tree to restore */ - // int k; /* node to move down */ - { - const v = s.heap[k]; - let j = k << 1; /* left son of k */ - while (j <= s.heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s.heap_len && - smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { - j++; + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$1) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s.heap[j], s.depth)) { break; } - /* Exchange v with the smallest son */ - s.heap[k] = s.heap[j]; - k = j; + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s.heap[k] = v; - }; + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ - // inlined manually - // const SMALLEST = 1; + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { - /* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ - const compress_block = (s, ltree, dtree) => - // deflate_state *s; - // const ct_data *ltree; /* literal tree */ - // const ct_data *dtree; /* distance tree */ - { - let dist; /* distance of matched string */ - let lc; /* match length or unmatched char (if dist == 0) */ - let lx = 0; /* running index in l_buf */ - let code; /* the code to send */ - let extra; /* number of extra bits to send */ + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ - if (s.last_lit !== 0) { - do { - dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); - lc = s.pending_buf[s.l_buf + lx]; - lx++; + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); - if (dist === 0) { - send_code(s, lc, ltree); /* send a literal byte */ - //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra !== 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - //Assert (code < D_CODES, "bad d_code"); + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra !== 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - // "pendingBuf overflow"); - - } while (lx < s.last_lit); - } - - send_code(s, END_BLOCK, ltree); - }; - - - /* =========================================================================== - * Construct one Huffman tree and assigns the code bit strings and lengths. - * Update the total bit length for the current block. - * IN assertion: the field freq is set for all tree elements. - * OUT assertions: the fields len and code are set to the optimal bit length - * and corresponding code. The length opt_len is updated; static_len is - * also updated if stree is not null. The field max_code is set. - */ - const build_tree = (s, desc) => - // deflate_state *s; - // tree_desc *desc; /* the tree descriptor */ - { - const tree = desc.dyn_tree; - const stree = desc.stat_desc.static_tree; - const has_stree = desc.stat_desc.has_stree; - const elems = desc.stat_desc.elems; - let n, m; /* iterate over heap elements */ - let max_code = -1; /* largest code with non zero frequency */ - let node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s.heap_len = 0; - s.heap_max = HEAP_SIZE$1; + /***/ + } - for (n = 0; n < elems; n++) { - if (tree[n * 2]/*.Freq*/ !== 0) { - s.heap[++s.heap_len] = max_code = n; - s.depth[n] = 0; + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } } else { - tree[n * 2 + 1]/*.Len*/ = 0; + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; } } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s.heap_len < 2) { - node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); - tree[node * 2]/*.Freq*/ = 1; - s.depth[node] = 0; - s.opt_len--; - - if (has_stree) { - s.static_len -= stree[node * 2 + 1]/*.Len*/; + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH$2) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; } - /* node is 0 or 1 so it does not have extra bits */ + /***/ + return BS_FINISH_DONE; } - desc.max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - //pqremove(s, tree, n); /* n = node of least frequency */ - /*** pqremove ***/ - n = s.heap[1/*SMALLEST*/]; - s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; - pqdownheap(s, tree, 1/*SMALLEST*/); + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } /***/ + } - m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + return BS_BLOCK_DONE; + } - s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ - s.heap[--s.heap_max] = m; - /* Create a new node father of n and m */ - tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; - s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; - tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + /* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ + function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ - /* and insert the new node in the heap */ - s.heap[1/*SMALLEST*/] = node++; - pqdownheap(s, tree, 1/*SMALLEST*/); + var _win = s.window; - } while (s.heap_len >= 2); + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$1) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } - s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, desc); + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); - /* The field len is now set, we can generate the bit codes */ - gen_codes(tree, max_code, s.bl_count); - }; + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH$2) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; + } /* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) */ - const scan_tree = (s, tree, max_code) => - // deflate_state *s; - // ct_data *tree; /* the tree to be scanned */ - // int max_code; /* and its largest code of non zero frequency */ - { - let n; /* iterates over all tree elements */ - let prevlen = -1; /* last emitted length */ - let curlen; /* length of current code */ + function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ - let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - let count = 0; /* repeat count of the current code */ - let max_count = 7; /* max repeat count */ - let min_count = 4; /* min repeat count */ + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH$1) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } - if (nextlen === 0) { - max_count = 138; - min_count = 3; + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } } - tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + s.insert = 0; + if (flush === Z_FINISH$2) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; + } - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + /* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ + function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; + } + + var configuration_table; + + configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ + ]; - if (++count < max_count && curlen === nextlen) { - continue; - } else if (count < min_count) { - s.bl_tree[curlen * 2]/*.Freq*/ += count; + /* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ + function lm_init(s) { + s.window_size = 2 * s.w_size; - } else if (curlen !== 0) { + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); - if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } - s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; - } else if (count <= 10) { - s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; + } - } else { - s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; - } - count = 0; - prevlen = curlen; + function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED$2; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ - if (nextlen === 0) { - max_count = 138; - min_count = 3; + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ - } else { - max_count = 7; - min_count = 4; - } - } - }; + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ - /* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ - const send_tree = (s, tree, max_code) => - // deflate_state *s; - // ct_data *tree; /* the tree to be scanned */ - // int max_code; /* and its largest code of non zero frequency */ - { - let n; /* iterates over all tree elements */ - let prevlen = -1; /* last emitted length */ - let curlen; /* length of current code */ + this.head = null; /* Heads of the hash chains or NIL. */ - let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ - let count = 0; /* repeat count of the current code */ - let max_count = 7; /* max repeat count */ - let min_count = 4; /* min repeat count */ + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ - if (++count < max_count && curlen === nextlen) { - continue; + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ - } else if (count < min_count) { - do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ - } else if (curlen !== 0) { - if (curlen !== prevlen) { - send_code(s, curlen, s.bl_tree); - count--; - } - //Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s.bl_tree); - send_bits(s, count - 3, 2); + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ - } else if (count <= 10) { - send_code(s, REPZ_3_10, s.bl_tree); - send_bits(s, count - 3, 3); + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ - } else { - send_code(s, REPZ_11_138, s.bl_tree); - send_bits(s, count - 11, 7); - } + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ - count = 0; - prevlen = curlen; - if (nextlen === 0) { - max_count = 138; - min_count = 3; + this.nice_match = 0; /* Stop searching when current match exceeds this */ - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; + /* used by trees.c: */ - } else { - max_count = 7; - min_count = 4; - } - } - }; + /* Didn't use ct_data typedef below to suppress compiler warning */ + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - /* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ - const build_bl_tree = (s) => { + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new require$$0.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new require$$0.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new require$$0.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); - let max_blindex; /* index of last bit length code of non zero freq */ + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, s.dyn_ltree, s.l_desc.max_code); - scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + //ush bl_count[MAX_BITS+1]; + this.bl_count = new require$$0.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ - /* Build the bit length tree: */ - build_tree(s, s.bl_desc); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new require$$0.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. */ - for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) { - if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { - break; - } - } - /* Update opt_len to include the bit length tree and counts */ - s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; - //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - // s->opt_len, s->static_len)); - - return max_blindex; - }; - - - /* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ - const send_all_trees = (s, lcodes, dcodes, blcodes) => - // deflate_state *s; - // int lcodes, dcodes, blcodes; /* number of codes for each tree */ - { - let rank; /* index in bl_order */ - //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - // "too many codes"); - //Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes - 1, 5); - send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); - } - //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + this.depth = new require$$0.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ - send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ - //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + this.l_buf = 0; /* buffer index for literals or lengths */ - send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ - //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); - }; + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + this.last_lit = 0; /* running index in l_buf */ - /* =========================================================================== - * Check if the data type is TEXT or BINARY, using the following algorithm: - * - TEXT if the two conditions below are satisfied: - * a) There are no non-portable control characters belonging to the - * "black list" (0..6, 14..25, 28..31). - * b) There is at least one printable character belonging to the - * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). - * - BINARY otherwise. - * - The following partially-portable control characters form a - * "gray list" that is ignored in this detection algorithm: - * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). - * IN assertion: the fields Freq of dyn_ltree are set. - */ - const detect_data_type = (s) => { - /* black_mask is the bit mask of black-listed bytes - * set bits 0..6, 14..25, and 28..31 - * 0xf3ffc07f = binary 11110011111111111100000001111111 + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. */ - let black_mask = 0xf3ffc07f; - let n; - /* Check for non-textual ("black-listed") bytes. */ - for (n = 0; n <= 31; n++, black_mask >>>= 1) { - if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { - return Z_BINARY; - } - } + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ - /* Check for textual ("white-listed") bytes. */ - if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || - s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - for (n = 32; n < LITERALS$1; n++) { - if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - } - /* There are no "black-listed" or "white-listed" bytes: - * this stream either is empty or has tolerated ("gray-listed") bytes only. + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. */ - return Z_BINARY; - }; + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ + } - let static_init_done = false; - /* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ - const _tr_init$1 = (s) => - { + function deflateResetKeep(strm) { + var s; - if (!static_init_done) { - tr_static_init(); - static_init_done = true; + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR$1); } - s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); - s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); - s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; - s.bi_buf = 0; - s.bi_valid = 0; + s = strm.state; + s.pending = 0; + s.pending_out = 0; - /* Initialize the first block of the first file: */ - init_block(s); - }; + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH$1; + trees._tr_init(s); + return Z_OK$2; + } - /* =========================================================================== - * Send a stored block - */ - const _tr_stored_block$1 = (s, buf, stored_len, last) => - //DeflateState *s; - //charf *buf; /* input block */ - //ulg stored_len; /* length of input block */ - //int last; /* one if this is the last block for a file */ - { - send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ - copy_block(s, buf, stored_len, true); /* with header */ - }; + function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK$2) { + lm_init(strm.state); + } + return ret; + } - /* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - */ - const _tr_align$1 = (s) => { - send_bits(s, STATIC_TREES << 1, 3); - send_code(s, END_BLOCK, static_ltree); - bi_flush(s); - }; + function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR$1; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR$1; } + strm.state.gzhead = head; + return Z_OK$2; + } - /* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ - const _tr_flush_block$1 = (s, buf, stored_len, last) => - //DeflateState *s; - //charf *buf; /* input block, or NULL if too old */ - //ulg stored_len; /* length of input block */ - //int last; /* one if this is the last block for a file */ - { - let opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - let max_blindex = 0; /* index of last bit length code of non zero freq */ + function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR$1; + } + var wrap = 1; - /* Build the Huffman trees unless a stored block is forced */ - if (s.level > 0) { + if (level === Z_DEFAULT_COMPRESSION$1) { + level = 6; + } - /* Check if the file is binary or text */ - if (s.strm.data_type === Z_UNKNOWN$1) { - s.strm.data_type = detect_data_type(s); - } + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } - /* Construct the literal and distance trees */ - build_tree(s, s.l_desc); - // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } - build_tree(s, s.d_desc); - // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR$1); + } - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = (s.opt_len + 3 + 7) >>> 3; - static_lenb = (s.static_len + 3 + 7) >>> 3; - // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - // s->last_lit)); + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ - if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + var s = new DeflateState(); - } else { - // Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } + strm.state = s; + s.strm = strm; - if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { - /* 4: two words for the lengths */ + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block$1(s, buf, stored_len, last); + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); - } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) { + s.window = new require$$0.Buf8(s.w_size * 2); + s.head = new require$$0.Buf16(s.hash_size); + s.prev = new require$$0.Buf16(s.w_size); - send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); - compress_block(s, static_ltree, static_dtree); + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ - } else { - send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); - send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); - compress_block(s, s.dyn_ltree, s.dyn_dtree); - } - // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - if (last) { - bi_windup(s); - } - // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - // s->compressed_len-7*last)); - }; + s.pending_buf_size = s.lit_bufsize * 4; - /* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ - const _tr_tally$1 = (s, dist, lc) => - // deflate_state *s; - // unsigned dist; /* distance of matched string */ - // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ - { - //let out_length, in_length, dcode; + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new require$$0.Buf8(s.pending_buf_size); - s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; - s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; - s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; - s.last_lit++; + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; - if (dist === 0) { - /* lc is the unmatched char */ - s.dyn_ltree[lc * 2]/*.Freq*/++; - } else { - s.matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - //Assert((ush)dist < (ush)MAX_DIST(s) && - // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + return deflateReset(strm); + } - s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++; - s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; - } + function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1); + } - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - //#ifdef TRUNCATE_BLOCK - // /* Try to guess if it is profitable to stop the current block here */ - // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { - // /* Compute an upper bound for the compressed length */ - // out_length = s.last_lit*8; - // in_length = s.strstart - s.block_start; - // - // for (dcode = 0; dcode < D_CODES; dcode++) { - // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); - // } - // out_length >>>= 3; - // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - // // s->last_lit, in_length, out_length, - // // 100L - out_length*100L/in_length)); - // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { - // return true; - // } - // } - //#endif + function deflate$2(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only - return (s.last_lit === s.lit_bufsize - 1); - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ - }; + if (!strm || !strm.state || + flush > Z_BLOCK$1 || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR$1) : Z_STREAM_ERROR$1; + } - var _tr_init_1 = _tr_init$1; - var _tr_stored_block_1 = _tr_stored_block$1; - var _tr_flush_block_1 = _tr_flush_block$1; - var _tr_tally_1 = _tr_tally$1; - var _tr_align_1 = _tr_align$1; + s = strm.state; - var trees = { - _tr_init: _tr_init_1, - _tr_stored_block: _tr_stored_block_1, - _tr_flush_block: _tr_flush_block_1, - _tr_tally: _tr_tally_1, - _tr_align: _tr_align_1 - }; + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH$2)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$1); + } - // Note: adler32 takes 12% for level 0 and 2% for level 6. - // It isn't worth it to make additional optimizations as in original. - // Small size is preferable. + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. + /* Write the header */ + if (s.status === INIT_STATE) { - const adler32 = (adler, buf, len, pos) => { - let s1 = (adler & 0xffff) |0, - s2 = ((adler >>> 16) & 0xffff) |0, - n = 0; + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; - while (len !== 0) { - // Set limit ~ twice less than 5552, to keep - // s2 in 31-bits, because we force signed ints. - // in other case %= will fail. - n = len > 2000 ? 2000 : len; - len -= n; + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); - do { - s1 = (s1 + buf[pos++]) |0; - s2 = (s2 + s1) |0; - } while (--n); + s.status = BUSY_STATE; + putShortMSB(s, header); - s1 %= 65521; - s2 %= 65521; + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } } - return (s1 | (s2 << 16)) |0; - }; - + //#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ - var adler32_1 = adler32; + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; - // Note: we can't get significant speed boost here. - // So write code to minimize size - no pregenerated tables - // and array tools dependencies. + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; - // Use ordinary array, since untyped makes no boost here - const makeTable = () => { - let c, table = []; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); - for (var n = 0; n < 256; n++) { - c = n; - for (var k = 0; k < 8; k++) { - c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; } - table[n] = c; } - - return table; - }; - - // Create table on load. Just 255 signed longs. Not a problem. - const crcTable = new Uint32Array(makeTable()); - - - const crc32 = (crc, buf, len, pos) => { - const t = crcTable; - const end = pos + len; - - crc ^= -1; - - for (let i = pos; i < end; i++) { - crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } } + //#endif - return (crc ^ (-1)); // >>> 0; - }; - - - var crc32_1 = crc32; - - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. - - var messages = { - 2: 'need dictionary', /* Z_NEED_DICT 2 */ - 1: 'stream end', /* Z_STREAM_END 1 */ - 0: '', /* Z_OK 0 */ - '-1': 'file error', /* Z_ERRNO (-1) */ - '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ - '-3': 'data error', /* Z_DATA_ERROR (-3) */ - '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ - '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ - '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ - }; - - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK$2; + } - var constants$2 = { + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH$2) { + return err(strm, Z_BUF_ERROR$1); + } - /* Allowed flush values; see deflate() and inflate() below for details */ - Z_NO_FLUSH: 0, - Z_PARTIAL_FLUSH: 1, - Z_SYNC_FLUSH: 2, - Z_FULL_FLUSH: 3, - Z_FINISH: 4, - Z_BLOCK: 5, - Z_TREES: 6, + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR$1); + } - /* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ - Z_OK: 0, - Z_STREAM_END: 1, - Z_NEED_DICT: 2, - Z_ERRNO: -1, - Z_STREAM_ERROR: -2, - Z_DATA_ERROR: -3, - Z_MEM_ERROR: -4, - Z_BUF_ERROR: -5, - //Z_VERSION_ERROR: -6, + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH$1 && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); - /* compression levels */ - Z_NO_COMPRESSION: 0, - Z_BEST_SPEED: 1, - Z_BEST_COMPRESSION: 9, - Z_DEFAULT_COMPRESSION: -1, + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK$2; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */ + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); - Z_FILTERED: 1, - Z_HUFFMAN_ONLY: 2, - Z_RLE: 3, - Z_FIXED: 4, - Z_DEFAULT_STRATEGY: 0, + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK$2; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} - /* Possible values of the data_type field (though see inflate()) */ - Z_BINARY: 0, - Z_TEXT: 1, - //Z_ASCII: 1, // = Z_TEXT (deprecated) - Z_UNKNOWN: 2, + if (flush !== Z_FINISH$2) { return Z_OK$2; } + if (s.wrap <= 0) { return Z_STREAM_END$2; } - /* The deflate compression method */ - Z_DEFLATED: 8 - //Z_NULL: null // Use -1 or null inline, depending on var type - }; + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK$2 : Z_STREAM_END$2; + } - const { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees; + function deflateEnd(strm) { + var status; + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR$1; + } + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR$1); + } + strm.state = null; - /* Public constants ==========================================================*/ - /* ===========================================================================*/ + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$1) : Z_OK$2; + } - const { - Z_NO_FLUSH: Z_NO_FLUSH$2, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$3, Z_BLOCK: Z_BLOCK$1, - Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_BUF_ERROR: Z_BUF_ERROR$1, - Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1, - Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1, - Z_UNKNOWN, - Z_DEFLATED: Z_DEFLATED$2 - } = constants$2; - /*============================================================================*/ + /* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ + function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; - const MAX_MEM_LEVEL = 9; - /* Maximum value for memLevel in deflateInit2 */ - const MAX_WBITS$1 = 15; - /* 32K LZ77 window */ - const DEF_MEM_LEVEL = 8; + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR$1; + } + s = strm.state; + wrap = s.wrap; - const LENGTH_CODES = 29; - /* number of length codes, not counting the special END_BLOCK code */ - const LITERALS = 256; - /* number of literal bytes 0..255 */ - const L_CODES = LITERALS + 1 + LENGTH_CODES; - /* number of Literal or Length codes, including the END_BLOCK code */ - const D_CODES = 30; - /* number of distance codes */ - const BL_CODES = 19; - /* number of codes used to transfer the bit lengths */ - const HEAP_SIZE = 2 * L_CODES + 1; - /* maximum heap size */ - const MAX_BITS = 15; - /* All codes must not exceed MAX_BITS bits */ + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR$1; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } - const MIN_MATCH = 3; - const MAX_MATCH = 258; - const MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ - const PRESET_DICT = 0x20; + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new require$$0.Buf8(s.w_size); + require$$0.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; - const INIT_STATE = 42; - const EXTRA_STATE = 69; - const NAME_STATE = 73; - const COMMENT_STATE = 91; - const HCRC_STATE = 103; - const BUSY_STATE = 113; - const FINISH_STATE = 666; + s.prev[str & s.w_mask] = s.head[s.ins_h]; - const BS_NEED_MORE = 1; /* block not completed, need more input or more output */ - const BS_BLOCK_DONE = 2; /* block flush performed */ - const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ - const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK$2; + } - const OS_CODE = 0x03; // Unix :) . Don't detect, use this default. - const err = (strm, errorCode) => { - strm.msg = messages[errorCode]; - return errorCode; - }; + var deflateInit_1 = deflateInit; + var deflateInit2_1 = deflateInit2; + var deflateReset_1 = deflateReset; + var deflateResetKeep_1 = deflateResetKeep; + var deflateSetHeader_1 = deflateSetHeader; + var deflate_2$1 = deflate$2; + var deflateEnd_1 = deflateEnd; + var deflateSetDictionary_1 = deflateSetDictionary; + var deflateInfo = 'pako deflate (from Nodeca project)'; - const rank = (f) => { - return ((f) << 1) - ((f) > 4 ? 9 : 0); - }; + /* Not implemented + exports.deflateBound = deflateBound; + exports.deflateCopy = deflateCopy; + exports.deflateParams = deflateParams; + exports.deflatePending = deflatePending; + exports.deflatePrime = deflatePrime; + exports.deflateTune = deflateTune; + */ - const zero = (buf) => { - let len = buf.length; while (--len >= 0) { buf[len] = 0; } + var deflate_1$1 = { + deflateInit: deflateInit_1, + deflateInit2: deflateInit2_1, + deflateReset: deflateReset_1, + deflateResetKeep: deflateResetKeep_1, + deflateSetHeader: deflateSetHeader_1, + deflate: deflate_2$1, + deflateEnd: deflateEnd_1, + deflateSetDictionary: deflateSetDictionary_1, + deflateInfo: deflateInfo }; + // Quick check if we can use fast array to bin string conversion + // + // - apply(Array) can fail on Android 2.2 + // - apply(Uint8Array) can fail on iOS 5.1 Safari + // + var STR_APPLY_OK = true; + var STR_APPLY_UIA_OK = true; - /* eslint-disable new-cap */ - let HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask; - // This hash causes less collisions, https://github.com/nodeca/pako/issues/135 - // But breaks binary compatibility - //let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask; - let HASH = HASH_ZLIB; + try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } + try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } - /* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->output buffer and copying into it. - * (See also read_buf()). - */ - const flush_pending = (strm) => { - const s = strm.state; - //_tr_flush_bits(s); - let len = s.pending; - if (len > strm.avail_out) { - len = strm.avail_out; + // Table with utf8 lengths (calculated by first byte of sequence) + // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, + // because max possible codepoint is 0x10ffff + var _utf8len = new require$$0.Buf8(256); + for (var q = 0; q < 256; q++) { + _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); + } + _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start + + + // convert string to array (typed, when possible) + var string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } - if (len === 0) { return; } - strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out); - strm.next_out += len; - s.pending_out += len; - strm.total_out += len; - strm.avail_out -= len; - s.pending -= len; - if (s.pending === 0) { - s.pending_out = 0; + // allocate buffer + buf = new require$$0.Buf8(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } } + + return buf; }; + // Helper (used in 2 places) + function buf2binstring(buf, len) { + // On Chrome, the arguments in a function call that are allowed is `65534`. + // If the length of the buffer is smaller than that, we can use this optimization, + // otherwise we will take a slower path. + if (len < 65534) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, require$$0.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; + } - const flush_block_only = (s, last) => { - _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); - s.block_start = s.strstart; - flush_pending(s.strm); + + // Convert byte array to binary string + var buf2binstring_1 = function (buf) { + return buf2binstring(buf, buf.length); }; - const put_byte = (s, b) => { - s.pending_buf[s.pending++] = b; + // Convert binary string (typed, when possible) + var binstring2buf = function (str) { + var buf = new require$$0.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; }; - /* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ - const putShortMSB = (s, b) => { + // convert array to string + var buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; - // put_byte(s, (Byte)(b >> 8)); - // put_byte(s, (Byte)(b & 0xff)); - s.pending_buf[s.pending++] = (b >>> 8) & 0xff; - s.pending_buf[s.pending++] = b & 0xff; - }; + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } - /* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->input buffer and copying from it. - * (See also flush_pending()). - */ - const read_buf = (strm, buf, start, size) => { + c_len = _utf8len[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } - let len = strm.avail_in; + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } - if (len > size) { len = size; } - if (len === 0) { return 0; } + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); + }; + + + // Calculate max possible position in utf8 buffer, + // that will not break sequence. If that's not possible + // - (very small limits) return max size as is. + // + // buf[] - utf8 bytes array + // max - length limit (mandatory); + var utf8border = function (buf, max) { + var pos; - strm.avail_in -= len; + max = max || buf.length; + if (max > buf.length) { max = buf.length; } - // zmemcpy(buf, strm->next_in, len); - buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start); - if (strm.state.wrap === 1) { - strm.adler = adler32_1(strm.adler, buf, len, start); - } + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } - else if (strm.state.wrap === 2) { - strm.adler = crc32_1(strm.adler, buf, len, start); - } + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } - strm.next_in += len; - strm.total_in += len; + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } - return len; + return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; + var strings$1 = { + string2buf: string2buf, + buf2binstring: buf2binstring_1, + binstring2buf: binstring2buf, + buf2string: buf2string, + utf8border: utf8border + }; - /* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ - const longest_match = (s, cur_match) => { - - let chain_length = s.max_chain_length; /* max hash chain length */ - let scan = s.strstart; /* current string */ - let match; /* matched string */ - let len; /* length of current match */ - let best_len = s.prev_length; /* best match length so far */ - let nice_match = s.nice_match; /* stop if match long enough */ - const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? - s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. - const _win = s.window; // shortcut + function ZStream$1() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; + } - const wmask = s.w_mask; - const prev = s.prev; + var zstream = ZStream$1; - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ + var zlib_deflate = deflate_1$1; - const strend = s.strstart + MAX_MATCH; - let scan_end1 = _win[scan + best_len - 1]; - let scan_end = _win[scan + best_len]; + var strings = strings$1; - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + var ZStream = zstream; - /* Do not waste too much time if we already have a good match: */ - if (s.prev_length >= s.good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if (nice_match > s.lookahead) { nice_match = s.lookahead; } + var toString$1 = Object.prototype.toString; - // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + /* Public constants ==========================================================*/ + /* ===========================================================================*/ - do { - // Assert(cur_match < s->strstart, "no future"); - match = cur_match; + var Z_NO_FLUSH = 0; + var Z_FINISH$1 = 4; - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ + var Z_OK$1 = 0; + var Z_STREAM_END$1 = 1; + var Z_SYNC_FLUSH = 2; - if (_win[match + best_len] !== scan_end || - _win[match + best_len - 1] !== scan_end1 || - _win[match] !== _win[scan] || - _win[++match] !== _win[scan + 1]) { - continue; - } + var Z_DEFAULT_COMPRESSION = -1; - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2; - match++; - // Assert(*scan == *match, "match[2]?"); + var Z_DEFAULT_STRATEGY = 0; - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - /*jshint noempty:false*/ - } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - scan < strend); + var Z_DEFLATED$1 = 8; - // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + /* ===========================================================================*/ - len = MAX_MATCH - (strend - scan); - scan = strend - MAX_MATCH; - if (len > best_len) { - s.match_start = cur_match; - best_len = len; - if (len >= nice_match) { - break; - } - scan_end1 = _win[scan + best_len - 1]; - scan_end = _win[scan + best_len]; - } - } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + /** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ - if (best_len <= s.lookahead) { - return best_len; - } - return s.lookahead; - }; + /* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + /** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ - /* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. + /** + * Deflate.err -> Number * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ - const fill_window = (s) => { + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ - const _w_size = s.w_size; - let p, n, m, more, str; + /** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ - //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); - do { - more = s.window_size - s.lookahead - s.strstart; + /** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ + function Deflate(options) { + if (!(this instanceof Deflate)) return new Deflate(options); - // JS ints have 32 bit, block below not needed - /* Deal with !@#$% 64K limit: */ - //if (sizeof(int) <= 2) { - // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - // more = wsize; - // - // } else if (more == (unsigned)(-1)) { - // /* Very unlikely, but possible on 16 bit machine if - // * strstart == 0 && lookahead == 1 (input done a byte at time) - // */ - // more--; - // } - //} + this.options = require$$0.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED$1, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: '' + }, options || {}); + var opt = this.options; - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } - s.window.set(s.window.subarray(_w_size, _w_size + _w_size), 0); - s.match_start -= _w_size; - s.strstart -= _w_size; - /* we now have strstart >= MAX_DIST */ - s.block_start -= _w_size; + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data - n = s.hash_size; - p = n; + this.strm = new ZStream(); + this.strm.avail_out = 0; - do { - m = s.head[--p]; - s.head[p] = (m >= _w_size ? m - _w_size : 0); - } while (--n); + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); - n = _w_size; - p = n; + if (status !== Z_OK$1) { + throw new Error(msg[status]); + } - do { - m = s.prev[--p]; - s.prev[p] = (m >= _w_size ? m - _w_size : 0); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } - more += _w_size; + if (opt.dictionary) { + var dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings.string2buf(opt.dictionary); + } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; } - if (s.strm.avail_in === 0) { - break; + + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + + if (status !== Z_OK$1) { + throw new Error(msg[status]); } - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - //Assert(more >= 2, "more < 2"); - n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); - s.lookahead += n; + this._dict_set = true; + } + } - /* Initialize the hash value now that we have some input: */ - if (s.lookahead + s.insert >= MIN_MATCH) { - str = s.strstart - s.insert; - s.ins_h = s.window[str]; + /** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ + Deflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; - /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ - s.ins_h = HASH(s, s.ins_h, s.window[str + 1]); - //#if MIN_MATCH != 3 - // Call update_hash() MIN_MATCH-3 more times - //#endif - while (s.insert) { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]); + if (this.ended) { return false; } - s.prev[str & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = str; - str++; - s.insert--; - if (s.lookahead + s.insert < MIN_MATCH) { - break; - } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH$1 : Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString$1.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new require$$0.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END$1 && status !== Z_OK$1) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH$1 || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(require$$0.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(require$$0.shrinkBuf(strm.output, strm.next_out)); } } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END$1); + + // Finalize on the last chunk. + if (_mode === Z_FINISH$1) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK$1; + } - } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK$1); + strm.avail_out = 0; + return true; + } - /* If the WIN_INIT bytes after the end of the current data have never been - * written, then zero those bytes in order to avoid memory check reports of - * the use of uninitialized (or uninitialised as Julian writes) bytes by - * the longest match routines. Update the high water mark for the next - * time through here. WIN_INIT is set to MAX_MATCH since the longest match - * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. - */ - // if (s.high_water < s.window_size) { - // const curr = s.strstart + s.lookahead; - // let init = 0; - // - // if (s.high_water < curr) { - // /* Previous high water mark below current data -- zero WIN_INIT - // * bytes or up to end of window, whichever is less. - // */ - // init = s.window_size - curr; - // if (init > WIN_INIT) - // init = WIN_INIT; - // zmemzero(s->window + curr, (unsigned)init); - // s->high_water = curr + init; - // } - // else if (s->high_water < (ulg)curr + WIN_INIT) { - // /* High water mark at or above current data, but below current data - // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up - // * to end of window, whichever is less. - // */ - // init = (ulg)curr + WIN_INIT - s->high_water; - // if (init > s->window_size - s->high_water) - // init = s->window_size - s->high_water; - // zmemzero(s->window + s->high_water, (unsigned)init); - // s->high_water += init; - // } - // } - // - // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, - // "not enough room for search"); + return true; }; - /* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ - const deflate_stored = (s, flush) => { - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - let max_block_size = 0xffff; + /** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ + Deflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); + }; - if (max_block_size > s.pending_buf_size - 5) { - max_block_size = s.pending_buf_size - 5; - } - /* Copy as much as possible from input to output: */ - for (;;) { - /* Fill the window as much as possible: */ - if (s.lookahead <= 1) { + /** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ + Deflate.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK$1) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = require$$0.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; - //Assert(s->strstart < s->w_size+MAX_DIST(s) || - // s->block_start >= (long)s->w_size, "slide too late"); - // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || - // s.block_start >= s.w_size)) { - // throw new Error("slide too late"); - // } - fill_window(s); - if (s.lookahead === 0 && flush === Z_NO_FLUSH$2) { - return BS_NEED_MORE; - } + /** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ + function deflate$1(input, options) { + var deflator = new Deflate(options); - if (s.lookahead === 0) { - break; - } - /* flush the current block */ - } - //Assert(s->block_start >= 0L, "block gone"); - // if (s.block_start < 0) throw new Error("block gone"); + deflator.push(input, true); - s.strstart += s.lookahead; - s.lookahead = 0; + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || msg[deflator.err]; } - /* Emit a stored block if pending_buf will be full: */ - const max_start = s.block_start + max_block_size; + return deflator.result; + } - if (s.strstart === 0 || s.strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s.lookahead = s.strstart - max_start; - s.strstart = max_start; - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ + /** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ + function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate$1(input, options); + } - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; + /** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ + function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate$1(input, options); + } - if (flush === Z_FINISH$3) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.strstart > s.block_start) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } + var Deflate_1 = Deflate; + var deflate_2 = deflate$1; + var deflateRaw_1 = deflateRaw; + var gzip_1 = gzip; - return BS_NEED_MORE; + var deflate_1 = { + Deflate: Deflate_1, + deflate: deflate_2, + deflateRaw: deflateRaw_1, + gzip: gzip_1 }; - /* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ - const deflate_fast = (s, flush) => { - - let hash_head; /* head of the hash chain */ - let bflush; /* set if current block must be flushed */ + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { - break; /* flush the current block */ - } - } + // See state defs from inflate.js + var BAD$1 = 30; /* got a data error -- remain here until reset */ + var TYPE$2 = 12; /* i: waiting for type bits, including last-flag bit */ - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]); - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } + /* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - } - if (s.match_length >= MIN_MATCH) { - // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + Entry assumptions: - /*** _tr_tally_dist(s, s.strstart - s.match_start, - s.match_length - MIN_MATCH, bflush); ***/ - bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 - s.lookahead -= s.match_length; + On return, state.mode is one of: - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ - if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { - s.match_length--; /* string at strstart already in table */ - do { - s.strstart++; - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]); - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s.match_length !== 0); - s.strstart++; - } else - { - s.strstart += s.match_length; - s.match_length = 0; - s.ins_h = s.window[s.strstart]; - /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ - s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]); + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data - //#if MIN_MATCH != 3 - // Call UPDATE_HASH() MIN_MATCH-3 more times - //#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s.window[s.strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); + Notes: - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); - if (flush === Z_FINISH$3) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; - }; + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. - /* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. */ - const deflate_slow = (s, flush) => { + var inffast = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ + //#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ + //#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; - let hash_head; /* head of hash chain */ - let bflush; /* set if current block must be flushed */ - let max_insert; + var input, output; // JS specific, because we have no pointers - /* Process the input block. */ - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); + //#ifdef INFLATE_STRICT + dmax = state.dmax; + //#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]); - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - /* Find the longest match, discarding those <= prev_length. - */ - s.prev_length = s.match_length; - s.prev_match = s.match_start; - s.match_length = MIN_MATCH - 1; + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ - if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && - s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } - if (s.match_length <= 5 && - (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + here = lcode[hold & lmask]; - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s.match_length = MIN_MATCH - 1; + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { - max_insert = s.strstart + s.lookahead - MIN_MATCH; - /* Do not insert strings in hash table beyond this. */ + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; - //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; - /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, - s.prev_length - MIN_MATCH, bflush);***/ - bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s.lookahead -= s.prev_length - 1; - s.prev_length -= 2; - do { - if (++s.strstart <= max_insert) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]); - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - } while (--s.prev_length !== 0); - s.match_available = 0; - s.match_length = MIN_MATCH - 1; - s.strstart++; + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); + //#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$1; + break top; + } + //#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$1; + break top; + } + + // (!) This block is disabled in zlib defaults, + // don't enable it for binary compatibility + //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + // if (len <= op - whave) { + // do { + // output[_out++] = 0; + // } while (--len); + // continue top; + // } + // len -= op - whave; + // do { + // output[_out++] = 0; + // } while (--op > whave); + // if (op === 0) { + // from = _out - dist; + // do { + // output[_out++] = output[from++]; + // } while (--len); + // continue top; + // } + //#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD$1; + break top; + } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; + break; // need to emulate goto via "continue" } - /***/ } - - } else if (s.match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); - - if (bflush) { - /*** FLUSH_BLOCK_ONLY(s, 0) ***/ - flush_block_only(s, false); - /***/ + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; } - s.strstart++; - s.lookahead--; - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE$2; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD$1; + break top; } - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s.match_available = 1; - s.strstart++; - s.lookahead--; - } - } - //Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s.match_available) { - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); - s.match_available = 0; - } - s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; - if (flush === Z_FINISH$3) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; + break; // need to emulate goto via "continue" } - /***/ - } + } while (_in < last && _out < end); - return BS_BLOCK_DONE; + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; }; + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. - /* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ - const deflate_rle = (s, flush) => { - let bflush; /* set if current block must be flushed */ - let prev; /* byte at distance one to match */ - let scan, strend; /* scan goes up to strend for length of run */ - const _win = s.window; + var MAXBITS = 15; + var ENOUGH_LENS$1 = 852; + var ENOUGH_DISTS$1 = 592; + //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest run, plus one for the unrolled loop. - */ - if (s.lookahead <= MAX_MATCH) { - fill_window(s); - if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$2) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } + var CODES$1 = 0; + var LENS$1 = 1; + var DISTS$1 = 2; - /* See how many times the previous byte repeats */ - s.match_length = 0; - if (s.lookahead >= MIN_MATCH && s.strstart > 0) { - scan = s.strstart - 1; - prev = _win[scan]; - if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { - strend = s.strstart + MAX_MATCH; - do { - /*jshint noempty:false*/ - } while (prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - scan < strend); - s.match_length = MAX_MATCH - (strend - scan); - if (s.match_length > s.lookahead) { - s.match_length = s.lookahead; - } - } - //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); - } + var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 + ]; - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (s.match_length >= MIN_MATCH) { - //check_match(s, s.strstart, s.strstart - 1, s.match_length); + var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 + ]; - /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ - bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH); + var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 + ]; - s.lookahead -= s.match_length; - s.strstart += s.match_length; - s.match_length = 0; - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); + var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 + ]; - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } + var inftrees = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) + { + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; + // var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new require$$0.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new require$$0.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; } - s.insert = 0; - if (flush === Z_FINISH$3) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } } - return BS_BLOCK_DONE; - }; + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; - /* =========================================================================== - * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. - * (It will be regenerated if this run of deflate switches away from Huffman.) - */ - const deflate_huff = (s, flush) => { - let bflush; /* set if current block must be flushed */ + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; - for (;;) { - /* Make sure that we have a literal to write. */ - if (s.lookahead === 0) { - fill_window(s); - if (s.lookahead === 0) { - if (flush === Z_NO_FLUSH$2) { - return BS_NEED_MORE; - } - break; /* flush the current block */ - } - } + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } - /* Output a literal byte */ - s.match_length = 0; - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - s.lookahead--; - s.strstart++; - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ } - s.insert = 0; - if (flush === Z_FINISH$3) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; + if (left > 0 && (type === CODES$1 || max !== 1)) { + return -1; /* incomplete set */ } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; } - /***/ } - return BS_BLOCK_DONE; - }; - /* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ - function Config(good_length, max_lazy, nice_length, max_chain, func) { + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. - this.good_length = good_length; - this.max_lazy = max_lazy; - this.nice_length = nice_length; - this.max_chain = max_chain; - this.func = func; - } + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. - const configuration_table = [ - /* good lazy nice chain */ - new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ - new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ - new Config(4, 5, 16, 8, deflate_fast), /* 2 */ - new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. - new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ - new Config(8, 16, 32, 32, deflate_slow), /* 5 */ - new Config(8, 16, 128, 128, deflate_slow), /* 6 */ - new Config(8, 32, 128, 256, deflate_slow), /* 7 */ - new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ - new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ - ]; + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ - /* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ - const lm_init = (s) => { + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES$1) { + base = extra = work; /* dummy value--not used */ + end = 19; - s.window_size = 2 * s.w_size; + } else if (type === LENS$1) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; - /*** CLEAR_HASH(s); ***/ - zero(s.head); // Fill with NIL (= 0); + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } - /* Set the default configuration parameters: - */ - s.max_lazy_match = configuration_table[s.level].max_lazy; - s.good_match = configuration_table[s.level].good_length; - s.nice_match = configuration_table[s.level].nice_length; - s.max_chain_length = configuration_table[s.level].max_chain; + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ - s.strstart = 0; - s.block_start = 0; - s.lookahead = 0; - s.insert = 0; - s.match_length = s.prev_length = MIN_MATCH - 1; - s.match_available = 0; - s.ins_h = 0; - }; + /* check available table space */ + if ((type === LENS$1 && used > ENOUGH_LENS$1) || + (type === DISTS$1 && used > ENOUGH_DISTS$1)) { + return 1; + } + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } - function DeflateState() { - this.strm = null; /* pointer back to this zlib stream */ - this.status = 0; /* as the name implies */ - this.pending_buf = null; /* output still pending */ - this.pending_buf_size = 0; /* size of pending_buf */ - this.pending_out = 0; /* next pending byte to output to the stream */ - this.pending = 0; /* nb of bytes in the pending buffer */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.gzhead = null; /* gzip header information to write */ - this.gzindex = 0; /* where in extra, name, or comment */ - this.method = Z_DEFLATED$2; /* can only be DEFLATED */ - this.last_flush = -1; /* value of flush param for previous deflate call */ + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ - this.w_size = 0; /* LZ77 window size (32K by default) */ - this.w_bits = 0; /* log2(w_size) (8..16) */ - this.w_mask = 0; /* w_size - 1 */ + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } - this.window = null; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. - */ + /* check for enough space */ + used += 1 << curr; + if ((type === LENS$1 && used > ENOUGH_LENS$1) || + (type === DISTS$1 && used > ENOUGH_DISTS$1)) { + return 1; + } - this.window_size = 0; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } - this.prev = null; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } - this.head = null; /* Heads of the hash chains or NIL. */ + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; + }; - this.ins_h = 0; /* hash index of string to be inserted */ - this.hash_size = 0; /* number of elements in hash table */ - this.hash_bits = 0; /* log2(hash_size) */ - this.hash_mask = 0; /* hash_size-1 */ + var inflate_fast = inffast; - this.hash_shift = 0; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ + var inflate_table = inftrees; - this.block_start = 0; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. - this.match_length = 0; /* length of best match */ - this.prev_match = 0; /* previous match */ - this.match_available = 0; /* set if previous match exists */ - this.strstart = 0; /* start of string to insert */ - this.match_start = 0; /* start of matching string */ - this.lookahead = 0; /* number of valid bytes ahead in window */ - this.prev_length = 0; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - this.max_chain_length = 0; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - this.max_lazy_match = 0; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ - // That's alias to max_lazy_match, don't use directly - //this.max_insert_length = 0; - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - this.level = 0; /* compression level (1..9) */ - this.strategy = 0; /* favor or force Huffman coding*/ - this.good_match = 0; - /* Use a faster search when the previous match is longer than this */ - this.nice_match = 0; /* Stop searching when current match exceeds this */ + var CODES = 0; + var LENS = 1; + var DISTS = 2; - /* used by trees.c: */ + /* Public constants ==========================================================*/ + /* ===========================================================================*/ - /* Didn't use ct_data typedef below to suppress compiler warning */ - // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + /* Allowed flush values; see deflate() and inflate() below for details */ + //var Z_NO_FLUSH = 0; + //var Z_PARTIAL_FLUSH = 1; + //var Z_SYNC_FLUSH = 2; + //var Z_FULL_FLUSH = 3; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_TREES = 6; - // Use flat array of DOUBLE size, with interleaved fata, - // because JS does not support effective - this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2); - this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2); - this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2); - zero(this.dyn_ltree); - zero(this.dyn_dtree); - zero(this.bl_tree); - this.l_desc = null; /* desc. for literal tree */ - this.d_desc = null; /* desc. for distance tree */ - this.bl_desc = null; /* desc. for bit length tree */ + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_NEED_DICT = 2; + //var Z_ERRNO = -1; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_MEM_ERROR = -4; + var Z_BUF_ERROR = -5; + //var Z_VERSION_ERROR = -6; - //ush bl_count[MAX_BITS+1]; - this.bl_count = new Uint16Array(MAX_BITS + 1); - /* number of codes at each bit length for an optimal tree */ + /* The deflate compression method */ + var Z_DEFLATED = 8; - //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */ - zero(this.heap); - this.heap_len = 0; /* number of elements in the heap */ - this.heap_max = 0; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ + /* STATES ====================================================================*/ + /* ===========================================================================*/ - this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; - zero(this.depth); - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - this.l_buf = 0; /* buffer index for literals or lengths */ + var HEAD = 1; /* i: waiting for magic header */ + var FLAGS = 2; /* i: waiting for method and flags (gzip) */ + var TIME = 3; /* i: waiting for modification time (gzip) */ + var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ + var EXLEN = 5; /* i: waiting for extra length (gzip) */ + var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ + var NAME = 7; /* i: waiting for end of file name (gzip) */ + var COMMENT = 8; /* i: waiting for end of comment (gzip) */ + var HCRC = 9; /* i: waiting for header crc (gzip) */ + var DICTID = 10; /* i: waiting for dictionary check value */ + var DICT = 11; /* waiting for inflateSetDictionary() call */ + var TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */ + var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ + var STORED = 14; /* i: waiting for stored size (length and complement) */ + var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ + var COPY = 16; /* i/o: waiting for input or output to copy stored block */ + var TABLE = 17; /* i: waiting for dynamic block table lengths */ + var LENLENS = 18; /* i: waiting for code length code lengths */ + var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ + var LEN_ = 20; /* i: same as LEN below, but only first time in */ + var LEN = 21; /* i: waiting for length/lit/eob code */ + var LENEXT = 22; /* i: waiting for length extra bits */ + var DIST = 23; /* i: waiting for distance code */ + var DISTEXT = 24; /* i: waiting for distance extra bits */ + var MATCH = 25; /* o: waiting for output space to copy string */ + var LIT = 26; /* o: waiting for output space to write literal */ + var CHECK = 27; /* i: waiting for 32-bit check value */ + var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ + var DONE = 29; /* finished check, done -- remain here until reset */ + var BAD = 30; /* got a data error -- remain here until reset */ + var MEM = 31; /* got an inflate() memory error -- remain here until reset */ + var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ - this.lit_bufsize = 0; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ + /* ===========================================================================*/ - this.last_lit = 0; /* running index in l_buf */ - this.d_buf = 0; - /* Buffer index for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - this.opt_len = 0; /* bit length of current block with optimal trees */ - this.static_len = 0; /* bit length of current block with static trees */ - this.matches = 0; /* number of string matches in current block */ - this.insert = 0; /* bytes at end of window left to insert */ + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + var MAX_WBITS = 15; + /* 32K LZ77 window */ + var DEF_WBITS = MAX_WBITS; - this.bi_buf = 0; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - this.bi_valid = 0; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - // Used for window memory init. We safely ignore it for JS. That makes - // sense only for pointers and memory check tools. - //this.high_water = 0; - /* High water mark offset in window for initialized bytes -- bytes above - * this are set to zero in order to avoid memory check warnings when - * longest match routines access bytes past the input. This is then - * updated to the new high water mark. - */ + function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); } - const deflateResetKeep = (strm) => { + function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ - if (!strm || !strm.state) { - return err(strm, Z_STREAM_ERROR$2); - } + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ - strm.total_in = strm.total_out = 0; - strm.data_type = Z_UNKNOWN; + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ - const s = strm.state; - s.pending = 0; - s.pending_out = 0; + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ - if (s.wrap < 0) { - s.wrap = -s.wrap; - /* was made negative by deflate(..., Z_FINISH); */ - } - s.status = (s.wrap ? INIT_STATE : BUSY_STATE); - strm.adler = (s.wrap === 2) ? - 0 // crc32(0, Z_NULL, 0) - : - 1; // adler32(0, Z_NULL, 0) - s.last_flush = Z_NO_FLUSH$2; - _tr_init(s); - return Z_OK$3; - }; + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + this.lens = new require$$0.Buf16(320); /* temporary storage for code lengths */ + this.work = new require$$0.Buf16(288); /* work area for code table building */ - const deflateReset = (strm) => { + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ + } - const ret = deflateResetKeep(strm); - if (ret === Z_OK$3) { - lm_init(strm.state); - } - return ret; - }; + function inflateResetKeep(strm) { + var state; + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new require$$0.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new require$$0.Buf32(ENOUGH_DISTS); - const deflateSetHeader = (strm, head) => { + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; + } - if (!strm || !strm.state) { return Z_STREAM_ERROR$2; } - if (strm.state.wrap !== 2) { return Z_STREAM_ERROR$2; } - strm.state.gzhead = head; - return Z_OK$3; - }; + function inflateReset(strm) { + var state; + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); - const deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => { + } - if (!strm) { // === Z_NULL - return Z_STREAM_ERROR$2; - } - let wrap = 1; + function inflateReset2(strm, windowBits) { + var wrap; + var state; - if (level === Z_DEFAULT_COMPRESSION$1) { - level = 6; - } + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; - if (windowBits < 0) { /* suppress zlib wrapper */ + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } - - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } } - - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return err(strm, Z_STREAM_ERROR$2); + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; } - - - if (windowBits === 8) { - windowBits = 9; + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; } - /* until 256-byte window bug fixed */ - - const s = new DeflateState(); - strm.state = s; - s.strm = strm; + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); + } - s.wrap = wrap; - s.gzhead = null; - s.w_bits = windowBits; - s.w_size = 1 << s.w_bits; - s.w_mask = s.w_size - 1; + function inflateInit2(strm, windowBits) { + var ret; + var state; - s.hash_bits = memLevel + 7; - s.hash_size = 1 << s.hash_bits; - s.hash_mask = s.hash_size - 1; - s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ - s.window = new Uint8Array(s.w_size * 2); - s.head = new Uint16Array(s.hash_size); - s.prev = new Uint16Array(s.w_size); + state = new InflateState(); - // Don't need mem init magic for JS. - //s.high_water = 0; /* nothing written to s->window yet */ + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; + } - s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); + } - s.pending_buf_size = s.lit_bufsize * 4; - //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - //s->pending_buf = (uchf *) overlay; - s.pending_buf = new Uint8Array(s.pending_buf_size); + /* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ + var virgin = true; - // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) - //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s.d_buf = 1 * s.lit_bufsize; + var lenfix, distfix; // We have no pointers in JS, so keep tables separate - //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - s.l_buf = (1 + 2) * s.lit_bufsize; + function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; - s.level = level; - s.strategy = strategy; - s.method = method; + lenfix = new require$$0.Buf32(512); + distfix = new require$$0.Buf32(32); - return deflateReset(strm); - }; + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } - const deflateInit = (strm, level) => { + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); - return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1); - }; + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); - const deflate$2 = (strm, flush) => { + /* do this just once */ + virgin = false; + } - let beg, val; // for gzip header write only + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; + } - if (!strm || !strm.state || - flush > Z_BLOCK$1 || flush < 0) { - return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2; - } - const s = strm.state; + /* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. - if (!strm.output || - (!strm.input && strm.avail_in !== 0) || - (s.status === FINISH_STATE && flush !== Z_FINISH$3)) { - return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2); - } + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ + function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; - s.strm = strm; /* just in case */ - const old_flush = s.last_flush; - s.last_flush = flush; + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; - /* Write the header */ - if (s.status === INIT_STATE) { + state.window = new require$$0.Buf8(state.wsize); + } - if (s.wrap === 2) { // GZIP header - strm.adler = 0; //crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (!s.gzhead) { // s->gzhead == Z_NULL - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s.status = BUSY_STATE; - } - else { - put_byte(s, (s.gzhead.text ? 1 : 0) + - (s.gzhead.hcrc ? 2 : 0) + - (!s.gzhead.extra ? 0 : 4) + - (!s.gzhead.name ? 0 : 8) + - (!s.gzhead.comment ? 0 : 16) - ); - put_byte(s, s.gzhead.time & 0xff); - put_byte(s, (s.gzhead.time >> 8) & 0xff); - put_byte(s, (s.gzhead.time >> 16) & 0xff); - put_byte(s, (s.gzhead.time >> 24) & 0xff); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, s.gzhead.os & 0xff); - if (s.gzhead.extra && s.gzhead.extra.length) { - put_byte(s, s.gzhead.extra.length & 0xff); - put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); - } - if (s.gzhead.hcrc) { - strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0); - } - s.gzindex = 0; - s.status = EXTRA_STATE; - } + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + require$$0.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; } - else // DEFLATE header - { - let header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8; - let level_flags = -1; + //zmemcpy(state->window + state->wnext, end - copy, dist); + require$$0.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + require$$0.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; + } - if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { - level_flags = 0; - } else if (s.level < 6) { - level_flags = 1; - } else if (s.level === 6) { - level_flags = 2; - } else { - level_flags = 3; - } - header |= (level_flags << 6); - if (s.strstart !== 0) { header |= PRESET_DICT; } - header += 31 - (header % 31); + function inflate$2(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new require$$0.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; - s.status = BUSY_STATE; - putShortMSB(s, header); - /* Save the adler32 of the preset dictionary: */ - if (s.strstart !== 0) { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - strm.adler = 1; // adler32(0L, Z_NULL, 0); - } + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; } - //#ifdef GZIP - if (s.status === EXTRA_STATE) { - if (s.gzhead.extra/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ + state = strm.state; + if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */ - while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE$1; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + require$$0.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - break; + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); } + have -= copy; + next += copy; + if (len) { break inf_leave; } } - put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); - s.gzindex++; - } - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (s.gzindex === s.gzhead.extra.length) { - s.gzindex = 0; - s.status = NAME_STATE; - } - } - else { - s.status = NAME_STATE; - } - } - if (s.status === NAME_STATE) { - if (s.gzhead.name/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; break; } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.name.length) { - val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE$1; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE$1; + /* falls through */ + case TYPE$1: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + require$$0.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE$1; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + //#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.gzindex = 0; - s.status = COMMENT_STATE; - } - } - else { - s.status = COMMENT_STATE; - } - } - if (s.status === COMMENT_STATE) { - if (s.gzhead.comment/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; + //#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.comment.length) { - val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; + while (state.have < 19) { + state.lens[order[state.have++]] = 0; } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.status = HCRC_STATE; - } - } - else { - s.status = HCRC_STATE; - } - } - if (s.status === HCRC_STATE) { - if (s.gzhead.hcrc) { - if (s.pending + 2 > s.pending_buf_size) { - flush_pending(strm); - } - if (s.pending + 2 <= s.pending_buf_size) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - strm.adler = 0; //crc32(0L, Z_NULL, 0); - s.status = BUSY_STATE; - } - } - else { - s.status = BUSY_STATE; - } - } - //#endif - - /* Flush as much pending output as possible */ - if (s.pending !== 0) { - flush_pending(strm); - if (strm.avail_out === 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s.last_flush = -1; - return Z_OK$3; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && - flush !== Z_FINISH$3) { - return err(strm, Z_BUF_ERROR$1); - } - - /* User must not provide more input after the first FINISH: */ - if (s.status === FINISH_STATE && strm.avail_in !== 0) { - return err(strm, Z_BUF_ERROR$1); - } - - /* Start a new block or continue the current one. - */ - if (strm.avail_in !== 0 || s.lookahead !== 0 || - (flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE)) { - let bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : - (s.strategy === Z_RLE ? deflate_rle(s, flush) : - configuration_table[s.level].func(s, flush)); + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; - if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { - s.status = FINISH_STATE; - } - if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { - if (strm.avail_out === 0) { - s.last_flush = -1; - /* avoid BUF_ERROR next call, see above */ - } - return Z_OK$3; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate === BS_BLOCK_DONE) { - if (flush === Z_PARTIAL_FLUSH) { - _tr_align(s); - } - else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */ + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; - _tr_stored_block(s, 0, 0, false); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush === Z_FULL_FLUSH$1) { - /*** CLEAR_HASH(s); ***/ /* forget history */ - zero(s.head); // Fill with NIL (= 0); + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; - if (s.lookahead === 0) { - s.strstart = 0; - s.block_start = 0; - s.insert = 0; + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } } } - } - flush_pending(strm); - if (strm.avail_out === 0) { - s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK$3; - } - } - } - //Assert(strm->avail_out > 0, "bug2"); - //if (strm.avail_out <= 0) { throw new Error("bug2");} - - if (flush !== Z_FINISH$3) { return Z_OK$3; } - if (s.wrap <= 0) { return Z_STREAM_END$3; } - - /* Write the trailer */ - if (s.wrap === 2) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - put_byte(s, (strm.adler >> 16) & 0xff); - put_byte(s, (strm.adler >> 24) & 0xff); - put_byte(s, strm.total_in & 0xff); - put_byte(s, (strm.total_in >> 8) & 0xff); - put_byte(s, (strm.total_in >> 16) & 0xff); - put_byte(s, (strm.total_in >> 24) & 0xff); - } - else - { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s.wrap > 0) { s.wrap = -s.wrap; } - /* write the trailer only once! */ - return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3; - }; - - - const deflateEnd = (strm) => { - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR$2; - } - - const status = strm.state.status; - if (status !== INIT_STATE && - status !== EXTRA_STATE && - status !== NAME_STATE && - status !== COMMENT_STATE && - status !== HCRC_STATE && - status !== BUSY_STATE && - status !== FINISH_STATE - ) { - return err(strm, Z_STREAM_ERROR$2); - } - - strm.state = null; - - return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3; - }; - - - /* ========================================================================= - * Initializes the compression dictionary from the given byte - * sequence without producing any compressed output. - */ - const deflateSetDictionary = (strm, dictionary) => { - - let dictLength = dictionary.length; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR$2; - } - - const s = strm.state; - const wrap = s.wrap; - - if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { - return Z_STREAM_ERROR$2; - } - - /* when using zlib wrappers, compute Adler-32 for provided dictionary */ - if (wrap === 1) { - /* adler32(strm->adler, dictionary, dictLength); */ - strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0); - } - - s.wrap = 0; /* avoid computing Adler-32 in read_buf */ - - /* if dictionary would fill window, just replace the history */ - if (dictLength >= s.w_size) { - if (wrap === 0) { /* already empty otherwise */ - /*** CLEAR_HASH(s); ***/ - zero(s.head); // Fill with NIL (= 0); - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - /* use the tail */ - // dictionary = dictionary.slice(dictLength - s.w_size); - let tmpDict = new Uint8Array(s.w_size); - tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0); - dictionary = tmpDict; - dictLength = s.w_size; - } - /* insert dictionary into window and hash */ - const avail = strm.avail_in; - const next = strm.next_in; - const input = strm.input; - strm.avail_in = dictLength; - strm.next_in = 0; - strm.input = dictionary; - fill_window(s); - while (s.lookahead >= MIN_MATCH) { - let str = s.strstart; - let n = s.lookahead - (MIN_MATCH - 1); - do { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]); - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - - s.head[s.ins_h] = str; - str++; - } while (--n); - s.strstart = str; - s.lookahead = MIN_MATCH - 1; - fill_window(s); - } - s.strstart += s.lookahead; - s.block_start = s.strstart; - s.insert = s.lookahead; - s.lookahead = 0; - s.match_length = s.prev_length = MIN_MATCH - 1; - s.match_available = 0; - strm.next_in = next; - strm.input = input; - strm.avail_in = avail; - s.wrap = wrap; - return Z_OK$3; - }; - - var deflateInit_1 = deflateInit; - var deflateInit2_1 = deflateInit2; - var deflateReset_1 = deflateReset; - var deflateResetKeep_1 = deflateResetKeep; - var deflateSetHeader_1 = deflateSetHeader; - var deflate_2$1 = deflate$2; - var deflateEnd_1 = deflateEnd; - var deflateSetDictionary_1 = deflateSetDictionary; - var deflateInfo = 'pako deflate (from Nodeca project)'; + /* handle error breaks in while */ + if (state.mode === BAD) { break; } - /* Not implemented - module.exports.deflateBound = deflateBound; - module.exports.deflateCopy = deflateCopy; - module.exports.deflateParams = deflateParams; - module.exports.deflatePending = deflatePending; - module.exports.deflatePrime = deflatePrime; - module.exports.deflateTune = deflateTune; - */ + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } - var deflate_1$2 = { - deflateInit: deflateInit_1, - deflateInit2: deflateInit2_1, - deflateReset: deflateReset_1, - deflateResetKeep: deflateResetKeep_1, - deflateSetHeader: deflateSetHeader_1, - deflate: deflate_2$1, - deflateEnd: deflateEnd_1, - deflateSetDictionary: deflateSetDictionary_1, - deflateInfo: deflateInfo - }; + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; - const _has = (obj, key) => { - return Object.prototype.hasOwnProperty.call(obj, key); - }; + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; - var assign = function (obj /*from1, from2, from3, ...*/) { - const sources = Array.prototype.slice.call(arguments, 1); - while (sources.length) { - const source = sources.shift(); - if (!source) { continue; } + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } - if (typeof source !== 'object') { - throw new TypeError(source + 'must be non-object'); - } + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; - for (const p in source) { - if (_has(source, p)) { - obj[p] = source[p]; - } - } - } + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- - return obj; - }; + if (state.mode === TYPE$1) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; - // Join array of chunks to single array. - var flattenChunks = (chunks) => { - // calculate data length - let len = 0; + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE$1; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; - for (let i = 0, l = chunks.length; i < l; i++) { - len += chunks[i].length; - } + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; - // join chunks - const result = new Uint8Array(len); + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } + //#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } + // (!) This block is disabled in zlib defaults, + // don't enable it for binary compatibility + //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + // Trace((stderr, "inflate.c too far\n")); + // copy -= state.whave; + // if (copy > state.length) { copy = state.length; } + // if (copy > left) { copy = left; } + // left -= copy; + // state.length -= copy; + // do { + // output[put++] = 0; + // } while (--copy); + // if (state.length === 0) { state.mode = LEN; } + // break; + //#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); - for (let i = 0, pos = 0, l = chunks.length; i < l; i++) { - let chunk = chunks[i]; - result.set(chunk, pos); - pos += chunk.length; + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } } - return result; - }; - - var common = { - assign: assign, - flattenChunks: flattenChunks - }; - - // String encode/decode helpers - - - // Quick check if we can use fast array to bin string conversion - // - // - apply(Array) can fail on Android 2.2 - // - apply(Uint8Array) can fail on iOS 5.1 Safari - // - let STR_APPLY_UIA_OK = true; - - try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } - + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" - // Table with utf8 lengths (calculated by first byte of sequence) - // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, - // because max possible codepoint is 0x10ffff - const _utf8len = new Uint8Array(256); - for (let q = 0; q < 256; q++) { - _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); - } - _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- - // convert string to array (typed, when possible) - var string2buf = (str) => { - if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) { - return new TextEncoder().encode(str); + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; } - - let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; - - // count binary size - for (m_pos = 0; m_pos < str_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); - m_pos++; - } - } - buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } - - // allocate buffer - buf = new Uint8Array(buf_len); - - // convert - for (i = 0, m_pos = 0; i < buf_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); - m_pos++; - } - } - if (c < 0x80) { - /* one byte */ - buf[i++] = c; - } else if (c < 0x800) { - /* two bytes */ - buf[i++] = 0xC0 | (c >>> 6); - buf[i++] = 0x80 | (c & 0x3f); - } else if (c < 0x10000) { - /* three bytes */ - buf[i++] = 0xE0 | (c >>> 12); - buf[i++] = 0x80 | (c >>> 6 & 0x3f); - buf[i++] = 0x80 | (c & 0x3f); - } else { - /* four bytes */ - buf[i++] = 0xf0 | (c >>> 18); - buf[i++] = 0x80 | (c >>> 12 & 0x3f); - buf[i++] = 0x80 | (c >>> 6 & 0x3f); - buf[i++] = 0x80 | (c & 0x3f); - } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE$1 ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; } + return ret; + } - return buf; - }; + function inflateEnd(strm) { - // Helper - const buf2binstring = (buf, len) => { - // On Chrome, the arguments in a function call that are allowed is `65534`. - // If the length of the buffer is smaller than that, we can use this optimization, - // otherwise we will take a slower path. - if (len < 65534) { - if (buf.subarray && STR_APPLY_UIA_OK) { - return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len)); - } + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; } - let result = ''; - for (let i = 0; i < len; i++) { - result += String.fromCharCode(buf[i]); + var state = strm.state; + if (state.window) { + state.window = null; } - return result; - }; + strm.state = null; + return Z_OK; + } + function inflateGetHeader(strm, head) { + var state; - // convert array to string - var buf2string = (buf, max) => { - const len = max || buf.length; + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } - if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) { - return new TextDecoder().decode(buf.subarray(0, max)); - } + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; + } - let i, out; + function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; - // Reserve max possible length (2 words per char) - // NB: by unknown reasons, Array is significantly faster for - // String.fromCharCode.apply than Uint16Array. - const utf16buf = new Array(len * 2); + var state; + var dictid; + var ret; - for (out = 0, i = 0; i < len;) { - let c = buf[i++]; - // quick process ascii - if (c < 0x80) { utf16buf[out++] = c; continue; } + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; - let c_len = _utf8len[c]; - // skip 5 & 6 byte codes - if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } - // apply mask on first byte - c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; - // join the rest - while (c_len > 1 && i < len) { - c = (c << 6) | (buf[i++] & 0x3f); - c_len--; + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; + } - // terminated by end of string? - if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + var inflateReset_1 = inflateReset; + var inflateReset2_1 = inflateReset2; + var inflateResetKeep_1 = inflateResetKeep; + var inflateInit_1 = inflateInit; + var inflateInit2_1 = inflateInit2; + var inflate_2$1 = inflate$2; + var inflateEnd_1 = inflateEnd; + var inflateGetHeader_1 = inflateGetHeader; + var inflateSetDictionary_1 = inflateSetDictionary; + var inflateInfo = 'pako inflate (from Nodeca project)'; - if (c < 0x10000) { - utf16buf[out++] = c; - } else { - c -= 0x10000; - utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); - utf16buf[out++] = 0xdc00 | (c & 0x3ff); - } - } + /* Not implemented + exports.inflateCopy = inflateCopy; + exports.inflateGetDictionary = inflateGetDictionary; + exports.inflateMark = inflateMark; + exports.inflatePrime = inflatePrime; + exports.inflateSync = inflateSync; + exports.inflateSyncPoint = inflateSyncPoint; + exports.inflateUndermine = inflateUndermine; + */ - return buf2binstring(utf16buf, out); + var inflate_1$1 = { + inflateReset: inflateReset_1, + inflateReset2: inflateReset2_1, + inflateResetKeep: inflateResetKeep_1, + inflateInit: inflateInit_1, + inflateInit2: inflateInit2_1, + inflate: inflate_2$1, + inflateEnd: inflateEnd_1, + inflateGetHeader: inflateGetHeader_1, + inflateSetDictionary: inflateSetDictionary_1, + inflateInfo: inflateInfo }; - - // Calculate max possible position in utf8 buffer, - // that will not break sequence. If that's not possible - // - (very small limits) return max size as is. + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // - // buf[] - utf8 bytes array - // max - length limit (mandatory); - var utf8border = (buf, max) => { + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. - max = max || buf.length; - if (max > buf.length) { max = buf.length; } + var constants$1 = { - // go back from last position, until start of sequence found - let pos = max - 1; - while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, - // Very small and broken sequence, - // return max, because we should return something anyway. - if (pos < 0) { return max; } + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, - // If we came to start of buffer - that means buffer is too small, - // return max too. - if (pos === 0) { return max; } + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, - return (pos + _utf8len[buf[pos]] > max) ? pos : max; - }; - var strings = { - string2buf: string2buf, - buf2string: buf2string, - utf8border: utf8border + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type }; // (C) 1995-2013 Jean-loup Gailly and Mark Adler @@ -16610,98 +9066,98 @@ var serviceContext = (function (vue) { // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. - function ZStream() { - /* next input byte */ - this.input = null; // JS specific, because we have no pointers - this.next_in = 0; - /* number of bytes available at input */ - this.avail_in = 0; - /* total number of input bytes read so far */ - this.total_in = 0; - /* next output byte should be put there */ - this.output = null; // JS specific, because we have no pointers - this.next_out = 0; - /* remaining free space at output */ - this.avail_out = 0; - /* total number of bytes output so far */ - this.total_out = 0; - /* last error message, NULL if no error */ - this.msg = ''/*Z_NULL*/; - /* not visible by applications */ - this.state = null; - /* best guess about the data type: binary or text */ - this.data_type = 2/*Z_UNKNOWN*/; - /* adler32 value of the uncompressed data */ - this.adler = 0; - } + function GZheader$1() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // - var zstream = ZStream; + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; + } - const toString$1 = Object.prototype.toString; + var gzheader = GZheader$1; - /* Public constants ==========================================================*/ - /* ===========================================================================*/ + var zlib_inflate = inflate_1$1; - const { - Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH: Z_FINISH$2, - Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2, - Z_DEFAULT_COMPRESSION, - Z_DEFAULT_STRATEGY, - Z_DEFLATED: Z_DEFLATED$1 - } = constants$2; + var constants = constants$1; - /* ===========================================================================*/ + var GZheader = gzheader; + var toString = Object.prototype.toString; /** - * class Deflate + * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[deflate]], - * [[deflateRaw]] and [[gzip]]. + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. **/ /* internal - * Deflate.chunks -> Array + * inflate.chunks -> Array * - * Chunks of output data, if [[Deflate#onData]] not overridden. + * Chunks of output data, if [[Inflate#onData]] not overridden. **/ /** - * Deflate.result -> Uint8Array + * Inflate.result -> Uint8Array|Array|String * - * Compressed result, generated by default [[Deflate#onData]] - * and [[Deflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Deflate#push]] with `Z_FINISH` / `true` param). + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). **/ /** - * Deflate.err -> Number + * Inflate.err -> Number * - * Error code after deflate finished. 0 (Z_OK) on success. - * You will not need it in real life, because deflate errors - * are possible only on wrong options or bad `onData` / `onEnd` - * custom handlers. + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. **/ /** - * Deflate.msg -> String + * Inflate.msg -> String * - * Error message, if [[Deflate.err]] != 0 + * Error message, if [[Inflate.err]] != 0 **/ /** - * new Deflate(options) - * - options (Object): zlib deflate options. + * new Inflate(options) + * - options (Object): zlib inflate options. * - * Creates new deflator instance with specified params. Throws exception + * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * - * - `level` * - `windowBits` - * - `memLevel` - * - `strategy` * - `dictionary` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) @@ -16710,52 +9166,63 @@ var serviceContext = (function (vue) { * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw deflate - * - `gzip` (Boolean) - create gzip wrapper - * - `header` (Object) - custom header for gzip - * - `text` (Boolean) - true if compressed data believed to be text - * - `time` (Number) - modification time, unix timestamp - * - `os` (Number) - operation system code - * - `extra` (Array) - array of bytes with extra data (max 65536) - * - `name` (String) - file name (binary string) - * - `comment` (String) - comment (binary string) - * - `hcrc` (Boolean) - true if header crc should be added + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. * * ##### Example: * * ```javascript - * const pako = require('pako') - * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * - * const deflate = new pako.Deflate({ level: 3}); + * var inflate = new pako.Inflate({ level: 3}); * - * deflate.push(chunk1, false); - * deflate.push(chunk2, true); // true -> last chunk + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk * - * if (deflate.err) { throw new Error(deflate.err); } + * if (inflate.err) { throw new Error(inflate.err); } * - * console.log(deflate.result); + * console.log(inflate.result); * ``` **/ - function Deflate$1(options) { - this.options = common.assign({ - level: Z_DEFAULT_COMPRESSION, - method: Z_DEFLATED$1, + function Inflate(options) { + if (!(this instanceof Inflate)) return new Inflate(options); + + this.options = require$$0.assign({ chunkSize: 16384, - windowBits: 15, - memLevel: 8, - strategy: Z_DEFAULT_STRATEGY + windowBits: 0, + to: '' }, options || {}); - let opt = this.options; + var opt = this.options; - if (opt.raw && (opt.windowBits > 0)) { + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } } - else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { - opt.windowBits += 16; + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } } this.err = 0; // error code, if happens (0 = Z_OK) @@ -16763,61 +9230,58 @@ var serviceContext = (function (vue) { this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data - this.strm = new zstream(); + this.strm = new ZStream(); this.strm.avail_out = 0; - let status = deflate_1$2.deflateInit2( + var status = zlib_inflate.inflateInit2( this.strm, - opt.level, - opt.method, - opt.windowBits, - opt.memLevel, - opt.strategy + opt.windowBits ); - if (status !== Z_OK$2) { - throw new Error(messages[status]); + if (status !== constants.Z_OK) { + throw new Error(msg[status]); } - if (opt.header) { - deflate_1$2.deflateSetHeader(this.strm, opt.header); - } + this.header = new GZheader(); + + zlib_inflate.inflateGetHeader(this.strm, this.header); + // Setup dictionary if (opt.dictionary) { - let dict; // Convert data if needed if (typeof opt.dictionary === 'string') { - // If we need to compress text, change encoding to utf8. - dict = strings.string2buf(opt.dictionary); - } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') { - dict = new Uint8Array(opt.dictionary); - } else { - dict = opt.dictionary; + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + opt.dictionary = new Uint8Array(opt.dictionary); } - - status = deflate_1$2.deflateSetDictionary(this.strm, dict); - - if (status !== Z_OK$2) { - throw new Error(messages[status]); + if (opt.raw) { //In raw mode we need to set the dictionary early + status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== constants.Z_OK) { + throw new Error(msg[status]); + } } - - this._dict_set = true; } } /** - * Deflate#push(data[, flush_mode]) -> Boolean - * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be - * converted to utf8 byte sequence. - * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. * - * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with - * new compressed chunks. Returns `true` on success. The last data block must - * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending - * buffers and call [[Deflate#onEnd]]. + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. * - * On fail call [[Deflate#onEnd]] with error code and return false. + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * @@ -16827,21 +9291,25 @@ var serviceContext = (function (vue) { * push(chunk, true); // push last chunk * ``` **/ - Deflate$1.prototype.push = function (data, flush_mode) { - const strm = this.strm; - const chunkSize = this.options.chunkSize; - let status, _flush_mode; + Inflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; - if (this.ended) { return false; } + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; - if (flush_mode === ~~flush_mode) _flush_mode = flush_mode; - else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1; + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? constants.Z_FINISH : constants.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { - // If we need to compress text, change encoding to utf8. - strm.input = strings.string2buf(data); - } else if (toString$1.call(data) === '[object ArrayBuffer]') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; @@ -16850,47 +9318,83 @@ var serviceContext = (function (vue) { strm.next_in = 0; strm.avail_in = strm.input.length; - for (;;) { + do { if (strm.avail_out === 0) { - strm.output = new Uint8Array(chunkSize); + strm.output = new require$$0.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } - // Make sure avail_out > 6 to avoid repeating markers - if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) { - this.onData(strm.output.subarray(0, strm.next_out)); - strm.avail_out = 0; - continue; + status = zlib_inflate.inflate(strm, constants.Z_NO_FLUSH); /* no bad return value */ + + if (status === constants.Z_NEED_DICT && dictionary) { + status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); } - status = deflate_1$2.deflate(strm, _flush_mode); + if (status === constants.Z_BUF_ERROR && allowBufError === true) { + status = constants.Z_OK; + allowBufError = false; + } - // Ended => flush and finish - if (status === Z_STREAM_END$2) { - if (strm.next_out > 0) { - this.onData(strm.output.subarray(0, strm.next_out)); - } - status = deflate_1$2.deflateEnd(this.strm); + if (status !== constants.Z_STREAM_END && status !== constants.Z_OK) { this.onEnd(status); this.ended = true; - return status === Z_OK$2; + return false; } - // Flush if out buffer full - if (strm.avail_out === 0) { - this.onData(strm.output); - continue; + if (strm.next_out) { + if (strm.avail_out === 0 || status === constants.Z_STREAM_END || (strm.avail_in === 0 && (_mode === constants.Z_FINISH || _mode === constants.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { require$$0.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(require$$0.shrinkBuf(strm.output, strm.next_out)); + } + } } - // Flush if requested and has data - if (_flush_mode > 0 && strm.next_out > 0) { - this.onData(strm.output.subarray(0, strm.next_out)); - strm.avail_out = 0; - continue; + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; } - if (strm.avail_in === 0) break; + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== constants.Z_STREAM_END); + + if (status === constants.Z_STREAM_END) { + _mode = constants.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === constants.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === constants.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === constants.Z_SYNC_FLUSH) { + this.onEnd(constants.Z_OK); + strm.avail_out = 0; + return true; } return true; @@ -16898,30 +9402,39 @@ var serviceContext = (function (vue) { /** - * Deflate#onData(chunk) -> Void - * - chunk (Uint8Array): output data. + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ - Deflate$1.prototype.onData = function (chunk) { + Inflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** - * Deflate#onEnd(status) -> Void - * - status (Number): deflate status. 0 (Z_OK) on success, + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * - * Called once after you tell deflate that the input stream is - * complete (Z_FINISH). By default - join collected chunks, + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ - Deflate$1.prototype.onEnd = function (status) { + Inflate.prototype.onEnd = function (status) { // On success - join - if (status === Z_OK$2) { - this.result = common.flattenChunks(this.chunks); + if (status === constants.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 aligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = require$$0.flattenChunks(this.chunks); + } } this.chunks = []; this.err = status; @@ -16930,2850 +9443,10453 @@ var serviceContext = (function (vue) { /** - * deflate(data[, options]) -> Uint8Array - * - data (Uint8Array|String): input data to compress. - * - options (Object): zlib deflate options. + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. * - * Compress `data` with deflate algorithm and `options`. + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. * * Supported options are: * - * - level * - windowBits - * - memLevel - * - strategy - * - dictionary * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. + * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * * * ##### Example: * * ```javascript - * const pako = require('pako') - * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]); + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; * - * console.log(pako.deflate(data)); + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } * ``` **/ - function deflate$1(input, options) { - const deflator = new Deflate$1(options); + function inflate$1(input, options) { + var inflator = new Inflate(options); - deflator.push(input, true); + inflator.push(input, true); // That will never happens, if you don't cheat with options :) - if (deflator.err) { throw deflator.msg || messages[deflator.err]; } + if (inflator.err) { throw inflator.msg || msg[inflator.err]; } - return deflator.result; + return inflator.result; } /** - * deflateRaw(data[, options]) -> Uint8Array - * - data (Uint8Array|String): input data to compress. - * - options (Object): zlib deflate options. + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. * - * The same as [[deflate]], but creates raw data, without wrapper + * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ - function deflateRaw$1(input, options) { + function inflateRaw(input, options) { options = options || {}; options.raw = true; - return deflate$1(input, options); + return inflate$1(input, options); } /** - * gzip(data[, options]) -> Uint8Array - * - data (Uint8Array|String): input data to compress. - * - options (Object): zlib deflate options. + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. * - * The same as [[deflate]], but create gzip wrapper instead of - * deflate one. + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. **/ - function gzip$1(input, options) { - options = options || {}; - options.gzip = true; - return deflate$1(input, options); - } - var Deflate_1$1 = Deflate$1; - var deflate_2 = deflate$1; - var deflateRaw_1$1 = deflateRaw$1; - var gzip_1$1 = gzip$1; - var constants$1 = constants$2; + var Inflate_1 = Inflate; + var inflate_2 = inflate$1; + var inflateRaw_1 = inflateRaw; + var ungzip = inflate$1; - var deflate_1$1 = { - Deflate: Deflate_1$1, - deflate: deflate_2, - deflateRaw: deflateRaw_1$1, - gzip: gzip_1$1, - constants: constants$1 + var inflate_1 = { + Inflate: Inflate_1, + inflate: inflate_2, + inflateRaw: inflateRaw_1, + ungzip: ungzip }; - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. + var deflate = deflate_1; - // See state defs from inflate.js - const BAD$1 = 30; /* got a data error -- remain here until reset */ - const TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */ + var inflate = inflate_1; - /* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. + var assign = require$$0.assign; - Entry assumptions: - state.mode === LEN - strm.avail_in >= 6 - strm.avail_out >= 258 - start >= strm.avail_out - state.bits < 8 - On return, state.mode is one of: - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - Notes: + var pako = {}; - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm.avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. + assign(pako, deflate, inflate, constants); - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm.avail_out >= 258 for each loop to avoid checking for - output space. - */ - var inffast = function inflate_fast(strm, start) { - let _in; /* local strm.input */ - let last; /* have enough input while in < last */ - let _out; /* local strm.output */ - let beg; /* inflate()'s initial strm.output */ - let end; /* while out < end, enough space available */ - //#ifdef INFLATE_STRICT - let dmax; /* maximum distance from zlib header */ - //#endif - let wsize; /* window size or zero if not using window */ - let whave; /* valid bytes in the window */ - let wnext; /* window write index */ - // Use `s_window` instead `window`, avoid conflict with instrumentation tools - let s_window; /* allocated sliding window, if wsize != 0 */ - let hold; /* local strm.hold */ - let bits; /* local strm.bits */ - let lcode; /* local strm.lencode */ - let dcode; /* local strm.distcode */ - let lmask; /* mask for first level of length codes */ - let dmask; /* mask for first level of distance codes */ - let here; /* retrieved table entry */ - let op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - let len; /* match length, unused bytes */ - let dist; /* match distance */ - let from; /* where to copy match from */ - let from_source; + var pako_1 = pako; + const TEMP_PATH$1 = ''; - let input, output; // JS specific, because we have no pointers + const API_UPX2PX = 'upx2px'; + const Upx2pxProtocol = [ + { + name: 'upx', + type: [Number, String], + required: true, + }, + ]; - /* copy state to local variables */ - const state = strm.state; - //here = state.here; - _in = strm.next_in; - input = strm.input; - last = _in + (strm.avail_in - 5); - _out = strm.next_out; - output = strm.output; - beg = _out - (start - strm.avail_out); - end = _out + (strm.avail_out - 257); - //#ifdef INFLATE_STRICT - dmax = state.dmax; - //#endif - wsize = state.wsize; - whave = state.whave; - wnext = state.wnext; - s_window = state.window; - hold = state.hold; - bits = state.bits; - lcode = state.lencode; - dcode = state.distcode; - lmask = (1 << state.lenbits) - 1; - dmask = (1 << state.distbits) - 1; + const EPS = 1e-4; + const BASE_DEVICE_WIDTH = 750; + let isIOS$1 = false; + let deviceWidth = 0; + let deviceDPR = 0; + function checkDeviceWidth() { + const { platform, pixelRatio, windowWidth } = getBaseSystemInfo(); + deviceWidth = windowWidth; + deviceDPR = pixelRatio; + isIOS$1 = platform === 'ios'; + } + function checkValue(value, defaultValue) { + const newValue = Number(value); + return isNaN(newValue) ? defaultValue : newValue; + } + const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => { + if (deviceWidth === 0) { + checkDeviceWidth(); + } + number = Number(number); + if (number === 0) { + return 0; + } + let width = newDeviceWidth || deviceWidth; + { + const config = __uniConfig.globalStyle || {}; + // ignore rpxCalcIncludeWidth + const maxWidth = checkValue(config.rpxCalcMaxDeviceWidth, 960); + const baseWidth = checkValue(config.rpxCalcBaseDeviceWidth, 375); + width = width <= maxWidth ? width : baseWidth; + } + let result = (number / BASE_DEVICE_WIDTH) * width; + if (result < 0) { + result = -result; + } + result = Math.floor(result + EPS); + if (result === 0) { + if (deviceDPR === 1 || !isIOS$1) { + result = 1; + } + else { + result = 0.5; + } + } + return number < 0 ? -result : result; + }, Upx2pxProtocol); + const API_ADD_INTERCEPTOR = 'addInterceptor'; + const API_REMOVE_INTERCEPTOR = 'removeInterceptor'; + const AddInterceptorProtocol = [ + { + name: 'method', + type: [String, Object], + required: true, + }, + ]; + const RemoveInterceptorProtocol = AddInterceptorProtocol; - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ + function mergeInterceptorHook(interceptors, interceptor) { + Object.keys(interceptor).forEach((hook) => { + if (isFunction(interceptor[hook])) { + interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]); + } + }); + } + function removeInterceptorHook(interceptors, interceptor) { + if (!interceptors || !interceptor) { + return; + } + Object.keys(interceptor).forEach((hook) => { + if (isFunction(interceptor[hook])) { + removeHook(interceptors[hook], interceptor[hook]); + } + }); + } + function mergeHook(parentVal, childVal) { + const res = childVal + ? parentVal + ? parentVal.concat(childVal) + : isArray$1(childVal) + ? childVal + : [childVal] + : parentVal; + return res ? dedupeHooks(res) : res; + } + function dedupeHooks(hooks) { + const res = []; + for (let i = 0; i < hooks.length; i++) { + if (res.indexOf(hooks[i]) === -1) { + res.push(hooks[i]); + } + } + return res; + } + function removeHook(hooks, hook) { + if (!hooks) { + return; + } + const index = hooks.indexOf(hook); + if (index !== -1) { + hooks.splice(index, 1); + } + } + const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => { + if (typeof method === 'string' && isPlainObject(interceptor)) { + mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); + } + else if (isPlainObject(method)) { + mergeInterceptorHook(globalInterceptors, method); + } + }, AddInterceptorProtocol); + const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => { + if (typeof method === 'string') { + if (isPlainObject(interceptor)) { + removeInterceptorHook(scopedInterceptors[method], interceptor); + } + else { + delete scopedInterceptors[method]; + } + } + else if (isPlainObject(method)) { + removeInterceptorHook(globalInterceptors, method); + } + }, RemoveInterceptorProtocol); + const interceptors = {}; + + const API_ON = '$on'; + const OnProtocol = [ + { + name: 'event', + type: String, + required: true, + }, + { + name: 'callback', + type: Function, + required: true, + }, + ]; + const API_ONCE = '$once'; + const OnceProtocol = OnProtocol; + const API_OFF = '$off'; + const OffProtocol = [ + { + name: 'event', + type: [String, Array], + }, + { + name: 'callback', + type: Function, + }, + ]; + const API_EMIT = '$emit'; + const EmitProtocol = [ + { + name: 'event', + type: String, + required: true, + }, + ]; - top: - do { - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } + const emitter = new Emitter(); + const $on = defineSyncApi(API_ON, (name, callback) => { + emitter.on(name, callback); + return () => emitter.off(name, callback); + }, OnProtocol); + const $once = defineSyncApi(API_ONCE, (name, callback) => { + emitter.once(name, callback); + return () => emitter.off(name, callback); + }, OnceProtocol); + const $off = defineSyncApi(API_OFF, (name, callback) => { + if (!name) { + emitter.e = {}; + return; + } + if (!Array.isArray(name)) + name = [name]; + name.forEach((n) => emitter.off(n, callback)); + }, OffProtocol); + const $emit = defineSyncApi(API_EMIT, (name, ...args) => { + emitter.emit(name, ...args); + }, EmitProtocol); - here = lcode[hold & lmask]; + const validator = [ + { + name: 'id', + type: String, + required: true, + }, + ]; + /* export const API_CREATE_AUDIO_CONTEXT = 'createAudioContext' + export type API_TYPE_CREATE_AUDIO_CONTEXT = typeof uni.createAudioContext + export const CreateAudioContextProtocol = validator */ + const API_CREATE_VIDEO_CONTEXT = 'createVideoContext'; + const API_CREATE_MAP_CONTEXT = 'createMapContext'; + const CreateMapContextProtocol = validator; + const API_CREATE_CANVAS_CONTEXT = 'createCanvasContext'; + const CreateCanvasContextProtocol = [ + { + name: 'canvasId', + type: String, + required: true, + }, + { + name: 'componentInstance', + type: Object, + }, + ]; + const API_CREATE_INNER_AUDIO_CONTEXT = 'createInnerAudioContext'; + const API_CREATE_LIVE_PUSHER_CONTEXT = 'createLivePusherContext'; + const CreateLivePusherContextProtocol = validator.concat({ + name: 'componentInstance', + type: Object, + }); - dolen: - for (;;) { // Goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = (here >>> 16) & 0xff/*here.op*/; - if (op === 0) { /* literal */ - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - output[_out++] = here & 0xffff/*here.val*/; - } - else if (op & 16) { /* length base */ - len = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - len += hold & ((1 << op) - 1); - hold >>>= op; - bits -= op; - } - //Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - here = dcode[hold & dmask]; + const RATES = [0.5, 0.8, 1.0, 1.25, 1.5, 2.0]; + class VideoContext { + constructor(id, pageId) { + this.id = id; + this.pageId = pageId; + } + play() { + operateVideoPlayer(this.id, this.pageId, 'play'); + } + pause() { + operateVideoPlayer(this.id, this.pageId, 'pause'); + } + stop() { + operateVideoPlayer(this.id, this.pageId, 'stop'); + } + seek(position) { + operateVideoPlayer(this.id, this.pageId, 'seek', { + position, + }); + } + sendDanmu(args) { + operateVideoPlayer(this.id, this.pageId, 'sendDanmu', args); + } + playbackRate(rate) { + if (!~RATES.indexOf(rate)) { + rate = 1.0; + } + operateVideoPlayer(this.id, this.pageId, 'playbackRate', { + rate, + }); + } + requestFullScreen(args = {}) { + operateVideoPlayer(this.id, this.pageId, 'requestFullScreen', args); + } + exitFullScreen() { + operateVideoPlayer(this.id, this.pageId, 'exitFullScreen'); + } + showStatusBar() { + operateVideoPlayer(this.id, this.pageId, 'showStatusBar'); + } + hideStatusBar() { + operateVideoPlayer(this.id, this.pageId, 'hideStatusBar'); + } + } + const createVideoContext = defineSyncApi(API_CREATE_VIDEO_CONTEXT, (id, context) => { + if (context) { + return new VideoContext(id, getPageIdByVm(context)); + } + return new VideoContext(id, getPageIdByVm(getCurrentPageVm())); + }); - dodist: - for (;;) { // goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = (here >>> 16) & 0xff/*here.op*/; + const operateMapCallback = (options, res) => { + const errMsg = res.errMsg || ''; + if (new RegExp('\\:\\s*fail').test(errMsg)) { + options.fail && options.fail(res); + } + else { + options.success && options.success(res); + } + options.complete && options.complete(res); + }; + const operateMapWrap = (id, pageId, type, options) => { + operateMap(id, pageId, type, options, (res) => { + options && operateMapCallback(options, res); + }); + }; + class MapContext { + constructor(id, pageId) { + this.id = id; + this.pageId = pageId; + } + getCenterLocation(options) { + operateMapWrap(this.id, this.pageId, 'getCenterLocation', options); + } + moveToLocation(options) { + operateMapWrap(this.id, this.pageId, 'moveToLocation', options); + } + getScale(options) { + operateMapWrap(this.id, this.pageId, 'getScale', options); + } + getRegion(options) { + operateMapWrap(this.id, this.pageId, 'getRegion', options); + } + includePoints(options) { + operateMapWrap(this.id, this.pageId, 'includePoints', options); + } + translateMarker(options) { + operateMapWrap(this.id, this.pageId, 'translateMarker', options); + } + $getAppMap() { + { + return plus.maps.getMapById(this.pageId + '-map-' + this.id); + } + } + addCustomLayer() { } + removeCustomLayer() { } + addGroundOverlay() { } + removeGroundOverlay() { } + updateGroundOverlay() { } + initMarkerCluster() { } + addMarkers() { } + removeMarkers() { } + moveAlong() { } + openMapApp() { } + } + const createMapContext = defineSyncApi(API_CREATE_MAP_CONTEXT, (id, context) => { + if (context) { + return new MapContext(id, getPageIdByVm(context)); + } + return new MapContext(id, getPageIdByVm(getCurrentPageVm())); + }, CreateMapContextProtocol); - if (op & 16) { /* distance base */ - dist = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - } - dist += hold & ((1 << op) - 1); - //#ifdef INFLATE_STRICT - if (dist > dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD$1; - break top; - } - //#endif - hold >>>= op; - bits -= op; - //Tracevv((stderr, "inflate: distance %u\n", dist)); - op = _out - beg; /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD$1; - break top; - } + function getInt(name, defaultValue) { + return function (value, params) { + if (value) { + params[name] = Math.round(value); + } + else if (typeof defaultValue !== 'undefined') { + params[name] = defaultValue; + } + }; + } + const formatWidth = getInt('width'); + const formatHeight = getInt('height'); + //#region getImageDataOptions + const API_CANVAS_GET_IMAGE_DATA = 'canvasGetImageData'; + const CanvasGetImageDataOptions = { + formatArgs: { + x: getInt('x'), + y: getInt('y'), + width: formatWidth, + height: formatHeight, + }, + }; + const CanvasGetImageDataProtocol = { + canvasId: { + type: String, + required: true, + }, + x: { + type: Number, + required: true, + }, + y: { + type: Number, + required: true, + }, + width: { + type: Number, + required: true, + }, + height: { + type: Number, + required: true, + }, + }; + //#endregion + //#region putImageData + const API_CANVAS_PUT_IMAGE_DATA = 'canvasPutImageData'; + const CanvasPutImageDataOptions = CanvasGetImageDataOptions; + const CanvasPutImageDataProtocol = + /*#__PURE__*/ extend({ + data: { + type: Uint8ClampedArray, + required: true, + }, + }, CanvasGetImageDataProtocol, { + height: { + type: Number, + }, + }); + //#endregion + //#region toTempFilePath + const fileTypes = { + PNG: 'png', + JPG: 'jpg', + JPEG: 'jpg', + }; + const API_CANVAS_TO_TEMP_FILE_PATH = 'canvasToTempFilePath'; + const CanvasToTempFilePathOptions = { + formatArgs: { + x: getInt('x', 0), + y: getInt('y', 0), + width: formatWidth, + height: formatHeight, + destWidth: getInt('destWidth'), + destHeight: getInt('destHeight'), + fileType(value, params) { + value = (value || '').toUpperCase(); + let type = fileTypes[value]; + if (!type) { + type = fileTypes.PNG; + } + params.fileType = type; + }, + quality(value, params) { + params.quality = value && value > 0 && value < 1 ? value : 1; + }, + }, + }; + const CanvasToTempFilePathProtocol = { + x: Number, + y: Number, + width: Number, + height: Number, + destWidth: Number, + destHeight: Number, + canvasId: { + type: String, + required: true, + }, + fileType: String, + quality: Number, + }; - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - // if (len <= op - whave) { - // do { - // output[_out++] = 0; - // } while (--len); - // continue top; - // } - // len -= op - whave; - // do { - // output[_out++] = 0; - // } while (--op > whave); - // if (op === 0) { - // from = _out - dist; - // do { - // output[_out++] = output[from++]; - // } while (--len); - // continue top; - // } - //#endif - } - from = 0; // window index - from_source = s_window; - if (wnext === 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - else if (wnext < op) { /* wrap around window */ - from += wsize + wnext - op; - op -= wnext; - if (op < len) { /* some from end of window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = 0; - if (wnext < len) { /* some from start of window */ - op = wnext; - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - } - else { /* contiguous in window */ - from += wnext - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - while (len > 2) { - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - len -= 3; - } - if (len) { - output[_out++] = from_source[from++]; - if (len > 1) { - output[_out++] = from_source[from++]; - } - } - } - else { - from = _out - dist; /* copy direct from output */ - do { /* minimum length is three */ - output[_out++] = output[from++]; - output[_out++] = output[from++]; - output[_out++] = output[from++]; - len -= 3; - } while (len > 2); - if (len) { - output[_out++] = output[from++]; - if (len > 1) { - output[_out++] = output[from++]; - } - } - } - } - else if ((op & 64) === 0) { /* 2nd level distance code */ - here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; - continue dodist; - } - else { - strm.msg = 'invalid distance code'; - state.mode = BAD$1; - break top; - } + //#region import + //#endregion + //#region UniServiceJSBridge + function operateCanvas(canvasId, pageId, type, data, callback) { + UniServiceJSBridge.invokeViewMethod(`canvas.${canvasId}`, { + type, + data, + }, pageId, (data) => { + if (callback) + callback(data); + }); + } + //#endregion + //#region methods + var methods1 = ['scale', 'rotate', 'translate', 'setTransform', 'transform']; + var methods2 = [ + 'drawImage', + 'fillText', + 'fill', + 'stroke', + 'fillRect', + 'strokeRect', + 'clearRect', + 'strokeText', + ]; + var methods3 = [ + 'setFillStyle', + 'setTextAlign', + 'setStrokeStyle', + 'setGlobalAlpha', + 'setShadow', + 'setFontSize', + 'setLineCap', + 'setLineJoin', + 'setLineWidth', + 'setMiterLimit', + 'setTextBaseline', + 'setLineDash', + ]; + function measureText(text, font) { + const canvas = document.createElement('canvas'); + const c2d = canvas.getContext('2d'); + c2d.font = font; + return c2d.measureText(text).width || 0; + } + //#endregion + //#region checkColor + const predefinedColor = { + aliceblue: '#f0f8ff', + antiquewhite: '#faebd7', + aqua: '#00ffff', + aquamarine: '#7fffd4', + azure: '#f0ffff', + beige: '#f5f5dc', + bisque: '#ffe4c4', + black: '#000000', + blanchedalmond: '#ffebcd', + blue: '#0000ff', + blueviolet: '#8a2be2', + brown: '#a52a2a', + burlywood: '#deb887', + cadetblue: '#5f9ea0', + chartreuse: '#7fff00', + chocolate: '#d2691e', + coral: '#ff7f50', + cornflowerblue: '#6495ed', + cornsilk: '#fff8dc', + crimson: '#dc143c', + cyan: '#00ffff', + darkblue: '#00008b', + darkcyan: '#008b8b', + darkgoldenrod: '#b8860b', + darkgray: '#a9a9a9', + darkgrey: '#a9a9a9', + darkgreen: '#006400', + darkkhaki: '#bdb76b', + darkmagenta: '#8b008b', + darkolivegreen: '#556b2f', + darkorange: '#ff8c00', + darkorchid: '#9932cc', + darkred: '#8b0000', + darksalmon: '#e9967a', + darkseagreen: '#8fbc8f', + darkslateblue: '#483d8b', + darkslategray: '#2f4f4f', + darkslategrey: '#2f4f4f', + darkturquoise: '#00ced1', + darkviolet: '#9400d3', + deeppink: '#ff1493', + deepskyblue: '#00bfff', + dimgray: '#696969', + dimgrey: '#696969', + dodgerblue: '#1e90ff', + firebrick: '#b22222', + floralwhite: '#fffaf0', + forestgreen: '#228b22', + fuchsia: '#ff00ff', + gainsboro: '#dcdcdc', + ghostwhite: '#f8f8ff', + gold: '#ffd700', + goldenrod: '#daa520', + gray: '#808080', + grey: '#808080', + green: '#008000', + greenyellow: '#adff2f', + honeydew: '#f0fff0', + hotpink: '#ff69b4', + indianred: '#cd5c5c', + indigo: '#4b0082', + ivory: '#fffff0', + khaki: '#f0e68c', + lavender: '#e6e6fa', + lavenderblush: '#fff0f5', + lawngreen: '#7cfc00', + lemonchiffon: '#fffacd', + lightblue: '#add8e6', + lightcoral: '#f08080', + lightcyan: '#e0ffff', + lightgoldenrodyellow: '#fafad2', + lightgray: '#d3d3d3', + lightgrey: '#d3d3d3', + lightgreen: '#90ee90', + lightpink: '#ffb6c1', + lightsalmon: '#ffa07a', + lightseagreen: '#20b2aa', + lightskyblue: '#87cefa', + lightslategray: '#778899', + lightslategrey: '#778899', + lightsteelblue: '#b0c4de', + lightyellow: '#ffffe0', + lime: '#00ff00', + limegreen: '#32cd32', + linen: '#faf0e6', + magenta: '#ff00ff', + maroon: '#800000', + mediumaquamarine: '#66cdaa', + mediumblue: '#0000cd', + mediumorchid: '#ba55d3', + mediumpurple: '#9370db', + mediumseagreen: '#3cb371', + mediumslateblue: '#7b68ee', + mediumspringgreen: '#00fa9a', + mediumturquoise: '#48d1cc', + mediumvioletred: '#c71585', + midnightblue: '#191970', + mintcream: '#f5fffa', + mistyrose: '#ffe4e1', + moccasin: '#ffe4b5', + navajowhite: '#ffdead', + navy: '#000080', + oldlace: '#fdf5e6', + olive: '#808000', + olivedrab: '#6b8e23', + orange: '#ffa500', + orangered: '#ff4500', + orchid: '#da70d6', + palegoldenrod: '#eee8aa', + palegreen: '#98fb98', + paleturquoise: '#afeeee', + palevioletred: '#db7093', + papayawhip: '#ffefd5', + peachpuff: '#ffdab9', + peru: '#cd853f', + pink: '#ffc0cb', + plum: '#dda0dd', + powderblue: '#b0e0e6', + purple: '#800080', + rebeccapurple: '#663399', + red: '#ff0000', + rosybrown: '#bc8f8f', + royalblue: '#4169e1', + saddlebrown: '#8b4513', + salmon: '#fa8072', + sandybrown: '#f4a460', + seagreen: '#2e8b57', + seashell: '#fff5ee', + sienna: '#a0522d', + silver: '#c0c0c0', + skyblue: '#87ceeb', + slateblue: '#6a5acd', + slategray: '#708090', + slategrey: '#708090', + snow: '#fffafa', + springgreen: '#00ff7f', + steelblue: '#4682b4', + tan: '#d2b48c', + teal: '#008080', + thistle: '#d8bfd8', + tomato: '#ff6347', + turquoise: '#40e0d0', + violet: '#ee82ee', + wheat: '#f5deb3', + white: '#ffffff', + whitesmoke: '#f5f5f5', + yellow: '#ffff00', + yellowgreen: '#9acd32', + transparent: '#00000000', + }; + function checkColor(e) { + // 其他开发者适配的echarts会传入一个undefined到这里 + e = e || '#000000'; + var t = null; + if ((t = /^#([0-9|A-F|a-f]{6})$/.exec(e)) != null) { + const n = parseInt(t[1].slice(0, 2), 16); + const o = parseInt(t[1].slice(2, 4), 16); + const r = parseInt(t[1].slice(4), 16); + return [n, o, r, 255]; + } + if ((t = /^#([0-9|A-F|a-f]{3})$/.exec(e)) != null) { + let n = t[1].slice(0, 1); + let o = t[1].slice(1, 2); + let r = t[1].slice(2, 3); + n = parseInt(n + n, 16); + o = parseInt(o + o, 16); + r = parseInt(r + r, 16); + return [n, o, r, 255]; + } + if ((t = /^rgb\((.+)\)$/.exec(e)) != null) { + return t[1] + .split(',') + .map(function (e) { + return Math.min(255, parseInt(e.trim())); + }) + .concat(255); + } + if ((t = /^rgba\((.+)\)$/.exec(e)) != null) { + return t[1].split(',').map(function (e, t) { + return t === 3 + ? Math.floor(255 * parseFloat(e.trim())) + : Math.min(255, parseInt(e.trim())); + }); + } + var i = e.toLowerCase(); + if (hasOwn$1(predefinedColor, i)) { + t = /^#([0-9|A-F|a-f]{6,8})$/.exec(predefinedColor[i]); + const n = parseInt(t[1].slice(0, 2), 16); + const o = parseInt(t[1].slice(2, 4), 16); + const r = parseInt(t[1].slice(4, 6), 16); + let a = parseInt(t[1].slice(6, 8), 16); + a = a >= 0 ? a : 255; + return [n, o, r, a]; + } + console.error('unsupported color:' + e); + return [0, 0, 0, 255]; + } + //#endregion + //#region Class + class CanvasGradient { + constructor(type, data) { + this.type = type; + this.data = data; + this.colorStop = []; + } + addColorStop(position, color) { + this.colorStop.push([position, checkColor(color)]); + } + } + class Pattern { + constructor(image, repetition) { + this.type = 'pattern'; + this.data = image; + this.colorStop = repetition; + } + } + class TextMetrics { + constructor(width) { + this.width = width; + } + } + class CanvasContext { + constructor(id, pageId) { + this.id = id; + this.pageId = pageId; + this.actions = []; + this.path = []; + this.subpath = []; + // this.currentTransform = [] + // this.currentStepAnimates = [] + this.drawingState = []; + this.state = { + lineDash: [0, 0], + shadowOffsetX: 0, + shadowOffsetY: 0, + shadowBlur: 0, + shadowColor: [0, 0, 0, 0], + font: '10px sans-serif', + fontSize: 10, + fontWeight: 'normal', + fontStyle: 'normal', + fontFamily: 'sans-serif', + }; + } + draw(reserve = false, callback) { + var actions = [...this.actions]; + this.actions = []; + this.path = []; + operateCanvas(this.id, this.pageId, 'actionsChanged', { + actions, + reserve, + }, callback); + } + createLinearGradient(x0, y0, x1, y1) { + return new CanvasGradient('linear', [x0, y0, x1, y1]); + } + createCircularGradient(x, y, r) { + return new CanvasGradient('radial', [x, y, r]); + } + createPattern(image, repetition) { + if (undefined === repetition) { + console.error("Failed to execute 'createPattern' on 'CanvasContext': 2 arguments required, but only 1 present."); + } + else if (['repeat', 'repeat-x', 'repeat-y', 'no-repeat'].indexOf(repetition) < 0) { + console.error("Failed to execute 'createPattern' on 'CanvasContext': The provided type ('" + + repetition + + "') is not one of 'repeat', 'no-repeat', 'repeat-x', or 'repeat-y'."); + } + else { + return new Pattern(image, repetition); + } + } + measureText(text) { + const font = this.state.font; + let width = 0; + { + const webview = plus.webview + .all() + .find((webview) => webview.getURL().endsWith('www/__uniappview.html')); + if (webview) { + width = Number(webview.evalJSSync(`(${measureText.toString()})(${JSON.stringify(text)},${JSON.stringify(font)})`)); + } + } + return new TextMetrics(width); + } + save() { + this.actions.push({ + method: 'save', + data: [], + }); + this.drawingState.push(this.state); + } + restore() { + this.actions.push({ + method: 'restore', + data: [], + }); + this.state = this.drawingState.pop() || { + lineDash: [0, 0], + shadowOffsetX: 0, + shadowOffsetY: 0, + shadowBlur: 0, + shadowColor: [0, 0, 0, 0], + font: '10px sans-serif', + fontSize: 10, + fontWeight: 'normal', + fontStyle: 'normal', + fontFamily: 'sans-serif', + }; + } + beginPath() { + this.path = []; + this.subpath = []; + } + moveTo(x, y) { + this.path.push({ + method: 'moveTo', + data: [x, y], + }); + this.subpath = [[x, y]]; + } + lineTo(x, y) { + if (this.path.length === 0 && this.subpath.length === 0) { + this.path.push({ + method: 'moveTo', + data: [x, y], + }); + } + else { + this.path.push({ + method: 'lineTo', + data: [x, y], + }); + } + this.subpath.push([x, y]); + } + quadraticCurveTo(cpx, cpy, x, y) { + this.path.push({ + method: 'quadraticCurveTo', + data: [cpx, cpy, x, y], + }); + this.subpath.push([x, y]); + } + bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) { + this.path.push({ + method: 'bezierCurveTo', + data: [cp1x, cp1y, cp2x, cp2y, x, y], + }); + this.subpath.push([x, y]); + } + arc(x, y, r, sAngle, eAngle, counterclockwise = false) { + this.path.push({ + method: 'arc', + data: [x, y, r, sAngle, eAngle, counterclockwise], + }); + this.subpath.push([x, y]); + } + rect(x, y, width, height) { + this.path.push({ + method: 'rect', + data: [x, y, width, height], + }); + this.subpath = [[x, y]]; + } + arcTo(x1, y1, x2, y2, radius) { + this.path.push({ + method: 'arcTo', + data: [x1, y1, x2, y2, radius], + }); + this.subpath.push([x2, y2]); + } + clip() { + this.actions.push({ + method: 'clip', + data: [...this.path], + }); + } + closePath() { + this.path.push({ + method: 'closePath', + data: [], + }); + if (this.subpath.length) { + this.subpath = [this.subpath.shift()]; + } + } + clearActions() { + this.actions = []; + this.path = []; + this.subpath = []; + } + getActions() { + var actions = [...this.actions]; + this.clearActions(); + return actions; + } + set lineDashOffset(value) { + this.actions.push({ + method: 'setLineDashOffset', + data: [value], + }); + } + set globalCompositeOperation(type) { + this.actions.push({ + method: 'setGlobalCompositeOperation', + data: [type], + }); + } + set shadowBlur(level) { + this.actions.push({ + method: 'setShadowBlur', + data: [level], + }); + } + set shadowColor(color) { + this.actions.push({ + method: 'setShadowColor', + data: [color], + }); + } + set shadowOffsetX(x) { + this.actions.push({ + method: 'setShadowOffsetX', + data: [x], + }); + } + set shadowOffsetY(y) { + this.actions.push({ + method: 'setShadowOffsetY', + data: [y], + }); + } + set font(value) { + var self = this; + this.state.font = value; + // eslint-disable-next-line + var fontFormat = value.match(/^(([\w\-]+\s)*)(\d+r?px)(\/(\d+\.?\d*(r?px)?))?\s+(.*)/); + if (fontFormat) { + var style = fontFormat[1].trim().split(/\s/); + var fontSize = parseFloat(fontFormat[3]); + var fontFamily = fontFormat[7]; + var actions = []; + style.forEach(function (value, index) { + if (['italic', 'oblique', 'normal'].indexOf(value) > -1) { + actions.push({ + method: 'setFontStyle', + data: [value], + }); + self.state.fontStyle = value; + } + else if (['bold', 'normal'].indexOf(value) > -1) { + actions.push({ + method: 'setFontWeight', + data: [value], + }); + self.state.fontWeight = value; + } + else if (index === 0) { + actions.push({ + method: 'setFontStyle', + data: ['normal'], + }); + self.state.fontStyle = 'normal'; + } + else if (index === 1) { + pushAction(); + } + }); + if (style.length === 1) { + pushAction(); + } + style = actions + .map(function (action) { + return action.data[0]; + }) + .join(' '); + this.state.fontSize = fontSize; + this.state.fontFamily = fontFamily; + this.actions.push({ + method: 'setFont', + data: [`${style} ${fontSize}px ${fontFamily}`], + }); + } + else { + console.warn("Failed to set 'font' on 'CanvasContext': invalid format."); + } + function pushAction() { + actions.push({ + method: 'setFontWeight', + data: ['normal'], + }); + self.state.fontWeight = 'normal'; + } + } + get font() { + return this.state.font; + } + set fillStyle(color) { + this.setFillStyle(color); + } + set strokeStyle(color) { + this.setStrokeStyle(color); + } + set globalAlpha(value) { + value = Math.floor(255 * parseFloat(value)); + this.actions.push({ + method: 'setGlobalAlpha', + data: [value], + }); + } + set textAlign(align) { + this.actions.push({ + method: 'setTextAlign', + data: [align], + }); + } + set lineCap(type) { + this.actions.push({ + method: 'setLineCap', + data: [type], + }); + } + set lineJoin(type) { + this.actions.push({ + method: 'setLineJoin', + data: [type], + }); + } + set lineWidth(value) { + this.actions.push({ + method: 'setLineWidth', + data: [value], + }); + } + set miterLimit(value) { + this.actions.push({ + method: 'setMiterLimit', + data: [value], + }); + } + set textBaseline(type) { + this.actions.push({ + method: 'setTextBaseline', + data: [type], + }); + } + } + const initCanvasContextProperty = /*#__PURE__*/ once(() => { + [...methods1, ...methods2].forEach(function (method) { + function get(method) { + switch (method) { + case 'fill': + case 'stroke': + return function () { + // @ts-ignore + this.actions.push({ + method: method + 'Path', + // @ts-ignore + data: [...this.path], + }); + }; + case 'fillRect': + return function (x, y, width, height) { + // @ts-ignore + this.actions.push({ + method: 'fillPath', + data: [ + { + method: 'rect', + data: [x, y, width, height], + }, + ], + }); + }; + case 'strokeRect': + return function (x, y, width, height) { + // @ts-ignore + this.actions.push({ + method: 'strokePath', + data: [ + { + method: 'rect', + data: [x, y, width, height], + }, + ], + }); + }; + case 'fillText': + case 'strokeText': + return function (text, x, y, maxWidth) { + var data = [text.toString(), x, y]; + if (typeof maxWidth === 'number') { + data.push(maxWidth); + } + // @ts-ignore + this.actions.push({ + method, + data, + }); + }; + case 'drawImage': + return function (imageResource, dx, dy, dWidth, dHeight, sx, sy, sWidth, sHeight) { + if (sHeight === undefined) { + sx = dx; + sy = dy; + sWidth = dWidth; + sHeight = dHeight; + dx = undefined; + dy = undefined; + dWidth = undefined; + dHeight = undefined; + } + var data; + function isNumber(e) { + return typeof e === 'number'; + } + data = + isNumber(dx) && + isNumber(dy) && + isNumber(dWidth) && + isNumber(dHeight) + ? [ + imageResource, + sx, + sy, + sWidth, + sHeight, + dx, + dy, + dWidth, + dHeight, + ] + : isNumber(sWidth) && isNumber(sHeight) + ? [imageResource, sx, sy, sWidth, sHeight] + : [imageResource, sx, sy]; + // @ts-ignore + this.actions.push({ + method, + data, + }); + }; + default: + return function (...data) { + // @ts-ignore + this.actions.push({ + method, + data, + }); + }; + } + } + CanvasContext.prototype[method] = get(method); + }); + methods3.forEach(function (method) { + function get(method) { + switch (method) { + case 'setFillStyle': + case 'setStrokeStyle': + return function (color) { + if (typeof color !== 'object') { + // @ts-ignore + this.actions.push({ + method, + data: ['normal', checkColor(color)], + }); + } + else { + // @ts-ignore + this.actions.push({ + method, + data: [color.type, color.data, color.colorStop], + }); + } + }; + case 'setGlobalAlpha': + return function (alpha) { + alpha = Math.floor(255 * parseFloat(alpha)); + // @ts-ignore + this.actions.push({ + method, + data: [alpha], + }); + }; + case 'setShadow': + return function (offsetX, offsetY, blur, color) { + color = checkColor(color); + // @ts-ignore + this.actions.push({ + method, + data: [offsetX, offsetY, blur, color], + }); + // @ts-ignore + this.state.shadowBlur = blur; + // @ts-ignore + this.state.shadowColor = color; + // @ts-ignore + this.state.shadowOffsetX = offsetX; + // @ts-ignore + this.state.shadowOffsetY = offsetY; + }; + case 'setLineDash': + return function (pattern, offset) { + pattern = pattern || [0, 0]; + offset = offset || 0; + // @ts-ignore + this.actions.push({ + method, + data: [pattern, offset], + }); + // @ts-ignore + this.state.lineDash = pattern; + }; + case 'setFontSize': + return function (fontSize) { + // @ts-ignore + this.state.font = this.state.font.replace(/\d+\.?\d*px/, fontSize + 'px'); + // @ts-ignore + this.state.fontSize = fontSize; + // @ts-ignore + this.actions.push({ + method, + data: [fontSize], + }); + }; + default: + return function (...data) { + // @ts-ignore + this.actions.push({ + method, + data, + }); + }; + } + } + CanvasContext.prototype[method] = get(method); + }); + }); + const createCanvasContext = defineSyncApi(API_CREATE_CANVAS_CONTEXT, (canvasId, componentInstance) => { + initCanvasContextProperty(); + if (componentInstance) { + return new CanvasContext(canvasId, getPageIdByVm(componentInstance)); + } + const pageId = getPageIdByVm(getCurrentPageVm()); + if (pageId) { + return new CanvasContext(canvasId, pageId); + } + else { + UniServiceJSBridge.emit(ON_ERROR, 'createCanvasContext:fail'); + } + }, CreateCanvasContextProtocol); + const canvasGetImageData = defineAsyncApi(API_CANVAS_GET_IMAGE_DATA, ({ canvasId, x, y, width, height }, { resolve, reject }) => { + const pageId = getPageIdByVm(getCurrentPageVm()); + if (!pageId) { + reject(); + return; + } + function callback(data) { + if (data.errMsg && data.errMsg.indexOf('fail') !== -1) { + reject('', data); + return; + } + let imgData = data.data; + if (imgData && imgData.length) { + if (data.compressed) { + imgData = pako_1.inflateRaw(imgData); + } + data.data = new Uint8ClampedArray(imgData); + } + delete data.compressed; + resolve(data); + } + operateCanvas(canvasId, pageId, 'getImageData', { + x, + y, + width, + height, + }, callback); + }, CanvasGetImageDataProtocol, CanvasGetImageDataOptions); + const canvasPutImageData = defineAsyncApi(API_CANVAS_PUT_IMAGE_DATA, ({ canvasId, data, x, y, width, height }, { resolve, reject }) => { + var pageId = getPageIdByVm(getCurrentPageVm()); + if (!pageId) { + reject(); + return; + } + let compressed; + const operate = () => { + operateCanvas(canvasId, pageId, 'putImageData', { + data, + x, + y, + width, + height, + compressed, + }, (data) => { + if (data.errMsg && data.errMsg.indexOf('fail') !== -1) { + reject(); + return; + } + resolve(data); + }); + }; + // iOS真机非调试模式压缩太慢暂时排除 + if ((plus.os.name !== 'iOS' || typeof __WEEX_DEVTOOL__ === 'boolean')) { + data = pako_1.deflateRaw(data, { to: 'string' }); + compressed = true; + } + else { + // fix ... 操作符 + data = Array.prototype.slice.call(data); + } + operate(); + }, CanvasPutImageDataProtocol, CanvasPutImageDataOptions); + const canvasToTempFilePath = defineAsyncApi(API_CANVAS_TO_TEMP_FILE_PATH, ({ x = 0, y = 0, width, height, destWidth, destHeight, canvasId, fileType, quality, }, { resolve, reject }) => { + var pageId = getPageIdByVm(getCurrentPageVm()); + if (!pageId) { + reject(); + return; + } + const dirname = `${TEMP_PATH$1}/canvas`; + operateCanvas(canvasId, pageId, 'toTempFilePath', { + x, + y, + width, + height, + destWidth, + destHeight, + fileType, + quality, + dirname, + }, (res) => { + if (res.errMsg && res.errMsg.indexOf('fail') !== -1) { + reject('', res); + return; + } + resolve(res); + }); + }, CanvasToTempFilePathProtocol, CanvasToTempFilePathOptions); - break; // need to emulate goto via "continue" - } - } - else if ((op & 64) === 0) { /* 2nd level length code */ - here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; - continue dolen; - } - else if (op & 32) { /* end-of-block */ - //Tracevv((stderr, "inflate: end of block\n")); - state.mode = TYPE$1; - break top; - } - else { - strm.msg = 'invalid literal/length code'; - state.mode = BAD$1; - break top; - } + //#endregion + /** + * 可以批量设置的监听事件 + */ + const innerAudioContextEventNames = [ + 'onCanplay', + 'onPlay', + 'onPause', + 'onStop', + 'onEnded', + 'onTimeUpdate', + 'onError', + 'onWaiting', + 'onSeeking', + 'onSeeked', + ]; + const innerAudioContextOffEventNames = [ + 'offCanplay', + 'offPlay', + 'offPause', + 'offStop', + 'offEnded', + 'offTimeUpdate', + 'offError', + 'offWaiting', + 'offSeeking', + 'offSeeked', + ]; - break; // need to emulate goto via "continue" - } - } while (_in < last && _out < end); + const defaultOptions = { + thresholds: [0], + initialRatio: 0, + observeAll: false, + }; + const MARGINS = ['top', 'right', 'bottom', 'left']; + let reqComponentObserverId$1 = 1; + function normalizeRootMargin(margins = {}) { + return MARGINS.map((name) => `${Number(margins[name]) || 0}px`).join(' '); + } + class ServiceIntersectionObserver { + constructor(component, options) { + this._pageId = getPageIdByVm(component); + this._component = component; + this._options = extend({}, defaultOptions, options); + } + relativeTo(selector, margins) { + this._options.relativeToSelector = selector; + this._options.rootMargin = normalizeRootMargin(margins); + return this; + } + relativeToViewport(margins) { + this._options.relativeToSelector = undefined; + this._options.rootMargin = normalizeRootMargin(margins); + return this; + } + observe(selector, callback) { + if (!isFunction(callback)) { + return; + } + this._options.selector = selector; + this._reqId = reqComponentObserverId$1++; + addIntersectionObserver({ + reqId: this._reqId, + component: this._component, + options: this._options, + callback, + }, this._pageId); + } + disconnect() { + this._reqId && + removeIntersectionObserver({ reqId: this._reqId, component: this._component }, this._pageId); + } + } + const createIntersectionObserver = defineSyncApi('createIntersectionObserver', (context, options) => { + if (context && !getPageIdByVm(context)) { + options = context; + context = null; + } + if (context) { + return new ServiceIntersectionObserver(context, options); + } + return new ServiceIntersectionObserver(getCurrentPageVm(), options); + }); + + let reqComponentObserverId = 1; + class ServiceMediaQueryObserver { + constructor(component) { + this._pageId = component.$page && component.$page.id; + this._component = component; + } + observe(options, callback) { + if (!isFunction(callback)) { + return; + } + this._reqId = reqComponentObserverId++; + addMediaQueryObserver({ + reqId: this._reqId, + component: this._component, + options, + callback, + }, this._pageId); + } + disconnect() { + this._reqId && + removeMediaQueryObserver({ + reqId: this._reqId, + component: this._component, + }, this._pageId); + } + } + const createMediaQueryObserver = defineSyncApi('createMediaQueryObserver', (context) => { + if (context && !getPageIdByVm(context)) { + context = null; + } + if (context) { + return new ServiceMediaQueryObserver(context); + } + return new ServiceMediaQueryObserver(getCurrentPageVm()); + }); + + // let eventReady = false + let index$3 = 0; + let optionsCache = {}; + function operateEditor(componentId, pageId, type, options) { + const data = { options }; + const needCallOptions = options && + ('success' in options || 'fail' in options || 'complete' in options); + if (needCallOptions) { + const callbackId = String(index$3++); + data.callbackId = callbackId; + optionsCache[callbackId] = options; + } + UniServiceJSBridge.invokeViewMethod(`editor.${componentId}`, { + type, + data, + }, pageId, ({ callbackId, data }) => { + if (needCallOptions) { + callOptions(optionsCache[callbackId], data); + delete optionsCache[callbackId]; + } + }); + } + class EditorContext { + constructor(id, pageId) { + this.id = id; + this.pageId = pageId; + } + format(name, value) { + this._exec('format', { + name, + value, + }); + } + insertDivider() { + this._exec('insertDivider'); + } + insertImage(options) { + this._exec('insertImage', options); + } + insertText(options) { + this._exec('insertText', options); + } + setContents(options) { + this._exec('setContents', options); + } + getContents(options) { + this._exec('getContents', options); + } + clear(options) { + this._exec('clear', options); + } + removeFormat(options) { + this._exec('removeFormat', options); + } + undo(options) { + this._exec('undo', options); + } + redo(options) { + this._exec('redo', options); + } + blur(options) { + this._exec('blur', options); + } + getSelectionText(options) { + this._exec('getSelectionText', options); + } + scrollIntoView(options) { + this._exec('scrollIntoView', options); + } + _exec(method, options) { + operateEditor(this.id, this.pageId, method, options); + } + } - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - _in -= len; - bits -= len << 3; - hold &= (1 << bits) - 1; + const ContextClasss = { + canvas: CanvasContext, + map: MapContext, + video: VideoContext, + editor: EditorContext, + }; + function convertContext(result) { + if (result && result.contextInfo) { + const { id, type, page } = result.contextInfo; + const ContextClass = ContextClasss[type]; + result.context = new ContextClass(id, page); + delete result.contextInfo; + } + } + class NodesRef { + constructor(selectorQuery, component, selector, single) { + this._selectorQuery = selectorQuery; + this._component = component; + this._selector = selector; + this._single = single; + } + boundingClientRect(callback) { + this._selectorQuery._push(this._selector, this._component, this._single, { + id: true, + dataset: true, + rect: true, + size: true, + }, callback); + return this._selectorQuery; + } + fields(fields, callback) { + this._selectorQuery._push(this._selector, this._component, this._single, fields, callback); + return this._selectorQuery; + } + scrollOffset(callback) { + this._selectorQuery._push(this._selector, this._component, this._single, { + id: true, + dataset: true, + scrollOffset: true, + }, callback); + return this._selectorQuery; + } + context(callback) { + this._selectorQuery._push(this._selector, this._component, this._single, { + context: true, + }, callback); + return this._selectorQuery; + } + } + class SelectorQuery { + constructor(page) { + this._component = undefined; + this._page = page; + this._queue = []; + this._queueCb = []; + } + exec(callback) { + requestComponentInfo(this._page, this._queue, (res) => { + const queueCbs = this._queueCb; + res.forEach((result, index) => { + if (Array.isArray(result)) { + result.forEach(convertContext); + } + else { + convertContext(result); + } + const queueCb = queueCbs[index]; + if (typeof queueCb === 'function') { + queueCb.call(this, result); + } + }); + // isFn(callback) && + if (typeof callback === 'function') { + callback.call(this, res); + } + }); + // TODO + return this._nodesRef; + } + in(component) { + this._component = component || undefined; + return this; + } + select(selector) { + return (this._nodesRef = new NodesRef(this, this._component, selector, true)); + } + selectAll(selector) { + return (this._nodesRef = new NodesRef(this, this._component, selector, false)); + } + selectViewport() { + return (this._nodesRef = new NodesRef(this, null, '', true)); + } + _push(selector, component, single, fields, callback) { + this._queue.push({ + component, + selector, + single, + fields, + }); + this._queueCb.push(callback); + } + } + const createSelectorQuery = (defineSyncApi('createSelectorQuery', (context) => { + if (context && !getPageIdByVm(context)) { + context = null; + } + return new SelectorQuery(context || getCurrentPageVm()); + })); - /* update state and return */ - strm.next_in = _in; - strm.next_out = _out; - strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); - strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); - state.hold = hold; - state.bits = bits; - return; + // import { elemInArray } from '../../helpers/protocol' + const API_CREATE_ANIMATION = 'createAnimation'; + // const timingFunctions: API_TYPE_CREATE_ANIMATION_Timing_Function[] = [ + // 'linear', + // 'ease', + // 'ease-in', + // 'ease-in-out', + // 'ease-out', + // 'step-start', + // 'step-end', + // ] + const CreateAnimationOptions = { + // 目前参数校验不支持此api校验 + formatArgs: { + /* duration: 400, + timingFunction(timingFunction, params) { + params.timingFunction = elemInArray(timingFunction, timingFunctions) + }, + delay: 0, + transformOrigin: '50% 50% 0', */ + }, + }; + const CreateAnimationProtocol = { + duration: Number, + timingFunction: String, + delay: Number, + transformOrigin: String, }; - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. + const defaultOption = { + duration: 400, + timingFunction: 'linear', + delay: 0, + transformOrigin: '50% 50% 0', + }; + class MPAnimation { + constructor(option) { + this.actions = []; + this.currentTransform = {}; + this.currentStepAnimates = []; + this.option = extend({}, defaultOption, option); + } + _getOption(option) { + const _option = { + transition: extend({}, this.option, option), + transformOrigin: '', + }; + _option.transformOrigin = _option.transition.transformOrigin; + delete _option.transition.transformOrigin; + return _option; + } + _pushAnimates(type, args) { + this.currentStepAnimates.push({ + type: type, + args: args, + }); + } + _converType(type) { + return type.replace(/[A-Z]/g, (text) => { + return `-${text.toLowerCase()}`; + }); + } + _getValue(value) { + return typeof value === 'number' ? `${value}px` : value; + } + export() { + const actions = this.actions; + this.actions = []; + return { + actions, + }; + } + step(option) { + this.currentStepAnimates.forEach((animate) => { + if (animate.type !== 'style') { + this.currentTransform[animate.type] = animate; + } + else { + this.currentTransform[`${animate.type}.${animate.args[0]}`] = animate; + } + }); + this.actions.push({ + animates: Object.values(this.currentTransform), + option: this._getOption(option), + }); + this.currentStepAnimates = []; + return this; + } + } + const initAnimationProperty = /*#__PURE__*/ once(() => { + const animateTypes1 = [ + 'matrix', + 'matrix3d', + 'rotate', + 'rotate3d', + 'rotateX', + 'rotateY', + 'rotateZ', + 'scale', + 'scale3d', + 'scaleX', + 'scaleY', + 'scaleZ', + 'skew', + 'skewX', + 'skewY', + 'translate', + 'translate3d', + 'translateX', + 'translateY', + 'translateZ', + ]; + const animateTypes2 = ['opacity', 'backgroundColor']; + const animateTypes3 = ['width', 'height', 'left', 'right', 'top', 'bottom']; + animateTypes1.concat(animateTypes2, animateTypes3).forEach((type) => { + MPAnimation.prototype[type] = function (...args) { + if (animateTypes2.concat(animateTypes3).includes(type)) { + this._pushAnimates('style', [ + this._converType(type), + animateTypes3.includes(type) ? this._getValue(args[0]) : args[0], + ]); + } + else { + this._pushAnimates(type, args); + } + return this; + }; + }); + }); + const createAnimation = defineSyncApi(API_CREATE_ANIMATION, (option) => { + initAnimationProperty(); + return new MPAnimation(option); + }, CreateAnimationProtocol, CreateAnimationOptions); - const MAXBITS = 15; - const ENOUGH_LENS$1 = 852; - const ENOUGH_DISTS$1 = 592; - //const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + const API_ON_TAB_BAR_MID_BUTTON_TAP = 'onTabBarMidButtonTap'; + const onTabBarMidButtonTap = defineOnApi(API_ON_TAB_BAR_MID_BUTTON_TAP, () => { + // noop + }); - const CODES$1 = 0; - const LENS$1 = 1; - const DISTS$1 = 2; + const API_ON_WINDOW_RESIZE = 'onWindowResize'; + const API_OFF_WINDOW_RESIZE = 'offWindowResize'; - const lbase = new Uint16Array([ /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 - ]); + /** + * 监听窗口大小变化 + */ + const onWindowResize = defineOnApi(API_ON_WINDOW_RESIZE, () => { + // 生命周期包括onResize,框架直接监听resize + // window.addEventListener('resize', onResize) + }); + /** + * 取消监听窗口大小变化 + */ + const offWindowResize = defineOffApi(API_OFF_WINDOW_RESIZE, () => { + // window.removeEventListener('resize', onResize) + }); - const lext = new Uint8Array([ /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 - ]); + const API_SET_LOCALE = 'setLocale'; + const API_GET_LOCALE = 'getLocale'; + const API_ON_LOCALE_CHANGE = 'onLocaleChange'; + const getLocale = defineSyncApi(API_GET_LOCALE, () => { + // 优先使用 $locale + const app = getApp({ allowDefault: true }); + if (app && app.$vm) { + return app.$vm.$locale; + } + return useI18n().getLocale(); + }); + const onLocaleChange = defineOnApi(API_ON_LOCALE_CHANGE, () => { }); + const setLocale = defineSyncApi(API_SET_LOCALE, (locale) => { + const app = getApp(); + if (!app) { + return false; + } + const oldLocale = app.$vm.$locale; + if (oldLocale !== locale) { + app.$vm.$locale = locale; + { + const pages = getCurrentPages(); + pages.forEach((page) => { + UniServiceJSBridge.publishHandler(API_SET_LOCALE, locale, page.$page.id); + }); + weex.requireModule('plus').setLanguage(locale); + } + // 执行 uni.onLocaleChange + UniServiceJSBridge.invokeOnCallback(API_ON_LOCALE_CHANGE, { locale }); + return true; + } + return false; + }); - const dbase = new Uint16Array([ /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0 - ]); + const API_SET_PAGE_META = 'setPageMeta'; + const setPageMeta = defineAsyncApi(API_SET_PAGE_META, (options, { resolve }) => { + resolve(setCurrentPageMeta(getCurrentPageVm(), options)); + }); - const dext = new Uint8Array([ /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64 - ]); + const API_GET_SELECTED_TEXT_RANGE = 'getSelectedTextRange'; - const inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) => - { - const bits = opts.bits; - //here = opts.here; /* table entry for duplication */ + const getSelectedTextRange = defineAsyncApi(API_GET_SELECTED_TEXT_RANGE, (_, { resolve, reject }) => { + UniServiceJSBridge.invokeViewMethod('getSelectedTextRange', {}, getCurrentPageId(), (res) => { + if (typeof res.end === 'undefined' && + typeof res.start === 'undefined') { + reject('no focused'); + } + else { + resolve(res); + } + }); + }); - let len = 0; /* a code's length in bits */ - let sym = 0; /* index of code symbols */ - let min = 0, max = 0; /* minimum and maximum code lengths */ - let root = 0; /* number of index bits for root table */ - let curr = 0; /* number of index bits for current table */ - let drop = 0; /* code bits to drop for sub-table */ - let left = 0; /* number of prefix codes available */ - let used = 0; /* code entries in table used */ - let huff = 0; /* Huffman code */ - let incr; /* for incrementing code, index */ - let fill; /* index for replicating entries */ - let low; /* low bits for current root entry */ - let mask; /* mask for low root bits */ - let next; /* next available space in table */ - let base = null; /* base value table to use */ - let base_index = 0; - // let shoextra; /* extra bits table to use */ - let end; /* use base and extra for symbol > end */ - const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ - const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ - let extra = null; - let extra_index = 0; - - let here_bits, here_op, here_val; + const appLaunchHooks = []; + function onAppLaunch(hook) { + const app = getApp({ allowDefault: true }); + if (app && app.$vm) { + return vue.injectHook(ON_LAUNCH, hook, app.$vm.$); + } + appLaunchHooks.push(hook); + } + function injectAppLaunchHooks(appInstance) { + appLaunchHooks.forEach((hook) => { + vue.injectHook(ON_LAUNCH, hook, appInstance); + }); + } + const API_GET_ENTER_OPTIONS_SYNC = 'getEnterOptionsSync'; + const getEnterOptionsSync = defineSyncApi(API_GET_ENTER_OPTIONS_SYNC, () => { + return getEnterOptions(); + }); + const API_GET_LAUNCH_OPTIONS_SYNC = 'getLaunchOptionsSync'; + const getLaunchOptionsSync = defineSyncApi(API_GET_LAUNCH_OPTIONS_SYNC, () => { + return getLaunchOptions(); + }); - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. + const API_GET_BACKGROUND_AUDIO_MANAGER = 'getBackgroundAudioManager'; - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. + const API_MAKE_PHONE_CALL = 'makePhoneCall'; + const MakePhoneCallProtocol = { + phoneNumber: String, + }; - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. + const API_ADD_PHONE_CONTACT = 'addPhoneContact'; - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ + const API_GET_CLIPBOARD_DATA = 'getClipboardData'; + const API_SET_CLIPBOARD_DATA = 'setClipboardData'; + const SetClipboardDataOptions = { + formatArgs: { + showToast: true, + }, + beforeInvoke() { + initI18nSetClipboardDataMsgsOnce(); + }, + beforeSuccess(res, params) { + if (!params.showToast) + return; + const { t } = useI18n(); + const title = t('uni.setClipboardData.success'); + if (title) { + uni.showToast({ + title: title, + icon: 'success', + mask: false, + }); + } + }, + }; + const SetClipboardDataProtocol = { + data: { + type: String, + required: true, + }, + showToast: { + type: Boolean, + }, + }; - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) { - count[len] = 0; - } - for (sym = 0; sym < codes; sym++) { - count[lens[lens_index + sym]]++; - } + const API_ON_ACCELEROMETER = 'onAccelerometer'; + const API_OFF_ACCELEROMETER = 'offAccelerometer'; + const API_START_ACCELEROMETER = 'startAccelerometer'; + const API_STOP_ACCELEROMETER = 'stopAccelerometer'; - /* bound code lengths, force root to be within code lengths */ - root = bits; - for (max = MAXBITS; max >= 1; max--) { - if (count[max] !== 0) { break; } - } - if (root > max) { - root = max; - } - if (max === 0) { /* no symbols to code at all */ - //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ - //table.bits[opts.table_index] = 1; //here.bits = (var char)1; - //table.val[opts.table_index++] = 0; //here.val = (var short)0; - table[table_index++] = (1 << 24) | (64 << 16) | 0; + const API_ON_COMPASS = 'onCompass'; + const API_OFF_COMPASS = 'offCompass'; + const API_START_COMPASS = 'startCompass'; + const API_STOP_COMPASS = 'stopCompass'; + const API_VIBRATE_SHORT = 'vibrateShort'; + const API_VIBRATE_LONG = 'vibrateLong'; - //table.op[opts.table_index] = 64; - //table.bits[opts.table_index] = 1; - //table.val[opts.table_index++] = 0; - table[table_index++] = (1 << 24) | (64 << 16) | 0; + const API_ON_BLUETOOTH_DEVICE_FOUND = 'onBluetoothDeviceFound'; + const API_ON_BLUETOOTH_ADAPTER_STATE_CHANGE = 'onBluetoothAdapterStateChange'; + const API_ON_BLE_CONNECTION_STATE_CHANGE = 'onBLEConnectionStateChange'; + const API_ON_BLE_CHARACTERISTIC_VALUE_CHANGE = 'onBLECharacteristicValueChange'; + const API_START_BLUETOOTH_DEVICES_DISCOVERY = 'startBluetoothDevicesDiscovery'; + const StartBluetoothDevicesDiscoveryProtocol = { + services: Array, + allowDuplicatesKey: Boolean, + interval: Number, + }; + const API_GET_CONNECTED_BLUETOOTH_DEVICES = 'getConnectedBluetoothDevices'; + const GetConnectedBluetoothDevicesProtocol = { + services: { + type: Array, + required: true, + }, + }; + const API_CREATE_BLE_CONNECTION = 'createBLEConnection'; + const CreateBLEConnectionProtocol = { + deviceId: { + type: String, + required: true, + }, + }; + const API_CLOSE_BLE_CONNECTION = 'closeBLEConnection'; + const CloseBLEConnectionProtocol = { + deviceId: { + type: String, + required: true, + }, + }; + const API_GET_BLE_DEVICE_SERVICES = 'getBLEDeviceServices'; + const GetBLEDeviceServicesProtocol = { + deviceId: { + type: String, + required: true, + }, + }; + const API_GET_BLE_DEVICE_CHARACTERISTICS = 'getBLEDeviceCharacteristics'; + const GetBLEDeviceCharacteristicsProtocol = { + deviceId: { + type: String, + required: true, + }, + serviceId: { + type: String, + required: true, + }, + }; + const API_NOTIFY_BLE_CHARACTERISTIC_VALUE_CHANGE = 'notifyBLECharacteristicValueChange'; + const NotifyBLECharacteristicValueChangeProtocol = { + deviceId: { + type: String, + required: true, + }, + serviceId: { + type: String, + required: true, + }, + characteristicId: { + type: String, + required: true, + }, + state: { + type: Boolean, + required: true, + }, + }; + const API_READ_BLE_CHARACTERISTIC_VALUE = 'readBLECharacteristicValue'; + const ReadBLECharacteristicValueProtocol = { + deviceId: { + type: String, + required: true, + }, + serviceId: { + type: String, + required: true, + }, + characteristicId: { + type: String, + required: true, + }, + }; + const API_WRITE_BLE_CHARACTERISTIC_VALUE = 'writeBLECharacteristicValue'; + const WriteBLECharacteristicValueProtocol = { + deviceId: { + type: String, + required: true, + }, + serviceId: { + type: String, + required: true, + }, + characteristicId: { + type: String, + required: true, + }, + value: { + type: Array, + required: true, + }, + }; + const API_SET_BLE_MTU = 'setBLEMTU'; + const SetBLEMTUProtocol = { + deviceId: { + type: String, + required: true, + }, + mtu: { + type: Number, + required: true, + }, + }; + const API_GET_BLE_DEVICE_RSSI = 'getBLEDeviceRSSI'; + const GetBLEDeviceRSSIProtocol = { + deviceId: { + type: String, + required: true, + }, + }; - opts.bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min < max; min++) { - if (count[min] !== 0) { break; } - } - if (root < min) { - root = min; - } + const API_ON_BEACON_UPDATE = 'onBeaconUpdate'; + const API_ON_BEACON_SERVICE_CHANGE = 'onBeaconServiceChange'; + const API_GET_BEACONS = 'getBeacons'; + const API_START_BEACON_DISCOVERY = 'startBeaconDiscovery'; + const StartBeaconDiscoveryProtocol = { + uuids: { + type: Array, + required: true, + }, + }; + const API_STOP_BEACON_DISCOVERY = 'stopBeaconDiscovery'; - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) { - return -1; - } /* over-subscribed */ - } - if (left > 0 && (type === CODES$1 || max !== 1)) { - return -1; /* incomplete set */ - } + const API_GET_SCREEN_BRIGHTNESS = 'getScreenBrightness'; + const API_SET_SCREEN_BRIGHTNESS = 'setScreenBrightness'; + const API_SET_KEEP_SCREEN_ON = 'setKeepScreenOn'; - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) { - offs[len + 1] = offs[len] + count[len]; - } + const API_CHECK_IS_SUPPORT_SOTER_AUTHENTICATION = 'soterAuthentication'; + const API_CHECK_IS_SOTER_ENROLLED_IN_DEVICE = 'checkIsSoterEnrolledInDevice'; + const CheckAuthModes = [ + 'fingerPrint', + 'facial', + 'speech', + ]; + const CheckIsSoterEnrolledInDeviceOptions = { + formatArgs: { + checkAuthMode(value, params) { + if (!value || !CheckAuthModes.includes(value)) + return 'checkAuthMode 填写错误'; + }, + }, + }; + const CheckIsSoterEnrolledInDeviceProtocols = { + checkAuthMode: String, + }; + const API_START_SOTER_AUTHENTICATION = 'checkIsSoterEnrolledInDevice'; + const StartSoterAuthenticationOptions = { + formatArgs: { + requestAuthModes(value, params) { + if (!value.includes('fingerPrint') && !value.includes('facial')) + return 'requestAuthModes 填写错误'; + }, + }, + }; + const StartSoterAuthenticationProtocols = { + requestAuthModes: { + type: Array, + required: true, + }, + challenge: String, + authContent: String, + }; - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) { - if (lens[lens_index + sym] !== 0) { - work[offs[lens[lens_index + sym]]++] = sym; - } - } + const API_SCAN_CODE = 'scanCode'; + const ScanCodeProtocol = { + onlyFromCamera: Boolean, + scanType: Array, + autoDecodeCharSet: Boolean, + }; - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. + const API_GET_STORAGE = 'getStorage'; + const GetStorageProtocol = { + key: { + type: String, + required: true, + }, + }; + const API_GET_STORAGE_SYNC = 'getStorageSync'; + const GetStorageSyncProtocol = [ + { + name: 'key', + type: String, + required: true, + }, + ]; + const API_SET_STORAGE = 'setStorage'; + const SetStorageProtocol = { + key: { + type: String, + required: true, + }, + data: { + required: true, + }, + }; + const API_SET_STORAGE_SYNC = 'setStorageSync'; + const SetStorageSyncProtocol = [ + { + name: 'key', + type: String, + required: true, + }, + { + name: 'data', + required: true, + }, + ]; + const API_REMOVE_STORAGE = 'removeStorage'; + const RemoveStorageProtocol = GetStorageProtocol; + const RemoveStorageSyncProtocol = GetStorageSyncProtocol; - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. + const API_SAVE_FILE = 'saveFile'; + const SaveFileOptions = { + formatArgs: { + tempFilePath(savedFilePath, params) { + params.tempFilePath = getRealPath(savedFilePath); + }, + }, + }; + const SaveFileProtocol = { + tempFilePath: { + type: String, + required: true, + }, + }; - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. + const API_GET_FILE_INFO = 'getFileInfo'; + const GetFileInfoOptions = { + formatArgs: { + filePath(filePath, params) { + params.filePath = getRealPath(filePath); + }, + }, + }; + const GetFileInfoProtocol = { + filePath: { + type: String, + required: true, + }, + }; - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftrees.h - for more information. + const API_OPEN_DOCUMENT = 'openDocument'; + const OpenDocumentOptions = { + formatArgs: { + filePath(filePath, params) { + params.filePath = getRealPath(filePath); + }, + }, + }; + const OpenDocumentProtocol = { + filePath: { + type: String, + required: true, + }, + fileType: String, + }; - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ + const API_HIDE_KEYBOARD = 'hideKeyboard'; + const API_SHOW_KEYBOARD = 'showKeyboard'; - /* set up for code type */ - // poor man optimization - use if-else instead of switch, - // to avoid deopts in old v8 - if (type === CODES$1) { - base = extra = work; /* dummy value--not used */ - end = 19; + const API_CHOOSE_LOCATION = 'chooseLocation'; + const ChooseLocationProtocol = { + keyword: String, + latitude: Number, + longitude: Number, + }; - } else if (type === LENS$1) { - base = lbase; - base_index -= 257; - extra = lext; - extra_index -= 257; - end = 256; + const API_GET_LOCATION = 'getLocation'; + const coordTypes = ['WGS84', 'GCJ02']; + const GetLocationOptions = { + formatArgs: { + type(value, params) { + value = (value || '').toUpperCase(); + if (coordTypes.indexOf(value) === -1) { + params.type = coordTypes[0]; + } + else { + params.type = value; + } + }, + altitude(value, params) { + params.altitude = value ? value : false; + }, + }, + }; + const GetLocationProtocol = { + type: String, + altitude: Boolean, + }; - } else { /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } + const API_OPEN_LOCATION = 'openLocation'; + const OpenLocationOptions = { + formatArgs: { + scale(value, params) { + value = Math.floor(value); + params.scale = value >= 5 && value <= 18 ? value : 18; + }, + }, + }; + const OpenLocationProtocol = { + latitude: { + type: Number, + required: true, + }, + longitude: { + type: Number, + required: true, + }, + scale: Number, + name: String, + address: String, + }; - /* initialize opts for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = table_index; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = -1; /* trigger new sub-table when len > root */ - used = 1 << root; /* use root table entries */ - mask = used - 1; /* mask for comparing low */ + const API_CHOOSE_IMAGE = 'chooseImage'; + const ChooseImageOptions = { + formatArgs: { + count(value, params) { + if (!value || value <= 0) { + params.count = 9; + } + }, + sizeType(sizeType, params) { + params.sizeType = elemsInArray(sizeType, CHOOSE_SIZE_TYPES); + }, + sourceType(sourceType, params) { + params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES); + }, + extension(extension, params) { + if (extension instanceof Array && extension.length === 0) { + return 'param extension should not be empty.'; + } + if (!extension) + params.extension = ['*']; + }, + }, + }; + const ChooseImageProtocol = { + count: Number, + sizeType: [Array, String], + sourceType: Array, + extension: Array, + }; - /* check available table space */ - if ((type === LENS$1 && used > ENOUGH_LENS$1) || - (type === DISTS$1 && used > ENOUGH_DISTS$1)) { - return 1; - } + const API_CHOOSE_VIDEO = 'chooseVideo'; + const ChooseVideoOptions = { + formatArgs: { + sourceType(sourceType, params) { + params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES); + }, + compressed: true, + maxDuration: 60, + camera: 'back', + extension(extension, params) { + if (extension instanceof Array && extension.length === 0) { + return 'param extension should not be empty.'; + } + if (!extension) + params.extension = ['*']; + }, + }, + }; + const ChooseVideoProtocol = { + sourceType: Array, + compressed: Boolean, + maxDuration: Number, + camera: String, + extension: Array, + }; - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - here_bits = len - drop; - if (work[sym] < end) { - here_op = 0; - here_val = work[sym]; - } - else if (work[sym] > end) { - here_op = extra[extra_index + work[sym]]; - here_val = base[base_index + work[sym]]; - } - else { - here_op = 32 + 64; /* end of block */ - here_val = 0; - } + const API_GET_IMAGE_INFO = 'getImageInfo'; + const GetImageInfoOptions = { + formatArgs: { + src(src, params) { + params.src = getRealPath(src); + }, + }, + }; + const GetImageInfoProtocol = { + src: { + type: String, + required: true, + }, + }; - /* replicate for those indices with low len bits equal to huff */ - incr = 1 << (len - drop); - fill = 1 << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; - } while (fill !== 0); + const API_PREVIEW_IMAGE = 'previewImage'; + const PreviewImageOptions = { + formatArgs: { + urls(urls, params) { + params.urls = urls.map((url) => typeof url === 'string' && url ? getRealPath(url) : ''); + }, + current(current, params) { + if (typeof current === 'number') { + params.current = + current > 0 && current < params.urls.length ? current : 0; + } + else if (typeof current === 'string' && current) { + params.current = getRealPath(current); + } + }, + }, + }; + const PreviewImageProtocol = { + urls: { + type: Array, + required: true, + }, + current: { + type: [Number, String], + }, + }; + const API_CLOSE_PREVIEW_IMAGE = 'closePreviewImage'; - /* backwards increment the len-bit code huff */ - incr = 1 << (len - 1); - while (huff & incr) { - incr >>= 1; - } - if (incr !== 0) { - huff &= incr - 1; - huff += incr; - } else { - huff = 0; - } + const API_GET_VIDEO_INFO = 'getVideoInfo'; + const GetVideoInfoOptions = { + formatArgs: { + src(src, params) { + params.src = getRealPath(src); + }, + }, + }; + const GetVideoInfoProtocol = { + src: { + type: String, + required: true, + }, + }; - /* go to next symbol, update count, len */ - sym++; - if (--count[len] === 0) { - if (len === max) { break; } - len = lens[lens_index + work[sym]]; - } + const API_SAVE_IMAGE_TO_PHOTOS_ALBUM = 'saveImageToPhotosAlbum'; + const SaveImageToPhotosAlbumOptions = { + formatArgs: { + filePath(filePath, params) { + params.filePath = getRealPath(filePath); + }, + }, + }; + const SaveImageToPhotosAlbumProtocol = { + filePath: { + type: String, + required: true, + }, + }; - /* create new sub-table if needed */ - if (len > root && (huff & mask) !== low) { - /* if first time, transition to sub-tables */ - if (drop === 0) { - drop = root; - } + const API_SAVE_VIDEO_TO_PHOTOS_ALBUM = 'saveVideoToPhotosAlbum'; + const SaveVideoToPhotosAlbumOptions = { + formatArgs: { + filePath(filePath, params) { + params.filePath = getRealPath(filePath); + }, + }, + }; + const SaveVideoToPhotosAlbumProtocol = { + filePath: { + type: String, + required: true, + }, + }; - /* increment past last table */ - next += min; /* here min is 1 << curr */ + const API_GET_RECORDER_MANAGER = 'getRecorderManager'; - /* determine length of next table */ - curr = len - drop; - left = 1 << curr; - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) { break; } - curr++; - left <<= 1; - } + const API_COMPRESS_IMAGE = 'compressImage'; + const CompressImageOptions = { + formatArgs: { + src(src, params) { + params.src = getRealPath(src); + }, + }, + }; + const CompressImageProtocol = { + src: { + type: String, + required: true, + }, + }; - /* check for enough space */ - used += 1 << curr; - if ((type === LENS$1 && used > ENOUGH_LENS$1) || - (type === DISTS$1 && used > ENOUGH_DISTS$1)) { - return 1; - } + const API_COMPRESS_VIDEO = 'compressVideo'; + const CompressVideoOptions = { + formatArgs: { + src(src, params) { + params.src = getRealPath(src); + }, + }, + }; + const CompressVideoProtocol = { + src: { + type: String, + required: true, + }, + quality: String, + bitrate: Number, + fps: Number, + resolution: Number, + }; - /* point entry in root table to sub-table */ - low = huff & mask; - /*table.op[low] = curr; - table.bits[low] = root; - table.val[low] = next - opts.table_index;*/ - table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; - } - } + const API_REQUEST = 'request'; + const dataType = { + JSON: 'json', + }; + const RESPONSE_TYPE = ['text', 'arraybuffer']; + const DEFAULT_RESPONSE_TYPE = 'text'; + const encode$1 = encodeURIComponent; + function stringifyQuery(url, data) { + let str = url.split('#'); + const hash = str[1] || ''; + str = str[0].split('?'); + let query = str[1] || ''; + url = str[0]; + const search = query.split('&').filter((item) => item); + const params = {}; + search.forEach((item) => { + const part = item.split('='); + params[part[0]] = part[1]; + }); + for (const key in data) { + if (hasOwn$1(data, key)) { + let v = data[key]; + if (typeof v === 'undefined' || v === null) { + v = ''; + } + else if (isPlainObject(v)) { + v = JSON.stringify(v); + } + params[encode$1(key)] = encode$1(v); + } + } + query = Object.keys(params) + .map((item) => `${item}=${params[item]}`) + .join('&'); + return url + (query ? '?' + query : '') + (hash ? '#' + hash : ''); + } + const RequestProtocol = { + method: String, + data: [Object, String, Array, ArrayBuffer], + url: { + type: String, + required: true, + }, + header: Object, + dataType: String, + responseType: String, + withCredentials: Boolean, + }; + const RequestOptions = { + formatArgs: { + method(value, params) { + params.method = elemInArray((value || '').toUpperCase(), HTTP_METHODS); + }, + data(value, params) { + params.data = value || ''; + }, + url(value, params) { + if (params.method === HTTP_METHODS[0] && + isPlainObject(params.data) && + Object.keys(params.data).length) { + // 将 method,data 校验提前,保证 url 校验时,method,data 已被格式化 + params.url = stringifyQuery(value, params.data); + } + }, + header(value, params) { + const header = (params.header = value || {}); + if (params.method !== HTTP_METHODS[0]) { + if (!Object.keys(header).find((key) => key.toLowerCase() === 'content-type')) { + header['Content-Type'] = 'application/json'; + } + } + }, + dataType(value, params) { + params.dataType = (value || dataType.JSON).toLowerCase(); + }, + responseType(value, params) { + params.responseType = (value || '').toLowerCase(); + if (RESPONSE_TYPE.indexOf(params.responseType) === -1) { + params.responseType = DEFAULT_RESPONSE_TYPE; + } + }, + }, + }; + const API_CONFIG_MTLS = 'configMTLS'; + const ConfigMTLSProtocol = { + certificates: { + type: Array, + required: true, + }, + }; + const ConfigMTLSOptions = { + formatArgs: { + certificates(value) { + if (value.some((item) => toRawType(item.host) !== 'String')) { + return '参数配置错误,请确认后重试'; + } + }, + }, + }; - /* fill in remaining table entry if code is incomplete (guaranteed to have - at most one remaining entry, since if the code is incomplete, the - maximum code length that was allowed to get this far is one bit) */ - if (huff !== 0) { - //table.op[next + huff] = 64; /* invalid code marker */ - //table.bits[next + huff] = len - drop; - //table.val[next + huff] = 0; - table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; - } + const API_DOWNLOAD_FILE = 'downloadFile'; + const DownloadFileOptions = { + formatArgs: { + header(value, params) { + params.header = value || {}; + }, + }, + }; + const DownloadFileProtocol = { + url: { + type: String, + required: true, + }, + header: Object, + timeout: Number, + }; - /* set return parameters */ - //opts.table_index += used; - opts.bits = root; - return 0; + const API_UPLOAD_FILE = 'uploadFile'; + const UploadFileOptions = { + formatArgs: { + filePath(filePath, params) { + if (filePath) { + params.filePath = getRealPath(filePath); + } + }, + header(value, params) { + params.header = value || {}; + }, + formData(value, params) { + params.formData = value || {}; + }, + }, + }; + const UploadFileProtocol = { + url: { + type: String, + required: true, + }, + files: Array, + filePath: String, + name: String, + header: Object, + formData: Object, + timeout: Number, }; + const API_CONNECT_SOCKET = 'connectSocket'; + const ConnectSocketOptions = { + formatArgs: { + header(value, params) { + params.header = value || {}; + }, + method(value, params) { + params.method = elemInArray((value || '').toUpperCase(), HTTP_METHODS); + }, + protocols(protocols, params) { + if (typeof protocols === 'string') { + params.protocols = [protocols]; + } + }, + }, + }; + const ConnectSocketProtocol = { + url: { + type: String, + required: true, + }, + header: { + type: Object, + }, + method: String, + protocols: [Array, String], + }; + const API_SEND_SOCKET_MESSAGE = 'sendSocketMessage'; + const SendSocketMessageProtocol = { + data: [String, ArrayBuffer], + }; + const API_CLOSE_SOCKET = 'closeSocket'; + const CloseSocketProtocol = { + code: Number, + reason: String, + }; - var inftrees = inflate_table; - - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. - - - - - - - const CODES = 0; - const LENS = 1; - const DISTS = 2; - - /* Public constants ==========================================================*/ - /* ===========================================================================*/ + function encodeQueryString(url) { + if (typeof url !== 'string') { + return url; + } + const index = url.indexOf('?'); + if (index === -1) { + return url; + } + const query = url + .substr(index + 1) + .trim() + .replace(/^(\?|#|&)/, ''); + if (!query) { + return url; + } + url = url.substr(0, index); + const params = []; + query.split('&').forEach((param) => { + const parts = param.replace(/\+/g, ' ').split('='); + const key = parts.shift(); + const val = parts.length > 0 ? parts.join('=') : ''; + params.push(key + '=' + encodeURIComponent(val)); + }); + return params.length ? url + '?' + params.join('&') : url; + } - const { - Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES, - Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR, - Z_DEFLATED - } = constants$2; + const ANIMATION_IN = [ + 'slide-in-right', + 'slide-in-left', + 'slide-in-top', + 'slide-in-bottom', + 'fade-in', + 'zoom-out', + 'zoom-fade-out', + 'pop-in', + 'none', + ]; + const ANIMATION_OUT = [ + 'slide-out-right', + 'slide-out-left', + 'slide-out-top', + 'slide-out-bottom', + 'fade-out', + 'zoom-in', + 'zoom-fade-in', + 'pop-out', + 'none', + ]; + const BaseRouteProtocol = { + url: { + type: String, + required: true, + }, + }; + const API_NAVIGATE_TO = 'navigateTo'; + const API_REDIRECT_TO = 'redirectTo'; + const API_RE_LAUNCH = 'reLaunch'; + const API_SWITCH_TAB = 'switchTab'; + const API_NAVIGATE_BACK = 'navigateBack'; + const API_PRELOAD_PAGE = 'preloadPage'; + const API_UN_PRELOAD_PAGE = 'unPreloadPage'; + const NavigateToProtocol = + /*#__PURE__*/ extend({}, BaseRouteProtocol, createAnimationProtocol(ANIMATION_IN)); + const NavigateBackProtocol = + /*#__PURE__*/ extend({ + delta: { + type: Number, + }, + }, createAnimationProtocol(ANIMATION_OUT)); + const RedirectToProtocol = BaseRouteProtocol; + const ReLaunchProtocol = BaseRouteProtocol; + const SwitchTabProtocol = BaseRouteProtocol; + const PreloadPageProtocol = BaseRouteProtocol; + const UnPreloadPageProtocol = BaseRouteProtocol; + const NavigateToOptions = + /*#__PURE__*/ createRouteOptions(API_NAVIGATE_TO); + const RedirectToOptions = + /*#__PURE__*/ createRouteOptions(API_REDIRECT_TO); + const ReLaunchOptions = + /*#__PURE__*/ createRouteOptions(API_RE_LAUNCH); + const SwitchTabOptions = + /*#__PURE__*/ createRouteOptions(API_SWITCH_TAB); + const NavigateBackOptions = { + formatArgs: { + delta(value, params) { + value = parseInt(value + '') || 1; + params.delta = Math.min(getCurrentPages().length - 1, value); + }, + }, + }; + function createAnimationProtocol(animationTypes) { + return { + animationType: { + type: String, + validator(type) { + if (type && animationTypes.indexOf(type) === -1) { + return ('`' + + type + + '` is not supported for `animationType` (supported values are: `' + + animationTypes.join('`|`') + + '`)'); + } + }, + }, + animationDuration: { + type: Number, + }, + }; + } + let navigatorLock; + function beforeRoute() { + navigatorLock = ''; + } + function createRouteOptions(type) { + return { + formatArgs: { + url: createNormalizeUrl(type), + }, + beforeAll: beforeRoute, + }; + } + function createNormalizeUrl(type) { + return function normalizeUrl(url, params) { + if (!url) { + return `Missing required args: "url"`; + } + // 格式化为绝对路径路由 + url = normalizeRoute(url); + const pagePath = url.split('?')[0]; + // 匹配路由是否存在 + const routeOptions = getRouteOptions(pagePath, true); + if (!routeOptions) { + return 'page `' + url + '` is not found'; + } + // 检测不同类型跳转 + if (type === API_NAVIGATE_TO || type === API_REDIRECT_TO) { + if (routeOptions.meta.isTabBar) { + return `can not ${type} a tabbar page`; + } + } + else if (type === API_SWITCH_TAB) { + if (!routeOptions.meta.isTabBar) { + return 'can not switch to no-tabBar page'; + } + } + // switchTab不允许传递参数,reLaunch到一个tabBar页面是可以的 + if ((type === API_SWITCH_TAB || type === API_PRELOAD_PAGE) && + routeOptions.meta.isTabBar && + params.openType !== 'appLaunch') { + url = pagePath; + } + // 首页自动格式化为`/` + if (routeOptions.meta.isEntry) { + url = url.replace(routeOptions.alias, '/'); + } + // 参数格式化 + params.url = encodeQueryString(url); + if (type === API_UN_PRELOAD_PAGE) { + return; + } + else if (type === API_PRELOAD_PAGE) { + { + if (!routeOptions.meta.isNVue) { + return 'can not preload vue page'; + } + } + if (routeOptions.meta.isTabBar) { + const pages = getCurrentPages(); + const tabBarPagePath = routeOptions.path.substr(1); + if (pages.find((page) => page.route === tabBarPagePath)) { + return 'tabBar page `' + tabBarPagePath + '` already exists'; + } + } + return; + } + // 主要拦截目标为用户快速点击时触发的多次跳转,该情况,通常前后 url 是一样的 + if (navigatorLock === url && params.openType !== 'appLaunch') { + return `${navigatorLock} locked`; + } + // 至少 onLaunch 之后,再启用lock逻辑(onLaunch之前可能开发者手动调用路由API,来提前跳转) + // enableNavigatorLock 临时开关(不对外开放),避免该功能上线后,有部分情况异常,可以让开发者临时关闭 lock 功能 + if (__uniConfig.ready) { + navigatorLock = url; + } + }; + } + const API_HIDE_LOADING = 'hideLoading'; - /* STATES ====================================================================*/ - /* ===========================================================================*/ + const API_HIDE_TOAST = 'hideToast'; + const API_LOAD_FONT_FACE = 'loadFontFace'; + const LoadFontFaceProtocol = { + family: { + type: String, + required: true, + }, + source: { + type: String, + required: true, + }, + desc: Object, + }; - const HEAD = 1; /* i: waiting for magic header */ - const FLAGS = 2; /* i: waiting for method and flags (gzip) */ - const TIME = 3; /* i: waiting for modification time (gzip) */ - const OS = 4; /* i: waiting for extra flags and operating system (gzip) */ - const EXLEN = 5; /* i: waiting for extra length (gzip) */ - const EXTRA = 6; /* i: waiting for extra bytes (gzip) */ - const NAME = 7; /* i: waiting for end of file name (gzip) */ - const COMMENT = 8; /* i: waiting for end of comment (gzip) */ - const HCRC = 9; /* i: waiting for header crc (gzip) */ - const DICTID = 10; /* i: waiting for dictionary check value */ - const DICT = 11; /* waiting for inflateSetDictionary() call */ - const TYPE = 12; /* i: waiting for type bits, including last-flag bit */ - const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ - const STORED = 14; /* i: waiting for stored size (length and complement) */ - const COPY_ = 15; /* i/o: same as COPY below, but only first time in */ - const COPY = 16; /* i/o: waiting for input or output to copy stored block */ - const TABLE = 17; /* i: waiting for dynamic block table lengths */ - const LENLENS = 18; /* i: waiting for code length code lengths */ - const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ - const LEN_ = 20; /* i: same as LEN below, but only first time in */ - const LEN = 21; /* i: waiting for length/lit/eob code */ - const LENEXT = 22; /* i: waiting for length extra bits */ - const DIST = 23; /* i: waiting for distance code */ - const DISTEXT = 24; /* i: waiting for distance extra bits */ - const MATCH = 25; /* o: waiting for output space to copy string */ - const LIT = 26; /* o: waiting for output space to write literal */ - const CHECK = 27; /* i: waiting for 32-bit check value */ - const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ - const DONE = 29; /* finished check, done -- remain here until reset */ - const BAD = 30; /* got a data error -- remain here until reset */ - const MEM = 31; /* got an inflate() memory error -- remain here until reset */ - const SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + const FRONT_COLORS = ['#ffffff', '#000000']; + const API_SET_NAVIGATION_BAR_COLOR = 'setNavigationBarColor'; + const SetNavigationBarColorOptions = { + formatArgs: { + animation(animation, params) { + if (!animation) { + animation = { duration: 0, timingFunc: 'linear' }; + } + params.animation = { + duration: animation.duration || 0, + timingFunc: animation.timingFunc || 'linear', + }; + }, + }, + }; + const SetNavigationBarColorProtocol = { + frontColor: { + type: String, + required: true, + validator(frontColor) { + if (FRONT_COLORS.indexOf(frontColor) === -1) { + return `invalid frontColor "${frontColor}"`; + } + }, + }, + backgroundColor: { + type: String, + required: true, + }, + animation: Object, + }; + const API_SET_NAVIGATION_BAR_TITLE = 'setNavigationBarTitle'; + const SetNavigationBarTitleProtocol = { + title: { + type: String, + required: true, + }, + }; + const API_SHOW_NAVIGATION_BAR_LOADING = 'showNavigationBarLoading'; + const API_HIDE_NAVIGATION_BAR_LOADING = 'hideNavigationBarLoading'; - /* ===========================================================================*/ + const API_PAGE_SCROLL_TO = 'pageScrollTo'; + const PageScrollToProtocol = { + scrollTop: Number, + selector: String, + duration: Number, + }; + const DEFAULT_DURATION = 300; + const PageScrollToOptions = { + formatArgs: { + duration(value, params) { + params.duration = Math.max(0, parseInt(value + '') || DEFAULT_DURATION); + }, + }, + }; + const API_SHOW_ACTION_SHEET = 'showActionSheet'; + const ShowActionSheetProtocol = { + itemList: { + type: Array, + required: true, + }, + title: String, + alertText: String, + itemColor: String, + popover: Object, + }; + const ShowActionSheetOptions = { + formatArgs: { + itemColor: '#000', + }, + }; + const API_SHOW_LOADING = 'showLoading'; + const ShowLoadingProtocol = { + title: String, + mask: Boolean, + }; + const ShowLoadingOptions = { + formatArgs: { + title: '', + mask: false, + }, + }; - const ENOUGH_LENS = 852; - const ENOUGH_DISTS = 592; - //const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + const API_SHOW_MODAL = 'showModal'; + const ShowModalProtocol = { + title: String, + content: String, + showCancel: Boolean, + cancelText: String, + cancelColor: String, + confirmText: String, + confirmColor: String, + }; + const ShowModalOptions = { + beforeInvoke() { + // dynamic init (tree shaking) + initI18nShowModalMsgsOnce(); + }, + formatArgs: { + title: '', + content: '', + showCancel: true, + cancelText(_value, params) { + if (!hasOwn$1(params, 'cancelText')) { + const { t } = useI18n(); + params.cancelText = t('uni.showModal.cancel'); + } + }, + cancelColor: '#000', + confirmText(_value, params) { + if (!hasOwn$1(params, 'confirmText')) { + const { t } = useI18n(); + params.confirmText = t('uni.showModal.confirm'); + } + }, + confirmColor: PRIMARY_COLOR, + }, + }; - const MAX_WBITS = 15; - /* 32K LZ77 window */ - const DEF_WBITS = MAX_WBITS; + const API_SHOW_TOAST = 'showToast'; + const SHOW_TOAST_ICON = [ + 'success', + 'loading', + 'none', + 'error', + ]; + const ShowToastProtocol = { + title: String, + icon: String, + image: String, + duration: Number, + mask: Boolean, + }; + const ShowToastOptions = { + formatArgs: { + title: '', + icon(type, params) { + params.icon = elemInArray(type, SHOW_TOAST_ICON); + }, + image(value, params) { + if (value) { + params.image = getRealPath(value); + } + else { + params.image = ''; + } + }, + duration: 1500, + mask: false, + }, + }; + const API_START_PULL_DOWN_REFRESH = 'startPullDownRefresh'; - const zswap32 = (q) => { + const API_STOP_PULL_DOWN_REFRESH = 'stopPullDownRefresh'; - return (((q >>> 24) & 0xff) + - ((q >>> 8) & 0xff00) + - ((q & 0xff00) << 8) + - ((q & 0xff) << 24)); + const IndexProtocol = { + index: { + type: Number, + required: true, + }, + }; + const IndexOptions = { + beforeInvoke() { + const pageMeta = getCurrentPageMeta(); + if (pageMeta && !pageMeta.isTabBar) { + return 'not TabBar page'; + } + }, + formatArgs: { + index(value) { + if (!__uniConfig.tabBar.list[value]) { + return 'tabbar item not found'; + } + }, + }, + }; + const API_SET_TAB_BAR_ITEM = 'setTabBarItem'; + const SetTabBarItemProtocol = + /*#__PURE__*/ extend({ + text: String, + iconPath: String, + selectedIconPath: String, + pagePath: String, + }, IndexProtocol); + const SetTabBarItemOptions = { + beforeInvoke: IndexOptions.beforeInvoke, + formatArgs: /*#__PURE__*/ extend({ + pagePath(value, params) { + if (value) { + params.pagePath = removeLeadingSlash(value); + } + }, + }, IndexOptions.formatArgs), + }; + const API_SET_TAB_BAR_STYLE = 'setTabBarStyle'; + const SetTabBarStyleProtocol = { + color: String, + selectedColor: String, + backgroundColor: String, + backgroundImage: String, + backgroundRepeat: String, + borderStyle: String, + }; + const GRADIENT_RE = /^(linear|radial)-gradient\(.+?\);?$/; + const SetTabBarStyleOptions = { + beforeInvoke: IndexOptions.beforeInvoke, + formatArgs: { + backgroundImage(value, params) { + if (value && !GRADIENT_RE.test(value)) { + params.backgroundImage = getRealPath(value); + } + }, + borderStyle(value, params) { + if (value) { + params.borderStyle = value === 'white' ? 'white' : 'black'; + } + }, + }, + }; + const API_HIDE_TAB_BAR = 'hideTabBar'; + const HideTabBarProtocol = { + animation: Boolean, + }; + const API_SHOW_TAB_BAR = 'showTabBar'; + const ShowTabBarProtocol = HideTabBarProtocol; + const API_HIDE_TAB_BAR_RED_DOT = 'hideTabBarRedDot'; + const HideTabBarRedDotProtocol = IndexProtocol; + const HideTabBarRedDotOptions = IndexOptions; + const API_SHOW_TAB_BAR_RED_DOT = 'showTabBarRedDot'; + const ShowTabBarRedDotProtocol = IndexProtocol; + const ShowTabBarRedDotOptions = IndexOptions; + const API_REMOVE_TAB_BAR_BADGE = 'removeTabBarBadge'; + const RemoveTabBarBadgeProtocol = IndexProtocol; + const RemoveTabBarBadgeOptions = IndexOptions; + const API_SET_TAB_BAR_BADGE = 'setTabBarBadge'; + const SetTabBarBadgeProtocol = + /*#__PURE__*/ extend({ + text: { + type: String, + required: true, + }, + }, IndexProtocol); + const SetTabBarBadgeOptions = { + beforeInvoke: IndexOptions.beforeInvoke, + formatArgs: /*#__PURE__*/ extend({ + text(value, params) { + if (getLen(value) >= 4) { + params.text = '...'; + } + }, + }, IndexOptions.formatArgs), }; - - function InflateState() { - this.mode = 0; /* current inflate mode */ - this.last = false; /* true if processing last block */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.havedict = false; /* true if dictionary provided */ - this.flags = 0; /* gzip header method and flags (0 if zlib) */ - this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ - this.check = 0; /* protected copy of check value */ - this.total = 0; /* protected copy of output count */ - // TODO: may be {} - this.head = null; /* where to save gzip header information */ - - /* sliding window */ - this.wbits = 0; /* log base 2 of requested window size */ - this.wsize = 0; /* window size or zero if not using window */ - this.whave = 0; /* valid bytes in the window */ - this.wnext = 0; /* window write index */ - this.window = null; /* allocated sliding window, if needed */ - - /* bit accumulator */ - this.hold = 0; /* input bit accumulator */ - this.bits = 0; /* number of bits in "in" */ - - /* for string and stored block copying */ - this.length = 0; /* literal or length of data to copy */ - this.offset = 0; /* distance back to copy string from */ - - /* for table and code decoding */ - this.extra = 0; /* extra bits needed */ - - /* fixed and dynamic code tables */ - this.lencode = null; /* starting table for length/literal codes */ - this.distcode = null; /* starting table for distance codes */ - this.lenbits = 0; /* index bits for lencode */ - this.distbits = 0; /* index bits for distcode */ - - /* dynamic table building */ - this.ncode = 0; /* number of code length code lengths */ - this.nlen = 0; /* number of length code lengths */ - this.ndist = 0; /* number of distance code lengths */ - this.have = 0; /* number of code lengths in lens[] */ - this.next = null; /* next available space in codes[] */ - - this.lens = new Uint16Array(320); /* temporary storage for code lengths */ - this.work = new Uint16Array(288); /* work area for code table building */ - - /* - because we don't have pointers in js, we use lencode and distcode directly - as buffers so we don't need codes - */ - //this.codes = new Int32Array(ENOUGH); /* space for code tables */ - this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ - this.distdyn = null; /* dynamic table for distance codes (JS specific) */ - this.sane = 0; /* if false, allow invalid distance too far */ - this.back = 0; /* bits back of last unprocessed length/lit */ - this.was = 0; /* initial length of match */ - } - - - const inflateResetKeep = (strm) => { - - if (!strm || !strm.state) { return Z_STREAM_ERROR$1; } - const state = strm.state; - strm.total_in = strm.total_out = state.total = 0; - strm.msg = ''; /*Z_NULL*/ - if (state.wrap) { /* to support ill-conceived Java test suite */ - strm.adler = state.wrap & 1; - } - state.mode = HEAD; - state.last = 0; - state.havedict = 0; - state.dmax = 32768; - state.head = null/*Z_NULL*/; - state.hold = 0; - state.bits = 0; - //state.lencode = state.distcode = state.next = state.codes; - state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS); - state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS); - - state.sane = 1; - state.back = -1; - //Tracev((stderr, "inflate: reset\n")); - return Z_OK$1; + const API_GET_PROVIDER = 'getProvider'; + const GetProviderProtocol = { + service: { + type: String, + required: true, + }, }; + const API_LOGIN = 'login'; + const LoginProtocol = { + provider: String, + scopes: [String, Array], + timeout: Number, + univerifyStyle: Object, + onlyAuthorize: Boolean, + }; + const API_GET_USER_INFO = 'getUserInfo'; + const GetUserInfoProtocol = { + provider: String, + withCredentials: Boolean, + timeout: Number, + lang: String, + }; + const API_GET_USER_PROFILE = 'ggetUserProfilegetUserProfile'; + const GgetUserProfileProtocol = { + provider: String, + withCredentials: Boolean, + timeout: Number, + lang: String, + }; + const API_PRE_LOGIN = 'preLogin'; + const provider = { + UNIVERIFY: 'univerify', + }; + const PreLoginOptions = { + formatArgs: { + provider(value, parmas) { + if (Object.values(provider).indexOf(String(value)) < 0) { + return 'provider error'; + } + }, + }, + }; + const PreLoginProtocol = { + provider: { + type: String, + required: true, + }, + }; + const API_CLOSE_AUTH_VIEW = 'closeAuthView'; + const API_GET_CHECK_BOX_STATE = 'getCheckBoxState'; + const API_GET_UNIVERIFY_MANAGER = 'getUniverifyManager'; - const inflateReset = (strm) => { - - if (!strm || !strm.state) { return Z_STREAM_ERROR$1; } - const state = strm.state; - state.wsize = 0; - state.whave = 0; - state.wnext = 0; - return inflateResetKeep(strm); - + const API_SHREA = 'share'; + const SCENE = [ + 'WXSceneSession', + 'WXSenceTimeline', + 'WXSceneFavorite', + ]; + const SahreOptions = { + formatArgs: { + scene(value, params) { + if (params.provider === 'weixin' && (!value || !SCENE.includes(value))) { + return `分享到微信时,scene必须为以下其中一个:${SCENE.join('、')}`; + } + }, + summary(value, params) { + if (params.type === 1 && !value) { + return '分享纯文本时,summary必填'; + } + }, + href(value, params) { + if (params.type === 0 && !value) { + return '分享图文时,href必填'; + } + }, + imageUrl(value, params) { + if ([0, 2, 5].includes(Number(params.type)) && !value) { + return '分享图文、纯图片、小程序时,imageUrl必填,推荐使用小于20Kb的图片'; + } + }, + mediaUrl(value, params) { + if ([3, 4].includes(Number(params.type)) && !value) { + return '分享音乐、视频时,mediaUrl必填'; + } + }, + miniProgram(value, params) { + if (params.type === 5 && !value) { + return '分享小程序时,miniProgram必填'; + } + }, + }, + }; + const ShareProtocols = { + provider: { + type: String, + required: true, + }, + type: Number, + title: String, + scene: String, + summary: String, + href: String, + imageUrl: String, + mediaUrl: String, + miniProgram: Object, + }; + const API_SHARE_WITH_SYSTEM = 'shareWithSystem'; + const TYPE = [ + 'text', + 'image', + ]; + const ShareWithSystemOptions = { + formatArgs: { + type(value, params) { + if (value && !TYPE.includes(value)) + return '分享参数 type 不正确。只支持text、image'; + params.type = elemInArray(value, TYPE); + }, + }, + }; + const ShareWithSystemProtocols = { + type: String, + summary: String, + href: String, + imageUrl: String, }; + const API_REQUEST_PAYMENT = 'requestPayment'; + const RequestPaymentProtocol = { + provider: { + type: String, + required: true, + }, + orderInfo: { + type: [String, Object], + required: true, + }, + timeStamp: String, + nonceStr: String, + package: String, + signType: String, + paySign: String, + }; - const inflateReset2 = (strm, windowBits) => { - let wrap; - - /* get the state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR$1; } - const state = strm.state; + const API_CREATE_REWARDED_VIDEO_AD = 'createRewardedVideoAd'; + const CreateRewardedVideoAdOptions = { + formatArgs: { + adpid: '', + adUnitId: '', + }, + }; + const CreateRewardedVideoAdProtocol = { + adpid: String, + adUnitId: String, + }; - /* extract wrap request from windowBits parameter */ - if (windowBits < 0) { - wrap = 0; - windowBits = -windowBits; - } - else { - wrap = (windowBits >> 4) + 1; - if (windowBits < 48) { - windowBits &= 15; - } - } + const API_CREATE_FULL_SCREEN_VIDEO_AD = 'createFullScreenVideoAd'; + const CreateFullScreenVideoAdOptions = { + formatArgs: { + adpid: '', + }, + }; + const CreateFullScreenVideoAdProtocol = { + adpid: String, + }; - /* set number of window bits, free window if different */ - if (windowBits && (windowBits < 8 || windowBits > 15)) { - return Z_STREAM_ERROR$1; - } - if (state.window !== null && state.wbits !== windowBits) { - state.window = null; - } + const API_CREATE_INTERSTITIAL_AD = 'createInterstitialAd'; + const CreateInterstitialAdOptions = { + formatArgs: { + adpid: '', + adUnitId: '', + }, + }; + const CreateInterstitialAdProtocol = { + adpid: String, + adUnitId: String, + }; - /* update state and reset the rest of it */ - state.wrap = wrap; - state.wbits = windowBits; - return inflateReset(strm); + const API_CREATE_INTERACTIVE_AD = 'createInteractiveAd'; + const CreateInteractiveAdOptions = { + formatArgs: { + adpid(value, params) { + if (!value) { + return 'adpid should not be empty.'; + } + if (value) + params.adpid = value; + }, + provider(value, params) { + if (!value) { + return 'provider should not be empty.'; + } + if (value) + params.provider = value; + }, + }, + }; + const CreateInteractiveAdProtocol = { + adpid: { + type: String, + required: true, + }, + provider: { + type: String, + required: true, + }, }; + function warpPlusSuccessCallback(resolve, after) { + return function successCallback(data) { + delete data.code; + delete data.message; + if (typeof after === 'function') { + data = after(data); + } + resolve(data); + }; + } + function warpPlusErrorCallback(reject, errMsg) { + return function errorCallback(error) { + error = error || {}; + // 一键登录errorCallback新增 appid、metadata、uid 参数返回 + errMsg = error.message || errMsg || ''; + delete error.message; + reject(errMsg, extend({ code: 0 }, error)); + }; + } + function warpPlusEvent(plusObject, event) { + return function () { + const object = plusObject(); + object(function (data) { + if (data) { + delete data.code; + delete data.message; + } + UniServiceJSBridge.invokeOnCallback(event, data); + }); + }; + } + function warpPlusMethod(plusObject, before, after) { + return function (options, { resolve, reject }) { + const object = plusObject(); + object(extend({}, typeof before === 'function' ? before(options) : options, { + success: warpPlusSuccessCallback(resolve, after), + fail: warpPlusErrorCallback(reject), + })); + }; + } + function isTabBarPage$1(path = '') { + if (!(__uniConfig.tabBar && Array.isArray(__uniConfig.tabBar.list))) { + return false; + } + try { + if (!path) { + const pages = getCurrentPages(); + if (!pages.length) { + return false; + } + const page = pages[pages.length - 1]; + if (!page) { + return false; + } + return page.$page.meta.isTabBar; + } + if (!/^\//.test(path)) { + path = addLeadingSlash(path); + } + const route = getRouteOptions(path); + return route && route.meta.isTabBar; + } + catch (e) { + if ((process.env.NODE_ENV !== 'production')) { + console.error(formatLog('isTabBarPage', e)); + } + } + return false; + } + + const STORAGE_DATA_TYPE = '__TYPE'; + const STORAGE_KEYS = 'uni-storage-keys'; + function parseValue(value) { + const types = ['object', 'string', 'number', 'boolean', 'undefined']; + try { + const object = typeof value === 'string' ? JSON.parse(value) : value; + const type = object.type; + if (types.indexOf(type) >= 0) { + const keys = Object.keys(object); + if (keys.length === 2 && 'data' in object) { + // eslint-disable-next-line valid-typeof + if (typeof object.data === type) { + return object.data; + } + // eslint-disable-next-line no-useless-escape + if (type === 'object' && + /^\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d{3}Z$/.test(object.data)) { + // ISO 8601 格式返回 Date + return new Date(object.data); + } + } + else if (keys.length === 1) { + return ''; + } + } + } + catch (error) { } + } + const setStorageSync = defineSyncApi(API_SET_STORAGE_SYNC, (key, data) => { + const type = typeof data; + const value = type === 'string' + ? data + : JSON.stringify({ + type, + data: data, + }); + try { + if (type === 'string' && parseValue(value) !== undefined) { + plus.storage.setItem(key + STORAGE_DATA_TYPE, type); + } + else { + plus.storage.removeItem(key + STORAGE_DATA_TYPE); + } + plus.storage.setItem(key, value); + } + catch (error) { } + }, SetStorageSyncProtocol); + const setStorage = defineAsyncApi(API_SET_STORAGE, ({ key, data }, { resolve, reject }) => { + const type = typeof data; + const value = type === 'string' + ? data + : JSON.stringify({ + type, + data: data, + }); + try { + const storage = plus.storage; + if (type === 'string' && parseValue(value) !== undefined) { + storage.setItemAsync(key + STORAGE_DATA_TYPE, type); + } + else { + storage.removeItemAsync(key + STORAGE_DATA_TYPE); + } + storage.setItemAsync(key, value, resolve, warpPlusErrorCallback(reject)); + } + catch (error) { + reject(error.message); + } + }, SetStorageProtocol); + function parseGetStorage(type, value) { + let data = value; + if (type !== 'string' || + (type === 'string' && value === '{"type":"undefined"}')) { + try { + // 兼容H5和V3初期历史格式 + let object = JSON.parse(value); + const result = parseValue(object); + if (result !== undefined) { + data = result; + } + else if (type) { + // 兼容App端历史格式 + data = object; + if (typeof object === 'string') { + object = JSON.parse(object); + const objectType = typeof object; + if (objectType === 'number' && type === 'date') { + data = new Date(object); + } + else if (objectType === + (['null', 'array'].indexOf(type) < 0 ? type : 'object')) { + data = object; + } + } + } + } + catch (error) { } + } + return data; + } + const getStorageSync = defineSyncApi(API_GET_STORAGE_SYNC, (key, t) => { + const value = plus.storage.getItem(key); + const typeOrigin = plus.storage.getItem(key + STORAGE_DATA_TYPE) || ''; + const type = typeOrigin.toLowerCase(); + if (typeof value !== 'string') { + return ''; + } + return parseGetStorage(type, value); + }, GetStorageSyncProtocol); + const getStorage = defineAsyncApi(API_GET_STORAGE, ({ key }, { resolve, reject }) => { + const storage = plus.storage; + storage.getItemAsync(key, function (res) { + storage.getItemAsync(key + STORAGE_DATA_TYPE, function (typeRes) { + const typeOrigin = typeRes.data || ''; + const type = typeOrigin.toLowerCase(); + resolve({ + data: parseGetStorage(type, res.data), + }); + }, function () { + const type = ''; + resolve({ + data: parseGetStorage(type, res.data), + }); + }); + }, warpPlusErrorCallback(reject)); + }, GetStorageProtocol); + const removeStorageSync = defineSyncApi(API_REMOVE_STORAGE, (key) => { + plus.storage.removeItem(key + STORAGE_DATA_TYPE); + plus.storage.removeItem(key); + }, RemoveStorageSyncProtocol); + const removeStorage = defineAsyncApi(API_REMOVE_STORAGE, ({ key }, { resolve, reject }) => { + // 兼容App端历史格式 + plus.storage.removeItemAsync(key + STORAGE_DATA_TYPE); + plus.storage.removeItemAsync(key, resolve, warpPlusErrorCallback(reject)); + }, RemoveStorageProtocol); + const clearStorageSync = (defineSyncApi('clearStorageSync', () => { + plus.storage.clear(); + })); + const clearStorage = (defineAsyncApi('clearStorage', (_, { resolve, reject }) => { + plus.storage.clearAsync(resolve, warpPlusErrorCallback(reject)); + })); + const getStorageInfoSync = (defineSyncApi('getStorageInfoSync', () => { + const length = plus.storage.getLength() || 0; + const keys = []; + let currentSize = 0; + for (let index = 0; index < length; index++) { + const key = plus.storage.key(index); + if (key !== STORAGE_KEYS && + (key.indexOf(STORAGE_DATA_TYPE) < 0 || + key.indexOf(STORAGE_DATA_TYPE) + STORAGE_DATA_TYPE.length !== + key.length)) { + const value = plus.storage.getItem(key); + currentSize += key.length + value.length; + keys.push(key); + } + } + return { + keys, + currentSize: Math.ceil((currentSize * 2) / 1024), + limitSize: Number.MAX_VALUE, + }; + })); + const getStorageInfo = (defineAsyncApi('getStorageInfo', (_, { resolve }) => { + resolve(getStorageInfoSync()); + })); + + const getFileInfo$1 = defineAsyncApi(API_GET_FILE_INFO, (options, { resolve, reject }) => { + plus.io.getFileInfo(extend(options, { + success: warpPlusSuccessCallback(resolve), + fail: warpPlusErrorCallback(reject), + })); + }, GetFileInfoProtocol, GetFileInfoOptions); - const inflateInit2 = (strm, windowBits) => { + const openDocument = defineAsyncApi(API_OPEN_DOCUMENT, ({ filePath, fileType }, { resolve, reject }) => { + const errorCallback = warpPlusErrorCallback(reject); + plus.runtime.openDocument(getRealPath(filePath), undefined, resolve, errorCallback); + }, OpenDocumentProtocol, OpenDocumentOptions); - if (!strm) { return Z_STREAM_ERROR$1; } - //strm.msg = Z_NULL; /* in case we return an error */ + function getFileName(path) { + const array = path.split('/'); + return array[array.length - 1]; + } + function getExtName(path) { + const array = path.split('.'); + return array.length > 1 ? '.' + array[array.length - 1] : ''; + } - const state = new InflateState(); + let index$2 = 0; + const SAVED_DIR = 'uniapp_save'; + const SAVE_PATH = `_doc/${SAVED_DIR}`; + function getSavedFileDir(success, fail) { + fail = fail || function () { }; + plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => { + // 请求_doc fs + fs.root.getDirectory(SAVED_DIR, { + // 获取文件保存目录对象 + create: true, + }, success, fail); + }, fail); + } + const saveFile = defineAsyncApi(API_SAVE_FILE, ({ tempFilePath }, { resolve, reject }) => { + const errorCallback = warpPlusErrorCallback(reject); + const fileName = `${Date.now()}${index$2++}${getExtName(tempFilePath)}`; + plus.io.resolveLocalFileSystemURL(tempFilePath, (entry) => { + // 读取临时文件 FileEntry + getSavedFileDir((dir) => { + entry.copyTo(dir, fileName, () => { + // 复制临时文件 FileEntry,为了避免把相册里的文件删除,使用 copy,微信中是要删除临时文件的 + const savedFilePath = SAVE_PATH + '/' + fileName; + resolve({ + savedFilePath, + }); + }, errorCallback); + }, errorCallback); + }, errorCallback); + }, SaveFileProtocol, SaveFileOptions); - //if (state === Z_NULL) return Z_MEM_ERROR; - //Tracev((stderr, "inflate: allocated\n")); - strm.state = state; - state.window = null/*Z_NULL*/; - const ret = inflateReset2(strm, windowBits); - if (ret !== Z_OK$1) { - strm.state = null/*Z_NULL*/; - } - return ret; + const isIOS = plus.os.name === 'iOS'; + let config; + /** + * tabbar显示状态 + */ + let visible = true; + let tabBar; + /** + * 设置角标 + * @param {string} type + * @param {number} index + * @param {string} text + */ + function setTabBarBadge$1(type, index, text) { + if (!tabBar) { + return; + } + if (type === 'none') { + tabBar.hideTabBarRedDot({ + index, + }); + tabBar.removeTabBarBadge({ + index, + }); + } + else if (type === 'text') { + tabBar.setTabBarBadge({ + index, + text, + }); + } + else if (type === 'redDot') { + tabBar.showTabBarRedDot({ + index, + }); + } + } + /** + * 动态设置 tabBar 某一项的内容 + */ + function setTabBarItem$1(index, text, iconPath, selectedIconPath, visible) { + const item = { + index, + }; + if (text !== undefined) { + item.text = text; + } + if (iconPath) { + item.iconPath = getRealPath(iconPath); + } + if (selectedIconPath) { + item.selectedIconPath = getRealPath(selectedIconPath); + } + if (visible !== undefined) { + item.visible = config.list[index].visible = visible; + delete item.index; + const tabbarItems = config.list.map((item) => ({ + visible: item.visible, + })); + tabbarItems[index] = item; + tabBar && tabBar.setTabBarItems({ list: tabbarItems }); + } + else { + tabBar && tabBar.setTabBarItem(item); + } + } + /** + * 动态设置 tabBar 的整体样式 + * @param {Object} style 样式 + */ + function setTabBarStyle$1(style) { + tabBar && tabBar.setTabBarStyle(style); + } + /** + * 隐藏 tabBar + * @param {boolean} animation 是否需要动画效果 + */ + function hideTabBar$1(animation) { + visible = false; + tabBar && + tabBar.hideTabBar({ + animation, + }); + } + /** + * 显示 tabBar + * @param {boolean} animation 是否需要动画效果 + */ + function showTabBar$1(animation) { + visible = true; + tabBar && + tabBar.showTabBar({ + animation, + }); + } + const maskClickCallback = []; + var tabBar$1 = { + id: '0', + init(options, clickCallback) { + if (options && options.list.length) { + config = options; + } + try { + tabBar = weex.requireModule('uni-tabview'); + } + catch (error) { + console.log(`uni.requireNativePlugin("uni-tabview") error ${error}`); + } + tabBar.onMaskClick(() => { + maskClickCallback.forEach((callback) => { + callback(); + }); + }); + tabBar && + tabBar.onClick(({ index }) => { + clickCallback(config.list[index], index); + }); + tabBar && + tabBar.onMidButtonClick(() => { + // publish('onTabBarMidButtonTap', {}) + }); + }, + indexOf(page) { + const itemLength = config && config.list && config.list.length; + if (itemLength) { + for (let i = 0; i < itemLength; i++) { + if (config.list[i].pagePath === page || + config.list[i].pagePath === `${page}.html`) { + return i; + } + } + } + return -1; + }, + switchTab(page) { + const index = this.indexOf(page); + if (index >= 0) { + tabBar && + tabBar.switchSelect({ + index, + }); + return true; + } + return false; + }, + setTabBarBadge: setTabBarBadge$1, + setTabBarItem: setTabBarItem$1, + setTabBarStyle: setTabBarStyle$1, + hideTabBar: hideTabBar$1, + showTabBar: showTabBar$1, + append(webview) { + tabBar && + tabBar.append({ + id: webview.id, + }, ({ code }) => { + if (code !== 0) { + setTimeout(() => { + this.append(webview); + }, 20); + } + }); + }, + get visible() { + return visible; + }, + get height() { + return ((config && config.height ? parseFloat(config.height) : TABBAR_HEIGHT) + + plus.navigator.getSafeAreaInsets().deviceBottom); + }, + // tabBar是否遮挡内容区域 + get cover() { + const array = ['extralight', 'light', 'dark']; + return isIOS && array.indexOf(config.blurEffect) >= 0; + }, + setStyle({ mask }) { + tabBar.setMask({ + color: mask, + }); + }, + addEventListener(_name, callback) { + maskClickCallback.push(callback); + }, + removeEventListener(_name, callback) { + const callbackIndex = maskClickCallback.indexOf(callback); + maskClickCallback.splice(callbackIndex, 1); + }, }; + function getCurrentWebview() { + const page = getCurrentPage(); + if (page) { + return page.$getAppWebview(); + } + return null; + } + function getWebview(page) { + if (page) { + return page.$getAppWebview(); + } + return getCurrentWebview(); + } + let pullDownRefreshWebview = null; + function getPullDownRefreshWebview() { + return pullDownRefreshWebview; + } + function setPullDownRefreshWebview(webview) { + pullDownRefreshWebview = webview; + } + function isTabBarPage(path = '') { + if (!(__uniConfig.tabBar && Array.isArray(__uniConfig.tabBar.list))) { + return false; + } + try { + if (!path) { + const pages = getCurrentPages(); + if (!pages.length) { + return false; + } + const page = pages[pages.length - 1]; + if (!page) { + return false; + } + return page.$page.meta.isTabBar; + } + if (!/^\//.test(path)) { + path = addLeadingSlash(path); + } + const route = __uniRoutes.find((route) => route.path === path); + return route && route.meta.isTabBar; + } + catch (e) { + if (process.env.NODE_ENV !== 'production') { + console.log('getCurrentPages is not ready'); + } + } + return false; + } - const inflateInit = (strm) => { - - return inflateInit2(strm, DEF_WBITS); - }; + function getStatusbarHeight() { + // 横屏时 iOS 获取的状态栏高度错误,进行纠正 + return plus.navigator.isImmersedStatusbar() + ? Math.round(plus.os.name === 'iOS' + ? plus.navigator.getSafeAreaInsets().top + : plus.navigator.getStatusbarHeight()) + : 0; + } + function getStatusBarStyle() { + let style = plus.navigator.getStatusBarStyle(); + if (style === 'UIStatusBarStyleBlackTranslucent' || + style === 'UIStatusBarStyleBlackOpaque' || + style === 'null') { + style = 'light'; + } + else if (style === 'UIStatusBarStyleDefault') { + style = 'dark'; + } + return style; + } + let deviceId; + function deviceId$1 () { + deviceId = deviceId || plus.device.uuid; + return deviceId; + } - /* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ - let virgin = true; + function getScreenInfo() { + const { resolutionWidth, resolutionHeight } = plus.screen.getCurrentSize(); + return { + screenWidth: Math.round(resolutionWidth), + screenHeight: Math.round(resolutionHeight), + }; + } + const getSystemInfoSync = defineSyncApi('getSystemInfoSync', () => { + const platform = plus.os.name.toLowerCase(); + const ios = platform === 'ios'; + const isAndroid = platform === 'android'; + const { screenWidth, screenHeight } = getScreenInfo(); + const statusBarHeight = getStatusbarHeight(); + let safeAreaInsets; + const titleNView = { + height: 0, + cover: false, + }; + const webview = getCurrentWebview(); + if (webview) { + const webStyle = webview.getStyle(); + const style = webStyle && webStyle.titleNView; + if (style && style.type && style.type !== 'none') { + titleNView.height = + style.type === 'transparent' ? 0 : statusBarHeight + NAVBAR_HEIGHT; + titleNView.cover = + style.type === 'transparent' || style.type === 'float'; + } + safeAreaInsets = webview.getSafeAreaInsets(); + } + else { + safeAreaInsets = plus.navigator.getSafeAreaInsets(); + } + const tabBarView = { + height: 0, + cover: false, + }; + if (isTabBarPage$1()) { + tabBarView.height = tabBar$1.visible ? tabBar$1.height : 0; + tabBarView.cover = tabBar$1.cover; + } + const windowTop = titleNView.cover ? titleNView.height : 0; + const windowBottom = tabBarView.cover ? tabBarView.height : 0; + let windowHeight = screenHeight - titleNView.height - tabBarView.height; + let windowHeightReal = screenHeight - + (titleNView.cover ? 0 : titleNView.height) - + (tabBarView.cover ? 0 : tabBarView.height); + const windowWidth = screenWidth; + if ((!tabBarView.height || tabBarView.cover) && + !safeAreaInsets.bottom && + safeAreaInsets.deviceBottom) { + windowHeight -= safeAreaInsets.deviceBottom; + windowHeightReal -= safeAreaInsets.deviceBottom; + } + safeAreaInsets = ios + ? safeAreaInsets + : { + left: 0, + right: 0, + top: titleNView.height && !titleNView.cover ? 0 : statusBarHeight, + bottom: 0, + }; + const safeArea = { + left: safeAreaInsets.left, + right: windowWidth - safeAreaInsets.right, + top: safeAreaInsets.top, + bottom: windowHeightReal - safeAreaInsets.bottom, + width: windowWidth - safeAreaInsets.left - safeAreaInsets.right, + height: windowHeightReal - safeAreaInsets.top - safeAreaInsets.bottom, + }; + return { + brand: plus.device.vendor, + model: plus.device.model, + pixelRatio: plus.screen.scale, + screenWidth, + screenHeight, + windowWidth, + windowHeight, + statusBarHeight, + language: plus.os.language, + system: `${ios ? 'iOS' : isAndroid ? 'Android' : ''} ${plus.os.version}`, + version: plus.runtime.innerVersion, + platform, + SDKVersion: '', + windowTop, + windowBottom, + safeArea, + safeAreaInsets: { + top: safeAreaInsets.top, + right: safeAreaInsets.right, + bottom: safeAreaInsets.bottom, + left: safeAreaInsets.left, + }, + deviceId: deviceId$1(), + }; + }); + const getSystemInfo = defineAsyncApi('getSystemInfo', (_, { resolve }) => { + return resolve(getSystemInfoSync()); + }); - let lenfix, distfix; // We have no pointers in JS, so keep tables separate + const DEVICE_FREQUENCY = 200; + const NETWORK_TYPES = [ + 'unknown', + 'none', + 'ethernet', + 'wifi', + '2g', + '3g', + '4g', + '5g', + ]; + const TEMP_PATH_BASE = '_doc/uniapp_temp'; + const TEMP_PATH = `${TEMP_PATH_BASE}_${Date.now()}`; + let listener$1 = null; + const onCompassChange = (defineOnApi(API_ON_COMPASS, () => { + startCompass(); + })); + const offCompassChange = (defineOffApi(API_OFF_COMPASS, () => { + stopCompass(); + })); + const startCompass = (defineAsyncApi(API_START_COMPASS, (_, { resolve, reject }) => { + if (!listener$1) { + listener$1 = plus.orientation.watchOrientation((res) => { + UniServiceJSBridge.invokeOnCallback(API_ON_COMPASS, { + direction: res.magneticHeading, + }); + }, (err) => { + reject(err.message); + listener$1 = null; + }, { + frequency: DEVICE_FREQUENCY, + }); + } + setTimeout(resolve, DEVICE_FREQUENCY); + })); + const stopCompass = (defineAsyncApi(API_STOP_COMPASS, (_, { resolve }) => { + if (listener$1) { + plus.orientation.clearWatch(listener$1); + listener$1 = null; + } + resolve(); + })); - const fixedtables = (state) => { + const vibrateShort = defineAsyncApi(API_VIBRATE_SHORT, (_, { resolve }) => { + plus.device.vibrate(15); + resolve(); + }); + const vibrateLong = defineAsyncApi(API_VIBRATE_LONG, (_, { resolve }) => { + plus.device.vibrate(400); + resolve(); + }); - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - lenfix = new Int32Array(512); - distfix = new Int32Array(32); + let listener = null; + const onAccelerometerChange = (defineOnApi(API_ON_ACCELEROMETER, () => { + startAccelerometer(); + })); + const offAccelerometerChange = (defineOffApi(API_OFF_ACCELEROMETER, () => { + stopAccelerometer(); + })); + const startAccelerometer = (defineAsyncApi(API_START_ACCELEROMETER, (_, { resolve, reject }) => { + if (!listener) { + listener = plus.accelerometer.watchAcceleration((res) => { + UniServiceJSBridge.invokeOnCallback(API_ON_ACCELEROMETER, { + x: (res && res.xAxis) || 0, + y: (res && res.yAxis) || 0, + z: (res && res.zAxis) || 0, + }); + }, (err) => { + listener = null; + reject(`startAccelerometer:fail ${err.message}`); + }, { + frequency: DEVICE_FREQUENCY, + }); + } + setTimeout(resolve, DEVICE_FREQUENCY); + })); + const stopAccelerometer = (defineAsyncApi(API_STOP_ACCELEROMETER, (_, { resolve }) => { + if (listener) { + plus.accelerometer.clearWatch(listener); + listener = null; + } + resolve(); + })); - /* literal/length table */ - let sym = 0; - while (sym < 144) { state.lens[sym++] = 8; } - while (sym < 256) { state.lens[sym++] = 9; } - while (sym < 280) { state.lens[sym++] = 7; } - while (sym < 288) { state.lens[sym++] = 8; } + const onBluetoothDeviceFound = defineOnApi(API_ON_BLUETOOTH_DEVICE_FOUND, warpPlusEvent(() => plus.bluetooth.onBluetoothDeviceFound.bind(plus.bluetooth), API_ON_BLUETOOTH_DEVICE_FOUND)); + const onBluetoothAdapterStateChange = defineOnApi(API_ON_BLUETOOTH_ADAPTER_STATE_CHANGE, warpPlusEvent(() => plus.bluetooth.onBluetoothAdapterStateChange.bind(plus.bluetooth), API_ON_BLUETOOTH_ADAPTER_STATE_CHANGE)); + const onBLEConnectionStateChange = defineOnApi(API_ON_BLE_CONNECTION_STATE_CHANGE, warpPlusEvent(() => plus.bluetooth.onBLEConnectionStateChange.bind(plus.bluetooth), API_ON_BLE_CONNECTION_STATE_CHANGE)); + const onBLECharacteristicValueChange = defineOnApi(API_ON_BLE_CHARACTERISTIC_VALUE_CHANGE, warpPlusEvent(() => plus.bluetooth.onBLECharacteristicValueChange.bind(plus.bluetooth), API_ON_BLE_CHARACTERISTIC_VALUE_CHANGE)); + const openBluetoothAdapter = defineAsyncApi('openBluetoothAdapter', warpPlusMethod(() => plus.bluetooth.openBluetoothAdapter.bind(plus.bluetooth))); + const closeBluetoothAdapter = defineAsyncApi('closeBluetoothAdapter', warpPlusMethod(() => plus.bluetooth.closeBluetoothAdapter.bind(plus.bluetooth))); + const getBluetoothAdapterState = defineAsyncApi('getBluetoothAdapterState', warpPlusMethod(() => plus.bluetooth.getBluetoothAdapterState)); + const startBluetoothDevicesDiscovery = defineAsyncApi(API_START_BLUETOOTH_DEVICES_DISCOVERY, warpPlusMethod(() => plus.bluetooth.startBluetoothDevicesDiscovery.bind(plus.bluetooth)), StartBluetoothDevicesDiscoveryProtocol); + const stopBluetoothDevicesDiscovery = defineAsyncApi('stopBluetoothDevicesDiscovery', warpPlusMethod(() => plus.bluetooth.stopBluetoothDevicesDiscovery.bind(plus.bluetooth))); + const getBluetoothDevices = defineAsyncApi('getBluetoothDevices', warpPlusMethod(() => plus.bluetooth.getBluetoothDevices.bind(plus.bluetooth))); + const getConnectedBluetoothDevices = defineAsyncApi(API_GET_CONNECTED_BLUETOOTH_DEVICES, warpPlusMethod(() => plus.bluetooth.getConnectedBluetoothDevices), GetConnectedBluetoothDevicesProtocol); + const createBLEConnection = defineAsyncApi(API_CREATE_BLE_CONNECTION, warpPlusMethod(() => plus.bluetooth.createBLEConnection.bind(plus.bluetooth)), CreateBLEConnectionProtocol); + const closeBLEConnection = defineAsyncApi(API_CLOSE_BLE_CONNECTION, warpPlusMethod(() => plus.bluetooth.closeBLEConnection.bind(plus.bluetooth)), CloseBLEConnectionProtocol); + const getBLEDeviceServices = defineAsyncApi(API_GET_BLE_DEVICE_SERVICES, warpPlusMethod(() => plus.bluetooth.getBLEDeviceServices.bind(plus.bluetooth)), GetBLEDeviceServicesProtocol); + const getBLEDeviceCharacteristics = defineAsyncApi(API_GET_BLE_DEVICE_CHARACTERISTICS, warpPlusMethod(() => plus.bluetooth.getBLEDeviceCharacteristics.bind(plus.bluetooth)), GetBLEDeviceCharacteristicsProtocol); + const notifyBLECharacteristicValueChange = defineAsyncApi(API_NOTIFY_BLE_CHARACTERISTIC_VALUE_CHANGE, warpPlusMethod(() => plus.bluetooth.notifyBLECharacteristicValueChange.bind(plus.bluetooth)), NotifyBLECharacteristicValueChangeProtocol); + const readBLECharacteristicValue = defineAsyncApi(API_READ_BLE_CHARACTERISTIC_VALUE, warpPlusMethod(() => plus.bluetooth.readBLECharacteristicValue.bind(plus.bluetooth)), ReadBLECharacteristicValueProtocol); + const writeBLECharacteristicValue = defineAsyncApi(API_WRITE_BLE_CHARACTERISTIC_VALUE, warpPlusMethod(() => plus.bluetooth.writeBLECharacteristicValue.bind(plus.bluetooth)), WriteBLECharacteristicValueProtocol); + const setBLEMTU = defineAsyncApi(API_SET_BLE_MTU, warpPlusMethod(() => plus.bluetooth.setBLEMTU.bind(plus.bluetooth)), SetBLEMTUProtocol); + const getBLEDeviceRSSI = defineAsyncApi(API_GET_BLE_DEVICE_RSSI, warpPlusMethod(() => plus.bluetooth.getBLEDeviceRSSI.bind(plus.bluetooth)), GetBLEDeviceRSSIProtocol); - inftrees(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + const onBeaconUpdate = defineOnApi(API_ON_BEACON_UPDATE, warpPlusEvent(() => plus.ibeacon.onBeaconUpdate.bind(plus.ibeacon), API_ON_BEACON_UPDATE)); + const onBeaconServiceChange = defineOnApi(API_ON_BEACON_SERVICE_CHANGE, warpPlusEvent(() => plus.ibeacon.onBeaconServiceChange.bind(plus.ibeacon), API_ON_BEACON_SERVICE_CHANGE)); + const getBeacons = defineAsyncApi(API_GET_BEACONS, warpPlusMethod(() => plus.ibeacon.getBeacons.bind(plus.ibeacon))); + const startBeaconDiscovery = defineAsyncApi(API_START_BEACON_DISCOVERY, warpPlusMethod(() => plus.ibeacon.startBeaconDiscovery.bind(plus.ibeacon)), StartBeaconDiscoveryProtocol); + const stopBeaconDiscovery = defineAsyncApi(API_STOP_BEACON_DISCOVERY, warpPlusMethod(() => plus.ibeacon.stopBeaconDiscovery.bind(plus.ibeacon))); - /* distance table */ - sym = 0; - while (sym < 32) { state.lens[sym++] = 5; } + const makePhoneCall = defineAsyncApi(API_MAKE_PHONE_CALL, ({ phoneNumber }, { resolve }) => { + plus.device.dial(phoneNumber); + return resolve(); + }, MakePhoneCallProtocol); - inftrees(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + const addPhoneContact = defineAsyncApi(API_ADD_PHONE_CONTACT, ({ photoFilePath = '', nickName, lastName, middleName, firstName, remark, mobilePhoneNumber, weChatNumber, addressCountry, addressState, addressCity, addressStreet, addressPostalCode, organization, title, workFaxNumber, workPhoneNumber, hostNumber, email, url, workAddressCountry, workAddressState, workAddressCity, workAddressStreet, workAddressPostalCode, homeFaxNumber, homePhoneNumber, homeAddressCountry, homeAddressState, homeAddressCity, homeAddressStreet, homeAddressPostalCode, }, { resolve, reject }) => { + plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE, (addressbook) => { + const contact = addressbook.create(); + const name = {}; + if (lastName) { + name.familyName = lastName; + } + if (firstName) { + name.givenName = firstName; + } + if (middleName) { + name.middleName = middleName; + } + contact.name = name; + if (nickName) { + contact.nickname = nickName; + } + if (photoFilePath) { + contact.photos = [ + { + type: 'url', + value: photoFilePath, + }, + ]; + } + if (remark) { + contact.note = remark; + } + const mobilePhone = { + type: 'mobile', + }; + const workPhone = { + type: 'work', + }; + const companyPhone = { + type: 'company', + }; + const homeFax = { + type: 'home fax', + }; + const workFax = { + type: 'work fax', + }; + if (mobilePhoneNumber) { + mobilePhone.value = mobilePhoneNumber; + } + if (workPhoneNumber) { + workPhone.value = workPhoneNumber; + } + if (hostNumber) { + companyPhone.value = hostNumber; + } + if (homeFaxNumber) { + homeFax.value = homeFaxNumber; + } + if (workFaxNumber) { + workFax.value = workFaxNumber; + } + contact.phoneNumbers = [ + mobilePhone, + workPhone, + companyPhone, + homeFax, + workFax, + ]; + if (email) { + contact.emails = [ + { + type: 'home', + value: email, + }, + ]; + } + if (url) { + contact.urls = [ + { + type: 'other', + value: url, + }, + ]; + } + if (weChatNumber) { + contact.ims = [ + { + type: 'other', + value: weChatNumber, + }, + ]; + } + const defaultAddress = { + type: 'other', + preferred: true, + }; + const homeAddress = { + type: 'home', + }; + const companyAddress = { + type: 'company', + }; + if (addressCountry) { + defaultAddress.country = addressCountry; + } + if (addressState) { + defaultAddress.region = addressState; + } + if (addressCity) { + defaultAddress.locality = addressCity; + } + if (addressStreet) { + defaultAddress.streetAddress = addressStreet; + } + if (addressPostalCode) { + defaultAddress.postalCode = addressPostalCode; + } + if (homeAddressCountry) { + homeAddress.country = homeAddressCountry; + } + if (homeAddressState) { + homeAddress.region = homeAddressState; + } + if (homeAddressCity) { + homeAddress.locality = homeAddressCity; + } + if (homeAddressStreet) { + homeAddress.streetAddress = homeAddressStreet; + } + if (homeAddressPostalCode) { + homeAddress.postalCode = homeAddressPostalCode; + } + if (workAddressCountry) { + companyAddress.country = workAddressCountry; + } + if (workAddressState) { + companyAddress.region = workAddressState; + } + if (workAddressCity) { + companyAddress.locality = workAddressCity; + } + if (workAddressStreet) { + companyAddress.streetAddress = workAddressStreet; + } + if (workAddressPostalCode) { + companyAddress.postalCode = workAddressPostalCode; + } + contact.addresses = [ + defaultAddress, + homeAddress, + companyAddress, + ]; + contact.save(() => { + resolve({ + errMsg: 'addPhoneContact:ok', + }); + }, (e) => { + reject('addPhoneContact:fail'); + }); + }, (e) => { + reject('addPhoneContact:fail'); + }); + }, MakePhoneCallProtocol); - /* do this just once */ - virgin = false; - } + function requireNativePlugin(pluginName) { + if (typeof weex !== 'undefined') { + return weex.requireModule(pluginName); + } + return __requireNativePlugin__(pluginName); + } + function sendNativeEvent(event, data, callback) { + // 实时获取weex module(weex可能会变化,比如首页nvue加速显示时) + return requireNativePlugin('plus').sendNativeEvent(event, data, callback); + } - state.lencode = lenfix; - state.lenbits = 9; - state.distcode = distfix; - state.distbits = 5; - }; + const getClipboardData = defineAsyncApi(API_GET_CLIPBOARD_DATA, (_, { resolve, reject }) => { + const clipboard = requireNativePlugin('clipboard'); + clipboard.getString((ret) => { + if (ret.result === 'success') { + resolve({ + data: ret.data, + }); + } + else { + reject('getClipboardData:fail'); + } + }); + }); + const setClipboardData = defineAsyncApi(API_SET_CLIPBOARD_DATA, (options, { resolve }) => { + const clipboard = requireNativePlugin('clipboard'); + clipboard.setString(options.data); + resolve(); + }, SetClipboardDataProtocol, SetClipboardDataOptions); + const API_ON_NETWORK_STATUS_CHANGE = 'onNetworkStatusChange'; + function networkListener() { + getNetworkType().then(({ networkType }) => { + UniServiceJSBridge.invokeOnCallback(API_ON_NETWORK_STATUS_CHANGE, { + isConnected: networkType !== 'none', + networkType, + }); + }); + } + // 注意:框架对on类的API已做了统一的前置处理(仅首次调用on方法时,会调用具体的平台on实现,后续调用,框架不会再调用,实现时,直接监听平台事件即可) + const onNetworkStatusChange = defineOnApi(API_ON_NETWORK_STATUS_CHANGE, () => { + plus.globalEvent.addEventListener('netchange', networkListener); + }); + // 注意:框架对off类的API已做了统一的前置处理(仅当框架内不存在对应的on监听时,会调用具体的平台off实现,若还存在事件,框架不会再调用,具体实现时,直接移除平台事件即可) + const offNetworkStatusChange = defineOffApi('offNetworkStatusChange', () => { + plus.globalEvent.removeEventListener('netchange', networkListener); + }); + const getNetworkType = defineAsyncApi('getNetworkType', (_args, { resolve }) => { + let networkType = NETWORK_TYPES[plus.networkinfo.getCurrentType()] || 'unknown'; + return resolve({ networkType }); + }); - /* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. + function checkIsSupportFaceID() { + const platform = plus.os.name.toLowerCase(); + if (platform !== 'ios') { + return false; + } + const faceID = requireNativePlugin('faceID'); + return !!(faceID && faceID.isSupport()); + } + function checkIsSupportFingerPrint() { + return !!(plus.fingerprint && plus.fingerprint.isSupport()); + } + const baseCheckIsSupportSoterAuthentication = (resolve) => { + const supportMode = []; + if (checkIsSupportFingerPrint()) { + supportMode.push('fingerPrint'); + } + if (checkIsSupportFaceID()) { + supportMode.push('facial'); + } + resolve && + resolve({ + supportMode, + }); + return { + supportMode, + errMsg: 'checkIsSupportSoterAuthentication:ok', + }; + }; + const checkIsSupportSoterAuthentication = defineAsyncApi(API_CHECK_IS_SUPPORT_SOTER_AUTHENTICATION, (_, { resolve, reject }) => { + baseCheckIsSupportSoterAuthentication(resolve); + }); + const basecheckIsSoterEnrolledInDevice = ({ checkAuthMode, resolve, reject, }) => { + const wrapReject = (errMsg, errRes) => reject && reject(errMsg, errRes); + const wrapResolve = (res) => resolve && resolve(res); + if (checkAuthMode === 'fingerPrint') { + if (checkIsSupportFingerPrint()) { + const isEnrolled = plus.fingerprint.isKeyguardSecure() && + plus.fingerprint.isEnrolledFingerprints(); + wrapResolve({ isEnrolled }); + return { + isEnrolled, + errMsg: 'checkIsSoterEnrolledInDevice:ok', + }; + } + wrapReject('not support', { isEnrolled: false }); + return { + isEnrolled: false, + errMsg: 'checkIsSoterEnrolledInDevice:fail not support', + }; + } + else if (checkAuthMode === 'facial') { + if (checkIsSupportFaceID()) { + const faceID = requireNativePlugin('faceID'); + const isEnrolled = faceID && faceID.isKeyguardSecure() && faceID.isEnrolledFaceID(); + wrapResolve({ isEnrolled }); + return { + isEnrolled, + errMsg: 'checkIsSoterEnrolledInDevice:ok', + }; + } + wrapReject('not support', { isEnrolled: false }); + return { + isEnrolled: false, + errMsg: 'checkIsSoterEnrolledInDevice:fail not support', + }; + } + wrapReject('not support', { isEnrolled: false }); + return { + isEnrolled: false, + errMsg: 'checkIsSoterEnrolledInDevice:fail not support', + }; + }; + const checkIsSoterEnrolledInDevice = defineAsyncApi(API_CHECK_IS_SOTER_ENROLLED_IN_DEVICE, ({ checkAuthMode }, { resolve, reject }) => { + basecheckIsSoterEnrolledInDevice({ checkAuthMode, resolve, reject }); + }, CheckIsSoterEnrolledInDeviceProtocols, CheckIsSoterEnrolledInDeviceOptions); + const startSoterAuthentication = defineAsyncApi(API_START_SOTER_AUTHENTICATION, ({ requestAuthModes, challenge = false, authContent }, { resolve, reject }) => { + /* + 以手机不支持facial未录入fingerPrint为例 + requestAuthModes:['facial','fingerPrint']时,微信小程序返回值里的authMode为"fingerPrint" + requestAuthModes:['fingerPrint','facial']时,微信小程序返回值里的authMode为"fingerPrint" + 即先过滤不支持的方式之后再判断是否录入 + 微信小程序errCode(从企业号开发者中心查到如下文档): + 0:识别成功 'startSoterAuthentication:ok' + 90001:本设备不支持SOTER 'startSoterAuthentication:fail not support soter' + 90002:用户未授权微信使用该生物认证接口 注:APP端暂不支持 + 90003:请求使用的生物认证方式不支持 'startSoterAuthentication:fail no corresponding mode' + 90004:未传入challenge或challenge长度过长(最长512字符)注:APP端暂不支持 + 90005:auth_content长度超过限制(最长42个字符)注:微信小程序auth_content指纹识别时无效果,faceID暂未测试 + 90007:内部错误 'startSoterAuthentication:fail auth key update error' + 90008:用户取消授权 'startSoterAuthentication:fail cancel' + 90009:识别失败 'startSoterAuthentication:fail' + 90010:重试次数过多被冻结 'startSoterAuthentication:fail authenticate freeze. please try again later' + 90011:用户未录入所选识别方式 'startSoterAuthentication:fail no fingerprint enrolled' + */ + initI18nStartSoterAuthenticationMsgsOnce(); + const { t } = useI18n(); + const supportMode = baseCheckIsSupportSoterAuthentication().supportMode; + if (supportMode.length === 0) { + return { + authMode: 'fingerPrint', + errCode: 90001, + errMsg: 'startSoterAuthentication:fail', + }; + } + const supportRequestAuthMode = []; + requestAuthModes.map((item, index) => { + if (supportMode.indexOf(item) > -1) { + supportRequestAuthMode.push(item); + } + }); + if (supportRequestAuthMode.length === 0) { + return { + authMode: 'fingerPrint', + errCode: 90003, + errMsg: 'startSoterAuthentication:fail no corresponding mode', + }; + } + const enrolledRequestAuthMode = []; + supportRequestAuthMode.map((item, index) => { + const checked = basecheckIsSoterEnrolledInDevice({ + checkAuthMode: item, + }).isEnrolled; + if (checked) { + enrolledRequestAuthMode.push(item); + } + }); + if (enrolledRequestAuthMode.length === 0) { + return { + authMode: supportRequestAuthMode[0], + errCode: 90011, + errMsg: `startSoterAuthentication:fail no ${supportRequestAuthMode[0]} enrolled`, + }; + } + const realAuthMode = enrolledRequestAuthMode[0]; + if (realAuthMode === 'fingerPrint') { + if (plus.os.name.toLowerCase() === 'android') { + plus.nativeUI.showWaiting(authContent || t('uni.startSoterAuthentication.authContent')).onclose = function () { + plus.fingerprint.cancel(); + }; + } + plus.fingerprint.authenticate(() => { + plus.nativeUI.closeWaiting(); + resolve({ + authMode: realAuthMode, + errCode: 0, + }); + }, (e) => { + const res = { + authMode: realAuthMode, + }; + switch (e.code) { + case e.AUTHENTICATE_MISMATCH: + // 微信小程序没有这个回调,如果要实现此处回调需要多次触发需要用事件publish实现 + // invoke(callbackId, { + // authMode: realAuthMode, + // errCode: 90009, + // errMsg: 'startSoterAuthentication:fail' + // }) + break; + case e.AUTHENTICATE_OVERLIMIT: + // 微信小程序在第一次重试次数超限时安卓IOS返回不一致,安卓端会返回次数超过限制(errCode: 90010),IOS端会返回认证失败(errCode: 90009)。APP-IOS实际运行时不会次数超限,超过指定次数之后会弹出输入密码的界面 + plus.nativeUI.closeWaiting(); + reject('authenticate freeze. please try again later', extend(res, { + errCode: 90010, + })); + break; + case e.CANCEL: + plus.nativeUI.closeWaiting(); + reject('cancel', extend(res, { + errCode: 90008, + })); + break; + default: + plus.nativeUI.closeWaiting(); + reject('', extend(res, { + errCode: 90007, + })); + break; + } + }, { + message: authContent, + }); + } + else if (realAuthMode === 'facial') { + const faceID = requireNativePlugin('faceID'); + faceID.authenticate({ + message: authContent, + }, (e) => { + const res = { + authMode: realAuthMode, + }; + if (e.type === 'success' && e.code === 0) { + resolve({ + authMode: realAuthMode, + errCode: 0, + }); + } + else { + switch (e.code) { + case 4: + reject('', extend(res, { + errCode: 90009, + })); + break; + case 5: + reject('authenticate freeze. please try again later', extend(res, { + errCode: 90010, + })); + break; + case 6: + reject('', extend(res, { + errCode: 90008, + })); + break; + default: + reject('', extend(res, { + errCode: 90007, + })); + break; + } + } + }); + } + }, StartSoterAuthenticationProtocols, StartSoterAuthenticationOptions); - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ - const updatewindow = (strm, src, end, copy) => { + let plus_; + let weex_; + let BroadcastChannel_; + function getRuntime() { + return typeof window === 'object' && + typeof navigator === 'object' && + typeof document === 'object' + ? 'webview' + : 'v8'; + } + function getPageId() { + return plus_.webview.currentWebview().id; + } + let channel; + let globalEvent$1; + const callbacks$2 = {}; + function onPlusMessage$1(res) { + const message = res.data && res.data.__message; + if (!message || !message.__page) { + return; + } + const pageId = message.__page; + const callback = callbacks$2[pageId]; + callback && callback(message); + if (!message.keep) { + delete callbacks$2[pageId]; + } + } + function addEventListener(pageId, callback) { + if (getRuntime() === 'v8') { + if (BroadcastChannel_) { + channel && channel.close(); + channel = new BroadcastChannel_(getPageId()); + channel.onmessage = onPlusMessage$1; + } + else if (!globalEvent$1) { + globalEvent$1 = weex_.requireModule('globalEvent'); + globalEvent$1.addEventListener('plusMessage', onPlusMessage$1); + } + } + else { + // @ts-ignore + window.__plusMessage = onPlusMessage$1; + } + callbacks$2[pageId] = callback; + } + class Page { + constructor(webview) { + this.webview = webview; + } + sendMessage(data) { + const message = JSON.parse(JSON.stringify({ + __message: { + data, + }, + })); + const id = this.webview.id; + if (BroadcastChannel_) { + const channel = new BroadcastChannel_(id); + channel.postMessage(message); + } + else { + plus_.webview.postMessageToUniNView && + plus_.webview.postMessageToUniNView(message, id); + } + } + close() { + this.webview.close(); + } + } + function showPage({ context = {}, url, data = {}, style = {}, onMessage, onClose, }) { + // eslint-disable-next-line + plus_ = context.plus || plus; + // eslint-disable-next-line + weex_ = context.weex || (typeof weex === 'object' ? weex : null); + // eslint-disable-next-line + BroadcastChannel_ = + context.BroadcastChannel || + (typeof BroadcastChannel === 'object' ? BroadcastChannel : null); + const titleNView = { + autoBackButton: true, + titleSize: '17px', + }; + const pageId = `page${Date.now()}`; + style = extend({}, style); + if (style.titleNView !== false && style.titleNView !== 'none') { + style.titleNView = extend(titleNView, style.titleNView); + } + const defaultStyle = { + top: 0, + bottom: 0, + usingComponents: {}, + popGesture: 'close', + scrollIndicator: 'none', + animationType: 'pop-in', + animationDuration: 200, + uniNView: { + path: `${(typeof process === 'object' && + process.env && + process.env.VUE_APP_TEMPLATE_PATH) || + ''}/${url}.js`, + defaultFontSize: plus_.screen.resolutionWidth / 20, + viewport: plus_.screen.resolutionWidth, + }, + }; + style = extend(defaultStyle, style); + const page = plus_.webview.create('', pageId, style, { + extras: { + from: getPageId(), + runtime: getRuntime(), + data, + useGlobalEvent: !BroadcastChannel_, + }, + }); + page.addEventListener('close', onClose); + addEventListener(pageId, (message) => { + if (typeof onMessage === 'function') { + onMessage(message.data); + } + if (!message.keep) { + page.close('auto'); + } + }); + page.show(style.animationType, style.animationDuration); + return new Page(page); + } - let dist; - const state = strm.state; + const scanCode = defineAsyncApi(API_SCAN_CODE, (options, { resolve, reject }) => { + initI18nScanCodeMsgsOnce(); + const { t } = useI18n(); + const statusBarStyle = getStatusBarStyle(); + const isDark = statusBarStyle !== 'light'; + let result; + let success = false; + const page = showPage({ + url: '__uniappscan', + data: Object.assign({}, options, { + messages: { + fail: t('uni.scanCode.fail'), + 'flash.on': t('uni.scanCode.flash.on'), + 'flash.off': t('uni.scanCode.flash.off'), + }, + }), + style: { + // @ts-expect-error + animationType: options.animationType || 'pop-in', + titleNView: { + autoBackButton: true, + type: 'float', + // @ts-expect-error + titleText: options.titleText || t('uni.scanCode.title'), + titleColor: '#ffffff', + backgroundColor: 'rgba(0,0,0,0)', + buttons: !options.onlyFromCamera + ? [ + { + // @ts-expect-error + text: options.albumText || t('uni.scanCode.album'), + fontSize: '17px', + width: '60px', + onclick: () => { + page.sendMessage({ + type: 'gallery', + }); + }, + }, + ] + : [], + }, + popGesture: 'close', + background: '#000000', + backButtonAutoControl: 'close', + }, + onMessage({ event, detail, }) { + result = detail; + success = event === 'marked'; + }, + onClose() { + if (isDark) { + plus.navigator.setStatusBarStyle('dark'); + } + result + ? success + ? (delete result.message, resolve(result)) + : reject(result.message) + : reject('cancel'); + }, + }); + if (isDark) { + plus.navigator.setStatusBarStyle('light'); + page.webview.addEventListener('popGesture', ({ type, result }) => { + if (type === 'start') { + plus.navigator.setStatusBarStyle('dark'); + } + else if (type === 'end' && !result) { + plus.navigator.setStatusBarStyle('light'); + } + }); + } + }, ScanCodeProtocol); - /* if it hasn't been done already, allocate space for the window */ - if (state.window === null) { - state.wsize = 1 << state.wbits; - state.wnext = 0; - state.whave = 0; + const onThemeChange = defineOnApi(ON_THEME_CHANGE, () => { + UniServiceJSBridge.on(ON_THEME_CHANGE, (res) => { + UniServiceJSBridge.invokeOnCallback(ON_THEME_CHANGE, res); + }); + }); - state.window = new Uint8Array(state.wsize); - } + const getScreenBrightness = defineAsyncApi(API_GET_SCREEN_BRIGHTNESS, (_, { resolve }) => { + const value = plus.screen.getBrightness(false); + resolve({ value }); + }); + const setScreenBrightness = defineAsyncApi(API_SET_SCREEN_BRIGHTNESS, (options, { resolve }) => { + plus.screen.setBrightness(options.value, false); + resolve(); + }); + const setKeepScreenOn = defineAsyncApi(API_SET_KEEP_SCREEN_ON, (options, { resolve }) => { + plus.device.setWakelock(!!options.keepScreenOn); + resolve(); + }); - /* copy state->wsize or less output bytes into the circular window */ - if (copy >= state.wsize) { - state.window.set(src.subarray(end - state.wsize, end), 0); - state.wnext = 0; - state.whave = state.wsize; - } - else { - dist = state.wsize - state.wnext; - if (dist > copy) { - dist = copy; - } - //zmemcpy(state->window + state->wnext, end - copy, dist); - state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext); - copy -= dist; - if (copy) { - //zmemcpy(state->window, end - copy, copy); - state.window.set(src.subarray(end - copy, end), 0); - state.wnext = copy; - state.whave = state.wsize; - } - else { - state.wnext += dist; - if (state.wnext === state.wsize) { state.wnext = 0; } - if (state.whave < state.wsize) { state.whave += dist; } - } - } - return 0; - }; + const getImageInfo = defineAsyncApi(API_GET_IMAGE_INFO, (options, { resolve, reject }) => { + const path = TEMP_PATH + '/download/'; + plus.io.getImageInfo(extend(options, { + savePath: path, + filename: path, + success: warpPlusSuccessCallback(resolve), + fail: warpPlusErrorCallback(reject), + })); + }, GetImageInfoProtocol, GetImageInfoOptions); + + const getVideoInfo = defineAsyncApi(API_GET_VIDEO_INFO, (options, { resolve, reject }) => { + plus.io.getVideoInfo({ + filePath: options.src, + success: (data) => { + return { + orientation: data.orientation, + type: data.type, + duration: data.duration, + size: data.size, + height: data.height, + width: data.width, + fps: data.fps || 30, + bitrate: data.bitrate, + }; + }, + fail: warpPlusErrorCallback(reject), + }); + }, GetVideoInfoProtocol, GetVideoInfoOptions); + const previewImage = defineAsyncApi(API_PREVIEW_IMAGE, ({ current = 0, indicator = 'number', loop = false, urls, longPressActions }, { resolve, reject }) => { + initI18nChooseImageMsgsOnce(); + const { t } = useI18n(); + urls = urls.map((url) => getRealPath(url)); + const index = Number(current); + if (isNaN(index)) { + current = urls.indexOf(getRealPath(current)); + current = current < 0 ? 0 : current; + } + else { + current = index; + } + plus.nativeUI.previewImage(urls, { + current, + indicator, + loop, + onLongPress: function (res) { + let itemList = []; + let itemColor = ''; + const hasLongPressActions = longPressActions && isPlainObject(longPressActions); + if (!hasLongPressActions) { + itemList = [t('uni.previewImage.button.save')]; + itemColor = '#000000'; + } + else { + itemList = longPressActions.itemList + ? longPressActions.itemList + : []; + itemColor = longPressActions.itemColor + ? longPressActions.itemColor + : '#000000'; + } + const options = { + buttons: itemList.map((item) => ({ + title: item, + color: itemColor, + })), + cancel: t('uni.previewImage.cancel'), + }; + plus.nativeUI.actionSheet(options, (e) => { + if (e.index > 0) { + if (hasLongPressActions) { + typeof longPressActions.success === 'function' && + longPressActions.success({ + tapIndex: e.index - 1, + index: res.index, + }); + return; + } + plus.gallery.save(res.url, () => { + plus.nativeUI.toast(t('uni.previewImage.save.success')); + }, function () { + plus.nativeUI.toast(t('uni.previewImage.save.fail')); + }); + } + else if (hasLongPressActions) { + typeof longPressActions.fail === 'function' && + longPressActions.fail({ + errMsg: 'showActionSheet:fail cancel', + }); + } + }); + }, + }); + resolve(); + }, PreviewImageProtocol, PreviewImageOptions); + const closePreviewImage = defineAsyncApi(API_CLOSE_PREVIEW_IMAGE, (_, { resolve, reject }) => { + try { + // @ts-expect-error + plus.nativeUI.closePreviewImage(); + resolve(); + } + catch (error) { + reject(); + } + }); - const inflate$2 = (strm, flush) => { + let recorder; + let recording = false; + let recordTimeout; + const publishRecorderStateChange = (state, res = {}) => { + onRecorderStateChange(extend({ + state, + }, res)); + }; + const Recorder = { + start({ duration = 60000, sampleRate, numberOfChannels, encodeBitRate, format = 'mp3', frameSize, + // audioSource = 'auto', + }) { + if (recording) { + return publishRecorderStateChange('start'); + } + recorder = plus.audio.getRecorder(); + recorder.record({ + format, + samplerate: sampleRate ? String(sampleRate) : '', + filename: TEMP_PATH + '/recorder/', + }, (res) => publishRecorderStateChange('stop', { + tempFilePath: res, + }), (err) => publishRecorderStateChange('error', { + errMsg: err.message, + })); + recordTimeout = setTimeout(() => { + Recorder.stop(); + }, duration); + publishRecorderStateChange('start'); + recording = true; + }, + stop() { + if (recording) { + recorder.stop(); + recording = false; + recordTimeout && clearTimeout(recordTimeout); + } + }, + pause() { + if (recording) { + publishRecorderStateChange('error', { + errMsg: 'Unsupported operation: pause', + }); + } + }, + resume() { + if (recording) { + publishRecorderStateChange('error', { + errMsg: 'Unsupported operation: resume', + }); + } + }, + }; + const callbacks$1 = { + pause: null, + resume: null, + start: null, + stop: null, + error: null, + }; + function onRecorderStateChange(res) { + const state = res.state; + delete res.state; + delete res.errMsg; + if (state && typeof callbacks$1[state] === 'function') { + callbacks$1[state](res); + } + } + class RecorderManager { + constructor() { } + onError(callback) { + callbacks$1.error = callback; + } + onFrameRecorded(callback) { } + onInterruptionBegin(callback) { } + onInterruptionEnd(callback) { } + onPause(callback) { + callbacks$1.pause = callback; + } + onResume(callback) { + callbacks$1.resume = callback; + } + onStart(callback) { + callbacks$1.start = callback; + } + onStop(callback) { + callbacks$1.stop = callback; + } + pause() { + Recorder.pause(); + } + resume() { + Recorder.resume(); + } + start(options) { + Recorder.start(options); + } + stop() { + Recorder.stop(); + } + } + let recorderManager; + const getRecorderManager = defineSyncApi(API_GET_RECORDER_MANAGER, () => recorderManager || (recorderManager = new RecorderManager())); - let state; - let input, output; // input/output buffers - let next; /* next input INDEX */ - let put; /* next output INDEX */ - let have, left; /* available input and output */ - let hold; /* bit buffer */ - let bits; /* bits in bit buffer */ - let _in, _out; /* save starting available input and output */ - let copy; /* number of stored or match bytes to copy */ - let from; /* where to copy match bytes from */ - let from_source; - let here = 0; /* current decoding table entry */ - let here_bits, here_op, here_val; // paked "here" denormalized (JS specific) - //let last; /* parent table entry */ - let last_bits, last_op, last_val; // paked "last" denormalized (JS specific) - let len; /* length to copy for repeats, bits to drop */ - let ret; /* return code */ - const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */ - let opts; + const saveVideoToPhotosAlbum = defineAsyncApi(API_SAVE_VIDEO_TO_PHOTOS_ALBUM, (options, { resolve, reject }) => { + plus.gallery.save(options.filePath, warpPlusSuccessCallback(resolve), warpPlusErrorCallback(reject)); + }, SaveVideoToPhotosAlbumProtocol, SaveVideoToPhotosAlbumOptions); - let n; // temporary variable for NEED_BITS + const saveImageToPhotosAlbum = defineAsyncApi(API_SAVE_IMAGE_TO_PHOTOS_ALBUM, (options, { resolve, reject }) => { + plus.gallery.save(options.filePath, warpPlusSuccessCallback(resolve), warpPlusErrorCallback(reject)); + }, SaveImageToPhotosAlbumProtocol, SaveImageToPhotosAlbumOptions); - const order = /* permutation of code lengths */ - new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]); + const compressImage = defineAsyncApi(API_COMPRESS_IMAGE, (options, { resolve, reject }) => { + const dst = `${TEMP_PATH}/compressed/${Date.now()}_${getFileName(options.src)}`; + plus.zip.compressImage(extend({}, options, { + dst, + }), () => { + resolve({ + tempFilePath: dst, + }); + }, reject); + }, CompressImageProtocol, CompressImageOptions); + const compressVideo = defineAsyncApi(API_COMPRESS_VIDEO, (options, { resolve, reject }) => { + const filename = `${TEMP_PATH}/compressed/${Date.now()}_${getFileName(options.src)}`; + plus.zip.compressVideo(extend({}, options, { + filename, + }), () => { + resolve({ + tempFilePath: filename, + }); + }, reject); + }, CompressVideoProtocol, CompressVideoOptions); - if (!strm || !strm.state || !strm.output || - (!strm.input && strm.avail_in !== 0)) { - return Z_STREAM_ERROR$1; - } + /** + * 获取文件信息 + * @param {string} filePath 文件路径 + * @returns {Promise} 文件信息Promise + */ + function getFileInfo(filePath) { + return new Promise((resolve, reject) => { + plus.io.resolveLocalFileSystemURL(filePath, function (entry) { + entry.getMetadata(resolve, reject, false); + }, reject); + }); + } + const chooseImage = defineAsyncApi(API_CHOOSE_IMAGE, ({ count, sizeType, sourceType, crop } = {}, { resolve, reject }) => { + initI18nChooseImageMsgsOnce(); + const { t } = useI18n(); + const errorCallback = warpPlusErrorCallback(reject); + function successCallback(paths) { + const tempFiles = []; + const tempFilePaths = []; + Promise.all(paths.map((path) => getFileInfo(path))) + .then((filesInfo) => { + filesInfo.forEach((file, index) => { + const path = paths[index]; + tempFilePaths.push(path); + tempFiles.push({ path, size: file.size }); + }); + resolve({ + tempFilePaths, + tempFiles, + }); + }) + .catch(errorCallback); + } + function openCamera() { + const camera = plus.camera.getCamera(); + camera.captureImage((path) => successCallback([path]), errorCallback, { + filename: TEMP_PATH + '/camera/', + resolution: 'high', + crop, + // @ts-expect-error + sizeType, + }); + } + function openAlbum() { + // @ts-ignore 5+此API分单选和多选,多选返回files:string[] + plus.gallery.pick(({ files }) => successCallback(files), errorCallback, { + maximum: count, + multiple: true, + system: false, + filename: TEMP_PATH + '/gallery/', + permissionAlert: true, + crop, + // @ts-expect-error + sizeType, + }); + } + if (sourceType.length === 1) { + if (sourceType.includes('album')) { + openAlbum(); + return; + } + else if (sourceType.includes('camera')) { + openCamera(); + return; + } + } + plus.nativeUI.actionSheet({ + cancel: t('uni.chooseImage.cancel'), + buttons: [ + { + title: t('uni.chooseImage.sourceType.camera'), + }, + { + title: t('uni.chooseImage.sourceType.album'), + }, + ], + }, (e) => { + switch (e.index) { + case 1: + openCamera(); + break; + case 2: + openAlbum(); + break; + default: + errorCallback(); + break; + } + }); + }, ChooseImageProtocol, ChooseImageOptions); - state = strm.state; - if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + const chooseVideo = defineAsyncApi(API_CHOOSE_VIDEO, ({ sourceType, compressed, maxDuration, camera }, { resolve, reject }) => { + initI18nChooseVideoMsgsOnce(); + const { t } = useI18n(); + const errorCallback = warpPlusErrorCallback(reject); + function successCallback(tempFilePath) { + plus.io.getVideoInfo({ + filePath: tempFilePath, + success(videoInfo) { + const result = { + errMsg: 'chooseVideo:ok', + tempFilePath: tempFilePath, + size: videoInfo.size, + duration: videoInfo.duration, + width: videoInfo.width, + height: videoInfo.height, + }; + // @ts-expect-error tempFile、name 仅H5支持 + resolve(result); + }, + fail: errorCallback, + }); + } + function openAlbum() { + plus.gallery.pick( + // @ts-ignore 5+此API分单选和多选,多选返回files:string[] + ({ files }) => successCallback(files[0]), errorCallback, { + filter: 'video', + system: false, + // 不启用 multiple 时 system 无效 + multiple: true, + maximum: 1, + filename: TEMP_PATH + '/gallery/', + permissionAlert: true, + // @ts-expect-error 新增参数,用于视频压缩 + videoCompress: compressed, + }); + } + function openCamera() { + const plusCamera = plus.camera.getCamera(); + plusCamera.startVideoCapture(successCallback, errorCallback, { + index: camera === 'front' ? '2' : '1', + videoMaximumDuration: maxDuration, + filename: TEMP_PATH + '/camera/', + // @ts-expect-error 新增参数,用于视频压缩 + videoCompress: compressed, + }); + } + if (sourceType.length === 1) { + if (sourceType.includes('album')) { + openAlbum(); + return; + } + else if (sourceType.includes('camera')) { + openCamera(); + return; + } + } + plus.nativeUI.actionSheet({ + cancel: t('uni.chooseVideo.cancel'), + buttons: [ + { + title: t('uni.chooseVideo.sourceType.camera'), + }, + { + title: t('uni.chooseVideo.sourceType.album'), + }, + ], + }, (e) => { + switch (e.index) { + case 1: + openCamera(); + break; + case 2: + openAlbum(); + break; + default: + errorCallback(); + break; + } + }); + }, ChooseVideoProtocol, ChooseVideoOptions); + const showKeyboard = defineAsyncApi(API_SHOW_KEYBOARD, (_, { resolve }) => { + plus.key.showSoftKeybord(); + resolve(); + }); + const hideKeyboard = defineAsyncApi(API_HIDE_KEYBOARD, (_, { resolve }) => { + plus.key.hideSoftKeybord(); + resolve(); + }); + function onKeyboardHeightChangeCallback(res) { + UniServiceJSBridge.invokeOnCallback(ON_KEYBOARD_HEIGHT_CHANGE, res); + } + const onKeyboardHeightChange = defineOnApi(ON_KEYBOARD_HEIGHT_CHANGE, () => { + UniServiceJSBridge.on(ON_KEYBOARD_HEIGHT_CHANGE, onKeyboardHeightChangeCallback); + }); + const offKeyboardHeightChange = defineOffApi(ON_KEYBOARD_HEIGHT_CHANGE, () => { + UniServiceJSBridge.off(ON_KEYBOARD_HEIGHT_CHANGE, onKeyboardHeightChangeCallback); + }); - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- + class DownloadTask { + constructor(downloader) { + this._callbacks = []; + this._downloader = downloader; + downloader.addEventListener('statechanged', (download, status) => { + if (download.downloadedSize && download.totalSize) { + this._callbacks.forEach((callback) => { + callback({ + progress: Math.round((download.downloadedSize / download.totalSize) * 100), + totalBytesWritten: download.downloadedSize, + totalBytesExpectedToWrite: download.totalSize, + }); + }); + } + }); + } + abort() { + this._downloader.abort(); + } + onProgressUpdate(callback) { + if (typeof callback !== 'function') { + return; + } + this._callbacks.push(callback); + } + offProgressUpdate(callback) { + const index = this._callbacks.indexOf(callback); + if (index >= 0) { + this._callbacks.splice(index, 1); + } + } + onHeadersReceived(callback) { + throw new Error('Method not implemented.'); + } + offHeadersReceived(callback) { + throw new Error('Method not implemented.'); + } + } + const downloadFile = defineTaskApi(API_DOWNLOAD_FILE, ({ url, header, timeout }, { resolve, reject }) => { + timeout = + (timeout || + (__uniConfig.networkTimeout && __uniConfig.networkTimeout.request) || + 60 * 1000) / 1000; + const downloader = plus.downloader.createDownload(url, { + timeout, + filename: TEMP_PATH + '/download/', + // 需要与其它平台上的表现保持一致,不走重试的逻辑。 + retry: 0, + retryInterval: 0, + }, (download, statusCode) => { + if (statusCode) { + resolve({ + tempFilePath: download.filename, + statusCode, + }); + } + else { + reject(`statusCode: ${statusCode}`); + } + }); + const downloadTask = new DownloadTask(downloader); + for (const name in header) { + if (hasOwn$1(header, name)) { + downloader.setRequestHeader(name, header[name]); + } + } + downloader.start(); + return downloadTask; + }, DownloadFileProtocol, DownloadFileOptions); - _in = have; - _out = left; - ret = Z_OK$1; + const cookiesParse = (header) => { + let cookiesStr = header['Set-Cookie'] || header['set-cookie']; + let cookiesArr = []; + if (!cookiesStr) { + return []; + } + if (cookiesStr[0] === '[' && cookiesStr[cookiesStr.length - 1] === ']') { + cookiesStr = cookiesStr.slice(1, -1); + } + const handleCookiesArr = cookiesStr.split(';'); + for (let i = 0; i < handleCookiesArr.length; i++) { + if (handleCookiesArr[i].indexOf('Expires=') !== -1 || + handleCookiesArr[i].indexOf('expires=') !== -1) { + cookiesArr.push(handleCookiesArr[i].replace(',', '')); + } + else { + cookiesArr.push(handleCookiesArr[i]); + } + } + cookiesArr = cookiesArr.join(';').split(','); + return cookiesArr; + }; + function formatResponse(res, args) { + if (typeof res.data === 'string' && res.data.charCodeAt(0) === 65279) { + res.data = res.data.substr(1); + } + res.statusCode = parseInt(String(res.statusCode), 10); + if (isPlainObject(res.header)) { + res.header = Object.keys(res.header).reduce(function (ret, key) { + const value = res.header[key]; + if (Array.isArray(value)) { + ret[key] = value.join(','); + } + else if (typeof value === 'string') { + ret[key] = value; + } + return ret; + }, {}); + } + if (args.dataType && args.dataType.toLowerCase() === 'json') { + try { + res.data = JSON.parse(res.data); + } + catch (e) { } + } + return res; + } + /** + * 请求任务类 + */ + class RequestTask { + constructor(requestTask) { + this._requestTask = requestTask; + } + abort() { + this._requestTask.abort(); + } + offHeadersReceived() { } + onHeadersReceived() { } + } + const request = defineTaskApi(API_REQUEST, (args, { resolve, reject }) => { + let { header, method, data, timeout, url, responseType, sslVerify, firstIpv4, + // NOTE 属性有但是types没有 + // @ts-ignore + tls, } = args; + let contentType; + for (const name in header) { + if (name.toLowerCase() === 'content-type') { + contentType = header[name]; + break; + } + } + if (method !== 'GET' && + contentType.indexOf('application/json') === 0 && + isPlainObject(data)) { + data = JSON.stringify(data); + } + const stream = requireNativePlugin('stream'); + const headers = {}; + let abortTimeout; + let aborted; + let hasContentType = false; + for (const name in header) { + if (!hasContentType && name.toLowerCase() === 'content-type') { + hasContentType = true; + headers['Content-Type'] = header[name]; + // TODO 需要重构 + if (method !== 'GET' && + header[name].indexOf('application/x-www-form-urlencoded') === 0 && + typeof data !== 'string' && + !(data instanceof ArrayBuffer)) { + const bodyArray = []; + for (const key in data) { + if (hasOwn$1(data, key)) { + bodyArray.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); + } + } + data = bodyArray.join('&'); + } + } + else { + headers[name] = header[name]; + } + } + if (!hasContentType && method === 'POST') { + headers['Content-Type'] = + 'application/x-www-form-urlencoded; charset=UTF-8'; + } + if (timeout) { + abortTimeout = setTimeout(() => { + aborted = true; + reject('timeout'); + }, timeout + 200); // TODO +200 发消息到原生层有时间开销,以后考虑由原生层回调超时 + } + const options = { + method, + url: url.trim(), + // weex 官方文档有误,headers 类型实际 object,用 string 类型会无响应 + headers, + type: responseType === 'arraybuffer' ? 'base64' : 'text', + // weex 官方文档未说明实际支持 timeout,单位:ms + timeout: timeout || 6e5, + // 配置和weex模块内相反 + sslVerify: !sslVerify, + firstIpv4: firstIpv4, + tls, + }; + if (method !== 'GET') { + options.body = typeof data === 'string' ? data : JSON.stringify(data); + } + stream.fetch(options, ({ ok, status, data, headers, errorMsg, }) => { + if (aborted) { + return; + } + if (abortTimeout) { + clearTimeout(abortTimeout); + } + const statusCode = status; + if (statusCode > 0) { + resolve(formatResponse({ + data: ok && responseType === 'arraybuffer' + ? base64ToArrayBuffer(data) + : data, + statusCode, + header: headers, + cookies: cookiesParse(headers), + }, args)); + } + else { + let errMsg = 'abort statusCode:' + statusCode; + if (errorMsg) { + errMsg = errMsg + ' ' + errorMsg; + } + reject(errMsg); + } + }); + return new RequestTask({ + abort() { + aborted = true; + if (abortTimeout) { + clearTimeout(abortTimeout); + } + reject('abort'); + }, + }); + }, RequestProtocol, RequestOptions); + const configMTLS = defineAsyncApi(API_CONFIG_MTLS, ({ certificates }, { resolve, reject }) => { + const stream = requireNativePlugin('stream'); + stream.configMTLS(certificates, ({ type, code, message }) => { + switch (type) { + case 'success': + resolve({ code }); + break; + case 'fail': + reject(message, { code }); + break; + } + }); + }, ConfigMTLSProtocol, ConfigMTLSOptions); - inf_leave: // goto emulation - for (;;) { - switch (state.mode) { - case HEAD: - if (state.wrap === 0) { - state.mode = TYPEDO; - break; - } - //=== NEEDBITS(16); - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ - state.check = 0/*crc32(0L, Z_NULL, 0)*/; - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32_1(state.check, hbuf, 2, 0); - //===// + const socketTasks = []; + const socketsMap = {}; + const globalEvent = { + open: '', + close: '', + error: '', + message: '', + }; + let socket; + function createSocketTask(args) { + const socketId = String(Date.now()); + let errMsg; + try { + if (!socket) { + socket = requireNativePlugin('uni-webSocket'); + bindSocketCallBack(socket); + } + socket.WebSocket({ + id: socketId, + url: args.url, + protocol: Array.isArray(args.protocols) + ? args.protocols.join(',') + : args.protocols, + header: args.header, + }); + } + catch (error) { + errMsg = error; + } + return { socket, socketId, errMsg }; + } + function bindSocketCallBack(socket) { + socket.onopen((e) => { + const curSocket = socketsMap[e.id]; + if (!curSocket) + return; + curSocket._socketOnOpen(); + }); + socket.onmessage((e) => { + const curSocket = socketsMap[e.id]; + if (!curSocket) + return; + curSocket._socketOnMessage(e); + }); + socket.onerror((e) => { + const curSocket = socketsMap[e.id]; + if (!curSocket) + return; + curSocket._socketOnError(); + }); + socket.onclose((e) => { + const curSocket = socketsMap[e.id]; + if (!curSocket) + return; + curSocket._socketOnClose(); + }); + } + class SocketTask { + constructor(socket, socketId) { + this.id = socketId; + this._socket = socket; + this._callbacks = { + open: [], + close: [], + error: [], + message: [], + }; + this.CLOSED = 3; + this.CLOSING = 2; + this.CONNECTING = 0; + this.OPEN = 1; + this.readyState = this.CLOSED; + if (!this._socket) + return; + } + _socketOnOpen() { + this.readyState = this.OPEN; + this.socketStateChange('open'); + } + _socketOnMessage(e) { + this.socketStateChange('message', { + data: typeof e.data === 'object' + ? base64ToArrayBuffer(e.data.base64) + : e.data, + }); + } + _socketOnError() { + this.socketStateChange('error'); + this.onErrorOrClose(); + } + _socketOnClose() { + this.socketStateChange('close'); + this.onErrorOrClose(); + } + onErrorOrClose() { + this.readyState = this.CLOSED; + delete socketsMap[this.id]; + const index = socketTasks.indexOf(this); + if (index >= 0) { + socketTasks.splice(index, 1); + } + } + socketStateChange(name, res = {}) { + const data = name === 'message' ? res : {}; + if (this === socketTasks[0] && globalEvent[name]) { + UniServiceJSBridge.invokeOnCallback(globalEvent[name], data); + } + // WYQ fix: App平台修复websocket onOpen时发送数据报错的Bug + this._callbacks[name].forEach((callback) => { + if (typeof callback === 'function') { + callback(data); + } + }); + } + send(args, callopt = true) { + if (this.readyState !== this.OPEN) { + callOptions(args, 'sendSocketMessage:fail WebSocket is not connected'); + } + try { + this._socket.send({ + id: this.id, + data: typeof args.data === 'object' + ? { + '@type': 'binary', + base64: arrayBufferToBase64(args.data), + } + : args.data, + }); + callopt && callOptions(args, 'sendSocketMessage:ok'); + } + catch (error) { + callopt && callOptions(args, `sendSocketMessage:fail ${error}`); + } + } + close(args, callopt = true) { + this.readyState = this.CLOSING; + try { + this._socket.close(extend({ + id: this.id, + args, + })); + callopt && callOptions(args, 'closeSocket:ok'); + } + catch (error) { + callopt && callOptions(args, `closeSocket:fail ${error}`); + } + } + onOpen(callback) { + this._callbacks.open.push(callback); + } + onClose(callback) { + this._callbacks.close.push(callback); + } + onError(callback) { + this._callbacks.error.push(callback); + } + onMessage(callback) { + this._callbacks.message.push(callback); + } + } + const connectSocket = defineTaskApi(API_CONNECT_SOCKET, ({ url, protocols, header, method }, { resolve, reject }) => { + const { socket, socketId, errMsg } = createSocketTask({ + url, + protocols, + header, + method, + }); + const socketTask = new SocketTask(socket, socketId); + if (errMsg) { + setTimeout(() => { + reject(errMsg); + }, 0); + } + else { + socketTasks.push(socketTask); + socketsMap[socketId] = socketTask; + } + setTimeout(() => { + resolve(); + }, 0); + return socketTask; + }, ConnectSocketProtocol, ConnectSocketOptions); + const sendSocketMessage = defineAsyncApi(API_SEND_SOCKET_MESSAGE, (args, { resolve, reject }) => { + const socketTask = socketTasks[0]; + if (!socketTask || socketTask.readyState !== socketTask.OPEN) { + reject('WebSocket is not connected'); + return; + } + socketTask.send({ data: args.data }, false); + resolve(); + }, SendSocketMessageProtocol); + const closeSocket = defineAsyncApi(API_CLOSE_SOCKET, (args, { resolve, reject }) => { + const socketTask = socketTasks[0]; + if (!socketTask) { + reject('WebSocket is not connected'); + return; + } + socketTask.readyState = socketTask.CLOSING; + socketTask.close(args, false); + resolve(); + }, CloseSocketProtocol); + function on(event) { + const api = `onSocket${capitalize(event)}`; + return defineOnApi(api, () => { + globalEvent[event] = api; + }); + } + const onSocketOpen = /*#__PURE__*/ on('open'); + const onSocketError = /*#__PURE__*/ on('error'); + const onSocketMessage = /*#__PURE__*/ on('message'); + const onSocketClose = /*#__PURE__*/ on('close'); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = FLAGS; - break; - } - state.flags = 0; /* expect zlib header */ - if (state.head) { - state.head.done = false; - } - if (!(state.wrap & 1) || /* check if zlib header allowed */ - (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { - strm.msg = 'incorrect header check'; - state.mode = BAD; - break; - } - if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD; - break; - } - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// - len = (hold & 0x0f)/*BITS(4)*/ + 8; - if (state.wbits === 0) { - state.wbits = len; - } - else if (len > state.wbits) { - strm.msg = 'invalid window size'; - state.mode = BAD; - break; - } + class UploadTask { + constructor(uploader) { + this._callbacks = []; + this._uploader = uploader; + uploader.addEventListener('statechanged', (upload, status) => { + if (upload.uploadedSize && upload.totalSize) { + this._callbacks.forEach((callback) => { + callback({ + progress: parseInt(String((upload.uploadedSize / upload.totalSize) * 100)), + totalBytesSent: upload.uploadedSize, + totalBytesExpectedToSend: upload.totalSize, + }); + }); + } + }); + } + abort() { + this._uploader.abort(); + } + onProgressUpdate(callback) { + if (typeof callback !== 'function') { + return; + } + this._callbacks.push(callback); + } + onHeadersReceived() { } + offProgressUpdate(callback) { + const index = this._callbacks.indexOf(callback); + if (index >= 0) { + this._callbacks.splice(index, 1); + } + } + offHeadersReceived() { } + } + const uploadFile = defineTaskApi(API_UPLOAD_FILE, ({ url, timeout, header, formData, files, filePath, name }, { resolve, reject }) => { + const uploader = plus.uploader.createUpload(url, { + timeout, + // 需要与其它平台上的表现保持一致,不走重试的逻辑。 + retry: 0, + retryInterval: 0, + }, (upload, statusCode) => { + if (statusCode) { + resolve({ + data: upload.responseText, + statusCode, + }); + } + else { + reject(`statusCode: ${statusCode}`); + } + }); + for (const name in header) { + if (hasOwn$1(header, name)) { + uploader.setRequestHeader(name, String(header[name])); + } + } + for (const name in formData) { + if (hasOwn$1(formData, name)) { + uploader.addData(name, String(formData[name])); + } + } + if (files && files.length) { + files.forEach((file) => { + uploader.addFile(getRealPath(file.uri), { + key: file.name || 'file', + }); + }); + } + else { + uploader.addFile(getRealPath(filePath), { + key: name, + }); + } + const uploadFileTask = new UploadTask(uploader); + uploader.start(); + return uploadFileTask; + }, UploadFileProtocol, UploadFileOptions); + + const audios = {}; + const evts = [ + 'play', + 'canplay', + 'ended', + 'stop', + 'waiting', + 'seeking', + 'seeked', + 'pause', + ]; + const AUDIO_DEFAULT_CATEGORY = 'ambient'; + const initStateChage = (audioId) => { + const audio = audios[audioId]; + if (!audio) { + return; + } + if (!audio.initStateChage) { + audio.initStateChage = true; + audio.addEventListener('error', (error) => { + onAudioStateChange({ + state: 'error', + audioId, + errMsg: 'MediaError', + errCode: error.code, + }); + }); + evts.forEach((event) => { + audio.addEventListener(event, () => { + // 添加 isStopped 属性是为了解决 安卓设备停止播放后获取播放进度不正确的问题 + if (event === 'play') { + audio.isStopped = false; + } + else if (event === 'stop') { + audio.isStopped = true; + } + onAudioStateChange({ + state: event, + audioId, + }); + }); + }); + } + }; + function createAudioInstance() { + const audioId = `${Date.now()}${Math.random()}`; + const audio = (audios[audioId] = plus.audio.createPlayer('')); // 此处空字符串必填 + audio.src = ''; + audio.volume = 1; + audio.startTime = 0; + audio.setSessionCategory(AUDIO_DEFAULT_CATEGORY); + return { + errMsg: 'createAudioInstance:ok', + audioId, + }; + } + function setAudioState({ audioId, src, startTime, autoplay = false, loop = false, obeyMuteSwitch, volume, category = AUDIO_DEFAULT_CATEGORY, }) { + const audio = audios[audioId]; + if (audio) { + const style = { + loop, + autoplay, + }; + if (src) { + audio.src = style.src = getRealPath(src); + } + if (startTime) { + audio.startTime = style.startTime = startTime; + } + if (typeof volume === 'number') { + audio.volume = style.volume = volume; + } + audio.setStyles(style); + if (category) { + audio.setSessionCategory(category); + } + initStateChage(audioId); + } + return { + errMsg: 'setAudioState:ok', + }; + } + function getAudioState({ audioId }) { + const audio = audios[audioId]; + if (!audio) { + return { + errMsg: 'getAudioState:fail', + }; + } + const { src, startTime, volume } = audio; + return { + errMsg: 'getAudioState:ok', + duration: 1e3 * (audio.getDuration() || 0), + currentTime: audio.isStopped ? 0 : 1e3 * audio.getPosition(), + paused: audio.isPaused(), + src, + volume, + startTime: 1e3 * startTime, + buffered: 1e3 * audio.getBuffered(), + }; + } + function operateAudio({ operationType, audioId, currentTime, }) { + const audio = audios[audioId]; + switch (operationType) { + case 'play': + case 'pause': + case 'stop': + audio[operationType === 'play' && audio.isPaused() ? 'resume' : operationType](); + break; + case 'seek': + typeof currentTime != 'undefined' ? audio.seekTo(currentTime / 1e3) : ''; + break; + } + return { + errMsg: 'operateAudio:ok', + }; + } + const innerAudioContexts = Object.create(null); + const onAudioStateChange = ({ state, audioId, errMsg, errCode, }) => { + const audio = innerAudioContexts[audioId]; + if (audio) { + emit(audio, state, errMsg, errCode); + if (state === 'play') { + const oldCurrentTime = audio.currentTime; + audio.__timing = setInterval(() => { + const currentTime = audio.currentTime; + if (currentTime !== oldCurrentTime) { + emit(audio, 'timeUpdate'); + } + }, 200); + } + else if (state === 'pause' || state === 'stop' || state === 'error') { + clearInterval(audio.__timing); + } + } + }; + const props$1 = [ + { + name: 'src', + cache: true, + }, + { + name: 'startTime', + default: 0, + cache: true, + }, + { + name: 'autoplay', + default: false, + cache: true, + }, + { + name: 'loop', + default: false, + cache: true, + }, + { + name: 'obeyMuteSwitch', + default: true, + readonly: true, + cache: true, + }, + { + name: 'duration', + readonly: true, + }, + { + name: 'currentTime', + readonly: true, + }, + { + name: 'paused', + readonly: true, + }, + { + name: 'buffered', + readonly: true, + }, + { + name: 'volume', + }, + ]; + class InnerAudioContext { + constructor(id) { + this.id = id; + this._callbacks = {}; + this._options = {}; + // 初始化事件监听列表 + innerAudioContextEventNames.forEach((eventName) => { + this._callbacks[eventName] = []; + }); + props$1.forEach((item) => { + const name = item.name; + Object.defineProperty(this, name, { + get: () => { + const result = item.cache + ? this._options + : getAudioState({ + audioId: this.id, + }); + const value = name in result ? result[name] : item.default; + return typeof value === 'number' && name !== 'volume' + ? value / 1e3 + : value; + }, + set: item.readonly + ? undefined + : (value) => { + this._options[name] = value; + setAudioState(extend({}, this._options, { + audioId: this.id, + })); + }, + }); + }); + initInnerAudioContextEventOnce(); + } + play() { + this._operate('play'); + } + pause() { + this._operate('pause'); + } + stop() { + this._operate('stop'); + } + seek(position) { + this._operate('seek', { + currentTime: position * 1e3, + }); + } + destroy() { + clearInterval(this.__timing); + if (audios[this.id]) { + audios[this.id].close(); + delete audios[this.id]; + } + delete innerAudioContexts[this.id]; + } + _operate(type, options) { + operateAudio(extend({}, options, { + audioId: this.id, + operationType: type, + })); + } + } + const initInnerAudioContextEventOnce = /*#__PURE__*/ once(() => { + // 批量设置音频上下文事件监听方法 + innerAudioContextEventNames.forEach((eventName) => { + InnerAudioContext.prototype[eventName] = function (callback) { + if (typeof callback === 'function') { + this._callbacks[eventName].push(callback); + } + }; + }); + // 批量设置音频上下文事件取消监听方法 + innerAudioContextOffEventNames.forEach((eventName) => { + InnerAudioContext.prototype[eventName] = function (callback) { + const callbacks = this._callbacks[eventName]; + const index = callbacks.indexOf(callback); + if (index >= 0) { + callbacks.splice(index, 1); + } + }; + }); + }); + function emit(audio, state, errMsg, errCode) { + const name = `on${capitalize(state)}`; + audio._callbacks[name].forEach((callback) => { + if (typeof callback === 'function') { + callback(state === 'error' + ? { + errMsg, + errCode, + } + : {}); + } + }); + } + /** + * 创建音频上下文 + */ + const createInnerAudioContext = defineSyncApi(API_CREATE_INNER_AUDIO_CONTEXT, () => { + const { audioId } = createAudioInstance(); + const innerAudioContext = new InnerAudioContext(audioId); + innerAudioContexts[audioId] = innerAudioContext; + return innerAudioContext; + }); - // !!! pako patch. Force use `options.windowBits` if passed. - // Required to always use max window size by default. - state.dmax = 1 << state.wbits; - //state.dmax = 1 << len; + const eventNames = [ + 'canplay', + 'play', + 'pause', + 'stop', + 'ended', + 'timeUpdate', + 'prev', + 'next', + 'error', + 'waiting', + ]; + const callbacks = { + canplay: [], + play: [], + pause: [], + stop: [], + ended: [], + timeUpdate: [], + prev: [], + next: [], + error: [], + waiting: [], + }; + let audio; + let timeUpdateTimer = null; + const TIME_UPDATE = 250; + const events = ['play', 'pause', 'ended', 'stop', 'canplay']; + function startTimeUpdateTimer() { + stopTimeUpdateTimer(); + timeUpdateTimer = setInterval(() => { + onBackgroundAudioStateChange({ state: 'timeUpdate' }); + }, TIME_UPDATE); + } + function stopTimeUpdateTimer() { + if (timeUpdateTimer !== null) { + clearInterval(timeUpdateTimer); + } + } + function initMusic() { + if (audio) { + return; + } + const publish = UniServiceJSBridge.invokeOnCallback; + audio = plus.audio.createPlayer({ + autoplay: true, + backgroundControl: true, + }); + audio.src = + audio.title = + audio.epname = + audio.singer = + audio.coverImgUrl = + audio.webUrl = + ''; + audio.startTime = 0; + events.forEach((event) => { + audio.addEventListener(event, () => { + // 添加 isStopped 属性是为了解决 安卓设备停止播放后获取播放进度不正确的问题 + if (event === 'play') { + audio.isStopped = false; + startTimeUpdateTimer(); + } + else if (event === 'stop') { + audio.isStopped = true; + } + if (event === 'pause' || event === 'ended' || event === 'stop') { + stopTimeUpdateTimer(); + } + const eventName = `onMusic${event[0].toUpperCase() + event.substr(1)}`; + publish(eventName, { + dataUrl: audio.src, + errMsg: `${eventName}:ok`, + }); + onBackgroundAudioStateChange({ + state: event, + dataUrl: audio.src, + }); + }); + }); + audio.addEventListener('waiting', () => { + stopTimeUpdateTimer(); + onBackgroundAudioStateChange({ + state: 'waiting', + dataUrl: audio.src, + }); + }); + audio.addEventListener('error', (err) => { + stopTimeUpdateTimer(); + publish('onMusicError', { + dataUrl: audio.src, + errMsg: 'Error:' + err.message, + }); + onBackgroundAudioStateChange({ + state: 'error', + dataUrl: audio.src, + errMsg: err.message, + errCode: err.code, + }); + }); + // @ts-ignore + audio.addEventListener('prev', () => publish('onBackgroundAudioPrev')); + // @ts-ignore + audio.addEventListener('next', () => publish('onBackgroundAudioNext')); + } + function getBackgroundAudioState() { + let data = { + duration: 0, + currentTime: 0, + paused: false, + src: '', + buffered: 0, + title: '', + epname: '', + singer: '', + coverImgUrl: '', + webUrl: '', + startTime: 0, + errMsg: 'getBackgroundAudioState:ok', + }; + if (audio) { + const newData = { + duration: audio.getDuration() || 0, + currentTime: audio.isStopped ? 0 : audio.getPosition(), + paused: audio.isPaused(), + src: audio.src, + buffered: audio.getBuffered(), + title: audio.title, + epname: audio.epname, + singer: audio.singer, + coverImgUrl: audio.coverImgUrl, + webUrl: audio.webUrl, + startTime: audio.startTime, + }; + data = extend(data, newData); + } + return data; + } + function setMusicState(args) { + initMusic(); + const props = [ + 'src', + 'startTime', + 'coverImgUrl', + 'webUrl', + 'singer', + 'epname', + 'title', + ]; + const style = {}; + Object.keys(args).forEach((key) => { + if (props.indexOf(key) >= 0) { + let val = args[key]; + if (key === props[0] && val) { + val = getRealPath(val); + } + audio[key] = style[key] = val; + } + }); + audio.setStyles(style); + } + function operateMusicPlayer({ operationType, src, position, api = 'operateMusicPlayer', title, coverImgUrl, }) { + var operationTypes = ['resume', 'pause', 'stop']; + if (operationTypes.indexOf(operationType) > 0) { + audio && audio[operationType](); + } + else if (operationType === 'play') { + setMusicState({ + src, + startTime: position, + title, + coverImgUrl, + }); + audio.play(); + } + else if (operationType === 'seek') { + audio && audio.seekTo(position); + } + return { + errMsg: `${api}:ok`, + }; + } + function operateBackgroundAudio({ operationType, src, startTime, currentTime, }) { + return operateMusicPlayer({ + operationType, + src, + position: startTime || currentTime || 0, + api: 'operateBackgroundAudio', + }); + } + function onBackgroundAudioStateChange({ state, errMsg, errCode, dataUrl, }) { + callbacks[state].forEach((callback) => { + if (typeof callback === 'function') { + callback(state === 'error' + ? { + errMsg, + errCode, + } + : {}); + } + }); + } + const onInitBackgroundAudioManager = /*#__PURE__*/ once(() => { + eventNames.forEach((item) => { + BackgroundAudioManager.prototype[`on${capitalize(item)}`] = + function (callback) { + callbacks[item].push(callback); + }; + }); + }); + const props = [ + { + name: 'duration', + readonly: true, + }, + { + name: 'currentTime', + readonly: true, + }, + { + name: 'paused', + readonly: true, + }, + { + name: 'src', + cache: true, + }, + { + name: 'startTime', + default: 0, + cache: true, + }, + { + name: 'buffered', + readonly: true, + }, + { + name: 'title', + cache: true, + }, + { + name: 'epname', + cache: true, + }, + { + name: 'singer', + cache: true, + }, + { + name: 'coverImgUrl', + cache: true, + }, + { + name: 'webUrl', + cache: true, + }, + { + name: 'protocol', + readonly: true, + default: 'http', + }, + ]; + class BackgroundAudioManager { + constructor() { + this._options = {}; + props.forEach((item) => { + const name = item.name; + Object.defineProperty(this, name, { + get: () => { + const result = item.cache ? this._options : getBackgroundAudioState(); + return name in result ? result[name] : item.default; + }, + set: item.readonly + ? undefined + : (value) => { + this._options[name] = value; + setMusicState(this._options); + }, + }); + }); + onInitBackgroundAudioManager(); + } + play() { + this._operate('play'); + } + pause() { + this._operate('pause'); + } + stop() { + this._operate('stop'); + } + seek(position) { + this._operate('seek', { + currentTime: position, + }); + } + _operate(type, options) { + operateBackgroundAudio(extend({}, options, { + operationType: type, + })); + } + } + let backgroundAudioManager; + const getBackgroundAudioManager = defineSyncApi(API_GET_BACKGROUND_AUDIO_MANAGER, () => backgroundAudioManager || + (backgroundAudioManager = new BackgroundAudioManager())); - //Tracev((stderr, "inflate: zlib header ok\n")); - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = hold & 0x200 ? DICTID : TYPE; - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - break; - case FLAGS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.flags = hold; - if ((state.flags & 0xff) !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD; - break; - } - if (state.flags & 0xe000) { - strm.msg = 'unknown header flags set'; - state.mode = BAD; - break; - } - if (state.head) { - state.head.text = ((hold >> 8) & 1); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32_1(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = TIME; - /* falls through */ - case TIME: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.time = hold; - } - if (state.flags & 0x0200) { - //=== CRC4(state.check, hold) - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - hbuf[2] = (hold >>> 16) & 0xff; - hbuf[3] = (hold >>> 24) & 0xff; - state.check = crc32_1(state.check, hbuf, 4, 0); - //=== - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = OS; - /* falls through */ - case OS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.xflags = (hold & 0xff); - state.head.os = (hold >> 8); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32_1(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = EXLEN; - /* falls through */ - case EXLEN: - if (state.flags & 0x0400) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length = hold; - if (state.head) { - state.head.extra_len = hold; - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32_1(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - else if (state.head) { - state.head.extra = null/*Z_NULL*/; - } - state.mode = EXTRA; - /* falls through */ - case EXTRA: - if (state.flags & 0x0400) { - copy = state.length; - if (copy > have) { copy = have; } - if (copy) { - if (state.head) { - len = state.head.extra_len - state.length; - if (!state.head.extra) { - // Use untyped array for more convenient processing later - state.head.extra = new Uint8Array(state.head.extra_len); - } - state.head.extra.set( - input.subarray( - next, - // extra field is limited to 65536 bytes - // - no need for additional size check - next + copy - ), - /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ - len - ); - //zmemcpy(state.head.extra + len, next, - // len + copy > state.head.extra_max ? - // state.head.extra_max - len : copy); - } - if (state.flags & 0x0200) { - state.check = crc32_1(state.check, input, copy, next); - } - have -= copy; - next += copy; - state.length -= copy; - } - if (state.length) { break inf_leave; } - } - state.length = 0; - state.mode = NAME; - /* falls through */ - case NAME: - if (state.flags & 0x0800) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - // TODO: 2 or 1 bytes? - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.name_max*/)) { - state.head.name += String.fromCharCode(len); - } - } while (len && copy < have); + class LivePusherContext { + constructor(id, ctx) { + this.id = id; + this.ctx = ctx; + } + start(option) { + return invokeVmMethodWithoutArgs(this.ctx, 'start', option); + } + stop(option) { + return invokeVmMethodWithoutArgs(this.ctx, 'stop', option); + } + pause(option) { + return invokeVmMethodWithoutArgs(this.ctx, 'pause', option); + } + resume(option) { + return invokeVmMethodWithoutArgs(this.ctx, 'resume', option); + } + switchCamera(option) { + return invokeVmMethodWithoutArgs(this.ctx, 'switchCamera', option); + } + snapshot(option) { + return invokeVmMethodWithoutArgs(this.ctx, 'snapshot', option); + } + toggleTorch(option) { + return invokeVmMethodWithoutArgs(this.ctx, 'toggleTorch', option); + } + playBGM(option) { + return invokeVmMethod(this.ctx, 'playBGM', option); + } + stopBGM(option) { + return invokeVmMethodWithoutArgs(this.ctx, 'stopBGM', option); + } + pauseBGM(option) { + return invokeVmMethodWithoutArgs(this.ctx, 'pauseBGM', option); + } + resumeBGM(option) { + return invokeVmMethodWithoutArgs(this.ctx, 'resumeBGM', option); + } + setBGMVolume(option) { + return invokeVmMethod(this.ctx, 'setBGMVolume', option); + } + startPreview(option) { + return invokeVmMethodWithoutArgs(this.ctx, 'startPreview', option); + } + stopPreview(args) { + return invokeVmMethodWithoutArgs(this.ctx, 'stopPreview', args); + } + } + const createLivePusherContext = defineSyncApi(API_CREATE_LIVE_PUSHER_CONTEXT, (id, vm) => { + if (!vm) { + return console.warn('uni.createLivePusherContext: 2 arguments required, but only 1 present'); + } + const elm = findElmById(id, vm); + if (!elm) { + return console.warn('Can not find `' + id + '`'); + } + return new LivePusherContext(id, elm); + }, CreateLivePusherContextProtocol); - if (state.flags & 0x0200) { - state.check = crc32_1(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.name = null; - } - state.length = 0; - state.mode = COMMENT; - /* falls through */ - case COMMENT: - if (state.flags & 0x1000) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.comm_max*/)) { - state.head.comment += String.fromCharCode(len); - } - } while (len && copy < have); - if (state.flags & 0x0200) { - state.check = crc32_1(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.comment = null; - } - state.mode = HCRC; - /* falls through */ - case HCRC: - if (state.flags & 0x0200) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.check & 0xffff)) { - strm.msg = 'header crc mismatch'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - if (state.head) { - state.head.hcrc = ((state.flags >> 9) & 1); - state.head.done = true; - } - strm.adler = state.check = 0; - state.mode = TYPE; - break; - case DICTID: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - strm.adler = state.check = zswap32(hold); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = DICT; - /* falls through */ - case DICT: - if (state.havedict === 0) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - return Z_NEED_DICT$1; - } - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = TYPE; - /* falls through */ - case TYPE: - if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } - /* falls through */ - case TYPEDO: - if (state.last) { - //--- BYTEBITS() ---// - hold >>>= bits & 7; - bits -= bits & 7; - //---// - state.mode = CHECK; - break; - } - //=== NEEDBITS(3); */ - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.last = (hold & 0x01)/*BITS(1)*/; - //--- DROPBITS(1) ---// - hold >>>= 1; - bits -= 1; - //---// + const PI = 3.1415926535897932384626; + const a = 6378245.0; + const ee = 0.00669342162296594323; + function gcj02towgs84(lng, lat) { + lat = +lat; + lng = +lng; + if (outOfChina(lng, lat)) { + return [lng, lat]; + } + let dlat = _transformlat(lng - 105.0, lat - 35.0); + let dlng = _transformlng(lng - 105.0, lat - 35.0); + const radlat = (lat / 180.0) * PI; + let magic = Math.sin(radlat); + magic = 1 - ee * magic * magic; + const sqrtmagic = Math.sqrt(magic); + dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI); + dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI); + const mglat = lat + dlat; + const mglng = lng + dlng; + return [lng * 2 - mglng, lat * 2 - mglat]; + } + function wgs84togcj02(lng, lat) { + lat = +lat; + lng = +lng; + if (outOfChina(lng, lat)) { + return [lng, lat]; + } + let dlat = _transformlat(lng - 105.0, lat - 35.0); + let dlng = _transformlng(lng - 105.0, lat - 35.0); + const radlat = (lat / 180.0) * PI; + let magic = Math.sin(radlat); + magic = 1 - ee * magic * magic; + const sqrtmagic = Math.sqrt(magic); + dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI); + dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI); + const mglat = lat + dlat; + const mglng = lng + dlng; + return [mglng, mglat]; + } + const outOfChina = function (lng, lat) { + return (lng < 72.004 || lng > 137.8347 || lat < 0.8293 || lat > 55.8271 || false); + }; + const _transformlat = function (lng, lat) { + let ret = -100.0 + + 2.0 * lng + + 3.0 * lat + + 0.2 * lat * lat + + 0.1 * lng * lat + + 0.2 * Math.sqrt(Math.abs(lng)); + ret += + ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * + 2.0) / + 3.0; + ret += + ((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) * 2.0) / + 3.0; + ret += + ((160.0 * Math.sin((lat / 12.0) * PI) + 320 * Math.sin((lat * PI) / 30.0)) * + 2.0) / + 3.0; + return ret; + }; + const _transformlng = function (lng, lat) { + let ret = 300.0 + + lng + + 2.0 * lat + + 0.1 * lng * lng + + 0.1 * lng * lat + + 0.1 * Math.sqrt(Math.abs(lng)); + ret += + ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * + 2.0) / + 3.0; + ret += + ((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) * 2.0) / + 3.0; + ret += + ((150.0 * Math.sin((lng / 12.0) * PI) + + 300.0 * Math.sin((lng / 30.0) * PI)) * + 2.0) / + 3.0; + return ret; + }; + + function getLocationSuccess(type, position, resolve) { + const coords = position.coords; + if (type !== position.coordsType) { + let coordArray; + if (type === 'wgs84') { + coordArray = gcj02towgs84(coords.longitude, coords.latitude); + } + else if (type === 'gcj02') { + coordArray = wgs84togcj02(coords.longitude, coords.latitude); + } + if (coordArray) { + coords.longitude = coordArray[0]; + coords.latitude = coordArray[1]; + } + } + resolve({ + type, + altitude: coords.altitude || 0, + latitude: coords.latitude, + longitude: coords.longitude, + speed: coords.speed, + accuracy: coords.accuracy, + address: position.address, + errMsg: 'getLocation:ok', + }); + } + const getLocation = defineAsyncApi(API_GET_LOCATION, ({ type = 'wgs84', geocode = false, altitude = false, highAccuracyExpireTime, }, { resolve, reject }) => { + plus.geolocation.getCurrentPosition((position) => { + getLocationSuccess(type, position, resolve); + }, (e) => { + // 坐标地址解析失败 + if (e.code === 1501) { + getLocationSuccess(type, e, resolve); + return; + } + reject('getLocation:fail ' + e.message); + }, { + geocode: geocode, + enableHighAccuracy: altitude, + timeout: highAccuracyExpireTime, + }); + }, GetLocationProtocol, GetLocationOptions); - switch ((hold & 0x03)/*BITS(2)*/) { - case 0: /* stored block */ - //Tracev((stderr, "inflate: stored block%s\n", - // state.last ? " (last)" : "")); - state.mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - //Tracev((stderr, "inflate: fixed codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = LEN_; /* decode codes */ - if (flush === Z_TREES) { - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break inf_leave; - } - break; - case 2: /* dynamic block */ - //Tracev((stderr, "inflate: dynamic codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = TABLE; - break; - case 3: - strm.msg = 'invalid block type'; - state.mode = BAD; - } - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break; - case STORED: - //--- BYTEBITS() ---// /* go to byte boundary */ - hold >>>= bits & 7; - bits -= bits & 7; - //---// - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { - strm.msg = 'invalid stored block lengths'; - state.mode = BAD; - break; - } - state.length = hold & 0xffff; - //Tracev((stderr, "inflate: stored length %u\n", - // state.length)); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = COPY_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case COPY_: - state.mode = COPY; - /* falls through */ - case COPY: - copy = state.length; - if (copy) { - if (copy > have) { copy = have; } - if (copy > left) { copy = left; } - if (copy === 0) { break inf_leave; } - //--- zmemcpy(put, next, copy); --- - output.set(input.subarray(next, next + copy), put); - //---// - have -= copy; - next += copy; - left -= copy; - put += copy; - state.length -= copy; - break; - } - //Tracev((stderr, "inflate: stored end\n")); - state.mode = TYPE; - break; - case TABLE: - //=== NEEDBITS(14); */ - while (bits < 14) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// - //#ifndef PKZIP_BUG_WORKAROUND - if (state.nlen > 286 || state.ndist > 30) { - strm.msg = 'too many length or distance symbols'; - state.mode = BAD; - break; - } - //#endif - //Tracev((stderr, "inflate: table sizes ok\n")); - state.have = 0; - state.mode = LENLENS; - /* falls through */ - case LENLENS: - while (state.have < state.ncode) { - //=== NEEDBITS(3); - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - while (state.have < 19) { - state.lens[order[state.have++]] = 0; - } - // We have separate tables & no pointers. 2 commented lines below not needed. - //state.next = state.codes; - //state.lencode = state.next; - // Switch to use dynamic table - state.lencode = state.lendyn; - state.lenbits = 7; + const chooseLocation = defineAsyncApi(API_CHOOSE_LOCATION, (options, { resolve, reject }) => { + const statusBarStyle = getStatusBarStyle(); + const isDark = statusBarStyle !== 'light'; + let result; + const page = showPage({ + url: '__uniappchooselocation', + data: options, + style: { + // @ts-expect-error + animationType: options.animationType || 'slide-in-bottom', + // @ts-expect-error + titleNView: false, + popGesture: 'close', + scrollIndicator: 'none', + }, + onMessage({ event, detail, }) { + if (event === 'selected') { + result = detail; + } + }, + onClose() { + if (isDark) { + plus.navigator.setStatusBarStyle('dark'); + } + result ? resolve(result) : reject('cancel'); + }, + }); + if (isDark) { + plus.navigator.setStatusBarStyle('light'); + page.webview.addEventListener('popGesture', ({ type, result }) => { + if (type === 'start') { + plus.navigator.setStatusBarStyle('dark'); + } + else if (type === 'end' && !result) { + plus.navigator.setStatusBarStyle('light'); + } + }); + } + }, ChooseLocationProtocol); + + const openLocation = defineAsyncApi(API_OPEN_LOCATION, (data, { resolve, reject }) => { + showPage({ + url: '__uniappopenlocation', + data, + style: { + titleNView: { + type: 'transparent', + }, + popGesture: 'close', + backButtonAutoControl: 'close', + }, + onClose() { + reject('cancel'); + }, + }); + return resolve(); + }, OpenLocationProtocol, OpenLocationOptions); + + const showModal = defineAsyncApi(API_SHOW_MODAL, ({ title = '', content = '', showCancel = true, cancelText, cancelColor, confirmText, confirmColor, editable = false, placeholderText = '', } = {}, { resolve }) => { + const buttons = showCancel ? [cancelText, confirmText] : [confirmText]; + const tip = editable ? placeholderText : buttons; + content = content || ' '; + plus.nativeUI[editable ? 'prompt' : 'confirm'](content, (e) => { + if (showCancel) { + const isConfirm = e.index === 1; + const res = { + confirm: isConfirm, + cancel: e.index === 0 || e.index === -1, + }; + isConfirm && editable && (res.content = e.value); + resolve(res); + } + else { + const res = { + confirm: e.index === 0, + cancel: false, + }; + editable && (res.content = e.value); + resolve(res); + } + }, title, tip, buttons); + }, ShowModalProtocol, ShowModalOptions); + + const showActionSheet = defineAsyncApi(API_SHOW_ACTION_SHEET, ({ itemList = [], itemColor = '#000000', title = '', alertText = '', popover, }, { resolve, reject }) => { + initI18nShowActionSheetMsgsOnce(); + const { t } = useI18n(); + const options = { + title, + cancel: t('uni.showActionSheet.cancel'), + buttons: itemList.map((item) => ({ + title: item, + color: itemColor, + })), + }; + if (title || alertText) { + options.title = alertText || title; + } + plus.nativeUI.actionSheet(extend(options, { + popover, + }), (e) => { + if (e.index > 0) { + resolve({ + tapIndex: e.index - 1, + }); + } + else { + reject('showActionSheet:fail cancel'); + } + }); + }, ShowActionSheetProtocol, ShowActionSheetOptions); - opts = { bits: state.lenbits }; - ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); - state.lenbits = opts.bits; + let toast; + let isShowToast = false; + let toastType = ''; + let timeout; + const showLoading = defineAsyncApi(API_SHOW_LOADING, (args, callbacks) => _showToast(extend({}, args, { + type: 'loading', + icon: 'loading', + }), callbacks), ShowLoadingProtocol, ShowLoadingOptions); + const _showToast = ({ title = '', icon = 'success', image = '', duration = 1500, mask = false, position, + // @ts-ignore ToastType + type = 'toast', + // @ts-ignore PlusNativeUIWaitingStyles + style, }, { resolve, reject }) => { + hide(''); + toastType = type; + if (['top', 'center', 'bottom'].includes(String(position))) { + // 仅可以关闭 richtext 类型,但 iOS 部分情况换行显示有问题 + plus.nativeUI.toast(title, { + verticalAlign: position, + }); + isShowToast = true; + } + else { + if (icon && !~['success', 'loading', 'error', 'none'].indexOf(icon)) { + icon = 'success'; + } + const waitingOptions = { + modal: mask, + back: 'transmit', + padding: '10px', + size: '16px', // 固定字体大小 + }; + if (!image && (!icon || icon === 'none')) { + // 无图 + // waitingOptions.width = '120px' + // waitingOptions.height = '40px' + waitingOptions.loading = { + display: 'none', + }; + } + else { + waitingOptions.width = '140px'; + waitingOptions.height = '112px'; + } + if (image) { + waitingOptions.loading = { + display: 'block', + height: '55px', + icon: image, + interval: duration, + }; + } + else { + if (['success', 'error'].indexOf(icon) !== -1) { + waitingOptions.loading = { + display: 'block', + height: '55px', + icon: icon === 'success' ? '__uniappsuccess.png' : '__uniapperror.png', + interval: duration, + }; + } + } + try { + toast = plus.nativeUI.showWaiting(title, extend(waitingOptions, style)); + } + catch (error) { + reject(`${error}`); + } + } + timeout = setTimeout(() => { + hide(''); + }, duration); + return resolve(); + }; + const showToast = defineAsyncApi(API_SHOW_TOAST, _showToast, ShowToastProtocol, ShowToastOptions); + const hideToast = defineAsyncApi(API_HIDE_TOAST, (_, callbacks) => hide('toast', callbacks)); + const hideLoading = defineAsyncApi(API_HIDE_LOADING, (_, callbacks) => hide('loading', callbacks)); + function hide(type = 'toast', callbacks) { + if (type && type !== toastType) { + // 应该不需要失败回调,在页面后退时,会主动 hideToast 和 hideLoading,如果 reject 会出异常。 + return callbacks && callbacks.resolve(); + } + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + if (isShowToast) { + plus.nativeUI.closeToast(); + } + else if (toast && toast.close) { + toast.close(); + } + toast = null; + isShowToast = false; + toastType = ''; + return callbacks && callbacks.resolve(); + } - if (ret) { - strm.msg = 'invalid code lengths set'; - state.mode = BAD; - break; - } - //Tracev((stderr, "inflate: code lengths ok\n")); - state.have = 0; - state.mode = CODELENS; - /* falls through */ - case CODELENS: - while (state.have < state.nlen + state.ndist) { - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; + const startPullDownRefresh = defineAsyncApi(API_START_PULL_DOWN_REFRESH, (_args, { resolve, reject }) => { + let webview = getPullDownRefreshWebview(); + if (webview) { + webview.endPullToRefresh(); + } + webview = getCurrentWebview(); + if (!webview) { + return reject(); + } + webview.beginPullToRefresh(); + setPullDownRefreshWebview(webview); + resolve(); + }); - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_val < 16) { - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.lens[state.have++] = here_val; - } - else { - if (here_val === 16) { - //=== NEEDBITS(here.bits + 2); - n = here_bits + 2; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - if (state.have === 0) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD; - break; - } - len = state.lens[state.have - 1]; - copy = 3 + (hold & 0x03);//BITS(2); - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - } - else if (here_val === 17) { - //=== NEEDBITS(here.bits + 3); - n = here_bits + 3; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 3 + (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - else { - //=== NEEDBITS(here.bits + 7); - n = here_bits + 7; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 11 + (hold & 0x7f);//BITS(7); - //--- DROPBITS(7) ---// - hold >>>= 7; - bits -= 7; - //---// - } - if (state.have + copy > state.nlen + state.ndist) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD; - break; - } - while (copy--) { - state.lens[state.have++] = len; - } - } - } + const stopPullDownRefresh = defineAsyncApi(API_STOP_PULL_DOWN_REFRESH, (_args, { resolve, reject }) => { + const webview = getPullDownRefreshWebview() || getCurrentWebview(); + if (!webview) { + return reject(); + } + webview.endPullToRefresh(); + setPullDownRefreshWebview(null); + resolve(); + }); - /* handle error breaks in while */ - if (state.mode === BAD) { break; } + const loadFontFace = defineAsyncApi(API_LOAD_FONT_FACE, (options, { resolve, reject }) => { + const pageId = getPageIdByVm(getCurrentPageVm()); + UniServiceJSBridge.invokeViewMethod(API_LOAD_FONT_FACE, options, pageId, (err) => { + if (err) { + reject(err); + } + else { + resolve(); + } + }); + }, LoadFontFaceProtocol); - /* check for end-of-block code (better have one) */ - if (state.lens[256] === 0) { - strm.msg = 'invalid code -- missing end-of-block'; - state.mode = BAD; - break; - } + const pageScrollTo = defineAsyncApi(API_PAGE_SCROLL_TO, (options, { resolve }) => { + const pageId = getPageIdByVm(getCurrentPageVm()); + UniServiceJSBridge.invokeViewMethod(API_PAGE_SCROLL_TO, options, pageId, resolve); + }, PageScrollToProtocol, PageScrollToOptions); - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftrees.h - concerning the ENOUGH constants, which depend on those values */ - state.lenbits = 9; + const setNavigationBarTitle = defineAsyncApi(API_SET_NAVIGATION_BAR_TITLE, ({ __page__, title }, { resolve, reject }) => { + const webview = getWebview(__page__); + if (webview) { + const style = webview.getStyle(); + if (style && style.titleNView) { + webview.setStyle({ + titleNView: { + titleText: title, + }, + }); + } + resolve(); + } + else { + reject(); + } + }, SetNavigationBarTitleProtocol); + const showNavigationBarLoading = defineAsyncApi(API_SHOW_NAVIGATION_BAR_LOADING, (_, { resolve }) => { + plus.nativeUI.showWaiting('', { + modal: false, + }); + resolve(); + }); + const hideNavigationBarLoading = defineAsyncApi(API_HIDE_NAVIGATION_BAR_LOADING, (_, { resolve }) => { + plus.nativeUI.closeWaiting(); + resolve(); + }); + function setPageStatusBarStyle(statusBarStyle) { + const pages = getCurrentPages(); + if (!pages.length) { + return; + } + // 框架内部页面跳转会从这里获取style配置 + pages[pages.length - 1].$page.statusBarStyle = statusBarStyle; + } + const setNavigationBarColor = defineAsyncApi(API_SET_NAVIGATION_BAR_COLOR, ({ __page__, frontColor, backgroundColor }, { resolve, reject }) => { + const webview = getWebview(__page__); + if (webview) { + const styles = {}; + if (frontColor) { + styles.titleColor = frontColor; + } + if (backgroundColor) { + styles.backgroundColor = backgroundColor; + } + const statusBarStyle = frontColor === '#000000' ? 'dark' : 'light'; + plus.navigator.setStatusBarStyle(statusBarStyle); + // 用户调用api时同时改变当前页配置,这样在系统调用设置时,可以避免覆盖用户设置 + setPageStatusBarStyle(statusBarStyle); + const style = webview.getStyle(); + if (style && style.titleNView) { + if (style.titleNView.autoBackButton) { + styles.backButton = styles.backButton || {}; + styles.backButton.color = frontColor; + } + webview.setStyle({ + titleNView: styles, + }); + } + resolve(); + } + else { + reject(); + } + }, SetNavigationBarColorProtocol, SetNavigationBarColorOptions); - opts = { bits: state.lenbits }; - ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.lenbits = opts.bits; - // state.lencode = state.next; + const setTabBarBadge = defineAsyncApi(API_SET_TAB_BAR_BADGE, ({ index, text }, { resolve, reject }) => { + tabBar$1.setTabBarBadge('text', index, text); + resolve(); + }, SetTabBarBadgeProtocol, SetTabBarBadgeOptions); + const setTabBarItem = defineAsyncApi(API_SET_TAB_BAR_ITEM, ({ index, text, iconPath, selectedIconPath, pagePath, visible }, { resolve, reject }) => { + if (!isTabBarPage()) { + return reject('not TabBar page'); + } + tabBar$1.setTabBarItem(index, text, iconPath, selectedIconPath, visible); + const route = pagePath && __uniRoutes.find(({ path }) => path === pagePath); + if (route) { + const meta = route.meta; + meta.isTabBar = true; + meta.tabBarIndex = index; + meta.isQuit = true; + const tabBar = __uniConfig.tabBar; + if (tabBar && tabBar.list && tabBar.list[index] && pagePath) { + tabBar.list[index].pagePath = pagePath.startsWith('/') + ? pagePath.substring(1) + : pagePath; + } + } + resolve(); + }, SetTabBarItemProtocol, SetTabBarItemOptions); + const setTabBarStyle = defineAsyncApi(API_SET_TAB_BAR_STYLE, (style = {}, { resolve, reject }) => { + if (!isTabBarPage()) { + return reject('not TabBar page'); + } + const borderStyles = { + black: 'rgba(0,0,0,0.4)', + white: 'rgba(255,255,255,0.4)', + }; + const borderStyle = style.borderStyle; + if (borderStyle && borderStyle in borderStyles) { + style.borderStyle = borderStyles[borderStyle]; + } + tabBar$1.setTabBarStyle(style); + resolve(); + }, SetTabBarStyleProtocol, SetTabBarStyleOptions); + const hideTabBar = defineAsyncApi(API_HIDE_TAB_BAR, (args, { resolve, reject }) => { + const animation = args && args.animation; + if (!isTabBarPage()) { + return reject('not TabBar page'); + } + tabBar$1.hideTabBar(Boolean(animation)); + resolve(); + }, HideTabBarProtocol); + const showTabBar = defineAsyncApi(API_SHOW_TAB_BAR, (args, { resolve, reject }) => { + const animation = args && args.animation; + if (!isTabBarPage()) { + return reject('not TabBar page'); + } + tabBar$1.showTabBar(Boolean(animation)); + resolve(); + }, ShowTabBarProtocol); + const showTabBarRedDot = defineAsyncApi(API_SHOW_TAB_BAR_RED_DOT, ({ index }, { resolve, reject }) => { + tabBar$1.setTabBarBadge('redDot', index); + resolve(); + }, ShowTabBarRedDotProtocol, ShowTabBarRedDotOptions); + const setTabBarBadgeNone = (index) => tabBar$1.setTabBarBadge('none', index); + const removeTabBarBadge = defineAsyncApi(API_REMOVE_TAB_BAR_BADGE, ({ index }, { resolve, reject }) => { + setTabBarBadgeNone(index); + resolve(); + }, RemoveTabBarBadgeProtocol, RemoveTabBarBadgeOptions); + const hideTabBarRedDot = defineAsyncApi(API_HIDE_TAB_BAR_RED_DOT, ({ index }, { resolve, reject }) => { + setTabBarBadgeNone(index); + resolve(); + }, HideTabBarRedDotProtocol, HideTabBarRedDotOptions); - if (ret) { - strm.msg = 'invalid literal/lengths set'; - state.mode = BAD; - break; - } + const VD_SYNC = 'vdSync'; + const APP_SERVICE_ID = '__uniapp__service'; + const ON_WEBVIEW_READY = 'onWebviewReady'; + const ACTION_TYPE_DICT = 0; + const WEBVIEW_INSERTED = 'webviewInserted'; + const WEBVIEW_REMOVED = 'webviewRemoved'; + + const EVENT_TYPE_NAME = 'UniAppSubNVue'; + class SubNvue { + constructor(id, isSub) { + this.callbacks = []; + const webview = (this.webview = plus.webview.getWebviewById(id)); + this.isSub = isSub || false; + if (webview.__uniapp_mask_id) { + const maskWebview = (this.maskWebview = + webview.__uniapp_mask_id === '0' + ? { + setStyle({ mask }) { + requireNativePlugin('uni-tabview').setMask({ + color: mask, + }); + }, + } + : plus.webview.getWebviewById(webview.__uniapp_mask_id)); + const closeMask = function () { + maskWebview.setStyle({ + mask: 'none', + }); + }; + webview.addEventListener('hide', closeMask); + webview.addEventListener('close', closeMask); + } + } + show(...args) { + if (this.maskWebview) { + const maskColor = this.webview.__uniapp_mask; + this.maskWebview.setStyle({ + mask: maskColor, + }); + } + this.webview.show(...args); + } + hide(...args) { + this.webview.hide(...args); + } + setStyle(style) { + this.webview.setStyle(style); + } + initMessage() { + if (this.messageReady) { + return; + } + this.messageReady = true; + const listener = (event) => { + if (event.data && event.data.type === EVENT_TYPE_NAME) { + const target = event.data.target; + if (target.id === this.webview.id && target.isSub === this.isSub) { + this.callbacks.forEach((callback) => { + callback({ + origin: this.webview.__uniapp_host, + data: event.data.data, + }); + }); + } + } + }; + const globalEvent = requireNativePlugin('globalEvent'); + globalEvent.addEventListener('plusMessage', listener); + this.webview.addEventListener('close', () => { + // TODO 暂时仅清空回调 + this.callbacks.length = 0; + // globalEvent.removeEventListener('plusMessage', listener) + }); + } + postMessage(data) { + const webviewExt = plus.webview; + webviewExt.postMessageToUniNView({ + type: EVENT_TYPE_NAME, + data, + target: { + id: this.webview.id, + isSub: !this.isSub, + }, + }, APP_SERVICE_ID); + } + onMessage(callback) { + this.initMessage(); + this.callbacks.push(callback); + } + } + const getSubNVueById = function (id, isSub) { + // TODO 暂时通过 isSub 区分来自 subNVue 页面 + return new SubNvue(id, isSub); + }; - state.distbits = 6; - //state.distcode.copy(state.codes); - // Switch to use dynamic table - state.distcode = state.distdyn; - opts = { bits: state.distbits }; - ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.distbits = opts.bits; - // state.distcode = state.next; + const providers = { + oauth(callback) { + plus.oauth.getServices((services) => { + services = services; + const provider = []; + services.forEach(({ id }) => { + provider.push(id); + }); + callback(null, provider); + }, (err) => { + err = err; + callback(err); + }); + }, + share(callback) { + plus.share.getServices((services) => { + services = services; + const provider = []; + services.forEach(({ id }) => { + provider.push(id); + }); + callback(null, provider); + }, (err) => { + callback(err); + }); + }, + payment(callback) { + plus.payment.getChannels((services) => { + const provider = []; + services.forEach(({ id }) => { + provider.push(id); + }); + callback(null, provider); + }, (err) => { + callback(err); + }); + }, + push(callback) { + if (typeof weex !== 'undefined' || typeof plus !== 'undefined') { + callback(null, [plus.push.getClientInfo().id]); + } + else { + callback(null, []); + } + }, + }; + const getProvider = defineAsyncApi(API_GET_PROVIDER, ({ service }, { resolve, reject }) => { + if (providers[service]) { + providers[service]((err, provider) => { + if (err) { + reject(err.message); + } + else { + resolve({ + service, + provider: provider, + }); + } + }); + } + else { + reject('service not found'); + } + }, GetProviderProtocol); - if (ret) { - strm.msg = 'invalid distances set'; - state.mode = BAD; - break; - } - //Tracev((stderr, 'inflate: codes ok\n')); - state.mode = LEN_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case LEN_: - state.mode = LEN; - /* falls through */ - case LEN: - if (have >= 6 && left >= 258) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - inffast(strm, _out); - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- + let univerifyManager; + function getService(provider) { + return new Promise((resolve, reject) => { + plus.oauth.getServices((services) => { + const service = services.find(({ id }) => id === provider); + service ? resolve(service) : reject(new Error('provider not find')); + }, reject); + }); + } + const login = defineAsyncApi(API_LOGIN, (params, { resolve, reject }) => { + const provider = params.provider || 'weixin'; + const errorCallback = warpPlusErrorCallback(reject); + const authOptions = provider === 'apple' + ? { scope: 'email' } + : params.univerifyStyle + ? { + univerifyStyle: univerifyButtonsClickHandling(params.univerifyStyle, errorCallback), + } + : {}; + getService(provider) + .then((service) => { + function login() { + if (params.onlyAuthorize && provider === 'weixin') { + service.authorize(({ code }) => { + resolve({ + code, + authResult: '', + }); + }, errorCallback); + return; + } + service.login((res) => { + const authResult = res.target.authResult; + resolve({ + code: authResult.code, + authResult: authResult, + }); + }, errorCallback, authOptions); + } + // 先注销再登录 + // apple登录logout之后无法重新触发获取email,fullname;一键登录无logout + if (provider === 'apple' || provider === 'univerify') { + login(); + } + else { + service.logout(login, login); + } + }) + .catch(errorCallback); + }, LoginProtocol); + const baseGetUserInfo = (params, { resolve, reject }) => { + const provider = params.provider || 'weixin'; + const errorCallback = warpPlusErrorCallback(reject); + getService(provider) + .then((loginService) => { + loginService.getUserInfo((res) => { + let userInfo = { nickName: '' }; + if (provider === 'weixin') { + const wechatUserInfo = loginService.userInfo; + if (wechatUserInfo) + userInfo = { + openId: wechatUserInfo.openid, + nickName: wechatUserInfo.nickname, + gender: wechatUserInfo.sex, + city: wechatUserInfo.city, + province: wechatUserInfo.province, + country: wechatUserInfo.country, + avatarUrl: wechatUserInfo.headimgurl, + unionId: wechatUserInfo.unionid, + }; + } + else if (provider === 'apple') { + const appleInfo = loginService.appleInfo; + if (appleInfo) + userInfo = { + openId: appleInfo.user, + fullName: appleInfo.fullName, + email: appleInfo.email, + authorizationCode: appleInfo.authorizationCode, + identityToken: appleInfo.identityToken, + realUserStatus: appleInfo.realUserStatus, + }; + } + else { + userInfo = loginService.userInfo; + if (userInfo) { + userInfo.openId = + userInfo.openId || + userInfo.openid || + loginService.authResult.openid; + userInfo.nickName = userInfo.nickName || userInfo.nickname; + userInfo.avatarUrl = userInfo.avatarUrl || userInfo.headimgurl; + } + } + let result = {}; + // @ts-ignore + if (params.data && params.data.api_name === 'webapi_getuserinfo') { + result.data = { + data: JSON.stringify(userInfo), + rawData: '', + signature: '', + encryptedData: '', + iv: '', + }; + } + else { + result.userInfo = userInfo; + } + resolve(result); + }, errorCallback); + }) + .catch(() => { + reject('请先调用 uni.login'); + }); + }; + const getUserInfo = defineAsyncApi(API_GET_USER_INFO, baseGetUserInfo, GetUserInfoProtocol); + /** + * 获取用户信息-兼容 + */ + const getUserProfile = defineAsyncApi(API_GET_USER_PROFILE, baseGetUserInfo, GgetUserProfileProtocol); + const preLogin = defineAsyncApi(API_PRE_LOGIN, ({ provider }, { resolve, reject }) => { + const successCallback = warpPlusSuccessCallback(resolve); + const errorCallback = warpPlusErrorCallback(reject); + getService(provider) + .then((service) => service.preLogin(successCallback, errorCallback)) + .catch(errorCallback); + }, PreLoginProtocol, PreLoginOptions); + const _closeAuthView = () => getService('univerify').then((service) => service.closeAuthView()); + const closeAuthView = defineSyncApi(API_CLOSE_AUTH_VIEW, _closeAuthView); + const getCheckBoxState = defineAsyncApi(API_GET_CHECK_BOX_STATE, (_, { resolve, reject }) => { + const successCallback = warpPlusSuccessCallback(resolve); + const errorCallback = warpPlusErrorCallback(reject); + try { + getService('univerify').then((service) => { + // @ts-expect-error + const state = service.getCheckBoxState(); + successCallback({ state }); + }); + } + catch (error) { + errorCallback(error); + } + }); + /** + * 一键登录自定义登陆按钮点击处理 + */ + function univerifyButtonsClickHandling(univerifyStyle, errorCallback) { + if (isPlainObject(univerifyStyle) && + isPlainObject(univerifyStyle.buttons) && + toTypeString(univerifyStyle.buttons.list) === '[object Array]') { + univerifyStyle.buttons.list.forEach((button, index) => { + univerifyStyle.buttons.list[index].onclick = function () { + const res = { + code: '30008', + message: '用户点击了自定义按钮', + index, + provider: button.provider, + }; + isPlainObject(univerifyManager) + ? univerifyManager._triggerUniverifyButtonsClick(res) + : _closeAuthView().then(() => { + errorCallback(res); + }); + }; + }); + } + return univerifyStyle; + } + class UniverifyManager { + constructor() { + this.provider = 'univerify'; + this.eventName = 'api.univerifyButtonsClick'; + } + close() { + closeAuthView(); + } + login(options) { + login(this._getOptions(options)); + } + getCheckBoxState(options) { + getCheckBoxState(options); + } + preLogin(options) { + preLogin(this._getOptions(options)); + } + onButtonsClick(callback) { + UniServiceJSBridge.on(this.eventName, callback); + } + offButtonsClick(callback) { + UniServiceJSBridge.off(this.eventName, callback); + } + _triggerUniverifyButtonsClick(res) { + UniServiceJSBridge.emit(this.eventName, res); + } + _getOptions(options = {}) { + return extend({}, options, { provider: this.provider }); + } + } + const getUniverifyManager = defineSyncApi(API_GET_UNIVERIFY_MANAGER, () => { + return univerifyManager || (univerifyManager = new UniverifyManager()); + }); - if (state.mode === TYPE) { - state.back = -1; - } - break; - } - state.back = 0; - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; + const registerRuntime = defineSyncApi('registerRuntime', (runtime) => { + // @ts-expect-error + extend(jsRuntime, runtime); + }); - if (here_bits <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_op && (here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.lencode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; + // 0:图文,1:纯文字,2:纯图片,3:音乐,4:视频,5:小程序 + const TYPES = { + 0: { + name: 'web', + title: '图文', + }, + 1: { + name: 'text', + title: '纯文字', + }, + 2: { + name: 'image', + title: '纯图片', + }, + 3: { + name: 'music', + title: '音乐', + }, + 4: { + name: 'video', + title: '视频', + }, + 5: { + name: 'miniProgram', + title: '小程序', + }, + }; + const parseParams = (args) => { + args.type = args.type || 0; + let { provider, type, title, summary: content, href, imageUrl, mediaUrl: media, scene, miniProgram, } = args; + if (typeof imageUrl === 'string' && imageUrl) { + imageUrl = getRealPath(imageUrl); + } + const shareType = TYPES[type]; + if (shareType) { + const sendMsg = { + provider, + type: shareType.name, + title, + content, + href, + pictures: [imageUrl], + thumbs: imageUrl ? [imageUrl] : undefined, + media, + miniProgram, + extra: { + scene, + }, + }; + if (provider === 'weixin' && (type === 1 || type === 2)) { + delete sendMsg.thumbs; + } + return sendMsg; + } + return '分享参数 type 不正确'; + }; + const sendShareMsg = function (service, params, resolve, reject, method = 'share') { + const errorCallback = warpPlusErrorCallback(reject); + service.send(params, () => { + resolve(); + }, errorCallback); + }; + const share = defineAsyncApi(API_SHREA, (params, { resolve, reject }) => { + const res = parseParams(params); + const errorCallback = warpPlusErrorCallback(reject); + if (typeof res === 'string') { + return reject(res); + } + else { + params = res; + } + plus.share.getServices((services) => { + const service = services.find(({ id }) => id === params.provider); + if (!service) { + reject('service not found'); + } + else { + if (service.authenticated) { + sendShareMsg(service, params, resolve, reject); + } + else { + service.authorize(() => sendShareMsg(service, params, resolve, reject), errorCallback); + } + } + }, errorCallback); + }, ShareProtocols, SahreOptions); + const shareWithSystem = defineAsyncApi(API_SHARE_WITH_SYSTEM, ({ type, imageUrl, summary, href }, { resolve, reject }) => { + const errorCallback = warpPlusErrorCallback(reject); + if (typeof imageUrl === 'string' && imageUrl) { + imageUrl = getRealPath(imageUrl); + } + plus.share.sendWithSystem({ + type, + pictures: imageUrl ? [imageUrl] : undefined, + content: summary, + href, + }, () => resolve(), errorCallback); + }, ShareWithSystemProtocols, ShareWithSystemOptions); - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - state.length = here_val; - if (here_op === 0) { - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - state.mode = LIT; - break; - } - if (here_op & 32) { - //Tracevv((stderr, "inflate: end of block\n")); - state.back = -1; - state.mode = TYPE; - break; - } - if (here_op & 64) { - strm.msg = 'invalid literal/length code'; - state.mode = BAD; - break; - } - state.extra = here_op & 15; - state.mode = LENEXT; - /* falls through */ - case LENEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } - //Tracevv((stderr, "inflate: length %u\n", state.length)); - state.was = state.length; - state.mode = DIST; - /* falls through */ - case DIST: - for (;;) { - here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; + const requestPayment = defineAsyncApi(API_REQUEST_PAYMENT, (params, { resolve, reject }) => { + const provider = params.provider; + const errorCallback = warpPlusErrorCallback(reject); + plus.payment.getChannels((services) => { + const service = services.find(({ id }) => id === provider); + if (!service) { + reject('service not found'); + } + else { + plus.payment.request(service, params.orderInfo, (res) => { + resolve(res); + }, errorCallback); + } + }, errorCallback); + }, RequestPaymentProtocol); - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if ((here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.distcode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; + function injectLifecycleHook(name, hook, publicThis, instance) { + if (isFunction(hook)) { + vue.injectHook(name, hook.bind(publicThis), instance); + } + } + function initHooks(options, instance, publicThis) { + const mpType = options.mpType || publicThis.$mpType; + // 为了组件也可以监听部分生命周期,故不再判断mpType,统一添加on开头的生命周期 + Object.keys(options).forEach((name) => { + if (name.indexOf('on') === 0) { + const hooks = options[name]; + if (isArray$1(hooks)) { + hooks.forEach((hook) => injectLifecycleHook(name, hook, publicThis, instance)); + } + else { + injectLifecycleHook(name, hooks, publicThis, instance); + } + } + }); + if (mpType === 'page') { + instance.__isVisible = true; + try { + invokeHook(publicThis, ON_LOAD, instance.attrs.__pageQuery); + delete instance.attrs.__pageQuery; + } + catch (e) { + console.error(e.message + LINEFEED + e.stack); + } + vue.nextTick(() => { + // 延迟onShow,保证组件的onShow也可以监听到 + invokeHook(publicThis, ON_SHOW); + }); + } + } - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - if (here_op & 64) { - strm.msg = 'invalid distance code'; - state.mode = BAD; - break; - } - state.offset = here_val; - state.extra = (here_op) & 15; - state.mode = DISTEXT; - /* falls through */ - case DISTEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } - //#ifdef INFLATE_STRICT - if (state.offset > state.dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break; - } - //#endif - //Tracevv((stderr, "inflate: distance %u\n", state.offset)); - state.mode = MATCH; - /* falls through */ - case MATCH: - if (left === 0) { break inf_leave; } - copy = _out - left; - if (state.offset > copy) { /* copy from window */ - copy = state.offset - copy; - if (copy > state.whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break; - } - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - // Trace((stderr, "inflate.c too far\n")); - // copy -= state.whave; - // if (copy > state.length) { copy = state.length; } - // if (copy > left) { copy = left; } - // left -= copy; - // state.length -= copy; - // do { - // output[put++] = 0; - // } while (--copy); - // if (state.length === 0) { state.mode = LEN; } - // break; - //#endif - } - if (copy > state.wnext) { - copy -= state.wnext; - from = state.wsize - copy; - } - else { - from = state.wnext - copy; - } - if (copy > state.length) { copy = state.length; } - from_source = state.window; - } - else { /* copy from output */ - from_source = output; - from = put - state.offset; - copy = state.length; - } - if (copy > left) { copy = left; } - left -= copy; - state.length -= copy; - do { - output[put++] = from_source[from++]; - } while (--copy); - if (state.length === 0) { state.mode = LEN; } - break; - case LIT: - if (left === 0) { break inf_leave; } - output[put++] = state.length; - left--; - state.mode = LEN; - break; - case CHECK: - if (state.wrap) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - // Use '|' instead of '+' to make sure that result is signed - hold |= input[next++] << bits; - bits += 8; - } - //===// - _out -= left; - strm.total_out += _out; - state.total += _out; - if (_out) { - strm.adler = state.check = - /*UPDATE(state.check, put - _out, _out);*/ - (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out)); + function initRenderjs(options, instance) { + initModules(instance, options.$renderjs, options['$' + RENDERJS_MODULES]); + } + function initModules(instance, modules, moduleIds = {}) { + if (!isArray$1(modules)) { + return; + } + const ownerId = instance.uid; + // 在vue的定制内核中,通过$wxsModules来判断事件函数源码中是否包含该模块调用 + // !$wxsModules.find(module => invokerSourceCode.indexOf('.' + module + '.') > -1) + const $wxsModules = (instance.$wxsModules || + (instance.$wxsModules = [])); + const ctx = instance.ctx; + modules.forEach((module) => { + if (moduleIds[module]) { + ctx[module] = proxyModule(ownerId, moduleIds[module], module); + $wxsModules.push(module); + } + else { + if ((process.env.NODE_ENV !== 'production')) { + console.error(formatLog('initModules', modules, moduleIds)); + } + } + }); + } + function proxyModule(ownerId, moduleId, module) { + const target = {}; + return new Proxy(target, { + get(_, p) { + return (target[p] || + (target[p] = createModuleFunction(ownerId, moduleId, module, p))); + }, + }); + } + function createModuleFunction(ownerId, moduleId, module, name) { + const target = () => { }; + const toJSON = () => WXS_PROTOCOL + JSON.stringify([ownerId, moduleId, module + '.' + name]); + return new Proxy(target, { + get(_, p) { + if (p === 'toJSON') { + return toJSON; + } + return (target[p] || + (target[p] = createModuleFunction(ownerId, moduleId, module + '.' + name, p))); + }, + apply(_target, _thisArg, args) { + return (WXS_PROTOCOL + + JSON.stringify([ownerId, moduleId, module + '.' + name, [...args]])); + }, + }); + } + + function initWxs(options, instance) { + initModules(instance, options.$wxs, options['$' + WXS_MODULES]); + } + + function applyOptions(options, instance, publicThis) { + { + initWxs(options, instance); + initRenderjs(options, instance); + } + initHooks(options, instance, publicThis); + } - } - _out = left; - // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too - if ((state.flags ? hold : zswap32(hold)) !== state.check) { - strm.msg = 'incorrect data check'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: check matches trailer\n")); - } - state.mode = LENGTH; - /* falls through */ - case LENGTH: - if (state.wrap && state.flags) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.total & 0xffffffff)) { - strm.msg = 'incorrect length check'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: length matches trailer\n")); - } - state.mode = DONE; - /* falls through */ - case DONE: - ret = Z_STREAM_END$1; - break inf_leave; - case BAD: - ret = Z_DATA_ERROR$1; - break inf_leave; - case MEM: - return Z_MEM_ERROR$1; - case SYNC: - /* falls through */ - default: - return Z_STREAM_ERROR$1; - } - } + function set(target, key, val) { + return (target[key] = val); + } - // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + function errorHandler(err, instance, info) { + if (!instance) { + throw err; + } + const app = getApp(); + if (!app || !app.$vm) { + throw err; + } + { + invokeHook(app.$vm, ON_ERROR, err); + } + } + function mergeAsArray(to, from) { + return to ? [...new Set([].concat(to, from))] : from; + } + function initOptionMergeStrategies(optionMergeStrategies) { + UniLifecycleHooks.forEach((name) => { + optionMergeStrategies[name] = mergeAsArray; + }); + } - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ + let realAtob; + const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/; + if (typeof atob !== 'function') { + realAtob = function (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() { + const token = uni.getStorageSync('uni_id_token') || ''; + const tokenArr = token.split('.'); + if (!token || tokenArr.length !== 3) { + return { + uid: null, + role: [], + permission: [], + tokenExpired: 0, + }; + } + let 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(globalProperties) { + globalProperties.uniIDHasRole = function (roleId) { + const { role } = getCurrentUserInfo(); + return role.indexOf(roleId) > -1; + }; + globalProperties.uniIDHasPermission = function (permissionId) { + const { permission } = getCurrentUserInfo(); + return this.uniIDHasRole('admin') || permission.indexOf(permissionId) > -1; + }; + globalProperties.uniIDTokenValid = function () { + const { tokenExpired } = getCurrentUserInfo(); + return tokenExpired > Date.now(); + }; + } - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- + function initApp(app) { + const appConfig = app._context.config; + if (isFunction(app._component.onError)) { + appConfig.errorHandler = errorHandler; + } + initOptionMergeStrategies(appConfig.optionMergeStrategies); + const globalProperties = appConfig.globalProperties; + { + uniIdMixin(globalProperties); + } + { + globalProperties.$set = set; + globalProperties.$applyOptions = applyOptions; + } + } + + let isInitEntryPage = false; + function initEntry() { + if (isInitEntryPage) { + return; + } + isInitEntryPage = true; + let entryPagePath; + let entryPageQuery; + const weexPlus = weex.requireModule('plus'); + if (weexPlus.getRedirectInfo) { + const { path, query, referrerInfo } = parseRedirectInfo(); + entryPagePath = path; + entryPageQuery = query; + __uniConfig.referrerInfo = referrerInfo; + } + else { + const argsJsonStr = plus.runtime.arguments; + if (!argsJsonStr) { + return; + } + try { + const args = JSON.parse(argsJsonStr); + entryPagePath = args.path || args.pathName; + entryPageQuery = args.query ? '?' + args.query : ''; + } + catch (e) { } + } + if (!entryPagePath || entryPagePath === __uniConfig.entryPagePath) { + if (entryPageQuery) { + __uniConfig.entryPageQuery = entryPageQuery; + } + return; + } + const entryRoute = addLeadingSlash(entryPagePath); + const routeOptions = getRouteOptions(entryRoute); + if (!routeOptions) { + return; + } + if (!routeOptions.meta.isTabBar) { + __uniConfig.realEntryPagePath = + __uniConfig.realEntryPagePath || __uniConfig.entryPagePath; + } + __uniConfig.entryPagePath = entryPagePath; + __uniConfig.entryPageQuery = entryPageQuery; + } + + function initTabBar() { + const { tabBar } = __uniConfig; + const len = tabBar && tabBar.list && tabBar.list.length; + if (!len) { + return; + } + const { entryPagePath } = __uniConfig; + tabBar.selectedIndex = 0; + const selected = tabBar.list.findIndex((page) => page.pagePath === entryPagePath); + tabBar$1.init(tabBar, (item, index) => { + uni.switchTab({ + url: addLeadingSlash(item.pagePath), + openType: 'switchTab', + from: 'tabBar', + success() { + invokeHook(ON_TAB_ITEM_TAP, { + index, + text: item.text, + pagePath: item.pagePath, + }); + }, + }); + }); + if (selected !== -1) { + // 取当前 tab 索引值 + tabBar.selectedIndex = selected; + selected !== 0 && tabBar$1.switchTab(entryPagePath); + } + } - if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && - (state.mode < CHECK || flush !== Z_FINISH$1))) { - if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; - } - _in -= strm.avail_in; - _out -= strm.avail_out; - strm.total_in += _in; - strm.total_out += _out; - state.total += _out; - if (state.wrap && _out) { - strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ - (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out)); - } - strm.data_type = state.bits + (state.last ? 64 : 0) + - (state.mode === TYPE ? 128 : 0) + - (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); - if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) { - ret = Z_BUF_ERROR; - } - return ret; - }; + function initRouteOptions(path, openType) { + // 需要序列化一遍 + const routeOptions = JSON.parse(JSON.stringify(getRouteOptions(path))); + routeOptions.meta = initRouteMeta(routeOptions.meta); + if (openType === 'reLaunch' || + (!__uniConfig.realEntryPagePath && getCurrentPages().length === 0) // redirectTo + ) { + routeOptions.meta.isQuit = true; + } + else if (!routeOptions.meta.isTabBar) { + routeOptions.meta.isQuit = false; + } + // TODO + // if (routeOptions.meta.isTabBar) { + // routeOptions.meta.visible = true + // } + return routeOptions; + } + function initNVue(webviewStyle, routeMeta, path) { + if (path && routeMeta.isNVue) { + webviewStyle.uniNView = { + path, + defaultFontSize: __uniConfig.defaultFontSize, + viewport: __uniConfig.viewport, + }; + } + } - const inflateEnd = (strm) => { + const colorRE = /^#[a-z0-9]{6}$/i; + function isColor(color) { + return color && (colorRE.test(color) || color === 'transparent'); + } - if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { - return Z_STREAM_ERROR$1; - } + function initBackgroundColor(webviewStyle, routeMeta) { + const { backgroundColor } = routeMeta; + if (!backgroundColor) { + return; + } + if (!isColor(backgroundColor)) { + return; + } + if (!webviewStyle.background) { + webviewStyle.background = backgroundColor; + } + if (!webviewStyle.backgroundColorTop) { + webviewStyle.backgroundColorTop = backgroundColor; + } + } - let state = strm.state; - if (state.window) { - state.window = null; - } - strm.state = null; - return Z_OK$1; + function initPopGesture(webviewStyle, routeMeta) { + // 不支持 hide + if (webviewStyle.popGesture === 'hide') { + delete webviewStyle.popGesture; + } + // 似乎没用了吧?记得是之前流应用时,需要 appback 的逻辑 + if (routeMeta.isQuit) { + webviewStyle.popGesture = (plus.os.name === 'iOS' ? 'appback' : 'none'); + } + } + + function initPullToRefresh(webviewStyle, routeMeta) { + if (!routeMeta.enablePullDownRefresh) { + return; + } + const pullToRefresh = normalizePullToRefreshRpx(extend({}, plus.os.name === 'Android' + ? defaultAndroidPullToRefresh + : defaultPullToRefresh, routeMeta.pullToRefresh)); + webviewStyle.pullToRefresh = initWebviewPullToRefreshI18n(pullToRefresh, routeMeta); + } + function initWebviewPullToRefreshI18n(pullToRefresh, routeMeta) { + const i18nResult = initPullToRefreshI18n(pullToRefresh); + if (!i18nResult) { + return pullToRefresh; + } + const [contentdownI18n, contentoverI18n, contentrefreshI18n] = i18nResult; + if (contentdownI18n || contentoverI18n || contentrefreshI18n) { + uni.onLocaleChange(() => { + const webview = plus.webview.getWebviewById(routeMeta.id + ''); + if (!webview) { + return; + } + const newPullToRefresh = { + support: true, + }; + if (contentdownI18n) { + newPullToRefresh.contentdown = { + caption: pullToRefresh.contentdown.caption, + }; + } + if (contentoverI18n) { + newPullToRefresh.contentover = { + caption: pullToRefresh.contentover.caption, + }; + } + if (contentrefreshI18n) { + newPullToRefresh.contentrefresh = { + caption: pullToRefresh.contentrefresh.caption, + }; + } + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('updateWebview', webview.id, newPullToRefresh)); + } + webview.setStyle({ + pullToRefresh: newPullToRefresh, + }); + }); + } + return pullToRefresh; + } + const defaultAndroidPullToRefresh = { support: true, style: 'circle' }; + const defaultPullToRefresh = { + support: true, + style: 'default', + height: '50px', + range: '200px', + contentdown: { + caption: '', + }, + contentover: { + caption: '', + }, + contentrefresh: { + caption: '', + }, }; + function initTitleNView(webviewStyle, routeMeta) { + const { navigationBar } = routeMeta; + if (navigationBar.style === 'custom') { + return false; + } + let autoBackButton = true; + if (routeMeta.isQuit) { + autoBackButton = false; + } + const titleNView = { + autoBackButton, + }; + Object.keys(navigationBar).forEach((name) => { + const value = navigationBar[name]; + if (name === 'backgroundColor') { + titleNView.backgroundColor = isColor(value) + ? value + : BACKGROUND_COLOR; + } + else if (name === 'titleImage' && value) { + titleNView.tags = createTitleImageTags(value); + } + else if (name === 'buttons' && isArray$1(value)) { + titleNView.buttons = value.map((button, index) => { + button.onclick = createTitleNViewBtnClick(index); + return button; + }); + } + else { + titleNView[name] = + value; + } + }); + webviewStyle.titleNView = initTitleNViewI18n(titleNView, routeMeta); + } + function initTitleNViewI18n(titleNView, routeMeta) { + const i18nResult = initNavigationBarI18n(titleNView); + if (!i18nResult) { + return titleNView; + } + const [titleTextI18n, searchInputPlaceholderI18n] = i18nResult; + if (titleTextI18n || searchInputPlaceholderI18n) { + uni.onLocaleChange(() => { + const webview = plus.webview.getWebviewById(routeMeta.id + ''); + if (!webview) { + return; + } + const newTitleNView = {}; + if (titleTextI18n) { + newTitleNView.titleText = titleNView.titleText; + } + if (searchInputPlaceholderI18n) { + newTitleNView.searchInput = { + placeholder: titleNView.searchInput.placeholder, + }; + } + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('updateWebview', webview.id, newTitleNView)); + } + webview.setStyle({ + titleNView: newTitleNView, + }); + }); + } + return titleNView; + } + function createTitleImageTags(titleImage) { + return [ + { + tag: 'img', + src: titleImage, + position: { + left: 'auto', + top: 'auto', + width: 'auto', + height: '26px', + }, + }, + ]; + } + function createTitleNViewBtnClick(index) { + return function onClick(btn) { + btn.index = index; + invokeHook(ON_NAVIGATION_BAR_BUTTON_TAP, btn); + }; + } + + function parseWebviewStyle(path, routeMeta) { + const webviewStyle = { + bounce: 'vertical', + }; + Object.keys(routeMeta).forEach((name) => { + if (WEBVIEW_STYLE_BLACKLIST.indexOf(name) === -1) { + webviewStyle[name] = + routeMeta[name]; + } + }); + initNVue(webviewStyle, routeMeta, path); + initPopGesture(webviewStyle, routeMeta); + initBackgroundColor(webviewStyle, routeMeta); + initTitleNView(webviewStyle, routeMeta); + initPullToRefresh(webviewStyle, routeMeta); + return webviewStyle; + } + const WEBVIEW_STYLE_BLACKLIST = [ + 'id', + 'route', + 'isNVue', + 'isQuit', + 'isEntry', + 'isTabBar', + 'tabBarIndex', + 'windowTop', + 'topWindow', + 'leftWindow', + 'rightWindow', + 'maxWidth', + 'usingComponents', + 'disableScroll', + 'enablePullDownRefresh', + 'navigationBar', + 'pullToRefresh', + 'onReachBottomDistance', + 'pageOrientation', + 'backgroundColor', + ]; - const inflateGetHeader = (strm, head) => { + let id = 2; + function getWebviewId() { + return id; + } + function genWebviewId() { + return id++; + } + function encode(val) { + return val; + } + function initUniPageUrl(path, query) { + const queryString = query ? stringifyQuery$1(query, encode) : ''; + return { + path: path.substr(1), + query: queryString ? queryString.substr(1) : queryString, + }; + } + function initDebugRefresh(isTab, path, query) { + const queryString = query ? stringifyQuery$1(query, encode) : ''; + return { + isTab, + arguments: JSON.stringify({ + path: path.substr(1), + query: queryString ? queryString.substr(1) : queryString, + }), + }; + } - /* check state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR$1; } - const state = strm.state; - if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; } + function createNVueWebview({ path, query, routeOptions, webviewStyle, }) { + const curWebviewId = genWebviewId(); + const curWebviewStyle = parseWebviewStyle(path, routeOptions.meta); + curWebviewStyle.uniPageUrl = initUniPageUrl(path, query); + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('createNVueWebview', curWebviewId, path, curWebviewStyle)); + } + curWebviewStyle.isTab = !!routeOptions.meta.isTabBar; + return plus.webview.create('', String(curWebviewId), curWebviewStyle, extend({ + nvue: true, + }, webviewStyle)); + } - /* save header structure */ - state.head = head; - head.done = false; - return Z_OK$1; - }; + const downgrade = plus.os.name === 'Android' && parseInt(plus.os.version) < 6; + const ANI_SHOW = downgrade ? 'slide-in-right' : 'pop-in'; + const ANI_DURATION = 300; + const ANI_CLOSE = downgrade ? 'slide-out-right' : 'pop-out'; + const VIEW_WEBVIEW_PATH = '_www/__uniappview.html'; + const WEBVIEW_ID_PREFIX = 'webviewId'; + let preloadWebview$1; + function setPreloadWebview(webview) { + preloadWebview$1 = webview; + } + function getPreloadWebview() { + return preloadWebview$1; + } + function createPreloadWebview() { + if (!preloadWebview$1 || preloadWebview$1.__uniapp_route) { + // 不存在,或已被使用 + preloadWebview$1 = plus.webview.create(VIEW_WEBVIEW_PATH, String(genWebviewId()), + // @ts-expect-error + { contentAdjust: false }); + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('createPreloadWebview', preloadWebview$1.id)); + } + } + return preloadWebview$1; + } - const inflateSetDictionary = (strm, dictionary) => { - const dictLength = dictionary.length; + function onWebviewClose(webview) { + const { popupSubNVueWebviews } = webview; + if (!popupSubNVueWebviews) { + return; + } + webview.addEventListener('close', () => { + Object.keys(popupSubNVueWebviews).forEach((id) => { + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('onWebviewClose', webview.id, 'popupSubNVueWebview', id, 'close')); + } + popupSubNVueWebviews[id].close('none'); + }); + }); + } - let state; - let dictid; - let ret; + let lastStatusBarStyle; + let oldSetStatusBarStyle = plus.navigator.setStatusBarStyle; + function restoreOldSetStatusBarStyle(setStatusBarStyle) { + oldSetStatusBarStyle = setStatusBarStyle; + } + function newSetStatusBarStyle(style) { + lastStatusBarStyle = style; + oldSetStatusBarStyle(style); + } + plus.navigator.setStatusBarStyle = newSetStatusBarStyle; + function setStatusBarStyle(statusBarStyle) { + if (!statusBarStyle) { + const page = getCurrentPage(); + if (!page) { + return; + } + statusBarStyle = page.$page.statusBarStyle; + if (!statusBarStyle || statusBarStyle === lastStatusBarStyle) { + return; + } + } + if (statusBarStyle === lastStatusBarStyle) { + return; + } + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('setStatusBarStyle', statusBarStyle)); + } + lastStatusBarStyle = statusBarStyle; + plus.navigator.setStatusBarStyle(statusBarStyle); + } - /* check state */ - if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR$1; } - state = strm.state; + let vueApp; + function getVueApp() { + return vueApp; + } + function initVueApp(appVm) { + const appContext = appVm.$.appContext; + vueApp = extend(appContext.app, { + mountPage(pageComponent, pageProps, pageContainer) { + const vnode = vue.createVNode(pageComponent, pageProps); + // store app context on the root VNode. + // this will be set on the root instance on initial mount. + vnode.appContext = appContext; + vnode.__page_container__ = pageContainer; + vue.render(vnode, pageContainer); + const publicThis = vnode.component.proxy; + publicThis.__page_container__ = pageContainer; + return publicThis; + }, + unmountPage: (pageInstance) => { + const { __page_container__ } = pageInstance; + if (__page_container__) { + __page_container__.isUnmounted = true; + vue.render(null, __page_container__); + } + }, + }); + } - if (state.wrap !== 0 && state.mode !== DICT) { - return Z_STREAM_ERROR$1; - } + const pages = []; + function addCurrentPage(page) { + pages.push(page); + } + function getPageById(id) { + return pages.find((page) => page.$page.id === id); + } + function getAllPages() { + return pages; + } + function getCurrentPages$1() { + const curPages = []; + pages.forEach((page) => { + if (page.$.__isTabBar) { + if (page.$.__isActive) { + curPages.push(page); + } + } + else { + curPages.push(page); + } + }); + return curPages; + } + function removeCurrentPage() { + const page = getCurrentPage(); + if (!page) { + return; + } + removePage(page); + } + function removePage(curPage) { + const index = pages.findIndex((page) => page === curPage); + if (index === -1) { + return; + } + if (!curPage.$page.meta.isNVue) { + getVueApp().unmountPage(curPage); + } + pages.splice(index, 1); + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('removePage', curPage.$page)); + } + } - /* check for correct dictionary identifier */ - if (state.mode === DICT) { - dictid = 1; /* adler32(0, null, 0)*/ - /* dictid = adler32(dictid, dictionary, dictLength); */ - dictid = adler32_1(dictid, dictionary, dictLength, 0); - if (dictid !== state.check) { - return Z_DATA_ERROR$1; - } - } - /* copy dictionary to window using updatewindow(), which will amend the - existing dictionary if appropriate */ - ret = updatewindow(strm, dictionary, dictLength, dictLength); - if (ret) { - state.mode = MEM; - return Z_MEM_ERROR$1; - } - state.havedict = 1; - // Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK$1; - }; + function onWebviewPopGesture(webview) { + let popStartStatusBarStyle; + webview.addEventListener('popGesture', (e) => { + if (e.type === 'start') { + // 设置下一个页面的 statusBarStyle + const pages = getCurrentPages(); + const page = pages[pages.length - 2]; + popStartStatusBarStyle = lastStatusBarStyle; + const statusBarStyle = page && page.$page.statusBarStyle; + statusBarStyle && setStatusBarStyle(statusBarStyle); + } + else if (e.type === 'end' && !e.result) { + // 拖拽未完成,设置为当前状态栏前景色 + setStatusBarStyle(popStartStatusBarStyle); + } + else if (e.type === 'end' && e.result) { + removeCurrentPage(); + setStatusBarStyle(); + // 触发前一个页面 onShow + invokeHook(ON_SHOW); + } + }); + } + function onWebviewRecovery(webview) { + if (webview.nvue) { + return; + } + const webviewId = webview.id; + const { subscribe, unsubscribe } = UniServiceJSBridge; + const onWebviewRecoveryReady = (_, pageId) => { + if (webviewId !== pageId) { + return; + } + unsubscribe(ON_WEBVIEW_READY, onWebviewRecoveryReady); + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog(`Recovery`, webviewId, 'ready')); + } + const page = getPageById(parseInt(pageId)); + if (page) { + const pageNode = page.__page_container__; + pageNode.restore(); + } + }; + // @ts-expect-error + webview.addEventListener('recovery', () => { + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('Recovery', webview.id)); + } + subscribe(ON_WEBVIEW_READY, onWebviewRecoveryReady); + }); + } - var inflateReset_1 = inflateReset; - var inflateReset2_1 = inflateReset2; - var inflateResetKeep_1 = inflateResetKeep; - var inflateInit_1 = inflateInit; - var inflateInit2_1 = inflateInit2; - var inflate_2$1 = inflate$2; - var inflateEnd_1 = inflateEnd; - var inflateGetHeader_1 = inflateGetHeader; - var inflateSetDictionary_1 = inflateSetDictionary; - var inflateInfo = 'pako inflate (from Nodeca project)'; + function onWebviewResize(webview) { + const { emit } = UniServiceJSBridge; + const onResize = function ({ width, height, }) { + const landscape = Math.abs(plus.navigator.getOrientation()) === 90; + const res = { + deviceOrientation: landscape ? 'landscape' : 'portrait', + size: { + windowWidth: Math.ceil(width), + windowHeight: Math.ceil(height), + }, + }; + emit(ON_RESIZE, res, parseInt(webview.id)); // Page lifecycle + }; + webview.addEventListener('resize', debounce(onResize, 50)); + } - /* Not implemented - module.exports.inflateCopy = inflateCopy; - module.exports.inflateGetDictionary = inflateGetDictionary; - module.exports.inflateMark = inflateMark; - module.exports.inflatePrime = inflatePrime; - module.exports.inflateSync = inflateSync; - module.exports.inflateSyncPoint = inflateSyncPoint; - module.exports.inflateUndermine = inflateUndermine; - */ + const WEBVIEW_LISTENERS = { + pullToRefresh: ON_PULL_DOWN_REFRESH, + titleNViewSearchInputChanged: ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, + titleNViewSearchInputConfirmed: ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, + titleNViewSearchInputClicked: ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, + titleNViewSearchInputFocusChanged: ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, + }; + function initWebviewEvent(webview) { + const id = parseInt(webview.id); + Object.keys(WEBVIEW_LISTENERS).forEach((name) => { + const hook = WEBVIEW_LISTENERS[name]; + webview.addEventListener(name, (e) => { + if (hook === ON_PULL_DOWN_REFRESH) { + // 设置当前正在下拉刷新的webview + setPullDownRefreshWebview(webview); + } + invokeHook(id, hook, e); + }); + }); + onWebviewClose(webview); + onWebviewResize(webview); + if (plus.os.name === 'iOS') { + onWebviewRecovery(webview); + onWebviewPopGesture(webview); + } + } - var inflate_1$2 = { - inflateReset: inflateReset_1, - inflateReset2: inflateReset2_1, - inflateResetKeep: inflateResetKeep_1, - inflateInit: inflateInit_1, - inflateInit2: inflateInit2_1, - inflate: inflate_2$1, - inflateEnd: inflateEnd_1, - inflateGetHeader: inflateGetHeader_1, - inflateSetDictionary: inflateSetDictionary_1, - inflateInfo: inflateInfo - }; + function initWebviewStyle(webview, path, query, routeMeta) { + const webviewStyle = parseWebviewStyle(path, routeMeta); + webviewStyle.uniPageUrl = initUniPageUrl(path, query); + const isTabBar = !!routeMeta.isTabBar; + if (!routeMeta.isNVue) { + webviewStyle.debugRefresh = initDebugRefresh(isTabBar, path, query); + } + else { + // android 需要使用 + webviewStyle.isTab = isTabBar; + } + webviewStyle.locale = weex.requireModule('plus').getLanguage(); + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('updateWebview', webviewStyle)); + } + webview.setStyle(webviewStyle); + } - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. + function initSubNVues(webview, path, routeMeta) { + const subNVues = routeMeta.subNVues || []; + subNVues.forEach((subNVue) => { + if (!subNVue.path) { + return; + } + const style = subNVue.style || {}; + const isNavigationBar = subNVue.type === 'navigationBar'; + const isPopup = subNVue.type === 'popup'; + style.uniNView = { + path: subNVue.path.replace('.nvue', '.js'), + defaultFontSize: __uniConfig.defaultFontSize, + viewport: __uniConfig.viewport, + }; + const extras = { + __uniapp_host: path, + __uniapp_origin: style.uniNView.path.split('?')[0].replace('.js', ''), + __uniapp_origin_id: webview.id, + __uniapp_origin_type: webview.__uniapp_type, + }; + let maskWebview; + if (isNavigationBar) { + style.position = 'dock'; + style.dock = 'top'; + style.top = '0'; + style.width = '100%'; + style.height = String(NAVBAR_HEIGHT + getStatusbarHeight()); + delete style.left; + delete style.right; + delete style.bottom; + delete style.margin; + } + else if (isPopup) { + style.position = 'absolute'; + if (isTabBarPage$1(path)) { + maskWebview = tabBar$1; + } + else { + maskWebview = webview; + } + extras.__uniapp_mask = style.mask || 'rgba(0,0,0,0.5)'; + extras.__uniapp_mask_id = maskWebview.id; + } + delete style.mask; + const subNVueWebview = plus.webview.create('', subNVue.id, style, extras); + if (isPopup) { + if (!maskWebview.popupSubNVueWebviews) { + maskWebview.popupSubNVueWebviews = {}; + } + maskWebview.popupSubNVueWebviews[subNVueWebview.id] = subNVueWebview; + const hideSubNVue = function () { + maskWebview.setStyle({ + mask: 'none', + }); + subNVueWebview.hide('auto'); + }; + maskWebview.addEventListener('maskClick', hideSubNVue); + let isRemoved = false; // 增加个 remove 标记,防止出错 + subNVueWebview.addEventListener('show', () => { + if (!isRemoved) { + plus.key.removeEventListener('backbutton', backbuttonListener); + plus.key.addEventListener('backbutton', hideSubNVue); + isRemoved = true; + } + }); + subNVueWebview.addEventListener('hide', () => { + if (isRemoved) { + plus.key.removeEventListener('backbutton', hideSubNVue); + plus.key.addEventListener('backbutton', backbuttonListener); + isRemoved = false; + } + }); + subNVueWebview.addEventListener('close', () => { + delete maskWebview.popupSubNVueWebviews[subNVueWebview.id]; + if (isRemoved) { + plus.key.removeEventListener('backbutton', hideSubNVue); + plus.key.addEventListener('backbutton', backbuttonListener); + isRemoved = false; + } + }); + } + else { + webview.append(subNVueWebview); + } + }); + } - function GZheader() { - /* true if compressed data believed to be text */ - this.text = 0; - /* modification time */ - this.time = 0; - /* extra flags (not used when writing a gzip file) */ - this.xflags = 0; - /* operating system */ - this.os = 0; - /* pointer to extra field or Z_NULL if none */ - this.extra = null; - /* extra field length (valid if extra != Z_NULL) */ - this.extra_len = 0; // Actually, we don't need it in JS, - // but leave for few code modifications + function initWebview(webview, path, query, routeMeta) { + // 首页或非 nvue 页面 + if (webview.id === '1' || !routeMeta.isNVue) { + // path 必须参数为空,因为首页已经在 manifest.json 中设置了 uniNView,不能再次设置,否则会二次加载 + initWebviewStyle(webview, '', query, routeMeta); + } + initSubNVues(webview, path, routeMeta); + initWebviewEvent(webview); + } - // - // Setup limits is not necessary because in js we should not preallocate memory - // for inflate use constant limit in 65536 bytes - // + function createWebview(options) { + if (options.routeOptions.meta.isNVue) { + return createNVueWebview(options); + } + if (getWebviewId() === 2) { + // 如果首页非 nvue,则直接返回 Launch Webview + return plus.webview.getLaunchWebview(); + } + return getPreloadWebview(); + } + function onWebviewReady(pageId, callback) { + UniServiceJSBridge.once(ON_WEBVIEW_READY + '.' + pageId, callback); + } - /* space at extra (only when reading header) */ - // this.extra_max = 0; - /* pointer to zero-terminated file name or Z_NULL */ - this.name = ''; - /* space at name (only when reading header) */ - // this.name_max = 0; - /* pointer to zero-terminated comment or Z_NULL */ - this.comment = ''; - /* space at comment (only when reading header) */ - // this.comm_max = 0; - /* true if there was or will be a header crc */ - this.hcrc = 0; - /* true when done reading gzip header (not used when writing a gzip file) */ - this.done = false; + class UniPageNode extends UniNode { + constructor(pageId, options, setup = false) { + super(NODE_TYPE_PAGE, '#page', null); + this._id = 1; + this._created = false; + this._updating = false; + this._createActionMap = new Map(); + this.updateActions = []; + this.dicts = []; + this.nodeId = 0; + this.pageId = pageId; + this.pageNode = this; + this.options = options; + this.isUnmounted = false; + this.createAction = [ACTION_TYPE_PAGE_CREATE, options]; + this.createdAction = [ACTION_TYPE_PAGE_CREATED]; + this.normalizeDict = this._normalizeDict.bind(this); + this._update = this.update.bind(this); + setup && this.setup(); + } + _normalizeDict(value, normalizeValue = true) { + if (!isPlainObject(value)) { + return this.addDict(value); + } + const dictArray = []; + Object.keys(value).forEach((n) => { + const dict = [this.addDict(n)]; + const v = value[n]; + if (normalizeValue) { + dict.push(this.addDict(v)); + } + else { + dict.push(v); + } + dictArray.push(dict); + }); + return dictArray; + } + addDict(value) { + const { dicts } = this; + const index = dicts.indexOf(value); + if (index > -1) { + return index; + } + return dicts.push(value) - 1; + } + onInjectHook(hook) { + if ((hook === ON_PAGE_SCROLL || hook === ON_REACH_BOTTOM) && + !this.scrollAction) { + this.scrollAction = [ + ACTION_TYPE_PAGE_SCROLL, + this.options.onReachBottomDistance, + ]; + this.push(this.scrollAction); + } + } + onCreate(thisNode, nodeName) { + pushCreateAction(this, thisNode.nodeId, nodeName); + return thisNode; + } + onInsertBefore(thisNode, newChild, refChild) { + pushInsertAction(this, newChild, thisNode.nodeId, (refChild && refChild.nodeId) || -1); + return newChild; + } + onRemoveChild(oldChild) { + pushRemoveAction(this, oldChild.nodeId); + return oldChild; + } + onAddEvent(thisNode, name, flag) { + if (thisNode.parentNode) { + pushAddEventAction(this, thisNode.nodeId, name, flag); + } + } + onAddWxsEvent(thisNode, name, wxsEvent, flag) { + if (thisNode.parentNode) { + pushAddWxsEventAction(this, thisNode.nodeId, name, wxsEvent, flag); + } + } + onRemoveEvent(thisNode, name) { + if (thisNode.parentNode) { + pushRemoveEventAction(this, thisNode.nodeId, name); + } + } + onSetAttribute(thisNode, qualifiedName, value) { + if (thisNode.parentNode) { + pushSetAttributeAction(this, thisNode.nodeId, qualifiedName, value); + } + } + onRemoveAttribute(thisNode, qualifiedName) { + if (thisNode.parentNode) { + pushRemoveAttributeAction(this, thisNode.nodeId, qualifiedName); + } + } + onTextContent(thisNode, text) { + if (thisNode.parentNode) { + pushSetTextAction(this, thisNode.nodeId, text); + } + } + onNodeValue(thisNode, val) { + if (thisNode.parentNode) { + pushSetTextAction(this, thisNode.nodeId, val); + } + } + genId() { + return this._id++; + } + push(action, extras) { + if (this.isUnmounted) { + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('PageNode', 'push.prevent', action)); + } + return; + } + switch (action[0]) { + case ACTION_TYPE_CREATE: + this._createActionMap.set(action[1], action); + break; + case ACTION_TYPE_INSERT: + const createAction = this._createActionMap.get(action[1]); + if (createAction) { + createAction[3] = action[2]; // parentNodeId + createAction[4] = action[3]; // anchorId + if (extras) { + createAction[5] = extras; + } + } + else { + if ((process.env.NODE_ENV !== 'production')) { + console.error(formatLog(`Insert`, action, 'not found createAction')); + } + } + break; + } + // insert 被合并进 create + if (action[0] !== ACTION_TYPE_INSERT) { + this.updateActions.push(action); + } + if (!this._updating) { + this._updating = true; + vue.queuePostFlushCb(this._update); + } + } + restore() { + this.clear(); + this.push(this.createAction); + if (this.scrollAction) { + this.push(this.scrollAction); + } + const restoreNode = (node) => { + this.onCreate(node, node.nodeName); + this.onInsertBefore(node.parentNode, node, null); + node.childNodes.forEach((childNode) => { + restoreNode(childNode); + }); + }; + this.childNodes.forEach((childNode) => restoreNode(childNode)); + this.push(this.createdAction); + } + setup() { + this.send([this.createAction]); + } + update() { + const { dicts, updateActions, _createActionMap } = this; + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('PageNode', 'update', updateActions.length, _createActionMap.size)); + } + // 首次 + if (!this._created) { + this._created = true; + updateActions.push(this.createdAction); + } + if (updateActions.length) { + if (dicts.length) { + updateActions.unshift([ACTION_TYPE_DICT, dicts]); + } + this.send(updateActions); + } + this.clear(); + } + clear() { + this.dicts.length = 0; + this.updateActions.length = 0; + this._updating = false; + this._createActionMap.clear(); + } + send(action) { + UniServiceJSBridge.publishHandler(VD_SYNC, action, this.pageId); + } + fireEvent(id, evt) { + const node = findNodeById(id, this); + if (node) { + node.dispatchEvent(evt); + } + else if ((process.env.NODE_ENV !== 'production')) { + console.error(formatLog('PageNode', 'fireEvent', id, 'not found', evt)); + } + } + } + function getPageNode(pageId) { + const page = getPageById(pageId); + if (!page) + return null; + return page.__page_container__; + } + function findNode(name, value, uniNode) { + if (typeof uniNode === 'number') { + uniNode = getPageNode(uniNode); + } + if (uniNode[name] === value) { + return uniNode; + } + const { childNodes } = uniNode; + for (let i = 0; i < childNodes.length; i++) { + const uniNode = findNode(name, value, childNodes[i]); + if (uniNode) { + return uniNode; + } + } + return null; + } + function findNodeById(nodeId, uniNode) { + return findNode('nodeId', nodeId, uniNode); + } + function findNodeByTagName(tagName, uniNode) { + return findNode('nodeName', tagName.toUpperCase(), uniNode); + } + function pushCreateAction(pageNode, nodeId, nodeName) { + pageNode.push([ + ACTION_TYPE_CREATE, + nodeId, + pageNode.addDict(nodeName), + -1, + -1, + ]); + } + function pushInsertAction(pageNode, newChild, parentNodeId, refChildId) { + const nodeJson = newChild.toJSON({ + attr: true, + normalize: pageNode.normalizeDict, + }); + pageNode.push([ACTION_TYPE_INSERT, newChild.nodeId, parentNodeId, refChildId], Object.keys(nodeJson).length ? nodeJson : undefined); + } + function pushRemoveAction(pageNode, nodeId) { + pageNode.push([ACTION_TYPE_REMOVE, nodeId]); + } + function pushAddEventAction(pageNode, nodeId, name, value) { + pageNode.push([ACTION_TYPE_ADD_EVENT, nodeId, pageNode.addDict(name), value]); + } + function pushAddWxsEventAction(pageNode, nodeId, name, wxsEvent, value) { + pageNode.push([ + ACTION_TYPE_ADD_WXS_EVENT, + nodeId, + pageNode.addDict(name), + pageNode.addDict(wxsEvent), + value, + ]); + } + function pushRemoveEventAction(pageNode, nodeId, name) { + pageNode.push([ACTION_TYPE_REMOVE_EVENT, nodeId, pageNode.addDict(name)]); + } + function normalizeAttrValue(pageNode, name, value) { + return name === 'style' && isPlainObject(value) + ? pageNode.normalizeDict(value) + : pageNode.addDict(value); + } + function pushSetAttributeAction(pageNode, nodeId, name, value) { + pageNode.push([ + ACTION_TYPE_SET_ATTRIBUTE, + nodeId, + pageNode.addDict(name), + normalizeAttrValue(pageNode, name, value), + ]); + } + function pushRemoveAttributeAction(pageNode, nodeId, name) { + pageNode.push([ACTION_TYPE_REMOVE_ATTRIBUTE, nodeId, pageNode.addDict(name)]); + } + function pushSetTextAction(pageNode, nodeId, text) { + pageNode.push([ACTION_TYPE_SET_TEXT, nodeId, pageNode.addDict(text)]); + } + function createPageNode(pageId, pageOptions, setup) { + return new UniPageNode(pageId, pageOptions, setup); } - var gzheader = GZheader; - - const toString = Object.prototype.toString; - - /* Public constants ==========================================================*/ - /* ===========================================================================*/ - - const { - Z_NO_FLUSH, Z_FINISH, - Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR - } = constants$2; - - /* ===========================================================================*/ - - - /** - * class Inflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[inflate]] - * and [[inflateRaw]]. - **/ - - /* internal - * inflate.chunks -> Array - * - * Chunks of output data, if [[Inflate#onData]] not overridden. - **/ - - /** - * Inflate.result -> Uint8Array|String - * - * Uncompressed result, generated by default [[Inflate#onData]] - * and [[Inflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Inflate#push]] with `Z_FINISH` / `true` param). - **/ - - /** - * Inflate.err -> Number - * - * Error code after inflate finished. 0 (Z_OK) on success. - * Should be checked if broken data possible. - **/ - - /** - * Inflate.msg -> String - * - * Error message, if [[Inflate.err]] != 0 - **/ - - - /** - * new Inflate(options) - * - options (Object): zlib inflate options. - * - * Creates new inflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `windowBits` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw inflate - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * By default, when no options set, autodetect deflate/gzip data format via - * wrapper header. - * - * ##### Example: - * - * ```javascript - * const pako = require('pako') - * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9]) - * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * const inflate = new pako.Inflate({ level: 3}); - * - * inflate.push(chunk1, false); - * inflate.push(chunk2, true); // true -> last chunk - * - * if (inflate.err) { throw new Error(inflate.err); } - * - * console.log(inflate.result); - * ``` - **/ - function Inflate$1(options) { - this.options = common.assign({ - chunkSize: 1024 * 64, - windowBits: 15, - to: '' - }, options || {}); - - const opt = this.options; - - // Force window size for `raw` data, if not set directly, - // because we have no header for autodetect. - if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { - opt.windowBits = -opt.windowBits; - if (opt.windowBits === 0) { opt.windowBits = -15; } - } - - // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate - if ((opt.windowBits >= 0) && (opt.windowBits < 16) && - !(options && options.windowBits)) { - opt.windowBits += 32; - } - - // Gzip header has no info about windows size, we can do autodetect only - // for deflate. So, if window size not set, force it to max when gzip possible - if ((opt.windowBits > 15) && (opt.windowBits < 48)) { - // bit 3 (16) -> gzipped data - // bit 4 (32) -> autodetect gzip/deflate - if ((opt.windowBits & 15) === 0) { - opt.windowBits |= 15; - } - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new zstream(); - this.strm.avail_out = 0; + function setupPage(component) { + const oldSetup = component.setup; + component.inheritAttrs = false; // 禁止继承 __pageId 等属性,避免告警 + component.setup = (_, ctx) => { + const { attrs: { __pageId, __pagePath, __pageQuery, __pageInstance }, } = ctx; + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog(__pagePath, 'setup')); + } + const instance = vue.getCurrentInstance(); + const pageVm = instance.proxy; + initPageVm(pageVm, __pageInstance); + addCurrentPage(initScope(__pageId, pageVm, __pageInstance)); + vue.onMounted(() => { + vue.nextTick(() => { + // onShow被延迟,故onReady也同时延迟 + invokeHook(pageVm, ON_READY); + }); + // TODO preloadSubPackages + }); + vue.onBeforeUnmount(() => { + invokeHook(pageVm, ON_UNLOAD); + }); + if (oldSetup) { + return oldSetup(__pageQuery, ctx); + } + }; + return component; + } + function initScope(pageId, vm, pageInstance) { + const $getAppWebview = () => { + return plus.webview.getWebviewById(pageId + ''); + }; + vm.$getAppWebview = $getAppWebview; + vm.$.ctx.$scope = { + $getAppWebview, + }; + vm.getOpenerEventChannel = () => { + if (!pageInstance.eventChannel) { + pageInstance.eventChannel = new EventChannel(pageId); + } + return pageInstance.eventChannel; + }; + return vm; + } - let status = inflate_1$2.inflateInit2( - this.strm, - opt.windowBits - ); + function isVuePageAsyncComponent(component) { + return isFunction(component); + } + const pagesMap = new Map(); + function definePage(pagePath, asyncComponent) { + pagesMap.set(pagePath, once(createFactory(asyncComponent))); + } + function createPage(__pageId, __pagePath, __pageQuery, __pageInstance, pageOptions) { + const pageNode = createPageNode(__pageId, pageOptions, true); + const app = getVueApp(); + const component = pagesMap.get(__pagePath)(); + const mountPage = (component) => app.mountPage(component, { + __pageId, + __pagePath, + __pageQuery, + __pageInstance, + }, pageNode); + if (isPromise(component)) { + return component.then((component) => mountPage(component)); + } + return mountPage(component); + } + function createFactory(component) { + return () => { + if (isVuePageAsyncComponent(component)) { + return component().then((component) => setupPage(component)); + } + return setupPage(component); + }; + } - if (status !== Z_OK) { - throw new Error(messages[status]); - } + const preloadWebviews = {}; + function removePreloadWebview(webview) { + const url = Object.keys(preloadWebviews).find((url) => preloadWebviews[url].id === webview.id); + if (url) { + if (process.env.NODE_ENV !== 'production') { + console.log(`[uni-app] removePreloadWebview(${webview.id})`); + } + delete preloadWebviews[url]; + } + } + function closePreloadWebview({ url }) { + const webview = preloadWebviews[url]; + if (webview) { + if (webview.__page__) { + if (!getCurrentPages().find((page) => page === webview.__page__)) { + // 未使用 + webview.close('none'); + } + else { + // 被使用 + webview.__preload__ = false; + } + } + else { + // 未使用 + webview.close('none'); + } + delete preloadWebviews[url]; + } + return webview; + } + function preloadWebview({ url, path, query, }) { + if (!preloadWebviews[url]) { + const routeOptions = JSON.parse(JSON.stringify(__uniRoutes.find((route) => route.path === path))); + preloadWebviews[url] = createWebview({ + path, + routeOptions, + query, + webviewStyle: { + __preload__: true, + __query__: JSON.stringify(query), + }, + }); + } + return preloadWebviews[url]; + } - this.header = new gzheader(); + function closeWebview(webview, animationType, animationDuration) { + webview[webview.__preload__ ? 'hide' : 'close'](animationType, animationDuration); + } + function showWebview(webview, animationType, animationDuration, showCallback, delay) { + if (typeof delay === 'undefined') { + delay = webview.nvue ? 0 : 100; + } + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('showWebview', 'delay', delay)); + } + const execShowCallback = function () { + if (execShowCallback._called) { + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('execShowCallback', 'prevent')); + } + return; + } + execShowCallback._called = true; + showCallback && showCallback(); + navigateFinish(); + }; + execShowCallback._called = false; + setTimeout(() => { + const timer = setTimeout(() => { + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('showWebview', 'callback', 'timer')); + } + execShowCallback(); + }, animationDuration + 150); + webview.show(animationType, animationDuration, () => { + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('showWebview', 'callback')); + } + if (!execShowCallback._called) { + clearTimeout(timer); + } + execShowCallback(); + }); + }, delay); + } + function backWebview(webview, callback) { + const children = webview.children(); + if (!children || !children.length) { + // 有子 webview + return callback(); + } + // 如果页面有subNvues,切使用了webview组件,则返回时子webview会取错,因此需要做id匹配 + const childWebview = children.find((webview) => webview.id.indexOf(WEBVIEW_ID_PREFIX) === 0) || + children[0]; + childWebview.canBack(({ canBack }) => { + if (canBack) { + childWebview.back(); // webview 返回 + } + else { + callback(); + } + }); + } - inflate_1$2.inflateGetHeader(this.strm, this.header); + let pendingNavigator = false; + function setPendingNavigator(path, callback, msg) { + pendingNavigator = { + path, + nvue: getRouteMeta(path).isNVue, + callback, + }; + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('setPendingNavigator', path, msg)); + } + } + function closePage(page, animationType, animationDuration) { + removePage(page); + closeWebview(page.$getAppWebview(), animationType, animationDuration); + } + function navigate(path, callback, isAppLaunch = false) { + if (!isAppLaunch && pendingNavigator) { + return console.error(`Waiting to navigate to: ${pendingNavigator.path}, do not operate continuously: ${path}.`); + } + if (__uniConfig.renderer === 'native') { + // 纯原生无需wait逻辑 + // 如果是首页还未初始化,需要等一等,其他无需等待 + if (getCurrentPages().length === 0) { + return setPendingNavigator(path, callback, 'waitForReady'); + } + return callback(); + } + // 未创建 preloadWebview 或 preloadWebview 已被使用 + const waitPreloadWebview = !preloadWebview$1 || (preloadWebview$1 && preloadWebview$1.__uniapp_route); + // 已创建未 loaded + const waitPreloadWebviewReady = preloadWebview$1 && !preloadWebview$1.loaded; + if (waitPreloadWebview || waitPreloadWebviewReady) { + setPendingNavigator(path, callback, waitPreloadWebview ? 'waitForCreate' : 'waitForReady'); + } + else { + callback(); + } + if (waitPreloadWebviewReady) { + onWebviewReady(preloadWebview$1.id, pendingNavigate); + } + } + function pendingNavigate() { + if (!pendingNavigator) { + return; + } + const { callback } = pendingNavigator; + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('pendingNavigate', pendingNavigator.path)); + } + pendingNavigator = false; + return callback(); + } + function navigateFinish() { + if (__uniConfig.renderer === 'native') { + if (!pendingNavigator) { + return; + } + if (pendingNavigator.nvue) { + return pendingNavigate(); + } + return; + } + // 创建预加载 + const preloadWebview = createPreloadWebview(); + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('navigateFinish', 'preloadWebview', preloadWebview.id)); + } + if (!pendingNavigator) { + return; + } + if (pendingNavigator.nvue) { + return pendingNavigate(); + } + preloadWebview.loaded + ? pendingNavigator.callback() + : onWebviewReady(preloadWebview.id, pendingNavigate); + } - // Setup dictionary - if (opt.dictionary) { - // Convert data if needed - if (typeof opt.dictionary === 'string') { - opt.dictionary = strings.string2buf(opt.dictionary); - } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { - opt.dictionary = new Uint8Array(opt.dictionary); - } - if (opt.raw) { //In raw mode we need to set the dictionary early - status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary); - if (status !== Z_OK) { - throw new Error(messages[status]); - } - } - } + function registerPage({ url, path, query, openType, webview, eventChannel, }) { + // fast 模式,nvue 首页时,会在nvue中主动调用registerPage并传入首页webview,此时初始化一下首页(因为此时可能还未调用registerApp) + if (webview) { + initEntry(); + } + if (preloadWebviews[url]) { + webview = preloadWebviews[url]; + const _webview = webview; + if (_webview.__page__) { + // 该预载页面已处于显示状态,不再使用该预加载页面,直接新开 + if (getCurrentPages().find((page) => page === _webview.__page__)) { + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('uni-app', `preloadWebview(${path},${_webview.id}) already in use`)); + } + webview = undefined; + } + else { + if (eventChannel) { + _webview.__page__.$page.eventChannel = eventChannel; + } + addCurrentPage(_webview.__page__); + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('uni-app', `reuse preloadWebview(${path},${_webview.id})`)); + } + return _webview; + } + } + } + const routeOptions = initRouteOptions(path, openType); + if (!webview) { + webview = createWebview({ path, routeOptions, query }); + } + else { + webview = plus.webview.getWebviewById(webview.id); + webview.nvue = routeOptions.meta.isNVue; + } + routeOptions.meta.id = parseInt(webview.id); + const isTabBar = !!routeOptions.meta.isTabBar; + if (isTabBar) { + tabBar$1.append(webview); + } + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('registerPage', path, webview.id)); + } + initWebview(webview, path, query, routeOptions.meta); + const route = path.substr(1); + webview.__uniapp_route = route; + const pageInstance = initPageInternalInstance(openType, url, query, routeOptions.meta, eventChannel); + initNVueEntryPage(webview); + if (webview.nvue) { + // nvue 时,先启用一个占位 vm + const fakeNVueVm = createNVueVm(parseInt(webview.id), webview, pageInstance); + initPageVm(fakeNVueVm, pageInstance); + addCurrentPage(fakeNVueVm); + } + else { + createPage(parseInt(webview.id), route, query, pageInstance, initPageOptions(routeOptions)); + } + return webview; + } + function initPageOptions({ meta }) { + const statusbarHeight = getStatusbarHeight(); + const { platform, pixelRatio, windowWidth } = getBaseSystemInfo(); + return { + css: true, + route: meta.route, + version: 1, + locale: '', + platform, + pixelRatio, + windowWidth, + disableScroll: meta.disableScroll === true, + onPageScroll: false, + onPageReachBottom: false, + onReachBottomDistance: hasOwn$1(meta, 'onReachBottomDistance') + ? meta.onReachBottomDistance + : ON_REACH_BOTTOM_DISTANCE, + statusbarHeight, + windowTop: meta.navigationBar.type === 'float' ? statusbarHeight + NAVBAR_HEIGHT : 0, + windowBottom: tabBar$1.indexOf(meta.route) >= 0 && tabBar$1.cover ? tabBar$1.height : 0, + }; + } + function initNVueEntryPage(webview) { + const isLaunchNVuePage = webview.id === '1' && webview.nvue; + // 首页是 nvue 时,在 registerPage 时,执行路由堆栈 + if (isLaunchNVuePage) { + if (__uniConfig.splashscreen && + __uniConfig.splashscreen.autoclose && + !__uniConfig.splashscreen.alwaysShowBeforeRender) { + plus.navigator.closeSplashscreen(); + } + __uniConfig.onReady(function () { + navigateFinish(); + }); + } + } + function createNVueVm(pageId, webview, pageInstance) { + return { + $: {}, + onNVuePageCreated(vm, curNVuePage) { + vm.$ = {}; // 补充一个 nvue 的 $ 对象,模拟 vue3 的,不然有部分地方访问了 $ + vm.$getAppWebview = () => webview; + vm.getOpenerEventChannel = curNVuePage.getOpenerEventChannel; + // 替换真实的 nvue 的 vm + initPageVm(vm, pageInstance); + const pages = getAllPages(); + const index = pages.findIndex((p) => p === curNVuePage); + if (index > -1) { + pages.splice(index, 1, vm); + } + if (webview.__preload__) { + webview.__page__ = vm; + } + }, + $getAppWebview() { + return webview; + }, + getOpenerEventChannel() { + if (!pageInstance.eventChannel) { + pageInstance.eventChannel = new EventChannel(pageId); + } + return pageInstance.eventChannel; + }, + }; } - /** - * Inflate#push(data[, flush_mode]) -> Boolean - * - data (Uint8Array|ArrayBuffer): input data - * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE - * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH, - * `true` means Z_FINISH. - * - * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with - * new output chunks. Returns `true` on success. If end of stream detected, - * [[Inflate#onEnd]] will be called. - * - * `flush_mode` is not needed for normal operation, because end of stream - * detected automatically. You may try to use it for advanced things, but - * this functionality was not tested. - * - * On fail call [[Inflate#onEnd]] with error code and return false. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ - Inflate$1.prototype.push = function (data, flush_mode) { - const strm = this.strm; - const chunkSize = this.options.chunkSize; - const dictionary = this.options.dictionary; - let status, _flush_mode, last_avail_out; - - if (this.ended) return false; - - if (flush_mode === ~~flush_mode) _flush_mode = flush_mode; - else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH; - - // Convert data if needed - if (toString.call(data) === '[object ArrayBuffer]') { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - for (;;) { - if (strm.avail_out === 0) { - strm.output = new Uint8Array(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - - status = inflate_1$2.inflate(strm, _flush_mode); - - if (status === Z_NEED_DICT && dictionary) { - status = inflate_1$2.inflateSetDictionary(strm, dictionary); - - if (status === Z_OK) { - status = inflate_1$2.inflate(strm, _flush_mode); - } else if (status === Z_DATA_ERROR) { - // Replace code with more verbose - status = Z_NEED_DICT; - } - } - - // Skip snyc markers if more data follows and not raw mode - while (strm.avail_in > 0 && - status === Z_STREAM_END && - strm.state.wrap > 0 && - data[strm.next_in] !== 0) - { - inflate_1$2.inflateReset(strm); - status = inflate_1$2.inflate(strm, _flush_mode); - } + const $reLaunch = ({ url }, { resolve, reject }) => { + const { path, query } = parseUrl(url); + navigate(path, () => { + _reLaunch({ + url, + path, + query, + }) + .then(resolve) + .catch(reject); + }); + }; + function _reLaunch({ url, path, query }) { + return new Promise((resolve) => { + // 获取目前所有页面 + const pages = getAllPages().slice(0); + const routeOptions = __uniRoutes.find((route) => route.path === path); + if (routeOptions.meta.isTabBar) { + tabBar$1.switchTab(path.slice(1)); + } + showWebview(registerPage({ + url, + path, + query, + openType: 'reLaunch', + }), 'none', 0, () => { + pages.forEach((page) => closePage(page, 'none')); + resolve(undefined); + }); + setStatusBarStyle(); + }); + } - switch (status) { - case Z_STREAM_ERROR: - case Z_DATA_ERROR: - case Z_NEED_DICT: - case Z_MEM_ERROR: - this.onEnd(status); - this.ended = true; - return false; - } + function initGlobalEvent() { + const plusGlobalEvent = plus.globalEvent; + const weexGlobalEvent = weex.requireModule('globalEvent'); + const emit = UniServiceJSBridge.emit; + if (weex.config.preload) { + plus.key.addEventListener(EVENT_BACKBUTTON, backbuttonListener); + } + else { + plusGlobalEvent.addEventListener('splashclosed', () => { + plus.key.addEventListener(EVENT_BACKBUTTON, backbuttonListener); + }); + } + plusGlobalEvent.addEventListener('pause', () => { + emit(ON_APP_ENTER_BACKGROUND); + }); + plusGlobalEvent.addEventListener('resume', () => { + const info = parseRedirectInfo(); + if (info && info.userAction) { + initEnterOptions(info); + initEnterReLaunch(info); + } + emit(ON_APP_ENTER_FOREGROUND, getEnterOptions()); + }); + weexGlobalEvent.addEventListener('uistylechange', function (event) { + const args = { + theme: event.uistyle, + }; + emit(ON_THEME_CHANGE, args); + }); + let keyboardHeightChange = 0; + plusGlobalEvent.addEventListener('KeyboardHeightChange', function (event) { + // 安卓设备首次获取高度为 0 + if (keyboardHeightChange !== event.height) { + keyboardHeightChange = event.height; + emit(ON_KEYBOARD_HEIGHT_CHANGE, { + height: keyboardHeightChange, + }); + } + }); + plusGlobalEvent.addEventListener('plusMessage', subscribePlusMessage); + // nvue webview post message + plusGlobalEvent.addEventListener('WebviewPostMessage', subscribePlusMessage); + } + function subscribePlusMessage({ data, }) { + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('plusMessage', data)); + } + if (data && data.type) { + UniServiceJSBridge.subscribeHandler('plusMessage.' + data.type, data.args); + } + } + function onPlusMessage(type, callback, once = false) { + UniServiceJSBridge.subscribe('plusMessage.' + type, callback, once); + } + function initEnterReLaunch(info) { + __uniConfig.realEntryPagePath = + __uniConfig.realEntryPagePath || __uniConfig.entryPagePath; + __uniConfig.entryPagePath = info.path; + __uniConfig.entryPageQuery = info.query; + $reLaunch({ url: addLeadingSlash(info.path) + info.query }, { resolve() { }, reject() { } }); + } - // Remember real `avail_out` value, because we may patch out buffer content - // to align utf8 strings boundaries. - last_avail_out = strm.avail_out; + function initAppLaunch(appVm) { + const { entryPagePath, entryPageQuery, referrerInfo } = __uniConfig; + const args = extend({ + // 为了让 uni-stat 在 uni.onLaunch 中可以 mixin + app: { mixin: appVm.$.appContext.app.mixin }, + }, initLaunchOptions({ + path: entryPagePath, + query: entryPageQuery, + referrerInfo: referrerInfo, + })); + injectAppLaunchHooks(appVm.$); + invokeHook(appVm, ON_LAUNCH, args); + invokeHook(appVm, ON_SHOW, args); + // https://tower.im/teams/226535/todos/16905/ + const getAppState = weex.requireModule('plus').getAppState; + const appState = getAppState && Number(getAppState()); + if (appState === 2) { + invokeHook(appVm, ON_HIDE, args); + } + } - if (strm.next_out) { - if (strm.avail_out === 0 || status === Z_STREAM_END) { + // 统一处理路径 + function getPath(path) { + path = path.replace(/\/$/, ''); + return path.indexOf('_') === 0 + ? plus.io.convertLocalFileSystemURL(path) + : path; + } + function clearTempFile() { + const basePath = getPath(TEMP_PATH_BASE); + const tempPath = getPath(TEMP_PATH); + // 获取父目录 + const dirParts = tempPath.split('/'); + dirParts.pop(); + const dirPath = dirParts.join('/'); + plus.io.resolveLocalFileSystemURL(plus.io.convertAbsoluteFileSystem(dirPath), (entry) => { + const reader = entry.createReader(); + reader.readEntries(function (entry) { + // plus.d.ts 类型不对 + const entries = entry; + if (entries && entries.length) { + entries.forEach(function (entry) { + if (entry.isDirectory && + entry.fullPath.indexOf(basePath) === 0 && + entry.fullPath.indexOf(tempPath) !== 0) { + entry.removeRecursively(); + } + }); + } + }); + }); + } - if (this.options.to === 'string') { + function onNodeEvent(nodeId, evt, pageNode) { + pageNode.fireEvent(nodeId, evt); + } - let next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + function onVdSync(actions, pageId) { + // 从所有pages中获取 + const page = getPageById(parseInt(pageId)); + if (!page) { + if ((process.env.NODE_ENV !== 'production')) { + console.error(formatLog('onVdSync', 'page', pageId, 'not found')); + } + return; + } + const pageNode = page.__page_container__; + actions.forEach((action) => { + switch (action[0]) { + case ACTION_TYPE_EVENT: + onNodeEvent(action[1], action[2], pageNode); + break; + } + }); + } - let tail = strm.next_out - next_out_utf8; - let utf8str = strings.buf2string(strm.output, next_out_utf8); + const _adDataCache = {}; + function getAdData(data, onsuccess, onerror) { + const { adpid, width } = data; + const key = adpid + '-' + width; + const adDataList = _adDataCache[key]; + if (adDataList && adDataList.length > 0) { + onsuccess(adDataList.splice(0, 1)[0]); + return; + } + plus.ad.getAds(data, (res) => { + const list = res.ads; + onsuccess(list.splice(0, 1)[0]); + _adDataCache[key] = adDataList ? adDataList.concat(list) : list; + }, (err) => { + onerror({ + errCode: err.code, + errMsg: err.message, + }); + }); + } + function subscribeAd() { + registerServiceMethod('getAdData', (args, resolve) => { + getAdData(args, (res) => { + resolve({ + code: 0, + data: res, + }); + }, (err) => { + resolve({ + code: 1, + message: err, + }); + }); + }); + } - // move tail & realign counters - strm.next_out = tail; - strm.avail_out = chunkSize - tail; - if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0); + const API_ROUTE = [ + 'switchTab', + 'reLaunch', + 'redirectTo', + 'navigateTo', + 'navigateBack', + ]; + function subscribeNavigator() { + API_ROUTE.forEach((name) => { + registerServiceMethod(name, (args) => { + uni[name](extend(args, { + fail(res) { + console.error(res.errMsg); + }, + })); + }); + }); + } - this.onData(utf8str); + const $navigateTo = (args, { resolve, reject }) => { + const { url, events, animationType, animationDuration } = args; + const { path, query } = parseUrl(url); + const [aniType, aniDuration] = initAnimation(path, animationType, animationDuration); + navigate(path, () => { + _navigateTo({ + url, + path, + query, + events, + aniType, + aniDuration, + }) + .then(resolve) + .catch(reject); + }, args.openType === 'appLaunch'); + }; + const navigateTo = defineAsyncApi(API_NAVIGATE_TO, $navigateTo, NavigateToProtocol, NavigateToOptions); + function _navigateTo({ url, path, query, events, aniType, aniDuration, }) { + // 当前页面触发 onHide + invokeHook(ON_HIDE); + const eventChannel = new EventChannel(getWebviewId() + 1, events); + return new Promise((resolve) => { + showWebview(registerPage({ url, path, query, openType: 'navigateTo', eventChannel }), aniType, aniDuration, () => { + resolve({ eventChannel }); + }); + setStatusBarStyle(); + }); + } + function initAnimation(path, animationType, animationDuration) { + const { globalStyle } = __uniConfig; + const meta = getRouteMeta(path); + return [ + animationType || + meta.animationType || + globalStyle.animationType || + ANI_SHOW, + animationDuration || + meta.animationDuration || + globalStyle.animationDuration || + ANI_DURATION, + ]; + } - } else { - this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out)); - } - } - } + const $switchTab = (args, { resolve, reject }) => { + const { url } = args; + const { path, query } = parseUrl(url); + navigate(path, () => { + _switchTab({ + url, + path, + query, + }) + .then(resolve) + .catch(reject); + }, args.openType === 'appLaunch'); + }; + const switchTab = defineAsyncApi(API_SWITCH_TAB, $switchTab, SwitchTabProtocol, SwitchTabOptions); + function _switchTab({ url, path, query, }) { + tabBar$1.switchTab(path.slice(1)); + const pages = getCurrentPages(); + const len = pages.length; + let callOnHide = false; + let callOnShow = false; + let currentPage; + if (len >= 1) { + // 前一个页面是非 tabBar 页面 + currentPage = pages[len - 1]; + if (currentPage && !currentPage.$.__isTabBar) { + // 前一个页面为非 tabBar 页面时,目标tabBar需要强制触发onShow + // 该情况下目标页tabBarPage的visible是不对的 + // 除非每次路由跳转都处理一遍tabBarPage的visible,目前仅switchTab会处理 + // 简单起见,暂时直接判断该情况,执行onShow + callOnShow = true; + pages.reverse().forEach((page) => { + if (!page.$.__isTabBar && page !== currentPage) { + closePage(page, 'none'); + } + }); + removePage(currentPage); + // 延迟执行避免iOS应用退出 + setTimeout(() => { + if (currentPage.$page.openType === 'redirectTo') { + closeWebview(currentPage.$getAppWebview(), ANI_CLOSE, ANI_DURATION); + } + else { + closeWebview(currentPage.$getAppWebview(), 'auto'); + } + }, 100); + } + else { + callOnHide = true; + } + } + let tabBarPage; + // 查找当前 tabBarPage,且设置 visible + getAllPages().forEach((page) => { + if (addLeadingSlash(page.route) === path) { + if (!page.$.__isActive) { + // 之前未显示 + callOnShow = true; + } + page.$.__isActive = true; + tabBarPage = page; + } + else { + if (page.$.__isTabBar) { + page.$.__isActive = false; + } + } + }); + // 相同tabBar页面 + if (currentPage === tabBarPage) { + callOnHide = false; + } + if (currentPage && callOnHide) { + invokeHook(currentPage, ON_HIDE); + } + return new Promise((resolve) => { + if (tabBarPage) { + const webview = tabBarPage.$getAppWebview(); + webview.show('none'); + // 等visible状态都切换完之后,再触发onShow,否则开发者在onShow里边 getCurrentPages 会不准确 + if (callOnShow && !webview.__preload__) { + invokeHook(tabBarPage, ON_SHOW); + } + setStatusBarStyle(); + resolve(undefined); + } + else { + showWebview(registerPage({ + url, + path, + query, + openType: 'switchTab', + }), 'none', 0, () => { + setStatusBarStyle(); + resolve(undefined); + }, 70); + } + }); + } - // Must repeat iteration if out buffer is full - if (status === Z_OK && last_avail_out === 0) continue; + let isLaunchWebviewReady = false; // 目前首页双向确定 ready,可能会导致触发两次 onWebviewReady(主要是 Android) + function subscribeWebviewReady(_data, pageId) { + const isLaunchWebview = pageId === '1'; + if (isLaunchWebview && isLaunchWebviewReady) { + if ((process.env.NODE_ENV !== 'production')) { + console.log('[uni-app] onLaunchWebviewReady.prevent'); + } + return; + } + if (isLaunchWebview) { + // 首页 + isLaunchWebviewReady = true; + setPreloadWebview(plus.webview.getLaunchWebview()); + } + else if (!preloadWebview$1) { + // preloadWebview 不存在,重新加载一下 + setPreloadWebview(plus.webview.getWebviewById(pageId)); + } + if (preloadWebview$1.id !== pageId) { + return console.error(`webviewReady[${preloadWebview$1.id}][${pageId}] not match`); + } + preloadWebview$1.loaded = true; // 标记已 ready + UniServiceJSBridge.emit(ON_WEBVIEW_READY + '.' + pageId); + isLaunchWebview && onLaunchWebviewReady(); + } + function onLaunchWebviewReady() { + const { autoclose, alwaysShowBeforeRender } = __uniConfig.splashscreen; + if (autoclose && !alwaysShowBeforeRender) { + plus.navigator.closeSplashscreen(); + } + const entryPagePath = addLeadingSlash(__uniConfig.entryPagePath); + const routeOptions = getRouteOptions(entryPagePath); + if (!routeOptions.meta.isNVue) { + // 非 nvue 首页,需要主动跳转 + const args = { + url: entryPagePath + (__uniConfig.entryPageQuery || ''), + openType: 'appLaunch', + }; + const handler = { resolve() { }, reject() { } }; + if (routeOptions.meta.isTabBar) { + return $switchTab(args, handler); + } + return $navigateTo(args, handler); + } + } - // Finalize if end of stream reached. - if (status === Z_STREAM_END) { - status = inflate_1$2.inflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return true; - } + function onWebviewInserted(_, pageId) { + const page = getPageById(parseInt(pageId)); + page && (page.__uniapp_webview = true); + } + function onWebviewRemoved(_, pageId) { + const page = getPageById(parseInt(pageId)); + page && delete page.__uniapp_webview; + } - if (strm.avail_in === 0) break; - } + const onWebInvokeAppService = ({ name, arg }, pageIds) => { + if (name === 'postMessage') { + onMessage(pageIds[0], arg); + } + else { + uni[name](extend(arg, { + fail(res) { + console.error(res.errMsg); + }, + })); + } + }; + function onMessage(pageId, arg) { + const uniNode = findNodeByTagName('web-view', parseInt(pageId)); + uniNode && + uniNode.dispatchEvent(createUniEvent({ + type: 'onMessage', + target: Object.create(null), + currentTarget: Object.create(null), + detail: { + data: [arg], + }, + })); + } - return true; - }; + function onWxsInvokeCallMethod({ nodeId, ownerId, method, args, }, pageId) { + const node = findNodeById(nodeId, parseInt(pageId)); + if (!node) { + if ((process.env.NODE_ENV !== 'production')) { + console.error(formatLog('Wxs', 'CallMethod', nodeId, 'not found')); + } + return; + } + const vm = resolveOwnerVm(ownerId, node.__vueParentComponent); + if (!vm) { + if ((process.env.NODE_ENV !== 'production')) { + console.error(formatLog('Wxs', 'CallMethod', 'vm not found')); + } + return; + } + if (!vm[method]) { + if ((process.env.NODE_ENV !== 'production')) { + console.error(formatLog('Wxs', 'CallMethod', method, ' not found')); + } + return; + } + vm[method](args); + } + function resolveOwnerVm(ownerId, vm) { + if (!vm) { + return null; + } + if (vm.uid === ownerId) { + return vm.proxy; + } + let parent = vm.parent; + while (parent) { + if (parent.uid === ownerId) { + return parent.proxy; + } + parent = parent.parent; + } + return vm.proxy; + } + function initSubscribeHandlers() { + const { subscribe, subscribeHandler, publishHandler } = UniServiceJSBridge; + onPlusMessage('subscribeHandler', ({ type, data, pageId }) => { + subscribeHandler(type, data, pageId); + }); + onPlusMessage(WEB_INVOKE_APPSERVICE, ({ data, webviewIds }) => { + onWebInvokeAppService(data, webviewIds); + }); + if (__uniConfig.renderer !== 'native') { + // 非纯原生 + subscribe(ON_WEBVIEW_READY, subscribeWebviewReady); + subscribe(VD_SYNC, onVdSync); + subscribeServiceMethod(); + subscribeAd(); + subscribeNavigator(); + subscribe(WEBVIEW_INSERTED, onWebviewInserted); + subscribe(WEBVIEW_REMOVED, onWebviewRemoved); + subscribe(ON_WXS_INVOKE_CALL_METHOD, onWxsInvokeCallMethod); + const routeOptions = getRouteOptions(addLeadingSlash(__uniConfig.entryPagePath)); + if (routeOptions && !routeOptions.meta.isNVue) { + // 防止首页 webview 初始化过早, service 还未开始监听 + publishHandler(ON_WEBVIEW_READY, {}, 1); + } + } + } - /** - * Inflate#onData(chunk) -> Void - * - chunk (Uint8Array|String): output data. When string output requested, - * each chunk will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ - Inflate$1.prototype.onData = function (chunk) { - this.chunks.push(chunk); - }; + let appCtx; + const defaultApp = { + globalData: {}, + }; + function getApp$1({ allowDefault = false } = {}) { + if (appCtx) { + // 真实的 App 已初始化 + return appCtx; + } + if (allowDefault) { + // 返回默认实现 + return defaultApp; + } + console.error('[warn]: getApp() failed. Learn more: https://uniapp.dcloud.io/collocation/frame/window?id=getapp.'); + } + function registerApp(appVm) { + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('registerApp')); + } + initVueApp(appVm); + appCtx = appVm; + initAppVm(appCtx); + extend(appCtx, defaultApp); // 拷贝默认实现 + const { $options } = appVm; + if ($options) { + appCtx.globalData = extend($options.globalData || {}, appCtx.globalData); + } + initService(); + initEntry(); + initTabBar(); + initGlobalEvent(); + initSubscribeHandlers(); + initAppLaunch(appVm); + // 10s后清理临时文件 + setTimeout(clearTempFile, 10000); + __uniConfig.ready = true; + } + var index$1 = { + install(app) { + initMount(app); + initApp(app); + initServicePlugin(app); + }, + }; + function initMount(app) { + const oldMount = app.mount; + app.mount = (rootContainer) => { + const instance = oldMount.call(app, rootContainer); + if (rootContainer === '#app') { + registerApp(instance); + } + return instance; + }; + } - /** - * Inflate#onEnd(status) -> Void - * - status (Number): inflate status. 0 (Z_OK) on success, - * other if not. - * - * Called either after you tell inflate that the input stream is - * complete (Z_FINISH). By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ - Inflate$1.prototype.onEnd = function (status) { - // On success - join - if (status === Z_OK) { - if (this.options.to === 'string') { - this.result = this.chunks.join(''); - } else { - this.result = common.flattenChunks(this.chunks); - } - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; - }; + function restoreGlobal(newVue, newWeex, newPlus, newSetTimeout, newClearTimeout, newSetInterval, newClearInterval) { + // 确保部分全局变量 是 app-service 中的 + // 若首页 nvue 初始化比 app-service 快,导致框架处于该 nvue 环境下 + // plus 如果不用 app-service,资源路径会出问题 + // 若首页 nvue 被销毁,如 redirectTo 或 reLaunch,则这些全局功能会损坏 + // 设置 vue3 + // @ts-ignore 最终vue会被替换为vue + vue = newVue; + if (plus !== newPlus) { + if ((process.env.NODE_ENV !== 'production')) { + console.log(`[restoreGlobal][${Date.now()}]`); + } + weex = newWeex; + // @ts-ignore + plus = newPlus; + restoreOldSetStatusBarStyle(plus.navigator.setStatusBarStyle); + plus.navigator.setStatusBarStyle = newSetStatusBarStyle; + /* eslint-disable no-global-assign */ + // @ts-ignore + setTimeout = newSetTimeout; + // @ts-ignore + clearTimeout = newClearTimeout; + // @ts-ignore + setInterval = newSetInterval; + // @ts-ignore + clearInterval = newClearInterval; + } + __uniConfig.serviceReady = true; + } + const sendHostEvent = sendNativeEvent; + const API_NAVIGATE_TO_MINI_PROGRAM = 'navigateToMiniProgram'; + const navigateToMiniProgram = defineAsyncApi(API_NAVIGATE_TO_MINI_PROGRAM, (data, { resolve, reject }) => { + sendHostEvent(API_NAVIGATE_TO_MINI_PROGRAM, data, (res) => { + if (res.errMsg && res.errMsg.indexOf(':ok') === -1) { + return reject(res.errMsg.split(' ')[1]); + } + resolve(); + }); + }); - /** - * inflate(data[, options]) -> Uint8Array|String - * - data (Uint8Array): input data to decompress. - * - options (Object): zlib inflate options. - * - * Decompress `data` with inflate/ungzip and `options`. Autodetect - * format via wrapper header by default. That's why we don't provide - * separate `ungzip` method. - * - * Supported options are: - * - * - windowBits - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information. - * - * Sugar (options): - * - * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify - * negative windowBits implicitly. - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * - * ##### Example: - * - * ```javascript - * const pako = require('pako'); - * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9])); - * let output; - * - * try { - * output = pako.inflate(input); - * } catch (err) { - * console.log(err); - * } - * ``` - **/ - function inflate$1(input, options) { - const inflator = new Inflate$1(options); + const EventType = { + load: 'load', + close: 'close', + error: 'error', + adClicked: 'adClicked', + }; + class AdEventHandler { + constructor() { + this._callbacks = {}; + } + onLoad(callback) { + this._addEventListener(EventType.load, callback); + } + onClose(callback) { + this._addEventListener(EventType.close, callback); + } + onError(callback) { + this._addEventListener(EventType.error, callback); + } + offLoad(callback) { + this._removeEventListener(EventType.load, callback); + } + offClose(callback) { + this._removeEventListener(EventType.close, callback); + } + offError(callback) { + this._removeEventListener(EventType.error, callback); + } + _addEventListener(type, callback) { + if (typeof callback !== 'function') { + return; + } + if (!this._callbacks[type]) { + this._callbacks[type] = []; + } + this._callbacks[type].push(callback); + } + _removeEventListener(type, callback) { + const arrayFunction = this._callbacks[type]; + const index = arrayFunction.indexOf(callback); + if (index > -1) { + arrayFunction.splice(index, 1); + } + } + _dispatchEvent(name, data) { + this._callbacks[name].forEach((callback) => { + callback(data || {}); + }); + } + } + class AdBase extends AdEventHandler { + constructor(adInstance, options) { + super(); + this.preload = true; + this._isLoaded = false; + this._isLoading = false; + this._loadPromiseResolve = null; + this._loadPromiseReject = null; + this._showPromiseResolve = null; + this._showPromiseReject = null; + this.preload = options.preload !== undefined ? options.preload : false; + const ad = (this._adInstance = adInstance); + ad.onLoad(() => { + this._isLoaded = true; + this._isLoading = false; + if (this._loadPromiseResolve != null) { + this._loadPromiseResolve(); + this._loadPromiseResolve = null; + } + if (this._showPromiseResolve != null) { + this._showPromiseResolve(); + this._showPromiseResolve = null; + this._showAd(); + } + this._dispatchEvent(EventType.load, {}); + }); + ad.onClose((e) => { + this._isLoaded = false; + this._isLoading = false; + this._dispatchEvent(EventType.close, e); + if (this.preload === true) { + this._loadAd(); + } + }); + ad.onError((e) => { + this._isLoading = false; + const data = { + code: e.code, + errMsg: e.message, + }; + this._dispatchEvent(EventType.error, data); + const error = new Error(JSON.stringify(data)); + if (this._loadPromiseReject != null) { + this._loadPromiseReject(error); + this._loadPromiseReject = null; + } + if (this._showPromiseReject != null) { + this._showPromiseReject(error); + this._showPromiseReject = null; + } + }); + ad.onAdClicked && + ad.onAdClicked(() => { + this._dispatchEvent(EventType.adClicked, {}); + }); + } + getProvider() { + return this._adInstance.getProvider(); + } + load() { + return new Promise((resolve, reject) => { + this._loadPromiseResolve = resolve; + this._loadPromiseReject = reject; + if (this._isLoading) { + return; + } + if (this._isLoaded) { + resolve(''); + } + else { + this._loadAd(); + } + }); + } + show() { + return new Promise((resolve, reject) => { + this._showPromiseResolve = resolve; + this._showPromiseReject = reject; + if (this._isLoading) { + return; + } + if (this._isLoaded) { + this._showAd(); + resolve(''); + } + else { + this._loadAd(); + } + }); + } + destroy() { + this._adInstance.destroy(); + } + _loadAd() { + this._isLoaded = false; + this._isLoading = true; + this._adInstance.load(); + } + _showAd() { + this._adInstance.show(); + } + } - inflator.push(input); + class RewardedVideoAd extends AdBase { + constructor(options) { + super(plus.ad.createRewardedVideoAd(options), options); + this._loadAd(); + } + } + const createRewardedVideoAd = (defineSyncApi(API_CREATE_REWARDED_VIDEO_AD, (options) => { + return new RewardedVideoAd(options); + }, CreateRewardedVideoAdProtocol, CreateRewardedVideoAdOptions)); - // That will never happens, if you don't cheat with options :) - if (inflator.err) throw inflator.msg || messages[inflator.err]; + class FullScreenVideoAd extends AdBase { + constructor(options) { + super(plus.ad.createFullScreenVideoAd(options), options); + this.preload = false; + } + } + const createFullScreenVideoAd = (defineSyncApi(API_CREATE_FULL_SCREEN_VIDEO_AD, (options) => { + return new FullScreenVideoAd(options); + }, CreateFullScreenVideoAdProtocol, CreateFullScreenVideoAdOptions)); - return inflator.result; - } + class InterstitialAd extends AdBase { + constructor(options) { + super(plus.ad.createInterstitialAd(options), options); + this.preload = false; + this._loadAd(); + } + } + const createInterstitialAd = (defineSyncApi(API_CREATE_INTERSTITIAL_AD, (options) => { + return new InterstitialAd(options); + }, CreateInterstitialAdProtocol, CreateInterstitialAdOptions)); + const sdkCache = {}; + const sdkQueue = {}; + function initSDK(options) { + const provider = options.provider; + if (!sdkCache[provider]) { + sdkCache[provider] = {}; + } + if (typeof sdkCache[provider].plugin === 'object') { + options.success(sdkCache[provider].plugin); + return; + } + if (!sdkQueue[provider]) { + sdkQueue[provider] = []; + } + sdkQueue[provider].push(options); + if (sdkCache[provider].status === true) { + options.__plugin = sdkCache[provider].plugin; + return; + } + sdkCache[provider].status = true; + const plugin = requireNativePlugin(provider); + if (!plugin || !plugin.initSDK) { + sdkQueue[provider].forEach((item) => { + item.fail({ + code: -1, + message: 'provider [' + provider + '] invalid', + }); + }); + sdkQueue[provider].length = 0; + sdkCache[provider].status = false; + return; + } + // TODO + sdkCache[provider].plugin = plugin; + options.__plugin = plugin; + plugin.initSDK((res) => { + const isSuccess = res.code === 1 || res.code === '1'; + if (isSuccess) { + sdkCache[provider].plugin = plugin; + } + else { + sdkCache[provider].status = false; + } + sdkQueue[provider].forEach((item) => { + if (isSuccess) { + item.success(item.__plugin); + } + else { + item.fail(res); + } + }); + sdkQueue[provider].length = 0; + }); + } + class InteractiveAd extends AdEventHandler { + constructor(options) { + super(); + this._adpid = ''; + this._provider = ''; + this._userData = null; + this._isLoaded = false; + this._isLoading = false; + this._loadPromiseResolve = null; + this._loadPromiseReject = null; + this._showPromiseResolve = null; + this._showPromiseReject = null; + this._adInstance = null; + this._adError = ''; + this._adpid = options.adpid; + this._provider = options.provider; + this._userData = options.userData; + setTimeout(() => { + this._init(); + }); + } + _init() { + this._adError = ''; + initSDK({ + provider: this._provider, + success: (res) => { + this._adInstance = res; + if (this._userData) { + this.bindUserData(this._userData); + } + this._loadAd(); + }, + fail: (err) => { + this._adError = err; + if (this._loadPromiseReject != null) { + this._loadPromiseReject(this._createError(err)); + this._loadPromiseReject = null; + } + this._dispatchEvent(EventType.error, err); + }, + }); + } + getProvider() { + return this._provider; + } + load() { + return new Promise((resolve, reject) => { + this._loadPromiseResolve = resolve; + this._loadPromiseReject = reject; + if (this._isLoading) { + return; + } + if (this._adError) { + this._init(); + return; + } + if (this._isLoaded) { + resolve(''); + } + else { + this._loadAd(); + } + }); + } + show() { + return new Promise((resolve, reject) => { + this._showPromiseResolve = resolve; + this._showPromiseReject = reject; + if (this._isLoading) { + return; + } + if (this._adError) { + this._init(); + return; + } + if (this._isLoaded) { + this._showAd(); + resolve(''); + } + else { + this._loadAd(); + } + }); + } + reportExposure() { + if (this._adInstance !== null) { + this._adInstance.reportExposure(); + } + } + bindUserData(data) { + if (this._adInstance !== null) { + this._adInstance.bindUserData(data); + } + } + destroy() { + if (this._adInstance !== null && this._adInstance.destroy) { + this._adInstance.destroy({ + adpid: this._adpid, + }); + } + } + _loadAd() { + if (this._adInstance !== null) { + if (this._isLoading === true) { + return; + } + this._isLoading = true; + this._adInstance.loadData({ + adpid: this._adpid, + }, (res) => { + this._isLoaded = true; + this._isLoading = false; + if (this._loadPromiseResolve != null) { + this._loadPromiseResolve(); + this._loadPromiseResolve = null; + } + if (this._showPromiseResolve != null) { + this._showPromiseResolve(); + this._showPromiseResolve = null; + this._showAd(); + } + this._dispatchEvent(EventType.load, res); + }, (err) => { + this._isLoading = false; + if (this._showPromiseReject != null) { + this._showPromiseReject(this._createError(err)); + this._showPromiseReject = null; + } + this._dispatchEvent(EventType.error, err); + }); + } + } + _showAd() { + if (this._adInstance !== null && this._isLoaded === true) { + this._adInstance.show({ + adpid: this._adpid, + }, () => { + this._isLoaded = false; + }, (err) => { + this._isLoaded = false; + if (this._showPromiseReject != null) { + this._showPromiseReject(this._createError(err)); + this._showPromiseReject = null; + } + this._dispatchEvent(EventType.error, err); + }); + } + } + _createError(err) { + return new Error(JSON.stringify(err)); + } + } + const createInteractiveAd = (defineSyncApi(API_CREATE_INTERACTIVE_AD, (options) => { + return new InteractiveAd(options); + }, CreateInteractiveAdProtocol, CreateInteractiveAdOptions)); - /** - * inflateRaw(data[, options]) -> Uint8Array|String - * - data (Uint8Array): input data to decompress. - * - options (Object): zlib inflate options. - * - * The same as [[inflate]], but creates raw data, without wrapper - * (header and adler32 crc). - **/ - function inflateRaw$1(input, options) { - options = options || {}; - options.raw = true; - return inflate$1(input, options); + const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, (args, { resolve, reject }) => { + const page = getCurrentPage(); + if (!page) { + return reject(`getCurrentPages is empty`); + } + if (invokeHook(page, ON_BACK_PRESS, { + from: args.from, + })) { + return resolve(); + } + uni.hideToast(); + uni.hideLoading(); + if (page.$page.meta.isQuit) { + quit(); + } + else if ( + // 处于直达页面 + page.$page.route === __uniConfig.entryPagePath && + __uniConfig.realEntryPagePath) { + // condition + __uniConfig.entryPagePath = __uniConfig.realEntryPagePath; + delete __uniConfig.realEntryPagePath; + uni.reLaunch({ + url: addLeadingSlash(__uniConfig.entryPagePath), + }); + } + else { + const { delta, animationType, animationDuration } = args; + back(delta, animationType, animationDuration); + } + return resolve(); + }, NavigateBackProtocol, NavigateBackOptions); + let firstBackTime = 0; + function quit() { + initI18nAppMsgsOnce(); + if (!firstBackTime) { + firstBackTime = Date.now(); + plus.nativeUI.toast(useI18n().t('uni.app.quit')); + setTimeout(() => { + firstBackTime = 0; + }, 2000); + } + else if (Date.now() - firstBackTime < 2000) { + plus.runtime.quit(); + } + } + function back(delta, animationType, animationDuration) { + const pages = getCurrentPages(); + const len = pages.length; + const currentPage = pages[len - 1]; + if (delta > 1) { + // 中间页隐藏 + pages + .slice(len - delta, len - 1) + .reverse() + .forEach((deltaPage) => { + closeWebview(plus.webview.getWebviewById(deltaPage.$page.id + ''), 'none', 0); + }); + } + const backPage = function (webview) { + if (animationType) { + closeWebview(webview, animationType, animationDuration || ANI_DURATION); + } + else { + if (currentPage.$page.openType === 'redirectTo') { + // 如果是 redirectTo 跳转的,需要指定 back 动画 + closeWebview(webview, ANI_CLOSE, ANI_DURATION); + } + else { + closeWebview(webview, 'auto'); + } + } + pages + .slice(len - delta, len) + .forEach((page) => removePage(page)); + setStatusBarStyle(); + // 前一个页面触发 onShow + invokeHook(ON_SHOW); + }; + const webview = plus.webview.getWebviewById(currentPage.$page.id + ''); + if (!currentPage.__uniapp_webview) { + return backPage(webview); + } + backWebview(webview, () => { + backPage(webview); + }); } + const redirectTo = defineAsyncApi(API_REDIRECT_TO, ({ url }, { resolve, reject }) => { + const { path, query } = parseUrl(url); + navigate(path, () => { + _redirectTo({ + url, + path, + query, + }) + .then(resolve) + .catch(reject); + }); + }, RedirectToProtocol, RedirectToOptions); + function _redirectTo({ url, path, query, }) { + // TODO exists + // if (exists === 'back') { + // const existsPageIndex = findExistsPageIndex(url) + // if (existsPageIndex !== -1) { + // const delta = len - existsPageIndex + // if (delta > 0) { + // navigateBack({ + // delta, + // }) + // invoke(callbackId, { + // errMsg: 'redirectTo:ok', + // }) + // return + // } + // } + // } + const lastPage = getCurrentPage(); + lastPage && removePage(lastPage); + return new Promise((resolve) => { + showWebview(registerPage({ + url, + path, + query, + openType: 'redirectTo', + }), 'none', 0, () => { + if (lastPage) { + const webview = lastPage + .$getAppWebview(); + if (webview.__preload__) { + removePreloadWebview(webview); + } + webview.close('none'); + } + resolve(undefined); + }); + setStatusBarStyle(); + }); + } - /** - * ungzip(data[, options]) -> Uint8Array|String - * - data (Uint8Array): input data to decompress. - * - options (Object): zlib inflate options. - * - * Just shortcut to [[inflate]], because it autodetects format - * by header.content. Done for convenience. - **/ - - - var Inflate_1$1 = Inflate$1; - var inflate_2 = inflate$1; - var inflateRaw_1$1 = inflateRaw$1; - var ungzip$1 = inflate$1; - var constants = constants$2; - - var inflate_1$1 = { - Inflate: Inflate_1$1, - inflate: inflate_2, - inflateRaw: inflateRaw_1$1, - ungzip: ungzip$1, - constants: constants - }; - - const { Deflate, deflate, deflateRaw, gzip } = deflate_1$1; - - const { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1; - - + const reLaunch = defineAsyncApi(API_RE_LAUNCH, $reLaunch, ReLaunchProtocol, ReLaunchOptions); - var Deflate_1 = Deflate; - var deflate_1 = deflate; - var deflateRaw_1 = deflateRaw; - var gzip_1 = gzip; - var Inflate_1 = Inflate; - var inflate_1 = inflate; - var inflateRaw_1 = inflateRaw; - var ungzip_1 = ungzip; - var constants_1 = constants$2; + const unPreloadPage = defineSyncApi(API_UN_PRELOAD_PAGE, ({ url }) => { + const webview = closePreloadWebview({ + url, + }); + if (webview) { + return { + id: webview.id, + url, + errMsg: 'unPreloadPage:ok', + }; + } + return { + url, + errMsg: 'unPreloadPage:fail not found', + }; + }, UnPreloadPageProtocol); + const preloadPage = defineAsyncApi(API_PRELOAD_PAGE, ({ url }, { resolve, reject }) => { + const urls = url.split('?'); + const path = urls[0]; + const query = parseQuery(urls[1] || ''); + const webview = preloadWebview({ + url, + path, + query, + }); + resolve({ + id: webview.id, + url, + errMsg: 'preloadPage:ok', + }); + }, PreloadPageProtocol); - var pako = { - Deflate: Deflate_1, - deflate: deflate_1, - deflateRaw: deflateRaw_1, - gzip: gzip_1, - Inflate: Inflate_1, - inflate: inflate_1, - inflateRaw: inflateRaw_1, - ungzip: ungzip_1, - constants: constants_1 + var uni$1 = { + __proto__: null, + navigateTo: navigateTo, + reLaunch: reLaunch, + switchTab: switchTab, + upx2px: upx2px, + addInterceptor: addInterceptor, + removeInterceptor: removeInterceptor, + interceptors: interceptors, + arrayBufferToBase64: arrayBufferToBase64, + base64ToArrayBuffer: base64ToArrayBuffer, + createIntersectionObserver: createIntersectionObserver, + createMediaQueryObserver: createMediaQueryObserver, + createSelectorQuery: createSelectorQuery, + createVideoContext: createVideoContext, + createMapContext: createMapContext, + createAnimation: createAnimation, + onWindowResize: onWindowResize, + offWindowResize: offWindowResize, + onTabBarMidButtonTap: onTabBarMidButtonTap, + createCanvasContext: createCanvasContext, + canvasGetImageData: canvasGetImageData, + canvasPutImageData: canvasPutImageData, + canvasToTempFilePath: canvasToTempFilePath, + getSelectedTextRange: getSelectedTextRange, + getLocale: getLocale, + setLocale: setLocale, + $on: $on, + $off: $off, + $once: $once, + $emit: $emit, + onAppLaunch: onAppLaunch, + onLocaleChange: onLocaleChange, + setPageMeta: setPageMeta, + getEnterOptionsSync: getEnterOptionsSync, + getLaunchOptionsSync: getLaunchOptionsSync, + setStorageSync: setStorageSync, + setStorage: setStorage, + getStorageSync: getStorageSync, + getStorage: getStorage, + removeStorageSync: removeStorageSync, + removeStorage: removeStorage, + clearStorageSync: clearStorageSync, + clearStorage: clearStorage, + getStorageInfoSync: getStorageInfoSync, + getStorageInfo: getStorageInfo, + getFileInfo: getFileInfo$1, + openDocument: openDocument, + saveFile: saveFile, + getSystemInfoSync: getSystemInfoSync, + getSystemInfo: getSystemInfo, + onCompassChange: onCompassChange, + offCompassChange: offCompassChange, + startCompass: startCompass, + stopCompass: stopCompass, + vibrateShort: vibrateShort, + vibrateLong: vibrateLong, + onAccelerometerChange: onAccelerometerChange, + offAccelerometerChange: offAccelerometerChange, + startAccelerometer: startAccelerometer, + stopAccelerometer: stopAccelerometer, + onBluetoothDeviceFound: onBluetoothDeviceFound, + onBluetoothAdapterStateChange: onBluetoothAdapterStateChange, + onBLEConnectionStateChange: onBLEConnectionStateChange, + onBLECharacteristicValueChange: onBLECharacteristicValueChange, + openBluetoothAdapter: openBluetoothAdapter, + closeBluetoothAdapter: closeBluetoothAdapter, + getBluetoothAdapterState: getBluetoothAdapterState, + startBluetoothDevicesDiscovery: startBluetoothDevicesDiscovery, + stopBluetoothDevicesDiscovery: stopBluetoothDevicesDiscovery, + getBluetoothDevices: getBluetoothDevices, + getConnectedBluetoothDevices: getConnectedBluetoothDevices, + createBLEConnection: createBLEConnection, + closeBLEConnection: closeBLEConnection, + getBLEDeviceServices: getBLEDeviceServices, + getBLEDeviceCharacteristics: getBLEDeviceCharacteristics, + notifyBLECharacteristicValueChange: notifyBLECharacteristicValueChange, + readBLECharacteristicValue: readBLECharacteristicValue, + writeBLECharacteristicValue: writeBLECharacteristicValue, + setBLEMTU: setBLEMTU, + getBLEDeviceRSSI: getBLEDeviceRSSI, + onBeaconUpdate: onBeaconUpdate, + onBeaconServiceChange: onBeaconServiceChange, + getBeacons: getBeacons, + startBeaconDiscovery: startBeaconDiscovery, + stopBeaconDiscovery: stopBeaconDiscovery, + makePhoneCall: makePhoneCall, + addPhoneContact: addPhoneContact, + getClipboardData: getClipboardData, + setClipboardData: setClipboardData, + onNetworkStatusChange: onNetworkStatusChange, + offNetworkStatusChange: offNetworkStatusChange, + getNetworkType: getNetworkType, + checkIsSupportSoterAuthentication: checkIsSupportSoterAuthentication, + checkIsSoterEnrolledInDevice: checkIsSoterEnrolledInDevice, + startSoterAuthentication: startSoterAuthentication, + scanCode: scanCode, + onThemeChange: onThemeChange, + getScreenBrightness: getScreenBrightness, + setScreenBrightness: setScreenBrightness, + setKeepScreenOn: setKeepScreenOn, + getImageInfo: getImageInfo, + getVideoInfo: getVideoInfo, + previewImage: previewImage, + closePreviewImage: closePreviewImage, + getRecorderManager: getRecorderManager, + saveVideoToPhotosAlbum: saveVideoToPhotosAlbum, + saveImageToPhotosAlbum: saveImageToPhotosAlbum, + compressImage: compressImage, + compressVideo: compressVideo, + chooseImage: chooseImage, + chooseVideo: chooseVideo, + showKeyboard: showKeyboard, + hideKeyboard: hideKeyboard, + onKeyboardHeightChange: onKeyboardHeightChange, + offKeyboardHeightChange: offKeyboardHeightChange, + downloadFile: downloadFile, + request: request, + configMTLS: configMTLS, + connectSocket: connectSocket, + sendSocketMessage: sendSocketMessage, + closeSocket: closeSocket, + onSocketOpen: onSocketOpen, + onSocketError: onSocketError, + onSocketMessage: onSocketMessage, + onSocketClose: onSocketClose, + uploadFile: uploadFile, + createInnerAudioContext: createInnerAudioContext, + getBackgroundAudioManager: getBackgroundAudioManager, + createLivePusherContext: createLivePusherContext, + getLocation: getLocation, + chooseLocation: chooseLocation, + openLocation: openLocation, + showModal: showModal, + showActionSheet: showActionSheet, + showLoading: showLoading, + showToast: showToast, + hideToast: hideToast, + hideLoading: hideLoading, + startPullDownRefresh: startPullDownRefresh, + stopPullDownRefresh: stopPullDownRefresh, + loadFontFace: loadFontFace, + pageScrollTo: pageScrollTo, + setNavigationBarTitle: setNavigationBarTitle, + showNavigationBarLoading: showNavigationBarLoading, + hideNavigationBarLoading: hideNavigationBarLoading, + setNavigationBarColor: setNavigationBarColor, + setTabBarBadge: setTabBarBadge, + setTabBarItem: setTabBarItem, + setTabBarStyle: setTabBarStyle, + hideTabBar: hideTabBar, + showTabBar: showTabBar, + showTabBarRedDot: showTabBarRedDot, + removeTabBarBadge: removeTabBarBadge, + hideTabBarRedDot: hideTabBarRedDot, + getSubNVueById: getSubNVueById, + getProvider: getProvider, + login: login, + getUserInfo: getUserInfo, + getUserProfile: getUserProfile, + preLogin: preLogin, + closeAuthView: closeAuthView, + getCheckBoxState: getCheckBoxState, + getUniverifyManager: getUniverifyManager, + registerRuntime: registerRuntime, + share: share, + shareWithSystem: shareWithSystem, + requestPayment: requestPayment, + requireNativePlugin: requireNativePlugin, + sendNativeEvent: sendNativeEvent, + __vuePlugin: index$1, + restoreGlobal: restoreGlobal, + sendHostEvent: sendHostEvent, + navigateToMiniProgram: navigateToMiniProgram, + createRewardedVideoAd: createRewardedVideoAd, + createFullScreenVideoAd: createFullScreenVideoAd, + createInterstitialAd: createInterstitialAd, + createInteractiveAd: createInteractiveAd, + navigateBack: navigateBack, + redirectTo: redirectTo, + unPreloadPage: unPreloadPage, + preloadPage: preloadPage }; - var pako_esm = { - __proto__: null, - Deflate: Deflate_1, - Inflate: Inflate_1, - constants: constants_1, - 'default': pako, - deflate: deflate_1, - deflateRaw: deflateRaw_1, - gzip: gzip_1, - inflate: inflate_1, - inflateRaw: inflateRaw_1, - ungzip: ungzip_1 + const UniServiceJSBridge$1 = /*#__PURE__*/ extend(ServiceJSBridge, { + publishHandler, + }); + function publishHandler(event, args, pageIds) { + args = JSON.stringify(args); + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('publishHandler', event, args, pageIds)); + } + if (!isArray$1(pageIds)) { + pageIds = [pageIds]; + } + const evalJSCode = `typeof UniViewJSBridge !== 'undefined' && UniViewJSBridge.subscribeHandler("${event}",${args},__PAGE_ID__)`; + if ((process.env.NODE_ENV !== 'production')) { + console.log(formatLog('publishHandler', 'size', evalJSCode.length)); + } + pageIds.forEach((id) => { + const idStr = String(id); + const webview = plus.webview.getWebviewById(idStr); + webview && webview.evalJS(evalJSCode.replace('__PAGE_ID__', idStr)); + }); + } + + var index = { + uni: uni$1, + getApp: getApp$1, + getCurrentPages: getCurrentPages$1, + __definePage: definePage, + __registerApp: registerApp, + __registerPage: registerPage, + UniServiceJSBridge: UniServiceJSBridge$1, }; return index; diff --git a/packages/uni-app-plus/dist/uni-app-view.umd.js b/packages/uni-app-plus/dist/uni-app-view.umd.js index 9eb5d2529..2562fbe3a 100644 --- a/packages/uni-app-plus/dist/uni-app-view.umd.js +++ b/packages/uni-app-plus/dist/uni-app-view.umd.js @@ -1,3 +1,3 @@ -(function(xn){typeof define=="function"&&define.amd?define(xn):xn()})(function(){"use strict";var xn="",zy="",Yy="",Gt={exports:{}},Zr={exports:{}},Qr={exports:{}},Oc=Qr.exports={version:"2.6.12"};typeof __e=="number"&&(__e=Oc);var pt={exports:{}},ei=pt.exports=typeof ei!="undefined"&&ei.Math==Math?ei:typeof self!="undefined"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=ei);var Ac=Qr.exports,Ws=pt.exports,Vs="__core-js_shared__",Hs=Ws[Vs]||(Ws[Vs]={});(Zr.exports=function(e,t){return Hs[e]||(Hs[e]=t!==void 0?t:{})})("versions",[]).push({version:Ac.version,mode:"window",copyright:"\xA9 2020 Denis Pushkarev (zloirock.ru)"});var Mc=0,Rc=Math.random(),En=function(e){return"Symbol(".concat(e===void 0?"":e,")_",(++Mc+Rc).toString(36))},Tn=Zr.exports("wks"),Pc=En,Cn=pt.exports.Symbol,js=typeof Cn=="function",Lc=Gt.exports=function(e){return Tn[e]||(Tn[e]=js&&Cn[e]||(js?Cn:Pc)("Symbol."+e))};Lc.store=Tn;var ti={},In=function(e){return typeof e=="object"?e!==null:typeof e=="function"},Nc=In,On=function(e){if(!Nc(e))throw TypeError(e+" is not an object!");return e},ri=function(e){try{return!!e()}catch(t){return!0}},hr=!ri(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7}),zs=In,An=pt.exports.document,Dc=zs(An)&&zs(An.createElement),Ys=function(e){return Dc?An.createElement(e):{}},kc=!hr&&!ri(function(){return Object.defineProperty(Ys("div"),"a",{get:function(){return 7}}).a!=7}),ii=In,Bc=function(e,t){if(!ii(e))return e;var r,i;if(t&&typeof(r=e.toString)=="function"&&!ii(i=r.call(e))||typeof(r=e.valueOf)=="function"&&!ii(i=r.call(e))||!t&&typeof(r=e.toString)=="function"&&!ii(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},qs=On,Fc=kc,$c=Bc,Uc=Object.defineProperty;ti.f=hr?Object.defineProperty:function(t,r,i){if(qs(t),r=$c(r,!0),qs(i),Fc)try{return Uc(t,r,i)}catch(n){}if("get"in i||"set"in i)throw TypeError("Accessors not supported!");return"value"in i&&(t[r]=i.value),t};var Xs=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}},Wc=ti,Vc=Xs,Jt=hr?function(e,t,r){return Wc.f(e,t,Vc(1,r))}:function(e,t,r){return e[t]=r,e},Mn=Gt.exports("unscopables"),Rn=Array.prototype;Rn[Mn]==null&&Jt(Rn,Mn,{});var Hc=function(e){Rn[Mn][e]=!0},jc=function(e,t){return{value:t,done:!!e}},Pn={},zc={}.toString,Yc=function(e){return zc.call(e).slice(8,-1)},qc=Yc,Xc=Object("z").propertyIsEnumerable(0)?Object:function(e){return qc(e)=="String"?e.split(""):Object(e)},Ks=function(e){if(e==null)throw TypeError("Can't call method on "+e);return e},Kc=Xc,Gc=Ks,ni=function(e){return Kc(Gc(e))},ai={exports:{}},Jc={}.hasOwnProperty,si=function(e,t){return Jc.call(e,t)},Zc=Zr.exports("native-function-to-string",Function.toString),Qc=pt.exports,oi=Jt,Gs=si,Ln=En("src"),Nn=Zc,Js="toString",ev=(""+Nn).split(Js);Qr.exports.inspectSource=function(e){return Nn.call(e)},(ai.exports=function(e,t,r,i){var n=typeof r=="function";n&&(Gs(r,"name")||oi(r,"name",t)),e[t]!==r&&(n&&(Gs(r,Ln)||oi(r,Ln,e[t]?""+e[t]:ev.join(String(t)))),e===Qc?e[t]=r:i?e[t]?e[t]=r:oi(e,t,r):(delete e[t],oi(e,t,r)))})(Function.prototype,Js,function(){return typeof this=="function"&&this[Ln]||Nn.call(this)});var Zs=function(e){if(typeof e!="function")throw TypeError(e+" is not a function!");return e},tv=Zs,rv=function(e,t,r){if(tv(e),t===void 0)return e;switch(r){case 1:return function(i){return e.call(t,i)};case 2:return function(i,n){return e.call(t,i,n)};case 3:return function(i,n,a){return e.call(t,i,n,a)}}return function(){return e.apply(t,arguments)}},Zt=pt.exports,li=Qr.exports,iv=Jt,nv=ai.exports,Qs=rv,Dn="prototype",Be=function(e,t,r){var i=e&Be.F,n=e&Be.G,a=e&Be.S,s=e&Be.P,o=e&Be.B,l=n?Zt:a?Zt[t]||(Zt[t]={}):(Zt[t]||{})[Dn],u=n?li:li[t]||(li[t]={}),v=u[Dn]||(u[Dn]={}),c,m,g,_;n&&(r=t);for(c in r)m=!i&&l&&l[c]!==void 0,g=(m?l:r)[c],_=o&&m?Qs(g,Zt):s&&typeof g=="function"?Qs(Function.call,g):g,l&&nv(l,c,g,e&Be.U),u[c]!=g&&iv(u,c,_),s&&v[c]!=g&&(v[c]=g)};Zt.core=li,Be.F=1,Be.G=2,Be.S=4,Be.P=8,Be.B=16,Be.W=32,Be.U=64,Be.R=128;var kn=Be,av=Math.ceil,sv=Math.floor,eo=function(e){return isNaN(e=+e)?0:(e>0?sv:av)(e)},ov=eo,lv=Math.min,uv=function(e){return e>0?lv(ov(e),9007199254740991):0},fv=eo,cv=Math.max,vv=Math.min,dv=function(e,t){return e=fv(e),e<0?cv(e+t,0):vv(e,t)},hv=ni,gv=uv,pv=dv,mv=function(e){return function(t,r,i){var n=hv(t),a=gv(n.length),s=pv(i,a),o;if(e&&r!=r){for(;a>s;)if(o=n[s++],o!=o)return!0}else for(;a>s;s++)if((e||s in n)&&n[s]===r)return e||s||0;return!e&&-1}},to=Zr.exports("keys"),_v=En,Bn=function(e){return to[e]||(to[e]=_v(e))},ro=si,bv=ni,wv=mv(!1),yv=Bn("IE_PROTO"),Sv=function(e,t){var r=bv(e),i=0,n=[],a;for(a in r)a!=yv&&ro(r,a)&&n.push(a);for(;t.length>i;)ro(r,a=t[i++])&&(~wv(n,a)||n.push(a));return n},io="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),xv=Sv,Ev=io,Fn=Object.keys||function(t){return xv(t,Ev)},Tv=ti,Cv=On,Iv=Fn,Ov=hr?Object.defineProperties:function(t,r){Cv(t);for(var i=Iv(r),n=i.length,a=0,s;n>a;)Tv.f(t,s=i[a++],r[s]);return t},no=pt.exports.document,Av=no&&no.documentElement,Mv=On,Rv=Ov,ao=io,Pv=Bn("IE_PROTO"),$n=function(){},Un="prototype",ui=function(){var e=Ys("iframe"),t=ao.length,r="<",i=">",n;for(e.style.display="none",Av.appendChild(e),e.src="javascript:",n=e.contentWindow.document,n.open(),n.write(r+"script"+i+"document.F=Object"+r+"/script"+i),n.close(),ui=n.F;t--;)delete ui[Un][ao[t]];return ui()},Lv=Object.create||function(t,r){var i;return t!==null?($n[Un]=Mv(t),i=new $n,$n[Un]=null,i[Pv]=t):i=ui(),r===void 0?i:Rv(i,r)},Nv=ti.f,Dv=si,so=Gt.exports("toStringTag"),oo=function(e,t,r){e&&!Dv(e=r?e:e.prototype,so)&&Nv(e,so,{configurable:!0,value:t})},kv=Lv,Bv=Xs,Fv=oo,lo={};Jt(lo,Gt.exports("iterator"),function(){return this});var $v=function(e,t,r){e.prototype=kv(lo,{next:Bv(1,r)}),Fv(e,t+" Iterator")},Uv=Ks,uo=function(e){return Object(Uv(e))},Wv=si,Vv=uo,fo=Bn("IE_PROTO"),Hv=Object.prototype,jv=Object.getPrototypeOf||function(e){return e=Vv(e),Wv(e,fo)?e[fo]:typeof e.constructor=="function"&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?Hv:null},Wn=kn,zv=ai.exports,co=Jt,vo=Pn,Yv=$v,qv=oo,Xv=jv,gr=Gt.exports("iterator"),Vn=!([].keys&&"next"in[].keys()),Kv="@@iterator",ho="keys",fi="values",go=function(){return this},Gv=function(e,t,r,i,n,a,s){Yv(r,t,i);var o=function(f){if(!Vn&&f in c)return c[f];switch(f){case ho:return function(){return new r(this,f)};case fi:return function(){return new r(this,f)}}return function(){return new r(this,f)}},l=t+" Iterator",u=n==fi,v=!1,c=e.prototype,m=c[gr]||c[Kv]||n&&c[n],g=m||o(n),_=n?u?o("entries"):g:void 0,b=t=="Array"&&c.entries||m,w,p,h;if(b&&(h=Xv(b.call(new e)),h!==Object.prototype&&h.next&&(qv(h,l,!0),typeof h[gr]!="function"&&co(h,gr,go))),u&&m&&m.name!==fi&&(v=!0,g=function(){return m.call(this)}),(Vn||v||!c[gr])&&co(c,gr,g),vo[t]=g,vo[l]=go,n)if(w={values:u?g:o(fi),keys:a?g:o(ho),entries:_},s)for(p in w)p in c||zv(c,p,w[p]);else Wn(Wn.P+Wn.F*(Vn||v),t,w);return w},Hn=Hc,ci=jc,po=Pn,Jv=ni,Zv=Gv(Array,"Array",function(e,t){this._t=Jv(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,r=this._i++;return!e||r>=e.length?(this._t=void 0,ci(1)):t=="keys"?ci(0,r):t=="values"?ci(0,e[r]):ci(0,[r,e[r]])},"values");po.Arguments=po.Array,Hn("keys"),Hn("values"),Hn("entries");for(var mo=Zv,Qv=Fn,ed=ai.exports,td=pt.exports,_o=Jt,bo=Pn,wo=Gt.exports,yo=wo("iterator"),So=wo("toStringTag"),xo=bo.Array,Eo={CSSRuleList:!0,CSSStyleDeclaration:!1,CSSValueList:!1,ClientRectList:!1,DOMRectList:!1,DOMStringList:!1,DOMTokenList:!0,DataTransferItemList:!1,FileList:!1,HTMLAllCollection:!1,HTMLCollection:!1,HTMLFormElement:!1,HTMLSelectElement:!1,MediaList:!0,MimeTypeArray:!1,NamedNodeMap:!1,NodeList:!0,PaintRequestList:!1,Plugin:!1,PluginArray:!1,SVGLengthList:!1,SVGNumberList:!1,SVGPathSegList:!1,SVGPointList:!1,SVGStringList:!1,SVGTransformList:!1,SourceBufferList:!1,StyleSheetList:!0,TextTrackCueList:!1,TextTrackList:!1,TouchList:!1},To=Qv(Eo),jn=0;jn!!r[a.toLowerCase()]:a=>!!r[a]}var id="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly",nd=hi(id);function Io(e){return!!e||e===""}var ad=hi("animation-iteration-count,border-image-outset,border-image-slice,border-image-width,box-flex,box-flex-group,box-ordinal-group,column-count,columns,flex,flex-grow,flex-positive,flex-shrink,flex-negative,flex-order,grid-row,grid-row-end,grid-row-span,grid-row-start,grid-column,grid-column-end,grid-column-span,grid-column-start,font-weight,line-clamp,line-height,opacity,order,orphans,tab-size,widows,z-index,zoom,fill-opacity,flood-opacity,stop-opacity,stroke-dasharray,stroke-dashoffset,stroke-miterlimit,stroke-opacity,stroke-width");function zn(e){if(oe(e)){for(var t={},r=0;r{if(r){var i=r.split(od);i.length>1&&(t[i[0].trim()]=i[1].trim())}}),t}function ld(e){var t="";if(!e||ye(e))return t;for(var r in e){var i=e[r],n=r.startsWith("--")?r:Ve(r);(ye(i)||typeof i=="number"&&ad(n))&&(t+="".concat(n,":").concat(i,";"))}return t}function Yn(e){var t="";if(ye(e))t=e;else if(oe(e))for(var r=0;r{},ud=()=>!1,fd=/^on[^a-z]/,gi=e=>fd.test(e),qn=e=>e.startsWith("onUpdate:"),ue=Object.assign,Ao=(e,t)=>{var r=e.indexOf(t);r>-1&&e.splice(r,1)},cd=Object.prototype.hasOwnProperty,te=(e,t)=>cd.call(e,t),oe=Array.isArray,mr=e=>_r(e)==="[object Map]",vd=e=>_r(e)==="[object Set]",ae=e=>typeof e=="function",ye=e=>typeof e=="string",Xn=e=>typeof e=="symbol",ke=e=>e!==null&&typeof e=="object",Mo=e=>ke(e)&&ae(e.then)&&ae(e.catch),dd=Object.prototype.toString,_r=e=>dd.call(e),Kn=e=>_r(e).slice(8,-1),Je=e=>_r(e)==="[object Object]",Gn=e=>ye(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,pi=hi(",key,ref,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),mi=e=>{var t=Object.create(null);return r=>{var i=t[r];return i||(t[r]=e(r))}},hd=/-(\w)/g,mt=mi(e=>e.replace(hd,(t,r)=>r?r.toUpperCase():"")),gd=/\B([A-Z])/g,Ve=mi(e=>e.replace(gd,"-$1").toLowerCase()),_i=mi(e=>e.charAt(0).toUpperCase()+e.slice(1)),Jn=mi(e=>e?"on".concat(_i(e)):""),br=(e,t)=>!Object.is(e,t),Zn=(e,t)=>{for(var r=0;r{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,value:r})},pd=e=>{var t=parseFloat(e);return isNaN(t)?e:t},Ro,md=()=>Ro||(Ro=typeof globalThis!="undefined"?globalThis:typeof self!="undefined"?self:typeof window!="undefined"||typeof window!="undefined"?window:{}),wr=` -`,Po=44,wi="#007aff",_d=/^([a-z-]+:)?\/\//i,bd=/^data:.*,.*/,Lo="wxs://",No="json://",wd="wxsModules",yd="renderjsModules",Do="onPageScroll",ko="onReachBottom",Sd="onWxsInvokeCallMethod",Qn=0;function ea(e){var t=Date.now(),r=Qn?t-Qn:0;Qn=t;for(var i=arguments.length,n=new Array(i>1?i-1:0),a=1;aJSON.stringify(s)).join(" "))}function ta(e){return ue({},e.dataset,e.__uniDataset)}function ra(e){return{passive:e}}function ia(e){var{id:t,offsetTop:r,offsetLeft:i}=e;return{id:t,dataset:ta(e),offsetTop:r,offsetLeft:i}}function xd(e,t,r){var i=document.fonts;if(i){var n=new FontFace(e,t,r);return n.load().then(()=>{i.add&&i.add(n)})}return new Promise(a=>{var s=document.createElement("style"),o=[];if(r){var{style:l,weight:u,stretch:v,unicodeRange:c,variant:m,featureSettings:g}=r;l&&o.push("font-style:".concat(l)),u&&o.push("font-weight:".concat(u)),v&&o.push("font-stretch:".concat(v)),c&&o.push("unicode-range:".concat(c)),m&&o.push("font-variant:".concat(m)),g&&o.push("font-feature-settings:".concat(g))}s.innerText='@font-face{font-family:"'.concat(e,'";src:').concat(t,";").concat(o.join(";"),"}"),document.head.appendChild(s),a()})}function Ed(e,t){if(ye(e)){var r=document.querySelector(e);r&&(e=r.getBoundingClientRect().top+window.pageYOffset)}e<0&&(e=0);var i=document.documentElement,{clientHeight:n,scrollHeight:a}=i;if(e=Math.min(e,a-n),t===0){i.scrollTop=document.body.scrollTop=e;return}if(window.scrollY!==e){var s=o=>{if(o<=0){window.scrollTo(0,e);return}var l=e-window.scrollY;requestAnimationFrame(function(){window.scrollTo(0,window.scrollY+l/o*10),s(o-10)})};s(t)}}function Td(){return typeof __channelId__=="string"&&__channelId__}function Cd(e,t){switch(Kn(t)){case"Function":return"function() { [native code] }";default:return t}}function Id(e,t,r){if(Td())return r.push(t.replace("at ","uni-app:///")),console[e].apply(console,r);var i=r.map(function(n){var a=_r(n).toLowerCase();if(a==="[object object]"||a==="[object array]")try{n="---BEGIN:JSON---"+JSON.stringify(n,Cd)+"---END:JSON---"}catch(o){n=a}else if(n===null)n="---NULL---";else if(n===void 0)n="---UNDEFINED---";else{var s=Kn(n).toUpperCase();s==="NUMBER"||s==="BOOLEAN"?n="---BEGIN:"+s+"---"+n+"---END:"+s+"---":n=String(n)}return n});return i.join("---COMMA---")+" "+t}function Od(e,t){for(var r=arguments.length,i=new Array(r>2?r-2:0),n=2;n-1&&n.splice(a,1)}}}var $o=/(?:Once|Passive|Capture)$/;function yi(e){var t;if($o.test(e)){t={};for(var r;r=e.match($o);)e=e.slice(0,e.length-r[0].length),t[r[0].toLowerCase()]=!0}return[Ve(e.slice(2)),t]}var aa={stop:1,prevent:1<<1,self:1<<2},Rd=0,Pd=1;function Uo(e,t){var{parentNode:r}=e;if(!r)return null;var{childNodes:i}=r;return i[i.indexOf(e)+(t==="n"?1:-1)]||null}function Ld(e){var{parentNode:t}=e;t&&t.removeChild(e)}function Nd(e){!e.nodeId&&e.pageNode&&(e.nodeId=e.pageNode.genId())}class Dd extends Md{constructor(t,r,i){super();if(this.pageNode=null,this.parentNode=null,this._text=null,i){var{pageNode:n}=i;n&&(this.pageNode=n,this.nodeId=n.genId(),!n.isUnmounted&&n.onCreate(this,r))}this.nodeType=t,this.nodeName=r,this.childNodes=[]}get firstChild(){return this.childNodes[0]||null}get lastChild(){var{childNodes:t}=this,r=t.length;return r?t[r-1]:null}get nextSibling(){return Uo(this,"n")}get nodeValue(){return null}set nodeValue(t){}get textContent(){return this._text||""}set textContent(t){this._text=t,this.pageNode&&!this.pageNode.isUnmounted&&this.pageNode.onTextContent(this,t)}get parentElement(){var{parentNode:t}=this;return t&&t.nodeType===Pd?t:null}get previousSibling(){return Uo(this,"p")}appendChild(t){return this.insertBefore(t,null)}cloneNode(t){var r=ue(Object.create(Object.getPrototypeOf(this)),this),{attributes:i}=r;return i&&(r.attributes=ue({},i)),t&&(r.childNodes=r.childNodes.map(n=>n.cloneNode(!0))),r}insertBefore(t,r){Ld(t),t.pageNode=this.pageNode,t.parentNode=this,Nd(t);var{childNodes:i}=this;if(r){var n=i.indexOf(r);if(n===-1)throw new Bo("Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.");i.splice(n,0,t)}else i.push(t);return this.pageNode&&!this.pageNode.isUnmounted?this.pageNode.onInsertBefore(this,t,r):t}removeChild(t){var{childNodes:r}=this,i=r.indexOf(t);if(i===-1)throw new Bo("Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.");return t.parentNode=null,r.splice(i,1),this.pageNode&&!this.pageNode.isUnmounted?this.pageNode.onRemoveChild(t):t}}var Wo="class",sa="style",kd="innerHTML",Bd="textContent",Si=".vShow",Vo=".vOwnerId",Ho=".vRenderjs",oa="change:",la=1,jo=2,ua=3,fa=4,zo=5,Yo=6,qo=7,Xo=8,Ko=9,Go=10,Jo=12,Zo=15,Fd=20;function $d(e){var t=Object.create(null);return r=>{var i=t[r];return i||(t[r]=e(r))}}function Ud(e){return $d(e)}function Wd(e){return e.indexOf("/")===0}function ca(e){return Wd(e)?e:"/"+e}function va(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,r;return function(){if(e){for(var i=arguments.length,n=new Array(i),a=0;ae.apply(this,arguments);r=setTimeout(n,t)};return i.cancel=function(){clearTimeout(r)},i}var Hd=Array.isArray,jd=e=>e!==null&&typeof e=="object",zd=["{","}"];class Yd{constructor(){this._caches=Object.create(null)}interpolate(t,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:zd;if(!r)return[t];var n=this._caches[t];return n||(n=Kd(t,i),this._caches[t]=n),Gd(n,r)}}var qd=/^(?:\d)+/,Xd=/^(?:\w)+/;function Kd(e,t){for(var[r,i]=t,n=[],a=0,s="";aJd.call(e,t),Zd=new Yd;function Qd(e,t){return!!t.find(r=>e.indexOf(r)!==-1)}function eh(e,t){return t.find(r=>e.indexOf(r)===0)}function tl(e,t){if(!!e){if(e=e.trim().replace(/_/g,"-"),t&&t[e])return e;if(e=e.toLowerCase(),e==="chinese")return yr;if(e.indexOf("zh")===0)return e.indexOf("-hans")>-1?yr:e.indexOf("-hant")>-1||Qd(e,["-tw","-hk","-mo","-cht"])?xi:yr;var r=eh(e,[_t,da,ha]);if(r)return r}}class th{constructor(t){var{locale:r,fallbackLocale:i,messages:n,watcher:a,formater:s}=t;this.locale=_t,this.fallbackLocale=_t,this.message={},this.messages={},this.watchers=[],i&&(this.fallbackLocale=i),this.formater=s||Zd,this.messages=n||{},this.setLocale(r||_t),a&&this.watchLocale(a)}setLocale(t){var r=this.locale;this.locale=tl(t,this.messages)||this.fallbackLocale,this.messages[this.locale]||(this.messages[this.locale]={}),this.message=this.messages[this.locale],r!==this.locale&&this.watchers.forEach(i=>{i(this.locale,r)})}getLocale(){return this.locale}watchLocale(t){var r=this.watchers.push(t)-1;return()=>{this.watchers.splice(r,1)}}add(t,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,n=this.messages[t];n?i?Object.assign(n,r):Object.keys(r).forEach(a=>{el(n,a)||(n[a]=r[a])}):this.messages[t]=r}f(t,r,i){return this.formater.interpolate(t,r,i).join("")}t(t,r,i){var n=this.message;return typeof r=="string"?(r=tl(r,this.messages),r&&(n=this.messages[r])):i=r,el(n,t)?this.formater.interpolate(n[t],i).join(""):(console.warn("Cannot translate the value of keypath ".concat(t,". Use the value of keypath as default.")),t)}}function rh(e,t){e.$watchLocale?e.$watchLocale(r=>{t.setLocale(r)}):e.$watch(()=>e.$locale,r=>{t.setLocale(r)})}function ih(){return typeof uni!="undefined"&&uni.getLocale?uni.getLocale():typeof window!="undefined"&&window.getLocale?window.getLocale():_t}function nh(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0;typeof e!="string"&&([e,t]=[t,e]),typeof e!="string"&&(e=ih()),typeof r!="string"&&(r=typeof __uniConfig!="undefined"&&__uniConfig.fallbackLocale||_t);var n=new th({locale:e,fallbackLocale:r,messages:t,watcher:i}),a=(s,o)=>{if(typeof getApp!="function")a=function(u,v){return n.t(u,v)};else{var l=!1;a=function(u,v){var c=getApp().$vm;return c&&(c.$locale,l||(l=!0,rh(c,n))),n.t(u,v)}}return a(s,o)};return{i18n:n,f(s,o,l){return n.f(s,o,l)},t(s,o){return a(s,o)},add(s,o){var l=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return n.add(s,o,l)},watch(s){return n.watchLocale(s)},getLocale(){return n.getLocale()},setLocale(s){return n.setLocale(s)}}}var ga;function He(){if(!ga){var e;typeof getApp=="function"?e=weex.requireModule("plus").getLanguage():e=plus.webview.currentWebview().getStyle().locale,ga=nh(e)}return ga}function nt(e,t,r){return t.reduce((i,n,a)=>(i[e+n]=r[a],i),{})}var ah=va(()=>{var e="uni.picker.",t=["done","cancel"];He().add(_t,nt(e,t,["Done","Cancel"]),!1),He().add(ha,nt(e,t,["OK","Cancelar"]),!1),He().add(da,nt(e,t,["OK","Annuler"]),!1),He().add(yr,nt(e,t,["\u5B8C\u6210","\u53D6\u6D88"]),!1),He().add(xi,nt(e,t,["\u5B8C\u6210","\u53D6\u6D88"]),!1)}),sh=va(()=>{var e="uni.button.",t=["feedback.title","feedback.send"];He().add(_t,nt(e,t,["feedback","send"]),!1),He().add(ha,nt(e,t,["realimentaci\xF3n","enviar"]),!1),He().add(da,nt(e,t,["retour d'information","envoyer"]),!1),He().add(yr,nt(e,t,["\u95EE\u9898\u53CD\u9988","\u53D1\u9001"]),!1),He().add(xi,nt(e,t,["\u554F\u984C\u53CD\u994B","\u767C\u9001"]),!1)}),rl=function(){};rl.prototype={on:function(e,t,r){var i=this.e||(this.e={});return(i[e]||(i[e]=[])).push({fn:t,ctx:r}),this},once:function(e,t,r){var i=this;function n(){i.off(e,n),t.apply(r,arguments)}return n._=t,this.on(e,n,r)},emit:function(e){var t=[].slice.call(arguments,1),r=((this.e||(this.e={}))[e]||[]).slice(),i=0,n=r.length;for(i;i1?i-1:0),a=1;a2&&arguments[2]!==void 0?arguments[2]:!1;t[n?"once":"on"]("".concat(e,".").concat(r),i)},unsubscribe(r,i){t.off("".concat(e,".").concat(r),i)},subscribeHandler(r,i,n){t.emit("".concat(e,".").concat(r),i,n)}}}var il="invokeViewApi",nl="invokeServiceApi",lh=1,uh=(e,t,r)=>{var{subscribe:i,publishHandler:n}=UniViewJSBridge,a=r?lh++:0;r&&i(nl+"."+a,r,!0),n(nl,{id:a,name:e,args:t})},Ei=Object.create(null);function Ti(e,t){return e+"."+t}function fh(e,t){UniViewJSBridge.subscribe(Ti(e,il),t?t(al):al)}function at(e,t,r){t=Ti(e,t),Ei[t]||(Ei[t]=r)}function ch(e,t){t=Ti(e,t),delete Ei[t]}function al(e,t){var{id:r,name:i,args:n}=e;i=Ti(t,i);var a=o=>{r&&UniViewJSBridge.publishHandler(il+"."+r,o)},s=Ei[i];s?s(n,a):a({})}var vh=ue(oh("service"),{invokeServiceMethod:uh}),dh=350,sl=10,Ci=ra(!0),Sr;function xr(){Sr&&(clearTimeout(Sr),Sr=null)}var ol=0,ll=0;function hh(e){if(xr(),e.touches.length===1){var{pageX:t,pageY:r}=e.touches[0];ol=t,ll=r,Sr=setTimeout(function(){var i=new CustomEvent("longpress",{bubbles:!0,cancelable:!0,target:e.target,currentTarget:e.currentTarget});i.touches=e.touches,i.changedTouches=e.changedTouches,e.target.dispatchEvent(i)},dh)}}function gh(e){if(!!Sr){if(e.touches.length!==1)return xr();var{pageX:t,pageY:r}=e.touches[0];if(Math.abs(t-ol)>sl||Math.abs(r-ll)>sl)return xr()}}function ph(){window.addEventListener("touchstart",hh,Ci),window.addEventListener("touchmove",gh,Ci),window.addEventListener("touchend",xr,Ci),window.addEventListener("touchcancel",xr,Ci)}function ul(e,t){var r=Number(e);return isNaN(r)?t:r}function mh(){var e=/^Apple/.test(navigator.vendor)&&typeof window.orientation=="number",t=e&&Math.abs(window.orientation)===90,r=e?Math[t?"max":"min"](screen.width,screen.height):screen.width,i=Math.min(window.innerWidth,document.documentElement.clientWidth,r)||r;return i}function _h(){function e(){var t=__uniConfig.globalStyle||{},r=ul(t.rpxCalcMaxDeviceWidth,960),i=ul(t.rpxCalcBaseDeviceWidth,375),n=mh();n=n<=r?n:i,document.documentElement.style.fontSize=n/23.4375+"px"}e(),document.addEventListener("DOMContentLoaded",e),window.addEventListener("load",e),window.addEventListener("resize",e)}function bh(){_h(),ph()}var wh=ri,yh=function(e,t){return!!e&&wh(function(){t?e.call(null,function(){},1):e.call(null)})},pa=kn,Sh=Zs,fl=uo,cl=ri,ma=[].sort,vl=[1,2,3];pa(pa.P+pa.F*(cl(function(){vl.sort(void 0)})||!cl(function(){vl.sort(null)})||!yh(ma)),"Array",{sort:function(t){return t===void 0?ma.call(fl(this)):ma.call(fl(this),Sh(t))}});var Lt,Ii=[];class xh{constructor(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.active=!0,this.effects=[],this.cleanups=[],!t&&Lt&&(this.parent=Lt,this.index=(Lt.scopes||(Lt.scopes=[])).push(this)-1)}run(t){if(this.active)try{return this.on(),t()}finally{this.off()}}on(){this.active&&(Ii.push(this),Lt=this)}off(){this.active&&(Ii.pop(),Lt=Ii[Ii.length-1])}stop(t){if(this.active){if(this.effects.forEach(i=>i.stop()),this.cleanups.forEach(i=>i()),this.scopes&&this.scopes.forEach(i=>i.stop(!0)),this.parent&&!t){var r=this.parent.scopes.pop();r&&r!==this&&(this.parent.scopes[this.index]=r,r.index=this.index)}this.active=!1}}}function Eh(e,t){t=t||Lt,t&&t.active&&t.effects.push(e)}var _a=e=>{var t=new Set(e);return t.w=0,t.n=0,t},dl=e=>(e.w&bt)>0,hl=e=>(e.n&bt)>0,Th=e=>{var{deps:t}=e;if(t.length)for(var r=0;r{var{deps:t}=e;if(t.length){for(var r=0,i=0;i1&&arguments[1]!==void 0?arguments[1]:null,i=arguments.length>2?arguments[2]:void 0;this.fn=t,this.scheduler=r,this.active=!0,this.deps=[],Eh(this,i)}run(){if(!this.active)return this.fn();if(!Tr.includes(this))try{return Tr.push(Nt=this),Ih(),bt=1<<++Er,Er<=wa?Th(this):gl(this),this.fn()}finally{Er<=wa&&Ch(this),bt=1<<--Er,kt(),Tr.pop();var t=Tr.length;Nt=t>0?Tr[t-1]:void 0}}stop(){this.active&&(gl(this),this.onStop&&this.onStop(),this.active=!1)}}function gl(e){var{deps:t}=e;if(t.length){for(var r=0;r{(c==="length"||c>=i)&&o.push(v)});else switch(r!==void 0&&o.push(s.get(r)),t){case"add":oe(e)?Gn(r)&&o.push(s.get("length")):(o.push(s.get(Dt)),mr(e)&&o.push(s.get(ya)));break;case"delete":oe(e)||(o.push(s.get(Dt)),mr(e)&&o.push(s.get(ya)));break;case"set":mr(e)&&o.push(s.get(Dt));break}if(o.length===1)o[0]&&Ea(o[0]);else{var l=[];for(var u of o)u&&l.push(...u);Ea(_a(l))}}}function Ea(e,t){for(var r of oe(e)?e:[...e])(r!==Nt||r.allowRecurse)&&(r.scheduler?r.scheduler():r.run())}var Oh=hi("__proto__,__v_isRef,__isVue"),_l=new Set(Object.getOwnPropertyNames(Symbol).map(e=>Symbol[e]).filter(Xn)),Ah=Ta(),Mh=Ta(!1,!0),Rh=Ta(!0),bl=Ph();function Ph(){var e={};return["includes","indexOf","lastIndexOf"].forEach(t=>{e[t]=function(){for(var r=ge(this),i=0,n=this.length;i{e[t]=function(){tr();for(var r=arguments.length,i=new Array(r),n=0;n0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function(i,n,a){if(n==="__v_isReactive")return!e;if(n==="__v_isReadonly")return e;if(n==="__v_raw"&&a===(e?t?Xh:Ol:t?Il:Cl).get(i))return i;var s=oe(i);if(!e&&s&&te(bl,n))return Reflect.get(bl,n,a);var o=Reflect.get(i,n,a);if((Xn(n)?_l.has(n):Oh(n))||(e||je(i,"get",n),t))return o;if(Ue(o)){var l=!s||!Gn(n);return l?o.value:o}return ke(o)?e?Al(o):Te(o):o}}var Lh=wl(),Nh=wl(!0);function wl(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return function(r,i,n,a){var s=r[i];if(!e&&(n=ge(n),s=ge(s),!oe(r)&&Ue(s)&&!Ue(n)))return s.value=n,!0;var o=oe(r)&&Gn(i)?Number(i)e,Oi=e=>Reflect.getPrototypeOf(e);function Ai(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;e=e.__v_raw;var n=ge(e),a=ge(t);t!==a&&!r&&je(n,"get",t),!r&&je(n,"get",a);var{has:s}=Oi(n),o=i?Ca:r?Aa:Cr;if(s.call(n,t))return o(e.get(t));if(s.call(n,a))return o(e.get(a));e!==n&&e.get(t)}function Mi(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,r=this.__v_raw,i=ge(r),n=ge(e);return e!==n&&!t&&je(i,"has",e),!t&&je(i,"has",n),e===n?r.has(e):r.has(e)||r.has(n)}function Ri(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return e=e.__v_raw,!t&&je(ge(e),"iterate",Dt),Reflect.get(e,"size",e)}function Sl(e){e=ge(e);var t=ge(this),r=Oi(t),i=r.has.call(t,e);return i||(t.add(e),vt(t,"add",e,e)),this}function xl(e,t){t=ge(t);var r=ge(this),{has:i,get:n}=Oi(r),a=i.call(r,e);a||(e=ge(e),a=i.call(r,e));var s=n.call(r,e);return r.set(e,t),a?br(t,s)&&vt(r,"set",e,t):vt(r,"add",e,t),this}function El(e){var t=ge(this),{has:r,get:i}=Oi(t),n=r.call(t,e);n||(e=ge(e),n=r.call(t,e)),i&&i.call(t,e);var a=t.delete(e);return n&&vt(t,"delete",e,void 0),a}function Tl(){var e=ge(this),t=e.size!==0,r=e.clear();return t&&vt(e,"clear",void 0,void 0),r}function Pi(e,t){return function(i,n){var a=this,s=a.__v_raw,o=ge(s),l=t?Ca:e?Aa:Cr;return!e&&je(o,"iterate",Dt),s.forEach((u,v)=>i.call(n,l(u),l(v),a))}}function Li(e,t,r){return function(){var i=this.__v_raw,n=ge(i),a=mr(n),s=e==="entries"||e===Symbol.iterator&&a,o=e==="keys"&&a,l=i[e](...arguments),u=r?Ca:t?Aa:Cr;return!t&&je(n,"iterate",o?ya:Dt),{next(){var{value:v,done:c}=l.next();return c?{value:v,done:c}:{value:s?[u(v[0]),u(v[1])]:u(v),done:c}},[Symbol.iterator](){return this}}}}function wt(e){return function(){return e==="delete"?!1:this}}function Uh(){var e={get(a){return Ai(this,a)},get size(){return Ri(this)},has:Mi,add:Sl,set:xl,delete:El,clear:Tl,forEach:Pi(!1,!1)},t={get(a){return Ai(this,a,!1,!0)},get size(){return Ri(this)},has:Mi,add:Sl,set:xl,delete:El,clear:Tl,forEach:Pi(!1,!0)},r={get(a){return Ai(this,a,!0)},get size(){return Ri(this,!0)},has(a){return Mi.call(this,a,!0)},add:wt("add"),set:wt("set"),delete:wt("delete"),clear:wt("clear"),forEach:Pi(!0,!1)},i={get(a){return Ai(this,a,!0,!0)},get size(){return Ri(this,!0)},has(a){return Mi.call(this,a,!0)},add:wt("add"),set:wt("set"),delete:wt("delete"),clear:wt("clear"),forEach:Pi(!0,!0)},n=["keys","values","entries",Symbol.iterator];return n.forEach(a=>{e[a]=Li(a,!1,!1),r[a]=Li(a,!0,!1),t[a]=Li(a,!1,!0),i[a]=Li(a,!0,!0)}),[e,r,t,i]}var[Wh,Vh,Hh,jh]=Uh();function Ia(e,t){var r=t?e?jh:Hh:e?Vh:Wh;return(i,n,a)=>n==="__v_isReactive"?!e:n==="__v_isReadonly"?e:n==="__v_raw"?i:Reflect.get(te(r,n)&&n in i?r:i,n,a)}var zh={get:Ia(!1,!1)},Yh={get:Ia(!1,!0)},qh={get:Ia(!0,!1)},Cl=new WeakMap,Il=new WeakMap,Ol=new WeakMap,Xh=new WeakMap;function Kh(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function Gh(e){return e.__v_skip||!Object.isExtensible(e)?0:Kh(Kn(e))}function Te(e){return e&&e.__v_isReadonly?e:Oa(e,!1,yl,zh,Cl)}function Jh(e){return Oa(e,!1,$h,Yh,Il)}function Al(e){return Oa(e,!0,Fh,qh,Ol)}function Oa(e,t,r,i,n){if(!ke(e)||e.__v_raw&&!(t&&e.__v_isReactive))return e;var a=n.get(e);if(a)return a;var s=Gh(e);if(s===0)return e;var o=new Proxy(e,s===2?i:r);return n.set(e,o),o}function rr(e){return Ml(e)?rr(e.__v_raw):!!(e&&e.__v_isReactive)}function Ml(e){return!!(e&&e.__v_isReadonly)}function Rl(e){return rr(e)||Ml(e)}function ge(e){var t=e&&e.__v_raw;return t?ge(t):e}function Ni(e){return bi(e,"__v_skip",!0),e}var Cr=e=>ke(e)?Te(e):e,Aa=e=>ke(e)?Al(e):e;function Pl(e){pl()&&(e=ge(e),e.dep||(e.dep=_a()),ml(e.dep))}function Ll(e,t){e=ge(e),e.dep&&Ea(e.dep)}function Ue(e){return Boolean(e&&e.__v_isRef===!0)}function $(e){return Nl(e,!1)}function Ma(e){return Nl(e,!0)}function Nl(e,t){return Ue(e)?e:new Zh(e,t)}class Zh{constructor(t,r){this._shallow=r,this.dep=void 0,this.__v_isRef=!0,this._rawValue=r?t:ge(t),this._value=r?t:Cr(t)}get value(){return Pl(this),this._value}set value(t){t=this._shallow?t:ge(t),br(t,this._rawValue)&&(this._rawValue=t,this._value=this._shallow?t:Cr(t),Ll(this))}}function Qh(e){return Ue(e)?e.value:e}var eg={get:(e,t,r)=>Qh(Reflect.get(e,t,r)),set:(e,t,r,i)=>{var n=e[t];return Ue(n)&&!Ue(r)?(n.value=r,!0):Reflect.set(e,t,r,i)}};function Dl(e){return rr(e)?e:new Proxy(e,eg)}class tg{constructor(t,r,i){this._setter=r,this.dep=void 0,this._dirty=!0,this.__v_isRef=!0,this.effect=new Sa(t,()=>{this._dirty||(this._dirty=!0,Ll(this))}),this.__v_isReadonly=i}get value(){var t=ge(this);return Pl(t),t._dirty&&(t._dirty=!1,t._value=t.effect.run()),t._value}set value(t){this._setter(t)}}function Q(e,t){var r,i,n=ae(e);n?(r=e,i=it):(r=e.get,i=e.set);var a=new tg(r,i,n||!i);return a}function rg(e,t){for(var r=e.vnode.props||be,i=arguments.length,n=new Array(i>2?i-2:0),a=2;ab.trim()):v&&(s=n.map(pd))}var m,g=r[m=Jn(t)]||r[m=Jn(mt(t))];!g&&o&&(g=r[m=Jn(Ve(t))]),g&&et(g,e,6,s);var _=r[m+"Once"];if(_){if(!e.emitted)e.emitted={};else if(e.emitted[m])return;e.emitted[m]=!0,et(_,e,6,s)}}function kl(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=t.emitsCache,n=i.get(e);if(n!==void 0)return n;var a=e.emits,s={},o=!1;if(!ae(e)){var l=u=>{var v=kl(u,t,!0);v&&(o=!0,ue(s,v))};!r&&t.mixins.length&&t.mixins.forEach(l),e.extends&&l(e.extends),e.mixins&&e.mixins.forEach(l)}return!a&&!o?(i.set(e,null),null):(oe(a)?a.forEach(u=>s[u]=null):ue(s,a),i.set(e,s),s)}function Ra(e,t){return!e||!gi(t)?!1:(t=t.slice(2).replace(/Once$/,""),te(e,t[0].toLowerCase()+t.slice(1))||te(e,Ve(t))||te(e,t))}var Qe=null,Bl=null;function Di(e){var t=Qe;return Qe=e,Bl=e&&e.type.__scopeId||null,t}function ig(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Qe;if(!t||e._n)return e;var r=function(){r._d&&au(-1);var i=Di(t),n=e(...arguments);return Di(i),r._d&&au(1),n};return r._n=!0,r._c=!0,r._d=!0,r}function qy(){}function Pa(e){var{type:t,vnode:r,proxy:i,withProxy:n,props:a,propsOptions:[s],slots:o,attrs:l,emit:u,render:v,renderCache:c,data:m,setupState:g,ctx:_,inheritAttrs:b}=e,w,p,h=Di(e);try{if(r.shapeFlag&4){var f=n||i;w=lt(v.call(f,f,c,a,g,m,_)),p=l}else{var d=t;w=lt(d.length>1?d(a,{attrs:l,slots:o,emit:u}):d(a,null)),p=t.props?l:ng(l)}}catch(C){Hi(C,e,1),w=O(Or)}var y=w;if(p&&b!==!1){var x=Object.keys(p),{shapeFlag:T}=y;x.length&&T&(1|6)&&(s&&x.some(qn)&&(p=ag(p,s)),y=Mr(y,p))}return r.dirs&&(y.dirs=y.dirs?y.dirs.concat(r.dirs):r.dirs),r.transition&&(y.transition=r.transition),w=y,Di(h),w}var ng=e=>{var t;for(var r in e)(r==="class"||r==="style"||gi(r))&&((t||(t={}))[r]=e[r]);return t},ag=(e,t)=>{var r={};for(var i in e)(!qn(i)||!(i.slice(9)in t))&&(r[i]=e[i]);return r};function sg(e,t,r){var{props:i,children:n,component:a}=e,{props:s,children:o,patchFlag:l}=t,u=a.emitsOptions;if(t.dirs||t.transition)return!0;if(r&&l>=0){if(l&1024)return!0;if(l&16)return i?Fl(i,s,u):!!s;if(l&8)for(var v=t.dynamicProps,c=0;ce.__isSuspense;function ug(e,t){t&&t.pendingBranch?oe(e)?t.effects.push(...e):t.effects.push(e):gu(e)}function Ne(e,t){if(De){var r=De.provides,i=De.parent&&De.parent.provides;i===r&&(r=De.provides=Object.create(i)),r[e]=t}}function pe(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=De||Qe;if(i){var n=i.parent==null?i.vnode.appContext&&i.vnode.appContext.provides:i.parent.provides;if(n&&e in n)return n[e];if(arguments.length>1)return r&&ae(t)?t.call(i.proxy):t}}function fg(e){return ae(e)?{setup:e,name:e.name}:e}var La=e=>!!e.type.__asyncLoader,$l=e=>e.type.__isKeepAlive;function Na(e,t){Ul(e,"a",t)}function cg(e,t){Ul(e,"da",t)}function Ul(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:De,i=e.__wdc||(e.__wdc=()=>{for(var a=r;a;){if(a.isDeactivated)return;a=a.parent}e()});if(ki(t,i,r),r)for(var n=r.parent;n&&n.parent;)$l(n.parent.vnode)&&vg(i,t,r,n),n=n.parent}function vg(e,t,r,i){var n=ki(t,e,i,!0);yt(()=>{Ao(i[t],n)},r)}function ki(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:De,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(r){var n=r[e]||(r[e]=[]),a=t.__weh||(t.__weh=function(){if(!r.isUnmounted){tr(),ir(r);for(var s=arguments.length,o=new Array(s),l=0;lfunction(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:De;return(!Vi||e==="sp")&&ki(e,t,r)},Wl=dt("bm"),Oe=dt("m"),dg=dt("bu"),hg=dt("u"),xe=dt("bum"),yt=dt("um"),gg=dt("sp"),pg=dt("rtg"),mg=dt("rtc");function _g(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:De;ki("ec",e,t)}var Da=!0;function bg(e){var t=jl(e),r=e.proxy,i=e.ctx;Da=!1,t.beforeCreate&&Vl(t.beforeCreate,e,"bc");var{data:n,computed:a,methods:s,watch:o,provide:l,inject:u,created:v,beforeMount:c,mounted:m,beforeUpdate:g,updated:_,activated:b,deactivated:w,beforeDestroy:p,beforeUnmount:h,destroyed:f,unmounted:d,render:y,renderTracked:x,renderTriggered:T,errorCaptured:C,serverPrefetch:A,expose:U,inheritAttrs:V,components:q,directives:he,filters:R}=t,k=null;if(u&&wg(u,i,k,e.appContext.config.unwrapInjectedRef),s)for(var ee in s){var ie=s[ee];ae(ie)&&(i[ee]=ie.bind(r))}if(n&&function(){var re=n.call(r,r);ke(re)&&(e.data=Te(re))}(),Da=!0,a){var z=function(re){var le=a[re],Ce=ae(le)?le.bind(r,r):ae(le.get)?le.get.bind(r,r):it,Ie=!ae(le)&&ae(le.set)?le.set.bind(r):it,Ge=Q({get:Ce,set:Ie});Object.defineProperty(i,re,{enumerable:!0,configurable:!0,get:()=>Ge.value,set:Mt=>Ge.value=Mt})};for(var Z in a)z(Z)}if(o)for(var ne in o)Hl(o[ne],i,r,ne);if(l){var we=ae(l)?l.call(r):l;Reflect.ownKeys(we).forEach(re=>{Ne(re,we[re])})}v&&Vl(v,e,"c");function se(re,le){oe(le)?le.forEach(Ce=>re(Ce.bind(r))):le&&re(le.bind(r))}if(se(Wl,c),se(Oe,m),se(dg,g),se(hg,_),se(Na,b),se(cg,w),se(_g,C),se(mg,x),se(pg,T),se(xe,h),se(yt,d),se(gg,A),oe(U))if(U.length){var G=e.exposed||(e.exposed={});U.forEach(re=>{Object.defineProperty(G,re,{get:()=>r[re],set:le=>r[re]=le})})}else e.exposed||(e.exposed={});y&&e.render===it&&(e.render=y),V!=null&&(e.inheritAttrs=V),q&&(e.components=q),he&&(e.directives=he)}function wg(e,t){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;oe(e)&&(e=ka(e));var i=function(a){var s=e[a],o=void 0;ke(s)?"default"in s?o=pe(s.from||a,s.default,!0):o=pe(s.from||a):o=pe(s),Ue(o)&&r?Object.defineProperty(t,a,{enumerable:!0,configurable:!0,get:()=>o.value,set:l=>o.value=l}):t[a]=o};for(var n in e)i(n)}function Vl(e,t,r){et(oe(e)?e.map(i=>i.bind(t.proxy)):e.bind(t.proxy),t,r)}function Hl(e,t,r,i){var n=i.includes(".")?bu(r,i):()=>r[i];if(ye(e)){var a=t[e];ae(a)&&W(n,a)}else if(ae(e))W(n,e.bind(r));else if(ke(e))if(oe(e))e.forEach(o=>Hl(o,t,r,i));else{var s=ae(e.handler)?e.handler.bind(r):t[e.handler];ae(s)&&W(n,s,e)}}function jl(e){var t=e.type,{mixins:r,extends:i}=t,{mixins:n,optionsCache:a,config:{optionMergeStrategies:s}}=e.appContext,o=a.get(t),l;return o?l=o:!n.length&&!r&&!i?l=t:(l={},n.length&&n.forEach(u=>Bi(l,u,s,!0)),Bi(l,t,s)),a.set(t,l),l}function Bi(e,t,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,{mixins:n,extends:a}=t;a&&Bi(e,a,r,!0),n&&n.forEach(l=>Bi(e,l,r,!0));for(var s in t)if(!(i&&s==="expose")){var o=yg[s]||r&&r[s];e[s]=o?o(e[s],t[s]):t[s]}return e}var yg={data:zl,props:Bt,emits:Bt,methods:Bt,computed:Bt,beforeCreate:Fe,created:Fe,beforeMount:Fe,mounted:Fe,beforeUpdate:Fe,updated:Fe,beforeDestroy:Fe,beforeUnmount:Fe,destroyed:Fe,unmounted:Fe,activated:Fe,deactivated:Fe,errorCaptured:Fe,serverPrefetch:Fe,components:Bt,directives:Bt,watch:xg,provide:zl,inject:Sg};function zl(e,t){return t?e?function(){return ue(ae(e)?e.call(this,this):e,ae(t)?t.call(this,this):t)}:t:e}function Sg(e,t){return Bt(ka(e),ka(t))}function ka(e){if(oe(e)){for(var t={},r=0;r3&&arguments[3]!==void 0?arguments[3]:!1,n={},a={};bi(a,$i,1),e.propsDefaults=Object.create(null),Yl(e,t,n,a);for(var s in e.propsOptions[0])s in n||(n[s]=void 0);r?e.props=i?n:Jh(n):e.type.props?e.props=n:e.props=a,e.attrs=a}function Tg(e,t,r,i){var{props:n,attrs:a,vnode:{patchFlag:s}}=e,o=ge(n),[l]=e.propsOptions,u=!1;if((i||s>0)&&!(s&16)){if(s&8)for(var v=e.vnode.dynamicProps,c=0;c2&&arguments[2]!==void 0?arguments[2]:!1,i=t.propsCache,n=i.get(e);if(n)return n;var a=e.props,s={},o=[],l=!1;if(!ae(e)){var u=f=>{l=!0;var[d,y]=ql(f,t,!0);ue(s,d),y&&o.push(...y)};!r&&t.mixins.length&&t.mixins.forEach(u),e.extends&&u(e.extends),e.mixins&&e.mixins.forEach(u)}if(!a&&!l)return i.set(e,pr),pr;if(oe(a))for(var v=0;v-1,b[1]=p<0||w-1||te(b,"default"))&&o.push(g)}}}var h=[s,o];return i.set(e,h),h}function Xl(e){return e[0]!=="$"}function Kl(e){var t=e&&e.toString().match(/^\s*function (\w+)/);return t?t[1]:e===null?"null":""}function Gl(e,t){return Kl(e)===Kl(t)}function Jl(e,t){return oe(t)?t.findIndex(r=>Gl(r,e)):ae(t)&&Gl(t,e)?0:-1}var Zl=e=>e[0]==="_"||e==="$stable",Fa=e=>oe(e)?e.map(lt):[lt(e)],Cg=(e,t,r)=>{var i=ig(function(){return Fa(t(...arguments))},r);return i._c=!1,i},Ql=(e,t,r)=>{var i=e._ctx;for(var n in e)if(!Zl(n)){var a=e[n];ae(a)?t[n]=Cg(n,a,i):a!=null&&function(){var s=Fa(a);t[n]=()=>s}()}},eu=(e,t)=>{var r=Fa(t);e.slots.default=()=>r},Ig=(e,t)=>{if(e.vnode.shapeFlag&32){var r=t._;r?(e.slots=ge(t),bi(t,"_",r)):Ql(t,e.slots={})}else e.slots={},t&&eu(e,t);bi(e.slots,$i,1)},Og=(e,t,r)=>{var{vnode:i,slots:n}=e,a=!0,s=be;if(i.shapeFlag&32){var o=t._;o?r&&o===1?a=!1:(ue(n,t),!r&&o===1&&delete n._):(a=!t.$stable,Ql(t,n)),s=t}else t&&(eu(e,t),s={default:1});if(a)for(var l in n)!Zl(l)&&!(l in s)&&delete n[l]};function Ir(e,t){var r=Qe;if(r===null)return e;for(var i=r.proxy,n=e.dirs||(e.dirs=[]),a=0;a1&&arguments[1]!==void 0?arguments[1]:null;n!=null&&!ke(n)&&(n=null);var a=tu(),s=new Set,o=!1,l=a.app={_uid:Ag++,_component:i,_props:n,_container:null,_context:a,_instance:null,version:rp,get config(){return a.config},set config(u){},use(u){for(var v=arguments.length,c=new Array(v>1?v-1:0),m=1;m3&&arguments[3]!==void 0?arguments[3]:null,L=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null,F=arguments.length>5&&arguments[5]!==void 0?arguments[5]:null,H=arguments.length>6&&arguments[6]!==void 0?arguments[6]:!1,B=arguments.length>7&&arguments[7]!==void 0?arguments[7]:null,D=arguments.length>8&&arguments[8]!==void 0?arguments[8]:!!E.dynamicChildren;if(S!==E){S&&!Ar(S,E)&&(P=Ge(S),G(S,L,F,!0),S=null),E.patchFlag===-2&&(D=!1,E.dynamicChildren=null);var{type:N,ref:J,shapeFlag:K}=E;switch(N){case Ua:p(S,E,M,P);break;case Or:h(S,E,M,P);break;case Wa:S==null&&f(E,M,P,H);break;case ot:he(S,E,M,P,L,F,H,B,D);break;default:K&1?x(S,E,M,P,L,F,H,B,D):K&6?R(S,E,M,P,L,F,H,B,D):(K&64||K&128)&&N.process(S,E,M,P,L,F,H,B,D,Me)}J!=null&&L&&$a(J,S&&S.ref,F,E||S,!E)}},p=(S,E,M,P)=>{if(S==null)i(E.el=o(E.children),M,P);else{var L=E.el=S.el;E.children!==S.children&&u(L,E.children)}},h=(S,E,M,P)=>{S==null?i(E.el=l(E.children||""),M,P):E.el=S.el},f=(S,E,M,P)=>{[S.el,S.anchor]=b(S.children,E,M,P)},d=(S,E,M)=>{for(var{el:P,anchor:L}=S,F;P&&P!==L;)F=m(P),i(P,E,M),P=F;i(L,E,M)},y=S=>{for(var{el:E,anchor:M}=S,P;E&&E!==M;)P=m(E),n(E),E=P;n(M)},x=(S,E,M,P,L,F,H,B,D)=>{H=H||E.type==="svg",S==null?T(E,M,P,L,F,H,B,D):U(S,E,L,F,H,B,D)},T=(S,E,M,P,L,F,H,B)=>{var D,N,{type:J,props:K,shapeFlag:X,transition:ce,patchFlag:Pe,dirs:Se}=S;if(S.el&&_!==void 0&&Pe===-1)D=S.el=_(S.el);else{if(D=S.el=s(S.type,F,K&&K.is,K),X&8?v(D,S.children):X&16&&A(S.children,D,null,P,L,F&&J!=="foreignObject",H,B),Se&&Ft(S,null,P,"created"),K){for(var I in K)I!=="value"&&!pi(I)&&a(D,I,null,K[I],F,S.children,P,L,Ie);"value"in K&&a(D,"value",null,K.value),(N=K.onVnodeBeforeMount)&&st(N,P,S)}C(D,S,S.scopeId,H,P)}Object.defineProperty(D,"__vueParentComponent",{value:P,enumerable:!1}),Se&&Ft(S,null,P,"beforeMount");var j=(!L||L&&!L.pendingBranch)&&ce&&!ce.persisted;j&&ce.beforeEnter(D),i(D,E,M),((N=K&&K.onVnodeMounted)||j||Se)&&$e(()=>{N&&st(N,P,S),j&&ce.enter(D),Se&&Ft(S,null,P,"mounted")},L)},C=(S,E,M,P,L)=>{if(M&&g(S,M),P)for(var F=0;F8&&arguments[8]!==void 0?arguments[8]:0,N=D;N{var B=E.el=S.el,{patchFlag:D,dynamicChildren:N,dirs:J}=E;D|=S.patchFlag&16;var K=S.props||be,X=E.props||be,ce;(ce=X.onVnodeBeforeUpdate)&&st(ce,M,E,S),J&&Ft(E,S,M,"beforeUpdate");var Pe=L&&E.type!=="foreignObject";if(N?V(S.dynamicChildren,N,B,M,P,Pe,F):H||Z(S,E,B,null,M,P,Pe,F,!1),D>0){if(D&16)q(B,E,K,X,M,P,L);else if(D&2&&K.class!==X.class&&a(B,"class",null,X.class,L),D&4&&a(B,"style",K.style,X.style,L),D&8)for(var Se=E.dynamicProps,I=0;I{ce&&st(ce,M,E,S),J&&Ft(E,S,M,"updated")},P)},V=(S,E,M,P,L,F,H)=>{for(var B=0;B{if(M!==P){for(var B in P)if(!pi(B)){var D=P[B],N=M[B];D!==N&&B!=="value"&&a(S,B,N,D,H,E.children,L,F,Ie)}if(M!==be)for(var J in M)!pi(J)&&!(J in P)&&a(S,J,M[J],null,H,E.children,L,F,Ie);"value"in P&&a(S,"value",M.value,P.value)}},he=(S,E,M,P,L,F,H,B,D)=>{var N=E.el=S?S.el:o(""),J=E.anchor=S?S.anchor:o(""),{patchFlag:K,dynamicChildren:X,slotScopeIds:ce}=E;ce&&(B=B?B.concat(ce):ce),S==null?(i(N,M,P),i(J,M,P),A(E.children,M,J,L,F,H,B,D)):K>0&&K&64&&X&&S.dynamicChildren?(V(S.dynamicChildren,X,M,L,F,H,B),(E.key!=null||L&&E===L.subTree)&&ru(S,E,!0)):Z(S,E,M,J,L,F,H,B,D)},R=(S,E,M,P,L,F,H,B,D)=>{E.slotScopeIds=B,S==null?E.shapeFlag&512?L.ctx.activate(E,M,P,H,D):k(E,M,P,L,F,H,D):ee(S,E,D)},k=(S,E,M,P,L,F,H)=>{var B=S.component=Hg(S,P,L);if($l(S)&&(B.ctx.renderer=Me),jg(B),B.asyncDep){if(L&&L.registerDep(B,ie),!S.el){var D=B.subTree=O(Or);h(null,D,E,M)}return}ie(B,S,E,M,L,F,H)},ee=(S,E,M)=>{var P=E.component=S.component;if(sg(S,E,M))if(P.asyncDep&&!P.asyncResolved){z(P,E,M);return}else P.next=E,Jg(P.update),P.update();else E.component=S.component,E.el=S.el,P.vnode=E},ie=(S,E,M,P,L,F,H)=>{var B=()=>{if(S.isMounted){var{next:fe,bu:Le,u:We,parent:Re,vnode:rt}=S,Rt=fe,ct;D.allowRecurse=!1,fe?(fe.el=rt.el,z(S,fe,H)):fe=rt,Le&&Zn(Le),(ct=fe.props&&fe.props.onVnodeBeforeUpdate)&&st(ct,Re,fe,rt),D.allowRecurse=!0;var Xt=Pa(S),gt=S.subTree;S.subTree=Xt,w(gt,Xt,c(gt.el),Ge(gt),S,L,F),fe.el=Xt.el,Rt===null&&og(S,Xt.el),We&&$e(We,L),(ct=fe.props&&fe.props.onVnodeUpdated)&&$e(()=>st(ct,Re,fe,rt),L)}else{var J,{el:K,props:X}=E,{bm:ce,m:Pe,parent:Se}=S,I=La(E);if(D.allowRecurse=!1,ce&&Zn(ce),!I&&(J=X&&X.onVnodeBeforeMount)&&st(J,Se,E),D.allowRecurse=!0,K&&Jr){var j=()=>{S.subTree=Pa(S),Jr(K,S.subTree,S,L,null)};I?E.type.__asyncLoader().then(()=>!S.isUnmounted&&j()):j()}else{var Y=S.subTree=Pa(S);w(null,Y,M,P,S,L,F),E.el=Y.el}if(Pe&&$e(Pe,L),!I&&(J=X&&X.onVnodeMounted)){var ve=E;$e(()=>st(J,Se,ve),L)}E.shapeFlag&256&&S.a&&$e(S.a,L),S.isMounted=!0,E=M=P=null}},D=new Sa(B,()=>vu(S.update),S.scope),N=S.update=D.run.bind(D);N.id=S.uid,D.allowRecurse=N.allowRecurse=!0,N()},z=(S,E,M)=>{E.component=S;var P=S.vnode.props;S.vnode=E,S.next=null,Tg(S,E.props,P,M),Og(S,E.children,M),tr(),Xa(void 0,S.update),kt()},Z=function(S,E,M,P,L,F,H,B){var D=arguments.length>8&&arguments[8]!==void 0?arguments[8]:!1,N=S&&S.children,J=S?S.shapeFlag:0,K=E.children,{patchFlag:X,shapeFlag:ce}=E;if(X>0){if(X&128){we(N,K,M,P,L,F,H,B,D);return}else if(X&256){ne(N,K,M,P,L,F,H,B,D);return}}ce&8?(J&16&&Ie(N,L,F),K!==N&&v(M,K)):J&16?ce&16?we(N,K,M,P,L,F,H,B,D):Ie(N,L,F,!0):(J&8&&v(M,""),ce&16&&A(K,M,P,L,F,H,B,D))},ne=(S,E,M,P,L,F,H,B,D)=>{S=S||pr,E=E||pr;var N=S.length,J=E.length,K=Math.min(N,J),X;for(X=0;XJ?Ie(S,L,F,!0,!1,K):A(E,M,P,L,F,H,B,D,K)},we=(S,E,M,P,L,F,H,B,D)=>{for(var N=0,J=E.length,K=S.length-1,X=J-1;N<=K&&N<=X;){var ce=S[N],Pe=E[N]=D?St(E[N]):lt(E[N]);if(Ar(ce,Pe))w(ce,Pe,M,null,L,F,H,B,D);else break;N++}for(;N<=K&&N<=X;){var Se=S[K],I=E[X]=D?St(E[X]):lt(E[X]);if(Ar(Se,I))w(Se,I,M,null,L,F,H,B,D);else break;K--,X--}if(N>K){if(N<=X)for(var j=X+1,Y=jX)for(;N<=K;)G(S[N],L,F,!0),N++;else{var ve=N,fe=N,Le=new Map;for(N=fe;N<=X;N++){var We=E[N]=D?St(E[N]):lt(E[N]);We.key!=null&&Le.set(We.key,N)}var Re,rt=0,Rt=X-fe+1,ct=!1,Xt=0,gt=new Array(Rt);for(N=0;N=Rt){G(dr,L,F,!0);continue}var Kt=void 0;if(dr.key!=null)Kt=Le.get(dr.key);else for(Re=fe;Re<=X;Re++)if(gt[Re-fe]===0&&Ar(dr,E[Re])){Kt=Re;break}Kt===void 0?G(dr,L,F,!0):(gt[Kt-fe]=N+1,Kt>=Xt?Xt=Kt:ct=!0,w(dr,E[Kt],M,null,L,F,H,B,D),rt++)}var Tc=ct?Lg(gt):pr;for(Re=Tc.length-1,N=Rt-1;N>=0;N--){var Us=fe+N,Cc=E[Us],Ic=Us+14&&arguments[4]!==void 0?arguments[4]:null,{el:F,type:H,transition:B,children:D,shapeFlag:N}=S;if(N&6){se(S.component.subTree,E,M,P);return}if(N&128){S.suspense.move(E,M,P);return}if(N&64){H.move(S,E,M,Me);return}if(H===ot){i(F,E,M);for(var J=0;JB.enter(F),L);else{var{leave:X,delayLeave:ce,afterLeave:Pe}=B,Se=()=>i(F,E,M),I=()=>{X(F,()=>{Se(),Pe&&Pe()})};ce?ce(F,Se,I):I()}else i(F,E,M)},G=function(S,E,M){var P=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,L=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,{type:F,props:H,ref:B,children:D,dynamicChildren:N,shapeFlag:J,patchFlag:K,dirs:X}=S;if(B!=null&&$a(B,null,M,S,!0),J&256){E.ctx.deactivate(S);return}var ce=J&1&&X,Pe=!La(S),Se;if(Pe&&(Se=H&&H.onVnodeBeforeUnmount)&&st(Se,E,S),J&6)Ce(S.component,M,P);else{if(J&128){S.suspense.unmount(M,P);return}ce&&Ft(S,null,E,"beforeUnmount"),J&64?S.type.remove(S,E,M,L,Me,P):N&&(F!==ot||K>0&&K&64)?Ie(N,E,M,!1,!0):(F===ot&&K&(128|256)||!L&&J&16)&&Ie(D,E,M),P&&re(S)}(Pe&&(Se=H&&H.onVnodeUnmounted)||ce)&&$e(()=>{Se&&st(Se,E,S),ce&&Ft(S,null,E,"unmounted")},M)},re=S=>{var{type:E,el:M,anchor:P,transition:L}=S;if(E===ot){le(M,P);return}if(E===Wa){y(S);return}var F=()=>{n(M),L&&!L.persisted&&L.afterLeave&&L.afterLeave()};if(S.shapeFlag&1&&L&&!L.persisted){var{leave:H,delayLeave:B}=L,D=()=>H(M,F);B?B(S.el,F,D):D()}else F()},le=(S,E)=>{for(var M;S!==E;)M=m(S),n(S),S=M;n(E)},Ce=(S,E,M)=>{var{bum:P,scope:L,update:F,subTree:H,um:B}=S;P&&Zn(P),L.stop(),F&&(F.active=!1,G(H,S,E,M)),B&&$e(B,E),$e(()=>{S.isUnmounted=!0},E),E&&E.pendingBranch&&!E.isUnmounted&&S.asyncDep&&!S.asyncResolved&&S.suspenseId===E.pendingId&&(E.deps--,E.deps===0&&E.resolve())},Ie=function(S,E,M){for(var P=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,L=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,F=arguments.length>5&&arguments[5]!==void 0?arguments[5]:0,H=F;HS.shapeFlag&6?Ge(S.component.subTree):S.shapeFlag&128?S.suspense.next():m(S.anchor||S.el),Mt=(S,E,M)=>{if(S==null)E._vnode&&G(E._vnode,null,null,!0);else{var P=E.__vueParent;w(E._vnode||null,S,E,null,P,null,M)}E._vnode=S},Me={p:w,um:G,m:se,r:re,mt:k,mc:A,pc:Z,pbc:V,n:Ge,o:e},Gr,Jr;return t&&([Gr,Jr]=t(Me)),{render:Mt,hydrate:Gr,createApp:Mg(Mt,Gr)}}function $a(e,t,r,i){var n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;if(oe(e)){e.forEach((_,b)=>$a(_,t&&(oe(t)?t[b]:t),r,i,n));return}if(!(La(i)&&!n)){var a=i.shapeFlag&4?ja(i.component)||i.component.proxy:i.el,s=n?null:a,{i:o,r:l}=e,u=t&&t.r,v=o.refs===be?o.refs={}:o.refs,c=o.setupState;if(u!=null&&u!==l&&(ye(u)?(v[u]=null,te(c,u)&&(c[u]=null)):Ue(u)&&(u.value=null)),ye(l)){var m=()=>{v[l]=s,te(c,l)&&(c[l]=s)};s?(m.id=-1,$e(m,r)):m()}else if(Ue(l)){var g=()=>{l.value=s};s?(g.id=-1,$e(g,r)):g()}else ae(l)&&Et(l,o,12,[s,v])}}function st(e,t,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;et(e,t,7,[r,i])}function ru(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=e.children,n=t.children;if(oe(i)&&oe(n))for(var a=0;a>1,e[r[o]]0&&(t[i]=r[a-1]),r[a]=i)}}for(a=r.length,s=r[a-1];a-- >0;)r[a]=s,s=t[s];return r}var Ng=e=>e.__isTeleport,Dg=Symbol(),ot=Symbol(void 0),Ua=Symbol(void 0),Or=Symbol(void 0),Wa=Symbol(void 0),iu=null,nu=1;function au(e){nu+=e}function Fi(e){return e?e.__v_isVNode===!0:!1}function Ar(e,t){return e.type===t.type&&e.key===t.key}var $i="__vInternal",su=e=>{var{key:t}=e;return t!=null?t:null},Ui=e=>{var{ref:t}=e;return t!=null?ye(t)||Ue(t)||ae(t)?{i:Qe,r:t}:t:null};function kg(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null,a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:e===ot?0:1,s=arguments.length>6&&arguments[6]!==void 0?arguments[6]:!1,o=arguments.length>7&&arguments[7]!==void 0?arguments[7]:!1,l={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&su(t),ref:t&&Ui(t),scopeId:Bl,slotScopeIds:null,children:r,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetAnchor:null,staticCount:0,shapeFlag:a,patchFlag:i,dynamicProps:n,dynamicChildren:null,appContext:null};return o?(Va(l,r),a&128&&e.normalize(l)):r&&(l.shapeFlag|=ye(r)?8:16),nu>0&&!s&&iu&&(l.patchFlag>0||a&6)&&l.patchFlag!==32&&iu.push(l),l}var O=Bg;function Bg(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null,a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!1;if((!e||e===Dg)&&(e=Or),Fi(e)){var s=Mr(e,t,!0);return r&&Va(s,r),s}if(Xg(e)&&(e=e.__vccOpts),t){t=Fg(t);var{class:o,style:l}=t;o&&!ye(o)&&(t.class=Yn(o)),ke(l)&&(Rl(l)&&!oe(l)&&(l=ue({},l)),t.style=zn(l))}var u=ye(e)?1:lg(e)?128:Ng(e)?64:ke(e)?4:ae(e)?2:0;return kg(e,t,r,i,n,u,a,!0)}function Fg(e){return e?Rl(e)||$i in e?ue({},e):e:null}function Mr(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,{props:i,ref:n,patchFlag:a,children:s}=e,o=t?ze(i||{},t):i,l={__v_isVNode:!0,__v_skip:!0,type:e.type,props:o,key:o&&su(o),ref:t&&t.ref?r&&n?oe(n)?n.concat(Ui(t)):[n,Ui(t)]:Ui(t):n,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:s,target:e.target,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==ot?a===-1?16:a|16:a,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:e.transition,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&Mr(e.ssContent),ssFallback:e.ssFallback&&Mr(e.ssFallback),el:e.el,anchor:e.anchor};return l}function $g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:" ",t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return O(Ua,null,e,t)}function lt(e){return e==null||typeof e=="boolean"?O(Or):oe(e)?O(ot,null,e.slice()):typeof e=="object"?St(e):O(Ua,null,String(e))}function St(e){return e.el===null||e.memo?e:Mr(e)}function Va(e,t){var r=0,{shapeFlag:i}=e;if(t==null)t=null;else if(oe(t))r=16;else if(typeof t=="object")if(i&(1|64)){var n=t.default;n&&(n._c&&(n._d=!1),Va(e,n()),n._c&&(n._d=!0));return}else{r=32;var a=t._;!a&&!($i in t)?t._ctx=Qe:a===3&&Qe&&(Qe.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else ae(t)?(t={default:t,_ctx:Qe},r=32):(t=String(t),i&64?(r=16,t=[$g(t)]):r=8);e.children=t,e.shapeFlag|=r}function ze(){for(var e={},t=0;te?ou(e)?ja(e)||e.proxy:Ha(e.parent):null,Wi=ue(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>Ha(e.parent),$root:e=>Ha(e.root),$emit:e=>e.emit,$options:e=>jl(e),$forceUpdate:e=>()=>vu(e.update),$nextTick:e=>sr.bind(e.proxy),$watch:e=>ep.bind(e)}),Ug={get(e,t){var{_:r}=e,{ctx:i,setupState:n,data:a,props:s,accessCache:o,type:l,appContext:u}=r,v;if(t[0]!=="$"){var c=o[t];if(c!==void 0)switch(c){case 0:return n[t];case 1:return a[t];case 3:return i[t];case 2:return s[t]}else{if(n!==be&&te(n,t))return o[t]=0,n[t];if(a!==be&&te(a,t))return o[t]=1,a[t];if((v=r.propsOptions[0])&&te(v,t))return o[t]=2,s[t];if(i!==be&&te(i,t))return o[t]=3,i[t];Da&&(o[t]=4)}}var m=Wi[t],g,_;if(m)return t==="$attrs"&&je(r,"get",t),m(r);if((g=l.__cssModules)&&(g=g[t]))return g;if(i!==be&&te(i,t))return o[t]=3,i[t];if(_=u.config.globalProperties,te(_,t))return _[t]},set(e,t,r){var{_:i}=e,{data:n,setupState:a,ctx:s}=i;if(a!==be&&te(a,t))a[t]=r;else if(n!==be&&te(n,t))n[t]=r;else if(te(i.props,t))return!1;return t[0]==="$"&&t.slice(1)in i?!1:(s[t]=r,!0)},has(e,t){var{_:{data:r,setupState:i,accessCache:n,ctx:a,appContext:s,propsOptions:o}}=e,l;return n[t]!==void 0||r!==be&&te(r,t)||i!==be&&te(i,t)||(l=o[0])&&te(l,t)||te(a,t)||te(Wi,t)||te(s.config.globalProperties,t)}},Wg=tu(),Vg=0;function Hg(e,t,r){var i=e.type,n=(t?t.appContext:e.appContext)||Wg,a={uid:Vg++,vnode:e,type:i,parent:t,appContext:n,root:null,next:null,subTree:null,update:null,scope:new xh(!0),render:null,proxy:null,exposed:null,exposeProxy:null,withProxy:null,provides:t?t.provides:Object.create(n.provides),accessCache:null,renderCache:[],components:null,directives:null,propsOptions:ql(i,n),emitsOptions:kl(i,n),emit:null,emitted:null,propsDefaults:be,inheritAttrs:i.inheritAttrs,ctx:be,data:be,props:be,attrs:be,slots:be,refs:be,setupState:be,setupContext:null,suspense:r,suspenseId:r?r.pendingId:0,asyncDep:null,asyncResolved:!1,isMounted:!1,isUnmounted:!1,isDeactivated:!1,bc:null,c:null,bm:null,m:null,bu:null,u:null,um:null,bum:null,da:null,a:null,rtg:null,rtc:null,ec:null,sp:null};return a.ctx={_:a},a.root=t?t.root:a,a.emit=rg.bind(null,a),e.ce&&e.ce(a),a}var De=null,xt=()=>De||Qe,ir=e=>{De=e,e.scope.on()},$t=()=>{De&&De.scope.off(),De=null};function ou(e){return e.vnode.shapeFlag&4}var Vi=!1;function jg(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;Vi=t;var{props:r,children:i}=e.vnode,n=ou(e);Eg(e,r,n,t),Ig(e,i);var a=n?zg(e,t):void 0;return Vi=!1,a}function zg(e,t){var r=e.type;e.accessCache=Object.create(null),e.proxy=Ni(new Proxy(e.ctx,Ug));var{setup:i}=r;if(i){var n=e.setupContext=i.length>1?qg(e):null;ir(e),tr();var a=Et(i,e,0,[e.props,n]);if(kt(),$t(),Mo(a)){if(a.then($t,$t),t)return a.then(s=>{lu(e,s,t)}).catch(s=>{Hi(s,e,0)});e.asyncDep=a}else lu(e,a,t)}else fu(e,t)}function lu(e,t,r){ae(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:ke(t)&&(e.setupState=Dl(t)),fu(e,r)}var uu;function fu(e,t,r){var i=e.type;if(!e.render){if(!t&&uu&&!i.render){var n=i.template;if(n){var{isCustomElement:a,compilerOptions:s}=e.appContext.config,{delimiters:o,compilerOptions:l}=i,u=ue(ue({isCustomElement:a,delimiters:o},s),l);i.render=uu(n,u)}}e.render=i.render||it}ir(e),tr(),bg(e),kt(),$t()}function Yg(e){return new Proxy(e.attrs,{get(t,r){return je(e,"get","$attrs"),t[r]}})}function qg(e){var t=i=>{e.exposed=i||{}},r;return{get attrs(){return r||(r=Yg(e))},slots:e.slots,emit:e.emit,expose:t}}function ja(e){if(e.exposed)return e.exposeProxy||(e.exposeProxy=new Proxy(Dl(Ni(e.exposed)),{get(t,r){if(r in t)return t[r];if(r in Wi)return Wi[r](e)}}))}function Xg(e){return ae(e)&&"__vccOpts"in e}function Et(e,t,r,i){var n;try{n=i?e(...i):e()}catch(a){Hi(a,t,r)}return n}function et(e,t,r,i){if(ae(e)){var n=Et(e,t,r,i);return n&&Mo(n)&&n.catch(o=>{Hi(o,t,r)}),n}for(var a=[],s=0;s>>1,n=Nr(Ye[i]);nht&&Ye.splice(t,1)}function hu(e,t,r,i){oe(e)?r.push(...e):(!t||!t.includes(e,e.allowRecurse?i+1:i))&&r.push(e),du()}function Zg(e){hu(e,Pr,Rr,nr)}function gu(e){hu(e,Tt,Lr,ar)}function Xa(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(Rr.length){for(qa=t,Pr=[...new Set(Rr)],Rr.length=0,nr=0;nrNr(r)-Nr(i)),ar=0;are.id==null?1/0:e.id;function mu(e){za=!1,ji=!0,Xa(e),Ye.sort((i,n)=>Nr(i)-Nr(n));var t=it;try{for(ht=0;ht2&&arguments[2]!==void 0?arguments[2]:be,o=De,l,u=!1,v=!1;if(Ue(e)?(l=()=>e.value,u=!!e._shallow):rr(e)?(l=()=>e,i=!0):oe(e)?(v=!0,u=e.some(rr),l=()=>e.map(h=>{if(Ue(h))return h.value;if(rr(h))return Ut(h);if(ae(h))return Et(h,o,2)})):ae(e)?t?l=()=>Et(e,o,2):l=()=>{if(!(o&&o.isUnmounted))return m&&m(),et(e,o,3,[g])}:l=it,t&&i){var c=l;l=()=>Ut(c())}var m,g=h=>{m=p.onStop=()=>{Et(h,o,4)}};if(Vi)return g=it,t?r&&et(t,o,3,[l(),v?[]:void 0,g]):l(),it;var _=v?[]:_u,b=()=>{if(!!p.active)if(t){var h=p.run();(i||u||(v?h.some((f,d)=>br(f,_[d])):br(h,_)))&&(m&&m(),et(t,o,3,[h,_===_u?void 0:_,g]),_=h)}else p.run()};b.allowRecurse=!!t;var w;n==="sync"?w=b:n==="post"?w=()=>$e(b,o&&o.suspense):w=()=>{!o||o.isMounted?Zg(b):b()};var p=new Sa(l,w);return t?r?b():_=p.run():n==="post"?$e(p.run.bind(p),o&&o.suspense):p.run(),()=>{p.stop(),o&&o.scope&&Ao(o.scope.effects,p)}}function ep(e,t,r){var i=this.proxy,n=ye(e)?e.includes(".")?bu(i,e):()=>i[e]:e.bind(i,i),a;ae(t)?a=t:(a=t.handler,r=t);var s=De;ir(this);var o=Ka(n,a.bind(i),r);return s?ir(s):$t(),o}function bu(e,t){var r=t.split(".");return()=>{for(var i=e,n=0;n{Ut(n,t)});else if(Je(e))for(var i in e)Ut(e[i],t);return e}function tp(e,t,r){var i=arguments.length;return i===2?ke(t)&&!oe(t)?Fi(t)?O(e,null,[t]):O(e,t):O(e,null,t):(i>3?r=Array.prototype.slice.call(arguments,2):i===3&&Fi(r)&&(r=[r]),O(e,t,r))}var rp="3.2.22",ip="http://www.w3.org/2000/svg",or=typeof document!="undefined"?document:null,wu=new Map,np={insert:(e,t,r)=>{t.insertBefore(e,r||null)},remove:e=>{var t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,r,i)=>{var n=t?or.createElementNS(ip,e):or.createElement(e,r?{is:r}:void 0);return e==="select"&&i&&i.multiple!=null&&n.setAttribute("multiple",i.multiple),n},createText:e=>or.createTextNode(e),createComment:e=>or.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>or.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},cloneNode(e){var t=e.cloneNode(!0);return"_value"in e&&(t._value=e._value),t},insertStaticContent(e,t,r,i){var n=r?r.previousSibling:t.lastChild,a=wu.get(e);if(!a){var s=or.createElement("template");if(s.innerHTML=i?"".concat(e,""):e,a=s.content,i){for(var o=a.firstChild;o.firstChild;)a.appendChild(o.firstChild);a.removeChild(o)}wu.set(e,a)}return t.insertBefore(a.cloneNode(!0),r),[n?n.nextSibling:t.firstChild,r?r.previousSibling:t.lastChild]}};function ap(e,t,r){var i=e._vtc;i&&(t=(t?[t,...i]:[...i]).join(" ")),t==null?e.removeAttribute("class"):r?e.setAttribute("class",t):e.className=t}function sp(e,t,r){var i=e.style,n=ye(r);if(r&&!n){for(var a in r)Ga(i,a,r[a]);if(t&&!ye(t))for(var s in t)r[s]==null&&Ga(i,s,"")}else{var o=i.display;n?t!==r&&(i.cssText=r):t&&e.removeAttribute("style"),"_vod"in e&&(i.display=o)}}var yu=/\s*!important$/;function Ga(e,t,r){if(oe(r))r.forEach(n=>Ga(e,t,n));else if(r=up(r),t.startsWith("--"))e.setProperty(t,r);else{var i=op(e,t);yu.test(r)?e.setProperty(Ve(i),r.replace(yu,""),"important"):e[i]=r}}var Su=["Webkit","Moz","ms"],Ja={};function op(e,t){var r=Ja[t];if(r)return r;var i=mt(t);if(i!=="filter"&&i in e)return Ja[t]=i;i=_i(i);for(var n=0;ntypeof rpx2px!="function"?e:ye(e)?e.replace(lp,(t,r)=>rpx2px(r)+"px"):e,xu="http://www.w3.org/1999/xlink";function fp(e,t,r,i,n){if(i&&t.startsWith("xlink:"))r==null?e.removeAttributeNS(xu,t.slice(6,t.length)):e.setAttributeNS(xu,t,r);else{var a=nd(t);r==null||a&&!Io(r)?e.removeAttribute(t):e.setAttribute(t,a?"":r)}}function cp(e,t,r,i,n,a,s){if(t==="innerHTML"||t==="textContent"){i&&s(i,n,a),e[t]=r==null?"":r;return}if(t==="value"&&e.tagName!=="PROGRESS"){e._value=r;var o=r==null?"":r;e.value!==o&&(e.value=o),r==null&&e.removeAttribute(t);return}if(r===""||r==null){var l=typeof e[t];if(l==="boolean"){e[t]=Io(r);return}else if(r==null&&l==="string"){e[t]="",e.removeAttribute(t);return}else if(l==="number"){try{e[t]=0}catch(u){}e.removeAttribute(t);return}}try{e[t]=r}catch(u){}}var zi=Date.now,Eu=!1;if(typeof window!="undefined"){zi()>document.createEvent("Event").timeStamp&&(zi=()=>performance.now());var Tu=navigator.userAgent.match(/firefox\/(\d+)/i);Eu=!!(Tu&&Number(Tu[1])<=53)}var Za=0,vp=Promise.resolve(),dp=()=>{Za=0},hp=()=>Za||(vp.then(dp),Za=zi());function gp(e,t,r,i){e.addEventListener(t,r,i)}function pp(e,t,r,i){e.removeEventListener(t,r,i)}function mp(e,t,r,i){var n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null,a=e._vei||(e._vei={}),s=a[t];if(i&&s)s.value=i;else{var[o,l]=_p(t);if(i){var u=a[t]=bp(i,n);gp(e,o,u,l)}else s&&(pp(e,o,s,l),a[t]=void 0)}}var Cu=/(?:Once|Passive|Capture)$/;function _p(e){var t;if(Cu.test(e)){t={};for(var r;r=e.match(Cu);)e=e.slice(0,e.length-r[0].length),t[r[0].toLowerCase()]=!0}return[Ve(e.slice(2)),t]}function bp(e,t){var r=i=>{var n=i.timeStamp||zi();(Eu||n>=r.attached-1)&&et(wp(i,r.value),t,5,[i])};return r.value=e,r.attached=hp(),r}function wp(e,t){if(oe(t)){var r=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{r.call(e),e._stopped=!0},t.map(i=>n=>!n._stopped&&i(n))}else return t}var Iu=/^on[a-z]/,yp=function(e,t,r,i){var n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,a=arguments.length>5?arguments[5]:void 0,s=arguments.length>6?arguments[6]:void 0,o=arguments.length>7?arguments[7]:void 0,l=arguments.length>8?arguments[8]:void 0;t==="class"?ap(e,i,n):t==="style"?sp(e,r,i):gi(t)?qn(t)||mp(e,t,r,i,s):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):Sp(e,t,i,n))?cp(e,t,i,a,s,o,l):(t==="true-value"?e._trueValue=i:t==="false-value"&&(e._falseValue=i),fp(e,t,i,n))};function Sp(e,t,r,i){return i?!!(t==="innerHTML"||t==="textContent"||t in e&&Iu.test(t)&&ae(r)):t==="spellcheck"||t==="draggable"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA"||Iu.test(t)&&ye(r)?!1:t in e}var xp=["ctrl","shift","alt","meta"],Ep={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>xp.some(r=>e["".concat(r,"Key")]&&!t.includes(r))},Qa=(e,t)=>function(r){for(var i=0;i1?a-1:0),o=1;o{kr(e,!1)}):kr(e,i))},beforeUnmount(e,t){var{value:r}=t;kr(e,r)}};function kr(e,t){e.style.display=t?e._vod:"none"}var Tp=ue({patchProp:yp},np),Ou;function Cp(){return Ou||(Ou=Rg(Tp))}var Au=function(){var e=Cp().createApp(...arguments),{mount:t}=e;return e.mount=r=>{var i=Ip(r);if(!!i){var n=e._component;!ae(n)&&!n.render&&!n.template&&(n.template=i.innerHTML),i.innerHTML="";var a=t(i,!1,i instanceof SVGElement);return i instanceof Element&&(i.removeAttribute("v-cloak"),i.setAttribute("data-v-app","")),a}},e};function Ip(e){if(ye(e)){var t=document.querySelector(e);return t}return e}var Mu=["top","left","right","bottom"],es,Yi={},Ze;function ts(){return!("CSS"in window)||typeof CSS.supports!="function"?Ze="":CSS.supports("top: env(safe-area-inset-top)")?Ze="env":CSS.supports("top: constant(safe-area-inset-top)")?Ze="constant":Ze="",Ze}function Ru(){if(Ze=typeof Ze=="string"?Ze:ts(),!Ze){Mu.forEach(function(o){Yi[o]=0});return}function e(o,l){var u=o.style;Object.keys(l).forEach(function(v){var c=l[v];u[v]=c})}var t=[];function r(o){o?t.push(o):t.forEach(function(l){l()})}var i=!1;try{var n=Object.defineProperty({},"passive",{get:function(){i={passive:!0}}});window.addEventListener("test",null,n)}catch(o){}function a(o,l){var u=document.createElement("div"),v=document.createElement("div"),c=document.createElement("div"),m=document.createElement("div"),g=100,_=1e4,b={position:"absolute",width:g+"px",height:"200px",boxSizing:"border-box",overflow:"hidden",paddingBottom:Ze+"(safe-area-inset-"+l+")"};e(u,b),e(v,b),e(c,{transition:"0s",animation:"none",width:"400px",height:"400px"}),e(m,{transition:"0s",animation:"none",width:"250%",height:"250%"}),u.appendChild(c),v.appendChild(m),o.appendChild(u),o.appendChild(v),r(function(){u.scrollTop=v.scrollTop=_;var p=u.scrollTop,h=v.scrollTop;function f(){this.scrollTop!==(this===u?p:h)&&(u.scrollTop=v.scrollTop=_,p=u.scrollTop,h=v.scrollTop,Op(l))}u.addEventListener("scroll",f,i),v.addEventListener("scroll",f,i)});var w=getComputedStyle(u);Object.defineProperty(Yi,l,{configurable:!0,get:function(){return parseFloat(w.paddingBottom)}})}var s=document.createElement("div");e(s,{position:"absolute",left:"0",top:"0",width:"0",height:"0",zIndex:"-1",overflow:"hidden",visibility:"hidden"}),Mu.forEach(function(o){a(s,o)}),document.body.appendChild(s),r(),es=!0}function qi(e){return es||Ru(),Yi[e]}var Xi=[];function Op(e){Xi.length||setTimeout(function(){var t={};Xi.forEach(function(r){t[r]=Yi[r]}),Xi.length=0,Ki.forEach(function(r){r(t)})},0),Xi.push(e)}var Ki=[];function Ap(e){!ts()||(es||Ru(),typeof e=="function"&&Ki.push(e))}function Mp(e){var t=Ki.indexOf(e);t>=0&&Ki.splice(t,1)}var Rp={get support(){return(typeof Ze=="string"?Ze:ts()).length!=0},get top(){return qi("top")},get left(){return qi("left")},get right(){return qi("right")},get bottom(){return qi("bottom")},onChange:Ap,offChange:Mp},Gi=Rp,Pp=Qa(()=>{},["prevent"]);function rs(){var e=document.documentElement.style,t=parseInt(e.getPropertyValue("--window-top"));return t?t+Gi.top:0}function Lp(){var e=document.documentElement.style,t=rs(),r=parseInt(e.getPropertyValue("--window-bottom")),i=parseInt(e.getPropertyValue("--window-left")),n=parseInt(e.getPropertyValue("--window-right"));return{top:t,bottom:r?r+Gi.bottom:0,left:i?i+Gi.left:0,right:n?n+Gi.right:0}}function Np(e){var t=document.documentElement.style;Object.keys(e).forEach(r=>{t.setProperty(r,e[r])})}function Ji(e){return Symbol(e)}function Pu(e){return e=e+"",e.indexOf("rpx")!==-1||e.indexOf("upx")!==-1}function Wt(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(t)return Dp(e);if(typeof e=="string"){var r=parseInt(e)||0;return Pu(e)?uni.upx2px(r):r}return e}function Dp(e){return Pu(e)?e.replace(/(\d+(\.\d+)?)[ru]px/g,(t,r)=>uni.upx2px(parseFloat(r))+"px"):e}var kp="M20.928 10.176l-4.928 4.928-4.928-4.928-0.896 0.896 4.928 4.928-4.928 4.928 0.896 0.896 4.928-4.928 4.928 4.928 0.896-0.896-4.928-4.928 4.928-4.928-0.896-0.896zM16 2.080q-3.776 0-7.040 1.888-3.136 1.856-4.992 4.992-1.888 3.264-1.888 7.040t1.888 7.040q1.856 3.136 4.992 4.992 3.264 1.888 7.040 1.888t7.040-1.888q3.136-1.856 4.992-4.992 1.888-3.264 1.888-7.040t-1.888-7.040q-1.856-3.136-4.992-4.992-3.264-1.888-7.040-1.888zM16 28.64q-3.424 0-6.4-1.728-2.848-1.664-4.512-4.512-1.728-2.976-1.728-6.4t1.728-6.4q1.664-2.848 4.512-4.512 2.976-1.728 6.4-1.728t6.4 1.728q2.848 1.664 4.512 4.512 1.728 2.976 1.728 6.4t-1.728 6.4q-1.664 2.848-4.512 4.512-2.976 1.728-6.4 1.728z",Bp="M16 0q-4.352 0-8.064 2.176-3.616 2.144-5.76 5.76-2.176 3.712-2.176 8.064t2.176 8.064q2.144 3.616 5.76 5.76 3.712 2.176 8.064 2.176t8.064-2.176q3.616-2.144 5.76-5.76 2.176-3.712 2.176-8.064t-2.176-8.064q-2.144-3.616-5.76-5.76-3.712-2.176-8.064-2.176zM22.688 21.408q0.32 0.32 0.304 0.752t-0.336 0.736-0.752 0.304-0.752-0.32l-5.184-5.376-5.376 5.184q-0.32 0.32-0.752 0.304t-0.736-0.336-0.304-0.752 0.32-0.752l5.376-5.184-5.184-5.376q-0.32-0.32-0.304-0.752t0.336-0.752 0.752-0.304 0.752 0.336l5.184 5.376 5.376-5.184q0.32-0.32 0.752-0.304t0.752 0.336 0.304 0.752-0.336 0.752l-5.376 5.184 5.184 5.376z",Fp="M15.808 1.696q-3.776 0-7.072 1.984-3.2 1.888-5.088 5.152-1.952 3.392-1.952 7.36 0 3.776 1.952 7.072 1.888 3.2 5.088 5.088 3.296 1.952 7.072 1.952 3.968 0 7.36-1.952 3.264-1.888 5.152-5.088 1.984-3.296 1.984-7.072 0-4-1.984-7.36-1.888-3.264-5.152-5.152-3.36-1.984-7.36-1.984zM20.864 18.592l-3.776 4.928q-0.448 0.576-1.088 0.576t-1.088-0.576l-3.776-4.928q-0.448-0.576-0.24-0.992t0.944-0.416h2.976v-8.928q0-0.256 0.176-0.432t0.4-0.176h1.216q0.224 0 0.4 0.176t0.176 0.432v8.928h2.976q0.736 0 0.944 0.416t-0.24 0.992z",$p="M15.808 0.128q-4.224 0-7.872 2.176-3.552 2.112-5.632 5.728-2.176 3.776-2.176 8.16 0 4.224 2.176 7.872 2.080 3.552 5.632 5.632 3.648 2.176 7.872 2.176 4.384 0 8.16-2.176 3.616-2.080 5.728-5.632 2.176-3.648 2.176-7.872 0-4.416-2.176-8.16-2.112-3.616-5.728-5.728-3.744-2.176-8.16-2.176zM16.864 23.776q0 0.064-0.064 0.064h-1.568q-0.096 0-0.096-0.064l-0.256-11.328q0-0.064 0.064-0.064h2.112q0.096 0 0.064 0.064l-0.256 11.328zM16 10.88q-0.576 0-0.976-0.4t-0.4-0.96 0.4-0.96 0.976-0.4 0.976 0.4 0.4 0.96-0.4 0.96-0.976 0.4z",Up="M20.928 22.688q-1.696 1.376-3.744 2.112-2.112 0.768-4.384 0.768-3.488 0-6.464-1.728-2.88-1.696-4.576-4.608-1.76-2.976-1.76-6.464t1.76-6.464q1.696-2.88 4.576-4.576 2.976-1.76 6.464-1.76t6.464 1.76q2.912 1.696 4.608 4.576 1.728 2.976 1.728 6.464 0 2.272-0.768 4.384-0.736 2.048-2.112 3.744l9.312 9.28-1.824 1.824-9.28-9.312zM12.8 23.008q2.784 0 5.184-1.376 2.304-1.376 3.68-3.68 1.376-2.4 1.376-5.184t-1.376-5.152q-1.376-2.336-3.68-3.68-2.4-1.408-5.184-1.408t-5.152 1.408q-2.336 1.344-3.68 3.68-1.408 2.368-1.408 5.152t1.408 5.184q1.344 2.304 3.68 3.68 2.368 1.376 5.152 1.376zM12.8 23.008v0z",Zi="M1.952 18.080q-0.32-0.352-0.416-0.88t0.128-0.976l0.16-0.352q0.224-0.416 0.64-0.528t0.8 0.176l6.496 4.704q0.384 0.288 0.912 0.272t0.88-0.336l17.312-14.272q0.352-0.288 0.848-0.256t0.848 0.352l-0.416-0.416q0.32 0.352 0.32 0.816t-0.32 0.816l-18.656 18.912q-0.32 0.352-0.8 0.352t-0.8-0.32l-7.936-8.064z",Wp="M15.808 0.16q-4.224 0-7.872 2.176-3.552 2.112-5.632 5.728-2.144 3.744-2.144 8.128 0 4.192 2.144 7.872 2.112 3.52 5.632 5.632 3.68 2.144 7.872 2.144 4.384 0 8.128-2.144 3.616-2.080 5.728-5.632 2.176-3.648 2.176-7.872 0-4.384-2.176-8.128-2.112-3.616-5.728-5.728-3.744-2.176-8.128-2.176zM24.832 11.328l-11.264 11.104q-0.032 0.032-0.112 0.032t-0.112-0.032l-5.216-5.376q-0.096-0.128 0-0.288l0.704-0.96q0.032-0.064 0.112-0.064t0.112 0.032l4.256 3.264q0.064 0.032 0.144 0.032t0.112-0.032l10.336-8.608q0.064-0.064 0.144-0.064t0.112 0.064l0.672 0.672q0.128 0.128 0 0.224z",Vp="M15.84 0.096q-4.224 0-7.872 2.176-3.552 2.112-5.632 5.728-2.144 3.744-2.144 8.128 0 4.192 2.144 7.872 2.112 3.52 5.632 5.632 3.68 2.144 7.872 2.144 4.384 0 8.128-2.144 3.616-2.080 5.728-5.632 2.176-3.648 2.176-7.872 0-4.384-2.176-8.128-2.112-3.616-5.728-5.728-3.744-2.176-8.128-2.176zM23.008 21.92l-0.512 0.896q-0.096 0.128-0.224 0.064l-8-3.808q-0.096-0.064-0.16-0.128-0.128-0.096-0.128-0.288l0.512-12.096q0-0.064 0.048-0.112t0.112-0.048h1.376q0.064 0 0.112 0.048t0.048 0.112l0.448 10.848 6.304 4.256q0.064 0.064 0.080 0.128t-0.016 0.128z",Hp="M15.808 0.16q-4.224 0-7.872 2.176-3.552 2.112-5.632 5.728-2.144 3.744-2.144 8.128 0 4.192 2.144 7.872 2.112 3.52 5.632 5.632 3.68 2.144 7.872 2.144 4.384 0 8.128-2.144 3.616-2.080 5.728-5.632 2.176-3.648 2.176-7.872 0-4.384-2.176-8.128-2.112-3.616-5.728-5.728-3.744-2.176-8.128-2.176zM15.136 8.672h1.728q0.128 0 0.224 0.096t0.096 0.256l-0.384 10.24q0 0.064-0.048 0.112t-0.112 0.048h-1.248q-0.096 0-0.144-0.048t-0.048-0.112l-0.384-10.24q0-0.16 0.096-0.256t0.224-0.096zM16 23.328q-0.48 0-0.832-0.352t-0.352-0.848 0.352-0.848 0.832-0.352 0.832 0.352 0.352 0.848-0.352 0.848-0.832 0.352z";function Qi(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#000",r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:27;return O("svg",{width:r,height:r,viewBox:"0 0 32 32"},[O("path",{d:e,fill:t},null,8,["d","fill"])],8,["width","height"])}function en(){return Ct()}function jp(){return window.__PAGE_INFO__}function Ct(){return window.__id__||(window.__id__=plus.webview.currentWebview().id),parseInt(window.__id__)}function zp(e){e.preventDefault()}var Lu,Nu=0;function Yp(e){var{onPageScroll:t,onReachBottom:r,onReachBottomDistance:i}=e,n=!1,a=!1,s=!0,o=()=>{var{scrollHeight:u}=document.documentElement,v=window.innerHeight,c=window.scrollY,m=c>0&&u>v&&c+v+i>=u,g=Math.abs(u-Nu)>i;return m&&(!a||g)?(Nu=u,a=!0,!0):(!m&&a&&(a=!1),!1)},l=()=>{t&&t(window.pageYOffset);function u(){if(o())return r&&r(),s=!1,setTimeout(function(){s=!0},350),!0}r&&s&&(u()||(Lu=setTimeout(u,300))),n=!1};return function(){clearTimeout(Lu),n||requestAnimationFrame(l),n=!0}}function is(e,t){if(t.indexOf("/")===0)return t;if(t.indexOf("./")===0)return is(e,t.substr(2));for(var r=t.split("/"),i=r.length,n=0;n0?e.split("/"):[];return a.splice(a.length-n-1,n+1),ca(a.concat(r).join("/"))}class qp{constructor(t){this.$bindClass=!1,this.$bindStyle=!1,this.$vm=t,this.$el=t.$el,this.$el.getAttribute&&(this.$bindClass=!!this.$el.getAttribute("class"),this.$bindStyle=!!this.$el.getAttribute("style"))}selectComponent(t){if(!(!this.$el||!t)){var r=Du(this.$el.querySelector(t));if(!!r)return ns(r)}}selectAllComponents(t){if(!this.$el||!t)return[];for(var r=[],i=this.$el.querySelectorAll(t),n=0;n-1&&r.splice(i,1)}var n=this.$el.__wxsRemoveClass||(this.$el.__wxsRemoveClass=[]);return n.indexOf(t)===-1&&(n.push(t),this.forceUpdate("class")),this}hasClass(t){return this.$el&&this.$el.classList.contains(t)}getDataset(){return this.$el&&this.$el.dataset}callMethod(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=this.$vm[t];ae(i)?i(JSON.parse(JSON.stringify(r))):this.$vm.ownerId&&UniViewJSBridge.publishHandler(Sd,{nodeId:this.$el.__id,ownerId:this.$vm.ownerId,method:t,args:r})}requestAnimationFrame(t){return window.requestAnimationFrame(t)}getState(){return this.$el&&(this.$el.__wxsState||(this.$el.__wxsState={}))}triggerEvent(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.$vm.$emit(t,r),this}getComputedStyle(t){if(this.$el){var r=window.getComputedStyle(this.$el);return t&&t.length?t.reduce((i,n)=>(i[n]=r[n],i),{}):r}return{}}setTimeout(t,r){return window.setTimeout(t,r)}clearTimeout(t){return window.clearTimeout(t)}getBoundingClientRect(){return this.$el.getBoundingClientRect()}}function ns(e){if(e&&e.$el)return e.$el.__wxsComponentDescriptor||(e.$el.__wxsComponentDescriptor=new qp(e)),e.$el.__wxsComponentDescriptor}function tn(e,t){return ns(e)}function Du(e){if(!!e)return Br(e)}function Br(e){return e.__wxsVm||(e.__wxsVm={ownerId:e.__ownerId,$el:e,$emit(){},$forceUpdate(){var{__wxsStyle:t,__wxsAddClass:r,__wxsRemoveClass:i,__wxsStyleChanged:n,__wxsClassChanged:a}=e,s,o;n&&(e.__wxsStyleChanged=!1,t&&(o=()=>{Object.keys(t).forEach(l=>{e.style[l]=t[l]})})),a&&(e.__wxsClassChanged=!1,s=()=>{i&&i.forEach(l=>{e.classList.remove(l)}),r&&r.forEach(l=>{e.classList.add(l)})}),requestAnimationFrame(()=>{s&&s(),o&&o()})}})}var Xp=e=>e.type==="click";function ku(e,t,r){var{currentTarget:i}=e;if(!(e instanceof Event)||!(i instanceof HTMLElement))return[e];if(i.tagName.indexOf("UNI-")!==0)return[e];var n=Bu(e);if(Xp(e))Gp(n,e);else if(e instanceof TouchEvent){var a=rs();n.touches=Fu(e.touches,a),n.changedTouches=Fu(e.changedTouches,a)}return[n]}function Kp(e){for(;e&&e.tagName.indexOf("UNI-")!==0;)e=e.parentElement;return e}function Bu(e){var{type:t,timeStamp:r,target:i,currentTarget:n}=e,a={type:t,timeStamp:r,target:ia(Kp(i)),detail:{},currentTarget:ia(n)};return e._stopped&&(a._stopped=!0),e.type.startsWith("touch")&&(a.touches=e.touches,a.changedTouches=e.changedTouches),a}function Gp(e,t){var{x:r,y:i}=t,n=rs();e.detail={x:r,y:i-n},e.touches=e.changedTouches=[Jp(t)]}function Jp(e){return{force:1,identifier:0,clientX:e.clientX,clientY:e.clientY,pageX:e.pageX,pageY:e.pageY}}function Fu(e,t){for(var r=[],i=0;i1&&arguments[1]!==void 0?arguments[1]:{},r=Ct()+"";plus.webview.postMessageToUniNView({type:"subscribeHandler",args:{type:e,data:t,pageId:r}},Zp)}function nm(e,t){var r=e[0];if(!(!t||!Je(t.formatArgs)&&Je(r)))for(var i=t.formatArgs,n=Object.keys(i),a=0;aplus.io.convertLocalFileSystemURL(e).replace(/^\/?apps\//,"/android_asset/apps/").replace(/\/$/,""));function lm(e){return e.indexOf("_www")===0||e.indexOf("_doc")===0||e.indexOf("_documents")===0||e.indexOf("_downloads")===0}plus.os.name;var um=[];function fm(e){return um.find(t=>t.$page.id===e)}class Xy extends Dd{constructor(t,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;super(Rd,"#page",null);this._id=1,this._created=!1,this._updating=!1,this._createActionMap=new Map,this.updateActions=[],this.dicts=[],this.nodeId=0,this.pageId=t,this.pageNode=this,this.options=r,this.isUnmounted=!1,this.createAction=[la,r],this.createdAction=[jo],this.normalizeDict=this._normalizeDict.bind(this),this._update=this.update.bind(this),i&&this.setup()}_normalizeDict(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(!Je(t))return this.addDict(t);var i=[];return Object.keys(t).forEach(n=>{var a=[this.addDict(n)],s=t[n];r?a.push(this.addDict(s)):a.push(s),i.push(a)}),i}addDict(t){var{dicts:r}=this,i=r.indexOf(t);return i>-1?i:r.push(t)-1}onInjectHook(t){(t===Do||t===ko)&&!this.scrollAction&&(this.scrollAction=[Zo,this.options.onReachBottomDistance],this.push(this.scrollAction))}onCreate(t,r){return dm(this,t.nodeId,r),t}onInsertBefore(t,r,i){return hm(this,r,t.nodeId,i&&i.nodeId||-1),r}onRemoveChild(t){return gm(this,t.nodeId),t}onAddEvent(t,r,i){t.parentNode&&pm(this,t.nodeId,r,i)}onAddWxsEvent(t,r,i,n){t.parentNode&&mm(this,t.nodeId,r,i,n)}onRemoveEvent(t,r){t.parentNode&&_m(this,t.nodeId,r)}onSetAttribute(t,r,i){t.parentNode&&wm(this,t.nodeId,r,i)}onRemoveAttribute(t,r){t.parentNode&&ym(this,t.nodeId,r)}onTextContent(t,r){t.parentNode&&zu(this,t.nodeId,r)}onNodeValue(t,r){t.parentNode&&zu(this,t.nodeId,r)}genId(){return this._id++}push(t,r){if(!this.isUnmounted){switch(t[0]){case ua:this._createActionMap.set(t[1],t);break;case fa:var i=this._createActionMap.get(t[1]);i&&(i[3]=t[2],i[4]=t[3],r&&(i[5]=r));break}t[0]!==fa&&this.updateActions.push(t),this._updating||(this._updating=!0,gu(this._update))}}restore(){this.clear(),this.push(this.createAction),this.scrollAction&&this.push(this.scrollAction);var t=r=>{this.onCreate(r,r.nodeName),this.onInsertBefore(r.parentNode,r,null),r.childNodes.forEach(i=>{t(i)})};this.childNodes.forEach(r=>t(r)),this.push(this.createdAction)}setup(){this.send([this.createAction])}update(){var{dicts:t,updateActions:r,_createActionMap:i}=this;this._created||(this._created=!0,r.push(this.createdAction)),r.length&&(t.length&&r.unshift([Uu,t]),this.send(r)),this.clear()}clear(){this.dicts.length=0,this.updateActions.length=0,this._updating=!1,this._createActionMap.clear()}send(t){UniServiceJSBridge.publishHandler(as,t,this.pageId)}fireEvent(t,r){var i=vm(t,this);i&&i.dispatchEvent(r)}}function cm(e){var t=fm(e);return t?t.__page_container__:null}function ju(e,t,r){if(typeof r=="number"&&(r=cm(r)),r[e]===t)return r;for(var{childNodes:i}=r,n=0;n{if(ss===0&&Am(),e=Number(e),e===0)return 0;var r=t||ss;{var i=__uniConfig.globalStyle||{},n=Ku(i.rpxCalcMaxDeviceWidth,960),a=Ku(i.rpxCalcBaseDeviceWidth,375);r=r<=n?r:a}var s=e/Om*r;return s<0&&(s=-s),s=Math.floor(s+Im),s===0&&(Xu===1||!qu?s=1:s=.5),e<0?-s:s}),Mm=[{name:"id",type:String,required:!0}];Mm.concat({name:"componentInstance",type:Object});var Ju={};Ju.f={}.propertyIsEnumerable;var Rm=hr,Pm=Fn,Lm=ni,Nm=Ju.f,Dm=function(e){return function(t){for(var r=Lm(t),i=Pm(r),n=i.length,a=0,s=[],o;n>a;)o=i[a++],(!Rm||Nm.call(r,o))&&s.push(e?[o,r[o]]:r[o]);return s}},Zu=kn,km=Dm(!1);Zu(Zu.S,"Object",{values:function(t){return km(t)}});var Bm="setPageMeta",Fm="loadFontFace",$m="pageScrollTo",Um=function(){if(typeof window!="object")return;if("IntersectionObserver"in window&&"IntersectionObserverEntry"in window&&"intersectionRatio"in window.IntersectionObserverEntry.prototype){"isIntersecting"in window.IntersectionObserverEntry.prototype||Object.defineProperty(window.IntersectionObserverEntry.prototype,"isIntersecting",{get:function(){return this.intersectionRatio>0}});return}function e(f){try{return f.defaultView&&f.defaultView.frameElement||null}catch(d){return null}}var t=function(f){for(var d=f,y=e(d);y;)d=y.ownerDocument,y=e(d);return d}(window.document),r=[],i=null,n=null;function a(f){this.time=f.time,this.target=f.target,this.rootBounds=_(f.rootBounds),this.boundingClientRect=_(f.boundingClientRect),this.intersectionRect=_(f.intersectionRect||g()),this.isIntersecting=!!f.intersectionRect;var d=this.boundingClientRect,y=d.width*d.height,x=this.intersectionRect,T=x.width*x.height;y?this.intersectionRatio=Number((T/y).toFixed(4)):this.intersectionRatio=this.isIntersecting?1:0}function s(f,d){var y=d||{};if(typeof f!="function")throw new Error("callback must be a function");if(y.root&&y.root.nodeType!=1&&y.root.nodeType!=9)throw new Error("root must be a Document or Element");this._checkForIntersections=l(this._checkForIntersections.bind(this),this.THROTTLE_TIMEOUT),this._callback=f,this._observationTargets=[],this._queuedEntries=[],this._rootMarginValues=this._parseRootMargin(y.rootMargin),this.thresholds=this._initThresholds(y.threshold),this.root=y.root||null,this.rootMargin=this._rootMarginValues.map(function(x){return x.value+x.unit}).join(" "),this._monitoringDocuments=[],this._monitoringUnsubscribes=[]}s.prototype.THROTTLE_TIMEOUT=100,s.prototype.POLL_INTERVAL=null,s.prototype.USE_MUTATION_OBSERVER=!0,s._setupCrossOriginUpdater=function(){return i||(i=function(f,d){!f||!d?n=g():n=b(f,d),r.forEach(function(y){y._checkForIntersections()})}),i},s._resetCrossOriginUpdater=function(){i=null,n=null},s.prototype.observe=function(f){var d=this._observationTargets.some(function(y){return y.element==f});if(!d){if(!(f&&f.nodeType==1))throw new Error("target must be an Element");this._registerInstance(),this._observationTargets.push({element:f,entry:null}),this._monitorIntersections(f.ownerDocument),this._checkForIntersections()}},s.prototype.unobserve=function(f){this._observationTargets=this._observationTargets.filter(function(d){return d.element!=f}),this._unmonitorIntersections(f.ownerDocument),this._observationTargets.length==0&&this._unregisterInstance()},s.prototype.disconnect=function(){this._observationTargets=[],this._unmonitorAllIntersections(),this._unregisterInstance()},s.prototype.takeRecords=function(){var f=this._queuedEntries.slice();return this._queuedEntries=[],f},s.prototype._initThresholds=function(f){var d=f||[0];return Array.isArray(d)||(d=[d]),d.sort().filter(function(y,x,T){if(typeof y!="number"||isNaN(y)||y<0||y>1)throw new Error("threshold must be a number between 0 and 1 inclusively");return y!==T[x-1]})},s.prototype._parseRootMargin=function(f){var d=f||"0px",y=d.split(/\s+/).map(function(x){var T=/^(-?\d*\.?\d+)(px|%)$/.exec(x);if(!T)throw new Error("rootMargin must be specified in pixels or percent");return{value:parseFloat(T[1]),unit:T[2]}});return y[1]=y[1]||y[0],y[2]=y[2]||y[0],y[3]=y[3]||y[1],y},s.prototype._monitorIntersections=function(f){var d=f.defaultView;if(!!d&&this._monitoringDocuments.indexOf(f)==-1){var y=this._checkForIntersections,x=null,T=null;this.POLL_INTERVAL?x=d.setInterval(y,this.POLL_INTERVAL):(u(d,"resize",y,!0),u(f,"scroll",y,!0),this.USE_MUTATION_OBSERVER&&"MutationObserver"in d&&(T=new d.MutationObserver(y),T.observe(f,{attributes:!0,childList:!0,characterData:!0,subtree:!0}))),this._monitoringDocuments.push(f),this._monitoringUnsubscribes.push(function(){var U=f.defaultView;U&&(x&&U.clearInterval(x),v(U,"resize",y,!0)),v(f,"scroll",y,!0),T&&T.disconnect()});var C=this.root&&(this.root.ownerDocument||this.root)||t;if(f!=C){var A=e(f);A&&this._monitorIntersections(A.ownerDocument)}}},s.prototype._unmonitorIntersections=function(f){var d=this._monitoringDocuments.indexOf(f);if(d!=-1){var y=this.root&&(this.root.ownerDocument||this.root)||t,x=this._observationTargets.some(function(A){var U=A.element.ownerDocument;if(U==f)return!0;for(;U&&U!=y;){var V=e(U);if(U=V&&V.ownerDocument,U==f)return!0}return!1});if(!x){var T=this._monitoringUnsubscribes[d];if(this._monitoringDocuments.splice(d,1),this._monitoringUnsubscribes.splice(d,1),T(),f!=y){var C=e(f);C&&this._unmonitorIntersections(C.ownerDocument)}}}},s.prototype._unmonitorAllIntersections=function(){var f=this._monitoringUnsubscribes.slice(0);this._monitoringDocuments.length=0,this._monitoringUnsubscribes.length=0;for(var d=0;d=0&&U>=0&&{top:y,bottom:x,left:T,right:C,width:A,height:U}||null}function m(f){var d;try{d=f.getBoundingClientRect()}catch(y){}return d?(d.width&&d.height||(d={top:d.top,right:d.right,bottom:d.bottom,left:d.left,width:d.right-d.left,height:d.bottom-d.top}),d):g()}function g(){return{top:0,bottom:0,left:0,right:0,width:0,height:0}}function _(f){return!f||"x"in f?f:{top:f.top,y:f.top,bottom:f.bottom,left:f.left,x:f.left,right:f.right,width:f.width,height:f.height}}function b(f,d){var y=d.top-f.top,x=d.left-f.left;return{top:y,left:x,height:d.height,width:d.width,bottom:y+d.height,right:x+d.width}}function w(f,d){for(var y=d;y;){if(y==f)return!0;y=p(y)}return!1}function p(f){var d=f.parentNode;return f.nodeType==9&&f!=t?e(f):(d&&d.assignedSlot&&(d=d.assignedSlot.parentNode),d&&d.nodeType==11&&d.host?d.host:d)}function h(f){return f&&f.nodeType===9}window.IntersectionObserver=s,window.IntersectionObserverEntry=a};function os(e){var{bottom:t,height:r,left:i,right:n,top:a,width:s}=e||{};return{bottom:t,height:r,left:i,right:n,top:a,width:s}}function Wm(e){var{intersectionRatio:t,boundingClientRect:{height:r,width:i},intersectionRect:{height:n,width:a}}=e;return t!==0?t:n===r?a/i:n/r}function Vm(e,t,r){Um();var i=t.relativeToSelector?e.querySelector(t.relativeToSelector):null,n=new IntersectionObserver(l=>{l.forEach(u=>{r({intersectionRatio:Wm(u),intersectionRect:os(u.intersectionRect),boundingClientRect:os(u.boundingClientRect),relativeRect:os(u.rootBounds),time:Date.now(),dataset:ta(u.target),id:u.target.id})})},{root:i,rootMargin:t.rootMargin,threshold:t.thresholds});if(t.observeAll){n.USE_MUTATION_OBSERVER=!0;for(var a=e.querySelectorAll(t.selector),s=0;s{var i=450,n=44;clearTimeout(t),e&&Math.abs(r.pageX-e.pageX)<=n&&Math.abs(r.pageY-e.pageY)<=n&&r.timeStamp-e.timeStamp<=i&&r.preventDefault(),e=r,t=setTimeout(()=>{e=null},i)})}}function Gm(e){if(!e.length)return r=>r;var t=function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof r=="number")return e[r];var n={};return r.forEach(a=>{var[s,o]=a;i?n[t(s)]=t(o):n[t(s)]=o}),n};return t}function Jm(e,t){if(!!t)return t.a&&(t.a=e(t.a)),t.e&&(t.e=e(t.e,!1)),t.w&&(t.w=Zm(t.w,e)),t.s&&(t.s=e(t.s)),t.t&&(t.t=e(t.t)),t}function Zm(e,t){var r={};return e.forEach(i=>{var[n,[a,s]]=i;r[t(n)]=[t(a),s]}),r}function Qm(e,t){return e.priority=t,e}var ls=new Set,e0=1,us=2,Qu=3,ef=4;function It(e,t){ls.add(Qm(e,t))}function t0(){try{[...ls].sort((e,t)=>e.priority-t.priority).forEach(e=>e())}finally{ls.clear()}}function tf(e,t){var r=window["__"+wd],i=r&&r[e];if(i)return i;if(t&&t.__renderjsInstances)return t.__renderjsInstances[e]}var r0=Lo.length;function i0(e,t,r){var[i,n,a,s]=cs(t),o=fs(e,i);if(oe(r)||oe(s)){var[l,u]=a.split(".");return vs(o,n,l,u,r||s)}return s0(o,n,a)}function n0(e,t,r){var[i,n,a]=cs(t),[s,o]=a.split("."),l=fs(e,i);return vs(l,n,s,o,[l0(r,e),tn(Br(l))])}function fs(e,t){if(e.__ownerId===t)return e;for(var r=e.parentElement;r;){if(r.__ownerId===t)return r;r=r.parentElement}return e}function cs(e){return JSON.parse(e.substr(r0))}function a0(e,t,r,i){var[n,a,s]=cs(e),o=fs(t,n),[l,u]=s.split(".");return vs(o,a,l,u,[r,i,tn(Br(o)),tn(Br(t))])}function vs(e,t,r,i,n){var a=tf(t,e);if(!a)return console.error(ea("wxs","module "+r+" not found"));var s=a[i];return ae(s)?s.apply(a,n):console.error(r+"."+i+" is not a function")}function s0(e,t,r){var i=tf(t,e);return i?Qo(i,r.substr(r.indexOf(".")+1)):console.error(ea("wxs","module "+r+" not found"))}function o0(e,t,r){var i=r;return n=>{try{a0(t,e.$,n,i)}catch(a){console.error(a)}i=n}}function l0(e,t){var r=Br(t);return Object.defineProperty(e,"instance",{get(){return tn(r)}}),e}function rf(e,t){Object.keys(t).forEach(r=>{f0(e,t[r])})}function u0(e){var{__renderjsInstances:t}=e.$;!t||Object.keys(t).forEach(r=>{t[r].$.appContext.app.unmount()})}function f0(e,t){var r=c0(t);if(!!r){var i=e.$;(i.__renderjsInstances||(i.__renderjsInstances={}))[t]=v0(r)}}function c0(e){var t=window["__"+yd],r=t&&t[e];return r||console.error(ea("renderjs",e+" not found"))}function v0(e){return e=e.default||e,e.render=()=>{},Au(e).mount(document.createElement("div"))}class lr{constructor(t,r,i,n){this.isMounted=!1,this.isUnmounted=!1,this.$hasWxsProps=!1,this.$children=[],this.id=t,this.tag=r,this.pid=i,n&&(this.$=n),this.$wxsProps=new Map;var a=this.$parent=_y(i);a&&a.appendUniChild(this)}init(t){te(t,"t")&&(this.$.textContent=t.t)}setText(t){this.$.textContent=t}insert(t,r){var i=this.$,n=Ke(t);r===-1?n.appendChild(i):n.insertBefore(i,Ke(r).$),this.isMounted=!0}remove(){this.removeUniParent();var{$:t}=this;t.parentNode.removeChild(t),this.isUnmounted=!0,gc(this.id),u0(this),this.removeUniChildren()}appendChild(t){return this.$.appendChild(t)}insertBefore(t,r){return this.$.insertBefore(t,r)}appendUniChild(t){this.$children.push(t)}removeUniChild(t){var r=this.$children.indexOf(t);r>=0&&this.$children.splice(r,1)}removeUniParent(){var{$parent:t}=this;t&&(t.removeUniChild(this),this.$parent=void 0)}removeUniChildren(){this.$children.forEach(t=>t.remove()),this.$children.length=0}setWxsProps(t){Object.keys(t).forEach(r=>{if(r.indexOf(oa)===0){var i=r.replace(oa,""),n=t[i],a=o0(this,t[r],n);It(()=>a(n),ef),this.$wxsProps.set(r,a),delete t[r],delete t[i],this.$hasWxsProps=!0}})}addWxsEvents(t){Object.keys(t).forEach(r=>{var[i,n]=t[r];this.addWxsEvent(r,i,n)})}addWxsEvent(t,r,i){}wxsPropsInvoke(t,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=this.$hasWxsProps&&this.$wxsProps.get(oa+t);if(n)return It(()=>i?sr(()=>n(r)):n(r),ef),!0}}function nf(e,t){var{__wxsAddClass:r,__wxsRemoveClass:i}=e;i&&i.length&&(t=t.split(/\s+/).filter(n=>i.indexOf(n)===-1).join(" "),i.length=0),r&&r.length&&(t=t+" "+r.join(" ")),e.className=t}function af(e,t){var r=e.style;if(ye(t))t===""?e.removeAttribute("style"):r.cssText=Wt(t,!0);else for(var i in t)ds(r,i,t[i]);var{__wxsStyle:n}=e;if(n)for(var a in n)ds(r,a,n[a])}var sf=/\s*!important$/;function ds(e,t,r){if(oe(r))r.forEach(n=>ds(e,t,n));else if(r=Wt(r,!0),t.startsWith("--"))e.setProperty(t,r);else{var i=d0(e,t);sf.test(r)?e.setProperty(Ve(i),r.replace(sf,""),"important"):e[i]=r}}var of=["Webkit"],hs={};function d0(e,t){var r=hs[t];if(r)return r;var i=mt(t);if(i!=="filter"&&i in e)return hs[t]=i;i=_i(i);for(var n=0;n{var[a]=ku(n);a.type=na(n.type,r),UniViewJSBridge.publishHandler(as,[[Fd,e,a]])};return t?Qa(i,vf(t)):i}function vf(e){var t=[];return e&aa.prevent&&t.push("prevent"),e&aa.self&&t.push("self"),e&aa.stop&&t.push("stop"),t}function h0(e,t,r,i){var[n,a]=yi(t);i===-1?lf(e,n):uf(e,n)||e.addEventListener(n,e.__listeners[n]=df(e,r,i),a)}function df(e,t,r){var i=n=>{n0(e,t,ku(n)[0])};return r?Qa(i,vf(r)):i}var g0=No.length;function gs(e,t){return ye(t)&&(t.indexOf(No)===0?t=JSON.parse(t.substr(g0)):t.indexOf(Lo)===0&&(t=i0(e,t))),t}function rn(e){return e.indexOf("--")===0}function ps(e,t){e._vod=e.style.display==="none"?"":e.style.display,e.style.display=t?e._vod:"none"}class hf extends lr{constructor(t,r,i,n,a){var s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:[];super(t,r.tagName,i,r);this.$props=Te({}),this.$.__id=t,this.$.__listeners=Object.create(null),this.$propNames=s,this._update=this.update.bind(this),this.init(a),this.insert(i,n)}init(t){te(t,"a")&&this.setAttrs(t.a),te(t,"s")&&this.setAttr("style",t.s),te(t,"e")&&this.addEvents(t.e),te(t,"w")&&this.addWxsEvents(t.w),super.init(t),W(this.$props,()=>{It(this._update,e0)},{flush:"sync"}),this.update(!0)}setAttrs(t){this.setWxsProps(t),Object.keys(t).forEach(r=>{this.setAttr(r,t[r])})}addEvents(t){Object.keys(t).forEach(r=>{this.addEvent(r,t[r])})}addWxsEvent(t,r,i){h0(this.$,t,r,i)}addEvent(t,r){ff(this.$,t,r)}removeEvent(t){ff(this.$,t,-1)}setAttr(t,r){t===Wo?nf(this.$,r):t===sa?af(this.$,r):t===Si?ps(this.$,r):t===Vo?this.$.__ownerId=r:t===Ho?It(()=>rf(this,r),Qu):t===kd?this.$.innerHTML=r:t===Bd?this.setText(r):this.setAttribute(t,r)}removeAttr(t){t===Wo?nf(this.$,""):t===sa?af(this.$,""):this.removeAttribute(t)}setAttribute(t,r){r=gs(this.$,r),this.$propNames.indexOf(t)!==-1?this.$props[t]=r:rn(t)?this.$.style.setProperty(t,r):this.wxsPropsInvoke(t,r)||this.$.setAttribute(t,r)}removeAttribute(t){this.$propNames.indexOf(t)!==-1?delete this.$props[t]:rn(t)?this.$.style.removeProperty(t):this.$.removeAttribute(t)}update(){}}class p0 extends lr{constructor(t,r,i){super(t,"#comment",r,document.createComment(""));this.insert(r,i)}}var Ky="";function gf(e){return/^-?\d+[ur]px$/i.test(e)?e.replace(/(^-?\d+)[ur]px$/i,(t,r)=>"".concat(uni.upx2px(parseFloat(r)),"px")):/^-?[\d\.]+$/.test(e)?"".concat(e,"px"):e||""}function m0(e){return e.replace(/[A-Z]/g,t=>"-".concat(t.toLowerCase())).replace("webkit","-webkit")}function _0(e){var t=["matrix","matrix3d","scale","scale3d","rotate3d","skew","translate","translate3d"],r=["scaleX","scaleY","scaleZ","rotate","rotateX","rotateY","rotateZ","skewX","skewY","translateX","translateY","translateZ"],i=["opacity","background-color"],n=["width","height","left","right","top","bottom"],a=e.animates,s=e.option,o=s.transition,l={},u=[];return a.forEach(v=>{var c=v.type,m=[...v.args];if(t.concat(r).includes(c))c.startsWith("rotate")||c.startsWith("skew")?m=m.map(_=>parseFloat(_)+"deg"):c.startsWith("translate")&&(m=m.map(gf)),r.indexOf(c)>=0&&(m.length=1),u.push("".concat(c,"(").concat(m.join(","),")"));else if(i.concat(n).includes(m[0])){c=m[0];var g=m[1];l[c]=n.includes(c)?gf(g):g}}),l.transform=l.webkitTransform=u.join(" "),l.transition=l.webkitTransition=Object.keys(l).map(v=>"".concat(m0(v)," ").concat(o.duration,"ms ").concat(o.timingFunction," ").concat(o.delay,"ms")).join(","),l.transformOrigin=l.webkitTransformOrigin=s.transformOrigin,l}function pf(e){var t=e.animation;if(!t||!t.actions||!t.actions.length)return;var r=0,i=t.actions,n=t.actions.length;function a(){var s=i[r],o=s.option.transition,l=_0(s);Object.keys(l).forEach(u=>{e.$el.style[u]=l[u]}),r+=1,r{a()},0)}var nn={props:["animation"],watch:{animation:{deep:!0,handler(){pf(this)}}},mounted(){pf(this)}},de=e=>{var{props:t,mixins:r}=e;return(!t||!t.animation)&&(r||(e.mixins=[])).push(nn),b0(e)},b0=e=>(e.compatConfig={MODE:3},fg(e)),w0={hoverClass:{type:String,default:"none"},hoverStopPropagation:{type:Boolean,default:!1},hoverStartTime:{type:[Number,String],default:50},hoverStayTime:{type:[Number,String],default:400}};function ms(e){var t=$(!1),r=!1,i,n;function a(){requestAnimationFrame(()=>{clearTimeout(n),n=setTimeout(()=>{t.value=!1},parseInt(e.hoverStayTime))})}function s(u){u._hoverPropagationStopped||!e.hoverClass||e.hoverClass==="none"||e.disabled||u.touches.length>1||(e.hoverStopPropagation&&(u._hoverPropagationStopped=!0),r=!0,i=setTimeout(()=>{t.value=!0,r||a()},parseInt(e.hoverStartTime)))}function o(){r=!1,t.value&&a()}function l(){r=!1,t.value=!1,clearTimeout(i)}return{hovering:t,binding:{onTouchstartPassive:s,onTouchend:o,onTouchcancel:l}}}function Fr(e,t){return ye(t)&&(t=[t]),t.reduce((r,i)=>(e[i]&&(r[i]=!0),r),Object.create(null))}function Vt(e){return e.__wwe=!0,e}function Ae(e,t){return(r,i,n)=>{e.value&&t(r,S0(r,i,e.value,n||{}))}}function y0(e){return(t,r)=>{e(t,Bu(r))}}function S0(e,t,r,i){var n=ia(r);return{type:i.type||e,timeStamp:t.timeStamp||0,target:n,currentTarget:n,detail:i}}var ut=Ji("uf"),x0=de({name:"Form",emits:["submit","reset"],setup(e,t){var{slots:r,emit:i}=t,n=$(null);return E0(Ae(n,i)),()=>O("uni-form",{ref:n},[O("span",null,[r.default&&r.default()])],512)}});function E0(e){var t=[];return Ne(ut,{addField(r){t.push(r)},removeField(r){t.splice(t.indexOf(r),1)},submit(r){e("submit",r,{value:t.reduce((i,n)=>{if(n.submit){var[a,s]=n.submit();a&&(i[a]=s)}return i},Object.create(null))})},reset(r){t.forEach(i=>i.reset&&i.reset()),e("reset",r)}}),t}var $r=Ji("ul"),T0={for:{type:String,default:""}},C0=de({name:"Label",props:T0,setup(e,t){var{slots:r}=t,i=en(),n=I0(),a=Q(()=>e.for||r.default&&r.default.length),s=Vt(o=>{var l=o.target,u=/^uni-(checkbox|radio|switch)-/.test(l.className);u||(u=/^uni-(checkbox|radio|switch|button)$|^(svg|path)$/i.test(l.tagName)),!u&&(e.for?UniViewJSBridge.emit("uni-label-click-"+i+"-"+e.for,o,!0):n.length&&n[0](o,!0))});return()=>O("uni-label",{class:{"uni-label-pointer":a},onClick:s},[r.default&&r.default()],10,["onClick"])}});function I0(){var e=[];return Ne($r,{addHandler(t){e.push(t)},removeHandler(t){e.splice(e.indexOf(t),1)}}),e}function an(e,t){mf(e.id,t),W(()=>e.id,(r,i)=>{_f(i,t,!0),mf(r,t,!0)}),yt(()=>{_f(e.id,t)})}function mf(e,t,r){var i=en();r&&!e||!Je(t)||Object.keys(t).forEach(n=>{r?n.indexOf("@")!==0&&n.indexOf("uni-")!==0&&UniViewJSBridge.on("uni-".concat(n,"-").concat(i,"-").concat(e),t[n]):n.indexOf("uni-")===0?UniViewJSBridge.on(n,t[n]):e&&UniViewJSBridge.on("uni-".concat(n,"-").concat(i,"-").concat(e),t[n])})}function _f(e,t,r){var i=en();r&&!e||!Je(t)||Object.keys(t).forEach(n=>{r?n.indexOf("@")!==0&&n.indexOf("uni-")!==0&&UniViewJSBridge.off("uni-".concat(n,"-").concat(i,"-").concat(e),t[n]):n.indexOf("uni-")===0?UniViewJSBridge.off(n,t[n]):e&&UniViewJSBridge.off("uni-".concat(n,"-").concat(i,"-").concat(e),t[n])})}var O0=de({name:"Button",props:{id:{type:String,default:""},hoverClass:{type:String,default:"button-hover"},hoverStartTime:{type:[Number,String],default:20},hoverStayTime:{type:[Number,String],default:70},hoverStopPropagation:{type:Boolean,default:!1},disabled:{type:[Boolean,String],default:!1},formType:{type:String,default:""},openType:{type:String,default:""},loading:{type:[Boolean,String],default:!1}},setup(e,t){var{slots:r}=t,i=$(null);sh();var n=pe(ut,!1),{hovering:a,binding:s}=ms(e),{t:o}=He(),l=Vt((v,c)=>{if(e.disabled)return v.stopImmediatePropagation();c&&i.value.click();var m=e.formType;if(m){if(!n)return;m==="submit"?n.submit(v):m==="reset"&&n.reset(v);return}e.openType==="feedback"&&A0(o("uni.button.feedback.title"),o("uni.button.feedback.send"))}),u=pe($r,!1);return u&&(u.addHandler(l),xe(()=>{u.removeHandler(l)})),an(e,{"label-click":l}),()=>{var v=e.hoverClass,c=Fr(e,"disabled"),m=Fr(e,"loading"),g=v&&v!=="none";return O("uni-button",ze({ref:i,onClick:l,class:g&&a.value?v:""},g&&s,c,m),[r.default&&r.default()],16,["onClick"])}}});function A0(e,t){var r=plus.webview.create("https://service.dcloud.net.cn/uniapp/feedback.html","feedback",{titleNView:{titleText:e,autoBackButton:!0,backgroundColor:"#F7F7F7",titleColor:"#007aff",buttons:[{text:t,color:"#007aff",fontSize:"16px",fontWeight:"bold",onclick:function(){r.evalJS('typeof mui !== "undefined" && mui.trigger(document.getElementById("submit"),"tap")')}}]}});r.show("slide-in-right")}var Ht=de({name:"ResizeSensor",props:{initial:{type:Boolean,default:!1}},emits:["resize"],setup(e,t){var{emit:r}=t,i=$(null),n=R0(i),a=M0(i,r,n);return P0(i,e,a,n),()=>O("uni-resize-sensor",{ref:i,onAnimationstartOnce:a},[O("div",{onScroll:a},[O("div",null,null)],40,["onScroll"]),O("div",{onScroll:a},[O("div",null,null)],40,["onScroll"])],40,["onAnimationstartOnce"])}});function M0(e,t,r){var i=Te({width:-1,height:-1});return W(()=>ue({},i),n=>t("resize",n)),()=>{var n=e.value;i.width=n.offsetWidth,i.height=n.offsetHeight,r()}}function R0(e){return()=>{var{firstElementChild:t,lastElementChild:r}=e.value;t.scrollLeft=1e5,t.scrollTop=1e5,r.scrollLeft=1e5,r.scrollTop=1e5}}function P0(e,t,r,i){Na(i),Oe(()=>{t.initial&&sr(r);var n=e.value;n.offsetParent!==n.parentElement&&(n.parentElement.style.position="relative"),"AnimationEvent"in window||i()})}var me=function(){var e=document.createElement("canvas");e.height=e.width=0;var t=e.getContext("2d"),r=t.backingStorePixelRatio||t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1;return(window.devicePixelRatio||1)/r}();function bf(e){e.width=e.offsetWidth*me,e.height=e.offsetHeight*me,e.getContext("2d").__hidpi__=!0}var wf=!1;function L0(){if(!wf){wf=!0;var e=function(i,n){for(var a in i)te(i,a)&&n(i[a],a)},t={fillRect:"all",clearRect:"all",strokeRect:"all",moveTo:"all",lineTo:"all",arc:[0,1,2],arcTo:"all",bezierCurveTo:"all",isPointinPath:"all",isPointinStroke:"all",quadraticCurveTo:"all",rect:"all",translate:"all",createRadialGradient:"all",createLinearGradient:"all",setTransform:[4,5]},r=CanvasRenderingContext2D.prototype;r.drawImageByCanvas=function(i){return function(n,a,s,o,l,u,v,c,m,g){if(!this.__hidpi__)return i.apply(this,arguments);a*=me,s*=me,o*=me,l*=me,u*=me,v*=me,c=g?c*me:c,m=g?m*me:m,i.call(this,n,a,s,o,l,u,v,c,m)}}(r.drawImage),me!==1&&(e(t,function(i,n){r[n]=function(a){return function(){if(!this.__hidpi__)return a.apply(this,arguments);var s=Array.prototype.slice.call(arguments);if(i==="all")s=s.map(function(l){return l*me});else if(Array.isArray(i))for(var o=0;oL0());function yf(e){return e&&tt(e)}function sn(e){return e=e.slice(0),e[3]=e[3]/255,"rgba("+e.join(",")+")"}function Sf(e,t){var r=e;return Array.from(t).map(i=>{var n=r.getBoundingClientRect();return{identifier:i.identifier,x:i.clientX-n.left,y:i.clientY-n.top}})}var Ur;function xf(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return Ur||(Ur=document.createElement("canvas")),Ur.width=e,Ur.height=t,Ur}var D0={canvasId:{type:String,default:""},disableScroll:{type:[Boolean,String],default:!1}},k0=de({inheritAttrs:!1,name:"Canvas",compatConfig:{MODE:3},props:D0,computed:{id(){return this.canvasId}},setup(e,t){var{emit:r,slots:i}=t;N0();var n=$(null),a=$(null),s=$(!1),o=y0(r),{$attrs:l,$excludeAttrs:u,$listeners:v}=Vf({excludeListeners:!0}),{_listeners:c}=B0(e,v,o),{_handleSubscribe:m,_resize:g}=F0(n,s);return mn(m,_n(e.canvasId),!0),Oe(()=>{g()}),()=>{var{canvasId:_,disableScroll:b}=e;return O("uni-canvas",ze({"canvas-id":_,"disable-scroll":b},l.value,u.value,c.value),[O("canvas",{ref:n,class:"uni-canvas-canvas",width:"300",height:"150"},null,512),O("div",{style:"position: absolute;top: 0;left: 0;width: 100%;height: 100%;overflow: hidden;"},[i.default&&i.default()]),O(Ht,{ref:a,onResize:g},null,8,["onResize"])],16,["canvas-id","disable-scroll"])}}});function B0(e,t,r){var i=Q(()=>{var n=["onTouchstart","onTouchmove","onTouchend"],a=t.value,s=ue({},(()=>{var o={};for(var l in a)if(Object.prototype.hasOwnProperty.call(a,l)){var u=a[l];o[l]=u}return o})());return n.forEach(o=>{var l=s[o],u=[];l&&u.push(Vt(v=>{r(o.replace("on","").toLocaleLowerCase(),ue({},(()=>{var c={};for(var m in v)c[m]=v[m];return c})(),{touches:Sf(v.currentTarget,v.touches),changedTouches:Sf(v.currentTarget,v.changedTouches)}))})),e.disableScroll&&o==="onTouchmove"&&u.push(Pp),s[o]=u}),s});return{_listeners:i}}function F0(e,t){var r=[],i={};function n(g){var _=e.value,b=!g||_.width!==Math.floor(g.width*me)||_.height!==Math.floor(g.height*me);if(!!b)if(_.width>0&&_.height>0){var w=_.getContext("2d"),p=w.getImageData(0,0,_.width,_.height);bf(_),w.putImageData(p,0,0)}else bf(_)}function a(g,_){var{actions:b,reserve:w}=g;if(!!b){if(t.value){r.push([b,w]);return}var p=e.value,h=p.getContext("2d");w||(h.fillStyle="#000000",h.strokeStyle="#000000",h.shadowColor="#000000",h.shadowBlur=0,h.shadowOffsetX=0,h.shadowOffsetY=0,h.setTransform(1,0,0,1,0,0),h.clearRect(0,0,p.width,p.height)),s(b);for(var f=function(x){var T=b[x],C=T.method,A=T.data,U=A[0];if(/^set/.test(C)&&C!=="setTransform"){var V=C[3].toLowerCase()+C.slice(4),q;if(V==="fillStyle"||V==="strokeStyle"){if(U==="normal")q=sn(A[1]);else if(U==="linear"){var he=h.createLinearGradient(...A[1]);A[2].forEach(function(G){var re=G[0],le=sn(G[1]);he.addColorStop(re,le)}),q=he}else if(U==="radial"){var R=A[1],k=R[0],ee=R[1],ie=R[2],z=h.createRadialGradient(k,ee,0,k,ee,ie);A[2].forEach(function(G){var re=G[0],le=sn(G[1]);z.addColorStop(re,le)}),q=z}else if(U==="pattern"){var Z=o(A[1],b.slice(x+1),_,function(G){G&&(h[V]=h.createPattern(G,A[2]))});return Z?"continue":"break"}h[V]=q}else if(V==="globalAlpha")h[V]=Number(U)/255;else if(V==="shadow"){var ne=["shadowOffsetX","shadowOffsetY","shadowBlur","shadowColor"];A.forEach(function(G,re){h[ne[re]]=ne[re]==="shadowColor"?sn(G):G})}else if(V==="fontSize"){var we=h.__font__||h.font;h.__font__=h.font=we.replace(/\d+\.?\d*px/,U+"px")}else V==="lineDash"?(h.setLineDash(U),h.lineDashOffset=A[1]||0):V==="textBaseline"?(U==="normal"&&(A[0]="alphabetic"),h[V]=U):V==="font"?h.__font__=h.font=U:h[V]=U}else if(C==="fillPath"||C==="strokePath")C=C.replace(/Path/,""),h.beginPath(),A.forEach(function(G){h[G.method].apply(h,G.data)}),h[C]();else if(C==="fillText")h.fillText.apply(h,A);else if(C==="drawImage"){var se=function(){var G=[...A],re=G[0],le=G.slice(1);if(i=i||{},o(re,b.slice(x+1),_,function(Ce){Ce&&h.drawImage.apply(h,[Ce].concat([...le.slice(4,8)],[...le.slice(0,4)]))}))return"break"}();if(se==="break")return"break"}else C==="clip"?(A.forEach(function(G){h[G.method].apply(h,G.data)}),h.clip()):h[C].apply(h,A)},d=0;d{f.src=d}).catch(()=>{f.src=p})}})}function o(g,_,b,w){var p=i[g];return p.ready?(w(p),!0):(r.unshift([_,!0]),t.value=!0,p.onload=function(){p.ready=!0,w(p),t.value=!1;var h=r.slice(0);r=[];for(var f=h.shift();f;)a({actions:f[0],reserve:f[1]},b),f=h.shift()},!1)}function l(g,_){var{x:b=0,y:w=0,width:p,height:h,destWidth:f,destHeight:d,hidpi:y=!0,dataType:x,quality:T=1,type:C="png"}=g,A=e.value,U,V=A.offsetWidth-b;p=p?Math.min(p,V):V;var q=A.offsetHeight-w;h=h?Math.min(h,q):q,y?(f=p,d=h):!f&&!d?(f=Math.round(p*me),d=Math.round(h*me)):f?d||(d=Math.round(h/p*f)):f=Math.round(p/h*d);var he=xf(f,d),R=he.getContext("2d");(C==="jpeg"||C==="jpg")&&(C="jpeg",R.fillStyle="#fff",R.fillRect(0,0,f,d)),R.__hidpi__=!0,R.drawImageByCanvas(A,b,w,p,h,0,0,f,d,!1);var k;try{var ee;if(x==="base64")U=he.toDataURL("image/".concat(C),T);else{var ie=R.getImageData(0,0,f,d),z=require("pako");U=z.deflateRaw(ie.data,{to:"string"}),ee=!0}k={data:U,compressed:ee,width:f,height:d}}catch(Z){k={errMsg:"canvasGetImageData:fail ".concat(Z)}}if(he.height=he.width=0,R.__hidpi__=!1,_)_(k);else return k}function u(g,_){var{data:b,x:w,y:p,width:h,height:f,compressed:d}=g;try{f||(f=Math.round(b.length/4/h));var y=xf(h,f),x=y.getContext("2d");if(d){var T=require("pako");b=T.inflateRaw(b)}x.putImageData(new ImageData(new Uint8ClampedArray(b),h,f),0,0),e.value.getContext("2d").drawImage(y,w,p,h,f),y.height=y.width=0}catch(C){_({errMsg:"canvasPutImageData:fail"});return}_({errMsg:"canvasPutImageData:ok"})}function v(g,_){var{x:b=0,y:w=0,width:p,height:h,destWidth:f,destHeight:d,fileType:y,quality:x,dirname:T}=g,C=l({x:b,y:w,width:p,height:h,destWidth:f,destHeight:d,hidpi:!1,dataType:"base64",type:y,quality:x});if(!C.data||!C.data.length){_({errMsg:C.errMsg.replace("canvasPutImageData","toTempFilePath")});return}Em(C.data)}var c={actionsChanged:a,getImageData:l,putImageData:u,toTempFilePath:v};function m(g,_,b){var w=c[g];g.indexOf("_")!==0&&typeof w=="function"&&w(_,b)}return ue(c,{_resize:n,_handleSubscribe:m})}var Ef=Ji("ucg"),$0={name:{type:String,default:""}},U0=de({name:"CheckboxGroup",props:$0,emits:["change"],setup(e,t){var{emit:r,slots:i}=t,n=$(null),a=Ae(n,r);return W0(e,a),()=>O("uni-checkbox-group",{ref:n},[i.default&&i.default()],512)}});function W0(e,t){var r=[],i=()=>r.reduce((a,s)=>(s.value.checkboxChecked&&a.push(s.value.value),a),new Array);Ne(Ef,{addField(a){r.push(a)},removeField(a){r.splice(r.indexOf(a),1)},checkboxChange(a){t("change",a,{value:i()})}});var n=pe(ut,!1);return n&&n.addField({submit:()=>{var a=["",null];return e.name!==""&&(a[0]=e.name,a[1]=i()),a}}),i}var V0={checked:{type:[Boolean,String],default:!1},id:{type:String,default:""},disabled:{type:[Boolean,String],default:!1},color:{type:String,default:"#007aff"},value:{type:String,default:""}},H0=de({name:"Checkbox",props:V0,setup(e,t){var{slots:r}=t,i=$(e.checked),n=$(e.value);W([()=>e.checked,()=>e.value],u=>{var[v,c]=u;i.value=v,n.value=c});var a=()=>{i.value=!1},{uniCheckGroup:s,uniLabel:o}=j0(i,n,a),l=u=>{e.disabled||(i.value=!i.value,s&&s.checkboxChange(u))};return o&&(o.addHandler(l),xe(()=>{o.removeHandler(l)})),an(e,{"label-click":l}),()=>{var u=Fr(e,"disabled");return O("uni-checkbox",ze(u,{onClick:l}),[O("div",{class:"uni-checkbox-wrapper"},[O("div",{class:["uni-checkbox-input",{"uni-checkbox-input-disabled":e.disabled}]},[i.value?Qi(Zi,e.color,22):""],2),r.default&&r.default()])],16,["onClick"])}}});function j0(e,t,r){var i=Q(()=>({checkboxChecked:Boolean(e.value),value:t.value})),n={reset:r},a=pe(Ef,!1);a&&a.addField(i);var s=pe(ut,!1);s&&s.addField(n);var o=pe($r,!1);return xe(()=>{a&&a.removeField(i),s&&s.removeField(n)}),{uniCheckGroup:a,uniForm:s,uniLabel:o}}var Tf,Wr,on,Ot,ln,_s;Qt(()=>{Wr=plus.os.name==="Android",on=plus.os.version||""}),document.addEventListener("keyboardchange",function(e){Ot=e.height,ln&&ln()},!1);function Cf(){}function Vr(e,t,r){Qt(()=>{var i="adjustResize",n="adjustPan",a="nothing",s=plus.webview.currentWebview(),o=_s||s.getStyle()||{},l={mode:r||o.softinputMode===i?i:e.adjustPosition?n:a,position:{top:0,height:0}};if(l.mode===n){var u=t.getBoundingClientRect();l.position.top=u.top,l.position.height=u.height+(Number(e.cursorSpacing)||0)}s.setSoftinputTemporary(l)})}function z0(e,t){if(e.showConfirmBar==="auto"){delete t.softinputNavBar;return}Qt(()=>{var r=plus.webview.currentWebview(),{softinputNavBar:i}=r.getStyle()||{},n=i!=="none";n!==e.showConfirmBar?(t.softinputNavBar=i||"auto",r.setStyle({softinputNavBar:e.showConfirmBar?"auto":"none"})):delete t.softinputNavBar})}function Y0(e){var t=e.softinputNavBar;t&&Qt(()=>{var r=plus.webview.currentWebview();r.setStyle({softinputNavBar:t})})}var If={cursorSpacing:{type:[Number,String],default:0},showConfirmBar:{type:[Boolean,String],default:"auto"},adjustPosition:{type:[Boolean,String],default:!0},autoBlur:{type:[Boolean,String],default:!1}},Of=["keyboardheightchange"];function Af(e,t,r){var i={};function n(a){var s,o=()=>{r("keyboardheightchange",{},{height:Ot,duration:.25}),s&&Ot===0&&Vr(e,a),e.autoBlur&&s&&Ot===0&&(Wr||parseInt(on)>=13)&&document.activeElement.blur()};a.addEventListener("focus",()=>{s=!0,clearTimeout(Tf),document.addEventListener("click",Cf,!1),ln=o,Ot&&r("keyboardheightchange",{},{height:Ot,duration:0}),z0(e,i),Vr(e,a)}),Wr&&a.addEventListener("click",()=>{!e.disabled&&!e.readOnly&&s&&Ot===0&&Vr(e,a)}),Wr||(parseInt(on)<12&&a.addEventListener("touchstart",()=>{!e.disabled&&!e.readOnly&&!s&&Vr(e,a)}),parseFloat(on)>=14.6&&!_s&&Qt(()=>{var u=plus.webview.currentWebview();_s=u.getStyle()||{}}));var l=()=>{document.removeEventListener("click",Cf,!1),ln=null,Ot&&r("keyboardheightchange",{},{height:0,duration:0}),Y0(i),Wr&&(Tf=setTimeout(()=>{Vr(e,a,!0)},300)),String(navigator.vendor).indexOf("Apple")===0&&document.documentElement.scrollTo(document.documentElement.scrollLeft,document.documentElement.scrollTop)};a.addEventListener("blur",()=>{a.blur(),s=!1,l()})}W(()=>t.value,a=>n(a))}var Mf=/^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,Rf=/^<\/([-A-Za-z0-9_]+)[^>]*>/,q0=/([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g,X0=ur("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr"),K0=ur("a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video"),G0=ur("abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var"),J0=ur("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr"),Z0=ur("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected"),Q0=ur("script,style");function Pf(e,t){var r,i,n,a=[],s=e;for(a.last=function(){return this[this.length-1]};e;){if(i=!0,!a.last()||!Q0[a.last()]){if(e.indexOf(""),r>=0&&(t.comment&&t.comment(e.substring(4,r)),e=e.substring(r+3),i=!1)):e.indexOf("]*>"),function(v,c){return c=c.replace(/|/g,"$1$2"),t.chars&&t.chars(c),""}),u("",a.last());if(e==s)throw"Parse Error: "+e;s=e}u();function l(v,c,m,g){if(c=c.toLowerCase(),K0[c])for(;a.last()&&G0[a.last()];)u("",a.last());if(J0[c]&&a.last()==c&&u("",c),g=X0[c]||!!g,g||a.push(c),t.start){var _=[];m.replace(q0,function(b,w){var p=arguments[2]?arguments[2]:arguments[3]?arguments[3]:arguments[4]?arguments[4]:Z0[w]?w:"";_.push({name:w,value:p,escaped:p.replace(/(^|[^\\])"/g,'$1\\"')})}),t.start&&t.start(c,_,g)}}function u(v,c){if(c)for(var m=a.length-1;m>=0&&a[m]!=c;m--);else var m=0;if(m>=0){for(var g=a.length-1;g>=m;g--)t.end&&t.end(a[g]);a.length=m}}}function ur(e){for(var t={},r=e.split(","),i=0;is()),delete bs[t]}}n.push(r)}function e_(e){var t=e.import("blots/block/embed");class r extends t{}return r.blotName="divider",r.tagName="HR",{"formats/divider":r}}function t_(e){var t=e.import("blots/inline");class r extends t{}return r.blotName="ins",r.tagName="INS",{"formats/ins":r}}function r_(e){var{Scope:t,Attributor:r}=e.import("parchment"),i={scope:t.BLOCK,whitelist:["left","right","center","justify"]},n=new r.Style("align","text-align",i);return{"formats/align":n}}function i_(e){var{Scope:t,Attributor:r}=e.import("parchment"),i={scope:t.BLOCK,whitelist:["rtl"]},n=new r.Style("direction","direction",i);return{"formats/direction":n}}function n_(e){var t=e.import("parchment"),r=e.import("blots/container"),i=e.import("formats/list/item");class n extends r{static create(s){var o=s==="ordered"?"OL":"UL",l=super.create(o);return(s==="checked"||s==="unchecked")&&l.setAttribute("data-checked",s==="checked"),l}static formats(s){if(s.tagName==="OL")return"ordered";if(s.tagName==="UL")return s.hasAttribute("data-checked")?s.getAttribute("data-checked")==="true"?"checked":"unchecked":"bullet"}constructor(s){super(s);var o=l=>{if(l.target.parentNode===s){var u=this.statics.formats(s),v=t.find(l.target);u==="checked"?v.format("list","unchecked"):u==="unchecked"&&v.format("list","checked")}};s.addEventListener("click",o)}format(s,o){this.children.length>0&&this.children.tail.format(s,o)}formats(){return{[this.statics.blotName]:this.statics.formats(this.domNode)}}insertBefore(s,o){if(s instanceof i)super.insertBefore(s,o);else{var l=o==null?this.length():o.offset(this),u=this.split(l);u.parent.insertBefore(s,u)}}optimize(s){super.optimize(s);var o=this.next;o!=null&&o.prev===this&&o.statics.blotName===this.statics.blotName&&o.domNode.tagName===this.domNode.tagName&&o.domNode.getAttribute("data-checked")===this.domNode.getAttribute("data-checked")&&(o.moveChildren(this),o.remove())}replace(s){if(s.statics.blotName!==this.statics.blotName){var o=t.create(this.statics.defaultChild);s.moveChildren(o),this.appendChild(o)}super.replace(s)}}return n.blotName="list",n.scope=t.Scope.BLOCK_BLOT,n.tagName=["OL","UL"],n.defaultChild="list-item",n.allowedChildren=[i],{"formats/list":n}}function a_(e){var{Scope:t}=e.import("parchment"),r=e.import("formats/background"),i=new r.constructor("backgroundColor","background-color",{scope:t.INLINE});return{"formats/backgroundColor":i}}function s_(e){var{Scope:t,Attributor:r}=e.import("parchment"),i={scope:t.BLOCK},n=["margin","marginTop","marginBottom","marginLeft","marginRight"],a=["padding","paddingTop","paddingBottom","paddingLeft","paddingRight"],s={};return n.concat(a).forEach(o=>{s["formats/".concat(o)]=new r.Style(o,Ve(o),i)}),s}function o_(e){var{Scope:t,Attributor:r}=e.import("parchment"),i={scope:t.INLINE},n=["font","fontSize","fontStyle","fontVariant","fontWeight","fontFamily"],a={};return n.forEach(s=>{a["formats/".concat(s)]=new r.Style(s,Ve(s),i)}),a}function l_(e){var{Scope:t,Attributor:r}=e.import("parchment"),i=[{name:"lineHeight",scope:t.BLOCK},{name:"letterSpacing",scope:t.INLINE},{name:"textDecoration",scope:t.INLINE},{name:"textIndent",scope:t.BLOCK}],n={};return i.forEach(a=>{var{name:s,scope:o}=a;n["formats/".concat(s)]=new r.Style(s,Ve(s),{scope:o})}),n}function u_(e){var t=e.import("formats/image"),r=["alt","height","width","data-custom","class","data-local"];t.sanitize=n=>n&&tt(n),t.formats=function(a){return r.reduce(function(s,o){return a.hasAttribute(o)&&(s[o]=a.getAttribute(o)),s},{})};var i=t.prototype.format;t.prototype.format=function(n,a){r.indexOf(n)>-1?a?this.domNode.setAttribute(n,a):this.domNode.removeAttribute(n):i.call(this,n,a)}}function f_(e){var t=e.import("formats/link");t.sanitize=r=>{var i=document.createElement("a");i.href=r;var n=i.href.slice(0,i.href.indexOf(":"));return t.PROTOCOL_WHITELIST.concat("file").indexOf(n)>-1?r:t.SANITIZED_URL}}function c_(e){var t={divider:e_,ins:t_,align:r_,direction:i_,list:n_,background:a_,box:s_,font:o_,text:l_,image:u_,link:f_},r={};Object.values(t).forEach(i=>ue(r,i(e))),e.register(r,!0)}function v_(e,t,r){var i,n,a,s=!1;W(()=>e.readOnly,_=>{i&&(a.enable(!_),_||a.blur())}),W(()=>e.placeholder,_=>{i&&u(_)});function o(_){var b=["span","strong","b","ins","em","i","u","a","del","s","sub","sup","img","div","p","h1","h2","h3","h4","h5","h6","hr","ol","ul","li","br"],w="",p;Pf(_,{start:function(f,d,y){if(!b.includes(f)){p=!y;return}p=!1;var x=d.map(C=>{var{name:A,value:U}=C;return"".concat(A,'="').concat(U,'"')}).join(" "),T="<".concat(f," ").concat(x," ").concat(y?"/":"",">");w+=T},end:function(f){p||(w+=""))},chars:function(f){p||(w+=f)}}),n=!0;var h=a.clipboard.convert(w);return n=!1,h}function l(){var _=a.root.innerHTML,b=a.getText(),w=a.getContents();return{html:_,text:b,delta:w}}function u(_){var b="data-placeholder",w=a.root;w.getAttribute(b)!==_&&w.setAttribute(b,_)}var v={};function c(_){var b=_?a.getFormat(_):{},w=Object.keys(b);(w.length!==Object.keys(v).length||w.find(p=>b[p]!==v[p]))&&(v=b,r("statuschange",{},b))}function m(_){var b=window.Quill;c_(b);var w={toolbar:!1,readOnly:e.readOnly,placeholder:e.placeholder};_.length&&(b.register("modules/ImageResize",window.ImageResize.default),w.modules={ImageResize:{modules:_}});var p=t.value;a=new b(p,w);var h=a.root,f=["focus","blur","input"];f.forEach(d=>{h.addEventListener(d,y=>{var x=l();if(d==="input"){if(Vu().platform==="ios"){var T=(x.html.match(/([\s\S]*)<\/span>/)||[])[1],C=T&&T.replace(/\s/g,"")?"":e.placeholder;u(C)}y.stopPropagation()}else r(d,y,x)})}),a.on("text-change",()=>{s||r("input",{},l())}),a.on("selection-change",c),a.on("scroll-optimize",()=>{var d=a.selection.getRange()[0];c(d)}),a.clipboard.addMatcher(Node.ELEMENT_NODE,(d,y)=>(n||y.ops&&(y.ops=y.ops.filter(x=>{var{insert:T}=x;return typeof T=="string"}).map(x=>{var{insert:T}=x;return{insert:T}})),y)),i=!0,r("ready",{},{})}Oe(()=>{var _=[];e.showImgSize&&_.push("DisplaySize"),e.showImgToolbar&&_.push("Toolbar"),e.showImgResize&&_.push("Resize");var b="./__uniappquill.js";Lf(window.Quill,b,()=>{if(_.length){var w="./__uniappquillimageresize.js";Lf(window.ImageResize,w,()=>{m(_)})}else m(_)})});var g=_n();mn((_,b,w)=>{var{options:p,callbackId:h}=b,f,d,y;if(i){var x=window.Quill;switch(_){case"format":{var{name:T="",value:C=!1}=p;d=a.getSelection(!0);var A=a.getFormat(d)[T]||!1;if(["bold","italic","underline","strike","ins"].includes(T))C=!A;else if(T==="direction"){C=C==="rtl"&&A?!1:C;var U=a.getFormat(d).align;C==="rtl"&&!U?a.format("align","right","user"):!C&&U==="right"&&a.format("align",!1,"user")}else if(T==="indent"){var V=a.getFormat(d).direction==="rtl";C=C==="+1",V&&(C=!C),C=C?"+1":"-1"}else T==="list"&&(C=C==="check"?"unchecked":C,A=A==="checked"?"unchecked":A),C=A&&A!==(C||!1)||!A&&C?C:!A;a.format(T,C,"user")}break;case"insertDivider":d=a.getSelection(!0),a.insertText(d.index,wr,"user"),a.insertEmbed(d.index+1,"divider",!0,"user"),a.setSelection(d.index+2,0,"silent");break;case"insertImage":{d=a.getSelection(!0);var{src:q="",alt:he="",width:R="",height:k="",extClass:ee="",data:ie={}}=p,z=tt(q);a.insertEmbed(d.index,"image",z,"user");var Z=/^(file|blob):/.test(z)?z:!1;s=!0,a.formatText(d.index,1,"data-local",Z),a.formatText(d.index,1,"alt",he),a.formatText(d.index,1,"width",R),a.formatText(d.index,1,"height",k),a.formatText(d.index,1,"class",ee),s=!1,a.formatText(d.index,1,"data-custom",Object.keys(ie).map(re=>"".concat(re,"=").concat(ie[re])).join("&")),a.setSelection(d.index+1,0,"silent")}break;case"insertText":{d=a.getSelection(!0);var{text:ne=""}=p;a.insertText(d.index,ne,"user"),a.setSelection(d.index+ne.length,0,"silent")}break;case"setContents":{var{delta:we,html:se}=p;typeof we=="object"?a.setContents(we,"silent"):typeof se=="string"?a.setContents(o(se),"silent"):y="contents is missing"}break;case"getContents":f=l();break;case"clear":a.setText("");break;case"removeFormat":{d=a.getSelection(!0);var G=x.import("parchment");d.length?a.removeFormat(d.index,d.length,"user"):Object.keys(a.getFormat(d)).forEach(re=>{G.query(re,G.Scope.INLINE)&&a.format(re,!1)})}break;case"undo":a.history.undo();break;case"redo":a.history.redo();break;case"blur":a.blur();break;case"getSelectionText":d=a.selection.savedRange,f={text:""},d&&d.length!==0&&(f.text=a.getText(d.index,d.length));break;case"scrollIntoView":a.scrollIntoView();break}c(d)}else y="not ready";h&&w({callbackId:h,data:ue({},f,{errMsg:"".concat(_,":").concat(y?"fail "+y:"ok")})})},g,!0)}var d_=ue({},If,{id:{type:String,default:""},readOnly:{type:[Boolean,String],default:!1},placeholder:{type:String,default:""},showImgSize:{type:[Boolean,String],default:!1},showImgToolbar:{type:[Boolean,String],default:!1},showImgResize:{type:[Boolean,String],default:!1}}),h_=de({name:"Editor",props:d_,emit:["ready","focus","blur","input","statuschange",...Of],setup(e,t){var{emit:r}=t,i=$(null),n=Ae(i,r);return v_(e,i,n),Af(e,i,n),()=>O("uni-editor",{ref:i,id:e.id,class:"ql-container"},null,8,["id"])}}),Nf="#10aeff",g_="#f76260",Df="#b2b2b2",p_="#f43530",m_={success:{d:Wp,c:wi},success_no_circle:{d:Zi,c:wi},info:{d:$p,c:Nf},warn:{d:Hp,c:g_},waiting:{d:Vp,c:Nf},cancel:{d:kp,c:p_},download:{d:Fp,c:wi},search:{d:Up,c:Df},clear:{d:Bp,c:Df}},__=de({name:"Icon",props:{type:{type:String,required:!0,default:""},size:{type:[String,Number],default:23},color:{type:String,default:""}},setup(e){var t=Q(()=>m_[e.type]);return()=>{var{value:r}=t;return O("uni-icon",null,[r&&r.d&&Qi(r.d,e.color||r.c,Wt(e.size))])}}}),b_={src:{type:String,default:""},mode:{type:String,default:"scaleToFill"},lazyLoad:{type:[Boolean,String],default:!1},draggable:{type:Boolean,default:!0}},un={widthFix:["offsetWidth","height"],heightFix:["offsetHeight","width"]},w_={aspectFit:["center center","contain"],aspectFill:["center center","cover"],widthFix:[,"100% 100%"],heightFix:[,"100% 100%"],top:["center top"],bottom:["center bottom"],center:["center center"],left:["left center"],right:["right center"],"top left":["left top"],"top right":["right top"],"bottom left":["left bottom"],"bottom right":["right bottom"]},y_=de({name:"Image",props:b_,setup(e,t){var{emit:r}=t,i=$(null),n=S_(i,e),a=Ae(i,r),{fixSize:s}=C_(i,e,n);return x_(n,s,a),()=>{var{mode:o}=e,{imgSrc:l,modeStyle:u,src:v}=n,c;return c=l?O("img",{src:l,draggable:e.draggable},null,8,["src","draggable"]):O("img",null,null),O("uni-image",{ref:i},[O("div",{style:u},null,4),c,un[o]?O(Ht,{onResize:s},null,8,["onResize"]):O("span",null,null)],512)}}});function S_(e,t){var r=$(""),i=Q(()=>{var a="auto",s="",o=w_[t.mode];return o?(o[0]&&(s=o[0]),o[1]&&(a=o[1])):(s="0% 0%",a="100% 100%"),"background-image:".concat(r.value?'url("'+r.value+'")':"none",";background-position:").concat(s,";background-size:").concat(a,";")}),n=Te({rootEl:e,src:Q(()=>t.src?tt(t.src):""),origWidth:0,origHeight:0,origStyle:{width:"",height:""},modeStyle:i,imgSrc:r});return Oe(()=>{var a=e.value,s=a.style;n.origWidth=Number(s.width)||0,n.origHeight=Number(s.height)||0}),n}function x_(e,t,r){var i,n=function(){var o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"";e.origWidth=o,e.origHeight=l,e.imgSrc=u},a=o=>{if(!o){s(),n();return}i=i||new Image,i.onload=l=>{var{width:u,height:v}=i;n(u,v,o),t(),s(),r("load",l,{width:u,height:v})},i.onerror=l=>{n(),s(),r("error",l,{errMsg:"GET ".concat(e.src," 404 (Not Found)")})},i.src=o},s=()=>{i&&(i.onload=null,i.onerror=null,i=null)};W(()=>e.src,o=>a(o)),Oe(()=>a(e.src)),xe(()=>s())}var E_=navigator.vendor==="Google Inc.";function T_(e){return E_&&e>10&&(e=Math.round(e/2)*2),e}function C_(e,t,r){var i=()=>{var{mode:a}=t,s=un[a];if(!!s){var{origWidth:o,origHeight:l}=r,u=o&&l?o/l:0;if(!!u){var v=e.value,c=v[s[0]];c&&(v.style[s[1]]=T_(c/u)+"px"),window.dispatchEvent(new CustomEvent("updateview"))}}},n=()=>{var{style:a}=e.value,{origStyle:{width:s,height:o}}=r;a.width=s,a.height=o};return W(()=>t.mode,(a,s)=>{un[s]&&n(),un[a]&&i()}),{fixSize:i,resetSize:n}}function I_(e,t){var r=0,i,n,a=function(){for(var s=arguments.length,o=new Array(s),l=0;l{n=null,r=u,e.apply(this,o)},u-rfn.forEach(t=>t.userAction=e);function A_(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userAction:!1};if(!kf){var t=["touchstart","touchmove","touchend","mousedown","mouseup"];t.forEach(r=>{document.addEventListener(r,function(){!ws&&Bf(!0),ws++,setTimeout(()=>{!--ws&&Bf(!1)},0)},O_)}),kf=!0}fn.push(e)}function M_(e){var t=fn.indexOf(e);t>=0&&fn.splice(t,1)}function R_(){var e=Te({userAction:!1});return Oe(()=>{A_(e)}),xe(()=>{M_(e)}),{state:e}}function Ff(){var e=Te({attrs:{}});return Oe(()=>{for(var t=xt();t;){var r=t.type.__scopeId;r&&(e.attrs[r]=""),t=t.proxy&&t.proxy.$mpType==="page"?null:t.parent}}),{state:e}}function P_(e,t){var r=pe(ut,!1);if(!!r){var i=xt(),n={submit(){var a=i.proxy;return[a[e],typeof t=="string"?a[t]:t.value]},reset(){typeof t=="string"?i.proxy[t]="":t.value=""}};r.addField(n),xe(()=>{r.removeField(n)})}}function L_(e,t){var r=document.activeElement;if(!r)return t({});var i={};["input","textarea"].includes(r.tagName.toLowerCase())&&(i.start=r.selectionStart,i.end=r.selectionEnd),t(i)}var N_=function(){at(Ct(),"getSelectedTextRange",L_)},D_=200,ys;function Ss(e){return e===null?"":String(e)}var $f=ue({},{name:{type:String,default:""},modelValue:{type:[String,Number],default:""},value:{type:[String,Number],default:""},disabled:{type:[Boolean,String],default:!1},autoFocus:{type:[Boolean,String],default:!1},focus:{type:[Boolean,String],default:!1},cursor:{type:[Number,String],default:-1},selectionStart:{type:[Number,String],default:-1},selectionEnd:{type:[Number,String],default:-1},type:{type:String,default:"text"},password:{type:[Boolean,String],default:!1},placeholder:{type:String,default:""},placeholderStyle:{type:String,default:""},placeholderClass:{type:String,default:""},maxlength:{type:[Number,String],default:140},confirmType:{type:String,default:"done"}},If),Uf=["input","focus","blur","update:value","update:modelValue","update:focus",...Of];function k_(e,t,r){var i=$(null),n=Ae(t,r),a=Q(()=>{var c=Number(e.selectionStart);return isNaN(c)?-1:c}),s=Q(()=>{var c=Number(e.selectionEnd);return isNaN(c)?-1:c}),o=Q(()=>{var c=Number(e.cursor);return isNaN(c)?-1:c}),l=Q(()=>{var c=Number(e.maxlength);return isNaN(c)?140:c}),u=Ss(e.modelValue)||Ss(e.value),v=Te({value:u,valueOrigin:u,maxlength:l,focus:e.focus,composing:!1,selectionStart:a,selectionEnd:s,cursor:o});return W(()=>v.focus,c=>r("update:focus",c)),W(()=>v.maxlength,c=>v.value=v.value.slice(0,c)),{fieldRef:i,state:v,trigger:n}}function B_(e,t,r,i){var n=Vd(o=>{t.value=Ss(o)},100);W(()=>e.modelValue,n),W(()=>e.value,n);var a=I_((o,l)=>{n.cancel(),r("update:modelValue",l.value),r("update:value",l.value),i("input",o,l)},100),s=(o,l,u)=>{n.cancel(),a(o,l),u&&a.flush()};return Wl(()=>{n.cancel(),a.cancel()}),{trigger:i,triggerInput:s}}function F_(e,t){var{state:r}=R_(),i=Q(()=>e.autoFocus||e.focus);function n(){if(!!i.value){var s=t.value;if(!s||!("plus"in window)){setTimeout(n,100);return}{var o=D_-(Date.now()-ys);if(o>0){setTimeout(n,o);return}s.focus(),r.userAction||plus.key.showSoftKeybord()}}}function a(){var s=t.value;s&&s.blur()}W(()=>e.focus,s=>{s?n():a()}),Oe(()=>{ys=ys||Date.now(),i.value&&sr(n)})}function $_(e,t,r,i,n){function a(){var l=e.value;l&&t.focus&&t.selectionStart>-1&&t.selectionEnd>-1&&(l.selectionStart=t.selectionStart,l.selectionEnd=t.selectionEnd)}function s(){var l=e.value;l&&t.focus&&t.selectionStart<0&&t.selectionEnd<0&&t.cursor>-1&&(l.selectionEnd=l.selectionStart=t.cursor)}function o(){var l=e.value,u=function(m){t.focus=!0,r("focus",m,{value:t.value}),a(),s()},v=function(m,g){m.stopPropagation(),!(typeof n=="function"&&n(m,t)===!1)&&(t.value=l.value,t.composing||i(m,{value:l.value,cursor:l.selectionEnd},g))},c=function(m){t.composing&&(t.composing=!1,v(m,!0)),t.focus=!1,r("blur",m,{value:t.value,cursor:m.target.selectionEnd})};l.addEventListener("change",m=>m.stopPropagation()),l.addEventListener("focus",u),l.addEventListener("blur",c),l.addEventListener("input",v),l.addEventListener("compositionstart",m=>{m.stopPropagation(),t.composing=!0}),l.addEventListener("compositionend",m=>{m.stopPropagation(),t.composing&&(t.composing=!1,v(m))})}W([()=>t.selectionStart,()=>t.selectionEnd],a),W(()=>t.cursor,s),W(()=>e.value,o)}function Wf(e,t,r,i){N_();var{fieldRef:n,state:a,trigger:s}=k_(e,t,r),{triggerInput:o}=B_(e,a,r,s);F_(e,n),Af(e,n,s);var{state:l}=Ff();P_("name",a),$_(n,a,s,o,i);var u=String(navigator.vendor).indexOf("Apple")===0&&CSS.supports("image-orientation:from-image");return{fieldRef:n,state:a,scopedAttrsState:l,fixDisabledColor:u,trigger:s}}var U_=ue({},$f,{placeholderClass:{type:String,default:"input-placeholder"},textContentType:{type:String,default:""}}),W_=de({name:"Input",props:U_,emits:["confirm",...Uf],setup(e,t){var{emit:r}=t,i=["text","number","idcard","digit","password","tel"],n=["off","one-time-code"],a=Q(()=>{var h="";switch(e.type){case"text":e.confirmType==="search"&&(h="search");break;case"idcard":h="text";break;case"digit":h="number";break;default:h=~i.includes(e.type)?e.type:"text";break}return e.password?"password":h}),s=Q(()=>{var h=n.indexOf(e.textContentType),f=n.indexOf(Ve(e.textContentType)),d=h!==-1?h:f!==-1?f:0;return n[d]}),o=$(""),l,u=$(null),{fieldRef:v,state:c,scopedAttrsState:m,fixDisabledColor:g,trigger:_}=Wf(e,u,r,(h,f)=>{var d=h.target;if(a.value==="number"){if(l&&(d.removeEventListener("blur",l),l=null),d.validity&&!d.validity.valid)return!o.value&&h.data==="-"||o.value[0]==="-"&&h.inputType==="deleteContentBackward"?(o.value="-",f.value="",l=()=>{o.value=d.value=""},d.addEventListener("blur",l),!1):(o.value=f.value=d.value=o.value==="-"?"":o.value,!1);o.value=d.value;var y=f.maxlength;if(y>0&&d.value.length>y)return d.value=d.value.slice(0,y),f.value=d.value,!1}}),b=["number","digit"],w=Q(()=>b.includes(e.type)?"0.000000000000000001":"");function p(h){h.key==="Enter"&&(h.stopPropagation(),_("confirm",h,{value:h.target.value}))}return()=>{var h=e.disabled&&g?O("input",{ref:v,value:c.value,tabindex:"-1",readonly:!!e.disabled,type:a.value,maxlength:c.maxlength,step:w.value,class:"uni-input-input",onFocus:f=>f.target.blur()},null,40,["value","readonly","type","maxlength","step","onFocus"]):O("input",{ref:v,value:c.value,disabled:!!e.disabled,type:a.value,maxlength:c.maxlength,step:w.value,enterkeyhint:e.confirmType,pattern:e.type==="number"?"[0-9]*":void 0,class:"uni-input-input",autocomplete:s.value,onKeyup:p},null,40,["value","disabled","type","maxlength","step","enterkeyhint","pattern","autocomplete","onKeyup"]);return O("uni-input",{ref:u},[O("div",{class:"uni-input-wrapper"},[Ir(O("div",ze(m.attrs,{style:e.placeholderStyle,class:["uni-input-placeholder",e.placeholderClass]}),[e.placeholder],16),[[Dr,!(c.value.length||o.value==="-")]]),e.confirmType==="search"?O("form",{action:"",onSubmit:f=>f.preventDefault(),class:"uni-input-form"},[h],40,["onSubmit"]):h])],512)}}});function V_(e){return Object.keys(e).map(t=>[t,e[t]])}var H_=["class","style"],j_=/^on[A-Z]+/,Vf=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{excludeListeners:t=!1,excludeKeys:r=[]}=e,i=xt(),n=Ma({}),a=Ma({}),s=Ma({}),o=r.concat(H_);return i.attrs=Te(i.attrs),Qg(()=>{var l=V_(i.attrs).reduce((u,v)=>{var[c,m]=v;return o.includes(c)?u.exclude[c]=m:j_.test(c)?(t||(u.attrs[c]=m),u.listeners[c]=m):u.attrs[c]=m,u},{exclude:{},attrs:{},listeners:{}});n.value=l.attrs,a.value=l.listeners,s.value=l.exclude}),{$attrs:n,$listeners:a,$excludeAttrs:s}},cn,Hr;function vn(){Qt(()=>{cn||(cn=plus.webview.currentWebview()),Hr||(Hr=(cn.getStyle()||{}).pullToRefresh||{})})}function At(e){var{disable:t}=e;Hr&&Hr.support&&cn.setPullToRefresh(Object.assign({},Hr,{support:!t}))}function xs(e){var t=[];return Array.isArray(e)&&e.forEach(r=>{Fi(r)?r.type===ot?t.push(...xs(r.children)):t.push(r):Array.isArray(r)&&t.push(...xs(r))}),t}function jr(e){var t=xt();t.rebuild=e}var z_={scaleArea:{type:Boolean,default:!1}},Y_=de({inheritAttrs:!1,name:"MovableArea",props:z_,setup(e,t){var{slots:r}=t,i=$(null),n=$(!1),{setContexts:a,events:s}=q_(e,i),{$listeners:o,$attrs:l,$excludeAttrs:u}=Vf(),v=o.value,c=["onTouchstart","onTouchmove","onTouchend"];c.forEach(p=>{var h=v[p],f=s["_".concat(p)];v[p]=h?[].concat(h,f):f}),Oe(()=>{s._resize(),vn(),n.value=!0});var m=[],g=[];function _(){for(var p=[],h=function(d){var y=m[d];y instanceof Element||(y=y.el);var x=g.find(T=>y===T.rootRef.value);x&&p.push(Ni(x))},f=0;f{m=i.value.children,_()});var b=p=>{g.push(p),_()},w=p=>{var h=g.indexOf(p);h>=0&&(g.splice(h,1),_())};return Ne("_isMounted",n),Ne("movableAreaRootRef",i),Ne("addMovableViewContext",b),Ne("removeMovableViewContext",w),()=>(r.default&&r.default(),O("uni-movable-area",ze({ref:i},l.value,u.value,v),[O(Ht,{onReize:s._resize},null,8,["onReize"]),m],16))}});function Hf(e){return Math.sqrt(e.x*e.x+e.y*e.y)}function q_(e,t){var r=$(0),i=$(0),n=Te({x:null,y:null}),a=$(null),s=null,o=[];function l(b){b&&b!==1&&(e.scaleArea?o.forEach(function(w){w._setScale(b)}):s&&s._setScale(b))}function u(b){var w=arguments.length>1&&arguments[1]!==void 0?arguments[1]:o,p=t.value;function h(f){for(var d=0;d{At({disable:!0});var w=b.touches;if(w&&w.length>1){var p={x:w[1].pageX-w[0].pageX,y:w[1].pageY-w[0].pageY};if(a.value=Hf(p),n.x=p.x,n.y=p.y,!e.scaleArea){var h=u(w[0].target),f=u(w[1].target);s=h&&h===f?h:null}}}),c=Vt(b=>{var w=b.touches;if(w&&w.length>1){b.preventDefault();var p={x:w[1].pageX-w[0].pageX,y:w[1].pageY-w[0].pageY};if(n.x!==null&&a.value&&a.value>0){var h=Hf(p)/a.value;l(h)}n.x=p.x,n.y=p.y}}),m=Vt(b=>{At({disable:!1});var w=b.touches;w&&w.length||b.changedTouches&&(n.x=0,n.y=0,a.value=null,e.scaleArea?o.forEach(function(p){p._endScale()}):s&&s._endScale())});function g(){_(),o.forEach(function(b,w){b.setParent()})}function _(){var b=window.getComputedStyle(t.value),w=t.value.getBoundingClientRect();r.value=w.width-["Left","Right"].reduce(function(p,h){var f="border"+h+"Width",d="padding"+h;return p+parseFloat(b[f])+parseFloat(b[d])},0),i.value=w.height-["Top","Bottom"].reduce(function(p,h){var f="border"+h+"Width",d="padding"+h;return p+parseFloat(b[f])+parseFloat(b[d])},0)}return Ne("movableAreaWidth",r),Ne("movableAreaHeight",i),{setContexts(b){o=b},events:{_onTouchstart:v,_onTouchmove:c,_onTouchend:m,_resize:g}}}var zr=function(e,t,r,i){e.addEventListener(t,n=>{typeof r=="function"&&r(n)===!1&&((typeof n.cancelable!="undefined"?n.cancelable:!0)&&n.preventDefault(),n.stopPropagation())},{passive:!1})},jf,zf;function dn(e,t,r){xe(()=>{document.removeEventListener("mousemove",jf),document.removeEventListener("mouseup",zf)});var i=0,n=0,a=0,s=0,o=function(g,_,b,w){if(t({target:g.target,currentTarget:g.currentTarget,preventDefault:g.preventDefault.bind(g),stopPropagation:g.stopPropagation.bind(g),touches:g.touches,changedTouches:g.changedTouches,detail:{state:_,x:b,y:w,dx:b-i,dy:w-n,ddx:b-a,ddy:w-s,timeStamp:g.timeStamp}})===!1)return!1},l=null,u,v;zr(e,"touchstart",function(g){if(u=!0,g.touches.length===1&&!l)return l=g,i=a=g.touches[0].pageX,n=s=g.touches[0].pageY,o(g,"start",i,n)}),zr(e,"mousedown",function(g){if(v=!0,!u&&!l)return l=g,i=a=g.pageX,n=s=g.pageY,o(g,"start",i,n)}),zr(e,"touchmove",function(g){if(g.touches.length===1&&l){var _=o(g,"move",g.touches[0].pageX,g.touches[0].pageY);return a=g.touches[0].pageX,s=g.touches[0].pageY,_}});var c=jf=function(g){if(!u&&v&&l){var _=o(g,"move",g.pageX,g.pageY);return a=g.pageX,s=g.pageY,_}};document.addEventListener("mousemove",c),zr(e,"touchend",function(g){if(g.touches.length===0&&l)return u=!1,l=null,o(g,"end",g.changedTouches[0].pageX,g.changedTouches[0].pageY)});var m=zf=function(g){if(v=!1,!u&&l)return l=null,o(g,"end",g.pageX,g.pageY)};document.addEventListener("mouseup",m),zr(e,"touchcancel",function(g){if(l){u=!1;var _=l;return l=null,o(g,r?"cancel":"end",_.touches[0].pageX,_.touches[0].pageY)}})}function hn(e,t,r){return e>t-r&&ethis._t&&(e=this._t,this._lastDt=e);var t=this._x_v*e+.5*this._x_a*Math.pow(e,2)+this._x_s,r=this._y_v*e+.5*this._y_a*Math.pow(e,2)+this._y_s;return(this._x_a>0&&tthis._endPositionX)&&(t=this._endPositionX),(this._y_a>0&&rthis._endPositionY)&&(r=this._endPositionY),{x:t,y:r}},ft.prototype.ds=function(e){return e===void 0&&(e=(new Date().getTime()-this._startTime)/1e3),e>this._t&&(e=this._t),{dx:this._x_v+this._x_a*e,dy:this._y_v+this._y_a*e}},ft.prototype.delta=function(){return{x:-1.5*Math.pow(this._x_v,2)/this._x_a||0,y:-1.5*Math.pow(this._y_v,2)/this._y_a||0}},ft.prototype.dt=function(){return-this._x_v/this._x_a},ft.prototype.done=function(){var e=hn(this.s().x,this._endPositionX)||hn(this.s().y,this._endPositionY)||this._lastDt===this._t;return this._lastDt=null,e},ft.prototype.setEnd=function(e,t){this._endPositionX=e,this._endPositionY=t},ft.prototype.reconfigure=function(e,t){this._m=e,this._f=1e3*t};function qe(e,t,r){this._m=e,this._k=t,this._c=r,this._solution=null,this._endPosition=0,this._startTime=0}qe.prototype._solve=function(e,t){var r=this._c,i=this._m,n=this._k,a=r*r-4*i*n;if(a===0){var s=-r/(2*i),o=e,l=t/(s*e);return{x:function(p){return(o+l*p)*Math.pow(Math.E,s*p)},dx:function(p){var h=Math.pow(Math.E,s*p);return s*(o+l*p)*h+l*h}}}if(a>0){var u=(-r-Math.sqrt(a))/(2*i),v=(-r+Math.sqrt(a))/(2*i),c=(t-u*e)/(v-u),m=e-c;return{x:function(p){var h,f;return p===this._t&&(h=this._powER1T,f=this._powER2T),this._t=p,h||(h=this._powER1T=Math.pow(Math.E,u*p)),f||(f=this._powER2T=Math.pow(Math.E,v*p)),m*h+c*f},dx:function(p){var h,f;return p===this._t&&(h=this._powER1T,f=this._powER2T),this._t=p,h||(h=this._powER1T=Math.pow(Math.E,u*p)),f||(f=this._powER2T=Math.pow(Math.E,v*p)),m*u*h+c*v*f}}}var g=Math.sqrt(4*i*n-r*r)/(2*i),_=-r/2*i,b=e,w=(t-_*e)/g;return{x:function(p){return Math.pow(Math.E,_*p)*(b*Math.cos(g*p)+w*Math.sin(g*p))},dx:function(p){var h=Math.pow(Math.E,_*p),f=Math.cos(g*p),d=Math.sin(g*p);return h*(w*g*f-b*g*d)+_*h*(w*d+b*f)}}},qe.prototype.x=function(e){return e===void 0&&(e=(new Date().getTime()-this._startTime)/1e3),this._solution?this._endPosition+this._solution.x(e):0},qe.prototype.dx=function(e){return e===void 0&&(e=(new Date().getTime()-this._startTime)/1e3),this._solution?this._solution.dx(e):0},qe.prototype.setEnd=function(e,t,r){if(r||(r=new Date().getTime()),e!==this._endPosition||!jt(t,.1)){t=t||0;var i=this._endPosition;this._solution&&(jt(t,.1)&&(t=this._solution.dx((r-this._startTime)/1e3)),i=this._solution.x((r-this._startTime)/1e3),jt(t,.1)&&(t=0),jt(i,.1)&&(i=0),i+=this._endPosition),this._solution&&jt(i-e,.1)&&jt(t,.1)||(this._endPosition=e,this._solution=this._solve(i-this._endPosition,t),this._startTime=r)}},qe.prototype.snap=function(e){this._startTime=new Date().getTime(),this._endPosition=e,this._solution={x:function(){return 0},dx:function(){return 0}}},qe.prototype.done=function(e){return e||(e=new Date().getTime()),hn(this.x(),this._endPosition,.1)&&jt(this.dx(),.1)},qe.prototype.reconfigure=function(e,t,r){this._m=e,this._k=t,this._c=r,this.done()||(this._solution=this._solve(this.x()-this._endPosition,this.dx()),this._startTime=new Date().getTime())},qe.prototype.springConstant=function(){return this._k},qe.prototype.damping=function(){return this._c},qe.prototype.configuration=function(){function e(r,i){r.reconfigure(1,i,r.damping())}function t(r,i){r.reconfigure(1,r.springConstant(),i)}return[{label:"Spring Constant",read:this.springConstant.bind(this),write:e.bind(this,this),min:100,max:1e3},{label:"Damping",read:this.damping.bind(this),write:t.bind(this,this),min:1,max:500}]};function Yr(e,t,r){this._springX=new qe(e,t,r),this._springY=new qe(e,t,r),this._springScale=new qe(e,t,r),this._startTime=0}Yr.prototype.setEnd=function(e,t,r,i){var n=new Date().getTime();this._springX.setEnd(e,i,n),this._springY.setEnd(t,i,n),this._springScale.setEnd(r,i,n),this._startTime=n},Yr.prototype.x=function(){var e=(new Date().getTime()-this._startTime)/1e3;return{x:this._springX.x(e),y:this._springY.x(e),scale:this._springScale.x(e)}},Yr.prototype.done=function(){var e=new Date().getTime();return this._springX.done(e)&&this._springY.done(e)&&this._springScale.done(e)},Yr.prototype.reconfigure=function(e,t,r){this._springX.reconfigure(e,t,r),this._springY.reconfigure(e,t,r),this._springScale.reconfigure(e,t,r)};var X_={direction:{type:String,default:"none"},inertia:{type:[Boolean,String],default:!1},outOfBounds:{type:[Boolean,String],default:!1},x:{type:[Number,String],default:0},y:{type:[Number,String],default:0},damping:{type:[Number,String],default:20},friction:{type:[Number,String],default:2},disabled:{type:[Boolean,String],default:!1},scale:{type:[Boolean,String],default:!1},scaleMin:{type:[Number,String],default:.5},scaleMax:{type:[Number,String],default:10},scaleValue:{type:[Number,String],default:1},animation:{type:[Boolean,String],default:!0}},K_=de({name:"MovableView",props:X_,emits:["change","scale"],setup(e,t){var{slots:r,emit:i}=t,n=$(null),a=Ae(n,i),{setParent:s}=G_(e,a,n);return()=>O("uni-movable-view",{ref:n},[O(Ht,{onResize:s},null,8,["onResize"]),r.default&&r.default()],512)}}),Ts=!1;function Yf(e){Ts||(Ts=!0,requestAnimationFrame(function(){e(),Ts=!1}))}function qf(e,t){if(e===t)return 0;var r=e.offsetLeft;return e.offsetParent?r+=qf(e.offsetParent,t):0}function Xf(e,t){if(e===t)return 0;var r=e.offsetTop;return e.offsetParent?r+=Xf(e.offsetParent,t):0}function Kf(e,t){return+((1e3*e-1e3*t)/1e3).toFixed(1)}function Gf(e,t,r){var i={id:0,cancelled:!1},n=function(s){s&&s.id&&cancelAnimationFrame(s.id),s&&(s.cancelled=!0)};function a(s,o,l,u){if(!s||!s.cancelled){l(o);var v=o.done();v||s.cancelled||(s.id=requestAnimationFrame(a.bind(null,s,o,l,u))),v&&u&&u(o)}}return a(i,e,t,r),{cancel:n.bind(null,i),model:e}}function gn(e){return/\d+[ur]px$/i.test(e)?uni.upx2px(parseFloat(e)):Number(e)||0}function G_(e,t,r){var i=pe("movableAreaWidth",$(0)),n=pe("movableAreaHeight",$(0)),a=pe("_isMounted",$(!1)),s=pe("movableAreaRootRef"),o=pe("addMovableViewContext",()=>{}),l=pe("removeMovableViewContext",()=>{}),u=$(gn(e.x)),v=$(gn(e.y)),c=$(Number(e.scaleValue)||1),m=$(0),g=$(0),_=$(0),b=$(0),w=$(0),p=$(0),h=null,f=null,d={x:0,y:0},y={x:0,y:0},x=1,T=1,C=0,A=0,U=!1,V=!1,q,he,R=null,k=null,ee=new Es,ie=new Es,z={historyX:[0,0],historyY:[0,0],historyT:[0,0]},Z=Q(()=>{var I=Number(e.damping);return isNaN(I)?20:I}),ne=Q(()=>{var I=Number(e.friction);return isNaN(I)||I<=0?2:I}),we=Q(()=>{var I=Number(e.scaleMin);return isNaN(I)?.5:I}),se=Q(()=>{var I=Number(e.scaleMax);return isNaN(I)?10:I}),G=Q(()=>e.direction==="all"||e.direction==="horizontal"),re=Q(()=>e.direction==="all"||e.direction==="vertical"),le=new Yr(1,9*Math.pow(Z.value,2)/40,Z.value),Ce=new ft(1,ne.value);W(()=>e.x,I=>{u.value=gn(I)}),W(()=>e.y,I=>{v.value=gn(I)}),W(u,I=>{Ge(I)}),W(v,I=>{Mt(I)}),W(()=>e.scaleValue,I=>{c.value=Number(I)||0}),W(c,I=>{Gr(I)}),W(we,()=>{Me()}),W(se,()=>{Me()});function Ie(){f&&f.cancel(),h&&h.cancel()}function Ge(I){if(G.value){if(I+y.x===C)return C;h&&h.cancel(),J(I+y.x,v.value+y.y,x)}return I}function Mt(I){if(re.value){if(I+y.y===A)return A;h&&h.cancel(),J(u.value+y.x,I+y.y,x)}return I}function Me(){if(!e.scale)return!1;B(x,!0),D(x)}function Gr(I){return e.scale?(I=N(I),B(I,!0),D(I),I):!1}function Jr(){U||e.disabled||(At({disable:!0}),Ie(),z.historyX=[0,0],z.historyY=[0,0],z.historyT=[0,0],G.value&&(q=C),re.value&&(he=A),r.value.style.willChange="transform",R=null,k=null,V=!0)}function S(I){if(!U&&!e.disabled&&V){var j=C,Y=A;if(k===null&&(k=Math.abs(I.detail.dx/I.detail.dy)>1?"htouchmove":"vtouchmove"),G.value&&(j=I.detail.dx+q,z.historyX.shift(),z.historyX.push(j),!re.value&&R===null&&(R=Math.abs(I.detail.dx/I.detail.dy)<1)),re.value&&(Y=I.detail.dy+he,z.historyY.shift(),z.historyY.push(Y),!G.value&&R===null&&(R=Math.abs(I.detail.dy/I.detail.dx)<1)),z.historyT.shift(),z.historyT.push(I.detail.timeStamp),!R){I.preventDefault();var ve="touch";j<_.value?e.outOfBounds?(ve="touch-out-of-bounds",j=_.value-ee.x(_.value-j)):j=_.value:j>w.value&&(e.outOfBounds?(ve="touch-out-of-bounds",j=w.value+ee.x(j-w.value)):j=w.value),Yp.value&&(e.outOfBounds?(ve="touch-out-of-bounds",Y=p.value+ie.x(Y-p.value)):Y=p.value),Yf(function(){X(j,Y,x,ve)})}}}function E(){if(!U&&!e.disabled&&V&&(At({disable:!1}),r.value.style.willChange="auto",V=!1,!R&&!K("out-of-bounds")&&e.inertia)){var I=1e3*(z.historyX[1]-z.historyX[0])/(z.historyT[1]-z.historyT[0]),j=1e3*(z.historyY[1]-z.historyY[0])/(z.historyT[1]-z.historyT[0]);Ce.setV(I,j),Ce.setS(C,A);var Y=Ce.delta().x,ve=Ce.delta().y,fe=Y+C,Le=ve+A;fe<_.value?(fe=_.value,Le=A+(_.value-C)*ve/Y):fe>w.value&&(fe=w.value,Le=A+(w.value-C)*ve/Y),Lep.value&&(Le=p.value,fe=C+(p.value-A)*Y/ve),Ce.setEnd(fe,Le),f=Gf(Ce,function(){var We=Ce.s(),Re=We.x,rt=We.y;X(Re,rt,x,"friction")},function(){f.cancel()})}!e.outOfBounds&&!e.inertia&&Ie()}function M(I,j){var Y=!1;return I>w.value?(I=w.value,Y=!0):I<_.value&&(I=_.value,Y=!0),j>p.value?(j=p.value,Y=!0):j3&&arguments[3]!==void 0?arguments[3]:"",fe=arguments.length>4?arguments[4]:void 0,Le=arguments.length>5?arguments[5]:void 0;I!==null&&I.toString()!=="NaN"&&typeof I=="number"||(I=C||0),j!==null&&j.toString()!=="NaN"&&typeof j=="number"||(j=A||0),I=Number(I.toFixed(1)),j=Number(j.toFixed(1)),Y=Number(Y.toFixed(1)),C===I&&A===j||fe||t("change",{},{x:Kf(I,y.x),y:Kf(j,y.y),source:ve}),e.scale||(Y=x),Y=N(Y),Y=+Y.toFixed(3),Le&&Y!==x&&t("scale",{},{x:I,y:j,scale:Y});var We="translateX("+I+"px) translateY("+j+"px) translateZ(0px) scale("+Y+")";r.value.style.transform=We,r.value.style.webkitTransform=We,C=I,A=j,x=Y}function ce(){if(!!a.value){Ie();var I=e.scale?c.value:1;P(),L(I),F(),C=u.value+y.x,A=v.value+y.y;var j=M(C,A),Y=j.x,ve=j.y;X(Y,ve,I,"",!0),D(I)}}function Pe(){U=!1,D(x)}function Se(I){I&&(I=T*I,H(),B(I))}return Oe(()=>{dn(r.value,j=>{switch(j.detail.state){case"start":Jr();break;case"move":S(j);break;case"end":E()}}),ce(),Ce.reconfigure(1,ne.value),le.reconfigure(1,9*Math.pow(Z.value,2)/40,Z.value),r.value.style.transformOrigin="center",vn();var I={rootRef:r,setParent:ce,_endScale:Pe,_setScale:Se};o(I),yt(()=>{l(I)})}),yt(()=>{Ie()}),{setParent:ce}}var J_=["navigate","redirect","switchTab","reLaunch","navigateBack"],Z_={hoverClass:{type:String,default:"navigator-hover"},url:{type:String,default:""},openType:{type:String,default:"navigate",validator(e){return Boolean(~J_.indexOf(e))}},delta:{type:Number,default:1},hoverStartTime:{type:[Number,String],default:50},hoverStayTime:{type:[Number,String],default:600},exists:{type:String,default:""},hoverStopPropagation:{type:Boolean,default:!1}},Q_=de({name:"Navigator",compatConfig:{MODE:3},props:Z_,setup(e,t){var{slots:r}=t,{hovering:i,binding:n}=ms(e);function a(s){if(e.openType!=="navigateBack"&&!e.url){console.error(" should have url attribute when using navigateTo, redirectTo, reLaunch or switchTab");return}switch(e.openType){case"navigate":uni.navigateTo({url:e.url});break;case"redirect":uni.redirectTo({url:e.url,exists:e.exists});break;case"switchTab":uni.switchTab({url:e.url});break;case"reLaunch":uni.reLaunch({url:e.url});break;case"navigateBack":uni.navigateBack({delta:e.delta});break}}return()=>{var{hoverClass:s}=e,o=e.hoverClass&&e.hoverClass!=="none";return O("uni-navigator",ze({class:o&&i.value?s:""},o&&n,{onClick:a}),[r.default&&r.default()],16,["onClick"])}}}),eb={value:{type:Array,default(){return[]},validator:function(e){return Array.isArray(e)&&e.filter(t=>typeof t=="number").length===e.length}},indicatorStyle:{type:String,default:""},indicatorClass:{type:String,default:""},maskStyle:{type:String,default:""},maskClass:{type:String,default:""}};function tb(e){var t=Te([...e.value]),r=Te({value:t,height:34});return W(()=>e.value,(i,n)=>{(i===n||i.length!==n.length||i.findIndex((a,s)=>a!==n[s])>=0)&&(r.value.length=i.length,i.forEach((a,s)=>{a!==r.value[s]&&r.value.splice(s,1,a)}))}),r}var rb=de({name:"PickerView",props:eb,emits:["change","pickstart","pickend","update:value"],setup(e,t){var{slots:r,emit:i}=t,n=$(null),a=$(null),s=Ae(n,i),o=tb(e),l=$(null),u=()=>{var _=l.value;o.height=_.$el.offsetHeight},v=$([]),c=$([]);function m(_){var b=c.value;if(b instanceof HTMLCollection)return Array.prototype.indexOf.call(b,_.el);var w=b.indexOf(_);return w!==-1?w:v.value.indexOf(_)}var g=function(_){var b=Q({get(){var w=m(_.vnode);return o.value[w]||0},set(w){var p=m(_.vnode);if(!(p<0)){var h=o.value[p];if(h!==w){o.value[p]=w;var f=o.value.map(d=>d);i("update:value",f),s("change",{},{value:f})}}}});return b};return Ne("getPickerViewColumn",g),Ne("pickerViewProps",e),Ne("pickerViewState",o),jr(()=>{u(),c.value=a.value.children}),()=>{var _=r.default&&r.default();return O("uni-picker-view",{ref:n},[O(Ht,{ref:l,onResize:b=>{var{height:w}=b;return o.height=w}},null,8,["onResize"]),O("div",{ref:a,class:"uni-picker-view-wrapper"},[_],512)],512)}}});class Jf{constructor(t){this._drag=t,this._dragLog=Math.log(t),this._x=0,this._v=0,this._startTime=0}set(t,r){this._x=t,this._v=r,this._startTime=new Date().getTime()}setVelocityByEnd(t){this._v=(t-this._x)*this._dragLog/(Math.pow(this._drag,100)-1)}x(t){t===void 0&&(t=(new Date().getTime()-this._startTime)/1e3);var r=t===this._dt&&this._powDragDt?this._powDragDt:this._powDragDt=Math.pow(this._drag,t);return this._dt=t,this._x+this._v*r/this._dragLog-this._v/this._dragLog}dx(t){t===void 0&&(t=(new Date().getTime()-this._startTime)/1e3);var r=t===this._dt&&this._powDragDt?this._powDragDt:this._powDragDt=Math.pow(this._drag,t);return this._dt=t,this._v*r}done(){return Math.abs(this.dx())<3}reconfigure(t){var r=this.x(),i=this.dx();this._drag=t,this._dragLog=Math.log(t),this.set(r,i)}configuration(){var t=this;return[{label:"Friction",read:function(){return t._drag},write:function(r){t.reconfigure(r)},min:.001,max:.1,step:.001}]}}function Zf(e,t,r){return e>t-r&&e0){var v=(-i-Math.sqrt(s))/(2*n),c=(-i+Math.sqrt(s))/(2*n),m=(r-v*t)/(c-v),g=t-m;return{x:function(h){var f,d;return h===this._t&&(f=this._powER1T,d=this._powER2T),this._t=h,f||(f=this._powER1T=Math.pow(Math.E,v*h)),d||(d=this._powER2T=Math.pow(Math.E,c*h)),g*f+m*d},dx:function(h){var f,d;return h===this._t&&(f=this._powER1T,d=this._powER2T),this._t=h,f||(f=this._powER1T=Math.pow(Math.E,v*h)),d||(d=this._powER2T=Math.pow(Math.E,c*h)),g*v*f+m*c*d}}}var _=Math.sqrt(4*n*a-i*i)/(2*n),b=-i/2*n,w=t,p=(r-b*t)/_;return{x:function(h){return Math.pow(Math.E,b*h)*(w*Math.cos(_*h)+p*Math.sin(_*h))},dx:function(h){var f=Math.pow(Math.E,b*h),d=Math.cos(_*h),y=Math.sin(_*h);return f*(p*_*d-w*_*y)+b*f*(p*y+w*d)}}}x(t){return t===void 0&&(t=(new Date().getTime()-this._startTime)/1e3),this._solution?this._endPosition+this._solution.x(t):0}dx(t){return t===void 0&&(t=(new Date().getTime()-this._startTime)/1e3),this._solution?this._solution.dx(t):0}setEnd(t,r,i){if(i||(i=new Date().getTime()),t!==this._endPosition||!zt(r,.4)){r=r||0;var n=this._endPosition;this._solution&&(zt(r,.4)&&(r=this._solution.dx((i-this._startTime)/1e3)),n=this._solution.x((i-this._startTime)/1e3),zt(r,.4)&&(r=0),zt(n,.4)&&(n=0),n+=this._endPosition),this._solution&&zt(n-t,.4)&&zt(r,.4)||(this._endPosition=t,this._solution=this._solve(n-this._endPosition,r),this._startTime=i)}}snap(t){this._startTime=new Date().getTime(),this._endPosition=t,this._solution={x:function(){return 0},dx:function(){return 0}}}done(t){return t||(t=new Date().getTime()),Zf(this.x(),this._endPosition,.4)&&zt(this.dx(),.4)}reconfigure(t,r,i){this._m=t,this._k=r,this._c=i,this.done()||(this._solution=this._solve(this.x()-this._endPosition,this.dx()),this._startTime=new Date().getTime())}springConstant(){return this._k}damping(){return this._c}configuration(){function t(i,n){i.reconfigure(1,n,i.damping())}function r(i,n){i.reconfigure(1,i.springConstant(),n)}return[{label:"Spring Constant",read:this.springConstant.bind(this),write:t.bind(this,this),min:100,max:1e3},{label:"Damping",read:this.damping.bind(this),write:r.bind(this,this),min:1,max:500}]}}class ib{constructor(t,r,i){this._extent=t,this._friction=r||new Jf(.01),this._spring=i||new Qf(1,90,20),this._startTime=0,this._springing=!1,this._springOffset=0}snap(t,r){this._springOffset=0,this._springing=!0,this._spring.snap(t),this._spring.setEnd(r)}set(t,r){this._friction.set(t,r),t>0&&r>=0?(this._springOffset=0,this._springing=!0,this._spring.snap(t),this._spring.setEnd(0)):t<-this._extent&&r<=0?(this._springOffset=0,this._springing=!0,this._spring.snap(t),this._spring.setEnd(-this._extent)):this._springing=!1,this._startTime=new Date().getTime()}x(t){if(!this._startTime)return 0;if(t||(t=(new Date().getTime()-this._startTime)/1e3),this._springing)return this._spring.x()+this._springOffset;var r=this._friction.x(t),i=this.dx(t);return(r>0&&i>=0||r<-this._extent&&i<=0)&&(this._springing=!0,this._spring.setEnd(0,i),r<-this._extent?this._springOffset=-this._extent:this._springOffset=0,r=this._spring.x()+this._springOffset),r}dx(t){var r;return this._lastTime===t?r=this._lastDx:r=this._springing?this._spring.dx(t):this._friction.dx(t),this._lastTime=t,this._lastDx=r,r}done(){return this._springing?this._spring.done():this._friction.done()}setVelocityByEnd(t){this._friction.setVelocityByEnd(t)}configuration(){var t=this._friction.configuration();return t.push.apply(t,this._spring.configuration()),t}}function nb(e,t,r){var i={id:0,cancelled:!1};function n(s,o,l,u){if(!s||!s.cancelled){l(o);var v=o.done();v||s.cancelled||(s.id=requestAnimationFrame(n.bind(null,s,o,l,u))),v&&u&&u(o)}}function a(s){s&&s.id&&cancelAnimationFrame(s.id),s&&(s.cancelled=!0)}return n(i,e,t,r),{cancel:a.bind(null,i),model:e}}class ab{constructor(t,r){r=r||{},this._element=t,this._options=r,this._enableSnap=r.enableSnap||!1,this._itemSize=r.itemSize||0,this._enableX=r.enableX||!1,this._enableY=r.enableY||!1,this._shouldDispatchScrollEvent=!!r.onScroll,this._enableX?(this._extent=(r.scrollWidth||this._element.offsetWidth)-this._element.parentElement.offsetWidth,this._scrollWidth=r.scrollWidth):(this._extent=(r.scrollHeight||this._element.offsetHeight)-this._element.parentElement.offsetHeight,this._scrollHeight=r.scrollHeight),this._position=0,this._scroll=new ib(this._extent,r.friction,r.spring),this._onTransitionEnd=this.onTransitionEnd.bind(this),this.updatePosition()}onTouchStart(){this._startPosition=this._position,this._lastChangePos=this._startPosition,this._startPosition>0?this._startPosition/=.5:this._startPosition<-this._extent&&(this._startPosition=(this._startPosition+this._extent)/.5-this._extent),this._animation&&(this._animation.cancel(),this._scrolling=!1),this.updatePosition()}onTouchMove(t,r){var i=this._startPosition;this._enableX?i+=t:this._enableY&&(i+=r),i>0?i*=.5:i<-this._extent&&(i=.5*(i+this._extent)-this._extent),this._position=i,this.updatePosition(),this.dispatchScroll()}onTouchEnd(t,r,i){if(this._enableSnap&&this._position>-this._extent&&this._position<0){if(this._enableY&&(Math.abs(r)this._itemSize/2?a-(this._itemSize-Math.abs(s)):a-s,n<=0&&n>=-this._extent&&this._scroll.setVelocityByEnd(n)}this._lastTime=Date.now(),this._lastDelay=0,this._scrolling=!0,this._lastChangePos=this._position,this._lastIdx=Math.floor(Math.abs(this._position/this._itemSize)),this._animation=nb(this._scroll,()=>{var o=Date.now(),l=(o-this._scroll._startTime)/1e3,u=this._scroll.x(l);this._position=u,this.updatePosition();var v=this._scroll.dx(l);this._shouldDispatchScrollEvent&&o-this._lastTime>this._lastDelay&&(this.dispatchScroll(),this._lastDelay=Math.abs(2e3/v),this._lastTime=o)},()=>{this._enableSnap&&(n<=0&&n>=-this._extent&&(this._position=n,this.updatePosition()),typeof this._options.onSnap=="function"&&this._options.onSnap(Math.floor(Math.abs(this._position)/this._itemSize))),this._shouldDispatchScrollEvent&&this.dispatchScroll(),this._scrolling=!1})}onTransitionEnd(){this._element.style.webkitTransition="",this._element.style.transition="",this._element.removeEventListener("transitionend",this._onTransitionEnd),this._snapping&&(this._snapping=!1),this.dispatchScroll()}snap(){var t=this._itemSize,r=this._position%t,i=Math.abs(r)>this._itemSize/2?this._position-(t-Math.abs(r)):this._position-r;this._position!==i&&(this._snapping=!0,this.scrollTo(-i),typeof this._options.onSnap=="function"&&this._options.onSnap(Math.floor(Math.abs(this._position)/this._itemSize)))}scrollTo(t,r){this._animation&&(this._animation.cancel(),this._scrolling=!1),typeof t=="number"&&(this._position=-t),this._position<-this._extent?this._position=-this._extent:this._position>0&&(this._position=0);var i="transform "+(r||.2)+"s ease-out";this._element.style.webkitTransition="-webkit-"+i,this._element.style.transition=i,this.updatePosition(),this._element.addEventListener("transitionend",this._onTransitionEnd)}dispatchScroll(){if(typeof this._options.onScroll=="function"&&Math.round(Number(this._lastPos))!==Math.round(this._position)){this._lastPos=this._position;var t={target:{scrollLeft:this._enableX?-this._position:0,scrollTop:this._enableY?-this._position:0,scrollHeight:this._scrollHeight||this._element.offsetHeight,scrollWidth:this._scrollWidth||this._element.offsetWidth,offsetHeight:this._element.parentElement.offsetHeight,offsetWidth:this._element.parentElement.offsetWidth}};this._options.onScroll(t)}}update(t,r,i){var n=0,a=this._position;this._enableX?(n=this._element.childNodes.length?(r||this._element.offsetWidth)-this._element.parentElement.offsetWidth:0,this._scrollWidth=r):(n=this._element.childNodes.length?(r||this._element.offsetHeight)-this._element.parentElement.offsetHeight:0,this._scrollHeight=r),typeof t=="number"&&(this._position=-t),this._position<-n?this._position=-n:this._position>0&&(this._position=0),this._itemSize=i||this._itemSize,this.updatePosition(),a!==this._position&&(this.dispatchScroll(),typeof this._options.onSnap=="function"&&this._options.onSnap(Math.floor(Math.abs(this._position)/this._itemSize))),this._extent=n,this._scroll._extent=n}updatePosition(){var t="";this._enableX?t="translateX("+this._position+"px) translateZ(0)":this._enableY&&(t="translateY("+this._position+"px) translateZ(0)"),this._element.style.webkitTransform=t,this._element.style.transform=t}isScrolling(){return this._scrolling||this._snapping}}function sb(e,t){var r={trackingID:-1,maxDy:0,maxDx:0},i=new ab(e,t);function n(l){var u=l,v=l;return u.detail.state==="move"||u.detail.state==="end"?{x:u.detail.dx,y:u.detail.dy}:{x:v.screenX-r.x,y:v.screenY-r.y}}function a(l){var u=l,v=l;u.detail.state==="start"?(r.trackingID="touch",r.x=u.detail.x,r.y=u.detail.y):(r.trackingID="mouse",r.x=v.screenX,r.y=v.screenY),r.maxDx=0,r.maxDy=0,r.historyX=[0],r.historyY=[0],r.historyTime=[u.detail.timeStamp||v.timeStamp],r.listener=i,i.onTouchStart&&i.onTouchStart(),l.preventDefault()}function s(l){var u=l,v=l;if(r.trackingID!==-1){l.preventDefault();var c=n(l);if(c){for(r.maxDy=Math.max(r.maxDy,Math.abs(c.y)),r.maxDx=Math.max(r.maxDx,Math.abs(c.x)),r.historyX.push(c.x),r.historyY.push(c.y),r.historyTime.push(u.detail.timeStamp||v.timeStamp);r.historyTime.length>10;)r.historyTime.shift(),r.historyX.shift(),r.historyY.shift();r.listener&&r.listener.onTouchMove&&r.listener.onTouchMove(c.x,c.y)}}}function o(l){if(r.trackingID!==-1){l.preventDefault();var u=n(l);if(u){var v=r.listener;r.trackingID=-1,r.listener=null;var c=r.historyTime.length,m={x:0,y:0};if(c>2)for(var g=r.historyTime.length-1,_=r.historyTime[g],b=r.historyX[g],w=r.historyY[g];g>0;){g--;var p=r.historyTime[g],h=_-p;if(h>30&&h<50){m.x=(b-r.historyX[g])/(h/1e3),m.y=(w-r.historyY[g])/(h/1e3);break}}r.historyTime=[],r.historyX=[],r.historyY=[],v&&v.onTouchEnd&&v.onTouchEnd(u.x,u.y,m)}}}return{scroller:i,handleTouchStart:a,handleTouchMove:s,handleTouchEnd:o}}var ob=0;function lb(e){var t="uni-picker-view-content-".concat(ob++);function r(){var i=document.createElement("style");i.innerText=".uni-picker-view-content.".concat(t,">*{height: ").concat(e.value,"px;overflow: hidden;}"),document.head.appendChild(i)}return W(()=>e.value,r),t}function ub(e){var t=20,r=0,i=0;e.addEventListener("touchstart",n=>{var a=n.changedTouches[0];r=a.clientX,i=a.clientY}),e.addEventListener("touchend",n=>{var a=n.changedTouches[0];if(Math.abs(a.clientX-r){o[u]=a[u]}),n.target.dispatchEvent(o)}})}var fb=de({name:"PickerViewColumn",setup(e,t){var{slots:r,emit:i}=t,n=$(null),a=$(null),s=pe("getPickerViewColumn"),o=xt(),l=s?s(o):$(0),u=pe("pickerViewProps"),v=pe("pickerViewState"),c=$(34),m=$(null),g=()=>{var A=m.value;c.value=A.$el.offsetHeight},_=Q(()=>(v.height-c.value)/2),{state:b}=Ff(),w=lb(c),p,h=Te({current:l.value,length:0}),f;function d(){p&&!f&&(f=!0,sr(()=>{f=!1;var A=Math.min(h.current,h.length-1);A=Math.max(A,0),p.update(A*c.value,void 0,c.value)}))}W(()=>l.value,A=>{A!==h.current&&(h.current=A,d())}),W(()=>h.current,A=>l.value=A),W([()=>c.value,()=>h.length,()=>v.height],d);var y=0;function x(A){var U=y+A.deltaY;if(Math.abs(U)>10){y=0;var V=Math.min(h.current+(U<0?-1:1),h.length-1);h.current=V=Math.max(V,0),p.scrollTo(V*c.value)}else y=U;A.preventDefault()}function T(A){var{clientY:U}=A,V=n.value;if(!p.isScrolling()){var q=V.getBoundingClientRect(),he=U-q.top-v.height/2,R=c.value/2;if(!(Math.abs(he)<=R)){var k=Math.ceil((Math.abs(he)-R)/c.value),ee=he<0?-k:k,ie=Math.min(h.current+ee,h.length-1);h.current=ie=Math.max(ie,0),p.scrollTo(ie*c.value)}}}var C=()=>{var A=n.value,U=a.value,{scroller:V,handleTouchStart:q,handleTouchMove:he,handleTouchEnd:R}=sb(U,{enableY:!0,enableX:!1,enableSnap:!0,itemSize:c.value,friction:new Jf(1e-4),spring:new Qf(2,90,20),onSnap:k=>{!isNaN(k)&&k!==h.current&&(h.current=k)}});p=V,dn(A,k=>{switch(k.detail.state){case"start":q(k),At({disable:!0});break;case"move":he(k),k.stopPropagation();break;case"end":case"cancel":R(k),At({disable:!1})}},!0),ub(A),vn(),d()};return jr(()=>{h.length=a.value.children.length,g(),C()}),()=>{var A=r.default&&r.default(),U="".concat(_.value,"px 0");return O("uni-picker-view-column",{ref:n},[O("div",{onWheel:x,onClick:T,class:"uni-picker-view-group"},[O("div",ze(b.attrs,{class:["uni-picker-view-mask",u.maskClass],style:"background-size: 100% ".concat(_.value,"px;").concat(u.maskStyle)}),null,16),O("div",ze(b.attrs,{class:["uni-picker-view-indicator",u.indicatorClass],style:u.indicatorStyle}),[O(Ht,{ref:m,onResize:V=>{var{height:q}=V;return c.value=q}},null,8,["onResize"])],16),O("div",{ref:a,class:["uni-picker-view-content",w],style:{padding:U}},[A],6)],40,["onWheel","onClick"])],512)}}}),Yt={activeColor:wi,backgroundColor:"#EBEBEB",activeMode:"backwards"},cb={percent:{type:[Number,String],default:0,validator(e){return!isNaN(parseFloat(e))}},showInfo:{type:[Boolean,String],default:!1},strokeWidth:{type:[Number,String],default:6,validator(e){return!isNaN(parseFloat(e))}},color:{type:String,default:Yt.activeColor},activeColor:{type:String,default:Yt.activeColor},backgroundColor:{type:String,default:Yt.backgroundColor},active:{type:[Boolean,String],default:!1},activeMode:{type:String,default:Yt.activeMode},duration:{type:[Number,String],default:30,validator(e){return!isNaN(parseFloat(e))}}},vb=de({name:"Progress",props:cb,setup(e){var t=db(e);return ec(t,e),W(()=>t.realPercent,(r,i)=>{t.strokeTimer&&clearInterval(t.strokeTimer),t.lastPercent=i||0,ec(t,e)}),()=>{var{showInfo:r}=e,{outerBarStyle:i,innerBarStyle:n,currentPercent:a}=t;return O("uni-progress",{class:"uni-progress"},[O("div",{style:i,class:"uni-progress-bar"},[O("div",{style:n,class:"uni-progress-inner-bar"},null,4)],4),r?O("p",{class:"uni-progress-info"},[a+"%"]):""])}}});function db(e){var t=$(0),r=Q(()=>"background-color: ".concat(e.backgroundColor,"; height: ").concat(e.strokeWidth,"px;")),i=Q(()=>{var s=e.color!==Yt.activeColor&&e.activeColor===Yt.activeColor?e.color:e.activeColor;return"width: ".concat(t.value,"%;background-color: ").concat(s)}),n=Q(()=>{var s=parseFloat(e.percent);return s<0&&(s=0),s>100&&(s=100),s}),a=Te({outerBarStyle:r,innerBarStyle:i,realPercent:n,currentPercent:t,strokeTimer:0,lastPercent:0});return a}function ec(e,t){t.active?(e.currentPercent=t.activeMode===Yt.activeMode?0:e.lastPercent,e.strokeTimer=setInterval(()=>{e.currentPercent+1>e.realPercent?(e.currentPercent=e.realPercent,e.strokeTimer&&clearInterval(e.strokeTimer)):e.currentPercent+=1},parseFloat(t.duration))):e.currentPercent=e.realPercent}var tc=Ji("ucg"),hb={name:{type:String,default:""}},gb=de({name:"RadioGroup",props:hb,setup(e,t){var{emit:r,slots:i}=t,n=$(null),a=Ae(n,r);return pb(e,a),()=>O("uni-radio-group",{ref:n},[i.default&&i.default()],512)}});function pb(e,t){var r=[];Oe(()=>{o(r.length-1)});var i=()=>{var l;return(l=r.find(u=>u.value.radioChecked))===null||l===void 0?void 0:l.value.value};Ne(tc,{addField(l){r.push(l)},removeField(l){r.splice(r.indexOf(l),1)},radioChange(l,u){var v=r.indexOf(u);o(v,!0),t("change",l,{value:i()})}});var n=pe(ut,!1),a={submit:()=>{var l=["",null];return e.name!==""&&(l[0]=e.name,l[1]=i()),l}};n&&(n.addField(a),xe(()=>{n.removeField(a)}));function s(l,u){l.value={radioChecked:u,value:l.value.value}}function o(l,u){r.forEach((v,c)=>{c!==l&&(u?s(r[c],!1):r.forEach((m,g)=>{c>=g||r[g].value.radioChecked&&s(r[c],!1)}))})}return r}var mb={checked:{type:[Boolean,String],default:!1},id:{type:String,default:""},disabled:{type:[Boolean,String],default:!1},color:{type:String,default:"#007aff"},value:{type:String,default:""}},_b=de({name:"Radio",props:mb,setup(e,t){var{slots:r}=t,i=$(e.checked),n=$(e.value),a=Q(()=>"background-color: ".concat(e.color,";border-color: ").concat(e.color,";"));W([()=>e.checked,()=>e.value],c=>{var[m,g]=c;i.value=m,n.value=g});var s=()=>{i.value=!1},{uniCheckGroup:o,uniLabel:l,field:u}=bb(i,n,s),v=c=>{e.disabled||(i.value=!0,o&&o.radioChange(c,u))};return l&&(l.addHandler(v),xe(()=>{l.removeHandler(v)})),an(e,{"label-click":v}),()=>{var c=Fr(e,"disabled");return O("uni-radio",ze(c,{onClick:v}),[O("div",{class:"uni-radio-wrapper"},[O("div",{class:["uni-radio-input",{"uni-radio-input-disabled":e.disabled}],style:i.value?a.value:""},[i.value?Qi(Zi,"#fff",18):""],6),r.default&&r.default()])],16,["onClick"])}}});function bb(e,t,r){var i=Q({get:()=>({radioChecked:Boolean(e.value),value:t.value}),set:l=>{var{radioChecked:u}=l;e.value=u}}),n={reset:r},a=pe(tc,!1);a&&a.addField(i);var s=pe(ut,!1);s&&s.addField(n);var o=pe($r,!1);return xe(()=>{a&&a.removeField(i),s&&s.removeField(n)}),{uniCheckGroup:a,uniForm:s,uniLabel:o,field:i}}function wb(e){return e.replace(/<\?xml.*\?>\n/,"").replace(/\n/,"").replace(/\n/,"")}function yb(e){return e.reduce(function(t,r){var i=r.value,n=r.name;return i.match(/ /)&&n!=="style"&&(i=i.split(" ")),t[n]?Array.isArray(t[n])?t[n].push(i):t[n]=[t[n],i]:t[n]=i,t},{})}function Sb(e){e=wb(e);var t=[],r={node:"root",children:[]};return Pf(e,{start:function(i,n,a){var s={name:i};if(n.length!==0&&(s.attrs=yb(n)),a){var o=t[0]||r;o.children||(o.children=[]),o.children.push(s)}else t.unshift(s)},end:function(i){var n=t.shift();if(n.name!==i&&console.error("invalid state: mismatch end tag"),t.length===0)r.children.push(n);else{var a=t[0];a.children||(a.children=[]),a.children.push(n)}},chars:function(i){var n={type:"text",text:i};if(t.length===0)r.children.push(n);else{var a=t[0];a.children||(a.children=[]),a.children.push(n)}},comment:function(i){var n={node:"comment",text:i},a=t[0];a.children||(a.children=[]),a.children.push(n)}}),r.children}var rc={a:"",abbr:"",address:"",article:"",aside:"",b:"",bdi:"",bdo:["dir"],big:"",blockquote:"",br:"",caption:"",center:"",cite:"",code:"",col:["span","width"],colgroup:["span","width"],dd:"",del:"",div:"",dl:"",dt:"",em:"",fieldset:"",font:"",footer:"",h1:"",h2:"",h3:"",h4:"",h5:"",h6:"",header:"",hr:"",i:"",img:["alt","src","height","width"],ins:"",label:"",legend:"",li:"",mark:"",nav:"",ol:["start","type"],p:"",pre:"",q:"",rt:"",ruby:"",s:"",section:"",small:"",span:"",strong:"",sub:"",sup:"",table:["width"],tbody:"",td:["colspan","height","rowspan","width"],tfoot:"",th:["colspan","height","rowspan","width"],thead:"",tr:["colspan","height","rowspan","width"],tt:"",u:"",ul:""},Cs={amp:"&",gt:">",lt:"<",nbsp:" ",quot:'"',apos:"'"};function xb(e){return e.replace(/&(([a-zA-Z]+)|(#x{0,1}[\da-zA-Z]+));/gi,function(t,r){if(te(Cs,r)&&Cs[r])return Cs[r];if(/^#[0-9]{1,4}$/.test(r))return String.fromCharCode(r.slice(1));if(/^#x[0-9a-f]{1,4}$/i.test(r))return String.fromCharCode("0"+r.slice(1));var i=document.createElement("div");return i.innerHTML=t,i.innerText||i.textContent})}function Eb(e,t,r){return e==="img"&&t==="src"?tt(r):r}function ic(e,t,r,i){return e.forEach(function(n){if(!!Je(n))if(!te(n,"type")||n.type==="node"){if(!(typeof n.name=="string"&&n.name))return;var a=n.name.toLowerCase();if(!te(rc,a))return;var s=document.createElement(a);if(!s)return;var o=n.attrs;if(Je(o)){var l=rc[a]||[];Object.keys(o).forEach(function(v){var c=o[v];switch(v){case"class":Array.isArray(c)&&(c=c.join(" "));case"style":s.setAttribute(v,c),r&&s.setAttribute(r,"");break;default:l.indexOf(v)!==-1&&s.setAttribute(v,Eb(a,v,c))}})}Tb(n,s,i);var u=n.children;Array.isArray(u)&&u.length&&ic(n.children,s,r,i),t.appendChild(s)}else n.type==="text"&&typeof n.text=="string"&&n.text!==""&&t.appendChild(document.createTextNode(xb(n.text)))}),t}function Tb(e,t,r){["a","img"].includes(e.name)&&r&&(t.setAttribute("onClick","return false;"),t.addEventListener("click",i=>{r(i,{node:e}),i.stopPropagation()},!0))}var Cb={nodes:{type:[Array,String],default:function(){return[]}}},Ib=de({name:"RichText",compatConfig:{MODE:3},props:Cb,emits:["click","touchstart","touchmove","touchcancel","touchend","longpress"],setup(e,t){var{emit:r,attrs:i}=t,n=xt(),a=$(null),s=Ae(a,r),o=!!i.onItemclick;function l(v){var c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};s("itemclick",v,c)}function u(v){var c;typeof v=="string"&&(v=Sb(v));var m=ic(v,document.createDocumentFragment(),(n==null||(c=n.root)===null||c===void 0?void 0:c.type).__scopeId||"",o&&l);a.value.firstElementChild.innerHTML="",a.value.firstElementChild.appendChild(m)}return W(()=>e.nodes,v=>{u(v)}),Oe(()=>{u(e.nodes)}),()=>O("uni-rich-text",{ref:a},[O("div",null,null)],512)}}),Is=ra(!0),Ob={scrollX:{type:[Boolean,String],default:!1},scrollY:{type:[Boolean,String],default:!1},upperThreshold:{type:[Number,String],default:50},lowerThreshold:{type:[Number,String],default:50},scrollTop:{type:[Number,String],default:0},scrollLeft:{type:[Number,String],default:0},scrollIntoView:{type:String,default:""},scrollWithAnimation:{type:[Boolean,String],default:!1},enableBackToTop:{type:[Boolean,String],default:!1},refresherEnabled:{type:[Boolean,String],default:!1},refresherThreshold:{type:Number,default:45},refresherDefaultStyle:{type:String,default:"back"},refresherBackground:{type:String,default:"#fff"},refresherTriggered:{type:[Boolean,String],default:!1}},Ab=de({name:"ScrollView",compatConfig:{MODE:3},props:Ob,emits:["scroll","scrolltoupper","scrolltolower","refresherrefresh","refresherrestore","refresherpulling","refresherabort","update:refresherTriggered"],setup(e,t){var{emit:r,slots:i}=t,n=$(null),a=$(null),s=$(null),o=$(null),l=$(null),u=Ae(n,r),{state:v,scrollTopNumber:c,scrollLeftNumber:m}=Mb(e);Rb(e,v,c,m,u,n,a,o,r);var g=Q(()=>{var _="";return e.scrollX?_+="overflow-x:auto;":_+="overflow-x:hidden;",e.scrollY?_+="overflow-y:auto;":_+="overflow-y:hidden;",_});return()=>{var{refresherEnabled:_,refresherBackground:b,refresherDefaultStyle:w}=e,{refresherHeight:p,refreshState:h,refreshRotate:f}=v;return O("uni-scroll-view",{ref:n},[O("div",{ref:s,class:"uni-scroll-view"},[O("div",{ref:a,style:g.value,class:"uni-scroll-view"},[O("div",{ref:o,class:"uni-scroll-view-content"},[_?O("div",{ref:l,style:{backgroundColor:b,height:p+"px"},class:"uni-scroll-view-refresher"},[w!=="none"?O("div",{class:"uni-scroll-view-refresh"},[O("div",{class:"uni-scroll-view-refresh-inner"},[h=="pulling"?O("svg",{key:"refresh__icon",style:{transform:"rotate("+f+"deg)"},fill:"#2BD009",class:"uni-scroll-view-refresh__icon",width:"24",height:"24",viewBox:"0 0 24 24"},[O("path",{d:"M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"},null),O("path",{d:"M0 0h24v24H0z",fill:"none"},null)],4):null,h=="refreshing"?O("svg",{key:"refresh__spinner",class:"uni-scroll-view-refresh__spinner",width:"24",height:"24",viewBox:"25 25 50 50"},[O("circle",{cx:"50",cy:"50",r:"20",fill:"none",style:"color: #2bd009","stroke-width":"3"},null)]):null])]):null,w=="none"?i.refresher&&i.refresher():null],4):null,i.default&&i.default()],512)],4)],512)],512)}}});function Mb(e){var t=Q(()=>Number(e.scrollTop)||0),r=Q(()=>Number(e.scrollLeft)||0),i=Te({lastScrollTop:t.value,lastScrollLeft:r.value,lastScrollToUpperTime:0,lastScrollToLowerTime:0,refresherHeight:0,refreshRotate:0,refreshState:""});return{state:i,scrollTopNumber:t,scrollLeftNumber:r}}function Rb(e,t,r,i,n,a,s,o,l){var u=!1,v=0,c=!1,m=()=>{},g=Q(()=>{var x=Number(e.upperThreshold);return isNaN(x)?50:x}),_=Q(()=>{var x=Number(e.lowerThreshold);return isNaN(x)?50:x});function b(x,T){var C=s.value,A=0,U="";if(x<0?x=0:T==="x"&&x>C.scrollWidth-C.offsetWidth?x=C.scrollWidth-C.offsetWidth:T==="y"&&x>C.scrollHeight-C.offsetHeight&&(x=C.scrollHeight-C.offsetHeight),T==="x"?A=C.scrollLeft-x:T==="y"&&(A=C.scrollTop-x),A!==0){var V=o.value;V.style.transition="transform .3s ease-out",V.style.webkitTransition="-webkit-transform .3s ease-out",T==="x"?U="translateX("+A+"px) translateZ(0)":T==="y"&&(U="translateY("+A+"px) translateZ(0)"),V.removeEventListener("transitionend",m),V.removeEventListener("webkitTransitionEnd",m),m=()=>d(x,T),V.addEventListener("transitionend",m),V.addEventListener("webkitTransitionEnd",m),T==="x"?C.style.overflowX="hidden":T==="y"&&(C.style.overflowY="hidden"),V.style.transform=U,V.style.webkitTransform=U}}function w(x){var T=x.target;n("scroll",x,{scrollLeft:T.scrollLeft,scrollTop:T.scrollTop,scrollHeight:T.scrollHeight,scrollWidth:T.scrollWidth,deltaX:t.lastScrollLeft-T.scrollLeft,deltaY:t.lastScrollTop-T.scrollTop}),e.scrollY&&(T.scrollTop<=g.value&&t.lastScrollTop-T.scrollTop>0&&x.timeStamp-t.lastScrollToUpperTime>200&&(n("scrolltoupper",x,{direction:"top"}),t.lastScrollToUpperTime=x.timeStamp),T.scrollTop+T.offsetHeight+_.value>=T.scrollHeight&&t.lastScrollTop-T.scrollTop<0&&x.timeStamp-t.lastScrollToLowerTime>200&&(n("scrolltolower",x,{direction:"bottom"}),t.lastScrollToLowerTime=x.timeStamp)),e.scrollX&&(T.scrollLeft<=g.value&&t.lastScrollLeft-T.scrollLeft>0&&x.timeStamp-t.lastScrollToUpperTime>200&&(n("scrolltoupper",x,{direction:"left"}),t.lastScrollToUpperTime=x.timeStamp),T.scrollLeft+T.offsetWidth+_.value>=T.scrollWidth&&t.lastScrollLeft-T.scrollLeft<0&&x.timeStamp-t.lastScrollToLowerTime>200&&(n("scrolltolower",x,{direction:"right"}),t.lastScrollToLowerTime=x.timeStamp)),t.lastScrollTop=T.scrollTop,t.lastScrollLeft=T.scrollLeft}function p(x){e.scrollY&&(e.scrollWithAnimation?b(x,"y"):s.value.scrollTop=x)}function h(x){e.scrollX&&(e.scrollWithAnimation?b(x,"x"):s.value.scrollLeft=x)}function f(x){if(x){if(!/^[_a-zA-Z][-_a-zA-Z0-9:]*$/.test(x)){console.error("id error: scroll-into-view=".concat(x));return}var T=a.value.querySelector("#"+x);if(T){var C=s.value.getBoundingClientRect(),A=T.getBoundingClientRect();if(e.scrollX){var U=A.left-C.left,V=s.value.scrollLeft,q=V+U;e.scrollWithAnimation?b(q,"x"):s.value.scrollLeft=q}if(e.scrollY){var he=A.top-C.top,R=s.value.scrollTop,k=R+he;e.scrollWithAnimation?b(k,"y"):s.value.scrollTop=k}}}}function d(x,T){o.value.style.transition="",o.value.style.webkitTransition="",o.value.style.transform="",o.value.style.webkitTransform="";var C=s.value;T==="x"?(C.style.overflowX=e.scrollX?"auto":"hidden",C.scrollLeft=x):T==="y"&&(C.style.overflowY=e.scrollY?"auto":"hidden",C.scrollTop=x),o.value.removeEventListener("transitionend",m),o.value.removeEventListener("webkitTransitionEnd",m)}function y(x){switch(x){case"refreshing":t.refresherHeight=e.refresherThreshold,u||(u=!0,n("refresherrefresh",{},{}),l("update:refresherTriggered",!0));break;case"restore":case"refresherabort":u=!1,t.refresherHeight=v=0,x==="restore"&&(c=!1,n("refresherrestore",{},{})),x==="refresherabort"&&c&&(c=!1,n("refresherabort",{},{}));break}t.refreshState=x}Oe(()=>{sr(()=>{p(r.value),h(i.value)}),f(e.scrollIntoView);var x=function(q){q.stopPropagation(),w(q)},T={x:0,y:0},C=null,A=function(q){var he=q.touches[0].pageX,R=q.touches[0].pageY,k=s.value;if(Math.abs(he-T.x)>Math.abs(R-T.y))if(e.scrollX){if(k.scrollLeft===0&&he>T.x){C=!1;return}else if(k.scrollWidth===k.offsetWidth+k.scrollLeft&&heT.y)C=!1,e.refresherEnabled&&q.cancelable!==!1&&q.preventDefault();else if(k.scrollHeight===k.offsetHeight+k.scrollTop&&R0&&(c=!0,n("refresherpulling",q,{deltaY:ee})));var ie=t.refresherHeight/e.refresherThreshold;t.refreshRotate=(ie>1?1:ie)*360}},U=function(q){q.touches.length===1&&(At({disable:!0}),T={x:q.touches[0].pageX,y:q.touches[0].pageY})},V=function(q){T={x:0,y:0},At({disable:!1}),t.refresherHeight>=e.refresherThreshold?y("refreshing"):y("refresherabort")};s.value.addEventListener("touchstart",U,Is),s.value.addEventListener("touchmove",A),s.value.addEventListener("scroll",x,Is),s.value.addEventListener("touchend",V,Is),vn(),xe(()=>{s.value.removeEventListener("touchstart",U),s.value.removeEventListener("touchmove",A),s.value.removeEventListener("scroll",x),s.value.removeEventListener("touchend",V)})}),Na(()=>{e.scrollY&&(s.value.scrollTop=t.lastScrollTop),e.scrollX&&(s.value.scrollLeft=t.lastScrollLeft)}),W(r,x=>{p(x)}),W(i,x=>{h(x)}),W(()=>e.scrollIntoView,x=>{f(x)}),W(()=>e.refresherTriggered,x=>{x===!0?y("refreshing"):x===!1&&y("restore")})}var Pb={name:{type:String,default:""},min:{type:[Number,String],default:0},max:{type:[Number,String],default:100},value:{type:[Number,String],default:0},step:{type:[Number,String],default:1},disabled:{type:[Boolean,String],default:!1},color:{type:String,default:"#e9e9e9"},backgroundColor:{type:String,default:"#e9e9e9"},activeColor:{type:String,default:"#007aff"},selectedColor:{type:String,default:"#007aff"},blockColor:{type:String,default:"#ffffff"},blockSize:{type:[Number,String],default:28},showValue:{type:[Boolean,String],default:!1}},Lb=de({name:"Slider",props:Pb,emits:["changing","change"],setup(e,t){var{emit:r}=t,i=$(null),n=$(null),a=$(null),s=$(Number(e.value));W(()=>e.value,c=>{s.value=Number(c)});var o=Ae(i,r),l=Nb(e,s),{_onClick:u,_onTrack:v}=Db(e,s,i,n,o);return Oe(()=>{dn(a.value,v)}),()=>{var{setBgColor:c,setBlockBg:m,setActiveColor:g,setBlockStyle:_}=l;return O("uni-slider",{ref:i,onClick:Vt(u)},[O("div",{class:"uni-slider-wrapper"},[O("div",{class:"uni-slider-tap-area"},[O("div",{style:c.value,class:"uni-slider-handle-wrapper"},[O("div",{ref:a,style:m.value,class:"uni-slider-handle"},null,4),O("div",{style:_.value,class:"uni-slider-thumb"},null,4),O("div",{style:g.value,class:"uni-slider-track"},null,4)],4)]),Ir(O("span",{ref:n,class:"uni-slider-value"},[s.value],512),[[Dr,e.showValue]])]),O("slot",null,null)],8,["onClick"])}}});function Nb(e,t){var r=()=>{var s=Number(e.max),o=Number(e.min);return 100*(t.value-o)/(s-o)+"%"},i=()=>e.backgroundColor!=="#e9e9e9"?e.backgroundColor:e.color!=="#007aff"?e.color:"#007aff",n=()=>e.activeColor!=="#007aff"?e.activeColor:e.selectedColor!=="#e9e9e9"?e.selectedColor:"#e9e9e9",a={setBgColor:Q(()=>({backgroundColor:i()})),setBlockBg:Q(()=>({left:r()})),setActiveColor:Q(()=>({backgroundColor:n(),width:r()})),setBlockStyle:Q(()=>({width:e.blockSize+"px",height:e.blockSize+"px",marginLeft:-e.blockSize/2+"px",marginTop:-e.blockSize/2+"px",left:r(),backgroundColor:e.blockColor}))};return a}function Db(e,t,r,i,n){var a=c=>{e.disabled||(o(c),n("change",c,{value:t.value}))},s=c=>{var m=Number(e.max),g=Number(e.min),_=Number(e.step);return cm?m:kb.mul.call(Math.round((c-g)/_),_)+g},o=c=>{var m=Number(e.max),g=Number(e.min),_=i.value,b=getComputedStyle(_,null).marginLeft,w=_.offsetWidth;w=w+parseInt(b);var p=r.value,h=p.offsetWidth-(e.showValue?w:0),f=p.getBoundingClientRect().left,d=(c.x-f)*(m-g)/h+g;t.value=s(d)},l=c=>{if(!e.disabled)return c.detail.state==="move"?(o({x:c.detail.x}),n("changing",c,{value:t.value}),!1):c.detail.state==="end"&&n("change",c,{value:t.value})},u=pe(ut,!1);if(u){var v={reset:()=>t.value=Number(e.min),submit:()=>{var c=["",null];return e.name!==""&&(c[0]=e.name,c[1]=t.value),c}};u.addField(v),xe(()=>{u.removeField(v)})}return{_onClick:a,_onTrack:l}}var kb={mul:function(e){var t=0,r=this.toString(),i=e.toString();try{t+=r.split(".")[1].length}catch(n){}try{t+=i.split(".")[1].length}catch(n){}return Number(r.replace(".",""))*Number(i.replace(".",""))/Math.pow(10,t)}},Bb={indicatorDots:{type:[Boolean,String],default:!1},vertical:{type:[Boolean,String],default:!1},autoplay:{type:[Boolean,String],default:!1},circular:{type:[Boolean,String],default:!1},interval:{type:[Number,String],default:5e3},duration:{type:[Number,String],default:500},current:{type:[Number,String],default:0},indicatorColor:{type:String,default:""},indicatorActiveColor:{type:String,default:""},previousMargin:{type:String,default:""},nextMargin:{type:String,default:""},currentItemId:{type:String,default:""},skipHiddenItemLayout:{type:[Boolean,String],default:!1},displayMultipleItems:{type:[Number,String],default:1},disableTouch:{type:[Boolean,String],default:!1}};function Fb(e){var t=Q(()=>{var a=Number(e.interval);return isNaN(a)?5e3:a}),r=Q(()=>{var a=Number(e.duration);return isNaN(a)?500:a}),i=Q(()=>{var a=Math.round(e.displayMultipleItems);return isNaN(a)?1:a}),n=Te({interval:t,duration:r,displayMultipleItems:i,current:Math.round(e.current)||0,currentItemId:e.currentItemId,userTracking:!1});return n}function $b(e,t,r,i,n,a){function s(){o&&(clearTimeout(o),o=null)}var o=null,l=!0,u=0,v=1,c=null,m=!1,g=0,_,b="",w,p=Q(()=>e.circular&&r.value.length>t.displayMultipleItems);function h(R){if(!l)for(var k=r.value,ee=k.length,ie=R+t.displayMultipleItems,z=0;z=Z.length&&(R-=Z.length),R=_%1>.5||_<0?R-1:R,a("transition",{},{dx:e.vertical?0:R*z.offsetWidth,dy:e.vertical?R*z.offsetHeight:0})}function d(){c&&(f(c.toPos),c=null)}function y(R){var k=r.value.length;if(!k)return-1;var ee=(Math.round(R)%k+k)%k;if(p.value){if(k<=t.displayMultipleItems)return 0}else if(ee>k-t.displayMultipleItems)return k-t.displayMultipleItems;return ee}function x(){c=null}function T(){if(!c){m=!1;return}var R=c,k=R.toPos,ee=R.acc,ie=R.endTime,z=R.source,Z=ie-Date.now();if(Z<=0){f(k),c=null,m=!1,_=null;var ne=r.value[t.current];if(ne){var we=ne.getItemId();a("animationfinish",{},{current:t.current,currentItemId:we,source:z})}return}var se=ee*Z*Z/2,G=k+se;f(G),w=requestAnimationFrame(T)}function C(R,k,ee){x();var ie=t.duration,z=r.value.length,Z=u;if(p.value)if(ee<0){for(;ZR;)Z-=z}else if(ee>0){for(;Z>R;)Z-=z;for(;Z+zR;)Z-=z;Z+z-R0&&v<1||(v=1)}var Z=u;u=-2;var ne=t.current;ne>=0?(l=!1,t.userTracking?(f(Z+ne-g),g=ne):(f(ne),e.autoplay&&A())):(l=!0,f(-t.displayMultipleItems-1))}W([()=>e.current,()=>e.currentItemId,()=>[...r.value]],()=>{var R=-1;if(e.currentItemId)for(var k=0,ee=r.value;ke.vertical,()=>p.value,()=>t.displayMultipleItems,()=>[...r.value]],U),W(()=>t.interval,()=>{o&&(s(),A())});function V(R,k){var ee=b;b="";var ie=r.value;if(!ee){var z=ie.length;C(R,"",p.value&&k+(z-R)%z>z/2?1:0)}var Z=ie[R];if(Z){var ne=t.currentItemId=Z.getItemId();a("change",{},{current:t.current,currentItemId:ne,source:ee})}}W(()=>t.current,(R,k)=>{V(R,k),n("update:current",R)}),W(()=>t.currentItemId,R=>{n("update:currentItemId",R)});function q(R){R?A():s()}W(()=>e.autoplay&&!t.userTracking,q),q(e.autoplay&&!t.userTracking),Oe(()=>{var R=!1,k=0,ee=0;function ie(){s(),g=u,k=0,ee=Date.now(),x()}function z(ne){var we=ee;ee=Date.now();var se=r.value.length,G=se-t.displayMultipleItems;function re(Ge){return .5-.25/(Ge+.5)}function le(Ge,Mt){var Me=g+Ge;k=.6*k+.4*Mt,p.value||(Me<0||Me>G)&&(Me<0?Me=-re(-Me):Me>G&&(Me=G+re(Me-G)),k=0),f(Me)}var Ce=ee-we||1,Ie=i.value;e.vertical?le(-ne.dy/Ie.offsetHeight,-ne.ddy/Ce):le(-ne.dx/Ie.offsetWidth,-ne.ddx/Ce)}function Z(ne){t.userTracking=!1;var we=k/Math.abs(k),se=0;!ne&&Math.abs(k)>.2&&(se=.5*we);var G=y(u+se);ne?f(g):(b="touch",t.current=G,C(G,"touch",se!==0?se:G===0&&p.value&&u>=1?1:0))}dn(i.value,ne=>{if(!e.disableTouch&&!l){if(ne.detail.state==="start")return t.userTracking=!0,R=!1,ie();if(ne.detail.state==="end")return Z(!1);if(ne.detail.state==="cancel")return Z(!0);if(t.userTracking){if(!R){R=!0;var we=Math.abs(ne.detail.dx),se=Math.abs(ne.detail.dy);if((we>=se&&e.vertical||we<=se&&!e.vertical)&&(t.userTracking=!1),!t.userTracking){e.autoplay&&A();return}}return z(ne.detail),!1}}})}),yt(()=>{s(),cancelAnimationFrame(w)});function he(R){C(t.current=R,b="click",p.value?1:0)}return{onSwiperDotClick:he}}var Ub=de({name:"Swiper",props:Bb,emits:["change","transition","animationfinish","update:current","update:currentItemId"],setup(e,t){var{slots:r,emit:i}=t,n=$(null),a=Ae(n,i),s=$(null),o=$(null),l=Fb(e),u=Q(()=>{var h={};return(e.nextMargin||e.previousMargin)&&(h=e.vertical?{left:0,right:0,top:Wt(e.previousMargin,!0),bottom:Wt(e.nextMargin,!0)}:{top:0,bottom:0,left:Wt(e.previousMargin,!0),right:Wt(e.nextMargin,!0)}),h}),v=Q(()=>{var h=Math.abs(100/l.displayMultipleItems)+"%";return{width:e.vertical?"100%":h,height:e.vertical?h:"100%"}}),c=[],m=[],g=$([]);function _(){for(var h=[],f=function(y){var x=c[y];x instanceof Element||(x=x.el);var T=m.find(C=>x===C.rootRef.value);T&&h.push(Ni(T))},d=0;d{c=o.value.children,_()});var b=function(h){m.push(h),_()};Ne("addSwiperContext",b);var w=function(h){var f=m.indexOf(h);f>=0&&(m.splice(f,1),_())};Ne("removeSwiperContext",w);var{onSwiperDotClick:p}=$b(e,l,g,o,i,a);return()=>{var h=r.default&&r.default();return c=xs(h),O("uni-swiper",{ref:n},[O("div",{ref:s,class:"uni-swiper-wrapper"},[O("div",{class:"uni-swiper-slides",style:u.value},[O("div",{ref:o,class:"uni-swiper-slide-frame",style:v.value},[h],4)],4),e.indicatorDots&&O("div",{class:["uni-swiper-dots",e.vertical?"uni-swiper-dots-vertical":"uni-swiper-dots-horizontal"]},[g.value.map((f,d,y)=>O("div",{onClick:()=>p(d),class:{"uni-swiper-dot":!0,"uni-swiper-dot-active":d=l.current||d{var a=pe("addSwiperContext");a&&a(n)}),yt(()=>{var a=pe("removeSwiperContext");a&&a(n)}),()=>O("uni-swiper-item",{ref:i,style:{position:"absolute",width:"100%",height:"100%"}},[r.default&&r.default()],512)}}),Hb={name:{type:String,default:""},checked:{type:[Boolean,String],default:!1},type:{type:String,default:"switch"},id:{type:String,default:""},disabled:{type:[Boolean,String],default:!1},color:{type:String,default:"#007aff"}},jb=de({name:"Switch",props:Hb,emits:["change"],setup(e,t){var{emit:r}=t,i=$(null),n=$(e.checked),a=zb(e,n),s=Ae(i,r);W(()=>e.checked,l=>{n.value=l});var o=l=>{e.disabled||(n.value=!n.value,s("change",l,{value:n.value}))};return a&&(a.addHandler(o),xe(()=>{a.removeHandler(o)})),an(e,{"label-click":o}),()=>{var{color:l,type:u}=e,v=Fr(e,"disabled");return O("uni-switch",ze({ref:i},v,{onClick:o}),[O("div",{class:"uni-switch-wrapper"},[Ir(O("div",{class:["uni-switch-input",[n.value?"uni-switch-input-checked":""]],style:{backgroundColor:n.value?l:"#DFDFDF",borderColor:n.value?l:"#DFDFDF"}},null,6),[[Dr,u==="switch"]]),Ir(O("div",{class:"uni-checkbox-input"},[n.value?Qi(Zi,e.color,22):""],512),[[Dr,u==="checkbox"]])])],16,["onClick"])}}});function zb(e,t){var r=pe(ut,!1),i=pe($r,!1),n={submit:()=>{var a=["",null];return e.name&&(a[0]=e.name,a[1]=t.value),a},reset:()=>{t.value=!1}};return r&&(r.addField(n),yt(()=>{r.removeField(n)})),i}var qr={ensp:"\u2002",emsp:"\u2003",nbsp:"\xA0"};function Yb(e,t){return e.replace(/\\n/g,wr).split(wr).map(r=>qb(r,t))}function qb(e,t){var{space:r,decode:i}=t;return!e||(r&&qr[r]&&(e=e.replace(/ /g,qr[r])),!i)?e:e.replace(/ /g,qr.nbsp).replace(/ /g,qr.ensp).replace(/ /g,qr.emsp).replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'")}var Xb=ue({},$f,{placeholderClass:{type:String,default:"input-placeholder"},autoHeight:{type:[Boolean,String],default:!1},confirmType:{type:String,default:""}}),Os=!1;function Kb(){var e="(prefers-color-scheme: dark)";Os=String(navigator.platform).indexOf("iP")===0&&String(navigator.vendor).indexOf("Apple")===0&&window.matchMedia(e).media!==e}var Gb=de({name:"Textarea",props:Xb,emit:["confirm","linechange",...Uf],setup(e,t){var{emit:r}=t,i=$(null),{fieldRef:n,state:a,scopedAttrsState:s,fixDisabledColor:o,trigger:l}=Wf(e,i,r),u=Q(()=>a.value.split(wr)),v=Q(()=>["done","go","next","search","send"].includes(e.confirmType)),c=$(0),m=$(null);W(()=>c.value,p=>{var h=i.value,f=m.value,d=parseFloat(getComputedStyle(h).lineHeight);isNaN(d)&&(d=f.offsetHeight);var y=Math.round(p/d);l("linechange",{},{height:p,heightRpx:750/window.innerWidth*p,lineCount:y}),e.autoHeight&&(h.style.height=p+"px")});function g(p){var{height:h}=p;c.value=h}function _(p){l("confirm",p,{value:a.value})}function b(p){p.key==="Enter"&&v.value&&p.preventDefault()}function w(p){if(p.key==="Enter"&&v.value){_(p);var h=p.target;h.blur()}}return Kb(),()=>{var p=e.disabled&&o?O("textarea",{ref:n,value:a.value,tabindex:"-1",readonly:!!e.disabled,maxlength:a.maxlength,class:{"uni-textarea-textarea":!0,"uni-textarea-textarea-fix-margin":Os},style:{overflowY:e.autoHeight?"hidden":"auto"},onFocus:h=>h.target.blur()},null,46,["value","readonly","maxlength","onFocus"]):O("textarea",{ref:n,value:a.value,disabled:!!e.disabled,maxlength:a.maxlength,enterkeyhint:e.confirmType,class:{"uni-textarea-textarea":!0,"uni-textarea-textarea-fix-margin":Os},style:{overflowY:e.autoHeight?"hidden":"auto"},onKeydown:b,onKeyup:w},null,46,["value","disabled","maxlength","enterkeyhint","onKeydown","onKeyup"]);return O("uni-textarea",{ref:i},[O("div",{class:"uni-textarea-wrapper"},[Ir(O("div",ze(s.attrs,{style:e.placeholderStyle,class:["uni-textarea-placeholder",e.placeholderClass]}),[e.placeholder],16),[[Dr,!a.value.length]]),O("div",{ref:m,class:"uni-textarea-line"},[" "],512),O("div",{class:"uni-textarea-compute"},[u.value.map(h=>O("div",null,[h.trim()?h:"."])),O(Ht,{initial:!0,onResize:g},null,8,["initial","onResize"])]),e.confirmType==="search"?O("form",{action:"",onSubmit:()=>!1,class:"uni-input-form"},[p],40,["onSubmit"]):p])],512)}}});ue({},w0);function pn(e,t){if(t||(t=e.id),!!t)return e.$options.name.toLowerCase()+"."+t}function nc(e,t,r){!e||at(r||Ct(),e,(i,n)=>{var{type:a,data:s}=i;t(a,s,n)})}function ac(e){!e||ch(Ct(),e)}function mn(e,t,r,i){var n=xt(),a=n.proxy;Oe(()=>{nc(t||pn(a),e,i),(r||!t)&&W(()=>a.id,(s,o)=>{nc(pn(a,s),e,i),ac(o&&pn(a,o))})}),xe(()=>{ac(t||pn(a))})}var Jb=0;function _n(e){var t=en(),r=xt(),i=r.proxy,n=i.$options.name.toLowerCase(),a=e||i.id||"context".concat(Jb++);return Oe(()=>{var s=i.$el;s.__uniContextInfo={id:a,type:n,page:t}}),"".concat(n,".").concat(a)}function Zb(e){return e.__uniContextInfo}class sc extends hf{constructor(t,r,i,n,a){var s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:[];super(t,r,i,n,a,[...nn.props,...s])}call(t){var r={animation:this.$props.animation,$el:this.$};t.call(r)}setAttribute(t,r){return t==="animation"&&(this.$animate=!0),super.setAttribute(t,r)}update(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!!this.$animate){if(t)return this.call(nn.mounted);this.$animate&&(this.$animate=!1,this.call(nn.watch.animation.handler))}}}var Qb=["space","decode"];class ew extends sc{constructor(t,r,i,n){super(t,document.createElement("uni-text"),r,i,n,Qb);this._text=""}init(t){this._text=t.t||"",super.init(t)}setText(t){this._text=t,this.update()}update(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,{$props:{space:r,decode:i}}=this;this.$.textContent=Yb(this._text,{space:r,decode:i}).join(wr),super.update(t)}}class tw extends lr{constructor(t,r,i,n){super(t,"#text",r,document.createTextNode(""));this.init(n),this.insert(r,i)}}var Gy="",rw=["hover-class","hover-stop-propagation","hover-start-time","hover-stay-time"];class iw extends sc{constructor(t,r,i,n,a){var s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:[];super(t,r,i,n,a,[...rw,...s])}update(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,r=this.$props["hover-class"];r&&r!=="none"?(this._hover||(this._hover=new nw(this.$,this.$props)),this._hover.addEvent()):this._hover&&this._hover.removeEvent(),super.update(t)}}class nw{constructor(t,r){this._listening=!1,this._hovering=!1,this._hoverTouch=!1,this.$=t,this.props=r,this.__hoverTouchStart=this._hoverTouchStart.bind(this),this.__hoverTouchEnd=this._hoverTouchEnd.bind(this),this.__hoverTouchCancel=this._hoverTouchCancel.bind(this)}get hovering(){return this._hovering}set hovering(t){this._hovering=t;var r=this.props["hover-class"];t?this.$.classList.add(r):this.$.classList.remove(r)}addEvent(){this._listening||(this._listening=!0,this.$.addEventListener("touchstart",this.__hoverTouchStart),this.$.addEventListener("touchend",this.__hoverTouchEnd),this.$.addEventListener("touchcancel",this.__hoverTouchCancel))}removeEvent(){!this._listening||(this._listening=!1,this.$.removeEventListener("touchstart",this.__hoverTouchStart),this.$.removeEventListener("touchend",this.__hoverTouchEnd),this.$.removeEventListener("touchcancel",this.__hoverTouchCancel))}_hoverTouchStart(t){if(!t._hoverPropagationStopped){var r=this.props["hover-class"];!r||r==="none"||this.$.disabled||t.touches.length>1||(this.props["hover-stop-propagation"]&&(t._hoverPropagationStopped=!0),this._hoverTouch=!0,this._hoverStartTimer=setTimeout(()=>{this.hovering=!0,this._hoverTouch||this._hoverReset()},this.props["hover-start-time"]))}}_hoverTouchEnd(){this._hoverTouch=!1,this.hovering&&this._hoverReset()}_hoverReset(){requestAnimationFrame(()=>{clearTimeout(this._hoverStayTimer),this._hoverStayTimer=setTimeout(()=>{this.hovering=!1},this.props["hover-stay-time"])})}_hoverTouchCancel(){this._hoverTouch=!1,this.hovering=!1,clearTimeout(this._hoverStartTimer)}}class aw extends iw{constructor(t,r,i,n){super(t,document.createElement("uni-view"),r,i,n)}}function oc(){var e=plus.webview.currentWebview(),t=e.getStyle(),r=t&&t.titleNView;return r&&r.type==="default"?Po+Yu():0}var lc=Symbol("onDraw");function sw(e){for(var t;e;){var r=getComputedStyle(e),i=r.transform||r.webkitTransform;t=i&&i!=="none"?!1:t,t=r.position==="fixed"?!0:t,e=e.parentElement}return t}function As(e,t){return Q(()=>{var r={};return Object.keys(e).forEach(i=>{if(!(t&&t.includes(i))){var n=e[i];n=i==="src"?tt(n):n,r[i.replace(/[A-Z]/g,a=>"-"+a.toLowerCase())]=n}}),r})}function Xr(e){var t=Te({top:"0px",left:"0px",width:"0px",height:"0px",position:"static"}),r=$(!1);function i(){var c=e.value,m=c.getBoundingClientRect(),g=["width","height"];r.value=m.width===0||m.height===0,r.value||(t.position=sw(c)?"absolute":"static",g.push("top","left")),g.forEach(_=>{var b=m[_];b=_==="top"?b+(t.position==="static"?document.documentElement.scrollTop||document.body.scrollTop||0:oc()):b,t[_]=b+"px"})}var n=null;function a(){n&&cancelAnimationFrame(n),n=requestAnimationFrame(()=>{n=null,i()})}window.addEventListener("updateview",a);var s=[],o=[];function l(c){o?o.push(c):c()}function u(c){var m=pe(lc),g=_=>{c(_),s.forEach(b=>b(t)),s=null};l(()=>{m?m(g):g({top:"0px",left:"0px",width:Number.MAX_SAFE_INTEGER+"px",height:Number.MAX_SAFE_INTEGER+"px",position:"static"})})}var v=function(c){s?s.push(c):c(t)};return Ne(lc,v),Oe(()=>{i(),o.forEach(c=>c()),o=null}),xe(()=>{window.removeEventListener("updateview",a)}),{position:t,hidden:r,onParentReady:u}}var ow=de({name:"Ad",props:{adpid:{type:[Number,String],default:""},data:{type:Object,default:null},dataCount:{type:Number,default:5},channel:{type:String,default:""}},setup(e,t){var{emit:r}=t,i=$(null),n=$(null),a=Ae(i,r),s=As(e,["id"]),{position:o,onParentReady:l}=Xr(n),u;return l(()=>{u=plus.ad.createAdView(Object.assign({},s.value,o)),plus.webview.currentWebview().append(u),u.setDislikeListener(c=>{n.value.style.height="0",window.dispatchEvent(new CustomEvent("updateview")),a("close",{},c)}),u.setRenderingListener(c=>{c.result===0?(n.value.style.height=c.height+"px",window.dispatchEvent(new CustomEvent("updateview"))):a("error",{},{errCode:c.result})}),u.setAdClickedListener(()=>{a("adclicked",{},{})}),W(()=>o,c=>u.setStyle(c),{deep:!0}),W(()=>e.adpid,c=>{c&&v()}),W(()=>e.data,c=>{c&&u.renderingBind(c)});function v(){var c={adpid:e.adpid,width:o.width,count:e.dataCount};e.channel!==void 0&&(c.ext={channel:e.channel}),UniViewJSBridge.invokeServiceMethod("getAdData",c,m=>{var{code:g,data:_,message:b}=m;g===0?u.renderingBind(_):a("error",{},{errMsg:b})})}e.adpid&&v()}),xe(()=>{u&&u.close()}),()=>O("uni-ad",{ref:i},[O("div",{ref:n,class:"uni-ad-container"},null,512)],512)}});class _e extends lr{constructor(t,r,i,n,a,s,o){super(t,r,n);var l=document.createElement("div");l.__vueParent=lw(this),this.$props=Te({}),this.init(s),this.$app=Au(my(i,this.$props)),this.$app.mount(l),this.$=l.firstElementChild,o&&(this.$holder=this.$.querySelector(o)),te(s,"t")&&this.setText(s.t||""),s.a&&te(s.a,Si)&&ps(this.$,s.a[Si]),this.insert(n,a),pu()}init(t){var{a:r,e:i,w:n}=t;r&&(this.setWxsProps(r),Object.keys(r).forEach(a=>{this.setAttr(a,r[a])})),te(t,"s")&&this.setAttr("style",t.s),i&&Object.keys(i).forEach(a=>{this.addEvent(a,i[a])}),n&&this.addWxsEvents(t.w)}setText(t){(this.$holder||this.$).textContent=t}addWxsEvent(t,r,i){this.$props[t]=df(this.$,r,i)}addEvent(t,r){this.$props[t]=cf(this.id,r,yi(t)[1])}removeEvent(t){this.$props[t]=null}setAttr(t,r){if(t===Si)this.$&&ps(this.$,r);else if(t===Vo)this.$.__ownerId=r;else if(t===Ho)It(()=>rf(this,r),Qu);else if(t===sa){var i=gs(this.$||Ke(this.pid).$,r),n=this.$props.style;Je(i)&&Je(n)?Object.keys(i).forEach(a=>{n[a]=i[a]}):this.$props.style=i}else rn(t)?this.$.style.setProperty(t,r):(r=gs(this.$||Ke(this.pid).$,r),this.wxsPropsInvoke(t,r,!0)||(this.$props[t]=r))}removeAttr(t){rn(t)?this.$.style.removeProperty(t):this.$props[t]=null}remove(){this.removeUniParent(),this.isUnmounted=!0,this.$app.unmount(),gc(this.id),this.removeUniChildren()}appendChild(t){return(this.$holder||this.$).appendChild(t)}insertBefore(t,r){return(this.$holder||this.$).insertBefore(t,r)}}class Kr extends _e{constructor(t,r,i,n,a,s,o){super(t,r,i,n,a,s,o)}getRebuildFn(){return this._rebuild||(this._rebuild=this.rebuild.bind(this)),this._rebuild}setText(t){return It(this.getRebuildFn(),us),super.setText(t)}appendChild(t){return It(this.getRebuildFn(),us),super.appendChild(t)}insertBefore(t,r){return It(this.getRebuildFn(),us),super.insertBefore(t,r)}rebuild(){var t=this.$.__vueParentComponent;t.rebuild&&t.rebuild()}}function lw(e){for(;e&&e.pid>0;)if(e=Ke(e.pid),e){var{__vueParentComponent:t}=e.$;if(t)return t}return null}function Ms(e,t,r){e.childNodes.forEach(i=>{i instanceof Element?i.className.indexOf(t)===-1&&e.removeChild(i):e.removeChild(i)}),e.appendChild(document.createTextNode(r))}class uw extends _e{constructor(t,r,i,n){super(t,"uni-ad",ow,r,i,n)}}var Jy="";class fw extends _e{constructor(t,r,i,n){super(t,"uni-button",O0,r,i,n)}}class fr extends lr{constructor(t,r,i,n){super(t,r,i);this.insert(i,n)}}class cw extends fr{constructor(t,r,i){super(t,"uni-camera",r,i)}}var Zy="";class vw extends _e{constructor(t,r,i,n){super(t,"uni-canvas",k0,r,i,n,"uni-canvas > div")}}var Qy="";class dw extends _e{constructor(t,r,i,n){super(t,"uni-checkbox",H0,r,i,n,".uni-checkbox-wrapper")}setText(t){Ms(this.$holder,"uni-checkbox-input",t)}}var e1="";class hw extends _e{constructor(t,r,i,n){super(t,"uni-checkbox-group",U0,r,i,n)}}var t1="",gw=0;function uc(e,t,r){var{position:i,hidden:n,onParentReady:a}=Xr(e),s,o;a(l=>{var u=Q(()=>{var f={};for(var d in i){var y=i[d],x=parseFloat(y),T=parseFloat(l[d]);if(d==="top"||d==="left")y=Math.max(x,T)+"px";else if(d==="width"||d==="height"){var C=d==="width"?"left":"top",A=parseFloat(l[C]),U=parseFloat(i[C]),V=Math.max(A-U,0),q=Math.max(U+x-(A+T),0);y=Math.max(x-V-q,0)+"px"}f[d]=y}return f}),v=["borderRadius","borderColor","borderWidth","backgroundColor"],c=["paddingTop","paddingRight","paddingBottom","paddingLeft","color","textAlign","lineHeight","fontSize","fontWeight","textOverflow","whiteSpace"],m=[],g={start:"left",end:"right"};function _(f){var d=getComputedStyle(e.value);return v.concat(c,m).forEach(y=>{f[y]=d[y]}),f}var b=Te(_({})),w=null;o=function(){w&&cancelAnimationFrame(w),w=requestAnimationFrame(()=>{w=null,_(b)})},window.addEventListener("updateview",o);function p(){var f={};for(var d in f){var y=f[d];(d==="top"||d==="left")&&(y=Math.min(parseFloat(y)-parseFloat(l[d]),0)+"px"),f[d]=y}return f}var h=Q(()=>{var f=p(),d=[{tag:"rect",position:f,rectStyles:{color:b.backgroundColor,radius:b.borderRadius,borderColor:b.borderColor,borderWidth:b.borderWidth}}];if("src"in r)r.src&&d.push({tag:"img",position:f,src:r.src});else{var y=parseFloat(b.lineHeight)-parseFloat(b.fontSize),x=parseFloat(f.width)-parseFloat(b.paddingLeft)-parseFloat(b.paddingRight);x=x<0?0:x;var T=parseFloat(f.height)-parseFloat(b.paddingTop)-y/2-parseFloat(b.paddingBottom);T=T<0?0:T,d.push({tag:"font",position:{top:"".concat(parseFloat(f.top)+parseFloat(b.paddingTop)+y/2,"px"),left:"".concat(parseFloat(f.left)+parseFloat(b.paddingLeft),"px"),width:"".concat(x,"px"),height:"".concat(T,"px")},textStyles:{align:g[b.textAlign]||b.textAlign,color:b.color,decoration:"none",lineSpacing:"".concat(y,"px"),margin:"0px",overflow:b.textOverflow,size:b.fontSize,verticalAlign:"top",weight:b.fontWeight,whiteSpace:b.whiteSpace},text:r.text})}return d});s=new plus.nativeObj.View("cover-".concat(Date.now(),"-").concat(gw++),u.value,h.value),plus.webview.currentWebview().append(s),n.value&&s.hide(),s.addEventListener("click",()=>{t("click",{},{})}),W(()=>n.value,f=>{s[f?"hide":"show"]()}),W(()=>u.value,f=>{s.setStyle(f)},{deep:!0}),W(()=>h.value,()=>{s.reset(),s.draw(h.value)},{deep:!0})}),xe(()=>{s&&s.close(),o&&window.removeEventListener("updateview",o)})}var pw="_doc/uniapp_temp/",mw={src:{type:String,default:""},autoSize:{type:[Boolean,String],default:!1}};function _w(e,t,r){var i=$(""),n;function a(){t.src="",i.value=e.autoSize?"width:0;height:0;":"";var o=e.src?tt(e.src):"";o.indexOf("http://")===0||o.indexOf("https://")===0?(n=plus.downloader.createDownload(o,{filename:pw+"/download/"},(l,u)=>{u===200?s(l.filename):r("error",{},{errMsg:"error"})}),n.start()):o&&s(o)}function s(o){t.src=o,plus.io.getImageInfo({src:o,success:l=>{var{width:u,height:v}=l;e.autoSize&&(i.value="width:".concat(u,"px;height:").concat(v,"px;"),window.dispatchEvent(new CustomEvent("updateview"))),r("load",{},{width:u,height:v})},fail:()=>{r("error",{},{errMsg:"error"})}})}return e.src&&a(),W(()=>e.src,a),xe(()=>{n&&n.abort()}),i}var fc=de({name:"CoverImage",props:mw,emits:["click","load","error"],setup(e,t){var{emit:r}=t,i=$(null),n=Ae(i,r),a=Te({src:""}),s=_w(e,a,n);return uc(i,n,a),()=>O("uni-cover-image",{ref:i,style:s.value},[O("div",{class:"uni-cover-image"},null)],4)}});class bw extends _e{constructor(t,r,i,n){super(t,"uni-cover-image",fc,r,i,n)}}var r1="",ww=de({name:"CoverView",emits:["click"],setup(e,t){var{emit:r}=t,i=$(null),n=$(null),a=Ae(i,r),s=Te({text:""});return uc(i,a,s),jr(()=>{var o=n.value.childNodes[0];s.text=o&&o instanceof Text?o.textContent:"",window.dispatchEvent(new CustomEvent("updateview"))}),()=>O("uni-cover-view",{ref:i},[O("div",{ref:n,class:"uni-cover-view"},null,512)],512)}});class yw extends Kr{constructor(t,r,i,n){super(t,"uni-cover-view",ww,r,i,n,".uni-cover-view")}}var i1="";class Sw extends _e{constructor(t,r,i,n){super(t,"uni-editor",h_,r,i,n)}}var n1="";class xw extends _e{constructor(t,r,i,n){super(t,"uni-form",x0,r,i,n,"span")}}class Ew extends fr{constructor(t,r,i){super(t,"uni-functional-page-navigator",r,i)}}var a1="";class Tw extends _e{constructor(t,r,i,n){super(t,"uni-icon",__,r,i,n)}}var s1="";class Cw extends _e{constructor(t,r,i,n){super(t,"uni-image",y_,r,i,n)}}var o1="";class Iw extends _e{constructor(t,r,i,n){super(t,"uni-input",W_,r,i,n)}}var l1="";class Ow extends _e{constructor(t,r,i,n){super(t,"uni-label",C0,r,i,n)}}class Aw extends fr{constructor(t,r,i){super(t,"uni-live-player",r,i)}}class Mw extends fr{constructor(t,r,i){super(t,"uni-live-pusher",r,i)}}var u1="",Rw=(e,t,r)=>{r({coord:{latitude:t,longitude:e}})};function Rs(e){if(e.indexOf("#")!==0)return{color:e,opacity:1};var t=e.substr(7,2);return{color:e.substr(0,7),opacity:t?Number("0x"+t)/255:1}}var Pw={id:{type:String,default:""},latitude:{type:[Number,String],default:""},longitude:{type:[Number,String],default:""},scale:{type:[String,Number],default:16},markers:{type:Array,default(){return[]}},polyline:{type:Array,default(){return[]}},circles:{type:Array,default(){return[]}},controls:{type:Array,default(){return[]}}},Lw=de({name:"Map",props:Pw,emits:["click","regionchange","controltap","markertap","callouttap"],setup(e,t){var{emit:r}=t,i=$(null),n=Ae(i,r),a=$(null),s=As(e,["id"]),{position:o,hidden:l,onParentReady:u}=Xr(a),v,{_addMarkers:c,_addMapLines:m,_addMapCircles:g,_setMap:_}=Nw(e,n);u(()=>{v=ue(plus.maps.create(Ct()+"-map-"+(e.id||Date.now()),Object.assign({},s.value,o,(()=>{if(e.latitude&&e.longitude)return{center:new plus.maps.Point(Number(e.longitude),Number(e.latitude))}})())),{__markers__:[],__lines__:[],__circles__:[]}),v.setZoom(parseInt(String(e.scale))),plus.webview.currentWebview().append(v),l.value&&v.hide(),v.onclick=w=>{n("click",{},w)},v.onstatuschanged=w=>{n("regionchange",{},{})},_(v),c(e.markers),m(e.polyline),g(e.circles),W(()=>s.value,w=>v&&v.setStyles(w),{deep:!0}),W(()=>o,w=>v&&v.setStyles(w),{deep:!0}),W(l,w=>{v&&v[w?"hide":"show"]()}),W(()=>e.scale,w=>{v&&v.setZoom(parseInt(String(w)))}),W([()=>e.latitude,()=>e.longitude],w=>{var[p,h]=w;v&&v.setStyles({center:new plus.maps.Point(Number(p),Number(h))})}),W(()=>e.markers,w=>{c(w,!0)},{deep:!0}),W(()=>e.polyline,w=>{m(w)},{deep:!0}),W(()=>e.circles,w=>{g(w)},{deep:!0})});var b=Q(()=>e.controls.map(w=>{var p={position:"absolute"};return["top","left","width","height"].forEach(h=>{w.position[h]&&(p[h]=w.position[h]+"px")}),{id:w.id,iconPath:tt(w.iconPath),position:p,clickable:w.clickable}}));return xe(()=>{v&&(v.close(),_(null))}),()=>O("uni-map",{ref:i,id:e.id},[O("div",{ref:a,class:"uni-map-container"},null,512),b.value.map((w,p)=>O(fc,{key:p,src:w.iconPath,style:w.position,"auto-size":!0,onClick:()=>w.clickable&&n("controltap",{},{controlId:w.id})},null,8,["src","style","auto-size","onClick"])),O("div",{class:"uni-map-slot"},null)],8,["id"])}});function Nw(e,t){var r;function i(g){var{longitude:_,latitude:b}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};!r||(r.setCenter(new plus.maps.Point(Number(_||e.longitude),Number(b||e.latitude))),g({errMsg:"moveToLocation:ok"}))}function n(g){!r||r.getCurrentCenter((_,b)=>{g({longitude:b.getLng(),latitude:b.getLat(),errMsg:"getCenterLocation:ok"})})}function a(g){if(!!r){var _=r.getBounds();g({southwest:_.getSouthWest(),northeast:_.getNorthEast(),errMsg:"getRegion:ok"})}}function s(g){!r||g({scale:r.getZoom(),errMsg:"getScale:ok"})}function o(g){if(!!r){var{id:_,latitude:b,longitude:w,iconPath:p,callout:h,label:f}=g;Rw(w,b,d=>{var y,{latitude:x,longitude:T}=d.coord,C=new plus.maps.Marker(new plus.maps.Point(T,x));p&&C.setIcon(tt(p)),f&&f.content&&C.setLabel(f.content);var A=void 0;h&&h.content&&(A=new plus.maps.Bubble(h.content)),A&&C.setBubble(A),(_||_===0)&&(C.onclick=U=>{t("markertap",{},{markerId:_})},A&&(A.onclick=()=>{t("callouttap",{},{markerId:_})})),(y=r)===null||y===void 0||y.addOverlay(C),r.__markers__.push(C)})}}function l(){if(!!r){var g=r.__markers__;g.forEach(_=>{var b;(b=r)===null||b===void 0||b.removeOverlay(_)}),r.__markers__=[]}}function u(g,_){_&&l(),g.forEach(b=>{o(b)})}function v(g){!r||(r.__lines__.length>0&&(r.__lines__.forEach(_=>{var b;(b=r)===null||b===void 0||b.removeOverlay(_)}),r.__lines__=[]),g.forEach(_=>{var b,{color:w,width:p}=_,h=_.points.map(y=>new plus.maps.Point(y.longitude,y.latitude)),f=new plus.maps.Polyline(h);if(w){var d=Rs(w);f.setStrokeColor(d.color),f.setStrokeOpacity(d.opacity)}p&&f.setLineWidth(p),(b=r)===null||b===void 0||b.addOverlay(f),r.__lines__.push(f)}))}function c(g){!r||(r.__circles__.length>0&&(r.__circles__.forEach(_=>{var b;(b=r)===null||b===void 0||b.removeOverlay(_)}),r.__circles__=[]),g.forEach(_=>{var b,{latitude:w,longitude:p,color:h,fillColor:f,radius:d,strokeWidth:y}=_,x=new plus.maps.Circle(new plus.maps.Point(p,w),d);if(h){var T=Rs(h);x.setStrokeColor(T.color),x.setStrokeOpacity(T.opacity)}if(f){var C=Rs(f);x.setFillColor(C.color),x.setFillOpacity(C.opacity)}y&&x.setLineWidth(y),(b=r)===null||b===void 0||b.addOverlay(x),r.__circles__.push(x)}))}var m={moveToLocation:i,getCenterLocation:n,getRegion:a,getScale:s};return mn((g,_,b)=>{m[g]&&m[g](b,_)},_n(),!0),{_addMarkers:u,_addMapLines:v,_addMapCircles:c,_setMap(g){r=g}}}class Dw extends _e{constructor(t,r,i,n){super(t,"uni-map",Lw,r,i,n,".uni-map-slot")}}var f1="";class kw extends Kr{constructor(t,r,i,n){super(t,"uni-movable-area",Y_,r,i,n)}}var c1="";class Bw extends _e{constructor(t,r,i,n){super(t,"uni-movable-view",K_,r,i,n)}}var v1="";class Fw extends _e{constructor(t,r,i,n){super(t,"uni-navigator",Q_,r,i,n)}}class $w extends fr{constructor(t,r,i){super(t,"uni-official-account",r,i)}}class Uw extends fr{constructor(t,r,i){super(t,"uni-open-data",r,i)}}var qt,cc,cr;function vc(){return typeof window=="object"&&typeof navigator=="object"&&typeof document=="object"?"webview":"v8"}function dc(){return qt.webview.currentWebview().id}var bn,Ps,Ls={};function Ns(e){var t=e.data&&e.data.__message;if(!(!t||!t.__page)){var r=t.__page,i=Ls[r];i&&i(t),t.keep||delete Ls[r]}}function Ww(e,t){vc()==="v8"?cr?(bn&&bn.close(),bn=new cr(dc()),bn.onmessage=Ns):Ps||(Ps=cc.requireModule("globalEvent"),Ps.addEventListener("plusMessage",Ns)):window.__plusMessage=Ns,Ls[e]=t}class Vw{constructor(t){this.webview=t}sendMessage(t){var r=JSON.parse(JSON.stringify({__message:{data:t}})),i=this.webview.id;if(cr){var n=new cr(i);n.postMessage(r)}else qt.webview.postMessageToUniNView&&qt.webview.postMessageToUniNView(r,i)}close(){this.webview.close()}}function Hw(e){var{context:t={},url:r,data:i={},style:n={},onMessage:a,onClose:s}=e;qt=t.plus||plus,cc=t.weex||(typeof weex=="object"?weex:null),cr=t.BroadcastChannel||(typeof BroadcastChannel=="object"?BroadcastChannel:null);var o={autoBackButton:!0,titleSize:"17px"},l="page".concat(Date.now());n=ue({},n),n.titleNView!==!1&&n.titleNView!=="none"&&(n.titleNView=ue(o,n.titleNView));var u={top:0,bottom:0,usingComponents:{},popGesture:"close",scrollIndicator:"none",animationType:"pop-in",animationDuration:200,uniNView:{path:"".concat(typeof process=="object"&&process.env&&{}.VUE_APP_TEMPLATE_PATH||"","/").concat(r,".js"),defaultFontSize:qt.screen.resolutionWidth/20,viewport:qt.screen.resolutionWidth}};n=ue(u,n);var v=qt.webview.create("",l,n,{extras:{from:dc(),runtime:vc(),data:i,useGlobalEvent:!cr}});return v.addEventListener("close",s),Ww(l,c=>{typeof a=="function"&&a(c.data),c.keep||v.close("auto")}),v.show(n.animationType,n.animationDuration),new Vw(v)}var Ee={SELECTOR:"selector",MULTISELECTOR:"multiSelector",TIME:"time",DATE:"date"},vr={YEAR:"year",MONTH:"month",DAY:"day"};function wn(e){return e>9?e:"0".concat(e)}function yn(e,t){e=String(e||"");var r=new Date;if(t===Ee.TIME){var i=e.split(":");i.length===2&&r.setHours(parseInt(i[0]),parseInt(i[1]))}else{var n=e.split("-");n.length===3&&r.setFullYear(parseInt(n[0]),parseInt(String(parseFloat(n[1])-1)),parseInt(n[2]))}return r}function jw(e){if(e.mode===Ee.TIME)return"00:00";if(e.mode===Ee.DATE){var t=new Date().getFullYear()-100;switch(e.fields){case vr.YEAR:return t;case vr.MONTH:return t+"-01";default:return t+"-01-01"}}return""}function zw(e){if(e.mode===Ee.TIME)return"23:59";if(e.mode===Ee.DATE){var t=new Date().getFullYear()+100;switch(e.fields){case vr.YEAR:return t;case vr.MONTH:return t+"-12";default:return t+"-12-31"}}return""}var Yw={name:{type:String,default:""},range:{type:Array,default(){return[]}},rangeKey:{type:String,default:""},value:{type:[Number,String,Array],default:0},mode:{type:String,default:Ee.SELECTOR,validator(e){return Object.values(Ee).indexOf(e)>=0}},fields:{type:String,default:""},start:{type:String,default:jw},end:{type:String,default:zw},disabled:{type:[Boolean,String],default:!1}},qw=de({name:"Picker",props:Yw,emits:["change","cancel","columnchange"],setup(e,t){var{emit:r}=t;ah();var{t:i,getLocale:n}=He(),a=$(null),s=Ae(a,r),o=$(null),l=$(null),u=()=>{var p=e.value;switch(e.mode){case Ee.MULTISELECTOR:{Array.isArray(p)||(p=[]),Array.isArray(o.value)||(o.value=[]);for(var h=o.value.length=Math.max(p.length,e.range.length),f=0;f{l.value&&l.value.sendMessage(p)},c=p=>{var h={event:"cancel"};l.value=Hw({url:"__uniapppicker",data:p,style:{titleNView:!1,animationType:"none",animationDuration:0,background:"rgba(0,0,0,0)",popGesture:"none"},onMessage:f=>{var d=f.event;if(d==="created"){v(p);return}if(d==="columnchange"){delete f.event,s(d,{},f);return}h=f},onClose:()=>{l.value=null;var f=h.event;delete h.event,f&&s(f,{},h)}})},m=(p,h)=>{plus.nativeUI[e.mode===Ee.TIME?"pickTime":"pickDate"](f=>{var d=f.date;s("change",{},{value:e.mode===Ee.TIME?"".concat(wn(d.getHours()),":").concat(wn(d.getMinutes())):"".concat(d.getFullYear(),"-").concat(wn(d.getMonth()+1),"-").concat(wn(d.getDate()))})},()=>{s("cancel",{},{})},e.mode===Ee.TIME?{time:yn(e.value,Ee.TIME),popover:h}:{date:yn(e.value,Ee.DATE),minDate:yn(e.start,Ee.DATE),maxDate:yn(e.end,Ee.DATE),popover:h})},g=(p,h)=>{(p.mode===Ee.TIME||p.mode===Ee.DATE)&&!p.fields?m(p,h):(p.fields=Object.values(vr).includes(p.fields)?p.fields:vr.DAY,c(p))},_=p=>{if(!e.disabled){var h=p.currentTarget,f=h.getBoundingClientRect();g(Object.assign({},e,{value:o.value,locale:n(),messages:{done:i("uni.picker.done"),cancel:i("uni.picker.cancel")}}),{top:f.top+oc(),left:f.left,width:f.width,height:f.height})}},b=pe(ut,!1),w={submit:()=>[e.name,o.value],reset:()=>{switch(e.mode){case Ee.SELECTOR:o.value=0;break;case Ee.MULTISELECTOR:Array.isArray(e.value)&&(o.value=e.value.map(p=>0));break;case Ee.DATE:case Ee.TIME:o.value="";break}}};return b&&(b.addField(w),xe(()=>b.removeField(w))),Object.keys(e).forEach(p=>{p!=="name"&&W(()=>e[p],h=>{var f={};f[p]=h,v(f)},{deep:!0})}),W(()=>e.value,u,{deep:!0}),u(),()=>O("uni-picker",{ref:a,onClick:_},[O("slot",null,null)],8,["onClick"])}});class Xw extends _e{constructor(t,r,i,n){super(t,"uni-picker",qw,r,i,n)}}var d1="";class Kw extends Kr{constructor(t,r,i,n){super(t,"uni-picker-view",rb,r,i,n,".uni-picker-view-wrapper")}}var h1="";class Gw extends Kr{constructor(t,r,i,n){super(t,"uni-picker-view-column",fb,r,i,n,".uni-picker-view-content")}}var g1="";class Jw extends _e{constructor(t,r,i,n){super(t,"uni-progress",vb,r,i,n)}}var p1="";class Zw extends _e{constructor(t,r,i,n){super(t,"uni-radio",_b,r,i,n,".uni-radio-wrapper")}setText(t){Ms(this.$holder,"uni-radio-input",t)}}var m1="";class Qw extends _e{constructor(t,r,i,n){super(t,"uni-radio-group",gb,r,i,n)}}var _1="";class ey extends _e{constructor(t,r,i,n){super(t,"uni-rich-text",Ib,r,i,n)}}var b1="";class ty extends _e{constructor(t,r,i,n){super(t,"uni-scroll-view",Ab,r,i,n,".uni-scroll-view-content")}setText(t){Ms(this.$holder,"uni-scroll-view-refresher",t)}}var w1="";class ry extends _e{constructor(t,r,i,n){super(t,"uni-slider",Lb,r,i,n)}}var y1="";class iy extends Kr{constructor(t,r,i,n){super(t,"uni-swiper",Ub,r,i,n,".uni-swiper-slide-frame")}}var S1="";class ny extends _e{constructor(t,r,i,n){super(t,"uni-swiper-item",Vb,r,i,n)}}var x1="";class ay extends _e{constructor(t,r,i,n){super(t,"uni-switch",jb,r,i,n)}}var E1="";class sy extends _e{constructor(t,r,i,n){super(t,"uni-textarea",Gb,r,i,n)}}var T1="",oy={id:{type:String,default:""},src:{type:String,default:""},duration:{type:[Number,String],default:""},controls:{type:[Boolean,String],default:!0},danmuList:{type:Array,default(){return[]}},danmuBtn:{type:[Boolean,String],default:!1},enableDanmu:{type:[Boolean,String],default:!1},autoplay:{type:[Boolean,String],default:!1},loop:{type:[Boolean,String],default:!1},muted:{type:[Boolean,String],default:!1},objectFit:{type:String,default:"contain"},poster:{type:String,default:""},direction:{type:[String,Number],default:""},showProgress:{type:Boolean,default:!0},initialTime:{type:[String,Number],default:0},showFullscreenBtn:{type:[Boolean,String],default:!0},pageGesture:{type:[Boolean,String],default:!1},enableProgressGesture:{type:[Boolean,String],default:!0},showPlayBtn:{type:[Boolean,String],default:!0},enablePlayGesture:{type:[Boolean,String],default:!0},showCenterPlayBtn:{type:[Boolean,String],default:!0},showLoading:{type:[Boolean,String],default:!0},codec:{type:String,default:"hardware"},httpCache:{type:[Boolean,String],default:!1},playStrategy:{type:[Number,String],default:0},header:{type:Object,default(){return{}}},advanced:{type:Array,default(){return[]}}},hc=["play","pause","ended","timeupdate","fullscreenchange","fullscreenclick","waiting","error"],ly=["play","pause","stop","seek","sendDanmu","playbackRate","requestFullScreen","exitFullScreen"],uy=de({name:"Video",props:oy,emits:hc,setup(e,t){var{emit:r}=t,i=$(null),n=Ae(i,r),a=$(null),s=As(e,["id"]),{position:o,hidden:l,onParentReady:u}=Xr(a),v;u(()=>{v=plus.video.createVideoPlayer("video"+Date.now(),Object.assign({},s.value,o)),plus.webview.currentWebview().append(v),l.value&&v.hide(),hc.forEach(m=>{v.addEventListener(m,g=>{n(m,{},g.detail)})}),W(()=>s.value,m=>v.setStyles(m),{deep:!0}),W(()=>o,m=>v.setStyles(m),{deep:!0}),W(()=>l.value,m=>{v[m?"hide":"show"](),m||v.setStyles(o)})});var c=_n();return mn((m,g)=>{if(ly.includes(m)){var _;switch(m){case"seek":_=g.position;break;case"sendDanmu":_=g;break;case"playbackRate":_=g.rate;break;case"requestFullScreen":_=g.direction;break}v&&v[m](_)}},c,!0),xe(()=>{v&&v.close()}),()=>O("uni-video",{ref:i,id:e.id},[O("div",{ref:a,class:"uni-video-container"},null,512),O("div",{class:"uni-video-slot"},null)],8,["id"])}});class fy extends _e{constructor(t,r,i,n){super(t,"uni-video",uy,r,i,n,".uni-video-slot")}}var C1="",cy={src:{type:String,default:""},webviewStyles:{type:Object,default(){return{}}}},Xe,vy=e=>{var{htmlId:t,src:r,webviewStyles:i}=e,n=plus.webview.currentWebview(),a=ue(i,{"uni-app":"none",isUniH5:!0}),s=n.getTitleNView();if(s){var o=Po+parseFloat(a.top||"0");plus.navigator.isImmersedStatusbar()&&(o+=Yu()),a.top=String(o),a.bottom=a.bottom||"0"}Xe=plus.webview.create(r,t,a),s&&Xe.addEventListener("titleUpdate",function(){var l,u=(l=Xe)===null||l===void 0?void 0:l.getTitle();n.setStyle({titleNView:{titleText:!u||u==="null"?" ":u}})}),plus.webview.currentWebview().append(Xe)},dy=()=>{var e;plus.webview.currentWebview().remove(Xe),(e=Xe)===null||e===void 0||e.close("none"),Xe=null},hy=de({name:"WebView",props:cy,setup(e){var t=Ct(),r=$(null),{hidden:i,onParentReady:n}=Xr(r),a=Q(()=>e.webviewStyles);return n(()=>{var s,o=$(tm+t);vy({htmlId:o.value,src:tt(e.src),webviewStyles:a.value}),UniViewJSBridge.publishHandler(Qp,{},t),i.value&&((s=Xe)===null||s===void 0||s.hide())}),xe(()=>{dy(),UniViewJSBridge.publishHandler(em,{},t)}),W(()=>e.src,s=>{var o,l=tt(s)||"";if(!!l){if(/^(http|https):\/\//.test(l)&&e.webviewStyles.progress){var u;(u=Xe)===null||u===void 0||u.setStyle({progress:{color:e.webviewStyles.progress.color}})}(o=Xe)===null||o===void 0||o.loadURL(l)}}),W(a,s=>{var o;(o=Xe)===null||o===void 0||o.setStyle(s)}),W(i,s=>{Xe&&Xe[s?"hide":"show"]()}),()=>O("uni-web-view",{ref:r},null,512)}});class gy extends _e{constructor(t,r,i,n){super(t,"uni-web-view",hy,r,i,n)}}var py={"#text":tw,"#comment":p0,VIEW:aw,IMAGE:Cw,TEXT:ew,NAVIGATOR:Fw,FORM:xw,BUTTON:fw,INPUT:Iw,LABEL:Ow,RADIO:Zw,CHECKBOX:dw,"CHECKBOX-GROUP":hw,AD:uw,CAMERA:cw,CANVAS:vw,"COVER-IMAGE":bw,"COVER-VIEW":yw,EDITOR:Sw,"FUNCTIONAL-PAGE-NAVIGATOR":Ew,ICON:Tw,"RADIO-GROUP":Qw,"LIVE-PLAYER":Aw,"LIVE-PUSHER":Mw,MAP:Dw,"MOVABLE-AREA":kw,"MOVABLE-VIEW":Bw,"OFFICIAL-ACCOUNT":$w,"OPEN-DATA":Uw,PICKER:Xw,"PICKER-VIEW":Kw,"PICKER-VIEW-COLUMN":Gw,PROGRESS:Jw,"RICH-TEXT":ey,"SCROLL-VIEW":ty,SLIDER:ry,SWIPER:iy,"SWIPER-ITEM":ny,SWITCH:ay,TEXTAREA:sy,VIDEO:fy,"WEB-VIEW":gy};function my(e,t){return()=>tp(e,t)}var Sn=new Map;function Ke(e){return Sn.get(e)}function _y(e){return Sn.get(e)}function gc(e){return Sn.delete(e)}function pc(e,t,r,i){var n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{},a;if(e===0)a=new lr(e,t,r,document.createElement(t));else{var s=py[t];s?a=new s(e,r,i,n):a=new hf(e,document.createElement(t),r,i,n)}return Sn.set(e,a),a}var Ds=[],mc=!1;function _c(e){if(mc)return e();Ds.push(e)}function ks(){mc=!0,Ds.forEach(e=>e()),Ds.length=0}function by(){}function bc(e){var{css:t,route:r,platform:i,pixelRatio:n,windowWidth:a,disableScroll:s,statusbarHeight:o,windowTop:l,windowBottom:u}=e;wy(r),yy(i,n,a),Sy();var v=plus.webview.currentWebview().id;window.__id__=v,document.title="".concat(r,"[").concat(v,"]"),Ey(o,l,u),s&&document.addEventListener("touchmove",zp),t?xy(r):ks()}function wy(e){window.__PAGE_INFO__={route:e}}function yy(e,t,r){window.__SYSTEM_INFO__={platform:e,pixelRatio:t,windowWidth:r}}function Sy(){pc(0,"div",-1,-1).$=document.getElementById("app")}function xy(e){var t=document.createElement("link");t.type="text/css",t.rel="stylesheet",t.href=e+".css",t.onload=ks,t.onerror=ks,document.head.appendChild(t)}function Ey(e,t,r){var i={"--window-left":"0px","--window-right":"0px","--window-top":t+"px","--window-bottom":r+"px","--status-bar-height":e+"px"};Np(i)}var wc=!1;function Ty(e){if(!wc){wc=!0;var t={onReachBottomDistance:e,onPageScroll(r){UniViewJSBridge.publishHandler(Do,{scrollTop:r})},onReachBottom(){UniViewJSBridge.publishHandler(ko)}};requestAnimationFrame(()=>document.addEventListener("scroll",Yp(t)))}}function Cy(e,t){var{scrollTop:r,selector:i,duration:n}=e;Ed(i||r||0,n),t()}function Iy(e){var t=e[0];t[0]===la?Oy(t):_c(()=>Ay(e))}function Oy(e){return bc(e[1])}function Ay(e){var t=e[0],r=Gm(t[0]===Uu?t[1]:[]);e.forEach(i=>{switch(i[0]){case la:return bc(i[1]);case jo:return by();case ua:return pc(i[1],r(i[2]),i[3],i[4],Jm(r,i[5]));case zo:return Ke(i[1]).remove();case Yo:return Ke(i[1]).setAttr(r(i[2]),r(i[3]));case qo:return Ke(i[1]).removeAttr(r(i[2]));case Xo:return Ke(i[1]).addEvent(r(i[2]),i[3]);case Jo:return Ke(i[1]).addWxsEvent(r(i[2]),r(i[3]),i[4]);case Ko:return Ke(i[1]).removeEvent(r(i[2]));case Go:return Ke(i[1]).setText(r(i[2]));case Zo:return Ty(i[1])}}),t0()}function My(){var{subscribe:e}=UniViewJSBridge;e(as,Iy),e(rm,He().setLocale),e($u,Ry)}function Ry(){UniViewJSBridge.publishHandler("webviewReady")}function yc(e){return window.__$__(e).$}function Py(e){var t={};if(e.id&&(t.id=""),e.dataset&&(t.dataset={}),e.rect&&(t.left=0,t.right=0,t.top=0,t.bottom=0),e.size&&(t.width=document.documentElement.clientWidth,t.height=document.documentElement.clientHeight),e.scrollOffset){var r=document.documentElement,i=document.body;t.scrollLeft=r.scrollLeft||i.scrollLeft||0,t.scrollTop=r.scrollTop||i.scrollTop||0,t.scrollHeight=r.scrollHeight||i.scrollHeight||0,t.scrollWidth=r.scrollWidth||i.scrollWidth||0}return t}function Bs(e,t){var r={},{top:i}=Lp();if(t.id&&(r.id=e.id),t.dataset&&(r.dataset=ta(e)),t.rect||t.size){var n=e.getBoundingClientRect();t.rect&&(r.left=n.left,r.right=n.right,r.top=n.top-i,r.bottom=n.bottom-i),t.size&&(r.width=n.width,r.height=n.height)}if(Array.isArray(t.properties)&&t.properties.forEach(o=>{o=o.replace(/-([a-z])/g,function(l,u){return u.toUpperCase()})}),t.scrollOffset)if(e.tagName==="UNI-SCROLL-VIEW"){var a=e.children[0].children[0];r.scrollLeft=a.scrollLeft,r.scrollTop=a.scrollTop,r.scrollHeight=a.scrollHeight,r.scrollWidth=a.scrollWidth}else r.scrollLeft=0,r.scrollTop=0,r.scrollHeight=0,r.scrollWidth=0;if(Array.isArray(t.computedStyle)){var s=getComputedStyle(e);t.computedStyle.forEach(o=>{r[o]=s[o]})}return t.context&&(r.contextInfo=Zb(e)),r}function Ly(e,t){return e?window.__$__(e).$:t.$el}function Sc(e,t){var r=e.matches||e.matchesSelector||e.mozMatchesSelector||e.msMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector||function(i){for(var n=this.parentElement.querySelectorAll(i),a=n.length;--a>=0&&n.item(a)!==this;);return a>-1};return r.call(e,t)}function Ny(e,t,r,i,n){var a=Ly(t,e),s=a.parentElement;if(!s)return i?null:[];var{nodeType:o}=a,l=o===3||o===8;if(i){var u=l?s.querySelector(r):Sc(a,r)?a:a.querySelector(r);return u?Bs(u,n):null}else{var v=[],c=(l?s:a).querySelectorAll(r);return c&&c.length&&[].forEach.call(c,m=>{v.push(Bs(m,n))}),!l&&Sc(a,r)&&v.unshift(Bs(a,n)),v}}function Dy(e,t,r){var i=[];t.forEach(n=>{var{component:a,selector:s,single:o,fields:l}=n;a===null?i.push(Py(l)):i.push(Ny(e,a,s,o,l))}),r(i)}function ky(e,t){var{pageStyle:r,rootFontSize:i}=t;if(r){var n=document.querySelector("uni-page-body")||document.body;n.setAttribute("style",r)}i&&document.documentElement.style.fontSize!==i&&(document.documentElement.style.fontSize=i)}function By(e,t){var{reqId:r,component:i,options:n,callback:a}=e,s=yc(i);(s.__io||(s.__io={}))[r]=Vm(s,n,a)}function Fy(e,t){var{reqId:r,component:i}=e,n=yc(i),a=n.__io&&n.__io[r];a&&(a.disconnect(),delete n.__io[r])}var Fs={},$s={};function $y(e){var t=[],r=["width","minWidth","maxWidth","height","minHeight","maxHeight","orientation"];for(var i of r)i!=="orientation"&&e[i]&&Number(e[i]>=0)&&t.push("(".concat(xc(i),": ").concat(Number(e[i]),"px)")),i==="orientation"&&e[i]&&t.push("(".concat(xc(i),": ").concat(e[i],")"));var n=t.join(" and ");return n}function xc(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase()}function Uy(e,t){var{reqId:r,component:i,options:n,callback:a}=e,s=Fs[r]=window.matchMedia($y(n)),o=$s[r]=l=>a(l.matches);o(s),s.addListener(o)}function Wy(e,t){var{reqId:r,component:i}=e,n=$s[r],a=Fs[r];a&&(a.removeListener(n),delete $s[r],delete Fs[r])}function Vy(e,t){var{family:r,source:i,desc:n}=e;xd(r,i,n).then(()=>{t()}).catch(a=>{t(a.toString())})}var Hy={$el:document.body};function jy(){var e=Ct();fh(e,t=>function(){for(var r=arguments.length,i=new Array(r),n=0;n{t.apply(null,i)})}),at(e,"requestComponentInfo",(t,r)=>{Dy(Hy,t.reqs,r)}),at(e,"addIntersectionObserver",t=>{By(ue({},t,{callback(r){UniViewJSBridge.publishHandler(t.eventName,r)}}))}),at(e,"removeIntersectionObserver",t=>{Fy(t)}),at(e,"addMediaQueryObserver",t=>{Uy(ue({},t,{callback(r){UniViewJSBridge.publishHandler(t.eventName,r)}}))}),at(e,"removeMediaQueryObserver",t=>{Wy(t)}),at(e,$m,Cy),at(e,Fm,Vy),at(e,Bm,t=>{ky(null,t)})}window.uni=Xm,window.UniViewJSBridge=Wu,window.rpx2px=Gu,window.__$__=Ke,window.__f__=Od;function Ec(){bh(),jy(),My(),Km(),Wu.publishHandler($u)}typeof plus!="undefined"?Ec():document.addEventListener("plusready",Ec)}); +(function(Yn){typeof define=="function"&&define.amd?define(Yn):Yn()})(function(){"use strict";var Yn="",DT="",BT="",Pr={exports:{}},sa={exports:{}},la={exports:{}},Nh=la.exports={version:"2.6.12"};typeof __e=="number"&&(__e=Nh);var $t={exports:{}},ua=$t.exports=typeof ua!="undefined"&&ua.Math==Math?ua:typeof self!="undefined"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=ua);var Dh=la.exports,Nl=$t.exports,Dl="__core-js_shared__",Bl=Nl[Dl]||(Nl[Dl]={});(sa.exports=function(e,t){return Bl[e]||(Bl[e]=t!==void 0?t:{})})("versions",[]).push({version:Dh.version,mode:"window",copyright:"\xA9 2020 Denis Pushkarev (zloirock.ru)"});var Bh=0,$h=Math.random(),qn=function(e){return"Symbol(".concat(e===void 0?"":e,")_",(++Bh+$h).toString(36))},Xn=sa.exports("wks"),Fh=qn,Zn=$t.exports.Symbol,$l=typeof Zn=="function",zh=Pr.exports=function(e){return Xn[e]||(Xn[e]=$l&&Zn[e]||($l?Zn:Fh)("Symbol."+e))};zh.store=Xn;var fa={},Kn=function(e){return typeof e=="object"?e!==null:typeof e=="function"},Uh=Kn,Gn=function(e){if(!Uh(e))throw TypeError(e+" is not an object!");return e},ca=function(e){try{return!!e()}catch(t){return!0}},si=!ca(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7}),Fl=Kn,Jn=$t.exports.document,Hh=Fl(Jn)&&Fl(Jn.createElement),zl=function(e){return Hh?Jn.createElement(e):{}},Wh=!si&&!ca(function(){return Object.defineProperty(zl("div"),"a",{get:function(){return 7}}).a!=7}),va=Kn,Vh=function(e,t){if(!va(e))return e;var r,i;if(t&&typeof(r=e.toString)=="function"&&!va(i=r.call(e))||typeof(r=e.valueOf)=="function"&&!va(i=r.call(e))||!t&&typeof(r=e.toString)=="function"&&!va(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")},Ul=Gn,jh=Wh,Yh=Vh,qh=Object.defineProperty;fa.f=si?Object.defineProperty:function(t,r,i){if(Ul(t),r=Yh(r,!0),Ul(i),jh)try{return qh(t,r,i)}catch(a){}if("get"in i||"set"in i)throw TypeError("Accessors not supported!");return"value"in i&&(t[r]=i.value),t};var Hl=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}},Xh=fa,Zh=Hl,Nr=si?function(e,t,r){return Xh.f(e,t,Zh(1,r))}:function(e,t,r){return e[t]=r,e},Qn=Pr.exports("unscopables"),eo=Array.prototype;eo[Qn]==null&&Nr(eo,Qn,{});var Kh=function(e){eo[Qn][e]=!0},Gh=function(e,t){return{value:t,done:!!e}},to={},Jh={}.toString,Qh=function(e){return Jh.call(e).slice(8,-1)},eg=Qh,tg=Object("z").propertyIsEnumerable(0)?Object:function(e){return eg(e)=="String"?e.split(""):Object(e)},Wl=function(e){if(e==null)throw TypeError("Can't call method on "+e);return e},rg=tg,ig=Wl,da=function(e){return rg(ig(e))},ha={exports:{}},ag={}.hasOwnProperty,ga=function(e,t){return ag.call(e,t)},ng=sa.exports("native-function-to-string",Function.toString),og=$t.exports,pa=Nr,Vl=ga,ro=qn("src"),io=ng,jl="toString",sg=(""+io).split(jl);la.exports.inspectSource=function(e){return io.call(e)},(ha.exports=function(e,t,r,i){var a=typeof r=="function";a&&(Vl(r,"name")||pa(r,"name",t)),e[t]!==r&&(a&&(Vl(r,ro)||pa(r,ro,e[t]?""+e[t]:sg.join(String(t)))),e===og?e[t]=r:i?e[t]?e[t]=r:pa(e,t,r):(delete e[t],pa(e,t,r)))})(Function.prototype,jl,function(){return typeof this=="function"&&this[ro]||io.call(this)});var Yl=function(e){if(typeof e!="function")throw TypeError(e+" is not a function!");return e},lg=Yl,ug=function(e,t,r){if(lg(e),t===void 0)return e;switch(r){case 1:return function(i){return e.call(t,i)};case 2:return function(i,a){return e.call(t,i,a)};case 3:return function(i,a,n){return e.call(t,i,a,n)}}return function(){return e.apply(t,arguments)}},Dr=$t.exports,ma=la.exports,fg=Nr,cg=ha.exports,ql=ug,ao="prototype",We=function(e,t,r){var i=e&We.F,a=e&We.G,n=e&We.S,o=e&We.P,s=e&We.B,l=a?Dr:n?Dr[t]||(Dr[t]={}):(Dr[t]||{})[ao],u=a?ma:ma[t]||(ma[t]={}),f=u[ao]||(u[ao]={}),v,p,d,_;a&&(r=t);for(v in r)p=!i&&l&&l[v]!==void 0,d=(p?l:r)[v],_=s&&p?ql(d,Dr):o&&typeof d=="function"?ql(Function.call,d):d,l&&cg(l,v,d,e&We.U),u[v]!=d&&fg(u,v,_),o&&f[v]!=d&&(f[v]=d)};Dr.core=ma,We.F=1,We.G=2,We.S=4,We.P=8,We.B=16,We.W=32,We.U=64,We.R=128;var no=We,vg=Math.ceil,dg=Math.floor,Xl=function(e){return isNaN(e=+e)?0:(e>0?dg:vg)(e)},hg=Xl,gg=Math.min,pg=function(e){return e>0?gg(hg(e),9007199254740991):0},mg=Xl,_g=Math.max,bg=Math.min,wg=function(e,t){return e=mg(e),e<0?_g(e+t,0):bg(e,t)},xg=da,yg=pg,Sg=wg,Eg=function(e){return function(t,r,i){var a=xg(t),n=yg(a.length),o=Sg(i,n),s;if(e&&r!=r){for(;n>o;)if(s=a[o++],s!=s)return!0}else for(;n>o;o++)if((e||o in a)&&a[o]===r)return e||o||0;return!e&&-1}},Zl=sa.exports("keys"),Tg=qn,oo=function(e){return Zl[e]||(Zl[e]=Tg(e))},Kl=ga,Cg=da,Og=Eg(!1),Ag=oo("IE_PROTO"),Ig=function(e,t){var r=Cg(e),i=0,a=[],n;for(n in r)n!=Ag&&Kl(r,n)&&a.push(n);for(;t.length>i;)Kl(r,n=t[i++])&&(~Og(a,n)||a.push(n));return a},Gl="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),kg=Ig,Mg=Gl,so=Object.keys||function(t){return kg(t,Mg)},Rg=fa,Lg=Gn,Pg=so,Ng=si?Object.defineProperties:function(t,r){Lg(t);for(var i=Pg(r),a=i.length,n=0,o;a>n;)Rg.f(t,o=i[n++],r[o]);return t},Jl=$t.exports.document,Dg=Jl&&Jl.documentElement,Bg=Gn,$g=Ng,Ql=Gl,Fg=oo("IE_PROTO"),lo=function(){},uo="prototype",_a=function(){var e=zl("iframe"),t=Ql.length,r="<",i=">",a;for(e.style.display="none",Dg.appendChild(e),e.src="javascript:",a=e.contentWindow.document,a.open(),a.write(r+"script"+i+"document.F=Object"+r+"/script"+i),a.close(),_a=a.F;t--;)delete _a[uo][Ql[t]];return _a()},zg=Object.create||function(t,r){var i;return t!==null?(lo[uo]=Bg(t),i=new lo,lo[uo]=null,i[Fg]=t):i=_a(),r===void 0?i:$g(i,r)},Ug=fa.f,Hg=ga,eu=Pr.exports("toStringTag"),tu=function(e,t,r){e&&!Hg(e=r?e:e.prototype,eu)&&Ug(e,eu,{configurable:!0,value:t})},Wg=zg,Vg=Hl,jg=tu,ru={};Nr(ru,Pr.exports("iterator"),function(){return this});var Yg=function(e,t,r){e.prototype=Wg(ru,{next:Vg(1,r)}),jg(e,t+" Iterator")},qg=Wl,iu=function(e){return Object(qg(e))},Xg=ga,Zg=iu,au=oo("IE_PROTO"),Kg=Object.prototype,Gg=Object.getPrototypeOf||function(e){return e=Zg(e),Xg(e,au)?e[au]:typeof e.constructor=="function"&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?Kg:null},fo=no,Jg=ha.exports,nu=Nr,ou=to,Qg=Yg,ep=tu,tp=Gg,li=Pr.exports("iterator"),co=!([].keys&&"next"in[].keys()),rp="@@iterator",su="keys",ba="values",lu=function(){return this},ip=function(e,t,r,i,a,n,o){Qg(r,t,i);var s=function(c){if(!co&&c in v)return v[c];switch(c){case su:return function(){return new r(this,c)};case ba:return function(){return new r(this,c)}}return function(){return new r(this,c)}},l=t+" Iterator",u=a==ba,f=!1,v=e.prototype,p=v[li]||v[rp]||a&&v[a],d=p||s(a),_=a?u?s("entries"):d:void 0,b=t=="Array"&&v.entries||p,x,m,g;if(b&&(g=tp(b.call(new e)),g!==Object.prototype&&g.next&&(ep(g,l,!0),typeof g[li]!="function"&&nu(g,li,lu))),u&&p&&p.name!==ba&&(f=!0,d=function(){return p.call(this)}),(co||f||!v[li])&&nu(v,li,d),ou[t]=d,ou[l]=lu,a)if(x={values:u?d:s(ba),keys:n?d:s(su),entries:_},o)for(m in x)m in v||Jg(v,m,x[m]);else fo(fo.P+fo.F*(co||f),t,x);return x},vo=Kh,wa=Gh,uu=to,ap=da,np=ip(Array,"Array",function(e,t){this._t=ap(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,r=this._i++;return!e||r>=e.length?(this._t=void 0,wa(1)):t=="keys"?wa(0,r):t=="values"?wa(0,e[r]):wa(0,[r,e[r]])},"values");uu.Arguments=uu.Array,vo("keys"),vo("values"),vo("entries");for(var fu=np,op=so,sp=ha.exports,lp=$t.exports,cu=Nr,vu=to,du=Pr.exports,hu=du("iterator"),gu=du("toStringTag"),pu=vu.Array,mu={CSSRuleList:!0,CSSStyleDeclaration:!1,CSSValueList:!1,ClientRectList:!1,DOMRectList:!1,DOMStringList:!1,DOMTokenList:!0,DataTransferItemList:!1,FileList:!1,HTMLAllCollection:!1,HTMLCollection:!1,HTMLFormElement:!1,HTMLSelectElement:!1,MediaList:!0,MimeTypeArray:!1,NamedNodeMap:!1,NodeList:!0,PaintRequestList:!1,Plugin:!1,PluginArray:!1,SVGLengthList:!1,SVGNumberList:!1,SVGPathSegList:!1,SVGPointList:!1,SVGStringList:!1,SVGTransformList:!1,SourceBufferList:!1,StyleSheetList:!0,TextTrackCueList:!1,TextTrackList:!1,TouchList:!1},_u=op(mu),ho=0;ho<_u.length;ho++){var xa=_u[ho],up=mu[xa],bu=lp[xa],sr=bu&&bu.prototype,ya;if(sr&&(sr[hu]||cu(sr,hu,pu),sr[gu]||cu(sr,gu,xa),vu[xa]=pu,up))for(ya in fu)sr[ya]||sp(sr,ya,fu[ya],!0)}function Sa(e,t){for(var r=Object.create(null),i=e.split(","),a=0;a!!r[n.toLowerCase()]:n=>!!r[n]}var fp="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly",cp=Sa(fp);function wu(e){return!!e||e===""}var vp=Sa("animation-iteration-count,border-image-outset,border-image-slice,border-image-width,box-flex,box-flex-group,box-ordinal-group,column-count,columns,flex,flex-grow,flex-positive,flex-shrink,flex-negative,flex-order,grid-row,grid-row-end,grid-row-span,grid-row-start,grid-column,grid-column-end,grid-column-span,grid-column-start,font-weight,line-clamp,line-height,opacity,order,orphans,tab-size,widows,z-index,zoom,fill-opacity,flood-opacity,stop-opacity,stroke-dasharray,stroke-dashoffset,stroke-miterlimit,stroke-opacity,stroke-width");function go(e){if(se(e)){for(var t={},r=0;r{if(r){var i=r.split(hp);i.length>1&&(t[i[0].trim()]=i[1].trim())}}),t}function gp(e){var t="";if(!e||Se(e))return t;for(var r in e){var i=e[r],a=r.startsWith("--")?r:Ke(r);(Se(i)||typeof i=="number"&&vp(a))&&(t+="".concat(a,":").concat(i,";"))}return t}function po(e){var t="";if(Se(e))t=e;else if(se(e))for(var r=0;r{},pp=()=>!1,mp=/^on[^a-z]/,Ea=e=>mp.test(e),mo=e=>e.startsWith("onUpdate:"),ve=Object.assign,yu=(e,t)=>{var r=e.indexOf(t);r>-1&&e.splice(r,1)},_p=Object.prototype.hasOwnProperty,re=(e,t)=>_p.call(e,t),se=Array.isArray,fi=e=>ci(e)==="[object Map]",bp=e=>ci(e)==="[object Set]",ne=e=>typeof e=="function",Se=e=>typeof e=="string",_o=e=>typeof e=="symbol",He=e=>e!==null&&typeof e=="object",Su=e=>He(e)&&ne(e.then)&&ne(e.catch),wp=Object.prototype.toString,ci=e=>wp.call(e),bo=e=>ci(e).slice(8,-1),mt=e=>ci(e)==="[object Object]",wo=e=>Se(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,Ta=Sa(",key,ref,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),Ca=e=>{var t=Object.create(null);return r=>{var i=t[r];return i||(t[r]=e(r))}},xp=/-(\w)/g,Ft=Ca(e=>e.replace(xp,(t,r)=>r?r.toUpperCase():"")),yp=/\B([A-Z])/g,Ke=Ca(e=>e.replace(yp,"-$1").toLowerCase()),Oa=Ca(e=>e.charAt(0).toUpperCase()+e.slice(1)),xo=Ca(e=>e?"on".concat(Oa(e)):""),vi=(e,t)=>!Object.is(e,t),yo=(e,t)=>{for(var r=0;r{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,value:r})},Sp=e=>{var t=parseFloat(e);return isNaN(t)?e:t},Eu,Ep=()=>Eu||(Eu=typeof globalThis!="undefined"?globalThis:typeof self!="undefined"?self:typeof window!="undefined"||typeof window!="undefined"?window:{}),di=` +`,Tu=44,Ia="#007aff",Tp=/^([a-z-]+:)?\/\//i,Cp=/^data:.*,.*/,Cu="wxs://",Ou="json://",Op="wxsModules",Ap="renderjsModules",Ip="onPageScroll",kp="onReachBottom",Mp="onWxsInvokeCallMethod",So=0;function Eo(e){var t=Date.now(),r=So?t-So:0;So=t;for(var i=arguments.length,a=new Array(i>1?i-1:0),n=1;nJSON.stringify(o)).join(" "))}function To(e){return ve({},e.dataset,e.__uniDataset)}function Co(e){return{passive:e}}function Oo(e){var{id:t,offsetTop:r,offsetLeft:i}=e;return{id:t,dataset:To(e),offsetTop:r,offsetLeft:i}}function Rp(e,t,r){var i=document.fonts;if(i){var a=new FontFace(e,t,r);return a.load().then(()=>{i.add&&i.add(a)})}return new Promise(n=>{var o=document.createElement("style"),s=[];if(r){var{style:l,weight:u,stretch:f,unicodeRange:v,variant:p,featureSettings:d}=r;l&&s.push("font-style:".concat(l)),u&&s.push("font-weight:".concat(u)),f&&s.push("font-stretch:".concat(f)),v&&s.push("unicode-range:".concat(v)),p&&s.push("font-variant:".concat(p)),d&&s.push("font-feature-settings:".concat(d))}o.innerText='@font-face{font-family:"'.concat(e,'";src:').concat(t,";").concat(s.join(";"),"}"),document.head.appendChild(o),n()})}function Lp(e,t){if(Se(e)){var r=document.querySelector(e);r&&(e=r.getBoundingClientRect().top+window.pageYOffset)}e<0&&(e=0);var i=document.documentElement,{clientHeight:a,scrollHeight:n}=i;if(e=Math.min(e,n-a),t===0){i.scrollTop=document.body.scrollTop=e;return}if(window.scrollY!==e){var o=s=>{if(s<=0){window.scrollTo(0,e);return}var l=e-window.scrollY;requestAnimationFrame(function(){window.scrollTo(0,window.scrollY+l/s*10),o(s-10)})};o(t)}}function Pp(){return typeof __channelId__=="string"&&__channelId__}function Np(e,t){switch(bo(t)){case"Function":return"function() { [native code] }";default:return t}}function Dp(e,t,r){if(Pp())return r.push(t.replace("at ","uni-app:///")),console[e].apply(console,r);var i=r.map(function(a){var n=ci(a).toLowerCase();if(n==="[object object]"||n==="[object array]")try{a="---BEGIN:JSON---"+JSON.stringify(a,Np)+"---END:JSON---"}catch(s){a=n}else if(a===null)a="---NULL---";else if(a===void 0)a="---UNDEFINED---";else{var o=bo(a).toUpperCase();o==="NUMBER"||o==="BOOLEAN"?a="---BEGIN:"+o+"---"+a+"---END:"+o+"---":a=String(a)}return a});return i.join("---COMMA---")+" "+t}function Bp(e,t){for(var r=arguments.length,i=new Array(r>2?r-2:0),a=2;a{var i=t[r];return i||(t[r]=e(r))}}function Qp(e){return Jp(e)}function e0(e){return e.indexOf("/")===0}function Ro(e){return e0(e)?e:"/"+e}function Lo(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,r;return function(){if(e){for(var i=arguments.length,a=new Array(i),n=0;ne.apply(this,arguments);r=setTimeout(a,t)};return i.cancel=function(){clearTimeout(r)},i}var r0=Array.isArray,i0=e=>e!==null&&typeof e=="object",a0=["{","}"];class n0{constructor(){this._caches=Object.create(null)}interpolate(t,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:a0;if(!r)return[t];var a=this._caches[t];return a||(a=l0(t,i),this._caches[t]=a),u0(a,r)}}var o0=/^(?:\d)+/,s0=/^(?:\w)+/;function l0(e,t){for(var[r,i]=t,a=[],n=0,o="";nf0.call(e,t),c0=new n0;function v0(e,t){return!!t.find(r=>e.indexOf(r)!==-1)}function d0(e,t){return t.find(r=>e.indexOf(r)===0)}function Nu(e,t){if(!!e){if(e=e.trim().replace(/_/g,"-"),t&&t[e])return e;if(e=e.toLowerCase(),e==="chinese")return hi;if(e.indexOf("zh")===0)return e.indexOf("-hans")>-1?hi:e.indexOf("-hant")>-1||v0(e,["-tw","-hk","-mo","-cht"])?Ma:hi;var r=d0(e,[zt,Po,No]);if(r)return r}}class h0{constructor(t){var{locale:r,fallbackLocale:i,messages:a,watcher:n,formater:o}=t;this.locale=zt,this.fallbackLocale=zt,this.message={},this.messages={},this.watchers=[],i&&(this.fallbackLocale=i),this.formater=o||c0,this.messages=a||{},this.setLocale(r||zt),n&&this.watchLocale(n)}setLocale(t){var r=this.locale;this.locale=Nu(t,this.messages)||this.fallbackLocale,this.messages[this.locale]||(this.messages[this.locale]={}),this.message=this.messages[this.locale],r!==this.locale&&this.watchers.forEach(i=>{i(this.locale,r)})}getLocale(){return this.locale}watchLocale(t){var r=this.watchers.push(t)-1;return()=>{this.watchers.splice(r,1)}}add(t,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,a=this.messages[t];a?i?Object.assign(a,r):Object.keys(r).forEach(n=>{Pu(a,n)||(a[n]=r[n])}):this.messages[t]=r}f(t,r,i){return this.formater.interpolate(t,r,i).join("")}t(t,r,i){var a=this.message;return typeof r=="string"?(r=Nu(r,this.messages),r&&(a=this.messages[r])):i=r,Pu(a,t)?this.formater.interpolate(a[t],i).join(""):(console.warn("Cannot translate the value of keypath ".concat(t,". Use the value of keypath as default.")),t)}}function g0(e,t){e.$watchLocale?e.$watchLocale(r=>{t.setLocale(r)}):e.$watch(()=>e.$locale,r=>{t.setLocale(r)})}function p0(){return typeof uni!="undefined"&&uni.getLocale?uni.getLocale():typeof window!="undefined"&&window.getLocale?window.getLocale():zt}function m0(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0;typeof e!="string"&&([e,t]=[t,e]),typeof e!="string"&&(e=p0()),typeof r!="string"&&(r=typeof __uniConfig!="undefined"&&__uniConfig.fallbackLocale||zt);var a=new h0({locale:e,fallbackLocale:r,messages:t,watcher:i}),n=(o,s)=>{if(typeof getApp!="function")n=function(u,f){return a.t(u,f)};else{var l=!1;n=function(u,f){var v=getApp().$vm;return v&&(v.$locale,l||(l=!0,g0(v,a))),a.t(u,f)}}return n(o,s)};return{i18n:a,f(o,s,l){return a.f(o,s,l)},t(o,s){return n(o,s)},add(o,s){var l=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return a.add(o,s,l)},watch(o){return a.watchLocale(o)},getLocale(){return a.getLocale()},setLocale(o){return a.setLocale(o)}}}var Do;function Ge(){if(!Do){var e;typeof getApp=="function"?e=weex.requireModule("plus").getLanguage():e=plus.webview.currentWebview().getStyle().locale,Do=m0(e)}return Do}function _t(e,t,r){return t.reduce((i,a,n)=>(i[e+a]=r[n],i),{})}var _0=Lo(()=>{var e="uni.picker.",t=["done","cancel"];Ge().add(zt,_t(e,t,["Done","Cancel"]),!1),Ge().add(No,_t(e,t,["OK","Cancelar"]),!1),Ge().add(Po,_t(e,t,["OK","Annuler"]),!1),Ge().add(hi,_t(e,t,["\u5B8C\u6210","\u53D6\u6D88"]),!1),Ge().add(Ma,_t(e,t,["\u5B8C\u6210","\u53D6\u6D88"]),!1)}),b0=Lo(()=>{var e="uni.button.",t=["feedback.title","feedback.send"];Ge().add(zt,_t(e,t,["feedback","send"]),!1),Ge().add(No,_t(e,t,["realimentaci\xF3n","enviar"]),!1),Ge().add(Po,_t(e,t,["retour d'information","envoyer"]),!1),Ge().add(hi,_t(e,t,["\u95EE\u9898\u53CD\u9988","\u53D1\u9001"]),!1),Ge().add(Ma,_t(e,t,["\u554F\u984C\u53CD\u994B","\u767C\u9001"]),!1)}),Du=function(){};Du.prototype={on:function(e,t,r){var i=this.e||(this.e={});return(i[e]||(i[e]=[])).push({fn:t,ctx:r}),this},once:function(e,t,r){var i=this;function a(){i.off(e,a),t.apply(r,arguments)}return a._=t,this.on(e,a,r)},emit:function(e){var t=[].slice.call(arguments,1),r=((this.e||(this.e={}))[e]||[]).slice(),i=0,a=r.length;for(i;i1?i-1:0),n=1;n2&&arguments[2]!==void 0?arguments[2]:!1;t[a?"once":"on"]("".concat(e,".").concat(r),i)},unsubscribe(r,i){t.off("".concat(e,".").concat(r),i)},subscribeHandler(r,i,a){t.emit("".concat(e,".").concat(r),i,a)}}}var Bu="invokeViewApi",$u="invokeServiceApi",x0=1,y0=(e,t,r)=>{var{subscribe:i,publishHandler:a}=UniViewJSBridge,n=r?x0++:0;r&&i($u+"."+n,r,!0),a($u,{id:n,name:e,args:t})},Ra=Object.create(null);function La(e,t){return e+"."+t}function S0(e,t){UniViewJSBridge.subscribe(La(e,Bu),t?t(Fu):Fu)}function bt(e,t,r){t=La(e,t),Ra[t]||(Ra[t]=r)}function E0(e,t){t=La(e,t),delete Ra[t]}function Fu(e,t){var{id:r,name:i,args:a}=e;i=La(t,i);var n=s=>{r&&UniViewJSBridge.publishHandler(Bu+"."+r,s)},o=Ra[i];o?o(a,n):n({})}var T0=ve(w0("service"),{invokeServiceMethod:y0}),C0=350,zu=10,Pa=Co(!0),gi;function pi(){gi&&(clearTimeout(gi),gi=null)}var Uu=0,Hu=0;function O0(e){if(pi(),e.touches.length===1){var{pageX:t,pageY:r}=e.touches[0];Uu=t,Hu=r,gi=setTimeout(function(){var i=new CustomEvent("longpress",{bubbles:!0,cancelable:!0,target:e.target,currentTarget:e.currentTarget});i.touches=e.touches,i.changedTouches=e.changedTouches,e.target.dispatchEvent(i)},C0)}}function A0(e){if(!!gi){if(e.touches.length!==1)return pi();var{pageX:t,pageY:r}=e.touches[0];if(Math.abs(t-Uu)>zu||Math.abs(r-Hu)>zu)return pi()}}function I0(){window.addEventListener("touchstart",O0,Pa),window.addEventListener("touchmove",A0,Pa),window.addEventListener("touchend",pi,Pa),window.addEventListener("touchcancel",pi,Pa)}function Wu(e,t){var r=Number(e);return isNaN(r)?t:r}function k0(){var e=/^Apple/.test(navigator.vendor)&&typeof window.orientation=="number",t=e&&Math.abs(window.orientation)===90,r=e?Math[t?"max":"min"](screen.width,screen.height):screen.width,i=Math.min(window.innerWidth,document.documentElement.clientWidth,r)||r;return i}function M0(){function e(){var t=__uniConfig.globalStyle||{},r=Wu(t.rpxCalcMaxDeviceWidth,960),i=Wu(t.rpxCalcBaseDeviceWidth,375),a=k0();a=a<=r?a:i,document.documentElement.style.fontSize=a/23.4375+"px"}e(),document.addEventListener("DOMContentLoaded",e),window.addEventListener("load",e),window.addEventListener("resize",e)}function R0(){M0(),I0()}var L0=ca,P0=function(e,t){return!!e&&L0(function(){t?e.call(null,function(){},1):e.call(null)})},Bo=no,N0=Yl,Vu=iu,ju=ca,$o=[].sort,Yu=[1,2,3];Bo(Bo.P+Bo.F*(ju(function(){Yu.sort(void 0)})||!ju(function(){Yu.sort(null)})||!P0($o)),"Array",{sort:function(t){return t===void 0?$o.call(Vu(this)):$o.call(Vu(this),N0(t))}});var lr,Na=[];class D0{constructor(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.active=!0,this.effects=[],this.cleanups=[],!t&&lr&&(this.parent=lr,this.index=(lr.scopes||(lr.scopes=[])).push(this)-1)}run(t){if(this.active)try{return this.on(),t()}finally{this.off()}}on(){this.active&&(Na.push(this),lr=this)}off(){this.active&&(Na.pop(),lr=Na[Na.length-1])}stop(t){if(this.active){if(this.effects.forEach(i=>i.stop()),this.cleanups.forEach(i=>i()),this.scopes&&this.scopes.forEach(i=>i.stop(!0)),this.parent&&!t){var r=this.parent.scopes.pop();r&&r!==this&&(this.parent.scopes[this.index]=r,r.index=this.index)}this.active=!1}}}function B0(e,t){t=t||lr,t&&t.active&&t.effects.push(e)}var Fo=e=>{var t=new Set(e);return t.w=0,t.n=0,t},qu=e=>(e.w&Ut)>0,Xu=e=>(e.n&Ut)>0,$0=e=>{var{deps:t}=e;if(t.length)for(var r=0;r{var{deps:t}=e;if(t.length){for(var r=0,i=0;i1&&arguments[1]!==void 0?arguments[1]:null,i=arguments.length>2?arguments[2]:void 0;this.fn=t,this.scheduler=r,this.active=!0,this.deps=[],B0(this,i)}run(){if(!this.active)return this.fn();if(!_i.includes(this))try{return _i.push(ur=this),z0(),Ut=1<<++mi,mi<=Uo?$0(this):Zu(this),this.fn()}finally{mi<=Uo&&F0(this),Ut=1<<--mi,cr(),_i.pop();var t=_i.length;ur=t>0?_i[t-1]:void 0}}stop(){this.active&&(Zu(this),this.onStop&&this.onStop(),this.active=!1)}}function Zu(e){var{deps:t}=e;if(t.length){for(var r=0;r{(v==="length"||v>=i)&&s.push(f)});else switch(r!==void 0&&s.push(o.get(r)),t){case"add":se(e)?wo(r)&&s.push(o.get("length")):(s.push(o.get(fr)),fi(e)&&s.push(o.get(Ho)));break;case"delete":se(e)||(s.push(o.get(fr)),fi(e)&&s.push(o.get(Ho)));break;case"set":fi(e)&&s.push(o.get(fr));break}if(s.length===1)s[0]&&jo(s[0]);else{var l=[];for(var u of s)u&&l.push(...u);jo(Fo(l))}}}function jo(e,t){for(var r of se(e)?e:[...e])(r!==ur||r.allowRecurse)&&(r.scheduler?r.scheduler():r.run())}var U0=Sa("__proto__,__v_isRef,__isVue"),Ju=new Set(Object.getOwnPropertyNames(Symbol).map(e=>Symbol[e]).filter(_o)),H0=Yo(),W0=Yo(!1,!0),V0=Yo(!0),Qu=j0();function j0(){var e={};return["includes","indexOf","lastIndexOf"].forEach(t=>{e[t]=function(){for(var r=me(this),i=0,a=this.length;i{e[t]=function(){Fr();for(var r=arguments.length,i=new Array(r),a=0;a0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function(i,a,n){if(a==="__v_isReactive")return!e;if(a==="__v_isReadonly")return e;if(a==="__v_raw"&&n===(e?t?sm:uf:t?lf:sf).get(i))return i;var o=se(i);if(!e&&o&&re(Qu,a))return Reflect.get(Qu,a,n);var s=Reflect.get(i,a,n);if((_o(a)?Ju.has(a):U0(a))||(e||Je(i,"get",a),t))return s;if(qe(s)){var l=!o||!wo(a);return l?s.value:s}return He(s)?e?ff(s):Ae(s):s}}var Y0=ef(),q0=ef(!0);function ef(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return function(r,i,a,n){var o=r[i];if(!e&&(a=me(a),o=me(o),!se(r)&&qe(o)&&!qe(a)))return o.value=a,!0;var s=se(r)&&wo(i)?Number(i)e,Da=e=>Reflect.getPrototypeOf(e);function Ba(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;e=e.__v_raw;var a=me(e),n=me(t);t!==n&&!r&&Je(a,"get",t),!r&&Je(a,"get",n);var{has:o}=Da(a),s=i?qo:r?Ko:bi;if(o.call(a,t))return s(e.get(t));if(o.call(a,n))return s(e.get(n));e!==a&&e.get(t)}function $a(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,r=this.__v_raw,i=me(r),a=me(e);return e!==a&&!t&&Je(i,"has",e),!t&&Je(i,"has",a),e===a?r.has(e):r.has(e)||r.has(a)}function Fa(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return e=e.__v_raw,!t&&Je(me(e),"iterate",fr),Reflect.get(e,"size",e)}function rf(e){e=me(e);var t=me(this),r=Da(t),i=r.has.call(t,e);return i||(t.add(e),Mt(t,"add",e,e)),this}function af(e,t){t=me(t);var r=me(this),{has:i,get:a}=Da(r),n=i.call(r,e);n||(e=me(e),n=i.call(r,e));var o=a.call(r,e);return r.set(e,t),n?vi(t,o)&&Mt(r,"set",e,t):Mt(r,"add",e,t),this}function nf(e){var t=me(this),{has:r,get:i}=Da(t),a=r.call(t,e);a||(e=me(e),a=r.call(t,e)),i&&i.call(t,e);var n=t.delete(e);return a&&Mt(t,"delete",e,void 0),n}function of(){var e=me(this),t=e.size!==0,r=e.clear();return t&&Mt(e,"clear",void 0,void 0),r}function za(e,t){return function(i,a){var n=this,o=n.__v_raw,s=me(o),l=t?qo:e?Ko:bi;return!e&&Je(s,"iterate",fr),o.forEach((u,f)=>i.call(a,l(u),l(f),n))}}function Ua(e,t,r){return function(){var i=this.__v_raw,a=me(i),n=fi(a),o=e==="entries"||e===Symbol.iterator&&n,s=e==="keys"&&n,l=i[e](...arguments),u=r?qo:t?Ko:bi;return!t&&Je(a,"iterate",s?Ho:fr),{next(){var{value:f,done:v}=l.next();return v?{value:f,done:v}:{value:o?[u(f[0]),u(f[1])]:u(f),done:v}},[Symbol.iterator](){return this}}}}function Ht(e){return function(){return e==="delete"?!1:this}}function Q0(){var e={get(n){return Ba(this,n)},get size(){return Fa(this)},has:$a,add:rf,set:af,delete:nf,clear:of,forEach:za(!1,!1)},t={get(n){return Ba(this,n,!1,!0)},get size(){return Fa(this)},has:$a,add:rf,set:af,delete:nf,clear:of,forEach:za(!1,!0)},r={get(n){return Ba(this,n,!0)},get size(){return Fa(this,!0)},has(n){return $a.call(this,n,!0)},add:Ht("add"),set:Ht("set"),delete:Ht("delete"),clear:Ht("clear"),forEach:za(!0,!1)},i={get(n){return Ba(this,n,!0,!0)},get size(){return Fa(this,!0)},has(n){return $a.call(this,n,!0)},add:Ht("add"),set:Ht("set"),delete:Ht("delete"),clear:Ht("clear"),forEach:za(!0,!0)},a=["keys","values","entries",Symbol.iterator];return a.forEach(n=>{e[n]=Ua(n,!1,!1),r[n]=Ua(n,!0,!1),t[n]=Ua(n,!1,!0),i[n]=Ua(n,!0,!0)}),[e,r,t,i]}var[em,tm,rm,im]=Q0();function Xo(e,t){var r=t?e?im:rm:e?tm:em;return(i,a,n)=>a==="__v_isReactive"?!e:a==="__v_isReadonly"?e:a==="__v_raw"?i:Reflect.get(re(r,a)&&a in i?r:i,a,n)}var am={get:Xo(!1,!1)},nm={get:Xo(!1,!0)},om={get:Xo(!0,!1)},sf=new WeakMap,lf=new WeakMap,uf=new WeakMap,sm=new WeakMap;function lm(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function um(e){return e.__v_skip||!Object.isExtensible(e)?0:lm(bo(e))}function Ae(e){return e&&e.__v_isReadonly?e:Zo(e,!1,tf,am,sf)}function fm(e){return Zo(e,!1,J0,nm,lf)}function ff(e){return Zo(e,!0,G0,om,uf)}function Zo(e,t,r,i,a){if(!He(e)||e.__v_raw&&!(t&&e.__v_isReactive))return e;var n=a.get(e);if(n)return n;var o=um(e);if(o===0)return e;var s=new Proxy(e,o===2?i:r);return a.set(e,s),s}function zr(e){return cf(e)?zr(e.__v_raw):!!(e&&e.__v_isReactive)}function cf(e){return!!(e&&e.__v_isReadonly)}function vf(e){return zr(e)||cf(e)}function me(e){var t=e&&e.__v_raw;return t?me(t):e}function Ha(e){return Aa(e,"__v_skip",!0),e}var bi=e=>He(e)?Ae(e):e,Ko=e=>He(e)?ff(e):e;function df(e){Ku()&&(e=me(e),e.dep||(e.dep=Fo()),Gu(e.dep))}function hf(e,t){e=me(e),e.dep&&jo(e.dep)}function qe(e){return Boolean(e&&e.__v_isRef===!0)}function U(e){return gf(e,!1)}function Go(e){return gf(e,!0)}function gf(e,t){return qe(e)?e:new cm(e,t)}class cm{constructor(t,r){this._shallow=r,this.dep=void 0,this.__v_isRef=!0,this._rawValue=r?t:me(t),this._value=r?t:bi(t)}get value(){return df(this),this._value}set value(t){t=this._shallow?t:me(t),vi(t,this._rawValue)&&(this._rawValue=t,this._value=this._shallow?t:bi(t),hf(this))}}function vm(e){return qe(e)?e.value:e}var dm={get:(e,t,r)=>vm(Reflect.get(e,t,r)),set:(e,t,r,i)=>{var a=e[t];return qe(a)&&!qe(r)?(a.value=r,!0):Reflect.set(e,t,r,i)}};function pf(e){return zr(e)?e:new Proxy(e,dm)}class hm{constructor(t,r,i){this._setter=r,this.dep=void 0,this._dirty=!0,this.__v_isRef=!0,this.effect=new Wo(t,()=>{this._dirty||(this._dirty=!0,hf(this))}),this.__v_isReadonly=i}get value(){var t=me(this);return df(t),t._dirty&&(t._dirty=!1,t._value=t.effect.run()),t._value}set value(t){this._setter(t)}}function Q(e,t){var r,i,a=ne(e);a?(r=e,i=pt):(r=e.get,i=e.set);var n=new hm(r,i,a||!i);return n}function gm(e,t){for(var r=e.vnode.props||xe,i=arguments.length,a=new Array(i>2?i-2:0),n=2;nb.trim()):f&&(o=a.map(Sp))}var p,d=r[p=xo(t)]||r[p=xo(Ft(t))];!d&&s&&(d=r[p=xo(Ke(t))]),d&&ct(d,e,6,o);var _=r[p+"Once"];if(_){if(!e.emitted)e.emitted={};else if(e.emitted[p])return;e.emitted[p]=!0,ct(_,e,6,o)}}function mf(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=t.emitsCache,a=i.get(e);if(a!==void 0)return a;var n=e.emits,o={},s=!1;if(!ne(e)){var l=u=>{var f=mf(u,t,!0);f&&(s=!0,ve(o,f))};!r&&t.mixins.length&&t.mixins.forEach(l),e.extends&&l(e.extends),e.mixins&&e.mixins.forEach(l)}return!n&&!s?(i.set(e,null),null):(se(n)?n.forEach(u=>o[u]=null):ve(o,n),i.set(e,o),o)}function Jo(e,t){return!e||!Ea(t)?!1:(t=t.slice(2).replace(/Once$/,""),re(e,t[0].toLowerCase()+t.slice(1))||re(e,Ke(t))||re(e,t))}var ft=null,_f=null;function Wa(e){var t=ft;return ft=e,_f=e&&e.type.__scopeId||null,t}function pm(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ft;if(!t||e._n)return e;var r=function(){r._d&&zf(-1);var i=Wa(t),a=e(...arguments);return Wa(i),r._d&&zf(1),a};return r._n=!0,r._c=!0,r._d=!0,r}function $T(){}function Qo(e){var{type:t,vnode:r,proxy:i,withProxy:a,props:n,propsOptions:[o],slots:s,attrs:l,emit:u,render:f,renderCache:v,data:p,setupState:d,ctx:_,inheritAttrs:b}=e,x,m,g=Wa(e);try{if(r.shapeFlag&4){var c=a||i;x=yt(f.call(c,c,v,n,d,p,_)),m=l}else{var h=t;x=yt(h.length>1?h(n,{attrs:l,slots:s,emit:u}):h(n,null)),m=t.props?l:mm(l)}}catch(E){Ga(E,e,1),x=I(xi)}var w=x;if(m&&b!==!1){var y=Object.keys(m),{shapeFlag:C}=w;y.length&&C&(1|6)&&(o&&y.some(mo)&&(m=_m(m,o)),w=Si(w,m))}return r.dirs&&(w.dirs=w.dirs?w.dirs.concat(r.dirs):r.dirs),r.transition&&(w.transition=r.transition),x=w,Wa(g),x}var mm=e=>{var t;for(var r in e)(r==="class"||r==="style"||Ea(r))&&((t||(t={}))[r]=e[r]);return t},_m=(e,t)=>{var r={};for(var i in e)(!mo(i)||!(i.slice(9)in t))&&(r[i]=e[i]);return r};function bm(e,t,r){var{props:i,children:a,component:n}=e,{props:o,children:s,patchFlag:l}=t,u=n.emitsOptions;if(t.dirs||t.transition)return!0;if(r&&l>=0){if(l&1024)return!0;if(l&16)return i?bf(i,o,u):!!o;if(l&8)for(var f=t.dynamicProps,v=0;ve.__isSuspense;function ym(e,t){t&&t.pendingBranch?se(e)?t.effects.push(...e):t.effects.push(e):v_(e)}function Fe(e,t){if(ze){var r=ze.provides,i=ze.parent&&ze.parent.provides;i===r&&(r=ze.provides=Object.create(i)),r[e]=t}}function _e(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=ze||ft;if(i){var a=i.parent==null?i.vnode.appContext&&i.vnode.appContext.provides:i.parent.provides;if(a&&e in a)return a[e];if(arguments.length>1)return r&&ne(t)?t.call(i.proxy):t}}function Sm(e){return ne(e)?{setup:e,name:e.name}:e}var es=e=>!!e.type.__asyncLoader,wf=e=>e.type.__isKeepAlive;function ts(e,t){xf(e,"a",t)}function Em(e,t){xf(e,"da",t)}function xf(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ze,i=e.__wdc||(e.__wdc=()=>{for(var n=r;n;){if(n.isDeactivated)return;n=n.parent}e()});if(Va(t,i,r),r)for(var a=r.parent;a&&a.parent;)wf(a.parent.vnode)&&Tm(i,t,r,a),a=a.parent}function Tm(e,t,r,i){var a=Va(t,e,i,!0);Wt(()=>{yu(i[t],a)},r)}function Va(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ze,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(r){var a=r[e]||(r[e]=[]),n=t.__weh||(t.__weh=function(){if(!r.isUnmounted){Fr(),Ur(r);for(var o=arguments.length,s=new Array(o),l=0;lfunction(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ze;return(!Ka||e==="sp")&&Va(e,t,r)},yf=Rt("bm"),Re=Rt("m"),Cm=Rt("bu"),Om=Rt("u"),Ce=Rt("bum"),Wt=Rt("um"),Am=Rt("sp"),Im=Rt("rtg"),km=Rt("rtc");function Mm(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ze;Va("ec",e,t)}var rs=!0;function Rm(e){var t=Tf(e),r=e.proxy,i=e.ctx;rs=!1,t.beforeCreate&&Sf(t.beforeCreate,e,"bc");var{data:a,computed:n,methods:o,watch:s,provide:l,inject:u,created:f,beforeMount:v,mounted:p,beforeUpdate:d,updated:_,activated:b,deactivated:x,beforeDestroy:m,beforeUnmount:g,destroyed:c,unmounted:h,render:w,renderTracked:y,renderTriggered:C,errorCaptured:E,serverPrefetch:O,expose:N,inheritAttrs:R,components:Y,directives:ue,filters:M}=t,B=null;if(u&&Lm(u,i,B,e.appContext.config.unwrapInjectedRef),o)for(var J in o){var te=o[J];ne(te)&&(i[J]=te.bind(r))}if(a&&function(){var ie=a.call(r,r);He(ie)&&(e.data=Ae(ie))}(),rs=!0,n){var W=function(ie){var le=n[ie],Ie=ne(le)?le.bind(r,r):ne(le.get)?le.get.bind(r,r):pt,ke=!ne(le)&&ne(le.set)?le.set.bind(r):pt,nt=Q({get:Ie,set:ke});Object.defineProperty(i,ie,{enumerable:!0,configurable:!0,get:()=>nt.value,set:nr=>nt.value=nr})};for(var ee in n)W(ee)}if(s)for(var ae in s)Ef(s[ae],i,r,ae);if(l){var ye=ne(l)?l.call(r):l;Reflect.ownKeys(ye).forEach(ie=>{Fe(ie,ye[ie])})}f&&Sf(f,e,"c");function oe(ie,le){se(le)?le.forEach(Ie=>ie(Ie.bind(r))):le&&ie(le.bind(r))}if(oe(yf,v),oe(Re,p),oe(Cm,d),oe(Om,_),oe(ts,b),oe(Em,x),oe(Mm,E),oe(km,y),oe(Im,C),oe(Ce,g),oe(Wt,h),oe(Am,O),se(N))if(N.length){var K=e.exposed||(e.exposed={});N.forEach(ie=>{Object.defineProperty(K,ie,{get:()=>r[ie],set:le=>r[ie]=le})})}else e.exposed||(e.exposed={});w&&e.render===pt&&(e.render=w),R!=null&&(e.inheritAttrs=R),Y&&(e.components=Y),ue&&(e.directives=ue)}function Lm(e,t){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;se(e)&&(e=is(e));var i=function(n){var o=e[n],s=void 0;He(o)?"default"in o?s=_e(o.from||n,o.default,!0):s=_e(o.from||n):s=_e(o),qe(s)&&r?Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get:()=>s.value,set:l=>s.value=l}):t[n]=s};for(var a in e)i(a)}function Sf(e,t,r){ct(se(e)?e.map(i=>i.bind(t.proxy)):e.bind(t.proxy),t,r)}function Ef(e,t,r,i){var a=i.includes(".")?Qf(r,i):()=>r[i];if(Se(e)){var n=t[e];ne(n)&&H(a,n)}else if(ne(e))H(a,e.bind(r));else if(He(e))if(se(e))e.forEach(s=>Ef(s,t,r,i));else{var o=ne(e.handler)?e.handler.bind(r):t[e.handler];ne(o)&&H(a,o,e)}}function Tf(e){var t=e.type,{mixins:r,extends:i}=t,{mixins:a,optionsCache:n,config:{optionMergeStrategies:o}}=e.appContext,s=n.get(t),l;return s?l=s:!a.length&&!r&&!i?l=t:(l={},a.length&&a.forEach(u=>ja(l,u,o,!0)),ja(l,t,o)),n.set(t,l),l}function ja(e,t,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,{mixins:a,extends:n}=t;n&&ja(e,n,r,!0),a&&a.forEach(l=>ja(e,l,r,!0));for(var o in t)if(!(i&&o==="expose")){var s=Pm[o]||r&&r[o];e[o]=s?s(e[o],t[o]):t[o]}return e}var Pm={data:Cf,props:vr,emits:vr,methods:vr,computed:vr,beforeCreate:Ve,created:Ve,beforeMount:Ve,mounted:Ve,beforeUpdate:Ve,updated:Ve,beforeDestroy:Ve,beforeUnmount:Ve,destroyed:Ve,unmounted:Ve,activated:Ve,deactivated:Ve,errorCaptured:Ve,serverPrefetch:Ve,components:vr,directives:vr,watch:Dm,provide:Cf,inject:Nm};function Cf(e,t){return t?e?function(){return ve(ne(e)?e.call(this,this):e,ne(t)?t.call(this,this):t)}:t:e}function Nm(e,t){return vr(is(e),is(t))}function is(e){if(se(e)){for(var t={},r=0;r3&&arguments[3]!==void 0?arguments[3]:!1,a={},n={};Aa(n,qa,1),e.propsDefaults=Object.create(null),Of(e,t,a,n);for(var o in e.propsOptions[0])o in a||(a[o]=void 0);r?e.props=i?a:fm(a):e.type.props?e.props=a:e.props=n,e.attrs=n}function $m(e,t,r,i){var{props:a,attrs:n,vnode:{patchFlag:o}}=e,s=me(a),[l]=e.propsOptions,u=!1;if((i||o>0)&&!(o&16)){if(o&8)for(var f=e.vnode.dynamicProps,v=0;v2&&arguments[2]!==void 0?arguments[2]:!1,i=t.propsCache,a=i.get(e);if(a)return a;var n=e.props,o={},s=[],l=!1;if(!ne(e)){var u=c=>{l=!0;var[h,w]=Af(c,t,!0);ve(o,h),w&&s.push(...w)};!r&&t.mixins.length&&t.mixins.forEach(u),e.extends&&u(e.extends),e.mixins&&e.mixins.forEach(u)}if(!n&&!l)return i.set(e,ui),ui;if(se(n))for(var f=0;f-1,b[1]=m<0||x-1||re(b,"default"))&&s.push(d)}}}var g=[o,s];return i.set(e,g),g}function If(e){return e[0]!=="$"}function kf(e){var t=e&&e.toString().match(/^\s*function (\w+)/);return t?t[1]:e===null?"null":""}function Mf(e,t){return kf(e)===kf(t)}function Rf(e,t){return se(t)?t.findIndex(r=>Mf(r,e)):ne(t)&&Mf(t,e)?0:-1}var Lf=e=>e[0]==="_"||e==="$stable",ns=e=>se(e)?e.map(yt):[yt(e)],Fm=(e,t,r)=>{var i=pm(function(){return ns(t(...arguments))},r);return i._c=!1,i},Pf=(e,t,r)=>{var i=e._ctx;for(var a in e)if(!Lf(a)){var n=e[a];ne(n)?t[a]=Fm(a,n,i):n!=null&&function(){var o=ns(n);t[a]=()=>o}()}},Nf=(e,t)=>{var r=ns(t);e.slots.default=()=>r},zm=(e,t)=>{if(e.vnode.shapeFlag&32){var r=t._;r?(e.slots=me(t),Aa(t,"_",r)):Pf(t,e.slots={})}else e.slots={},t&&Nf(e,t);Aa(e.slots,qa,1)},Um=(e,t,r)=>{var{vnode:i,slots:a}=e,n=!0,o=xe;if(i.shapeFlag&32){var s=t._;s?r&&s===1?n=!1:(ve(a,t),!r&&s===1&&delete a._):(n=!t.$stable,Pf(t,a)),o=t}else t&&(Nf(e,t),o={default:1});if(n)for(var l in a)!Lf(l)&&!(l in o)&&delete a[l]};function wi(e,t){var r=ft;if(r===null)return e;for(var i=r.proxy,a=e.dirs||(e.dirs=[]),n=0;n1&&arguments[1]!==void 0?arguments[1]:null;a!=null&&!He(a)&&(a=null);var n=Df(),o=new Set,s=!1,l=n.app={_uid:Hm++,_component:i,_props:a,_container:null,_context:n,_instance:null,version:p_,get config(){return n.config},set config(u){},use(u){for(var f=arguments.length,v=new Array(f>1?f-1:0),p=1;p3&&arguments[3]!==void 0?arguments[3]:null,P=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null,z=arguments.length>5&&arguments[5]!==void 0?arguments[5]:null,V=arguments.length>6&&arguments[6]!==void 0?arguments[6]:!1,F=arguments.length>7&&arguments[7]!==void 0?arguments[7]:null,$=arguments.length>8&&arguments[8]!==void 0?arguments[8]:!!T.dynamicChildren;if(S!==T){S&&!yi(S,T)&&(L=nt(S),K(S,P,z,!0),S=null),T.patchFlag===-2&&($=!1,T.dynamicChildren=null);var{type:D,ref:G,shapeFlag:Z}=T;switch(D){case ss:m(S,T,k,L);break;case xi:g(S,T,k,L);break;case ls:S==null&&c(T,k,L,V);break;case xt:ue(S,T,k,L,P,z,V,F,$);break;default:Z&1?y(S,T,k,L,P,z,V,F,$):Z&6?M(S,T,k,L,P,z,V,F,$):(Z&64||Z&128)&&D.process(S,T,k,L,P,z,V,F,$,Ne)}G!=null&&P&&os(G,S&&S.ref,z,T||S,!T)}},m=(S,T,k,L)=>{if(S==null)i(T.el=s(T.children),k,L);else{var P=T.el=S.el;T.children!==S.children&&u(P,T.children)}},g=(S,T,k,L)=>{S==null?i(T.el=l(T.children||""),k,L):T.el=S.el},c=(S,T,k,L)=>{[S.el,S.anchor]=b(S.children,T,k,L)},h=(S,T,k)=>{for(var{el:L,anchor:P}=S,z;L&&L!==P;)z=p(L),i(L,T,k),L=z;i(P,T,k)},w=S=>{for(var{el:T,anchor:k}=S,L;T&&T!==k;)L=p(T),a(T),T=L;a(k)},y=(S,T,k,L,P,z,V,F,$)=>{V=V||T.type==="svg",S==null?C(T,k,L,P,z,V,F,$):N(S,T,P,z,V,F,$)},C=(S,T,k,L,P,z,V,F)=>{var $,D,{type:G,props:Z,shapeFlag:X,transition:ce,patchFlag:Be,dirs:Te}=S;if(S.el&&_!==void 0&&Be===-1)$=S.el=_(S.el);else{if($=S.el=o(S.type,z,Z&&Z.is,Z),X&8?f($,S.children):X&16&&O(S.children,$,null,L,P,z&&G!=="foreignObject",V,F),Te&&dr(S,null,L,"created"),Z){for(var A in Z)A!=="value"&&!Ta(A)&&n($,A,null,Z[A],z,S.children,L,P,ke);"value"in Z&&n($,"value",null,Z.value),(D=Z.onVnodeBeforeMount)&&wt(D,L,S)}E($,S,S.scopeId,V,L)}Object.defineProperty($,"__vueParentComponent",{value:L,enumerable:!1}),Te&&dr(S,null,L,"beforeMount");var j=(!P||P&&!P.pendingBranch)&&ce&&!ce.persisted;j&&ce.beforeEnter($),i($,T,k),((D=Z&&Z.onVnodeMounted)||j||Te)&&je(()=>{D&&wt(D,L,S),j&&ce.enter($),Te&&dr(S,null,L,"mounted")},P)},E=(S,T,k,L,P)=>{if(k&&d(S,k),L)for(var z=0;z8&&arguments[8]!==void 0?arguments[8]:0,D=$;D{var F=T.el=S.el,{patchFlag:$,dynamicChildren:D,dirs:G}=T;$|=S.patchFlag&16;var Z=S.props||xe,X=T.props||xe,ce;(ce=X.onVnodeBeforeUpdate)&&wt(ce,k,T,S),G&&dr(T,S,k,"beforeUpdate");var Be=P&&T.type!=="foreignObject";if(D?R(S.dynamicChildren,D,F,k,L,Be,z):V||ee(S,T,F,null,k,L,Be,z,!1),$>0){if($&16)Y(F,T,Z,X,k,L,P);else if($&2&&Z.class!==X.class&&n(F,"class",null,X.class,P),$&4&&n(F,"style",Z.style,X.style,P),$&8)for(var Te=T.dynamicProps,A=0;A{ce&&wt(ce,k,T,S),G&&dr(T,S,k,"updated")},L)},R=(S,T,k,L,P,z,V)=>{for(var F=0;F{if(k!==L){for(var F in L)if(!Ta(F)){var $=L[F],D=k[F];$!==D&&F!=="value"&&n(S,F,D,$,V,T.children,P,z,ke)}if(k!==xe)for(var G in k)!Ta(G)&&!(G in L)&&n(S,G,k[G],null,V,T.children,P,z,ke);"value"in L&&n(S,"value",k.value,L.value)}},ue=(S,T,k,L,P,z,V,F,$)=>{var D=T.el=S?S.el:s(""),G=T.anchor=S?S.anchor:s(""),{patchFlag:Z,dynamicChildren:X,slotScopeIds:ce}=T;ce&&(F=F?F.concat(ce):ce),S==null?(i(D,k,L),i(G,k,L),O(T.children,k,G,P,z,V,F,$)):Z>0&&Z&64&&X&&S.dynamicChildren?(R(S.dynamicChildren,X,k,P,z,V,F),(T.key!=null||P&&T===P.subTree)&&Bf(S,T,!0)):ee(S,T,k,G,P,z,V,F,$)},M=(S,T,k,L,P,z,V,F,$)=>{T.slotScopeIds=F,S==null?T.shapeFlag&512?P.ctx.activate(T,k,L,V,$):B(T,k,L,P,z,V,$):J(S,T,$)},B=(S,T,k,L,P,z,V)=>{var F=S.component=r_(S,L,P);if(wf(S)&&(F.ctx.renderer=Ne),i_(F),F.asyncDep){if(P&&P.registerDep(F,te),!S.el){var $=F.subTree=I(xi);g(null,$,T,k)}return}te(F,S,T,k,P,z,V)},J=(S,T,k)=>{var L=T.component=S.component;if(bm(S,T,k))if(L.asyncDep&&!L.asyncResolved){W(L,T,k);return}else L.next=T,f_(L.update),L.update();else T.component=S.component,T.el=S.el,L.vnode=T},te=(S,T,k,L,P,z,V)=>{var F=()=>{if(S.isMounted){var{next:fe,bu:$e,u:Ze,parent:De,vnode:gt}=S,or=fe,kt;$.allowRecurse=!1,fe?(fe.el=gt.el,W(S,fe,V)):fe=gt,$e&&yo($e),(kt=fe.props&&fe.props.onVnodeBeforeUpdate)&&wt(kt,De,fe,gt),$.allowRecurse=!0;var Rr=Qo(S),Bt=S.subTree;S.subTree=Rr,x(Bt,Rr,v(Bt.el),nt(Bt),S,P,z),fe.el=Rr.el,or===null&&wm(S,Rr.el),Ze&&je(Ze,P),(kt=fe.props&&fe.props.onVnodeUpdated)&&je(()=>wt(kt,De,fe,gt),P)}else{var G,{el:Z,props:X}=T,{bm:ce,m:Be,parent:Te}=S,A=es(T);if($.allowRecurse=!1,ce&&yo(ce),!A&&(G=X&&X.onVnodeBeforeMount)&&wt(G,Te,T),$.allowRecurse=!0,Z&&oa){var j=()=>{S.subTree=Qo(S),oa(Z,S.subTree,S,P,null)};A?T.type.__asyncLoader().then(()=>!S.isUnmounted&&j()):j()}else{var q=S.subTree=Qo(S);x(null,q,k,L,S,P,z),T.el=q.el}if(Be&&je(Be,P),!A&&(G=X&&X.onVnodeMounted)){var he=T;je(()=>wt(G,Te,he),P)}T.shapeFlag&256&&S.a&&je(S.a,P),S.isMounted=!0,T=k=L=null}},$=new Wo(F,()=>qf(S.update),S.scope),D=S.update=$.run.bind($);D.id=S.uid,$.allowRecurse=D.allowRecurse=!0,D()},W=(S,T,k)=>{T.component=S;var L=S.vnode.props;S.vnode=T,S.next=null,$m(S,T.props,L,k),Um(S,T.children,k),Fr(),gs(void 0,S.update),cr()},ee=function(S,T,k,L,P,z,V,F){var $=arguments.length>8&&arguments[8]!==void 0?arguments[8]:!1,D=S&&S.children,G=S?S.shapeFlag:0,Z=T.children,{patchFlag:X,shapeFlag:ce}=T;if(X>0){if(X&128){ye(D,Z,k,L,P,z,V,F,$);return}else if(X&256){ae(D,Z,k,L,P,z,V,F,$);return}}ce&8?(G&16&&ke(D,P,z),Z!==D&&f(k,Z)):G&16?ce&16?ye(D,Z,k,L,P,z,V,F,$):ke(D,P,z,!0):(G&8&&f(k,""),ce&16&&O(Z,k,L,P,z,V,F,$))},ae=(S,T,k,L,P,z,V,F,$)=>{S=S||ui,T=T||ui;var D=S.length,G=T.length,Z=Math.min(D,G),X;for(X=0;XG?ke(S,P,z,!0,!1,Z):O(T,k,L,P,z,V,F,$,Z)},ye=(S,T,k,L,P,z,V,F,$)=>{for(var D=0,G=T.length,Z=S.length-1,X=G-1;D<=Z&&D<=X;){var ce=S[D],Be=T[D]=$?Vt(T[D]):yt(T[D]);if(yi(ce,Be))x(ce,Be,k,null,P,z,V,F,$);else break;D++}for(;D<=Z&&D<=X;){var Te=S[Z],A=T[X]=$?Vt(T[X]):yt(T[X]);if(yi(Te,A))x(Te,A,k,null,P,z,V,F,$);else break;Z--,X--}if(D>Z){if(D<=X)for(var j=X+1,q=jX)for(;D<=Z;)K(S[D],P,z,!0),D++;else{var he=D,fe=D,$e=new Map;for(D=fe;D<=X;D++){var Ze=T[D]=$?Vt(T[D]):yt(T[D]);Ze.key!=null&&$e.set(Ze.key,D)}var De,gt=0,or=X-fe+1,kt=!1,Rr=0,Bt=new Array(or);for(D=0;D=or){K(oi,P,z,!0);continue}var Lr=void 0;if(oi.key!=null)Lr=$e.get(oi.key);else for(De=fe;De<=X;De++)if(Bt[De-fe]===0&&yi(oi,T[De])){Lr=De;break}Lr===void 0?K(oi,P,z,!0):(Bt[Lr-fe]=D+1,Lr>=Rr?Rr=Lr:kt=!0,x(oi,T[Lr],k,null,P,z,V,F,$),gt++)}var Rh=kt?Ym(Bt):ui;for(De=Rh.length-1,D=or-1;D>=0;D--){var Pl=fe+D,Lh=T[Pl],Ph=Pl+14&&arguments[4]!==void 0?arguments[4]:null,{el:z,type:V,transition:F,children:$,shapeFlag:D}=S;if(D&6){oe(S.component.subTree,T,k,L);return}if(D&128){S.suspense.move(T,k,L);return}if(D&64){V.move(S,T,k,Ne);return}if(V===xt){i(z,T,k);for(var G=0;G<$.length;G++)oe($[G],T,k,L);i(S.anchor,T,k);return}if(V===ls){h(S,T,k);return}var Z=L!==2&&D&1&&F;if(Z)if(L===0)F.beforeEnter(z),i(z,T,k),je(()=>F.enter(z),P);else{var{leave:X,delayLeave:ce,afterLeave:Be}=F,Te=()=>i(z,T,k),A=()=>{X(z,()=>{Te(),Be&&Be()})};ce?ce(z,Te,A):A()}else i(z,T,k)},K=function(S,T,k){var L=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,P=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,{type:z,props:V,ref:F,children:$,dynamicChildren:D,shapeFlag:G,patchFlag:Z,dirs:X}=S;if(F!=null&&os(F,null,k,S,!0),G&256){T.ctx.deactivate(S);return}var ce=G&1&&X,Be=!es(S),Te;if(Be&&(Te=V&&V.onVnodeBeforeUnmount)&&wt(Te,T,S),G&6)Ie(S.component,k,L);else{if(G&128){S.suspense.unmount(k,L);return}ce&&dr(S,null,T,"beforeUnmount"),G&64?S.type.remove(S,T,k,P,Ne,L):D&&(z!==xt||Z>0&&Z&64)?ke(D,T,k,!1,!0):(z===xt&&Z&(128|256)||!P&&G&16)&&ke($,T,k),L&&ie(S)}(Be&&(Te=V&&V.onVnodeUnmounted)||ce)&&je(()=>{Te&&wt(Te,T,S),ce&&dr(S,null,T,"unmounted")},k)},ie=S=>{var{type:T,el:k,anchor:L,transition:P}=S;if(T===xt){le(k,L);return}if(T===ls){w(S);return}var z=()=>{a(k),P&&!P.persisted&&P.afterLeave&&P.afterLeave()};if(S.shapeFlag&1&&P&&!P.persisted){var{leave:V,delayLeave:F}=P,$=()=>V(k,z);F?F(S.el,z,$):$()}else z()},le=(S,T)=>{for(var k;S!==T;)k=p(S),a(S),S=k;a(T)},Ie=(S,T,k)=>{var{bum:L,scope:P,update:z,subTree:V,um:F}=S;L&&yo(L),P.stop(),z&&(z.active=!1,K(V,S,T,k)),F&&je(F,T),je(()=>{S.isUnmounted=!0},T),T&&T.pendingBranch&&!T.isUnmounted&&S.asyncDep&&!S.asyncResolved&&S.suspenseId===T.pendingId&&(T.deps--,T.deps===0&&T.resolve())},ke=function(S,T,k){for(var L=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,P=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,z=arguments.length>5&&arguments[5]!==void 0?arguments[5]:0,V=z;VS.shapeFlag&6?nt(S.component.subTree):S.shapeFlag&128?S.suspense.next():p(S.anchor||S.el),nr=(S,T,k)=>{if(S==null)T._vnode&&K(T._vnode,null,null,!0);else{var L=T.__vueParent;x(T._vnode||null,S,T,null,L,null,k)}T._vnode=S},Ne={p:x,um:K,m:oe,r:ie,mt:B,mc:O,pc:ee,pbc:R,n:nt,o:e},na,oa;return t&&([na,oa]=t(Ne)),{render:nr,hydrate:na,createApp:Wm(nr,na)}}function os(e,t,r,i){var a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;if(se(e)){e.forEach((_,b)=>os(_,t&&(se(t)?t[b]:t),r,i,a));return}if(!(es(i)&&!a)){var n=i.shapeFlag&4?cs(i.component)||i.component.proxy:i.el,o=a?null:n,{i:s,r:l}=e,u=t&&t.r,f=s.refs===xe?s.refs={}:s.refs,v=s.setupState;if(u!=null&&u!==l&&(Se(u)?(f[u]=null,re(v,u)&&(v[u]=null)):qe(u)&&(u.value=null)),Se(l)){var p=()=>{f[l]=o,re(v,l)&&(v[l]=o)};o?(p.id=-1,je(p,r)):p()}else if(qe(l)){var d=()=>{l.value=o};o?(d.id=-1,je(d,r)):d()}else ne(l)&&Yt(l,s,12,[o,f])}}function wt(e,t,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;ct(e,t,7,[r,i])}function Bf(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=e.children,a=t.children;if(se(i)&&se(a))for(var n=0;n>1,e[r[s]]0&&(t[i]=r[n-1]),r[n]=i)}}for(n=r.length,o=r[n-1];n-- >0;)r[n]=o,o=t[o];return r}var qm=e=>e.__isTeleport,Xm=Symbol(),xt=Symbol(void 0),ss=Symbol(void 0),xi=Symbol(void 0),ls=Symbol(void 0),$f=null,Ff=1;function zf(e){Ff+=e}function Ya(e){return e?e.__v_isVNode===!0:!1}function yi(e,t){return e.type===t.type&&e.key===t.key}var qa="__vInternal",Uf=e=>{var{key:t}=e;return t!=null?t:null},Xa=e=>{var{ref:t}=e;return t!=null?Se(t)||qe(t)||ne(t)?{i:ft,r:t}:t:null};function Zm(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null,n=arguments.length>5&&arguments[5]!==void 0?arguments[5]:e===xt?0:1,o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:!1,s=arguments.length>7&&arguments[7]!==void 0?arguments[7]:!1,l={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&Uf(t),ref:t&&Xa(t),scopeId:_f,slotScopeIds:null,children:r,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetAnchor:null,staticCount:0,shapeFlag:n,patchFlag:i,dynamicProps:a,dynamicChildren:null,appContext:null};return s?(us(l,r),n&128&&e.normalize(l)):r&&(l.shapeFlag|=Se(r)?8:16),Ff>0&&!o&&$f&&(l.patchFlag>0||n&6)&&l.patchFlag!==32&&$f.push(l),l}var I=Km;function Km(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null,n=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!1;if((!e||e===Xm)&&(e=xi),Ya(e)){var o=Si(e,t,!0);return r&&us(o,r),o}if(s_(e)&&(e=e.__vccOpts),t){t=Gm(t);var{class:s,style:l}=t;s&&!Se(s)&&(t.class=po(s)),He(l)&&(vf(l)&&!se(l)&&(l=ve({},l)),t.style=go(l))}var u=Se(e)?1:xm(e)?128:qm(e)?64:He(e)?4:ne(e)?2:0;return Zm(e,t,r,i,a,u,n,!0)}function Gm(e){return e?vf(e)||qa in e?ve({},e):e:null}function Si(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,{props:i,ref:a,patchFlag:n,children:o}=e,s=t?Qe(i||{},t):i,l={__v_isVNode:!0,__v_skip:!0,type:e.type,props:s,key:s&&Uf(s),ref:t&&t.ref?r&&a?se(a)?a.concat(Xa(t)):[a,Xa(t)]:Xa(t):a,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:o,target:e.target,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==xt?n===-1?16:n|16:n,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:e.transition,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&Si(e.ssContent),ssFallback:e.ssFallback&&Si(e.ssFallback),el:e.el,anchor:e.anchor};return l}function Jm(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:" ",t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return I(ss,null,e,t)}function yt(e){return e==null||typeof e=="boolean"?I(xi):se(e)?I(xt,null,e.slice()):typeof e=="object"?Vt(e):I(ss,null,String(e))}function Vt(e){return e.el===null||e.memo?e:Si(e)}function us(e,t){var r=0,{shapeFlag:i}=e;if(t==null)t=null;else if(se(t))r=16;else if(typeof t=="object")if(i&(1|64)){var a=t.default;a&&(a._c&&(a._d=!1),us(e,a()),a._c&&(a._d=!0));return}else{r=32;var n=t._;!n&&!(qa in t)?t._ctx=ft:n===3&&ft&&(ft.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else ne(t)?(t={default:t,_ctx:ft},r=32):(t=String(t),i&64?(r=16,t=[Jm(t)]):r=8);e.children=t,e.shapeFlag|=r}function Qe(){for(var e={},t=0;te?Hf(e)?cs(e)||e.proxy:fs(e.parent):null,Za=ve(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>fs(e.parent),$root:e=>fs(e.root),$emit:e=>e.emit,$options:e=>Tf(e),$forceUpdate:e=>()=>qf(e.update),$nextTick:e=>Vr.bind(e.proxy),$watch:e=>h_.bind(e)}),Qm={get(e,t){var{_:r}=e,{ctx:i,setupState:a,data:n,props:o,accessCache:s,type:l,appContext:u}=r,f;if(t[0]!=="$"){var v=s[t];if(v!==void 0)switch(v){case 0:return a[t];case 1:return n[t];case 3:return i[t];case 2:return o[t]}else{if(a!==xe&&re(a,t))return s[t]=0,a[t];if(n!==xe&&re(n,t))return s[t]=1,n[t];if((f=r.propsOptions[0])&&re(f,t))return s[t]=2,o[t];if(i!==xe&&re(i,t))return s[t]=3,i[t];rs&&(s[t]=4)}}var p=Za[t],d,_;if(p)return t==="$attrs"&&Je(r,"get",t),p(r);if((d=l.__cssModules)&&(d=d[t]))return d;if(i!==xe&&re(i,t))return s[t]=3,i[t];if(_=u.config.globalProperties,re(_,t))return _[t]},set(e,t,r){var{_:i}=e,{data:a,setupState:n,ctx:o}=i;if(n!==xe&&re(n,t))n[t]=r;else if(a!==xe&&re(a,t))a[t]=r;else if(re(i.props,t))return!1;return t[0]==="$"&&t.slice(1)in i?!1:(o[t]=r,!0)},has(e,t){var{_:{data:r,setupState:i,accessCache:a,ctx:n,appContext:o,propsOptions:s}}=e,l;return a[t]!==void 0||r!==xe&&re(r,t)||i!==xe&&re(i,t)||(l=s[0])&&re(l,t)||re(n,t)||re(Za,t)||re(o.config.globalProperties,t)}},e_=Df(),t_=0;function r_(e,t,r){var i=e.type,a=(t?t.appContext:e.appContext)||e_,n={uid:t_++,vnode:e,type:i,parent:t,appContext:a,root:null,next:null,subTree:null,update:null,scope:new D0(!0),render:null,proxy:null,exposed:null,exposeProxy:null,withProxy:null,provides:t?t.provides:Object.create(a.provides),accessCache:null,renderCache:[],components:null,directives:null,propsOptions:Af(i,a),emitsOptions:mf(i,a),emit:null,emitted:null,propsDefaults:xe,inheritAttrs:i.inheritAttrs,ctx:xe,data:xe,props:xe,attrs:xe,slots:xe,refs:xe,setupState:xe,setupContext:null,suspense:r,suspenseId:r?r.pendingId:0,asyncDep:null,asyncResolved:!1,isMounted:!1,isUnmounted:!1,isDeactivated:!1,bc:null,c:null,bm:null,m:null,bu:null,u:null,um:null,bum:null,da:null,a:null,rtg:null,rtc:null,ec:null,sp:null};return n.ctx={_:n},n.root=t?t.root:n,n.emit=gm.bind(null,n),e.ce&&e.ce(n),n}var ze=null,jt=()=>ze||ft,Ur=e=>{ze=e,e.scope.on()},hr=()=>{ze&&ze.scope.off(),ze=null};function Hf(e){return e.vnode.shapeFlag&4}var Ka=!1;function i_(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;Ka=t;var{props:r,children:i}=e.vnode,a=Hf(e);Bm(e,r,a,t),zm(e,i);var n=a?a_(e,t):void 0;return Ka=!1,n}function a_(e,t){var r=e.type;e.accessCache=Object.create(null),e.proxy=Ha(new Proxy(e.ctx,Qm));var{setup:i}=r;if(i){var a=e.setupContext=i.length>1?o_(e):null;Ur(e),Fr();var n=Yt(i,e,0,[e.props,a]);if(cr(),hr(),Su(n)){if(n.then(hr,hr),t)return n.then(o=>{Wf(e,o,t)}).catch(o=>{Ga(o,e,0)});e.asyncDep=n}else Wf(e,n,t)}else jf(e,t)}function Wf(e,t,r){ne(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:He(t)&&(e.setupState=pf(t)),jf(e,r)}var Vf;function jf(e,t,r){var i=e.type;if(!e.render){if(!t&&Vf&&!i.render){var a=i.template;if(a){var{isCustomElement:n,compilerOptions:o}=e.appContext.config,{delimiters:s,compilerOptions:l}=i,u=ve(ve({isCustomElement:n,delimiters:s},o),l);i.render=Vf(a,u)}}e.render=i.render||pt}Ur(e),Fr(),Rm(e),cr(),hr()}function n_(e){return new Proxy(e.attrs,{get(t,r){return Je(e,"get","$attrs"),t[r]}})}function o_(e){var t=i=>{e.exposed=i||{}},r;return{get attrs(){return r||(r=n_(e))},slots:e.slots,emit:e.emit,expose:t}}function cs(e){if(e.exposed)return e.exposeProxy||(e.exposeProxy=new Proxy(pf(Ha(e.exposed)),{get(t,r){if(r in t)return t[r];if(r in Za)return Za[r](e)}}))}function s_(e){return ne(e)&&"__vccOpts"in e}function Yt(e,t,r,i){var a;try{a=i?e(...i):e()}catch(n){Ga(n,t,r)}return a}function ct(e,t,r,i){if(ne(e)){var a=Yt(e,t,r,i);return a&&Su(a)&&a.catch(s=>{Ga(s,t,r)}),a}for(var n=[],o=0;o>>1,a=Oi(et[i]);aLt&&et.splice(t,1)}function Zf(e,t,r,i){se(e)?r.push(...e):(!t||!t.includes(e,e.allowRecurse?i+1:i))&&r.push(e),Xf()}function c_(e){Zf(e,Ti,Ei,Hr)}function v_(e){Zf(e,qt,Ci,Wr)}function gs(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(Ei.length){for(hs=t,Ti=[...new Set(Ei)],Ei.length=0,Hr=0;HrOi(r)-Oi(i)),Wr=0;Wre.id==null?1/0:e.id;function Gf(e){vs=!1,Ja=!0,gs(e),et.sort((i,a)=>Oi(i)-Oi(a));var t=pt;try{for(Lt=0;Lt2&&arguments[2]!==void 0?arguments[2]:xe,s=ze,l,u=!1,f=!1;if(qe(e)?(l=()=>e.value,u=!!e._shallow):zr(e)?(l=()=>e,i=!0):se(e)?(f=!0,u=e.some(zr),l=()=>e.map(g=>{if(qe(g))return g.value;if(zr(g))return gr(g);if(ne(g))return Yt(g,s,2)})):ne(e)?t?l=()=>Yt(e,s,2):l=()=>{if(!(s&&s.isUnmounted))return p&&p(),ct(e,s,3,[d])}:l=pt,t&&i){var v=l;l=()=>gr(v())}var p,d=g=>{p=m.onStop=()=>{Yt(g,s,4)}};if(Ka)return d=pt,t?r&&ct(t,s,3,[l(),f?[]:void 0,d]):l(),pt;var _=f?[]:Jf,b=()=>{if(!!m.active)if(t){var g=m.run();(i||u||(f?g.some((c,h)=>vi(c,_[h])):vi(g,_)))&&(p&&p(),ct(t,s,3,[g,_===Jf?void 0:_,d]),_=g)}else m.run()};b.allowRecurse=!!t;var x;a==="sync"?x=b:a==="post"?x=()=>je(b,s&&s.suspense):x=()=>{!s||s.isMounted?c_(b):b()};var m=new Wo(l,x);return t?r?b():_=m.run():a==="post"?je(m.run.bind(m),s&&s.suspense):m.run(),()=>{m.stop(),s&&s.scope&&yu(s.scope.effects,m)}}function h_(e,t,r){var i=this.proxy,a=Se(e)?e.includes(".")?Qf(i,e):()=>i[e]:e.bind(i,i),n;ne(t)?n=t:(n=t.handler,r=t);var o=ze;Ur(this);var s=ps(a,n.bind(i),r);return o?Ur(o):hr(),s}function Qf(e,t){var r=t.split(".");return()=>{for(var i=e,a=0;a{gr(a,t)});else if(mt(e))for(var i in e)gr(e[i],t);return e}function g_(e,t,r){var i=arguments.length;return i===2?He(t)&&!se(t)?Ya(t)?I(e,null,[t]):I(e,t):I(e,null,t):(i>3?r=Array.prototype.slice.call(arguments,2):i===3&&Ya(r)&&(r=[r]),I(e,t,r))}var p_="3.2.22",m_="http://www.w3.org/2000/svg",jr=typeof document!="undefined"?document:null,ec=new Map,__={insert:(e,t,r)=>{t.insertBefore(e,r||null)},remove:e=>{var t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,r,i)=>{var a=t?jr.createElementNS(m_,e):jr.createElement(e,r?{is:r}:void 0);return e==="select"&&i&&i.multiple!=null&&a.setAttribute("multiple",i.multiple),a},createText:e=>jr.createTextNode(e),createComment:e=>jr.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>jr.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},cloneNode(e){var t=e.cloneNode(!0);return"_value"in e&&(t._value=e._value),t},insertStaticContent(e,t,r,i){var a=r?r.previousSibling:t.lastChild,n=ec.get(e);if(!n){var o=jr.createElement("template");if(o.innerHTML=i?"".concat(e,""):e,n=o.content,i){for(var s=n.firstChild;s.firstChild;)n.appendChild(s.firstChild);n.removeChild(s)}ec.set(e,n)}return t.insertBefore(n.cloneNode(!0),r),[a?a.nextSibling:t.firstChild,r?r.previousSibling:t.lastChild]}};function b_(e,t,r){var i=e._vtc;i&&(t=(t?[t,...i]:[...i]).join(" ")),t==null?e.removeAttribute("class"):r?e.setAttribute("class",t):e.className=t}function w_(e,t,r){var i=e.style,a=Se(r);if(r&&!a){for(var n in r)ms(i,n,r[n]);if(t&&!Se(t))for(var o in t)r[o]==null&&ms(i,o,"")}else{var s=i.display;a?t!==r&&(i.cssText=r):t&&e.removeAttribute("style"),"_vod"in e&&(i.display=s)}}var tc=/\s*!important$/;function ms(e,t,r){if(se(r))r.forEach(a=>ms(e,t,a));else if(r=S_(r),t.startsWith("--"))e.setProperty(t,r);else{var i=x_(e,t);tc.test(r)?e.setProperty(Ke(i),r.replace(tc,""),"important"):e[i]=r}}var rc=["Webkit","Moz","ms"],_s={};function x_(e,t){var r=_s[t];if(r)return r;var i=Ft(t);if(i!=="filter"&&i in e)return _s[t]=i;i=Oa(i);for(var a=0;atypeof rpx2px!="function"?e:Se(e)?e.replace(y_,(t,r)=>rpx2px(r)+"px"):e,ic="http://www.w3.org/1999/xlink";function E_(e,t,r,i,a){if(i&&t.startsWith("xlink:"))r==null?e.removeAttributeNS(ic,t.slice(6,t.length)):e.setAttributeNS(ic,t,r);else{var n=cp(t);r==null||n&&!wu(r)?e.removeAttribute(t):e.setAttribute(t,n?"":r)}}function T_(e,t,r,i,a,n,o){if(t==="innerHTML"||t==="textContent"){i&&o(i,a,n),e[t]=r==null?"":r;return}if(t==="value"&&e.tagName!=="PROGRESS"){e._value=r;var s=r==null?"":r;e.value!==s&&(e.value=s),r==null&&e.removeAttribute(t);return}if(r===""||r==null){var l=typeof e[t];if(l==="boolean"){e[t]=wu(r);return}else if(r==null&&l==="string"){e[t]="",e.removeAttribute(t);return}else if(l==="number"){try{e[t]=0}catch(u){}e.removeAttribute(t);return}}try{e[t]=r}catch(u){}}var Qa=Date.now,ac=!1;if(typeof window!="undefined"){Qa()>document.createEvent("Event").timeStamp&&(Qa=()=>performance.now());var nc=navigator.userAgent.match(/firefox\/(\d+)/i);ac=!!(nc&&Number(nc[1])<=53)}var bs=0,C_=Promise.resolve(),O_=()=>{bs=0},A_=()=>bs||(C_.then(O_),bs=Qa());function I_(e,t,r,i){e.addEventListener(t,r,i)}function k_(e,t,r,i){e.removeEventListener(t,r,i)}function M_(e,t,r,i){var a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null,n=e._vei||(e._vei={}),o=n[t];if(i&&o)o.value=i;else{var[s,l]=R_(t);if(i){var u=n[t]=L_(i,a);I_(e,s,u,l)}else o&&(k_(e,s,o,l),n[t]=void 0)}}var oc=/(?:Once|Passive|Capture)$/;function R_(e){var t;if(oc.test(e)){t={};for(var r;r=e.match(oc);)e=e.slice(0,e.length-r[0].length),t[r[0].toLowerCase()]=!0}return[Ke(e.slice(2)),t]}function L_(e,t){var r=i=>{var a=i.timeStamp||Qa();(ac||a>=r.attached-1)&&ct(P_(i,r.value),t,5,[i])};return r.value=e,r.attached=A_(),r}function P_(e,t){if(se(t)){var r=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{r.call(e),e._stopped=!0},t.map(i=>a=>!a._stopped&&i(a))}else return t}var sc=/^on[a-z]/,N_=function(e,t,r,i){var a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,n=arguments.length>5?arguments[5]:void 0,o=arguments.length>6?arguments[6]:void 0,s=arguments.length>7?arguments[7]:void 0,l=arguments.length>8?arguments[8]:void 0;t==="class"?b_(e,i,a):t==="style"?w_(e,r,i):Ea(t)?mo(t)||M_(e,t,r,i,o):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):D_(e,t,i,a))?T_(e,t,i,n,o,s,l):(t==="true-value"?e._trueValue=i:t==="false-value"&&(e._falseValue=i),E_(e,t,i,a))};function D_(e,t,r,i){return i?!!(t==="innerHTML"||t==="textContent"||t in e&&sc.test(t)&&ne(r)):t==="spellcheck"||t==="draggable"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA"||sc.test(t)&&Se(r)?!1:t in e}var B_=["ctrl","shift","alt","meta"],$_={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>B_.some(r=>e["".concat(r,"Key")]&&!t.includes(r))},ws=(e,t)=>function(r){for(var i=0;i1?n-1:0),s=1;s{Ii(e,!1)}):Ii(e,i))},beforeUnmount(e,t){var{value:r}=t;Ii(e,r)}};function Ii(e,t){e.style.display=t?e._vod:"none"}var F_=ve({patchProp:N_},__),lc;function z_(){return lc||(lc=Vm(F_))}var uc=function(){var e=z_().createApp(...arguments),{mount:t}=e;return e.mount=r=>{var i=U_(r);if(!!i){var a=e._component;!ne(a)&&!a.render&&!a.template&&(a.template=i.innerHTML),i.innerHTML="";var n=t(i,!1,i instanceof SVGElement);return i instanceof Element&&(i.removeAttribute("v-cloak"),i.setAttribute("data-v-app","")),n}},e};function U_(e){if(Se(e)){var t=document.querySelector(e);return t}return e}var fc=["top","left","right","bottom"],xs,en={},ot;function ys(){return!("CSS"in window)||typeof CSS.supports!="function"?ot="":CSS.supports("top: env(safe-area-inset-top)")?ot="env":CSS.supports("top: constant(safe-area-inset-top)")?ot="constant":ot="",ot}function cc(){if(ot=typeof ot=="string"?ot:ys(),!ot){fc.forEach(function(s){en[s]=0});return}function e(s,l){var u=s.style;Object.keys(l).forEach(function(f){var v=l[f];u[f]=v})}var t=[];function r(s){s?t.push(s):t.forEach(function(l){l()})}var i=!1;try{var a=Object.defineProperty({},"passive",{get:function(){i={passive:!0}}});window.addEventListener("test",null,a)}catch(s){}function n(s,l){var u=document.createElement("div"),f=document.createElement("div"),v=document.createElement("div"),p=document.createElement("div"),d=100,_=1e4,b={position:"absolute",width:d+"px",height:"200px",boxSizing:"border-box",overflow:"hidden",paddingBottom:ot+"(safe-area-inset-"+l+")"};e(u,b),e(f,b),e(v,{transition:"0s",animation:"none",width:"400px",height:"400px"}),e(p,{transition:"0s",animation:"none",width:"250%",height:"250%"}),u.appendChild(v),f.appendChild(p),s.appendChild(u),s.appendChild(f),r(function(){u.scrollTop=f.scrollTop=_;var m=u.scrollTop,g=f.scrollTop;function c(){this.scrollTop!==(this===u?m:g)&&(u.scrollTop=f.scrollTop=_,m=u.scrollTop,g=f.scrollTop,H_(l))}u.addEventListener("scroll",c,i),f.addEventListener("scroll",c,i)});var x=getComputedStyle(u);Object.defineProperty(en,l,{configurable:!0,get:function(){return parseFloat(x.paddingBottom)}})}var o=document.createElement("div");e(o,{position:"absolute",left:"0",top:"0",width:"0",height:"0",zIndex:"-1",overflow:"hidden",visibility:"hidden"}),fc.forEach(function(s){n(o,s)}),document.body.appendChild(o),r(),xs=!0}function tn(e){return xs||cc(),en[e]}var rn=[];function H_(e){rn.length||setTimeout(function(){var t={};rn.forEach(function(r){t[r]=en[r]}),rn.length=0,an.forEach(function(r){r(t)})},0),rn.push(e)}var an=[];function W_(e){!ys()||(xs||cc(),typeof e=="function"&&an.push(e))}function V_(e){var t=an.indexOf(e);t>=0&&an.splice(t,1)}var j_={get support(){return(typeof ot=="string"?ot:ys()).length!=0},get top(){return tn("top")},get left(){return tn("left")},get right(){return tn("right")},get bottom(){return tn("bottom")},onChange:W_,offChange:V_},nn=j_,Y_=ws(()=>{},["prevent"]);function Ss(){var e=document.documentElement.style,t=parseInt(e.getPropertyValue("--window-top"));return t?t+nn.top:0}function q_(){var e=document.documentElement.style,t=Ss(),r=parseInt(e.getPropertyValue("--window-bottom")),i=parseInt(e.getPropertyValue("--window-left")),a=parseInt(e.getPropertyValue("--window-right"));return{top:t,bottom:r?r+nn.bottom:0,left:i?i+nn.left:0,right:a?a+nn.right:0}}function X_(e){var t=document.documentElement.style;Object.keys(e).forEach(r=>{t.setProperty(r,e[r])})}function on(e){return Symbol(e)}function vc(e){return e=e+"",e.indexOf("rpx")!==-1||e.indexOf("upx")!==-1}function pr(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(t)return Z_(e);if(typeof e=="string"){var r=parseInt(e)||0;return vc(e)?uni.upx2px(r):r}return e}function Z_(e){return vc(e)?e.replace(/(\d+(\.\d+)?)[ru]px/g,(t,r)=>uni.upx2px(parseFloat(r))+"px"):e}var K_="M20.928 10.176l-4.928 4.928-4.928-4.928-0.896 0.896 4.928 4.928-4.928 4.928 0.896 0.896 4.928-4.928 4.928 4.928 0.896-0.896-4.928-4.928 4.928-4.928-0.896-0.896zM16 2.080q-3.776 0-7.040 1.888-3.136 1.856-4.992 4.992-1.888 3.264-1.888 7.040t1.888 7.040q1.856 3.136 4.992 4.992 3.264 1.888 7.040 1.888t7.040-1.888q3.136-1.856 4.992-4.992 1.888-3.264 1.888-7.040t-1.888-7.040q-1.856-3.136-4.992-4.992-3.264-1.888-7.040-1.888zM16 28.64q-3.424 0-6.4-1.728-2.848-1.664-4.512-4.512-1.728-2.976-1.728-6.4t1.728-6.4q1.664-2.848 4.512-4.512 2.976-1.728 6.4-1.728t6.4 1.728q2.848 1.664 4.512 4.512 1.728 2.976 1.728 6.4t-1.728 6.4q-1.664 2.848-4.512 4.512-2.976 1.728-6.4 1.728z",G_="M16 0q-4.352 0-8.064 2.176-3.616 2.144-5.76 5.76-2.176 3.712-2.176 8.064t2.176 8.064q2.144 3.616 5.76 5.76 3.712 2.176 8.064 2.176t8.064-2.176q3.616-2.144 5.76-5.76 2.176-3.712 2.176-8.064t-2.176-8.064q-2.144-3.616-5.76-5.76-3.712-2.176-8.064-2.176zM22.688 21.408q0.32 0.32 0.304 0.752t-0.336 0.736-0.752 0.304-0.752-0.32l-5.184-5.376-5.376 5.184q-0.32 0.32-0.752 0.304t-0.736-0.336-0.304-0.752 0.32-0.752l5.376-5.184-5.184-5.376q-0.32-0.32-0.304-0.752t0.336-0.752 0.752-0.304 0.752 0.336l5.184 5.376 5.376-5.184q0.32-0.32 0.752-0.304t0.752 0.336 0.304 0.752-0.336 0.752l-5.376 5.184 5.184 5.376z",J_="M15.808 1.696q-3.776 0-7.072 1.984-3.2 1.888-5.088 5.152-1.952 3.392-1.952 7.36 0 3.776 1.952 7.072 1.888 3.2 5.088 5.088 3.296 1.952 7.072 1.952 3.968 0 7.36-1.952 3.264-1.888 5.152-5.088 1.984-3.296 1.984-7.072 0-4-1.984-7.36-1.888-3.264-5.152-5.152-3.36-1.984-7.36-1.984zM20.864 18.592l-3.776 4.928q-0.448 0.576-1.088 0.576t-1.088-0.576l-3.776-4.928q-0.448-0.576-0.24-0.992t0.944-0.416h2.976v-8.928q0-0.256 0.176-0.432t0.4-0.176h1.216q0.224 0 0.4 0.176t0.176 0.432v8.928h2.976q0.736 0 0.944 0.416t-0.24 0.992z",Q_="M15.808 0.128q-4.224 0-7.872 2.176-3.552 2.112-5.632 5.728-2.176 3.776-2.176 8.16 0 4.224 2.176 7.872 2.080 3.552 5.632 5.632 3.648 2.176 7.872 2.176 4.384 0 8.16-2.176 3.616-2.080 5.728-5.632 2.176-3.648 2.176-7.872 0-4.416-2.176-8.16-2.112-3.616-5.728-5.728-3.744-2.176-8.16-2.176zM16.864 23.776q0 0.064-0.064 0.064h-1.568q-0.096 0-0.096-0.064l-0.256-11.328q0-0.064 0.064-0.064h2.112q0.096 0 0.064 0.064l-0.256 11.328zM16 10.88q-0.576 0-0.976-0.4t-0.4-0.96 0.4-0.96 0.976-0.4 0.976 0.4 0.4 0.96-0.4 0.96-0.976 0.4z",eb="M20.928 22.688q-1.696 1.376-3.744 2.112-2.112 0.768-4.384 0.768-3.488 0-6.464-1.728-2.88-1.696-4.576-4.608-1.76-2.976-1.76-6.464t1.76-6.464q1.696-2.88 4.576-4.576 2.976-1.76 6.464-1.76t6.464 1.76q2.912 1.696 4.608 4.576 1.728 2.976 1.728 6.464 0 2.272-0.768 4.384-0.736 2.048-2.112 3.744l9.312 9.28-1.824 1.824-9.28-9.312zM12.8 23.008q2.784 0 5.184-1.376 2.304-1.376 3.68-3.68 1.376-2.4 1.376-5.184t-1.376-5.152q-1.376-2.336-3.68-3.68-2.4-1.408-5.184-1.408t-5.152 1.408q-2.336 1.344-3.68 3.68-1.408 2.368-1.408 5.152t1.408 5.184q1.344 2.304 3.68 3.68 2.368 1.376 5.152 1.376zM12.8 23.008v0z",sn="M1.952 18.080q-0.32-0.352-0.416-0.88t0.128-0.976l0.16-0.352q0.224-0.416 0.64-0.528t0.8 0.176l6.496 4.704q0.384 0.288 0.912 0.272t0.88-0.336l17.312-14.272q0.352-0.288 0.848-0.256t0.848 0.352l-0.416-0.416q0.32 0.352 0.32 0.816t-0.32 0.816l-18.656 18.912q-0.32 0.352-0.8 0.352t-0.8-0.32l-7.936-8.064z",tb="M15.808 0.16q-4.224 0-7.872 2.176-3.552 2.112-5.632 5.728-2.144 3.744-2.144 8.128 0 4.192 2.144 7.872 2.112 3.52 5.632 5.632 3.68 2.144 7.872 2.144 4.384 0 8.128-2.144 3.616-2.080 5.728-5.632 2.176-3.648 2.176-7.872 0-4.384-2.176-8.128-2.112-3.616-5.728-5.728-3.744-2.176-8.128-2.176zM24.832 11.328l-11.264 11.104q-0.032 0.032-0.112 0.032t-0.112-0.032l-5.216-5.376q-0.096-0.128 0-0.288l0.704-0.96q0.032-0.064 0.112-0.064t0.112 0.032l4.256 3.264q0.064 0.032 0.144 0.032t0.112-0.032l10.336-8.608q0.064-0.064 0.144-0.064t0.112 0.064l0.672 0.672q0.128 0.128 0 0.224z",rb="M15.84 0.096q-4.224 0-7.872 2.176-3.552 2.112-5.632 5.728-2.144 3.744-2.144 8.128 0 4.192 2.144 7.872 2.112 3.52 5.632 5.632 3.68 2.144 7.872 2.144 4.384 0 8.128-2.144 3.616-2.080 5.728-5.632 2.176-3.648 2.176-7.872 0-4.384-2.176-8.128-2.112-3.616-5.728-5.728-3.744-2.176-8.128-2.176zM23.008 21.92l-0.512 0.896q-0.096 0.128-0.224 0.064l-8-3.808q-0.096-0.064-0.16-0.128-0.128-0.096-0.128-0.288l0.512-12.096q0-0.064 0.048-0.112t0.112-0.048h1.376q0.064 0 0.112 0.048t0.048 0.112l0.448 10.848 6.304 4.256q0.064 0.064 0.080 0.128t-0.016 0.128z",ib="M15.808 0.16q-4.224 0-7.872 2.176-3.552 2.112-5.632 5.728-2.144 3.744-2.144 8.128 0 4.192 2.144 7.872 2.112 3.52 5.632 5.632 3.68 2.144 7.872 2.144 4.384 0 8.128-2.144 3.616-2.080 5.728-5.632 2.176-3.648 2.176-7.872 0-4.384-2.176-8.128-2.112-3.616-5.728-5.728-3.744-2.176-8.128-2.176zM15.136 8.672h1.728q0.128 0 0.224 0.096t0.096 0.256l-0.384 10.24q0 0.064-0.048 0.112t-0.112 0.048h-1.248q-0.096 0-0.144-0.048t-0.048-0.112l-0.384-10.24q0-0.16 0.096-0.256t0.224-0.096zM16 23.328q-0.48 0-0.832-0.352t-0.352-0.848 0.352-0.848 0.832-0.352 0.832 0.352 0.352 0.848-0.352 0.848-0.832 0.352z";function ln(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#000",r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:27;return I("svg",{width:r,height:r,viewBox:"0 0 32 32"},[I("path",{d:e,fill:t},null,8,["d","fill"])],8,["width","height"])}function un(){return Xt()}function ab(){return window.__PAGE_INFO__}function Xt(){return window.__id__||(window.__id__=plus.webview.currentWebview().id),parseInt(window.__id__)}function nb(e){e.preventDefault()}var dc,hc=0;function ob(e){var{onPageScroll:t,onReachBottom:r,onReachBottomDistance:i}=e,a=!1,n=!1,o=!0,s=()=>{var{scrollHeight:u}=document.documentElement,f=window.innerHeight,v=window.scrollY,p=v>0&&u>f&&v+f+i>=u,d=Math.abs(u-hc)>i;return p&&(!n||d)?(hc=u,n=!0,!0):(!p&&n&&(n=!1),!1)},l=()=>{t&&t(window.pageYOffset);function u(){if(s())return r&&r(),o=!1,setTimeout(function(){o=!0},350),!0}r&&o&&(u()||(dc=setTimeout(u,300))),a=!1};return function(){clearTimeout(dc),a||requestAnimationFrame(l),a=!0}}function Es(e,t){if(t.indexOf("/")===0)return t;if(t.indexOf("./")===0)return Es(e,t.substr(2));for(var r=t.split("/"),i=r.length,a=0;a0?e.split("/"):[];return n.splice(n.length-a-1,a+1),Ro(n.concat(r).join("/"))}class sb{constructor(t){this.$bindClass=!1,this.$bindStyle=!1,this.$vm=t,this.$el=t.$el,this.$el.getAttribute&&(this.$bindClass=!!this.$el.getAttribute("class"),this.$bindStyle=!!this.$el.getAttribute("style"))}selectComponent(t){if(!(!this.$el||!t)){var r=gc(this.$el.querySelector(t));if(!!r)return Ts(r)}}selectAllComponents(t){if(!this.$el||!t)return[];for(var r=[],i=this.$el.querySelectorAll(t),a=0;a-1&&r.splice(i,1)}var a=this.$el.__wxsRemoveClass||(this.$el.__wxsRemoveClass=[]);return a.indexOf(t)===-1&&(a.push(t),this.forceUpdate("class")),this}hasClass(t){return this.$el&&this.$el.classList.contains(t)}getDataset(){return this.$el&&this.$el.dataset}callMethod(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=this.$vm[t];ne(i)?i(JSON.parse(JSON.stringify(r))):this.$vm.ownerId&&UniViewJSBridge.publishHandler(Mp,{nodeId:this.$el.__id,ownerId:this.$vm.ownerId,method:t,args:r})}requestAnimationFrame(t){return window.requestAnimationFrame(t)}getState(){return this.$el&&(this.$el.__wxsState||(this.$el.__wxsState={}))}triggerEvent(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.$vm.$emit(t,r),this}getComputedStyle(t){if(this.$el){var r=window.getComputedStyle(this.$el);return t&&t.length?t.reduce((i,a)=>(i[a]=r[a],i),{}):r}return{}}setTimeout(t,r){return window.setTimeout(t,r)}clearTimeout(t){return window.clearTimeout(t)}getBoundingClientRect(){return this.$el.getBoundingClientRect()}}function Ts(e){if(e&&e.$el)return e.$el.__wxsComponentDescriptor||(e.$el.__wxsComponentDescriptor=new sb(e)),e.$el.__wxsComponentDescriptor}function fn(e,t){return Ts(e)}function gc(e){if(!!e)return ki(e)}function ki(e){return e.__wxsVm||(e.__wxsVm={ownerId:e.__ownerId,$el:e,$emit(){},$forceUpdate(){var{__wxsStyle:t,__wxsAddClass:r,__wxsRemoveClass:i,__wxsStyleChanged:a,__wxsClassChanged:n}=e,o,s;a&&(e.__wxsStyleChanged=!1,t&&(s=()=>{Object.keys(t).forEach(l=>{e.style[l]=t[l]})})),n&&(e.__wxsClassChanged=!1,o=()=>{i&&i.forEach(l=>{e.classList.remove(l)}),r&&r.forEach(l=>{e.classList.add(l)})}),requestAnimationFrame(()=>{o&&o(),s&&s()})}})}var lb=e=>e.type==="click";function pc(e,t,r){var{currentTarget:i}=e;if(!(e instanceof Event)||!(i instanceof HTMLElement))return[e];if(i.tagName.indexOf("UNI-")!==0)return[e];var a=mc(e);if(lb(e))fb(a,e);else if(e instanceof TouchEvent){var n=Ss();a.touches=_c(e.touches,n),a.changedTouches=_c(e.changedTouches,n)}return[a]}function ub(e){for(;e&&e.tagName.indexOf("UNI-")!==0;)e=e.parentElement;return e}function mc(e){var{type:t,timeStamp:r,target:i,currentTarget:a}=e,n={type:t,timeStamp:r,target:Oo(ub(i)),detail:{},currentTarget:Oo(a)};return e._stopped&&(n._stopped=!0),e.type.startsWith("touch")&&(n.touches=e.touches,n.changedTouches=e.changedTouches),n}function fb(e,t){var{x:r,y:i}=t,a=Ss();e.detail={x:r,y:i-a},e.touches=e.changedTouches=[cb(t)]}function cb(e){return{force:1,identifier:0,clientX:e.clientX,clientY:e.clientY,pageX:e.pageX,pageY:e.pageY}}function _c(e,t){for(var r=[],i=0;i1&&arguments[1]!==void 0?arguments[1]:{},r=Xt()+"";plus.webview.postMessageToUniNView({type:"subscribeHandler",args:{type:e,data:t,pageId:r}},vb)}function bb(e,t){var r=e[0];if(!(!t||!mt(t.formatArgs)&&mt(r)))for(var i=t.formatArgs,a=Object.keys(i),n=0;nplus.io.convertLocalFileSystemURL(e).replace(/^\/?apps\//,"/android_asset/apps/").replace(/\/$/,""));function Sb(e){return e.indexOf("_www")===0||e.indexOf("_doc")===0||e.indexOf("_documents")===0||e.indexOf("_downloads")===0}var Pt={};(function(e){var t=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Int32Array!="undefined";function r(n,o){return Object.prototype.hasOwnProperty.call(n,o)}e.assign=function(n){for(var o=Array.prototype.slice.call(arguments,1);o.length;){var s=o.shift();if(!!s){if(typeof s!="object")throw new TypeError(s+"must be non-object");for(var l in s)r(s,l)&&(n[l]=s[l])}}return n},e.shrinkBuf=function(n,o){return n.length===o?n:n.subarray?n.subarray(0,o):(n.length=o,n)};var i={arraySet:function(n,o,s,l,u){if(o.subarray&&n.subarray){n.set(o.subarray(s,s+l),u);return}for(var f=0;f=0;)e[t]=0}var Ob=0,Cc=1,Ab=2,Ib=3,kb=258,Cs=29,Ri=256,Li=Ri+1+Cs,Xr=30,Os=19,Oc=2*Li+1,mr=15,As=16,Mb=7,Is=256,Ac=16,Ic=17,kc=18,ks=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],cn=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Rb=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],Mc=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Lb=512,Nt=new Array((Li+2)*2);qr(Nt);var Pi=new Array(Xr*2);qr(Pi);var Ni=new Array(Lb);qr(Ni);var Di=new Array(kb-Ib+1);qr(Di);var Ms=new Array(Cs);qr(Ms);var vn=new Array(Xr);qr(vn);function Rs(e,t,r,i,a){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=i,this.max_length=a,this.has_stree=e&&e.length}var Rc,Lc,Pc;function Ls(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function Nc(e){return e<256?Ni[e]:Ni[256+(e>>>7)]}function Bi(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function Xe(e,t,r){e.bi_valid>As-r?(e.bi_buf|=t<>As-e.bi_valid,e.bi_valid+=r-As):(e.bi_buf|=t<>>=1,r<<=1;while(--t>0);return r>>>1}function Pb(e){e.bi_valid===16?(Bi(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function Nb(e,t){var r=t.dyn_tree,i=t.max_code,a=t.stat_desc.static_tree,n=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,l=t.stat_desc.max_length,u,f,v,p,d,_,b=0;for(p=0;p<=mr;p++)e.bl_count[p]=0;for(r[e.heap[e.heap_max]*2+1]=0,u=e.heap_max+1;ul&&(p=l,b++),r[f*2+1]=p,!(f>i)&&(e.bl_count[p]++,d=0,f>=s&&(d=o[f-s]),_=r[f*2],e.opt_len+=_*(p+d),n&&(e.static_len+=_*(a[f*2+1]+d)));if(b!==0){do{for(p=l-1;e.bl_count[p]===0;)p--;e.bl_count[p]--,e.bl_count[p+1]+=2,e.bl_count[l]--,b-=2}while(b>0);for(p=l;p!==0;p--)for(f=e.bl_count[p];f!==0;)v=e.heap[--u],!(v>i)&&(r[v*2+1]!==p&&(e.opt_len+=(p-r[v*2+1])*r[v*2],r[v*2+1]=p),f--)}}function Bc(e,t,r){var i=new Array(mr+1),a=0,n,o;for(n=1;n<=mr;n++)i[n]=a=a+r[n-1]<<1;for(o=0;o<=t;o++){var s=e[o*2+1];s!==0&&(e[o*2]=Dc(i[s]++,s))}}function Db(){var e,t,r,i,a,n=new Array(mr+1);for(r=0,i=0;i>=7;i8?Bi(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function Bb(e,t,r,i){Fc(e),i&&(Bi(e,r),Bi(e,~r)),Eb.arraySet(e.pending_buf,e.window,t,r,e.pending),e.pending+=r}function zc(e,t,r,i){var a=t*2,n=r*2;return e[a]>1;o>=1;o--)Ps(e,r,o);u=n;do o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Ps(e,r,1),s=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=s,r[u*2]=r[o*2]+r[s*2],e.depth[u]=(e.depth[o]>=e.depth[s]?e.depth[o]:e.depth[s])+1,r[o*2+1]=r[s*2+1]=u,e.heap[1]=u++,Ps(e,r,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],Nb(e,t),Bc(r,l,e.bl_count)}function Hc(e,t,r){var i,a=-1,n,o=t[0*2+1],s=0,l=7,u=4;for(o===0&&(l=138,u=3),t[(r+1)*2+1]=65535,i=0;i<=r;i++)n=o,o=t[(i+1)*2+1],!(++s=3&&e.bl_tree[Mc[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function Fb(e,t,r,i){var a;for(Xe(e,t-257,5),Xe(e,r-1,5),Xe(e,i-4,4),a=0;a>>=1)if(t&1&&e.dyn_ltree[r*2]!==0)return Ec;if(e.dyn_ltree[9*2]!==0||e.dyn_ltree[10*2]!==0||e.dyn_ltree[13*2]!==0)return Tc;for(r=32;r0?(e.strm.data_type===Cb&&(e.strm.data_type=zb(e)),Ns(e,e.l_desc),Ns(e,e.d_desc),o=$b(e),a=e.opt_len+3+7>>>3,n=e.static_len+3+7>>>3,n<=a&&(a=n)):a=n=r+5,r+4<=a&&t!==-1?jc(e,t,r,i):e.strategy===Tb||n===a?(Xe(e,(Cc<<1)+(i?1:0),3),Uc(e,Nt,Pi)):(Xe(e,(Ab<<1)+(i?1:0),3),Fb(e,e.l_desc.max_code+1,e.d_desc.max_code+1,o+1),Uc(e,e.dyn_ltree,e.dyn_dtree)),$c(e),i&&Fc(e)}function Vb(e,t,r){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=r&255,e.last_lit++,t===0?e.dyn_ltree[r*2]++:(e.matches++,t--,e.dyn_ltree[(Di[r]+Ri+1)*2]++,e.dyn_dtree[Nc(t)*2]++),e.last_lit===e.lit_bufsize-1}Yr._tr_init=Ub,Yr._tr_stored_block=jc,Yr._tr_flush_block=Wb,Yr._tr_tally=Vb,Yr._tr_align=Hb;function jb(e,t,r,i){for(var a=e&65535|0,n=e>>>16&65535|0,o=0;r!==0;){o=r>2e3?2e3:r,r-=o;do a=a+t[i++]|0,n=n+a|0;while(--o);a%=65521,n%=65521}return a|n<<16|0}var Yc=jb;function Yb(){for(var e,t=[],r=0;r<256;r++){e=r;for(var i=0;i<8;i++)e=e&1?3988292384^e>>>1:e>>>1;t[r]=e}return t}var qb=Yb();function Xb(e,t,r,i){var a=qb,n=i+r;e^=-1;for(var o=i;o>>8^a[(e^t[o])&255];return e^-1}var qc=Xb,Ds={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Ye=Pt,st=Yr,Xc=Yc,Zt=qc,Zb=Ds,_r=0,Kb=1,Gb=3,Kt=4,Zc=5,Tt=0,Kc=1,lt=-2,Jb=-3,Bs=-5,Qb=-1,ew=1,dn=2,tw=3,rw=4,iw=0,aw=2,hn=8,nw=9,ow=15,sw=8,lw=29,uw=256,$s=uw+1+lw,fw=30,cw=19,vw=2*$s+1,dw=15,de=3,Gt=258,dt=Gt+de+1,hw=32,gn=42,Fs=69,pn=73,mn=91,_n=103,br=113,$i=666,Le=1,Fi=2,wr=3,Zr=4,gw=3;function Jt(e,t){return e.msg=Zb[t],t}function Gc(e){return(e<<1)-(e>4?9:0)}function Qt(e){for(var t=e.length;--t>=0;)e[t]=0}function er(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),r!==0&&(Ye.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,t.pending===0&&(t.pending_out=0))}function Ue(e,t){st._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,er(e.strm)}function pe(e,t){e.pending_buf[e.pending++]=t}function zi(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function pw(e,t,r,i){var a=e.avail_in;return a>i&&(a=i),a===0?0:(e.avail_in-=a,Ye.arraySet(t,e.input,e.next_in,a,r),e.state.wrap===1?e.adler=Xc(e.adler,t,a,r):e.state.wrap===2&&(e.adler=Zt(e.adler,t,a,r)),e.next_in+=a,e.total_in+=a,a)}function Jc(e,t){var r=e.max_chain_length,i=e.strstart,a,n,o=e.prev_length,s=e.nice_match,l=e.strstart>e.w_size-dt?e.strstart-(e.w_size-dt):0,u=e.window,f=e.w_mask,v=e.prev,p=e.strstart+Gt,d=u[i+o-1],_=u[i+o];e.prev_length>=e.good_match&&(r>>=2),s>e.lookahead&&(s=e.lookahead);do if(a=t,!(u[a+o]!==_||u[a+o-1]!==d||u[a]!==u[i]||u[++a]!==u[i+1])){i+=2,a++;do;while(u[++i]===u[++a]&&u[++i]===u[++a]&&u[++i]===u[++a]&&u[++i]===u[++a]&&u[++i]===u[++a]&&u[++i]===u[++a]&&u[++i]===u[++a]&&u[++i]===u[++a]&&io){if(e.match_start=t,o=n,n>=s)break;d=u[i+o-1],_=u[i+o]}}while((t=v[t&f])>l&&--r!=0);return o<=e.lookahead?o:e.lookahead}function xr(e){var t=e.w_size,r,i,a,n,o;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-dt)){Ye.arraySet(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,i=e.hash_size,r=i;do a=e.head[--r],e.head[r]=a>=t?a-t:0;while(--i);i=t,r=i;do a=e.prev[--r],e.prev[r]=a>=t?a-t:0;while(--i);n+=t}if(e.strm.avail_in===0)break;if(i=pw(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=de)for(o=e.strstart-e.insert,e.ins_h=e.window[o],e.ins_h=(e.ins_h<e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(xr(e),e.lookahead===0&&t===_r)return Le;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var i=e.block_start+r;if((e.strstart===0||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,Ue(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-dt&&(Ue(e,!1),e.strm.avail_out===0))return Le}return e.insert=0,t===Kt?(Ue(e,!0),e.strm.avail_out===0?wr:Zr):(e.strstart>e.block_start&&(Ue(e,!1),e.strm.avail_out===0),Le)}function zs(e,t){for(var r,i;;){if(e.lookahead=de&&(e.ins_h=(e.ins_h<=de)if(i=st._tr_tally(e,e.strstart-e.match_start,e.match_length-de),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=de){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<=de&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=de-1)),e.prev_length>=de&&e.match_length<=e.prev_length){a=e.strstart+e.lookahead-de,i=st._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-de),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=a&&(e.ins_h=(e.ins_h<=de&&e.strstart>0&&(a=e.strstart-1,i=o[a],i===o[++a]&&i===o[++a]&&i===o[++a])){n=e.strstart+Gt;do;while(i===o[++a]&&i===o[++a]&&i===o[++a]&&i===o[++a]&&i===o[++a]&&i===o[++a]&&i===o[++a]&&i===o[++a]&&ae.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=de?(r=st._tr_tally(e,1,e.match_length-de),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=st._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(Ue(e,!1),e.strm.avail_out===0))return Le}return e.insert=0,t===Kt?(Ue(e,!0),e.strm.avail_out===0?wr:Zr):e.last_lit&&(Ue(e,!1),e.strm.avail_out===0)?Le:Fi}function bw(e,t){for(var r;;){if(e.lookahead===0&&(xr(e),e.lookahead===0)){if(t===_r)return Le;break}if(e.match_length=0,r=st._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(Ue(e,!1),e.strm.avail_out===0))return Le}return e.insert=0,t===Kt?(Ue(e,!0),e.strm.avail_out===0?wr:Zr):e.last_lit&&(Ue(e,!1),e.strm.avail_out===0)?Le:Fi}function Ct(e,t,r,i,a){this.good_length=e,this.max_lazy=t,this.nice_length=r,this.max_chain=i,this.func=a}var Gr;Gr=[new Ct(0,0,0,0,mw),new Ct(4,4,8,4,zs),new Ct(4,5,16,8,zs),new Ct(4,6,32,32,zs),new Ct(4,4,16,16,Kr),new Ct(8,16,32,32,Kr),new Ct(8,16,128,128,Kr),new Ct(8,32,128,256,Kr),new Ct(32,128,258,1024,Kr),new Ct(32,258,258,4096,Kr)];function ww(e){e.window_size=2*e.w_size,Qt(e.head),e.max_lazy_match=Gr[e.level].max_lazy,e.good_match=Gr[e.level].good_length,e.nice_match=Gr[e.level].nice_length,e.max_chain_length=Gr[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=de-1,e.match_available=0,e.ins_h=0}function xw(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=hn,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Ye.Buf16(vw*2),this.dyn_dtree=new Ye.Buf16((2*fw+1)*2),this.bl_tree=new Ye.Buf16((2*cw+1)*2),Qt(this.dyn_ltree),Qt(this.dyn_dtree),Qt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Ye.Buf16(dw+1),this.heap=new Ye.Buf16(2*$s+1),Qt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Ye.Buf16(2*$s+1),Qt(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function Qc(e){var t;return!e||!e.state?Jt(e,lt):(e.total_in=e.total_out=0,e.data_type=aw,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?gn:br,e.adler=t.wrap===2?0:1,t.last_flush=_r,st._tr_init(t),Tt)}function ev(e){var t=Qc(e);return t===Tt&&ww(e.state),t}function yw(e,t){return!e||!e.state||e.state.wrap!==2?lt:(e.state.gzhead=t,Tt)}function tv(e,t,r,i,a,n){if(!e)return lt;var o=1;if(t===Qb&&(t=6),i<0?(o=0,i=-i):i>15&&(o=2,i-=16),a<1||a>nw||r!==hn||i<8||i>15||t<0||t>9||n<0||n>rw)return Jt(e,lt);i===8&&(i=9);var s=new xw;return e.state=s,s.strm=e,s.wrap=o,s.gzhead=null,s.w_bits=i,s.w_size=1<Zc||t<0)return e?Jt(e,lt):lt;if(i=e.state,!e.output||!e.input&&e.avail_in!==0||i.status===$i&&t!==Kt)return Jt(e,e.avail_out===0?Bs:lt);if(i.strm=e,r=i.last_flush,i.last_flush=t,i.status===gn)if(i.wrap===2)e.adler=0,pe(i,31),pe(i,139),pe(i,8),i.gzhead?(pe(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),pe(i,i.gzhead.time&255),pe(i,i.gzhead.time>>8&255),pe(i,i.gzhead.time>>16&255),pe(i,i.gzhead.time>>24&255),pe(i,i.level===9?2:i.strategy>=dn||i.level<2?4:0),pe(i,i.gzhead.os&255),i.gzhead.extra&&i.gzhead.extra.length&&(pe(i,i.gzhead.extra.length&255),pe(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=Zt(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=Fs):(pe(i,0),pe(i,0),pe(i,0),pe(i,0),pe(i,0),pe(i,i.level===9?2:i.strategy>=dn||i.level<2?4:0),pe(i,gw),i.status=br);else{var o=hn+(i.w_bits-8<<4)<<8,s=-1;i.strategy>=dn||i.level<2?s=0:i.level<6?s=1:i.level===6?s=2:s=3,o|=s<<6,i.strstart!==0&&(o|=hw),o+=31-o%31,i.status=br,zi(i,o),i.strstart!==0&&(zi(i,e.adler>>>16),zi(i,e.adler&65535)),e.adler=1}if(i.status===Fs)if(i.gzhead.extra){for(a=i.pending;i.gzindex<(i.gzhead.extra.length&65535)&&!(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>a&&(e.adler=Zt(e.adler,i.pending_buf,i.pending-a,a)),er(e),a=i.pending,i.pending===i.pending_buf_size));)pe(i,i.gzhead.extra[i.gzindex]&255),i.gzindex++;i.gzhead.hcrc&&i.pending>a&&(e.adler=Zt(e.adler,i.pending_buf,i.pending-a,a)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=pn)}else i.status=pn;if(i.status===pn)if(i.gzhead.name){a=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>a&&(e.adler=Zt(e.adler,i.pending_buf,i.pending-a,a)),er(e),a=i.pending,i.pending===i.pending_buf_size)){n=1;break}i.gzindexa&&(e.adler=Zt(e.adler,i.pending_buf,i.pending-a,a)),n===0&&(i.gzindex=0,i.status=mn)}else i.status=mn;if(i.status===mn)if(i.gzhead.comment){a=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>a&&(e.adler=Zt(e.adler,i.pending_buf,i.pending-a,a)),er(e),a=i.pending,i.pending===i.pending_buf_size)){n=1;break}i.gzindexa&&(e.adler=Zt(e.adler,i.pending_buf,i.pending-a,a)),n===0&&(i.status=_n)}else i.status=_n;if(i.status===_n&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&er(e),i.pending+2<=i.pending_buf_size&&(pe(i,e.adler&255),pe(i,e.adler>>8&255),e.adler=0,i.status=br)):i.status=br),i.pending!==0){if(er(e),e.avail_out===0)return i.last_flush=-1,Tt}else if(e.avail_in===0&&Gc(t)<=Gc(r)&&t!==Kt)return Jt(e,Bs);if(i.status===$i&&e.avail_in!==0)return Jt(e,Bs);if(e.avail_in!==0||i.lookahead!==0||t!==_r&&i.status!==$i){var l=i.strategy===dn?bw(i,t):i.strategy===tw?_w(i,t):Gr[i.level].func(i,t);if((l===wr||l===Zr)&&(i.status=$i),l===Le||l===wr)return e.avail_out===0&&(i.last_flush=-1),Tt;if(l===Fi&&(t===Kb?st._tr_align(i):t!==Zc&&(st._tr_stored_block(i,0,0,!1),t===Gb&&(Qt(i.head),i.lookahead===0&&(i.strstart=0,i.block_start=0,i.insert=0))),er(e),e.avail_out===0))return i.last_flush=-1,Tt}return t!==Kt?Tt:i.wrap<=0?Kc:(i.wrap===2?(pe(i,e.adler&255),pe(i,e.adler>>8&255),pe(i,e.adler>>16&255),pe(i,e.adler>>24&255),pe(i,e.total_in&255),pe(i,e.total_in>>8&255),pe(i,e.total_in>>16&255),pe(i,e.total_in>>24&255)):(zi(i,e.adler>>>16),zi(i,e.adler&65535)),er(e),i.wrap>0&&(i.wrap=-i.wrap),i.pending!==0?Tt:Kc)}function Tw(e){var t;return!e||!e.state?lt:(t=e.state.status,t!==gn&&t!==Fs&&t!==pn&&t!==mn&&t!==_n&&t!==br&&t!==$i?Jt(e,lt):(e.state=null,t===br?Jt(e,Jb):Tt))}function Cw(e,t){var r=t.length,i,a,n,o,s,l,u,f;if(!e||!e.state||(i=e.state,o=i.wrap,o===2||o===1&&i.status!==gn||i.lookahead))return lt;for(o===1&&(e.adler=Xc(e.adler,t,r,0)),i.wrap=0,r>=i.w_size&&(o===0&&(Qt(i.head),i.strstart=0,i.block_start=0,i.insert=0),f=new Ye.Buf8(i.w_size),Ye.arraySet(f,t,r-i.w_size,i.w_size,0),t=f,r=i.w_size),s=e.avail_in,l=e.next_in,u=e.input,e.avail_in=r,e.next_in=0,e.input=t,xr(i);i.lookahead>=de;){a=i.strstart,n=i.lookahead-(de-1);do i.ins_h=(i.ins_h<=252?6:tr>=248?5:tr>=240?4:tr>=224?3:tr>=192?2:1;Ui[254]=Ui[254]=1,yr.string2buf=function(e){var t,r,i,a,n,o=e.length,s=0;for(a=0;a>>6,t[n++]=128|r&63):r<65536?(t[n++]=224|r>>>12,t[n++]=128|r>>>6&63,t[n++]=128|r&63):(t[n++]=240|r>>>18,t[n++]=128|r>>>12&63,t[n++]=128|r>>>6&63,t[n++]=128|r&63);return t};function av(e,t){if(t<65534&&(e.subarray&&iv||!e.subarray&&rv))return String.fromCharCode.apply(null,bn.shrinkBuf(e,t));for(var r="",i=0;i4){s[i++]=65533,r+=n-1;continue}for(a&=n===2?31:n===3?15:7;n>1&&r1){s[i++]=65533;continue}a<65536?s[i++]=a:(a-=65536,s[i++]=55296|a>>10&1023,s[i++]=56320|a&1023)}return av(s,i)},yr.utf8border=function(e,t){var r;for(t=t||e.length,t>e.length&&(t=e.length),r=t-1;r>=0&&(e[r]&192)==128;)r--;return r<0||r===0?t:r+Ui[e[r]]>t?r:t};function Ow(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var nv=Ow,Hi=St,Wi=Pt,Us=yr,Hs=Ds,Aw=nv,ov=Object.prototype.toString,Iw=0,Ws=4,Jr=0,sv=1,lv=2,kw=-1,Mw=0,Rw=8;function Sr(e){if(!(this instanceof Sr))return new Sr(e);this.options=Wi.assign({level:kw,method:Rw,chunkSize:16384,windowBits:15,memLevel:8,strategy:Mw,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Aw,this.strm.avail_out=0;var r=Hi.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(r!==Jr)throw new Error(Hs[r]);if(t.header&&Hi.deflateSetHeader(this.strm,t.header),t.dictionary){var i;if(typeof t.dictionary=="string"?i=Us.string2buf(t.dictionary):ov.call(t.dictionary)==="[object ArrayBuffer]"?i=new Uint8Array(t.dictionary):i=t.dictionary,r=Hi.deflateSetDictionary(this.strm,i),r!==Jr)throw new Error(Hs[r]);this._dict_set=!0}}Sr.prototype.push=function(e,t){var r=this.strm,i=this.options.chunkSize,a,n;if(this.ended)return!1;n=t===~~t?t:t===!0?Ws:Iw,typeof e=="string"?r.input=Us.string2buf(e):ov.call(e)==="[object ArrayBuffer]"?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new Wi.Buf8(i),r.next_out=0,r.avail_out=i),a=Hi.deflate(r,n),a!==sv&&a!==Jr)return this.onEnd(a),this.ended=!0,!1;(r.avail_out===0||r.avail_in===0&&(n===Ws||n===lv))&&(this.options.to==="string"?this.onData(Us.buf2binstring(Wi.shrinkBuf(r.output,r.next_out))):this.onData(Wi.shrinkBuf(r.output,r.next_out)))}while((r.avail_in>0||r.avail_out===0)&&a!==sv);return n===Ws?(a=Hi.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===Jr):(n===lv&&(this.onEnd(Jr),r.avail_out=0),!0)},Sr.prototype.onData=function(e){this.chunks.push(e)},Sr.prototype.onEnd=function(e){e===Jr&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Wi.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function Vs(e,t){var r=new Sr(t);if(r.push(e,!0),r.err)throw r.msg||Hs[r.err];return r.result}function Lw(e,t){return t=t||{},t.raw=!0,Vs(e,t)}function Pw(e,t){return t=t||{},t.gzip=!0,Vs(e,t)}Mi.Deflate=Sr,Mi.deflate=Vs,Mi.deflateRaw=Lw,Mi.gzip=Pw;var Vi={},ht={},wn=30,Nw=12,Dw=function(t,r){var i,a,n,o,s,l,u,f,v,p,d,_,b,x,m,g,c,h,w,y,C,E,O,N,R;i=t.state,a=t.next_in,N=t.input,n=a+(t.avail_in-5),o=t.next_out,R=t.output,s=o-(r-t.avail_out),l=o+(t.avail_out-257),u=i.dmax,f=i.wsize,v=i.whave,p=i.wnext,d=i.window,_=i.hold,b=i.bits,x=i.lencode,m=i.distcode,g=(1<>>24,_>>>=w,b-=w,w=h>>>16&255,w===0)R[o++]=h&65535;else if(w&16){y=h&65535,w&=15,w&&(b>>=w,b-=w),b<15&&(_+=N[a++]<>>24,_>>>=w,b-=w,w=h>>>16&255,w&16){if(C=h&65535,w&=15,bu){t.msg="invalid distance too far back",i.mode=wn;break e}if(_>>>=w,b-=w,w=o-s,C>w){if(w=C-w,w>v&&i.sane){t.msg="invalid distance too far back",i.mode=wn;break e}if(E=0,O=d,p===0){if(E+=f-w,w2;)R[o++]=O[E++],R[o++]=O[E++],R[o++]=O[E++],y-=3;y&&(R[o++]=O[E++],y>1&&(R[o++]=O[E++]))}else{E=o-C;do R[o++]=R[E++],R[o++]=R[E++],R[o++]=R[E++],y-=3;while(y>2);y&&(R[o++]=R[E++],y>1&&(R[o++]=R[E++]))}}else if((w&64)==0){h=m[(h&65535)+(_&(1<>3,a-=y,b-=y<<3,_&=(1<=1&&Y[d]===0;d--);if(_>d&&(_=d),d===0)return n[o++]=1<<24|64<<16|0,n[o++]=1<<24|64<<16|0,l.bits=1,0;for(p=1;p0&&(t===vv||d!==1))return-1;for(ue[1]=0,f=1;ffv||t===dv&&g>cv)return 1;for(;;){J=f-x,s[v]R?(te=M[B+s[v]],W=O[N+s[v]]):(te=32+64,W=0),h=1<>x)+w]=J<<24|te<<16|W|0;while(w!==0);for(h=1<>=1;if(h!==0?(c&=h-1,c+=h):c=0,v++,--Y[f]==0){if(f===d)break;f=r[i+s[v]]}if(f>_&&(c&C)!==y){for(x===0&&(x=_),E+=p,b=f-x,m=1<fv||t===dv&&g>cv)return 1;y=c&C,n[y]=_<<24|b<<16|E-o|0}}return c!==0&&(n[E+c]=f-x<<24|64<<16|0),l.bits=_,0},tt=Pt,Ys=Yc,Ot=qc,Hw=Dw,ji=Uw,Ww=0,hv=1,gv=2,pv=4,Vw=5,xn=6,Er=0,jw=1,Yw=2,ut=-2,mv=-3,_v=-4,qw=-5,bv=8,wv=1,xv=2,yv=3,Sv=4,Ev=5,Tv=6,Cv=7,Ov=8,Av=9,Iv=10,yn=11,Dt=12,qs=13,kv=14,Xs=15,Mv=16,Rv=17,Lv=18,Pv=19,Sn=20,En=21,Nv=22,Dv=23,Bv=24,$v=25,Fv=26,Zs=27,zv=28,Uv=29,Ee=30,Hv=31,Xw=32,Zw=852,Kw=592,Gw=15,Jw=Gw;function Wv(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function Qw(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new tt.Buf16(320),this.work=new tt.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Vv(e){var t;return!e||!e.state?ut:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=wv,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new tt.Buf32(Zw),t.distcode=t.distdyn=new tt.Buf32(Kw),t.sane=1,t.back=-1,Er)}function jv(e){var t;return!e||!e.state?ut:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,Vv(e))}function Yv(e,t){var r,i;return!e||!e.state||(i=e.state,t<0?(r=0,t=-t):(r=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?ut:(i.window!==null&&i.wbits!==t&&(i.window=null),i.wrap=r,i.wbits=t,jv(e))}function qv(e,t){var r,i;return e?(i=new Qw,e.state=i,i.window=null,r=Yv(e,t),r!==Er&&(e.state=null),r):ut}function e1(e){return qv(e,Jw)}var Xv=!0,Ks,Gs;function t1(e){if(Xv){var t;for(Ks=new tt.Buf32(512),Gs=new tt.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(ji(hv,e.lens,0,288,Ks,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;ji(gv,e.lens,0,32,Gs,0,e.work,{bits:5}),Xv=!1}e.lencode=Ks,e.lenbits=9,e.distcode=Gs,e.distbits=5}function Zv(e,t,r,i){var a,n=e.state;return n.window===null&&(n.wsize=1<=n.wsize?(tt.arraySet(n.window,t,r-n.wsize,n.wsize,0),n.wnext=0,n.whave=n.wsize):(a=n.wsize-n.wnext,a>i&&(a=i),tt.arraySet(n.window,t,r-i,a,n.wnext),i-=a,i?(tt.arraySet(n.window,t,r-i,i,0),n.wnext=i,n.whave=n.wsize):(n.wnext+=a,n.wnext===n.wsize&&(n.wnext=0),n.whave>>8&255,r.check=Ot(r.check,O,2,0),u=0,f=0,r.mode=xv;break}if(r.flags=0,r.head&&(r.head.done=!1),!(r.wrap&1)||(((u&255)<<8)+(u>>8))%31){e.msg="incorrect header check",r.mode=Ee;break}if((u&15)!==bv){e.msg="unknown compression method",r.mode=Ee;break}if(u>>>=4,f-=4,C=(u&15)+8,r.wbits===0)r.wbits=C;else if(C>r.wbits){e.msg="invalid window size",r.mode=Ee;break}r.dmax=1<>8&1),r.flags&512&&(O[0]=u&255,O[1]=u>>>8&255,r.check=Ot(r.check,O,2,0)),u=0,f=0,r.mode=yv;case yv:for(;f<32;){if(s===0)break e;s--,u+=i[n++]<>>8&255,O[2]=u>>>16&255,O[3]=u>>>24&255,r.check=Ot(r.check,O,4,0)),u=0,f=0,r.mode=Sv;case Sv:for(;f<16;){if(s===0)break e;s--,u+=i[n++]<>8),r.flags&512&&(O[0]=u&255,O[1]=u>>>8&255,r.check=Ot(r.check,O,2,0)),u=0,f=0,r.mode=Ev;case Ev:if(r.flags&1024){for(;f<16;){if(s===0)break e;s--,u+=i[n++]<>>8&255,r.check=Ot(r.check,O,2,0)),u=0,f=0}else r.head&&(r.head.extra=null);r.mode=Tv;case Tv:if(r.flags&1024&&(d=r.length,d>s&&(d=s),d&&(r.head&&(C=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),tt.arraySet(r.head.extra,i,n,d,C)),r.flags&512&&(r.check=Ot(r.check,i,d,n)),s-=d,n+=d,r.length-=d),r.length))break e;r.length=0,r.mode=Cv;case Cv:if(r.flags&2048){if(s===0)break e;d=0;do C=i[n+d++],r.head&&C&&r.length<65536&&(r.head.name+=String.fromCharCode(C));while(C&&d>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=Dt;break;case Iv:for(;f<32;){if(s===0)break e;s--,u+=i[n++]<>>=f&7,f-=f&7,r.mode=Zs;break}for(;f<3;){if(s===0)break e;s--,u+=i[n++]<>>=1,f-=1,u&3){case 0:r.mode=kv;break;case 1:if(t1(r),r.mode=Sn,t===xn){u>>>=2,f-=2;break e}break;case 2:r.mode=Rv;break;case 3:e.msg="invalid block type",r.mode=Ee}u>>>=2,f-=2;break;case kv:for(u>>>=f&7,f-=f&7;f<32;){if(s===0)break e;s--,u+=i[n++]<>>16^65535)){e.msg="invalid stored block lengths",r.mode=Ee;break}if(r.length=u&65535,u=0,f=0,r.mode=Xs,t===xn)break e;case Xs:r.mode=Mv;case Mv:if(d=r.length,d){if(d>s&&(d=s),d>l&&(d=l),d===0)break e;tt.arraySet(a,i,n,d,o),s-=d,n+=d,l-=d,o+=d,r.length-=d;break}r.mode=Dt;break;case Rv:for(;f<14;){if(s===0)break e;s--,u+=i[n++]<>>=5,f-=5,r.ndist=(u&31)+1,u>>>=5,f-=5,r.ncode=(u&15)+4,u>>>=4,f-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=Ee;break}r.have=0,r.mode=Lv;case Lv:for(;r.have>>=3,f-=3}for(;r.have<19;)r.lens[Y[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,N={bits:r.lenbits},E=ji(Ww,r.lens,0,19,r.lencode,0,r.work,N),r.lenbits=N.bits,E){e.msg="invalid code lengths set",r.mode=Ee;break}r.have=0,r.mode=Pv;case Pv:for(;r.have>>24,g=x>>>16&255,c=x&65535,!(m<=f);){if(s===0)break e;s--,u+=i[n++]<>>=m,f-=m,r.lens[r.have++]=c;else{if(c===16){for(R=m+2;f>>=m,f-=m,r.have===0){e.msg="invalid bit length repeat",r.mode=Ee;break}C=r.lens[r.have-1],d=3+(u&3),u>>>=2,f-=2}else if(c===17){for(R=m+3;f>>=m,f-=m,C=0,d=3+(u&7),u>>>=3,f-=3}else{for(R=m+7;f>>=m,f-=m,C=0,d=11+(u&127),u>>>=7,f-=7}if(r.have+d>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=Ee;break}for(;d--;)r.lens[r.have++]=C}}if(r.mode===Ee)break;if(r.lens[256]===0){e.msg="invalid code -- missing end-of-block",r.mode=Ee;break}if(r.lenbits=9,N={bits:r.lenbits},E=ji(hv,r.lens,0,r.nlen,r.lencode,0,r.work,N),r.lenbits=N.bits,E){e.msg="invalid literal/lengths set",r.mode=Ee;break}if(r.distbits=6,r.distcode=r.distdyn,N={bits:r.distbits},E=ji(gv,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,N),r.distbits=N.bits,E){e.msg="invalid distances set",r.mode=Ee;break}if(r.mode=Sn,t===xn)break e;case Sn:r.mode=En;case En:if(s>=6&&l>=258){e.next_out=o,e.avail_out=l,e.next_in=n,e.avail_in=s,r.hold=u,r.bits=f,Hw(e,p),o=e.next_out,a=e.output,l=e.avail_out,n=e.next_in,i=e.input,s=e.avail_in,u=r.hold,f=r.bits,r.mode===Dt&&(r.back=-1);break}for(r.back=0;x=r.lencode[u&(1<>>24,g=x>>>16&255,c=x&65535,!(m<=f);){if(s===0)break e;s--,u+=i[n++]<>h)],m=x>>>24,g=x>>>16&255,c=x&65535,!(h+m<=f);){if(s===0)break e;s--,u+=i[n++]<>>=h,f-=h,r.back+=h}if(u>>>=m,f-=m,r.back+=m,r.length=c,g===0){r.mode=Fv;break}if(g&32){r.back=-1,r.mode=Dt;break}if(g&64){e.msg="invalid literal/length code",r.mode=Ee;break}r.extra=g&15,r.mode=Nv;case Nv:if(r.extra){for(R=r.extra;f>>=r.extra,f-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=Dv;case Dv:for(;x=r.distcode[u&(1<>>24,g=x>>>16&255,c=x&65535,!(m<=f);){if(s===0)break e;s--,u+=i[n++]<>h)],m=x>>>24,g=x>>>16&255,c=x&65535,!(h+m<=f);){if(s===0)break e;s--,u+=i[n++]<>>=h,f-=h,r.back+=h}if(u>>>=m,f-=m,r.back+=m,g&64){e.msg="invalid distance code",r.mode=Ee;break}r.offset=c,r.extra=g&15,r.mode=Bv;case Bv:if(r.extra){for(R=r.extra;f>>=r.extra,f-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=Ee;break}r.mode=$v;case $v:if(l===0)break e;if(d=p-l,r.offset>d){if(d=r.offset-d,d>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=Ee;break}d>r.wnext?(d-=r.wnext,_=r.wsize-d):_=r.wnext-d,d>r.length&&(d=r.length),b=r.window}else b=a,_=o-r.offset,d=r.length;d>l&&(d=l),l-=d,r.length-=d;do a[o++]=b[_++];while(--d);r.length===0&&(r.mode=En);break;case Fv:if(l===0)break e;a[o++]=r.length,l--,r.mode=En;break;case Zs:if(r.wrap){for(;f<32;){if(s===0)break e;s--,u|=i[n++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(e&&e.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15)==0&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l1,this.strm.avail_out=0;var r=ei.inflateInit2(this.strm,t.windowBits);if(r!==Me.Z_OK)throw new Error(Js[r]);if(this.header=new u1,ei.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=Tn.string2buf(t.dictionary):Gv.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(r=ei.inflateSetDictionary(this.strm,t.dictionary),r!==Me.Z_OK)))throw new Error(Js[r])}Tr.prototype.push=function(e,t){var r=this.strm,i=this.options.chunkSize,a=this.options.dictionary,n,o,s,l,u,f=!1;if(this.ended)return!1;o=t===~~t?t:t===!0?Me.Z_FINISH:Me.Z_NO_FLUSH,typeof e=="string"?r.input=Tn.binstring2buf(e):Gv.call(e)==="[object ArrayBuffer]"?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new Yi.Buf8(i),r.next_out=0,r.avail_out=i),n=ei.inflate(r,Me.Z_NO_FLUSH),n===Me.Z_NEED_DICT&&a&&(n=ei.inflateSetDictionary(this.strm,a)),n===Me.Z_BUF_ERROR&&f===!0&&(n=Me.Z_OK,f=!1),n!==Me.Z_STREAM_END&&n!==Me.Z_OK)return this.onEnd(n),this.ended=!0,!1;r.next_out&&(r.avail_out===0||n===Me.Z_STREAM_END||r.avail_in===0&&(o===Me.Z_FINISH||o===Me.Z_SYNC_FLUSH))&&(this.options.to==="string"?(s=Tn.utf8border(r.output,r.next_out),l=r.next_out-s,u=Tn.buf2string(r.output,s),r.next_out=l,r.avail_out=i-l,l&&Yi.arraySet(r.output,r.output,s,l,0),this.onData(u)):this.onData(Yi.shrinkBuf(r.output,r.next_out))),r.avail_in===0&&r.avail_out===0&&(f=!0)}while((r.avail_in>0||r.avail_out===0)&&n!==Me.Z_STREAM_END);return n===Me.Z_STREAM_END&&(o=Me.Z_FINISH),o===Me.Z_FINISH?(n=ei.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===Me.Z_OK):(o===Me.Z_SYNC_FLUSH&&(this.onEnd(Me.Z_OK),r.avail_out=0),!0)},Tr.prototype.onData=function(e){this.chunks.push(e)},Tr.prototype.onEnd=function(e){e===Me.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Yi.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function Qs(e,t){var r=new Tr(t);if(r.push(e,!0),r.err)throw r.msg||Js[r.err];return r.result}function f1(e,t){return t=t||{},t.raw=!0,Qs(e,t)}Vi.Inflate=Tr,Vi.inflate=Qs,Vi.inflateRaw=f1,Vi.ungzip=Qs;var c1=Pt.assign,v1=Mi,d1=Vi,h1=Kv,Jv={};c1(Jv,v1,d1,h1);var Qv=Jv;function g1(e,t,r){}function p1(e){return Promise.resolve(e)}var m1="upx2px",_1=1e-4,b1=750,ed=!1,el=0,td=0;function w1(){var{platform:e,pixelRatio:t,windowWidth:r}=yc();el=r,td=t,ed=e==="ios"}function rd(e,t){var r=Number(e);return isNaN(r)?t:r}var id=yb(m1,(e,t)=>{if(el===0&&w1(),e=Number(e),e===0)return 0;var r=t||el;{var i=__uniConfig.globalStyle||{},a=rd(i.rpxCalcMaxDeviceWidth,960),n=rd(i.rpxCalcBaseDeviceWidth,375);r=r<=a?r:n}var o=e/b1*r;return o<0&&(o=-o),o=Math.floor(o+_1),o===0&&(td===1||!ed?o=1:o=.5),e<0?-o:o}),x1=[{name:"id",type:String,required:!0}];x1.concat({name:"componentInstance",type:Object});var ad={};ad.f={}.propertyIsEnumerable;var y1=si,S1=so,E1=da,T1=ad.f,C1=function(e){return function(t){for(var r=E1(t),i=S1(r),a=i.length,n=0,o=[],s;a>n;)s=i[n++],(!y1||T1.call(r,s))&&o.push(e?[s,r[s]]:r[s]);return o}},nd=no,O1=C1(!1);nd(nd.S,"Object",{values:function(t){return O1(t)}});var A1="setPageMeta",I1="loadFontFace",k1="pageScrollTo",M1=function(){if(typeof window!="object")return;if("IntersectionObserver"in window&&"IntersectionObserverEntry"in window&&"intersectionRatio"in window.IntersectionObserverEntry.prototype){"isIntersecting"in window.IntersectionObserverEntry.prototype||Object.defineProperty(window.IntersectionObserverEntry.prototype,"isIntersecting",{get:function(){return this.intersectionRatio>0}});return}function e(c){try{return c.defaultView&&c.defaultView.frameElement||null}catch(h){return null}}var t=function(c){for(var h=c,w=e(h);w;)h=w.ownerDocument,w=e(h);return h}(window.document),r=[],i=null,a=null;function n(c){this.time=c.time,this.target=c.target,this.rootBounds=_(c.rootBounds),this.boundingClientRect=_(c.boundingClientRect),this.intersectionRect=_(c.intersectionRect||d()),this.isIntersecting=!!c.intersectionRect;var h=this.boundingClientRect,w=h.width*h.height,y=this.intersectionRect,C=y.width*y.height;w?this.intersectionRatio=Number((C/w).toFixed(4)):this.intersectionRatio=this.isIntersecting?1:0}function o(c,h){var w=h||{};if(typeof c!="function")throw new Error("callback must be a function");if(w.root&&w.root.nodeType!=1&&w.root.nodeType!=9)throw new Error("root must be a Document or Element");this._checkForIntersections=l(this._checkForIntersections.bind(this),this.THROTTLE_TIMEOUT),this._callback=c,this._observationTargets=[],this._queuedEntries=[],this._rootMarginValues=this._parseRootMargin(w.rootMargin),this.thresholds=this._initThresholds(w.threshold),this.root=w.root||null,this.rootMargin=this._rootMarginValues.map(function(y){return y.value+y.unit}).join(" "),this._monitoringDocuments=[],this._monitoringUnsubscribes=[]}o.prototype.THROTTLE_TIMEOUT=100,o.prototype.POLL_INTERVAL=null,o.prototype.USE_MUTATION_OBSERVER=!0,o._setupCrossOriginUpdater=function(){return i||(i=function(c,h){!c||!h?a=d():a=b(c,h),r.forEach(function(w){w._checkForIntersections()})}),i},o._resetCrossOriginUpdater=function(){i=null,a=null},o.prototype.observe=function(c){var h=this._observationTargets.some(function(w){return w.element==c});if(!h){if(!(c&&c.nodeType==1))throw new Error("target must be an Element");this._registerInstance(),this._observationTargets.push({element:c,entry:null}),this._monitorIntersections(c.ownerDocument),this._checkForIntersections()}},o.prototype.unobserve=function(c){this._observationTargets=this._observationTargets.filter(function(h){return h.element!=c}),this._unmonitorIntersections(c.ownerDocument),this._observationTargets.length==0&&this._unregisterInstance()},o.prototype.disconnect=function(){this._observationTargets=[],this._unmonitorAllIntersections(),this._unregisterInstance()},o.prototype.takeRecords=function(){var c=this._queuedEntries.slice();return this._queuedEntries=[],c},o.prototype._initThresholds=function(c){var h=c||[0];return Array.isArray(h)||(h=[h]),h.sort().filter(function(w,y,C){if(typeof w!="number"||isNaN(w)||w<0||w>1)throw new Error("threshold must be a number between 0 and 1 inclusively");return w!==C[y-1]})},o.prototype._parseRootMargin=function(c){var h=c||"0px",w=h.split(/\s+/).map(function(y){var C=/^(-?\d*\.?\d+)(px|%)$/.exec(y);if(!C)throw new Error("rootMargin must be specified in pixels or percent");return{value:parseFloat(C[1]),unit:C[2]}});return w[1]=w[1]||w[0],w[2]=w[2]||w[0],w[3]=w[3]||w[1],w},o.prototype._monitorIntersections=function(c){var h=c.defaultView;if(!!h&&this._monitoringDocuments.indexOf(c)==-1){var w=this._checkForIntersections,y=null,C=null;this.POLL_INTERVAL?y=h.setInterval(w,this.POLL_INTERVAL):(u(h,"resize",w,!0),u(c,"scroll",w,!0),this.USE_MUTATION_OBSERVER&&"MutationObserver"in h&&(C=new h.MutationObserver(w),C.observe(c,{attributes:!0,childList:!0,characterData:!0,subtree:!0}))),this._monitoringDocuments.push(c),this._monitoringUnsubscribes.push(function(){var N=c.defaultView;N&&(y&&N.clearInterval(y),f(N,"resize",w,!0)),f(c,"scroll",w,!0),C&&C.disconnect()});var E=this.root&&(this.root.ownerDocument||this.root)||t;if(c!=E){var O=e(c);O&&this._monitorIntersections(O.ownerDocument)}}},o.prototype._unmonitorIntersections=function(c){var h=this._monitoringDocuments.indexOf(c);if(h!=-1){var w=this.root&&(this.root.ownerDocument||this.root)||t,y=this._observationTargets.some(function(O){var N=O.element.ownerDocument;if(N==c)return!0;for(;N&&N!=w;){var R=e(N);if(N=R&&R.ownerDocument,N==c)return!0}return!1});if(!y){var C=this._monitoringUnsubscribes[h];if(this._monitoringDocuments.splice(h,1),this._monitoringUnsubscribes.splice(h,1),C(),c!=w){var E=e(c);E&&this._unmonitorIntersections(E.ownerDocument)}}}},o.prototype._unmonitorAllIntersections=function(){var c=this._monitoringUnsubscribes.slice(0);this._monitoringDocuments.length=0,this._monitoringUnsubscribes.length=0;for(var h=0;h=0&&N>=0&&{top:w,bottom:y,left:C,right:E,width:O,height:N}||null}function p(c){var h;try{h=c.getBoundingClientRect()}catch(w){}return h?(h.width&&h.height||(h={top:h.top,right:h.right,bottom:h.bottom,left:h.left,width:h.right-h.left,height:h.bottom-h.top}),h):d()}function d(){return{top:0,bottom:0,left:0,right:0,width:0,height:0}}function _(c){return!c||"x"in c?c:{top:c.top,y:c.top,bottom:c.bottom,left:c.left,x:c.left,right:c.right,width:c.width,height:c.height}}function b(c,h){var w=h.top-c.top,y=h.left-c.left;return{top:w,left:y,height:h.height,width:h.width,bottom:w+h.height,right:y+h.width}}function x(c,h){for(var w=h;w;){if(w==c)return!0;w=m(w)}return!1}function m(c){var h=c.parentNode;return c.nodeType==9&&c!=t?e(c):(h&&h.assignedSlot&&(h=h.assignedSlot.parentNode),h&&h.nodeType==11&&h.host?h.host:h)}function g(c){return c&&c.nodeType===9}window.IntersectionObserver=o,window.IntersectionObserverEntry=n};function tl(e){var{bottom:t,height:r,left:i,right:a,top:n,width:o}=e||{};return{bottom:t,height:r,left:i,right:a,top:n,width:o}}function R1(e){var{intersectionRatio:t,boundingClientRect:{height:r,width:i},intersectionRect:{height:a,width:n}}=e;return t!==0?t:a===r?n/i:a/r}function L1(e,t,r){M1();var i=t.relativeToSelector?e.querySelector(t.relativeToSelector):null,a=new IntersectionObserver(l=>{l.forEach(u=>{r({intersectionRatio:R1(u),intersectionRect:tl(u.intersectionRect),boundingClientRect:tl(u.boundingClientRect),relativeRect:tl(u.rootBounds),time:Date.now(),dataset:To(u.target),id:u.target.id})})},{root:i,rootMargin:t.rootMargin,threshold:t.thresholds});if(t.observeAll){a.USE_MUTATION_OBSERVER=!0;for(var n=e.querySelectorAll(t.selector),o=0;o{var i=450,a=44;clearTimeout(t),e&&Math.abs(r.pageX-e.pageX)<=a&&Math.abs(r.pageY-e.pageY)<=a&&r.timeStamp-e.timeStamp<=i&&r.preventDefault(),e=r,t=setTimeout(()=>{e=null},i)})}}function U1(e){if(!e.length)return r=>r;var t=function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof r=="number")return e[r];var a={};return r.forEach(n=>{var[o,s]=n;i?a[t(o)]=t(s):a[t(o)]=s}),a};return t}function H1(e,t){if(!!t)return t.a&&(t.a=e(t.a)),t.e&&(t.e=e(t.e,!1)),t.w&&(t.w=W1(t.w,e)),t.s&&(t.s=e(t.s)),t.t&&(t.t=e(t.t)),t}function W1(e,t){var r={};return e.forEach(i=>{var[a,[n,o]]=i;r[t(a)]=[t(n),o]}),r}function V1(e,t){return e.priority=t,e}var rl=new Set,j1=1,il=2,od=3,sd=4;function rr(e,t){rl.add(V1(e,t))}function Y1(){try{[...rl].sort((e,t)=>e.priority-t.priority).forEach(e=>e())}finally{rl.clear()}}function ld(e,t){var r=window["__"+Op],i=r&&r[e];if(i)return i;if(t&&t.__renderjsInstances)return t.__renderjsInstances[e]}var q1=Cu.length;function X1(e,t,r){var[i,a,n,o]=nl(t),s=al(e,i);if(se(r)||se(o)){var[l,u]=n.split(".");return ol(s,a,l,u,r||o)}return G1(s,a,n)}function Z1(e,t,r){var[i,a,n]=nl(t),[o,s]=n.split("."),l=al(e,i);return ol(l,a,o,s,[Q1(r,e),fn(ki(l))])}function al(e,t){if(e.__ownerId===t)return e;for(var r=e.parentElement;r;){if(r.__ownerId===t)return r;r=r.parentElement}return e}function nl(e){return JSON.parse(e.substr(q1))}function K1(e,t,r,i){var[a,n,o]=nl(e),s=al(t,a),[l,u]=o.split(".");return ol(s,n,l,u,[r,i,fn(ki(s)),fn(ki(t))])}function ol(e,t,r,i,a){var n=ld(t,e);if(!n)return console.error(Eo("wxs","module "+r+" not found"));var o=n[i];return ne(o)?o.apply(n,a):console.error(r+"."+i+" is not a function")}function G1(e,t,r){var i=ld(t,e);return i?Lu(i,r.substr(r.indexOf(".")+1)):console.error(Eo("wxs","module "+r+" not found"))}function J1(e,t,r){var i=r;return a=>{try{K1(t,e.$,a,i)}catch(n){console.error(n)}i=a}}function Q1(e,t){var r=ki(t);return Object.defineProperty(e,"instance",{get(){return fn(r)}}),e}function ud(e,t){Object.keys(t).forEach(r=>{tx(e,t[r])})}function ex(e){var{__renderjsInstances:t}=e.$;!t||Object.keys(t).forEach(r=>{t[r].$.appContext.app.unmount()})}function tx(e,t){var r=rx(t);if(!!r){var i=e.$;(i.__renderjsInstances||(i.__renderjsInstances={}))[t]=ix(r)}}function rx(e){var t=window["__"+Ap],r=t&&t[e];return r||console.error(Eo("renderjs",e+" not found"))}function ix(e){return e=e.default||e,e.render=()=>{},uc(e).mount(document.createElement("div"))}class ti{constructor(t,r,i,a){this.isMounted=!1,this.isUnmounted=!1,this.$hasWxsProps=!1,this.$children=[],this.id=t,this.tag=r,this.pid=i,a&&(this.$=a),this.$wxsProps=new Map;var n=this.$parent=uT(i);n&&n.appendUniChild(this)}init(t){re(t,"t")&&(this.$.textContent=t.t)}setText(t){this.$.textContent=t}insert(t,r){var i=this.$,a=at(t);r===-1?a.appendChild(i):a.insertBefore(i,at(r).$),this.isMounted=!0}remove(){this.removeUniParent();var{$:t}=this;t.parentNode.removeChild(t),this.isUnmounted=!0,yh(this.id),ex(this),this.removeUniChildren()}appendChild(t){return this.$.appendChild(t)}insertBefore(t,r){return this.$.insertBefore(t,r)}appendUniChild(t){this.$children.push(t)}removeUniChild(t){var r=this.$children.indexOf(t);r>=0&&this.$children.splice(r,1)}removeUniParent(){var{$parent:t}=this;t&&(t.removeUniChild(this),this.$parent=void 0)}removeUniChildren(){this.$children.forEach(t=>t.remove()),this.$children.length=0}setWxsProps(t){Object.keys(t).forEach(r=>{if(r.indexOf(Mo)===0){var i=r.replace(Mo,""),a=t[i],n=J1(this,t[r],a);rr(()=>n(a),sd),this.$wxsProps.set(r,n),delete t[r],delete t[i],this.$hasWxsProps=!0}})}addWxsEvents(t){Object.keys(t).forEach(r=>{var[i,a]=t[r];this.addWxsEvent(r,i,a)})}addWxsEvent(t,r,i){}wxsPropsInvoke(t,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,a=this.$hasWxsProps&&this.$wxsProps.get(Mo+t);if(a)return rr(()=>i?Vr(()=>a(r)):a(r),sd),!0}}function fd(e,t){var{__wxsAddClass:r,__wxsRemoveClass:i}=e;i&&i.length&&(t=t.split(/\s+/).filter(a=>i.indexOf(a)===-1).join(" "),i.length=0),r&&r.length&&(t=t+" "+r.join(" ")),e.className=t}function cd(e,t){var r=e.style;if(Se(t))t===""?e.removeAttribute("style"):r.cssText=pr(t,!0);else for(var i in t)sl(r,i,t[i]);var{__wxsStyle:a}=e;if(a)for(var n in a)sl(r,n,a[n])}var vd=/\s*!important$/;function sl(e,t,r){if(se(r))r.forEach(a=>sl(e,t,a));else if(r=pr(r,!0),t.startsWith("--"))e.setProperty(t,r);else{var i=ax(e,t);vd.test(r)?e.setProperty(Ke(i),r.replace(vd,""),"important"):e[i]=r}}var dd=["Webkit"],ll={};function ax(e,t){var r=ll[t];if(r)return r;var i=Ft(t);if(i!=="filter"&&i in e)return ll[t]=i;i=Oa(i);for(var a=0;a{var[n]=pc(a);n.type=$p(a.type,r),UniViewJSBridge.publishHandler(bc,[[Gp,e,n]])};return t?ws(i,_d(t)):i}function _d(e){var t=[];return e&Io.prevent&&t.push("prevent"),e&Io.self&&t.push("self"),e&Io.stop&&t.push("stop"),t}function nx(e,t,r,i){var[a,n]=Ao(t);i===-1?hd(e,a):gd(e,a)||e.addEventListener(a,e.__listeners[a]=bd(e,r,i),n)}function bd(e,t,r){var i=a=>{Z1(e,t,pc(a)[0])};return r?ws(i,_d(r)):i}var ox=Ou.length;function ul(e,t){return Se(t)&&(t.indexOf(Ou)===0?t=JSON.parse(t.substr(ox)):t.indexOf(Cu)===0&&(t=X1(e,t))),t}function Cn(e){return e.indexOf("--")===0}function fl(e,t){e._vod=e.style.display==="none"?"":e.style.display,e.style.display=t?e._vod:"none"}class wd extends ti{constructor(t,r,i,a,n){var o=arguments.length>5&&arguments[5]!==void 0?arguments[5]:[];super(t,r.tagName,i,r);this.$props=Ae({}),this.$.__id=t,this.$.__listeners=Object.create(null),this.$propNames=o,this._update=this.update.bind(this),this.init(n),this.insert(i,a)}init(t){re(t,"a")&&this.setAttrs(t.a),re(t,"s")&&this.setAttr("style",t.s),re(t,"e")&&this.addEvents(t.e),re(t,"w")&&this.addWxsEvents(t.w),super.init(t),H(this.$props,()=>{rr(this._update,j1)},{flush:"sync"}),this.update(!0)}setAttrs(t){this.setWxsProps(t),Object.keys(t).forEach(r=>{this.setAttr(r,t[r])})}addEvents(t){Object.keys(t).forEach(r=>{this.addEvent(r,t[r])})}addWxsEvent(t,r,i){nx(this.$,t,r,i)}addEvent(t,r){pd(this.$,t,r)}removeEvent(t){pd(this.$,t,-1)}setAttr(t,r){t===Iu?fd(this.$,r):t===ko?cd(this.$,r):t===ka?fl(this.$,r):t===ku?this.$.__ownerId=r:t===Mu?rr(()=>ud(this,r),od):t===Fp?this.$.innerHTML=r:t===zp?this.setText(r):this.setAttribute(t,r)}removeAttr(t){t===Iu?fd(this.$,""):t===ko?cd(this.$,""):this.removeAttribute(t)}setAttribute(t,r){r=ul(this.$,r),this.$propNames.indexOf(t)!==-1?this.$props[t]=r:Cn(t)?this.$.style.setProperty(t,r):this.wxsPropsInvoke(t,r)||this.$.setAttribute(t,r)}removeAttribute(t){this.$propNames.indexOf(t)!==-1?delete this.$props[t]:Cn(t)?this.$.style.removeProperty(t):this.$.removeAttribute(t)}update(){}}class sx extends ti{constructor(t,r,i){super(t,"#comment",r,document.createComment(""));this.insert(r,i)}}var FT="";function xd(e){return/^-?\d+[ur]px$/i.test(e)?e.replace(/(^-?\d+)[ur]px$/i,(t,r)=>"".concat(uni.upx2px(parseFloat(r)),"px")):/^-?[\d\.]+$/.test(e)?"".concat(e,"px"):e||""}function lx(e){return e.replace(/[A-Z]/g,t=>"-".concat(t.toLowerCase())).replace("webkit","-webkit")}function ux(e){var t=["matrix","matrix3d","scale","scale3d","rotate3d","skew","translate","translate3d"],r=["scaleX","scaleY","scaleZ","rotate","rotateX","rotateY","rotateZ","skewX","skewY","translateX","translateY","translateZ"],i=["opacity","background-color"],a=["width","height","left","right","top","bottom"],n=e.animates,o=e.option,s=o.transition,l={},u=[];return n.forEach(f=>{var v=f.type,p=[...f.args];if(t.concat(r).includes(v))v.startsWith("rotate")||v.startsWith("skew")?p=p.map(_=>parseFloat(_)+"deg"):v.startsWith("translate")&&(p=p.map(xd)),r.indexOf(v)>=0&&(p.length=1),u.push("".concat(v,"(").concat(p.join(","),")"));else if(i.concat(a).includes(p[0])){v=p[0];var d=p[1];l[v]=a.includes(v)?xd(d):d}}),l.transform=l.webkitTransform=u.join(" "),l.transition=l.webkitTransition=Object.keys(l).map(f=>"".concat(lx(f)," ").concat(s.duration,"ms ").concat(s.timingFunction," ").concat(s.delay,"ms")).join(","),l.transformOrigin=l.webkitTransformOrigin=o.transformOrigin,l}function yd(e){var t=e.animation;if(!t||!t.actions||!t.actions.length)return;var r=0,i=t.actions,a=t.actions.length;function n(){var o=i[r],s=o.option.transition,l=ux(o);Object.keys(l).forEach(u=>{e.$el.style[u]=l[u]}),r+=1,r{n()},0)}var On={props:["animation"],watch:{animation:{deep:!0,handler(){yd(this)}}},mounted(){yd(this)}},ge=e=>{var{props:t,mixins:r}=e;return(!t||!t.animation)&&(r||(e.mixins=[])).push(On),fx(e)},fx=e=>(e.compatConfig={MODE:3},Sm(e)),cx={hoverClass:{type:String,default:"none"},hoverStopPropagation:{type:Boolean,default:!1},hoverStartTime:{type:[Number,String],default:50},hoverStayTime:{type:[Number,String],default:400}};function cl(e){var t=U(!1),r=!1,i,a;function n(){requestAnimationFrame(()=>{clearTimeout(a),a=setTimeout(()=>{t.value=!1},parseInt(e.hoverStayTime))})}function o(u){u._hoverPropagationStopped||!e.hoverClass||e.hoverClass==="none"||e.disabled||u.touches.length>1||(e.hoverStopPropagation&&(u._hoverPropagationStopped=!0),r=!0,i=setTimeout(()=>{t.value=!0,r||n()},parseInt(e.hoverStartTime)))}function s(){r=!1,t.value&&n()}function l(){r=!1,t.value=!1,clearTimeout(i)}return{hovering:t,binding:{onTouchstartPassive:o,onTouchend:s,onTouchcancel:l}}}function qi(e,t){return Se(t)&&(t=[t]),t.reduce((r,i)=>(e[i]&&(r[i]=!0),r),Object.create(null))}function Cr(e){return e.__wwe=!0,e}function Pe(e,t){return(r,i,a)=>{e.value&&t(r,dx(r,i,e.value,a||{}))}}function vx(e){return(t,r)=>{e(t,mc(r))}}function dx(e,t,r,i){var a=Oo(r);return{type:i.type||e,timeStamp:t.timeStamp||0,target:a,currentTarget:a,detail:i}}var At=on("uf"),hx=ge({name:"Form",emits:["submit","reset"],setup(e,t){var{slots:r,emit:i}=t,a=U(null);return gx(Pe(a,i)),()=>I("uni-form",{ref:a},[I("span",null,[r.default&&r.default()])],512)}});function gx(e){var t=[];return Fe(At,{addField(r){t.push(r)},removeField(r){t.splice(t.indexOf(r),1)},submit(r){e("submit",r,{value:t.reduce((i,a)=>{if(a.submit){var[n,o]=a.submit();n&&(i[n]=o)}return i},Object.create(null))})},reset(r){t.forEach(i=>i.reset&&i.reset()),e("reset",r)}}),t}var Xi=on("ul"),px={for:{type:String,default:""}},mx=ge({name:"Label",props:px,setup(e,t){var{slots:r}=t,i=un(),a=_x(),n=Q(()=>e.for||r.default&&r.default.length),o=Cr(s=>{var l=s.target,u=/^uni-(checkbox|radio|switch)-/.test(l.className);u||(u=/^uni-(checkbox|radio|switch|button)$|^(svg|path)$/i.test(l.tagName)),!u&&(e.for?UniViewJSBridge.emit("uni-label-click-"+i+"-"+e.for,s,!0):a.length&&a[0](s,!0))});return()=>I("uni-label",{class:{"uni-label-pointer":n},onClick:o},[r.default&&r.default()],10,["onClick"])}});function _x(){var e=[];return Fe(Xi,{addHandler(t){e.push(t)},removeHandler(t){e.splice(e.indexOf(t),1)}}),e}function An(e,t){Sd(e.id,t),H(()=>e.id,(r,i)=>{Ed(i,t,!0),Sd(r,t,!0)}),Wt(()=>{Ed(e.id,t)})}function Sd(e,t,r){var i=un();r&&!e||!mt(t)||Object.keys(t).forEach(a=>{r?a.indexOf("@")!==0&&a.indexOf("uni-")!==0&&UniViewJSBridge.on("uni-".concat(a,"-").concat(i,"-").concat(e),t[a]):a.indexOf("uni-")===0?UniViewJSBridge.on(a,t[a]):e&&UniViewJSBridge.on("uni-".concat(a,"-").concat(i,"-").concat(e),t[a])})}function Ed(e,t,r){var i=un();r&&!e||!mt(t)||Object.keys(t).forEach(a=>{r?a.indexOf("@")!==0&&a.indexOf("uni-")!==0&&UniViewJSBridge.off("uni-".concat(a,"-").concat(i,"-").concat(e),t[a]):a.indexOf("uni-")===0?UniViewJSBridge.off(a,t[a]):e&&UniViewJSBridge.off("uni-".concat(a,"-").concat(i,"-").concat(e),t[a])})}var bx=ge({name:"Button",props:{id:{type:String,default:""},hoverClass:{type:String,default:"button-hover"},hoverStartTime:{type:[Number,String],default:20},hoverStayTime:{type:[Number,String],default:70},hoverStopPropagation:{type:Boolean,default:!1},disabled:{type:[Boolean,String],default:!1},formType:{type:String,default:""},openType:{type:String,default:""},loading:{type:[Boolean,String],default:!1}},setup(e,t){var{slots:r}=t,i=U(null);b0();var a=_e(At,!1),{hovering:n,binding:o}=cl(e),{t:s}=Ge(),l=Cr((f,v)=>{if(e.disabled)return f.stopImmediatePropagation();v&&i.value.click();var p=e.formType;if(p){if(!a)return;p==="submit"?a.submit(f):p==="reset"&&a.reset(f);return}e.openType==="feedback"&&wx(s("uni.button.feedback.title"),s("uni.button.feedback.send"))}),u=_e(Xi,!1);return u&&(u.addHandler(l),Ce(()=>{u.removeHandler(l)})),An(e,{"label-click":l}),()=>{var f=e.hoverClass,v=qi(e,"disabled"),p=qi(e,"loading"),d=f&&f!=="none";return I("uni-button",Qe({ref:i,onClick:l,class:d&&n.value?f:""},d&&o,v,p),[r.default&&r.default()],16,["onClick"])}}});function wx(e,t){var r=plus.webview.create("https://service.dcloud.net.cn/uniapp/feedback.html","feedback",{titleNView:{titleText:e,autoBackButton:!0,backgroundColor:"#F7F7F7",titleColor:"#007aff",buttons:[{text:t,color:"#007aff",fontSize:"16px",fontWeight:"bold",onclick:function(){r.evalJS('typeof mui !== "undefined" && mui.trigger(document.getElementById("submit"),"tap")')}}]}});r.show("slide-in-right")}var Or=ge({name:"ResizeSensor",props:{initial:{type:Boolean,default:!1}},emits:["resize"],setup(e,t){var{emit:r}=t,i=U(null),a=yx(i),n=xx(i,r,a);return Sx(i,e,n,a),()=>I("uni-resize-sensor",{ref:i,onAnimationstartOnce:n},[I("div",{onScroll:n},[I("div",null,null)],40,["onScroll"]),I("div",{onScroll:n},[I("div",null,null)],40,["onScroll"])],40,["onAnimationstartOnce"])}});function xx(e,t,r){var i=Ae({width:-1,height:-1});return H(()=>ve({},i),a=>t("resize",a)),()=>{var a=e.value;i.width=a.offsetWidth,i.height=a.offsetHeight,r()}}function yx(e){return()=>{var{firstElementChild:t,lastElementChild:r}=e.value;t.scrollLeft=1e5,t.scrollTop=1e5,r.scrollLeft=1e5,r.scrollTop=1e5}}function Sx(e,t,r,i){ts(i),Re(()=>{t.initial&&Vr(r);var a=e.value;a.offsetParent!==a.parentElement&&(a.parentElement.style.position="relative"),"AnimationEvent"in window||i()})}var be=function(){var e=document.createElement("canvas");e.height=e.width=0;var t=e.getContext("2d"),r=t.backingStorePixelRatio||t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1;return(window.devicePixelRatio||1)/r}();function Td(e){e.width=e.offsetWidth*be,e.height=e.offsetHeight*be,e.getContext("2d").__hidpi__=!0}var Cd=!1;function Ex(){if(!Cd){Cd=!0;var e=function(i,a){for(var n in i)re(i,n)&&a(i[n],n)},t={fillRect:"all",clearRect:"all",strokeRect:"all",moveTo:"all",lineTo:"all",arc:[0,1,2],arcTo:"all",bezierCurveTo:"all",isPointinPath:"all",isPointinStroke:"all",quadraticCurveTo:"all",rect:"all",translate:"all",createRadialGradient:"all",createLinearGradient:"all",setTransform:[4,5]},r=CanvasRenderingContext2D.prototype;r.drawImageByCanvas=function(i){return function(a,n,o,s,l,u,f,v,p,d){if(!this.__hidpi__)return i.apply(this,arguments);n*=be,o*=be,s*=be,l*=be,u*=be,f*=be,v=d?v*be:v,p=d?p*be:p,i.call(this,a,n,o,s,l,u,f,v,p)}}(r.drawImage),be!==1&&(e(t,function(i,a){r[a]=function(n){return function(){if(!this.__hidpi__)return n.apply(this,arguments);var o=Array.prototype.slice.call(arguments);if(i==="all")o=o.map(function(l){return l*be});else if(Array.isArray(i))for(var s=0;sEx());function Od(e){return e&&vt(e)}function In(e){return e=e.slice(0),e[3]=e[3]/255,"rgba("+e.join(",")+")"}function Ad(e,t){var r=e;return Array.from(t).map(i=>{var a=r.getBoundingClientRect();return{identifier:i.identifier,x:i.clientX-a.left,y:i.clientY-a.top}})}var Zi;function Id(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return Zi||(Zi=document.createElement("canvas")),Zi.width=e,Zi.height=t,Zi}var Cx={canvasId:{type:String,default:""},disableScroll:{type:[Boolean,String],default:!1}},Ox=ge({inheritAttrs:!1,name:"Canvas",compatConfig:{MODE:3},props:Cx,computed:{id(){return this.canvasId}},setup(e,t){var{emit:r,slots:i}=t;Tx();var a=U(null),n=U(null),o=U(!1),s=vx(r),{$attrs:l,$excludeAttrs:u,$listeners:f}=Xd({excludeListeners:!0}),{_listeners:v}=Ax(e,f,s),{_handleSubscribe:p,_resize:d}=Ix(a,o);return zn(p,Un(e.canvasId),!0),Re(()=>{d()}),()=>{var{canvasId:_,disableScroll:b}=e;return I("uni-canvas",Qe({"canvas-id":_,"disable-scroll":b},l.value,u.value,v.value),[I("canvas",{ref:a,class:"uni-canvas-canvas",width:"300",height:"150"},null,512),I("div",{style:"position: absolute;top: 0;left: 0;width: 100%;height: 100%;overflow: hidden;"},[i.default&&i.default()]),I(Or,{ref:n,onResize:d},null,8,["onResize"])],16,["canvas-id","disable-scroll"])}}});function Ax(e,t,r){var i=Q(()=>{var a=["onTouchstart","onTouchmove","onTouchend"],n=t.value,o=ve({},(()=>{var s={};for(var l in n)if(Object.prototype.hasOwnProperty.call(n,l)){var u=n[l];s[l]=u}return s})());return a.forEach(s=>{var l=o[s],u=[];l&&u.push(Cr(f=>{r(s.replace("on","").toLocaleLowerCase(),ve({},(()=>{var v={};for(var p in f)v[p]=f[p];return v})(),{touches:Ad(f.currentTarget,f.touches),changedTouches:Ad(f.currentTarget,f.changedTouches)}))})),e.disableScroll&&s==="onTouchmove"&&u.push(Y_),o[s]=u}),o});return{_listeners:i}}function Ix(e,t){var r=[],i={};function a(d){var _=e.value,b=!d||_.width!==Math.floor(d.width*be)||_.height!==Math.floor(d.height*be);if(!!b)if(_.width>0&&_.height>0){var x=_.getContext("2d"),m=x.getImageData(0,0,_.width,_.height);Td(_),x.putImageData(m,0,0)}else Td(_)}function n(d,_){var{actions:b,reserve:x}=d;if(!!b){if(t.value){r.push([b,x]);return}var m=e.value,g=m.getContext("2d");x||(g.fillStyle="#000000",g.strokeStyle="#000000",g.shadowColor="#000000",g.shadowBlur=0,g.shadowOffsetX=0,g.shadowOffsetY=0,g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,m.width,m.height)),o(b);for(var c=function(y){var C=b[y],E=C.method,O=C.data,N=O[0];if(/^set/.test(E)&&E!=="setTransform"){var R=E[3].toLowerCase()+E.slice(4),Y;if(R==="fillStyle"||R==="strokeStyle"){if(N==="normal")Y=In(O[1]);else if(N==="linear"){var ue=g.createLinearGradient(...O[1]);O[2].forEach(function(K){var ie=K[0],le=In(K[1]);ue.addColorStop(ie,le)}),Y=ue}else if(N==="radial"){var M=O[1],B=M[0],J=M[1],te=M[2],W=g.createRadialGradient(B,J,0,B,J,te);O[2].forEach(function(K){var ie=K[0],le=In(K[1]);W.addColorStop(ie,le)}),Y=W}else if(N==="pattern"){var ee=s(O[1],b.slice(y+1),_,function(K){K&&(g[R]=g.createPattern(K,O[2]))});return ee?"continue":"break"}g[R]=Y}else if(R==="globalAlpha")g[R]=Number(N)/255;else if(R==="shadow"){var ae=["shadowOffsetX","shadowOffsetY","shadowBlur","shadowColor"];O.forEach(function(K,ie){g[ae[ie]]=ae[ie]==="shadowColor"?In(K):K})}else if(R==="fontSize"){var ye=g.__font__||g.font;g.__font__=g.font=ye.replace(/\d+\.?\d*px/,N+"px")}else R==="lineDash"?(g.setLineDash(N),g.lineDashOffset=O[1]||0):R==="textBaseline"?(N==="normal"&&(O[0]="alphabetic"),g[R]=N):R==="font"?g.__font__=g.font=N:g[R]=N}else if(E==="fillPath"||E==="strokePath")E=E.replace(/Path/,""),g.beginPath(),O.forEach(function(K){g[K.method].apply(g,K.data)}),g[E]();else if(E==="fillText")g.fillText.apply(g,O);else if(E==="drawImage"){var oe=function(){var K=[...O],ie=K[0],le=K.slice(1);if(i=i||{},s(ie,b.slice(y+1),_,function(Ie){Ie&&g.drawImage.apply(g,[Ie].concat([...le.slice(4,8)],[...le.slice(0,4)]))}))return"break"}();if(oe==="break")return"break"}else E==="clip"?(O.forEach(function(K){g[K.method].apply(g,K.data)}),g.clip()):g[E].apply(g,O)},h=0;h{c.src=h}).catch(()=>{c.src=m})}})}function s(d,_,b,x){var m=i[d];return m.ready?(x(m),!0):(r.unshift([_,!0]),t.value=!0,m.onload=function(){m.ready=!0,x(m),t.value=!1;var g=r.slice(0);r=[];for(var c=g.shift();c;)n({actions:c[0],reserve:c[1]},b),c=g.shift()},!1)}function l(d,_){var{x:b=0,y:x=0,width:m,height:g,destWidth:c,destHeight:h,hidpi:w=!0,dataType:y,quality:C=1,type:E="png"}=d,O=e.value,N,R=O.offsetWidth-b;m=m?Math.min(m,R):R;var Y=O.offsetHeight-x;g=g?Math.min(g,Y):Y,w?(c=m,h=g):!c&&!h?(c=Math.round(m*be),h=Math.round(g*be)):c?h||(h=Math.round(g/m*c)):c=Math.round(m/g*h);var ue=Id(c,h),M=ue.getContext("2d");(E==="jpeg"||E==="jpg")&&(E="jpeg",M.fillStyle="#fff",M.fillRect(0,0,c,h)),M.__hidpi__=!0,M.drawImageByCanvas(O,b,x,m,g,0,0,c,h,!1);var B;try{var J;if(y==="base64")N=ue.toDataURL("image/".concat(E),C);else{var te=M.getImageData(0,0,c,h);N=Qv.deflateRaw(te.data,{to:"string"}),J=!0}B={data:N,compressed:J,width:c,height:h}}catch(W){B={errMsg:"canvasGetImageData:fail ".concat(W)}}if(ue.height=ue.width=0,M.__hidpi__=!1,_)_(B);else return B}function u(d,_){var{data:b,x,y:m,width:g,height:c,compressed:h}=d;try{h&&(b=Qv.inflateRaw(b)),c||(c=Math.round(b.length/4/g));var w=Id(g,c),y=w.getContext("2d");y.putImageData(new ImageData(new Uint8ClampedArray(b),g,c),0,0),e.value.getContext("2d").drawImage(w,x,m,g,c),w.height=w.width=0}catch(C){_({errMsg:"canvasPutImageData:fail"});return}_({errMsg:"canvasPutImageData:ok"})}function f(d,_){var{x:b=0,y:x=0,width:m,height:g,destWidth:c,destHeight:h,fileType:w,quality:y,dirname:C}=d,E=l({x:b,y:x,width:m,height:g,destWidth:c,destHeight:h,hidpi:!1,dataType:"base64",type:w,quality:y});if(!E.data||!E.data.length){_({errMsg:E.errMsg.replace("canvasPutImageData","toTempFilePath")});return}g1(E.data)}var v={actionsChanged:n,getImageData:l,putImageData:u,toTempFilePath:f};function p(d,_,b){var x=v[d];d.indexOf("_")!==0&&typeof x=="function"&&x(_,b)}return ve(v,{_resize:a,_handleSubscribe:p})}var kd=on("ucg"),kx={name:{type:String,default:""}},Mx=ge({name:"CheckboxGroup",props:kx,emits:["change"],setup(e,t){var{emit:r,slots:i}=t,a=U(null),n=Pe(a,r);return Rx(e,n),()=>I("uni-checkbox-group",{ref:a},[i.default&&i.default()],512)}});function Rx(e,t){var r=[],i=()=>r.reduce((n,o)=>(o.value.checkboxChecked&&n.push(o.value.value),n),new Array);Fe(kd,{addField(n){r.push(n)},removeField(n){r.splice(r.indexOf(n),1)},checkboxChange(n){t("change",n,{value:i()})}});var a=_e(At,!1);return a&&a.addField({submit:()=>{var n=["",null];return e.name!==""&&(n[0]=e.name,n[1]=i()),n}}),i}var Lx={checked:{type:[Boolean,String],default:!1},id:{type:String,default:""},disabled:{type:[Boolean,String],default:!1},color:{type:String,default:"#007aff"},value:{type:String,default:""}},Px=ge({name:"Checkbox",props:Lx,setup(e,t){var{slots:r}=t,i=U(e.checked),a=U(e.value);H([()=>e.checked,()=>e.value],u=>{var[f,v]=u;i.value=f,a.value=v});var n=()=>{i.value=!1},{uniCheckGroup:o,uniLabel:s}=Nx(i,a,n),l=u=>{e.disabled||(i.value=!i.value,o&&o.checkboxChange(u))};return s&&(s.addHandler(l),Ce(()=>{s.removeHandler(l)})),An(e,{"label-click":l}),()=>{var u=qi(e,"disabled");return I("uni-checkbox",Qe(u,{onClick:l}),[I("div",{class:"uni-checkbox-wrapper"},[I("div",{class:["uni-checkbox-input",{"uni-checkbox-input-disabled":e.disabled}]},[i.value?ln(sn,e.color,22):""],2),r.default&&r.default()])],16,["onClick"])}}});function Nx(e,t,r){var i=Q(()=>({checkboxChecked:Boolean(e.value),value:t.value})),a={reset:r},n=_e(kd,!1);n&&n.addField(i);var o=_e(At,!1);o&&o.addField(a);var s=_e(Xi,!1);return Ce(()=>{n&&n.removeField(i),o&&o.removeField(a)}),{uniCheckGroup:n,uniForm:o,uniLabel:s}}var Md,Ki,kn,ir,Mn,vl;Br(()=>{Ki=plus.os.name==="Android",kn=plus.os.version||""}),document.addEventListener("keyboardchange",function(e){ir=e.height,Mn&&Mn()},!1);function Rd(){}function Gi(e,t,r){Br(()=>{var i="adjustResize",a="adjustPan",n="nothing",o=plus.webview.currentWebview(),s=vl||o.getStyle()||{},l={mode:r||s.softinputMode===i?i:e.adjustPosition?a:n,position:{top:0,height:0}};if(l.mode===a){var u=t.getBoundingClientRect();l.position.top=u.top,l.position.height=u.height+(Number(e.cursorSpacing)||0)}o.setSoftinputTemporary(l)})}function Dx(e,t){if(e.showConfirmBar==="auto"){delete t.softinputNavBar;return}Br(()=>{var r=plus.webview.currentWebview(),{softinputNavBar:i}=r.getStyle()||{},a=i!=="none";a!==e.showConfirmBar?(t.softinputNavBar=i||"auto",r.setStyle({softinputNavBar:e.showConfirmBar?"auto":"none"})):delete t.softinputNavBar})}function Bx(e){var t=e.softinputNavBar;t&&Br(()=>{var r=plus.webview.currentWebview();r.setStyle({softinputNavBar:t})})}var Ld={cursorSpacing:{type:[Number,String],default:0},showConfirmBar:{type:[Boolean,String],default:"auto"},adjustPosition:{type:[Boolean,String],default:!0},autoBlur:{type:[Boolean,String],default:!1}},Pd=["keyboardheightchange"];function Nd(e,t,r){var i={};function a(n){var o,s=()=>{r("keyboardheightchange",{},{height:ir,duration:.25}),o&&ir===0&&Gi(e,n),e.autoBlur&&o&&ir===0&&(Ki||parseInt(kn)>=13)&&document.activeElement.blur()};n.addEventListener("focus",()=>{o=!0,clearTimeout(Md),document.addEventListener("click",Rd,!1),Mn=s,ir&&r("keyboardheightchange",{},{height:ir,duration:0}),Dx(e,i),Gi(e,n)}),Ki&&n.addEventListener("click",()=>{!e.disabled&&!e.readOnly&&o&&ir===0&&Gi(e,n)}),Ki||(parseInt(kn)<12&&n.addEventListener("touchstart",()=>{!e.disabled&&!e.readOnly&&!o&&Gi(e,n)}),parseFloat(kn)>=14.6&&!vl&&Br(()=>{var u=plus.webview.currentWebview();vl=u.getStyle()||{}}));var l=()=>{document.removeEventListener("click",Rd,!1),Mn=null,ir&&r("keyboardheightchange",{},{height:0,duration:0}),Bx(i),Ki&&(Md=setTimeout(()=>{Gi(e,n,!0)},300)),String(navigator.vendor).indexOf("Apple")===0&&document.documentElement.scrollTo(document.documentElement.scrollLeft,document.documentElement.scrollTop)};n.addEventListener("blur",()=>{n.blur(),o=!1,l()})}H(()=>t.value,n=>a(n))}var Dd=/^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,Bd=/^<\/([-A-Za-z0-9_]+)[^>]*>/,$x=/([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g,Fx=ri("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr"),zx=ri("a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video"),Ux=ri("abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var"),Hx=ri("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr"),Wx=ri("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected"),Vx=ri("script,style");function $d(e,t){var r,i,a,n=[],o=e;for(n.last=function(){return this[this.length-1]};e;){if(i=!0,!n.last()||!Vx[n.last()]){if(e.indexOf(""),r>=0&&(t.comment&&t.comment(e.substring(4,r)),e=e.substring(r+3),i=!1)):e.indexOf("]*>"),function(f,v){return v=v.replace(/|/g,"$1$2"),t.chars&&t.chars(v),""}),u("",n.last());if(e==o)throw"Parse Error: "+e;o=e}u();function l(f,v,p,d){if(v=v.toLowerCase(),zx[v])for(;n.last()&&Ux[n.last()];)u("",n.last());if(Hx[v]&&n.last()==v&&u("",v),d=Fx[v]||!!d,d||n.push(v),t.start){var _=[];p.replace($x,function(b,x){var m=arguments[2]?arguments[2]:arguments[3]?arguments[3]:arguments[4]?arguments[4]:Wx[x]?x:"";_.push({name:x,value:m,escaped:m.replace(/(^|[^\\])"/g,'$1\\"')})}),t.start&&t.start(v,_,d)}}function u(f,v){if(v)for(var p=n.length-1;p>=0&&n[p]!=v;p--);else var p=0;if(p>=0){for(var d=n.length-1;d>=p;d--)t.end&&t.end(n[d]);n.length=p}}}function ri(e){for(var t={},r=e.split(","),i=0;io()),delete dl[t]}}a.push(r)}function jx(e){var t=e.import("blots/block/embed");class r extends t{}return r.blotName="divider",r.tagName="HR",{"formats/divider":r}}function Yx(e){var t=e.import("blots/inline");class r extends t{}return r.blotName="ins",r.tagName="INS",{"formats/ins":r}}function qx(e){var{Scope:t,Attributor:r}=e.import("parchment"),i={scope:t.BLOCK,whitelist:["left","right","center","justify"]},a=new r.Style("align","text-align",i);return{"formats/align":a}}function Xx(e){var{Scope:t,Attributor:r}=e.import("parchment"),i={scope:t.BLOCK,whitelist:["rtl"]},a=new r.Style("direction","direction",i);return{"formats/direction":a}}function Zx(e){var t=e.import("parchment"),r=e.import("blots/container"),i=e.import("formats/list/item");class a extends r{static create(o){var s=o==="ordered"?"OL":"UL",l=super.create(s);return(o==="checked"||o==="unchecked")&&l.setAttribute("data-checked",o==="checked"),l}static formats(o){if(o.tagName==="OL")return"ordered";if(o.tagName==="UL")return o.hasAttribute("data-checked")?o.getAttribute("data-checked")==="true"?"checked":"unchecked":"bullet"}constructor(o){super(o);var s=l=>{if(l.target.parentNode===o){var u=this.statics.formats(o),f=t.find(l.target);u==="checked"?f.format("list","unchecked"):u==="unchecked"&&f.format("list","checked")}};o.addEventListener("click",s)}format(o,s){this.children.length>0&&this.children.tail.format(o,s)}formats(){return{[this.statics.blotName]:this.statics.formats(this.domNode)}}insertBefore(o,s){if(o instanceof i)super.insertBefore(o,s);else{var l=s==null?this.length():s.offset(this),u=this.split(l);u.parent.insertBefore(o,u)}}optimize(o){super.optimize(o);var s=this.next;s!=null&&s.prev===this&&s.statics.blotName===this.statics.blotName&&s.domNode.tagName===this.domNode.tagName&&s.domNode.getAttribute("data-checked")===this.domNode.getAttribute("data-checked")&&(s.moveChildren(this),s.remove())}replace(o){if(o.statics.blotName!==this.statics.blotName){var s=t.create(this.statics.defaultChild);o.moveChildren(s),this.appendChild(s)}super.replace(o)}}return a.blotName="list",a.scope=t.Scope.BLOCK_BLOT,a.tagName=["OL","UL"],a.defaultChild="list-item",a.allowedChildren=[i],{"formats/list":a}}function Kx(e){var{Scope:t}=e.import("parchment"),r=e.import("formats/background"),i=new r.constructor("backgroundColor","background-color",{scope:t.INLINE});return{"formats/backgroundColor":i}}function Gx(e){var{Scope:t,Attributor:r}=e.import("parchment"),i={scope:t.BLOCK},a=["margin","marginTop","marginBottom","marginLeft","marginRight"],n=["padding","paddingTop","paddingBottom","paddingLeft","paddingRight"],o={};return a.concat(n).forEach(s=>{o["formats/".concat(s)]=new r.Style(s,Ke(s),i)}),o}function Jx(e){var{Scope:t,Attributor:r}=e.import("parchment"),i={scope:t.INLINE},a=["font","fontSize","fontStyle","fontVariant","fontWeight","fontFamily"],n={};return a.forEach(o=>{n["formats/".concat(o)]=new r.Style(o,Ke(o),i)}),n}function Qx(e){var{Scope:t,Attributor:r}=e.import("parchment"),i=[{name:"lineHeight",scope:t.BLOCK},{name:"letterSpacing",scope:t.INLINE},{name:"textDecoration",scope:t.INLINE},{name:"textIndent",scope:t.BLOCK}],a={};return i.forEach(n=>{var{name:o,scope:s}=n;a["formats/".concat(o)]=new r.Style(o,Ke(o),{scope:s})}),a}function ey(e){var t=e.import("formats/image"),r=["alt","height","width","data-custom","class","data-local"];t.sanitize=a=>a&&vt(a),t.formats=function(n){return r.reduce(function(o,s){return n.hasAttribute(s)&&(o[s]=n.getAttribute(s)),o},{})};var i=t.prototype.format;t.prototype.format=function(a,n){r.indexOf(a)>-1?n?this.domNode.setAttribute(a,n):this.domNode.removeAttribute(a):i.call(this,a,n)}}function ty(e){var t=e.import("formats/link");t.sanitize=r=>{var i=document.createElement("a");i.href=r;var a=i.href.slice(0,i.href.indexOf(":"));return t.PROTOCOL_WHITELIST.concat("file").indexOf(a)>-1?r:t.SANITIZED_URL}}function ry(e){var t={divider:jx,ins:Yx,align:qx,direction:Xx,list:Zx,background:Kx,box:Gx,font:Jx,text:Qx,image:ey,link:ty},r={};Object.values(t).forEach(i=>ve(r,i(e))),e.register(r,!0)}function iy(e,t,r){var i,a,n,o=!1;H(()=>e.readOnly,_=>{i&&(n.enable(!_),_||n.blur())}),H(()=>e.placeholder,_=>{i&&u(_)});function s(_){var b=["span","strong","b","ins","em","i","u","a","del","s","sub","sup","img","div","p","h1","h2","h3","h4","h5","h6","hr","ol","ul","li","br"],x="",m;$d(_,{start:function(c,h,w){if(!b.includes(c)){m=!w;return}m=!1;var y=h.map(E=>{var{name:O,value:N}=E;return"".concat(O,'="').concat(N,'"')}).join(" "),C="<".concat(c," ").concat(y," ").concat(w?"/":"",">");x+=C},end:function(c){m||(x+=""))},chars:function(c){m||(x+=c)}}),a=!0;var g=n.clipboard.convert(x);return a=!1,g}function l(){var _=n.root.innerHTML,b=n.getText(),x=n.getContents();return{html:_,text:b,delta:x}}function u(_){var b="data-placeholder",x=n.root;x.getAttribute(b)!==_&&x.setAttribute(b,_)}var f={};function v(_){var b=_?n.getFormat(_):{},x=Object.keys(b);(x.length!==Object.keys(f).length||x.find(m=>b[m]!==f[m]))&&(f=b,r("statuschange",{},b))}function p(_){var b=window.Quill;ry(b);var x={toolbar:!1,readOnly:e.readOnly,placeholder:e.placeholder};_.length&&(b.register("modules/ImageResize",window.ImageResize.default),x.modules={ImageResize:{modules:_}});var m=t.value;n=new b(m,x);var g=n.root,c=["focus","blur","input"];c.forEach(h=>{g.addEventListener(h,w=>{var y=l();if(h==="input"){if(yc().platform==="ios"){var C=(y.html.match(/([\s\S]*)<\/span>/)||[])[1],E=C&&C.replace(/\s/g,"")?"":e.placeholder;u(E)}w.stopPropagation()}else r(h,w,y)})}),n.on("text-change",()=>{o||r("input",{},l())}),n.on("selection-change",v),n.on("scroll-optimize",()=>{var h=n.selection.getRange()[0];v(h)}),n.clipboard.addMatcher(Node.ELEMENT_NODE,(h,w)=>(a||w.ops&&(w.ops=w.ops.filter(y=>{var{insert:C}=y;return typeof C=="string"}).map(y=>{var{insert:C}=y;return{insert:C}})),w)),i=!0,r("ready",{},{})}Re(()=>{var _=[];e.showImgSize&&_.push("DisplaySize"),e.showImgToolbar&&_.push("Toolbar"),e.showImgResize&&_.push("Resize");var b="./__uniappquill.js";Fd(window.Quill,b,()=>{if(_.length){var x="./__uniappquillimageresize.js";Fd(window.ImageResize,x,()=>{p(_)})}else p(_)})});var d=Un();zn((_,b,x)=>{var{options:m,callbackId:g}=b,c,h,w;if(i){var y=window.Quill;switch(_){case"format":{var{name:C="",value:E=!1}=m;h=n.getSelection(!0);var O=n.getFormat(h)[C]||!1;if(["bold","italic","underline","strike","ins"].includes(C))E=!O;else if(C==="direction"){E=E==="rtl"&&O?!1:E;var N=n.getFormat(h).align;E==="rtl"&&!N?n.format("align","right","user"):!E&&N==="right"&&n.format("align",!1,"user")}else if(C==="indent"){var R=n.getFormat(h).direction==="rtl";E=E==="+1",R&&(E=!E),E=E?"+1":"-1"}else C==="list"&&(E=E==="check"?"unchecked":E,O=O==="checked"?"unchecked":O),E=O&&O!==(E||!1)||!O&&E?E:!O;n.format(C,E,"user")}break;case"insertDivider":h=n.getSelection(!0),n.insertText(h.index,di,"user"),n.insertEmbed(h.index+1,"divider",!0,"user"),n.setSelection(h.index+2,0,"silent");break;case"insertImage":{h=n.getSelection(!0);var{src:Y="",alt:ue="",width:M="",height:B="",extClass:J="",data:te={}}=m,W=vt(Y);n.insertEmbed(h.index,"image",W,"user");var ee=/^(file|blob):/.test(W)?W:!1;o=!0,n.formatText(h.index,1,"data-local",ee),n.formatText(h.index,1,"alt",ue),n.formatText(h.index,1,"width",M),n.formatText(h.index,1,"height",B),n.formatText(h.index,1,"class",J),o=!1,n.formatText(h.index,1,"data-custom",Object.keys(te).map(ie=>"".concat(ie,"=").concat(te[ie])).join("&")),n.setSelection(h.index+1,0,"silent")}break;case"insertText":{h=n.getSelection(!0);var{text:ae=""}=m;n.insertText(h.index,ae,"user"),n.setSelection(h.index+ae.length,0,"silent")}break;case"setContents":{var{delta:ye,html:oe}=m;typeof ye=="object"?n.setContents(ye,"silent"):typeof oe=="string"?n.setContents(s(oe),"silent"):w="contents is missing"}break;case"getContents":c=l();break;case"clear":n.setText("");break;case"removeFormat":{h=n.getSelection(!0);var K=y.import("parchment");h.length?n.removeFormat(h.index,h.length,"user"):Object.keys(n.getFormat(h)).forEach(ie=>{K.query(ie,K.Scope.INLINE)&&n.format(ie,!1)})}break;case"undo":n.history.undo();break;case"redo":n.history.redo();break;case"blur":n.blur();break;case"getSelectionText":h=n.selection.savedRange,c={text:""},h&&h.length!==0&&(c.text=n.getText(h.index,h.length));break;case"scrollIntoView":n.scrollIntoView();break}v(h)}else w="not ready";g&&x({callbackId:g,data:ve({},c,{errMsg:"".concat(_,":").concat(w?"fail "+w:"ok")})})},d,!0)}var ay=ve({},Ld,{id:{type:String,default:""},readOnly:{type:[Boolean,String],default:!1},placeholder:{type:String,default:""},showImgSize:{type:[Boolean,String],default:!1},showImgToolbar:{type:[Boolean,String],default:!1},showImgResize:{type:[Boolean,String],default:!1}}),ny=ge({name:"Editor",props:ay,emit:["ready","focus","blur","input","statuschange",...Pd],setup(e,t){var{emit:r}=t,i=U(null),a=Pe(i,r);return iy(e,i,a),Nd(e,i,a),()=>I("uni-editor",{ref:i,id:e.id,class:"ql-container"},null,8,["id"])}}),zd="#10aeff",oy="#f76260",Ud="#b2b2b2",sy="#f43530",ly={success:{d:tb,c:Ia},success_no_circle:{d:sn,c:Ia},info:{d:Q_,c:zd},warn:{d:ib,c:oy},waiting:{d:rb,c:zd},cancel:{d:K_,c:sy},download:{d:J_,c:Ia},search:{d:eb,c:Ud},clear:{d:G_,c:Ud}},uy=ge({name:"Icon",props:{type:{type:String,required:!0,default:""},size:{type:[String,Number],default:23},color:{type:String,default:""}},setup(e){var t=Q(()=>ly[e.type]);return()=>{var{value:r}=t;return I("uni-icon",null,[r&&r.d&&ln(r.d,e.color||r.c,pr(e.size))])}}}),fy={src:{type:String,default:""},mode:{type:String,default:"scaleToFill"},lazyLoad:{type:[Boolean,String],default:!1},draggable:{type:Boolean,default:!0}},Rn={widthFix:["offsetWidth","height"],heightFix:["offsetHeight","width"]},cy={aspectFit:["center center","contain"],aspectFill:["center center","cover"],widthFix:[,"100% 100%"],heightFix:[,"100% 100%"],top:["center top"],bottom:["center bottom"],center:["center center"],left:["left center"],right:["right center"],"top left":["left top"],"top right":["right top"],"bottom left":["left bottom"],"bottom right":["right bottom"]},vy=ge({name:"Image",props:fy,setup(e,t){var{emit:r}=t,i=U(null),a=dy(i,e),n=Pe(i,r),{fixSize:o}=my(i,e,a);return hy(a,o,n),()=>{var{mode:s}=e,{imgSrc:l,modeStyle:u,src:f}=a,v;return v=l?I("img",{src:l,draggable:e.draggable},null,8,["src","draggable"]):I("img",null,null),I("uni-image",{ref:i},[I("div",{style:u},null,4),v,Rn[s]?I(Or,{onResize:o},null,8,["onResize"]):I("span",null,null)],512)}}});function dy(e,t){var r=U(""),i=Q(()=>{var n="auto",o="",s=cy[t.mode];return s?(s[0]&&(o=s[0]),s[1]&&(n=s[1])):(o="0% 0%",n="100% 100%"),"background-image:".concat(r.value?'url("'+r.value+'")':"none",";background-position:").concat(o,";background-size:").concat(n,";")}),a=Ae({rootEl:e,src:Q(()=>t.src?vt(t.src):""),origWidth:0,origHeight:0,origStyle:{width:"",height:""},modeStyle:i,imgSrc:r});return Re(()=>{var n=e.value,o=n.style;a.origWidth=Number(o.width)||0,a.origHeight=Number(o.height)||0}),a}function hy(e,t,r){var i,a=function(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"";e.origWidth=s,e.origHeight=l,e.imgSrc=u},n=s=>{if(!s){o(),a();return}i=i||new Image,i.onload=l=>{var{width:u,height:f}=i;a(u,f,s),t(),o(),r("load",l,{width:u,height:f})},i.onerror=l=>{a(),o(),r("error",l,{errMsg:"GET ".concat(e.src," 404 (Not Found)")})},i.src=s},o=()=>{i&&(i.onload=null,i.onerror=null,i=null)};H(()=>e.src,s=>n(s)),Re(()=>n(e.src)),Ce(()=>o())}var gy=navigator.vendor==="Google Inc.";function py(e){return gy&&e>10&&(e=Math.round(e/2)*2),e}function my(e,t,r){var i=()=>{var{mode:n}=t,o=Rn[n];if(!!o){var{origWidth:s,origHeight:l}=r,u=s&&l?s/l:0;if(!!u){var f=e.value,v=f[o[0]];v&&(f.style[o[1]]=py(v/u)+"px"),window.dispatchEvent(new CustomEvent("updateview"))}}},a=()=>{var{style:n}=e.value,{origStyle:{width:o,height:s}}=r;n.width=o,n.height=s};return H(()=>t.mode,(n,o)=>{Rn[o]&&a(),Rn[n]&&i()}),{fixSize:i,resetSize:a}}function _y(e,t){var r=0,i,a,n=function(){for(var o=arguments.length,s=new Array(o),l=0;l{a=null,r=u,e.apply(this,s)},u-rLn.forEach(t=>t.userAction=e);function wy(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userAction:!1};if(!Hd){var t=["touchstart","touchmove","touchend","mousedown","mouseup"];t.forEach(r=>{document.addEventListener(r,function(){!hl&&Wd(!0),hl++,setTimeout(()=>{!--hl&&Wd(!1)},0)},by)}),Hd=!0}Ln.push(e)}function xy(e){var t=Ln.indexOf(e);t>=0&&Ln.splice(t,1)}function yy(){var e=Ae({userAction:!1});return Re(()=>{wy(e)}),Ce(()=>{xy(e)}),{state:e}}function Vd(){var e=Ae({attrs:{}});return Re(()=>{for(var t=jt();t;){var r=t.type.__scopeId;r&&(e.attrs[r]=""),t=t.proxy&&t.proxy.$mpType==="page"?null:t.parent}}),{state:e}}function Sy(e,t){var r=_e(At,!1);if(!!r){var i=jt(),a={submit(){var n=i.proxy;return[n[e],typeof t=="string"?n[t]:t.value]},reset(){typeof t=="string"?i.proxy[t]="":t.value=""}};r.addField(a),Ce(()=>{r.removeField(a)})}}function Ey(e,t){var r=document.activeElement;if(!r)return t({});var i={};["input","textarea"].includes(r.tagName.toLowerCase())&&(i.start=r.selectionStart,i.end=r.selectionEnd),t(i)}var Ty=function(){bt(Xt(),"getSelectedTextRange",Ey)},Cy=200,gl;function pl(e){return e===null?"":String(e)}var jd=ve({},{name:{type:String,default:""},modelValue:{type:[String,Number],default:""},value:{type:[String,Number],default:""},disabled:{type:[Boolean,String],default:!1},autoFocus:{type:[Boolean,String],default:!1},focus:{type:[Boolean,String],default:!1},cursor:{type:[Number,String],default:-1},selectionStart:{type:[Number,String],default:-1},selectionEnd:{type:[Number,String],default:-1},type:{type:String,default:"text"},password:{type:[Boolean,String],default:!1},placeholder:{type:String,default:""},placeholderStyle:{type:String,default:""},placeholderClass:{type:String,default:""},maxlength:{type:[Number,String],default:140},confirmType:{type:String,default:"done"}},Ld),Yd=["input","focus","blur","update:value","update:modelValue","update:focus",...Pd];function Oy(e,t,r){var i=U(null),a=Pe(t,r),n=Q(()=>{var v=Number(e.selectionStart);return isNaN(v)?-1:v}),o=Q(()=>{var v=Number(e.selectionEnd);return isNaN(v)?-1:v}),s=Q(()=>{var v=Number(e.cursor);return isNaN(v)?-1:v}),l=Q(()=>{var v=Number(e.maxlength);return isNaN(v)?140:v}),u=pl(e.modelValue)||pl(e.value),f=Ae({value:u,valueOrigin:u,maxlength:l,focus:e.focus,composing:!1,selectionStart:n,selectionEnd:o,cursor:s});return H(()=>f.focus,v=>r("update:focus",v)),H(()=>f.maxlength,v=>f.value=f.value.slice(0,v)),{fieldRef:i,state:f,trigger:a}}function Ay(e,t,r,i){var a=t0(s=>{t.value=pl(s)},100);H(()=>e.modelValue,a),H(()=>e.value,a);var n=_y((s,l)=>{a.cancel(),r("update:modelValue",l.value),r("update:value",l.value),i("input",s,l)},100),o=(s,l,u)=>{a.cancel(),n(s,l),u&&n.flush()};return yf(()=>{a.cancel(),n.cancel()}),{trigger:i,triggerInput:o}}function Iy(e,t){var{state:r}=yy(),i=Q(()=>e.autoFocus||e.focus);function a(){if(!!i.value){var o=t.value;if(!o||!("plus"in window)){setTimeout(a,100);return}{var s=Cy-(Date.now()-gl);if(s>0){setTimeout(a,s);return}o.focus(),r.userAction||plus.key.showSoftKeybord()}}}function n(){var o=t.value;o&&o.blur()}H(()=>e.focus,o=>{o?a():n()}),Re(()=>{gl=gl||Date.now(),i.value&&Vr(a)})}function ky(e,t,r,i,a){function n(){var l=e.value;l&&t.focus&&t.selectionStart>-1&&t.selectionEnd>-1&&(l.selectionStart=t.selectionStart,l.selectionEnd=t.selectionEnd)}function o(){var l=e.value;l&&t.focus&&t.selectionStart<0&&t.selectionEnd<0&&t.cursor>-1&&(l.selectionEnd=l.selectionStart=t.cursor)}function s(){var l=e.value,u=function(p){t.focus=!0,r("focus",p,{value:t.value}),n(),o()},f=function(p,d){p.stopPropagation(),!(typeof a=="function"&&a(p,t)===!1)&&(t.value=l.value,t.composing||i(p,{value:l.value,cursor:l.selectionEnd},d))},v=function(p){t.composing&&(t.composing=!1,f(p,!0)),t.focus=!1,r("blur",p,{value:t.value,cursor:p.target.selectionEnd})};l.addEventListener("change",p=>p.stopPropagation()),l.addEventListener("focus",u),l.addEventListener("blur",v),l.addEventListener("input",f),l.addEventListener("compositionstart",p=>{p.stopPropagation(),t.composing=!0}),l.addEventListener("compositionend",p=>{p.stopPropagation(),t.composing&&(t.composing=!1,f(p))})}H([()=>t.selectionStart,()=>t.selectionEnd],n),H(()=>t.cursor,o),H(()=>e.value,s)}function qd(e,t,r,i){Ty();var{fieldRef:a,state:n,trigger:o}=Oy(e,t,r),{triggerInput:s}=Ay(e,n,r,o);Iy(e,a),Nd(e,a,o);var{state:l}=Vd();Sy("name",n),ky(a,n,o,s,i);var u=String(navigator.vendor).indexOf("Apple")===0&&CSS.supports("image-orientation:from-image");return{fieldRef:a,state:n,scopedAttrsState:l,fixDisabledColor:u,trigger:o}}var My=ve({},jd,{placeholderClass:{type:String,default:"input-placeholder"},textContentType:{type:String,default:""}}),Ry=ge({name:"Input",props:My,emits:["confirm",...Yd],setup(e,t){var{emit:r}=t,i=["text","number","idcard","digit","password","tel"],a=["off","one-time-code"],n=Q(()=>{var g="";switch(e.type){case"text":e.confirmType==="search"&&(g="search");break;case"idcard":g="text";break;case"digit":g="number";break;default:g=~i.includes(e.type)?e.type:"text";break}return e.password?"password":g}),o=Q(()=>{var g=a.indexOf(e.textContentType),c=a.indexOf(Ke(e.textContentType)),h=g!==-1?g:c!==-1?c:0;return a[h]}),s=U(""),l,u=U(null),{fieldRef:f,state:v,scopedAttrsState:p,fixDisabledColor:d,trigger:_}=qd(e,u,r,(g,c)=>{var h=g.target;if(n.value==="number"){if(l&&(h.removeEventListener("blur",l),l=null),h.validity&&!h.validity.valid)return!s.value&&g.data==="-"||s.value[0]==="-"&&g.inputType==="deleteContentBackward"?(s.value="-",c.value="",l=()=>{s.value=h.value=""},h.addEventListener("blur",l),!1):(s.value=c.value=h.value=s.value==="-"?"":s.value,!1);s.value=h.value;var w=c.maxlength;if(w>0&&h.value.length>w)return h.value=h.value.slice(0,w),c.value=h.value,!1}}),b=["number","digit"],x=Q(()=>b.includes(e.type)?"0.000000000000000001":"");function m(g){g.key==="Enter"&&(g.stopPropagation(),_("confirm",g,{value:g.target.value}))}return()=>{var g=e.disabled&&d?I("input",{ref:f,value:v.value,tabindex:"-1",readonly:!!e.disabled,type:n.value,maxlength:v.maxlength,step:x.value,class:"uni-input-input",onFocus:c=>c.target.blur()},null,40,["value","readonly","type","maxlength","step","onFocus"]):I("input",{ref:f,value:v.value,disabled:!!e.disabled,type:n.value,maxlength:v.maxlength,step:x.value,enterkeyhint:e.confirmType,pattern:e.type==="number"?"[0-9]*":void 0,class:"uni-input-input",autocomplete:o.value,onKeyup:m},null,40,["value","disabled","type","maxlength","step","enterkeyhint","pattern","autocomplete","onKeyup"]);return I("uni-input",{ref:u},[I("div",{class:"uni-input-wrapper"},[wi(I("div",Qe(p.attrs,{style:e.placeholderStyle,class:["uni-input-placeholder",e.placeholderClass]}),[e.placeholder],16),[[Ai,!(v.value.length||s.value==="-")]]),e.confirmType==="search"?I("form",{action:"",onSubmit:c=>c.preventDefault(),class:"uni-input-form"},[g],40,["onSubmit"]):g])],512)}}});function Ly(e){return Object.keys(e).map(t=>[t,e[t]])}var Py=["class","style"],Ny=/^on[A-Z]+/,Xd=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{excludeListeners:t=!1,excludeKeys:r=[]}=e,i=jt(),a=Go({}),n=Go({}),o=Go({}),s=r.concat(Py);return i.attrs=Ae(i.attrs),d_(()=>{var l=Ly(i.attrs).reduce((u,f)=>{var[v,p]=f;return s.includes(v)?u.exclude[v]=p:Ny.test(v)?(t||(u.attrs[v]=p),u.listeners[v]=p):u.attrs[v]=p,u},{exclude:{},attrs:{},listeners:{}});a.value=l.attrs,n.value=l.listeners,o.value=l.exclude}),{$attrs:a,$listeners:n,$excludeAttrs:o}},Pn,Ji;function Nn(){Br(()=>{Pn||(Pn=plus.webview.currentWebview()),Ji||(Ji=(Pn.getStyle()||{}).pullToRefresh||{})})}function ar(e){var{disable:t}=e;Ji&&Ji.support&&Pn.setPullToRefresh(Object.assign({},Ji,{support:!t}))}function ml(e){var t=[];return Array.isArray(e)&&e.forEach(r=>{Ya(r)?r.type===xt?t.push(...ml(r.children)):t.push(r):Array.isArray(r)&&t.push(...ml(r))}),t}function Qi(e){var t=jt();t.rebuild=e}var Dy={scaleArea:{type:Boolean,default:!1}},By=ge({inheritAttrs:!1,name:"MovableArea",props:Dy,setup(e,t){var{slots:r}=t,i=U(null),a=U(!1),{setContexts:n,events:o}=$y(e,i),{$listeners:s,$attrs:l,$excludeAttrs:u}=Xd(),f=s.value,v=["onTouchstart","onTouchmove","onTouchend"];v.forEach(m=>{var g=f[m],c=o["_".concat(m)];f[m]=g?[].concat(g,c):c}),Re(()=>{o._resize(),Nn(),a.value=!0});var p=[],d=[];function _(){for(var m=[],g=function(h){var w=p[h];w instanceof Element||(w=w.el);var y=d.find(C=>w===C.rootRef.value);y&&m.push(Ha(y))},c=0;c{p=i.value.children,_()});var b=m=>{d.push(m),_()},x=m=>{var g=d.indexOf(m);g>=0&&(d.splice(g,1),_())};return Fe("_isMounted",a),Fe("movableAreaRootRef",i),Fe("addMovableViewContext",b),Fe("removeMovableViewContext",x),()=>(r.default&&r.default(),I("uni-movable-area",Qe({ref:i},l.value,u.value,f),[I(Or,{onReize:o._resize},null,8,["onReize"]),p],16))}});function Zd(e){return Math.sqrt(e.x*e.x+e.y*e.y)}function $y(e,t){var r=U(0),i=U(0),a=Ae({x:null,y:null}),n=U(null),o=null,s=[];function l(b){b&&b!==1&&(e.scaleArea?s.forEach(function(x){x._setScale(b)}):o&&o._setScale(b))}function u(b){var x=arguments.length>1&&arguments[1]!==void 0?arguments[1]:s,m=t.value;function g(c){for(var h=0;h{ar({disable:!0});var x=b.touches;if(x&&x.length>1){var m={x:x[1].pageX-x[0].pageX,y:x[1].pageY-x[0].pageY};if(n.value=Zd(m),a.x=m.x,a.y=m.y,!e.scaleArea){var g=u(x[0].target),c=u(x[1].target);o=g&&g===c?g:null}}}),v=Cr(b=>{var x=b.touches;if(x&&x.length>1){b.preventDefault();var m={x:x[1].pageX-x[0].pageX,y:x[1].pageY-x[0].pageY};if(a.x!==null&&n.value&&n.value>0){var g=Zd(m)/n.value;l(g)}a.x=m.x,a.y=m.y}}),p=Cr(b=>{ar({disable:!1});var x=b.touches;x&&x.length||b.changedTouches&&(a.x=0,a.y=0,n.value=null,e.scaleArea?s.forEach(function(m){m._endScale()}):o&&o._endScale())});function d(){_(),s.forEach(function(b,x){b.setParent()})}function _(){var b=window.getComputedStyle(t.value),x=t.value.getBoundingClientRect();r.value=x.width-["Left","Right"].reduce(function(m,g){var c="border"+g+"Width",h="padding"+g;return m+parseFloat(b[c])+parseFloat(b[h])},0),i.value=x.height-["Top","Bottom"].reduce(function(m,g){var c="border"+g+"Width",h="padding"+g;return m+parseFloat(b[c])+parseFloat(b[h])},0)}return Fe("movableAreaWidth",r),Fe("movableAreaHeight",i),{setContexts(b){s=b},events:{_onTouchstart:f,_onTouchmove:v,_onTouchend:p,_resize:d}}}var ea=function(e,t,r,i){e.addEventListener(t,a=>{typeof r=="function"&&r(a)===!1&&((typeof a.cancelable!="undefined"?a.cancelable:!0)&&a.preventDefault(),a.stopPropagation())},{passive:!1})},Kd,Gd;function Dn(e,t,r){Ce(()=>{document.removeEventListener("mousemove",Kd),document.removeEventListener("mouseup",Gd)});var i=0,a=0,n=0,o=0,s=function(d,_,b,x){if(t({target:d.target,currentTarget:d.currentTarget,preventDefault:d.preventDefault.bind(d),stopPropagation:d.stopPropagation.bind(d),touches:d.touches,changedTouches:d.changedTouches,detail:{state:_,x:b,y:x,dx:b-i,dy:x-a,ddx:b-n,ddy:x-o,timeStamp:d.timeStamp}})===!1)return!1},l=null,u,f;ea(e,"touchstart",function(d){if(u=!0,d.touches.length===1&&!l)return l=d,i=n=d.touches[0].pageX,a=o=d.touches[0].pageY,s(d,"start",i,a)}),ea(e,"mousedown",function(d){if(f=!0,!u&&!l)return l=d,i=n=d.pageX,a=o=d.pageY,s(d,"start",i,a)}),ea(e,"touchmove",function(d){if(d.touches.length===1&&l){var _=s(d,"move",d.touches[0].pageX,d.touches[0].pageY);return n=d.touches[0].pageX,o=d.touches[0].pageY,_}});var v=Kd=function(d){if(!u&&f&&l){var _=s(d,"move",d.pageX,d.pageY);return n=d.pageX,o=d.pageY,_}};document.addEventListener("mousemove",v),ea(e,"touchend",function(d){if(d.touches.length===0&&l)return u=!1,l=null,s(d,"end",d.changedTouches[0].pageX,d.changedTouches[0].pageY)});var p=Gd=function(d){if(f=!1,!u&&l)return l=null,s(d,"end",d.pageX,d.pageY)};document.addEventListener("mouseup",p),ea(e,"touchcancel",function(d){if(l){u=!1;var _=l;return l=null,s(d,r?"cancel":"end",_.touches[0].pageX,_.touches[0].pageY)}})}function Bn(e,t,r){return e>t-r&&ethis._t&&(e=this._t,this._lastDt=e);var t=this._x_v*e+.5*this._x_a*Math.pow(e,2)+this._x_s,r=this._y_v*e+.5*this._y_a*Math.pow(e,2)+this._y_s;return(this._x_a>0&&tthis._endPositionX)&&(t=this._endPositionX),(this._y_a>0&&rthis._endPositionY)&&(r=this._endPositionY),{x:t,y:r}},It.prototype.ds=function(e){return e===void 0&&(e=(new Date().getTime()-this._startTime)/1e3),e>this._t&&(e=this._t),{dx:this._x_v+this._x_a*e,dy:this._y_v+this._y_a*e}},It.prototype.delta=function(){return{x:-1.5*Math.pow(this._x_v,2)/this._x_a||0,y:-1.5*Math.pow(this._y_v,2)/this._y_a||0}},It.prototype.dt=function(){return-this._x_v/this._x_a},It.prototype.done=function(){var e=Bn(this.s().x,this._endPositionX)||Bn(this.s().y,this._endPositionY)||this._lastDt===this._t;return this._lastDt=null,e},It.prototype.setEnd=function(e,t){this._endPositionX=e,this._endPositionY=t},It.prototype.reconfigure=function(e,t){this._m=e,this._f=1e3*t};function rt(e,t,r){this._m=e,this._k=t,this._c=r,this._solution=null,this._endPosition=0,this._startTime=0}rt.prototype._solve=function(e,t){var r=this._c,i=this._m,a=this._k,n=r*r-4*i*a;if(n===0){var o=-r/(2*i),s=e,l=t/(o*e);return{x:function(m){return(s+l*m)*Math.pow(Math.E,o*m)},dx:function(m){var g=Math.pow(Math.E,o*m);return o*(s+l*m)*g+l*g}}}if(n>0){var u=(-r-Math.sqrt(n))/(2*i),f=(-r+Math.sqrt(n))/(2*i),v=(t-u*e)/(f-u),p=e-v;return{x:function(m){var g,c;return m===this._t&&(g=this._powER1T,c=this._powER2T),this._t=m,g||(g=this._powER1T=Math.pow(Math.E,u*m)),c||(c=this._powER2T=Math.pow(Math.E,f*m)),p*g+v*c},dx:function(m){var g,c;return m===this._t&&(g=this._powER1T,c=this._powER2T),this._t=m,g||(g=this._powER1T=Math.pow(Math.E,u*m)),c||(c=this._powER2T=Math.pow(Math.E,f*m)),p*u*g+v*f*c}}}var d=Math.sqrt(4*i*a-r*r)/(2*i),_=-r/2*i,b=e,x=(t-_*e)/d;return{x:function(m){return Math.pow(Math.E,_*m)*(b*Math.cos(d*m)+x*Math.sin(d*m))},dx:function(m){var g=Math.pow(Math.E,_*m),c=Math.cos(d*m),h=Math.sin(d*m);return g*(x*d*c-b*d*h)+_*g*(x*h+b*c)}}},rt.prototype.x=function(e){return e===void 0&&(e=(new Date().getTime()-this._startTime)/1e3),this._solution?this._endPosition+this._solution.x(e):0},rt.prototype.dx=function(e){return e===void 0&&(e=(new Date().getTime()-this._startTime)/1e3),this._solution?this._solution.dx(e):0},rt.prototype.setEnd=function(e,t,r){if(r||(r=new Date().getTime()),e!==this._endPosition||!Ar(t,.1)){t=t||0;var i=this._endPosition;this._solution&&(Ar(t,.1)&&(t=this._solution.dx((r-this._startTime)/1e3)),i=this._solution.x((r-this._startTime)/1e3),Ar(t,.1)&&(t=0),Ar(i,.1)&&(i=0),i+=this._endPosition),this._solution&&Ar(i-e,.1)&&Ar(t,.1)||(this._endPosition=e,this._solution=this._solve(i-this._endPosition,t),this._startTime=r)}},rt.prototype.snap=function(e){this._startTime=new Date().getTime(),this._endPosition=e,this._solution={x:function(){return 0},dx:function(){return 0}}},rt.prototype.done=function(e){return e||(e=new Date().getTime()),Bn(this.x(),this._endPosition,.1)&&Ar(this.dx(),.1)},rt.prototype.reconfigure=function(e,t,r){this._m=e,this._k=t,this._c=r,this.done()||(this._solution=this._solve(this.x()-this._endPosition,this.dx()),this._startTime=new Date().getTime())},rt.prototype.springConstant=function(){return this._k},rt.prototype.damping=function(){return this._c},rt.prototype.configuration=function(){function e(r,i){r.reconfigure(1,i,r.damping())}function t(r,i){r.reconfigure(1,r.springConstant(),i)}return[{label:"Spring Constant",read:this.springConstant.bind(this),write:e.bind(this,this),min:100,max:1e3},{label:"Damping",read:this.damping.bind(this),write:t.bind(this,this),min:1,max:500}]};function ta(e,t,r){this._springX=new rt(e,t,r),this._springY=new rt(e,t,r),this._springScale=new rt(e,t,r),this._startTime=0}ta.prototype.setEnd=function(e,t,r,i){var a=new Date().getTime();this._springX.setEnd(e,i,a),this._springY.setEnd(t,i,a),this._springScale.setEnd(r,i,a),this._startTime=a},ta.prototype.x=function(){var e=(new Date().getTime()-this._startTime)/1e3;return{x:this._springX.x(e),y:this._springY.x(e),scale:this._springScale.x(e)}},ta.prototype.done=function(){var e=new Date().getTime();return this._springX.done(e)&&this._springY.done(e)&&this._springScale.done(e)},ta.prototype.reconfigure=function(e,t,r){this._springX.reconfigure(e,t,r),this._springY.reconfigure(e,t,r),this._springScale.reconfigure(e,t,r)};var Fy={direction:{type:String,default:"none"},inertia:{type:[Boolean,String],default:!1},outOfBounds:{type:[Boolean,String],default:!1},x:{type:[Number,String],default:0},y:{type:[Number,String],default:0},damping:{type:[Number,String],default:20},friction:{type:[Number,String],default:2},disabled:{type:[Boolean,String],default:!1},scale:{type:[Boolean,String],default:!1},scaleMin:{type:[Number,String],default:.5},scaleMax:{type:[Number,String],default:10},scaleValue:{type:[Number,String],default:1},animation:{type:[Boolean,String],default:!0}},zy=ge({name:"MovableView",props:Fy,emits:["change","scale"],setup(e,t){var{slots:r,emit:i}=t,a=U(null),n=Pe(a,i),{setParent:o}=Uy(e,n,a);return()=>I("uni-movable-view",{ref:a},[I(Or,{onResize:o},null,8,["onResize"]),r.default&&r.default()],512)}}),bl=!1;function Jd(e){bl||(bl=!0,requestAnimationFrame(function(){e(),bl=!1}))}function Qd(e,t){if(e===t)return 0;var r=e.offsetLeft;return e.offsetParent?r+=Qd(e.offsetParent,t):0}function eh(e,t){if(e===t)return 0;var r=e.offsetTop;return e.offsetParent?r+=eh(e.offsetParent,t):0}function th(e,t){return+((1e3*e-1e3*t)/1e3).toFixed(1)}function rh(e,t,r){var i={id:0,cancelled:!1},a=function(o){o&&o.id&&cancelAnimationFrame(o.id),o&&(o.cancelled=!0)};function n(o,s,l,u){if(!o||!o.cancelled){l(s);var f=s.done();f||o.cancelled||(o.id=requestAnimationFrame(n.bind(null,o,s,l,u))),f&&u&&u(s)}}return n(i,e,t,r),{cancel:a.bind(null,i),model:e}}function $n(e){return/\d+[ur]px$/i.test(e)?uni.upx2px(parseFloat(e)):Number(e)||0}function Uy(e,t,r){var i=_e("movableAreaWidth",U(0)),a=_e("movableAreaHeight",U(0)),n=_e("_isMounted",U(!1)),o=_e("movableAreaRootRef"),s=_e("addMovableViewContext",()=>{}),l=_e("removeMovableViewContext",()=>{}),u=U($n(e.x)),f=U($n(e.y)),v=U(Number(e.scaleValue)||1),p=U(0),d=U(0),_=U(0),b=U(0),x=U(0),m=U(0),g=null,c=null,h={x:0,y:0},w={x:0,y:0},y=1,C=1,E=0,O=0,N=!1,R=!1,Y,ue,M=null,B=null,J=new _l,te=new _l,W={historyX:[0,0],historyY:[0,0],historyT:[0,0]},ee=Q(()=>{var A=Number(e.damping);return isNaN(A)?20:A}),ae=Q(()=>{var A=Number(e.friction);return isNaN(A)||A<=0?2:A}),ye=Q(()=>{var A=Number(e.scaleMin);return isNaN(A)?.5:A}),oe=Q(()=>{var A=Number(e.scaleMax);return isNaN(A)?10:A}),K=Q(()=>e.direction==="all"||e.direction==="horizontal"),ie=Q(()=>e.direction==="all"||e.direction==="vertical"),le=new ta(1,9*Math.pow(ee.value,2)/40,ee.value),Ie=new It(1,ae.value);H(()=>e.x,A=>{u.value=$n(A)}),H(()=>e.y,A=>{f.value=$n(A)}),H(u,A=>{nt(A)}),H(f,A=>{nr(A)}),H(()=>e.scaleValue,A=>{v.value=Number(A)||0}),H(v,A=>{na(A)}),H(ye,()=>{Ne()}),H(oe,()=>{Ne()});function ke(){c&&c.cancel(),g&&g.cancel()}function nt(A){if(K.value){if(A+w.x===E)return E;g&&g.cancel(),G(A+w.x,f.value+w.y,y)}return A}function nr(A){if(ie.value){if(A+w.y===O)return O;g&&g.cancel(),G(u.value+w.x,A+w.y,y)}return A}function Ne(){if(!e.scale)return!1;F(y,!0),$(y)}function na(A){return e.scale?(A=D(A),F(A,!0),$(A),A):!1}function oa(){N||e.disabled||(ar({disable:!0}),ke(),W.historyX=[0,0],W.historyY=[0,0],W.historyT=[0,0],K.value&&(Y=E),ie.value&&(ue=O),r.value.style.willChange="transform",M=null,B=null,R=!0)}function S(A){if(!N&&!e.disabled&&R){var j=E,q=O;if(B===null&&(B=Math.abs(A.detail.dx/A.detail.dy)>1?"htouchmove":"vtouchmove"),K.value&&(j=A.detail.dx+Y,W.historyX.shift(),W.historyX.push(j),!ie.value&&M===null&&(M=Math.abs(A.detail.dx/A.detail.dy)<1)),ie.value&&(q=A.detail.dy+ue,W.historyY.shift(),W.historyY.push(q),!K.value&&M===null&&(M=Math.abs(A.detail.dy/A.detail.dx)<1)),W.historyT.shift(),W.historyT.push(A.detail.timeStamp),!M){A.preventDefault();var he="touch";j<_.value?e.outOfBounds?(he="touch-out-of-bounds",j=_.value-J.x(_.value-j)):j=_.value:j>x.value&&(e.outOfBounds?(he="touch-out-of-bounds",j=x.value+J.x(j-x.value)):j=x.value),qm.value&&(e.outOfBounds?(he="touch-out-of-bounds",q=m.value+te.x(q-m.value)):q=m.value),Jd(function(){X(j,q,y,he)})}}}function T(){if(!N&&!e.disabled&&R&&(ar({disable:!1}),r.value.style.willChange="auto",R=!1,!M&&!Z("out-of-bounds")&&e.inertia)){var A=1e3*(W.historyX[1]-W.historyX[0])/(W.historyT[1]-W.historyT[0]),j=1e3*(W.historyY[1]-W.historyY[0])/(W.historyT[1]-W.historyT[0]);Ie.setV(A,j),Ie.setS(E,O);var q=Ie.delta().x,he=Ie.delta().y,fe=q+E,$e=he+O;fe<_.value?(fe=_.value,$e=O+(_.value-E)*he/q):fe>x.value&&(fe=x.value,$e=O+(x.value-E)*he/q),$em.value&&($e=m.value,fe=E+(m.value-O)*q/he),Ie.setEnd(fe,$e),c=rh(Ie,function(){var Ze=Ie.s(),De=Ze.x,gt=Ze.y;X(De,gt,y,"friction")},function(){c.cancel()})}!e.outOfBounds&&!e.inertia&&ke()}function k(A,j){var q=!1;return A>x.value?(A=x.value,q=!0):A<_.value&&(A=_.value,q=!0),j>m.value?(j=m.value,q=!0):j3&&arguments[3]!==void 0?arguments[3]:"",fe=arguments.length>4?arguments[4]:void 0,$e=arguments.length>5?arguments[5]:void 0;A!==null&&A.toString()!=="NaN"&&typeof A=="number"||(A=E||0),j!==null&&j.toString()!=="NaN"&&typeof j=="number"||(j=O||0),A=Number(A.toFixed(1)),j=Number(j.toFixed(1)),q=Number(q.toFixed(1)),E===A&&O===j||fe||t("change",{},{x:th(A,w.x),y:th(j,w.y),source:he}),e.scale||(q=y),q=D(q),q=+q.toFixed(3),$e&&q!==y&&t("scale",{},{x:A,y:j,scale:q});var Ze="translateX("+A+"px) translateY("+j+"px) translateZ(0px) scale("+q+")";r.value.style.transform=Ze,r.value.style.webkitTransform=Ze,E=A,O=j,y=q}function ce(){if(!!n.value){ke();var A=e.scale?v.value:1;L(),P(A),z(),E=u.value+w.x,O=f.value+w.y;var j=k(E,O),q=j.x,he=j.y;X(q,he,A,"",!0),$(A)}}function Be(){N=!1,$(y)}function Te(A){A&&(A=C*A,V(),F(A))}return Re(()=>{Dn(r.value,j=>{switch(j.detail.state){case"start":oa();break;case"move":S(j);break;case"end":T()}}),ce(),Ie.reconfigure(1,ae.value),le.reconfigure(1,9*Math.pow(ee.value,2)/40,ee.value),r.value.style.transformOrigin="center",Nn();var A={rootRef:r,setParent:ce,_endScale:Be,_setScale:Te};s(A),Wt(()=>{l(A)})}),Wt(()=>{ke()}),{setParent:ce}}var Hy=["navigate","redirect","switchTab","reLaunch","navigateBack"],Wy={hoverClass:{type:String,default:"navigator-hover"},url:{type:String,default:""},openType:{type:String,default:"navigate",validator(e){return Boolean(~Hy.indexOf(e))}},delta:{type:Number,default:1},hoverStartTime:{type:[Number,String],default:50},hoverStayTime:{type:[Number,String],default:600},exists:{type:String,default:""},hoverStopPropagation:{type:Boolean,default:!1}},Vy=ge({name:"Navigator",compatConfig:{MODE:3},props:Wy,setup(e,t){var{slots:r}=t,{hovering:i,binding:a}=cl(e);function n(o){if(e.openType!=="navigateBack"&&!e.url){console.error(" should have url attribute when using navigateTo, redirectTo, reLaunch or switchTab");return}switch(e.openType){case"navigate":uni.navigateTo({url:e.url});break;case"redirect":uni.redirectTo({url:e.url,exists:e.exists});break;case"switchTab":uni.switchTab({url:e.url});break;case"reLaunch":uni.reLaunch({url:e.url});break;case"navigateBack":uni.navigateBack({delta:e.delta});break}}return()=>{var{hoverClass:o}=e,s=e.hoverClass&&e.hoverClass!=="none";return I("uni-navigator",Qe({class:s&&i.value?o:""},s&&a,{onClick:n}),[r.default&&r.default()],16,["onClick"])}}}),jy={value:{type:Array,default(){return[]},validator:function(e){return Array.isArray(e)&&e.filter(t=>typeof t=="number").length===e.length}},indicatorStyle:{type:String,default:""},indicatorClass:{type:String,default:""},maskStyle:{type:String,default:""},maskClass:{type:String,default:""}};function Yy(e){var t=Ae([...e.value]),r=Ae({value:t,height:34});return H(()=>e.value,(i,a)=>{(i===a||i.length!==a.length||i.findIndex((n,o)=>n!==a[o])>=0)&&(r.value.length=i.length,i.forEach((n,o)=>{n!==r.value[o]&&r.value.splice(o,1,n)}))}),r}var qy=ge({name:"PickerView",props:jy,emits:["change","pickstart","pickend","update:value"],setup(e,t){var{slots:r,emit:i}=t,a=U(null),n=U(null),o=Pe(a,i),s=Yy(e),l=U(null),u=()=>{var _=l.value;s.height=_.$el.offsetHeight},f=U([]),v=U([]);function p(_){var b=v.value;if(b instanceof HTMLCollection)return Array.prototype.indexOf.call(b,_.el);var x=b.indexOf(_);return x!==-1?x:f.value.indexOf(_)}var d=function(_){var b=Q({get(){var x=p(_.vnode);return s.value[x]||0},set(x){var m=p(_.vnode);if(!(m<0)){var g=s.value[m];if(g!==x){s.value[m]=x;var c=s.value.map(h=>h);i("update:value",c),o("change",{},{value:c})}}}});return b};return Fe("getPickerViewColumn",d),Fe("pickerViewProps",e),Fe("pickerViewState",s),Qi(()=>{u(),v.value=n.value.children}),()=>{var _=r.default&&r.default();return I("uni-picker-view",{ref:a},[I(Or,{ref:l,onResize:b=>{var{height:x}=b;return s.height=x}},null,8,["onResize"]),I("div",{ref:n,class:"uni-picker-view-wrapper"},[_],512)],512)}}});class ih{constructor(t){this._drag=t,this._dragLog=Math.log(t),this._x=0,this._v=0,this._startTime=0}set(t,r){this._x=t,this._v=r,this._startTime=new Date().getTime()}setVelocityByEnd(t){this._v=(t-this._x)*this._dragLog/(Math.pow(this._drag,100)-1)}x(t){t===void 0&&(t=(new Date().getTime()-this._startTime)/1e3);var r=t===this._dt&&this._powDragDt?this._powDragDt:this._powDragDt=Math.pow(this._drag,t);return this._dt=t,this._x+this._v*r/this._dragLog-this._v/this._dragLog}dx(t){t===void 0&&(t=(new Date().getTime()-this._startTime)/1e3);var r=t===this._dt&&this._powDragDt?this._powDragDt:this._powDragDt=Math.pow(this._drag,t);return this._dt=t,this._v*r}done(){return Math.abs(this.dx())<3}reconfigure(t){var r=this.x(),i=this.dx();this._drag=t,this._dragLog=Math.log(t),this.set(r,i)}configuration(){var t=this;return[{label:"Friction",read:function(){return t._drag},write:function(r){t.reconfigure(r)},min:.001,max:.1,step:.001}]}}function ah(e,t,r){return e>t-r&&e0){var f=(-i-Math.sqrt(o))/(2*a),v=(-i+Math.sqrt(o))/(2*a),p=(r-f*t)/(v-f),d=t-p;return{x:function(g){var c,h;return g===this._t&&(c=this._powER1T,h=this._powER2T),this._t=g,c||(c=this._powER1T=Math.pow(Math.E,f*g)),h||(h=this._powER2T=Math.pow(Math.E,v*g)),d*c+p*h},dx:function(g){var c,h;return g===this._t&&(c=this._powER1T,h=this._powER2T),this._t=g,c||(c=this._powER1T=Math.pow(Math.E,f*g)),h||(h=this._powER2T=Math.pow(Math.E,v*g)),d*f*c+p*v*h}}}var _=Math.sqrt(4*a*n-i*i)/(2*a),b=-i/2*a,x=t,m=(r-b*t)/_;return{x:function(g){return Math.pow(Math.E,b*g)*(x*Math.cos(_*g)+m*Math.sin(_*g))},dx:function(g){var c=Math.pow(Math.E,b*g),h=Math.cos(_*g),w=Math.sin(_*g);return c*(m*_*h-x*_*w)+b*c*(m*w+x*h)}}}x(t){return t===void 0&&(t=(new Date().getTime()-this._startTime)/1e3),this._solution?this._endPosition+this._solution.x(t):0}dx(t){return t===void 0&&(t=(new Date().getTime()-this._startTime)/1e3),this._solution?this._solution.dx(t):0}setEnd(t,r,i){if(i||(i=new Date().getTime()),t!==this._endPosition||!Ir(r,.4)){r=r||0;var a=this._endPosition;this._solution&&(Ir(r,.4)&&(r=this._solution.dx((i-this._startTime)/1e3)),a=this._solution.x((i-this._startTime)/1e3),Ir(r,.4)&&(r=0),Ir(a,.4)&&(a=0),a+=this._endPosition),this._solution&&Ir(a-t,.4)&&Ir(r,.4)||(this._endPosition=t,this._solution=this._solve(a-this._endPosition,r),this._startTime=i)}}snap(t){this._startTime=new Date().getTime(),this._endPosition=t,this._solution={x:function(){return 0},dx:function(){return 0}}}done(t){return t||(t=new Date().getTime()),ah(this.x(),this._endPosition,.4)&&Ir(this.dx(),.4)}reconfigure(t,r,i){this._m=t,this._k=r,this._c=i,this.done()||(this._solution=this._solve(this.x()-this._endPosition,this.dx()),this._startTime=new Date().getTime())}springConstant(){return this._k}damping(){return this._c}configuration(){function t(i,a){i.reconfigure(1,a,i.damping())}function r(i,a){i.reconfigure(1,i.springConstant(),a)}return[{label:"Spring Constant",read:this.springConstant.bind(this),write:t.bind(this,this),min:100,max:1e3},{label:"Damping",read:this.damping.bind(this),write:r.bind(this,this),min:1,max:500}]}}class Xy{constructor(t,r,i){this._extent=t,this._friction=r||new ih(.01),this._spring=i||new nh(1,90,20),this._startTime=0,this._springing=!1,this._springOffset=0}snap(t,r){this._springOffset=0,this._springing=!0,this._spring.snap(t),this._spring.setEnd(r)}set(t,r){this._friction.set(t,r),t>0&&r>=0?(this._springOffset=0,this._springing=!0,this._spring.snap(t),this._spring.setEnd(0)):t<-this._extent&&r<=0?(this._springOffset=0,this._springing=!0,this._spring.snap(t),this._spring.setEnd(-this._extent)):this._springing=!1,this._startTime=new Date().getTime()}x(t){if(!this._startTime)return 0;if(t||(t=(new Date().getTime()-this._startTime)/1e3),this._springing)return this._spring.x()+this._springOffset;var r=this._friction.x(t),i=this.dx(t);return(r>0&&i>=0||r<-this._extent&&i<=0)&&(this._springing=!0,this._spring.setEnd(0,i),r<-this._extent?this._springOffset=-this._extent:this._springOffset=0,r=this._spring.x()+this._springOffset),r}dx(t){var r;return this._lastTime===t?r=this._lastDx:r=this._springing?this._spring.dx(t):this._friction.dx(t),this._lastTime=t,this._lastDx=r,r}done(){return this._springing?this._spring.done():this._friction.done()}setVelocityByEnd(t){this._friction.setVelocityByEnd(t)}configuration(){var t=this._friction.configuration();return t.push.apply(t,this._spring.configuration()),t}}function Zy(e,t,r){var i={id:0,cancelled:!1};function a(o,s,l,u){if(!o||!o.cancelled){l(s);var f=s.done();f||o.cancelled||(o.id=requestAnimationFrame(a.bind(null,o,s,l,u))),f&&u&&u(s)}}function n(o){o&&o.id&&cancelAnimationFrame(o.id),o&&(o.cancelled=!0)}return a(i,e,t,r),{cancel:n.bind(null,i),model:e}}class Ky{constructor(t,r){r=r||{},this._element=t,this._options=r,this._enableSnap=r.enableSnap||!1,this._itemSize=r.itemSize||0,this._enableX=r.enableX||!1,this._enableY=r.enableY||!1,this._shouldDispatchScrollEvent=!!r.onScroll,this._enableX?(this._extent=(r.scrollWidth||this._element.offsetWidth)-this._element.parentElement.offsetWidth,this._scrollWidth=r.scrollWidth):(this._extent=(r.scrollHeight||this._element.offsetHeight)-this._element.parentElement.offsetHeight,this._scrollHeight=r.scrollHeight),this._position=0,this._scroll=new Xy(this._extent,r.friction,r.spring),this._onTransitionEnd=this.onTransitionEnd.bind(this),this.updatePosition()}onTouchStart(){this._startPosition=this._position,this._lastChangePos=this._startPosition,this._startPosition>0?this._startPosition/=.5:this._startPosition<-this._extent&&(this._startPosition=(this._startPosition+this._extent)/.5-this._extent),this._animation&&(this._animation.cancel(),this._scrolling=!1),this.updatePosition()}onTouchMove(t,r){var i=this._startPosition;this._enableX?i+=t:this._enableY&&(i+=r),i>0?i*=.5:i<-this._extent&&(i=.5*(i+this._extent)-this._extent),this._position=i,this.updatePosition(),this.dispatchScroll()}onTouchEnd(t,r,i){if(this._enableSnap&&this._position>-this._extent&&this._position<0){if(this._enableY&&(Math.abs(r)this._itemSize/2?n-(this._itemSize-Math.abs(o)):n-o,a<=0&&a>=-this._extent&&this._scroll.setVelocityByEnd(a)}this._lastTime=Date.now(),this._lastDelay=0,this._scrolling=!0,this._lastChangePos=this._position,this._lastIdx=Math.floor(Math.abs(this._position/this._itemSize)),this._animation=Zy(this._scroll,()=>{var s=Date.now(),l=(s-this._scroll._startTime)/1e3,u=this._scroll.x(l);this._position=u,this.updatePosition();var f=this._scroll.dx(l);this._shouldDispatchScrollEvent&&s-this._lastTime>this._lastDelay&&(this.dispatchScroll(),this._lastDelay=Math.abs(2e3/f),this._lastTime=s)},()=>{this._enableSnap&&(a<=0&&a>=-this._extent&&(this._position=a,this.updatePosition()),typeof this._options.onSnap=="function"&&this._options.onSnap(Math.floor(Math.abs(this._position)/this._itemSize))),this._shouldDispatchScrollEvent&&this.dispatchScroll(),this._scrolling=!1})}onTransitionEnd(){this._element.style.webkitTransition="",this._element.style.transition="",this._element.removeEventListener("transitionend",this._onTransitionEnd),this._snapping&&(this._snapping=!1),this.dispatchScroll()}snap(){var t=this._itemSize,r=this._position%t,i=Math.abs(r)>this._itemSize/2?this._position-(t-Math.abs(r)):this._position-r;this._position!==i&&(this._snapping=!0,this.scrollTo(-i),typeof this._options.onSnap=="function"&&this._options.onSnap(Math.floor(Math.abs(this._position)/this._itemSize)))}scrollTo(t,r){this._animation&&(this._animation.cancel(),this._scrolling=!1),typeof t=="number"&&(this._position=-t),this._position<-this._extent?this._position=-this._extent:this._position>0&&(this._position=0);var i="transform "+(r||.2)+"s ease-out";this._element.style.webkitTransition="-webkit-"+i,this._element.style.transition=i,this.updatePosition(),this._element.addEventListener("transitionend",this._onTransitionEnd)}dispatchScroll(){if(typeof this._options.onScroll=="function"&&Math.round(Number(this._lastPos))!==Math.round(this._position)){this._lastPos=this._position;var t={target:{scrollLeft:this._enableX?-this._position:0,scrollTop:this._enableY?-this._position:0,scrollHeight:this._scrollHeight||this._element.offsetHeight,scrollWidth:this._scrollWidth||this._element.offsetWidth,offsetHeight:this._element.parentElement.offsetHeight,offsetWidth:this._element.parentElement.offsetWidth}};this._options.onScroll(t)}}update(t,r,i){var a=0,n=this._position;this._enableX?(a=this._element.childNodes.length?(r||this._element.offsetWidth)-this._element.parentElement.offsetWidth:0,this._scrollWidth=r):(a=this._element.childNodes.length?(r||this._element.offsetHeight)-this._element.parentElement.offsetHeight:0,this._scrollHeight=r),typeof t=="number"&&(this._position=-t),this._position<-a?this._position=-a:this._position>0&&(this._position=0),this._itemSize=i||this._itemSize,this.updatePosition(),n!==this._position&&(this.dispatchScroll(),typeof this._options.onSnap=="function"&&this._options.onSnap(Math.floor(Math.abs(this._position)/this._itemSize))),this._extent=a,this._scroll._extent=a}updatePosition(){var t="";this._enableX?t="translateX("+this._position+"px) translateZ(0)":this._enableY&&(t="translateY("+this._position+"px) translateZ(0)"),this._element.style.webkitTransform=t,this._element.style.transform=t}isScrolling(){return this._scrolling||this._snapping}}function Gy(e,t){var r={trackingID:-1,maxDy:0,maxDx:0},i=new Ky(e,t);function a(l){var u=l,f=l;return u.detail.state==="move"||u.detail.state==="end"?{x:u.detail.dx,y:u.detail.dy}:{x:f.screenX-r.x,y:f.screenY-r.y}}function n(l){var u=l,f=l;u.detail.state==="start"?(r.trackingID="touch",r.x=u.detail.x,r.y=u.detail.y):(r.trackingID="mouse",r.x=f.screenX,r.y=f.screenY),r.maxDx=0,r.maxDy=0,r.historyX=[0],r.historyY=[0],r.historyTime=[u.detail.timeStamp||f.timeStamp],r.listener=i,i.onTouchStart&&i.onTouchStart(),l.preventDefault()}function o(l){var u=l,f=l;if(r.trackingID!==-1){l.preventDefault();var v=a(l);if(v){for(r.maxDy=Math.max(r.maxDy,Math.abs(v.y)),r.maxDx=Math.max(r.maxDx,Math.abs(v.x)),r.historyX.push(v.x),r.historyY.push(v.y),r.historyTime.push(u.detail.timeStamp||f.timeStamp);r.historyTime.length>10;)r.historyTime.shift(),r.historyX.shift(),r.historyY.shift();r.listener&&r.listener.onTouchMove&&r.listener.onTouchMove(v.x,v.y)}}}function s(l){if(r.trackingID!==-1){l.preventDefault();var u=a(l);if(u){var f=r.listener;r.trackingID=-1,r.listener=null;var v=r.historyTime.length,p={x:0,y:0};if(v>2)for(var d=r.historyTime.length-1,_=r.historyTime[d],b=r.historyX[d],x=r.historyY[d];d>0;){d--;var m=r.historyTime[d],g=_-m;if(g>30&&g<50){p.x=(b-r.historyX[d])/(g/1e3),p.y=(x-r.historyY[d])/(g/1e3);break}}r.historyTime=[],r.historyX=[],r.historyY=[],f&&f.onTouchEnd&&f.onTouchEnd(u.x,u.y,p)}}}return{scroller:i,handleTouchStart:n,handleTouchMove:o,handleTouchEnd:s}}var Jy=0;function Qy(e){var t="uni-picker-view-content-".concat(Jy++);function r(){var i=document.createElement("style");i.innerText=".uni-picker-view-content.".concat(t,">*{height: ").concat(e.value,"px;overflow: hidden;}"),document.head.appendChild(i)}return H(()=>e.value,r),t}function eS(e){var t=20,r=0,i=0;e.addEventListener("touchstart",a=>{var n=a.changedTouches[0];r=n.clientX,i=n.clientY}),e.addEventListener("touchend",a=>{var n=a.changedTouches[0];if(Math.abs(n.clientX-r){s[u]=n[u]}),a.target.dispatchEvent(s)}})}var tS=ge({name:"PickerViewColumn",setup(e,t){var{slots:r,emit:i}=t,a=U(null),n=U(null),o=_e("getPickerViewColumn"),s=jt(),l=o?o(s):U(0),u=_e("pickerViewProps"),f=_e("pickerViewState"),v=U(34),p=U(null),d=()=>{var O=p.value;v.value=O.$el.offsetHeight},_=Q(()=>(f.height-v.value)/2),{state:b}=Vd(),x=Qy(v),m,g=Ae({current:l.value,length:0}),c;function h(){m&&!c&&(c=!0,Vr(()=>{c=!1;var O=Math.min(g.current,g.length-1);O=Math.max(O,0),m.update(O*v.value,void 0,v.value)}))}H(()=>l.value,O=>{O!==g.current&&(g.current=O,h())}),H(()=>g.current,O=>l.value=O),H([()=>v.value,()=>g.length,()=>f.height],h);var w=0;function y(O){var N=w+O.deltaY;if(Math.abs(N)>10){w=0;var R=Math.min(g.current+(N<0?-1:1),g.length-1);g.current=R=Math.max(R,0),m.scrollTo(R*v.value)}else w=N;O.preventDefault()}function C(O){var{clientY:N}=O,R=a.value;if(!m.isScrolling()){var Y=R.getBoundingClientRect(),ue=N-Y.top-f.height/2,M=v.value/2;if(!(Math.abs(ue)<=M)){var B=Math.ceil((Math.abs(ue)-M)/v.value),J=ue<0?-B:B,te=Math.min(g.current+J,g.length-1);g.current=te=Math.max(te,0),m.scrollTo(te*v.value)}}}var E=()=>{var O=a.value,N=n.value,{scroller:R,handleTouchStart:Y,handleTouchMove:ue,handleTouchEnd:M}=Gy(N,{enableY:!0,enableX:!1,enableSnap:!0,itemSize:v.value,friction:new ih(1e-4),spring:new nh(2,90,20),onSnap:B=>{!isNaN(B)&&B!==g.current&&(g.current=B)}});m=R,Dn(O,B=>{switch(B.detail.state){case"start":Y(B),ar({disable:!0});break;case"move":ue(B),B.stopPropagation();break;case"end":case"cancel":M(B),ar({disable:!1})}},!0),eS(O),Nn(),h()};return Qi(()=>{g.length=n.value.children.length,d(),E()}),()=>{var O=r.default&&r.default(),N="".concat(_.value,"px 0");return I("uni-picker-view-column",{ref:a},[I("div",{onWheel:y,onClick:C,class:"uni-picker-view-group"},[I("div",Qe(b.attrs,{class:["uni-picker-view-mask",u.maskClass],style:"background-size: 100% ".concat(_.value,"px;").concat(u.maskStyle)}),null,16),I("div",Qe(b.attrs,{class:["uni-picker-view-indicator",u.indicatorClass],style:u.indicatorStyle}),[I(Or,{ref:p,onResize:R=>{var{height:Y}=R;return v.value=Y}},null,8,["onResize"])],16),I("div",{ref:n,class:["uni-picker-view-content",x],style:{padding:N}},[O],6)],40,["onWheel","onClick"])],512)}}}),kr={activeColor:Ia,backgroundColor:"#EBEBEB",activeMode:"backwards"},rS={percent:{type:[Number,String],default:0,validator(e){return!isNaN(parseFloat(e))}},showInfo:{type:[Boolean,String],default:!1},strokeWidth:{type:[Number,String],default:6,validator(e){return!isNaN(parseFloat(e))}},color:{type:String,default:kr.activeColor},activeColor:{type:String,default:kr.activeColor},backgroundColor:{type:String,default:kr.backgroundColor},active:{type:[Boolean,String],default:!1},activeMode:{type:String,default:kr.activeMode},duration:{type:[Number,String],default:30,validator(e){return!isNaN(parseFloat(e))}}},iS=ge({name:"Progress",props:rS,setup(e){var t=aS(e);return oh(t,e),H(()=>t.realPercent,(r,i)=>{t.strokeTimer&&clearInterval(t.strokeTimer),t.lastPercent=i||0,oh(t,e)}),()=>{var{showInfo:r}=e,{outerBarStyle:i,innerBarStyle:a,currentPercent:n}=t;return I("uni-progress",{class:"uni-progress"},[I("div",{style:i,class:"uni-progress-bar"},[I("div",{style:a,class:"uni-progress-inner-bar"},null,4)],4),r?I("p",{class:"uni-progress-info"},[n+"%"]):""])}}});function aS(e){var t=U(0),r=Q(()=>"background-color: ".concat(e.backgroundColor,"; height: ").concat(e.strokeWidth,"px;")),i=Q(()=>{var o=e.color!==kr.activeColor&&e.activeColor===kr.activeColor?e.color:e.activeColor;return"width: ".concat(t.value,"%;background-color: ").concat(o)}),a=Q(()=>{var o=parseFloat(e.percent);return o<0&&(o=0),o>100&&(o=100),o}),n=Ae({outerBarStyle:r,innerBarStyle:i,realPercent:a,currentPercent:t,strokeTimer:0,lastPercent:0});return n}function oh(e,t){t.active?(e.currentPercent=t.activeMode===kr.activeMode?0:e.lastPercent,e.strokeTimer=setInterval(()=>{e.currentPercent+1>e.realPercent?(e.currentPercent=e.realPercent,e.strokeTimer&&clearInterval(e.strokeTimer)):e.currentPercent+=1},parseFloat(t.duration))):e.currentPercent=e.realPercent}var sh=on("ucg"),nS={name:{type:String,default:""}},oS=ge({name:"RadioGroup",props:nS,setup(e,t){var{emit:r,slots:i}=t,a=U(null),n=Pe(a,r);return sS(e,n),()=>I("uni-radio-group",{ref:a},[i.default&&i.default()],512)}});function sS(e,t){var r=[];Re(()=>{s(r.length-1)});var i=()=>{var l;return(l=r.find(u=>u.value.radioChecked))===null||l===void 0?void 0:l.value.value};Fe(sh,{addField(l){r.push(l)},removeField(l){r.splice(r.indexOf(l),1)},radioChange(l,u){var f=r.indexOf(u);s(f,!0),t("change",l,{value:i()})}});var a=_e(At,!1),n={submit:()=>{var l=["",null];return e.name!==""&&(l[0]=e.name,l[1]=i()),l}};a&&(a.addField(n),Ce(()=>{a.removeField(n)}));function o(l,u){l.value={radioChecked:u,value:l.value.value}}function s(l,u){r.forEach((f,v)=>{v!==l&&(u?o(r[v],!1):r.forEach((p,d)=>{v>=d||r[d].value.radioChecked&&o(r[v],!1)}))})}return r}var lS={checked:{type:[Boolean,String],default:!1},id:{type:String,default:""},disabled:{type:[Boolean,String],default:!1},color:{type:String,default:"#007aff"},value:{type:String,default:""}},uS=ge({name:"Radio",props:lS,setup(e,t){var{slots:r}=t,i=U(e.checked),a=U(e.value),n=Q(()=>"background-color: ".concat(e.color,";border-color: ").concat(e.color,";"));H([()=>e.checked,()=>e.value],v=>{var[p,d]=v;i.value=p,a.value=d});var o=()=>{i.value=!1},{uniCheckGroup:s,uniLabel:l,field:u}=fS(i,a,o),f=v=>{e.disabled||(i.value=!0,s&&s.radioChange(v,u))};return l&&(l.addHandler(f),Ce(()=>{l.removeHandler(f)})),An(e,{"label-click":f}),()=>{var v=qi(e,"disabled");return I("uni-radio",Qe(v,{onClick:f}),[I("div",{class:"uni-radio-wrapper"},[I("div",{class:["uni-radio-input",{"uni-radio-input-disabled":e.disabled}],style:i.value?n.value:""},[i.value?ln(sn,"#fff",18):""],6),r.default&&r.default()])],16,["onClick"])}}});function fS(e,t,r){var i=Q({get:()=>({radioChecked:Boolean(e.value),value:t.value}),set:l=>{var{radioChecked:u}=l;e.value=u}}),a={reset:r},n=_e(sh,!1);n&&n.addField(i);var o=_e(At,!1);o&&o.addField(a);var s=_e(Xi,!1);return Ce(()=>{n&&n.removeField(i),o&&o.removeField(a)}),{uniCheckGroup:n,uniForm:o,uniLabel:s,field:i}}function cS(e){return e.replace(/<\?xml.*\?>\n/,"").replace(/\n/,"").replace(/\n/,"")}function vS(e){return e.reduce(function(t,r){var i=r.value,a=r.name;return i.match(/ /)&&a!=="style"&&(i=i.split(" ")),t[a]?Array.isArray(t[a])?t[a].push(i):t[a]=[t[a],i]:t[a]=i,t},{})}function dS(e){e=cS(e);var t=[],r={node:"root",children:[]};return $d(e,{start:function(i,a,n){var o={name:i};if(a.length!==0&&(o.attrs=vS(a)),n){var s=t[0]||r;s.children||(s.children=[]),s.children.push(o)}else t.unshift(o)},end:function(i){var a=t.shift();if(a.name!==i&&console.error("invalid state: mismatch end tag"),t.length===0)r.children.push(a);else{var n=t[0];n.children||(n.children=[]),n.children.push(a)}},chars:function(i){var a={type:"text",text:i};if(t.length===0)r.children.push(a);else{var n=t[0];n.children||(n.children=[]),n.children.push(a)}},comment:function(i){var a={node:"comment",text:i},n=t[0];n.children||(n.children=[]),n.children.push(a)}}),r.children}var lh={a:"",abbr:"",address:"",article:"",aside:"",b:"",bdi:"",bdo:["dir"],big:"",blockquote:"",br:"",caption:"",center:"",cite:"",code:"",col:["span","width"],colgroup:["span","width"],dd:"",del:"",div:"",dl:"",dt:"",em:"",fieldset:"",font:"",footer:"",h1:"",h2:"",h3:"",h4:"",h5:"",h6:"",header:"",hr:"",i:"",img:["alt","src","height","width"],ins:"",label:"",legend:"",li:"",mark:"",nav:"",ol:["start","type"],p:"",pre:"",q:"",rt:"",ruby:"",s:"",section:"",small:"",span:"",strong:"",sub:"",sup:"",table:["width"],tbody:"",td:["colspan","height","rowspan","width"],tfoot:"",th:["colspan","height","rowspan","width"],thead:"",tr:["colspan","height","rowspan","width"],tt:"",u:"",ul:""},wl={amp:"&",gt:">",lt:"<",nbsp:" ",quot:'"',apos:"'"};function hS(e){return e.replace(/&(([a-zA-Z]+)|(#x{0,1}[\da-zA-Z]+));/gi,function(t,r){if(re(wl,r)&&wl[r])return wl[r];if(/^#[0-9]{1,4}$/.test(r))return String.fromCharCode(r.slice(1));if(/^#x[0-9a-f]{1,4}$/i.test(r))return String.fromCharCode("0"+r.slice(1));var i=document.createElement("div");return i.innerHTML=t,i.innerText||i.textContent})}function gS(e,t,r){return e==="img"&&t==="src"?vt(r):r}function uh(e,t,r,i){return e.forEach(function(a){if(!!mt(a))if(!re(a,"type")||a.type==="node"){if(!(typeof a.name=="string"&&a.name))return;var n=a.name.toLowerCase();if(!re(lh,n))return;var o=document.createElement(n);if(!o)return;var s=a.attrs;if(mt(s)){var l=lh[n]||[];Object.keys(s).forEach(function(f){var v=s[f];switch(f){case"class":Array.isArray(v)&&(v=v.join(" "));case"style":o.setAttribute(f,v),r&&o.setAttribute(r,"");break;default:l.indexOf(f)!==-1&&o.setAttribute(f,gS(n,f,v))}})}pS(a,o,i);var u=a.children;Array.isArray(u)&&u.length&&uh(a.children,o,r,i),t.appendChild(o)}else a.type==="text"&&typeof a.text=="string"&&a.text!==""&&t.appendChild(document.createTextNode(hS(a.text)))}),t}function pS(e,t,r){["a","img"].includes(e.name)&&r&&(t.setAttribute("onClick","return false;"),t.addEventListener("click",i=>{r(i,{node:e}),i.stopPropagation()},!0))}var mS={nodes:{type:[Array,String],default:function(){return[]}}},_S=ge({name:"RichText",compatConfig:{MODE:3},props:mS,emits:["click","touchstart","touchmove","touchcancel","touchend","longpress"],setup(e,t){var{emit:r,attrs:i}=t,a=jt(),n=U(null),o=Pe(n,r),s=!!i.onItemclick;function l(f){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};o("itemclick",f,v)}function u(f){var v;typeof f=="string"&&(f=dS(f));var p=uh(f,document.createDocumentFragment(),(a==null||(v=a.root)===null||v===void 0?void 0:v.type).__scopeId||"",s&&l);n.value.firstElementChild.innerHTML="",n.value.firstElementChild.appendChild(p)}return H(()=>e.nodes,f=>{u(f)}),Re(()=>{u(e.nodes)}),()=>I("uni-rich-text",{ref:n},[I("div",null,null)],512)}}),xl=Co(!0),bS={scrollX:{type:[Boolean,String],default:!1},scrollY:{type:[Boolean,String],default:!1},upperThreshold:{type:[Number,String],default:50},lowerThreshold:{type:[Number,String],default:50},scrollTop:{type:[Number,String],default:0},scrollLeft:{type:[Number,String],default:0},scrollIntoView:{type:String,default:""},scrollWithAnimation:{type:[Boolean,String],default:!1},enableBackToTop:{type:[Boolean,String],default:!1},refresherEnabled:{type:[Boolean,String],default:!1},refresherThreshold:{type:Number,default:45},refresherDefaultStyle:{type:String,default:"back"},refresherBackground:{type:String,default:"#fff"},refresherTriggered:{type:[Boolean,String],default:!1}},wS=ge({name:"ScrollView",compatConfig:{MODE:3},props:bS,emits:["scroll","scrolltoupper","scrolltolower","refresherrefresh","refresherrestore","refresherpulling","refresherabort","update:refresherTriggered"],setup(e,t){var{emit:r,slots:i}=t,a=U(null),n=U(null),o=U(null),s=U(null),l=U(null),u=Pe(a,r),{state:f,scrollTopNumber:v,scrollLeftNumber:p}=xS(e);yS(e,f,v,p,u,a,n,s,r);var d=Q(()=>{var _="";return e.scrollX?_+="overflow-x:auto;":_+="overflow-x:hidden;",e.scrollY?_+="overflow-y:auto;":_+="overflow-y:hidden;",_});return()=>{var{refresherEnabled:_,refresherBackground:b,refresherDefaultStyle:x}=e,{refresherHeight:m,refreshState:g,refreshRotate:c}=f;return I("uni-scroll-view",{ref:a},[I("div",{ref:o,class:"uni-scroll-view"},[I("div",{ref:n,style:d.value,class:"uni-scroll-view"},[I("div",{ref:s,class:"uni-scroll-view-content"},[_?I("div",{ref:l,style:{backgroundColor:b,height:m+"px"},class:"uni-scroll-view-refresher"},[x!=="none"?I("div",{class:"uni-scroll-view-refresh"},[I("div",{class:"uni-scroll-view-refresh-inner"},[g=="pulling"?I("svg",{key:"refresh__icon",style:{transform:"rotate("+c+"deg)"},fill:"#2BD009",class:"uni-scroll-view-refresh__icon",width:"24",height:"24",viewBox:"0 0 24 24"},[I("path",{d:"M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"},null),I("path",{d:"M0 0h24v24H0z",fill:"none"},null)],4):null,g=="refreshing"?I("svg",{key:"refresh__spinner",class:"uni-scroll-view-refresh__spinner",width:"24",height:"24",viewBox:"25 25 50 50"},[I("circle",{cx:"50",cy:"50",r:"20",fill:"none",style:"color: #2bd009","stroke-width":"3"},null)]):null])]):null,x=="none"?i.refresher&&i.refresher():null],4):null,i.default&&i.default()],512)],4)],512)],512)}}});function xS(e){var t=Q(()=>Number(e.scrollTop)||0),r=Q(()=>Number(e.scrollLeft)||0),i=Ae({lastScrollTop:t.value,lastScrollLeft:r.value,lastScrollToUpperTime:0,lastScrollToLowerTime:0,refresherHeight:0,refreshRotate:0,refreshState:""});return{state:i,scrollTopNumber:t,scrollLeftNumber:r}}function yS(e,t,r,i,a,n,o,s,l){var u=!1,f=0,v=!1,p=()=>{},d=Q(()=>{var y=Number(e.upperThreshold);return isNaN(y)?50:y}),_=Q(()=>{var y=Number(e.lowerThreshold);return isNaN(y)?50:y});function b(y,C){var E=o.value,O=0,N="";if(y<0?y=0:C==="x"&&y>E.scrollWidth-E.offsetWidth?y=E.scrollWidth-E.offsetWidth:C==="y"&&y>E.scrollHeight-E.offsetHeight&&(y=E.scrollHeight-E.offsetHeight),C==="x"?O=E.scrollLeft-y:C==="y"&&(O=E.scrollTop-y),O!==0){var R=s.value;R.style.transition="transform .3s ease-out",R.style.webkitTransition="-webkit-transform .3s ease-out",C==="x"?N="translateX("+O+"px) translateZ(0)":C==="y"&&(N="translateY("+O+"px) translateZ(0)"),R.removeEventListener("transitionend",p),R.removeEventListener("webkitTransitionEnd",p),p=()=>h(y,C),R.addEventListener("transitionend",p),R.addEventListener("webkitTransitionEnd",p),C==="x"?E.style.overflowX="hidden":C==="y"&&(E.style.overflowY="hidden"),R.style.transform=N,R.style.webkitTransform=N}}function x(y){var C=y.target;a("scroll",y,{scrollLeft:C.scrollLeft,scrollTop:C.scrollTop,scrollHeight:C.scrollHeight,scrollWidth:C.scrollWidth,deltaX:t.lastScrollLeft-C.scrollLeft,deltaY:t.lastScrollTop-C.scrollTop}),e.scrollY&&(C.scrollTop<=d.value&&t.lastScrollTop-C.scrollTop>0&&y.timeStamp-t.lastScrollToUpperTime>200&&(a("scrolltoupper",y,{direction:"top"}),t.lastScrollToUpperTime=y.timeStamp),C.scrollTop+C.offsetHeight+_.value>=C.scrollHeight&&t.lastScrollTop-C.scrollTop<0&&y.timeStamp-t.lastScrollToLowerTime>200&&(a("scrolltolower",y,{direction:"bottom"}),t.lastScrollToLowerTime=y.timeStamp)),e.scrollX&&(C.scrollLeft<=d.value&&t.lastScrollLeft-C.scrollLeft>0&&y.timeStamp-t.lastScrollToUpperTime>200&&(a("scrolltoupper",y,{direction:"left"}),t.lastScrollToUpperTime=y.timeStamp),C.scrollLeft+C.offsetWidth+_.value>=C.scrollWidth&&t.lastScrollLeft-C.scrollLeft<0&&y.timeStamp-t.lastScrollToLowerTime>200&&(a("scrolltolower",y,{direction:"right"}),t.lastScrollToLowerTime=y.timeStamp)),t.lastScrollTop=C.scrollTop,t.lastScrollLeft=C.scrollLeft}function m(y){e.scrollY&&(e.scrollWithAnimation?b(y,"y"):o.value.scrollTop=y)}function g(y){e.scrollX&&(e.scrollWithAnimation?b(y,"x"):o.value.scrollLeft=y)}function c(y){if(y){if(!/^[_a-zA-Z][-_a-zA-Z0-9:]*$/.test(y)){console.error("id error: scroll-into-view=".concat(y));return}var C=n.value.querySelector("#"+y);if(C){var E=o.value.getBoundingClientRect(),O=C.getBoundingClientRect();if(e.scrollX){var N=O.left-E.left,R=o.value.scrollLeft,Y=R+N;e.scrollWithAnimation?b(Y,"x"):o.value.scrollLeft=Y}if(e.scrollY){var ue=O.top-E.top,M=o.value.scrollTop,B=M+ue;e.scrollWithAnimation?b(B,"y"):o.value.scrollTop=B}}}}function h(y,C){s.value.style.transition="",s.value.style.webkitTransition="",s.value.style.transform="",s.value.style.webkitTransform="";var E=o.value;C==="x"?(E.style.overflowX=e.scrollX?"auto":"hidden",E.scrollLeft=y):C==="y"&&(E.style.overflowY=e.scrollY?"auto":"hidden",E.scrollTop=y),s.value.removeEventListener("transitionend",p),s.value.removeEventListener("webkitTransitionEnd",p)}function w(y){switch(y){case"refreshing":t.refresherHeight=e.refresherThreshold,u||(u=!0,a("refresherrefresh",{},{}),l("update:refresherTriggered",!0));break;case"restore":case"refresherabort":u=!1,t.refresherHeight=f=0,y==="restore"&&(v=!1,a("refresherrestore",{},{})),y==="refresherabort"&&v&&(v=!1,a("refresherabort",{},{}));break}t.refreshState=y}Re(()=>{Vr(()=>{m(r.value),g(i.value)}),c(e.scrollIntoView);var y=function(Y){Y.stopPropagation(),x(Y)},C={x:0,y:0},E=null,O=function(Y){var ue=Y.touches[0].pageX,M=Y.touches[0].pageY,B=o.value;if(Math.abs(ue-C.x)>Math.abs(M-C.y))if(e.scrollX){if(B.scrollLeft===0&&ue>C.x){E=!1;return}else if(B.scrollWidth===B.offsetWidth+B.scrollLeft&&ueC.y)E=!1,e.refresherEnabled&&Y.cancelable!==!1&&Y.preventDefault();else if(B.scrollHeight===B.offsetHeight+B.scrollTop&&M0&&(v=!0,a("refresherpulling",Y,{deltaY:J})));var te=t.refresherHeight/e.refresherThreshold;t.refreshRotate=(te>1?1:te)*360}},N=function(Y){Y.touches.length===1&&(ar({disable:!0}),C={x:Y.touches[0].pageX,y:Y.touches[0].pageY})},R=function(Y){C={x:0,y:0},ar({disable:!1}),t.refresherHeight>=e.refresherThreshold?w("refreshing"):w("refresherabort")};o.value.addEventListener("touchstart",N,xl),o.value.addEventListener("touchmove",O),o.value.addEventListener("scroll",y,xl),o.value.addEventListener("touchend",R,xl),Nn(),Ce(()=>{o.value.removeEventListener("touchstart",N),o.value.removeEventListener("touchmove",O),o.value.removeEventListener("scroll",y),o.value.removeEventListener("touchend",R)})}),ts(()=>{e.scrollY&&(o.value.scrollTop=t.lastScrollTop),e.scrollX&&(o.value.scrollLeft=t.lastScrollLeft)}),H(r,y=>{m(y)}),H(i,y=>{g(y)}),H(()=>e.scrollIntoView,y=>{c(y)}),H(()=>e.refresherTriggered,y=>{y===!0?w("refreshing"):y===!1&&w("restore")})}var SS={name:{type:String,default:""},min:{type:[Number,String],default:0},max:{type:[Number,String],default:100},value:{type:[Number,String],default:0},step:{type:[Number,String],default:1},disabled:{type:[Boolean,String],default:!1},color:{type:String,default:"#e9e9e9"},backgroundColor:{type:String,default:"#e9e9e9"},activeColor:{type:String,default:"#007aff"},selectedColor:{type:String,default:"#007aff"},blockColor:{type:String,default:"#ffffff"},blockSize:{type:[Number,String],default:28},showValue:{type:[Boolean,String],default:!1}},ES=ge({name:"Slider",props:SS,emits:["changing","change"],setup(e,t){var{emit:r}=t,i=U(null),a=U(null),n=U(null),o=U(Number(e.value));H(()=>e.value,v=>{o.value=Number(v)});var s=Pe(i,r),l=TS(e,o),{_onClick:u,_onTrack:f}=CS(e,o,i,a,s);return Re(()=>{Dn(n.value,f)}),()=>{var{setBgColor:v,setBlockBg:p,setActiveColor:d,setBlockStyle:_}=l;return I("uni-slider",{ref:i,onClick:Cr(u)},[I("div",{class:"uni-slider-wrapper"},[I("div",{class:"uni-slider-tap-area"},[I("div",{style:v.value,class:"uni-slider-handle-wrapper"},[I("div",{ref:n,style:p.value,class:"uni-slider-handle"},null,4),I("div",{style:_.value,class:"uni-slider-thumb"},null,4),I("div",{style:d.value,class:"uni-slider-track"},null,4)],4)]),wi(I("span",{ref:a,class:"uni-slider-value"},[o.value],512),[[Ai,e.showValue]])]),I("slot",null,null)],8,["onClick"])}}});function TS(e,t){var r=()=>{var o=Number(e.max),s=Number(e.min);return 100*(t.value-s)/(o-s)+"%"},i=()=>e.backgroundColor!=="#e9e9e9"?e.backgroundColor:e.color!=="#007aff"?e.color:"#007aff",a=()=>e.activeColor!=="#007aff"?e.activeColor:e.selectedColor!=="#e9e9e9"?e.selectedColor:"#e9e9e9",n={setBgColor:Q(()=>({backgroundColor:i()})),setBlockBg:Q(()=>({left:r()})),setActiveColor:Q(()=>({backgroundColor:a(),width:r()})),setBlockStyle:Q(()=>({width:e.blockSize+"px",height:e.blockSize+"px",marginLeft:-e.blockSize/2+"px",marginTop:-e.blockSize/2+"px",left:r(),backgroundColor:e.blockColor}))};return n}function CS(e,t,r,i,a){var n=v=>{e.disabled||(s(v),a("change",v,{value:t.value}))},o=v=>{var p=Number(e.max),d=Number(e.min),_=Number(e.step);return vp?p:OS.mul.call(Math.round((v-d)/_),_)+d},s=v=>{var p=Number(e.max),d=Number(e.min),_=i.value,b=getComputedStyle(_,null).marginLeft,x=_.offsetWidth;x=x+parseInt(b);var m=r.value,g=m.offsetWidth-(e.showValue?x:0),c=m.getBoundingClientRect().left,h=(v.x-c)*(p-d)/g+d;t.value=o(h)},l=v=>{if(!e.disabled)return v.detail.state==="move"?(s({x:v.detail.x}),a("changing",v,{value:t.value}),!1):v.detail.state==="end"&&a("change",v,{value:t.value})},u=_e(At,!1);if(u){var f={reset:()=>t.value=Number(e.min),submit:()=>{var v=["",null];return e.name!==""&&(v[0]=e.name,v[1]=t.value),v}};u.addField(f),Ce(()=>{u.removeField(f)})}return{_onClick:n,_onTrack:l}}var OS={mul:function(e){var t=0,r=this.toString(),i=e.toString();try{t+=r.split(".")[1].length}catch(a){}try{t+=i.split(".")[1].length}catch(a){}return Number(r.replace(".",""))*Number(i.replace(".",""))/Math.pow(10,t)}},AS={indicatorDots:{type:[Boolean,String],default:!1},vertical:{type:[Boolean,String],default:!1},autoplay:{type:[Boolean,String],default:!1},circular:{type:[Boolean,String],default:!1},interval:{type:[Number,String],default:5e3},duration:{type:[Number,String],default:500},current:{type:[Number,String],default:0},indicatorColor:{type:String,default:""},indicatorActiveColor:{type:String,default:""},previousMargin:{type:String,default:""},nextMargin:{type:String,default:""},currentItemId:{type:String,default:""},skipHiddenItemLayout:{type:[Boolean,String],default:!1},displayMultipleItems:{type:[Number,String],default:1},disableTouch:{type:[Boolean,String],default:!1}};function IS(e){var t=Q(()=>{var n=Number(e.interval);return isNaN(n)?5e3:n}),r=Q(()=>{var n=Number(e.duration);return isNaN(n)?500:n}),i=Q(()=>{var n=Math.round(e.displayMultipleItems);return isNaN(n)?1:n}),a=Ae({interval:t,duration:r,displayMultipleItems:i,current:Math.round(e.current)||0,currentItemId:e.currentItemId,userTracking:!1});return a}function kS(e,t,r,i,a,n){function o(){s&&(clearTimeout(s),s=null)}var s=null,l=!0,u=0,f=1,v=null,p=!1,d=0,_,b="",x,m=Q(()=>e.circular&&r.value.length>t.displayMultipleItems);function g(M){if(!l)for(var B=r.value,J=B.length,te=M+t.displayMultipleItems,W=0;W=ee.length&&(M-=ee.length),M=_%1>.5||_<0?M-1:M,n("transition",{},{dx:e.vertical?0:M*W.offsetWidth,dy:e.vertical?M*W.offsetHeight:0})}function h(){v&&(c(v.toPos),v=null)}function w(M){var B=r.value.length;if(!B)return-1;var J=(Math.round(M)%B+B)%B;if(m.value){if(B<=t.displayMultipleItems)return 0}else if(J>B-t.displayMultipleItems)return B-t.displayMultipleItems;return J}function y(){v=null}function C(){if(!v){p=!1;return}var M=v,B=M.toPos,J=M.acc,te=M.endTime,W=M.source,ee=te-Date.now();if(ee<=0){c(B),v=null,p=!1,_=null;var ae=r.value[t.current];if(ae){var ye=ae.getItemId();n("animationfinish",{},{current:t.current,currentItemId:ye,source:W})}return}var oe=J*ee*ee/2,K=B+oe;c(K),x=requestAnimationFrame(C)}function E(M,B,J){y();var te=t.duration,W=r.value.length,ee=u;if(m.value)if(J<0){for(;eeM;)ee-=W}else if(J>0){for(;ee>M;)ee-=W;for(;ee+WM;)ee-=W;ee+W-M0&&f<1||(f=1)}var ee=u;u=-2;var ae=t.current;ae>=0?(l=!1,t.userTracking?(c(ee+ae-d),d=ae):(c(ae),e.autoplay&&O())):(l=!0,c(-t.displayMultipleItems-1))}H([()=>e.current,()=>e.currentItemId,()=>[...r.value]],()=>{var M=-1;if(e.currentItemId)for(var B=0,J=r.value;Be.vertical,()=>m.value,()=>t.displayMultipleItems,()=>[...r.value]],N),H(()=>t.interval,()=>{s&&(o(),O())});function R(M,B){var J=b;b="";var te=r.value;if(!J){var W=te.length;E(M,"",m.value&&B+(W-M)%W>W/2?1:0)}var ee=te[M];if(ee){var ae=t.currentItemId=ee.getItemId();n("change",{},{current:t.current,currentItemId:ae,source:J})}}H(()=>t.current,(M,B)=>{R(M,B),a("update:current",M)}),H(()=>t.currentItemId,M=>{a("update:currentItemId",M)});function Y(M){M?O():o()}H(()=>e.autoplay&&!t.userTracking,Y),Y(e.autoplay&&!t.userTracking),Re(()=>{var M=!1,B=0,J=0;function te(){o(),d=u,B=0,J=Date.now(),y()}function W(ae){var ye=J;J=Date.now();var oe=r.value.length,K=oe-t.displayMultipleItems;function ie(nt){return .5-.25/(nt+.5)}function le(nt,nr){var Ne=d+nt;B=.6*B+.4*nr,m.value||(Ne<0||Ne>K)&&(Ne<0?Ne=-ie(-Ne):Ne>K&&(Ne=K+ie(Ne-K)),B=0),c(Ne)}var Ie=J-ye||1,ke=i.value;e.vertical?le(-ae.dy/ke.offsetHeight,-ae.ddy/Ie):le(-ae.dx/ke.offsetWidth,-ae.ddx/Ie)}function ee(ae){t.userTracking=!1;var ye=B/Math.abs(B),oe=0;!ae&&Math.abs(B)>.2&&(oe=.5*ye);var K=w(u+oe);ae?c(d):(b="touch",t.current=K,E(K,"touch",oe!==0?oe:K===0&&m.value&&u>=1?1:0))}Dn(i.value,ae=>{if(!e.disableTouch&&!l){if(ae.detail.state==="start")return t.userTracking=!0,M=!1,te();if(ae.detail.state==="end")return ee(!1);if(ae.detail.state==="cancel")return ee(!0);if(t.userTracking){if(!M){M=!0;var ye=Math.abs(ae.detail.dx),oe=Math.abs(ae.detail.dy);if((ye>=oe&&e.vertical||ye<=oe&&!e.vertical)&&(t.userTracking=!1),!t.userTracking){e.autoplay&&O();return}}return W(ae.detail),!1}}})}),Wt(()=>{o(),cancelAnimationFrame(x)});function ue(M){E(t.current=M,b="click",m.value?1:0)}return{onSwiperDotClick:ue}}var MS=ge({name:"Swiper",props:AS,emits:["change","transition","animationfinish","update:current","update:currentItemId"],setup(e,t){var{slots:r,emit:i}=t,a=U(null),n=Pe(a,i),o=U(null),s=U(null),l=IS(e),u=Q(()=>{var g={};return(e.nextMargin||e.previousMargin)&&(g=e.vertical?{left:0,right:0,top:pr(e.previousMargin,!0),bottom:pr(e.nextMargin,!0)}:{top:0,bottom:0,left:pr(e.previousMargin,!0),right:pr(e.nextMargin,!0)}),g}),f=Q(()=>{var g=Math.abs(100/l.displayMultipleItems)+"%";return{width:e.vertical?"100%":g,height:e.vertical?g:"100%"}}),v=[],p=[],d=U([]);function _(){for(var g=[],c=function(w){var y=v[w];y instanceof Element||(y=y.el);var C=p.find(E=>y===E.rootRef.value);C&&g.push(Ha(C))},h=0;h{v=s.value.children,_()});var b=function(g){p.push(g),_()};Fe("addSwiperContext",b);var x=function(g){var c=p.indexOf(g);c>=0&&(p.splice(c,1),_())};Fe("removeSwiperContext",x);var{onSwiperDotClick:m}=kS(e,l,d,s,i,n);return()=>{var g=r.default&&r.default();return v=ml(g),I("uni-swiper",{ref:a},[I("div",{ref:o,class:"uni-swiper-wrapper"},[I("div",{class:"uni-swiper-slides",style:u.value},[I("div",{ref:s,class:"uni-swiper-slide-frame",style:f.value},[g],4)],4),e.indicatorDots&&I("div",{class:["uni-swiper-dots",e.vertical?"uni-swiper-dots-vertical":"uni-swiper-dots-horizontal"]},[d.value.map((c,h,w)=>I("div",{onClick:()=>m(h),class:{"uni-swiper-dot":!0,"uni-swiper-dot-active":h=l.current||h{var n=_e("addSwiperContext");n&&n(a)}),Wt(()=>{var n=_e("removeSwiperContext");n&&n(a)}),()=>I("uni-swiper-item",{ref:i,style:{position:"absolute",width:"100%",height:"100%"}},[r.default&&r.default()],512)}}),PS={name:{type:String,default:""},checked:{type:[Boolean,String],default:!1},type:{type:String,default:"switch"},id:{type:String,default:""},disabled:{type:[Boolean,String],default:!1},color:{type:String,default:"#007aff"}},NS=ge({name:"Switch",props:PS,emits:["change"],setup(e,t){var{emit:r}=t,i=U(null),a=U(e.checked),n=DS(e,a),o=Pe(i,r);H(()=>e.checked,l=>{a.value=l});var s=l=>{e.disabled||(a.value=!a.value,o("change",l,{value:a.value}))};return n&&(n.addHandler(s),Ce(()=>{n.removeHandler(s)})),An(e,{"label-click":s}),()=>{var{color:l,type:u}=e,f=qi(e,"disabled");return I("uni-switch",Qe({ref:i},f,{onClick:s}),[I("div",{class:"uni-switch-wrapper"},[wi(I("div",{class:["uni-switch-input",[a.value?"uni-switch-input-checked":""]],style:{backgroundColor:a.value?l:"#DFDFDF",borderColor:a.value?l:"#DFDFDF"}},null,6),[[Ai,u==="switch"]]),wi(I("div",{class:"uni-checkbox-input"},[a.value?ln(sn,e.color,22):""],512),[[Ai,u==="checkbox"]])])],16,["onClick"])}}});function DS(e,t){var r=_e(At,!1),i=_e(Xi,!1),a={submit:()=>{var n=["",null];return e.name&&(n[0]=e.name,n[1]=t.value),n},reset:()=>{t.value=!1}};return r&&(r.addField(a),Wt(()=>{r.removeField(a)})),i}var ra={ensp:"\u2002",emsp:"\u2003",nbsp:"\xA0"};function BS(e,t){return e.replace(/\\n/g,di).split(di).map(r=>$S(r,t))}function $S(e,t){var{space:r,decode:i}=t;return!e||(r&&ra[r]&&(e=e.replace(/ /g,ra[r])),!i)?e:e.replace(/ /g,ra.nbsp).replace(/ /g,ra.ensp).replace(/ /g,ra.emsp).replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'")}var FS=ve({},jd,{placeholderClass:{type:String,default:"input-placeholder"},autoHeight:{type:[Boolean,String],default:!1},confirmType:{type:String,default:""}}),yl=!1;function zS(){var e="(prefers-color-scheme: dark)";yl=String(navigator.platform).indexOf("iP")===0&&String(navigator.vendor).indexOf("Apple")===0&&window.matchMedia(e).media!==e}var US=ge({name:"Textarea",props:FS,emit:["confirm","linechange",...Yd],setup(e,t){var{emit:r}=t,i=U(null),{fieldRef:a,state:n,scopedAttrsState:o,fixDisabledColor:s,trigger:l}=qd(e,i,r),u=Q(()=>n.value.split(di)),f=Q(()=>["done","go","next","search","send"].includes(e.confirmType)),v=U(0),p=U(null);H(()=>v.value,m=>{var g=i.value,c=p.value,h=parseFloat(getComputedStyle(g).lineHeight);isNaN(h)&&(h=c.offsetHeight);var w=Math.round(m/h);l("linechange",{},{height:m,heightRpx:750/window.innerWidth*m,lineCount:w}),e.autoHeight&&(g.style.height=m+"px")});function d(m){var{height:g}=m;v.value=g}function _(m){l("confirm",m,{value:n.value})}function b(m){m.key==="Enter"&&f.value&&m.preventDefault()}function x(m){if(m.key==="Enter"&&f.value){_(m);var g=m.target;g.blur()}}return zS(),()=>{var m=e.disabled&&s?I("textarea",{ref:a,value:n.value,tabindex:"-1",readonly:!!e.disabled,maxlength:n.maxlength,class:{"uni-textarea-textarea":!0,"uni-textarea-textarea-fix-margin":yl},style:{overflowY:e.autoHeight?"hidden":"auto"},onFocus:g=>g.target.blur()},null,46,["value","readonly","maxlength","onFocus"]):I("textarea",{ref:a,value:n.value,disabled:!!e.disabled,maxlength:n.maxlength,enterkeyhint:e.confirmType,class:{"uni-textarea-textarea":!0,"uni-textarea-textarea-fix-margin":yl},style:{overflowY:e.autoHeight?"hidden":"auto"},onKeydown:b,onKeyup:x},null,46,["value","disabled","maxlength","enterkeyhint","onKeydown","onKeyup"]);return I("uni-textarea",{ref:i},[I("div",{class:"uni-textarea-wrapper"},[wi(I("div",Qe(o.attrs,{style:e.placeholderStyle,class:["uni-textarea-placeholder",e.placeholderClass]}),[e.placeholder],16),[[Ai,!n.value.length]]),I("div",{ref:p,class:"uni-textarea-line"},[" "],512),I("div",{class:"uni-textarea-compute"},[u.value.map(g=>I("div",null,[g.trim()?g:"."])),I(Or,{initial:!0,onResize:d},null,8,["initial","onResize"])]),e.confirmType==="search"?I("form",{action:"",onSubmit:()=>!1,class:"uni-input-form"},[m],40,["onSubmit"]):m])],512)}}});ve({},cx);function Fn(e,t){if(t||(t=e.id),!!t)return e.$options.name.toLowerCase()+"."+t}function fh(e,t,r){!e||bt(r||Xt(),e,(i,a)=>{var{type:n,data:o}=i;t(n,o,a)})}function ch(e){!e||E0(Xt(),e)}function zn(e,t,r,i){var a=jt(),n=a.proxy;Re(()=>{fh(t||Fn(n),e,i),(r||!t)&&H(()=>n.id,(o,s)=>{fh(Fn(n,o),e,i),ch(s&&Fn(n,s))})}),Ce(()=>{ch(t||Fn(n))})}var HS=0;function Un(e){var t=un(),r=jt(),i=r.proxy,a=i.$options.name.toLowerCase(),n=e||i.id||"context".concat(HS++);return Re(()=>{var o=i.$el;o.__uniContextInfo={id:n,type:a,page:t}}),"".concat(a,".").concat(n)}function WS(e){return e.__uniContextInfo}class vh extends wd{constructor(t,r,i,a,n){var o=arguments.length>5&&arguments[5]!==void 0?arguments[5]:[];super(t,r,i,a,n,[...On.props,...o])}call(t){var r={animation:this.$props.animation,$el:this.$};t.call(r)}setAttribute(t,r){return t==="animation"&&(this.$animate=!0),super.setAttribute(t,r)}update(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!!this.$animate){if(t)return this.call(On.mounted);this.$animate&&(this.$animate=!1,this.call(On.watch.animation.handler))}}}var VS=["space","decode"];class jS extends vh{constructor(t,r,i,a){super(t,document.createElement("uni-text"),r,i,a,VS);this._text=""}init(t){this._text=t.t||"",super.init(t)}setText(t){this._text=t,this.update()}update(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,{$props:{space:r,decode:i}}=this;this.$.textContent=BS(this._text,{space:r,decode:i}).join(di),super.update(t)}}class YS extends ti{constructor(t,r,i,a){super(t,"#text",r,document.createTextNode(""));this.init(a),this.insert(r,i)}}var zT="",qS=["hover-class","hover-stop-propagation","hover-start-time","hover-stay-time"];class XS extends vh{constructor(t,r,i,a,n){var o=arguments.length>5&&arguments[5]!==void 0?arguments[5]:[];super(t,r,i,a,n,[...qS,...o])}update(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,r=this.$props["hover-class"];r&&r!=="none"?(this._hover||(this._hover=new ZS(this.$,this.$props)),this._hover.addEvent()):this._hover&&this._hover.removeEvent(),super.update(t)}}class ZS{constructor(t,r){this._listening=!1,this._hovering=!1,this._hoverTouch=!1,this.$=t,this.props=r,this.__hoverTouchStart=this._hoverTouchStart.bind(this),this.__hoverTouchEnd=this._hoverTouchEnd.bind(this),this.__hoverTouchCancel=this._hoverTouchCancel.bind(this)}get hovering(){return this._hovering}set hovering(t){this._hovering=t;var r=this.props["hover-class"];t?this.$.classList.add(r):this.$.classList.remove(r)}addEvent(){this._listening||(this._listening=!0,this.$.addEventListener("touchstart",this.__hoverTouchStart),this.$.addEventListener("touchend",this.__hoverTouchEnd),this.$.addEventListener("touchcancel",this.__hoverTouchCancel))}removeEvent(){!this._listening||(this._listening=!1,this.$.removeEventListener("touchstart",this.__hoverTouchStart),this.$.removeEventListener("touchend",this.__hoverTouchEnd),this.$.removeEventListener("touchcancel",this.__hoverTouchCancel))}_hoverTouchStart(t){if(!t._hoverPropagationStopped){var r=this.props["hover-class"];!r||r==="none"||this.$.disabled||t.touches.length>1||(this.props["hover-stop-propagation"]&&(t._hoverPropagationStopped=!0),this._hoverTouch=!0,this._hoverStartTimer=setTimeout(()=>{this.hovering=!0,this._hoverTouch||this._hoverReset()},this.props["hover-start-time"]))}}_hoverTouchEnd(){this._hoverTouch=!1,this.hovering&&this._hoverReset()}_hoverReset(){requestAnimationFrame(()=>{clearTimeout(this._hoverStayTimer),this._hoverStayTimer=setTimeout(()=>{this.hovering=!1},this.props["hover-stay-time"])})}_hoverTouchCancel(){this._hoverTouch=!1,this.hovering=!1,clearTimeout(this._hoverStartTimer)}}class KS extends XS{constructor(t,r,i,a){super(t,document.createElement("uni-view"),r,i,a)}}function dh(){return plus.navigator.isImmersedStatusbar()?Math.round(plus.os.name==="iOS"?plus.navigator.getSafeAreaInsets().top:plus.navigator.getStatusbarHeight()):0}function hh(){var e=plus.webview.currentWebview(),t=e.getStyle(),r=t&&t.titleNView;return r&&r.type==="default"?Tu+dh():0}var gh=Symbol("onDraw");function GS(e){for(var t;e;){var r=getComputedStyle(e),i=r.transform||r.webkitTransform;t=i&&i!=="none"?!1:t,t=r.position==="fixed"?!0:t,e=e.parentElement}return t}function Sl(e,t){return Q(()=>{var r={};return Object.keys(e).forEach(i=>{if(!(t&&t.includes(i))){var a=e[i];a=i==="src"?vt(a):a,r[i.replace(/[A-Z]/g,n=>"-"+n.toLowerCase())]=a}}),r})}function ia(e){var t=Ae({top:"0px",left:"0px",width:"0px",height:"0px",position:"static"}),r=U(!1);function i(){var v=e.value,p=v.getBoundingClientRect(),d=["width","height"];r.value=p.width===0||p.height===0,r.value||(t.position=GS(v)?"absolute":"static",d.push("top","left")),d.forEach(_=>{var b=p[_];b=_==="top"?b+(t.position==="static"?document.documentElement.scrollTop||document.body.scrollTop||0:hh()):b,t[_]=b+"px"})}var a=null;function n(){a&&cancelAnimationFrame(a),a=requestAnimationFrame(()=>{a=null,i()})}window.addEventListener("updateview",n);var o=[],s=[];function l(v){s?s.push(v):v()}function u(v){var p=_e(gh),d=_=>{v(_),o.forEach(b=>b(t)),o=null};l(()=>{p?p(d):d({top:"0px",left:"0px",width:Number.MAX_SAFE_INTEGER+"px",height:Number.MAX_SAFE_INTEGER+"px",position:"static"})})}var f=function(v){o?o.push(v):v(t)};return Fe(gh,f),Re(()=>{i(),s.forEach(v=>v()),s=null}),Ce(()=>{window.removeEventListener("updateview",n)}),{position:t,hidden:r,onParentReady:u}}var JS=ge({name:"Ad",props:{adpid:{type:[Number,String],default:""},data:{type:Object,default:null},dataCount:{type:Number,default:5},channel:{type:String,default:""}},setup(e,t){var{emit:r}=t,i=U(null),a=U(null),n=Pe(i,r),o=Sl(e,["id"]),{position:s,onParentReady:l}=ia(a),u;return l(()=>{u=plus.ad.createAdView(Object.assign({},o.value,s)),plus.webview.currentWebview().append(u),u.setDislikeListener(v=>{a.value.style.height="0",window.dispatchEvent(new CustomEvent("updateview")),n("close",{},v)}),u.setRenderingListener(v=>{v.result===0?(a.value.style.height=v.height+"px",window.dispatchEvent(new CustomEvent("updateview"))):n("error",{},{errCode:v.result})}),u.setAdClickedListener(()=>{n("adclicked",{},{})}),H(()=>s,v=>u.setStyle(v),{deep:!0}),H(()=>e.adpid,v=>{v&&f()}),H(()=>e.data,v=>{v&&u.renderingBind(v)});function f(){var v={adpid:e.adpid,width:s.width,count:e.dataCount};e.channel!==void 0&&(v.ext={channel:e.channel}),UniViewJSBridge.invokeServiceMethod("getAdData",v,p=>{var{code:d,data:_,message:b}=p;d===0?u.renderingBind(_):n("error",{},{errMsg:b})})}e.adpid&&f()}),Ce(()=>{u&&u.close()}),()=>I("uni-ad",{ref:i},[I("div",{ref:a,class:"uni-ad-container"},null,512)],512)}});class we extends ti{constructor(t,r,i,a,n,o,s){super(t,r,a);var l=document.createElement("div");l.__vueParent=QS(this),this.$props=Ae({}),this.init(o),this.$app=uc(lT(i,this.$props)),this.$app.mount(l),this.$=l.firstElementChild,s&&(this.$holder=this.$.querySelector(s)),re(o,"t")&&this.setText(o.t||""),o.a&&re(o.a,ka)&&fl(this.$,o.a[ka]),this.insert(a,n),Kf()}init(t){var{a:r,e:i,w:a}=t;r&&(this.setWxsProps(r),Object.keys(r).forEach(n=>{this.setAttr(n,r[n])})),re(t,"s")&&this.setAttr("style",t.s),i&&Object.keys(i).forEach(n=>{this.addEvent(n,i[n])}),a&&this.addWxsEvents(t.w)}setText(t){(this.$holder||this.$).textContent=t}addWxsEvent(t,r,i){this.$props[t]=bd(this.$,r,i)}addEvent(t,r){this.$props[t]=md(this.id,r,Ao(t)[1])}removeEvent(t){this.$props[t]=null}setAttr(t,r){if(t===ka)this.$&&fl(this.$,r);else if(t===ku)this.$.__ownerId=r;else if(t===Mu)rr(()=>ud(this,r),od);else if(t===ko){var i=ul(this.$||at(this.pid).$,r),a=this.$props.style;mt(i)&&mt(a)?Object.keys(i).forEach(n=>{a[n]=i[n]}):this.$props.style=i}else Cn(t)?this.$.style.setProperty(t,r):(r=ul(this.$||at(this.pid).$,r),this.wxsPropsInvoke(t,r,!0)||(this.$props[t]=r))}removeAttr(t){Cn(t)?this.$.style.removeProperty(t):this.$props[t]=null}remove(){this.removeUniParent(),this.isUnmounted=!0,this.$app.unmount(),yh(this.id),this.removeUniChildren()}appendChild(t){return(this.$holder||this.$).appendChild(t)}insertBefore(t,r){return(this.$holder||this.$).insertBefore(t,r)}}class aa extends we{constructor(t,r,i,a,n,o,s){super(t,r,i,a,n,o,s)}getRebuildFn(){return this._rebuild||(this._rebuild=this.rebuild.bind(this)),this._rebuild}setText(t){return rr(this.getRebuildFn(),il),super.setText(t)}appendChild(t){return rr(this.getRebuildFn(),il),super.appendChild(t)}insertBefore(t,r){return rr(this.getRebuildFn(),il),super.insertBefore(t,r)}rebuild(){var t=this.$.__vueParentComponent;t.rebuild&&t.rebuild()}}function QS(e){for(;e&&e.pid>0;)if(e=at(e.pid),e){var{__vueParentComponent:t}=e.$;if(t)return t}return null}function El(e,t,r){e.childNodes.forEach(i=>{i instanceof Element?i.className.indexOf(t)===-1&&e.removeChild(i):e.removeChild(i)}),e.appendChild(document.createTextNode(r))}class eE extends we{constructor(t,r,i,a){super(t,"uni-ad",JS,r,i,a)}}var UT="";class tE extends we{constructor(t,r,i,a){super(t,"uni-button",bx,r,i,a)}}class ii extends ti{constructor(t,r,i,a){super(t,r,i);this.insert(i,a)}}class rE extends ii{constructor(t,r,i){super(t,"uni-camera",r,i)}}var HT="";class iE extends we{constructor(t,r,i,a){super(t,"uni-canvas",Ox,r,i,a,"uni-canvas > div")}}var WT="";class aE extends we{constructor(t,r,i,a){super(t,"uni-checkbox",Px,r,i,a,".uni-checkbox-wrapper")}setText(t){El(this.$holder,"uni-checkbox-input",t)}}var VT="";class nE extends we{constructor(t,r,i,a){super(t,"uni-checkbox-group",Mx,r,i,a)}}var jT="",oE=0;function ph(e,t,r){var{position:i,hidden:a,onParentReady:n}=ia(e),o,s;n(l=>{var u=Q(()=>{var c={};for(var h in i){var w=i[h],y=parseFloat(w),C=parseFloat(l[h]);if(h==="top"||h==="left")w=Math.max(y,C)+"px";else if(h==="width"||h==="height"){var E=h==="width"?"left":"top",O=parseFloat(l[E]),N=parseFloat(i[E]),R=Math.max(O-N,0),Y=Math.max(N+y-(O+C),0);w=Math.max(y-R-Y,0)+"px"}c[h]=w}return c}),f=["borderRadius","borderColor","borderWidth","backgroundColor"],v=["paddingTop","paddingRight","paddingBottom","paddingLeft","color","textAlign","lineHeight","fontSize","fontWeight","textOverflow","whiteSpace"],p=[],d={start:"left",end:"right"};function _(c){var h=getComputedStyle(e.value);return f.concat(v,p).forEach(w=>{c[w]=h[w]}),c}var b=Ae(_({})),x=null;s=function(){x&&cancelAnimationFrame(x),x=requestAnimationFrame(()=>{x=null,_(b)})},window.addEventListener("updateview",s);function m(){var c={};for(var h in c){var w=c[h];(h==="top"||h==="left")&&(w=Math.min(parseFloat(w)-parseFloat(l[h]),0)+"px"),c[h]=w}return c}var g=Q(()=>{var c=m(),h=[{tag:"rect",position:c,rectStyles:{color:b.backgroundColor,radius:b.borderRadius,borderColor:b.borderColor,borderWidth:b.borderWidth}}];if("src"in r)r.src&&h.push({tag:"img",position:c,src:r.src});else{var w=parseFloat(b.lineHeight)-parseFloat(b.fontSize),y=parseFloat(c.width)-parseFloat(b.paddingLeft)-parseFloat(b.paddingRight);y=y<0?0:y;var C=parseFloat(c.height)-parseFloat(b.paddingTop)-w/2-parseFloat(b.paddingBottom);C=C<0?0:C,h.push({tag:"font",position:{top:"".concat(parseFloat(c.top)+parseFloat(b.paddingTop)+w/2,"px"),left:"".concat(parseFloat(c.left)+parseFloat(b.paddingLeft),"px"),width:"".concat(y,"px"),height:"".concat(C,"px")},textStyles:{align:d[b.textAlign]||b.textAlign,color:b.color,decoration:"none",lineSpacing:"".concat(w,"px"),margin:"0px",overflow:b.textOverflow,size:b.fontSize,verticalAlign:"top",weight:b.fontWeight,whiteSpace:b.whiteSpace},text:r.text})}return h});o=new plus.nativeObj.View("cover-".concat(Date.now(),"-").concat(oE++),u.value,g.value),plus.webview.currentWebview().append(o),a.value&&o.hide(),o.addEventListener("click",()=>{t("click",{},{})}),H(()=>a.value,c=>{o[c?"hide":"show"]()}),H(()=>u.value,c=>{o.setStyle(c)},{deep:!0}),H(()=>g.value,()=>{o.reset(),o.draw(g.value)},{deep:!0})}),Ce(()=>{o&&o.close(),s&&window.removeEventListener("updateview",s)})}var sE="_doc/uniapp_temp/",lE={src:{type:String,default:""},autoSize:{type:[Boolean,String],default:!1}};function uE(e,t,r){var i=U(""),a;function n(){t.src="",i.value=e.autoSize?"width:0;height:0;":"";var s=e.src?vt(e.src):"";s.indexOf("http://")===0||s.indexOf("https://")===0?(a=plus.downloader.createDownload(s,{filename:sE+"/download/"},(l,u)=>{u===200?o(l.filename):r("error",{},{errMsg:"error"})}),a.start()):s&&o(s)}function o(s){t.src=s,plus.io.getImageInfo({src:s,success:l=>{var{width:u,height:f}=l;e.autoSize&&(i.value="width:".concat(u,"px;height:").concat(f,"px;"),window.dispatchEvent(new CustomEvent("updateview"))),r("load",{},{width:u,height:f})},fail:()=>{r("error",{},{errMsg:"error"})}})}return e.src&&n(),H(()=>e.src,n),Ce(()=>{a&&a.abort()}),i}var mh=ge({name:"CoverImage",props:lE,emits:["click","load","error"],setup(e,t){var{emit:r}=t,i=U(null),a=Pe(i,r),n=Ae({src:""}),o=uE(e,n,a);return ph(i,a,n),()=>I("uni-cover-image",{ref:i,style:o.value},[I("div",{class:"uni-cover-image"},null)],4)}});class fE extends we{constructor(t,r,i,a){super(t,"uni-cover-image",mh,r,i,a)}}var YT="",cE=ge({name:"CoverView",emits:["click"],setup(e,t){var{emit:r}=t,i=U(null),a=U(null),n=Pe(i,r),o=Ae({text:""});return ph(i,n,o),Qi(()=>{var s=a.value.childNodes[0];o.text=s&&s instanceof Text?s.textContent:"",window.dispatchEvent(new CustomEvent("updateview"))}),()=>I("uni-cover-view",{ref:i},[I("div",{ref:a,class:"uni-cover-view"},null,512)],512)}});class vE extends aa{constructor(t,r,i,a){super(t,"uni-cover-view",cE,r,i,a,".uni-cover-view")}}var qT="";class dE extends we{constructor(t,r,i,a){super(t,"uni-editor",ny,r,i,a)}}var XT="";class hE extends we{constructor(t,r,i,a){super(t,"uni-form",hx,r,i,a,"span")}}class gE extends ii{constructor(t,r,i){super(t,"uni-functional-page-navigator",r,i)}}var ZT="";class pE extends we{constructor(t,r,i,a){super(t,"uni-icon",uy,r,i,a)}}var KT="";class mE extends we{constructor(t,r,i,a){super(t,"uni-image",vy,r,i,a)}}var GT="";class _E extends we{constructor(t,r,i,a){super(t,"uni-input",Ry,r,i,a)}}var JT="";class bE extends we{constructor(t,r,i,a){super(t,"uni-label",mx,r,i,a)}}class wE extends ii{constructor(t,r,i){super(t,"uni-live-player",r,i)}}class xE extends ii{constructor(t,r,i){super(t,"uni-live-pusher",r,i)}}var QT="",yE=(e,t,r)=>{r({coord:{latitude:t,longitude:e}})};function Tl(e){if(e.indexOf("#")!==0)return{color:e,opacity:1};var t=e.substr(7,2);return{color:e.substr(0,7),opacity:t?Number("0x"+t)/255:1}}var SE={id:{type:String,default:""},latitude:{type:[Number,String],default:""},longitude:{type:[Number,String],default:""},scale:{type:[String,Number],default:16},markers:{type:Array,default(){return[]}},polyline:{type:Array,default(){return[]}},circles:{type:Array,default(){return[]}},controls:{type:Array,default(){return[]}}},EE=ge({name:"Map",props:SE,emits:["click","regionchange","controltap","markertap","callouttap"],setup(e,t){var{emit:r}=t,i=U(null),a=Pe(i,r),n=U(null),o=Sl(e,["id"]),{position:s,hidden:l,onParentReady:u}=ia(n),f,{_addMarkers:v,_addMapLines:p,_addMapCircles:d,_setMap:_}=TE(e,a);u(()=>{f=ve(plus.maps.create(Xt()+"-map-"+(e.id||Date.now()),Object.assign({},o.value,s,(()=>{if(e.latitude&&e.longitude)return{center:new plus.maps.Point(Number(e.longitude),Number(e.latitude))}})())),{__markers__:[],__lines__:[],__circles__:[]}),f.setZoom(parseInt(String(e.scale))),plus.webview.currentWebview().append(f),l.value&&f.hide(),f.onclick=x=>{a("click",{},x)},f.onstatuschanged=x=>{a("regionchange",{},{})},_(f),v(e.markers),p(e.polyline),d(e.circles),H(()=>o.value,x=>f&&f.setStyles(x),{deep:!0}),H(()=>s,x=>f&&f.setStyles(x),{deep:!0}),H(l,x=>{f&&f[x?"hide":"show"]()}),H(()=>e.scale,x=>{f&&f.setZoom(parseInt(String(x)))}),H([()=>e.latitude,()=>e.longitude],x=>{var[m,g]=x;f&&f.setStyles({center:new plus.maps.Point(Number(m),Number(g))})}),H(()=>e.markers,x=>{v(x,!0)},{deep:!0}),H(()=>e.polyline,x=>{p(x)},{deep:!0}),H(()=>e.circles,x=>{d(x)},{deep:!0})});var b=Q(()=>e.controls.map(x=>{var m={position:"absolute"};return["top","left","width","height"].forEach(g=>{x.position[g]&&(m[g]=x.position[g]+"px")}),{id:x.id,iconPath:vt(x.iconPath),position:m,clickable:x.clickable}}));return Ce(()=>{f&&(f.close(),_(null))}),()=>I("uni-map",{ref:i,id:e.id},[I("div",{ref:n,class:"uni-map-container"},null,512),b.value.map((x,m)=>I(mh,{key:m,src:x.iconPath,style:x.position,"auto-size":!0,onClick:()=>x.clickable&&a("controltap",{},{controlId:x.id})},null,8,["src","style","auto-size","onClick"])),I("div",{class:"uni-map-slot"},null)],8,["id"])}});function TE(e,t){var r;function i(d){var{longitude:_,latitude:b}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};!r||(r.setCenter(new plus.maps.Point(Number(_||e.longitude),Number(b||e.latitude))),d({errMsg:"moveToLocation:ok"}))}function a(d){!r||r.getCurrentCenter((_,b)=>{d({longitude:b.getLng(),latitude:b.getLat(),errMsg:"getCenterLocation:ok"})})}function n(d){if(!!r){var _=r.getBounds();d({southwest:_.getSouthWest(),northeast:_.getNorthEast(),errMsg:"getRegion:ok"})}}function o(d){!r||d({scale:r.getZoom(),errMsg:"getScale:ok"})}function s(d){if(!!r){var{id:_,latitude:b,longitude:x,iconPath:m,callout:g,label:c}=d;yE(x,b,h=>{var w,{latitude:y,longitude:C}=h.coord,E=new plus.maps.Marker(new plus.maps.Point(C,y));m&&E.setIcon(vt(m)),c&&c.content&&E.setLabel(c.content);var O=void 0;g&&g.content&&(O=new plus.maps.Bubble(g.content)),O&&E.setBubble(O),(_||_===0)&&(E.onclick=N=>{t("markertap",{},{markerId:_})},O&&(O.onclick=()=>{t("callouttap",{},{markerId:_})})),(w=r)===null||w===void 0||w.addOverlay(E),r.__markers__.push(E)})}}function l(){if(!!r){var d=r.__markers__;d.forEach(_=>{var b;(b=r)===null||b===void 0||b.removeOverlay(_)}),r.__markers__=[]}}function u(d,_){_&&l(),d.forEach(b=>{s(b)})}function f(d){!r||(r.__lines__.length>0&&(r.__lines__.forEach(_=>{var b;(b=r)===null||b===void 0||b.removeOverlay(_)}),r.__lines__=[]),d.forEach(_=>{var b,{color:x,width:m}=_,g=_.points.map(w=>new plus.maps.Point(w.longitude,w.latitude)),c=new plus.maps.Polyline(g);if(x){var h=Tl(x);c.setStrokeColor(h.color),c.setStrokeOpacity(h.opacity)}m&&c.setLineWidth(m),(b=r)===null||b===void 0||b.addOverlay(c),r.__lines__.push(c)}))}function v(d){!r||(r.__circles__.length>0&&(r.__circles__.forEach(_=>{var b;(b=r)===null||b===void 0||b.removeOverlay(_)}),r.__circles__=[]),d.forEach(_=>{var b,{latitude:x,longitude:m,color:g,fillColor:c,radius:h,strokeWidth:w}=_,y=new plus.maps.Circle(new plus.maps.Point(m,x),h);if(g){var C=Tl(g);y.setStrokeColor(C.color),y.setStrokeOpacity(C.opacity)}if(c){var E=Tl(c);y.setFillColor(E.color),y.setFillOpacity(E.opacity)}w&&y.setLineWidth(w),(b=r)===null||b===void 0||b.addOverlay(y),r.__circles__.push(y)}))}var p={moveToLocation:i,getCenterLocation:a,getRegion:n,getScale:o};return zn((d,_,b)=>{p[d]&&p[d](b,_)},Un(),!0),{_addMarkers:u,_addMapLines:f,_addMapCircles:v,_setMap(d){r=d}}}class CE extends we{constructor(t,r,i,a){super(t,"uni-map",EE,r,i,a,".uni-map-slot")}}var e2="";class OE extends aa{constructor(t,r,i,a){super(t,"uni-movable-area",By,r,i,a)}}var t2="";class AE extends we{constructor(t,r,i,a){super(t,"uni-movable-view",zy,r,i,a)}}var r2="";class IE extends we{constructor(t,r,i,a){super(t,"uni-navigator",Vy,r,i,a)}}class kE extends ii{constructor(t,r,i){super(t,"uni-official-account",r,i)}}class ME extends ii{constructor(t,r,i){super(t,"uni-open-data",r,i)}}var Mr,_h,ai;function bh(){return typeof window=="object"&&typeof navigator=="object"&&typeof document=="object"?"webview":"v8"}function wh(){return Mr.webview.currentWebview().id}var Hn,Cl,Ol={};function Al(e){var t=e.data&&e.data.__message;if(!(!t||!t.__page)){var r=t.__page,i=Ol[r];i&&i(t),t.keep||delete Ol[r]}}function RE(e,t){bh()==="v8"?ai?(Hn&&Hn.close(),Hn=new ai(wh()),Hn.onmessage=Al):Cl||(Cl=_h.requireModule("globalEvent"),Cl.addEventListener("plusMessage",Al)):window.__plusMessage=Al,Ol[e]=t}class LE{constructor(t){this.webview=t}sendMessage(t){var r=JSON.parse(JSON.stringify({__message:{data:t}})),i=this.webview.id;if(ai){var a=new ai(i);a.postMessage(r)}else Mr.webview.postMessageToUniNView&&Mr.webview.postMessageToUniNView(r,i)}close(){this.webview.close()}}function PE(e){var{context:t={},url:r,data:i={},style:a={},onMessage:n,onClose:o}=e;Mr=t.plus||plus,_h=t.weex||(typeof weex=="object"?weex:null),ai=t.BroadcastChannel||(typeof BroadcastChannel=="object"?BroadcastChannel:null);var s={autoBackButton:!0,titleSize:"17px"},l="page".concat(Date.now());a=ve({},a),a.titleNView!==!1&&a.titleNView!=="none"&&(a.titleNView=ve(s,a.titleNView));var u={top:0,bottom:0,usingComponents:{},popGesture:"close",scrollIndicator:"none",animationType:"pop-in",animationDuration:200,uniNView:{path:"".concat(typeof process=="object"&&process.env&&{}.VUE_APP_TEMPLATE_PATH||"","/").concat(r,".js"),defaultFontSize:Mr.screen.resolutionWidth/20,viewport:Mr.screen.resolutionWidth}};a=ve(u,a);var f=Mr.webview.create("",l,a,{extras:{from:wh(),runtime:bh(),data:i,useGlobalEvent:!ai}});return f.addEventListener("close",o),RE(l,v=>{typeof n=="function"&&n(v.data),v.keep||f.close("auto")}),f.show(a.animationType,a.animationDuration),new LE(f)}var Oe={SELECTOR:"selector",MULTISELECTOR:"multiSelector",TIME:"time",DATE:"date"},ni={YEAR:"year",MONTH:"month",DAY:"day"};function Wn(e){return e>9?e:"0".concat(e)}function Vn(e,t){e=String(e||"");var r=new Date;if(t===Oe.TIME){var i=e.split(":");i.length===2&&r.setHours(parseInt(i[0]),parseInt(i[1]))}else{var a=e.split("-");a.length===3&&r.setFullYear(parseInt(a[0]),parseInt(String(parseFloat(a[1])-1)),parseInt(a[2]))}return r}function NE(e){if(e.mode===Oe.TIME)return"00:00";if(e.mode===Oe.DATE){var t=new Date().getFullYear()-100;switch(e.fields){case ni.YEAR:return t;case ni.MONTH:return t+"-01";default:return t+"-01-01"}}return""}function DE(e){if(e.mode===Oe.TIME)return"23:59";if(e.mode===Oe.DATE){var t=new Date().getFullYear()+100;switch(e.fields){case ni.YEAR:return t;case ni.MONTH:return t+"-12";default:return t+"-12-31"}}return""}var BE={name:{type:String,default:""},range:{type:Array,default(){return[]}},rangeKey:{type:String,default:""},value:{type:[Number,String,Array],default:0},mode:{type:String,default:Oe.SELECTOR,validator(e){return Object.values(Oe).indexOf(e)>=0}},fields:{type:String,default:""},start:{type:String,default:NE},end:{type:String,default:DE},disabled:{type:[Boolean,String],default:!1}},$E=ge({name:"Picker",props:BE,emits:["change","cancel","columnchange"],setup(e,t){var{emit:r}=t;_0();var{t:i,getLocale:a}=Ge(),n=U(null),o=Pe(n,r),s=U(null),l=U(null),u=()=>{var m=e.value;switch(e.mode){case Oe.MULTISELECTOR:{Array.isArray(m)||(m=[]),Array.isArray(s.value)||(s.value=[]);for(var g=s.value.length=Math.max(m.length,e.range.length),c=0;c{l.value&&l.value.sendMessage(m)},v=m=>{var g={event:"cancel"};l.value=PE({url:"__uniapppicker",data:m,style:{titleNView:!1,animationType:"none",animationDuration:0,background:"rgba(0,0,0,0)",popGesture:"none"},onMessage:c=>{var h=c.event;if(h==="created"){f(m);return}if(h==="columnchange"){delete c.event,o(h,{},c);return}g=c},onClose:()=>{l.value=null;var c=g.event;delete g.event,c&&o(c,{},g)}})},p=(m,g)=>{plus.nativeUI[e.mode===Oe.TIME?"pickTime":"pickDate"](c=>{var h=c.date;o("change",{},{value:e.mode===Oe.TIME?"".concat(Wn(h.getHours()),":").concat(Wn(h.getMinutes())):"".concat(h.getFullYear(),"-").concat(Wn(h.getMonth()+1),"-").concat(Wn(h.getDate()))})},()=>{o("cancel",{},{})},e.mode===Oe.TIME?{time:Vn(e.value,Oe.TIME),popover:g}:{date:Vn(e.value,Oe.DATE),minDate:Vn(e.start,Oe.DATE),maxDate:Vn(e.end,Oe.DATE),popover:g})},d=(m,g)=>{(m.mode===Oe.TIME||m.mode===Oe.DATE)&&!m.fields?p(m,g):(m.fields=Object.values(ni).includes(m.fields)?m.fields:ni.DAY,v(m))},_=m=>{if(!e.disabled){var g=m.currentTarget,c=g.getBoundingClientRect();d(Object.assign({},e,{value:s.value,locale:a(),messages:{done:i("uni.picker.done"),cancel:i("uni.picker.cancel")}}),{top:c.top+hh(),left:c.left,width:c.width,height:c.height})}},b=_e(At,!1),x={submit:()=>[e.name,s.value],reset:()=>{switch(e.mode){case Oe.SELECTOR:s.value=0;break;case Oe.MULTISELECTOR:Array.isArray(e.value)&&(s.value=e.value.map(m=>0));break;case Oe.DATE:case Oe.TIME:s.value="";break}}};return b&&(b.addField(x),Ce(()=>b.removeField(x))),Object.keys(e).forEach(m=>{m!=="name"&&H(()=>e[m],g=>{var c={};c[m]=g,f(c)},{deep:!0})}),H(()=>e.value,u,{deep:!0}),u(),()=>I("uni-picker",{ref:n,onClick:_},[I("slot",null,null)],8,["onClick"])}});class FE extends we{constructor(t,r,i,a){super(t,"uni-picker",$E,r,i,a)}}var i2="";class zE extends aa{constructor(t,r,i,a){super(t,"uni-picker-view",qy,r,i,a,".uni-picker-view-wrapper")}}var a2="";class UE extends aa{constructor(t,r,i,a){super(t,"uni-picker-view-column",tS,r,i,a,".uni-picker-view-content")}}var n2="";class HE extends we{constructor(t,r,i,a){super(t,"uni-progress",iS,r,i,a)}}var o2="";class WE extends we{constructor(t,r,i,a){super(t,"uni-radio",uS,r,i,a,".uni-radio-wrapper")}setText(t){El(this.$holder,"uni-radio-input",t)}}var s2="";class VE extends we{constructor(t,r,i,a){super(t,"uni-radio-group",oS,r,i,a)}}var l2="";class jE extends we{constructor(t,r,i,a){super(t,"uni-rich-text",_S,r,i,a)}}var u2="";class YE extends we{constructor(t,r,i,a){super(t,"uni-scroll-view",wS,r,i,a,".uni-scroll-view-content")}setText(t){El(this.$holder,"uni-scroll-view-refresher",t)}}var f2="";class qE extends we{constructor(t,r,i,a){super(t,"uni-slider",ES,r,i,a)}}var c2="";class XE extends aa{constructor(t,r,i,a){super(t,"uni-swiper",MS,r,i,a,".uni-swiper-slide-frame")}}var v2="";class ZE extends we{constructor(t,r,i,a){super(t,"uni-swiper-item",LS,r,i,a)}}var d2="";class KE extends we{constructor(t,r,i,a){super(t,"uni-switch",NS,r,i,a)}}var h2="";class GE extends we{constructor(t,r,i,a){super(t,"uni-textarea",US,r,i,a)}}var g2="",JE={id:{type:String,default:""},src:{type:String,default:""},duration:{type:[Number,String],default:""},controls:{type:[Boolean,String],default:!0},danmuList:{type:Array,default(){return[]}},danmuBtn:{type:[Boolean,String],default:!1},enableDanmu:{type:[Boolean,String],default:!1},autoplay:{type:[Boolean,String],default:!1},loop:{type:[Boolean,String],default:!1},muted:{type:[Boolean,String],default:!1},objectFit:{type:String,default:"contain"},poster:{type:String,default:""},direction:{type:[String,Number],default:""},showProgress:{type:Boolean,default:!0},initialTime:{type:[String,Number],default:0},showFullscreenBtn:{type:[Boolean,String],default:!0},pageGesture:{type:[Boolean,String],default:!1},enableProgressGesture:{type:[Boolean,String],default:!0},showPlayBtn:{type:[Boolean,String],default:!0},enablePlayGesture:{type:[Boolean,String],default:!0},showCenterPlayBtn:{type:[Boolean,String],default:!0},showLoading:{type:[Boolean,String],default:!0},codec:{type:String,default:"hardware"},httpCache:{type:[Boolean,String],default:!1},playStrategy:{type:[Number,String],default:0},header:{type:Object,default(){return{}}},advanced:{type:Array,default(){return[]}}},xh=["play","pause","ended","timeupdate","fullscreenchange","fullscreenclick","waiting","error"],QE=["play","pause","stop","seek","sendDanmu","playbackRate","requestFullScreen","exitFullScreen"],eT=ge({name:"Video",props:JE,emits:xh,setup(e,t){var{emit:r}=t,i=U(null),a=Pe(i,r),n=U(null),o=Sl(e,["id"]),{position:s,hidden:l,onParentReady:u}=ia(n),f;u(()=>{f=plus.video.createVideoPlayer("video"+Date.now(),Object.assign({},o.value,s)),plus.webview.currentWebview().append(f),l.value&&f.hide(),xh.forEach(p=>{f.addEventListener(p,d=>{a(p,{},d.detail)})}),H(()=>o.value,p=>f.setStyles(p),{deep:!0}),H(()=>s,p=>f.setStyles(p),{deep:!0}),H(()=>l.value,p=>{f[p?"hide":"show"](),p||f.setStyles(s)})});var v=Un();return zn((p,d)=>{if(QE.includes(p)){var _;switch(p){case"seek":_=d.position;break;case"sendDanmu":_=d;break;case"playbackRate":_=d.rate;break;case"requestFullScreen":_=d.direction;break}f&&f[p](_)}},v,!0),Ce(()=>{f&&f.close()}),()=>I("uni-video",{ref:i,id:e.id},[I("div",{ref:n,class:"uni-video-container"},null,512),I("div",{class:"uni-video-slot"},null)],8,["id"])}});class tT extends we{constructor(t,r,i,a){super(t,"uni-video",eT,r,i,a,".uni-video-slot")}}var p2="",rT={src:{type:String,default:""},webviewStyles:{type:Object,default(){return{}}}},it,iT=e=>{var{htmlId:t,src:r,webviewStyles:i}=e,a=plus.webview.currentWebview(),n=ve(i,{"uni-app":"none",isUniH5:!0}),o=a.getTitleNView();if(o){var s=Tu+parseFloat(n.top||"0");plus.navigator.isImmersedStatusbar()&&(s+=dh()),n.top=String(s),n.bottom=n.bottom||"0"}it=plus.webview.create(r,t,n),o&&it.addEventListener("titleUpdate",function(){var l,u=(l=it)===null||l===void 0?void 0:l.getTitle();a.setStyle({titleNView:{titleText:!u||u==="null"?" ":u}})}),plus.webview.currentWebview().append(it)},aT=()=>{var e;plus.webview.currentWebview().remove(it),(e=it)===null||e===void 0||e.close("none"),it=null},nT=ge({name:"WebView",props:rT,setup(e){var t=Xt(),r=U(null),{hidden:i,onParentReady:a}=ia(r),n=Q(()=>e.webviewStyles);return a(()=>{var o,s=U(pb+t);iT({htmlId:s.value,src:vt(e.src),webviewStyles:n.value}),UniViewJSBridge.publishHandler(hb,{},t),i.value&&((o=it)===null||o===void 0||o.hide())}),Ce(()=>{aT(),UniViewJSBridge.publishHandler(gb,{},t)}),H(()=>e.src,o=>{var s,l=vt(o)||"";if(!!l){if(/^(http|https):\/\//.test(l)&&e.webviewStyles.progress){var u;(u=it)===null||u===void 0||u.setStyle({progress:{color:e.webviewStyles.progress.color}})}(s=it)===null||s===void 0||s.loadURL(l)}}),H(n,o=>{var s;(s=it)===null||s===void 0||s.setStyle(o)}),H(i,o=>{it&&it[o?"hide":"show"]()}),()=>I("uni-web-view",{ref:r},null,512)}});class oT extends we{constructor(t,r,i,a){super(t,"uni-web-view",nT,r,i,a)}}var sT={"#text":YS,"#comment":sx,VIEW:KS,IMAGE:mE,TEXT:jS,NAVIGATOR:IE,FORM:hE,BUTTON:tE,INPUT:_E,LABEL:bE,RADIO:WE,CHECKBOX:aE,"CHECKBOX-GROUP":nE,AD:eE,CAMERA:rE,CANVAS:iE,"COVER-IMAGE":fE,"COVER-VIEW":vE,EDITOR:dE,"FUNCTIONAL-PAGE-NAVIGATOR":gE,ICON:pE,"RADIO-GROUP":VE,"LIVE-PLAYER":wE,"LIVE-PUSHER":xE,MAP:CE,"MOVABLE-AREA":OE,"MOVABLE-VIEW":AE,"OFFICIAL-ACCOUNT":kE,"OPEN-DATA":ME,PICKER:FE,"PICKER-VIEW":zE,"PICKER-VIEW-COLUMN":UE,PROGRESS:HE,"RICH-TEXT":jE,"SCROLL-VIEW":YE,SLIDER:qE,SWIPER:XE,"SWIPER-ITEM":ZE,SWITCH:KE,TEXTAREA:GE,VIDEO:tT,"WEB-VIEW":oT};function lT(e,t){return()=>g_(e,t)}var jn=new Map;function at(e){return jn.get(e)}function uT(e){return jn.get(e)}function yh(e){return jn.delete(e)}function Sh(e,t,r,i){var a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{},n;if(e===0)n=new ti(e,t,r,document.createElement(t));else{var o=sT[t];o?n=new o(e,r,i,a):n=new wd(e,document.createElement(t),r,i,a)}return jn.set(e,n),n}var Il=[],Eh=!1;function Th(e){if(Eh)return e();Il.push(e)}function kl(){Eh=!0,Il.forEach(e=>e()),Il.length=0}function fT(){}function Ch(e){var{css:t,route:r,platform:i,pixelRatio:a,windowWidth:n,disableScroll:o,statusbarHeight:s,windowTop:l,windowBottom:u}=e;cT(r),vT(i,a,n),dT();var f=plus.webview.currentWebview().id;window.__id__=f,document.title="".concat(r,"[").concat(f,"]"),gT(s,l,u),o&&document.addEventListener("touchmove",nb),t?hT(r):kl()}function cT(e){window.__PAGE_INFO__={route:e}}function vT(e,t,r){window.__SYSTEM_INFO__={platform:e,pixelRatio:t,windowWidth:r}}function dT(){Sh(0,"div",-1,-1).$=document.getElementById("app")}function hT(e){var t=document.createElement("link");t.type="text/css",t.rel="stylesheet",t.href=e+".css",t.onload=kl,t.onerror=kl,document.head.appendChild(t)}function gT(e,t,r){var i={"--window-left":"0px","--window-right":"0px","--window-top":t+"px","--window-bottom":r+"px","--status-bar-height":e+"px"};X_(i)}var Oh=!1;function pT(e){if(!Oh){Oh=!0;var t={onReachBottomDistance:e,onPageScroll(r){UniViewJSBridge.publishHandler(Ip,{scrollTop:r})},onReachBottom(){UniViewJSBridge.publishHandler(kp)}};requestAnimationFrame(()=>document.addEventListener("scroll",ob(t)))}}function mT(e,t){var{scrollTop:r,selector:i,duration:a}=e;Lp(i||r||0,a),t()}function _T(e){var t=e[0];t[0]===Ru?bT(t):Th(()=>wT(e))}function bT(e){return Ch(e[1])}function wT(e){var t=e[0],r=U1(t[0]===db?t[1]:[]);e.forEach(i=>{switch(i[0]){case Ru:return Ch(i[1]);case Up:return fT();case Hp:return Sh(i[1],r(i[2]),i[3],i[4],H1(r,i[5]));case Wp:return at(i[1]).remove();case Vp:return at(i[1]).setAttr(r(i[2]),r(i[3]));case jp:return at(i[1]).removeAttr(r(i[2]));case Yp:return at(i[1]).addEvent(r(i[2]),i[3]);case Zp:return at(i[1]).addWxsEvent(r(i[2]),r(i[3]),i[4]);case qp:return at(i[1]).removeEvent(r(i[2]));case Xp:return at(i[1]).setText(r(i[2]));case Kp:return pT(i[1])}}),Y1()}function xT(){var{subscribe:e}=UniViewJSBridge;e(bc,_T),e(mb,Ge().setLocale),e(wc,yT)}function yT(){UniViewJSBridge.publishHandler("webviewReady")}function Ah(e){return window.__$__(e).$}function ST(e){var t={};if(e.id&&(t.id=""),e.dataset&&(t.dataset={}),e.rect&&(t.left=0,t.right=0,t.top=0,t.bottom=0),e.size&&(t.width=document.documentElement.clientWidth,t.height=document.documentElement.clientHeight),e.scrollOffset){var r=document.documentElement,i=document.body;t.scrollLeft=r.scrollLeft||i.scrollLeft||0,t.scrollTop=r.scrollTop||i.scrollTop||0,t.scrollHeight=r.scrollHeight||i.scrollHeight||0,t.scrollWidth=r.scrollWidth||i.scrollWidth||0}return t}function Ml(e,t){var r={},{top:i}=q_();if(t.id&&(r.id=e.id),t.dataset&&(r.dataset=To(e)),t.rect||t.size){var a=e.getBoundingClientRect();t.rect&&(r.left=a.left,r.right=a.right,r.top=a.top-i,r.bottom=a.bottom-i),t.size&&(r.width=a.width,r.height=a.height)}if(Array.isArray(t.properties)&&t.properties.forEach(s=>{s=s.replace(/-([a-z])/g,function(l,u){return u.toUpperCase()})}),t.scrollOffset)if(e.tagName==="UNI-SCROLL-VIEW"){var n=e.children[0].children[0];r.scrollLeft=n.scrollLeft,r.scrollTop=n.scrollTop,r.scrollHeight=n.scrollHeight,r.scrollWidth=n.scrollWidth}else r.scrollLeft=0,r.scrollTop=0,r.scrollHeight=0,r.scrollWidth=0;if(Array.isArray(t.computedStyle)){var o=getComputedStyle(e);t.computedStyle.forEach(s=>{r[s]=o[s]})}return t.context&&(r.contextInfo=WS(e)),r}function ET(e,t){return e?window.__$__(e).$:t.$el}function Ih(e,t){var r=e.matches||e.matchesSelector||e.mozMatchesSelector||e.msMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector||function(i){for(var a=this.parentElement.querySelectorAll(i),n=a.length;--n>=0&&a.item(n)!==this;);return n>-1};return r.call(e,t)}function TT(e,t,r,i,a){var n=ET(t,e),o=n.parentElement;if(!o)return i?null:[];var{nodeType:s}=n,l=s===3||s===8;if(i){var u=l?o.querySelector(r):Ih(n,r)?n:n.querySelector(r);return u?Ml(u,a):null}else{var f=[],v=(l?o:n).querySelectorAll(r);return v&&v.length&&[].forEach.call(v,p=>{f.push(Ml(p,a))}),!l&&Ih(n,r)&&f.unshift(Ml(n,a)),f}}function CT(e,t,r){var i=[];t.forEach(a=>{var{component:n,selector:o,single:s,fields:l}=a;n===null?i.push(ST(l)):i.push(TT(e,n,o,s,l))}),r(i)}function OT(e,t){var{pageStyle:r,rootFontSize:i}=t;if(r){var a=document.querySelector("uni-page-body")||document.body;a.setAttribute("style",r)}i&&document.documentElement.style.fontSize!==i&&(document.documentElement.style.fontSize=i)}function AT(e,t){var{reqId:r,component:i,options:a,callback:n}=e,o=Ah(i);(o.__io||(o.__io={}))[r]=L1(o,a,n)}function IT(e,t){var{reqId:r,component:i}=e,a=Ah(i),n=a.__io&&a.__io[r];n&&(n.disconnect(),delete a.__io[r])}var Rl={},Ll={};function kT(e){var t=[],r=["width","minWidth","maxWidth","height","minHeight","maxHeight","orientation"];for(var i of r)i!=="orientation"&&e[i]&&Number(e[i]>=0)&&t.push("(".concat(kh(i),": ").concat(Number(e[i]),"px)")),i==="orientation"&&e[i]&&t.push("(".concat(kh(i),": ").concat(e[i],")"));var a=t.join(" and ");return a}function kh(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase()}function MT(e,t){var{reqId:r,component:i,options:a,callback:n}=e,o=Rl[r]=window.matchMedia(kT(a)),s=Ll[r]=l=>n(l.matches);s(o),o.addListener(s)}function RT(e,t){var{reqId:r,component:i}=e,a=Ll[r],n=Rl[r];n&&(n.removeListener(a),delete Ll[r],delete Rl[r])}function LT(e,t){var{family:r,source:i,desc:a}=e;Rp(r,i,a).then(()=>{t()}).catch(n=>{t(n.toString())})}var PT={$el:document.body};function NT(){var e=Xt();S0(e,t=>function(){for(var r=arguments.length,i=new Array(r),a=0;a{t.apply(null,i)})}),bt(e,"requestComponentInfo",(t,r)=>{CT(PT,t.reqs,r)}),bt(e,"addIntersectionObserver",t=>{AT(ve({},t,{callback(r){UniViewJSBridge.publishHandler(t.eventName,r)}}))}),bt(e,"removeIntersectionObserver",t=>{IT(t)}),bt(e,"addMediaQueryObserver",t=>{MT(ve({},t,{callback(r){UniViewJSBridge.publishHandler(t.eventName,r)}}))}),bt(e,"removeMediaQueryObserver",t=>{RT(t)}),bt(e,k1,mT),bt(e,I1,LT),bt(e,A1,t=>{OT(null,t)})}window.uni=F1,window.UniViewJSBridge=xc,window.rpx2px=id,window.__$__=at,window.__f__=Bp;function Mh(){R0(),NT(),xT(),z1(),xc.publishHandler(wc)}typeof plus!="undefined"?Mh():document.addEventListener("plusready",Mh)}); diff --git a/packages/uni-app-plus/package.json b/packages/uni-app-plus/package.json index 45592a611..c51565ca5 100644 --- a/packages/uni-app-plus/package.json +++ b/packages/uni-app-plus/package.json @@ -32,8 +32,10 @@ "@dcloudio/uni-h5": "3.0.0-alpha-3021320211123002", "@dcloudio/uni-i18n": "3.0.0-alpha-3021320211123002", "@dcloudio/uni-shared": "3.0.0-alpha-3021320211123002", + "@types/pako": "1.0.2", "@vue/compiler-sfc": "3.2.22", "autoprefixer": "^10.4.0", + "pako": "^1.0.11", "vue": "3.2.22" }, "dependencies": { diff --git a/packages/uni-app-plus/src/platform/index.ts b/packages/uni-app-plus/src/platform/index.ts index 83f59eb27..eef2a250c 100644 --- a/packages/uni-app-plus/src/platform/index.ts +++ b/packages/uni-app-plus/src/platform/index.ts @@ -29,3 +29,5 @@ export { getEnterOptions, getLaunchOptions, } from '../service/framework/app/utils' + +export { inflateRaw, deflateRaw } from 'pako' diff --git a/packages/uni-components/package.json b/packages/uni-components/package.json index ff0fb6627..ba548925f 100644 --- a/packages/uni-components/package.json +++ b/packages/uni-components/package.json @@ -18,7 +18,6 @@ }, "gitHead": "33e807d66e1fe47e2ee08ad9c59247e37b8884da", "devDependencies": { - "@dcloudio/uni-shared": "3.0.0-alpha-3021320211123002", - "pako": "^1.0.11" + "@dcloudio/uni-shared": "3.0.0-alpha-3021320211123002" } } diff --git a/packages/uni-components/src/components/canvas/index.tsx b/packages/uni-components/src/components/canvas/index.tsx index fc21b15a5..45a502b32 100644 --- a/packages/uni-components/src/components/canvas/index.tsx +++ b/packages/uni-components/src/components/canvas/index.tsx @@ -13,12 +13,13 @@ import { saveImage, getSameOriginUrl, getRealPath, + inflateRaw, + deflateRaw, } from '@dcloudio/uni-platform' import ResizeSensor from '../resize-sensor' import { useNativeEvent, NativeEventTrigger } from '../../helpers/useEvent' import { pixelRatio, wrapper, initHidpi } from '../../helpers/hidpi' import { once } from '@dcloudio/uni-shared' -import pako from 'pako' const initHidpiOnce = /*#__PURE__*/ once(() => { return __NODE_JS__ ? onMounted(initHidpi) : initHidpi() @@ -562,7 +563,7 @@ function useMethods( } else { const imgData = context.getImageData(0, 0, destWidth, destHeight) if (__PLATFORM__ === 'app') { - data = pako.deflateRaw(imgData.data as any, { to: 'string' }) + data = deflateRaw(imgData.data as any, { to: 'string' }) compressed = true } else { // fix [...]展开TypedArray在低版本手机报错的问题,使用Array.prototype.slice @@ -609,7 +610,7 @@ function useMethods( ) { try { if (__PLATFORM__ === 'app' && compressed) { - data = pako.inflateRaw(data) as any + data = inflateRaw(data) as any } if (!height) { height = Math.round(data.length / 4 / width) diff --git a/packages/uni-h5/dist/uni-h5.cjs.js b/packages/uni-h5/dist/uni-h5.cjs.js index 85fa37720..08e0ea63d 100644 --- a/packages/uni-h5/dist/uni-h5.cjs.js +++ b/packages/uni-h5/dist/uni-h5.cjs.js @@ -142,7 +142,7 @@ function initNavigationBarI18n(navigationBar) { } } function initTabBarI18n(tabBar2) { - if (isEnableLocale()) { + if (isEnableLocale() && tabBar2.list) { tabBar2.list.forEach((item) => { defineI18nProperty(item, ["text"]); }); @@ -1561,6 +1561,10 @@ function getSameOriginUrl(url) { } return urlToFile(url).then(fileToUrl); } +const inflateRaw = (...args) => { +}; +const deflateRaw = (...args) => { +}; var ResizeSensor = /* @__PURE__ */ defineBuiltInComponent({ name: "ResizeSensor", props: { @@ -2043,13 +2047,13 @@ function useMethods(canvasRef, actionsWaiting) { compressed }, resolve) { try { + if (false) + ; if (!height) { height = Math.round(data.length / 4 / width); } const canvas = getTempCanvas(width, height); const context = canvas.getContext("2d"); - if (false) - ; context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0); canvasRef.value.getContext("2d").drawImage(canvas, x, y, width, height); canvas.height = canvas.width = 0; diff --git a/packages/uni-h5/dist/uni-h5.es.js b/packages/uni-h5/dist/uni-h5.es.js index c1245f700..15258134d 100644 --- a/packages/uni-h5/dist/uni-h5.es.js +++ b/packages/uni-h5/dist/uni-h5.es.js @@ -328,7 +328,7 @@ function initNavigationBarI18n(navigationBar) { } } function initTabBarI18n(tabBar2) { - if (isEnableLocale()) { + if (isEnableLocale() && tabBar2.list) { tabBar2.list.forEach((item) => { defineI18nProperty(item, ["text"]); }); @@ -3946,6 +3946,7 @@ const canvasGetImageData = /* @__PURE__ */ defineAsyncApi(API_CANVAS_GET_IMAGE_D if (imgData && imgData.length) { data.data = new Uint8ClampedArray(imgData); } + delete data.compressed; resolve(data); } operateCanvas(canvasId, pageId, "getImageData", { @@ -3978,7 +3979,9 @@ const canvasPutImageData = /* @__PURE__ */ defineAsyncApi(API_CANVAS_PUT_IMAGE_D resolve(data2); }); }; - data = Array.prototype.slice.call(data); + { + data = Array.prototype.slice.call(data); + } operate(); }, CanvasPutImageDataProtocol, CanvasPutImageDataOptions); const canvasToTempFilePath = /* @__PURE__ */ defineAsyncApi(API_CANVAS_TO_TEMP_FILE_PATH, ({ @@ -6115,6 +6118,10 @@ function initLaunchOptions({ extend(enterOptions, launchOptions); return launchOptions; } +const inflateRaw = (...args) => { +}; +const deflateRaw = (...args) => { +}; var ResizeSensor = /* @__PURE__ */ defineBuiltInComponent({ name: "ResizeSensor", props: { @@ -6745,13 +6752,13 @@ function useMethods(canvasRef, actionsWaiting) { compressed }, resolve) { try { + if (false) + ; if (!height) { height = Math.round(data.length / 4 / width); } const canvas = getTempCanvas(width, height); const context = canvas.getContext("2d"); - if (false) - ; context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0); canvasRef.value.getContext("2d").drawImage(canvas, x, y, width, height); canvas.height = canvas.width = 0; diff --git a/packages/uni-h5/package.json b/packages/uni-h5/package.json index a51e17e2d..54b2b4e14 100644 --- a/packages/uni-h5/package.json +++ b/packages/uni-h5/package.json @@ -36,7 +36,6 @@ "@vue/server-renderer": "3.2.22", "@vue/shared": "3.2.22", "localstorage-polyfill": "^1.0.1", - "pako": "^2.0.3", "safe-area-insets": "^1.4.1", "vue-router": "^4.0.12", "xmlhttprequest": "^1.8.0" diff --git a/packages/uni-h5/src/platform/index.ts b/packages/uni-h5/src/platform/index.ts index 49eab7212..1ba32b298 100644 --- a/packages/uni-h5/src/platform/index.ts +++ b/packages/uni-h5/src/platform/index.ts @@ -16,3 +16,6 @@ export * from './saveImage' export * from './constants' export { getSameOriginUrl } from '../helpers/file' export { getEnterOptions, getLaunchOptions } from '../framework/setup/utils' + +export const inflateRaw = (...args: any[]): any => {} +export const deflateRaw = (...args: any[]): any => {} diff --git a/packages/uni-h5/vite.config.ts b/packages/uni-h5/vite.config.ts index ee71f7e37..f0c65245f 100644 --- a/packages/uni-h5/vite.config.ts +++ b/packages/uni-h5/vite.config.ts @@ -38,8 +38,6 @@ const rollupPlugins = [ // 该插件限制了不能以__开头 _NODE_JS_: FORMAT === 'cjs' ? 1 : 0, }, - // 忽略 pako 内部条件编译 - exclude: ['**/*/pako.esm.mjs'], }), ] if (FORMAT === 'cjs') { diff --git a/packages/uni-stat/dist/uni-stat.cjs.js b/packages/uni-stat/dist/uni-stat.cjs.js index 60c3aec3c..d3bd8f326 100644 --- a/packages/uni-stat/dist/uni-stat.cjs.js +++ b/packages/uni-stat/dist/uni-stat.cjs.js @@ -10,952 +10,952 @@ const APP_PVER_TIME = 300; const OPERATING_TIME = 10; const DIFF_TIME = 60 * 1000 * 60 * 24; -const statConfig$1 = { - appid: process.env.UNI_APP_ID, +const statConfig$1 = { + appid: process.env.UNI_APP_ID, +}; +const UUID_KEY = '__DC_STAT_UUID'; +const UUID_VALUE = '__DC_UUID_VALUE'; + +function getUuid() { + let uuid = ''; + if (getPlatformName() === 'n') { + try { + uuid = plus.runtime.getDCloudId(); + } catch (e) { + uuid = ''; + } + return uuid + } + + try { + uuid = uni.getStorageSync(UUID_KEY); + } catch (e) { + uuid = UUID_VALUE; + } + + if (!uuid) { + uuid = Date.now() + '' + Math.floor(Math.random() * 1e7); + try { + uni.setStorageSync(UUID_KEY, uuid); + } catch (e) { + uni.setStorageSync(UUID_KEY, UUID_VALUE); + } + } + return uuid +} + +const getSgin = (statData) => { + let arr = Object.keys(statData); + let sortArr = arr.sort(); + let sgin = {}; + let sginStr = ''; + for (var i in sortArr) { + sgin[sortArr[i]] = statData[sortArr[i]]; + sginStr += sortArr[i] + '=' + statData[sortArr[i]] + '&'; + } + // const options = sginStr.substr(0, sginStr.length - 1) + // sginStr = sginStr.substr(0, sginStr.length - 1) + '&key=' + STAT_KEY; + // const si = crypto.createHash('md5').update(sginStr).digest('hex'); + return { + sign: '', + options: sginStr.substr(0, sginStr.length - 1), + } +}; + +const getSplicing = (data) => { + let str = ''; + for (var i in data) { + str += i + '=' + data[i] + '&'; + } + return str.substr(0, str.length - 1) +}; + +const getTime = () => { + return parseInt(new Date().getTime() / 1000) +}; + +const getPlatformName = () => { + const aliArr = ['y', 'a', 'p', 'mp-ali']; + const platformList = { + 'app-plus': 'n', + h5: 'h5', + 'mp-weixin': 'wx', + [aliArr.reverse().join('')]: 'ali', + 'mp-baidu': 'bd', + 'mp-toutiao': 'tt', + 'mp-qq': 'qq', + 'quickapp-native': 'qn', + 'mp-kuaishou': 'ks', + }; + return platformList[process.env.VUE_APP_PLATFORM] +}; + +const getPackName = () => { + let packName = ''; + if (getPlatformName() === 'wx' || getPlatformName() === 'qq') { + // 兼容微信小程序低版本基础库 + if (uni.canIUse('getAccountInfoSync')) { + packName = uni.getAccountInfoSync().miniProgram.appId || ''; + } + } + return packName +}; + +const getVersion = () => { + return getPlatformName() === 'n' ? plus.runtime.version : '' +}; + +const getChannel = () => { + const platformName = getPlatformName(); + let channel = ''; + if (platformName === 'n') { + channel = plus.runtime.channel; + } + return channel +}; + +const getScene = (options) => { + const platformName = getPlatformName(); + let scene = ''; + if (options) { + return options + } + if (platformName === 'wx') { + scene = uni.getLaunchOptionsSync().scene; + } + return scene +}; +const First__Visit__Time__KEY = 'First__Visit__Time'; +const Last__Visit__Time__KEY = 'Last__Visit__Time'; + +const getFirstVisitTime = () => { + const timeStorge = uni.getStorageSync(First__Visit__Time__KEY); + let time = 0; + if (timeStorge) { + time = timeStorge; + } else { + time = getTime(); + uni.setStorageSync(First__Visit__Time__KEY, time); + uni.removeStorageSync(Last__Visit__Time__KEY); + } + return time +}; + +const getLastVisitTime = () => { + const timeStorge = uni.getStorageSync(Last__Visit__Time__KEY); + let time = 0; + if (timeStorge) { + time = timeStorge; + } else { + time = ''; + } + uni.setStorageSync(Last__Visit__Time__KEY, getTime()); + return time +}; + +const PAGE_RESIDENCE_TIME = '__page__residence__time'; +let First_Page_residence_time = 0; +let Last_Page_residence_time = 0; + +const setPageResidenceTime = () => { + First_Page_residence_time = getTime(); + if (getPlatformName() === 'n') { + uni.setStorageSync(PAGE_RESIDENCE_TIME, getTime()); + } + return First_Page_residence_time +}; + +const getPageResidenceTime = () => { + Last_Page_residence_time = getTime(); + if (getPlatformName() === 'n') { + First_Page_residence_time = uni.getStorageSync(PAGE_RESIDENCE_TIME); + } + return Last_Page_residence_time - First_Page_residence_time +}; +const TOTAL__VISIT__COUNT = 'Total__Visit__Count'; +const getTotalVisitCount = () => { + const timeStorge = uni.getStorageSync(TOTAL__VISIT__COUNT); + let count = 1; + if (timeStorge) { + count = timeStorge; + count++; + } + uni.setStorageSync(TOTAL__VISIT__COUNT, count); + return count +}; + +const GetEncodeURIComponentOptions = (statData) => { + let data = {}; + for (let prop in statData) { + data[prop] = encodeURIComponent(statData[prop]); + } + return data +}; + +let Set__First__Time = 0; +let Set__Last__Time = 0; + +const getFirstTime = () => { + let time = new Date().getTime(); + Set__First__Time = time; + Set__Last__Time = 0; + return time +}; + +const getLastTime = () => { + let time = new Date().getTime(); + Set__Last__Time = time; + return time +}; + +const getResidenceTime = (type) => { + let residenceTime = 0; + if (Set__First__Time !== 0) { + residenceTime = Set__Last__Time - Set__First__Time; + } + + residenceTime = parseInt(residenceTime / 1000); + residenceTime = residenceTime < 1 ? 1 : residenceTime; + if (type === 'app') { + let overtime = residenceTime > APP_PVER_TIME ? true : false; + return { + residenceTime, + overtime, + } + } + if (type === 'page') { + let overtime = residenceTime > PAGE_PVER_TIME ? true : false; + return { + residenceTime, + overtime, + } + } + + return { + residenceTime, + } +}; + +const getRoute = () => { + var pages = getCurrentPages(); + var page = pages[pages.length - 1]; + if (!page) return '' + // TODO 需要确认如果不用 $vm ,其他平台会不会出错 + let _self = page.$vm; + + if (getPlatformName() === 'bd') { + return _self.$mp && _self.$mp.page.is + } else { + return _self.route || (_self.$scope && _self.$scope.route) + } +}; + +const getPageRoute = (_this) => { + let pageVm = _this.self; + let page = pageVm.$page || pageVm.$scope.$page; + return page.fullPath === '/' ? page.route : page.fullPath +}; + +const getPageTypes = (self) => { + if ( + self.$mpType === 'page' || + (self.$mp && self.$mp.mpType === 'page') || + self.$options.mpType === 'page' + ) { + return true + } + return false +}; + +const calibration = (eventName, options) => { + // login 、 share 、pay_success 、pay_fail 、register 、title + if (!eventName) { + console.error(`uni.report 缺少 [eventName] 参数`); + return true + } + if (typeof eventName !== 'string') { + console.error(`uni.report [eventName] 参数类型错误,只能为 String 类型`); + return true + } + if (eventName.length > 255) { + console.error(`uni.report [eventName] 参数长度不能大于 255`); + return true + } + + if (typeof options !== 'string' && typeof options !== 'object') { + console.error( + `uni.report [options] 参数类型错误,只能为 String 或 Object 类型` + ); + return true + } + + if (typeof options === 'string' && options.length > 255) { + console.error(`uni.report [options] 参数长度不能大于 255`); + return true + } + + if (eventName === 'title' && typeof options !== 'string') { + console.error( + 'uni.report [eventName] 参数为 title 时,[options] 参数只能为 String 类型' + ); + return true + } +}; + +const Report_Data_Time = 'Report_Data_Time'; +const Report_Status = 'Report_Status'; +const isReportData = () => { + return new Promise((resolve, reject) => { + let start_time = ''; + let end_time = new Date().getTime(); + let diff_time = DIFF_TIME; + let report_status = 1; + try { + start_time = uni.getStorageSync(Report_Data_Time); + report_status = uni.getStorageSync(Report_Status); + } catch (e) { + start_time = ''; + report_status = 1; + } + + if (report_status === '') { + requestData(({ enable }) => { + uni.setStorageSync(Report_Data_Time, end_time); + uni.setStorageSync(Report_Status, enable); + if (enable === 1) { + resolve(); + } + }); + return + } + + if (report_status === 1) { + resolve(); + } + + if (!start_time) { + uni.setStorageSync(Report_Data_Time, end_time); + start_time = end_time; + } + + if (end_time - start_time > diff_time) { + requestData(({ enable }) => { + uni.setStorageSync(Report_Data_Time, end_time); + uni.setStorageSync(Report_Status, enable); + }); + } + }) +}; + +const requestData = (done) => { + let formData = { + usv: STAT_VERSION, + conf: JSON.stringify({ + ak: statConfig$1.appid, + }), + }; + uni.request({ + url: STAT_URL, + method: 'GET', + data: formData, + success: (res) => { + const { data } = res; + if (data.ret === 0) { + typeof done === 'function' && + done({ + enable: data.enable, + }); + } + }, + fail: (e) => { + let report_status_code = 1; + try { + report_status_code = uni.getStorageSync(Report_Status); + } catch (e) { + report_status_code = 1; + } + if (report_status_code === '') { + report_status_code = 1; + } + typeof done === 'function' && + done({ + enable: report_status_code, + }); + }, + }); }; -const UUID_KEY = '__DC_STAT_UUID'; -const UUID_VALUE = '__DC_UUID_VALUE'; -function getUuid() { - let uuid = ''; - if (getPlatformName() === 'n') { - try { - uuid = plus.runtime.getDCloudId(); - } catch (e) { - uuid = ''; - } - return uuid - } - - try { - uuid = uni.getStorageSync(UUID_KEY); - } catch (e) { - uuid = UUID_VALUE; - } - - if (!uuid) { - uuid = Date.now() + '' + Math.floor(Math.random() * 1e7); - try { - uni.setStorageSync(UUID_KEY, uuid); - } catch (e) { - uni.setStorageSync(UUID_KEY, UUID_VALUE); - } - } - return uuid -} - -const getSgin = (statData) => { - let arr = Object.keys(statData); - let sortArr = arr.sort(); - let sgin = {}; - let sginStr = ''; - for (var i in sortArr) { - sgin[sortArr[i]] = statData[sortArr[i]]; - sginStr += sortArr[i] + '=' + statData[sortArr[i]] + '&'; - } - // const options = sginStr.substr(0, sginStr.length - 1) - // sginStr = sginStr.substr(0, sginStr.length - 1) + '&key=' + STAT_KEY; - // const si = crypto.createHash('md5').update(sginStr).digest('hex'); - return { - sign: '', - options: sginStr.substr(0, sginStr.length - 1), - } -}; - -const getSplicing = (data) => { - let str = ''; - for (var i in data) { - str += i + '=' + data[i] + '&'; - } - return str.substr(0, str.length - 1) -}; - -const getTime = () => { - return parseInt(new Date().getTime() / 1000) -}; - -const getPlatformName = () => { - const aliArr = ['y', 'a', 'p', 'mp-ali']; - const platformList = { - 'app-plus': 'n', - h5: 'h5', - 'mp-weixin': 'wx', - [aliArr.reverse().join('')]: 'ali', - 'mp-baidu': 'bd', - 'mp-toutiao': 'tt', - 'mp-qq': 'qq', - 'quickapp-native': 'qn', - 'mp-kuaishou': 'ks', - }; - return platformList[process.env.VUE_APP_PLATFORM] -}; - -const getPackName = () => { - let packName = ''; - if (getPlatformName() === 'wx' || getPlatformName() === 'qq') { - // 兼容微信小程序低版本基础库 - if (uni.canIUse('getAccountInfoSync')) { - packName = uni.getAccountInfoSync().miniProgram.appId || ''; - } - } - return packName -}; - -const getVersion = () => { - return getPlatformName() === 'n' ? plus.runtime.version : '' -}; - -const getChannel = () => { - const platformName = getPlatformName(); - let channel = ''; - if (platformName === 'n') { - channel = plus.runtime.channel; - } - return channel -}; - -const getScene = (options) => { - const platformName = getPlatformName(); - let scene = ''; - if (options) { - return options - } - if (platformName === 'wx') { - scene = uni.getLaunchOptionsSync().scene; - } - return scene -}; -const First__Visit__Time__KEY = 'First__Visit__Time'; -const Last__Visit__Time__KEY = 'Last__Visit__Time'; - -const getFirstVisitTime = () => { - const timeStorge = uni.getStorageSync(First__Visit__Time__KEY); - let time = 0; - if (timeStorge) { - time = timeStorge; - } else { - time = getTime(); - uni.setStorageSync(First__Visit__Time__KEY, time); - uni.removeStorageSync(Last__Visit__Time__KEY); - } - return time -}; - -const getLastVisitTime = () => { - const timeStorge = uni.getStorageSync(Last__Visit__Time__KEY); - let time = 0; - if (timeStorge) { - time = timeStorge; - } else { - time = ''; - } - uni.setStorageSync(Last__Visit__Time__KEY, getTime()); - return time -}; - -const PAGE_RESIDENCE_TIME = '__page__residence__time'; -let First_Page_residence_time = 0; -let Last_Page_residence_time = 0; - -const setPageResidenceTime = () => { - First_Page_residence_time = getTime(); - if (getPlatformName() === 'n') { - uni.setStorageSync(PAGE_RESIDENCE_TIME, getTime()); - } - return First_Page_residence_time -}; - -const getPageResidenceTime = () => { - Last_Page_residence_time = getTime(); - if (getPlatformName() === 'n') { - First_Page_residence_time = uni.getStorageSync(PAGE_RESIDENCE_TIME); - } - return Last_Page_residence_time - First_Page_residence_time -}; -const TOTAL__VISIT__COUNT = 'Total__Visit__Count'; -const getTotalVisitCount = () => { - const timeStorge = uni.getStorageSync(TOTAL__VISIT__COUNT); - let count = 1; - if (timeStorge) { - count = timeStorge; - count++; - } - uni.setStorageSync(TOTAL__VISIT__COUNT, count); - return count -}; - -const GetEncodeURIComponentOptions = (statData) => { - let data = {}; - for (let prop in statData) { - data[prop] = encodeURIComponent(statData[prop]); - } - return data -}; - -let Set__First__Time = 0; -let Set__Last__Time = 0; - -const getFirstTime = () => { - let time = new Date().getTime(); - Set__First__Time = time; - Set__Last__Time = 0; - return time -}; - -const getLastTime = () => { - let time = new Date().getTime(); - Set__Last__Time = time; - return time -}; - -const getResidenceTime = (type) => { - let residenceTime = 0; - if (Set__First__Time !== 0) { - residenceTime = Set__Last__Time - Set__First__Time; - } - - residenceTime = parseInt(residenceTime / 1000); - residenceTime = residenceTime < 1 ? 1 : residenceTime; - if (type === 'app') { - let overtime = residenceTime > APP_PVER_TIME ? true : false; - return { - residenceTime, - overtime, - } - } - if (type === 'page') { - let overtime = residenceTime > PAGE_PVER_TIME ? true : false; - return { - residenceTime, - overtime, - } - } - - return { - residenceTime, - } -}; - -const getRoute = () => { - var pages = getCurrentPages(); - var page = pages[pages.length - 1]; - if (!page) return '' - // TODO 需要确认如果不用 $vm ,其他平台会不会出错 - let _self = page.$vm; - - if (getPlatformName() === 'bd') { - return _self.$mp && _self.$mp.page.is - } else { - return _self.route || (_self.$scope && _self.$scope.route) - } -}; - -const getPageRoute = (_this) => { - let pageVm = _this.self; - let page = pageVm.$page || pageVm.$scope.$page; - return page.fullPath === '/' ? page.route : page.fullPath -}; - -const getPageTypes = (self) => { - if ( - self.$mpType === 'page' || - (self.$mp && self.$mp.mpType === 'page') || - self.$options.mpType === 'page' - ) { - return true - } - return false -}; - -const calibration = (eventName, options) => { - // login 、 share 、pay_success 、pay_fail 、register 、title - if (!eventName) { - console.error(`uni.report 缺少 [eventName] 参数`); - return true - } - if (typeof eventName !== 'string') { - console.error(`uni.report [eventName] 参数类型错误,只能为 String 类型`); - return true - } - if (eventName.length > 255) { - console.error(`uni.report [eventName] 参数长度不能大于 255`); - return true - } - - if (typeof options !== 'string' && typeof options !== 'object') { - console.error( - `uni.report [options] 参数类型错误,只能为 String 或 Object 类型` - ); - return true - } - - if (typeof options === 'string' && options.length > 255) { - console.error(`uni.report [options] 参数长度不能大于 255`); - return true - } - - if (eventName === 'title' && typeof options !== 'string') { - console.error( - 'uni.report [eventName] 参数为 title 时,[options] 参数只能为 String 类型' - ); - return true - } -}; - -const Report_Data_Time = 'Report_Data_Time'; -const Report_Status = 'Report_Status'; -const isReportData = () => { - return new Promise((resolve, reject) => { - let start_time = ''; - let end_time = new Date().getTime(); - let diff_time = DIFF_TIME; - let report_status = 1; - try { - start_time = uni.getStorageSync(Report_Data_Time); - report_status = uni.getStorageSync(Report_Status); - } catch (e) { - start_time = ''; - report_status = 1; - } - - if (report_status === '') { - requestData(({ enable }) => { - uni.setStorageSync(Report_Data_Time, end_time); - uni.setStorageSync(Report_Status, enable); - if (enable === 1) { - resolve(); - } - }); - return - } - - if (report_status === 1) { - resolve(); - } - - if (!start_time) { - uni.setStorageSync(Report_Data_Time, end_time); - start_time = end_time; - } - - if (end_time - start_time > diff_time) { - requestData(({ enable }) => { - uni.setStorageSync(Report_Data_Time, end_time); - uni.setStorageSync(Report_Status, enable); - }); - } - }) -}; - -const requestData = (done) => { - let formData = { - usv: STAT_VERSION, - conf: JSON.stringify({ - ak: statConfig$1.appid, - }), - }; - uni.request({ - url: STAT_URL, - method: 'GET', - data: formData, - success: (res) => { - const { data } = res; - if (data.ret === 0) { - typeof done === 'function' && - done({ - enable: data.enable, - }); - } - }, - fail: (e) => { - let report_status_code = 1; - try { - report_status_code = uni.getStorageSync(Report_Status); - } catch (e) { - report_status_code = 1; - } - if (report_status_code === '') { - report_status_code = 1; - } - typeof done === 'function' && - done({ - enable: report_status_code, - }); - }, - }); -}; - -let titleJsons = {}; -// #ifdef MP -let pagesTitle = require('uni-pages?{"type":"style"}').default; -pagesTitle = pagesTitle.pages; -for (let i in pagesTitle) { - titleJsons[i] = pagesTitle[i].navigationBarTitleText || ''; -} -// #endif -// #ifndef MP -titleJsons = process.env.UNI_STAT_TITLE_JSON; -// #endif - -const statConfig = { - appid: process.env.UNI_APP_ID, -}; -const resultOptions = uni.getSystemInfoSync(); - -class Util { - constructor() { - this.self = ''; - this._retry = 0; - this._platform = ''; - this._query = {}; - this._navigationBarTitle = { - config: '', - page: '', - report: '', - lt: '', - }; - this._operatingTime = 0; - this._reportingRequestData = { - 1: [], - 11: [], - }; - this.__prevent_triggering = false; - - this.__licationHide = false; - this.__licationShow = false; - this._lastPageRoute = ''; - this.statData = { - uuid: getUuid(), - ut: getPlatformName(), - mpn: getPackName(), - ak: statConfig.appid, - usv: STAT_VERSION, - v: getVersion(), - ch: getChannel(), - cn: '', - pn: '', - ct: '', - t: getTime(), - tt: '', - p: resultOptions.platform === 'android' ? 'a' : 'i', - brand: resultOptions.brand || '', - md: resultOptions.model, - sv: resultOptions.system.replace(/(Android|iOS)\s/, ''), - mpsdk: resultOptions.SDKVersion || '', - mpv: resultOptions.version || '', - lang: resultOptions.language, - pr: resultOptions.pixelRatio, - ww: resultOptions.windowWidth, - wh: resultOptions.windowHeight, - sw: resultOptions.screenWidth, - sh: resultOptions.screenHeight, - }; - // 注册拦截器 - let registerInterceptor = - typeof uni.addInterceptor === 'function' && - process.env.NODE_ENV !== 'development'; - if (registerInterceptor) { - this.addInterceptorInit(); - this.interceptLogin(); - this.interceptShare(true); - this.interceptRequestPayment(); - } - } - - addInterceptorInit() { - let self = this; - uni.addInterceptor('setNavigationBarTitle', { - invoke(args) { - self._navigationBarTitle.page = args.title; - }, - }); - } - - interceptLogin() { - let self = this; - uni.addInterceptor('login', { - complete() { - self._login(); - }, - }); - } - - interceptShare(type) { - let self = this; - if (!type) { - self._share(); - return - } - uni.addInterceptor('share', { - success() { - self._share(); - }, - fail() { - self._share(); - }, - }); - } - - interceptRequestPayment() { - let self = this; - uni.addInterceptor('requestPayment', { - success() { - self._payment('pay_success'); - }, - fail() { - self._payment('pay_fail'); - }, - }); - } - - getIsReportData() { - return isReportData() - } - - _applicationShow() { - if (this.__licationHide) { - getLastTime(); - const time = getResidenceTime('app'); - if (time.overtime) { - let options = { - path: this._lastPageRoute, - scene: this.statData.sc, - }; - this._sendReportRequest(options); - } - this.__licationHide = false; - } - } - - _applicationHide(self, type) { - this.__licationHide = true; - getLastTime(); - const time = getResidenceTime(); - getFirstTime(); - const route = getPageRoute(this); - this._sendHideRequest( - { - urlref: route, - urlref_ts: time.residenceTime, - }, - type - ); - } - - _pageShow() { - const route = getPageRoute(this); - const routepath = getRoute(); - this._navigationBarTitle.config = - (titleJsons && titleJsons[routepath]) || ''; - if (this.__licationShow) { - getFirstTime(); - this.__licationShow = false; - this._lastPageRoute = route; - return - } - - getLastTime(); - const time = getResidenceTime('page'); - // 停留时间 - if (time.overtime) { - let options = { - path: route, - scene: this.statData.sc, - }; - this._sendReportRequest(options); - } - getFirstTime(); - } - - _pageHide() { - if (!this.__licationHide) { - getLastTime(); - const time = getResidenceTime('page'); - let route = getPageRoute(this); - if (!this._lastPageRoute) { - this._lastPageRoute = route; - } - this._sendPageRequest({ - url: route, - urlref: this._lastPageRoute, - urlref_ts: time.residenceTime, - }); - this._lastPageRoute = route; - this._navigationBarTitle = { - config: '', - page: '', - report: '', - lt: '', - }; - return - } - } - - _login() { - this._sendEventRequest( - { - key: 'login', - }, - 0 - ); - } - - _share() { - this._sendEventRequest( - { - key: 'share', - }, - 0 - ); - } - _payment(key) { - this._sendEventRequest( - { - key, - }, - 0 - ); - } - _sendReportRequest(options) { - this._navigationBarTitle.lt = '1'; - this._navigationBarTitle.config = - (titleJsons && titleJsons[options.path]) || ''; - let query = - options.query && JSON.stringify(options.query) !== '{}' - ? '?' + JSON.stringify(options.query) - : ''; - this.statData.lt = '1'; - this.statData.url = options.path + query || ''; - this.statData.t = getTime(); - this.statData.sc = getScene(options.scene); - this.statData.fvts = getFirstVisitTime(); - this.statData.lvts = getLastVisitTime(); - this.statData.tvc = getTotalVisitCount(); - if (getPlatformName() === 'n') { - this.getProperty(); - } else { - this.getNetworkInfo(); - } - } - - _sendPageRequest(opt) { - let { url, urlref, urlref_ts } = opt; - this._navigationBarTitle.lt = '11'; - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '11', - ut: this.statData.ut, - url, - tt: this.statData.tt, - urlref, - urlref_ts, - ch: this.statData.ch, - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options); - } - - _sendHideRequest(opt, type) { - let { urlref, urlref_ts } = opt; - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '3', - ut: this.statData.ut, - urlref, - urlref_ts, - ch: this.statData.ch, - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options, type); - } - _sendEventRequest({ key = '', value = '' } = {}) { - const route = this._lastPageRoute; - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '21', - ut: this.statData.ut, - url: route, - ch: this.statData.ch, - e_n: key, - e_v: typeof value === 'object' ? JSON.stringify(value) : value.toString(), - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options); - } - - getNetworkInfo() { - uni.getNetworkType({ - success: (result) => { - this.statData.net = result.networkType; - this.getLocation(); - }, - }); - } - - getProperty() { - plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => { - this.statData.v = wgtinfo.version || ''; - this.getNetworkInfo(); - }); - } - - getLocation() { - { - this.statData.lat = 0; - this.statData.lng = 0; - this.request(this.statData); - } - } - - request(data, type) { - let time = getTime(); - const title = this._navigationBarTitle; - data.ttn = title.page; - data.ttpj = title.config; - data.ttc = title.report; - let requestData = this._reportingRequestData; - if (getPlatformName() === 'n') { - requestData = uni.getStorageSync('__UNI__STAT__DATA') || {}; - } - if (!requestData[data.lt]) { - requestData[data.lt] = []; - } - requestData[data.lt].push(data); - if (getPlatformName() === 'n') { - uni.setStorageSync('__UNI__STAT__DATA', requestData); - } - if (getPageResidenceTime() < OPERATING_TIME && !type) { - return - } - let uniStatData = this._reportingRequestData; - if (getPlatformName() === 'n') { - uniStatData = uni.getStorageSync('__UNI__STAT__DATA'); - } - // 时间超过,重新获取时间戳 - setPageResidenceTime(); - let firstArr = []; - let contentArr = []; - let lastArr = []; - - for (let i in uniStatData) { - const rd = uniStatData[i]; - rd.forEach((elm) => { - const newData = getSplicing(elm); - if (i === 0) { - firstArr.push(newData); - } else if (i === 3) { - lastArr.push(newData); - } else { - contentArr.push(newData); - } - }); - } - - firstArr.push(...contentArr, ...lastArr); - let optionsData = { - usv: STAT_VERSION, //统计 SDK 版本号 - t: time, //发送请求时的时间戮 - requests: JSON.stringify(firstArr), - }; - - this._reportingRequestData = {}; - if (getPlatformName() === 'n') { - uni.removeStorageSync('__UNI__STAT__DATA'); - } - - if (data.ut === 'h5') { - this.imageRequest(optionsData); - return - } - - if (getPlatformName() === 'n' && this.statData.p === 'a') { - setTimeout(() => { - this._sendRequest(optionsData); - }, 200); - return - } - this._sendRequest(optionsData); - } - _sendRequest(optionsData) { - this.getIsReportData().then(() => { - uni.request({ - url: STAT_URL, - method: 'POST', - data: optionsData, - success: () => {}, - fail: (e) => { - if (++this._retry < 3) { - setTimeout(() => { - this._sendRequest(optionsData); - }, 1000); - } - }, - }); - }); - } - /** - * h5 请求 - */ - imageRequest(data) { - this.getIsReportData().then(() => { - let image = new Image(); - let options = getSgin(GetEncodeURIComponentOptions(data)).options; - image.src = STAT_H5_URL + '?' + options; - }); - } - - sendEvent(key, value) { - // 校验 type 参数 - if (calibration(key, value)) return - - if (key === 'title') { - this._navigationBarTitle.report = value; - return - } - this._sendEventRequest( - { - key, - value: typeof value === 'object' ? JSON.stringify(value) : value, - }, - 1 - ); - } -} - -class Stat extends Util { - static getInstance() { - if (!this.instance) { - this.instance = new Stat(); - } - return this.instance - } - constructor() { - super(); - this.instance = null; - } - - report(options, self) { - // TODO 需要确认如果不用 $vm ,其他平台会不会出错 - setPageResidenceTime(); - this.__licationShow = true; - this._sendReportRequest(options, true); - } - - load(options, self) { - this.self = self; - this._query = options; - } - - show(self) { - this.self = self; - if (getPageTypes(self)) { - this._pageShow(self); - } else { - this._applicationShow(self); - } - } - ready(self) {} - hide(self) { - this.self = self; - if (getPageTypes(self)) { - this._pageHide(self); - } else { - this._applicationHide(self, true); - } - } - error(em) { - if (this._platform === 'devtools') { - if (process.env.NODE_ENV === 'development') { - console.info('当前运行环境为开发者工具,不上报数据。'); - } - } - let emVal = ''; - if (!em.message) { - emVal = JSON.stringify(em); - } else { - emVal = em.stack; - } - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '31', - ut: this.statData.ut, - ch: this.statData.ch, - mpsdk: this.statData.mpsdk, - mpv: this.statData.mpv, - v: this.statData.v, - em: emVal, - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options); - } -} +let titleJsons = {}; +// #ifdef MP +let pagesTitle = require('uni-pages?{"type":"style"}').default; +pagesTitle = pagesTitle.pages; +for (let i in pagesTitle) { + titleJsons[i] = pagesTitle[i].navigationBarTitleText || ''; +} +// #endif +// #ifndef MP +titleJsons = process.env.UNI_STAT_TITLE_JSON; +// #endif + +const statConfig = { + appid: process.env.UNI_APP_ID, +}; +const resultOptions = uni.getSystemInfoSync(); + +class Util { + constructor() { + this.self = ''; + this._retry = 0; + this._platform = ''; + this._query = {}; + this._navigationBarTitle = { + config: '', + page: '', + report: '', + lt: '', + }; + this._operatingTime = 0; + this._reportingRequestData = { + 1: [], + 11: [], + }; + this.__prevent_triggering = false; + + this.__licationHide = false; + this.__licationShow = false; + this._lastPageRoute = ''; + this.statData = { + uuid: getUuid(), + ut: getPlatformName(), + mpn: getPackName(), + ak: statConfig.appid, + usv: STAT_VERSION, + v: getVersion(), + ch: getChannel(), + cn: '', + pn: '', + ct: '', + t: getTime(), + tt: '', + p: resultOptions.platform === 'android' ? 'a' : 'i', + brand: resultOptions.brand || '', + md: resultOptions.model, + sv: resultOptions.system.replace(/(Android|iOS)\s/, ''), + mpsdk: resultOptions.SDKVersion || '', + mpv: resultOptions.version || '', + lang: resultOptions.language, + pr: resultOptions.pixelRatio, + ww: resultOptions.windowWidth, + wh: resultOptions.windowHeight, + sw: resultOptions.screenWidth, + sh: resultOptions.screenHeight, + }; + // 注册拦截器 + let registerInterceptor = + typeof uni.addInterceptor === 'function' && + process.env.NODE_ENV !== 'development'; + if (registerInterceptor) { + this.addInterceptorInit(); + this.interceptLogin(); + this.interceptShare(true); + this.interceptRequestPayment(); + } + } + + addInterceptorInit() { + let self = this; + uni.addInterceptor('setNavigationBarTitle', { + invoke(args) { + self._navigationBarTitle.page = args.title; + }, + }); + } + + interceptLogin() { + let self = this; + uni.addInterceptor('login', { + complete() { + self._login(); + }, + }); + } + + interceptShare(type) { + let self = this; + if (!type) { + self._share(); + return + } + uni.addInterceptor('share', { + success() { + self._share(); + }, + fail() { + self._share(); + }, + }); + } + + interceptRequestPayment() { + let self = this; + uni.addInterceptor('requestPayment', { + success() { + self._payment('pay_success'); + }, + fail() { + self._payment('pay_fail'); + }, + }); + } + + getIsReportData() { + return isReportData() + } + + _applicationShow() { + if (this.__licationHide) { + getLastTime(); + const time = getResidenceTime('app'); + if (time.overtime) { + let options = { + path: this._lastPageRoute, + scene: this.statData.sc, + }; + this._sendReportRequest(options); + } + this.__licationHide = false; + } + } + + _applicationHide(self, type) { + this.__licationHide = true; + getLastTime(); + const time = getResidenceTime(); + getFirstTime(); + const route = getPageRoute(this); + this._sendHideRequest( + { + urlref: route, + urlref_ts: time.residenceTime, + }, + type + ); + } + + _pageShow() { + const route = getPageRoute(this); + const routepath = getRoute(); + this._navigationBarTitle.config = + (titleJsons && titleJsons[routepath]) || ''; + if (this.__licationShow) { + getFirstTime(); + this.__licationShow = false; + this._lastPageRoute = route; + return + } + + getLastTime(); + const time = getResidenceTime('page'); + // 停留时间 + if (time.overtime) { + let options = { + path: route, + scene: this.statData.sc, + }; + this._sendReportRequest(options); + } + getFirstTime(); + } + + _pageHide() { + if (!this.__licationHide) { + getLastTime(); + const time = getResidenceTime('page'); + let route = getPageRoute(this); + if (!this._lastPageRoute) { + this._lastPageRoute = route; + } + this._sendPageRequest({ + url: route, + urlref: this._lastPageRoute, + urlref_ts: time.residenceTime, + }); + this._lastPageRoute = route; + this._navigationBarTitle = { + config: '', + page: '', + report: '', + lt: '', + }; + return + } + } + + _login() { + this._sendEventRequest( + { + key: 'login', + }, + 0 + ); + } + + _share() { + this._sendEventRequest( + { + key: 'share', + }, + 0 + ); + } + _payment(key) { + this._sendEventRequest( + { + key, + }, + 0 + ); + } + _sendReportRequest(options) { + this._navigationBarTitle.lt = '1'; + this._navigationBarTitle.config = + (titleJsons && titleJsons[options.path]) || ''; + let query = + options.query && JSON.stringify(options.query) !== '{}' + ? '?' + JSON.stringify(options.query) + : ''; + this.statData.lt = '1'; + this.statData.url = options.path + query || ''; + this.statData.t = getTime(); + this.statData.sc = getScene(options.scene); + this.statData.fvts = getFirstVisitTime(); + this.statData.lvts = getLastVisitTime(); + this.statData.tvc = getTotalVisitCount(); + if (getPlatformName() === 'n') { + this.getProperty(); + } else { + this.getNetworkInfo(); + } + } + + _sendPageRequest(opt) { + let { url, urlref, urlref_ts } = opt; + this._navigationBarTitle.lt = '11'; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '11', + ut: this.statData.ut, + url, + tt: this.statData.tt, + urlref, + urlref_ts, + ch: this.statData.ch, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } + + _sendHideRequest(opt, type) { + let { urlref, urlref_ts } = opt; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '3', + ut: this.statData.ut, + urlref, + urlref_ts, + ch: this.statData.ch, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options, type); + } + _sendEventRequest({ key = '', value = '' } = {}) { + const route = this._lastPageRoute; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '21', + ut: this.statData.ut, + url: route, + ch: this.statData.ch, + e_n: key, + e_v: typeof value === 'object' ? JSON.stringify(value) : value.toString(), + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } + + getNetworkInfo() { + uni.getNetworkType({ + success: (result) => { + this.statData.net = result.networkType; + this.getLocation(); + }, + }); + } + + getProperty() { + plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => { + this.statData.v = wgtinfo.version || ''; + this.getNetworkInfo(); + }); + } + + getLocation() { + { + this.statData.lat = 0; + this.statData.lng = 0; + this.request(this.statData); + } + } + + request(data, type) { + let time = getTime(); + const title = this._navigationBarTitle; + data.ttn = title.page; + data.ttpj = title.config; + data.ttc = title.report; + let requestData = this._reportingRequestData; + if (getPlatformName() === 'n') { + requestData = uni.getStorageSync('__UNI__STAT__DATA') || {}; + } + if (!requestData[data.lt]) { + requestData[data.lt] = []; + } + requestData[data.lt].push(data); + if (getPlatformName() === 'n') { + uni.setStorageSync('__UNI__STAT__DATA', requestData); + } + if (getPageResidenceTime() < OPERATING_TIME && !type) { + return + } + let uniStatData = this._reportingRequestData; + if (getPlatformName() === 'n') { + uniStatData = uni.getStorageSync('__UNI__STAT__DATA'); + } + // 时间超过,重新获取时间戳 + setPageResidenceTime(); + let firstArr = []; + let contentArr = []; + let lastArr = []; + + for (let i in uniStatData) { + const rd = uniStatData[i]; + rd.forEach((elm) => { + const newData = getSplicing(elm); + if (i === 0) { + firstArr.push(newData); + } else if (i === 3) { + lastArr.push(newData); + } else { + contentArr.push(newData); + } + }); + } + + firstArr.push(...contentArr, ...lastArr); + let optionsData = { + usv: STAT_VERSION, //统计 SDK 版本号 + t: time, //发送请求时的时间戮 + requests: JSON.stringify(firstArr), + }; + + this._reportingRequestData = {}; + if (getPlatformName() === 'n') { + uni.removeStorageSync('__UNI__STAT__DATA'); + } + + if (data.ut === 'h5') { + this.imageRequest(optionsData); + return + } + + if (getPlatformName() === 'n' && this.statData.p === 'a') { + setTimeout(() => { + this._sendRequest(optionsData); + }, 200); + return + } + this._sendRequest(optionsData); + } + _sendRequest(optionsData) { + this.getIsReportData().then(() => { + uni.request({ + url: STAT_URL, + method: 'POST', + data: optionsData, + success: () => {}, + fail: (e) => { + if (++this._retry < 3) { + setTimeout(() => { + this._sendRequest(optionsData); + }, 1000); + } + }, + }); + }); + } + /** + * h5 请求 + */ + imageRequest(data) { + this.getIsReportData().then(() => { + let image = new Image(); + let options = getSgin(GetEncodeURIComponentOptions(data)).options; + image.src = STAT_H5_URL + '?' + options; + }); + } + + sendEvent(key, value) { + // 校验 type 参数 + if (calibration(key, value)) return + + if (key === 'title') { + this._navigationBarTitle.report = value; + return + } + this._sendEventRequest( + { + key, + value: typeof value === 'object' ? JSON.stringify(value) : value, + }, + 1 + ); + } +} + +class Stat extends Util { + static getInstance() { + if (!this.instance) { + this.instance = new Stat(); + } + return this.instance + } + constructor() { + super(); + this.instance = null; + } + + report(options, self) { + // TODO 需要确认如果不用 $vm ,其他平台会不会出错 + setPageResidenceTime(); + this.__licationShow = true; + this._sendReportRequest(options, true); + } + + load(options, self) { + this.self = self; + this._query = options; + } + + show(self) { + this.self = self; + if (getPageTypes(self)) { + this._pageShow(self); + } else { + this._applicationShow(self); + } + } + ready(self) {} + hide(self) { + this.self = self; + if (getPageTypes(self)) { + this._pageHide(self); + } else { + this._applicationHide(self, true); + } + } + error(em) { + if (this._platform === 'devtools') { + if (process.env.NODE_ENV === 'development') { + console.info('当前运行环境为开发者工具,不上报数据。'); + } + } + let emVal = ''; + if (!em.message) { + emVal = JSON.stringify(em); + } else { + emVal = em.stack; + } + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '31', + ut: this.statData.ut, + ch: this.statData.ch, + mpsdk: this.statData.mpsdk, + mpv: this.statData.mpv, + v: this.statData.v, + em: emVal, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } +} var Stat$1 = Stat; -const stat = Stat$1.getInstance(); -let isHide = false; -const lifecycle = { - onLaunch(options) { - stat.report(options, this); - }, - onReady() { - stat.ready(this); - }, - onLoad(options) { - stat.load(options, this); - // 重写分享,获取分享上报事件 - if (this.$scope && this.$scope.onShareAppMessage) { - let oldShareAppMessage = this.$scope.onShareAppMessage; - this.$scope.onShareAppMessage = function (options) { - stat.interceptShare(false); - return oldShareAppMessage.call(this, options) - }; - } - }, - onShow() { - isHide = false; - stat.show(this); - }, - onHide() { - isHide = true; - stat.hide(this); - }, - onUnload() { - if (isHide) { - isHide = false; - return - } - stat.hide(this); - }, - onError(e) { - stat.error(e); - }, -}; - -function main() { - if (process.env.NODE_ENV === 'development') { - uni.report = function (type, options) {}; - } else { - uni.onAppLaunch((options) => { - stat.report(options); - // 小程序平台此时也无法获取getApp,统一在options中传递一个app对象 - options.app.$vm.$.appContext.app.mixin(lifecycle); - uni.report = function (type, options) { - stat.sendEvent(type, options); - }; - }); - } -} - +const stat = Stat$1.getInstance(); +let isHide = false; +const lifecycle = { + onLaunch(options) { + stat.report(options, this); + }, + onReady() { + stat.ready(this); + }, + onLoad(options) { + stat.load(options, this); + // 重写分享,获取分享上报事件 + if (this.$scope && this.$scope.onShareAppMessage) { + let oldShareAppMessage = this.$scope.onShareAppMessage; + this.$scope.onShareAppMessage = function (options) { + stat.interceptShare(false); + return oldShareAppMessage.call(this, options) + }; + } + }, + onShow() { + isHide = false; + stat.show(this); + }, + onHide() { + isHide = true; + stat.hide(this); + }, + onUnload() { + if (isHide) { + isHide = false; + return + } + stat.hide(this); + }, + onError(e) { + stat.error(e); + }, +}; + +function main() { + if (process.env.NODE_ENV === 'development') { + uni.report = function (type, options) {}; + } else { + uni.onAppLaunch((options) => { + stat.report(options); + // 小程序平台此时也无法获取getApp,统一在options中传递一个app对象 + options.app.$vm.$.appContext.app.mixin(lifecycle); + uni.report = function (type, options) { + stat.sendEvent(type, options); + }; + }); + } +} + main(); diff --git a/packages/uni-stat/dist/uni-stat.es.js b/packages/uni-stat/dist/uni-stat.es.js index 017f38e9b..bc5b1638d 100644 --- a/packages/uni-stat/dist/uni-stat.es.js +++ b/packages/uni-stat/dist/uni-stat.es.js @@ -8,952 +8,952 @@ const APP_PVER_TIME = 300; const OPERATING_TIME = 10; const DIFF_TIME = 60 * 1000 * 60 * 24; -const statConfig$1 = { - appid: process.env.UNI_APP_ID, +const statConfig$1 = { + appid: process.env.UNI_APP_ID, +}; +const UUID_KEY = '__DC_STAT_UUID'; +const UUID_VALUE = '__DC_UUID_VALUE'; + +function getUuid() { + let uuid = ''; + if (getPlatformName() === 'n') { + try { + uuid = plus.runtime.getDCloudId(); + } catch (e) { + uuid = ''; + } + return uuid + } + + try { + uuid = uni.getStorageSync(UUID_KEY); + } catch (e) { + uuid = UUID_VALUE; + } + + if (!uuid) { + uuid = Date.now() + '' + Math.floor(Math.random() * 1e7); + try { + uni.setStorageSync(UUID_KEY, uuid); + } catch (e) { + uni.setStorageSync(UUID_KEY, UUID_VALUE); + } + } + return uuid +} + +const getSgin = (statData) => { + let arr = Object.keys(statData); + let sortArr = arr.sort(); + let sgin = {}; + let sginStr = ''; + for (var i in sortArr) { + sgin[sortArr[i]] = statData[sortArr[i]]; + sginStr += sortArr[i] + '=' + statData[sortArr[i]] + '&'; + } + // const options = sginStr.substr(0, sginStr.length - 1) + // sginStr = sginStr.substr(0, sginStr.length - 1) + '&key=' + STAT_KEY; + // const si = crypto.createHash('md5').update(sginStr).digest('hex'); + return { + sign: '', + options: sginStr.substr(0, sginStr.length - 1), + } +}; + +const getSplicing = (data) => { + let str = ''; + for (var i in data) { + str += i + '=' + data[i] + '&'; + } + return str.substr(0, str.length - 1) +}; + +const getTime = () => { + return parseInt(new Date().getTime() / 1000) +}; + +const getPlatformName = () => { + const aliArr = ['y', 'a', 'p', 'mp-ali']; + const platformList = { + 'app-plus': 'n', + h5: 'h5', + 'mp-weixin': 'wx', + [aliArr.reverse().join('')]: 'ali', + 'mp-baidu': 'bd', + 'mp-toutiao': 'tt', + 'mp-qq': 'qq', + 'quickapp-native': 'qn', + 'mp-kuaishou': 'ks', + }; + return platformList[process.env.VUE_APP_PLATFORM] +}; + +const getPackName = () => { + let packName = ''; + if (getPlatformName() === 'wx' || getPlatformName() === 'qq') { + // 兼容微信小程序低版本基础库 + if (uni.canIUse('getAccountInfoSync')) { + packName = uni.getAccountInfoSync().miniProgram.appId || ''; + } + } + return packName +}; + +const getVersion = () => { + return getPlatformName() === 'n' ? plus.runtime.version : '' +}; + +const getChannel = () => { + const platformName = getPlatformName(); + let channel = ''; + if (platformName === 'n') { + channel = plus.runtime.channel; + } + return channel +}; + +const getScene = (options) => { + const platformName = getPlatformName(); + let scene = ''; + if (options) { + return options + } + if (platformName === 'wx') { + scene = uni.getLaunchOptionsSync().scene; + } + return scene +}; +const First__Visit__Time__KEY = 'First__Visit__Time'; +const Last__Visit__Time__KEY = 'Last__Visit__Time'; + +const getFirstVisitTime = () => { + const timeStorge = uni.getStorageSync(First__Visit__Time__KEY); + let time = 0; + if (timeStorge) { + time = timeStorge; + } else { + time = getTime(); + uni.setStorageSync(First__Visit__Time__KEY, time); + uni.removeStorageSync(Last__Visit__Time__KEY); + } + return time +}; + +const getLastVisitTime = () => { + const timeStorge = uni.getStorageSync(Last__Visit__Time__KEY); + let time = 0; + if (timeStorge) { + time = timeStorge; + } else { + time = ''; + } + uni.setStorageSync(Last__Visit__Time__KEY, getTime()); + return time +}; + +const PAGE_RESIDENCE_TIME = '__page__residence__time'; +let First_Page_residence_time = 0; +let Last_Page_residence_time = 0; + +const setPageResidenceTime = () => { + First_Page_residence_time = getTime(); + if (getPlatformName() === 'n') { + uni.setStorageSync(PAGE_RESIDENCE_TIME, getTime()); + } + return First_Page_residence_time +}; + +const getPageResidenceTime = () => { + Last_Page_residence_time = getTime(); + if (getPlatformName() === 'n') { + First_Page_residence_time = uni.getStorageSync(PAGE_RESIDENCE_TIME); + } + return Last_Page_residence_time - First_Page_residence_time +}; +const TOTAL__VISIT__COUNT = 'Total__Visit__Count'; +const getTotalVisitCount = () => { + const timeStorge = uni.getStorageSync(TOTAL__VISIT__COUNT); + let count = 1; + if (timeStorge) { + count = timeStorge; + count++; + } + uni.setStorageSync(TOTAL__VISIT__COUNT, count); + return count +}; + +const GetEncodeURIComponentOptions = (statData) => { + let data = {}; + for (let prop in statData) { + data[prop] = encodeURIComponent(statData[prop]); + } + return data +}; + +let Set__First__Time = 0; +let Set__Last__Time = 0; + +const getFirstTime = () => { + let time = new Date().getTime(); + Set__First__Time = time; + Set__Last__Time = 0; + return time +}; + +const getLastTime = () => { + let time = new Date().getTime(); + Set__Last__Time = time; + return time +}; + +const getResidenceTime = (type) => { + let residenceTime = 0; + if (Set__First__Time !== 0) { + residenceTime = Set__Last__Time - Set__First__Time; + } + + residenceTime = parseInt(residenceTime / 1000); + residenceTime = residenceTime < 1 ? 1 : residenceTime; + if (type === 'app') { + let overtime = residenceTime > APP_PVER_TIME ? true : false; + return { + residenceTime, + overtime, + } + } + if (type === 'page') { + let overtime = residenceTime > PAGE_PVER_TIME ? true : false; + return { + residenceTime, + overtime, + } + } + + return { + residenceTime, + } +}; + +const getRoute = () => { + var pages = getCurrentPages(); + var page = pages[pages.length - 1]; + if (!page) return '' + // TODO 需要确认如果不用 $vm ,其他平台会不会出错 + let _self = page.$vm; + + if (getPlatformName() === 'bd') { + return _self.$mp && _self.$mp.page.is + } else { + return _self.route || (_self.$scope && _self.$scope.route) + } +}; + +const getPageRoute = (_this) => { + let pageVm = _this.self; + let page = pageVm.$page || pageVm.$scope.$page; + return page.fullPath === '/' ? page.route : page.fullPath +}; + +const getPageTypes = (self) => { + if ( + self.$mpType === 'page' || + (self.$mp && self.$mp.mpType === 'page') || + self.$options.mpType === 'page' + ) { + return true + } + return false +}; + +const calibration = (eventName, options) => { + // login 、 share 、pay_success 、pay_fail 、register 、title + if (!eventName) { + console.error(`uni.report 缺少 [eventName] 参数`); + return true + } + if (typeof eventName !== 'string') { + console.error(`uni.report [eventName] 参数类型错误,只能为 String 类型`); + return true + } + if (eventName.length > 255) { + console.error(`uni.report [eventName] 参数长度不能大于 255`); + return true + } + + if (typeof options !== 'string' && typeof options !== 'object') { + console.error( + `uni.report [options] 参数类型错误,只能为 String 或 Object 类型` + ); + return true + } + + if (typeof options === 'string' && options.length > 255) { + console.error(`uni.report [options] 参数长度不能大于 255`); + return true + } + + if (eventName === 'title' && typeof options !== 'string') { + console.error( + 'uni.report [eventName] 参数为 title 时,[options] 参数只能为 String 类型' + ); + return true + } +}; + +const Report_Data_Time = 'Report_Data_Time'; +const Report_Status = 'Report_Status'; +const isReportData = () => { + return new Promise((resolve, reject) => { + let start_time = ''; + let end_time = new Date().getTime(); + let diff_time = DIFF_TIME; + let report_status = 1; + try { + start_time = uni.getStorageSync(Report_Data_Time); + report_status = uni.getStorageSync(Report_Status); + } catch (e) { + start_time = ''; + report_status = 1; + } + + if (report_status === '') { + requestData(({ enable }) => { + uni.setStorageSync(Report_Data_Time, end_time); + uni.setStorageSync(Report_Status, enable); + if (enable === 1) { + resolve(); + } + }); + return + } + + if (report_status === 1) { + resolve(); + } + + if (!start_time) { + uni.setStorageSync(Report_Data_Time, end_time); + start_time = end_time; + } + + if (end_time - start_time > diff_time) { + requestData(({ enable }) => { + uni.setStorageSync(Report_Data_Time, end_time); + uni.setStorageSync(Report_Status, enable); + }); + } + }) +}; + +const requestData = (done) => { + let formData = { + usv: STAT_VERSION, + conf: JSON.stringify({ + ak: statConfig$1.appid, + }), + }; + uni.request({ + url: STAT_URL, + method: 'GET', + data: formData, + success: (res) => { + const { data } = res; + if (data.ret === 0) { + typeof done === 'function' && + done({ + enable: data.enable, + }); + } + }, + fail: (e) => { + let report_status_code = 1; + try { + report_status_code = uni.getStorageSync(Report_Status); + } catch (e) { + report_status_code = 1; + } + if (report_status_code === '') { + report_status_code = 1; + } + typeof done === 'function' && + done({ + enable: report_status_code, + }); + }, + }); }; -const UUID_KEY = '__DC_STAT_UUID'; -const UUID_VALUE = '__DC_UUID_VALUE'; -function getUuid() { - let uuid = ''; - if (getPlatformName() === 'n') { - try { - uuid = plus.runtime.getDCloudId(); - } catch (e) { - uuid = ''; - } - return uuid - } - - try { - uuid = uni.getStorageSync(UUID_KEY); - } catch (e) { - uuid = UUID_VALUE; - } - - if (!uuid) { - uuid = Date.now() + '' + Math.floor(Math.random() * 1e7); - try { - uni.setStorageSync(UUID_KEY, uuid); - } catch (e) { - uni.setStorageSync(UUID_KEY, UUID_VALUE); - } - } - return uuid -} - -const getSgin = (statData) => { - let arr = Object.keys(statData); - let sortArr = arr.sort(); - let sgin = {}; - let sginStr = ''; - for (var i in sortArr) { - sgin[sortArr[i]] = statData[sortArr[i]]; - sginStr += sortArr[i] + '=' + statData[sortArr[i]] + '&'; - } - // const options = sginStr.substr(0, sginStr.length - 1) - // sginStr = sginStr.substr(0, sginStr.length - 1) + '&key=' + STAT_KEY; - // const si = crypto.createHash('md5').update(sginStr).digest('hex'); - return { - sign: '', - options: sginStr.substr(0, sginStr.length - 1), - } -}; - -const getSplicing = (data) => { - let str = ''; - for (var i in data) { - str += i + '=' + data[i] + '&'; - } - return str.substr(0, str.length - 1) -}; - -const getTime = () => { - return parseInt(new Date().getTime() / 1000) -}; - -const getPlatformName = () => { - const aliArr = ['y', 'a', 'p', 'mp-ali']; - const platformList = { - 'app-plus': 'n', - h5: 'h5', - 'mp-weixin': 'wx', - [aliArr.reverse().join('')]: 'ali', - 'mp-baidu': 'bd', - 'mp-toutiao': 'tt', - 'mp-qq': 'qq', - 'quickapp-native': 'qn', - 'mp-kuaishou': 'ks', - }; - return platformList[process.env.VUE_APP_PLATFORM] -}; - -const getPackName = () => { - let packName = ''; - if (getPlatformName() === 'wx' || getPlatformName() === 'qq') { - // 兼容微信小程序低版本基础库 - if (uni.canIUse('getAccountInfoSync')) { - packName = uni.getAccountInfoSync().miniProgram.appId || ''; - } - } - return packName -}; - -const getVersion = () => { - return getPlatformName() === 'n' ? plus.runtime.version : '' -}; - -const getChannel = () => { - const platformName = getPlatformName(); - let channel = ''; - if (platformName === 'n') { - channel = plus.runtime.channel; - } - return channel -}; - -const getScene = (options) => { - const platformName = getPlatformName(); - let scene = ''; - if (options) { - return options - } - if (platformName === 'wx') { - scene = uni.getLaunchOptionsSync().scene; - } - return scene -}; -const First__Visit__Time__KEY = 'First__Visit__Time'; -const Last__Visit__Time__KEY = 'Last__Visit__Time'; - -const getFirstVisitTime = () => { - const timeStorge = uni.getStorageSync(First__Visit__Time__KEY); - let time = 0; - if (timeStorge) { - time = timeStorge; - } else { - time = getTime(); - uni.setStorageSync(First__Visit__Time__KEY, time); - uni.removeStorageSync(Last__Visit__Time__KEY); - } - return time -}; - -const getLastVisitTime = () => { - const timeStorge = uni.getStorageSync(Last__Visit__Time__KEY); - let time = 0; - if (timeStorge) { - time = timeStorge; - } else { - time = ''; - } - uni.setStorageSync(Last__Visit__Time__KEY, getTime()); - return time -}; - -const PAGE_RESIDENCE_TIME = '__page__residence__time'; -let First_Page_residence_time = 0; -let Last_Page_residence_time = 0; - -const setPageResidenceTime = () => { - First_Page_residence_time = getTime(); - if (getPlatformName() === 'n') { - uni.setStorageSync(PAGE_RESIDENCE_TIME, getTime()); - } - return First_Page_residence_time -}; - -const getPageResidenceTime = () => { - Last_Page_residence_time = getTime(); - if (getPlatformName() === 'n') { - First_Page_residence_time = uni.getStorageSync(PAGE_RESIDENCE_TIME); - } - return Last_Page_residence_time - First_Page_residence_time -}; -const TOTAL__VISIT__COUNT = 'Total__Visit__Count'; -const getTotalVisitCount = () => { - const timeStorge = uni.getStorageSync(TOTAL__VISIT__COUNT); - let count = 1; - if (timeStorge) { - count = timeStorge; - count++; - } - uni.setStorageSync(TOTAL__VISIT__COUNT, count); - return count -}; - -const GetEncodeURIComponentOptions = (statData) => { - let data = {}; - for (let prop in statData) { - data[prop] = encodeURIComponent(statData[prop]); - } - return data -}; - -let Set__First__Time = 0; -let Set__Last__Time = 0; - -const getFirstTime = () => { - let time = new Date().getTime(); - Set__First__Time = time; - Set__Last__Time = 0; - return time -}; - -const getLastTime = () => { - let time = new Date().getTime(); - Set__Last__Time = time; - return time -}; - -const getResidenceTime = (type) => { - let residenceTime = 0; - if (Set__First__Time !== 0) { - residenceTime = Set__Last__Time - Set__First__Time; - } - - residenceTime = parseInt(residenceTime / 1000); - residenceTime = residenceTime < 1 ? 1 : residenceTime; - if (type === 'app') { - let overtime = residenceTime > APP_PVER_TIME ? true : false; - return { - residenceTime, - overtime, - } - } - if (type === 'page') { - let overtime = residenceTime > PAGE_PVER_TIME ? true : false; - return { - residenceTime, - overtime, - } - } - - return { - residenceTime, - } -}; - -const getRoute = () => { - var pages = getCurrentPages(); - var page = pages[pages.length - 1]; - if (!page) return '' - // TODO 需要确认如果不用 $vm ,其他平台会不会出错 - let _self = page.$vm; - - if (getPlatformName() === 'bd') { - return _self.$mp && _self.$mp.page.is - } else { - return _self.route || (_self.$scope && _self.$scope.route) - } -}; - -const getPageRoute = (_this) => { - let pageVm = _this.self; - let page = pageVm.$page || pageVm.$scope.$page; - return page.fullPath === '/' ? page.route : page.fullPath -}; - -const getPageTypes = (self) => { - if ( - self.$mpType === 'page' || - (self.$mp && self.$mp.mpType === 'page') || - self.$options.mpType === 'page' - ) { - return true - } - return false -}; - -const calibration = (eventName, options) => { - // login 、 share 、pay_success 、pay_fail 、register 、title - if (!eventName) { - console.error(`uni.report 缺少 [eventName] 参数`); - return true - } - if (typeof eventName !== 'string') { - console.error(`uni.report [eventName] 参数类型错误,只能为 String 类型`); - return true - } - if (eventName.length > 255) { - console.error(`uni.report [eventName] 参数长度不能大于 255`); - return true - } - - if (typeof options !== 'string' && typeof options !== 'object') { - console.error( - `uni.report [options] 参数类型错误,只能为 String 或 Object 类型` - ); - return true - } - - if (typeof options === 'string' && options.length > 255) { - console.error(`uni.report [options] 参数长度不能大于 255`); - return true - } - - if (eventName === 'title' && typeof options !== 'string') { - console.error( - 'uni.report [eventName] 参数为 title 时,[options] 参数只能为 String 类型' - ); - return true - } -}; - -const Report_Data_Time = 'Report_Data_Time'; -const Report_Status = 'Report_Status'; -const isReportData = () => { - return new Promise((resolve, reject) => { - let start_time = ''; - let end_time = new Date().getTime(); - let diff_time = DIFF_TIME; - let report_status = 1; - try { - start_time = uni.getStorageSync(Report_Data_Time); - report_status = uni.getStorageSync(Report_Status); - } catch (e) { - start_time = ''; - report_status = 1; - } - - if (report_status === '') { - requestData(({ enable }) => { - uni.setStorageSync(Report_Data_Time, end_time); - uni.setStorageSync(Report_Status, enable); - if (enable === 1) { - resolve(); - } - }); - return - } - - if (report_status === 1) { - resolve(); - } - - if (!start_time) { - uni.setStorageSync(Report_Data_Time, end_time); - start_time = end_time; - } - - if (end_time - start_time > diff_time) { - requestData(({ enable }) => { - uni.setStorageSync(Report_Data_Time, end_time); - uni.setStorageSync(Report_Status, enable); - }); - } - }) -}; - -const requestData = (done) => { - let formData = { - usv: STAT_VERSION, - conf: JSON.stringify({ - ak: statConfig$1.appid, - }), - }; - uni.request({ - url: STAT_URL, - method: 'GET', - data: formData, - success: (res) => { - const { data } = res; - if (data.ret === 0) { - typeof done === 'function' && - done({ - enable: data.enable, - }); - } - }, - fail: (e) => { - let report_status_code = 1; - try { - report_status_code = uni.getStorageSync(Report_Status); - } catch (e) { - report_status_code = 1; - } - if (report_status_code === '') { - report_status_code = 1; - } - typeof done === 'function' && - done({ - enable: report_status_code, - }); - }, - }); -}; - -let titleJsons = {}; -// #ifdef MP -let pagesTitle = require('uni-pages?{"type":"style"}').default; -pagesTitle = pagesTitle.pages; -for (let i in pagesTitle) { - titleJsons[i] = pagesTitle[i].navigationBarTitleText || ''; -} -// #endif -// #ifndef MP -titleJsons = process.env.UNI_STAT_TITLE_JSON; -// #endif - -const statConfig = { - appid: process.env.UNI_APP_ID, -}; -const resultOptions = uni.getSystemInfoSync(); - -class Util { - constructor() { - this.self = ''; - this._retry = 0; - this._platform = ''; - this._query = {}; - this._navigationBarTitle = { - config: '', - page: '', - report: '', - lt: '', - }; - this._operatingTime = 0; - this._reportingRequestData = { - 1: [], - 11: [], - }; - this.__prevent_triggering = false; - - this.__licationHide = false; - this.__licationShow = false; - this._lastPageRoute = ''; - this.statData = { - uuid: getUuid(), - ut: getPlatformName(), - mpn: getPackName(), - ak: statConfig.appid, - usv: STAT_VERSION, - v: getVersion(), - ch: getChannel(), - cn: '', - pn: '', - ct: '', - t: getTime(), - tt: '', - p: resultOptions.platform === 'android' ? 'a' : 'i', - brand: resultOptions.brand || '', - md: resultOptions.model, - sv: resultOptions.system.replace(/(Android|iOS)\s/, ''), - mpsdk: resultOptions.SDKVersion || '', - mpv: resultOptions.version || '', - lang: resultOptions.language, - pr: resultOptions.pixelRatio, - ww: resultOptions.windowWidth, - wh: resultOptions.windowHeight, - sw: resultOptions.screenWidth, - sh: resultOptions.screenHeight, - }; - // 注册拦截器 - let registerInterceptor = - typeof uni.addInterceptor === 'function' && - process.env.NODE_ENV !== 'development'; - if (registerInterceptor) { - this.addInterceptorInit(); - this.interceptLogin(); - this.interceptShare(true); - this.interceptRequestPayment(); - } - } - - addInterceptorInit() { - let self = this; - uni.addInterceptor('setNavigationBarTitle', { - invoke(args) { - self._navigationBarTitle.page = args.title; - }, - }); - } - - interceptLogin() { - let self = this; - uni.addInterceptor('login', { - complete() { - self._login(); - }, - }); - } - - interceptShare(type) { - let self = this; - if (!type) { - self._share(); - return - } - uni.addInterceptor('share', { - success() { - self._share(); - }, - fail() { - self._share(); - }, - }); - } - - interceptRequestPayment() { - let self = this; - uni.addInterceptor('requestPayment', { - success() { - self._payment('pay_success'); - }, - fail() { - self._payment('pay_fail'); - }, - }); - } - - getIsReportData() { - return isReportData() - } - - _applicationShow() { - if (this.__licationHide) { - getLastTime(); - const time = getResidenceTime('app'); - if (time.overtime) { - let options = { - path: this._lastPageRoute, - scene: this.statData.sc, - }; - this._sendReportRequest(options); - } - this.__licationHide = false; - } - } - - _applicationHide(self, type) { - this.__licationHide = true; - getLastTime(); - const time = getResidenceTime(); - getFirstTime(); - const route = getPageRoute(this); - this._sendHideRequest( - { - urlref: route, - urlref_ts: time.residenceTime, - }, - type - ); - } - - _pageShow() { - const route = getPageRoute(this); - const routepath = getRoute(); - this._navigationBarTitle.config = - (titleJsons && titleJsons[routepath]) || ''; - if (this.__licationShow) { - getFirstTime(); - this.__licationShow = false; - this._lastPageRoute = route; - return - } - - getLastTime(); - const time = getResidenceTime('page'); - // 停留时间 - if (time.overtime) { - let options = { - path: route, - scene: this.statData.sc, - }; - this._sendReportRequest(options); - } - getFirstTime(); - } - - _pageHide() { - if (!this.__licationHide) { - getLastTime(); - const time = getResidenceTime('page'); - let route = getPageRoute(this); - if (!this._lastPageRoute) { - this._lastPageRoute = route; - } - this._sendPageRequest({ - url: route, - urlref: this._lastPageRoute, - urlref_ts: time.residenceTime, - }); - this._lastPageRoute = route; - this._navigationBarTitle = { - config: '', - page: '', - report: '', - lt: '', - }; - return - } - } - - _login() { - this._sendEventRequest( - { - key: 'login', - }, - 0 - ); - } - - _share() { - this._sendEventRequest( - { - key: 'share', - }, - 0 - ); - } - _payment(key) { - this._sendEventRequest( - { - key, - }, - 0 - ); - } - _sendReportRequest(options) { - this._navigationBarTitle.lt = '1'; - this._navigationBarTitle.config = - (titleJsons && titleJsons[options.path]) || ''; - let query = - options.query && JSON.stringify(options.query) !== '{}' - ? '?' + JSON.stringify(options.query) - : ''; - this.statData.lt = '1'; - this.statData.url = options.path + query || ''; - this.statData.t = getTime(); - this.statData.sc = getScene(options.scene); - this.statData.fvts = getFirstVisitTime(); - this.statData.lvts = getLastVisitTime(); - this.statData.tvc = getTotalVisitCount(); - if (getPlatformName() === 'n') { - this.getProperty(); - } else { - this.getNetworkInfo(); - } - } - - _sendPageRequest(opt) { - let { url, urlref, urlref_ts } = opt; - this._navigationBarTitle.lt = '11'; - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '11', - ut: this.statData.ut, - url, - tt: this.statData.tt, - urlref, - urlref_ts, - ch: this.statData.ch, - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options); - } - - _sendHideRequest(opt, type) { - let { urlref, urlref_ts } = opt; - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '3', - ut: this.statData.ut, - urlref, - urlref_ts, - ch: this.statData.ch, - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options, type); - } - _sendEventRequest({ key = '', value = '' } = {}) { - const route = this._lastPageRoute; - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '21', - ut: this.statData.ut, - url: route, - ch: this.statData.ch, - e_n: key, - e_v: typeof value === 'object' ? JSON.stringify(value) : value.toString(), - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options); - } - - getNetworkInfo() { - uni.getNetworkType({ - success: (result) => { - this.statData.net = result.networkType; - this.getLocation(); - }, - }); - } - - getProperty() { - plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => { - this.statData.v = wgtinfo.version || ''; - this.getNetworkInfo(); - }); - } - - getLocation() { - { - this.statData.lat = 0; - this.statData.lng = 0; - this.request(this.statData); - } - } - - request(data, type) { - let time = getTime(); - const title = this._navigationBarTitle; - data.ttn = title.page; - data.ttpj = title.config; - data.ttc = title.report; - let requestData = this._reportingRequestData; - if (getPlatformName() === 'n') { - requestData = uni.getStorageSync('__UNI__STAT__DATA') || {}; - } - if (!requestData[data.lt]) { - requestData[data.lt] = []; - } - requestData[data.lt].push(data); - if (getPlatformName() === 'n') { - uni.setStorageSync('__UNI__STAT__DATA', requestData); - } - if (getPageResidenceTime() < OPERATING_TIME && !type) { - return - } - let uniStatData = this._reportingRequestData; - if (getPlatformName() === 'n') { - uniStatData = uni.getStorageSync('__UNI__STAT__DATA'); - } - // 时间超过,重新获取时间戳 - setPageResidenceTime(); - let firstArr = []; - let contentArr = []; - let lastArr = []; - - for (let i in uniStatData) { - const rd = uniStatData[i]; - rd.forEach((elm) => { - const newData = getSplicing(elm); - if (i === 0) { - firstArr.push(newData); - } else if (i === 3) { - lastArr.push(newData); - } else { - contentArr.push(newData); - } - }); - } - - firstArr.push(...contentArr, ...lastArr); - let optionsData = { - usv: STAT_VERSION, //统计 SDK 版本号 - t: time, //发送请求时的时间戮 - requests: JSON.stringify(firstArr), - }; - - this._reportingRequestData = {}; - if (getPlatformName() === 'n') { - uni.removeStorageSync('__UNI__STAT__DATA'); - } - - if (data.ut === 'h5') { - this.imageRequest(optionsData); - return - } - - if (getPlatformName() === 'n' && this.statData.p === 'a') { - setTimeout(() => { - this._sendRequest(optionsData); - }, 200); - return - } - this._sendRequest(optionsData); - } - _sendRequest(optionsData) { - this.getIsReportData().then(() => { - uni.request({ - url: STAT_URL, - method: 'POST', - data: optionsData, - success: () => {}, - fail: (e) => { - if (++this._retry < 3) { - setTimeout(() => { - this._sendRequest(optionsData); - }, 1000); - } - }, - }); - }); - } - /** - * h5 请求 - */ - imageRequest(data) { - this.getIsReportData().then(() => { - let image = new Image(); - let options = getSgin(GetEncodeURIComponentOptions(data)).options; - image.src = STAT_H5_URL + '?' + options; - }); - } - - sendEvent(key, value) { - // 校验 type 参数 - if (calibration(key, value)) return - - if (key === 'title') { - this._navigationBarTitle.report = value; - return - } - this._sendEventRequest( - { - key, - value: typeof value === 'object' ? JSON.stringify(value) : value, - }, - 1 - ); - } -} - -class Stat extends Util { - static getInstance() { - if (!this.instance) { - this.instance = new Stat(); - } - return this.instance - } - constructor() { - super(); - this.instance = null; - } - - report(options, self) { - // TODO 需要确认如果不用 $vm ,其他平台会不会出错 - setPageResidenceTime(); - this.__licationShow = true; - this._sendReportRequest(options, true); - } - - load(options, self) { - this.self = self; - this._query = options; - } - - show(self) { - this.self = self; - if (getPageTypes(self)) { - this._pageShow(self); - } else { - this._applicationShow(self); - } - } - ready(self) {} - hide(self) { - this.self = self; - if (getPageTypes(self)) { - this._pageHide(self); - } else { - this._applicationHide(self, true); - } - } - error(em) { - if (this._platform === 'devtools') { - if (process.env.NODE_ENV === 'development') { - console.info('当前运行环境为开发者工具,不上报数据。'); - } - } - let emVal = ''; - if (!em.message) { - emVal = JSON.stringify(em); - } else { - emVal = em.stack; - } - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '31', - ut: this.statData.ut, - ch: this.statData.ch, - mpsdk: this.statData.mpsdk, - mpv: this.statData.mpv, - v: this.statData.v, - em: emVal, - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options); - } -} +let titleJsons = {}; +// #ifdef MP +let pagesTitle = require('uni-pages?{"type":"style"}').default; +pagesTitle = pagesTitle.pages; +for (let i in pagesTitle) { + titleJsons[i] = pagesTitle[i].navigationBarTitleText || ''; +} +// #endif +// #ifndef MP +titleJsons = process.env.UNI_STAT_TITLE_JSON; +// #endif + +const statConfig = { + appid: process.env.UNI_APP_ID, +}; +const resultOptions = uni.getSystemInfoSync(); + +class Util { + constructor() { + this.self = ''; + this._retry = 0; + this._platform = ''; + this._query = {}; + this._navigationBarTitle = { + config: '', + page: '', + report: '', + lt: '', + }; + this._operatingTime = 0; + this._reportingRequestData = { + 1: [], + 11: [], + }; + this.__prevent_triggering = false; + + this.__licationHide = false; + this.__licationShow = false; + this._lastPageRoute = ''; + this.statData = { + uuid: getUuid(), + ut: getPlatformName(), + mpn: getPackName(), + ak: statConfig.appid, + usv: STAT_VERSION, + v: getVersion(), + ch: getChannel(), + cn: '', + pn: '', + ct: '', + t: getTime(), + tt: '', + p: resultOptions.platform === 'android' ? 'a' : 'i', + brand: resultOptions.brand || '', + md: resultOptions.model, + sv: resultOptions.system.replace(/(Android|iOS)\s/, ''), + mpsdk: resultOptions.SDKVersion || '', + mpv: resultOptions.version || '', + lang: resultOptions.language, + pr: resultOptions.pixelRatio, + ww: resultOptions.windowWidth, + wh: resultOptions.windowHeight, + sw: resultOptions.screenWidth, + sh: resultOptions.screenHeight, + }; + // 注册拦截器 + let registerInterceptor = + typeof uni.addInterceptor === 'function' && + process.env.NODE_ENV !== 'development'; + if (registerInterceptor) { + this.addInterceptorInit(); + this.interceptLogin(); + this.interceptShare(true); + this.interceptRequestPayment(); + } + } + + addInterceptorInit() { + let self = this; + uni.addInterceptor('setNavigationBarTitle', { + invoke(args) { + self._navigationBarTitle.page = args.title; + }, + }); + } + + interceptLogin() { + let self = this; + uni.addInterceptor('login', { + complete() { + self._login(); + }, + }); + } + + interceptShare(type) { + let self = this; + if (!type) { + self._share(); + return + } + uni.addInterceptor('share', { + success() { + self._share(); + }, + fail() { + self._share(); + }, + }); + } + + interceptRequestPayment() { + let self = this; + uni.addInterceptor('requestPayment', { + success() { + self._payment('pay_success'); + }, + fail() { + self._payment('pay_fail'); + }, + }); + } + + getIsReportData() { + return isReportData() + } + + _applicationShow() { + if (this.__licationHide) { + getLastTime(); + const time = getResidenceTime('app'); + if (time.overtime) { + let options = { + path: this._lastPageRoute, + scene: this.statData.sc, + }; + this._sendReportRequest(options); + } + this.__licationHide = false; + } + } + + _applicationHide(self, type) { + this.__licationHide = true; + getLastTime(); + const time = getResidenceTime(); + getFirstTime(); + const route = getPageRoute(this); + this._sendHideRequest( + { + urlref: route, + urlref_ts: time.residenceTime, + }, + type + ); + } + + _pageShow() { + const route = getPageRoute(this); + const routepath = getRoute(); + this._navigationBarTitle.config = + (titleJsons && titleJsons[routepath]) || ''; + if (this.__licationShow) { + getFirstTime(); + this.__licationShow = false; + this._lastPageRoute = route; + return + } + + getLastTime(); + const time = getResidenceTime('page'); + // 停留时间 + if (time.overtime) { + let options = { + path: route, + scene: this.statData.sc, + }; + this._sendReportRequest(options); + } + getFirstTime(); + } + + _pageHide() { + if (!this.__licationHide) { + getLastTime(); + const time = getResidenceTime('page'); + let route = getPageRoute(this); + if (!this._lastPageRoute) { + this._lastPageRoute = route; + } + this._sendPageRequest({ + url: route, + urlref: this._lastPageRoute, + urlref_ts: time.residenceTime, + }); + this._lastPageRoute = route; + this._navigationBarTitle = { + config: '', + page: '', + report: '', + lt: '', + }; + return + } + } + + _login() { + this._sendEventRequest( + { + key: 'login', + }, + 0 + ); + } + + _share() { + this._sendEventRequest( + { + key: 'share', + }, + 0 + ); + } + _payment(key) { + this._sendEventRequest( + { + key, + }, + 0 + ); + } + _sendReportRequest(options) { + this._navigationBarTitle.lt = '1'; + this._navigationBarTitle.config = + (titleJsons && titleJsons[options.path]) || ''; + let query = + options.query && JSON.stringify(options.query) !== '{}' + ? '?' + JSON.stringify(options.query) + : ''; + this.statData.lt = '1'; + this.statData.url = options.path + query || ''; + this.statData.t = getTime(); + this.statData.sc = getScene(options.scene); + this.statData.fvts = getFirstVisitTime(); + this.statData.lvts = getLastVisitTime(); + this.statData.tvc = getTotalVisitCount(); + if (getPlatformName() === 'n') { + this.getProperty(); + } else { + this.getNetworkInfo(); + } + } + + _sendPageRequest(opt) { + let { url, urlref, urlref_ts } = opt; + this._navigationBarTitle.lt = '11'; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '11', + ut: this.statData.ut, + url, + tt: this.statData.tt, + urlref, + urlref_ts, + ch: this.statData.ch, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } + + _sendHideRequest(opt, type) { + let { urlref, urlref_ts } = opt; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '3', + ut: this.statData.ut, + urlref, + urlref_ts, + ch: this.statData.ch, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options, type); + } + _sendEventRequest({ key = '', value = '' } = {}) { + const route = this._lastPageRoute; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '21', + ut: this.statData.ut, + url: route, + ch: this.statData.ch, + e_n: key, + e_v: typeof value === 'object' ? JSON.stringify(value) : value.toString(), + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } + + getNetworkInfo() { + uni.getNetworkType({ + success: (result) => { + this.statData.net = result.networkType; + this.getLocation(); + }, + }); + } + + getProperty() { + plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => { + this.statData.v = wgtinfo.version || ''; + this.getNetworkInfo(); + }); + } + + getLocation() { + { + this.statData.lat = 0; + this.statData.lng = 0; + this.request(this.statData); + } + } + + request(data, type) { + let time = getTime(); + const title = this._navigationBarTitle; + data.ttn = title.page; + data.ttpj = title.config; + data.ttc = title.report; + let requestData = this._reportingRequestData; + if (getPlatformName() === 'n') { + requestData = uni.getStorageSync('__UNI__STAT__DATA') || {}; + } + if (!requestData[data.lt]) { + requestData[data.lt] = []; + } + requestData[data.lt].push(data); + if (getPlatformName() === 'n') { + uni.setStorageSync('__UNI__STAT__DATA', requestData); + } + if (getPageResidenceTime() < OPERATING_TIME && !type) { + return + } + let uniStatData = this._reportingRequestData; + if (getPlatformName() === 'n') { + uniStatData = uni.getStorageSync('__UNI__STAT__DATA'); + } + // 时间超过,重新获取时间戳 + setPageResidenceTime(); + let firstArr = []; + let contentArr = []; + let lastArr = []; + + for (let i in uniStatData) { + const rd = uniStatData[i]; + rd.forEach((elm) => { + const newData = getSplicing(elm); + if (i === 0) { + firstArr.push(newData); + } else if (i === 3) { + lastArr.push(newData); + } else { + contentArr.push(newData); + } + }); + } + + firstArr.push(...contentArr, ...lastArr); + let optionsData = { + usv: STAT_VERSION, //统计 SDK 版本号 + t: time, //发送请求时的时间戮 + requests: JSON.stringify(firstArr), + }; + + this._reportingRequestData = {}; + if (getPlatformName() === 'n') { + uni.removeStorageSync('__UNI__STAT__DATA'); + } + + if (data.ut === 'h5') { + this.imageRequest(optionsData); + return + } + + if (getPlatformName() === 'n' && this.statData.p === 'a') { + setTimeout(() => { + this._sendRequest(optionsData); + }, 200); + return + } + this._sendRequest(optionsData); + } + _sendRequest(optionsData) { + this.getIsReportData().then(() => { + uni.request({ + url: STAT_URL, + method: 'POST', + data: optionsData, + success: () => {}, + fail: (e) => { + if (++this._retry < 3) { + setTimeout(() => { + this._sendRequest(optionsData); + }, 1000); + } + }, + }); + }); + } + /** + * h5 请求 + */ + imageRequest(data) { + this.getIsReportData().then(() => { + let image = new Image(); + let options = getSgin(GetEncodeURIComponentOptions(data)).options; + image.src = STAT_H5_URL + '?' + options; + }); + } + + sendEvent(key, value) { + // 校验 type 参数 + if (calibration(key, value)) return + + if (key === 'title') { + this._navigationBarTitle.report = value; + return + } + this._sendEventRequest( + { + key, + value: typeof value === 'object' ? JSON.stringify(value) : value, + }, + 1 + ); + } +} + +class Stat extends Util { + static getInstance() { + if (!this.instance) { + this.instance = new Stat(); + } + return this.instance + } + constructor() { + super(); + this.instance = null; + } + + report(options, self) { + // TODO 需要确认如果不用 $vm ,其他平台会不会出错 + setPageResidenceTime(); + this.__licationShow = true; + this._sendReportRequest(options, true); + } + + load(options, self) { + this.self = self; + this._query = options; + } + + show(self) { + this.self = self; + if (getPageTypes(self)) { + this._pageShow(self); + } else { + this._applicationShow(self); + } + } + ready(self) {} + hide(self) { + this.self = self; + if (getPageTypes(self)) { + this._pageHide(self); + } else { + this._applicationHide(self, true); + } + } + error(em) { + if (this._platform === 'devtools') { + if (process.env.NODE_ENV === 'development') { + console.info('当前运行环境为开发者工具,不上报数据。'); + } + } + let emVal = ''; + if (!em.message) { + emVal = JSON.stringify(em); + } else { + emVal = em.stack; + } + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '31', + ut: this.statData.ut, + ch: this.statData.ch, + mpsdk: this.statData.mpsdk, + mpv: this.statData.mpv, + v: this.statData.v, + em: emVal, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } +} var Stat$1 = Stat; -const stat = Stat$1.getInstance(); -let isHide = false; -const lifecycle = { - onLaunch(options) { - stat.report(options, this); - }, - onReady() { - stat.ready(this); - }, - onLoad(options) { - stat.load(options, this); - // 重写分享,获取分享上报事件 - if (this.$scope && this.$scope.onShareAppMessage) { - let oldShareAppMessage = this.$scope.onShareAppMessage; - this.$scope.onShareAppMessage = function (options) { - stat.interceptShare(false); - return oldShareAppMessage.call(this, options) - }; - } - }, - onShow() { - isHide = false; - stat.show(this); - }, - onHide() { - isHide = true; - stat.hide(this); - }, - onUnload() { - if (isHide) { - isHide = false; - return - } - stat.hide(this); - }, - onError(e) { - stat.error(e); - }, -}; - -function main() { - if (process.env.NODE_ENV === 'development') { - uni.report = function (type, options) {}; - } else { - uni.onAppLaunch((options) => { - stat.report(options); - // 小程序平台此时也无法获取getApp,统一在options中传递一个app对象 - options.app.$vm.$.appContext.app.mixin(lifecycle); - uni.report = function (type, options) { - stat.sendEvent(type, options); - }; - }); - } -} - +const stat = Stat$1.getInstance(); +let isHide = false; +const lifecycle = { + onLaunch(options) { + stat.report(options, this); + }, + onReady() { + stat.ready(this); + }, + onLoad(options) { + stat.load(options, this); + // 重写分享,获取分享上报事件 + if (this.$scope && this.$scope.onShareAppMessage) { + let oldShareAppMessage = this.$scope.onShareAppMessage; + this.$scope.onShareAppMessage = function (options) { + stat.interceptShare(false); + return oldShareAppMessage.call(this, options) + }; + } + }, + onShow() { + isHide = false; + stat.show(this); + }, + onHide() { + isHide = true; + stat.hide(this); + }, + onUnload() { + if (isHide) { + isHide = false; + return + } + stat.hide(this); + }, + onError(e) { + stat.error(e); + }, +}; + +function main() { + if (process.env.NODE_ENV === 'development') { + uni.report = function (type, options) {}; + } else { + uni.onAppLaunch((options) => { + stat.report(options); + // 小程序平台此时也无法获取getApp,统一在options中传递一个app对象 + options.app.$vm.$.appContext.app.mixin(lifecycle); + uni.report = function (type, options) { + stat.sendEvent(type, options); + }; + }); + } +} + main(); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f5728dfc0..a04e627d7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -144,12 +144,8 @@ importers: packages/uni-api: specifiers: '@dcloudio/uni-shared': 3.0.0-alpha-3021320211123002 - '@types/pako': ^1.0.2 - pako: ^1.0.11 devDependencies: '@dcloudio/uni-shared': link:../uni-shared - '@types/pako': 1.0.2 - pako: 1.0.11 packages/uni-app: specifiers: @@ -175,8 +171,10 @@ importers: '@dcloudio/uni-h5': 3.0.0-alpha-3021320211123002 '@dcloudio/uni-i18n': 3.0.0-alpha-3021320211123002 '@dcloudio/uni-shared': 3.0.0-alpha-3021320211123002 + '@types/pako': 1.0.2 '@vue/compiler-sfc': 3.2.22 autoprefixer: ^10.4.0 + pako: ^1.0.11 vue: 3.2.22 dependencies: '@dcloudio/uni-app-vite': link:../uni-app-vite @@ -186,8 +184,10 @@ importers: '@dcloudio/uni-h5': link:../uni-h5 '@dcloudio/uni-i18n': link:../uni-i18n '@dcloudio/uni-shared': link:../uni-shared + '@types/pako': 1.0.2 '@vue/compiler-sfc': 3.2.22 autoprefixer: 10.4.0 + pako: 1.0.11 vue: 3.2.22 packages/uni-app-vite: @@ -441,10 +441,8 @@ importers: packages/uni-components: specifiers: '@dcloudio/uni-shared': 3.0.0-alpha-3021320211123002 - pako: ^1.0.11 devDependencies: '@dcloudio/uni-shared': link:../uni-shared - pako: 1.0.11 packages/uni-core: specifiers: @@ -471,7 +469,6 @@ importers: '@vue/shared': 3.2.22 acorn-loose: ^8.2.1 localstorage-polyfill: ^1.0.1 - pako: ^2.0.3 safe-area-insets: ^1.4.1 vue: 3.2.22 vue-router: ^4.0.12 @@ -484,7 +481,6 @@ importers: '@vue/server-renderer': 3.2.22_vue@3.2.22 '@vue/shared': 3.2.22 localstorage-polyfill: 1.0.1 - pako: 2.0.4 safe-area-insets: 1.4.1 vue-router: 4.0.12_vue@3.2.22 xmlhttprequest: 1.8.0 @@ -6987,10 +6983,6 @@ packages: resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} dev: true - /pako/2.0.4: - resolution: {integrity: sha512-v8tweI900AUkZN6heMU/4Uy4cXRc2AYNRggVmTR+dEncawDJgCdLMximOVA2p4qO57WMynangsfGRb5WD6L1Bg==} - dev: false - /parent-module/1.0.1: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} -- GitLab