( res: ServerResponse, status: HttpErrorStatus, type: ProblemType, title: string, detail?: string, )
| 8 | import type { HttpErrorStatus } from '@inkeep/open-knowledge-server'; |
| 9 | |
| 10 | export function emitProblem( |
| 11 | res: ServerResponse, |
| 12 | status: HttpErrorStatus, |
| 13 | type: ProblemType, |
| 14 | title: string, |
| 15 | detail?: string, |
| 16 | ): void { |
| 17 | const instance = `urn:uuid:${randomUUID()}`; |
| 18 | if (res.headersSent || res.writableEnded || res.destroyed) { |
| 19 | console.error('[ok ui] emitProblem called after headers sent — suppressed', { |
| 20 | type, |
| 21 | status, |
| 22 | instance, |
| 23 | }); |
| 24 | return; |
| 25 | } |
| 26 | const body: ProblemDetails = { |
| 27 | type, |
| 28 | title, |
| 29 | status, |
| 30 | instance, |
| 31 | ...(detail !== undefined ? { detail } : {}), |
| 32 | }; |
| 33 | const validated = ProblemDetailsSchema.safeParse(body); |
| 34 | if (!validated.success) { |
| 35 | console.error('[ok ui] emitProblem produced an invalid ProblemDetails body:', { |
| 36 | issues: validated.error.issues, |
| 37 | originalStatus: status, |
| 38 | body, |
| 39 | }); |
| 40 | const fallbackStatus = 500 as const; |
| 41 | res.writeHead(fallbackStatus, { |
| 42 | 'Content-Type': 'application/problem+json', |
| 43 | 'X-Content-Type-Options': 'nosniff', |
| 44 | 'Cache-Control': 'no-store', |
| 45 | }); |
| 46 | res.end( |
| 47 | JSON.stringify({ |
| 48 | type: 'urn:ok:error:internal-server-error' satisfies ProblemType, |
| 49 | title: 'Internal server error.', |
| 50 | status: fallbackStatus, |
| 51 | instance, |
| 52 | }), |
| 53 | ); |
| 54 | return; |
| 55 | } |
| 56 | res.writeHead(status, { |
| 57 | 'Content-Type': 'application/problem+json', |
| 58 | 'X-Content-Type-Options': 'nosniff', |
| 59 | 'Cache-Control': 'no-store', |
| 60 | }); |
| 61 | res.end(JSON.stringify(body)); |
| 62 | } |
no test coverage detected