@hublo/sentinel 1.7.0-alpha.4 → 1.7.0-alpha.6

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.
@@ -12,8 +12,8 @@ import {
12
12
  presetNotInstalledYet,
13
13
  registerAdapters,
14
14
  resolve
15
- } from "../chunk-CTSBAGVM.js";
16
- import "../chunk-ETVNZUU4.js";
15
+ } from "../chunk-YRBFCQQI.js";
16
+ import "../chunk-ZZMYV576.js";
17
17
  import {
18
18
  resolveContext,
19
19
  separateToolArgs
@@ -594,45 +594,42 @@ async function runMigrate(ctx) {
594
594
  );
595
595
  }
596
596
  if (!ctx.targets.includes("typescript")) return 1;
597
- const { migrateModule } = await import("../migrate-W5VLHDT5.js");
597
+ const { migrateModule } = await import("../migrate-X7PB2X7R.js");
598
598
  const migration = migrateModule(module.root, {
599
599
  write: !ctx.dryRun,
600
600
  workspaceRoot: findWorkspaceRoot(module.root) ?? module.root
601
601
  });
602
- if (ctx.json) {
603
- process.stdout.write(
604
- `${JSON.stringify({ module: module.name, target: "typescript", ...migration }, null, 2)}
605
- `
606
- );
607
- } else {
608
- const mark = migration.outcome === "migrated" || migration.outcome === "proved" ? "\u2713" : migration.outcome === "skipped" ? "\xB7" : "\u2717";
609
- process.stdout.write(` ${mark} ${module.name} \u2014 ${migration.message}
610
- `);
611
- for (const file of migration.files) {
612
- process.stdout.write(
613
- ` ${file.kept ? "\u2713" : "\xB7"} ${file.file}${file.reason ? `: ${file.reason}` : ""}
614
- `
602
+ process.stdout.write(
603
+ ctx.json ? `${JSON.stringify({ module: module.name, target: "typescript", ...migration }, null, 2)}
604
+ ` : renderMigration(module.name, migration)
605
+ );
606
+ return migration.outcome === "migrated" || migration.outcome === "proved" || migration.outcome === "skipped" ? 0 : 1;
607
+ }
608
+ var SHOWN_DIFFERENCES = 20;
609
+ function renderMigration(name, migration) {
610
+ const mark = migration.outcome === "migrated" || migration.outcome === "proved" ? "\u2713" : migration.outcome === "skipped" ? "\xB7" : "\u2717";
611
+ const lines = [` ${mark} ${name} \u2014 ${migration.message}`];
612
+ for (const file of migration.files) {
613
+ lines.push(` ${file.kept ? "\u2713" : "\xB7"} ${file.file}${file.reason ? `: ${file.reason}` : ""}`);
614
+ if (file.aliases !== void 0) {
615
+ lines.push(
616
+ ` ${file.legacy ? "extends legacy, " : ""}${file.aliases.kept} of ${file.aliases.of} aliases, ${file.resolutions ?? 0} resolutions compared${file.written && file.written.length > 0 ? `, wrote ${file.written.join(", ")}` : ""}`
615
617
  );
616
- if (file.aliases !== void 0) {
617
- process.stdout.write(
618
- ` ${file.legacy ? "extends legacy, " : ""}${file.aliases.kept} of ${file.aliases.of} aliases, ${file.resolutions ?? 0} resolutions compared${file.written && file.written.length > 0 ? `, wrote ${file.written.join(", ")}` : ""}
619
- `
620
- );
621
- }
622
- for (const line of [
623
- ...(file.configDifferences ?? []).map(
624
- (d) => `${d.key}: ${d.before ?? "unset"} -> ${d.after ?? "unset"}`
625
- ),
626
- ...file.resolutionDifferences ?? []
627
- ].slice(0, 20)) {
628
- process.stdout.write(` ${line}
629
- `);
630
- }
631
618
  }
632
- for (const note of migration.notes) process.stdout.write(` note: ${note}
633
- `);
619
+ const differences = [
620
+ ...(file.configDifferences ?? []).map(
621
+ (difference) => `${difference.key}: ${difference.before ?? "unset"} -> ${difference.after ?? "unset"}`
622
+ ),
623
+ ...file.resolutionDifferences ?? []
624
+ ];
625
+ for (const line of differences.slice(0, SHOWN_DIFFERENCES)) lines.push(` ${line}`);
626
+ if (differences.length > SHOWN_DIFFERENCES) {
627
+ lines.push(` \u2026 ${differences.length - SHOWN_DIFFERENCES} more, all of them under --json`);
628
+ }
634
629
  }
635
- return migration.outcome === "migrated" || migration.outcome === "proved" || migration.outcome === "skipped" ? 0 : 1;
630
+ for (const note of migration.notes) lines.push(` note: ${note}`);
631
+ return `${lines.join("\n")}
632
+ `;
636
633
  }
637
634
 
638
635
  // src/cli/run-validate.ts
@@ -2,13 +2,16 @@ import {
2
2
  DEFERRED_RULES,
3
3
  LEGACY_ENTRY,
4
4
  SHIPPED_PRESETS,
5
+ STACK_PRESET_PATTERN,
5
6
  appliedOptions,
7
+ comparable,
6
8
  extendsList,
7
9
  hasShippedPreset,
10
+ isLegacyEntry,
8
11
  raisedFromBase,
9
12
  tsLegacyLayer,
10
13
  tsPresetFor
11
- } from "./chunk-ETVNZUU4.js";
14
+ } from "./chunk-ZZMYV576.js";
12
15
  import {
13
16
  BaseAdapter,
14
17
  ESLINT_CONFIG_FILES,
@@ -7036,7 +7039,8 @@ function workspaceRootFrom(cwd) {
7036
7039
  var IMPORTER_TSCONFIGS = ["tsconfig.app.json", "tsconfig.lib.json", "tsconfig.json"];
7037
7040
  function toTable(workspaceRoot, found) {
7038
7041
  const table = /* @__PURE__ */ new Map();
7039
- for (const [alias, targets2] of Object.entries(found?.paths ?? {})) {
7042
+ if (found === void 0) return table;
7043
+ for (const [alias, targets2] of Object.entries(found.paths)) {
7040
7044
  if (alias === "apps/*" || alias === "libs/*") continue;
7041
7045
  table.set(
7042
7046
  alias,
@@ -7140,13 +7144,17 @@ function moduleOf(path2, roots) {
7140
7144
  }
7141
7145
  return best;
7142
7146
  }
7143
- function buildConsumerIndex(workspaceRoot, moduleRoots) {
7144
- const imported = /* @__PURE__ */ new Set();
7145
- const testOnly = /* @__PURE__ */ new Set();
7147
+ function chainKey(found) {
7148
+ return `${found.declaredIn}\0${found.baseDirectory}\0${JSON.stringify(found.paths)}`;
7149
+ }
7150
+ function importerTables(workspaceRoot, moduleRoots) {
7146
7151
  const baseTable = aliasTable(workspaceRoot);
7147
- const tableByChain = /* @__PURE__ */ new Map([
7148
- [`${join30(workspaceRoot, WORKSPACE_TSCONFIG)}\0${workspaceRoot}`, baseTable]
7149
- ]);
7152
+ const tableByChain = /* @__PURE__ */ new Map();
7153
+ try {
7154
+ const base = chainPaths(join30(workspaceRoot, WORKSPACE_TSCONFIG));
7155
+ if (base !== void 0) tableByChain.set(chainKey(base), baseTable);
7156
+ } catch {
7157
+ }
7150
7158
  const tableByModule = /* @__PURE__ */ new Map();
7151
7159
  const readCache = /* @__PURE__ */ new Map();
7152
7160
  const unreadable = [];
@@ -7163,13 +7171,19 @@ function buildConsumerIndex(workspaceRoot, moduleRoots) {
7163
7171
  const found = importerPaths(workspaceRoot, module, readCache, unreadable);
7164
7172
  let table = baseTable;
7165
7173
  if (found !== void 0) {
7166
- const chain = `${found.declaredIn}\0${found.baseDirectory}`;
7167
- table = tableByChain.get(chain) ?? toTable(workspaceRoot, found);
7168
- tableByChain.set(chain, table);
7174
+ const key = chainKey(found);
7175
+ table = tableByChain.get(key) ?? toTable(workspaceRoot, found);
7176
+ tableByChain.set(key, table);
7169
7177
  }
7170
7178
  tableByModule.set(module, table);
7171
7179
  return table;
7172
7180
  };
7181
+ return { baseTable, tableFor, unreadable };
7182
+ }
7183
+ function buildConsumerIndex(workspaceRoot, moduleRoots) {
7184
+ const imported = /* @__PURE__ */ new Set();
7185
+ const testOnly = /* @__PURE__ */ new Set();
7186
+ const { baseTable, tableFor, unreadable } = importerTables(workspaceRoot, moduleRoots);
7173
7187
  const hasAnyTable = baseTable.size > 0 || moduleRoots.some((module) => tableFor(`${module}/probe.ts`).size > 0);
7174
7188
  if (!hasAnyTable) return { imported, testOnly, builtFrom: "no alias table" };
7175
7189
  const result = spawnSync5(
@@ -7228,7 +7242,7 @@ function buildConsumerIndex(workspaceRoot, moduleRoots) {
7228
7242
  imported,
7229
7243
  testOnly,
7230
7244
  builtFrom: `git grep over ${distinctSpecifiers} distinct specifiers, ${seenByTable.size} alias table(s)`,
7231
- warnings: unreadable
7245
+ warnings: [...unreadable]
7232
7246
  };
7233
7247
  }
7234
7248
  function cacheKey(workspaceRoot) {
@@ -8365,11 +8379,11 @@ function presetOwnedKeys2(compilerOptions, preset) {
8365
8379
  const raised = raisedFromBase(preset);
8366
8380
  const presetOptions = tsPresetFor(preset).compilerOptions;
8367
8381
  return owned.filter(
8368
- (key) => !raised.includes(key) || sameOptionValue(compilerOptions?.[key], presetOptions[key])
8382
+ (key) => !raised.includes(key) || sameOptionValue(key, compilerOptions?.[key], presetOptions[key])
8369
8383
  );
8370
8384
  }
8371
- function sameOptionValue(left, right) {
8372
- return JSON.stringify(left)?.toLowerCase() === JSON.stringify(right)?.toLowerCase();
8385
+ function sameOptionValue(key, left, right) {
8386
+ return comparable(key, left) === comparable(key, right);
8373
8387
  }
8374
8388
  function localOnlyCompilerOptions(compilerOptions, preset) {
8375
8389
  const sets = presetCompilerOptionKeys(preset);
@@ -8385,7 +8399,7 @@ function standardOverrides(compilerOptions, preset) {
8385
8399
  if (preset === void 0 || !hasShippedPreset(preset)) return [];
8386
8400
  const presetOptions = tsPresetFor(preset).compilerOptions;
8387
8401
  return raisedFromBase(preset).filter(
8388
- (key) => compilerOptions !== void 0 && key in compilerOptions && !sameOptionValue(compilerOptions[key], presetOptions[key])
8402
+ (key) => compilerOptions !== void 0 && key in compilerOptions && !sameOptionValue(key, compilerOptions[key], presetOptions[key])
8389
8403
  ).map((key) => ({
8390
8404
  rule: key,
8391
8405
  value: compilerOptions?.[key],
@@ -8431,7 +8445,7 @@ function resolveTsconfigTarget(moduleDir) {
8431
8445
  }
8432
8446
 
8433
8447
  // src/roles/typescript/read-adoption.ts
8434
- var SENTINEL_PRESET = /^@hublo\/sentinel\/(?:typescript|tsconfig)\/(?!legacy$)[a-z-]+$/;
8448
+ var SENTINEL_PRESET = STACK_PRESET_PATTERN;
8435
8449
  function readTsconfigAdoption(cwd) {
8436
8450
  return readAdoption(cwd, {
8437
8451
  candidates: TSCONFIG_CANDIDATES,
@@ -8490,11 +8504,10 @@ function typecheckScripts(cwd) {
8490
8504
  };
8491
8505
  }
8492
8506
  var SENTINEL_TS_PRESET = /@hublo\/sentinel\/(?:typescript|tsconfig)\//;
8493
- var SENTINEL_LEGACY = /@hublo\/sentinel\/(?:typescript|tsconfig)\/legacy$/;
8494
8507
  function composeExtends(current, preset) {
8495
8508
  const chain = typeof current === "string" ? [current] : Array.isArray(current) ? current.filter((entry) => typeof entry === "string") : [];
8496
8509
  const withoutOwn = chain.filter(
8497
- (entry) => entry !== preset && (!SENTINEL_TS_PRESET.test(entry) || SENTINEL_LEGACY.test(entry))
8510
+ (entry) => entry !== preset && (!SENTINEL_TS_PRESET.test(entry) || isLegacyEntry(entry))
8498
8511
  );
8499
8512
  return [...withoutOwn, preset];
8500
8513
  }
@@ -8830,7 +8843,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
8830
8843
  const config = this.readConfig(join33(ctx.cwd, target.path));
8831
8844
  const options = config?.compilerOptions;
8832
8845
  const overrides = standardOverrides(options, stack);
8833
- const legacy = config !== void 0 && extendsList(config).includes(LEGACY_ENTRY) ? legacyCompromises(options, stack) : [];
8846
+ const legacy = config !== void 0 && extendsList(config).some(isLegacyEntry) ? legacyCompromises(options, stack) : [];
8834
8847
  return {
8835
8848
  runner: "tsc",
8836
8849
  configFile: target.path,
@@ -259,11 +259,17 @@ function tsPresetFor(preset) {
259
259
  // src/roles/typescript/legacy.ts
260
260
  var BASE_FILE = "tsconfig.base.json";
261
261
  var LEGACY_ENTRY = `@hublo/sentinel/typescript/${LEGACY_LAYER}`;
262
+ function isLegacyEntry(entry) {
263
+ return entry === LEGACY_ENTRY;
264
+ }
265
+ var STACK_PRESET_PATTERN = new RegExp(
266
+ `^@hublo\\/sentinel\\/(?:typescript|tsconfig)\\/(?!${LEGACY_LAYER}$)[a-z-]+$`
267
+ );
262
268
  function isBaseEntry(entry) {
263
269
  return entry === BASE_FILE || entry.endsWith(`/${BASE_FILE}`);
264
270
  }
265
271
  function isStackPresetEntry(entry) {
266
- return /^@hublo\/sentinel\/(?:typescript|tsconfig)\/[a-z-]+$/.test(entry) && !entry.endsWith(`/${LEGACY_LAYER}`);
272
+ return STACK_PRESET_PATTERN.test(entry);
267
273
  }
268
274
  function extendsList(config) {
269
275
  const value = config.extends;
@@ -272,6 +278,7 @@ function extendsList(config) {
272
278
  }
273
279
 
274
280
  export {
281
+ comparable,
275
282
  appliedOptions,
276
283
  diffConfigs,
277
284
  remainder,
@@ -282,6 +289,8 @@ export {
282
289
  hasShippedPreset,
283
290
  tsPresetFor,
284
291
  LEGACY_ENTRY,
292
+ isLegacyEntry,
293
+ STACK_PRESET_PATTERN,
285
294
  isBaseEntry,
286
295
  isStackPresetEntry,
287
296
  extendsList
package/dist/index.js CHANGED
@@ -6,8 +6,8 @@ import {
6
6
  registerAdapters,
7
7
  resolve,
8
8
  setDefaultRunner
9
- } from "./chunk-CTSBAGVM.js";
10
- import "./chunk-ETVNZUU4.js";
9
+ } from "./chunk-YRBFCQQI.js";
10
+ import "./chunk-ZZMYV576.js";
11
11
  import {
12
12
  BaseAdapter
13
13
  } from "./chunk-P6KTBQ2Q.js";
@@ -6,7 +6,7 @@ import {
6
6
  isBaseEntry,
7
7
  isStackPresetEntry,
8
8
  remainder
9
- } from "./chunk-ETVNZUU4.js";
9
+ } from "./chunk-ZZMYV576.js";
10
10
  import {
11
11
  binFromOwnInstall,
12
12
  resolveBin,
@@ -20,7 +20,7 @@ import {
20
20
  import { execFileSync, spawnSync } from "node:child_process";
21
21
  import { existsSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
22
22
  import { createRequire } from "node:module";
23
- import { dirname as dirname2, join, relative as relative2, resolve as resolve2 } from "node:path";
23
+ import { dirname as dirname2, isAbsolute, join, relative as relative2, resolve as resolve2 } from "node:path";
24
24
  import { stripComments } from "jsonc-parser";
25
25
 
26
26
  // src/roles/typescript/migrate/detach.ts
@@ -79,7 +79,7 @@ function parseTrace(text) {
79
79
  const patterns = /* @__PURE__ */ new Set();
80
80
  let open;
81
81
  let afterPathsLine = false;
82
- for (const line of text.split("\n")) {
82
+ for (const line of text.split(/\r?\n/)) {
83
83
  const isPathsMatch = afterPathsLine;
84
84
  afterPathsLine = line.startsWith("'paths' option is specified");
85
85
  const resolving = RESOLVING_MODULE.exec(line) ?? RESOLVING_TYPE.exec(line);
@@ -110,9 +110,10 @@ function diffResolutions(before, after) {
110
110
  for (const key of /* @__PURE__ */ new Set([...before.keys(), ...after.keys()])) {
111
111
  const was = before.get(key);
112
112
  const now = after.get(key);
113
- if (was === now) continue;
113
+ if (was === now && before.has(key) === after.has(key)) continue;
114
114
  const [from, name] = key.split("\0");
115
- lines.push(`${from ?? ""}: '${name ?? ""}' ${was ?? "unresolved"} -> ${now ?? "unresolved"}`);
115
+ const say = (side, value) => side.has(key) ? value ?? "unresolved" : "absent";
116
+ lines.push(`${from ?? ""}: '${name ?? ""}' ${say(before, was)} -> ${say(after, now)}`);
116
117
  }
117
118
  return lines;
118
119
  }
@@ -128,25 +129,33 @@ function readTsconfig(file) {
128
129
  function tscFor(directory) {
129
130
  return resolveBin(directory, "tsc") ?? binFromOwnInstall("typescript", "tsc") ?? "tsc";
130
131
  }
132
+ var TSC_OUTPUT_LIMIT = 512 * 1024 * 1024;
131
133
  function tsc(directory, tsconfig, extra) {
132
- try {
133
- return execFileSync(tscFor(directory), ["-p", tsconfig, ...extra], {
134
- cwd: directory,
135
- encoding: "utf8",
136
- maxBuffer: 2 ** 31 - 1,
137
- stdio: ["ignore", "pipe", "pipe"]
138
- });
139
- } catch (error) {
140
- const failure = error;
141
- if (typeof failure.stdout === "string" && failure.stdout.length > 0) return failure.stdout;
142
- const said = typeof failure.stderr === "string" && failure.stderr !== "" ? failure.stderr : failure.message;
143
- throw new Error(`tsc -p ${tsconfig} ${extra.join(" ")}: ${String(said).trim()}`, {
144
- cause: error
145
- });
146
- }
134
+ const command = `tsc -p ${tsconfig} ${extra.join(" ")}`;
135
+ const run = spawnSync(tscFor(directory), ["-p", tsconfig, ...extra], {
136
+ cwd: directory,
137
+ encoding: "utf8",
138
+ maxBuffer: TSC_OUTPUT_LIMIT,
139
+ stdio: ["ignore", "pipe", "pipe"]
140
+ });
141
+ if (run.error !== void 0)
142
+ throw new Error(`${command}: ${run.error.message}`, { cause: run.error });
143
+ if (run.signal !== null) throw new Error(`${command}: killed by ${run.signal}`);
144
+ if (run.status === 0) return run.stdout;
145
+ const typeErrors = run.status === 1 || run.status === 2;
146
+ if (typeErrors && run.stdout.length > 0) return run.stdout;
147
+ const said = run.stderr.trim() || run.stdout.trim() || `exit ${String(run.status)}, no output`;
148
+ throw new Error(`${command}: ${said}`);
147
149
  }
148
150
  function showConfig(directory, tsconfig) {
149
- return JSON.parse(tsc(directory, tsconfig, ["--showConfig"]));
151
+ const printed = tsc(directory, tsconfig, ["--showConfig"]);
152
+ try {
153
+ return JSON.parse(printed);
154
+ } catch {
155
+ throw new Error(
156
+ `tsc --showConfig on ${join(directory, tsconfig)} did not print a config: ${printed.trim().slice(0, 300)}`
157
+ );
158
+ }
150
159
  }
151
160
  function withProbe(directory, config, use) {
152
161
  writeFileSync(join(directory, PROBE), JSON.stringify(config));
@@ -157,7 +166,8 @@ function withProbe(directory, config, use) {
157
166
  }
158
167
  }
159
168
  function compilesFiles(config) {
160
- return !(Array.isArray(config.files) && config.files.length === 0 && config.include === void 0);
169
+ const empty = (list) => Array.isArray(list) && list.length === 0;
170
+ return !(empty(config.files) && (config.include === void 0 || empty(config.include)));
161
171
  }
162
172
  function inheritors(directory, names, target) {
163
173
  const reaches = (name, seen) => {
@@ -178,20 +188,25 @@ function owner(file, directory) {
178
188
  }
179
189
  return directory;
180
190
  }
181
- function trackedFiles(directory) {
191
+ function moduleFiles(directory) {
192
+ let listed;
182
193
  try {
183
- return execFileSync("git", ["ls-files", "--cached"], { cwd: directory, encoding: "utf8" }).split("\n").filter(Boolean);
194
+ listed = execFileSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
195
+ cwd: directory,
196
+ encoding: "utf8"
197
+ });
184
198
  } catch {
185
199
  return void 0;
186
200
  }
187
- }
188
- function outsidePrograms(directory, chained, tracked) {
189
- const listed = new Set(
190
- chained.flatMap(
191
- (name) => tsc(directory, name, ["--listFilesOnly"]).split("\n").map((line) => line.trim()).filter(Boolean)
192
- )
201
+ return [...new Set(listed.split("\0").filter(Boolean))].filter(
202
+ (name) => existsSync(join(directory, name))
193
203
  );
194
- return tracked.filter((name) => SOURCE.test(name) && !name.endsWith(".d.ts")).map((name) => join(directory, name)).filter((file) => existsSync(file) && !listed.has(file) && owner(file, directory) === directory);
204
+ }
205
+ function programFiles(directory, name) {
206
+ return tsc(directory, name, ["--listFilesOnly"]).split(/\r?\n/).map((line) => line.trim()).filter((line) => isAbsolute(line));
207
+ }
208
+ function outsidePrograms(directory, listed, files) {
209
+ return files.filter((name) => SOURCE.test(name) && !name.endsWith(".d.ts")).map((name) => join(directory, name)).filter((file) => existsSync(file) && !listed.has(file) && owner(file, directory) === directory);
195
210
  }
196
211
  function trace(directory, name) {
197
212
  return parseTrace(tsc(directory, name, ["--noEmit", "--traceResolution"]));
@@ -226,29 +241,47 @@ function sentinelInstalls(directory, presets) {
226
241
  if (legacy === void 0) return "no-legacy";
227
242
  return presets.every((preset) => packageRoot(preset) === legacy) ? "one" : "several";
228
243
  }
229
- function migrateTsconfig(directory, target, names, options) {
230
- const file = join(directory, target);
231
- const shown = relative2(options.workspaceRoot, file);
232
- const original = readFileSync(file, "utf8");
244
+ function refused(file, refusal, reason) {
245
+ return { file, kept: false, refusal, reason };
246
+ }
247
+ function refuseEarly(directory, shown, original, chain) {
233
248
  if (stripComments(original) !== original) {
234
- return { file: shown, kept: false, reason: "it has comments a rewrite would drop; left as is" };
249
+ return refused(shown, "comments", "it has comments a rewrite would drop; left as is");
235
250
  }
236
- const config = readTsconfig(file);
237
- const chain = extendsList(config);
238
- const baseEntry = chain.find(isBaseEntry);
239
- if (baseEntry === void 0)
240
- return { file: shown, kept: false, reason: "it does not extend the base" };
241
- const baseFile = resolve2(directory, baseEntry);
242
- const base = readTsconfig(baseFile);
243
- const basePaths = base.compilerOptions?.paths ?? {};
251
+ const installs = sentinelInstalls(directory, chain.filter(isStackPresetEntry));
252
+ if (installs === "no-legacy") {
253
+ return refused(
254
+ shown,
255
+ "no-legacy",
256
+ `${LEGACY_ENTRY} does not resolve from this module: bump its @hublo/sentinel to the version running this command, run \`pnpm install\`, and run it again`
257
+ );
258
+ }
259
+ if (installs === "several") {
260
+ return refused(
261
+ shown,
262
+ "several-installs",
263
+ `${LEGACY_ENTRY} and the stack preset resolve from two different @hublo/sentinel installs here; give this module one sentinel version and run \`pnpm install\``
264
+ );
265
+ }
266
+ return void 0;
267
+ }
268
+ function baseline(directory, target, names, files) {
244
269
  const chained = inheritors(directory, names, target).filter(
245
270
  (name) => compilesFiles(readTsconfig(join(directory, name)))
246
271
  );
247
272
  const before = new Map(names.map((name) => [name, showConfig(directory, name)]));
273
+ const listed = new Map(chained.map((name) => [name, programFiles(directory, name)]));
274
+ const empty = new Set(chained.filter((name) => listed.get(name)?.length === 0));
248
275
  const traces = new Map(chained.map((name) => [name, trace(directory, name)]));
249
- const tracked = trackedFiles(directory);
250
- const outside = tracked === void 0 ? [] : outsidePrograms(directory, chained, tracked);
276
+ const compiled = new Set([...listed.values()].flat());
277
+ const outside = files === void 0 ? [] : outsidePrograms(directory, compiled, files);
251
278
  if (outside.length > 0) traces.set(OUTSIDE, traceOutside(directory, target, outside));
279
+ return { before, traces, outside, empty };
280
+ }
281
+ function planDetach(directory, config, chain, effective, traces) {
282
+ const baseFile = resolve2(directory, chain.find(isBaseEntry) ?? "");
283
+ const base = readTsconfig(baseFile);
284
+ const basePaths = base.compilerOptions?.paths ?? {};
252
285
  const matched = new Set([...traces.values()].flatMap((one) => [...one.patterns]));
253
286
  const paths = pickPaths(
254
287
  basePaths,
@@ -256,21 +289,11 @@ function migrateTsconfig(directory, target, names, options) {
256
289
  pathsRootOf(baseFile, base.compilerOptions?.baseUrl),
257
290
  directory
258
291
  );
259
- const effective = before.get(target) ?? {};
260
- const withoutBase = chain.filter((entry) => !isBaseEntry(entry));
261
292
  const inputs = Object.fromEntries(
262
293
  ["files", "include", "references"].filter((key) => key in config).map((key) => [key, config[key]])
263
294
  );
264
295
  const layers = (entries) => withProbe(directory, { extends: entries, ...inputs }, (probe) => showConfig(directory, probe));
265
- const installs = sentinelInstalls(directory, chain.filter(isStackPresetEntry));
266
- if (installs !== "one") {
267
- return {
268
- file: shown,
269
- kept: false,
270
- reason: installs === "no-legacy" ? `${LEGACY_ENTRY} does not resolve from this module: bump its @hublo/sentinel to the version running this command, run \`pnpm install\`, and run it again` : `${LEGACY_ENTRY} and the stack preset resolve from two different @hublo/sentinel installs here; give this module one sentinel version and run \`pnpm install\``
271
- };
272
- }
273
- const stack = layers(withoutBase);
296
+ const stack = layers(chain.filter((entry) => !isBaseEntry(entry)));
274
297
  const withLegacy = layers(chain.map((entry) => isBaseEntry(entry) ? LEGACY_ENTRY : entry));
275
298
  const stackApplied = appliedOptions(stack);
276
299
  const legacyKeys = new Set(
@@ -283,22 +306,14 @@ function migrateTsconfig(directory, target, names, options) {
283
306
  ({ key }) => key !== "paths"
284
307
  );
285
308
  const exclude = config.exclude === void 0 ? effective.exclude : void 0;
286
- const report = {
287
- file: shown,
288
- legacy,
289
- aliases: { kept: Object.keys(paths).length, of: Object.keys(basePaths).length },
290
- written: copied.map(({ key }) => key),
291
- resolutions: [...traces.values()].reduce((sum, one) => sum + one.resolutions.size, 0),
292
- outsidePrograms: outside.map((path) => relative2(directory, path))
293
- };
294
- let kept = false;
309
+ return { paths, legacy, copied, exclude, aliasesOfBase: Object.keys(basePaths).length };
310
+ }
311
+ function proveRewrite(directory, target, names, contents, { before, traces, outside }) {
312
+ const file = join(directory, target);
313
+ const original = readFileSync(file, "utf8");
295
314
  writeFileSync(`${file}${ORIGINAL}`, original);
296
315
  try {
297
- writeFileSync(
298
- file,
299
- `${JSON.stringify(detachedConfig({ config, legacy, copied, paths, exclude }), null, 2)}
300
- `
301
- );
316
+ writeFileSync(file, contents);
302
317
  const configDifferences = names.flatMap(
303
318
  (name) => diffConfigs(before.get(name) ?? {}, showConfig(directory, name)).map((difference) => ({
304
319
  ...difference,
@@ -311,24 +326,65 @@ function migrateTsconfig(directory, target, names, options) {
311
326
  (name === OUTSIDE ? traceOutside(directory, target, outside) : trace(directory, name)).resolutions
312
327
  ).map((line) => `${name}: ${line}`)
313
328
  );
314
- const proved = configDifferences.length === 0 && resolutionDifferences.length === 0;
315
- kept = proved && options.write;
316
- return {
317
- ...report,
318
- kept,
319
- ...proved ? {} : { reason: "tsc does not agree before and after; restored" },
320
- configDifferences,
321
- resolutionDifferences
322
- };
329
+ return { configDifferences, resolutionDifferences };
323
330
  } finally {
324
- if (!kept) writeFileSync(file, original);
331
+ writeFileSync(file, original);
325
332
  unlinkSync(`${file}${ORIGINAL}`);
326
333
  }
327
334
  }
328
- function restoreInterrupted(moduleRoot, tracked, notes, workspaceRoot) {
335
+ function proveTsconfig(directory, target, names, files, workspaceRoot) {
336
+ const file = join(directory, target);
337
+ const shown = relative2(workspaceRoot, file);
338
+ const original = readFileSync(file, "utf8");
339
+ const config = readTsconfig(file);
340
+ const chain = extendsList(config);
341
+ const early = refuseEarly(directory, shown, original, chain);
342
+ if (early !== void 0) return { result: early };
343
+ const known = baseline(directory, target, names, files);
344
+ const unread = [...known.traces].filter(
345
+ ([name, one]) => name !== OUTSIDE && !known.empty.has(name) && one.resolutions.size === 0
346
+ );
347
+ if (unread.length > 0) {
348
+ return {
349
+ result: refused(
350
+ shown,
351
+ "no-trace",
352
+ `tsc --traceResolution printed no resolution sentinel could read for ${unread.map(([name]) => name).join(", ")}; nothing can be proved`
353
+ )
354
+ };
355
+ }
356
+ const plan = planDetach(directory, config, chain, known.before.get(target) ?? {}, known.traces);
357
+ const contents = `${JSON.stringify(
358
+ detachedConfig({
359
+ config,
360
+ legacy: plan.legacy,
361
+ copied: plan.copied,
362
+ paths: plan.paths,
363
+ exclude: plan.exclude
364
+ }),
365
+ null,
366
+ 2
367
+ )}
368
+ `;
369
+ const differences = proveRewrite(directory, target, names, contents, known);
370
+ const agrees = differences.configDifferences.length === 0 && differences.resolutionDifferences.length === 0;
371
+ const result = {
372
+ file: shown,
373
+ kept: false,
374
+ ...agrees ? {} : { refusal: "disagrees", reason: "tsc does not agree before and after; restored" },
375
+ legacy: plan.legacy,
376
+ aliases: { kept: Object.keys(plan.paths).length, of: plan.aliasesOfBase },
377
+ written: plan.copied.map(({ key }) => key),
378
+ resolutions: [...known.traces.values()].reduce((sum, one) => sum + one.resolutions.size, 0),
379
+ outsidePrograms: known.outside.map((path) => relative2(directory, path)),
380
+ ...differences
381
+ };
382
+ return agrees ? { result, contents } : { result };
383
+ }
384
+ function restoreInterrupted(moduleRoot, files, notes, workspaceRoot) {
329
385
  const folders = /* @__PURE__ */ new Set([
330
386
  moduleRoot,
331
- ...(tracked ?? []).filter((name) => TSCONFIG_NAME.test(name.slice(name.lastIndexOf("/") + 1))).map((name) => join(moduleRoot, dirname2(name)))
387
+ ...(files ?? []).filter((name) => TSCONFIG_NAME.test(name.slice(name.lastIndexOf("/") + 1))).map((name) => join(moduleRoot, dirname2(name)))
332
388
  ]);
333
389
  for (const folder of folders) {
334
390
  for (const name of readdirSync(folder).filter((entry) => entry.endsWith(ORIGINAL))) {
@@ -341,9 +397,7 @@ function restoreInterrupted(moduleRoot, tracked, notes, workspaceRoot) {
341
397
  }
342
398
  }
343
399
  function formatWritten(moduleRoot, files, notes, options) {
344
- const proved = files.filter(
345
- (one) => options.write ? one.kept : one.configDifferences?.length === 0 && one.resolutionDifferences?.length === 0
346
- );
400
+ const proved = files.filter((one) => options.write ? one.kept : one.refusal === void 0);
347
401
  if (proved.length === 0) return;
348
402
  const formatter = writtenFileFormatter(moduleRoot);
349
403
  if (formatter === void 0) {
@@ -368,10 +422,10 @@ function formatWritten(moduleRoot, files, notes, options) {
368
422
  function isOwnModule(folder) {
369
423
  return existsSync(join(folder, "package.json")) || existsSync(join(folder, "project.json"));
370
424
  }
371
- function foldersToMigrate(moduleRoot, tracked, notes) {
425
+ function foldersToMigrate(moduleRoot, files, notes) {
372
426
  const nested = [
373
427
  ...new Set(
374
- (tracked ?? []).filter(
428
+ (files ?? []).filter(
375
429
  (name) => TSCONFIG_NAME.test(name.slice(name.lastIndexOf("/") + 1)) && name.includes("/")
376
430
  ).map((name) => join(moduleRoot, dirname2(name)))
377
431
  )
@@ -390,14 +444,83 @@ function foldersToMigrate(moduleRoot, tracked, notes) {
390
444
  (folder) => readdirSync(folder).filter((name) => TSCONFIG_NAME.test(name) && name !== PROBE).some((name) => extendsList(readTsconfig(join(folder, name))).some(isBaseEntry))
391
445
  );
392
446
  }
447
+ function removeLeftProbe(folder, notes, workspaceRoot) {
448
+ if (!existsSync(join(folder, PROBE))) return;
449
+ unlinkSync(join(folder, PROBE));
450
+ notes.push(`removed ${relative2(workspaceRoot, join(folder, PROBE))}, left by an interrupted run`);
451
+ }
452
+ function proveFolder(folder, files, workspaceRoot) {
453
+ const names = readdirSync(folder).filter((name) => TSCONFIG_NAME.test(name) && name !== PROBE);
454
+ const targets = names.filter(
455
+ (name) => extendsList(readTsconfig(join(folder, name))).some(isBaseEntry)
456
+ );
457
+ return targets.map((target) => {
458
+ const shown = relative2(workspaceRoot, join(folder, target));
459
+ if (!extendsList(readTsconfig(join(folder, target))).some(isStackPresetEntry)) {
460
+ return {
461
+ result: refused(
462
+ shown,
463
+ "not-adopted",
464
+ "it extends the base but no sentinel preset: only an adopted module is detached. Run `sentinel --init --typescript` first"
465
+ )
466
+ };
467
+ }
468
+ try {
469
+ return proveTsconfig(folder, target, names, files, workspaceRoot);
470
+ } catch (error) {
471
+ return { result: refused(shown, "error", error.message) };
472
+ }
473
+ });
474
+ }
475
+ function markPartlyAdopted(proved) {
476
+ const adopted = proved.filter(({ result }) => result.refusal !== "not-adopted");
477
+ if (adopted.length === 0) return;
478
+ for (const one of proved) {
479
+ if (one.result.refusal !== "not-adopted") continue;
480
+ const name = one.result.file.slice(one.result.file.lastIndexOf("/") + 1);
481
+ one.result = {
482
+ ...one.result,
483
+ refusal: "partly-adopted",
484
+ reason: `${name} extends the base without a sentinel preset, while this module's other tsconfigs are adopted: add the module's stack preset to its \`extends\` (or make it extend the adopted tsconfig), then run again`
485
+ };
486
+ }
487
+ }
488
+ function summarize(results, write) {
489
+ const plural = (count) => `${count} tsconfig${count === 1 ? "" : "s"}`;
490
+ if (results.every((one) => one.refusal === "not-adopted")) {
491
+ return {
492
+ outcome: "blocked",
493
+ message: "this module is not adopted: run `sentinel --init --typescript` first. Nothing was written"
494
+ };
495
+ }
496
+ const refusals = results.filter((one) => one.refusal !== void 0);
497
+ if (refusals.length === 0) {
498
+ return write ? {
499
+ outcome: "migrated",
500
+ message: `detached ${plural(results.length)} from tsconfig.base.json`
501
+ } : {
502
+ outcome: "proved",
503
+ message: "dry run: tsc agrees before and after on every tsconfig; nothing was written"
504
+ };
505
+ }
506
+ const disagreeing = refusals.filter((one) => one.refusal === "disagrees").length;
507
+ const unproved = refusals.length - disagreeing;
508
+ const why = [
509
+ ...disagreeing > 0 ? [`tsc does not agree on ${plural(disagreeing)}`] : [],
510
+ ...unproved > 0 ? [`${plural(unproved)} could not be proved`] : []
511
+ ].join(", ");
512
+ return { outcome: "failed", message: `${write ? "" : "dry run: "}${why}; nothing was written` };
513
+ }
393
514
  function migrateModule(moduleRoot, options) {
394
515
  const notes = [];
395
- const tracked = trackedFiles(moduleRoot);
396
- if (tracked === void 0) {
397
- notes.push("not a git checkout: the files outside every program were not traced");
516
+ const files = moduleFiles(moduleRoot);
517
+ if (files === void 0) {
518
+ notes.push(
519
+ "not a git checkout: the files outside every program were not traced, and only the module's own folder was checked for nested tsconfigs and for a run left interrupted"
520
+ );
398
521
  }
399
- restoreInterrupted(moduleRoot, tracked, notes, options.workspaceRoot);
400
- const folders = foldersToMigrate(moduleRoot, tracked, notes);
522
+ restoreInterrupted(moduleRoot, files, notes, options.workspaceRoot);
523
+ const folders = foldersToMigrate(moduleRoot, files, notes);
401
524
  if (folders.length === 0) {
402
525
  return {
403
526
  outcome: "skipped",
@@ -406,60 +529,22 @@ function migrateModule(moduleRoot, options) {
406
529
  notes
407
530
  };
408
531
  }
409
- const files = [];
532
+ const proved = [];
410
533
  for (const folder of folders) {
411
- if (existsSync(join(folder, PROBE))) {
412
- unlinkSync(join(folder, PROBE));
413
- notes.push(
414
- `removed ${relative2(options.workspaceRoot, join(folder, PROBE))}, left by an interrupted run`
415
- );
416
- }
417
- const names = readdirSync(folder).filter((name) => TSCONFIG_NAME.test(name) && name !== PROBE);
418
- const targets = names.filter(
419
- (name) => extendsList(readTsconfig(join(folder, name))).some(isBaseEntry)
420
- );
421
- for (const target of targets) {
422
- const chain = extendsList(readTsconfig(join(folder, target)));
423
- if (!chain.some(isStackPresetEntry)) {
424
- files.push({
425
- file: relative2(options.workspaceRoot, join(folder, target)),
426
- kept: false,
427
- reason: "it extends the base but no sentinel preset: only an adopted module is detached. Run `sentinel --init --typescript` first"
428
- });
429
- continue;
430
- }
431
- files.push(migrateTsconfig(folder, target, names, options));
432
- }
534
+ removeLeftProbe(folder, notes, options.workspaceRoot);
535
+ proved.push(...proveFolder(folder, files, options.workspaceRoot));
433
536
  }
434
- formatWritten(moduleRoot, files, notes, options);
435
- const refused = files.filter((one) => !one.kept);
436
- const notAdopted = files.every((one) => one.reason?.includes("no sentinel preset") === true);
437
- if (notAdopted) {
438
- return {
439
- outcome: "blocked",
440
- message: "this module is not adopted: run `sentinel --init --typescript` first. Nothing was written",
441
- files,
442
- notes
443
- };
444
- }
445
- const unproved = files.filter((one) => one.configDifferences === void 0);
446
- if (!options.write) {
447
- const proved = files.every(
448
- (one) => one.configDifferences?.length === 0 && one.resolutionDifferences?.length === 0
449
- );
450
- return {
451
- outcome: proved ? "proved" : "failed",
452
- message: proved ? "dry run: tsc agrees before and after on every tsconfig; nothing was written" : unproved.length > 0 ? `dry run: ${unproved.length} tsconfig${unproved.length === 1 ? "" : "s"} could not be proved; nothing was written` : "dry run: tsc does not agree on every tsconfig; nothing was written",
453
- files,
454
- notes
455
- };
537
+ markPartlyAdopted(proved);
538
+ const allHold = proved.every(({ result }) => result.refusal === void 0);
539
+ const write = options.write && allHold;
540
+ if (write) {
541
+ for (const { result, contents } of proved) {
542
+ writeFileSync(resolve2(options.workspaceRoot, result.file), contents ?? "");
543
+ }
456
544
  }
457
- return {
458
- outcome: refused.length === 0 ? "migrated" : "failed",
459
- message: refused.length === 0 ? `detached ${files.length} tsconfig${files.length === 1 ? "" : "s"} from tsconfig.base.json` : `${refused.length} of ${files.length} tsconfig${files.length === 1 ? "" : "s"} kept as they were`,
460
- files,
461
- notes
462
- };
545
+ const results = proved.map(({ result }) => ({ ...result, kept: write }));
546
+ formatWritten(moduleRoot, results, notes, options);
547
+ return { ...summarize(results, options.write), files: results, notes };
463
548
  }
464
549
  export {
465
550
  ORIGINAL,
@@ -72,7 +72,9 @@ and the `paths` entries tsc reports having MATCHED (`--traceResolution`), the se
72
72
  files no tsconfig compiles included. Measured on 113 modules (sentinel#147), that is all that is
73
73
  left once the presets carry the base's standards.
74
74
 
75
- It keeps nothing unless tsc agrees, and restores the file otherwise:
75
+ It is all or nothing. Every tsconfig of the module that extends the base is proved first, each
76
+ rewritten and put back in turn, and the module's files are written only when tsc agrees on every
77
+ one of them, on both:
76
78
 
77
79
  - `--showConfig` of every tsconfig of the folder applies the same options, `paths` aside. Applied,
78
80
  not printed: the base printed `alwaysStrict`, `allowJs: false` and `isolatedModules`, and the
@@ -84,9 +86,31 @@ It keeps nothing unless tsc agrees, and restores the file otherwise:
84
86
  A kept tsconfig is then formatted with the style the module states (its `.oxfmtrc.json`, else
85
87
  the workspace's Prettier), the same rule `--init --test` follows: whitespace only, after tsc agreed.
86
88
 
87
- It refuses, and writes nothing, for a module not adopted yet (run `--init --typescript` first), a
88
- tsconfig with comments, and a module whose installed sentinel has no `legacy`. A nested folder
89
- that is a module of its own is named and left to its own run.
89
+ It refuses, and writes nothing, for:
90
+
91
+ - a module not adopted yet (run `--init --typescript` first);
92
+ - a module with one tsconfig that extends the base without a sentinel preset, even when the others
93
+ are proved (`partly-adopted`). On the monorepo that is `tsconfig.acceptance.json` in `contract`
94
+ and `network`. Detaching the rest would leave the module compiling two ways, still on the base.
95
+ `--init` adopts the main tsconfig only, so the fix is to add the stack preset to that file's
96
+ `extends`, or to make it extend the adopted tsconfig;
97
+ - a tsconfig with comments;
98
+ - a module whose installed sentinel has no `legacy`, or resolves it from another install than its
99
+ stack preset;
100
+ - a tsconfig tsc cannot read (`error`, naming what tsc said), or a program that compiles files and
101
+ whose trace yields no resolution at all (`no-trace`): every program resolves at least its type
102
+ references, the smallest of the monorepo's 111 traces 447, so none means the trace was not read.
103
+ A solution file (`files: []`, `include` absent or `[]`) compiles nothing and is not traced: its
104
+ programs are, through the tsconfigs that extend it. A program tsc lists no file for (a spec
105
+ tsconfig in a library with no tests) is not a `no-trace` either: its trace must stay empty
106
+ after the rewrite.
107
+
108
+ A nested folder that is a module of its own is named and left to its own run. Each refusal carries a
109
+ `refusal` code in `--json` (`not-adopted`, `partly-adopted`, `comments`, `no-legacy`,
110
+ `several-installs`, `no-trace`, `disagrees`, `error`).
111
+
112
+ `--dry-run` writes nothing either, but each tsconfig is rewritten on disk for the time of its proof.
113
+ A watcher (the Nx daemon, tsserver, a dev server) can see it come and go.
90
114
 
91
115
  Once migrated, `--inspect` lists the compromises the module takes from `legacy` under
92
116
  `inherited compromises (debt to remove)`: the options the stack preset does not set and the module
@@ -125,7 +149,7 @@ sentinel --inspect --typescript # adoption + conformity coverage
125
149
  | `--ci` | from the root, only affected modules; non-zero exit on failure |
126
150
  | `--json` | machine-readable envelope on stdout, for every verb; progress goes to stderr |
127
151
  | `--max-diagnostics <n>` | cap the diagnostics embedded per module in `--run --json` (`0` = no cap) |
128
- | `--dry-run` | preview what `--init` would write, or prove `--migrate` and restore, changing nothing |
152
+ | `--dry-run` | preview what `--init` would write, or prove `--migrate` and write nothing (see above) |
129
153
  | `--rehearse` | with `--dry-run`: run the autofix passes in a copy and name the source they rewrite |
130
154
  | `--runner <tool>` | override the default runner |
131
155
  | `-- <tool options>` | `--run` only, one type named: everything after `--` goes to tsc itself (see below) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hublo/sentinel",
3
- "version": "1.7.0-alpha.4",
3
+ "version": "1.7.0-alpha.6",
4
4
  "description": "One CLI that guards code health across Hublo repos: shared lint/typescript/build/test presets, static & dynamic analysis, and architecture checks.",
5
5
  "type": "module",
6
6
  "license": "MIT",