import SSE from './sse.js'; interface AIOptionsConfig { baseUrl: string; token: string; appCode: string; lang: string; } interface SSEParams { aiOptions: AIOptionsConfig; url: string; method: string; data: object; callback: (content: any, type?: any) => void | Promise; } // const baseUrl = 'https://dev.wensi.cc/client/'; const headers: any = {}; const timeout = 60000; // export const getTmpUid = async () => { // if (localStorage.getItem('tmpUid')) return localStorage.getItem('tmpUid'); // try{ // const res = await fetch(`${baseUrl}cli/chatgpt/v1/getTmpUid`, { // method: 'GET', // headers, // }).then(res => res.json()); // if (res.code == 200) { // localStorage.setItem('tmpUid', res.data) // return res.data; // } // return ''; // }catch(e){ // return ''; // } // }; const sse = async ({ aiOptions, url, method, data, callback }: SSEParams) => { let payload; let timeoutId: any = null; if (method === 'post') { headers['Content-Type'] = 'application/json'; if (data) { // data.tmpUid = await getTmpUid(); payload = JSON.stringify(data); } } try { const source = new SSE(`${aiOptions.baseUrl}${url}`, { headers: { ...headers, 'X-Auth-Token': aiOptions.token, 'X-App-Code': aiOptions.appCode, 'Accept-Language': aiOptions.lang, }, payload, }); source.addEventListener('message', (event: any) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => { if (callback) callback(null, 'timeout'); source.close(); }, timeout); try { let content = JSON.parse(event.data); // console.log(111, content); if (content.end === true) { clearTimeout(timeoutId); if (callback) callback(content); source.close(); } else { if (callback) callback(content); } } catch (e) {} }); source.addEventListener('error', (error: any) => { source.close(); let message = ''; if (error.data) { try { const data = JSON.parse(error.data); message = data.detail?.message; } catch (e) { const parser = new DOMParser(); const doc = parser.parseFromString(error.data, 'text/html'); const msg = doc.querySelector('.message p'); message = msg ? msg.textContent + '. ' : ''; const explanation = doc.querySelector('.explanation'); message += explanation ? explanation.textContent : ''; } } else { message = 'fail'; } if (callback) callback(null, message); }); source.stream(); timeoutId = setTimeout(() => { if (callback) callback(null, 'timeout'); source.close(); }, timeout); return source; } catch (e) { if (callback) callback(null, e); return null; } }; export default sse;