import { fileURLToPath } from "node:url"; import type { PlatformError } from "effect"; import { Effect, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; /** What {@link SourceProcess.run} and {@link SourceProcess.command} take besides the script. */ export interface SourceProcessOptions { /** Arguments after the script. */ readonly args?: ReadonlyArray; /** * The child's environment, on top of `PATH`. The child gets only `PATH` and these: it never inherits the test * process's environment, so a variable the test runner sets cannot leak into what the fixture observes. */ readonly env?: Readonly>; /** * Bytes written to the child's stdin, which is then closed. Omitted, stdin is closed at once, so a child that reads * it to its end never waits on the test. */ readonly stdin?: string | Uint8Array; } /** A finished {@link SourceProcess.run}: the exit code and every byte of both streams, decoded as UTF-8. */ export interface SourceProcessResult { readonly exitCode: number; readonly stdout: string; readonly stderr: string; } const register = fileURLToPath(new URL("./register-ts.mjs", import.meta.url)); const command = (script: string, options: SourceProcessOptions = {}): ChildProcess.Command => ChildProcess.make(process.execPath, ["--import", register, script, ...(options.args ?? [])], { env: { PATH: process.env.PATH ?? "", ...options.env }, stdin: options.stdin === undefined ? Stream.empty : Stream.make(typeof options.stdin === "string" ? new TextEncoder().encode(options.stdin) : options.stdin), }); const text = (stream: Stream.Stream) => Stream.mkString(Stream.decodeText(stream)); const run = ( script: string, options?: SourceProcessOptions, ): Effect.Effect => Effect.scoped( Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const handle = yield* spawner.spawn(command(script, options)); const [stdout, stderr, exitCode] = yield* Effect.all( [text(handle.stdout), text(handle.stderr), handle.exitCode], { concurrency: "unbounded" }, ); return { exitCode: Number(exitCode), stdout, stderr }; }), ); /** * A real child process running a TypeScript fixture against the workspace's package sources, under tsx: the one * place a test that needs a real process (its real stdout, its exit, its timers) starts one. * * @remarks * The child is `node --import