import*as S from"node:http";import{AsyncLocalStorage as u}from"node:async_hooks";import{Readable as w,Stream as E}from"node:stream";import{pipeline as b}from"node:stream/promises";import{ReadableStream as k}from"node:stream/web";import{getPathPrefix as H}from"@redocly/theme/core/utils";import{SERVER_EDITOR_APP_URL as x}from"../../shared/urls.js";import{logger as m}from"../utils/index.js";import{exit as A}from"../utils/process.js";const y=new u;globalThis.redoclyCookieStorage=y;function q(n,l=4e3){return new Promise((h,i)=>{const d=S.createServer(async(t,r)=>{const R=t.headers.cookie||"";y.run(R,async()=>{let s;try{const e=new URL(t.url||"",`http://${t.headers.host}`),o=[],c=t.rawHeaders.length;for(let f=0;f<c;f+=2)o.push([t.rawHeaders[f],t.rawHeaders[f+1]]);const a={headers:o,method:t.method};t.method==="GET"||t.method==="HEAD"||(a.body=w.toWeb(t),a.duplex="half");const p=new Request(e.toString(),a);p.context={remoteAddr:{hostname:t.socket.remoteAddress,port:t.socket.remotePort},url:e},s=await n.fetch(p)}catch(e){s=new Response(null,{status:500}),e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError"?s=new Response(null,{status:504}):e.code==="ERR_INVALID_URL"&&(s=new Response("Invalid URL",{status:404})),m.error(`Error while handling request: %s
%s`,e.message,e.stack))}r.setHeader("Access-Control-Allow-Origin",x),r.setHeader("Access-Control-Allow-Credentials","true");for(const[e,o]of s.headers||[])try{e==="set-cookie"?r.setHeader(e,s.headers.getSetCookie(e)):r.setHeader(e,o)}catch(c){m.error(`Error while setting header: ${c?.message}`)}if(r.setHeader("Vary","Cookie"),r.statusCode=s.status||500,s.body)try{if(L(s)){const e=new E.Transform({transform(o,c,a){if(r.closed||r.destroyed)return a();r.write(o,c)?process.nextTick(a):r.once("drain",a)},flush(o){if(r.closed||r.destroyed)return o();r.end(),o()}});await b(s.body instanceof k?w.fromWeb(s.body):s.body,e)}else{const e=await s.text();r.setHeader("Content-Length",Buffer.byteLength(e)),r.end(e)}}catch(e){console.error(e);const o=e instanceof Error?e:new Error("unknown error",{cause:e});r.destroy(o)}else r.end()})});process.on("SIGTERM",()=>{d.close(()=>{A(0)})}),d.listen(parseInt(String(l),10)).on("listening",()=>{m.logSticky("server",`  \u{1F310} Preview URL: http://127.0.0.1:${l}${H()}`),h(d)}).on("error",i)})}function L(n){const l=n.headers.get("content-type")||"",h=n.headers.get("x-accel-buffering")||"",i=n.headers.get("content-encoding"),d=n.headers.get("content-length"),t=n.headers.get("transfer-encoding");return i||t||d||/^no$/i.test(h)||!/^(text\/(?!event-stream\b))/i.test(l)}export{q as startHttpServer};
