@ref0/workspace 0.1.0 → 0.3.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.
@@ -0,0 +1,63 @@
1
+ import { repoRoot, symbolCache, workingFiles } from "./symbols.mjs";
2
+ // src/symbols/find.ts
3
+ /**
4
+ * Finds the functions, classes, consts and types the repo already has, by words in their name,
5
+ * signature, doc comment or path, so you can reuse one instead of writing it again.
6
+ *
7
+ * ref0-workspace symbols find <words...>
8
+ *
9
+ * Prints the ten best matches in the working tree, tests included. A word in the name counts
10
+ * most, then a word in the doc comment, then one in the signature or path, and a symbol that
11
+ * matches every word ranks above one that doesn't.
12
+ */
13
+ /** `storedCheckCode` or `stored_check_code` as `['stored', 'check', 'code']`. */
14
+ const wordsOf = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter((word) => word !== "");
15
+ /** `bytes` as `byte`, so it matches `byte` and `bytes` alike. */
16
+ const stem = (word) => word.length > 3 && word.endsWith("s") ? word.slice(0, -1) : word;
17
+ /** How well `symbol` matches one query word, or 0. */
18
+ const wordScore = (symbol, word) => {
19
+ const name = symbol.name.toLowerCase();
20
+ const nameWords = wordsOf(symbol.name);
21
+ if (name === word) return 12;
22
+ if (nameWords.includes(word)) return 6;
23
+ if (nameWords.some((nameWord) => nameWord.startsWith(word))) return 4;
24
+ if (name.includes(word)) return 3;
25
+ if (wordsOf(symbol.doc).some((docWord) => docWord.startsWith(word))) return 2;
26
+ if (symbol.signature.toLowerCase().includes(word)) return 1;
27
+ return symbol.file.toLowerCase().includes(word) ? .5 : 0;
28
+ };
29
+ /** The ten symbols that best match the words in `query`, best first. */
30
+ const best = (symbols, query) => {
31
+ const words = query.flatMap(wordsOf).map(stem);
32
+ return symbols.flatMap((symbol) => {
33
+ const scores = words.map((word) => wordScore(symbol, word));
34
+ if (scores.every((score) => score === 0)) return [];
35
+ return [{
36
+ symbol,
37
+ score: scores.reduce((sum, each) => sum + each, 0) + (scores.includes(0) ? 0 : 5) + (symbol.exported ? 1 : 0) - (symbol.test ? 2 : 0)
38
+ }];
39
+ }).sort((a, b) => b.score - a.score || a.symbol.name.length - b.symbol.name.length || a.symbol.file.localeCompare(b.symbol.file)).slice(0, 10).map(({ symbol }) => symbol);
40
+ };
41
+ const findUsage = "usage: ref0-workspace symbols find <words...>";
42
+ /** Prints what in the repo `from` is in best matches `query`, and answers the exit code. */
43
+ const symbolsFind = (query, from) => {
44
+ if (query.length === 0) {
45
+ console.error(findUsage);
46
+ return 2;
47
+ }
48
+ const root = repoRoot(from);
49
+ const cache = symbolCache(root);
50
+ const found = best(workingFiles(root).flatMap(cache.symbolsOf), query);
51
+ cache.save();
52
+ if (found.length === 0) {
53
+ console.log(`Nothing matches ${query.join(" ")}.`);
54
+ return 0;
55
+ }
56
+ for (const symbol of found) {
57
+ console.log(`${symbol.name} ${symbol.kind}${symbol.exported ? ", exported" : ""} ${symbol.file}:${symbol.line}`);
58
+ console.log(` ${symbol.signature}`);
59
+ if (symbol.doc !== "") console.log(` ${symbol.doc}`);
60
+ }
61
+ return 0;
62
+ };
63
+ export { best, findUsage, symbolsFind };
@@ -0,0 +1,390 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { pid } from "node:process";
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { createHash } from "node:crypto";
7
+ import { deserialize, serialize } from "node:v8";
8
+ import { parseAst } from "vite-plus";
9
+ // src/symbols/symbols.ts
10
+ /**
11
+ * The functions, classes, consts and types declared at the top level of the repo's source files,
12
+ * each with a fingerprint of its body, for `check.ts` and `find.ts`.
13
+ *
14
+ * A fingerprint lists a body's syntax nodes in order: each node's type, each literal as written,
15
+ * and each name. Names the body declares, its parameters and locals, become numbered
16
+ * placeholders, so a copy with its locals renamed has the same fingerprint. Names it reads from
17
+ * outside, such as the functions it calls and the properties it reads, stay as written, so
18
+ * `x => foo(x)` and `x => bar(x)` differ. Types, comments and whitespace aren't in it.
19
+ *
20
+ * A looser fingerprint, for near copies, writes every name but a property's as `$`. Its runs of
21
+ * five tokens make the set `check.ts` compares.
22
+ *
23
+ * `symbolCache` keeps each file's declarations by its path and text, so a run parses only the
24
+ * files that changed since the last. Callers list the files, and compare, fresh each run.
25
+ */
26
+ const sourceFile = /\.(?:[cm]?[jt]s|[jt]sx)$/;
27
+ const skipped = [
28
+ /\.d\.[cm]?ts$/,
29
+ /\.gen\.ts$/,
30
+ /(?:^|\/)(?:dist|node_modules)\//,
31
+ /^\.(?:agents|claude)\//
32
+ ];
33
+ /** Whether the index reads the file at `path`. */
34
+ const indexed = (path) => sourceFile.test(path) && !skipped.some((pattern) => pattern.test(path));
35
+ const git = (root, args, input) => execFileSync("git", args, {
36
+ cwd: root,
37
+ input,
38
+ maxBuffer: 1073741824
39
+ });
40
+ /** The root of the git repo `from` is in. */
41
+ const repoRoot = (from) => git(from, ["rev-parse", "--show-toplevel"]).toString("utf8").trim();
42
+ const paths = (output) => output.toString("utf8").split("\0").filter((path) => path !== "" && indexed(path));
43
+ /** Each file the index reads in the working tree: tracked, or new and not ignored. */
44
+ const workingFiles = (root) => paths(git(root, [
45
+ "ls-files",
46
+ "-z",
47
+ "--cached",
48
+ "--others",
49
+ "--exclude-standard"
50
+ ])).filter((path) => existsSync(join(root, path))).map((path) => ({
51
+ path,
52
+ text: readFileSync(join(root, path), "utf8")
53
+ }));
54
+ /** Each of `wanted` at `commit`, or each file the index reads there; a missing one is left out. */
55
+ const filesAt = (root, commit, wanted) => {
56
+ const listed = wanted ?? paths(git(root, [
57
+ "ls-tree",
58
+ "-r",
59
+ "-z",
60
+ "--name-only",
61
+ commit
62
+ ]));
63
+ if (listed.length === 0) return [];
64
+ const output = git(root, ["cat-file", "--batch"], listed.map((path) => `${commit}:${path}\n`).join(""));
65
+ const files = [];
66
+ let at = 0;
67
+ for (const path of listed) {
68
+ const headerEnd = output.indexOf(10, at);
69
+ const header = output.toString("utf8", at, headerEnd);
70
+ at = headerEnd + 1;
71
+ if (header.endsWith(" missing")) continue;
72
+ const size = Number(header.split(" ")[2]);
73
+ files.push({
74
+ path,
75
+ text: output.toString("utf8", at, at + size)
76
+ });
77
+ at += size + 1;
78
+ }
79
+ return files;
80
+ };
81
+ const isNode = (value) => value instanceof Object && "type" in value && "start" in value && "end" in value;
82
+ /** An identifier's name, or an empty string for a node without one. */
83
+ const nameOf = (node) => "name" in node ? String(node.name) : "";
84
+ const typeFields = /* @__PURE__ */ new Set([
85
+ "typeAnnotation",
86
+ "returnType",
87
+ "typeParameters",
88
+ "typeArguments",
89
+ "superTypeArguments",
90
+ "implements"
91
+ ]);
92
+ /** Each node directly under `node`, with the field that holds it, types left out. */
93
+ const childrenOf = (node) => Object.entries(node).flatMap(([field, value]) => {
94
+ if (typeFields.has(field)) return [];
95
+ if (Array.isArray(value)) return value.filter(isNode).map((child) => [field, child]);
96
+ return isNode(value) ? [[field, value]] : [];
97
+ });
98
+ const functionTypes = /* @__PURE__ */ new Set([
99
+ "FunctionDeclaration",
100
+ "FunctionExpression",
101
+ "ArrowFunctionExpression"
102
+ ]);
103
+ /** The names a binding pattern declares, such as `{ a, b: [c] }`, into `names`. */
104
+ const addBindings = (pattern, names) => {
105
+ if (pattern.type === "Identifier") {
106
+ names.add(nameOf(pattern));
107
+ return;
108
+ }
109
+ for (const [field, child] of childrenOf(pattern)) {
110
+ if (pattern.type === "Property" && field !== "value") continue;
111
+ if (pattern.type === "AssignmentPattern" && field !== "left") continue;
112
+ addBindings(child, names);
113
+ }
114
+ };
115
+ /** Every name declared anywhere in `node`: parameters, variables, functions, classes, catches. */
116
+ const declaredIn = (node, names) => {
117
+ for (const [field, child] of childrenOf(node)) {
118
+ if (functionTypes.has(node.type) && (field === "params" || field === "id") || node.type === "VariableDeclarator" && field === "id" || node.type === "CatchClause" && field === "param" || (node.type === "ClassDeclaration" || node.type === "ClassExpression") && field === "id") addBindings(child, names);
119
+ declaredIn(child, names);
120
+ }
121
+ return names;
122
+ };
123
+ const keyedTypes = /* @__PURE__ */ new Set([
124
+ "Property",
125
+ "MethodDefinition",
126
+ "PropertyDefinition",
127
+ "AccessorProperty",
128
+ "TSPropertySignature"
129
+ ]);
130
+ /** Whether `field` of `parent` names a property, as `b` does in `a.b` and `{ b: 1 }`. */
131
+ const namesProperty = (parent, field) => !("computed" in parent && parent.computed === true) && (parent.type === "MemberExpression" && field === "property" || keyedTypes.has(parent.type) && field === "key");
132
+ const wrapperFields = /* @__PURE__ */ new Set(["expression", "parameter"]);
133
+ /** A body's fingerprint and its looser one, token by token, and its count of nodes. */
134
+ const fingerprint = (body, text, own) => {
135
+ const declared = declaredIn(body, new Set(own === void 0 ? [] : [own]));
136
+ const placeholders = /* @__PURE__ */ new Map();
137
+ const strict = [];
138
+ const loose = [];
139
+ let size = 0;
140
+ const emit = (strictToken, looseToken = strictToken) => {
141
+ strict.push(strictToken);
142
+ loose.push(looseToken);
143
+ };
144
+ const walk = (node, parent, field) => {
145
+ if (node.type.startsWith("TS")) {
146
+ for (const [childField, child] of childrenOf(node)) if (wrapperFields.has(childField)) walk(child, node, childField);
147
+ return;
148
+ }
149
+ size += 1;
150
+ emit(node.type);
151
+ if (node.type === "Identifier" || node.type === "PrivateIdentifier") {
152
+ const name = nameOf(node);
153
+ if (parent !== void 0 && namesProperty(parent, field)) emit(`.${name}`);
154
+ else if (declared.has(name)) {
155
+ if (!placeholders.has(name)) placeholders.set(name, placeholders.size);
156
+ emit(`$${placeholders.get(name)}`, "$");
157
+ } else emit(name, "$");
158
+ return;
159
+ }
160
+ if (node.type === "JSXIdentifier") emit(nameOf(node));
161
+ else if (node.type === "Literal" || node.type === "TemplateElement") emit(text.slice(node.start, node.end));
162
+ else if (node.type === "JSXText") {
163
+ const words = text.slice(node.start, node.end).replace(/\s+/g, " ").trim();
164
+ if (words !== "") emit(words);
165
+ }
166
+ for (const [childField, child] of childrenOf(node)) walk(child, node, childField);
167
+ };
168
+ walk(body, void 0, "");
169
+ return {
170
+ strict,
171
+ loose,
172
+ size
173
+ };
174
+ };
175
+ /** FNV-1a, 32 bits, of `text`. */
176
+ const fnv = (text) => {
177
+ let hash = 2166136261;
178
+ for (let index = 0; index < text.length; index += 1) {
179
+ hash ^= text.charCodeAt(index);
180
+ hash = Math.imul(hash, 16777619);
181
+ }
182
+ return hash >>> 0;
183
+ };
184
+ const runLength = 5;
185
+ /**
186
+ * The hashes of each run of `runLength` tokens, sorted. A run that repeats is hashed with its
187
+ * count so far, so a list of 40 names isn't as alike as one of 14. A body that's mostly one run
188
+ * repeated, such as a long list of names, has none: it would be like any list as long.
189
+ */
190
+ const runsOf = (tokens) => {
191
+ const seen = /* @__PURE__ */ new Map();
192
+ const hashes = [];
193
+ for (let index = 0; index + runLength <= Math.max(tokens.length, runLength); index += 1) {
194
+ const run = tokens.slice(index, index + runLength).join("");
195
+ const times = seen.get(run) ?? 0;
196
+ seen.set(run, times + 1);
197
+ hashes.push(fnv(`${run}\u0002${times}`));
198
+ }
199
+ return seen.size < hashes.length / 2 ? /* @__PURE__ */ new Uint32Array() : Uint32Array.from(new Set(hashes)).sort();
200
+ };
201
+ /** The comment lines straight above `start`, top first, each trimmed. */
202
+ const commentAbove = (text, start) => {
203
+ const lines = [];
204
+ let end = text.lastIndexOf("\n", start - 1);
205
+ while (end > 0) {
206
+ const begin = text.lastIndexOf("\n", end - 1) + 1;
207
+ const line = text.slice(begin, end).trim();
208
+ if (!/^(?:\/\/|\/\*|\*)/.test(line)) break;
209
+ lines.unshift(line);
210
+ end = begin - 1;
211
+ }
212
+ return lines;
213
+ };
214
+ /** The first line of the doc comment in `comment`, if it has one. */
215
+ const docOf = (comment) => {
216
+ const opening = comment.map((line) => line.startsWith("/**")).lastIndexOf(true);
217
+ if (opening === -1) return "";
218
+ return comment.slice(opening).map((line) => line.replace(/^\/\*\*|\*\/$/g, "").replace(/^\*\s?/, "").trim()).find((line) => line !== "") ?? "";
219
+ };
220
+ /** The reason a `// CLONE:` comment in `comment` gives, if it has one. */
221
+ const cloneReason = (comment) => {
222
+ for (const line of comment) {
223
+ const reason = /\bCLONE:\s*(\S.*)$/.exec(line)?.[1]?.replace(/\s*\*\/$/, "");
224
+ if (reason !== void 0 && reason !== "") return reason;
225
+ }
226
+ };
227
+ const oneLine = (text) => {
228
+ const line = text.replace(/\s+/g, " ").trim();
229
+ return line.length > 160 ? `${line.slice(0, 159)}…` : line;
230
+ };
231
+ const langOf = (path) => {
232
+ if (path.endsWith(".tsx")) return "tsx";
233
+ return /\.[cm]?ts$/.test(path) ? "ts" : "jsx";
234
+ };
235
+ /** The declarations a top-level statement makes. */
236
+ const declarationsOf = (statement) => {
237
+ const declaration = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? statement.declaration : statement;
238
+ if (declaration === null) return [];
239
+ switch (declaration.type) {
240
+ case "FunctionDeclaration": return declaration.body === null ? [] : [{
241
+ name: declaration.id?.name ?? "default",
242
+ kind: "function",
243
+ body: declaration,
244
+ signatureEnd: declaration.body.start
245
+ }];
246
+ case "ClassDeclaration": return [{
247
+ name: declaration.id?.name ?? "default",
248
+ kind: "class",
249
+ body: declaration,
250
+ signatureEnd: declaration.body.start
251
+ }];
252
+ case "TSTypeAliasDeclaration":
253
+ case "TSInterfaceDeclaration": return [{
254
+ name: declaration.id.name,
255
+ kind: "type",
256
+ body: declaration,
257
+ signatureEnd: declaration.end
258
+ }];
259
+ case "VariableDeclaration": return declaration.declarations.flatMap((declarator) => {
260
+ const init = declarator.init;
261
+ if (declarator.id.type !== "Identifier" || init === null) return [];
262
+ const callable = init.type === "ArrowFunctionExpression" || init.type === "FunctionExpression";
263
+ return [{
264
+ name: declarator.id.name,
265
+ kind: callable ? "function" : "const",
266
+ body: init,
267
+ signatureEnd: callable ? init.body?.start ?? init.end : init.end
268
+ }];
269
+ });
270
+ default: return [];
271
+ }
272
+ };
273
+ /** Where each line of `text` starts. */
274
+ const lineStarts = (text) => {
275
+ const starts = [0];
276
+ for (let at = text.indexOf("\n"); at !== -1; at = text.indexOf("\n", at + 1)) starts.push(at + 1);
277
+ return starts;
278
+ };
279
+ /** The line, from 1, of offset `at`. */
280
+ const lineOf = (starts, at) => {
281
+ let low = 0;
282
+ let high = starts.length - 1;
283
+ while (low < high) {
284
+ const middle = low + high + 1 >> 1;
285
+ if ((starts[middle] ?? 0) <= at) low = middle;
286
+ else high = middle - 1;
287
+ }
288
+ return low + 1;
289
+ };
290
+ /** The top-level declarations in one file, or undefined when it doesn't parse. */
291
+ const parsed = (file) => {
292
+ let program;
293
+ try {
294
+ program = parseAst(file.text, { lang: langOf(file.path) }, file.path);
295
+ } catch {
296
+ console.error(`symbols: ${file.path} doesn't parse, so it's left out`);
297
+ return;
298
+ }
299
+ const starts = lineStarts(file.text);
300
+ const test = /\.test\.[cm]?[jt]sx?$/.test(file.path);
301
+ return program.body.flatMap((statement) => {
302
+ const exported = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration";
303
+ const comment = commentAbove(file.text, statement.start);
304
+ return declarationsOf(statement).map((declared) => {
305
+ const { strict, loose, size } = fingerprint(declared.body, file.text, declared.name);
306
+ const written = file.text.slice(declared.body.start, declared.signatureEnd);
307
+ const signature = declared.kind === "function" ? written : written.split("\n", 1)[0] ?? "";
308
+ return {
309
+ name: declared.name,
310
+ kind: declared.kind,
311
+ file: file.path,
312
+ line: lineOf(starts, declared.body.start),
313
+ exported,
314
+ test,
315
+ signature: oneLine(signature),
316
+ doc: docOf(comment),
317
+ clone: cloneReason(comment),
318
+ size,
319
+ hash: createHash("sha1").update(strict.join("")).digest("hex").slice(0, 16),
320
+ runs: runsOf(loose)
321
+ };
322
+ });
323
+ });
324
+ };
325
+ const version = createHash("sha256").update(readFileSync(fileURLToPath(import.meta.url))).update(`\0${import.meta.resolve("vite-plus")}`).digest("hex");
326
+ const isKept = (value) => Array.isArray(value) && value[0] === version && value[1] instanceof Map;
327
+ /**
328
+ * Each file's declarations, kept per checkout in `node_modules/.cache/ref0-workspace-symbols/`, so
329
+ * a file isn't parsed again until its path, its text or what makes declarations from them changes.
330
+ * Only
331
+ * declarations are kept: callers list the files and compare their declarations each run. A file
332
+ * that doesn't parse isn't kept, so it's reported each time. `save` keeps the files this run read.
333
+ */
334
+ const symbolCache = (root) => {
335
+ const path = join(root, "node_modules/.cache/ref0-workspace-symbols/symbols.bin");
336
+ const kept = (() => {
337
+ try {
338
+ const value = deserialize(readFileSync(path));
339
+ return isKept(value) ? value[1] : /* @__PURE__ */ new Map();
340
+ } catch {
341
+ return /* @__PURE__ */ new Map();
342
+ }
343
+ })();
344
+ const read = /* @__PURE__ */ new Map();
345
+ let parsedAny = false;
346
+ /** The top-level declarations in one file. A file that doesn't parse has none. */
347
+ const symbolsOf = (file) => {
348
+ const key = createHash("sha1").update(`${file.path}\0`).update(file.text).digest("hex");
349
+ const known = read.get(key) ?? kept.get(key);
350
+ if (known !== void 0) {
351
+ read.set(key, known);
352
+ return known;
353
+ }
354
+ const symbols = parsed(file);
355
+ if (symbols === void 0) return [];
356
+ parsedAny = true;
357
+ read.set(key, symbols);
358
+ return symbols;
359
+ };
360
+ /** Keeps the declarations of the files this run read, when they aren't what's kept already. */
361
+ const save = () => {
362
+ if (!parsedAny && read.size === kept.size) return;
363
+ const temporary = `${path}.${pid}`;
364
+ mkdirSync(dirname(path), { recursive: true });
365
+ writeFileSync(temporary, serialize([version, read]));
366
+ renameSync(temporary, path);
367
+ };
368
+ return {
369
+ symbolsOf,
370
+ save
371
+ };
372
+ };
373
+ /** How alike two sets of runs are: what they share over what either has, from 0 to 1. */
374
+ const likeness = (a, b) => {
375
+ let shared = 0;
376
+ let i = 0;
377
+ let j = 0;
378
+ while (i < a.length && j < b.length) {
379
+ const x = a[i] ?? 0;
380
+ const y = b[j] ?? 0;
381
+ if (x === y) {
382
+ shared += 1;
383
+ i += 1;
384
+ j += 1;
385
+ } else if (x < y) i += 1;
386
+ else j += 1;
387
+ }
388
+ return shared / (a.length + b.length - shared);
389
+ };
390
+ export { filesAt, git, indexed, likeness, repoRoot, symbolCache, workingFiles };
@@ -0,0 +1,68 @@
1
+ import { fromRoot, reachedProjects } from "./types/projects.mjs";
2
+ import { execFile } from "node:child_process";
3
+ import { execPath } from "node:process";
4
+ import { promisify } from "node:util";
5
+ import { dirname, join } from "node:path";
6
+ // src/type-coverage.ts
7
+ /**
8
+ * Fails when a tracked TypeScript file is in no project the root `tsconfig.json` reaches, or when
9
+ * lint ignores it.
10
+ *
11
+ * ref0-workspace type-coverage
12
+ *
13
+ * `types`, the type check, checks the projects the root reaches, each file with the options of the
14
+ * project that includes it, and a file that none includes not at all. The root's references are
15
+ * the workspace's projects: one outside them goes unseen, as one in ref0 once gave its SDK's source
16
+ * no Node types and hid 44 errors. So this follows the root's references, and each project's own,
17
+ * asks TypeScript which files each project includes, and names every tracked `.ts`, `.tsx`, `.mts`
18
+ * or `.cts` file that none does.
19
+ *
20
+ * Lint's rules, its type-aware ones too, read only the files lint doesn't ignore, as lint ignoring
21
+ * a folder in ref0 once hid 57 errors. So this asks lint, the repo's own Vite+, which files it
22
+ * reads, and names every tracked TypeScript file it doesn't, other than the files a tool writes.
23
+ */
24
+ const run = promisify(execFile);
25
+ const generated = /\.gen\.(?:d\.)?ts$/u;
26
+ /** The files lint reads in the workspace at `root`, by path from it. */
27
+ const lintedFiles = async (root) => {
28
+ const vp = join(dirname(fromRoot(root, "vite-plus/package.json")), "bin/vp");
29
+ const { stdout } = await run(execPath, [
30
+ vp,
31
+ "lint",
32
+ "--debug=files"
33
+ ], {
34
+ cwd: root,
35
+ maxBuffer: 67108864
36
+ });
37
+ return new Set(stdout.split("\n").filter((path) => path !== ""));
38
+ };
39
+ /** Checks the repo at `root`, names each file outside, and answers the exit code. */
40
+ const typeCoverage = async (root) => {
41
+ const { stdout: listed } = await run("git", [
42
+ "ls-files",
43
+ "-z",
44
+ "--",
45
+ "*.ts",
46
+ "*.tsx",
47
+ "*.mts",
48
+ "*.cts"
49
+ ], {
50
+ cwd: root,
51
+ encoding: "utf8",
52
+ maxBuffer: 67108864
53
+ });
54
+ const tracked = listed.split("\0").filter((path) => path !== "");
55
+ const [projects, linted] = await Promise.all([reachedProjects(root, join(root, "tsconfig.json")), lintedFiles(root)]);
56
+ const reached = new Set(projects.flatMap(({ files }) => [...files]));
57
+ const uncovered = tracked.filter((path) => !reached.has(join(root, path)));
58
+ const unlinted = tracked.filter((path) => !linted.has(path) && !generated.test(path));
59
+ for (const path of uncovered) console.error(`::error file=${path}::${path} is in no project the root tsconfig.json reaches: include it in one, or reference its project from tsconfig.json.`);
60
+ for (const path of unlinted) console.error(`::error file=${path}::${path} is a file lint ignores, so no lint rule reads it: take it out of lint's ignorePatterns in vite.config.ts.`);
61
+ if (uncovered.length > 0 || unlinted.length > 0) {
62
+ console.error(`type-coverage: of ${tracked.length} TypeScript files, ${uncovered.length} are in no project and lint ignores ${unlinted.length}`);
63
+ return 1;
64
+ }
65
+ console.log(`type-coverage: all ${tracked.length} TypeScript files are in a project the root reaches, and lint reads each one a tool doesn't write`);
66
+ return 0;
67
+ };
68
+ export { typeCoverage };
@@ -0,0 +1,157 @@
1
+ import { manifestInputs, sha256, workspaceFiles } from "./inputs.mjs";
2
+ import { env } from "node:process";
3
+ import { isAbsolute, join, relative, resolve } from "node:path";
4
+ import { Option, Schema } from "effect";
5
+ import { randomBytes } from "node:crypto";
6
+ import { mkdir, readFile, readdir, rename, stat, unlink, utimes, writeFile } from "node:fs/promises";
7
+ import { homedir } from "node:os";
8
+ // src/types/cache.ts
9
+ /**
10
+ * Each project's type check results, kept for every worktree on the machine in one folder,
11
+ * `$XDG_CACHE_HOME/ref0-workspace-types/` or `~/.cache/ref0-workspace-types/`, or
12
+ * `REF0_WORKSPACE_TYPES_CACHE` when it's set, so `types` replays a project whose inputs another
13
+ * worktree, or this one, already checked, and checks the rest.
14
+ *
15
+ * A project's key hashes the contents of every file its program read, as tsrs's `--listFiles`
16
+ * named them, except the packages under `node_modules/.pnpm/`, which the lockfile pins. It also
17
+ * hashes what decides which files a program reads and how: the lockfile, `pnpm-workspace.yaml`,
18
+ * every `package.json` and `tsconfig*.json` in the workspace and each file a config's `extends`
19
+ * names, the path of every file a project includes, and tsrs's arguments. So an edit to any file
20
+ * a program read moves that project's key, and adding, removing or renaming a project's file moves
21
+ * every key. Contents are hashed rather than dated, since each worktree is a fresh checkout, and
22
+ * every path is from the worktree's root, so two worktrees at the same contents share a key. A
23
+ * result is kept only when no file it read, and no shared input, changed while it ran.
24
+ *
25
+ * Each result is a file named by its key, in a folder for its project, so worktrees on different
26
+ * branches keep theirs side by side, and a project keeps its `kept` most recently used. A result
27
+ * is written to a file of its own and renamed into place, so a reader in another worktree finds it
28
+ * whole or not at all, and one removed while it's read was opened already. `types` keeps only
29
+ * passes.
30
+ *
31
+ * It doesn't see a new file that would win a module resolution tsrs made elsewhere, outside every
32
+ * project's includes, such as a hand-made package in an ignored `node_modules`.
33
+ */
34
+ /** A kept result: the files its program read, from the root, and the key they hashed to. */
35
+ const Entry = Schema.Struct({
36
+ key: Schema.String,
37
+ files: Schema.Array(Schema.String),
38
+ status: Schema.Number,
39
+ diagnostics: Schema.String
40
+ });
41
+ const decodeEntry = Schema.decodeUnknownOption(Schema.fromJsonString(Entry));
42
+ const keptOrNone = (text) => Option.getOrUndefined(decodeEntry(text));
43
+ /** Splits tsrs's output into its diagnostics and the files `--listFiles` named, by absolute path. */
44
+ const splitListed = (output) => {
45
+ const files = [];
46
+ const diagnostics = [];
47
+ for (const line of output.split("\n")) if (isAbsolute(line) && !/\(\d+,\d+\): /.test(line)) files.push(line);
48
+ else diagnostics.push(line);
49
+ return {
50
+ files,
51
+ diagnostics: diagnostics.join("\n")
52
+ };
53
+ };
54
+ /** A write left by a run that died before its rename, which no live run still writes after this. */
55
+ const abandonedMs = 36e5;
56
+ /**
57
+ * The machine's folder of results, for every worktree: `REF0_WORKSPACE_TYPES_CACHE`, from `root`,
58
+ * or the user's cache.
59
+ */
60
+ const cacheFolder = (root) => {
61
+ const named = env["REF0_WORKSPACE_TYPES_CACHE"];
62
+ if (named !== void 0 && named !== "") return resolve(root, named);
63
+ const base = env["XDG_CACHE_HOME"];
64
+ return join(base !== void 0 && isAbsolute(base) ? base : join(homedir(), ".cache"), "ref0-workspace-types");
65
+ };
66
+ /** The cache for `root`'s projects, checked with tsrs's `args`. */
67
+ const typesCache = (root, projects, args) => {
68
+ const folder = cacheFolder(root);
69
+ const hashes = /* @__PURE__ */ new Map();
70
+ const hashOf = (file) => {
71
+ let hash = hashes.get(file);
72
+ if (hash === void 0) {
73
+ hash = readFile(join(root, file)).then(sha256, () => "missing");
74
+ hashes.set(file, hash);
75
+ }
76
+ return hash;
77
+ };
78
+ const sharedAt = Date.now();
79
+ const sharedInputs = manifestInputs(root, workspaceFiles(root));
80
+ const shared = (async () => {
81
+ const included = projects.flatMap(({ files }) => [...files].map((file) => relative(root, file)));
82
+ return sha256(JSON.stringify({
83
+ args,
84
+ inputs: await Promise.all(sharedInputs.map(async (file) => [file, await hashOf(file)])),
85
+ included: included.sort()
86
+ }));
87
+ })();
88
+ const changedSince = async (files, since, gone) => {
89
+ return (await Promise.all(files.map((file) => stat(resolve(root, file)).then(({ mtimeMs }) => mtimeMs, () => gone)))).some((time) => time >= since);
90
+ };
91
+ const keyOf = async (files) => sha256(JSON.stringify([await shared, await Promise.all(files.map(async (file) => [file, await hashOf(file)]))]));
92
+ const projectFolder = (project) => join(folder, sha256(relative(root, project.config)).slice(0, 16));
93
+ const listed = async (project) => {
94
+ const at = projectFolder(project);
95
+ const names = await readdir(at).catch(() => []);
96
+ return (await Promise.all(names.map(async (name) => {
97
+ const time = await stat(join(at, name)).then(({ mtimeMs }) => mtimeMs, () => void 0);
98
+ return time === void 0 ? [] : [[name, time]];
99
+ }))).flat().sort((a, b) => b[1] - a[1]);
100
+ };
101
+ /**
102
+ * The project's result whose key holds, of those it keeps, any worktree's. A replay marks it
103
+ * used, so the results a project keeps are those runs still ask for.
104
+ */
105
+ const replay = async (project) => {
106
+ const at = projectFolder(project);
107
+ const results = (await listed(project)).filter(([name]) => name.endsWith(".json"));
108
+ for (const [name] of results.slice(0, 32)) {
109
+ const text = await readFile(join(at, name), "utf8").catch(() => void 0);
110
+ const entry = text === void 0 ? void 0 : keptOrNone(text);
111
+ if (entry === void 0 || name !== `${entry.key}.json`) continue;
112
+ const { key, files, status, diagnostics } = entry;
113
+ if (await keyOf(files) !== key) continue;
114
+ const now = /* @__PURE__ */ new Date();
115
+ await utimes(join(at, name), now, now).catch(() => void 0);
116
+ return {
117
+ status,
118
+ diagnostics
119
+ };
120
+ }
121
+ };
122
+ const prune = async (project) => {
123
+ const at = projectFolder(project);
124
+ const all = await listed(project);
125
+ const results = all.filter(([name]) => name.endsWith(".json"));
126
+ const abandoned = all.filter(([name, time]) => !name.endsWith(".json") && time < Date.now() - abandonedMs);
127
+ for (const [name] of [...results.slice(32), ...abandoned]) await unlink(join(at, name)).catch(() => void 0);
128
+ };
129
+ /**
130
+ * Keeps a fresh result, read from `listed`, the absolute paths tsrs named, unless a file it read
131
+ * changed after `started`, when tsrs began, or a shared input changed after it was read.
132
+ */
133
+ const keep = async (project, started, listed, result) => {
134
+ const files = listed.flatMap((file) => {
135
+ const path = relative(root, file);
136
+ return path.startsWith("node_modules/.pnpm/") || path.startsWith("..") ? [] : [path];
137
+ }).sort();
138
+ if (await changedSince(files, started, Infinity) || await changedSince(sharedInputs, sharedAt, 0)) return;
139
+ const at = projectFolder(project);
140
+ const key = await keyOf(files);
141
+ const out = join(at, `${key}.json`);
142
+ const temporary = `${out}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
143
+ await mkdir(at, { recursive: true });
144
+ await writeFile(temporary, JSON.stringify({
145
+ key,
146
+ files,
147
+ ...result
148
+ }));
149
+ await rename(temporary, out);
150
+ await prune(project);
151
+ };
152
+ return {
153
+ replay,
154
+ keep
155
+ };
156
+ };
157
+ export { cacheFolder, splitListed, typesCache };