react-doctor 0.2.13 → 0.2.14-dev.09fe1ff

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -59,6 +59,7 @@ var Diagnostic = class extends Schema.Class("Diagnostic")({
59
59
  plugin: Schema.String,
60
60
  rule: Schema.String,
61
61
  severity: Severity,
62
+ title: Schema.optional(Schema.String),
62
63
  message: Schema.String,
63
64
  help: Schema.String,
64
65
  url: Schema.optional(Schema.String),
@@ -2094,6 +2095,8 @@ const isFile = (filePath) => {
2094
2095
  }
2095
2096
  };
2096
2097
  const SOURCE_FILE_PATTERN = /\.(tsx?|jsx?)$/;
2098
+ const GENERATED_BUNDLE_FILE_PATTERN = /\.(iife|umd|global|min)\.js$/i;
2099
+ const MINIFIED_SNIFF_BYTES = 65536;
2097
2100
  const GIT_LS_FILES_MAX_BUFFER_BYTES = 50 * 1024 * 1024;
2098
2101
  const IGNORED_DIRECTORIES = new Set([
2099
2102
  ".git",
@@ -2109,6 +2112,34 @@ const IGNORED_DIRECTORIES = new Set([
2109
2112
  "out",
2110
2113
  "storybook-static"
2111
2114
  ]);
2115
+ const isLintableSourceFile = (filePath) => SOURCE_FILE_PATTERN.test(filePath) && !GENERATED_BUNDLE_FILE_PATTERN.test(filePath);
2116
+ const isMinifiedSource = (absolutePath) => {
2117
+ let fileDescriptor;
2118
+ try {
2119
+ fileDescriptor = fs.openSync(absolutePath, "r");
2120
+ const buffer = Buffer.alloc(MINIFIED_SNIFF_BYTES);
2121
+ const bytesRead = fs.readSync(fileDescriptor, buffer, 0, MINIFIED_SNIFF_BYTES, 0);
2122
+ const prefix = buffer.toString("utf8", 0, bytesRead);
2123
+ const lines = prefix.split("\n");
2124
+ const longestLineLength = lines.reduce((longest, line) => Math.max(longest, line.length), 0);
2125
+ const averageLineLength = prefix.length / lines.length;
2126
+ return longestLineLength > 1e3 && averageLineLength > 500;
2127
+ } catch {
2128
+ return false;
2129
+ } finally {
2130
+ if (fileDescriptor !== void 0) fs.closeSync(fileDescriptor);
2131
+ }
2132
+ };
2133
+ const isLargeMinifiedFile = (absolutePath) => {
2134
+ let sizeBytes;
2135
+ try {
2136
+ sizeBytes = fs.statSync(absolutePath).size;
2137
+ } catch {
2138
+ return false;
2139
+ }
2140
+ if (sizeBytes < 2e4) return false;
2141
+ return isMinifiedSource(absolutePath);
2142
+ };
2112
2143
  const IGNORABLE_READDIR_ERROR_CODES = new Set([
2113
2144
  "EACCES",
2114
2145
  "EPERM",
@@ -2139,7 +2170,7 @@ const countSourceFilesViaFilesystem = (rootDirectory) => {
2139
2170
  if (!entry.name.startsWith(".") && !IGNORED_DIRECTORIES.has(entry.name)) stack.push(path.join(currentDirectory, entry.name));
2140
2171
  continue;
2141
2172
  }
2142
- if (entry.isFile() && SOURCE_FILE_PATTERN.test(entry.name)) count++;
2173
+ if (entry.isFile() && isLintableSourceFile(entry.name) && !isLargeMinifiedFile(path.join(currentDirectory, entry.name))) count++;
2143
2174
  }
2144
2175
  }
2145
2176
  return count;
@@ -2157,7 +2188,7 @@ const countSourceFilesViaGit = (rootDirectory) => {
2157
2188
  maxBuffer: GIT_LS_FILES_MAX_BUFFER_BYTES
2158
2189
  });
2159
2190
  if (result.error || result.status !== 0) return null;
2160
- return result.stdout.split("\0").filter((filePath) => filePath.length > 0 && SOURCE_FILE_PATTERN.test(filePath)).length;
2191
+ return result.stdout.split("\0").filter((filePath) => filePath.length > 0 && isLintableSourceFile(filePath) && !isLargeMinifiedFile(path.resolve(rootDirectory, filePath))).length;
2161
2192
  };
2162
2193
  const countSourceFiles = (rootDirectory) => countSourceFilesViaGit(rootDirectory) ?? countSourceFilesViaFilesystem(rootDirectory);
2163
2194
  const cachedPackageJsons = /* @__PURE__ */ new Map();
@@ -3240,7 +3271,15 @@ const STAGED_FILES_PROJECT_CONFIG_FILENAMES = [
3240
3271
  ];
3241
3272
  const OXLINT_OUTPUT_MAX_BYTES = 50 * 1024 * 1024;
3242
3273
  const OXLINT_SPAWN_TIMEOUT_MS = 6e4;
3274
+ const DEAD_CODE_WORKER_MAX_OLD_SPACE_MB = 8192;
3243
3275
  const RECOMMENDED_PNPM_MINIMUM_RELEASE_AGE_MINUTES = 10080;
3276
+ const DIAGNOSTIC_CATEGORY_BUCKETS = [
3277
+ "Security",
3278
+ "Bugs",
3279
+ "Performance",
3280
+ "Accessibility",
3281
+ "Maintainability"
3282
+ ];
3244
3283
  const MAX_GLOB_PATTERN_LENGTH_CHARS = 1024;
3245
3284
  const CONFIG_CACHE_TTL_MS = 300 * 1e3;
3246
3285
  var InvalidGlobPatternError = class extends Error {
@@ -3862,10 +3901,13 @@ const collectStringSet = (values) => {
3862
3901
  * wins over `test-noise`)
3863
3902
  * 2. severity overrides (top-level `rules` / `categories`, with
3864
3903
  * `"off"` dropping)
3865
- * 3. ignore filters (rules / file patterns / per-file overrides)
3866
- * 4. `rn-no-raw-text` suppression via configured `textComponents` and
3904
+ * 3. warning suppression (only when `showWarnings` is false: drops every
3905
+ * `"warning"`-severity diagnostic unless a severity override opts a
3906
+ * specific rule / category back in)
3907
+ * 4. ignore filters (rules / file patterns / per-file overrides)
3908
+ * 5. `rn-no-raw-text` suppression via configured `textComponents` and
3867
3909
  * `rawTextWrapperComponents` (config-driven JSX enclosure checks)
3868
- * 5. inline suppressions (`// react-doctor-disable-next-line ...`)
3910
+ * 6. inline suppressions (`// react-doctor-disable-next-line ...`)
3869
3911
  *
3870
3912
  * Returns `null` when the diagnostic is dropped, the (possibly
3871
3913
  * severity-restamped) diagnostic otherwise.
@@ -3875,7 +3917,7 @@ const collectStringSet = (values) => {
3875
3917
  * `mergeAndFilterDiagnostics` wrapper apply this closure per element.
3876
3918
  */
3877
3919
  const buildDiagnosticPipeline = (input) => {
3878
- const { rootDirectory, userConfig, readFileLinesSync, respectInlineDisables } = input;
3920
+ const { rootDirectory, userConfig, readFileLinesSync, respectInlineDisables, showWarnings } = input;
3879
3921
  const severityControls = buildRuleSeverityControls(userConfig);
3880
3922
  const ignoredRules = new Set(Array.isArray(userConfig?.ignore?.rules) ? userConfig.ignore.rules.filter((rule) => typeof rule === "string") : []);
3881
3923
  const ignoredFilePatterns = compileIgnoredFilePatterns(userConfig);
@@ -3925,15 +3967,17 @@ const buildDiagnosticPipeline = (input) => {
3925
3967
  return { apply: (diagnostic) => {
3926
3968
  if (shouldAutoSuppress(diagnostic)) return null;
3927
3969
  let current = diagnostic;
3970
+ let explicitSeverityOverride;
3928
3971
  if (severityControls) {
3929
3972
  const { ruleKey, category } = getDiagnosticRuleIdentity(current);
3930
- const override = resolveRuleSeverityOverride({
3973
+ explicitSeverityOverride = resolveRuleSeverityOverride({
3931
3974
  ruleKey,
3932
3975
  category
3933
3976
  }, severityControls);
3934
- if (override === "off") return null;
3935
- if (override !== void 0) current = restampSeverity(current, override);
3977
+ if (explicitSeverityOverride === "off") return null;
3978
+ if (explicitSeverityOverride !== void 0) current = restampSeverity(current, explicitSeverityOverride);
3936
3979
  }
3980
+ if (!showWarnings && current.severity === "warning" && explicitSeverityOverride !== "warn") return null;
3937
3981
  if (userConfig) {
3938
3982
  if (isRuleIgnored(`${current.plugin}/${current.rule}`)) return null;
3939
3983
  if (isFileIgnoredByPatterns(current.filePath, rootDirectory, ignoredFilePatterns)) return null;
@@ -4165,10 +4209,18 @@ const VALID_RULE_SEVERITIES = [
4165
4209
  "warn",
4166
4210
  "off"
4167
4211
  ];
4212
+ const KNOWN_CATEGORY_LABEL = DIAGNOSTIC_CATEGORY_BUCKETS.join(", ");
4213
+ const isDiagnosticCategoryBucket = (value) => DIAGNOSTIC_CATEGORY_BUCKETS.includes(value);
4214
+ const filterKnownCategories = (fieldName, categories) => categories.filter((category) => {
4215
+ if (isDiagnosticCategoryBucket(category)) return true;
4216
+ warnConfigIssue(`config field "${fieldName}" lists "${category}", which is not a known category (expected one of: ${KNOWN_CATEGORY_LABEL}); ignoring the entry.`);
4217
+ return false;
4218
+ });
4168
4219
  const BOOLEAN_FIELD_NAMES = [
4169
4220
  "lint",
4170
4221
  "deadCode",
4171
4222
  "verbose",
4223
+ "warnings",
4172
4224
  "customRulesOnly",
4173
4225
  "share",
4174
4226
  "noScore",
@@ -4217,13 +4269,15 @@ const validateSurfaceControls = (surface, rawControls) => {
4217
4269
  warnConfigIssue(`config field "surfaces.${surface}" must be an object (got ${typeof rawControls}); ignoring this surface.`);
4218
4270
  return;
4219
4271
  }
4220
- const validated = {};
4272
+ const validatedSurfaceControls = {};
4221
4273
  for (const fieldName of SURFACE_CONTROL_FIELD_NAMES) {
4222
4274
  if (rawControls[fieldName] === void 0) continue;
4223
- const result = validateStringArrayField(`surfaces.${surface}.${fieldName}`, rawControls[fieldName]);
4224
- if (result !== void 0) validated[fieldName] = result;
4275
+ const qualifiedName = `surfaces.${surface}.${fieldName}`;
4276
+ const result = validateStringArrayField(qualifiedName, rawControls[fieldName]);
4277
+ if (result === void 0) continue;
4278
+ validatedSurfaceControls[fieldName] = fieldName === "includeCategories" || fieldName === "excludeCategories" ? filterKnownCategories(qualifiedName, result) : result;
4225
4279
  }
4226
- return validated;
4280
+ return validatedSurfaceControls;
4227
4281
  };
4228
4282
  const validateSurfacesField = (rawSurfaces) => {
4229
4283
  if (!isPlainObject$1(rawSurfaces)) {
@@ -4241,7 +4295,7 @@ const validateSurfacesField = (rawSurfaces) => {
4241
4295
  }
4242
4296
  return validated;
4243
4297
  };
4244
- const validateSeverityMap = (fieldName, rawMap) => {
4298
+ const validateSeverityMap = (fieldName, rawMap, keysAreCategories = false) => {
4245
4299
  if (!isPlainObject$1(rawMap)) {
4246
4300
  warnConfigIssue(`config field "${fieldName}" must be an object (got ${typeof rawMap}); ignoring this field.`);
4247
4301
  return;
@@ -4252,6 +4306,10 @@ const validateSeverityMap = (fieldName, rawMap) => {
4252
4306
  warnConfigIssue(`config field "${fieldName}" has an empty key; ignoring the entry.`);
4253
4307
  continue;
4254
4308
  }
4309
+ if (keysAreCategories && !isDiagnosticCategoryBucket(key)) {
4310
+ warnConfigIssue(`config field "${fieldName}.${key}" is not a known category (expected one of: ${KNOWN_CATEGORY_LABEL}); ignoring the entry.`);
4311
+ continue;
4312
+ }
4255
4313
  if (!isRuleSeverity(value)) {
4256
4314
  warnConfigIssue(`config field "${fieldName}.${key}" must be one of: ${VALID_RULE_SEVERITIES.join(", ")} (got ${formatType(value)}); ignoring the entry.`);
4257
4315
  continue;
@@ -4272,7 +4330,7 @@ const validateConfigTypes = (config) => {
4272
4330
  for (const fieldName of BOOLEAN_FIELD_NAMES) applyFieldValidator(config, validated, fieldName, (value) => coerceMaybeBooleanString(fieldName, value));
4273
4331
  for (const fieldName of STRING_FIELD_NAMES) applyFieldValidator(config, validated, fieldName, (value) => validateString(fieldName, value));
4274
4332
  applyFieldValidator(config, validated, "surfaces", validateSurfacesField);
4275
- for (const fieldName of SEVERITY_FIELD_NAMES) applyFieldValidator(config, validated, fieldName, (value) => validateSeverityMap(fieldName, value));
4333
+ for (const fieldName of SEVERITY_FIELD_NAMES) applyFieldValidator(config, validated, fieldName, (value) => validateSeverityMap(fieldName, value, fieldName === "categories"));
4276
4334
  applyFieldValidator(config, validated, "plugins", (value) => validateStringArrayField("plugins", value));
4277
4335
  return validated;
4278
4336
  };
@@ -4356,11 +4414,12 @@ const resolveConfigRootDir = (config, configSourceDirectory) => {
4356
4414
  }
4357
4415
  return resolvedRootDir;
4358
4416
  };
4359
- const resolveDiagnoseTarget = (directory) => {
4417
+ const resolveDiagnoseTarget = (directory, options = {}) => {
4360
4418
  if (isFile(path.join(directory, "package.json"))) return directory;
4361
4419
  const reactSubprojects = discoverReactSubprojects(directory);
4362
4420
  if (reactSubprojects.length === 0) return null;
4363
4421
  if (reactSubprojects.length === 1) return reactSubprojects[0].directory;
4422
+ if (options.allowAmbiguous === true) return null;
4364
4423
  throw new AmbiguousProjectError(directory, reactSubprojects.map((subproject) => path.relative(directory, subproject.directory)).toSorted());
4365
4424
  };
4366
4425
  /**
@@ -4374,7 +4433,8 @@ const resolveDiagnoseTarget = (directory) => {
4374
4433
  * project root, if configured.
4375
4434
  * 4. Walk into a nested React subproject when the requested
4376
4435
  * directory has no `package.json` of its own (raises
4377
- * `AmbiguousProjectError` when multiple candidates exist).
4436
+ * `AmbiguousProjectError` when multiple candidates exist unless
4437
+ * the caller opts into keeping the wrapper directory).
4378
4438
  *
4379
4439
  * Throws `ProjectNotFoundError` when neither the requested directory
4380
4440
  * nor any discoverable nested project has a `package.json`.
@@ -4386,14 +4446,14 @@ const resolveDiagnoseTarget = (directory) => {
4386
4446
  * via its own cache). Routing through `resolveScanTarget` keeps every
4387
4447
  * shell in agreement on what "the scan directory" means.
4388
4448
  */
4389
- const resolveScanTarget = (requestedDirectory) => {
4449
+ const resolveScanTarget = (requestedDirectory, options = {}) => {
4390
4450
  const absoluteRequested = path.resolve(requestedDirectory);
4391
4451
  const loadedConfig = loadConfigWithSource(absoluteRequested);
4392
4452
  const userConfig = loadedConfig?.config ?? null;
4393
4453
  const configSourceDirectory = loadedConfig?.sourceDirectory ?? null;
4394
4454
  const redirectedDirectory = resolveConfigRootDir(userConfig, configSourceDirectory);
4395
4455
  const directoryAfterRedirect = redirectedDirectory ?? absoluteRequested;
4396
- const resolvedDirectory = resolveDiagnoseTarget(directoryAfterRedirect) ?? directoryAfterRedirect;
4456
+ const resolvedDirectory = resolveDiagnoseTarget(directoryAfterRedirect, options) ?? directoryAfterRedirect;
4397
4457
  if (!isDirectory(resolvedDirectory)) throw existsSync(resolvedDirectory) ? new NotADirectoryError(resolvedDirectory) : new ProjectNotFoundError(resolvedDirectory);
4398
4458
  return {
4399
4459
  resolvedDirectory,
@@ -4572,99 +4632,6 @@ const checkReducedMotion = (rootDirectory) => {
4572
4632
  return [MISSING_REDUCED_MOTION_DIAGNOSTIC];
4573
4633
  };
4574
4634
  const computeJsxIncludePaths = (includePaths) => includePaths.length > 0 ? includePaths.filter((filePath) => JSX_FILE_PATTERN.test(filePath)) : void 0;
4575
- const toStringSet = (values) => {
4576
- if (!values || values.length === 0) return /* @__PURE__ */ new Set();
4577
- return new Set(values.filter((value) => typeof value === "string" && value.length > 0));
4578
- };
4579
- const buildResolvedControls = (surface, userControls) => {
4580
- const excludeTags = new Set(DEFAULT_SURFACE_EXCLUDED_TAGS[surface]);
4581
- const includeTags = toStringSet(userControls?.includeTags);
4582
- for (const tag of includeTags) excludeTags.delete(tag);
4583
- for (const tag of toStringSet(userControls?.excludeTags)) excludeTags.add(tag);
4584
- return {
4585
- includeTags,
4586
- excludeTags,
4587
- includeCategories: toStringSet(userControls?.includeCategories),
4588
- excludeCategories: toStringSet(userControls?.excludeCategories),
4589
- includeRuleKeys: toStringSet(userControls?.includeRules),
4590
- excludeRuleKeys: toStringSet(userControls?.excludeRules)
4591
- };
4592
- };
4593
- const intersects = (values, candidates) => values.some((value) => candidates.has(value));
4594
- const isDiagnosticOnSurface = (diagnostic, surface, config) => {
4595
- const resolved = buildResolvedControls(surface, config?.surfaces?.[surface]);
4596
- const { ruleKey, category, tags } = getDiagnosticRuleIdentity(diagnostic);
4597
- if (resolved.includeRuleKeys.has(ruleKey)) return true;
4598
- if (resolved.includeCategories.has(category)) return true;
4599
- if (intersects(tags, resolved.includeTags)) return true;
4600
- if (resolved.excludeRuleKeys.has(ruleKey)) return false;
4601
- if (resolved.excludeCategories.has(category)) return false;
4602
- if (intersects(tags, resolved.excludeTags)) return false;
4603
- return true;
4604
- };
4605
- const filterDiagnosticsForSurface = (diagnostics, surface, config) => diagnostics.filter((diagnostic) => isDiagnosticOnSurface(diagnostic, surface, config));
4606
- const listSourceFilesViaGit = (rootDirectory) => {
4607
- const result = spawnSync("git", [
4608
- "ls-files",
4609
- "-z",
4610
- "--cached",
4611
- "--others",
4612
- "--exclude-standard"
4613
- ], {
4614
- cwd: rootDirectory,
4615
- encoding: "utf-8",
4616
- maxBuffer: GIT_LS_FILES_MAX_BUFFER_BYTES
4617
- });
4618
- if (result.error || result.status !== 0) return null;
4619
- return result.stdout.split("\0").filter((filePath) => filePath.length > 0 && SOURCE_FILE_PATTERN.test(filePath));
4620
- };
4621
- const listSourceFilesViaFilesystem = (rootDirectory) => {
4622
- const filePaths = [];
4623
- const stack = [rootDirectory];
4624
- while (stack.length > 0) {
4625
- const currentDirectory = stack.pop();
4626
- const entries = readDirectoryEntries(currentDirectory);
4627
- for (const entry of entries) {
4628
- const absolutePath = path.join(currentDirectory, entry.name);
4629
- if (entry.isDirectory()) {
4630
- if (!entry.name.startsWith(".") && !IGNORED_DIRECTORIES.has(entry.name)) stack.push(absolutePath);
4631
- continue;
4632
- }
4633
- if (entry.isFile() && SOURCE_FILE_PATTERN.test(entry.name)) filePaths.push(path.relative(rootDirectory, absolutePath).replace(/\\/g, "/"));
4634
- }
4635
- }
4636
- return filePaths;
4637
- };
4638
- const listSourceFiles = (rootDirectory) => listSourceFilesViaGit(rootDirectory) ?? listSourceFilesViaFilesystem(rootDirectory);
4639
- const resolveLintIncludePaths = (rootDirectory, userConfig) => {
4640
- if (!Array.isArray(userConfig?.ignore?.files) || userConfig.ignore.files.length === 0) return;
4641
- const ignoredPatterns = compileIgnoredFilePatterns(userConfig);
4642
- return listSourceFiles(rootDirectory).filter((filePath) => {
4643
- if (!JSX_FILE_PATTERN.test(filePath)) return false;
4644
- return !isFileIgnoredByPatterns(filePath, rootDirectory, ignoredPatterns);
4645
- });
4646
- };
4647
- var Config = class Config extends Context.Service()("react-doctor/Config") {
4648
- static layerNode = Layer.effect(Config, Effect.gen(function* () {
4649
- const cache = yield* Cache.make({
4650
- capacity: 16,
4651
- timeToLive: CONFIG_CACHE_TTL_MS,
4652
- lookup: (directory) => Effect.sync(() => {
4653
- const loaded = loadConfigWithSource(directory);
4654
- const redirected = resolveConfigRootDir(loaded?.config ?? null, loaded?.sourceDirectory ?? null);
4655
- return {
4656
- config: loaded?.config ?? null,
4657
- resolvedDirectory: redirected ?? directory,
4658
- configSourceDirectory: loaded?.sourceDirectory ?? null
4659
- };
4660
- })
4661
- });
4662
- return Config.of({ resolve: Effect.fn("Config.resolve")(function* (directory) {
4663
- return yield* Cache.get(cache, directory);
4664
- }) });
4665
- }));
4666
- static layerOf = (resolved) => Layer.succeed(Config, Config.of({ resolve: () => Effect.succeed(resolved) }));
4667
- };
4668
4635
  const LINGUIST_ATTRIBUTE_PATTERN = /^linguist-(?:vendored|generated)(?:=([a-zA-Z0-9]+))?$/i;
4669
4636
  const FALSY_VALUES = new Set([
4670
4637
  "false",
@@ -4746,6 +4713,30 @@ const collectIgnorePatterns = (rootDirectory) => {
4746
4713
  cachedPatternsByRoot.set(rootDirectory, patterns);
4747
4714
  return patterns;
4748
4715
  };
4716
+ /**
4717
+ * Resolves a path to its canonical, symlink-free form, falling back to
4718
+ * the input when it cannot be realpath'd (broken symlink, permission
4719
+ * error) so a best-effort normalization never throws.
4720
+ *
4721
+ * deslop's dead-code module graph is collected with `fast-glob` (which
4722
+ * keeps the scan root's symlinks intact) while imports are resolved
4723
+ * through `oxc-resolver` (which returns realpath'd targets). When the
4724
+ * project root sits behind a symlink — e.g. macOS iCloud-synced
4725
+ * `~/Documents` / `~/Desktop`, or a symlinked checkout — those two path
4726
+ * spaces diverge: every resolved import misses the graph and the files
4727
+ * they point at (commonly every `@/…` alias target) are mis-reported as
4728
+ * unreachable. Canonicalizing the root before the scan keeps both path
4729
+ * spaces in agreement.
4730
+ */
4731
+ const toCanonicalPath = (filePath) => {
4732
+ try {
4733
+ return fs.realpathSync(filePath);
4734
+ } catch {
4735
+ return filePath;
4736
+ }
4737
+ };
4738
+ const DEAD_CODE_PLUGIN = "deslop";
4739
+ const DEAD_CODE_CATEGORY = "Maintainability";
4749
4740
  const TSCONFIG_FILENAMES$1 = ["tsconfig.json", "tsconfig.base.json"];
4750
4741
  const DEAD_CODE_WORKER_SCRIPT = `
4751
4742
  const inputChunks = [];
@@ -4921,7 +4912,11 @@ const buildDeadCodeWorkerError = (workerError) => {
4921
4912
  return error;
4922
4913
  };
4923
4914
  const createDeadCodeWorker = (input) => {
4924
- const child = spawn(process.execPath, ["-e", DEAD_CODE_WORKER_SCRIPT], {
4915
+ const child = spawn(process.execPath, [
4916
+ `--max-old-space-size=${DEAD_CODE_WORKER_MAX_OLD_SPACE_MB}`,
4917
+ "-e",
4918
+ DEAD_CODE_WORKER_SCRIPT
4919
+ ], {
4925
4920
  stdio: [
4926
4921
  "pipe",
4927
4922
  "pipe",
@@ -4996,7 +4991,8 @@ const runDeadCodeWorkerWithTimeout = (handle, timeoutMs) => new Promise((resolve
4996
4991
  });
4997
4992
  });
4998
4993
  const checkDeadCode = async (options) => {
4999
- const { rootDirectory, userConfig } = options;
4994
+ const { userConfig } = options;
4995
+ const rootDirectory = toCanonicalPath(options.rootDirectory);
5000
4996
  if (!fs.existsSync(path.join(rootDirectory, "package.json"))) return [];
5001
4997
  const ignorePatterns = collectDeadCodeIgnorePatterns(rootDirectory, userConfig);
5002
4998
  const result = parseDeadCodeWorkerResult(await runDeadCodeWorkerWithTimeout((options.createWorker ?? createDeadCodeWorker)({
@@ -5009,59 +5005,162 @@ const checkDeadCode = async (options) => {
5009
5005
  const diagnostics = [];
5010
5006
  for (const unusedFile of result.unusedFiles) diagnostics.push({
5011
5007
  filePath: toRelative(unusedFile.path),
5012
- plugin: "deslop",
5008
+ plugin: DEAD_CODE_PLUGIN,
5013
5009
  rule: "unused-file",
5014
5010
  severity: "warning",
5015
5011
  message: "Unused file — not reachable from any entry point",
5016
5012
  help: "Delete the file if it is truly unreachable, or import it from an entry point.",
5017
5013
  line: 0,
5018
5014
  column: 0,
5019
- category: "Dead Code"
5015
+ category: DEAD_CODE_CATEGORY
5020
5016
  });
5021
5017
  for (const unusedExport of result.unusedExports) {
5022
5018
  const label = unusedExport.isTypeOnly ? "type export" : "export";
5023
5019
  diagnostics.push({
5024
5020
  filePath: toRelative(unusedExport.path),
5025
- plugin: "deslop",
5021
+ plugin: DEAD_CODE_PLUGIN,
5026
5022
  rule: unusedExport.isTypeOnly ? "unused-type" : "unused-export",
5027
5023
  severity: "warning",
5028
5024
  message: `Unused ${label}: \`${unusedExport.name}\``,
5029
5025
  help: "Drop the `export` keyword (or remove the declaration) if no other module uses this symbol.",
5030
5026
  line: unusedExport.line,
5031
5027
  column: unusedExport.column,
5032
- category: "Dead Code"
5028
+ category: DEAD_CODE_CATEGORY
5033
5029
  });
5034
5030
  }
5035
5031
  for (const unusedDependency of result.unusedDependencies) {
5036
5032
  const label = unusedDependency.isDevDependency ? "devDependency" : "dependency";
5037
5033
  diagnostics.push({
5038
5034
  filePath: "package.json",
5039
- plugin: "deslop",
5035
+ plugin: DEAD_CODE_PLUGIN,
5040
5036
  rule: unusedDependency.isDevDependency ? "unused-dev-dependency" : "unused-dependency",
5041
5037
  severity: "warning",
5042
5038
  message: `Unused ${label}: \`${unusedDependency.name}\``,
5043
5039
  help: "Remove the dependency from package.json if it is genuinely unused.",
5044
5040
  line: 0,
5045
5041
  column: 0,
5046
- category: "Dead Code"
5042
+ category: DEAD_CODE_CATEGORY
5047
5043
  });
5048
5044
  }
5049
5045
  for (const cycle of result.circularDependencies) {
5050
5046
  if (cycle.files.length === 0) continue;
5051
5047
  diagnostics.push({
5052
5048
  filePath: toRelative(cycle.files[0]),
5053
- plugin: "deslop",
5049
+ plugin: DEAD_CODE_PLUGIN,
5054
5050
  rule: "circular-dependency",
5055
5051
  severity: "warning",
5056
5052
  message: `Circular import cycle: ${cycle.files.map(toRelative).join(" → ")}`,
5057
5053
  help: "Break the cycle by extracting the shared code into a third module that both files import.",
5058
5054
  line: 0,
5059
5055
  column: 0,
5060
- category: "Dead Code"
5056
+ category: DEAD_CODE_CATEGORY
5061
5057
  });
5062
5058
  }
5063
5059
  return diagnostics;
5064
5060
  };
5061
+ const DEAD_CODE_RULE_KEY_PREFIX = `${DEAD_CODE_PLUGIN}/`;
5062
+ const isSurfacingOverride = (override) => override === "warn" || override === "error";
5063
+ const deadCodeMaySurfaceWhenWarningsHidden = (userConfig) => {
5064
+ const severityControls = buildRuleSeverityControls(userConfig);
5065
+ if (!severityControls) return false;
5066
+ if (isSurfacingOverride(severityControls.categories?.["Maintainability"])) return true;
5067
+ for (const [ruleKey, override] of Object.entries(severityControls.rules ?? {})) if (ruleKey.startsWith(DEAD_CODE_RULE_KEY_PREFIX) && isSurfacingOverride(override)) return true;
5068
+ return false;
5069
+ };
5070
+ const toStringSet = (values) => {
5071
+ if (!values || values.length === 0) return /* @__PURE__ */ new Set();
5072
+ return new Set(values.filter((value) => typeof value === "string" && value.length > 0));
5073
+ };
5074
+ const buildResolvedControls = (surface, userControls) => {
5075
+ const excludeTags = new Set(DEFAULT_SURFACE_EXCLUDED_TAGS[surface]);
5076
+ const includeTags = toStringSet(userControls?.includeTags);
5077
+ for (const tag of includeTags) excludeTags.delete(tag);
5078
+ for (const tag of toStringSet(userControls?.excludeTags)) excludeTags.add(tag);
5079
+ return {
5080
+ includeTags,
5081
+ excludeTags,
5082
+ includeCategories: toStringSet(userControls?.includeCategories),
5083
+ excludeCategories: toStringSet(userControls?.excludeCategories),
5084
+ includeRuleKeys: toStringSet(userControls?.includeRules),
5085
+ excludeRuleKeys: toStringSet(userControls?.excludeRules)
5086
+ };
5087
+ };
5088
+ const intersects = (values, candidates) => values.some((value) => candidates.has(value));
5089
+ const isDiagnosticOnSurface = (diagnostic, surface, config) => {
5090
+ const resolved = buildResolvedControls(surface, config?.surfaces?.[surface]);
5091
+ const { ruleKey, category, tags } = getDiagnosticRuleIdentity(diagnostic);
5092
+ if (resolved.includeRuleKeys.has(ruleKey)) return true;
5093
+ if (resolved.includeCategories.has(category)) return true;
5094
+ if (intersects(tags, resolved.includeTags)) return true;
5095
+ if (resolved.excludeRuleKeys.has(ruleKey)) return false;
5096
+ if (resolved.excludeCategories.has(category)) return false;
5097
+ if (intersects(tags, resolved.excludeTags)) return false;
5098
+ return true;
5099
+ };
5100
+ const filterDiagnosticsForSurface = (diagnostics, surface, config) => diagnostics.filter((diagnostic) => isDiagnosticOnSurface(diagnostic, surface, config));
5101
+ const excludeMinifiedFiles = (rootDirectory, relativePaths) => relativePaths.filter((relativePath) => !isLargeMinifiedFile(path.resolve(rootDirectory, relativePath)));
5102
+ const listSourceFilesViaGit = (rootDirectory) => {
5103
+ const result = spawnSync("git", [
5104
+ "ls-files",
5105
+ "-z",
5106
+ "--cached",
5107
+ "--others",
5108
+ "--exclude-standard"
5109
+ ], {
5110
+ cwd: rootDirectory,
5111
+ encoding: "utf-8",
5112
+ maxBuffer: GIT_LS_FILES_MAX_BUFFER_BYTES
5113
+ });
5114
+ if (result.error || result.status !== 0) return null;
5115
+ return result.stdout.split("\0").filter((filePath) => filePath.length > 0 && isLintableSourceFile(filePath));
5116
+ };
5117
+ const listSourceFilesViaFilesystem = (rootDirectory) => {
5118
+ const filePaths = [];
5119
+ const stack = [rootDirectory];
5120
+ while (stack.length > 0) {
5121
+ const currentDirectory = stack.pop();
5122
+ const entries = readDirectoryEntries(currentDirectory);
5123
+ for (const entry of entries) {
5124
+ const absolutePath = path.join(currentDirectory, entry.name);
5125
+ if (entry.isDirectory()) {
5126
+ if (!entry.name.startsWith(".") && !IGNORED_DIRECTORIES.has(entry.name)) stack.push(absolutePath);
5127
+ continue;
5128
+ }
5129
+ if (entry.isFile() && isLintableSourceFile(entry.name)) filePaths.push(path.relative(rootDirectory, absolutePath).replace(/\\/g, "/"));
5130
+ }
5131
+ }
5132
+ return filePaths;
5133
+ };
5134
+ const listSourceFiles = (rootDirectory) => excludeMinifiedFiles(rootDirectory, listSourceFilesViaGit(rootDirectory) ?? listSourceFilesViaFilesystem(rootDirectory));
5135
+ const resolveLintIncludePaths = (rootDirectory, userConfig) => {
5136
+ if (!Array.isArray(userConfig?.ignore?.files) || userConfig.ignore.files.length === 0) return;
5137
+ const ignoredPatterns = compileIgnoredFilePatterns(userConfig);
5138
+ return listSourceFiles(rootDirectory).filter((filePath) => {
5139
+ if (!JSX_FILE_PATTERN.test(filePath)) return false;
5140
+ return !isFileIgnoredByPatterns(filePath, rootDirectory, ignoredPatterns);
5141
+ });
5142
+ };
5143
+ var Config = class Config extends Context.Service()("react-doctor/Config") {
5144
+ static layerNode = Layer.effect(Config, Effect.gen(function* () {
5145
+ const cache = yield* Cache.make({
5146
+ capacity: 16,
5147
+ timeToLive: CONFIG_CACHE_TTL_MS,
5148
+ lookup: (directory) => Effect.sync(() => {
5149
+ const loaded = loadConfigWithSource(directory);
5150
+ const redirected = resolveConfigRootDir(loaded?.config ?? null, loaded?.sourceDirectory ?? null);
5151
+ return {
5152
+ config: loaded?.config ?? null,
5153
+ resolvedDirectory: redirected ?? directory,
5154
+ configSourceDirectory: loaded?.sourceDirectory ?? null
5155
+ };
5156
+ })
5157
+ });
5158
+ return Config.of({ resolve: Effect.fn("Config.resolve")(function* (directory) {
5159
+ return yield* Cache.get(cache, directory);
5160
+ }) });
5161
+ }));
5162
+ static layerOf = (resolved) => Layer.succeed(Config, Config.of({ resolve: () => Effect.succeed(resolved) }));
5163
+ };
5065
5164
  /**
5066
5165
  * `DeadCode` runs whole-project reachability analysis and streams
5067
5166
  * diagnostics. Reachability is a whole-project property — the
@@ -5567,12 +5666,12 @@ const findFilesWithDisableDirectivesViaGit = async (rootDirectory, includePaths)
5567
5666
  return null;
5568
5667
  }
5569
5668
  if (grepResult === null) return null;
5570
- return grepResult.stdout.split("\n").filter((filePath) => filePath.length > 0 && SOURCE_FILE_PATTERN.test(filePath));
5669
+ return grepResult.stdout.split("\n").filter((filePath) => filePath.length > 0 && isLintableSourceFile(filePath));
5571
5670
  };
5572
5671
  const findFilesWithDisableDirectivesViaFilesystem = (rootDirectory, includePaths) => {
5573
5672
  const matches = [];
5574
5673
  const checkFile = (relativePath) => {
5575
- if (!SOURCE_FILE_PATTERN.test(relativePath)) return;
5674
+ if (!isLintableSourceFile(relativePath)) return;
5576
5675
  const absolutePath = path.join(rootDirectory, relativePath);
5577
5676
  let content;
5578
5677
  try {
@@ -5939,6 +6038,149 @@ const appendReanimatedSharedValueHint = (help, rule, project) => {
5939
6038
  if (!help) return REANIMATED_SHARED_VALUE_HINT;
5940
6039
  return `${help}\n\n${REANIMATED_SHARED_VALUE_HINT}`;
5941
6040
  };
6041
+ const REDACTED_PLACEHOLDER = "<redacted>";
6042
+ const KEEP_PREFIX = `$1${REDACTED_PLACEHOLDER}`;
6043
+ const KNOWN_SECRET_RULES = [
6044
+ {
6045
+ pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
6046
+ replacement: REDACTED_PLACEHOLDER
6047
+ },
6048
+ {
6049
+ pattern: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,
6050
+ replacement: REDACTED_PLACEHOLDER
6051
+ },
6052
+ {
6053
+ pattern: /(?<=:\/\/)[^\s/:@]+:[^\s/@]+(?=@)/g,
6054
+ replacement: REDACTED_PLACEHOLDER
6055
+ },
6056
+ {
6057
+ pattern: /\b(AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA|A3T[A-Z0-9])[0-9A-Z]{16,}/g,
6058
+ replacement: KEEP_PREFIX
6059
+ },
6060
+ {
6061
+ pattern: /\b(gh[pousr]_)[A-Za-z0-9]{36,}/g,
6062
+ replacement: KEEP_PREFIX
6063
+ },
6064
+ {
6065
+ pattern: /\b(github_pat_)[A-Za-z0-9_]{22,}/g,
6066
+ replacement: KEEP_PREFIX
6067
+ },
6068
+ {
6069
+ pattern: /\b(glpat-)[A-Za-z0-9_-]{20,}/g,
6070
+ replacement: KEEP_PREFIX
6071
+ },
6072
+ {
6073
+ pattern: /\b(xox[baprs]-)[A-Za-z0-9-]{10,}/g,
6074
+ replacement: KEEP_PREFIX
6075
+ },
6076
+ {
6077
+ pattern: /(?<=hooks\.slack\.com\/services\/)[A-Za-z0-9/+_-]{20,}/g,
6078
+ replacement: REDACTED_PLACEHOLDER
6079
+ },
6080
+ {
6081
+ pattern: /\b((?:sk|rk)_(?:live|test)_)[0-9A-Za-z]{10,}/g,
6082
+ replacement: KEEP_PREFIX
6083
+ },
6084
+ {
6085
+ pattern: /\b(sk-(?:proj-|ant-)?)[A-Za-z0-9_-]{20,}/g,
6086
+ replacement: KEEP_PREFIX
6087
+ },
6088
+ {
6089
+ pattern: /\b(AIza)[0-9A-Za-z_-]{35,}/g,
6090
+ replacement: KEEP_PREFIX
6091
+ },
6092
+ {
6093
+ pattern: /\b(ya29\.)[0-9A-Za-z_-]{20,}/g,
6094
+ replacement: KEEP_PREFIX
6095
+ },
6096
+ {
6097
+ pattern: /\b(npm_)[A-Za-z0-9]{36,}/g,
6098
+ replacement: KEEP_PREFIX
6099
+ },
6100
+ {
6101
+ pattern: /\b(SG\.)[A-Za-z0-9_-]{22,}\.[A-Za-z0-9_-]{43,}/g,
6102
+ replacement: KEEP_PREFIX
6103
+ },
6104
+ {
6105
+ pattern: /\b(SK)[0-9a-fA-F]{32,}/g,
6106
+ replacement: KEEP_PREFIX
6107
+ },
6108
+ {
6109
+ pattern: /\b(dop_v1_)[a-f0-9]{64,}/g,
6110
+ replacement: KEEP_PREFIX
6111
+ },
6112
+ {
6113
+ pattern: /\b(shp(?:at|ca|pa|ss)_)[a-fA-F0-9]{32,}/g,
6114
+ replacement: KEEP_PREFIX
6115
+ },
6116
+ {
6117
+ pattern: /\b(sq0[a-z]{3}-)[0-9A-Za-z_-]{22,}/g,
6118
+ replacement: KEEP_PREFIX
6119
+ },
6120
+ {
6121
+ pattern: /\b([0-9]{8,10}:AA)[0-9A-Za-z_-]{32,}/g,
6122
+ replacement: KEEP_PREFIX
6123
+ },
6124
+ {
6125
+ pattern: /(?<=\bBearer\s)[A-Za-z0-9._~+/=-]{16,}/g,
6126
+ replacement: REDACTED_PLACEHOLDER
6127
+ },
6128
+ {
6129
+ pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
6130
+ replacement: REDACTED_PLACEHOLDER
6131
+ }
6132
+ ];
6133
+ const CANDIDATE_TOKEN_PATTERN = /[A-Za-z0-9_][A-Za-z0-9_-]*/g;
6134
+ const HEX_DIGEST_PATTERN = /^(?:[0-9a-f]{32}|[0-9a-f]{40}|[0-9a-f]{64})$/;
6135
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6136
+ const HAS_LETTER_PATTERN = /[A-Za-z]/;
6137
+ const HAS_DIGIT_PATTERN = /[0-9]/;
6138
+ const shannonEntropyBits = (value) => {
6139
+ const counts = /* @__PURE__ */ new Map();
6140
+ for (const char of value) counts.set(char, (counts.get(char) ?? 0) + 1);
6141
+ let bits = 0;
6142
+ for (const count of counts.values()) {
6143
+ const probability = count / value.length;
6144
+ bits -= probability * Math.log2(probability);
6145
+ }
6146
+ return bits;
6147
+ };
6148
+ const looksLikeHighEntropySecret = (token) => {
6149
+ if (token.length < 32) return false;
6150
+ if (!HAS_LETTER_PATTERN.test(token) || !HAS_DIGIT_PATTERN.test(token)) return false;
6151
+ if (HEX_DIGEST_PATTERN.test(token) || UUID_PATTERN.test(token)) return false;
6152
+ return shannonEntropyBits(token) >= 3;
6153
+ };
6154
+ const redactHighEntropyTokens = (text) => text.replace(CANDIDATE_TOKEN_PATTERN, (token) => looksLikeHighEntropySecret(token) ? REDACTED_PLACEHOLDER : token);
6155
+ /**
6156
+ * Masks API keys, tokens, private keys, credentialed URLs, and emails
6157
+ * found anywhere inside a free-text string, returning the scrubbed text.
6158
+ * Applied to every diagnostic's `message` / `help` at construction time
6159
+ * so secrets never reach the terminal, the JSON report, or the score
6160
+ * API — react-doctor must never echo or transmit a user's secrets.
6161
+ *
6162
+ * Provider tokens keep their non-secret, type-identifying prefix (e.g.
6163
+ * `sk_live_<redacted>`, `ghp_<redacted>`, `AKIA<redacted>`) so the leaked
6164
+ * credential's type stays visible; structural or unknown-format secrets
6165
+ * with no meaningful prefix are masked whole.
6166
+ *
6167
+ * Runs the high-precision known-shape detectors first, then a generic
6168
+ * entropy-gated sweep for unknown-format secrets. Idempotent: the inert
6169
+ * `<redacted>` placeholder matches none of the detectors and is too
6170
+ * short for the generic sweep, so re-running leaves the text unchanged.
6171
+ *
6172
+ * Accepts `unknown` on purpose: callers feed it diagnostic `message` /
6173
+ * `help` that originate from oxlint JSON, which is only shape-checked at
6174
+ * the top level (the per-field `string` types are assumed, not validated).
6175
+ * A malformed non-string value returns `""` instead of throwing on
6176
+ * `.replace`, so one bad diagnostic can't abort parsing the whole batch.
6177
+ */
6178
+ const redactSensitiveText = (text) => {
6179
+ if (typeof text !== "string" || text === "") return "";
6180
+ let redacted = text;
6181
+ for (const rule of KNOWN_SECRET_RULES) redacted = redacted.replace(rule.pattern, rule.replacement);
6182
+ return redactHighEntropyTokens(redacted);
6183
+ };
5942
6184
  const REACT_MODULE_SOURCE = "react";
5943
6185
  const REQUIRE_IDENTIFIER = "require";
5944
6186
  const USE_IDENTIFIER = "use";
@@ -6233,25 +6475,26 @@ const shouldSuppressLocalUseHookDiagnostic = (diagnostic, rootDirectory) => {
6233
6475
  return bindingResolution !== null && !bindingResolution.isReactUseBinding;
6234
6476
  };
6235
6477
  const FILEPATH_WITH_LOCATION_PATTERN = /\S+\.\w+:\d+:\d+[\s\S]*$/;
6236
- const REACT_COMPILER_MESSAGE = "React Compiler can't optimize this code";
6478
+ const REACT_COMPILER_TITLE = "React Compiler can't optimize this";
6479
+ const REACT_COMPILER_MESSAGE = "This component misses React Compiler's automatic memoization & re-renders more than it should. Rewrite the flagged code so the compiler can optimize it.";
6237
6480
  const PLUGIN_CATEGORY_MAP = {
6238
- react: "Correctness",
6239
- "react-hooks": "Correctness",
6240
- "react-hooks-js": "React Compiler",
6241
- "react-doctor": "Other",
6481
+ react: "Bugs",
6482
+ "react-hooks": "Bugs",
6483
+ "react-hooks-js": "Performance",
6484
+ "react-doctor": "Bugs",
6242
6485
  "jsx-a11y": "Accessibility",
6243
- effect: "State & Effects",
6244
- eslint: "Correctness",
6245
- oxc: "Correctness",
6246
- typescript: "Correctness",
6247
- unicorn: "Correctness",
6248
- import: "Bundle Size",
6249
- promise: "Correctness",
6250
- n: "Correctness",
6251
- node: "Correctness",
6252
- vitest: "Correctness",
6253
- jest: "Correctness",
6254
- nextjs: "Next.js"
6486
+ effect: "Bugs",
6487
+ eslint: "Bugs",
6488
+ oxc: "Bugs",
6489
+ typescript: "Bugs",
6490
+ unicorn: "Bugs",
6491
+ import: "Performance",
6492
+ promise: "Bugs",
6493
+ n: "Bugs",
6494
+ node: "Bugs",
6495
+ vitest: "Bugs",
6496
+ jest: "Bugs",
6497
+ nextjs: "Bugs"
6255
6498
  };
6256
6499
  const lookupOwnString = (record, key) => Object.hasOwn(record, key) ? record[key] : void 0;
6257
6500
  const getRuleRecommendation = (ruleName, project) => {
@@ -6259,7 +6502,16 @@ const getRuleRecommendation = (ruleName, project) => {
6259
6502
  return reactDoctorPlugin.rules[ruleName]?.recommendation;
6260
6503
  };
6261
6504
  const getRuleCategory = (ruleName) => reactDoctorPlugin.rules[ruleName]?.category;
6505
+ const getRuleTitle = (ruleName) => reactDoctorPlugin.rules[ruleName]?.title;
6506
+ const resolveDiagnosticTitle = (plugin, rule) => plugin === "react-hooks-js" ? REACT_COMPILER_TITLE : getRuleTitle(rule);
6262
6507
  const cleanDiagnosticMessage = (message, help, plugin, rule, project) => {
6508
+ const cleaned = resolveCleanedDiagnostic(typeof message === "string" ? message : "", typeof help === "string" ? help : "", plugin, rule, project);
6509
+ return {
6510
+ message: redactSensitiveText(cleaned.message),
6511
+ help: redactSensitiveText(cleaned.help)
6512
+ };
6513
+ };
6514
+ const resolveCleanedDiagnostic = (message, help, plugin, rule, project) => {
6263
6515
  if (plugin === "react-hooks-js") return {
6264
6516
  message: REACT_COMPILER_MESSAGE,
6265
6517
  help: appendReanimatedSharedValueHint(message.replace(FILEPATH_WITH_LOCATION_PATTERN, "").trim() || help, rule, project)
@@ -6280,7 +6532,7 @@ const parseRuleCode = (code) => {
6280
6532
  rule: match[2]
6281
6533
  };
6282
6534
  };
6283
- const resolveDiagnosticCategory = (plugin, rule) => getRuleCategory(rule) ?? lookupOwnString(PLUGIN_CATEGORY_MAP, plugin) ?? "Other";
6535
+ const resolveDiagnosticCategory = (plugin, rule) => getRuleCategory(rule) ?? lookupOwnString(PLUGIN_CATEGORY_MAP, plugin) ?? "Bugs";
6284
6536
  const isOxlintOutput = (value) => {
6285
6537
  if (typeof value !== "object" || value === null) return false;
6286
6538
  const candidate = value;
@@ -6304,7 +6556,16 @@ const parseOxlintOutput = (stdout, project, rootDirectory) => {
6304
6556
  throw new ReactDoctorError({ reason: new OxlintOutputUnparseable({ preview: stdout.slice(0, 200) }) });
6305
6557
  }
6306
6558
  if (!isOxlintOutput(parsed)) throw new ReactDoctorError({ reason: new OxlintOutputUnparseable({ preview: stdout.slice(0, 200) }) });
6307
- return parsed.diagnostics.filter((diagnostic) => diagnostic.code && SOURCE_FILE_PATTERN.test(diagnostic.filename) && !shouldSuppressLocalUseHookDiagnostic(diagnostic, rootDirectory)).map((diagnostic) => {
6559
+ const minifiedFileCache = /* @__PURE__ */ new Map();
6560
+ const isMinifiedDiagnosticFile = (filename) => {
6561
+ const absolutePath = path.isAbsolute(filename) ? filename : path.resolve(rootDirectory || ".", filename);
6562
+ const cached = minifiedFileCache.get(absolutePath);
6563
+ if (cached !== void 0) return cached;
6564
+ const minified = isMinifiedSource(absolutePath);
6565
+ minifiedFileCache.set(absolutePath, minified);
6566
+ return minified;
6567
+ };
6568
+ return parsed.diagnostics.filter((diagnostic) => diagnostic.code && isLintableSourceFile(diagnostic.filename) && !isMinifiedDiagnosticFile(diagnostic.filename) && !shouldSuppressLocalUseHookDiagnostic(diagnostic, rootDirectory)).map((diagnostic) => {
6308
6569
  const { plugin, rule } = parseRuleCode(diagnostic.code);
6309
6570
  const primaryLabel = diagnostic.labels[0];
6310
6571
  const cleaned = cleanDiagnosticMessage(diagnostic.message, diagnostic.help, plugin, rule, project);
@@ -6313,6 +6574,7 @@ const parseOxlintOutput = (stdout, project, rootDirectory) => {
6313
6574
  plugin,
6314
6575
  rule,
6315
6576
  severity: diagnostic.severity,
6577
+ title: resolveDiagnosticTitle(plugin, rule),
6316
6578
  message: cleaned.message,
6317
6579
  help: cleaned.help,
6318
6580
  url: diagnostic.url,
@@ -6464,11 +6726,14 @@ const spawnLintBatches = async (input) => {
6464
6726
  onFileProgress(scannedFileCount + batchFileIndex, totalFileCount);
6465
6727
  }
6466
6728
  }, 50) : null;
6467
- const batchDiagnostics = await spawnLintBatch(batch);
6468
- if (progressInterval !== null) clearInterval(progressInterval);
6469
- allDiagnostics.push(...batchDiagnostics);
6470
- scannedFileCount += batch.length;
6471
- onFileProgress?.(scannedFileCount, totalFileCount);
6729
+ try {
6730
+ const batchDiagnostics = await spawnLintBatch(batch);
6731
+ allDiagnostics.push(...batchDiagnostics);
6732
+ scannedFileCount += batch.length;
6733
+ onFileProgress?.(scannedFileCount, totalFileCount);
6734
+ } finally {
6735
+ if (progressInterval !== null) clearInterval(progressInterval);
6736
+ }
6472
6737
  }
6473
6738
  if (droppedFiles.length > 0 && onPartialFailure) {
6474
6739
  const previewFiles = droppedFiles.slice(0, 3).join(", ");
@@ -6727,7 +6992,8 @@ var Progress = class Progress extends Context.Service()("react-doctor/Progress")
6727
6992
  static layerNoop = Layer.succeed(Progress, Progress.of({ start: () => Effect.succeed({
6728
6993
  update: () => Effect.void,
6729
6994
  succeed: () => Effect.void,
6730
- fail: () => Effect.void
6995
+ fail: () => Effect.void,
6996
+ stop: () => Effect.void
6731
6997
  }) }));
6732
6998
  static layerCapture = Layer.effect(Progress, Effect.map(ProgressCapture, (events) => Progress.of({ start: (text) => Effect.gen(function* () {
6733
6999
  yield* Ref.update(events, (existing) => [...existing, {
@@ -6746,6 +7012,10 @@ var Progress = class Progress extends Context.Service()("react-doctor/Progress")
6746
7012
  fail: (displayText) => Ref.update(events, (existing) => [...existing, {
6747
7013
  _tag: "Failed",
6748
7014
  text: displayText
7015
+ }]),
7016
+ stop: () => Ref.update(events, (existing) => [...existing, {
7017
+ _tag: "Stopped",
7018
+ text
6749
7019
  }])
6750
7020
  };
6751
7021
  }) }))).pipe(Layer.provideMerge(ProgressCapture.layer));
@@ -6817,17 +7087,21 @@ var Reporter = class Reporter extends Context.Service()("react-doctor/Reporter")
6817
7087
  });
6818
7088
  }));
6819
7089
  };
6820
- const parseScoreResult = (value) => {
6821
- if (typeof value !== "object" || value === null) return null;
6822
- if (!("score" in value) || !("label" in value)) return null;
6823
- const scoreValue = Reflect.get(value, "score");
6824
- const labelValue = Reflect.get(value, "label");
6825
- if (typeof scoreValue !== "number" || typeof labelValue !== "string") return null;
6826
- return {
6827
- score: scoreValue,
6828
- label: labelValue
6829
- };
6830
- };
7090
+ const RulePrioritySchema = Schema.Struct({
7091
+ priority: Schema.NullOr(Schema.Number),
7092
+ tier: Schema.Literals([
7093
+ "P0",
7094
+ "P1",
7095
+ "P2",
7096
+ "P3"
7097
+ ])
7098
+ });
7099
+ const ScoreApiResponseSchema = Schema.Struct({
7100
+ score: Schema.Number,
7101
+ label: Schema.String,
7102
+ rules: Schema.optional(Schema.Record(Schema.String, RulePrioritySchema))
7103
+ });
7104
+ const parseScoreResult = (value) => Option.getOrNull(Schema.decodeUnknownOption(ScoreApiResponseSchema)(value));
6831
7105
  const stripFilePaths = (diagnostics) => diagnostics.map(({ filePath: _filePath, ...rest }) => rest);
6832
7106
  const isAbortError = (error) => error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
6833
7107
  const describeFailure = (error) => {
@@ -6991,15 +7265,18 @@ const runInspect = (input, hooks = {}) => Effect.gen(function* () {
6991
7265
  repo
6992
7266
  }).pipe(Effect.orElseSucceed(() => null)) : Effect.succeed(null));
6993
7267
  const lintIncludePaths = computeJsxIncludePaths([...input.includePaths]) ?? resolveLintIncludePaths(scanDirectory, resolvedConfig.config);
7268
+ const scannedFilePaths = input.suppressScanSummary ? (lintIncludePaths ?? (yield* filesService.listSourceFiles(scanDirectory))).map((relativePath) => path.resolve(scanDirectory, relativePath)) : [];
6994
7269
  const beforeLint = hooks.beforeLint ?? NO_HOOKS.beforeLint;
6995
7270
  const afterLint = hooks.afterLint ?? NO_HOOKS.afterLint;
6996
7271
  yield* beforeLint(project, lintIncludePaths ?? void 0);
6997
7272
  const isDiffMode = input.includePaths.length > 0;
7273
+ const showWarnings = input.warnings ?? resolvedConfig.config?.warnings ?? false;
6998
7274
  const transform = buildDiagnosticPipeline({
6999
7275
  rootDirectory: scanDirectory,
7000
7276
  userConfig: resolvedConfig.config,
7001
7277
  readFileLinesSync: fileReader(filesService, scanDirectory),
7002
- respectInlineDisables: input.respectInlineDisables
7278
+ respectInlineDisables: input.respectInlineDisables,
7279
+ showWarnings
7003
7280
  });
7004
7281
  const applyPerElementPipeline = (rawStream) => rawStream.pipe(Stream.filterMap(filterMapNullable(transform.apply)), Stream.tap((diagnostic) => reporterService.emit(diagnostic)));
7005
7282
  const environmentDiagnostics = isDiffMode ? [] : [...checkReducedMotion(scanDirectory), ...checkPnpmHardening(scanDirectory)];
@@ -7045,7 +7322,7 @@ const runInspect = (input, hooks = {}) => Effect.gen(function* () {
7045
7322
  const lintFailureState = yield* Ref.get(lintFailure);
7046
7323
  yield* afterLint(lintFailureState.didFail);
7047
7324
  if (lintFailureState.didFail) yield* scanProgress.fail(formatLintFailText(lintFailureState.reasonTag, process.version));
7048
- const shouldRunDeadCode = input.runDeadCode && !isDiffMode;
7325
+ const shouldRunDeadCode = input.runDeadCode && !isDiffMode && (showWarnings || deadCodeMaySurfaceWhenWarningsHidden(resolvedConfig.config));
7049
7326
  const deadCodeCollected = lintFailureState.didFail || !shouldRunDeadCode ? [] : yield* scanProgress.update("Analyzing dead code...").pipe(Effect.andThen(Stream.runCollect(applyPerElementPipeline(deadCodeService.run({
7050
7327
  rootDirectory: scanDirectory,
7051
7328
  userConfig: resolvedConfig.config
@@ -7057,9 +7334,11 @@ const runInspect = (input, hooks = {}) => Effect.gen(function* () {
7057
7334
  return Stream.empty;
7058
7335
  }))))))));
7059
7336
  const deadCodeFailureState = yield* Ref.get(deadCodeFailure);
7060
- const scanElapsedSeconds = ((Date.now() - scanStartTime) / 1e3).toFixed(1);
7337
+ const scanElapsedMilliseconds = Date.now() - scanStartTime;
7338
+ const scanElapsedSeconds = (scanElapsedMilliseconds / 1e3).toFixed(1);
7061
7339
  const totalFileCount = lastReportedTotalFileCount || (lintIncludePaths?.length ?? project.sourceFileCount);
7062
7340
  if (!lintFailureState.didFail) if (deadCodeFailureState.didFail) yield* scanProgress.fail(DEAD_CODE_FAIL_TEXT);
7341
+ else if (input.suppressScanSummary) yield* scanProgress.stop();
7063
7342
  else yield* scanProgress.succeed(`Scanned ${totalFileCount} ${totalFileCount === 1 ? "file" : "files"} in ${scanElapsedSeconds}s`);
7064
7343
  yield* reporterService.finalize;
7065
7344
  const finalDiagnostics = [
@@ -7100,7 +7379,10 @@ const runInspect = (input, hooks = {}) => Effect.gen(function* () {
7100
7379
  lintFailureReasonKind: lintFailureState.reasonKind,
7101
7380
  lintPartialFailures,
7102
7381
  didDeadCodeFail: deadCodeFailureState.didFail,
7103
- deadCodeFailureReason: deadCodeFailureState.reason
7382
+ deadCodeFailureReason: deadCodeFailureState.reason,
7383
+ scannedFileCount: totalFileCount,
7384
+ scannedFilePaths,
7385
+ scanElapsedMilliseconds
7104
7386
  };
7105
7387
  }).pipe(Effect.withSpan("runInspect", { attributes: {
7106
7388
  "inspect.directory": input.directory,
@@ -7226,7 +7508,7 @@ const isPathInsideDirectory = (childAbsolutePath, parentAbsolutePath) => {
7226
7508
  static layerNode = Layer.effect(StagedFiles, Effect.gen(function* () {
7227
7509
  const git = yield* Git;
7228
7510
  return StagedFiles.of({
7229
- discoverSourceFiles: (directory) => git.stagedFilePaths(directory).pipe(Effect.map((entries) => entries.filter((entry) => SOURCE_FILE_PATTERN.test(entry)))),
7511
+ discoverSourceFiles: (directory) => git.stagedFilePaths(directory).pipe(Effect.map((entries) => entries.filter(isLintableSourceFile))),
7230
7512
  materialize: ({ directory, stagedFiles, tempDirectory }) => Effect.gen(function* () {
7231
7513
  const materializedFiles = [];
7232
7514
  const resolvedTempDirectory = path.resolve(tempDirectory);
@@ -7435,7 +7717,7 @@ const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.
7435
7717
  GitBaseBranchInvalid: (reason) => Effect.die(new Error(reason.detail)),
7436
7718
  GitBaseBranchMissing: (reason) => Effect.die(new Error(reason.message))
7437
7719
  })));
7438
- const filterSourceFiles = (filePaths) => filePaths.filter((filePath) => SOURCE_FILE_PATTERN.test(filePath));
7720
+ const filterSourceFiles = (filePaths) => filePaths.filter(isLintableSourceFile);
7439
7721
  var import_picocolors = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
7440
7722
  let p = process || {}, argv = p.argv || [], env = p.env || {};
7441
7723
  let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
@@ -7522,6 +7804,7 @@ const buildInspectProgram = (scanTarget, options, configOverride) => {
7522
7804
  includePaths,
7523
7805
  customRulesOnly: effectiveConfig?.customRulesOnly ?? false,
7524
7806
  respectInlineDisables: options.respectInlineDisables ?? effectiveConfig?.respectInlineDisables ?? true,
7807
+ warnings: options.warnings ?? effectiveConfig?.warnings ?? false,
7525
7808
  adoptExistingLintConfig: effectiveConfig?.adoptExistingLintConfig ?? true,
7526
7809
  ignoredTags: new Set(effectiveConfig?.ignore?.tags ?? []),
7527
7810
  runDeadCode: options.deadCode ?? effectiveConfig?.deadCode ?? true,