my-uniapp-tools
Version:
一个功能强大、性能优化的 uni-app 开发工具库,提供剪贴板、本地存储、导航、系统信息等常用功能
2 lines (1 loc) • 25.5 kB
JavaScript
class e 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 t{static instance;errorCallbacks=[];static getInstance(){return t.instance||(t.instance=new t),t.instance}onError(e){this.errorCallbacks.push(e)}handleError(t,n){const a={code:t instanceof e?t.code:"UNKNOWN_ERROR",message:t.message,module:t instanceof e?t.module:n,timestamp:t instanceof e?t.timestamp:Date.now(),stack:t.stack};this.errorCallbacks.forEach(e=>{try{e(a)}catch(e){}})}createModuleErrorHandler(t){return(n,a,s)=>{const r=new e(n,a,t);return s&&(r.stack=s.stack),this.handleError(r,t),r}}}async function n(e,n,a="ASYNC_ERROR"){try{return await e()}catch(e){return t.getInstance().createModuleErrorHandler(n)(a,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function a(e,n,a="SYNC_ERROR",s=null){try{return e()}catch(e){return t.getInstance().createModuleErrorHandler(n)(a,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),s}}var s=Object.freeze({__proto__:null,ErrorHandler:t,UniAppToolsError:e,safeAsync:n,safeSync:a});class r{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return r.instance||(r.instance=new r),r.instance}start(e,t,n){const a={name:e,startTime:performance.now(),module:t,metadata:n};this.metrics.set(e,a)}end(e){const t=this.metrics.get(e);return t?(t.endTime=performance.now(),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 a=`${n.module}.${n.name}`;t[a]||(t[a]={total:0,count:0}),t[a].total+=n.duration||0,t[a].count+=1});const n={};Object.entries(t).forEach(([e,t])=>{n[e]=t.total/t.count});const a=[...this.completedMetrics].sort((e,t)=>(t.duration||0)-(e.duration||0)).slice(0,10);return{byModule:e,slowest:a,average:n}}clear(){this.metrics.clear(),this.completedMetrics=[]}}function o(e){return function(t,n,a){const s=a.value;a.value=function(...a){const o=r.getInstance(),i=`${t.constructor.name}.${n}`;o.start(i,e,{args:a.length});try{const e=s.apply(this,a);return e instanceof Promise?e.finally(()=>{o.end(i)}):(o.end(i),e)}catch(e){throw o.end(i),e}}}}var i=Object.freeze({__proto__:null,PerformanceMonitor:r,measurePerformance:o});const c=(e="",t=!1,n="none",a=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:a})};function u(e){return a(()=>{if(null===e||"object"!=typeof e)return e;const t=new WeakMap;return function e(n){if(null===n||"object"!=typeof n)return n;if(t.has(n))return t.get(n);if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(n instanceof Map){const a=new Map;return t.set(n,a),n.forEach((t,n)=>{a.set(e(n),e(t))}),a}if(n instanceof Set){const a=new Set;return t.set(n,a),n.forEach(t=>{a.add(e(t))}),a}if(Array.isArray(n)){const a=new Array(n.length);t.set(n,a);for(let t=0;t<n.length;t++)a[t]=e(n[t]);return a}const a=Object.create(Object.getPrototypeOf(n));t.set(n,a);const s=Object.getOwnPropertyDescriptors(n);for(const t in s){const n=s[t];void 0!==n.value&&(n.value=e(n.value)),Object.defineProperty(a,t,n)}return a}(e)},"utils","DEEP_CLONE_ERROR",e)}function l(e,t){const n=r.getInstance();n.start("mergeObjects","utils");const s=a(()=>Object.assign(e,t),"utils","MERGE_OBJECTS_ERROR",e);return n.end("mergeObjects"),s}function d(e,t){const n=r.getInstance();n.start("deepMerge","utils");const s=a(()=>{const n=u(e);return function e(t,n){for(const a in n)if(n.hasOwnProperty(a)){const s=n[a],r=t[a];s&&"object"==typeof s&&!Array.isArray(s)&&r&&"object"==typeof r&&!Array.isArray(r)?e(r,s):t[a]=u(s)}}(n,t),n},"utils","DEEP_MERGE_ERROR",e);return n.end("deepMerge"),s}function g(e,t,n=!1){let a,s=null;const r=function(...r){const o=n&&!s;return s&&clearTimeout(s),s=setTimeout(()=>{s=null,n||(a=e.apply(this,r))},t),o&&(a=e.apply(this,r)),a};return r.cancel=()=>{s&&(clearTimeout(s),s=null)},r}function m(e,t,n={}){let a,s=null,r=0;const{leading:o=!0,trailing:i=!0}=n,c=function(...n){const c=Date.now();r||o||(r=c);const u=t-(c-r);return u<=0||u>t?(s&&(clearTimeout(s),s=null),r=c,a=e.apply(this,n)):!s&&i&&(s=setTimeout(()=>{r=o?Date.now():0,s=null,a=e.apply(this,n)},u)),a};return c.cancel=()=>{s&&(clearTimeout(s),s=null),r=0},c}function p(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return l(e,u(t))}return u(t)}const h=e=>{const t=r.getInstance();t.start("getH5UrlParams","utils");const n=a(()=>{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(a){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n},"utils","GET_H5_URL_PARAMS_ERROR",e?null:{});return t.end("getH5UrlParams"),n};class f{static instance;navigationQueue=[];isNavigating=!1;maxQueueSize=10;static getInstance(){return f.instance||(f.instance=new f),f.instance}async processQueue(){if(!this.isNavigating&&0!==this.navigationQueue.length){for(this.isNavigating=!0;this.navigationQueue.length>0;){const e=this.navigationQueue.shift();if(e)try{await e(),await new Promise(e=>setTimeout(e,100))}catch(e){}}this.isNavigating=!1}}addToQueue(e){this.navigationQueue.length>=this.maxQueueSize&&this.navigationQueue.shift(),this.navigationQueue.push(e),this.processQueue()}async navigateTo(e){const t=r.getInstance();return t.start("navigateTo","navigation",{url:e.url}),new Promise(a=>{this.addToQueue(async()=>{const s=await n(()=>new Promise(n=>{let a=e.url;if(e.params&&Object.keys(e.params).length>0){const t=Object.entries(e.params).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");a+=(a.includes("?")?"&":"?")+t}uni.navigateTo({url:a,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>{t.end("navigateTo"),n(!0)},fail:e=>{t.end("navigateTo"),n(!1)}})}),"navigation","NAVIGATE_TO_ERROR");a(s??!1)})})}async redirectTo(e){const t=r.getInstance();return t.start("redirectTo","navigation",{url:e.url}),new Promise(a=>{this.addToQueue(async()=>{const s=await n(()=>new Promise(n=>{let a=e.url;if(e.params&&Object.keys(e.params).length>0){const t=Object.entries(e.params).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");a+=(a.includes("?")?"&":"?")+t}uni.redirectTo({url:a,success:()=>{t.end("redirectTo"),n(!0)},fail:e=>{t.end("redirectTo"),n(!1)}})}),"navigation","REDIRECT_TO_ERROR");a(s??!1)})})}async navigateBack(e="",t={}){const a=r.getInstance();a.start("navigateBack","navigation");const s={delta:1,timeout:5e3,enableDebounce:!0,debounceWait:300,...t};return new Promise(t=>{this.addToQueue(async()=>{const r=await n(()=>new Promise(t=>{if(getCurrentPages().length<=s.delta)return void t(!1);const n=setTimeout(()=>{t(!1)},s.timeout);uni.navigateBack({delta:s.delta,success:()=>{clearTimeout(n),setTimeout(()=>{try{const n=getCurrentPages();if(n.length>0){const t=n[n.length-1];t.$vm&&"function"==typeof t.$vm.init?t.$vm.init(e):t.route}a.end("navigateBack"),t(!0)}catch(e){a.end("navigateBack"),t(!0)}},100)},fail:e=>{clearTimeout(n),a.end("navigateBack"),t(!1)}})}),"navigation","NAVIGATE_BACK_ERROR");t(r??!1)})})}async switchTab(e){const t=r.getInstance();return t.start("switchTab","navigation",{url:e}),new Promise(a=>{this.addToQueue(async()=>{const s=await n(()=>new Promise(n=>{uni.switchTab({url:e,success:()=>{t.end("switchTab"),n(!0)},fail:e=>{t.end("switchTab"),n(!1)}})}),"navigation","SWITCH_TAB_ERROR");a(s??!1)})})}async reLaunch(e){const t=r.getInstance();return t.start("reLaunch","navigation",{url:e.url}),new Promise(a=>{this.addToQueue(async()=>{const s=await n(()=>new Promise(n=>{let a=e.url;if(e.params&&Object.keys(e.params).length>0){const t=Object.entries(e.params).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");a+=(a.includes("?")?"&":"?")+t}uni.reLaunch({url:a,success:()=>{t.end("reLaunch"),n(!0)},fail:e=>{t.end("reLaunch"),n(!1)}})}),"navigation","RELAUNCH_ERROR");a(s??!1)})})}getCurrentPageInfo(){return a(()=>{const e=getCurrentPages();if(0===e.length)return null;const t=e[e.length-1];return{route:t.route||"",options:t.options||{}}},"navigation","GET_CURRENT_PAGE_ERROR",null)}getPageStack(){return a(()=>getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}})),"navigation","GET_PAGE_STACK_ERROR",[])??[]}clearQueue(){this.navigationQueue=[],this.isNavigating=!1}}const y=f.getInstance(),w=async(e="",t={})=>await y.navigateBack(e,t),R=async(e="",t={})=>{const n=r.getInstance();n.start("useBackOrHome","navigation");try{const a=getCurrentPages(),s=t.delta||1;if(a.length>s){const a=await y.navigateBack(e,t);return n.end("useBackOrHome"),a}const r=t.homePage||"pages/index/index",o=r.startsWith("/")?r:`/${r}`,i=await y.reLaunch({url:o,params:t.homeParams});return n.end("useBackOrHome"),i}catch(e){return n.end("useBackOrHome"),!1}},E=g(w,300),T=async e=>await y.navigateTo(e),S=async e=>await y.redirectTo(e),v=async e=>await y.switchTab(e),_=async e=>await y.reLaunch(e),P=()=>y.getCurrentPageInfo(),O=()=>y.getPageStack(),I=()=>{y.clearQueue()},b=async(e,t=3)=>{for(let n=0;n<t;n++){if(await T(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1},C={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};async function A(e,t={}){const s=r.getInstance();s.start("copyText","clipboard",{textLength:e.length});const o={...C,...t};if(!e||"string"!=typeof e)return o.showToast&&c("复制内容不能为空",!1,"error"),s.end("copyText"),!1;if(e.length>1e4)return o.showToast&&c("复制内容过长",!1,"error"),s.end("copyText"),!1;let i=!1;return i=await n(()=>new Promise(t=>{uni.setClipboardData({data:e,success:()=>{o.showToast&&c(o.successMessage),t(!0)},fail:()=>{o.showToast&&c(o.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_NATIVE_ERROR")??!1,i=await async function(e,t){if(navigator.clipboard&&window.isSecureContext){if(await n(async()=>(await Promise.race([navigator.clipboard.writeText(e),new Promise((e,n)=>setTimeout(()=>n(new Error("Clipboard API timeout")),t.timeout))]),!0),"clipboard","CLIPBOARD_API_ERROR"))return t.showToast&&c(t.successMessage),!0}return function(e,t){return a(()=>{const n=document.createElement("textarea");Object.assign(n.style,{position:"fixed",top:"-9999px",left:"-9999px",width:"1px",height:"1px",padding:"0",border:"none",outline:"none",boxShadow:"none",background:"transparent",fontSize:"16px"}),n.value=e,n.setAttribute("readonly",""),n.setAttribute("contenteditable","true"),document.body.appendChild(n),n.focus(),n.select(),n.setSelectionRange(0,e.length);const a=document.execCommand("copy");return document.body.removeChild(n),a?(t.showToast&&c(t.successMessage),!0):(t.showToast&&c(t.failMessage),!1)},"clipboard","FALLBACK_COPY_ERROR",!1)??!1}(e,t)}(e,o),s.end("copyText"),i}async function x(e={}){const t=r.getInstance();t.start("readClipboard","clipboard");const a={...C,...e};if(navigator.clipboard&&window.isSecureContext){const e=await n(async()=>await Promise.race([navigator.clipboard.readText(),new Promise((e,t)=>setTimeout(()=>t(new Error("Read clipboard timeout")),a.timeout))]),"clipboard","READ_CLIPBOARD_ERROR");return t.end("readClipboard"),e}return a.showToast&&c("当前平台不支持读取剪贴板",!1,"error"),t.end("readClipboard"),null}function F(){return!(!navigator.clipboard||!window.isSecureContext)}async function M(e={}){return await A("",e)}class k{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return k.instance||(k.instance=new k),k.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 z=k.getInstance(),B=(e=!0)=>{const t=r.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=z.get(n);if(e)return t.end("getWindowInfo"),e}const s=a(()=>{const t=uni.getWindowInfo();return e&&z.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),s},j=()=>{let e;return e="weixin",e="web",e="app",e="alipay",e="h5","h5"},L=()=>{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}}},U=()=>{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){}},D=()=>{try{return uni.getSystemInfoSync().statusBarHeight||0}catch(e){return 0}},N=()=>{try{const e=j();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},$=()=>{try{const e=D(),t=j();if("weixin"===t||"alipay"===t){const t=N();if(t){return t.height+e}}return e+0}catch(e){return D()+0}},G=()=>{try{const e=D();return{statusBarHeight:e,navHeight:$()}}catch(e){return{statusBarHeight:0,navHeight:44}}},H=e=>a(()=>{const t=j();return("h5"===t||"web"===t)&&"undefined"!=typeof document&&(document.title=e,!0)},"system","SET_PAGE_TITLE_ERROR",!1),W=(e,t="image/x-icon")=>a(()=>{const n=j();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),Q=()=>{const e=r.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};class J{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return J.instance||(J.instance=new J),J.instance}compress(e){return e.replace(/(.)\1{2,}/g,(e,t)=>`${t}*${e.length}`)}decompress(e){return e.replace(/(.)\*(\d+)/g,(e,t,n)=>t.repeat(parseInt(n)))}encrypt(e){return btoa(encodeURIComponent(e))}decrypt(e){try{return decodeURIComponent(atob(e))}catch{return e}}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,n={}){const s=r.getInstance();s.start(`setStorage_${e}`,"localStorage");const o=a(()=>{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const a={value:t,timestamp:Date.now(),ttl:n.ttl,compressed:n.compress,encrypted:n.encrypt};let s=JSON.stringify(a);if(n.compress&&(s=this.compress(s)),n.encrypt&&(s=this.encrypt(s)),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,a),!0},"localStorage","SET_STORAGE_ERROR",!1);return s.end(`setStorage_${e}`),o??!1}get(e,t){const n=r.getInstance();n.start(`getStorage_${e}`,"localStorage");const s=a(()=>{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}let n=uni.getStorageSync(e);if(!n)return t;if("string"!=typeof n)return t;let a,s=n;if(s&&s.includes("="))try{const e=this.decrypt(s);e&&(s=e)}catch{}if(s&&s.includes("*"))try{s=this.decompress(s)}catch{}try{const e=JSON.parse(s);a=e&&"object"==typeof e&&"value"in e&&"timestamp"in e?e:{value:e,timestamp:Date.now()}}catch{return s}return this.isExpired(a)?(this.remove(e),t):(this.cache.set(e,a),a.value)},"localStorage","GET_STORAGE_ERROR",t);return n.end(`getStorage_${e}`),s??t}remove(e){return a(()=>!(!e||"string"!=typeof e)&&(uni.removeStorageSync(e),this.cache.delete(e),!0),"localStorage","REMOVE_STORAGE_ERROR",!1)??!1}clear(){return a(()=>(uni.clearStorageSync(),this.cache.clear(),!0),"localStorage","CLEAR_STORAGE_ERROR",!1)??!1}getInfo(){return a(()=>{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}},"localStorage","GET_STORAGE_INFO_ERROR",{keys:[],currentSize:0,limitSize:0})??{keys:[],currentSize:0,limitSize:0}}cleanExpired(){const e=r.getInstance();e.start("cleanExpiredStorage","localStorage");const t=a(()=>{const e=this.getInfo();let t=0;return e.keys.forEach(e=>{void 0===this.get(e)&&t++}),t},"localStorage","CLEAN_EXPIRED_ERROR",0);return e.end("cleanExpiredStorage"),t??0}}const V=J.getInstance();function Y(e,t,n={}){return V.set(e,t,n)}function q(e,t){return V.get(e,t)}function K(e){return e?V.remove(e):V.clear()}async function X(e,t,a={}){return await n(()=>new Promise(n=>{n(Y(e,t,a))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1}async function Z(e,t){return await n(()=>new Promise(n=>{n(q(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t}function ee(){return V.getInfo()}function te(){return V.cleanExpired()}function ne(e,t={}){const n=r.getInstance();n.start("batchSetStorage","localStorage");let a=0;return Object.entries(e).forEach(([e,n])=>{Y(e,n,t)&&a++}),n.end("batchSetStorage"),a}function ae(e){const t=r.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=q(e)}),t.end("batchGetStorage"),n}const se={name:"file",maxSize:10,allowedTypes:["jpg","jpeg","png","gif","webp"],showToast:!0,timeout:6e4,successMessage:"上传成功",failMessage:"上传失败"},re={type:"image",count:1,sizeType:["original","compressed"],sourceType:["album","camera"],extension:[],maxSize:10,showToast:!0,failMessage:"选择文件失败"};async function oe(e={}){const t=r.getInstance();t.start("chooseFile","upload",{count:e.count,type:e.type});const a={...re,...e};let s=a.type;var o;("messagefile"===(o=s)?"function"==typeof uni.chooseMessageFile:"local"===o||"image"===o)||(s="image");const i=await n(()=>new Promise(e=>{const t=t=>{const n=t.errMsg||a.failMessage;a.showToast&&c(n,!1,"error"),e({success:!1,message:n,type:s})};"image"!==s&&"local"!==s?"messagefile"===s?uni.chooseMessageFile({count:a.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:a.count,sizeType:a.sizeType,sourceType:a.sourceType,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],a=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:a,type:"image"})},fail:t}):"local"===s&&("function"==typeof uni.chooseFile?uni.chooseFile({count:a.count,extension:a.extension,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],a=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:a,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=a=>{const s=a.target.files;if(s&&s.length>0){const n=Array.from(s).map(e=>({path:URL.createObjectURL(e),size:e.size,name:e.name,type:e.type,file:e})),a=n.map(e=>({path:e.path,size:e.size}));t({success:!0,tempFilePaths:n.map(e=>e.path),tempFiles:a,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()}(a,e)}).then(e=>{if(!e.success||!e.tempFiles||!a.maxSize)return e;if(e.tempFiles.filter(e=>{var t,n;return!(t=e.size,(n=a.maxSize)&&t>1024*n*1024?{valid:!1,message:`文件大小不能超过 ${n}MB`}:{valid:!0}).valid}).length>0){const t=`部分文件大小超过 ${a.maxSize}MB 限制`;return a.showToast&&c(t,!1,"error"),{...e,success:!1,message:t}}return e}),"upload","CHOOSE_FILE_ERROR");return t.end("chooseFile"),i||{success:!1,message:"选择文件失败",type:s}}async function ie(e={}){const t=await oe({...e,type:"image"});return{success:t.success,tempFilePaths:t.tempFilePaths,tempFiles:t.tempFiles,message:t.message}}async function ce(e,t,a){const s=r.getInstance();s.start("uploadFile","upload",{filePath:e});const o={...se,...t};if(!o.url){const e="上传地址不能为空";return o.showToast&&c(e,!1,"error"),s.end("uploadFile"),{success:!1,message:e}}const i=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,o);if(!i.valid)return o.showToast&&c(i.message,!1,"error"),s.end("uploadFile"),{success:!1,message:i.message};const u=await n(()=>new Promise(t=>{const n=uni.uploadFile({url:o.url,filePath:e,name:o.name,formData:o.formData,header:o.header,timeout:o.timeout,success:n=>{let a;try{a=JSON.parse(n.data)}catch{a=n.data}if(200===n.statusCode)o.showToast&&c(o.successMessage,!1,"success"),t({success:!0,data:a,tempFilePath:e,statusCode:n.statusCode});else{const e=`上传失败,状态码:${n.statusCode}`;o.showToast&&c(e,!1,"error"),t({success:!1,message:e,statusCode:n.statusCode})}},fail:n=>{const a=n.errMsg||o.failMessage;o.showToast&&c(a,!1,"error"),t({success:!1,message:a,tempFilePath:e})}});a&&n&&n.onProgressUpdate(e=>{a({progress:e.progress,totalBytesSent:e.totalBytesSent,totalBytesExpectedToSend:e.totalBytesExpectedToSend})})}),"upload","UPLOAD_FILE_ERROR");return s.end("uploadFile"),u||{success:!1,message:"上传文件失败"}}async function ue(e,t={},n){const a=r.getInstance();a.start("chooseAndUploadFile","upload");const s=await oe(t);if(!s.success||!s.tempFilePaths)return a.end("chooseAndUploadFile"),[{success:!1,message:s.message||"选择文件失败"}];const o=s.tempFilePaths.map(t=>ce(t,e,n)),i=await Promise.all(o);return a.end("chooseAndUploadFile"),i}async function le(e,t={},n){return ue(e,{...t,type:"image"},n)}function de(){return"undefined"!=typeof uni&&"function"==typeof uni.chooseImage&&"function"==typeof uni.uploadFile}async function ge(e){return await n(()=>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 me=(e,t,n)=>{const s=r.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))})},pe="1.0.8";async function he(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,logLevel:a="warn"}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return s}),n=e.getInstance();t&&n.onError(e=>{})}if(t){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return i}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},6e4)}}export{t as ErrorHandler,r as PerformanceMonitor,e as UniAppToolsError,pe as VERSION,ae as batchGetStorage,ne as batchSetStorage,ue as chooseAndUploadFile,le as chooseAndUploadImage,oe as chooseFile,ie as chooseImage,te as cleanExpiredStorage,M as clearClipboard,I as clearNavigationQueue,K as clearStorageSync,A as copyText,g as debounce,u as deepClone,d as deepMerge,L as getCurrentEnv,P as getCurrentPageInfo,ge as getFileInfo,h as getH5UrlParams,N as getMenuButtonBoundingClientRect,$ as getNavHeight,O as getPageStack,j as getPlatform,D as getStatusBarHeight,Z as getStorage,ee as getStorageInfo,q as getStorageSync,G as getTopNavBarHeight,he as initUniAppTools,F as isClipboardSupported,de as isUploadSupported,Q as isWechat,o as measurePerformance,l as mergeObjects,T as navigateTo,U as onCheckForUpdate,_ as reLaunch,x as readClipboard,S as redirectTo,n as safeAsync,b as safeNavigateTo,a as safeSync,W as setPageIcon,H as setPageTitle,X as setStorage,Y as setStorageSync,v as switchTab,m as throttle,ce as uploadFile,w as useBack,E as useBackDebounced,R as useBackOrHome,p as useDeepCopyByObj,c as useToast,B as useWindowInfo,me as weChatOfficialAccountPayment};