my-uniapp-tools 3.0.1 → 3.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/my-uniapp-tools.cjs.js +1 -1
- package/dist/my-uniapp-tools.esm.js +1 -1
- package/dist/upload/index.d.ts +9 -0
- package/dist/utils/index.d.ts +22 -76
- package/dist/weixin/index.d.ts +12 -19
- package/package.json +3 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("@vant/area-data");class t extends Error{code;module;timestamp;constructor(e,t,n){super(t),this.name="UniAppToolsError",this.code=e,this.module=n,this.timestamp=Date.now()}}class n{static instance;errorCallbacks=[];static getInstance(){return n.instance||(n.instance=new n),n.instance}onError(e){this.errorCallbacks.push(e)}handleError(e,n){const r={code:e instanceof t?e.code:"UNKNOWN_ERROR",message:e.message,module:e instanceof t?e.module:n,timestamp:e instanceof t?e.timestamp:Date.now(),stack:e.stack};this.errorCallbacks.forEach(e=>{try{e(r)}catch(e){}})}createModuleErrorHandler(e){return(n,r,s)=>{const o=new t(n,r,e);return s&&(o.stack=s.stack),this.handleError(o,e),o}}}async function r(e,t,r="ASYNC_ERROR"){try{return await e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(r,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function s(e,t,r="SYNC_ERROR",s=null){try{return e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(r,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),s}}var o=Object.freeze({__proto__:null,ErrorHandler:n,UniAppToolsError:t,safeAsync:r,safeSync:s});function a(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}class c{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return c.instance||(c.instance=new c),c.instance}start(e,t,n){const r={name:e,startTime:a(),module:t,metadata:n};this.metrics.set(e,r)}end(e){const t=this.metrics.get(e);return t?(t.endTime=a(),t.duration=t.endTime-t.startTime,this.metrics.delete(e),this.completedMetrics.push(t),this.completedMetrics.length>this.maxStoredMetrics&&this.completedMetrics.shift(),t):null}getReport(){const e={},t={};this.completedMetrics.forEach(n=>{e[n.module]||(e[n.module]=[]),e[n.module].push(n);const r=`${n.module}.${n.name}`;t[r]||(t[r]={total:0,count:0}),t[r].total+=n.duration||0,t[r].count+=1});const n={};Object.entries(t).forEach(([e,t])=>{n[e]=t.total/t.count});const r=[...this.completedMetrics].sort((e,t)=>(t.duration||0)-(e.duration||0)).slice(0,10);return{byModule:e,slowest:r,average:n}}clear(){this.metrics.clear(),this.completedMetrics=[]}}function i(e){return function(t,n,r){const s=r.value;r.value=function(...r){const o=c.getInstance(),a=`${t.constructor.name}.${n}`;o.start(a,e,{args:r.length});try{const e=s.apply(this,r);return e instanceof Promise?e.finally(()=>{o.end(a)}):(o.end(a),e)}catch(e){throw o.end(a),e}}}}var u=Object.freeze({__proto__:null,PerformanceMonitor:c,measurePerformance:i});class l{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return l.instance||(l.instance=new l),l.instance}set(e,t,n=this.defaultTTL){this.cache.set(e,{data:t,timestamp:Date.now(),ttl:n})}get(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttl?(this.cache.delete(e),null):t.data:null}clear(){this.cache.clear()}}const f=l.getInstance(),p=(e=!0)=>{const t=c.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=f.get(n);if(e)return t.end("getWindowInfo"),e}const r=s(()=>{const t=uni.getWindowInfo();return e&&f.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),r},d=()=>{const e="platform",t=f.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",f.set(e,"h5"),"h5"},m=()=>{try{const e=p();return e?.statusBarHeight||0}catch(e){return 0}},h=()=>{try{const e=d();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},g=()=>{try{const e=m(),t=d();if("weixin"===t||"alipay"===t){const t=h();if(t){return t.height+e}}return e+0}catch(e){return m()+0}};function w(e){if(null===e||"object"!=typeof e)return e;try{if("undefined"!=typeof structuredClone)try{return structuredClone(e)}catch(e){}return JSON.parse(JSON.stringify(e))}catch(e){throw new Error(`深拷贝失败: ${e instanceof Error?e.message:String(e)}`)}}function y(e,t){return Object.assign(e,t)}function x(e,t,n=!1){let r,s=null;const o=function(...o){const a=n&&!s;return s&&clearTimeout(s),s=setTimeout(()=>{s=null,n||(r=e.apply(this,o))},t),a&&(r=e.apply(this,o)),r};return o.cancel=()=>{s&&(clearTimeout(s),s=null)},o}const S=e.areaList,E=e.useCascaderAreaData;const v=(e="",t=!1,n="none",r=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:r})};function T(e,t){if(!t||0===Object.keys(t).length)return e;const n=Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");return e+(e.includes("?")?"&":"?")+n}async function P(e){return new Promise(t=>{const n=T(e.url,e.params);uni.navigateTo({url:n,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>t(!0),fail:e=>{t(!1)}})})}async function C(e="",t={}){return new Promise(n=>{const r=t.delta||1,s=t.timeout||5e3;if(getCurrentPages().length<=r)return void n(!1);const o=setTimeout(()=>{n(!1)},s);uni.navigateBack({delta:r,success:()=>{clearTimeout(o),setTimeout(()=>{try{const t=getCurrentPages();if(t.length>0){const n=t[t.length-1];n.$vm&&"function"==typeof n.$vm.init&&n.$vm.init(e)}n(!0)}catch(e){n(!0)}},100)},fail:e=>{clearTimeout(o),n(!1)}})})}const R=x(C,300);async function I(e){return new Promise(t=>{const n=T(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}const M={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};class A{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return A.instance||(A.instance=new A),A.instance}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,n={}){try{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const r={value:t,timestamp:Date.now(),ttl:n.ttl},s=JSON.stringify(r);if(s.length>1048576)throw new Error("存储数据过大");if(uni.setStorageSync(e,s),this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}return this.cache.set(e,r),!0}catch(e){throw e}}get(e,t){try{if(!e||"string"!=typeof e)return t;if(this.cache.has(e)){const n=this.cache.get(e);return this.isExpired(n)?(this.cache.delete(e),this.remove(e),t):n.value}const n=uni.getStorageSync(e);if(!n||"string"!=typeof n)return t;const r=JSON.parse(n);let s;return s=r&&"object"==typeof r&&"value"in r&&"timestamp"in r?r:{value:r,timestamp:Date.now()},this.isExpired(s)?(this.remove(e),t):(this.cache.set(e,s),s.value)}catch(e){return t}}remove(e){try{return!(!e||"string"!=typeof e)&&(uni.removeStorageSync(e),this.cache.delete(e),!0)}catch(e){return!1}}clear(){try{return uni.clearStorageSync(),this.cache.clear(),!0}catch(e){return!1}}getInfo(){try{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}}catch(e){return{keys:[],currentSize:0,limitSize:0}}}cleanExpired(){try{const e=this.getInfo();let t=0;return e.keys.forEach(e=>{void 0===this.get(e)&&t++}),t}catch(e){return 0}}}const b=A.getInstance();function O(e,t,n={}){return b.set(e,t,n)}function _(e,t){return b.get(e,t)}function D(e,t){if(!t)return{valid:!0};return e>1024*t*1024?{valid:!1,message:`文件大小不能超过 ${t}MB`}:{valid:!0}}function k(e){const t=e.lastIndexOf(".");if(-1!==t&&t!==e.length-1)return e.slice(t+1).toLowerCase()}function j(e){return`${Date.now()}_${e}_${Math.random().toString(16).slice(2)}`}function U(e,t){if(0===e.length)return{success:!1,files:e,message:"未选择任何文件"};const{maxSelectFileSizeMB:n,extensions:r}=t;if(n){if(e.some(e=>!D(e.size,n).valid))return{success:!1,files:e,message:`部分文件大小超过 ${n}MB 限制`}}if(r&&r.length>0){const t=r.map(e=>e.toLowerCase());if(e.some(e=>!e.ext||!t.includes(e.ext)))return{success:!1,files:e,message:`存在不支持的文件类型,仅支持:${r.join(", ")}`}}return{success:!0,files:e}}async function W(e){return"undefined"!=typeof document&&"undefined"!=typeof window?function(e){const{type:t="image",count:n=1,extensions:r}=e;return new Promise(s=>{if("undefined"==typeof document)return void s({success:!1,files:[],message:"当前环境不支持文件选择"});const o=document.createElement("input");o.type="file",o.multiple=n>1,"image"===t?o.accept="image/*":r&&r.length>0&&(o.accept=r.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),o.onchange=t=>{const n=t.target,r=n?.files;if(!r||0===r.length)return s({success:!1,files:[],message:"用户取消选择"}),void document.body.removeChild(o);const a=U(Array.from(r).map((e,t)=>{const n=k(e.name),r=URL.createObjectURL(e);return{id:j(t),name:e.name,size:e.size,path:r,mimeType:e.type,ext:n,source:"file",platform:"h5",raw:e}}),e);s(a),document.body.removeChild(o)},o.style.display="none",document.body.appendChild(o),o.click()})}(e):function(e){const{type:t="image",count:n=1}=e;return new Promise(r=>{const s="undefined"==typeof uni?null:uni;if(!s)return void r({success:!1,files:[],message:"当前环境不支持文件选择"});const o=e=>{r({success:!1,files:[],message:e?.errMsg||"选择文件失败"})};"image"!==t||"function"!=typeof s.chooseImage?"function"!=typeof s.chooseMessageFile?"function"!=typeof s.chooseFile?r({success:!1,files:[],message:"当前平台不支持文件选择"}):s.chooseFile({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=k(e.path);return{id:j(t),name:`file_${t}`,size:e.size,path:e.path,ext:n,source:"file",platform:"app",raw:e}});r(U(n,e))},fail:o}):s.chooseMessageFile({count:n,type:"all",success:t=>{const n=t.tempFiles.map((e,t)=>{const n=k(e.name||e.path);return{id:j(t),name:e.name,size:e.size,path:e.path,ext:n,source:"file",platform:"weixin",raw:e}});r(U(n,e))},fail:o}):s.chooseImage({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=k(e.path);return{id:j(t),name:`image_${t}`,size:e.size,path:e.path,ext:n,source:"album",platform:"weixin",raw:e}});r(U(n,e))},fail:o})})}(e)}async function B(e,t,n){const{url:r,maxUploadFileSizeMB:s,showToast:o=!0,beforeUpload:a}=t;if("function"==typeof a){if(!await Promise.resolve(a(e)))return{file:e,success:!1,message:"已取消上传"}}if(!r){const t="上传地址不能为空";return o&&v(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const c=D(e.size,s);return c.valid?"h5"===e.platform&&e.raw instanceof File?function(e,t,n){const{url:r,fieldName:s="file",formData:o,headers:a,showToast:c=!0,successMessage:i="上传成功",failMessage:u="上传失败",onProgress:l}=t;return new Promise(t=>{const f=e.raw;if(!(f&&f instanceof File)){const n="H5 环境缺少原生文件对象";return c&&v(n,!1,"error"),void t({file:e,success:!1,message:n})}const p=new XMLHttpRequest,d=new FormData;d.append(s,f,e.name),o&&Object.keys(o).forEach(e=>{d.append(e,String(o[e]))}),l&&p.upload.addEventListener("progress",t=>{if(t.lengthComputable){const n=Math.round(t.loaded/t.total*100);l(e,n)}}),p.addEventListener("load",()=>{const r=p.status,s=r>=200&&r<300;let o=p.responseText;try{o=JSON.parse(p.responseText)}catch{}if(s)c&&1===n&&v(i,!1,"success"),t({file:e,success:!0,statusCode:r,data:o});else{const n=`上传失败,状态码:${r}`;c&&v(n,!1,"error"),t({file:e,success:!1,statusCode:r,data:o,message:n})}}),p.addEventListener("error",()=>{const n=u;c&&v(n,!1,"error"),t({file:e,success:!1,message:n})}),p.addEventListener("abort",()=>{t({file:e,success:!1,message:"上传已取消"})}),p.open("POST",r),a&&Object.keys(a).forEach(e=>{p.setRequestHeader(e,a[e])}),p.send(d)})}(e,t,n):function(e,t,n){const{url:r,fieldName:s="file",formData:o,headers:a,showToast:c=!0,successMessage:i="上传成功",failMessage:u="上传失败",onProgress:l}=t,f="undefined"==typeof uni?null:uni;if(!f||"function"!=typeof f.uploadFile){const t="当前环境不支持文件上传";return c&&v(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{const p=f.uploadFile({url:r,filePath:e.path,name:s,formData:o,header:a,success:r=>{let s=r.data;try{s=JSON.parse(r.data)}catch{}const o=r.statusCode;if(o>=200&&o<300)c&&1===n&&v(i,!1,"success"),t({file:e,success:!0,statusCode:o,data:s});else{const n=`上传失败,状态码:${o}`;c&&v(n,!1,"error"),t({file:e,success:!1,statusCode:o,data:s,message:n})}},fail:n=>{const r=n?.errMsg||u;c&&v(r,!1,"error"),t({file:e,success:!1,message:r})}});l&&p&&"function"==typeof p.onProgressUpdate&&p.onProgressUpdate(t=>{l(e,t.progress)})})}(e,t,n):(o&&c.message&&v(c.message,!1,"error"),Promise.resolve({file:e,success:!1,message:c.message}))}async function F(e){const{showToast:t=!0,failMessage:n="选择文件失败"}=e;try{const r=await W(e);if(!r.success){const e=r.message||n;return t&&e&&v(e,!1,"error"),[{file:null,success:!1,message:e}]}const s=r.files;if(0===s.length)return[];const o=s.length;return await async function(e,t,n){const r=new Array(e.length),s=t.concurrency&&t.concurrency>0?Math.min(t.concurrency,e.length):e.length;let o=0;const a=async()=>{for(;;){const s=o;if(s>=e.length)break;o+=1;const a=e[s],c=await B(a,t,n);r[s]=c}},c=[];for(let e=0;e<s;e+=1)c.push(a());return await Promise.all(c),r}(s,e,o)}catch(e){const r=n;return t&&r&&v(r,!1,"error"),[{file:null,success:!1,message:r}]}}const H=()=>{const e=c.getInstance();e.start("isWechat","system");const t=s(()=>{if("undefined"!=typeof navigator&&navigator.userAgent){return navigator.userAgent.toLowerCase().includes("micromessenger")}return!1},"system","IS_WECHAT_ERROR",!1);return e.end("isWechat"),t||!1},L=()=>new Promise(e=>{if("undefined"!=typeof window&&window.wx)return void e(!0);const t=["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];let n=0;const r=s=>{const o=document.createElement("script");o.src=s,o.async=!0,o.onload=()=>{e(!0)},o.onerror=()=>{n++,n<t.length?(document.head.removeChild(o),r(t[n])):(document.head.removeChild(o),e(!1))},document.head.appendChild(o)};r(t[n]),e(!1)}),N=async e=>{const t=c.getInstance();t.start("configWechatJSSDK","wechat");try{if(!H())return!1;return!!await L()&&new Promise(t=>{window.wx?(window.wx.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),window.wx.ready(()=>{t(!0)}),window.wx.error(e=>{t(!1)})):t(!1),t(!1)})}catch(e){return!1}finally{t.end("configWechatJSSDK")}},$=e=>{s(()=>{window.wx&&H()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},z=e=>{s(()=>{window.wx&&H()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class J{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return J.instance||(J.instance=new J),J.instance}async init(e){return this.config=e,this.isConfigured=await N(e),this.isConfigured}isReady(){return this.isConfigured&&H()}getConfig(){return this.config}setShareData(e){this.isReady()&&($(e),z(e))}}exports.ErrorHandler=n,exports.PerformanceMonitor=c,exports.UniAppToolsError=t,exports.VERSION="2.0.0",exports.WechatSDK=J,exports.areaList=S,exports.batchGetStorage=function(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=_(e)}),t.end("batchGetStorage"),n},exports.batchSetStorage=function(e,t={}){const n=c.getInstance();n.start("batchSetStorage","localStorage");let r=0;return Object.entries(e).forEach(([e,n])=>{O(e,n,t)&&r++}),n.end("batchSetStorage"),r},exports.checkWechatJSAPI=e=>new Promise(t=>{window.wx&&H()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),exports.cleanExpiredStorage=function(){return b.cleanExpired()},exports.clearStorageSync=function(e){return e?b.remove(e):b.clear()},exports.configWechatJSSDK=N,exports.copyText=async function(e,t={}){const n=c.getInstance();n.start("copyText","clipboard",{textLength:e.length});const s={...M,...t};if(!e||"string"!=typeof e)return s.showToast&&v("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return s.showToast&&v("复制内容过长",!1,"error"),n.end("copyText"),!1;const o=await r(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{s.showToast&&v(s.successMessage),t(!0)},fail:()=>{s.showToast&&v(s.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),o},exports.debounce=x,exports.deepClone=w,exports.deepMerge=function(e,t){const n=w(e);return function e(t,n){for(const r in n)if(n.hasOwnProperty(r)){const s=n[r],o=t[r];s&&"object"==typeof s&&!Array.isArray(s)&&o&&"object"==typeof o&&!Array.isArray(o)?e(o,s):t[r]=w(s)}}(n,t),n},exports.extractUrlParts=function(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,r={};return t.searchParams.forEach((e,t)=>{r[t]=e}),{path:n,params:r}}catch(e){return{path:"",params:{}}}},exports.getCurrentEnv=()=>{try{const e=uni.getAccountInfoSync();return{appId:e.miniProgram?.appId||"",version:e.miniProgram?.version||"",envVersion:e.miniProgram?.envVersion||"",accountInfo:e}}catch(e){return{appId:"",version:"",envVersion:"",accountInfo:null}}},exports.getCurrentPageInfo=function(){try{const e=getCurrentPages();if(0===e.length)return null;const t=e[e.length-1];return{route:t.route||"",options:t.options||{}}}catch(e){return null}},exports.getH5UrlParams=e=>{try{if("undefined"==typeof window||!window.location)throw new Error("不在 H5 浏览器环境中");const t=new URLSearchParams(window.location.search),n={};return t.forEach((e,t)=>{try{n[t]=decodeURIComponent(e)}catch(r){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return e?null:{}}},exports.getMenuButtonBoundingClientRect=h,exports.getNavHeight=g,exports.getPageStack=function(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return[]}},exports.getPlatform=d,exports.getStatusBarHeight=m,exports.getStorage=async function(e,t){return await r(()=>new Promise(n=>{n(_(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t},exports.getStorageInfo=function(){return b.getInfo()},exports.getStorageSync=_,exports.getTopNavBarHeight=()=>{try{const e=m();return{statusBarHeight:e,navHeight:g()}}catch(e){return{statusBarHeight:0,navHeight:44}}},exports.initUniAppTools=async function(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,onError:r=null,performanceReportInterval:s=0}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return o}),t=e.getInstance();"function"==typeof r?t.onError(r):t.onError(e=>{})}if(t&&s>0){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return u}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},s)}},exports.isWechat=H,exports.loadWechatJSSDK=L,exports.measurePerformance=i,exports.mergeObjects=y,exports.navigateTo=P,exports.onCheckForUpdate=()=>{try{const e=uni.getUpdateManager();e.onCheckForUpdate(function(e){e.hasUpdate}),e.onUpdateReady(function(t){uni.showModal({title:"更新提示",content:"新版本已经准备好,是否重启应用?",showCancel:!0,cancelText:"稍后",confirmText:"立即重启",success(t){t.confirm&&e.applyUpdate()}})}),e.onUpdateFailed(function(e){uni.showModal({title:"更新失败",content:"新版本下载失败,请检查网络连接或稍后重试",showCancel:!1,confirmText:"知道了"})})}catch(e){}},exports.reLaunch=I,exports.redirectTo=async function(e){return new Promise(t=>{const n=T(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})},exports.safeAsync=r,exports.safeNavigateTo=async function(e,t=3){for(let n=0;n<t;n++){if(await P(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1},exports.safeSync=s,exports.selectAndUpload=F,exports.selectAndUploadImage=async function(e){return F({...e,type:"image"})},exports.setPageIcon=(e,t="image/x-icon")=>s(()=>{const n=d();if(("h5"===n||"web"===n)&&"undefined"!=typeof document){document.querySelectorAll('link[rel*="icon"]').forEach(e=>e.remove());const n=document.createElement("link");return n.rel="icon",n.type=t,n.href=e,document.head.appendChild(n),!0}return!1},"system","SET_PAGE_ICON_ERROR",!1),exports.setPageTitle=e=>e&&"string"==typeof e?new Promise(t=>{try{uni.setNavigationBarTitle({title:e,success:()=>{t(!0)},fail:e=>{t(!1)}})}catch(e){t(!1)}}):Promise.resolve(!1),exports.setStorage=async function(e,t,n={}){return await r(()=>new Promise(r=>{r(O(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1},exports.setStorageSync=O,exports.shareToFriend=z,exports.shareToTimeline=$,exports.switchTab=async function(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:e=>{t(!1)}})})},exports.throttle=function(e,t,n={}){let r,s=null,o=0;const{leading:a=!0,trailing:c=!0}=n,i=function(...n){const i=Date.now();o||a||(o=i);const u=t-(i-o);return u<=0||u>t?(s&&(clearTimeout(s),s=null),o=i,r=e.apply(this,n)):!s&&c&&(s=setTimeout(()=>{o=a?Date.now():0,s=null,r=e.apply(this,n)},u)),r};return i.cancel=()=>{s&&(clearTimeout(s),s=null),o=0},i},exports.useBack=C,exports.useBackDebounced=R,exports.useBackOrHome=async function(e="",t={}){const n=getCurrentPages(),r=t.delta||1;if(n.length>r)return await C(e,t);const s=t.homePage||"pages/index/index",o=s.startsWith("/")?s:`/${s}`;return await I({url:o,params:t.homeParams})},exports.useCascaderAreaData=E,exports.useDeepCopyByObj=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return y(e,w(t))}return w(t)},exports.useRegions=function(){return e.useCascaderAreaData()},exports.useToast=v,exports.useTryCatch=function(e,t={}){return async(...n)=>{try{return{data:await e(...n),error:null}}catch(e){return t.onError?.(e),{data:null,error:e}}finally{t.onFinally?.()}}},exports.useWindowInfo=p,exports.weChatOfficialAccountPayment=(e,t,n)=>{const r=c.getInstance();return r.start("weChatOfficialAccountPayment","payment"),new Promise(o=>{s(()=>{if("undefined"==typeof window||!window.navigator)throw new Error("不在浏览器环境中,无法调用微信支付");if(!(e&&e.appId&&e.timeStamp&&e.nonceStr&&e.package&&e.paySign))throw new Error("微信支付配置参数不完整");function s(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){r.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),o(!0)):(n?.(e),o(!1))})}catch(e){r.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),o(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",s,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",s),e.attachEvent("onWeixinJSBridgeReady",s))}else s();return!0},"payment","WECHAT_PAY_ERROR",!1)||(r.end("weChatOfficialAccountPayment"),o(!1))})};
|
|
1
|
+
"use strict";var e=require("@vant/area-data");class t extends Error{code;module;timestamp;constructor(e,t,n){super(t),this.name="UniAppToolsError",this.code=e,this.module=n,this.timestamp=Date.now()}}class n{static instance;errorCallbacks=[];static getInstance(){return n.instance||(n.instance=new n),n.instance}onError(e){this.errorCallbacks.push(e)}handleError(e,n){const r={code:e instanceof t?e.code:"UNKNOWN_ERROR",message:e.message,module:e instanceof t?e.module:n,timestamp:e instanceof t?e.timestamp:Date.now(),stack:e.stack};this.errorCallbacks.forEach(e=>{try{e(r)}catch(e){}})}createModuleErrorHandler(e){return(n,r,s)=>{const o=new t(n,r,e);return s&&(o.stack=s.stack),this.handleError(o,e),o}}}async function r(e,t,r="ASYNC_ERROR"){try{return await e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(r,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function s(e,t,r="SYNC_ERROR",s=null){try{return e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(r,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),s}}var o=Object.freeze({__proto__:null,ErrorHandler:n,UniAppToolsError:t,safeAsync:r,safeSync:s});function a(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}class c{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return c.instance||(c.instance=new c),c.instance}start(e,t,n){const r={name:e,startTime:a(),module:t,metadata:n};this.metrics.set(e,r)}end(e){const t=this.metrics.get(e);return t?(t.endTime=a(),t.duration=t.endTime-t.startTime,this.metrics.delete(e),this.completedMetrics.push(t),this.completedMetrics.length>this.maxStoredMetrics&&this.completedMetrics.shift(),t):null}getReport(){const e={},t={};this.completedMetrics.forEach(n=>{e[n.module]||(e[n.module]=[]),e[n.module].push(n);const r=`${n.module}.${n.name}`;t[r]||(t[r]={total:0,count:0}),t[r].total+=n.duration||0,t[r].count+=1});const n={};Object.entries(t).forEach(([e,t])=>{n[e]=t.total/t.count});const r=[...this.completedMetrics].sort((e,t)=>(t.duration||0)-(e.duration||0)).slice(0,10);return{byModule:e,slowest:r,average:n}}clear(){this.metrics.clear(),this.completedMetrics=[]}}function i(e){return function(t,n,r){const s=r.value;r.value=function(...r){const o=c.getInstance(),a=`${t.constructor.name}.${n}`;o.start(a,e,{args:r.length});try{const e=s.apply(this,r);return e instanceof Promise?e.finally(()=>{o.end(a)}):(o.end(a),e)}catch(e){throw o.end(a),e}}}}var u=Object.freeze({__proto__:null,PerformanceMonitor:c,measurePerformance:i});class l{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return l.instance||(l.instance=new l),l.instance}set(e,t,n=this.defaultTTL){this.cache.set(e,{data:t,timestamp:Date.now(),ttl:n})}get(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttl?(this.cache.delete(e),null):t.data:null}clear(){this.cache.clear()}}const f=l.getInstance(),p=(e=!0)=>{const t=c.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=f.get(n);if(e)return t.end("getWindowInfo"),e}const r=s(()=>{const t=uni.getWindowInfo();return e&&f.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),r},m=()=>{const e="platform",t=f.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",f.set(e,"h5"),"h5"},d=()=>{try{const e=p();return e?.statusBarHeight||0}catch(e){return 0}},h=()=>{try{const e=m();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},g=()=>{try{const e=d(),t=m();if("weixin"===t||"alipay"===t){const t=h();if(t){return t.height+e}}return e+0}catch(e){return d()+0}};function y(e){if(null===e||"object"!=typeof e)return e;try{if("undefined"!=typeof structuredClone)try{return structuredClone(e)}catch(e){}return JSON.parse(JSON.stringify(e))}catch(e){throw new Error(`深拷贝失败: ${e instanceof Error?e.message:String(e)}`)}}function w(e,t,n=!1){let r,s=null;const o=function(...o){const a=n&&!s;return s&&clearTimeout(s),s=setTimeout(()=>{s=null,n||(r=e.apply(this,o))},t),a&&(r=e.apply(this,o)),r};return o.cancel=()=>{s&&(clearTimeout(s),s=null)},o}const x=e.areaList,S=e.useCascaderAreaData;const v=(e="",t=!1,n="none",r=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:r})};function T(e,t){if(!t||0===Object.keys(t).length)return e;const n=Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");return e+(e.includes("?")?"&":"?")+n}async function E(e){return new Promise(t=>{const n=T(e.url,e.params);uni.navigateTo({url:n,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>t(!0),fail:e=>{t(!1)}})})}async function P(e="",t={}){return new Promise(n=>{const r=t.delta||1,s=t.timeout||5e3;if(getCurrentPages().length<=r)return void n(!1);const o=setTimeout(()=>{n(!1)},s);uni.navigateBack({delta:r,success:()=>{clearTimeout(o),setTimeout(()=>{try{const t=getCurrentPages();if(t.length>0){const n=t[t.length-1];n.$vm&&"function"==typeof n.$vm.init&&n.$vm.init(e)}n(!0)}catch(e){n(!0)}},100)},fail:e=>{clearTimeout(o),n(!1)}})})}const C=w(P,300);async function M(e){return new Promise(t=>{const n=T(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}const R={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};class b{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return b.instance||(b.instance=new b),b.instance}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,n={}){try{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const r={value:t,timestamp:Date.now(),ttl:n.ttl},s=JSON.stringify(r);if(s.length>1048576)throw new Error("存储数据过大");if(uni.setStorageSync(e,s),this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}return this.cache.set(e,r),!0}catch(e){throw e}}get(e,t){try{if(!e||"string"!=typeof e)return t;if(this.cache.has(e)){const n=this.cache.get(e);return this.isExpired(n)?(this.cache.delete(e),this.remove(e),t):n.value}const n=uni.getStorageSync(e);if(!n||"string"!=typeof n)return t;const r=JSON.parse(n);let s;return s=r&&"object"==typeof r&&"value"in r&&"timestamp"in r?r:{value:r,timestamp:Date.now()},this.isExpired(s)?(this.remove(e),t):(this.cache.set(e,s),s.value)}catch(e){return t}}remove(e){try{return!(!e||"string"!=typeof e)&&(uni.removeStorageSync(e),this.cache.delete(e),!0)}catch(e){return!1}}clear(){try{return uni.clearStorageSync(),this.cache.clear(),!0}catch(e){return!1}}getInfo(){try{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}}catch(e){return{keys:[],currentSize:0,limitSize:0}}}cleanExpired(){try{const e=this.getInfo();let t=0;return e.keys.forEach(e=>{void 0===this.get(e)&&t++}),t}catch(e){return 0}}}const I=b.getInstance();function O(e,t,n={}){return I.set(e,t,n)}function A(e,t){return I.get(e,t)}function k(e){const t=e.lastIndexOf(".");if(-1!==t&&t!==e.length-1)return e.slice(t+1).toLowerCase()}function _(e){return`${Date.now()}_${e}_${Math.random().toString(16).slice(2)}`}function U(e,t){if(!t)return{valid:!0};return e>1024*t*1024?{valid:!1,message:`文件大小不能超过 ${t}MB`}:{valid:!0}}function j(e,t){if(0===e.length)return{success:!1,files:e,message:"未选择任何文件"};const{maxSelectFileSizeMB:n,extensions:r}=t;if(n){if(e.some(e=>!U(e.size,n).valid))return{success:!1,files:e,message:`部分文件大小超过 ${n}MB 限制`}}if(r&&r.length>0){const t=r.map(e=>e.toLowerCase());if(e.some(e=>!e.ext||!t.includes(e.ext)))return{success:!1,files:e,message:`存在不支持的文件类型,仅支持:${r.join(", ")}`}}return{success:!0,files:e}}async function L(e){return"undefined"!=typeof document&&"undefined"!=typeof window?function(e){const{type:t="image",count:n=1,extensions:r}=e;return new Promise(s=>{if("undefined"==typeof document)return void s({success:!1,files:[],message:"当前环境不支持文件选择"});const o=document.createElement("input");o.type="file",o.multiple=n>1,"image"===t?o.accept="image/*":r&&r.length>0&&(o.accept=r.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),o.onchange=t=>{const n=t.target,r=n?.files;if(!r||0===r.length)return s({success:!1,files:[],message:"用户取消选择"}),void document.body.removeChild(o);const a=j(Array.from(r).map((e,t)=>{const n=k(e.name),r=URL.createObjectURL(e);return{id:_(t),name:e.name,size:e.size,path:r,mimeType:e.type,ext:n,source:"file",platform:"h5",raw:e}}),e);s(a),document.body.removeChild(o)},o.style.display="none",document.body.appendChild(o),o.click()})}(e):function(e){const{type:t="image",count:n=1}=e;return new Promise(r=>{const s="undefined"==typeof uni?null:uni;if(!s)return void r({success:!1,files:[],message:"当前环境不支持文件选择"});const o=e=>{const t=function(e){const t=(e||"").trim();if(!t)return"选择文件失败";const n=t.toLowerCase();return n.includes("fail cancel")||n.includes("cancel")?"用户取消选择":/[\u4e00-\u9fff]/.test(t)?t:"选择文件失败"}(e?.errMsg);r({success:!1,files:[],message:t})},a=function(){let e="unknown";return e="h5",e="weixin",e="alipay",e="app","app"}();"image"!==t||"function"!=typeof s.chooseImage?"function"!=typeof s.chooseMessageFile?"function"!=typeof s.chooseFile?r({success:!1,files:[],message:"当前平台不支持文件选择"}):s.chooseFile({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=k(e.path);return{id:_(t),name:`file_${t}`,size:e.size,path:e.path,ext:n,source:"file",platform:a,raw:e}});r(j(n,e))},fail:o}):s.chooseMessageFile({count:n,type:"all",success:t=>{const n=t.tempFiles.map((e,t)=>{const n=k(e.name||e.path);return{id:_(t),name:e.name,size:e.size,path:e.path,ext:n,source:"file",platform:a,raw:e}});r(j(n,e))},fail:o}):s.chooseImage({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=k(e.path);return{id:_(t),name:`image_${t}`,size:e.size,path:e.path,ext:n,source:"album",platform:a,raw:e}});r(j(n,e))},fail:o})})}(e)}async function D(e,t,n){const{url:r,maxUploadFileSizeMB:s,showToast:o=!0,beforeUpload:a}=t;if("function"==typeof a){if(!await Promise.resolve(a(e)))return{file:e,success:!1,message:"已取消上传"}}if(!r){const t="上传地址不能为空";return o&&v(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const c=U(e.size,s);return c.valid?"h5"===e.platform&&e.raw instanceof File?function(e,t,n){const{url:r,fieldName:s="file",formData:o,headers:a,showToast:c=!0,successMessage:i="上传成功",failMessage:u="上传失败",onProgress:l,uploadTimeoutMs:f,autoRevokeObjectURL:p=!1}=t;return new Promise(t=>{const m=e.raw;if(!(m&&m instanceof File)){const n="H5 环境缺少原生文件对象";return c&&v(n,!1,"none"),void t({file:e,success:!1,message:n})}const d=p&&"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&"string"==typeof e.path&&e.path.startsWith("blob:"),h=()=>{if(d)try{URL.revokeObjectURL(e.path)}catch{}},g=new XMLHttpRequest,y=new FormData;y.append(s,m,e.name),o&&Object.keys(o).forEach(e=>{y.append(e,String(o[e]))}),l&&g.upload.addEventListener("progress",t=>{if(t.lengthComputable){const n=Math.round(t.loaded/t.total*100);l(e,n)}}),g.addEventListener("load",()=>{const r=g.status,s=r>=200&&r<300;let o=g.responseText;try{o=JSON.parse(g.responseText)}catch{}if(s)c&&1===n&&v(i,!1,"none"),h(),t({file:e,success:!0,statusCode:r,data:o});else{const n=`上传失败,状态码:${r}`;c&&v(n,!1,"none"),h(),t({file:e,success:!1,statusCode:r,data:o,message:n})}}),g.addEventListener("error",()=>{const n=u;c&&v(n,!1,"none"),h(),t({file:e,success:!1,message:n})}),g.addEventListener("timeout",()=>{const n=f?`上传超时(${f}ms)`:"上传超时";c&&v(n,!1,"none"),h(),t({file:e,success:!1,message:n})}),g.addEventListener("abort",()=>{h(),t({file:e,success:!1,message:"上传已取消"})}),g.open("POST",r),"number"==typeof f&&f>0&&(g.timeout=f),a&&Object.keys(a).forEach(e=>{g.setRequestHeader(e,a[e])}),g.send(y)})}(e,t,n):function(e,t,n){const{url:r,fieldName:s="file",formData:o,headers:a,showToast:c=!0,successMessage:i="上传成功",failMessage:u="上传失败",onProgress:l,uploadTimeoutMs:f}=t,p="undefined"==typeof uni?null:uni;if(!p||"function"!=typeof p.uploadFile){const t="当前环境不支持文件上传";return c&&v(t,!1,"none"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{let m=!1,d=null;const h=e=>{m||(m=!0,d&&(clearTimeout(d),d=null),t(e))};let g=null;"number"==typeof f&&f>0&&(d=setTimeout(()=>{try{g&&"function"==typeof g.abort&&g.abort()}catch{}const t=`上传超时(${f}ms)`;c&&v(t,!1,"none"),h({file:e,success:!1,message:t})},f)),g=p.uploadFile({url:r,filePath:e.path,name:s,formData:o,header:a,success:t=>{let r=t.data;try{r=JSON.parse(t.data)}catch{}const s=t.statusCode;if(s>=200&&s<300)c&&1===n&&v(i,!1,"none"),h({file:e,success:!0,statusCode:s,data:r});else{const t=`上传失败,状态码:${s}`;c&&v(t,!1,"none"),h({file:e,success:!1,statusCode:s,data:r,message:t})}},fail:t=>{const n=t?.errMsg||u;c&&v(n,!1,"none"),h({file:e,success:!1,message:n})}}),l&&g&&"function"==typeof g.onProgressUpdate&&g.onProgressUpdate(t=>{l(e,t.progress)})})}(e,t,n):(o&&c.message&&v(c.message,!1,"error"),Promise.resolve({file:e,success:!1,message:c.message}))}async function N(e){const{showToast:t=!0,failMessage:n="选择文件失败"}=e;try{const r=await L(e);if(!r.success){const e=r.message||n;return t&&e&&v(e,!1,"none"),[{file:null,success:!1,message:e}]}const s=r.files;if(0===s.length)return[];const o=s.length;return await async function(e,t,n){const r=new Array(e.length),s=t.concurrency&&t.concurrency>0?Math.min(t.concurrency,e.length):e.length;let o=0;const a=async()=>{for(;;){const s=o;if(s>=e.length)break;o+=1;const a=e[s],c=await D(a,t,n);r[s]=c}},c=[];for(let e=0;e<s;e+=1)c.push(a());return await Promise.all(c),r}(s,e,o)}catch(e){const r=n;return t&&r&&v(r,!1,"none"),[{file:null,success:!1,message:r}]}}const $=()=>!("undefined"==typeof navigator||!navigator.userAgent)&&navigator.userAgent.toLowerCase().includes("micromessenger"),B=()=>"undefined"!=typeof window&&"undefined"!=typeof document,F=()=>B()&&$()&&window.wx||null;let z=!1,W=null;const H=(e={})=>{const{timeoutMs:t=1e4}=e;if(z||B()&&window.wx)return z=!0,Promise.resolve(!0);if(!B())return Promise.resolve(!1);if(W)return W;const n=e.cdnUrls&&e.cdnUrls.length>0?e.cdnUrls:["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];return W=new Promise(e=>{let r=!1,s=null,o=null,a=0;const c=t=>{r||(r=!0,s&&(clearTimeout(s),s=null),o&&o.parentNode&&o.parentNode.removeChild(o),t&&(z=!0),W=null,e(t))},i=()=>{if(a>=n.length)return void c(!1);if(!document.head)return void c(!1);const e=n[a];a+=1;const t=document.createElement("script");o=t,t.src=e,t.async=!0,t.onload=()=>c(!0),t.onerror=()=>{t.parentNode&&t.parentNode.removeChild(t),o=null,i()},document.head.appendChild(t)};s=setTimeout(()=>{c(!1)},t),i()}),W};let J=null;const q=async(e,t={})=>{const{timeoutMs:n=1e4}=t;if(!$())return!1;if(J)return J;if(!await H({timeoutMs:n}))return!1;if(!B())return!1;const r=window.wx;return!!r&&(J=new Promise(t=>{let s=!1,o=null;const a=e=>{s||(s=!0,o&&(clearTimeout(o),o=null),J=null,t(e))};o=setTimeout(()=>a(!1),n);try{r.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),r.ready(()=>{a(!0)}),r.error(e=>{a(!1)})}catch(e){a(!1)}}),J)},G=e=>{const t=F();t&&(t.updateTimelineShareData?t.updateTimelineShareData(e):t.onMenuShareTimeline&&t.onMenuShareTimeline(e))},Y=e=>{const t=F();t&&(t.updateAppMessageShareData?t.updateAppMessageShareData(e):t.onMenuShareAppMessage&&t.onMenuShareAppMessage(e))};class K{static instance;isConfigured=!1;config=null;initPromise=null;constructor(){}static getInstance(){return K.instance||(K.instance=new K),K.instance}async init(e){return this.initPromise||(this.config=e,this.initPromise=q(e).then(e=>(this.isConfigured=e,e)).finally(()=>{this.initPromise=null})),this.initPromise}isReady(){return this.isConfigured&&$()}getConfig(){return this.config}setShareData(e){this.isReady()&&(G(e),Y(e))}}exports.ErrorHandler=n,exports.PerformanceMonitor=c,exports.UniAppToolsError=t,exports.VERSION="2.0.0",exports.WechatSDK=K,exports.areaList=x,exports.batchGetStorage=function(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=A(e)}),t.end("batchGetStorage"),n},exports.batchSetStorage=function(e,t={}){const n=c.getInstance();n.start("batchSetStorage","localStorage");let r=0;return Object.entries(e).forEach(([e,n])=>{O(e,n,t)&&r++}),n.end("batchSetStorage"),r},exports.checkWechatJSAPI=(e,t={})=>{const{timeoutMs:n=8e3}=t;return new Promise(t=>{const r=F();if(!r||"function"!=typeof r.checkJsApi)return void t({});let s=!1;const o=e=>{s||(s=!0,t(e))},a=setTimeout(()=>o({}),n);try{r.checkJsApi({jsApiList:e,success:e=>{clearTimeout(a),o(e?.checkResult||{})}})}catch(e){clearTimeout(a),o({})}})},exports.cleanExpiredStorage=function(){return I.cleanExpired()},exports.clearStorageSync=function(e){return e?I.remove(e):I.clear()},exports.configWechatJSSDK=q,exports.copyText=async function(e,t={}){const n=c.getInstance();n.start("copyText","clipboard",{textLength:e.length});const s={...R,...t};if(!e||"string"!=typeof e)return s.showToast&&v("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return s.showToast&&v("复制内容过长",!1,"error"),n.end("copyText"),!1;const o=await r(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{s.showToast&&v(s.successMessage),t(!0)},fail:()=>{s.showToast&&v(s.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),o},exports.debounce=w,exports.deepClone=y,exports.deepMerge=function(e,t){const n=y(e);return function e(t,n){for(const r in n)if(n.hasOwnProperty(r)){const s=n[r],o=t[r];s&&"object"==typeof s&&!Array.isArray(s)&&o&&"object"==typeof o&&!Array.isArray(o)?e(o,s):t[r]=y(s)}}(n,t),n},exports.extractUrlParts=function(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,r={};return t.searchParams.forEach((e,t)=>{r[t]=e}),{path:n,params:r}}catch(e){return{path:"",params:{}}}},exports.getCurrentEnv=()=>{try{const e=uni.getAccountInfoSync();return{appId:e.miniProgram?.appId||"",version:e.miniProgram?.version||"",envVersion:e.miniProgram?.envVersion||"",accountInfo:e}}catch(e){return{appId:"",version:"",envVersion:"",accountInfo:null}}},exports.getCurrentPageInfo=function(){try{const e=getCurrentPages();if(0===e.length)return null;const t=e[e.length-1];return{route:t.route||"",options:t.options||{}}}catch(e){return null}},exports.getH5UrlParams=e=>{try{if("undefined"==typeof window||!window.location)throw new Error("不在 H5 浏览器环境中");const t=new URLSearchParams(window.location.search),n={};return t.forEach((e,t)=>{try{n[t]=decodeURIComponent(e)}catch(r){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return e?null:{}}},exports.getMenuButtonBoundingClientRect=h,exports.getNavHeight=g,exports.getPageStack=function(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return[]}},exports.getPlatform=m,exports.getStatusBarHeight=d,exports.getStorage=async function(e,t){return await r(()=>new Promise(n=>{n(A(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t},exports.getStorageInfo=function(){return I.getInfo()},exports.getStorageSync=A,exports.getTopNavBarHeight=()=>{try{const e=d();return{statusBarHeight:e,navHeight:g()}}catch(e){return{statusBarHeight:0,navHeight:44}}},exports.initUniAppTools=async function(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,onError:r=null,performanceReportInterval:s=0}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return o}),t=e.getInstance();"function"==typeof r?t.onError(r):t.onError(e=>{})}if(t&&s>0){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return u}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},s)}},exports.isWechat=$,exports.loadWechatJSSDK=H,exports.measurePerformance=i,exports.mergeObjects=function(e,t){if(!t||0===Object.keys(t).length)return e;const n={...e};for(const r of Object.keys(e))Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n},exports.navigateTo=E,exports.onCheckForUpdate=()=>{try{const e=uni.getUpdateManager();e.onCheckForUpdate(function(e){e.hasUpdate}),e.onUpdateReady(function(t){uni.showModal({title:"更新提示",content:"新版本已经准备好,是否重启应用?",showCancel:!0,cancelText:"稍后",confirmText:"立即重启",success(t){t.confirm&&e.applyUpdate()}})}),e.onUpdateFailed(function(e){uni.showModal({title:"更新失败",content:"新版本下载失败,请检查网络连接或稍后重试",showCancel:!1,confirmText:"知道了"})})}catch(e){}},exports.reLaunch=M,exports.redirectTo=async function(e){return new Promise(t=>{const n=T(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})},exports.safeAsync=r,exports.safeNavigateTo=async function(e,t=3){for(let n=0;n<t;n++){if(await E(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1},exports.safeSync=s,exports.selectAndUpload=N,exports.selectAndUploadImage=async function(e){return N({...e,type:"image"})},exports.setPageIcon=(e,t="image/x-icon")=>s(()=>{const n=m();if(("h5"===n||"web"===n)&&"undefined"!=typeof document){document.querySelectorAll('link[rel*="icon"]').forEach(e=>e.remove());const n=document.createElement("link");return n.rel="icon",n.type=t,n.href=e,document.head.appendChild(n),!0}return!1},"system","SET_PAGE_ICON_ERROR",!1),exports.setPageTitle=e=>e&&"string"==typeof e?new Promise(t=>{try{uni.setNavigationBarTitle({title:e,success:()=>{t(!0)},fail:e=>{t(!1)}})}catch(e){t(!1)}}):Promise.resolve(!1),exports.setStorage=async function(e,t,n={}){return await r(()=>new Promise(r=>{r(O(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1},exports.setStorageSync=O,exports.shareToFriend=Y,exports.shareToTimeline=G,exports.switchTab=async function(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:e=>{t(!1)}})})},exports.throttle=function(e,t,n={}){let r,s=null,o=0;const{leading:a=!0,trailing:c=!0}=n,i=function(...n){const i=Date.now();o||a||(o=i);const u=t-(i-o);return u<=0||u>t?(s&&(clearTimeout(s),s=null),o=i,r=e.apply(this,n)):!s&&c&&(s=setTimeout(()=>{o=a?Date.now():0,s=null,r=e.apply(this,n)},u)),r};return i.cancel=()=>{s&&(clearTimeout(s),s=null),o=0},i},exports.useBack=P,exports.useBackDebounced=C,exports.useBackOrHome=async function(e="",t={}){const n=getCurrentPages(),r=t.delta||1;if(n.length>r)return await P(e,t);const s=t.homePage||"pages/index/index",o=s.startsWith("/")?s:`/${s}`;return await M({url:o,params:t.homeParams})},exports.useCascaderAreaData=S,exports.useRegions=function(){return e.useCascaderAreaData()},exports.useToast=v,exports.useTryCatch=function(e,t={}){return async(...n)=>{try{return{data:await e(...n),error:null}}catch(e){return t.onError?.(e),{data:null,error:e}}finally{t.onFinally?.()}}},exports.useWindowInfo=p,exports.weChatOfficialAccountPayment=(e,t,n)=>{const r=c.getInstance();return r.start("weChatOfficialAccountPayment","payment"),new Promise(o=>{s(()=>{if("undefined"==typeof window||!window.navigator)throw new Error("不在浏览器环境中,无法调用微信支付");if(!(e&&e.appId&&e.timeStamp&&e.nonceStr&&e.package&&e.paySign))throw new Error("微信支付配置参数不完整");function s(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){r.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),o(!0)):(n?.(e),o(!1))})}catch(e){r.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),o(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",s,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",s),e.attachEvent("onWeixinJSBridgeReady",s))}else s();return!0},"payment","WECHAT_PAY_ERROR",!1)||(r.end("weChatOfficialAccountPayment"),o(!1))})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{areaList as e,useCascaderAreaData as t}from"@vant/area-data";class n extends Error{code;module;timestamp;constructor(e,t,n){super(t),this.name="UniAppToolsError",this.code=e,this.module=n,this.timestamp=Date.now()}}class r{static instance;errorCallbacks=[];static getInstance(){return r.instance||(r.instance=new r),r.instance}onError(e){this.errorCallbacks.push(e)}handleError(e,t){const r={code:e instanceof n?e.code:"UNKNOWN_ERROR",message:e.message,module:e instanceof n?e.module:t,timestamp:e instanceof n?e.timestamp:Date.now(),stack:e.stack};this.errorCallbacks.forEach(e=>{try{e(r)}catch(e){}})}createModuleErrorHandler(e){return(t,r,s)=>{const a=new n(t,r,e);return s&&(a.stack=s.stack),this.handleError(a,e),a}}}async function s(e,t,n="ASYNC_ERROR"){try{return await e()}catch(e){return r.getInstance().createModuleErrorHandler(t)(n,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function a(e,t,n="SYNC_ERROR",s=null){try{return e()}catch(e){return r.getInstance().createModuleErrorHandler(t)(n,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),s}}var o=Object.freeze({__proto__:null,ErrorHandler:r,UniAppToolsError:n,safeAsync:s,safeSync:a});function i(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}class c{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return c.instance||(c.instance=new c),c.instance}start(e,t,n){const r={name:e,startTime:i(),module:t,metadata:n};this.metrics.set(e,r)}end(e){const t=this.metrics.get(e);return t?(t.endTime=i(),t.duration=t.endTime-t.startTime,this.metrics.delete(e),this.completedMetrics.push(t),this.completedMetrics.length>this.maxStoredMetrics&&this.completedMetrics.shift(),t):null}getReport(){const e={},t={};this.completedMetrics.forEach(n=>{e[n.module]||(e[n.module]=[]),e[n.module].push(n);const r=`${n.module}.${n.name}`;t[r]||(t[r]={total:0,count:0}),t[r].total+=n.duration||0,t[r].count+=1});const n={};Object.entries(t).forEach(([e,t])=>{n[e]=t.total/t.count});const r=[...this.completedMetrics].sort((e,t)=>(t.duration||0)-(e.duration||0)).slice(0,10);return{byModule:e,slowest:r,average:n}}clear(){this.metrics.clear(),this.completedMetrics=[]}}function u(e){return function(t,n,r){const s=r.value;r.value=function(...r){const a=c.getInstance(),o=`${t.constructor.name}.${n}`;a.start(o,e,{args:r.length});try{const e=s.apply(this,r);return e instanceof Promise?e.finally(()=>{a.end(o)}):(a.end(o),e)}catch(e){throw a.end(o),e}}}}var l=Object.freeze({__proto__:null,PerformanceMonitor:c,measurePerformance:u});class f{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return f.instance||(f.instance=new f),f.instance}set(e,t,n=this.defaultTTL){this.cache.set(e,{data:t,timestamp:Date.now(),ttl:n})}get(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttl?(this.cache.delete(e),null):t.data:null}clear(){this.cache.clear()}}const d=f.getInstance(),m=(e=!0)=>{const t=c.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=d.get(n);if(e)return t.end("getWindowInfo"),e}const r=a(()=>{const t=uni.getWindowInfo();return e&&d.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),r},h=()=>{const e="platform",t=d.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",d.set(e,"h5"),"h5"},p=()=>{try{const e=uni.getAccountInfoSync();return{appId:e.miniProgram?.appId||"",version:e.miniProgram?.version||"",envVersion:e.miniProgram?.envVersion||"",accountInfo:e}}catch(e){return{appId:"",version:"",envVersion:"",accountInfo:null}}},g=()=>{try{const e=uni.getUpdateManager();e.onCheckForUpdate(function(e){e.hasUpdate}),e.onUpdateReady(function(t){uni.showModal({title:"更新提示",content:"新版本已经准备好,是否重启应用?",showCancel:!0,cancelText:"稍后",confirmText:"立即重启",success(t){t.confirm&&e.applyUpdate()}})}),e.onUpdateFailed(function(e){uni.showModal({title:"更新失败",content:"新版本下载失败,请检查网络连接或稍后重试",showCancel:!1,confirmText:"知道了"})})}catch(e){}},w=()=>{try{const e=m();return e?.statusBarHeight||0}catch(e){return 0}},y=()=>{try{const e=h();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},S=()=>{try{const e=w(),t=h();if("weixin"===t||"alipay"===t){const t=y();if(t){return t.height+e}}return e+0}catch(e){return w()+0}},E=()=>{try{const e=w();return{statusBarHeight:e,navHeight:S()}}catch(e){return{statusBarHeight:0,navHeight:44}}},v=e=>e&&"string"==typeof e?new Promise(t=>{try{uni.setNavigationBarTitle({title:e,success:()=>{t(!0)},fail:e=>{t(!1)}})}catch(e){t(!1)}}):Promise.resolve(!1),x=(e,t="image/x-icon")=>a(()=>{const n=h();if(("h5"===n||"web"===n)&&"undefined"!=typeof document){document.querySelectorAll('link[rel*="icon"]').forEach(e=>e.remove());const n=document.createElement("link");return n.rel="icon",n.type=t,n.href=e,document.head.appendChild(n),!0}return!1},"system","SET_PAGE_ICON_ERROR",!1);function T(e){if(null===e||"object"!=typeof e)return e;try{if("undefined"!=typeof structuredClone)try{return structuredClone(e)}catch(e){}return JSON.parse(JSON.stringify(e))}catch(e){throw new Error(`深拷贝失败: ${e instanceof Error?e.message:String(e)}`)}}function R(e,t){return Object.assign(e,t)}function P(e,t){const n=T(e);return function e(t,n){for(const r in n)if(n.hasOwnProperty(r)){const s=n[r],a=t[r];s&&"object"==typeof s&&!Array.isArray(s)&&a&&"object"==typeof a&&!Array.isArray(a)?e(a,s):t[r]=T(s)}}(n,t),n}function C(e,t,n=!1){let r,s=null;const a=function(...a){const o=n&&!s;return s&&clearTimeout(s),s=setTimeout(()=>{s=null,n||(r=e.apply(this,a))},t),o&&(r=e.apply(this,a)),r};return a.cancel=()=>{s&&(clearTimeout(s),s=null)},a}function M(e,t,n={}){let r,s=null,a=0;const{leading:o=!0,trailing:i=!0}=n,c=function(...n){const c=Date.now();a||o||(a=c);const u=t-(c-a);return u<=0||u>t?(s&&(clearTimeout(s),s=null),a=c,r=e.apply(this,n)):!s&&i&&(s=setTimeout(()=>{a=o?Date.now():0,s=null,r=e.apply(this,n)},u)),r};return c.cancel=()=>{s&&(clearTimeout(s),s=null),a=0},c}function I(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return R(e,T(t))}return T(t)}const _=e=>{try{if("undefined"==typeof window||!window.location)throw new Error("不在 H5 浏览器环境中");const t=new URLSearchParams(window.location.search),n={};return t.forEach((e,t)=>{try{n[t]=decodeURIComponent(e)}catch(r){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return e?null:{}}};function b(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,r={};return t.searchParams.forEach((e,t)=>{r[t]=e}),{path:n,params:r}}catch(e){return{path:"",params:{}}}}function A(e,t={}){return async(...n)=>{try{return{data:await e(...n),error:null}}catch(e){return t.onError?.(e),{data:null,error:e}}finally{t.onFinally?.()}}}const O=e,k=t;function D(){return t()}const j=(e="",t=!1,n="none",r=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:r})};function $(e,t){if(!t||0===Object.keys(t).length)return e;const n=Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");return e+(e.includes("?")?"&":"?")+n}async function z(e){return new Promise(t=>{const n=$(e.url,e.params);uni.navigateTo({url:n,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>t(!0),fail:e=>{t(!1)}})})}async function F(e){return new Promise(t=>{const n=$(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}async function L(e="",t={}){return new Promise(n=>{const r=t.delta||1,s=t.timeout||5e3;if(getCurrentPages().length<=r)return void n(!1);const a=setTimeout(()=>{n(!1)},s);uni.navigateBack({delta:r,success:()=>{clearTimeout(a),setTimeout(()=>{try{const t=getCurrentPages();if(t.length>0){const n=t[t.length-1];n.$vm&&"function"==typeof n.$vm.init&&n.$vm.init(e)}n(!0)}catch(e){n(!0)}},100)},fail:e=>{clearTimeout(a),n(!1)}})})}async function N(e="",t={}){const n=getCurrentPages(),r=t.delta||1;if(n.length>r)return await L(e,t);const s=t.homePage||"pages/index/index",a=s.startsWith("/")?s:`/${s}`;return await H({url:a,params:t.homeParams})}const W=C(L,300);async function U(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:e=>{t(!1)}})})}async function H(e){return new Promise(t=>{const n=$(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}function B(){try{const e=getCurrentPages();if(0===e.length)return null;const t=e[e.length-1];return{route:t.route||"",options:t.options||{}}}catch(e){return null}}function J(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return[]}}async function q(e,t=3){for(let n=0;n<t;n++){if(await z(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1}const G={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};async function Y(e,t={}){const n=c.getInstance();n.start("copyText","clipboard",{textLength:e.length});const r={...G,...t};if(!e||"string"!=typeof e)return r.showToast&&j("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return r.showToast&&j("复制内容过长",!1,"error"),n.end("copyText"),!1;const a=await s(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{r.showToast&&j(r.successMessage),t(!0)},fail:()=>{r.showToast&&j(r.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),a}class K{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return K.instance||(K.instance=new K),K.instance}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,n={}){try{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const r={value:t,timestamp:Date.now(),ttl:n.ttl},s=JSON.stringify(r);if(s.length>1048576)throw new Error("存储数据过大");if(uni.setStorageSync(e,s),this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}return this.cache.set(e,r),!0}catch(e){throw e}}get(e,t){try{if(!e||"string"!=typeof e)return t;if(this.cache.has(e)){const n=this.cache.get(e);return this.isExpired(n)?(this.cache.delete(e),this.remove(e),t):n.value}const n=uni.getStorageSync(e);if(!n||"string"!=typeof n)return t;const r=JSON.parse(n);let s;return s=r&&"object"==typeof r&&"value"in r&&"timestamp"in r?r:{value:r,timestamp:Date.now()},this.isExpired(s)?(this.remove(e),t):(this.cache.set(e,s),s.value)}catch(e){return t}}remove(e){try{return!(!e||"string"!=typeof e)&&(uni.removeStorageSync(e),this.cache.delete(e),!0)}catch(e){return!1}}clear(){try{return uni.clearStorageSync(),this.cache.clear(),!0}catch(e){return!1}}getInfo(){try{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}}catch(e){return{keys:[],currentSize:0,limitSize:0}}}cleanExpired(){try{const e=this.getInfo();let t=0;return e.keys.forEach(e=>{void 0===this.get(e)&&t++}),t}catch(e){return 0}}}const V=K.getInstance();function X(e,t,n={}){return V.set(e,t,n)}function Q(e,t){return V.get(e,t)}function Z(e){return e?V.remove(e):V.clear()}async function ee(e,t,n={}){return await s(()=>new Promise(r=>{r(X(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1}async function te(e,t){return await s(()=>new Promise(n=>{n(Q(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t}function ne(){return V.getInfo()}function re(){return V.cleanExpired()}function se(e,t={}){const n=c.getInstance();n.start("batchSetStorage","localStorage");let r=0;return Object.entries(e).forEach(([e,n])=>{X(e,n,t)&&r++}),n.end("batchSetStorage"),r}function ae(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=Q(e)}),t.end("batchGetStorage"),n}function oe(e,t){if(!t)return{valid:!0};return e>1024*t*1024?{valid:!1,message:`文件大小不能超过 ${t}MB`}:{valid:!0}}function ie(e){const t=e.lastIndexOf(".");if(-1!==t&&t!==e.length-1)return e.slice(t+1).toLowerCase()}function ce(e){return`${Date.now()}_${e}_${Math.random().toString(16).slice(2)}`}function ue(e,t){if(0===e.length)return{success:!1,files:e,message:"未选择任何文件"};const{maxSelectFileSizeMB:n,extensions:r}=t;if(n){if(e.some(e=>!oe(e.size,n).valid))return{success:!1,files:e,message:`部分文件大小超过 ${n}MB 限制`}}if(r&&r.length>0){const t=r.map(e=>e.toLowerCase());if(e.some(e=>!e.ext||!t.includes(e.ext)))return{success:!1,files:e,message:`存在不支持的文件类型,仅支持:${r.join(", ")}`}}return{success:!0,files:e}}async function le(e){return"undefined"!=typeof document&&"undefined"!=typeof window?function(e){const{type:t="image",count:n=1,extensions:r}=e;return new Promise(s=>{if("undefined"==typeof document)return void s({success:!1,files:[],message:"当前环境不支持文件选择"});const a=document.createElement("input");a.type="file",a.multiple=n>1,"image"===t?a.accept="image/*":r&&r.length>0&&(a.accept=r.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),a.onchange=t=>{const n=t.target,r=n?.files;if(!r||0===r.length)return s({success:!1,files:[],message:"用户取消选择"}),void document.body.removeChild(a);const o=ue(Array.from(r).map((e,t)=>{const n=ie(e.name),r=URL.createObjectURL(e);return{id:ce(t),name:e.name,size:e.size,path:r,mimeType:e.type,ext:n,source:"file",platform:"h5",raw:e}}),e);s(o),document.body.removeChild(a)},a.style.display="none",document.body.appendChild(a),a.click()})}(e):function(e){const{type:t="image",count:n=1}=e;return new Promise(r=>{const s="undefined"==typeof uni?null:uni;if(!s)return void r({success:!1,files:[],message:"当前环境不支持文件选择"});const a=e=>{r({success:!1,files:[],message:e?.errMsg||"选择文件失败"})};"image"!==t||"function"!=typeof s.chooseImage?"function"!=typeof s.chooseMessageFile?"function"!=typeof s.chooseFile?r({success:!1,files:[],message:"当前平台不支持文件选择"}):s.chooseFile({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=ie(e.path);return{id:ce(t),name:`file_${t}`,size:e.size,path:e.path,ext:n,source:"file",platform:"app",raw:e}});r(ue(n,e))},fail:a}):s.chooseMessageFile({count:n,type:"all",success:t=>{const n=t.tempFiles.map((e,t)=>{const n=ie(e.name||e.path);return{id:ce(t),name:e.name,size:e.size,path:e.path,ext:n,source:"file",platform:"weixin",raw:e}});r(ue(n,e))},fail:a}):s.chooseImage({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=ie(e.path);return{id:ce(t),name:`image_${t}`,size:e.size,path:e.path,ext:n,source:"album",platform:"weixin",raw:e}});r(ue(n,e))},fail:a})})}(e)}async function fe(e,t,n){const{url:r,maxUploadFileSizeMB:s,showToast:a=!0,beforeUpload:o}=t;if("function"==typeof o){if(!await Promise.resolve(o(e)))return{file:e,success:!1,message:"已取消上传"}}if(!r){const t="上传地址不能为空";return a&&j(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const i=oe(e.size,s);return i.valid?"h5"===e.platform&&e.raw instanceof File?function(e,t,n){const{url:r,fieldName:s="file",formData:a,headers:o,showToast:i=!0,successMessage:c="上传成功",failMessage:u="上传失败",onProgress:l}=t;return new Promise(t=>{const f=e.raw;if(!(f&&f instanceof File)){const n="H5 环境缺少原生文件对象";return i&&j(n,!1,"error"),void t({file:e,success:!1,message:n})}const d=new XMLHttpRequest,m=new FormData;m.append(s,f,e.name),a&&Object.keys(a).forEach(e=>{m.append(e,String(a[e]))}),l&&d.upload.addEventListener("progress",t=>{if(t.lengthComputable){const n=Math.round(t.loaded/t.total*100);l(e,n)}}),d.addEventListener("load",()=>{const r=d.status,s=r>=200&&r<300;let a=d.responseText;try{a=JSON.parse(d.responseText)}catch{}if(s)i&&1===n&&j(c,!1,"success"),t({file:e,success:!0,statusCode:r,data:a});else{const n=`上传失败,状态码:${r}`;i&&j(n,!1,"error"),t({file:e,success:!1,statusCode:r,data:a,message:n})}}),d.addEventListener("error",()=>{const n=u;i&&j(n,!1,"error"),t({file:e,success:!1,message:n})}),d.addEventListener("abort",()=>{t({file:e,success:!1,message:"上传已取消"})}),d.open("POST",r),o&&Object.keys(o).forEach(e=>{d.setRequestHeader(e,o[e])}),d.send(m)})}(e,t,n):function(e,t,n){const{url:r,fieldName:s="file",formData:a,headers:o,showToast:i=!0,successMessage:c="上传成功",failMessage:u="上传失败",onProgress:l}=t,f="undefined"==typeof uni?null:uni;if(!f||"function"!=typeof f.uploadFile){const t="当前环境不支持文件上传";return i&&j(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{const d=f.uploadFile({url:r,filePath:e.path,name:s,formData:a,header:o,success:r=>{let s=r.data;try{s=JSON.parse(r.data)}catch{}const a=r.statusCode;if(a>=200&&a<300)i&&1===n&&j(c,!1,"success"),t({file:e,success:!0,statusCode:a,data:s});else{const n=`上传失败,状态码:${a}`;i&&j(n,!1,"error"),t({file:e,success:!1,statusCode:a,data:s,message:n})}},fail:n=>{const r=n?.errMsg||u;i&&j(r,!1,"error"),t({file:e,success:!1,message:r})}});l&&d&&"function"==typeof d.onProgressUpdate&&d.onProgressUpdate(t=>{l(e,t.progress)})})}(e,t,n):(a&&i.message&&j(i.message,!1,"error"),Promise.resolve({file:e,success:!1,message:i.message}))}async function de(e){const{showToast:t=!0,failMessage:n="选择文件失败"}=e;try{const r=await le(e);if(!r.success){const e=r.message||n;return t&&e&&j(e,!1,"error"),[{file:null,success:!1,message:e}]}const s=r.files;if(0===s.length)return[];const a=s.length;return await async function(e,t,n){const r=new Array(e.length),s=t.concurrency&&t.concurrency>0?Math.min(t.concurrency,e.length):e.length;let a=0;const o=async()=>{for(;;){const s=a;if(s>=e.length)break;a+=1;const o=e[s],i=await fe(o,t,n);r[s]=i}},i=[];for(let e=0;e<s;e+=1)i.push(o());return await Promise.all(i),r}(s,e,a)}catch(e){const r=n;return t&&r&&j(r,!1,"error"),[{file:null,success:!1,message:r}]}}async function me(e){return de({...e,type:"image"})}const he=(e,t,n)=>{const r=c.getInstance();return r.start("weChatOfficialAccountPayment","payment"),new Promise(s=>{a(()=>{if("undefined"==typeof window||!window.navigator)throw new Error("不在浏览器环境中,无法调用微信支付");if(!(e&&e.appId&&e.timeStamp&&e.nonceStr&&e.package&&e.paySign))throw new Error("微信支付配置参数不完整");function a(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){r.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),s(!0)):(n?.(e),s(!1))})}catch(e){r.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),s(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",a,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",a),e.attachEvent("onWeixinJSBridgeReady",a))}else a();return!0},"payment","WECHAT_PAY_ERROR",!1)||(r.end("weChatOfficialAccountPayment"),s(!1))})},pe=()=>{const e=c.getInstance();e.start("isWechat","system");const t=a(()=>{if("undefined"!=typeof navigator&&navigator.userAgent){return navigator.userAgent.toLowerCase().includes("micromessenger")}return!1},"system","IS_WECHAT_ERROR",!1);return e.end("isWechat"),t||!1},ge=()=>new Promise(e=>{if("undefined"!=typeof window&&window.wx)return void e(!0);const t=["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];let n=0;const r=s=>{const a=document.createElement("script");a.src=s,a.async=!0,a.onload=()=>{e(!0)},a.onerror=()=>{n++,n<t.length?(document.head.removeChild(a),r(t[n])):(document.head.removeChild(a),e(!1))},document.head.appendChild(a)};r(t[n]),e(!1)}),we=async e=>{const t=c.getInstance();t.start("configWechatJSSDK","wechat");try{if(!pe())return!1;return!!await ge()&&new Promise(t=>{window.wx?(window.wx.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),window.wx.ready(()=>{t(!0)}),window.wx.error(e=>{t(!1)})):t(!1),t(!1)})}catch(e){return!1}finally{t.end("configWechatJSSDK")}},ye=e=>new Promise(t=>{window.wx&&pe()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),Se=e=>{a(()=>{window.wx&&pe()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},Ee=e=>{a(()=>{window.wx&&pe()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class ve{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return ve.instance||(ve.instance=new ve),ve.instance}async init(e){return this.config=e,this.isConfigured=await we(e),this.isConfigured}isReady(){return this.isConfigured&&pe()}getConfig(){return this.config}setShareData(e){this.isReady()&&(Se(e),Ee(e))}}const xe="2.0.0";async function Te(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,onError:r=null,performanceReportInterval:s=0}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return o}),t=e.getInstance();"function"==typeof r?t.onError(r):t.onError(e=>{})}if(t&&s>0){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return l}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},s)}}export{r as ErrorHandler,c as PerformanceMonitor,n as UniAppToolsError,xe as VERSION,ve as WechatSDK,O as areaList,ae as batchGetStorage,se as batchSetStorage,ye as checkWechatJSAPI,re as cleanExpiredStorage,Z as clearStorageSync,we as configWechatJSSDK,Y as copyText,C as debounce,T as deepClone,P as deepMerge,b as extractUrlParts,p as getCurrentEnv,B as getCurrentPageInfo,_ as getH5UrlParams,y as getMenuButtonBoundingClientRect,S as getNavHeight,J as getPageStack,h as getPlatform,w as getStatusBarHeight,te as getStorage,ne as getStorageInfo,Q as getStorageSync,E as getTopNavBarHeight,Te as initUniAppTools,pe as isWechat,ge as loadWechatJSSDK,u as measurePerformance,R as mergeObjects,z as navigateTo,g as onCheckForUpdate,H as reLaunch,F as redirectTo,s as safeAsync,q as safeNavigateTo,a as safeSync,de as selectAndUpload,me as selectAndUploadImage,x as setPageIcon,v as setPageTitle,ee as setStorage,X as setStorageSync,Ee as shareToFriend,Se as shareToTimeline,U as switchTab,M as throttle,L as useBack,W as useBackDebounced,N as useBackOrHome,k as useCascaderAreaData,I as useDeepCopyByObj,D as useRegions,j as useToast,A as useTryCatch,m as useWindowInfo,he as weChatOfficialAccountPayment};
|
|
1
|
+
import{areaList as e,useCascaderAreaData as t}from"@vant/area-data";class n extends Error{code;module;timestamp;constructor(e,t,n){super(t),this.name="UniAppToolsError",this.code=e,this.module=n,this.timestamp=Date.now()}}class s{static instance;errorCallbacks=[];static getInstance(){return s.instance||(s.instance=new s),s.instance}onError(e){this.errorCallbacks.push(e)}handleError(e,t){const s={code:e instanceof n?e.code:"UNKNOWN_ERROR",message:e.message,module:e instanceof n?e.module:t,timestamp:e instanceof n?e.timestamp:Date.now(),stack:e.stack};this.errorCallbacks.forEach(e=>{try{e(s)}catch(e){}})}createModuleErrorHandler(e){return(t,s,r)=>{const o=new n(t,s,e);return r&&(o.stack=r.stack),this.handleError(o,e),o}}}async function r(e,t,n="ASYNC_ERROR"){try{return await e()}catch(e){return s.getInstance().createModuleErrorHandler(t)(n,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function o(e,t,n="SYNC_ERROR",r=null){try{return e()}catch(e){return s.getInstance().createModuleErrorHandler(t)(n,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),r}}var a=Object.freeze({__proto__:null,ErrorHandler:s,UniAppToolsError:n,safeAsync:r,safeSync:o});function i(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}class c{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return c.instance||(c.instance=new c),c.instance}start(e,t,n){const s={name:e,startTime:i(),module:t,metadata:n};this.metrics.set(e,s)}end(e){const t=this.metrics.get(e);return t?(t.endTime=i(),t.duration=t.endTime-t.startTime,this.metrics.delete(e),this.completedMetrics.push(t),this.completedMetrics.length>this.maxStoredMetrics&&this.completedMetrics.shift(),t):null}getReport(){const e={},t={};this.completedMetrics.forEach(n=>{e[n.module]||(e[n.module]=[]),e[n.module].push(n);const s=`${n.module}.${n.name}`;t[s]||(t[s]={total:0,count:0}),t[s].total+=n.duration||0,t[s].count+=1});const n={};Object.entries(t).forEach(([e,t])=>{n[e]=t.total/t.count});const s=[...this.completedMetrics].sort((e,t)=>(t.duration||0)-(e.duration||0)).slice(0,10);return{byModule:e,slowest:s,average:n}}clear(){this.metrics.clear(),this.completedMetrics=[]}}function u(e){return function(t,n,s){const r=s.value;s.value=function(...s){const o=c.getInstance(),a=`${t.constructor.name}.${n}`;o.start(a,e,{args:s.length});try{const e=r.apply(this,s);return e instanceof Promise?e.finally(()=>{o.end(a)}):(o.end(a),e)}catch(e){throw o.end(a),e}}}}var l=Object.freeze({__proto__:null,PerformanceMonitor:c,measurePerformance:u});class f{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return f.instance||(f.instance=new f),f.instance}set(e,t,n=this.defaultTTL){this.cache.set(e,{data:t,timestamp:Date.now(),ttl:n})}get(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttl?(this.cache.delete(e),null):t.data:null}clear(){this.cache.clear()}}const m=f.getInstance(),d=(e=!0)=>{const t=c.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=m.get(n);if(e)return t.end("getWindowInfo"),e}const s=o(()=>{const t=uni.getWindowInfo();return e&&m.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),s},h=()=>{const e="platform",t=m.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",m.set(e,"h5"),"h5"},p=()=>{try{const e=uni.getAccountInfoSync();return{appId:e.miniProgram?.appId||"",version:e.miniProgram?.version||"",envVersion:e.miniProgram?.envVersion||"",accountInfo:e}}catch(e){return{appId:"",version:"",envVersion:"",accountInfo:null}}},g=()=>{try{const e=uni.getUpdateManager();e.onCheckForUpdate(function(e){e.hasUpdate}),e.onUpdateReady(function(t){uni.showModal({title:"更新提示",content:"新版本已经准备好,是否重启应用?",showCancel:!0,cancelText:"稍后",confirmText:"立即重启",success(t){t.confirm&&e.applyUpdate()}})}),e.onUpdateFailed(function(e){uni.showModal({title:"更新失败",content:"新版本下载失败,请检查网络连接或稍后重试",showCancel:!1,confirmText:"知道了"})})}catch(e){}},y=()=>{try{const e=d();return e?.statusBarHeight||0}catch(e){return 0}},w=()=>{try{const e=h();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},v=()=>{try{const e=y(),t=h();if("weixin"===t||"alipay"===t){const t=w();if(t){return t.height+e}}return e+0}catch(e){return y()+0}},S=()=>{try{const e=y();return{statusBarHeight:e,navHeight:v()}}catch(e){return{statusBarHeight:0,navHeight:44}}},E=e=>e&&"string"==typeof e?new Promise(t=>{try{uni.setNavigationBarTitle({title:e,success:()=>{t(!0)},fail:e=>{t(!1)}})}catch(e){t(!1)}}):Promise.resolve(!1),T=(e,t="image/x-icon")=>o(()=>{const n=h();if(("h5"===n||"web"===n)&&"undefined"!=typeof document){document.querySelectorAll('link[rel*="icon"]').forEach(e=>e.remove());const n=document.createElement("link");return n.rel="icon",n.type=t,n.href=e,document.head.appendChild(n),!0}return!1},"system","SET_PAGE_ICON_ERROR",!1);function P(e){if(null===e||"object"!=typeof e)return e;try{if("undefined"!=typeof structuredClone)try{return structuredClone(e)}catch(e){}return JSON.parse(JSON.stringify(e))}catch(e){throw new Error(`深拷贝失败: ${e instanceof Error?e.message:String(e)}`)}}function M(e,t){const n=P(e);return function e(t,n){for(const s in n)if(n.hasOwnProperty(s)){const r=n[s],o=t[s];r&&"object"==typeof r&&!Array.isArray(r)&&o&&"object"==typeof o&&!Array.isArray(o)?e(o,r):t[s]=P(r)}}(n,t),n}function R(e,t){if(!t||0===Object.keys(t).length)return e;const n={...e};for(const s of Object.keys(e))Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=t[s]);return n}function C(e,t,n=!1){let s,r=null;const o=function(...o){const a=n&&!r;return r&&clearTimeout(r),r=setTimeout(()=>{r=null,n||(s=e.apply(this,o))},t),a&&(s=e.apply(this,o)),s};return o.cancel=()=>{r&&(clearTimeout(r),r=null)},o}function b(e,t,n={}){let s,r=null,o=0;const{leading:a=!0,trailing:i=!0}=n,c=function(...n){const c=Date.now();o||a||(o=c);const u=t-(c-o);return u<=0||u>t?(r&&(clearTimeout(r),r=null),o=c,s=e.apply(this,n)):!r&&i&&(r=setTimeout(()=>{o=a?Date.now():0,r=null,s=e.apply(this,n)},u)),s};return c.cancel=()=>{r&&(clearTimeout(r),r=null),o=0},c}function x(e,t={}){return async(...n)=>{try{return{data:await e(...n),error:null}}catch(e){return t.onError?.(e),{data:null,error:e}}finally{t.onFinally?.()}}}const I=e=>{try{if("undefined"==typeof window||!window.location)throw new Error("不在 H5 浏览器环境中");const t=new URLSearchParams(window.location.search),n={};return t.forEach((e,t)=>{try{n[t]=decodeURIComponent(e)}catch(s){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return e?null:{}}};function O(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,s={};return t.searchParams.forEach((e,t)=>{s[t]=e}),{path:n,params:s}}catch(e){return{path:"",params:{}}}}const _=e,A=t;function k(){return t()}const j=(e="",t=!1,n="none",s=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:s})};function L(e,t){if(!t||0===Object.keys(t).length)return e;const n=Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");return e+(e.includes("?")?"&":"?")+n}async function U(e){return new Promise(t=>{const n=L(e.url,e.params);uni.navigateTo({url:n,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>t(!0),fail:e=>{t(!1)}})})}async function $(e){return new Promise(t=>{const n=L(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}async function D(e="",t={}){return new Promise(n=>{const s=t.delta||1,r=t.timeout||5e3;if(getCurrentPages().length<=s)return void n(!1);const o=setTimeout(()=>{n(!1)},r);uni.navigateBack({delta:s,success:()=>{clearTimeout(o),setTimeout(()=>{try{const t=getCurrentPages();if(t.length>0){const n=t[t.length-1];n.$vm&&"function"==typeof n.$vm.init&&n.$vm.init(e)}n(!0)}catch(e){n(!0)}},100)},fail:e=>{clearTimeout(o),n(!1)}})})}async function z(e="",t={}){const n=getCurrentPages(),s=t.delta||1;if(n.length>s)return await D(e,t);const r=t.homePage||"pages/index/index",o=r.startsWith("/")?r:`/${r}`;return await B({url:o,params:t.homeParams})}const N=C(D,300);async function F(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:e=>{t(!1)}})})}async function B(e){return new Promise(t=>{const n=L(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}function W(){try{const e=getCurrentPages();if(0===e.length)return null;const t=e[e.length-1];return{route:t.route||"",options:t.options||{}}}catch(e){return null}}function H(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return[]}}async function J(e,t=3){for(let n=0;n<t;n++){if(await U(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1}const q={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};async function G(e,t={}){const n=c.getInstance();n.start("copyText","clipboard",{textLength:e.length});const s={...q,...t};if(!e||"string"!=typeof e)return s.showToast&&j("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return s.showToast&&j("复制内容过长",!1,"error"),n.end("copyText"),!1;const o=await r(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{s.showToast&&j(s.successMessage),t(!0)},fail:()=>{s.showToast&&j(s.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),o}class Y{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return Y.instance||(Y.instance=new Y),Y.instance}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,n={}){try{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const s={value:t,timestamp:Date.now(),ttl:n.ttl},r=JSON.stringify(s);if(r.length>1048576)throw new Error("存储数据过大");if(uni.setStorageSync(e,r),this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}return this.cache.set(e,s),!0}catch(e){throw e}}get(e,t){try{if(!e||"string"!=typeof e)return t;if(this.cache.has(e)){const n=this.cache.get(e);return this.isExpired(n)?(this.cache.delete(e),this.remove(e),t):n.value}const n=uni.getStorageSync(e);if(!n||"string"!=typeof n)return t;const s=JSON.parse(n);let r;return r=s&&"object"==typeof s&&"value"in s&&"timestamp"in s?s:{value:s,timestamp:Date.now()},this.isExpired(r)?(this.remove(e),t):(this.cache.set(e,r),r.value)}catch(e){return t}}remove(e){try{return!(!e||"string"!=typeof e)&&(uni.removeStorageSync(e),this.cache.delete(e),!0)}catch(e){return!1}}clear(){try{return uni.clearStorageSync(),this.cache.clear(),!0}catch(e){return!1}}getInfo(){try{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}}catch(e){return{keys:[],currentSize:0,limitSize:0}}}cleanExpired(){try{const e=this.getInfo();let t=0;return e.keys.forEach(e=>{void 0===this.get(e)&&t++}),t}catch(e){return 0}}}const V=Y.getInstance();function X(e,t,n={}){return V.set(e,t,n)}function K(e,t){return V.get(e,t)}function Q(e){return e?V.remove(e):V.clear()}async function Z(e,t,n={}){return await r(()=>new Promise(s=>{s(X(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1}async function ee(e,t){return await r(()=>new Promise(n=>{n(K(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t}function te(){return V.getInfo()}function ne(){return V.cleanExpired()}function se(e,t={}){const n=c.getInstance();n.start("batchSetStorage","localStorage");let s=0;return Object.entries(e).forEach(([e,n])=>{X(e,n,t)&&s++}),n.end("batchSetStorage"),s}function re(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=K(e)}),t.end("batchGetStorage"),n}function oe(e){const t=e.lastIndexOf(".");if(-1!==t&&t!==e.length-1)return e.slice(t+1).toLowerCase()}function ae(e){return`${Date.now()}_${e}_${Math.random().toString(16).slice(2)}`}function ie(e,t){if(!t)return{valid:!0};return e>1024*t*1024?{valid:!1,message:`文件大小不能超过 ${t}MB`}:{valid:!0}}function ce(e,t){if(0===e.length)return{success:!1,files:e,message:"未选择任何文件"};const{maxSelectFileSizeMB:n,extensions:s}=t;if(n){if(e.some(e=>!ie(e.size,n).valid))return{success:!1,files:e,message:`部分文件大小超过 ${n}MB 限制`}}if(s&&s.length>0){const t=s.map(e=>e.toLowerCase());if(e.some(e=>!e.ext||!t.includes(e.ext)))return{success:!1,files:e,message:`存在不支持的文件类型,仅支持:${s.join(", ")}`}}return{success:!0,files:e}}async function ue(e){return"undefined"!=typeof document&&"undefined"!=typeof window?function(e){const{type:t="image",count:n=1,extensions:s}=e;return new Promise(r=>{if("undefined"==typeof document)return void r({success:!1,files:[],message:"当前环境不支持文件选择"});const o=document.createElement("input");o.type="file",o.multiple=n>1,"image"===t?o.accept="image/*":s&&s.length>0&&(o.accept=s.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),o.onchange=t=>{const n=t.target,s=n?.files;if(!s||0===s.length)return r({success:!1,files:[],message:"用户取消选择"}),void document.body.removeChild(o);const a=ce(Array.from(s).map((e,t)=>{const n=oe(e.name),s=URL.createObjectURL(e);return{id:ae(t),name:e.name,size:e.size,path:s,mimeType:e.type,ext:n,source:"file",platform:"h5",raw:e}}),e);r(a),document.body.removeChild(o)},o.style.display="none",document.body.appendChild(o),o.click()})}(e):function(e){const{type:t="image",count:n=1}=e;return new Promise(s=>{const r="undefined"==typeof uni?null:uni;if(!r)return void s({success:!1,files:[],message:"当前环境不支持文件选择"});const o=e=>{const t=function(e){const t=(e||"").trim();if(!t)return"选择文件失败";const n=t.toLowerCase();return n.includes("fail cancel")||n.includes("cancel")?"用户取消选择":/[\u4e00-\u9fff]/.test(t)?t:"选择文件失败"}(e?.errMsg);s({success:!1,files:[],message:t})},a=function(){let e="unknown";return e="h5",e="weixin",e="alipay",e="app","app"}();"image"!==t||"function"!=typeof r.chooseImage?"function"!=typeof r.chooseMessageFile?"function"!=typeof r.chooseFile?s({success:!1,files:[],message:"当前平台不支持文件选择"}):r.chooseFile({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=oe(e.path);return{id:ae(t),name:`file_${t}`,size:e.size,path:e.path,ext:n,source:"file",platform:a,raw:e}});s(ce(n,e))},fail:o}):r.chooseMessageFile({count:n,type:"all",success:t=>{const n=t.tempFiles.map((e,t)=>{const n=oe(e.name||e.path);return{id:ae(t),name:e.name,size:e.size,path:e.path,ext:n,source:"file",platform:a,raw:e}});s(ce(n,e))},fail:o}):r.chooseImage({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=oe(e.path);return{id:ae(t),name:`image_${t}`,size:e.size,path:e.path,ext:n,source:"album",platform:a,raw:e}});s(ce(n,e))},fail:o})})}(e)}async function le(e,t,n){const{url:s,maxUploadFileSizeMB:r,showToast:o=!0,beforeUpload:a}=t;if("function"==typeof a){if(!await Promise.resolve(a(e)))return{file:e,success:!1,message:"已取消上传"}}if(!s){const t="上传地址不能为空";return o&&j(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const i=ie(e.size,r);return i.valid?"h5"===e.platform&&e.raw instanceof File?function(e,t,n){const{url:s,fieldName:r="file",formData:o,headers:a,showToast:i=!0,successMessage:c="上传成功",failMessage:u="上传失败",onProgress:l,uploadTimeoutMs:f,autoRevokeObjectURL:m=!1}=t;return new Promise(t=>{const d=e.raw;if(!(d&&d instanceof File)){const n="H5 环境缺少原生文件对象";return i&&j(n,!1,"none"),void t({file:e,success:!1,message:n})}const h=m&&"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&"string"==typeof e.path&&e.path.startsWith("blob:"),p=()=>{if(h)try{URL.revokeObjectURL(e.path)}catch{}},g=new XMLHttpRequest,y=new FormData;y.append(r,d,e.name),o&&Object.keys(o).forEach(e=>{y.append(e,String(o[e]))}),l&&g.upload.addEventListener("progress",t=>{if(t.lengthComputable){const n=Math.round(t.loaded/t.total*100);l(e,n)}}),g.addEventListener("load",()=>{const s=g.status,r=s>=200&&s<300;let o=g.responseText;try{o=JSON.parse(g.responseText)}catch{}if(r)i&&1===n&&j(c,!1,"none"),p(),t({file:e,success:!0,statusCode:s,data:o});else{const n=`上传失败,状态码:${s}`;i&&j(n,!1,"none"),p(),t({file:e,success:!1,statusCode:s,data:o,message:n})}}),g.addEventListener("error",()=>{const n=u;i&&j(n,!1,"none"),p(),t({file:e,success:!1,message:n})}),g.addEventListener("timeout",()=>{const n=f?`上传超时(${f}ms)`:"上传超时";i&&j(n,!1,"none"),p(),t({file:e,success:!1,message:n})}),g.addEventListener("abort",()=>{p(),t({file:e,success:!1,message:"上传已取消"})}),g.open("POST",s),"number"==typeof f&&f>0&&(g.timeout=f),a&&Object.keys(a).forEach(e=>{g.setRequestHeader(e,a[e])}),g.send(y)})}(e,t,n):function(e,t,n){const{url:s,fieldName:r="file",formData:o,headers:a,showToast:i=!0,successMessage:c="上传成功",failMessage:u="上传失败",onProgress:l,uploadTimeoutMs:f}=t,m="undefined"==typeof uni?null:uni;if(!m||"function"!=typeof m.uploadFile){const t="当前环境不支持文件上传";return i&&j(t,!1,"none"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{let d=!1,h=null;const p=e=>{d||(d=!0,h&&(clearTimeout(h),h=null),t(e))};let g=null;"number"==typeof f&&f>0&&(h=setTimeout(()=>{try{g&&"function"==typeof g.abort&&g.abort()}catch{}const t=`上传超时(${f}ms)`;i&&j(t,!1,"none"),p({file:e,success:!1,message:t})},f)),g=m.uploadFile({url:s,filePath:e.path,name:r,formData:o,header:a,success:t=>{let s=t.data;try{s=JSON.parse(t.data)}catch{}const r=t.statusCode;if(r>=200&&r<300)i&&1===n&&j(c,!1,"none"),p({file:e,success:!0,statusCode:r,data:s});else{const t=`上传失败,状态码:${r}`;i&&j(t,!1,"none"),p({file:e,success:!1,statusCode:r,data:s,message:t})}},fail:t=>{const n=t?.errMsg||u;i&&j(n,!1,"none"),p({file:e,success:!1,message:n})}}),l&&g&&"function"==typeof g.onProgressUpdate&&g.onProgressUpdate(t=>{l(e,t.progress)})})}(e,t,n):(o&&i.message&&j(i.message,!1,"error"),Promise.resolve({file:e,success:!1,message:i.message}))}async function fe(e){const{showToast:t=!0,failMessage:n="选择文件失败"}=e;try{const s=await ue(e);if(!s.success){const e=s.message||n;return t&&e&&j(e,!1,"none"),[{file:null,success:!1,message:e}]}const r=s.files;if(0===r.length)return[];const o=r.length;return await async function(e,t,n){const s=new Array(e.length),r=t.concurrency&&t.concurrency>0?Math.min(t.concurrency,e.length):e.length;let o=0;const a=async()=>{for(;;){const r=o;if(r>=e.length)break;o+=1;const a=e[r],i=await le(a,t,n);s[r]=i}},i=[];for(let e=0;e<r;e+=1)i.push(a());return await Promise.all(i),s}(r,e,o)}catch(e){const s=n;return t&&s&&j(s,!1,"none"),[{file:null,success:!1,message:s}]}}async function me(e){return fe({...e,type:"image"})}const de=(e,t,n)=>{const s=c.getInstance();return s.start("weChatOfficialAccountPayment","payment"),new Promise(r=>{o(()=>{if("undefined"==typeof window||!window.navigator)throw new Error("不在浏览器环境中,无法调用微信支付");if(!(e&&e.appId&&e.timeStamp&&e.nonceStr&&e.package&&e.paySign))throw new Error("微信支付配置参数不完整");function o(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){s.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),r(!0)):(n?.(e),r(!1))})}catch(e){s.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),r(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",o,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",o),e.attachEvent("onWeixinJSBridgeReady",o))}else o();return!0},"payment","WECHAT_PAY_ERROR",!1)||(s.end("weChatOfficialAccountPayment"),r(!1))})},he=()=>!("undefined"==typeof navigator||!navigator.userAgent)&&navigator.userAgent.toLowerCase().includes("micromessenger"),pe=()=>"undefined"!=typeof window&&"undefined"!=typeof document,ge=()=>pe()&&he()&&window.wx||null;let ye=!1,we=null;const ve=(e={})=>{const{timeoutMs:t=1e4}=e;if(ye||pe()&&window.wx)return ye=!0,Promise.resolve(!0);if(!pe())return Promise.resolve(!1);if(we)return we;const n=e.cdnUrls&&e.cdnUrls.length>0?e.cdnUrls:["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];return we=new Promise(e=>{let s=!1,r=null,o=null,a=0;const i=t=>{s||(s=!0,r&&(clearTimeout(r),r=null),o&&o.parentNode&&o.parentNode.removeChild(o),t&&(ye=!0),we=null,e(t))},c=()=>{if(a>=n.length)return void i(!1);if(!document.head)return void i(!1);const e=n[a];a+=1;const t=document.createElement("script");o=t,t.src=e,t.async=!0,t.onload=()=>i(!0),t.onerror=()=>{t.parentNode&&t.parentNode.removeChild(t),o=null,c()},document.head.appendChild(t)};r=setTimeout(()=>{i(!1)},t),c()}),we};let Se=null;const Ee=async(e,t={})=>{const{timeoutMs:n=1e4}=t;if(!he())return!1;if(Se)return Se;if(!await ve({timeoutMs:n}))return!1;if(!pe())return!1;const s=window.wx;return!!s&&(Se=new Promise(t=>{let r=!1,o=null;const a=e=>{r||(r=!0,o&&(clearTimeout(o),o=null),Se=null,t(e))};o=setTimeout(()=>a(!1),n);try{s.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),s.ready(()=>{a(!0)}),s.error(e=>{a(!1)})}catch(e){a(!1)}}),Se)},Te=(e,t={})=>{const{timeoutMs:n=8e3}=t;return new Promise(t=>{const s=ge();if(!s||"function"!=typeof s.checkJsApi)return void t({});let r=!1;const o=e=>{r||(r=!0,t(e))},a=setTimeout(()=>o({}),n);try{s.checkJsApi({jsApiList:e,success:e=>{clearTimeout(a),o(e?.checkResult||{})}})}catch(e){clearTimeout(a),o({})}})},Pe=e=>{const t=ge();t&&(t.updateTimelineShareData?t.updateTimelineShareData(e):t.onMenuShareTimeline&&t.onMenuShareTimeline(e))},Me=e=>{const t=ge();t&&(t.updateAppMessageShareData?t.updateAppMessageShareData(e):t.onMenuShareAppMessage&&t.onMenuShareAppMessage(e))};class Re{static instance;isConfigured=!1;config=null;initPromise=null;constructor(){}static getInstance(){return Re.instance||(Re.instance=new Re),Re.instance}async init(e){return this.initPromise||(this.config=e,this.initPromise=Ee(e).then(e=>(this.isConfigured=e,e)).finally(()=>{this.initPromise=null})),this.initPromise}isReady(){return this.isConfigured&&he()}getConfig(){return this.config}setShareData(e){this.isReady()&&(Pe(e),Me(e))}}const Ce="2.0.0";async function be(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,onError:s=null,performanceReportInterval:r=0}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return a}),t=e.getInstance();"function"==typeof s?t.onError(s):t.onError(e=>{})}if(t&&r>0){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return l}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},r)}}export{s as ErrorHandler,c as PerformanceMonitor,n as UniAppToolsError,Ce as VERSION,Re as WechatSDK,_ as areaList,re as batchGetStorage,se as batchSetStorage,Te as checkWechatJSAPI,ne as cleanExpiredStorage,Q as clearStorageSync,Ee as configWechatJSSDK,G as copyText,C as debounce,P as deepClone,M as deepMerge,O as extractUrlParts,p as getCurrentEnv,W as getCurrentPageInfo,I as getH5UrlParams,w as getMenuButtonBoundingClientRect,v as getNavHeight,H as getPageStack,h as getPlatform,y as getStatusBarHeight,ee as getStorage,te as getStorageInfo,K as getStorageSync,S as getTopNavBarHeight,be as initUniAppTools,he as isWechat,ve as loadWechatJSSDK,u as measurePerformance,R as mergeObjects,U as navigateTo,g as onCheckForUpdate,B as reLaunch,$ as redirectTo,r as safeAsync,J as safeNavigateTo,o as safeSync,fe as selectAndUpload,me as selectAndUploadImage,T as setPageIcon,E as setPageTitle,Z as setStorage,X as setStorageSync,Me as shareToFriend,Pe as shareToTimeline,F as switchTab,b as throttle,D as useBack,N as useBackDebounced,z as useBackOrHome,A as useCascaderAreaData,k as useRegions,j as useToast,x as useTryCatch,d as useWindowInfo,de as weChatOfficialAccountPayment};
|
package/dist/upload/index.d.ts
CHANGED
|
@@ -51,6 +51,15 @@ export interface SelectAndUploadOptions {
|
|
|
51
51
|
headers?: Record<string, string>;
|
|
52
52
|
/** 单次最大并发上传数量(默认与文件数相同,即全部并行) */
|
|
53
53
|
concurrency?: number;
|
|
54
|
+
/** 上传超时(毫秒),超时将中止上传并返回失败结果 */
|
|
55
|
+
uploadTimeoutMs?: number;
|
|
56
|
+
/**
|
|
57
|
+
* H5 环境下是否在上传结束后自动释放 `URL.createObjectURL` 创建的对象 URL
|
|
58
|
+
* @description
|
|
59
|
+
* - 默认 false:保持旧行为不变(部分业务可能在上传后仍需要用 path 预览)
|
|
60
|
+
* - 若业务不再需要该 blob URL,建议开启以减少长时间使用下的内存占用
|
|
61
|
+
*/
|
|
62
|
+
autoRevokeObjectURL?: boolean;
|
|
54
63
|
/**
|
|
55
64
|
* 上传前拦截钩子
|
|
56
65
|
* 返回 false 或 Promise<false> 将跳过该文件的上传,并在结果中标记为失败(不弹 toast)
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -3,104 +3,65 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { useCascaderAreaData as vantUseCascaderAreaData } from '@vant/area-data';
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
* @
|
|
8
|
-
* @returns 深拷贝后的对象
|
|
9
|
-
* @description 兼容小程序、App、H5 多端环境的深拷贝实现
|
|
6
|
+
* 高性能深拷贝(uni-app 多端兼容)
|
|
7
|
+
* @description H5 环境优先使用 structuredClone,降级为 JSON 序列化
|
|
10
8
|
*/
|
|
11
9
|
export declare function deepClone<T>(obj: T): T;
|
|
12
|
-
/**
|
|
13
|
-
* 浅拷贝对象合并
|
|
14
|
-
* @param target 目标对象
|
|
15
|
-
* @param source 源对象
|
|
16
|
-
* @returns 合并后的目标对象
|
|
17
|
-
*/
|
|
18
|
-
export declare function mergeObjects<T extends Record<string, any>>(target: T, source: Partial<T>): T;
|
|
19
10
|
/**
|
|
20
11
|
* 深度合并对象
|
|
21
|
-
* @param target 目标对象
|
|
22
|
-
* @param source 源对象
|
|
23
|
-
* @returns 深度合并后的新对象
|
|
24
12
|
*/
|
|
25
13
|
export declare function deepMerge<T extends Record<string, any>>(target: T, source: Partial<T>): T;
|
|
26
14
|
/**
|
|
27
|
-
*
|
|
28
|
-
* @
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
15
|
+
* 只合并目标对象中已存在的字段
|
|
16
|
+
* @description 避免后端返回的冗余字段污染前端表单状态
|
|
17
|
+
*/
|
|
18
|
+
export declare function mergeObjects<T extends Record<string, any>, U extends Record<string, any>>(base: T, incoming: U): T;
|
|
19
|
+
/**
|
|
20
|
+
* 防抖函数
|
|
32
21
|
*/
|
|
33
22
|
export declare function debounce<T extends (...args: any[]) => any>(func: T, wait: number, immediate?: boolean): T;
|
|
34
23
|
/**
|
|
35
|
-
*
|
|
36
|
-
* @param func 要节流的函数
|
|
37
|
-
* @param wait 等待时间(毫秒)
|
|
38
|
-
* @param options 选项
|
|
39
|
-
* @returns 节流后的函数
|
|
24
|
+
* 节流函数
|
|
40
25
|
*/
|
|
41
26
|
export declare function throttle<T extends (...args: any[]) => any>(func: T, wait: number, options?: {
|
|
42
27
|
leading?: boolean;
|
|
43
28
|
trailing?: boolean;
|
|
44
29
|
}): T;
|
|
45
30
|
/**
|
|
46
|
-
*
|
|
47
|
-
* @
|
|
48
|
-
*/
|
|
49
|
-
export declare function useDeepCopyByObj<T>(target: T, source: any): T;
|
|
50
|
-
/**
|
|
51
|
-
* H5 环境 URL 参数获取函数接口
|
|
31
|
+
* 封装通用的 try/catch/finally 调用
|
|
32
|
+
* @returns 包装后的执行函数,返回 Promise<{ data, error }>
|
|
52
33
|
*/
|
|
34
|
+
export declare function useTryCatch<T extends (...args: any[]) => any>(fn: T, options?: {
|
|
35
|
+
onError?: (error: unknown) => void;
|
|
36
|
+
onFinally?: () => void;
|
|
37
|
+
}): (...args: Parameters<T>) => Promise<{
|
|
38
|
+
data: Awaited<ReturnType<T>> | null;
|
|
39
|
+
error: unknown;
|
|
40
|
+
}>;
|
|
53
41
|
export interface UrlParams {
|
|
54
42
|
[key: string]: string;
|
|
55
43
|
}
|
|
56
44
|
/**
|
|
57
45
|
* 获取 H5 环境下的 URL 参数
|
|
58
|
-
* @
|
|
59
|
-
* @returns 如果指定参数名则返回对应值或null,否则返回所有参数对象
|
|
60
|
-
* @description 在 H5 环境中解析 URL 参数
|
|
46
|
+
* @description 仅在 H5 环境有效
|
|
61
47
|
*/
|
|
62
48
|
export declare const getH5UrlParams: (paramName?: string) => string | null | UrlParams;
|
|
63
49
|
/**
|
|
64
50
|
* 从URL中提取页面路径和参数
|
|
65
|
-
* @param url 要解析的URL
|
|
66
|
-
* @returns 包含路径和参数的对象
|
|
67
|
-
* @example
|
|
68
|
-
* ```js
|
|
69
|
-
* const url = "http://example.com/path/to/page?foo=bar&baz=qux";
|
|
70
|
-
* const { path, params } = extractUrlParts(url);
|
|
71
|
-
* console.log(path); // "/path/to/page"
|
|
72
|
-
* console.log(params); // { foo: "bar", baz: "qux" }
|
|
73
|
-
* ```
|
|
74
51
|
*/
|
|
75
52
|
export declare function extractUrlParts(url: string): {
|
|
76
53
|
path: string;
|
|
77
54
|
params: Record<string, string>;
|
|
78
55
|
};
|
|
79
|
-
/**
|
|
80
|
-
* 封装通用的 try/catch/finally 调用
|
|
81
|
-
* @param fn 需要被保护执行的函数,可以返回同步结果或 Promise
|
|
82
|
-
* @param options 可选配置项,支持错误和最终回调
|
|
83
|
-
* @returns 返回一个包装后的执行函数,执行结果为 Promise<{ data, error }>
|
|
84
|
-
*/
|
|
85
|
-
export declare function useTryCatch<T extends (...args: any[]) => any>(fn: T, options?: {
|
|
86
|
-
onError?: (error: unknown) => void;
|
|
87
|
-
onFinally?: () => void;
|
|
88
|
-
}): (...args: Parameters<T>) => Promise<{
|
|
89
|
-
data: Awaited<ReturnType<T>> | null;
|
|
90
|
-
error: unknown;
|
|
91
|
-
}>;
|
|
92
56
|
/**
|
|
93
57
|
* 中国省市区数据
|
|
94
|
-
* @description
|
|
58
|
+
* @description 数据来源于 @vant/area-data
|
|
95
59
|
*/
|
|
96
60
|
export declare const areaList: {
|
|
97
61
|
province_list: Record<string, string>;
|
|
98
62
|
city_list: Record<string, string>;
|
|
99
63
|
county_list: Record<string, string>;
|
|
100
64
|
};
|
|
101
|
-
/**
|
|
102
|
-
* 级联选择器选项类型
|
|
103
|
-
*/
|
|
104
65
|
export interface CascaderOption {
|
|
105
66
|
text: string;
|
|
106
67
|
value: string;
|
|
@@ -108,26 +69,11 @@ export interface CascaderOption {
|
|
|
108
69
|
}
|
|
109
70
|
/**
|
|
110
71
|
* 生成级联选择器所需的省市区数据
|
|
111
|
-
* @
|
|
112
|
-
* @description 将 areaList 转换为级联选择器组件所需的树形结构数据,数据来源于 @vant/area-data
|
|
113
|
-
* @example
|
|
114
|
-
* ```ts
|
|
115
|
-
* import { useCascaderAreaData } from 'uniapp-tool-functions';
|
|
116
|
-
*
|
|
117
|
-
* const cascaderData = useCascaderAreaData();
|
|
118
|
-
* ```
|
|
72
|
+
* @description 将 areaList 转换为级联选择器组件所需的树形结构
|
|
119
73
|
*/
|
|
120
74
|
export declare const useCascaderAreaData: typeof vantUseCascaderAreaData;
|
|
121
75
|
/**
|
|
122
76
|
* 生成中国省市区级联数据
|
|
123
|
-
* @
|
|
124
|
-
* @description 此函数是 useCascaderAreaData 的别名,用于生成省市区三级联动数据
|
|
125
|
-
* @example
|
|
126
|
-
* ```ts
|
|
127
|
-
* import { useRegions } from 'uniapp-tool-functions';
|
|
128
|
-
*
|
|
129
|
-
* const regions = useRegions();
|
|
130
|
-
* console.log(regions); // 返回省市区三级联动数据
|
|
131
|
-
* ```
|
|
77
|
+
* @description useCascaderAreaData 的别名
|
|
132
78
|
*/
|
|
133
79
|
export declare function useRegions(): CascaderOption[];
|
package/dist/weixin/index.d.ts
CHANGED
|
@@ -35,36 +35,31 @@ declare global {
|
|
|
35
35
|
}
|
|
36
36
|
/**
|
|
37
37
|
* 检测是否在微信浏览器中运行
|
|
38
|
-
* @returns 是否为微信浏览器环境
|
|
39
|
-
* @description 检测当前是否在微信浏览器中运行(不包括微信小程序)
|
|
40
38
|
*/
|
|
41
39
|
export declare const isWechat: () => boolean;
|
|
42
40
|
/**
|
|
43
41
|
* 动态加载微信 JS-SDK
|
|
44
|
-
*
|
|
45
|
-
* @description 支持主备CDN地址,提升服务稳定性
|
|
42
|
+
* 支持主备 CDN 地址,提升服务稳定性
|
|
46
43
|
*/
|
|
47
|
-
export declare const loadWechatJSSDK: (
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
44
|
+
export declare const loadWechatJSSDK: (options?: {
|
|
45
|
+
timeoutMs?: number;
|
|
46
|
+
cdnUrls?: string[];
|
|
47
|
+
}) => Promise<boolean>;
|
|
48
|
+
export declare const configWechatJSSDK: (config: WxConfig, options?: {
|
|
49
|
+
timeoutMs?: number;
|
|
50
|
+
}) => Promise<boolean>;
|
|
54
51
|
/**
|
|
55
52
|
* 检查微信 JS-SDK API 可用性
|
|
56
|
-
* @param jsApiList 需要检查的 API 列表
|
|
57
|
-
* @returns Promise<Record<string, boolean>> API 可用性结果
|
|
58
53
|
*/
|
|
59
|
-
export declare const checkWechatJSAPI: (jsApiList: string[]
|
|
54
|
+
export declare const checkWechatJSAPI: (jsApiList: string[], options?: {
|
|
55
|
+
timeoutMs?: number;
|
|
56
|
+
}) => Promise<Record<string, boolean>>;
|
|
60
57
|
/**
|
|
61
58
|
* 微信分享到朋友圈
|
|
62
|
-
* @param config 分享配置
|
|
63
59
|
*/
|
|
64
60
|
export declare const shareToTimeline: (config: WxShareConfig) => void;
|
|
65
61
|
/**
|
|
66
62
|
* 微信分享给朋友
|
|
67
|
-
* @param config 分享配置
|
|
68
63
|
*/
|
|
69
64
|
export declare const shareToFriend: (config: WxShareConfig) => void;
|
|
70
65
|
/**
|
|
@@ -74,12 +69,11 @@ export declare class WechatSDK {
|
|
|
74
69
|
private static instance;
|
|
75
70
|
private isConfigured;
|
|
76
71
|
private config;
|
|
72
|
+
private initPromise;
|
|
77
73
|
private constructor();
|
|
78
74
|
static getInstance(): WechatSDK;
|
|
79
75
|
/**
|
|
80
76
|
* 初始化微信 JS-SDK
|
|
81
|
-
* @param config 配置参数
|
|
82
|
-
* @returns Promise<boolean>
|
|
83
77
|
*/
|
|
84
78
|
init(config: WxConfig): Promise<boolean>;
|
|
85
79
|
/**
|
|
@@ -92,7 +86,6 @@ export declare class WechatSDK {
|
|
|
92
86
|
getConfig(): WxConfig | null;
|
|
93
87
|
/**
|
|
94
88
|
* 设置分享信息
|
|
95
|
-
* @param shareConfig 分享配置
|
|
96
89
|
*/
|
|
97
90
|
setShareData(shareConfig: WxShareConfig): void;
|
|
98
91
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "my-uniapp-tools",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "一个功能强大、性能优化的 uni-app 开发工具库,提供剪贴板、本地存储、导航、系统信息等常用功能",
|
|
6
6
|
"main": "dist/my-uniapp-tools.cjs.js",
|
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
"build": "rollup -c && tsc --declaration --emitDeclarationOnly --outDir dist",
|
|
17
17
|
"build:prod": "NODE_ENV=production rollup -c && tsc --declaration --emitDeclarationOnly --outDir dist",
|
|
18
18
|
"prepublishOnly": "npm run build:prod",
|
|
19
|
-
"test": "
|
|
19
|
+
"test": "npm run build && node tests/run-tests.js",
|
|
20
|
+
"test:only": "node tests/run-tests.js",
|
|
20
21
|
"dev": "node src/index.js",
|
|
21
22
|
"docs:dev": "vuepress dev docs",
|
|
22
23
|
"docs:build": "vuepress build docs",
|