tsc-after 0.3.0 → 0.4.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.
package/README.md CHANGED
@@ -15,9 +15,21 @@ Rename `foo.ts` to `foo/index.ts`, and `dist/foo.js` lives on forever.
15
15
 
16
16
  ## Usage
17
17
 
18
+ In `package.json`, replace the clean-then-compile command:
19
+
20
+ ```diff
21
+ - rm -rf dist && tsc
22
+ + tsc && tsc-after
23
+ ```
24
+
25
+ Additional usage:
26
+
18
27
  ```sh
19
- # Preview for tsconfig.json; --verbose lists individual paths.
20
- tsc-after --dry --verbose
28
+ # Clean after compile; run after tsc build.
29
+ tsc-after
30
+
31
+ # Preview planned removals for tsconfig.json.
32
+ tsc-after --dry
21
33
 
22
34
  # Select a tsconfig file instead of the default.
23
35
  tsc-after --project tsconfig.build.json
@@ -26,37 +38,39 @@ tsc-after --project tsconfig.build.json
26
38
  tsc-after -p packages/core
27
39
  ```
28
40
 
29
- The project path must be inside the current working directory.
30
- Positional arguments and unknown flags are rejected.
31
-
32
- For a basic project with a dedicated `outDir`, `tsc-after` uses TypeScript's output-name API to identify expected outputs, removes other regular files in `outDir`, and removes directories left empty by cleanup.
33
- It skips symbolic links and entries on other devices.
34
- This behavior and its safety limits are not yet verified for every TypeScript configuration or output type.
41
+ `tsc-after` asks TypeScript which files the project emits, then removes every other regular file in `outDir` and `declarationDir`, along with directories left empty.
42
+ It skips symbolic links and entries on other devices inside `outDir` or `declarationDir`.
35
43
 
36
- `--dry` leaves files unchanged, but individual paths are currently printed only with `--verbose`; its summary also reports zero files removed rather than counting planned removals ([issue #8](https://github.com/michal-kocarek/tsc-after/issues/8)).
44
+ `--dry` lists planned removals without changing files.
45
+ Use `--verbose` to add individual removed and skipped entries.
37
46
 
38
47
  ## Limitations
39
48
 
40
- - `outDir` must be set and dedicated to TypeScript outputs.
41
- Other regular files there, including copied assets, are treated as stale.
42
- - By default, `tsc-after` reads `tsconfig.json` from the current directory and does not search parent directories.
43
- - `incremental`, `tsBuildInfoFile`, `composite`, `declarationDir`, and watch configurations are rejected.
44
- Project references are not followed.
45
- - Source files reached only through imports or `paths` aliases are not included when checking source/output overlap or expected outputs.
46
- Cleanup may delete those sources if they are inside `outDir`, or delete their emitted files as stale ([issue #2](https://github.com/michal-kocarek/tsc-after/issues/2)).
47
- - Cleanup confinement and source/output overlap checks are incomplete.
48
- Do not rely on the current checks to protect valuable files.
49
- - Handling of TypeScript configurations and emitted file types is incomplete and still needs verification.
49
+ `tsc-after` reads your tsconfig the way `tsc` does; this list covers only where it differs.
50
50
 
51
- Related open work: [configuration handling (#2)](https://github.com/michal-kocarek/tsc-after/issues/2), [incremental build state (#4)](https://github.com/michal-kocarek/tsc-after/issues/4), [cleanup safety (#6)](https://github.com/michal-kocarek/tsc-after/issues/6), and [output coverage (#7)](https://github.com/michal-kocarek/tsc-after/issues/7).
51
+ - `outDir` and `declarationDir` must hold only TypeScript outputs: anything else, including copied assets and tsconfig files, is removed as stale.
52
+ - Parent directories are not searched for `tsconfig.json`.
53
+ - `outFile`, `composite`, `incremental`, and `tsBuildInfoFile` ([#4](https://github.com/michal-kocarek/tsc-after/issues/4)) are rejected, and project references are not followed.
54
+ - Support for TypeScript versions 3.9 - 4.1 is limited:
55
+ - `rootDir` is required ([#15](https://github.com/michal-kocarek/tsc-after/issues/15)).
56
+ - 3.9 only: `emitDeclarationOnly` with `resolveJsonModule` and JSON source files, and `allowJs` with `jsx: preserve`, `declaration`, and `.jsx` source files are refused ([#15](https://github.com/michal-kocarek/tsc-after/issues/15)).
57
+ - TypeScript 7.1 beta support is experimental.
52
58
 
53
59
  Planned: `--copy`, `--exclude`, and `--watch`.
54
60
  See [`product.md`](./docs/product.md) for the roadmap.
55
61
 
62
+ ## Security measures
63
+
64
+ - Cleanup is refused unless `outDir` is set and `noEmit` is disabled.
65
+ - `outDir` and `declarationDir` must be inside, and not equal to, the current working directory.
66
+ - Cleanup is refused when `outDir` or `declarationDir` contains a source file of the project.
67
+ - Cleanup is refused when `outDir` or `declarationDir` is reached through a symbolic link.
68
+ - A `--project` path outside the current working directory is refused.
69
+
56
70
  ## Requirements
57
71
 
58
- - the project's tsconfig file must exist inside the current working directory (unlike `tsc`, it does not search parent directories for `tsconfig.json`)
59
- - source code must be compiled in dedicated `outDir` path
72
+ - Node.js 16.19.0 or later, including the latest LTS.
73
+ - TypeScript 3.9.10 through 7.x, including 7.1 beta (except 7.0, which has no API support).
60
74
 
61
75
  ## Exit codes
62
76
 
@@ -70,7 +84,6 @@ Wiping `outDir` before every build (`rm -rf dist && tsc`, `rimraf dist && tsc`,
70
84
  On GitHub, about 274k `package.json` files run `rm -rf dist` and another 199k run `rimraf dist` (see [`market-research.md`](./docs/market-research.md)).
71
85
 
72
86
  `tsc-after` is intended to remove only stale outputs rather than wiping `outDir` and rebuilding everything.
73
- Incremental builds are not supported.
74
87
 
75
88
  **Using a bundler such as tsup, Vite, or esbuild?**<br>
76
89
  They already clean up after themselves, so you probably don't need `tsc-after`.
package/dist/tscAfter.js CHANGED
@@ -5,6 +5,9 @@ import ts from "typescript";
5
5
  // src/common/errors.ts
6
6
  /** Error whose message is human-readable and printed to the user without a stack trace. */
7
7
  var UserError = class extends Error {};
8
+ function assertUnreachable(value) {
9
+ throw new Error("Unreachable code reached.", { cause: value });
10
+ }
8
11
  function isNodeErrorOf(error, errorClass, code) {
9
12
  if (!(error instanceof errorClass)) return false;
10
13
  if (code === void 0) return true;
@@ -110,63 +113,37 @@ function help() {
110
113
  ].join("\n\n"));
111
114
  }
112
115
  // src/common/paths.ts
113
- function isPathInside(dirPath, filePath) {
114
- const normalizedDirPath = ts.sys.useCaseSensitiveFileNames ? dirPath : dirPath.toLowerCase();
115
- const normalizedFilePath = ts.sys.useCaseSensitiveFileNames ? filePath : filePath.toLowerCase();
116
- const relativePath = path.relative(normalizedDirPath, normalizedFilePath);
117
- return relativePath === "" || !path.isAbsolute(relativePath) && relativePath !== ".." && !relativePath.startsWith(`..${path.sep}`);
116
+ function isPathInside(dirPath, filePath, useCaseSensitiveFileNames) {
117
+ const normalizedDirPath = normalizePathForComparison(dirPath, useCaseSensitiveFileNames);
118
+ const normalizedFilePath = normalizePathForComparison(filePath, useCaseSensitiveFileNames);
119
+ return normalizedDirPath === normalizedFilePath || normalizedFilePath.startsWith(normalizedDirPath.endsWith(path.sep) ? normalizedDirPath : `${normalizedDirPath}${path.sep}`);
118
120
  }
119
- // src/tasks/mainAction.ts
121
+ function normalizePathForComparison(filePath, useCaseSensitiveFileNames) {
122
+ const normalizedPath = path.resolve(filePath);
123
+ return useCaseSensitiveFileNames ? normalizedPath : normalizedPath.toLowerCase();
124
+ }
125
+ // src/common/cleanupRoots.ts
120
126
  const MISSING_OUT_DIR_ERROR = "outDir is not set in tsconfig.json; tsc-after only cleans a dedicated outDir. Set compilerOptions.outDir, e.g. \"dist\".";
121
- function mainAction(args) {
122
- const cwd = process.cwd();
123
- const projectAbsolutePath = path.resolve(cwd, args.values.project);
124
- if (!isPathInside(cwd, projectAbsolutePath)) throw new UserError(`Refusing to traverse outside current working directory to read tsconfig!`);
125
- const tsconfigAbsolutePath = fs.existsSync(projectAbsolutePath) && fs.statSync(projectAbsolutePath).isDirectory() ? path.join(projectAbsolutePath, "tsconfig.json") : projectAbsolutePath;
126
- if (!isPathInside(cwd, tsconfigAbsolutePath) || isPathInside(tsconfigAbsolutePath, cwd)) throw new UserError(`Refusing to traverse outside current working directory to read tsconfig!`);
127
- print(`Using tsconfig: ${path.relative(cwd, tsconfigAbsolutePath)}`);
128
- const formatHost = {
129
- getCanonicalFileName: (fileName) => fileName,
130
- getCurrentDirectory: () => cwd,
131
- getNewLine: () => ts.sys.newLine
132
- };
133
- const tsconfig = ts.getParsedCommandLineOfConfigFile(tsconfigAbsolutePath, void 0, {
134
- ...ts.sys,
135
- onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
136
- throw new UserError(ts.formatDiagnostics([diagnostic], formatHost).trimEnd());
137
- }
138
- });
139
- if (tsconfig === void 0) throw new UserError("Could not read tsconfig.json.");
140
- if (tsconfig.errors.length > 0) throw new UserError(ts.formatDiagnostics(tsconfig.errors, formatHost).trimEnd());
141
- if (tsconfig.options.outDir === void 0) throw new UserError(MISSING_OUT_DIR_ERROR);
142
- const outDir = tsconfig.options.outDir;
143
- const outDirAbsolutePath = path.resolve(outDir);
144
- const outDirRelativePath = path.relative(cwd, outDirAbsolutePath);
145
- if (!isPathInside(cwd, outDirAbsolutePath) || isPathInside(outDirAbsolutePath, cwd)) throw new UserError(`Refusing to traverse outside safe paths containing tsconfig to process outDir!`);
146
- if (tsconfig.options.incremental === true) throw new UserError("Incremental mode is not supported");
147
- if (tsconfig.options.tsBuildInfoFile !== void 0) throw new UserError("tsBuildInfoFile is not supported");
148
- if (tsconfig.options.composite === true) throw new UserError("Composite mode is not supported");
149
- if (tsconfig.options.project !== void 0) throw new UserError("Project mode is not supported");
150
- if (tsconfig.options.declarationDir !== void 0) throw new UserError("declarationDir is not supported");
151
- if (tsconfig.watchOptions) throw new UserError("Watch mode is not supported");
152
- const isInsideOutDir = (filePath) => isPathInside(outDirAbsolutePath, filePath) || isPathInside(outDirAbsolutePath, fs.realpathSync(filePath));
153
- for (const file of tsconfig.fileNames) if (isInsideOutDir(path.resolve(file))) throw new UserError(`Refusing to clean outDir '${outDirRelativePath}': it contains source file '${path.relative(cwd, file)}'.`);
154
- const configFile = tsconfig.options["configFile"];
155
- const configFilePaths = [configFile?.fileName ?? tsconfigAbsolutePath, ...configFile?.extendedSourceFiles ?? []];
156
- for (const file of configFilePaths) if (isInsideOutDir(path.resolve(file))) throw new UserError(`Refusing to clean outDir '${outDirRelativePath}': it contains config file '${path.relative(cwd, file)}'.`);
157
- if (args.values.noClean) return;
158
- const expectedOutDirPaths = /* @__PURE__ */ new Set();
159
- for (const file of tsconfig.fileNames) ts.getOutputFileNames(tsconfig, file, !ts.sys.useCaseSensitiveFileNames).forEach((fiePath) => expectedOutDirPaths.add(fiePath));
127
+ const DECLARATION_DISABLED_ERROR = "Refusing to clean declarationDir because declaration is not enabled.";
128
+ function readCleanupRoot(root, expectedOutputPaths, useCaseSensitiveFileNames) {
129
+ try {
130
+ fs.lstatSync(root.path);
131
+ } catch (error) {
132
+ if (isNodeErrorOf(error, Error, "ENOENT")) return [];
133
+ throw error;
134
+ }
135
+ const normalizedExpectedOutputPaths = new Set([...expectedOutputPaths].map((filePath) => normalizePathForComparison(filePath, useCaseSensitiveFileNames)));
136
+ return readDir(root.path);
160
137
  function readDir(dirPath) {
161
138
  const verdicts = [];
162
139
  const stat = fs.lstatSync(dirPath);
163
140
  if (!stat.isDirectory()) throw new UserError(`Not a directory ${dirPath}!`);
164
141
  let dirIsEmpty = true;
165
- for (const child of fs.readdirSync(dirPath)) {
142
+ for (const child of fs.readdirSync(dirPath).sort()) {
166
143
  const fullPath = path.join(dirPath, child);
167
144
  const fullPathStat = fs.lstatSync(fullPath);
168
145
  if (fullPathStat.dev !== stat.dev) {
169
- if (args.values.verbose) verdicts.push({
146
+ verdicts.push({
170
147
  path: fullPath,
171
148
  reason: "different device",
172
149
  type: "skipped"
@@ -175,7 +152,7 @@ function mainAction(args) {
175
152
  continue;
176
153
  }
177
154
  if (fullPathStat.isSymbolicLink()) {
178
- if (args.values.verbose) verdicts.push({
155
+ verdicts.push({
179
156
  path: fullPath,
180
157
  reason: "symbolic link",
181
158
  type: "skipped"
@@ -184,8 +161,8 @@ function mainAction(args) {
184
161
  continue;
185
162
  }
186
163
  if (fullPathStat.isFile()) {
187
- if (expectedOutDirPaths.has(fullPath)) {
188
- if (args.values.verbose) verdicts.push({
164
+ if (normalizedExpectedOutputPaths.has(normalizePathForComparison(fullPath, useCaseSensitiveFileNames))) {
165
+ verdicts.push({
189
166
  path: fullPath,
190
167
  reason: "expected output file",
191
168
  type: "skipped"
@@ -200,11 +177,16 @@ function mainAction(args) {
200
177
  continue;
201
178
  }
202
179
  if (fullPathStat.isDirectory()) {
203
- const result = readDir(fullPath);
204
- verdicts.push(...result.verdicts);
205
- if (!result.dirIsEmpty) dirIsEmpty = false;
180
+ const childVerdicts = readDir(fullPath);
181
+ verdicts.push(...childVerdicts);
182
+ if (childVerdicts.some((verdict) => verdict.type === "skipped")) dirIsEmpty = false;
206
183
  continue;
207
184
  }
185
+ verdicts.push({
186
+ path: fullPath,
187
+ reason: "unknown file type",
188
+ type: "skipped"
189
+ });
208
190
  dirIsEmpty = false;
209
191
  }
210
192
  if (dirIsEmpty) verdicts.push({
@@ -216,59 +198,171 @@ function mainAction(args) {
216
198
  reason: "directory not empty",
217
199
  type: "skipped"
218
200
  });
219
- return {
220
- dirIsEmpty,
221
- verdicts
222
- };
201
+ return verdicts;
223
202
  }
224
- let outDirExists = true;
225
- try {
226
- fs.lstatSync(outDir);
227
- } catch (error) {
228
- if (!isNodeErrorOf(error, Error, "ENOENT")) throw error;
229
- outDirExists = false;
203
+ }
204
+ function resolveCleanupRoots(project, cwd, useCaseSensitiveFileNames) {
205
+ if (project.options.outDir === void 0) throw new UserError(MISSING_OUT_DIR_ERROR);
206
+ const outDirAbsolutePath = path.resolve(cwd, project.options.outDir);
207
+ const roots = [{
208
+ name: "outDir",
209
+ path: outDirAbsolutePath,
210
+ relativePath: path.relative(cwd, outDirAbsolutePath)
211
+ }];
212
+ if (project.options.declarationDir !== void 0) {
213
+ if (project.options.declaration !== true) throw new UserError(DECLARATION_DISABLED_ERROR);
214
+ const declarationDir = path.resolve(cwd, project.options.declarationDir);
215
+ roots.push({
216
+ name: "declarationDir",
217
+ path: declarationDir,
218
+ relativePath: path.relative(cwd, declarationDir)
219
+ });
230
220
  }
231
- if (outDirExists && fs.realpathSync(outDir) !== path.resolve(outDir)) throw new UserError(`Refusing to clean outDir through a symbolic link: ${outDirRelativePath}!`);
232
- const result = outDirExists ? readDir(outDir) : { verdicts: [] };
233
- if (args.values.verbose) for (const verdict of result.verdicts) switch (verdict.type) {
234
- case "removeDir":
235
- print(`Remove empty directory: ${verdict.path}`);
236
- break;
237
- case "removeFile":
238
- print(`Remove file: ${verdict.path}`);
239
- break;
240
- case "skipped": print(`Skipped (${verdict.reason}): ${verdict.path}`);
221
+ for (const root of roots) {
222
+ if (!isPathInside(cwd, root.path, useCaseSensitiveFileNames) || isPathInside(root.path, cwd, useCaseSensitiveFileNames)) throw new UserError(`Refusing to traverse outside safe paths containing tsconfig to process ${root.name}!`);
223
+ let componentPath = cwd;
224
+ for (const component of root.relativePath.split(path.sep)) {
225
+ componentPath = path.join(componentPath, component);
226
+ let stat;
227
+ try {
228
+ stat = fs.lstatSync(componentPath);
229
+ } catch (error) {
230
+ if (isNodeErrorOf(error, Error, "ENOENT")) break;
231
+ throw error;
232
+ }
233
+ if (stat.isSymbolicLink()) throw new UserError(`Refusing to clean ${root.name} through a symbolic link: ${root.relativePath}!`);
234
+ if (!stat.isDirectory()) throw new UserError(notADirectoryError(root, path.relative(cwd, componentPath)));
235
+ }
236
+ for (const file of project.programFileNames) {
237
+ const filePath = path.resolve(cwd, file);
238
+ let realFilePath = filePath;
239
+ try {
240
+ realFilePath = fs.realpathSync(filePath);
241
+ } catch (error) {
242
+ if (!isNodeErrorOf(error, Error, "ENOENT")) throw error;
243
+ }
244
+ if (isPathInside(root.path, filePath, useCaseSensitiveFileNames) || isPathInside(root.path, realFilePath, useCaseSensitiveFileNames)) throw new UserError(`Refusing to clean ${root.name} '${root.relativePath}': it contains source file '${path.relative(cwd, file)}'.`);
245
+ }
241
246
  }
242
- let removedDirs = 0;
243
- let removedFiles = 0;
244
- if (!args.values.dry) for (const verdict of result.verdicts) switch (verdict.type) {
245
- case "removeDir":
246
- fs.rmdirSync(verdict.path);
247
- removedDirs++;
248
- break;
249
- case "removeFile":
250
- fs.rmSync(verdict.path, { recursive: false });
251
- removedFiles++;
247
+ return roots.filter((root) => root.name === "outDir" || !isPathInside(outDirAbsolutePath, root.path, useCaseSensitiveFileNames));
248
+ }
249
+ function notADirectoryError(root, componentPath) {
250
+ return `Refusing to clean ${root.name} '${root.relativePath}': '${componentPath}' is not a directory.`;
251
+ }
252
+ const TYPESCRIPT_4_0 = 4e6;
253
+ const TYPESCRIPT_4_2 = 4002e3;
254
+ function parseTypeScriptVersion(version) {
255
+ const match = /^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-[-.0-9A-Za-z]+)?(?:\+[-.0-9A-Za-z]+)?$/u.exec(version);
256
+ if (match?.groups === void 0) return NaN;
257
+ const { major, minor, patch } = match.groups;
258
+ return Number(major) * 1e6 + Number(minor) * 1e3 + Number(patch);
259
+ }
260
+ const typescriptVersion = parseTypeScriptVersion(ts.version);
261
+ // src/common/typescript/loadCompiler.ts
262
+ async function loadCompiler() {
263
+ if (typescriptVersion < 3009e3) throw new UserError("TypeScript 3.8 and earlier are not supported. Use TypeScript 3.9 or later.");
264
+ if (typescriptVersion < 7e6) {
265
+ const { TypeScriptPre7Compiler } = await import("./typescriptPre7Compiler-B9gRUB0n.js");
266
+ return new TypeScriptPre7Compiler();
252
267
  }
253
- if (args.values.dry || removedDirs > 0 || removedFiles > 0) print(`${binName}: ${args.values.dry ? "Would remove" : "Removed"} ${removedFiles.toFixed()} files${removedDirs > 0 ? ` and ${removedDirs.toFixed()} empty directories` : ""} from ${styleText("italic", outDirRelativePath)}`);
268
+ if (typescriptVersion < 7001e3) throw new UserError("TypeScript 7.0 is not supported. Use TypeScript 7.1 or later.");
269
+ const { TypeScript7Compiler } = await import("./typescript7Compiler-CKul_b13.js");
270
+ return TypeScript7Compiler.create();
271
+ }
272
+ // src/tasks/mainAction.ts
273
+ const NO_EMIT_ERROR = "Refusing to clean outDir because noEmit is enabled.";
274
+ async function mainAction(args) {
275
+ const cwd = process.cwd();
276
+ const compiler = await loadCompiler();
277
+ let cleanupRoots;
278
+ let expectedOutDirPaths;
279
+ let outDirAbsolutePath;
280
+ try {
281
+ const isPathInsideWithCompiler = (dirPath, filePath) => isPathInside(dirPath, filePath, compiler.useCaseSensitiveFileNames);
282
+ const projectAbsolutePath = path.resolve(cwd, args.values.project);
283
+ if (!isPathInsideWithCompiler(cwd, projectAbsolutePath)) throw new UserError(`Refusing to traverse outside current working directory to read tsconfig!`);
284
+ const tsconfigAbsolutePath = fs.existsSync(projectAbsolutePath) && fs.statSync(projectAbsolutePath).isDirectory() ? path.join(projectAbsolutePath, "tsconfig.json") : projectAbsolutePath;
285
+ if (!isPathInsideWithCompiler(cwd, tsconfigAbsolutePath) || isPathInsideWithCompiler(tsconfigAbsolutePath, cwd)) throw new UserError(`Refusing to traverse outside current working directory to read tsconfig!`);
286
+ print(`Using tsconfig: ${path.relative(cwd, tsconfigAbsolutePath)}`);
287
+ const project = compiler.parseProject(tsconfigAbsolutePath);
288
+ if (project.options.noEmit === true) throw new UserError(NO_EMIT_ERROR);
289
+ if (project.options.outFile !== void 0) throw new UserError("outFile is not supported");
290
+ if (project.options.incremental === true) throw new UserError("Incremental mode is not supported");
291
+ if (project.options.tsBuildInfoFile !== void 0) throw new UserError("tsBuildInfoFile is not supported");
292
+ if (project.options.composite === true) throw new UserError("Composite mode is not supported");
293
+ if (project.options.project !== void 0) throw new UserError("Project mode is not supported");
294
+ cleanupRoots = resolveCleanupRoots(project, cwd, compiler.useCaseSensitiveFileNames);
295
+ const outDirRoot = cleanupRoots.find((root) => root.name === "outDir");
296
+ if (outDirRoot === void 0) throw new Error("Missing outDir cleanup root.");
297
+ outDirAbsolutePath = outDirRoot.path;
298
+ if (args.values.noClean) return;
299
+ expectedOutDirPaths = compiler.getOutputPaths(project);
300
+ } finally {
301
+ compiler.close();
302
+ }
303
+ const results = cleanupRoots.map((root) => readCleanupRoot(root, expectedOutDirPaths, compiler.useCaseSensitiveFileNames));
304
+ const { dry, verbose } = args.values;
305
+ const removeVerb = dry ? "Would remove" : "Removed";
306
+ for (const [index, root] of cleanupRoots.entries()) {
307
+ const result = results[index];
308
+ if (result === void 0) throw new Error("Missing cleanup result.");
309
+ let fileCount = 0;
310
+ let dirCount = 0;
311
+ for (const verdict of result) {
312
+ if (root.name === "declarationDir" && isPathInside(outDirAbsolutePath, verdict.path, compiler.useCaseSensitiveFileNames)) continue;
313
+ const displayPath = path.relative(cwd, verdict.path);
314
+ switch (verdict.type) {
315
+ case "removeDir":
316
+ if (!dry) try {
317
+ fs.rmdirSync(verdict.path);
318
+ } catch (error) {
319
+ if (verdict.path === root.path && isNodeErrorOf(error, Error, "EBUSY")) {
320
+ if (verbose) print(`Skipped (busy directory): ${displayPath}`);
321
+ break;
322
+ }
323
+ throw error;
324
+ }
325
+ dirCount++;
326
+ if (dry || verbose) print(`${removeVerb} empty directory: ${displayPath}`);
327
+ break;
328
+ case "removeFile":
329
+ if (!dry) fs.rmSync(verdict.path, { recursive: false });
330
+ fileCount++;
331
+ if (dry || verbose) print(`${removeVerb} file: ${displayPath}`);
332
+ break;
333
+ case "skipped":
334
+ if (verbose) print(`Skipped (${verdict.reason}): ${displayPath}`);
335
+ break;
336
+ default: assertUnreachable(verdict);
337
+ }
338
+ }
339
+ const parts = [];
340
+ if (fileCount > 0) parts.push(formatCount(fileCount, "file", "files"));
341
+ if (dirCount > 0) parts.push(formatCount(dirCount, "empty directory", "empty directories"));
342
+ if (parts.length > 0) print(`${binName}: ${removeVerb} ${parts.join(" and ")} from ${styleText("italic", root.relativePath)}`);
343
+ else if (dry || cleanupRoots.length > 1) print(`${binName}: Nothing to remove from ${styleText("italic", root.relativePath)}`);
344
+ }
345
+ }
346
+ function formatCount(count, singular, plural) {
347
+ return `${count.toFixed()} ${count === 1 ? singular : plural}`;
254
348
  }
255
349
  // package.json
256
- var version$1 = "0.3.0";
350
+ var version$1 = "0.4.1";
257
351
  // src/tasks/version.ts
258
352
  function version() {
259
353
  print(`${binName}/${version$1} ${process.platform}-${process.arch} node-${process.versions.node} typescript-${ts.version}`);
260
354
  }
261
355
  // src/entrypoints/tscAfter.ts
262
- function main() {
356
+ async function main() {
263
357
  try {
264
358
  const args = parseArgs(process.argv.slice(2));
265
359
  if (args.values.version) version();
266
360
  else if (args.values.help) help();
267
- else mainAction(args);
361
+ else await mainAction(args);
268
362
  } catch (error) {
269
363
  if (!(error instanceof UserError)) throw error;
270
364
  printError(error.message);
271
365
  }
272
366
  }
273
367
  main();
274
- export {};
368
+ export { UserError as i, TYPESCRIPT_4_2 as n, typescriptVersion as r, TYPESCRIPT_4_0 as t };
@@ -0,0 +1,177 @@
1
+ import fs from "node:fs";
2
+ import { i as UserError } from "./tscAfter.js";
3
+ import path from "node:path";
4
+ // src/common/typescript/outputPaths.ts
5
+ const declarationFileExtensions = [
6
+ ".d.ts",
7
+ ".d.mts",
8
+ ".d.cts"
9
+ ];
10
+ const esmFileExtensions = [".mts", ".mjs"];
11
+ const cjsFileExtensions = [".cts", ".cjs"];
12
+ function getOutputFileNames(options, fileName) {
13
+ const sourcePath = path.resolve(fileName);
14
+ const sourceExtension = path.extname(sourcePath);
15
+ if (isDeclarationFile(sourcePath)) return [];
16
+ const isJsonFile = sourceExtension === ".json";
17
+ if ((sourceExtension === ".js" || sourceExtension === ".jsx" || sourceExtension === ".mjs" || sourceExtension === ".cjs") && options.allowJs !== true) return [];
18
+ const outputFileNames = [];
19
+ const outputPath = getOutputPath(sourcePath, resolveOptionPath(options.outDir, options.configFilePath), options.rootDir, options.configFilePath);
20
+ if (isJsonFile) {
21
+ if (options.emitDeclarationOnly !== true) outputFileNames.push(outputPath);
22
+ return outputFileNames;
23
+ }
24
+ const javaScriptExtension = getJavaScriptExtension(sourceExtension, options.jsx);
25
+ if (javaScriptExtension === void 0) return [];
26
+ if (options.emitDeclarationOnly !== true) {
27
+ const javaScriptPath = replaceExtension(outputPath, javaScriptExtension);
28
+ outputFileNames.push(javaScriptPath);
29
+ if (options.sourceMap === true) outputFileNames.push(`${javaScriptPath}.map`);
30
+ }
31
+ if (options.declaration === true || options.composite === true) {
32
+ const declarationPath = replaceExtension(getOutputPath(sourcePath, resolveOptionPath(options.declarationDir ?? options.outDir, options.configFilePath), options.rootDir, options.configFilePath), getDeclarationExtension(sourceExtension));
33
+ outputFileNames.push(declarationPath);
34
+ if (options.declarationMap === true) outputFileNames.push(`${declarationPath}.map`);
35
+ }
36
+ return outputFileNames;
37
+ }
38
+ function getDeclarationExtension(sourceExtension) {
39
+ if (esmFileExtensions.includes(sourceExtension)) return ".d.mts";
40
+ if (cjsFileExtensions.includes(sourceExtension)) return ".d.cts";
41
+ return ".d.ts";
42
+ }
43
+ function getJavaScriptExtension(sourceExtension, jsx) {
44
+ if (sourceExtension === ".tsx" || sourceExtension === ".jsx") return jsx === "preserve" ? ".jsx" : ".js";
45
+ if (sourceExtension === ".ts" || sourceExtension === ".js") return ".js";
46
+ if (sourceExtension === ".mts") return ".mjs";
47
+ if (sourceExtension === ".cts") return ".cjs";
48
+ if (sourceExtension === ".mjs" || sourceExtension === ".cjs") return sourceExtension;
49
+ }
50
+ function getOutputPath(sourcePath, outputDirectory, rootDir, configFilePath) {
51
+ if (outputDirectory === void 0) return sourcePath;
52
+ const resolvedRootDir = path.resolve(path.dirname(configFilePath), rootDir ?? ".");
53
+ return path.resolve(outputDirectory, path.relative(resolvedRootDir, sourcePath));
54
+ }
55
+ function isDeclarationFile(fileName) {
56
+ return declarationFileExtensions.some((extension) => fileName.endsWith(extension)) || /\.d\..+\.ts$/u.test(path.basename(fileName));
57
+ }
58
+ function replaceExtension(fileName, extension) {
59
+ return `${fileName.slice(0, -path.extname(fileName).length)}${extension}`;
60
+ }
61
+ function resolveOptionPath(optionPath, configFilePath) {
62
+ return optionPath === void 0 ? void 0 : path.resolve(path.dirname(configFilePath), optionPath);
63
+ }
64
+ // src/common/typescript/typescript7Compiler.ts
65
+ const syncModuleSpecifier = "typescript/sync";
66
+ /**
67
+ * Uses the `typescript/sync` API for TypeScript 7.1 and later.
68
+ * The documented synchronous client fits this synchronous compiler contract.
69
+ */
70
+ var TypeScript7Compiler = class TypeScript7Compiler {
71
+ useCaseSensitiveFileNames;
72
+ api;
73
+ cachedProject;
74
+ isClosed = false;
75
+ program;
76
+ projects = /* @__PURE__ */ new WeakMap();
77
+ typescriptSync;
78
+ constructor(typescriptSync, api) {
79
+ this.typescriptSync = typescriptSync;
80
+ this.api = api;
81
+ this.useCaseSensitiveFileNames = api.getCanonicalFileName("a") !== api.getCanonicalFileName("A");
82
+ }
83
+ static async create() {
84
+ const typescriptSync = await loadTypeScript7SyncModule();
85
+ const api = new typescriptSync.API();
86
+ try {
87
+ api.parseCommandLine([]);
88
+ return new TypeScript7Compiler(typescriptSync, api);
89
+ } catch (error) {
90
+ api.close();
91
+ throw error;
92
+ }
93
+ }
94
+ close() {
95
+ if (this.isClosed) return;
96
+ this.isClosed = true;
97
+ const program = this.program;
98
+ this.program = void 0;
99
+ this.cachedProject = void 0;
100
+ try {
101
+ program?.dispose();
102
+ } finally {
103
+ this.api.close();
104
+ }
105
+ }
106
+ getOutputPaths(project) {
107
+ this.assertOpen();
108
+ const config = this.projects.get(project);
109
+ if (config === void 0) throw new Error("Project was not parsed by this compiler.");
110
+ if (this.cachedProject !== project) {
111
+ const previousProgram = this.program;
112
+ this.program = void 0;
113
+ this.cachedProject = void 0;
114
+ previousProgram?.dispose();
115
+ this.program = this.api.createProgram(config.fileNames, config.options);
116
+ this.cachedProject = project;
117
+ }
118
+ const program = this.program;
119
+ if (program === void 0) throw new Error("Could not create TypeScript program.");
120
+ const configFilePath = project.configFilePath;
121
+ const outputOptions = {
122
+ ...config.options,
123
+ configFilePath,
124
+ jsx: config.options.jsx === this.typescriptSync.JsxEmit.Preserve ? "preserve" : void 0
125
+ };
126
+ const outputPaths = program.getSourceFileNames().filter((fileName) => {
127
+ const metadata = program.getSourceFileMetadata(fileName);
128
+ return metadata !== void 0 && !metadata.isDefaultLibrary && !metadata.isFromExternalLibrary;
129
+ }).flatMap((fileName) => getOutputFileNames(outputOptions, fileName));
130
+ return new Set(outputPaths);
131
+ }
132
+ parseProject(configFilePath) {
133
+ this.assertOpen();
134
+ try {
135
+ fs.readFileSync(configFilePath);
136
+ } catch {
137
+ throw new UserError(`error TS5083: Cannot read file '${configFilePath}'.`);
138
+ }
139
+ const checkDiagnostics = (diagnostics) => {
140
+ if (diagnostics.length === 0) return;
141
+ throw new UserError(this.typescriptSync.formatDiagnosticsWithColorAndContext(diagnostics, {
142
+ getCanonicalFileName: (fileName) => this.api.getCanonicalFileName(fileName),
143
+ getCurrentDirectory: () => this.api.getCurrentDirectory(),
144
+ getNewLine: () => this.api.getNewLine()
145
+ }).trimEnd());
146
+ };
147
+ const checkConfigFile = (filePath) => {
148
+ const result = this.api.readConfigFile(filePath);
149
+ if (result.error !== void 0) checkDiagnostics([result.error]);
150
+ };
151
+ checkConfigFile(configFilePath);
152
+ const config = this.api.parseConfigFile(configFilePath);
153
+ checkDiagnostics(config.errors);
154
+ const program = this.api.createProgram(config.fileNames, config.options);
155
+ const project = {
156
+ configFilePath,
157
+ fileNames: config.fileNames,
158
+ options: config.options,
159
+ programFileNames: program.getSourceFileNames().filter((fileName) => {
160
+ const metadata = program.getSourceFileMetadata(fileName);
161
+ return metadata !== void 0 && !metadata.isDefaultLibrary && !metadata.isFromExternalLibrary;
162
+ })
163
+ };
164
+ this.program?.dispose();
165
+ this.program = program;
166
+ this.cachedProject = project;
167
+ this.projects.set(project, config);
168
+ return project;
169
+ }
170
+ assertOpen() {
171
+ if (this.isClosed) throw new Error("Compiler is closed.");
172
+ }
173
+ };
174
+ async function loadTypeScript7SyncModule() {
175
+ return await import(syncModuleSpecifier);
176
+ }
177
+ export { TypeScript7Compiler };
@@ -0,0 +1,68 @@
1
+ import ts from "typescript";
2
+ import { i as UserError, r as typescriptVersion } from "./tscAfter.js";
3
+ // src/common/typescript/typescriptPre7Compiler.ts
4
+ /** Uses the `typescript` API for TypeScript 3.9 through 6.x. */
5
+ var TypeScriptPre7Compiler = class {
6
+ useCaseSensitiveFileNames;
7
+ parsedCommandLines = /* @__PURE__ */ new WeakMap();
8
+ constructor() {
9
+ this.useCaseSensitiveFileNames = ts.sys.useCaseSensitiveFileNames;
10
+ }
11
+ close() {}
12
+ getOutputPaths(project) {
13
+ const parsedCommandLine = this.parsedCommandLines.get(project);
14
+ if (parsedCommandLine === void 0) throw new Error("Project was not parsed by this compiler.");
15
+ if (typescriptVersion < 4002e3 && parsedCommandLine.options.rootDir === void 0) throw new UserError("Refusing to clean outDir: TypeScript 3.9 through 4.1 require rootDir to be set.");
16
+ const emittableFileNames = project.programFileNames.filter((fileName) => !isDeclarationFileName(fileName));
17
+ if (typescriptVersion < 4e6 && parsedCommandLine.options.emitDeclarationOnly === true && parsedCommandLine.options.resolveJsonModule === true && emittableFileNames.some((fileName) => fileName.endsWith(".json"))) throw new UserError("Refusing to clean outDir: TypeScript 3.9 cannot safely determine outputs for emitDeclarationOnly with resolveJsonModule.");
18
+ if (typescriptVersion < 4e6 && parsedCommandLine.options.allowJs === true && parsedCommandLine.options.jsx === ts.JsxEmit.Preserve && parsedCommandLine.options.declaration === true && emittableFileNames.some((fileName) => fileName.endsWith(".jsx"))) throw new UserError("Refusing to clean outDir: TypeScript 3.9 cannot safely determine outputs for allowJs JSX preserve with declaration.");
19
+ const outputCommandLine = {
20
+ ...parsedCommandLine,
21
+ fileNames: emittableFileNames
22
+ };
23
+ const outputPaths = /* @__PURE__ */ new Set();
24
+ for (const fileName of emittableFileNames) for (const outputPath of ts.getOutputFileNames(outputCommandLine, fileName, !this.useCaseSensitiveFileNames)) outputPaths.add(outputPath);
25
+ return outputPaths;
26
+ }
27
+ parseProject(configFilePath) {
28
+ const formatHost = {
29
+ getCanonicalFileName: (fileName) => fileName,
30
+ getCurrentDirectory: () => process.cwd(),
31
+ getNewLine: () => ts.sys.newLine
32
+ };
33
+ const checkConfigFile = (filePath) => {
34
+ const config = ts.readConfigFile(filePath.replaceAll("\\", "/"), (name) => ts.sys.readFile(name));
35
+ if (config.error !== void 0) throw new UserError(ts.formatDiagnostics([config.error], formatHost).trimEnd());
36
+ };
37
+ checkConfigFile(configFilePath);
38
+ const parsedCommandLine = ts.getParsedCommandLineOfConfigFile(configFilePath, void 0, {
39
+ ...ts.sys,
40
+ onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
41
+ throw new UserError(ts.formatDiagnostics([diagnostic], formatHost).trimEnd());
42
+ }
43
+ });
44
+ if (parsedCommandLine === void 0) throw new UserError("Could not read tsconfig.json.");
45
+ if (parsedCommandLine.errors.length > 0) throw new UserError(ts.formatDiagnostics(parsedCommandLine.errors, formatHost).trimEnd());
46
+ const configFileOption = parsedCommandLine.options["configFile"];
47
+ const configFile = isConfigFileMetadata(configFileOption) ? configFileOption : void 0;
48
+ for (const filePath of configFile?.extendedSourceFiles ?? []) checkConfigFile(filePath);
49
+ const program = ts.createProgram(parsedCommandLine.fileNames, parsedCommandLine.options);
50
+ const project = {
51
+ configFilePath: configFile?.fileName ?? configFilePath,
52
+ fileNames: parsedCommandLine.fileNames,
53
+ options: parsedCommandLine.options,
54
+ programFileNames: program.getSourceFiles().filter((sourceFile) => !program.isSourceFileDefaultLibrary(sourceFile) && !program.isSourceFileFromExternalLibrary(sourceFile)).map((sourceFile) => sourceFile.fileName)
55
+ };
56
+ this.parsedCommandLines.set(project, parsedCommandLine);
57
+ return project;
58
+ }
59
+ };
60
+ function isConfigFileMetadata(value) {
61
+ if (typeof value !== "object" || value === null || !("fileName" in value) || typeof value.fileName !== "string") return false;
62
+ if ("extendedSourceFiles" in value && value.extendedSourceFiles !== void 0) return Array.isArray(value.extendedSourceFiles) && value.extendedSourceFiles.every((fileName) => typeof fileName === "string");
63
+ return true;
64
+ }
65
+ function isDeclarationFileName(fileName) {
66
+ return fileName.endsWith(".d.ts") || fileName.endsWith(".d.mts") || fileName.endsWith(".d.cts");
67
+ }
68
+ export { TypeScriptPre7Compiler };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsc-after",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Remove stale build output that tsc leaves behind when you delete or rename source files. Tsconfig-aware: just run tsc && tsc-after. 🧹",
5
5
  "keywords": [
6
6
  "build",
@@ -60,6 +60,7 @@
60
60
  "@eslint-community/eslint-plugin-eslint-comments": "4.8.1",
61
61
  "@eslint/js": "10.0.1",
62
62
  "@eslint/markdown": "9.0.0",
63
+ "@eslint/shell": "0.1.2",
63
64
  "@release-it/conventional-changelog": "12.0.2",
64
65
  "@tsconfig/node-lts": "26.0.1",
65
66
  "@tsconfig/node-ts": "23.6.5",
@@ -93,11 +94,12 @@
93
94
  "release-it": "21.1.2",
94
95
  "tsdown": "0.23.7",
95
96
  "typescript": "6.0.3",
97
+ "typescript-7": "npm:typescript@7.1.0-beta",
96
98
  "typescript-eslint": "8.73.0",
97
99
  "vitest": "5.1.1"
98
100
  },
99
101
  "peerDependencies": {
100
- "typescript": ">=5.9.3"
102
+ "typescript": ">=3.9.10 <7 || >=7.1.0-beta <8"
101
103
  },
102
104
  "packageManager": "pnpm@12.21.0",
103
105
  "engines": {