joytalk 0.0.2 → 0.0.3

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[je]=this[je]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=X(i);r[c]||(_n(s,i),r[c]=!0)}return a.isArray(t)?t.forEach(o):o(t),this}};C.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);a.reduceDescriptors(C.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});a.freezeMethods(C);function Te(e,t){const n=this||ee,r=t||n,s=C.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 dt(e){return!!(e&&e.__CANCEL__)}function K(e,t,n){E.call(this,e??"canceled",E.ERR_CANCELED,t,n),this.name="CanceledError"}a.inherits(K,E,{__CANCEL__:!0});function ht(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 Dn(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Fn(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 p=o,S=0;for(;p!==s;)S+=n[p++],p=p%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),u-i<t)return;const w=l&&u-l;return w?Math.round(S*1e3/w):void 0}}function xn(e,t){let n=0,r=1e3/t,s,o;const i=(u,l=Date.now())=>{n=l,s=null,o&&(clearTimeout(o),o=null),e(...u)};return[(...u)=>{const l=Date.now(),p=l-n;p>=r?i(u,l):(s=u,o||(o=setTimeout(()=>{o=null,i(s)},r-p)))},()=>s&&i(s)]}const ce=(e,t,n=3)=>{let r=0;const s=Fn(50,250);return xn(o=>{const i=o.loaded,c=o.lengthComputable?o.total:void 0,d=i-r,u=s(d),l=i<=c;r=i;const p={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(p)},n)},ve=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},qe=e=>(...t)=>a.asap(()=>e(...t)),Ln=R.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,R.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(R.origin),R.navigator&&/(msie|trident)/i.test(R.navigator.userAgent)):()=>!0,In=R.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 Pn(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function kn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function pt(e,t,n){let r=!Pn(t);return e&&(r||n==!1)?kn(e,t):t}const Me=e=>e instanceof C?{...e}:e;function M(e,t){t=t||{};const n={};function r(u,l,p,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,p,S){if(a.isUndefined(l)){if(!a.isUndefined(u))return r(void 0,u,p,S)}else return r(u,l,p,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,p){if(p in t)return r(u,l);if(p 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,p)=>s(Me(u),Me(l),p,!0)};return a.forEach(Object.keys({...e,...t}),function(l){const p=d[l]||s,S=p(e[l],t[l],l);a.isUndefined(S)&&p!==c||(n[l]=S)}),n}const mt=e=>{const t=M({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:c}=t;if(t.headers=i=C.from(i),t.url=lt(pt(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(R.hasStandardBrowserEnv||R.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,p])=>{u.includes(l.toLowerCase())&&i.set(l,p)})}}if(R.hasStandardBrowserEnv&&(r&&a.isFunction(r)&&(r=r(t)),r||r!==!1&&Ln(t.url))){const d=s&&o&&In.read(o);d&&i.set(s,d)}return t},Bn=typeof XMLHttpRequest<"u",Hn=Bn&&function(e){return new Promise(function(n,r){const s=mt(e);let o=s.data;const i=C.from(s.headers).normalize();let{responseType:c,onUploadProgress:d,onDownloadProgress:u}=s,l,p,S,w,f;function m(){w&&w(),f&&f(),s.cancelToken&&s.cancelToken.unsubscribe(l),s.signal&&s.signal.removeEventListener("abort",l)}let h=new XMLHttpRequest;h.open(s.method.toUpperCase(),s.url,!0),h.timeout=s.timeout;function y(){if(!h)return;const b=C.from("getAllResponseHeaders"in h&&h.getAllResponseHeaders()),D={data:!c||c==="text"||c==="json"?h.responseText:h.response,status:h.status,statusText:h.statusText,headers:b,config:e,request:h};ht(function(_){n(_),m()},function(_){r(_),m()},D),h=null}"onloadend"in h?h.onloadend=y:h.onreadystatechange=function(){!h||h.readyState!==4||h.status===0&&!(h.responseURL&&h.responseURL.indexOf("file:")===0)||setTimeout(y)},h.onabort=function(){h&&(r(new E("Request aborted",E.ECONNABORTED,e,h)),h=null)},h.onerror=function(g){const D=g&&g.message?g.message:"Network Error",H=new E(D,E.ERR_NETWORK,e,h);H.event=g||null,r(H),h=null},h.ontimeout=function(){let g=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const D=s.transitional||ut;s.timeoutErrorMessage&&(g=s.timeoutErrorMessage),r(new E(g,D.clarifyTimeoutError?E.ETIMEDOUT:E.ECONNABORTED,e,h)),h=null},o===void 0&&i.setContentType(null),"setRequestHeader"in h&&a.forEach(i.toJSON(),function(g,D){h.setRequestHeader(D,g)}),a.isUndefined(s.withCredentials)||(h.withCredentials=!!s.withCredentials),c&&c!=="json"&&(h.responseType=s.responseType),u&&([S,f]=ce(u,!0),h.addEventListener("progress",S)),d&&h.upload&&([p,w]=ce(d),h.upload.addEventListener("progress",p),h.upload.addEventListener("loadend",w)),(s.cancelToken||s.signal)&&(l=b=>{h&&(r(!b||b.type?new K(null,e,h):b),h.abort(),h=null)},s.cancelToken&&s.cancelToken.subscribe(l),s.signal&&(s.signal.aborted?l():s.signal.addEventListener("abort",l)));const U=Dn(s.url);if(U&&R.protocols.indexOf(U)===-1){r(new E("Unsupported protocol "+U+":",E.ERR_BAD_REQUEST,e));return}h.send(o||null)})},jn=(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 K(l instanceof Error?l.message:l))}};let i=t&&setTimeout(()=>{i=null,o(new E(`timeout ${t} of ms exceeded`,E.ETIMEDOUT))},t);const c=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(u=>{u.unsubscribe?u.unsubscribe(o):u.removeEventListener("abort",o)}),e=null)};e.forEach(u=>u.addEventListener("abort",o));const{signal:d}=r;return d.unsubscribe=()=>a.asap(c),d}},vn=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,s;for(;r<n;)s=r+t,yield e.slice(r,s),r=s},qn=async function*(e,t){for await(const n of Mn(e))yield*vn(n,t)},Mn=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()}},$e=(e,t,n,r)=>{const s=qn(e,t);let o=0,i,c=d=>{i||(i=!0,r&&r(d))};return new ReadableStream({async pull(d){try{const{done:u,value:l}=await s.next();if(u){c(),d.close();return}let p=l.byteLength;if(n){let S=o+=p;n(S)}d.enqueue(new Uint8Array(l))}catch(u){throw c(u),u}},cancel(d){return c(d),s.return()}},{highWaterMark:2})},Je=64*1024,{isFunction:se}=a,$n=(({Request:e,Response:t})=>({Request:e,Response:t}))(a.global),{ReadableStream:ze,TextEncoder:Ge}=a.global,We=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Jn=e=>{e=a.merge.call({skipUndefined:!0},$n,e);const{fetch:t,Request:n,Response:r}=e,s=t?se(t):typeof fetch=="function",o=se(n),i=se(r);if(!s)return!1;const c=s&&se(ze),d=s&&(typeof Ge=="function"?(f=>m=>f.encode(m))(new Ge):async f=>new Uint8Array(await new n(f).arrayBuffer())),u=o&&c&&We(()=>{let f=!1;const m=new n(R.origin,{body:new ze,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!m}),l=i&&c&&We(()=>a.isReadableStream(new r("").body)),p={stream:l&&(f=>f.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!p[f]&&(p[f]=(m,h)=>{let y=m&&m[f];if(y)return y.call(m);throw new E(`Response type '${f}' is not supported`,E.ERR_NOT_SUPPORT,h)})});const S=async f=>{if(f==null)return 0;if(a.isBlob(f))return f.size;if(a.isSpecCompliantForm(f))return(await new n(R.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 h=a.toFiniteNumber(f.getContentLength());return h??S(m)};return async f=>{let{url:m,method:h,data:y,signal:U,cancelToken:b,timeout:g,onDownloadProgress:D,onUploadProgress:H,responseType:_,headers:me,withCredentials:te="same-origin",fetchOptions:_e}=mt(f),De=t||fetch;_=_?(_+"").toLowerCase():"text";let ne=jn([U,b&&b.toAbortSignal()],g),V=null;const j=ne&&ne.unsubscribe&&(()=>{ne.unsubscribe()});let Fe;try{if(H&&u&&h!=="get"&&h!=="head"&&(Fe=await w(me,y))!==0){let k=new n(m,{method:"POST",body:y,duplex:"half"}),J;if(a.isFormData(y)&&(J=k.headers.get("content-type"))&&me.setContentType(J),k.body){const[Ee,re]=ve(Fe,ce(qe(H)));y=$e(k.body,Je,Ee,re)}}a.isString(te)||(te=te?"include":"omit");const L=o&&"credentials"in n.prototype,xe={..._e,signal:ne,method:h.toUpperCase(),headers:me.normalize().toJSON(),body:y,duplex:"half",credentials:L?te:void 0};V=o&&new n(m,xe);let P=await(o?De(V,_e):De(m,xe));const Le=l&&(_==="stream"||_==="response");if(l&&(D||Le&&j)){const k={};["status","statusText","headers"].forEach(Ie=>{k[Ie]=P[Ie]});const J=a.toFiniteNumber(P.headers.get("content-length")),[Ee,re]=D&&ve(J,ce(qe(D),!0))||[];P=new r($e(P.body,Je,Ee,()=>{re&&re(),j&&j()}),k)}_=_||"text";let wt=await p[a.findKey(p,_)||"text"](P,f);return!Le&&j&&j(),await new Promise((k,J)=>{ht(k,J,{data:wt,headers:C.from(P.headers),status:P.status,statusText:P.statusText,config:f,request:V})})}catch(L){throw j&&j(),L&&L.name==="TypeError"&&/Load failed|fetch/i.test(L.message)?Object.assign(new E("Network Error",E.ERR_NETWORK,f,V),{cause:L.cause||L}):E.from(L,L&&L.code,f,V)}}},zn=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=zn;for(;c--;)d=o[c],u=l.get(d),u===void 0&&l.set(d,u=c?new Map:Jn(t)),l=u;return u};Et();const Ce={http:cn,xhr:Hn,fetch:{get:Et}};a.forEach(Ce,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Ke=e=>`- ${e}`,Gn=e=>a.isFunction(e)||e===null||e===!1;function Wn(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,!Gn(r)&&(s=Ce[(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(Ke).join(`
5
5
  `):" "+Ke(i[0]):"as no adapter specified";throw new E("There is no suitable adapter to dispatch the request "+c,"ERR_NOT_SUPPORT")}return s}const St={getAdapter:Wn,adapters:Ce};function ye(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new K(null,e)}function Ve(e){return ye(e),e.headers=C.from(e.headers),e.data=Te.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),St.getAdapter(e.adapter||ee.adapter,e)(e).then(function(r){return ye(e),r.data=Te.call(e,e.transformResponse,r),r.headers=C.from(r.headers),r},function(r){return dt(r)||(ye(e),r&&r.response&&(r.response.data=Te.call(e,e.transformResponse,r.response),r.response.headers=C.from(r.response.headers))),Promise.reject(r)})}const Tt="1.13.2",pe={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{pe[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Xe={};pe.transitional=function(t,n,r){function s(o,i){return"[Axios v"+Tt+"] 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&&!Xe[i]&&(Xe[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}};pe.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Kn(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 ae={assertOptions:Kn,validators:pe},I=ae.validators;let q=class{constructor(t){this.defaults=t||{},this.interceptors={request:new He,response:new He}}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=M(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&ae.assertOptions(r,{silentJSONParsing:I.transitional(I.boolean),forcedJSONParsing:I.transitional(I.boolean),clarifyTimeoutError:I.transitional(I.boolean)},!1),s!=null&&(a.isFunction(s)?n.paramsSerializer={serialize:s}:ae.assertOptions(s,{encode:I.function,serialize:I.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ae.assertOptions(n,{baseUrl:I.spelling("baseURL"),withXsrfToken:I.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=C.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,p=0,S;if(!d){const f=[Ve.bind(this),void 0];for(f.unshift(...c),f.push(...u),S=f.length,l=Promise.resolve(n);p<S;)l=l.then(f[p++],f[p++]);return l}S=c.length;let w=n;for(;p<S;){const f=c[p++],m=c[p++];try{w=f(w)}catch(h){m.call(this,h);break}}try{l=Ve.call(this,w)}catch(f){return Promise.reject(f)}for(p=0,S=u.length;p<S;)l=l.then(u[p++],u[p++]);return l}getUri(t){t=M(this.defaults,t);const n=pt(t.baseURL,t.url,t.allowAbsoluteUrls);return lt(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){q.prototype[t]=function(n,r){return this.request(M(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(M(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}q.prototype[t]=n(),q.prototype[t+"Form"]=n(!0)});let Vn=class yt{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 K(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 yt(function(s){t=s}),cancel:t}}};function Xn(e){return function(n){return e.apply(null,n)}}function Qn(e){return a.isObject(e)&&e.isAxiosError===!0}const Oe={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(Oe).forEach(([e,t])=>{Oe[t]=e});function bt(e){const t=new q(e),n=Qe(q.prototype.request,t);return a.extend(n,q.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return bt(M(e,s))},n}const T=bt(ee);T.Axios=q;T.CanceledError=K;T.CancelToken=Vn;T.isCancel=dt;T.VERSION=Tt;T.toFormData=he;T.AxiosError=E;T.Cancel=T.CanceledError;T.all=function(t){return Promise.all(t)};T.spread=Xn;T.isAxiosError=Qn;T.mergeConfig=M;T.AxiosHeaders=C;T.formToJSON=e=>ft(a.isHTMLForm(e)?new FormData(e):e);T.getAdapter=St.getAdapter;T.HttpStatusCode=Oe;T.default=T;const{Axios:ur,AxiosError:fr,CanceledError:dr,isCancel:hr,CancelToken:pr,VERSION:mr,all:Er,Cancel:Sr,isAxiosError:Tr,spread:yr,toFormData:br,AxiosHeaders:wr,HttpStatusCode:Rr,formToJSON:Or,getAdapter:Ar,mergeConfig:gr}=T,Ue="JOYTALK_TOKEN";var z=(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))(z||{}),F=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(F||{}),B=(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))(B||{}),le=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(le||{});function Yn(e){return e.contentType==="1"}var O=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(O||{}),A=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(A||{});const $=T.create({baseURL:"http://dev-joytalk-api.halaladmin.vip",timeout:6e5});$.interceptors.request.use(e=>(e.noAuth||(e.headers.Authorization=`Bearer ${localStorage.getItem(Ue)}`),delete e.noAuth,e),e=>Promise.reject(e));$.interceptors.response.use(e=>e.data.code!==200?(console.error(e.data.message),Promise.reject(e)):Promise.resolve(e.data),e=>Promise.reject(e));const Zn=e=>$.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),er=e=>T.post("https://joytalk-fat.obs.ap-southeast-1.myhuaweicloud.com:443",e,{headers:{"Content-Type":"multipart/form-data"}}),tr=e=>$.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),nr=e=>$.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),rr=()=>$.get("/api/open-auth/user/v1/UserService/GetUserInfo"),sr=e=>$.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e);class or{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()}}const ir="https://joytalk-fat.obs.ap-southeast-1.myhuaweicloud.com:443/";class ar extends or{config;ws=null;status=A.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;customerGroupId="";OBS_URL=ir;sessionData=null;userInfo=null;constructor(t){super(),this.config={token:t.token||"",autoReconnect:t.autoReconnect??!0,reconnectInterval:t.reconnectInterval??3e3,maxReconnectAttempts:t.maxReconnectAttempts??5,heartbeatTimeout:t.heartbeatTimeout??1e4},localStorage.setItem(Ue,this.config.token||"")}connect(t){return this.customerGroupId=t,new Promise((n,r)=>{if(this.status===A.CONNECTED){n();return}if(this.status!==A.CONNECTING){this.setStatus(A.CONNECTING);try{const s=this.buildWebSocketUrl();this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(A.CONNECTED),this.emit(O.CONNECTED),n()},this.ws.onmessage=o=>{try{this.handleMessage(o.data)}catch(i){console.error("解析消息失败:",i)}},this.ws.onerror=o=>{console.error("连接错误:",o),this.setStatus(A.ERROR),this.emit(O.ERROR,o),r(o)},this.ws.onclose=()=>{this.setStatus(A.DISCONNECTED),this.emit(O.DISCONNECTED),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(A.ERROR),this.emit(O.ERROR,s),r(s)}}})}disconnect(){this.config.autoReconnect=!1,this.sessionData=null,this.clearReconnectTimer(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus(A.DISCONNECTED)}sendMessage(t,n,r=z.SEND){if(this.status!==A.CONNECTED||!this.ws)throw new Error("未连接到服务器");const s={msgType:r,data:t,toUid:this.sessionData?.cid,chatType:n,editId:void 0};this.ws.send(JSON.stringify(s))}sendText(t){return this.sendMessage(t,F.TEXT),Promise.resolve(!0)}sendFile({file:t,thumbnailFile:n,chatType:r}){return new Promise(async(s,o)=>{try{const[i,c]=await Promise.all([this.handleUploadFile(t),n?this.handleUploadFile(n):Promise.resolve(void 0)]),d={fileName:t.name,fileUrl:i,thumbnailUrl:c,fileSize:t.size};this.sendMessage(JSON.stringify(d),r),s(JSON.stringify(d))}catch(i){console.error("上传文件失败:",i),o(i)}})}getStatus(){return this.status}isConnected(){return this.status===A.CONNECTED}buildWebSocketUrl(){const t=new URL("ws://dev-joytalk-api.halaladmin.vip/api/ws");return this.config.token&&t.searchParams.set("Authorization",this.config.token),t.toString()}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),this.isMessage(t))try{switch(t.code){case B.CONNECT_SUCCESS:this.sendMessage(this.customerGroupId,void 0,z.INBOUND);break;case B.MATCH_INFO:case B.MATCH_SUCCESS:if(console.log("MATCH_SUCCESS",this.sessionData),this.sessionData)return;const n=JSON.parse(typeof t.data=="string"?t.data:JSON.stringify(t.data));this.sessionData=n,t.data=n,this.getFaqList(),this.emit(O.MESSAGE,t);break;case B.SEND_SUCCESS:const r=JSON.parse(typeof t.data=="string"?t.data:JSON.stringify(t.data));if(r.sessionId!==this.sessionData?.sessionId)return;t.chatType!==F.TEXT&&typeof r.content=="string"&&(r.content=JSON.parse(r.content),r.content?.fileUrl?.startsWith("http")||(r.content.fileUrl=this.OBS_URL+r.content.fileUrl),r.content?.thumbnailUrl?.startsWith("http")||(r.content.thumbnailUrl=this.OBS_URL+r.content.thumbnailUrl)),t.data=r,this.emit(O.MESSAGE,t);break;default:this.emit(O.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}isMessage(t){return typeof t=="object"&&t!==null&&"data"in t&&"msgType"in t&&"toUid"in t&&"chatType"in t&&"code"in t}setStatus(t){this.status!==t&&(this.status=t,this.emit(O.STATUS_CHANGE,t))}scheduleReconnect(){this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(A.RECONNECTING),this.reconnectTimer=setTimeout(()=>{this.connect(this.customerGroupId).catch(t=>{console.error("重连失败:",t)})},this.config.reconnectInterval)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}sendHeartbeat(){if(!(this.status!==A.CONNECTED||!this.ws))try{this.ws.send("pong"),this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer=setTimeout(()=>{Date.now()-this.lastHeartbeatTime>=this.config.heartbeatTimeout&&(this.emit(O.HEARTBEAT_TIMEOUT),console.warn("心跳超时,尝试重连"),this.ws&&this.ws.close())},this.config.heartbeatTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=10}){const r=await sr({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>{let i=o.content;return o.contentType===F.TEXT?i=o.content:(i=JSON.parse(o.content),i?.fileUrl?.startsWith("http")||(i.fileUrl=this.OBS_URL+i.fileUrl),i?.thumbnailUrl?.startsWith("http")||(i.thumbnailUrl=this.OBS_URL+i.thumbnailUrl)),{...o,content:i}});return{hasMore:r.data.hasMore,list:s.reverse()}}getConsultationList(t){return tr({entranceId:t})}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await Zn({ext:s||""}),{accessKeyId:i,signature:c,policy:d,key:u}=o.data,l=new FormData;l.append("key",u),l.append("AccessKeyId",i),l.append("signature",c),l.append("policy",d),l.append("file",t),(await er(l)).status===204?n(this.OBS_URL+u):r(new Error("上传文件失败"))})}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("loadedmetadata",()=>{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(new 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(new Error("视频加载失败"))}),s.load()});async getFaqList(){const t=await nr({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:B.SEND_SUCCESS,data:{content:n,contentType:F.FAQ,sendUserType:le.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now()},msgType:z.SEND,chatType:F.FAQ,toUid:this.sessionData?.uid};this.emit(O.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={sendUserType:le.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now()},r={code:B.SEND_SUCCESS,data:n,msgType:z.SEND,chatType:F.FAQ,toUid:this.sessionData?.uid};if(t.isMulti){const s={...r,data:{...n,content:{list:t.item},contentType:F.FAQ}};this.emit(O.MESSAGE,s)}else{const s=t.item?.[0]||t;if(s.answer){const o={...r,data:{...n,content:s.answer,contentType:F.TEXT}};this.emit(O.MESSAGE,o)}s.imageUrl?.forEach(o=>{const i={...r,data:{...n,content:{fileUrl:o?.startsWith("http")?o:this.OBS_URL+o,fileName:o.split("/").pop()},contentType:F.IMAGE}};this.emit(O.MESSAGE,i)})}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await rr();return this.userInfo=t.data,this.userInfo}}exports.ChatType=F;exports.ConnectionStatus=A;exports.EventType=O;exports.MessageCode=B;exports.MessageType=z;exports.SendUserType=le;exports.TOKEN_KEY=Ue;exports.default=ar;exports.isTextMessage=Yn;
6
+ `+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=M(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&ae.assertOptions(r,{silentJSONParsing:I.transitional(I.boolean),forcedJSONParsing:I.transitional(I.boolean),clarifyTimeoutError:I.transitional(I.boolean)},!1),s!=null&&(a.isFunction(s)?n.paramsSerializer={serialize:s}:ae.assertOptions(s,{encode:I.function,serialize:I.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ae.assertOptions(n,{baseUrl:I.spelling("baseURL"),withXsrfToken:I.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=C.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,p=0,S;if(!d){const f=[Ve.bind(this),void 0];for(f.unshift(...c),f.push(...u),S=f.length,l=Promise.resolve(n);p<S;)l=l.then(f[p++],f[p++]);return l}S=c.length;let w=n;for(;p<S;){const f=c[p++],m=c[p++];try{w=f(w)}catch(h){m.call(this,h);break}}try{l=Ve.call(this,w)}catch(f){return Promise.reject(f)}for(p=0,S=u.length;p<S;)l=l.then(u[p++],u[p++]);return l}getUri(t){t=M(this.defaults,t);const n=pt(t.baseURL,t.url,t.allowAbsoluteUrls);return lt(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){q.prototype[t]=function(n,r){return this.request(M(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(M(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}q.prototype[t]=n(),q.prototype[t+"Form"]=n(!0)});let Vn=class yt{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 K(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 yt(function(s){t=s}),cancel:t}}};function Xn(e){return function(n){return e.apply(null,n)}}function Qn(e){return a.isObject(e)&&e.isAxiosError===!0}const Oe={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(Oe).forEach(([e,t])=>{Oe[t]=e});function bt(e){const t=new q(e),n=Qe(q.prototype.request,t);return a.extend(n,q.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return bt(M(e,s))},n}const T=bt(ee);T.Axios=q;T.CanceledError=K;T.CancelToken=Vn;T.isCancel=dt;T.VERSION=Tt;T.toFormData=he;T.AxiosError=E;T.Cancel=T.CanceledError;T.all=function(t){return Promise.all(t)};T.spread=Xn;T.isAxiosError=Qn;T.mergeConfig=M;T.AxiosHeaders=C;T.formToJSON=e=>ft(a.isHTMLForm(e)?new FormData(e):e);T.getAdapter=St.getAdapter;T.HttpStatusCode=Oe;T.default=T;const{Axios:ur,AxiosError:fr,CanceledError:dr,isCancel:hr,CancelToken:pr,VERSION:mr,all:Er,Cancel:Sr,isAxiosError:Tr,spread:yr,toFormData:br,AxiosHeaders:wr,HttpStatusCode:Rr,formToJSON:Or,getAdapter:Ar,mergeConfig:gr}=T,Ue="JOYTALK_TOKEN";var z=(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))(z||{}),F=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(F||{}),B=(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))(B||{}),le=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(le||{});function Yn(e){return e.contentType==="1"}var O=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(O||{}),A=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(A||{});const $=T.create({baseURL:"http://dev-joytalk-api.halaladmin.vip",timeout:6e5});$.interceptors.request.use(e=>(e.noAuth||(e.headers.Authorization=`Bearer ${localStorage.getItem(Ue)}`),delete e.noAuth,e),e=>Promise.reject(e));$.interceptors.response.use(e=>e.data.code!==200?(console.error(e.data.message),Promise.reject(e)):Promise.resolve(e.data),e=>Promise.reject(e));const Zn=e=>$.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),er=e=>T.post("https://joytalk-fat.obs.ap-southeast-1.myhuaweicloud.com",e,{headers:{"Content-Type":"multipart/form-data"}}),tr=e=>$.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),nr=e=>$.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),rr=()=>$.get("/api/open-auth/user/v1/UserService/GetUserInfo"),sr=e=>$.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e);class or{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()}}const ir="https://joytalk-fat.obs.ap-southeast-1.myhuaweicloud.com/";class ar extends or{config;ws=null;status=A.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;customerGroupId="";OBS_URL=ir;sessionData=null;userInfo=null;constructor(t){super(),this.config={token:t.token||"",autoReconnect:t.autoReconnect??!0,reconnectInterval:t.reconnectInterval??3e3,maxReconnectAttempts:t.maxReconnectAttempts??5,heartbeatTimeout:t.heartbeatTimeout??1e4},localStorage.setItem(Ue,this.config.token||"")}connect(t){return this.customerGroupId=t,new Promise((n,r)=>{if(this.status===A.CONNECTED){n();return}if(this.status!==A.CONNECTING){this.setStatus(A.CONNECTING);try{const s=this.buildWebSocketUrl();this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(A.CONNECTED),this.emit(O.CONNECTED),n()},this.ws.onmessage=o=>{try{this.handleMessage(o.data)}catch(i){console.error("解析消息失败:",i)}},this.ws.onerror=o=>{console.error("连接错误:",o),this.setStatus(A.ERROR),this.emit(O.ERROR,o),r(o)},this.ws.onclose=()=>{this.setStatus(A.DISCONNECTED),this.emit(O.DISCONNECTED),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(A.ERROR),this.emit(O.ERROR,s),r(s)}}})}disconnect(){this.config.autoReconnect=!1,this.sessionData=null,this.clearReconnectTimer(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus(A.DISCONNECTED)}sendMessage(t,n,r=z.SEND){if(this.status!==A.CONNECTED||!this.ws)throw new Error("未连接到服务器");const s={msgType:r,data:t,toUid:this.sessionData?.cid,chatType:n,editId:void 0};this.ws.send(JSON.stringify(s))}sendText(t){return this.sendMessage(t,F.TEXT),Promise.resolve(!0)}sendFile({file:t,thumbnailFile:n,chatType:r}){return new Promise(async(s,o)=>{try{const[i,c]=await Promise.all([this.handleUploadFile(t),n?this.handleUploadFile(n):Promise.resolve(void 0)]),d={fileName:t.name,fileUrl:i,thumbnailUrl:c,fileSize:t.size};this.sendMessage(JSON.stringify(d),r),s(JSON.stringify(d))}catch(i){console.error("上传文件失败:",i),o(i)}})}getStatus(){return this.status}isConnected(){return this.status===A.CONNECTED}buildWebSocketUrl(){const t=new URL("ws://dev-joytalk-api.halaladmin.vip/api/ws");return this.config.token&&t.searchParams.set("Authorization",this.config.token),t.toString()}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),this.isMessage(t))try{switch(t.code){case B.CONNECT_SUCCESS:this.sendMessage(this.customerGroupId,void 0,z.INBOUND);break;case B.MATCH_INFO:case B.MATCH_SUCCESS:if(console.log("MATCH_SUCCESS",this.sessionData),this.sessionData)return;const n=JSON.parse(typeof t.data=="string"?t.data:JSON.stringify(t.data));this.sessionData=n,t.data=n,this.getFaqList(),this.emit(O.MESSAGE,t);break;case B.SEND_SUCCESS:const r=JSON.parse(typeof t.data=="string"?t.data:JSON.stringify(t.data));if(r.sessionId!==this.sessionData?.sessionId)return;t.chatType!==F.TEXT&&typeof r.content=="string"&&(r.content=JSON.parse(r.content),r.content?.fileUrl?.startsWith("http")||(r.content.fileUrl=this.OBS_URL+r.content.fileUrl),r.content?.thumbnailUrl?.startsWith("http")||(r.content.thumbnailUrl=this.OBS_URL+r.content.thumbnailUrl)),t.data=r,this.emit(O.MESSAGE,t);break;default:this.emit(O.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}isMessage(t){return typeof t=="object"&&t!==null&&"data"in t&&"msgType"in t&&"toUid"in t&&"chatType"in t&&"code"in t}setStatus(t){this.status!==t&&(this.status=t,this.emit(O.STATUS_CHANGE,t))}scheduleReconnect(){this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(A.RECONNECTING),this.reconnectTimer=setTimeout(()=>{this.connect(this.customerGroupId).catch(t=>{console.error("重连失败:",t)})},this.config.reconnectInterval)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}sendHeartbeat(){if(!(this.status!==A.CONNECTED||!this.ws))try{this.ws.send("pong"),this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer=setTimeout(()=>{Date.now()-this.lastHeartbeatTime>=this.config.heartbeatTimeout&&(this.emit(O.HEARTBEAT_TIMEOUT),console.warn("心跳超时,尝试重连"),this.ws&&this.ws.close())},this.config.heartbeatTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=50}){const r=await sr({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>{let i=o.content;return o.contentType===F.TEXT?i=o.content:(i=JSON.parse(o.content),i?.fileUrl?.startsWith("http")||(i.fileUrl=this.OBS_URL+i.fileUrl),i?.thumbnailUrl?.startsWith("http")||(i.thumbnailUrl=this.OBS_URL+i.thumbnailUrl)),{...o,content:i}});return{hasMore:r.data.hasMore,list:s.reverse()}}getConsultationList(t){return tr({entranceId:t})}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await Zn({ext:s||""}),{accessKeyId:i,signature:c,policy:d,key:u}=o.data,l=new FormData;l.append("key",u),l.append("AccessKeyId",i),l.append("signature",c),l.append("policy",d),l.append("file",t),(await er(l)).status===204?n(this.OBS_URL+u):r(new Error("上传文件失败"))})}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(new 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(new Error("视频加载失败"))}),s.load()});async getFaqList(){const t=await nr({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:B.SEND_SUCCESS,data:{content:n,contentType:F.FAQ,sendUserType:le.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now()},msgType:z.SEND,chatType:F.FAQ,toUid:this.sessionData?.uid};this.emit(O.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={sendUserType:le.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now()},r={code:B.SEND_SUCCESS,data:n,msgType:z.SEND,chatType:F.FAQ,toUid:this.sessionData?.uid};if(t.isMulti){const s={...r,data:{...n,content:{list:t.item},contentType:F.FAQ}};this.emit(O.MESSAGE,s)}else{const s=t.item?.[0]||t;if(s.answer){const o={...r,data:{...n,content:s.answer,contentType:F.TEXT}};this.emit(O.MESSAGE,o)}s.imageUrl?.forEach(o=>{const i={...r,data:{...n,content:{fileUrl:o?.startsWith("http")?o:this.OBS_URL+o,fileName:o.split("/").pop()},contentType:F.IMAGE}};this.emit(O.MESSAGE,i)})}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await rr();return this.userInfo=t.data,this.userInfo}}exports.ChatType=F;exports.ConnectionStatus=A;exports.EventType=O;exports.MessageCode=B;exports.MessageType=z;exports.SendUserType=le;exports.TOKEN_KEY=Ue;exports.default=ar;exports.isTextMessage=Yn;
package/dist/index.es.js CHANGED
@@ -61,10 +61,10 @@ function et(e, t) {
61
61
  return null;
62
62
  }
63
63
  const v = typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : typeof window < "u" ? window : global, tt = (e) => !z(e) && e !== v;
64
- function Te() {
64
+ function ye() {
65
65
  const { caseless: e, skipUndefined: t } = tt(this) && this || {}, n = {}, r = (s, o) => {
66
66
  const i = e && et(n, o) || o;
67
- oe(n[i]) && oe(s) ? n[i] = Te(n[i], s) : oe(s) ? n[i] = Te({}, s) : G(s) ? n[i] = s.slice() : (!t || !z(s)) && (n[i] = s);
67
+ oe(n[i]) && oe(s) ? n[i] = ye(n[i], s) : oe(s) ? n[i] = ye({}, s) : G(s) ? n[i] = s.slice() : (!t || !z(s)) && (n[i] = s);
68
68
  };
69
69
  for (let s = 0, o = arguments.length; s < o; s++)
70
70
  arguments[s] && Z(arguments[s], r);
@@ -203,7 +203,7 @@ const nn = (e) => {
203
203
  isTypedArray: zt,
204
204
  isFileList: Dt,
205
205
  forEach: Z,
206
- merge: Te,
206
+ merge: ye,
207
207
  extend: jt,
208
208
  trim: Ht,
209
209
  stripBOM: vt,
@@ -289,7 +289,7 @@ E.from = (e, t, n, r, s, o) => {
289
289
  return E.call(i, c, d, n, r, s), e && i.cause == null && Object.defineProperty(i, "cause", { value: e, configurable: !0 }), i.name = e && e.name || "Error", o && Object.assign(i, o), i;
290
290
  };
291
291
  const cn = null;
292
- function be(e) {
292
+ function Te(e) {
293
293
  return a.isPlainObject(e) || a.isArray(e);
294
294
  }
295
295
  function it(e) {
@@ -301,7 +301,7 @@ function Pe(e, t, n) {
301
301
  }).join(n ? "." : "") : t;
302
302
  }
303
303
  function ln(e) {
304
- return a.isArray(e) && !e.some(be);
304
+ return a.isArray(e) && !e.some(Te);
305
305
  }
306
306
  const un = a.toFlatObject(a, {}, null, function(t) {
307
307
  return /^is[A-Z]/.test(t);
@@ -330,38 +330,38 @@ function de(e, t, n) {
330
330
  return a.isArrayBuffer(f) || a.isTypedArray(f) ? d && typeof Blob == "function" ? new Blob([f]) : Buffer.from(f) : f;
331
331
  }
332
332
  function l(f, m, h) {
333
- let T = f;
333
+ let y = f;
334
334
  if (f && !h && typeof f == "object") {
335
335
  if (a.endsWith(m, "{}"))
336
336
  m = r ? m : m.slice(0, -2), f = JSON.stringify(f);
337
- else if (a.isArray(f) && ln(f) || (a.isFileList(f) || a.endsWith(m, "[]")) && (T = a.toArray(f)))
338
- return m = it(m), T.forEach(function(b, O) {
339
- !(a.isUndefined(b) || b === null) && t.append(
337
+ else if (a.isArray(f) && ln(f) || (a.isFileList(f) || a.endsWith(m, "[]")) && (y = a.toArray(f)))
338
+ return m = it(m), y.forEach(function(T, O) {
339
+ !(a.isUndefined(T) || T === null) && t.append(
340
340
  // eslint-disable-next-line no-nested-ternary
341
341
  i === !0 ? Pe([m], O, o) : i === null ? m : m + "[]",
342
- u(b)
342
+ u(T)
343
343
  );
344
344
  }), !1;
345
345
  }
346
- return be(f) ? !0 : (t.append(Pe(h, m, o), u(f)), !1);
346
+ return Te(f) ? !0 : (t.append(Pe(h, m, o), u(f)), !1);
347
347
  }
348
348
  const p = [], S = Object.assign(un, {
349
349
  defaultVisitor: l,
350
350
  convertValue: u,
351
- isVisitable: be
351
+ isVisitable: Te
352
352
  });
353
353
  function w(f, m) {
354
354
  if (!a.isUndefined(f)) {
355
355
  if (p.indexOf(f) !== -1)
356
356
  throw Error("Circular reference detected in " + m.join("."));
357
- p.push(f), a.forEach(f, function(T, U) {
358
- (!(a.isUndefined(T) || T === null) && s.call(
357
+ p.push(f), a.forEach(f, function(y, U) {
358
+ (!(a.isUndefined(y) || y === null) && s.call(
359
359
  t,
360
- T,
360
+ y,
361
361
  a.isString(U) ? U.trim() : U,
362
362
  m,
363
363
  S
364
- )) === !0 && w(T, m ? m.concat(U) : [U]);
364
+ )) === !0 && w(y, m ? m.concat(U) : [U]);
365
365
  }), p.pop();
366
366
  }
367
367
  }
@@ -483,18 +483,18 @@ const lt = {
483
483
  },
484
484
  protocols: ["http", "https", "file", "blob", "url", "data"]
485
485
  }, Ne = typeof window < "u" && typeof document < "u", we = typeof navigator == "object" && navigator || void 0, En = Ne && (!we || ["ReactNative", "NativeScript", "NS"].indexOf(we.product) < 0), Sn = typeof WorkerGlobalScope < "u" && // eslint-disable-next-line no-undef
486
- self instanceof WorkerGlobalScope && typeof self.importScripts == "function", yn = Ne && window.location.href || "http://localhost", Tn = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
486
+ self instanceof WorkerGlobalScope && typeof self.importScripts == "function", bn = Ne && window.location.href || "http://localhost", yn = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
487
487
  __proto__: null,
488
488
  hasBrowserEnv: Ne,
489
489
  hasStandardBrowserEnv: En,
490
490
  hasStandardBrowserWebWorkerEnv: Sn,
491
491
  navigator: we,
492
- origin: yn
492
+ origin: bn
493
493
  }, Symbol.toStringTag, { value: "Module" })), R = {
494
- ...Tn,
494
+ ...yn,
495
495
  ...mn
496
496
  };
497
- function bn(e, t) {
497
+ function Tn(e, t) {
498
498
  return de(e, new R.classes.URLSearchParams(), {
499
499
  visitor: function(n, r, s, o) {
500
500
  return R.isNode && a.isBuffer(n) ? (this.append(r, n.toString("base64")), !1) : o.defaultVisitor.apply(this, arguments);
@@ -555,7 +555,7 @@ const ee = {
555
555
  let c;
556
556
  if (o) {
557
557
  if (r.indexOf("application/x-www-form-urlencoded") > -1)
558
- return bn(t, this.formSerializer).toString();
558
+ return Tn(t, this.formSerializer).toString();
559
559
  if ((c = a.isFileList(t)) || r.indexOf("multipart/form-data") > -1) {
560
560
  const d = this.env && this.env.FormData;
561
561
  return de(
@@ -1032,16 +1032,16 @@ const pt = (e) => {
1032
1032
  }
1033
1033
  let h = new XMLHttpRequest();
1034
1034
  h.open(s.method.toUpperCase(), s.url, !0), h.timeout = s.timeout;
1035
- function T() {
1035
+ function y() {
1036
1036
  if (!h)
1037
1037
  return;
1038
- const b = C.from(
1038
+ const T = C.from(
1039
1039
  "getAllResponseHeaders" in h && h.getAllResponseHeaders()
1040
1040
  ), D = {
1041
1041
  data: !c || c === "text" || c === "json" ? h.responseText : h.response,
1042
1042
  status: h.status,
1043
1043
  statusText: h.statusText,
1044
- headers: b,
1044
+ headers: T,
1045
1045
  config: e,
1046
1046
  request: h
1047
1047
  };
@@ -1051,8 +1051,8 @@ const pt = (e) => {
1051
1051
  r(_), m();
1052
1052
  }, D), h = null;
1053
1053
  }
1054
- "onloadend" in h ? h.onloadend = T : h.onreadystatechange = function() {
1055
- !h || h.readyState !== 4 || h.status === 0 && !(h.responseURL && h.responseURL.indexOf("file:") === 0) || setTimeout(T);
1054
+ "onloadend" in h ? h.onloadend = y : h.onreadystatechange = function() {
1055
+ !h || h.readyState !== 4 || h.status === 0 && !(h.responseURL && h.responseURL.indexOf("file:") === 0) || setTimeout(y);
1056
1056
  }, h.onabort = function() {
1057
1057
  h && (r(new E("Request aborted", E.ECONNABORTED, e, h)), h = null);
1058
1058
  }, h.onerror = function(O) {
@@ -1069,8 +1069,8 @@ const pt = (e) => {
1069
1069
  )), h = null;
1070
1070
  }, o === void 0 && i.setContentType(null), "setRequestHeader" in h && a.forEach(i.toJSON(), function(O, D) {
1071
1071
  h.setRequestHeader(D, O);
1072
- }), a.isUndefined(s.withCredentials) || (h.withCredentials = !!s.withCredentials), c && c !== "json" && (h.responseType = s.responseType), u && ([S, f] = ce(u, !0), h.addEventListener("progress", S)), d && h.upload && ([p, w] = ce(d), h.upload.addEventListener("progress", p), h.upload.addEventListener("loadend", w)), (s.cancelToken || s.signal) && (l = (b) => {
1073
- h && (r(!b || b.type ? new W(null, e, h) : b), h.abort(), h = null);
1072
+ }), a.isUndefined(s.withCredentials) || (h.withCredentials = !!s.withCredentials), c && c !== "json" && (h.responseType = s.responseType), u && ([S, f] = ce(u, !0), h.addEventListener("progress", S)), d && h.upload && ([p, w] = ce(d), h.upload.addEventListener("progress", p), h.upload.addEventListener("loadend", w)), (s.cancelToken || s.signal) && (l = (T) => {
1073
+ h && (r(!T || T.type ? new W(null, e, h) : T), h.abort(), h = null);
1074
1074
  }, s.cancelToken && s.cancelToken.subscribe(l), s.signal && (s.signal.aborted ? l() : s.signal.addEventListener("abort", l)));
1075
1075
  const U = Dn(s.url);
1076
1076
  if (U && R.protocols.indexOf(U) === -1) {
@@ -1193,9 +1193,9 @@ const pt = (e) => {
1193
1193
  };
1194
1194
  s && ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((f) => {
1195
1195
  !p[f] && (p[f] = (m, h) => {
1196
- let T = m && m[f];
1197
- if (T)
1198
- return T.call(m);
1196
+ let y = m && m[f];
1197
+ if (y)
1198
+ return y.call(m);
1199
1199
  throw new E(`Response type '${f}' is not supported`, E.ERR_NOT_SUPPORT, h);
1200
1200
  });
1201
1201
  });
@@ -1221,9 +1221,9 @@ const pt = (e) => {
1221
1221
  let {
1222
1222
  url: m,
1223
1223
  method: h,
1224
- data: T,
1224
+ data: y,
1225
1225
  signal: U,
1226
- cancelToken: b,
1226
+ cancelToken: T,
1227
1227
  timeout: O,
1228
1228
  onDownloadProgress: D,
1229
1229
  onUploadProgress: B,
@@ -1233,24 +1233,24 @@ const pt = (e) => {
1233
1233
  fetchOptions: Ue
1234
1234
  } = pt(f), _e = t || fetch;
1235
1235
  _ = _ ? (_ + "").toLowerCase() : "text";
1236
- let ne = jn([U, b && b.toAbortSignal()], O), K = null;
1236
+ let ne = jn([U, T && T.toAbortSignal()], O), K = null;
1237
1237
  const H = ne && ne.unsubscribe && (() => {
1238
1238
  ne.unsubscribe();
1239
1239
  });
1240
1240
  let De;
1241
1241
  try {
1242
- if (B && u && h !== "get" && h !== "head" && (De = await w(pe, T)) !== 0) {
1242
+ if (B && u && h !== "get" && h !== "head" && (De = await w(pe, y)) !== 0) {
1243
1243
  let k = new n(m, {
1244
1244
  method: "POST",
1245
- body: T,
1245
+ body: y,
1246
1246
  duplex: "half"
1247
1247
  }), J;
1248
- if (a.isFormData(T) && (J = k.headers.get("content-type")) && pe.setContentType(J), k.body) {
1248
+ if (a.isFormData(y) && (J = k.headers.get("content-type")) && pe.setContentType(J), k.body) {
1249
1249
  const [me, re] = je(
1250
1250
  De,
1251
1251
  ce(ve(B))
1252
1252
  );
1253
- T = Me(k.body, $e, me, re);
1253
+ y = Me(k.body, $e, me, re);
1254
1254
  }
1255
1255
  }
1256
1256
  a.isString(te) || (te = te ? "include" : "omit");
@@ -1259,7 +1259,7 @@ const pt = (e) => {
1259
1259
  signal: ne,
1260
1260
  method: h.toUpperCase(),
1261
1261
  headers: pe.normalize().toJSON(),
1262
- body: T,
1262
+ body: y,
1263
1263
  duplex: "half",
1264
1264
  credentials: x ? te : void 0
1265
1265
  };
@@ -1373,22 +1373,22 @@ const Et = {
1373
1373
  */
1374
1374
  adapters: Ce
1375
1375
  };
1376
- function ye(e) {
1376
+ function be(e) {
1377
1377
  if (e.cancelToken && e.cancelToken.throwIfRequested(), e.signal && e.signal.aborted)
1378
1378
  throw new W(null, e);
1379
1379
  }
1380
1380
  function Ke(e) {
1381
- return ye(e), e.headers = C.from(e.headers), e.data = Se.call(
1381
+ return be(e), e.headers = C.from(e.headers), e.data = Se.call(
1382
1382
  e,
1383
1383
  e.transformRequest
1384
1384
  ), ["post", "put", "patch"].indexOf(e.method) !== -1 && e.headers.setContentType("application/x-www-form-urlencoded", !1), Et.getAdapter(e.adapter || ee.adapter, e)(e).then(function(r) {
1385
- return ye(e), r.data = Se.call(
1385
+ return be(e), r.data = Se.call(
1386
1386
  e,
1387
1387
  e.transformResponse,
1388
1388
  r
1389
1389
  ), r.headers = C.from(r.headers), r;
1390
1390
  }, function(r) {
1391
- return ft(r) || (ye(e), r && r.response && (r.response.data = Se.call(
1391
+ return ft(r) || (be(e), r && r.response && (r.response.data = Se.call(
1392
1392
  e,
1393
1393
  e.transformResponse,
1394
1394
  r.response
@@ -1568,7 +1568,7 @@ a.forEach(["post", "put", "patch"], function(t) {
1568
1568
  }
1569
1569
  q.prototype[t] = n(), q.prototype[t + "Form"] = n(!0);
1570
1570
  });
1571
- let Vn = class yt {
1571
+ let Vn = class bt {
1572
1572
  constructor(t) {
1573
1573
  if (typeof t != "function")
1574
1574
  throw new TypeError("executor must be a function.");
@@ -1634,7 +1634,7 @@ let Vn = class yt {
1634
1634
  static source() {
1635
1635
  let t;
1636
1636
  return {
1637
- token: new yt(function(s) {
1637
+ token: new bt(function(s) {
1638
1638
  t = s;
1639
1639
  }),
1640
1640
  cancel: t
@@ -1723,32 +1723,32 @@ const Re = {
1723
1723
  Object.entries(Re).forEach(([e, t]) => {
1724
1724
  Re[t] = e;
1725
1725
  });
1726
- function Tt(e) {
1726
+ function yt(e) {
1727
1727
  const t = new q(e), n = Xe(q.prototype.request, t);
1728
1728
  return a.extend(n, q.prototype, t, { allOwnKeys: !0 }), a.extend(n, t, null, { allOwnKeys: !0 }), n.create = function(s) {
1729
- return Tt(M(e, s));
1729
+ return yt(M(e, s));
1730
1730
  }, n;
1731
1731
  }
1732
- const y = Tt(ee);
1733
- y.Axios = q;
1734
- y.CanceledError = W;
1735
- y.CancelToken = Vn;
1736
- y.isCancel = ft;
1737
- y.VERSION = St;
1738
- y.toFormData = de;
1739
- y.AxiosError = E;
1740
- y.Cancel = y.CanceledError;
1741
- y.all = function(t) {
1732
+ const b = yt(ee);
1733
+ b.Axios = q;
1734
+ b.CanceledError = W;
1735
+ b.CancelToken = Vn;
1736
+ b.isCancel = ft;
1737
+ b.VERSION = St;
1738
+ b.toFormData = de;
1739
+ b.AxiosError = E;
1740
+ b.Cancel = b.CanceledError;
1741
+ b.all = function(t) {
1742
1742
  return Promise.all(t);
1743
1743
  };
1744
- y.spread = Xn;
1745
- y.isAxiosError = Qn;
1746
- y.mergeConfig = M;
1747
- y.AxiosHeaders = C;
1748
- y.formToJSON = (e) => ut(a.isHTMLForm(e) ? new FormData(e) : e);
1749
- y.getAdapter = Et.getAdapter;
1750
- y.HttpStatusCode = Re;
1751
- y.default = y;
1744
+ b.spread = Xn;
1745
+ b.isAxiosError = Qn;
1746
+ b.mergeConfig = M;
1747
+ b.AxiosHeaders = C;
1748
+ b.formToJSON = (e) => ut(a.isHTMLForm(e) ? new FormData(e) : e);
1749
+ b.getAdapter = Et.getAdapter;
1750
+ b.HttpStatusCode = Re;
1751
+ b.default = b;
1752
1752
  const {
1753
1753
  Axios: cr,
1754
1754
  AxiosError: lr,
@@ -1760,25 +1760,25 @@ const {
1760
1760
  Cancel: mr,
1761
1761
  isAxiosError: Er,
1762
1762
  spread: Sr,
1763
- toFormData: yr,
1764
- AxiosHeaders: Tr,
1765
- HttpStatusCode: br,
1763
+ toFormData: br,
1764
+ AxiosHeaders: yr,
1765
+ HttpStatusCode: Tr,
1766
1766
  formToJSON: wr,
1767
1767
  getAdapter: Rr,
1768
1768
  mergeConfig: Or
1769
- } = y, bt = "JOYTALK_TOKEN";
1769
+ } = b, Tt = "JOYTALK_TOKEN";
1770
1770
  var X = /* @__PURE__ */ ((e) => (e.SEND = "1", e.WITHDRAW = "2", e.EDIT = "3", e.SYSTEM_NOTICE = "4", e.TRANSFER = "5", e.INBOUND = "6", e.REPLY = "7", e.UNBIND = "8", e))(X || {}), I = /* @__PURE__ */ ((e) => (e.TEXT = "1", e.IMAGE = "2", e.VIDEO = "3", e.FILE = "4", e.FAQ = "5", e))(I || {}), j = /* @__PURE__ */ ((e) => (e[e.CONNECT_SUCCESS = 200] = "CONNECT_SUCCESS", e[e.CONNECT_FAILED = 40001] = "CONNECT_FAILED", e[e.TRANSFER_CUSTOMER_SUCCESS = 201] = "TRANSFER_CUSTOMER_SUCCESS", e[e.TRANSFER_TO_CUSTOMER_SUCCESS = 202] = "TRANSFER_TO_CUSTOMER_SUCCESS", e[e.TRANSFER_USER_SUCCESS = 203] = "TRANSFER_USER_SUCCESS", e[e.TRANSFER_FAIL = 50001] = "TRANSFER_FAIL", e[e.MATCH_FAIL = 50002] = "MATCH_FAIL", e[e.MATCH_INFO = 50005] = "MATCH_INFO", e[e.MATCH_SUCCESS = 50006] = "MATCH_SUCCESS", e[e.RETRACT = 204] = "RETRACT", e[e.RETRACT_FAIL = 50003] = "RETRACT_FAIL", e[e.EDIT = 205] = "EDIT", e[e.EDIT_FAIL = 50004] = "EDIT_FAIL", e[e.COMMON_FAIL = 5e4] = "COMMON_FAIL", e[e.SEND_SUCCESS = 206] = "SEND_SUCCESS", e[e.SEND_CALLBACK = 207] = "SEND_CALLBACK", e[e.CHANGE_CHAT_STATUS = 208] = "CHANGE_CHAT_STATUS", e))(j || {}), Oe = /* @__PURE__ */ ((e) => (e.CUSTOMER = "1", e.USER = "2", e.ANONYMOUS = "3", e))(Oe || {});
1771
1771
  function Ar(e) {
1772
1772
  return e.contentType === "1";
1773
1773
  }
1774
1774
  var A = /* @__PURE__ */ ((e) => (e.CONNECTED = "connected", e.DISCONNECTED = "disconnected", e.ERROR = "error", e.MESSAGE = "message", e.STATUS_CHANGE = "status_change", e.HEARTBEAT_TIMEOUT = "heartbeat_timeout", e))(A || {}), g = /* @__PURE__ */ ((e) => (e.DISCONNECTED = "disconnected", e.CONNECTING = "connecting", e.CONNECTED = "connected", e.RECONNECTING = "reconnecting", e.ERROR = "error", e))(g || {});
1775
- const $ = y.create({
1775
+ const $ = b.create({
1776
1776
  baseURL: "http://dev-joytalk-api.halaladmin.vip",
1777
1777
  timeout: 6e5
1778
1778
  });
1779
1779
  $.interceptors.request.use(
1780
1780
  (e) => (e.noAuth || (e.headers.Authorization = `Bearer ${localStorage.getItem(
1781
- bt
1781
+ Tt
1782
1782
  )}`), delete e.noAuth, e),
1783
1783
  (e) => Promise.reject(e)
1784
1784
  );
@@ -1789,7 +1789,7 @@ $.interceptors.response.use(
1789
1789
  const Yn = (e) => $.post(
1790
1790
  "/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",
1791
1791
  e
1792
- ), Zn = (e) => y.post("https://joytalk-fat.obs.ap-southeast-1.myhuaweicloud.com:443", e, {
1792
+ ), Zn = (e) => b.post("https://joytalk-fat.obs.ap-southeast-1.myhuaweicloud.com", e, {
1793
1793
  headers: {
1794
1794
  "Content-Type": "multipart/form-data"
1795
1795
  }
@@ -1852,7 +1852,7 @@ class sr {
1852
1852
  t ? this.events.delete(t) : this.events.clear();
1853
1853
  }
1854
1854
  }
1855
- const or = "https://joytalk-fat.obs.ap-southeast-1.myhuaweicloud.com:443/";
1855
+ const or = "https://joytalk-fat.obs.ap-southeast-1.myhuaweicloud.com/";
1856
1856
  class gr extends sr {
1857
1857
  config;
1858
1858
  ws = null;
@@ -1876,7 +1876,7 @@ class gr extends sr {
1876
1876
  reconnectInterval: t.reconnectInterval ?? 3e3,
1877
1877
  maxReconnectAttempts: t.maxReconnectAttempts ?? 5,
1878
1878
  heartbeatTimeout: t.heartbeatTimeout ?? 1e4
1879
- }, localStorage.setItem(bt, this.config.token || "");
1879
+ }, localStorage.setItem(Tt, this.config.token || "");
1880
1880
  }
1881
1881
  /**
1882
1882
  * 连接到服务器
@@ -2099,7 +2099,7 @@ class gr extends sr {
2099
2099
  */
2100
2100
  async getHistoryMessages({
2101
2101
  lastMsgId: t,
2102
- size: n = 10
2102
+ size: n = 50
2103
2103
  }) {
2104
2104
  const r = await rr({
2105
2105
  sessionId: this.sessionData?.sessionId,
@@ -2142,7 +2142,7 @@ class gr extends sr {
2142
2142
  return;
2143
2143
  }
2144
2144
  const c = URL.createObjectURL(t);
2145
- s.preload = "metadata", s.src = c, s.muted = !0, s.playsInline = !0, s.addEventListener("loadedmetadata", () => {
2145
+ s.preload = "metadata", s.src = c, s.muted = !0, s.playsInline = !0, s.addEventListener("loadeddata", () => {
2146
2146
  o.width = s.videoWidth, o.height = s.videoHeight, s.currentTime = 0;
2147
2147
  }), s.addEventListener("seeked", () => {
2148
2148
  try {
@@ -2266,7 +2266,7 @@ export {
2266
2266
  j as MessageCode,
2267
2267
  X as MessageType,
2268
2268
  Oe as SendUserType,
2269
- bt as TOKEN_KEY,
2269
+ Tt as TOKEN_KEY,
2270
2270
  gr as default,
2271
2271
  Ar as isTextMessage
2272
2272
  };
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[Ve]=this[Ve]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=te(i);r[c]||(An(s,i),r[c]=!0)}return a.isArray(t)?t.forEach(o):o(t),this}};C.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),a.reduceDescriptors(C.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),a.freezeMethods(C);function Ae(e,t){const n=this||ee,r=t||n,s=C.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 Xe(e){return!!(e&&e.__CANCEL__)}function K(e,t,n){E.call(this,e??"canceled",E.ERR_CANCELED,t,n),this.name="CanceledError"}a.inherits(K,E,{__CANCEL__:!0});function Qe(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 gn(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Nn(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 p=o,S=0;for(;p!==s;)S+=n[p++],p=p%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),u-i<t)return;const R=l&&u-l;return R?Math.round(S*1e3/R):void 0}}function Cn(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(),p=l-n;p>=r?i(u,l):(s=u,o||(o=setTimeout(()=>{o=null,i(s)},r-p)))},()=>s&&i(s)]}const le=(e,t,n=3)=>{let r=0;const s=Nn(50,250);return Cn(o=>{const i=o.loaded,c=o.lengthComputable?o.total:void 0,d=i-r,u=s(d),l=i<=c;r=i;const p={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(p)},n)},Ye=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Ze=e=>(...t)=>a.asap(()=>e(...t)),Un=w.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,w.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(w.origin),w.navigator&&/(msie|trident)/i.test(w.navigator.userAgent)):()=>!0,_n=w.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 Dn(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Fn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function et(e,t,n){let r=!Dn(t);return e&&(r||n==!1)?Fn(e,t):t}const tt=e=>e instanceof C?{...e}:e;function v(e,t){t=t||{};const n={};function r(u,l,p,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,p,S){if(a.isUndefined(l)){if(!a.isUndefined(u))return r(void 0,u,p,S)}else return r(u,l,p,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,p){if(p in t)return r(u,l);if(p 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,p)=>s(tt(u),tt(l),p,!0)};return a.forEach(Object.keys({...e,...t}),function(l){const p=d[l]||s,S=p(e[l],t[l],l);a.isUndefined(S)&&p!==c||(n[l]=S)}),n}const nt=e=>{const t=v({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:c}=t;if(t.headers=i=C.from(i),t.url=ze(et(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(w.hasStandardBrowserEnv||w.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,p])=>{u.includes(l.toLowerCase())&&i.set(l,p)})}}if(w.hasStandardBrowserEnv&&(r&&a.isFunction(r)&&(r=r(t)),r||r!==!1&&Un(t.url))){const d=s&&o&&_n.read(o);d&&i.set(s,d)}return t},Ln=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const s=nt(e);let o=s.data;const i=C.from(s.headers).normalize();let{responseType:c,onUploadProgress:d,onDownloadProgress:u}=s,l,p,S,R,f;function m(){R&&R(),f&&f(),s.cancelToken&&s.cancelToken.unsubscribe(l),s.signal&&s.signal.removeEventListener("abort",l)}let h=new XMLHttpRequest;h.open(s.method.toUpperCase(),s.url,!0),h.timeout=s.timeout;function y(){if(!h)return;const b=C.from("getAllResponseHeaders"in h&&h.getAllResponseHeaders()),x={data:!c||c==="text"||c==="json"?h.responseText:h.response,status:h.status,statusText:h.statusText,headers:b,config:e,request:h};Qe(function(D){n(D),m()},function(D){r(D),m()},x),h=null}"onloadend"in h?h.onloadend=y:h.onreadystatechange=function(){!h||h.readyState!==4||h.status===0&&!(h.responseURL&&h.responseURL.indexOf("file:")===0)||setTimeout(y)},h.onabort=function(){h&&(r(new E("Request aborted",E.ECONNABORTED,e,h)),h=null)},h.onerror=function(U){const x=U&&U.message?U.message:"Network Error",$=new E(x,E.ERR_NETWORK,e,h);$.event=U||null,r($),h=null},h.ontimeout=function(){let U=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const x=s.transitional||We;s.timeoutErrorMessage&&(U=s.timeoutErrorMessage),r(new E(U,x.clarifyTimeoutError?E.ETIMEDOUT:E.ECONNABORTED,e,h)),h=null},o===void 0&&i.setContentType(null),"setRequestHeader"in h&&a.forEach(i.toJSON(),function(U,x){h.setRequestHeader(x,U)}),a.isUndefined(s.withCredentials)||(h.withCredentials=!!s.withCredentials),c&&c!=="json"&&(h.responseType=s.responseType),u&&([S,f]=le(u,!0),h.addEventListener("progress",S)),d&&h.upload&&([p,R]=le(d),h.upload.addEventListener("progress",p),h.upload.addEventListener("loadend",R)),(s.cancelToken||s.signal)&&(l=b=>{h&&(r(!b||b.type?new K(null,e,h):b),h.abort(),h=null)},s.cancelToken&&s.cancelToken.subscribe(l),s.signal&&(s.signal.aborted?l():s.signal.addEventListener("abort",l)));const _=gn(s.url);if(_&&w.protocols.indexOf(_)===-1){r(new E("Unsupported protocol "+_+":",E.ERR_BAD_REQUEST,e));return}h.send(o||null)})},xn=(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 K(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}},In=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},Pn=async function*(e,t){for await(const n of kn(e))yield*In(n,t)},kn=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()}},rt=(e,t,n,r)=>{const s=Pn(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 p=l.byteLength;if(n){let S=o+=p;n(S)}d.enqueue(new Uint8Array(l))}catch(u){throw c(u),u}},cancel(d){return c(d),s.return()}},{highWaterMark:2})},st=64*1024,{isFunction:ue}=a,Bn=(({Request:e,Response:t})=>({Request:e,Response:t}))(a.global),{ReadableStream:ot,TextEncoder:it}=a.global,at=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Hn=e=>{e=a.merge.call({skipUndefined:!0},Bn,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(ot),d=s&&(typeof it=="function"?(f=>m=>f.encode(m))(new it):async f=>new Uint8Array(await new n(f).arrayBuffer())),u=o&&c&&at(()=>{let f=!1;const m=new n(w.origin,{body:new ot,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!m}),l=i&&c&&at(()=>a.isReadableStream(new r("").body)),p={stream:l&&(f=>f.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!p[f]&&(p[f]=(m,h)=>{let y=m&&m[f];if(y)return y.call(m);throw new E(`Response type '${f}' is not supported`,E.ERR_NOT_SUPPORT,h)})});const S=async f=>{if(f==null)return 0;if(a.isBlob(f))return f.size;if(a.isSpecCompliantForm(f))return(await new n(w.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},R=async(f,m)=>{const h=a.toFiniteNumber(f.getContentLength());return h??S(m)};return async f=>{let{url:m,method:h,data:y,signal:_,cancelToken:b,timeout:U,onDownloadProgress:x,onUploadProgress:$,responseType:D,headers:_e,withCredentials:pe="same-origin",fetchOptions:mt}=nt(f),Et=t||fetch;D=D?(D+"").toLowerCase():"text";let me=xn([_,b&&b.toAbortSignal()],U),ne=null;const J=me&&me.unsubscribe&&(()=>{me.unsubscribe()});let St;try{if($&&u&&h!=="get"&&h!=="head"&&(St=await R(_e,y))!==0){let H=new n(m,{method:"POST",body:y,duplex:"half"}),X;if(a.isFormData(y)&&(X=H.headers.get("content-type"))&&_e.setContentType(X),H.body){const[De,Ee]=Ye(St,le(Ze($)));y=rt(H.body,st,De,Ee)}}a.isString(pe)||(pe=pe?"include":"omit");const P=o&&"credentials"in n.prototype,Tt={...mt,signal:me,method:h.toUpperCase(),headers:_e.normalize().toJSON(),body:y,duplex:"half",credentials:P?pe:void 0};ne=o&&new n(m,Tt);let B=await(o?Et(ne,mt):Et(m,Tt));const yt=l&&(D==="stream"||D==="response");if(l&&(x||yt&&J)){const H={};["status","statusText","headers"].forEach(bt=>{H[bt]=B[bt]});const X=a.toFiniteNumber(B.headers.get("content-length")),[De,Ee]=x&&Ye(X,le(Ze(x),!0))||[];B=new r(rt(B.body,st,De,()=>{Ee&&Ee(),J&&J()}),H)}D=D||"text";let nr=await p[a.findKey(p,D)||"text"](B,f);return!yt&&J&&J(),await new Promise((H,X)=>{Qe(H,X,{data:nr,headers:C.from(B.headers),status:B.status,statusText:B.statusText,config:f,request:ne})})}catch(P){throw J&&J(),P&&P.name==="TypeError"&&/Load failed|fetch/i.test(P.message)?Object.assign(new E("Network Error",E.ERR_NETWORK,f,ne),{cause:P.cause||P}):E.from(P,P&&P.code,f,ne)}}},jn=new Map,ct=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=jn;for(;c--;)d=o[c],u=l.get(d),u===void 0&&l.set(d,u=c?new Map:Hn(t)),l=u;return u};ct();const ge={http:an,xhr:Ln,fetch:{get:ct}};a.forEach(ge,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const lt=e=>`- ${e}`,vn=e=>a.isFunction(e)||e===null||e===!1;function qn(e,t){e=a.isArray(e)?e:[e];const{length:n}=e;let r,s;const o={};for(let i=0;i<n;i++){r=e[i];let c;if(s=r,!vn(r)&&(s=ge[(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(lt).join(`
5
5
  `):" "+lt(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 ut={getAdapter:qn,adapters:ge};function Ne(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new K(null,e)}function ft(e){return Ne(e),e.headers=C.from(e.headers),e.data=Ae.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),ut.getAdapter(e.adapter||ee.adapter,e)(e).then(function(r){return Ne(e),r.data=Ae.call(e,e.transformResponse,r),r.headers=C.from(r.headers),r},function(r){return Xe(r)||(Ne(e),r&&r.response&&(r.response.data=Ae.call(e,e.transformResponse,r.response),r.response.headers=C.from(r.response.headers))),Promise.reject(r)})}const dt="1.13.2",fe={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{fe[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const ht={};fe.transitional=function(t,n,r){function s(o,i){return"[Axios v"+dt+"] 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&&!ht[i]&&(ht[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}},fe.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Mn(e,t,n){if(typeof e!="object")throw new E("options must be an object",E.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const o=r[s],i=t[o];if(i){const c=e[o],d=c===void 0||i(c,o,e);if(d!==!0)throw new E("option "+o+" must be "+d,E.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new E("Unknown option "+o,E.ERR_BAD_OPTION)}}const de={assertOptions:Mn,validators:fe},I=de.validators;let q=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Ge,response:new Ge}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=`
6
- `+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=v(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&de.assertOptions(r,{silentJSONParsing:I.transitional(I.boolean),forcedJSONParsing:I.transitional(I.boolean),clarifyTimeoutError:I.transitional(I.boolean)},!1),s!=null&&(a.isFunction(s)?n.paramsSerializer={serialize:s}:de.assertOptions(s,{encode:I.function,serialize:I.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),de.assertOptions(n,{baseUrl:I.spelling("baseURL"),withXsrfToken:I.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=C.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,p=0,S;if(!d){const f=[ft.bind(this),void 0];for(f.unshift(...c),f.push(...u),S=f.length,l=Promise.resolve(n);p<S;)l=l.then(f[p++],f[p++]);return l}S=c.length;let R=n;for(;p<S;){const f=c[p++],m=c[p++];try{R=f(R)}catch(h){m.call(this,h);break}}try{l=ft.call(this,R)}catch(f){return Promise.reject(f)}for(p=0,S=u.length;p<S;)l=l.then(u[p++],u[p++]);return l}getUri(t){t=v(this.defaults,t);const n=et(t.baseURL,t.url,t.allowAbsoluteUrls);return ze(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){q.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}))}}q.prototype[t]=n(),q.prototype[t+"Form"]=n(!0)});let $n=class wt{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 K(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 wt(function(s){t=s}),cancel:t}}};function Jn(e){return function(n){return e.apply(null,n)}}function zn(e){return a.isObject(e)&&e.isAxiosError===!0}const Ce={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(Ce).forEach(([e,t])=>{Ce[t]=e});function pt(e){const t=new q(e),n=z(q.prototype.request,t);return a.extend(n,q.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return pt(v(e,s))},n}const T=pt(ee);T.Axios=q,T.CanceledError=K,T.CancelToken=$n,T.isCancel=Xe,T.VERSION=dt,T.toFormData=ae,T.AxiosError=E,T.Cancel=T.CanceledError,T.all=function(t){return Promise.all(t)},T.spread=Jn,T.isAxiosError=zn,T.mergeConfig=v,T.AxiosHeaders=C,T.formToJSON=e=>Ke(a.isHTMLForm(e)?new FormData(e):e),T.getAdapter=ut.getAdapter,T.HttpStatusCode=Ce,T.default=T;const{Axios:lr,AxiosError:ur,CanceledError:fr,isCancel:dr,CancelToken:hr,VERSION:pr,all:mr,Cancel:Er,isAxiosError:Sr,spread:Tr,toFormData:yr,AxiosHeaders:br,HttpStatusCode:wr,formToJSON:Rr,getAdapter:Or,mergeConfig:Ar}=T,Ue="JOYTALK_TOKEN";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||{}),L=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(L||{}),k=(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))(k||{}),he=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(he||{});function Gn(e){return e.contentType==="1"}var O=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(O||{}),A=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(A||{});const M=T.create({baseURL:"http://dev-joytalk-api.halaladmin.vip",timeout:6e5});M.interceptors.request.use(e=>(e.noAuth||(e.headers.Authorization=`Bearer ${localStorage.getItem(Ue)}`),delete e.noAuth,e),e=>Promise.reject(e)),M.interceptors.response.use(e=>e.data.code!==200?(console.error(e.data.message),Promise.reject(e)):Promise.resolve(e.data),e=>Promise.reject(e));const Wn=e=>M.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),Kn=e=>T.post("https://joytalk-fat.obs.ap-southeast-1.myhuaweicloud.com:443",e,{headers:{"Content-Type":"multipart/form-data"}}),Vn=e=>M.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),Xn=e=>M.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),Qn=()=>M.get("/api/open-auth/user/v1/UserService/GetUserInfo"),Yn=e=>M.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e);class Zn{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()}}const er="https://joytalk-fat.obs.ap-southeast-1.myhuaweicloud.com:443/";class tr extends Zn{config;ws=null;status=A.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;customerGroupId="";OBS_URL=er;sessionData=null;userInfo=null;constructor(t){super(),this.config={token:t.token||"",autoReconnect:t.autoReconnect??!0,reconnectInterval:t.reconnectInterval??3e3,maxReconnectAttempts:t.maxReconnectAttempts??5,heartbeatTimeout:t.heartbeatTimeout??1e4},localStorage.setItem(Ue,this.config.token||"")}connect(t){return this.customerGroupId=t,new Promise((n,r)=>{if(this.status===A.CONNECTED){n();return}if(this.status!==A.CONNECTING){this.setStatus(A.CONNECTING);try{const s=this.buildWebSocketUrl();this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(A.CONNECTED),this.emit(O.CONNECTED),n()},this.ws.onmessage=o=>{try{this.handleMessage(o.data)}catch(i){console.error("解析消息失败:",i)}},this.ws.onerror=o=>{console.error("连接错误:",o),this.setStatus(A.ERROR),this.emit(O.ERROR,o),r(o)},this.ws.onclose=()=>{this.setStatus(A.DISCONNECTED),this.emit(O.DISCONNECTED),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(A.ERROR),this.emit(O.ERROR,s),r(s)}}})}disconnect(){this.config.autoReconnect=!1,this.sessionData=null,this.clearReconnectTimer(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus(A.DISCONNECTED)}sendMessage(t,n,r=V.SEND){if(this.status!==A.CONNECTED||!this.ws)throw new Error("未连接到服务器");const s={msgType:r,data:t,toUid:this.sessionData?.cid,chatType:n,editId:void 0};this.ws.send(JSON.stringify(s))}sendText(t){return this.sendMessage(t,L.TEXT),Promise.resolve(!0)}sendFile({file:t,thumbnailFile:n,chatType:r}){return new Promise(async(s,o)=>{try{const[i,c]=await Promise.all([this.handleUploadFile(t),n?this.handleUploadFile(n):Promise.resolve(void 0)]),d={fileName:t.name,fileUrl:i,thumbnailUrl:c,fileSize:t.size};this.sendMessage(JSON.stringify(d),r),s(JSON.stringify(d))}catch(i){console.error("上传文件失败:",i),o(i)}})}getStatus(){return this.status}isConnected(){return this.status===A.CONNECTED}buildWebSocketUrl(){const t=new URL("ws://dev-joytalk-api.halaladmin.vip/api/ws");return this.config.token&&t.searchParams.set("Authorization",this.config.token),t.toString()}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),this.isMessage(t))try{switch(t.code){case k.CONNECT_SUCCESS:this.sendMessage(this.customerGroupId,void 0,V.INBOUND);break;case k.MATCH_INFO:case k.MATCH_SUCCESS:if(console.log("MATCH_SUCCESS",this.sessionData),this.sessionData)return;const n=JSON.parse(typeof t.data=="string"?t.data:JSON.stringify(t.data));this.sessionData=n,t.data=n,this.getFaqList(),this.emit(O.MESSAGE,t);break;case k.SEND_SUCCESS:const r=JSON.parse(typeof t.data=="string"?t.data:JSON.stringify(t.data));if(r.sessionId!==this.sessionData?.sessionId)return;t.chatType!==L.TEXT&&typeof r.content=="string"&&(r.content=JSON.parse(r.content),r.content?.fileUrl?.startsWith("http")||(r.content.fileUrl=this.OBS_URL+r.content.fileUrl),r.content?.thumbnailUrl?.startsWith("http")||(r.content.thumbnailUrl=this.OBS_URL+r.content.thumbnailUrl)),t.data=r,this.emit(O.MESSAGE,t);break;default:this.emit(O.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}isMessage(t){return typeof t=="object"&&t!==null&&"data"in t&&"msgType"in t&&"toUid"in t&&"chatType"in t&&"code"in t}setStatus(t){this.status!==t&&(this.status=t,this.emit(O.STATUS_CHANGE,t))}scheduleReconnect(){this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(A.RECONNECTING),this.reconnectTimer=setTimeout(()=>{this.connect(this.customerGroupId).catch(t=>{console.error("重连失败:",t)})},this.config.reconnectInterval)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}sendHeartbeat(){if(!(this.status!==A.CONNECTED||!this.ws))try{this.ws.send("pong"),this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer=setTimeout(()=>{Date.now()-this.lastHeartbeatTime>=this.config.heartbeatTimeout&&(this.emit(O.HEARTBEAT_TIMEOUT),console.warn("心跳超时,尝试重连"),this.ws&&this.ws.close())},this.config.heartbeatTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=10}){const r=await Yn({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>{let i=o.content;return o.contentType===L.TEXT?i=o.content:(i=JSON.parse(o.content),i?.fileUrl?.startsWith("http")||(i.fileUrl=this.OBS_URL+i.fileUrl),i?.thumbnailUrl?.startsWith("http")||(i.thumbnailUrl=this.OBS_URL+i.thumbnailUrl)),{...o,content:i}});return{hasMore:r.data.hasMore,list:s.reverse()}}getConsultationList(t){return Vn({entranceId:t})}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await Wn({ext:s||""}),{accessKeyId:i,signature:c,policy:d,key:u}=o.data,l=new FormData;l.append("key",u),l.append("AccessKeyId",i),l.append("signature",c),l.append("policy",d),l.append("file",t),(await Kn(l)).status===204?n(this.OBS_URL+u):r(new Error("上传文件失败"))})}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("loadedmetadata",()=>{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(new 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(new Error("视频加载失败"))}),s.load()});async getFaqList(){const t=await Xn({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:k.SEND_SUCCESS,data:{content:n,contentType:L.FAQ,sendUserType:he.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now()},msgType:V.SEND,chatType:L.FAQ,toUid:this.sessionData?.uid};this.emit(O.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={sendUserType:he.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now()},r={code:k.SEND_SUCCESS,data:n,msgType:V.SEND,chatType:L.FAQ,toUid:this.sessionData?.uid};if(t.isMulti){const s={...r,data:{...n,content:{list:t.item},contentType:L.FAQ}};this.emit(O.MESSAGE,s)}else{const s=t.item?.[0]||t;if(s.answer){const o={...r,data:{...n,content:s.answer,contentType:L.TEXT}};this.emit(O.MESSAGE,o)}s.imageUrl?.forEach(o=>{const i={...r,data:{...n,content:{fileUrl:o?.startsWith("http")?o:this.OBS_URL+o,fileName:o.split("/").pop()},contentType:L.IMAGE}};this.emit(O.MESSAGE,i)})}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await Qn();return this.userInfo=t.data,this.userInfo}}g.ChatType=L,g.ConnectionStatus=A,g.EventType=O,g.MessageCode=k,g.MessageType=V,g.SendUserType=he,g.TOKEN_KEY=Ue,g.default=tr,g.isTextMessage=Gn,Object.defineProperties(g,{__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&&de.assertOptions(r,{silentJSONParsing:I.transitional(I.boolean),forcedJSONParsing:I.transitional(I.boolean),clarifyTimeoutError:I.transitional(I.boolean)},!1),s!=null&&(a.isFunction(s)?n.paramsSerializer={serialize:s}:de.assertOptions(s,{encode:I.function,serialize:I.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),de.assertOptions(n,{baseUrl:I.spelling("baseURL"),withXsrfToken:I.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=C.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,p=0,S;if(!d){const f=[ft.bind(this),void 0];for(f.unshift(...c),f.push(...u),S=f.length,l=Promise.resolve(n);p<S;)l=l.then(f[p++],f[p++]);return l}S=c.length;let R=n;for(;p<S;){const f=c[p++],m=c[p++];try{R=f(R)}catch(h){m.call(this,h);break}}try{l=ft.call(this,R)}catch(f){return Promise.reject(f)}for(p=0,S=u.length;p<S;)l=l.then(u[p++],u[p++]);return l}getUri(t){t=v(this.defaults,t);const n=et(t.baseURL,t.url,t.allowAbsoluteUrls);return ze(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){q.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}))}}q.prototype[t]=n(),q.prototype[t+"Form"]=n(!0)});let $n=class wt{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 K(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 wt(function(s){t=s}),cancel:t}}};function Jn(e){return function(n){return e.apply(null,n)}}function zn(e){return a.isObject(e)&&e.isAxiosError===!0}const Ce={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(Ce).forEach(([e,t])=>{Ce[t]=e});function pt(e){const t=new q(e),n=z(q.prototype.request,t);return a.extend(n,q.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return pt(v(e,s))},n}const T=pt(ee);T.Axios=q,T.CanceledError=K,T.CancelToken=$n,T.isCancel=Xe,T.VERSION=dt,T.toFormData=ae,T.AxiosError=E,T.Cancel=T.CanceledError,T.all=function(t){return Promise.all(t)},T.spread=Jn,T.isAxiosError=zn,T.mergeConfig=v,T.AxiosHeaders=C,T.formToJSON=e=>Ke(a.isHTMLForm(e)?new FormData(e):e),T.getAdapter=ut.getAdapter,T.HttpStatusCode=Ce,T.default=T;const{Axios:lr,AxiosError:ur,CanceledError:fr,isCancel:dr,CancelToken:hr,VERSION:pr,all:mr,Cancel:Er,isAxiosError:Sr,spread:Tr,toFormData:yr,AxiosHeaders:br,HttpStatusCode:wr,formToJSON:Rr,getAdapter:Or,mergeConfig:Ar}=T,Ue="JOYTALK_TOKEN";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||{}),L=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(L||{}),k=(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))(k||{}),he=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(he||{});function Gn(e){return e.contentType==="1"}var O=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(O||{}),A=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(A||{});const M=T.create({baseURL:"http://dev-joytalk-api.halaladmin.vip",timeout:6e5});M.interceptors.request.use(e=>(e.noAuth||(e.headers.Authorization=`Bearer ${localStorage.getItem(Ue)}`),delete e.noAuth,e),e=>Promise.reject(e)),M.interceptors.response.use(e=>e.data.code!==200?(console.error(e.data.message),Promise.reject(e)):Promise.resolve(e.data),e=>Promise.reject(e));const Wn=e=>M.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),Kn=e=>T.post("https://joytalk-fat.obs.ap-southeast-1.myhuaweicloud.com",e,{headers:{"Content-Type":"multipart/form-data"}}),Vn=e=>M.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),Xn=e=>M.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),Qn=()=>M.get("/api/open-auth/user/v1/UserService/GetUserInfo"),Yn=e=>M.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e);class Zn{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()}}const er="https://joytalk-fat.obs.ap-southeast-1.myhuaweicloud.com/";class tr extends Zn{config;ws=null;status=A.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;customerGroupId="";OBS_URL=er;sessionData=null;userInfo=null;constructor(t){super(),this.config={token:t.token||"",autoReconnect:t.autoReconnect??!0,reconnectInterval:t.reconnectInterval??3e3,maxReconnectAttempts:t.maxReconnectAttempts??5,heartbeatTimeout:t.heartbeatTimeout??1e4},localStorage.setItem(Ue,this.config.token||"")}connect(t){return this.customerGroupId=t,new Promise((n,r)=>{if(this.status===A.CONNECTED){n();return}if(this.status!==A.CONNECTING){this.setStatus(A.CONNECTING);try{const s=this.buildWebSocketUrl();this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(A.CONNECTED),this.emit(O.CONNECTED),n()},this.ws.onmessage=o=>{try{this.handleMessage(o.data)}catch(i){console.error("解析消息失败:",i)}},this.ws.onerror=o=>{console.error("连接错误:",o),this.setStatus(A.ERROR),this.emit(O.ERROR,o),r(o)},this.ws.onclose=()=>{this.setStatus(A.DISCONNECTED),this.emit(O.DISCONNECTED),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(A.ERROR),this.emit(O.ERROR,s),r(s)}}})}disconnect(){this.config.autoReconnect=!1,this.sessionData=null,this.clearReconnectTimer(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus(A.DISCONNECTED)}sendMessage(t,n,r=V.SEND){if(this.status!==A.CONNECTED||!this.ws)throw new Error("未连接到服务器");const s={msgType:r,data:t,toUid:this.sessionData?.cid,chatType:n,editId:void 0};this.ws.send(JSON.stringify(s))}sendText(t){return this.sendMessage(t,L.TEXT),Promise.resolve(!0)}sendFile({file:t,thumbnailFile:n,chatType:r}){return new Promise(async(s,o)=>{try{const[i,c]=await Promise.all([this.handleUploadFile(t),n?this.handleUploadFile(n):Promise.resolve(void 0)]),d={fileName:t.name,fileUrl:i,thumbnailUrl:c,fileSize:t.size};this.sendMessage(JSON.stringify(d),r),s(JSON.stringify(d))}catch(i){console.error("上传文件失败:",i),o(i)}})}getStatus(){return this.status}isConnected(){return this.status===A.CONNECTED}buildWebSocketUrl(){const t=new URL("ws://dev-joytalk-api.halaladmin.vip/api/ws");return this.config.token&&t.searchParams.set("Authorization",this.config.token),t.toString()}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),this.isMessage(t))try{switch(t.code){case k.CONNECT_SUCCESS:this.sendMessage(this.customerGroupId,void 0,V.INBOUND);break;case k.MATCH_INFO:case k.MATCH_SUCCESS:if(console.log("MATCH_SUCCESS",this.sessionData),this.sessionData)return;const n=JSON.parse(typeof t.data=="string"?t.data:JSON.stringify(t.data));this.sessionData=n,t.data=n,this.getFaqList(),this.emit(O.MESSAGE,t);break;case k.SEND_SUCCESS:const r=JSON.parse(typeof t.data=="string"?t.data:JSON.stringify(t.data));if(r.sessionId!==this.sessionData?.sessionId)return;t.chatType!==L.TEXT&&typeof r.content=="string"&&(r.content=JSON.parse(r.content),r.content?.fileUrl?.startsWith("http")||(r.content.fileUrl=this.OBS_URL+r.content.fileUrl),r.content?.thumbnailUrl?.startsWith("http")||(r.content.thumbnailUrl=this.OBS_URL+r.content.thumbnailUrl)),t.data=r,this.emit(O.MESSAGE,t);break;default:this.emit(O.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}isMessage(t){return typeof t=="object"&&t!==null&&"data"in t&&"msgType"in t&&"toUid"in t&&"chatType"in t&&"code"in t}setStatus(t){this.status!==t&&(this.status=t,this.emit(O.STATUS_CHANGE,t))}scheduleReconnect(){this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(A.RECONNECTING),this.reconnectTimer=setTimeout(()=>{this.connect(this.customerGroupId).catch(t=>{console.error("重连失败:",t)})},this.config.reconnectInterval)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}sendHeartbeat(){if(!(this.status!==A.CONNECTED||!this.ws))try{this.ws.send("pong"),this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer=setTimeout(()=>{Date.now()-this.lastHeartbeatTime>=this.config.heartbeatTimeout&&(this.emit(O.HEARTBEAT_TIMEOUT),console.warn("心跳超时,尝试重连"),this.ws&&this.ws.close())},this.config.heartbeatTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=50}){const r=await Yn({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>{let i=o.content;return o.contentType===L.TEXT?i=o.content:(i=JSON.parse(o.content),i?.fileUrl?.startsWith("http")||(i.fileUrl=this.OBS_URL+i.fileUrl),i?.thumbnailUrl?.startsWith("http")||(i.thumbnailUrl=this.OBS_URL+i.thumbnailUrl)),{...o,content:i}});return{hasMore:r.data.hasMore,list:s.reverse()}}getConsultationList(t){return Vn({entranceId:t})}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await Wn({ext:s||""}),{accessKeyId:i,signature:c,policy:d,key:u}=o.data,l=new FormData;l.append("key",u),l.append("AccessKeyId",i),l.append("signature",c),l.append("policy",d),l.append("file",t),(await Kn(l)).status===204?n(this.OBS_URL+u):r(new Error("上传文件失败"))})}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(new 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(new Error("视频加载失败"))}),s.load()});async getFaqList(){const t=await Xn({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:k.SEND_SUCCESS,data:{content:n,contentType:L.FAQ,sendUserType:he.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now()},msgType:V.SEND,chatType:L.FAQ,toUid:this.sessionData?.uid};this.emit(O.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={sendUserType:he.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now()},r={code:k.SEND_SUCCESS,data:n,msgType:V.SEND,chatType:L.FAQ,toUid:this.sessionData?.uid};if(t.isMulti){const s={...r,data:{...n,content:{list:t.item},contentType:L.FAQ}};this.emit(O.MESSAGE,s)}else{const s=t.item?.[0]||t;if(s.answer){const o={...r,data:{...n,content:s.answer,contentType:L.TEXT}};this.emit(O.MESSAGE,o)}s.imageUrl?.forEach(o=>{const i={...r,data:{...n,content:{fileUrl:o?.startsWith("http")?o:this.OBS_URL+o,fileName:o.split("/").pop()},contentType:L.IMAGE}};this.emit(O.MESSAGE,i)})}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await Qn();return this.userInfo=t.data,this.userInfo}}g.ChatType=L,g.ConnectionStatus=A,g.EventType=O,g.MessageCode=k,g.MessageType=V,g.SendUserType=he,g.TOKEN_KEY=Ue,g.default=tr,g.isTextMessage=Gn,Object.defineProperties(g,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
@@ -30,9 +30,12 @@ export interface ConsultationItem {
30
30
  name: string;
31
31
  }
32
32
  export interface ConsultationListResponse {
33
+ /** 咨询列表 */
33
34
  list: ConsultationItem[];
34
35
  /** 秒数 */
35
36
  second: number;
37
+ /** 欢迎语 */
38
+ welcomeSentence: string;
36
39
  }
37
40
  export interface UserAuthParams {
38
41
  /** 商户AppKey */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "joytalk",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "JoyTalk SDK - 用于集成客服功能的 JavaScript SDK",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -1,12 +0,0 @@
1
- import { SessionData } from '../../types';
2
- import { EventEmitter } from '../../utils/event-emitter';
3
- export declare class ApiClient extends EventEmitter {
4
- /** obs 地址 */
5
- readonly OBS_URL: string;
6
- /**
7
- * 获取咨询列表
8
- */
9
- getConsultationList(entranceId: number): Promise<import('../../types').RequestResponse<import('../../types').ConsultationListResponse>>;
10
- handleUploadFile(file: File): Promise<string>;
11
- getFaqList(sessionData: SessionData): Promise<void>;
12
- }
@@ -1,74 +0,0 @@
1
- import { ConnectionStatus, SDKConfig } from '../../types';
2
- import { EventEmitter } from '../../utils/event-emitter';
3
- /**
4
- * 连接管理器接口
5
- */
6
- export interface IConnectionManager {
7
- connect(customerGroupId: string): Promise<void>;
8
- disconnect(): void;
9
- getStatus(): ConnectionStatus;
10
- isConnected(): boolean;
11
- getWebSocket(): WebSocket | null;
12
- }
13
- /**
14
- * WebSocket 连接管理器
15
- */
16
- export declare class ConnectionManager extends EventEmitter implements IConnectionManager {
17
- private config;
18
- private ws;
19
- private status;
20
- private reconnectTimer;
21
- private reconnectAttempts;
22
- private heartbeatTimeoutTimer;
23
- private lastHeartbeatTime;
24
- private customerGroupId;
25
- constructor(config: Required<SDKConfig>);
26
- /**
27
- * 连接到服务器
28
- */
29
- connect(customerGroupId: string): Promise<void>;
30
- /**
31
- * 断开连接
32
- */
33
- disconnect(): void;
34
- /**
35
- * 获取当前连接状态
36
- */
37
- getStatus(): ConnectionStatus;
38
- /**
39
- * 是否已连接
40
- */
41
- isConnected(): boolean;
42
- /**
43
- * 获取 WebSocket 实例
44
- */
45
- getWebSocket(): WebSocket | null;
46
- /**
47
- * 设置消息处理器
48
- */
49
- setMessageHandler(handler: (data: string | MessageEvent) => void): void;
50
- /**
51
- * 发送心跳
52
- */
53
- sendHeartbeat(): void;
54
- /**
55
- * 处理心跳响应
56
- */
57
- handleHeartbeatResponse(): void;
58
- /**
59
- * 构建 WebSocket URL
60
- */
61
- private buildWebSocketUrl;
62
- /**
63
- * 设置连接状态
64
- */
65
- private setStatus;
66
- /**
67
- * 安排重连
68
- */
69
- private scheduleReconnect;
70
- /**
71
- * 清除重连定时器
72
- */
73
- private clearReconnectTimer;
74
- }
@@ -1,23 +0,0 @@
1
- import { SessionData, FaqItem } from '../../types';
2
- /**
3
- * FAQ 管理器接口
4
- */
5
- export interface IFaqManager {
6
- getFaqList(sessionData: SessionData): Promise<void>;
7
- sendFaq(faqItem: FaqItem, sessionData: SessionData, obsUrl: string): void;
8
- }
9
- /**
10
- * FAQ 管理器
11
- */
12
- export declare class FaqManager implements IFaqManager {
13
- private emit;
14
- constructor(emit: (event: string, data?: any) => void);
15
- /**
16
- * 获取 FAQ 列表
17
- */
18
- getFaqList(sessionData: SessionData): Promise<void>;
19
- /**
20
- * 发送 FAQ
21
- */
22
- sendFaq(faqItem: FaqItem, sessionData: SessionData, obsUrl: string): void;
23
- }
@@ -1,29 +0,0 @@
1
- /**
2
- * 文件上传模块
3
- */
4
- /**
5
- * 文件上传器接口
6
- */
7
- export interface IFileUploader {
8
- uploadFile(file: File): Promise<string>;
9
- getVideoThumbnail(videoFile: File): Promise<File>;
10
- getObsUrl(): string;
11
- }
12
- /**
13
- * 文件上传器
14
- */
15
- export declare class FileUploader implements IFileUploader {
16
- private obsUrl;
17
- /**
18
- * 获取 OBS URL
19
- */
20
- getObsUrl(): string;
21
- /**
22
- * 上传文件
23
- */
24
- uploadFile(file: File): Promise<string>;
25
- /**
26
- * 获取视频文件的首帧作为缩略图
27
- */
28
- getVideoThumbnail(videoFile: File): Promise<File>;
29
- }
@@ -1,62 +0,0 @@
1
- import { MessageType, ChatType, Message, SessionData } from '../../types';
2
- /**
3
- * 消息处理器接口
4
- */
5
- export interface IMessageHandler {
6
- handleMessage(data: string | Message): void;
7
- sendMessage(data: string, chatType: ChatType | undefined, msgType?: MessageType): void;
8
- sendText(content: string): Promise<boolean>;
9
- sendFile(params: {
10
- file: File;
11
- thumbnailFile?: File;
12
- chatType: ChatType.IMAGE | ChatType.VIDEO | ChatType.FILE;
13
- }): Promise<string>;
14
- }
15
- /**
16
- * 消息处理器
17
- */
18
- export declare class MessageHandler implements IMessageHandler {
19
- private ws;
20
- private sessionData;
21
- private customerGroupId;
22
- private obsUrl;
23
- private emit;
24
- private handleUploadFile;
25
- constructor(ws: WebSocket | null, sessionData: SessionData | null, customerGroupId: string, obsUrl: string, emit: (event: string, data?: any) => void, handleUploadFile: (file: File) => Promise<string>);
26
- /**
27
- * 更新 WebSocket 实例
28
- */
29
- updateWebSocket(ws: WebSocket | null): void;
30
- /**
31
- * 更新会话数据
32
- */
33
- updateSessionData(sessionData: SessionData | null): void;
34
- /**
35
- * 更新客户组ID
36
- */
37
- updateCustomerGroupId(customerGroupId: string): void;
38
- /**
39
- * 处理收到的消息
40
- */
41
- handleMessage(data: string | Message): void;
42
- /**
43
- * 发送消息
44
- */
45
- sendMessage(data: string, chatType: ChatType | undefined, msgType?: MessageType): void;
46
- /**
47
- * 发送文本消息
48
- */
49
- sendText(content: string): Promise<boolean>;
50
- /**
51
- * 发送文件消息
52
- */
53
- sendFile({ file, thumbnailFile, chatType, }: {
54
- file: File;
55
- thumbnailFile?: File;
56
- chatType: ChatType.IMAGE | ChatType.VIDEO | ChatType.FILE;
57
- }): Promise<string>;
58
- /**
59
- * 判断是否为消息对象
60
- */
61
- private isMessage;
62
- }
@@ -1,25 +0,0 @@
1
- import { UserInfo } from '../../types';
2
- /**
3
- * 用户管理器接口
4
- */
5
- export interface IUserManager {
6
- getUserInfo(): Promise<UserInfo>;
7
- }
8
- /**
9
- * 用户管理器
10
- */
11
- export declare class UserManager implements IUserManager {
12
- private userInfo;
13
- /**
14
- * 获取用户信息
15
- */
16
- getUserInfo(): Promise<UserInfo>;
17
- /**
18
- * 获取缓存的用户信息
19
- */
20
- getCachedUserInfo(): UserInfo | null;
21
- /**
22
- * 清除用户信息缓存
23
- */
24
- clearCache(): void;
25
- }
@@ -1,2 +0,0 @@
1
- export declare class HttpHandler {
2
- }