@jetlinks-web/core 2.2.18 → 2.2.19
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/dist/index.mjs +2 -2
- package/package.json +1 -1
- package/src/axios.ts +2 -2
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{TOKEN_KEY as S,BASE_API as U,LOCAL_BASE_API as D}from"@jetlinks-web/constants";import{getToken as P,randomString as B}from"@jetlinks-web/utils";import J from"axios";import{isFunction as A,isObject as G}from"lodash-es";var l=window.JetlinksCore?.instance||null,o={filter_url:[],code:200,codeKey:"status",timeout:1e3*15,handleRequest:void 0,handleResponse:void 0,handleError:void 0,langKey:"lang",requestOptions:s=>({}),tokenExpiration:()=>{},handleReconnect:()=>Promise.resolve(),isCreateTokenRefresh:!1},R=[],q=!1,me=window.__MICRO_APP_ENVIRONMENT__,g=new Map,Y=s=>{let e=
|
|
1
|
+
import{TOKEN_KEY as S,BASE_API as U,LOCAL_BASE_API as D}from"@jetlinks-web/constants";import{getToken as P,randomString as B}from"@jetlinks-web/utils";import J from"axios";import{isFunction as A,isObject as G}from"lodash-es";var l=window.JetlinksCore?.instance||null,o={filter_url:[],code:200,codeKey:"status",timeout:1e3*15,handleRequest:void 0,handleResponse:void 0,handleError:void 0,langKey:"lang",requestOptions:s=>({}),tokenExpiration:()=>{},handleReconnect:()=>Promise.resolve(),isCreateTokenRefresh:!1},R=[],q=!1,me=window.__MICRO_APP_ENVIRONMENT__,g=new Map,Y=s=>{let e=B(32);g.has(e)&&g.get(e)?.abort();let t=new AbortController;s.signal=t.signal,s.__requestKey=e,g.set(e,t)},F=s=>{Y(s);let e=P(),t=localStorage.getItem(o.langKey),n=localStorage.getItem(D);if(t&&(s.headers[o.langKey]=t),n&&!s.baseURL){let r=s.url.startsWith("/")?s.url:`/${s.url}`;s.url=n+r}if(!e&&!o.filter_url?.some(r=>s.url?.includes(r)))return o.tokenExpiration?.(),s;if(s.headers[S]||(s.headers[S]=e),o.requestOptions&&A(o.requestOptions)){let r=o.requestOptions(s);if(r&&G(r))for(let a in r)s[a]=r[a]}return s},V=s=>{if(o.handleResponse&&A(o.handleResponse))return o.handleResponse(s);let e=s.config?.__requestKey;if(e&&g.delete(e),s.data instanceof ArrayBuffer)return s;let t=s.data[o.codeKey||"status"];return typeof s.data=="object"&&typeof s.data.success>"u"&&(s.data.success=t===o.code),s.data},z=async s=>{let e=s.config;if(q)return new Promise((t,n)=>{R.push({resolve:t,reject:n})}).then(t=>(e.headers[S]=t,l(e))).catch(t=>Promise.reject(t));e._retry=!0,q=!0;try{if(await o.handleReconnect?.()){let n=P();return e.headers[S]=n,R.forEach(r=>r.resolve(n)),l(e)}}catch(t){throw R.forEach(n=>n.reject(t)),t}finally{R=[],q=!1}},M=async s=>{let e=s.response?.message||"Error",t=0;if(s.response){let{data:n,status:r}=s.response;switch(t=r,r){case 400:case 403:case 500:e=`${n?.message}`.substring(0,90);break;case 401:if(e=s.response.data.result?.text||"\u7528\u6237\u672A\u767B\u5F55",o.tokenExpiration?.(s),o.isCreateTokenRefresh)return z(s);break;case 404:e=s?.response?.data?.message||`${n?.error} ${n?.path}`;break;default:break}}else s.response===void 0&&(e=s.message.includes("timeout")?"\u63A5\u53E3\u54CD\u5E94\u8D85\u65F6":s.message,t="timeout");return o.handleError&&A(o.handleError)&&o.handleError(e,t,s),Promise.reject(s)},ge=()=>{g.forEach(s=>s.abort()),g.clear()},we=s=>{s&&(o=Object.assign(o,s)),l=J.create({withCredentials:!1,timeout:o.timeout,baseURL:U}),l.interceptors.request.use(F,M),l.interceptors.response.use(V,M)},x=(s,e={},t)=>l({method:"POST",url:s,data:e,...t}),T=(s,e=void 0,t)=>l({method:"GET",url:s,params:e,...t}),$=(s,e={},t)=>l({method:"PUT",url:s,data:e,...t}),j=(s,e={},t)=>l({method:"patch",url:s,data:e,...t}),I=(s,e=void 0,t)=>l({method:"DELETE",url:s,params:e,...t}),X=(s,e,t)=>T(s,e,{responseType:"arraybuffer",...t}),Z=(s,e,t)=>x(s,e,{responseType:"arraybuffer",...t}),ee={post:x,get:T,put:$,patch:j,remove:I,getStream:X,postStream:Z},v=class{constructor(e){this.basePath=e;this.basePath=e.startsWith("/")?e:`/${e}`}requestWrapper(e,t,n={},r={}){let{url:a=e,method:y=t,...i}=r;return ee[y](`${this.basePath}${a}`,n,i)}page(e={},t={url:void 0,method:void 0}){return this.requestWrapper("/_query","post",e,t)}noPage(e={},t={url:void 0,method:void 0}){return this.requestWrapper("/_query/no-paging","post",{paging:!1,...e},t)}detail(e,t,n={url:void 0,method:void 0}){return this.requestWrapper(`/${e}/detail`,"get",t,n)}save(e={},t={url:void 0,method:void 0}){return this.requestWrapper("","post",e,t)}update(e={},t={url:void 0,method:void 0}){return this.requestWrapper("","patch",e,t)}delete(e,t,n={url:void 0,method:void 0}){return this.requestWrapper(`/${e}`,"post",t,n)}batch(e={},t,n){let r=`/_batch${t?"/"+t:""}`;return this.requestWrapper(r,"post",e,n)}post(e,t,n){return x(`${this.basePath}${e}`,t,n)}get(e,t,n){return T(`${this.basePath}${e}`,t,n)}put(e,t,n){return $(`${this.basePath}${e}`,t,n)}patch(e,t,n){return j(`${this.basePath}${e}`,t,n)}remove(e,t,n){return I(`${this.basePath}${e}`,t,n)}getStream(e,t,n){return T(`${this.basePath}${e}`,t,{responseType:"arraybuffer",...n})}postStream(e,t,n){return x(`${this.basePath}${e}`,t,{responseType:"arraybuffer",...n})}};import{getToken as te}from"@jetlinks-web/utils";import{BASE_API as se,TOKEN_KEY as N}from"@jetlinks-web/constants";import{isFunction as K,isObject as L}from"lodash-es";import{Observable as H}from"rxjs";var W=class{options={code:200,codeKey:"status"};isRead=!1;controller=null;constructor(){}create(e){this.options=Object.assign(this.options,e)}getUrl(e){return se+e}get(e,t="{}",n={}){let r=this.getUrl(e),a=this,y=this.controller=new AbortController;return new H(i=>{let h;return fetch(r,{method:"GET",signal:y.signal,keepalive:!0,...n,...this.handleRequest(r)}).then(m=>{h=m.body?.getReader();let k=new TextDecoder,p="";if(!h){i.error(new Error("No readable stream available"));return}let w=()=>{if(!a.isRead){h.cancel(),i.complete();return}h.read().then(({done:d,value:E})=>{if(d){if(p.trim().length>0)try{i.next(JSON.parse(p.trim()))}catch(u){i.error(u)}i.complete();return}let C=k.decode(E,{stream:!0});p+=C;let f=p.split(`
|
|
2
2
|
`);for(let u=0;u<f.length-1;++u){let b=f[u].trim();if(b.length>0)try{i.next(JSON.parse(b.startsWith("data:")?b.slice(5):b))}catch(O){i.error(O);return}}p=f[f.length-1],w()}).catch(d=>{d.name!=="AbortError"&&i.error(d)})};a.isRead=!0,w()}).catch(m=>{i.error(m)}),()=>{a.cancel()}})}post(e,t={},n={}){let r=this.getUrl(e),a=this,y=this.controller=new AbortController;return new H(i=>{let h;return fetch(r,{method:"POST",signal:y.signal,keepalive:!0,body:L(t)?JSON.stringify(t):t,...n,...this.handleRequest(r)}).then(async m=>{h=m.body?.getReader();let k=new TextDecoder,p="";if(!h){i.error(new Error("No readable stream available"));return}let w=()=>{if(!a.isRead){h.cancel(),i.complete();return}h.read().then(({done:d,value:E})=>{if(d){if(p.trim().length>0)try{i.next(JSON.parse(p.trim()))}catch(u){i.error(u)}i.complete();return}let C=k.decode(E,{stream:!0});p+=C;let f=p.split(`
|
|
3
|
-
`);for(let u=0;u<f.length-1;++u){let b=f[u].trim();if(b.length>0)try{i.next(JSON.parse(b.startsWith("data:")?b.slice(5):b))}catch(O){i.error(O);return}}p=f[f.length-1],w()}).catch(d=>{d.name!=="AbortError"&&i.error(d)})};a.isRead=!0,w()}).catch(m=>{i.error(m)}),()=>{a.cancel()}})}handleRequest(e){let t={headers:{"Content-Type":"application/x-ndjson"}},n=te();if(!n&&this.options.filter_url?.some(r=>r.includes(e)))return this.options.tokenExpiration?.(),t;if(t.headers[N]||(t.headers[N]=n),this.options.requestOptions&&K(this.options.requestOptions)){let r=this.options.requestOptions(t);if(r&&L(r))for(let a in r)t[a]=r[a]}return t}handleResponse(e){return this.options.handleResponse&&K(this.options.handleResponse)?this.options.handleResponse(e):e}cancel(){this.isRead&&(this.isRead=!1),this.controller&&this.controller.abort()}},Ee=new
|
|
3
|
+
`);for(let u=0;u<f.length-1;++u){let b=f[u].trim();if(b.length>0)try{i.next(JSON.parse(b.startsWith("data:")?b.slice(5):b))}catch(O){i.error(O);return}}p=f[f.length-1],w()}).catch(d=>{d.name!=="AbortError"&&i.error(d)})};a.isRead=!0,w()}).catch(m=>{i.error(m)}),()=>{a.cancel()}})}handleRequest(e){let t={headers:{"Content-Type":"application/x-ndjson"}},n=te();if(!n&&this.options.filter_url?.some(r=>r.includes(e)))return this.options.tokenExpiration?.(),t;if(t.headers[N]||(t.headers[N]=n),this.options.requestOptions&&K(this.options.requestOptions)){let r=this.options.requestOptions(t);if(r&&L(r))for(let a in r)t[a]=r[a]}return t}handleResponse(e){return this.options.handleResponse&&K(this.options.handleResponse)?this.options.handleResponse(e):e}cancel(){this.isRead&&(this.isRead=!1),this.controller&&this.controller.abort()}},Ee=new W;import{webSocket as ne}from"rxjs/webSocket";import{Observable as re,Subject as ie,timer as Q,EMPTY as oe}from"rxjs";import{retry as ae,catchError as ce}from"rxjs/operators";import{notification as pe}from"ant-design-vue";var c=window.__MICRO_APP_ENVIRONMENT__,_=class{ws=null;subscriptions=new Map;pendingSubscriptions=new Map;heartbeatSubscription=null;reconnectAttempts=0;maxReconnectAttempts=2;isConnected=!1;tempQueue=[];url="";options={};wsClient;constructor(e){this.setOptions(e),this.setupConnectionMonitor(),c&&window.microApp.addGlobalDataListener(t=>{this.wsClient=t.wsClient})}setOptions(e){this.options=e||{}}initWebSocket(e){this.url=e}setupConnectionMonitor(){c||(window.addEventListener("online",()=>{console.log("Network is online, attempting to reconnect..."),this.reconnect()}),window.addEventListener("offline",()=>{console.log("Network is offline, caching subscriptions..."),this.cacheSubscriptions()}),window.addEventListener("beforeunload",()=>{this.disconnect()}))}getReconnectDelay(){return this.reconnectAttempts<=10?5e3:this.reconnectAttempts<=20?15e3:6e4}setupWebSocket(){if(c&&this.wsClient){this.wsClient.setupWebSocket();return}this.ws||!this.url||(this.ws=ne({url:this.url,openObserver:{next:()=>{console.log("WebSocket connected"),this.isConnected=!0,this.reconnectAttempts=0,this.startHeartbeat(),this.restoreSubscriptions(),this.processTempQueue()}},closeObserver:{next:()=>{console.log("WebSocket disconnected"),this.isConnected=!1;let e=this.getReconnectDelay();setTimeout(()=>{this.reconnectAttempts+=1,!(this.reconnectAttempts>this.maxReconnectAttempts)&&(this.cacheSubscriptions(),this.stopHeartbeat(),this.reconnect())},e)}}}),this.ws.pipe(ce(e=>(console.error("WebSocket error:",e),oe)),ae({delay:(e,t)=>{if(this.reconnectAttempts=t,t>this.maxReconnectAttempts)throw new Error("Max reconnection attempts reached");return Q(this.getReconnectDelay())}})).subscribe(e=>this.handleMessage(e),e=>console.error("WebSocket error:",e)))}startHeartbeat(){if(c&&this.wsClient){this.wsClient.startHeartbeat();return}this.stopHeartbeat(),this.heartbeatSubscription=Q(0,2e3).subscribe(()=>{this.send({type:"ping"})})}stopHeartbeat(){if(c&&this.wsClient){this.wsClient.stopHeartbeat();return}this.heartbeatSubscription&&(this.heartbeatSubscription.unsubscribe(),this.heartbeatSubscription=null)}handleMessage(e){if(c&&this.wsClient){this.wsClient.handleMessage(e);return}if(e.type==="pong")return;if(e.type==="error"){this.options.onError?this.options.onError(e):pe.error({key:"error",message:e.message});return}let t=this.subscriptions.get(e.requestId||"");t&&(e.type==="complete"?(t.complete(),this.subscriptions.delete(e.requestId||"")):e.type==="result"&&t.next(e))}processTempQueue(){if(c&&this.wsClient){this.wsClient.processTempQueue();return}for(;this.tempQueue.length>0;){let e=this.tempQueue.shift();e&&this.send(e)}}cacheSubscriptions(){if(c&&this.wsClient){this.wsClient.cacheSubscriptions();return}this.pendingSubscriptions=new Map(this.subscriptions),this.subscriptions.clear()}restoreSubscriptions(){if(c&&this.wsClient){this.wsClient.restoreSubscriptions();return}this.pendingSubscriptions.forEach((e,t)=>{this.subscriptions.set(t,e)}),this.pendingSubscriptions.clear()}reconnect(){if(c&&this.wsClient){this.wsClient.reconnect();return}!this.isConnected&&navigator.onLine&&(this.ws=null,this.setupWebSocket())}connect(){if(c&&this.wsClient){this.wsClient.connect();return}this.setupWebSocket()}disconnect(){if(c&&this.wsClient){this.wsClient.disconnect();return}this.ws&&(this.ws.complete(),this.ws=null),this.stopHeartbeat(),this.subscriptions.clear(),this.pendingSubscriptions.clear(),this.tempQueue=[]}send(e){if(c&&this.wsClient){this.wsClient.send(e);return}this.ws&&this.isConnected?this.ws.next(e):this.tempQueue.push(e)}getWebSocket(e,t,n={}){if(console.log("getWebSocket",this.wsClient,e),c&&this.wsClient)return this.wsClient.getWebSocket(e,t,n);let r=new ie;this.subscriptions.set(e,r);let a={id:e,topic:t,parameter:n,type:"sub"};return this.send(a),new re(y=>{let i=r.subscribe(y);return()=>{i.unsubscribe(),this.send({id:e,type:"unsub"}),this.subscriptions.delete(e)}})}},Me=new _;var ue,Pe=s=>{ue=s};var le={},je=(s={})=>{le=s};var he,Ne=s=>{he=s};export{W as NdJson,v as Request,_ as WebSocketClient,ge as abortAllRequests,we as crateAxios,T as get,X as getStream,Ne as installLocales,Pe as installRouter,je as installStores,l as instance,he as locales,Ee as ndJson,j as patch,x as post,Z as postStream,$ as put,I as remove,ee as request,ue as router,le as stores,Me as wsClient};
|
package/package.json
CHANGED
package/src/axios.ts
CHANGED
|
@@ -32,7 +32,7 @@ const isApp = (window as any).__MICRO_APP_ENVIRONMENT__
|
|
|
32
32
|
|
|
33
33
|
const pendingRequests = new Map<string, AbortController>();
|
|
34
34
|
const requestRecords = (config: ExpandRequestConfig) => {
|
|
35
|
-
const key =
|
|
35
|
+
const key = randomString(32)
|
|
36
36
|
|
|
37
37
|
// 取消重复请求
|
|
38
38
|
if (pendingRequests.has(key)) {
|
|
@@ -41,7 +41,7 @@ const requestRecords = (config: ExpandRequestConfig) => {
|
|
|
41
41
|
|
|
42
42
|
const controller = new AbortController()
|
|
43
43
|
config.signal = controller.signal;
|
|
44
|
-
config.__requestKey =
|
|
44
|
+
config.__requestKey = key;
|
|
45
45
|
|
|
46
46
|
pendingRequests.set(key, controller)
|
|
47
47
|
}
|