@evandam93/dev-env 0.0.0-stage → 0.1.1

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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +282 -2
  3. package/bin/dev-env.js +3 -0
  4. package/dist/abandoned.d.ts +2 -0
  5. package/dist/abandoned.js +66 -0
  6. package/dist/affected/graph.d.ts +43 -0
  7. package/dist/affected/graph.js +222 -0
  8. package/dist/affected/index.d.ts +5 -0
  9. package/dist/affected/index.js +3 -0
  10. package/dist/affected/layout.d.ts +11 -0
  11. package/dist/affected/layout.js +34 -0
  12. package/dist/affected/run.d.ts +10 -0
  13. package/dist/affected/run.js +96 -0
  14. package/dist/affected/select.d.ts +27 -0
  15. package/dist/affected/select.js +79 -0
  16. package/dist/checkout.d.ts +13 -0
  17. package/dist/checkout.js +40 -0
  18. package/dist/cli.d.ts +1 -0
  19. package/dist/cli.js +98 -0
  20. package/dist/compose.d.ts +18 -0
  21. package/dist/compose.js +119 -0
  22. package/dist/environment.d.ts +33 -0
  23. package/dist/environment.js +387 -0
  24. package/dist/errors.d.ts +4 -0
  25. package/dist/errors.js +4 -0
  26. package/dist/index.d.ts +4 -0
  27. package/dist/index.js +2 -0
  28. package/dist/machine.d.ts +3 -0
  29. package/dist/machine.js +17 -0
  30. package/dist/manifest.d.ts +95 -0
  31. package/dist/manifest.js +91 -0
  32. package/dist/ports.d.ts +6 -0
  33. package/dist/ports.js +92 -0
  34. package/dist/processes.d.ts +13 -0
  35. package/dist/processes.js +116 -0
  36. package/dist/readiness.d.ts +6 -0
  37. package/dist/readiness.js +31 -0
  38. package/dist/shared.d.ts +9 -0
  39. package/dist/shared.js +81 -0
  40. package/dist/slots.d.ts +21 -0
  41. package/dist/slots.js +165 -0
  42. package/dist/state.d.ts +21 -0
  43. package/dist/state.js +36 -0
  44. package/dist/test-environment.d.ts +36 -0
  45. package/dist/test-environment.js +67 -0
  46. package/dist/workspace.d.ts +31 -0
  47. package/dist/workspace.js +140 -0
  48. package/package.json +75 -4
@@ -0,0 +1,11 @@
1
+ import type { Manifest } from '../manifest.ts';
2
+ import type { Layout } from './graph.ts';
3
+ export declare const TARGET_SHARED: readonly string[];
4
+ /**
5
+ * The layout of the target in `target`, inside the repository in
6
+ * `repository`: its processes and their sources from its manifest, the
7
+ * repository's workspace packages, and every path shared by all its specs,
8
+ * the target's own, the repository's and its package manager's, and those
9
+ * the manifest's `shared` adds.
10
+ */
11
+ export declare const layoutOf: (target: string, repository: string, manifest: Manifest) => Layout;
@@ -0,0 +1,34 @@
1
+ import { packageManagerOf, repositorySharedOf, workspacePackagesOf, } from '../workspace.js';
2
+ /*
3
+ * What every test environment of a target is built from without importing
4
+ * it: its manifest, its services, and the settings that compile and run its
5
+ * specs. A change to one runs every spec. Paths are relative to the target.
6
+ */
7
+ export const TARGET_SHARED = [
8
+ 'dev-env.ts',
9
+ 'compose.yaml',
10
+ 'compose.test.yaml',
11
+ 'package.json',
12
+ 'tsconfig.json',
13
+ // A target's shared compiler options, such as its import aliases.
14
+ 'tsconfig.*.json',
15
+ 'vitest.integration.ts',
16
+ ];
17
+ /**
18
+ * The layout of the target in `target`, inside the repository in
19
+ * `repository`: its processes and their sources from its manifest, the
20
+ * repository's workspace packages, and every path shared by all its specs,
21
+ * the target's own, the repository's and its package manager's, and those
22
+ * the manifest's `shared` adds.
23
+ */
24
+ export const layoutOf = (target, repository, manifest) => ({
25
+ target,
26
+ repository,
27
+ processes: new Map(Object.entries(manifest.services).flatMap(([name, service]) => service.kind === 'process' ? [[name, service.sources]] : [])),
28
+ packages: workspacePackagesOf(repository),
29
+ shared: [
30
+ ...TARGET_SHARED,
31
+ ...repositorySharedOf(packageManagerOf(repository)),
32
+ ...(manifest.shared ?? []),
33
+ ],
34
+ });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Runs the integration specs of `name` that the checkout's changes since
3
+ * `base` reach, saying which it chose and why, and returns Vitest's exit code.
4
+ * Without `base`, it compares with where the checkout left the remote's
5
+ * default branch. With `list`, it only says which it would run.
6
+ */
7
+ export declare const runAffected: (cwd: string, name: string, { base, list, }?: {
8
+ readonly base?: string;
9
+ readonly list?: boolean;
10
+ }) => Promise<number>;
@@ -0,0 +1,96 @@
1
+ import { execFileSync, spawnSync } from 'node:child_process';
2
+ import { relative } from 'node:path';
3
+ import { stdout } from 'node:process';
4
+ import { resolveCheckout } from '../checkout.js';
5
+ import { DevEnvError } from '../errors.js';
6
+ import { loadTarget } from '../manifest.js';
7
+ import { commandOf, packageManagerOf } from '../workspace.js';
8
+ import { graphOf, specsIn } from './graph.js';
9
+ import { layoutOf } from './layout.js';
10
+ import { forPullRequest, selectSpecs } from './select.js';
11
+ const git = (cwd, ...args) => execFileSync('git', args, {
12
+ cwd,
13
+ encoding: 'utf8',
14
+ stdio: ['ignore', 'pipe', 'pipe'],
15
+ })
16
+ .split('\n')
17
+ .filter((line) => line !== '');
18
+ const gitOrNothing = (cwd, ...args) => {
19
+ try {
20
+ return git(cwd, ...args)[0];
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ };
26
+ /*
27
+ * The remote's default branch, as `origin/HEAD` names it, or else
28
+ * `origin/main` or `origin/master`, whichever exists.
29
+ */
30
+ const defaultBranchOf = (root) => {
31
+ const head = gitOrNothing(root, 'rev-parse', '--abbrev-ref', '--verify', '--quiet', 'origin/HEAD');
32
+ if (head !== undefined && head !== 'origin/HEAD')
33
+ return head;
34
+ const found = ['origin/main', 'origin/master'].find((branch) => gitOrNothing(root, 'rev-parse', '--verify', '--quiet', branch) !==
35
+ undefined);
36
+ if (found === undefined)
37
+ throw new DevEnvError('No origin/HEAD, origin/main or origin/master to compare with. Pass the base with --base <ref>.');
38
+ return found;
39
+ };
40
+ /**
41
+ * Runs the integration specs of `name` that the checkout's changes since
42
+ * `base` reach, saying which it chose and why, and returns Vitest's exit code.
43
+ * Without `base`, it compares with where the checkout left the remote's
44
+ * default branch. With `list`, it only says which it would run.
45
+ */
46
+ export const runAffected = async (cwd, name, { base, list = false, } = {}) => {
47
+ const { root } = await resolveCheckout(cwd);
48
+ const target = await loadTarget(root, name);
49
+ const since = base ?? git(root, 'merge-base', 'HEAD', defaultBranchOf(root))[0] ?? '';
50
+ // Committed and uncommitted changes since the base, and files git does not track yet.
51
+ const changed = [
52
+ ...new Set([
53
+ ...git(root, 'diff', '--name-only', '--no-renames', since),
54
+ ...git(root, 'ls-files', '--others', '--exclude-standard'),
55
+ ]),
56
+ ];
57
+ const here = relative(root, target.directory);
58
+ const paths = changed.map((path) => path.startsWith(`${here}/`) ? path.slice(here.length + 1) : `/${path}`);
59
+ const print = (line) => stdout.write(`${line}\n`);
60
+ const layout = layoutOf(target.directory, root, target.manifest);
61
+ const selection = selectSpecs(graphOf(layout), paths);
62
+ print(`${name}: ${paths.length} paths changed since ${since.slice(0, 12)}.`);
63
+ if (selection.kind === 'everything') {
64
+ print('Every integration spec is affected, because:');
65
+ for (const reason of selection.because)
66
+ print(` ${reason}`);
67
+ }
68
+ const lists = target.manifest.specs ?? {};
69
+ const chosen = forPullRequest(selection, specsIn(layout), lists);
70
+ const left = (lists.beforeRelease ?? []).filter((spec) => selection.kind === 'everything' || selection.specs.has(spec));
71
+ if (left.length > 0)
72
+ print(`Left to the full suite before a release: ${left.join(', ')}.`);
73
+ if (chosen.size === 0) {
74
+ print('No change reaches an integration spec, so none runs.');
75
+ return 0;
76
+ }
77
+ print(`Running ${chosen.size} integration specs:`);
78
+ // With every spec affected, the reasons above are every spec's, so each lists only its own.
79
+ const own = (reasons) => selection.kind === 'everything'
80
+ ? reasons.filter((reason) => !selection.because.includes(reason))
81
+ : reasons;
82
+ for (const [spec, reasons] of chosen) {
83
+ print(` ${spec}`);
84
+ for (const reason of own(reasons))
85
+ print(` ${reason}`);
86
+ }
87
+ const files = [...chosen.keys()];
88
+ if (list)
89
+ return 0;
90
+ const [command = 'npm', ...args] = commandOf(packageManagerOf(root), 'vitest', ['run', '--config', 'vitest.integration.ts', ...files]);
91
+ const run = spawnSync(command, args, {
92
+ cwd: target.directory,
93
+ stdio: 'inherit',
94
+ });
95
+ return run.status ?? 1;
96
+ };
@@ -0,0 +1,27 @@
1
+ import { type Graph } from './graph.ts';
2
+ export type Selection = {
3
+ readonly kind: 'everything';
4
+ readonly because: readonly string[];
5
+ } | {
6
+ readonly kind: 'specs';
7
+ /** Each chosen spec, with the changed paths that chose it. */
8
+ readonly specs: ReadonlyMap<string, readonly string[]>;
9
+ };
10
+ export declare const matches: (glob: string, path: string) => boolean;
11
+ /**
12
+ * Chooses the integration specs that `changed` reaches in `graph`. A changed
13
+ * spec runs itself, a path the graph's `shared` globs match runs every spec,
14
+ * and a path no spec reaches runs nothing.
15
+ */
16
+ export declare const selectSpecs: (graph: Graph, changed: readonly string[]) => Selection;
17
+ /** Integration specs a pull request runs whatever it changes, and those it leaves to the full suite before a release. */
18
+ export interface SpecLists {
19
+ readonly always?: readonly string[];
20
+ readonly beforeRelease?: readonly string[];
21
+ }
22
+ /**
23
+ * The specs a pull request runs, each with why: those its changes reach, or
24
+ * every spec when they reach shared code, and every spec it always runs,
25
+ * less those only the full suite runs.
26
+ */
27
+ export declare const forPullRequest: (selection: Selection, allSpecs: readonly string[], { always, beforeRelease }: SpecLists) => ReadonlyMap<string, readonly string[]>;
@@ -0,0 +1,79 @@
1
+ import { isRuntime } from './graph.js';
2
+ const SPECIAL = /\*\*\/|\*\*|\*|[.+?^${}()|[\]\\]/g;
3
+ const patternOf = (glob) => new RegExp(`^${glob.replace(SPECIAL, (token) => {
4
+ if (token === '**/')
5
+ return '(?:.*/)?';
6
+ if (token === '**')
7
+ return '.*';
8
+ if (token === '*')
9
+ return '[^/]*';
10
+ return `\\${token}`;
11
+ })}$`);
12
+ export const matches = (glob, path) => patternOf(glob).test(path);
13
+ const describe = (path, route) => route.kind === 'imports'
14
+ ? `${path}, imported by the spec`
15
+ : `${path}, through ${route.process}`;
16
+ const routeTo = (reach, path) => {
17
+ const file = reach.files.get(path);
18
+ if (file !== undefined)
19
+ return file;
20
+ if (!isRuntime(path))
21
+ return undefined;
22
+ for (const [directory, route] of reach.directories)
23
+ if (path.startsWith(directory))
24
+ return route;
25
+ return undefined;
26
+ };
27
+ /**
28
+ * Chooses the integration specs that `changed` reaches in `graph`. A changed
29
+ * spec runs itself, a path the graph's `shared` globs match runs every spec,
30
+ * and a path no spec reaches runs nothing.
31
+ */
32
+ export const selectSpecs = (graph, changed) => {
33
+ const everything = [];
34
+ const chosen = new Map();
35
+ const choose = (spec, reason) => chosen.set(spec, [...(chosen.get(spec) ?? []), reason]);
36
+ for (const path of changed) {
37
+ // Tests, stories and docs run nowhere, even inside a shared directory.
38
+ if (!graph.specs.has(path) && !isRuntime(path))
39
+ continue;
40
+ const shared = graph.shared.find((glob) => matches(glob, path));
41
+ if (shared !== undefined) {
42
+ everything.push(`${path} is shared, as ${shared}`);
43
+ continue;
44
+ }
45
+ for (const [spec, reach] of graph.specs) {
46
+ if (path === spec) {
47
+ choose(spec, path);
48
+ continue;
49
+ }
50
+ const route = routeTo(reach, path);
51
+ if (route !== undefined)
52
+ choose(spec, describe(path, route));
53
+ }
54
+ }
55
+ if (everything.length > 0)
56
+ return { kind: 'everything', because: everything };
57
+ return {
58
+ kind: 'specs',
59
+ specs: new Map([...chosen].sort(([a], [b]) => a.localeCompare(b))),
60
+ };
61
+ };
62
+ /**
63
+ * The specs a pull request runs, each with why: those its changes reach, or
64
+ * every spec when they reach shared code, and every spec it always runs,
65
+ * less those only the full suite runs.
66
+ */
67
+ export const forPullRequest = (selection, allSpecs, { always = [], beforeRelease = [] }) => {
68
+ const chosen = new Map(selection.kind === 'everything'
69
+ ? allSpecs.map((spec) => [spec, selection.because])
70
+ : selection.specs);
71
+ for (const spec of always)
72
+ chosen.set(spec, [
73
+ ...(chosen.get(spec) ?? []),
74
+ 'every pull request runs it',
75
+ ]);
76
+ for (const spec of beforeRelease)
77
+ chosen.delete(spec);
78
+ return new Map([...chosen].sort(([a], [b]) => a.localeCompare(b)));
79
+ };
@@ -0,0 +1,13 @@
1
+ export type Mode = 'dev' | 'test' | `test-${number}`;
2
+ export declare const isTestMode: (mode: Mode) => boolean;
3
+ export declare const testModeOf: (lane: number) => Mode;
4
+ export interface Checkout {
5
+ readonly root: string;
6
+ readonly id: string;
7
+ readonly gitCommonDirectory: string;
8
+ }
9
+ export declare const environmentIdOf: (root: string) => string;
10
+ export declare const environmentKeyOf: (target: string, mode: Mode) => string;
11
+ export declare const composeProjectOf: (checkout: Pick<Checkout, 'root' | 'id'>, target: string, mode: Mode) => string;
12
+ export declare const resolveCheckout: (cwd: string) => Promise<Checkout>;
13
+ export declare const checkoutRootsOf: (checkout: Checkout) => Promise<readonly string[]>;
@@ -0,0 +1,40 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { realpath } from 'node:fs/promises';
4
+ import { basename } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { DevEnvError } from './errors.js';
7
+ const run = promisify(execFile);
8
+ export const isTestMode = (mode) => mode !== 'dev';
9
+ export const testModeOf = (lane) => lane === 1 ? 'test' : `test-${lane}`;
10
+ export const environmentIdOf = (root) => createHash('sha256').update(root).digest('hex').slice(0, 8);
11
+ export const environmentKeyOf = (target, mode) => mode === 'dev' ? target : `${target}.${mode}`;
12
+ export const composeProjectOf = (checkout, target, mode) => {
13
+ const name = basename(checkout.root)
14
+ .toLowerCase()
15
+ .replaceAll(/[^a-z0-9_-]/g, '-')
16
+ .replace(/^[^a-z0-9]+/, '');
17
+ const suffix = mode === 'dev' ? '' : `-${mode}`;
18
+ return `${name || 'checkout'}-${checkout.id}-${target}${suffix}`;
19
+ };
20
+ const git = async (cwd, ...args) => {
21
+ const { stdout } = await run('git', args, { cwd });
22
+ return stdout.trim();
23
+ };
24
+ export const resolveCheckout = async (cwd) => {
25
+ try {
26
+ const root = await realpath(await git(cwd, 'rev-parse', '--show-toplevel'));
27
+ const gitCommonDirectory = await git(cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir');
28
+ return { root, id: environmentIdOf(root), gitCommonDirectory };
29
+ }
30
+ catch {
31
+ throw new DevEnvError(`${cwd} is not inside a git checkout.`);
32
+ }
33
+ };
34
+ export const checkoutRootsOf = async (checkout) => {
35
+ const listing = await git(checkout.root, 'worktree', 'list', '--porcelain');
36
+ return listing
37
+ .split('\n')
38
+ .filter((line) => line.startsWith('worktree '))
39
+ .map((line) => line.slice('worktree '.length));
40
+ };
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,98 @@
1
+ import { stderr, stdout } from 'node:process';
2
+ import { isTestMode } from './checkout.js';
3
+ import { resetTestEnvironments } from './test-environment.js';
4
+ import { describeCheckout, resetTarget, startTarget, stopAll, stopTarget, } from './environment.js';
5
+ import { DevEnvError } from './errors.js';
6
+ import { runAffected } from './affected/run.js';
7
+ const USAGE = `Usage:
8
+ dev-env start <target>... [--test]
9
+ dev-env stop [target]... [--test]
10
+ dev-env info [--json]
11
+ dev-env reset <target>... [--test]
12
+ dev-env affected <target> [--base <ref>] [--list]
13
+ `;
14
+ const printEnvironment = (environment) => {
15
+ const suffix = isTestMode(environment.mode) ? ` (${environment.mode})` : '';
16
+ stdout.write(`${environment.target}${suffix}\n`);
17
+ for (const [name, service] of Object.entries(environment.services)) {
18
+ const status = service.running ? 'running' : 'stopped';
19
+ stdout.write(` ${name}: ${service.url ?? service.address} [${status}]\n`);
20
+ }
21
+ };
22
+ const printCheckout = (info) => {
23
+ stdout.write(`${info.checkout} (${info.environmentId})\n`);
24
+ stdout.write(`Available: ${info.available.join(', ') || 'none'}\n`);
25
+ info.environments.forEach(printEnvironment);
26
+ };
27
+ const requireTargets = (targets) => {
28
+ if (targets.length === 0)
29
+ throw new DevEnvError(USAGE.trimEnd());
30
+ };
31
+ const main = async (argv) => {
32
+ const args = argv.filter((arg) => arg !== '--');
33
+ const [command, ...rest] = args;
34
+ const baseAt = rest.indexOf('--base');
35
+ const base = baseAt === -1 ? undefined : rest[baseAt + 1];
36
+ const options = baseAt === -1 ? rest : rest.toSpliced(baseAt, 2);
37
+ const flags = options.filter((arg) => arg.startsWith('--'));
38
+ const targets = options.filter((arg) => !arg.startsWith('--'));
39
+ const mode = flags.includes('--test') ? 'test' : 'dev';
40
+ const cwd = process.cwd();
41
+ switch (command) {
42
+ case 'start': {
43
+ requireTargets(targets);
44
+ for (const target of targets) {
45
+ printEnvironment(await startTarget(cwd, target, mode));
46
+ }
47
+ return;
48
+ }
49
+ case 'stop': {
50
+ if (targets.length === 0) {
51
+ await stopAll(cwd, flags.includes('--test') ? 'test' : undefined);
52
+ return;
53
+ }
54
+ for (const target of targets)
55
+ await stopTarget(cwd, target, mode);
56
+ return;
57
+ }
58
+ case 'reset': {
59
+ requireTargets(targets);
60
+ for (const target of targets) {
61
+ // A test environment may have several lanes, and --test resets them all.
62
+ if (isTestMode(mode))
63
+ await resetTestEnvironments({ cwd, target });
64
+ else
65
+ await resetTarget(cwd, target, mode);
66
+ }
67
+ return;
68
+ }
69
+ case 'info': {
70
+ const info = await describeCheckout(cwd);
71
+ if (flags.includes('--json')) {
72
+ stdout.write(`${JSON.stringify(info, null, 2)}\n`);
73
+ }
74
+ else {
75
+ printCheckout(info);
76
+ }
77
+ return;
78
+ }
79
+ case 'affected': {
80
+ const [target] = targets;
81
+ if (target === undefined || targets.length > 1)
82
+ throw new DevEnvError(USAGE.trimEnd());
83
+ process.exitCode = await runAffected(cwd, target, {
84
+ base,
85
+ list: flags.includes('--list'),
86
+ });
87
+ return;
88
+ }
89
+ default:
90
+ throw new DevEnvError(USAGE.trimEnd());
91
+ }
92
+ };
93
+ await main(process.argv.slice(2)).catch((error) => {
94
+ stderr.write(error instanceof DevEnvError
95
+ ? `${error.message}\n`
96
+ : `${error instanceof Error ? error.stack : String(error)}\n`);
97
+ process.exitCode = 1;
98
+ });
@@ -0,0 +1,18 @@
1
+ export interface ComposeProject {
2
+ readonly name: string;
3
+ readonly directory: string;
4
+ /** compose.yaml, then any override for the mode, in the order Compose merges them. */
5
+ readonly files: readonly string[];
6
+ readonly variables: Readonly<Record<string, string>>;
7
+ }
8
+ export declare const composeFileOf: (directory: string) => string;
9
+ export declare const testOverrideOf: (directory: string) => string;
10
+ export declare const isDockerAvailable: () => Promise<boolean>;
11
+ export declare const assertDockerAvailable: () => Promise<void>;
12
+ export declare const assertServicesAreSafe: (project: ComposeProject, services: readonly string[]) => Promise<void>;
13
+ export declare const composeUp: (project: ComposeProject, services: readonly string[], timeoutMs: number) => Promise<void>;
14
+ export declare const composeStop: (project: ComposeProject, services?: readonly string[]) => Promise<void>;
15
+ export declare const composeDownWithVolumes: (project: ComposeProject) => Promise<void>;
16
+ export declare const composeRemoveWithVolumes: (project: ComposeProject, services: readonly string[]) => Promise<void>;
17
+ /** Running services and the host port each one publishes. */
18
+ export declare const runningServicesOf: (project: ComposeProject) => Promise<ReadonlyMap<string, number | undefined>>;
@@ -0,0 +1,119 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { join } from 'node:path';
3
+ import { promisify } from 'node:util';
4
+ import { DevEnvError } from './errors.js';
5
+ import { LOOPBACK } from './ports.js';
6
+ const run = promisify(execFile);
7
+ const MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
8
+ export const composeFileOf = (directory) => join(directory, 'compose.yaml');
9
+ /*
10
+ * A test environment's data is thrown away after every file, so a target can
11
+ * trade durability for speed there, in compose.test.yaml, without touching the
12
+ * dev environment it keeps between days.
13
+ */
14
+ export const testOverrideOf = (directory) => join(directory, 'compose.test.yaml');
15
+ export const isDockerAvailable = async () => {
16
+ try {
17
+ await run('docker', ['info']);
18
+ return true;
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ };
24
+ export const assertDockerAvailable = async () => {
25
+ if (!(await isDockerAvailable())) {
26
+ throw new DevEnvError('This target needs Docker. Start Docker and retry.');
27
+ }
28
+ };
29
+ const compose = async (project, ...args) => {
30
+ try {
31
+ const { stdout } = await run('docker', [
32
+ 'compose',
33
+ '--project-name',
34
+ project.name,
35
+ ...project.files.flatMap((file) => ['--file', file]),
36
+ ...args,
37
+ ], {
38
+ env: { ...process.env, ...project.variables },
39
+ maxBuffer: MAX_OUTPUT_BYTES,
40
+ });
41
+ return stdout;
42
+ }
43
+ catch (error) {
44
+ const { stderr } = error;
45
+ throw new DevEnvError(`docker compose ${args[0]} failed for ${project.name}.\n${stderr?.trim() ?? ''}`);
46
+ }
47
+ };
48
+ /*
49
+ * Compose reports a service with no healthcheck as ready once it has started,
50
+ * and a port with no host address is reachable from the whole network.
51
+ */
52
+ export const assertServicesAreSafe = async (project, services) => {
53
+ const config = JSON.parse(await compose(project, 'config', '--format', 'json'));
54
+ for (const service of services) {
55
+ const definition = config.services?.[service];
56
+ if (definition === undefined) {
57
+ throw new DevEnvError(`Service "${service}" is not defined in ${composeFileOf(project.directory)}.`);
58
+ }
59
+ if (definition.healthcheck === undefined ||
60
+ definition.healthcheck.disable === true) {
61
+ throw new DevEnvError(`Service "${service}" needs a healthcheck.`);
62
+ }
63
+ const exposed = definition.ports?.find((port) => port.host_ip !== LOOPBACK);
64
+ if (exposed !== undefined) {
65
+ throw new DevEnvError(`Service "${service}" must publish its port on ${LOOPBACK}.`);
66
+ }
67
+ }
68
+ };
69
+ export const composeUp = async (project, services, timeoutMs) => {
70
+ try {
71
+ await compose(project, 'up', '--detach', '--wait', '--remove-orphans', '--wait-timeout', String(Math.ceil(timeoutMs / 1000)), ...services);
72
+ }
73
+ catch (error) {
74
+ const logs = await compose(project, 'logs', '--no-color', '--tail', '20', ...services).catch(() => '');
75
+ const reason = error instanceof Error ? error.message : String(error);
76
+ throw new DevEnvError(`Services did not become healthy: ${services.join(', ')}.\n${reason}\n${logs}`);
77
+ }
78
+ };
79
+ export const composeStop = async (project, services = []) => {
80
+ await compose(project, 'stop', ...services);
81
+ };
82
+ /* Scoped to this project, so it cannot reach another environment's volumes. */
83
+ export const composeDownWithVolumes = async (project) => {
84
+ await compose(project, 'down', '--volumes', '--remove-orphans');
85
+ };
86
+ /*
87
+ * Only the named services, with every volume they mount, so their next start
88
+ * has no data. `rm --volumes` takes only anonymous volumes, so the named ones
89
+ * are removed by the names Compose gave them in this project.
90
+ */
91
+ export const composeRemoveWithVolumes = async (project, services) => {
92
+ const config = JSON.parse(await compose(project, 'config', '--format', 'json'));
93
+ const volumes = services.flatMap((service) => (config.services?.[service]?.volumes ?? []).flatMap((mount) => mount.type === 'volume' && mount.source !== undefined
94
+ ? [config.volumes?.[mount.source]?.name ?? mount.source]
95
+ : []));
96
+ await compose(project, 'rm', '--stop', '--force', '--volumes', ...services);
97
+ if (volumes.length === 0)
98
+ return;
99
+ try {
100
+ await run('docker', ['volume', 'rm', '--force', ...new Set(volumes)]);
101
+ }
102
+ catch (error) {
103
+ const { stderr } = error;
104
+ throw new DevEnvError(`Could not remove the volumes of ${services.join(', ')} in ${project.name}.\n${stderr?.trim() ?? ''}`);
105
+ }
106
+ };
107
+ /** Running services and the host port each one publishes. */
108
+ export const runningServicesOf = async (project) => {
109
+ const output = await compose(project, 'ps', '--format', 'json');
110
+ const containers = output
111
+ .split('\n')
112
+ .filter((line) => line.trim() !== '')
113
+ .map((line) => JSON.parse(line))
114
+ .filter((container) => container.State === 'running');
115
+ return new Map(containers.map((container) => [
116
+ container.Service,
117
+ container.Publishers?.find((publisher) => Boolean(publisher.PublishedPort))?.PublishedPort,
118
+ ]));
119
+ };
@@ -0,0 +1,33 @@
1
+ import type { Mode } from './checkout.ts';
2
+ export interface ServiceInfo {
3
+ readonly kind: 'process' | 'compose';
4
+ readonly running: boolean;
5
+ readonly port: number;
6
+ readonly address: string;
7
+ readonly url?: string;
8
+ }
9
+ export interface EnvironmentInfo {
10
+ readonly target: string;
11
+ readonly mode: Mode;
12
+ /** Unique on the machine, to tell this environment's data apart in a shared service. */
13
+ readonly name: string;
14
+ readonly composeProject?: string;
15
+ readonly services: Readonly<Record<string, ServiceInfo>>;
16
+ }
17
+ export interface CheckoutInfo {
18
+ readonly environmentId: string;
19
+ readonly checkout: string;
20
+ readonly available: readonly string[];
21
+ readonly environments: readonly EnvironmentInfo[];
22
+ }
23
+ export declare const startTarget: (cwd: string, targetName: string, mode: Mode) => Promise<EnvironmentInfo>;
24
+ export declare const startTestTarget: (cwd: string, targetName: string, mode: Mode, { without, settings: asked, }?: {
25
+ readonly without?: readonly string[];
26
+ readonly settings?: Readonly<Record<string, string>>;
27
+ }) => Promise<EnvironmentInfo>;
28
+ export declare const stopTarget: (cwd: string, targetName: string, mode: Mode) => Promise<void>;
29
+ export declare const stopAll: (cwd: string, mode?: Mode) => Promise<void>;
30
+ export declare const resetTarget: (cwd: string, targetName: string, mode: Mode) => Promise<void>;
31
+ export declare const stopService: (cwd: string, targetName: string, mode: Mode, service: string) => Promise<void>;
32
+ export declare const startService: (cwd: string, targetName: string, mode: Mode, service: string) => Promise<void>;
33
+ export declare const describeCheckout: (cwd: string) => Promise<CheckoutInfo>;