Skip to content

Commit 63e24f2

Browse files
authored
Merge pull request #20 from rhyek/fix/config-typecheck-speed
Speed up the config type check, and ignore errors in declaration files
2 parents 8a78c2c + 7f2946b commit 63e24f2

5 files changed

Lines changed: 169 additions & 204 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
# Changelog
22

3+
## 0.8.1
4+
5+
### Fixes
6+
7+
- **The config type check before `start` and `run` takes about a third of the time, and an error
8+
inside a declaration file no longer fails it.**
9+
310
## 0.8.0
411

512
### Features

‎docs/config/config-file.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -220,9 +220,11 @@ stackctl.config.ts(4,24): error TS2322: Type 'string' is not assignable to type
220220

221221
- **The check runs the `tsc` of the `typescript` installed beside the config**, in the workspace
222222
root's `node_modules`. Without one, there is no check.
223-
- **The `tsconfig.json` beside the config sets the compiler options.** Only the config and what
224-
it imports are checked, and nothing is written. Without a `tsconfig.json`, the check runs with
225-
`--strict`, `--module nodenext` and `--target esnext`.
223+
- **The `tsconfig.json` beside the config sets the compiler options.** The config, and the source
224+
files it imports, are checked against the declarations they use, never the declaration files
225+
themselves, so an error inside one in `node_modules` doesn't count. Nothing is written.
226+
Without a `tsconfig.json`, the check runs with `--strict`, `--module nodenext` and
227+
`--target esnext`.
226228
- **A JavaScript config (`.js`, `.mjs`) isn't checked**, and no other command checks.
227229

228230
## `--workspace-dir`

‎packages/stackctl/src/cli.ts‎

Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,7 @@ import { takeHandedSessionId } from './running.js';
2626
// changes before a session starts over from them (see relaunch.ts).
2727
import { relaunchWithCappedYoungGeneration } from './relaunch.js';
2828
import { readOwnVersion } from './skill.js';
29-
import {
30-
findConfigPath,
31-
locateWorkspace,
32-
needsNoWorkspace,
33-
resolveWorkspaceDirArg,
34-
} from './workspace-root.js';
29+
import { locateWorkspace, needsNoWorkspace, resolveWorkspaceDirArg } from './workspace-root.js';
3530

3631
// The entry point: Commander wiring only. What a command runs lives under `commands/` and is
3732
// imported by its action, so a command loads its own code and nothing else's — `--help` and
@@ -155,20 +150,6 @@ function anchorAtWorkspaceRoot(invocationCwd: string): void {
155150
captureShellEnv();
156151
}
157152

158-
/**
159-
* What `start` and `run` do before anything else: type-check the workspace's config with its own
160-
* `tsc`, and exit 1 on a type error (see `config-typecheck.ts`).
161-
*/
162-
async function typecheckConfigOrExit(): Promise<void> {
163-
const root = process.cwd();
164-
const configPath = findConfigPath(root);
165-
if (configPath === null) {
166-
return;
167-
}
168-
const { assertConfigTypechecks } = await import('./config-typecheck.js');
169-
await assertConfigTypechecks(configPath, root);
170-
}
171-
172153
/** Commander option-parser for repeatable `-s/--service <name>` flags. */
173154
function collect(value: string, previous: string[]): string[] {
174155
return [...previous, value];
@@ -329,14 +310,14 @@ program
329310
console.error(agentRefusal);
330311
process.exit(1);
331312
}
332-
await typecheckConfigOrExit();
313+
await (await import('./config-typecheck.js')).checkConfigTypes();
333314
await runDetach(opts);
334315
}
335316

336317
relaunchWithCappedYoungGeneration();
337318
// After starting over, so it runs once; the session `--detach` starts was checked by it.
338319
if (!detachedSession) {
339-
await typecheckConfigOrExit();
320+
await (await import('./config-typecheck.js')).checkConfigTypes();
340321
}
341322
const { runDefaultAction } = await import('./commands/default.js');
342323
await runDefaultAction(opts);
@@ -529,7 +510,7 @@ program
529510
code: 'commander.missingArgument',
530511
});
531512
}
532-
await typecheckConfigOrExit();
513+
await (await import('./config-typecheck.js')).checkConfigTypes();
533514
const { runOneOffCommand } = await import('./commands/one-off.js');
534515
await runOneOffCommand({ kind: 'run', target, script, args: after }, oneOffContext(flags));
535516
});
Lines changed: 90 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
import fs from 'node:fs';
22
import os from 'node:os';
33
import path from 'node:path';
4-
import { afterEach, describe, expect, test } from 'vitest';
5-
import { checkTsconfig, findTsc, typecheckConfig } from './config-typecheck.js';
4+
import { afterEach, describe, expect, test, vi } from 'vitest';
5+
import { checkConfigTypes } from './config-typecheck.js';
66

7-
// The repo's own typescript, linked into each workspace as the workspace's.
7+
// The repo's own typescript (7), linked into a workspace as the workspace's.
88
const TYPESCRIPT = path.resolve(import.meta.dirname, '../../../node_modules/typescript');
99

1010
const dirs: string[] = [];
1111
afterEach(() => {
12+
vi.restoreAllMocks();
1213
for (const dir of dirs.splice(0)) {
1314
fs.rmSync(dir, { recursive: true, force: true });
1415
}
@@ -22,60 +23,49 @@ function workspace(files: Record<string, string>, typescript = true): string {
2223
for (const [name, content] of Object.entries(files)) {
2324
fs.writeFileSync(path.join(ws, name), content);
2425
}
26+
fs.mkdirSync(path.join(ws, 'node_modules'));
2527
if (typescript) {
26-
fs.mkdirSync(path.join(ws, 'node_modules'));
2728
fs.symlinkSync(TYPESCRIPT, path.join(ws, 'node_modules', 'typescript'));
2829
}
2930
return ws;
3031
}
3132

33+
/** Runs the check in `ws`: what it printed, or `null` when it passed. */
34+
async function check(ws: string): Promise<string | null> {
35+
let printed: string | null = null;
36+
vi.spyOn(console, 'error').mockImplementation((message: string) => {
37+
printed = message;
38+
});
39+
const exit = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never);
40+
await checkConfigTypes(ws);
41+
expect(exit.mock.calls).toEqual(printed === null ? [] : [[1]]);
42+
return printed;
43+
}
44+
3245
const TSCONFIG = JSON.stringify({
3346
compilerOptions: { strict: true, module: 'nodenext', target: 'esnext', types: [] },
3447
});
3548
const CLEAN = 'const port: number = 3000;\nexport default { port };\n';
3649
const BROKEN = 'const port: number = "3000";\nexport default { port };\n';
50+
const TS2322 =
51+
"stackctl.config.ts(1,7): error TS2322: Type 'string' is not assignable to type 'number'.";
3752

38-
const check = (ws: string, name = 'stackctl.config.ts') => typecheckConfig(path.join(ws, name), ws);
39-
40-
describe('typecheckConfig', () => {
41-
test('passes a config without type errors, against the workspace tsconfig', async () => {
42-
const ws = workspace({ 'tsconfig.json': TSCONFIG, 'stackctl.config.ts': CLEAN });
43-
expect(await check(ws)).toEqual({ kind: 'ok' });
44-
});
45-
46-
test("reports tsc's errors for a config with type errors", async () => {
47-
const ws = workspace({ 'tsconfig.json': TSCONFIG, 'stackctl.config.ts': BROKEN });
48-
const result = await check(ws);
49-
expect(result.kind).toBe('errors');
50-
expect(result.kind === 'errors' && result.output).toContain(
51-
"stackctl.config.ts(1,7): error TS2322: Type 'string' is not assignable to type 'number'.",
52-
);
53-
});
54-
55-
test('applies the workspace tsconfig: an option it sets is checked', async () => {
56-
const tsconfig = JSON.stringify({
57-
compilerOptions: { strict: true, module: 'nodenext', types: [], noUnusedLocals: true },
58-
});
59-
const config = 'const unused = 1;\nexport default {};\n';
60-
const ws = workspace({ 'tsconfig.json': tsconfig, 'stackctl.config.ts': config });
61-
const result = await check(ws);
62-
expect(result.kind === 'errors' && result.output).toContain('error TS6133');
63-
});
64-
65-
test('writes nothing into the workspace, an incremental, composite base included', async () => {
53+
describe('checkConfigTypes', () => {
54+
test('passes a config without type errors, and writes nothing, whatever the tsconfig emits', async () => {
6655
const tsconfig = JSON.stringify({
6756
compilerOptions: {
6857
composite: true,
6958
incremental: true,
7059
tsBuildInfoFile: './build.tsbuildinfo',
60+
emitDeclarationOnly: true,
61+
declarationMap: true,
7162
outDir: 'dist',
7263
module: 'nodenext',
7364
types: [],
7465
},
75-
include: ['src'],
7666
});
7767
const ws = workspace({ 'tsconfig.json': tsconfig, 'stackctl.config.ts': CLEAN });
78-
expect(await check(ws)).toEqual({ kind: 'ok' });
68+
expect(await check(ws)).toBeNull();
7969
expect(fs.readdirSync(ws).sort()).toEqual([
8070
'node_modules',
8171
'package.json',
@@ -85,64 +75,84 @@ describe('typecheckConfig', () => {
8575
expect(fs.readdirSync(path.join(ws, 'node_modules', '.stackctl'))).toEqual([]);
8676
});
8777

88-
test('accepts a base that emits only declarations, with their maps', async () => {
78+
test("exits 1 with tsc's errors for a config with a type error", async () => {
79+
const ws = workspace({ 'tsconfig.json': TSCONFIG, 'stackctl.config.ts': BROKEN });
80+
expect(await check(ws)).toBe(`stackctl: stackctl.config.ts has type errors:\n\n${TS2322}`);
81+
});
82+
83+
test('applies the tsconfig beside the config', async () => {
8984
const tsconfig = JSON.stringify({
90-
compilerOptions: {
91-
composite: true,
92-
emitDeclarationOnly: true,
93-
declarationMap: true,
94-
outDir: 'dist',
95-
module: 'nodenext',
96-
types: [],
97-
},
85+
compilerOptions: { module: 'nodenext', types: [], noUnusedLocals: true },
9886
});
99-
const ws = workspace({ 'tsconfig.json': tsconfig, 'stackctl.config.ts': CLEAN });
100-
expect(await check(ws)).toEqual({ kind: 'ok' });
87+
const config = 'const unused = 1;\nexport default {};\n';
88+
const ws = workspace({ 'tsconfig.json': tsconfig, 'stackctl.config.ts': config });
89+
expect(await check(ws)).toContain('error TS6133');
90+
});
91+
92+
test('checks the config against declaration files, never the files themselves', async () => {
93+
const files = {
94+
'tsconfig.json': JSON.stringify({ compilerOptions: { module: 'nodenext', types: [], skipLibCheck: false } }), // oxfmt-ignore
95+
'api.d.ts': 'export declare const port: number;\nexport declare const broken: Missing;\n',
96+
'stackctl.config.ts':
97+
"import { port } from './api.js';\nexport const label: string = port;\n",
98+
};
99+
const printed = await check(workspace(files));
100+
expect(printed).toContain('stackctl.config.ts(2,14): error TS2322');
101+
expect(printed).not.toContain('api.d.ts');
101102
});
102103

103104
test("checks with stackctl's own flags when no tsconfig sits beside the config", async () => {
104-
expect(await check(workspace({ 'stackctl.config.ts': CLEAN }))).toEqual({ kind: 'ok' });
105-
const result = await check(workspace({ 'stackctl.config.ts': BROKEN }));
106-
expect(result.kind === 'errors' && result.output).toContain('error TS2322');
105+
expect(await check(workspace({ 'stackctl.config.ts': CLEAN }))).toBeNull();
106+
expect(await check(workspace({ 'stackctl.config.ts': BROKEN }))).toContain(TS2322);
107107
});
108108

109109
test('skips a JavaScript config, and a workspace without typescript', async () => {
110-
const js = workspace({ 'stackctl.config.mjs': 'export default {};\n' });
111-
expect(await check(js, 'stackctl.config.mjs')).toEqual({
112-
kind: 'skipped',
113-
reason: 'a JavaScript config',
114-
});
115-
const none = workspace({ 'stackctl.config.ts': BROKEN }, false);
116-
expect(await check(none)).toEqual({ kind: 'skipped', reason: 'no typescript installed' });
110+
expect(await check(workspace({ 'stackctl.config.mjs': 'export default {};\n' }))).toBeNull();
111+
expect(await check(workspace({ 'stackctl.config.ts': BROKEN }, false))).toBeNull();
117112
});
118113
});
119114

120-
describe('findTsc', () => {
121-
test('finds the tsc script of the typescript in the directory, never one above it', () => {
122-
const ws = workspace({});
123-
const sub = path.join(ws, 'apps', 'web');
124-
fs.mkdirSync(sub, { recursive: true });
125-
expect(findTsc(ws)).toBe(path.join(ws, 'node_modules', 'typescript', 'bin', 'tsc'));
126-
expect(findTsc(sub)).toBeNull();
127-
expect(findTsc(workspace({}, false))).toBeNull();
115+
describe('which tsc runs', () => {
116+
/**
117+
* A workspace whose `typescript` is a stand-in: its `bin/tsc` prints `from the script` and fails,
118+
* and `getExePath`, when given, is its `lib/getExePath.js`.
119+
*/
120+
function standIn(getExePath?: string): string {
121+
const ws = workspace({ 'tsconfig.json': TSCONFIG, 'stackctl.config.ts': CLEAN }, false);
122+
const pkg = path.join(ws, 'node_modules', 'typescript');
123+
fs.mkdirSync(path.join(pkg, 'bin'), { recursive: true });
124+
fs.writeFileSync(path.join(pkg, 'package.json'), '{ "type": "module" }\n');
125+
fs.writeFileSync(
126+
path.join(pkg, 'bin', 'tsc'),
127+
"process.stdout.write('from the script');\nprocess.exitCode = 2;\n",
128+
);
129+
if (getExePath !== undefined) {
130+
fs.mkdirSync(path.join(pkg, 'lib'));
131+
fs.writeFileSync(path.join(pkg, 'lib', 'getExePath.js'), getExePath);
132+
}
133+
return ws;
134+
}
135+
const fromScript = 'stackctl: stackctl.config.ts has type errors:\n\nfrom the script';
136+
137+
test('the binary getExePath.js names, as TypeScript 7 has it', async () => {
138+
const ws = standIn("export default () => new URL('./tsc-binary', import.meta.url).pathname;");
139+
const binary = path.join(ws, 'node_modules', 'typescript', 'lib', 'tsc-binary');
140+
fs.writeFileSync(binary, "#!/bin/sh\nprintf 'from the binary'\nexit 2\n", { mode: 0o755 });
141+
expect(await check(ws)).toBe(
142+
'stackctl: stackctl.config.ts has type errors:\n\nfrom the binary',
143+
);
128144
});
129-
});
130145

131-
describe('checkTsconfig', () => {
132-
test('extends the base, checks only the config and roots it at its directory', () => {
133-
expect(checkTsconfig('/repo/stackctl.config.ts', '/repo/tsconfig.json')).toEqual({
134-
extends: '/repo/tsconfig.json',
135-
compilerOptions: {
136-
noEmit: true,
137-
composite: false,
138-
incremental: false,
139-
tsBuildInfoFile: null,
140-
emitDeclarationOnly: false,
141-
declarationMap: false,
142-
rootDir: '/repo',
143-
},
144-
files: ['/repo/stackctl.config.ts'],
145-
include: [],
146-
});
146+
test('bin/tsc, with Node.js, without getExePath.js, as TypeScript 5 and 6 have it', async () => {
147+
expect(await check(standIn())).toBe(fromScript);
148+
});
149+
150+
test.each([
151+
['throws', 'export default () => { throw new Error("no binary"); };'],
152+
['names no file', "export default () => '/nonexistent/tsc';"],
153+
['returns no string', 'export default () => 42;'],
154+
['fails to load', 'export default ('],
155+
])('bin/tsc when getExePath.js %s', async (_what, source) => {
156+
expect(await check(standIn(source))).toBe(fromScript);
147157
});
148158
});

0 commit comments

Comments
 (0)