automator.js 12.0 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
var hasOwnProperty = Object.prototype.hasOwnProperty
var hasOwn = function (val, key) {
  return hasOwnProperty.call(val, key)
}
var isUndef = function (v) {
  return v === undefined || v === null
}
var isArray = Array.isArray
var isPromise = function (obj) {
  return (
    !!obj &&
    (typeof obj === 'object' || typeof obj === 'function') &&
    typeof obj.then === 'function'
  )
}
var cacheStringFunction = function (fn) {
  var cache = Object.create(null)
  return function (str) {
    var hit = cache[str]
    return hit || (cache[str] = fn(str))
  }
}
var camelizeRE = /-(\w)/g
var camelize = cacheStringFunction(function (str) {
  return str.replace(camelizeRE, function (_, c) {
    return c ? c.toUpperCase() : ''
  })
})
var capitalize = cacheStringFunction(function (str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
})
var PATH_RE =
  /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g
function getPaths(path, data) {
  if (isArray(path)) {
    return path
  }
  if (data && hasOwn(data, path)) {
    return [path]
  }
  var res = []
  path.replace(PATH_RE, function (match, p1, offset, string) {
    res.push(offset ? string.replace(/\\(\\)?/g, '$1') : p1 || match)
    return string
  })
  return res
}
function getDataByPath(data, path) {
  var paths = getPaths(path, data)
  var dataPath
  for (dataPath = paths.shift(); !isUndef(dataPath); ) {
    if (null == (data = data[dataPath])) {
      return
    }
    dataPath = paths.shift()
  }
  return data
}

function getPageId(page) {
  if (page.__wxWebviewId__) {
    //mp-weixin
    return page.__wxWebviewId__
  }
  if (page.privateProperties) {
    //mp-baidu
    return page.privateProperties.slaveId
  }
  if (page.$page) {
    //h5 and app-plus
    return page.$page.id
  }
}
function getPagePath(page) {
  return page.route || page.uri
}
function getPageQuery(page) {
  return page.options || (page.$page && page.$page.options) || {}
}
function parsePage(page) {
  return {
    id: getPageId(page),
    path: getPagePath(page),
    query: getPageQuery(page),
  }
}
function getPageById(id) {
  return getCurrentPages().find(function (page) {
    return getPageId(page) === id
  })
}
function getPageVm(id) {
  var page = getPageById(id)
  return page && page.$vm
}
function getNodeId(scope) {
  return scope.__wxExparserNodeId__ || scope.nodeId || scope.id
}
function matchNodeId(vm, nodeId) {
  return vm.$scope && getNodeId(vm.$scope) === nodeId
}
function findComponentVm(vm, nodeId) {
  var res
  if (vm) {
    if (matchNodeId(vm, nodeId)) {
      res = vm
    } else {
      vm.$children.find(function (child) {
        res = findComponentVm(child, nodeId)
        return res
      })
    }
  }
  return res
}
function getComponentVm(pageId, nodeId) {
  var pageVm = getPageVm(pageId)
  return pageVm && findComponentVm(pageVm, nodeId)
}
function getData(vm, path) {
  var data
  if (vm) {
    data = path ? getDataByPath(vm.$data, path) : Object.assign({}, vm.$data)
  }
  return Promise.resolve({ data: data })
}
function setData(vm, data) {
  if (vm) {
    Object.keys(data).forEach(function (name) {
      vm[name] = data[name]
    })
  }
  return Promise.resolve()
}
var CALL_METHOD_ERROR
;(function (CALL_METHOD_ERROR) {
  CALL_METHOD_ERROR['VM_NOT_EXISTS'] = 'VM_NOT_EXISTS'
  CALL_METHOD_ERROR['METHOD_NOT_EXISTS'] = 'METHOD_NOT_EXISTS'
})(CALL_METHOD_ERROR || (CALL_METHOD_ERROR = {}))
function callMethod(vm, method, args) {
  return new Promise(function (resolve, reject) {
    if (!vm) {
      return reject(CALL_METHOD_ERROR.VM_NOT_EXISTS)
    }
    if (!vm[method]) {
      return reject(CALL_METHOD_ERROR.VM_NOT_EXISTS)
    }
    var ret = vm[method].apply(vm, args)
    isPromise(ret)
      ? ret.then(function (res) {
          resolve({ result: res })
        })
      : resolve({ result: ret })
  })
}

var SYNC_APIS = [
  'stopRecord',
  'getRecorderManager',
  'pauseVoice',
  'stopVoice',
  'pauseBackgroundAudio',
  'stopBackgroundAudio',
  'getBackgroundAudioManager',
  'createAudioContext',
  'createInnerAudioContext',
  'createVideoContext',
  'createCameraContext',
  'createMapContext',
  'canIUse',
  'startAccelerometer',
  'stopAccelerometer',
  'startCompass',
  'stopCompass',
  'hideToast',
  'hideLoading',
  'showNavigationBarLoading',
  'hideNavigationBarLoading',
  'navigateBack',
  'createAnimation',
  'pageScrollTo',
  'createSelectorQuery',
  'createCanvasContext',
  'createContext',
  'drawCanvas',
  'hideKeyboard',
  'stopPullDownRefresh',
  'arrayBufferToBase64',
  'base64ToArrayBuffer',
]
var originUni = {}
var SYNC_API_RE = /Sync$/
var MOCK_API_BLACKLIST_RE = /^on|^off/
function isSyncApi(method) {
  return SYNC_API_RE.test(method) || SYNC_APIS.indexOf(method) !== -1
}
function canIMock(method) {
  return !MOCK_API_BLACKLIST_RE.test(method)
}
var App = {
  getPageStack: function () {
    return Promise.resolve({
      pageStack: getCurrentPages().map(function (page) {
        return parsePage(page)
      }),
    })
  },
  getCurrentPage: function () {
    var pages = getCurrentPages()
    var len = pages.length
    return new Promise(function (resolve, reject) {
      if (!len) {
        reject(Error('getCurrentPages().length=0'))
      } else {
        resolve(parsePage(pages[len - 1]))
      }
    })
  },
  callUniMethod: function (params) {
    var method = params.method
    var args = params.args
    return new Promise(function (resolve, reject) {
      if (!uni[method]) {
        return reject(Error('uni.' + method + ' not exists'))
      }
      if (isSyncApi(method)) {
        return resolve({
          result: uni[method].apply(uni, args),
        })
      }
      var params = [
        Object.assign({}, args[0] || {}, {
          success: function (result) {
            var timeout = method === 'pageScrollTo' ? 350 : 0
            setTimeout(function () {
              resolve({ result: result })
            }, timeout)
          },
          fail: function (res) {
            reject(Error(res.errMsg.replace(method + ':fail ', '')))
          },
        }),
      ]
      uni[method].apply(uni, params)
    })
  },
  mockUniMethod: function (params) {
    var method = params.method
    if (!uni[method]) {
      throw Error('uni.' + method + ' not exists')
    }
    if (!canIMock(method)) {
      throw Error("You can't mock uni." + method)
    }
    // TODO getOwnPropertyDescriptor?
    var result = params.result
    if (isUndef(result)) {
      // restoreUniMethod
      if (originUni[method]) {
        uni[method] = originUni[method]
        delete originUni[method]
      }
      return Promise.resolve()
    }
    var mockFn = isSyncApi(method)
      ? function () {
          return result
        }
      : function (params) {
          setTimeout(function () {
            var isFail = result.errMsg && result.errMsg.indexOf(':fail') !== -1
            if (isFail) {
              params.fail && params.fail(result)
            } else {
              params.success && params.success(result)
            }
            params.complete && params.complete(result)
          }, 4)
        }
    // mockFn.origin = originUni[method] || uni[method];
    if (!originUni[method]) {
      originUni[method] = uni[method]
    }
    uni[method] = mockFn
    return Promise.resolve()
  },
}

var Page = {
  getData: function (params) {
    return getData(getPageVm(params.pageId), params.path)
  },
  setData: function (params) {
    return setData(getPageVm(params.pageId), params.data)
  },
  callMethod: function (params) {
    var _a
    var err =
      ((_a = {}),
      (_a[CALL_METHOD_ERROR.VM_NOT_EXISTS] =
        'Page[' + params.pageId + '] not exists'),
      (_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS] =
        'page.' + params.method + ' not exists'),
      _a)
    return new Promise(function (resolve, reject) {
      callMethod(getPageVm(params.pageId), params.method, params.args)
        .then(function (res) {
          return resolve(res)
        })
        .catch(function (type) {
          reject(Error(err[type]))
        })
    })
  },
}

function getNodeId$1(params) {
  return params.nodeId || params.elementId
}
var Element = {
  getData: function (params) {
    return getData(
      getComponentVm(params.pageId, getNodeId$1(params)),
      params.path
    )
  },
  setData: function (params) {
    return setData(
      getComponentVm(params.pageId, getNodeId$1(params)),
      params.data
    )
  },
  callMethod: function (params) {
    var _a
    var nodeId = getNodeId$1(params)
    var err =
      ((_a = {}),
      (_a[CALL_METHOD_ERROR.VM_NOT_EXISTS] =
        'Component[' + params.pageId + ':' + nodeId + '] not exists'),
      (_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS] =
        'component.' + params.method + ' not exists'),
      _a)
    return new Promise(function (resolve, reject) {
      callMethod(
        getComponentVm(params.pageId, nodeId),
        params.method,
        params.args
      )
        .then(function (res) {
          return resolve(res)
        })
        .catch(function (type) {
          reject(Error(err[type]))
        })
    })
  },
}

// Unique ID creation requires a high quality random # generator. In the browser we therefore
// require the crypto API and do not support built-in fallback to lower quality random number
// generators (like Math.random()).
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
// find the complete implementation of crypto (msCrypto) on IE11.
var getRandomValues =
  (typeof crypto != 'undefined' &&
    crypto.getRandomValues &&
    crypto.getRandomValues.bind(crypto)) ||
  (typeof msCrypto != 'undefined' &&
    typeof msCrypto.getRandomValues == 'function' &&
    msCrypto.getRandomValues.bind(msCrypto))

/**
 * Convert array of 16 byte values to UUID string format of the form:
 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
 */
var byteToHex = []

for (var i = 0; i < 256; ++i) {
  byteToHex[i] = (i + 0x100).toString(16).substr(1)
}

var BUILITIN = [
  'movable-view',
  'picker',
  'ad',
  'button',
  'checkbox-group',
  'checkbox',
  'form',
  'icon',
  'label',
  'movable-area',
  'navigator',
  'picker-view-column',
  'picker-view',
  'progress',
  'radio-group',
  'radio',
  'rich-text',
  'u-slider',
  'swiper-item',
  'swiper',
  'switch',
]
var BUILITIN_ALIAS = BUILITIN.map(function (tag) {
  return capitalize(camelize(tag))
})

var Api = {}
Object.keys(App).forEach(function (method) {
  Api['App.' + method] = App[method]
})
Object.keys(Page).forEach(function (method) {
  Api['Page.' + method] = Page[method]
})
Object.keys(Element).forEach(function (method) {
  Api['Element.' + method] = Element[method]
})
var wsEndpoint = process.env.UNI_AUTOMATOR_WS_ENDPOINT
var socketTask
function send(data) {
  socketTask.send({ data: JSON.stringify(data) })
}
function onMessage(res) {
  var _a = JSON.parse(res.data),
    id = _a.id,
    method = _a.method,
    params = _a.params
  var data = { id: id }
  var fn = Api[method]
  if (!fn) {
    if (!fn) {
      data.error = {
        message: method + ' unimplemented',
      }
      return send(data)
    }
  }
  try {
    fn(params)
      .then(function (res) {
        res && (data.result = res)
      })
      .catch(function (err) {
        data.error = {
          message: err.message,
        }
      })
      .finally(function () {
        send(data)
      })
  } catch (err) {
    data.error = {
      message: err.message,
    }
    send(data)
  }
}
function initRuntimeAutomator(options) {
  if (options === void 0) {
    options = {}
  }
  socketTask = uni.connectSocket({
    url: wsEndpoint,
    complete: function () {},
  })
  socketTask.onMessage(onMessage)
  socketTask.onOpen(function (res) {
    options.success && options.success()
    console.log('已开启自动化测试...')
  })
  socketTask.onError(function (res) {
    console.log('automator.onError', res)
  })
  socketTask.onClose(function () {
    options.fail && options.fail({ errMsg: '$$initRuntimeAutomator:fail' })
    console.log('automator.onClose')
  })
}
//@ts-ignore
{
  //@ts-ignore
  swan.$$initRuntimeAutomator = initRuntimeAutomator
  setTimeout(function () {
    //@ts-ignore
    swan.$$initRuntimeAutomator()
  }, 500)
}