joytalk 0.0.40 → 0.0.41

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 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[Ve]=this[Ve]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=ne(i);r[c]||(vn(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||ie,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 ee(e,t,n){E.call(this,e??"canceled",E.ERR_CANCELED,t,n),this.name="CanceledError"}a.inherits(ee,E,{__CANCEL__:!0});function At(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 jn(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 Mn(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=jn(50,250);return Mn(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]]},Ke=e=>(...t)=>a.asap(()=>e(...t)),$n=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,qn=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 Gn(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function zn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function bt(e,t,n){let r=!Gn(t);return e&&(r||n==!1)?zn(e,t):t}const Xe=e=>e instanceof D?{...e}:e;function K(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(Xe(u),Xe(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 gt=e=>{const t=K({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:c}=t;if(t.headers=i=D.from(i),t.url=Tt(bt(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&&$n(t.url))){const d=s&&o&&qn.read(o);d&&i.set(s,d)}return t},Jn=typeof XMLHttpRequest<"u",Vn=Jn&&function(e){return new Promise(function(n,r){const s=gt(e);let o=s.data;const i=D.from(s.headers).normalize();let{responseType:c,onUploadProgress:d,onDownloadProgress:u}=s,l,h,S,w,f;function m(){w&&w(),f&&f(),s.cancelToken&&s.cancelToken.unsubscribe(l),s.signal&&s.signal.removeEventListener("abort",l)}let p=new XMLHttpRequest;p.open(s.method.toUpperCase(),s.url,!0),p.timeout=s.timeout;function R(){if(!p)return;const y=D.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),P={data:!c||c==="text"||c==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:y,config:e,request:p};At(function(L){n(L),m()},function(L){r(L),m()},P),p=null}"onloadend"in p?p.onloadend=R:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(R)},p.onabort=function(){p&&(r(new E("Request aborted",E.ECONNABORTED,e,p)),p=null)},p.onerror=function(U){const P=U&&U.message?U.message:"Network Error",z=new E(P,E.ERR_NETWORK,e,p);z.event=U||null,r(z),p=null},p.ontimeout=function(){let U=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const P=s.transitional||wt;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]=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=y=>{p&&(r(!y||y.type?new ee(null,e,p):y),p.abort(),p=null)},s.cancelToken&&s.cancelToken.subscribe(l),s.signal&&(s.signal.aborted?l():s.signal.addEventListener("abort",l)));const I=Hn(s.url);if(I&&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 ee(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}},Kn=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},Xn=async function*(e,t){for await(const n of Yn(e))yield*Kn(n,t)},Yn=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()}},Ye=(e,t,n,r)=>{const s=Xn(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})},Qe=64*1024,{isFunction:ue}=a,Qn=(({Request:e,Response:t})=>({Request:e,Response:t}))(a.global),{ReadableStream:Ze,TextEncoder:et}=a.global,tt=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Zn=e=>{e=a.merge.call({skipUndefined:!0},Qn,e);const{fetch:t,Request:n,Response:r}=e,s=t?ue(t):typeof fetch=="function",o=ue(n),i=ue(r);if(!s)return!1;const c=s&&ue(Ze),d=s&&(typeof et=="function"?(f=>m=>f.encode(m))(new et):async f=>new Uint8Array(await new n(f).arrayBuffer())),u=o&&c&&tt(()=>{let f=!1;const m=new n(O.origin,{body:new Ze,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!m}),l=i&&c&&tt(()=>a.isReadableStream(new r("").body)),h={stream:l&&(f=>f.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!h[f]&&(h[f]=(m,p)=>{let R=m&&m[f];if(R)return R.call(m);throw new E(`Response type '${f}' is not supported`,E.ERR_NOT_SUPPORT,p)})});const S=async f=>{if(f==null)return 0;if(a.isBlob(f))return f.size;if(a.isSpecCompliantForm(f))return(await new n(O.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(a.isArrayBufferView(f)||a.isArrayBuffer(f))return f.byteLength;if(a.isURLSearchParams(f)&&(f=f+""),a.isString(f))return(await d(f)).byteLength},w=async(f,m)=>{const p=a.toFiniteNumber(f.getContentLength());return p??S(m)};return async f=>{let{url:m,method:p,data:R,signal:I,cancelToken:y,timeout:U,onDownloadProgress:P,onUploadProgress:z,responseType:L,headers:Ae,withCredentials:ae="same-origin",fetchOptions:ke}=gt(f),ve=t||fetch;L=L?(L+"").toLowerCase():"text";let ce=Wn([I,y&&y.toAbortSignal()],U),te=null;const J=ce&&ce.unsubscribe&&(()=>{ce.unsubscribe()});let He;try{if(z&&u&&p!=="get"&&p!=="head"&&(He=await w(Ae,R))!==0){let M=new n(m,{method:"POST",body:R,duplex:"half"}),X;if(a.isFormData(R)&&(X=M.headers.get("content-type"))&&Ae.setContentType(X),M.body){const[be,le]=We(He,pe(Ke(z)));R=Ye(M.body,Qe,be,le)}}a.isString(ae)||(ae=ae?"include":"omit");const B=o&&"credentials"in n.prototype,je={...ke,signal:ce,method:p.toUpperCase(),headers:Ae.normalize().toJSON(),body:R,duplex:"half",credentials:B?ae:void 0};te=o&&new n(m,je);let j=await(o?ve(te,ke):ve(m,je));const Me=l&&(L==="stream"||L==="response");if(l&&(P||Me&&J)){const M={};["status","statusText","headers"].forEach($e=>{M[$e]=j[$e]});const X=a.toFiniteNumber(j.headers.get("content-length")),[be,le]=P&&We(X,pe(Ke(P),!0))||[];j=new r(Ye(j.body,Qe,be,()=>{le&&le(),J&&J()}),M)}L=L||"text";let Dt=await h[a.findKey(h,L)||"text"](j,f);return!Me&&J&&J(),await new Promise((M,X)=>{At(M,X,{data:Dt,headers:D.from(j.headers),status:j.status,statusText:j.statusText,config:f,request:te})})}catch(B){throw J&&J(),B&&B.name==="TypeError"&&/Load failed|fetch/i.test(B.message)?Object.assign(new E("Network Error",E.ERR_NETWORK,f,te),{cause:B.cause||B}):E.from(B,B&&B.code,f,te)}}},er=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=er;for(;c--;)d=o[c],u=l.get(d),u===void 0&&l.set(d,u=c?new Map:Zn(t)),l=u;return u};Nt();const xe={http:Sn,xhr:Vn,fetch:{get:Nt}};a.forEach(xe,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const nt=e=>`- ${e}`,tr=e=>a.isFunction(e)||e===null||e===!1;function nr(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,!tr(r)&&(s=xe[(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(nt).join(`
5
5
  `):" "+nt(i[0]):"as no adapter specified";throw new E("There is no suitable adapter to dispatch the request "+c,"ERR_NOT_SUPPORT")}return s}const Ot={getAdapter:nr,adapters:xe};function Oe(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ee(null,e)}function rt(e){return Oe(e),e.headers=D.from(e.headers),e.data=Ne.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Ot.getAdapter(e.adapter||ie.adapter,e)(e).then(function(r){return Oe(e),r.data=Ne.call(e,e.transformResponse,r),r.headers=D.from(r.headers),r},function(r){return yt(r)||(Oe(e),r&&r.response&&(r.response.data=Ne.call(e,e.transformResponse,r.response),r.response.headers=D.from(r.response.headers))),Promise.reject(r)})}const Ct="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 st={};ye.transitional=function(t,n,r){function s(o,i){return"[Axios v"+Ct+"] 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&&!st[i]&&(st[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 rr(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 he={assertOptions:rr,validators:ye},k=he.validators;let W=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Je,response:new Je}}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=K(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&he.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}:he.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),he.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=[rt.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=rt.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=K(this.defaults,t);const n=bt(t.baseURL,t.url,t.allowAbsoluteUrls);return Tt(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){W.prototype[t]=function(n,r){return this.request(K(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(K(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 sr=class Ut{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 ee(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 Ut(function(s){t=s}),cancel:t}}};function or(e){return function(n){return e.apply(null,n)}}function ir(e){return a.isObject(e)&&e.isAxiosError===!0}const De={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(De).forEach(([e,t])=>{De[t]=e});function _t(e){const t=new W(e),n=it(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 _t(K(e,s))},n}const T=_t(ie);T.Axios=W;T.CanceledError=ee;T.CancelToken=sr;T.isCancel=yt;T.VERSION=Ct;T.toFormData=Re;T.AxiosError=E;T.Cancel=T.CanceledError;T.all=function(t){return Promise.all(t)};T.spread=or;T.isAxiosError=ir;T.mergeConfig=K;T.AxiosHeaders=D;T.formToJSON=e=>Rt(a.isHTMLForm(e)?new FormData(e):e);T.getAdapter=Ot.getAdapter;T.HttpStatusCode=De;T.default=T;const{Axios:Ir,AxiosError:Lr,CanceledError:Fr,isCancel:Pr,CancelToken:xr,VERSION:Br,all:kr,Cancel:vr,isAxiosError:Hr,spread:jr,toFormData:Mr,AxiosHeaders:$r,HttpStatusCode:qr,formToJSON:Gr,getAdapter:zr,mergeConfig:Jr}=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:"数据为空"}},ar="/api/customer-service/customer/v1/CustomerService/TestLineLatency",cr="/api/customer-service/customer/v1/CustomerService/ListLines",lr="/pub/logo.png",Ie={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 Y=null;function ur(e){const t=`${e.replace(/\/$/,"")}${ar}`;return T.get(t,{timeout:1e4}).then(n=>n.data?.code!==200?Promise.reject(n):e)}function fr(e){const t=`${e.replace(/\/$/,"")}${lr}`;return T.get(t,{timeout:1e4}).then(()=>e).catch(()=>Promise.reject(new Error("Download latency test failed")))}function dr(e){return e?.length?Promise.any(e.map(t=>ur(t))):Promise.reject(new Error("No urls to test"))}function hr(e){return e?.length?Promise.any(e.map(t=>fr(t))):Promise.reject(new Error("No download urls to test"))}async function Be(e,t){if(F.api&&F.download)return;if(Y)return Y;const n=Ie[t].BASE_API_URL||"",r=Ie[t].OBS_URL||"";F.api=n,F.download=r,F.ws=n.replace(/http/g,"ws"),n||(Y=Promise.reject(new Error("环境配置错误")),await Y),Y=(async()=>{const s=await T.get(`${n.replace(/\/$/,"")}${cr}`,{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?dr(o).catch(()=>c):Promise.resolve(c),i.length?hr(i).catch(()=>d):Promise.resolve(d)]);F.api=u,F.download=l,F.ws=u.replace(/http/g,"ws")})(),await Y}const G=T.create({timeout:6e5});G.interceptors.request.use(async e=>{const t=new q,n=t.config.token;return n?(e.headers.Authorization=`Bearer ${n}`,t.config.language&&(e.headers["Accept-Language"]=t.config.language),await Be(n,t.config.env),e.baseURL=F.api,e):Promise.reject(b.UNINITIALIZED)},e=>Promise.reject(e));G.interceptors.response.use(e=>e.data?.code!==200?Promise.reject(e):Promise.resolve(e.data),e=>Promise.reject(e));function pr(){return F.api}function me(){return F.download}function mr(){return F.ws}const Er=e=>G.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),Sr=async e=>{const t=me();return T.post(`${t}`,e,{headers:{"Content-Type":"multipart/form-data"}})},Tr=async(e,t)=>T.put(t,e,{headers:{"Content-Type":e.type}}),wr=e=>G.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),Rr=e=>G.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),yr=()=>G.get("/api/open-auth/user/v1/UserService/GetUserInfo"),Ar=e=>G.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e),br=e=>{const t=new q,n=t.config.env,r=pr()||Ie[n].BASE_API_URL;return T.post(`${r}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,e,{headers:t.config.language?{"Accept-Language":t.config.language}:void 0})},gr=e=>G.get("/api/chat/chat/v1/Chat/GetMsg",{params:e});var v=(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))(v||{}),H=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(H||{}),C=(e=>(e[e.CONNECT_SUCCESS=200]="CONNECT_SUCCESS",e[e.CONNECT_FAILED=40001]="CONNECT_FAILED",e[e.TRANSFER_CUSTOMER_SUCCESS=201]="TRANSFER_CUSTOMER_SUCCESS",e[e.TRANSFER_TO_CUSTOMER_SUCCESS=202]="TRANSFER_TO_CUSTOMER_SUCCESS",e[e.TRANSFER_USER_SUCCESS=203]="TRANSFER_USER_SUCCESS",e[e.TRANSFER_FAIL=50001]="TRANSFER_FAIL",e[e.MATCH_FAIL=50002]="MATCH_FAIL",e[e.MATCH_INFO=50005]="MATCH_INFO",e[e.MATCH_SUCCESS=50006]="MATCH_SUCCESS",e[e.RETRACT=204]="RETRACT",e[e.RETRACT_FAIL=50003]="RETRACT_FAIL",e[e.EDIT=205]="EDIT",e[e.EDIT_FAIL=50004]="EDIT_FAIL",e[e.COMMON_FAIL=5e4]="COMMON_FAIL",e[e.SEND_SUCCESS=206]="SEND_SUCCESS",e[e.SEND_CALLBACK=207]="SEND_CALLBACK",e[e.CHANGE_CHAT_STATUS=208]="CHANGE_CHAT_STATUS",e[e.REPLY_FAIL=50008]="REPLY_FAIL",e[e.REPLY_SUCCESS=209]="REPLY_SUCCESS",e[e.UNBIND_SUCCESS=60006]="UNBIND_SUCCESS",e[e.BAN_CUSTOMER=60007]="BAN_CUSTOMER",e[e.BAN_ENTRY=60008]="BAN_ENTRY",e[e.REMATCH=60001]="REMATCH",e))(C||{}),Ee=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(Ee||{}),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 Or(e,t){return await Be(e,t),`${await mr()}/api/ws?Authorization=${e}`}function Cr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function Ur(e){return typeof e=="object"&&e!==null&&"data"in e&&"msgType"in e&&"toUid"in e&&"chatType"in e&&"code"in e}function ot(e){return e.customerServiceAvatar=$(e.customerServiceAvatar),e.userAvatar=$(e.customerServiceAvatar),e.contentType!==H.TEXT&&(e.content=JSON.parse(e.content),e.content.fileUrl=$(e.content.fileUrl),e.content.thumbnailUrl=$(e.content.thumbnailUrl)),e.replyType&&e.replyType!==H.TEXT&&typeof e.replyContent=="string"&&(e.replyContent=JSON.parse(e.replyContent),e.replyContent.fileUrl=$(e.replyContent.fileUrl),e.replyContent.thumbnailUrl=$(e.replyContent.thumbnailUrl)),e}function $(e=""){return e&&!e.startsWith("http")?me()+"/"+e:e}class q extends Nr{config={token:"",autoReconnect:!0,reconnectInterval:3e3,maxReconnectAttempts:5,responseTimeout:15e3,env:"production",language:"en-US"};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}={}){if(super(),q.instance)return q.instance;q.instance=this,this.config.env=t||"production"}async init(t){if(!t.token)return Promise.reject(b.PARAMETER_ERROR);await Be(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 Or(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.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(N.DISCONNECTED),this.emit(A.DISCONNECTED),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(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=v.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===v.SEND?new Promise(async(o,i)=>{const c=Cr();s.ext=c;const d=await gr({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===g.UNBIND&&(await this.sendMessage(this.consultationTypeId,void 0,v.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,H.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=me();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),!!Ur(t))try{const n=t.data?JSON.parse(t.data):t.data;switch(t.data=n,t.code){case C.CONNECT_SUCCESS:this.matchStatus===g.MATCHED||this.matchStatus===g.MATCHING?this.matchStatus=g.UNBIND:this.matchStatus=g.MATCHING,this.sendMessage(this.consultationTypeId,void 0,v.INBOUND);break;case C.MATCH_INFO:case C.MATCH_SUCCESS:if(this.matchStatus===g.MATCHED)return;t.data.customerAvatar=$(t.data.customerAvatar),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;ot(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.config.env==="development"&&console.warn(`第${this.reconnectAttempts+1}次安排重连`,new Date().toISOString()),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),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!==g.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const r=await Ar({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>ot(o));return{hasMore:r.data.hasMore,list:s}}async getConsultationList(t){return(await wr({entranceId:t})).data}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await Er({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 Tr(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 Sr(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 Rr({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:H.FAQ,sendUserType:Ee.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:v.SEND},msgType:v.SEND,chatType:H.FAQ};this.emit(A.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={code:C.SEND_SUCCESS,data:{sendUserType:Ee.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:v.SEND,contentType:H.FAQ,content:{}},msgType:v.SEND,chatType:H.FAQ};if(t.isMulti)n.data.content={list:t.item},this.emit(A.MESSAGE,n);else{const r=t.item?.[0]||t,s=me();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 t.data.avatar=$(t.data.avatar),this.userInfo=t.data,this.userInfo}async anonymousLogin(t,n){return(await br({appKey:t,entranceId:n,userSource:"H5"})).data}setLanguage(t){this.config.language=t||"en-US"}}exports.ChatType=H;exports.ConnectionStatus=N;exports.EventType=A;exports.JoyTalk=q;exports.MatchStatus=g;exports.MessageCode=C;exports.MessageType=v;exports.SendUserType=Ee;exports.default=q;
6
+ `+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=K(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&he.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}:he.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),he.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=[rt.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=rt.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=K(this.defaults,t);const n=bt(t.baseURL,t.url,t.allowAbsoluteUrls);return Tt(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){W.prototype[t]=function(n,r){return this.request(K(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(K(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 sr=class Ut{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 ee(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 Ut(function(s){t=s}),cancel:t}}};function or(e){return function(n){return e.apply(null,n)}}function ir(e){return a.isObject(e)&&e.isAxiosError===!0}const De={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(De).forEach(([e,t])=>{De[t]=e});function _t(e){const t=new W(e),n=it(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 _t(K(e,s))},n}const T=_t(ie);T.Axios=W;T.CanceledError=ee;T.CancelToken=sr;T.isCancel=yt;T.VERSION=Ct;T.toFormData=Re;T.AxiosError=E;T.Cancel=T.CanceledError;T.all=function(t){return Promise.all(t)};T.spread=or;T.isAxiosError=ir;T.mergeConfig=K;T.AxiosHeaders=D;T.formToJSON=e=>Rt(a.isHTMLForm(e)?new FormData(e):e);T.getAdapter=Ot.getAdapter;T.HttpStatusCode=De;T.default=T;const{Axios:Ir,AxiosError:Lr,CanceledError:Fr,isCancel:Pr,CancelToken:xr,VERSION:Br,all:kr,Cancel:vr,isAxiosError:Hr,spread:jr,toFormData:Mr,AxiosHeaders:$r,HttpStatusCode:qr,formToJSON:Gr,getAdapter:zr,mergeConfig:Jr}=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:"数据为空"}},ar="/api/customer-service/customer/v1/CustomerService/TestLineLatency",cr="/api/customer-service/customer/v1/CustomerService/ListLines",lr="/pub/logo.png",Ie={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 Y=null;function ur(e){const t=`${e.replace(/\/$/,"")}${ar}`;return T.get(t,{timeout:1e4}).then(n=>n.data?.code!==200?Promise.reject(n):e)}function fr(e){const t=`${e.replace(/\/$/,"")}${lr}`;return T.get(t,{timeout:1e4}).then(()=>e).catch(()=>Promise.reject(new Error("Download latency test failed")))}function dr(e){return e?.length?Promise.any(e.map(t=>ur(t))):Promise.reject(new Error("No urls to test"))}function hr(e){return e?.length?Promise.any(e.map(t=>fr(t))):Promise.reject(new Error("No download urls to test"))}async function Be(e,t){if(F.api&&F.download)return;if(Y)return Y;const n=Ie[t].BASE_API_URL||"",r=Ie[t].OBS_URL||"";F.api=n,F.download=r,F.ws=n.replace(/http/g,"ws"),n||(Y=Promise.reject(new Error("环境配置错误")),await Y),Y=(async()=>{const s=await T.get(`${n.replace(/\/$/,"")}${cr}`,{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?dr(o).catch(()=>c):Promise.resolve(c),i.length?hr(i).catch(()=>d):Promise.resolve(d)]);F.api=u,F.download=l,F.ws=u.replace(/http/g,"ws")})(),await Y}const G=T.create({timeout:6e5});G.interceptors.request.use(async e=>{const t=new q,n=t.config.token;return n?(e.headers.Authorization=`Bearer ${n}`,t.config.language&&(e.headers["Accept-Language"]=t.config.language),await Be(n,t.config.env),e.baseURL=F.api,e):Promise.reject(b.UNINITIALIZED)},e=>Promise.reject(e));G.interceptors.response.use(e=>e.data?.code!==200?Promise.reject(e):Promise.resolve(e.data),e=>Promise.reject(e));function pr(){return F.api}function me(){return F.download}function mr(){return F.ws}const Er=e=>G.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),Sr=async e=>{const t=me();return T.post(`${t}`,e,{headers:{"Content-Type":"multipart/form-data"}})},Tr=async(e,t)=>T.put(t,e,{headers:{"Content-Type":e.type}}),wr=e=>G.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),Rr=e=>G.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),yr=()=>G.get("/api/open-auth/user/v1/UserService/GetUserInfo"),Ar=e=>G.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e),br=e=>{const t=new q,n=t.config.env,r=pr()||Ie[n].BASE_API_URL;return T.post(`${r}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,e,{headers:t.config.language?{"Accept-Language":t.config.language}:void 0})},gr=e=>G.get("/api/chat/chat/v1/Chat/GetMsg",{params:e});var v=(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))(v||{}),H=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(H||{}),C=(e=>(e[e.CONNECT_SUCCESS=200]="CONNECT_SUCCESS",e[e.CONNECT_FAILED=40001]="CONNECT_FAILED",e[e.TRANSFER_CUSTOMER_SUCCESS=201]="TRANSFER_CUSTOMER_SUCCESS",e[e.TRANSFER_TO_CUSTOMER_SUCCESS=202]="TRANSFER_TO_CUSTOMER_SUCCESS",e[e.TRANSFER_USER_SUCCESS=203]="TRANSFER_USER_SUCCESS",e[e.TRANSFER_FAIL=50001]="TRANSFER_FAIL",e[e.MATCH_FAIL=50002]="MATCH_FAIL",e[e.MATCH_INFO=50005]="MATCH_INFO",e[e.MATCH_SUCCESS=50006]="MATCH_SUCCESS",e[e.RETRACT=204]="RETRACT",e[e.RETRACT_FAIL=50003]="RETRACT_FAIL",e[e.EDIT=205]="EDIT",e[e.EDIT_FAIL=50004]="EDIT_FAIL",e[e.COMMON_FAIL=5e4]="COMMON_FAIL",e[e.SEND_SUCCESS=206]="SEND_SUCCESS",e[e.SEND_CALLBACK=207]="SEND_CALLBACK",e[e.CHANGE_CHAT_STATUS=208]="CHANGE_CHAT_STATUS",e[e.REPLY_FAIL=50008]="REPLY_FAIL",e[e.REPLY_SUCCESS=209]="REPLY_SUCCESS",e[e.UNBIND_SUCCESS=60006]="UNBIND_SUCCESS",e[e.BAN_CUSTOMER=60007]="BAN_CUSTOMER",e[e.BAN_ENTRY=60008]="BAN_ENTRY",e[e.REMATCH=60001]="REMATCH",e))(C||{}),Ee=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(Ee||{}),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 Or(e,t){return await Be(e,t),`${await mr()}/api/ws?Authorization=${e}`}function Cr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function Ur(e){return typeof e=="object"&&e!==null&&"data"in e&&"msgType"in e&&"toUid"in e&&"chatType"in e&&"code"in e}function ot(e){return e.customerServiceAvatar=$(e.customerServiceAvatar),e.userAvatar=$(e.customerServiceAvatar),e.contentType!==H.TEXT&&(e.content=JSON.parse(e.content),e.content.fileUrl=$(e.content.fileUrl),e.content.thumbnailUrl=$(e.content.thumbnailUrl)),e.replyType&&e.replyType!==H.TEXT&&e.replyContent&&typeof e.replyContent=="string"&&(e.replyContent=JSON.parse(e.replyContent),e.replyContent.fileUrl=$(e.replyContent.fileUrl),e.replyContent.thumbnailUrl=$(e.replyContent.thumbnailUrl)),e}function $(e=""){return e&&!e.startsWith("http")?me()+"/"+e:e}class q extends Nr{config={token:"",autoReconnect:!0,reconnectInterval:3e3,maxReconnectAttempts:5,responseTimeout:15e3,env:"production",language:"en-US"};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}={}){if(super(),q.instance)return q.instance;q.instance=this,this.config.env=t||"production"}async init(t){if(!t.token)return Promise.reject(b.PARAMETER_ERROR);await Be(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 Or(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.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(N.DISCONNECTED),this.emit(A.DISCONNECTED),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(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=v.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===v.SEND?new Promise(async(o,i)=>{const c=Cr();s.ext=c;const d=await gr({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===g.UNBIND&&(await this.sendMessage(this.consultationTypeId,void 0,v.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,H.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=me();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),!!Ur(t))try{const n=t.data?JSON.parse(t.data):t.data;switch(t.data=n,t.code){case C.CONNECT_SUCCESS:this.matchStatus===g.MATCHED||this.matchStatus===g.MATCHING?this.matchStatus=g.UNBIND:this.matchStatus=g.MATCHING,this.sendMessage(this.consultationTypeId,void 0,v.INBOUND);break;case C.MATCH_INFO:case C.MATCH_SUCCESS:if(this.matchStatus===g.MATCHED)return;t.data.customerAvatar=$(t.data.customerAvatar),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;ot(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.config.env==="development"&&console.warn(`第${this.reconnectAttempts+1}次安排重连`,new Date().toISOString()),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),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!==g.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const r=await Ar({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>ot(o));return{hasMore:r.data.hasMore,list:s}}async getConsultationList(t){return(await wr({entranceId:t})).data}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await Er({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 Tr(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 Sr(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 Rr({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:H.FAQ,sendUserType:Ee.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:v.SEND},msgType:v.SEND,chatType:H.FAQ};this.emit(A.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={code:C.SEND_SUCCESS,data:{sendUserType:Ee.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:v.SEND,contentType:H.FAQ,content:{}},msgType:v.SEND,chatType:H.FAQ};if(t.isMulti)n.data.content={list:t.item},this.emit(A.MESSAGE,n);else{const r=t.item?.[0]||t,s=me();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 t.data.avatar=$(t.data.avatar),this.userInfo=t.data,this.userInfo}async anonymousLogin(t,n){return(await br({appKey:t,entranceId:n,userSource:"H5"})).data}setLanguage(t){this.config.language=t||"en-US"}}exports.ChatType=H;exports.ConnectionStatus=N;exports.EventType=A;exports.JoyTalk=q;exports.MatchStatus=g;exports.MessageCode=C;exports.MessageType=v;exports.SendUserType=Ee;exports.default=q;
package/dist/index.es.js CHANGED
@@ -2011,7 +2011,7 @@ function Ur(e) {
2011
2011
  return typeof e == "object" && e !== null && "data" in e && "msgType" in e && "toUid" in e && "chatType" in e && "code" in e;
2012
2012
  }
2013
2013
  function ot(e) {
2014
- return e.customerServiceAvatar = M(e.customerServiceAvatar), e.userAvatar = M(e.customerServiceAvatar), e.contentType !== $.TEXT && (e.content = JSON.parse(e.content), e.content.fileUrl = M(e.content.fileUrl), e.content.thumbnailUrl = M(e.content.thumbnailUrl)), e.replyType && e.replyType !== $.TEXT && typeof e.replyContent == "string" && (e.replyContent = JSON.parse(
2014
+ return e.customerServiceAvatar = M(e.customerServiceAvatar), e.userAvatar = M(e.customerServiceAvatar), e.contentType !== $.TEXT && (e.content = JSON.parse(e.content), e.content.fileUrl = M(e.content.fileUrl), e.content.thumbnailUrl = M(e.content.thumbnailUrl)), e.replyType && e.replyType !== $.TEXT && e.replyContent && typeof e.replyContent == "string" && (e.replyContent = JSON.parse(
2015
2015
  e.replyContent
2016
2016
  ), e.replyContent.fileUrl = M(e.replyContent.fileUrl), e.replyContent.thumbnailUrl = M(
2017
2017
  e.replyContent.thumbnailUrl
package/dist/index.umd.js CHANGED
@@ -3,4 +3,4 @@
3
3
  `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(s=>r.set(s)),r}static accessor(t){const r=(this[rt]=this[rt]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=ae(i);r[c]||(Fn(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 Ie(e,t){const n=this||ie,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 st(e){return!!(e&&e.__CANCEL__)}function ee(e,t,n){E.call(this,e??"canceled",E.ERR_CANCELED,t,n),this.name="CanceledError"}a.inherits(ee,E,{__CANCEL__:!0});function ot(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 Pn(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function xn(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 Bn(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 me=(e,t,n=3)=>{let r=0;const s=xn(50,250);return Bn(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)},it=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},at=e=>(...t)=>a.asap(()=>e(...t)),kn=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,vn=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 jn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function ct(e,t,n){let r=!Hn(t);return e&&(r||n==!1)?jn(e,t):t}const lt=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(lt(u),lt(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 ut=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=Ze(ct(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&&kn(t.url))){const d=s&&o&&vn.read(o);d&&i.set(s,d)}return t},Mn=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const s=ut(e);let o=s.data;const i=D.from(s.headers).normalize();let{responseType:c,onUploadProgress:d,onDownloadProgress:u}=s,l,h,S,w,f;function m(){w&&w(),f&&f(),s.cancelToken&&s.cancelToken.unsubscribe(l),s.signal&&s.signal.removeEventListener("abort",l)}let p=new XMLHttpRequest;p.open(s.method.toUpperCase(),s.url,!0),p.timeout=s.timeout;function R(){if(!p)return;const A=D.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),B={data:!c||c==="text"||c==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:A,config:e,request:p};ot(function(P){n(P),m()},function(P){r(P),m()},B),p=null}"onloadend"in p?p.onloadend=R:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(R)},p.onabort=function(){p&&(r(new E("Request aborted",E.ECONNABORTED,e,p)),p=null)},p.onerror=function(I){const B=I&&I.message?I.message:"Network Error",K=new E(B,E.ERR_NETWORK,e,p);K.event=I||null,r(K),p=null},p.ontimeout=function(){let I=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const B=s.transitional||tt;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]=me(u,!0),p.addEventListener("progress",S)),d&&p.upload&&([h,w]=me(d),p.upload.addEventListener("progress",h),p.upload.addEventListener("loadend",w)),(s.cancelToken||s.signal)&&(l=A=>{p&&(r(!A||A.type?new ee(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=Pn(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)})},$n=(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 ee(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}},qn=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},Gn=async function*(e,t){for await(const n of zn(e))yield*qn(n,t)},zn=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()}},ft=(e,t,n,r)=>{const s=Gn(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})},dt=64*1024,{isFunction:Ee}=a,Jn=(({Request:e,Response:t})=>({Request:e,Response:t}))(a.global),{ReadableStream:ht,TextEncoder:pt}=a.global,mt=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Vn=e=>{e=a.merge.call({skipUndefined:!0},Jn,e);const{fetch:t,Request:n,Response:r}=e,s=t?Ee(t):typeof fetch=="function",o=Ee(n),i=Ee(r);if(!s)return!1;const c=s&&Ee(ht),d=s&&(typeof pt=="function"?(f=>m=>f.encode(m))(new pt):async f=>new Uint8Array(await new n(f).arrayBuffer())),u=o&&c&&mt(()=>{let f=!1;const m=new n(N.origin,{body:new ht,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!m}),l=i&&c&&mt(()=>a.isReadableStream(new r("").body)),h={stream:l&&(f=>f.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!h[f]&&(h[f]=(m,p)=>{let R=m&&m[f];if(R)return R.call(m);throw new E(`Response type '${f}' is not supported`,E.ERR_NOT_SUPPORT,p)})});const S=async f=>{if(f==null)return 0;if(a.isBlob(f))return f.size;if(a.isSpecCompliantForm(f))return(await new n(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:R,signal:F,cancelToken:A,timeout:I,onDownloadProgress:B,onUploadProgress:K,responseType:P,headers:ke,withCredentials:ye="same-origin",fetchOptions:gt}=ut(f),Nt=t||fetch;P=P?(P+"").toLowerCase():"text";let Ae=$n([F,A&&A.toAbortSignal()],I),ce=null;const X=Ae&&Ae.unsubscribe&&(()=>{Ae.unsubscribe()});let Ot;try{if(K&&u&&p!=="get"&&p!=="head"&&(Ot=await w(ke,R))!==0){let z=new n(m,{method:"POST",body:R,duplex:"half"}),ne;if(a.isFormData(R)&&(ne=z.headers.get("content-type"))&&ke.setContentType(ne),z.body){const[ve,be]=it(Ot,me(at(K)));R=ft(z.body,dt,ve,be)}}a.isString(ye)||(ye=ye?"include":"omit");const H=o&&"credentials"in n.prototype,Ct={...gt,signal:Ae,method:p.toUpperCase(),headers:ke.normalize().toJSON(),body:R,duplex:"half",credentials:H?ye:void 0};ce=o&&new n(m,Ct);let G=await(o?Nt(ce,gt):Nt(m,Ct));const Ut=l&&(P==="stream"||P==="response");if(l&&(B||Ut&&X)){const z={};["status","statusText","headers"].forEach(_t=>{z[_t]=G[_t]});const ne=a.toFiniteNumber(G.headers.get("content-length")),[ve,be]=B&&it(ne,me(at(B),!0))||[];G=new r(ft(G.body,dt,ve,()=>{be&&be(),X&&X()}),z)}P=P||"text";let br=await h[a.findKey(h,P)||"text"](G,f);return!Ut&&X&&X(),await new Promise((z,ne)=>{ot(z,ne,{data:br,headers:D.from(G.headers),status:G.status,statusText:G.statusText,config:f,request:ce})})}catch(H){throw X&&X(),H&&H.name==="TypeError"&&/Load failed|fetch/i.test(H.message)?Object.assign(new E("Network Error",E.ERR_NETWORK,f,ce),{cause:H.cause||H}):E.from(H,H&&H.code,f,ce)}}},Wn=new Map,Et=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:Vn(t)),l=u;return u};Et();const Le={http:En,xhr:Mn,fetch:{get:Et}};a.forEach(Le,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const St=e=>`- ${e}`,Kn=e=>a.isFunction(e)||e===null||e===!1;function Xn(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,!Kn(r)&&(s=Le[(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(St).join(`
5
5
  `):" "+St(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 Tt={getAdapter:Xn,adapters:Le};function Fe(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ee(null,e)}function wt(e){return Fe(e),e.headers=D.from(e.headers),e.data=Ie.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Tt.getAdapter(e.adapter||ie.adapter,e)(e).then(function(r){return Fe(e),r.data=Ie.call(e,e.transformResponse,r),r.headers=D.from(r.headers),r},function(r){return st(r)||(Fe(e),r&&r.response&&(r.response.data=Ie.call(e,e.transformResponse,r.response),r.response.headers=D.from(r.response.headers))),Promise.reject(r)})}const Rt="1.13.2",Se={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Se[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const yt={};Se.transitional=function(t,n,r){function s(o,i){return"[Axios v"+Rt+"] 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}},Se.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Yn(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 Te={assertOptions:Yn,validators:Se},k=Te.validators;let W=class{constructor(t){this.defaults=t||{},this.interceptors={request:new et,response:new et}}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&&Te.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}:Te.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),Te.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=[wt.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=wt.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=ct(t.baseURL,t.url,t.allowAbsoluteUrls);return Ze(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 Qn=class Dt{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 ee(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 Dt(function(s){t=s}),cancel:t}}};function Zn(e){return function(n){return e.apply(null,n)}}function er(e){return a.isObject(e)&&e.isAxiosError===!0}const Pe={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(Pe).forEach(([e,t])=>{Pe[t]=e});function At(e){const t=new W(e),n=Y(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 At(V(e,s))},n}const T=At(ie);T.Axios=W,T.CanceledError=ee,T.CancelToken=Qn,T.isCancel=st,T.VERSION=Rt,T.toFormData=he,T.AxiosError=E,T.Cancel=T.CanceledError,T.all=function(t){return Promise.all(t)},T.spread=Zn,T.isAxiosError=er,T.mergeConfig=V,T.AxiosHeaders=D,T.formToJSON=e=>nt(a.isHTMLForm(e)?new FormData(e):e),T.getAdapter=Tt.getAdapter,T.HttpStatusCode=Pe,T.default=T;const{Axios:Dr,AxiosError:Ir,CanceledError:Lr,isCancel:Fr,CancelToken:Pr,VERSION:xr,all:Br,Cancel:kr,isAxiosError:vr,spread:Hr,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:"数据为空"}},tr="/api/customer-service/customer/v1/CustomerService/TestLineLatency",nr="/api/customer-service/customer/v1/CustomerService/ListLines",rr="/pub/logo.png",xe={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 te=null;function sr(e){const t=`${e.replace(/\/$/,"")}${tr}`;return T.get(t,{timeout:1e4}).then(n=>n.data?.code!==200?Promise.reject(n):e)}function or(e){const t=`${e.replace(/\/$/,"")}${rr}`;return T.get(t,{timeout:1e4}).then(()=>e).catch(()=>Promise.reject(new Error("Download latency test failed")))}function ir(e){return e?.length?Promise.any(e.map(t=>sr(t))):Promise.reject(new Error("No urls to test"))}function ar(e){return e?.length?Promise.any(e.map(t=>or(t))):Promise.reject(new Error("No download urls to test"))}async function Be(e,t){if(L.api&&L.download)return;if(te)return te;const n=xe[t].BASE_API_URL||"",r=xe[t].OBS_URL||"";L.api=n,L.download=r,L.ws=n.replace(/http/g,"ws"),n||(te=Promise.reject(new Error("环境配置错误")),await te),te=(async()=>{const s=await T.get(`${n.replace(/\/$/,"")}${nr}`,{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?ir(o).catch(()=>c):Promise.resolve(c),i.length?ar(i).catch(()=>d):Promise.resolve(d)]);L.api=u,L.download=l,L.ws=u.replace(/http/g,"ws")})(),await te}const M=T.create({timeout:6e5});M.interceptors.request.use(async e=>{const t=new q,n=t.config.token;return n?(e.headers.Authorization=`Bearer ${n}`,t.config.language&&(e.headers["Accept-Language"]=t.config.language),await Be(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 cr(){return L.api}function we(){return L.download}function lr(){return L.ws}const ur=e=>M.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),fr=async e=>{const t=we();return T.post(`${t}`,e,{headers:{"Content-Type":"multipart/form-data"}})},dr=async(e,t)=>T.put(t,e,{headers:{"Content-Type":e.type}}),hr=e=>M.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),pr=e=>M.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),mr=()=>M.get("/api/open-auth/user/v1/UserService/GetUserInfo"),Er=e=>M.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e),Sr=e=>{const t=new q,n=t.config.env,r=cr()||xe[n].BASE_API_URL;return T.post(`${r}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,e,{headers:t.config.language?{"Accept-Language":t.config.language}:void 0})},Tr=e=>M.get("/api/chat/chat/v1/Chat/GetMsg",{params:e});var v=(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))(v||{}),j=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(j||{}),C=(e=>(e[e.CONNECT_SUCCESS=200]="CONNECT_SUCCESS",e[e.CONNECT_FAILED=40001]="CONNECT_FAILED",e[e.TRANSFER_CUSTOMER_SUCCESS=201]="TRANSFER_CUSTOMER_SUCCESS",e[e.TRANSFER_TO_CUSTOMER_SUCCESS=202]="TRANSFER_TO_CUSTOMER_SUCCESS",e[e.TRANSFER_USER_SUCCESS=203]="TRANSFER_USER_SUCCESS",e[e.TRANSFER_FAIL=50001]="TRANSFER_FAIL",e[e.MATCH_FAIL=50002]="MATCH_FAIL",e[e.MATCH_INFO=50005]="MATCH_INFO",e[e.MATCH_SUCCESS=50006]="MATCH_SUCCESS",e[e.RETRACT=204]="RETRACT",e[e.RETRACT_FAIL=50003]="RETRACT_FAIL",e[e.EDIT=205]="EDIT",e[e.EDIT_FAIL=50004]="EDIT_FAIL",e[e.COMMON_FAIL=5e4]="COMMON_FAIL",e[e.SEND_SUCCESS=206]="SEND_SUCCESS",e[e.SEND_CALLBACK=207]="SEND_CALLBACK",e[e.CHANGE_CHAT_STATUS=208]="CHANGE_CHAT_STATUS",e[e.REPLY_FAIL=50008]="REPLY_FAIL",e[e.REPLY_SUCCESS=209]="REPLY_SUCCESS",e[e.UNBIND_SUCCESS=60006]="UNBIND_SUCCESS",e[e.BAN_CUSTOMER=60007]="BAN_CUSTOMER",e[e.BAN_ENTRY=60008]="BAN_ENTRY",e[e.REMATCH=60001]="REMATCH",e))(C||{}),Re=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(Re||{}),y=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(y||{}),O=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(O||{}),g=(e=>(e.UNMATCHED="1",e.MATCHING="2",e.MATCHED="3",e.UNBIND="4",e))(g||{});class wr{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 Rr(e,t){return await Be(e,t),`${await lr()}/api/ws?Authorization=${e}`}function yr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function Ar(e){return typeof e=="object"&&e!==null&&"data"in e&&"msgType"in e&&"toUid"in e&&"chatType"in e&&"code"in e}function bt(e){return e.customerServiceAvatar=$(e.customerServiceAvatar),e.userAvatar=$(e.customerServiceAvatar),e.contentType!==j.TEXT&&(e.content=JSON.parse(e.content),e.content.fileUrl=$(e.content.fileUrl),e.content.thumbnailUrl=$(e.content.thumbnailUrl)),e.replyType&&e.replyType!==j.TEXT&&typeof e.replyContent=="string"&&(e.replyContent=JSON.parse(e.replyContent),e.replyContent.fileUrl=$(e.replyContent.fileUrl),e.replyContent.thumbnailUrl=$(e.replyContent.thumbnailUrl)),e}function $(e=""){return e&&!e.startsWith("http")?we()+"/"+e:e}class q extends wr{config={token:"",autoReconnect:!0,reconnectInterval:3e3,maxReconnectAttempts:5,responseTimeout:15e3,env:"production",language:"en-US"};ws=null;status=O.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;consultationTypeId="";sessionData=null;userInfo=null;static instance=null;matchStatus=g.UNMATCHED;constructor({env:t}={}){if(super(),q.instance)return q.instance;q.instance=this,this.config.env=t||"production"}async init(t){if(!t.token)return Promise.reject(b.PARAMETER_ERROR);await Be(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 Rr(this.config.token,this.config.env);this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(O.CONNECTED),this.emit(y.CONNECTED),n()},this.ws.onmessage=o=>{try{this.handleMessage(o.data)}catch(i){throw console.error("解析消息失败:",i),b.DATA_PARSING_ERROR}},this.ws.onerror=o=>{console.error("连接错误:",o),this.setStatus(O.ERROR),this.emit(y.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(O.DISCONNECTED),this.emit(y.DISCONNECTED),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(O.ERROR),this.emit(y.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(O.DISCONNECTED)}async sendMessage(t,n,r=v.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===v.SEND?new Promise(async(o,i)=>{const c=yr();s.ext=c;const d=await Tr({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===g.UNBIND&&(await this.sendMessage(this.consultationTypeId,void 0,v.INBOUND),await new Promise((t,n)=>{const r=setTimeout(()=>{clearTimeout(r),n(b.MESSAGE_SEND_FAIL)},this.config.responseTimeout);this.once(y.MESSAGE,s=>{s.code===C.REMATCH&&(clearTimeout(r),t(!0))})})),this.matchStatus!==g.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=we();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),!!Ar(t))try{const n=t.data?JSON.parse(t.data):t.data;switch(t.data=n,t.code){case C.CONNECT_SUCCESS:this.matchStatus===g.MATCHED||this.matchStatus===g.MATCHING?this.matchStatus=g.UNBIND:this.matchStatus=g.MATCHING,this.sendMessage(this.consultationTypeId,void 0,v.INBOUND);break;case C.MATCH_INFO:case C.MATCH_SUCCESS:if(this.matchStatus===g.MATCHED)return;t.data.customerAvatar=$(t.data.customerAvatar),this.sessionData=t.data,this.matchStatus===g.UNBIND?(this.matchStatus=g.MATCHED,this.emit(y.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=g.MATCHED,this.getFaqList(),this.emit(y.MESSAGE,t));break;case C.TRANSFER_USER_SUCCESS:if(n.oldSessionId!==this.sessionData?.sessionId)return;const r=t.data;this.sessionData={...this.sessionData,cid:String(r.cid),customerAvatar:r.customerAvatar,customerName:r.customerName,groupId:r.groupId,sessionId:r.sessionId},this.emit(y.MESSAGE,t);break;case C.SEND_SUCCESS:case C.EDIT:case C.REPLY_SUCCESS:const s=t.data;if(s.sessionId!==this.sessionData?.sessionId)return;bt(s),this.emit(y.MESSAGE,t);break;case C.SEND_CALLBACK:const o=t.ext,c=t.data.messageId;this.emit(o,c);break;case C.UNBIND_SUCCESS:if(n.sessionId!==this.sessionData?.sessionId)return;this.matchStatus=g.UNBIND,this.sessionData=null,this.emit(y.MESSAGE,t);break;default:this.emit(y.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}setStatus(t){this.status!==t&&(this.status=t,this.emit(y.STATUS_CHANGE,t))}scheduleReconnect(){this.config.env==="development"&&console.warn(`第${this.reconnectAttempts+1}次安排重连`,new Date().toISOString()),this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(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(y.HEARTBEAT_TIMEOUT),this.config.env==="development"&&console.warn("心跳超时,尝试重连",new Date().toISOString()),this.ws&&this.ws.close())},this.config.responseTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=50}){if(this.matchStatus!==g.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const r=await Er({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>bt(o));return{hasMore:r.data.hasMore,list:s}}async getConsultationList(t){return(await hr({entranceId:t})).data}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await ur({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 dr(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 fr(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 pr({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:Re.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:v.SEND},msgType:v.SEND,chatType:j.FAQ};this.emit(y.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={code:C.SEND_SUCCESS,data:{sendUserType:Re.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:v.SEND,contentType:j.FAQ,content:{}},msgType:v.SEND,chatType:j.FAQ};if(t.isMulti)n.data.content={list:t.item},this.emit(y.MESSAGE,n);else{const r=t.item?.[0]||t,s=we();r.imageUrl=r.imageUrl?.map(o=>o?.startsWith("http")?o:`${s}/${o}`),n.data.content={answer:r},this.emit(y.MESSAGE,n)}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await mr();return t.data.avatar=$(t.data.avatar),this.userInfo=t.data,this.userInfo}async anonymousLogin(t,n){return(await Sr({appKey:t,entranceId:n,userSource:"H5"})).data}setLanguage(t){this.config.language=t||"en-US"}}U.ChatType=j,U.ConnectionStatus=O,U.EventType=y,U.JoyTalk=q,U.MatchStatus=g,U.MessageCode=C,U.MessageType=v,U.SendUserType=Re,U.default=q,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=V(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&Te.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}:Te.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),Te.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=[wt.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=wt.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=ct(t.baseURL,t.url,t.allowAbsoluteUrls);return Ze(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 Qn=class Dt{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 ee(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 Dt(function(s){t=s}),cancel:t}}};function Zn(e){return function(n){return e.apply(null,n)}}function er(e){return a.isObject(e)&&e.isAxiosError===!0}const Pe={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(Pe).forEach(([e,t])=>{Pe[t]=e});function At(e){const t=new W(e),n=Y(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 At(V(e,s))},n}const T=At(ie);T.Axios=W,T.CanceledError=ee,T.CancelToken=Qn,T.isCancel=st,T.VERSION=Rt,T.toFormData=he,T.AxiosError=E,T.Cancel=T.CanceledError,T.all=function(t){return Promise.all(t)},T.spread=Zn,T.isAxiosError=er,T.mergeConfig=V,T.AxiosHeaders=D,T.formToJSON=e=>nt(a.isHTMLForm(e)?new FormData(e):e),T.getAdapter=Tt.getAdapter,T.HttpStatusCode=Pe,T.default=T;const{Axios:Dr,AxiosError:Ir,CanceledError:Lr,isCancel:Fr,CancelToken:Pr,VERSION:xr,all:Br,Cancel:kr,isAxiosError:vr,spread:Hr,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:"数据为空"}},tr="/api/customer-service/customer/v1/CustomerService/TestLineLatency",nr="/api/customer-service/customer/v1/CustomerService/ListLines",rr="/pub/logo.png",xe={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 te=null;function sr(e){const t=`${e.replace(/\/$/,"")}${tr}`;return T.get(t,{timeout:1e4}).then(n=>n.data?.code!==200?Promise.reject(n):e)}function or(e){const t=`${e.replace(/\/$/,"")}${rr}`;return T.get(t,{timeout:1e4}).then(()=>e).catch(()=>Promise.reject(new Error("Download latency test failed")))}function ir(e){return e?.length?Promise.any(e.map(t=>sr(t))):Promise.reject(new Error("No urls to test"))}function ar(e){return e?.length?Promise.any(e.map(t=>or(t))):Promise.reject(new Error("No download urls to test"))}async function Be(e,t){if(L.api&&L.download)return;if(te)return te;const n=xe[t].BASE_API_URL||"",r=xe[t].OBS_URL||"";L.api=n,L.download=r,L.ws=n.replace(/http/g,"ws"),n||(te=Promise.reject(new Error("环境配置错误")),await te),te=(async()=>{const s=await T.get(`${n.replace(/\/$/,"")}${nr}`,{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?ir(o).catch(()=>c):Promise.resolve(c),i.length?ar(i).catch(()=>d):Promise.resolve(d)]);L.api=u,L.download=l,L.ws=u.replace(/http/g,"ws")})(),await te}const M=T.create({timeout:6e5});M.interceptors.request.use(async e=>{const t=new q,n=t.config.token;return n?(e.headers.Authorization=`Bearer ${n}`,t.config.language&&(e.headers["Accept-Language"]=t.config.language),await Be(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 cr(){return L.api}function we(){return L.download}function lr(){return L.ws}const ur=e=>M.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),fr=async e=>{const t=we();return T.post(`${t}`,e,{headers:{"Content-Type":"multipart/form-data"}})},dr=async(e,t)=>T.put(t,e,{headers:{"Content-Type":e.type}}),hr=e=>M.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),pr=e=>M.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),mr=()=>M.get("/api/open-auth/user/v1/UserService/GetUserInfo"),Er=e=>M.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e),Sr=e=>{const t=new q,n=t.config.env,r=cr()||xe[n].BASE_API_URL;return T.post(`${r}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,e,{headers:t.config.language?{"Accept-Language":t.config.language}:void 0})},Tr=e=>M.get("/api/chat/chat/v1/Chat/GetMsg",{params:e});var v=(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))(v||{}),j=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(j||{}),C=(e=>(e[e.CONNECT_SUCCESS=200]="CONNECT_SUCCESS",e[e.CONNECT_FAILED=40001]="CONNECT_FAILED",e[e.TRANSFER_CUSTOMER_SUCCESS=201]="TRANSFER_CUSTOMER_SUCCESS",e[e.TRANSFER_TO_CUSTOMER_SUCCESS=202]="TRANSFER_TO_CUSTOMER_SUCCESS",e[e.TRANSFER_USER_SUCCESS=203]="TRANSFER_USER_SUCCESS",e[e.TRANSFER_FAIL=50001]="TRANSFER_FAIL",e[e.MATCH_FAIL=50002]="MATCH_FAIL",e[e.MATCH_INFO=50005]="MATCH_INFO",e[e.MATCH_SUCCESS=50006]="MATCH_SUCCESS",e[e.RETRACT=204]="RETRACT",e[e.RETRACT_FAIL=50003]="RETRACT_FAIL",e[e.EDIT=205]="EDIT",e[e.EDIT_FAIL=50004]="EDIT_FAIL",e[e.COMMON_FAIL=5e4]="COMMON_FAIL",e[e.SEND_SUCCESS=206]="SEND_SUCCESS",e[e.SEND_CALLBACK=207]="SEND_CALLBACK",e[e.CHANGE_CHAT_STATUS=208]="CHANGE_CHAT_STATUS",e[e.REPLY_FAIL=50008]="REPLY_FAIL",e[e.REPLY_SUCCESS=209]="REPLY_SUCCESS",e[e.UNBIND_SUCCESS=60006]="UNBIND_SUCCESS",e[e.BAN_CUSTOMER=60007]="BAN_CUSTOMER",e[e.BAN_ENTRY=60008]="BAN_ENTRY",e[e.REMATCH=60001]="REMATCH",e))(C||{}),Re=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(Re||{}),y=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(y||{}),O=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(O||{}),g=(e=>(e.UNMATCHED="1",e.MATCHING="2",e.MATCHED="3",e.UNBIND="4",e))(g||{});class wr{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 Rr(e,t){return await Be(e,t),`${await lr()}/api/ws?Authorization=${e}`}function yr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function Ar(e){return typeof e=="object"&&e!==null&&"data"in e&&"msgType"in e&&"toUid"in e&&"chatType"in e&&"code"in e}function bt(e){return e.customerServiceAvatar=$(e.customerServiceAvatar),e.userAvatar=$(e.customerServiceAvatar),e.contentType!==j.TEXT&&(e.content=JSON.parse(e.content),e.content.fileUrl=$(e.content.fileUrl),e.content.thumbnailUrl=$(e.content.thumbnailUrl)),e.replyType&&e.replyType!==j.TEXT&&e.replyContent&&typeof e.replyContent=="string"&&(e.replyContent=JSON.parse(e.replyContent),e.replyContent.fileUrl=$(e.replyContent.fileUrl),e.replyContent.thumbnailUrl=$(e.replyContent.thumbnailUrl)),e}function $(e=""){return e&&!e.startsWith("http")?we()+"/"+e:e}class q extends wr{config={token:"",autoReconnect:!0,reconnectInterval:3e3,maxReconnectAttempts:5,responseTimeout:15e3,env:"production",language:"en-US"};ws=null;status=O.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;consultationTypeId="";sessionData=null;userInfo=null;static instance=null;matchStatus=g.UNMATCHED;constructor({env:t}={}){if(super(),q.instance)return q.instance;q.instance=this,this.config.env=t||"production"}async init(t){if(!t.token)return Promise.reject(b.PARAMETER_ERROR);await Be(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 Rr(this.config.token,this.config.env);this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(O.CONNECTED),this.emit(y.CONNECTED),n()},this.ws.onmessage=o=>{try{this.handleMessage(o.data)}catch(i){throw console.error("解析消息失败:",i),b.DATA_PARSING_ERROR}},this.ws.onerror=o=>{console.error("连接错误:",o),this.setStatus(O.ERROR),this.emit(y.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(O.DISCONNECTED),this.emit(y.DISCONNECTED),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(O.ERROR),this.emit(y.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(O.DISCONNECTED)}async sendMessage(t,n,r=v.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===v.SEND?new Promise(async(o,i)=>{const c=yr();s.ext=c;const d=await Tr({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===g.UNBIND&&(await this.sendMessage(this.consultationTypeId,void 0,v.INBOUND),await new Promise((t,n)=>{const r=setTimeout(()=>{clearTimeout(r),n(b.MESSAGE_SEND_FAIL)},this.config.responseTimeout);this.once(y.MESSAGE,s=>{s.code===C.REMATCH&&(clearTimeout(r),t(!0))})})),this.matchStatus!==g.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=we();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),!!Ar(t))try{const n=t.data?JSON.parse(t.data):t.data;switch(t.data=n,t.code){case C.CONNECT_SUCCESS:this.matchStatus===g.MATCHED||this.matchStatus===g.MATCHING?this.matchStatus=g.UNBIND:this.matchStatus=g.MATCHING,this.sendMessage(this.consultationTypeId,void 0,v.INBOUND);break;case C.MATCH_INFO:case C.MATCH_SUCCESS:if(this.matchStatus===g.MATCHED)return;t.data.customerAvatar=$(t.data.customerAvatar),this.sessionData=t.data,this.matchStatus===g.UNBIND?(this.matchStatus=g.MATCHED,this.emit(y.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=g.MATCHED,this.getFaqList(),this.emit(y.MESSAGE,t));break;case C.TRANSFER_USER_SUCCESS:if(n.oldSessionId!==this.sessionData?.sessionId)return;const r=t.data;this.sessionData={...this.sessionData,cid:String(r.cid),customerAvatar:r.customerAvatar,customerName:r.customerName,groupId:r.groupId,sessionId:r.sessionId},this.emit(y.MESSAGE,t);break;case C.SEND_SUCCESS:case C.EDIT:case C.REPLY_SUCCESS:const s=t.data;if(s.sessionId!==this.sessionData?.sessionId)return;bt(s),this.emit(y.MESSAGE,t);break;case C.SEND_CALLBACK:const o=t.ext,c=t.data.messageId;this.emit(o,c);break;case C.UNBIND_SUCCESS:if(n.sessionId!==this.sessionData?.sessionId)return;this.matchStatus=g.UNBIND,this.sessionData=null,this.emit(y.MESSAGE,t);break;default:this.emit(y.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}setStatus(t){this.status!==t&&(this.status=t,this.emit(y.STATUS_CHANGE,t))}scheduleReconnect(){this.config.env==="development"&&console.warn(`第${this.reconnectAttempts+1}次安排重连`,new Date().toISOString()),this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(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(y.HEARTBEAT_TIMEOUT),this.config.env==="development"&&console.warn("心跳超时,尝试重连",new Date().toISOString()),this.ws&&this.ws.close())},this.config.responseTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=50}){if(this.matchStatus!==g.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const r=await Er({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>bt(o));return{hasMore:r.data.hasMore,list:s}}async getConsultationList(t){return(await hr({entranceId:t})).data}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await ur({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 dr(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 fr(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 pr({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:Re.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:v.SEND},msgType:v.SEND,chatType:j.FAQ};this.emit(y.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={code:C.SEND_SUCCESS,data:{sendUserType:Re.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:v.SEND,contentType:j.FAQ,content:{}},msgType:v.SEND,chatType:j.FAQ};if(t.isMulti)n.data.content={list:t.item},this.emit(y.MESSAGE,n);else{const r=t.item?.[0]||t,s=we();r.imageUrl=r.imageUrl?.map(o=>o?.startsWith("http")?o:`${s}/${o}`),n.data.content={answer:r},this.emit(y.MESSAGE,n)}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await mr();return t.data.avatar=$(t.data.avatar),this.userInfo=t.data,this.userInfo}async anonymousLogin(t,n){return(await Sr({appKey:t,entranceId:n,userSource:"H5"})).data}setLanguage(t){this.config.language=t||"en-US"}}U.ChatType=j,U.ConnectionStatus=O,U.EventType=y,U.JoyTalk=q,U.MatchStatus=g,U.MessageCode=C,U.MessageType=v,U.SendUserType=Re,U.default=q,Object.defineProperties(U,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "joytalk",
3
- "version": "0.0.40",
3
+ "version": "0.0.41",
4
4
  "description": "JoyTalk SDK - 用于集成客服功能的 JavaScript SDK",
5
5
  "type": "module",
6
6
  "scripts": {