qlfy-ecological-login 1.2.3 → 1.2.4
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/lib/index.mjs +1 -1
- package/lib/index.mjs.gz +0 -0
- package/lib/index.umd.js +1 -1
- package/lib/index.umd.js.gz +0 -0
- package/package.json +1 -1
package/lib/index.mjs
CHANGED
|
@@ -2242,7 +2242,7 @@ const at = /* @__PURE__ */ ct({
|
|
|
2242
2242
|
i("loginFail", { message: "用户配置获取失败" }), u = !1;
|
|
2243
2243
|
return;
|
|
2244
2244
|
}
|
|
2245
|
-
if (n.showLog && console.log("【qlfyEcologicalLogin】用户配置获取成功"), !A.data.menus.length) {
|
|
2245
|
+
if (n.showLog && console.log("【qlfyEcologicalLogin】用户配置获取成功"), !A.data.data.menus.length) {
|
|
2246
2246
|
if (n.showLog && console.log("【qlfyEcologicalLogin】本账号无菜单访问权限"), await T(), n.forceMode) return _e();
|
|
2247
2247
|
i("loginFail", { message: "token无效失效" }), u = !1;
|
|
2248
2248
|
return;
|
package/lib/index.mjs.gz
CHANGED
|
Binary file
|
package/lib/index.umd.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){const n=new this(t);return r.forEach(o=>n.set(o)),n}static accessor(t){const n=(this[je]=this[je]={accessors:{}}).accessors,o=this.prototype;function s(i){const c=W(i);n[c]||(hn(o,i),n[c]=!0)}return a.isArray(t)?t.forEach(s):s(t),this}};C.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),a.reduceDescriptors(C.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}}),a.freezeMethods(C);function pe(e,t){const r=this||V,n=t||r,o=C.from(n.headers);let s=n.data;return a.forEach(e,function(c){s=c.call(r,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function He(e){return!!(e&&e.__CANCEL__)}function z(e,t,r){g.call(this,e??"canceled",g.ERR_CANCELED,t,r),this.name="CanceledError"}a.inherits(z,g,{__CANCEL__:!0});function ze(e,t,r){const n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new g("Request failed with status code "+r.status,[g.ERR_BAD_REQUEST,g.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function pn(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function mn(e,t){e=e||10;const r=new Array(e),n=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(f){const l=Date.now(),u=n[s];i||(i=l),r[o]=f,n[o]=l;let d=s,y=0;for(;d!==o;)y+=r[d++],d=d%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),l-i<t)return;const E=u&&l-u;return E?Math.round(y*1e3/E):void 0}}function gn(e,t){let r=0,n=1e3/t,o,s;const i=(l,u=Date.now())=>{r=u,o=null,s&&(clearTimeout(s),s=null),e.apply(null,l)};return[(...l)=>{const u=Date.now(),d=u-r;d>=n?i(l,u):(o=l,s||(s=setTimeout(()=>{s=null,i(o)},n-d)))},()=>o&&i(o)]}const ne=(e,t,r=3)=>{let n=0;const o=mn(50,250);return gn(s=>{const i=s.loaded,c=s.lengthComputable?s.total:void 0,f=i-n,l=o(f),u=i<=c;n=i;const d={loaded:i,total:c,progress:c?i/c:void 0,bytes:f,rate:l||void 0,estimated:l&&c&&u?(c-i)/l:void 0,event:s,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(d)},r)},ve=(e,t)=>{const r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},Je=e=>(...t)=>a.asap(()=>e(...t)),wn=L.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,L.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(L.origin),L.navigator&&/(msie|trident)/i.test(L.navigator.userAgent)):()=>!0,yn=L.hasStandardBrowserEnv?{write(e,t,r,n,o,s){const i=[e+"="+encodeURIComponent(t)];a.isNumber(r)&&i.push("expires="+new Date(r).toGMTString()),a.isString(n)&&i.push("path="+n),a.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function bn(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function En(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Ve(e,t,r){let n=!bn(t);return e&&(n||r==!1)?En(e,t):t}const We=e=>e instanceof C?{...e}:e;function I(e,t){t=t||{};const r={};function n(l,u,d,y){return a.isPlainObject(l)&&a.isPlainObject(u)?a.merge.call({caseless:y},l,u):a.isPlainObject(u)?a.merge({},u):a.isArray(u)?u.slice():u}function o(l,u,d,y){if(a.isUndefined(u)){if(!a.isUndefined(l))return n(void 0,l,d,y)}else return n(l,u,d,y)}function s(l,u){if(!a.isUndefined(u))return n(void 0,u)}function i(l,u){if(a.isUndefined(u)){if(!a.isUndefined(l))return n(void 0,l)}else return n(void 0,u)}function c(l,u,d){if(d in t)return n(l,u);if(d in e)return n(void 0,l)}const f={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:c,headers:(l,u,d)=>o(We(l),We(u),d,!0)};return a.forEach(Object.keys(Object.assign({},e,t)),function(u){const d=f[u]||o,y=d(e[u],t[u],u);a.isUndefined(y)&&d!==c||(r[u]=y)}),r}const Ke=e=>{const t=I({},e);let{data:r,withXSRFToken:n,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:c}=t;t.headers=i=C.from(i),t.url=Ue(Ve(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&i.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):"")));let f;if(a.isFormData(r)){if(L.hasStandardBrowserEnv||L.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if((f=i.getContentType())!==!1){const[l,...u]=f?f.split(";").map(d=>d.trim()).filter(Boolean):[];i.setContentType([l||"multipart/form-data",...u].join("; "))}}if(L.hasStandardBrowserEnv&&(n&&a.isFunction(n)&&(n=n(t)),n||n!==!1&&wn(t.url))){const l=o&&s&&yn.read(s);l&&i.set(o,l)}return t},Sn=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(r,n){const o=Ke(e);let s=o.data;const i=C.from(o.headers).normalize();let{responseType:c,onUploadProgress:f,onDownloadProgress:l}=o,u,d,y,E,h;function m(){E&&E(),h&&h(),o.cancelToken&&o.cancelToken.unsubscribe(u),o.signal&&o.signal.removeEventListener("abort",u)}let p=new XMLHttpRequest;p.open(o.method.toUpperCase(),o.url,!0),p.timeout=o.timeout;function S(){if(!p)return;const T=C.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),R={data:!c||c==="text"||c==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:T,config:e,request:p};ze(function(x){r(x),m()},function(x){n(x),m()},R),p=null}"onloadend"in p?p.onloadend=S:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(S)},p.onabort=function(){p&&(n(new g("Request aborted",g.ECONNABORTED,e,p)),p=null)},p.onerror=function(){n(new g("Network Error",g.ERR_NETWORK,e,p)),p=null},p.ontimeout=function(){let w=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const R=o.transitional||Me;o.timeoutErrorMessage&&(w=o.timeoutErrorMessage),n(new g(w,R.clarifyTimeoutError?g.ETIMEDOUT:g.ECONNABORTED,e,p)),p=null},s===void 0&&i.setContentType(null),"setRequestHeader"in p&&a.forEach(i.toJSON(),function(w,R){p.setRequestHeader(R,w)}),a.isUndefined(o.withCredentials)||(p.withCredentials=!!o.withCredentials),c&&c!=="json"&&(p.responseType=o.responseType),l&&([y,h]=ne(l,!0),p.addEventListener("progress",y)),f&&p.upload&&([d,E]=ne(f),p.upload.addEventListener("progress",d),p.upload.addEventListener("loadend",E)),(o.cancelToken||o.signal)&&(u=T=>{p&&(n(!T||T.type?new z(null,e,p):T),p.abort(),p=null)},o.cancelToken&&o.cancelToken.subscribe(u),o.signal&&(o.signal.aborted?u():o.signal.addEventListener("abort",u)));const O=pn(o.url);if(O&&L.protocols.indexOf(O)===-1){n(new g("Unsupported protocol "+O+":",g.ERR_BAD_REQUEST,e));return}p.send(s||null)})},Rn=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let n=new AbortController,o;const s=function(l){if(!o){o=!0,c();const u=l instanceof Error?l:this.reason;n.abort(u instanceof g?u:new z(u instanceof Error?u.message:u))}};let i=t&&setTimeout(()=>{i=null,s(new g(`timeout ${t} of ms exceeded`,g.ETIMEDOUT))},t);const c=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(l=>{l.unsubscribe?l.unsubscribe(s):l.removeEventListener("abort",s)}),e=null)};e.forEach(l=>l.addEventListener("abort",s));const{signal:f}=n;return f.unsubscribe=()=>a.asap(c),f}},Tn=function*(e,t){let r=e.byteLength;if(r<t){yield e;return}let n=0,o;for(;n<r;)o=n+t,yield e.slice(n,o),n=o},On=async function*(e,t){for await(const r of An(e))yield*Tn(r,t)},An=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:r,value:n}=await t.read();if(r)break;yield n}}finally{await t.cancel()}},Xe=(e,t,r,n)=>{const o=On(e,t);let s=0,i,c=f=>{i||(i=!0,n&&n(f))};return new ReadableStream({async pull(f){try{const{done:l,value:u}=await o.next();if(l){c(),f.close();return}let d=u.byteLength;if(r){let y=s+=d;r(y)}f.enqueue(new Uint8Array(u))}catch(l){throw c(l),l}},cancel(f){return c(f),o.return()}},{highWaterMark:2})},re=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Ge=re&&typeof ReadableStream=="function",xn=re&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Qe=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Ln=Ge&&Qe(()=>{let e=!1;const t=new Request(L.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),Ze=64*1024,me=Ge&&Qe(()=>a.isReadableStream(new Response("").body)),oe={stream:me&&(e=>e.body)};re&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!oe[t]&&(oe[t]=a.isFunction(e[t])?r=>r[t]():(r,n)=>{throw new g(`Response type '${t}' is not supported`,g.ERR_NOT_SUPPORT,n)})})})(new Response);const Pn=async e=>{if(e==null)return 0;if(a.isBlob(e))return e.size;if(a.isSpecCompliantForm(e))return(await new Request(L.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(a.isArrayBufferView(e)||a.isArrayBuffer(e))return e.byteLength;if(a.isURLSearchParams(e)&&(e=e+""),a.isString(e))return(await xn(e)).byteLength},kn=async(e,t)=>{const r=a.toFiniteNumber(e.getContentLength());return r??Pn(t)},ge={http:Xt,xhr:Sn,fetch:re&&(async e=>{let{url:t,method:r,data:n,signal:o,cancelToken:s,timeout:i,onDownloadProgress:c,onUploadProgress:f,responseType:l,headers:u,withCredentials:d="same-origin",fetchOptions:y}=Ke(e);l=l?(l+"").toLowerCase():"text";let E=Rn([o,s&&s.toAbortSignal()],i),h;const m=E&&E.unsubscribe&&(()=>{E.unsubscribe()});let p;try{if(f&&Ln&&r!=="get"&&r!=="head"&&(p=await kn(u,n))!==0){let R=new Request(t,{method:"POST",body:n,duplex:"half"}),A;if(a.isFormData(n)&&(A=R.headers.get("content-type"))&&u.setContentType(A),R.body){const[x,q]=ve(p,ne(Je(f)));n=Xe(R.body,Ze,x,q)}}a.isString(d)||(d=d?"include":"omit");const S="credentials"in Request.prototype;h=new Request(t,{...y,signal:E,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:S?d:void 0});let O=await fetch(h,y);const T=me&&(l==="stream"||l==="response");if(me&&(c||T&&m)){const R={};["status","statusText","headers"].forEach(lt=>{R[lt]=O[lt]});const A=a.toFiniteNumber(O.headers.get("content-length")),[x,q]=c&&ve(A,ne(Je(c),!0))||[];O=new Response(Xe(O.body,Ze,x,()=>{q&&q(),m&&m()}),R)}l=l||"text";let w=await oe[a.findKey(oe,l)||"text"](O,e);return!T&&m&&m(),await new Promise((R,A)=>{ze(R,A,{data:w,headers:C.from(O.headers),status:O.status,statusText:O.statusText,config:e,request:h})})}catch(S){throw m&&m(),S&&S.name==="TypeError"&&/Load failed|fetch/i.test(S.message)?Object.assign(new g("Network Error",g.ERR_NETWORK,e,h),{cause:S.cause||S}):g.from(S,S&&S.code,e,h)}})};a.forEach(ge,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Ye=e=>`- ${e}`,Cn=e=>a.isFunction(e)||e===null||e===!1,et={getAdapter:e=>{e=a.isArray(e)?e:[e];const{length:t}=e;let r,n;const o={};for(let s=0;s<t;s++){r=e[s];let i;if(n=r,!Cn(r)&&(n=ge[(i=String(r)).toLowerCase()],n===void 0))throw new g(`Unknown adapter '${i}'`);if(n)break;o[i||"#"+s]=n}if(!n){const s=Object.entries(o).map(([c,f])=>`adapter ${c} `+(f===!1?"is not supported by the environment":"is not available in the build"));let i=t?s.length>1?`since :
|
|
4
4
|
`+s.map(Ye).join(`
|
|
5
5
|
`):" "+Ye(s[0]):"as no adapter specified";throw new g("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return n},adapters:ge};function we(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new z(null,e)}function tt(e){return we(e),e.headers=C.from(e.headers),e.data=pe.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),et.getAdapter(e.adapter||V.adapter)(e).then(function(n){return we(e),n.data=pe.call(e,e.transformResponse,n),n.headers=C.from(n.headers),n},function(n){return He(n)||(we(e),n&&n.response&&(n.response.data=pe.call(e,e.transformResponse,n.response),n.response.headers=C.from(n.response.headers))),Promise.reject(n)})}const nt="1.10.0",se={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{se[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const rt={};se.transitional=function(t,r,n){function o(s,i){return"[Axios v"+nt+"] Transitional option '"+s+"'"+i+(n?". "+n:"")}return(s,i,c)=>{if(t===!1)throw new g(o(i," has been removed"+(r?" in "+r:"")),g.ERR_DEPRECATED);return r&&!rt[i]&&(rt[i]=!0,console.warn(o(i," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(s,i,c):!0}},se.spelling=function(t){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${t}`),!0)};function Dn(e,t,r){if(typeof e!="object")throw new g("options must be an object",g.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let o=n.length;for(;o-- >0;){const s=n[o],i=t[s];if(i){const c=e[s],f=c===void 0||i(c,s,e);if(f!==!0)throw new g("option "+s+" must be "+f,g.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new g("Unknown option "+s,g.ERR_BAD_OPTION)}}const ie={assertOptions:Dn,validators:se},N=ie.validators;let M=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Ie,response:new Ie}}async request(t,r){try{return await this._request(t,r)}catch(n){if(n instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{n.stack?s&&!String(n.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(n.stack+=`
|
|
6
|
-
`+s):n.stack=s}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=I(this.defaults,r);const{transitional:n,paramsSerializer:o,headers:s}=r;n!==void 0&&ie.assertOptions(n,{silentJSONParsing:N.transitional(N.boolean),forcedJSONParsing:N.transitional(N.boolean),clarifyTimeoutError:N.transitional(N.boolean)},!1),o!=null&&(a.isFunction(o)?r.paramsSerializer={serialize:o}:ie.assertOptions(o,{encode:N.function,serialize:N.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),ie.assertOptions(r,{baseUrl:N.spelling("baseURL"),withXsrfToken:N.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let i=s&&a.merge(s.common,s[r.method]);s&&a.forEach(["delete","get","head","post","put","patch","common"],h=>{delete s[h]}),r.headers=C.concat(i,s);const c=[];let f=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(r)===!1||(f=f&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const l=[];this.interceptors.response.forEach(function(m){l.push(m.fulfilled,m.rejected)});let u,d=0,y;if(!f){const h=[tt.bind(this),void 0];for(h.unshift.apply(h,c),h.push.apply(h,l),y=h.length,u=Promise.resolve(r);d<y;)u=u.then(h[d++],h[d++]);return u}y=c.length;let E=r;for(d=0;d<y;){const h=c[d++],m=c[d++];try{E=h(E)}catch(p){m.call(this,p);break}}try{u=tt.call(this,E)}catch(h){return Promise.reject(h)}for(d=0,y=l.length;d<y;)u=u.then(l[d++],l[d++]);return u}getUri(t){t=I(this.defaults,t);const r=Ve(t.baseURL,t.url,t.allowAbsoluteUrls);return Ue(r,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){M.prototype[t]=function(r,n){return this.request(I(n||{},{method:t,url:r,data:(n||{}).data}))}}),a.forEach(["post","put","patch"],function(t){function r(n){return function(s,i,c){return this.request(I(c||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}M.prototype[t]=r(),M.prototype[t+"Form"]=r(!0)});let Nn=class ut{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(s){r=s});const n=this;this.promise.then(o=>{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](o);n._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(c=>{n.subscribe(c),s=c}).then(o);return i.cancel=function(){n.unsubscribe(s)},i},t(function(s,i,c){n.reason||(n.reason=new z(s,i,c),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new ut(function(o){t=o}),cancel:t}}};function Bn(e){return function(r){return e.apply(null,r)}}function _n(e){return a.isObject(e)&&e.isAxiosError===!0}const ye={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ye).forEach(([e,t])=>{ye[t]=e});function ot(e){const t=new M(e),r=Re(M.prototype.request,t);return a.extend(r,M.prototype,t,{allOwnKeys:!0}),a.extend(r,t,null,{allOwnKeys:!0}),r.create=function(o){return ot(I(e,o))},r}const b=ot(V);b.Axios=M,b.CanceledError=z,b.CancelToken=Nn,b.isCancel=He,b.VERSION=nt,b.toFormData=ee,b.AxiosError=g,b.Cancel=b.CanceledError,b.all=function(t){return Promise.all(t)},b.spread=Bn,b.isAxiosError=_n,b.mergeConfig=I,b.AxiosHeaders=C,b.formToJSON=e=>$e(a.isHTMLForm(e)?new FormData(e):e),b.getAdapter=et.getAdapter,b.HttpStatusCode=ye,b.default=b;const{Axios:tr,AxiosError:nr,CanceledError:rr,isCancel:or,CancelToken:sr,VERSION:ir,all:ar,Cancel:cr,isAxiosError:lr,spread:ur,toFormData:fr,AxiosHeaders:dr,HttpStatusCode:hr,formToJSON:pr,getAdapter:mr,mergeConfig:gr}=b;class Fn{constructor(t,r,n=1){this.db=null,this.dbName=t,this.storeName=r,this.version=n}open(){return new Promise((t,r)=>{if(this.db){t(this.db);return}const n=indexedDB.open(this.dbName,this.version);n.onupgradeneeded=o=>{const s=o.target.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"})},n.onsuccess=o=>{this.db=o.target.result,t(this.db)},n.onerror=o=>{console.error("IndexedDB 打开失败:",o.target.error),r(o.target.error)},n.onblocked=()=>{console.warn("数据库操作被阻塞,请关闭其他连接"),r(new Error("数据库操作被阻塞"))}})}close(){this.db&&(this.db.close(),this.db=null)}put(t){return new Promise((r,n)=>{if(!this.db){n(new Error("数据库未打开,请先调用 open() 方法"));return}const o=this.db.transaction(this.storeName,"readwrite"),i=o.objectStore(this.storeName).put(t);i.onsuccess=()=>{r(t)},i.onerror=()=>{console.error("数据存储失败:",i.error),n(i.error)},o.onerror=()=>{console.error("事务错误:",o.error),n(o.error)}})}update(t){return new Promise(async(r,n)=>{try{if(!await this.get(t.id)){n(new Error(`ID为 ${t.id} 的数据不存在,无法更新`));return}const s=await this.put(t);r(s)}catch(o){console.error("数据更新失败:",o),n(o)}})}partialUpdate(t,r){return new Promise(async(n,o)=>{try{const s=await this.get(t);if(!s){o(new Error(`ID为 ${t} 的数据不存在,无法更新`));return}const i={...s,...r,id:t},c=await this.put(i);n(c)}catch(s){console.error("数据部分更新失败:",s),o(s)}})}get(t){return new Promise((r,n)=>{if(!this.db){n(new Error("数据库未打开,请先调用 open() 方法"));return}const i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(t);i.onsuccess=()=>{r(i.result)},i.onerror=()=>{console.error("数据读取失败:",i.error),n(i.error)}})}delete(t){return new Promise((r,n)=>{if(!this.db){n(new Error("数据库未打开,请先调用 open() 方法"));return}const i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(t);i.onsuccess=()=>{r()},i.onerror=()=>{console.error("数据删除失败:",i.error),n(i.error)}})}getAll(){return new Promise((t,r)=>{if(!this.db){r(new Error("数据库未打开,请先调用 open() 方法"));return}const s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{console.error("获取所有数据失败:",s.error),r(s.error)}})}clear(){return new Promise((t,r)=>{if(!this.db){r(new Error("数据库未打开,请先调用 open() 方法"));return}const s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{console.error("清空存储失败:",s.error),r(s.error)}})}}class qn{constructor(){}set(t,r,n){let o=null;if(typeof n=="number"&&n>0)o=Date.now()+n*1e3;else if(typeof n>"u"){const i=this.getRaw(t);o=i?i.expire:null}const s={value:r,expire:o};localStorage.setItem(t,JSON.stringify(s))}get(t){const r=this.getRaw(t);return r?r.expire&&Date.now()>r.expire?(this.remove(t),null):r.value:null}getRaw(t){try{const r=localStorage.getItem(t);if(!r)return null;const n=JSON.parse(r);return n&&typeof n=="object"&&"value"in n&&"expire"in n?n:{value:r,expire:null}}catch{return{value:localStorage.getItem(t),expire:null}}}remove(t){localStorage.removeItem(t)}clear(){localStorage.clear()}}function Un(){return typeof window<"u"&&"indexedDB"in window&&indexedDB!==null&&indexedDB!==void 0}class In{constructor(){this.isInitialized=!1,this.indexedDBManager=new Fn("qlfyEcologicalLogin","loginData")}async ensureInitialized(){this.isInitialized||(await this.indexedDBManager.open(),this.isInitialized=!0)}async set(t,r){await this.ensureInitialized(),await this.indexedDBManager.put({id:t,data:r})}async get(t){await this.ensureInitialized();const r=await this.indexedDBManager.get(t);return r?r.data:null}async remove(t){await this.ensureInitialized(),await this.indexedDBManager.delete(t)}}class Mn{constructor(){this.localStorageManager=new qn}set(t,r){this.localStorageManager.set(t,r)}get(t){return this.localStorageManager.get(t)}remove(t){this.localStorageManager.remove(t)}}function $n(){return Un()?new In:new Mn}let $="qlfyEcologicalLogin_";const be=$n();async function j(e){$.indexOf(e.props.clientId)==-1&&($+=e.props.clientId);const t=be.set($,e);t instanceof Promise&&await t}async function Ee(){const e=be.remove($);e instanceof Promise&&await e}async function _(e){e&&$.indexOf(e)==-1&&($+=e);const t=be.get($),r=t instanceof Promise?await t:t;return r||{props:null,loginInfo:null,routerMode:vn(),isOutLogin:!1,token:"",refreshToken:"",tenant_id:168,userPermission:{}}}async function Se(e=!0,t,r){let n=await _();const o=n.props;if(o.openDebugger)debugger;if(!o||!o.isEnabled){console.error(new Error("统一登陆未开启,请检查配置"));return}const s=n.token;if(!s){console.error(new Error("未登陆或token失效"));return}b({method:"post",url:o.loginServiceBaseAddress+"/admin-api/system/auth/logout",headers:{"tenant-id":n.loginInfo.tenant_id,Authorization:"Bearer "+s}}).then(async i=>{i.data.code?r&&r(i):(e&&await F(),t&&t(i),await Ee(),await j(n))}).catch(i=>{console.log(i),r&&r(i)})}async function F(){const t=(await _()).props;if(!t||!t.isEnabled){console.error(new Error("统一登陆未开启,请检查配置"));return}const r=await zn();r&&setTimeout(()=>{window.open(r,"_self")}),await Ee()}async function st(){const e=await _(),t=e.props;return!t||!t.isEnabled?(console.error(new Error("统一登陆未开启,请检查配置")),""):e.token}async function it(){const e=await _(),t=e.props;return!t||!t.isEnabled?(console.error(new Error("统一登陆未开启,请检查配置")),null):e.loginInfo}async function jn(){let e=await _();const t=e.props;return!t||!t.isEnabled?(console.error(new Error("统一登陆未开启,请检查配置")),null):e.userPermission}async function Hn(){let e=await _();const t=e.props;return!t||!t.isEnabled?(console.error(new Error("统一登陆未开启,请检查配置")),null):e.refreshToken}async function zn(){const t=(await _()).props;if(!t||!t.isEnabled)return console.error(new Error("统一登陆未开启,请检查配置")),null;if(!t.clientId||!t.clientSecret)return console.error("未配置应用id或应用密钥!"),"";if(!t.loginPageBaseAddress)return console.error("未配置登录页基础地址!"),"";let r=await at(["token","refreshToken"],!1),n=t.redirectUrl||encodeURIComponent(r);return`${t.loginPageBaseAddress}/#/login?clientId=${t.clientId}&clientSecret=${t.clientSecret}&redirectUrl=${n}`}function vn(){if(window.location.href.includes("#")){const t=window.location.href.indexOf("#"),r=window.location.href.substring(t+1);if(r.startsWith("/")||r.includes("?"))return"hash"}return"history"}async function at(e,t=!1,r=window.location.href,n){if(n||(n=(await _()).routerMode),!["hash","history"].includes(n))throw new Error('路由模式必须是 "hash" 或 "history"');let o,s,i;if(n==="hash"){const c=r.indexOf("#");if(c===-1)return r;s=r.substring(0,c+1);const l=r.substring(c+1).split("?"),u=l[0],d=l[1]||"";i=new URLSearchParams(d),e.forEach(h=>{i.delete(h)});const y=i.toString(),E=y?`${u}?${y}`:u;o=`${s}${E}`}else{o=new URL(r),e.forEach(f=>{o.searchParams.delete(f)});const c=o.searchParams.toString();o=c?`${o.href}?${c}`:o.href}return t&&history.replaceState({},"",o),o}function K(e){if(e===null)return null;if(typeof e!="object")return e;if(e instanceof Date)return new Date(e);if(e instanceof RegExp)return new RegExp(e);let t=new e.constructor;for(let r in e)e.hasOwnProperty(r)&&(t[r]=K(e[r]));return t}function Jn(e){if(!e)throw new Error("请传入有效的Vue Router实例");return(()=>{var n,o,s,i;if((n=e.options)!=null&&n.history){const c=e.options.history;if((c==null?void 0:c.type)==="hash"||((o=c==null?void 0:c.constructor)==null?void 0:o.name)==="HashHistory")return"hash"}if(typeof e.mode=="string")return e.mode;const r=e.history;if(r){const c=(s=r.constructor)==null?void 0:s.name;if(c!=null&&c.includes("Hash")||c!=null&&c.includes("hash"))return"hash"}return typeof window<"u"&&((i=window.location)!=null&&i.hash)&&window.location.hash!=="#"?"hash":""})().toLowerCase()==="hash"}const ct=B.defineComponent({__name:"index",props:{clientId:{},clientSecret:{},loginPageBaseAddress:{},loginServiceBaseAddress:{},useRouter:{},forceMode:{type:Boolean,default:!0},clientName:{},token:{},isEnabled:{type:Boolean,default:!0},redirectPath:{default:""},tenantId:{default:168},showLog:{type:Boolean,default:!1},openDebugger:{type:Boolean,default:!1}},emits:["loggingIn","loginSuccess","loginFail","tokenRefresh"],setup(e,{expose:t,emit:r}){const n=e,o=n.useRouter,s=n.useRouter.currentRoute,i=r;let c=!0,f=null,l=null,u=!1,d=null;t({logout:async()=>await Se(),getToken:async()=>await st(),getLoginInfo:async()=>await it(),goLogin:async()=>await F()}),o.beforeEach(async(w,R,A)=>{n.forceMode&&!u?(n.showLog&&console.log("【qlfyEcologicalLogin】【路由拦截中】等待登陆放行..."),d=K(w.query),(u||await S())&&(n.showLog&&console.log("【qlfyEcologicalLogin】【路由拦截中】登陆成功路由放行"),d=null,delete w.query.token,delete w.query.refreshToken,A(w))):A()}),B.onBeforeUnmount(()=>{}),B.watch(()=>s.value.path,(w,R)=>{f&&clearTimeout(f),B.nextTick(()=>{f=setTimeout(()=>{n.isEnabled&&y()},300)})},{deep:!0,immediate:!0}),B.watch(()=>n.isEnabled,w=>{setTimeout(async()=>{w&&y(),w||(await Ee(),f&&clearTimeout(f))})},{deep:!0});async function y(){if(n.openDebugger)debugger;n.isEnabled&&(l=await _(n.clientId),await O(),E())}async function E(){if(n.showLog&&console.log("【qlfyEcologicalLogin】登陆流程执行..."),n.token){n.showLog&&console.log("【qlfyEcologicalLogin】读取参数中的token"),l.isOutLogin=!0,l.token=n.token,await j(l),c&&i("loggingIn",l.token),m(n.token,c),c=!1;return}if((s.value.query.token||d!=null&&d.token)&&c){n.showLog&&console.log("【qlfyEcologicalLogin】读取链接中的token"),l.token=s.value.query.token||(d==null?void 0:d.token),l.refreshToken=s.value.query.refreshToken,await j(l),await T(),c&&i("loggingIn",l.token),m(l.token,c),c=!1;return}const w=l.token;if(w){n.showLog&&console.log("【qlfyEcologicalLogin】读取上一次缓存的token"),c&&i("loggingIn",w),m(w,c),c=!1;return}h()}async function h(){n.forceMode?await F():(i("loginFail",{msg:"未登陆",data:null}),u=!1)}function m(w,R){n.showLog&&console.log("【qlfyEcologicalLogin】尝试效验token");let A={token:w};const x={"tenant-id":n.tenantId,Authorization:"Basic "+btoa(n.clientId+":"+n.clientSecret)};b.post(n.loginServiceBaseAddress+"/admin-api/system/oauth2/check-token","",{params:A,headers:x}).then(async q=>{if(q.data.code!==0){if(n.showLog&&console.log("【qlfyEcologicalLogin】token无效, 无refreshToken"),n.forceMode)return await F();i("loginFail",{message:"token失效"}),u=!1;return}n.showLog&&console.log("【qlfyEcologicalLogin】token校验通过"),l.loginInfo=q.data.data,await j(l),R&&p(w)}).catch(async q=>{l.token="",await j(l),n.forceMode&&await F(),!n.forceMode&&(i("loginFail",{message:"token失效"}),u=!1)})}function p(w){n.showLog&&console.log("【qlfyEcologicalLogin】获取用户配置数据");let R={clientId:n.clientId};const A={"tenant-id":l.loginInfo.tenant_id,Authorization:w};b.get(n.loginServiceBaseAddress+"/admin-api/system/auth/get-permission-info",{params:R,headers:A}).then(async x=>{if(x.data.code!==0){if(n.showLog&&console.log("【qlfyEcologicalLogin】获取用户权限数据失败"),n.forceMode)return F();i("loginFail",{message:"用户配置获取失败"}),u=!1;return}if(n.showLog&&console.log("【qlfyEcologicalLogin】用户配置获取成功"),!x.data.menus.length){if(n.showLog&&console.log("【qlfyEcologicalLogin】本账号无菜单访问权限"),await T(),n.forceMode)return Se();i("loginFail",{message:"token无效失效"}),u=!1;return}l.userPermission=x.data,await j(l),await T(),i("loginSuccess",K(l.userPermission)),u=!0}).catch(x=>{if(n.showLog&&console.log("【qlfyEcologicalLogin】用户配置数据获取失败"),n.forceMode)return F();i("loginFail",{message:"用户配置获取失败",data:x}),u=!1})}function S(){return new Promise((w,R)=>{let A=null;u?w(!0):A=setInterval(x=>{u&&(A&&clearInterval(A),w(!0))},50),setTimeout(()=>{A&&clearInterval(A),R(!1)},1e4)})}async function O(){const w={...n};delete w.useRouter,l.props=K(w),l.routerMode=Jn(o)?"hash":"history",await j(l)}async function T(){await at(["token","refreshToken"],!0);let w=K(s.value.query);delete w.token,delete w.refreshToken,o.currentRoute.value.query=w}return(w,R)=>null}}),Vn=ct,Wn={install(e){e.component("qlfyEcologicalLogin",ct)}};P.default=Wn,P.getLoginInfo=it,P.getRefreshToken=Hn,P.getToken=st,P.getUserPermission=jn,P.goLogin=F,P.logout=Se,P.qlfyEcologicalLogin=Vn,Object.defineProperties(P,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
6
|
+
`+s):n.stack=s}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=I(this.defaults,r);const{transitional:n,paramsSerializer:o,headers:s}=r;n!==void 0&&ie.assertOptions(n,{silentJSONParsing:N.transitional(N.boolean),forcedJSONParsing:N.transitional(N.boolean),clarifyTimeoutError:N.transitional(N.boolean)},!1),o!=null&&(a.isFunction(o)?r.paramsSerializer={serialize:o}:ie.assertOptions(o,{encode:N.function,serialize:N.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),ie.assertOptions(r,{baseUrl:N.spelling("baseURL"),withXsrfToken:N.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let i=s&&a.merge(s.common,s[r.method]);s&&a.forEach(["delete","get","head","post","put","patch","common"],h=>{delete s[h]}),r.headers=C.concat(i,s);const c=[];let f=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(r)===!1||(f=f&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const l=[];this.interceptors.response.forEach(function(m){l.push(m.fulfilled,m.rejected)});let u,d=0,y;if(!f){const h=[tt.bind(this),void 0];for(h.unshift.apply(h,c),h.push.apply(h,l),y=h.length,u=Promise.resolve(r);d<y;)u=u.then(h[d++],h[d++]);return u}y=c.length;let E=r;for(d=0;d<y;){const h=c[d++],m=c[d++];try{E=h(E)}catch(p){m.call(this,p);break}}try{u=tt.call(this,E)}catch(h){return Promise.reject(h)}for(d=0,y=l.length;d<y;)u=u.then(l[d++],l[d++]);return u}getUri(t){t=I(this.defaults,t);const r=Ve(t.baseURL,t.url,t.allowAbsoluteUrls);return Ue(r,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){M.prototype[t]=function(r,n){return this.request(I(n||{},{method:t,url:r,data:(n||{}).data}))}}),a.forEach(["post","put","patch"],function(t){function r(n){return function(s,i,c){return this.request(I(c||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}M.prototype[t]=r(),M.prototype[t+"Form"]=r(!0)});let Nn=class ut{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(s){r=s});const n=this;this.promise.then(o=>{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](o);n._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(c=>{n.subscribe(c),s=c}).then(o);return i.cancel=function(){n.unsubscribe(s)},i},t(function(s,i,c){n.reason||(n.reason=new z(s,i,c),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new ut(function(o){t=o}),cancel:t}}};function Bn(e){return function(r){return e.apply(null,r)}}function _n(e){return a.isObject(e)&&e.isAxiosError===!0}const ye={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ye).forEach(([e,t])=>{ye[t]=e});function ot(e){const t=new M(e),r=Re(M.prototype.request,t);return a.extend(r,M.prototype,t,{allOwnKeys:!0}),a.extend(r,t,null,{allOwnKeys:!0}),r.create=function(o){return ot(I(e,o))},r}const b=ot(V);b.Axios=M,b.CanceledError=z,b.CancelToken=Nn,b.isCancel=He,b.VERSION=nt,b.toFormData=ee,b.AxiosError=g,b.Cancel=b.CanceledError,b.all=function(t){return Promise.all(t)},b.spread=Bn,b.isAxiosError=_n,b.mergeConfig=I,b.AxiosHeaders=C,b.formToJSON=e=>$e(a.isHTMLForm(e)?new FormData(e):e),b.getAdapter=et.getAdapter,b.HttpStatusCode=ye,b.default=b;const{Axios:tr,AxiosError:nr,CanceledError:rr,isCancel:or,CancelToken:sr,VERSION:ir,all:ar,Cancel:cr,isAxiosError:lr,spread:ur,toFormData:fr,AxiosHeaders:dr,HttpStatusCode:hr,formToJSON:pr,getAdapter:mr,mergeConfig:gr}=b;class Fn{constructor(t,r,n=1){this.db=null,this.dbName=t,this.storeName=r,this.version=n}open(){return new Promise((t,r)=>{if(this.db){t(this.db);return}const n=indexedDB.open(this.dbName,this.version);n.onupgradeneeded=o=>{const s=o.target.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"})},n.onsuccess=o=>{this.db=o.target.result,t(this.db)},n.onerror=o=>{console.error("IndexedDB 打开失败:",o.target.error),r(o.target.error)},n.onblocked=()=>{console.warn("数据库操作被阻塞,请关闭其他连接"),r(new Error("数据库操作被阻塞"))}})}close(){this.db&&(this.db.close(),this.db=null)}put(t){return new Promise((r,n)=>{if(!this.db){n(new Error("数据库未打开,请先调用 open() 方法"));return}const o=this.db.transaction(this.storeName,"readwrite"),i=o.objectStore(this.storeName).put(t);i.onsuccess=()=>{r(t)},i.onerror=()=>{console.error("数据存储失败:",i.error),n(i.error)},o.onerror=()=>{console.error("事务错误:",o.error),n(o.error)}})}update(t){return new Promise(async(r,n)=>{try{if(!await this.get(t.id)){n(new Error(`ID为 ${t.id} 的数据不存在,无法更新`));return}const s=await this.put(t);r(s)}catch(o){console.error("数据更新失败:",o),n(o)}})}partialUpdate(t,r){return new Promise(async(n,o)=>{try{const s=await this.get(t);if(!s){o(new Error(`ID为 ${t} 的数据不存在,无法更新`));return}const i={...s,...r,id:t},c=await this.put(i);n(c)}catch(s){console.error("数据部分更新失败:",s),o(s)}})}get(t){return new Promise((r,n)=>{if(!this.db){n(new Error("数据库未打开,请先调用 open() 方法"));return}const i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(t);i.onsuccess=()=>{r(i.result)},i.onerror=()=>{console.error("数据读取失败:",i.error),n(i.error)}})}delete(t){return new Promise((r,n)=>{if(!this.db){n(new Error("数据库未打开,请先调用 open() 方法"));return}const i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(t);i.onsuccess=()=>{r()},i.onerror=()=>{console.error("数据删除失败:",i.error),n(i.error)}})}getAll(){return new Promise((t,r)=>{if(!this.db){r(new Error("数据库未打开,请先调用 open() 方法"));return}const s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{console.error("获取所有数据失败:",s.error),r(s.error)}})}clear(){return new Promise((t,r)=>{if(!this.db){r(new Error("数据库未打开,请先调用 open() 方法"));return}const s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{console.error("清空存储失败:",s.error),r(s.error)}})}}class qn{constructor(){}set(t,r,n){let o=null;if(typeof n=="number"&&n>0)o=Date.now()+n*1e3;else if(typeof n>"u"){const i=this.getRaw(t);o=i?i.expire:null}const s={value:r,expire:o};localStorage.setItem(t,JSON.stringify(s))}get(t){const r=this.getRaw(t);return r?r.expire&&Date.now()>r.expire?(this.remove(t),null):r.value:null}getRaw(t){try{const r=localStorage.getItem(t);if(!r)return null;const n=JSON.parse(r);return n&&typeof n=="object"&&"value"in n&&"expire"in n?n:{value:r,expire:null}}catch{return{value:localStorage.getItem(t),expire:null}}}remove(t){localStorage.removeItem(t)}clear(){localStorage.clear()}}function Un(){return typeof window<"u"&&"indexedDB"in window&&indexedDB!==null&&indexedDB!==void 0}class In{constructor(){this.isInitialized=!1,this.indexedDBManager=new Fn("qlfyEcologicalLogin","loginData")}async ensureInitialized(){this.isInitialized||(await this.indexedDBManager.open(),this.isInitialized=!0)}async set(t,r){await this.ensureInitialized(),await this.indexedDBManager.put({id:t,data:r})}async get(t){await this.ensureInitialized();const r=await this.indexedDBManager.get(t);return r?r.data:null}async remove(t){await this.ensureInitialized(),await this.indexedDBManager.delete(t)}}class Mn{constructor(){this.localStorageManager=new qn}set(t,r){this.localStorageManager.set(t,r)}get(t){return this.localStorageManager.get(t)}remove(t){this.localStorageManager.remove(t)}}function $n(){return Un()?new In:new Mn}let $="qlfyEcologicalLogin_";const be=$n();async function j(e){$.indexOf(e.props.clientId)==-1&&($+=e.props.clientId);const t=be.set($,e);t instanceof Promise&&await t}async function Ee(){const e=be.remove($);e instanceof Promise&&await e}async function _(e){e&&$.indexOf(e)==-1&&($+=e);const t=be.get($),r=t instanceof Promise?await t:t;return r||{props:null,loginInfo:null,routerMode:vn(),isOutLogin:!1,token:"",refreshToken:"",tenant_id:168,userPermission:{}}}async function Se(e=!0,t,r){let n=await _();const o=n.props;if(o.openDebugger)debugger;if(!o||!o.isEnabled){console.error(new Error("统一登陆未开启,请检查配置"));return}const s=n.token;if(!s){console.error(new Error("未登陆或token失效"));return}b({method:"post",url:o.loginServiceBaseAddress+"/admin-api/system/auth/logout",headers:{"tenant-id":n.loginInfo.tenant_id,Authorization:"Bearer "+s}}).then(async i=>{i.data.code?r&&r(i):(e&&await F(),t&&t(i),await Ee(),await j(n))}).catch(i=>{console.log(i),r&&r(i)})}async function F(){const t=(await _()).props;if(!t||!t.isEnabled){console.error(new Error("统一登陆未开启,请检查配置"));return}const r=await zn();r&&setTimeout(()=>{window.open(r,"_self")}),await Ee()}async function st(){const e=await _(),t=e.props;return!t||!t.isEnabled?(console.error(new Error("统一登陆未开启,请检查配置")),""):e.token}async function it(){const e=await _(),t=e.props;return!t||!t.isEnabled?(console.error(new Error("统一登陆未开启,请检查配置")),null):e.loginInfo}async function jn(){let e=await _();const t=e.props;return!t||!t.isEnabled?(console.error(new Error("统一登陆未开启,请检查配置")),null):e.userPermission}async function Hn(){let e=await _();const t=e.props;return!t||!t.isEnabled?(console.error(new Error("统一登陆未开启,请检查配置")),null):e.refreshToken}async function zn(){const t=(await _()).props;if(!t||!t.isEnabled)return console.error(new Error("统一登陆未开启,请检查配置")),null;if(!t.clientId||!t.clientSecret)return console.error("未配置应用id或应用密钥!"),"";if(!t.loginPageBaseAddress)return console.error("未配置登录页基础地址!"),"";let r=await at(["token","refreshToken"],!1),n=t.redirectUrl||encodeURIComponent(r);return`${t.loginPageBaseAddress}/#/login?clientId=${t.clientId}&clientSecret=${t.clientSecret}&redirectUrl=${n}`}function vn(){if(window.location.href.includes("#")){const t=window.location.href.indexOf("#"),r=window.location.href.substring(t+1);if(r.startsWith("/")||r.includes("?"))return"hash"}return"history"}async function at(e,t=!1,r=window.location.href,n){if(n||(n=(await _()).routerMode),!["hash","history"].includes(n))throw new Error('路由模式必须是 "hash" 或 "history"');let o,s,i;if(n==="hash"){const c=r.indexOf("#");if(c===-1)return r;s=r.substring(0,c+1);const l=r.substring(c+1).split("?"),u=l[0],d=l[1]||"";i=new URLSearchParams(d),e.forEach(h=>{i.delete(h)});const y=i.toString(),E=y?`${u}?${y}`:u;o=`${s}${E}`}else{o=new URL(r),e.forEach(f=>{o.searchParams.delete(f)});const c=o.searchParams.toString();o=c?`${o.href}?${c}`:o.href}return t&&history.replaceState({},"",o),o}function K(e){if(e===null)return null;if(typeof e!="object")return e;if(e instanceof Date)return new Date(e);if(e instanceof RegExp)return new RegExp(e);let t=new e.constructor;for(let r in e)e.hasOwnProperty(r)&&(t[r]=K(e[r]));return t}function Jn(e){if(!e)throw new Error("请传入有效的Vue Router实例");return(()=>{var n,o,s,i;if((n=e.options)!=null&&n.history){const c=e.options.history;if((c==null?void 0:c.type)==="hash"||((o=c==null?void 0:c.constructor)==null?void 0:o.name)==="HashHistory")return"hash"}if(typeof e.mode=="string")return e.mode;const r=e.history;if(r){const c=(s=r.constructor)==null?void 0:s.name;if(c!=null&&c.includes("Hash")||c!=null&&c.includes("hash"))return"hash"}return typeof window<"u"&&((i=window.location)!=null&&i.hash)&&window.location.hash!=="#"?"hash":""})().toLowerCase()==="hash"}const ct=B.defineComponent({__name:"index",props:{clientId:{},clientSecret:{},loginPageBaseAddress:{},loginServiceBaseAddress:{},useRouter:{},forceMode:{type:Boolean,default:!0},clientName:{},token:{},isEnabled:{type:Boolean,default:!0},redirectPath:{default:""},tenantId:{default:168},showLog:{type:Boolean,default:!1},openDebugger:{type:Boolean,default:!1}},emits:["loggingIn","loginSuccess","loginFail","tokenRefresh"],setup(e,{expose:t,emit:r}){const n=e,o=n.useRouter,s=n.useRouter.currentRoute,i=r;let c=!0,f=null,l=null,u=!1,d=null;t({logout:async()=>await Se(),getToken:async()=>await st(),getLoginInfo:async()=>await it(),goLogin:async()=>await F()}),o.beforeEach(async(w,R,A)=>{n.forceMode&&!u?(n.showLog&&console.log("【qlfyEcologicalLogin】【路由拦截中】等待登陆放行..."),d=K(w.query),(u||await S())&&(n.showLog&&console.log("【qlfyEcologicalLogin】【路由拦截中】登陆成功路由放行"),d=null,delete w.query.token,delete w.query.refreshToken,A(w))):A()}),B.onBeforeUnmount(()=>{}),B.watch(()=>s.value.path,(w,R)=>{f&&clearTimeout(f),B.nextTick(()=>{f=setTimeout(()=>{n.isEnabled&&y()},300)})},{deep:!0,immediate:!0}),B.watch(()=>n.isEnabled,w=>{setTimeout(async()=>{w&&y(),w||(await Ee(),f&&clearTimeout(f))})},{deep:!0});async function y(){if(n.openDebugger)debugger;n.isEnabled&&(l=await _(n.clientId),await O(),E())}async function E(){if(n.showLog&&console.log("【qlfyEcologicalLogin】登陆流程执行..."),n.token){n.showLog&&console.log("【qlfyEcologicalLogin】读取参数中的token"),l.isOutLogin=!0,l.token=n.token,await j(l),c&&i("loggingIn",l.token),m(n.token,c),c=!1;return}if((s.value.query.token||d!=null&&d.token)&&c){n.showLog&&console.log("【qlfyEcologicalLogin】读取链接中的token"),l.token=s.value.query.token||(d==null?void 0:d.token),l.refreshToken=s.value.query.refreshToken,await j(l),await T(),c&&i("loggingIn",l.token),m(l.token,c),c=!1;return}const w=l.token;if(w){n.showLog&&console.log("【qlfyEcologicalLogin】读取上一次缓存的token"),c&&i("loggingIn",w),m(w,c),c=!1;return}h()}async function h(){n.forceMode?await F():(i("loginFail",{msg:"未登陆",data:null}),u=!1)}function m(w,R){n.showLog&&console.log("【qlfyEcologicalLogin】尝试效验token");let A={token:w};const x={"tenant-id":n.tenantId,Authorization:"Basic "+btoa(n.clientId+":"+n.clientSecret)};b.post(n.loginServiceBaseAddress+"/admin-api/system/oauth2/check-token","",{params:A,headers:x}).then(async q=>{if(q.data.code!==0){if(n.showLog&&console.log("【qlfyEcologicalLogin】token无效, 无refreshToken"),n.forceMode)return await F();i("loginFail",{message:"token失效"}),u=!1;return}n.showLog&&console.log("【qlfyEcologicalLogin】token校验通过"),l.loginInfo=q.data.data,await j(l),R&&p(w)}).catch(async q=>{l.token="",await j(l),n.forceMode&&await F(),!n.forceMode&&(i("loginFail",{message:"token失效"}),u=!1)})}function p(w){n.showLog&&console.log("【qlfyEcologicalLogin】获取用户配置数据");let R={clientId:n.clientId};const A={"tenant-id":l.loginInfo.tenant_id,Authorization:w};b.get(n.loginServiceBaseAddress+"/admin-api/system/auth/get-permission-info",{params:R,headers:A}).then(async x=>{if(x.data.code!==0){if(n.showLog&&console.log("【qlfyEcologicalLogin】获取用户权限数据失败"),n.forceMode)return F();i("loginFail",{message:"用户配置获取失败"}),u=!1;return}if(n.showLog&&console.log("【qlfyEcologicalLogin】用户配置获取成功"),!x.data.data.menus.length){if(n.showLog&&console.log("【qlfyEcologicalLogin】本账号无菜单访问权限"),await T(),n.forceMode)return Se();i("loginFail",{message:"token无效失效"}),u=!1;return}l.userPermission=x.data,await j(l),await T(),i("loginSuccess",K(l.userPermission)),u=!0}).catch(x=>{if(n.showLog&&console.log("【qlfyEcologicalLogin】用户配置数据获取失败"),n.forceMode)return F();i("loginFail",{message:"用户配置获取失败",data:x}),u=!1})}function S(){return new Promise((w,R)=>{let A=null;u?w(!0):A=setInterval(x=>{u&&(A&&clearInterval(A),w(!0))},50),setTimeout(()=>{A&&clearInterval(A),R(!1)},1e4)})}async function O(){const w={...n};delete w.useRouter,l.props=K(w),l.routerMode=Jn(o)?"hash":"history",await j(l)}async function T(){await at(["token","refreshToken"],!0);let w=K(s.value.query);delete w.token,delete w.refreshToken,o.currentRoute.value.query=w}return(w,R)=>null}}),Vn=ct,Wn={install(e){e.component("qlfyEcologicalLogin",ct)}};P.default=Wn,P.getLoginInfo=it,P.getRefreshToken=Hn,P.getToken=st,P.getUserPermission=jn,P.goLogin=F,P.logout=Se,P.qlfyEcologicalLogin=Vn,Object.defineProperties(P,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
package/lib/index.umd.js.gz
CHANGED
|
Binary file
|