my-uniapp-tools 1.0.21 → 2.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.
- package/README.md +27 -0
- package/dist/clipboard/index.d.ts +2 -19
- package/dist/localStorage/index.d.ts +0 -2
- package/dist/my-uniapp-tools.cjs.js +1 -1
- package/dist/my-uniapp-tools.esm.js +1 -1
- package/dist/navigation/index.d.ts +31 -30
- package/dist/upload/index.d.ts +0 -10
- package/dist/utils/index.d.ts +48 -5
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -473,6 +473,33 @@ if (isUploadSupported()) {
|
|
|
473
473
|
}
|
|
474
474
|
```
|
|
475
475
|
|
|
476
|
+
### 💳 支付(微信公众号 H5)
|
|
477
|
+
|
|
478
|
+
#### weChatOfficialAccountPayment(config, onSuccess?, onError?)
|
|
479
|
+
|
|
480
|
+
在微信内置浏览器中调起支付。
|
|
481
|
+
|
|
482
|
+
```javascript
|
|
483
|
+
import { weChatOfficialAccountPayment } from 'my-uniapp-tools';
|
|
484
|
+
|
|
485
|
+
// 从服务端获取签名后的支付参数
|
|
486
|
+
const payConfig = await fetch('/api/pay/wechat/unified-order', {
|
|
487
|
+
method: 'POST',
|
|
488
|
+
body: JSON.stringify({ orderId: '123456' })
|
|
489
|
+
}).then(r => r.json());
|
|
490
|
+
|
|
491
|
+
const ok = await weChatOfficialAccountPayment(
|
|
492
|
+
payConfig,
|
|
493
|
+
() => uni.showToast({ title: '支付成功', icon: 'success' }),
|
|
494
|
+
() => uni.showToast({ title: '已取消或失败', icon: 'none' })
|
|
495
|
+
);
|
|
496
|
+
|
|
497
|
+
if (!ok) {
|
|
498
|
+
// 非微信环境或调用失败
|
|
499
|
+
uni.showToast({ title: '请在微信中打开', icon: 'none' });
|
|
500
|
+
}
|
|
501
|
+
```
|
|
502
|
+
|
|
476
503
|
### 🛠️ 工具函数
|
|
477
504
|
|
|
478
505
|
#### deepClone(obj)
|
|
@@ -11,28 +11,11 @@ interface ClipboardConfig {
|
|
|
11
11
|
timeout?: number;
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
|
-
*
|
|
14
|
+
* 跨平台文本复制功能(统一使用 uni.setClipboardData)
|
|
15
15
|
* @param text 要复制的文本内容
|
|
16
16
|
* @param config 配置选项
|
|
17
|
-
* @description 支持 H5、App
|
|
17
|
+
* @description 支持 H5、App、小程序,统一使用 uni.setClipboardData API
|
|
18
18
|
* @returns Promise<boolean> 复制是否成功
|
|
19
19
|
*/
|
|
20
20
|
export declare function copyText(text: string, config?: ClipboardConfig): Promise<boolean>;
|
|
21
|
-
/**
|
|
22
|
-
* 读取剪贴板内容(仅H5平台支持)
|
|
23
|
-
* @param config 配置选项
|
|
24
|
-
* @returns Promise<string | null> 剪贴板内容,失败时返回null
|
|
25
|
-
*/
|
|
26
|
-
export declare function readClipboard(config?: ClipboardConfig): Promise<string | null>;
|
|
27
|
-
/**
|
|
28
|
-
* 检查剪贴板API是否可用
|
|
29
|
-
* @returns boolean 是否支持剪贴板操作
|
|
30
|
-
*/
|
|
31
|
-
export declare function isClipboardSupported(): boolean;
|
|
32
|
-
/**
|
|
33
|
-
* 清空剪贴板(仅H5平台支持)
|
|
34
|
-
* @param config 配置选项
|
|
35
|
-
* @returns Promise<boolean> 是否成功
|
|
36
|
-
*/
|
|
37
|
-
export declare function clearClipboard(config?: ClipboardConfig): Promise<boolean>;
|
|
38
21
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";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});class c{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return c.instance||(c.instance=new c),c.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 u=c.getInstance(),l=()=>{let e="unknown";try{const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{};t&&void 0!==t.wx&&"function"==typeof t.wx.getSystemInfo?e="weixin":t&&void 0!==t.my?e="alipay":t&&void 0!==t.plus?e="app":"undefined"!=typeof window&&"undefined"!=typeof document&&(e="h5")}catch(e){}return e},p=()=>{try{return uni.getSystemInfoSync().statusBarHeight||0}catch(e){return 0}},d=()=>{try{const e=l();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},g=()=>{try{const e=p(),t=l();if("weixin"===t||"alipay"===t){const t=d();if(t){return t.height+e}}return e+0}catch(e){return p()+0}};function m(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 h(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 f(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}const w=(e="",t=!1,n="none",a=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:a})};class y{static instance;navigationQueue=[];isNavigating=!1;maxQueueSize=10;static getInstance(){return y.instance||(y.instance=new y),y.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 R=y.getInstance(),x=async(e="",t={})=>await R.navigateBack(e,t),S=f(x,300),E=async e=>await R.navigateTo(e),T={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};async function v(e,t={}){const s=r.getInstance();s.start("copyText","clipboard",{textLength:e.length});const o={...T,...t};if(!e||"string"!=typeof e)return o.showToast&&w("复制内容不能为空",!1,"error"),s.end("copyText"),!1;if(e.length>1e4)return o.showToast&&w("复制内容过长",!1,"error"),s.end("copyText"),!1;let i=!1;return i=await n(()=>new Promise(t=>{"undefined"==typeof uni||!uni||"function"!=typeof uni.setClipboardData?t(!1):uni.setClipboardData({data:e,success:()=>{o.showToast&&w(o.successMessage),t(!0)},fail:()=>{o.showToast&&w(o.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_NATIVE_ERROR")??!1,i=await async function(e,t){const s="undefined"!=typeof navigator&&!!navigator,r="undefined"!=typeof window&&!!window,o=s&&navigator.clipboard,i=r&&window.isSecureContext;if(o&&i){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&&w(t.successMessage),!0}return function(e,t){return a(()=>{if("undefined"==typeof document||"undefined"==typeof window)return t.showToast&&w(t.failMessage),!1;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&&w(t.successMessage),!0):(t.showToast&&w(t.failMessage),!1)},"clipboard","FALLBACK_COPY_ERROR",!1)??!1}(e,t)}(e,o),s.end("copyText"),i}class P{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return P.instance||(P.instance=new P),P.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 I=P.getInstance();function O(e,t,n={}){return I.set(e,t,n)}function _(e,t){return I.get(e,t)}const C={name:"file",maxSize:10,allowedTypes:["jpg","jpeg","png","gif","webp"],showToast:!0,timeout:6e4,successMessage:"上传成功",failMessage:"上传失败"},b={type:"image",count:1,sizeType:["original","compressed"],sourceType:["album","camera"],extension:[],maxSize:10,showToast:!0,failMessage:"选择文件失败",onPartialInvalid:"fail"};function A(e,t,n){if(!e)return{valid:!1,message:"文件路径不能为空"};if(t.allowedTypes&&t.allowedTypes.length>0){const a=e.split(".").pop()?.toLowerCase(),s=t.allowedTypes.map(e=>e.toLowerCase()),r=!!n&&s.some(e=>!!e.includes("/")&&(e.endsWith("/*")?n.startsWith(e.slice(0,e.indexOf("/"))):n===e)),o=!!a&&s.some(e=>!e.includes("/")&&e.replace(/^\./,"")===a);if(!r&&!o)return{valid:!1,message:`不支持的文件类型,仅支持:${t.allowedTypes.join(", ")}`}}return{valid:!0}}async function F(e={}){const t=r.getInstance();t.start("chooseFile","upload",{count:e.count,type:e.type});const a={...b,...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&&w(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,name:e.name,type:e.type}));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)return e;const t=a.maxSize?e.tempFiles.filter(e=>{return!(t=e.size,n=a.maxSize,n&&t>1024*n*1024?{valid:!1,message:`文件大小不能超过 ${n}MB`}:{valid:!0}).valid;var t,n}):[],n="image"===a.type||a.extension.length>0,s=n?e.tempFiles.filter(e=>{const t={url:"",allowedTypes:"image"===a.type&&0===a.extension.length?["image/*"]:a.extension};return!A(e.path,t,e.type).valid}):[],r=new Set;t.forEach(e=>r.add(e.path)),s.forEach(e=>r.add(e.path));const o=Array.from(r);if(0===o.length)return e;const i=`部分文件不合规:${[a.maxSize?`大小超过 ${a.maxSize}MB`:"",n?"类型不符合要求":""].filter(Boolean).join(",")}`;if("filter"===a.onPartialInvalid){const t=e.tempFiles.filter(e=>!r.has(e.path));return{...e,tempFiles:t,tempFilePaths:t.map(e=>e.path),invalidFiles:o,message:i,success:t.length>0}}return a.showToast&&w(i,!1,"error"),{...e,success:"allow"===a.onPartialInvalid,invalidFiles:o,message:i}}),"upload","CHOOSE_FILE_ERROR");return t.end("chooseFile"),i||{success:!1,message:"选择文件失败",type:s}}async function M(e,t,a){const s=r.getInstance();s.start("uploadFile","upload",{filePath:e});const o={...C,...t};if(!o.url){const e="上传地址不能为空";return o.showToast&&w(e,!1,"error"),s.end("uploadFile"),{success:!1,message:e}}const i=A(e,o);if(!i.valid)return o.showToast&&w(i.message,!1,"error"),s.end("uploadFile"),{success:!1,message:i.message};const c=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&&w(o.successMessage,!1,"success"),t({success:!0,data:a,tempFilePath:e,statusCode:n.statusCode,originalResult:n});else{const e=`上传失败,状态码:${n.statusCode}`;o.showToast&&w(e,!1,"error"),t({success:!1,message:e,statusCode:n.statusCode,originalResult:n})}},fail:n=>{const a=n.errMsg||o.failMessage;o.showToast&&w(a,!1,"error"),t({success:!1,message:a,tempFilePath:e,originalResult:n})}});a&&n&&n.onProgressUpdate(e=>{a({progress:e.progress,totalBytesSent:e.totalBytesSent,totalBytesExpectedToSend:e.totalBytesExpectedToSend})})}),"upload","UPLOAD_FILE_ERROR");return s.end("uploadFile"),c||{success:!1,message:"上传文件失败"}}async function k(e,t={},n){const a=r.getInstance();a.start("chooseAndUploadFile","upload");const s=await F(t);if(!s.success||!s.tempFilePaths)return a.end("chooseAndUploadFile"),[{success:!1,message:s.message||"选择文件失败"}];const o=s.tempFilePaths.map(t=>M(t,e,n)),i=await Promise.all(o);return a.end("chooseAndUploadFile"),i}const B=()=>{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},j=()=>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 a=s=>{const r=document.createElement("script");r.src=s,r.async=!0,r.onload=()=>{e(!0)},r.onerror=()=>{n++,n<t.length?(document.head.removeChild(r),a(t[n])):(document.head.removeChild(r),e(!1))},document.head.appendChild(r)};a(t[n]),e(!1)}),D=async e=>{const t=r.getInstance();t.start("configWechatJSSDK","wechat");try{if(!B())return!1;return!!await j()&&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")}},U=e=>{a(()=>{window.wx&&B()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},L=e=>{a(()=>{window.wx&&B()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class z{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return z.instance||(z.instance=new z),z.instance}async init(e){return this.config=e,this.isConfigured=await D(e),this.isConfigured}isReady(){return this.isConfigured&&B()}getConfig(){return this.config}setShareData(e){this.isReady()&&(U(e),L(e))}}exports.ErrorHandler=t,exports.PerformanceMonitor=r,exports.UniAppToolsError=e,exports.VERSION="1.0.8",exports.WechatSDK=z,exports.batchGetStorage=function(e){const t=r.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=r.getInstance();n.start("batchSetStorage","localStorage");let a=0;return Object.entries(e).forEach(([e,n])=>{O(e,n,t)&&a++}),n.end("batchSetStorage"),a},exports.checkWechatJSAPI=e=>new Promise(t=>{window.wx&&B()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),exports.chooseAndUploadFile=k,exports.chooseAndUploadImage=async function(e,t={},n){return k(e,{...t,type:"image"},n)},exports.chooseFile=F,exports.chooseImage=async function(e={}){const t=await F({...e,type:"image"});return{success:t.success,tempFilePaths:t.tempFilePaths,tempFiles:t.tempFiles,message:t.message}},exports.cleanExpiredStorage=function(){return I.cleanExpired()},exports.clearClipboard=async function(e={}){return await v("",e)},exports.clearNavigationQueue=()=>{R.clearQueue()},exports.clearStorageSync=function(e){return e?I.remove(e):I.clear()},exports.configWechatJSSDK=D,exports.copyText=v,exports.debounce=f,exports.deepClone=m,exports.deepMerge=function(e,t){const n=r.getInstance();n.start("deepMerge","utils");const s=a(()=>{const n=m(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]=m(s)}}(n,t),n},"utils","DEEP_MERGE_ERROR",e);return n.end("deepMerge"),s},exports.extractUrlParts=function(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,a={};return t.searchParams.forEach((e,t)=>{a[t]=e}),{path:n,params:a}}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=()=>R.getCurrentPageInfo(),exports.getFileInfo=async function(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")},exports.getH5UrlParams=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},exports.getMenuButtonBoundingClientRect=d,exports.getNavHeight=g,exports.getPageStack=()=>R.getPageStack(),exports.getPlatform=l,exports.getStatusBarHeight=p,exports.getStorage=async function(e,t){return await n(()=>new Promise(n=>{n(_(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t},exports.getStorageInfo=function(){return I.getInfo()},exports.getStorageSync=_,exports.getTopNavBarHeight=()=>{try{const e=p();return{statusBarHeight:e,navHeight:g()}}catch(e){return{statusBarHeight:0,navHeight:44}}},exports.initUniAppTools=async function(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)}},exports.isClipboardSupported=function(){const e="undefined"!=typeof navigator&&!!navigator,t="undefined"!=typeof window&&!!window;return!!(e&&t&&navigator.clipboard&&window.isSecureContext)},exports.isUploadSupported=function(){return"undefined"!=typeof uni&&"function"==typeof uni.uploadFile},exports.isWechat=B,exports.loadWechatJSSDK=j,exports.measurePerformance=o,exports.mergeObjects=h,exports.navigateTo=E,exports.onCheckForUpdate=()=>{try{const e=uni.getUpdateManager();e.onCheckForUpdate(function(e){e.hasUpdate}),e.onUpdateReady(function(t){uni.showModal({title:"更新提示",content:"新版本已经准备好,是否重启应用?",showCancel:!0,cancelText:"稍后",confirmText:"立即重启",success(t){t.confirm&&e.applyUpdate()}})}),e.onUpdateFailed(function(e){uni.showModal({title:"更新失败",content:"新版本下载失败,请检查网络连接或稍后重试",showCancel:!1,confirmText:"知道了"})})}catch(e){}},exports.reLaunch=async e=>await R.reLaunch(e),exports.readClipboard=async function(e={}){const t=r.getInstance();t.start("readClipboard","clipboard");const a={...T,...e},s="undefined"!=typeof navigator&&!!navigator,o="undefined"!=typeof window&&!!window;if(s&&o&&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&&w("当前平台不支持读取剪贴板",!1,"error"),t.end("readClipboard"),null},exports.redirectTo=async e=>await R.redirectTo(e),exports.safeAsync=n,exports.safeNavigateTo=async(e,t=3)=>{for(let n=0;n<t;n++){if(await E(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1},exports.safeSync=a,exports.setPageIcon=(e,t="image/x-icon")=>a(()=>{const n=l();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,a={}){return await n(()=>new Promise(n=>{n(O(e,t,a))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1},exports.setStorageSync=O,exports.shareToFriend=L,exports.shareToTimeline=U,exports.switchTab=async e=>await R.switchTab(e),exports.throttle=function(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},exports.uploadFile=M,exports.useBack=x,exports.useBackDebounced=S,exports.useBackOrHome=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 R.navigateBack(e,t);return n.end("useBackOrHome"),a}const r=t.homePage||"pages/index/index",o=r.startsWith("/")?r:`/${r}`,i=await R.reLaunch({url:o,params:t.homeParams});return n.end("useBackOrHome"),i}catch(e){return n.end("useBackOrHome"),!1}},exports.useDeepCopyByObj=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return h(e,m(t))}return m(t)},exports.useToast=w,exports.useTryCatch=function(e,t={}){return async(...n)=>{try{return{data:await e(...n),error:null}}catch(e){return t.onError?.(e),{data:null,error:e}}finally{t.onFinally?.()}}},exports.useWindowInfo=(e=!0)=>{const t=r.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=u.get(n);if(e)return t.end("getWindowInfo"),e}const s=a(()=>{const t=uni.getWindowInfo();return e&&u.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),s},exports.weChatOfficialAccountPayment=(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))})};
|
|
1
|
+
"use strict";var e=require("@vant/area-data");class t extends Error{code;module;timestamp;constructor(e,t,n){super(t),this.name="UniAppToolsError",this.code=e,this.module=n,this.timestamp=Date.now()}}class n{static instance;errorCallbacks=[];static getInstance(){return n.instance||(n.instance=new n),n.instance}onError(e){this.errorCallbacks.push(e)}handleError(e,n){const s={code:e instanceof t?e.code:"UNKNOWN_ERROR",message:e.message,module:e instanceof t?e.module:n,timestamp:e instanceof t?e.timestamp:Date.now(),stack:e.stack};this.errorCallbacks.forEach(e=>{try{e(s)}catch(e){}})}createModuleErrorHandler(e){return(n,s,r)=>{const a=new t(n,s,e);return r&&(a.stack=r.stack),this.handleError(a,e),a}}}async function s(e,t,s="ASYNC_ERROR"){try{return await e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(s,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function r(e,t,s="SYNC_ERROR",r=null){try{return e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(s,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),r}}var a=Object.freeze({__proto__:null,ErrorHandler:n,UniAppToolsError:t,safeAsync:s,safeSync:r});function o(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}class i{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return i.instance||(i.instance=new i),i.instance}start(e,t,n){const s={name:e,startTime:o(),module:t,metadata:n};this.metrics.set(e,s)}end(e){const t=this.metrics.get(e);return t?(t.endTime=o(),t.duration=t.endTime-t.startTime,this.metrics.delete(e),this.completedMetrics.push(t),this.completedMetrics.length>this.maxStoredMetrics&&this.completedMetrics.shift(),t):null}getReport(){const e={},t={};this.completedMetrics.forEach(n=>{e[n.module]||(e[n.module]=[]),e[n.module].push(n);const s=`${n.module}.${n.name}`;t[s]||(t[s]={total:0,count:0}),t[s].total+=n.duration||0,t[s].count+=1});const n={};Object.entries(t).forEach(([e,t])=>{n[e]=t.total/t.count});const s=[...this.completedMetrics].sort((e,t)=>(t.duration||0)-(e.duration||0)).slice(0,10);return{byModule:e,slowest:s,average:n}}clear(){this.metrics.clear(),this.completedMetrics=[]}}function c(e){return function(t,n,s){const r=s.value;s.value=function(...s){const a=i.getInstance(),o=`${t.constructor.name}.${n}`;a.start(o,e,{args:s.length});try{const e=r.apply(this,s);return e instanceof Promise?e.finally(()=>{a.end(o)}):(a.end(o),e)}catch(e){throw a.end(o),e}}}}var u=Object.freeze({__proto__:null,PerformanceMonitor:i,measurePerformance:c});class l{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return l.instance||(l.instance=new l),l.instance}set(e,t,n=this.defaultTTL){this.cache.set(e,{data:t,timestamp:Date.now(),ttl:n})}get(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttl?(this.cache.delete(e),null):t.data:null}clear(){this.cache.clear()}}const p=l.getInstance(),m=()=>{const e="platform",t=p.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",p.set(e,"h5"),"h5"},d=()=>{try{return uni.getSystemInfoSync().statusBarHeight||0}catch(e){return 0}},h=()=>{try{const e=m();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},g=()=>{try{const e=d(),t=m();if("weixin"===t||"alipay"===t){const t=h();if(t){return t.height+e}}return e+0}catch(e){return d()+0}};function f(e){if(null===e||"object"!=typeof e)return e;try{if("undefined"!=typeof structuredClone)try{return structuredClone(e)}catch(e){}return JSON.parse(JSON.stringify(e))}catch(e){throw new Error(`深拷贝失败: ${e instanceof Error?e.message:String(e)}`)}}function y(e,t){return Object.assign(e,t)}function w(e,t,n=!1){let s,r=null;const a=function(...a){const o=n&&!r;return r&&clearTimeout(r),r=setTimeout(()=>{r=null,n||(s=e.apply(this,a))},t),o&&(s=e.apply(this,a)),s};return a.cancel=()=>{r&&(clearTimeout(r),r=null)},a}const x=e.areaList,S=e.useCascaderAreaData;const T=(e="",t=!1,n="none",s=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:s})};function E(e,t){if(!t||0===Object.keys(t).length)return e;const n=Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");return e+(e.includes("?")?"&":"?")+n}async function P(e){return new Promise(t=>{const n=E(e.url,e.params);uni.navigateTo({url:n,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>t(!0),fail:e=>{t(!1)}})})}async function R(e="",t={}){return new Promise(n=>{const s=t.delta||1,r=t.timeout||5e3;if(getCurrentPages().length<=s)return void n(!1);const a=setTimeout(()=>{n(!1)},r);uni.navigateBack({delta:s,success:()=>{clearTimeout(a),setTimeout(()=>{try{const t=getCurrentPages();if(t.length>0){const n=t[t.length-1];n.$vm&&"function"==typeof n.$vm.init&&n.$vm.init(e)}n(!0)}catch(e){n(!0)}},100)},fail:e=>{clearTimeout(a),n(!1)}})})}const v=w(R,300);async function I(e){return new Promise(t=>{const n=E(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}const C={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};class F{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return F.instance||(F.instance=new F),F.instance}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,n={}){try{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const s={value:t,timestamp:Date.now(),ttl:n.ttl},r=JSON.stringify(s);if(r.length>1048576)throw new Error("存储数据过大");if(uni.setStorageSync(e,r),this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}return this.cache.set(e,s),!0}catch(e){throw e}}get(e,t){try{if(!e||"string"!=typeof e)return t;if(this.cache.has(e)){const n=this.cache.get(e);return this.isExpired(n)?(this.cache.delete(e),this.remove(e),t):n.value}const n=uni.getStorageSync(e);if(!n||"string"!=typeof n)return t;const s=JSON.parse(n);let r;return r=s&&"object"==typeof s&&"value"in s&&"timestamp"in s?s:{value:s,timestamp:Date.now()},this.isExpired(r)?(this.remove(e),t):(this.cache.set(e,r),r.value)}catch(e){return t}}remove(e){try{return!(!e||"string"!=typeof e)&&(uni.removeStorageSync(e),this.cache.delete(e),!0)}catch(e){return!1}}clear(){try{return uni.clearStorageSync(),this.cache.clear(),!0}catch(e){return!1}}getInfo(){try{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}}catch(e){return{keys:[],currentSize:0,limitSize:0}}}cleanExpired(){try{const e=this.getInfo();let t=0;return e.keys.forEach(e=>{void 0===this.get(e)&&t++}),t}catch(e){return 0}}}const A=F.getInstance();function M(e,t,n={}){return A.set(e,t,n)}function O(e,t){return A.get(e,t)}const _={name:"file",maxSize:10,allowedTypes:["jpg","jpeg","png","gif","webp"],showToast:!0,timeout:6e4,successMessage:"上传成功",failMessage:"上传失败"},b={type:"image",count:1,sizeType:["original","compressed"],sourceType:["album","camera"],extension:[],maxSize:10,showToast:!0,failMessage:"选择文件失败"};async function D(e={}){const t=i.getInstance();t.start("chooseFile","upload",{count:e.count,type:e.type});const n={...b,...e};let r=n.type;var a;("messagefile"===(a=r)?"function"==typeof uni.chooseMessageFile:"local"===a||"image"===a)||(r="image");const o=await s(()=>new Promise(e=>{const t=t=>{const s=t.errMsg||n.failMessage;n.showToast&&T(s,!1,"error"),e({success:!1,message:s,type:r})};"image"!==r&&"local"!==r?"messagefile"===r?uni.chooseMessageFile({count:n.count,type:"all",success:t=>{e({success:!0,tempFilePaths:t.tempFiles.map(e=>e.path),tempFiles:t.tempFiles,type:"messagefile"})},fail:t}):"image"===r?uni.chooseImage({count:n.count,sizeType:n.sizeType,sourceType:n.sourceType,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"image"})},fail:t}):"local"===r&&("function"==typeof uni.chooseFile?uni.chooseFile({count:n.count,extension:n.extension,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"local"})},fail:t}):e({success:!1,message:"当前平台不支持选择本地文件",type:r})):function(e,t){const n=document.createElement("input");n.type="file",n.multiple=e.count>1,"image"===e.type?n.accept="image/*":e.extension.length>0&&(n.accept=e.extension.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),n.onchange=s=>{const r=s.target.files;if(r&&r.length>0){const n=Array.from(r).map(e=>({path:URL.createObjectURL(e),size:e.size,name:e.name,type:e.type,file:e})),s=n.map(e=>({path:e.path,size:e.size}));t({success:!0,tempFilePaths:n.map(e=>e.path),tempFiles:s,type:e.type})}else t({success:!1,message:"用户取消选择",type:e.type});document.body.removeChild(n)},n.style.display="none",document.body.appendChild(n),n.click()}(n,e)}).then(e=>{if(!e.success||!e.tempFiles||!n.maxSize)return e;if(e.tempFiles.filter(e=>{var t,s;return!(t=e.size,(s=n.maxSize)&&t>1024*s*1024?{valid:!1,message:`文件大小不能超过 ${s}MB`}:{valid:!0}).valid}).length>0){const t=`部分文件大小超过 ${n.maxSize}MB 限制`;return n.showToast&&T(t,!1,"error"),{...e,success:!1,message:t}}return e}),"upload","CHOOSE_FILE_ERROR");return t.end("chooseFile"),o||{success:!1,message:"选择文件失败",type:r}}async function k(e,t,n){const r=i.getInstance();r.start("uploadFile","upload",{filePath:e});const a={..._,...t};if(!a.url){const e="上传地址不能为空";return a.showToast&&T(e,!1,"error"),r.end("uploadFile"),{success:!1,message:e}}const o=function(e,t){if(!e)return{valid:!1,message:"文件路径不能为空"};if(t.allowedTypes&&t.allowedTypes.length>0){const n=e.split(".").pop()?.toLowerCase();if(!n||!t.allowedTypes.includes(n))return{valid:!1,message:`不支持的文件类型,仅支持:${t.allowedTypes.join(", ")}`}}return{valid:!0}}(e,a);if(!o.valid)return a.showToast&&T(o.message,!1,"error"),r.end("uploadFile"),{success:!1,message:o.message};const c=await s(()=>new Promise(t=>{const s=uni.uploadFile({url:a.url,filePath:e,name:a.name,formData:a.formData,header:a.header,timeout:a.timeout,success:n=>{let s;try{s=JSON.parse(n.data)}catch{s=n.data}if(200===n.statusCode)a.showToast&&T(a.successMessage,!1,"success"),t({success:!0,data:s,tempFilePath:e,statusCode:n.statusCode});else{const e=`上传失败,状态码:${n.statusCode}`;a.showToast&&T(e,!1,"error"),t({success:!1,message:e,statusCode:n.statusCode})}},fail:n=>{const s=n.errMsg||a.failMessage;a.showToast&&T(s,!1,"error"),t({success:!1,message:s,tempFilePath:e})}});n&&s&&s.onProgressUpdate(e=>{n({progress:e.progress,totalBytesSent:e.totalBytesSent,totalBytesExpectedToSend:e.totalBytesExpectedToSend})})}),"upload","UPLOAD_FILE_ERROR");return r.end("uploadFile"),c||{success:!1,message:"上传文件失败"}}async function z(e,t={},n){const s=i.getInstance();s.start("chooseAndUploadFile","upload");const r=await D(t);if(!r.success||!r.tempFilePaths)return s.end("chooseAndUploadFile"),[{success:!1,message:r.message||"选择文件失败"}];const a=r.tempFilePaths.map(t=>k(t,e,n)),o=await Promise.all(a);return s.end("chooseAndUploadFile"),o}const j=()=>{const e=i.getInstance();e.start("isWechat","system");const t=r(()=>{if("undefined"!=typeof navigator&&navigator.userAgent){return navigator.userAgent.toLowerCase().includes("micromessenger")}return!1},"system","IS_WECHAT_ERROR",!1);return e.end("isWechat"),t||!1},U=()=>new Promise(e=>{if("undefined"!=typeof window&&window.wx)return void e(!0);const t=["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];let n=0;const s=r=>{const a=document.createElement("script");a.src=r,a.async=!0,a.onload=()=>{e(!0)},a.onerror=()=>{n++,n<t.length?(document.head.removeChild(a),s(t[n])):(document.head.removeChild(a),e(!1))},document.head.appendChild(a)};s(t[n]),e(!1)}),B=async e=>{const t=i.getInstance();t.start("configWechatJSSDK","wechat");try{if(!j())return!1;return!!await U()&&new Promise(t=>{window.wx?(window.wx.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),window.wx.ready(()=>{t(!0)}),window.wx.error(e=>{t(!1)})):t(!1),t(!1)})}catch(e){return!1}finally{t.end("configWechatJSSDK")}},W=e=>{r(()=>{window.wx&&j()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},H=e=>{r(()=>{window.wx&&j()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class L{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return L.instance||(L.instance=new L),L.instance}async init(e){return this.config=e,this.isConfigured=await B(e),this.isConfigured}isReady(){return this.isConfigured&&j()}getConfig(){return this.config}setShareData(e){this.isReady()&&(W(e),H(e))}}exports.ErrorHandler=n,exports.PerformanceMonitor=i,exports.UniAppToolsError=t,exports.VERSION="1.0.8",exports.WechatSDK=L,exports.areaList=x,exports.batchGetStorage=function(e){const t=i.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=O(e)}),t.end("batchGetStorage"),n},exports.batchSetStorage=function(e,t={}){const n=i.getInstance();n.start("batchSetStorage","localStorage");let s=0;return Object.entries(e).forEach(([e,n])=>{M(e,n,t)&&s++}),n.end("batchSetStorage"),s},exports.checkWechatJSAPI=e=>new Promise(t=>{window.wx&&j()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),exports.chooseAndUploadFile=z,exports.chooseAndUploadImage=async function(e,t={},n){return z(e,{...t,type:"image"},n)},exports.chooseFile=D,exports.chooseImage=async function(e={}){const t=await D({...e,type:"image"});return{success:t.success,tempFilePaths:t.tempFilePaths,tempFiles:t.tempFiles,message:t.message}},exports.cleanExpiredStorage=function(){return A.cleanExpired()},exports.clearStorageSync=function(e){return e?A.remove(e):A.clear()},exports.configWechatJSSDK=B,exports.copyText=async function(e,t={}){const n=i.getInstance();n.start("copyText","clipboard",{textLength:e.length});const r={...C,...t};if(!e||"string"!=typeof e)return r.showToast&&T("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return r.showToast&&T("复制内容过长",!1,"error"),n.end("copyText"),!1;const a=await s(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{r.showToast&&T(r.successMessage),t(!0)},fail:()=>{r.showToast&&T(r.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),a},exports.debounce=w,exports.deepClone=f,exports.deepMerge=function(e,t){const n=f(e);return function e(t,n){for(const s in n)if(n.hasOwnProperty(s)){const r=n[s],a=t[s];r&&"object"==typeof r&&!Array.isArray(r)&&a&&"object"==typeof a&&!Array.isArray(a)?e(a,r):t[s]=f(r)}}(n,t),n},exports.extractUrlParts=function(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,s={};return t.searchParams.forEach((e,t)=>{s[t]=e}),{path:n,params:s}}catch(e){return{path:"",params:{}}}},exports.getCurrentEnv=()=>{try{const e=uni.getAccountInfoSync();return{appId:e.miniProgram?.appId||"",version:e.miniProgram?.version||"",envVersion:e.miniProgram?.envVersion||"",accountInfo:e}}catch(e){return{appId:"",version:"",envVersion:"",accountInfo:null}}},exports.getCurrentPageInfo=function(){try{const e=getCurrentPages();if(0===e.length)return null;const t=e[e.length-1];return{route:t.route||"",options:t.options||{}}}catch(e){return null}},exports.getFileInfo=async function(e){return await s(()=>new Promise((t,n)=>{uni.getFileInfo({filePath:e,digestAlgorithm:"md5",success:e=>{const n=e;t({size:n.size,digest:n.digest})},fail:n})}),"upload","GET_FILE_INFO_ERROR")},exports.getH5UrlParams=e=>{try{if("undefined"==typeof window||!window.location)throw new Error("不在 H5 浏览器环境中");const t=new URLSearchParams(window.location.search),n={};return t.forEach((e,t)=>{try{n[t]=decodeURIComponent(e)}catch(s){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return e?null:{}}},exports.getMenuButtonBoundingClientRect=h,exports.getNavHeight=g,exports.getPageStack=function(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return[]}},exports.getPlatform=m,exports.getStatusBarHeight=d,exports.getStorage=async function(e,t){return await s(()=>new Promise(n=>{n(O(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t},exports.getStorageInfo=function(){return A.getInfo()},exports.getStorageSync=O,exports.getTopNavBarHeight=()=>{try{const e=d();return{statusBarHeight:e,navHeight:g()}}catch(e){return{statusBarHeight:0,navHeight:44}}},exports.initUniAppTools=async function(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,onError:s=null,performanceReportInterval:r=0}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return a}),t=e.getInstance();"function"==typeof s?t.onError(s):t.onError(e=>{})}if(t&&r>0){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return u}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},r)}},exports.isUploadSupported=function(){return"undefined"!=typeof uni&&"function"==typeof uni.chooseImage&&"function"==typeof uni.uploadFile},exports.isWechat=j,exports.loadWechatJSSDK=U,exports.measurePerformance=c,exports.mergeObjects=y,exports.navigateTo=P,exports.onCheckForUpdate=()=>{try{const e=uni.getUpdateManager();e.onCheckForUpdate(function(e){e.hasUpdate}),e.onUpdateReady(function(t){uni.showModal({title:"更新提示",content:"新版本已经准备好,是否重启应用?",showCancel:!0,cancelText:"稍后",confirmText:"立即重启",success(t){t.confirm&&e.applyUpdate()}})}),e.onUpdateFailed(function(e){uni.showModal({title:"更新失败",content:"新版本下载失败,请检查网络连接或稍后重试",showCancel:!1,confirmText:"知道了"})})}catch(e){}},exports.reLaunch=I,exports.redirectTo=async function(e){return new Promise(t=>{const n=E(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})},exports.safeAsync=s,exports.safeNavigateTo=async function(e,t=3){for(let n=0;n<t;n++){if(await P(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1},exports.safeSync=r,exports.setPageIcon=(e,t="image/x-icon")=>r(()=>{const n=m();if(("h5"===n||"web"===n)&&"undefined"!=typeof document){document.querySelectorAll('link[rel*="icon"]').forEach(e=>e.remove());const n=document.createElement("link");return n.rel="icon",n.type=t,n.href=e,document.head.appendChild(n),!0}return!1},"system","SET_PAGE_ICON_ERROR",!1),exports.setPageTitle=e=>e&&"string"==typeof e?new Promise(t=>{try{uni.setNavigationBarTitle({title:e,success:()=>{t(!0)},fail:e=>{t(!1)}})}catch(e){t(!1)}}):Promise.resolve(!1),exports.setStorage=async function(e,t,n={}){return await s(()=>new Promise(s=>{s(M(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1},exports.setStorageSync=M,exports.shareToFriend=H,exports.shareToTimeline=W,exports.switchTab=async function(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:e=>{t(!1)}})})},exports.throttle=function(e,t,n={}){let s,r=null,a=0;const{leading:o=!0,trailing:i=!0}=n,c=function(...n){const c=Date.now();a||o||(a=c);const u=t-(c-a);return u<=0||u>t?(r&&(clearTimeout(r),r=null),a=c,s=e.apply(this,n)):!r&&i&&(r=setTimeout(()=>{a=o?Date.now():0,r=null,s=e.apply(this,n)},u)),s};return c.cancel=()=>{r&&(clearTimeout(r),r=null),a=0},c},exports.uploadFile=k,exports.useBack=R,exports.useBackDebounced=v,exports.useBackOrHome=async function(e="",t={}){const n=getCurrentPages(),s=t.delta||1;if(n.length>s)return await R(e,t);const r=t.homePage||"pages/index/index",a=r.startsWith("/")?r:`/${r}`;return await I({url:a,params:t.homeParams})},exports.useCascaderAreaData=S,exports.useDeepCopyByObj=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return y(e,f(t))}return f(t)},exports.useRegions=function(){return e.useCascaderAreaData()},exports.useToast=T,exports.useTryCatch=function(e,t={}){return async(...n)=>{try{return{data:await e(...n),error:null}}catch(e){return t.onError?.(e),{data:null,error:e}}finally{t.onFinally?.()}}},exports.useWindowInfo=(e=!0)=>{const t=i.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=p.get(n);if(e)return t.end("getWindowInfo"),e}const s=r(()=>{const t=uni.getWindowInfo();return e&&p.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),s},exports.weChatOfficialAccountPayment=(e,t,n)=>{const s=i.getInstance();return s.start("weChatOfficialAccountPayment","payment"),new Promise(a=>{r(()=>{if("undefined"==typeof window||!window.navigator)throw new Error("不在浏览器环境中,无法调用微信支付");if(!(e&&e.appId&&e.timeStamp&&e.nonceStr&&e.package&&e.paySign))throw new Error("微信支付配置参数不完整");function r(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){s.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),a(!0)):(n?.(e),a(!1))})}catch(e){s.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),a(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",r,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",r),e.attachEvent("onWeixinJSBridgeReady",r))}else r();return!0},"payment","WECHAT_PAY_ERROR",!1)||(s.end("weChatOfficialAccountPayment"),a(!1))})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
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 i=new e(n,a,t);return s&&(i.stack=s.stack),this.handleError(i,t),i}}}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 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 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 r(e){return function(t,n,a){const s=a.value;a.value=function(...a){const r=i.getInstance(),o=`${t.constructor.name}.${n}`;r.start(o,e,{args:a.length});try{const e=s.apply(this,a);return e instanceof Promise?e.finally(()=>{r.end(o)}):(r.end(o),e)}catch(e){throw r.end(o),e}}}}var o=Object.freeze({__proto__:null,PerformanceMonitor:i,measurePerformance:r});class c{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return c.instance||(c.instance=new c),c.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 u=c.getInstance(),l=(e=!0)=>{const t=i.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=u.get(n);if(e)return t.end("getWindowInfo"),e}const s=a(()=>{const t=uni.getWindowInfo();return e&&u.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),s},d=()=>{let e="unknown";try{const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{};t&&void 0!==t.wx&&"function"==typeof t.wx.getSystemInfo?e="weixin":t&&void 0!==t.my?e="alipay":t&&void 0!==t.plus?e="app":"undefined"!=typeof window&&"undefined"!=typeof document&&(e="h5")}catch(e){}return e},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){}},m=()=>{try{return uni.getSystemInfoSync().statusBarHeight||0}catch(e){return 0}},h=()=>{try{const e=d();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},f=()=>{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}},w=()=>{try{const e=m();return{statusBarHeight:e,navHeight:f()}}catch(e){return{statusBarHeight:0,navHeight:44}}},y=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),R=(e,t="image/x-icon")=>a(()=>{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);function E(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 T(e,t){const n=i.getInstance();n.start("mergeObjects","utils");const s=a(()=>Object.assign(e,t),"utils","MERGE_OBJECTS_ERROR",e);return n.end("mergeObjects"),s}function S(e,t){const n=i.getInstance();n.start("deepMerge","utils");const s=a(()=>{const n=E(e);return function e(t,n){for(const a in n)if(n.hasOwnProperty(a)){const s=n[a],i=t[a];s&&"object"==typeof s&&!Array.isArray(s)&&i&&"object"==typeof i&&!Array.isArray(i)?e(i,s):t[a]=E(s)}}(n,t),n},"utils","DEEP_MERGE_ERROR",e);return n.end("deepMerge"),s}function v(e,t,n=!1){let a,s=null;const i=function(...i){const r=n&&!s;return s&&clearTimeout(s),s=setTimeout(()=>{s=null,n||(a=e.apply(this,i))},t),r&&(a=e.apply(this,i)),a};return i.cancel=()=>{s&&(clearTimeout(s),s=null)},i}function P(e,t,n={}){let a,s=null,i=0;const{leading:r=!0,trailing:o=!0}=n,c=function(...n){const c=Date.now();i||r||(i=c);const u=t-(c-i);return u<=0||u>t?(s&&(clearTimeout(s),s=null),i=c,a=e.apply(this,n)):!s&&o&&(s=setTimeout(()=>{i=r?Date.now():0,s=null,a=e.apply(this,n)},u)),a};return c.cancel=()=>{s&&(clearTimeout(s),s=null),i=0},c}function _(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return T(e,E(t))}return E(t)}const I=e=>{const t=i.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};function O(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,a={};return t.searchParams.forEach((e,t)=>{a[t]=e}),{path:n,params:a}}catch(e){return{path:"",params:{}}}}function x(e,t={}){return async(...n)=>{try{return{data:await e(...n),error:null}}catch(e){return t.onError?.(e),{data:null,error:e}}finally{t.onFinally?.()}}}const C=(e="",t=!1,n="none",a=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:a})};class b{static instance;navigationQueue=[];isNavigating=!1;maxQueueSize=10;static getInstance(){return b.instance||(b.instance=new b),b.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=i.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=i.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=i.getInstance();a.start("navigateBack","navigation");const s={delta:1,timeout:5e3,enableDebounce:!0,debounceWait:300,...t};return new Promise(t=>{this.addToQueue(async()=>{const i=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(i??!1)})})}async switchTab(e){const t=i.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=i.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 A=b.getInstance(),F=async(e="",t={})=>await A.navigateBack(e,t),M=async(e="",t={})=>{const n=i.getInstance();n.start("useBackOrHome","navigation");try{const a=getCurrentPages(),s=t.delta||1;if(a.length>s){const a=await A.navigateBack(e,t);return n.end("useBackOrHome"),a}const i=t.homePage||"pages/index/index",r=i.startsWith("/")?i:`/${i}`,o=await A.reLaunch({url:r,params:t.homeParams});return n.end("useBackOrHome"),o}catch(e){return n.end("useBackOrHome"),!1}},k=v(F,300),j=async e=>await A.navigateTo(e),B=async e=>await A.redirectTo(e),L=async e=>await A.switchTab(e),z=async e=>await A.reLaunch(e),D=()=>A.getCurrentPageInfo(),U=()=>A.getPageStack(),N=()=>{A.clearQueue()},$=async(e,t=3)=>{for(let n=0;n<t;n++){if(await j(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1},H={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};async function W(e,t={}){const s=i.getInstance();s.start("copyText","clipboard",{textLength:e.length});const r={...H,...t};if(!e||"string"!=typeof e)return r.showToast&&C("复制内容不能为空",!1,"error"),s.end("copyText"),!1;if(e.length>1e4)return r.showToast&&C("复制内容过长",!1,"error"),s.end("copyText"),!1;let o=!1;return o=await n(()=>new Promise(t=>{"undefined"==typeof uni||!uni||"function"!=typeof uni.setClipboardData?t(!1):uni.setClipboardData({data:e,success:()=>{r.showToast&&C(r.successMessage),t(!0)},fail:()=>{r.showToast&&C(r.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_NATIVE_ERROR")??!1,o=await async function(e,t){const s="undefined"!=typeof navigator&&!!navigator,i="undefined"!=typeof window&&!!window,r=s&&navigator.clipboard,o=i&&window.isSecureContext;if(r&&o){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(()=>{if("undefined"==typeof document||"undefined"==typeof window)return t.showToast&&C(t.failMessage),!1;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,r),s.end("copyText"),o}async function G(e={}){const t=i.getInstance();t.start("readClipboard","clipboard");const a={...H,...e},s="undefined"!=typeof navigator&&!!navigator,r="undefined"!=typeof window&&!!window;if(s&&r&&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 Q(){const e="undefined"!=typeof navigator&&!!navigator,t="undefined"!=typeof window&&!!window;return!!(e&&t&&navigator.clipboard&&window.isSecureContext)}async function J(e={}){return await W("",e)}class q{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return q.instance||(q.instance=new q),q.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=i.getInstance();s.start(`setStorage_${e}`,"localStorage");const r=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}`),r??!1}get(e,t){const n=i.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=i.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=q.getInstance();function Y(e,t,n={}){return V.set(e,t,n)}function K(e,t){return V.get(e,t)}function X(e){return e?V.remove(e):V.clear()}async function Z(e,t,a={}){return await n(()=>new Promise(n=>{n(Y(e,t,a))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1}async function ee(e,t){return await n(()=>new Promise(n=>{n(K(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t}function te(){return V.getInfo()}function ne(){return V.cleanExpired()}function ae(e,t={}){const n=i.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 se(e){const t=i.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=K(e)}),t.end("batchGetStorage"),n}const ie={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:"选择文件失败",onPartialInvalid:"fail"};function oe(e,t,n){if(!e)return{valid:!1,message:"文件路径不能为空"};if(t.allowedTypes&&t.allowedTypes.length>0){const a=e.split(".").pop()?.toLowerCase(),s=t.allowedTypes.map(e=>e.toLowerCase()),i=!!n&&s.some(e=>!!e.includes("/")&&(e.endsWith("/*")?n.startsWith(e.slice(0,e.indexOf("/"))):n===e)),r=!!a&&s.some(e=>!e.includes("/")&&e.replace(/^\./,"")===a);if(!i&&!r)return{valid:!1,message:`不支持的文件类型,仅支持:${t.allowedTypes.join(", ")}`}}return{valid:!0}}async function ce(e={}){const t=i.getInstance();t.start("chooseFile","upload",{count:e.count,type:e.type});const a={...re,...e};let s=a.type;var r;("messagefile"===(r=s)?"function"==typeof uni.chooseMessageFile:"local"===r||"image"===r)||(s="image");const o=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,name:e.name,type:e.type}));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)return e;const t=a.maxSize?e.tempFiles.filter(e=>{return!(t=e.size,n=a.maxSize,n&&t>1024*n*1024?{valid:!1,message:`文件大小不能超过 ${n}MB`}:{valid:!0}).valid;var t,n}):[],n="image"===a.type||a.extension.length>0,s=n?e.tempFiles.filter(e=>{const t={url:"",allowedTypes:"image"===a.type&&0===a.extension.length?["image/*"]:a.extension};return!oe(e.path,t,e.type).valid}):[],i=new Set;t.forEach(e=>i.add(e.path)),s.forEach(e=>i.add(e.path));const r=Array.from(i);if(0===r.length)return e;const o=`部分文件不合规:${[a.maxSize?`大小超过 ${a.maxSize}MB`:"",n?"类型不符合要求":""].filter(Boolean).join(",")}`;if("filter"===a.onPartialInvalid){const t=e.tempFiles.filter(e=>!i.has(e.path));return{...e,tempFiles:t,tempFilePaths:t.map(e=>e.path),invalidFiles:r,message:o,success:t.length>0}}return a.showToast&&C(o,!1,"error"),{...e,success:"allow"===a.onPartialInvalid,invalidFiles:r,message:o}}),"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,a){const s=i.getInstance();s.start("uploadFile","upload",{filePath:e});const r={...ie,...t};if(!r.url){const e="上传地址不能为空";return r.showToast&&C(e,!1,"error"),s.end("uploadFile"),{success:!1,message:e}}const o=oe(e,r);if(!o.valid)return r.showToast&&C(o.message,!1,"error"),s.end("uploadFile"),{success:!1,message:o.message};const c=await n(()=>new Promise(t=>{const n=uni.uploadFile({url:r.url,filePath:e,name:r.name,formData:r.formData,header:r.header,timeout:r.timeout,success:n=>{let a;try{a=JSON.parse(n.data)}catch{a=n.data}if(200===n.statusCode)r.showToast&&C(r.successMessage,!1,"success"),t({success:!0,data:a,tempFilePath:e,statusCode:n.statusCode,originalResult:n});else{const e=`上传失败,状态码:${n.statusCode}`;r.showToast&&C(e,!1,"error"),t({success:!1,message:e,statusCode:n.statusCode,originalResult:n})}},fail:n=>{const a=n.errMsg||r.failMessage;r.showToast&&C(a,!1,"error"),t({success:!1,message:a,tempFilePath:e,originalResult:n})}});a&&n&&n.onProgressUpdate(e=>{a({progress:e.progress,totalBytesSent:e.totalBytesSent,totalBytesExpectedToSend:e.totalBytesExpectedToSend})})}),"upload","UPLOAD_FILE_ERROR");return s.end("uploadFile"),c||{success:!1,message:"上传文件失败"}}async function de(e,t={},n){const a=i.getInstance();a.start("chooseAndUploadFile","upload");const s=await ce(t);if(!s.success||!s.tempFilePaths)return a.end("chooseAndUploadFile"),[{success:!1,message:s.message||"选择文件失败"}];const r=s.tempFilePaths.map(t=>le(t,e,n)),o=await Promise.all(r);return a.end("chooseAndUploadFile"),o}async function pe(e,t={},n){return de(e,{...t,type:"image"},n)}function ge(){return"undefined"!=typeof uni&&"function"==typeof uni.uploadFile}async function me(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 he=(e,t,n)=>{const s=i.getInstance();return s.start("weChatOfficialAccountPayment","payment"),new Promise(i=>{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),i(!0)):(n?.(e),i(!1))})}catch(e){s.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),i(!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"),i(!1))})},fe=()=>{const e=i.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 a=s=>{const i=document.createElement("script");i.src=s,i.async=!0,i.onload=()=>{e(!0)},i.onerror=()=>{n++,n<t.length?(document.head.removeChild(i),a(t[n])):(document.head.removeChild(i),e(!1))},document.head.appendChild(i)};a(t[n]),e(!1)}),ye=async e=>{const t=i.getInstance();t.start("configWechatJSSDK","wechat");try{if(!fe())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")}},Re=e=>new Promise(t=>{window.wx&&fe()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),Ee=e=>{a(()=>{window.wx&&fe()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},Te=e=>{a(()=>{window.wx&&fe()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class Se{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return Se.instance||(Se.instance=new Se),Se.instance}async init(e){return this.config=e,this.isConfigured=await ye(e),this.isConfigured}isReady(){return this.isConfigured&&fe()}getConfig(){return this.config}setShareData(e){this.isReady()&&(Ee(e),Te(e))}}const ve="1.0.8";async function Pe(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 o}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},6e4)}}export{t as ErrorHandler,i as PerformanceMonitor,e as UniAppToolsError,ve as VERSION,Se as WechatSDK,se as batchGetStorage,ae as batchSetStorage,Re as checkWechatJSAPI,de as chooseAndUploadFile,pe as chooseAndUploadImage,ce as chooseFile,ue as chooseImage,ne as cleanExpiredStorage,J as clearClipboard,N as clearNavigationQueue,X as clearStorageSync,ye as configWechatJSSDK,W as copyText,v as debounce,E as deepClone,S as deepMerge,O as extractUrlParts,p as getCurrentEnv,D as getCurrentPageInfo,me as getFileInfo,I as getH5UrlParams,h as getMenuButtonBoundingClientRect,f as getNavHeight,U as getPageStack,d as getPlatform,m as getStatusBarHeight,ee as getStorage,te as getStorageInfo,K as getStorageSync,w as getTopNavBarHeight,Pe as initUniAppTools,Q as isClipboardSupported,ge as isUploadSupported,fe as isWechat,we as loadWechatJSSDK,r as measurePerformance,T as mergeObjects,j as navigateTo,g as onCheckForUpdate,z as reLaunch,G as readClipboard,B as redirectTo,n as safeAsync,$ as safeNavigateTo,a as safeSync,R as setPageIcon,y as setPageTitle,Z as setStorage,Y as setStorageSync,Te as shareToFriend,Ee as shareToTimeline,L as switchTab,P as throttle,le as uploadFile,F as useBack,k as useBackDebounced,M as useBackOrHome,_ as useDeepCopyByObj,C as useToast,x as useTryCatch,l as useWindowInfo,he as weChatOfficialAccountPayment};
|
|
1
|
+
import{areaList as e,useCascaderAreaData as t}from"@vant/area-data";class n extends Error{code;module;timestamp;constructor(e,t,n){super(t),this.name="UniAppToolsError",this.code=e,this.module=n,this.timestamp=Date.now()}}class s{static instance;errorCallbacks=[];static getInstance(){return s.instance||(s.instance=new s),s.instance}onError(e){this.errorCallbacks.push(e)}handleError(e,t){const s={code:e instanceof n?e.code:"UNKNOWN_ERROR",message:e.message,module:e instanceof n?e.module:t,timestamp:e instanceof n?e.timestamp:Date.now(),stack:e.stack};this.errorCallbacks.forEach(e=>{try{e(s)}catch(e){}})}createModuleErrorHandler(e){return(t,s,r)=>{const a=new n(t,s,e);return r&&(a.stack=r.stack),this.handleError(a,e),a}}}async function r(e,t,n="ASYNC_ERROR"){try{return await e()}catch(e){return s.getInstance().createModuleErrorHandler(t)(n,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function a(e,t,n="SYNC_ERROR",r=null){try{return e()}catch(e){return s.getInstance().createModuleErrorHandler(t)(n,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),r}}var o=Object.freeze({__proto__:null,ErrorHandler:s,UniAppToolsError:n,safeAsync:r,safeSync:a});function i(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}class c{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return c.instance||(c.instance=new c),c.instance}start(e,t,n){const s={name:e,startTime:i(),module:t,metadata:n};this.metrics.set(e,s)}end(e){const t=this.metrics.get(e);return t?(t.endTime=i(),t.duration=t.endTime-t.startTime,this.metrics.delete(e),this.completedMetrics.push(t),this.completedMetrics.length>this.maxStoredMetrics&&this.completedMetrics.shift(),t):null}getReport(){const e={},t={};this.completedMetrics.forEach(n=>{e[n.module]||(e[n.module]=[]),e[n.module].push(n);const s=`${n.module}.${n.name}`;t[s]||(t[s]={total:0,count:0}),t[s].total+=n.duration||0,t[s].count+=1});const n={};Object.entries(t).forEach(([e,t])=>{n[e]=t.total/t.count});const s=[...this.completedMetrics].sort((e,t)=>(t.duration||0)-(e.duration||0)).slice(0,10);return{byModule:e,slowest:s,average:n}}clear(){this.metrics.clear(),this.completedMetrics=[]}}function u(e){return function(t,n,s){const r=s.value;s.value=function(...s){const a=c.getInstance(),o=`${t.constructor.name}.${n}`;a.start(o,e,{args:s.length});try{const e=r.apply(this,s);return e instanceof Promise?e.finally(()=>{a.end(o)}):(a.end(o),e)}catch(e){throw a.end(o),e}}}}var l=Object.freeze({__proto__:null,PerformanceMonitor:c,measurePerformance:u});class m{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return m.instance||(m.instance=new m),m.instance}set(e,t,n=this.defaultTTL){this.cache.set(e,{data:t,timestamp:Date.now(),ttl:n})}get(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttl?(this.cache.delete(e),null):t.data:null}clear(){this.cache.clear()}}const p=m.getInstance(),d=(e=!0)=>{const t=c.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=p.get(n);if(e)return t.end("getWindowInfo"),e}const s=a(()=>{const t=uni.getWindowInfo();return e&&p.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),s},h=()=>{const e="platform",t=p.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",p.set(e,"h5"),"h5"},f=()=>{try{const e=uni.getAccountInfoSync();return{appId:e.miniProgram?.appId||"",version:e.miniProgram?.version||"",envVersion:e.miniProgram?.envVersion||"",accountInfo:e}}catch(e){return{appId:"",version:"",envVersion:"",accountInfo:null}}},g=()=>{try{const e=uni.getUpdateManager();e.onCheckForUpdate(function(e){e.hasUpdate}),e.onUpdateReady(function(t){uni.showModal({title:"更新提示",content:"新版本已经准备好,是否重启应用?",showCancel:!0,cancelText:"稍后",confirmText:"立即重启",success(t){t.confirm&&e.applyUpdate()}})}),e.onUpdateFailed(function(e){uni.showModal({title:"更新失败",content:"新版本下载失败,请检查网络连接或稍后重试",showCancel:!1,confirmText:"知道了"})})}catch(e){}},w=()=>{try{return uni.getSystemInfoSync().statusBarHeight||0}catch(e){return 0}},y=()=>{try{const e=h();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},S=()=>{try{const e=w(),t=h();if("weixin"===t||"alipay"===t){const t=y();if(t){return t.height+e}}return e+0}catch(e){return w()+0}},E=()=>{try{const e=w();return{statusBarHeight:e,navHeight:S()}}catch(e){return{statusBarHeight:0,navHeight:44}}},T=e=>e&&"string"==typeof e?new Promise(t=>{try{uni.setNavigationBarTitle({title:e,success:()=>{t(!0)},fail:e=>{t(!1)}})}catch(e){t(!1)}}):Promise.resolve(!1),P=(e,t="image/x-icon")=>a(()=>{const n=h();if(("h5"===n||"web"===n)&&"undefined"!=typeof document){document.querySelectorAll('link[rel*="icon"]').forEach(e=>e.remove());const n=document.createElement("link");return n.rel="icon",n.type=t,n.href=e,document.head.appendChild(n),!0}return!1},"system","SET_PAGE_ICON_ERROR",!1);function R(e){if(null===e||"object"!=typeof e)return e;try{if("undefined"!=typeof structuredClone)try{return structuredClone(e)}catch(e){}return JSON.parse(JSON.stringify(e))}catch(e){throw new Error(`深拷贝失败: ${e instanceof Error?e.message:String(e)}`)}}function v(e,t){return Object.assign(e,t)}function x(e,t){const n=R(e);return function e(t,n){for(const s in n)if(n.hasOwnProperty(s)){const r=n[s],a=t[s];r&&"object"==typeof r&&!Array.isArray(r)&&a&&"object"==typeof a&&!Array.isArray(a)?e(a,r):t[s]=R(r)}}(n,t),n}function I(e,t,n=!1){let s,r=null;const a=function(...a){const o=n&&!r;return r&&clearTimeout(r),r=setTimeout(()=>{r=null,n||(s=e.apply(this,a))},t),o&&(s=e.apply(this,a)),s};return a.cancel=()=>{r&&(clearTimeout(r),r=null)},a}function F(e,t,n={}){let s,r=null,a=0;const{leading:o=!0,trailing:i=!0}=n,c=function(...n){const c=Date.now();a||o||(a=c);const u=t-(c-a);return u<=0||u>t?(r&&(clearTimeout(r),r=null),a=c,s=e.apply(this,n)):!r&&i&&(r=setTimeout(()=>{a=o?Date.now():0,r=null,s=e.apply(this,n)},u)),s};return c.cancel=()=>{r&&(clearTimeout(r),r=null),a=0},c}function C(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return v(e,R(t))}return R(t)}const A=e=>{try{if("undefined"==typeof window||!window.location)throw new Error("不在 H5 浏览器环境中");const t=new URLSearchParams(window.location.search),n={};return t.forEach((e,t)=>{try{n[t]=decodeURIComponent(e)}catch(s){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return e?null:{}}};function _(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,s={};return t.searchParams.forEach((e,t)=>{s[t]=e}),{path:n,params:s}}catch(e){return{path:"",params:{}}}}function M(e,t={}){return async(...n)=>{try{return{data:await e(...n),error:null}}catch(e){return t.onError?.(e),{data:null,error:e}}finally{t.onFinally?.()}}}const O=e,b=t;function z(){return t()}const j=(e="",t=!1,n="none",s=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:s})};function D(e,t){if(!t||0===Object.keys(t).length)return e;const n=Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");return e+(e.includes("?")?"&":"?")+n}async function k(e){return new Promise(t=>{const n=D(e.url,e.params);uni.navigateTo({url:n,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>t(!0),fail:e=>{t(!1)}})})}async function L(e){return new Promise(t=>{const n=D(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}async function U(e="",t={}){return new Promise(n=>{const s=t.delta||1,r=t.timeout||5e3;if(getCurrentPages().length<=s)return void n(!1);const a=setTimeout(()=>{n(!1)},r);uni.navigateBack({delta:s,success:()=>{clearTimeout(a),setTimeout(()=>{try{const t=getCurrentPages();if(t.length>0){const n=t[t.length-1];n.$vm&&"function"==typeof n.$vm.init&&n.$vm.init(e)}n(!0)}catch(e){n(!0)}},100)},fail:e=>{clearTimeout(a),n(!1)}})})}async function W(e="",t={}){const n=getCurrentPages(),s=t.delta||1;if(n.length>s)return await U(e,t);const r=t.homePage||"pages/index/index",a=r.startsWith("/")?r:`/${r}`;return await $({url:a,params:t.homeParams})}const B=I(U,300);async function N(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:e=>{t(!1)}})})}async function $(e){return new Promise(t=>{const n=D(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}function H(){try{const e=getCurrentPages();if(0===e.length)return null;const t=e[e.length-1];return{route:t.route||"",options:t.options||{}}}catch(e){return null}}function J(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return[]}}async function q(e,t=3){for(let n=0;n<t;n++){if(await k(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1}const G={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};async function Y(e,t={}){const n=c.getInstance();n.start("copyText","clipboard",{textLength:e.length});const s={...G,...t};if(!e||"string"!=typeof e)return s.showToast&&j("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return s.showToast&&j("复制内容过长",!1,"error"),n.end("copyText"),!1;const a=await r(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{s.showToast&&j(s.successMessage),t(!0)},fail:()=>{s.showToast&&j(s.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),a}class K{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return K.instance||(K.instance=new K),K.instance}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,n={}){try{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const s={value:t,timestamp:Date.now(),ttl:n.ttl},r=JSON.stringify(s);if(r.length>1048576)throw new Error("存储数据过大");if(uni.setStorageSync(e,r),this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}return this.cache.set(e,s),!0}catch(e){throw e}}get(e,t){try{if(!e||"string"!=typeof e)return t;if(this.cache.has(e)){const n=this.cache.get(e);return this.isExpired(n)?(this.cache.delete(e),this.remove(e),t):n.value}const n=uni.getStorageSync(e);if(!n||"string"!=typeof n)return t;const s=JSON.parse(n);let r;return r=s&&"object"==typeof s&&"value"in s&&"timestamp"in s?s:{value:s,timestamp:Date.now()},this.isExpired(r)?(this.remove(e),t):(this.cache.set(e,r),r.value)}catch(e){return t}}remove(e){try{return!(!e||"string"!=typeof e)&&(uni.removeStorageSync(e),this.cache.delete(e),!0)}catch(e){return!1}}clear(){try{return uni.clearStorageSync(),this.cache.clear(),!0}catch(e){return!1}}getInfo(){try{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}}catch(e){return{keys:[],currentSize:0,limitSize:0}}}cleanExpired(){try{const e=this.getInfo();let t=0;return e.keys.forEach(e=>{void 0===this.get(e)&&t++}),t}catch(e){return 0}}}const V=K.getInstance();function X(e,t,n={}){return V.set(e,t,n)}function Q(e,t){return V.get(e,t)}function Z(e){return e?V.remove(e):V.clear()}async function ee(e,t,n={}){return await r(()=>new Promise(s=>{s(X(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1}async function te(e,t){return await r(()=>new Promise(n=>{n(Q(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t}function ne(){return V.getInfo()}function se(){return V.cleanExpired()}function re(e,t={}){const n=c.getInstance();n.start("batchSetStorage","localStorage");let s=0;return Object.entries(e).forEach(([e,n])=>{X(e,n,t)&&s++}),n.end("batchSetStorage"),s}function ae(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=Q(e)}),t.end("batchGetStorage"),n}const oe={name:"file",maxSize:10,allowedTypes:["jpg","jpeg","png","gif","webp"],showToast:!0,timeout:6e4,successMessage:"上传成功",failMessage:"上传失败"},ie={type:"image",count:1,sizeType:["original","compressed"],sourceType:["album","camera"],extension:[],maxSize:10,showToast:!0,failMessage:"选择文件失败"};async function ce(e={}){const t=c.getInstance();t.start("chooseFile","upload",{count:e.count,type:e.type});const n={...ie,...e};let s=n.type;var a;("messagefile"===(a=s)?"function"==typeof uni.chooseMessageFile:"local"===a||"image"===a)||(s="image");const o=await r(()=>new Promise(e=>{const t=t=>{const r=t.errMsg||n.failMessage;n.showToast&&j(r,!1,"error"),e({success:!1,message:r,type:s})};"image"!==s&&"local"!==s?"messagefile"===s?uni.chooseMessageFile({count:n.count,type:"all",success:t=>{e({success:!0,tempFilePaths:t.tempFiles.map(e=>e.path),tempFiles:t.tempFiles,type:"messagefile"})},fail:t}):"image"===s?uni.chooseImage({count:n.count,sizeType:n.sizeType,sourceType:n.sourceType,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"image"})},fail:t}):"local"===s&&("function"==typeof uni.chooseFile?uni.chooseFile({count:n.count,extension:n.extension,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"local"})},fail:t}):e({success:!1,message:"当前平台不支持选择本地文件",type:s})):function(e,t){const n=document.createElement("input");n.type="file",n.multiple=e.count>1,"image"===e.type?n.accept="image/*":e.extension.length>0&&(n.accept=e.extension.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),n.onchange=s=>{const r=s.target.files;if(r&&r.length>0){const n=Array.from(r).map(e=>({path:URL.createObjectURL(e),size:e.size,name:e.name,type:e.type,file:e})),s=n.map(e=>({path:e.path,size:e.size}));t({success:!0,tempFilePaths:n.map(e=>e.path),tempFiles:s,type:e.type})}else t({success:!1,message:"用户取消选择",type:e.type});document.body.removeChild(n)},n.style.display="none",document.body.appendChild(n),n.click()}(n,e)}).then(e=>{if(!e.success||!e.tempFiles||!n.maxSize)return e;if(e.tempFiles.filter(e=>{var t,s;return!(t=e.size,(s=n.maxSize)&&t>1024*s*1024?{valid:!1,message:`文件大小不能超过 ${s}MB`}:{valid:!0}).valid}).length>0){const t=`部分文件大小超过 ${n.maxSize}MB 限制`;return n.showToast&&j(t,!1,"error"),{...e,success:!1,message:t}}return e}),"upload","CHOOSE_FILE_ERROR");return t.end("chooseFile"),o||{success:!1,message:"选择文件失败",type:s}}async function ue(e={}){const t=await ce({...e,type:"image"});return{success:t.success,tempFilePaths:t.tempFilePaths,tempFiles:t.tempFiles,message:t.message}}async function le(e,t,n){const s=c.getInstance();s.start("uploadFile","upload",{filePath:e});const a={...oe,...t};if(!a.url){const e="上传地址不能为空";return a.showToast&&j(e,!1,"error"),s.end("uploadFile"),{success:!1,message:e}}const o=function(e,t){if(!e)return{valid:!1,message:"文件路径不能为空"};if(t.allowedTypes&&t.allowedTypes.length>0){const n=e.split(".").pop()?.toLowerCase();if(!n||!t.allowedTypes.includes(n))return{valid:!1,message:`不支持的文件类型,仅支持:${t.allowedTypes.join(", ")}`}}return{valid:!0}}(e,a);if(!o.valid)return a.showToast&&j(o.message,!1,"error"),s.end("uploadFile"),{success:!1,message:o.message};const i=await r(()=>new Promise(t=>{const s=uni.uploadFile({url:a.url,filePath:e,name:a.name,formData:a.formData,header:a.header,timeout:a.timeout,success:n=>{let s;try{s=JSON.parse(n.data)}catch{s=n.data}if(200===n.statusCode)a.showToast&&j(a.successMessage,!1,"success"),t({success:!0,data:s,tempFilePath:e,statusCode:n.statusCode});else{const e=`上传失败,状态码:${n.statusCode}`;a.showToast&&j(e,!1,"error"),t({success:!1,message:e,statusCode:n.statusCode})}},fail:n=>{const s=n.errMsg||a.failMessage;a.showToast&&j(s,!1,"error"),t({success:!1,message:s,tempFilePath:e})}});n&&s&&s.onProgressUpdate(e=>{n({progress:e.progress,totalBytesSent:e.totalBytesSent,totalBytesExpectedToSend:e.totalBytesExpectedToSend})})}),"upload","UPLOAD_FILE_ERROR");return s.end("uploadFile"),i||{success:!1,message:"上传文件失败"}}async function me(e,t={},n){const s=c.getInstance();s.start("chooseAndUploadFile","upload");const r=await ce(t);if(!r.success||!r.tempFilePaths)return s.end("chooseAndUploadFile"),[{success:!1,message:r.message||"选择文件失败"}];const a=r.tempFilePaths.map(t=>le(t,e,n)),o=await Promise.all(a);return s.end("chooseAndUploadFile"),o}async function pe(e,t={},n){return me(e,{...t,type:"image"},n)}function de(){return"undefined"!=typeof uni&&"function"==typeof uni.chooseImage&&"function"==typeof uni.uploadFile}async function he(e){return await r(()=>new Promise((t,n)=>{uni.getFileInfo({filePath:e,digestAlgorithm:"md5",success:e=>{const n=e;t({size:n.size,digest:n.digest})},fail:n})}),"upload","GET_FILE_INFO_ERROR")}const fe=(e,t,n)=>{const s=c.getInstance();return s.start("weChatOfficialAccountPayment","payment"),new Promise(r=>{a(()=>{if("undefined"==typeof window||!window.navigator)throw new Error("不在浏览器环境中,无法调用微信支付");if(!(e&&e.appId&&e.timeStamp&&e.nonceStr&&e.package&&e.paySign))throw new Error("微信支付配置参数不完整");function a(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){s.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),r(!0)):(n?.(e),r(!1))})}catch(e){s.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),r(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",a,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",a),e.attachEvent("onWeixinJSBridgeReady",a))}else a();return!0},"payment","WECHAT_PAY_ERROR",!1)||(s.end("weChatOfficialAccountPayment"),r(!1))})},ge=()=>{const e=c.getInstance();e.start("isWechat","system");const t=a(()=>{if("undefined"!=typeof navigator&&navigator.userAgent){return navigator.userAgent.toLowerCase().includes("micromessenger")}return!1},"system","IS_WECHAT_ERROR",!1);return e.end("isWechat"),t||!1},we=()=>new Promise(e=>{if("undefined"!=typeof window&&window.wx)return void e(!0);const t=["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];let n=0;const s=r=>{const a=document.createElement("script");a.src=r,a.async=!0,a.onload=()=>{e(!0)},a.onerror=()=>{n++,n<t.length?(document.head.removeChild(a),s(t[n])):(document.head.removeChild(a),e(!1))},document.head.appendChild(a)};s(t[n]),e(!1)}),ye=async e=>{const t=c.getInstance();t.start("configWechatJSSDK","wechat");try{if(!ge())return!1;return!!await we()&&new Promise(t=>{window.wx?(window.wx.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),window.wx.ready(()=>{t(!0)}),window.wx.error(e=>{t(!1)})):t(!1),t(!1)})}catch(e){return!1}finally{t.end("configWechatJSSDK")}},Se=e=>new Promise(t=>{window.wx&&ge()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),Ee=e=>{a(()=>{window.wx&&ge()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},Te=e=>{a(()=>{window.wx&&ge()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class Pe{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return Pe.instance||(Pe.instance=new Pe),Pe.instance}async init(e){return this.config=e,this.isConfigured=await ye(e),this.isConfigured}isReady(){return this.isConfigured&&ge()}getConfig(){return this.config}setShareData(e){this.isReady()&&(Ee(e),Te(e))}}const Re="1.0.8";async function ve(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,onError:s=null,performanceReportInterval:r=0}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return o}),t=e.getInstance();"function"==typeof s?t.onError(s):t.onError(e=>{})}if(t&&r>0){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return l}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},r)}}export{s as ErrorHandler,c as PerformanceMonitor,n as UniAppToolsError,Re as VERSION,Pe as WechatSDK,O as areaList,ae as batchGetStorage,re as batchSetStorage,Se as checkWechatJSAPI,me as chooseAndUploadFile,pe as chooseAndUploadImage,ce as chooseFile,ue as chooseImage,se as cleanExpiredStorage,Z as clearStorageSync,ye as configWechatJSSDK,Y as copyText,I as debounce,R as deepClone,x as deepMerge,_ as extractUrlParts,f as getCurrentEnv,H as getCurrentPageInfo,he as getFileInfo,A as getH5UrlParams,y as getMenuButtonBoundingClientRect,S as getNavHeight,J as getPageStack,h as getPlatform,w as getStatusBarHeight,te as getStorage,ne as getStorageInfo,Q as getStorageSync,E as getTopNavBarHeight,ve as initUniAppTools,de as isUploadSupported,ge as isWechat,we as loadWechatJSSDK,u as measurePerformance,v as mergeObjects,k as navigateTo,g as onCheckForUpdate,$ as reLaunch,L as redirectTo,r as safeAsync,q as safeNavigateTo,a as safeSync,P as setPageIcon,T as setPageTitle,ee as setStorage,X as setStorageSync,Te as shareToFriend,Ee as shareToTimeline,N as switchTab,F as throttle,le as uploadFile,U as useBack,B as useBackDebounced,W as useBackOrHome,b as useCascaderAreaData,C as useDeepCopyByObj,z as useRegions,j as useToast,M as useTryCatch,d as useWindowInfo,fe as weChatOfficialAccountPayment};
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* 导航相关工具函数(简化优化版本)
|
|
3
|
+
*
|
|
4
|
+
* 优化说明:
|
|
5
|
+
* 1. 移除导航队列(uni-app 框架已处理导航冲突)
|
|
6
|
+
* 2. 移除单例模式(不需要状态管理)
|
|
7
|
+
* 3. 移除 safeAsync 包装(让错误自然抛出)
|
|
8
|
+
* 4. 移除性能监控(在开发环境手动测量即可)
|
|
9
|
+
* 5. 简化代码逻辑,提升可维护性
|
|
3
10
|
*/
|
|
4
11
|
/**
|
|
5
12
|
* 导航配置选项
|
|
@@ -7,8 +14,6 @@
|
|
|
7
14
|
interface NavigationOptions {
|
|
8
15
|
delta?: number;
|
|
9
16
|
timeout?: number;
|
|
10
|
-
enableDebounce?: boolean;
|
|
11
|
-
debounceWait?: number;
|
|
12
17
|
}
|
|
13
18
|
/**
|
|
14
19
|
* 页面跳转选项
|
|
@@ -21,59 +26,59 @@ interface NavigateOptions {
|
|
|
21
26
|
events?: Record<string, Function>;
|
|
22
27
|
}
|
|
23
28
|
/**
|
|
24
|
-
*
|
|
29
|
+
* 跳转到指定页面
|
|
30
|
+
* @param options 导航选项
|
|
31
|
+
* @returns Promise<boolean> 是否成功
|
|
25
32
|
*/
|
|
26
|
-
|
|
27
|
-
homePage?: string;
|
|
28
|
-
homeParams?: Record<string, any>;
|
|
29
|
-
}
|
|
33
|
+
export declare function navigateTo(options: NavigateOptions): Promise<boolean>;
|
|
30
34
|
/**
|
|
31
|
-
*
|
|
32
|
-
* @param params 返回上一页时传入的参数
|
|
35
|
+
* 重定向到指定页面
|
|
33
36
|
* @param options 导航选项
|
|
34
37
|
* @returns Promise<boolean> 是否成功
|
|
35
38
|
*/
|
|
36
|
-
export declare
|
|
39
|
+
export declare function redirectTo(options: NavigateOptions): Promise<boolean>;
|
|
37
40
|
/**
|
|
38
|
-
*
|
|
41
|
+
* 返回上一页
|
|
39
42
|
* @param params 返回上一页时传入的参数
|
|
40
43
|
* @param options 导航选项
|
|
41
44
|
* @returns Promise<boolean> 是否成功
|
|
42
45
|
*/
|
|
43
|
-
export declare
|
|
46
|
+
export declare function useBack(params?: any, options?: NavigationOptions): Promise<boolean>;
|
|
44
47
|
/**
|
|
45
|
-
*
|
|
48
|
+
* 返回上一页或跳转首页选项
|
|
46
49
|
*/
|
|
47
|
-
|
|
50
|
+
interface BackOrHomeOptions extends NavigationOptions {
|
|
51
|
+
homePage?: string;
|
|
52
|
+
homeParams?: Record<string, any>;
|
|
53
|
+
}
|
|
48
54
|
/**
|
|
49
|
-
*
|
|
55
|
+
* 返回上一页,若没有上一页则重定向到首页
|
|
56
|
+
* @param params 返回上一页时传入的参数
|
|
50
57
|
* @param options 导航选项
|
|
51
58
|
* @returns Promise<boolean> 是否成功
|
|
52
59
|
*/
|
|
53
|
-
export declare
|
|
60
|
+
export declare function useBackOrHome(params?: any, options?: BackOrHomeOptions): Promise<boolean>;
|
|
54
61
|
/**
|
|
55
|
-
*
|
|
56
|
-
* @param options 导航选项
|
|
57
|
-
* @returns Promise<boolean> 是否成功
|
|
62
|
+
* 防抖版本的返回上一页
|
|
58
63
|
*/
|
|
59
|
-
export declare const
|
|
64
|
+
export declare const useBackDebounced: typeof useBack;
|
|
60
65
|
/**
|
|
61
66
|
* 切换到Tab页面
|
|
62
67
|
* @param url Tab页面路径
|
|
63
68
|
* @returns Promise<boolean> 是否成功
|
|
64
69
|
*/
|
|
65
|
-
export declare
|
|
70
|
+
export declare function switchTab(url: string): Promise<boolean>;
|
|
66
71
|
/**
|
|
67
72
|
* 重新启动到指定页面
|
|
68
73
|
* @param options 导航选项
|
|
69
74
|
* @returns Promise<boolean> 是否成功
|
|
70
75
|
*/
|
|
71
|
-
export declare
|
|
76
|
+
export declare function reLaunch(options: NavigateOptions): Promise<boolean>;
|
|
72
77
|
/**
|
|
73
78
|
* 获取当前页面信息
|
|
74
79
|
* @returns 当前页面信息
|
|
75
80
|
*/
|
|
76
|
-
export declare
|
|
81
|
+
export declare function getCurrentPageInfo(): {
|
|
77
82
|
route: string;
|
|
78
83
|
options: any;
|
|
79
84
|
} | null;
|
|
@@ -81,19 +86,15 @@ export declare const getCurrentPageInfo: () => {
|
|
|
81
86
|
* 获取页面栈信息
|
|
82
87
|
* @returns 页面栈数组
|
|
83
88
|
*/
|
|
84
|
-
export declare
|
|
89
|
+
export declare function getPageStack(): Array<{
|
|
85
90
|
route: string;
|
|
86
91
|
options: any;
|
|
87
92
|
}>;
|
|
88
|
-
/**
|
|
89
|
-
* 清空导航队列
|
|
90
|
-
*/
|
|
91
|
-
export declare const clearNavigationQueue: () => void;
|
|
92
93
|
/**
|
|
93
94
|
* 安全的页面跳转(带重试机制)
|
|
94
95
|
* @param options 导航选项
|
|
95
96
|
* @param maxRetries 最大重试次数
|
|
96
97
|
* @returns Promise<boolean> 是否成功
|
|
97
98
|
*/
|
|
98
|
-
export declare
|
|
99
|
+
export declare function safeNavigateTo(options: NavigateOptions, maxRetries?: number): Promise<boolean>;
|
|
99
100
|
export {};
|
package/dist/upload/index.d.ts
CHANGED
|
@@ -51,8 +51,6 @@ export interface ChooseFileConfig {
|
|
|
51
51
|
showToast?: boolean;
|
|
52
52
|
/** 失败提示信息 */
|
|
53
53
|
failMessage?: string;
|
|
54
|
-
/** 当存在不合规文件(大小/类型)时的处理策略,默认 'fail' */
|
|
55
|
-
onPartialInvalid?: 'fail' | 'filter' | 'allow';
|
|
56
54
|
}
|
|
57
55
|
/**
|
|
58
56
|
* 选择图片配置接口(向后兼容)
|
|
@@ -73,8 +71,6 @@ export interface UploadResult {
|
|
|
73
71
|
tempFilePath?: string;
|
|
74
72
|
/** HTTP 状态码 */
|
|
75
73
|
statusCode?: number;
|
|
76
|
-
/** 原始结果(便于调试与错误定位) */
|
|
77
|
-
originalResult?: any;
|
|
78
74
|
}
|
|
79
75
|
/**
|
|
80
76
|
* 选择文件结果接口
|
|
@@ -88,17 +84,11 @@ export interface ChooseFileResult {
|
|
|
88
84
|
tempFiles?: Array<{
|
|
89
85
|
path: string;
|
|
90
86
|
size: number;
|
|
91
|
-
/** 文件名(H5 可用,其他平台可能缺失) */
|
|
92
|
-
name?: string;
|
|
93
|
-
/** MIME 类型(H5 可用)或基于扩展名推断 */
|
|
94
|
-
type?: string;
|
|
95
87
|
}>;
|
|
96
88
|
/** 提示信息 */
|
|
97
89
|
message?: string;
|
|
98
90
|
/** 文件选择类型 */
|
|
99
91
|
type: FileSelectType;
|
|
100
|
-
/** 不合规文件(路径列表),用于业务自行提示或过滤 */
|
|
101
|
-
invalidFiles?: string[];
|
|
102
92
|
}
|
|
103
93
|
/**
|
|
104
94
|
* 选择图片结果接口(向后兼容)
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 工具函数库
|
|
3
3
|
*/
|
|
4
|
+
import { useCascaderAreaData as vantUseCascaderAreaData } from '@vant/area-data';
|
|
4
5
|
/**
|
|
5
|
-
*
|
|
6
|
+
* 高性能深拷贝实现(uni-app 多端兼容版本)
|
|
6
7
|
* @param obj 要拷贝的对象
|
|
7
8
|
* @returns 深拷贝后的对象
|
|
8
|
-
* @description
|
|
9
|
+
* @description 兼容小程序、App、H5 多端环境的深拷贝实现
|
|
9
10
|
*/
|
|
10
11
|
export declare function deepClone<T>(obj: T): T;
|
|
11
12
|
/**
|
|
12
|
-
*
|
|
13
|
+
* 浅拷贝对象合并
|
|
13
14
|
* @param target 目标对象
|
|
14
15
|
* @param source 源对象
|
|
15
16
|
* @returns 合并后的目标对象
|
|
@@ -53,10 +54,10 @@ export interface UrlParams {
|
|
|
53
54
|
[key: string]: string;
|
|
54
55
|
}
|
|
55
56
|
/**
|
|
56
|
-
* 获取 H5 环境下的 URL
|
|
57
|
+
* 获取 H5 环境下的 URL 参数
|
|
57
58
|
* @param paramName 可选,指定要获取的参数名
|
|
58
59
|
* @returns 如果指定参数名则返回对应值或null,否则返回所有参数对象
|
|
59
|
-
* @description 在 H5 环境中解析 URL
|
|
60
|
+
* @description 在 H5 环境中解析 URL 参数
|
|
60
61
|
*/
|
|
61
62
|
export declare const getH5UrlParams: (paramName?: string) => string | null | UrlParams;
|
|
62
63
|
/**
|
|
@@ -88,3 +89,45 @@ export declare function useTryCatch<T extends (...args: any[]) => any>(fn: T, op
|
|
|
88
89
|
data: Awaited<ReturnType<T>> | null;
|
|
89
90
|
error: unknown;
|
|
90
91
|
}>;
|
|
92
|
+
/**
|
|
93
|
+
* 中国省市区数据
|
|
94
|
+
* @description 包含省、市、区三级行政区划数据,数据来源于 @vant/area-data
|
|
95
|
+
*/
|
|
96
|
+
export declare const areaList: {
|
|
97
|
+
province_list: Record<string, string>;
|
|
98
|
+
city_list: Record<string, string>;
|
|
99
|
+
county_list: Record<string, string>;
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* 级联选择器选项类型
|
|
103
|
+
*/
|
|
104
|
+
export interface CascaderOption {
|
|
105
|
+
text: string;
|
|
106
|
+
value: string;
|
|
107
|
+
children?: CascaderOption[];
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* 生成级联选择器所需的省市区数据
|
|
111
|
+
* @returns 级联选择器数据数组
|
|
112
|
+
* @description 将 areaList 转换为级联选择器组件所需的树形结构数据,数据来源于 @vant/area-data
|
|
113
|
+
* @example
|
|
114
|
+
* ```ts
|
|
115
|
+
* import { useCascaderAreaData } from 'uniapp-tool-functions';
|
|
116
|
+
*
|
|
117
|
+
* const cascaderData = useCascaderAreaData();
|
|
118
|
+
* ```
|
|
119
|
+
*/
|
|
120
|
+
export declare const useCascaderAreaData: typeof vantUseCascaderAreaData;
|
|
121
|
+
/**
|
|
122
|
+
* 生成中国省市区级联数据
|
|
123
|
+
* @returns 级联选择器数据数组
|
|
124
|
+
* @description 此函数是 useCascaderAreaData 的别名,用于生成省市区三级联动数据
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* import { useRegions } from 'uniapp-tool-functions';
|
|
128
|
+
*
|
|
129
|
+
* const regions = useRegions();
|
|
130
|
+
* console.log(regions); // 返回省市区三级联动数据
|
|
131
|
+
* ```
|
|
132
|
+
*/
|
|
133
|
+
export declare function useRegions(): CascaderOption[];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "my-uniapp-tools",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "一个功能强大、性能优化的 uni-app 开发工具库,提供剪贴板、本地存储、导航、系统信息等常用功能",
|
|
6
6
|
"main": "dist/my-uniapp-tools.cjs.js",
|
|
@@ -60,6 +60,7 @@
|
|
|
60
60
|
"@dcloudio/types": "^3.0.0"
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
|
+
"@vant/area-data": "^2.1.0",
|
|
63
64
|
"tslib": "^2.8.1"
|
|
64
65
|
},
|
|
65
66
|
"devDependencies": {
|