const MAX_PENDING_DELTA_CHARACTERS=64*1024;function createOrderedStreamEmitter(t,n={}){let r=n.maxPendingEvents??64;if(!Number.isInteger(r)||r<1)throw RangeError(`maxPendingEvents must be a positive integer.`);let i=[],a=new Set,o=new Set,s=!1,c=0,l=0,u,d=!1,f=!1,p=new AbortController,throwIfFailed=()=>{if(d)throw u},settleIdleWaiters=()=>{for(let e of o)e();o.clear()},hasCapacity=()=>l<r&&c<MAX_PENDING_DELTA_CHARACTERS,settleCapacityWaiters=()=>{if(hasCapacity()){for(let e of a)e();a.clear()}},pump=async()=>{if(!(f||d)){for(f=!0;i.length>0;){let e=i.shift();if(e===void 0)break;c-=e.deltaCharacters,l-=e.sourceEvents,settleCapacityWaiters();try{await t(materializeEvent(e),e.messages)}catch(e){d||(u=e,d=!0,p.abort(e)),i.length=0,c=0,l=0,settleCapacityWaiters();break}}f=!1,settleIdleWaiters()}},waitForIdle=async()=>{if(!f&&i.length===0){throwIfFailed();return}await new Promise(e=>{o.add(e)}),throwIfFailed()},waitForCapacity=async()=>{hasCapacity()||(await new Promise(e=>{a.add(e)}),throwIfFailed())};return{async closeAndDrain(){s=!0,pump(),await waitForIdle()},async emit(t,n){if(throwIfFailed(),s)throw TypeError(`Cannot emit after the ordered stream emitter has closed.`);let a=i[i.length-1],o=appendDelta(t);a===void 0||!mergeAdjacentAppends(a,t,n)?i.push({deltaCharacters:o?.length??0,event:t,messages:n,sourceEvents:1}):(a.deltaCharacters+=o?.length??0,a.sourceEvents+=1),c+=o?.length??0,l+=1,pump(),(l>=r||c>=MAX_PENDING_DELTA_CHARACTERS)&&await waitForCapacity(),throwIfFailed()},failureSignal:p.signal}}function mergeAdjacentAppends(e,t,n){return e.event.type===`message.appended`&&t.type===`message.appended`?sameCoordinates(e.event,t)?(e.deltaParts??=[e.event.data.messageDelta],e.deltaParts.push(t.data.messageDelta),e.event=t,e.messages=n,!0):!1:e.event.type===`reasoning.appended`&&t.type===`reasoning.appended`&&sameCoordinates(e.event,t)?(e.deltaParts??=[e.event.data.reasoningDelta],e.deltaParts.push(t.data.reasoningDelta),e.event=t,e.messages=n,!0):!1}function appendDelta(e){if(e.type===`message.appended`)return e.data.messageDelta;if(e.type===`reasoning.appended`)return e.data.reasoningDelta}function materializeEvent(e){return e.deltaParts===void 0?e.event:e.event.type===`message.appended`?{...e.event,data:{...e.event.data,messageDelta:e.deltaParts.join(``)}}:e.event.type===`reasoning.appended`?{...e.event,data:{...e.event.data,reasoningDelta:e.deltaParts.join(``)}}:e.event}function sameCoordinates(e,t){return e.data.sequence===t.data.sequence&&e.data.stepIndex===t.data.stepIndex&&e.data.turnId===t.data.turnId}export{createOrderedStreamEmitter};