vitecompose 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,670 @@
1
+ import { spawn } from "node:child_process";
2
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
3
+ // src/core/process.ts
4
+ const KILL_GRACE_MS = 2e3;
5
+ const ownedChildren = /* @__PURE__ */ new Set();
6
+ let exitHookInstalled = false;
7
+ const track = (child) => {
8
+ if (!exitHookInstalled) {
9
+ exitHookInstalled = true;
10
+ process.on("exit", () => killOwnedChildren("SIGKILL"));
11
+ }
12
+ ownedChildren.add(child);
13
+ child.once("close", () => ownedChildren.delete(child));
14
+ };
15
+ /** Ends every child this process started and has not yet seen exit. Safe to call from a signal handler. */
16
+ const killOwnedChildren = (signal = "SIGTERM") => {
17
+ for (const child of ownedChildren) child.kill(signal);
18
+ };
19
+ const describeCommand = (command, args, isPrivate) => isPrivate ? `${command} (private command)` : [command, ...args].join(" ");
20
+ var CommandStartError = class extends Error {
21
+ name = "CommandStartError";
22
+ constructor(command, args, cause, isPrivate) {
23
+ super(`Could not start ${describeCommand(command, args, isPrivate)}: ${isPrivate ? "start failed" : cause.message}`, { cause: isPrivate ? void 0 : cause });
24
+ }
25
+ };
26
+ var CommandTimeoutError = class extends Error {
27
+ name = "CommandTimeoutError";
28
+ constructor(command, args, timeoutMs, isPrivate) {
29
+ super(`Command timed out after ${timeoutMs}ms: ${describeCommand(command, args, isPrivate)}`);
30
+ }
31
+ };
32
+ var CommandCanceledError = class extends Error {
33
+ name = "CommandCanceledError";
34
+ constructor(command, args, isPrivate) {
35
+ super(`Command canceled: ${describeCommand(command, args, isPrivate)}`);
36
+ }
37
+ };
38
+ var CommandFailedError = class extends Error {
39
+ name = "CommandFailedError";
40
+ status;
41
+ /** Absent for private commands, because the output could contain what they protect. */
42
+ result;
43
+ constructor(command, args, result, isPrivate) {
44
+ const reason = result.status === null ? `signal ${result.signal}` : `status ${result.status}`;
45
+ const output = isPrivate ? "" : `${result.stdout}\n${result.stderr}`.trim();
46
+ super(`Command failed with ${reason}: ${describeCommand(command, args, isPrivate)}${output ? `\n${output}` : ""}`);
47
+ this.status = result.status;
48
+ this.result = isPrivate ? void 0 : result;
49
+ }
50
+ };
51
+ /**
52
+ * Runs a command without blocking the event loop, so Vitest timeouts can still fire.
53
+ * A nonzero exit is a result, not an error. Failure to start, timeouts and cancellation reject.
54
+ */
55
+ const run = (command, args, options) => {
56
+ const { promise, resolve, reject } = Promise.withResolvers();
57
+ const isPrivate = options.private;
58
+ if (options.signal?.aborted) {
59
+ reject(new CommandCanceledError(command, args, isPrivate));
60
+ return promise;
61
+ }
62
+ const child = spawn(command, args, {
63
+ cwd: options.cwd,
64
+ env: options.env ?? process.env,
65
+ stdio: [
66
+ "pipe",
67
+ "pipe",
68
+ "pipe"
69
+ ]
70
+ });
71
+ track(child);
72
+ const stdoutChunks = [];
73
+ const stderrChunks = [];
74
+ child.stdout.on("data", (chunk) => stdoutChunks.push(chunk));
75
+ child.stderr.on("data", (chunk) => stderrChunks.push(chunk));
76
+ let ending;
77
+ let killTimer;
78
+ const end = (reason) => {
79
+ ending ??= reason;
80
+ child.kill("SIGTERM");
81
+ killTimer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
82
+ };
83
+ const timeoutTimer = setTimeout(() => end("timeout"), options.timeoutMs);
84
+ const onAbort = () => end("canceled");
85
+ options.signal?.addEventListener("abort", onAbort, { once: true });
86
+ const finish = () => {
87
+ clearTimeout(timeoutTimer);
88
+ clearTimeout(killTimer);
89
+ options.signal?.removeEventListener("abort", onAbort);
90
+ };
91
+ child.once("error", (error) => {
92
+ finish();
93
+ reject(new CommandStartError(command, args, error, isPrivate));
94
+ });
95
+ child.once("close", (status, signal) => {
96
+ finish();
97
+ if (ending === "timeout") {
98
+ reject(new CommandTimeoutError(command, args, options.timeoutMs, isPrivate));
99
+ return;
100
+ }
101
+ if (ending === "canceled") {
102
+ reject(new CommandCanceledError(command, args, isPrivate));
103
+ return;
104
+ }
105
+ const stdoutBytes = Buffer.concat(stdoutChunks);
106
+ const stderrBytes = Buffer.concat(stderrChunks);
107
+ resolve({
108
+ status,
109
+ signal,
110
+ stdout: stdoutBytes.toString("utf8"),
111
+ stderr: stderrBytes.toString("utf8"),
112
+ stdoutBytes,
113
+ stderrBytes
114
+ });
115
+ });
116
+ child.stdin.on("error", () => {});
117
+ child.stdin.end(options.input);
118
+ return promise;
119
+ };
120
+ /** Like `run`, but any exit other than status 0 rejects with `CommandFailedError`. */
121
+ const runChecked = async (command, args, options) => {
122
+ const result = await run(command, args, options);
123
+ if (result.status !== 0) throw new CommandFailedError(command, args, result, options.private);
124
+ return result;
125
+ };
126
+ /** Starts a long-lived child that this process owns. It is ended on process exit if not stopped first. */
127
+ const startBackground = (command, args, options = {}) => {
128
+ const child = spawn(command, args, {
129
+ env: options.env ?? process.env,
130
+ stdio: [
131
+ "ignore",
132
+ "pipe",
133
+ "pipe"
134
+ ]
135
+ });
136
+ track(child);
137
+ const { promise: exited, resolve } = Promise.withResolvers();
138
+ let running = true;
139
+ const markExited = () => {
140
+ running = false;
141
+ resolve();
142
+ };
143
+ child.once("close", markExited);
144
+ child.once("error", markExited);
145
+ return {
146
+ child,
147
+ exited,
148
+ isRunning: () => running,
149
+ stop: async () => {
150
+ if (!running) return;
151
+ child.kill("SIGTERM");
152
+ const killTimer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
153
+ await exited;
154
+ clearTimeout(killTimer);
155
+ }
156
+ };
157
+ };
158
+ // src/core/wait.ts
159
+ var WaitTimeoutError = class extends Error {
160
+ name = "WaitTimeoutError";
161
+ lastState;
162
+ constructor(what, timeoutMs, lastState) {
163
+ const state = lastState === void 0 ? "" : ` Last state: ${JSON.stringify(lastState)}`;
164
+ super(`Timed out after ${timeoutMs}ms waiting for ${what}.${state}`);
165
+ this.lastState = lastState;
166
+ }
167
+ };
168
+ /**
169
+ * Polls `read` until `predicate` accepts the value, and returns that value.
170
+ * An error from `read` or `predicate` ends the wait: broken access must not look like "not ready yet",
171
+ * and a predicate can throw to report a terminal failure immediately.
172
+ */
173
+ const waitFor = async (read, predicate, options) => {
174
+ const deadline = Date.now() + options.timeoutMs;
175
+ const intervalMs = options.intervalMs ?? 1e3;
176
+ while (true) {
177
+ options.signal?.throwIfAborted();
178
+ const value = await read();
179
+ if (predicate(value)) return value;
180
+ if (Date.now() + intervalMs > deadline) throw new WaitTimeoutError(options.describe, options.timeoutMs, options.summarize?.(value));
181
+ await setTimeout$1(intervalMs, void 0, { signal: options.signal });
182
+ }
183
+ };
184
+ // src/core/compose.ts
185
+ const DEFAULT_CMD_TIMEOUT_MS = 6e4;
186
+ const DEFAULT_UP_TIMEOUT_MS = 18e4;
187
+ const DEFAULT_WAIT_TIMEOUT_MS = 12e4;
188
+ const KNOWN_STATES = /* @__PURE__ */ new Set([
189
+ "created",
190
+ "running",
191
+ "paused",
192
+ "restarting",
193
+ "removing",
194
+ "exited",
195
+ "dead",
196
+ "unknown"
197
+ ]);
198
+ const KNOWN_HEALTH = /* @__PURE__ */ new Set([
199
+ "starting",
200
+ "healthy",
201
+ "unhealthy",
202
+ "none",
203
+ ""
204
+ ]);
205
+ const asString = (value) => typeof value === "string" ? value : "";
206
+ const asNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
207
+ const normalizeState = (raw) => {
208
+ const lowered = asString(raw).toLowerCase();
209
+ return KNOWN_STATES.has(lowered) ? lowered : "unknown";
210
+ };
211
+ const normalizeHealth = (raw) => {
212
+ const lowered = asString(raw).toLowerCase();
213
+ return KNOWN_HEALTH.has(lowered) ? lowered : "";
214
+ };
215
+ const parseContainerRecord = (raw) => {
216
+ if (!raw || typeof raw !== "object") return null;
217
+ const record = raw;
218
+ const id = asString(record.ID ?? record.Id ?? record.id);
219
+ const name = asString(record.Name ?? record.name);
220
+ const service = asString(record.Service ?? record.service);
221
+ if (!id && !name && !service) return null;
222
+ const publishers = (Array.isArray(record.Publishers) ? record.Publishers : []).filter((entry) => Boolean(entry && typeof entry === "object")).map((entry) => ({
223
+ url: asString(entry.URL ?? entry.url),
224
+ targetPort: asNumber(entry.TargetPort ?? entry.targetPort),
225
+ publishedPort: asNumber(entry.PublishedPort ?? entry.publishedPort),
226
+ protocol: asString(entry.Protocol ?? entry.protocol) || "tcp"
227
+ }));
228
+ return {
229
+ id,
230
+ name,
231
+ service,
232
+ state: normalizeState(record.State ?? record.state),
233
+ status: asString(record.Status ?? record.status),
234
+ health: normalizeHealth(record.Health ?? record.health),
235
+ exitCode: asNumber(record.ExitCode ?? record.exitCode),
236
+ publishers
237
+ };
238
+ };
239
+ /**
240
+ * Parses `docker compose ps --format json`, which emits either NDJSON (one JSON object per line)
241
+ * or a single JSON array depending on the Docker Compose version.
242
+ */
243
+ const parseComposePsJson = (stdout) => {
244
+ const trimmed = stdout.trim();
245
+ if (!trimmed) return [];
246
+ if (trimmed.startsWith("[")) {
247
+ const parsed = JSON.parse(trimmed);
248
+ if (!Array.isArray(parsed)) return [];
249
+ return parsed.map(parseContainerRecord).filter((entry) => entry !== null);
250
+ }
251
+ return trimmed.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => parseContainerRecord(JSON.parse(line))).filter((entry) => entry !== null);
252
+ };
253
+ /**
254
+ * Parses `docker compose port <service> <port>` output (for example `0.0.0.0:54321` or `[::]:54321`).
255
+ * Wildcard bind addresses are normalized to `127.0.0.1` so HTTP clients and DB drivers can connect directly.
256
+ */
257
+ const parseComposePort = (stdout) => {
258
+ const lines = stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
259
+ if (lines.length === 0) throw new Error("docker compose port returned no host binding");
260
+ const chosen = lines.find((line) => !line.startsWith("[") && !line.startsWith("::")) ?? lines[0];
261
+ const lastColon = chosen.lastIndexOf(":");
262
+ if (lastColon < 0) throw new Error(`Unexpected docker compose port output: "${chosen}"`);
263
+ const rawHost = chosen.slice(0, lastColon).replace(/^\[|\]$/g, "");
264
+ const port = Number.parseInt(chosen.slice(lastColon + 1), 10);
265
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) throw new Error(`Invalid port in docker compose port output: "${chosen}"`);
266
+ return {
267
+ host: rawHost === "" || rawHost === "0.0.0.0" || rawHost === "::" || rawHost === "*" ? "127.0.0.1" : rawHost,
268
+ port
269
+ };
270
+ };
271
+ /** Safe summary for timeout errors and failure evidence — never includes container env vars. */
272
+ const summarizeContainer = (container) => {
273
+ if (!container) return null;
274
+ return {
275
+ name: container.name,
276
+ service: container.service,
277
+ state: container.state,
278
+ status: container.status,
279
+ ...container.health ? { health: container.health } : {},
280
+ ...container.state === "exited" ? { exitCode: container.exitCode } : {}
281
+ };
282
+ };
283
+ const composeBaseArgs = (target, profiles) => {
284
+ const args = [
285
+ "compose",
286
+ "--project-name",
287
+ target.projectName
288
+ ];
289
+ for (const file of target.composeFiles) args.push("--file", file);
290
+ if (target.envFile) args.push("--env-file", target.envFile);
291
+ for (const profile of profiles ?? []) args.push("--profile", profile);
292
+ return args;
293
+ };
294
+ const toServiceList = (services) => typeof services === "string" ? [services] : [...services];
295
+ const matchesPattern = (text, pattern) => typeof pattern === "string" ? text.includes(pattern) : pattern.test(text);
296
+ const createComposeClient = (target, options = {}) => {
297
+ const rootDir = options.rootDir ?? target.cwd;
298
+ const execCompose = (subArgs, opts = {}) => runChecked("docker", [...composeBaseArgs(target, opts.profiles), ...subArgs], {
299
+ cwd: target.cwd,
300
+ env: opts.env,
301
+ input: opts.input,
302
+ private: opts.private,
303
+ timeoutMs: opts.timeoutMs ?? DEFAULT_CMD_TIMEOUT_MS,
304
+ signal: opts.ignoreSignal ? void 0 : options.signal
305
+ });
306
+ const ps = async (psOptions = {}) => {
307
+ const args = [
308
+ "ps",
309
+ "--format",
310
+ "json"
311
+ ];
312
+ if (psOptions.all !== false) args.push("--all");
313
+ for (const service of psOptions.services ?? []) args.push(service);
314
+ const { stdout } = await execCompose(args, { profiles: psOptions.profiles });
315
+ return parseComposePsJson(stdout);
316
+ };
317
+ const inspect = async (service) => {
318
+ const containers = await ps({
319
+ services: [service],
320
+ all: true
321
+ });
322
+ return containers.find((container) => container.service === service) ?? containers[0] ?? null;
323
+ };
324
+ const port = async (service, containerPort, portOptions = {}) => {
325
+ const args = ["port"];
326
+ if (portOptions.protocol) args.push("--protocol", portOptions.protocol);
327
+ if (portOptions.index !== void 0) args.push("--index", String(portOptions.index));
328
+ args.push(service, String(containerPort));
329
+ const { stdout } = await execCompose(args);
330
+ return parseComposePort(stdout);
331
+ };
332
+ const url = async (service, containerPort, urlOptions = {}) => {
333
+ const binding = await port(service, containerPort, { index: urlOptions.index });
334
+ const protocol = urlOptions.protocol ?? "http";
335
+ const rawPath = urlOptions.path ?? "";
336
+ const path = rawPath === "" ? "" : rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
337
+ return `${protocol}://${binding.host}:${binding.port}${path}`;
338
+ };
339
+ const waitForRunning = async (service, waitOptions = {}) => {
340
+ return await waitFor(() => inspect(service), (current) => {
341
+ if (!current) return false;
342
+ if (current.state === "exited" || current.state === "dead") throw new Error(`Service "${service}" terminated while waiting to run (state=${current.state}, exitCode=${current.exitCode}, status=${current.status})`);
343
+ return current.state === "running";
344
+ }, {
345
+ timeoutMs: waitOptions.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS,
346
+ intervalMs: waitOptions.intervalMs ?? 500,
347
+ signal: waitOptions.signal ?? options.signal,
348
+ describe: `service "${service}" to be running`,
349
+ summarize: summarizeContainer
350
+ });
351
+ };
352
+ const waitForHealthy = async (service, waitOptions = {}) => {
353
+ return await waitFor(() => inspect(service), (current) => {
354
+ if (!current) return false;
355
+ if (current.state === "exited" || current.state === "dead") throw new Error(`Service "${service}" terminated while waiting for health (state=${current.state}, exitCode=${current.exitCode}, status=${current.status})`);
356
+ if (current.health === "unhealthy") throw new Error(`Service "${service}" became unhealthy (status=${current.status})`);
357
+ if (current.state !== "running") return false;
358
+ return current.health === "healthy" || current.health === "" || current.health === "none";
359
+ }, {
360
+ timeoutMs: waitOptions.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS,
361
+ intervalMs: waitOptions.intervalMs ?? 500,
362
+ signal: waitOptions.signal ?? options.signal,
363
+ describe: `service "${service}" to become healthy`,
364
+ summarize: summarizeContainer
365
+ });
366
+ };
367
+ const waitForStopped = async (service, waitOptions = {}) => waitFor(() => inspect(service), (current) => current === null || current.state !== "running" && current.state !== "restarting", {
368
+ timeoutMs: waitOptions.timeoutMs ?? DEFAULT_CMD_TIMEOUT_MS,
369
+ intervalMs: waitOptions.intervalMs ?? 250,
370
+ signal: waitOptions.signal ?? options.signal,
371
+ describe: `service "${service}" to stop`,
372
+ summarize: summarizeContainer
373
+ });
374
+ const waitForExit = async (service, waitOptions = {}) => {
375
+ return await waitFor(() => inspect(service), (current) => current !== null && current.state === "exited", {
376
+ timeoutMs: waitOptions.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS,
377
+ intervalMs: waitOptions.intervalMs ?? 500,
378
+ signal: waitOptions.signal ?? options.signal,
379
+ describe: `service "${service}" to exit`,
380
+ summarize: summarizeContainer
381
+ });
382
+ };
383
+ const logs = async (service, logsOptions = {}) => {
384
+ const args = [
385
+ "logs",
386
+ "--no-color",
387
+ "--no-log-prefix"
388
+ ];
389
+ if (logsOptions.tailLines !== void 0) args.push("--tail", String(logsOptions.tailLines));
390
+ if (logsOptions.since) args.push("--since", logsOptions.since);
391
+ if (logsOptions.timestamps) args.push("--timestamps");
392
+ args.push(service);
393
+ const { stdout, stderr } = await execCompose(args, { timeoutMs: logsOptions.timeoutMs });
394
+ return [stdout, stderr].filter((part) => part.length > 0).join("\n");
395
+ };
396
+ const waitForLogs = async (service, patterns, waitOptions = {}) => {
397
+ const required = Array.isArray(patterns) ? patterns : [patterns];
398
+ return waitFor(() => logs(service, { tailLines: waitOptions.tailLines ?? 500 }), (text) => required.every((pattern) => matchesPattern(text, pattern)), {
399
+ timeoutMs: waitOptions.timeoutMs ?? DEFAULT_CMD_TIMEOUT_MS,
400
+ intervalMs: waitOptions.intervalMs ?? 500,
401
+ signal: waitOptions.signal ?? options.signal,
402
+ describe: `logs of "${service}" matching ${required.map(String).join(", ")}`,
403
+ summarize: (text) => ({ tail: text.slice(-400) })
404
+ });
405
+ };
406
+ const waitForHttp = async (service, containerPort, waitOptions = {}) => {
407
+ const endpoint = await url(service, containerPort, {
408
+ protocol: waitOptions.protocol,
409
+ path: waitOptions.path
410
+ });
411
+ const checkStatus = typeof waitOptions.expectedStatus === "function" ? waitOptions.expectedStatus : waitOptions.expectedStatus !== void 0 ? (status) => status === waitOptions.expectedStatus : (status) => status >= 200 && status < 300;
412
+ await waitFor(async () => {
413
+ try {
414
+ const response = await fetch(endpoint, { signal: waitOptions.signal ?? options.signal });
415
+ return {
416
+ ok: checkStatus(response.status),
417
+ status: response.status
418
+ };
419
+ } catch (error) {
420
+ return {
421
+ ok: false,
422
+ error: error instanceof Error ? error.message : String(error)
423
+ };
424
+ }
425
+ }, (result) => result.ok, {
426
+ timeoutMs: waitOptions.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS,
427
+ intervalMs: waitOptions.intervalMs ?? 500,
428
+ signal: waitOptions.signal ?? options.signal,
429
+ describe: `HTTP ready at ${endpoint}`,
430
+ summarize: (result) => result
431
+ });
432
+ return endpoint;
433
+ };
434
+ const stopTemporarily = async (service, outageOptions = {}) => {
435
+ const actionTimeoutMs = outageOptions.timeoutMs ?? DEFAULT_CMD_TIMEOUT_MS;
436
+ const restoreTimeoutMs = outageOptions.restoreTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
437
+ const waitMode = outageOptions.waitForRestore ?? "healthy";
438
+ let restored = false;
439
+ const restore = async () => {
440
+ if (restored) return;
441
+ restored = true;
442
+ try {
443
+ await execCompose(["start", service], {
444
+ timeoutMs: actionTimeoutMs,
445
+ ignoreSignal: true
446
+ });
447
+ if (!await inspect(service)) throw new Error(`Service "${service}" has no container to start`);
448
+ if (waitMode === "healthy") await waitForHealthy(service, {
449
+ timeoutMs: restoreTimeoutMs,
450
+ signal: void 0
451
+ });
452
+ else if (waitMode === "running") await waitForRunning(service, {
453
+ timeoutMs: restoreTimeoutMs,
454
+ signal: void 0
455
+ });
456
+ } catch (error) {
457
+ await options.onEnvironmentDamaged?.(`could not restore service "${service}" after stopTemporarily: ${String(error)}`);
458
+ throw error;
459
+ }
460
+ };
461
+ try {
462
+ if (outageOptions.kill) {
463
+ const args = ["kill"];
464
+ if (outageOptions.signal) args.push("--signal", outageOptions.signal);
465
+ args.push(service);
466
+ await execCompose(args, { timeoutMs: actionTimeoutMs });
467
+ } else await execCompose(["stop", service], { timeoutMs: actionTimeoutMs });
468
+ await waitForStopped(service, { timeoutMs: actionTimeoutMs });
469
+ } catch (error) {
470
+ await restore().catch(() => {});
471
+ throw error;
472
+ }
473
+ return {
474
+ restore,
475
+ [Symbol.asyncDispose]: restore
476
+ };
477
+ };
478
+ const pauseTemporarily = async (service, outageOptions = {}) => {
479
+ const actionTimeoutMs = outageOptions.timeoutMs ?? DEFAULT_CMD_TIMEOUT_MS;
480
+ const restoreTimeoutMs = outageOptions.restoreTimeoutMs ?? DEFAULT_CMD_TIMEOUT_MS;
481
+ let restored = false;
482
+ const restore = async () => {
483
+ if (restored) return;
484
+ restored = true;
485
+ try {
486
+ await execCompose(["unpause", service], {
487
+ timeoutMs: restoreTimeoutMs,
488
+ ignoreSignal: true
489
+ });
490
+ await waitForRunning(service, {
491
+ timeoutMs: restoreTimeoutMs,
492
+ signal: void 0
493
+ });
494
+ } catch (error) {
495
+ await options.onEnvironmentDamaged?.(`could not unpause service "${service}" after pauseTemporarily: ${String(error)}`);
496
+ throw error;
497
+ }
498
+ };
499
+ try {
500
+ await execCompose(["pause", service], { timeoutMs: actionTimeoutMs });
501
+ } catch (error) {
502
+ await restore().catch(() => {});
503
+ throw error;
504
+ }
505
+ return {
506
+ restore,
507
+ [Symbol.asyncDispose]: restore
508
+ };
509
+ };
510
+ return {
511
+ target,
512
+ rootDir,
513
+ up: async (upOptions = {}) => {
514
+ const args = ["up", "-d"];
515
+ if (upOptions.build) args.push("--build");
516
+ if (upOptions.forceRecreate) args.push("--force-recreate");
517
+ if (upOptions.noDeps) args.push("--no-deps");
518
+ if (upOptions.wait) args.push("--wait");
519
+ for (const service of upOptions.services ?? []) args.push(service);
520
+ await execCompose(args, {
521
+ profiles: upOptions.profiles,
522
+ timeoutMs: upOptions.timeoutMs ?? DEFAULT_UP_TIMEOUT_MS,
523
+ env: upOptions.env
524
+ });
525
+ },
526
+ down: async (downOptions = {}) => {
527
+ const args = ["down"];
528
+ if (downOptions.volumes) args.push("--volumes");
529
+ if (downOptions.removeOrphans) args.push("--remove-orphans");
530
+ await execCompose(args, {
531
+ profiles: downOptions.profiles,
532
+ timeoutMs: downOptions.timeoutMs ?? DEFAULT_UP_TIMEOUT_MS,
533
+ ignoreSignal: true
534
+ });
535
+ },
536
+ ps,
537
+ inspect,
538
+ port,
539
+ url,
540
+ exec: async (service, command, execOptions = {}) => {
541
+ const args = ["exec", "-T"];
542
+ if (execOptions.user) args.push("--user", execOptions.user);
543
+ if (execOptions.workdir) args.push("--workdir", execOptions.workdir);
544
+ for (const [key, value] of Object.entries(execOptions.env ?? {})) args.push("--env", `${key}=${value}`);
545
+ args.push(service, ...command);
546
+ return run("docker", [...composeBaseArgs(target), ...args], {
547
+ cwd: target.cwd,
548
+ input: execOptions.input,
549
+ private: execOptions.private,
550
+ timeoutMs: execOptions.timeoutMs ?? DEFAULT_CMD_TIMEOUT_MS,
551
+ signal: options.signal
552
+ });
553
+ },
554
+ run: async (service, command = [], runOptions = {}) => {
555
+ const args = ["run", "-T"];
556
+ if (runOptions.rm !== false) args.push("--rm");
557
+ if (runOptions.noDeps) args.push("--no-deps");
558
+ if (runOptions.user) args.push("--user", runOptions.user);
559
+ if (runOptions.workdir) args.push("--workdir", runOptions.workdir);
560
+ for (const [key, value] of Object.entries(runOptions.env ?? {})) args.push("--env", `${key}=${value}`);
561
+ args.push(service, ...command);
562
+ return run("docker", [...composeBaseArgs(target), ...args], {
563
+ cwd: target.cwd,
564
+ input: runOptions.input,
565
+ private: runOptions.private,
566
+ timeoutMs: runOptions.timeoutMs ?? DEFAULT_UP_TIMEOUT_MS,
567
+ signal: options.signal
568
+ });
569
+ },
570
+ logs,
571
+ start: async (services, opts = {}) => {
572
+ await execCompose(["start", ...toServiceList(services)], { timeoutMs: opts.timeoutMs });
573
+ },
574
+ stop: async (services, opts = {}) => {
575
+ await execCompose(["stop", ...toServiceList(services)], { timeoutMs: opts.timeoutMs });
576
+ },
577
+ kill: async (services, opts = {}) => {
578
+ const args = ["kill"];
579
+ if (opts.signal) args.push("--signal", opts.signal);
580
+ args.push(...toServiceList(services));
581
+ await execCompose(args, { timeoutMs: opts.timeoutMs });
582
+ },
583
+ restart: async (services, opts = {}) => {
584
+ await execCompose(["restart", ...toServiceList(services)], { timeoutMs: opts.timeoutMs });
585
+ },
586
+ pause: async (services, opts = {}) => {
587
+ await execCompose(["pause", ...toServiceList(services)], { timeoutMs: opts.timeoutMs });
588
+ },
589
+ unpause: async (services, opts = {}) => {
590
+ await execCompose(["unpause", ...toServiceList(services)], { timeoutMs: opts.timeoutMs });
591
+ },
592
+ waitForRunning,
593
+ waitForHealthy,
594
+ waitForStopped,
595
+ waitForExit,
596
+ waitForLogs,
597
+ waitForHttp,
598
+ stopTemporarily,
599
+ pauseTemporarily
600
+ };
601
+ };
602
+ // src/core/scope.ts
603
+ var DisposalError = class extends AggregateError {
604
+ name = "DisposalError";
605
+ constructor(errors) {
606
+ const details = errors.map((error) => error instanceof Error ? error.message : String(error));
607
+ super(errors, `${errors.length} cleanup(s) failed: ${details.join("; ")}`);
608
+ }
609
+ };
610
+ const DEFAULT_CLEANUP_TIMEOUT_MS = 6e4;
611
+ const bounded = async (cleanup, label, timeoutMs) => {
612
+ const { promise: expired, reject } = Promise.withResolvers();
613
+ const timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Cleanup "${label}" timed out after ${timeoutMs}ms`)), timeoutMs);
614
+ try {
615
+ await Promise.race([Promise.resolve().then(cleanup), expired]);
616
+ } finally {
617
+ clearTimeout(timer);
618
+ }
619
+ };
620
+ /**
621
+ * Vitest does not time out fixture teardown, so each cleanup carries its own limit.
622
+ * A hung cleanup is reported and the remaining ones still run.
623
+ */
624
+ const createScope = (options = {}) => {
625
+ const cleanups = [];
626
+ let disposal;
627
+ const dispose = () => {
628
+ disposal ??= (async () => {
629
+ const errors = [];
630
+ for (const { cleanup, label, timeoutMs } of cleanups.reverse()) try {
631
+ await bounded(cleanup, label, timeoutMs);
632
+ } catch (error) {
633
+ errors.push(error);
634
+ }
635
+ if (errors.length > 0) throw new DisposalError(errors);
636
+ })();
637
+ return disposal;
638
+ };
639
+ return {
640
+ defer: (cleanup, deferOptions = {}) => {
641
+ if (disposal) throw new Error("Cannot defer a cleanup on a scope that is already disposed");
642
+ cleanups.push({
643
+ cleanup,
644
+ label: deferOptions.label ?? `cleanup ${cleanups.length + 1}`,
645
+ timeoutMs: deferOptions.timeoutMs ?? options.cleanupTimeoutMs ?? DEFAULT_CLEANUP_TIMEOUT_MS
646
+ });
647
+ },
648
+ dispose,
649
+ [Symbol.asyncDispose]: dispose
650
+ };
651
+ };
652
+ /**
653
+ * Runs `body` with a scope and always disposes it. If `body` fails, its error is the one thrown,
654
+ * and cleanup failures are logged. A failed cleanup must not replace the failure that explains the run.
655
+ */
656
+ const withScope = async (body, options) => {
657
+ const scope = createScope(options);
658
+ let result;
659
+ try {
660
+ result = await body(scope);
661
+ } catch (primary) {
662
+ await scope.dispose().catch((error) => {
663
+ console.error(`[vitecompose] cleanup also failed: ${String(error)}`);
664
+ });
665
+ throw primary;
666
+ }
667
+ await scope.dispose();
668
+ return result;
669
+ };
670
+ export { runChecked as _, createComposeClient as a, summarizeContainer as c, CommandCanceledError as d, CommandFailedError as f, run as g, killOwnedChildren as h, composeBaseArgs as i, WaitTimeoutError as l, CommandTimeoutError as m, createScope as n, parseComposePort as o, CommandStartError as p, withScope as r, parseComposePsJson as s, DisposalError as t, waitFor as u, startBackground as v };