joytalk 0.0.37 → 0.0.38
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.cjs.js +1 -1
- package/dist/index.es.js +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs.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,...n){const r=new this(t);return n.forEach(s=>r.set(s)),r}static accessor(t){const r=(this[Je]=this[Je]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=te(i);r[c]||(kn(s,i),r[c]=!0)}return a.isArray(t)?t.forEach(o):o(t),this}};D.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);a.reduceDescriptors(D.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});a.freezeMethods(D);function Ne(e,t){const n=this||oe,r=t||n,s=D.from(r.headers);let o=r.data;return a.forEach(e,function(c){o=c.call(n,o,s.normalize(),t?t.status:void 0)}),s.normalize(),o}function Rt(e){return!!(e&&e.__CANCEL__)}function Z(e,t,n){E.call(this,e??"canceled",E.ERR_CANCELED,t,n),this.name="CanceledError"}a.inherits(Z,E,{__CANCEL__:!0});function yt(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new E("Request failed with status code "+n.status,[E.ERR_BAD_REQUEST,E.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Hn(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function vn(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s=0,o=0,i;return t=t!==void 0?t:1e3,function(d){const u=Date.now(),l=r[o];i||(i=u),n[s]=d,r[s]=u;let h=o,S=0;for(;h!==s;)S+=n[h++],h=h%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),u-i<t)return;const w=l&&u-l;return w?Math.round(S*1e3/w):void 0}}function jn(e,t){let n=0,r=1e3/t,s,o;const i=(u,l=Date.now())=>{n=l,s=null,o&&(clearTimeout(o),o=null),e(...u)};return[(...u)=>{const l=Date.now(),h=l-n;h>=r?i(u,l):(s=u,o||(o=setTimeout(()=>{o=null,i(s)},r-h)))},()=>s&&i(s)]}const he=(e,t,n=3)=>{let r=0;const s=vn(50,250);return jn(o=>{const i=o.loaded,c=o.lengthComputable?o.total:void 0,d=i-r,u=s(d),l=i<=c;r=i;const h={loaded:i,total:c,progress:c?i/c:void 0,bytes:d,rate:u||void 0,estimated:u&&c&&l?(c-i)/u:void 0,event:o,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(h)},n)},We=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Ve=e=>(...t)=>a.asap(()=>e(...t)),Mn=g.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,g.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(g.origin),g.navigator&&/(msie|trident)/i.test(g.navigator.userAgent)):()=>!0,$n=g.hasStandardBrowserEnv?{write(e,t,n,r,s,o,i){if(typeof document>"u")return;const c=[`${e}=${encodeURIComponent(t)}`];a.isNumber(n)&&c.push(`expires=${new Date(n).toUTCString()}`),a.isString(r)&&c.push(`path=${r}`),a.isString(s)&&c.push(`domain=${s}`),o===!0&&c.push("secure"),a.isString(i)&&c.push(`SameSite=${i}`),document.cookie=c.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function qn(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Gn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function At(e,t,n){let r=!qn(t);return e&&(r||n==!1)?Gn(e,t):t}const Ke=e=>e instanceof D?{...e}:e;function V(e,t){t=t||{};const n={};function r(u,l,h,S){return a.isPlainObject(u)&&a.isPlainObject(l)?a.merge.call({caseless:S},u,l):a.isPlainObject(l)?a.merge({},l):a.isArray(l)?l.slice():l}function s(u,l,h,S){if(a.isUndefined(l)){if(!a.isUndefined(u))return r(void 0,u,h,S)}else return r(u,l,h,S)}function o(u,l){if(!a.isUndefined(l))return r(void 0,l)}function i(u,l){if(a.isUndefined(l)){if(!a.isUndefined(u))return r(void 0,u)}else return r(void 0,l)}function c(u,l,h){if(h in t)return r(u,l);if(h in e)return r(void 0,u)}const d={url:o,method:o,data:o,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:(u,l,h)=>s(Ke(u),Ke(l),h,!0)};return a.forEach(Object.keys({...e,...t}),function(l){const h=d[l]||s,S=h(e[l],t[l],l);a.isUndefined(S)&&h!==c||(n[l]=S)}),n}const bt=e=>{const t=V({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:c}=t;if(t.headers=i=D.from(i),t.url=St(At(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&i.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),a.isFormData(n)){if(g.hasStandardBrowserEnv||g.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(a.isFunction(n.getHeaders)){const d=n.getHeaders(),u=["content-type","content-length"];Object.entries(d).forEach(([l,h])=>{u.includes(l.toLowerCase())&&i.set(l,h)})}}if(g.hasStandardBrowserEnv&&(r&&a.isFunction(r)&&(r=r(t)),r||r!==!1&&Mn(t.url))){const d=s&&o&&$n.read(o);d&&i.set(s,d)}return t},zn=typeof XMLHttpRequest<"u",Jn=zn&&function(e){return new Promise(function(n,r){const s=bt(e);let o=s.data;const i=D.from(s.headers).normalize();let{responseType:c,onUploadProgress:d,onDownloadProgress:u}=s,l,h,S,w,f;function m(){w&&w(),f&&f(),s.cancelToken&&s.cancelToken.unsubscribe(l),s.signal&&s.signal.removeEventListener("abort",l)}let p=new XMLHttpRequest;p.open(s.method.toUpperCase(),s.url,!0),p.timeout=s.timeout;function R(){if(!p)return;const y=D.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),P={data:!c||c==="text"||c==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:y,config:e,request:p};yt(function(L){n(L),m()},function(L){r(L),m()},P),p=null}"onloadend"in p?p.onloadend=R:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(R)},p.onabort=function(){p&&(r(new E("Request aborted",E.ECONNABORTED,e,p)),p=null)},p.onerror=function(U){const P=U&&U.message?U.message:"Network Error",G=new E(P,E.ERR_NETWORK,e,p);G.event=U||null,r(G),p=null},p.ontimeout=function(){let U=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const P=s.transitional||Tt;s.timeoutErrorMessage&&(U=s.timeoutErrorMessage),r(new E(U,P.clarifyTimeoutError?E.ETIMEDOUT:E.ECONNABORTED,e,p)),p=null},o===void 0&&i.setContentType(null),"setRequestHeader"in p&&a.forEach(i.toJSON(),function(U,P){p.setRequestHeader(P,U)}),a.isUndefined(s.withCredentials)||(p.withCredentials=!!s.withCredentials),c&&c!=="json"&&(p.responseType=s.responseType),u&&([S,f]=he(u,!0),p.addEventListener("progress",S)),d&&p.upload&&([h,w]=he(d),p.upload.addEventListener("progress",h),p.upload.addEventListener("loadend",w)),(s.cancelToken||s.signal)&&(l=y=>{p&&(r(!y||y.type?new Z(null,e,p):y),p.abort(),p=null)},s.cancelToken&&s.cancelToken.subscribe(l),s.signal&&(s.signal.aborted?l():s.signal.addEventListener("abort",l)));const I=Hn(s.url);if(I&&g.protocols.indexOf(I)===-1){r(new E("Unsupported protocol "+I+":",E.ERR_BAD_REQUEST,e));return}p.send(o||null)})},Wn=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,s;const o=function(u){if(!s){s=!0,c();const l=u instanceof Error?u:this.reason;r.abort(l instanceof E?l:new Z(l instanceof Error?l.message:l))}};let i=t&&setTimeout(()=>{i=null,o(new E(`timeout ${t} of ms exceeded`,E.ETIMEDOUT))},t);const c=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(u=>{u.unsubscribe?u.unsubscribe(o):u.removeEventListener("abort",o)}),e=null)};e.forEach(u=>u.addEventListener("abort",o));const{signal:d}=r;return d.unsubscribe=()=>a.asap(c),d}},Vn=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,s;for(;r<n;)s=r+t,yield e.slice(r,s),r=s},Kn=async function*(e,t){for await(const n of Xn(e))yield*Vn(n,t)},Xn=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Xe=(e,t,n,r)=>{const s=Kn(e,t);let o=0,i,c=d=>{i||(i=!0,r&&r(d))};return new ReadableStream({async pull(d){try{const{done:u,value:l}=await s.next();if(u){c(),d.close();return}let h=l.byteLength;if(n){let S=o+=h;n(S)}d.enqueue(new Uint8Array(l))}catch(u){throw c(u),u}},cancel(d){return c(d),s.return()}},{highWaterMark:2})},Ye=64*1024,{isFunction:le}=a,Yn=(({Request:e,Response:t})=>({Request:e,Response:t}))(a.global),{ReadableStream:Qe,TextEncoder:Ze}=a.global,et=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Qn=e=>{e=a.merge.call({skipUndefined:!0},Yn,e);const{fetch:t,Request:n,Response:r}=e,s=t?le(t):typeof fetch=="function",o=le(n),i=le(r);if(!s)return!1;const c=s&&le(Qe),d=s&&(typeof Ze=="function"?(f=>m=>f.encode(m))(new Ze):async f=>new Uint8Array(await new n(f).arrayBuffer())),u=o&&c&&et(()=>{let f=!1;const m=new n(g.origin,{body:new Qe,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!m}),l=i&&c&&et(()=>a.isReadableStream(new r("").body)),h={stream:l&&(f=>f.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!h[f]&&(h[f]=(m,p)=>{let R=m&&m[f];if(R)return R.call(m);throw new E(`Response type '${f}' is not supported`,E.ERR_NOT_SUPPORT,p)})});const S=async f=>{if(f==null)return 0;if(a.isBlob(f))return f.size;if(a.isSpecCompliantForm(f))return(await new n(g.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(a.isArrayBufferView(f)||a.isArrayBuffer(f))return f.byteLength;if(a.isURLSearchParams(f)&&(f=f+""),a.isString(f))return(await d(f)).byteLength},w=async(f,m)=>{const p=a.toFiniteNumber(f.getContentLength());return p??S(m)};return async f=>{let{url:m,method:p,data:R,signal:I,cancelToken:y,timeout:U,onDownloadProgress:P,onUploadProgress:G,responseType:L,headers:ye,withCredentials:ie="same-origin",fetchOptions:Be}=bt(f),ke=t||fetch;L=L?(L+"").toLowerCase():"text";let ae=Wn([I,y&&y.toAbortSignal()],U),ee=null;const z=ae&&ae.unsubscribe&&(()=>{ae.unsubscribe()});let He;try{if(G&&u&&p!=="get"&&p!=="head"&&(He=await w(ye,R))!==0){let M=new n(m,{method:"POST",body:R,duplex:"half"}),K;if(a.isFormData(R)&&(K=M.headers.get("content-type"))&&ye.setContentType(K),M.body){const[Ae,ce]=We(He,he(Ve(G)));R=Xe(M.body,Ye,Ae,ce)}}a.isString(ie)||(ie=ie?"include":"omit");const B=o&&"credentials"in n.prototype,ve={...Be,signal:ae,method:p.toUpperCase(),headers:ye.normalize().toJSON(),body:R,duplex:"half",credentials:B?ie:void 0};ee=o&&new n(m,ve);let j=await(o?ke(ee,Be):ke(m,ve));const je=l&&(L==="stream"||L==="response");if(l&&(P||je&&z)){const M={};["status","statusText","headers"].forEach(Me=>{M[Me]=j[Me]});const K=a.toFiniteNumber(j.headers.get("content-length")),[Ae,ce]=P&&We(K,he(Ve(P),!0))||[];j=new r(Xe(j.body,Ye,Ae,()=>{ce&&ce(),z&&z()}),M)}L=L||"text";let _t=await h[a.findKey(h,L)||"text"](j,f);return!je&&z&&z(),await new Promise((M,K)=>{yt(M,K,{data:_t,headers:D.from(j.headers),status:j.status,statusText:j.statusText,config:f,request:ee})})}catch(B){throw z&&z(),B&&B.name==="TypeError"&&/Load failed|fetch/i.test(B.message)?Object.assign(new E("Network Error",E.ERR_NETWORK,f,ee),{cause:B.cause||B}):E.from(B,B&&B.code,f,ee)}}},Zn=new Map,Nt=e=>{let t=e&&e.env||{};const{fetch:n,Request:r,Response:s}=t,o=[r,s,n];let i=o.length,c=i,d,u,l=Zn;for(;c--;)d=o[c],u=l.get(d),u===void 0&&l.set(d,u=c?new Map:Qn(t)),l=u;return u};Nt();const Pe={http:En,xhr:Jn,fetch:{get:Nt}};a.forEach(Pe,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const tt=e=>`- ${e}`,er=e=>a.isFunction(e)||e===null||e===!1;function tr(e,t){e=a.isArray(e)?e:[e];const{length:n}=e;let r,s;const o={};for(let i=0;i<n;i++){r=e[i];let c;if(s=r,!er(r)&&(s=Pe[(c=String(r)).toLowerCase()],s===void 0))throw new E(`Unknown adapter '${c}'`);if(s&&(a.isFunction(s)||(s=s.get(t))))break;o[c||"#"+i]=s}if(!s){const i=Object.entries(o).map(([d,u])=>`adapter ${d} `+(u===!1?"is not supported by the environment":"is not available in the build"));let c=n?i.length>1?`since :
|
|
4
4
|
`+i.map(tt).join(`
|
|
5
5
|
`):" "+tt(i[0]):"as no adapter specified";throw new E("There is no suitable adapter to dispatch the request "+c,"ERR_NOT_SUPPORT")}return s}const Ot={getAdapter:tr,adapters:Pe};function Oe(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Z(null,e)}function nt(e){return Oe(e),e.headers=D.from(e.headers),e.data=Ne.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Ot.getAdapter(e.adapter||oe.adapter,e)(e).then(function(r){return Oe(e),r.data=Ne.call(e,e.transformResponse,r),r.headers=D.from(r.headers),r},function(r){return Rt(r)||(Oe(e),r&&r.response&&(r.response.data=Ne.call(e,e.transformResponse,r.response),r.response.headers=D.from(r.response.headers))),Promise.reject(r)})}const gt="1.13.2",Re={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Re[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const rt={};Re.transitional=function(t,n,r){function s(o,i){return"[Axios v"+gt+"] Transitional option '"+o+"'"+i+(r?". "+r:"")}return(o,i,c)=>{if(t===!1)throw new E(s(i," has been removed"+(n?" in "+n:"")),E.ERR_DEPRECATED);return n&&!rt[i]&&(rt[i]=!0,console.warn(s(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(o,i,c):!0}};Re.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function nr(e,t,n){if(typeof e!="object")throw new E("options must be an object",E.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const o=r[s],i=t[o];if(i){const c=e[o],d=c===void 0||i(c,o,e);if(d!==!0)throw new E("option "+o+" must be "+d,E.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new E("Unknown option "+o,E.ERR_BAD_OPTION)}}const de={assertOptions:nr,validators:Re},k=de.validators;let W=class{constructor(t){this.defaults=t||{},this.interceptors={request:new ze,response:new ze}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=`
|
|
6
|
-
`+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=V(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&de.assertOptions(r,{silentJSONParsing:k.transitional(k.boolean),forcedJSONParsing:k.transitional(k.boolean),clarifyTimeoutError:k.transitional(k.boolean)},!1),s!=null&&(a.isFunction(s)?n.paramsSerializer={serialize:s}:de.assertOptions(s,{encode:k.function,serialize:k.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),de.assertOptions(n,{baseUrl:k.spelling("baseURL"),withXsrfToken:k.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=o&&a.merge(o.common,o[n.method]);o&&a.forEach(["delete","get","head","post","put","patch","common"],f=>{delete o[f]}),n.headers=D.concat(i,o);const c=[];let d=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(d=d&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const u=[];this.interceptors.response.forEach(function(m){u.push(m.fulfilled,m.rejected)});let l,h=0,S;if(!d){const f=[nt.bind(this),void 0];for(f.unshift(...c),f.push(...u),S=f.length,l=Promise.resolve(n);h<S;)l=l.then(f[h++],f[h++]);return l}S=c.length;let w=n;for(;h<S;){const f=c[h++],m=c[h++];try{w=f(w)}catch(p){m.call(this,p);break}}try{l=nt.call(this,w)}catch(f){return Promise.reject(f)}for(h=0,S=u.length;h<S;)l=l.then(u[h++],u[h++]);return l}getUri(t){t=V(this.defaults,t);const n=At(t.baseURL,t.url,t.allowAbsoluteUrls);return St(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){W.prototype[t]=function(n,r){return this.request(V(r||{},{method:t,url:n,data:(r||{}).data}))}});a.forEach(["post","put","patch"],function(t){function n(r){return function(o,i,c){return this.request(V(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}W.prototype[t]=n(),W.prototype[t+"Form"]=n(!0)});let rr=class Ct{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(o){n=o});const r=this;this.promise.then(s=>{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(c=>{r.subscribe(c),o=c}).then(s);return i.cancel=function(){r.unsubscribe(o)},i},t(function(o,i,c){r.reason||(r.reason=new Z(o,i,c),n(r.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 n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Ct(function(s){t=s}),cancel:t}}};function sr(e){return function(n){return e.apply(null,n)}}function or(e){return a.isObject(e)&&e.isAxiosError===!0}const _e={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,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(_e).forEach(([e,t])=>{_e[t]=e});function Ut(e){const t=new W(e),n=ot(W.prototype.request,t);return a.extend(n,W.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return Ut(V(e,s))},n}const T=Ut(oe);T.Axios=W;T.CanceledError=Z;T.CancelToken=rr;T.isCancel=Rt;T.VERSION=gt;T.toFormData=we;T.AxiosError=E;T.Cancel=T.CanceledError;T.all=function(t){return Promise.all(t)};T.spread=sr;T.isAxiosError=or;T.mergeConfig=V;T.AxiosHeaders=D;T.formToJSON=e=>wt(a.isHTMLForm(e)?new FormData(e):e);T.getAdapter=Ot.getAdapter;T.HttpStatusCode=_e;T.default=T;const{Axios:Dr,AxiosError:Ir,CanceledError:Lr,isCancel:Fr,CancelToken:Pr,VERSION:xr,all:Br,Cancel:kr,isAxiosError:Hr,spread:vr,toFormData:jr,AxiosHeaders:Mr,HttpStatusCode:$r,formToJSON:qr,getAdapter:Gr,mergeConfig:zr}=T,b={UNINITIALIZED:{code:10001,msg:"未初始化"},DISCONNECTED:{code:10002,msg:"未连接"},NO_CUSTOMER_SERVICE:{code:10003,msg:"未分配客服"},MESSAGE_SEND_FAIL:{code:10004,msg:"消息发送失败"},DATA_PARSING_ERROR:{code:10005,msg:"数据解析异常"},FILE_NOT_EXIST:{code:10006,msg:"文件不存在"},FILE_PARSING_ERROR:{code:10007,msg:"文件解析异常"},AUTH_INFO_ERROR:{code:10008,msg:"授权信息错误"},FILE_UPLOAD_FAIL:{code:10009,msg:"文件上传失败"},PARAMETER_ERROR:{code:10010,msg:"参数异常"},EMPTY_DATA:{code:10011,msg:"数据为空"}},ir="/api/customer-service/customer/v1/CustomerService/TestLineLatency",ar="/api/customer-service/customer/v1/CustomerService/ListLines",cr="/pub/logo.png",De={development:{BASE_API_URL:"http://dev-joytalk-api.halaladmin.vip",OBS_URL:"http://dev-joytalk-img.halaladmin.vip"},prodtest:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img.halaladmin.vip"},production:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img.halaladmin.vip"}},F={api:"",download:"",ws:""};let X=null;function lr(e){const t=`${e.replace(/\/$/,"")}${ir}`;return T.get(t,{timeout:1e4}).then(n=>n.data?.code!==200?Promise.reject(n):e)}function ur(e){const t=`${e.replace(/\/$/,"")}${cr}`;return T.get(t,{timeout:1e4}).then(()=>e).catch(()=>Promise.reject(new Error("Download latency test failed")))}function fr(e){return e?.length?Promise.any(e.map(t=>lr(t))):Promise.reject(new Error("No urls to test"))}function dr(e){return e?.length?Promise.any(e.map(t=>ur(t))):Promise.reject(new Error("No download urls to test"))}async function xe(e,t){if(F.api&&F.download)return;if(X)return X;const n=De[t].BASE_API_URL||"",r=De[t].OBS_URL||"";F.api=n,F.download=r,F.ws=n.replace(/http/g,"ws"),n||(X=Promise.reject(new Error("环境配置错误")),await X),X=(async()=>{const s=await T.get(`${n.replace(/\/$/,"")}${ar}`,{headers:{Authorization:`Bearer ${e}`},timeout:15e3});if(s.data?.code!==200||!s.data?.data)return Promise.reject(s);const o=(s.data.data.api??[]).map(h=>h.url).filter(Boolean),i=(s.data.data.download??[]).map(h=>h.url).filter(Boolean),c=n,d=r,[u,l]=await Promise.all([o.length?fr(o).catch(()=>c):Promise.resolve(c),i.length?dr(i).catch(()=>d):Promise.resolve(d)]);F.api=u,F.download=l,F.ws=u.replace(/http/g,"ws")})(),await X}const q=T.create({timeout:6e5});q.interceptors.request.use(async e=>{const t=new $,n=t.config.token;return n?(e.headers.Authorization=`Bearer ${n}`,await xe(n,t.config.env),e.baseURL=F.api,e):Promise.reject(b.UNINITIALIZED)},e=>Promise.reject(e));q.interceptors.response.use(e=>e.data?.code!==200?Promise.reject(e):Promise.resolve(e.data),e=>Promise.reject(e));function hr(){return F.api}function pe(){return F.download}function pr(){return F.ws}const mr=e=>q.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),Er=async e=>{const t=pe();return T.post(`${t}`,e,{headers:{"Content-Type":"multipart/form-data"}})},Sr=async(e,t)=>T.put(t,e,{headers:{"Content-Type":"application/octet-stream"}}),Tr=e=>q.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),wr=e=>q.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),Rr=()=>q.get("/api/open-auth/user/v1/UserService/GetUserInfo"),yr=e=>q.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e),Ar=e=>{const n=new $().config.env,r=hr()||De[n].BASE_API_URL;return T.post(`${r}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,e)},br=e=>q.get("/api/chat/chat/v1/Chat/GetMsg",{params:e});var H=(e=>(e.SEND="1",e.WITHDRAW="2",e.EDIT="3",e.SYSTEM_NOTICE="4",e.TRANSFER="5",e.INBOUND="6",e.REPLY="7",e.UNBIND="8",e))(H||{}),v=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(v||{}),C=(e=>(e[e.CONNECT_SUCCESS=200]="CONNECT_SUCCESS",e[e.CONNECT_FAILED=40001]="CONNECT_FAILED",e[e.TRANSFER_CUSTOMER_SUCCESS=201]="TRANSFER_CUSTOMER_SUCCESS",e[e.TRANSFER_TO_CUSTOMER_SUCCESS=202]="TRANSFER_TO_CUSTOMER_SUCCESS",e[e.TRANSFER_USER_SUCCESS=203]="TRANSFER_USER_SUCCESS",e[e.TRANSFER_FAIL=50001]="TRANSFER_FAIL",e[e.MATCH_FAIL=50002]="MATCH_FAIL",e[e.MATCH_INFO=50005]="MATCH_INFO",e[e.MATCH_SUCCESS=50006]="MATCH_SUCCESS",e[e.RETRACT=204]="RETRACT",e[e.RETRACT_FAIL=50003]="RETRACT_FAIL",e[e.EDIT=205]="EDIT",e[e.EDIT_FAIL=50004]="EDIT_FAIL",e[e.COMMON_FAIL=5e4]="COMMON_FAIL",e[e.SEND_SUCCESS=206]="SEND_SUCCESS",e[e.SEND_CALLBACK=207]="SEND_CALLBACK",e[e.CHANGE_CHAT_STATUS=208]="CHANGE_CHAT_STATUS",e[e.REPLY_FAIL=50008]="REPLY_FAIL",e[e.REPLY_SUCCESS=209]="REPLY_SUCCESS",e[e.UNBIND_SUCCESS=60006]="UNBIND_SUCCESS",e[e.BAN_CUSTOMER=60007]="BAN_CUSTOMER",e[e.BAN_ENTRY=60008]="BAN_ENTRY",e[e.REMATCH=60001]="REMATCH",e))(C||{}),me=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(me||{}),A=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(A||{}),O=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(O||{}),N=(e=>(e.UNMATCHED="1",e.MATCHING="2",e.MATCHED="3",e.UNBIND="4",e))(N||{});class Nr{events=new Map;on(t,n){this.events.has(t)||this.events.set(t,[]),this.events.get(t).push(n)}off(t,n){const r=this.events.get(t);if(r){const s=r.indexOf(n);s>-1&&r.splice(s,1)}}emit(t,n){const r=this.events.get(t);r&&r.forEach(s=>{try{s(n)}catch(o){console.error(`事件回调执行错误 [${t}]:`,o)}})}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}once(t,n){const r=s=>{n(s),this.off(t,r)};this.on(t,r)}}async function Or(e,t){return await xe(e,t),`${await pr()}/api/ws?Authorization=${e}`}function gr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function Cr(e){return typeof e=="object"&&e!==null&&"data"in e&&"msgType"in e&&"toUid"in e&&"chatType"in e&&"code"in e}function st(e){const t=pe()+"/";return e.contentType!==v.TEXT&&(e.content=JSON.parse(e.content),e.content?.fileUrl?.startsWith("http")||(e.content.fileUrl=t+e.content.fileUrl),e.content?.thumbnailUrl?.startsWith("http")||(e.content.thumbnailUrl=t+e.content.thumbnailUrl)),e.replyType&&e.replyType!==v.TEXT&&typeof e.replyContent=="string"&&(e.replyContent=JSON.parse(e.replyContent),e.replyContent?.fileUrl?.startsWith("http")||(e.replyContent.fileUrl=t+e.replyContent.fileUrl),e.replyContent?.thumbnailUrl?.startsWith("http")||(e.replyContent.thumbnailUrl=t+e.replyContent.thumbnailUrl)),e}class $ extends Nr{config={token:"",autoReconnect:!0,reconnectInterval:3e3,maxReconnectAttempts:5,responseTimeout:15e3,env:"production"};ws=null;status=O.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;consultationTypeId="";sessionData=null;userInfo=null;static instance=null;matchStatus=N.UNMATCHED;constructor({env:t="production"}={}){if(super(),$.instance)return $.instance;$.instance=this,this.config.env=t}async init(t){if(!t.token)return Promise.reject(b.PARAMETER_ERROR);await xe(t.token,this.config.env),this.config=Object.assign(this.config,t)}connect(t){return this.consultationTypeId=t,new Promise(async(n,r)=>{if(!this.config.token)return r(b.UNINITIALIZED);if(this.status===O.CONNECTED)return n();if(this.status!==O.CONNECTING){this.setStatus(O.CONNECTING);try{const s=await Or(this.config.token,this.config.env);this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(O.CONNECTED),this.emit(A.CONNECTED),n()},this.ws.onmessage=o=>{try{this.handleMessage(o.data)}catch(i){throw console.error("解析消息失败:",i),b.DATA_PARSING_ERROR}},this.ws.onerror=o=>{console.error("连接错误:",o),this.setStatus(O.ERROR),this.emit(A.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(O.DISCONNECTED),this.emit(A.DISCONNECTED),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(O.ERROR),this.emit(A.ERROR,s),r(s)}}})}disconnect(){this.config.autoReconnect=!1,this.sessionData=null,this.matchStatus=N.UNMATCHED,this.clearReconnectTimer(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus(O.DISCONNECTED)}async sendMessage(t,n,r=H.SEND){const s={msgType:r,data:t,toUid:this.sessionData?.cid,chatType:n,editId:void 0};if(this.status!==O.CONNECTED||!this.ws)if(this.ws&&this.status===O.DISCONNECTED){console.log("连接断开,尝试重新连接");try{await this.connect(this.consultationTypeId)}catch(o){throw console.error("重连失败:",o),b.DISCONNECTED}}else throw console.error(b.DISCONNECTED),b.DISCONNECTED;try{if(!this.ws)throw b.DISCONNECTED;return r===H.SEND?new Promise(async(o,i)=>{const c=gr();s.ext=c;const d=await br({ext:c});d.data?.messageId?(this.ws.send(JSON.stringify(s)),o({messageId:d.data.messageId,data:t})):i(b.MESSAGE_SEND_FAIL)}):(this.ws.send(JSON.stringify(s)),{data:t})}catch(o){throw console.error("发送消息失败:",o),b.MESSAGE_SEND_FAIL}}async checkMatchStatus(){if(this.matchStatus===N.UNBIND&&(await this.sendMessage(this.consultationTypeId,void 0,H.INBOUND),await new Promise((t,n)=>{const r=setTimeout(()=>{clearTimeout(r),n(b.MESSAGE_SEND_FAIL)},this.config.responseTimeout);this.once(A.MESSAGE,s=>{s.code===C.REMATCH&&(clearTimeout(r),t(!0))})})),this.matchStatus!==N.MATCHED)throw console.error(b.NO_CUSTOMER_SERVICE),b.NO_CUSTOMER_SERVICE}async sendText(t){return await this.checkMatchStatus(),this.sendMessage(t,v.TEXT)}async sendFile({file:t,thumbnailFile:n,chatType:r}){try{await this.checkMatchStatus();const[s,o]=await Promise.all([this.handleUploadFile(t),n?this.handleUploadFile(n):Promise.resolve(void 0)]),i={fileName:t.name,fileUrl:s,thumbnailUrl:o,fileSize:t.size},{messageId:c}=await this.sendMessage(JSON.stringify(i),r),d=pe();return{messageId:c,content:{fileName:t.name,fileUrl:`${d}/${s}`,thumbnailUrl:o?`${d}/${o}`:void 0,fileSize:t.size}}}catch(s){throw console.error("上传文件失败:",s),s}}getStatus(){return this.status}isConnected(){return this.status===O.CONNECTED}handleMessage(t){if(t==="ping"){this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.sendHeartbeat();return}if(t=JSON.parse(t),!!Cr(t))try{const n=t.data?JSON.parse(t.data):t.data;switch(t.data=n,t.code){case C.CONNECT_SUCCESS:this.matchStatus===N.MATCHED||this.matchStatus===N.MATCHING?this.matchStatus=N.UNBIND:this.matchStatus=N.MATCHING,this.sendMessage(this.consultationTypeId,void 0,H.INBOUND);break;case C.MATCH_INFO:case C.MATCH_SUCCESS:if(this.matchStatus===N.MATCHED)return;this.sessionData=t.data,this.matchStatus===N.UNBIND?(this.matchStatus=N.MATCHED,this.emit(A.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=N.MATCHED,this.getFaqList(),this.emit(A.MESSAGE,t));break;case C.TRANSFER_USER_SUCCESS:if(n.oldSessionId!==this.sessionData?.sessionId)return;const r=t.data;this.sessionData={...this.sessionData,cid:String(r.cid),customerAvatar:r.customerAvatar,customerName:r.customerName,groupId:r.groupId,sessionId:r.sessionId},this.emit(A.MESSAGE,t);break;case C.SEND_SUCCESS:case C.EDIT:case C.REPLY_SUCCESS:const s=t.data;if(s.sessionId!==this.sessionData?.sessionId)return;st(s),this.emit(A.MESSAGE,t);break;case C.SEND_CALLBACK:const o=t.ext,c=t.data.messageId;this.emit(o,c);break;case C.UNBIND_SUCCESS:if(n.sessionId!==this.sessionData?.sessionId)return;this.matchStatus=N.UNBIND,this.sessionData=null,this.emit(A.MESSAGE,t);break;default:this.emit(A.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}setStatus(t){this.status!==t&&(this.status=t,this.emit(A.STATUS_CHANGE,t))}scheduleReconnect(){this.config.env==="development"&&console.warn(`第${this.reconnectAttempts+1}次安排重连`,new Date().toISOString()),this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(O.RECONNECTING),this.reconnectTimer=setTimeout(()=>{this.connect(this.consultationTypeId).catch(t=>{console.error("重连失败:",t)})},this.config.reconnectInterval)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}sendHeartbeat(){if(!(this.status!==O.CONNECTED||!this.ws))try{this.ws.send("pong"),this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer=setTimeout(()=>{Date.now()-this.lastHeartbeatTime>=this.config.responseTimeout&&(this.emit(A.HEARTBEAT_TIMEOUT),this.config.env==="development"&&console.warn("心跳超时,尝试重连",new Date().toISOString()),this.ws&&this.ws.close())},this.config.responseTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=50}){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const r=await yr({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>st(o));return{hasMore:r.data.hasMore,list:s}}async getConsultationList(t){return(await Tr({entranceId:t})).data}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await mr({ext:s||""}),{accessKeyId:i,signature:c,policy:d,key:u,maxLimit:l,url:h}=o.data;if(t.size>l*1024*1024)return r(`文件大小不能超过${l}MB`);if(h){const S=await Sr(t,h);S.status===200?n(`${u}`):r(S.data)}else{const S=new FormData;S.append("key",u),S.append("AccessKeyId",i),S.append("signature",c),S.append("policy",d),S.append("file",t);const w=await Er(S);w.status===204?n(`${u}`):r(w.data)}})}getVideoThumbnail=t=>new Promise((n,r)=>{const s=document.createElement("video"),o=document.createElement("canvas"),i=o.getContext("2d");if(!i){r(new Error("无法创建 canvas 上下文"));return}const c=URL.createObjectURL(t);s.preload="metadata",s.src=c,s.muted=!0,s.playsInline=!0,s.addEventListener("loadeddata",()=>{o.width=s.videoWidth,o.height=s.videoHeight,s.currentTime=0}),s.addEventListener("seeked",()=>{try{i.drawImage(s,0,0,o.width,o.height),o.toBlob(d=>{if(URL.revokeObjectURL(c),s.remove(),!d){r(b.FILE_PARSING_ERROR);return}const u=t.name.replace(/\.[^/.]+$/,"")+"_thumb.jpg",l=new File([d],u,{type:"image/jpeg",lastModified:Date.now()});n(l)},"image/jpeg",.6)}catch(d){URL.revokeObjectURL(c),s.remove(),r(d)}}),s.addEventListener("error",()=>{URL.revokeObjectURL(c),s.remove(),r(b.FILE_PARSING_ERROR)}),s.load()});async getFaqList(){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const t=await wr({id:this.sessionData?.cid});if(!t.data?.topic?.length)return;const n={guideText:t.data.guideText,list:t.data.topic.map(r=>({...r,question:r.question}))};setTimeout(()=>{const r={code:C.SEND_SUCCESS,data:{content:n,contentType:v.FAQ,sendUserType:me.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND},msgType:H.SEND,chatType:v.FAQ};this.emit(A.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={code:C.SEND_SUCCESS,data:{sendUserType:me.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND,contentType:v.FAQ,content:{}},msgType:H.SEND,chatType:v.FAQ};if(t.isMulti)n.data.content={list:t.item},this.emit(A.MESSAGE,n);else{const r=t.item?.[0]||t,s=pe();r.imageUrl=r.imageUrl?.map(o=>o?.startsWith("http")?o:`${s}/${o}`),n.data.content={answer:r},this.emit(A.MESSAGE,n)}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await Rr();return this.userInfo=t.data,this.userInfo}async anonymousLogin(t,n){return(await Ar({appKey:t,entranceId:n,userSource:"H5"})).data}}exports.ChatType=v;exports.ConnectionStatus=O;exports.EventType=A;exports.JoyTalk=$;exports.MatchStatus=N;exports.MessageCode=C;exports.MessageType=H;exports.SendUserType=me;exports.default=$;
|
|
6
|
+
`+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=V(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&de.assertOptions(r,{silentJSONParsing:k.transitional(k.boolean),forcedJSONParsing:k.transitional(k.boolean),clarifyTimeoutError:k.transitional(k.boolean)},!1),s!=null&&(a.isFunction(s)?n.paramsSerializer={serialize:s}:de.assertOptions(s,{encode:k.function,serialize:k.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),de.assertOptions(n,{baseUrl:k.spelling("baseURL"),withXsrfToken:k.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=o&&a.merge(o.common,o[n.method]);o&&a.forEach(["delete","get","head","post","put","patch","common"],f=>{delete o[f]}),n.headers=D.concat(i,o);const c=[];let d=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(d=d&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const u=[];this.interceptors.response.forEach(function(m){u.push(m.fulfilled,m.rejected)});let l,h=0,S;if(!d){const f=[nt.bind(this),void 0];for(f.unshift(...c),f.push(...u),S=f.length,l=Promise.resolve(n);h<S;)l=l.then(f[h++],f[h++]);return l}S=c.length;let w=n;for(;h<S;){const f=c[h++],m=c[h++];try{w=f(w)}catch(p){m.call(this,p);break}}try{l=nt.call(this,w)}catch(f){return Promise.reject(f)}for(h=0,S=u.length;h<S;)l=l.then(u[h++],u[h++]);return l}getUri(t){t=V(this.defaults,t);const n=At(t.baseURL,t.url,t.allowAbsoluteUrls);return St(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){W.prototype[t]=function(n,r){return this.request(V(r||{},{method:t,url:n,data:(r||{}).data}))}});a.forEach(["post","put","patch"],function(t){function n(r){return function(o,i,c){return this.request(V(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}W.prototype[t]=n(),W.prototype[t+"Form"]=n(!0)});let rr=class Ct{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(o){n=o});const r=this;this.promise.then(s=>{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(c=>{r.subscribe(c),o=c}).then(s);return i.cancel=function(){r.unsubscribe(o)},i},t(function(o,i,c){r.reason||(r.reason=new Z(o,i,c),n(r.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 n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Ct(function(s){t=s}),cancel:t}}};function sr(e){return function(n){return e.apply(null,n)}}function or(e){return a.isObject(e)&&e.isAxiosError===!0}const _e={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,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(_e).forEach(([e,t])=>{_e[t]=e});function Ut(e){const t=new W(e),n=ot(W.prototype.request,t);return a.extend(n,W.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return Ut(V(e,s))},n}const T=Ut(oe);T.Axios=W;T.CanceledError=Z;T.CancelToken=rr;T.isCancel=Rt;T.VERSION=gt;T.toFormData=we;T.AxiosError=E;T.Cancel=T.CanceledError;T.all=function(t){return Promise.all(t)};T.spread=sr;T.isAxiosError=or;T.mergeConfig=V;T.AxiosHeaders=D;T.formToJSON=e=>wt(a.isHTMLForm(e)?new FormData(e):e);T.getAdapter=Ot.getAdapter;T.HttpStatusCode=_e;T.default=T;const{Axios:Dr,AxiosError:Ir,CanceledError:Lr,isCancel:Fr,CancelToken:Pr,VERSION:xr,all:Br,Cancel:kr,isAxiosError:Hr,spread:vr,toFormData:jr,AxiosHeaders:Mr,HttpStatusCode:$r,formToJSON:qr,getAdapter:Gr,mergeConfig:zr}=T,b={UNINITIALIZED:{code:10001,msg:"未初始化"},DISCONNECTED:{code:10002,msg:"未连接"},NO_CUSTOMER_SERVICE:{code:10003,msg:"未分配客服"},MESSAGE_SEND_FAIL:{code:10004,msg:"消息发送失败"},DATA_PARSING_ERROR:{code:10005,msg:"数据解析异常"},FILE_NOT_EXIST:{code:10006,msg:"文件不存在"},FILE_PARSING_ERROR:{code:10007,msg:"文件解析异常"},AUTH_INFO_ERROR:{code:10008,msg:"授权信息错误"},FILE_UPLOAD_FAIL:{code:10009,msg:"文件上传失败"},PARAMETER_ERROR:{code:10010,msg:"参数异常"},EMPTY_DATA:{code:10011,msg:"数据为空"}},ir="/api/customer-service/customer/v1/CustomerService/TestLineLatency",ar="/api/customer-service/customer/v1/CustomerService/ListLines",cr="/pub/logo.png",De={development:{BASE_API_URL:"http://dev-joytalk-api.halaladmin.vip",OBS_URL:"http://dev-joytalk-img.halaladmin.vip"},prodtest:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img.halaladmin.vip"},production:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img.halaladmin.vip"}},F={api:"",download:"",ws:""};let X=null;function lr(e){const t=`${e.replace(/\/$/,"")}${ir}`;return T.get(t,{timeout:1e4}).then(n=>n.data?.code!==200?Promise.reject(n):e)}function ur(e){const t=`${e.replace(/\/$/,"")}${cr}`;return T.get(t,{timeout:1e4}).then(()=>e).catch(()=>Promise.reject(new Error("Download latency test failed")))}function fr(e){return e?.length?Promise.any(e.map(t=>lr(t))):Promise.reject(new Error("No urls to test"))}function dr(e){return e?.length?Promise.any(e.map(t=>ur(t))):Promise.reject(new Error("No download urls to test"))}async function xe(e,t){if(F.api&&F.download)return;if(X)return X;const n=De[t].BASE_API_URL||"",r=De[t].OBS_URL||"";F.api=n,F.download=r,F.ws=n.replace(/http/g,"ws"),n||(X=Promise.reject(new Error("环境配置错误")),await X),X=(async()=>{const s=await T.get(`${n.replace(/\/$/,"")}${ar}`,{headers:{Authorization:`Bearer ${e}`},timeout:15e3});if(s.data?.code!==200||!s.data?.data)return Promise.reject(s);const o=(s.data.data.api??[]).map(h=>h.url).filter(Boolean),i=(s.data.data.download??[]).map(h=>h.url).filter(Boolean),c=n,d=r,[u,l]=await Promise.all([o.length?fr(o).catch(()=>c):Promise.resolve(c),i.length?dr(i).catch(()=>d):Promise.resolve(d)]);F.api=u,F.download=l,F.ws=u.replace(/http/g,"ws")})(),await X}const q=T.create({timeout:6e5});q.interceptors.request.use(async e=>{const t=new $,n=t.config.token;return n?(e.headers.Authorization=`Bearer ${n}`,await xe(n,t.config.env),e.baseURL=F.api,e):Promise.reject(b.UNINITIALIZED)},e=>Promise.reject(e));q.interceptors.response.use(e=>e.data?.code!==200?Promise.reject(e):Promise.resolve(e.data),e=>Promise.reject(e));function hr(){return F.api}function pe(){return F.download}function pr(){return F.ws}const mr=e=>q.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),Er=async e=>{const t=pe();return T.post(`${t}`,e,{headers:{"Content-Type":"multipart/form-data"}})},Sr=async(e,t)=>T.put(t,e,{headers:{"Content-Type":e.type}}),Tr=e=>q.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),wr=e=>q.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),Rr=()=>q.get("/api/open-auth/user/v1/UserService/GetUserInfo"),yr=e=>q.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e),Ar=e=>{const n=new $().config.env,r=hr()||De[n].BASE_API_URL;return T.post(`${r}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,e)},br=e=>q.get("/api/chat/chat/v1/Chat/GetMsg",{params:e});var H=(e=>(e.SEND="1",e.WITHDRAW="2",e.EDIT="3",e.SYSTEM_NOTICE="4",e.TRANSFER="5",e.INBOUND="6",e.REPLY="7",e.UNBIND="8",e))(H||{}),v=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(v||{}),C=(e=>(e[e.CONNECT_SUCCESS=200]="CONNECT_SUCCESS",e[e.CONNECT_FAILED=40001]="CONNECT_FAILED",e[e.TRANSFER_CUSTOMER_SUCCESS=201]="TRANSFER_CUSTOMER_SUCCESS",e[e.TRANSFER_TO_CUSTOMER_SUCCESS=202]="TRANSFER_TO_CUSTOMER_SUCCESS",e[e.TRANSFER_USER_SUCCESS=203]="TRANSFER_USER_SUCCESS",e[e.TRANSFER_FAIL=50001]="TRANSFER_FAIL",e[e.MATCH_FAIL=50002]="MATCH_FAIL",e[e.MATCH_INFO=50005]="MATCH_INFO",e[e.MATCH_SUCCESS=50006]="MATCH_SUCCESS",e[e.RETRACT=204]="RETRACT",e[e.RETRACT_FAIL=50003]="RETRACT_FAIL",e[e.EDIT=205]="EDIT",e[e.EDIT_FAIL=50004]="EDIT_FAIL",e[e.COMMON_FAIL=5e4]="COMMON_FAIL",e[e.SEND_SUCCESS=206]="SEND_SUCCESS",e[e.SEND_CALLBACK=207]="SEND_CALLBACK",e[e.CHANGE_CHAT_STATUS=208]="CHANGE_CHAT_STATUS",e[e.REPLY_FAIL=50008]="REPLY_FAIL",e[e.REPLY_SUCCESS=209]="REPLY_SUCCESS",e[e.UNBIND_SUCCESS=60006]="UNBIND_SUCCESS",e[e.BAN_CUSTOMER=60007]="BAN_CUSTOMER",e[e.BAN_ENTRY=60008]="BAN_ENTRY",e[e.REMATCH=60001]="REMATCH",e))(C||{}),me=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(me||{}),A=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(A||{}),O=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(O||{}),N=(e=>(e.UNMATCHED="1",e.MATCHING="2",e.MATCHED="3",e.UNBIND="4",e))(N||{});class Nr{events=new Map;on(t,n){this.events.has(t)||this.events.set(t,[]),this.events.get(t).push(n)}off(t,n){const r=this.events.get(t);if(r){const s=r.indexOf(n);s>-1&&r.splice(s,1)}}emit(t,n){const r=this.events.get(t);r&&r.forEach(s=>{try{s(n)}catch(o){console.error(`事件回调执行错误 [${t}]:`,o)}})}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}once(t,n){const r=s=>{n(s),this.off(t,r)};this.on(t,r)}}async function Or(e,t){return await xe(e,t),`${await pr()}/api/ws?Authorization=${e}`}function gr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function Cr(e){return typeof e=="object"&&e!==null&&"data"in e&&"msgType"in e&&"toUid"in e&&"chatType"in e&&"code"in e}function st(e){const t=pe()+"/";return e.contentType!==v.TEXT&&(e.content=JSON.parse(e.content),e.content?.fileUrl?.startsWith("http")||(e.content.fileUrl=t+e.content.fileUrl),e.content?.thumbnailUrl?.startsWith("http")||(e.content.thumbnailUrl=t+e.content.thumbnailUrl)),e.replyType&&e.replyType!==v.TEXT&&typeof e.replyContent=="string"&&(e.replyContent=JSON.parse(e.replyContent),e.replyContent?.fileUrl?.startsWith("http")||(e.replyContent.fileUrl=t+e.replyContent.fileUrl),e.replyContent?.thumbnailUrl?.startsWith("http")||(e.replyContent.thumbnailUrl=t+e.replyContent.thumbnailUrl)),e}class $ extends Nr{config={token:"",autoReconnect:!0,reconnectInterval:3e3,maxReconnectAttempts:5,responseTimeout:15e3,env:"production"};ws=null;status=O.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;consultationTypeId="";sessionData=null;userInfo=null;static instance=null;matchStatus=N.UNMATCHED;constructor({env:t="production"}={}){if(super(),$.instance)return $.instance;$.instance=this,this.config.env=t}async init(t){if(!t.token)return Promise.reject(b.PARAMETER_ERROR);await xe(t.token,this.config.env),this.config=Object.assign(this.config,t)}connect(t){return this.consultationTypeId=t,new Promise(async(n,r)=>{if(!this.config.token)return r(b.UNINITIALIZED);if(this.status===O.CONNECTED)return n();if(this.status!==O.CONNECTING){this.setStatus(O.CONNECTING);try{const s=await Or(this.config.token,this.config.env);this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(O.CONNECTED),this.emit(A.CONNECTED),n()},this.ws.onmessage=o=>{try{this.handleMessage(o.data)}catch(i){throw console.error("解析消息失败:",i),b.DATA_PARSING_ERROR}},this.ws.onerror=o=>{console.error("连接错误:",o),this.setStatus(O.ERROR),this.emit(A.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(O.DISCONNECTED),this.emit(A.DISCONNECTED),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(O.ERROR),this.emit(A.ERROR,s),r(s)}}})}disconnect(){this.config.autoReconnect=!1,this.sessionData=null,this.matchStatus=N.UNMATCHED,this.clearReconnectTimer(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus(O.DISCONNECTED)}async sendMessage(t,n,r=H.SEND){const s={msgType:r,data:t,toUid:this.sessionData?.cid,chatType:n,editId:void 0};if(this.status!==O.CONNECTED||!this.ws)if(this.ws&&this.status===O.DISCONNECTED){console.log("连接断开,尝试重新连接");try{await this.connect(this.consultationTypeId)}catch(o){throw console.error("重连失败:",o),b.DISCONNECTED}}else throw console.error(b.DISCONNECTED),b.DISCONNECTED;try{if(!this.ws)throw b.DISCONNECTED;return r===H.SEND?new Promise(async(o,i)=>{const c=gr();s.ext=c;const d=await br({ext:c});d.data?.messageId?(this.ws.send(JSON.stringify(s)),o({messageId:d.data.messageId,data:t})):i(b.MESSAGE_SEND_FAIL)}):(this.ws.send(JSON.stringify(s)),{data:t})}catch(o){throw console.error("发送消息失败:",o),b.MESSAGE_SEND_FAIL}}async checkMatchStatus(){if(this.matchStatus===N.UNBIND&&(await this.sendMessage(this.consultationTypeId,void 0,H.INBOUND),await new Promise((t,n)=>{const r=setTimeout(()=>{clearTimeout(r),n(b.MESSAGE_SEND_FAIL)},this.config.responseTimeout);this.once(A.MESSAGE,s=>{s.code===C.REMATCH&&(clearTimeout(r),t(!0))})})),this.matchStatus!==N.MATCHED)throw console.error(b.NO_CUSTOMER_SERVICE),b.NO_CUSTOMER_SERVICE}async sendText(t){return await this.checkMatchStatus(),this.sendMessage(t,v.TEXT)}async sendFile({file:t,thumbnailFile:n,chatType:r}){try{await this.checkMatchStatus();const[s,o]=await Promise.all([this.handleUploadFile(t),n?this.handleUploadFile(n):Promise.resolve(void 0)]),i={fileName:t.name,fileUrl:s,thumbnailUrl:o,fileSize:t.size},{messageId:c}=await this.sendMessage(JSON.stringify(i),r),d=pe();return{messageId:c,content:{fileName:t.name,fileUrl:`${d}/${s}`,thumbnailUrl:o?`${d}/${o}`:void 0,fileSize:t.size}}}catch(s){throw console.error("上传文件失败:",s),s}}getStatus(){return this.status}isConnected(){return this.status===O.CONNECTED}handleMessage(t){if(t==="ping"){this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.sendHeartbeat();return}if(t=JSON.parse(t),!!Cr(t))try{const n=t.data?JSON.parse(t.data):t.data;switch(t.data=n,t.code){case C.CONNECT_SUCCESS:this.matchStatus===N.MATCHED||this.matchStatus===N.MATCHING?this.matchStatus=N.UNBIND:this.matchStatus=N.MATCHING,this.sendMessage(this.consultationTypeId,void 0,H.INBOUND);break;case C.MATCH_INFO:case C.MATCH_SUCCESS:if(this.matchStatus===N.MATCHED)return;this.sessionData=t.data,this.matchStatus===N.UNBIND?(this.matchStatus=N.MATCHED,this.emit(A.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=N.MATCHED,this.getFaqList(),this.emit(A.MESSAGE,t));break;case C.TRANSFER_USER_SUCCESS:if(n.oldSessionId!==this.sessionData?.sessionId)return;const r=t.data;this.sessionData={...this.sessionData,cid:String(r.cid),customerAvatar:r.customerAvatar,customerName:r.customerName,groupId:r.groupId,sessionId:r.sessionId},this.emit(A.MESSAGE,t);break;case C.SEND_SUCCESS:case C.EDIT:case C.REPLY_SUCCESS:const s=t.data;if(s.sessionId!==this.sessionData?.sessionId)return;st(s),this.emit(A.MESSAGE,t);break;case C.SEND_CALLBACK:const o=t.ext,c=t.data.messageId;this.emit(o,c);break;case C.UNBIND_SUCCESS:if(n.sessionId!==this.sessionData?.sessionId)return;this.matchStatus=N.UNBIND,this.sessionData=null,this.emit(A.MESSAGE,t);break;default:this.emit(A.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}setStatus(t){this.status!==t&&(this.status=t,this.emit(A.STATUS_CHANGE,t))}scheduleReconnect(){this.config.env==="development"&&console.warn(`第${this.reconnectAttempts+1}次安排重连`,new Date().toISOString()),this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(O.RECONNECTING),this.reconnectTimer=setTimeout(()=>{this.connect(this.consultationTypeId).catch(t=>{console.error("重连失败:",t)})},this.config.reconnectInterval)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}sendHeartbeat(){if(!(this.status!==O.CONNECTED||!this.ws))try{this.ws.send("pong"),this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer=setTimeout(()=>{Date.now()-this.lastHeartbeatTime>=this.config.responseTimeout&&(this.emit(A.HEARTBEAT_TIMEOUT),this.config.env==="development"&&console.warn("心跳超时,尝试重连",new Date().toISOString()),this.ws&&this.ws.close())},this.config.responseTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=50}){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const r=await yr({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>st(o));return{hasMore:r.data.hasMore,list:s}}async getConsultationList(t){return(await Tr({entranceId:t})).data}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await mr({ext:s||""}),{accessKeyId:i,signature:c,policy:d,key:u,maxLimit:l,url:h}=o.data;if(t.size>l*1024*1024)return r(`文件大小不能超过${l}MB`);if(h){const S=await Sr(t,h);S.status===200?n(`${u}`):r(S.data)}else{const S=new FormData;S.append("key",u),S.append("AccessKeyId",i),S.append("signature",c),S.append("policy",d),S.append("file",t);const w=await Er(S);w.status===204?n(`${u}`):r(w.data)}})}getVideoThumbnail=t=>new Promise((n,r)=>{const s=document.createElement("video"),o=document.createElement("canvas"),i=o.getContext("2d");if(!i){r(new Error("无法创建 canvas 上下文"));return}const c=URL.createObjectURL(t);s.preload="metadata",s.src=c,s.muted=!0,s.playsInline=!0,s.addEventListener("loadeddata",()=>{o.width=s.videoWidth,o.height=s.videoHeight,s.currentTime=0}),s.addEventListener("seeked",()=>{try{i.drawImage(s,0,0,o.width,o.height),o.toBlob(d=>{if(URL.revokeObjectURL(c),s.remove(),!d){r(b.FILE_PARSING_ERROR);return}const u=t.name.replace(/\.[^/.]+$/,"")+"_thumb.jpg",l=new File([d],u,{type:"image/jpeg",lastModified:Date.now()});n(l)},"image/jpeg",.6)}catch(d){URL.revokeObjectURL(c),s.remove(),r(d)}}),s.addEventListener("error",()=>{URL.revokeObjectURL(c),s.remove(),r(b.FILE_PARSING_ERROR)}),s.load()});async getFaqList(){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const t=await wr({id:this.sessionData?.cid});if(!t.data?.topic?.length)return;const n={guideText:t.data.guideText,list:t.data.topic.map(r=>({...r,question:r.question}))};setTimeout(()=>{const r={code:C.SEND_SUCCESS,data:{content:n,contentType:v.FAQ,sendUserType:me.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND},msgType:H.SEND,chatType:v.FAQ};this.emit(A.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={code:C.SEND_SUCCESS,data:{sendUserType:me.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND,contentType:v.FAQ,content:{}},msgType:H.SEND,chatType:v.FAQ};if(t.isMulti)n.data.content={list:t.item},this.emit(A.MESSAGE,n);else{const r=t.item?.[0]||t,s=pe();r.imageUrl=r.imageUrl?.map(o=>o?.startsWith("http")?o:`${s}/${o}`),n.data.content={answer:r},this.emit(A.MESSAGE,n)}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await Rr();return this.userInfo=t.data,this.userInfo}async anonymousLogin(t,n){return(await Ar({appKey:t,entranceId:n,userSource:"H5"})).data}}exports.ChatType=v;exports.ConnectionStatus=O;exports.EventType=A;exports.JoyTalk=$;exports.MatchStatus=N;exports.MessageCode=C;exports.MessageType=H;exports.SendUserType=me;exports.default=$;
|
package/dist/index.es.js
CHANGED
|
@@ -1912,7 +1912,7 @@ const mr = (e) => $.post(
|
|
|
1912
1912
|
});
|
|
1913
1913
|
}, Sr = async (e, t) => T.put(t, e, {
|
|
1914
1914
|
headers: {
|
|
1915
|
-
"Content-Type":
|
|
1915
|
+
"Content-Type": e.type
|
|
1916
1916
|
}
|
|
1917
1917
|
}), Tr = (e) => $.post(
|
|
1918
1918
|
"/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",
|
package/dist/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,...n){const r=new this(t);return n.forEach(s=>r.set(s)),r}static accessor(t){const r=(this[nt]=this[nt]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=ie(i);r[c]||(Ln(s,i),r[c]=!0)}return a.isArray(t)?t.forEach(o):o(t),this}};D.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),a.reduceDescriptors(D.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),a.freezeMethods(D);function De(e,t){const n=this||oe,r=t||n,s=D.from(r.headers);let o=r.data;return a.forEach(e,function(c){o=c.call(n,o,s.normalize(),t?t.status:void 0)}),s.normalize(),o}function rt(e){return!!(e&&e.__CANCEL__)}function Z(e,t,n){E.call(this,e??"canceled",E.ERR_CANCELED,t,n),this.name="CanceledError"}a.inherits(Z,E,{__CANCEL__:!0});function st(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new E("Request failed with status code "+n.status,[E.ERR_BAD_REQUEST,E.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Fn(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pn(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s=0,o=0,i;return t=t!==void 0?t:1e3,function(d){const u=Date.now(),l=r[o];i||(i=u),n[s]=d,r[s]=u;let h=o,S=0;for(;h!==s;)S+=n[h++],h=h%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),u-i<t)return;const w=l&&u-l;return w?Math.round(S*1e3/w):void 0}}function xn(e,t){let n=0,r=1e3/t,s,o;const i=(u,l=Date.now())=>{n=l,s=null,o&&(clearTimeout(o),o=null),e(...u)};return[(...u)=>{const l=Date.now(),h=l-n;h>=r?i(u,l):(s=u,o||(o=setTimeout(()=>{o=null,i(s)},r-h)))},()=>s&&i(s)]}const pe=(e,t,n=3)=>{let r=0;const s=Pn(50,250);return xn(o=>{const i=o.loaded,c=o.lengthComputable?o.total:void 0,d=i-r,u=s(d),l=i<=c;r=i;const h={loaded:i,total:c,progress:c?i/c:void 0,bytes:d,rate:u||void 0,estimated:u&&c&&l?(c-i)/u:void 0,event:o,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(h)},n)},ot=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},it=e=>(...t)=>a.asap(()=>e(...t)),Bn=O.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,O.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(O.origin),O.navigator&&/(msie|trident)/i.test(O.navigator.userAgent)):()=>!0,kn=O.hasStandardBrowserEnv?{write(e,t,n,r,s,o,i){if(typeof document>"u")return;const c=[`${e}=${encodeURIComponent(t)}`];a.isNumber(n)&&c.push(`expires=${new Date(n).toUTCString()}`),a.isString(r)&&c.push(`path=${r}`),a.isString(s)&&c.push(`domain=${s}`),o===!0&&c.push("secure"),a.isString(i)&&c.push(`SameSite=${i}`),document.cookie=c.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function Hn(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function vn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function at(e,t,n){let r=!Hn(t);return e&&(r||n==!1)?vn(e,t):t}const ct=e=>e instanceof D?{...e}:e;function J(e,t){t=t||{};const n={};function r(u,l,h,S){return a.isPlainObject(u)&&a.isPlainObject(l)?a.merge.call({caseless:S},u,l):a.isPlainObject(l)?a.merge({},l):a.isArray(l)?l.slice():l}function s(u,l,h,S){if(a.isUndefined(l)){if(!a.isUndefined(u))return r(void 0,u,h,S)}else return r(u,l,h,S)}function o(u,l){if(!a.isUndefined(l))return r(void 0,l)}function i(u,l){if(a.isUndefined(l)){if(!a.isUndefined(u))return r(void 0,u)}else return r(void 0,l)}function c(u,l,h){if(h in t)return r(u,l);if(h in e)return r(void 0,u)}const d={url:o,method:o,data:o,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:(u,l,h)=>s(ct(u),ct(l),h,!0)};return a.forEach(Object.keys({...e,...t}),function(l){const h=d[l]||s,S=h(e[l],t[l],l);a.isUndefined(S)&&h!==c||(n[l]=S)}),n}const lt=e=>{const t=J({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:c}=t;if(t.headers=i=D.from(i),t.url=Qe(at(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&i.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),a.isFormData(n)){if(O.hasStandardBrowserEnv||O.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(a.isFunction(n.getHeaders)){const d=n.getHeaders(),u=["content-type","content-length"];Object.entries(d).forEach(([l,h])=>{u.includes(l.toLowerCase())&&i.set(l,h)})}}if(O.hasStandardBrowserEnv&&(r&&a.isFunction(r)&&(r=r(t)),r||r!==!1&&Bn(t.url))){const d=s&&o&&kn.read(o);d&&i.set(s,d)}return t},jn=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const s=lt(e);let o=s.data;const i=D.from(s.headers).normalize();let{responseType:c,onUploadProgress:d,onDownloadProgress:u}=s,l,h,S,w,f;function m(){w&&w(),f&&f(),s.cancelToken&&s.cancelToken.unsubscribe(l),s.signal&&s.signal.removeEventListener("abort",l)}let p=new XMLHttpRequest;p.open(s.method.toUpperCase(),s.url,!0),p.timeout=s.timeout;function R(){if(!p)return;const A=D.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),B={data:!c||c==="text"||c==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:A,config:e,request:p};st(function(P){n(P),m()},function(P){r(P),m()},B),p=null}"onloadend"in p?p.onloadend=R:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(R)},p.onabort=function(){p&&(r(new E("Request aborted",E.ECONNABORTED,e,p)),p=null)},p.onerror=function(I){const B=I&&I.message?I.message:"Network Error",V=new E(B,E.ERR_NETWORK,e,p);V.event=I||null,r(V),p=null},p.ontimeout=function(){let I=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const B=s.transitional||et;s.timeoutErrorMessage&&(I=s.timeoutErrorMessage),r(new E(I,B.clarifyTimeoutError?E.ETIMEDOUT:E.ECONNABORTED,e,p)),p=null},o===void 0&&i.setContentType(null),"setRequestHeader"in p&&a.forEach(i.toJSON(),function(I,B){p.setRequestHeader(B,I)}),a.isUndefined(s.withCredentials)||(p.withCredentials=!!s.withCredentials),c&&c!=="json"&&(p.responseType=s.responseType),u&&([S,f]=pe(u,!0),p.addEventListener("progress",S)),d&&p.upload&&([h,w]=pe(d),p.upload.addEventListener("progress",h),p.upload.addEventListener("loadend",w)),(s.cancelToken||s.signal)&&(l=A=>{p&&(r(!A||A.type?new Z(null,e,p):A),p.abort(),p=null)},s.cancelToken&&s.cancelToken.subscribe(l),s.signal&&(s.signal.aborted?l():s.signal.addEventListener("abort",l)));const F=Fn(s.url);if(F&&O.protocols.indexOf(F)===-1){r(new E("Unsupported protocol "+F+":",E.ERR_BAD_REQUEST,e));return}p.send(o||null)})},Mn=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,s;const o=function(u){if(!s){s=!0,c();const l=u instanceof Error?u:this.reason;r.abort(l instanceof E?l:new Z(l instanceof Error?l.message:l))}};let i=t&&setTimeout(()=>{i=null,o(new E(`timeout ${t} of ms exceeded`,E.ETIMEDOUT))},t);const c=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(u=>{u.unsubscribe?u.unsubscribe(o):u.removeEventListener("abort",o)}),e=null)};e.forEach(u=>u.addEventListener("abort",o));const{signal:d}=r;return d.unsubscribe=()=>a.asap(c),d}},$n=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,s;for(;r<n;)s=r+t,yield e.slice(r,s),r=s},qn=async function*(e,t){for await(const n of Gn(e))yield*$n(n,t)},Gn=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},ut=(e,t,n,r)=>{const s=qn(e,t);let o=0,i,c=d=>{i||(i=!0,r&&r(d))};return new ReadableStream({async pull(d){try{const{done:u,value:l}=await s.next();if(u){c(),d.close();return}let h=l.byteLength;if(n){let S=o+=h;n(S)}d.enqueue(new Uint8Array(l))}catch(u){throw c(u),u}},cancel(d){return c(d),s.return()}},{highWaterMark:2})},ft=64*1024,{isFunction:me}=a,zn=(({Request:e,Response:t})=>({Request:e,Response:t}))(a.global),{ReadableStream:dt,TextEncoder:ht}=a.global,pt=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Jn=e=>{e=a.merge.call({skipUndefined:!0},zn,e);const{fetch:t,Request:n,Response:r}=e,s=t?me(t):typeof fetch=="function",o=me(n),i=me(r);if(!s)return!1;const c=s&&me(dt),d=s&&(typeof ht=="function"?(f=>m=>f.encode(m))(new ht):async f=>new Uint8Array(await new n(f).arrayBuffer())),u=o&&c&&pt(()=>{let f=!1;const m=new n(O.origin,{body:new dt,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!m}),l=i&&c&&pt(()=>a.isReadableStream(new r("").body)),h={stream:l&&(f=>f.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!h[f]&&(h[f]=(m,p)=>{let R=m&&m[f];if(R)return R.call(m);throw new E(`Response type '${f}' is not supported`,E.ERR_NOT_SUPPORT,p)})});const S=async f=>{if(f==null)return 0;if(a.isBlob(f))return f.size;if(a.isSpecCompliantForm(f))return(await new n(O.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(a.isArrayBufferView(f)||a.isArrayBuffer(f))return f.byteLength;if(a.isURLSearchParams(f)&&(f=f+""),a.isString(f))return(await d(f)).byteLength},w=async(f,m)=>{const p=a.toFiniteNumber(f.getContentLength());return p??S(m)};return async f=>{let{url:m,method:p,data:R,signal:F,cancelToken:A,timeout:I,onDownloadProgress:B,onUploadProgress:V,responseType:P,headers:Be,withCredentials:Re="same-origin",fetchOptions:bt}=lt(f),Nt=t||fetch;P=P?(P+"").toLowerCase():"text";let ye=Mn([F,A&&A.toAbortSignal()],I),ae=null;const K=ye&&ye.unsubscribe&&(()=>{ye.unsubscribe()});let Ot;try{if(V&&u&&p!=="get"&&p!=="head"&&(Ot=await w(Be,R))!==0){let G=new n(m,{method:"POST",body:R,duplex:"half"}),te;if(a.isFormData(R)&&(te=G.headers.get("content-type"))&&Be.setContentType(te),G.body){const[ke,Ae]=ot(Ot,pe(it(V)));R=ut(G.body,ft,ke,Ae)}}a.isString(Re)||(Re=Re?"include":"omit");const v=o&&"credentials"in n.prototype,gt={...bt,signal:ye,method:p.toUpperCase(),headers:Be.normalize().toJSON(),body:R,duplex:"half",credentials:v?Re:void 0};ae=o&&new n(m,gt);let q=await(o?Nt(ae,bt):Nt(m,gt));const Ct=l&&(P==="stream"||P==="response");if(l&&(B||Ct&&K)){const G={};["status","statusText","headers"].forEach(Ut=>{G[Ut]=q[Ut]});const te=a.toFiniteNumber(q.headers.get("content-length")),[ke,Ae]=B&&ot(te,pe(it(B),!0))||[];q=new r(ut(q.body,ft,ke,()=>{Ae&&Ae(),K&&K()}),G)}P=P||"text";let Ar=await h[a.findKey(h,P)||"text"](q,f);return!Ct&&K&&K(),await new Promise((G,te)=>{st(G,te,{data:Ar,headers:D.from(q.headers),status:q.status,statusText:q.statusText,config:f,request:ae})})}catch(v){throw K&&K(),v&&v.name==="TypeError"&&/Load failed|fetch/i.test(v.message)?Object.assign(new E("Network Error",E.ERR_NETWORK,f,ae),{cause:v.cause||v}):E.from(v,v&&v.code,f,ae)}}},Wn=new Map,mt=e=>{let t=e&&e.env||{};const{fetch:n,Request:r,Response:s}=t,o=[r,s,n];let i=o.length,c=i,d,u,l=Wn;for(;c--;)d=o[c],u=l.get(d),u===void 0&&l.set(d,u=c?new Map:Jn(t)),l=u;return u};mt();const Ie={http:mn,xhr:jn,fetch:{get:mt}};a.forEach(Ie,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Et=e=>`- ${e}`,Vn=e=>a.isFunction(e)||e===null||e===!1;function Kn(e,t){e=a.isArray(e)?e:[e];const{length:n}=e;let r,s;const o={};for(let i=0;i<n;i++){r=e[i];let c;if(s=r,!Vn(r)&&(s=Ie[(c=String(r)).toLowerCase()],s===void 0))throw new E(`Unknown adapter '${c}'`);if(s&&(a.isFunction(s)||(s=s.get(t))))break;o[c||"#"+i]=s}if(!s){const i=Object.entries(o).map(([d,u])=>`adapter ${d} `+(u===!1?"is not supported by the environment":"is not available in the build"));let c=n?i.length>1?`since :
|
|
4
4
|
`+i.map(Et).join(`
|
|
5
5
|
`):" "+Et(i[0]):"as no adapter specified";throw new E("There is no suitable adapter to dispatch the request "+c,"ERR_NOT_SUPPORT")}return s}const St={getAdapter:Kn,adapters:Ie};function Le(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Z(null,e)}function Tt(e){return Le(e),e.headers=D.from(e.headers),e.data=De.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),St.getAdapter(e.adapter||oe.adapter,e)(e).then(function(r){return Le(e),r.data=De.call(e,e.transformResponse,r),r.headers=D.from(r.headers),r},function(r){return rt(r)||(Le(e),r&&r.response&&(r.response.data=De.call(e,e.transformResponse,r.response),r.response.headers=D.from(r.response.headers))),Promise.reject(r)})}const wt="1.13.2",Ee={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Ee[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Rt={};Ee.transitional=function(t,n,r){function s(o,i){return"[Axios v"+wt+"] Transitional option '"+o+"'"+i+(r?". "+r:"")}return(o,i,c)=>{if(t===!1)throw new E(s(i," has been removed"+(n?" in "+n:"")),E.ERR_DEPRECATED);return n&&!Rt[i]&&(Rt[i]=!0,console.warn(s(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(o,i,c):!0}},Ee.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Xn(e,t,n){if(typeof e!="object")throw new E("options must be an object",E.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const o=r[s],i=t[o];if(i){const c=e[o],d=c===void 0||i(c,o,e);if(d!==!0)throw new E("option "+o+" must be "+d,E.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new E("Unknown option "+o,E.ERR_BAD_OPTION)}}const Se={assertOptions:Xn,validators:Ee},k=Se.validators;let W=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Ze,response:new Ze}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=`
|
|
6
|
-
`+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=J(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&Se.assertOptions(r,{silentJSONParsing:k.transitional(k.boolean),forcedJSONParsing:k.transitional(k.boolean),clarifyTimeoutError:k.transitional(k.boolean)},!1),s!=null&&(a.isFunction(s)?n.paramsSerializer={serialize:s}:Se.assertOptions(s,{encode:k.function,serialize:k.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Se.assertOptions(n,{baseUrl:k.spelling("baseURL"),withXsrfToken:k.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=o&&a.merge(o.common,o[n.method]);o&&a.forEach(["delete","get","head","post","put","patch","common"],f=>{delete o[f]}),n.headers=D.concat(i,o);const c=[];let d=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(d=d&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const u=[];this.interceptors.response.forEach(function(m){u.push(m.fulfilled,m.rejected)});let l,h=0,S;if(!d){const f=[Tt.bind(this),void 0];for(f.unshift(...c),f.push(...u),S=f.length,l=Promise.resolve(n);h<S;)l=l.then(f[h++],f[h++]);return l}S=c.length;let w=n;for(;h<S;){const f=c[h++],m=c[h++];try{w=f(w)}catch(p){m.call(this,p);break}}try{l=Tt.call(this,w)}catch(f){return Promise.reject(f)}for(h=0,S=u.length;h<S;)l=l.then(u[h++],u[h++]);return l}getUri(t){t=J(this.defaults,t);const n=at(t.baseURL,t.url,t.allowAbsoluteUrls);return Qe(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){W.prototype[t]=function(n,r){return this.request(J(r||{},{method:t,url:n,data:(r||{}).data}))}}),a.forEach(["post","put","patch"],function(t){function n(r){return function(o,i,c){return this.request(J(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}W.prototype[t]=n(),W.prototype[t+"Form"]=n(!0)});let Yn=class _t{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(o){n=o});const r=this;this.promise.then(s=>{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(c=>{r.subscribe(c),o=c}).then(s);return i.cancel=function(){r.unsubscribe(o)},i},t(function(o,i,c){r.reason||(r.reason=new Z(o,i,c),n(r.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 n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new _t(function(s){t=s}),cancel:t}}};function Qn(e){return function(n){return e.apply(null,n)}}function Zn(e){return a.isObject(e)&&e.isAxiosError===!0}const Fe={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,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Fe).forEach(([e,t])=>{Fe[t]=e});function yt(e){const t=new W(e),n=X(W.prototype.request,t);return a.extend(n,W.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return yt(J(e,s))},n}const T=yt(oe);T.Axios=W,T.CanceledError=Z,T.CancelToken=Yn,T.isCancel=rt,T.VERSION=wt,T.toFormData=de,T.AxiosError=E,T.Cancel=T.CanceledError,T.all=function(t){return Promise.all(t)},T.spread=Qn,T.isAxiosError=Zn,T.mergeConfig=J,T.AxiosHeaders=D,T.formToJSON=e=>tt(a.isHTMLForm(e)?new FormData(e):e),T.getAdapter=St.getAdapter,T.HttpStatusCode=Fe,T.default=T;const{Axios:_r,AxiosError:Dr,CanceledError:Ir,isCancel:Lr,CancelToken:Fr,VERSION:Pr,all:xr,Cancel:Br,isAxiosError:kr,spread:Hr,toFormData:vr,AxiosHeaders:jr,HttpStatusCode:Mr,formToJSON:$r,getAdapter:qr,mergeConfig:Gr}=T,b={UNINITIALIZED:{code:10001,msg:"未初始化"},DISCONNECTED:{code:10002,msg:"未连接"},NO_CUSTOMER_SERVICE:{code:10003,msg:"未分配客服"},MESSAGE_SEND_FAIL:{code:10004,msg:"消息发送失败"},DATA_PARSING_ERROR:{code:10005,msg:"数据解析异常"},FILE_NOT_EXIST:{code:10006,msg:"文件不存在"},FILE_PARSING_ERROR:{code:10007,msg:"文件解析异常"},AUTH_INFO_ERROR:{code:10008,msg:"授权信息错误"},FILE_UPLOAD_FAIL:{code:10009,msg:"文件上传失败"},PARAMETER_ERROR:{code:10010,msg:"参数异常"},EMPTY_DATA:{code:10011,msg:"数据为空"}},er="/api/customer-service/customer/v1/CustomerService/TestLineLatency",tr="/api/customer-service/customer/v1/CustomerService/ListLines",nr="/pub/logo.png",Pe={development:{BASE_API_URL:"http://dev-joytalk-api.halaladmin.vip",OBS_URL:"http://dev-joytalk-img.halaladmin.vip"},prodtest:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img.halaladmin.vip"},production:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img.halaladmin.vip"}},L={api:"",download:"",ws:""};let ee=null;function rr(e){const t=`${e.replace(/\/$/,"")}${er}`;return T.get(t,{timeout:1e4}).then(n=>n.data?.code!==200?Promise.reject(n):e)}function sr(e){const t=`${e.replace(/\/$/,"")}${nr}`;return T.get(t,{timeout:1e4}).then(()=>e).catch(()=>Promise.reject(new Error("Download latency test failed")))}function or(e){return e?.length?Promise.any(e.map(t=>rr(t))):Promise.reject(new Error("No urls to test"))}function ir(e){return e?.length?Promise.any(e.map(t=>sr(t))):Promise.reject(new Error("No download urls to test"))}async function xe(e,t){if(L.api&&L.download)return;if(ee)return ee;const n=Pe[t].BASE_API_URL||"",r=Pe[t].OBS_URL||"";L.api=n,L.download=r,L.ws=n.replace(/http/g,"ws"),n||(ee=Promise.reject(new Error("环境配置错误")),await ee),ee=(async()=>{const s=await T.get(`${n.replace(/\/$/,"")}${tr}`,{headers:{Authorization:`Bearer ${e}`},timeout:15e3});if(s.data?.code!==200||!s.data?.data)return Promise.reject(s);const o=(s.data.data.api??[]).map(h=>h.url).filter(Boolean),i=(s.data.data.download??[]).map(h=>h.url).filter(Boolean),c=n,d=r,[u,l]=await Promise.all([o.length?or(o).catch(()=>c):Promise.resolve(c),i.length?ir(i).catch(()=>d):Promise.resolve(d)]);L.api=u,L.download=l,L.ws=u.replace(/http/g,"ws")})(),await ee}const M=T.create({timeout:6e5});M.interceptors.request.use(async e=>{const t=new $,n=t.config.token;return n?(e.headers.Authorization=`Bearer ${n}`,await xe(n,t.config.env),e.baseURL=L.api,e):Promise.reject(b.UNINITIALIZED)},e=>Promise.reject(e)),M.interceptors.response.use(e=>e.data?.code!==200?Promise.reject(e):Promise.resolve(e.data),e=>Promise.reject(e));function ar(){return L.api}function Te(){return L.download}function cr(){return L.ws}const lr=e=>M.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),ur=async e=>{const t=Te();return T.post(`${t}`,e,{headers:{"Content-Type":"multipart/form-data"}})},fr=async(e,t)=>T.put(t,e,{headers:{"Content-Type":"application/octet-stream"}}),dr=e=>M.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),hr=e=>M.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),pr=()=>M.get("/api/open-auth/user/v1/UserService/GetUserInfo"),mr=e=>M.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e),Er=e=>{const n=new $().config.env,r=ar()||Pe[n].BASE_API_URL;return T.post(`${r}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,e)},Sr=e=>M.get("/api/chat/chat/v1/Chat/GetMsg",{params:e});var H=(e=>(e.SEND="1",e.WITHDRAW="2",e.EDIT="3",e.SYSTEM_NOTICE="4",e.TRANSFER="5",e.INBOUND="6",e.REPLY="7",e.UNBIND="8",e))(H||{}),j=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(j||{}),C=(e=>(e[e.CONNECT_SUCCESS=200]="CONNECT_SUCCESS",e[e.CONNECT_FAILED=40001]="CONNECT_FAILED",e[e.TRANSFER_CUSTOMER_SUCCESS=201]="TRANSFER_CUSTOMER_SUCCESS",e[e.TRANSFER_TO_CUSTOMER_SUCCESS=202]="TRANSFER_TO_CUSTOMER_SUCCESS",e[e.TRANSFER_USER_SUCCESS=203]="TRANSFER_USER_SUCCESS",e[e.TRANSFER_FAIL=50001]="TRANSFER_FAIL",e[e.MATCH_FAIL=50002]="MATCH_FAIL",e[e.MATCH_INFO=50005]="MATCH_INFO",e[e.MATCH_SUCCESS=50006]="MATCH_SUCCESS",e[e.RETRACT=204]="RETRACT",e[e.RETRACT_FAIL=50003]="RETRACT_FAIL",e[e.EDIT=205]="EDIT",e[e.EDIT_FAIL=50004]="EDIT_FAIL",e[e.COMMON_FAIL=5e4]="COMMON_FAIL",e[e.SEND_SUCCESS=206]="SEND_SUCCESS",e[e.SEND_CALLBACK=207]="SEND_CALLBACK",e[e.CHANGE_CHAT_STATUS=208]="CHANGE_CHAT_STATUS",e[e.REPLY_FAIL=50008]="REPLY_FAIL",e[e.REPLY_SUCCESS=209]="REPLY_SUCCESS",e[e.UNBIND_SUCCESS=60006]="UNBIND_SUCCESS",e[e.BAN_CUSTOMER=60007]="BAN_CUSTOMER",e[e.BAN_ENTRY=60008]="BAN_ENTRY",e[e.REMATCH=60001]="REMATCH",e))(C||{}),we=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(we||{}),y=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(y||{}),g=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(g||{}),N=(e=>(e.UNMATCHED="1",e.MATCHING="2",e.MATCHED="3",e.UNBIND="4",e))(N||{});class Tr{events=new Map;on(t,n){this.events.has(t)||this.events.set(t,[]),this.events.get(t).push(n)}off(t,n){const r=this.events.get(t);if(r){const s=r.indexOf(n);s>-1&&r.splice(s,1)}}emit(t,n){const r=this.events.get(t);r&&r.forEach(s=>{try{s(n)}catch(o){console.error(`事件回调执行错误 [${t}]:`,o)}})}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}once(t,n){const r=s=>{n(s),this.off(t,r)};this.on(t,r)}}async function wr(e,t){return await xe(e,t),`${await cr()}/api/ws?Authorization=${e}`}function Rr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function yr(e){return typeof e=="object"&&e!==null&&"data"in e&&"msgType"in e&&"toUid"in e&&"chatType"in e&&"code"in e}function At(e){const t=Te()+"/";return e.contentType!==j.TEXT&&(e.content=JSON.parse(e.content),e.content?.fileUrl?.startsWith("http")||(e.content.fileUrl=t+e.content.fileUrl),e.content?.thumbnailUrl?.startsWith("http")||(e.content.thumbnailUrl=t+e.content.thumbnailUrl)),e.replyType&&e.replyType!==j.TEXT&&typeof e.replyContent=="string"&&(e.replyContent=JSON.parse(e.replyContent),e.replyContent?.fileUrl?.startsWith("http")||(e.replyContent.fileUrl=t+e.replyContent.fileUrl),e.replyContent?.thumbnailUrl?.startsWith("http")||(e.replyContent.thumbnailUrl=t+e.replyContent.thumbnailUrl)),e}class $ extends Tr{config={token:"",autoReconnect:!0,reconnectInterval:3e3,maxReconnectAttempts:5,responseTimeout:15e3,env:"production"};ws=null;status=g.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;consultationTypeId="";sessionData=null;userInfo=null;static instance=null;matchStatus=N.UNMATCHED;constructor({env:t="production"}={}){if(super(),$.instance)return $.instance;$.instance=this,this.config.env=t}async init(t){if(!t.token)return Promise.reject(b.PARAMETER_ERROR);await xe(t.token,this.config.env),this.config=Object.assign(this.config,t)}connect(t){return this.consultationTypeId=t,new Promise(async(n,r)=>{if(!this.config.token)return r(b.UNINITIALIZED);if(this.status===g.CONNECTED)return n();if(this.status!==g.CONNECTING){this.setStatus(g.CONNECTING);try{const s=await wr(this.config.token,this.config.env);this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(g.CONNECTED),this.emit(y.CONNECTED),n()},this.ws.onmessage=o=>{try{this.handleMessage(o.data)}catch(i){throw console.error("解析消息失败:",i),b.DATA_PARSING_ERROR}},this.ws.onerror=o=>{console.error("连接错误:",o),this.setStatus(g.ERROR),this.emit(y.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(g.DISCONNECTED),this.emit(y.DISCONNECTED),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(g.ERROR),this.emit(y.ERROR,s),r(s)}}})}disconnect(){this.config.autoReconnect=!1,this.sessionData=null,this.matchStatus=N.UNMATCHED,this.clearReconnectTimer(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus(g.DISCONNECTED)}async sendMessage(t,n,r=H.SEND){const s={msgType:r,data:t,toUid:this.sessionData?.cid,chatType:n,editId:void 0};if(this.status!==g.CONNECTED||!this.ws)if(this.ws&&this.status===g.DISCONNECTED){console.log("连接断开,尝试重新连接");try{await this.connect(this.consultationTypeId)}catch(o){throw console.error("重连失败:",o),b.DISCONNECTED}}else throw console.error(b.DISCONNECTED),b.DISCONNECTED;try{if(!this.ws)throw b.DISCONNECTED;return r===H.SEND?new Promise(async(o,i)=>{const c=Rr();s.ext=c;const d=await Sr({ext:c});d.data?.messageId?(this.ws.send(JSON.stringify(s)),o({messageId:d.data.messageId,data:t})):i(b.MESSAGE_SEND_FAIL)}):(this.ws.send(JSON.stringify(s)),{data:t})}catch(o){throw console.error("发送消息失败:",o),b.MESSAGE_SEND_FAIL}}async checkMatchStatus(){if(this.matchStatus===N.UNBIND&&(await this.sendMessage(this.consultationTypeId,void 0,H.INBOUND),await new Promise((t,n)=>{const r=setTimeout(()=>{clearTimeout(r),n(b.MESSAGE_SEND_FAIL)},this.config.responseTimeout);this.once(y.MESSAGE,s=>{s.code===C.REMATCH&&(clearTimeout(r),t(!0))})})),this.matchStatus!==N.MATCHED)throw console.error(b.NO_CUSTOMER_SERVICE),b.NO_CUSTOMER_SERVICE}async sendText(t){return await this.checkMatchStatus(),this.sendMessage(t,j.TEXT)}async sendFile({file:t,thumbnailFile:n,chatType:r}){try{await this.checkMatchStatus();const[s,o]=await Promise.all([this.handleUploadFile(t),n?this.handleUploadFile(n):Promise.resolve(void 0)]),i={fileName:t.name,fileUrl:s,thumbnailUrl:o,fileSize:t.size},{messageId:c}=await this.sendMessage(JSON.stringify(i),r),d=Te();return{messageId:c,content:{fileName:t.name,fileUrl:`${d}/${s}`,thumbnailUrl:o?`${d}/${o}`:void 0,fileSize:t.size}}}catch(s){throw console.error("上传文件失败:",s),s}}getStatus(){return this.status}isConnected(){return this.status===g.CONNECTED}handleMessage(t){if(t==="ping"){this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.sendHeartbeat();return}if(t=JSON.parse(t),!!yr(t))try{const n=t.data?JSON.parse(t.data):t.data;switch(t.data=n,t.code){case C.CONNECT_SUCCESS:this.matchStatus===N.MATCHED||this.matchStatus===N.MATCHING?this.matchStatus=N.UNBIND:this.matchStatus=N.MATCHING,this.sendMessage(this.consultationTypeId,void 0,H.INBOUND);break;case C.MATCH_INFO:case C.MATCH_SUCCESS:if(this.matchStatus===N.MATCHED)return;this.sessionData=t.data,this.matchStatus===N.UNBIND?(this.matchStatus=N.MATCHED,this.emit(y.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=N.MATCHED,this.getFaqList(),this.emit(y.MESSAGE,t));break;case C.TRANSFER_USER_SUCCESS:if(n.oldSessionId!==this.sessionData?.sessionId)return;const r=t.data;this.sessionData={...this.sessionData,cid:String(r.cid),customerAvatar:r.customerAvatar,customerName:r.customerName,groupId:r.groupId,sessionId:r.sessionId},this.emit(y.MESSAGE,t);break;case C.SEND_SUCCESS:case C.EDIT:case C.REPLY_SUCCESS:const s=t.data;if(s.sessionId!==this.sessionData?.sessionId)return;At(s),this.emit(y.MESSAGE,t);break;case C.SEND_CALLBACK:const o=t.ext,c=t.data.messageId;this.emit(o,c);break;case C.UNBIND_SUCCESS:if(n.sessionId!==this.sessionData?.sessionId)return;this.matchStatus=N.UNBIND,this.sessionData=null,this.emit(y.MESSAGE,t);break;default:this.emit(y.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}setStatus(t){this.status!==t&&(this.status=t,this.emit(y.STATUS_CHANGE,t))}scheduleReconnect(){this.config.env==="development"&&console.warn(`第${this.reconnectAttempts+1}次安排重连`,new Date().toISOString()),this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(g.RECONNECTING),this.reconnectTimer=setTimeout(()=>{this.connect(this.consultationTypeId).catch(t=>{console.error("重连失败:",t)})},this.config.reconnectInterval)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}sendHeartbeat(){if(!(this.status!==g.CONNECTED||!this.ws))try{this.ws.send("pong"),this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer=setTimeout(()=>{Date.now()-this.lastHeartbeatTime>=this.config.responseTimeout&&(this.emit(y.HEARTBEAT_TIMEOUT),this.config.env==="development"&&console.warn("心跳超时,尝试重连",new Date().toISOString()),this.ws&&this.ws.close())},this.config.responseTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=50}){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const r=await mr({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>At(o));return{hasMore:r.data.hasMore,list:s}}async getConsultationList(t){return(await dr({entranceId:t})).data}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await lr({ext:s||""}),{accessKeyId:i,signature:c,policy:d,key:u,maxLimit:l,url:h}=o.data;if(t.size>l*1024*1024)return r(`文件大小不能超过${l}MB`);if(h){const S=await fr(t,h);S.status===200?n(`${u}`):r(S.data)}else{const S=new FormData;S.append("key",u),S.append("AccessKeyId",i),S.append("signature",c),S.append("policy",d),S.append("file",t);const w=await ur(S);w.status===204?n(`${u}`):r(w.data)}})}getVideoThumbnail=t=>new Promise((n,r)=>{const s=document.createElement("video"),o=document.createElement("canvas"),i=o.getContext("2d");if(!i){r(new Error("无法创建 canvas 上下文"));return}const c=URL.createObjectURL(t);s.preload="metadata",s.src=c,s.muted=!0,s.playsInline=!0,s.addEventListener("loadeddata",()=>{o.width=s.videoWidth,o.height=s.videoHeight,s.currentTime=0}),s.addEventListener("seeked",()=>{try{i.drawImage(s,0,0,o.width,o.height),o.toBlob(d=>{if(URL.revokeObjectURL(c),s.remove(),!d){r(b.FILE_PARSING_ERROR);return}const u=t.name.replace(/\.[^/.]+$/,"")+"_thumb.jpg",l=new File([d],u,{type:"image/jpeg",lastModified:Date.now()});n(l)},"image/jpeg",.6)}catch(d){URL.revokeObjectURL(c),s.remove(),r(d)}}),s.addEventListener("error",()=>{URL.revokeObjectURL(c),s.remove(),r(b.FILE_PARSING_ERROR)}),s.load()});async getFaqList(){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const t=await hr({id:this.sessionData?.cid});if(!t.data?.topic?.length)return;const n={guideText:t.data.guideText,list:t.data.topic.map(r=>({...r,question:r.question}))};setTimeout(()=>{const r={code:C.SEND_SUCCESS,data:{content:n,contentType:j.FAQ,sendUserType:we.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND},msgType:H.SEND,chatType:j.FAQ};this.emit(y.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={code:C.SEND_SUCCESS,data:{sendUserType:we.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND,contentType:j.FAQ,content:{}},msgType:H.SEND,chatType:j.FAQ};if(t.isMulti)n.data.content={list:t.item},this.emit(y.MESSAGE,n);else{const r=t.item?.[0]||t,s=Te();r.imageUrl=r.imageUrl?.map(o=>o?.startsWith("http")?o:`${s}/${o}`),n.data.content={answer:r},this.emit(y.MESSAGE,n)}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await pr();return this.userInfo=t.data,this.userInfo}async anonymousLogin(t,n){return(await Er({appKey:t,entranceId:n,userSource:"H5"})).data}}U.ChatType=j,U.ConnectionStatus=g,U.EventType=y,U.JoyTalk=$,U.MatchStatus=N,U.MessageCode=C,U.MessageType=H,U.SendUserType=we,U.default=$,Object.defineProperties(U,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
6
|
+
`+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=J(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&Se.assertOptions(r,{silentJSONParsing:k.transitional(k.boolean),forcedJSONParsing:k.transitional(k.boolean),clarifyTimeoutError:k.transitional(k.boolean)},!1),s!=null&&(a.isFunction(s)?n.paramsSerializer={serialize:s}:Se.assertOptions(s,{encode:k.function,serialize:k.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Se.assertOptions(n,{baseUrl:k.spelling("baseURL"),withXsrfToken:k.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=o&&a.merge(o.common,o[n.method]);o&&a.forEach(["delete","get","head","post","put","patch","common"],f=>{delete o[f]}),n.headers=D.concat(i,o);const c=[];let d=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(d=d&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const u=[];this.interceptors.response.forEach(function(m){u.push(m.fulfilled,m.rejected)});let l,h=0,S;if(!d){const f=[Tt.bind(this),void 0];for(f.unshift(...c),f.push(...u),S=f.length,l=Promise.resolve(n);h<S;)l=l.then(f[h++],f[h++]);return l}S=c.length;let w=n;for(;h<S;){const f=c[h++],m=c[h++];try{w=f(w)}catch(p){m.call(this,p);break}}try{l=Tt.call(this,w)}catch(f){return Promise.reject(f)}for(h=0,S=u.length;h<S;)l=l.then(u[h++],u[h++]);return l}getUri(t){t=J(this.defaults,t);const n=at(t.baseURL,t.url,t.allowAbsoluteUrls);return Qe(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){W.prototype[t]=function(n,r){return this.request(J(r||{},{method:t,url:n,data:(r||{}).data}))}}),a.forEach(["post","put","patch"],function(t){function n(r){return function(o,i,c){return this.request(J(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}W.prototype[t]=n(),W.prototype[t+"Form"]=n(!0)});let Yn=class _t{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(o){n=o});const r=this;this.promise.then(s=>{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(c=>{r.subscribe(c),o=c}).then(s);return i.cancel=function(){r.unsubscribe(o)},i},t(function(o,i,c){r.reason||(r.reason=new Z(o,i,c),n(r.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 n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new _t(function(s){t=s}),cancel:t}}};function Qn(e){return function(n){return e.apply(null,n)}}function Zn(e){return a.isObject(e)&&e.isAxiosError===!0}const Fe={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,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Fe).forEach(([e,t])=>{Fe[t]=e});function yt(e){const t=new W(e),n=X(W.prototype.request,t);return a.extend(n,W.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return yt(J(e,s))},n}const T=yt(oe);T.Axios=W,T.CanceledError=Z,T.CancelToken=Yn,T.isCancel=rt,T.VERSION=wt,T.toFormData=de,T.AxiosError=E,T.Cancel=T.CanceledError,T.all=function(t){return Promise.all(t)},T.spread=Qn,T.isAxiosError=Zn,T.mergeConfig=J,T.AxiosHeaders=D,T.formToJSON=e=>tt(a.isHTMLForm(e)?new FormData(e):e),T.getAdapter=St.getAdapter,T.HttpStatusCode=Fe,T.default=T;const{Axios:_r,AxiosError:Dr,CanceledError:Ir,isCancel:Lr,CancelToken:Fr,VERSION:Pr,all:xr,Cancel:Br,isAxiosError:kr,spread:Hr,toFormData:vr,AxiosHeaders:jr,HttpStatusCode:Mr,formToJSON:$r,getAdapter:qr,mergeConfig:Gr}=T,b={UNINITIALIZED:{code:10001,msg:"未初始化"},DISCONNECTED:{code:10002,msg:"未连接"},NO_CUSTOMER_SERVICE:{code:10003,msg:"未分配客服"},MESSAGE_SEND_FAIL:{code:10004,msg:"消息发送失败"},DATA_PARSING_ERROR:{code:10005,msg:"数据解析异常"},FILE_NOT_EXIST:{code:10006,msg:"文件不存在"},FILE_PARSING_ERROR:{code:10007,msg:"文件解析异常"},AUTH_INFO_ERROR:{code:10008,msg:"授权信息错误"},FILE_UPLOAD_FAIL:{code:10009,msg:"文件上传失败"},PARAMETER_ERROR:{code:10010,msg:"参数异常"},EMPTY_DATA:{code:10011,msg:"数据为空"}},er="/api/customer-service/customer/v1/CustomerService/TestLineLatency",tr="/api/customer-service/customer/v1/CustomerService/ListLines",nr="/pub/logo.png",Pe={development:{BASE_API_URL:"http://dev-joytalk-api.halaladmin.vip",OBS_URL:"http://dev-joytalk-img.halaladmin.vip"},prodtest:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img.halaladmin.vip"},production:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img.halaladmin.vip"}},L={api:"",download:"",ws:""};let ee=null;function rr(e){const t=`${e.replace(/\/$/,"")}${er}`;return T.get(t,{timeout:1e4}).then(n=>n.data?.code!==200?Promise.reject(n):e)}function sr(e){const t=`${e.replace(/\/$/,"")}${nr}`;return T.get(t,{timeout:1e4}).then(()=>e).catch(()=>Promise.reject(new Error("Download latency test failed")))}function or(e){return e?.length?Promise.any(e.map(t=>rr(t))):Promise.reject(new Error("No urls to test"))}function ir(e){return e?.length?Promise.any(e.map(t=>sr(t))):Promise.reject(new Error("No download urls to test"))}async function xe(e,t){if(L.api&&L.download)return;if(ee)return ee;const n=Pe[t].BASE_API_URL||"",r=Pe[t].OBS_URL||"";L.api=n,L.download=r,L.ws=n.replace(/http/g,"ws"),n||(ee=Promise.reject(new Error("环境配置错误")),await ee),ee=(async()=>{const s=await T.get(`${n.replace(/\/$/,"")}${tr}`,{headers:{Authorization:`Bearer ${e}`},timeout:15e3});if(s.data?.code!==200||!s.data?.data)return Promise.reject(s);const o=(s.data.data.api??[]).map(h=>h.url).filter(Boolean),i=(s.data.data.download??[]).map(h=>h.url).filter(Boolean),c=n,d=r,[u,l]=await Promise.all([o.length?or(o).catch(()=>c):Promise.resolve(c),i.length?ir(i).catch(()=>d):Promise.resolve(d)]);L.api=u,L.download=l,L.ws=u.replace(/http/g,"ws")})(),await ee}const M=T.create({timeout:6e5});M.interceptors.request.use(async e=>{const t=new $,n=t.config.token;return n?(e.headers.Authorization=`Bearer ${n}`,await xe(n,t.config.env),e.baseURL=L.api,e):Promise.reject(b.UNINITIALIZED)},e=>Promise.reject(e)),M.interceptors.response.use(e=>e.data?.code!==200?Promise.reject(e):Promise.resolve(e.data),e=>Promise.reject(e));function ar(){return L.api}function Te(){return L.download}function cr(){return L.ws}const lr=e=>M.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),ur=async e=>{const t=Te();return T.post(`${t}`,e,{headers:{"Content-Type":"multipart/form-data"}})},fr=async(e,t)=>T.put(t,e,{headers:{"Content-Type":e.type}}),dr=e=>M.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),hr=e=>M.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),pr=()=>M.get("/api/open-auth/user/v1/UserService/GetUserInfo"),mr=e=>M.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e),Er=e=>{const n=new $().config.env,r=ar()||Pe[n].BASE_API_URL;return T.post(`${r}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,e)},Sr=e=>M.get("/api/chat/chat/v1/Chat/GetMsg",{params:e});var H=(e=>(e.SEND="1",e.WITHDRAW="2",e.EDIT="3",e.SYSTEM_NOTICE="4",e.TRANSFER="5",e.INBOUND="6",e.REPLY="7",e.UNBIND="8",e))(H||{}),j=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(j||{}),C=(e=>(e[e.CONNECT_SUCCESS=200]="CONNECT_SUCCESS",e[e.CONNECT_FAILED=40001]="CONNECT_FAILED",e[e.TRANSFER_CUSTOMER_SUCCESS=201]="TRANSFER_CUSTOMER_SUCCESS",e[e.TRANSFER_TO_CUSTOMER_SUCCESS=202]="TRANSFER_TO_CUSTOMER_SUCCESS",e[e.TRANSFER_USER_SUCCESS=203]="TRANSFER_USER_SUCCESS",e[e.TRANSFER_FAIL=50001]="TRANSFER_FAIL",e[e.MATCH_FAIL=50002]="MATCH_FAIL",e[e.MATCH_INFO=50005]="MATCH_INFO",e[e.MATCH_SUCCESS=50006]="MATCH_SUCCESS",e[e.RETRACT=204]="RETRACT",e[e.RETRACT_FAIL=50003]="RETRACT_FAIL",e[e.EDIT=205]="EDIT",e[e.EDIT_FAIL=50004]="EDIT_FAIL",e[e.COMMON_FAIL=5e4]="COMMON_FAIL",e[e.SEND_SUCCESS=206]="SEND_SUCCESS",e[e.SEND_CALLBACK=207]="SEND_CALLBACK",e[e.CHANGE_CHAT_STATUS=208]="CHANGE_CHAT_STATUS",e[e.REPLY_FAIL=50008]="REPLY_FAIL",e[e.REPLY_SUCCESS=209]="REPLY_SUCCESS",e[e.UNBIND_SUCCESS=60006]="UNBIND_SUCCESS",e[e.BAN_CUSTOMER=60007]="BAN_CUSTOMER",e[e.BAN_ENTRY=60008]="BAN_ENTRY",e[e.REMATCH=60001]="REMATCH",e))(C||{}),we=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(we||{}),y=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(y||{}),g=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(g||{}),N=(e=>(e.UNMATCHED="1",e.MATCHING="2",e.MATCHED="3",e.UNBIND="4",e))(N||{});class Tr{events=new Map;on(t,n){this.events.has(t)||this.events.set(t,[]),this.events.get(t).push(n)}off(t,n){const r=this.events.get(t);if(r){const s=r.indexOf(n);s>-1&&r.splice(s,1)}}emit(t,n){const r=this.events.get(t);r&&r.forEach(s=>{try{s(n)}catch(o){console.error(`事件回调执行错误 [${t}]:`,o)}})}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}once(t,n){const r=s=>{n(s),this.off(t,r)};this.on(t,r)}}async function wr(e,t){return await xe(e,t),`${await cr()}/api/ws?Authorization=${e}`}function Rr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function yr(e){return typeof e=="object"&&e!==null&&"data"in e&&"msgType"in e&&"toUid"in e&&"chatType"in e&&"code"in e}function At(e){const t=Te()+"/";return e.contentType!==j.TEXT&&(e.content=JSON.parse(e.content),e.content?.fileUrl?.startsWith("http")||(e.content.fileUrl=t+e.content.fileUrl),e.content?.thumbnailUrl?.startsWith("http")||(e.content.thumbnailUrl=t+e.content.thumbnailUrl)),e.replyType&&e.replyType!==j.TEXT&&typeof e.replyContent=="string"&&(e.replyContent=JSON.parse(e.replyContent),e.replyContent?.fileUrl?.startsWith("http")||(e.replyContent.fileUrl=t+e.replyContent.fileUrl),e.replyContent?.thumbnailUrl?.startsWith("http")||(e.replyContent.thumbnailUrl=t+e.replyContent.thumbnailUrl)),e}class $ extends Tr{config={token:"",autoReconnect:!0,reconnectInterval:3e3,maxReconnectAttempts:5,responseTimeout:15e3,env:"production"};ws=null;status=g.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;consultationTypeId="";sessionData=null;userInfo=null;static instance=null;matchStatus=N.UNMATCHED;constructor({env:t="production"}={}){if(super(),$.instance)return $.instance;$.instance=this,this.config.env=t}async init(t){if(!t.token)return Promise.reject(b.PARAMETER_ERROR);await xe(t.token,this.config.env),this.config=Object.assign(this.config,t)}connect(t){return this.consultationTypeId=t,new Promise(async(n,r)=>{if(!this.config.token)return r(b.UNINITIALIZED);if(this.status===g.CONNECTED)return n();if(this.status!==g.CONNECTING){this.setStatus(g.CONNECTING);try{const s=await wr(this.config.token,this.config.env);this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(g.CONNECTED),this.emit(y.CONNECTED),n()},this.ws.onmessage=o=>{try{this.handleMessage(o.data)}catch(i){throw console.error("解析消息失败:",i),b.DATA_PARSING_ERROR}},this.ws.onerror=o=>{console.error("连接错误:",o),this.setStatus(g.ERROR),this.emit(y.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(g.DISCONNECTED),this.emit(y.DISCONNECTED),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(g.ERROR),this.emit(y.ERROR,s),r(s)}}})}disconnect(){this.config.autoReconnect=!1,this.sessionData=null,this.matchStatus=N.UNMATCHED,this.clearReconnectTimer(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus(g.DISCONNECTED)}async sendMessage(t,n,r=H.SEND){const s={msgType:r,data:t,toUid:this.sessionData?.cid,chatType:n,editId:void 0};if(this.status!==g.CONNECTED||!this.ws)if(this.ws&&this.status===g.DISCONNECTED){console.log("连接断开,尝试重新连接");try{await this.connect(this.consultationTypeId)}catch(o){throw console.error("重连失败:",o),b.DISCONNECTED}}else throw console.error(b.DISCONNECTED),b.DISCONNECTED;try{if(!this.ws)throw b.DISCONNECTED;return r===H.SEND?new Promise(async(o,i)=>{const c=Rr();s.ext=c;const d=await Sr({ext:c});d.data?.messageId?(this.ws.send(JSON.stringify(s)),o({messageId:d.data.messageId,data:t})):i(b.MESSAGE_SEND_FAIL)}):(this.ws.send(JSON.stringify(s)),{data:t})}catch(o){throw console.error("发送消息失败:",o),b.MESSAGE_SEND_FAIL}}async checkMatchStatus(){if(this.matchStatus===N.UNBIND&&(await this.sendMessage(this.consultationTypeId,void 0,H.INBOUND),await new Promise((t,n)=>{const r=setTimeout(()=>{clearTimeout(r),n(b.MESSAGE_SEND_FAIL)},this.config.responseTimeout);this.once(y.MESSAGE,s=>{s.code===C.REMATCH&&(clearTimeout(r),t(!0))})})),this.matchStatus!==N.MATCHED)throw console.error(b.NO_CUSTOMER_SERVICE),b.NO_CUSTOMER_SERVICE}async sendText(t){return await this.checkMatchStatus(),this.sendMessage(t,j.TEXT)}async sendFile({file:t,thumbnailFile:n,chatType:r}){try{await this.checkMatchStatus();const[s,o]=await Promise.all([this.handleUploadFile(t),n?this.handleUploadFile(n):Promise.resolve(void 0)]),i={fileName:t.name,fileUrl:s,thumbnailUrl:o,fileSize:t.size},{messageId:c}=await this.sendMessage(JSON.stringify(i),r),d=Te();return{messageId:c,content:{fileName:t.name,fileUrl:`${d}/${s}`,thumbnailUrl:o?`${d}/${o}`:void 0,fileSize:t.size}}}catch(s){throw console.error("上传文件失败:",s),s}}getStatus(){return this.status}isConnected(){return this.status===g.CONNECTED}handleMessage(t){if(t==="ping"){this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.sendHeartbeat();return}if(t=JSON.parse(t),!!yr(t))try{const n=t.data?JSON.parse(t.data):t.data;switch(t.data=n,t.code){case C.CONNECT_SUCCESS:this.matchStatus===N.MATCHED||this.matchStatus===N.MATCHING?this.matchStatus=N.UNBIND:this.matchStatus=N.MATCHING,this.sendMessage(this.consultationTypeId,void 0,H.INBOUND);break;case C.MATCH_INFO:case C.MATCH_SUCCESS:if(this.matchStatus===N.MATCHED)return;this.sessionData=t.data,this.matchStatus===N.UNBIND?(this.matchStatus=N.MATCHED,this.emit(y.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=N.MATCHED,this.getFaqList(),this.emit(y.MESSAGE,t));break;case C.TRANSFER_USER_SUCCESS:if(n.oldSessionId!==this.sessionData?.sessionId)return;const r=t.data;this.sessionData={...this.sessionData,cid:String(r.cid),customerAvatar:r.customerAvatar,customerName:r.customerName,groupId:r.groupId,sessionId:r.sessionId},this.emit(y.MESSAGE,t);break;case C.SEND_SUCCESS:case C.EDIT:case C.REPLY_SUCCESS:const s=t.data;if(s.sessionId!==this.sessionData?.sessionId)return;At(s),this.emit(y.MESSAGE,t);break;case C.SEND_CALLBACK:const o=t.ext,c=t.data.messageId;this.emit(o,c);break;case C.UNBIND_SUCCESS:if(n.sessionId!==this.sessionData?.sessionId)return;this.matchStatus=N.UNBIND,this.sessionData=null,this.emit(y.MESSAGE,t);break;default:this.emit(y.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}setStatus(t){this.status!==t&&(this.status=t,this.emit(y.STATUS_CHANGE,t))}scheduleReconnect(){this.config.env==="development"&&console.warn(`第${this.reconnectAttempts+1}次安排重连`,new Date().toISOString()),this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(g.RECONNECTING),this.reconnectTimer=setTimeout(()=>{this.connect(this.consultationTypeId).catch(t=>{console.error("重连失败:",t)})},this.config.reconnectInterval)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}sendHeartbeat(){if(!(this.status!==g.CONNECTED||!this.ws))try{this.ws.send("pong"),this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer=setTimeout(()=>{Date.now()-this.lastHeartbeatTime>=this.config.responseTimeout&&(this.emit(y.HEARTBEAT_TIMEOUT),this.config.env==="development"&&console.warn("心跳超时,尝试重连",new Date().toISOString()),this.ws&&this.ws.close())},this.config.responseTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=50}){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const r=await mr({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>At(o));return{hasMore:r.data.hasMore,list:s}}async getConsultationList(t){return(await dr({entranceId:t})).data}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await lr({ext:s||""}),{accessKeyId:i,signature:c,policy:d,key:u,maxLimit:l,url:h}=o.data;if(t.size>l*1024*1024)return r(`文件大小不能超过${l}MB`);if(h){const S=await fr(t,h);S.status===200?n(`${u}`):r(S.data)}else{const S=new FormData;S.append("key",u),S.append("AccessKeyId",i),S.append("signature",c),S.append("policy",d),S.append("file",t);const w=await ur(S);w.status===204?n(`${u}`):r(w.data)}})}getVideoThumbnail=t=>new Promise((n,r)=>{const s=document.createElement("video"),o=document.createElement("canvas"),i=o.getContext("2d");if(!i){r(new Error("无法创建 canvas 上下文"));return}const c=URL.createObjectURL(t);s.preload="metadata",s.src=c,s.muted=!0,s.playsInline=!0,s.addEventListener("loadeddata",()=>{o.width=s.videoWidth,o.height=s.videoHeight,s.currentTime=0}),s.addEventListener("seeked",()=>{try{i.drawImage(s,0,0,o.width,o.height),o.toBlob(d=>{if(URL.revokeObjectURL(c),s.remove(),!d){r(b.FILE_PARSING_ERROR);return}const u=t.name.replace(/\.[^/.]+$/,"")+"_thumb.jpg",l=new File([d],u,{type:"image/jpeg",lastModified:Date.now()});n(l)},"image/jpeg",.6)}catch(d){URL.revokeObjectURL(c),s.remove(),r(d)}}),s.addEventListener("error",()=>{URL.revokeObjectURL(c),s.remove(),r(b.FILE_PARSING_ERROR)}),s.load()});async getFaqList(){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const t=await hr({id:this.sessionData?.cid});if(!t.data?.topic?.length)return;const n={guideText:t.data.guideText,list:t.data.topic.map(r=>({...r,question:r.question}))};setTimeout(()=>{const r={code:C.SEND_SUCCESS,data:{content:n,contentType:j.FAQ,sendUserType:we.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND},msgType:H.SEND,chatType:j.FAQ};this.emit(y.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={code:C.SEND_SUCCESS,data:{sendUserType:we.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND,contentType:j.FAQ,content:{}},msgType:H.SEND,chatType:j.FAQ};if(t.isMulti)n.data.content={list:t.item},this.emit(y.MESSAGE,n);else{const r=t.item?.[0]||t,s=Te();r.imageUrl=r.imageUrl?.map(o=>o?.startsWith("http")?o:`${s}/${o}`),n.data.content={answer:r},this.emit(y.MESSAGE,n)}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await pr();return this.userInfo=t.data,this.userInfo}async anonymousLogin(t,n){return(await Er({appKey:t,entranceId:n,userSource:"H5"})).data}}U.ChatType=j,U.ConnectionStatus=g,U.EventType=y,U.JoyTalk=$,U.MatchStatus=N,U.MessageCode=C,U.MessageType=H,U.SendUserType=we,U.default=$,Object.defineProperties(U,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|