@cvoc/core 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* @cvoc/core v0.
|
|
1
|
+
/* @cvoc/core v0.11.0 | MIT */
|
|
2
2
|
import mqtt from 'mqtt';
|
|
3
3
|
|
|
4
4
|
const LogLevel = {
|
|
@@ -823,7 +823,7 @@ class MessageClient {
|
|
|
823
823
|
}
|
|
824
824
|
|
|
825
825
|
/** @cvoc/core 版本号,值与 package.json 保持一致 */
|
|
826
|
-
const coreVersion = "0.
|
|
826
|
+
const coreVersion = "0.11.0";
|
|
827
827
|
|
|
828
828
|
export { Config, EventEmitter as Event, EventEmitter, HttpClient, Logger as Log, LogLevel, Logger, MessageClient as Message, MessageClient, MessageConnectionState, coreVersion, event, getGlobalLogLevel, log, setGlobalLogLevel };
|
|
829
829
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* @cvoc/core v0.
|
|
1
|
+
/* @cvoc/core v0.11.0 | MIT | browser IIFE bundle */
|
|
2
2
|
var CognvocCore = (function (exports, mqtt) {
|
|
3
3
|
'use strict';
|
|
4
4
|
|
|
@@ -824,7 +824,7 @@ var CognvocCore = (function (exports, mqtt) {
|
|
|
824
824
|
}
|
|
825
825
|
|
|
826
826
|
/** @cvoc/core 版本号,值与 package.json 保持一致 */
|
|
827
|
-
const coreVersion = "0.
|
|
827
|
+
const coreVersion = "0.11.0";
|
|
828
828
|
|
|
829
829
|
exports.Config = Config;
|
|
830
830
|
exports.Event = EventEmitter;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var CognvocCore=function(e,t){"use strict";const n={Debug:"debug",Info:"info",Warn:"warn",Error:"error",Silent:"silent"},s={[n.Debug]:10,[n.Info]:20,[n.Warn]:30,[n.Error]:40,[n.Silent]:Number.POSITIVE_INFINITY};let r=n.Info;function i(e){r=e}class o{constructor(e={}){this.namespace=e.namespace,this.handler=e.handler}debug(e,...t){this.write(n.Debug,e,t)}info(e,...t){this.write(n.Info,e,t)}warn(e,...t){this.write(n.Warn,e,t)}error(e,...t){this.write(n.Error,e,t)}write(e,t,i){if(s[e]<s[r])return;const o={level:e,message:t,args:i,namespace:this.namespace,timestamp:Date.now()};if(this.handler)return void this.handler(o);const a=this.namespace?`[${this.namespace}] ${t}`:t,{console:c}=globalThis;if(!c)return;const h=e===n.Debug&&"function"!=typeof c.debug?c.log:c[e];h?.(a,...i)}}const a=new o,c={apiUrl:"",accessToken:"",refreshToken:"",tenantId:""};let h={},d=!1;const l=new o({namespace:"EventEmitter"});class u{constructor(){this.listeners=new Map}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.off(e,t)}}once(e,t){const n=s=>{this.off(e,n),t(s)};return this.on(e,n)}off(e,t){const n=this.listeners.get(e);n&&(n.delete(t),0===n.size&&this.listeners.delete(e))}emit(e,t){const n=this.listeners.get(e);if(!n||0===n.size)return!1;for(const s of Array.from(n))try{s(t)}catch(t){l.error(`listener for event "${String(e)}" threw:`,t)}return!0}clear(e){void 0!==e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){return void 0!==e?this.listeners.get(e)?.size??0:Array.from(this.listeners.values()).reduce((e,t)=>e+t.size,0)}}const f=new u,p=new o({namespace:"HttpClient"});const g=new o({namespace:"MessageClient"}),k={Idle:"idle",Connecting:"connecting",Connected:"connected",Reconnecting:"reconnecting",Closed:"closed",Error:"error",TokenExpired:"token-expired"};class b{constructor(e){if(this.client=null,this.state=k.Idle,this.handlers=new Map,this.subscribedTopics=new Set,this.tokenExpiredListeners=new Set,this.connectedListeners=new Set,this.connectSettlers=null,this.handleConnect=()=>{const e=this.state===k.Connected;if(this.state=k.Connected,this.resubscribeAll(),this.publishBirth(),!e)for(const e of Array.from(this.connectedListeners))try{e()}catch(e){g.error("onConnected listener execution failed:",e)}},this.handleReconnect=()=>{this.state=k.Reconnecting},this.handleClose=()=>{this.state!==k.Error&&this.state!==k.TokenExpired&&(this.state=k.Closed)},this.handleOffline=()=>{this.state===k.Connected&&(this.state=k.Reconnecting)},this.handleError=e=>{this.isTokenExpiredError(e)?this.markTokenExpired(e):(this.state=k.Error,g.error("mqtt error:",e))},this.handleMessage=(e,t)=>{const n=this.decodePayload(t);g.debug(`received message on topic "${e}"`,n);const s=this.handlers.get(e);if(s&&0!==s.size)for(const t of Array.from(s))try{t(n,e)}catch(t){g.error(`handler for topic "${e}" threw:`,t)}},this.options=e,e.topics&&e.topics.length>0)for(const t of e.topics)this.subscribedTopics.add(t);this.connect().catch(e=>{this.state!==k.Closed&&g.error("mqtt auto-connect failed:",e)})}getState(){return this.state}onTokenExpired(e){return this.tokenExpiredListeners.add(e),()=>{this.tokenExpiredListeners.delete(e)}}onConnected(e){return this.connectedListeners.add(e),()=>{this.connectedListeners.delete(e)}}setToken(e){e!==this.options.token&&(this.options.token=e,this.reconnectWithCurrentToken())}connect(){return this.state===k.Connected||this.state===k.Connecting||this.state===k.Reconnecting?Promise.resolve():(this.disposeClient(),this.state=k.Connecting,new Promise((e,n)=>{let s;try{s=t.connect(this.options.url,{clientId:`agent-sdk-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,username:this.options.username,password:this.options.token,keepalive:this.options.keepalive,will:this.options.will&&{topic:this.options.will.topic,payload:this.options.will.payload,qos:this.options.will.qos??1,retain:this.options.will.retain??!0}})}catch(e){return this.state=k.Error,void n(e)}this.client=s,this.connectSettlers={resolve:e,reject:n},s.on("connect",this.handleConnect),s.on("reconnect",this.handleReconnect),s.on("close",this.handleClose),s.on("offline",this.handleOffline),s.on("error",this.handleError),s.on("message",this.handleMessage);const r=()=>{o(),e()},i=e=>{o(),n(e)},o=()=>{this.connectSettlers=null,s.off("connect",r),s.off("error",i)};s.once("connect",r),s.once("error",i)}))}disconnect(){return new Promise(e=>{const t=this.client;if(!t)return this.reset(),void e();let n=!1;const s=()=>{n||(n=!0,clearTimeout(r),this.settlePendingConnect(new Error("Connection closed by agent")),this.reset(),e())},r=setTimeout(s,2e3);t.once("close",s);try{t.end(!0)}catch{s()}})}subscribe(e,t,n){t&&this.addListener(e,t);const s=this.client;s&&this.state===k.Connected&&s.subscribe(e,n??{qos:2},t=>{t&&g.error(`subscribe ${e} failed`,t)}),this.subscribedTopics.add(e)}unsubscribe(e){this.subscribedTopics.delete(e),this.handlers.delete(e);const t=this.client;t&&this.state===k.Connected&&t.unsubscribe(e)}send(e,t,n){const s=this.client;if(!s)throw new Error("send failed: not connected");const r=this.encodePayload(t);s.publish(e,r,n??{qos:2})}on(e,t){return this.addListener(e,t),()=>this.removeListener(e,t)}off(e,t){this.removeListener(e,t)}clear(e){void 0!==e?this.handlers.delete(e):this.handlers.clear()}addListener(e,t){let n=this.handlers.get(e);n||(n=new Set,this.handlers.set(e,n)),n.add(t)}removeListener(e,t){const n=this.handlers.get(e);n&&(n.delete(t),0===n.size&&this.handlers.delete(e))}reset(){this.state=k.Closed,this.client=null,this.connectSettlers=null,this.handlers.clear(),this.subscribedTopics.clear()}settlePendingConnect(e){const t=this.connectSettlers;this.connectSettlers=null,t?.reject(e)}disposeClient(){const e=this.client;if(e){this.client=null;try{e.removeAllListeners(),e.end(!0)}catch{}this.settlePendingConnect(new Error("Connection discarded (token updated or client rebuilt)"))}}reconnectWithCurrentToken(){this.disposeClient(),this.state=k.Idle,this.connect().catch(e=>{g.error("Connection reconnect with new token failed:",e)})}markTokenExpired(e){const t=this.state!==k.TokenExpired;if(this.settlePendingConnect(e??new Error("Connection token expired or invalid")),this.disposeClient(),this.state=k.TokenExpired,t){g.warn("mqtt token expired or invalid, auto-reconnect stopped",e?.message);for(const e of Array.from(this.tokenExpiredListeners))try{e()}catch(e){g.error("onTokenExpired listener execution failed:",e)}}}isTokenExpiredError(e){return/unexpected server response: 401|not authorized|unauthorized|bad user(name)? or password|authenticat(?:e|ion) fail|token (?:expired|invalid)/i.test(e?.message??"")}resubscribeAll(){const e=this.client;if(e&&this.state===k.Connected&&0!==this.subscribedTopics.size)for(const t of this.subscribedTopics)e.subscribe(t,{qos:2},e=>{e&&g.error(`subscribe ${t} failed`,e)})}encodePayload(e){return"string"==typeof e?e:JSON.stringify(e)}decodePayload(e){const t=new TextDecoder("utf-8").decode(e);try{return JSON.parse(t)}catch{return t}}publishBirth(){const e=this.options.birth,t=this.client;e&&t&&t.publish(e.topic,e.payload,{qos:e.qos??1,retain:e.retain??!0},t=>{t&&g.error(`publish birth to "${e.topic}" failed`,t)})}}return e.Config=class{constructor(){}static init(e){const{apiUrl:t,accessToken:n,refreshToken:s,tenantId:r,logLevel:o,phone:a}=e;void 0!==t&&(c.apiUrl=t),void 0!==n&&(c.accessToken=n),void 0!==s&&(c.refreshToken=s),void 0!==r&&(c.tenantId=r),o&&i(o),void 0!==a&&(h=a),d=!0}static isInitialized(){return d}static ensureInitialized(){if(!d)throw new Error("Config is not initialized. Please call Config.init() before using any module.")}static getGlobalConfig(){return c}static updateTokens(e){c.accessToken=e.accessToken,void 0!==e.refreshToken&&(c.refreshToken=e.refreshToken)}static getPhoneConfig(){return h}},e.Event=u,e.EventEmitter=u,e.HttpClient=class{constructor(e){this.refreshing=null,this.refreshFailed=!1,this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.token=e.token??"",this.refreshToken=e.refreshToken??"",this.tenantId=e.tenantId??""}setBaseUrl(e){this.baseUrl=e.replace(/\/+$/,"")}setToken(e){this.token=e,this.refreshFailed=!1}setRefreshToken(e){this.refreshToken=e,this.refreshFailed=!1}async checkIn(e="AVAILABLE"){const t=await this.request("/acc/acd/agent/check-in",{method:"POST",contentType:"json",body:{presence:e}});return!0!==t.data&&p.warn("checkIn returned abnormal:",t),t.data}async checkOut(){const e=await this.request("/acc/acd/agent/check-out",{method:"POST",contentType:"json"});return!0!==e.data&&p.warn("checkOut returned abnormal:",e),e.data}async heartbeat(e={}){const t=await this.request("/acc/acd/agent/heartbeat",{method:"POST",contentType:"form",body:e});return!0!==t.data&&p.warn("heartbeat returned abnormal:",t),t.data}async agentPresence(e,t){const n=await this.request("/acc/acd/agent/presence",{method:"PUT",contentType:"json",body:t?{presence:e,reason:t}:{presence:e}});return!0!==n.data&&p.warn("agentPresence returned abnormal:",n),n.data}async agentInfo(){const e=await this.request("/acc/acd/agent/self",{method:"GET",contentType:"form"});return e.data?e.data:(p.warn("agentInfo returned abnormal:",e),null)}async getMqttToken(){const e=await this.request("/infra/mqtt/token",{method:"POST",contentType:"json",body:{clientNo:"agent-sdk"}});return e.data?.token?e.data.token:(p.warn("getMqttToken returned abnormal:",e),"")}async doRefreshToken(e=this.refreshToken){return p.warn("doRefreshToken skipped: refresh token is disabled"),null}async tryRefreshToken(){return!1}async request(e,t,n=!0){const s={Authorization:`Bearer ${this.token}`,"Tenant-Id":String(this.tenantId),"Content-Type":"json"===t.contentType?"application/json;charset=UTF-8":"application/x-www-form-urlencoded;charset=UTF-8"};let r;t.body&&Object.keys(t.body).length>0&&(r="json"===t.contentType?JSON.stringify(t.body):new URLSearchParams(Object.entries(t.body).map(([e,t])=>[e,String(t)])).toString());const i=this.token,o=await fetch(`${this.baseUrl}${e}`,{method:t.method,headers:s,body:r});if(o.ok){const s=await o.json();return n&&401===s?.code&&(this.token!==i||await this.tryRefreshToken())?(p.info("Token expired, refreshing and retrying:",e),this.request(e,t,!1)):s}if(n&&401===o.status&&(this.token!==i||await this.tryRefreshToken()))return p.info("Token expired, refreshing and retrying:",e),this.request(e,t,!1);throw new Error(`HTTP ${o.status} ${o.statusText}`)}async download(e,t=!0){const n={Authorization:`Bearer ${this.token}`,"Tenant-Id":String(this.tenantId)},s=this.token,r=await fetch(`${this.baseUrl}${e}`,{method:"GET",headers:n});if(r.ok){if((r.headers.get("content-type")??"").includes("application/json")){const n=await r.json();if(t&&401===n.code&&(this.token!==s||await this.tryRefreshToken()))return p.info("Token expired, refreshing and retrying download:",e),this.download(e,!1);throw new Error(`下载失败:${n.msg||"未知错误"} (code=${n.code})`)}return r.blob()}if(t&&401===r.status&&(this.token!==s||await this.tryRefreshToken()))return p.info("Token expired, refreshing and retrying download:",e),this.download(e,!1);throw new Error(`HTTP ${r.status} ${r.statusText}`)}},e.Log=o,e.LogLevel=n,e.Logger=o,e.Message=b,e.MessageClient=b,e.MessageConnectionState=k,e.coreVersion="0.10.0",e.event=f,e.getGlobalLogLevel=function(){return r},e.log=a,e.setGlobalLogLevel=i,e}({},mqtt);
|
|
1
|
+
var CognvocCore=function(e,t){"use strict";const n={Debug:"debug",Info:"info",Warn:"warn",Error:"error",Silent:"silent"},s={[n.Debug]:10,[n.Info]:20,[n.Warn]:30,[n.Error]:40,[n.Silent]:Number.POSITIVE_INFINITY};let r=n.Info;function i(e){r=e}class o{constructor(e={}){this.namespace=e.namespace,this.handler=e.handler}debug(e,...t){this.write(n.Debug,e,t)}info(e,...t){this.write(n.Info,e,t)}warn(e,...t){this.write(n.Warn,e,t)}error(e,...t){this.write(n.Error,e,t)}write(e,t,i){if(s[e]<s[r])return;const o={level:e,message:t,args:i,namespace:this.namespace,timestamp:Date.now()};if(this.handler)return void this.handler(o);const a=this.namespace?`[${this.namespace}] ${t}`:t,{console:c}=globalThis;if(!c)return;const h=e===n.Debug&&"function"!=typeof c.debug?c.log:c[e];h?.(a,...i)}}const a=new o,c={apiUrl:"",accessToken:"",refreshToken:"",tenantId:""};let h={},d=!1;const l=new o({namespace:"EventEmitter"});class u{constructor(){this.listeners=new Map}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.off(e,t)}}once(e,t){const n=s=>{this.off(e,n),t(s)};return this.on(e,n)}off(e,t){const n=this.listeners.get(e);n&&(n.delete(t),0===n.size&&this.listeners.delete(e))}emit(e,t){const n=this.listeners.get(e);if(!n||0===n.size)return!1;for(const s of Array.from(n))try{s(t)}catch(t){l.error(`listener for event "${String(e)}" threw:`,t)}return!0}clear(e){void 0!==e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){return void 0!==e?this.listeners.get(e)?.size??0:Array.from(this.listeners.values()).reduce((e,t)=>e+t.size,0)}}const f=new u,p=new o({namespace:"HttpClient"});const g=new o({namespace:"MessageClient"}),k={Idle:"idle",Connecting:"connecting",Connected:"connected",Reconnecting:"reconnecting",Closed:"closed",Error:"error",TokenExpired:"token-expired"};class b{constructor(e){if(this.client=null,this.state=k.Idle,this.handlers=new Map,this.subscribedTopics=new Set,this.tokenExpiredListeners=new Set,this.connectedListeners=new Set,this.connectSettlers=null,this.handleConnect=()=>{const e=this.state===k.Connected;if(this.state=k.Connected,this.resubscribeAll(),this.publishBirth(),!e)for(const e of Array.from(this.connectedListeners))try{e()}catch(e){g.error("onConnected listener execution failed:",e)}},this.handleReconnect=()=>{this.state=k.Reconnecting},this.handleClose=()=>{this.state!==k.Error&&this.state!==k.TokenExpired&&(this.state=k.Closed)},this.handleOffline=()=>{this.state===k.Connected&&(this.state=k.Reconnecting)},this.handleError=e=>{this.isTokenExpiredError(e)?this.markTokenExpired(e):(this.state=k.Error,g.error("mqtt error:",e))},this.handleMessage=(e,t)=>{const n=this.decodePayload(t);g.debug(`received message on topic "${e}"`,n);const s=this.handlers.get(e);if(s&&0!==s.size)for(const t of Array.from(s))try{t(n,e)}catch(t){g.error(`handler for topic "${e}" threw:`,t)}},this.options=e,e.topics&&e.topics.length>0)for(const t of e.topics)this.subscribedTopics.add(t);this.connect().catch(e=>{this.state!==k.Closed&&g.error("mqtt auto-connect failed:",e)})}getState(){return this.state}onTokenExpired(e){return this.tokenExpiredListeners.add(e),()=>{this.tokenExpiredListeners.delete(e)}}onConnected(e){return this.connectedListeners.add(e),()=>{this.connectedListeners.delete(e)}}setToken(e){e!==this.options.token&&(this.options.token=e,this.reconnectWithCurrentToken())}connect(){return this.state===k.Connected||this.state===k.Connecting||this.state===k.Reconnecting?Promise.resolve():(this.disposeClient(),this.state=k.Connecting,new Promise((e,n)=>{let s;try{s=t.connect(this.options.url,{clientId:`agent-sdk-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,username:this.options.username,password:this.options.token,keepalive:this.options.keepalive,will:this.options.will&&{topic:this.options.will.topic,payload:this.options.will.payload,qos:this.options.will.qos??1,retain:this.options.will.retain??!0}})}catch(e){return this.state=k.Error,void n(e)}this.client=s,this.connectSettlers={resolve:e,reject:n},s.on("connect",this.handleConnect),s.on("reconnect",this.handleReconnect),s.on("close",this.handleClose),s.on("offline",this.handleOffline),s.on("error",this.handleError),s.on("message",this.handleMessage);const r=()=>{o(),e()},i=e=>{o(),n(e)},o=()=>{this.connectSettlers=null,s.off("connect",r),s.off("error",i)};s.once("connect",r),s.once("error",i)}))}disconnect(){return new Promise(e=>{const t=this.client;if(!t)return this.reset(),void e();let n=!1;const s=()=>{n||(n=!0,clearTimeout(r),this.settlePendingConnect(new Error("Connection closed by agent")),this.reset(),e())},r=setTimeout(s,2e3);t.once("close",s);try{t.end(!0)}catch{s()}})}subscribe(e,t,n){t&&this.addListener(e,t);const s=this.client;s&&this.state===k.Connected&&s.subscribe(e,n??{qos:2},t=>{t&&g.error(`subscribe ${e} failed`,t)}),this.subscribedTopics.add(e)}unsubscribe(e){this.subscribedTopics.delete(e),this.handlers.delete(e);const t=this.client;t&&this.state===k.Connected&&t.unsubscribe(e)}send(e,t,n){const s=this.client;if(!s)throw new Error("send failed: not connected");const r=this.encodePayload(t);s.publish(e,r,n??{qos:2})}on(e,t){return this.addListener(e,t),()=>this.removeListener(e,t)}off(e,t){this.removeListener(e,t)}clear(e){void 0!==e?this.handlers.delete(e):this.handlers.clear()}addListener(e,t){let n=this.handlers.get(e);n||(n=new Set,this.handlers.set(e,n)),n.add(t)}removeListener(e,t){const n=this.handlers.get(e);n&&(n.delete(t),0===n.size&&this.handlers.delete(e))}reset(){this.state=k.Closed,this.client=null,this.connectSettlers=null,this.handlers.clear(),this.subscribedTopics.clear()}settlePendingConnect(e){const t=this.connectSettlers;this.connectSettlers=null,t?.reject(e)}disposeClient(){const e=this.client;if(e){this.client=null;try{e.removeAllListeners(),e.end(!0)}catch{}this.settlePendingConnect(new Error("Connection discarded (token updated or client rebuilt)"))}}reconnectWithCurrentToken(){this.disposeClient(),this.state=k.Idle,this.connect().catch(e=>{g.error("Connection reconnect with new token failed:",e)})}markTokenExpired(e){const t=this.state!==k.TokenExpired;if(this.settlePendingConnect(e??new Error("Connection token expired or invalid")),this.disposeClient(),this.state=k.TokenExpired,t){g.warn("mqtt token expired or invalid, auto-reconnect stopped",e?.message);for(const e of Array.from(this.tokenExpiredListeners))try{e()}catch(e){g.error("onTokenExpired listener execution failed:",e)}}}isTokenExpiredError(e){return/unexpected server response: 401|not authorized|unauthorized|bad user(name)? or password|authenticat(?:e|ion) fail|token (?:expired|invalid)/i.test(e?.message??"")}resubscribeAll(){const e=this.client;if(e&&this.state===k.Connected&&0!==this.subscribedTopics.size)for(const t of this.subscribedTopics)e.subscribe(t,{qos:2},e=>{e&&g.error(`subscribe ${t} failed`,e)})}encodePayload(e){return"string"==typeof e?e:JSON.stringify(e)}decodePayload(e){const t=new TextDecoder("utf-8").decode(e);try{return JSON.parse(t)}catch{return t}}publishBirth(){const e=this.options.birth,t=this.client;e&&t&&t.publish(e.topic,e.payload,{qos:e.qos??1,retain:e.retain??!0},t=>{t&&g.error(`publish birth to "${e.topic}" failed`,t)})}}return e.Config=class{constructor(){}static init(e){const{apiUrl:t,accessToken:n,refreshToken:s,tenantId:r,logLevel:o,phone:a}=e;void 0!==t&&(c.apiUrl=t),void 0!==n&&(c.accessToken=n),void 0!==s&&(c.refreshToken=s),void 0!==r&&(c.tenantId=r),o&&i(o),void 0!==a&&(h=a),d=!0}static isInitialized(){return d}static ensureInitialized(){if(!d)throw new Error("Config is not initialized. Please call Config.init() before using any module.")}static getGlobalConfig(){return c}static updateTokens(e){c.accessToken=e.accessToken,void 0!==e.refreshToken&&(c.refreshToken=e.refreshToken)}static getPhoneConfig(){return h}},e.Event=u,e.EventEmitter=u,e.HttpClient=class{constructor(e){this.refreshing=null,this.refreshFailed=!1,this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.token=e.token??"",this.refreshToken=e.refreshToken??"",this.tenantId=e.tenantId??""}setBaseUrl(e){this.baseUrl=e.replace(/\/+$/,"")}setToken(e){this.token=e,this.refreshFailed=!1}setRefreshToken(e){this.refreshToken=e,this.refreshFailed=!1}async checkIn(e="AVAILABLE"){const t=await this.request("/acc/acd/agent/check-in",{method:"POST",contentType:"json",body:{presence:e}});return!0!==t.data&&p.warn("checkIn returned abnormal:",t),t.data}async checkOut(){const e=await this.request("/acc/acd/agent/check-out",{method:"POST",contentType:"json"});return!0!==e.data&&p.warn("checkOut returned abnormal:",e),e.data}async heartbeat(e={}){const t=await this.request("/acc/acd/agent/heartbeat",{method:"POST",contentType:"form",body:e});return!0!==t.data&&p.warn("heartbeat returned abnormal:",t),t.data}async agentPresence(e,t){const n=await this.request("/acc/acd/agent/presence",{method:"PUT",contentType:"json",body:t?{presence:e,reason:t}:{presence:e}});return!0!==n.data&&p.warn("agentPresence returned abnormal:",n),n.data}async agentInfo(){const e=await this.request("/acc/acd/agent/self",{method:"GET",contentType:"form"});return e.data?e.data:(p.warn("agentInfo returned abnormal:",e),null)}async getMqttToken(){const e=await this.request("/infra/mqtt/token",{method:"POST",contentType:"json",body:{clientNo:"agent-sdk"}});return e.data?.token?e.data.token:(p.warn("getMqttToken returned abnormal:",e),"")}async doRefreshToken(e=this.refreshToken){return p.warn("doRefreshToken skipped: refresh token is disabled"),null}async tryRefreshToken(){return!1}async request(e,t,n=!0){const s={Authorization:`Bearer ${this.token}`,"Tenant-Id":String(this.tenantId),"Content-Type":"json"===t.contentType?"application/json;charset=UTF-8":"application/x-www-form-urlencoded;charset=UTF-8"};let r;t.body&&Object.keys(t.body).length>0&&(r="json"===t.contentType?JSON.stringify(t.body):new URLSearchParams(Object.entries(t.body).map(([e,t])=>[e,String(t)])).toString());const i=this.token,o=await fetch(`${this.baseUrl}${e}`,{method:t.method,headers:s,body:r});if(o.ok){const s=await o.json();return n&&401===s?.code&&(this.token!==i||await this.tryRefreshToken())?(p.info("Token expired, refreshing and retrying:",e),this.request(e,t,!1)):s}if(n&&401===o.status&&(this.token!==i||await this.tryRefreshToken()))return p.info("Token expired, refreshing and retrying:",e),this.request(e,t,!1);throw new Error(`HTTP ${o.status} ${o.statusText}`)}async download(e,t=!0){const n={Authorization:`Bearer ${this.token}`,"Tenant-Id":String(this.tenantId)},s=this.token,r=await fetch(`${this.baseUrl}${e}`,{method:"GET",headers:n});if(r.ok){if((r.headers.get("content-type")??"").includes("application/json")){const n=await r.json();if(t&&401===n.code&&(this.token!==s||await this.tryRefreshToken()))return p.info("Token expired, refreshing and retrying download:",e),this.download(e,!1);throw new Error(`下载失败:${n.msg||"未知错误"} (code=${n.code})`)}return r.blob()}if(t&&401===r.status&&(this.token!==s||await this.tryRefreshToken()))return p.info("Token expired, refreshing and retrying download:",e),this.download(e,!1);throw new Error(`HTTP ${r.status} ${r.statusText}`)}},e.Log=o,e.LogLevel=n,e.Logger=o,e.Message=b,e.MessageClient=b,e.MessageConnectionState=k,e.coreVersion="0.11.0",e.event=f,e.getGlobalLogLevel=function(){return r},e.log=a,e.setGlobalLogLevel=i,e}({},mqtt);
|
|
2
2
|
//# sourceMappingURL=index.global.min.js.map
|