my-uniapp-tools 2.0.1 → 3.0.0

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.
@@ -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(),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
+ "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 p=l.getInstance(),f=(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 r=s(()=>{const t=uni.getWindowInfo();return e&&p.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),r},d=()=>{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"},m=()=>{try{const e=f();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 R(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=x(R,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 A={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};class M{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return M.instance||(M.instance=new M),M.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=M.getInstance();function _(e,t,n={}){return b.set(e,t,n)}function O(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,fieldName:s="file",formData:o,headers:a,maxUploadFileSizeMB:c,showToast:i=!0,successMessage:u="上传成功",failMessage:l="上传失败",onProgress:p,beforeUpload:f}=t;if("function"==typeof f){if(!await Promise.resolve(f(e)))return{file:e,success:!1,message:"已取消上传"}}if(!r){const t="上传地址不能为空";return i&&v(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const d=D(e.size,c);if(!d.valid)return i&&d.message&&v(d.message,!1,"error"),Promise.resolve({file:e,success:!1,message:d.message});const m="undefined"==typeof uni?null:uni;if(!m||"function"!=typeof m.uploadFile){const t="当前环境不支持文件上传";return i&&v(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{const c=m.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)i&&1===n&&v(u,!1,"success"),t({file:e,success:!0,statusCode:o,data:s});else{const n=`上传失败,状态码:${o}`;i&&v(n,!1,"error"),t({file:e,success:!1,statusCode:o,data:s,message:n})}},fail:n=>{const r=n?.errMsg||l;i&&v(r,!1,"error"),t({file:e,success:!1,message:r})}});p&&c&&"function"==typeof c.onProgressUpdate&&c.onProgressUpdate(t=>{p(e,t.progress)})})}async function z(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 N=()=>{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},$=()=>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)}),F=async e=>{const t=c.getInstance();t.start("configWechatJSSDK","wechat");try{if(!N())return!1;return!!await $()&&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=>{s(()=>{window.wx&&N()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},L=e=>{s(()=>{window.wx&&N()&&(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 F(e),this.isConfigured}isReady(){return this.isConfigured&&N()}getConfig(){return this.config}setShareData(e){this.isReady()&&(H(e),L(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]=O(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])=>{_(e,n,t)&&r++}),n.end("batchSetStorage"),r},exports.checkWechatJSAPI=e=>new Promise(t=>{window.wx&&N()?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=F,exports.copyText=async function(e,t={}){const n=c.getInstance();n.start("copyText","clipboard",{textLength:e.length});const s={...A,...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(O(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t},exports.getStorageInfo=function(){return b.getInfo()},exports.getStorageSync=O,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=N,exports.loadWechatJSSDK=$,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=z,exports.selectAndUploadImage=async function(e){return z({...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(_(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1},exports.setStorageSync=_,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 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=R,exports.useBackDebounced=C,exports.useBackOrHome=async function(e="",t={}){const n=getCurrentPages(),r=t.delta||1;if(n.length>r)return await R(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=f,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 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};
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 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 r=a(()=>{const t=uni.getWindowInfo();return e&&m.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),r},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){}},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}}},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 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 T(e,t){return Object.assign(e,t)}function P(e,t){const n=R(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]=R(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 I(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 M(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return T(e,R(t))}return R(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 A(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 b(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 z(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){return new Promise(t=>{const n=z(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 W(e){return new Promise(t=>{const n=z(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}async function F(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 U(e="",t={}){const n=getCurrentPages(),r=t.delta||1;if(n.length>r)return await F(e,t);const s=t.homePage||"pages/index/index",a=s.startsWith("/")?s:`/${s}`;return await B({url:a,params:t.homeParams})}const N=C(F,300);async function L(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=z(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 $(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,fieldName:s="file",formData:a,headers:o,maxUploadFileSizeMB:i,showToast:c=!0,successMessage:u="上传成功",failMessage:l="上传失败",onProgress:f,beforeUpload:m}=t;if("function"==typeof m){if(!await Promise.resolve(m(e)))return{file:e,success:!1,message:"已取消上传"}}if(!r){const t="上传地址不能为空";return c&&j(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const d=oe(e.size,i);if(!d.valid)return c&&d.message&&j(d.message,!1,"error"),Promise.resolve({file:e,success:!1,message:d.message});const h="undefined"==typeof uni?null:uni;if(!h||"function"!=typeof h.uploadFile){const t="当前环境不支持文件上传";return c&&j(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{const i=h.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)c&&1===n&&j(u,!1,"success"),t({file:e,success:!0,statusCode:a,data:s});else{const n=`上传失败,状态码:${a}`;c&&j(n,!1,"error"),t({file:e,success:!1,statusCode:a,data:s,message:n})}},fail:n=>{const r=n?.errMsg||l;c&&j(r,!1,"error"),t({file:e,success:!1,message:r})}});f&&i&&"function"==typeof i.onProgressUpdate&&i.onProgressUpdate(t=>{f(e,t.progress)})})}async function me(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 de(e){return me({...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 Re(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,R as deepClone,P as deepMerge,A as extractUrlParts,p as getCurrentEnv,H 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,Re as initUniAppTools,pe as isWechat,ge as loadWechatJSSDK,u as measurePerformance,T as mergeObjects,$ as navigateTo,g as onCheckForUpdate,B as reLaunch,W as redirectTo,s as safeAsync,q as safeNavigateTo,a as safeSync,me as selectAndUpload,de as selectAndUploadImage,x as setPageIcon,v as setPageTitle,ee as setStorage,X as setStorageSync,Ee as shareToFriend,Se as shareToTimeline,L as switchTab,I as throttle,F as useBack,N as useBackDebounced,U as useBackOrHome,k as useCascaderAreaData,M as useDeepCopyByObj,D as useRegions,j as useToast,b as useTryCatch,d as useWindowInfo,he as weChatOfficialAccountPayment};
@@ -1,153 +1,94 @@
1
1
  /**
2
- * 文件上传相关工具函数
3
- * 支持微信小程序、支付宝小程序、H5多端兼容
2
+ * 多端文件上传工具(全新实现)
3
+ * 核心入口:selectAndUpload 一步完成“选择 + 上传”业务流程
4
+ * 支持 H5、微信小程序、App 等 uni-app 运行环境
4
5
  */
5
6
  /**
6
- * 上传配置接口
7
+ * 单个文件的统一描述结构
8
+ * 将各平台返回值规整成统一的 UniFile,方便业务使用
7
9
  */
8
- export interface UploadConfig {
9
- /** 上传服务器地址 */
10
- url: string;
11
- /** 文件对应的 key,开发者在服务端可以通过这个 key 获取文件的二进制内容 */
12
- name?: string;
13
- /** HTTP 请求中其他额外的 form data */
14
- formData?: Record<string, any>;
15
- /** HTTP 请求 Header,Header 中不能设置 Referer */
16
- header?: Record<string, string>;
17
- /** 文件大小限制(MB) */
18
- maxSize?: number;
19
- /** 允许的文件类型 */
20
- allowedTypes?: string[];
21
- /** 是否显示提示信息 */
22
- showToast?: boolean;
23
- /** 超时时间(ms) */
24
- timeout?: number;
25
- /** 成功提示信息 */
26
- successMessage?: string;
27
- /** 失败提示信息 */
28
- failMessage?: string;
10
+ export interface UniFile {
11
+ /** 文件唯一标识(由本工具生成) */
12
+ id: string;
13
+ /** 文件名 */
14
+ name: string;
15
+ /** 文件大小(字节) */
16
+ size: number;
17
+ /** 本地临时路径 / H5 对象 URL */
18
+ path: string;
19
+ /** MIME 类型(如果可用) */
20
+ mimeType?: string;
21
+ /** 文件扩展名(不带点,例如:jpg、png) */
22
+ ext?: string;
23
+ /** 文件来源(相册、相机、本地文件等) */
24
+ source?: 'camera' | 'album' | 'file' | 'chat' | 'unknown';
25
+ /** 运行平台(仅作标记使用) */
26
+ platform?: 'weixin' | 'alipay' | 'h5' | 'app' | 'unknown';
27
+ /** 平台原始返回对象,保留以备高级用法 */
28
+ raw?: unknown;
29
29
  }
30
30
  /**
31
- * 文件选择类型
32
- */
33
- export type FileSelectType = 'image' | 'messagefile' | 'local';
34
- /**
35
- * 选择文件配置接口
31
+ * 选择 + 上传 一体化配置
36
32
  */
37
- export interface ChooseFileConfig {
38
- /** 文件选择类型 */
39
- type?: FileSelectType;
33
+ export interface SelectAndUploadOptions {
34
+ /** 上传服务器地址 */
35
+ url: string;
36
+ /** 选择的文件类型 */
37
+ type?: 'image' | 'file' | 'any';
40
38
  /** 最多可以选择的文件数量 */
41
39
  count?: number;
42
- /** 所选的图片的尺寸(仅image类型有效) */
43
- sizeType?: ('original' | 'compressed')[];
44
- /** 选择图片的来源(仅image类型有效) */
45
- sourceType?: ('album' | 'camera')[];
46
- /** 文件类型限制(仅local类型有效) */
47
- extension?: string[];
48
- /** 文件大小限制(MB) */
49
- maxSize?: number;
50
- /** 是否显示提示信息 */
40
+ /** 选择阶段:单个文件允许的最大体积(MB),超出则认为选择失败 */
41
+ maxSelectFileSizeMB?: number;
42
+ /** 上传阶段:单个文件允许的最大体积(MB),超出则不会发起上传请求 */
43
+ maxUploadFileSizeMB?: number;
44
+ /** 允许的文件扩展名(不带点,例如:['jpg','png']) */
45
+ extensions?: string[];
46
+ /** 表单字段名,后端通过此字段接收文件 */
47
+ fieldName?: string;
48
+ /** 额外的表单字段 */
49
+ formData?: Record<string, string | number>;
50
+ /** HTTP 请求头 */
51
+ headers?: Record<string, string>;
52
+ /** 单次最大并发上传数量(默认与文件数相同,即全部并行) */
53
+ concurrency?: number;
54
+ /**
55
+ * 上传前拦截钩子
56
+ * 返回 false 或 Promise<false> 将跳过该文件的上传,并在结果中标记为失败(不弹 toast)
57
+ */
58
+ beforeUpload?: (file: UniFile) => boolean | Promise<boolean>;
59
+ /** 是否显示 toast 提示,默认 true */
51
60
  showToast?: boolean;
52
- /** 失败提示信息 */
61
+ /** 上传成功的提示信息(仅单文件上传时生效) */
62
+ successMessage?: string;
63
+ /** 上传失败的默认提示信息 */
53
64
  failMessage?: string;
65
+ /** 上传进度回调 */
66
+ onProgress?: (file: UniFile, progress: number) => void;
54
67
  }
55
68
  /**
56
- * 选择图片配置接口(向后兼容)
57
- */
58
- export interface ChooseImageConfig extends Omit<ChooseFileConfig, 'type' | 'extension'> {
59
- }
60
- /**
61
- * 上传结果接口
69
+ * 单个文件的上传结果
62
70
  */
63
71
  export interface UploadResult {
64
- /** 是否成功 */
72
+ /** 对应的文件,选择阶段失败时为 null */
73
+ file: UniFile | null;
74
+ /** 是否上传成功 */
65
75
  success: boolean;
66
- /** 服务器返回的数据 */
67
- data?: any;
68
- /** 提示信息 */
69
- message?: string;
70
- /** 本地临时文件路径 */
71
- tempFilePath?: string;
72
- /** HTTP 状态码 */
76
+ /** HTTP 状态码(如果有) */
73
77
  statusCode?: number;
74
- }
75
- /**
76
- * 选择文件结果接口
77
- */
78
- export interface ChooseFileResult {
79
- /** 是否成功 */
80
- success: boolean;
81
- /** 临时文件路径数组 */
82
- tempFilePaths?: string[];
83
- /** 临时文件对象数组 */
84
- tempFiles?: Array<{
85
- path: string;
86
- size: number;
87
- }>;
78
+ /** 服务器返回的数据(成功或失败时的响应体) */
79
+ data?: unknown;
88
80
  /** 提示信息 */
89
81
  message?: string;
90
- /** 文件选择类型 */
91
- type: FileSelectType;
92
82
  }
93
83
  /**
94
- * 选择图片结果接口(向后兼容)
84
+ * 选择并上传文件(业务一体化入口)
85
+ * @param options 选择与上传配置
86
+ * @returns 每个文件对应的上传结果列表
95
87
  */
96
- export interface ChooseImageResult extends Omit<ChooseFileResult, 'type'> {
97
- }
88
+ export declare function selectAndUpload(options: SelectAndUploadOptions): Promise<UploadResult[]>;
98
89
  /**
99
- * 上传进度回调函数类型
90
+ * 选择并上传图片的便捷方法
91
+ * 等价于在 selectAndUpload 中指定 type: 'image'
92
+ * @param options 业务配置
100
93
  */
101
- export type ProgressCallback = (progress: {
102
- /** 上传进度百分比 */
103
- progress: number;
104
- /** 已经上传的数据长度 */
105
- totalBytesSent: number;
106
- /** 预期需要上传的数据总长度 */
107
- totalBytesExpectedToSend: number;
108
- }) => void;
109
- export declare function chooseFile(config?: ChooseFileConfig): Promise<ChooseFileResult>;
110
- /**
111
- * 选择图片(向后兼容)
112
- * @param config 选择配置
113
- * @returns Promise<ChooseImageResult> 选择结果
114
- */
115
- export declare function chooseImage(config?: ChooseImageConfig): Promise<ChooseImageResult>;
116
- /**
117
- * 上传文件
118
- * @param filePath 文件路径
119
- * @param config 上传配置
120
- * @param onProgress 进度回调
121
- * @returns Promise<UploadResult> 上传结果
122
- */
123
- export declare function uploadFile(filePath: string, config: UploadConfig, onProgress?: ProgressCallback): Promise<UploadResult>;
124
- /**
125
- * 选择并上传文件(一体化功能)
126
- * @param config 上传配置
127
- * @param chooseConfig 选择文件配置
128
- * @param onProgress 进度回调
129
- * @returns Promise<UploadResult[]> 上传结果数组
130
- */
131
- export declare function chooseAndUploadFile(config: UploadConfig, chooseConfig?: ChooseFileConfig, onProgress?: ProgressCallback): Promise<UploadResult[]>;
132
- /**
133
- * 选择并上传图片(向后兼容)
134
- * @param config 上传配置
135
- * @param chooseConfig 选择图片配置
136
- * @param onProgress 进度回调
137
- * @returns Promise<UploadResult[]> 上传结果数组
138
- */
139
- export declare function chooseAndUploadImage(config: UploadConfig, chooseConfig?: ChooseImageConfig, onProgress?: ProgressCallback): Promise<UploadResult[]>;
140
- /**
141
- * 检查是否支持文件上传
142
- * @returns boolean 是否支持
143
- */
144
- export declare function isUploadSupported(): boolean;
145
- /**
146
- * 获取文件信息
147
- * @param filePath 文件路径
148
- * @returns Promise<{size: number, type?: string}> 文件信息
149
- */
150
- export declare function getFileInfo(filePath: string): Promise<{
151
- size: number;
152
- digest?: string;
153
- } | null>;
94
+ export declare function selectAndUploadImage(options: Omit<SelectAndUploadOptions, 'type'>): Promise<UploadResult[]>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-uniapp-tools",
3
- "version": "2.0.1",
3
+ "version": "3.0.0",
4
4
  "type": "module",
5
5
  "description": "一个功能强大、性能优化的 uni-app 开发工具库,提供剪贴板、本地存储、导航、系统信息等常用功能",
6
6
  "main": "dist/my-uniapp-tools.cjs.js",