joytalk 0.0.34 → 0.0.36
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 +108 -110
- package/dist/index.umd.js +3 -3
- 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 yt(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 Rt(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=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,$n=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 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(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&&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 y(){if(!p)return;const R=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:R,config:e,request:p};Rt(function(L){n(L),m()},function(L){r(L),m()},P),p=null}"onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},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=R=>{p&&(r(!R||R.type?new Z(null,e,p):R),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&&O.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(O.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 y=m&&m[f];if(y)return y.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:y,signal:I,cancelToken:R,timeout:U,onDownloadProgress:P,onUploadProgress:G,responseType:L,headers:Re,withCredentials:ie="same-origin",fetchOptions:Be}=bt(f),ke=t||fetch;L=L?(L+"").toLowerCase():"text";let ae=Wn([I,R&&R.toAbortSignal()],U),ee=null;const z=ae&&ae.unsubscribe&&(()=>{ae.unsubscribe()});let He;try{if(G&&u&&p!=="get"&&p!=="head"&&(He=await w(Re,y))!==0){let M=new n(m,{method:"POST",body:y,duplex:"half"}),K;if(a.isFormData(y)&&(K=M.headers.get("content-type"))&&Re.setContentType(K),M.body){const[Ae,ce]=We(He,he(Ve(G)));y=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:Re.normalize().toJSON(),body:y,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)=>{Rt(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 gt={getAdapter:tr,adapters:Pe};function ge(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Z(null,e)}function nt(e){return ge(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),gt.getAdapter(e.adapter||oe.adapter,e)(e).then(function(r){return ge(e),r.data=Ne.call(e,e.transformResponse,r),r.headers=D.from(r.headers),r},function(r){return yt(r)||(ge(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 Ot="1.13.2",ye={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ye[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const rt={};ye.transitional=function(t,n,r){function s(o,i){return"[Axios v"+Ot+"] 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}};ye.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:ye},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=yt;T.VERSION=Ot;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=gt.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-05.halaladmin.vip"},prodtest:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img-05.halaladmin.vip"},production:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img-05.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}),yr=()=>q.get("/api/open-auth/user/v1/UserService/GetUserInfo"),Rr=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.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||{}),N=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(N||{}),g=(e=>(e.UNMATCHED="1",e.MATCHING="2",e.MATCHED="3",e.UNBIND="4",e))(g||{});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 gr(e,t){return await xe(e,t),`${await pr()}/api/ws?Authorization=${e}`}function Or(){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=N.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;consultationTypeId="";sessionData=null;userInfo=null;static instance=null;matchStatus=g.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===N.CONNECTED)return n();if(this.status!==N.CONNECTING){this.setStatus(N.CONNECTING);try{const s=await gr(this.config.token,this.config.env);this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(N.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(N.ERROR),this.emit(A.ERROR,o),r(o)},this.ws.onclose=()=>{this.setStatus(N.DISCONNECTED),this.emit(A.DISCONNECTED),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(N.ERROR),this.emit(A.ERROR,s),r(s)}}})}disconnect(){this.config.autoReconnect=!1,this.sessionData=null,this.matchStatus=g.UNMATCHED,this.clearReconnectTimer(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus(N.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!==N.CONNECTED||!this.ws)if(this.ws&&this.status===N.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=Or();s.ext=c;const d=await br({ext:c});console.log("🚀 ~ JoyTalk ~ sendMessage ~ res:",d.data.messageId),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===g.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!==g.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===N.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:if(this.matchStatus===g.MATCHED||this.matchStatus===g.MATCHING)return;this.matchStatus=g.MATCHING,this.sendMessage(this.consultationTypeId,void 0,H.INBOUND);break;case C.MATCH_INFO:case C.MATCH_SUCCESS:if(this.matchStatus===g.MATCHED)return;this.sessionData=t.data,this.matchStatus===g.UNBIND?(this.matchStatus=g.MATCHED,this.emit(A.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=g.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=g.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.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(N.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!==N.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),console.warn("心跳超时,尝试重连"),this.ws&&this.ws.close())},this.config.responseTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=50}){if(this.matchStatus!==g.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const r=await Rr({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!==g.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 yr();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=N;exports.EventType=A;exports.JoyTalk=$;exports.MatchStatus=g;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=yt;T.VERSION=Ot;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=gt.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}),yr=()=>q.get("/api/open-auth/user/v1/UserService/GetUserInfo"),Rr=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.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||{}),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 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 gr(e,t){return await xe(e,t),`${await pr()}/api/ws?Authorization=${e}`}function Or(){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=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 gr(this.config.token,this.config.env);this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(g.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(g.ERROR),this.emit(A.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(g.DISCONNECTED),this.emit(A.DISCONNECTED),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(g.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(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=Or();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===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),!!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("安排重连",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(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 Rr({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 yr();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=g;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
|
@@ -303,10 +303,10 @@ function qe(e, t, n) {
|
|
|
303
303
|
function Sn(e) {
|
|
304
304
|
return a.isArray(e) && !e.some(ge);
|
|
305
305
|
}
|
|
306
|
-
const
|
|
306
|
+
const wn = a.toFlatObject(a, {}, null, function(t) {
|
|
307
307
|
return /^is[A-Z]/.test(t);
|
|
308
308
|
});
|
|
309
|
-
function
|
|
309
|
+
function we(e, t, n) {
|
|
310
310
|
if (!a.isObject(e))
|
|
311
311
|
throw new TypeError("target must be an object");
|
|
312
312
|
t = t || new FormData(), n = a.toFlatObject(n, {
|
|
@@ -345,12 +345,12 @@ function Te(e, t, n) {
|
|
|
345
345
|
}
|
|
346
346
|
return ge(f) ? !0 : (t.append(qe(p, m, o), u(f)), !1);
|
|
347
347
|
}
|
|
348
|
-
const h = [], S = Object.assign(
|
|
348
|
+
const h = [], S = Object.assign(wn, {
|
|
349
349
|
defaultVisitor: l,
|
|
350
350
|
convertValue: u,
|
|
351
351
|
isVisitable: ge
|
|
352
352
|
});
|
|
353
|
-
function
|
|
353
|
+
function T(f, m) {
|
|
354
354
|
if (!a.isUndefined(f)) {
|
|
355
355
|
if (h.indexOf(f) !== -1)
|
|
356
356
|
throw Error("Circular reference detected in " + m.join("."));
|
|
@@ -361,13 +361,13 @@ function Te(e, t, n) {
|
|
|
361
361
|
a.isString(I) ? I.trim() : I,
|
|
362
362
|
m,
|
|
363
363
|
S
|
|
364
|
-
)) === !0 &&
|
|
364
|
+
)) === !0 && T(R, m ? m.concat(I) : [I]);
|
|
365
365
|
}), h.pop();
|
|
366
366
|
}
|
|
367
367
|
}
|
|
368
368
|
if (!a.isObject(e))
|
|
369
369
|
throw new TypeError("data must be an object");
|
|
370
|
-
return
|
|
370
|
+
return T(e), t;
|
|
371
371
|
}
|
|
372
372
|
function Ge(e) {
|
|
373
373
|
const t = {
|
|
@@ -384,7 +384,7 @@ function Ge(e) {
|
|
|
384
384
|
});
|
|
385
385
|
}
|
|
386
386
|
function Le(e, t) {
|
|
387
|
-
this._pairs = [], e &&
|
|
387
|
+
this._pairs = [], e && we(e, this, t);
|
|
388
388
|
}
|
|
389
389
|
const Et = Le.prototype;
|
|
390
390
|
Et.append = function(t, n) {
|
|
@@ -398,13 +398,13 @@ Et.toString = function(t) {
|
|
|
398
398
|
return n(s[0]) + "=" + n(s[1]);
|
|
399
399
|
}, "").join("&");
|
|
400
400
|
};
|
|
401
|
-
function
|
|
401
|
+
function Tn(e) {
|
|
402
402
|
return encodeURIComponent(e).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+");
|
|
403
403
|
}
|
|
404
404
|
function St(e, t, n) {
|
|
405
405
|
if (!t)
|
|
406
406
|
return e;
|
|
407
|
-
const r = n && n.encode ||
|
|
407
|
+
const r = n && n.encode || Tn;
|
|
408
408
|
a.isFunction(n) && (n = {
|
|
409
409
|
serialize: n
|
|
410
410
|
});
|
|
@@ -470,7 +470,7 @@ class ze {
|
|
|
470
470
|
});
|
|
471
471
|
}
|
|
472
472
|
}
|
|
473
|
-
const
|
|
473
|
+
const wt = {
|
|
474
474
|
silentJSONParsing: !0,
|
|
475
475
|
forcedJSONParsing: !0,
|
|
476
476
|
clarifyTimeoutError: !1
|
|
@@ -490,14 +490,14 @@ self instanceof WorkerGlobalScope && typeof self.importScripts == "function", gn
|
|
|
490
490
|
hasStandardBrowserWebWorkerEnv: On,
|
|
491
491
|
navigator: Ce,
|
|
492
492
|
origin: gn
|
|
493
|
-
}, Symbol.toStringTag, { value: "Module" })),
|
|
493
|
+
}, Symbol.toStringTag, { value: "Module" })), O = {
|
|
494
494
|
...Cn,
|
|
495
495
|
...bn
|
|
496
496
|
};
|
|
497
497
|
function Un(e, t) {
|
|
498
|
-
return
|
|
498
|
+
return we(e, new O.classes.URLSearchParams(), {
|
|
499
499
|
visitor: function(n, r, s, o) {
|
|
500
|
-
return
|
|
500
|
+
return O.isNode && a.isBuffer(n) ? (this.append(r, n.toString("base64")), !1) : o.defaultVisitor.apply(this, arguments);
|
|
501
501
|
},
|
|
502
502
|
...t
|
|
503
503
|
});
|
|
@@ -514,7 +514,7 @@ function Dn(e) {
|
|
|
514
514
|
o = n[r], t[o] = e[o];
|
|
515
515
|
return t;
|
|
516
516
|
}
|
|
517
|
-
function
|
|
517
|
+
function Tt(e) {
|
|
518
518
|
function t(n, r, s, o) {
|
|
519
519
|
let i = n[o++];
|
|
520
520
|
if (i === "__proto__") return !0;
|
|
@@ -540,12 +540,12 @@ function In(e, t, n) {
|
|
|
540
540
|
return (n || JSON.stringify)(e);
|
|
541
541
|
}
|
|
542
542
|
const oe = {
|
|
543
|
-
transitional:
|
|
543
|
+
transitional: wt,
|
|
544
544
|
adapter: ["xhr", "http", "fetch"],
|
|
545
545
|
transformRequest: [function(t, n) {
|
|
546
546
|
const r = n.getContentType() || "", s = r.indexOf("application/json") > -1, o = a.isObject(t);
|
|
547
547
|
if (o && a.isHTMLForm(t) && (t = new FormData(t)), a.isFormData(t))
|
|
548
|
-
return s ? JSON.stringify(
|
|
548
|
+
return s ? JSON.stringify(Tt(t)) : t;
|
|
549
549
|
if (a.isArrayBuffer(t) || a.isBuffer(t) || a.isStream(t) || a.isFile(t) || a.isBlob(t) || a.isReadableStream(t))
|
|
550
550
|
return t;
|
|
551
551
|
if (a.isArrayBufferView(t))
|
|
@@ -558,7 +558,7 @@ const oe = {
|
|
|
558
558
|
return Un(t, this.formSerializer).toString();
|
|
559
559
|
if ((c = a.isFileList(t)) || r.indexOf("multipart/form-data") > -1) {
|
|
560
560
|
const d = this.env && this.env.FormData;
|
|
561
|
-
return
|
|
561
|
+
return we(
|
|
562
562
|
c ? { "files[]": t } : t,
|
|
563
563
|
d && new d(),
|
|
564
564
|
this.formSerializer
|
|
@@ -592,8 +592,8 @@ const oe = {
|
|
|
592
592
|
maxContentLength: -1,
|
|
593
593
|
maxBodyLength: -1,
|
|
594
594
|
env: {
|
|
595
|
-
FormData:
|
|
596
|
-
Blob:
|
|
595
|
+
FormData: O.classes.FormData,
|
|
596
|
+
Blob: O.classes.Blob
|
|
597
597
|
},
|
|
598
598
|
validateStatus: function(t) {
|
|
599
599
|
return t >= 200 && t < 300;
|
|
@@ -851,8 +851,8 @@ function vn(e, t) {
|
|
|
851
851
|
S += n[h++], h = h % e;
|
|
852
852
|
if (s = (s + 1) % e, s === o && (o = (o + 1) % e), u - i < t)
|
|
853
853
|
return;
|
|
854
|
-
const
|
|
855
|
-
return
|
|
854
|
+
const T = l && u - l;
|
|
855
|
+
return T ? Math.round(S * 1e3 / T) : void 0;
|
|
856
856
|
};
|
|
857
857
|
}
|
|
858
858
|
function jn(e, t) {
|
|
@@ -893,10 +893,10 @@ const he = (e, t, n = 3) => {
|
|
|
893
893
|
total: e,
|
|
894
894
|
loaded: r
|
|
895
895
|
}), t[1]];
|
|
896
|
-
}, Ve = (e) => (...t) => a.asap(() => e(...t)), Mn =
|
|
897
|
-
new URL(
|
|
898
|
-
|
|
899
|
-
) : () => !0, $n =
|
|
896
|
+
}, Ve = (e) => (...t) => a.asap(() => e(...t)), Mn = O.hasStandardBrowserEnv ? /* @__PURE__ */ ((e, t) => (n) => (n = new URL(n, O.origin), e.protocol === n.protocol && e.host === n.host && (t || e.port === n.port)))(
|
|
897
|
+
new URL(O.origin),
|
|
898
|
+
O.navigator && /(msie|trident)/i.test(O.navigator.userAgent)
|
|
899
|
+
) : () => !0, $n = O.hasStandardBrowserEnv ? (
|
|
900
900
|
// Standard browser envs support document.cookie
|
|
901
901
|
{
|
|
902
902
|
write(e, t, n, r, s, o, i) {
|
|
@@ -1007,7 +1007,7 @@ const bt = (e) => {
|
|
|
1007
1007
|
"Authorization",
|
|
1008
1008
|
"Basic " + btoa((c.username || "") + ":" + (c.password ? unescape(encodeURIComponent(c.password)) : ""))
|
|
1009
1009
|
), a.isFormData(n)) {
|
|
1010
|
-
if (
|
|
1010
|
+
if (O.hasStandardBrowserEnv || O.hasStandardBrowserWebWorkerEnv)
|
|
1011
1011
|
i.setContentType(void 0);
|
|
1012
1012
|
else if (a.isFunction(n.getHeaders)) {
|
|
1013
1013
|
const d = n.getHeaders(), u = ["content-type", "content-length"];
|
|
@@ -1016,7 +1016,7 @@ const bt = (e) => {
|
|
|
1016
1016
|
});
|
|
1017
1017
|
}
|
|
1018
1018
|
}
|
|
1019
|
-
if (
|
|
1019
|
+
if (O.hasStandardBrowserEnv && (r && a.isFunction(r) && (r = r(t)), r || r !== !1 && Mn(t.url))) {
|
|
1020
1020
|
const d = s && o && $n.read(o);
|
|
1021
1021
|
d && i.set(s, d);
|
|
1022
1022
|
}
|
|
@@ -1026,9 +1026,9 @@ const bt = (e) => {
|
|
|
1026
1026
|
const s = bt(e);
|
|
1027
1027
|
let o = s.data;
|
|
1028
1028
|
const i = D.from(s.headers).normalize();
|
|
1029
|
-
let { responseType: c, onUploadProgress: d, onDownloadProgress: u } = s, l, h, S,
|
|
1029
|
+
let { responseType: c, onUploadProgress: d, onDownloadProgress: u } = s, l, h, S, T, f;
|
|
1030
1030
|
function m() {
|
|
1031
|
-
|
|
1031
|
+
T && T(), f && f(), s.cancelToken && s.cancelToken.unsubscribe(l), s.signal && s.signal.removeEventListener("abort", l);
|
|
1032
1032
|
}
|
|
1033
1033
|
let p = new XMLHttpRequest();
|
|
1034
1034
|
p.open(s.method.toUpperCase(), s.url, !0), p.timeout = s.timeout;
|
|
@@ -1060,7 +1060,7 @@ const bt = (e) => {
|
|
|
1060
1060
|
q.event = C || null, r(q), p = null;
|
|
1061
1061
|
}, p.ontimeout = function() {
|
|
1062
1062
|
let C = s.timeout ? "timeout of " + s.timeout + "ms exceeded" : "timeout exceeded";
|
|
1063
|
-
const P = s.transitional ||
|
|
1063
|
+
const P = s.transitional || wt;
|
|
1064
1064
|
s.timeoutErrorMessage && (C = s.timeoutErrorMessage), r(new E(
|
|
1065
1065
|
C,
|
|
1066
1066
|
P.clarifyTimeoutError ? E.ETIMEDOUT : E.ECONNABORTED,
|
|
@@ -1069,11 +1069,11 @@ const bt = (e) => {
|
|
|
1069
1069
|
)), p = null;
|
|
1070
1070
|
}, o === void 0 && i.setContentType(null), "setRequestHeader" in p && a.forEach(i.toJSON(), function(C, P) {
|
|
1071
1071
|
p.setRequestHeader(P, C);
|
|
1072
|
-
}), 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,
|
|
1072
|
+
}), 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, T] = he(d), p.upload.addEventListener("progress", h), p.upload.addEventListener("loadend", T)), (s.cancelToken || s.signal) && (l = (y) => {
|
|
1073
1073
|
p && (r(!y || y.type ? new Z(null, e, p) : y), p.abort(), p = null);
|
|
1074
1074
|
}, s.cancelToken && s.cancelToken.subscribe(l), s.signal && (s.signal.aborted ? l() : s.signal.addEventListener("abort", l)));
|
|
1075
1075
|
const I = Hn(s.url);
|
|
1076
|
-
if (I &&
|
|
1076
|
+
if (I && O.protocols.indexOf(I) === -1) {
|
|
1077
1077
|
r(new E("Unsupported protocol " + I + ":", E.ERR_BAD_REQUEST, e));
|
|
1078
1078
|
return;
|
|
1079
1079
|
}
|
|
@@ -1180,7 +1180,7 @@ const bt = (e) => {
|
|
|
1180
1180
|
return !1;
|
|
1181
1181
|
const c = s && le(Qe), d = s && (typeof Ze == "function" ? /* @__PURE__ */ ((f) => (m) => f.encode(m))(new Ze()) : async (f) => new Uint8Array(await new n(f).arrayBuffer())), u = o && c && et(() => {
|
|
1182
1182
|
let f = !1;
|
|
1183
|
-
const m = new n(
|
|
1183
|
+
const m = new n(O.origin, {
|
|
1184
1184
|
body: new Qe(),
|
|
1185
1185
|
method: "POST",
|
|
1186
1186
|
get duplex() {
|
|
@@ -1205,7 +1205,7 @@ const bt = (e) => {
|
|
|
1205
1205
|
if (a.isBlob(f))
|
|
1206
1206
|
return f.size;
|
|
1207
1207
|
if (a.isSpecCompliantForm(f))
|
|
1208
|
-
return (await new n(
|
|
1208
|
+
return (await new n(O.origin, {
|
|
1209
1209
|
method: "POST",
|
|
1210
1210
|
body: f
|
|
1211
1211
|
}).arrayBuffer()).byteLength;
|
|
@@ -1213,7 +1213,7 @@ const bt = (e) => {
|
|
|
1213
1213
|
return f.byteLength;
|
|
1214
1214
|
if (a.isURLSearchParams(f) && (f = f + ""), a.isString(f))
|
|
1215
1215
|
return (await d(f)).byteLength;
|
|
1216
|
-
},
|
|
1216
|
+
}, T = async (f, m) => {
|
|
1217
1217
|
const p = a.toFiniteNumber(f.getContentLength());
|
|
1218
1218
|
return p ?? S(m);
|
|
1219
1219
|
};
|
|
@@ -1239,7 +1239,7 @@ const bt = (e) => {
|
|
|
1239
1239
|
});
|
|
1240
1240
|
let He;
|
|
1241
1241
|
try {
|
|
1242
|
-
if (q && u && p !== "get" && p !== "head" && (He = await
|
|
1242
|
+
if (q && u && p !== "get" && p !== "head" && (He = await T(Re, R)) !== 0) {
|
|
1243
1243
|
let j = new n(m, {
|
|
1244
1244
|
method: "POST",
|
|
1245
1245
|
body: R,
|
|
@@ -1395,14 +1395,14 @@ function nt(e) {
|
|
|
1395
1395
|
), r.response.headers = D.from(r.response.headers))), Promise.reject(r);
|
|
1396
1396
|
});
|
|
1397
1397
|
}
|
|
1398
|
-
const gt = "1.13.2",
|
|
1398
|
+
const gt = "1.13.2", Te = {};
|
|
1399
1399
|
["object", "boolean", "number", "function", "string", "symbol"].forEach((e, t) => {
|
|
1400
|
-
|
|
1400
|
+
Te[e] = function(r) {
|
|
1401
1401
|
return typeof r === e || "a" + (t < 1 ? "n " : " ") + e;
|
|
1402
1402
|
};
|
|
1403
1403
|
});
|
|
1404
1404
|
const rt = {};
|
|
1405
|
-
|
|
1405
|
+
Te.transitional = function(t, n, r) {
|
|
1406
1406
|
function s(o, i) {
|
|
1407
1407
|
return "[Axios v" + gt + "] Transitional option '" + o + "'" + i + (r ? ". " + r : "");
|
|
1408
1408
|
}
|
|
@@ -1420,7 +1420,7 @@ we.transitional = function(t, n, r) {
|
|
|
1420
1420
|
)), t ? t(o, i, c) : !0;
|
|
1421
1421
|
};
|
|
1422
1422
|
};
|
|
1423
|
-
|
|
1423
|
+
Te.spelling = function(t) {
|
|
1424
1424
|
return (n, r) => (console.warn(`${r} is likely a misspelling of ${t}`), !0);
|
|
1425
1425
|
};
|
|
1426
1426
|
function nr(e, t, n) {
|
|
@@ -1442,7 +1442,7 @@ function nr(e, t, n) {
|
|
|
1442
1442
|
}
|
|
1443
1443
|
const de = {
|
|
1444
1444
|
assertOptions: nr,
|
|
1445
|
-
validators:
|
|
1445
|
+
validators: Te
|
|
1446
1446
|
}, k = de.validators;
|
|
1447
1447
|
let J = class {
|
|
1448
1448
|
constructor(t) {
|
|
@@ -1519,18 +1519,18 @@ let J = class {
|
|
|
1519
1519
|
return l;
|
|
1520
1520
|
}
|
|
1521
1521
|
S = c.length;
|
|
1522
|
-
let
|
|
1522
|
+
let T = n;
|
|
1523
1523
|
for (; h < S; ) {
|
|
1524
1524
|
const f = c[h++], m = c[h++];
|
|
1525
1525
|
try {
|
|
1526
|
-
|
|
1526
|
+
T = f(T);
|
|
1527
1527
|
} catch (p) {
|
|
1528
1528
|
m.call(this, p);
|
|
1529
1529
|
break;
|
|
1530
1530
|
}
|
|
1531
1531
|
}
|
|
1532
1532
|
try {
|
|
1533
|
-
l = nt.call(this,
|
|
1533
|
+
l = nt.call(this, T);
|
|
1534
1534
|
} catch (f) {
|
|
1535
1535
|
return Promise.reject(f);
|
|
1536
1536
|
}
|
|
@@ -1729,26 +1729,26 @@ function Ut(e) {
|
|
|
1729
1729
|
return Ut(W(e, s));
|
|
1730
1730
|
}, n;
|
|
1731
1731
|
}
|
|
1732
|
-
const
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1732
|
+
const w = Ut(oe);
|
|
1733
|
+
w.Axios = J;
|
|
1734
|
+
w.CanceledError = Z;
|
|
1735
|
+
w.CancelToken = rr;
|
|
1736
|
+
w.isCancel = Rt;
|
|
1737
|
+
w.VERSION = gt;
|
|
1738
|
+
w.toFormData = we;
|
|
1739
|
+
w.AxiosError = E;
|
|
1740
|
+
w.Cancel = w.CanceledError;
|
|
1741
|
+
w.all = function(t) {
|
|
1742
1742
|
return Promise.all(t);
|
|
1743
1743
|
};
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1744
|
+
w.spread = sr;
|
|
1745
|
+
w.isAxiosError = or;
|
|
1746
|
+
w.mergeConfig = W;
|
|
1747
|
+
w.AxiosHeaders = D;
|
|
1748
|
+
w.formToJSON = (e) => Tt(a.isHTMLForm(e) ? new FormData(e) : e);
|
|
1749
|
+
w.getAdapter = Ot.getAdapter;
|
|
1750
|
+
w.HttpStatusCode = Ue;
|
|
1751
|
+
w.default = w;
|
|
1752
1752
|
const {
|
|
1753
1753
|
Axios: Dr,
|
|
1754
1754
|
AxiosError: Ir,
|
|
@@ -1766,7 +1766,7 @@ const {
|
|
|
1766
1766
|
formToJSON: qr,
|
|
1767
1767
|
getAdapter: Gr,
|
|
1768
1768
|
mergeConfig: zr
|
|
1769
|
-
} =
|
|
1769
|
+
} = w, A = {
|
|
1770
1770
|
/** 未初始化 */
|
|
1771
1771
|
UNINITIALIZED: {
|
|
1772
1772
|
code: 10001,
|
|
@@ -1825,15 +1825,15 @@ const {
|
|
|
1825
1825
|
}, ir = "/api/customer-service/customer/v1/CustomerService/TestLineLatency", ar = "/api/customer-service/customer/v1/CustomerService/ListLines", cr = "/pub/logo.png", _e = {
|
|
1826
1826
|
development: {
|
|
1827
1827
|
BASE_API_URL: "http://dev-joytalk-api.halaladmin.vip",
|
|
1828
|
-
OBS_URL: "http://dev-joytalk-img
|
|
1828
|
+
OBS_URL: "http://dev-joytalk-img.halaladmin.vip"
|
|
1829
1829
|
},
|
|
1830
1830
|
prodtest: {
|
|
1831
1831
|
BASE_API_URL: "https://fat-joytalk-api.halaladmin.vip",
|
|
1832
|
-
OBS_URL: "https://fat-joytalk-img
|
|
1832
|
+
OBS_URL: "https://fat-joytalk-img.halaladmin.vip"
|
|
1833
1833
|
},
|
|
1834
1834
|
production: {
|
|
1835
1835
|
BASE_API_URL: "https://fat-joytalk-api.halaladmin.vip",
|
|
1836
|
-
OBS_URL: "https://fat-joytalk-img
|
|
1836
|
+
OBS_URL: "https://fat-joytalk-img.halaladmin.vip"
|
|
1837
1837
|
}
|
|
1838
1838
|
}, F = {
|
|
1839
1839
|
api: "",
|
|
@@ -1843,13 +1843,13 @@ const {
|
|
|
1843
1843
|
let K = null;
|
|
1844
1844
|
function lr(e) {
|
|
1845
1845
|
const t = `${e.replace(/\/$/, "")}${ir}`;
|
|
1846
|
-
return
|
|
1846
|
+
return w.get(t, {
|
|
1847
1847
|
timeout: 1e4
|
|
1848
1848
|
}).then((n) => n.data?.code !== 200 ? Promise.reject(n) : e);
|
|
1849
1849
|
}
|
|
1850
1850
|
function ur(e) {
|
|
1851
1851
|
const t = `${e.replace(/\/$/, "")}${cr}`;
|
|
1852
|
-
return
|
|
1852
|
+
return w.get(t, {
|
|
1853
1853
|
timeout: 1e4
|
|
1854
1854
|
}).then(() => e).catch(() => Promise.reject(new Error("Download latency test failed")));
|
|
1855
1855
|
}
|
|
@@ -1864,7 +1864,7 @@ async function xe(e, t) {
|
|
|
1864
1864
|
if (K) return K;
|
|
1865
1865
|
const n = _e[t].BASE_API_URL || "", r = _e[t].OBS_URL || "";
|
|
1866
1866
|
F.api = n, F.download = r, F.ws = n.replace(/http/g, "ws"), n || (K = Promise.reject(new Error("环境配置错误")), await K), K = (async () => {
|
|
1867
|
-
const s = await
|
|
1867
|
+
const s = await w.get(`${n.replace(/\/$/, "")}${ar}`, {
|
|
1868
1868
|
headers: { Authorization: `Bearer ${e}` },
|
|
1869
1869
|
timeout: 15e3
|
|
1870
1870
|
});
|
|
@@ -1877,7 +1877,7 @@ async function xe(e, t) {
|
|
|
1877
1877
|
F.api = u, F.download = l, F.ws = u.replace(/http/g, "ws");
|
|
1878
1878
|
})(), await K;
|
|
1879
1879
|
}
|
|
1880
|
-
const $ =
|
|
1880
|
+
const $ = w.create({
|
|
1881
1881
|
timeout: 6e5
|
|
1882
1882
|
});
|
|
1883
1883
|
$.interceptors.request.use(
|
|
@@ -1905,19 +1905,19 @@ const mr = (e) => $.post(
|
|
|
1905
1905
|
e
|
|
1906
1906
|
), Er = async (e) => {
|
|
1907
1907
|
const t = pe();
|
|
1908
|
-
return
|
|
1908
|
+
return w.post(`${t}`, e, {
|
|
1909
1909
|
headers: {
|
|
1910
1910
|
"Content-Type": "multipart/form-data"
|
|
1911
1911
|
}
|
|
1912
1912
|
});
|
|
1913
|
-
}, Sr = async (e, t) =>
|
|
1913
|
+
}, Sr = async (e, t) => w.put(t, e, {
|
|
1914
1914
|
headers: {
|
|
1915
1915
|
"Content-Type": "application/octet-stream"
|
|
1916
1916
|
}
|
|
1917
|
-
}),
|
|
1917
|
+
}), wr = (e) => $.post(
|
|
1918
1918
|
"/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",
|
|
1919
1919
|
e
|
|
1920
|
-
),
|
|
1920
|
+
), Tr = (e) => $.get(
|
|
1921
1921
|
"/api/open-auth/faq/v1/FaqService/GetFaqList",
|
|
1922
1922
|
{
|
|
1923
1923
|
params: e
|
|
@@ -1929,7 +1929,7 @@ const mr = (e) => $.post(
|
|
|
1929
1929
|
e
|
|
1930
1930
|
), Ar = (e) => {
|
|
1931
1931
|
const n = new X().config.env, r = hr() || _e[n].BASE_API_URL;
|
|
1932
|
-
return
|
|
1932
|
+
return w.post(
|
|
1933
1933
|
`${r}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,
|
|
1934
1934
|
e
|
|
1935
1935
|
);
|
|
@@ -1939,7 +1939,7 @@ const mr = (e) => $.post(
|
|
|
1939
1939
|
params: e
|
|
1940
1940
|
}
|
|
1941
1941
|
);
|
|
1942
|
-
var H = /* @__PURE__ */ ((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 || {}), M = /* @__PURE__ */ ((e) => (e.TEXT = "1", e.IMAGE = "2", e.VIDEO = "3", e.FILE = "4", e.FAQ = "5", e))(M || {}), U = /* @__PURE__ */ ((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.REMATCH = 60001] = "REMATCH", e))(U || {}), De = /* @__PURE__ */ ((e) => (e.CUSTOMER = "1", e.USER = "2", e.ANONYMOUS = "3", e))(De || {}), b = /* @__PURE__ */ ((e) => (e.CONNECTED = "connected", e.DISCONNECTED = "disconnected", e.ERROR = "error", e.MESSAGE = "message", e.STATUS_CHANGE = "status_change", e.HEARTBEAT_TIMEOUT = "heartbeat_timeout", e))(b || {}),
|
|
1942
|
+
var H = /* @__PURE__ */ ((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 || {}), M = /* @__PURE__ */ ((e) => (e.TEXT = "1", e.IMAGE = "2", e.VIDEO = "3", e.FILE = "4", e.FAQ = "5", e))(M || {}), U = /* @__PURE__ */ ((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.REMATCH = 60001] = "REMATCH", e))(U || {}), De = /* @__PURE__ */ ((e) => (e.CUSTOMER = "1", e.USER = "2", e.ANONYMOUS = "3", e))(De || {}), b = /* @__PURE__ */ ((e) => (e.CONNECTED = "connected", e.DISCONNECTED = "disconnected", e.ERROR = "error", e.MESSAGE = "message", e.STATUS_CHANGE = "status_change", e.HEARTBEAT_TIMEOUT = "heartbeat_timeout", e))(b || {}), g = /* @__PURE__ */ ((e) => (e.DISCONNECTED = "disconnected", e.CONNECTING = "connecting", e.CONNECTED = "connected", e.RECONNECTING = "reconnecting", e.ERROR = "error", e))(g || {}), N = /* @__PURE__ */ ((e) => (e.UNMATCHED = "1", e.MATCHING = "2", e.MATCHED = "3", e.UNBIND = "4", e))(N || {});
|
|
1943
1943
|
class Nr {
|
|
1944
1944
|
events = /* @__PURE__ */ new Map();
|
|
1945
1945
|
/**
|
|
@@ -2021,7 +2021,7 @@ class X extends Nr {
|
|
|
2021
2021
|
env: "production"
|
|
2022
2022
|
};
|
|
2023
2023
|
ws = null;
|
|
2024
|
-
status =
|
|
2024
|
+
status = g.DISCONNECTED;
|
|
2025
2025
|
reconnectTimer = null;
|
|
2026
2026
|
reconnectAttempts = 0;
|
|
2027
2027
|
/** 心跳超时定时器 */
|
|
@@ -2034,7 +2034,7 @@ class X extends Nr {
|
|
|
2034
2034
|
userInfo = null;
|
|
2035
2035
|
static instance = null;
|
|
2036
2036
|
/** 匹配状态 */
|
|
2037
|
-
matchStatus =
|
|
2037
|
+
matchStatus = N.UNMATCHED;
|
|
2038
2038
|
constructor({ env: t = "production" } = {}) {
|
|
2039
2039
|
if (super(), X.instance)
|
|
2040
2040
|
return X.instance;
|
|
@@ -2053,17 +2053,17 @@ class X extends Nr {
|
|
|
2053
2053
|
return this.consultationTypeId = t, new Promise(async (n, r) => {
|
|
2054
2054
|
if (!this.config.token)
|
|
2055
2055
|
return r(A.UNINITIALIZED);
|
|
2056
|
-
if (this.status ===
|
|
2056
|
+
if (this.status === g.CONNECTED)
|
|
2057
2057
|
return n();
|
|
2058
|
-
if (this.status !==
|
|
2059
|
-
this.setStatus(
|
|
2058
|
+
if (this.status !== g.CONNECTING) {
|
|
2059
|
+
this.setStatus(g.CONNECTING);
|
|
2060
2060
|
try {
|
|
2061
2061
|
const s = await Or(
|
|
2062
2062
|
this.config.token,
|
|
2063
2063
|
this.config.env
|
|
2064
2064
|
);
|
|
2065
2065
|
this.ws = new WebSocket(s), this.ws.onopen = () => {
|
|
2066
|
-
this.reconnectAttempts = 0, this.setStatus(
|
|
2066
|
+
this.reconnectAttempts = 0, this.setStatus(g.CONNECTED), this.emit(b.CONNECTED), n();
|
|
2067
2067
|
}, this.ws.onmessage = (o) => {
|
|
2068
2068
|
try {
|
|
2069
2069
|
this.handleMessage(o.data);
|
|
@@ -2071,12 +2071,12 @@ class X extends Nr {
|
|
|
2071
2071
|
throw console.error("解析消息失败:", i), A.DATA_PARSING_ERROR;
|
|
2072
2072
|
}
|
|
2073
2073
|
}, this.ws.onerror = (o) => {
|
|
2074
|
-
console.error("连接错误:", o), this.setStatus(
|
|
2074
|
+
console.error("连接错误:", o), this.setStatus(g.ERROR), this.emit(b.ERROR, o), r(o);
|
|
2075
2075
|
}, this.ws.onclose = () => {
|
|
2076
|
-
this.setStatus(
|
|
2076
|
+
this.config.env === "development" && console.warn("连接断开", (/* @__PURE__ */ new Date()).toISOString()), this.setStatus(g.DISCONNECTED), this.emit(b.DISCONNECTED), this.config.autoReconnect && this.reconnectAttempts < this.config.maxReconnectAttempts && this.scheduleReconnect();
|
|
2077
2077
|
};
|
|
2078
2078
|
} catch (s) {
|
|
2079
|
-
this.setStatus(
|
|
2079
|
+
this.setStatus(g.ERROR), this.emit(b.ERROR, s), r(s);
|
|
2080
2080
|
}
|
|
2081
2081
|
}
|
|
2082
2082
|
});
|
|
@@ -2086,7 +2086,7 @@ class X extends Nr {
|
|
|
2086
2086
|
* @returns void
|
|
2087
2087
|
*/
|
|
2088
2088
|
disconnect() {
|
|
2089
|
-
this.config.autoReconnect = !1, this.sessionData = null, this.matchStatus =
|
|
2089
|
+
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);
|
|
2090
2090
|
}
|
|
2091
2091
|
/**
|
|
2092
2092
|
* 发送消息
|
|
@@ -2103,8 +2103,8 @@ class X extends Nr {
|
|
|
2103
2103
|
chatType: n,
|
|
2104
2104
|
editId: void 0
|
|
2105
2105
|
};
|
|
2106
|
-
if (this.status !==
|
|
2107
|
-
if (this.ws && this.status ===
|
|
2106
|
+
if (this.status !== g.CONNECTED || !this.ws)
|
|
2107
|
+
if (this.ws && this.status === g.DISCONNECTED) {
|
|
2108
2108
|
console.log("连接断开,尝试重新连接");
|
|
2109
2109
|
try {
|
|
2110
2110
|
await this.connect(this.consultationTypeId);
|
|
@@ -2120,7 +2120,7 @@ class X extends Nr {
|
|
|
2120
2120
|
const c = gr();
|
|
2121
2121
|
s.ext = c;
|
|
2122
2122
|
const d = await br({ ext: c });
|
|
2123
|
-
|
|
2123
|
+
d.data?.messageId ? (this.ws.send(JSON.stringify(s)), o({ messageId: d.data.messageId, data: t })) : i(A.MESSAGE_SEND_FAIL);
|
|
2124
2124
|
}) : (this.ws.send(JSON.stringify(s)), { data: t });
|
|
2125
2125
|
} catch (o) {
|
|
2126
2126
|
throw console.error("发送消息失败:", o), A.MESSAGE_SEND_FAIL;
|
|
@@ -2131,7 +2131,7 @@ class X extends Nr {
|
|
|
2131
2131
|
* @returns Promise<void>
|
|
2132
2132
|
*/
|
|
2133
2133
|
async checkMatchStatus() {
|
|
2134
|
-
if (this.matchStatus ===
|
|
2134
|
+
if (this.matchStatus === N.UNBIND && (await this.sendMessage(
|
|
2135
2135
|
this.consultationTypeId,
|
|
2136
2136
|
void 0,
|
|
2137
2137
|
H.INBOUND
|
|
@@ -2142,7 +2142,7 @@ class X extends Nr {
|
|
|
2142
2142
|
this.once(b.MESSAGE, (s) => {
|
|
2143
2143
|
s.code === U.REMATCH && (clearTimeout(r), t(!0));
|
|
2144
2144
|
});
|
|
2145
|
-
})), this.matchStatus !==
|
|
2145
|
+
})), this.matchStatus !== N.MATCHED)
|
|
2146
2146
|
throw console.error(A.NO_CUSTOMER_SERVICE), A.NO_CUSTOMER_SERVICE;
|
|
2147
2147
|
}
|
|
2148
2148
|
/**
|
|
@@ -2203,7 +2203,7 @@ class X extends Nr {
|
|
|
2203
2203
|
* @returns boolean
|
|
2204
2204
|
*/
|
|
2205
2205
|
isConnected() {
|
|
2206
|
-
return this.status ===
|
|
2206
|
+
return this.status === g.CONNECTED;
|
|
2207
2207
|
}
|
|
2208
2208
|
/**
|
|
2209
2209
|
* 处理收到的消息
|
|
@@ -2221,9 +2221,7 @@ class X extends Nr {
|
|
|
2221
2221
|
switch (t.data = n, t.code) {
|
|
2222
2222
|
// 连接成功
|
|
2223
2223
|
case U.CONNECT_SUCCESS:
|
|
2224
|
-
|
|
2225
|
-
return;
|
|
2226
|
-
this.matchStatus = g.MATCHING, this.sendMessage(
|
|
2224
|
+
this.matchStatus === N.MATCHED || this.matchStatus === N.MATCHING ? this.matchStatus = N.UNBIND : this.matchStatus = N.MATCHING, this.sendMessage(
|
|
2227
2225
|
this.consultationTypeId,
|
|
2228
2226
|
void 0,
|
|
2229
2227
|
H.INBOUND
|
|
@@ -2232,12 +2230,12 @@ class X extends Nr {
|
|
|
2232
2230
|
// 匹配成功
|
|
2233
2231
|
case U.MATCH_INFO:
|
|
2234
2232
|
case U.MATCH_SUCCESS:
|
|
2235
|
-
if (this.matchStatus ===
|
|
2233
|
+
if (this.matchStatus === N.MATCHED)
|
|
2236
2234
|
return;
|
|
2237
|
-
this.sessionData = t.data, this.matchStatus ===
|
|
2235
|
+
this.sessionData = t.data, this.matchStatus === N.UNBIND ? (this.matchStatus = N.MATCHED, this.emit(b.MESSAGE, {
|
|
2238
2236
|
...t,
|
|
2239
2237
|
code: U.REMATCH
|
|
2240
|
-
})) : (this.matchStatus =
|
|
2238
|
+
})) : (this.matchStatus = N.MATCHED, this.getFaqList(), this.emit(b.MESSAGE, t));
|
|
2241
2239
|
break;
|
|
2242
2240
|
// 转接用户成功
|
|
2243
2241
|
case U.TRANSFER_USER_SUCCESS:
|
|
@@ -2268,7 +2266,7 @@ class X extends Nr {
|
|
|
2268
2266
|
case U.UNBIND_SUCCESS:
|
|
2269
2267
|
if (n.sessionId !== this.sessionData?.sessionId)
|
|
2270
2268
|
return;
|
|
2271
|
-
this.matchStatus =
|
|
2269
|
+
this.matchStatus = N.UNBIND, this.sessionData = null, this.emit(b.MESSAGE, t);
|
|
2272
2270
|
break;
|
|
2273
2271
|
default:
|
|
2274
2272
|
this.emit(b.MESSAGE, t);
|
|
@@ -2291,7 +2289,7 @@ class X extends Nr {
|
|
|
2291
2289
|
* @returns void
|
|
2292
2290
|
*/
|
|
2293
2291
|
scheduleReconnect() {
|
|
2294
|
-
this.clearReconnectTimer(), this.reconnectAttempts++, this.setStatus(
|
|
2292
|
+
this.config.env === "development" && console.warn("安排重连", (/* @__PURE__ */ new Date()).toISOString()), this.clearReconnectTimer(), this.reconnectAttempts++, this.setStatus(g.RECONNECTING), this.reconnectTimer = setTimeout(() => {
|
|
2295
2293
|
this.connect(this.consultationTypeId).catch((t) => {
|
|
2296
2294
|
console.error("重连失败:", t);
|
|
2297
2295
|
});
|
|
@@ -2309,10 +2307,10 @@ class X extends Nr {
|
|
|
2309
2307
|
* @returns void
|
|
2310
2308
|
*/
|
|
2311
2309
|
sendHeartbeat() {
|
|
2312
|
-
if (!(this.status !==
|
|
2310
|
+
if (!(this.status !== g.CONNECTED || !this.ws))
|
|
2313
2311
|
try {
|
|
2314
2312
|
this.ws.send("pong"), this.lastHeartbeatTime = Date.now(), this.heartbeatTimeoutTimer = setTimeout(() => {
|
|
2315
|
-
Date.now() - this.lastHeartbeatTime >= this.config.responseTimeout && (this.emit(b.HEARTBEAT_TIMEOUT), console.warn("心跳超时,尝试重连"), this.ws && this.ws.close());
|
|
2313
|
+
Date.now() - this.lastHeartbeatTime >= this.config.responseTimeout && (this.emit(b.HEARTBEAT_TIMEOUT), this.config.env === "development" && console.warn("心跳超时,尝试重连", (/* @__PURE__ */ new Date()).toISOString()), this.ws && this.ws.close());
|
|
2316
2314
|
}, this.config.responseTimeout);
|
|
2317
2315
|
} catch (t) {
|
|
2318
2316
|
console.error("发送心跳失败:", t);
|
|
@@ -2327,7 +2325,7 @@ class X extends Nr {
|
|
|
2327
2325
|
lastMsgId: t,
|
|
2328
2326
|
size: n = 50
|
|
2329
2327
|
}) {
|
|
2330
|
-
if (this.matchStatus !==
|
|
2328
|
+
if (this.matchStatus !== N.MATCHED)
|
|
2331
2329
|
return Promise.reject(A.NO_CUSTOMER_SERVICE);
|
|
2332
2330
|
const r = await yr({
|
|
2333
2331
|
sessionId: this.sessionData?.sessionId,
|
|
@@ -2344,7 +2342,7 @@ class X extends Nr {
|
|
|
2344
2342
|
* @returns Promise<ConsultationList>
|
|
2345
2343
|
*/
|
|
2346
2344
|
async getConsultationList(t) {
|
|
2347
|
-
return (await
|
|
2345
|
+
return (await wr({ entranceId: t })).data;
|
|
2348
2346
|
}
|
|
2349
2347
|
handleUploadFile(t) {
|
|
2350
2348
|
return new Promise(async (n, r) => {
|
|
@@ -2357,8 +2355,8 @@ class X extends Nr {
|
|
|
2357
2355
|
} else {
|
|
2358
2356
|
const S = new FormData();
|
|
2359
2357
|
S.append("key", u), S.append("AccessKeyId", i), S.append("signature", c), S.append("policy", d), S.append("file", t);
|
|
2360
|
-
const
|
|
2361
|
-
|
|
2358
|
+
const T = await Er(S);
|
|
2359
|
+
T.status === 204 ? n(`${u}`) : r(T.data);
|
|
2362
2360
|
}
|
|
2363
2361
|
});
|
|
2364
2362
|
}
|
|
@@ -2402,9 +2400,9 @@ class X extends Nr {
|
|
|
2402
2400
|
}), s.load();
|
|
2403
2401
|
});
|
|
2404
2402
|
async getFaqList() {
|
|
2405
|
-
if (this.matchStatus !==
|
|
2403
|
+
if (this.matchStatus !== N.MATCHED)
|
|
2406
2404
|
return Promise.reject(A.NO_CUSTOMER_SERVICE);
|
|
2407
|
-
const t = await
|
|
2405
|
+
const t = await Tr({ id: this.sessionData?.cid });
|
|
2408
2406
|
if (!t.data?.topic?.length)
|
|
2409
2407
|
return;
|
|
2410
2408
|
const n = {
|
|
@@ -2474,10 +2472,10 @@ class X extends Nr {
|
|
|
2474
2472
|
}
|
|
2475
2473
|
export {
|
|
2476
2474
|
M as ChatType,
|
|
2477
|
-
|
|
2475
|
+
g as ConnectionStatus,
|
|
2478
2476
|
b as EventType,
|
|
2479
2477
|
X as JoyTalk,
|
|
2480
|
-
|
|
2478
|
+
N as MatchStatus,
|
|
2481
2479
|
U as MessageCode,
|
|
2482
2480
|
H as MessageType,
|
|
2483
2481
|
De as SendUserType,
|
package/dist/index.umd.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
(function(U,X){typeof exports=="object"&&typeof module<"u"?X(exports):typeof define=="function"&&define.amd?define(["exports"],X):(U=typeof globalThis<"u"?globalThis:U||self,X(U.JoyTalk={}))})(this,(function(U){"use strict";function X(e,t){return function(){return e.apply(t,arguments)}}const{toString:Dt}=Object.prototype,{getPrototypeOf:be}=Object,{iterator:ce,toStringTag:He}=Symbol,le=(e=>t=>{const n=Dt.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),x=e=>(e=e.toLowerCase(),t=>le(t)===e),ue=e=>t=>typeof t===e,{isArray:Y}=Array,Q=ue("undefined");function ne(e){return e!==null&&!Q(e)&&e.constructor!==null&&!Q(e.constructor)&&_(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ve=x("ArrayBuffer");function It(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ve(e.buffer),t}const Lt=ue("string"),_=ue("function"),je=ue("number"),re=e=>e!==null&&typeof e=="object",Ft=e=>e===!0||e===!1,fe=e=>{if(le(e)!=="object")return!1;const t=be(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(He in e)&&!(ce in e)},Pt=e=>{if(!re(e)||ne(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},xt=x("Date"),Bt=x("File"),kt=x("Blob"),Ht=x("FileList"),vt=e=>re(e)&&_(e.pipe),jt=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||_(e.append)&&((t=le(e))==="formdata"||t==="object"&&_(e.toString)&&e.toString()==="[object FormData]"))},Mt=x("URLSearchParams"),[$t,qt,Gt,zt]=["ReadableStream","Request","Response","Headers"].map(x),Jt=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function se(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,s;if(typeof e!="object"&&(e=[e]),Y(e))for(r=0,s=e.length;r<s;r++)t.call(null,e[r],r,e);else{if(ne(e))return;const o=n?Object.getOwnPropertyNames(e):Object.keys(e),i=o.length;let c;for(r=0;r<i;r++)c=o[r],t.call(null,e[c],c,e)}}function Me(e,t){if(ne(e))return null;t=t.toLowerCase();const n=Object.keys(e);let r=n.length,s;for(;r-- >0;)if(s=n[r],t===s.toLowerCase())return s;return null}const z=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,$e=e=>!Q(e)&&e!==z;function Ne(){const{caseless:e,skipUndefined:t}=$e(this)&&this||{},n={},r=(s,o)=>{const i=e&&Me(n,o)||o;fe(n[i])&&fe(s)?n[i]=Ne(n[i],s):fe(s)?n[i]=Ne({},s):Y(s)?n[i]=s.slice():(!t||!Q(s))&&(n[i]=s)};for(let s=0,o=arguments.length;s<o;s++)arguments[s]&&se(arguments[s],r);return n}const Wt=(e,t,n,{allOwnKeys:r}={})=>(se(t,(s,o)=>{n&&_(s)?e[o]=X(s,n):e[o]=s},{allOwnKeys:r}),e),Vt=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Kt=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Xt=(e,t,n,r)=>{let s,o,i;const c={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),o=s.length;o-- >0;)i=s[o],(!r||r(i,e,t))&&!c[i]&&(t[i]=e[i],c[i]=!0);e=n!==!1&&be(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},Yt=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},Qt=e=>{if(!e)return null;if(Y(e))return e;let t=e.length;if(!je(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Zt=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&be(Uint8Array)),en=(e,t)=>{const r=(e&&e[ce]).call(e);let s;for(;(s=r.next())&&!s.done;){const o=s.value;t.call(e,o[0],o[1])}},tn=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},nn=x("HTMLFormElement"),rn=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),qe=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),sn=x("RegExp"),Ge=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};se(n,(s,o)=>{let i;(i=t(s,o,e))!==!1&&(r[o]=i||s)}),Object.defineProperties(e,r)},on=e=>{Ge(e,(t,n)=>{if(_(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(_(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},an=(e,t)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return Y(e)?r(e):r(String(e).split(t)),n},cn=()=>{},ln=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function un(e){return!!(e&&_(e.append)&&e[He]==="FormData"&&e[ce])}const fn=e=>{const t=new Array(10),n=(r,s)=>{if(re(r)){if(t.indexOf(r)>=0)return;if(ne(r))return r;if(!("toJSON"in r)){t[s]=r;const o=Y(r)?[]:{};return se(r,(i,c)=>{const d=n(i,s+1);!Q(d)&&(o[c]=d)}),t[s]=void 0,o}}return r};return n(e,0)},dn=x("AsyncFunction"),hn=e=>e&&(re(e)||_(e))&&_(e.then)&&_(e.catch),ze=((e,t)=>e?setImmediate:t?((n,r)=>(z.addEventListener("message",({source:s,data:o})=>{s===z&&o===n&&r.length&&r.shift()()},!1),s=>{r.push(s),z.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",_(z.postMessage)),pn=typeof queueMicrotask<"u"?queueMicrotask.bind(z):typeof process<"u"&&process.nextTick||ze,a={isArray:Y,isArrayBuffer:ve,isBuffer:ne,isFormData:jt,isArrayBufferView:It,isString:Lt,isNumber:je,isBoolean:Ft,isObject:re,isPlainObject:fe,isEmptyObject:Pt,isReadableStream:$t,isRequest:qt,isResponse:Gt,isHeaders:zt,isUndefined:Q,isDate:xt,isFile:Bt,isBlob:kt,isRegExp:sn,isFunction:_,isStream:vt,isURLSearchParams:Mt,isTypedArray:Zt,isFileList:Ht,forEach:se,merge:Ne,extend:Wt,trim:Jt,stripBOM:Vt,inherits:Kt,toFlatObject:Xt,kindOf:le,kindOfTest:x,endsWith:Yt,toArray:Qt,forEachEntry:en,matchAll:tn,isHTMLForm:nn,hasOwnProperty:qe,hasOwnProp:qe,reduceDescriptors:Ge,freezeMethods:on,toObjectSet:an,toCamelCase:rn,noop:cn,toFiniteNumber:ln,findKey:Me,global:z,isContextDefined:$e,isSpecCompliantForm:un,toJSONObject:fn,isAsyncFn:dn,isThenable:hn,setImmediate:ze,asap:pn,isIterable:e=>e!=null&&_(e[ce])};function E(e,t,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s,this.status=s.status?s.status:null)}a.inherits(E,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:a.toJSONObject(this.config),code:this.code,status:this.status}}});const Je=E.prototype,We={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{We[e]={value:e}}),Object.defineProperties(E,We),Object.defineProperty(Je,"isAxiosError",{value:!0}),E.from=(e,t,n,r,s,o)=>{const i=Object.create(Je);a.toFlatObject(e,i,function(l){return l!==Error.prototype},u=>u!=="isAxiosError");const c=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return E.call(i,c,d,n,r,s),e&&i.cause==null&&Object.defineProperty(i,"cause",{value:e,configurable:!0}),i.name=e&&e.name||"Error",o&&Object.assign(i,o),i};const mn=null;function ge(e){return a.isPlainObject(e)||a.isArray(e)}function Ve(e){return a.endsWith(e,"[]")?e.slice(0,-2):e}function Ke(e,t,n){return e?e.concat(t).map(function(s,o){return s=Ve(s),!n&&o?"["+s+"]":s}).join(n?".":""):t}function En(e){return a.isArray(e)&&!e.some(ge)}const Sn=a.toFlatObject(a,{},null,function(t){return/^is[A-Z]/.test(t)});function de(e,t,n){if(!a.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=a.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,p){return!a.isUndefined(p[m])});const r=n.metaTokens,s=n.visitor||l,o=n.dots,i=n.indexes,d=(n.Blob||typeof Blob<"u"&&Blob)&&a.isSpecCompliantForm(t);if(!a.isFunction(s))throw new TypeError("visitor must be a function");function u(f){if(f===null)return"";if(a.isDate(f))return f.toISOString();if(a.isBoolean(f))return f.toString();if(!d&&a.isBlob(f))throw new E("Blob is not supported. Use a Buffer instead.");return a.isArrayBuffer(f)||a.isTypedArray(f)?d&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function l(f,m,p){let y=f;if(f&&!p&&typeof f=="object"){if(a.endsWith(m,"{}"))m=r?m:m.slice(0,-2),f=JSON.stringify(f);else if(a.isArray(f)&&En(f)||(a.isFileList(f)||a.endsWith(m,"[]"))&&(y=a.toArray(f)))return m=Ve(m),y.forEach(function(A,I){!(a.isUndefined(A)||A===null)&&t.append(i===!0?Ke([m],I,o):i===null?m:m+"[]",u(A))}),!1}return ge(f)?!0:(t.append(Ke(p,m,o),u(f)),!1)}const h=[],S=Object.assign(Sn,{defaultVisitor:l,convertValue:u,isVisitable:ge});function w(f,m){if(!a.isUndefined(f)){if(h.indexOf(f)!==-1)throw Error("Circular reference detected in "+m.join("."));h.push(f),a.forEach(f,function(y,F){(!(a.isUndefined(y)||y===null)&&s.call(t,y,a.isString(F)?F.trim():F,m,S))===!0&&w(y,m?m.concat(F):[F])}),h.pop()}}if(!a.isObject(e))throw new TypeError("data must be an object");return w(e),t}function Xe(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Oe(e,t){this._pairs=[],e&&de(e,this,t)}const Ye=Oe.prototype;Ye.append=function(t,n){this._pairs.push([t,n])},Ye.toString=function(t){const n=t?function(r){return t.call(this,r,Xe)}:Xe;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function Tn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Qe(e,t,n){if(!t)return e;const r=n&&n.encode||Tn;a.isFunction(n)&&(n={serialize:n});const s=n&&n.serialize;let o;if(s?o=s(t,n):o=a.isURLSearchParams(t)?t.toString():new Oe(t,n).toString(r),o){const i=e.indexOf("#");i!==-1&&(e=e.slice(0,i)),e+=(e.indexOf("?")===-1?"?":"&")+o}return e}class Ze{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){a.forEach(this.handlers,function(r){r!==null&&t(r)})}}const et={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},wn={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:Oe,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Ce=typeof window<"u"&&typeof document<"u",Ue=typeof navigator=="object"&&navigator||void 0,yn=Ce&&(!Ue||["ReactNative","NativeScript","NS"].indexOf(Ue.product)<0),Rn=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",An=Ce&&window.location.href||"http://localhost",N={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ce,hasStandardBrowserEnv:yn,hasStandardBrowserWebWorkerEnv:Rn,navigator:Ue,origin:An},Symbol.toStringTag,{value:"Module"})),...wn};function bn(e,t){return de(e,new N.classes.URLSearchParams,{visitor:function(n,r,s,o){return N.isNode&&a.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...t})}function Nn(e){return a.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gn(e){const t={},n=Object.keys(e);let r;const s=n.length;let o;for(r=0;r<s;r++)o=n[r],t[o]=e[o];return t}function tt(e){function t(n,r,s,o){let i=n[o++];if(i==="__proto__")return!0;const c=Number.isFinite(+i),d=o>=n.length;return i=!i&&a.isArray(s)?s.length:i,d?(a.hasOwnProp(s,i)?s[i]=[s[i],r]:s[i]=r,!c):((!s[i]||!a.isObject(s[i]))&&(s[i]=[]),t(n,r,s[i],o)&&a.isArray(s[i])&&(s[i]=gn(s[i])),!c)}if(a.isFormData(e)&&a.isFunction(e.entries)){const n={};return a.forEachEntry(e,(r,s)=>{t(Nn(r),s,n,0)}),n}return null}function On(e,t,n){if(a.isString(e))try{return(t||JSON.parse)(e),a.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const oe={transitional:et,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=a.isObject(t);if(o&&a.isHTMLForm(t)&&(t=new FormData(t)),a.isFormData(t))return s?JSON.stringify(tt(t)):t;if(a.isArrayBuffer(t)||a.isBuffer(t)||a.isStream(t)||a.isFile(t)||a.isBlob(t)||a.isReadableStream(t))return t;if(a.isArrayBufferView(t))return t.buffer;if(a.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return bn(t,this.formSerializer).toString();if((c=a.isFileList(t))||r.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return de(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),On(t)):t}],transformResponse:[function(t){const n=this.transitional||oe.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(a.isResponse(t)||a.isReadableStream(t))return t;if(t&&a.isString(t)&&(r&&!this.responseType||s)){const i=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(t,this.parseReviver)}catch(c){if(i)throw c.name==="SyntaxError"?E.from(c,E.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:N.classes.FormData,Blob:N.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};a.forEach(["delete","get","head","post","put","patch"],e=>{oe.headers[e]={}});const Cn=a.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Un=e=>{const t={};let n,r,s;return e&&e.split(`
|
|
1
|
+
(function(U,X){typeof exports=="object"&&typeof module<"u"?X(exports):typeof define=="function"&&define.amd?define(["exports"],X):(U=typeof globalThis<"u"?globalThis:U||self,X(U.JoyTalk={}))})(this,(function(U){"use strict";function X(e,t){return function(){return e.apply(t,arguments)}}const{toString:Dt}=Object.prototype,{getPrototypeOf:be}=Object,{iterator:ce,toStringTag:He}=Symbol,le=(e=>t=>{const n=Dt.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),x=e=>(e=e.toLowerCase(),t=>le(t)===e),ue=e=>t=>typeof t===e,{isArray:Y}=Array,Q=ue("undefined");function ne(e){return e!==null&&!Q(e)&&e.constructor!==null&&!Q(e.constructor)&&_(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ve=x("ArrayBuffer");function It(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ve(e.buffer),t}const Lt=ue("string"),_=ue("function"),je=ue("number"),re=e=>e!==null&&typeof e=="object",Ft=e=>e===!0||e===!1,fe=e=>{if(le(e)!=="object")return!1;const t=be(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(He in e)&&!(ce in e)},Pt=e=>{if(!re(e)||ne(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},xt=x("Date"),Bt=x("File"),kt=x("Blob"),Ht=x("FileList"),vt=e=>re(e)&&_(e.pipe),jt=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||_(e.append)&&((t=le(e))==="formdata"||t==="object"&&_(e.toString)&&e.toString()==="[object FormData]"))},Mt=x("URLSearchParams"),[$t,qt,Gt,zt]=["ReadableStream","Request","Response","Headers"].map(x),Jt=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function se(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,s;if(typeof e!="object"&&(e=[e]),Y(e))for(r=0,s=e.length;r<s;r++)t.call(null,e[r],r,e);else{if(ne(e))return;const o=n?Object.getOwnPropertyNames(e):Object.keys(e),i=o.length;let c;for(r=0;r<i;r++)c=o[r],t.call(null,e[c],c,e)}}function Me(e,t){if(ne(e))return null;t=t.toLowerCase();const n=Object.keys(e);let r=n.length,s;for(;r-- >0;)if(s=n[r],t===s.toLowerCase())return s;return null}const z=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,$e=e=>!Q(e)&&e!==z;function Ne(){const{caseless:e,skipUndefined:t}=$e(this)&&this||{},n={},r=(s,o)=>{const i=e&&Me(n,o)||o;fe(n[i])&&fe(s)?n[i]=Ne(n[i],s):fe(s)?n[i]=Ne({},s):Y(s)?n[i]=s.slice():(!t||!Q(s))&&(n[i]=s)};for(let s=0,o=arguments.length;s<o;s++)arguments[s]&&se(arguments[s],r);return n}const Wt=(e,t,n,{allOwnKeys:r}={})=>(se(t,(s,o)=>{n&&_(s)?e[o]=X(s,n):e[o]=s},{allOwnKeys:r}),e),Vt=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Kt=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Xt=(e,t,n,r)=>{let s,o,i;const c={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),o=s.length;o-- >0;)i=s[o],(!r||r(i,e,t))&&!c[i]&&(t[i]=e[i],c[i]=!0);e=n!==!1&&be(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},Yt=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},Qt=e=>{if(!e)return null;if(Y(e))return e;let t=e.length;if(!je(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Zt=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&be(Uint8Array)),en=(e,t)=>{const r=(e&&e[ce]).call(e);let s;for(;(s=r.next())&&!s.done;){const o=s.value;t.call(e,o[0],o[1])}},tn=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},nn=x("HTMLFormElement"),rn=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),qe=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),sn=x("RegExp"),Ge=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};se(n,(s,o)=>{let i;(i=t(s,o,e))!==!1&&(r[o]=i||s)}),Object.defineProperties(e,r)},on=e=>{Ge(e,(t,n)=>{if(_(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(_(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},an=(e,t)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return Y(e)?r(e):r(String(e).split(t)),n},cn=()=>{},ln=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function un(e){return!!(e&&_(e.append)&&e[He]==="FormData"&&e[ce])}const fn=e=>{const t=new Array(10),n=(r,s)=>{if(re(r)){if(t.indexOf(r)>=0)return;if(ne(r))return r;if(!("toJSON"in r)){t[s]=r;const o=Y(r)?[]:{};return se(r,(i,c)=>{const d=n(i,s+1);!Q(d)&&(o[c]=d)}),t[s]=void 0,o}}return r};return n(e,0)},dn=x("AsyncFunction"),hn=e=>e&&(re(e)||_(e))&&_(e.then)&&_(e.catch),ze=((e,t)=>e?setImmediate:t?((n,r)=>(z.addEventListener("message",({source:s,data:o})=>{s===z&&o===n&&r.length&&r.shift()()},!1),s=>{r.push(s),z.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",_(z.postMessage)),pn=typeof queueMicrotask<"u"?queueMicrotask.bind(z):typeof process<"u"&&process.nextTick||ze,a={isArray:Y,isArrayBuffer:ve,isBuffer:ne,isFormData:jt,isArrayBufferView:It,isString:Lt,isNumber:je,isBoolean:Ft,isObject:re,isPlainObject:fe,isEmptyObject:Pt,isReadableStream:$t,isRequest:qt,isResponse:Gt,isHeaders:zt,isUndefined:Q,isDate:xt,isFile:Bt,isBlob:kt,isRegExp:sn,isFunction:_,isStream:vt,isURLSearchParams:Mt,isTypedArray:Zt,isFileList:Ht,forEach:se,merge:Ne,extend:Wt,trim:Jt,stripBOM:Vt,inherits:Kt,toFlatObject:Xt,kindOf:le,kindOfTest:x,endsWith:Yt,toArray:Qt,forEachEntry:en,matchAll:tn,isHTMLForm:nn,hasOwnProperty:qe,hasOwnProp:qe,reduceDescriptors:Ge,freezeMethods:on,toObjectSet:an,toCamelCase:rn,noop:cn,toFiniteNumber:ln,findKey:Me,global:z,isContextDefined:$e,isSpecCompliantForm:un,toJSONObject:fn,isAsyncFn:dn,isThenable:hn,setImmediate:ze,asap:pn,isIterable:e=>e!=null&&_(e[ce])};function E(e,t,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s,this.status=s.status?s.status:null)}a.inherits(E,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:a.toJSONObject(this.config),code:this.code,status:this.status}}});const Je=E.prototype,We={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{We[e]={value:e}}),Object.defineProperties(E,We),Object.defineProperty(Je,"isAxiosError",{value:!0}),E.from=(e,t,n,r,s,o)=>{const i=Object.create(Je);a.toFlatObject(e,i,function(l){return l!==Error.prototype},u=>u!=="isAxiosError");const c=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return E.call(i,c,d,n,r,s),e&&i.cause==null&&Object.defineProperty(i,"cause",{value:e,configurable:!0}),i.name=e&&e.name||"Error",o&&Object.assign(i,o),i};const mn=null;function ge(e){return a.isPlainObject(e)||a.isArray(e)}function Ve(e){return a.endsWith(e,"[]")?e.slice(0,-2):e}function Ke(e,t,n){return e?e.concat(t).map(function(s,o){return s=Ve(s),!n&&o?"["+s+"]":s}).join(n?".":""):t}function En(e){return a.isArray(e)&&!e.some(ge)}const Sn=a.toFlatObject(a,{},null,function(t){return/^is[A-Z]/.test(t)});function de(e,t,n){if(!a.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=a.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,p){return!a.isUndefined(p[m])});const r=n.metaTokens,s=n.visitor||l,o=n.dots,i=n.indexes,d=(n.Blob||typeof Blob<"u"&&Blob)&&a.isSpecCompliantForm(t);if(!a.isFunction(s))throw new TypeError("visitor must be a function");function u(f){if(f===null)return"";if(a.isDate(f))return f.toISOString();if(a.isBoolean(f))return f.toString();if(!d&&a.isBlob(f))throw new E("Blob is not supported. Use a Buffer instead.");return a.isArrayBuffer(f)||a.isTypedArray(f)?d&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function l(f,m,p){let y=f;if(f&&!p&&typeof f=="object"){if(a.endsWith(m,"{}"))m=r?m:m.slice(0,-2),f=JSON.stringify(f);else if(a.isArray(f)&&En(f)||(a.isFileList(f)||a.endsWith(m,"[]"))&&(y=a.toArray(f)))return m=Ve(m),y.forEach(function(A,I){!(a.isUndefined(A)||A===null)&&t.append(i===!0?Ke([m],I,o):i===null?m:m+"[]",u(A))}),!1}return ge(f)?!0:(t.append(Ke(p,m,o),u(f)),!1)}const h=[],S=Object.assign(Sn,{defaultVisitor:l,convertValue:u,isVisitable:ge});function w(f,m){if(!a.isUndefined(f)){if(h.indexOf(f)!==-1)throw Error("Circular reference detected in "+m.join("."));h.push(f),a.forEach(f,function(y,F){(!(a.isUndefined(y)||y===null)&&s.call(t,y,a.isString(F)?F.trim():F,m,S))===!0&&w(y,m?m.concat(F):[F])}),h.pop()}}if(!a.isObject(e))throw new TypeError("data must be an object");return w(e),t}function Xe(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Oe(e,t){this._pairs=[],e&&de(e,this,t)}const Ye=Oe.prototype;Ye.append=function(t,n){this._pairs.push([t,n])},Ye.toString=function(t){const n=t?function(r){return t.call(this,r,Xe)}:Xe;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function Tn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Qe(e,t,n){if(!t)return e;const r=n&&n.encode||Tn;a.isFunction(n)&&(n={serialize:n});const s=n&&n.serialize;let o;if(s?o=s(t,n):o=a.isURLSearchParams(t)?t.toString():new Oe(t,n).toString(r),o){const i=e.indexOf("#");i!==-1&&(e=e.slice(0,i)),e+=(e.indexOf("?")===-1?"?":"&")+o}return e}class Ze{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){a.forEach(this.handlers,function(r){r!==null&&t(r)})}}const et={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},wn={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:Oe,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Ce=typeof window<"u"&&typeof document<"u",Ue=typeof navigator=="object"&&navigator||void 0,yn=Ce&&(!Ue||["ReactNative","NativeScript","NS"].indexOf(Ue.product)<0),Rn=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",An=Ce&&window.location.href||"http://localhost",g={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ce,hasStandardBrowserEnv:yn,hasStandardBrowserWebWorkerEnv:Rn,navigator:Ue,origin:An},Symbol.toStringTag,{value:"Module"})),...wn};function bn(e,t){return de(e,new g.classes.URLSearchParams,{visitor:function(n,r,s,o){return g.isNode&&a.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...t})}function Nn(e){return a.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gn(e){const t={},n=Object.keys(e);let r;const s=n.length;let o;for(r=0;r<s;r++)o=n[r],t[o]=e[o];return t}function tt(e){function t(n,r,s,o){let i=n[o++];if(i==="__proto__")return!0;const c=Number.isFinite(+i),d=o>=n.length;return i=!i&&a.isArray(s)?s.length:i,d?(a.hasOwnProp(s,i)?s[i]=[s[i],r]:s[i]=r,!c):((!s[i]||!a.isObject(s[i]))&&(s[i]=[]),t(n,r,s[i],o)&&a.isArray(s[i])&&(s[i]=gn(s[i])),!c)}if(a.isFormData(e)&&a.isFunction(e.entries)){const n={};return a.forEachEntry(e,(r,s)=>{t(Nn(r),s,n,0)}),n}return null}function On(e,t,n){if(a.isString(e))try{return(t||JSON.parse)(e),a.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const oe={transitional:et,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=a.isObject(t);if(o&&a.isHTMLForm(t)&&(t=new FormData(t)),a.isFormData(t))return s?JSON.stringify(tt(t)):t;if(a.isArrayBuffer(t)||a.isBuffer(t)||a.isStream(t)||a.isFile(t)||a.isBlob(t)||a.isReadableStream(t))return t;if(a.isArrayBufferView(t))return t.buffer;if(a.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return bn(t,this.formSerializer).toString();if((c=a.isFileList(t))||r.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return de(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),On(t)):t}],transformResponse:[function(t){const n=this.transitional||oe.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(a.isResponse(t)||a.isReadableStream(t))return t;if(t&&a.isString(t)&&(r&&!this.responseType||s)){const i=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(t,this.parseReviver)}catch(c){if(i)throw c.name==="SyntaxError"?E.from(c,E.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:g.classes.FormData,Blob:g.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};a.forEach(["delete","get","head","post","put","patch"],e=>{oe.headers[e]={}});const Cn=a.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Un=e=>{const t={};let n,r,s;return e&&e.split(`
|
|
2
2
|
`).forEach(function(i){s=i.indexOf(":"),n=i.substring(0,s).trim().toLowerCase(),r=i.substring(s+1).trim(),!(!n||t[n]&&Cn[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},nt=Symbol("internals");function ie(e){return e&&String(e).trim().toLowerCase()}function he(e){return e===!1||e==null?e:a.isArray(e)?e.map(he):String(e)}function _n(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const Dn=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function _e(e,t,n,r,s){if(a.isFunction(r))return r.call(this,t,n);if(s&&(t=n),!!a.isString(t)){if(a.isString(r))return t.indexOf(r)!==-1;if(a.isRegExp(r))return r.test(t)}}function In(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function Ln(e,t){const n=a.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(s,o,i){return this[r].call(this,t,s,o,i)},configurable:!0})})}let D=class{constructor(t){t&&this.set(t)}set(t,n,r){const s=this;function o(c,d,u){const l=ie(d);if(!l)throw new Error("header name must be a non-empty string");const h=a.findKey(s,l);(!h||s[h]===void 0||u===!0||u===void 0&&s[h]!==!1)&&(s[h||d]=he(c))}const i=(c,d)=>a.forEach(c,(u,l)=>o(u,l,d));if(a.isPlainObject(t)||t instanceof this.constructor)i(t,n);else if(a.isString(t)&&(t=t.trim())&&!Dn(t))i(Un(t),n);else if(a.isObject(t)&&a.isIterable(t)){let c={},d,u;for(const l of t){if(!a.isArray(l))throw TypeError("Object iterator must return a key-value pair");c[u=l[0]]=(d=c[u])?a.isArray(d)?[...d,l[1]]:[d,l[1]]:l[1]}i(c,n)}else t!=null&&o(n,t,r);return this}get(t,n){if(t=ie(t),t){const r=a.findKey(this,t);if(r){const s=this[r];if(!n)return s;if(n===!0)return _n(s);if(a.isFunction(n))return n.call(this,s,r);if(a.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ie(t),t){const r=a.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||_e(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let s=!1;function o(i){if(i=ie(i),i){const c=a.findKey(r,i);c&&(!n||_e(r,r[c],c,n))&&(delete r[c],s=!0)}}return a.isArray(t)?t.forEach(o):o(t),s}clear(t){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!t||_e(this,this[o],o,t,!0))&&(delete this[o],s=!0)}return s}normalize(t){const n=this,r={};return a.forEach(this,(s,o)=>{const i=a.findKey(r,o);if(i){n[i]=he(s),delete n[o];return}const c=t?In(o):String(o).trim();c!==o&&delete n[o],n[c]=he(s),r[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return a.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=t&&a.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
|
|
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=N.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,N.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(N.origin),N.navigator&&/(msie|trident)/i.test(N.navigator.userAgent)):()=>!0,kn=N.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(N.hasStandardBrowserEnv||N.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(N.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 y(){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=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},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&&N.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(N.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 y=m&&m[f];if(y)return y.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(N.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:y,signal:F,cancelToken:A,timeout:I,onDownloadProgress:B,onUploadProgress:V,responseType:P,headers:Be,withCredentials:ye="same-origin",fetchOptions:bt}=lt(f),Nt=t||fetch;P=P?(P+"").toLowerCase():"text";let Re=Mn([F,A&&A.toAbortSignal()],I),ae=null;const K=Re&&Re.unsubscribe&&(()=>{Re.unsubscribe()});let gt;try{if(V&&u&&p!=="get"&&p!=="head"&&(gt=await w(Be,y))!==0){let G=new n(m,{method:"POST",body:y,duplex:"half"}),te;if(a.isFormData(y)&&(te=G.headers.get("content-type"))&&Be.setContentType(te),G.body){const[ke,Ae]=ot(gt,pe(it(V)));y=ut(G.body,ft,ke,Ae)}}a.isString(ye)||(ye=ye?"include":"omit");const v=o&&"credentials"in n.prototype,Ot={...bt,signal:Re,method:p.toUpperCase(),headers:Be.normalize().toJSON(),body:y,duplex:"half",credentials:v?ye:void 0};ae=o&&new n(m,Ot);let q=await(o?Nt(ae,bt):Nt(m,Ot));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 :
|
|
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=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,kn=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 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(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&&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 y(){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=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},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&&g.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(g.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 y=m&&m[f];if(y)return y.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:y,signal:F,cancelToken:A,timeout:I,onDownloadProgress:B,onUploadProgress:V,responseType:P,headers:Be,withCredentials:ye="same-origin",fetchOptions:bt}=lt(f),Nt=t||fetch;P=P?(P+"").toLowerCase():"text";let Re=Mn([F,A&&A.toAbortSignal()],I),ae=null;const K=Re&&Re.unsubscribe&&(()=>{Re.unsubscribe()});let gt;try{if(V&&u&&p!=="get"&&p!=="head"&&(gt=await w(Be,y))!==0){let G=new n(m,{method:"POST",body:y,duplex:"half"}),te;if(a.isFormData(y)&&(te=G.headers.get("content-type"))&&Be.setContentType(te),G.body){const[ke,Ae]=ot(gt,pe(it(V)));y=ut(G.body,ft,ke,Ae)}}a.isString(ye)||(ye=ye?"include":"omit");const v=o&&"credentials"in n.prototype,Ot={...bt,signal:Re,method:p.toUpperCase(),headers:Be.normalize().toJSON(),body:y,duplex:"half",credentials:v?ye:void 0};ae=o&&new n(m,Ot);let q=await(o?Nt(ae,bt):Nt(m,Ot));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 yt={};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&&!yt[i]&&(yt[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 Rt(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 Rt(J(e,s))},n}const T=Rt(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-05.halaladmin.vip"},prodtest:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img-05.halaladmin.vip"},production:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img-05.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.REMATCH=60001]="REMATCH",e))(C||{}),we=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(we||{}),R=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(R||{}),g=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(g||{}),O=(e=>(e.UNMATCHED="1",e.MATCHING="2",e.MATCHED="3",e.UNBIND="4",e))(O||{});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 yr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function Rr(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=O.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(R.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(R.ERROR,o),r(o)},this.ws.onclose=()=>{this.setStatus(g.DISCONNECTED),this.emit(R.DISCONNECTED),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(g.ERROR),this.emit(R.ERROR,s),r(s)}}})}disconnect(){this.config.autoReconnect=!1,this.sessionData=null,this.matchStatus=O.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=yr();s.ext=c;const d=await Sr({ext:c});console.log("🚀 ~ JoyTalk ~ sendMessage ~ res:",d.data.messageId),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===O.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(R.MESSAGE,s=>{s.code===C.REMATCH&&(clearTimeout(r),t(!0))})})),this.matchStatus!==O.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),!!Rr(t))try{const n=t.data?JSON.parse(t.data):t.data;switch(t.data=n,t.code){case C.CONNECT_SUCCESS:if(this.matchStatus===O.MATCHED||this.matchStatus===O.MATCHING)return;this.matchStatus=O.MATCHING,this.sendMessage(this.consultationTypeId,void 0,H.INBOUND);break;case C.MATCH_INFO:case C.MATCH_SUCCESS:if(this.matchStatus===O.MATCHED)return;this.sessionData=t.data,this.matchStatus===O.UNBIND?(this.matchStatus=O.MATCHED,this.emit(R.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=O.MATCHED,this.getFaqList(),this.emit(R.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(R.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(R.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=O.UNBIND,this.sessionData=null,this.emit(R.MESSAGE,t);break;default:this.emit(R.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}setStatus(t){this.status!==t&&(this.status=t,this.emit(R.STATUS_CHANGE,t))}scheduleReconnect(){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(R.HEARTBEAT_TIMEOUT),console.warn("心跳超时,尝试重连"),this.ws&&this.ws.close())},this.config.responseTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=50}){if(this.matchStatus!==O.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!==O.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(R.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(R.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(R.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=R,U.JoyTalk=$,U.MatchStatus=O,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 Rt(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 Rt(J(e,s))},n}const T=Rt(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.REMATCH=60001]="REMATCH",e))(C||{}),we=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(we||{}),R=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(R||{}),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 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 yr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function Rr(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=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 wr(this.config.token,this.config.env);this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(O.CONNECTED),this.emit(R.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(R.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(O.DISCONNECTED),this.emit(R.DISCONNECTED),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(O.ERROR),this.emit(R.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=yr();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(R.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===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),!!Rr(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(R.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=N.MATCHED,this.getFaqList(),this.emit(R.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(R.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(R.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(R.MESSAGE,t);break;default:this.emit(R.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}setStatus(t){this.status!==t&&(this.status=t,this.emit(R.STATUS_CHANGE,t))}scheduleReconnect(){this.config.env==="development"&&console.warn("安排重连",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(R.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(R.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(R.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(R.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=O,U.EventType=R,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"}})}));
|