uni-app-service.es.js 235.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
export function createServiceContext(Vue,weex, plus,instanceContext){
fxy060608's avatar
fxy060608 已提交
2 3 4 5 6 7 8
const setTimeout = instanceContext.setTimeout;
const clearTimeout = instanceContext.clearTimeout;
const setInterval = instanceContext.setInterval;
const clearInterval = instanceContext.clearInterval;
const __uniConfig = instanceContext.__uniConfig;
const __uniRoutes = instanceContext.__uniRoutes;

fxy060608's avatar
fxy060608 已提交
9
var serviceContext = (function (vue) {
fxy060608's avatar
fxy060608 已提交
10
  'use strict';
fxy060608's avatar
fxy060608 已提交
11

fxy060608's avatar
fxy060608 已提交
12 13 14 15 16 17 18
  /*
   * base64-arraybuffer
   * https://github.com/niklasvh/base64-arraybuffer
   *
   * Copyright (c) 2012 Niklas von Hertzen
   * Licensed under the MIT license.
   */
fxy060608's avatar
fxy060608 已提交
19

fxy060608's avatar
fxy060608 已提交
20
  var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
fxy060608's avatar
fxy060608 已提交
21

fxy060608's avatar
fxy060608 已提交
22 23 24 25 26
  // 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;
fxy060608's avatar
fxy060608 已提交
27
    }
fxy060608's avatar
fxy060608 已提交
28 29
    return lookup
  })();
fxy060608's avatar
fxy060608 已提交
30

fxy060608's avatar
fxy060608 已提交
31 32 33 34 35
  function encode$3(arraybuffer) {
    var bytes = new Uint8Array(arraybuffer),
      i,
      len = bytes.length,
      base64 = '';
fxy060608's avatar
fxy060608 已提交
36

fxy060608's avatar
fxy060608 已提交
37 38 39 40 41
    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];
fxy060608's avatar
fxy060608 已提交
42 43
    }

fxy060608's avatar
fxy060608 已提交
44 45 46 47
    if (len % 3 === 2) {
      base64 = base64.substring(0, base64.length - 1) + '=';
    } else if (len % 3 === 1) {
      base64 = base64.substring(0, base64.length - 2) + '==';
fxy060608's avatar
fxy060608 已提交
48 49
    }

fxy060608's avatar
fxy060608 已提交
50 51
    return base64
  }
fxy060608's avatar
fxy060608 已提交
52

fxy060608's avatar
fxy060608 已提交
53
  function decode$1(base64) {
fxy060608's avatar
fxy060608 已提交
54 55 56 57 58 59 60 61
    var bufferLength = base64.length * 0.75,
      len = base64.length,
      i,
      p = 0,
      encoded1,
      encoded2,
      encoded3,
      encoded4;
fxy060608's avatar
fxy060608 已提交
62

fxy060608's avatar
fxy060608 已提交
63 64 65 66 67
    if (base64[base64.length - 1] === '=') {
      bufferLength--;
      if (base64[base64.length - 2] === '=') {
        bufferLength--;
      }
fxy060608's avatar
fxy060608 已提交
68 69
    }

fxy060608's avatar
fxy060608 已提交
70 71
    var arraybuffer = new ArrayBuffer(bufferLength),
      bytes = new Uint8Array(arraybuffer);
fxy060608's avatar
fxy060608 已提交
72

fxy060608's avatar
fxy060608 已提交
73 74 75 76 77
    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)];
fxy060608's avatar
fxy060608 已提交
78

fxy060608's avatar
fxy060608 已提交
79 80 81
      bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
      bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
      bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
fxy060608's avatar
fxy060608 已提交
82 83
    }

fxy060608's avatar
fxy060608 已提交
84 85
    return arraybuffer
  }
fxy060608's avatar
fxy060608 已提交
86

fxy060608's avatar
fxy060608 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
  /**
   * Make a map and return a function for checking if a key
   * is in that map.
   * IMPORTANT: all calls of this function must be prefixed with
   * \/\*#\_\_PURE\_\_\*\/
   * So that rollup can tree-shake them if necessary.
   */
  function makeMap(str, expectsLowerCase) {
      const map = Object.create(null);
      const list = str.split(',');
      for (let i = 0; i < list.length; i++) {
          map[list[i]] = true;
      }
      return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  }
fxy060608's avatar
fxy060608 已提交
102
  (process.env.NODE_ENV !== 'production')
fxy060608's avatar
fxy060608 已提交
103 104
      ? Object.freeze({})
      : {};
fxy060608's avatar
fxy060608 已提交
105
  (process.env.NODE_ENV !== 'production') ? Object.freeze([]) : [];
fxy060608's avatar
fxy060608 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
  const extend = Object.assign;
  const hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  const hasOwn$1 = (val, key) => hasOwnProperty$1.call(val, key);
  const isArray = Array.isArray;
  const isFunction = (val) => typeof val === 'function';
  const isString = (val) => typeof val === 'string';
  const isObject$1 = (val) => val !== null && typeof val === 'object';
  const objectToString = Object.prototype.toString;
  const toTypeString = (value) => objectToString.call(value);
  const toRawType = (value) => {
      // extract "RawType" from strings like "[object RawType]"
      return toTypeString(value).slice(8, -1);
  };
  const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  const cacheStringFunction$1 = (fn) => {
      const cache = Object.create(null);
      return ((str) => {
          const hit = cache[str];
          return hit || (cache[str] = fn(str));
      });
  };
  /**
   * @private
   */
fxy060608's avatar
fxy060608 已提交
130
  const capitalize = cacheStringFunction$1((str) => str.charAt(0).toUpperCase() + str.slice(1));
fxy060608's avatar
fxy060608 已提交
131

fxy060608's avatar
fxy060608 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
  const HTTP_METHODS = [
      'GET',
      'OPTIONS',
      'HEAD',
      'POST',
      'PUT',
      'DELETE',
      'TRACE',
      'CONNECT',
  ];
  function elemInArray(str, arr) {
      if (!str || arr.indexOf(str) === -1) {
          return arr[0];
      }
      return str;
  }
  function validateProtocolFail(name, msg) {
      console.warn(`${name}: ${msg}`);
  }
  function validateProtocol(name, data, protocol, onFail) {
      if (!onFail) {
          onFail = validateProtocolFail;
      }
      for (const key in protocol) {
fxy060608's avatar
fxy060608 已提交
156
          const errMsg = validateProp(key, data[key], protocol[key], !hasOwn$1(data, key));
fxy060608's avatar
fxy060608 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
          if (isString(errMsg)) {
              onFail(name, errMsg);
          }
      }
  }
  function validateProtocols(name, args, protocol, onFail) {
      if (!protocol) {
          return;
      }
      if (!isArray(protocol)) {
          return validateProtocol(name, args[0] || Object.create(null), protocol, onFail);
      }
      const len = protocol.length;
      const argsLen = args.length;
      for (let i = 0; i < len; i++) {
          const opts = protocol[i];
          const data = Object.create(null);
          if (argsLen > i) {
              data[opts.name] = args[i];
          }
          validateProtocol(name, data, { [opts.name]: opts }, onFail);
      }
  }
fxy060608's avatar
fxy060608 已提交
180
  function validateProp(name, value, prop, isAbsent) {
fxy060608's avatar
fxy060608 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
      if (!isPlainObject(prop)) {
          prop = { type: prop };
      }
      const { type, required, validator } = prop;
      // required!
      if (required && isAbsent) {
          return 'Missing required args: "' + name + '"';
      }
      // missing but optional
      if (value == null && !required) {
          return;
      }
      // type check
      if (type != null) {
          let isValid = false;
          const types = isArray(type) ? type : [type];
          const expectedTypes = [];
          // value is valid as long as one of the specified types match
          for (let i = 0; i < types.length && !isValid; i++) {
fxy060608's avatar
fxy060608 已提交
200
              const { valid, expectedType } = assertType(value, types[i]);
fxy060608's avatar
fxy060608 已提交
201 202 203 204
              expectedTypes.push(expectedType || '');
              isValid = valid;
          }
          if (!isValid) {
fxy060608's avatar
fxy060608 已提交
205
              return getInvalidTypeMessage(name, value, expectedTypes);
fxy060608's avatar
fxy060608 已提交
206 207 208 209 210 211 212
          }
      }
      // custom validator
      if (validator) {
          return validator(value);
      }
  }
fxy060608's avatar
fxy060608 已提交
213 214
  const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol');
  function assertType(value, type) {
fxy060608's avatar
fxy060608 已提交
215
      let valid;
fxy060608's avatar
fxy060608 已提交
216 217
      const expectedType = getType(type);
      if (isSimpleType(expectedType)) {
fxy060608's avatar
fxy060608 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
          const t = typeof value;
          valid = t === expectedType.toLowerCase();
          // for primitive wrapper objects
          if (!valid && t === 'object') {
              valid = value instanceof type;
          }
      }
      else if (expectedType === 'Object') {
          valid = isObject$1(value);
      }
      else if (expectedType === 'Array') {
          valid = isArray(value);
      }
      else {
          {
              valid = value instanceof type;
          }
      }
      return {
          valid,
          expectedType,
      };
  }
fxy060608's avatar
fxy060608 已提交
241
  function getInvalidTypeMessage(name, value, expectedTypes) {
fxy060608's avatar
fxy060608 已提交
242 243 244 245
      let message = `Invalid args: type check failed for args "${name}".` +
          ` Expected ${expectedTypes.map(capitalize).join(', ')}`;
      const expectedType = expectedTypes[0];
      const receivedType = toRawType(value);
fxy060608's avatar
fxy060608 已提交
246 247
      const expectedValue = styleValue(value, expectedType);
      const receivedValue = styleValue(value, receivedType);
fxy060608's avatar
fxy060608 已提交
248 249
      // check if we need to specify expected value
      if (expectedTypes.length === 1 &&
fxy060608's avatar
fxy060608 已提交
250 251
          isExplicable(expectedType) &&
          !isBoolean(expectedType, receivedType)) {
fxy060608's avatar
fxy060608 已提交
252 253 254 255
          message += ` with value ${expectedValue}`;
      }
      message += `, got ${receivedType} `;
      // check if we need to specify received value
fxy060608's avatar
fxy060608 已提交
256
      if (isExplicable(receivedType)) {
fxy060608's avatar
fxy060608 已提交
257 258 259 260
          message += `with value ${receivedValue}.`;
      }
      return message;
  }
fxy060608's avatar
fxy060608 已提交
261
  function getType(ctor) {
fxy060608's avatar
fxy060608 已提交
262 263 264
      const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
      return match ? match[1] : '';
  }
fxy060608's avatar
fxy060608 已提交
265
  function styleValue(value, type) {
fxy060608's avatar
fxy060608 已提交
266 267 268 269 270 271 272 273 274 275
      if (type === 'String') {
          return `"${value}"`;
      }
      else if (type === 'Number') {
          return `${Number(value)}`;
      }
      else {
          return `${value}`;
      }
  }
fxy060608's avatar
fxy060608 已提交
276
  function isExplicable(type) {
fxy060608's avatar
fxy060608 已提交
277 278 279
      const explicitTypes = ['string', 'number', 'boolean'];
      return explicitTypes.some((elem) => type.toLowerCase() === elem);
  }
fxy060608's avatar
fxy060608 已提交
280
  function isBoolean(...args) {
fxy060608's avatar
fxy060608 已提交
281 282
      return args.some((elem) => elem.toLowerCase() === 'boolean');
  }
fxy060608's avatar
fxy060608 已提交
283

fxy060608's avatar
fxy060608 已提交
284 285 286 287 288 289 290 291 292 293 294
  function tryCatch(fn) {
      return function () {
          try {
              return fn.apply(fn, arguments);
          }
          catch (e) {
              // TODO
              console.error(e);
          }
      };
  }
fxy060608's avatar
fxy060608 已提交
295

fxy060608's avatar
fxy060608 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
  let invokeCallbackId = 1;
  const invokeCallbacks = {};
  function addInvokeCallback(id, name, callback, keepAlive = false) {
      invokeCallbacks[id] = {
          name,
          keepAlive,
          callback,
      };
      return id;
  }
  // onNativeEventReceive((event,data)=>{}) 需要两个参数,目前写死最多两个参数
  function invokeCallback(id, res, extras) {
      if (typeof id === 'number') {
          const opts = invokeCallbacks[id];
          if (opts) {
              if (!opts.keepAlive) {
                  delete invokeCallbacks[id];
              }
              return opts.callback(res, extras);
          }
      }
      return res;
  }
  function findInvokeCallbackByName(name) {
      for (const key in invokeCallbacks) {
          if (invokeCallbacks[key].name === name) {
              return true;
          }
      }
      return false;
  }
fxy060608's avatar
fxy060608 已提交
327 328 329 330 331 332 333 334 335 336 337
  function removeKeepAliveApiCallback(name, callback) {
      for (const key in invokeCallbacks) {
          const item = invokeCallbacks[key];
          if (item.callback === callback && item.name === name) {
              delete invokeCallbacks[key];
          }
      }
  }
  function offKeepAliveApiCallback(name) {
      UniServiceJSBridge.off('api.' + name);
  }
fxy060608's avatar
fxy060608 已提交
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
  function onKeepAliveApiCallback(name) {
      UniServiceJSBridge.on('api.' + name, (res) => {
          for (const key in invokeCallbacks) {
              const opts = invokeCallbacks[key];
              if (opts.name === name) {
                  opts.callback(res);
              }
          }
      });
  }
  function createKeepAliveApiCallback(name, callback) {
      return addInvokeCallback(invokeCallbackId++, name, callback, true);
  }
  const API_SUCCESS = 'success';
  const API_FAIL = 'fail';
  const API_COMPLETE = 'complete';
  function getApiCallbacks(args) {
      const apiCallbacks = {};
      for (const name in args) {
          const fn = args[name];
          if (isFunction(fn)) {
              apiCallbacks[name] = tryCatch(fn);
              delete args[name];
          }
      }
      return apiCallbacks;
  }
  function normalizeErrMsg(errMsg, name) {
      if (!errMsg || errMsg.indexOf(':fail') === -1) {
          return name + ':ok';
      }
      return name + errMsg.substring(errMsg.indexOf(':fail'));
  }
  function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
      if (!isPlainObject(args)) {
          args = {};
      }
      const { success, fail, complete } = getApiCallbacks(args);
      const hasSuccess = isFunction(success);
      const hasFail = isFunction(fail);
      const hasComplete = isFunction(complete);
      const callbackId = invokeCallbackId++;
      addInvokeCallback(callbackId, name, (res) => {
          res = res || {};
          res.errMsg = normalizeErrMsg(res.errMsg, name);
          isFunction(beforeAll) && beforeAll(res);
          if (res.errMsg === name + ':ok') {
              isFunction(beforeSuccess) && beforeSuccess(res);
              hasSuccess && success(res);
          }
          else {
              hasFail && fail(res);
          }
          hasComplete && complete(res);
      });
      return callbackId;
  }
fxy060608's avatar
fxy060608 已提交
395

fxy060608's avatar
fxy060608 已提交
396
  const callbacks$2 = [API_SUCCESS, API_FAIL, API_COMPLETE];
fxy060608's avatar
fxy060608 已提交
397 398
  function hasCallback(args) {
      if (isPlainObject(args) &&
fxy060608's avatar
fxy060608 已提交
399
          callbacks$2.find((cb) => isFunction(args[cb]))) {
fxy060608's avatar
fxy060608 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
          return true;
      }
      return false;
  }
  function handlePromise(promise) {
      return promise;
  }
  function promisify(fn) {
      return (args = {}) => {
          if (hasCallback(args)) {
              return fn(args);
          }
          return handlePromise(new Promise((resolve, reject) => {
              fn(extend(args, { success: resolve, fail: reject }));
          }));
      };
  }
fxy060608's avatar
fxy060608 已提交
417

fxy060608's avatar
fxy060608 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
  function formatApiArgs(args, options) {
      const params = args[0];
      if (!options ||
          (!isPlainObject(options.formatArgs) && isPlainObject(params))) {
          return;
      }
      const formatArgs = options.formatArgs;
      const keys = Object.keys(formatArgs);
      for (let i = 0; i < keys.length; i++) {
          const name = keys[i];
          const formatterOrDefaultValue = formatArgs[name];
          if (isFunction(formatterOrDefaultValue)) {
              const errMsg = formatterOrDefaultValue(args[0][name], params);
              if (isString(errMsg)) {
                  return errMsg;
              }
          }
          else {
              // defaultValue
              if (!hasOwn$1(params, name)) {
                  params[name] = formatterOrDefaultValue;
              }
          }
      }
  }
  function invokeSuccess(id, name, res) {
      return invokeCallback(id, extend(res || {}, { errMsg: name + ':ok' }));
  }
  function invokeFail(id, name, errMsg, errRes) {
      return invokeCallback(id, extend({ errMsg: name + ':fail' + (errMsg ? ' ' + errMsg : '') }, errRes));
  }
  function beforeInvokeApi(name, args, protocol, options) {
      if ((process.env.NODE_ENV !== 'production')) {
          validateProtocols(name, args, protocol);
      }
      if (options && options.beforeInvoke) {
          const errMsg = options.beforeInvoke(args);
          if (isString(errMsg)) {
              return errMsg;
          }
      }
      const errMsg = formatApiArgs(args, options);
      if (errMsg) {
          return errMsg;
      }
  }
  function checkCallback(callback) {
      if (!isFunction(callback)) {
          throw new Error('Invalid args: type check failed for args "callback". Expected Function');
      }
  }
  function wrapperOnApi(name, fn, options) {
      return (callback) => {
          checkCallback(callback);
          const errMsg = beforeInvokeApi(name, [callback], undefined, options);
          if (errMsg) {
              throw new Error(errMsg);
          }
          // 是否是首次调用on,如果是首次,需要初始化onMethod监听
          const isFirstInvokeOnApi = !findInvokeCallbackByName(name);
          createKeepAliveApiCallback(name, callback);
          if (isFirstInvokeOnApi) {
              onKeepAliveApiCallback(name);
              fn();
          }
      };
  }
fxy060608's avatar
fxy060608 已提交
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
  function wrapperOffApi(name, fn, options) {
      return (callback) => {
          checkCallback(callback);
          const errMsg = beforeInvokeApi(name, [callback], undefined, options);
          if (errMsg) {
              throw new Error(errMsg);
          }
          name = name.replace('off', 'on');
          removeKeepAliveApiCallback(name, callback);
          // 是否还存在监听,若已不存在,则移除onMethod监听
          const hasInvokeOnApi = findInvokeCallbackByName(name);
          if (!hasInvokeOnApi) {
              offKeepAliveApiCallback(name);
              fn();
          }
      };
  }
fxy060608's avatar
fxy060608 已提交
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
  function wrapperTaskApi(name, fn, protocol, options) {
      return (args) => {
          const id = createAsyncApiCallback(name, args, options);
          const errMsg = beforeInvokeApi(name, [args], protocol, options);
          if (errMsg) {
              return invokeFail(id, name, errMsg);
          }
          return fn(args, {
              resolve: (res) => invokeSuccess(id, name, res),
              reject: (errMsg, errRes) => invokeFail(id, name, errMsg, errRes),
          });
      };
  }
  function wrapperSyncApi(name, fn, protocol, options) {
      return (...args) => {
          const errMsg = beforeInvokeApi(name, args, protocol, options);
          if (errMsg) {
              throw new Error(errMsg);
          }
          return fn.apply(null, args);
      };
  }
  function wrapperAsyncApi(name, fn, protocol, options) {
      return wrapperTaskApi(name, fn, protocol, options);
  }
  function defineOnApi(name, fn, options) {
      return wrapperOnApi(name, fn, options);
  }
fxy060608's avatar
fxy060608 已提交
530 531 532
  function defineOffApi(name, fn, options) {
      return wrapperOffApi(name, fn, options);
  }
fxy060608's avatar
fxy060608 已提交
533 534 535 536 537 538 539 540 541
  function defineTaskApi(name, fn, protocol, options) {
      return promisify(wrapperTaskApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options));
  }
  function defineSyncApi(name, fn, protocol, options) {
      return wrapperSyncApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
  }
  function defineAsyncApi(name, fn, protocol, options) {
      return promisify(wrapperAsyncApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options));
  }
fxy060608's avatar
fxy060608 已提交
542

fxy060608's avatar
fxy060608 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
  const API_BASE64_TO_ARRAY_BUFFER = 'base64ToArrayBuffer';
  const Base64ToArrayBufferProtocol = [
      {
          name: 'base64',
          type: String,
          required: true,
      },
  ];
  const API_ARRAY_BUFFER_TO_BASE64 = 'arrayBufferToBase64';
  const ArrayBufferToBase64Protocol = [
      {
          name: 'arrayBuffer',
          type: [ArrayBuffer, Uint8Array],
          required: true,
      },
  ];

  // @ts-ignore
  const base64ToArrayBuffer = defineSyncApi(API_BASE64_TO_ARRAY_BUFFER, (base64) => {
fxy060608's avatar
fxy060608 已提交
562
      return decode$1(base64);
fxy060608's avatar
fxy060608 已提交
563 564 565 566 567
  }, Base64ToArrayBufferProtocol);
  const arrayBufferToBase64 = defineSyncApi(API_ARRAY_BUFFER_TO_BASE64, (arrayBuffer) => {
      return encode$3(arrayBuffer);
  }, ArrayBufferToBase64Protocol);

fxy060608's avatar
fxy060608 已提交
568 569 570 571 572 573
  function formatLog(module, ...args) {
      return `[${Date.now()}][${module}]:${args
        .map((arg) => JSON.stringify(arg))
        .join(' ')}`;
  }

fxy060608's avatar
fxy060608 已提交
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
  const encode$2 = encodeURIComponent;
  function stringifyQuery$1(obj, encodeStr = encode$2) {
      const res = obj
          ? Object.keys(obj)
              .map((key) => {
              let val = obj[key];
              if (typeof val === undefined || val === null) {
                  val = '';
              }
              else if (isPlainObject(val)) {
                  val = JSON.stringify(val);
              }
              return encodeStr(key) + '=' + encodeStr(val);
          })
              .filter((x) => x.length > 0)
              .join('&')
          : null;
      return res ? `?${res}` : '';
  }
fxy060608's avatar
fxy060608 已提交
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
  /**
   * Decode text using `decodeURIComponent`. Returns the original text if it
   * fails.
   *
   * @param text - string to decode
   * @returns decoded string
   */
  function decode(text) {
      try {
          return decodeURIComponent('' + text);
      }
      catch (err) { }
      return '' + text;
  }
  const PLUS_RE = /\+/g; // %2B
  /**
   * https://github.com/vuejs/vue-router-next/blob/master/src/query.ts
   * @internal
   *
   * @param search - search string to parse
   * @returns a query object
   */
  function parseQuery(search) {
      const query = {};
      // avoid creating an object with an empty key and empty value
      // because of split('&')
      if (search === '' || search === '?')
          return query;
      const hasLeadingIM = search[0] === '?';
      const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&');
      for (let i = 0; i < searchParams.length; ++i) {
          // pre decode the + into space
          const searchParam = searchParams[i].replace(PLUS_RE, ' ');
          // allow the = character
          let eqPos = searchParam.indexOf('=');
          let key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
          let value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
          if (key in query) {
              // an extra variable for ts types
              let currentValue = query[key];
              if (!isArray(currentValue)) {
                  currentValue = query[key] = [currentValue];
              }
              currentValue.push(value);
          }
          else {
              query[key] = value;
          }
      }
      return query;
  }

  function parseUrl(url) {
      const [path, querystring] = url.split('?', 2);
      return {
          path,
fxy060608's avatar
fxy060608 已提交
649
          query: parseQuery(querystring || ''),
fxy060608's avatar
fxy060608 已提交
650 651
      };
  }
fxy060608's avatar
fxy060608 已提交
652

fxy060608's avatar
fxy060608 已提交
653 654 655 656 657 658 659 660 661 662 663 664 665
  class DOMException extends Error {
      constructor(message) {
          super(message);
          this.name = 'DOMException';
      }
  }
  class UniEventTarget {
      constructor() {
          this._listeners = {};
      }
      dispatchEvent(evt) {
          const listeners = this._listeners[evt.type];
          if (!listeners) {
fxy060608's avatar
fxy060608 已提交
666 667 668
              if ((process.env.NODE_ENV !== 'production')) {
                  console.error(formatLog('dispatchEvent', this.nodeId), evt.type, 'not found');
              }
fxy060608's avatar
fxy060608 已提交
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
              return false;
          }
          const len = listeners.length;
          for (let i = 0; i < len; i++) {
              listeners[i].call(this, evt);
              if (evt._end) {
                  break;
              }
          }
          return evt.cancelable && evt.defaultPrevented;
      }
      addEventListener(type, listener, options) {
          const isOnce = options && options.once;
          if (isOnce) {
              const wrapper = function (evt) {
                  listener.apply(this, [evt]);
                  this.removeEventListener(type, wrapper, options);
              };
              return this.addEventListener(type, wrapper, extend(options, { once: false }));
          }
          (this._listeners[type] || (this._listeners[type] = [])).push(listener);
      }
      removeEventListener(type, callback, options) {
          const listeners = this._listeners[type.toLowerCase()];
          if (!listeners) {
              return;
          }
          const index = listeners.indexOf(callback);
          if (index > -1) {
              listeners.splice(index, 1);
          }
      }
fxy060608's avatar
fxy060608 已提交
701
  }
fxy060608's avatar
fxy060608 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
  const COMPONENT_MAP = {
      VIEW: 1,
      IMAGE: 2,
      TEXT: 3,
      '#text': 4,
      '#comment': 5,
      NAVIGATOR: 6,
      FORM: 7,
      BUTTON: 8,
      INPUT: 9,
      LABEL: 10,
      RADIO: 11,
      CHECKBOX: 12,
      'CHECKBOX-GROUP': 13,
      AD: 14,
      AUDIO: 15,
      CAMERA: 16,
      CANVAS: 17,
      'COVER-IMAGE': 18,
      'COVER-VIEW': 19,
      EDITOR: 20,
      'FUNCTIONAL-PAGE-NAVIGATOR': 21,
      ICON: 22,
      'RADIO-GROUP': 23,
      'LIVE-PLAYER': 24,
      'LIVE-PUSHER': 25,
      MAP: 26,
      'MOVABLE-AREA': 27,
      'MOVABLE-VIEW': 28,
      'OFFICIAL-ACCOUNT': 29,
      'OPEN-DATA': 30,
      PICKER: 31,
      'PICKER-VIEW': 32,
      'PICKER-VIEW-COLUMN': 33,
      PROGRESS: 34,
      'RICH-TEXT': 35,
      'SCROLL-VIEW': 36,
      SLIDER: 37,
      SWIPER: 38,
      'SWIPER-ITEM': 39,
      SWITCH: 40,
      TEXTAREA: 41,
      VIDEO: 42,
      'WEB-VIEW': 43,
  };
  function encodeTag(tag) {
      return COMPONENT_MAP[tag] || tag;
  }

  const NODE_TYPE_PAGE = 0;
  const NODE_TYPE_ELEMENT = 1;
  function sibling(node, type) {
      const { parentNode } = node;
      if (!parentNode) {
          return null;
      }
      const { childNodes } = parentNode;
      return childNodes[childNodes.indexOf(node) + (type === 'n' ? 1 : -1)] || null;
  }
  function removeNode(node) {
      const { parentNode } = node;
      if (parentNode) {
          parentNode.removeChild(node);
      }
  }
  function checkNodeId(node) {
fxy060608's avatar
fxy060608 已提交
768
      if (!node.nodeId && node.pageNode) {
fxy060608's avatar
fxy060608 已提交
769 770 771 772 773 774 775 776 777 778 779 780
          node.nodeId = node.pageNode.genId();
      }
  }
  // 为优化性能,各平台不使用proxy来实现node的操作拦截,而是直接通过pageNode定制
  class UniNode extends UniEventTarget {
      constructor(nodeType, nodeName, container) {
          super();
          this.pageNode = null;
          this.parentNode = null;
          this._text = null;
          if (container) {
              const { pageNode } = container;
fxy060608's avatar
fxy060608 已提交
781 782 783 784 785
              if (pageNode) {
                  this.pageNode = pageNode;
                  this.nodeId = pageNode.genId();
                  pageNode.onCreate(this, encodeTag(nodeName));
              }
fxy060608's avatar
fxy060608 已提交
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
          }
          this.nodeType = nodeType;
          this.nodeName = nodeName;
          this.childNodes = [];
      }
      get firstChild() {
          return this.childNodes[0] || null;
      }
      get lastChild() {
          const { childNodes } = this;
          const length = childNodes.length;
          return length ? childNodes[length - 1] : null;
      }
      get nextSibling() {
          return sibling(this, 'n');
      }
      get nodeValue() {
          return null;
      }
      set nodeValue(_val) { }
      get textContent() {
          return this._text || '';
      }
      set textContent(text) {
          this._text = text;
          if (this.pageNode) {
              this.pageNode.onTextContent(this, text);
          }
      }
      get parentElement() {
          const { parentNode } = this;
          if (parentNode && parentNode.nodeType === NODE_TYPE_ELEMENT) {
              return parentNode;
          }
          return null;
      }
      get previousSibling() {
          return sibling(this, 'p');
      }
      appendChild(newChild) {
          return this.insertBefore(newChild, null);
      }
      cloneNode(deep) {
          const cloned = extend(Object.create(Object.getPrototypeOf(this)), this);
          const { attributes } = cloned;
          if (attributes) {
              cloned.attributes = extend({}, attributes);
          }
          if (deep) {
              cloned.childNodes = cloned.childNodes.map((childNode) => childNode.cloneNode(true));
          }
          return cloned;
      }
      insertBefore(newChild, refChild) {
          removeNode(newChild);
          newChild.pageNode = this.pageNode;
          newChild.parentNode = this;
          checkNodeId(newChild);
          const { childNodes } = this;
          if (refChild) {
fxy060608's avatar
fxy060608 已提交
846
              const index = childNodes.indexOf(refChild);
fxy060608's avatar
fxy060608 已提交
847 848 849 850 851 852 853 854 855
              if (index === -1) {
                  throw new DOMException(`Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.`);
              }
              childNodes.splice(index, 0, newChild);
          }
          else {
              childNodes.push(newChild);
          }
          return this.pageNode
fxy060608's avatar
fxy060608 已提交
856
              ? this.pageNode.onInsertBefore(this, newChild, refChild)
fxy060608's avatar
fxy060608 已提交
857 858 859 860 861 862 863 864 865 866
              : newChild;
      }
      removeChild(oldChild) {
          const { childNodes } = this;
          const index = childNodes.indexOf(oldChild);
          if (index === -1) {
              throw new DOMException(`Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.`);
          }
          oldChild.parentNode = null;
          childNodes.splice(index, 1);
fxy060608's avatar
fxy060608 已提交
867
          return this.pageNode ? this.pageNode.onRemoveChild(oldChild) : oldChild;
fxy060608's avatar
fxy060608 已提交
868 869 870 871
      }
  }

  function cache(fn) {
fxy060608's avatar
fxy060608 已提交
872
      const cache = Object.create(null);
fxy060608's avatar
fxy060608 已提交
873
      return (str) => {
fxy060608's avatar
fxy060608 已提交
874 875
          const hit = cache[str];
          return hit || (cache[str] = fn(str));
fxy060608's avatar
fxy060608 已提交
876 877 878 879 880
      };
  }
  function cacheStringFunction(fn) {
      return cache(fn);
  }
fxy060608's avatar
fxy060608 已提交
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
  const invokeArrayFns = (fns, arg) => {
      let ret;
      for (let i = 0; i < fns.length; i++) {
          ret = fns[i](arg);
      }
      return ret;
  };
  function once(fn, ctx = null) {
      let res;
      return ((...args) => {
          if (fn) {
              res = fn.apply(ctx, args);
              fn = null;
          }
          return res;
      });
  }
  function callOptions(options, data) {
      options = options || {};
      if (typeof data === 'string') {
          data = {
              errMsg: data,
          };
      }
      if (/:ok$/.test(data.errMsg)) {
          if (typeof options.success === 'function') {
              options.success(data);
          }
      }
      else {
          if (typeof options.fail === 'function') {
              options.fail(data);
          }
      }
      if (typeof options.complete === 'function') {
          options.complete(data);
      }
  }

fxy060608's avatar
fxy060608 已提交
920
  const NAVBAR_HEIGHT = 44;
fxy060608's avatar
fxy060608 已提交
921
  const TABBAR_HEIGHT = 50;
fxy060608's avatar
fxy060608 已提交
922
  const ON_REACH_BOTTOM_DISTANCE = 50;
fxy060608's avatar
fxy060608 已提交
923 924 925
  const PRIMARY_COLOR = '#007aff';
  const BACKGROUND_COLOR = '#f7f7f7'; // 背景色,如标题栏默认背景色
  const SCHEME_RE = /^([a-z-]+:)?\/\//i;
fxy060608's avatar
fxy060608 已提交
926
  const DATA_RE = /^data:.*,.*/;
fxy060608's avatar
fxy060608 已提交
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941

  const isObject = (val) => val !== null && typeof val === 'object';
  class BaseFormatter {
      constructor() {
          this._caches = Object.create(null);
      }
      interpolate(message, values) {
          if (!values) {
              return [message];
          }
          let tokens = this._caches[message];
          if (!tokens) {
              tokens = parse(message);
              this._caches[message] = tokens;
          }
fxy060608's avatar
fxy060608 已提交
942
          return compile(tokens, values);
fxy060608's avatar
fxy060608 已提交
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
      }
  }
  const RE_TOKEN_LIST_VALUE = /^(?:\d)+/;
  const RE_TOKEN_NAMED_VALUE = /^(?:\w)+/;
  function parse(format) {
      const tokens = [];
      let position = 0;
      let text = '';
      while (position < format.length) {
          let char = format[position++];
          if (char === '{') {
              if (text) {
                  tokens.push({ type: 'text', value: text });
              }
              text = '';
              let sub = '';
              char = format[position++];
              while (char !== undefined && char !== '}') {
                  sub += char;
                  char = format[position++];
              }
              const isClosed = char === '}';
              const type = RE_TOKEN_LIST_VALUE.test(sub)
                  ? 'list'
                  : isClosed && RE_TOKEN_NAMED_VALUE.test(sub)
                      ? 'named'
                      : 'unknown';
              tokens.push({ value: sub, type });
          }
          else if (char === '%') {
              // when found rails i18n syntax, skip text capture
              if (format[position] !== '{') {
                  text += char;
              }
          }
          else {
              text += char;
          }
      }
      text && tokens.push({ type: 'text', value: text });
      return tokens;
  }
fxy060608's avatar
fxy060608 已提交
985
  function compile(tokens, values) {
fxy060608's avatar
fxy060608 已提交
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
      const compiled = [];
      let index = 0;
      const mode = Array.isArray(values)
          ? 'list'
          : isObject(values)
              ? 'named'
              : 'unknown';
      if (mode === 'unknown') {
          return compiled;
      }
      while (index < tokens.length) {
          const token = tokens[index];
          switch (token.type) {
              case 'text':
                  compiled.push(token.value);
                  break;
              case 'list':
                  compiled.push(values[parseInt(token.value, 10)]);
                  break;
              case 'named':
                  if (mode === 'named') {
                      compiled.push(values[token.value]);
                  }
                  else {
                      if (process.env.NODE_ENV !== 'production') {
                          console.warn(`Type of token '${token.type}' and format of value '${mode}' don't match!`);
                      }
                  }
                  break;
              case 'unknown':
                  if (process.env.NODE_ENV !== 'production') {
                      console.warn(`Detect 'unknown' type of token!`);
                  }
                  break;
          }
          index++;
      }
      return compiled;
  }

  const LOCALE_ZH_HANS = 'zh-Hans';
  const LOCALE_ZH_HANT = 'zh-Hant';
  const LOCALE_EN = 'en';
  const LOCALE_FR = 'fr';
  const LOCALE_ES = 'es';
  const hasOwnProperty = Object.prototype.hasOwnProperty;
  const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  const defaultFormatter = new BaseFormatter();
  function include(str, parts) {
      return !!parts.find((part) => str.indexOf(part) !== -1);
  }
  function startsWith(str, parts) {
      return parts.find((part) => str.indexOf(part) === 0);
  }
  function normalizeLocale(locale, messages) {
      if (!locale) {
          return;
      }
      locale = locale.trim().replace(/_/g, '-');
      if (messages[locale]) {
          return locale;
      }
      locale = locale.toLowerCase();
      if (locale.indexOf('zh') === 0) {
          if (locale.indexOf('-hans') !== -1) {
              return LOCALE_ZH_HANS;
          }
          if (locale.indexOf('-hant') !== -1) {
              return LOCALE_ZH_HANT;
          }
          if (include(locale, ['-tw', '-hk', '-mo', '-cht'])) {
              return LOCALE_ZH_HANT;
          }
          return LOCALE_ZH_HANS;
      }
      const lang = startsWith(locale, [LOCALE_EN, LOCALE_FR, LOCALE_ES]);
      if (lang) {
          return lang;
      }
  }
  class I18n {
      constructor({ locale, fallbackLocale, messages, watcher, formater, }) {
          this.locale = LOCALE_EN;
          this.fallbackLocale = LOCALE_EN;
          this.message = {};
          this.messages = {};
          this.watchers = [];
          if (fallbackLocale) {
              this.fallbackLocale = fallbackLocale;
          }
          this.formater = formater || defaultFormatter;
          this.messages = messages || {};
          this.setLocale(locale);
          if (watcher) {
              this.watchLocale(watcher);
          }
      }
      setLocale(locale) {
          const oldLocale = this.locale;
          this.locale = normalizeLocale(locale, this.messages) || this.fallbackLocale;
          if (!this.messages[this.locale]) {
              // 可能初始化时不存在
              this.messages[this.locale] = {};
          }
          this.message = this.messages[this.locale];
          this.watchers.forEach((watcher) => {
              watcher(this.locale, oldLocale);
          });
      }
      getLocale() {
          return this.locale;
      }
      watchLocale(fn) {
          const index = this.watchers.push(fn) - 1;
          return () => {
              this.watchers.splice(index, 1);
          };
      }
      add(locale, message) {
          if (this.messages[locale]) {
              Object.assign(this.messages[locale], message);
          }
          else {
              this.messages[locale] = message;
          }
      }
      t(key, locale, values) {
          let message = this.message;
          if (typeof locale === 'string') {
              locale = normalizeLocale(locale, this.messages);
              locale && (message = this.messages[locale]);
          }
          else {
              values = locale;
          }
          if (!hasOwn(message, key)) {
              console.warn(`Cannot translate the value of keypath ${key}. Use the value of keypath as default.`);
              return key;
          }
          return this.formater.interpolate(message[key], values).join('');
      }
  }

  function initLocaleWatcher(appVm, i18n) {
      appVm.$i18n &&
          appVm.$i18n.vm.$watch('locale', (newLocale) => {
              i18n.setLocale(newLocale);
          }, {
              immediate: true,
          });
  }
  // function getDefaultLocale() {
  //   if (typeof navigator !== 'undefined') {
  //     return (navigator as any).userLanguage || navigator.language
  //   }
  //   if (typeof plus !== 'undefined') {
  //     // TODO 待调整为最新的获取语言代码
  //     return plus.os.language
  //   }
  //   return uni.getSystemInfoSync().language
  // }
  function initVueI18n(locale = LOCALE_EN, messages = {}, fallbackLocale = LOCALE_EN) {
      // 兼容旧版本入参
      if (typeof locale !== 'string') {
          [locale, messages] = [messages, locale];
      }
      if (typeof locale !== 'string') {
          locale = fallbackLocale;
      }
      const i18n = new I18n({
          locale: locale || fallbackLocale,
          fallbackLocale,
          messages,
      });
      let t = (key, values) => {
          if (typeof getApp !== 'function') {
              // app view
              /* eslint-disable no-func-assign */
              t = function (key, values) {
                  return i18n.t(key, values);
              };
          }
          else {
              const appVm = getApp().$vm;
              if (!appVm.$t || !appVm.$i18n) {
                  // if (!locale) {
                  //   i18n.setLocale(getDefaultLocale())
                  // }
                  /* eslint-disable no-func-assign */
                  t = function (key, values) {
                      return i18n.t(key, values);
                  };
              }
              else {
                  initLocaleWatcher(appVm, i18n);
                  /* eslint-disable no-func-assign */
                  t = function (key, values) {
                      const $i18n = appVm.$i18n;
                      const silentTranslationWarn = $i18n.silentTranslationWarn;
                      $i18n.silentTranslationWarn = true;
                      const msg = appVm.$t(key, values);
                      $i18n.silentTranslationWarn = silentTranslationWarn;
                      if (msg !== key) {
                          return msg;
                      }
                      return i18n.t(key, $i18n.locale, values);
                  };
              }
          }
          return t(key, values);
      };
      return {
          i18n,
          t(key, values) {
fxy060608's avatar
fxy060608 已提交
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
              return t(key, values);
          },
          add(locale, message) {
              return i18n.add(locale, message);
          },
          getLocale() {
              return i18n.getLocale();
          },
          setLocale(newLocale) {
              return i18n.setLocale(newLocale);
          },
      };
fxy060608's avatar
fxy060608 已提交
1212 1213
  }

fxy060608's avatar
fxy060608 已提交
1214 1215 1216 1217 1218 1219 1220 1221
  let i18n;
  function useI18n() {
      if (!i18n) {
          let language;
          {
              {
                  language = navigator.language;
              }
fxy060608's avatar
fxy060608 已提交
1222
          }
fxy060608's avatar
fxy060608 已提交
1223
          i18n = initVueI18n(language);
fxy060608's avatar
fxy060608 已提交
1224
      }
fxy060608's avatar
fxy060608 已提交
1225
      return i18n;
fxy060608's avatar
fxy060608 已提交
1226 1227
  }

fxy060608's avatar
fxy060608 已提交
1228 1229 1230 1231 1232 1233 1234
  // This file is created by scripts/i18n.js
  function normalizeMessages(namespace, messages) {
      return Object.keys(messages).reduce((res, name) => {
          res[namespace + name] = messages[name];
          return res;
      }, {});
  }
fxy060608's avatar
fxy060608 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
  const initI18nAppMsgsOnce = /*#__PURE__*/ once(() => {
      const name = 'uni.app.';
      {
          useI18n().add(LOCALE_EN, normalizeMessages(name, { quit: 'Press back button again to exit' }));
      }
      {
          useI18n().add(LOCALE_ES, normalizeMessages(name, { quit: 'Pulse otra vez para salir' }));
      }
      {
          useI18n().add(LOCALE_FR, normalizeMessages(name, {
              quit: "Appuyez à nouveau pour quitter l'application",
          }));
      }
      {
          useI18n().add(LOCALE_ZH_HANS, normalizeMessages(name, { quit: '再按一次退出应用' }));
      }
      {
          useI18n().add(LOCALE_ZH_HANT, normalizeMessages(name, { quit: '再按一次退出應用' }));
      }
  });
fxy060608's avatar
fxy060608 已提交
1255 1256 1257 1258
  const initI18nShowActionSheetMsgsOnce = /*#__PURE__*/ once(() => {
      const name = 'uni.showActionSheet.';
      {
          useI18n().add(LOCALE_EN, normalizeMessages(name, { cancel: 'Cancel' }));
fxy060608's avatar
fxy060608 已提交
1259
      }
fxy060608's avatar
fxy060608 已提交
1260 1261
      {
          useI18n().add(LOCALE_ES, normalizeMessages(name, { cancel: 'Cancelar' }));
fxy060608's avatar
fxy060608 已提交
1262
      }
fxy060608's avatar
fxy060608 已提交
1263 1264
      {
          useI18n().add(LOCALE_FR, normalizeMessages(name, { cancel: 'Annuler' }));
fxy060608's avatar
fxy060608 已提交
1265
      }
fxy060608's avatar
fxy060608 已提交
1266 1267
      {
          useI18n().add(LOCALE_ZH_HANS, normalizeMessages(name, { cancel: '取消' }));
fxy060608's avatar
fxy060608 已提交
1268
      }
fxy060608's avatar
fxy060608 已提交
1269 1270
      {
          useI18n().add(LOCALE_ZH_HANT, normalizeMessages(name, { cancel: '取消' }));
fxy060608's avatar
fxy060608 已提交
1271
      }
fxy060608's avatar
fxy060608 已提交
1272 1273 1274 1275 1276
  });
  const initI18nShowModalMsgsOnce = /*#__PURE__*/ once(() => {
      const name = 'uni.showModal.';
      {
          useI18n().add(LOCALE_EN, normalizeMessages(name, { cancel: 'Cancel', confirm: 'OK' }));
fxy060608's avatar
fxy060608 已提交
1277
      }
fxy060608's avatar
fxy060608 已提交
1278 1279
      {
          useI18n().add(LOCALE_ES, normalizeMessages(name, { cancel: 'Cancelar', confirm: 'OK' }));
fxy060608's avatar
fxy060608 已提交
1280
      }
fxy060608's avatar
fxy060608 已提交
1281 1282
      {
          useI18n().add(LOCALE_FR, normalizeMessages(name, { cancel: 'Annuler', confirm: 'OK' }));
fxy060608's avatar
fxy060608 已提交
1283
      }
fxy060608's avatar
fxy060608 已提交
1284 1285
      {
          useI18n().add(LOCALE_ZH_HANS, normalizeMessages(name, { cancel: '取消', confirm: '确定' }));
fxy060608's avatar
fxy060608 已提交
1286
      }
fxy060608's avatar
fxy060608 已提交
1287 1288
      {
          useI18n().add(LOCALE_ZH_HANT, normalizeMessages(name, { cancel: '取消', confirm: '確定' }));
fxy060608's avatar
fxy060608 已提交
1289
      }
fxy060608's avatar
fxy060608 已提交
1290 1291 1292 1293 1294 1295 1296 1297 1298
  });
  const initI18nChooseImageMsgsOnce = /*#__PURE__*/ once(() => {
      const name = 'uni.chooseImage.';
      {
          useI18n().add(LOCALE_EN, normalizeMessages(name, {
              cancel: 'Cancel',
              'sourceType.album': 'Album',
              'sourceType.camera': 'Camera',
          }));
fxy060608's avatar
fxy060608 已提交
1299
      }
fxy060608's avatar
fxy060608 已提交
1300 1301 1302 1303 1304 1305
      {
          useI18n().add(LOCALE_ES, normalizeMessages(name, {
              cancel: 'Cancelar',
              'sourceType.album': 'Álbum',
              'sourceType.camera': 'Cámara',
          }));
fxy060608's avatar
fxy060608 已提交
1306
      }
fxy060608's avatar
fxy060608 已提交
1307 1308 1309 1310 1311 1312
      {
          useI18n().add(LOCALE_FR, normalizeMessages(name, {
              cancel: 'Annuler',
              'sourceType.album': 'Album',
              'sourceType.camera': 'Caméra',
          }));
fxy060608's avatar
fxy060608 已提交
1313
      }
fxy060608's avatar
fxy060608 已提交
1314 1315 1316 1317 1318 1319
      {
          useI18n().add(LOCALE_ZH_HANS, normalizeMessages(name, {
              cancel: '取消',
              'sourceType.album': '从相册选择',
              'sourceType.camera': '拍摄',
          }));
fxy060608's avatar
fxy060608 已提交
1320
      }
fxy060608's avatar
fxy060608 已提交
1321 1322 1323 1324 1325 1326
      {
          useI18n().add(LOCALE_ZH_HANT, normalizeMessages(name, {
              cancel: '取消',
              'sourceType.album': '從相冊選擇',
              'sourceType.camera': '拍攝',
          }));
fxy060608's avatar
fxy060608 已提交
1327
      }
fxy060608's avatar
fxy060608 已提交
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
  });
  const initI18nStartSoterAuthenticationMsgsOnce = /*#__PURE__*/ once(() => {
      const name = 'uni.startSoterAuthentication.';
      {
          useI18n().add(LOCALE_EN, normalizeMessages(name, { authContent: 'Fingerprint recognition' }));
      }
      {
          useI18n().add(LOCALE_ES, normalizeMessages(name, {
              authContent: 'Reconocimiento de huellas dactilares',
          }));
      }
      {
          useI18n().add(LOCALE_FR, normalizeMessages(name, {
              authContent: "Reconnaissance de l'empreinte digitale",
          }));
      }
      {
          useI18n().add(LOCALE_ZH_HANS, normalizeMessages(name, { authContent: '指纹识别中...' }));
      }
      {
          useI18n().add(LOCALE_ZH_HANT, normalizeMessages(name, { authContent: '指紋識別中...' }));
      }
fxy060608's avatar
fxy060608 已提交
1350
  });
fxy060608's avatar
fxy060608 已提交
1351

fxy060608's avatar
fxy060608 已提交
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
  const E = function () {
      // Keep this empty so it's easier to inherit from
      // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
  };
  E.prototype = {
      on: function (name, callback, ctx) {
          var e = this.e || (this.e = {});
          (e[name] || (e[name] = [])).push({
              fn: callback,
              ctx: ctx,
fxy060608's avatar
fxy060608 已提交
1362
          });
fxy060608's avatar
fxy060608 已提交
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
          return this;
      },
      once: function (name, callback, ctx) {
          var self = this;
          function listener() {
              self.off(name, listener);
              callback.apply(ctx, arguments);
          }
          listener._ = callback;
          return this.on(name, listener, ctx);
      },
      emit: function (name) {
          var data = [].slice.call(arguments, 1);
          var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
          var i = 0;
          var len = evtArr.length;
          for (i; i < len; i++) {
              evtArr[i].fn.apply(evtArr[i].ctx, data);
          }
          return this;
      },
      off: function (name, callback) {
          var e = this.e || (this.e = {});
          var evts = e[name];
          var liveEvents = [];
          if (evts && callback) {
              for (var i = 0, len = evts.length; i < len; i++) {
                  if (evts[i].fn !== callback && evts[i].fn._ !== callback)
                      liveEvents.push(evts[i]);
              }
          }
          // Remove event from queue to prevent memory leak
          // Suggested by https://github.com/lazd
          // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910
          liveEvents.length ? (e[name] = liveEvents) : delete e[name];
          return this;
      },
  };

fxy060608's avatar
fxy060608 已提交
1402
  // TODO 等待 vue3 的兼容模式自带emitter
fxy060608's avatar
fxy060608 已提交
1403
  function initBridge(subscribeNamespace) {
fxy060608's avatar
fxy060608 已提交
1404 1405
      // TODO vue3 compatibility builds
      const emitter = new E();
fxy060608's avatar
fxy060608 已提交
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
      return {
          on(event, callback) {
              return emitter.on(event, callback);
          },
          once(event, callback) {
              return emitter.once(event, callback);
          },
          off(event, callback) {
              return emitter.off(event, callback);
          },
          emit(event, ...args) {
              return emitter.emit(event, ...args);
          },
fxy060608's avatar
fxy060608 已提交
1419 1420
          subscribe(event, callback, once = false) {
              emitter[once ? 'once' : 'on'](`${subscribeNamespace}.${event}`, callback);
fxy060608's avatar
fxy060608 已提交
1421 1422
          },
          unsubscribe(event, callback) {
fxy060608's avatar
fxy060608 已提交
1423
              emitter.off(`${subscribeNamespace}.${event}`, callback);
fxy060608's avatar
fxy060608 已提交
1424 1425 1426
          },
          subscribeHandler(event, args, pageId) {
              if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
1427
                  console.log(formatLog(subscribeNamespace, 'subscribeHandler', pageId, event, args));
fxy060608's avatar
fxy060608 已提交
1428
              }
fxy060608's avatar
fxy060608 已提交
1429
              emitter.emit(`${subscribeNamespace}.${event}`, args, pageId);
fxy060608's avatar
fxy060608 已提交
1430
          },
fxy060608's avatar
fxy060608 已提交
1431
      };
fxy060608's avatar
fxy060608 已提交
1432
  }
fxy060608's avatar
fxy060608 已提交
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458

  function hasRpx(str) {
      return str.indexOf('rpx') !== -1 || str.indexOf('upx') !== -1;
  }
  function rpx2px(str, replace = false) {
      if (replace) {
          return rpx2pxWithReplace(str);
      }
      if (typeof str === 'string') {
          const res = parseInt(str) || 0;
          if (hasRpx(str)) {
              return uni.upx2px(res);
          }
          return res;
      }
      return str;
  }
  function rpx2pxWithReplace(str) {
      if (!hasRpx(str)) {
          return str;
      }
      return str.replace(/(\d+(\.\d+)?)[ru]px/g, (_a, b) => {
          return uni.upx2px(parseFloat(b)) + 'px';
      });
  }

fxy060608's avatar
fxy060608 已提交
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
  function getPageById(id) {
      return getCurrentPages().find((page) => page.$page.id === id);
  }
  function getPageVmById(id) {
      const page = getPageById(id);
      if (page) {
          return page.$vm;
      }
  }
  function getCurrentPage() {
      const pages = getCurrentPages();
      const len = pages.length;
      if (len) {
          return pages[len - 1];
      }
  }
  function getCurrentPageVm() {
      const page = getCurrentPage();
      if (page) {
          return page.$vm;
      }
  }
fxy060608's avatar
fxy060608 已提交
1481 1482 1483 1484
  const PAGE_META_KEYS = ['navigationBar', 'pullToRefresh'];
  function initGlobalStyle() {
      return JSON.parse(JSON.stringify(__uniConfig.globalStyle || {}));
  }
fxy060608's avatar
fxy060608 已提交
1485
  function initRouteMeta(pageMeta, id) {
fxy060608's avatar
fxy060608 已提交
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
      const globalStyle = initGlobalStyle();
      const res = extend({ id }, globalStyle, pageMeta);
      PAGE_META_KEYS.forEach((name) => {
          res[name] = extend({}, globalStyle[name], pageMeta[name]);
      });
      return res;
  }
  function normalizePullToRefreshRpx(pullToRefresh) {
      if (pullToRefresh.offset) {
          pullToRefresh.offset = rpx2px(pullToRefresh.offset);
      }
      if (pullToRefresh.height) {
          pullToRefresh.height = rpx2px(pullToRefresh.height);
      }
      if (pullToRefresh.range) {
          pullToRefresh.range = rpx2px(pullToRefresh.range);
      }
      return pullToRefresh;
fxy060608's avatar
fxy060608 已提交
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
  }
  function initPageInternalInstance(url, pageQuery, meta) {
      const { id, route } = meta;
      return {
          id: id,
          path: '/' + route,
          route: route,
          fullPath: url,
          options: pageQuery,
          meta,
      };
  }

  function invokeHook(vm, name, args) {
      if (isString(vm)) {
          args = name;
          name = vm;
          vm = getCurrentPageVm();
      }
      else if (typeof vm === 'number') {
          const page = getCurrentPages().find((page) => page.$page.id === vm);
          if (page) {
              vm = page.$vm;
          }
          else {
              vm = getCurrentPageVm();
          }
      }
      if (!vm) {
          return;
      }
      const hooks = vm.$[name];
      return hooks && invokeArrayFns(hooks, args);
fxy060608's avatar
fxy060608 已提交
1537 1538
  }

fxy060608's avatar
fxy060608 已提交
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
  function normalizeRoute(toRoute) {
      if (toRoute.indexOf('/') === 0) {
          return toRoute;
      }
      let fromRoute = '';
      const pages = getCurrentPages();
      if (pages.length) {
          fromRoute = pages[pages.length - 1].$page.route;
      }
      return getRealRoute(fromRoute, toRoute);
  }
fxy060608's avatar
fxy060608 已提交
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
  function getRealRoute(fromRoute, toRoute) {
      if (toRoute.indexOf('/') === 0) {
          return toRoute;
      }
      if (toRoute.indexOf('./') === 0) {
          return getRealRoute(fromRoute, toRoute.substr(2));
      }
      const toRouteArray = toRoute.split('/');
      const toRouteLength = toRouteArray.length;
      let i = 0;
      for (; i < toRouteLength && toRouteArray[i] === '..'; i++) {
          // noop
      }
      toRouteArray.splice(0, i);
      toRoute = toRouteArray.join('/');
      const fromRouteArray = fromRoute.length > 0 ? fromRoute.split('/') : [];
      fromRouteArray.splice(fromRouteArray.length - i - 1, i + 1);
      return '/' + fromRouteArray.concat(toRouteArray).join('/');
fxy060608's avatar
fxy060608 已提交
1568 1569 1570 1571 1572 1573
  }
  function getRouteOptions(path, alias = false) {
      if (alias) {
          return __uniRoutes.find((route) => route.path === path || route.alias === path);
      }
      return __uniRoutes.find((route) => route.path === path);
fxy060608's avatar
fxy060608 已提交
1574 1575 1576 1577 1578 1579
  }
  function getRouteMeta(path) {
      const routeOptions = getRouteOptions(path);
      if (routeOptions) {
          return routeOptions.meta;
      }
fxy060608's avatar
fxy060608 已提交
1580 1581
  }

fxy060608's avatar
fxy060608 已提交
1582
  const ServiceJSBridge = /*#__PURE__*/ extend(initBridge('view' /* view 指的是 service 层订阅的是 view 层事件 */), {
fxy060608's avatar
fxy060608 已提交
1583 1584 1585 1586 1587
      invokeOnCallback(name, res) {
          return UniServiceJSBridge.emit('api.' + name, res);
      },
  });

fxy060608's avatar
fxy060608 已提交
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
  function initOn() {
      UniServiceJSBridge.on('onAppEnterForeground', onAppEnterForeground);
      UniServiceJSBridge.on('onAppEnterBackground', onAppEnterBackground);
  }
  function onAppEnterForeground() {
      const page = getCurrentPage();
      const showOptions = {
          path: '',
          query: {},
      };
      if (page) {
          showOptions.path = page.$page.route;
          showOptions.query = page.$page.options;
      }
      invokeHook(getApp(), 'onShow', showOptions);
      invokeHook(page, 'onShow');
  }
  function onAppEnterBackground() {
      invokeHook(getApp(), 'onHide');
      invokeHook(getCurrentPage(), 'onHide');
  }

  const SUBSCRIBE_LIFECYCLE_HOOKS = ['onPageScroll', 'onReachBottom'];
  function initSubscribe() {
      SUBSCRIBE_LIFECYCLE_HOOKS.forEach((name) => UniServiceJSBridge.subscribe(name, createPageEvent(name)));
  }
  function createPageEvent(name) {
      return (args, pageId) => {
          const vm = getPageVmById(pageId);
          if (vm) {
              invokeHook(vm, name, args);
          }
      };
  }

  function initService() {
      initOn();
      initSubscribe();
  }

fxy060608's avatar
fxy060608 已提交
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
  function querySelector(vm, selector) {
      const el = vm.$el.querySelector(selector);
      return el && el.__vue__;
  }
  function querySelectorAll(vm, selector) {
      const nodeList = vm.$el.querySelectorAll(selector);
      if (nodeList) {
          return [...nodeList].map((node) => node.__vue__).filter(Boolean);
      }
      return [];
  }
  function createSelectorQuery() {
      return uni.createSelectorQuery().in(this);
  }
  function createMediaQueryObserver() {
      return uni.createMediaQueryObserver(this);
  }
  function createIntersectionObserver(options) {
      return uni.createIntersectionObserver(this, options);
  }
  function selectComponent(selector) {
      return querySelector(this, selector);
  }
  function selectAllComponents(selector) {
      return querySelectorAll(this, selector);
  }

  var wxInstance = /*#__PURE__*/Object.freeze({
    __proto__: null,
    createSelectorQuery: createSelectorQuery,
    createMediaQueryObserver: createMediaQueryObserver,
    createIntersectionObserver: createIntersectionObserver,
    selectComponent: selectComponent,
    selectAllComponents: selectAllComponents
  });

  function initAppConfig(appConfig) {
      {
          const globalProperties = appConfig.globalProperties;
          extend(globalProperties, wxInstance);
      }
  }

fxy060608's avatar
fxy060608 已提交
1671
  function initServicePlugin(app) {
fxy060608's avatar
fxy060608 已提交
1672 1673 1674
      initAppConfig(app._context.config);
  }

fxy060608's avatar
fxy060608 已提交
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
  function getRealPath(filepath) {
      // 无协议的情况补全 https
      if (filepath.indexOf('//') === 0) {
          return 'https:' + filepath;
      }
      // 网络资源或base64
      if (SCHEME_RE.test(filepath) || DATA_RE.test(filepath)) {
          return filepath;
      }
      if (isSystemURL(filepath)) {
          return 'file://' + normalizeLocalPath(filepath);
      }
      const wwwPath = 'file://' + normalizeLocalPath('_www');
      // 绝对路径转换为本地文件系统路径
      if (filepath.indexOf('/') === 0) {
          // 平台绝对路径 安卓、iOS
          if (filepath.startsWith('/storage/') ||
              filepath.includes('/Containers/Data/Application/')) {
              return 'file://' + filepath;
          }
          return wwwPath + filepath;
      }
      // 相对资源
      if (filepath.indexOf('../') === 0 || filepath.indexOf('./') === 0) {
          // @ts-expect-error app-view
          if (typeof __id__ === 'string') {
              // @ts-expect-error app-view
              return wwwPath + getRealRoute('/' + __id__, filepath);
          }
          else {
              const pages = getCurrentPages();
              if (pages.length) {
                  return (wwwPath + getRealRoute('/' + pages[pages.length - 1].route, filepath));
              }
          }
      }
      return filepath;
  }
  const normalizeLocalPath = cacheStringFunction((filepath) => {
      return plus.io
          .convertLocalFileSystemURL(filepath)
          .replace(/^\/?apps\//, '/android_asset/apps/')
          .replace(/\/$/, '');
  });
  function isSystemURL(filepath) {
      if (filepath.indexOf('_www') === 0 ||
          filepath.indexOf('_doc') === 0 ||
          filepath.indexOf('_documents') === 0 ||
          filepath.indexOf('_downloads') === 0) {
          return true;
      }
      return false;
  }

  const API_CREATE_INNER_AUDIO_CONTEXT = 'createInnerAudioContext';

  //#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 API_GET_BACKGROUND_AUDIO_MANAGER = 'getBackgroundAudioManager';

  const API_MAKE_PHONE_CALL = 'makePhoneCall';
  const MakePhoneCallProtocol = {
      phoneNumber: String,
  };

1767 1768
  const API_ADD_PHONE_CONTACT = 'addPhoneContact';

fxy060608's avatar
fxy060608 已提交
1769 1770 1771
  const API_GET_CLIPBOARD_DATA = 'getClipboardData';
  const API_SET_CLIPBOARD_DATA = 'setClipboardData';

fxy060608's avatar
fxy060608 已提交
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
  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';

fxy060608's avatar
fxy060608 已提交
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
  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,
  };

fxy060608's avatar
fxy060608 已提交
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
  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_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_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_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_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';

fxy060608's avatar
fxy060608 已提交
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
  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,
  };

fxy060608's avatar
fxy060608 已提交
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
  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_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_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,
  };

fxy060608's avatar
fxy060608 已提交
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
  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 BaseRouteProtocol = {
      url: {
          type: String,
          required: true,
      },
  };
  const API_NAVIGATE_TO = 'navigateTo';
  const API_REDIRECT_TO = 'redirectTo';
  const API_SWITCH_TAB = 'switchTab';
fxy060608's avatar
fxy060608 已提交
2359
  const API_NAVIGATE_BACK = 'navigateBack';
fxy060608's avatar
fxy060608 已提交
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
  const API_PRELOAD_PAGE = 'preloadPage';
  const API_UN_PRELOAD_PAGE = 'unPreloadPage';
  const NavigateToProtocol = 
  /*#__PURE__*/ extend({}, BaseRouteProtocol, createAnimationProtocol(ANIMATION_IN));
  const NavigateToOptions = 
  /*#__PURE__*/ createRouteOptions(API_NAVIGATE_TO);
  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.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;
          }
      };
  }

fxy060608's avatar
fxy060608 已提交
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
  const API_HIDE_LOADING = 'hideLoading';

  const API_HIDE_TOAST = 'hideToast';

  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_GET_PROVIDER = 'getProvider';
  const GetProviderProtocol = {
      service: {
          type: String,
          required: true,
      },
  };

fxy060608's avatar
fxy060608 已提交
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
  const API_LOGIN = 'login';
  const LoginProtocol = {
      provider: String,
      scopes: [String, Array],
      timeout: Number,
      univerifyStyle: Object,
  };
  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_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 (!TYPE.includes(value))
                  return '分享参数 type 不正确';
              return 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,
  };

fxy060608's avatar
fxy060608 已提交
2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
  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,
      },
  };

fxy060608's avatar
fxy060608 已提交
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
  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),
          }));
      };
  }
fxy060608's avatar
fxy060608 已提交
2806
  function callApiSync(api, args, resolve, reject) {
fxy060608's avatar
fxy060608 已提交
2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998
      api(args)
          .then(() => {
          resolve();
      })
          .catch((errMsg) => {
          reject(errMsg);
      });
  }

  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 = 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 }) => {
      plus.io.resolveLocalFileSystemURL(getRealPath(filePath), (entry) => {
          plus.runtime.openFile(getRealPath(filePath));
          resolve();
      }, (err) => {
          reject('openDocument:fail ' + err.message);
      });
  }, OpenDocumentProtocol, OpenDocumentOptions);

  const DEVICE_FREQUENCY = 200;
fxy060608's avatar
fxy060608 已提交
2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
  const NETWORK_TYPES = [
      'unknown',
      'none',
      'ethernet',
      'wifi',
      '2g',
      '3g',
      '4g',
      '5g',
  ];
fxy060608's avatar
fxy060608 已提交
3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
  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 = (defineOnApi(API_OFF_COMPASS, () => {
      stopCompass();
  }));
  const startCompass = (defineAsyncApi(API_START_COMPASS, (_, { resolve, reject }) => {
      if (!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 = (defineOnApi(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, API_ON_BLUETOOTH_DEVICE_FOUND));
  const onBluetoothAdapterStateChange = defineOnApi(API_ON_BLUETOOTH_ADAPTER_STATE_CHANGE, warpPlusEvent(() => plus.bluetooth.onBluetoothAdapterStateChange, API_ON_BLUETOOTH_ADAPTER_STATE_CHANGE));
  const onBLEConnectionStateChange = defineOnApi(API_ON_BLE_CONNECTION_STATE_CHANGE, warpPlusEvent(() => plus.bluetooth.onBLEConnectionStateChange, API_ON_BLE_CONNECTION_STATE_CHANGE));
  const onBLECharacteristicValueChange = defineOnApi(API_ON_BLE_CHARACTERISTIC_VALUE_CHANGE, warpPlusEvent(() => plus.bluetooth.onBLECharacteristicValueChange, API_ON_BLE_CHARACTERISTIC_VALUE_CHANGE));
  const openBluetoothAdapter = defineAsyncApi('openBluetoothAdapter', warpPlusMethod(() => plus.bluetooth.openBluetoothAdapter));
  const closeBluetoothAdapter = defineAsyncApi('closeBluetoothAdapter', warpPlusMethod(() => plus.bluetooth.closeBluetoothAdapter));
  const getBluetoothAdapterState = defineAsyncApi('getBluetoothAdapterState', warpPlusMethod(() => plus.bluetooth.getBluetoothAdapterState));
  const startBluetoothDevicesDiscovery = defineAsyncApi(API_START_BLUETOOTH_DEVICES_DISCOVERY, warpPlusMethod(() => plus.bluetooth.startBluetoothDevicesDiscovery), StartBluetoothDevicesDiscoveryProtocol);
  const stopBluetoothDevicesDiscovery = defineAsyncApi('stopBluetoothDevicesDiscovery', warpPlusMethod(() => plus.bluetooth.stopBluetoothDevicesDiscovery));
  const getBluetoothDevices = defineAsyncApi('getBluetoothDevices', warpPlusMethod(() => plus.bluetooth.getBluetoothDevices));
  const getConnectedBluetoothDevices = defineAsyncApi(API_GET_CONNECTED_BLUETOOTH_DEVICES, warpPlusMethod(() => plus.bluetooth.getConnectedBluetoothDevices), GetConnectedBluetoothDevicesProtocol);
  const createBLEConnection = defineAsyncApi(API_CREATE_BLE_CONNECTION, warpPlusMethod(() => plus.bluetooth.createBLEConnection), CreateBLEConnectionProtocol);
  const closeBLEConnection = defineAsyncApi(API_CLOSE_BLE_CONNECTION, warpPlusMethod(() => plus.bluetooth.closeBLEConnection), CloseBLEConnectionProtocol);
  const getBLEDeviceServices = defineAsyncApi(API_GET_BLE_DEVICE_SERVICES, warpPlusMethod(() => plus.bluetooth.getBLEDeviceServices), GetBLEDeviceServicesProtocol);
  const getBLEDeviceCharacteristics = defineAsyncApi(API_GET_BLE_DEVICE_CHARACTERISTICS, warpPlusMethod(() => plus.bluetooth.getBLEDeviceCharacteristics), GetBLEDeviceCharacteristicsProtocol);
  const notifyBLECharacteristicValueChange = defineAsyncApi(API_NOTIFY_BLE_CHARACTERISTIC_VALUE_CHANGE, warpPlusMethod(() => plus.bluetooth.notifyBLECharacteristicValueChange), NotifyBLECharacteristicValueChangeProtocol);
  const readBLECharacteristicValue = defineAsyncApi(API_READ_BLE_CHARACTERISTIC_VALUE, warpPlusMethod(() => plus.bluetooth.readBLECharacteristicValue), ReadBLECharacteristicValueProtocol);
  const writeBLECharacteristicValue = defineAsyncApi(API_WRITE_BLE_CHARACTERISTIC_VALUE, warpPlusMethod(() => plus.bluetooth.writeBLECharacteristicValue), WriteBLECharacteristicValueProtocol);
  const setBLEMTU = defineAsyncApi(API_SET_BLE_MTU, warpPlusMethod(() => plus.bluetooth.setBLEMTU), SetBLEMTUProtocol);
  const getBLEDeviceRSSI = defineAsyncApi(API_GET_BLE_DEVICE_RSSI, warpPlusMethod(() => plus.bluetooth.getBLEDeviceRSSI), GetBLEDeviceRSSIProtocol);

  const onBeaconUpdate = defineOnApi(API_ON_BEACON_UPDATE, warpPlusEvent(() => plus.ibeacon.onBeaconUpdate, API_ON_BEACON_UPDATE));
  const onBeaconServiceChange = defineOnApi(API_ON_BEACON_SERVICE_CHANGE, warpPlusEvent(() => plus.ibeacon.onBeaconServiceChange, API_ON_BEACON_SERVICE_CHANGE));
  const getBeacons = defineAsyncApi(API_GET_BEACONS, warpPlusMethod(() => plus.ibeacon.getBeacons));
  const startBeaconDiscovery = defineAsyncApi(API_START_BEACON_DISCOVERY, warpPlusMethod(() => plus.ibeacon.startBeaconDiscovery), StartBeaconDiscoveryProtocol);
  const stopBeaconDiscovery = defineAsyncApi(API_STOP_BEACON_DISCOVERY, warpPlusMethod(() => plus.ibeacon.stopBeaconDiscovery));

  const makePhoneCall = defineAsyncApi(API_MAKE_PHONE_CALL, ({ phoneNumber }, { resolve }) => {
      plus.device.dial(phoneNumber);
      return resolve();
  }, MakePhoneCallProtocol);

3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
  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);

fxy060608's avatar
fxy060608 已提交
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325
  function requireNativePlugin(pluginName) {
      /* eslint-disable no-undef */
      if (typeof weex !== 'undefined') {
          return weex.requireModule(pluginName);
      }
      /* eslint-disable no-undef */
      return __requireNativePlugin__(pluginName);
  }

  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();
  });

  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 });
  });

fxy060608's avatar
fxy060608 已提交
3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550
  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);

fxy060608's avatar
fxy060608 已提交
3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697
  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);

  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, }) {
          if (recording) {
              return publishRecorderStateChange('start');
          }
          recorder = plus.audio.getRecorder();
          recorder.record({
              format,
              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',
              });
          }
      },
  };
fxy060608's avatar
fxy060608 已提交
3698
  const callbacks$1 = {
fxy060608's avatar
fxy060608 已提交
3699 3700 3701 3702 3703 3704 3705 3706 3707 3708
      pause: null,
      resume: null,
      start: null,
      stop: null,
      error: null,
  };
  function onRecorderStateChange(res) {
      const state = res.state;
      delete res.state;
      delete res.errMsg;
fxy060608's avatar
fxy060608 已提交
3709 3710
      if (state && typeof callbacks$1[state] === 'function') {
          callbacks$1[state](res);
fxy060608's avatar
fxy060608 已提交
3711 3712 3713 3714 3715
      }
  }
  class RecorderManager {
      constructor() { }
      onError(callback) {
fxy060608's avatar
fxy060608 已提交
3716
          callbacks$1.error = callback;
fxy060608's avatar
fxy060608 已提交
3717 3718 3719 3720 3721
      }
      onFrameRecorded(callback) { }
      onInterruptionBegin(callback) { }
      onInterruptionEnd(callback) { }
      onPause(callback) {
fxy060608's avatar
fxy060608 已提交
3722
          callbacks$1.pause = callback;
fxy060608's avatar
fxy060608 已提交
3723 3724
      }
      onResume(callback) {
fxy060608's avatar
fxy060608 已提交
3725
          callbacks$1.resume = callback;
fxy060608's avatar
fxy060608 已提交
3726 3727
      }
      onStart(callback) {
fxy060608's avatar
fxy060608 已提交
3728
          callbacks$1.start = callback;
fxy060608's avatar
fxy060608 已提交
3729 3730
      }
      onStop(callback) {
fxy060608's avatar
fxy060608 已提交
3731
          callbacks$1.stop = callback;
fxy060608's avatar
fxy060608 已提交
3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756
      }
      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);

fxy060608's avatar
fxy060608 已提交
3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783
  function getFileName(path) {
      const array = path.split('/');
      return array[array.length - 1];
  }

  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 dst = `${TEMP_PATH}/compressed/${Date.now()}_${getFileName(options.src)}`;
      plus.zip.compressVideo(extend({}, options, {
          dst,
      }), () => {
          resolve({
              tempFilePath: dst,
          });
      }, reject);
  }, CompressVideoProtocol, CompressVideoOptions);

fxy060608's avatar
fxy060608 已提交
3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519
  const showKeyboard = defineAsyncApi(API_SHOW_KEYBOARD, (_, { resolve }) => {
      plus.key.showSoftKeybord();
      resolve();
  });
  const hideKeyboard = defineAsyncApi(API_HIDE_KEYBOARD, (_, { resolve }) => {
      plus.key.hideSoftKeybord();
      resolve();
  });

  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 socketTasks = [];
  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');
          }
          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 };
  }
  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;
          this._socket.onopen(() => {
              this.readyState = this.OPEN;
              this.socketStateChange('open');
          });
          this._socket.onmessage((e) => {
              this.socketStateChange('message', {
                  data: typeof e.data === 'object'
                      ? base64ToArrayBuffer(e.data.base64)
                      : e.data,
              });
          });
          this._socket.onerror(() => {
              this.onErrorOrClose();
              this.socketStateChange('error');
          });
          this._socket.onclose(() => {
              this.onErrorOrClose();
              this.socketStateChange('close');
          });
          const oldSocketSend = this._socket.send;
          const oldSocketClose = this._socket.close;
          this._socket.send = (res) => {
              oldSocketSend(extend({
                  id: this.id,
                  data: typeof res.data === 'object'
                      ? {
                          '@type': 'binary',
                          base64: arrayBufferToBase64(res.data),
                      }
                      : res.data,
              }));
          };
          this._socket.close = (res) => {
              oldSocketClose(extend({
                  id: this.id,
                  res,
              }));
          };
      }
      onErrorOrClose() {
          this.readyState = this.CLOSED;
          const index = socketTasks.indexOf(this);
          if (index >= 0) {
              socketTasks.splice(index, 1);
          }
      }
      socketStateChange(name, res = {}) {
          if (this === socketTasks[0] && globalEvent[name]) {
              UniServiceJSBridge.invokeOnCallback(globalEvent[name], res);
          }
          // WYQ fix: App平台修复websocket onOpen时发送数据报错的Bug
          this._callbacks[name].forEach((callback) => {
              if (typeof callback === 'function') {
                  callback(name === 'message' ? res : {});
              }
          });
      }
      send(args) {
          if (this.readyState !== this.OPEN) {
              callOptions(args, 'sendSocketMessage:fail WebSocket is not connected');
          }
          try {
              this._socket.send({
                  data: args.data,
              });
              callOptions(args, 'sendSocketMessage:ok');
          }
          catch (error) {
              callOptions(args, `sendSocketMessage:fail ${error}`);
          }
      }
      close(args) {
          this.readyState = this.CLOSING;
          try {
              this._socket.close(args);
              callOptions(args, 'closeSocket:ok');
          }
          catch (error) {
              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);
      }
      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('sendSocketMessage:fail WebSocket is not connected');
          return;
      }
      socketTask._socket.send({
          data: args.data,
      });
      resolve();
  }, SendSocketMessageProtocol);
  const closeSocket = defineAsyncApi(API_CLOSE_SOCKET, (args, { resolve, reject }) => {
      const socketTask = socketTasks[0];
      if (!socketTask) {
          reject('closeSocket:fail WebSocket is not connected');
          return;
      }
      socketTask.readyState = socketTask.CLOSING;
      const { code, reason } = args;
      socketTask._socket.close({ code, reason });
      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');

  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${state[0].toUpperCase() + state.substr(1)}`;
      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',
  ];
fxy060608's avatar
fxy060608 已提交
4520
  const callbacks = {
fxy060608's avatar
fxy060608 已提交
4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698
      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, }) {
fxy060608's avatar
fxy060608 已提交
4699
      callbacks[state].forEach((callback) => {
fxy060608's avatar
fxy060608 已提交
4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713
          if (typeof callback === 'function') {
              callback(state === 'error'
                  ? {
                      errMsg,
                      errCode,
                  }
                  : {});
          }
      });
  }
  const onInitBackgroundAudioManager = /*#__PURE__*/ once(() => {
      eventNames.forEach((item) => {
          const name = item[0].toUpperCase() + item.substr(1);
          BackgroundAudioManager.prototype[`on${name}`] = function (callback) {
fxy060608's avatar
fxy060608 已提交
4714
              callbacks[item].push(callback);
fxy060608's avatar
fxy060608 已提交
4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153
          };
      });
  });
  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()));

  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 }, { 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,
      });
  }, GetLocationProtocol, GetLocationOptions);

  const showModal = defineAsyncApi(API_SHOW_MODAL, ({ title = '', content = '', showCancel = true, cancelText, cancelColor, confirmText, confirmColor, } = {}, { resolve }) => {
      content = content || ' ';
      plus.nativeUI.confirm(content, (e) => {
          if (showCancel) {
              resolve({
                  confirm: e.index === 1,
                  cancel: e.index === 0 || e.index === -1,
              });
          }
          else {
              resolve({
                  confirm: e.index === 0,
                  cancel: false,
              });
          }
      }, title, showCancel ? [cancelText, confirmText] : [confirmText]);
  }, 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);

  let toast;
  let isShowToast = false;
  let toastType = '';
  let timeout;
  const showLoading = defineAsyncApi(API_SHOW_LOADING, (args, { resolve, reject }) => {
      callApiSync(showToast, extend({}, args, {
          type: 'loading',
      }), resolve, reject);
  }, ShowLoadingProtocol, ShowLoadingOptions);
  const hideLoading = defineAsyncApi(API_HIDE_LOADING, (_, { resolve, reject }) => {
      callApiSync(hide, 'loading', resolve, reject);
  });
  const showToast = defineAsyncApi(API_SHOW_TOAST, ({ 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();
  }, ShowToastProtocol, ShowToastOptions);
  const hideToast = defineAsyncApi(API_HIDE_TOAST, (_, { resolve, reject }) => {
      callApiSync(hide, 'toast', resolve, reject);
  });
  function hide(type = 'toast') {
      if (type && type !== toastType) {
          return;
      }
      if (timeout) {
          clearTimeout(timeout);
          timeout = null;
      }
      if (isShowToast) {
          plus.nativeUI.closeToast();
      }
      else if (toast && toast.close) {
          toast.close();
      }
      toast = null;
      isShowToast = false;
      toastType = '';
      return {
          errMsg: 'hide:ok',
      };
  }

  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);

fxy060608's avatar
fxy060608 已提交
5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299
  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 baseLogin = (params, { resolve, reject, }) => {
      const provider = params.provider || 'weixin';
      const errorCallback = warpPlusErrorCallback(reject);
      getService(provider)
          .then((service) => {
          function login() {
              service.login((res) => {
                  const authResult = res.target.authResult;
                  resolve({
                      code: authResult.code,
                      authResult: authResult,
                  });
              }, errorCallback, provider === 'apple'
                  ? { scope: 'email' }
                  : {
                      univerifyStyle: univerifyButtonsClickHandling(params.univerifyStyle, errorCallback),
                  } || {});
          }
          // 先注销再登录
          // apple登录logout之后无法重新触发获取email,fullname;一键登录无logout
          if (provider === 'apple' || provider === 'univerify') {
              login();
          }
          else {
              service.logout(login, login);
          }
      })
          .catch(errorCallback);
  };
  const login = defineAsyncApi(API_LOGIN, baseLogin, LoginProtocol);
  const getUserInfo = defineAsyncApi(API_GET_USER_INFO, (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,
                          // @ts-ignore
                          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');
      });
  }, GetUserInfoProtocol);
  /**
   * 获取用户信息-兼容
   */
  const getUserProfile = defineAsyncApi(API_GET_USER_PROFILE, (params, { resolve, reject }) => {
      return baseLogin(params, { resolve, reject });
  }, GgetUserProfileProtocol);
  const preLogin = defineAsyncApi(API_PRE_LOGIN, (params, { resolve, reject }) => {
      const successCallback = warpPlusSuccessCallback(resolve);
      const errorCallback = warpPlusErrorCallback(reject);
      getService(params.provider)
          .then((service) => service.preLogin(successCallback, errorCallback))
          .catch(errorCallback);
  }, PreLoginProtocol, PreLoginOptions);
  const _closeAuthView = () => getService('univerify').then((service) => service.closeAuthView());
  const closeAuthView = defineAsyncApi(API_CLOSE_AUTH_VIEW, _closeAuthView);
  /**
   * 一键登录自定义登陆按钮点击处理
   */
  function univerifyButtonsClickHandling(univerifyStyle, errorCallback) {
      if (isPlainObject(univerifyStyle) &&
          univerifyStyle.buttons &&
          toTypeString(univerifyStyle.buttons.list) === '[object Array]' &&
          univerifyStyle.buttons.list.length > 0) {
          univerifyStyle.buttons.list.forEach((button, index) => {
              univerifyStyle.buttons.list[index].onclick = function () {
                  _closeAuthView().then(() => {
                      errorCallback({
                          code: '30008',
                          message: '用户点击了自定义按钮',
                          index,
                          provider: button.provider,
                      });
                  });
              };
          });
      }
      return univerifyStyle;
  }

fxy060608's avatar
fxy060608 已提交
5300 5301 5302 5303 5304
  const registerRuntime = defineSyncApi('registerRuntime', (runtime) => {
      // @ts-expect-error
      extend(jsRuntime, runtime);
  });

fxy060608's avatar
fxy060608 已提交
5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419
  // 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);

  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);

fxy060608's avatar
fxy060608 已提交
5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437
  function applyOptions(options, instance, publicThis) {
      Object.keys(options).forEach((name) => {
          if (name.indexOf('on') === 0) {
              const hook = options[name];
              if (isFunction(hook)) {
                  vue.injectHook(name, hook.bind(publicThis), instance);
              }
          }
      });
  }

  function set(target, key, val) {
      return (target[key] = val);
  }

  function errorHandler(err, instance, info) {
      if (!instance) {
          throw err;
fxy060608's avatar
fxy060608 已提交
5438
      }
fxy060608's avatar
fxy060608 已提交
5439 5440 5441
      const app = getApp();
      if (!app || !app.$vm) {
          throw err;
fxy060608's avatar
fxy060608 已提交
5442
      }
fxy060608's avatar
fxy060608 已提交
5443 5444
      {
          invokeHook(app.$vm, 'onError', err);
fxy060608's avatar
fxy060608 已提交
5445
      }
fxy060608's avatar
fxy060608 已提交
5446 5447 5448 5449 5450 5451
  }

  function initApp(app) {
      const appConfig = app._context.config;
      if (isFunction(app._component.onError)) {
          appConfig.errorHandler = errorHandler;
fxy060608's avatar
fxy060608 已提交
5452
      }
fxy060608's avatar
fxy060608 已提交
5453 5454 5455 5456
      const globalProperties = appConfig.globalProperties;
      {
          globalProperties.$set = set;
          globalProperties.$applyOptions = applyOptions;
fxy060608's avatar
fxy060608 已提交
5457
      }
fxy060608's avatar
fxy060608 已提交
5458 5459 5460 5461 5462 5463
  }

  let isInitEntryPage = false;
  function initEntry() {
      if (isInitEntryPage) {
          return;
fxy060608's avatar
fxy060608 已提交
5464
      }
fxy060608's avatar
fxy060608 已提交
5465 5466 5467 5468 5469 5470 5471 5472
      isInitEntryPage = true;
      let entryPagePath;
      let entryPageQuery;
      const weexPlus = weex.requireModule('plus');
      if (weexPlus.getRedirectInfo) {
          const info = weexPlus.getRedirectInfo() || {};
          entryPagePath = info.path;
          entryPageQuery = info.query ? '?' + info.query : '';
fxy060608's avatar
fxy060608 已提交
5473
      }
fxy060608's avatar
fxy060608 已提交
5474 5475 5476
      else {
          const argsJsonStr = plus.runtime.arguments;
          if (!argsJsonStr) {
fxy060608's avatar
fxy060608 已提交
5477 5478
              return;
          }
fxy060608's avatar
fxy060608 已提交
5479 5480 5481 5482 5483 5484
          try {
              const args = JSON.parse(argsJsonStr);
              entryPagePath = args.path || args.pathName;
              entryPageQuery = args.query ? '?' + args.query : '';
          }
          catch (e) { }
fxy060608's avatar
fxy060608 已提交
5485
      }
fxy060608's avatar
fxy060608 已提交
5486 5487 5488
      if (!entryPagePath || entryPagePath === __uniConfig.entryPagePath) {
          if (entryPageQuery) {
              __uniConfig.entryPageQuery = entryPageQuery;
fxy060608's avatar
fxy060608 已提交
5489
          }
fxy060608's avatar
fxy060608 已提交
5490
          return;
fxy060608's avatar
fxy060608 已提交
5491
      }
fxy060608's avatar
fxy060608 已提交
5492 5493 5494 5495
      const entryRoute = '/' + entryPagePath;
      const routeOptions = getRouteOptions(entryRoute);
      if (!routeOptions) {
          return;
fxy060608's avatar
fxy060608 已提交
5496
      }
fxy060608's avatar
fxy060608 已提交
5497 5498 5499
      if (!routeOptions.meta.isTabBar) {
          __uniConfig.realEntryPagePath =
              __uniConfig.realEntryPagePath || __uniConfig.entryPagePath;
fxy060608's avatar
fxy060608 已提交
5500
      }
fxy060608's avatar
fxy060608 已提交
5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520
      __uniConfig.entryPagePath = entryPagePath;
      __uniConfig.entryPageQuery = entryPageQuery;
  }

  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(type, index, text) {
      if (!tabBar) {
          return;
fxy060608's avatar
fxy060608 已提交
5521
      }
fxy060608's avatar
fxy060608 已提交
5522 5523 5524 5525 5526 5527
      if (type === 'none') {
          tabBar.hideTabBarRedDot({
              index,
          });
          tabBar.removeTabBarBadge({
              index,
fxy060608's avatar
fxy060608 已提交
5528 5529
          });
      }
fxy060608's avatar
fxy060608 已提交
5530 5531 5532 5533
      else if (type === 'text') {
          tabBar.setTabBarBadge({
              index,
              text,
fxy060608's avatar
fxy060608 已提交
5534 5535
          });
      }
fxy060608's avatar
fxy060608 已提交
5536 5537 5538 5539
      else if (type === 'redDot') {
          tabBar.showTabBarRedDot({
              index,
          });
fxy060608's avatar
fxy060608 已提交
5540
      }
fxy060608's avatar
fxy060608 已提交
5541 5542 5543 5544 5545 5546 5547 5548 5549 5550
  }
  /**
   * 动态设置 tabBar 某一项的内容
   */
  function setTabBarItem(index, text, iconPath, selectedIconPath) {
      const item = {
          index,
      };
      if (text !== undefined) {
          item.text = text;
fxy060608's avatar
fxy060608 已提交
5551
      }
fxy060608's avatar
fxy060608 已提交
5552 5553
      if (iconPath) {
          item.iconPath = getRealPath(iconPath);
fxy060608's avatar
fxy060608 已提交
5554
      }
fxy060608's avatar
fxy060608 已提交
5555 5556
      if (selectedIconPath) {
          item.selectedIconPath = getRealPath(selectedIconPath);
fxy060608's avatar
fxy060608 已提交
5557
      }
fxy060608's avatar
fxy060608 已提交
5558
      tabBar && tabBar.setTabBarItem(item);
fxy060608's avatar
fxy060608 已提交
5559
  }
fxy060608's avatar
fxy060608 已提交
5560 5561 5562 5563 5564 5565
  /**
   * 动态设置 tabBar 的整体样式
   * @param {Object} style 样式
   */
  function setTabBarStyle(style) {
      tabBar && tabBar.setTabBarStyle(style);
fxy060608's avatar
fxy060608 已提交
5566
  }
fxy060608's avatar
fxy060608 已提交
5567 5568 5569 5570 5571 5572 5573 5574 5575 5576
  /**
   * 隐藏 tabBar
   * @param {boolean} animation 是否需要动画效果
   */
  function hideTabBar(animation) {
      visible = false;
      tabBar &&
          tabBar.hideTabBar({
              animation,
          });
fxy060608's avatar
fxy060608 已提交
5577
  }
fxy060608's avatar
fxy060608 已提交
5578 5579 5580 5581 5582 5583 5584 5585 5586
  /**
   * 显示 tabBar
   * @param {boolean} animation 是否需要动画效果
   */
  function showTabBar(animation) {
      visible = true;
      tabBar &&
          tabBar.showTabBar({
              animation,
fxy060608's avatar
fxy060608 已提交
5587 5588
          });
  }
fxy060608's avatar
fxy060608 已提交
5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605
  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();
              });
fxy060608's avatar
fxy060608 已提交
5606
          });
fxy060608's avatar
fxy060608 已提交
5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622
          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;
fxy060608's avatar
fxy060608 已提交
5623 5624
                  }
              }
fxy060608's avatar
fxy060608 已提交
5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670
          }
          return -1;
      },
      switchTab(page) {
          const index = this.indexOf(page);
          if (index >= 0) {
              tabBar &&
                  tabBar.switchSelect({
                      index,
                  });
              return true;
          }
          return false;
      },
      setTabBarBadge,
      setTabBarItem,
      setTabBarStyle,
      hideTabBar,
      showTabBar,
      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,
fxy060608's avatar
fxy060608 已提交
5671
          });
fxy060608's avatar
fxy060608 已提交
5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686
      },
      addEventListener(_name, callback) {
          maskClickCallback.push(callback);
      },
      removeEventListener(_name, callback) {
          const callbackIndex = maskClickCallback.indexOf(callback);
          maskClickCallback.splice(callbackIndex, 1);
      },
  };

  function initTabBar() {
      const { tabBar } = __uniConfig;
      const len = tabBar && tabBar.list && tabBar.list.length;
      if (!len) {
          return;
fxy060608's avatar
fxy060608 已提交
5687
      }
fxy060608's avatar
fxy060608 已提交
5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702
      const { entryPagePath } = __uniConfig;
      tabBar.selectedIndex = 0;
      const selected = tabBar.list.findIndex((page) => page.pagePath === entryPagePath);
      tabBar$1.init(tabBar, (item, index) => {
          uni.switchTab({
              url: '/' + item.pagePath,
              openType: 'switchTab',
              from: 'tabBar',
              success() {
                  invokeHook('onTabItemTap', {
                      index,
                      text: item.text,
                      pagePath: item.pagePath,
                  });
              },
fxy060608's avatar
fxy060608 已提交
5703
          });
fxy060608's avatar
fxy060608 已提交
5704 5705 5706 5707 5708
      });
      if (selected !== -1) {
          // 取当前 tab 索引值
          tabBar.selectedIndex = selected;
          selected !== 0 && tabBar$1.switchTab(entryPagePath);
fxy060608's avatar
fxy060608 已提交
5709
      }
fxy060608's avatar
fxy060608 已提交
5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723
  }

  function backbuttonListener() {
      uni.navigateBack({
          from: 'backbutton',
      });
  }

  function initGlobalEvent() {
      const plusGlobalEvent = plus.globalEvent;
      const weexGlobalEvent = weex.requireModule('globalEvent');
      const emit = UniServiceJSBridge.emit;
      if (weex.config.preload) {
          plus.key.addEventListener('backbutton', backbuttonListener);
fxy060608's avatar
fxy060608 已提交
5724
      }
fxy060608's avatar
fxy060608 已提交
5725 5726 5727 5728
      else {
          plusGlobalEvent.addEventListener('splashclosed', () => {
              plus.key.addEventListener('backbutton', backbuttonListener);
          });
fxy060608's avatar
fxy060608 已提交
5729
      }
fxy060608's avatar
fxy060608 已提交
5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747
      plusGlobalEvent.addEventListener('pause', () => {
          emit('onAppEnterBackground');
      });
      plusGlobalEvent.addEventListener('resume', () => {
          emit('onAppEnterForeground');
      });
      weexGlobalEvent.addEventListener('uistylechange', function (event) {
          const args = {
              theme: event.uistyle,
          };
          emit('onThemeChange', args);
      });
      plusGlobalEvent.addEventListener('plusMessage', subscribePlusMessage);
      // nvue webview post message
      plusGlobalEvent.addEventListener('WebviewPostMessage', subscribePlusMessage);
  }
  function subscribePlusMessage({ data, }) {
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
5748
          console.log(formatLog('plusMessage', data));
fxy060608's avatar
fxy060608 已提交
5749
      }
fxy060608's avatar
fxy060608 已提交
5750 5751
      if (data && data.type) {
          UniServiceJSBridge.subscribeHandler('plusMessage.' + data.type, data.args);
fxy060608's avatar
fxy060608 已提交
5752 5753
      }
  }
fxy060608's avatar
fxy060608 已提交
5754 5755 5756
  function onPlusMessage(type, callback, once = false) {
      UniServiceJSBridge.subscribe('plusMessage.' + type, callback, once);
  }
fxy060608's avatar
fxy060608 已提交
5757

fxy060608's avatar
fxy060608 已提交
5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798
  function initAppLaunch(appVm) {
      const args = {
          path: __uniConfig.entryPagePath,
          query: {},
          scene: 1001,
      };
      invokeHook(appVm, 'onLaunch', args);
      invokeHook(appVm, 'onShow', args);
  }

  // 统一处理路径
  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();
                      }
                  });
              }
          });
      });
  }
fxy060608's avatar
fxy060608 已提交
5799

fxy060608's avatar
fxy060608 已提交
5800
  const VD_SYNC = 'vdSync';
fxy060608's avatar
fxy060608 已提交
5801 5802
  const ON_WEBVIEW_READY = 'onWebviewReady';

fxy060608's avatar
fxy060608 已提交
5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835
  const ACTION_TYPE_PAGE_CREATE = 1;
  const ACTION_TYPE_PAGE_CREATED = 2;
  const ACTION_TYPE_CREATE = 3;
  const ACTION_TYPE_INSERT = 4;
  const ACTION_TYPE_REMOVE = 5;
  const ACTION_TYPE_SET_ATTRIBUTE = 6;
  const ACTION_TYPE_REMOVE_ATTRIBUTE = 7;
  const ACTION_TYPE_SET_TEXT = 8;
  const ACTION_TYPE_EVENT = 20;

  function onNodeEvent(nodeId, evt, pageNode) {
      pageNode.fireEvent(nodeId, evt);
  }

  function onVdSync(actions, pageId) {
      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.$.appContext.app
          ._container;
      actions.forEach((action) => {
          switch (action[0]) {
              case ACTION_TYPE_EVENT:
                  onNodeEvent(action[1], action[2], pageNode);
                  break;
          }
      });
  }

fxy060608's avatar
fxy060608 已提交
5836 5837 5838 5839 5840 5841 5842
  function initNVue(webviewStyle, routeMeta, path) {
      if (path && routeMeta.isNVue) {
          webviewStyle.uniNView = {
              path,
              defaultFontSize: __uniConfig.defaultFontSize,
              viewport: __uniConfig.viewport,
          };
fxy060608's avatar
fxy060608 已提交
5843 5844 5845
      }
  }

fxy060608's avatar
fxy060608 已提交
5846 5847 5848 5849 5850 5851 5852 5853
  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) {
fxy060608's avatar
fxy060608 已提交
5854 5855
          return;
      }
fxy060608's avatar
fxy060608 已提交
5856
      if (!isColor(backgroundColor)) {
fxy060608's avatar
fxy060608 已提交
5857 5858
          return;
      }
fxy060608's avatar
fxy060608 已提交
5859 5860
      if (!webviewStyle.background) {
          webviewStyle.background = backgroundColor;
fxy060608's avatar
fxy060608 已提交
5861
      }
fxy060608's avatar
fxy060608 已提交
5862 5863
      if (!webviewStyle.backgroundColorTop) {
          webviewStyle.backgroundColorTop = backgroundColor;
fxy060608's avatar
fxy060608 已提交
5864 5865 5866
      }
  }

fxy060608's avatar
fxy060608 已提交
5867 5868 5869 5870
  function initPopGesture(webviewStyle, routeMeta) {
      // 不支持 hide
      if (webviewStyle.popGesture === 'hide') {
          delete webviewStyle.popGesture;
fxy060608's avatar
fxy060608 已提交
5871
      }
fxy060608's avatar
fxy060608 已提交
5872 5873 5874
      // 似乎没用了吧?记得是之前流应用时,需要 appback 的逻辑
      if (routeMeta.isQuit) {
          webviewStyle.popGesture = (plus.os.name === 'iOS' ? 'appback' : 'none');
fxy060608's avatar
fxy060608 已提交
5875
      }
fxy060608's avatar
fxy060608 已提交
5876 5877 5878 5879 5880
  }

  function initPullToRefresh(webviewStyle, routeMeta) {
      if (!routeMeta.enablePullDownRefresh) {
          return;
fxy060608's avatar
fxy060608 已提交
5881
      }
fxy060608's avatar
fxy060608 已提交
5882 5883 5884
      webviewStyle.pullToRefresh = normalizePullToRefreshRpx(extend({}, plus.os.name === 'Android'
          ? defaultAndroidPullToRefresh
          : defaultPullToRefresh, routeMeta.pullToRefresh));
fxy060608's avatar
fxy060608 已提交
5885
  }
fxy060608's avatar
fxy060608 已提交
5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906
  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;
fxy060608's avatar
fxy060608 已提交
5907
      }
fxy060608's avatar
fxy060608 已提交
5908 5909 5910
      let autoBackButton = true;
      if (routeMeta.isQuit) {
          autoBackButton = false;
fxy060608's avatar
fxy060608 已提交
5911
      }
fxy060608's avatar
fxy060608 已提交
5912 5913 5914 5915 5916 5917 5918 5919 5920
      const titleNView = {
          autoBackButton,
      };
      Object.keys(navigationBar).forEach((name) => {
          const value = navigationBar[name];
          if (name === 'backgroundColor') {
              titleNView.backgroundColor = isColor(value)
                  ? value
                  : BACKGROUND_COLOR;
fxy060608's avatar
fxy060608 已提交
5921
          }
fxy060608's avatar
fxy060608 已提交
5922 5923
          else if (name === 'titleImage' && value) {
              titleNView.tags = createTitleImageTags(value);
fxy060608's avatar
fxy060608 已提交
5924
          }
fxy060608's avatar
fxy060608 已提交
5925 5926 5927 5928
          else if (name === 'buttons' && isArray(value)) {
              titleNView.buttons = value.map((button, index) => {
                  button.onclick = createTitleNViewBtnClick(index);
                  return button;
fxy060608's avatar
fxy060608 已提交
5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954
              });
          }
      });
      webviewStyle.titleNView = 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('onNavigationBarButtonTap', btn);
      };
  }

fxy060608's avatar
fxy060608 已提交
5955
  function parseWebviewStyle(path, routeMeta) {
fxy060608's avatar
fxy060608 已提交
5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995
      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;
fxy060608's avatar
fxy060608 已提交
5996
  let preloadWebview$1;
fxy060608's avatar
fxy060608 已提交
5997 5998 5999 6000 6001 6002 6003
  function getWebviewId() {
      return id;
  }
  function genWebviewId() {
      return id++;
  }
  function getPreloadWebview() {
fxy060608's avatar
fxy060608 已提交
6004
      return preloadWebview$1;
fxy060608's avatar
fxy060608 已提交
6005 6006 6007 6008 6009 6010 6011 6012 6013 6014
  }
  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,
      };
fxy060608's avatar
fxy060608 已提交
6015 6016 6017 6018 6019 6020 6021 6022 6023 6024
  }
  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,
          }),
      };
fxy060608's avatar
fxy060608 已提交
6025 6026 6027 6028
  }

  function createNVueWebview({ path, query, routeOptions, webviewStyle, }) {
      const curWebviewId = genWebviewId();
fxy060608's avatar
fxy060608 已提交
6029
      const curWebviewStyle = parseWebviewStyle(path, routeOptions.meta);
fxy060608's avatar
fxy060608 已提交
6030 6031
      curWebviewStyle.uniPageUrl = initUniPageUrl(path, query);
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6032
          console.log(formatLog('createNVueWebview', curWebviewId, path, curWebviewStyle));
fxy060608's avatar
fxy060608 已提交
6033 6034 6035 6036 6037 6038 6039
      }
      curWebviewStyle.isTab = !!routeOptions.meta.isTabBar;
      return plus.webview.create('', String(curWebviewId), curWebviewStyle, extend({
          nvue: true,
      }, webviewStyle));
  }

fxy060608's avatar
fxy060608 已提交
6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051
  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;
      }
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6052
          console.log(formatLog('updateWebview', webviewStyle));
fxy060608's avatar
fxy060608 已提交
6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063
      }
      webview.setStyle(webviewStyle);
  }

  function initWebview(webview, path, query, routeMeta) {
      // 首页或非 nvue 页面
      if (webview.id === '1' || !routeMeta.isNVue) {
          initWebviewStyle(webview, path, query, routeMeta);
      }
  }

fxy060608's avatar
fxy060608 已提交
6064 6065 6066 6067 6068
  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 VIEW_WEBVIEW_PATH = '_www/__uniappview.html';

fxy060608's avatar
fxy060608 已提交
6069 6070 6071
  let preloadWebview;
  function setPreloadWebview(webview) {
      preloadWebview = webview;
fxy060608's avatar
fxy060608 已提交
6072 6073 6074 6075 6076 6077
  }
  function createPreloadWebview() {
      if (!preloadWebview || preloadWebview.__uniapp_route) {
          // 不存在,或已被使用
          preloadWebview = plus.webview.create(VIEW_WEBVIEW_PATH, String(genWebviewId()));
          if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6078
              console.log(formatLog('createPreloadWebview', preloadWebview.id));
fxy060608's avatar
fxy060608 已提交
6079 6080 6081
          }
      }
      return preloadWebview;
fxy060608's avatar
fxy060608 已提交
6082 6083
  }

fxy060608's avatar
fxy060608 已提交
6084 6085 6086 6087 6088 6089 6090 6091 6092
  function createWebview(options) {
      if (options.routeOptions.meta.isNVue) {
          return createNVueWebview(options);
      }
      if (getWebviewId() === 2) {
          // 如果首页非 nvue,则直接返回 Launch Webview
          return plus.webview.getLaunchWebview();
      }
      return getPreloadWebview();
fxy060608's avatar
fxy060608 已提交
6093 6094 6095
  }
  function onWebviewReady(pageId, callback) {
      UniServiceJSBridge.once(ON_WEBVIEW_READY + '.' + pageId, callback);
fxy060608's avatar
fxy060608 已提交
6096 6097
  }

fxy060608's avatar
fxy060608 已提交
6098 6099 6100 6101 6102 6103
  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');
fxy060608's avatar
fxy060608 已提交
6104
          }
fxy060608's avatar
fxy060608 已提交
6105
          return;
fxy060608's avatar
fxy060608 已提交
6106
      }
fxy060608's avatar
fxy060608 已提交
6107 6108 6109 6110
      if (isLaunchWebview) {
          // 首页
          isLaunchWebviewReady = true;
          setPreloadWebview(plus.webview.getLaunchWebview());
fxy060608's avatar
fxy060608 已提交
6111
      }
fxy060608's avatar
fxy060608 已提交
6112 6113 6114
      else if (!preloadWebview) {
          // preloadWebview 不存在,重新加载一下
          setPreloadWebview(plus.webview.getWebviewById(pageId));
fxy060608's avatar
fxy060608 已提交
6115
      }
fxy060608's avatar
fxy060608 已提交
6116 6117
      if (preloadWebview.id !== pageId) {
          return console.error(`webviewReady[${preloadWebview.id}][${pageId}] not match`);
fxy060608's avatar
fxy060608 已提交
6118
      }
fxy060608's avatar
fxy060608 已提交
6119 6120 6121
      preloadWebview.loaded = true; // 标记已 ready
      UniServiceJSBridge.emit(ON_WEBVIEW_READY + '.' + pageId);
      isLaunchWebview && onLaunchWebviewReady();
fxy060608's avatar
fxy060608 已提交
6122
  }
fxy060608's avatar
fxy060608 已提交
6123 6124 6125 6126
  function onLaunchWebviewReady() {
      const { autoclose, alwaysShowBeforeRender } = __uniConfig.splashscreen;
      if (autoclose && !alwaysShowBeforeRender) {
          plus.navigator.closeSplashscreen();
fxy060608's avatar
fxy060608 已提交
6127
      }
fxy060608's avatar
fxy060608 已提交
6128 6129 6130 6131 6132 6133 6134 6135 6136 6137
      const entryPagePath = '/' + __uniConfig.entryPagePath;
      const routeOptions = getRouteOptions(entryPagePath);
      if (!routeOptions.meta.isNVue) {
          // 非 nvue 首页,需要主动跳转
          const args = {
              url: entryPagePath + (__uniConfig.entryPageQuery || ''),
              openType: 'appLaunch',
          };
          if (routeOptions.meta.isTabBar) {
              return uni.switchTab(args);
fxy060608's avatar
fxy060608 已提交
6138
          }
fxy060608's avatar
fxy060608 已提交
6139
          return uni.navigateTo(args);
fxy060608's avatar
fxy060608 已提交
6140
      }
fxy060608's avatar
fxy060608 已提交
6141 6142
  }

fxy060608's avatar
fxy060608 已提交
6143 6144 6145 6146 6147 6148 6149 6150
  function initSubscribeHandlers() {
      const { subscribe, subscribeHandler } = UniServiceJSBridge;
      onPlusMessage('subscribeHandler', ({ type, data, pageId }) => {
          subscribeHandler(type, data, pageId);
      });
      if (__uniConfig.renderer !== 'native') {
          // 非纯原生
          subscribe(ON_WEBVIEW_READY, subscribeWebviewReady);
fxy060608's avatar
fxy060608 已提交
6151
          subscribe(VD_SYNC, onVdSync);
fxy060608's avatar
fxy060608 已提交
6152
      }
fxy060608's avatar
fxy060608 已提交
6153 6154
  }

fxy060608's avatar
fxy060608 已提交
6155 6156 6157 6158 6159 6160 6161 6162
  let appCtx;
  const defaultApp = {
      globalData: {},
  };
  function getApp$1({ allowDefault = false } = {}) {
      if (appCtx) {
          // 真实的 App 已初始化
          return appCtx;
fxy060608's avatar
fxy060608 已提交
6163
      }
fxy060608's avatar
fxy060608 已提交
6164 6165 6166
      if (allowDefault) {
          // 返回默认实现
          return defaultApp;
fxy060608's avatar
fxy060608 已提交
6167
      }
fxy060608's avatar
fxy060608 已提交
6168 6169 6170 6171
      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')) {
fxy060608's avatar
fxy060608 已提交
6172
          console.log(formatLog('registerApp'));
fxy060608's avatar
fxy060608 已提交
6173
      }
fxy060608's avatar
fxy060608 已提交
6174 6175 6176 6177 6178 6179
      appCtx = appVm;
      appCtx.$vm = appVm;
      extend(appCtx, defaultApp); // 拷贝默认实现
      const { $options } = appVm;
      if ($options) {
          appCtx.globalData = extend($options.globalData || {}, appCtx.globalData);
fxy060608's avatar
fxy060608 已提交
6180
      }
fxy060608's avatar
fxy060608 已提交
6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204
      initService();
      initEntry();
      initTabBar();
      initGlobalEvent();
      initSubscribeHandlers();
      initAppLaunch(appVm);
      // 10s后清理临时文件
      setTimeout(clearTempFile, 10000);
      __uniConfig.ready = true;
  }

  var __vuePlugin = {
      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);
fxy060608's avatar
fxy060608 已提交
6205
          }
fxy060608's avatar
fxy060608 已提交
6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218
          return instance;
      };
  }

  const EventType = {
      load: 'load',
      close: 'close',
      error: 'error',
      adClicked: 'adClicked',
  };
  class AdEventHandler {
      constructor() {
          this._callbacks = {};
fxy060608's avatar
fxy060608 已提交
6219
      }
fxy060608's avatar
fxy060608 已提交
6220 6221
      onLoad(callback) {
          this._addEventListener(EventType.load, callback);
fxy060608's avatar
fxy060608 已提交
6222
      }
fxy060608's avatar
fxy060608 已提交
6223 6224
      onClose(callback) {
          this._addEventListener(EventType.close, callback);
fxy060608's avatar
fxy060608 已提交
6225
      }
fxy060608's avatar
fxy060608 已提交
6226 6227
      onError(callback) {
          this._addEventListener(EventType.error, callback);
fxy060608's avatar
fxy060608 已提交
6228
      }
fxy060608's avatar
fxy060608 已提交
6229 6230
      offLoad(callback) {
          this._removeEventListener(EventType.load, callback);
fxy060608's avatar
fxy060608 已提交
6231
      }
fxy060608's avatar
fxy060608 已提交
6232 6233
      offClose(callback) {
          this._removeEventListener(EventType.close, callback);
fxy060608's avatar
fxy060608 已提交
6234
      }
fxy060608's avatar
fxy060608 已提交
6235 6236
      offError(callback) {
          this._removeEventListener(EventType.error, callback);
fxy060608's avatar
fxy060608 已提交
6237
      }
fxy060608's avatar
fxy060608 已提交
6238 6239 6240 6241 6242
      _addEventListener(type, callback) {
          if (typeof callback !== 'function') {
              return;
          }
          this._callbacks[type].push(callback);
fxy060608's avatar
fxy060608 已提交
6243
      }
fxy060608's avatar
fxy060608 已提交
6244 6245 6246 6247 6248
      _removeEventListener(type, callback) {
          const arrayFunction = this._callbacks[type];
          const index = arrayFunction.indexOf(callback);
          if (index > -1) {
              arrayFunction.splice(index, 1);
fxy060608's avatar
fxy060608 已提交
6249 6250
          }
      }
fxy060608's avatar
fxy060608 已提交
6251 6252 6253 6254
      _dispatchEvent(name, data) {
          this._callbacks[name].forEach((callback) => {
              callback(data || {});
          });
fxy060608's avatar
fxy060608 已提交
6255 6256
      }
  }
fxy060608's avatar
fxy060608 已提交
6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311
  class AdBase extends AdEventHandler {
      constructor(adInstance, options) {
          super();
          this._isLoaded = false;
          this._isLoading = false;
          this._preload = true;
          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, {});
              });
fxy060608's avatar
fxy060608 已提交
6312
      }
fxy060608's avatar
fxy060608 已提交
6313 6314 6315 6316 6317 6318 6319 6320 6321
      getProvider() {
          return this._adInstance.getProvider();
      }
      load() {
          return new Promise((resolve, reject) => {
              this._loadPromiseResolve = resolve;
              this._loadPromiseReject = reject;
              if (this._isLoading) {
                  return;
fxy060608's avatar
fxy060608 已提交
6322
              }
fxy060608's avatar
fxy060608 已提交
6323 6324 6325 6326 6327 6328 6329
              if (this._isLoaded) {
                  resolve('');
              }
              else {
                  this._loadAd();
              }
          });
fxy060608's avatar
fxy060608 已提交
6330
      }
fxy060608's avatar
fxy060608 已提交
6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345
      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();
              }
          });
fxy060608's avatar
fxy060608 已提交
6346
      }
fxy060608's avatar
fxy060608 已提交
6347 6348
      destroy() {
          this._adInstance.destroy();
fxy060608's avatar
fxy060608 已提交
6349
      }
fxy060608's avatar
fxy060608 已提交
6350 6351 6352 6353
      _loadAd() {
          this._isLoaded = false;
          this._isLoading = true;
          this._adInstance.load();
fxy060608's avatar
fxy060608 已提交
6354
      }
fxy060608's avatar
fxy060608 已提交
6355 6356
      _showAd() {
          this._adInstance.show();
fxy060608's avatar
fxy060608 已提交
6357 6358 6359
      }
  }

fxy060608's avatar
fxy060608 已提交
6360 6361 6362 6363
  class RewardedVideoAd extends AdBase {
      constructor(options) {
          super(plus.ad.createRewardedVideoAd(options), options);
          this._loadAd();
fxy060608's avatar
fxy060608 已提交
6364
      }
fxy060608's avatar
fxy060608 已提交
6365 6366 6367 6368 6369 6370 6371 6372
  }
  const createRewardedVideoAd = (defineSyncApi(API_CREATE_REWARDED_VIDEO_AD, (options) => {
      return new RewardedVideoAd(options);
  }, CreateRewardedVideoAdProtocol, CreateRewardedVideoAdOptions));

  class FullScreenVideoAd extends AdBase {
      constructor(options) {
          super(plus.ad.createFullScreenVideoAd(options), options);
fxy060608's avatar
fxy060608 已提交
6373
      }
fxy060608's avatar
fxy060608 已提交
6374 6375 6376 6377 6378 6379 6380 6381 6382
  }
  const createFullScreenVideoAd = (defineSyncApi(API_CREATE_FULL_SCREEN_VIDEO_AD, (options) => {
      return new FullScreenVideoAd(options);
  }, CreateFullScreenVideoAdProtocol, CreateFullScreenVideoAdOptions));

  class InterstitialAd extends AdBase {
      constructor(options) {
          super(plus.ad.createInterstitialAd(options), options);
          this._loadAd();
fxy060608's avatar
fxy060608 已提交
6383
      }
fxy060608's avatar
fxy060608 已提交
6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394
  }
  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] = {};
fxy060608's avatar
fxy060608 已提交
6395
      }
fxy060608's avatar
fxy060608 已提交
6396 6397
      if (typeof sdkCache[provider].plugin === 'object') {
          options.success(sdkCache[provider].plugin);
fxy060608's avatar
fxy060608 已提交
6398 6399
          return;
      }
fxy060608's avatar
fxy060608 已提交
6400 6401
      if (!sdkQueue[provider]) {
          sdkQueue[provider] = [];
fxy060608's avatar
fxy060608 已提交
6402
      }
fxy060608's avatar
fxy060608 已提交
6403 6404 6405
      sdkQueue[provider].push(options);
      if (sdkCache[provider].status === true) {
          options.__plugin = sdkCache[provider].plugin;
fxy060608's avatar
fxy060608 已提交
6406 6407
          return;
      }
fxy060608's avatar
fxy060608 已提交
6408 6409 6410 6411 6412 6413 6414 6415
      sdkCache[provider].status = true;
      const plugin = requireNativePlugin(provider);
      if (!plugin || !plugin.initSDK) {
          sdkQueue[provider].forEach((item) => {
              item.fail({
                  code: -1,
                  message: 'provider [' + provider + '] invalid',
              });
fxy060608's avatar
fxy060608 已提交
6416
          });
fxy060608's avatar
fxy060608 已提交
6417 6418 6419
          sdkQueue[provider].length = 0;
          sdkCache[provider].status = false;
          return;
fxy060608's avatar
fxy060608 已提交
6420
      }
fxy060608's avatar
fxy060608 已提交
6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438
      // 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);
              }
fxy060608's avatar
fxy060608 已提交
6439
          });
fxy060608's avatar
fxy060608 已提交
6440 6441
          sdkQueue[provider].length = 0;
      });
fxy060608's avatar
fxy060608 已提交
6442
  }
fxy060608's avatar
fxy060608 已提交
6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462
  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();
          });
fxy060608's avatar
fxy060608 已提交
6463
      }
fxy060608's avatar
fxy060608 已提交
6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483
      _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);
              },
          });
fxy060608's avatar
fxy060608 已提交
6484
      }
fxy060608's avatar
fxy060608 已提交
6485 6486
      getProvider() {
          return this._provider;
fxy060608's avatar
fxy060608 已提交
6487
      }
fxy060608's avatar
fxy060608 已提交
6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504
      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();
              }
fxy060608's avatar
fxy060608 已提交
6505
          });
fxy060608's avatar
fxy060608 已提交
6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524
      }
      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();
              }
fxy060608's avatar
fxy060608 已提交
6525
          });
fxy060608's avatar
fxy060608 已提交
6526 6527 6528 6529
      }
      reportExposure() {
          if (this._adInstance !== null) {
              this._adInstance.reportExposure();
fxy060608's avatar
fxy060608 已提交
6530
          }
fxy060608's avatar
fxy060608 已提交
6531 6532 6533 6534
      }
      bindUserData(data) {
          if (this._adInstance !== null) {
              this._adInstance.bindUserData(data);
fxy060608's avatar
fxy060608 已提交
6535
          }
fxy060608's avatar
fxy060608 已提交
6536 6537 6538 6539 6540
      }
      destroy() {
          if (this._adInstance !== null && this._adInstance.destroy) {
              this._adInstance.destroy({
                  adpid: this._adpid,
fxy060608's avatar
fxy060608 已提交
6541 6542
              });
          }
fxy060608's avatar
fxy060608 已提交
6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572
      }
      _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);
              });
fxy060608's avatar
fxy060608 已提交
6573
          }
fxy060608's avatar
fxy060608 已提交
6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585
      }
      _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;
fxy060608's avatar
fxy060608 已提交
6586
                  }
fxy060608's avatar
fxy060608 已提交
6587
                  this._dispatchEvent(EventType.error, err);
fxy060608's avatar
fxy060608 已提交
6588
              });
fxy060608's avatar
fxy060608 已提交
6589
          }
fxy060608's avatar
fxy060608 已提交
6590
      }
fxy060608's avatar
fxy060608 已提交
6591 6592
      _createError(err) {
          return new Error(JSON.stringify(err));
fxy060608's avatar
fxy060608 已提交
6593
      }
fxy060608's avatar
fxy060608 已提交
6594 6595 6596 6597
  }
  const createInteractiveAd = (defineSyncApi(API_CREATE_INTERACTIVE_AD, (options) => {
      return new InteractiveAd(options);
  }, CreateInteractiveAdProtocol, CreateInteractiveAdOptions));
fxy060608's avatar
fxy060608 已提交
6598

fxy060608's avatar
fxy060608 已提交
6599 6600 6601 6602 6603 6604 6605 6606
  let pendingNavigator = false;
  function setPendingNavigator(path, callback, msg) {
      pendingNavigator = {
          path,
          nvue: getRouteMeta(path).isNVue,
          callback,
      };
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6607
          console.log(formatLog('setPendingNavigator', path, msg));
fxy060608's avatar
fxy060608 已提交
6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627
      }
  }
  function navigate(path, callback, isAppLaunch) {
      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 || (preloadWebview && preloadWebview.__uniapp_route);
      // 已创建未 loaded
      const waitPreloadWebviewReady = preloadWebview && !preloadWebview.loaded;
      if (waitPreloadWebview || waitPreloadWebviewReady) {
          setPendingNavigator(path, callback, waitPreloadWebview ? 'waitForCreate' : 'waitForReady');
fxy060608's avatar
fxy060608 已提交
6628 6629
      }
      else {
fxy060608's avatar
fxy060608 已提交
6630 6631 6632 6633
          callback();
      }
      if (waitPreloadWebviewReady) {
          onWebviewReady(preloadWebview.id, pendingNavigate);
fxy060608's avatar
fxy060608 已提交
6634 6635
      }
  }
fxy060608's avatar
fxy060608 已提交
6636 6637 6638 6639 6640 6641
  function pendingNavigate() {
      if (!pendingNavigator) {
          return;
      }
      const { callback } = pendingNavigator;
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6642
          console.log(formatLog('pendingNavigate', pendingNavigator.path));
fxy060608's avatar
fxy060608 已提交
6643
      }
fxy060608's avatar
fxy060608 已提交
6644 6645
      pendingNavigator = false;
      return callback();
fxy060608's avatar
fxy060608 已提交
6646
  }
fxy060608's avatar
fxy060608 已提交
6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659
  function navigateFinish() {
      if (__uniConfig.renderer === 'native') {
          if (!pendingNavigator) {
              return;
          }
          if (pendingNavigator.nvue) {
              return pendingNavigate();
          }
          return;
      }
      // 创建预加载
      const preloadWebview = createPreloadWebview();
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6660
          console.log(formatLog('navigateFinish', 'preloadWebview', preloadWebview.id));
fxy060608's avatar
fxy060608 已提交
6661 6662 6663 6664 6665 6666 6667 6668 6669 6670
      }
      if (!pendingNavigator) {
          return;
      }
      if (pendingNavigator.nvue) {
          return pendingNavigate();
      }
      preloadWebview.loaded
          ? pendingNavigator.callback()
          : onWebviewReady(preloadWebview.id, pendingNavigate);
fxy060608's avatar
fxy060608 已提交
6671 6672
  }

fxy060608's avatar
fxy060608 已提交
6673 6674 6675 6676 6677
  function showWebview(webview, animationType, animationDuration, showCallback, delay) {
      if (typeof delay === 'undefined') {
          delay = webview.nvue ? 0 : 100;
      }
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6678
          console.log(formatLog('showWebview', 'delay', delay));
fxy060608's avatar
fxy060608 已提交
6679 6680 6681 6682
      }
      const execShowCallback = function () {
          if (execShowCallback._called) {
              if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6683
                  console.log(formatLog('execShowCallback', 'prevent'));
fxy060608's avatar
fxy060608 已提交
6684 6685 6686 6687 6688 6689
              }
              return;
          }
          execShowCallback._called = true;
          showCallback && showCallback();
          navigateFinish();
fxy060608's avatar
fxy060608 已提交
6690
      };
fxy060608's avatar
fxy060608 已提交
6691 6692 6693 6694
      execShowCallback._called = false;
      setTimeout(() => {
          const timer = setTimeout(() => {
              if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6695
                  console.log(formatLog('showWebview', 'callback', 'timer'));
fxy060608's avatar
fxy060608 已提交
6696 6697 6698 6699 6700
              }
              execShowCallback();
          }, animationDuration + 150);
          webview.show(animationType, animationDuration, () => {
              if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6701
                  console.log(formatLog('showWebview', 'callback'));
fxy060608's avatar
fxy060608 已提交
6702 6703 6704
              }
              if (!execShowCallback._called) {
                  clearTimeout(timer);
fxy060608's avatar
fxy060608 已提交
6705
              }
fxy060608's avatar
fxy060608 已提交
6706
              execShowCallback();
fxy060608's avatar
fxy060608 已提交
6707
          });
fxy060608's avatar
fxy060608 已提交
6708
      }, delay);
fxy060608's avatar
fxy060608 已提交
6709 6710
  }

fxy060608's avatar
fxy060608 已提交
6711 6712 6713 6714
  class UniPageNode extends UniNode {
      constructor(pageId, options, setup = false) {
          super(NODE_TYPE_PAGE, '#page', null);
          this._id = 1;
fxy060608's avatar
fxy060608 已提交
6715
          this._created = false;
fxy060608's avatar
fxy060608 已提交
6716 6717 6718 6719 6720 6721
          this.updateActions = [];
          this.nodeId = 0;
          this.pageId = pageId;
          this.pageNode = this;
          this.createAction = [ACTION_TYPE_PAGE_CREATE, options];
          this.createdAction = [ACTION_TYPE_PAGE_CREATED];
fxy060608's avatar
fxy060608 已提交
6722
          this._update = this.update.bind(this);
fxy060608's avatar
fxy060608 已提交
6723 6724 6725 6726 6727 6728
          setup && this.setup();
      }
      onCreate(thisNode, nodeName) {
          pushCreateAction(this, thisNode.nodeId, nodeName);
          return thisNode;
      }
fxy060608's avatar
fxy060608 已提交
6729 6730
      onInsertBefore(thisNode, newChild, refChild) {
          pushInsertAction(this, newChild, thisNode.nodeId, (refChild && refChild.nodeId) || -1);
fxy060608's avatar
fxy060608 已提交
6731 6732
          return newChild;
      }
fxy060608's avatar
fxy060608 已提交
6733 6734
      onRemoveChild(oldChild) {
          pushRemoveAction(this, oldChild.nodeId);
fxy060608's avatar
fxy060608 已提交
6735 6736 6737 6738 6739
          return oldChild;
      }
      onSetAttribute(thisNode, qualifiedName, value) {
          if (thisNode.parentNode) {
              pushSetAttributeAction(this, thisNode.nodeId, qualifiedName, value);
fxy060608's avatar
fxy060608 已提交
6740
          }
fxy060608's avatar
fxy060608 已提交
6741
      }
fxy060608's avatar
fxy060608 已提交
6742 6743 6744 6745
      onRemoveAttribute(thisNode, qualifiedName) {
          if (thisNode.parentNode) {
              pushRemoveAttributeAction(this, thisNode.nodeId, qualifiedName);
          }
fxy060608's avatar
fxy060608 已提交
6746
      }
fxy060608's avatar
fxy060608 已提交
6747 6748 6749 6750
      onTextContent(thisNode, text) {
          if (thisNode.parentNode) {
              pushSetTextAction(this, thisNode.nodeId, text);
          }
fxy060608's avatar
fxy060608 已提交
6751
      }
fxy060608's avatar
fxy060608 已提交
6752 6753 6754 6755
      onNodeValue(thisNode, val) {
          if (thisNode.parentNode) {
              pushSetTextAction(this, thisNode.nodeId, val);
          }
fxy060608's avatar
fxy060608 已提交
6756
      }
fxy060608's avatar
fxy060608 已提交
6757 6758
      genId() {
          return this._id++;
fxy060608's avatar
fxy060608 已提交
6759
      }
fxy060608's avatar
fxy060608 已提交
6760 6761
      push(action) {
          this.updateActions.push(action);
fxy060608's avatar
fxy060608 已提交
6762 6763 6764 6765
          if ((process.env.NODE_ENV !== 'production')) {
              console.log(formatLog('PageNode', 'push', action));
          }
          vue.queuePostFlushCb(this._update);
fxy060608's avatar
fxy060608 已提交
6766 6767 6768 6769 6770 6771 6772 6773 6774
      }
      restore() {
          this.push(this.createAction);
          // TODO restore children
          this.push(this.createdAction);
      }
      setup() {
          this.send([this.createAction]);
      }
fxy060608's avatar
fxy060608 已提交
6775 6776 6777 6778 6779
      // mounted() {
      //   const { updateActions, createdAction } = this
      //   updateActions.unshift(createdAction)
      //   this.update()
      // }
fxy060608's avatar
fxy060608 已提交
6780 6781
      update() {
          const { updateActions } = this;
fxy060608's avatar
fxy060608 已提交
6782 6783 6784
          if ((process.env.NODE_ENV !== 'production')) {
              console.log(formatLog('PageNode', 'update', updateActions.length));
          }
fxy060608's avatar
fxy060608 已提交
6785 6786 6787 6788 6789
          // 首次
          if (!this._created) {
              this._created = true;
              updateActions.push(this.createdAction);
          }
fxy060608's avatar
fxy060608 已提交
6790 6791 6792
          if (updateActions.length) {
              this.send(updateActions);
              updateActions.length = 0;
fxy060608's avatar
fxy060608 已提交
6793
          }
fxy060608's avatar
fxy060608 已提交
6794
      }
fxy060608's avatar
fxy060608 已提交
6795
      send(action) {
fxy060608's avatar
fxy060608 已提交
6796
          UniServiceJSBridge.publishHandler(VD_SYNC, action, this.pageId);
fxy060608's avatar
fxy060608 已提交
6797
      }
fxy060608's avatar
fxy060608 已提交
6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819
      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 findNodeById(id, uniNode) {
      if (uniNode.nodeId === id) {
          return uniNode;
      }
      const { childNodes } = uniNode;
      for (let i = 0; i < childNodes.length; i++) {
          const uniNode = findNodeById(id, childNodes[i]);
          if (uniNode) {
              return uniNode;
          }
      }
      return null;
fxy060608's avatar
fxy060608 已提交
6820 6821 6822 6823
  }
  function pushCreateAction(pageNode, nodeId, nodeName) {
      pageNode.push([ACTION_TYPE_CREATE, nodeId, nodeName]);
  }
fxy060608's avatar
fxy060608 已提交
6824
  function pushInsertAction(pageNode, newChild, parentNodeId, refChildId) {
fxy060608's avatar
fxy060608 已提交
6825 6826 6827 6828
      pageNode.push([
          ACTION_TYPE_INSERT,
          newChild.nodeId,
          parentNodeId,
fxy060608's avatar
fxy060608 已提交
6829
          refChildId,
fxy060608's avatar
fxy060608 已提交
6830 6831 6832
          newChild.toJSON({ attr: true }),
      ]);
  }
fxy060608's avatar
fxy060608 已提交
6833 6834
  function pushRemoveAction(pageNode, nodeId) {
      pageNode.push([ACTION_TYPE_REMOVE, nodeId]);
fxy060608's avatar
fxy060608 已提交
6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846
  }
  function pushSetAttributeAction(pageNode, nodeId, name, value) {
      pageNode.push([ACTION_TYPE_SET_ATTRIBUTE, nodeId, name, value]);
  }
  function pushRemoveAttributeAction(pageNode, nodeId, name) {
      pageNode.push([ACTION_TYPE_REMOVE_ATTRIBUTE, nodeId, name]);
  }
  function pushSetTextAction(pageNode, nodeId, text) {
      pageNode.push([ACTION_TYPE_SET_TEXT, nodeId, text]);
  }
  function createPageNode(pageId, pageOptions, setup) {
      return new UniPageNode(pageId, pageOptions, setup);
fxy060608's avatar
fxy060608 已提交
6847 6848
  }

fxy060608's avatar
fxy060608 已提交
6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865
  const pages = [];
  function addCurrentPage(page) {
      pages.push(page);
  }
  function getCurrentPages$1() {
      const curPages = [];
      pages.forEach((page) => {
          if (page.__isTabBar) {
              if (page.$.__isActive) {
                  curPages.push(page);
              }
          }
          else {
              curPages.push(page);
          }
      });
      return curPages;
fxy060608's avatar
fxy060608 已提交
6866 6867
  }

fxy060608's avatar
fxy060608 已提交
6868 6869 6870 6871
  function setupPage(component, { pageId, pagePath, pageQuery, pageInstance }) {
      const oldSetup = component.setup;
      component.setup = (_props, ctx) => {
          if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6872
              console.log(formatLog(pagePath, 'setup'));
fxy060608's avatar
fxy060608 已提交
6873 6874 6875 6876 6877 6878 6879
          }
          const instance = vue.getCurrentInstance();
          const pageVm = instance.proxy;
          pageVm.$page = pageInstance;
          addCurrentPage(initScope(pageId, pageVm));
          if (oldSetup) {
              return oldSetup(pageQuery, ctx);
fxy060608's avatar
fxy060608 已提交
6880 6881
          }
      };
fxy060608's avatar
fxy060608 已提交
6882 6883 6884 6885 6886 6887 6888 6889 6890
      return component;
  }
  function initScope(pageId, vm) {
      vm.$scope = {
          $getAppWebview() {
              return plus.webview.getWebviewById(String(pageId));
          },
      };
      return vm;
fxy060608's avatar
fxy060608 已提交
6891 6892
  }

fxy060608's avatar
fxy060608 已提交
6893 6894 6895 6896 6897
  const pagesMap = new Map();
  function definePage(pagePath, component) {
      pagesMap.set(pagePath, once(createFactory(component)));
  }
  function createPage(pageId, pagePath, pageQuery, pageInstance, pageOptions) {
fxy060608's avatar
fxy060608 已提交
6898 6899
      return vue.createApp(pagesMap.get(pagePath)({
          pageId,
fxy060608's avatar
fxy060608 已提交
6900 6901 6902
          pagePath,
          pageQuery,
          pageInstance,
fxy060608's avatar
fxy060608 已提交
6903
      }))
fxy060608's avatar
fxy060608 已提交
6904
          .use(__vuePlugin)
fxy060608's avatar
fxy060608 已提交
6905
          .mount(createPageNode(pageId, pageOptions, true));
fxy060608's avatar
fxy060608 已提交
6906 6907
  }
  function createFactory(component) {
fxy060608's avatar
fxy060608 已提交
6908 6909
      return (props) => {
          return setupPage(component, props);
fxy060608's avatar
fxy060608 已提交
6910 6911 6912
      };
  }

fxy060608's avatar
fxy060608 已提交
6913 6914
  function initRouteOptions(path, openType) {
      // 需要序列化一遍
fxy060608's avatar
fxy060608 已提交
6915
      const routeOptions = JSON.parse(JSON.stringify(getRouteOptions(path)));
fxy060608's avatar
fxy060608 已提交
6916
      routeOptions.meta = initRouteMeta(routeOptions.meta);
fxy060608's avatar
fxy060608 已提交
6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931
      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;
  }

fxy060608's avatar
fxy060608 已提交
6932 6933 6934 6935 6936 6937 6938 6939 6940
  function getStatusbarHeight() {
      // 横屏时 iOS 获取的状态栏高度错误,进行纠正
      return plus.navigator.isImmersedStatusbar()
          ? Math.round(plus.os.name === 'iOS'
              ? plus.navigator.getSafeAreaInsets().top
              : plus.navigator.getStatusbarHeight())
          : 0;
  }

fxy060608's avatar
fxy060608 已提交
6941
  function registerPage({ url, path, query, openType, webview, vm, }) {
fxy060608's avatar
fxy060608 已提交
6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954
      // fast 模式,nvue 首页时,会在nvue中主动调用registerPage并传入首页webview,此时初始化一下首页(因为此时可能还未调用registerApp)
      if (webview) {
          initEntry();
      }
      // TODO preloadWebview
      const routeOptions = initRouteOptions(path, openType);
      if (!webview) {
          webview = createWebview({ path, routeOptions, query });
      }
      else {
          webview = plus.webview.getWebviewById(webview.id);
          webview.nvue = routeOptions.meta.isNVue;
      }
fxy060608's avatar
fxy060608 已提交
6955
      routeOptions.meta.id = parseInt(webview.id);
fxy060608's avatar
fxy060608 已提交
6956 6957 6958 6959
      const isTabBar = !!routeOptions.meta.isTabBar;
      if (isTabBar) {
          tabBar$1.append(webview);
      }
fxy060608's avatar
fxy060608 已提交
6960
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6961
          console.log(formatLog('registerPage', path, webview.id));
fxy060608's avatar
fxy060608 已提交
6962
      }
fxy060608's avatar
fxy060608 已提交
6963
      initWebview(webview, path, query, routeOptions.meta);
fxy060608's avatar
fxy060608 已提交
6964
      const route = path.substr(1);
fxy060608's avatar
fxy060608 已提交
6965
      webview.__uniapp_route = route;
fxy060608's avatar
fxy060608 已提交
6966
      const pageInstance = initPageInternalInstance(url, query, routeOptions.meta);
fxy060608's avatar
fxy060608 已提交
6967
      if (!webview.nvue) {
fxy060608's avatar
fxy060608 已提交
6968 6969 6970 6971
          createPage(parseInt(webview.id), route, query, pageInstance, initPageOptions(routeOptions));
      }
      else {
          vm && addCurrentPage(vm);
fxy060608's avatar
fxy060608 已提交
6972
      }
fxy060608's avatar
fxy060608 已提交
6973
      return webview;
fxy060608's avatar
fxy060608 已提交
6974 6975 6976 6977
  }
  function initPageOptions({ meta }) {
      const statusbarHeight = getStatusbarHeight();
      return {
fxy060608's avatar
fxy060608 已提交
6978
          css: true,
fxy060608's avatar
fxy060608 已提交
6979
          route: meta.route,
fxy060608's avatar
fxy060608 已提交
6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991
          version: 1,
          locale: '',
          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,
      };
fxy060608's avatar
fxy060608 已提交
6992
  }
fxy060608's avatar
fxy060608 已提交
6993

fxy060608's avatar
fxy060608 已提交
6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032
  const navigateTo = defineAsyncApi(API_NAVIGATE_TO, (args, { resolve, reject }) => {
      const { url, animationType, animationDuration } = args;
      const { path, query } = parseUrl(url);
      const [aniType, aniDuration] = initAnimation(path, animationType, animationDuration);
      navigate(path, () => {
          _navigateTo({
              url,
              path,
              query,
              aniType,
              aniDuration,
          })
              .then(resolve)
              .catch(reject);
      }, args.openType === 'appLaunch');
  }, NavigateToProtocol, NavigateToOptions);
  function _navigateTo({ url, path, query, aniType, aniDuration, }) {
      // TODO eventChannel
      return new Promise((resolve) => {
          showWebview(registerPage({ url, path, query, openType: 'navigateTo' }), aniType, aniDuration, () => {
              resolve(undefined);
          });
      });
  }
  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,
      ];
  }

fxy060608's avatar
fxy060608 已提交
7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057
  const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, (args, { resolve, reject }) => {
      const page = getCurrentPage();
      if (!page) {
          return;
      }
      if (page.$page.meta.isQuit) {
          quit();
      }
      return resolve();
  });
  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();
      }
  }

fxy060608's avatar
fxy060608 已提交
7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107
  var uni$1 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    setStorageSync: setStorageSync,
    setStorage: setStorage,
    getStorageSync: getStorageSync,
    getStorage: getStorage,
    removeStorageSync: removeStorageSync,
    removeStorage: removeStorage,
    clearStorageSync: clearStorageSync,
    clearStorage: clearStorage,
    getStorageInfoSync: getStorageInfoSync,
    getStorageInfo: getStorageInfo,
    getFileInfo: getFileInfo,
    openDocument: openDocument,
    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,
7108
    addPhoneContact: addPhoneContact,
fxy060608's avatar
fxy060608 已提交
7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152
    getClipboardData: getClipboardData,
    setClipboardData: setClipboardData,
    onNetworkStatusChange: onNetworkStatusChange,
    offNetworkStatusChange: offNetworkStatusChange,
    getNetworkType: getNetworkType,
    checkIsSupportSoterAuthentication: checkIsSupportSoterAuthentication,
    checkIsSoterEnrolledInDevice: checkIsSoterEnrolledInDevice,
    startSoterAuthentication: startSoterAuthentication,
    getImageInfo: getImageInfo,
    getVideoInfo: getVideoInfo,
    previewImage: previewImage,
    getRecorderManager: getRecorderManager,
    saveVideoToPhotosAlbum: saveVideoToPhotosAlbum,
    saveImageToPhotosAlbum: saveImageToPhotosAlbum,
    compressImage: compressImage,
    compressVideo: compressVideo,
    showKeyboard: showKeyboard,
    hideKeyboard: hideKeyboard,
    downloadFile: downloadFile,
    request: request,
    createSocketTask: createSocketTask,
    connectSocket: connectSocket,
    sendSocketMessage: sendSocketMessage,
    closeSocket: closeSocket,
    onSocketOpen: onSocketOpen,
    onSocketError: onSocketError,
    onSocketMessage: onSocketMessage,
    onSocketClose: onSocketClose,
    createInnerAudioContext: createInnerAudioContext,
    getBackgroundAudioManager: getBackgroundAudioManager,
    getLocation: getLocation,
    showModal: showModal,
    showActionSheet: showActionSheet,
    showLoading: showLoading,
    hideLoading: hideLoading,
    showToast: showToast,
    hideToast: hideToast,
    hide: hide,
    getProvider: getProvider,
    login: login,
    getUserInfo: getUserInfo,
    getUserProfile: getUserProfile,
    preLogin: preLogin,
    closeAuthView: closeAuthView,
fxy060608's avatar
fxy060608 已提交
7153
    registerRuntime: registerRuntime,
fxy060608's avatar
fxy060608 已提交
7154 7155 7156
    share: share,
    shareWithSystem: shareWithSystem,
    requestPayment: requestPayment,
fxy060608's avatar
fxy060608 已提交
7157
    __vuePlugin: __vuePlugin,
fxy060608's avatar
fxy060608 已提交
7158 7159 7160 7161
    createRewardedVideoAd: createRewardedVideoAd,
    createFullScreenVideoAd: createFullScreenVideoAd,
    createInterstitialAd: createInterstitialAd,
    createInteractiveAd: createInteractiveAd,
fxy060608's avatar
fxy060608 已提交
7162 7163
    navigateTo: navigateTo,
    navigateBack: navigateBack
fxy060608's avatar
fxy060608 已提交
7164 7165 7166 7167 7168 7169 7170 7171
  });

  const UniServiceJSBridge$1 = /*#__PURE__*/ extend(ServiceJSBridge, {
      publishHandler,
  });
  function publishHandler(event, args, pageIds) {
      args = JSON.stringify(args);
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
7172
          console.log(formatLog('publishHandler', event, args, pageIds));
fxy060608's avatar
fxy060608 已提交
7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184
      }
      if (!isArray(pageIds)) {
          pageIds = [pageIds];
      }
      const evalJSCode = `typeof UniViewJSBridge !== 'undefined' && UniViewJSBridge.subscribeHandler("${event}",${args},__PAGE_ID__)`;
      pageIds.forEach((id) => {
          const idStr = String(id);
          const webview = plus.webview.getWebviewById(idStr);
          webview && webview.evalJS(evalJSCode.replace('__PAGE_ID__', idStr));
      });
  }

fxy060608's avatar
fxy060608 已提交
7185 7186
  var index = {
      uni: uni$1,
fxy060608's avatar
fxy060608 已提交
7187 7188
      getApp: getApp$1,
      getCurrentPages: getCurrentPages$1,
fxy060608's avatar
fxy060608 已提交
7189
      __definePage: definePage,
fxy060608's avatar
fxy060608 已提交
7190 7191
      __registerApp: registerApp,
      __registerPage: registerPage,
fxy060608's avatar
fxy060608 已提交
7192
      UniServiceJSBridge: UniServiceJSBridge$1,
fxy060608's avatar
fxy060608 已提交
7193
  };
fxy060608's avatar
fxy060608 已提交
7194

fxy060608's avatar
fxy060608 已提交
7195
  return index;
fxy060608's avatar
fxy060608 已提交
7196

fxy060608's avatar
fxy060608 已提交
7197
}(Vue));
fxy060608's avatar
fxy060608 已提交
7198 7199 7200
const uni = serviceContext.uni;
const getApp = serviceContext.getApp;
const getCurrentPages = serviceContext.getCurrentPages;
fxy060608's avatar
fxy060608 已提交
7201
const UniServiceJSBridge = serviceContext.UniServiceJSBridge;
fxy060608's avatar
fxy060608 已提交
7202 7203
return serviceContext;
}