uni-app-service.es.js 261.7 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
  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));
      });
  };
fxy060608's avatar
fxy060608 已提交
127 128 129 130 131 132 133 134 135 136 137 138
  const camelizeRE = /-(\w)/g;
  /**
   * @private
   */
  const camelize = cacheStringFunction$1((str) => {
      return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  });
  const hyphenateRE = /\B([A-Z])/g;
  /**
   * @private
   */
  const hyphenate = cacheStringFunction$1((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
fxy060608's avatar
fxy060608 已提交
139 140 141
  /**
   * @private
   */
fxy060608's avatar
fxy060608 已提交
142
  const capitalize = cacheStringFunction$1((str) => str.charAt(0).toUpperCase() + str.slice(1));
fxy060608's avatar
fxy060608 已提交
143

fxy060608's avatar
fxy060608 已提交
144 145
  const CHOOSE_SIZE_TYPES = ['original', 'compressed'];
  const CHOOSE_SOURCE_TYPES = ['album', 'camera'];
fxy060608's avatar
fxy060608 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
  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;
  }
fxy060608's avatar
fxy060608 已提交
162 163 164 165 166 167 168 169
  function elemsInArray(strArr, optionalVal) {
      if (!isArray(strArr) ||
          strArr.length === 0 ||
          strArr.find((val) => optionalVal.indexOf(val) === -1)) {
          return optionalVal;
      }
      return strArr;
  }
fxy060608's avatar
fxy060608 已提交
170 171 172 173 174 175 176 177
  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 已提交
178
          const errMsg = validateProp(key, data[key], protocol[key], !hasOwn$1(data, key));
fxy060608's avatar
fxy060608 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
          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 已提交
202
  function validateProp(name, value, prop, isAbsent) {
fxy060608's avatar
fxy060608 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
      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 已提交
222
              const { valid, expectedType } = assertType(value, types[i]);
fxy060608's avatar
fxy060608 已提交
223 224 225 226
              expectedTypes.push(expectedType || '');
              isValid = valid;
          }
          if (!isValid) {
fxy060608's avatar
fxy060608 已提交
227
              return getInvalidTypeMessage(name, value, expectedTypes);
fxy060608's avatar
fxy060608 已提交
228 229 230 231 232 233 234
          }
      }
      // custom validator
      if (validator) {
          return validator(value);
      }
  }
fxy060608's avatar
fxy060608 已提交
235 236
  const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol');
  function assertType(value, type) {
fxy060608's avatar
fxy060608 已提交
237
      let valid;
fxy060608's avatar
fxy060608 已提交
238 239
      const expectedType = getType(type);
      if (isSimpleType(expectedType)) {
fxy060608's avatar
fxy060608 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
          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 {
          {
fxy060608's avatar
fxy060608 已提交
255 256
              // App平台ArrayBuffer等参数跨实例传输,无法通过 instanceof 识别
              valid = value instanceof type || toRawType(value) === getType(type);
fxy060608's avatar
fxy060608 已提交
257 258 259 260 261 262 263
          }
      }
      return {
          valid,
          expectedType,
      };
  }
fxy060608's avatar
fxy060608 已提交
264
  function getInvalidTypeMessage(name, value, expectedTypes) {
fxy060608's avatar
fxy060608 已提交
265 266 267 268
      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 已提交
269 270
      const expectedValue = styleValue(value, expectedType);
      const receivedValue = styleValue(value, receivedType);
fxy060608's avatar
fxy060608 已提交
271 272
      // check if we need to specify expected value
      if (expectedTypes.length === 1 &&
fxy060608's avatar
fxy060608 已提交
273 274
          isExplicable(expectedType) &&
          !isBoolean(expectedType, receivedType)) {
fxy060608's avatar
fxy060608 已提交
275 276 277 278
          message += ` with value ${expectedValue}`;
      }
      message += `, got ${receivedType} `;
      // check if we need to specify received value
fxy060608's avatar
fxy060608 已提交
279
      if (isExplicable(receivedType)) {
fxy060608's avatar
fxy060608 已提交
280 281 282 283
          message += `with value ${receivedValue}.`;
      }
      return message;
  }
fxy060608's avatar
fxy060608 已提交
284
  function getType(ctor) {
fxy060608's avatar
fxy060608 已提交
285 286 287
      const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
      return match ? match[1] : '';
  }
fxy060608's avatar
fxy060608 已提交
288
  function styleValue(value, type) {
fxy060608's avatar
fxy060608 已提交
289 290 291 292 293 294 295 296 297 298
      if (type === 'String') {
          return `"${value}"`;
      }
      else if (type === 'Number') {
          return `${Number(value)}`;
      }
      else {
          return `${value}`;
      }
  }
fxy060608's avatar
fxy060608 已提交
299
  function isExplicable(type) {
fxy060608's avatar
fxy060608 已提交
300 301 302
      const explicitTypes = ['string', 'number', 'boolean'];
      return explicitTypes.some((elem) => type.toLowerCase() === elem);
  }
fxy060608's avatar
fxy060608 已提交
303
  function isBoolean(...args) {
fxy060608's avatar
fxy060608 已提交
304 305
      return args.some((elem) => elem.toLowerCase() === 'boolean');
  }
fxy060608's avatar
fxy060608 已提交
306

fxy060608's avatar
fxy060608 已提交
307 308 309 310 311 312 313 314 315 316 317
  function tryCatch(fn) {
      return function () {
          try {
              return fn.apply(fn, arguments);
          }
          catch (e) {
              // TODO
              console.error(e);
          }
      };
  }
fxy060608's avatar
fxy060608 已提交
318

fxy060608's avatar
fxy060608 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
  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 已提交
350 351 352 353 354 355 356 357 358 359 360
  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 已提交
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
  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;
  }
fxy060608's avatar
fxy060608 已提交
388
  function normalizeErrMsg$1(errMsg, name) {
fxy060608's avatar
fxy060608 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
      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 || {};
fxy060608's avatar
fxy060608 已提交
405
          res.errMsg = normalizeErrMsg$1(res.errMsg, name);
fxy060608's avatar
fxy060608 已提交
406 407 408 409 410 411 412 413 414 415 416 417
          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 已提交
418

fxy060608's avatar
fxy060608 已提交
419 420
  function hasCallback(args) {
      if (isPlainObject(args) &&
fxy060608's avatar
fxy060608 已提交
421
          [API_SUCCESS, API_FAIL, API_COMPLETE].find((cb) => isFunction(args[cb]))) {
fxy060608's avatar
fxy060608 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
          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 已提交
439

fxy060608's avatar
fxy060608 已提交
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 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
  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 已提交
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
  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 已提交
524 525 526 527 528 529 530
  function normalizeErrMsg(errMsg) {
      if (errMsg instanceof Error) {
          console.error(errMsg);
          return errMsg.message;
      }
      return errMsg;
  }
fxy060608's avatar
fxy060608 已提交
531 532 533 534 535 536 537 538 539
  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),
fxy060608's avatar
fxy060608 已提交
540
              reject: (errMsg, errRes) => invokeFail(id, name, normalizeErrMsg(errMsg), errRes),
fxy060608's avatar
fxy060608 已提交
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
          });
      };
  }
  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 已提交
559 560 561
  function defineOffApi(name, fn, options) {
      return wrapperOffApi(name, fn, options);
  }
fxy060608's avatar
fxy060608 已提交
562 563 564 565 566 567 568 569 570
  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 已提交
571

fxy060608's avatar
fxy060608 已提交
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
  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 已提交
591
      return decode$1(base64);
fxy060608's avatar
fxy060608 已提交
592 593 594 595 596
  }, Base64ToArrayBufferProtocol);
  const arrayBufferToBase64 = defineSyncApi(API_ARRAY_BUFFER_TO_BASE64, (arrayBuffer) => {
      return encode$3(arrayBuffer);
  }, ArrayBufferToBase64Protocol);

fxy060608's avatar
fxy060608 已提交
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
  /**
   * 简易版systemInfo,主要为upx2px,i18n服务
   * @returns
   */
  function getBaseSystemInfo() {
      // @ts-expect-error view 层
      if (typeof __SYSTEM_INFO__ !== 'undefined') {
          return window.__SYSTEM_INFO__;
      }
      const { resolutionWidth } = plus.screen.getCurrentSize();
      return {
          platform: (plus.os.name || '').toLowerCase(),
          pixelRatio: plus.screen.scale,
          windowWidth: Math.round(resolutionWidth),
      };
  }

fxy060608's avatar
fxy060608 已提交
614 615 616 617 618 619
  function formatLog(module, ...args) {
      return `[${Date.now()}][${module}]:${args
        .map((arg) => JSON.stringify(arg))
        .join(' ')}`;
  }

fxy060608's avatar
fxy060608 已提交
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
  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 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 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
  /**
   * 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 已提交
695
          query: parseQuery(querystring || ''),
fxy060608's avatar
fxy060608 已提交
696 697
      };
  }
fxy060608's avatar
fxy060608 已提交
698

fxy060608's avatar
fxy060608 已提交
699 700 701 702 703 704
  class DOMException extends Error {
      constructor(message) {
          super(message);
          this.name = 'DOMException';
      }
  }
fxy060608's avatar
fxy060608 已提交
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

  function normalizeEventType(type, options) {
      if (options) {
          if (options.capture) {
              type += 'Capture';
          }
          if (options.once) {
              type += 'Once';
          }
          if (options.passive) {
              type += 'Passive';
          }
      }
      return `on${capitalize(camelize(type))}`;
  }
  class UniEvent {
      constructor(type, opts) {
          this.defaultPrevented = false;
          this.timeStamp = Date.now();
          this._stop = false;
          this._end = false;
          this.type = type;
          this.bubbles = !!opts.bubbles;
          this.cancelable = !!opts.cancelable;
      }
      preventDefault() {
          this.defaultPrevented = true;
      }
      stopImmediatePropagation() {
          this._end = this._stop = true;
      }
      stopPropagation() {
          this._stop = true;
      }
  }
  function createUniEvent(evt) {
      if (evt instanceof UniEvent) {
          return evt;
      }
      const [type] = parseEventName(evt.type);
      const uniEvent = new UniEvent(type, {
          bubbles: false,
          cancelable: false,
      });
      extend(uniEvent, evt);
      return uniEvent;
  }
fxy060608's avatar
fxy060608 已提交
752 753
  class UniEventTarget {
      constructor() {
fxy060608's avatar
fxy060608 已提交
754
          this.listeners = Object.create(null);
fxy060608's avatar
fxy060608 已提交
755 756
      }
      dispatchEvent(evt) {
fxy060608's avatar
fxy060608 已提交
757
          const listeners = this.listeners[evt.type];
fxy060608's avatar
fxy060608 已提交
758
          if (!listeners) {
fxy060608's avatar
fxy060608 已提交
759 760 761
              if ((process.env.NODE_ENV !== 'production')) {
                  console.error(formatLog('dispatchEvent', this.nodeId), evt.type, 'not found');
              }
fxy060608's avatar
fxy060608 已提交
762 763
              return false;
          }
fxy060608's avatar
fxy060608 已提交
764 765
          // 格式化事件类型
          const event = createUniEvent(evt);
fxy060608's avatar
fxy060608 已提交
766 767
          const len = listeners.length;
          for (let i = 0; i < len; i++) {
fxy060608's avatar
fxy060608 已提交
768 769
              listeners[i].call(this, event);
              if (event._end) {
fxy060608's avatar
fxy060608 已提交
770 771 772
                  break;
              }
          }
fxy060608's avatar
fxy060608 已提交
773
          return event.cancelable && event.defaultPrevented;
fxy060608's avatar
fxy060608 已提交
774 775
      }
      addEventListener(type, listener, options) {
fxy060608's avatar
fxy060608 已提交
776
          type = normalizeEventType(type, options);
fxy060608's avatar
fxy060608 已提交
777
          (this.listeners[type] || (this.listeners[type] = [])).push(listener);
fxy060608's avatar
fxy060608 已提交
778 779
      }
      removeEventListener(type, callback, options) {
fxy060608's avatar
fxy060608 已提交
780
          type = normalizeEventType(type, options);
fxy060608's avatar
fxy060608 已提交
781
          const listeners = this.listeners[type];
fxy060608's avatar
fxy060608 已提交
782 783 784 785 786 787 788 789
          if (!listeners) {
              return;
          }
          const index = listeners.indexOf(callback);
          if (index > -1) {
              listeners.splice(index, 1);
          }
      }
fxy060608's avatar
fxy060608 已提交
790
  }
fxy060608's avatar
fxy060608 已提交
791 792 793 794 795 796 797 798 799 800 801 802 803
  const optionsModifierRE = /(?:Once|Passive|Capture)$/;
  function parseEventName(name) {
      let options;
      if (optionsModifierRE.test(name)) {
          options = {};
          let m;
          while ((m = name.match(optionsModifierRE))) {
              name = name.slice(0, name.length - m[0].length);
              options[m[0].toLowerCase()] = true;
          }
      }
      return [hyphenate(name.slice(2)), options];
  }
fxy060608's avatar
fxy060608 已提交
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 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
  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 已提交
870
      if (!node.nodeId && node.pageNode) {
fxy060608's avatar
fxy060608 已提交
871 872 873 874 875 876 877 878 879 880 881 882
          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 已提交
883 884 885
              if (pageNode) {
                  this.pageNode = pageNode;
                  this.nodeId = pageNode.genId();
fxy060608's avatar
fxy060608 已提交
886
                  !pageNode.isUnmounted && pageNode.onCreate(this, encodeTag(nodeName));
fxy060608's avatar
fxy060608 已提交
887
              }
fxy060608's avatar
fxy060608 已提交
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
          }
          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;
fxy060608's avatar
fxy060608 已提交
913
          if (this.pageNode && !this.pageNode.isUnmounted) {
fxy060608's avatar
fxy060608 已提交
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
              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 已提交
948
              const index = childNodes.indexOf(refChild);
fxy060608's avatar
fxy060608 已提交
949 950 951 952 953 954 955 956
              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);
          }
fxy060608's avatar
fxy060608 已提交
957
          return this.pageNode && !this.pageNode.isUnmounted
fxy060608's avatar
fxy060608 已提交
958
              ? this.pageNode.onInsertBefore(this, newChild, refChild)
fxy060608's avatar
fxy060608 已提交
959 960 961 962 963 964 965 966 967 968
              : 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 已提交
969 970 971
          return this.pageNode && !this.pageNode.isUnmounted
              ? this.pageNode.onRemoveChild(oldChild)
              : oldChild;
fxy060608's avatar
fxy060608 已提交
972 973 974 975
      }
  }

  function cache(fn) {
fxy060608's avatar
fxy060608 已提交
976
      const cache = Object.create(null);
fxy060608's avatar
fxy060608 已提交
977
      return (str) => {
fxy060608's avatar
fxy060608 已提交
978 979
          const hit = cache[str];
          return hit || (cache[str] = fn(str));
fxy060608's avatar
fxy060608 已提交
980 981 982 983 984
      };
  }
  function cacheStringFunction(fn) {
      return cache(fn);
  }
fxy060608's avatar
fxy060608 已提交
985 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
  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 已提交
1024
  const NAVBAR_HEIGHT = 44;
fxy060608's avatar
fxy060608 已提交
1025
  const TABBAR_HEIGHT = 50;
fxy060608's avatar
fxy060608 已提交
1026
  const ON_REACH_BOTTOM_DISTANCE = 50;
fxy060608's avatar
fxy060608 已提交
1027 1028 1029
  const PRIMARY_COLOR = '#007aff';
  const BACKGROUND_COLOR = '#f7f7f7'; // 背景色,如标题栏默认背景色
  const SCHEME_RE = /^([a-z-]+:)?\/\//i;
fxy060608's avatar
fxy060608 已提交
1030
  const DATA_RE = /^data:.*,.*/;
fxy060608's avatar
fxy060608 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045

  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 已提交
1046
          return compile(tokens, values);
fxy060608's avatar
fxy060608 已提交
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
      }
  }
  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 已提交
1089
  function compile(tokens, values) {
fxy060608's avatar
fxy060608 已提交
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 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
      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 已提交
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
              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 已提交
1316 1317
  }

fxy060608's avatar
fxy060608 已提交
1318 1319 1320 1321 1322
  let i18n;
  function useI18n() {
      if (!i18n) {
          let language;
          {
fxy060608's avatar
fxy060608 已提交
1323 1324
              // TODO 需替换为新API
              language = plus.os.language;
fxy060608's avatar
fxy060608 已提交
1325
          }
fxy060608's avatar
fxy060608 已提交
1326
          i18n = initVueI18n(language);
fxy060608's avatar
fxy060608 已提交
1327
      }
fxy060608's avatar
fxy060608 已提交
1328
      return i18n;
fxy060608's avatar
fxy060608 已提交
1329 1330
  }

fxy060608's avatar
fxy060608 已提交
1331 1332 1333 1334 1335 1336 1337
  // 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 已提交
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
  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 已提交
1358 1359 1360 1361
  const initI18nShowActionSheetMsgsOnce = /*#__PURE__*/ once(() => {
      const name = 'uni.showActionSheet.';
      {
          useI18n().add(LOCALE_EN, normalizeMessages(name, { cancel: 'Cancel' }));
fxy060608's avatar
fxy060608 已提交
1362
      }
fxy060608's avatar
fxy060608 已提交
1363 1364
      {
          useI18n().add(LOCALE_ES, normalizeMessages(name, { cancel: 'Cancelar' }));
fxy060608's avatar
fxy060608 已提交
1365
      }
fxy060608's avatar
fxy060608 已提交
1366 1367
      {
          useI18n().add(LOCALE_FR, normalizeMessages(name, { cancel: 'Annuler' }));
fxy060608's avatar
fxy060608 已提交
1368
      }
fxy060608's avatar
fxy060608 已提交
1369 1370
      {
          useI18n().add(LOCALE_ZH_HANS, normalizeMessages(name, { cancel: '取消' }));
fxy060608's avatar
fxy060608 已提交
1371
      }
fxy060608's avatar
fxy060608 已提交
1372 1373
      {
          useI18n().add(LOCALE_ZH_HANT, normalizeMessages(name, { cancel: '取消' }));
fxy060608's avatar
fxy060608 已提交
1374
      }
fxy060608's avatar
fxy060608 已提交
1375 1376 1377 1378 1379
  });
  const initI18nShowModalMsgsOnce = /*#__PURE__*/ once(() => {
      const name = 'uni.showModal.';
      {
          useI18n().add(LOCALE_EN, normalizeMessages(name, { cancel: 'Cancel', confirm: 'OK' }));
fxy060608's avatar
fxy060608 已提交
1380
      }
fxy060608's avatar
fxy060608 已提交
1381 1382
      {
          useI18n().add(LOCALE_ES, normalizeMessages(name, { cancel: 'Cancelar', confirm: 'OK' }));
fxy060608's avatar
fxy060608 已提交
1383
      }
fxy060608's avatar
fxy060608 已提交
1384 1385
      {
          useI18n().add(LOCALE_FR, normalizeMessages(name, { cancel: 'Annuler', confirm: 'OK' }));
fxy060608's avatar
fxy060608 已提交
1386
      }
fxy060608's avatar
fxy060608 已提交
1387 1388
      {
          useI18n().add(LOCALE_ZH_HANS, normalizeMessages(name, { cancel: '取消', confirm: '确定' }));
fxy060608's avatar
fxy060608 已提交
1389
      }
fxy060608's avatar
fxy060608 已提交
1390 1391
      {
          useI18n().add(LOCALE_ZH_HANT, normalizeMessages(name, { cancel: '取消', confirm: '確定' }));
fxy060608's avatar
fxy060608 已提交
1392
      }
fxy060608's avatar
fxy060608 已提交
1393 1394 1395 1396 1397 1398 1399 1400 1401
  });
  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 已提交
1402
      }
fxy060608's avatar
fxy060608 已提交
1403 1404 1405 1406 1407 1408
      {
          useI18n().add(LOCALE_ES, normalizeMessages(name, {
              cancel: 'Cancelar',
              'sourceType.album': 'Álbum',
              'sourceType.camera': 'Cámara',
          }));
fxy060608's avatar
fxy060608 已提交
1409
      }
fxy060608's avatar
fxy060608 已提交
1410 1411 1412 1413 1414 1415
      {
          useI18n().add(LOCALE_FR, normalizeMessages(name, {
              cancel: 'Annuler',
              'sourceType.album': 'Album',
              'sourceType.camera': 'Caméra',
          }));
fxy060608's avatar
fxy060608 已提交
1416
      }
fxy060608's avatar
fxy060608 已提交
1417 1418 1419 1420 1421 1422
      {
          useI18n().add(LOCALE_ZH_HANS, normalizeMessages(name, {
              cancel: '取消',
              'sourceType.album': '从相册选择',
              'sourceType.camera': '拍摄',
          }));
fxy060608's avatar
fxy060608 已提交
1423
      }
fxy060608's avatar
fxy060608 已提交
1424 1425 1426 1427 1428 1429
      {
          useI18n().add(LOCALE_ZH_HANT, normalizeMessages(name, {
              cancel: '取消',
              'sourceType.album': '從相冊選擇',
              'sourceType.camera': '拍攝',
          }));
fxy060608's avatar
fxy060608 已提交
1430
      }
fxy060608's avatar
fxy060608 已提交
1431
  });
fxy060608's avatar
fxy060608 已提交
1432 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 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
  const initI18nChooseVideoMsgsOnce = /*#__PURE__*/ once(() => {
      const name = 'uni.chooseVideo.';
      {
          useI18n().add(LOCALE_EN, normalizeMessages(name, {
              cancel: 'Cancel',
              'sourceType.album': 'Album',
              'sourceType.camera': 'Camera',
          }));
      }
      {
          useI18n().add(LOCALE_ES, normalizeMessages(name, {
              cancel: 'Cancelar',
              'sourceType.album': 'Álbum',
              'sourceType.camera': 'Cámara',
          }));
      }
      {
          useI18n().add(LOCALE_FR, normalizeMessages(name, {
              cancel: 'Annuler',
              'sourceType.album': 'Album',
              'sourceType.camera': 'Caméra',
          }));
      }
      {
          useI18n().add(LOCALE_ZH_HANS, normalizeMessages(name, {
              cancel: '取消',
              'sourceType.album': '从相册选择',
              'sourceType.camera': '拍摄',
          }));
      }
      {
          useI18n().add(LOCALE_ZH_HANT, normalizeMessages(name, {
              cancel: '取消',
              'sourceType.album': '從相冊選擇',
              'sourceType.camera': '拍攝',
          }));
      }
  });
fxy060608's avatar
fxy060608 已提交
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
  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 已提交
1491
  });
fxy060608's avatar
fxy060608 已提交
1492

fxy060608's avatar
fxy060608 已提交
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
  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 已提交
1503
          });
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 1537 1538 1539 1540 1541 1542
          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 已提交
1543
  // TODO 等待 vue3 的兼容模式自带emitter
fxy060608's avatar
fxy060608 已提交
1544
  function initBridge(subscribeNamespace) {
fxy060608's avatar
fxy060608 已提交
1545 1546
      // TODO vue3 compatibility builds
      const emitter = new E();
fxy060608's avatar
fxy060608 已提交
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
      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 已提交
1560 1561
          subscribe(event, callback, once = false) {
              emitter[once ? 'once' : 'on'](`${subscribeNamespace}.${event}`, callback);
fxy060608's avatar
fxy060608 已提交
1562 1563
          },
          unsubscribe(event, callback) {
fxy060608's avatar
fxy060608 已提交
1564
              emitter.off(`${subscribeNamespace}.${event}`, callback);
fxy060608's avatar
fxy060608 已提交
1565 1566 1567
          },
          subscribeHandler(event, args, pageId) {
              if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
1568
                  console.log(formatLog(subscribeNamespace, 'subscribeHandler', pageId, event, args));
fxy060608's avatar
fxy060608 已提交
1569
              }
fxy060608's avatar
fxy060608 已提交
1570
              emitter.emit(`${subscribeNamespace}.${event}`, args, pageId);
fxy060608's avatar
fxy060608 已提交
1571
          },
fxy060608's avatar
fxy060608 已提交
1572
      };
fxy060608's avatar
fxy060608 已提交
1573
  }
fxy060608's avatar
fxy060608 已提交
1574 1575

  function hasRpx(str) {
fxy060608's avatar
fxy060608 已提交
1576
      str = str + '';
fxy060608's avatar
fxy060608 已提交
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
      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 已提交
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
  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 已提交
1623 1624 1625 1626
  const PAGE_META_KEYS = ['navigationBar', 'pullToRefresh'];
  function initGlobalStyle() {
      return JSON.parse(JSON.stringify(__uniConfig.globalStyle || {}));
  }
fxy060608's avatar
fxy060608 已提交
1627
  function initRouteMeta(pageMeta, id) {
fxy060608's avatar
fxy060608 已提交
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
      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 已提交
1646
  }
fxy060608's avatar
fxy060608 已提交
1647
  function initPageInternalInstance(openType, url, pageQuery, meta) {
fxy060608's avatar
fxy060608 已提交
1648 1649 1650 1651 1652 1653 1654 1655
      const { id, route } = meta;
      return {
          id: id,
          path: '/' + route,
          route: route,
          fullPath: url,
          options: pageQuery,
          meta,
fxy060608's avatar
fxy060608 已提交
1656
          openType,
fxy060608's avatar
fxy060608 已提交
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
      };
  }

  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 已提交
1680 1681
  }

fxy060608's avatar
fxy060608 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
  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 已提交
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
  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 已提交
1711 1712 1713 1714 1715 1716
  }
  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 已提交
1717 1718 1719 1720 1721 1722
  }
  function getRouteMeta(path) {
      const routeOptions = getRouteOptions(path);
      if (routeOptions) {
          return routeOptions.meta;
      }
fxy060608's avatar
fxy060608 已提交
1723 1724
  }

fxy060608's avatar
fxy060608 已提交
1725
  const ServiceJSBridge = /*#__PURE__*/ extend(initBridge('view' /* view 指的是 service 层订阅的是 view 层事件 */), {
fxy060608's avatar
fxy060608 已提交
1726 1727 1728 1729 1730
      invokeOnCallback(name, res) {
          return UniServiceJSBridge.emit('api.' + name, res);
      },
  });

fxy060608's avatar
fxy060608 已提交
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 1767 1768 1769 1770
  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 已提交
1771 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
  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 已提交
1814
  function initServicePlugin(app) {
fxy060608's avatar
fxy060608 已提交
1815 1816 1817
      initAppConfig(app._context.config);
  }

fxy060608's avatar
fxy060608 已提交
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
  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 {
fxy060608's avatar
fxy060608 已提交
1848 1849 1850
              const page = getCurrentPage();
              if (page) {
                  return wwwPath + getRealRoute('/' + page.route, filepath);
fxy060608's avatar
fxy060608 已提交
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
              }
          }
      }
      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,
  };

1910 1911
  const API_ADD_PHONE_CONTACT = 'addPhoneContact';

fxy060608's avatar
fxy060608 已提交
1912 1913 1914
  const API_GET_CLIPBOARD_DATA = 'getClipboardData';
  const API_SET_CLIPBOARD_DATA = 'setClipboardData';

fxy060608's avatar
fxy060608 已提交
1915 1916 1917 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 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
  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 已提交
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
  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 已提交
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 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 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
  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,
  };

fxy060608's avatar
fxy060608 已提交
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
  const API_CHOOSE_IMAGE = 'chooseImage';
  const ChooseImageOptions = {
      formatArgs: {
          count(value, params) {
              if (!value || value <= 0) {
                  params.count = 9;
              }
          },
          sizeType(sizeType, params) {
              params.sizeType = elemsInArray(sizeType, CHOOSE_SIZE_TYPES);
          },
          sourceType(sourceType, params) {
              params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES);
          },
          extension(extension, params) {
              if (extension instanceof Array && extension.length === 0) {
                  return 'param extension should not be empty.';
              }
              if (!extension)
                  params.extension = [''];
          },
      },
  };
  const ChooseImageProtocol = {
      count: Number,
      sizeType: [Array, String],
      sourceType: Array,
      extension: Array,
  };

  const API_CHOOSE_VIDEO = 'chooseVideo';
  const ChooseVideoOptions = {
      formatArgs: {
          sourceType(sourceType, params) {
              params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES);
          },
          compressed: true,
          maxDuration: 60,
          camera: 'back',
          extension(extension, params) {
              if (extension instanceof Array && extension.length === 0) {
                  return 'param extension should not be empty.';
              }
              if (!extension)
                  params.extension = [''];
          },
      },
  };
  const ChooseVideoProtocol = {
      sourceType: Array,
      compressed: Boolean,
      maxDuration: Number,
      camera: String,
      extension: Array,
  };

fxy060608's avatar
fxy060608 已提交
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 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
  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 已提交
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
  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 已提交
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 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
  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,
  };

fxy060608's avatar
fxy060608 已提交
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
  const API_UPLOAD_FILE = 'uploadFile';
  const UploadFileOptions = {
      formatArgs: {
          filePath(filePath, params) {
              if (filePath) {
                  params.filePath = getRealPath(filePath);
              }
          },
          header(value, params) {
              params.header = value || {};
          },
          formData(value, params) {
              params.formData = value || {};
          },
      },
  };
  const UploadFileProtocol = {
      url: {
          type: String,
          required: true,
      },
      files: Array,
      filePath: String,
      name: String,
      header: Object,
      formData: Object,
      timeout: Number,
  };

fxy060608's avatar
fxy060608 已提交
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
  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 已提交
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 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
  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',
  ];
fxy060608's avatar
fxy060608 已提交
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
  const ANIMATION_OUT = [
      'slide-out-right',
      'slide-out-left',
      'slide-out-top',
      'slide-out-bottom',
      'fade-out',
      'zoom-in',
      'zoom-fade-in',
      'pop-out',
      'none',
  ];
fxy060608's avatar
fxy060608 已提交
2589 2590 2591 2592 2593 2594 2595 2596 2597
  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 已提交
2598
  const API_NAVIGATE_BACK = 'navigateBack';
fxy060608's avatar
fxy060608 已提交
2599 2600 2601 2602
  const API_PRELOAD_PAGE = 'preloadPage';
  const API_UN_PRELOAD_PAGE = 'unPreloadPage';
  const NavigateToProtocol = 
  /*#__PURE__*/ extend({}, BaseRouteProtocol, createAnimationProtocol(ANIMATION_IN));
fxy060608's avatar
fxy060608 已提交
2603 2604 2605 2606 2607 2608
  const NavigateBackProtocol = 
  /*#__PURE__*/ extend({
      delta: {
          type: Number,
      },
  }, createAnimationProtocol(ANIMATION_OUT));
fxy060608's avatar
fxy060608 已提交
2609 2610
  const NavigateToOptions = 
  /*#__PURE__*/ createRouteOptions(API_NAVIGATE_TO);
fxy060608's avatar
fxy060608 已提交
2611 2612 2613 2614 2615 2616 2617 2618
  const NavigateBackOptions = {
      formatArgs: {
          delta(value, params) {
              value = parseInt(value + '') || 1;
              params.delta = Math.min(getCurrentPages().length - 1, value);
          },
      },
  };
fxy060608's avatar
fxy060608 已提交
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
  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) {
fxy060608's avatar
fxy060608 已提交
2690 2691 2692 2693 2694
              {
                  if (!routeOptions.meta.isNVue) {
                      return 'can not preload vue page';
                  }
              }
fxy060608's avatar
fxy060608 已提交
2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
              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 已提交
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 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 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825
  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 已提交
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
  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) {
fxy060608's avatar
fxy060608 已提交
2930 2931 2932
              if (value && !TYPE.includes(value))
                  return '分享参数 type 不正确。只支持text、image';
              params.type = elemInArray(value, TYPE);
fxy060608's avatar
fxy060608 已提交
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
          },
      },
  };
  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 已提交
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 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023
  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 已提交
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 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
  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),
          }));
      };
  }

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

fxy060608's avatar
fxy060608 已提交
3231
  const getFileInfo$1 = defineAsyncApi(API_GET_FILE_INFO, (options, { resolve, reject }) => {
fxy060608's avatar
fxy060608 已提交
3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247
      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 已提交
3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
  const NETWORK_TYPES = [
      'unknown',
      'none',
      'ethernet',
      'wifi',
      '2g',
      '3g',
      '4g',
      '5g',
  ];
fxy060608's avatar
fxy060608 已提交
3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 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 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
  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);

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
  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 已提交
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 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574
  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 已提交
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 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 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 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 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799
  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 已提交
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
  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,
fxy060608's avatar
fxy060608 已提交
3912
              samplerate: sampleRate ? String(sampleRate) : '',
fxy060608's avatar
fxy060608 已提交
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
              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 已提交
3947
  const callbacks$1 = {
fxy060608's avatar
fxy060608 已提交
3948 3949 3950 3951 3952 3953 3954 3955 3956 3957
      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 已提交
3958 3959
      if (state && typeof callbacks$1[state] === 'function') {
          callbacks$1[state](res);
fxy060608's avatar
fxy060608 已提交
3960 3961 3962 3963 3964
      }
  }
  class RecorderManager {
      constructor() { }
      onError(callback) {
fxy060608's avatar
fxy060608 已提交
3965
          callbacks$1.error = callback;
fxy060608's avatar
fxy060608 已提交
3966 3967 3968 3969 3970
      }
      onFrameRecorded(callback) { }
      onInterruptionBegin(callback) { }
      onInterruptionEnd(callback) { }
      onPause(callback) {
fxy060608's avatar
fxy060608 已提交
3971
          callbacks$1.pause = callback;
fxy060608's avatar
fxy060608 已提交
3972 3973
      }
      onResume(callback) {
fxy060608's avatar
fxy060608 已提交
3974
          callbacks$1.resume = callback;
fxy060608's avatar
fxy060608 已提交
3975 3976
      }
      onStart(callback) {
fxy060608's avatar
fxy060608 已提交
3977
          callbacks$1.start = callback;
fxy060608's avatar
fxy060608 已提交
3978 3979
      }
      onStop(callback) {
fxy060608's avatar
fxy060608 已提交
3980
          callbacks$1.stop = callback;
fxy060608's avatar
fxy060608 已提交
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
      }
      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 已提交
4006 4007 4008 4009 4010
  function getFileName(path) {
      const array = path.split('/');
      return array[array.length - 1];
  }

fxy060608's avatar
fxy060608 已提交
4011
  const compressImage$1 = defineAsyncApi(API_COMPRESS_IMAGE, (options, { resolve, reject }) => {
fxy060608's avatar
fxy060608 已提交
4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032
      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 已提交
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
  /**
   * 获取文件信息
   * @param {string} filePath 文件路径
   * @returns {Promise} 文件信息Promise
   */
  function getFileInfo(filePath) {
      return new Promise((resolve, reject) => {
          plus.io.resolveLocalFileSystemURL(filePath, function (entry) {
              entry.getMetadata(resolve, reject, false);
          }, reject);
      });
  }
  function compressImage(tempFilePath) {
      const dst = `${TEMP_PATH}/compressed/${Date.now()}_${getFileName(tempFilePath)}`;
      return new Promise((resolve) => {
          plus.nativeUI.showWaiting();
          plus.zip.compressImage({
              src: tempFilePath,
              dst,
              overwrite: true,
          }, () => {
              plus.nativeUI.closeWaiting();
              resolve(dst);
          }, () => {
              plus.nativeUI.closeWaiting();
              resolve(tempFilePath);
          });
      });
  }
  const chooseImage = defineAsyncApi(API_CHOOSE_IMAGE, 
  // @ts-ignore crop 属性App特有
  ({ count, sizeType, sourceType, crop } = {}, { resolve, reject }) => {
      initI18nChooseImageMsgsOnce();
      const { t } = useI18n();
      const errorCallback = warpPlusErrorCallback(reject);
      function successCallback(paths) {
          const tempFiles = [];
          const tempFilePaths = [];
          // plus.zip.compressImage 压缩文件并发调用在iOS端容易出现问题(图像错误、闪退),改为队列执行
          paths
              .reduce((promise, path) => {
              return promise
                  .then(() => {
                  return getFileInfo(path);
              })
                  .then((fileInfo) => {
                  const size = fileInfo.size;
                  // 压缩阈值 0.5 兆
                  const THRESHOLD = 1024 * 1024 * 0.5;
                  // 判断是否需要压缩
                  if (!crop &&
                      sizeType.includes('compressed') &&
                      size > THRESHOLD) {
                      return compressImage(path).then((dstPath) => {
                          path = dstPath;
                          return getFileInfo(path);
                      });
                  }
                  return fileInfo;
              })
                  .then(({ size }) => {
                  tempFilePaths.push(path);
                  tempFiles.push({
                      path,
                      size: size,
                  });
              });
          }, Promise.resolve())
              .then(() => {
              resolve({
                  tempFilePaths,
                  tempFiles,
              });
          })
              .catch(errorCallback);
      }
      function openCamera() {
          const camera = plus.camera.getCamera();
          camera.captureImage((path) => successCallback([path]), errorCallback, {
              filename: TEMP_PATH + '/camera/',
              resolution: 'high',
              crop,
          });
      }
      function openAlbum() {
          // NOTE 5+此API分单选和多选,多选返回files:string[]
          // @ts-ignore
          plus.gallery.pick(({ files }) => successCallback(files), errorCallback, {
              maximum: count,
              multiple: true,
              system: false,
              filename: TEMP_PATH + '/gallery/',
              permissionAlert: true,
              crop,
          });
      }
      if (sourceType.length === 1) {
          if (sourceType.includes('album')) {
              openAlbum();
              return;
          }
          else if (sourceType.includes('camera')) {
              openCamera();
              return;
          }
      }
      plus.nativeUI.actionSheet({
          cancel: t('uni.chooseImage.cancel'),
          buttons: [
              {
                  title: t('uni.chooseImage.sourceType.camera'),
              },
              {
                  title: t('uni.chooseImage.sourceType.album'),
              },
          ],
      }, (e) => {
          switch (e.index) {
              case 1:
                  openCamera();
                  break;
              case 2:
                  openAlbum();
                  break;
              default:
                  errorCallback();
                  break;
          }
      });
  }, ChooseImageProtocol, ChooseImageOptions);

  const chooseVideo = defineAsyncApi(API_CHOOSE_VIDEO, ({ sourceType, compressed, maxDuration, camera }, { resolve, reject }) => {
      initI18nChooseVideoMsgsOnce();
      const { t } = useI18n();
      const errorCallback = warpPlusErrorCallback(reject);
      function successCallback(tempFilePath = '') {
          const filename = `${TEMP_PATH}/compressed/${Date.now()}_${getFileName(tempFilePath)}`;
          const compressVideo = compressed
              ? new Promise((resolve) => {
                  plus.zip.compressVideo({
                      src: tempFilePath,
                      filename,
                  }, ({ tempFilePath }) => {
                      resolve(tempFilePath);
                  }, () => {
                      resolve(tempFilePath);
                  });
              })
              : Promise.resolve(tempFilePath);
          if (compressed) {
              plus.nativeUI.showWaiting();
          }
          compressVideo.then((tempFilePath) => {
              if (compressed) {
                  plus.nativeUI.closeWaiting();
              }
              plus.io.getVideoInfo({
                  filePath: tempFilePath,
                  success(videoInfo) {
                      const result = {
                          errMsg: 'chooseVideo:ok',
                          tempFilePath: tempFilePath,
                          size: videoInfo.size,
                          duration: videoInfo.duration,
                          width: videoInfo.width,
                          height: videoInfo.height,
                      };
                      resolve(result);
                  },
                  fail: errorCallback,
              });
          });
      }
      function openAlbum() {
          plus.gallery.pick(
          // NOTE 5+此API分单选和多选,多选返回files:string[]
          // @ts-ignore
          ({ files }) => successCallback(files[0]), errorCallback, {
              filter: 'video',
              system: false,
              // 不启用 multiple 时 system 无效
              multiple: true,
              maximum: 1,
              filename: TEMP_PATH + '/gallery/',
              permissionAlert: true,
          });
      }
      function openCamera() {
          const plusCamera = plus.camera.getCamera();
          plusCamera.startVideoCapture(successCallback, errorCallback, {
              index: camera === 'front' ? '2' : '1',
              videoMaximumDuration: maxDuration,
              filename: TEMP_PATH + '/camera/',
          });
      }
      if (sourceType.length === 1) {
          if (sourceType.includes('album')) {
              openAlbum();
              return;
          }
          else if (sourceType.includes('camera')) {
              openCamera();
              return;
          }
      }
      plus.nativeUI.actionSheet({
          cancel: t('uni.chooseVideo.cancel'),
          buttons: [
              {
                  title: t('uni.chooseVideo.sourceType.camera'),
              },
              {
                  title: t('uni.chooseVideo.sourceType.album'),
              },
          ],
      }, (e) => {
          switch (e.index) {
              case 1:
                  openCamera();
                  break;
              case 2:
                  openAlbum();
                  break;
              default:
                  errorCallback();
                  break;
          }
      });
  }, ChooseVideoProtocol, ChooseVideoOptions);

fxy060608's avatar
fxy060608 已提交
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
  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 = [];
fxy060608's avatar
fxy060608 已提交
4510
  const socketsMap = {};
fxy060608's avatar
fxy060608 已提交
4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523
  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');
fxy060608's avatar
fxy060608 已提交
4524
              bindSocketCallBack(socket);
fxy060608's avatar
fxy060608 已提交
4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539
          }
          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 };
  }
fxy060608's avatar
fxy060608 已提交
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
  function bindSocketCallBack(socket) {
      socket.onopen((e) => {
          const curSocket = socketsMap[e.id];
          if (!curSocket)
              return;
          curSocket._socketOnOpen();
      });
      socket.onmessage((e) => {
          const curSocket = socketsMap[e.id];
          if (!curSocket)
              return;
          curSocket._socketOnMessage(e);
      });
      socket.onerror((e) => {
          const curSocket = socketsMap[e.id];
          if (!curSocket)
              return;
          curSocket._socketOnError();
      });
      socket.onclose((e) => {
          const curSocket = socketsMap[e.id];
          if (!curSocket)
              return;
          curSocket._socketOnClose();
      });
  }
fxy060608's avatar
fxy060608 已提交
4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582
  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;
fxy060608's avatar
fxy060608 已提交
4583 4584 4585 4586 4587 4588 4589 4590 4591 4592
      }
      _socketOnOpen() {
          this.readyState = this.OPEN;
          this.socketStateChange('open');
      }
      _socketOnMessage(e) {
          this.socketStateChange('message', {
              data: typeof e.data === 'object'
                  ? base64ToArrayBuffer(e.data.base64)
                  : e.data,
fxy060608's avatar
fxy060608 已提交
4593 4594
          });
      }
fxy060608's avatar
fxy060608 已提交
4595 4596 4597 4598 4599 4600 4601 4602
      _socketOnError() {
          this.socketStateChange('error');
          this.onErrorOrClose();
      }
      _socketOnClose() {
          this.socketStateChange('close');
          this.onErrorOrClose();
      }
fxy060608's avatar
fxy060608 已提交
4603 4604
      onErrorOrClose() {
          this.readyState = this.CLOSED;
fxy060608's avatar
fxy060608 已提交
4605
          delete socketsMap[this.id];
fxy060608's avatar
fxy060608 已提交
4606 4607 4608 4609 4610 4611
          const index = socketTasks.indexOf(this);
          if (index >= 0) {
              socketTasks.splice(index, 1);
          }
      }
      socketStateChange(name, res = {}) {
fxy060608's avatar
fxy060608 已提交
4612
          const data = name === 'message' ? res : {};
fxy060608's avatar
fxy060608 已提交
4613
          if (this === socketTasks[0] && globalEvent[name]) {
fxy060608's avatar
fxy060608 已提交
4614
              UniServiceJSBridge.invokeOnCallback(globalEvent[name], data);
fxy060608's avatar
fxy060608 已提交
4615 4616 4617 4618
          }
          // WYQ fix: App平台修复websocket onOpen时发送数据报错的Bug
          this._callbacks[name].forEach((callback) => {
              if (typeof callback === 'function') {
fxy060608's avatar
fxy060608 已提交
4619
                  callback(data);
fxy060608's avatar
fxy060608 已提交
4620 4621 4622
              }
          });
      }
fxy060608's avatar
fxy060608 已提交
4623
      send(args, callopt = true) {
fxy060608's avatar
fxy060608 已提交
4624 4625 4626 4627 4628
          if (this.readyState !== this.OPEN) {
              callOptions(args, 'sendSocketMessage:fail WebSocket is not connected');
          }
          try {
              this._socket.send({
fxy060608's avatar
fxy060608 已提交
4629 4630 4631 4632 4633 4634 4635
                  id: this.id,
                  data: typeof args.data === 'object'
                      ? {
                          '@type': 'binary',
                          base64: arrayBufferToBase64(args.data),
                      }
                      : args.data,
fxy060608's avatar
fxy060608 已提交
4636
              });
fxy060608's avatar
fxy060608 已提交
4637
              callopt && callOptions(args, 'sendSocketMessage:ok');
fxy060608's avatar
fxy060608 已提交
4638 4639
          }
          catch (error) {
fxy060608's avatar
fxy060608 已提交
4640
              callopt && callOptions(args, `sendSocketMessage:fail ${error}`);
fxy060608's avatar
fxy060608 已提交
4641 4642
          }
      }
fxy060608's avatar
fxy060608 已提交
4643
      close(args, callopt = true) {
fxy060608's avatar
fxy060608 已提交
4644 4645
          this.readyState = this.CLOSING;
          try {
fxy060608's avatar
fxy060608 已提交
4646 4647 4648 4649
              this._socket.close(extend({
                  id: this.id,
                  args,
              }));
fxy060608's avatar
fxy060608 已提交
4650
              callopt && callOptions(args, 'closeSocket:ok');
fxy060608's avatar
fxy060608 已提交
4651 4652
          }
          catch (error) {
fxy060608's avatar
fxy060608 已提交
4653
              callopt && callOptions(args, `closeSocket:fail ${error}`);
fxy060608's avatar
fxy060608 已提交
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
          }
      }
      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);
fxy060608's avatar
fxy060608 已提交
4684
          socketsMap[socketId] = socketTask;
fxy060608's avatar
fxy060608 已提交
4685 4686 4687 4688 4689 4690 4691 4692 4693
      }
      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) {
fxy060608's avatar
fxy060608 已提交
4694
          reject('WebSocket is not connected');
fxy060608's avatar
fxy060608 已提交
4695 4696
          return;
      }
fxy060608's avatar
fxy060608 已提交
4697
      socketTask.send({ data: args.data }, false);
fxy060608's avatar
fxy060608 已提交
4698 4699 4700 4701 4702
      resolve();
  }, SendSocketMessageProtocol);
  const closeSocket = defineAsyncApi(API_CLOSE_SOCKET, (args, { resolve, reject }) => {
      const socketTask = socketTasks[0];
      if (!socketTask) {
fxy060608's avatar
fxy060608 已提交
4703
          reject('WebSocket is not connected');
fxy060608's avatar
fxy060608 已提交
4704 4705 4706
          return;
      }
      socketTask.readyState = socketTask.CLOSING;
fxy060608's avatar
fxy060608 已提交
4707
      socketTask.close(args, false);
fxy060608's avatar
fxy060608 已提交
4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720
      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');

fxy060608's avatar
fxy060608 已提交
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
  class UploadTask {
      constructor(uploader) {
          this._callbacks = [];
          this._uploader = uploader;
          uploader.addEventListener('statechanged', (upload, status) => {
              if (upload.uploadedSize && upload.totalSize) {
                  this._callbacks.forEach((callback) => {
                      callback({
                          progress: parseInt(String((upload.uploadedSize / upload.totalSize) * 100)),
                          totalBytesSent: upload.uploadedSize,
                          totalBytesExpectedToSend: upload.totalSize,
                      });
                  });
              }
          });
      }
      abort() {
          this._uploader.abort();
      }
      onProgressUpdate(callback) {
          if (typeof callback !== 'function') {
              return;
          }
          this._callbacks.push(callback);
      }
      onHeadersReceived() { }
      offProgressUpdate(callback) {
          const index = this._callbacks.indexOf(callback);
          if (index >= 0) {
              this._callbacks.splice(index, 1);
          }
      }
      offHeadersReceived() { }
  }
  const uploadFile = defineTaskApi(API_UPLOAD_FILE, ({ url, timeout, header, formData, files, filePath, name }, { resolve, reject }) => {
      const uploader = plus.uploader.createUpload(url, {
          timeout,
          // 需要与其它平台上的表现保持一致,不走重试的逻辑。
          retry: 0,
          retryInterval: 0,
      }, (upload, statusCode) => {
          if (statusCode) {
              resolve({
                  data: upload.responseText,
                  statusCode,
              });
          }
          else {
              reject(`statusCode: ${statusCode}`);
          }
      });
      for (const name in header) {
          if (hasOwn$1(header, name)) {
              uploader.setRequestHeader(name, String(header[name]));
          }
      }
      for (const name in formData) {
          if (hasOwn$1(formData, name)) {
              uploader.addData(name, String(formData[name]));
          }
      }
      if (files && files.length) {
          files.forEach((file) => {
              uploader.addFile(getRealPath(file.uri), {
                  key: file.name || 'file',
              });
          });
      }
      else {
          uploader.addFile(getRealPath(filePath), {
              key: name,
          });
      }
      const uploadFileTask = new UploadTask(uploader);
      uploader.start();
      return uploadFileTask;
  }, UploadFileProtocol, UploadFileOptions);

fxy060608's avatar
fxy060608 已提交
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
  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()}`;
fxy060608's avatar
fxy060608 已提交
4844
      const audio = (audios[audioId] = plus.audio.createPlayer('')); // 此处空字符串必填
fxy060608's avatar
fxy060608 已提交
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
      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) {
fxy060608's avatar
fxy060608 已提交
4921
                      emit(audio, 'timeUpdate');
fxy060608's avatar
fxy060608 已提交
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
                  }
              }, 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) {
fxy060608's avatar
fxy060608 已提交
5061
      const name = `on${capitalize(state)}`;
fxy060608's avatar
fxy060608 已提交
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
      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 已提交
5095
  const callbacks = {
fxy060608's avatar
fxy060608 已提交
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 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
      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 已提交
5274
      callbacks[state].forEach((callback) => {
fxy060608's avatar
fxy060608 已提交
5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286
          if (typeof callback === 'function') {
              callback(state === 'error'
                  ? {
                      errMsg,
                      errCode,
                  }
                  : {});
          }
      });
  }
  const onInitBackgroundAudioManager = /*#__PURE__*/ once(() => {
      eventNames.forEach((item) => {
fxy060608's avatar
fxy060608 已提交
5287 5288 5289 5290
          BackgroundAudioManager.prototype[`on${capitalize(item)}`] =
              function (callback) {
                  callbacks[item].push(callback);
              };
fxy060608's avatar
fxy060608 已提交
5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 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 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564
      });
  });
  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;
fxy060608's avatar
fxy060608 已提交
5565 5566 5567 5568
  const showLoading = defineAsyncApi(API_SHOW_LOADING, (args, callbacks) => _showToast(extend({}, args, {
      type: 'loading',
  }), callbacks), ShowLoadingProtocol, ShowLoadingOptions);
  const _showToast = ({ title = '', icon = 'success', image = '', duration = 1500, mask = false, position, 
fxy060608's avatar
fxy060608 已提交
5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632
  // @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();
fxy060608's avatar
fxy060608 已提交
5633 5634 5635 5636 5637
  };
  const showToast = defineAsyncApi(API_SHOW_TOAST, _showToast, ShowToastProtocol, ShowToastOptions);
  const hideToast = defineAsyncApi(API_HIDE_TOAST, (_, callbacks) => hide('toast', callbacks));
  const hideLoading = defineAsyncApi(API_HIDE_LOADING, (_, callbacks) => hide('loading', callbacks));
  function hide(type = 'toast', callbacks) {
fxy060608's avatar
fxy060608 已提交
5638
      if (type && type !== toastType) {
fxy060608's avatar
fxy060608 已提交
5639 5640
          // 应该不需要失败回调,在页面后退时,会主动 hideToast 和 hideLoading,如果 reject 会出异常。
          return callbacks && callbacks.resolve();
fxy060608's avatar
fxy060608 已提交
5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654
      }
      if (timeout) {
          clearTimeout(timeout);
          timeout = null;
      }
      if (isShowToast) {
          plus.nativeUI.closeToast();
      }
      else if (toast && toast.close) {
          toast.close();
      }
      toast = null;
      isShowToast = false;
      toastType = '';
fxy060608's avatar
fxy060608 已提交
5655
      return callbacks && callbacks.resolve();
fxy060608's avatar
fxy060608 已提交
5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722
  }

  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 已提交
5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 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 5799 5800 5801 5802 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 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868
  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 已提交
5869 5870 5871 5872 5873
  const registerRuntime = defineSyncApi('registerRuntime', (runtime) => {
      // @ts-expect-error
      extend(jsRuntime, runtime);
  });

fxy060608's avatar
fxy060608 已提交
5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 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 5955 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
  // 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 已提交
5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006
  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 已提交
6007
      }
fxy060608's avatar
fxy060608 已提交
6008 6009 6010
      const app = getApp();
      if (!app || !app.$vm) {
          throw err;
fxy060608's avatar
fxy060608 已提交
6011
      }
fxy060608's avatar
fxy060608 已提交
6012 6013
      {
          invokeHook(app.$vm, 'onError', err);
fxy060608's avatar
fxy060608 已提交
6014
      }
fxy060608's avatar
fxy060608 已提交
6015 6016 6017 6018 6019 6020
  }

  function initApp(app) {
      const appConfig = app._context.config;
      if (isFunction(app._component.onError)) {
          appConfig.errorHandler = errorHandler;
fxy060608's avatar
fxy060608 已提交
6021
      }
fxy060608's avatar
fxy060608 已提交
6022 6023 6024 6025
      const globalProperties = appConfig.globalProperties;
      {
          globalProperties.$set = set;
          globalProperties.$applyOptions = applyOptions;
fxy060608's avatar
fxy060608 已提交
6026
      }
fxy060608's avatar
fxy060608 已提交
6027 6028 6029 6030 6031 6032
  }

  let isInitEntryPage = false;
  function initEntry() {
      if (isInitEntryPage) {
          return;
fxy060608's avatar
fxy060608 已提交
6033
      }
fxy060608's avatar
fxy060608 已提交
6034 6035 6036 6037 6038 6039 6040 6041
      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 已提交
6042
      }
fxy060608's avatar
fxy060608 已提交
6043 6044 6045
      else {
          const argsJsonStr = plus.runtime.arguments;
          if (!argsJsonStr) {
fxy060608's avatar
fxy060608 已提交
6046 6047
              return;
          }
fxy060608's avatar
fxy060608 已提交
6048 6049 6050 6051 6052 6053
          try {
              const args = JSON.parse(argsJsonStr);
              entryPagePath = args.path || args.pathName;
              entryPageQuery = args.query ? '?' + args.query : '';
          }
          catch (e) { }
fxy060608's avatar
fxy060608 已提交
6054
      }
fxy060608's avatar
fxy060608 已提交
6055 6056 6057
      if (!entryPagePath || entryPagePath === __uniConfig.entryPagePath) {
          if (entryPageQuery) {
              __uniConfig.entryPageQuery = entryPageQuery;
fxy060608's avatar
fxy060608 已提交
6058
          }
fxy060608's avatar
fxy060608 已提交
6059
          return;
fxy060608's avatar
fxy060608 已提交
6060
      }
fxy060608's avatar
fxy060608 已提交
6061 6062 6063 6064
      const entryRoute = '/' + entryPagePath;
      const routeOptions = getRouteOptions(entryRoute);
      if (!routeOptions) {
          return;
fxy060608's avatar
fxy060608 已提交
6065
      }
fxy060608's avatar
fxy060608 已提交
6066 6067 6068
      if (!routeOptions.meta.isTabBar) {
          __uniConfig.realEntryPagePath =
              __uniConfig.realEntryPagePath || __uniConfig.entryPagePath;
fxy060608's avatar
fxy060608 已提交
6069
      }
fxy060608's avatar
fxy060608 已提交
6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089
      __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 已提交
6090
      }
fxy060608's avatar
fxy060608 已提交
6091 6092 6093 6094 6095 6096
      if (type === 'none') {
          tabBar.hideTabBarRedDot({
              index,
          });
          tabBar.removeTabBarBadge({
              index,
fxy060608's avatar
fxy060608 已提交
6097 6098
          });
      }
fxy060608's avatar
fxy060608 已提交
6099 6100 6101 6102
      else if (type === 'text') {
          tabBar.setTabBarBadge({
              index,
              text,
fxy060608's avatar
fxy060608 已提交
6103 6104
          });
      }
fxy060608's avatar
fxy060608 已提交
6105 6106 6107 6108
      else if (type === 'redDot') {
          tabBar.showTabBarRedDot({
              index,
          });
fxy060608's avatar
fxy060608 已提交
6109
      }
fxy060608's avatar
fxy060608 已提交
6110 6111 6112 6113 6114 6115 6116 6117 6118 6119
  }
  /**
   * 动态设置 tabBar 某一项的内容
   */
  function setTabBarItem(index, text, iconPath, selectedIconPath) {
      const item = {
          index,
      };
      if (text !== undefined) {
          item.text = text;
fxy060608's avatar
fxy060608 已提交
6120
      }
fxy060608's avatar
fxy060608 已提交
6121 6122
      if (iconPath) {
          item.iconPath = getRealPath(iconPath);
fxy060608's avatar
fxy060608 已提交
6123
      }
fxy060608's avatar
fxy060608 已提交
6124 6125
      if (selectedIconPath) {
          item.selectedIconPath = getRealPath(selectedIconPath);
fxy060608's avatar
fxy060608 已提交
6126
      }
fxy060608's avatar
fxy060608 已提交
6127
      tabBar && tabBar.setTabBarItem(item);
fxy060608's avatar
fxy060608 已提交
6128
  }
fxy060608's avatar
fxy060608 已提交
6129 6130 6131 6132 6133 6134
  /**
   * 动态设置 tabBar 的整体样式
   * @param {Object} style 样式
   */
  function setTabBarStyle(style) {
      tabBar && tabBar.setTabBarStyle(style);
fxy060608's avatar
fxy060608 已提交
6135
  }
fxy060608's avatar
fxy060608 已提交
6136 6137 6138 6139 6140 6141 6142 6143 6144 6145
  /**
   * 隐藏 tabBar
   * @param {boolean} animation 是否需要动画效果
   */
  function hideTabBar(animation) {
      visible = false;
      tabBar &&
          tabBar.hideTabBar({
              animation,
          });
fxy060608's avatar
fxy060608 已提交
6146
  }
fxy060608's avatar
fxy060608 已提交
6147 6148 6149 6150 6151 6152 6153 6154 6155
  /**
   * 显示 tabBar
   * @param {boolean} animation 是否需要动画效果
   */
  function showTabBar(animation) {
      visible = true;
      tabBar &&
          tabBar.showTabBar({
              animation,
fxy060608's avatar
fxy060608 已提交
6156 6157
          });
  }
fxy060608's avatar
fxy060608 已提交
6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174
  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 已提交
6175
          });
fxy060608's avatar
fxy060608 已提交
6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191
          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 已提交
6192 6193
                  }
              }
fxy060608's avatar
fxy060608 已提交
6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239
          }
          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 已提交
6240
          });
fxy060608's avatar
fxy060608 已提交
6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255
      },
      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 已提交
6256
      }
fxy060608's avatar
fxy060608 已提交
6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271
      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 已提交
6272
          });
fxy060608's avatar
fxy060608 已提交
6273 6274 6275 6276 6277
      });
      if (selected !== -1) {
          // 取当前 tab 索引值
          tabBar.selectedIndex = selected;
          selected !== 0 && tabBar$1.switchTab(entryPagePath);
fxy060608's avatar
fxy060608 已提交
6278
      }
fxy060608's avatar
fxy060608 已提交
6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292
  }

  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 已提交
6293
      }
fxy060608's avatar
fxy060608 已提交
6294 6295 6296 6297
      else {
          plusGlobalEvent.addEventListener('splashclosed', () => {
              plus.key.addEventListener('backbutton', backbuttonListener);
          });
fxy060608's avatar
fxy060608 已提交
6298
      }
fxy060608's avatar
fxy060608 已提交
6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316
      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 已提交
6317
          console.log(formatLog('plusMessage', data));
fxy060608's avatar
fxy060608 已提交
6318
      }
fxy060608's avatar
fxy060608 已提交
6319 6320
      if (data && data.type) {
          UniServiceJSBridge.subscribeHandler('plusMessage.' + data.type, data.args);
fxy060608's avatar
fxy060608 已提交
6321 6322
      }
  }
fxy060608's avatar
fxy060608 已提交
6323 6324 6325
  function onPlusMessage(type, callback, once = false) {
      UniServiceJSBridge.subscribe('plusMessage.' + type, callback, once);
  }
fxy060608's avatar
fxy060608 已提交
6326

fxy060608's avatar
fxy060608 已提交
6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367
  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 已提交
6368

fxy060608's avatar
fxy060608 已提交
6369
  const VD_SYNC = 'vdSync';
fxy060608's avatar
fxy060608 已提交
6370
  const ON_WEBVIEW_READY = 'onWebviewReady';
fxy060608's avatar
fxy060608 已提交
6371 6372
  const INVOKE_VIEW_API = 'invokeViewApi';
  const INVOKE_SERVICE_API = 'invokeServiceApi';
fxy060608's avatar
fxy060608 已提交
6373

fxy060608's avatar
fxy060608 已提交
6374 6375 6376 6377 6378 6379 6380
  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;
fxy060608's avatar
fxy060608 已提交
6381 6382 6383
  const ACTION_TYPE_ADD_EVENT = 8;
  const ACTION_TYPE_REMOVE_EVENT = 9;
  const ACTION_TYPE_SET_TEXT = 10;
fxy060608's avatar
fxy060608 已提交
6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408
  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 已提交
6409 6410 6411 6412 6413 6414 6415
  function initNVue(webviewStyle, routeMeta, path) {
      if (path && routeMeta.isNVue) {
          webviewStyle.uniNView = {
              path,
              defaultFontSize: __uniConfig.defaultFontSize,
              viewport: __uniConfig.viewport,
          };
fxy060608's avatar
fxy060608 已提交
6416 6417 6418
      }
  }

fxy060608's avatar
fxy060608 已提交
6419 6420 6421 6422 6423 6424 6425 6426
  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 已提交
6427 6428
          return;
      }
fxy060608's avatar
fxy060608 已提交
6429
      if (!isColor(backgroundColor)) {
fxy060608's avatar
fxy060608 已提交
6430 6431
          return;
      }
fxy060608's avatar
fxy060608 已提交
6432 6433
      if (!webviewStyle.background) {
          webviewStyle.background = backgroundColor;
fxy060608's avatar
fxy060608 已提交
6434
      }
fxy060608's avatar
fxy060608 已提交
6435 6436
      if (!webviewStyle.backgroundColorTop) {
          webviewStyle.backgroundColorTop = backgroundColor;
fxy060608's avatar
fxy060608 已提交
6437 6438 6439
      }
  }

fxy060608's avatar
fxy060608 已提交
6440 6441 6442 6443
  function initPopGesture(webviewStyle, routeMeta) {
      // 不支持 hide
      if (webviewStyle.popGesture === 'hide') {
          delete webviewStyle.popGesture;
fxy060608's avatar
fxy060608 已提交
6444
      }
fxy060608's avatar
fxy060608 已提交
6445 6446 6447
      // 似乎没用了吧?记得是之前流应用时,需要 appback 的逻辑
      if (routeMeta.isQuit) {
          webviewStyle.popGesture = (plus.os.name === 'iOS' ? 'appback' : 'none');
fxy060608's avatar
fxy060608 已提交
6448
      }
fxy060608's avatar
fxy060608 已提交
6449 6450 6451 6452 6453
  }

  function initPullToRefresh(webviewStyle, routeMeta) {
      if (!routeMeta.enablePullDownRefresh) {
          return;
fxy060608's avatar
fxy060608 已提交
6454
      }
fxy060608's avatar
fxy060608 已提交
6455 6456 6457
      webviewStyle.pullToRefresh = normalizePullToRefreshRpx(extend({}, plus.os.name === 'Android'
          ? defaultAndroidPullToRefresh
          : defaultPullToRefresh, routeMeta.pullToRefresh));
fxy060608's avatar
fxy060608 已提交
6458
  }
fxy060608's avatar
fxy060608 已提交
6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479
  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 已提交
6480
      }
fxy060608's avatar
fxy060608 已提交
6481 6482 6483
      let autoBackButton = true;
      if (routeMeta.isQuit) {
          autoBackButton = false;
fxy060608's avatar
fxy060608 已提交
6484
      }
fxy060608's avatar
fxy060608 已提交
6485 6486 6487 6488 6489 6490 6491 6492 6493
      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 已提交
6494
          }
fxy060608's avatar
fxy060608 已提交
6495 6496
          else if (name === 'titleImage' && value) {
              titleNView.tags = createTitleImageTags(value);
fxy060608's avatar
fxy060608 已提交
6497
          }
fxy060608's avatar
fxy060608 已提交
6498 6499 6500 6501
          else if (name === 'buttons' && isArray(value)) {
              titleNView.buttons = value.map((button, index) => {
                  button.onclick = createTitleNViewBtnClick(index);
                  return button;
fxy060608's avatar
fxy060608 已提交
6502 6503
              });
          }
fxy060608's avatar
fxy060608 已提交
6504 6505 6506 6507
          else {
              titleNView[name] =
                  value;
          }
fxy060608's avatar
fxy060608 已提交
6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531
      });
      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 已提交
6532
  function parseWebviewStyle(path, routeMeta) {
fxy060608's avatar
fxy060608 已提交
6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 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 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587
      const webviewStyle = {
          bounce: 'vertical',
      };
      Object.keys(routeMeta).forEach((name) => {
          if (WEBVIEW_STYLE_BLACKLIST.indexOf(name) === -1) {
              webviewStyle[name] =
                  routeMeta[name];
          }
      });
      initNVue(webviewStyle, routeMeta, path);
      initPopGesture(webviewStyle, routeMeta);
      initBackgroundColor(webviewStyle, routeMeta);
      initTitleNView(webviewStyle, routeMeta);
      initPullToRefresh(webviewStyle, routeMeta);
      return webviewStyle;
  }
  const WEBVIEW_STYLE_BLACKLIST = [
      'id',
      'route',
      'isNVue',
      'isQuit',
      'isEntry',
      'isTabBar',
      'tabBarIndex',
      'windowTop',
      'topWindow',
      'leftWindow',
      'rightWindow',
      'maxWidth',
      'usingComponents',
      'disableScroll',
      'enablePullDownRefresh',
      'navigationBar',
      'pullToRefresh',
      'onReachBottomDistance',
      'pageOrientation',
      'backgroundColor',
  ];

  let id = 2;
  function getWebviewId() {
      return id;
  }
  function genWebviewId() {
      return id++;
  }
  function encode(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 已提交
6588 6589 6590 6591 6592 6593 6594 6595 6596 6597
  }
  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 已提交
6598 6599 6600 6601
  }

  function createNVueWebview({ path, query, routeOptions, webviewStyle, }) {
      const curWebviewId = genWebviewId();
fxy060608's avatar
fxy060608 已提交
6602
      const curWebviewStyle = parseWebviewStyle(path, routeOptions.meta);
fxy060608's avatar
fxy060608 已提交
6603 6604
      curWebviewStyle.uniPageUrl = initUniPageUrl(path, query);
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
6605
          console.log(formatLog('createNVueWebview', curWebviewId, path, curWebviewStyle));
fxy060608's avatar
fxy060608 已提交
6606 6607 6608 6609 6610 6611 6612
      }
      curWebviewStyle.isTab = !!routeOptions.meta.isTabBar;
      return plus.webview.create('', String(curWebviewId), curWebviewStyle, extend({
          nvue: true,
      }, webviewStyle));
  }

fxy060608's avatar
fxy060608 已提交
6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637
  const downgrade = plus.os.name === 'Android' && parseInt(plus.os.version) < 6;
  const ANI_SHOW = downgrade ? 'slide-in-right' : 'pop-in';
  const ANI_DURATION = 300;
  const ANI_CLOSE = downgrade ? 'slide-out-right' : 'pop-out';
  const VIEW_WEBVIEW_PATH = '_www/__uniappview.html';
  const WEBVIEW_ID_PREFIX = 'webviewId';

  let preloadWebview;
  function setPreloadWebview(webview) {
      preloadWebview = webview;
  }
  function getPreloadWebview() {
      return preloadWebview;
  }
  function createPreloadWebview() {
      if (!preloadWebview || preloadWebview.__uniapp_route) {
          // 不存在,或已被使用
          preloadWebview = plus.webview.create(VIEW_WEBVIEW_PATH, String(genWebviewId()));
          if ((process.env.NODE_ENV !== 'production')) {
              console.log(formatLog('createPreloadWebview', preloadWebview.id));
          }
      }
      return preloadWebview;
  }

fxy060608's avatar
fxy060608 已提交
6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649
  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 已提交
6650
          console.log(formatLog('updateWebview', webviewStyle));
fxy060608's avatar
fxy060608 已提交
6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661
      }
      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 已提交
6662 6663 6664 6665 6666 6667 6668 6669 6670
  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 已提交
6671 6672 6673
  }
  function onWebviewReady(pageId, callback) {
      UniServiceJSBridge.once(ON_WEBVIEW_READY + '.' + pageId, callback);
fxy060608's avatar
fxy060608 已提交
6674 6675
  }

fxy060608's avatar
fxy060608 已提交
6676 6677 6678 6679 6680 6681
  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 已提交
6682
          }
fxy060608's avatar
fxy060608 已提交
6683
          return;
fxy060608's avatar
fxy060608 已提交
6684
      }
fxy060608's avatar
fxy060608 已提交
6685 6686 6687 6688
      if (isLaunchWebview) {
          // 首页
          isLaunchWebviewReady = true;
          setPreloadWebview(plus.webview.getLaunchWebview());
fxy060608's avatar
fxy060608 已提交
6689
      }
fxy060608's avatar
fxy060608 已提交
6690 6691 6692
      else if (!preloadWebview) {
          // preloadWebview 不存在,重新加载一下
          setPreloadWebview(plus.webview.getWebviewById(pageId));
fxy060608's avatar
fxy060608 已提交
6693
      }
fxy060608's avatar
fxy060608 已提交
6694 6695
      if (preloadWebview.id !== pageId) {
          return console.error(`webviewReady[${preloadWebview.id}][${pageId}] not match`);
fxy060608's avatar
fxy060608 已提交
6696
      }
fxy060608's avatar
fxy060608 已提交
6697 6698 6699
      preloadWebview.loaded = true; // 标记已 ready
      UniServiceJSBridge.emit(ON_WEBVIEW_READY + '.' + pageId);
      isLaunchWebview && onLaunchWebviewReady();
fxy060608's avatar
fxy060608 已提交
6700
  }
fxy060608's avatar
fxy060608 已提交
6701 6702 6703 6704
  function onLaunchWebviewReady() {
      const { autoclose, alwaysShowBeforeRender } = __uniConfig.splashscreen;
      if (autoclose && !alwaysShowBeforeRender) {
          plus.navigator.closeSplashscreen();
fxy060608's avatar
fxy060608 已提交
6705
      }
fxy060608's avatar
fxy060608 已提交
6706 6707 6708 6709 6710 6711 6712 6713 6714 6715
      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 已提交
6716
          }
fxy060608's avatar
fxy060608 已提交
6717
          return uni.navigateTo(args);
fxy060608's avatar
fxy060608 已提交
6718
      }
fxy060608's avatar
fxy060608 已提交
6719 6720
  }

fxy060608's avatar
fxy060608 已提交
6721 6722 6723 6724 6725 6726 6727 6728
  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 已提交
6729
          subscribe(VD_SYNC, onVdSync);
fxy060608's avatar
fxy060608 已提交
6730
          subscribe(INVOKE_SERVICE_API, onInvokeServiceApi);
fxy060608's avatar
fxy060608 已提交
6731
      }
fxy060608's avatar
fxy060608 已提交
6732
  }
fxy060608's avatar
fxy060608 已提交
6733
  function onInvokeServiceApi({ data: { method, args }, }) {
fxy060608's avatar
fxy060608 已提交
6734
      uni[method] && uni[method](args);
fxy060608's avatar
fxy060608 已提交
6735 6736
  }

fxy060608's avatar
fxy060608 已提交
6737 6738 6739 6740 6741 6742 6743 6744
  let appCtx;
  const defaultApp = {
      globalData: {},
  };
  function getApp$1({ allowDefault = false } = {}) {
      if (appCtx) {
          // 真实的 App 已初始化
          return appCtx;
fxy060608's avatar
fxy060608 已提交
6745
      }
fxy060608's avatar
fxy060608 已提交
6746 6747 6748
      if (allowDefault) {
          // 返回默认实现
          return defaultApp;
fxy060608's avatar
fxy060608 已提交
6749
      }
fxy060608's avatar
fxy060608 已提交
6750 6751 6752 6753
      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 已提交
6754
          console.log(formatLog('registerApp'));
fxy060608's avatar
fxy060608 已提交
6755
      }
fxy060608's avatar
fxy060608 已提交
6756 6757 6758 6759 6760 6761
      appCtx = appVm;
      appCtx.$vm = appVm;
      extend(appCtx, defaultApp); // 拷贝默认实现
      const { $options } = appVm;
      if ($options) {
          appCtx.globalData = extend($options.globalData || {}, appCtx.globalData);
fxy060608's avatar
fxy060608 已提交
6762
      }
fxy060608's avatar
fxy060608 已提交
6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786
      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 已提交
6787
          }
fxy060608's avatar
fxy060608 已提交
6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800
          return instance;
      };
  }

  const EventType = {
      load: 'load',
      close: 'close',
      error: 'error',
      adClicked: 'adClicked',
  };
  class AdEventHandler {
      constructor() {
          this._callbacks = {};
fxy060608's avatar
fxy060608 已提交
6801
      }
fxy060608's avatar
fxy060608 已提交
6802 6803
      onLoad(callback) {
          this._addEventListener(EventType.load, callback);
fxy060608's avatar
fxy060608 已提交
6804
      }
fxy060608's avatar
fxy060608 已提交
6805 6806
      onClose(callback) {
          this._addEventListener(EventType.close, callback);
fxy060608's avatar
fxy060608 已提交
6807
      }
fxy060608's avatar
fxy060608 已提交
6808 6809
      onError(callback) {
          this._addEventListener(EventType.error, callback);
fxy060608's avatar
fxy060608 已提交
6810
      }
fxy060608's avatar
fxy060608 已提交
6811 6812
      offLoad(callback) {
          this._removeEventListener(EventType.load, callback);
fxy060608's avatar
fxy060608 已提交
6813
      }
fxy060608's avatar
fxy060608 已提交
6814 6815
      offClose(callback) {
          this._removeEventListener(EventType.close, callback);
fxy060608's avatar
fxy060608 已提交
6816
      }
fxy060608's avatar
fxy060608 已提交
6817 6818
      offError(callback) {
          this._removeEventListener(EventType.error, callback);
fxy060608's avatar
fxy060608 已提交
6819
      }
fxy060608's avatar
fxy060608 已提交
6820 6821 6822 6823 6824
      _addEventListener(type, callback) {
          if (typeof callback !== 'function') {
              return;
          }
          this._callbacks[type].push(callback);
fxy060608's avatar
fxy060608 已提交
6825
      }
fxy060608's avatar
fxy060608 已提交
6826 6827 6828 6829 6830
      _removeEventListener(type, callback) {
          const arrayFunction = this._callbacks[type];
          const index = arrayFunction.indexOf(callback);
          if (index > -1) {
              arrayFunction.splice(index, 1);
fxy060608's avatar
fxy060608 已提交
6831 6832
          }
      }
fxy060608's avatar
fxy060608 已提交
6833 6834 6835 6836
      _dispatchEvent(name, data) {
          this._callbacks[name].forEach((callback) => {
              callback(data || {});
          });
fxy060608's avatar
fxy060608 已提交
6837 6838
      }
  }
fxy060608's avatar
fxy060608 已提交
6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893
  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 已提交
6894
      }
fxy060608's avatar
fxy060608 已提交
6895 6896 6897 6898 6899 6900 6901 6902 6903
      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 已提交
6904
              }
fxy060608's avatar
fxy060608 已提交
6905 6906 6907 6908 6909 6910 6911
              if (this._isLoaded) {
                  resolve('');
              }
              else {
                  this._loadAd();
              }
          });
fxy060608's avatar
fxy060608 已提交
6912
      }
fxy060608's avatar
fxy060608 已提交
6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927
      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 已提交
6928
      }
fxy060608's avatar
fxy060608 已提交
6929 6930
      destroy() {
          this._adInstance.destroy();
fxy060608's avatar
fxy060608 已提交
6931
      }
fxy060608's avatar
fxy060608 已提交
6932 6933 6934 6935
      _loadAd() {
          this._isLoaded = false;
          this._isLoading = true;
          this._adInstance.load();
fxy060608's avatar
fxy060608 已提交
6936
      }
fxy060608's avatar
fxy060608 已提交
6937 6938
      _showAd() {
          this._adInstance.show();
fxy060608's avatar
fxy060608 已提交
6939 6940 6941
      }
  }

fxy060608's avatar
fxy060608 已提交
6942 6943 6944 6945
  class RewardedVideoAd extends AdBase {
      constructor(options) {
          super(plus.ad.createRewardedVideoAd(options), options);
          this._loadAd();
fxy060608's avatar
fxy060608 已提交
6946
      }
fxy060608's avatar
fxy060608 已提交
6947 6948 6949 6950 6951 6952 6953 6954
  }
  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 已提交
6955
      }
fxy060608's avatar
fxy060608 已提交
6956 6957 6958 6959 6960 6961 6962 6963 6964
  }
  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 已提交
6965
      }
fxy060608's avatar
fxy060608 已提交
6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976
  }
  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 已提交
6977
      }
fxy060608's avatar
fxy060608 已提交
6978 6979
      if (typeof sdkCache[provider].plugin === 'object') {
          options.success(sdkCache[provider].plugin);
fxy060608's avatar
fxy060608 已提交
6980 6981
          return;
      }
fxy060608's avatar
fxy060608 已提交
6982 6983
      if (!sdkQueue[provider]) {
          sdkQueue[provider] = [];
fxy060608's avatar
fxy060608 已提交
6984
      }
fxy060608's avatar
fxy060608 已提交
6985 6986 6987
      sdkQueue[provider].push(options);
      if (sdkCache[provider].status === true) {
          options.__plugin = sdkCache[provider].plugin;
fxy060608's avatar
fxy060608 已提交
6988 6989
          return;
      }
fxy060608's avatar
fxy060608 已提交
6990 6991 6992 6993 6994 6995 6996 6997
      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 已提交
6998
          });
fxy060608's avatar
fxy060608 已提交
6999 7000 7001
          sdkQueue[provider].length = 0;
          sdkCache[provider].status = false;
          return;
fxy060608's avatar
fxy060608 已提交
7002
      }
fxy060608's avatar
fxy060608 已提交
7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020
      // 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 已提交
7021
          });
fxy060608's avatar
fxy060608 已提交
7022 7023
          sdkQueue[provider].length = 0;
      });
fxy060608's avatar
fxy060608 已提交
7024
  }
fxy060608's avatar
fxy060608 已提交
7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044
  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 已提交
7045
      }
fxy060608's avatar
fxy060608 已提交
7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065
      _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 已提交
7066
      }
fxy060608's avatar
fxy060608 已提交
7067 7068
      getProvider() {
          return this._provider;
fxy060608's avatar
fxy060608 已提交
7069
      }
fxy060608's avatar
fxy060608 已提交
7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086
      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 已提交
7087
          });
fxy060608's avatar
fxy060608 已提交
7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106
      }
      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 已提交
7107
          });
fxy060608's avatar
fxy060608 已提交
7108 7109 7110 7111
      }
      reportExposure() {
          if (this._adInstance !== null) {
              this._adInstance.reportExposure();
fxy060608's avatar
fxy060608 已提交
7112
          }
fxy060608's avatar
fxy060608 已提交
7113 7114 7115 7116
      }
      bindUserData(data) {
          if (this._adInstance !== null) {
              this._adInstance.bindUserData(data);
fxy060608's avatar
fxy060608 已提交
7117
          }
fxy060608's avatar
fxy060608 已提交
7118 7119 7120 7121 7122
      }
      destroy() {
          if (this._adInstance !== null && this._adInstance.destroy) {
              this._adInstance.destroy({
                  adpid: this._adpid,
fxy060608's avatar
fxy060608 已提交
7123 7124
              });
          }
fxy060608's avatar
fxy060608 已提交
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 7153 7154
      }
      _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 已提交
7155
          }
fxy060608's avatar
fxy060608 已提交
7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167
      }
      _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 已提交
7168
                  }
fxy060608's avatar
fxy060608 已提交
7169
                  this._dispatchEvent(EventType.error, err);
fxy060608's avatar
fxy060608 已提交
7170
              });
fxy060608's avatar
fxy060608 已提交
7171
          }
fxy060608's avatar
fxy060608 已提交
7172
      }
fxy060608's avatar
fxy060608 已提交
7173 7174
      _createError(err) {
          return new Error(JSON.stringify(err));
fxy060608's avatar
fxy060608 已提交
7175
      }
fxy060608's avatar
fxy060608 已提交
7176 7177 7178 7179
  }
  const createInteractiveAd = (defineSyncApi(API_CREATE_INTERACTIVE_AD, (options) => {
      return new InteractiveAd(options);
  }, CreateInteractiveAdProtocol, CreateInteractiveAdOptions));
fxy060608's avatar
fxy060608 已提交
7180

fxy060608's avatar
fxy060608 已提交
7181 7182 7183 7184 7185 7186 7187 7188
  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 已提交
7189
          console.log(formatLog('setPendingNavigator', path, msg));
fxy060608's avatar
fxy060608 已提交
7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209
      }
  }
  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 已提交
7210 7211
      }
      else {
fxy060608's avatar
fxy060608 已提交
7212 7213 7214 7215
          callback();
      }
      if (waitPreloadWebviewReady) {
          onWebviewReady(preloadWebview.id, pendingNavigate);
fxy060608's avatar
fxy060608 已提交
7216 7217
      }
  }
fxy060608's avatar
fxy060608 已提交
7218 7219 7220 7221 7222 7223
  function pendingNavigate() {
      if (!pendingNavigator) {
          return;
      }
      const { callback } = pendingNavigator;
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
7224
          console.log(formatLog('pendingNavigate', pendingNavigator.path));
fxy060608's avatar
fxy060608 已提交
7225
      }
fxy060608's avatar
fxy060608 已提交
7226 7227
      pendingNavigator = false;
      return callback();
fxy060608's avatar
fxy060608 已提交
7228
  }
fxy060608's avatar
fxy060608 已提交
7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241
  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 已提交
7242
          console.log(formatLog('navigateFinish', 'preloadWebview', preloadWebview.id));
fxy060608's avatar
fxy060608 已提交
7243 7244 7245 7246 7247 7248 7249 7250 7251 7252
      }
      if (!pendingNavigator) {
          return;
      }
      if (pendingNavigator.nvue) {
          return pendingNavigate();
      }
      preloadWebview.loaded
          ? pendingNavigator.callback()
          : onWebviewReady(preloadWebview.id, pendingNavigate);
fxy060608's avatar
fxy060608 已提交
7253 7254
  }

fxy060608's avatar
fxy060608 已提交
7255 7256 7257
  function closeWebview(webview, animationType, animationDuration) {
      webview[webview.__preload__ ? 'hide' : 'close'](animationType, animationDuration);
  }
fxy060608's avatar
fxy060608 已提交
7258 7259 7260 7261 7262
  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 已提交
7263
          console.log(formatLog('showWebview', 'delay', delay));
fxy060608's avatar
fxy060608 已提交
7264 7265 7266 7267
      }
      const execShowCallback = function () {
          if (execShowCallback._called) {
              if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
7268
                  console.log(formatLog('execShowCallback', 'prevent'));
fxy060608's avatar
fxy060608 已提交
7269 7270 7271 7272 7273 7274
              }
              return;
          }
          execShowCallback._called = true;
          showCallback && showCallback();
          navigateFinish();
fxy060608's avatar
fxy060608 已提交
7275
      };
fxy060608's avatar
fxy060608 已提交
7276 7277 7278 7279
      execShowCallback._called = false;
      setTimeout(() => {
          const timer = setTimeout(() => {
              if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
7280
                  console.log(formatLog('showWebview', 'callback', 'timer'));
fxy060608's avatar
fxy060608 已提交
7281 7282 7283 7284 7285
              }
              execShowCallback();
          }, animationDuration + 150);
          webview.show(animationType, animationDuration, () => {
              if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
7286
                  console.log(formatLog('showWebview', 'callback'));
fxy060608's avatar
fxy060608 已提交
7287 7288 7289
              }
              if (!execShowCallback._called) {
                  clearTimeout(timer);
fxy060608's avatar
fxy060608 已提交
7290
              }
fxy060608's avatar
fxy060608 已提交
7291
              execShowCallback();
fxy060608's avatar
fxy060608 已提交
7292
          });
fxy060608's avatar
fxy060608 已提交
7293
      }, delay);
fxy060608's avatar
fxy060608 已提交
7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311
  }
  function backWebview(webview, callback) {
      const children = webview.children();
      if (!children || !children.length) {
          // 有子 webview
          return callback();
      }
      // 如果页面有subNvues,切使用了webview组件,则返回时子webview会取错,因此需要做id匹配
      const childWebview = children.find((webview) => webview.id.indexOf(WEBVIEW_ID_PREFIX) === 0) ||
          children[0];
      childWebview.canBack(({ canBack }) => {
          if (canBack) {
              childWebview.back(); // webview 返回
          }
          else {
              callback();
          }
      });
fxy060608's avatar
fxy060608 已提交
7312 7313
  }

fxy060608's avatar
fxy060608 已提交
7314 7315 7316 7317
  class UniPageNode extends UniNode {
      constructor(pageId, options, setup = false) {
          super(NODE_TYPE_PAGE, '#page', null);
          this._id = 1;
fxy060608's avatar
fxy060608 已提交
7318
          this._created = false;
fxy060608's avatar
fxy060608 已提交
7319
          this._createActionMap = new Map();
fxy060608's avatar
fxy060608 已提交
7320 7321 7322 7323
          this.updateActions = [];
          this.nodeId = 0;
          this.pageId = pageId;
          this.pageNode = this;
fxy060608's avatar
fxy060608 已提交
7324
          this.isUnmounted = false;
fxy060608's avatar
fxy060608 已提交
7325 7326
          this.createAction = [ACTION_TYPE_PAGE_CREATE, options];
          this.createdAction = [ACTION_TYPE_PAGE_CREATED];
fxy060608's avatar
fxy060608 已提交
7327
          this._update = this.update.bind(this);
fxy060608's avatar
fxy060608 已提交
7328 7329 7330 7331 7332 7333
          setup && this.setup();
      }
      onCreate(thisNode, nodeName) {
          pushCreateAction(this, thisNode.nodeId, nodeName);
          return thisNode;
      }
fxy060608's avatar
fxy060608 已提交
7334 7335
      onInsertBefore(thisNode, newChild, refChild) {
          pushInsertAction(this, newChild, thisNode.nodeId, (refChild && refChild.nodeId) || -1);
fxy060608's avatar
fxy060608 已提交
7336 7337
          return newChild;
      }
fxy060608's avatar
fxy060608 已提交
7338 7339
      onRemoveChild(oldChild) {
          pushRemoveAction(this, oldChild.nodeId);
fxy060608's avatar
fxy060608 已提交
7340 7341
          return oldChild;
      }
fxy060608's avatar
fxy060608 已提交
7342 7343 7344 7345 7346 7347 7348 7349 7350 7351
      onAddEvent(thisNode, name, flag) {
          if (thisNode.parentNode) {
              pushAddEventAction(this, thisNode.nodeId, name, flag);
          }
      }
      onRemoveEvent(thisNode, name) {
          if (thisNode.parentNode) {
              pushRemoveEventAction(this, thisNode.nodeId, name);
          }
      }
fxy060608's avatar
fxy060608 已提交
7352 7353 7354
      onSetAttribute(thisNode, qualifiedName, value) {
          if (thisNode.parentNode) {
              pushSetAttributeAction(this, thisNode.nodeId, qualifiedName, value);
fxy060608's avatar
fxy060608 已提交
7355
          }
fxy060608's avatar
fxy060608 已提交
7356
      }
fxy060608's avatar
fxy060608 已提交
7357 7358 7359 7360
      onRemoveAttribute(thisNode, qualifiedName) {
          if (thisNode.parentNode) {
              pushRemoveAttributeAction(this, thisNode.nodeId, qualifiedName);
          }
fxy060608's avatar
fxy060608 已提交
7361
      }
fxy060608's avatar
fxy060608 已提交
7362 7363 7364 7365
      onTextContent(thisNode, text) {
          if (thisNode.parentNode) {
              pushSetTextAction(this, thisNode.nodeId, text);
          }
fxy060608's avatar
fxy060608 已提交
7366
      }
fxy060608's avatar
fxy060608 已提交
7367 7368 7369 7370
      onNodeValue(thisNode, val) {
          if (thisNode.parentNode) {
              pushSetTextAction(this, thisNode.nodeId, val);
          }
fxy060608's avatar
fxy060608 已提交
7371
      }
fxy060608's avatar
fxy060608 已提交
7372 7373
      genId() {
          return this._id++;
fxy060608's avatar
fxy060608 已提交
7374
      }
fxy060608's avatar
fxy060608 已提交
7375
      push(action, extras) {
fxy060608's avatar
fxy060608 已提交
7376 7377 7378 7379 7380 7381
          if (this.isUnmounted) {
              if ((process.env.NODE_ENV !== 'production')) {
                  console.log(formatLog('PageNode', 'push.prevent', action));
              }
              return;
          }
fxy060608's avatar
fxy060608 已提交
7382 7383 7384 7385 7386 7387 7388
          switch (action[0]) {
              case ACTION_TYPE_CREATE:
                  this._createActionMap.set(action[1], action);
                  break;
              case ACTION_TYPE_INSERT:
                  const createAction = this._createActionMap.get(action[1]);
                  if (createAction) {
fxy060608's avatar
fxy060608 已提交
7389 7390 7391 7392
                      createAction[3] = action[2]; // parentNodeId
                      if (extras) {
                          createAction[4] = extras;
                      }
fxy060608's avatar
fxy060608 已提交
7393 7394 7395 7396 7397 7398 7399 7400
                  }
                  else {
                      if ((process.env.NODE_ENV !== 'production')) {
                          console.error(formatLog(`Insert`, action, 'not found createAction'));
                      }
                  }
                  break;
          }
fxy060608's avatar
fxy060608 已提交
7401
          this.updateActions.push(action);
fxy060608's avatar
fxy060608 已提交
7402
          vue.queuePostFlushCb(this._update);
fxy060608's avatar
fxy060608 已提交
7403 7404 7405 7406 7407 7408 7409 7410 7411 7412
      }
      restore() {
          this.push(this.createAction);
          // TODO restore children
          this.push(this.createdAction);
      }
      setup() {
          this.send([this.createAction]);
      }
      update() {
fxy060608's avatar
fxy060608 已提交
7413
          const { updateActions, _createActionMap } = this;
fxy060608's avatar
fxy060608 已提交
7414
          if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
7415
              console.log(formatLog('PageNode', 'update', updateActions.length, _createActionMap.size));
fxy060608's avatar
fxy060608 已提交
7416
          }
fxy060608's avatar
fxy060608 已提交
7417
          _createActionMap.clear();
fxy060608's avatar
fxy060608 已提交
7418 7419 7420 7421 7422
          // 首次
          if (!this._created) {
              this._created = true;
              updateActions.push(this.createdAction);
          }
fxy060608's avatar
fxy060608 已提交
7423 7424 7425
          if (updateActions.length) {
              this.send(updateActions);
              updateActions.length = 0;
fxy060608's avatar
fxy060608 已提交
7426
          }
fxy060608's avatar
fxy060608 已提交
7427
      }
fxy060608's avatar
fxy060608 已提交
7428
      send(action) {
fxy060608's avatar
fxy060608 已提交
7429
          UniServiceJSBridge.publishHandler(VD_SYNC, action, this.pageId);
fxy060608's avatar
fxy060608 已提交
7430
      }
fxy060608's avatar
fxy060608 已提交
7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452
      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 已提交
7453 7454
  }
  function pushCreateAction(pageNode, nodeId, nodeName) {
fxy060608's avatar
fxy060608 已提交
7455
      pageNode.push([ACTION_TYPE_CREATE, nodeId, nodeName, -1]);
fxy060608's avatar
fxy060608 已提交
7456
  }
fxy060608's avatar
fxy060608 已提交
7457
  function pushInsertAction(pageNode, newChild, parentNodeId, refChildId) {
fxy060608's avatar
fxy060608 已提交
7458 7459
      const nodeJson = newChild.toJSON({ attr: true });
      pageNode.push([ACTION_TYPE_INSERT, newChild.nodeId, parentNodeId, refChildId], Object.keys(nodeJson).length ? nodeJson : undefined);
fxy060608's avatar
fxy060608 已提交
7460
  }
fxy060608's avatar
fxy060608 已提交
7461 7462
  function pushRemoveAction(pageNode, nodeId) {
      pageNode.push([ACTION_TYPE_REMOVE, nodeId]);
fxy060608's avatar
fxy060608 已提交
7463
  }
fxy060608's avatar
fxy060608 已提交
7464 7465 7466 7467 7468 7469
  function pushAddEventAction(pageNode, nodeId, name, value) {
      pageNode.push([ACTION_TYPE_ADD_EVENT, nodeId, name, value]);
  }
  function pushRemoveEventAction(pageNode, nodeId, name) {
      pageNode.push([ACTION_TYPE_REMOVE_EVENT, nodeId, name]);
  }
fxy060608's avatar
fxy060608 已提交
7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480
  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 已提交
7481 7482
  }

fxy060608's avatar
fxy060608 已提交
7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499
  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 已提交
7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512
  }
  function removePage(curPage) {
      const index = pages.findIndex((page) => page === curPage);
      if (index === -1) {
          return;
      }
      if (!curPage.$page.meta.isNVue) {
          curPage.$.appContext.app.unmount();
      }
      pages.splice(index, 1);
      if ((process.env.NODE_ENV !== 'production')) {
          console.log(formatLog('removePage', curPage.$page));
      }
fxy060608's avatar
fxy060608 已提交
7513 7514
  }

fxy060608's avatar
fxy060608 已提交
7515
  function setupPage(component) {
fxy060608's avatar
fxy060608 已提交
7516
      const oldSetup = component.setup;
fxy060608's avatar
fxy060608 已提交
7517 7518 7519
      component.inheritAttrs = false; // 禁止继承 __pageId 等属性,避免告警
      component.setup = (_, ctx) => {
          const { attrs: { __pageId, __pagePath, __pageQuery, __pageInstance }, } = ctx;
fxy060608's avatar
fxy060608 已提交
7520
          if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
7521
              console.log(formatLog(__pagePath, 'setup'));
fxy060608's avatar
fxy060608 已提交
7522 7523 7524
          }
          const instance = vue.getCurrentInstance();
          const pageVm = instance.proxy;
fxy060608's avatar
fxy060608 已提交
7525 7526
          pageVm.$page = __pageInstance;
          addCurrentPage(initScope(__pageId, pageVm));
fxy060608's avatar
fxy060608 已提交
7527
          if (oldSetup) {
fxy060608's avatar
fxy060608 已提交
7528
              return oldSetup(__pageQuery, ctx);
fxy060608's avatar
fxy060608 已提交
7529 7530
          }
      };
fxy060608's avatar
fxy060608 已提交
7531 7532 7533
      return component;
  }
  function initScope(pageId, vm) {
fxy060608's avatar
fxy060608 已提交
7534 7535 7536 7537
      const $getAppWebview = () => {
          return plus.webview.getWebviewById(pageId + '');
      };
      vm.$getAppWebview = $getAppWebview;
fxy060608's avatar
fxy060608 已提交
7538
      vm.$scope = {
fxy060608's avatar
fxy060608 已提交
7539
          $getAppWebview,
fxy060608's avatar
fxy060608 已提交
7540 7541
      };
      return vm;
fxy060608's avatar
fxy060608 已提交
7542 7543
  }

fxy060608's avatar
fxy060608 已提交
7544 7545 7546 7547
  const pagesMap = new Map();
  function definePage(pagePath, component) {
      pagesMap.set(pagePath, once(createFactory(component)));
  }
fxy060608's avatar
fxy060608 已提交
7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561
  function createPage(__pageId, __pagePath, __pageQuery, __pageInstance, pageOptions) {
      const pageNode = createPageNode(__pageId, pageOptions, true);
      const app = vue.createApp(pagesMap.get(__pagePath)(), {
          __pageId,
          __pagePath,
          __pageQuery,
          __pageInstance,
      }).use(__vuePlugin);
      const oldUnmount = app.unmount;
      app.unmount = () => {
          pageNode.isUnmounted = true;
          return oldUnmount.call(app);
      };
      return app.mount(pageNode);
fxy060608's avatar
fxy060608 已提交
7562 7563
  }
  function createFactory(component) {
fxy060608's avatar
fxy060608 已提交
7564 7565
      return () => {
          return setupPage(component);
fxy060608's avatar
fxy060608 已提交
7566 7567 7568
      };
  }

fxy060608's avatar
fxy060608 已提交
7569 7570
  function initRouteOptions(path, openType) {
      // 需要序列化一遍
fxy060608's avatar
fxy060608 已提交
7571
      const routeOptions = JSON.parse(JSON.stringify(getRouteOptions(path)));
fxy060608's avatar
fxy060608 已提交
7572
      routeOptions.meta = initRouteMeta(routeOptions.meta);
fxy060608's avatar
fxy060608 已提交
7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587
      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 已提交
7588 7589 7590 7591 7592 7593 7594 7595 7596
  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 已提交
7597
  function registerPage({ url, path, query, openType, webview, vm, }) {
fxy060608's avatar
fxy060608 已提交
7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610
      // 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 已提交
7611
      routeOptions.meta.id = parseInt(webview.id);
fxy060608's avatar
fxy060608 已提交
7612 7613 7614 7615
      const isTabBar = !!routeOptions.meta.isTabBar;
      if (isTabBar) {
          tabBar$1.append(webview);
      }
fxy060608's avatar
fxy060608 已提交
7616
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
7617
          console.log(formatLog('registerPage', path, webview.id));
fxy060608's avatar
fxy060608 已提交
7618
      }
fxy060608's avatar
fxy060608 已提交
7619
      initWebview(webview, path, query, routeOptions.meta);
fxy060608's avatar
fxy060608 已提交
7620
      const route = path.substr(1);
fxy060608's avatar
fxy060608 已提交
7621
      webview.__uniapp_route = route;
fxy060608's avatar
fxy060608 已提交
7622
      const pageInstance = initPageInternalInstance(openType, url, query, routeOptions.meta);
fxy060608's avatar
fxy060608 已提交
7623
      if (!webview.nvue) {
fxy060608's avatar
fxy060608 已提交
7624 7625 7626 7627
          createPage(parseInt(webview.id), route, query, pageInstance, initPageOptions(routeOptions));
      }
      else {
          vm && addCurrentPage(vm);
fxy060608's avatar
fxy060608 已提交
7628
      }
fxy060608's avatar
fxy060608 已提交
7629
      return webview;
fxy060608's avatar
fxy060608 已提交
7630 7631 7632
  }
  function initPageOptions({ meta }) {
      const statusbarHeight = getStatusbarHeight();
fxy060608's avatar
fxy060608 已提交
7633
      const { platform, pixelRatio, windowWidth } = getBaseSystemInfo();
fxy060608's avatar
fxy060608 已提交
7634
      return {
fxy060608's avatar
fxy060608 已提交
7635
          css: true,
fxy060608's avatar
fxy060608 已提交
7636
          route: meta.route,
fxy060608's avatar
fxy060608 已提交
7637 7638
          version: 1,
          locale: '',
fxy060608's avatar
fxy060608 已提交
7639 7640 7641
          platform,
          pixelRatio,
          windowWidth,
fxy060608's avatar
fxy060608 已提交
7642 7643 7644 7645 7646 7647 7648 7649 7650 7651
          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 已提交
7652
  }
fxy060608's avatar
fxy060608 已提交
7653

fxy060608's avatar
fxy060608 已提交
7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692
  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 已提交
7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721
  let lastStatusBarStyle;
  let oldSetStatusBarStyle = plus.navigator.setStatusBarStyle;
  function newSetStatusBarStyle(style) {
      lastStatusBarStyle = style;
      oldSetStatusBarStyle(style);
  }
  plus.navigator.setStatusBarStyle = newSetStatusBarStyle;
  function setStatusBarStyle(statusBarStyle) {
      if (!statusBarStyle) {
          const pages = getCurrentPages();
          if (!pages.length) {
              return;
          }
          statusBarStyle = pages[pages.length - 1].$page
              .statusBarStyle;
          if (!statusBarStyle || statusBarStyle === lastStatusBarStyle) {
              return;
          }
      }
      if (statusBarStyle === lastStatusBarStyle) {
          return;
      }
      if ((process.env.NODE_ENV !== 'production')) {
          console.log(formatLog('setStatusBarStyle', statusBarStyle));
      }
      lastStatusBarStyle = statusBarStyle;
      plus.navigator.setStatusBarStyle(statusBarStyle);
  }

fxy060608's avatar
fxy060608 已提交
7722 7723 7724
  const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, (args, { resolve, reject }) => {
      const page = getCurrentPage();
      if (!page) {
fxy060608's avatar
fxy060608 已提交
7725
          return reject(`getCurrentPages is empty`);
fxy060608's avatar
fxy060608 已提交
7726
      }
fxy060608's avatar
fxy060608 已提交
7727 7728 7729 7730 7731 7732 7733
      if (invokeHook(page, 'onBackPress', {
          from: args.from,
      })) {
          return resolve();
      }
      uni.hideToast();
      uni.hideLoading();
fxy060608's avatar
fxy060608 已提交
7734 7735 7736
      if (page.$page.meta.isQuit) {
          quit();
      }
fxy060608's avatar
fxy060608 已提交
7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748
      else if (page.$page.id === 1 && __uniConfig.realEntryPagePath) {
          // condition
          __uniConfig.entryPagePath = __uniConfig.realEntryPagePath;
          delete __uniConfig.realEntryPagePath;
          uni.reLaunch({
              url: '/' + __uniConfig.entryPagePath,
          });
      }
      else {
          const { delta, animationType, animationDuration } = args;
          back(delta, animationType, animationDuration);
      }
fxy060608's avatar
fxy060608 已提交
7749
      return resolve();
fxy060608's avatar
fxy060608 已提交
7750
  }, NavigateBackProtocol, NavigateBackOptions);
fxy060608's avatar
fxy060608 已提交
7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763
  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 已提交
7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802
  }
  function back(delta, animationType, animationDuration) {
      const pages = getCurrentPages();
      const len = pages.length;
      const currentPage = pages[len - 1];
      if (delta > 1) {
          // 中间页隐藏
          pages
              .slice(len - delta, len - 1)
              .reverse()
              .forEach((deltaPage) => {
              closeWebview(plus.webview.getWebviewById(deltaPage.$page.id + ''), 'none', 0);
          });
      }
      const backPage = function (webview) {
          if (animationType) {
              closeWebview(webview, animationType, animationDuration || ANI_DURATION);
          }
          else {
              if (currentPage.$page.openType === 'redirectTo') {
                  // 如果是 redirectTo 跳转的,需要制定 back 动画
                  closeWebview(webview, ANI_CLOSE, ANI_DURATION);
              }
              else {
                  closeWebview(webview, 'auto');
              }
          }
          pages
              .slice(len - delta, len)
              .forEach((page) => removePage(page));
          setStatusBarStyle();
      };
      const webview = plus.webview.getWebviewById(currentPage.$page.id + '');
      if (!currentPage.__uniapp_webview) {
          return backPage(webview);
      }
      backWebview(webview, () => {
          backPage(webview);
      });
fxy060608's avatar
fxy060608 已提交
7803 7804
  }

fxy060608's avatar
fxy060608 已提交
7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830
  // TODO
  // export {
  //   upx2px,
  //   addInterceptor,
  //   removeInterceptor,
  //   promiseInterceptor,
  //   arrayBufferToBase64,
  //   base64ToArrayBuffer,
  //   createIntersectionObserver,
  //   createMediaQueryObserver,
  //   createSelectorQuery,
  //   createVideoContext,
  //   createMapContext,
  //   createAnimation,
  //   onTabBarMidButtonTap,
  //   createCanvasContext,
  //   canvasGetImageData,
  //   canvasPutImageData,
  //   canvasToTempFilePath,
  //   getSelectedTextRange,
  //   $on,
  //   $off,
  //   $once,
  //   $emit,
  // } from '@dcloudio/uni-api'

fxy060608's avatar
fxy060608 已提交
7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842
  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,
fxy060608's avatar
fxy060608 已提交
7843
    getFileInfo: getFileInfo$1,
fxy060608's avatar
fxy060608 已提交
7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880
    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,
7881
    addPhoneContact: addPhoneContact,
fxy060608's avatar
fxy060608 已提交
7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895
    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,
fxy060608's avatar
fxy060608 已提交
7896
    compressImage: compressImage$1,
fxy060608's avatar
fxy060608 已提交
7897
    compressVideo: compressVideo,
fxy060608's avatar
fxy060608 已提交
7898 7899
    chooseImage: chooseImage,
    chooseVideo: chooseVideo,
fxy060608's avatar
fxy060608 已提交
7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910
    showKeyboard: showKeyboard,
    hideKeyboard: hideKeyboard,
    downloadFile: downloadFile,
    request: request,
    connectSocket: connectSocket,
    sendSocketMessage: sendSocketMessage,
    closeSocket: closeSocket,
    onSocketOpen: onSocketOpen,
    onSocketError: onSocketError,
    onSocketMessage: onSocketMessage,
    onSocketClose: onSocketClose,
fxy060608's avatar
fxy060608 已提交
7911
    uploadFile: uploadFile,
fxy060608's avatar
fxy060608 已提交
7912 7913 7914 7915 7916 7917 7918 7919
    createInnerAudioContext: createInnerAudioContext,
    getBackgroundAudioManager: getBackgroundAudioManager,
    getLocation: getLocation,
    showModal: showModal,
    showActionSheet: showActionSheet,
    showLoading: showLoading,
    showToast: showToast,
    hideToast: hideToast,
fxy060608's avatar
fxy060608 已提交
7920
    hideLoading: hideLoading,
fxy060608's avatar
fxy060608 已提交
7921 7922 7923 7924 7925 7926
    getProvider: getProvider,
    login: login,
    getUserInfo: getUserInfo,
    getUserProfile: getUserProfile,
    preLogin: preLogin,
    closeAuthView: closeAuthView,
fxy060608's avatar
fxy060608 已提交
7927
    registerRuntime: registerRuntime,
fxy060608's avatar
fxy060608 已提交
7928 7929 7930
    share: share,
    shareWithSystem: shareWithSystem,
    requestPayment: requestPayment,
fxy060608's avatar
fxy060608 已提交
7931
    __vuePlugin: __vuePlugin,
fxy060608's avatar
fxy060608 已提交
7932 7933 7934 7935
    createRewardedVideoAd: createRewardedVideoAd,
    createFullScreenVideoAd: createFullScreenVideoAd,
    createInterstitialAd: createInterstitialAd,
    createInteractiveAd: createInteractiveAd,
fxy060608's avatar
fxy060608 已提交
7936 7937
    navigateTo: navigateTo,
    navigateBack: navigateBack
fxy060608's avatar
fxy060608 已提交
7938 7939
  });

fxy060608's avatar
fxy060608 已提交
7940 7941 7942 7943 7944 7945
  let invokeViewMethodId = 0;
  const invokeViewMethod = (name, args, callback, pageId) => {
      const id = invokeViewMethodId++;
      UniServiceJSBridge$1.subscribe(INVOKE_VIEW_API + '.' + id, callback, true);
      publishHandler(INVOKE_VIEW_API, { id, name, args }, pageId);
  };
fxy060608's avatar
fxy060608 已提交
7946 7947
  const UniServiceJSBridge$1 = /*#__PURE__*/ extend(ServiceJSBridge, {
      publishHandler,
fxy060608's avatar
fxy060608 已提交
7948
      invokeViewMethod,
fxy060608's avatar
fxy060608 已提交
7949 7950 7951 7952
  });
  function publishHandler(event, args, pageIds) {
      args = JSON.stringify(args);
      if ((process.env.NODE_ENV !== 'production')) {
fxy060608's avatar
fxy060608 已提交
7953
          console.log(formatLog('publishHandler', event, args, pageIds));
fxy060608's avatar
fxy060608 已提交
7954 7955 7956 7957 7958
      }
      if (!isArray(pageIds)) {
          pageIds = [pageIds];
      }
      const evalJSCode = `typeof UniViewJSBridge !== 'undefined' && UniViewJSBridge.subscribeHandler("${event}",${args},__PAGE_ID__)`;
fxy060608's avatar
fxy060608 已提交
7959 7960 7961
      if ((process.env.NODE_ENV !== 'production')) {
          console.log(formatLog('publishHandler', 'size', evalJSCode.length));
      }
fxy060608's avatar
fxy060608 已提交
7962 7963 7964 7965 7966 7967 7968
      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 已提交
7969 7970
  var index = {
      uni: uni$1,
fxy060608's avatar
fxy060608 已提交
7971 7972
      getApp: getApp$1,
      getCurrentPages: getCurrentPages$1,
fxy060608's avatar
fxy060608 已提交
7973
      __definePage: definePage,
fxy060608's avatar
fxy060608 已提交
7974 7975
      __registerApp: registerApp,
      __registerPage: registerPage,
fxy060608's avatar
fxy060608 已提交
7976
      UniServiceJSBridge: UniServiceJSBridge$1,
fxy060608's avatar
fxy060608 已提交
7977
  };
fxy060608's avatar
fxy060608 已提交
7978

fxy060608's avatar
fxy060608 已提交
7979
  return index;
fxy060608's avatar
fxy060608 已提交
7980

fxy060608's avatar
fxy060608 已提交
7981
}(Vue));
fxy060608's avatar
fxy060608 已提交
7982 7983 7984
const uni = serviceContext.uni;
const getApp = serviceContext.getApp;
const getCurrentPages = serviceContext.getCurrentPages;
fxy060608's avatar
fxy060608 已提交
7985
const UniServiceJSBridge = serviceContext.UniServiceJSBridge;
fxy060608's avatar
fxy060608 已提交
7986 7987
return serviceContext;
}