my-uniapp-tools 2.0.0 → 2.0.1

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/index.d.ts CHANGED
@@ -10,4 +10,4 @@ export * from "./localStorage";
10
10
  export * from "./upload";
11
11
  export * from "./payment";
12
12
  export * from "./weixin";
13
- export const VERSION: "1.0.8";
13
+ export const VERSION: "2.0.0";
@@ -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 s={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(s)}catch(e){}})}createModuleErrorHandler(e){return(n,s,r)=>{const a=new t(n,s,e);return r&&(a.stack=r.stack),this.handleError(a,e),a}}}async function s(e,t,s="ASYNC_ERROR"){try{return await e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(s,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function r(e,t,s="SYNC_ERROR",r=null){try{return e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(s,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),r}}var a=Object.freeze({__proto__:null,ErrorHandler:n,UniAppToolsError:t,safeAsync:s,safeSync:r});function o(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}class i{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return i.instance||(i.instance=new i),i.instance}start(e,t,n){const s={name:e,startTime:o(),module:t,metadata:n};this.metrics.set(e,s)}end(e){const t=this.metrics.get(e);return t?(t.endTime=o(),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 c(e){return function(t,n,s){const r=s.value;s.value=function(...s){const a=i.getInstance(),o=`${t.constructor.name}.${n}`;a.start(o,e,{args:s.length});try{const e=r.apply(this,s);return e instanceof Promise?e.finally(()=>{a.end(o)}):(a.end(o),e)}catch(e){throw a.end(o),e}}}}var u=Object.freeze({__proto__:null,PerformanceMonitor:i,measurePerformance:c});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 p=l.getInstance(),m=()=>{const e="platform",t=p.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",p.set(e,"h5"),"h5"},d=()=>{try{return uni.getSystemInfoSync().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 f(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 w(e,t,n=!1){let s,r=null;const a=function(...a){const o=n&&!r;return r&&clearTimeout(r),r=setTimeout(()=>{r=null,n||(s=e.apply(this,a))},t),o&&(s=e.apply(this,a)),s};return a.cancel=()=>{r&&(clearTimeout(r),r=null)},a}const x=e.areaList,S=e.useCascaderAreaData;const T=(e="",t=!1,n="none",s=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:s})};function E(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=E(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 R(e="",t={}){return new Promise(n=>{const s=t.delta||1,r=t.timeout||5e3;if(getCurrentPages().length<=s)return void n(!1);const a=setTimeout(()=>{n(!1)},r);uni.navigateBack({delta:s,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)}})})}const v=w(R,300);async function I(e){return new Promise(t=>{const n=E(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}const C={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};class F{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return F.instance||(F.instance=new F),F.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 A=F.getInstance();function M(e,t,n={}){return A.set(e,t,n)}function O(e,t){return A.get(e,t)}const _={name:"file",maxSize:10,allowedTypes:["jpg","jpeg","png","gif","webp"],showToast:!0,timeout:6e4,successMessage:"上传成功",failMessage:"上传失败"},b={type:"image",count:1,sizeType:["original","compressed"],sourceType:["album","camera"],extension:[],maxSize:10,showToast:!0,failMessage:"选择文件失败"};async function D(e={}){const t=i.getInstance();t.start("chooseFile","upload",{count:e.count,type:e.type});const n={...b,...e};let r=n.type;var a;("messagefile"===(a=r)?"function"==typeof uni.chooseMessageFile:"local"===a||"image"===a)||(r="image");const o=await s(()=>new Promise(e=>{const t=t=>{const s=t.errMsg||n.failMessage;n.showToast&&T(s,!1,"error"),e({success:!1,message:s,type:r})};"image"!==r&&"local"!==r?"messagefile"===r?uni.chooseMessageFile({count:n.count,type:"all",success:t=>{e({success:!0,tempFilePaths:t.tempFiles.map(e=>e.path),tempFiles:t.tempFiles,type:"messagefile"})},fail:t}):"image"===r?uni.chooseImage({count:n.count,sizeType:n.sizeType,sourceType:n.sourceType,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"image"})},fail:t}):"local"===r&&("function"==typeof uni.chooseFile?uni.chooseFile({count:n.count,extension:n.extension,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"local"})},fail:t}):e({success:!1,message:"当前平台不支持选择本地文件",type:r})):function(e,t){const n=document.createElement("input");n.type="file",n.multiple=e.count>1,"image"===e.type?n.accept="image/*":e.extension.length>0&&(n.accept=e.extension.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),n.onchange=s=>{const r=s.target.files;if(r&&r.length>0){const n=Array.from(r).map(e=>({path:URL.createObjectURL(e),size:e.size,name:e.name,type:e.type,file:e})),s=n.map(e=>({path:e.path,size:e.size}));t({success:!0,tempFilePaths:n.map(e=>e.path),tempFiles:s,type:e.type})}else t({success:!1,message:"用户取消选择",type:e.type});document.body.removeChild(n)},n.style.display="none",document.body.appendChild(n),n.click()}(n,e)}).then(e=>{if(!e.success||!e.tempFiles||!n.maxSize)return e;if(e.tempFiles.filter(e=>{var t,s;return!(t=e.size,(s=n.maxSize)&&t>1024*s*1024?{valid:!1,message:`文件大小不能超过 ${s}MB`}:{valid:!0}).valid}).length>0){const t=`部分文件大小超过 ${n.maxSize}MB 限制`;return n.showToast&&T(t,!1,"error"),{...e,success:!1,message:t}}return e}),"upload","CHOOSE_FILE_ERROR");return t.end("chooseFile"),o||{success:!1,message:"选择文件失败",type:r}}async function k(e,t,n){const r=i.getInstance();r.start("uploadFile","upload",{filePath:e});const a={..._,...t};if(!a.url){const e="上传地址不能为空";return a.showToast&&T(e,!1,"error"),r.end("uploadFile"),{success:!1,message:e}}const o=function(e,t){if(!e)return{valid:!1,message:"文件路径不能为空"};if(t.allowedTypes&&t.allowedTypes.length>0){const n=e.split(".").pop()?.toLowerCase();if(!n||!t.allowedTypes.includes(n))return{valid:!1,message:`不支持的文件类型,仅支持:${t.allowedTypes.join(", ")}`}}return{valid:!0}}(e,a);if(!o.valid)return a.showToast&&T(o.message,!1,"error"),r.end("uploadFile"),{success:!1,message:o.message};const c=await s(()=>new Promise(t=>{const s=uni.uploadFile({url:a.url,filePath:e,name:a.name,formData:a.formData,header:a.header,timeout:a.timeout,success:n=>{let s;try{s=JSON.parse(n.data)}catch{s=n.data}if(200===n.statusCode)a.showToast&&T(a.successMessage,!1,"success"),t({success:!0,data:s,tempFilePath:e,statusCode:n.statusCode});else{const e=`上传失败,状态码:${n.statusCode}`;a.showToast&&T(e,!1,"error"),t({success:!1,message:e,statusCode:n.statusCode})}},fail:n=>{const s=n.errMsg||a.failMessage;a.showToast&&T(s,!1,"error"),t({success:!1,message:s,tempFilePath:e})}});n&&s&&s.onProgressUpdate(e=>{n({progress:e.progress,totalBytesSent:e.totalBytesSent,totalBytesExpectedToSend:e.totalBytesExpectedToSend})})}),"upload","UPLOAD_FILE_ERROR");return r.end("uploadFile"),c||{success:!1,message:"上传文件失败"}}async function z(e,t={},n){const s=i.getInstance();s.start("chooseAndUploadFile","upload");const r=await D(t);if(!r.success||!r.tempFilePaths)return s.end("chooseAndUploadFile"),[{success:!1,message:r.message||"选择文件失败"}];const a=r.tempFilePaths.map(t=>k(t,e,n)),o=await Promise.all(a);return s.end("chooseAndUploadFile"),o}const j=()=>{const e=i.getInstance();e.start("isWechat","system");const t=r(()=>{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},U=()=>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 s=r=>{const a=document.createElement("script");a.src=r,a.async=!0,a.onload=()=>{e(!0)},a.onerror=()=>{n++,n<t.length?(document.head.removeChild(a),s(t[n])):(document.head.removeChild(a),e(!1))},document.head.appendChild(a)};s(t[n]),e(!1)}),B=async e=>{const t=i.getInstance();t.start("configWechatJSSDK","wechat");try{if(!j())return!1;return!!await U()&&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")}},W=e=>{r(()=>{window.wx&&j()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},H=e=>{r(()=>{window.wx&&j()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class L{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return L.instance||(L.instance=new L),L.instance}async init(e){return this.config=e,this.isConfigured=await B(e),this.isConfigured}isReady(){return this.isConfigured&&j()}getConfig(){return this.config}setShareData(e){this.isReady()&&(W(e),H(e))}}exports.ErrorHandler=n,exports.PerformanceMonitor=i,exports.UniAppToolsError=t,exports.VERSION="1.0.8",exports.WechatSDK=L,exports.areaList=x,exports.batchGetStorage=function(e){const t=i.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=O(e)}),t.end("batchGetStorage"),n},exports.batchSetStorage=function(e,t={}){const n=i.getInstance();n.start("batchSetStorage","localStorage");let s=0;return Object.entries(e).forEach(([e,n])=>{M(e,n,t)&&s++}),n.end("batchSetStorage"),s},exports.checkWechatJSAPI=e=>new Promise(t=>{window.wx&&j()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),exports.chooseAndUploadFile=z,exports.chooseAndUploadImage=async function(e,t={},n){return z(e,{...t,type:"image"},n)},exports.chooseFile=D,exports.chooseImage=async function(e={}){const t=await D({...e,type:"image"});return{success:t.success,tempFilePaths:t.tempFilePaths,tempFiles:t.tempFiles,message:t.message}},exports.cleanExpiredStorage=function(){return A.cleanExpired()},exports.clearStorageSync=function(e){return e?A.remove(e):A.clear()},exports.configWechatJSSDK=B,exports.copyText=async function(e,t={}){const n=i.getInstance();n.start("copyText","clipboard",{textLength:e.length});const r={...C,...t};if(!e||"string"!=typeof e)return r.showToast&&T("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return r.showToast&&T("复制内容过长",!1,"error"),n.end("copyText"),!1;const a=await s(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{r.showToast&&T(r.successMessage),t(!0)},fail:()=>{r.showToast&&T(r.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),a},exports.debounce=w,exports.deepClone=f,exports.deepMerge=function(e,t){const n=f(e);return function e(t,n){for(const s in n)if(n.hasOwnProperty(s)){const r=n[s],a=t[s];r&&"object"==typeof r&&!Array.isArray(r)&&a&&"object"==typeof a&&!Array.isArray(a)?e(a,r):t[s]=f(r)}}(n,t),n},exports.extractUrlParts=function(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:{}}}},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.getFileInfo=async function(e){return await s(()=>new Promise((t,n)=>{uni.getFileInfo({filePath:e,digestAlgorithm:"md5",success:e=>{const n=e;t({size:n.size,digest:n.digest})},fail:n})}),"upload","GET_FILE_INFO_ERROR")},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(s){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 s(()=>new Promise(n=>{n(O(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t},exports.getStorageInfo=function(){return A.getInfo()},exports.getStorageSync=O,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: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 u}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},r)}},exports.isUploadSupported=function(){return"undefined"!=typeof uni&&"function"==typeof uni.chooseImage&&"function"==typeof uni.uploadFile},exports.isWechat=j,exports.loadWechatJSSDK=U,exports.measurePerformance=c,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=E(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})},exports.safeAsync=s,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=r,exports.setPageIcon=(e,t="image/x-icon")=>r(()=>{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 s(()=>new Promise(s=>{s(M(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1},exports.setStorageSync=M,exports.shareToFriend=H,exports.shareToTimeline=W,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 s,r=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?(r&&(clearTimeout(r),r=null),a=c,s=e.apply(this,n)):!r&&i&&(r=setTimeout(()=>{a=o?Date.now():0,r=null,s=e.apply(this,n)},u)),s};return c.cancel=()=>{r&&(clearTimeout(r),r=null),a=0},c},exports.uploadFile=k,exports.useBack=R,exports.useBackDebounced=v,exports.useBackOrHome=async function(e="",t={}){const n=getCurrentPages(),s=t.delta||1;if(n.length>s)return await R(e,t);const r=t.homePage||"pages/index/index",a=r.startsWith("/")?r:`/${r}`;return await I({url:a,params:t.homeParams})},exports.useCascaderAreaData=S,exports.useDeepCopyByObj=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return y(e,f(t))}return f(t)},exports.useRegions=function(){return e.useCascaderAreaData()},exports.useToast=T,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=(e=!0)=>{const t=i.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=p.get(n);if(e)return t.end("getWindowInfo"),e}const s=r(()=>{const t=uni.getWindowInfo();return e&&p.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),s},exports.weChatOfficialAccountPayment=(e,t,n)=>{const s=i.getInstance();return s.start("weChatOfficialAccountPayment","payment"),new Promise(a=>{r(()=>{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 r(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){s.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),a(!0)):(n?.(e),a(!1))})}catch(e){s.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),a(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",r,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",r),e.attachEvent("onWeixinJSBridgeReady",r))}else r();return!0},"payment","WECHAT_PAY_ERROR",!1)||(s.end("weChatOfficialAccountPayment"),a(!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 s={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(s)}catch(e){}})}createModuleErrorHandler(e){return(n,s,r)=>{const a=new t(n,s,e);return r&&(a.stack=r.stack),this.handleError(a,e),a}}}async function s(e,t,s="ASYNC_ERROR"){try{return await e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(s,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function r(e,t,s="SYNC_ERROR",r=null){try{return e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(s,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),r}}var a=Object.freeze({__proto__:null,ErrorHandler:n,UniAppToolsError:t,safeAsync:s,safeSync:r});function o(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}class i{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return i.instance||(i.instance=new i),i.instance}start(e,t,n){const s={name:e,startTime:o(),module:t,metadata:n};this.metrics.set(e,s)}end(e){const t=this.metrics.get(e);return t?(t.endTime=o(),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 c(e){return function(t,n,s){const r=s.value;s.value=function(...s){const a=i.getInstance(),o=`${t.constructor.name}.${n}`;a.start(o,e,{args:s.length});try{const e=r.apply(this,s);return e instanceof Promise?e.finally(()=>{a.end(o)}):(a.end(o),e)}catch(e){throw a.end(o),e}}}}var u=Object.freeze({__proto__:null,PerformanceMonitor:i,measurePerformance:c});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 p=l.getInstance(),d=(e=!0)=>{const t=i.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=p.get(n);if(e)return t.end("getWindowInfo"),e}const s=r(()=>{const t=uni.getWindowInfo();return e&&p.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),s},m=()=>{const e="platform",t=p.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",p.set(e,"h5"),"h5"},h=()=>{try{const e=d();return e?.statusBarHeight||0}catch(e){return 0}},g=()=>{try{const e=m();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},f=()=>{try{const e=h(),t=m();if("weixin"===t||"alipay"===t){const t=g();if(t){return t.height+e}}return e+0}catch(e){return h()+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){return Object.assign(e,t)}function x(e,t,n=!1){let s,r=null;const a=function(...a){const o=n&&!r;return r&&clearTimeout(r),r=setTimeout(()=>{r=null,n||(s=e.apply(this,a))},t),o&&(s=e.apply(this,a)),s};return a.cancel=()=>{r&&(clearTimeout(r),r=null)},a}const S=e.areaList,T=e.useCascaderAreaData;const E=(e="",t=!1,n="none",s=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:s})};function P(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 R(e){return new Promise(t=>{const n=P(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 v(e="",t={}){return new Promise(n=>{const s=t.delta||1,r=t.timeout||5e3;if(getCurrentPages().length<=s)return void n(!1);const a=setTimeout(()=>{n(!1)},r);uni.navigateBack({delta:s,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)}})})}const I=x(v,300);async function C(e){return new Promise(t=>{const n=P(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}const F={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 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 M=A.getInstance();function O(e,t,n={}){return M.set(e,t,n)}function _(e,t){return M.get(e,t)}const b={name:"file",maxSize:10,allowedTypes:["jpg","jpeg","png","gif","webp"],showToast:!0,timeout:6e4,successMessage:"上传成功",failMessage:"上传失败"},D={type:"image",count:1,sizeType:["original","compressed"],sourceType:["album","camera"],extension:[],maxSize:10,showToast:!0,failMessage:"选择文件失败"};async function k(e={}){const t=i.getInstance();t.start("chooseFile","upload",{count:e.count,type:e.type});const n={...D,...e};let r=n.type;var a;("messagefile"===(a=r)?"function"==typeof uni.chooseMessageFile:"local"===a||"image"===a)||(r="image");const o=await s(()=>new Promise(e=>{const t=t=>{const s=t.errMsg||n.failMessage;n.showToast&&E(s,!1,"error"),e({success:!1,message:s,type:r})};"image"!==r&&"local"!==r?"messagefile"===r?uni.chooseMessageFile({count:n.count,type:"all",success:t=>{e({success:!0,tempFilePaths:t.tempFiles.map(e=>e.path),tempFiles:t.tempFiles,type:"messagefile"})},fail:t}):"image"===r?uni.chooseImage({count:n.count,sizeType:n.sizeType,sourceType:n.sourceType,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"image"})},fail:t}):"local"===r&&("function"==typeof uni.chooseFile?uni.chooseFile({count:n.count,extension:n.extension,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"local"})},fail:t}):e({success:!1,message:"当前平台不支持选择本地文件",type:r})):function(e,t){const n=document.createElement("input");n.type="file",n.multiple=e.count>1,"image"===e.type?n.accept="image/*":e.extension.length>0&&(n.accept=e.extension.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),n.onchange=s=>{const r=s.target.files;if(r&&r.length>0){const n=Array.from(r).map(e=>({path:URL.createObjectURL(e),size:e.size,name:e.name,type:e.type,file:e})),s=n.map(e=>({path:e.path,size:e.size}));t({success:!0,tempFilePaths:n.map(e=>e.path),tempFiles:s,type:e.type})}else t({success:!1,message:"用户取消选择",type:e.type});document.body.removeChild(n)},n.style.display="none",document.body.appendChild(n),n.click()}(n,e)}).then(e=>{if(!e.success||!e.tempFiles||!n.maxSize)return e;if(e.tempFiles.filter(e=>{var t,s;return!(t=e.size,(s=n.maxSize)&&t>1024*s*1024?{valid:!1,message:`文件大小不能超过 ${s}MB`}:{valid:!0}).valid}).length>0){const t=`部分文件大小超过 ${n.maxSize}MB 限制`;return n.showToast&&E(t,!1,"error"),{...e,success:!1,message:t}}return e}),"upload","CHOOSE_FILE_ERROR");return t.end("chooseFile"),o||{success:!1,message:"选择文件失败",type:r}}async function z(e,t,n){const r=i.getInstance();r.start("uploadFile","upload",{filePath:e});const a={...b,...t};if(!a.url){const e="上传地址不能为空";return a.showToast&&E(e,!1,"error"),r.end("uploadFile"),{success:!1,message:e}}const o=function(e,t){if(!e)return{valid:!1,message:"文件路径不能为空"};if(t.allowedTypes&&t.allowedTypes.length>0){const n=e.split(".").pop()?.toLowerCase();if(!n||!t.allowedTypes.includes(n))return{valid:!1,message:`不支持的文件类型,仅支持:${t.allowedTypes.join(", ")}`}}return{valid:!0}}(e,a);if(!o.valid)return a.showToast&&E(o.message,!1,"error"),r.end("uploadFile"),{success:!1,message:o.message};const c=await s(()=>new Promise(t=>{const s=uni.uploadFile({url:a.url,filePath:e,name:a.name,formData:a.formData,header:a.header,timeout:a.timeout,success:n=>{let s;try{s=JSON.parse(n.data)}catch{s=n.data}if(200===n.statusCode)a.showToast&&E(a.successMessage,!1,"success"),t({success:!0,data:s,tempFilePath:e,statusCode:n.statusCode});else{const e=`上传失败,状态码:${n.statusCode}`;a.showToast&&E(e,!1,"error"),t({success:!1,message:e,statusCode:n.statusCode})}},fail:n=>{const s=n.errMsg||a.failMessage;a.showToast&&E(s,!1,"error"),t({success:!1,message:s,tempFilePath:e})}});n&&s&&s.onProgressUpdate(e=>{n({progress:e.progress,totalBytesSent:e.totalBytesSent,totalBytesExpectedToSend:e.totalBytesExpectedToSend})})}),"upload","UPLOAD_FILE_ERROR");return r.end("uploadFile"),c||{success:!1,message:"上传文件失败"}}async function j(e,t={},n){const s=i.getInstance();s.start("chooseAndUploadFile","upload");const r=await k(t);if(!r.success||!r.tempFilePaths)return s.end("chooseAndUploadFile"),[{success:!1,message:r.message||"选择文件失败"}];const a=r.tempFilePaths.map(t=>z(t,e,n)),o=await Promise.all(a);return s.end("chooseAndUploadFile"),o}const U=()=>{const e=i.getInstance();e.start("isWechat","system");const t=r(()=>{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},B=()=>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 s=r=>{const a=document.createElement("script");a.src=r,a.async=!0,a.onload=()=>{e(!0)},a.onerror=()=>{n++,n<t.length?(document.head.removeChild(a),s(t[n])):(document.head.removeChild(a),e(!1))},document.head.appendChild(a)};s(t[n]),e(!1)}),W=async e=>{const t=i.getInstance();t.start("configWechatJSSDK","wechat");try{if(!U())return!1;return!!await B()&&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")}},H=e=>{r(()=>{window.wx&&U()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},L=e=>{r(()=>{window.wx&&U()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class N{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return N.instance||(N.instance=new N),N.instance}async init(e){return this.config=e,this.isConfigured=await W(e),this.isConfigured}isReady(){return this.isConfigured&&U()}getConfig(){return this.config}setShareData(e){this.isReady()&&(H(e),L(e))}}exports.ErrorHandler=n,exports.PerformanceMonitor=i,exports.UniAppToolsError=t,exports.VERSION="2.0.0",exports.WechatSDK=N,exports.areaList=S,exports.batchGetStorage=function(e){const t=i.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=i.getInstance();n.start("batchSetStorage","localStorage");let s=0;return Object.entries(e).forEach(([e,n])=>{O(e,n,t)&&s++}),n.end("batchSetStorage"),s},exports.checkWechatJSAPI=e=>new Promise(t=>{window.wx&&U()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),exports.chooseAndUploadFile=j,exports.chooseAndUploadImage=async function(e,t={},n){return j(e,{...t,type:"image"},n)},exports.chooseFile=k,exports.chooseImage=async function(e={}){const t=await k({...e,type:"image"});return{success:t.success,tempFilePaths:t.tempFilePaths,tempFiles:t.tempFiles,message:t.message}},exports.cleanExpiredStorage=function(){return M.cleanExpired()},exports.clearStorageSync=function(e){return e?M.remove(e):M.clear()},exports.configWechatJSSDK=W,exports.copyText=async function(e,t={}){const n=i.getInstance();n.start("copyText","clipboard",{textLength:e.length});const r={...F,...t};if(!e||"string"!=typeof e)return r.showToast&&E("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return r.showToast&&E("复制内容过长",!1,"error"),n.end("copyText"),!1;const a=await s(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{r.showToast&&E(r.successMessage),t(!0)},fail:()=>{r.showToast&&E(r.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),a},exports.debounce=x,exports.deepClone=y,exports.deepMerge=function(e,t){const n=y(e);return function e(t,n){for(const s in n)if(n.hasOwnProperty(s)){const r=n[s],a=t[s];r&&"object"==typeof r&&!Array.isArray(r)&&a&&"object"==typeof a&&!Array.isArray(a)?e(a,r):t[s]=y(r)}}(n,t),n},exports.extractUrlParts=function(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:{}}}},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.getFileInfo=async function(e){return await s(()=>new Promise((t,n)=>{uni.getFileInfo({filePath:e,digestAlgorithm:"md5",success:e=>{const n=e;t({size:n.size,digest:n.digest})},fail:n})}),"upload","GET_FILE_INFO_ERROR")},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(s){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return e?null:{}}},exports.getMenuButtonBoundingClientRect=g,exports.getNavHeight=f,exports.getPageStack=function(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return[]}},exports.getPlatform=m,exports.getStatusBarHeight=h,exports.getStorage=async function(e,t){return await s(()=>new Promise(n=>{n(_(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t},exports.getStorageInfo=function(){return M.getInfo()},exports.getStorageSync=_,exports.getTopNavBarHeight=()=>{try{const e=h();return{statusBarHeight:e,navHeight:f()}}catch(e){return{statusBarHeight:0,navHeight:44}}},exports.initUniAppTools=async function(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 u}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},r)}},exports.isUploadSupported=function(){return"undefined"!=typeof uni&&"function"==typeof uni.chooseImage&&"function"==typeof uni.uploadFile},exports.isWechat=U,exports.loadWechatJSSDK=B,exports.measurePerformance=c,exports.mergeObjects=w,exports.navigateTo=R,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=C,exports.redirectTo=async function(e){return new Promise(t=>{const n=P(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})},exports.safeAsync=s,exports.safeNavigateTo=async function(e,t=3){for(let n=0;n<t;n++){if(await R(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1},exports.safeSync=r,exports.setPageIcon=(e,t="image/x-icon")=>r(()=>{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 s(()=>new Promise(s=>{s(O(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1},exports.setStorageSync=O,exports.shareToFriend=L,exports.shareToTimeline=H,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 s,r=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?(r&&(clearTimeout(r),r=null),a=c,s=e.apply(this,n)):!r&&i&&(r=setTimeout(()=>{a=o?Date.now():0,r=null,s=e.apply(this,n)},u)),s};return c.cancel=()=>{r&&(clearTimeout(r),r=null),a=0},c},exports.uploadFile=z,exports.useBack=v,exports.useBackDebounced=I,exports.useBackOrHome=async function(e="",t={}){const n=getCurrentPages(),s=t.delta||1;if(n.length>s)return await v(e,t);const r=t.homePage||"pages/index/index",a=r.startsWith("/")?r:`/${r}`;return await C({url:a,params:t.homeParams})},exports.useCascaderAreaData=T,exports.useDeepCopyByObj=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return w(e,y(t))}return y(t)},exports.useRegions=function(){return e.useCascaderAreaData()},exports.useToast=E,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=d,exports.weChatOfficialAccountPayment=(e,t,n)=>{const s=i.getInstance();return s.start("weChatOfficialAccountPayment","payment"),new Promise(a=>{r(()=>{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 r(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){s.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),a(!0)):(n?.(e),a(!1))})}catch(e){s.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),a(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",r,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",r),e.attachEvent("onWeixinJSBridgeReady",r))}else r();return!0},"payment","WECHAT_PAY_ERROR",!1)||(s.end("weChatOfficialAccountPayment"),a(!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 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 a=new n(t,s,e);return r&&(a.stack=r.stack),this.handleError(a,e),a}}}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 a(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 o=Object.freeze({__proto__:null,ErrorHandler:s,UniAppToolsError:n,safeAsync:r,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 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 a=c.getInstance(),o=`${t.constructor.name}.${n}`;a.start(o,e,{args:s.length});try{const e=r.apply(this,s);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 m{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return m.instance||(m.instance=new m),m.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 p=m.getInstance(),d=(e=!0)=>{const t=c.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=p.get(n);if(e)return t.end("getWindowInfo"),e}const s=a(()=>{const t=uni.getWindowInfo();return e&&p.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),s},h=()=>{const e="platform",t=p.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",p.set(e,"h5"),"h5"},f=()=>{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{return uni.getSystemInfoSync().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}}},T=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),P=(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 R(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 v(e,t){return Object.assign(e,t)}function x(e,t){const n=R(e);return function e(t,n){for(const s in n)if(n.hasOwnProperty(s)){const r=n[s],a=t[s];r&&"object"==typeof r&&!Array.isArray(r)&&a&&"object"==typeof a&&!Array.isArray(a)?e(a,r):t[s]=R(r)}}(n,t),n}function I(e,t,n=!1){let s,r=null;const a=function(...a){const o=n&&!r;return r&&clearTimeout(r),r=setTimeout(()=>{r=null,n||(s=e.apply(this,a))},t),o&&(s=e.apply(this,a)),s};return a.cancel=()=>{r&&(clearTimeout(r),r=null)},a}function F(e,t,n={}){let s,r=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?(r&&(clearTimeout(r),r=null),a=c,s=e.apply(this,n)):!r&&i&&(r=setTimeout(()=>{a=o?Date.now():0,r=null,s=e.apply(this,n)},u)),s};return c.cancel=()=>{r&&(clearTimeout(r),r=null),a=0},c}function C(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return v(e,R(t))}return R(t)}const A=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 _(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:{}}}}function M(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,b=t;function z(){return t()}const j=(e="",t=!1,n="none",s=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:s})};function D(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 k(e){return new Promise(t=>{const n=D(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 L(e){return new Promise(t=>{const n=D(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}async function U(e="",t={}){return new Promise(n=>{const s=t.delta||1,r=t.timeout||5e3;if(getCurrentPages().length<=s)return void n(!1);const a=setTimeout(()=>{n(!1)},r);uni.navigateBack({delta:s,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 W(e="",t={}){const n=getCurrentPages(),s=t.delta||1;if(n.length>s)return await U(e,t);const r=t.homePage||"pages/index/index",a=r.startsWith("/")?r:`/${r}`;return await $({url:a,params:t.homeParams})}const B=I(U,300);async function N(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:e=>{t(!1)}})})}async function $(e){return new Promise(t=>{const n=D(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}function H(){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 k(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 s={...G,...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 a=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"),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 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=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 r(()=>new Promise(s=>{s(X(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1}async function te(e,t){return await r(()=>new Promise(n=>{n(Q(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t}function ne(){return V.getInfo()}function se(){return V.cleanExpired()}function re(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 ae(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=Q(e)}),t.end("batchGetStorage"),n}const oe={name:"file",maxSize:10,allowedTypes:["jpg","jpeg","png","gif","webp"],showToast:!0,timeout:6e4,successMessage:"上传成功",failMessage:"上传失败"},ie={type:"image",count:1,sizeType:["original","compressed"],sourceType:["album","camera"],extension:[],maxSize:10,showToast:!0,failMessage:"选择文件失败"};async function ce(e={}){const t=c.getInstance();t.start("chooseFile","upload",{count:e.count,type:e.type});const n={...ie,...e};let s=n.type;var a;("messagefile"===(a=s)?"function"==typeof uni.chooseMessageFile:"local"===a||"image"===a)||(s="image");const o=await r(()=>new Promise(e=>{const t=t=>{const r=t.errMsg||n.failMessage;n.showToast&&j(r,!1,"error"),e({success:!1,message:r,type:s})};"image"!==s&&"local"!==s?"messagefile"===s?uni.chooseMessageFile({count:n.count,type:"all",success:t=>{e({success:!0,tempFilePaths:t.tempFiles.map(e=>e.path),tempFiles:t.tempFiles,type:"messagefile"})},fail:t}):"image"===s?uni.chooseImage({count:n.count,sizeType:n.sizeType,sourceType:n.sourceType,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"image"})},fail:t}):"local"===s&&("function"==typeof uni.chooseFile?uni.chooseFile({count:n.count,extension:n.extension,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"local"})},fail:t}):e({success:!1,message:"当前平台不支持选择本地文件",type:s})):function(e,t){const n=document.createElement("input");n.type="file",n.multiple=e.count>1,"image"===e.type?n.accept="image/*":e.extension.length>0&&(n.accept=e.extension.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),n.onchange=s=>{const r=s.target.files;if(r&&r.length>0){const n=Array.from(r).map(e=>({path:URL.createObjectURL(e),size:e.size,name:e.name,type:e.type,file:e})),s=n.map(e=>({path:e.path,size:e.size}));t({success:!0,tempFilePaths:n.map(e=>e.path),tempFiles:s,type:e.type})}else t({success:!1,message:"用户取消选择",type:e.type});document.body.removeChild(n)},n.style.display="none",document.body.appendChild(n),n.click()}(n,e)}).then(e=>{if(!e.success||!e.tempFiles||!n.maxSize)return e;if(e.tempFiles.filter(e=>{var t,s;return!(t=e.size,(s=n.maxSize)&&t>1024*s*1024?{valid:!1,message:`文件大小不能超过 ${s}MB`}:{valid:!0}).valid}).length>0){const t=`部分文件大小超过 ${n.maxSize}MB 限制`;return n.showToast&&j(t,!1,"error"),{...e,success:!1,message:t}}return e}),"upload","CHOOSE_FILE_ERROR");return t.end("chooseFile"),o||{success:!1,message:"选择文件失败",type:s}}async function ue(e={}){const t=await ce({...e,type:"image"});return{success:t.success,tempFilePaths:t.tempFilePaths,tempFiles:t.tempFiles,message:t.message}}async function le(e,t,n){const s=c.getInstance();s.start("uploadFile","upload",{filePath:e});const a={...oe,...t};if(!a.url){const e="上传地址不能为空";return a.showToast&&j(e,!1,"error"),s.end("uploadFile"),{success:!1,message:e}}const o=function(e,t){if(!e)return{valid:!1,message:"文件路径不能为空"};if(t.allowedTypes&&t.allowedTypes.length>0){const n=e.split(".").pop()?.toLowerCase();if(!n||!t.allowedTypes.includes(n))return{valid:!1,message:`不支持的文件类型,仅支持:${t.allowedTypes.join(", ")}`}}return{valid:!0}}(e,a);if(!o.valid)return a.showToast&&j(o.message,!1,"error"),s.end("uploadFile"),{success:!1,message:o.message};const i=await r(()=>new Promise(t=>{const s=uni.uploadFile({url:a.url,filePath:e,name:a.name,formData:a.formData,header:a.header,timeout:a.timeout,success:n=>{let s;try{s=JSON.parse(n.data)}catch{s=n.data}if(200===n.statusCode)a.showToast&&j(a.successMessage,!1,"success"),t({success:!0,data:s,tempFilePath:e,statusCode:n.statusCode});else{const e=`上传失败,状态码:${n.statusCode}`;a.showToast&&j(e,!1,"error"),t({success:!1,message:e,statusCode:n.statusCode})}},fail:n=>{const s=n.errMsg||a.failMessage;a.showToast&&j(s,!1,"error"),t({success:!1,message:s,tempFilePath:e})}});n&&s&&s.onProgressUpdate(e=>{n({progress:e.progress,totalBytesSent:e.totalBytesSent,totalBytesExpectedToSend:e.totalBytesExpectedToSend})})}),"upload","UPLOAD_FILE_ERROR");return s.end("uploadFile"),i||{success:!1,message:"上传文件失败"}}async function me(e,t={},n){const s=c.getInstance();s.start("chooseAndUploadFile","upload");const r=await ce(t);if(!r.success||!r.tempFilePaths)return s.end("chooseAndUploadFile"),[{success:!1,message:r.message||"选择文件失败"}];const a=r.tempFilePaths.map(t=>le(t,e,n)),o=await Promise.all(a);return s.end("chooseAndUploadFile"),o}async function pe(e,t={},n){return me(e,{...t,type:"image"},n)}function de(){return"undefined"!=typeof uni&&"function"==typeof uni.chooseImage&&"function"==typeof uni.uploadFile}async function he(e){return await r(()=>new Promise((t,n)=>{uni.getFileInfo({filePath:e,digestAlgorithm:"md5",success:e=>{const n=e;t({size:n.size,digest:n.digest})},fail:n})}),"upload","GET_FILE_INFO_ERROR")}const fe=(e,t,n)=>{const s=c.getInstance();return s.start("weChatOfficialAccountPayment","payment"),new Promise(r=>{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){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",a,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",a),e.attachEvent("onWeixinJSBridgeReady",a))}else a();return!0},"payment","WECHAT_PAY_ERROR",!1)||(s.end("weChatOfficialAccountPayment"),r(!1))})},ge=()=>{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},we=()=>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 s=r=>{const a=document.createElement("script");a.src=r,a.async=!0,a.onload=()=>{e(!0)},a.onerror=()=>{n++,n<t.length?(document.head.removeChild(a),s(t[n])):(document.head.removeChild(a),e(!1))},document.head.appendChild(a)};s(t[n]),e(!1)}),ye=async e=>{const t=c.getInstance();t.start("configWechatJSSDK","wechat");try{if(!ge())return!1;return!!await we()&&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")}},Se=e=>new Promise(t=>{window.wx&&ge()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),Ee=e=>{a(()=>{window.wx&&ge()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},Te=e=>{a(()=>{window.wx&&ge()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class Pe{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return Pe.instance||(Pe.instance=new Pe),Pe.instance}async init(e){return this.config=e,this.isConfigured=await ye(e),this.isConfigured}isReady(){return this.isConfigured&&ge()}getConfig(){return this.config}setShareData(e){this.isReady()&&(Ee(e),Te(e))}}const Re="1.0.8";async function ve(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 o}),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,Re as VERSION,Pe as WechatSDK,O as areaList,ae as batchGetStorage,re as batchSetStorage,Se as checkWechatJSAPI,me as chooseAndUploadFile,pe as chooseAndUploadImage,ce as chooseFile,ue as chooseImage,se as cleanExpiredStorage,Z as clearStorageSync,ye as configWechatJSSDK,Y as copyText,I as debounce,R as deepClone,x as deepMerge,_ as extractUrlParts,f as getCurrentEnv,H as getCurrentPageInfo,he as getFileInfo,A 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,ve as initUniAppTools,de as isUploadSupported,ge as isWechat,we as loadWechatJSSDK,u as measurePerformance,v as mergeObjects,k as navigateTo,g as onCheckForUpdate,$ as reLaunch,L as redirectTo,r as safeAsync,q as safeNavigateTo,a as safeSync,P as setPageIcon,T as setPageTitle,ee as setStorage,X as setStorageSync,Te as shareToFriend,Ee as shareToTimeline,N as switchTab,F as throttle,le as uploadFile,U as useBack,B as useBackDebounced,W as useBackOrHome,b as useCascaderAreaData,C as useDeepCopyByObj,z as useRegions,j as useToast,M as useTryCatch,d as useWindowInfo,fe 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 a=new n(t,s,e);return r&&(a.stack=r.stack),this.handleError(a,e),a}}}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 a(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 o=Object.freeze({__proto__:null,ErrorHandler:s,UniAppToolsError:n,safeAsync:r,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 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 a=c.getInstance(),o=`${t.constructor.name}.${n}`;a.start(o,e,{args:s.length});try{const e=r.apply(this,s);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 m{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return m.instance||(m.instance=new m),m.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 p=m.getInstance(),d=(e=!0)=>{const t=c.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=p.get(n);if(e)return t.end("getWindowInfo"),e}const s=a(()=>{const t=uni.getWindowInfo();return e&&p.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),s},h=()=>{const e="platform",t=p.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",p.set(e,"h5"),"h5"},f=()=>{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=d();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}}},T=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),P=(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 R(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 v(e,t){return Object.assign(e,t)}function x(e,t){const n=R(e);return function e(t,n){for(const s in n)if(n.hasOwnProperty(s)){const r=n[s],a=t[s];r&&"object"==typeof r&&!Array.isArray(r)&&a&&"object"==typeof a&&!Array.isArray(a)?e(a,r):t[s]=R(r)}}(n,t),n}function I(e,t,n=!1){let s,r=null;const a=function(...a){const o=n&&!r;return r&&clearTimeout(r),r=setTimeout(()=>{r=null,n||(s=e.apply(this,a))},t),o&&(s=e.apply(this,a)),s};return a.cancel=()=>{r&&(clearTimeout(r),r=null)},a}function F(e,t,n={}){let s,r=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?(r&&(clearTimeout(r),r=null),a=c,s=e.apply(this,n)):!r&&i&&(r=setTimeout(()=>{a=o?Date.now():0,r=null,s=e.apply(this,n)},u)),s};return c.cancel=()=>{r&&(clearTimeout(r),r=null),a=0},c}function C(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return v(e,R(t))}return R(t)}const A=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 _(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:{}}}}function M(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,b=t;function z(){return t()}const j=(e="",t=!1,n="none",s=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:s})};function D(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 k(e){return new Promise(t=>{const n=D(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 L(e){return new Promise(t=>{const n=D(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}async function U(e="",t={}){return new Promise(n=>{const s=t.delta||1,r=t.timeout||5e3;if(getCurrentPages().length<=s)return void n(!1);const a=setTimeout(()=>{n(!1)},r);uni.navigateBack({delta:s,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 W(e="",t={}){const n=getCurrentPages(),s=t.delta||1;if(n.length>s)return await U(e,t);const r=t.homePage||"pages/index/index",a=r.startsWith("/")?r:`/${r}`;return await $({url:a,params:t.homeParams})}const B=I(U,300);async function N(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:e=>{t(!1)}})})}async function $(e){return new Promise(t=>{const n=D(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}function H(){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 k(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 s={...G,...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 a=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"),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 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=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 r(()=>new Promise(s=>{s(X(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1}async function te(e,t){return await r(()=>new Promise(n=>{n(Q(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t}function ne(){return V.getInfo()}function se(){return V.cleanExpired()}function re(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 ae(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=Q(e)}),t.end("batchGetStorage"),n}const oe={name:"file",maxSize:10,allowedTypes:["jpg","jpeg","png","gif","webp"],showToast:!0,timeout:6e4,successMessage:"上传成功",failMessage:"上传失败"},ie={type:"image",count:1,sizeType:["original","compressed"],sourceType:["album","camera"],extension:[],maxSize:10,showToast:!0,failMessage:"选择文件失败"};async function ce(e={}){const t=c.getInstance();t.start("chooseFile","upload",{count:e.count,type:e.type});const n={...ie,...e};let s=n.type;var a;("messagefile"===(a=s)?"function"==typeof uni.chooseMessageFile:"local"===a||"image"===a)||(s="image");const o=await r(()=>new Promise(e=>{const t=t=>{const r=t.errMsg||n.failMessage;n.showToast&&j(r,!1,"error"),e({success:!1,message:r,type:s})};"image"!==s&&"local"!==s?"messagefile"===s?uni.chooseMessageFile({count:n.count,type:"all",success:t=>{e({success:!0,tempFilePaths:t.tempFiles.map(e=>e.path),tempFiles:t.tempFiles,type:"messagefile"})},fail:t}):"image"===s?uni.chooseImage({count:n.count,sizeType:n.sizeType,sourceType:n.sourceType,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"image"})},fail:t}):"local"===s&&("function"==typeof uni.chooseFile?uni.chooseFile({count:n.count,extension:n.extension,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"local"})},fail:t}):e({success:!1,message:"当前平台不支持选择本地文件",type:s})):function(e,t){const n=document.createElement("input");n.type="file",n.multiple=e.count>1,"image"===e.type?n.accept="image/*":e.extension.length>0&&(n.accept=e.extension.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),n.onchange=s=>{const r=s.target.files;if(r&&r.length>0){const n=Array.from(r).map(e=>({path:URL.createObjectURL(e),size:e.size,name:e.name,type:e.type,file:e})),s=n.map(e=>({path:e.path,size:e.size}));t({success:!0,tempFilePaths:n.map(e=>e.path),tempFiles:s,type:e.type})}else t({success:!1,message:"用户取消选择",type:e.type});document.body.removeChild(n)},n.style.display="none",document.body.appendChild(n),n.click()}(n,e)}).then(e=>{if(!e.success||!e.tempFiles||!n.maxSize)return e;if(e.tempFiles.filter(e=>{var t,s;return!(t=e.size,(s=n.maxSize)&&t>1024*s*1024?{valid:!1,message:`文件大小不能超过 ${s}MB`}:{valid:!0}).valid}).length>0){const t=`部分文件大小超过 ${n.maxSize}MB 限制`;return n.showToast&&j(t,!1,"error"),{...e,success:!1,message:t}}return e}),"upload","CHOOSE_FILE_ERROR");return t.end("chooseFile"),o||{success:!1,message:"选择文件失败",type:s}}async function ue(e={}){const t=await ce({...e,type:"image"});return{success:t.success,tempFilePaths:t.tempFilePaths,tempFiles:t.tempFiles,message:t.message}}async function le(e,t,n){const s=c.getInstance();s.start("uploadFile","upload",{filePath:e});const a={...oe,...t};if(!a.url){const e="上传地址不能为空";return a.showToast&&j(e,!1,"error"),s.end("uploadFile"),{success:!1,message:e}}const o=function(e,t){if(!e)return{valid:!1,message:"文件路径不能为空"};if(t.allowedTypes&&t.allowedTypes.length>0){const n=e.split(".").pop()?.toLowerCase();if(!n||!t.allowedTypes.includes(n))return{valid:!1,message:`不支持的文件类型,仅支持:${t.allowedTypes.join(", ")}`}}return{valid:!0}}(e,a);if(!o.valid)return a.showToast&&j(o.message,!1,"error"),s.end("uploadFile"),{success:!1,message:o.message};const i=await r(()=>new Promise(t=>{const s=uni.uploadFile({url:a.url,filePath:e,name:a.name,formData:a.formData,header:a.header,timeout:a.timeout,success:n=>{let s;try{s=JSON.parse(n.data)}catch{s=n.data}if(200===n.statusCode)a.showToast&&j(a.successMessage,!1,"success"),t({success:!0,data:s,tempFilePath:e,statusCode:n.statusCode});else{const e=`上传失败,状态码:${n.statusCode}`;a.showToast&&j(e,!1,"error"),t({success:!1,message:e,statusCode:n.statusCode})}},fail:n=>{const s=n.errMsg||a.failMessage;a.showToast&&j(s,!1,"error"),t({success:!1,message:s,tempFilePath:e})}});n&&s&&s.onProgressUpdate(e=>{n({progress:e.progress,totalBytesSent:e.totalBytesSent,totalBytesExpectedToSend:e.totalBytesExpectedToSend})})}),"upload","UPLOAD_FILE_ERROR");return s.end("uploadFile"),i||{success:!1,message:"上传文件失败"}}async function me(e,t={},n){const s=c.getInstance();s.start("chooseAndUploadFile","upload");const r=await ce(t);if(!r.success||!r.tempFilePaths)return s.end("chooseAndUploadFile"),[{success:!1,message:r.message||"选择文件失败"}];const a=r.tempFilePaths.map(t=>le(t,e,n)),o=await Promise.all(a);return s.end("chooseAndUploadFile"),o}async function pe(e,t={},n){return me(e,{...t,type:"image"},n)}function de(){return"undefined"!=typeof uni&&"function"==typeof uni.chooseImage&&"function"==typeof uni.uploadFile}async function he(e){return await r(()=>new Promise((t,n)=>{uni.getFileInfo({filePath:e,digestAlgorithm:"md5",success:e=>{const n=e;t({size:n.size,digest:n.digest})},fail:n})}),"upload","GET_FILE_INFO_ERROR")}const fe=(e,t,n)=>{const s=c.getInstance();return s.start("weChatOfficialAccountPayment","payment"),new Promise(r=>{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){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",a,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",a),e.attachEvent("onWeixinJSBridgeReady",a))}else a();return!0},"payment","WECHAT_PAY_ERROR",!1)||(s.end("weChatOfficialAccountPayment"),r(!1))})},ge=()=>{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},we=()=>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 s=r=>{const a=document.createElement("script");a.src=r,a.async=!0,a.onload=()=>{e(!0)},a.onerror=()=>{n++,n<t.length?(document.head.removeChild(a),s(t[n])):(document.head.removeChild(a),e(!1))},document.head.appendChild(a)};s(t[n]),e(!1)}),ye=async e=>{const t=c.getInstance();t.start("configWechatJSSDK","wechat");try{if(!ge())return!1;return!!await we()&&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")}},Se=e=>new Promise(t=>{window.wx&&ge()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),Ee=e=>{a(()=>{window.wx&&ge()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},Te=e=>{a(()=>{window.wx&&ge()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class Pe{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return Pe.instance||(Pe.instance=new Pe),Pe.instance}async init(e){return this.config=e,this.isConfigured=await ye(e),this.isConfigured}isReady(){return this.isConfigured&&ge()}getConfig(){return this.config}setShareData(e){this.isReady()&&(Ee(e),Te(e))}}const Re="2.0.0";async function ve(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 o}),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,Re as VERSION,Pe as WechatSDK,O as areaList,ae as batchGetStorage,re as batchSetStorage,Se as checkWechatJSAPI,me as chooseAndUploadFile,pe as chooseAndUploadImage,ce as chooseFile,ue as chooseImage,se as cleanExpiredStorage,Z as clearStorageSync,ye as configWechatJSSDK,Y as copyText,I as debounce,R as deepClone,x as deepMerge,_ as extractUrlParts,f as getCurrentEnv,H as getCurrentPageInfo,he as getFileInfo,A 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,ve as initUniAppTools,de as isUploadSupported,ge as isWechat,we as loadWechatJSSDK,u as measurePerformance,v as mergeObjects,k as navigateTo,g as onCheckForUpdate,$ as reLaunch,L as redirectTo,r as safeAsync,q as safeNavigateTo,a as safeSync,P as setPageIcon,T as setPageTitle,ee as setStorage,X as setStorageSync,Te as shareToFriend,Ee as shareToTimeline,N as switchTab,F as throttle,le as uploadFile,U as useBack,B as useBackDebounced,W as useBackOrHome,b as useCascaderAreaData,C as useDeepCopyByObj,z as useRegions,j as useToast,M as useTryCatch,d as useWindowInfo,fe as weChatOfficialAccountPayment};
@@ -48,7 +48,7 @@ export declare const onCheckForUpdate: () => void;
48
48
  * @returns 状态栏高度(单位:px)
49
49
  * @description 获取设备状态栏的高度,用于适配不同设备的状态栏
50
50
  */
51
- export declare const getStatusBarHeight: () => number;
51
+ export declare const getStatusBarHeight: () => any;
52
52
  /**
53
53
  * 获取菜单按钮边界信息
54
54
  * @returns 菜单按钮边界信息对象或null
@@ -60,14 +60,14 @@ export declare const getMenuButtonBoundingClientRect: () => UniApp.GetMenuButton
60
60
  * @returns 导航栏高度(单位:px)
61
61
  * @description 获取导航栏的总高度,根据不同平台采用不同的计算方式
62
62
  */
63
- export declare const getNavHeight: () => number;
63
+ export declare const getNavHeight: () => any;
64
64
  /**
65
65
  * @returns 包含状态栏高度和导航栏高度的配置对象
66
66
  * @description 一次性获取应用所需的状态栏和导航栏高度配置信息
67
67
  */
68
68
  export declare const getTopNavBarHeight: () => {
69
- statusBarHeight: number;
70
- navHeight: number;
69
+ statusBarHeight: any;
70
+ navHeight: any;
71
71
  };
72
72
  /**
73
73
  * 修改页面标题
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-uniapp-tools",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "type": "module",
5
5
  "description": "一个功能强大、性能优化的 uni-app 开发工具库,提供剪贴板、本地存储、导航、系统信息等常用功能",
6
6
  "main": "dist/my-uniapp-tools.cjs.js",