@zgeoff/rig 0.0.1 → 0.0.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.
Files changed (143) hide show
  1. package/README.md +87 -3
  2. package/dist/browser/browser-preload.d.ts +1 -0
  3. package/dist/browser/build-browser-run.d.ts +9 -0
  4. package/dist/browser/build-lane-environments.d.ts +8 -0
  5. package/dist/browser/build-recorded-command.d.ts +1 -0
  6. package/dist/browser/find-browser-run.d.ts +4 -0
  7. package/dist/browser/find-private-dir-problem.d.ts +2 -0
  8. package/dist/browser/has-browser-build-script.d.ts +1 -0
  9. package/dist/browser/has-error-code.d.ts +1 -0
  10. package/dist/browser/is-zombie-state.d.ts +1 -0
  11. package/dist/browser/lane-files.d.ts +13 -0
  12. package/dist/browser/make-browser-lane-hooks.d.ts +22 -0
  13. package/dist/browser/pick-chrome-dirs.d.ts +7 -0
  14. package/dist/browser/pick-exit-code-after-tests.d.ts +1 -0
  15. package/dist/browser/pick-step-after-build.d.ts +7 -0
  16. package/dist/browser/pick-stop-step.d.ts +17 -0
  17. package/dist/browser/probe-host-process.d.ts +1 -0
  18. package/dist/browser/probe-process.d.ts +6 -0
  19. package/dist/browser/probe-run.d.ts +9 -0
  20. package/dist/browser/process-group-still-running-error.d.ts +4 -0
  21. package/dist/browser/process-group-stop-error.d.ts +4 -0
  22. package/dist/browser/process-groups.d.ts +5 -0
  23. package/dist/browser/process-runtime.d.ts +15 -0
  24. package/dist/browser/read-dir-names.d.ts +1 -0
  25. package/dist/browser/read-process-table.d.ts +6 -0
  26. package/dist/browser/remove-exited-run-dirs.d.ts +2 -0
  27. package/dist/browser/remove-path.d.ts +1 -0
  28. package/dist/browser/run-in-page.d.ts +23 -0
  29. package/dist/browser/should-keep-run-folders.d.ts +1 -0
  30. package/dist/browser/start-browser.d.ts +9 -0
  31. package/dist/browser/start-process-group.d.ts +17 -0
  32. package/dist/browser/wire-browser-lane-hooks.d.ts +12 -0
  33. package/dist/build-diet-command.d.ts +1 -0
  34. package/dist/build-init-scripts.d.ts +3 -0
  35. package/dist/build-test-selection.d.ts +23 -0
  36. package/dist/build-unit-command.d.ts +2 -0
  37. package/dist/cli.d.ts +2 -0
  38. package/dist/define-rig.d.ts +2 -0
  39. package/dist/find-timeout-arg.d.ts +1 -0
  40. package/dist/format-no-match-message.d.ts +1 -0
  41. package/dist/format-no-tests-message.d.ts +1 -0
  42. package/dist/index.d.ts +6 -0
  43. package/dist/index.js +255 -0
  44. package/dist/init-files.d.ts +6 -0
  45. package/dist/is-command-name.d.ts +3 -0
  46. package/dist/lane-hooks.d.ts +13 -0
  47. package/dist/make-repo-lane-hooks.d.ts +12 -0
  48. package/dist/parse-duration.d.ts +1 -0
  49. package/dist/parse-lane-hook.d.ts +3 -0
  50. package/dist/parse-lane-start.d.ts +2 -0
  51. package/dist/parse-rig-config.d.ts +9 -0
  52. package/dist/parse-test-args.d.ts +5 -0
  53. package/dist/pick-e2e-dirs.d.ts +1 -0
  54. package/dist/pick-lane-selection.d.ts +2 -0
  55. package/dist/read-cli-args.d.ts +5 -0
  56. package/dist/read-memory-budget.d.ts +8 -0
  57. package/dist/read-rig-config.d.ts +6 -0
  58. package/dist/read-tracked-files.d.ts +1 -0
  59. package/dist/read-worker-count.d.ts +13 -0
  60. package/dist/resolve-diet-script.d.ts +1 -0
  61. package/dist/resolve-related-tests.d.ts +6 -0
  62. package/dist/run-cli.d.ts +9 -0
  63. package/dist/run-command.d.ts +6 -0
  64. package/dist/run-init.d.ts +8 -0
  65. package/dist/run-lane-hooks.d.ts +2 -0
  66. package/dist/run-lane.d.ts +18 -0
  67. package/dist/run-related-tests.d.ts +10 -0
  68. package/dist/run-unit-tests.d.ts +12 -0
  69. package/dist/run-unit.d.ts +8 -0
  70. package/dist/standard-lanes.d.ts +8 -0
  71. package/dist/system-clock.d.ts +5 -0
  72. package/dist/types.d.ts +42 -0
  73. package/package.json +41 -3
  74. package/src/browser/browser-preload.ts +36 -0
  75. package/src/browser/build-browser-run.ts +32 -0
  76. package/src/browser/build-lane-environments.ts +33 -0
  77. package/src/browser/build-recorded-command.ts +12 -0
  78. package/src/browser/find-browser-run.ts +15 -0
  79. package/src/browser/find-private-dir-problem.ts +21 -0
  80. package/src/browser/has-browser-build-script.ts +7 -0
  81. package/src/browser/has-error-code.ts +3 -0
  82. package/src/browser/is-zombie-state.ts +4 -0
  83. package/src/browser/lane-files.ts +56 -0
  84. package/src/browser/make-browser-lane-hooks.ts +228 -0
  85. package/src/browser/pick-chrome-dirs.ts +34 -0
  86. package/src/browser/pick-exit-code-after-tests.ts +5 -0
  87. package/src/browser/pick-step-after-build.ts +20 -0
  88. package/src/browser/pick-stop-step.ts +28 -0
  89. package/src/browser/probe-host-process.ts +11 -0
  90. package/src/browser/probe-process.ts +35 -0
  91. package/src/browser/probe-run.ts +38 -0
  92. package/src/browser/process-group-still-running-error.ts +9 -0
  93. package/src/browser/process-group-stop-error.ts +10 -0
  94. package/src/browser/process-groups.ts +45 -0
  95. package/src/browser/process-runtime.ts +40 -0
  96. package/src/browser/read-dir-names.ts +15 -0
  97. package/src/browser/read-process-table.ts +35 -0
  98. package/src/browser/remove-exited-run-dirs.ts +21 -0
  99. package/src/browser/remove-path.ts +5 -0
  100. package/src/browser/run-in-page.ts +103 -0
  101. package/src/browser/should-keep-run-folders.ts +7 -0
  102. package/src/browser/start-browser.ts +40 -0
  103. package/src/browser/start-process-group.ts +168 -0
  104. package/src/browser/wire-browser-lane-hooks.ts +88 -0
  105. package/src/build-diet-command.ts +11 -0
  106. package/src/build-init-scripts.ts +40 -0
  107. package/src/build-test-selection.ts +124 -0
  108. package/src/build-unit-command.ts +22 -0
  109. package/src/cli.ts +73 -0
  110. package/src/define-rig.ts +195 -0
  111. package/src/find-timeout-arg.ts +3 -0
  112. package/src/format-no-match-message.ts +3 -0
  113. package/src/format-no-tests-message.ts +3 -0
  114. package/src/index.ts +14 -0
  115. package/src/init-files.ts +15 -0
  116. package/src/is-command-name.ts +9 -0
  117. package/src/lane-hooks.ts +15 -0
  118. package/src/make-repo-lane-hooks.ts +70 -0
  119. package/src/parse-duration.ts +14 -0
  120. package/src/parse-lane-hook.ts +20 -0
  121. package/src/parse-lane-start.ts +30 -0
  122. package/src/parse-rig-config.ts +96 -0
  123. package/src/parse-test-args.ts +14 -0
  124. package/src/pick-e2e-dirs.ts +25 -0
  125. package/src/pick-lane-selection.ts +14 -0
  126. package/src/read-cli-args.ts +57 -0
  127. package/src/read-memory-budget.ts +65 -0
  128. package/src/read-rig-config.ts +32 -0
  129. package/src/read-tracked-files.ts +20 -0
  130. package/src/read-worker-count.ts +40 -0
  131. package/src/resolve-diet-script.ts +7 -0
  132. package/src/resolve-related-tests.ts +52 -0
  133. package/src/run-cli.ts +68 -0
  134. package/src/run-command.ts +36 -0
  135. package/src/run-init.ts +71 -0
  136. package/src/run-lane-hooks.ts +49 -0
  137. package/src/run-lane.ts +138 -0
  138. package/src/run-related-tests.ts +113 -0
  139. package/src/run-unit-tests.ts +42 -0
  140. package/src/run-unit.ts +68 -0
  141. package/src/standard-lanes.ts +23 -0
  142. package/src/system-clock.ts +10 -0
  143. package/src/types.ts +75 -0
@@ -0,0 +1,124 @@
1
+ import { posix } from 'node:path';
2
+ import { match } from 'ts-pattern';
3
+ import type { TestArgs } from './parse-test-args.ts';
4
+ import { pickE2EDirs } from './pick-e2e-dirs.ts';
5
+ import type { ResolvedLane, RigConfig } from './types.ts';
6
+
7
+ export type TestSelection =
8
+ | { readonly kind: 'lane'; readonly flags: readonly string[] }
9
+ | { readonly kind: 'empty' }
10
+ | { readonly kind: 'files'; readonly files: readonly string[]; readonly flags: readonly string[] }
11
+ | { readonly kind: 'none'; readonly paths: readonly string[] };
12
+
13
+ export interface TestSelectionRequest {
14
+ readonly config: RigConfig;
15
+
16
+ readonly lane: Pick<ResolvedLane, 'name' | 'suffix'>;
17
+
18
+ readonly repoRoot: string;
19
+
20
+ readonly trackedFiles: readonly string[];
21
+
22
+ readonly args: TestArgs;
23
+ }
24
+
25
+ // bun test runs every file that a path argument names, whatever lane the file belongs to, so rig
26
+ // narrows the paths to the lane's own files and hands bun test that exact list.
27
+ export function buildTestSelection(request: TestSelectionRequest): TestSelection {
28
+ const split = request.args;
29
+ const laneFiles = collectLaneTestFiles(request.config, request.lane, request.trackedFiles);
30
+
31
+ if (split.paths.length === 0) {
32
+ return laneFiles.length === 0 ? { kind: 'empty' } : { kind: 'lane', flags: split.flags };
33
+ }
34
+
35
+ const selectors = split.paths.map((path) =>
36
+ buildSelector(path, request.repoRoot, request.trackedFiles),
37
+ );
38
+
39
+ const files = laneFiles.filter((file) =>
40
+ selectors.some((selector) => isSelected(file, selector)),
41
+ );
42
+
43
+ return files.length === 0
44
+ ? { kind: 'none', paths: split.paths }
45
+ : { kind: 'files', files: files.map((file) => `./${file}`), flags: split.flags };
46
+ }
47
+
48
+ const testFilePattern = /[._](?:test|spec)\.[jt]sx?$/u;
49
+
50
+ // The unit lane takes every test file that no other lane claims, the e2e lane the ones under its
51
+ // folders, and any other lane the ones with its suffix.
52
+ function collectLaneTestFiles(
53
+ config: RigConfig,
54
+ lane: Pick<ResolvedLane, 'name' | 'suffix'>,
55
+ trackedFiles: readonly string[],
56
+ ): readonly string[] {
57
+ const e2eDirs = pickE2EDirs(trackedFiles);
58
+
59
+ const isUnderE2EDir = (file: string) =>
60
+ e2eDirs.some((directory) => file.startsWith(`${directory}/`));
61
+
62
+ const isClaimedBySuffix = (file: string) =>
63
+ config.lanes.some((other) => other.suffix !== null && hasLaneSuffix(file, other.suffix));
64
+
65
+ const testFiles = trackedFiles.filter((file) => testFilePattern.test(file));
66
+ const suffix = lane.suffix;
67
+
68
+ if (suffix !== null) {
69
+ return testFiles.filter((file) => hasLaneSuffix(file, suffix));
70
+ }
71
+
72
+ return lane.name === 'e2e'
73
+ ? testFiles.filter((file) => isUnderE2EDir(file) && !isClaimedBySuffix(file))
74
+ : testFiles.filter((file) => !isUnderE2EDir(file) && !isClaimedBySuffix(file));
75
+ }
76
+
77
+ function hasLaneSuffix(file: string, suffix: string): boolean {
78
+ return file.endsWith(`${suffix}.test.ts`) || file.endsWith(`${suffix}.test.tsx`);
79
+ }
80
+
81
+ type Selector =
82
+ | { readonly kind: 'file'; readonly path: string }
83
+ | { readonly kind: 'directory'; readonly path: string }
84
+ | { readonly kind: 'filter'; readonly text: string }
85
+ | { readonly kind: 'missing' };
86
+
87
+ // A path names a tracked file or a folder that holds one, read against the repo root. A bare word
88
+ // that names neither is bun test's filter on the path, and a `./`, `../` or absolute path that
89
+ // names neither, or a path outside the repo, selects nothing.
90
+ function buildSelector(path: string, repoRoot: string, trackedFiles: readonly string[]): Selector {
91
+ const normalized = posix.relative(repoRoot, posix.resolve(repoRoot, path));
92
+
93
+ if (normalized === '..' || normalized.startsWith('../') || posix.isAbsolute(normalized)) {
94
+ return { kind: 'missing' };
95
+ }
96
+
97
+ if (normalized === '') {
98
+ return { kind: 'directory', path: '' };
99
+ }
100
+
101
+ if (trackedFiles.includes(normalized)) {
102
+ return { kind: 'file', path: normalized };
103
+ }
104
+
105
+ if (trackedFiles.some((file) => file.startsWith(`${normalized}/`))) {
106
+ return { kind: 'directory', path: normalized };
107
+ }
108
+
109
+ const isPathLike = path.startsWith('./') || path.startsWith('../') || posix.isAbsolute(path);
110
+
111
+ return isPathLike ? { kind: 'missing' } : { kind: 'filter', text: normalized };
112
+ }
113
+
114
+ function isSelected(file: string, selector: Selector): boolean {
115
+ return match(selector)
116
+ .with({ kind: 'file' }, (fileSelector) => file === fileSelector.path)
117
+ .with(
118
+ { kind: 'directory' },
119
+ (directory) => directory.path === '' || file.startsWith(`${directory.path}/`),
120
+ )
121
+ .with({ kind: 'filter' }, (filter) => file.includes(filter.text))
122
+ .with({ kind: 'missing' }, () => false)
123
+ .exhaustive();
124
+ }
@@ -0,0 +1,22 @@
1
+ import type { RigConfig } from './types.ts';
2
+
3
+ // The e2e lane has no suffix, so the unit run leaves out the folders that the e2e lane selects,
4
+ // from the same list, and nothing else.
5
+ export function buildUnitCommand(
6
+ config: RigConfig,
7
+ e2eDirs: readonly string[],
8
+ workerCount: number,
9
+ extraArgs: readonly string[],
10
+ ): readonly string[] {
11
+ const suffixPatterns = config.lanes.flatMap((lane) =>
12
+ lane.suffix === null ? [] : [`**/*${lane.suffix}.test.ts`, `**/*${lane.suffix}.test.tsx`],
13
+ );
14
+
15
+ const e2ePatterns = e2eDirs.map((directory) => `${directory}/**`);
16
+
17
+ const ignoreArgs = [...suffixPatterns, ...e2ePatterns].map(
18
+ (pattern) => `--path-ignore-patterns=${pattern}`,
19
+ );
20
+
21
+ return ['bun', 'test', `--parallel=${workerCount}`, '--randomize', ...ignoreArgs, ...extraArgs];
22
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env bun
2
+ import { existsSync } from 'node:fs';
3
+ import { availableParallelism, totalmem } from 'node:os';
4
+ import { wireBrowserLaneHooks } from './browser/wire-browser-lane-hooks.ts';
5
+ import { initFiles } from './init-files.ts';
6
+ import { readOptionalText } from './read-memory-budget.ts';
7
+ import { readRigConfig } from './read-rig-config.ts';
8
+ import { readTrackedFiles } from './read-tracked-files.ts';
9
+ import { readWorkerCount } from './read-worker-count.ts';
10
+ import { resolveDietScript } from './resolve-diet-script.ts';
11
+ import { runCLI } from './run-cli.ts';
12
+ import { runCommand } from './run-command.ts';
13
+
14
+ // A signal stops the run's processes through the abort, and the run waits for them to exit before
15
+ // it returns, so a lane's stop hook and folder cleanup still run.
16
+ const controller = new AbortController();
17
+
18
+ function handleSignal() {
19
+ controller.abort();
20
+ }
21
+
22
+ process.on('SIGINT', handleSignal);
23
+ process.on('SIGTERM', handleSignal);
24
+ process.on('SIGHUP', handleSignal);
25
+
26
+ const output = {
27
+ out: (text: string) => {
28
+ process.stdout.write(text);
29
+ },
30
+ err: (text: string) => {
31
+ process.stderr.write(text);
32
+ },
33
+ };
34
+
35
+ // `bun run` starts a package script in the folder of the package that defines it.
36
+ const repoRoot = process.cwd();
37
+
38
+ try {
39
+ process.exitCode = await runCLI(
40
+ process.argv.slice(2),
41
+ {
42
+ repoRoot,
43
+ environment: process.env,
44
+ signal: controller.signal,
45
+ runID: String(process.pid),
46
+ },
47
+ {
48
+ dietScript: resolveDietScript(),
49
+ output,
50
+ sources: { cwd: repoRoot, probeFile: existsSync },
51
+ readConfig: (root) =>
52
+ readRigConfig(root, { probeFile: existsSync, importModule: (path) => import(path) }),
53
+ readTrackedFiles,
54
+ initFiles,
55
+ readWorkerCount: () =>
56
+ readWorkerCount({
57
+ env: process.env,
58
+ cores: availableParallelism(),
59
+ totalMemory: totalmem(),
60
+ procRoot: '/proc',
61
+ cgroupRoot: '/sys/fs/cgroup',
62
+ readText: readOptionalText,
63
+ }),
64
+ importModule: (path) => import(path),
65
+ runCommand,
66
+ wireBrowserLaneHooks,
67
+ },
68
+ );
69
+ } catch (error) {
70
+ console.error('rig:', error);
71
+
72
+ process.exitCode = 1;
73
+ }
@@ -0,0 +1,195 @@
1
+ import { isCommandName } from './is-command-name.ts';
2
+ import { parseDuration } from './parse-duration.ts';
3
+ import { standardLanes } from './standard-lanes.ts';
4
+ import type { StandardLane } from './standard-lanes.ts';
5
+ import type { LaneDeclaration, ResolvedLane, RigConfig, RigDeclaration } from './types.ts';
6
+
7
+ const laneNamePattern = /^[a-z][a-z0-9-]*$/u;
8
+
9
+ // A config file is outside input, so a bad value throws an error that names the lane and the field.
10
+ export function defineRig(declaration: RigDeclaration): RigConfig {
11
+ const declared = Object.entries(declaration.lanes ?? {});
12
+
13
+ for (const [name] of declared) {
14
+ if (!laneNamePattern.test(name)) {
15
+ throw new Error(
16
+ `rig.config.ts: the lane name "${name}" must be lowercase letters, digits and dashes, starting with a letter`,
17
+ );
18
+ }
19
+
20
+ if (isCommandName(name)) {
21
+ throw new Error(
22
+ `rig.config.ts: the lane name "${name}" is a rig command, so \`rig ${name}\` could never run the lane`,
23
+ );
24
+ }
25
+ }
26
+
27
+ const lanes = [
28
+ ...standardLanes.map((standard) =>
29
+ resolveStandardLane(standard, declaration.lanes?.[standard.name]),
30
+ ),
31
+ ...declared
32
+ .filter(([name]) => !standardLanes.some((standard) => standard.name === name))
33
+ .map(([name, laneDeclaration]) => resolveProjectLane(name, laneDeclaration)),
34
+ ];
35
+
36
+ assertDistinctSuffixes(lanes);
37
+
38
+ return { lanes };
39
+ }
40
+
41
+ function resolveStandardLane(
42
+ standard: StandardLane,
43
+ declaration: LaneDeclaration | undefined,
44
+ ): ResolvedLane {
45
+ const declared = declaration ?? {};
46
+
47
+ assertDirectoryLaneDeclaration(standard, declared);
48
+
49
+ if (
50
+ standard.name === 'browser' &&
51
+ (declared.start !== undefined || declared.stop !== undefined)
52
+ ) {
53
+ throw new Error(
54
+ 'rig.config.ts: lane "browser" declares a start or a stop, but the browser lane has its hooks built in',
55
+ );
56
+ }
57
+
58
+ return {
59
+ name: standard.name,
60
+ suffix:
61
+ declared.suffix === undefined ? standard.suffix : readSuffix(standard.name, declared.suffix),
62
+ limitMs:
63
+ declared.limit === undefined ? standard.limitMs : readLimit(standard.name, declared.limit),
64
+ parallel: standard.parallel,
65
+ memory: readMemory(standard.name, declared.memory),
66
+ start: readModulePath(standard.name, 'start', declared.start),
67
+ stop: readModulePath(standard.name, 'stop', declared.stop),
68
+ };
69
+ }
70
+
71
+ // The unit lane runs what the other lanes leave, and the e2e lane runs its directories, so
72
+ // neither has a suffix, and the unit run takes no limit or hooks of its own.
73
+ const directoryLaneFields = new Map<string, readonly (keyof LaneDeclaration)[]>([
74
+ ['unit', ['suffix', 'limit', 'start', 'stop']],
75
+ ['e2e', ['suffix']],
76
+ ]);
77
+
78
+ function assertDirectoryLaneDeclaration(
79
+ standard: StandardLane,
80
+ declaration: LaneDeclaration,
81
+ ): void {
82
+ for (const field of directoryLaneFields.get(standard.name) ?? []) {
83
+ if (declaration[field] !== undefined) {
84
+ throw new Error(
85
+ `rig.config.ts: lane "${standard.name}" declares ${field}, which the ${standard.name} lane does not take`,
86
+ );
87
+ }
88
+ }
89
+ }
90
+
91
+ const suffixPattern = /^\.[a-z0-9][a-z0-9-]*$/u;
92
+
93
+ const directoryLaneNames = standardLanes
94
+ .filter((standard) => standard.suffix === null)
95
+ .map((standard) => standard.name);
96
+
97
+ function readSuffix(lane: string, suffix: string): string {
98
+ if (!suffixPattern.test(suffix)) {
99
+ throw new Error(
100
+ `rig.config.ts: lane "${lane}" has the suffix "${suffix}", which must be a dot and then lowercase letters, digits and dashes`,
101
+ );
102
+ }
103
+
104
+ const directoryLane = directoryLaneNames.find((name) => suffix === `.${name}`);
105
+
106
+ if (directoryLane !== undefined) {
107
+ throw new Error(
108
+ `rig.config.ts: lane "${lane}" has the suffix "${suffix}", which the ${directoryLane} lane reserves, because the lint rules key that lane by its name`,
109
+ );
110
+ }
111
+
112
+ return suffix;
113
+ }
114
+
115
+ function readLimit(lane: string, limit: string): number {
116
+ const limitMs = parseDuration(limit);
117
+
118
+ if (limitMs === null) {
119
+ throw new Error(
120
+ `rig.config.ts: lane "${lane}" has the limit "${limit}", which is no duration such as '15s' or '1500ms'`,
121
+ );
122
+ }
123
+
124
+ return limitMs;
125
+ }
126
+
127
+ const memoryPattern = /^[1-9]\d*[KMG]?$/u;
128
+
129
+ function readMemory(lane: string, memory: string | undefined): string | null {
130
+ if (memory === undefined) {
131
+ return null;
132
+ }
133
+
134
+ if (!memoryPattern.test(memory)) {
135
+ throw new Error(
136
+ `rig.config.ts: lane "${lane}" has the memory "${memory}", which is no budget such as '512M' or '8G'`,
137
+ );
138
+ }
139
+
140
+ return memory;
141
+ }
142
+
143
+ function readModulePath(
144
+ lane: string,
145
+ field: 'start' | 'stop',
146
+ path: string | undefined,
147
+ ): string | null {
148
+ if (path === undefined) {
149
+ return null;
150
+ }
151
+
152
+ if (path === '' || path.startsWith('/')) {
153
+ throw new Error(
154
+ `rig.config.ts: lane "${lane}" has the ${field} "${path}", which must be a path relative to the repo root`,
155
+ );
156
+ }
157
+
158
+ return path;
159
+ }
160
+
161
+ function resolveProjectLane(name: string, declaration: LaneDeclaration): ResolvedLane {
162
+ if (declaration.limit === undefined) {
163
+ throw new Error(`rig.config.ts: lane "${name}" needs a limit, such as '15s'`);
164
+ }
165
+
166
+ return {
167
+ name,
168
+ suffix: declaration.suffix === undefined ? `.${name}` : readSuffix(name, declaration.suffix),
169
+ limitMs: readLimit(name, declaration.limit),
170
+ parallel: 1,
171
+ memory: readMemory(name, declaration.memory),
172
+ start: readModulePath(name, 'start', declaration.start),
173
+ stop: readModulePath(name, 'stop', declaration.stop),
174
+ };
175
+ }
176
+
177
+ function assertDistinctSuffixes(lanes: readonly ResolvedLane[]): void {
178
+ const owners = new Map<string, string>();
179
+
180
+ for (const lane of lanes) {
181
+ if (lane.suffix === null) {
182
+ continue;
183
+ }
184
+
185
+ const owner = owners.get(lane.suffix);
186
+
187
+ if (owner !== undefined) {
188
+ throw new Error(
189
+ `rig.config.ts: lanes "${owner}" and "${lane.name}" both use the suffix "${lane.suffix}"`,
190
+ );
191
+ }
192
+
193
+ owners.set(lane.suffix, lane.name);
194
+ }
195
+ }
@@ -0,0 +1,3 @@
1
+ export function findTimeoutArg(args: readonly string[]): string | undefined {
2
+ return args.find((arg) => arg === '--timeout' || arg.startsWith('--timeout='));
3
+ }
@@ -0,0 +1,3 @@
1
+ export function formatNoMatchMessage(laneName: string, paths: readonly string[]): string {
2
+ return `rig: the ${laneName} lane has no tests that match ${paths.join(' ')}\n`;
3
+ }
@@ -0,0 +1,3 @@
1
+ export function formatNoTestsMessage(laneName: string): string {
2
+ return `rig: the ${laneName} lane has no tests\n`;
3
+ }
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ export { defineRig } from './define-rig.ts';
2
+ export { parseRigConfig } from './parse-rig-config.ts';
3
+ export type { ParsedRigConfig } from './parse-rig-config.ts';
4
+ export { runInPage } from './browser/run-in-page.ts';
5
+ export type { PageResultSchema } from './browser/run-in-page.ts';
6
+
7
+ export type {
8
+ LaneContext,
9
+ LaneDeclaration,
10
+ LaneStart,
11
+ ResolvedLane,
12
+ RigConfig,
13
+ RigDeclaration,
14
+ } from './types.ts';
@@ -0,0 +1,15 @@
1
+ export interface InitFiles {
2
+ readonly readJSON: (path: string) => Promise<unknown>;
3
+
4
+ readonly writeText: (path: string, text: string) => Promise<void>;
5
+
6
+ readonly probeFile: (path: string) => Promise<boolean>;
7
+ }
8
+
9
+ export const initFiles: InitFiles = {
10
+ readJSON: (path) => Bun.file(path).json(),
11
+ writeText: async (path, text) => {
12
+ await Bun.write(path, text);
13
+ },
14
+ probeFile: (path) => Bun.file(path).exists(),
15
+ };
@@ -0,0 +1,9 @@
1
+ // The built-in commands that `rig` dispatches before it looks for a lane, so no lane may take one
2
+ // of these names.
3
+ export const commandNames = ['init', 'related'] as const;
4
+
5
+ export type CommandName = (typeof commandNames)[number];
6
+
7
+ export function isCommandName(name: string): name is CommandName {
8
+ return commandNames.some((command) => command === name);
9
+ }
@@ -0,0 +1,15 @@
1
+ export type LaneEnvironment = Readonly<Record<string, string | undefined>>;
2
+
3
+ export type LaneStartOutcome =
4
+ | { readonly kind: 'proceed'; readonly environment: LaneEnvironment }
5
+ | { readonly kind: 'finish'; readonly exitCode: number };
6
+
7
+ // The three steps of a lane run. `start` prepares what the tests need, and either hands on the
8
+ // environment of the test process or finishes the run early. `stop` always runs.
9
+ export interface LaneHooks {
10
+ readonly start: () => Promise<LaneStartOutcome>;
11
+
12
+ readonly run: (testArgs: readonly string[], environment: LaneEnvironment) => Promise<number>;
13
+
14
+ readonly stop: () => Promise<void>;
15
+ }
@@ -0,0 +1,70 @@
1
+ import { join } from 'node:path';
2
+ import { buildDietCommand } from './build-diet-command.ts';
3
+ import type { LaneHooks } from './lane-hooks.ts';
4
+ import { parseLaneHook } from './parse-lane-hook.ts';
5
+ import { parseLaneStart } from './parse-lane-start.ts';
6
+ import type { CommandOptions } from './run-command.ts';
7
+ import type { LaneContext } from './types.ts';
8
+
9
+ export interface RepoLaneOptions {
10
+ readonly context: LaneContext;
11
+
12
+ readonly dietScript: string;
13
+
14
+ readonly parallel: number;
15
+
16
+ readonly signal: AbortSignal;
17
+
18
+ readonly importModule: (path: string) => Promise<unknown>;
19
+
20
+ readonly runCommand: (command: readonly string[], options: CommandOptions) => Promise<number>;
21
+ }
22
+
23
+ // The hooks of a lane that a repo declares: its start and stop modules around `bun test` under
24
+ // diet. A lane with no module for a hook skips that hook.
25
+ export function makeRepoLaneHooks(options: RepoLaneOptions): LaneHooks {
26
+ const lane = options.context.lane;
27
+
28
+ return {
29
+ start: async () => {
30
+ if (lane.start === null) {
31
+ return { kind: 'proceed', environment: options.context.environment };
32
+ }
33
+
34
+ const started = await runHook(lane.start, options);
35
+
36
+ return {
37
+ kind: 'proceed',
38
+ environment: {
39
+ ...options.context.environment,
40
+ ...parseLaneStart(started, lane.start).environment,
41
+ },
42
+ };
43
+ },
44
+ run: (testArgs, environment) =>
45
+ options.runCommand(
46
+ buildDietCommand(options.dietScript, lane.memory, [
47
+ 'bun',
48
+ 'test',
49
+ `--parallel=${options.parallel}`,
50
+ ...testArgs,
51
+ ]),
52
+ { cwd: options.context.repoRoot, environment, signal: options.signal },
53
+ ),
54
+ stop: async () => {
55
+ if (lane.stop !== null) {
56
+ await runHook(lane.stop, options);
57
+ }
58
+ },
59
+ };
60
+ }
61
+
62
+ async function runHook(path: string, options: RepoLaneOptions): Promise<unknown> {
63
+ const absolutePath = join(options.context.repoRoot, path);
64
+
65
+ const loaded = await options.importModule(absolutePath);
66
+
67
+ const hook = parseLaneHook(loaded, path);
68
+
69
+ return hook(options.context);
70
+ }
@@ -0,0 +1,14 @@
1
+ const durationPattern = /^(?<count>[1-9]\d*)(?<unit>ms|s)$/u;
2
+
3
+ // Returns null for text that is no duration, so the caller names the field it came from.
4
+ export function parseDuration(text: string): number | null {
5
+ const groups = durationPattern.exec(text)?.groups;
6
+
7
+ if (groups === undefined) {
8
+ return null;
9
+ }
10
+
11
+ const count = Number(groups['count']);
12
+
13
+ return groups['unit'] === 's' ? count * 1000 : count;
14
+ }
@@ -0,0 +1,20 @@
1
+ import { isRecord } from '@zgeoff/std';
2
+ import type { LaneContext } from './types.ts';
3
+
4
+ export type LaneHook = (context: LaneContext) => Promise<unknown>;
5
+
6
+ // A repo's hook module comes from outside the program, so its default export is checked before
7
+ // rig calls it.
8
+ export function parseLaneHook(loaded: unknown, path: string): LaneHook {
9
+ const hook = isRecord(loaded) ? loaded['default'] : null;
10
+
11
+ if (!isLaneHook(hook)) {
12
+ throw new Error(`${path} must default-export a function that takes the lane context`);
13
+ }
14
+
15
+ return hook;
16
+ }
17
+
18
+ function isLaneHook(value: unknown): value is LaneHook {
19
+ return typeof value === 'function';
20
+ }
@@ -0,0 +1,30 @@
1
+ import type { LaneStart } from './types.ts';
2
+
3
+ export function parseLaneStart(value: unknown, path: string): LaneStart {
4
+ if (value === undefined) {
5
+ return {};
6
+ }
7
+
8
+ const environment: unknown =
9
+ typeof value === 'object' && value !== null ? Reflect.get(value, 'environment') : null;
10
+
11
+ if (environment === undefined) {
12
+ return {};
13
+ }
14
+
15
+ if (!isStringRecord(environment)) {
16
+ throw new Error(
17
+ `the start hook ${path} must return nothing or { environment: Record<string, string> }`,
18
+ );
19
+ }
20
+
21
+ return { environment };
22
+ }
23
+
24
+ function isStringRecord(value: unknown): value is Record<string, string> {
25
+ return (
26
+ typeof value === 'object' &&
27
+ value !== null &&
28
+ Object.values(value).every((entry: unknown) => typeof entry === 'string')
29
+ );
30
+ }