UNPKG

asyncsse

Version:

Fetch Server-Sent Events (SSE) as an async iterable

6 lines (5 loc) 1.01 kB
async function*p(a,n={},s={}){let e,r=null,t="";try{if(e=await(s.fetch??fetch)(a,n),s.onResponse&&await s.onResponse(e),!e.ok){yield{error:`HTTP ${e.status} ${e.statusText} - ${await e.text()}`};return}if(!e.body){yield{error:"No response body"};return}r=e.body.getReader();let o=new TextDecoder;for(;;){let{value:i,done:f}=await r.read();t+=o.decode(i,{stream:!0});let d=t.split(/(?=\r?\n\r?\n)/);t=d.pop()||"";for(let y of d){let l=c(y);Object.keys(l).length>0&&(yield l)}if(f)break}if(t.trim()){let i=c(t.trim());Object.keys(i).length>0&&(yield i)}}catch(o){if(t.trim()){let i=c(t.trim());Object.keys(i).length>0&&(yield i)}yield{error:`Failed: ${o}`}}finally{if(r)try{await r.cancel()}catch{}}}var c=a=>{let n={},s="";for(let e of a.split(` `)){if(e.startsWith(":"))continue;let r=e.indexOf(":");if(r===-1){s&&(n[s]+=` `+e);continue}let[t,o]=[e.slice(0,r),e.slice(r+1).trim()];t==="data"?n.data=(n.data||"")+(n.data?` `:"")+o:n[t]=o,s=t}return n};export{p as asyncSSE}; //# sourceMappingURL=asyncsse.js.map