Open History to see the last commit
1#!/usr/bin/env node
2// Runs CI's unused-code check as one cached Knip pass: files and dependencies
3// everywhere, unused exports in the workspaces that are kept clean of them.
4
5import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
6import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import * as Digest from "effect/crypto/Digest";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as Schema from "effect/Schema";
14import * as Stream from "effect/Stream";
15import { Command, Flag } from "effect/cli";
16import { ChildProcess, ChildProcessSpawner } from "effect/process";
17
18const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
19
20const EXPORT_WORKSPACES = [
21 "apps/server",
22 "apps/desktop",
23 "apps/web",
24 "packages/client-runtime",
25 "packages/contracts",
26 "packages/effect-acp",
27 "packages/effect-codex-app-server",
28 "packages/shared",
29 "packages/ssh",
30 "packages/tailscale",
31 "packages/provider-core",
32 "packages/provider-acp",
33 "packages/provider-acp-registry",
34 "packages/provider-testing",
35 "packages/provider-pi",
36 "packages/provider-muse",
37 "packages/provider-opencode",
38 "packages/provider-cursor",
39 "packages/provider-fx",
40 "packages/provider-kiro",
41 "packages/secret-provider-core",
42 "packages/secret-provider-definitions",
43 "packages/secret-provider-onepassword",
44 "packages/source-control-core",
45 "packages/source-control-cursor-origin",
46 "packages/source-control-definitions",
47 "packages/source-control-azure-devops",
48 "packages/source-control-bitbucket",
49 "packages/source-control-forgejo",
50 "packages/source-control-gitcafe",
51 "packages/source-control-github",
52 "packages/source-control-gitlab",
53 "packages/source-control-tanstack-source",
54 "packages/source-control-testing",
55];
56
57// Files that decide how an import resolves or what Knip reports, beyond the
58// source file that holds the import.
59const RESOLUTION_FILE =
60 /(^|\/)(package\.json|tsconfig[^/]*\.json|knip\.jsonc?|\.gitignore|pnpm-lock\.yaml|pnpm-workspace\.yaml)$|^patches\//;
61
62// Knip's cache and the schema verdicts each trust the contents of the files
63// they read, so neither notices an unchanged import resolving elsewhere. Both
64// are kept only while this is unchanged: the file list, manifests, tsconfigs,
65// installed packages and these scripts. None (git failed) runs uncached.
66const fingerprint = Effect.fn("knipCheck.fingerprint")(function* (
67 cwd: string,
68 scripts: ReadonlyArray<string>,
69) {
70 const fs = yield* FileSystem.FileSystem;
71 const path = yield* Path.Path;
72 const digest = yield* Digest.Digest;
73 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
74 // Untracked files count and ignored ones do not, as for Knip. A tracked file
75 // deleted from disk is listed a second time by --deleted.
76 const [files, exitCode] = yield* Effect.scoped(
77 Effect.gen(function* () {
78 const handle = yield* spawner.spawn(
79 ChildProcess.make(
80 "git",
81 ["ls-files", "--cached", "--others", "--deleted", "--exclude-standard", "-z"],
82 { cwd },
83 ),
84 );
85 return yield* Effect.all(
86 [Stream.mkString(Stream.decodeText(handle.stdout)), handle.exitCode],
87 {
88 concurrency: 2,
89 },
90 );
91 }),
92 ).pipe(Effect.orElseSucceed(() => ["", 1] as const));
93 if (exitCode !== 0) return Option.none<string>();
94
95 const contents = yield* Effect.forEach(
96 [
97 ...files
98 .split("\0")
99 .filter((file) => RESOLUTION_FILE.test(file))
100 .map((file) => path.join(cwd, file)),
101 path.join(cwd, "node_modules/.pnpm/lock.yaml"),
102 ...scripts,
103 ],
104 (file) =>
105 fs.readFile(file).pipe(
106 Effect.flatMap((bytes) => digest.digestHex(Digest.sha256, bytes)),
107 Effect.orElseSucceed(() => "missing"),
108 Effect.map((hash) => `${file}\0${hash}`),
109 ),
110 { concurrency: 32 },
111 );
112 return Option.some(
113 yield* digest.digestHex(
114 Digest.sha256,
115 new TextEncoder().encode(`${files}\n${contents.join("\n")}`),
116 ),
117 );
118});
119
120export const knipCheck = Effect.fn("knipCheck")(function* (input: {
121 readonly cwd: Option.Option<string>;
122}) {
123 const fs = yield* FileSystem.FileSystem;
124 const path = yield* Path.Path;
125 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
126 const cwd = Option.isSome(input.cwd)
127 ? path.resolve(input.cwd.value)
128 : yield* path.fromFileUrl(new URL("..", import.meta.url));
129 const preprocessor = yield* path.fromFileUrl(new URL("knip-schemas.ts", import.meta.url));
130 const cli = path.join(
131 path.dirname(yield* path.fromFileUrl(new URL(import.meta.resolve("knip")))),
132 "cli.js",
133 );
134
135 const cacheDir = path.join(cwd, "node_modules/.cache/knip-check");
136 const current = yield* fingerprint(cwd, [
137 preprocessor,
138 yield* path.fromFileUrl(new URL(import.meta.url)),
139 ]);
140 if (Option.isSome(current)) {
141 const stamp = path.join(cacheDir, "fingerprint");
142 const previous = yield* fs.readFileString(stamp).pipe(Effect.orElseSucceed(() => ""));
143 if (previous !== current.value) {
144 yield* fs.remove(cacheDir, { recursive: true, force: true });
145 yield* fs.makeDirectory(cacheDir, { recursive: true });
146 yield* fs.writeFileString(stamp, current.value);
147 }
148 }
149
150 const preprocessorOptions = yield* encodeJson({
151 exportWorkspaces: EXPORT_WORKSPACES,
152 ...(Option.isSome(current) ? { verdicts: path.join(cacheDir, "schemas.json") } : {}),
153 });
154 const exitCode = yield* Effect.scoped(
155 Effect.gen(function* () {
156 const handle = yield* spawner.spawn(
157 ChildProcess.make(
158 "node",
159 [
160 cli,
161 "--include",
162 "files,dependencies",
163 "--exports",
164 "--no-config-hints",
165 "--preprocessor",
166 preprocessor,
167 "--preprocessor-options",
168 preprocessorOptions,
169 ...(Option.isSome(current) ? ["--cache", "--cache-location", cacheDir] : []),
170 ],
171 { cwd, stdin: "inherit", stdout: "inherit", stderr: "inherit" },
172 ),
173 );
174 return yield* handle.exitCode;
175 }),
176 );
177 yield* Effect.sync(() => (process.exitCode = exitCode));
178});
179
180const command = Command.make(
181 "knip-check",
182 {
183 cwd: Flag.String("cwd").pipe(
184 Flag.withDescription("Project to check instead of this repository."),
185 Flag.optional,
186 ),
187 },
188 knipCheck,
189).pipe(Command.withDescription("Report unused files, dependencies and exports."));
190
191if (import.meta.main) {
192 Command.run(command, { version: "0.0.0" }).pipe(
193 Effect.provide([NodeServices.layer, NodeCrypto.layer]),
194 NodeRuntime.runMain,
195 );
196}