* Wrap a JSON-bodied /internal/* handler with the standard bearer-auth + * generation-check + json-parse + error-response boilerplate. The handler * `fn` is called with the parsed body; whatever it returns is JSON-stringified * into a 200 Response, or the handler can return a Response directly to
( req: Request, fn: (body: any) => T | Promise<T> | Response | Promise<Response>, )
| 404 | * New routes become a single call to internalHandler. |
| 405 | */ |
| 406 | async function internalHandler<T>( |
| 407 | req: Request, |
| 408 | fn: (body: any) => T | Promise<T> | Response | Promise<Response>, |
| 409 | ): Promise<Response> { |
| 410 | const denied = checkInternalAuth(req); |
| 411 | if (denied) return denied; |
| 412 | let body: any; |
| 413 | try { |
| 414 | body = await req.json(); |
| 415 | } catch { |
| 416 | return new Response('bad', { status: 400 }); |
| 417 | } |
| 418 | try { |
| 419 | const result = await fn(body); |
| 420 | if (result instanceof Response) return result; |
| 421 | if (result === undefined || result === null) return new Response('ok'); |
| 422 | return new Response(JSON.stringify(result), { |
| 423 | status: 200, |
| 424 | headers: { 'Content-Type': 'application/json' }, |
| 425 | }); |
| 426 | } catch { |
| 427 | return new Response('bad', { status: 400 }); |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | /** |
| 432 | * Spawn the claude PTY for a session if it hasn't been spawned yet. |
no test coverage detected