| 1 | import { Miniflare, type MiniflareOptions, type Response } from "miniflare"; |
| 2 | import type { RolldownOutput } from "rolldown"; |
| 3 | import { miniflareModulesFromRolldownOutput } from "./miniflare-module.ts"; |
| 4 | |
| 5 | export interface MiniflareInstance { |
| 6 | url: URL; |
| 7 | fetch(path: string): Promise<Response>; |
| 8 | fetchText(path: string): Promise<string>; |
| 9 | fetchJson<T>(path: string): Promise<T>; |
| 10 | [Symbol.asyncDispose]: () => Promise<void>; |
| 11 | } |
| 12 | |
| 13 | export type Options = Extract<MiniflareOptions, { modules: Array<any> }>; |
| 14 | |
| 15 | export async function createMiniflare( |
| 16 | options: Options, |
| 17 | ): Promise<MiniflareInstance> { |
| 18 | const miniflare = new Miniflare(options); |
| 19 | const url = await miniflare.ready; |
| 20 | const fetch = (path: string) => |
| 21 | miniflare.dispatchFetch(`http://localhost${path}`); |
| 22 | return { |
| 23 | url, |
| 24 | fetch, |
| 25 | fetchText: (path: string) => |
| 26 | fetch(path).then((response) => response.text()), |
| 27 | fetchJson: <T>(path: string) => |
| 28 | fetch(path).then((response) => response.json() as Promise<T>), |
| 29 | [Symbol.asyncDispose]: () => miniflare.dispose(), |
| 30 | }; |
| 31 | } |
| 32 | |
| 33 | export async function createMiniflareFromRolldown( |
| 34 | output: RolldownOutput, |
| 35 | options: Partial<Options> = {}, |
| 36 | ): Promise<MiniflareInstance> { |
| 37 | return createMiniflare({ |
| 38 | modules: miniflareModulesFromRolldownOutput(output.output), |
| 39 | ...options, |
| 40 | }); |
| 41 | } |