TypeScript
ci: enforce runtime exports while allowing types and schemas (#10171)
Julius Marminge5fe5c6fe9bb7
diff --git a/docs/operations/development.md b/docs/operations/development.mdindex 39686807d6d..8016a777b22 100644--- a/docs/operations/development.md+++ b/docs/operations/development.md@@ -72,8 +72,10 @@ Windows investigation while that suite is not a required gate.### Unused code`vp run knip:check` checks unused files and dependencies across the repo, then-unused exports and types in `packages/tailscale` and `packages/effect-codex-app-server`.-CI enforces both checks.+unused runtime exports in every internal package under `packages/`. CI enforces both checks.+Exported types and Effect schemas are allowed without consumers. The schema preprocessor+recognizes schema types, including aliases and schema classes; functions that create or decode+schemas remain checked. Completely unused files remain checked too.Use `vp run knip --workspace apps/web` to audit one workspace, including exports,or `vp run knip:production --workspace apps/web` to find code kept alive only by tests.The full export audit still has findings and is not a repo-wide CI gate. Extend thediff --git a/knip.jsonc b/knip.jsoncindex 25706930133..aa665d09602 100644--- a/knip.jsonc+++ b/knip.jsonc@@ -1,5 +1,7 @@{"$schema": "https://unpkg.com/knip@6/schema.json",+ // Exported types are part of our contracts even before they have consumers.+ "rules": { "types": "off", "nsTypes": "off" },// These executables are supplied by the OS or installed separately from npm."ignoreBinaries": ["eas", "file", "mkfifo", "pkill", "pkg-config", "plutil", "sips"],"workspaces": {@@ -10,6 +12,10 @@"vite": { "entry": [".github/**/*.test.cjs"] },"vitest": { "entry": [".github/**/*.test.cjs"] },},+ "scripts": {+ // Knip loads its preprocessor through a CLI option, not a source import.+ "entry": ["knip-schemas.ts"],+ },"apps/server": {// Vite+ pack entries and the launcher used by installed background services."entry": [diff --git a/package.json b/package.jsonindex 1bfdac638f9..5e72b463a10 100644--- a/package.json+++ b/package.json@@ -25,9 +25,9 @@"typecheck": "vp run -r --concurrency-limit 2 typecheck","tc": "vp run -r --concurrency-limit 2 typecheck","lint": "vp lint --report-unused-disable-directives",- "knip": "knip",- "knip:check": "knip --include files,dependencies --no-config-hints && knip --workspace packages/tailscale --workspace packages/effect-codex-app-server --workspace packages/ssh --exports --no-config-hints",- "knip:production": "knip --production",+ "knip": "knip --preprocessor ./scripts/knip-schemas.ts",+ "knip:check": "knip --include files,dependencies --no-config-hints && knip --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints",+ "knip:production": "knip --production --preprocessor ./scripts/knip-schemas.ts","lint:mobile": "node scripts/mobile-native-static-check.ts","test": "vp run -r test","test:resource-monitor": "cargo test --locked --manifest-path native/resource-monitor/Cargo.toml",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex bd6ed98740a..e9987c20f28 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -991,6 +991,9 @@ importers:'@types/pngjs':specifier: 6.0.5version: 6.0.5+ typescript:+ specifier: 'catalog:'+ version: 6.0.3vite-plus:specifier: 'catalog:'version: 0.3.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])diff --git a/scripts/knip-schemas.test.ts b/scripts/knip-schemas.test.tsnew file mode 100644index 00000000000..1184557d0e4--- /dev/null+++ b/scripts/knip-schemas.test.ts@@ -0,0 +1,151 @@+// @effect-diagnostics nodeBuiltinImport:off - Runs the real Knip CLI against a disposable on-disk project.+import * as NodeChildProcess from "node:child_process";+import * as NodeFS from "node:fs";+import * as NodeModule from "node:module";+import * as NodePath from "node:path";+import * as NodeProcess from "node:process";+import { expect, it } from "vite-plus/test";++const require = NodeModule.createRequire(import.meta.url);+const cli = NodePath.join(NodePath.dirname(require.resolve("knip")), "cli.js");+const preprocessor = NodePath.join(import.meta.dirname, "knip-schemas.ts");++it("allows types and schemas through the real Knip CLI without hiding runtime or file findings", () => {+ // Keeping the disposable project here gives it the same Effect installation as the scripts.+ const cwd = NodeFS.mkdtempSync(NodePath.join(import.meta.dirname, ".knip-test-"));+ const write = (file: string, content: string) =>+ NodeFS.writeFileSync(NodePath.join(cwd, file), content);+ const run = (filtered: boolean) =>+ NodeChildProcess.spawnSync(+ NodeProcess.execPath,+ [+ cli,+ "--directory",+ cwd,+ "--config",+ NodePath.join(cwd, "knip.json"),+ "--no-config-hints",+ "--include",+ "files,dependencies,exports,nsExports,types,nsTypes,duplicates",+ "--reporter",+ "json",+ ...(filtered ? ["--preprocessor", preprocessor] : []),+ ],+ { encoding: "utf8" },+ );+ try {+ write(+ "package.json",+ JSON.stringify({ private: true, type: "module", dependencies: { effect: "*" } }),+ );+ write(+ "tsconfig.json",+ JSON.stringify({ compilerOptions: { module: "NodeNext", strict: true } }),+ );+ write(+ "knip.json",+ JSON.stringify({+ entry: ["entry.ts"],+ project: ["*.ts"],+ includeEntryExports: true,+ include: [+ "exports",+ "nsExports",+ "types",+ "nsTypes",+ "duplicates",+ "files",+ "dependencies",+ ],+ rules: { types: "off", nsTypes: "off" },+ }),+ );+ write(+ "entry.ts",+ `+ import * as S from "effect/Schema";+ import * as ns from "./namespace.ts";+ console.log(ns);+ export { Remote as Reexported } from "./remote.ts";+ export const Text = S.String;+ export const Alias = Text;+ const Internal = S.Boolean;+ export type Internal = typeof Internal.Type;+ export const PublicAlias = Internal;+ export default Text;+ export const Record = S.Struct({ name: Text }).annotate({ title: "record" });+ export const Branded = S.String.pipe(S.brand("Name"));+ export class Failure extends S.TaggedErrorClass<Failure>()("Failure", { reason: Text }) {}+ export class Person extends S.Class<Person>("Person")({ name: Text }) {}+ export type UnusedType = { name: string };+ export interface UnusedInterface { name: string }+ `,+ );+ write(+ "remote.ts",+ `+ import { Schema as S } from "effect";+ export const Remote = S.Struct({ id: S.Number });+ throw new Error("The preprocessor must never evaluate application modules");+ `,+ );+ write(+ "namespace.ts",+ `+ import * as S from "effect/Schema";+ export const Unused = S.Number;+ export type UnusedType = string;+ `,+ );+ const baseline = run(false);+ expect(baseline.status, baseline.stderr).toBe(1);+ expect(baseline.stdout).toContain('"Text"');+ const allowed = run(true);+ expect(allowed.status, allowed.stderr + allowed.stdout).toBe(0);+ expect(JSON.parse(allowed.stdout).issues).toEqual([]);++ NodeFS.appendFileSync(+ NodePath.join(cwd, "entry.ts"),+ `+ export const decode = S.decodeUnknownSync(Text);+ export const makeSchema = () => S.String;+ export const LooksLikeSchema = { ast: "not a schema" };+ export const ordinary = 123;+ export const duplicate = ordinary;+ `,+ );+ NodeFS.appendFileSync(NodePath.join(cwd, "namespace.ts"), `export const helper = () => 1;`);+ write("unused.ts", `export const orphan = 1;`);+ write(+ "package.json",+ JSON.stringify({+ private: true,+ type: "module",+ dependencies: { effect: "*", "unused-knip-fixture-dependency": "*" },+ }),+ );+ const rejected = run(true);+ expect(rejected.status, rejected.stderr).toBe(1);+ const issues = JSON.parse(rejected.stdout).issues;+ const entry = issues.find((issue: { file: string }) => issue.file === "entry.ts");+ expect(entry.exports.map((issue: { name: string }) => issue.name).sort()).toEqual([+ "LooksLikeSchema",+ "decode",+ "duplicate",+ "makeSchema",+ "ordinary",+ ]);+ expect(entry.duplicates).toHaveLength(1);+ expect(+ issues.find((issue: { file: string }) => issue.file === "namespace.ts").nsExports,+ ).toEqual([expect.objectContaining({ name: "helper" })]);+ expect(issues.find((issue: { file: string }) => issue.file === "unused.ts").files).toHaveLength(+ 1,+ );+ expect(+ issues.find((issue: { file: string }) => issue.file === "package.json").dependencies,+ ).toEqual([expect.objectContaining({ name: "unused-knip-fixture-dependency" })]);+ } finally {+ NodeFS.rmSync(cwd, { recursive: true, force: true });+ }+});diff --git a/scripts/knip-schemas.ts b/scripts/knip-schemas.tsnew file mode 100644index 00000000000..fafa7ccd678--- /dev/null+++ b/scripts/knip-schemas.ts@@ -0,0 +1,96 @@+// @effect-diagnostics nodeBuiltinImport:off - Knip and the TypeScript compiler host use synchronous Node paths.+import * as NodePath from "node:path";+import type { Preprocessor } from "knip";+import ts from "typescript";++// Effect 4 schemas carry this marker, including aliases and Schema.Class constructors.+// Checking the type avoids evaluating application modules or exempting schema factories/decoders.+const schemaTypeId = "~effect/Schema/Schema";++const preprocess: Preprocessor = (options) => {+ const categories = ["exports", "nsExports", "duplicates"] as const;+ const projects = new Map<string | undefined, Set<string>>();+ for (const category of categories) {+ for (const [filePath, issues] of Object.entries(options.issues[category])) {+ if (Object.keys(issues).length === 0) continue;+ const configPath = ts.findConfigFile(+ NodePath.dirname(NodePath.resolve(options.cwd, filePath)),+ ts.sys.fileExists,+ );+ const files = projects.get(configPath) ?? new Set<string>();+ files.add(filePath);+ projects.set(configPath, files);+ }+ }++ for (const [configPath, files] of projects) {+ const config = configPath+ ? ts.getParsedCommandLineOfConfigFile(+ configPath,+ {},+ {+ ...ts.sys,+ onUnRecoverableConfigFileDiagnostic: (diagnostic) => {+ throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));+ },+ },+ )+ : undefined;+ if (config?.errors.length) {+ throw new Error(+ config.errors+ .map((error) => ts.flattenDiagnosticMessageText(error.messageText, "\n"))+ .join("\n"),+ );+ }+ const program = ts.createProgram(+ [...files].map((file) => NodePath.resolve(options.cwd, file)),+ {+ module: ts.ModuleKind.NodeNext,+ allowJs: true,+ ...config?.options,+ noEmit: true,+ },+ );+ const checker = program.getTypeChecker();+ for (const filePath of files) {+ const source = program.getSourceFile(NodePath.resolve(options.cwd, filePath));+ const module = source && checker.getSymbolAtLocation(source);+ if (!source || !module) continue;+ const schemas = new Set(+ checker.getExportsOfModule(module).flatMap((symbol) => {+ const exported =+ symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;+ // Duplicate exports can name a private value with a public type of the same name.+ const target =+ exported.flags & ts.SymbolFlags.Value+ ? exported+ : checker.resolveName(symbol.name, source, ts.SymbolFlags.Value, false);+ if (!target) return [];+ const type = checker.getTypeOfSymbolAtLocation(target, target.valueDeclaration ?? source);+ const marker = type.getProperty(schemaTypeId);+ if (!marker) return [];+ const markerType = checker.getTypeOfSymbolAtLocation(marker, source);+ return markerType.isStringLiteral() && markerType.value === schemaTypeId+ ? [symbol.name]+ : [];+ }),+ );+ for (const category of categories) {+ const issues = options.issues[category][filePath];+ if (!issues) continue;+ for (const [key, issue] of Object.entries(issues)) {+ const symbols = issue.symbols ?? [{ symbol: issue.symbol }];+ if (symbols.length > 0 && symbols.every(({ symbol }) => schemas.has(symbol))) {+ delete issues[key];+ options.counters[category]--;+ }+ }+ if (Object.keys(issues).length === 0) delete options.issues[category][filePath];+ }+ }+ }+ return options;+};++export default preprocess;diff --git a/scripts/package.json b/scripts/package.jsonindex 042d69a8d9f..0d080008ead 100644--- a/scripts/package.json+++ b/scripts/package.json@@ -18,6 +18,7 @@"devDependencies": {"@effect/vitest": "catalog:","@types/pngjs": "6.0.5",+ "typescript": "catalog:","vite-plus": "catalog:"}}