Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Deferred from "effect/Deferred";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Layer from "effect/Layer";
7import * as PlatformError from "effect/PlatformError";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import { TestClock } from "effect/testing";
11import { ChildProcessSpawner } from "effect/process";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import { SpawnExecutableResolution } from "@t3tools/shared/shell";
14
15import * as ProcessRunner from "./processRunner.ts";
16
17type ChildProcessCommand = {
18 readonly command: string;
19 readonly args: ReadonlyArray<string>;
20 readonly options: {
21 readonly shell?: boolean | string;
22 };
23};
24
25function asChildProcessCommand(command: unknown): ChildProcessCommand {
26 return command as ChildProcessCommand;
27}
28
29function makeHandle(input: {
30 readonly stdout?: string | Stream.Stream<Uint8Array>;
31 readonly stderr?: string | Stream.Stream<Uint8Array>;
32 readonly code?: number;
33 readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
34 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
35}) {
36 return ChildProcessSpawner.makeHandle({
37 pid: ChildProcessSpawner.ProcessId(1),
38 exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
39 isRunning: Effect.succeed(false),
40 kill: () => Effect.void,
41 unref: Effect.succeed(Effect.void),
42 stdin: input.stdin ?? Sink.drain,
43 stdout:
44 typeof input.stdout === "string"
45 ? Stream.encodeText(Stream.make(input.stdout))
46 : (input.stdout ?? Stream.empty),
47 stderr:
48 typeof input.stderr === "string"
49 ? Stream.encodeText(Stream.make(input.stderr))
50 : (input.stderr ?? Stream.empty),
51 all: Stream.empty,
52 getInputFd: () => Sink.drain,
53 getOutputFd: () => Stream.empty,
54 });
55}
56
57function makeSpawner(
58 f: (
59 command: ChildProcessCommand,
60 ) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>,
61) {
62 return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
63}
64
65const runWith =
66 (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) =>
67 (input: ProcessRunner.ProcessRunInput) =>
68 Effect.service(ProcessRunner.ProcessRunner).pipe(
69 Effect.flatMap((runner) =>
70 runner.run({
71 ...input,
72 }),
73 ),
74 Effect.provide(
75 ProcessRunner.layer.pipe(
76 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
77 ),
78 ),
79 );
80
81describe("runProcess", () => {
82 it.effect("collects stdout through an injected ChildProcessSpawner", () =>
83 Effect.gen(function* () {
84 const spawner = makeSpawner((command) =>
85 Effect.sync(() => {
86 expect(command.command).toBe("fake");
87 expect(command.args).toEqual(["stdout-bytes", "32"]);
88 return makeHandle({ stdout: "x".repeat(32) });
89 }),
90 );
91
92 const result = yield* runWith(spawner)({
93 command: "fake",
94 args: ["stdout-bytes", "32"],
95 });
96
97 expect(result.code).toBe(0);
98 expect(result.stdout).toBe("x".repeat(32));
99 expect(result.timedOut).toBe(false);
100 }),
101 );
102
103 it.effect("runs through the ProcessRunner service", () => {
104 const spawner = makeSpawner((command) =>
105 Effect.sync(() => {
106 expect(command.command).toBe("fake");
107 expect(command.args).toEqual(["--service"]);
108 return makeHandle({ stdout: "service ok" });
109 }),
110 );
111 const layer = ProcessRunner.layer.pipe(
112 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
113 );
114
115 return Effect.gen(function* () {
116 const runner = yield* ProcessRunner.ProcessRunner;
117 const result = yield* runner.run({
118 command: "fake",
119 args: ["--service"],
120 });
121
122 expect(result.stdout).toBe("service ok");
123 }).pipe(Effect.provide(layer));
124 });
125
126 it.effect("resolves and escapes Windows command shims before spawning", () => {
127 const spawner = makeSpawner((command) =>
128 Effect.sync(() => {
129 expect(command.command).toBe(
130 [
131 '^"C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd^"',
132 '^"repos^"',
133 '^"pr^"',
134 '^"list^"',
135 '^"--source-branch^"',
136 '^"feature^ ^&^ release^"',
137 ].join(" "),
138 );
139 expect(command.args).toEqual([]);
140 expect(command.options.shell).toBe(true);
141 return makeHandle({ stdout: "[]" });
142 }),
143 );
144
145 return runWith(spawner)({
146 command: "az",
147 args: ["repos", "pr", "list", "--source-branch", "feature & release"],
148 env: { AZURE_CONFIG_DIR: "C:\\Users\\tester\\.azure" },
149 }).pipe(
150 Effect.provideService(HostProcess.Platform, "win32"),
151 Effect.provideService(HostProcess.Environment, {
152 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
153 PATHEXT: ".COM;.EXE;.BAT;.CMD",
154 }),
155 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) =>
156 env.PATH === "C:\\Users\\tester\\AppData\\Roaming\\npm" &&
157 env.AZURE_CONFIG_DIR === "C:\\Users\\tester\\.azure"
158 ? "C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd"
159 : undefined,
160 ),
161 Effect.map((result) => {
162 expect(result.stdout).toBe("[]");
163 }),
164 );
165 });
166
167 it.effect("preserves resolved spawn context and cause", () =>
168 Effect.gen(function* () {
169 const cause = PlatformError.systemError({
170 _tag: "PermissionDenied",
171 module: "ChildProcessSpawner",
172 method: "spawn",
173 pathOrDescriptor: "/actual/fake",
174 });
175 const spawner = makeSpawner(() => Effect.fail(cause));
176
177 const error = yield* runWith(spawner)({
178 command: "fake",
179 args: ["--flag", "secret-token-value"],
180 cwd: "/logical",
181 spawnCwd: "/actual",
182 }).pipe(Effect.flip);
183
184 expect(error._tag).toBe("ProcessSpawnError");
185 if (error._tag !== "ProcessSpawnError") {
186 return expect.fail("Expected ProcessSpawnError");
187 }
188 expect(error).toMatchObject({
189 command: "fake",
190 argumentCount: 2,
191 cwd: "/logical",
192 spawnCwd: "/actual",
193 resolvedCommand: "fake",
194 resolvedArgumentCount: 2,
195 shell: false,
196 });
197 expect(error.cause).toBe(cause);
198 expect(error.message).toBe("Failed to spawn process 'fake' in '/actual'");
199 expect(error).not.toHaveProperty("args");
200 expect(error).not.toHaveProperty("resolvedArgs");
201 expect(error.message).not.toContain("secret-token-value");
202 }),
203 );
204
205 it.effect("fails when output exceeds max buffer in default mode", () =>
206 Effect.gen(function* () {
207 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
208
209 const error = yield* runWith(spawner)({
210 command: "fake",
211 args: ["stdout-bytes", "2048"],
212 maxOutputBytes: 128,
213 }).pipe(Effect.flip);
214
215 expect(error._tag).toBe("ProcessOutputLimitError");
216 if (error._tag !== "ProcessOutputLimitError") {
217 return expect.fail("Expected ProcessOutputLimitError");
218 }
219 expect(error).toMatchObject({
220 stream: "stdout",
221 maxBytes: 128,
222 observedBytes: 2048,
223 });
224 expect(error.message).toBe(
225 "Process 'fake' stdout produced 2048 bytes, exceeding the 128 byte limit",
226 );
227 }),
228 );
229
230 it.effect("accepts output at the byte limit followed by an empty chunk", () =>
231 Effect.gen(function* () {
232 const output = new TextEncoder().encode("exactly");
233 const spawner = makeSpawner(() =>
234 Effect.succeed(
235 makeHandle({
236 stdout: Stream.make(output, new Uint8Array()),
237 }),
238 ),
239 );
240
241 const result = yield* runWith(spawner)({
242 command: "fake",
243 args: ["exact-limit"],
244 maxOutputBytes: output.byteLength,
245 });
246
247 expect(result.stdout).toBe("exactly");
248 }),
249 );
250
251 it.effect("fails fast on output limit before timeout for long-running output", () =>
252 Effect.gen(function* () {
253 const textChunk = "x".repeat(64);
254 const spawner = makeSpawner(() =>
255 Effect.succeed(
256 makeHandle({
257 stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
258 Stream.encodeText,
259 ),
260 exitCode: Effect.never,
261 }),
262 ),
263 );
264
265 const error = yield* runWith(spawner)({
266 command: "fake",
267 args: ["spam-stdout"],
268 maxOutputBytes: 128,
269 timeout: "2 seconds",
270 }).pipe(Effect.flip);
271
272 expect(error).toBeInstanceOf(ProcessRunner.ProcessOutputLimitError);
273 }),
274 );
275
276 it.effect("truncates output when outputMode is truncate", () =>
277 Effect.gen(function* () {
278 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
279
280 const result = yield* runWith(spawner)({
281 command: "fake",
282 args: ["stdout-bytes", "2048"],
283 maxOutputBytes: 128,
284 outputMode: "truncate",
285 });
286
287 expect(result.code).toBe(0);
288 expect(result.stdout.length).toBeLessThanOrEqual(128);
289 expect(result.stdoutTruncated).toBe(true);
290 expect(result.stderrTruncated).toBe(false);
291 }),
292 );
293
294 it.effect("writes stdin before waiting for exit", () =>
295 Effect.gen(function* () {
296 const stdinWritten = yield* Deferred.make<void>();
297 const decoder = new TextDecoder();
298 const spawner = makeSpawner(() =>
299 Effect.succeed(
300 makeHandle({
301 stdout: "stdin payload",
302 stdin: Sink.forEach((chunk: Uint8Array) => {
303 const text = decoder.decode(chunk, { stream: true });
304 return text.includes("stdin payload")
305 ? Deferred.succeed(stdinWritten, undefined)
306 : Effect.void;
307 }),
308 exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
309 }),
310 ),
311 );
312
313 const result = yield* runWith(spawner)({
314 command: "fake",
315 args: ["stdin-echo"],
316 stdin: "stdin payload",
317 });
318
319 expect(result.stdout).toBe("stdin payload");
320 expect(result.code).toBe(0);
321 }),
322 );
323
324 it.effect("returns output for non-zero exit codes", () =>
325 Effect.gen(function* () {
326 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stderr: "boom", code: 2 })));
327
328 const result = yield* runWith(spawner)({
329 command: "fake",
330 args: ["stderr-exit", "boom", "2"],
331 });
332
333 expect(result.code).toBe(2);
334 expect(result.stderr).toBe("boom");
335 }),
336 );
337
338 it.effect("fails on timeout", () =>
339 Effect.gen(function* () {
340 const spawner = makeSpawner(() =>
341 Effect.succeed(
342 makeHandle({
343 exitCode: Effect.never,
344 }),
345 ),
346 );
347 const errorFiber = yield* runWith(spawner)({
348 command: "fake",
349 args: ["sleep"],
350 cwd: "/logical",
351 spawnCwd: "/actual",
352 timeout: "50 millis",
353 }).pipe(Effect.flip, Effect.forkScoped);
354
355 yield* Effect.yieldNow;
356 yield* TestClock.adjust(Duration.millis(50));
357 const error = yield* Fiber.join(errorFiber);
358
359 expect(error._tag).toBe("ProcessTimeoutError");
360 if (error._tag !== "ProcessTimeoutError") {
361 return expect.fail("Expected ProcessTimeoutError");
362 }
363 expect(error).toMatchObject({
364 command: "fake",
365 argumentCount: 1,
366 cwd: "/logical",
367 spawnCwd: "/actual",
368 timeoutMs: 50,
369 });
370 expect(error.message).toBe("Process 'fake' in '/actual' timed out after 50ms");
371 }),
372 );
373
374 it.effect("returns a synthetic timed out result when timeoutBehavior is timedOutResult", () =>
375 Effect.gen(function* () {
376 const spawner = makeSpawner(() =>
377 Effect.succeed(
378 makeHandle({
379 exitCode: Effect.never,
380 }),
381 ),
382 );
383 const resultFiber = yield* runWith(spawner)({
384 command: "fake",
385 args: ["sleep"],
386 timeout: "50 millis",
387 timeoutBehavior: "timedOutResult",
388 }).pipe(Effect.forkScoped);
389
390 yield* Effect.yieldNow;
391 yield* TestClock.adjust(Duration.millis(50));
392 const result = yield* Fiber.join(resultFiber);
393
394 expect(result).toMatchObject({
395 stdout: "",
396 stderr: "",
397 code: null,
398 timedOut: true,
399 stdoutTruncated: false,
400 stderrTruncated: false,
401 });
402 }),
403 );
404});
405
406describe("isWindowsCommandNotFound", () => {
407 it.effect("matches the localized German cmd.exe error text", () =>
408 Effect.gen(function* () {
409 const isCommandNotFound = yield* ProcessRunner.isWindowsCommandNotFound(
410 1,
411 "wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
412 ).pipe(Effect.provideService(HostProcess.Platform, "win32"));
413 expect(isCommandNotFound).toBe(true);
414 }),
415 );
416});
417
418describe("commandName", () => {
419 it("drops the directory from POSIX and Windows paths", () => {
420 expect(ProcessRunner.commandName("/Users/me/.local/bin/claude")).toBe("claude");
421 expect(ProcessRunner.commandName("C:\\Program Files\\nodejs\\npx.cmd")).toBe("npx.cmd");
422 expect(ProcessRunner.commandName("git")).toBe("git");
423 });
424});