| 149 | } |
| 150 | |
| 151 | async function handlePrompt(request: Request, env: Env): Promise<Response> { |
| 152 | let body: PromptRequest; |
| 153 | try { |
| 154 | body = (await request.json()) as PromptRequest; |
| 155 | } catch { |
| 156 | return errorJSON(new Error("invalid JSON body"), 400); |
| 157 | } |
| 158 | |
| 159 | const prompt = body.prompt; |
| 160 | if (typeof prompt !== "string" || prompt.trim().length === 0) { |
| 161 | return errorJSON(new Error("must provide a non-empty prompt"), 400); |
| 162 | } |
| 163 | |
| 164 | // One Durable Object instance owns the workspace. A fixed name |
| 165 | // keeps every request on the same store; swap in a per-user name |
| 166 | // to give each caller an isolated workspace. |
| 167 | const stub = env.AssetWorkspace.get(env.AssetWorkspace.idFromName("default")); |
| 168 | try { |
| 169 | const result = await stub.generate(prompt); |
| 170 | return new Response(JSON.stringify(result), { |
| 171 | status: 200, |
| 172 | headers: { "content-type": "application/json" }, |
| 173 | }); |
| 174 | } catch (error) { |
| 175 | return errorJSON(error, 500); |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | function errorJSON(error: unknown, status: number): Response { |
| 180 | const message = error instanceof Error ? error.message : String(error); |