"use strict";var t,e,s=require("crypto-js"),r=require("ws");class o{constructor(t,e=.5,s=2048,r=4,o){this.domain=t,this.temperature=e,this.max_tokens=s,this.top_k=r,this.chat_id=o}static createFromVersion(t){return new o(function(t){switch(t){case 1:return"general";case 2:return"generalv2";case 3:return"generalv3";case 3.5:return"generalv3.5";default:throw new Error("不存在的版本.")}}(t))}toValue(){return{chat:{domain:this.domain,temperature:this.temperature,max_tokens:this.max_tokens,top_k:this.top_k,chat_id:this.chat_id}}}}class n{constructor(t){this.text=t}static fromMessage(t){return new n(t.text).toValue()}toValue(){return{message:{text:this.text}}}}class i{constructor(t){this.responseValueList=t}getAllContent(){return this.hasError(),this.responseValueList.map((t=>t.payload.choices.text.map((t=>t.content)).join(""))).join("")}getPromptTokens(){var t,e;return this.hasError(),null===(e=null===(t=this.responseValueList.at(-1))||void 0===t?void 0:t.payload.usage)||void 0===e?void 0:e.text.prompt_tokens}getCompletionTokens(){var t,e;return this.hasError(),null===(e=null===(t=this.responseValueList.at(-1))||void 0===t?void 0:t.payload.usage)||void 0===e?void 0:e.text.completion_tokens}getTotalTokens(){var t,e;return this.hasError(),null===(e=null===(t=this.responseValueList.at(-1))||void 0===t?void 0:t.payload.usage)||void 0===e?void 0:e.text.total_tokens}hasError(){this.responseValueList.forEach((t=>{if(0!==t.header.code)throw new Error(JSON.stringify(t))}))}}function a(t,e,s,r){return new(s||(s=Promise))((function(o,n){function i(t){try{h(r.next(t))}catch(t){n(t)}}function a(t){try{h(r.throw(t))}catch(t){n(t)}}function h(t){var e;t.done?o(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(i,a)}h((r=r.apply(t,e||[])).next())}))}exports.Role=void 0,(t=exports.Role||(exports.Role={})).Assistant="assistant",t.User="user",t.System="system","function"==typeof SuppressedError&&SuppressedError;class h{constructor(t,e,s=5e3){this.spark=t,this.uid=e,this.tokenLength=s,this.history=[],this.systemContent=null}speak(t){return a(this,arguments,void 0,(function*(t,e=o.createFromVersion(this.spark.version),s){if(t.length<=0)throw new Error("内容不可以为空.");const r=yield this.spark.request({header:{app_id:this.spark.APPID,uid:this.uid},parameter:e.toValue(),payload:{message:{text:[...this.getHistory(),{role:exports.Role.User,content:t}]}}},6e4,s);return this.history.push({role:exports.Role.User,content:t}),this.history.push({role:exports.Role.Assistant,content:r.getAllContent()}),r}))}getHistory(t=this.tokenLength){const e=[];null!==this.systemContent&&this.systemContent.length>0&&e.push({role:exports.Role.System,content:this.systemContent});for(let s of this.history){if(!(0+s.content.length<=t))return e;e.push(s)}return e}setSystemContent(t){this.systemContent=t}}!function(t){t[t.Browser=0]="Browser",t[t.Node=1]="Node"}(e||(e={}));class c{constructor(t){this.url=t,this.environment=c.getEnvironment(),this.environment===e.Browser?this.webSocket=new WebSocket(t):this.webSocket=new r(t)}static getEnvironment(){return"undefined"!=typeof window?e.Browser:e.Node}addEventListener(t,s,o){(this.environment===e.Browser&&this.webSocket instanceof WebSocket||this.webSocket instanceof r)&&this.webSocket.addEventListener(t,s,o)}removeEventListener(t,s,o){(this.environment===e.Browser&&this.webSocket instanceof WebSocket||this.webSocket instanceof r)&&this.webSocket.removeEventListener(t,s,o)}close(){this.webSocket.close()}send(t){this.webSocket.send(t)}}exports.Parameter=o,exports.Payload=n,exports.Response=i,exports.SparkDesk=class{get version(){return this.option.version}constructor(t){this.option=t}get APPID(){return this.option.APPID}getWebsocketUrl(){const t=this.option.APIKey,e=this.option.APISecret,r=this.getDomain();this.option.noEncryption&&(r.protocol="ws");const o=r.host,n=(new Date).toUTCString(),i=`host: ${o}\ndate: ${n}\nGET ${r.pathname} HTTP/1.1`,a=s.HmacSHA256(i,e),h=s.enc.Base64.stringify(a);return`${r}?authorization=${btoa(`api_key="${t}", algorithm="hmac-sha256", headers="host date request-line", signature="${h}"`)}&date=${n}&host=${o}`}getDomain(){switch(this.option.version){case 1:return new URL("wss://spark-api.xf-yun.com/v1.1/chat");case 2:return new URL("wss://spark-api.xf-yun.com/v2.1/chat");case 3:return new URL("wss://spark-api.xf-yun.com/v3.1/chat");case 3.5:return new URL("wss://spark-api.xf-yun.com/v3.5/chat");default:throw new Error("不存在的版本.")}}request(t){return a(this,arguments,void 0,(function*(t,e=6e4,s){return new Promise(((r,o)=>{const n=setTimeout((()=>{o(new Error("请求超时")),a&&a.close()}),e),a=new c(this.getWebsocketUrl()),h=[];a.addEventListener("open",(()=>{a.send(JSON.stringify(t))})),a.addEventListener("message",(t=>{s&&s(t);const e=JSON.parse(t.data.toString());h.push(e)})),a.addEventListener("close",(()=>{clearTimeout(n),r(new i(h))})),a.addEventListener("error",o)}))}))}createUser(t,e){return new h(this,t,e)}},exports.User=h;