uni.api.esm.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755
  1. import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isFunction, isPromise, extend, remove } from '@vue/shared';
  2. import { LINEFEED, Emitter, onCreateVueApp, invokeCreateVueAppHook } from '@dcloudio/uni-shared';
  3. import { normalizeLocale, LOCALE_EN } from '@dcloudio/uni-i18n';
  4. function getBaseSystemInfo() {
  5. return my.getSystemInfoSync();
  6. }
  7. function validateProtocolFail(name, msg) {
  8. console.warn(`${name}: ${msg}`);
  9. }
  10. function validateProtocol(name, data, protocol, onFail) {
  11. if (!onFail) {
  12. onFail = validateProtocolFail;
  13. }
  14. for (const key in protocol) {
  15. const errMsg = validateProp(key, data[key], protocol[key], !hasOwn(data, key));
  16. if (isString(errMsg)) {
  17. onFail(name, errMsg);
  18. }
  19. }
  20. }
  21. function validateProtocols(name, args, protocol, onFail) {
  22. if (!protocol) {
  23. return;
  24. }
  25. if (!isArray(protocol)) {
  26. return validateProtocol(name, args[0] || Object.create(null), protocol, onFail);
  27. }
  28. const len = protocol.length;
  29. const argsLen = args.length;
  30. for (let i = 0; i < len; i++) {
  31. const opts = protocol[i];
  32. const data = Object.create(null);
  33. if (argsLen > i) {
  34. data[opts.name] = args[i];
  35. }
  36. validateProtocol(name, data, { [opts.name]: opts }, onFail);
  37. }
  38. }
  39. function validateProp(name, value, prop, isAbsent) {
  40. if (!isPlainObject(prop)) {
  41. prop = { type: prop };
  42. }
  43. const { type, required, validator } = prop;
  44. // required!
  45. if (required && isAbsent) {
  46. return 'Missing required args: "' + name + '"';
  47. }
  48. // missing but optional
  49. if (value == null && !required) {
  50. return;
  51. }
  52. // type check
  53. if (type != null) {
  54. let isValid = false;
  55. const types = isArray(type) ? type : [type];
  56. const expectedTypes = [];
  57. // value is valid as long as one of the specified types match
  58. for (let i = 0; i < types.length && !isValid; i++) {
  59. const { valid, expectedType } = assertType(value, types[i]);
  60. expectedTypes.push(expectedType || '');
  61. isValid = valid;
  62. }
  63. if (!isValid) {
  64. return getInvalidTypeMessage(name, value, expectedTypes);
  65. }
  66. }
  67. // custom validator
  68. if (validator) {
  69. return validator(value);
  70. }
  71. }
  72. const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol');
  73. function assertType(value, type) {
  74. let valid;
  75. const expectedType = getType(type);
  76. if (isSimpleType(expectedType)) {
  77. const t = typeof value;
  78. valid = t === expectedType.toLowerCase();
  79. // for primitive wrapper objects
  80. if (!valid && t === 'object') {
  81. valid = value instanceof type;
  82. }
  83. }
  84. else if (expectedType === 'Object') {
  85. valid = isObject(value);
  86. }
  87. else if (expectedType === 'Array') {
  88. valid = isArray(value);
  89. }
  90. else {
  91. {
  92. valid = value instanceof type;
  93. }
  94. }
  95. return {
  96. valid,
  97. expectedType,
  98. };
  99. }
  100. function getInvalidTypeMessage(name, value, expectedTypes) {
  101. let message = `Invalid args: type check failed for args "${name}".` +
  102. ` Expected ${expectedTypes.map(capitalize).join(', ')}`;
  103. const expectedType = expectedTypes[0];
  104. const receivedType = toRawType(value);
  105. const expectedValue = styleValue(value, expectedType);
  106. const receivedValue = styleValue(value, receivedType);
  107. // check if we need to specify expected value
  108. if (expectedTypes.length === 1 &&
  109. isExplicable(expectedType) &&
  110. !isBoolean(expectedType, receivedType)) {
  111. message += ` with value ${expectedValue}`;
  112. }
  113. message += `, got ${receivedType} `;
  114. // check if we need to specify received value
  115. if (isExplicable(receivedType)) {
  116. message += `with value ${receivedValue}.`;
  117. }
  118. return message;
  119. }
  120. function getType(ctor) {
  121. const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
  122. return match ? match[1] : '';
  123. }
  124. function styleValue(value, type) {
  125. if (type === 'String') {
  126. return `"${value}"`;
  127. }
  128. else if (type === 'Number') {
  129. return `${Number(value)}`;
  130. }
  131. else {
  132. return `${value}`;
  133. }
  134. }
  135. function isExplicable(type) {
  136. const explicitTypes = ['string', 'number', 'boolean'];
  137. return explicitTypes.some((elem) => type.toLowerCase() === elem);
  138. }
  139. function isBoolean(...args) {
  140. return args.some((elem) => elem.toLowerCase() === 'boolean');
  141. }
  142. function tryCatch(fn) {
  143. return function () {
  144. try {
  145. return fn.apply(fn, arguments);
  146. }
  147. catch (e) {
  148. // TODO
  149. console.error(e);
  150. }
  151. };
  152. }
  153. let invokeCallbackId = 1;
  154. const invokeCallbacks = {};
  155. function addInvokeCallback(id, name, callback, keepAlive = false) {
  156. invokeCallbacks[id] = {
  157. name,
  158. keepAlive,
  159. callback,
  160. };
  161. return id;
  162. }
  163. // onNativeEventReceive((event,data)=>{}) 需要两个参数,目前写死最多两个参数
  164. function invokeCallback(id, res, extras) {
  165. if (typeof id === 'number') {
  166. const opts = invokeCallbacks[id];
  167. if (opts) {
  168. if (!opts.keepAlive) {
  169. delete invokeCallbacks[id];
  170. }
  171. return opts.callback(res, extras);
  172. }
  173. }
  174. return res;
  175. }
  176. const API_SUCCESS = 'success';
  177. const API_FAIL = 'fail';
  178. const API_COMPLETE = 'complete';
  179. function getApiCallbacks(args) {
  180. const apiCallbacks = {};
  181. for (const name in args) {
  182. const fn = args[name];
  183. if (isFunction(fn)) {
  184. apiCallbacks[name] = tryCatch(fn);
  185. delete args[name];
  186. }
  187. }
  188. return apiCallbacks;
  189. }
  190. function normalizeErrMsg$1(errMsg, name) {
  191. if (!errMsg || errMsg.indexOf(':fail') === -1) {
  192. return name + ':ok';
  193. }
  194. return name + errMsg.substring(errMsg.indexOf(':fail'));
  195. }
  196. function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
  197. if (!isPlainObject(args)) {
  198. args = {};
  199. }
  200. const { success, fail, complete } = getApiCallbacks(args);
  201. const hasSuccess = isFunction(success);
  202. const hasFail = isFunction(fail);
  203. const hasComplete = isFunction(complete);
  204. const callbackId = invokeCallbackId++;
  205. addInvokeCallback(callbackId, name, (res) => {
  206. res = res || {};
  207. res.errMsg = normalizeErrMsg$1(res.errMsg, name);
  208. isFunction(beforeAll) && beforeAll(res);
  209. if (res.errMsg === name + ':ok') {
  210. isFunction(beforeSuccess) && beforeSuccess(res, args);
  211. hasSuccess && success(res);
  212. }
  213. else {
  214. hasFail && fail(res);
  215. }
  216. hasComplete && complete(res);
  217. });
  218. return callbackId;
  219. }
  220. const HOOK_SUCCESS = 'success';
  221. const HOOK_FAIL = 'fail';
  222. const HOOK_COMPLETE = 'complete';
  223. const globalInterceptors = {};
  224. const scopedInterceptors = {};
  225. function wrapperHook(hook, params) {
  226. return function (data) {
  227. return hook(data, params) || data;
  228. };
  229. }
  230. function queue(hooks, data, params) {
  231. let promise = false;
  232. for (let i = 0; i < hooks.length; i++) {
  233. const hook = hooks[i];
  234. if (promise) {
  235. promise = Promise.resolve(wrapperHook(hook, params));
  236. }
  237. else {
  238. const res = hook(data, params);
  239. if (isPromise(res)) {
  240. promise = Promise.resolve(res);
  241. }
  242. if (res === false) {
  243. return {
  244. then() { },
  245. catch() { },
  246. };
  247. }
  248. }
  249. }
  250. return (promise || {
  251. then(callback) {
  252. return callback(data);
  253. },
  254. catch() { },
  255. });
  256. }
  257. function wrapperOptions(interceptors, options = {}) {
  258. [HOOK_SUCCESS, HOOK_FAIL, HOOK_COMPLETE].forEach((name) => {
  259. const hooks = interceptors[name];
  260. if (!isArray(hooks)) {
  261. return;
  262. }
  263. const oldCallback = options[name];
  264. options[name] = function callbackInterceptor(res) {
  265. queue(hooks, res, options).then((res) => {
  266. return (isFunction(oldCallback) && oldCallback(res)) || res;
  267. });
  268. };
  269. });
  270. return options;
  271. }
  272. function wrapperReturnValue(method, returnValue) {
  273. const returnValueHooks = [];
  274. if (isArray(globalInterceptors.returnValue)) {
  275. returnValueHooks.push(...globalInterceptors.returnValue);
  276. }
  277. const interceptor = scopedInterceptors[method];
  278. if (interceptor && isArray(interceptor.returnValue)) {
  279. returnValueHooks.push(...interceptor.returnValue);
  280. }
  281. returnValueHooks.forEach((hook) => {
  282. returnValue = hook(returnValue) || returnValue;
  283. });
  284. return returnValue;
  285. }
  286. function getApiInterceptorHooks(method) {
  287. const interceptor = Object.create(null);
  288. Object.keys(globalInterceptors).forEach((hook) => {
  289. if (hook !== 'returnValue') {
  290. interceptor[hook] = globalInterceptors[hook].slice();
  291. }
  292. });
  293. const scopedInterceptor = scopedInterceptors[method];
  294. if (scopedInterceptor) {
  295. Object.keys(scopedInterceptor).forEach((hook) => {
  296. if (hook !== 'returnValue') {
  297. interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
  298. }
  299. });
  300. }
  301. return interceptor;
  302. }
  303. function invokeApi(method, api, options, params) {
  304. const interceptor = getApiInterceptorHooks(method);
  305. if (interceptor && Object.keys(interceptor).length) {
  306. if (isArray(interceptor.invoke)) {
  307. const res = queue(interceptor.invoke, options);
  308. return res.then((options) => {
  309. // 重新访问 getApiInterceptorHooks, 允许 invoke 中再次调用 addInterceptor,removeInterceptor
  310. return api(wrapperOptions(getApiInterceptorHooks(method), options), ...params);
  311. });
  312. }
  313. else {
  314. return api(wrapperOptions(interceptor, options), ...params);
  315. }
  316. }
  317. return api(options, ...params);
  318. }
  319. function hasCallback(args) {
  320. if (isPlainObject(args) &&
  321. [API_SUCCESS, API_FAIL, API_COMPLETE].find((cb) => isFunction(args[cb]))) {
  322. return true;
  323. }
  324. return false;
  325. }
  326. function handlePromise(promise) {
  327. // if (__UNI_FEATURE_PROMISE__) {
  328. // return promise
  329. // .then((data) => {
  330. // return [null, data]
  331. // })
  332. // .catch((err) => [err])
  333. // }
  334. return promise;
  335. }
  336. function promisify$1(name, fn) {
  337. return (args = {}, ...rest) => {
  338. if (hasCallback(args)) {
  339. return wrapperReturnValue(name, invokeApi(name, fn, args, rest));
  340. }
  341. return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
  342. invokeApi(name, fn, extend(args, { success: resolve, fail: reject }), rest);
  343. })));
  344. };
  345. }
  346. function formatApiArgs(args, options) {
  347. const params = args[0];
  348. if (!options ||
  349. (!isPlainObject(options.formatArgs) && isPlainObject(params))) {
  350. return;
  351. }
  352. const formatArgs = options.formatArgs;
  353. const keys = Object.keys(formatArgs);
  354. for (let i = 0; i < keys.length; i++) {
  355. const name = keys[i];
  356. const formatterOrDefaultValue = formatArgs[name];
  357. if (isFunction(formatterOrDefaultValue)) {
  358. const errMsg = formatterOrDefaultValue(args[0][name], params);
  359. if (isString(errMsg)) {
  360. return errMsg;
  361. }
  362. }
  363. else {
  364. // defaultValue
  365. if (!hasOwn(params, name)) {
  366. params[name] = formatterOrDefaultValue;
  367. }
  368. }
  369. }
  370. }
  371. function invokeSuccess(id, name, res) {
  372. const result = {
  373. errMsg: name + ':ok',
  374. };
  375. return invokeCallback(id, extend((res || {}), result));
  376. }
  377. function invokeFail(id, name, errMsg, errRes = {}) {
  378. const apiErrMsg = name + ':fail' + (errMsg ? ' ' + errMsg : '');
  379. delete errRes.errCode;
  380. return invokeCallback(id, typeof UniError !== 'undefined'
  381. ? typeof errRes.errCode !== 'undefined'
  382. ? new UniError(name, errRes.errCode, apiErrMsg)
  383. : new UniError(apiErrMsg, errRes)
  384. : extend({ errMsg: apiErrMsg }, errRes));
  385. }
  386. function beforeInvokeApi(name, args, protocol, options) {
  387. if ((process.env.NODE_ENV !== 'production')) {
  388. validateProtocols(name, args, protocol);
  389. }
  390. if (options && options.beforeInvoke) {
  391. const errMsg = options.beforeInvoke(args);
  392. if (isString(errMsg)) {
  393. return errMsg;
  394. }
  395. }
  396. const errMsg = formatApiArgs(args, options);
  397. if (errMsg) {
  398. return errMsg;
  399. }
  400. }
  401. function normalizeErrMsg(errMsg) {
  402. if (!errMsg || isString(errMsg)) {
  403. return errMsg;
  404. }
  405. if (errMsg.stack) {
  406. console.error(errMsg.message + LINEFEED + errMsg.stack);
  407. return errMsg.message;
  408. }
  409. return errMsg;
  410. }
  411. function wrapperTaskApi(name, fn, protocol, options) {
  412. return (args) => {
  413. const id = createAsyncApiCallback(name, args, options);
  414. const errMsg = beforeInvokeApi(name, [args], protocol, options);
  415. if (errMsg) {
  416. return invokeFail(id, name, errMsg);
  417. }
  418. return fn(args, {
  419. resolve: (res) => invokeSuccess(id, name, res),
  420. reject: (errMsg, errRes) => invokeFail(id, name, normalizeErrMsg(errMsg), errRes),
  421. });
  422. };
  423. }
  424. function wrapperSyncApi(name, fn, protocol, options) {
  425. return (...args) => {
  426. const errMsg = beforeInvokeApi(name, args, protocol, options);
  427. if (errMsg) {
  428. throw new Error(errMsg);
  429. }
  430. return fn.apply(null, args);
  431. };
  432. }
  433. function wrapperAsyncApi(name, fn, protocol, options) {
  434. return wrapperTaskApi(name, fn, protocol, options);
  435. }
  436. function defineSyncApi(name, fn, protocol, options) {
  437. return wrapperSyncApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
  438. }
  439. function defineAsyncApi(name, fn, protocol, options) {
  440. return promisify$1(name, wrapperAsyncApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options));
  441. }
  442. const API_UPX2PX = 'upx2px';
  443. const Upx2pxProtocol = [
  444. {
  445. name: 'upx',
  446. type: [Number, String],
  447. required: true,
  448. },
  449. ];
  450. const EPS = 1e-4;
  451. const BASE_DEVICE_WIDTH = 750;
  452. let isIOS = false;
  453. let deviceWidth = 0;
  454. let deviceDPR = 0;
  455. function checkDeviceWidth() {
  456. const { platform, pixelRatio, windowWidth } = getBaseSystemInfo();
  457. deviceWidth = windowWidth;
  458. deviceDPR = pixelRatio;
  459. isIOS = platform === 'ios';
  460. }
  461. const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => {
  462. if (deviceWidth === 0) {
  463. checkDeviceWidth();
  464. }
  465. number = Number(number);
  466. if (number === 0) {
  467. return 0;
  468. }
  469. let width = newDeviceWidth || deviceWidth;
  470. let result = (number / BASE_DEVICE_WIDTH) * width;
  471. if (result < 0) {
  472. result = -result;
  473. }
  474. result = Math.floor(result + EPS);
  475. if (result === 0) {
  476. if (deviceDPR === 1 || !isIOS) {
  477. result = 1;
  478. }
  479. else {
  480. result = 0.5;
  481. }
  482. }
  483. return number < 0 ? -result : result;
  484. }, Upx2pxProtocol);
  485. const API_ADD_INTERCEPTOR = 'addInterceptor';
  486. const API_REMOVE_INTERCEPTOR = 'removeInterceptor';
  487. const AddInterceptorProtocol = [
  488. {
  489. name: 'method',
  490. type: [String, Object],
  491. required: true,
  492. },
  493. ];
  494. const RemoveInterceptorProtocol = AddInterceptorProtocol;
  495. function mergeInterceptorHook(interceptors, interceptor) {
  496. Object.keys(interceptor).forEach((hook) => {
  497. if (isFunction(interceptor[hook])) {
  498. interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]);
  499. }
  500. });
  501. }
  502. function removeInterceptorHook(interceptors, interceptor) {
  503. if (!interceptors || !interceptor) {
  504. return;
  505. }
  506. Object.keys(interceptor).forEach((name) => {
  507. const hooks = interceptors[name];
  508. const hook = interceptor[name];
  509. if (isArray(hooks) && isFunction(hook)) {
  510. remove(hooks, hook);
  511. }
  512. });
  513. }
  514. function mergeHook(parentVal, childVal) {
  515. const res = childVal
  516. ? parentVal
  517. ? parentVal.concat(childVal)
  518. : isArray(childVal)
  519. ? childVal
  520. : [childVal]
  521. : parentVal;
  522. return res ? dedupeHooks(res) : res;
  523. }
  524. function dedupeHooks(hooks) {
  525. const res = [];
  526. for (let i = 0; i < hooks.length; i++) {
  527. if (res.indexOf(hooks[i]) === -1) {
  528. res.push(hooks[i]);
  529. }
  530. }
  531. return res;
  532. }
  533. const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
  534. if (isString(method) && isPlainObject(interceptor)) {
  535. mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
  536. }
  537. else if (isPlainObject(method)) {
  538. mergeInterceptorHook(globalInterceptors, method);
  539. }
  540. }, AddInterceptorProtocol);
  541. const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
  542. if (isString(method)) {
  543. if (isPlainObject(interceptor)) {
  544. removeInterceptorHook(scopedInterceptors[method], interceptor);
  545. }
  546. else {
  547. delete scopedInterceptors[method];
  548. }
  549. }
  550. else if (isPlainObject(method)) {
  551. removeInterceptorHook(globalInterceptors, method);
  552. }
  553. }, RemoveInterceptorProtocol);
  554. const interceptors = {};
  555. const API_ON = '$on';
  556. const OnProtocol = [
  557. {
  558. name: 'event',
  559. type: String,
  560. required: true,
  561. },
  562. {
  563. name: 'callback',
  564. type: Function,
  565. required: true,
  566. },
  567. ];
  568. const API_ONCE = '$once';
  569. const OnceProtocol = OnProtocol;
  570. const API_OFF = '$off';
  571. const OffProtocol = [
  572. {
  573. name: 'event',
  574. type: [String, Array],
  575. },
  576. {
  577. name: 'callback',
  578. type: Function,
  579. },
  580. ];
  581. const API_EMIT = '$emit';
  582. const EmitProtocol = [
  583. {
  584. name: 'event',
  585. type: String,
  586. required: true,
  587. },
  588. ];
  589. const emitter = new Emitter();
  590. const $on = defineSyncApi(API_ON, (name, callback) => {
  591. emitter.on(name, callback);
  592. return () => emitter.off(name, callback);
  593. }, OnProtocol);
  594. const $once = defineSyncApi(API_ONCE, (name, callback) => {
  595. emitter.once(name, callback);
  596. return () => emitter.off(name, callback);
  597. }, OnceProtocol);
  598. const $off = defineSyncApi(API_OFF, (name, callback) => {
  599. if (!name) {
  600. emitter.e = {};
  601. return;
  602. }
  603. if (!isArray(name))
  604. name = [name];
  605. name.forEach((n) => emitter.off(n, callback));
  606. }, OffProtocol);
  607. const $emit = defineSyncApi(API_EMIT, (name, ...args) => {
  608. emitter.emit(name, ...args);
  609. }, EmitProtocol);
  610. let cid;
  611. let cidErrMsg;
  612. let enabled;
  613. function normalizePushMessage(message) {
  614. try {
  615. return JSON.parse(message);
  616. }
  617. catch (e) { }
  618. return message;
  619. }
  620. /**
  621. * @private
  622. * @param args
  623. */
  624. function invokePushCallback(args) {
  625. if (args.type === 'enabled') {
  626. enabled = true;
  627. }
  628. else if (args.type === 'clientId') {
  629. cid = args.cid;
  630. cidErrMsg = args.errMsg;
  631. invokeGetPushCidCallbacks(cid, args.errMsg);
  632. }
  633. else if (args.type === 'pushMsg') {
  634. const message = {
  635. type: 'receive',
  636. data: normalizePushMessage(args.message),
  637. };
  638. for (let i = 0; i < onPushMessageCallbacks.length; i++) {
  639. const callback = onPushMessageCallbacks[i];
  640. callback(message);
  641. // 该消息已被阻止
  642. if (message.stopped) {
  643. break;
  644. }
  645. }
  646. }
  647. else if (args.type === 'click') {
  648. onPushMessageCallbacks.forEach((callback) => {
  649. callback({
  650. type: 'click',
  651. data: normalizePushMessage(args.message),
  652. });
  653. });
  654. }
  655. }
  656. const getPushCidCallbacks = [];
  657. function invokeGetPushCidCallbacks(cid, errMsg) {
  658. getPushCidCallbacks.forEach((callback) => {
  659. callback(cid, errMsg);
  660. });
  661. getPushCidCallbacks.length = 0;
  662. }
  663. const API_GET_PUSH_CLIENT_ID = 'getPushClientId';
  664. const getPushClientId = defineAsyncApi(API_GET_PUSH_CLIENT_ID, (_, { resolve, reject }) => {
  665. Promise.resolve().then(() => {
  666. if (typeof enabled === 'undefined') {
  667. enabled = false;
  668. cid = '';
  669. cidErrMsg = 'uniPush is not enabled';
  670. }
  671. getPushCidCallbacks.push((cid, errMsg) => {
  672. if (cid) {
  673. resolve({ cid });
  674. }
  675. else {
  676. reject(errMsg);
  677. }
  678. });
  679. if (typeof cid !== 'undefined') {
  680. invokeGetPushCidCallbacks(cid, cidErrMsg);
  681. }
  682. });
  683. });
  684. const onPushMessageCallbacks = [];
  685. // 不使用 defineOnApi 实现,是因为 defineOnApi 依赖 UniServiceJSBridge ,该对象目前在小程序上未提供,故简单实现
  686. const onPushMessage = (fn) => {
  687. if (onPushMessageCallbacks.indexOf(fn) === -1) {
  688. onPushMessageCallbacks.push(fn);
  689. }
  690. };
  691. const offPushMessage = (fn) => {
  692. if (!fn) {
  693. onPushMessageCallbacks.length = 0;
  694. }
  695. else {
  696. const index = onPushMessageCallbacks.indexOf(fn);
  697. if (index > -1) {
  698. onPushMessageCallbacks.splice(index, 1);
  699. }
  700. }
  701. };
  702. const SYNC_API_RE = /^\$|getLocale|setLocale|sendNativeEvent|restoreGlobal|requireGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64|getDeviceInfo|getAppBaseInfo|getWindowInfo|getSystemSetting|getAppAuthorizeSetting/;
  703. const CONTEXT_API_RE = /^create|Manager$/;
  704. // Context例外情况
  705. const CONTEXT_API_RE_EXC = ['createBLEConnection'];
  706. // 同步例外情况
  707. const ASYNC_API = ['createBLEConnection'];
  708. const CALLBACK_API_RE = /^on|^off/;
  709. function isContextApi(name) {
  710. return CONTEXT_API_RE.test(name) && CONTEXT_API_RE_EXC.indexOf(name) === -1;
  711. }
  712. function isSyncApi(name) {
  713. return SYNC_API_RE.test(name) && ASYNC_API.indexOf(name) === -1;
  714. }
  715. function isCallbackApi(name) {
  716. return CALLBACK_API_RE.test(name) && name !== 'onPush';
  717. }
  718. function shouldPromise(name) {
  719. if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
  720. return false;
  721. }
  722. return true;
  723. }
  724. /* eslint-disable no-extend-native */
  725. if (!Promise.prototype.finally) {
  726. Promise.prototype.finally = function (onfinally) {
  727. const promise = this.constructor;
  728. return this.then((value) => promise.resolve(onfinally && onfinally()).then(() => value), (reason) => promise.resolve(onfinally && onfinally()).then(() => {
  729. throw reason;
  730. }));
  731. };
  732. }
  733. function promisify(name, api) {
  734. if (!shouldPromise(name)) {
  735. return api;
  736. }
  737. if (!isFunction(api)) {
  738. return api;
  739. }
  740. return function promiseApi(options = {}, ...rest) {
  741. if (isFunction(options.success) ||
  742. isFunction(options.fail) ||
  743. isFunction(options.complete)) {
  744. return wrapperReturnValue(name, invokeApi(name, api, options, rest));
  745. }
  746. return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
  747. invokeApi(name, api, extend({}, options, {
  748. success: resolve,
  749. fail: reject,
  750. }), rest);
  751. })));
  752. };
  753. }
  754. const CALLBACKS = ['success', 'fail', 'cancel', 'complete'];
  755. function initWrapper(protocols) {
  756. function processCallback(methodName, method, returnValue) {
  757. return function (res) {
  758. return method(processReturnValue(methodName, res, returnValue));
  759. };
  760. }
  761. function processArgs(methodName, fromArgs, argsOption = {}, returnValue = {}, keepFromArgs = false) {
  762. if (isPlainObject(fromArgs)) {
  763. // 一般 api 的参数解析
  764. const toArgs = (keepFromArgs === true ? fromArgs : {}); // returnValue 为 false 时,说明是格式化返回值,直接在返回值对象上修改赋值
  765. if (isFunction(argsOption)) {
  766. argsOption = argsOption(fromArgs, toArgs) || {};
  767. }
  768. for (const key in fromArgs) {
  769. if (hasOwn(argsOption, key)) {
  770. let keyOption = argsOption[key];
  771. if (isFunction(keyOption)) {
  772. keyOption = keyOption(fromArgs[key], fromArgs, toArgs);
  773. }
  774. if (!keyOption) {
  775. // 不支持的参数
  776. console.warn(`支付宝小程序 ${methodName} 暂不支持 ${key}`);
  777. }
  778. else if (isString(keyOption)) {
  779. // 重写参数 key
  780. toArgs[keyOption] = fromArgs[key];
  781. }
  782. else if (isPlainObject(keyOption)) {
  783. // {name:newName,value:value}可重新指定参数 key:value
  784. toArgs[keyOption.name ? keyOption.name : key] = keyOption.value;
  785. }
  786. }
  787. else if (CALLBACKS.indexOf(key) !== -1) {
  788. const callback = fromArgs[key];
  789. if (isFunction(callback)) {
  790. toArgs[key] = processCallback(methodName, callback, returnValue);
  791. }
  792. }
  793. else {
  794. if (!keepFromArgs && !hasOwn(toArgs, key)) {
  795. toArgs[key] = fromArgs[key];
  796. }
  797. }
  798. }
  799. return toArgs;
  800. }
  801. else if (isFunction(fromArgs)) {
  802. fromArgs = processCallback(methodName, fromArgs, returnValue);
  803. }
  804. return fromArgs;
  805. }
  806. function processReturnValue(methodName, res, returnValue, keepReturnValue = false) {
  807. if (isFunction(protocols.returnValue)) {
  808. // 处理通用 returnValue
  809. res = protocols.returnValue(methodName, res);
  810. }
  811. return processArgs(methodName, res, returnValue, {}, keepReturnValue);
  812. }
  813. return function wrapper(methodName, method) {
  814. if (!hasOwn(protocols, methodName)) {
  815. return method;
  816. }
  817. const protocol = protocols[methodName];
  818. if (!protocol) {
  819. // 暂不支持的 api
  820. return function () {
  821. console.error(`支付宝小程序 暂不支持${methodName}`);
  822. };
  823. }
  824. return function (arg1, arg2) {
  825. // 目前 api 最多两个参数
  826. let options = protocol;
  827. if (isFunction(protocol)) {
  828. options = protocol(arg1);
  829. }
  830. arg1 = processArgs(methodName, arg1, options.args, options.returnValue);
  831. const args = [arg1];
  832. if (typeof arg2 !== 'undefined') {
  833. args.push(arg2);
  834. }
  835. const returnValue = my[options.name || methodName].apply(my, args);
  836. if (isSyncApi(methodName)) {
  837. // 同步 api
  838. return processReturnValue(methodName, returnValue, options.returnValue, isContextApi(methodName));
  839. }
  840. return returnValue;
  841. };
  842. };
  843. }
  844. const getLocale = () => {
  845. // 优先使用 $locale
  846. const app = isFunction(getApp) && getApp({ allowDefault: true });
  847. if (app && app.$vm) {
  848. return app.$vm.$locale;
  849. }
  850. return normalizeLocale(my.getSystemInfoSync().language) || LOCALE_EN;
  851. };
  852. const setLocale = (locale) => {
  853. const app = isFunction(getApp) && getApp();
  854. if (!app) {
  855. return false;
  856. }
  857. const oldLocale = app.$vm.$locale;
  858. if (oldLocale !== locale) {
  859. app.$vm.$locale = locale;
  860. onLocaleChangeCallbacks.forEach((fn) => fn({ locale }));
  861. return true;
  862. }
  863. return false;
  864. };
  865. const onLocaleChangeCallbacks = [];
  866. const onLocaleChange = (fn) => {
  867. if (onLocaleChangeCallbacks.indexOf(fn) === -1) {
  868. onLocaleChangeCallbacks.push(fn);
  869. }
  870. };
  871. if (typeof global !== 'undefined') {
  872. global.getLocale = getLocale;
  873. }
  874. const UUID_KEY = '__DC_STAT_UUID';
  875. let deviceId;
  876. function useDeviceId(global = my) {
  877. return function addDeviceId(_, toRes) {
  878. deviceId = deviceId || global.getStorageSync(UUID_KEY);
  879. if (!deviceId) {
  880. deviceId = Date.now() + '' + Math.floor(Math.random() * 1e7);
  881. my.setStorage({
  882. key: UUID_KEY,
  883. data: deviceId,
  884. });
  885. }
  886. toRes.deviceId = deviceId;
  887. };
  888. }
  889. function addSafeAreaInsets(fromRes, toRes) {
  890. if (fromRes.safeArea) {
  891. const safeArea = fromRes.safeArea;
  892. toRes.safeAreaInsets = {
  893. top: safeArea.top,
  894. left: safeArea.left,
  895. right: fromRes.windowWidth - safeArea.right,
  896. bottom: fromRes.screenHeight - safeArea.bottom,
  897. };
  898. }
  899. }
  900. function populateParameters(fromRes, toRes) {
  901. const { brand = '', model = '', system = '', language = '', theme, version, platform, fontSizeSetting, SDKVersion, pixelRatio, deviceOrientation, } = fromRes;
  902. // const isQuickApp = "mp-alipay".indexOf('quickapp-webview') !== -1
  903. // osName osVersion
  904. let osName = '';
  905. let osVersion = '';
  906. {
  907. osName = platform;
  908. osVersion = system;
  909. }
  910. let hostVersion = version;
  911. // deviceType
  912. let deviceType = getGetDeviceType(fromRes, model);
  913. // deviceModel
  914. let deviceBrand = getDeviceBrand(brand);
  915. // hostName
  916. let _hostName = getHostName(fromRes);
  917. // deviceOrientation
  918. let _deviceOrientation = deviceOrientation; // 仅 微信 百度 支持
  919. // devicePixelRatio
  920. let _devicePixelRatio = pixelRatio;
  921. // SDKVersion
  922. let _SDKVersion = SDKVersion;
  923. {
  924. _SDKVersion = my.SDKVersion;
  925. }
  926. // hostLanguage
  927. const hostLanguage = language.replace(/_/g, '-');
  928. // wx.getAccountInfoSync
  929. const parameters = {
  930. appId: process.env.UNI_APP_ID,
  931. appName: process.env.UNI_APP_NAME,
  932. appVersion: process.env.UNI_APP_VERSION_NAME,
  933. appVersionCode: process.env.UNI_APP_VERSION_CODE,
  934. appLanguage: getAppLanguage(hostLanguage),
  935. uniCompileVersion: process.env.UNI_COMPILER_VERSION,
  936. uniRuntimeVersion: process.env.UNI_COMPILER_VERSION,
  937. uniPlatform: process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM,
  938. deviceBrand,
  939. deviceModel: model,
  940. deviceType,
  941. devicePixelRatio: _devicePixelRatio,
  942. deviceOrientation: _deviceOrientation,
  943. osName: osName.toLocaleLowerCase(),
  944. osVersion,
  945. hostTheme: theme,
  946. hostVersion,
  947. hostLanguage,
  948. hostName: _hostName,
  949. hostSDKVersion: _SDKVersion,
  950. hostFontSizeSetting: fontSizeSetting,
  951. windowTop: 0,
  952. windowBottom: 0,
  953. // TODO
  954. osLanguage: undefined,
  955. osTheme: undefined,
  956. ua: undefined,
  957. hostPackageName: undefined,
  958. browserName: undefined,
  959. browserVersion: undefined,
  960. };
  961. extend(toRes, parameters);
  962. }
  963. function getGetDeviceType(fromRes, model) {
  964. // deviceType
  965. let deviceType = fromRes.deviceType || 'phone';
  966. {
  967. const deviceTypeMaps = {
  968. ipad: 'pad',
  969. windows: 'pc',
  970. mac: 'pc',
  971. };
  972. const deviceTypeMapsKeys = Object.keys(deviceTypeMaps);
  973. const _model = model.toLocaleLowerCase();
  974. for (let index = 0; index < deviceTypeMapsKeys.length; index++) {
  975. const _m = deviceTypeMapsKeys[index];
  976. if (_model.indexOf(_m) !== -1) {
  977. deviceType = deviceTypeMaps[_m];
  978. break;
  979. }
  980. }
  981. }
  982. return deviceType;
  983. }
  984. function getDeviceBrand(brand) {
  985. // deviceModel
  986. let deviceBrand = brand;
  987. if (deviceBrand) {
  988. deviceBrand = deviceBrand.toLocaleLowerCase();
  989. }
  990. return deviceBrand;
  991. }
  992. function getAppLanguage(defaultLanguage) {
  993. return getLocale ? getLocale() : defaultLanguage;
  994. }
  995. function getHostName(fromRes) {
  996. const _platform = "mp-alipay".split('-')[1];
  997. let _hostName = fromRes.hostName || _platform; // mp-jd
  998. _hostName = fromRes.app;
  999. return _hostName;
  1000. }
  1001. const redirectTo = {};
  1002. const eventChannels = {};
  1003. let id = 0;
  1004. function initEventChannel(events, cache = true) {
  1005. id++;
  1006. const eventChannel = new my.EventChannel(id, events);
  1007. if (cache) {
  1008. eventChannels[id] = eventChannel;
  1009. }
  1010. return eventChannel;
  1011. }
  1012. function getEventChannel(id) {
  1013. const eventChannel = eventChannels[id];
  1014. delete eventChannels[id];
  1015. return eventChannel;
  1016. }
  1017. const navigateTo$1 = () => {
  1018. let eventChannel;
  1019. return {
  1020. args(fromArgs) {
  1021. eventChannel = initEventChannel(fromArgs.events);
  1022. if (fromArgs.url) {
  1023. fromArgs.url =
  1024. fromArgs.url +
  1025. (fromArgs.url.indexOf('?') === -1 ? '?' : '&') +
  1026. '__id__=' +
  1027. eventChannel.id;
  1028. }
  1029. },
  1030. returnValue(fromRes) {
  1031. fromRes.eventChannel = eventChannel;
  1032. },
  1033. };
  1034. };
  1035. const baseApis = {
  1036. $on,
  1037. $off,
  1038. $once,
  1039. $emit,
  1040. upx2px,
  1041. interceptors,
  1042. addInterceptor,
  1043. removeInterceptor,
  1044. onCreateVueApp,
  1045. invokeCreateVueAppHook,
  1046. getLocale,
  1047. setLocale,
  1048. onLocaleChange,
  1049. getPushClientId,
  1050. onPushMessage,
  1051. offPushMessage,
  1052. invokePushCallback,
  1053. };
  1054. function initUni(api, protocols, platform = my) {
  1055. const wrapper = initWrapper(protocols);
  1056. const UniProxyHandlers = {
  1057. get(target, key) {
  1058. if (hasOwn(target, key)) {
  1059. return target[key];
  1060. }
  1061. if (hasOwn(api, key)) {
  1062. return promisify(key, api[key]);
  1063. }
  1064. if (hasOwn(baseApis, key)) {
  1065. return promisify(key, baseApis[key]);
  1066. }
  1067. // event-api
  1068. // provider-api?
  1069. return promisify(key, wrapper(key, platform[key]));
  1070. },
  1071. };
  1072. // 处理 api mp 打包后为不同js,emitter 无法共享问题
  1073. {
  1074. platform.$emit = $emit;
  1075. if (!my.canIUse('getOpenerEventChannel'))
  1076. platform.getEventChannel = getEventChannel;
  1077. }
  1078. return new Proxy({}, UniProxyHandlers);
  1079. }
  1080. function initGetProvider(providers) {
  1081. return function getProvider({ service, success, fail, complete, }) {
  1082. let res;
  1083. if (providers[service]) {
  1084. res = {
  1085. errMsg: 'getProvider:ok',
  1086. service,
  1087. provider: providers[service],
  1088. };
  1089. isFunction(success) && success(res);
  1090. }
  1091. else {
  1092. res = {
  1093. errMsg: 'getProvider:fail:服务[' + service + ']不存在',
  1094. };
  1095. isFunction(fail) && fail(res);
  1096. }
  1097. isFunction(complete) && complete(res);
  1098. };
  1099. }
  1100. let onKeyboardHeightChangeCallback;
  1101. const getProvider = initGetProvider({
  1102. oauth: ['alipay'],
  1103. share: ['alipay'],
  1104. payment: ['alipay'],
  1105. push: ['alipay'],
  1106. });
  1107. function setStorageSync(key, data) {
  1108. return my.setStorageSync({
  1109. key,
  1110. data,
  1111. });
  1112. }
  1113. function getStorageSync(key) {
  1114. const result = my.getStorageSync({
  1115. key,
  1116. });
  1117. // 支付宝平台会返回一个 success 值,但是目前测试的结果这个始终是 true。当没有存储数据的时候,其它平台会返回空字符串。
  1118. return result.data !== null ? result.data : '';
  1119. }
  1120. function removeStorageSync(key) {
  1121. return my.removeStorageSync({
  1122. key,
  1123. });
  1124. }
  1125. function startGyroscope(args) {
  1126. if (hasOwn(args, 'interval')) {
  1127. console.warn('支付宝小程序 startGyroscope暂不支持interval');
  1128. }
  1129. args.success &&
  1130. args.success({
  1131. errMsg: 'startGyroscope:ok',
  1132. });
  1133. args.complete &&
  1134. args.complete({
  1135. errMsg: 'startGyroscope:ok',
  1136. });
  1137. }
  1138. function createExecCallback(execCallback) {
  1139. return function wrapperExecCallback(res) {
  1140. this.actions.forEach((action, index) => {
  1141. (action._$callbacks || []).forEach((callback) => {
  1142. callback(res[index]);
  1143. });
  1144. });
  1145. if (isFunction(execCallback)) {
  1146. execCallback(res);
  1147. }
  1148. };
  1149. }
  1150. function addCallback(callback) {
  1151. if (isFunction(callback)) {
  1152. const action = this.actions[this.actions.length - 1];
  1153. if (action) {
  1154. (action._$callbacks || (action._$callbacks = [])).push(callback);
  1155. }
  1156. }
  1157. }
  1158. function createSelectorQuery() {
  1159. const query = my.createSelectorQuery();
  1160. const oldExec = query.exec;
  1161. const oldScrollOffset = query.scrollOffset;
  1162. const oldBoundingClientRect = query.boundingClientRect;
  1163. query.exec = function exec(callback) {
  1164. return oldExec.call(this, createExecCallback(callback).bind(this));
  1165. };
  1166. query.scrollOffset = function scrollOffset(callback) {
  1167. const ret = oldScrollOffset.call(this);
  1168. addCallback.call(this, callback);
  1169. return ret;
  1170. };
  1171. query.boundingClientRect = function boundingClientRect(callback) {
  1172. const ret = oldBoundingClientRect.call(this);
  1173. addCallback.call(this, callback);
  1174. return ret;
  1175. };
  1176. if (!query.fields) {
  1177. query.fields = function ({ rect, size, scrollOffset }, callback) {
  1178. if (rect || size) {
  1179. this.boundingClientRect();
  1180. }
  1181. if (scrollOffset) {
  1182. this.scrollOffset();
  1183. }
  1184. addCallback.call(this, callback);
  1185. return this;
  1186. };
  1187. }
  1188. if (!query.in) {
  1189. query.in = function () {
  1190. return this;
  1191. };
  1192. }
  1193. return query;
  1194. }
  1195. function createIntersectionObserver(component, options) {
  1196. if (options && options.observeAll) {
  1197. options.selectAll = options.observeAll;
  1198. delete options.observeAll;
  1199. }
  1200. return my.createIntersectionObserver(options);
  1201. }
  1202. function onKeyboardHeightChange(callback) {
  1203. // 与微信小程序一致仅保留最后一次监听
  1204. if (onKeyboardHeightChangeCallback) {
  1205. $off('uni:keyboardHeightChange', onKeyboardHeightChangeCallback);
  1206. }
  1207. onKeyboardHeightChangeCallback = callback;
  1208. $on('uni:keyboardHeightChange', onKeyboardHeightChangeCallback);
  1209. }
  1210. function offKeyboardHeightChange() {
  1211. // 与微信小程序一致移除最后一次监听
  1212. $off('uni:keyboardHeightChange', onKeyboardHeightChangeCallback);
  1213. onKeyboardHeightChangeCallback = undefined;
  1214. }
  1215. var shims = /*#__PURE__*/Object.freeze({
  1216. __proto__: null,
  1217. createIntersectionObserver: createIntersectionObserver,
  1218. createSelectorQuery: createSelectorQuery,
  1219. getProvider: getProvider,
  1220. getStorageSync: getStorageSync,
  1221. offKeyboardHeightChange: offKeyboardHeightChange,
  1222. onKeyboardHeightChange: onKeyboardHeightChange,
  1223. removeStorageSync: removeStorageSync,
  1224. setStorageSync: setStorageSync,
  1225. startGyroscope: startGyroscope
  1226. });
  1227. function handleNetworkInfo(fromRes, toRes) {
  1228. const nextworkType = fromRes.networkType;
  1229. switch (nextworkType) {
  1230. case 'NOTREACHABLE':
  1231. toRes.networkType = 'none';
  1232. break;
  1233. case 'WWAN':
  1234. // TODO ?
  1235. toRes.networkType = '3g';
  1236. break;
  1237. default:
  1238. toRes.networkType = fromRes.networkType.toLowerCase();
  1239. break;
  1240. }
  1241. }
  1242. function handleSystemInfo(fromRes, toRes) {
  1243. addSafeAreaInsets(fromRes, toRes);
  1244. useDeviceId({
  1245. getStorageSync: getStorageSync,
  1246. })(fromRes, toRes);
  1247. populateParameters(fromRes, toRes);
  1248. let platform = fromRes.platform ? fromRes.platform.toLowerCase() : 'devtools';
  1249. if (my.canIUse('isIDE')) {
  1250. // @ts-expect-error Property 'isIDE' does not exist on type 'typeof my'
  1251. platform = my.isIDE ? 'devtools' : platform;
  1252. }
  1253. else {
  1254. if (!~['android', 'ios'].indexOf(platform)) {
  1255. platform = 'devtools';
  1256. }
  1257. }
  1258. toRes.platform = platform;
  1259. }
  1260. function returnValue(methodName, res = {}) {
  1261. // 通用 returnValue 解析
  1262. if (res.error || res.errorMessage) {
  1263. res.errMsg = `${methodName}:fail ${res.errorMessage || res.error}`;
  1264. delete res.error;
  1265. delete res.errorMessage;
  1266. }
  1267. else {
  1268. res.errMsg = `${methodName}:ok`;
  1269. }
  1270. return res;
  1271. }
  1272. const request = {
  1273. name: my.canIUse('request') ? 'request' : 'httpRequest',
  1274. args(fromArgs) {
  1275. const method = fromArgs.method || 'GET';
  1276. if (!fromArgs.header) {
  1277. // 默认增加 header 参数,方便格式化 content-type
  1278. fromArgs.header = {};
  1279. }
  1280. const headers = {
  1281. 'content-type': 'application/json',
  1282. };
  1283. Object.keys(fromArgs.header).forEach((key) => {
  1284. headers[key.toLocaleLowerCase()] = fromArgs.header[key];
  1285. });
  1286. return {
  1287. header() {
  1288. return {
  1289. name: 'headers',
  1290. value: headers,
  1291. };
  1292. },
  1293. data(data) {
  1294. // 钉钉小程序在content-type为application/json时需上传字符串形式data,使用my.dd在真机运行钉钉小程序时不能正确判断
  1295. if (my.canIUse('saveFileToDingTalk') &&
  1296. method.toUpperCase() === 'POST' &&
  1297. headers['content-type'].indexOf('application/json') === 0 &&
  1298. isPlainObject(data)) {
  1299. return {
  1300. name: 'data',
  1301. value: JSON.stringify(data),
  1302. };
  1303. }
  1304. return {
  1305. name: 'data',
  1306. value: data,
  1307. };
  1308. },
  1309. method: 'method',
  1310. responseType: false,
  1311. };
  1312. },
  1313. returnValue: {
  1314. status: 'statusCode',
  1315. headers: 'header',
  1316. },
  1317. };
  1318. const setNavigationBarColor = {
  1319. name: 'setNavigationBar',
  1320. args: {
  1321. frontColor: false,
  1322. animation: false,
  1323. },
  1324. };
  1325. const setNavigationBarTitle = {
  1326. name: 'setNavigationBar',
  1327. };
  1328. function showModal({ showCancel = true } = {}) {
  1329. if (showCancel) {
  1330. return {
  1331. name: 'confirm',
  1332. args: {
  1333. cancelColor: false,
  1334. confirmColor: false,
  1335. cancelText: 'cancelButtonText',
  1336. confirmText: 'confirmButtonText',
  1337. },
  1338. returnValue(fromRes, toRes) {
  1339. toRes.confirm = fromRes.confirm;
  1340. toRes.cancel = !fromRes.confirm;
  1341. },
  1342. };
  1343. }
  1344. return {
  1345. name: 'alert',
  1346. args: {
  1347. confirmColor: false,
  1348. confirmText: 'buttonText',
  1349. },
  1350. returnValue(fromRes, toRes) {
  1351. toRes.confirm = true;
  1352. toRes.cancel = false;
  1353. },
  1354. };
  1355. }
  1356. function showToast({ icon = 'success' } = {}) {
  1357. const args = {
  1358. title: 'content',
  1359. icon: 'type',
  1360. image: false,
  1361. mask: false,
  1362. };
  1363. if (icon === 'loading') {
  1364. return {
  1365. name: 'showLoading',
  1366. args,
  1367. };
  1368. }
  1369. return {
  1370. name: 'showToast',
  1371. args,
  1372. };
  1373. }
  1374. const showActionSheet = {
  1375. name: 'showActionSheet',
  1376. args: {
  1377. itemList: 'items',
  1378. itemColor: false,
  1379. },
  1380. returnValue: {
  1381. index: 'tapIndex',
  1382. },
  1383. };
  1384. const showLoading = {
  1385. args: {
  1386. title: 'content',
  1387. },
  1388. };
  1389. const uploadFile = {
  1390. args: {
  1391. name: 'fileName',
  1392. },
  1393. // 从测试结果看,是有返回对象的,文档上没有说明。
  1394. };
  1395. const downloadFile = {
  1396. returnValue: {
  1397. apFilePath: 'tempFilePath',
  1398. },
  1399. };
  1400. const getFileInfo = {
  1401. args: {
  1402. filePath: 'apFilePath',
  1403. },
  1404. };
  1405. const compressImage = {
  1406. args(fromArgs, toArgs) {
  1407. toArgs.compressLevel = 4;
  1408. if (fromArgs && fromArgs.quality) {
  1409. toArgs.compressLevel = Math.floor(fromArgs.quality / 26);
  1410. }
  1411. if (fromArgs.src) {
  1412. toArgs.apFilePaths = [fromArgs.src];
  1413. }
  1414. },
  1415. returnValue(fromRes, toRes) {
  1416. const apFilePaths = fromRes.apFilePaths;
  1417. if (apFilePaths && apFilePaths.length) {
  1418. toRes.tempFilePath = apFilePaths[0];
  1419. }
  1420. },
  1421. };
  1422. const chooseVideo = {
  1423. // 支付宝小程序文档中未找到(仅在getSetting处提及),但实际可用
  1424. returnValue: {
  1425. apFilePath: 'tempFilePath',
  1426. },
  1427. };
  1428. const connectSocket = {
  1429. args: {
  1430. method: false,
  1431. protocols: false,
  1432. },
  1433. // TODO 有没有返回值还需要测试下
  1434. };
  1435. const chooseImage = {
  1436. returnValue(result) {
  1437. var _a, _b;
  1438. const hasTempFilePaths = hasOwn(result, 'tempFilePaths') && result.tempFilePaths;
  1439. if (hasOwn(result, 'apFilePaths') && !hasTempFilePaths) {
  1440. result.tempFilePaths = [];
  1441. (_a = result.apFilePaths) === null || _a === void 0 ? void 0 : _a.forEach((apFilePath) => { var _a; return (_a = result.tempFilePaths) === null || _a === void 0 ? void 0 : _a.push(apFilePath); });
  1442. }
  1443. if (!hasOwn(result, 'tempFiles') && hasTempFilePaths) {
  1444. result.tempFiles = [];
  1445. (_b = result.tempFilePaths) === null || _b === void 0 ? void 0 : _b.forEach((tempFilePath) => { var _a; return (_a = result.tempFiles) === null || _a === void 0 ? void 0 : _a.push({ path: tempFilePath }); });
  1446. }
  1447. return {};
  1448. },
  1449. };
  1450. const previewImage = {
  1451. args(fromArgs, toArgs) {
  1452. // 支付宝小程序的 current 是索引值,而非图片地址。
  1453. const currentIndex = Number(fromArgs.current);
  1454. if (isNaN(currentIndex)) {
  1455. if (fromArgs.current && isArray(fromArgs.urls)) {
  1456. const index = fromArgs.urls.indexOf(fromArgs.current);
  1457. toArgs.current = ~index ? index : 0;
  1458. }
  1459. }
  1460. else {
  1461. toArgs.current = currentIndex;
  1462. }
  1463. return {
  1464. indicator: false,
  1465. loop: false,
  1466. };
  1467. },
  1468. };
  1469. const saveFile = {
  1470. args: {
  1471. tempFilePath: 'apFilePath',
  1472. },
  1473. returnValue: {
  1474. apFilePath: 'savedFilePath',
  1475. },
  1476. };
  1477. const getSavedFileInfo = {
  1478. args: {
  1479. filePath: 'apFilePath',
  1480. },
  1481. };
  1482. const getSavedFileList = {
  1483. returnValue(fromRes, toRes) {
  1484. toRes.fileList = fromRes.fileList.map((file) => {
  1485. return {
  1486. filePath: file.apFilePath,
  1487. createTime: file.createTime,
  1488. size: file.size,
  1489. };
  1490. });
  1491. },
  1492. };
  1493. const removeSavedFile = {
  1494. args: {
  1495. filePath: 'apFilePath',
  1496. },
  1497. };
  1498. const getLocation = {
  1499. args: {
  1500. type: false,
  1501. altitude: false,
  1502. },
  1503. };
  1504. const openLocation = {
  1505. args: {
  1506. // TODO address 参数在阿里上是必传的
  1507. },
  1508. };
  1509. const getNetworkType = {
  1510. returnValue: handleNetworkInfo,
  1511. };
  1512. const onNetworkStatusChange = {
  1513. returnValue: handleNetworkInfo,
  1514. };
  1515. const stopAccelerometer = {
  1516. name: 'offAccelerometerChange',
  1517. };
  1518. const stopCompass = {
  1519. name: 'offCompassChange',
  1520. };
  1521. const scanCode = {
  1522. name: 'scan',
  1523. args: {
  1524. onlyFromCamera: 'hideAlbum',
  1525. },
  1526. returnValue: {
  1527. code: 'result',
  1528. },
  1529. };
  1530. const setClipboardData = {
  1531. name: 'setClipboard',
  1532. args: {
  1533. data: 'text',
  1534. },
  1535. };
  1536. const getClipboardData = {
  1537. name: 'getClipboard',
  1538. returnValue: {
  1539. text: 'data',
  1540. },
  1541. };
  1542. const pageScrollTo = {
  1543. args: {
  1544. duration: false,
  1545. },
  1546. };
  1547. const login = {
  1548. name: 'getAuthCode',
  1549. returnValue: {
  1550. authCode: 'code',
  1551. },
  1552. };
  1553. const getUserInfo = {
  1554. name: my.canIUse('getOpenUserInfo') ? 'getOpenUserInfo' : 'getAuthUserInfo',
  1555. returnValue(fromRes, toRes) {
  1556. if (my.canIUse('getOpenUserInfo')) {
  1557. let response;
  1558. try {
  1559. response = JSON.parse(fromRes.response).response;
  1560. }
  1561. catch (e) { }
  1562. if (response) {
  1563. toRes.userInfo = response;
  1564. toRes.userInfo.avatarUrl = response.avatar;
  1565. delete response.avatar;
  1566. }
  1567. }
  1568. else {
  1569. toRes.userInfo = {
  1570. openId: '',
  1571. nickName: fromRes.nickName,
  1572. avatarUrl: fromRes.avatar,
  1573. };
  1574. }
  1575. },
  1576. };
  1577. const requestPayment = {
  1578. name: 'tradePay',
  1579. args: {
  1580. orderInfo: 'tradeNO',
  1581. },
  1582. };
  1583. const getBLEDeviceServices = {
  1584. returnValue(fromRes, toRes) {
  1585. toRes.services = fromRes.services.map((item) => {
  1586. return {
  1587. uuid: item.serviceId,
  1588. isPrimary: item.isPrimary,
  1589. };
  1590. });
  1591. },
  1592. };
  1593. const createBLEConnection = {
  1594. name: 'connectBLEDevice',
  1595. args: {
  1596. timeout: false,
  1597. },
  1598. };
  1599. const closeBLEConnection = {
  1600. name: 'disconnectBLEDevice',
  1601. };
  1602. const onBLEConnectionStateChange = {
  1603. name: 'onBLEConnectionStateChanged',
  1604. };
  1605. const makePhoneCall = {
  1606. args: {
  1607. phoneNumber: 'number',
  1608. },
  1609. };
  1610. const stopGyroscope = {
  1611. name: 'offGyroscopeChange',
  1612. };
  1613. const getSystemInfo = {
  1614. returnValue: handleSystemInfo,
  1615. };
  1616. const getSystemInfoSync = {
  1617. returnValue: handleSystemInfo,
  1618. };
  1619. // 文档没提到,但是实测可用。
  1620. const canvasToTempFilePath = {
  1621. returnValue(fromRes, toRes) {
  1622. // 真机的情况下会有 tempFilePath 这个值,因此需要主动修改。
  1623. toRes.tempFilePath = fromRes.apFilePath;
  1624. },
  1625. };
  1626. const setScreenBrightness = {
  1627. args: {
  1628. value: 'brightness',
  1629. },
  1630. };
  1631. const getScreenBrightness = {
  1632. returnValue: {
  1633. brightness: 'value',
  1634. },
  1635. };
  1636. const showShareMenu = {
  1637. name: 'showSharePanel',
  1638. };
  1639. const hideHomeButton = {
  1640. name: 'hideBackHome',
  1641. };
  1642. // 钉钉小程序处理
  1643. const saveImageToPhotosAlbum = my.canIUse('saveImageToPhotosAlbum')
  1644. ? {}
  1645. : {
  1646. name: 'saveImage',
  1647. args: {
  1648. filePath: 'url',
  1649. },
  1650. };
  1651. const saveVideoToPhotosAlbum = {
  1652. args: {
  1653. filePath: 'src',
  1654. },
  1655. };
  1656. const chooseAddress = {
  1657. name: 'getAddress',
  1658. returnValue(fromRes, toRes) {
  1659. const info = fromRes.result || {};
  1660. toRes.userName = info.fullname;
  1661. toRes.countyName = info.country;
  1662. toRes.provinceName = info.prov;
  1663. toRes.cityName = info.city;
  1664. toRes.detailInfo = info.address;
  1665. toRes.telNumber = info.mobilePhone;
  1666. toRes.errMsg = toRes.errMsg + ' ' + fromRes.resultStatus;
  1667. },
  1668. };
  1669. const navigateTo = my.canIUse('getOpenerEventChannel')
  1670. ? {}
  1671. : navigateTo$1();
  1672. var protocols = /*#__PURE__*/Object.freeze({
  1673. __proto__: null,
  1674. canvasToTempFilePath: canvasToTempFilePath,
  1675. chooseAddress: chooseAddress,
  1676. chooseImage: chooseImage,
  1677. chooseVideo: chooseVideo,
  1678. closeBLEConnection: closeBLEConnection,
  1679. compressImage: compressImage,
  1680. connectSocket: connectSocket,
  1681. createBLEConnection: createBLEConnection,
  1682. downloadFile: downloadFile,
  1683. getBLEDeviceServices: getBLEDeviceServices,
  1684. getClipboardData: getClipboardData,
  1685. getFileInfo: getFileInfo,
  1686. getLocation: getLocation,
  1687. getNetworkType: getNetworkType,
  1688. getSavedFileInfo: getSavedFileInfo,
  1689. getSavedFileList: getSavedFileList,
  1690. getScreenBrightness: getScreenBrightness,
  1691. getSystemInfo: getSystemInfo,
  1692. getSystemInfoSync: getSystemInfoSync,
  1693. getUserInfo: getUserInfo,
  1694. hideHomeButton: hideHomeButton,
  1695. login: login,
  1696. makePhoneCall: makePhoneCall,
  1697. navigateTo: navigateTo,
  1698. onBLEConnectionStateChange: onBLEConnectionStateChange,
  1699. onNetworkStatusChange: onNetworkStatusChange,
  1700. openLocation: openLocation,
  1701. pageScrollTo: pageScrollTo,
  1702. previewImage: previewImage,
  1703. redirectTo: redirectTo,
  1704. removeSavedFile: removeSavedFile,
  1705. request: request,
  1706. requestPayment: requestPayment,
  1707. returnValue: returnValue,
  1708. saveFile: saveFile,
  1709. saveImageToPhotosAlbum: saveImageToPhotosAlbum,
  1710. saveVideoToPhotosAlbum: saveVideoToPhotosAlbum,
  1711. scanCode: scanCode,
  1712. setClipboardData: setClipboardData,
  1713. setNavigationBarColor: setNavigationBarColor,
  1714. setNavigationBarTitle: setNavigationBarTitle,
  1715. setScreenBrightness: setScreenBrightness,
  1716. showActionSheet: showActionSheet,
  1717. showLoading: showLoading,
  1718. showModal: showModal,
  1719. showShareMenu: showShareMenu,
  1720. showToast: showToast,
  1721. stopAccelerometer: stopAccelerometer,
  1722. stopCompass: stopCompass,
  1723. stopGyroscope: stopGyroscope,
  1724. uploadFile: uploadFile
  1725. });
  1726. var index = initUni(shims, protocols);
  1727. export { index as default };