import{createEveMessageStreamRoutePath}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";const STREAM_OPEN_RETRYABLE_STATUS=new Set([404,409,425,500,502,503,504]);async function*openStreamIterable(e){let t=e.startIndex,n=e.maxReconnectAttempts;for(;;){let a=await openStreamBody({...e,startIndex:t}),o=!1;try{for await(let e of readNdjsonStream(a))t+=1,yield e}catch(e){if(!isStreamDisconnectError(e))throw e;o=!0}if(!o||n<=0)return;--n}}async function openStreamBody(r){let i,o;for(let s=0;s<12;s+=1){let c=createClientUrl(r.host,createEveMessageStreamRoutePath(r.sessionId),r.startIndex>0?{startIndex:String(r.startIndex)}:void 0),l=await r.resolveHeaders(),u=await fetch(c,{headers:l,signal:r.signal??null});if(u.ok){if(!u.body)throw new ClientError(u.status,`Response body is null.`);return u.body}if(i=u.status,o=await u.text(),!STREAM_OPEN_RETRYABLE_STATUS.has(u.status))throw new ClientError(u.status,o);s<11&&await sleep(250)}throw new ClientError(i??0,o??`Failed to open message stream.`)}async function sleep(e){await new Promise(t=>setTimeout(t,e))}export{openStreamBody,openStreamIterable};