import{toErrorMessage}from"#shared/errors.js";import{Readable}from"node:stream";function createPublicRequest(e,n){let r=e.headers.host??`localhost`,i=new URL(e.url??`/`,`http://${r}`),a=new Headers;for(let[t,n]of Object.entries(e.headers))if(Array.isArray(n))for(let e of n)a.append(t,e);else n!==void 0&&a.set(t,n);let o=e.method!==`GET`&&e.method!==`HEAD`;return new Request(i,{body:o?Readable.toWeb(e):void 0,duplex:o?`half`:void 0,headers:a,method:e.method,signal:n})}async function writeResponse(e,n,r){if(e.destroyed){await n.body?.cancel();return}e.statusCode=n.status,e.statusMessage=n.statusText;let i=n.headers.getSetCookie?.call(n.headers)??[];if(n.headers.forEach((t,n)=>{n.toLowerCase()!==`set-cookie`&&e.setHeader(n,t)}),i.length>0&&e.setHeader(`set-cookie`,[...i]),n.body===null){await endResponse(e);return}let a=Readable.fromWeb(n.body),cancelBody=()=>a.destroy(r.reason);r.addEventListener(`abort`,cancelBody,{once:!0});try{await new Promise((t,n)=>{a.once(`error`,n),e.once(`error`,n),e.once(`close`,()=>{e.writableEnded||n(Error(`Development client disconnected.`))}),e.once(`finish`,t),a.pipe(e)})}finally{r.removeEventListener(`abort`,cancelBody),!a.destroyed&&(r.aborted||e.destroyed)&&a.destroy()}}function writeRequestError(t,n){if(t.headersSent){t.destroy();return}t.statusCode=503,t.setHeader(`content-type`,`application/json; charset=utf-8`),!t.writableEnded&&!t.destroyed&&t.end(JSON.stringify({error:toErrorMessage(n)}))}function closeServer(e){if(!e.listening)return Promise.resolve();let t=new Promise((t,n)=>{e.close(e=>{e===void 0?t():n(e)})});return e.closeIdleConnections?.(),t}async function endResponse(e){await new Promise((t,n)=>{e.once(`error`,n),e.end(t)})}export{closeServer,createPublicRequest,writeRequestError,writeResponse};