@jetlinks-web/core 2.2.12 → 2.2.13
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 +1 -2
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
1
|
import{TOKEN_KEY as S,BASE_API as B,LOCAL_BASE_API as U}from"@jetlinks-web/constants";import{getToken as j,randomString as J}from"@jetlinks-web/utils";import G from"axios";import{isFunction as T,isObject as Y}from"lodash-es";var h,a={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},w=[],E=!1,be=window.__MICRO_APP_ENVIRONMENT__,b=new Map,F=s=>{let e=J(32);b.has(e)&&b.get(e)?.abort();let t=new AbortController;s.signal=t.signal,s.__requestKey=e,b.set(e,t)},V=s=>{F(s);let e=j(),t=localStorage.getItem(a.langKey),r=localStorage.getItem(U);if(t&&(s.headers[a.langKey]=t),r&&!s.baseURL){let n=s.url.startsWith("/")?s.url:`/${s.url}`;s.url=r+n}if(!e&&!a.filter_url?.some(n=>s.url?.includes(n)))return a.tokenExpiration?.(),s;if(s.headers[S]||(s.headers[S]=e),a.requestOptions&&T(a.requestOptions)){let n=a.requestOptions(s);if(n&&Y(n))for(let i in n)s[i]=n[i]}return s},z=s=>{if(a.handleResponse&&T(a.handleResponse))return a.handleResponse(s);let e=s.config?.__requestKey;if(e&&b.delete(e),s.data instanceof ArrayBuffer)return s;let t=s.data[a.codeKey||"status"];return typeof s.data=="object"&&typeof s.data.success>"u"&&(s.data.success=t===a.code),s.data},X=async s=>{let e=s.config;if(E)return new Promise((t,r)=>{w.push({resolve:t,reject:r})}).then(t=>(e.headers[S]=t,h(e))).catch(t=>Promise.reject(t));e._retry=!0,E=!0;try{if(await a.handleReconnect?.()){let r=j();return e.headers[S]=r,w.forEach(n=>n.resolve(r)),h(e)}}catch(t){throw w.forEach(r=>r.reject(t)),t}finally{w=[],E=!1}},M=async s=>{let e=s.response?.message||"Error",t=0;if(s.response){let{data:r,status:n}=s.response;switch(t=n,n){case 400:case 403:case 500:e=`${r?.message}`.substring(0,90);break;case 401:if(e=s.response.data.result?.text||"\u7528\u6237\u672A\u767B\u5F55",a.tokenExpiration?.(s),a.isCreateTokenRefresh)return X(s);break;case 404:e=s?.response?.data?.message||`${r?.error} ${r?.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 a.handleError&&T(a.handleError)&&a.handleError(e,t,s),Promise.reject(s)},ye=()=>{b.forEach(s=>s.abort()),b.clear()},Re=s=>{s&&(a=Object.assign(a,s)),h=G.create({withCredentials:!1,timeout:a.timeout,baseURL:B}),h.interceptors.request.use(V,M),h.interceptors.response.use(z,M)},W=(s,e={},t)=>h({method:"POST",url:s,data:e,...t}),P=(s,e=void 0,t)=>h({method:"GET",url:s,params:e,...t}),N=(s,e={},t)=>h({method:"PUT",url:s,data:e,...t}),_=(s,e={},t)=>h({method:"patch",url:s,data:e,...t}),q=(s,e=void 0,t)=>h({method:"DELETE",url:s,params:e,...t}),Z=(s,e,t)=>P(s,e,{responseType:"arraybuffer",...t}),ee=(s,e,t)=>W(s,e,{responseType:"arraybuffer",...t}),x={post:W,get:P,put:N,patch:_,remove:q,getStream:Z,postStream:ee},I=class{modulePath;constructor(e){this.modulePath=e}page(e={},t={url:void 0,method:void 0}){let{url:r="/_query",method:n="post",...i}=t;return x[n](`${this.modulePath}${r}`,e,i)}noPage(e={},t={url:void 0,method:void 0}){let{url:r="/_query/no-page",method:n="post",...i}=t;return x[n](`${this.modulePath}${r}`,{paging:!1,...e},i)}detail(e,t,r={url:void 0,method:void 0}){let{url:n=`/${e}/detail`,method:i="get",...d}=r;return x[i](`${this.modulePath}${n}`,t,d)}save(e={},t={url:void 0,method:void 0}){let{url:r="/_create",method:n="post",...i}=t;return x[n](`${this.modulePath}${r}`,e,i)}update(e={},t={url:void 0,method:void 0}){let{url:r="/_update",method:n="patch",...i}=t;return _(`${this.modulePath}${r}`,e,i)}delete(e,t,r={url:void 0,method:void 0}){let{url:n=`/${e}`,method:i="post",...d}=r;return q(`${this.modulePath}${n}`,t,d)}post(...e){let[t,r,n]=e;return W(`${this.modulePath}${t}`,r,n)}get(...e){let[t,r,n]=e;return P(`${this.modulePath}${t}`,r,n)}put(...e){let[t,r,n]=e;return N(`${this.modulePath}${t}`,r,n)}patch(...e){let[t,r,n]=e;return _(`${this.modulePath}${t}`,r,n)}remove(...e){let[t,r,n]=e;return q(`${this.modulePath}${t}`,r,n)}};import{getToken as te}from"@jetlinks-web/utils";import{BASE_API as se,TOKEN_KEY as K}from"@jetlinks-web/constants";import{isFunction as L,isObject as H}from"lodash-es";import{Observable as Q}from"rxjs";var v=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="{}",r={}){let n=this.getUrl(e),i=this,d=this.controller=new AbortController;return new Q(o=>{let u;return fetch(n,{method:"GET",signal:d.signal,keepalive:!0,...r,...this.handleRequest(n)}).then(m=>{u=m.body?.getReader();let k=new TextDecoder,l="";if(!u){o.error(new Error("No readable stream available"));return}let y=()=>{if(!i.isRead){u.cancel(),o.complete();return}u.read().then(({done:g,value:A})=>{if(g){if(l.trim().length>0)try{o.next(JSON.parse(l.trim()))}catch(p){o.error(p)}o.complete();return}let C=k.decode(A,{stream:!0});l+=C;let f=l.split(`
|
|
2
2
|
`);for(let p=0;p<f.length-1;++p){let R=f[p].trim();if(R.length>0)try{o.next(JSON.parse(R))}catch(O){o.error(O),u.cancel();return}}l=f[f.length-1],y()}).catch(g=>o.error(g))};i.isRead=!0,y()}).catch(m=>{o.error(m)}),()=>{i.cancel()}})}post(e,t={},r={}){let n=this.getUrl(e),i=this,d=this.controller=new AbortController;return new Q(o=>{let u;return fetch(n,{method:"POST",signal:d.signal,keepalive:!0,body:H(t)?JSON.stringify(t):t,...r,...this.handleRequest(n)}).then(async m=>{u=m.body?.getReader();let k=new TextDecoder,l="";if(!u){o.error(new Error("No readable stream available"));return}let y=()=>{if(!i.isRead){u.cancel(),o.complete();return}u.read().then(({done:g,value:A})=>{if(g){if(l.trim().length>0)try{o.next(JSON.parse(l.trim()))}catch(p){o.error(p)}o.complete();return}let C=k.decode(A,{stream:!0});l+=C;let f=l.split(`
|
|
3
|
-
`);for(let p=0;p<f.length-1;++p){let R=f[p].trim();if(R.length>0)try{o.next(JSON.parse(R))}catch(O){o.error(O),u.cancel();return}}l=f[f.length-1],y()}).catch(g=>o.error(g))};i.isRead=!0,y()}).catch(m=>{o.error(m)}),()=>{i.cancel()}})}handleRequest(e){let t={headers:{"Content-Type":"application/x-ndjson"}},r=te();if(!r&&this.options.filter_url?.some(n=>n.includes(e)))return this.options.tokenExpiration?.(),t;if(t.headers[K]||(t.headers[K]=r),this.options.requestOptions&&L(this.options.requestOptions)){let n=this.options.requestOptions(t);if(n&&H(n))for(let i in n)t[i]=n[i]}return t}handleResponse(e){return this.options.handleResponse&&L(this.options.handleResponse)?this.options.handleResponse(e):e}cancel(){this.isRead&&(this.isRead=!1),this.controller.abort()}},Ce=new v;import{webSocket as ne}from"rxjs/webSocket";import{Observable as re,Subject as ie,timer as D,EMPTY as oe}from"rxjs";import{retry as ae,catchError as ce}from"rxjs/operators";import{notification as ue}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 D(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=D(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):ue.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,r={}){if(console.log("getWebSocket",this.wsClient,e),c&&this.wsClient)return this.wsClient.getWebSocket(e,t,r);let n=new ie;this.subscriptions.set(e,n);let i={id:e,topic:t,parameter:r,type:"sub"};return this.send(i),new re(d=>{let o=n.subscribe(d);return()=>{o.unsubscribe(),this.send({id:e,type:"unsub"}),this.subscriptions.delete(e)}})}},Pe=new $;var le,$e=s=>{le=s};var pe={},Ie=(s={})=>{pe=s};var he,Ne=s=>{he=s};
|
|
4
|
-
export{v as NdJson,I as Request,$ as WebSocketClient,ye as abortAllRequests,Re as crateAxios,P as get,Z as getStream,Ne as installLocales,$e as installRouter,Ie as installStores,he as locales,Ce as ndJson,_ as patch,W as post,ee as postStream,N as put,q as remove,x as request,le as router,pe as stores,Pe as wsClient};
|
|
3
|
+
`);for(let p=0;p<f.length-1;++p){let R=f[p].trim();if(R.length>0)try{o.next(JSON.parse(R))}catch(O){o.error(O),u.cancel();return}}l=f[f.length-1],y()}).catch(g=>o.error(g))};i.isRead=!0,y()}).catch(m=>{o.error(m)}),()=>{i.cancel()}})}handleRequest(e){let t={headers:{"Content-Type":"application/x-ndjson"}},r=te();if(!r&&this.options.filter_url?.some(n=>n.includes(e)))return this.options.tokenExpiration?.(),t;if(t.headers[K]||(t.headers[K]=r),this.options.requestOptions&&L(this.options.requestOptions)){let n=this.options.requestOptions(t);if(n&&H(n))for(let i in n)t[i]=n[i]}return t}handleResponse(e){return this.options.handleResponse&&L(this.options.handleResponse)?this.options.handleResponse(e):e}cancel(){this.isRead&&(this.isRead=!1),this.controller.abort()}},Ce=new v;import{webSocket as ne}from"rxjs/webSocket";import{Observable as re,Subject as ie,timer as D,EMPTY as oe}from"rxjs";import{retry as ae,catchError as ce}from"rxjs/operators";import{notification as ue}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 D(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=D(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):ue.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,r={}){if(console.log("getWebSocket",this.wsClient,e),c&&this.wsClient)return this.wsClient.getWebSocket(e,t,r);let n=new ie;this.subscriptions.set(e,n);let i={id:e,topic:t,parameter:r,type:"sub"};return this.send(i),new re(d=>{let o=n.subscribe(d);return()=>{o.unsubscribe(),this.send({id:e,type:"unsub"}),this.subscriptions.delete(e)}})}},Pe=new $;var le,$e=s=>{le=s};var pe={},Ie=(s={})=>{pe=s};var he,Ne=s=>{he=s};export{v as NdJson,I as Request,$ as WebSocketClient,ye as abortAllRequests,Re as crateAxios,P as get,Z as getStream,Ne as installLocales,$e as installRouter,Ie as installStores,he as locales,Ce as ndJson,_ as patch,W as post,ee as postStream,N as put,q as remove,x as request,le as router,pe as stores,Pe as wsClient};
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jetlinks-web/core",
|
|
3
|
-
"version": "2.2.
|
|
4
|
-
"main": "dist/
|
|
5
|
-
"module": "dist/
|
|
6
|
-
"types": "dist/
|
|
3
|
+
"version": "2.2.13",
|
|
4
|
+
"main": "dist/index.mjs",
|
|
5
|
+
"module": "dist/index.mjs",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
7
|
"keywords": [
|
|
8
8
|
"jetlinks",
|
|
9
9
|
"jetlinks-web",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"rxjs": "^7.8.1",
|
|
31
31
|
"@jetlinks-web/constants": "^1.0.9",
|
|
32
32
|
"@jetlinks-web/types": "^1.0.2",
|
|
33
|
-
"@jetlinks-web/utils": "^1.2.
|
|
33
|
+
"@jetlinks-web/utils": "^1.2.12"
|
|
34
34
|
},
|
|
35
35
|
"publishConfig": {
|
|
36
36
|
"registry": "https://registry.npmjs.org/",
|