qsh-webview-sdk 2.0.6 → 2.0.8
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 +32 -9
- package/dist/index.d.ts +86 -17
- package/dist/qsh-webview-sdk.es.js +1152 -892
- package/dist/qsh-webview-sdk.es.js.map +1 -1
- package/dist/qsh-webview-sdk.umd.js +1 -1
- package/dist/qsh-webview-sdk.umd.js.map +1 -1
- package/package.json +47 -47
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(I,m){typeof exports=="object"&&typeof module!="undefined"?module.exports=m():typeof define=="function"&&define.amd?define(m):(I=typeof globalThis!="undefined"?globalThis:I||self,I.qsh=m())})(this,function(){"use strict";var cn=Object.defineProperty,un=Object.defineProperties;var ln=Object.getOwnPropertyDescriptors;var yt=Object.getOwnPropertySymbols;var dn=Object.prototype.hasOwnProperty,fn=Object.prototype.propertyIsEnumerable;var Ce=(I,m,p)=>m in I?cn(I,m,{enumerable:!0,configurable:!0,writable:!0,value:p}):I[m]=p,h=(I,m)=>{for(var p in m||(m={}))dn.call(m,p)&&Ce(I,p,m[p]);if(yt)for(var p of yt(m))fn.call(m,p)&&Ce(I,p,m[p]);return I},N=(I,m)=>un(I,ln(m));var $=(I,m,p)=>Ce(I,typeof m!="symbol"?m+"":m,p);var E=(I,m,p)=>new Promise((Z,G)=>{var Q=v=>{try{V(p.next(v))}catch(ie){G(ie)}},ee=v=>{try{V(p.throw(v))}catch(ie){G(ie)}},V=v=>v.done?Z(v.value):Promise.resolve(v.value).then(Q,ee);V((p=p.apply(I,m)).next())});function I(){return typeof window!="undefined"?window:void 0}function m(){return typeof navigator=="undefined"?"":navigator.userAgent||""}function p(){const t=I();if(!t)return!1;if(t.__wxjs_environment==="miniprogram"||t.wx&&t.wx.miniProgram)return!0;const e=m();return!!(e&&/micromessenger/i.test(e)&&/miniProgram/i.test(e))}function Z(){const t=I();return!!(t&&t.plus)}function G(){const t=I();return!!(t&&(t.__dcloud_weex_postMessage||t.__dcloud_weex_))}function Q(){const t=I();return!!(t&&(t.__uniapp_x_postMessage||t.__uniapp_x_))}function ee(){const t=m();return/uni-app/i.test(t)}function V(){const t=m();return/Html5Plus/i.test(t)}function v(){return ee()||V()}function ie(){return Q()?"uvue":G()?"nvue":p()?"weixin":Z()?"plus":v()?"webview":ee()?"UniApp":"h5"}let de=null;function Ee(t=!1){return de&&!t||(de={isWeixinMiniProgram:p(),isAppPlus:Z(),isNvue:G(),isUvue:Q(),isUniApp:ee(),isHtml5Plus:V(),isUniAppWebView:v(),type:ie()}),de}const f=Ee(),k={PLATFORM_NOT_SUPPORTED:"PLATFORM_NOT_SUPPORTED",API_CALL_FAILED:"API_CALL_FAILED",BRIDGE_NOT_READY:"BRIDGE_NOT_READY",INVALID_PARAMETERS:"INVALID_PARAMETERS",NETWORK_ERROR:"NETWORK_ERROR"};class M extends Error{constructor(e,r,n={},i=null){super(r),this.name="QshError",this.type=e,this.context=n,this.originalError=i,this.timestamp=new Date().toISOString(),Error.captureStackTrace&&Error.captureStackTrace(this,M)}toJSON(){return{name:this.name,type:this.type,message:this.message,context:this.context,timestamp:this.timestamp,stack:this.stack}}}const _=class _{static setDebugMode(e){_.isDebugMode=e}static addErrorCallback(e){typeof e=="function"&&_.errorCallbacks.push(e)}static removeErrorCallback(e){const r=_.errorCallbacks.indexOf(e);r>-1&&_.errorCallbacks.splice(r,1)}static handleApiError(e,r={}){let n;return e instanceof M?n=e:e instanceof Error?n=new M(k.API_CALL_FAILED,e.message,r,e):n=new M(k.API_CALL_FAILED,String(e),r),_.logError(n),_.notifyCallbacks(n),n}static handlePlatformNotSupported(e,r){const n=new M(k.PLATFORM_NOT_SUPPORTED,`API "${r}" is not supported on platform "${e}"`,{platformType:e,apiName:r});return _.logError(n),_.notifyCallbacks(n),n}static handleBridgeNotReady(e){const r=new M(k.BRIDGE_NOT_READY,`Bridge is not ready when calling "${e}"`,{apiName:e});return _.logError(r),_.notifyCallbacks(r),r}static handleInvalidParameters(e,r,n,i){const a=new M(k.INVALID_PARAMETERS,`Invalid parameter "${r}" in "${e}": expected ${n}, got ${typeof i}`,{apiName:e,paramName:r,expectedType:n,actualValue:i});return _.logError(a),_.notifyCallbacks(a),a}static safeExecute(e,r={}){try{return e()}catch(n){return _.handleApiError(n,r)}}static safeExecuteAsync(n){return E(this,arguments,function*(e,r={}){try{return yield e()}catch(i){return _.handleApiError(i,r)}})}static logError(e){if(typeof console!="undefined"){const r=`[QSH-SDK Error] ${e.type}: ${e.message}`;_.isDebugMode?console.error(r,{context:e.context,originalError:e.originalError,stack:e.stack,timestamp:e.timestamp}):console.error(r)}}static notifyCallbacks(e){_.errorCallbacks.forEach(r=>{try{r(e)}catch(n){typeof console!="undefined"&&console.error("[QSH-SDK] Error in error callback:",n)}})}static createErrorDecorator(e={}){return function(r,n,i){const a=i.value;return i.value=function(...g){return _.safeExecute(()=>a.apply(this,g),N(h({},e),{method:n,target:r.constructor.name}))},i}}};$(_,"isDebugMode",!1),$(_,"errorCallbacks",[]);let u=_;const C={UNINITIALIZED:"uninitialized",INITIALIZING:"initializing",READY:"ready",ERROR:"error"};class It{constructor(){this.state=C.UNINITIALIZED,this.readyPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.initializationError=null,this.handleBridgeReady=this.handleBridgeReady.bind(this),this.handleInitializationError=this.handleInitializationError.bind(this)}getState(){return this.state}isReady(){return this.state===C.READY}isInitializing(){return this.state===C.INITIALIZING}hasError(){return this.state===C.ERROR}getInitializationError(){return this.initializationError}waitForReady(){return this.isReady()?Promise.resolve():this.hasError()?Promise.reject(this.initializationError):(this.readyPromise||(this.readyPromise=new Promise((e,r)=>{this.isReady()?e():this.hasError()?r(this.initializationError):(this.readyCallbacks.push(e),this.errorCallbacks.push(r))})),this.readyPromise)}startInitialization(e){return E(this,null,function*(){if(this.state!==C.UNINITIALIZED)return this.waitForReady();this.state=C.INITIALIZING;try{yield e(),this.handleBridgeReady()}catch(r){throw this.handleInitializationError(r),r}return this.waitForReady()})}handleBridgeReady(){this.state===C.INITIALIZING&&(this.state=C.READY,this.readyCallbacks.forEach(e=>{try{e()}catch(r){u.handleApiError(r,{context:"StateManager.handleBridgeReady"})}}),this.readyCallbacks=[],this.errorCallbacks=[])}handleInitializationError(e){this.state=C.ERROR,this.initializationError=e,this.errorCallbacks.forEach(r=>{try{r(e)}catch(n){u.handleApiError(n,{context:"StateManager.handleInitializationError"})}}),this.readyCallbacks=[],this.errorCallbacks=[]}reset(){this.state=C.UNINITIALIZED,this.readyPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.initializationError=null}onStateChange(e,r){if(this.state===e)return setTimeout(()=>r(this.state),0),()=>{};const n=()=>{this.state===e&&r(this.state)};return e===C.READY?this.readyCallbacks.push(n):e===C.ERROR&&this.errorCallbacks.push(n),()=>{const i=this.readyCallbacks.indexOf(n);i>-1&&this.readyCallbacks.splice(i,1);const a=this.errorCallbacks.indexOf(n);a>-1&&this.errorCallbacks.splice(a,1)}}getStats(){return{state:this.state,readyCallbacksCount:this.readyCallbacks.length,errorCallbacksCount:this.errorCallbacks.length,hasReadyPromise:!!this.readyPromise,hasInitializationError:!!this.initializationError}}}const j=new It,Me=()=>j.waitForReady(),At=()=>j.isReady(),Ot=()=>j.getState(),w={ERROR:0,WARN:1,INFO:2,DEBUG:3,TRACE:4},se={[w.ERROR]:"ERROR",[w.WARN]:"WARN",[w.INFO]:"INFO",[w.DEBUG]:"DEBUG",[w.TRACE]:"TRACE"},c=class c{static setLevel(e){e>=w.ERROR&&e<=w.TRACE&&(c.currentLevel=e,c.log(w.INFO,"Logger",`日志级别设置为: ${se[e]}`))}static enableDevMode(){c.setLevel(w.DEBUG),c.log(w.INFO,"Logger","开发模式已启用")}static enableProdMode(){c.setLevel(w.WARN),c.log(w.INFO,"Logger","生产模式已启用")}static enableModule(e){c.enabledModules.add(e),c.log(w.INFO,"Logger",`模块日志已启用: ${e}`)}static disableModule(e){c.enabledModules.delete(e),c.log(w.INFO,"Logger",`模块日志已禁用: ${e}`)}static shouldLog(e,r){return e>c.currentLevel?!1:r&&c.enabledModules.size>0?c.enabledModules.has(r):!0}static log(e,r,n,...i){if(!c.shouldLog(e,r))return;const a=new Date().toISOString(),g=se[e],l=r?`[${r}]`:"",d=`${c.prefix} ${l} ${n}`,A={timestamp:a,level:e,levelName:g,module:r,message:n,args:i};if(c.addToHistory(A),typeof c.reporter=="function")try{c.reporter(A)}catch(b){}c.outputToConsole(e,d,...i)}static addToHistory(e){c.logHistory.push(e),c.logHistory.length>c.maxHistorySize&&c.logHistory.shift()}static outputToConsole(e,r,...n){if(typeof console=="undefined")return;const i=n&&n.length>0;switch(e){case w.ERROR:i?console.error(r,...n):console.error(r);break;case w.WARN:i?console.warn(r,...n):console.warn(r);break;case w.INFO:i?console.info(r,...n):console.info(r);break;case w.DEBUG:case w.TRACE:i?console.log(r,...n):console.log(r);break}}static error(e,r,...n){c.log(w.ERROR,e,r,...n)}static warn(e,r,...n){c.log(w.WARN,e,r,...n)}static info(e,r,...n){c.log(w.INFO,e,r,...n)}static debug(e,r,...n){c.log(w.DEBUG,e,r,...n)}static trace(e,r,...n){c.log(w.TRACE,e,r,...n)}static getHistory(e){return e&&e>0?c.logHistory.slice(-e):[...c.logHistory]}static clearHistory(){c.logHistory=[],c.log(w.INFO,"Logger","日志历史已清空")}static getStats(){const e={currentLevel:c.currentLevel,currentLevelName:se[c.currentLevel],enabledModules:Array.from(c.enabledModules),historySize:c.logHistory.length,maxHistorySize:c.maxHistorySize},r={};for(const n of Object.keys(se))r[se[n]]=0;return c.logHistory.forEach(n=>{r[n.levelName]++}),e.levelCounts=r,e}static exportToJSON(e){const r=c.getHistory(e),n=c.getStats();return JSON.stringify({exportTime:new Date().toISOString(),stats:n,logs:r},null,2)}static createModuleLogger(e){return{error:(r,...n)=>c.error(e,r,...n),warn:(r,...n)=>c.warn(e,r,...n),info:(r,...n)=>c.info(e,r,...n),debug:(r,...n)=>c.debug(e,r,...n),trace:(r,...n)=>c.trace(e,r,...n)}}static setReporter(e){c.reporter=typeof e=="function"?e:null}};$(c,"currentLevel",w.ERROR),$(c,"enabledModules",new Set),$(c,"logHistory",[]),$(c,"maxHistorySize",1e3),$(c,"prefix","[QSH-SDK]"),$(c,"reporter",null);let S=c;if(typeof window!="undefined"){const t=window.location&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"||window.location.hostname.includes("192.168.")),e=window.location&&(window.location.search.includes("debug=true")||window.location.search.includes("qsh_debug=1"));let r=!1;try{r=localStorage&&localStorage.getItem("qsh_debug")==="true"}catch(n){}(t||e||r)&&S.enableDevMode()}const y=S.createModuleLogger("Bridge"),O=S.createModuleLogger("Platform"),s=S.createModuleLogger("API"),L=S.createModuleLogger("State"),be=/complete|loaded|interactive/;function _t(t){return ee()||V()?(y.debug("检测到 APP 环境,开始初始化"),window.__uniapp_x_postMessage||window.__uniapp_x_||window.__dcloud_weex_postMessage||window.__dcloud_weex_?(y.debug("NVUE/UVUE 环境,等待 DOMContentLoaded"),document.addEventListener("DOMContentLoaded",t)):window.plus&&be.test(document.readyState)?(y.debug("Plus 环境已就绪,立即初始化"),setTimeout(t,0)):(y.debug("Plus 环境,等待 plusready 事件"),document.addEventListener("plusready",t)),!0):!1}function Nt(t){return window.wx&&window.wx.miniProgram?(y.debug("检测到微信小程序环境,开始初始化"),window.WeixinJSBridge&&window.WeixinJSBridge.invoke?(y.debug("微信 JSBridge 已就绪,立即初始化"),setTimeout(t,0)):(y.debug("微信 JSBridge 未就绪,等待 WeixinJSBridgeReady 事件"),document.addEventListener("WeixinJSBridgeReady",t)),!0):!1}function Rt(t){return y.info("开始初始化 JSBridge"),_t(t)?(y.info("使用 APP 环境初始化"),!0):Nt(t)?(y.info("使用微信小程序环境初始化"),!0):(y.debug("使用默认 H5 环境初始化"),be.test(document.readyState)?(y.debug("DOM 已就绪,立即初始化"),setTimeout(t,0)):(y.debug("DOM 未就绪,等待 DOMContentLoaded"),document.addEventListener("DOMContentLoaded",t)),!0)}function St(){return j.waitForReady()}function ve(){return j.startInitialization(()=>E(null,null,function*(){return new Promise((t,e)=>{const r=()=>{t()},n=i=>{const a=u.handleApiError(i,{context:"bridge initialization"});e(a)};try{Rt(()=>{r()})}catch(i){n(i)}})}))}const T={UNINITIALIZED:"uninitialized",CONFIGURING:"configuring",CONFIGURED:"configured",ERROR:"error"};class Tt{constructor(){this.state=T.UNINITIALIZED,this.configPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.lastError=null,this.CONFIG_API_URL=this.getConfigApiUrl(),this.CLIENT_ID="bmfw-client",this.DEFAULT_JS_API_LIST=["chooseImage","uploadImage","previewImage","downloadImage","getLocalImgData","scanQRCode","getLocation","openLocation","updateAppMessageShareData","updateTimelineShareData"],this.handleConfigSuccess=this.handleConfigSuccess.bind(this),this.handleConfigError=this.handleConfigError.bind(this)}getConfigApiUrl(){return typeof window!="undefined"&&(window.location.hostname==="localhost"||window.location.hostname.includes("127.0.0.1")||window.location.hostname.includes("natappfree.cc")||window.location.port==="5174"),"https://unified-platform-service.xjy2.cn/api/wechat/mp/jssdk-sign"}getCurrentPageUrl(){if(typeof window=="undefined"||!window.location)throw new Error("无法获取当前页面URL");const e=window.location.href,r=e.indexOf("#");return r!==-1?e.substring(0,r):e}fetchWeixinConfig(){return E(this,null,function*(){const e=this.getCurrentPageUrl();if(this.isTestMode())return O.info("使用测试模式,返回模拟配置"),this.getMockConfig();const r=`${this.CONFIG_API_URL}?clientId=${this.CLIENT_ID}&url=${encodeURIComponent(e)}`;O.debug("请求微信配置",{url:r});try{const n=yield fetch(r);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);const i=yield n.json();if(O.debug("微信配置响应",i),!i.success||i.code!==200)throw new Error(`配置获取失败: ${i.message||"未知错误"}`);const{data:a}=i;if(!a||!a.appId||!a.timestamp||!a.nonceStr||!a.signature)throw new Error("配置数据格式不正确,缺少必需字段");return a}catch(n){if(O.error("获取微信配置失败",n),this.shouldUseTestMode(n))return O.warn("网络请求失败,降级到测试模式"),this.getMockConfig();throw new M(k.NETWORK_ERROR,`获取微信配置失败: ${n.message}`,{url:r,originalError:n})}})}isTestMode(){if(typeof window=="undefined")return!1;if(new URLSearchParams(window.location.search).get("qsh_test")==="true")return!0;try{if(localStorage.getItem("qsh_test")==="true")return!0}catch(r){}return!1}shouldUseTestMode(e){const r=window.location.hostname==="localhost"||window.location.hostname.includes("natappfree.cc"),n=!window.wx||!window.wx.miniProgram,i=e.message.includes("CORS")||e.message.includes("Failed to fetch");return r&&n&&i}getMockConfig(){return{appId:"wx_test_app_id",timestamp:Math.floor(Date.now()/1e3).toString(),nonceStr:Math.random().toString(36).substring(2,15),signature:"test_signature_"+Math.random().toString(36).substring(2,10)}}executeWeixinConfig(e){if(this.isTestMode()||e.appId==="wx_test_app_id"){O.info("测试模式:模拟微信配置成功"),setTimeout(()=>{this.handleConfigSuccess()},100);return}if(!window.wx)throw new Error("微信JS-SDK未加载");const r={debug:!1,appId:e.appId,timestamp:parseInt(e.timestamp),nonceStr:e.nonceStr,signature:e.signature,jsApiList:this.DEFAULT_JS_API_LIST};O.info("执行微信配置",r),window.wx.ready(this.handleConfigSuccess),window.wx.error(this.handleConfigError),window.wx.config(r)}handleConfigSuccess(){O.info("微信配置成功"),this.state=T.CONFIGURED,this.readyCallbacks.forEach(e=>{try{e()}catch(r){u.handleApiError(r,{context:"WeixinConfigManager.handleConfigSuccess"})}}),this.readyCallbacks=[],this.errorCallbacks=[]}handleConfigError(e){const r=`微信配置验证失败: ${JSON.stringify(e)}`;O.error(r,e),this.state=T.ERROR,this.lastError=new M(k.API_CALL_FAILED,r,{weixinErrorResponse:e}),this.errorCallbacks.forEach(n=>{try{n(this.lastError)}catch(i){u.handleApiError(i,{context:"WeixinConfigManager.handleConfigError"})}}),this.readyCallbacks=[],this.errorCallbacks=[]}autoConfig(){return E(this,null,function*(){return this.state===T.CONFIGURED?Promise.resolve():this.state===T.ERROR?Promise.reject(this.lastError):this.configPromise?this.configPromise:(this.state=T.CONFIGURING,this.configPromise=this.performAutoConfig(),this.configPromise)})}performAutoConfig(){return E(this,null,function*(){return u.safeExecuteAsync(()=>E(this,null,function*(){if(typeof window=="undefined")throw new Error("非浏览器环境无法执行微信配置");if(!window.wx)throw new Error("微信JS-SDK未加载,无法执行配置");const e=yield this.fetchWeixinConfig();return this.executeWeixinConfig(e),new Promise((r,n)=>{if(this.state===T.CONFIGURED){r();return}if(this.state===T.ERROR){n(this.lastError);return}this.readyCallbacks.push(r),this.errorCallbacks.push(n)})}),{context:"WeixinConfigManager.performAutoConfig"})})}waitForReady(){return this.state===T.CONFIGURED?Promise.resolve():this.state===T.ERROR?Promise.reject(this.lastError):this.state===T.UNINITIALIZED?this.autoConfig():new Promise((e,r)=>{this.readyCallbacks.push(e),this.errorCallbacks.push(r)})}isReady(){return this.state===T.CONFIGURED}getState(){return this.state}getLastError(){return this.lastError}reset(){this.state=T.UNINITIALIZED,this.configPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.lastError=null,O.debug("微信配置管理器已重置")}getStats(){return{state:this.state,readyCallbacksCount:this.readyCallbacks.length,errorCallbacksCount:this.errorCallbacks.length,hasConfigPromise:!!this.configPromise,hasLastError:!!this.lastError,configApiUrl:this.CONFIG_API_URL,clientId:this.CLIENT_ID,jsApiList:this.DEFAULT_JS_API_LIST}}}const B=new Tt;let te=!1,ye=!1,fe=!1;function Pt(){if(typeof window=="undefined"||ye||te||window.wx&&window.wx.miniProgram)return!1;const t=navigator.userAgent||"",e=/micromessenger/i.test(t),r=/miniProgram/i.test(t),n=typeof window.__wxjs_environment!="undefined"&&window.__wxjs_environment==="miniprogram";return e&&(r||n)}function Ie(){return E(this,null,function*(){if(fe)return B.waitForReady();fe=!0,O.info("开始自动配置微信JS-SDK");try{yield B.autoConfig(),O.info("微信JS-SDK自动配置完成")}catch(t){O.error("微信JS-SDK自动配置失败",t)}})}function Ct(){return Pt()?document.getElementById("weixin-jssdk")?(te=!1,ye=!0,fe?B.waitForReady():Ie()):new Promise(t=>{te=!0;try{const e=document.createElement("script");e.id="weixin-jssdk",e.type="text/javascript",e.async=!0,e.src="https://res.wx.qq.com/open/js/jweixin-1.6.2.js",e.onload=function(){return E(this,null,function*(){ye=!0,te=!1,O.info("微信 JS-SDK 已自动加载");try{yield Ie()}catch(n){O.error("微信配置失败,将使用消息桥作为后备",n)}t()})},e.onerror=function(){te=!1,O.warn("微信 JS-SDK 加载失败,SDK 将使用消息桥作为后备"),t()},(document.getElementsByTagName("head")[0]||document.documentElement).appendChild(e)}catch(e){te=!1,O.error("注入微信 JS-SDK 失败",e),t()}}):Promise.resolve()}function F(){return B.waitForReady()}function K(){return B.isReady()}function Mt(){return B.getState()}function Le(){return B}function bt(){return E(this,null,function*(){return O.info("手动重试微信配置"),B.reset(),fe=!1,Ie()})}class vt{constructor(){this.plugins=new Map,this.installed=new Set,this.installOrder=[],s.debug("插件管理器已初始化")}register(e){return u.safeExecute(()=>{this.validatePlugin(e);const{name:r,version:n}=e;if(this.plugins.has(r)){const i=this.plugins.get(r);s.warn(`插件 ${r} 已注册(版本 ${i.version}),将被覆盖为版本 ${n}`)}return this.plugins.set(r,e),s.info(`插件已注册: ${r}@${n}`),this},{context:"PluginManager.register",pluginName:e==null?void 0:e.name})}validatePlugin(e){if(!e||typeof e!="object")throw new Error("插件必须是一个对象");if(!e.name||typeof e.name!="string")throw new Error("插件必须有 name 属性(字符串)");if(!e.version||typeof e.version!="string")throw new Error(`插件 ${e.name} 必须有 version 属性(字符串)`);if(!e.install||typeof e.install!="function")throw new Error(`插件 ${e.name} 必须实现 install 方法`);if(e.dependencies&&!Array.isArray(e.dependencies))throw new Error(`插件 ${e.name} 的 dependencies 必须是数组`)}install(e,r){return E(this,null,function*(){return u.safeExecute(()=>E(this,null,function*(){if(!this.plugins.has(e))throw new Error(`插件 ${e} 未注册`);if(this.installed.has(e)){s.debug(`插件 ${e} 已安装,跳过`);return}const n=this.plugins.get(e);if(n.dependencies&&n.dependencies.length>0){s.debug(`安装插件 ${e} 的依赖:`,n.dependencies);for(const i of n.dependencies)yield this.install(i,r)}s.info(`开始安装插件: ${e}@${n.version}`),yield n.install(r),this.installed.add(e),this.installOrder.push(e),s.info(`插件安装成功: ${e}@${n.version}`)}),{context:"PluginManager.install",pluginName:e})})}uninstall(e,r){return E(this,null,function*(){return u.safeExecute(()=>E(this,null,function*(){if(!this.installed.has(e)){s.debug(`插件 ${e} 未安装,跳过卸载`);return}const n=this.plugins.get(e);n.uninstall&&typeof n.uninstall=="function"&&(s.info(`开始卸载插件: ${e}`),yield n.uninstall(r)),this.installed.delete(e);const i=this.installOrder.indexOf(e);i>-1&&this.installOrder.splice(i,1),s.info(`插件已卸载: ${e}`)}),{context:"PluginManager.uninstall",pluginName:e})})}uninstallAll(e){return E(this,null,function*(){const r=[...this.installOrder].reverse();for(const n of r)yield this.uninstall(n,e)})}registerAll(e){if(!Array.isArray(e))throw new Error("plugins 必须是数组");return e.forEach(r=>this.register(r)),this}installAll(e,r){return E(this,null,function*(){if(!Array.isArray(e))throw new Error("names 必须是数组");for(const n of e)yield this.install(n,r)})}isRegistered(e){return this.plugins.has(e)}isInstalled(e){return this.installed.has(e)}getPlugin(e){return this.plugins.get(e)}getPluginList(){return Array.from(this.plugins.entries()).map(([e,r])=>({name:e,version:r.version,installed:this.installed.has(e),dependencies:r.dependencies||[]}))}getStats(){return{registered:this.plugins.size,installed:this.installed.size,plugins:this.getPluginList()}}clear(){this.plugins.clear(),this.installed.clear(),this.installOrder=[]}}const ae=new vt;class Lt{constructor(){this.requestInterceptors=[],this.responseInterceptors=[],s.debug("拦截器链已初始化")}useRequest(e,r={}){if(typeof e!="function")throw new Error("拦截器必须是函数");const{priority:n=0}=r;return this.requestInterceptors.push({fn:e,priority:n}),this.requestInterceptors.sort((i,a)=>a.priority-i.priority),s.debug("请求拦截器已注册",{priority:n}),()=>{const i=this.requestInterceptors.findIndex(a=>a.fn===e);i>-1&&(this.requestInterceptors.splice(i,1),s.debug("请求拦截器已移除"))}}useResponse(e,r={}){if(typeof e!="function")throw new Error("拦截器必须是函数");const{priority:n=0}=r;return this.responseInterceptors.push({fn:e,priority:n}),this.responseInterceptors.sort((i,a)=>a.priority-i.priority),s.debug("响应拦截器已注册",{priority:n}),()=>{const i=this.responseInterceptors.findIndex(a=>a.fn===e);i>-1&&(this.responseInterceptors.splice(i,1),s.debug("响应拦截器已移除"))}}runRequest(e){return E(this,null,function*(){let r=h({},e);for(const{fn:n}of this.requestInterceptors){if(r.abort){s.debug("请求被中止",{apiName:r.apiName});break}try{const i=yield n(r);i&&(r=i)}catch(i){s.error("请求拦截器执行失败",i),r.abort=!0,r.error=i;break}}return r})}runResponse(e,r){return E(this,null,function*(){let n=e;for(const{fn:i}of this.responseInterceptors)try{const a=yield i(n,r);a!==void 0&&(n=a)}catch(a){s.error("响应拦截器执行失败",a)}return n})}clear(){this.requestInterceptors=[],this.responseInterceptors=[],s.debug("所有拦截器已清空")}getStats(){return{requestInterceptors:this.requestInterceptors.length,responseInterceptors:this.responseInterceptors.length}}}const q=new Lt,Dt={request:t=>(t.startTime=Date.now(),s.debug(`[API 调用] ${t.apiName}`,{params:t.params}),t),response:(t,e)=>{const r=Date.now()-e.startTime;return s.debug(`[API 完成] ${e.apiName}`,{duration:`${r}ms`,success:t==null?void 0:t.success}),t}},z={metrics:new Map,request:t=>(t.perfStartTime=performance.now(),t),response:(t,e)=>{const r=performance.now()-e.perfStartTime;z.metrics.has(e.apiName)||z.metrics.set(e.apiName,{count:0,totalTime:0,minTime:1/0,maxTime:0,avgTime:0});const n=z.metrics.get(e.apiName);return n.count++,n.totalTime+=r,n.minTime=Math.min(n.minTime,r),n.maxTime=Math.max(n.maxTime,r),n.avgTime=n.totalTime/n.count,t},getReport:()=>{const t={};return z.metrics.forEach((e,r)=>{t[r]=h({},e)}),t},clearMetrics:()=>{z.metrics.clear()}};function xt(t={}){const{maxRetries:e=3,retryDelay:r=1e3,shouldRetry:n=i=>!i.success}=t;return{response:(i,a)=>E(null,null,function*(){return a.retryCount||(a.retryCount=0),n(i)&&a.retryCount<e&&(a.retryCount++,s.warn(`API 调用失败,第 ${a.retryCount} 次重试: ${a.apiName}`),yield new Promise(g=>setTimeout(g,r)),i.shouldRetry=!0,i.retryContext=a),i})}}function Ut(t={}){return{request:e=>{const r=t[e.apiName];if(r&&typeof r=="function"){const n=r(e.params);n&&(s.error(`参数验证失败: ${e.apiName}`,n),e.abort=!0,e.validationError=n)}return e}}}class Wt{constructor(){this.state={sdk:{status:"uninitialized",version:"2.0.5",error:null},platform:{type:f.type,isWeixinMiniProgram:f.isWeixinMiniProgram,isAppPlus:f.isAppPlus,isNvue:f.isNvue,isUvue:f.isUvue,features:{}},weixin:{configStatus:"pending",jsApiList:[],configError:null},network:{online:typeof navigator!="undefined"?navigator.onLine:!0,type:"unknown"},permissions:{camera:"prompt",location:"prompt",album:"prompt"},api:{}},this.listeners=new Map,this.wildcardListeners=new Set,this.initNetworkListener(),L.debug("状态仓库已初始化")}get(e){return e.split(".").reduce((n,i)=>n!=null?n[i]:void 0,this.state)}set(e,r){const n=e.split("."),i=n.pop(),a=n.reduce((l,d)=>((!l[d]||typeof l[d]!="object")&&(l[d]={}),l[d]),this.state),g=a[i];g!==r&&(a[i]=r,L.debug(`状态已更新: ${e}`,{oldValue:g,newValue:r}),this.notify(e,r,g))}batchUpdate(e){Object.entries(e).forEach(([r,n])=>{this.set(r,n)})}subscribe(e,r){if(typeof r!="function")throw new Error("listener 必须是函数");return e==="*"?(this.wildcardListeners.add(r),L.debug("添加通配符订阅者"),()=>{this.wildcardListeners.delete(r),L.debug("移除通配符订阅者")}):(this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),L.debug(`添加订阅者: ${e}`),()=>{const n=this.listeners.get(e);n&&(n.delete(r),n.size===0&&this.listeners.delete(e),L.debug(`移除订阅者: ${e}`))})}subscribeOnce(e,r){const n=this.subscribe(e,(i,a,g)=>{r(i,a,g),n()});return n}notify(e,r,n){const i=this.listeners.get(e);i&&i.forEach(g=>{try{g(r,n,e)}catch(l){L.error("订阅者执行失败",l)}});const a=e.split(".");for(let g=1;g<a.length;g++){const l=a.slice(0,g).join("."),d=this.listeners.get(l);if(d){const A=this.get(l);d.forEach(b=>{try{b(A,void 0,l)}catch(P){L.error("父路径订阅者执行失败",P)}})}}this.wildcardListeners.forEach(g=>{try{g(r,n,e)}catch(l){L.error("通配符订阅者执行失败",l)}})}initNetworkListener(){if(typeof window!="undefined"&&(window.addEventListener("online",()=>{this.set("network.online",!0)}),window.addEventListener("offline",()=>{this.set("network.online",!1)}),navigator.connection)){const e=navigator.connection,r=()=>{this.set("network.type",e.effectiveType||"unknown")};e.addEventListener("change",r),r()}}setApiLoading(e,r=!0){const n=`api.${e}`,i=this.get(n)||{};this.set(n,N(h({},i),{loading:r,lastCall:r?Date.now():i.lastCall}))}setApiResult(e,r){const n=`api.${e}`,i=this.get(n)||{};this.set(n,N(h({},i),{loading:!1,lastResult:r,lastCallEnd:Date.now()}))}getSnapshot(){return JSON.parse(JSON.stringify(this.state))}reset(){const{platform:e}=this.state;this.state={sdk:{status:"uninitialized",version:"2.0.5",error:null},platform:e,weixin:{configStatus:"pending",jsApiList:[],configError:null},network:{online:typeof navigator!="undefined"?navigator.onLine:!0,type:"unknown"},permissions:{camera:"prompt",location:"prompt",album:"prompt"},api:{}},L.debug("状态已重置")}getStats(){return{listeners:this.listeners.size,wildcardListeners:this.wildcardListeners.size,apiStates:Object.keys(this.state.api).length}}}const U=new Wt,o={SDK_NOT_READY:"E_SDK_001",SDK_INIT_FAILED:"E_SDK_002",SDK_CONFIG_FAILED:"E_SDK_003",PLATFORM_NOT_SUPPORTED:"E_SDK_004",NETWORK_ERROR:"E_NET_001",NETWORK_TIMEOUT:"E_NET_002",NETWORK_OFFLINE:"E_NET_003",IMAGE_CANCELLED:"E_IMG_001",IMAGE_NO_PERMISSION:"E_IMG_002",IMAGE_SIZE_EXCEED:"E_IMG_003",IMAGE_COUNT_EXCEED:"E_IMG_004",IMAGE_FORMAT_ERROR:"E_IMG_005",IMAGE_CONFIG_NOT_READY:"E_IMG_006",LOCATION_CANCELLED:"E_LOC_001",LOCATION_NO_PERMISSION:"E_LOC_002",LOCATION_UNAVAILABLE:"E_LOC_003",LOCATION_TIMEOUT:"E_LOC_004",SCAN_CANCELLED:"E_SCAN_001",SCAN_NO_PERMISSION:"E_SCAN_002",SCAN_INVALID_CODE:"E_SCAN_003",SCAN_CONFIG_NOT_READY:"E_SCAN_004",PERMISSION_DENIED:"E_PERM_001",PERMISSION_CAMERA:"E_PERM_002",PERMISSION_LOCATION:"E_PERM_003",PERMISSION_ALBUM:"E_PERM_004",PERMISSION_MICROPHONE:"E_PERM_005",PARAM_INVALID:"E_PARAM_001",PARAM_MISSING:"E_PARAM_002",PARAM_TYPE_ERROR:"E_PARAM_003",API_TIMEOUT:"E_TIMEOUT_001",UNKNOWN_ERROR:"E_UNKNOWN_999"},Ae={[o.SDK_NOT_READY]:"SDK 未就绪",[o.SDK_INIT_FAILED]:"SDK 初始化失败",[o.SDK_CONFIG_FAILED]:"SDK 配置失败",[o.PLATFORM_NOT_SUPPORTED]:"当前平台不支持此功能",[o.NETWORK_ERROR]:"网络错误",[o.NETWORK_TIMEOUT]:"网络超时",[o.NETWORK_OFFLINE]:"网络已断开",[o.IMAGE_CANCELLED]:"用户取消选择图片",[o.IMAGE_NO_PERMISSION]:"无相机/相册权限",[o.IMAGE_SIZE_EXCEED]:"图片大小超出限制",[o.IMAGE_COUNT_EXCEED]:"图片数量超出限制",[o.IMAGE_FORMAT_ERROR]:"图片格式不支持",[o.IMAGE_CONFIG_NOT_READY]:"微信配置未完成",[o.LOCATION_CANCELLED]:"用户取消定位",[o.LOCATION_NO_PERMISSION]:"无定位权限",[o.LOCATION_UNAVAILABLE]:"定位服务不可用",[o.LOCATION_TIMEOUT]:"定位超时",[o.SCAN_CANCELLED]:"用户取消扫码",[o.SCAN_NO_PERMISSION]:"无相机权限",[o.SCAN_INVALID_CODE]:"无效的二维码/条形码",[o.SCAN_CONFIG_NOT_READY]:"微信配置未完成",[o.PERMISSION_DENIED]:"权限被拒绝",[o.PERMISSION_CAMERA]:"无相机权限",[o.PERMISSION_LOCATION]:"无定位权限",[o.PERMISSION_ALBUM]:"无相册权限",[o.PERMISSION_MICROPHONE]:"无麦克风权限",[o.PARAM_INVALID]:"参数无效",[o.PARAM_MISSING]:"缺少必需参数",[o.PARAM_TYPE_ERROR]:"参数类型错误",[o.API_TIMEOUT]:"API 调用超时",[o.UNKNOWN_ERROR]:"未知错误"},D={USER_CANCEL:"user_cancel",PERMISSION:"permission",NETWORK:"network",PARAM:"param",SYSTEM:"system",CONFIG:"config",UNKNOWN:"unknown"},$t={"IMAGE/USER_CANCEL":o.IMAGE_CANCELLED,"IMAGE/PERMISSION_DENIED":o.IMAGE_NO_PERMISSION,"COMMON/UNKNOWN":o.UNKNOWN_ERROR,"COMMON/CONFIG_NOT_READY":o.IMAGE_CONFIG_NOT_READY,"COMMON/PLATFORM_NOT_SUPPORTED":o.PLATFORM_NOT_SUPPORTED},De={weixin:{patterns:[{pattern:/cancel/i,code:o.IMAGE_CANCELLED},{pattern:/permission|auth\s*deny/i,code:o.IMAGE_NO_PERMISSION},{pattern:/config/i,code:o.IMAGE_CONFIG_NOT_READY},{pattern:/timeout/i,code:o.API_TIMEOUT},{pattern:/network/i,code:o.NETWORK_ERROR}],default:o.UNKNOWN_ERROR},uniapp:{patterns:[{pattern:/cancel/i,code:o.IMAGE_CANCELLED},{pattern:/permission|denied/i,code:o.IMAGE_NO_PERMISSION},{pattern:/timeout/i,code:o.API_TIMEOUT},{pattern:/network/i,code:o.NETWORK_ERROR},{pattern:/not_in_container/i,code:o.PLATFORM_NOT_SUPPORTED}],default:o.UNKNOWN_ERROR}},xe={chooseImage:{"fail cancel":o.IMAGE_CANCELLED,"fail auth deny":o.IMAGE_NO_PERMISSION,"fail No Permission":o.IMAGE_NO_PERMISSION,NOT_IN_CONTAINER:o.PLATFORM_NOT_SUPPORTED},scanCode:{"fail cancel":o.SCAN_CANCELLED,"fail auth deny":o.SCAN_NO_PERMISSION,"fail No Permission":o.SCAN_NO_PERMISSION,NOT_IN_CONTAINER:o.PLATFORM_NOT_SUPPORTED}};function Ue(t){return t?t.includes("CANCEL")?D.USER_CANCEL:t.includes("PERM")||t.includes("PERMISSION")?D.PERMISSION:t.includes("NET")||t.includes("NETWORK")?D.NETWORK:t.includes("PARAM")?D.PARAM:t.includes("CONFIG")?D.CONFIG:t.includes("SDK")||t.includes("PLATFORM")?D.SYSTEM:D.UNKNOWN:D.UNKNOWN}function kt(t){return t.includes("NET_")||t.includes("TIMEOUT")||t===o.NETWORK_ERROR||t===o.NETWORK_TIMEOUT||t===o.API_TIMEOUT}function Bt(t){return t.includes("CANCEL")||Ue(t)===D.USER_CANCEL}function re(t){return Ae[t]||Ae[o.UNKNOWN_ERROR]}class W extends Error{constructor(e,r,n={}){super(r),this.name="StandardError",this.code=e,this.message=r||re(e),this.platform=n.platform||f.type,this.apiName=n.apiName,this.category=n.category||Ue(e),this.retriable=n.retriable!==void 0?n.retriable:kt(e),this.originalError=n.originalError,this.details=n.details||{},this.timestamp=Date.now()}isRetriable(){return this.retriable}isUserAction(){return Bt(this.code)}toJSON(){return h({code:this.code,message:this.message,platform:this.platform,apiName:this.apiName,category:this.category,retriable:this.retriable,timestamp:this.timestamp,details:this.details},process.env.NODE_ENV!=="production"&&this.originalError?{originalError:this.originalError}:{})}}function We(t,e={}){if(t instanceof W)return t;const{apiName:r,platform:n=f.type}=e;return t&&typeof t.code=="string"&&t.code.includes("/")?Ft(t,{apiName:r,platform:n}):t&&(t.errMsg||t.message)?Kt(t,{apiName:r,platform:n}):typeof t=="string"?new W(o.UNKNOWN_ERROR,t,{apiName:r,platform:n,originalError:t}):new W(o.UNKNOWN_ERROR,"未知错误",{apiName:r,platform:n,originalError:t,details:{errorType:typeof t}})}function Ft(t,e){const{apiName:r,platform:n}=e,i=t.code,a=$t[i]||o.UNKNOWN_ERROR;return s.debug("转换旧版错误码",{legacy:i,new:a}),new W(a,t.message||re(a),{apiName:r,platform:t.platform||n,originalError:t,details:h({legacyCode:i,legacyVersion:t.version},t.details)})}function Kt(t,e){const{apiName:r,platform:n}=e,i=(t.errMsg||t.message||"").toLowerCase();if(r&&xe[r]){const l=xe[r];for(const[d,A]of Object.entries(l))if(i.includes(d.toLowerCase()))return new W(A,re(A),{apiName:r,platform:n,originalError:t})}const a=De[n]||De.uniapp;for(const{pattern:l,code:d}of a.patterns)if(l.test(i))return new W(d,re(d),{apiName:r,platform:n,originalError:t});const g=a.default||o.UNKNOWN_ERROR;return new W(g,t.errMsg||t.message||re(g),{apiName:r,platform:n,originalError:t})}const $e={response:(t,e)=>{if(!t.success&&t.error){const r=We(t.error,{apiName:e.apiName,platform:f.type});t.error=r.toJSON(),t.errorCode=r.code,t.errorCategory=r.category,t.retriable=r.isRetriable(),s.debug("错误已标准化",{api:e.apiName,code:r.code,category:r.category})}return t}};function zt(t,e={}){return new W(t,re(t),e)}function Gt(t){return t instanceof W}function Vt(t,e,r){return e?Promise.race([t(),new Promise((n,i)=>setTimeout(()=>i(new Error(`Init task timeout: ${r}`)),e))]):t()}function jt(){return E(this,arguments,function*(t=[],e={}){for(const r of t){const n=(r==null?void 0:r.name)||"anonymous-task",i=(r==null?void 0:r.run)||r;if(typeof i=="function")try{yield Vt(()=>Promise.resolve().then(()=>i()),r.timeoutMs,n),typeof r.onSuccess=="function"&&r.onSuccess()}catch(a){if(typeof r.onError=="function"&&r.onError(a),typeof e.onError=="function")e.onError(a,r);else throw a}}})}class ke{constructor(e){this.name=e}processNavigationOptions(e={}){const{url:r,delta:n=1}=e,i=r&&encodeURI(r),a=parseInt(n)||1;return N(h({},e),{url:i,delta:a})}processMessageOptions(e={}){const{data:r={}}=e;return{data:r}}navigateTo(e){const r=this.processNavigationOptions(e);return this.performNavigation("navigateTo",r)}navigateBack(e={}){const r=this.processNavigationOptions(e);return this.performNavigation("navigateBack",r)}switchTab(e){const r=this.processNavigationOptions(e);return this.performNavigation("switchTab",r)}reLaunch(e){const r=this.processNavigationOptions(e);return this.performNavigation("reLaunch",r)}redirectTo(e){const r=this.processNavigationOptions(e);return this.performNavigation("redirectTo",r)}postMessage(e={}){const r=this.processMessageOptions(e);return this.performPostMessage(r)}getEnv(e){return this.performGetEnv(e)}performNavigation(e,r){throw new Error(`${this.name} platform must implement performNavigation method`)}performPostMessage(e){throw new Error(`${this.name} platform must implement performPostMessage method`)}performGetEnv(e){throw new Error(`${this.name} platform must implement performGetEnv method`)}}let oe=[];function qt(){if(oe.length===0&&window.plus){const t=plus.webview.currentWebview();if(!t)throw new Error("plus.webview.currentWebview() is undefined");const e=t.parent(),r=e?e.id:t.id;oe.push(r)}return oe}function Jt(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};if(t==="postMessage"){const i={data:e};return window.__uniapp_x_postMessage?window.__uniapp_x_postMessage(i):window.__uniapp_x_.postMessage(JSON.stringify(i))}const n={type:"WEB_INVOKE_APPSERVICE",args:{data:r,webviewIds:oe}};window.__uniapp_x_postMessage?window.__uniapp_x_postMessageToService(n):window.__uniapp_x_.postMessageToService(JSON.stringify(n))}function Ht(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};if(t==="postMessage"){const i={data:[e]};return window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(i):window.__dcloud_weex_.postMessage(JSON.stringify(i))}const n={type:"WEB_INVOKE_APPSERVICE",args:{data:r,webviewIds:oe}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(n):window.__dcloud_weex_.postMessageToService(JSON.stringify(n))}function Yt(t,e){const r={options:{timestamp:+new Date},name:t,arg:e},n=qt();if(plus.webview.getWebviewById("__uniapp__service"))plus.webview.postMessageToUniNView({type:"WEB_INVOKE_APPSERVICE",args:{data:r,webviewIds:n}},"__uniapp__service");else{const i=JSON.stringify(r),a=JSON.stringify(n);plus.webview.getLaunchWebview().evalJS(`UniPlusBridge.subscribeHandler("WEB_INVOKE_APPSERVICE",${i},${a});`)}}function Xt(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:r,pageId:""},"*")}function ce(t,e){Q()?Jt(t,e):G()?Ht(t,e):Z()?Yt(t,e):Xt(t,e)}class Be extends ke{constructor(){super("weixin")}isWeixinApiAvailable(){return typeof window!="undefined"&&window.wx&&window.wx.miniProgram}performNavigation(e,r){return u.safeExecute(()=>{const{url:n,delta:i}=r;if(O.debug(`微信平台执行导航操作: ${e}`,r),this.isWeixinApiAvailable()){const g=window.wx.miniProgram[e];if(typeof g=="function"){O.debug(`使用微信原生 API: wx.miniProgram.${e}`);const l=e==="navigateBack"?{delta:i}:{url:n};return g.call(window.wx.miniProgram,l)}}O.debug(`使用消息桥接执行: ${e}`),ce(e,e==="navigateBack"?{delta:i}:{url:n})},{platform:this.name,method:"performNavigation",navigationType:e,options:r})}performPostMessage(e){return u.safeExecute(()=>{const{data:r}=e;if(this.isWeixinApiAvailable())return window.wx.miniProgram.postMessage({data:r});ce("postMessage",r)},{platform:this.name,method:"performPostMessage",options:e})}performGetEnv(e){return u.safeExecute(()=>{if(!e||typeof e!="function")throw new Error("Callback function is required for getEnv");if(this.isWeixinApiAvailable()&&window.wx.miniProgram.getEnv)return window.wx.miniProgram.getEnv(e);e({miniprogram:!0,weixin:!0})},{platform:this.name,method:"performGetEnv"})}}const J=new Be;var Fe=Object.freeze({__proto__:null,WeixinPlatform:Be,getEnv:t=>J.getEnv(t),navigateBack:t=>J.navigateBack(t),navigateTo:t=>J.navigateTo(t),postMessage:t=>J.postMessage(t),reLaunch:t=>J.reLaunch(t),redirectTo:t=>J.redirectTo(t),switchTab:t=>J.switchTab(t)});class Ke extends ke{constructor(){super("app")}performNavigation(e,r){return u.safeExecute(()=>{const{url:n,delta:i}=r;ce(e,e==="navigateBack"?{delta:i}:{url:n})},{platform:this.name,method:"performNavigation",navigationType:e,options:r})}performPostMessage(e){return u.safeExecute(()=>{const{data:r}=e;ce("postMessage",r)},{platform:this.name,method:"performPostMessage",options:e})}performGetEnv(e){return u.safeExecute(()=>{if(!e||typeof e!="function")throw new Error("Callback function is required for getEnv");const r={};let n=!1;Q()?(r.uvue=!0,n=!0):G()?(r.nvue=!0,n=!0):Z()&&(r.plus=!0,n=!0),n?r.app=!0:r.h5=!0,e(r)},{platform:this.name,method:"performGetEnv"})}}const H=new Ke;var ze=Object.freeze({__proto__:null,AppPlatform:Ke,getEnv:t=>H.getEnv(t),navigateBack:t=>H.navigateBack(t),navigateTo:t=>H.navigateTo(t),postMessage:t=>H.postMessage(t),reLaunch:t=>H.reLaunch(t),redirectTo:t=>H.redirectTo(t),switchTab:t=>H.switchTab(t)});function ue(){return p()?Fe:ze}function Zt(t){return ue().navigateTo(t)}function Qt(t){return ue().navigateBack(t)}function er(t){return ue().switchTab(t)}function tr(t){return ue().reLaunch(t)}function rr(t){return ue().redirectTo(t)}function Ge(){return p()?Fe:ze}function nr(t={}){return Ge().postMessage(t)}function ir(t){return Ge().getEnv(t)}function sr(t){return t&&typeof t=="object"&&t.__v_raw?t.__v_raw:t}function ar(){return"qsh_callback_"+Date.now()+"_"+Math.random().toString(36).substring(2,9)}class or{constructor(){this.callbacks=new Map,this.timeouts=new Map,this.defaultTimeout=3e4,typeof window!="undefined"&&(window.qshWebviewCallbacks||(window.qshWebviewCallbacks={})),y.debug("WebView 桥接器已初始化")}callApi(i){return E(this,arguments,function*(e,r={},n={}){return u.safeExecute(()=>E(this,null,function*(){var A;if(typeof window!="undefined"&&window===window.parent&&!window.plus&&!window.__uniapp_x_postMessage&&!window.__uniapp_x_&&!window.__dcloud_weex_postMessage&&!window.__dcloud_weex_){const b=new M(k.PLATFORM_NOT_SUPPORTED,"当前不在宿主 WebView 容器中,无法发送消息");n&&typeof n.fail=="function"&&n.fail({errMsg:b.message,code:"NOT_IN_CONTAINER"}),n&&typeof n.complete=="function"&&n.complete({success:!1,error:{errMsg:b.message}});return}const g={apiName:e,params:r,callbacks:n,timestamp:Date.now(),abort:!1,metadata:{}};U.setApiLoading(e,!0);const l=yield q.runRequest(g);if(l.abort){y.warn("API 调用被拦截器中止",{api:e}),U.setApiLoading(e,!1),n.fail&&n.fail({errMsg:((A=l.error)==null?void 0:A.message)||"API 调用被中止",code:"INTERCEPTED"}),n.complete&&n.complete({success:!1});return}const d=ar();if(n.success||n.fail||n.complete){if(this.callbacks.set(d,N(h({},n),{context:l})),window.qshWebviewCallbacks[d]=Pe=>{this.handleCallback(d,Pe)},r.isPersistent||r.disableTimeout)y.info(`API ${e} 禁用超时清理,将等待回调返回后清理`,{callbackId:d,isPersistent:r.isPersistent,disableTimeout:r.disableTimeout});else{const Pe=setTimeout(()=>{y.warn("API 调用超时,自动清理回调",{api:e,callbackId:d}),n.fail&&n.fail({errMsg:`API ${e} 调用超时`,code:"TIMEOUT"}),this.cleanupCallback(d)},r.timeout||this.defaultTimeout);this.timeouts.set(d,Pe)}const P={type:"qsh_api_call",api:e,params:l.params,callbackId:d,timestamp:Date.now()};y.info("发送 API 调用消息",{api:e,callbackId:d,hasSuccess:!!n.success,hasFail:!!n.fail}),console.log("message:",JSON.stringify(sr(P),null,2)),ce("postMessage",P)}}),{context:"WebViewBridge.callApi",api:e})})}handleCallback(e,r){return E(this,null,function*(){return u.safeExecute(()=>E(this,null,function*(){var b,P;const n=this.callbacks.get(e);if(!n){y.warn("未找到回调函数",{callbackId:e});return}const{success:i,fail:a,complete:g,context:l}=n;y.debug("处理回调",{callbackId:e,result:r});const d=yield q.runResponse(r,l);l&&U.setApiResult(l.apiName,d),d.success&&i?i(d.data):!d.success&&a&&a(d.error||{errMsg:"操作失败"}),g&&g(d),((P=(b=n.context)==null?void 0:b.params)==null?void 0:P.isPersistent)?y.debug("持久监听API:保留回调",{callbackId:e}):(this.cleanupCallback(e),y.debug("回调执行完成,已清理",{callbackId:e}))}),{context:"WebViewBridge.handleCallback",callbackId:e})})}cleanupCallback(e){const r=this.timeouts.get(e);r&&(clearTimeout(r),this.timeouts.delete(e)),this.callbacks.delete(e),typeof window!="undefined"&&window.qshWebviewCallbacks&&delete window.qshWebviewCallbacks[e]}clearCallbacks(){y.debug("清理所有回调",{count:this.callbacks.size}),this.timeouts.forEach(e=>clearTimeout(e)),this.timeouts.clear(),this.callbacks.clear(),typeof window!="undefined"&&window.qshWebviewCallbacks&&Object.keys(window.qshWebviewCallbacks).forEach(e=>{e.startsWith("qsh_callback_")&&delete window.qshWebviewCallbacks[e]})}getStatus(){return{isSupported:typeof window!="undefined"&&window.uni&&typeof window.uni.postMessage=="function",activeCallbacks:this.callbacks.size,globalCallbacksCount:typeof window!="undefined"&&window.qshWebviewCallbacks?Object.keys(window.qshWebviewCallbacks).length:0}}}const cr=new or,x=(t,e,r)=>cr.callApi(t,e,r),ge={ALBUM:"album",CAMERA:"camera"},he={ORIGINAL:"original",COMPRESSED:"compressed"},ur={count:9,sizeType:[he.ORIGINAL,he.COMPRESSED],sourceType:[ge.ALBUM,ge.CAMERA]};function lr(t={}){const e=h(h({},ur),t);return Array.isArray(e.sizeType)||(e.sizeType=[e.sizeType].filter(Boolean)),Array.isArray(e.sourceType)||(e.sourceType=[e.sourceType].filter(Boolean)),e.count=Math.max(1,Math.min(9,parseInt(e.count)||1)),e.sizeType.length===0&&(e.sizeType=[he.COMPRESSED]),e.sourceType.length===0&&(e.sourceType=[ge.ALBUM]),e}function Ve(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(f.type)}function je(t){return u.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!K()){s.info("等待微信配置完成"),F().then(()=>je(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信图片选择",t),window.wx.chooseImage({count:t.count,sizeType:t.sizeType,sourceType:t.sourceType,success:r=>{var n,i;s.info("微信图片选择成功",{count:((n=r.localIds)==null?void 0:n.length)||0}),(i=t.success)==null||i.call(t,r)},fail:r=>{var n;s.error("微信图片选择失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"chooseImageInWeixin",platform:"weixin"})}function dr(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用图片选择",t),x("chooseImage",N(h({},t),{disableTimeout:!0}),{success:e=>{var r,n;s.info("UniApp 图片选择成功",{count:((r=e==null?void 0:e.tempFilePaths)==null?void 0:r.length)||0}),(n=t.success)==null||n.call(t,e)},fail:e=>{var r;s.error("UniApp 图片选择失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"chooseImageInUniApp",platform:"uniapp"})}function fr(t={}){return u.safeExecute(()=>{var r;if(!Ve()){const n={errMsg:`当前环境 (${f.type}) 不支持图片选择功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持图片选择",{platform:f.type}),(r=t.fail)==null||r.call(t,n);return}const e=lr(t);s.info("开始选择图片",{platform:f.type,count:e.count,sizeType:e.sizeType,sourceType:e.sourceType}),p()?je(e):dr(e)},{context:"chooseImage",options:t})}function gr(){return{supported:Ve(),environment:f.type,implementation:p()?"weixin":"webview",features:{multipleSelection:!0,sizeTypeSelection:!0,sourceTypeSelection:!0,asyncSupport:!0}}}const Y={QR_CODE:"qrCode",BAR_CODE:"barCode",DATA_MATRIX:"datamatrix",PDF417:"pdf417"},hr={onlyFromCamera:!0,scanType:[Y.QR_CODE,Y.BAR_CODE]};function pr(t={}){const e=h(h({},hr),t);return Array.isArray(e.scanType)||(e.scanType=[e.scanType].filter(Boolean)),e.scanType.length===0&&(e.scanType=[Y.QR_CODE,Y.BAR_CODE]),e.onlyFromCamera=!!e.onlyFromCamera,e}function qe(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(f.type)}function Je(t){return u.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!K()){s.info("等待微信配置完成"),F().then(()=>Je(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信扫码",t),window.wx.scanQRCode({needResult:1,scanType:t.scanType,success:r=>{var i;s.info("微信扫码成功",{result:r.resultStr});const n={result:r.resultStr,scanType:mr(r.resultStr),charSet:"utf-8",errMsg:"scanCode:ok"};(i=t.success)==null||i.call(t,n)},fail:r=>{var n;s.error("微信扫码失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"scanCodeInWeixin",platform:"weixin"})}function mr(t){return t?t.length>50||/[^\d]/.test(t)?Y.QR_CODE:Y.BAR_CODE:"unknown"}function wr(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用扫码",t),x("scanCode",N(h({},t),{disableTimeout:!0}),{success:e=>{var r;s.info("UniApp 扫码成功",{result:e==null?void 0:e.result,scanType:e==null?void 0:e.scanType}),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 扫码失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"scanCodeInUniApp",platform:"uniapp"})}function Er(t={}){return u.safeExecute(()=>{var r;if(!qe()){const n={errMsg:`当前环境 (${f.type}) 不支持扫码功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持扫码",{platform:f.type}),(r=t.fail)==null||r.call(t,n);return}const e=pr(t);s.info("开始扫码",{platform:f.type,onlyFromCamera:e.onlyFromCamera,scanType:e.scanType}),p()?Je(e):wr(e)},{context:"scanCode",options:t})}function yr(){return{supported:qe(),environment:f.type,implementation:p()?"weixin":"webview",features:{onlyFromCamera:!0,scanTypeSelection:!0,multipleTypes:!0,asyncSupport:!0}}}const pe={WGS84:"wgs84",GCJ02:"gcj02",BD09:"bd09"},Ir={type:pe.WGS84,altitude:!1},Ar={scale:18};function Or(t={}){const e=h(h({},Ir),t);return Object.values(pe).includes(e.type)||(e.type=pe.WGS84),e.altitude=!!e.altitude,e}function _r(t={}){const e=h(h({},Ar),t);if(e.latitude===void 0||e.latitude===null)throw{errMsg:"缺少必需参数:latitude(纬度)",code:"PARAM_MISSING"};if(typeof e.latitude!="number")throw{errMsg:`latitude 参数类型错误:期望 number,实际 ${typeof e.latitude}`,code:"PARAM_TYPE_ERROR",details:{param:"latitude",expected:"number",actual:typeof e.latitude,value:e.latitude}};if(e.latitude<-90||e.latitude>90)throw{errMsg:`latitude 超出范围:有效范围 -90 ~ 90,实际值 ${e.latitude}`,code:"PARAM_INVALID",details:{param:"latitude",value:e.latitude,validRange:"-90 ~ 90"}};if(e.longitude===void 0||e.longitude===null)throw{errMsg:"缺少必需参数:longitude(经度)",code:"PARAM_MISSING"};if(typeof e.longitude!="number")throw{errMsg:`longitude 参数类型错误:期望 number,实际 ${typeof e.longitude}`,code:"PARAM_TYPE_ERROR",details:{param:"longitude",expected:"number",actual:typeof e.longitude,value:e.longitude}};if(e.longitude<-180||e.longitude>180)throw{errMsg:`longitude 超出范围:有效范围 -180 ~ 180,实际值 ${e.longitude}`,code:"PARAM_INVALID",details:{param:"longitude",value:e.longitude,validRange:"-180 ~ 180"}};if(e.scale!==void 0&&e.scale!==null){const r=Number(e.scale);isNaN(r)?(s.warn("scale 参数无效,使用默认值 18",{scale:e.scale}),e.scale=18):e.scale=Math.max(1,Math.min(28,Math.floor(r)))}return e}function Oe(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(f.type)}function He(t){return u.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!K()){s.info("等待微信配置完成"),F().then(()=>He(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信定位",t),window.wx.getLocation({type:t.type,success:r=>{var n;s.info("微信定位成功",{latitude:r.latitude,longitude:r.longitude}),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;s.error("微信定位失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"getLocationInWeixin",platform:"weixin"})}function Ye(t){return u.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!K()){s.info("等待微信配置完成"),F().then(()=>Ye(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信查看位置",t),window.wx.openLocation({latitude:t.latitude,longitude:t.longitude,name:t.name||"",address:t.address||"",scale:t.scale||18,infoUrl:t.infoUrl||"",success:r=>{var n;s.info("微信查看位置成功"),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;s.error("微信查看位置失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"openLocationInWeixin",platform:"weixin"})}function Nr(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用获取位置",t),x("getLocation",t,{success:e=>{var r;s.info("UniApp 获取位置成功",{latitude:e==null?void 0:e.latitude,longitude:e==null?void 0:e.longitude}),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 获取位置失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"getLocationInUniApp",platform:"uniapp"})}function Rr(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用查看位置",t),x("openLocation",t,{success:e=>{var r;s.info("UniApp 查看位置成功"),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 查看位置失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"openLocationInUniApp",platform:"uniapp"})}function Sr(t={}){return u.safeExecute(()=>{var r;if(!Oe()){const n={errMsg:`当前环境 (${f.type}) 不支持定位功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持定位",{platform:f.type}),(r=t.fail)==null||r.call(t,n);return}const e=Or(t);s.info("开始获取位置",{platform:f.type,type:e.type,altitude:e.altitude}),p()?He(e):Nr(e)},{context:"getLocation",options:t})}function Tr(t={}){return u.safeExecute(()=>{var r,n,i;if(!Oe()){const a={errMsg:`当前环境 (${f.type}) 不支持查看位置功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持查看位置",{platform:f.type}),(r=t.fail)==null||r.call(t,a);return}let e;try{e=_r(t)}catch(a){s.error("参数验证失败",a),(n=t.fail)==null||n.call(t,a),(i=t.complete)==null||i.call(t);return}s.info("开始查看位置",{platform:f.type,latitude:e.latitude,longitude:e.longitude,name:e.name}),p()?Ye(e):Rr(e)},{context:"openLocation",options:t})}function Pr(){return{supported:Oe(),environment:f.type,implementation:p()?"weixin":"webview",features:{getLocation:!0,openLocation:!0,coordinateTypes:!0,altitudeSupport:!0,asyncSupport:!0}}}const Cr={latitude:null,longitude:null};function Mr(t={}){const e=h(h({},Cr),t);return e.latitude!==null&&e.latitude!==void 0&&(typeof e.latitude!="number"?(s.warn("latitude 参数类型错误,已忽略",{latitude:e.latitude}),e.latitude=null):(e.latitude<-90||e.latitude>90)&&(s.warn("latitude 超出范围,已忽略",{latitude:e.latitude}),e.latitude=null)),e.longitude!==null&&e.longitude!==void 0&&(typeof e.longitude!="number"?(s.warn("longitude 参数类型错误,已忽略",{longitude:e.longitude}),e.longitude=null):(e.longitude<-180||e.longitude>180)&&(s.warn("longitude 超出范围,已忽略",{longitude:e.longitude}),e.longitude=null)),e}function Xe(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(f.type)}function Ze(t){return u.safeExecute(()=>{var n;if(!window.wx){const i={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(n=t.fail)==null||n.call(t,i);return}if(!K()){s.info("等待微信配置完成"),F().then(()=>Ze(t)).catch(i=>{var a;s.error("微信配置失败",i),(a=t.fail)==null||a.call(t,{errMsg:`微信配置失败: ${i.message}`})});return}s.debug("调用微信位置选择",t);const e={success:i=>{var g;s.info("微信位置选择成功",{name:i.name,address:i.address,latitude:i.latitude,longitude:i.longitude});const a={name:i.name,address:i.address,latitude:i.latitude,longitude:i.longitude,errMsg:"chooseLocation:ok"};(g=t.success)==null||g.call(t,a)},fail:i=>{var a;s.error("微信位置选择失败",i),(a=t.fail)==null||a.call(t,i)},complete:t.complete},r={};t.latitude!==null&&t.latitude!==void 0&&(r.latitude=t.latitude),t.longitude!==null&&t.longitude!==void 0&&(r.longitude=t.longitude),window.wx.chooseLocation(N(h({},r),{success:e.success,fail:e.fail,complete:e.complete}))},{context:"chooseLocationInWeixin",platform:"weixin"})}function br(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用位置选择",t);const e={disableTimeout:!0,success:r=>{var n;s.info("UniApp 位置选择成功",{name:r==null?void 0:r.name,address:r==null?void 0:r.address,latitude:r==null?void 0:r.latitude,longitude:r==null?void 0:r.longitude}),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;s.error("UniApp 位置选择失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete};t.latitude!==null&&t.latitude!==void 0&&(e.latitude=t.latitude),t.longitude!==null&&t.longitude!==void 0&&(e.longitude=t.longitude),x("chooseLocation",e,{success:r=>{e.success(r)},fail:r=>{e.fail(r)},complete:e.complete})},{context:"chooseLocationInUniApp",platform:"uniapp"})}function vr(t={}){return u.safeExecute(()=>{var r;if(!Xe()){const n={errMsg:`当前环境 (${f.type}) 不支持位置选择功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持位置选择",{platform:f.type}),(r=t.fail)==null||r.call(t,n);return}const e=Mr(t);s.info("开始选择位置",{platform:f.type,latitude:e.latitude,longitude:e.longitude}),p()?Ze(e):br(e)},{context:"chooseLocation",options:t})}function Lr(){return{supported:Xe(),environment:f.type,implementation:p()?"weixin":"webview",features:{chooseLocation:!0,centerPoint:!0,asyncSupport:!0}}}const Qe=new Map;function Dr(t,e={}){Qe.set(t,e)}function xr(t,e){const r=Qe.get(t);if(r)return r[e]||r.default}const Ur={0:"WXSceneSession",1:"WXSceneTimeline"},Wr={0:"图文/网页",1:"纯文字",2:"纯图片",3:"音乐",4:"视频",5:"小程序"};function et(t={}){return u.safeExecute(()=>{var n,i;if(typeof window=="undefined"||!window.wx){const a={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};return(n=t.fail)==null||n.call(t,a),Promise.reject(a)}if(!K())return s.info("等待微信配置完成"),F().then(()=>et(t));const e=tt(t);if(!e.success){const a={errMsg:e.message||"参数校验失败",code:"INVALID_PARAMS"};return(i=t.fail)==null||i.call(t,a),Promise.reject(a)}const r=e.params;return s.debug("调用微信分享",r),new Promise((a,g)=>{window.wx[r.scene](N(h({},r),{success:()=>{var d;const l={errMsg:"weixinShare:ok"};(d=t.success)==null||d.call(t,l),a(l)},fail:l=>{var A;const d={errMsg:(l==null?void 0:l.errMsg)||"weixinShare:fail",details:l};s.error("微信分享失败",d),(A=t.fail)==null||A.call(t,d),g(d)},complete:t.complete}))})},{context:"toShareInWeixin",platform:"weixin"})}function tt(t={}){const e=h({},t),r={scene:e.scene===1?"updateTimelineShareData":"updateAppMessageShareData"};return s.info("格式化微信参数",e),Object.prototype.hasOwnProperty.call(e,"title")?Object.prototype.hasOwnProperty.call(e,"imageUrl")?Object.prototype.hasOwnProperty.call(e,"path")?Object.prototype.hasOwnProperty.call(e,"summary")?(r.title=e.title,r.imgUrl=e.imageUrl,r.link=e.path,r.desc=e.summary,{params:r,success:!0}):{message:"参数字段summary值缺少!",success:!1}:{message:"参数字段path值缺少!",success:!1}:{message:"参数字段imageUrl值缺少!",success:!1}:{message:"参数字段title值缺少!",success:!1}}function ne(t={}){return u.safeExecute(()=>(s.debug("通过 WebView 桥接调用微信分享",t),new Promise((e,r)=>{x("toShareData",t,{success:n=>{var i;(i=t.success)==null||i.call(t,n),e(n)},fail:n=>{var i;s.error("UniApp 微信分享失败",n),(i=t.fail)==null||i.call(t,n),r(n)},complete:t.complete})})),{context:"toShareInUniApp",platform:"uniapp"})}function $r(t={}){const e=h({},t),r={provider:"weixin",scene:"WXSceneSession"};if(s.info("格式化 UniApp 参数",e),[0,1].some(n=>parseInt(n)===parseInt(e.scene))?r.scene=Ur[e.scene]:r.scene="WXSceneSession",Object.prototype.hasOwnProperty.call(e,"type")){const n=Number(e.type);if(Object.keys(Wr).some(a=>parseInt(a)===n)){if(r.type=n,[0].includes(n))if(Object.prototype.hasOwnProperty.call(e,"path"))r.href=e.path;else return{message:"参数字段path值缺少!",success:!1};if([0,1].includes(n))if(Object.prototype.hasOwnProperty.call(e,"summary"))r.summary=e.summary;else return{message:"参数字段summary值缺少!",success:!1};if([0,2,5].includes(n))if(Object.prototype.hasOwnProperty.call(e,"imageUrl"))r.imageUrl=e.imageUrl;else return{message:"参数字段imageUrl值缺少!",success:!1};[5].includes(n)&&Object.prototype.hasOwnProperty.call(e,"miniProgram")&&h({},e.miniProgram),Object.prototype.hasOwnProperty.call(e,"title")&&(r.title=e.title),Object.prototype.hasOwnProperty.call(e,"success")&&(r.success=e.success),Object.prototype.hasOwnProperty.call(e,"fail")&&(r.fail=e.fail),Object.prototype.hasOwnProperty.call(e,"complete")&&(r.complete=e.complete)}else return{message:"参数字段type值有误!",success:!1}}else return{message:"参数字段type缺少!",success:!1};return{params:r,success:!0}}const rt="share.toShare";Dr(rt,{weixin:et,webview:ne,plus:ne,nvue:ne,uvue:ne,UniApp:ne,h5:ne,default:void 0});function kr(t={}){return u.safeExecute(()=>{var a,g;const e=Ee(),r=xr(rt,e.type);if(typeof r!="function"){const l={errMsg:`当前环境 (${e.type}) 不支持微信分享功能`,code:"PLATFORM_NOT_SUPPORTED"};return s.error("平台不支持微信分享",{platform:e.type}),(a=t.fail)==null||a.call(t,l),Promise.reject(l)}const n=p()?tt(t):$r(t);if(!n.success){const l={errMsg:n.message||"参数校验失败",code:"INVALID_PARAMS"};return(g=t.fail)==null||g.call(t,l),Promise.reject(l)}const i=n.params;return s.info("开始微信分享",{platform:e.type,type:i==null?void 0:i.type}),r(i)},{context:"toShare",options:t})}const Br={OFF:"off",ON:"on",UNAVAILABLE:"unavailable",UNAUTHORIZED:"unauthorized"},Fr={allowDuplicatesKey:!1,services:[]};function me(t={}){return h(h({},Fr),t)}function le(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(f.type)}function Kr(t){return u.safeExecute(()=>E(null,null,function*(){var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}K()||(s.info("等待微信配置完成"),yield F()),wx.openBluetoothAdapter({success:()=>{s.info("微信蓝牙适配器已打开"),nt(t)},fail:r=>{var n;s.error("蓝牙适配器打开失败",r),(n=t.fail)==null||n.call(t,r)}})}),{context:"openBluetoothAdapterInWeixin"})}function zr(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用蓝牙功能",t),x("bluetooth",t,{success:e=>{var r;s.info("UniApp 蓝牙调用成功",e),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 蓝牙调用失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"bluetoothInUniApp"})}function Gr(t){return u.safeExecute(()=>{var e;s.debug("通过 WebView 桥接调用蓝牙设备搜索功能",t),x("bluetoothDevicesDiscovery",{action:"startBluetoothDevicesDiscovery",params:{services:t.services||[],allowDuplicatesKey:(e=t.allowDuplicatesKey)!=null?e:!1}},{success:r=>{var n;console.log("[Bluetooth] 设备开启搜索成功:",r),s.info("UniApp 蓝牙设备开启搜索成功",r),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;console.error("[Bluetooth] 设备开启搜索失败:",r),s.error("UniApp 蓝牙设备开启搜索失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"startBluetoothDevicesDiscoveryInUniApp"})}const we=new Set;function Vr(t,e={}){return u.safeExecute(()=>{var r;return we.add(t),we.size===1&&x("onBluetoothDeviceFound",{action:"onBluetoothDeviceFound",isPersistent:!0,params:{services:e.services||[],allowDuplicatesKey:(r=e.allowDuplicatesKey)!=null?r:!1}},{success:n=>{we.forEach(i=>{typeof i=="function"?u.safeExecute(()=>i(n),{context:"BluetoothDeviceCallback"}):console.warn("[BluetoothDeviceCallback] 不是函数:",i)})},fail:n=>{var i;console.error("[Bluetooth] 搜索失败:",n),(i=e.fail)==null||i.call(e,n)},complete:e.complete}),()=>we.delete(t)},{context:"qsh_onBluetoothDeviceFound"})}function jr(t){return u.safeExecute(()=>{var e;s.debug("通过 WebView 桥接调用蓝牙连接功能",t),x("bluetoothConnection",{action:"createBLEConnection",params:{deviceId:t.deviceId,name:t.name,autoConnect:(e=t.autoConnect)!=null?e:!1}},{success:r=>{var n;console.log("[Bluetooth] 蓝牙连接成功:",r),s.info("UniApp 蓝牙连接成功",r),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;console.error("[Bluetooth] 蓝牙连接失败:",r),s.error("UniApp 蓝牙连接失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"createBLEConnectionInUniApp"})}function qr(t={}){return u.safeExecute(()=>{var r;if(!le()){const n={errMsg:`当前环境 (${f.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙",{platform:f.type}),(r=t.fail)==null||r.call(t,n);return}const e=me(t);s.info("开始蓝牙操作",{platform:f.type,services:e.services,allowDuplicatesKey:e.allowDuplicatesKey}),p()?Kr(e):zr(e)},{context:"openBluetoothAdapter",options:t})}function Jr(t={}){return u.safeExecute(()=>{var r,n;if(!le()){const i={errMsg:`当前环境 (${f.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙",{platform:f.type}),(r=t.fail)==null||r.call(t,i),(n=t.complete)==null||n.call(t,i);return}const e=me(t);s.info("开始搜索蓝牙设备",{platform:f.type,services:e.services,allowDuplicatesKey:e.allowDuplicatesKey}),p()?startBluetoothDevicesDiscoveryInWeixin(e):Gr(e)},{context:"startBluetoothDevicesDiscovery",options:t})}function nt(t,e={}){return u.safeExecute(()=>{var n,i;if(!le()){const a={errMsg:`当前环境 (${f.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙",{platform:f.type}),(n=e.fail)==null||n.call(e,a),(i=e.complete)==null||i.call(e,a);return}const r=me(e);s.info("注册蓝牙设备发现监听",{platform:f.type}),p()?onBluetoothDeviceFoundInWeixin(r):Vr(t,r)},{context:"onBluetoothDeviceFound",options:e})}function Hr(t={}){return u.safeExecute(()=>{var a,g,l,d;if(!le()){const A={errMsg:`当前环境 (${f.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙连接",{platform:f.type}),(a=t.fail)==null||a.call(t,A),(g=t.complete)==null||g.call(t,A);return}const e=me(t),{name:r,deviceId:n,autoConnect:i=!1}=e;if(!n){const A={errMsg:"缺少 deviceId 参数",code:"INVALID_PARAMS"};(l=t.fail)==null||l.call(t,A),(d=t.complete)==null||d.call(t,A);return}s.info("创建蓝牙连接",{deviceId:n,autoConnect:i,platform:f.type}),p()?uni.createBLEConnection({deviceId:n,autoConnect:i,success:t.success,fail:t.fail,complete:t.complete}):jr(e)},{context:"createBLEConnection",options:t})}function Yr(){return{supported:le(),environment:f.type,implementation:p()?"weixin":"webview",features:{discovery:!0,connect:!0,readWrite:!0,notify:!0,asyncSupport:!0}}}const it=Ee();q.useResponse($e.response,{priority:1e3});let st=!1;function at(){if(st)return;st=!0,jt([{name:"load-weixin-sdk",run:Ct,timeoutMs:8e3},{name:"init-bridge",run:ve,timeoutMs:8e3}],{onError:(e,r)=>{console.error(`[QSH-SDK] 初始化失败(${(r==null?void 0:r.name)||"unknown"}):`,e)}})}typeof window!="undefined"&&(document.readyState==="complete"||document.readyState==="interactive"?setTimeout(at,0):document.addEventListener("DOMContentLoaded",at));function R(t,{apiName:e}={}){return function(r={},...n){const i=r&&typeof r=="object"&&(typeof r.success=="function"||typeof r.fail=="function"||typeof r.complete=="function"),a=r&&typeof r=="object"?r:{},g=()=>i?t(a,...n):new Promise((d,A)=>{const b=N(h({},a),{success:P=>{typeof a.success=="function"&&a.success(P),d(P)},fail:P=>{typeof a.fail=="function"&&a.fail(P),A(P)},complete:a.complete});t(b,...n)});return(typeof window=="undefined"?Promise.resolve():Me()).then(()=>g()).catch(d=>{throw console.error(`[QSH-SDK] ${e||"API"} call failed:`,d),d})}}const ot=R(Zt),ct=R(Qt),ut=R(er),lt=R(tr),dt=R(rr),ft=R(nr);function gt(t){const e=()=>ir(t);return(typeof window=="undefined"?Promise.resolve():Me()).then(()=>e())}const _e=R(fr);function Xr(t={}){return new Promise((e,r)=>{_e(N(h({},t),{success:e,fail:r}))})}const Ne=R(Er);function Zr(t={}){return new Promise((e,r)=>{Ne(N(h({},t),{success:e,fail:r}))})}const Qr=R(kr),Re=R(Sr);function en(t={}){return new Promise((e,r)=>{Re(N(h({},t),{success:e,fail:r}))})}const Se=R(Tr);function tn(t={}){return new Promise((e,r)=>{Se(N(h({},t),{success:e,fail:r}))})}const Te=R(vr);function rn(t={}){return new Promise((e,r)=>{Te(N(h({},t),{success:e,fail:r}))})}const ht=R(qr);function nn(t={}){return new Promise((e,r)=>{ht(N(h({},t),{success:e,fail:r}))})}const pt=R(Jr);function sn(t={}){return new Promise((e,r)=>{pt(N(h({},t),{success:e,fail:r}))})}const mt=R(nt);function an(t={}){return new Promise((e,r)=>{mt(N(h({},t),{success:e,fail:r}))})}const wt=R(Hr);function on(t={}){return new Promise((e,r)=>{wt(N(h({},t),{success:e,fail:r}))})}const X={navigateTo:ot,navigateBack:ct,switchTab:ut,reLaunch:lt,redirectTo:dt,postMessage:ft,getEnv:gt,chooseImage:_e,chooseImageAsync:Xr,scanCode:Ne,scanCodeAsync:Zr,getLocation:Re,getLocationAsync:en,openLocation:Se,openLocationAsync:tn,chooseLocation:Te,chooseLocationAsync:rn,environment:it,ready:St,init:ve,isReady:At,getState:Ot,weixin:{waitForConfig:F,isConfigReady:K,getConfigState:Mt,retryConfig:bt},webView:null,ImageSourceTypes:ge,ImageSizeTypes:he,getImageCapabilities:gr,ScanTypes:Y,getScanCapabilities:yr,CoordinateTypes:pe,getLocationCapabilities:Pr,getChooseLocationCapabilities:Lr,openBluetoothAdapter:ht,openBluetoothAdapterAsync:nn,startBluetoothDevicesDiscovery:pt,startBluetoothDevicesDiscoveryAsync:sn,onBluetoothDeviceFound:mt,onBluetoothDeviceFoundAsync:an,createBLEConnection:wt,createBLEConnectionAsync:on,BluetoothStates:Br,toShare:Qr,getBluetoothCapabilities:Yr,plugins:{manager:ae,register:t=>ae.register(t),install:t=>ae.install(t,X),list:()=>ae.getPluginList()},interceptors:{chain:q,useRequest:(t,e)=>q.useRequest(t,e),useResponse:(t,e)=>q.useResponse(t,e),builtin:{logging:Dt,performance:z,createRetry:xt,createValidation:Ut,errorNormalizer:$e}},metrics:{getPerformanceReport:()=>z.getReport(),clearPerformanceMetrics:()=>z.clearMetrics()},errors:{codes:o,messages:Ae,categories:D,normalize:We,create:zt,isStandard:Gt},store:{instance:U,get:t=>U.get(t),set:(t,e)=>U.set(t,e),subscribe:(t,e)=>U.subscribe(t,e),getSnapshot:()=>U.getSnapshot()},debug:{logger:S,setLogReporter:t=>S.setReporter(t),errorHandler:u,stateManager:j,enableDevMode:()=>S.enableDevMode(),getLogs:t=>S.getHistory(t),getStats:()=>({logger:S.getStats(),state:j.getStats(),weixinConfig:Le().getStats(),plugins:ae.getStats(),interceptors:q.getStats(),store:U.getStats()}),getWeixinConfigManager:Le,exportDebugInfo:()=>S.exportToJSON()}};it.isWeixinMiniProgram?X.webView=window.wx&&window.wx.miniProgram:X.webView={navigateTo:ot,navigateBack:ct,switchTab:ut,reLaunch:lt,redirectTo:dt,postMessage:ft,getEnv:gt,chooseImage:_e,scanCode:Ne,getLocation:Re,openLocation:Se,chooseLocation:Te};const Et=typeof window.uni!="undefined"?window.uni:{};return Object.keys(Et).forEach(t=>{X.hasOwnProperty(t)||(X[t]=Et[t])}),typeof window!="undefined"&&(window.qsh=X),X});
|
|
1
|
+
(function(A,m){typeof exports=="object"&&typeof module!="undefined"?module.exports=m():typeof define=="function"&&define.amd?define(m):(A=typeof globalThis!="undefined"?globalThis:A||self,A.qsh=m())})(this,function(){"use strict";var Pn=Object.defineProperty,Tn=Object.defineProperties;var Ln=Object.getOwnPropertyDescriptors;var St=Object.getOwnPropertySymbols;var Mn=Object.prototype.hasOwnProperty,bn=Object.prototype.propertyIsEnumerable;var ve=(A,m,p)=>m in A?Pn(A,m,{enumerable:!0,configurable:!0,writable:!0,value:p}):A[m]=p,g=(A,m)=>{for(var p in m||(m={}))Mn.call(m,p)&&ve(A,p,m[p]);if(St)for(var p of St(m))bn.call(m,p)&&ve(A,p,m[p]);return A},_=(A,m)=>Tn(A,Ln(m));var $=(A,m,p)=>ve(A,typeof m!="symbol"?m+"":m,p);var E=(A,m,p)=>new Promise((ee,j)=>{var te=v=>{try{q(p.next(v))}catch(ce){j(ce)}},re=v=>{try{q(p.throw(v))}catch(ce){j(ce)}},q=v=>v.done?ee(v.value):Promise.resolve(v.value).then(te,re);q((p=p.apply(A,m)).next())});function A(){return typeof window!="undefined"?window:void 0}function m(){return typeof navigator=="undefined"?"":navigator.userAgent||""}function p(){const t=A();if(!t)return!1;if(t.__wxjs_environment==="miniprogram"||t.wx&&t.wx.miniProgram)return!0;const e=m();return!!(e&&/micromessenger/i.test(e)&&/miniProgram/i.test(e))}function ee(){const t=A();return!!(t&&t.plus)}function j(){const t=A();return!!(t&&(t.__dcloud_weex_postMessage||t.__dcloud_weex_))}function te(){const t=A();return!!(t&&(t.__uniapp_x_postMessage||t.__uniapp_x_))}function re(){const t=m();return/uni-app/i.test(t)}function q(){const t=m();return/Html5Plus/i.test(t)}function v(){return re()||q()}function ce(){return te()?"uvue":j()?"nvue":p()?"weixin":ee()?"plus":v()?"webview":re()?"UniApp":"h5"}let he=null;function Oe(t=!1){return he&&!t||(he={isWeixinMiniProgram:p(),isAppPlus:ee(),isNvue:j(),isUvue:te(),isUniApp:re(),isHtml5Plus:q(),isUniAppWebView:v(),type:ce()}),he}const c=Oe(),B={PLATFORM_NOT_SUPPORTED:"PLATFORM_NOT_SUPPORTED",API_CALL_FAILED:"API_CALL_FAILED",BRIDGE_NOT_READY:"BRIDGE_NOT_READY",INVALID_PARAMETERS:"INVALID_PARAMETERS",NETWORK_ERROR:"NETWORK_ERROR"};class M extends Error{constructor(e,r,n={},i=null){super(r),this.name="QshError",this.type=e,this.context=n,this.originalError=i,this.timestamp=new Date().toISOString(),Error.captureStackTrace&&Error.captureStackTrace(this,M)}toJSON(){return{name:this.name,type:this.type,message:this.message,context:this.context,timestamp:this.timestamp,stack:this.stack}}}const N=class N{static setDebugMode(e){N.isDebugMode=e}static addErrorCallback(e){typeof e=="function"&&N.errorCallbacks.push(e)}static removeErrorCallback(e){const r=N.errorCallbacks.indexOf(e);r>-1&&N.errorCallbacks.splice(r,1)}static handleApiError(e,r={}){let n;return e instanceof M?n=e:e instanceof Error?n=new M(B.API_CALL_FAILED,e.message,r,e):n=new M(B.API_CALL_FAILED,String(e),r),N.logError(n),N.notifyCallbacks(n),n}static handlePlatformNotSupported(e,r){const n=new M(B.PLATFORM_NOT_SUPPORTED,`API "${r}" is not supported on platform "${e}"`,{platformType:e,apiName:r});return N.logError(n),N.notifyCallbacks(n),n}static handleBridgeNotReady(e){const r=new M(B.BRIDGE_NOT_READY,`Bridge is not ready when calling "${e}"`,{apiName:e});return N.logError(r),N.notifyCallbacks(r),r}static handleInvalidParameters(e,r,n,i){const a=new M(B.INVALID_PARAMETERS,`Invalid parameter "${r}" in "${e}": expected ${n}, got ${typeof i}`,{apiName:e,paramName:r,expectedType:n,actualValue:i});return N.logError(a),N.notifyCallbacks(a),a}static safeExecute(e,r={}){try{return e()}catch(n){return N.handleApiError(n,r)}}static safeExecuteAsync(n){return E(this,arguments,function*(e,r={}){try{return yield e()}catch(i){return N.handleApiError(i,r)}})}static logError(e){if(typeof console!="undefined"){const r=`[QSH-SDK Error] ${e.type}: ${e.message}`;N.isDebugMode?console.error(r,{context:e.context,originalError:e.originalError,stack:e.stack,timestamp:e.timestamp}):console.error(r)}}static notifyCallbacks(e){N.errorCallbacks.forEach(r=>{try{r(e)}catch(n){typeof console!="undefined"&&console.error("[QSH-SDK] Error in error callback:",n)}})}static createErrorDecorator(e={}){return function(r,n,i){const a=i.value;return i.value=function(...h){return N.safeExecute(()=>a.apply(this,h),_(g({},e),{method:n,target:r.constructor.name}))},i}}};$(N,"isDebugMode",!1),$(N,"errorCallbacks",[]);let u=N;const L={UNINITIALIZED:"uninitialized",INITIALIZING:"initializing",READY:"ready",ERROR:"error"};class Pt{constructor(){this.state=L.UNINITIALIZED,this.readyPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.initializationError=null,this.handleBridgeReady=this.handleBridgeReady.bind(this),this.handleInitializationError=this.handleInitializationError.bind(this)}getState(){return this.state}isReady(){return this.state===L.READY}isInitializing(){return this.state===L.INITIALIZING}hasError(){return this.state===L.ERROR}getInitializationError(){return this.initializationError}waitForReady(){return this.isReady()?Promise.resolve():this.hasError()?Promise.reject(this.initializationError):(this.readyPromise||(this.readyPromise=new Promise((e,r)=>{this.isReady()?e():this.hasError()?r(this.initializationError):(this.readyCallbacks.push(e),this.errorCallbacks.push(r))})),this.readyPromise)}startInitialization(e){return E(this,null,function*(){if(this.state!==L.UNINITIALIZED)return this.waitForReady();this.state=L.INITIALIZING;try{yield e(),this.handleBridgeReady()}catch(r){throw this.handleInitializationError(r),r}return this.waitForReady()})}handleBridgeReady(){this.state===L.INITIALIZING&&(this.state=L.READY,this.readyCallbacks.forEach(e=>{try{e()}catch(r){u.handleApiError(r,{context:"StateManager.handleBridgeReady"})}}),this.readyCallbacks=[],this.errorCallbacks=[])}handleInitializationError(e){this.state=L.ERROR,this.initializationError=e,this.errorCallbacks.forEach(r=>{try{r(e)}catch(n){u.handleApiError(n,{context:"StateManager.handleInitializationError"})}}),this.readyCallbacks=[],this.errorCallbacks=[]}reset(){this.state=L.UNINITIALIZED,this.readyPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.initializationError=null}onStateChange(e,r){if(this.state===e)return setTimeout(()=>r(this.state),0),()=>{};const n=()=>{this.state===e&&r(this.state)};return e===L.READY?this.readyCallbacks.push(n):e===L.ERROR&&this.errorCallbacks.push(n),()=>{const i=this.readyCallbacks.indexOf(n);i>-1&&this.readyCallbacks.splice(i,1);const a=this.errorCallbacks.indexOf(n);a>-1&&this.errorCallbacks.splice(a,1)}}getStats(){return{state:this.state,readyCallbacksCount:this.readyCallbacks.length,errorCallbacksCount:this.errorCallbacks.length,hasReadyPromise:!!this.readyPromise,hasInitializationError:!!this.initializationError}}}const J=new Pt,xe=()=>J.waitForReady(),Tt=()=>J.isReady(),Lt=()=>J.getState(),w={ERROR:0,WARN:1,INFO:2,DEBUG:3,TRACE:4},ue={[w.ERROR]:"ERROR",[w.WARN]:"WARN",[w.INFO]:"INFO",[w.DEBUG]:"DEBUG",[w.TRACE]:"TRACE"},l=class l{static setLevel(e){e>=w.ERROR&&e<=w.TRACE&&(l.currentLevel=e,l.log(w.INFO,"Logger",`日志级别设置为: ${ue[e]}`))}static enableDevMode(){l.setLevel(w.DEBUG),l.log(w.INFO,"Logger","开发模式已启用")}static enableProdMode(){l.setLevel(w.WARN),l.log(w.INFO,"Logger","生产模式已启用")}static enableModule(e){l.enabledModules.add(e),l.log(w.INFO,"Logger",`模块日志已启用: ${e}`)}static disableModule(e){l.enabledModules.delete(e),l.log(w.INFO,"Logger",`模块日志已禁用: ${e}`)}static shouldLog(e,r){return e>l.currentLevel?!1:r&&l.enabledModules.size>0?l.enabledModules.has(r):!0}static log(e,r,n,...i){if(!l.shouldLog(e,r))return;const a=new Date().toISOString(),h=ue[e],f=r?`[${r}]`:"",d=`${l.prefix} ${f} ${n}`,O={timestamp:a,level:e,levelName:h,module:r,message:n,args:i};if(l.addToHistory(O),typeof l.reporter=="function")try{l.reporter(O)}catch(b){}l.outputToConsole(e,d,...i)}static addToHistory(e){l.logHistory.push(e),l.logHistory.length>l.maxHistorySize&&l.logHistory.shift()}static outputToConsole(e,r,...n){if(typeof console=="undefined")return;const i=n&&n.length>0;switch(e){case w.ERROR:i?console.error(r,...n):console.error(r);break;case w.WARN:i?console.warn(r,...n):console.warn(r);break;case w.INFO:i?console.info(r,...n):console.info(r);break;case w.DEBUG:case w.TRACE:i?console.log(r,...n):console.log(r);break}}static error(e,r,...n){l.log(w.ERROR,e,r,...n)}static warn(e,r,...n){l.log(w.WARN,e,r,...n)}static info(e,r,...n){l.log(w.INFO,e,r,...n)}static debug(e,r,...n){l.log(w.DEBUG,e,r,...n)}static trace(e,r,...n){l.log(w.TRACE,e,r,...n)}static getHistory(e){return e&&e>0?l.logHistory.slice(-e):[...l.logHistory]}static clearHistory(){l.logHistory=[],l.log(w.INFO,"Logger","日志历史已清空")}static getStats(){const e={currentLevel:l.currentLevel,currentLevelName:ue[l.currentLevel],enabledModules:Array.from(l.enabledModules),historySize:l.logHistory.length,maxHistorySize:l.maxHistorySize},r={};for(const n of Object.keys(ue))r[ue[n]]=0;return l.logHistory.forEach(n=>{r[n.levelName]++}),e.levelCounts=r,e}static exportToJSON(e){const r=l.getHistory(e),n=l.getStats();return JSON.stringify({exportTime:new Date().toISOString(),stats:n,logs:r},null,2)}static createModuleLogger(e){return{error:(r,...n)=>l.error(e,r,...n),warn:(r,...n)=>l.warn(e,r,...n),info:(r,...n)=>l.info(e,r,...n),debug:(r,...n)=>l.debug(e,r,...n),trace:(r,...n)=>l.trace(e,r,...n)}}static setReporter(e){l.reporter=typeof e=="function"?e:null}};$(l,"currentLevel",w.ERROR),$(l,"enabledModules",new Set),$(l,"logHistory",[]),$(l,"maxHistorySize",1e3),$(l,"prefix","[QSH-SDK]"),$(l,"reporter",null);let S=l;if(typeof window!="undefined"){const t=window.location&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"||window.location.hostname.includes("192.168.")),e=window.location&&(window.location.search.includes("debug=true")||window.location.search.includes("qsh_debug=1"));let r=!1;try{r=localStorage&&localStorage.getItem("qsh_debug")==="true"}catch(n){}(t||e||r)&&S.enableDevMode()}const y=S.createModuleLogger("Bridge"),C=S.createModuleLogger("Platform"),s=S.createModuleLogger("API"),x=S.createModuleLogger("State"),De=/complete|loaded|interactive/;function Mt(t){return re()||q()?(y.debug("检测到 APP 环境,开始初始化"),window.__uniapp_x_postMessage||window.__uniapp_x_||window.__dcloud_weex_postMessage||window.__dcloud_weex_?(y.debug("NVUE/UVUE 环境,等待 DOMContentLoaded"),document.addEventListener("DOMContentLoaded",t)):window.plus&&De.test(document.readyState)?(y.debug("Plus 环境已就绪,立即初始化"),setTimeout(t,0)):(y.debug("Plus 环境,等待 plusready 事件"),document.addEventListener("plusready",t)),!0):!1}function bt(t){return window.wx&&window.wx.miniProgram?(y.debug("检测到微信小程序环境,开始初始化"),window.WeixinJSBridge&&window.WeixinJSBridge.invoke?(y.debug("微信 JSBridge 已就绪,立即初始化"),setTimeout(t,0)):(y.debug("微信 JSBridge 未就绪,等待 WeixinJSBridgeReady 事件"),document.addEventListener("WeixinJSBridgeReady",t)),!0):!1}function vt(t){return y.info("开始初始化 JSBridge"),Mt(t)?(y.info("使用 APP 环境初始化"),!0):bt(t)?(y.info("使用微信小程序环境初始化"),!0):(y.debug("使用默认 H5 环境初始化"),De.test(document.readyState)?(y.debug("DOM 已就绪,立即初始化"),setTimeout(t,0)):(y.debug("DOM 未就绪,等待 DOMContentLoaded"),document.addEventListener("DOMContentLoaded",t)),!0)}function xt(){return J.waitForReady()}function Ue(){return J.startInitialization(()=>E(null,null,function*(){return new Promise((t,e)=>{const r=()=>{t()},n=i=>{const a=u.handleApiError(i,{context:"bridge initialization"});e(a)};try{vt(()=>{r()})}catch(i){n(i)}})}))}const P={UNINITIALIZED:"uninitialized",CONFIGURING:"configuring",CONFIGURED:"configured",ERROR:"error"};class Dt{constructor(){this.state=P.UNINITIALIZED,this.configPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.lastError=null,this.CONFIG_API_URL=this.getConfigApiUrl(),this.CLIENT_ID="bmfw-client",this.DEFAULT_JS_API_LIST=["chooseImage","uploadImage","previewImage","downloadImage","getLocalImgData","scanQRCode","getLocation","openLocation","updateAppMessageShareData","updateTimelineShareData"],this.handleConfigSuccess=this.handleConfigSuccess.bind(this),this.handleConfigError=this.handleConfigError.bind(this)}getConfigApiUrl(){return typeof window!="undefined"&&(window.location.hostname==="localhost"||window.location.hostname.includes("127.0.0.1")||window.location.hostname.includes("natappfree.cc")||window.location.port==="5174"),"https://unified-platform-service.xjy2.cn/api/wechat/mp/jssdk-sign"}getCurrentPageUrl(){if(typeof window=="undefined"||!window.location)throw new Error("无法获取当前页面URL");const e=window.location.href,r=e.indexOf("#");return r!==-1?e.substring(0,r):e}fetchWeixinConfig(){return E(this,null,function*(){const e=this.getCurrentPageUrl();if(this.isTestMode())return C.info("使用测试模式,返回模拟配置"),this.getMockConfig();const r=`${this.CONFIG_API_URL}?clientId=${this.CLIENT_ID}&url=${encodeURIComponent(e)}`;C.debug("请求微信配置",{url:r});try{const n=yield fetch(r);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);const i=yield n.json();if(C.debug("微信配置响应",i),!i.success||i.code!==200)throw new Error(`配置获取失败: ${i.message||"未知错误"}`);const{data:a}=i;if(!a||!a.appId||!a.timestamp||!a.nonceStr||!a.signature)throw new Error("配置数据格式不正确,缺少必需字段");return a}catch(n){if(C.error("获取微信配置失败",n),this.shouldUseTestMode(n))return C.warn("网络请求失败,降级到测试模式"),this.getMockConfig();throw new M(B.NETWORK_ERROR,`获取微信配置失败: ${n.message}`,{url:r,originalError:n})}})}isTestMode(){if(typeof window=="undefined")return!1;if(new URLSearchParams(window.location.search).get("qsh_test")==="true")return!0;try{if(localStorage.getItem("qsh_test")==="true")return!0}catch(r){}return!1}shouldUseTestMode(e){const r=window.location.hostname==="localhost"||window.location.hostname.includes("natappfree.cc"),n=!window.wx||!window.wx.miniProgram,i=e.message.includes("CORS")||e.message.includes("Failed to fetch");return r&&n&&i}getMockConfig(){return{appId:"wx_test_app_id",timestamp:Math.floor(Date.now()/1e3).toString(),nonceStr:Math.random().toString(36).substring(2,15),signature:"test_signature_"+Math.random().toString(36).substring(2,10)}}executeWeixinConfig(e){if(this.isTestMode()||e.appId==="wx_test_app_id"){C.info("测试模式:模拟微信配置成功"),setTimeout(()=>{this.handleConfigSuccess()},100);return}if(!window.wx)throw new Error("微信JS-SDK未加载");const r={debug:!1,appId:e.appId,timestamp:parseInt(e.timestamp),nonceStr:e.nonceStr,signature:e.signature,jsApiList:this.DEFAULT_JS_API_LIST};C.info("执行微信配置",r),window.wx.ready(this.handleConfigSuccess),window.wx.error(this.handleConfigError),window.wx.config(r)}handleConfigSuccess(){C.info("微信配置成功"),this.state=P.CONFIGURED,this.readyCallbacks.forEach(e=>{try{e()}catch(r){u.handleApiError(r,{context:"WeixinConfigManager.handleConfigSuccess"})}}),this.readyCallbacks=[],this.errorCallbacks=[]}handleConfigError(e){const r=`微信配置验证失败: ${JSON.stringify(e)}`;C.error(r,e),this.state=P.ERROR,this.lastError=new M(B.API_CALL_FAILED,r,{weixinErrorResponse:e}),this.errorCallbacks.forEach(n=>{try{n(this.lastError)}catch(i){u.handleApiError(i,{context:"WeixinConfigManager.handleConfigError"})}}),this.readyCallbacks=[],this.errorCallbacks=[]}autoConfig(){return E(this,null,function*(){return this.state===P.CONFIGURED?Promise.resolve():this.state===P.ERROR?Promise.reject(this.lastError):this.configPromise?this.configPromise:(this.state=P.CONFIGURING,this.configPromise=this.performAutoConfig(),this.configPromise)})}performAutoConfig(){return E(this,null,function*(){return u.safeExecuteAsync(()=>E(this,null,function*(){if(typeof window=="undefined")throw new Error("非浏览器环境无法执行微信配置");if(!window.wx)throw new Error("微信JS-SDK未加载,无法执行配置");const e=yield this.fetchWeixinConfig();return this.executeWeixinConfig(e),new Promise((r,n)=>{if(this.state===P.CONFIGURED){r();return}if(this.state===P.ERROR){n(this.lastError);return}this.readyCallbacks.push(r),this.errorCallbacks.push(n)})}),{context:"WeixinConfigManager.performAutoConfig"})})}waitForReady(){return this.state===P.CONFIGURED?Promise.resolve():this.state===P.ERROR?Promise.reject(this.lastError):this.state===P.UNINITIALIZED?this.autoConfig():new Promise((e,r)=>{this.readyCallbacks.push(e),this.errorCallbacks.push(r)})}isReady(){return this.state===P.CONFIGURED}getState(){return this.state}getLastError(){return this.lastError}reset(){this.state=P.UNINITIALIZED,this.configPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.lastError=null,C.debug("微信配置管理器已重置")}getStats(){return{state:this.state,readyCallbacksCount:this.readyCallbacks.length,errorCallbacksCount:this.errorCallbacks.length,hasConfigPromise:!!this.configPromise,hasLastError:!!this.lastError,configApiUrl:this.CONFIG_API_URL,clientId:this.CLIENT_ID,jsApiList:this.DEFAULT_JS_API_LIST}}}const F=new Dt;let ne=!1,_e=!1,me=!1;function Ut(){if(typeof window=="undefined"||_e||ne||window.wx&&window.wx.miniProgram)return!1;const t=navigator.userAgent||"",e=/micromessenger/i.test(t),r=/miniProgram/i.test(t),n=typeof window.__wxjs_environment!="undefined"&&window.__wxjs_environment==="miniprogram";return e&&(r||n)}function Ce(){return E(this,null,function*(){if(me)return F.waitForReady();me=!0,C.info("开始自动配置微信JS-SDK");try{yield F.autoConfig(),C.info("微信JS-SDK自动配置完成")}catch(t){C.error("微信JS-SDK自动配置失败",t)}})}function Wt(){return Ut()?document.getElementById("weixin-jssdk")?(ne=!1,_e=!0,me?F.waitForReady():Ce()):new Promise(t=>{ne=!0;try{const e=document.createElement("script");e.id="weixin-jssdk",e.type="text/javascript",e.async=!0,e.src="https://res.wx.qq.com/open/js/jweixin-1.6.2.js",e.onload=function(){return E(this,null,function*(){_e=!0,ne=!1,C.info("微信 JS-SDK 已自动加载");try{yield Ce()}catch(n){C.error("微信配置失败,将使用消息桥作为后备",n)}t()})},e.onerror=function(){ne=!1,C.warn("微信 JS-SDK 加载失败,SDK 将使用消息桥作为后备"),t()},(document.getElementsByTagName("head")[0]||document.documentElement).appendChild(e)}catch(e){ne=!1,C.error("注入微信 JS-SDK 失败",e),t()}}):Promise.resolve()}function k(){return F.waitForReady()}function z(){return F.isReady()}function $t(){return F.getState()}function We(){return F}function Bt(){return E(this,null,function*(){return C.info("手动重试微信配置"),F.reset(),me=!1,Ce()})}class Ft{constructor(){this.plugins=new Map,this.installed=new Set,this.installOrder=[],s.debug("插件管理器已初始化")}register(e){return u.safeExecute(()=>{this.validatePlugin(e);const{name:r,version:n}=e;if(this.plugins.has(r)){const i=this.plugins.get(r);s.warn(`插件 ${r} 已注册(版本 ${i.version}),将被覆盖为版本 ${n}`)}return this.plugins.set(r,e),s.info(`插件已注册: ${r}@${n}`),this},{context:"PluginManager.register",pluginName:e==null?void 0:e.name})}validatePlugin(e){if(!e||typeof e!="object")throw new Error("插件必须是一个对象");if(!e.name||typeof e.name!="string")throw new Error("插件必须有 name 属性(字符串)");if(!e.version||typeof e.version!="string")throw new Error(`插件 ${e.name} 必须有 version 属性(字符串)`);if(!e.install||typeof e.install!="function")throw new Error(`插件 ${e.name} 必须实现 install 方法`);if(e.dependencies&&!Array.isArray(e.dependencies))throw new Error(`插件 ${e.name} 的 dependencies 必须是数组`)}install(e,r){return E(this,null,function*(){return u.safeExecute(()=>E(this,null,function*(){if(!this.plugins.has(e))throw new Error(`插件 ${e} 未注册`);if(this.installed.has(e)){s.debug(`插件 ${e} 已安装,跳过`);return}const n=this.plugins.get(e);if(n.dependencies&&n.dependencies.length>0){s.debug(`安装插件 ${e} 的依赖:`,n.dependencies);for(const i of n.dependencies)yield this.install(i,r)}s.info(`开始安装插件: ${e}@${n.version}`),yield n.install(r),this.installed.add(e),this.installOrder.push(e),s.info(`插件安装成功: ${e}@${n.version}`)}),{context:"PluginManager.install",pluginName:e})})}uninstall(e,r){return E(this,null,function*(){return u.safeExecute(()=>E(this,null,function*(){if(!this.installed.has(e)){s.debug(`插件 ${e} 未安装,跳过卸载`);return}const n=this.plugins.get(e);n.uninstall&&typeof n.uninstall=="function"&&(s.info(`开始卸载插件: ${e}`),yield n.uninstall(r)),this.installed.delete(e);const i=this.installOrder.indexOf(e);i>-1&&this.installOrder.splice(i,1),s.info(`插件已卸载: ${e}`)}),{context:"PluginManager.uninstall",pluginName:e})})}uninstallAll(e){return E(this,null,function*(){const r=[...this.installOrder].reverse();for(const n of r)yield this.uninstall(n,e)})}registerAll(e){if(!Array.isArray(e))throw new Error("plugins 必须是数组");return e.forEach(r=>this.register(r)),this}installAll(e,r){return E(this,null,function*(){if(!Array.isArray(e))throw new Error("names 必须是数组");for(const n of e)yield this.install(n,r)})}isRegistered(e){return this.plugins.has(e)}isInstalled(e){return this.installed.has(e)}getPlugin(e){return this.plugins.get(e)}getPluginList(){return Array.from(this.plugins.entries()).map(([e,r])=>({name:e,version:r.version,installed:this.installed.has(e),dependencies:r.dependencies||[]}))}getStats(){return{registered:this.plugins.size,installed:this.installed.size,plugins:this.getPluginList()}}clear(){this.plugins.clear(),this.installed.clear(),this.installOrder=[]}}const le=new Ft;class kt{constructor(){this.requestInterceptors=[],this.responseInterceptors=[],s.debug("拦截器链已初始化")}useRequest(e,r={}){if(typeof e!="function")throw new Error("拦截器必须是函数");const{priority:n=0}=r;return this.requestInterceptors.push({fn:e,priority:n}),this.requestInterceptors.sort((i,a)=>a.priority-i.priority),s.debug("请求拦截器已注册",{priority:n}),()=>{const i=this.requestInterceptors.findIndex(a=>a.fn===e);i>-1&&(this.requestInterceptors.splice(i,1),s.debug("请求拦截器已移除"))}}useResponse(e,r={}){if(typeof e!="function")throw new Error("拦截器必须是函数");const{priority:n=0}=r;return this.responseInterceptors.push({fn:e,priority:n}),this.responseInterceptors.sort((i,a)=>a.priority-i.priority),s.debug("响应拦截器已注册",{priority:n}),()=>{const i=this.responseInterceptors.findIndex(a=>a.fn===e);i>-1&&(this.responseInterceptors.splice(i,1),s.debug("响应拦截器已移除"))}}runRequest(e){return E(this,null,function*(){let r=g({},e);for(const{fn:n}of this.requestInterceptors){if(r.abort){s.debug("请求被中止",{apiName:r.apiName});break}try{const i=yield n(r);i&&(r=i)}catch(i){s.error("请求拦截器执行失败",i),r.abort=!0,r.error=i;break}}return r})}runResponse(e,r){return E(this,null,function*(){let n=e;for(const{fn:i}of this.responseInterceptors)try{const a=yield i(n,r);a!==void 0&&(n=a)}catch(a){s.error("响应拦截器执行失败",a)}return n})}clear(){this.requestInterceptors=[],this.responseInterceptors=[],s.debug("所有拦截器已清空")}getStats(){return{requestInterceptors:this.requestInterceptors.length,responseInterceptors:this.responseInterceptors.length}}}const H=new kt,zt={request:t=>(t.startTime=Date.now(),s.debug(`[API 调用] ${t.apiName}`,{params:t.params}),t),response:(t,e)=>{const r=Date.now()-e.startTime;return s.debug(`[API 完成] ${e.apiName}`,{duration:`${r}ms`,success:t==null?void 0:t.success}),t}},K={metrics:new Map,request:t=>(t.perfStartTime=performance.now(),t),response:(t,e)=>{const r=performance.now()-e.perfStartTime;K.metrics.has(e.apiName)||K.metrics.set(e.apiName,{count:0,totalTime:0,minTime:1/0,maxTime:0,avgTime:0});const n=K.metrics.get(e.apiName);return n.count++,n.totalTime+=r,n.minTime=Math.min(n.minTime,r),n.maxTime=Math.max(n.maxTime,r),n.avgTime=n.totalTime/n.count,t},getReport:()=>{const t={};return K.metrics.forEach((e,r)=>{t[r]=g({},e)}),t},clearMetrics:()=>{K.metrics.clear()}};function Kt(t={}){const{maxRetries:e=3,retryDelay:r=1e3,shouldRetry:n=i=>!i.success}=t;return{response:(i,a)=>E(null,null,function*(){return a.retryCount||(a.retryCount=0),n(i)&&a.retryCount<e&&(a.retryCount++,s.warn(`API 调用失败,第 ${a.retryCount} 次重试: ${a.apiName}`),yield new Promise(h=>setTimeout(h,r)),i.shouldRetry=!0,i.retryContext=a),i})}}function Gt(t={}){return{request:e=>{const r=t[e.apiName];if(r&&typeof r=="function"){const n=r(e.params);n&&(s.error(`参数验证失败: ${e.apiName}`,n),e.abort=!0,e.validationError=n)}return e}}}class Vt{constructor(){this.state={sdk:{status:"uninitialized",version:"2.0.5",error:null},platform:{type:c.type,isWeixinMiniProgram:c.isWeixinMiniProgram,isAppPlus:c.isAppPlus,isNvue:c.isNvue,isUvue:c.isUvue,features:{}},weixin:{configStatus:"pending",jsApiList:[],configError:null},network:{online:typeof navigator!="undefined"?navigator.onLine:!0,type:"unknown"},permissions:{camera:"prompt",location:"prompt",album:"prompt"},api:{}},this.listeners=new Map,this.wildcardListeners=new Set,this.initNetworkListener(),x.debug("状态仓库已初始化")}get(e){return e.split(".").reduce((n,i)=>n!=null?n[i]:void 0,this.state)}set(e,r){const n=e.split("."),i=n.pop(),a=n.reduce((f,d)=>((!f[d]||typeof f[d]!="object")&&(f[d]={}),f[d]),this.state),h=a[i];h!==r&&(a[i]=r,x.debug(`状态已更新: ${e}`,{oldValue:h,newValue:r}),this.notify(e,r,h))}batchUpdate(e){Object.entries(e).forEach(([r,n])=>{this.set(r,n)})}subscribe(e,r){if(typeof r!="function")throw new Error("listener 必须是函数");return e==="*"?(this.wildcardListeners.add(r),x.debug("添加通配符订阅者"),()=>{this.wildcardListeners.delete(r),x.debug("移除通配符订阅者")}):(this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),x.debug(`添加订阅者: ${e}`),()=>{const n=this.listeners.get(e);n&&(n.delete(r),n.size===0&&this.listeners.delete(e),x.debug(`移除订阅者: ${e}`))})}subscribeOnce(e,r){const n=this.subscribe(e,(i,a,h)=>{r(i,a,h),n()});return n}notify(e,r,n){const i=this.listeners.get(e);i&&i.forEach(h=>{try{h(r,n,e)}catch(f){x.error("订阅者执行失败",f)}});const a=e.split(".");for(let h=1;h<a.length;h++){const f=a.slice(0,h).join("."),d=this.listeners.get(f);if(d){const O=this.get(f);d.forEach(b=>{try{b(O,void 0,f)}catch(T){x.error("父路径订阅者执行失败",T)}})}}this.wildcardListeners.forEach(h=>{try{h(r,n,e)}catch(f){x.error("通配符订阅者执行失败",f)}})}initNetworkListener(){if(typeof window!="undefined"&&(window.addEventListener("online",()=>{this.set("network.online",!0)}),window.addEventListener("offline",()=>{this.set("network.online",!1)}),navigator.connection)){const e=navigator.connection,r=()=>{this.set("network.type",e.effectiveType||"unknown")};e.addEventListener("change",r),r()}}setApiLoading(e,r=!0){const n=`api.${e}`,i=this.get(n)||{};this.set(n,_(g({},i),{loading:r,lastCall:r?Date.now():i.lastCall}))}setApiResult(e,r){const n=`api.${e}`,i=this.get(n)||{};this.set(n,_(g({},i),{loading:!1,lastResult:r,lastCallEnd:Date.now()}))}getSnapshot(){return JSON.parse(JSON.stringify(this.state))}reset(){const{platform:e}=this.state;this.state={sdk:{status:"uninitialized",version:"2.0.5",error:null},platform:e,weixin:{configStatus:"pending",jsApiList:[],configError:null},network:{online:typeof navigator!="undefined"?navigator.onLine:!0,type:"unknown"},permissions:{camera:"prompt",location:"prompt",album:"prompt"},api:{}},x.debug("状态已重置")}getStats(){return{listeners:this.listeners.size,wildcardListeners:this.wildcardListeners.size,apiStates:Object.keys(this.state.api).length}}}const U=new Vt,o={SDK_NOT_READY:"E_SDK_001",SDK_INIT_FAILED:"E_SDK_002",SDK_CONFIG_FAILED:"E_SDK_003",PLATFORM_NOT_SUPPORTED:"E_SDK_004",NETWORK_ERROR:"E_NET_001",NETWORK_TIMEOUT:"E_NET_002",NETWORK_OFFLINE:"E_NET_003",IMAGE_CANCELLED:"E_IMG_001",IMAGE_NO_PERMISSION:"E_IMG_002",IMAGE_SIZE_EXCEED:"E_IMG_003",IMAGE_COUNT_EXCEED:"E_IMG_004",IMAGE_FORMAT_ERROR:"E_IMG_005",IMAGE_CONFIG_NOT_READY:"E_IMG_006",LOCATION_CANCELLED:"E_LOC_001",LOCATION_NO_PERMISSION:"E_LOC_002",LOCATION_UNAVAILABLE:"E_LOC_003",LOCATION_TIMEOUT:"E_LOC_004",SCAN_CANCELLED:"E_SCAN_001",SCAN_NO_PERMISSION:"E_SCAN_002",SCAN_INVALID_CODE:"E_SCAN_003",SCAN_CONFIG_NOT_READY:"E_SCAN_004",PERMISSION_DENIED:"E_PERM_001",PERMISSION_CAMERA:"E_PERM_002",PERMISSION_LOCATION:"E_PERM_003",PERMISSION_ALBUM:"E_PERM_004",PERMISSION_MICROPHONE:"E_PERM_005",PARAM_INVALID:"E_PARAM_001",PARAM_MISSING:"E_PARAM_002",PARAM_TYPE_ERROR:"E_PARAM_003",API_TIMEOUT:"E_TIMEOUT_001",UNKNOWN_ERROR:"E_UNKNOWN_999"},Ne={[o.SDK_NOT_READY]:"SDK 未就绪",[o.SDK_INIT_FAILED]:"SDK 初始化失败",[o.SDK_CONFIG_FAILED]:"SDK 配置失败",[o.PLATFORM_NOT_SUPPORTED]:"当前平台不支持此功能",[o.NETWORK_ERROR]:"网络错误",[o.NETWORK_TIMEOUT]:"网络超时",[o.NETWORK_OFFLINE]:"网络已断开",[o.IMAGE_CANCELLED]:"用户取消选择图片",[o.IMAGE_NO_PERMISSION]:"无相机/相册权限",[o.IMAGE_SIZE_EXCEED]:"图片大小超出限制",[o.IMAGE_COUNT_EXCEED]:"图片数量超出限制",[o.IMAGE_FORMAT_ERROR]:"图片格式不支持",[o.IMAGE_CONFIG_NOT_READY]:"微信配置未完成",[o.LOCATION_CANCELLED]:"用户取消定位",[o.LOCATION_NO_PERMISSION]:"无定位权限",[o.LOCATION_UNAVAILABLE]:"定位服务不可用",[o.LOCATION_TIMEOUT]:"定位超时",[o.SCAN_CANCELLED]:"用户取消扫码",[o.SCAN_NO_PERMISSION]:"无相机权限",[o.SCAN_INVALID_CODE]:"无效的二维码/条形码",[o.SCAN_CONFIG_NOT_READY]:"微信配置未完成",[o.PERMISSION_DENIED]:"权限被拒绝",[o.PERMISSION_CAMERA]:"无相机权限",[o.PERMISSION_LOCATION]:"无定位权限",[o.PERMISSION_ALBUM]:"无相册权限",[o.PERMISSION_MICROPHONE]:"无麦克风权限",[o.PARAM_INVALID]:"参数无效",[o.PARAM_MISSING]:"缺少必需参数",[o.PARAM_TYPE_ERROR]:"参数类型错误",[o.API_TIMEOUT]:"API 调用超时",[o.UNKNOWN_ERROR]:"未知错误"},D={USER_CANCEL:"user_cancel",PERMISSION:"permission",NETWORK:"network",PARAM:"param",SYSTEM:"system",CONFIG:"config",UNKNOWN:"unknown"},jt={"IMAGE/USER_CANCEL":o.IMAGE_CANCELLED,"IMAGE/PERMISSION_DENIED":o.IMAGE_NO_PERMISSION,"COMMON/UNKNOWN":o.UNKNOWN_ERROR,"COMMON/CONFIG_NOT_READY":o.IMAGE_CONFIG_NOT_READY,"COMMON/PLATFORM_NOT_SUPPORTED":o.PLATFORM_NOT_SUPPORTED},$e={weixin:{patterns:[{pattern:/cancel/i,code:o.IMAGE_CANCELLED},{pattern:/permission|auth\s*deny/i,code:o.IMAGE_NO_PERMISSION},{pattern:/config/i,code:o.IMAGE_CONFIG_NOT_READY},{pattern:/timeout/i,code:o.API_TIMEOUT},{pattern:/network/i,code:o.NETWORK_ERROR}],default:o.UNKNOWN_ERROR},uniapp:{patterns:[{pattern:/cancel/i,code:o.IMAGE_CANCELLED},{pattern:/permission|denied/i,code:o.IMAGE_NO_PERMISSION},{pattern:/timeout/i,code:o.API_TIMEOUT},{pattern:/network/i,code:o.NETWORK_ERROR},{pattern:/not_in_container/i,code:o.PLATFORM_NOT_SUPPORTED}],default:o.UNKNOWN_ERROR}},Be={chooseImage:{"fail cancel":o.IMAGE_CANCELLED,"fail auth deny":o.IMAGE_NO_PERMISSION,"fail No Permission":o.IMAGE_NO_PERMISSION,NOT_IN_CONTAINER:o.PLATFORM_NOT_SUPPORTED},scanCode:{"fail cancel":o.SCAN_CANCELLED,"fail auth deny":o.SCAN_NO_PERMISSION,"fail No Permission":o.SCAN_NO_PERMISSION,NOT_IN_CONTAINER:o.PLATFORM_NOT_SUPPORTED}};function Fe(t){return t?t.includes("CANCEL")?D.USER_CANCEL:t.includes("PERM")||t.includes("PERMISSION")?D.PERMISSION:t.includes("NET")||t.includes("NETWORK")?D.NETWORK:t.includes("PARAM")?D.PARAM:t.includes("CONFIG")?D.CONFIG:t.includes("SDK")||t.includes("PLATFORM")?D.SYSTEM:D.UNKNOWN:D.UNKNOWN}function qt(t){return t.includes("NET_")||t.includes("TIMEOUT")||t===o.NETWORK_ERROR||t===o.NETWORK_TIMEOUT||t===o.API_TIMEOUT}function Jt(t){return t.includes("CANCEL")||Fe(t)===D.USER_CANCEL}function ie(t){return Ne[t]||Ne[o.UNKNOWN_ERROR]}class W extends Error{constructor(e,r,n={}){super(r),this.name="StandardError",this.code=e,this.message=r||ie(e),this.platform=n.platform||c.type,this.apiName=n.apiName,this.category=n.category||Fe(e),this.retriable=n.retriable!==void 0?n.retriable:qt(e),this.originalError=n.originalError,this.details=n.details||{},this.timestamp=Date.now()}isRetriable(){return this.retriable}isUserAction(){return Jt(this.code)}toJSON(){return g({code:this.code,message:this.message,platform:this.platform,apiName:this.apiName,category:this.category,retriable:this.retriable,timestamp:this.timestamp,details:this.details},process.env.NODE_ENV!=="production"&&this.originalError?{originalError:this.originalError}:{})}}function ke(t,e={}){if(t instanceof W)return t;const{apiName:r,platform:n=c.type}=e;return t&&typeof t.code=="string"&&t.code.includes("/")?Ht(t,{apiName:r,platform:n}):t&&(t.errMsg||t.message)?Yt(t,{apiName:r,platform:n}):typeof t=="string"?new W(o.UNKNOWN_ERROR,t,{apiName:r,platform:n,originalError:t}):new W(o.UNKNOWN_ERROR,"未知错误",{apiName:r,platform:n,originalError:t,details:{errorType:typeof t}})}function Ht(t,e){const{apiName:r,platform:n}=e,i=t.code,a=jt[i]||o.UNKNOWN_ERROR;return s.debug("转换旧版错误码",{legacy:i,new:a}),new W(a,t.message||ie(a),{apiName:r,platform:t.platform||n,originalError:t,details:g({legacyCode:i,legacyVersion:t.version},t.details)})}function Yt(t,e){const{apiName:r,platform:n}=e,i=(t.errMsg||t.message||"").toLowerCase();if(r&&Be[r]){const f=Be[r];for(const[d,O]of Object.entries(f))if(i.includes(d.toLowerCase()))return new W(O,ie(O),{apiName:r,platform:n,originalError:t})}const a=$e[n]||$e.uniapp;for(const{pattern:f,code:d}of a.patterns)if(f.test(i))return new W(d,ie(d),{apiName:r,platform:n,originalError:t});const h=a.default||o.UNKNOWN_ERROR;return new W(h,t.errMsg||t.message||ie(h),{apiName:r,platform:n,originalError:t})}const ze={response:(t,e)=>{if(!t.success&&t.error){const r=ke(t.error,{apiName:e.apiName,platform:c.type});t.error=r.toJSON(),t.errorCode=r.code,t.errorCategory=r.category,t.retriable=r.isRetriable(),s.debug("错误已标准化",{api:e.apiName,code:r.code,category:r.category})}return t}};function Xt(t,e={}){return new W(t,ie(t),e)}function Zt(t){return t instanceof W}function Qt(t,e,r){return e?Promise.race([t(),new Promise((n,i)=>setTimeout(()=>i(new Error(`Init task timeout: ${r}`)),e))]):t()}function er(){return E(this,arguments,function*(t=[],e={}){for(const r of t){const n=(r==null?void 0:r.name)||"anonymous-task",i=(r==null?void 0:r.run)||r;if(typeof i=="function")try{yield Qt(()=>Promise.resolve().then(()=>i()),r.timeoutMs,n),typeof r.onSuccess=="function"&&r.onSuccess()}catch(a){if(typeof r.onError=="function"&&r.onError(a),typeof e.onError=="function")e.onError(a,r);else throw a}}})}class Ke{constructor(e){this.name=e}processNavigationOptions(e={}){const{url:r,delta:n=1}=e,i=r&&encodeURI(r),a=parseInt(n)||1;return _(g({},e),{url:i,delta:a})}processMessageOptions(e={}){const{data:r={}}=e;return{data:r}}navigateTo(e){const r=this.processNavigationOptions(e);return this.performNavigation("navigateTo",r)}navigateBack(e={}){const r=this.processNavigationOptions(e);return this.performNavigation("navigateBack",r)}switchTab(e){const r=this.processNavigationOptions(e);return this.performNavigation("switchTab",r)}reLaunch(e){const r=this.processNavigationOptions(e);return this.performNavigation("reLaunch",r)}redirectTo(e){const r=this.processNavigationOptions(e);return this.performNavigation("redirectTo",r)}postMessage(e={}){const r=this.processMessageOptions(e);return this.performPostMessage(r)}getEnv(e){return this.performGetEnv(e)}performNavigation(e,r){throw new Error(`${this.name} platform must implement performNavigation method`)}performPostMessage(e){throw new Error(`${this.name} platform must implement performPostMessage method`)}performGetEnv(e){throw new Error(`${this.name} platform must implement performGetEnv method`)}}let fe=[];function tr(){if(fe.length===0&&window.plus){const t=plus.webview.currentWebview();if(!t)throw new Error("plus.webview.currentWebview() is undefined");const e=t.parent(),r=e?e.id:t.id;fe.push(r)}return fe}function rr(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};if(t==="postMessage"){const i={data:e};return window.__uniapp_x_postMessage?window.__uniapp_x_postMessage(i):window.__uniapp_x_.postMessage(JSON.stringify(i))}const n={type:"WEB_INVOKE_APPSERVICE",args:{data:r,webviewIds:fe}};window.__uniapp_x_postMessage?window.__uniapp_x_postMessageToService(n):window.__uniapp_x_.postMessageToService(JSON.stringify(n))}function nr(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};if(t==="postMessage"){const i={data:[e]};return window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(i):window.__dcloud_weex_.postMessage(JSON.stringify(i))}const n={type:"WEB_INVOKE_APPSERVICE",args:{data:r,webviewIds:fe}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(n):window.__dcloud_weex_.postMessageToService(JSON.stringify(n))}function ir(t,e){const r={options:{timestamp:+new Date},name:t,arg:e},n=tr();if(plus.webview.getWebviewById("__uniapp__service"))plus.webview.postMessageToUniNView({type:"WEB_INVOKE_APPSERVICE",args:{data:r,webviewIds:n}},"__uniapp__service");else{const i=JSON.stringify(r),a=JSON.stringify(n);plus.webview.getLaunchWebview().evalJS(`UniPlusBridge.subscribeHandler("WEB_INVOKE_APPSERVICE",${i},${a});`)}}function sr(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:r,pageId:""},"*")}function de(t,e){te()?rr(t,e):j()?nr(t,e):ee()?ir(t,e):sr(t,e)}class Ge extends Ke{constructor(){super("weixin")}isWeixinApiAvailable(){return typeof window!="undefined"&&window.wx&&window.wx.miniProgram}performNavigation(e,r){return u.safeExecute(()=>{const{url:n,delta:i}=r;if(C.debug(`微信平台执行导航操作: ${e}`,r),this.isWeixinApiAvailable()){const h=window.wx.miniProgram[e];if(typeof h=="function"){C.debug(`使用微信原生 API: wx.miniProgram.${e}`);const f=e==="navigateBack"?{delta:i}:{url:n};return h.call(window.wx.miniProgram,f)}}C.debug(`使用消息桥接执行: ${e}`),de(e,e==="navigateBack"?{delta:i}:{url:n})},{platform:this.name,method:"performNavigation",navigationType:e,options:r})}performPostMessage(e){return u.safeExecute(()=>{const{data:r}=e;if(this.isWeixinApiAvailable())return window.wx.miniProgram.postMessage({data:r});de("postMessage",r)},{platform:this.name,method:"performPostMessage",options:e})}performGetEnv(e){return u.safeExecute(()=>{if(!e||typeof e!="function")throw new Error("Callback function is required for getEnv");if(this.isWeixinApiAvailable()&&window.wx.miniProgram.getEnv)return window.wx.miniProgram.getEnv(e);e({miniprogram:!0,weixin:!0})},{platform:this.name,method:"performGetEnv"})}}const Y=new Ge;var Ve=Object.freeze({__proto__:null,WeixinPlatform:Ge,getEnv:t=>Y.getEnv(t),navigateBack:t=>Y.navigateBack(t),navigateTo:t=>Y.navigateTo(t),postMessage:t=>Y.postMessage(t),reLaunch:t=>Y.reLaunch(t),redirectTo:t=>Y.redirectTo(t),switchTab:t=>Y.switchTab(t)});class je extends Ke{constructor(){super("app")}performNavigation(e,r){return u.safeExecute(()=>{const{url:n,delta:i}=r;de(e,e==="navigateBack"?{delta:i}:{url:n})},{platform:this.name,method:"performNavigation",navigationType:e,options:r})}performPostMessage(e){return u.safeExecute(()=>{const{data:r}=e;de("postMessage",r)},{platform:this.name,method:"performPostMessage",options:e})}performGetEnv(e){return u.safeExecute(()=>{if(!e||typeof e!="function")throw new Error("Callback function is required for getEnv");const r={};let n=!1;te()?(r.uvue=!0,n=!0):j()?(r.nvue=!0,n=!0):ee()&&(r.plus=!0,n=!0),n?r.app=!0:r.h5=!0,e(r)},{platform:this.name,method:"performGetEnv"})}}const X=new je;var qe=Object.freeze({__proto__:null,AppPlatform:je,getEnv:t=>X.getEnv(t),navigateBack:t=>X.navigateBack(t),navigateTo:t=>X.navigateTo(t),postMessage:t=>X.postMessage(t),reLaunch:t=>X.reLaunch(t),redirectTo:t=>X.redirectTo(t),switchTab:t=>X.switchTab(t)});function ge(){return p()?Ve:qe}function ar(t){return ge().navigateTo(t)}function or(t){return ge().navigateBack(t)}function cr(t){return ge().switchTab(t)}function ur(t){return ge().reLaunch(t)}function lr(t){return ge().redirectTo(t)}function Je(){return p()?Ve:qe}function fr(t={}){return Je().postMessage(t)}function dr(t){return Je().getEnv(t)}function gr(t){return t&&typeof t=="object"&&t.__v_raw?t.__v_raw:t}function pr(){return"qsh_callback_"+Date.now()+"_"+Math.random().toString(36).substring(2,9)}class hr{constructor(){this.callbacks=new Map,this.timeouts=new Map,this.persistentCallbacksByApi=new Map,this.defaultTimeout=3e4,typeof window!="undefined"&&(window.qshWebviewCallbacks||(window.qshWebviewCallbacks={})),y.debug("WebView 桥接器已初始化")}callApi(i){return E(this,arguments,function*(e,r={},n={}){return u.safeExecute(()=>E(this,null,function*(){var O;if(typeof window!="undefined"&&window===window.parent&&!window.plus&&!window.__uniapp_x_postMessage&&!window.__uniapp_x_&&!window.__dcloud_weex_postMessage&&!window.__dcloud_weex_){const b=new M(B.PLATFORM_NOT_SUPPORTED,"当前不在宿主 WebView 容器中,无法发送消息");n&&typeof n.fail=="function"&&n.fail({errMsg:b.message,code:"NOT_IN_CONTAINER"}),n&&typeof n.complete=="function"&&n.complete({success:!1,error:{errMsg:b.message}});return}const h={apiName:e,params:r,callbacks:n,timestamp:Date.now(),abort:!1,metadata:{}};U.setApiLoading(e,!0);const f=yield H.runRequest(h);if(f.abort){y.warn("API 调用被拦截器中止",{api:e}),U.setApiLoading(e,!1),n.fail&&n.fail({errMsg:((O=f.error)==null?void 0:O.message)||"API 调用被中止",code:"INTERCEPTED"}),n.complete&&n.complete({success:!1});return}const d=pr();if(n.success||n.fail||n.complete){if(this.callbacks.set(d,_(g({},n),{context:f})),window.qshWebviewCallbacks[d]=be=>{this.handleCallback(d,be)},r.isPersistent&&(this.persistentCallbacksByApi.has(e)||this.persistentCallbacksByApi.set(e,new Set),this.persistentCallbacksByApi.get(e).add(d)),r.isPersistent||r.disableTimeout)y.info(`API ${e} 禁用超时清理,将等待回调返回后清理`,{callbackId:d,isPersistent:r.isPersistent,disableTimeout:r.disableTimeout});else{const be=setTimeout(()=>{y.warn("API 调用超时,自动清理回调",{api:e,callbackId:d}),n.fail&&n.fail({errMsg:`API ${e} 调用超时`,code:"TIMEOUT"}),this.cleanupCallback(d)},r.timeout||this.defaultTimeout);this.timeouts.set(d,be)}const T={type:"qsh_api_call",api:e,params:f.params,callbackId:d,timestamp:Date.now()};y.info("发送 API 调用消息",{api:e,callbackId:d,hasSuccess:!!n.success,hasFail:!!n.fail}),console.log("message:",JSON.stringify(gr(T),null,2)),de("postMessage",T)}}),{context:"WebViewBridge.callApi",api:e})})}handleCallback(e,r){return E(this,null,function*(){return u.safeExecute(()=>E(this,null,function*(){var b,T;const n=this.callbacks.get(e);if(!n){y.warn("未找到回调函数",{callbackId:e});return}const{success:i,fail:a,complete:h,context:f}=n;y.debug("处理回调",{callbackId:e,result:r});const d=yield H.runResponse(r,f);f&&U.setApiResult(f.apiName,d),d.success&&i?i(d.data):!d.success&&a&&a(d.error||{errMsg:"操作失败"}),h&&h(d),((T=(b=n.context)==null?void 0:b.params)==null?void 0:T.isPersistent)?y.debug("持久监听API:保留回调",{callbackId:e}):(this.cleanupCallback(e),y.debug("回调执行完成,已清理",{callbackId:e}))}),{context:"WebViewBridge.handleCallback",callbackId:e})})}cleanupCallback(e){const r=this.timeouts.get(e);if(r&&(clearTimeout(r),this.timeouts.delete(e)),this.callbacks.delete(e),typeof window!="undefined"&&window.qshWebviewCallbacks&&delete window.qshWebviewCallbacks[e],this.persistentCallbacksByApi&&this.persistentCallbacksByApi.size>0){const n=[];this.persistentCallbacksByApi.forEach((i,a)=>{i.has(e)&&(i.delete(e),i.size===0&&n.push(a))}),n.forEach(i=>this.persistentCallbacksByApi.delete(i))}}clearCallbacks(){y.debug("清理所有回调",{count:this.callbacks.size}),this.timeouts.forEach(e=>clearTimeout(e)),this.timeouts.clear(),this.callbacks.clear(),this.persistentCallbacksByApi&&this.persistentCallbacksByApi.clear(),typeof window!="undefined"&&window.qshWebviewCallbacks&&Object.keys(window.qshWebviewCallbacks).forEach(e=>{e.startsWith("qsh_callback_")&&delete window.qshWebviewCallbacks[e]})}cleanupPersistentCallbacksByApi(e){const r=this.persistentCallbacksByApi.get(e);if(!r||r.size===0)return 0;const n=Array.from(r);return n.forEach(i=>this.cleanupCallback(i)),this.persistentCallbacksByApi.delete(e),y.info("已清理持久回调",{api:e,count:n.length}),n.length}getStatus(){return{isSupported:typeof window!="undefined"&&window.uni&&typeof window.uni.postMessage=="function",activeCallbacks:this.callbacks.size,globalCallbacksCount:typeof window!="undefined"&&window.qshWebviewCallbacks?Object.keys(window.qshWebviewCallbacks).length:0}}}const He=new hr,R=(t,e,r)=>He.callApi(t,e,r),se=t=>He.cleanupPersistentCallbacksByApi(t),we={ALBUM:"album",CAMERA:"camera"},Ee={ORIGINAL:"original",COMPRESSED:"compressed"},mr={count:9,sizeType:[Ee.ORIGINAL,Ee.COMPRESSED],sourceType:[we.ALBUM,we.CAMERA]};function wr(t={}){const e=g(g({},mr),t);return Array.isArray(e.sizeType)||(e.sizeType=[e.sizeType].filter(Boolean)),Array.isArray(e.sourceType)||(e.sourceType=[e.sourceType].filter(Boolean)),e.count=Math.max(1,Math.min(9,parseInt(e.count)||1)),e.sizeType.length===0&&(e.sizeType=[Ee.COMPRESSED]),e.sourceType.length===0&&(e.sourceType=[we.ALBUM]),e}function Ye(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(c.type)}function Xe(t){return u.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!z()){s.info("等待微信配置完成"),k().then(()=>Xe(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信图片选择",t),window.wx.chooseImage({count:t.count,sizeType:t.sizeType,sourceType:t.sourceType,success:r=>{var n,i;s.info("微信图片选择成功",{count:((n=r.localIds)==null?void 0:n.length)||0}),(i=t.success)==null||i.call(t,r)},fail:r=>{var n;s.error("微信图片选择失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"chooseImageInWeixin",platform:"weixin"})}function Er(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用图片选择",t),R("chooseImage",_(g({},t),{disableTimeout:!0}),{success:e=>{var r,n;s.info("UniApp 图片选择成功",{count:((r=e==null?void 0:e.tempFilePaths)==null?void 0:r.length)||0}),(n=t.success)==null||n.call(t,e)},fail:e=>{var r;s.error("UniApp 图片选择失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"chooseImageInUniApp",platform:"uniapp"})}function yr(t={}){return u.safeExecute(()=>{var r;if(!Ye()){const n={errMsg:`当前环境 (${c.type}) 不支持图片选择功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持图片选择",{platform:c.type}),(r=t.fail)==null||r.call(t,n);return}const e=wr(t);s.info("开始选择图片",{platform:c.type,count:e.count,sizeType:e.sizeType,sourceType:e.sourceType}),p()?Xe(e):Er(e)},{context:"chooseImage",options:t})}function Ir(){return{supported:Ye(),environment:c.type,implementation:p()?"weixin":"webview",features:{multipleSelection:!0,sizeTypeSelection:!0,sourceTypeSelection:!0,asyncSupport:!0}}}const Z={QR_CODE:"qrCode",BAR_CODE:"barCode",DATA_MATRIX:"datamatrix",PDF417:"pdf417"},Ar={onlyFromCamera:!0,scanType:[Z.QR_CODE,Z.BAR_CODE]};function Or(t={}){const e=g(g({},Ar),t);return Array.isArray(e.scanType)||(e.scanType=[e.scanType].filter(Boolean)),e.scanType.length===0&&(e.scanType=[Z.QR_CODE,Z.BAR_CODE]),e.onlyFromCamera=!!e.onlyFromCamera,e}function Ze(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(c.type)}function Qe(t){return u.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!z()){s.info("等待微信配置完成"),k().then(()=>Qe(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信扫码",t),window.wx.scanQRCode({needResult:1,scanType:t.scanType,success:r=>{var i;s.info("微信扫码成功",{result:r.resultStr});const n={result:r.resultStr,scanType:_r(r.resultStr),charSet:"utf-8",errMsg:"scanCode:ok"};(i=t.success)==null||i.call(t,n)},fail:r=>{var n;s.error("微信扫码失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"scanCodeInWeixin",platform:"weixin"})}function _r(t){return t?t.length>50||/[^\d]/.test(t)?Z.QR_CODE:Z.BAR_CODE:"unknown"}function Cr(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用扫码",t),R("scanCode",_(g({},t),{disableTimeout:!0}),{success:e=>{var r;s.info("UniApp 扫码成功",{result:e==null?void 0:e.result,scanType:e==null?void 0:e.scanType}),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 扫码失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"scanCodeInUniApp",platform:"uniapp"})}function Nr(t={}){return u.safeExecute(()=>{var r;if(!Ze()){const n={errMsg:`当前环境 (${c.type}) 不支持扫码功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持扫码",{platform:c.type}),(r=t.fail)==null||r.call(t,n);return}const e=Or(t);s.info("开始扫码",{platform:c.type,onlyFromCamera:e.onlyFromCamera,scanType:e.scanType}),p()?Qe(e):Cr(e)},{context:"scanCode",options:t})}function Rr(){return{supported:Ze(),environment:c.type,implementation:p()?"weixin":"webview",features:{onlyFromCamera:!0,scanTypeSelection:!0,multipleTypes:!0,asyncSupport:!0}}}const ae={WGS84:"wgs84",GCJ02:"gcj02",BD09:"bd09"},Sr={type:ae.WGS84,altitude:!1},Pr={scale:18};function Tr(t={}){const e=g(g({},Sr),t);return Object.values(ae).includes(e.type)||(e.type=ae.WGS84),e.altitude=!!e.altitude,e}function Lr(t={}){const e=g({},t);return Object.values(ae).includes(e.type)||(e.type=ae.WGS84),e.needFullAccuracy=!!e.needFullAccuracy,e}function Mr(t={}){const e=g(g({},Pr),t);if(e.latitude===void 0||e.latitude===null)throw{errMsg:"缺少必需参数:latitude(纬度)",code:"PARAM_MISSING"};if(typeof e.latitude!="number")throw{errMsg:`latitude 参数类型错误:期望 number,实际 ${typeof e.latitude}`,code:"PARAM_TYPE_ERROR",details:{param:"latitude",expected:"number",actual:typeof e.latitude,value:e.latitude}};if(e.latitude<-90||e.latitude>90)throw{errMsg:`latitude 超出范围:有效范围 -90 ~ 90,实际值 ${e.latitude}`,code:"PARAM_INVALID",details:{param:"latitude",value:e.latitude,validRange:"-90 ~ 90"}};if(e.longitude===void 0||e.longitude===null)throw{errMsg:"缺少必需参数:longitude(经度)",code:"PARAM_MISSING"};if(typeof e.longitude!="number")throw{errMsg:`longitude 参数类型错误:期望 number,实际 ${typeof e.longitude}`,code:"PARAM_TYPE_ERROR",details:{param:"longitude",expected:"number",actual:typeof e.longitude,value:e.longitude}};if(e.longitude<-180||e.longitude>180)throw{errMsg:`longitude 超出范围:有效范围 -180 ~ 180,实际值 ${e.longitude}`,code:"PARAM_INVALID",details:{param:"longitude",value:e.longitude,validRange:"-180 ~ 180"}};if(e.scale!==void 0&&e.scale!==null){const r=Number(e.scale);isNaN(r)?(s.warn("scale 参数无效,使用默认值 18",{scale:e.scale}),e.scale=18):e.scale=Math.max(1,Math.min(28,Math.floor(r)))}return e}function Re(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(c.type)}function et(t){return u.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!z()){s.info("等待微信配置完成"),k().then(()=>et(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信定位",t),window.wx.getLocation({type:t.type,success:r=>{var n;s.info("微信定位成功",{latitude:r.latitude,longitude:r.longitude}),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;s.error("微信定位失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"getLocationInWeixin",platform:"weixin"})}function tt(t){return u.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!z()){s.info("等待微信配置完成"),k().then(()=>tt(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信查看位置",t),window.wx.openLocation({latitude:t.latitude,longitude:t.longitude,name:t.name||"",address:t.address||"",scale:t.scale||18,infoUrl:t.infoUrl||"",success:r=>{var n;s.info("微信查看位置成功"),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;s.error("微信查看位置失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"openLocationInWeixin",platform:"weixin"})}function br(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用获取位置",t),R("getLocation",t,{success:e=>{var r;s.info("UniApp 获取位置成功",{latitude:e==null?void 0:e.latitude,longitude:e==null?void 0:e.longitude}),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 获取位置失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"getLocationInUniApp",platform:"uniapp"})}function vr(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用查看位置",t),R("openLocation",t,{success:e=>{var r;s.info("UniApp 查看位置成功"),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 查看位置失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"openLocationInUniApp",platform:"uniapp"})}function xr(t={}){return u.safeExecute(()=>{var r;if(!Re()){const n={errMsg:`当前环境 (${c.type}) 不支持定位功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持定位",{platform:c.type}),(r=t.fail)==null||r.call(t,n);return}const e=Tr(t);s.info("开始获取位置",{platform:c.type,type:e.type,altitude:e.altitude}),p()?et(e):br(e)},{context:"getLocation",options:t})}function Dr(t={}){return u.safeExecute(()=>{var r,n,i;if(!Re()){const a={errMsg:`当前环境 (${c.type}) 不支持查看位置功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持查看位置",{platform:c.type}),(r=t.fail)==null||r.call(t,a);return}let e;try{e=Mr(t)}catch(a){s.error("参数验证失败",a),(n=t.fail)==null||n.call(t,a),(i=t.complete)==null||i.call(t);return}s.info("开始查看位置",{platform:c.type,latitude:e.latitude,longitude:e.longitude,name:e.name}),p()?tt(e):vr(e)},{context:"openLocation",options:t})}function Ur(){const t=p();return{supported:Re(),environment:c.type,implementation:t?"weixin":"webview",features:{getLocation:!0,openLocation:!0,coordinateTypes:!0,altitudeSupport:!0,asyncSupport:!0,onLocationChange:!t}}}const G=new Set,V=new Set;function rt(t,e,r){t.forEach(n=>{if(typeof n=="function"){u.safeExecute(()=>n(e),{context:r});return}s.warn("监听回调不是函数,已跳过",{type:typeof n})})}function Wr(t={}){return u.safeExecute(()=>{var r,n;if(p()){const i={errMsg:`当前环境 (${c.type}) 不支持该接口`,code:"PLATFORM_NOT_SUPPORTED"};s.error("当前环境不支持此接口",{platform:c.type}),(r=t.fail)==null||r.call(t,i),(n=t.complete)==null||n.call(t,i);return}const e=Lr(t);s.info("正在开启定位监听"),R("startLocationUpdate",{type:e.type,needFullAccuracy:e.needFullAccuracy},{success:i=>{var a;s.info("定位监听已启动"),(a=t.success)==null||a.call(t,i)},fail:i=>{var a;return(a=t.fail)==null?void 0:a.call(t,i)},complete:t.complete})},{context:"startLocationUpdate"})}function $r(t={}){return u.safeExecute(()=>{var e,r;if(p()){const n={errMsg:`当前环境 (${c.type}) 不支持该接口`,code:"PLATFORM_NOT_SUPPORTED"};s.error("当前环境不支持此接口",{platform:c.type}),(e=t.fail)==null||e.call(t,n),(r=t.complete)==null||r.call(t,n);return}s.info("正在停止定位监听"),R("stopLocationUpdate",t,{success:n=>{var i;s.info("定位监听已停止"),(i=t.success)==null||i.call(t,n)},fail:n=>{var i;return(i=t.fail)==null?void 0:i.call(t,n)},complete:t.complete})},{context:"stopLocationUpdate"})}function Br(t){return u.safeExecute(()=>{if(p()){s.warn("当前环境不支持此接口",{platform:c.type});return}if(typeof t!="function")throw s.error("onLocationChange 回调不是函数",{type:typeof t}),{errMsg:"onLocationChange 回调必须是函数",code:"INVALID_CALLBACK"};const e=G.size>0;G.add(t),e||(s.debug("注册实时位置变化监听器"),R("onLocationChange",{isPersistent:!0},{success:r=>{s.debug("收到实时位置推送",r),rt(G,r,"onLocationChange")},fail:r=>{s.warn("位置变化监听出错,请通过 onLocationChangeError 监听错误",r),G.delete(t),G.size===0&&se("onLocationChange")}}))},{context:"onLocationChange"})}function Fr(t){return u.safeExecute(()=>{if(p()){s.warn("当前环境不支持此接口",{platform:c.type});return}if(t&&typeof t!="function")throw s.error("offLocationChange 回调不是函数",{type:typeof t}),{errMsg:"offLocationChange 回调必须是函数",code:"INVALID_CALLBACK"};t?G.delete(t):G.clear(),!(G.size>0)&&(s.info("移除位置变化监听器"),R("offLocationChange",{},{success:()=>{s.info("位置变化监听已移除"),se("onLocationChange")},fail:e=>{s.error("移除位置变化监听失败",e),se("onLocationChange")}}))},{context:"offLocationChange"})}function kr(t){return u.safeExecute(()=>{if(p()){s.warn("当前环境不支持此接口",{platform:c.type});return}if(typeof t!="function")throw s.error("onLocationChangeError 回调不是函数",{type:typeof t}),{errMsg:"onLocationChangeError 回调必须是函数",code:"INVALID_CALLBACK"};const e=V.size>0;V.add(t),e||(s.debug("注册位置更新错误监听器"),R("onLocationChangeError",{isPersistent:!0},{success:r=>{s.warn("持续定位发生异常",r),rt(V,r,"onLocationChangeError")},fail:r=>{s.warn("位置更新错误监听注册失败",r),V.delete(t),V.size===0&&se("onLocationChangeError")}}))},{context:"onLocationChangeError"})}function zr(t){return u.safeExecute(()=>{if(p()){s.warn("当前环境不支持此接口",{platform:c.type});return}if(t&&typeof t!="function")throw s.error("offLocationChangeError 回调不是函数",{type:typeof t}),{errMsg:"offLocationChangeError 回调必须是函数",code:"INVALID_CALLBACK"};t?V.delete(t):V.clear(),!(V.size>0)&&(s.info("移除定位错误监听器"),R("offLocationChangeError",{},{success:()=>{s.info("定位错误监听已移除"),se("onLocationChangeError")},fail:e=>{s.error("移除定位错误监听失败",e),se("onLocationChangeError")}}))},{context:"offLocationChangeError"})}const Kr={latitude:null,longitude:null};function Gr(t={}){const e=g(g({},Kr),t);return e.latitude!==null&&e.latitude!==void 0&&(typeof e.latitude!="number"?(s.warn("latitude 参数类型错误,已忽略",{latitude:e.latitude}),e.latitude=null):(e.latitude<-90||e.latitude>90)&&(s.warn("latitude 超出范围,已忽略",{latitude:e.latitude}),e.latitude=null)),e.longitude!==null&&e.longitude!==void 0&&(typeof e.longitude!="number"?(s.warn("longitude 参数类型错误,已忽略",{longitude:e.longitude}),e.longitude=null):(e.longitude<-180||e.longitude>180)&&(s.warn("longitude 超出范围,已忽略",{longitude:e.longitude}),e.longitude=null)),e}function nt(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(c.type)}function it(t){return u.safeExecute(()=>{var n;if(!window.wx){const i={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(n=t.fail)==null||n.call(t,i);return}if(!z()){s.info("等待微信配置完成"),k().then(()=>it(t)).catch(i=>{var a;s.error("微信配置失败",i),(a=t.fail)==null||a.call(t,{errMsg:`微信配置失败: ${i.message}`})});return}s.debug("调用微信位置选择",t);const e={success:i=>{var h;s.info("微信位置选择成功",{name:i.name,address:i.address,latitude:i.latitude,longitude:i.longitude});const a={name:i.name,address:i.address,latitude:i.latitude,longitude:i.longitude,errMsg:"chooseLocation:ok"};(h=t.success)==null||h.call(t,a)},fail:i=>{var a;s.error("微信位置选择失败",i),(a=t.fail)==null||a.call(t,i)},complete:t.complete},r={};t.latitude!==null&&t.latitude!==void 0&&(r.latitude=t.latitude),t.longitude!==null&&t.longitude!==void 0&&(r.longitude=t.longitude),window.wx.chooseLocation(_(g({},r),{success:e.success,fail:e.fail,complete:e.complete}))},{context:"chooseLocationInWeixin",platform:"weixin"})}function Vr(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用位置选择",t);const e={disableTimeout:!0,success:r=>{var n;s.info("UniApp 位置选择成功",{name:r==null?void 0:r.name,address:r==null?void 0:r.address,latitude:r==null?void 0:r.latitude,longitude:r==null?void 0:r.longitude}),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;s.error("UniApp 位置选择失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete};t.latitude!==null&&t.latitude!==void 0&&(e.latitude=t.latitude),t.longitude!==null&&t.longitude!==void 0&&(e.longitude=t.longitude),R("chooseLocation",e,{success:r=>{e.success(r)},fail:r=>{e.fail(r)},complete:e.complete})},{context:"chooseLocationInUniApp",platform:"uniapp"})}function jr(t={}){return u.safeExecute(()=>{var r;if(!nt()){const n={errMsg:`当前环境 (${c.type}) 不支持位置选择功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持位置选择",{platform:c.type}),(r=t.fail)==null||r.call(t,n);return}const e=Gr(t);s.info("开始选择位置",{platform:c.type,latitude:e.latitude,longitude:e.longitude}),p()?it(e):Vr(e)},{context:"chooseLocation",options:t})}function qr(){return{supported:nt(),environment:c.type,implementation:p()?"weixin":"webview",features:{chooseLocation:!0,centerPoint:!0,asyncSupport:!0}}}const st=new Map;function Jr(t,e={}){st.set(t,e)}function Hr(t,e){const r=st.get(t);if(r)return r[e]||r.default}const Yr={0:"WXSceneSession",1:"WXSceneTimeline"},Xr={0:"图文/网页",1:"纯文字",2:"纯图片",3:"音乐",4:"视频",5:"小程序"};function at(t={}){return u.safeExecute(()=>{var n,i;if(typeof window=="undefined"||!window.wx){const a={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};return(n=t.fail)==null||n.call(t,a),Promise.reject(a)}if(!z())return s.info("等待微信配置完成"),k().then(()=>at(t));const e=ot(t);if(!e.success){const a={errMsg:e.message||"参数校验失败",code:"INVALID_PARAMS"};return(i=t.fail)==null||i.call(t,a),Promise.reject(a)}const r=e.params;return s.debug("调用微信分享",r),new Promise((a,h)=>{window.wx[r.scene](_(g({},r),{success:()=>{var d;const f={errMsg:"weixinShare:ok"};(d=t.success)==null||d.call(t,f),a(f)},fail:f=>{var O;const d={errMsg:(f==null?void 0:f.errMsg)||"weixinShare:fail",details:f};s.error("微信分享失败",d),(O=t.fail)==null||O.call(t,d),h(d)},complete:t.complete}))})},{context:"toShareInWeixin",platform:"weixin"})}function ot(t={}){const e=g({},t),r={scene:e.scene===1?"updateTimelineShareData":"updateAppMessageShareData"};return s.info("格式化微信参数",e),Object.prototype.hasOwnProperty.call(e,"title")?Object.prototype.hasOwnProperty.call(e,"imageUrl")?Object.prototype.hasOwnProperty.call(e,"path")?Object.prototype.hasOwnProperty.call(e,"summary")?(r.title=e.title,r.imgUrl=e.imageUrl,r.link=e.path,r.desc=e.summary,{params:r,success:!0}):{message:"参数字段summary值缺少!",success:!1}:{message:"参数字段path值缺少!",success:!1}:{message:"参数字段imageUrl值缺少!",success:!1}:{message:"参数字段title值缺少!",success:!1}}function oe(t={}){return u.safeExecute(()=>(s.debug("通过 WebView 桥接调用微信分享",t),new Promise((e,r)=>{R("toShareData",t,{success:n=>{var i;(i=t.success)==null||i.call(t,n),e(n)},fail:n=>{var i;s.error("UniApp 微信分享失败",n),(i=t.fail)==null||i.call(t,n),r(n)},complete:t.complete})})),{context:"toShareInUniApp",platform:"uniapp"})}function Zr(t={}){const e=g({},t),r={provider:"weixin",scene:"WXSceneSession"};if(s.info("格式化 UniApp 参数",e),[0,1].some(n=>parseInt(n)===parseInt(e.scene))?r.scene=Yr[e.scene]:r.scene="WXSceneSession",Object.prototype.hasOwnProperty.call(e,"type")){const n=Number(e.type);if(Object.keys(Xr).some(a=>parseInt(a)===n)){if(r.type=n,[0].includes(n))if(Object.prototype.hasOwnProperty.call(e,"path"))r.href=e.path;else return{message:"参数字段path值缺少!",success:!1};if([0,1].includes(n))if(Object.prototype.hasOwnProperty.call(e,"summary"))r.summary=e.summary;else return{message:"参数字段summary值缺少!",success:!1};if([0,2,5].includes(n))if(Object.prototype.hasOwnProperty.call(e,"imageUrl"))r.imageUrl=e.imageUrl;else return{message:"参数字段imageUrl值缺少!",success:!1};[5].includes(n)&&Object.prototype.hasOwnProperty.call(e,"miniProgram")&&g({},e.miniProgram),Object.prototype.hasOwnProperty.call(e,"title")&&(r.title=e.title),Object.prototype.hasOwnProperty.call(e,"success")&&(r.success=e.success),Object.prototype.hasOwnProperty.call(e,"fail")&&(r.fail=e.fail),Object.prototype.hasOwnProperty.call(e,"complete")&&(r.complete=e.complete)}else return{message:"参数字段type值有误!",success:!1}}else return{message:"参数字段type缺少!",success:!1};return{params:r,success:!0}}const ct="share.toShare";Jr(ct,{weixin:at,webview:oe,plus:oe,nvue:oe,uvue:oe,UniApp:oe,h5:oe,default:void 0});function Qr(t={}){return u.safeExecute(()=>{var a,h;const e=Oe(),r=Hr(ct,e.type);if(typeof r!="function"){const f={errMsg:`当前环境 (${e.type}) 不支持微信分享功能`,code:"PLATFORM_NOT_SUPPORTED"};return s.error("平台不支持微信分享",{platform:e.type}),(a=t.fail)==null||a.call(t,f),Promise.reject(f)}const n=p()?ot(t):Zr(t);if(!n.success){const f={errMsg:n.message||"参数校验失败",code:"INVALID_PARAMS"};return(h=t.fail)==null||h.call(t,f),Promise.reject(f)}const i=n.params;return s.info("开始微信分享",{platform:e.type,type:i==null?void 0:i.type}),r(i)},{context:"toShare",options:t})}const en={OFF:"off",ON:"on",UNAVAILABLE:"unavailable",UNAUTHORIZED:"unauthorized"},tn={allowDuplicatesKey:!1,services:[]};function ye(t={}){return g(g({},tn),t)}function pe(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(c.type)}function rn(t){return u.safeExecute(()=>E(null,null,function*(){var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}z()||(s.info("等待微信配置完成"),yield k()),wx.openBluetoothAdapter({success:()=>{s.info("微信蓝牙适配器已打开"),ut(t)},fail:r=>{var n;s.error("蓝牙适配器打开失败",r),(n=t.fail)==null||n.call(t,r)}})}),{context:"openBluetoothAdapterInWeixin"})}function nn(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用蓝牙功能",t),R("bluetooth",t,{success:e=>{var r;s.info("UniApp 蓝牙调用成功",e),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 蓝牙调用失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"bluetoothInUniApp"})}function sn(t){return u.safeExecute(()=>{var e;s.debug("通过 WebView 桥接调用蓝牙设备搜索功能",t),R("bluetoothDevicesDiscovery",{action:"startBluetoothDevicesDiscovery",params:{services:t.services||[],allowDuplicatesKey:(e=t.allowDuplicatesKey)!=null?e:!1}},{success:r=>{var n;console.log("[Bluetooth] 设备开启搜索成功:",r),s.info("UniApp 蓝牙设备开启搜索成功",r),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;console.error("[Bluetooth] 设备开启搜索失败:",r),s.error("UniApp 蓝牙设备开启搜索失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"startBluetoothDevicesDiscoveryInUniApp"})}const Ie=new Set;function an(t,e={}){return u.safeExecute(()=>{var r;return Ie.add(t),Ie.size===1&&R("onBluetoothDeviceFound",{action:"onBluetoothDeviceFound",isPersistent:!0,params:{services:e.services||[],allowDuplicatesKey:(r=e.allowDuplicatesKey)!=null?r:!1}},{success:n=>{Ie.forEach(i=>{typeof i=="function"?u.safeExecute(()=>i(n),{context:"BluetoothDeviceCallback"}):console.warn("[BluetoothDeviceCallback] 不是函数:",i)})},fail:n=>{var i;console.error("[Bluetooth] 搜索失败:",n),(i=e.fail)==null||i.call(e,n)},complete:e.complete}),()=>Ie.delete(t)},{context:"qsh_onBluetoothDeviceFound"})}function on(t){return u.safeExecute(()=>{var e;s.debug("通过 WebView 桥接调用蓝牙连接功能",t),R("bluetoothConnection",{action:"createBLEConnection",params:{deviceId:t.deviceId,name:t.name,autoConnect:(e=t.autoConnect)!=null?e:!1}},{success:r=>{var n;console.log("[Bluetooth] 蓝牙连接成功:",r),s.info("UniApp 蓝牙连接成功",r),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;console.error("[Bluetooth] 蓝牙连接失败:",r),s.error("UniApp 蓝牙连接失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"createBLEConnectionInUniApp"})}function cn(t={}){return u.safeExecute(()=>{var r;if(!pe()){const n={errMsg:`当前环境 (${c.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙",{platform:c.type}),(r=t.fail)==null||r.call(t,n);return}const e=ye(t);s.info("开始蓝牙操作",{platform:c.type,services:e.services,allowDuplicatesKey:e.allowDuplicatesKey}),p()?rn(e):nn(e)},{context:"openBluetoothAdapter",options:t})}function un(t={}){return u.safeExecute(()=>{var r,n;if(!pe()){const i={errMsg:`当前环境 (${c.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙",{platform:c.type}),(r=t.fail)==null||r.call(t,i),(n=t.complete)==null||n.call(t,i);return}const e=ye(t);s.info("开始搜索蓝牙设备",{platform:c.type,services:e.services,allowDuplicatesKey:e.allowDuplicatesKey}),p()?startBluetoothDevicesDiscoveryInWeixin(e):sn(e)},{context:"startBluetoothDevicesDiscovery",options:t})}function ut(t,e={}){return u.safeExecute(()=>{var n,i;if(!pe()){const a={errMsg:`当前环境 (${c.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙",{platform:c.type}),(n=e.fail)==null||n.call(e,a),(i=e.complete)==null||i.call(e,a);return}const r=ye(e);s.info("注册蓝牙设备发现监听",{platform:c.type}),p()?onBluetoothDeviceFoundInWeixin(r):an(t,r)},{context:"onBluetoothDeviceFound",options:e})}function ln(t={}){return u.safeExecute(()=>{var a,h,f,d;if(!pe()){const O={errMsg:`当前环境 (${c.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙连接",{platform:c.type}),(a=t.fail)==null||a.call(t,O),(h=t.complete)==null||h.call(t,O);return}const e=ye(t),{name:r,deviceId:n,autoConnect:i=!1}=e;if(!n){const O={errMsg:"缺少 deviceId 参数",code:"INVALID_PARAMS"};(f=t.fail)==null||f.call(t,O),(d=t.complete)==null||d.call(t,O);return}s.info("创建蓝牙连接",{deviceId:n,autoConnect:i,platform:c.type}),p()?uni.createBLEConnection({deviceId:n,autoConnect:i,success:t.success,fail:t.fail,complete:t.complete}):on(e)},{context:"createBLEConnection",options:t})}function fn(){return{supported:pe(),environment:c.type,implementation:p()?"weixin":"webview",features:{discovery:!0,connect:!0,readWrite:!0,notify:!0,asyncSupport:!0}}}const dn={};function gn(t={}){return g(g({},dn),t)}function lt(){return["UniApp","plus","nvue","uvue"].includes(c.type)}function pn(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用打印PDF",t),R("printPdf",_(g({},t),{isPersistent:!0}),{success:e=>{var r;s.info("UniApp 打印PDF成功",e),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 打印PDF失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"printPdfInUniApp",platform:"uniapp"})}function hn(t={}){return u.safeExecute(()=>{var r;if(!lt()){const n={errMsg:`当前环境 (${c.type}) 不支持打印PDF功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持打印PDF",{platform:c.type}),(r=t.fail)==null||r.call(t,n);return}const e=gn(t);s.info("开始打印PDF",{platform:c.type}),pn(e)},{context:"printPdf",options:t})}function mn(){return{supported:lt(),environment:c.type,implementation:"uniapp",features:{asyncSupport:!0}}}const ft=Oe();H.useResponse(ze.response,{priority:1e3});let dt=!1;function gt(){if(dt)return;dt=!0,er([{name:"load-weixin-sdk",run:Wt,timeoutMs:8e3},{name:"init-bridge",run:Ue,timeoutMs:8e3}],{onError:(e,r)=>{console.error(`[QSH-SDK] 初始化失败(${(r==null?void 0:r.name)||"unknown"}):`,e)}})}typeof window!="undefined"&&(document.readyState==="complete"||document.readyState==="interactive"?setTimeout(gt,0):document.addEventListener("DOMContentLoaded",gt));function I(t,{apiName:e}={}){return function(r={},...n){const i=r&&typeof r=="object"&&(typeof r.success=="function"||typeof r.fail=="function"||typeof r.complete=="function"),a=r&&typeof r=="object"?r:{},h=()=>i?t(a,...n):new Promise((d,O)=>{const b=_(g({},a),{success:T=>{typeof a.success=="function"&&a.success(T),d(T)},fail:T=>{typeof a.fail=="function"&&a.fail(T),O(T)},complete:a.complete});t(b,...n)});return(typeof window=="undefined"?Promise.resolve():xe()).then(()=>h()).catch(d=>{throw console.error(`[QSH-SDK] ${e||"API"} call failed:`,d),d})}}function Ae(t){return typeof t=="function"?{success:t}:t&&typeof t=="object"?t:{}}const pt=I(ar),ht=I(or),mt=I(cr),wt=I(ur),Et=I(lr),yt=I(fr);function It(t){const e=()=>dr(t);return(typeof window=="undefined"?Promise.resolve():xe()).then(()=>e())}const Se=I(yr);function wn(t={}){return new Promise((e,r)=>{Se(_(g({},t),{success:e,fail:r}))})}const At=I(hn);function En(t={}){return new Promise((e,r)=>{At(_(g({},t),{success:e,fail:r}))})}const Pe=I(Nr);function yn(t={}){return new Promise((e,r)=>{Pe(_(g({},t),{success:e,fail:r}))})}const In=I(Qr),Te=I(xr);function An(t={}){return new Promise((e,r)=>{Te(_(g({},t),{success:e,fail:r}))})}const Le=I(Dr);function On(t={}){return new Promise((e,r)=>{Le(_(g({},t),{success:e,fail:r}))})}const Me=I(jr);function _n(t={}){return new Promise((e,r)=>{Me(_(g({},t),{success:e,fail:r}))})}const Ot=I(cn);function Cn(t={}){return new Promise((e,r)=>{Ot(_(g({},t),{success:e,fail:r}))})}const _t=I(un);function Nn(t={}){return new Promise((e,r)=>{_t(_(g({},t),{success:e,fail:r}))})}const Ct=I(ut);function Rn(t={}){return new Promise((e,r)=>{Ct(_(g({},t),{success:e,fail:r}))})}const Nt=I(ln);function Sn(t={}){return new Promise((e,r)=>{Nt(_(g({},t),{success:e,fail:r}))})}const Q={navigateTo:pt,navigateBack:ht,switchTab:mt,reLaunch:wt,redirectTo:Et,postMessage:yt,getEnv:It,chooseImage:Se,chooseImageAsync:wn,scanCode:Pe,scanCodeAsync:yn,getLocation:Te,getLocationAsync:An,openLocation:Le,openLocationAsync:On,chooseLocation:Me,chooseLocationAsync:_n,onLocationChange:t=>I((e={})=>Br(e.success),{apiName:"onLocationChange"})(Ae(t)),offLocationChange:t=>I((e={})=>Fr(e.success),{apiName:"offLocationChange"})(Ae(t)),onLocationChangeError:t=>I((e={})=>kr(e.success),{apiName:"onLocationChangeError"})(Ae(t)),offLocationChangeError:t=>I((e={})=>zr(e.success),{apiName:"offLocationChangeError"})(Ae(t)),startLocationUpdate:I(Wr,{apiName:"startLocationUpdate"}),stopLocationUpdate:I($r,{apiName:"stopLocationUpdate"}),environment:ft,ready:xt,init:Ue,isReady:Tt,getState:Lt,weixin:{waitForConfig:k,isConfigReady:z,getConfigState:$t,retryConfig:Bt},webView:null,ImageSourceTypes:we,ImageSizeTypes:Ee,getImageCapabilities:Ir,ScanTypes:Z,getScanCapabilities:Rr,CoordinateTypes:ae,getLocationCapabilities:Ur,getChooseLocationCapabilities:qr,openBluetoothAdapter:Ot,openBluetoothAdapterAsync:Cn,startBluetoothDevicesDiscovery:_t,startBluetoothDevicesDiscoveryAsync:Nn,onBluetoothDeviceFound:Ct,onBluetoothDeviceFoundAsync:Rn,createBLEConnection:Nt,createBLEConnectionAsync:Sn,BluetoothStates:en,toShare:In,getBluetoothCapabilities:fn,printPdf:At,printPdfAsync:En,getPrintCapabilities:mn,plugins:{manager:le,register:t=>le.register(t),install:t=>le.install(t,Q),list:()=>le.getPluginList()},interceptors:{chain:H,useRequest:(t,e)=>H.useRequest(t,e),useResponse:(t,e)=>H.useResponse(t,e),builtin:{logging:zt,performance:K,createRetry:Kt,createValidation:Gt,errorNormalizer:ze}},metrics:{getPerformanceReport:()=>K.getReport(),clearPerformanceMetrics:()=>K.clearMetrics()},errors:{codes:o,messages:Ne,categories:D,normalize:ke,create:Xt,isStandard:Zt},store:{instance:U,get:t=>U.get(t),set:(t,e)=>U.set(t,e),subscribe:(t,e)=>U.subscribe(t,e),getSnapshot:()=>U.getSnapshot()},debug:{logger:S,setLogReporter:t=>S.setReporter(t),errorHandler:u,stateManager:J,enableDevMode:()=>S.enableDevMode(),getLogs:t=>S.getHistory(t),getStats:()=>({logger:S.getStats(),state:J.getStats(),weixinConfig:We().getStats(),plugins:le.getStats(),interceptors:H.getStats(),store:U.getStats()}),getWeixinConfigManager:We,exportDebugInfo:()=>S.exportToJSON()}};ft.isWeixinMiniProgram?Q.webView=window.wx&&window.wx.miniProgram:Q.webView={navigateTo:pt,navigateBack:ht,switchTab:mt,reLaunch:wt,redirectTo:Et,postMessage:yt,getEnv:It,chooseImage:Se,scanCode:Pe,getLocation:Te,openLocation:Le,chooseLocation:Me};const Rt=typeof window.uni!="undefined"?window.uni:{};return Object.keys(Rt).forEach(t=>{Q.hasOwnProperty(t)||(Q[t]=Rt[t])}),typeof window!="undefined"&&(window.qsh=Q),Q});
|
|
2
2
|
//# sourceMappingURL=qsh-webview-sdk.umd.js.map
|