fallow-type-aware 3.33.1 → 3.34.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fallow-type-aware",
3
- "version": "3.33.1",
3
+ "version": "3.34.0",
4
4
  "description": "Optional TypeScript-Go semantic refinement sidecar for Fallow",
5
5
  "license": "MIT",
6
6
  "repository": {
package/src/cli.mjs CHANGED
@@ -2,12 +2,19 @@ import path from "node:path";
2
2
  import { createInterface } from "node:readline";
3
3
 
4
4
  import {
5
+ MUTANT_TYPECHECK_OPERATION,
5
6
  SESSION_ENVELOPE_TYPES,
6
7
  STATUS_OPERATION,
7
8
  WIRE_PROTOCOL_VERSION,
8
9
  } from "./generated-protocol.mjs";
9
10
  import { analyzeSemanticQueries, createSemanticSession } from "./semantic.mjs";
10
- import { createSemanticResponse, createStatusResponse, parseRequest } from "./protocol.mjs";
11
+ import { checkMutants } from "./mutant-typecheck.mjs";
12
+ import {
13
+ createMutantTypecheckResponse,
14
+ createSemanticResponse,
15
+ createStatusResponse,
16
+ parseRequest,
17
+ } from "./protocol.mjs";
11
18
 
12
19
  const MAX_REQUEST_BYTES = 8 * 1024 * 1024;
13
20
  const [ANALYZE_ENVELOPE, SHUTDOWN_ENVELOPE] = SESSION_ENVELOPE_TYPES;
@@ -91,6 +98,9 @@ const runSession = async (input, output) => {
91
98
  throw new Error("invalid semantic session envelope");
92
99
  }
93
100
  const request = parseRequest(envelope.request);
101
+ if (request.operation === MUTANT_TYPECHECK_OPERATION) {
102
+ throw new Error("a semantic session does not accept a mutant-typecheck request");
103
+ }
94
104
  if (!session) {
95
105
  root = request.root;
96
106
  session = createSemanticSession(root);
@@ -145,6 +155,14 @@ export const run = async ({ input, output, args = [] }) => {
145
155
  return;
146
156
  }
147
157
  const request = parseRequest(rawRequest);
158
+ if (request.operation === MUTANT_TYPECHECK_OPERATION) {
159
+ const results = checkMutants(request);
160
+ writeJson(
161
+ output,
162
+ createMutantTypecheckResponse({ results, elapsedMs: performance.now() - startedAt }),
163
+ );
164
+ return;
165
+ }
148
166
  const result = analyzeSemanticQueries(request);
149
167
  writeJson(output, responseFor(result, performance.now() - startedAt));
150
168
  };
@@ -5,6 +5,7 @@ export const TYPE_AWARE_PROTOCOL = Object.freeze({
5
5
  semantic_schema_version: 3,
6
6
  analysis_operation: "semantic-queries",
7
7
  status_operation: "status",
8
+ mutant_typecheck_operation: "mutant-typecheck",
8
9
  query_operations: ["symbol-use", "symbol-trace", "api-surface", "symbol-impact", "type-coupling"],
9
10
  session_envelope_types: ["analyze", "shutdown"],
10
11
  backend: {
@@ -20,6 +21,7 @@ export const WIRE_PROTOCOL_VERSION = TYPE_AWARE_PROTOCOL.wire_protocol_version;
20
21
  export const SEMANTIC_SCHEMA_VERSION = TYPE_AWARE_PROTOCOL.semantic_schema_version;
21
22
  export const ANALYSIS_OPERATION = TYPE_AWARE_PROTOCOL.analysis_operation;
22
23
  export const STATUS_OPERATION = TYPE_AWARE_PROTOCOL.status_operation;
24
+ export const MUTANT_TYPECHECK_OPERATION = TYPE_AWARE_PROTOCOL.mutant_typecheck_operation;
23
25
  export const QUERY_OPERATIONS = Object.freeze(TYPE_AWARE_PROTOCOL.query_operations);
24
26
  export const SESSION_ENVELOPE_TYPES = Object.freeze(TYPE_AWARE_PROTOCOL.session_envelope_types);
25
27
  export const BACKEND_FAMILY = TYPE_AWARE_PROTOCOL.backend.family;
@@ -0,0 +1,177 @@
1
+ // Type-checks mutated source files for `fallow mutation --typecheck`.
2
+ //
3
+ // The check applies one mutant at a time to an in-memory copy of its file and
4
+ // compares the error diagnostics of that file with the diagnostics of the
5
+ // original file. A new error makes the mutant `compile-error`. The check reads
6
+ // only the mutated file, so a mutant that breaks only another file stays
7
+ // `compiles`. The project files on disk never change.
8
+
9
+ import { createHash } from "node:crypto";
10
+ import { readFileSync } from "node:fs";
11
+ import path from "node:path";
12
+
13
+ import { API, DiagnosticCategory } from "typescript/unstable/sync";
14
+
15
+ import { canonicalFileIdentity } from "./file-identity.mjs";
16
+
17
+ const JAVASCRIPT_EXTENSIONS = new Set([".js", ".jsx", ".mjs", ".cjs"]);
18
+ const LEADING_COMMENTS = /^(?:\s|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*/u;
19
+ const NO_CHECK_PRAGMA = /@ts-nocheck\b/u;
20
+ const MAX_CODES = 8;
21
+
22
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
23
+
24
+ const isInferredProject = (project) =>
25
+ project.configFileName.split(path.sep).join("/").endsWith("/dev/null/inferred");
26
+
27
+ const hasNoCheckPragma = (text) => NO_CHECK_PRAGMA.test(LEADING_COMMENTS.exec(text)?.[0] ?? "");
28
+
29
+ const isChecked = (project, absolutePath, text) => {
30
+ if (hasNoCheckPragma(text)) return false;
31
+ if (!JAVASCRIPT_EXTENSIONS.has(path.extname(absolutePath).toLowerCase())) return true;
32
+ return project.compilerOptions?.checkJs === true;
33
+ };
34
+
35
+ const errorKey = (diagnostic) => `${diagnostic.code}\u0000${diagnostic.text}`;
36
+
37
+ const fileErrors = (project, absolutePath) =>
38
+ [
39
+ ...project.program.getSyntacticDiagnostics(absolutePath),
40
+ ...project.program.getSemanticDiagnostics(absolutePath),
41
+ ].filter((diagnostic) => diagnostic.category === DiagnosticCategory.Error);
42
+
43
+ const countKeys = (diagnostics) => {
44
+ const counts = new Map();
45
+ for (const diagnostic of diagnostics) {
46
+ const key = errorKey(diagnostic);
47
+ counts.set(key, (counts.get(key) ?? 0) + 1);
48
+ }
49
+ return counts;
50
+ };
51
+
52
+ // The codes of the errors that the mutated file has and the original file
53
+ // does not have. Positions move with the mutation, so the comparison uses the
54
+ // code and the message text.
55
+ const newErrorCodes = (baseline, diagnostics) => {
56
+ const remaining = new Map(baseline);
57
+ const codes = new Set();
58
+ for (const diagnostic of diagnostics) {
59
+ const key = errorKey(diagnostic);
60
+ const count = remaining.get(key) ?? 0;
61
+ if (count > 0) remaining.set(key, count - 1);
62
+ else codes.add(diagnostic.code);
63
+ }
64
+ return [...codes].toSorted((left, right) => left - right).slice(0, MAX_CODES);
65
+ };
66
+
67
+ const mutatedText = (original, mutant) =>
68
+ Buffer.concat([
69
+ original.subarray(0, mutant.start),
70
+ Buffer.from(mutant.replacement, "utf8"),
71
+ original.subarray(mutant.end),
72
+ ]).toString("utf8");
73
+
74
+ const unchecked = (file, reason) =>
75
+ file.mutants.map((mutant) => ({ id: mutant.id, outcome: "unchecked", reason }));
76
+
77
+ const readOriginal = (file) => {
78
+ try {
79
+ return readFileSync(file.absolutePath);
80
+ } catch {
81
+ return null;
82
+ }
83
+ };
84
+
85
+ const defaultProjectConfig = (api, absolutePath) => {
86
+ const snapshot = api.updateSnapshot({ openFiles: [absolutePath] });
87
+ try {
88
+ const project = snapshot.getDefaultProjectForFile(absolutePath);
89
+ return project && !isInferredProject(project) ? project.configFileName : null;
90
+ } finally {
91
+ api.updateSnapshot({ closeFiles: [absolutePath] }).dispose();
92
+ snapshot.dispose();
93
+ }
94
+ };
95
+
96
+ const createOverlayApi = (root, createApi) => {
97
+ const overlay = new Map();
98
+ const api = createApi({
99
+ cwd: root,
100
+ fs: {
101
+ readFile: (fileName) =>
102
+ overlay.size === 0 ? undefined : overlay.get(canonicalFileIdentity(fileName)),
103
+ },
104
+ });
105
+ return { api, overlay };
106
+ };
107
+
108
+ const sourceSkipReason = (file, original) => {
109
+ if (original === null) return "file-missing";
110
+ const changed = file.sourceSha256 !== null && sha256(original) !== file.sourceSha256;
111
+ return changed ? "source-changed" : null;
112
+ };
113
+
114
+ const projectSkipReason = (project, file, original) => {
115
+ if (!project?.program.getSourceFile(file.absolutePath)) return "no-project";
116
+ return isChecked(project, file.absolutePath, original.toString("utf8"))
117
+ ? null
118
+ : "not-type-checked";
119
+ };
120
+
121
+ const checkMutant = (context, check, mutant) => {
122
+ context.overlay.set(check.identity, mutatedText(check.original, mutant));
123
+ const next = context.api.updateSnapshot(check.changes);
124
+ check.snapshot.dispose();
125
+ check.snapshot = next;
126
+ const errors = fileErrors(next.getProject(check.config), check.file.absolutePath);
127
+ const codes = newErrorCodes(check.baseline, errors);
128
+ return codes.length > 0
129
+ ? { id: mutant.id, outcome: "compile-error", codes }
130
+ : { id: mutant.id, outcome: "compiles" };
131
+ };
132
+
133
+ const checkInProject = (context, file, original, config) => {
134
+ const check = {
135
+ file,
136
+ original,
137
+ config,
138
+ identity: canonicalFileIdentity(file.absolutePath),
139
+ changes: { fileChanges: { changed: [file.absolutePath] } },
140
+ snapshot: context.api.updateSnapshot({ openProjects: [config] }),
141
+ baseline: null,
142
+ };
143
+ try {
144
+ const project = check.snapshot.getProject(config);
145
+ const reason = projectSkipReason(project, file, original);
146
+ if (reason !== null) return unchecked(file, reason);
147
+ check.baseline = countKeys(fileErrors(project, file.absolutePath));
148
+ return file.mutants.map((mutant) => checkMutant(context, check, mutant));
149
+ } finally {
150
+ context.overlay.delete(check.identity);
151
+ context.api.updateSnapshot({ ...check.changes, closeProjects: [config] }).dispose();
152
+ check.snapshot.dispose();
153
+ }
154
+ };
155
+
156
+ const checkFile = (context, file) => {
157
+ const original = readOriginal(file);
158
+ const reason = sourceSkipReason(file, original);
159
+ if (reason !== null) return unchecked(file, reason);
160
+ const config = defaultProjectConfig(context.api, file.absolutePath);
161
+ if (config === null) return unchecked(file, "no-project");
162
+ return checkInProject(context, file, original, config);
163
+ };
164
+
165
+ /** Type-checks each mutant of a parsed `mutant-typecheck` request. */
166
+ export const checkMutants = (
167
+ { root, files },
168
+ { createApi = (options) => new API(options) } = {},
169
+ ) => {
170
+ if (files.length === 0) return [];
171
+ const context = createOverlayApi(root, createApi);
172
+ try {
173
+ return files.flatMap((file) => checkFile(context, file));
174
+ } finally {
175
+ context.api.close();
176
+ }
177
+ };
package/src/protocol.mjs CHANGED
@@ -7,9 +7,11 @@ import {
7
7
  ANALYSIS_OPERATION,
8
8
  BACKEND_FAMILY,
9
9
  BACKEND_VERSION,
10
+ MUTANT_TYPECHECK_OPERATION,
10
11
  QUERY_OPERATIONS as MANIFEST_QUERY_OPERATIONS,
11
12
  WIRE_PROTOCOL_VERSION,
12
13
  } from "./generated-protocol.mjs";
14
+ import { canonicalFileIdentity } from "./file-identity.mjs";
13
15
  import { normalizePhaseTimings, normalizeSemanticResult } from "./response-normalization.mjs";
14
16
 
15
17
  const require = createRequire(import.meta.url);
@@ -375,8 +377,75 @@ const parseBatchRequest = (value) => {
375
377
  return { root, projects, queries, evidenceLimit };
376
378
  };
377
379
 
380
+ const MUTANT_TYPECHECK_REQUEST_KEYS = new Set(["protocol_version", "operation", "root", "files"]);
381
+ const MUTANT_FILE_KEYS = new Set(["path", "source_sha256", "mutants"]);
382
+ const MUTANT_KEYS = new Set(["id", "start", "end", "replacement"]);
383
+ const SHA256_HEX = /^[0-9a-f]{64}$/u;
384
+ const MAX_MUTANTS = 25_000;
385
+ const MAX_MUTANT_ID_CHARS = 64;
386
+
387
+ const requireText = (value, field) => {
388
+ if (typeof value !== "string") throw new Error(`${field} must be a string`);
389
+ if ([...value].length > MAX_STRING_CHARS) {
390
+ throw new Error(`${field} exceeds the ${MAX_STRING_CHARS} character limit`);
391
+ }
392
+ return value;
393
+ };
394
+
395
+ const parseMutant = (value, field, ids) => {
396
+ requireObject(value, field);
397
+ requireExactKeys(value, MUTANT_KEYS, field);
398
+ const id = requireString(value.id, `${field}.id`);
399
+ if (id.length > MAX_MUTANT_ID_CHARS) {
400
+ throw new Error(`${field}.id exceeds the ${MAX_MUTANT_ID_CHARS} character limit`);
401
+ }
402
+ if (ids.has(id)) throw new Error(`duplicate mutant id ${id}`);
403
+ ids.add(id);
404
+ const start = requireInteger(value.start, `${field}.start`, 0);
405
+ const end = requireInteger(value.end, `${field}.end`, start);
406
+ return { id, start, end, replacement: requireText(value.replacement, `${field}.replacement`) };
407
+ };
408
+
409
+ const parseMutantFile = (value, field, root, ids) => {
410
+ requireObject(value, field);
411
+ requireExactKeys(value, MUTANT_FILE_KEYS, field);
412
+ const { candidatePath, absolutePath } = parseCandidatePath(value.path, `${field}.path`, root);
413
+ const sourceSha256 =
414
+ value.source_sha256 === undefined
415
+ ? null
416
+ : requireString(value.source_sha256, `${field}.source_sha256`);
417
+ if (sourceSha256 !== null && !SHA256_HEX.test(sourceSha256)) {
418
+ throw new Error(`${field}.source_sha256 must be a lowercase SHA-256 hex digest`);
419
+ }
420
+ return {
421
+ path: candidatePath,
422
+ absolutePath: canonicalFileIdentity(absolutePath),
423
+ sourceSha256,
424
+ mutants: requireBoundedArray(value.mutants, `${field}.mutants`, MAX_MUTANTS).map(
425
+ (mutant, index) => parseMutant(mutant, `${field}.mutants[${index}]`, ids),
426
+ ),
427
+ };
428
+ };
429
+
430
+ const parseMutantTypecheckRequest = (value) => {
431
+ requireExactKeys(value, MUTANT_TYPECHECK_REQUEST_KEYS, "request");
432
+ const root = parseRoot(value.root);
433
+ const ids = new Set();
434
+ const files = requireBoundedArray(value.files, "files", MAX_MUTANTS).map((file, index) =>
435
+ parseMutantFile(file, `files[${index}]`, root, ids),
436
+ );
437
+ if (ids.size > MAX_MUTANTS) throw new Error(`mutants exceed the ${MAX_MUTANTS} item limit`);
438
+ return { operation: MUTANT_TYPECHECK_OPERATION, root, files };
439
+ };
440
+
378
441
  export const parseRequest = (value) => {
379
442
  requireObject(value, "request");
443
+ if (
444
+ value.protocol_version === WIRE_PROTOCOL_VERSION &&
445
+ value.operation === MUTANT_TYPECHECK_OPERATION
446
+ ) {
447
+ return parseMutantTypecheckRequest(value);
448
+ }
380
449
  if (value.protocol_version === WIRE_PROTOCOL_VERSION) {
381
450
  return parseBatchRequest(value);
382
451
  }
@@ -405,3 +474,13 @@ export const createSemanticResponse = ({
405
474
  warnings: normalizeWarnings(warnings),
406
475
  elapsed_ms: Math.max(0, Math.round(elapsedMs)),
407
476
  });
477
+
478
+ export const createMutantTypecheckResponse = ({ results, elapsedMs }) => ({
479
+ protocol_version: WIRE_PROTOCOL_VERSION,
480
+ operation: MUTANT_TYPECHECK_OPERATION,
481
+ sidecar_version: SIDECAR_VERSION,
482
+ backend: BACKEND_FAMILY,
483
+ backend_version: BACKEND_VERSION,
484
+ results,
485
+ elapsed_ms: Math.max(0, Math.round(elapsedMs)),
486
+ });