| 21 | |
| 22 | // Mock BlockRun API server |
| 23 | async function startMockServer(): Promise<{ port: number; close: () => Promise<void> }> { |
| 24 | const server = createServer(async (req: IncomingMessage, res: ServerResponse) => { |
| 25 | const chunks: Buffer[] = []; |
| 26 | for await (const chunk of req) { |
| 27 | chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); |
| 28 | } |
| 29 | const body = Buffer.concat(chunks).toString(); |
| 30 | requestBodies.push(body); |
| 31 | |
| 32 | try { |
| 33 | const parsed = JSON.parse(body) as { model?: string; messages?: Array<{ content: string }> }; |
| 34 | const model = parsed.model || "unknown"; |
| 35 | modelCalls.push(model); |
| 36 | |
| 37 | // Track payment attempt (x-payment header means payment was attempted) |
| 38 | if (req.headers["x-payment"]) { |
| 39 | paymentAttempts.push(Date.now()); |
| 40 | } |
| 41 | |
| 42 | // Success response |
| 43 | res.writeHead(200, { "Content-Type": "application/json" }); |
| 44 | res.end( |
| 45 | JSON.stringify({ |
| 46 | id: "chatcmpl-test", |
| 47 | object: "chat.completion", |
| 48 | created: Date.now(), |
| 49 | model, |
| 50 | choices: [ |
| 51 | { |
| 52 | index: 0, |
| 53 | message: { role: "assistant", content: `Response from ${model}` }, |
| 54 | finish_reason: "stop", |
| 55 | }, |
| 56 | ], |
| 57 | usage: { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 }, |
| 58 | }), |
| 59 | ); |
| 60 | } catch { |
| 61 | res.writeHead(400, { "Content-Type": "application/json" }); |
| 62 | res.end(JSON.stringify({ error: "Invalid request" })); |
| 63 | } |
| 64 | }); |
| 65 | |
| 66 | return new Promise((resolve) => { |
| 67 | server.listen(0, "127.0.0.1", () => { |
| 68 | const addr = server.address() as AddressInfo; |
| 69 | resolve({ |
| 70 | port: addr.port, |
| 71 | close: () => new Promise<void>((res) => server.close(() => res())), |
| 72 | }); |
| 73 | }); |
| 74 | }); |
| 75 | } |
| 76 | |
| 77 | // Import after mock server is ready |
| 78 | async function runTests() { |