| 2968 | } |
| 2969 | |
| 2970 | async function readJsonBody(request: IncomingMessage, maxBodyBytes: number): Promise<unknown> { |
| 2971 | const chunks: Buffer[] = []; |
| 2972 | let totalBytes = 0; |
| 2973 | for await (const chunk of request) { |
| 2974 | const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); |
| 2975 | totalBytes += buffer.byteLength; |
| 2976 | if (totalBytes > maxBodyBytes) { |
| 2977 | throw new Error(`Request body exceeded ${maxBodyBytes} bytes.`); |
| 2978 | } |
| 2979 | chunks.push(buffer); |
| 2980 | } |
| 2981 | if (chunks.length === 0) { |
| 2982 | return {}; |
| 2983 | } |
| 2984 | try { |
| 2985 | return JSON.parse(Buffer.concat(chunks).toString('utf8')); |
| 2986 | } catch (error) { |
| 2987 | const message = error instanceof Error && error.message.trim() |
| 2988 | ? error.message.trim() |
| 2989 | : 'Malformed JSON request body.'; |
| 2990 | throw new Error(message); |
| 2991 | } |
| 2992 | } |
| 2993 | |
| 2994 | function startSse(response: ServerResponse): void { |
| 2995 | response.writeHead(200, { |