@stll/oxlint-config 0.8.0 → 0.9.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.
@@ -0,0 +1,870 @@
1
+ #!/usr/bin/env node
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ let node_fs = require("node:fs");
4
+ let node_child_process = require("node:child_process");
5
+ let node_path = require("node:path");
6
+ let node_fs_promises = require("node:fs/promises");
7
+ let node_module = require("node:module");
8
+ let node_os = require("node:os");
9
+ let node_perf_hooks = require("node:perf_hooks");
10
+ let node_util = require("node:util");
11
+ //#region src/typecheck-parity.ts
12
+ const fixtures = [
13
+ {
14
+ name: "module-detection",
15
+ flags: ["noUnusedLocals"],
16
+ files: { "input.ts": "const unused = 1;" },
17
+ codes: [6133]
18
+ },
19
+ {
20
+ name: "skip-declaration-check",
21
+ flags: ["skipLibCheck"],
22
+ files: { "input.d.ts": "export declare const value: MissingType;" },
23
+ codes: []
24
+ },
25
+ {
26
+ name: "json-import",
27
+ flags: ["resolveJsonModule"],
28
+ files: {
29
+ "data.json": "{ \"name\": \"value\" }",
30
+ "input.ts": "import data from \"./data.json\"; export const value: string = data.name;"
31
+ },
32
+ codes: []
33
+ },
34
+ {
35
+ name: "interop-import",
36
+ flags: ["esModuleInterop"],
37
+ files: {
38
+ "types.d.cts": "declare const value: string; export = value;",
39
+ "input.ts": "import value from \"./types.cjs\"; export const result: string = value;"
40
+ },
41
+ codes: []
42
+ },
43
+ {
44
+ name: "valid-control",
45
+ flags: [],
46
+ files: { "input.ts": "export const value: string = \"correct\";" },
47
+ codes: []
48
+ },
49
+ {
50
+ name: "type-mismatch",
51
+ flags: [],
52
+ files: { "input.ts": "export const value: number = \"wrong\";" },
53
+ codes: [2322]
54
+ },
55
+ {
56
+ name: "missing-property",
57
+ flags: [],
58
+ files: { "input.ts": "export const value: { name: string } = {};" },
59
+ codes: [2741]
60
+ },
61
+ {
62
+ name: "strict-null",
63
+ flags: ["strictNullChecks"],
64
+ files: { "input.ts": "export const value: string = null;" },
65
+ codes: [2322]
66
+ },
67
+ {
68
+ name: "unchecked-index",
69
+ flags: ["noUncheckedIndexedAccess"],
70
+ files: { "input.ts": "export const value: string = [\"value\"][1];" },
71
+ codes: [2322]
72
+ },
73
+ {
74
+ name: "unused-local",
75
+ flags: ["noUnusedLocals"],
76
+ files: { "input.ts": "const unused = 1; export {};" },
77
+ codes: [6133]
78
+ },
79
+ {
80
+ name: "unused-parameter",
81
+ flags: ["noUnusedParameters"],
82
+ files: { "input.ts": "export const value = (unused: string) => 1;" },
83
+ codes: [6133]
84
+ },
85
+ {
86
+ name: "implicit-any",
87
+ flags: ["noImplicitAny"],
88
+ files: { "input.ts": "export const value = (input) => input;" },
89
+ codes: [7006]
90
+ },
91
+ {
92
+ name: "missing-import",
93
+ flags: [],
94
+ files: { "input.ts": "import { value } from \"./missing.js\"; export { value };" },
95
+ codes: [2307]
96
+ },
97
+ {
98
+ name: "side-effect-import",
99
+ flags: ["noUncheckedSideEffectImports"],
100
+ files: { "input.ts": "import \"./missing.js\";" },
101
+ codes: [2882]
102
+ },
103
+ {
104
+ name: "generic-constraint",
105
+ flags: [],
106
+ files: { "input.ts": "type Box<T extends string> = { value: T }; export type Value = Box<number>;" },
107
+ codes: [2344]
108
+ },
109
+ {
110
+ name: "exact-optional",
111
+ flags: ["exactOptionalPropertyTypes"],
112
+ files: { "input.ts": "export const value: { optional?: string } = { optional: undefined };" },
113
+ codes: [2375]
114
+ },
115
+ {
116
+ name: "fallthrough",
117
+ flags: ["noFallthroughCasesInSwitch"],
118
+ files: { "input.ts": "export const run = (value: number) => { switch (value) { case 0: value++; case 1: return value; default: return 0; } };" },
119
+ codes: [7029]
120
+ },
121
+ {
122
+ name: "implicit-override",
123
+ flags: ["noImplicitOverride"],
124
+ files: { "input.ts": "class Base { value = 1; } export class Child extends Base { value = 2; }" },
125
+ codes: [4114]
126
+ },
127
+ {
128
+ name: "implicit-return",
129
+ flags: ["noImplicitReturns"],
130
+ files: { "input.ts": "export const run = (value: boolean) => { if (value) return 1; };" },
131
+ codes: [7030]
132
+ },
133
+ {
134
+ name: "unknown-catch",
135
+ flags: ["useUnknownInCatchVariables"],
136
+ files: { "input.ts": "export const run = () => { try { return 1; } catch (error) { return error.message; } };" },
137
+ codes: [18046]
138
+ },
139
+ {
140
+ name: "index-property",
141
+ flags: ["noPropertyAccessFromIndexSignature"],
142
+ files: { "input.ts": "export const run = (value: Record<string, string>) => value.name;" },
143
+ codes: [4111]
144
+ },
145
+ {
146
+ name: "erasable-syntax",
147
+ flags: ["erasableSyntaxOnly"],
148
+ files: { "input.ts": "export enum Value { First }" },
149
+ codes: [1294]
150
+ },
151
+ {
152
+ name: "type-only-import",
153
+ flags: ["verbatimModuleSyntax"],
154
+ files: {
155
+ "types.ts": "export type Value = string;",
156
+ "input.ts": "import { Value } from \"./types.js\"; export const value: Value = \"value\";"
157
+ },
158
+ codes: [1484]
159
+ },
160
+ {
161
+ name: "checked-javascript",
162
+ flags: ["allowJs", "checkJs"],
163
+ files: { "input.js": "/** @type {number} */\nexport const value = \"wrong\";" },
164
+ codes: [2322]
165
+ },
166
+ {
167
+ name: "strict-function",
168
+ flags: ["strictFunctionTypes"],
169
+ files: { "input.ts": "export const value: (input: string | number) => void = (input: string) => { input.toUpperCase(); };" },
170
+ codes: [2322]
171
+ },
172
+ {
173
+ name: "strict-initialization",
174
+ flags: ["strictPropertyInitialization"],
175
+ files: { "input.ts": "export class Value { name: string; }" },
176
+ codes: [2564]
177
+ },
178
+ {
179
+ name: "strict-bind",
180
+ flags: ["strictBindCallApply"],
181
+ files: { "input.ts": "const value = (input: string) => input; export const result = value.call(undefined, 1);" },
182
+ codes: [2345]
183
+ },
184
+ {
185
+ name: "implicit-this",
186
+ flags: ["noImplicitThis"],
187
+ files: { "input.ts": "export function value() { return this.name; }" },
188
+ codes: [2683]
189
+ },
190
+ {
191
+ name: "strict-iterator",
192
+ flags: ["strictBuiltinIteratorReturn"],
193
+ files: { "input.ts": "export const value: string = [\"value\"].values().next().value;" },
194
+ codes: [2322]
195
+ },
196
+ {
197
+ name: "always-strict",
198
+ flags: ["alwaysStrict"],
199
+ files: { "input.ts": "export const value = (eval: string) => eval;" },
200
+ codes: [1215]
201
+ },
202
+ {
203
+ name: "file-casing",
204
+ flags: ["forceConsistentCasingInFileNames"],
205
+ files: {
206
+ "named.ts": "export const name = \"value\";",
207
+ "Named.ts": "export const name = \"value\";",
208
+ "input.ts": "import { name } from \"./named.js\"; import { name as other } from \"./Named.js\"; export const value = name + other;"
209
+ },
210
+ codes: [1149, 1261],
211
+ anyCode: true
212
+ }
213
+ ];
214
+ const diagnosticCodes = (text) => [...new Set([...text.matchAll(/(?:TS|(?:error|warning)\s+)(\d{4,5})/g)].map((match) => Number(match.at(1))))].sort((a, b) => a - b);
215
+ const diagnosticParity = ({ expected, match, baseline, candidate }) => {
216
+ const tscCodes = diagnosticCodes(baseline.output);
217
+ const bunCodes = diagnosticCodes(candidate.output);
218
+ const seeded = match === "any" ? expected.some((code) => tscCodes.includes(code)) : expected.every((code) => tscCodes.includes(code));
219
+ const missing = tscCodes.filter((code) => !bunCodes.includes(code));
220
+ const extra = bunCodes.filter((code) => !tscCodes.includes(code));
221
+ const exitsMatch = expected.length === 0 ? baseline.status === 0 && candidate.status === 0 && tscCodes.length === 0 && bunCodes.length === 0 : baseline.status !== null && baseline.status !== 0 && candidate.status !== null && candidate.status !== 0;
222
+ return {
223
+ tscCodes,
224
+ bunCodes,
225
+ missing,
226
+ extra,
227
+ passed: seeded && exitsMatch && baseline.status === candidate.status && missing.length === 0 && extra.length === 0
228
+ };
229
+ };
230
+ const configurationDiagnostics = (output, repo) => diagnosticSet(output, repo).filter((diagnostic) => /^(?:<config>:0:|.*\.json:[0-9]+:)(?:[56][0-9]{3}|1800[23]|2688)(?::|$)/.test(diagnostic) || /:1800[23](?::|$)/.test(diagnostic));
231
+ const fixtureParity = (options) => {
232
+ const result = diagnosticParity(options);
233
+ const { baseline, candidate, expected, match } = options;
234
+ const identityParity = compareDiagnosticSets({
235
+ status: baseline.status,
236
+ diagnostics: diagnosticSet(baseline.output, options.repo ?? process.cwd())
237
+ }, {
238
+ status: candidate.status,
239
+ diagnostics: diagnosticSet(candidate.output, options.repo ?? process.cwd())
240
+ });
241
+ const configDiagnostics = [...configurationDiagnostics(baseline.output, options.repo ?? process.cwd()).map((diagnostic) => `TypeScript: ${diagnostic}`), ...configurationDiagnostics(candidate.output, options.repo ?? process.cwd()).map((diagnostic) => `Bun: ${diagnostic}`)];
242
+ const seedFiles = new Set(options.seedFiles.map((file) => (0, node_path.resolve)(options.repo ?? process.cwd(), file)));
243
+ const seededCodes = new Set(diagnosticSet(baseline.output, options.repo ?? process.cwd()).flatMap((diagnostic) => {
244
+ const diagnosticMatch = /^(.*):[0-9]+:([0-9]+)$/.exec(diagnostic);
245
+ const file = diagnosticMatch?.at(1);
246
+ const code = diagnosticMatch?.at(2);
247
+ return file !== void 0 && code !== void 0 && seedFiles.has((0, node_path.resolve)(options.repo ?? process.cwd(), file)) ? [Number(code)] : [];
248
+ }));
249
+ const active = expected.length > 0 && (match === "any" ? expected.some((code) => seededCodes.has(code)) : expected.every((code) => seededCodes.has(code)));
250
+ const validExits = baseline.status !== null && candidate.status !== null && (result.tscCodes.length === 0 ? baseline.status === 0 : baseline.status !== 0) && (result.bunCodes.length === 0 ? candidate.status === 0 : candidate.status !== 0);
251
+ return {
252
+ ...result,
253
+ active,
254
+ configurationDiagnostics: configDiagnostics,
255
+ identityMissing: identityParity.missing,
256
+ identityExtra: identityParity.extra,
257
+ passed: configDiagnostics.length === 0 && identityParity.passed && validExits && baseline.status === candidate.status && result.missing.length === 0 && result.extra.length === 0
258
+ };
259
+ };
260
+ const fixtureRunPassed = (results) => results.some(({ active }) => active) && results.every(({ passed }) => passed);
261
+ const diagnosticLocation = (file, repo) => {
262
+ const normalized = file.replaceAll("\\", "/");
263
+ const bundled = /^bundled:\/\/\/libs\/(lib\.[^/]+\.d\.ts)$/.exec(normalized);
264
+ const installed = /(?:^|\/)node_modules\/(?:typescript|@typescript\/(?:native|typescript-[^/]+))\/(?:.*\/)?(lib\.[^/]+\.d\.ts)$/.exec(normalized);
265
+ const library = bundled?.at(1) ?? installed?.at(1);
266
+ return library === void 0 ? (0, node_path.relative)(repo, (0, node_path.resolve)(repo, file)).replaceAll("\\", "/") : `<lib>/${library}`;
267
+ };
268
+ const globalDiagnosticKey = (code, message) => `<config>:0:${code}:${message.trim().replaceAll(/\s+/g, " ")}`;
269
+ const diagnosticSet = (output, repo) => {
270
+ const clean = (0, node_util.stripVTControlCharacters)(output);
271
+ const diagnostics = /* @__PURE__ */ new Set();
272
+ for (const block of clean.matchAll(/<error\b([^>]*)>([\s\S]*?)<\/error>/g)) {
273
+ const attributes = new Map([...(block.at(1) ?? "").matchAll(/(\w+)="([^"]*)"/g)].map((match) => [match.at(1), match.at(2)]));
274
+ const file = attributes.get("file");
275
+ const row = attributes.get("line");
276
+ const code = attributes.get("code");
277
+ if (code === void 0 || !/^TS\d+$/.test(code)) continue;
278
+ if (file !== void 0 && row !== void 0 && row !== "0") diagnostics.add(`${diagnosticLocation(file, repo)}:${row}:${code.slice(2)}`);
279
+ else {
280
+ const message = (block.at(2) ?? "").split(/<(?:source|related)\b/).at(0) ?? "";
281
+ diagnostics.add(globalDiagnosticKey(code.slice(2), message));
282
+ }
283
+ }
284
+ for (const line of clean.split("\n")) {
285
+ if (line.startsWith("<error ")) continue;
286
+ const match = /^(.*?)\((\d+),\d+\):\s*(?:error|warning) TS(\d+)/.exec(line) ?? /^(.*?):(\d+):\d+:\s*(?:error|warning) (?:TS)?(\d+)/.exec(line);
287
+ if (match) {
288
+ const [, file = "", row = "", code = ""] = match;
289
+ diagnostics.add(`${diagnosticLocation(file, repo)}:${row}:${code}`);
290
+ } else {
291
+ const global = /^(?:error|warning) TS(\d+):\s*(.*)/.exec(line);
292
+ if (global) diagnostics.add(globalDiagnosticKey(global.at(1) ?? "", global.at(2) ?? ""));
293
+ }
294
+ }
295
+ return [...diagnostics].sort();
296
+ };
297
+ const compareDiagnosticSets = (baseline, candidate) => {
298
+ const missing = baseline.diagnostics.filter((item) => !candidate.diagnostics.includes(item));
299
+ const extra = candidate.diagnostics.filter((item) => !baseline.diagnostics.includes(item));
300
+ const valid = (result) => result.status !== null && (result.diagnostics.length === 0 ? result.status === 0 : result.status !== 0);
301
+ return {
302
+ missing,
303
+ extra,
304
+ passed: valid(baseline) && valid(candidate) && baseline.status === candidate.status && missing.length === 0 && extra.length === 0
305
+ };
306
+ };
307
+ const assertUnshadowedCheck = async (repo) => {
308
+ const manifest = JSON.parse(await (0, node_fs_promises.readFile)((0, node_path.join)(repo, "package.json"), "utf8"));
309
+ if (typeof manifest !== "object" || manifest === null) throw new Error("Invalid repository package.json");
310
+ if ("scripts" in manifest && typeof manifest.scripts === "object" && manifest.scripts !== null && "check" in manifest.scripts) throw new Error("Repository package.json must not define a \"check\" script: it shadows Bun typechecking; rename that script before running parity");
311
+ };
312
+ const resolveCompiler = async (repo, policy) => {
313
+ if (typeof policy !== "object" || policy === null || !("typescriptInstallLayouts" in policy) || !Array.isArray(policy.typescriptInstallLayouts)) throw new Error("toolchain.json must define typescriptInstallLayouts");
314
+ const manifest = JSON.parse(await (0, node_fs_promises.readFile)((0, node_path.join)(repo, "package.json"), "utf8"));
315
+ if (typeof manifest !== "object" || manifest === null) throw new Error("Invalid repository package.json");
316
+ const dependencies = /* @__PURE__ */ new Map();
317
+ for (const key of ["dependencies", "devDependencies"]) {
318
+ if (!(key in manifest)) continue;
319
+ const section = Reflect.get(manifest, key);
320
+ if (typeof section === "object" && section !== null) for (const [name, specifier] of Object.entries(section)) dependencies.set(name, specifier);
321
+ }
322
+ const require = (0, node_module.createRequire)((0, node_path.join)(repo, "package.json"));
323
+ for (const layout of [...policy.typescriptInstallLayouts].reverse()) {
324
+ if (typeof layout !== "object" || layout === null || !("compilerPackage" in layout) || typeof layout.compilerPackage !== "string") throw new Error("Invalid TypeScript install layout");
325
+ if (!dependencies.has(layout.compilerPackage)) continue;
326
+ const packagePath = require.resolve(`${layout.compilerPackage}/package.json`);
327
+ const installed = JSON.parse(await (0, node_fs_promises.readFile)(packagePath, "utf8"));
328
+ if (typeof installed !== "object" || installed === null || !("bin" in installed) || typeof installed.bin !== "object" || installed.bin === null || !("tsc" in installed.bin) || typeof installed.bin.tsc !== "string") throw new Error(`${layout.compilerPackage} must expose a tsc binary`);
329
+ if (!("compilerSpecifier" in layout) || typeof layout.compilerSpecifier !== "string") throw new Error("TypeScript install layout must define compilerSpecifier");
330
+ const expectedVersion = layout.compilerSpecifier.replace(/^npm:typescript@/, "");
331
+ if (!("version" in installed) || installed.version !== expectedVersion) throw new Error(`${layout.compilerPackage} must install TypeScript ${expectedVersion}`);
332
+ return (0, node_path.resolve)(packagePath, "..", installed.bin.tsc);
333
+ }
334
+ throw new Error("Repository must declare a compiler from typescriptInstallLayouts");
335
+ };
336
+ const assertBunVersion = (bun, policy) => {
337
+ if (typeof policy !== "object" || policy === null || !("bun" in policy) || typeof policy.bun !== "string") throw new Error("toolchain.json must define bun");
338
+ const result = (0, node_child_process.spawnSync)(bun, ["--version"], { encoding: "utf8" });
339
+ if (result.error) throw result.error;
340
+ const installed = result.stdout.trim();
341
+ if (result.status !== 0 || installed !== policy.bun) throw new Error(`Bun must be ${policy.bun}; selected runtime reports ${installed || "no version"}`);
342
+ };
343
+ const bunCheckArgs = (project, build = false) => [
344
+ "check",
345
+ "--no-pretty",
346
+ "--all",
347
+ ...build ? ["--build"] : [],
348
+ ...project === void 0 ? [] : [`--project=${project}`]
349
+ ];
350
+ const canonicalOptions = (value) => {
351
+ if (Array.isArray(value)) return `[${value.map(canonicalOptions).join(",")}]`;
352
+ if (typeof value === "object" && value !== null) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalOptions(Reflect.get(value, key))}`).join(",")}}`;
353
+ if (value !== null && typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") throw new Error("Invalid effective compiler option");
354
+ return JSON.stringify(value);
355
+ };
356
+ const EMIT_ONLY_OPTIONS = /* @__PURE__ */ new Set([
357
+ "composite",
358
+ "declaration",
359
+ "declarationDir",
360
+ "declarationMap",
361
+ "emitDeclarationOnly",
362
+ "outDir",
363
+ "outFile",
364
+ "rootDir",
365
+ "sourceMap",
366
+ "inlineSourceMap",
367
+ "inlineSources",
368
+ "incremental",
369
+ "tsBuildInfoFile",
370
+ "noEmitOnError",
371
+ "importHelpers",
372
+ "noEmitHelpers",
373
+ "emitBOM",
374
+ "mapRoot",
375
+ "sourceRoot",
376
+ "newLine",
377
+ "preserveConstEnums",
378
+ "removeComments",
379
+ "stripInternal",
380
+ "downlevelIteration",
381
+ "isolatedDeclarations",
382
+ "noEmit"
383
+ ]);
384
+ const resolvedCompilerOptions = ({ compilerOptions, configPath }) => {
385
+ if (typeof compilerOptions !== "object" || compilerOptions === null || Array.isArray(compilerOptions)) throw new Error(`Invalid compiler options: ${configPath}`);
386
+ const options = Object.fromEntries(Object.entries(compilerOptions));
387
+ const directory = (0, node_path.dirname)(configPath);
388
+ const rootDir = options["rootDir"];
389
+ if (rootDir !== void 0 && typeof rootDir !== "string") throw new Error(`Invalid rootDir: ${configPath}`);
390
+ if (typeof rootDir === "string") options["rootDir"] = (0, node_path.resolve)(directory, rootDir);
391
+ let resolutionDirectory = directory;
392
+ const absolutePaths = (value) => {
393
+ if (!Array.isArray(value) || !value.every((entry) => typeof entry === "string")) throw new Error(`Invalid compiler path option: ${configPath}`);
394
+ return value.map((entry) => (0, node_path.resolve)(resolutionDirectory, entry));
395
+ };
396
+ for (const name of ["rootDirs", "typeRoots"]) if (name in options) options[name] = absolutePaths(options[name]);
397
+ if ("baseUrl" in options) {
398
+ const baseUrl = options["baseUrl"];
399
+ if (typeof baseUrl !== "string") throw new Error(`Invalid baseUrl: ${configPath}`);
400
+ resolutionDirectory = (0, node_path.resolve)(directory, baseUrl);
401
+ options["baseUrl"] = resolutionDirectory;
402
+ }
403
+ if ("paths" in options) {
404
+ const paths = options["paths"];
405
+ if (typeof paths !== "object" || paths === null || Array.isArray(paths)) throw new Error(`Invalid paths: ${configPath}`);
406
+ options["paths"] = Object.fromEntries(Object.entries(paths).map(([key, value]) => [key, absolutePaths(value)]));
407
+ }
408
+ return options;
409
+ };
410
+ const fixtureCompilerOptions = (args) => {
411
+ const options = Object.fromEntries(Object.entries(resolvedCompilerOptions(args)).filter(([name]) => !EMIT_ONLY_OPTIONS.has(name)));
412
+ options["noEmit"] = true;
413
+ return options;
414
+ };
415
+ const fixtureInputs = ({ files, compilerOptions }) => {
416
+ const inputs = files.filter((file) => /\.(?:[cm]?[jt]sx?|json)$/.test(file));
417
+ for (const input of inputs) {
418
+ if (/\.[cm]?jsx?$/.test(input) && compilerOptions["allowJs"] !== true) return {
419
+ status: "inapplicable",
420
+ reason: `${input} requires allowJs`
421
+ };
422
+ if (input.endsWith(".json") && compilerOptions["resolveJsonModule"] !== true) return {
423
+ status: "inapplicable",
424
+ reason: `${input} requires resolveJsonModule`
425
+ };
426
+ }
427
+ return {
428
+ status: "applicable",
429
+ files: inputs
430
+ };
431
+ };
432
+ const fixturePackageContext = (configPath) => {
433
+ for (let folder = (0, node_path.dirname)(configPath);; folder = (0, node_path.dirname)(folder)) {
434
+ try {
435
+ const manifest = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(folder, "package.json"), "utf8"));
436
+ if (typeof manifest !== "object" || manifest === null) throw new Error(`Invalid package.json: ${folder}`);
437
+ if (!("type" in manifest)) return {};
438
+ if (manifest.type !== "module" && manifest.type !== "commonjs") throw new Error(`Invalid package type: ${folder}`);
439
+ return { type: manifest.type };
440
+ } catch (error) {
441
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
442
+ }
443
+ if ((0, node_path.dirname)(folder) === folder) return {};
444
+ }
445
+ };
446
+ const groupCompilerConfigs = (configs) => {
447
+ const groups = /* @__PURE__ */ new Map();
448
+ for (const config of configs) {
449
+ const compilerOptions = fixtureCompilerOptions({
450
+ compilerOptions: config.compilerOptions,
451
+ configPath: config.path
452
+ });
453
+ const key = canonicalOptions({
454
+ compilerOptions,
455
+ resolutionContext: "typeRoots" in compilerOptions ? null : (0, node_path.dirname)(config.path),
456
+ packageContext: config.packageContext ?? {}
457
+ });
458
+ const existing = groups.get(key);
459
+ if (existing) existing.projects.push(config.path);
460
+ else groups.set(key, {
461
+ path: config.path,
462
+ projects: [config.path],
463
+ compilerOptions: config.compilerOptions,
464
+ ...config.packageContext === void 0 ? {} : { packageContext: config.packageContext }
465
+ });
466
+ }
467
+ return [...groups.values()];
468
+ };
469
+ const discoverConfigGroups = ({ repo, compiler }) => {
470
+ const configs = [];
471
+ const visited = /* @__PURE__ */ new Set();
472
+ const projects = [];
473
+ let build = false;
474
+ const visit = (project) => {
475
+ const path = (0, node_fs.realpathSync)((0, node_fs.statSync)(project).isDirectory() ? (0, node_path.join)(project, "tsconfig.json") : project);
476
+ if (visited.has(path)) return;
477
+ visited.add(path);
478
+ const result = (0, node_child_process.spawnSync)(process.execPath, [
479
+ compiler,
480
+ "--showConfig",
481
+ "--project",
482
+ path
483
+ ], {
484
+ cwd: repo,
485
+ encoding: "utf8",
486
+ maxBuffer: 64 * 1024 * 1024
487
+ });
488
+ if (result.error) throw result.error;
489
+ if (result.status !== 0) throw new Error(result.stdout + result.stderr);
490
+ const config = JSON.parse(result.stdout);
491
+ if (typeof config !== "object" || config === null) throw new Error(`Invalid resolved config: ${path}`);
492
+ const references = "references" in config && Array.isArray(config.references) ? config.references : [];
493
+ build ||= references.length > 0;
494
+ const compilerOptions = "compilerOptions" in config ? config.compilerOptions : {};
495
+ if (typeof compilerOptions !== "object" || compilerOptions === null || Array.isArray(compilerOptions)) throw new Error(`Invalid compiler options: ${path}`);
496
+ const rawFiles = "files" in config ? config.files : [];
497
+ if (!Array.isArray(rawFiles)) throw new Error(`Invalid project files: ${path}`);
498
+ const files = rawFiles.map((file) => {
499
+ if (typeof file !== "string") throw new Error(`Invalid project file: ${path}`);
500
+ return (0, node_path.resolve)((0, node_path.dirname)(path), file);
501
+ });
502
+ const referencePaths = [];
503
+ projects.push({
504
+ path,
505
+ compilerOptions,
506
+ files,
507
+ references: referencePaths
508
+ });
509
+ if (files.length > 0 || references.length === 0) configs.push({
510
+ path,
511
+ compilerOptions,
512
+ packageContext: fixturePackageContext(path)
513
+ });
514
+ for (const reference of references) {
515
+ if (typeof reference !== "object" || reference === null || !("path" in reference) || typeof reference.path !== "string") throw new Error(`Invalid project reference: ${path}`);
516
+ const referencedProject = (0, node_path.resolve)((0, node_path.dirname)(path), reference.path);
517
+ const referencePath = (0, node_fs.realpathSync)((0, node_fs.statSync)(referencedProject).isDirectory() ? (0, node_path.join)(referencedProject, "tsconfig.json") : referencedProject);
518
+ referencePaths.push(referencePath);
519
+ visit(referencePath);
520
+ }
521
+ };
522
+ visit((0, node_path.join)(repo, "tsconfig.json"));
523
+ const groups = groupCompilerConfigs(configs);
524
+ if (groups.length === 0) throw new Error("No consumer compiler configurations to compare");
525
+ return {
526
+ build,
527
+ groups,
528
+ projects
529
+ };
530
+ };
531
+ const timedCommand = ({ command, args, repo }) => {
532
+ const started = node_perf_hooks.performance.now();
533
+ const result = (0, node_child_process.spawnSync)("/usr/bin/time", [
534
+ process.platform === "darwin" ? "-l" : "-v",
535
+ command,
536
+ ...args
537
+ ], {
538
+ cwd: repo,
539
+ encoding: "utf8",
540
+ maxBuffer: 64 * 1024 * 1024
541
+ });
542
+ if (result.error) throw result.error;
543
+ const rss = process.platform === "darwin" ? /([0-9]+)\s+maximum resident set size/.exec(result.stderr) : /Maximum resident set size \(kbytes\):\s*([0-9]+)/.exec(result.stderr);
544
+ if (!rss) throw new Error("Cannot measure maximum RSS with /usr/bin/time");
545
+ return {
546
+ status: result.status,
547
+ output: result.stdout + result.stderr,
548
+ wall: (node_perf_hooks.performance.now() - started) / 1e3,
549
+ maxRssKiB: Number(rss[1]) / (process.platform === "darwin" ? 1024 : 1)
550
+ };
551
+ };
552
+ const NO_WORK_MAX_RSS_KIB = 16 * 1024;
553
+ const NO_WORK_MAX_WALL_SECONDS = .25;
554
+ const sourceDiagnosticSet = ({ output, repo, scratch, configPaths }) => {
555
+ const configs = new Set(configPaths.map((path) => (0, node_path.resolve)(path)));
556
+ const invalid = new Set(configurationDiagnostics(output, repo));
557
+ return diagnosticSet(output, repo).filter((diagnostic) => {
558
+ if (invalid.has(diagnostic)) return false;
559
+ if (diagnostic.startsWith("<config>:")) return true;
560
+ const file = /^(.*):[0-9]+:[0-9]+$/.exec(diagnostic)?.at(1);
561
+ if (file === void 0) return false;
562
+ const path = (0, node_path.resolve)(repo, file);
563
+ return !configs.has(path) && path !== scratch && !path.startsWith(scratch + "/");
564
+ });
565
+ };
566
+ const diagnosticExitStatus = ({ status, output, repo }) => status === 2 && configurationDiagnostics(output, repo).length === 0 && diagnosticSet(output, repo).some((diagnostic) => !diagnostic.startsWith("<config>:")) ? 1 : status;
567
+ const repositoryDiagnosticComparison = ({ baseline, candidate, repo, scratch, configPaths }) => {
568
+ const configs = new Set(configPaths.map((path) => (0, node_path.resolve)(path)));
569
+ const configurationErrors = (output) => [.../* @__PURE__ */ new Set([...configurationDiagnostics(output, repo), ...diagnosticSet(output, repo).filter((diagnostic) => {
570
+ const file = /^(.*):[0-9]+:[0-9]+$/.exec(diagnostic)?.at(1);
571
+ return file !== void 0 && configs.has((0, node_path.resolve)(repo, file));
572
+ })])];
573
+ const configurationErrorsFound = [...configurationErrors(baseline.output).map((diagnostic) => `TypeScript: ${diagnostic}`), ...configurationErrors(candidate.output).map((diagnostic) => `Bun: ${diagnostic}`)];
574
+ const diagnostics = (output) => sourceDiagnosticSet({
575
+ output,
576
+ repo,
577
+ scratch,
578
+ configPaths
579
+ });
580
+ const comparison = compareDiagnosticSets({
581
+ status: baseline.status,
582
+ diagnostics: diagnostics(baseline.output)
583
+ }, {
584
+ status: candidate.status,
585
+ diagnostics: diagnostics(candidate.output)
586
+ });
587
+ return {
588
+ ...comparison,
589
+ passed: configurationErrorsFound.length === 0 && comparison.passed,
590
+ configurationDiagnostics: configurationErrorsFound
591
+ };
592
+ };
593
+ const temporaryProjectTree = async ({ scratch, projects }) => {
594
+ const contexts = /* @__PURE__ */ new Map();
595
+ const linkedFolders = /* @__PURE__ */ new Set();
596
+ for (const project of projects) {
597
+ const path = (0, node_path.join)(scratch, "projects", (0, node_path.relative)((0, node_path.resolve)("/"), project));
598
+ const folder = (0, node_path.dirname)(path);
599
+ await (0, node_fs_promises.mkdir)(folder, { recursive: true });
600
+ for (let original = (0, node_path.dirname)(project);; original = (0, node_path.dirname)(original)) {
601
+ if (!linkedFolders.has(original)) {
602
+ linkedFolders.add(original);
603
+ const modules = (0, node_path.join)(original, "node_modules");
604
+ try {
605
+ if ((0, node_fs.statSync)(modules).isDirectory()) {
606
+ const destination = (0, node_path.join)(scratch, "projects", (0, node_path.relative)((0, node_path.resolve)("/"), original));
607
+ await (0, node_fs_promises.mkdir)(destination, { recursive: true });
608
+ await (0, node_fs_promises.symlink)(modules, (0, node_path.join)(destination, "node_modules"), "dir");
609
+ }
610
+ } catch (error) {
611
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
612
+ }
613
+ }
614
+ if ((0, node_path.dirname)(original) === original) break;
615
+ }
616
+ contexts.set(project, {
617
+ path,
618
+ folder,
619
+ outputFolder: (0, node_path.join)(folder, `${(0, node_path.basename)(path)}.parity-output`)
620
+ });
621
+ }
622
+ return contexts;
623
+ };
624
+ const compareRepository = async ({ repo, compiler, bun, graph }) => {
625
+ const scratch = await (0, node_fs_promises.mkdtemp)((0, node_path.join)((0, node_os.tmpdir)(), "parity-repository-"));
626
+ try {
627
+ const contexts = await temporaryProjectTree({
628
+ scratch,
629
+ projects: graph.projects.map(({ path }) => path)
630
+ });
631
+ const configPaths = new Map([...contexts].map(([original, context]) => [original, context.path]));
632
+ const requiredOutputs = new Set(graph.projects.flatMap(({ references }) => references));
633
+ for (const project of graph.projects) {
634
+ const context = contexts.get(project.path);
635
+ if (context === void 0) throw new Error(`Missing temporary project: ${project.path}`);
636
+ const { path: configPath, outputFolder } = context;
637
+ const options = resolvedCompilerOptions({
638
+ configPath: project.path,
639
+ compilerOptions: project.compilerOptions
640
+ });
641
+ const declarationsRequired = graph.build && requiredOutputs.has(project.path) && options["composite"] === true;
642
+ options["noEmit"] = !graph.build || options["noEmit"] === true && !declarationsRequired;
643
+ const relocatesOutput = options["noEmit"] !== true || "outDir" in options || "declarationDir" in options;
644
+ if (!("rootDir" in options) && relocatesOutput) options["rootDir"] = (0, node_path.dirname)(project.path);
645
+ if (relocatesOutput) options["outDir"] = (0, node_path.join)(outputFolder, "output");
646
+ const emitsDeclarations = options["declaration"] === true || options["composite"] === true && options["declaration"] !== false;
647
+ if (graph.build && emitsDeclarations || "declarationDir" in options) options["declarationDir"] = (0, node_path.join)(outputFolder, "declarations");
648
+ if (graph.build || options["incremental"] === true || options["composite"] === true) options["tsBuildInfoFile"] = (0, node_path.join)(outputFolder, "project.tsbuildinfo");
649
+ if (graph.build) {
650
+ options["declarationMap"] = false;
651
+ if (emitsDeclarations) options["emitDeclarationOnly"] = true;
652
+ options["noEmitOnError"] = false;
653
+ }
654
+ if ("outFile" in options) options["outFile"] = (0, node_path.join)(outputFolder, "bundle.js");
655
+ await (0, node_fs_promises.writeFile)(configPath, JSON.stringify({
656
+ compilerOptions: options,
657
+ files: project.files,
658
+ include: [],
659
+ references: project.references.map((path) => {
660
+ const temporary = configPaths.get(path);
661
+ if (temporary === void 0) throw new Error(`Missing referenced temporary project: ${path}`);
662
+ return { path: temporary };
663
+ })
664
+ }));
665
+ }
666
+ const root = configPaths.get((0, node_fs.realpathSync)((0, node_path.join)(repo, "tsconfig.json")));
667
+ if (root === void 0) throw new Error("Missing temporary root config");
668
+ const baselineRaw = timedCommand({
669
+ command: process.execPath,
670
+ args: [
671
+ compiler,
672
+ ...graph.build ? [
673
+ "--build",
674
+ "--force",
675
+ root
676
+ ] : [
677
+ "--noEmit",
678
+ "--project",
679
+ root
680
+ ],
681
+ "--pretty",
682
+ "false"
683
+ ],
684
+ repo
685
+ });
686
+ const candidate = timedCommand({
687
+ command: bun,
688
+ args: bunCheckArgs(root, graph.build),
689
+ repo
690
+ });
691
+ const sourceDiagnostics = (output) => sourceDiagnosticSet({
692
+ output,
693
+ repo,
694
+ scratch,
695
+ configPaths: graph.projects.map(({ path }) => path)
696
+ });
697
+ const baselineDiagnostics = sourceDiagnostics(baselineRaw.output);
698
+ const baseline = {
699
+ ...baselineRaw,
700
+ rawStatus: baselineRaw.status,
701
+ status: diagnosticExitStatus({
702
+ status: baselineRaw.status,
703
+ output: baselineRaw.output,
704
+ repo
705
+ }),
706
+ diagnostics: baselineDiagnostics
707
+ };
708
+ const repository = repositoryDiagnosticComparison({
709
+ baseline,
710
+ candidate,
711
+ repo,
712
+ scratch,
713
+ configPaths: [...graph.projects.map(({ path }) => path), ...configPaths.values()]
714
+ });
715
+ return {
716
+ baseline,
717
+ candidate: {
718
+ ...candidate,
719
+ rawStatus: candidate.status,
720
+ diagnostics: sourceDiagnostics(candidate.output)
721
+ },
722
+ repository
723
+ };
724
+ } finally {
725
+ await (0, node_fs_promises.rm)(scratch, {
726
+ recursive: true,
727
+ force: true
728
+ });
729
+ }
730
+ };
731
+ const runTypecheckParity = async ({ repo, policy, bun = process.versions.bun ? process.execPath : "bun" }) => {
732
+ await assertUnshadowedCheck(repo);
733
+ assertBunVersion(bun, policy);
734
+ const compiler = await resolveCompiler(repo, policy);
735
+ const graph = discoverConfigGroups({
736
+ repo,
737
+ compiler
738
+ });
739
+ const { groups } = graph;
740
+ const { baseline, candidate, repository } = await compareRepository({
741
+ repo,
742
+ compiler,
743
+ bun,
744
+ graph
745
+ });
746
+ console.log("Class | TypeScript diagnostics | Bun diagnostics | Result");
747
+ console.log(`repository | ${baseline.diagnostics.join(",")} | ${candidate.diagnostics.join(",")} | ${repository.passed ? "PASS" : "FAIL"}`);
748
+ console.log(`repository tsc: wall=${baseline.wall.toFixed(3)}s maxRSS=${baseline.maxRssKiB}KiB exit=${baseline.rawStatus}`);
749
+ console.log(`repository bun: wall=${candidate.wall.toFixed(3)}s maxRSS=${candidate.maxRssKiB}KiB exit=${candidate.rawStatus}`);
750
+ for (const diagnostic of repository.configurationDiagnostics) console.error(`FAIL: invalid repository configuration: ${diagnostic}`);
751
+ const scratch = await (0, node_fs_promises.mkdtemp)((0, node_path.join)((0, node_os.tmpdir)(), "typecheck-parity-"));
752
+ const groupResults = [];
753
+ try {
754
+ for (const [index, group] of groups.entries()) {
755
+ console.log(`Config group ${index + 1}: ${(0, node_path.relative)(repo, group.path)} (${group.projects.length} projects)`);
756
+ const results = [];
757
+ let tscWall = 0;
758
+ let bunWall = 0;
759
+ let tscRss = 0;
760
+ let bunRss = 0;
761
+ const context = (await temporaryProjectTree({
762
+ scratch: (0, node_path.join)(scratch, `config-${index + 1}`),
763
+ projects: [group.path]
764
+ })).get(group.path);
765
+ if (context === void 0) throw new Error(`Missing temporary fixture context: ${group.path}`);
766
+ const groupFolder = context.folder;
767
+ const compilerOptions = fixtureCompilerOptions({
768
+ compilerOptions: group.compilerOptions,
769
+ configPath: group.path
770
+ });
771
+ await (0, node_fs_promises.writeFile)((0, node_path.join)(groupFolder, "package.json"), JSON.stringify(group.packageContext ?? fixturePackageContext(group.path)));
772
+ for (const fixture of fixtures) {
773
+ const inputs = fixtureInputs({
774
+ files: Object.keys(fixture.files),
775
+ compilerOptions
776
+ });
777
+ if (inputs.status === "inapplicable") {
778
+ console.log(`${fixture.name} (inactive under this config: ${inputs.reason}) | | | INACTIVE`);
779
+ continue;
780
+ }
781
+ const folder = (0, node_path.join)(groupFolder, fixture.name);
782
+ await (0, node_fs_promises.mkdir)(folder);
783
+ await (0, node_fs_promises.writeFile)((0, node_path.join)(folder, "tsconfig.json"), JSON.stringify({
784
+ compilerOptions,
785
+ files: inputs.files,
786
+ include: [],
787
+ exclude: []
788
+ }));
789
+ for (const [name, content] of Object.entries(fixture.files)) await (0, node_fs_promises.writeFile)((0, node_path.join)(folder, name), content);
790
+ const tsc = timedCommand({
791
+ command: process.execPath,
792
+ args: [
793
+ compiler,
794
+ "--noEmit",
795
+ "--pretty",
796
+ "false",
797
+ "-p",
798
+ folder
799
+ ],
800
+ repo: folder
801
+ });
802
+ const checked = timedCommand({
803
+ command: bun,
804
+ args: [...bunCheckArgs(folder), "--threads=1"],
805
+ repo: folder
806
+ });
807
+ const result = fixtureParity({
808
+ seedFiles: inputs.files,
809
+ expected: fixture.codes,
810
+ match: fixture.anyCode ? "any" : "all",
811
+ repo: folder,
812
+ baseline: {
813
+ ...tsc,
814
+ status: diagnosticExitStatus({
815
+ status: tsc.status,
816
+ output: tsc.output,
817
+ repo: folder
818
+ })
819
+ },
820
+ candidate: checked
821
+ });
822
+ results.push(result);
823
+ tscWall += tsc.wall;
824
+ bunWall += checked.wall;
825
+ tscRss = Math.max(tscRss, tsc.maxRssKiB);
826
+ bunRss = Math.max(bunRss, checked.maxRssKiB);
827
+ if (result.configurationDiagnostics.length > 0) {
828
+ console.error(`FAIL: invalid fixture configuration for ${fixture.name}: ${result.configurationDiagnostics.join("; ")}`);
829
+ console.log(`${fixture.name} | configuration error | configuration error | FAIL`);
830
+ continue;
831
+ }
832
+ let outcome = "INACTIVE";
833
+ if (result.active) outcome = result.passed ? "PASS" : "FAIL";
834
+ console.log(`${fixture.name}${result.active ? "" : " (inactive under this config)"} | ${result.tscCodes.join(",")} | ${result.bunCodes.join(",")} | ${outcome}`);
835
+ if (!result.active && !result.passed) console.error(`FAIL: diagnostic comparison differs for inactive class ${fixture.name}: TypeScript exit=${tsc.status}, Bun exit=${checked.status}; missing=${result.identityMissing.join(",")}; extra=${result.identityExtra.join(",")}`);
836
+ if (result.active && result.bunCodes.length === 0) {
837
+ console.error(`FAIL: Bun returned zero diagnostics for active class ${fixture.name} (exit ${checked.status})`);
838
+ if (checked.maxRssKiB <= NO_WORK_MAX_RSS_KIB && checked.wall <= NO_WORK_MAX_WALL_SECONDS) console.error(`Bun measured little checker work: wall=${checked.wall.toFixed(3)}s maxRSS=${checked.maxRssKiB}KiB; verify the checker invocation`);
839
+ }
840
+ }
841
+ console.log(`fixtures tsc: wall=${tscWall.toFixed(3)}s maxRSS=${tscRss}KiB`);
842
+ console.log(`fixtures bun: wall=${bunWall.toFixed(3)}s maxRSS=${bunRss}KiB`);
843
+ if (!results.some(({ active }) => active)) console.error(`FAIL: zero seeded fixture classes active under config group ${index + 1}`);
844
+ groupResults.push(fixtureRunPassed(results));
845
+ }
846
+ } finally {
847
+ await (0, node_fs_promises.rm)(scratch, {
848
+ recursive: true,
849
+ force: true
850
+ });
851
+ }
852
+ return repository.passed && groupResults.every((passed) => passed);
853
+ };
854
+ //#endregion
855
+ //#region src/typecheck-parity-cli.ts
856
+ const main = async () => {
857
+ if (process.argv.slice(2).length > 0) throw new Error("Usage: stll-typecheck-parity (run from repository root)");
858
+ const policy = JSON.parse(await (0, node_fs_promises.readFile)(new URL("../toolchain.json", require("url").pathToFileURL(__filename).href), "utf8"));
859
+ if (!await runTypecheckParity({
860
+ repo: process.cwd(),
861
+ policy
862
+ })) process.exitCode = 1;
863
+ };
864
+ main().catch((error) => {
865
+ process.stderr.write(`typecheck-parity: ${error instanceof Error ? error.message : String(error)}\n`);
866
+ process.exitCode = 1;
867
+ });
868
+ //#endregion
869
+
870
+ //# sourceMappingURL=typecheck-parity-cli.cjs.map