react-doctor 0.4.1-dev.e181ac1 → 0.4.2-dev.1044e29

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/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1486eaee-ed07-5eef-a9d7-51293140e237")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d1b95aab-fa59-5a23-83a0-37e1ff08b002")}catch(e){}}();
3
3
  import { createRequire } from "node:module";
4
4
  import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
5
5
  import * as path$1 from "node:path";
@@ -5151,8 +5151,8 @@ const isFile = (filePath) => {
5151
5151
  return false;
5152
5152
  }
5153
5153
  };
5154
- const SOURCE_FILE_PATTERN = /\.(tsx?|jsx?)$/;
5155
- const GENERATED_BUNDLE_FILE_PATTERN = /\.(iife|umd|global|min)\.js$/i;
5154
+ const SOURCE_FILE_PATTERN = /\.(tsx?|jsx?|mts|mjs)$/;
5155
+ const GENERATED_BUNDLE_FILE_PATTERN = /\.(iife|umd|global|min)\.m?js$/i;
5156
5156
  const MINIFIED_SNIFF_BYTES = 65536;
5157
5157
  const GIT_LS_FILES_MAX_BUFFER_BYTES = 50 * 1024 * 1024;
5158
5158
  const IGNORED_DIRECTORIES = new Set([
@@ -6361,6 +6361,7 @@ const SCORE_API_URL = "https://www.react.doctor/api/score";
6361
6361
  const ENTERPRISE_CONTACT_URL = "https://react.doctor/enterprise";
6362
6362
  const SHARE_BASE_URL = "https://react.doctor/share";
6363
6363
  const CI_URL = "https://react.doctor/ci";
6364
+ const GITHUB_ACTIONS_SETUP_URL = "https://www.react.doctor/docs/ci-and-prs/github-actions-setup";
6364
6365
  const DOCS_URL = "https://react.doctor/docs";
6365
6366
  const DOCS_RULES_BASE_URL = `${DOCS_URL}/rules`;
6366
6367
  const FETCH_TIMEOUT_MS = 1e4;
@@ -6724,7 +6725,6 @@ const LEGACY_RULE_KEY_TO_NATIVE_RULE_KEY = {
6724
6725
  "react/jsx-no-new-function-as-prop": "react-doctor/jsx-no-new-function-as-prop",
6725
6726
  "react/jsx-no-new-object-as-prop": "react-doctor/jsx-no-new-object-as-prop",
6726
6727
  "react/jsx-no-script-url": "react-doctor/jsx-no-script-url",
6727
- "react/jsx-no-target-blank": "react-doctor/jsx-no-target-blank",
6728
6728
  "react/jsx-no-undef": "react-doctor/jsx-no-undef",
6729
6729
  "react/jsx-no-useless-fragment": "react-doctor/jsx-no-useless-fragment",
6730
6730
  "react/jsx-pascal-case": "react-doctor/jsx-pascal-case",
@@ -7920,51 +7920,51 @@ const FLAGGED_DEPENDENCIES = [
7920
7920
  {
7921
7921
  packageName: "expo-modules-autolinking",
7922
7922
  rule: "expo-no-redundant-dependency",
7923
- message: "\"expo-modules-autolinking\" should not be a direct dependency — Expo installs it transitively as needed",
7923
+ message: "\"expo-modules-autolinking\" should not be a direct dependency. Expo pins the compatible version through the SDK, and a direct entry can drift to a version that breaks prebuild, Metro, or native builds",
7924
7924
  help: "Remove `expo-modules-autolinking` from your package.json"
7925
7925
  },
7926
7926
  {
7927
7927
  packageName: "expo-dev-launcher",
7928
7928
  rule: "expo-no-redundant-dependency",
7929
- message: "\"expo-dev-launcher\" should not be a direct dependency — it is pulled in by `expo-dev-client`",
7929
+ message: "\"expo-dev-launcher\" should not be a direct dependency. `expo-dev-client` pins the compatible launcher, and a direct entry can drift to a version that breaks native builds",
7930
7930
  help: "Remove `expo-dev-launcher` and depend on `expo-dev-client` instead"
7931
7931
  },
7932
7932
  {
7933
7933
  packageName: "expo-dev-menu",
7934
7934
  rule: "expo-no-redundant-dependency",
7935
- message: "\"expo-dev-menu\" should not be a direct dependency — it is pulled in by `expo-dev-client`",
7935
+ message: "\"expo-dev-menu\" should not be a direct dependency. `expo-dev-client` pins the compatible dev menu, and a direct entry can drift to a version that breaks native builds",
7936
7936
  help: "Remove `expo-dev-menu` and depend on `expo-dev-client` instead"
7937
7937
  },
7938
7938
  {
7939
7939
  packageName: "expo-modules-core",
7940
7940
  rule: "expo-no-redundant-dependency",
7941
- message: "\"expo-modules-core\" should not be a direct dependency — use the API re-exported from the `expo` package",
7941
+ message: "\"expo-modules-core\" should not be a direct dependency. Expo pins the compatible native core, and a direct entry can drift to a version that breaks prebuild or native builds",
7942
7942
  help: "Remove `expo-modules-core` from your package.json and import from `expo` instead"
7943
7943
  },
7944
7944
  {
7945
7945
  packageName: "@expo/metro-config",
7946
7946
  rule: "expo-no-redundant-dependency",
7947
- message: "\"@expo/metro-config\" should not be a direct dependency — use the `expo/metro-config` sub-export of the `expo` package",
7947
+ message: "\"@expo/metro-config\" should not be a direct dependency. Expo pins the compatible Metro config, and a direct entry can drift to a version that breaks bundling",
7948
7948
  help: "Remove `@expo/metro-config` and import `expo/metro-config` in your metro.config.js"
7949
7949
  },
7950
7950
  {
7951
7951
  packageName: "@types/react-native",
7952
7952
  rule: "expo-no-redundant-dependency",
7953
- message: "\"@types/react-native\" should not be installed — React Native ships its own types since SDK 48",
7953
+ message: "\"@types/react-native\" should not be installed. React Native ships its own types since SDK 48, so the extra package can introduce duplicate or stale type definitions",
7954
7954
  help: "Remove `@types/react-native` from your package.json",
7955
7955
  minSdkMajor: 48
7956
7956
  },
7957
7957
  {
7958
7958
  packageName: "@expo/config-plugins",
7959
7959
  rule: "expo-no-redundant-dependency",
7960
- message: "\"@expo/config-plugins\" should not be a direct dependency — use the `expo/config-plugins` sub-export of the `expo` package",
7960
+ message: "\"@expo/config-plugins\" should not be a direct dependency. Expo pins the compatible config-plugin API, and a direct entry can drift to a version that breaks prebuild",
7961
7961
  help: "Remove `@expo/config-plugins`; config-plugin authors should import from `expo/config-plugins`. See https://github.com/expo/expo/pull/18855",
7962
7962
  minSdkMajor: 48
7963
7963
  },
7964
7964
  {
7965
7965
  packageName: "@expo/prebuild-config",
7966
7966
  rule: "expo-no-redundant-dependency",
7967
- message: "\"@expo/prebuild-config\" should not be a direct dependency — Expo installs it transitively",
7967
+ message: "\"@expo/prebuild-config\" should not be a direct dependency. Expo pins the compatible prebuild config, and a direct entry can drift to a version that breaks prebuild",
7968
7968
  help: "Remove `@expo/prebuild-config` from your package.json",
7969
7969
  minSdkMajor: 53
7970
7970
  },
@@ -7978,28 +7978,28 @@ const FLAGGED_DEPENDENCIES = [
7978
7978
  {
7979
7979
  packageName: "expo-app-loading",
7980
7980
  rule: "expo-no-redundant-dependency",
7981
- message: "\"expo-app-loading\" was removed in SDK 49",
7981
+ message: "\"expo-app-loading\" was removed in SDK 49, so keeping it can leave imports unresolved after upgrading Expo",
7982
7982
  help: "Remove `expo-app-loading` and use `expo-splash-screen` instead. See https://docs.expo.dev/versions/latest/sdk/splash-screen/",
7983
7983
  minSdkMajor: 49
7984
7984
  },
7985
7985
  {
7986
7986
  packageName: "expo-firebase-analytics",
7987
7987
  rule: "expo-no-redundant-dependency",
7988
- message: "\"expo-firebase-analytics\" was removed in SDK 48",
7988
+ message: "\"expo-firebase-analytics\" was removed in SDK 48, so keeping it can leave imports unresolved or fail native builds after upgrading Expo",
7989
7989
  help: FIREBASE_HELP,
7990
7990
  minSdkMajor: 48
7991
7991
  },
7992
7992
  {
7993
7993
  packageName: "expo-firebase-recaptcha",
7994
7994
  rule: "expo-no-redundant-dependency",
7995
- message: "\"expo-firebase-recaptcha\" was removed in SDK 48",
7995
+ message: "\"expo-firebase-recaptcha\" was removed in SDK 48, so keeping it can leave imports unresolved or fail native builds after upgrading Expo",
7996
7996
  help: FIREBASE_HELP,
7997
7997
  minSdkMajor: 48
7998
7998
  },
7999
7999
  {
8000
8000
  packageName: "expo-firebase-core",
8001
8001
  rule: "expo-no-redundant-dependency",
8002
- message: "\"expo-firebase-core\" was removed in SDK 48",
8002
+ message: "\"expo-firebase-core\" was removed in SDK 48, so keeping it can leave imports unresolved or fail native builds after upgrading Expo",
8003
8003
  help: FIREBASE_HELP,
8004
8004
  minSdkMajor: 48
8005
8005
  }
@@ -8040,7 +8040,7 @@ const checkExpoGitignore = (context) => {
8040
8040
  }));
8041
8041
  if (findLocalModuleNativeFiles(rootDirectory).find((nativeFilePath) => isPathGitIgnored(rootDirectory, nativeFilePath) === true) !== void 0) diagnostics.push(buildExpoDiagnostic({
8042
8042
  rule: "expo-gitignore",
8043
- message: "The native `ios`/`android` directories of a local Expo module under `modules/` are gitignored — usually caused by an overly broad `ios`/`android` ignore rule",
8043
+ message: "The native `ios`/`android` directories of a local Expo module under `modules/` are gitignored, so required native code can be missing from CI or teammate checkouts.",
8044
8044
  help: "Use anchored patterns like `/ios` and `/android` in .gitignore so only the top-level native directories are excluded, not those inside `modules/`"
8045
8045
  }));
8046
8046
  return diagnostics;
@@ -8102,17 +8102,16 @@ const checkExpoPackageJsonConflicts = (context) => {
8102
8102
  const conflictingScriptNames = CONFLICTING_SCRIPT_NAMES.filter((scriptName) => Boolean(packageJson.scripts?.[scriptName]));
8103
8103
  if (conflictingScriptNames.length > 0) {
8104
8104
  const quotedNames = conflictingScriptNames.map((name) => `"${name}"`).join(", ");
8105
- const shadowsExpoCli = conflictingScriptNames.includes("expo");
8106
8105
  diagnostics.push(buildExpoDiagnostic({
8107
8106
  rule: "expo-package-json-conflict",
8108
- message: `package.json defines ${quotedNames} ${conflictingScriptNames.length === 1 ? "as a script that conflicts" : "as scripts that conflict"} with binaries in node_modules/.bin${shadowsExpoCli ? " — a `expo` script shadows the Expo CLI and will likely cause build failures" : ""}`,
8107
+ message: `package.json defines ${quotedNames} ${conflictingScriptNames.length === 1 ? "as a script that shadows" : "as scripts that shadow"} Expo/React Native binaries in node_modules/.bin, so tooling can run the local script instead of the expected CLI and fail builds.`,
8109
8108
  help: "Rename these scripts so they don't collide with the `expo` / `react-native` binaries"
8110
8109
  }));
8111
8110
  }
8112
8111
  const packageName = packageJson.name;
8113
8112
  if (typeof packageName === "string" && context.directDependencyNames.has(packageName)) diagnostics.push(buildExpoDiagnostic({
8114
8113
  rule: "expo-package-json-conflict",
8115
- message: `package.json "name" is "${packageName}", which collides with a dependency of the same name`,
8114
+ message: `package.json "name" is "${packageName}", which collides with a dependency of the same name, so package self-resolution can shadow the dependency and break imports that expect the installed package.`,
8116
8115
  help: "Rename your package so it no longer matches one of its dependencies"
8117
8116
  }));
8118
8117
  return diagnostics;
@@ -8183,7 +8182,7 @@ const checkExpoRouterReactNavigation = (context) => {
8183
8182
  if (reactNavigationNames.length === 0) return [];
8184
8183
  return [buildExpoDiagnostic({
8185
8184
  rule: "expo-router-no-react-navigation",
8186
- message: `As of SDK 56, expo-router is no longer compatible with react-navigation, but ${reactNavigationNames.map((name) => `"${name}"`).join(", ")} ${reactNavigationNames.length === 1 ? "is" : "are"} installed as direct ${reactNavigationNames.length === 1 ? "dependency" : "dependencies"}`,
8185
+ message: `As of SDK 56, expo-router is no longer compatible with directly installed @react-navigation packages, so keeping ${reactNavigationNames.map((name) => `"${name}"`).join(", ")} can break routing or linking behavior after the SDK upgrade.`,
8187
8186
  help: "Remove these `@react-navigation/*` packages and replace direct imports with their expo-router equivalents. See https://docs.expo.dev/router/migrate/sdk-55-to-56/"
8188
8187
  })];
8189
8188
  };
@@ -8555,7 +8554,9 @@ const setColorEnabled = (enabled) => {
8555
8554
  highlighter.gray = colors.gray;
8556
8555
  highlighter.bold = colors.bold;
8557
8556
  };
8558
- const computeJsxIncludePaths = (includePaths) => includePaths.length > 0 ? includePaths.filter((filePath) => JSX_FILE_PATTERN.test(filePath)) : void 0;
8557
+ const NEXT_ENTRY_FILE_PATTERN = /^(?:\.\/)?(?:src\/)?(?:middleware|proxy)\.(?:tsx?|jsx?|mts|mjs)$/;
8558
+ const shouldIncludeExplicitLintPath = (filePath, project) => JSX_FILE_PATTERN.test(filePath) || project?.framework === "nextjs" && NEXT_ENTRY_FILE_PATTERN.test(filePath);
8559
+ const computeExplicitLintIncludePaths = (includePaths, project) => includePaths.length > 0 ? includePaths.filter((filePath) => shouldIncludeExplicitLintPath(filePath, project)) : void 0;
8559
8560
  const LINGUIST_ATTRIBUTE_PATTERN = /^linguist-(?:vendored|generated)(?:=([a-zA-Z0-9]+))?$/i;
8560
8561
  const FALSY_VALUES = new Set([
8561
8562
  "false",
@@ -8981,7 +8982,7 @@ const checkDeadCode = async (options) => {
8981
8982
  plugin: DEAD_CODE_PLUGIN,
8982
8983
  rule: "unused-file",
8983
8984
  severity: "warning",
8984
- message: "Unused file — not reachable from any entry point",
8985
+ message: "Unused file is not reachable from any entry point, so it adds maintenance surface without shipping any code.",
8985
8986
  help: "Delete the file if it is truly unreachable, or import it from an entry point.",
8986
8987
  line: 0,
8987
8988
  column: 0,
@@ -8994,7 +8995,7 @@ const checkDeadCode = async (options) => {
8994
8995
  plugin: DEAD_CODE_PLUGIN,
8995
8996
  rule: unusedExport.isTypeOnly ? "unused-type" : "unused-export",
8996
8997
  severity: "warning",
8997
- message: `Unused ${label}: \`${unusedExport.name}\``,
8998
+ message: `Unused ${label}: \`${unusedExport.name}\` is exported but no module imports it, so it expands the public surface and can mislead callers about supported API.`,
8998
8999
  help: "Drop the `export` keyword (or remove the declaration) if no other module uses this symbol.",
8999
9000
  line: unusedExport.line,
9000
9001
  column: unusedExport.column,
@@ -9008,7 +9009,7 @@ const checkDeadCode = async (options) => {
9008
9009
  plugin: DEAD_CODE_PLUGIN,
9009
9010
  rule: unusedDependency.isDevDependency ? "unused-dev-dependency" : "unused-dependency",
9010
9011
  severity: "warning",
9011
- message: `Unused ${label}: \`${unusedDependency.name}\``,
9012
+ message: `Unused ${label}: \`${unusedDependency.name}\` is not imported by the project, so it adds install time and supply-chain surface without being used.`,
9012
9013
  help: "Remove the dependency from package.json if it is genuinely unused.",
9013
9014
  line: 0,
9014
9015
  column: 0,
@@ -9022,7 +9023,7 @@ const checkDeadCode = async (options) => {
9022
9023
  plugin: DEAD_CODE_PLUGIN,
9023
9024
  rule: "circular-dependency",
9024
9025
  severity: "warning",
9025
- message: `Circular import cycle: ${cycle.files.map(toRelative).join(" → ")}`,
9026
+ message: `Circular import cycle: ${cycle.files.map(toRelative).join(" → ")}. Modules in the cycle can observe partially initialized exports, causing order-dependent bugs.`,
9026
9027
  help: "Break the cycle by extracting the shared code into a third module that both files import.",
9027
9028
  line: 0,
9028
9029
  column: 0,
@@ -9105,11 +9106,11 @@ const listSourceFilesViaFilesystem = (rootDirectory) => {
9105
9106
  return filePaths;
9106
9107
  };
9107
9108
  const listSourceFiles = (rootDirectory) => excludeMinifiedFiles(rootDirectory, listSourceFilesViaGit(rootDirectory) ?? listSourceFilesViaFilesystem(rootDirectory));
9108
- const resolveLintIncludePaths = (rootDirectory, userConfig) => {
9109
+ const resolveLintIncludePaths = (rootDirectory, userConfig, project) => {
9109
9110
  if (!Array.isArray(userConfig?.ignore?.files) || userConfig.ignore.files.length === 0) return;
9110
9111
  const ignoredPatterns = compileIgnoredFilePatterns(userConfig);
9111
9112
  return listSourceFiles(rootDirectory).filter((filePath) => {
9112
- if (!JSX_FILE_PATTERN.test(filePath)) return false;
9113
+ if (!shouldIncludeExplicitLintPath(filePath, project)) return false;
9113
9114
  return !isFileIgnoredByPatterns(filePath, rootDirectory, ignoredPatterns);
9114
9115
  });
9115
9116
  };
@@ -11461,7 +11462,7 @@ const runInspect = (input, hooks = {}) => Effect.gen(function* () {
11461
11462
  directory: scanDirectory,
11462
11463
  repo
11463
11464
  }).pipe(Effect.orElseSucceed(() => null)) : Effect.succeed(null));
11464
- const lintIncludePaths = (input.skipJsxIncludeFilter ? input.includePaths.length > 0 ? [...input.includePaths] : void 0 : computeJsxIncludePaths([...input.includePaths])) ?? resolveLintIncludePaths(scanDirectory, resolvedConfig.config);
11465
+ const lintIncludePaths = (input.skipJsxIncludeFilter ? input.includePaths.length > 0 ? [...input.includePaths] : void 0 : computeExplicitLintIncludePaths([...input.includePaths], project)) ?? resolveLintIncludePaths(scanDirectory, resolvedConfig.config, project);
11465
11466
  const scannedFilePaths = input.suppressScanSummary ? (lintIncludePaths ?? (yield* filesService.listSourceFiles(scanDirectory))).map((relativePath) => path$1.resolve(scanDirectory, relativePath)) : [];
11466
11467
  const beforeLint = hooks.beforeLint ?? NO_HOOKS.beforeLint;
11467
11468
  const afterLint = hooks.afterLint ?? NO_HOOKS.afterLint;
@@ -12247,7 +12248,7 @@ const makeNoopConsole = () => ({
12247
12248
  });
12248
12249
  //#endregion
12249
12250
  //#region src/cli/utils/version.ts
12250
- const VERSION = "0.4.1-dev.e181ac1";
12251
+ const VERSION = "0.4.2-dev.1044e29";
12251
12252
  //#endregion
12252
12253
  //#region src/cli/utils/json-mode.ts
12253
12254
  let context = null;
@@ -12605,13 +12606,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
12605
12606
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
12606
12607
  * standard `SENTRY_RELEASE` override.
12607
12608
  */
12608
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.1-dev.e181ac1`;
12609
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.2-dev.1044e29`;
12609
12610
  /**
12610
12611
  * Deployment environment shown in Sentry's environment filter. Defaults to
12611
12612
  * `production` for tagged releases and `development` for dev/unbuilt versions,
12612
12613
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
12613
12614
  */
12614
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.1-dev.e181ac1") ? "development" : "production");
12615
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.2-dev.1044e29") ? "development" : "production");
12615
12616
  /**
12616
12617
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
12617
12618
  * (set to `0` to disable tracing) and falls back to
@@ -15874,13 +15875,14 @@ const buildRuntimeLayers = (input) => {
15874
15875
  const linterLayer = input.shouldSkipLint ? Linter.layerOf([]) : Linter.layerOxlint;
15875
15876
  const deadCodeLayer = input.shouldRunDeadCode ? DeadCode.layerNode : DeadCode.layerOf([]);
15876
15877
  const scoreLayer = input.shouldComputeScore ? Score.layerHttp : Score.layerOf(null);
15878
+ const projectLayer = input.projectInfoOverride === void 0 ? Project.layerNode : Project.layerOf(input.projectInfoOverride);
15877
15879
  const progressLayer = input.shouldShowProgressSpinners ? Progress.layerOra(buildSpinnerProgressHandle) : Progress.layerNoop;
15878
15880
  const configLayer = input.hasConfigOverride ? Config.layerOf({
15879
15881
  config: input.userConfig,
15880
15882
  resolvedDirectory: input.directory,
15881
15883
  configSourceDirectory: input.configSourceDirectory
15882
15884
  }) : Config.layerNode;
15883
- const baseLayers = Layer.mergeAll(Project.layerNode, configLayer, Files.layerNode, Git.layerNode, linterLayer, LintPartialFailures.layerLive, deadCodeLayer, progressLayer, Reporter.layerNoop, scoreLayer);
15885
+ const baseLayers = Layer.mergeAll(projectLayer, configLayer, Files.layerNode, Git.layerNode, linterLayer, LintPartialFailures.layerLive, deadCodeLayer, progressLayer, Reporter.layerNoop, scoreLayer);
15884
15886
  return input.oxlintConcurrency === void 0 ? baseLayers : Layer.mergeAll(baseLayers, Layer.succeed(OxlintConcurrency, input.oxlintConcurrency));
15885
15887
  };
15886
15888
  //#endregion
@@ -16473,8 +16475,22 @@ const buildCodeFrame = (input) => {
16473
16475
  });
16474
16476
  };
16475
16477
  //#endregion
16478
+ //#region src/cli/utils/resolve-measure-width.ts
16479
+ const resolveClampedWidth = (input) => {
16480
+ const terminalColumns = process.stdout.columns;
16481
+ if (!terminalColumns || terminalColumns <= 0) return input.fullWidth;
16482
+ const availableColumns = terminalColumns - input.reservedColumns;
16483
+ return Math.max(input.minWidth, Math.min(input.fullWidth, availableColumns));
16484
+ };
16485
+ const resolveMeasureWidth = (reservedColumns = 0) => resolveClampedWidth({
16486
+ reservedColumns,
16487
+ fullWidth: 60,
16488
+ minWidth: 24
16489
+ });
16490
+ //#endregion
16476
16491
  //#region src/cli/utils/build-section-divider.ts
16477
- const buildSectionDivider = () => highlighter.dim(` ${"─".repeat(60)}`);
16492
+ const DIVIDER_INDENT = " ";
16493
+ const buildSectionDivider = () => highlighter.dim(`${DIVIDER_INDENT}${"─".repeat(resolveMeasureWidth(2))}`);
16478
16494
  //#endregion
16479
16495
  //#region src/cli/utils/indent-multiline-text.ts
16480
16496
  const indentMultilineText = (text, linePrefix) => text.split("\n").map((lineText) => `${linePrefix}${lineText}`).join("\n");
@@ -16634,7 +16650,10 @@ const buildDiagnosticClusterLines = (cluster, resolveSourceRoot, renderCodeFrame
16634
16650
  endLine: isMultiSite ? cluster.endLine : void 0,
16635
16651
  rootDirectory: resolveSourceRoot(lead)
16636
16652
  }) : null;
16637
- if (codeFrame) lines.push(indentMultilineText(boxText(codeFrame, 60), TOP_ERROR_DETAIL_INDENT));
16653
+ if (codeFrame) {
16654
+ const boxInnerWidth = resolveMeasureWidth(8);
16655
+ lines.push(indentMultilineText(boxText(codeFrame, boxInnerWidth), TOP_ERROR_DETAIL_INDENT));
16656
+ }
16638
16657
  const seenHints = /* @__PURE__ */ new Set();
16639
16658
  for (const diagnostic of cluster.diagnostics) if (diagnostic.suppressionHint && !seenHints.has(diagnostic.suppressionHint)) {
16640
16659
  seenHints.add(diagnostic.suppressionHint);
@@ -16652,8 +16671,8 @@ const buildRuleDetailBlock = (ruleKey, ruleDiagnostics, resolveSourceRoot, rende
16652
16671
  const learnMoreLine = formatLearnMoreLine(representative);
16653
16672
  if (learnMoreLine) lines.push(`${TOP_ERROR_DETAIL_INDENT}${highlighter.info(learnMoreLine)}`);
16654
16673
  }
16655
- if (!renderEverySite) for (const explanationLine of wrapTextToWidth(representative.message, 60, { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
16656
- if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, 60, { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
16674
+ for (const explanationLine of wrapTextToWidth(representative.message, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
16675
+ if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
16657
16676
  if (renderEverySite && isAgentEnvironment) {
16658
16677
  const fixRecipeLine = formatFixRecipeLine(representative);
16659
16678
  if (fixRecipeLine) lines.push(highlighter.gray(`${TOP_ERROR_DETAIL_INDENT}${fixRecipeLine}`));
@@ -16789,6 +16808,9 @@ const computeProjectedScore = async (topErrorSource, rescoreSource, currentScore
16789
16808
  if (!potentialScore || potentialScore.score <= currentScore.score) return null;
16790
16809
  return potentialScore.score;
16791
16810
  };
16811
+ //#endregion
16812
+ //#region src/cli/utils/filter-diagnostics-by-categories.ts
16813
+ const filterDiagnosticsByCategories = (diagnostics, categories) => categories.size === 0 ? [...diagnostics] : diagnostics.filter((diagnostic) => categories.has(diagnostic.category));
16792
16814
  const FORCE_ONBOARDING_ENV_VAR = "REACT_DOCTOR_FORCE_ONBOARDING";
16793
16815
  const FALSY_FLAG_VALUES = new Set([
16794
16816
  "",
@@ -16847,14 +16869,21 @@ const RAINBOW_HUE_SHIFT_PER_FRAME = 9;
16847
16869
  const RAINBOW_GRADIENT_WIDTH = 80;
16848
16870
  const RAINBOW_OKLCH_LIGHTNESS = .638;
16849
16871
  const RAINBOW_OKLCH_CHROMA = .129;
16872
+ const FACE_BOX_TOP_BORDER = "┌─────┐";
16873
+ const SCORE_RIGHT_COLUMN_OFFSET = 11;
16874
+ const getScoreBarWidth = () => resolveClampedWidth({
16875
+ reservedColumns: SCORE_RIGHT_COLUMN_OFFSET + 1,
16876
+ fullWidth: 50,
16877
+ minWidth: 10
16878
+ });
16850
16879
  const buildScoreBarSegments = (filledCount) => {
16851
- const emptyCount = 50 - filledCount;
16880
+ const emptyCount = Math.max(0, getScoreBarWidth() - filledCount);
16852
16881
  return {
16853
16882
  filledSegment: "█".repeat(filledCount),
16854
16883
  emptySegment: "░".repeat(emptyCount)
16855
16884
  };
16856
16885
  };
16857
- const getFilledCount = (score) => Math.round(score / 100 * 50);
16886
+ const getFilledCount = (score) => Math.round(score / 100 * getScoreBarWidth());
16858
16887
  const joinScoreHeaderFrame = (lines) => `${lines[0]}\n\r${lines[1]}\n\r${lines[2]}\n\r${lines[3]}\n`;
16859
16888
  const buildRawScoreBar = (displayScore) => {
16860
16889
  const { filledSegment, emptySegment } = buildScoreBarSegments(getFilledCount(displayScore));
@@ -16890,10 +16919,11 @@ const buildScoreBar = (displayScore, colorScore = displayScore) => {
16890
16919
  return colorizeByScore(filledSegment, colorScore) + highlighter.dim(emptySegment);
16891
16920
  };
16892
16921
  const buildProjectedScoreBar = (currentScore, potentialScore) => {
16922
+ const barWidth = getScoreBarWidth();
16893
16923
  const currentFill = getFilledCount(currentScore);
16894
- const potentialFill = Math.min(getFilledCount(potentialScore), 50);
16924
+ const potentialFill = Math.min(getFilledCount(potentialScore), barWidth);
16895
16925
  const gainCount = Math.max(0, potentialFill - currentFill);
16896
- const emptyCount = Math.max(0, 50 - currentFill - gainCount);
16926
+ const emptyCount = Math.max(0, barWidth - currentFill - gainCount);
16897
16927
  return colorizeByScore("█".repeat(currentFill), currentScore) + highlighter.dim(colorizeByScore("▓".repeat(gainCount), currentScore)) + highlighter.dim("░".repeat(emptyCount));
16898
16928
  };
16899
16929
  const getDoctorFace = (score) => {
@@ -16906,7 +16936,7 @@ const RAW_BRANDING_LINE = "React Doctor (https://react.doctor)";
16906
16936
  const buildRawFaceLines = (score) => {
16907
16937
  const [eyes, mouth] = getDoctorFace(score);
16908
16938
  return [
16909
- "┌─────┐",
16939
+ FACE_BOX_TOP_BORDER,
16910
16940
  `│ ${eyes} │`,
16911
16941
  `│ ${mouth} │`,
16912
16942
  "└─────┘"
@@ -17048,6 +17078,11 @@ const writeDiagnosticsDirectory = (diagnostics) => {
17048
17078
  };
17049
17079
  //#endregion
17050
17080
  //#region src/cli/utils/render-summary.ts
17081
+ const FOOTER_DESCRIPTION_INDENT = " ";
17082
+ const printFooterDescription = (description) => Effect.gen(function* () {
17083
+ const wrapWidth = resolveMeasureWidth(2);
17084
+ for (const line of wrapTextToWidth(description, wrapWidth)) yield* Console.log(highlighter.dim(`${FOOTER_DESCRIPTION_INDENT}${line}`));
17085
+ });
17051
17086
  const buildShareUrl = (diagnostics, scoreResult, projectName) => {
17052
17087
  const errorCount = diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
17053
17088
  const warningCount = diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length;
@@ -17067,14 +17102,14 @@ const printFooter = (input) => Effect.gen(function* () {
17067
17102
  if (!input.isOffline) {
17068
17103
  const shareUrl = buildShareUrl(input.diagnostics, input.scoreResult, input.projectName);
17069
17104
  yield* Console.log(` ${highlighter.bold("Share:")} ${highlighter.info(shareUrl)}`);
17070
- yield* Console.log(highlighter.dim(" Tell others how you did on socials"));
17105
+ yield* printFooterDescription("Tell others how you did on socials");
17071
17106
  yield* Console.log("");
17072
17107
  }
17073
17108
  yield* Console.log(` ${highlighter.bold("Docs:")} ${highlighter.info(DOCS_URL)}`);
17074
- yield* Console.log(highlighter.dim(" Learn more about fixing issues, setting up CI/CD, and configuring rules with a config file"));
17109
+ yield* printFooterDescription("Learn more about fixing issues, setting up CI/CD, and configuring rules with a config file");
17075
17110
  yield* Console.log("");
17076
17111
  yield* Console.log(` ${highlighter.bold("GitHub:")} ${highlighter.info(CANONICAL_GITHUB_URL)}`);
17077
- yield* Console.log(highlighter.dim(" Report issues and star the repository!"));
17112
+ yield* printFooterDescription("Report issues and star the repository!");
17078
17113
  });
17079
17114
  const printSummary = (input) => Effect.gen(function* () {
17080
17115
  if (input.scoreResult) {
@@ -17206,11 +17241,47 @@ const resolveOxlintNodeEffect = (isLintEnabled, isQuiet) => Effect.gen(function*
17206
17241
  });
17207
17242
  const resolveOxlintNode = (isLintEnabled, isQuiet) => Effect.runPromise(resolveOxlintNodeEffect(isLintEnabled, isQuiet).pipe(Effect.provide(NodeResolver.layerNode)));
17208
17243
  //#endregion
17244
+ //#region src/cli/utils/cli-input-error.ts
17245
+ /**
17246
+ * A mistake in *how the CLI was invoked* — a malformed `<file>:<line>`
17247
+ * argument, mutually exclusive flags, or an unknown `--project` name. This is
17248
+ * user input, not a react-doctor bug, so `isExpectedUserError` routes it
17249
+ * through `handleUserError`: a clean, single-line message with no Sentry
17250
+ * report and no "Something went wrong, open a prefilled issue" block.
17251
+ *
17252
+ * The `message` is rendered verbatim, so it must read as a complete,
17253
+ * human-readable sentence that tells the user how to fix their invocation.
17254
+ */
17255
+ var CliInputError = class extends Error {
17256
+ name = "CliInputError";
17257
+ };
17258
+ //#endregion
17259
+ //#region src/cli/utils/resolve-cli-categories.ts
17260
+ const categoryByLowercase = new Map(DIAGNOSTIC_CATEGORY_BUCKETS.map((category) => [category.toLowerCase(), category]));
17261
+ const knownCategoryList = DIAGNOSTIC_CATEGORY_BUCKETS.join(", ");
17262
+ const splitCategoryFlagValue = (value) => value.split(",").map((category) => category.trim()).filter((category) => category.length > 0);
17263
+ const resolveCliCategories = (categoryFlag) => {
17264
+ const rawCategoryValues = categoryFlag === void 0 ? [] : Array.isArray(categoryFlag) ? categoryFlag : [categoryFlag];
17265
+ const resolvedCategories = [];
17266
+ const seenCategories = /* @__PURE__ */ new Set();
17267
+ for (const rawCategoryValue of rawCategoryValues) for (const categoryQuery of splitCategoryFlagValue(rawCategoryValue)) {
17268
+ const matchedCategory = categoryByLowercase.get(categoryQuery.toLowerCase());
17269
+ if (matchedCategory === void 0) throw new CliInputError(`Unknown category "${categoryQuery}". Expected one of: ${knownCategoryList}.`);
17270
+ if (!seenCategories.has(matchedCategory)) {
17271
+ seenCategories.add(matchedCategory);
17272
+ resolvedCategories.push(matchedCategory);
17273
+ }
17274
+ }
17275
+ if (rawCategoryValues.length > 0 && resolvedCategories.length === 0) throw new CliInputError(`--category requires one of: ${knownCategoryList}.`);
17276
+ return resolvedCategories.length > 0 ? resolvedCategories : void 0;
17277
+ };
17278
+ //#endregion
17209
17279
  //#region src/inspect.ts
17210
17280
  const silentConsole = makeNoopConsole();
17211
17281
  const runConsole = (effect) => {
17212
17282
  Effect.runSync(effect);
17213
17283
  };
17284
+ const formatCategorySelection = (categoryFilters) => [...categoryFilters].join(", ");
17214
17285
  const buildIgnoredTags = (userConfig) => {
17215
17286
  const tags = /* @__PURE__ */ new Set();
17216
17287
  if (userConfig?.ignore?.tags) for (const tag of userConfig.ignore.tags) tags.add(tag);
@@ -17231,6 +17302,7 @@ const mergeInspectOptions = (inputOptions, userConfig) => ({
17231
17302
  share: userConfig?.share ?? true,
17232
17303
  respectInlineDisables: inputOptions.respectInlineDisables ?? userConfig?.respectInlineDisables ?? true,
17233
17304
  warnings: inputOptions.warnings ?? userConfig?.warnings ?? true,
17305
+ categoryFilters: new Set(resolveCliCategories(inputOptions.categoryFilters) ?? []),
17234
17306
  adoptExistingLintConfig: userConfig?.adoptExistingLintConfig ?? true,
17235
17307
  ignoredTags: buildIgnoredTags(userConfig),
17236
17308
  outputSurface: inputOptions.outputSurface ?? "cli",
@@ -17317,6 +17389,7 @@ const runBaselineComparison = async (params) => {
17317
17389
  hasConfigOverride: true,
17318
17390
  userConfig: params.userConfig,
17319
17391
  configSourceDirectory: null,
17392
+ projectInfoOverride: params.headProjectInfo,
17320
17393
  shouldSkipLint: !params.options.lint || !params.resolvedNodeBinaryPath,
17321
17394
  shouldRunDeadCode: false,
17322
17395
  shouldComputeScore: false,
@@ -17416,6 +17489,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17416
17489
  directory,
17417
17490
  options,
17418
17491
  userConfig,
17492
+ headProjectInfo: output.project,
17419
17493
  headDiagnostics: output.diagnostics,
17420
17494
  resolvedNodeBinaryPath,
17421
17495
  baselineRef: options.baseline.ref
@@ -17514,14 +17588,16 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17514
17588
  const animateRender = !options.silent && !options.verbose && canAnimateOnboarding(process.stdout);
17515
17589
  const pause = onboardingSectionPause(animateRender);
17516
17590
  const surfaceDiagnostics = filterDiagnosticsForSurface([...diagnostics], options.outputSurface, userConfig);
17591
+ const printedDiagnostics = filterDiagnosticsByCategories(surfaceDiagnostics, options.categoryFilters);
17517
17592
  const demotedDiagnosticCount = diagnostics.length - surfaceDiagnostics.length;
17518
17593
  const lintSourceFileCount = options.includePaths.length > 0 ? options.includePaths.length : project.sourceFileCount;
17519
- if (surfaceDiagnostics.length === 0) {
17594
+ if (printedDiagnostics.length === 0) {
17520
17595
  yield* pause;
17521
17596
  if (hasSkippedChecks) {
17522
17597
  const skippedLabel = skippedChecks.join(" and ");
17523
17598
  yield* Console.warn(highlighter.warn(`No issues detected, but ${skippedLabel} checks failed — results are incomplete.`));
17524
- } else if (demotedDiagnosticCount > 0) yield* Console.log(highlighter.success(`No issues found! (${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface — see config.surfaces.)`));
17599
+ } else if (options.categoryFilters.size > 0) yield* Console.log(highlighter.success(`No issues found in category ${formatCategorySelection(options.categoryFilters)}!`));
17600
+ else if (demotedDiagnosticCount > 0) yield* Console.log(highlighter.success(`No issues found! (${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface — see config.surfaces.)`));
17525
17601
  else yield* Console.log(highlighter.success("No issues found!"));
17526
17602
  yield* Console.log("");
17527
17603
  yield* pause;
@@ -17534,20 +17610,20 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17534
17610
  }
17535
17611
  yield* pause;
17536
17612
  yield* Console.log("");
17537
- yield* printDiagnostics([...surfaceDiagnostics], options.verbose, directory, buildRulePriorityMap([score]), isCodingAgentEnvironment(), {
17613
+ yield* printDiagnostics([...printedDiagnostics], options.verbose, directory, buildRulePriorityMap([score]), isCodingAgentEnvironment(), {
17538
17614
  sectionPause: pause,
17539
17615
  animateCountUp: animateRender
17540
17616
  });
17541
17617
  if (options.isNonInteractiveEnvironment && options.outputSurface !== "prComment") yield* printAgentGuidance();
17542
- if (demotedDiagnosticCount > 0) {
17618
+ if (options.categoryFilters.size === 0 && demotedDiagnosticCount > 0) {
17543
17619
  yield* Console.log(highlighter.gray(` ${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface (e.g. design cleanup) — run \`npx react-doctor@latest .\` locally for the full list.`));
17544
17620
  yield* Console.log("");
17545
17621
  }
17546
- const potentialScore = score ? yield* Effect.promise(() => computeProjectedScore([...surfaceDiagnostics], [...surfaceDiagnostics], score)) : null;
17622
+ const potentialScore = score ? yield* Effect.promise(() => computeProjectedScore([...printedDiagnostics], [...surfaceDiagnostics], score)) : null;
17547
17623
  const shouldShowShareLink = !options.noScore && options.share && !options.isCi;
17548
17624
  yield* pause;
17549
17625
  yield* printSummary({
17550
- diagnostics: [...surfaceDiagnostics],
17626
+ diagnostics: [...printedDiagnostics],
17551
17627
  elapsedMilliseconds,
17552
17628
  scoreResult: score,
17553
17629
  potentialScore,
@@ -17563,7 +17639,7 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17563
17639
  }
17564
17640
  yield* pause;
17565
17641
  yield* printFooter({
17566
- diagnostics: [...surfaceDiagnostics],
17642
+ diagnostics: [...printedDiagnostics],
17567
17643
  scoreResult: score,
17568
17644
  projectName: project.projectName,
17569
17645
  isOffline: !shouldShowShareLink
@@ -17694,21 +17770,6 @@ const handleUserError = (error, options = {}) => {
17694
17770
  process.exitCode = 1;
17695
17771
  };
17696
17772
  //#endregion
17697
- //#region src/cli/utils/cli-input-error.ts
17698
- /**
17699
- * A mistake in *how the CLI was invoked* — a malformed `<file>:<line>`
17700
- * argument, mutually exclusive flags, or an unknown `--project` name. This is
17701
- * user input, not a react-doctor bug, so `isExpectedUserError` routes it
17702
- * through `handleUserError`: a clean, single-line message with no Sentry
17703
- * report and no "Something went wrong, open a prefilled issue" block.
17704
- *
17705
- * The `message` is rendered verbatim, so it must read as a complete,
17706
- * human-readable sentence that tells the user how to fix their invocation.
17707
- */
17708
- var CliInputError = class extends Error {
17709
- name = "CliInputError";
17710
- };
17711
- //#endregion
17712
17773
  //#region src/cli/utils/is-expected-user-error.ts
17713
17774
  /**
17714
17775
  * Whether `error` is an expected, user-actionable failure — the user's project
@@ -17980,190 +18041,24 @@ const installDoctorScript = (options) => {
17980
18041
  ...scriptTarget.reason !== void 0 ? { scriptReason: scriptTarget.reason } : {}
17981
18042
  };
17982
18043
  };
17983
- //#endregion
17984
- //#region src/cli/utils/install-agent-hooks.ts
17985
- const CLAUDE_AGENT = "claude-code";
17986
- const CURSOR_AGENT = "cursor";
17987
- const CLAUDE_SETTINGS_RELATIVE_PATH = ".claude/settings.json";
17988
- const CLAUDE_HOOK_RELATIVE_PATH = ".claude/hooks/react-doctor.sh";
17989
- const CLAUDE_HOOK_COMMAND = "sh \"$CLAUDE_PROJECT_DIR/.claude/hooks/react-doctor.sh\"";
17990
- const CURSOR_HOOKS_RELATIVE_PATH = ".cursor/hooks.json";
17991
- const CURSOR_HOOK_RELATIVE_PATH = ".cursor/hooks/react-doctor.sh";
17992
- const CURSOR_HOOK_MATCHER = "Write|Edit|MultiEdit|ApplyPatch";
17993
- const CURSOR_HOOKS_SCHEMA_VERSION = 1;
17994
- const JSON_INDENT_SPACES$1 = 2;
17995
- const isSupportedAgent = (agent) => agent === CLAUDE_AGENT || agent === CURSOR_AGENT;
17996
- const readJsonFile = (filePath, fallback) => {
17997
- if (!fs$1.existsSync(filePath)) return fallback;
17998
- const content = fs$1.readFileSync(filePath, "utf8").trim();
17999
- if (content.length === 0) return fallback;
18000
- return JSON.parse(content);
18001
- };
18002
- const writeJsonFile = (filePath, value) => {
18003
- fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18004
- fs$1.writeFileSync(filePath, `${JSON.stringify(value, null, JSON_INDENT_SPACES$1)}\n`);
18005
- };
18006
- const writeHookScript = (filePath) => {
18007
- fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18008
- fs$1.writeFileSync(filePath, buildAgentHookScript());
18009
- fs$1.chmodSync(filePath, 493);
18010
- };
18011
- const hasClaudeHookCommand = (groups) => groups.some((group) => (group.hooks ?? []).some((hook) => hook.command === CLAUDE_HOOK_COMMAND));
18012
- const installClaudeHook = (projectRoot) => {
18013
- const settingsPath = path$1.join(projectRoot, CLAUDE_SETTINGS_RELATIVE_PATH);
18014
- const hookPath = path$1.join(projectRoot, CLAUDE_HOOK_RELATIVE_PATH);
18015
- const settings = readJsonFile(settingsPath, {});
18016
- const hooks = { ...settings.hooks ?? {} };
18017
- const postToolBatchHooks = [...hooks.PostToolBatch ?? []];
18018
- if (!hasClaudeHookCommand(postToolBatchHooks)) postToolBatchHooks.push({ hooks: [{
18019
- type: "command",
18020
- command: CLAUDE_HOOK_COMMAND
18021
- }] });
18022
- hooks.PostToolBatch = postToolBatchHooks;
18023
- writeJsonFile(settingsPath, {
18024
- ...settings,
18025
- hooks
18026
- });
18027
- writeHookScript(hookPath);
18028
- return [settingsPath, hookPath];
18029
- };
18030
- const hasCursorHookCommand = (handlers) => handlers.some((handler) => handler.command === CURSOR_HOOK_RELATIVE_PATH);
18031
- const installCursorHook = (projectRoot) => {
18032
- const configPath = path$1.join(projectRoot, CURSOR_HOOKS_RELATIVE_PATH);
18033
- const hookPath = path$1.join(projectRoot, CURSOR_HOOK_RELATIVE_PATH);
18034
- const config = readJsonFile(configPath, {});
18035
- const hooks = { ...config.hooks ?? {} };
18036
- const postToolUseHooks = [...hooks.postToolUse ?? []];
18037
- if (!hasCursorHookCommand(postToolUseHooks)) postToolUseHooks.push({
18038
- command: CURSOR_HOOK_RELATIVE_PATH,
18039
- matcher: CURSOR_HOOK_MATCHER,
18040
- timeout: 120
18041
- });
18042
- hooks.postToolUse = postToolUseHooks;
18043
- writeJsonFile(configPath, {
18044
- ...config,
18045
- version: config.version ?? CURSOR_HOOKS_SCHEMA_VERSION,
18046
- hooks
18047
- });
18048
- writeHookScript(hookPath);
18049
- return [configPath, hookPath];
18044
+ const formatDoctorScriptInstallMessage = (scriptResult) => {
18045
+ const scriptName = scriptResult.scriptName ?? "doctor";
18046
+ if (scriptResult.scriptStatus === "created") return `Added package script: ${scriptName}.`;
18047
+ if (scriptResult.scriptStatus === "existing") return `Package script already exists: ${scriptName}.`;
18048
+ if (scriptResult.scriptReason === "script-names-taken") return "Skipped package script: doctor and react-doctor are already taken.";
18049
+ if (scriptResult.scriptReason === "doctor-script-taken") return "Skipped package script: doctor and react-doctor scripts already exist.";
18050
+ if (scriptResult.scriptReason === "invalid-scripts") return "Skipped package script: scripts field is not an object.";
18051
+ return "Skipped package script: package.json missing or invalid.";
18050
18052
  };
18051
- const buildAgentHookScript = () => [
18052
- "#!/bin/sh",
18053
- "set -u",
18054
- "",
18055
- "input_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook.XXXXXX\")",
18056
- "output_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook-output.XXXXXX\")",
18057
- "trap 'rm -f \"$input_file\" \"$output_file\"' EXIT",
18058
- "cat > \"$input_file\"",
18059
- "",
18060
- "script_dir=$(CDPATH= cd \"$(dirname \"$0\")\" && pwd)",
18061
- "project_root=${CLAUDE_PROJECT_DIR:-}",
18062
- "if [ -z \"$project_root\" ]; then",
18063
- " project_root=$(CDPATH= cd \"$script_dir/../..\" && pwd)",
18064
- "fi",
18065
- "if ! cd \"$project_root\"; then",
18066
- " exit 0",
18067
- "fi",
18068
- "",
18069
- "should_scan() {",
18070
- " if ! command -v node >/dev/null 2>&1; then",
18071
- " return 0",
18072
- " fi",
18073
- "",
18074
- " node - \"$input_file\" <<'NODE'",
18075
- "const fs = require('node:fs');",
18076
- "const inputPath = process.argv[2];",
18077
- "const editToolNames = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'ApplyPatch']);",
18078
- "try {",
18079
- " const input = JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18080
- " const eventName = input.hook_event_name || input.eventName || input.event_name;",
18081
- " if (eventName === 'PostToolBatch') {",
18082
- " const toolCalls = Array.isArray(input.tool_calls) ? input.tool_calls : [];",
18083
- " process.exit(toolCalls.some((toolCall) => editToolNames.has(toolCall.tool_name)) ? 0 : 10);",
18084
- " }",
18085
- " const toolName = input.tool_name || input.toolName || input.tool;",
18086
- " process.exit(!toolName || editToolNames.has(toolName) ? 0 : 10);",
18087
- "} catch {",
18088
- " process.exit(0);",
18089
- "}",
18090
- "NODE",
18091
- "}",
18092
- "",
18093
- "run_react_doctor() {",
18094
- " if [ -x ./node_modules/.bin/react-doctor ]; then",
18095
- " ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
18096
- " return",
18097
- " fi",
18098
- "",
18099
- " if command -v react-doctor >/dev/null 2>&1; then",
18100
- " react-doctor --verbose --diff --blocking warning --no-score",
18101
- " return",
18102
- " fi",
18103
- "",
18104
- " if command -v pnpm >/dev/null 2>&1; then",
18105
- " pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
18106
- " return",
18107
- " fi",
18108
- "",
18109
- " if command -v npx >/dev/null 2>&1; then",
18110
- " npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
18111
- " return",
18112
- " fi",
18113
- "",
18114
- " printf '%s\\n' 'react-doctor: command not found; skipping agent hook scan.'",
18115
- " return 0",
18116
- "}",
18117
- "",
18118
- "if ! should_scan; then",
18119
- " exit 0",
18120
- "fi",
18121
- "",
18122
- "if run_react_doctor > \"$output_file\" 2>&1; then",
18123
- " exit 0",
18124
- "fi",
18125
- "",
18126
- "node - \"$input_file\" \"$output_file\" <<'NODE'",
18127
- "const fs = require('node:fs');",
18128
- "const inputPath = process.argv[2];",
18129
- "const outputPath = process.argv[3];",
18130
- "const readInput = () => {",
18131
- " try {",
18132
- " return JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18133
- " } catch {",
18134
- " return {};",
18135
- " }",
18136
- "};",
18137
- "const input = readInput();",
18138
- "const scanOutput = fs.readFileSync(outputPath, 'utf8').trim();",
18139
- "if (!scanOutput) process.exit(0);",
18140
- "const message = `React Doctor found issues in the changed files. Review this output and fix the regressions before finishing. For confirmed issues that cannot be fixed now, create GitHub issues with the rule, file/line, confidence, impact, and proposed fix.\\n\\n${scanOutput}`;",
18141
- "if (input.hook_event_name === 'PostToolBatch') {",
18142
- " console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolBatch', additionalContext: message } }));",
18143
- "} else {",
18144
- " console.log(JSON.stringify({ additional_context: message }));",
18145
- "}",
18146
- "NODE",
18147
- ""
18148
- ].join("\n");
18149
- const installReactDoctorAgentHooks = (options) => {
18150
- const installedAgents = [];
18151
- const files = [];
18152
- const requestedAgents = options.agents.filter(isSupportedAgent);
18153
- for (const agent of requestedAgents) {
18154
- if (agent === CLAUDE_AGENT) {
18155
- files.push(...installClaudeHook(options.projectRoot));
18156
- installedAgents.push(agent);
18157
- }
18158
- if (agent === CURSOR_AGENT) {
18159
- files.push(...installCursorHook(options.projectRoot));
18160
- installedAgents.push(agent);
18161
- }
18053
+ const installReactDoctorScriptStep = (projectRoot) => {
18054
+ const scriptSpinner = spinner("Installing React Doctor package script...").start();
18055
+ try {
18056
+ const scriptResult = installDoctorScript({ projectRoot });
18057
+ scriptSpinner.succeed(formatDoctorScriptInstallMessage(scriptResult));
18058
+ } catch (error) {
18059
+ scriptSpinner.fail("Failed to install React Doctor package script.");
18060
+ throw error;
18162
18061
  }
18163
- return {
18164
- installedAgents,
18165
- files
18166
- };
18167
18062
  };
18168
18063
  //#endregion
18169
18064
  //#region src/cli/utils/install-github-workflow.ts
@@ -18176,37 +18071,20 @@ const buildWorkflowContent = () => `# React Doctor — finds security, performan
18176
18071
  name: React Doctor
18177
18072
 
18178
18073
  on:
18074
+ # Scans the PR's changed files and posts a sticky summary comment listing only the new issues introduced relative to the merge base of the target branch.
18179
18075
  pull_request:
18180
18076
  types: [opened, synchronize, reopened, ready_for_review]
18181
- # Scans \`main\` on every push so you get a health-score trend on the
18182
- # default branch — useful for tracking the overall number commit-by-commit
18183
- # and catching regressions that slipped past PR review. PR-specific steps
18184
- # (the sticky summary comment) are skipped automatically on \`push\` events.
18185
- # Comment this block out if you only want PR-time scans.
18077
+ # Scans \`main\` on every push to track the health-score trend and catch regressions that slipped past PR review.
18186
18078
  push:
18187
18079
  branches: [main]
18188
18080
 
18189
18081
  permissions:
18190
- # \`actions/checkout\` needs this to read the repo source.
18191
18082
  contents: read
18192
- # Two uses: (1) reads the PR's changed-file list so the scan only checks
18193
- # what the PR touched (faster, scoped to the diff), and (2) posts/updates
18194
- # the sticky React Doctor summary comment on the PR. Downgrade \`write\` to
18195
- # \`read\` to keep the changed-file scan but disable comment posting.
18196
18083
  pull-requests: write
18197
- # The sticky-comment step uses GitHub's \`issues.createComment\` /
18198
- # \`issues.updateComment\` endpoints — those are the same APIs that back PR
18199
- # comments (PRs are issues under the hood). Not exercised on \`push\`
18200
- # events, so safe to drop if you only run on \`main\`.
18201
18084
  issues: write
18202
- # Lets the action publish a commit status with the score + error/warning
18203
- # counts (links to the run). This is how a \`push\` to \`main\` surfaces its
18204
- # result, since the PR comment is skipped off pull requests. Drop it to
18205
- # disable the status (or set \`commit-status: false\` below).
18206
18085
  statuses: write
18207
18086
 
18208
- # Cancels any in-flight scan for the same PR (or branch, on push) the moment
18209
- # a new commit arrives, so reviewers only ever see the latest run.
18087
+ # Cancels any in-flight scan for the same PR (or branch, on push) the moment a new commit arrives, so reviewers only ever see the latest run.
18210
18088
  concurrency:
18211
18089
  group: react-doctor-\${{ github.event.pull_request.number || github.ref }}
18212
18090
  cancel-in-progress: true
@@ -18273,1074 +18151,1359 @@ const installReactDoctorWorkflow = (projectRoot) => {
18273
18151
  };
18274
18152
  }
18275
18153
  };
18276
- //#endregion
18277
- //#region src/cli/utils/report-workflow-result.ts
18278
- const reportWorkflowResult = (workflowSpinner, result, projectRoot) => {
18279
- if (result.status === "failed") {
18280
- workflowSpinner.fail("Couldn't write the GitHub Actions workflow.");
18281
- return false;
18282
- }
18283
- if (result.status === "exists") {
18284
- workflowSpinner.succeed("GitHub Actions workflow already configured.");
18285
- return false;
18154
+ const upgradeReactDoctorWorkflowInPlace = (projectRoot) => {
18155
+ const workflow = readReactDoctorWorkflow(projectRoot);
18156
+ if (!workflow) return {
18157
+ status: "not-needed",
18158
+ workflowPath: getReactDoctorWorkflowPath(projectRoot)
18159
+ };
18160
+ const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
18161
+ if (!changed) return {
18162
+ status: "not-needed",
18163
+ workflowPath: workflow.workflowPath
18164
+ };
18165
+ try {
18166
+ fs$1.writeFileSync(workflow.workflowPath, content);
18167
+ return {
18168
+ status: "upgraded",
18169
+ workflowPath: workflow.workflowPath
18170
+ };
18171
+ } catch {
18172
+ return {
18173
+ status: "failed",
18174
+ workflowPath: workflow.workflowPath
18175
+ };
18286
18176
  }
18287
- workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18288
- recordCount(METRIC.installWorkflow, 1);
18289
- return true;
18290
18177
  };
18291
18178
  //#endregion
18292
- //#region src/cli/utils/install-git-hook-file.ts
18293
- const REACT_DOCTOR_BLOCK_START = "# react-doctor hook start";
18294
- const REACT_DOCTOR_BLOCK_END = "# react-doctor hook end";
18295
- const REACT_DOCTOR_BLOCK_PATTERN = new RegExp(`(?:${REACT_DOCTOR_BLOCK_START}[\\s\\S]*?${REACT_DOCTOR_BLOCK_END}\\n?|# react-doctor hook launcher start[\\s\\S]*?# react-doctor hook launcher end\\n?)`);
18296
- const SHEBANG = "#!/bin/sh";
18297
- const SHEBANG_PREFIX = "#!";
18298
- const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
18299
- const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
18300
- const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
18301
- const buildReactDoctorHookBlock = () => [
18302
- REACT_DOCTOR_BLOCK_START,
18303
- "react_doctor_scan_staged_files() {",
18304
- ` if [ -x "${LOCAL_REACT_DOCTOR_BIN}" ]; then`,
18305
- ` "${LOCAL_REACT_DOCTOR_BIN}" ${REACT_DOCTOR_COMMAND.replace("react-doctor ", "")}`,
18306
- " return",
18307
- " fi",
18308
- "",
18309
- " if command -v react-doctor >/dev/null 2>&1; then",
18310
- ` ${REACT_DOCTOR_COMMAND}`,
18311
- " return",
18312
- " fi",
18313
- "",
18314
- " if command -v pnpm >/dev/null 2>&1; then",
18315
- ` ${PNPM_REACT_DOCTOR_COMMAND}`,
18316
- " return",
18317
- " fi",
18318
- "",
18319
- " if command -v npx >/dev/null 2>&1; then",
18320
- ` ${NPX_REACT_DOCTOR_COMMAND}`,
18321
- " return",
18322
- " fi",
18323
- "",
18324
- " printf '%s\\n' \"react-doctor: command not found; skipping staged scan.\"",
18325
- "}",
18326
- "",
18327
- "react_doctor_output=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-hook.XXXXXX\")",
18328
- "if react_doctor_scan_staged_files > \"$react_doctor_output\" 2>&1; then",
18329
- " rm -f \"$react_doctor_output\"",
18330
- "else",
18331
- " rm -f \"$react_doctor_output\"",
18332
- ` printf '%s\\n' "React Doctor found staged regressions." "Run ${REACT_DOCTOR_COMMAND} to inspect." "Want them fixed? Ask your agent to run that command and resolve the findings." >&2`,
18333
- "fi",
18334
- REACT_DOCTOR_BLOCK_END
18335
- ].join("\n");
18336
- const mergeHookContent = (existingContent) => {
18337
- const hookBlock = `${buildReactDoctorHookBlock()}\n`;
18338
- if (REACT_DOCTOR_BLOCK_PATTERN.test(existingContent)) return ensureTrailingNewline(existingContent.replace(REACT_DOCTOR_BLOCK_PATTERN, hookBlock));
18339
- if (existingContent.length === 0) return `${SHEBANG}\n\n${hookBlock}`;
18340
- const normalizedExistingContent = ensureTrailingNewline(existingContent);
18341
- if (normalizedExistingContent.startsWith(SHEBANG_PREFIX)) {
18342
- const [shebangLine, ...remainingLines] = normalizedExistingContent.split("\n");
18343
- return [
18344
- shebangLine,
18345
- "",
18346
- hookBlock.trimEnd(),
18347
- ...remainingLines
18348
- ].join("\n");
18179
+ //#region src/cli/utils/hash-project-root.ts
18180
+ const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
18181
+ //#endregion
18182
+ //#region src/cli/utils/action-upgrade-prompt.ts
18183
+ const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
18184
+ const getActionUpgradeStore = (options = {}) => new Conf({
18185
+ projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
18186
+ cwd: options.cwd
18187
+ });
18188
+ const hasHandledActionUpgrade = (projectRoot, storeOptions = {}) => {
18189
+ try {
18190
+ const upgrades = getActionUpgradeStore(storeOptions).get("actionUpgrades", {});
18191
+ return Boolean(upgrades[hashProjectRoot(projectRoot)]);
18192
+ } catch {
18193
+ return true;
18349
18194
  }
18350
- return `${SHEBANG}\n\n${hookBlock}${normalizedExistingContent}`;
18351
18195
  };
18352
- const removeLegacyManagedRunner = (projectRoot) => {
18353
- const runnerPath = path$1.join(projectRoot, LEGACY_HOOK_RUNNER_RELATIVE_PATH);
18354
- fs$1.rmSync(runnerPath, { force: true });
18355
- for (const directory of [path$1.dirname(runnerPath), path$1.join(projectRoot, ".react-doctor")]) try {
18356
- fs$1.rmdirSync(directory);
18357
- } catch {}
18196
+ const recordActionUpgradeDecision = (projectRoot, outcome, storeOptions = {}) => {
18197
+ try {
18198
+ const store = getActionUpgradeStore(storeOptions);
18199
+ const upgrades = store.get("actionUpgrades", {});
18200
+ store.set("actionUpgrades", {
18201
+ ...upgrades,
18202
+ [hashProjectRoot(projectRoot)]: {
18203
+ rootDirectory: path$1.resolve(projectRoot),
18204
+ outcome,
18205
+ at: (/* @__PURE__ */ new Date()).toISOString()
18206
+ }
18207
+ });
18208
+ return true;
18209
+ } catch {
18210
+ return false;
18211
+ }
18358
18212
  };
18359
- const installDirectGitHook = (options) => {
18360
- const didHookExist = fs$1.existsSync(options.hookPath);
18361
- const nextContent = mergeHookContent(didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "");
18362
- if (options.hooksPathConfig !== void 0) runGit(options.projectRoot, [
18363
- "config",
18364
- "core.hooksPath",
18365
- options.hooksPathConfig
18366
- ]);
18367
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18368
- fs$1.writeFileSync(options.hookPath, nextContent);
18369
- fs$1.chmodSync(options.hookPath, 493);
18370
- removeLegacyManagedRunner(options.projectRoot);
18213
+ //#endregion
18214
+ //#region src/cli/utils/open-url.ts
18215
+ const resolveOpenCommand = (url) => {
18216
+ if (process$1.platform === "darwin") return {
18217
+ command: "open",
18218
+ args: [url]
18219
+ };
18220
+ if (process$1.platform === "win32") return {
18221
+ command: "cmd",
18222
+ args: [
18223
+ "/c",
18224
+ "start",
18225
+ "",
18226
+ url
18227
+ ]
18228
+ };
18371
18229
  return {
18372
- hookPath: options.hookPath,
18373
- kind: options.kind ?? "git",
18374
- status: didHookExist ? "updated" : "created"
18230
+ command: "xdg-open",
18231
+ args: [url]
18375
18232
  };
18376
18233
  };
18234
+ const openUrl = (url) => {
18235
+ try {
18236
+ const { command, args } = resolveOpenCommand(url);
18237
+ const child = spawn(command, args, {
18238
+ detached: true,
18239
+ stdio: "ignore"
18240
+ });
18241
+ child.on("error", () => {});
18242
+ child.unref();
18243
+ return true;
18244
+ } catch {
18245
+ return false;
18246
+ }
18247
+ };
18377
18248
  //#endregion
18378
- //#region src/cli/utils/install-git-hook-config-managers.ts
18379
- const appendStringCommand = (existingCommand) => {
18380
- const existingCommandText = typeof existingCommand === "string" ? existingCommand : Array.isArray(existingCommand) ? existingCommand.filter((entry) => typeof entry === "string").join("\n") : "";
18381
- return existingCommandText.includes("react-doctor --staged --blocking warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
18249
+ //#region src/cli/utils/ask-add-to-github-actions.ts
18250
+ const CI_YES_CHOICE = "ci-yes";
18251
+ const CI_LEARN_MORE_CHOICE = "ci-learn-more";
18252
+ const CI_NO_CHOICE = "ci-no";
18253
+ const SGR_BOLD_OFF = "\x1B[22m";
18254
+ const ciQuestionMessage = [
18255
+ "Add React Doctor to GitHub Actions?",
18256
+ `${SGR_BOLD_OFF} ${highlighter.dim("Scan every pull request to prevent new React issues while you fix the backlog.")}`,
18257
+ `${SGR_BOLD_OFF} ${highlighter.dim(`Used by teams at ${CI_TRUST_COMPANIES}.`)}`
18258
+ ].join("\n");
18259
+ const askAddToGitHubActions = async (prompt = prompts) => {
18260
+ while (true) {
18261
+ const { ciChoice } = await prompt({
18262
+ type: "select",
18263
+ name: "ciChoice",
18264
+ message: ciQuestionMessage,
18265
+ hint: " ",
18266
+ choices: [
18267
+ {
18268
+ title: "Yes",
18269
+ description: "Adds the workflow file and a doctor package script",
18270
+ value: CI_YES_CHOICE
18271
+ },
18272
+ {
18273
+ title: "Learn more",
18274
+ description: "Opens the docs page in your browser",
18275
+ value: CI_LEARN_MORE_CHOICE
18276
+ },
18277
+ {
18278
+ title: "No",
18279
+ description: "Skip for now",
18280
+ value: CI_NO_CHOICE
18281
+ }
18282
+ ],
18283
+ initial: 0
18284
+ }, { onCancel: () => true });
18285
+ if (ciChoice === void 0) return "cancel";
18286
+ if (ciChoice === CI_YES_CHOICE) return "yes";
18287
+ if (ciChoice === CI_NO_CHOICE) return "no";
18288
+ const opened = openUrl(GITHUB_ACTIONS_SETUP_URL);
18289
+ cliLogger.log(opened ? `Opened ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} in your browser.` : `Visit ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} to learn more.`);
18290
+ cliLogger.break();
18291
+ }
18382
18292
  };
18383
- const appendArrayCommand = (existingCommands) => {
18384
- const commands = Array.isArray(existingCommands) ? existingCommands.filter((entry) => typeof entry === "string") : typeof existingCommands === "string" ? [existingCommands] : [];
18385
- return commands.some((command) => command.includes("react-doctor --staged --blocking warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
18293
+ //#endregion
18294
+ //#region src/cli/utils/ask-upgrade-action-version.ts
18295
+ const UPGRADE_YES_CHOICE = "upgrade-yes";
18296
+ const UPGRADE_NO_CHOICE = "upgrade-no";
18297
+ const askUpgradeActionVersion = async (prompt = prompts) => {
18298
+ const { upgradeChoice } = await prompt({
18299
+ type: "select",
18300
+ name: "upgradeChoice",
18301
+ message: "A new major of the React Doctor Action (v2) is out. Upgrade this repo's workflow?",
18302
+ hint: " ",
18303
+ choices: [{
18304
+ title: "Yes (recommended)",
18305
+ description: "Bump the workflow to millionco/react-doctor@v2",
18306
+ value: UPGRADE_YES_CHOICE
18307
+ }, {
18308
+ title: "No, thanks",
18309
+ description: "Keep @v1 — won't ask again for this repo",
18310
+ value: UPGRADE_NO_CHOICE
18311
+ }],
18312
+ initial: 0
18313
+ }, { onCancel: () => true });
18314
+ if (upgradeChoice === void 0) return "cancel";
18315
+ return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
18386
18316
  };
18387
- const installPackageJsonHook = (options, strategy) => {
18388
- const packageJsonPath = getPackageJsonPath(options.projectRoot);
18389
- const didHookExist = fs$1.existsSync(packageJsonPath);
18390
- const packageJson = readPackageJson(options.projectRoot);
18391
- const nextPackageJson = isRecord(packageJson) ? { ...packageJson } : {};
18392
- const parentKeys = strategy.path.slice(0, -1);
18393
- const leafKey = strategy.path[strategy.path.length - 1];
18394
- let parent = nextPackageJson;
18395
- for (const key of parentKeys) {
18396
- const existing = parent[key];
18397
- const cloned = isRecord(existing) ? { ...existing } : {};
18398
- parent[key] = cloned;
18399
- parent = cloned;
18317
+ //#endregion
18318
+ //#region src/cli/utils/open-workflow-pull-request.ts
18319
+ const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
18320
+ const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
18321
+ const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
18322
+ const DEFAULT_PR_BODY = `Adds a [React Doctor](https://www.react.doctor) scan to every pull request and every push to the default branch. The workflow file is documented inline.
18323
+
18324
+ Docs: https://www.react.doctor/ci`;
18325
+ const execFileAsync$1 = promisify(execFile);
18326
+ const run = async (command, args, cwd) => {
18327
+ try {
18328
+ const { stdout, stderr } = await execFileAsync$1(command, [...args], {
18329
+ cwd,
18330
+ encoding: "utf8"
18331
+ });
18332
+ return {
18333
+ success: true,
18334
+ stdout: stdout.trim(),
18335
+ stderr: stderr.trim()
18336
+ };
18337
+ } catch (error) {
18338
+ const failure = error;
18339
+ return {
18340
+ success: false,
18341
+ stdout: (failure.stdout ?? "").trim(),
18342
+ stderr: (failure.stderr ?? "").trim()
18343
+ };
18400
18344
  }
18401
- parent[leafKey] = strategy.leafShape === "array" ? appendArrayCommand(parent[leafKey]) : appendStringCommand(parent[leafKey]);
18402
- writeJsonFile$1(packageJsonPath, nextPackageJson);
18403
- removeLegacyManagedRunner(options.projectRoot);
18404
- return {
18405
- hookPath: packageJsonPath,
18406
- kind: strategy.kind,
18407
- status: didHookExist ? "updated" : "created"
18408
- };
18409
18345
  };
18410
- const installSimpleGitHooks = (options) => installPackageJsonHook(options, {
18411
- kind: "simple-git-hooks",
18412
- path: ["simple-git-hooks", "pre-commit"],
18413
- leafShape: "string"
18414
- });
18415
- const installGhooks = (options) => installPackageJsonHook(options, {
18416
- kind: "ghooks",
18417
- path: [
18418
- "config",
18419
- "ghooks",
18420
- "pre-commit"
18421
- ],
18422
- leafShape: "string"
18423
- });
18424
- const installPreCommitNpm = (options) => installPackageJsonHook(options, {
18425
- kind: "pre-commit-npm",
18426
- path: ["pre-commit"],
18427
- leafShape: "array"
18428
- });
18429
- const installPrettyQuick = (options) => installPackageJsonHook(options, {
18430
- kind: "pretty-quick",
18431
- path: ["gitHooks", "pre-commit"],
18432
- leafShape: "string"
18433
- });
18434
- const installYorkie = (options) => installPackageJsonHook(options, {
18435
- kind: "yorkie",
18436
- path: ["gitHooks", "pre-commit"],
18437
- leafShape: "string"
18438
- });
18439
- const installGitHooksJs = (options) => installPackageJsonHook(options, {
18440
- kind: "git-hooks-js",
18441
- path: ["git-hooks", "pre-commit"],
18442
- leafShape: "string"
18443
- });
18444
- const appendIndentedBlockToTopLevelSection = (content, sectionName, block) => {
18445
- const normalizedContent = ensureTrailingNewline(content);
18446
- const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(normalizedContent);
18447
- if (match === null) return ensureTrailingNewline([
18448
- normalizedContent.trimEnd(),
18449
- "",
18450
- `${sectionName}:`,
18451
- ...block,
18452
- ""
18453
- ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18454
- const sectionStartIndex = match.index;
18455
- const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18456
- nextSectionPattern.lastIndex = sectionStartIndex + match[0].length;
18457
- let nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18458
- while (nextSectionMatch !== null && nextSectionMatch.index === sectionStartIndex) nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18459
- const insertIndex = nextSectionMatch?.index ?? normalizedContent.length;
18460
- const prefix = normalizedContent.slice(0, insertIndex).trimEnd();
18461
- const suffix = normalizedContent.slice(insertIndex);
18462
- return ensureTrailingNewline([
18463
- prefix,
18464
- ...block,
18465
- suffix.trimStart()
18466
- ].join("\n"));
18467
- };
18468
- const findTopLevelSectionRange = (content, sectionName) => {
18469
- const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(content);
18470
- if (match === null) return null;
18471
- const headerLineEndIndex = content.indexOf("\n", match.index);
18472
- const headerEndIndex = headerLineEndIndex === -1 ? match.index + match[0].length : headerLineEndIndex + 1;
18473
- const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18474
- nextSectionPattern.lastIndex = headerEndIndex;
18475
- return {
18476
- headerEndIndex,
18477
- contentEndIndex: nextSectionPattern.exec(content)?.index ?? content.length
18478
- };
18479
- };
18480
- const appendLefthookCommand = (content) => {
18481
- const normalizedContent = ensureTrailingNewline(content);
18482
- const sectionRange = findTopLevelSectionRange(normalizedContent, "pre-commit");
18483
- const reactDoctorCommandBlock = [
18484
- " react-doctor:",
18485
- ` run: ${NON_BLOCKING_REACT_DOCTOR_COMMAND}`,
18486
- ""
18487
- ];
18488
- if (sectionRange === null) return ensureTrailingNewline([
18489
- normalizedContent.trimEnd(),
18490
- "",
18491
- "pre-commit:",
18492
- " commands:",
18493
- ...reactDoctorCommandBlock
18494
- ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18495
- const sectionContent = normalizedContent.slice(sectionRange.headerEndIndex, sectionRange.contentEndIndex);
18496
- const commandsMatch = /^ commands:\s*$/m.exec(sectionContent);
18497
- const insertIndex = commandsMatch === null ? sectionRange.headerEndIndex : sectionRange.headerEndIndex + sectionContent.indexOf(commandsMatch[0]) + commandsMatch[0].length + 1;
18498
- const insertBlock = commandsMatch === null ? [" commands:", ...reactDoctorCommandBlock].join("\n") : reactDoctorCommandBlock.join("\n");
18499
- return ensureTrailingNewline(`${normalizedContent.slice(0, insertIndex)}${insertBlock}${normalizedContent.slice(insertIndex)}`);
18500
- };
18501
- const installLefthook = (options) => {
18502
- const didHookExist = fs$1.existsSync(options.hookPath);
18503
- const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18504
- if (!existingContent.includes("react-doctor")) {
18505
- const nextContent = appendLefthookCommand(existingContent);
18506
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18507
- fs$1.writeFileSync(options.hookPath, nextContent);
18508
- }
18509
- removeLegacyManagedRunner(options.projectRoot);
18510
- return {
18511
- hookPath: options.hookPath,
18512
- kind: "lefthook",
18513
- status: didHookExist ? "updated" : "created"
18514
- };
18515
- };
18516
- const installPreCommit = (options) => {
18517
- const didHookExist = fs$1.existsSync(options.hookPath);
18518
- const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18519
- if (!existingContent.includes("id: react-doctor")) {
18520
- const hasReposKey = /^repos:\s*$/m.test(existingContent);
18521
- const localHookBlock = [
18522
- " - repo: local",
18523
- " hooks:",
18524
- " - id: react-doctor",
18525
- " name: react-doctor",
18526
- ` entry: sh -c '${NON_BLOCKING_REACT_DOCTOR_COMMAND}'`,
18527
- " language: system",
18528
- " pass_filenames: false",
18529
- ""
18530
- ].join("\n");
18531
- const nextContent = hasReposKey ? `${ensureTrailingNewline(existingContent)}${localHookBlock}` : `repos:\n${localHookBlock}`;
18532
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18533
- fs$1.writeFileSync(options.hookPath, nextContent);
18534
- }
18535
- removeLegacyManagedRunner(options.projectRoot);
18536
- return {
18537
- hookPath: options.hookPath,
18538
- kind: "pre-commit",
18539
- status: didHookExist ? "updated" : "created"
18540
- };
18541
- };
18542
- const installOvercommit = (options) => {
18543
- const didHookExist = fs$1.existsSync(options.hookPath);
18544
- const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18545
- if (!existingContent.includes("ReactDoctor")) {
18546
- const nextContent = appendIndentedBlockToTopLevelSection(existingContent, "PreCommit", [
18547
- " ReactDoctor:",
18548
- " enabled: true",
18549
- ` command: ['sh', '-c', '${NON_BLOCKING_REACT_DOCTOR_COMMAND}']`,
18550
- ""
18551
- ]);
18552
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18553
- fs$1.writeFileSync(options.hookPath, nextContent);
18346
+ const detectDefaultBranch = async (cwd) => {
18347
+ const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
18348
+ if (symRef.success) {
18349
+ const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
18350
+ if (branchMatch) return branchMatch[1];
18554
18351
  }
18555
- removeLegacyManagedRunner(options.projectRoot);
18556
- return {
18557
- hookPath: options.hookPath,
18558
- kind: "overcommit",
18559
- status: didHookExist ? "updated" : "created"
18560
- };
18561
- };
18562
- //#endregion
18563
- //#region src/cli/utils/install-git-hook.ts
18564
- const isHuskyProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".husky")) || packageHasDependency(projectRoot, "husky");
18565
- const isVitePlusProject = (projectRoot) => packageHasDependency(projectRoot, "vite-plus");
18566
- const isSimpleGitHooksProject = (projectRoot) => {
18567
- const packageJson = readPackageJson(projectRoot);
18568
- return isRecord(packageJson) && isRecord(packageJson["simple-git-hooks"]) || packageHasDependency(projectRoot, "simple-git-hooks") || fs$1.existsSync(path$1.join(projectRoot, ".simple-git-hooks.cjs"));
18352
+ if ((await run("git", [
18353
+ "rev-parse",
18354
+ "--verify",
18355
+ "origin/main"
18356
+ ], cwd)).success) return "main";
18357
+ if ((await run("git", [
18358
+ "rev-parse",
18359
+ "--verify",
18360
+ "origin/master"
18361
+ ], cwd)).success) return "master";
18362
+ return null;
18569
18363
  };
18570
- const getLefthookConfigPath = (projectRoot) => {
18571
- for (const fileName of LEFTHOOK_CONFIG_FILES) {
18572
- const filePath = path$1.join(projectRoot, fileName);
18573
- if (fs$1.existsSync(filePath)) return filePath;
18574
- }
18575
- return packageHasDependency(projectRoot, "lefthook") ? path$1.join(projectRoot, LEFTHOOK_CONFIG_FILES[0] ?? "lefthook.yml") : null;
18364
+ const findUniqueBranchName = async (cwd) => {
18365
+ if (!(await run("git", [
18366
+ "rev-parse",
18367
+ "--verify",
18368
+ NEW_BRANCH_PREFIX
18369
+ ], cwd)).success) return NEW_BRANCH_PREFIX;
18370
+ return `${NEW_BRANCH_PREFIX}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:T]/g, "")}`;
18576
18371
  };
18577
- const isPreCommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, PRE_COMMIT_CONFIG_FILE));
18578
- const isOvercommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".overcommit.yml")) || packageHasDependency(projectRoot, "overcommit");
18579
- const isYorkieProject = (projectRoot) => packageHasRecordKey(projectRoot, "gitHooks") || packageHasDependency(projectRoot, "yorkie");
18580
- const isGhooksProject = (projectRoot) => packageHasDependency(projectRoot, "ghooks") || packageHasNestedRecordKey(projectRoot, "config", "ghooks");
18581
- const isGitHooksJsProject = (projectRoot) => packageHasRecordKey(projectRoot, "git-hooks") || packageHasDependency(projectRoot, "git-hooks-js");
18582
- const isPreCommitNpmProject = (projectRoot) => packageHasDependency(projectRoot, "pre-commit");
18583
- const isPrettyQuickProject = (projectRoot) => packageHasDependency(projectRoot, "pretty-quick");
18584
- const detectGitHookTarget = (projectRoot) => {
18585
- if (runGit(projectRoot, ["rev-parse", "--is-inside-work-tree"]) !== "true") return null;
18586
- const topLevel = runGit(projectRoot, ["rev-parse", "--show-toplevel"]) ?? projectRoot;
18587
- const configuredHooksPath = runGit(projectRoot, [
18588
- "config",
18589
- "--path",
18590
- "--get",
18591
- "core.hooksPath"
18592
- ]);
18593
- if (configuredHooksPath !== null && configuredHooksPath.length > 0) return {
18594
- hookPath: path$1.join(resolveGitPath(topLevel, configuredHooksPath), HOOK_FILE_NAME),
18595
- runnerRoot: topLevel,
18596
- kind: "configured"
18597
- };
18598
- if (isHuskyProject(topLevel)) return {
18599
- hookPath: path$1.join(topLevel, HUSKY_HOOKS_PATH, HOOK_FILE_NAME),
18600
- runnerRoot: topLevel,
18601
- kind: "husky",
18602
- hooksPathConfig: HUSKY_HOOKS_PATH
18603
- };
18604
- if (isVitePlusProject(topLevel)) return {
18605
- hookPath: path$1.join(topLevel, VITE_PLUS_HOOKS_PATH, HOOK_FILE_NAME),
18606
- runnerRoot: topLevel,
18607
- kind: "vite-plus",
18608
- hooksPathConfig: VITE_PLUS_HOOKS_PATH
18372
+ const openWorkflowPullRequest = async (params) => {
18373
+ const workflowPath = path$1.resolve(params.workflowPath);
18374
+ const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
18375
+ const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
18376
+ const prBody = params.prBody ?? DEFAULT_PR_BODY;
18377
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18378
+ if (!repoRootProbe.success) return {
18379
+ status: "not-attempted",
18380
+ reason: "not-a-git-repo"
18609
18381
  };
18610
- if (isSimpleGitHooksProject(topLevel)) return {
18611
- hookPath: path$1.join(topLevel, "package.json"),
18612
- runnerRoot: topLevel,
18613
- kind: "simple-git-hooks"
18382
+ const cwd = repoRootProbe.stdout;
18383
+ if (!isCommandAvailable("gh")) return {
18384
+ status: "not-attempted",
18385
+ reason: "gh-not-installed"
18614
18386
  };
18615
- const lefthookConfigPath = getLefthookConfigPath(topLevel);
18616
- if (lefthookConfigPath !== null) return {
18617
- hookPath: lefthookConfigPath,
18618
- runnerRoot: topLevel,
18619
- kind: "lefthook"
18387
+ if (!(await run("gh", ["auth", "status"], cwd)).success) return {
18388
+ status: "not-attempted",
18389
+ reason: "gh-not-authenticated"
18620
18390
  };
18621
- if (isPreCommitProject(topLevel)) return {
18622
- hookPath: path$1.join(topLevel, PRE_COMMIT_CONFIG_FILE),
18623
- runnerRoot: topLevel,
18624
- kind: "pre-commit"
18391
+ const defaultBranch = await detectDefaultBranch(cwd);
18392
+ if (!defaultBranch) return {
18393
+ status: "not-attempted",
18394
+ reason: "no-default-branch"
18625
18395
  };
18626
- if (isOvercommitProject(topLevel)) return {
18627
- hookPath: path$1.join(topLevel, OVERCOMMIT_CONFIG_FILE),
18628
- runnerRoot: topLevel,
18629
- kind: "overcommit"
18396
+ const previousBranchProbe = await run("git", [
18397
+ "rev-parse",
18398
+ "--abbrev-ref",
18399
+ "HEAD"
18400
+ ], cwd);
18401
+ if (!previousBranchProbe.success || previousBranchProbe.stdout === "HEAD") return {
18402
+ status: "not-attempted",
18403
+ reason: "detached-head"
18630
18404
  };
18631
- if (isYorkieProject(topLevel)) return {
18632
- hookPath: getPackageJsonPath(topLevel),
18633
- runnerRoot: topLevel,
18634
- kind: "yorkie"
18635
- };
18636
- if (isGhooksProject(topLevel)) return {
18637
- hookPath: getPackageJsonPath(topLevel),
18638
- runnerRoot: topLevel,
18639
- kind: "ghooks"
18640
- };
18641
- if (isGitHooksJsProject(topLevel)) return {
18642
- hookPath: getPackageJsonPath(topLevel),
18643
- runnerRoot: topLevel,
18644
- kind: "git-hooks-js"
18405
+ const previousBranch = previousBranchProbe.stdout;
18406
+ await run("git", [
18407
+ "fetch",
18408
+ "origin",
18409
+ defaultBranch
18410
+ ], cwd);
18411
+ const newBranch = await findUniqueBranchName(cwd);
18412
+ if (!(await run("git", [
18413
+ "checkout",
18414
+ "-b",
18415
+ newBranch,
18416
+ `origin/${defaultBranch}`
18417
+ ], cwd)).success) return {
18418
+ status: "not-attempted",
18419
+ reason: "checkout-failed"
18645
18420
  };
18646
- if (isPreCommitNpmProject(topLevel)) return {
18647
- hookPath: getPackageJsonPath(topLevel),
18648
- runnerRoot: topLevel,
18649
- kind: "pre-commit-npm"
18421
+ const restoreToPreviousBranch = async (deleteNewBranch) => {
18422
+ await run("git", ["checkout", previousBranch], cwd);
18423
+ if (deleteNewBranch) await run("git", [
18424
+ "branch",
18425
+ "-D",
18426
+ newBranch
18427
+ ], cwd);
18650
18428
  };
18651
- if (isPrettyQuickProject(topLevel)) return {
18652
- hookPath: getPackageJsonPath(topLevel),
18653
- runnerRoot: topLevel,
18654
- kind: "pretty-quick"
18429
+ if (!(await run("git", [
18430
+ "add",
18431
+ "--",
18432
+ path$1.relative(cwd, workflowPath)
18433
+ ], cwd)).success) {
18434
+ await restoreToPreviousBranch(true);
18435
+ return {
18436
+ status: "not-attempted",
18437
+ reason: "git-add-failed"
18438
+ };
18439
+ }
18440
+ if (!(await run("git", [
18441
+ "commit",
18442
+ "-m",
18443
+ commitMessage
18444
+ ], cwd)).success) {
18445
+ await restoreToPreviousBranch(true);
18446
+ return {
18447
+ status: "not-attempted",
18448
+ reason: "git-commit-failed"
18449
+ };
18450
+ }
18451
+ if (!(await run("git", [
18452
+ "push",
18453
+ "-u",
18454
+ "origin",
18455
+ newBranch
18456
+ ], cwd)).success) {
18457
+ await restoreToPreviousBranch(true);
18458
+ return {
18459
+ status: "not-attempted",
18460
+ reason: "git-push-failed"
18461
+ };
18462
+ }
18463
+ const prCreate = await run("gh", [
18464
+ "pr",
18465
+ "create",
18466
+ "--title",
18467
+ prTitle,
18468
+ "--body",
18469
+ prBody,
18470
+ "--base",
18471
+ defaultBranch,
18472
+ "--head",
18473
+ newBranch
18474
+ ], cwd);
18475
+ await restoreToPreviousBranch(false);
18476
+ if (!prCreate.success) return {
18477
+ status: "branch-pushed",
18478
+ branch: newBranch
18655
18479
  };
18656
- const hookPath = runGit(projectRoot, [
18657
- "rev-parse",
18658
- "--git-path",
18659
- HOOK_RELATIVE_PATH
18660
- ]);
18661
- if (hookPath === null || hookPath.length === 0) return null;
18662
18480
  return {
18663
- hookPath: resolveGitPath(projectRoot, hookPath),
18664
- runnerRoot: topLevel,
18665
- kind: "git"
18481
+ status: "pr-opened",
18482
+ url: prCreate.stdout.split(/\r?\n/).filter(Boolean).pop() ?? ""
18666
18483
  };
18667
18484
  };
18668
- const installReactDoctorGitHook = (options) => {
18669
- if (options.kind === "simple-git-hooks") return installSimpleGitHooks(options);
18670
- if (options.kind === "lefthook") return installLefthook(options);
18671
- if (options.kind === "pre-commit") return installPreCommit(options);
18672
- if (options.kind === "overcommit") return installOvercommit(options);
18673
- if (options.kind === "yorkie") return installYorkie(options);
18674
- if (options.kind === "ghooks") return installGhooks(options);
18675
- if (options.kind === "git-hooks-js") return installGitHooksJs(options);
18676
- if (options.kind === "pre-commit-npm") return installPreCommitNpm(options);
18677
- if (options.kind === "pretty-quick") return installPrettyQuick(options);
18678
- return installDirectGitHook(options);
18485
+ const stageWorkflowFile = async (params) => {
18486
+ const workflowPath = path$1.resolve(params.workflowPath);
18487
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18488
+ if (!repoRootProbe.success) return false;
18489
+ return (await run("git", [
18490
+ "add",
18491
+ "--",
18492
+ path$1.relative(repoRootProbe.stdout, workflowPath)
18493
+ ], repoRootProbe.stdout)).success;
18679
18494
  };
18680
18495
  //#endregion
18681
- //#region src/cli/utils/should-skip-prompts.ts
18682
- const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
18496
+ //#region src/cli/utils/report-workflow-result.ts
18497
+ const reportWorkflowResult = (workflowSpinner, result, projectRoot) => {
18498
+ if (result.status === "failed") {
18499
+ workflowSpinner.fail("Couldn't write the GitHub Actions workflow.");
18500
+ return false;
18501
+ }
18502
+ if (result.status === "exists") {
18503
+ workflowSpinner.succeed("GitHub Actions workflow already configured.");
18504
+ return false;
18505
+ }
18506
+ workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18507
+ recordCount(METRIC.installWorkflow, 1);
18508
+ return true;
18509
+ };
18683
18510
  //#endregion
18684
- //#region src/cli/utils/install-react-doctor.ts
18685
- const SETUP_OPTION_GIT_HOOK = "git-hook";
18686
- const SETUP_OPTION_AGENT_HOOKS = "agent-hooks";
18687
- const SETUP_OPTION_WORKFLOW = "workflow";
18688
- const SETUP_OPTION_SKIP = "skip";
18689
- const CONFIG_ONLY_GIT_HOOK_KINDS = new Set([
18690
- "ghooks",
18691
- "git-hooks-js",
18692
- "lefthook",
18693
- "overcommit",
18694
- "pre-commit",
18695
- "pre-commit-npm",
18696
- "pretty-quick",
18697
- "simple-git-hooks",
18698
- "yorkie"
18699
- ]);
18700
- const PACKAGE_MANAGER_LOCKFILES = [
18701
- {
18702
- packageManager: "pnpm",
18703
- fileName: "pnpm-lock.yaml"
18704
- },
18705
- {
18706
- packageManager: "yarn",
18707
- fileName: "yarn.lock"
18708
- },
18709
- {
18710
- packageManager: "bun",
18711
- fileName: "bun.lockb"
18712
- },
18713
- {
18714
- packageManager: "bun",
18715
- fileName: "bun.lock"
18716
- },
18717
- {
18718
- packageManager: "npm",
18719
- fileName: "package-lock.json"
18511
+ //#region src/cli/utils/set-up-github-actions.ts
18512
+ const setUpGitHubActions = async (options) => {
18513
+ const projectRoot = findNearestPackageDirectory(options.rootDirectory) ?? options.rootDirectory;
18514
+ try {
18515
+ installReactDoctorScriptStep(projectRoot);
18516
+ } catch {}
18517
+ const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
18518
+ const workflowResult = installReactDoctorWorkflow(projectRoot);
18519
+ const didCreateWorkflow = reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
18520
+ cliLogger.break();
18521
+ if (workflowResult.status === "failed") {
18522
+ cliLogger.log(` Couldn't set up GitHub Actions automatically. Follow the guide at ${highlighter.info(CI_URL)}`);
18523
+ return false;
18720
18524
  }
18721
- ];
18722
- const findNearestFileDirectory = (startDirectory, fileNames) => {
18723
- let currentDirectory = path$1.resolve(startDirectory);
18724
- while (true) {
18725
- if (fileNames.some((fileName) => fs$1.existsSync(path$1.join(currentDirectory, fileName)))) return currentDirectory;
18726
- const parentDirectory = path$1.dirname(currentDirectory);
18727
- if (parentDirectory === currentDirectory) return null;
18728
- currentDirectory = parentDirectory;
18525
+ if (workflowResult.status === "created") {
18526
+ const pullRequestSpinner = spinner("Opening a pull request for review...").start();
18527
+ const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
18528
+ if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
18529
+ else if (pullRequestResult.status === "branch-pushed") pullRequestSpinner.warn(`Pushed branch ${highlighter.bold(pullRequestResult.branch)} but couldn't open a PR. Open one with: gh pr create --head ${pullRequestResult.branch}`);
18530
+ else {
18531
+ pullRequestSpinner.stop();
18532
+ const didStage = await stageWorkflowFile({ workflowPath: workflowResult.workflowPath });
18533
+ cliLogger.log(didStage ? ` Staged the workflow file. Commit it to start scanning every pull request.` : " React Doctor will now scan every new pull request automatically.");
18534
+ }
18535
+ }
18536
+ cliLogger.log(` Learn more: ${highlighter.info(CI_URL)}`);
18537
+ return didCreateWorkflow;
18538
+ };
18539
+ //#endregion
18540
+ //#region src/cli/utils/install-agent-hooks.ts
18541
+ const CLAUDE_AGENT = "claude-code";
18542
+ const CURSOR_AGENT = "cursor";
18543
+ const CLAUDE_SETTINGS_RELATIVE_PATH = ".claude/settings.json";
18544
+ const CLAUDE_HOOK_RELATIVE_PATH = ".claude/hooks/react-doctor.sh";
18545
+ const CLAUDE_HOOK_COMMAND = "sh \"$CLAUDE_PROJECT_DIR/.claude/hooks/react-doctor.sh\"";
18546
+ const CURSOR_HOOKS_RELATIVE_PATH = ".cursor/hooks.json";
18547
+ const CURSOR_HOOK_RELATIVE_PATH = ".cursor/hooks/react-doctor.sh";
18548
+ const CURSOR_HOOK_MATCHER = "Write|Edit|MultiEdit|ApplyPatch";
18549
+ const CURSOR_HOOKS_SCHEMA_VERSION = 1;
18550
+ const JSON_INDENT_SPACES$1 = 2;
18551
+ const isSupportedAgent = (agent) => agent === CLAUDE_AGENT || agent === CURSOR_AGENT;
18552
+ const readJsonFile = (filePath, fallback) => {
18553
+ if (!fs$1.existsSync(filePath)) return fallback;
18554
+ const content = fs$1.readFileSync(filePath, "utf8").trim();
18555
+ if (content.length === 0) return fallback;
18556
+ return JSON.parse(content);
18557
+ };
18558
+ const writeJsonFile = (filePath, value) => {
18559
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18560
+ fs$1.writeFileSync(filePath, `${JSON.stringify(value, null, JSON_INDENT_SPACES$1)}\n`);
18561
+ };
18562
+ const writeHookScript = (filePath) => {
18563
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18564
+ fs$1.writeFileSync(filePath, buildAgentHookScript());
18565
+ fs$1.chmodSync(filePath, 493);
18566
+ };
18567
+ const hasClaudeHookCommand = (groups) => groups.some((group) => (group.hooks ?? []).some((hook) => hook.command === CLAUDE_HOOK_COMMAND));
18568
+ const installClaudeHook = (projectRoot) => {
18569
+ const settingsPath = path$1.join(projectRoot, CLAUDE_SETTINGS_RELATIVE_PATH);
18570
+ const hookPath = path$1.join(projectRoot, CLAUDE_HOOK_RELATIVE_PATH);
18571
+ const settings = readJsonFile(settingsPath, {});
18572
+ const hooks = { ...settings.hooks ?? {} };
18573
+ const postToolBatchHooks = [...hooks.PostToolBatch ?? []];
18574
+ if (!hasClaudeHookCommand(postToolBatchHooks)) postToolBatchHooks.push({ hooks: [{
18575
+ type: "command",
18576
+ command: CLAUDE_HOOK_COMMAND
18577
+ }] });
18578
+ hooks.PostToolBatch = postToolBatchHooks;
18579
+ writeJsonFile(settingsPath, {
18580
+ ...settings,
18581
+ hooks
18582
+ });
18583
+ writeHookScript(hookPath);
18584
+ return [settingsPath, hookPath];
18585
+ };
18586
+ const hasCursorHookCommand = (handlers) => handlers.some((handler) => handler.command === CURSOR_HOOK_RELATIVE_PATH);
18587
+ const installCursorHook = (projectRoot) => {
18588
+ const configPath = path$1.join(projectRoot, CURSOR_HOOKS_RELATIVE_PATH);
18589
+ const hookPath = path$1.join(projectRoot, CURSOR_HOOK_RELATIVE_PATH);
18590
+ const config = readJsonFile(configPath, {});
18591
+ const hooks = { ...config.hooks ?? {} };
18592
+ const postToolUseHooks = [...hooks.postToolUse ?? []];
18593
+ if (!hasCursorHookCommand(postToolUseHooks)) postToolUseHooks.push({
18594
+ command: CURSOR_HOOK_RELATIVE_PATH,
18595
+ matcher: CURSOR_HOOK_MATCHER,
18596
+ timeout: 120
18597
+ });
18598
+ hooks.postToolUse = postToolUseHooks;
18599
+ writeJsonFile(configPath, {
18600
+ ...config,
18601
+ version: config.version ?? CURSOR_HOOKS_SCHEMA_VERSION,
18602
+ hooks
18603
+ });
18604
+ writeHookScript(hookPath);
18605
+ return [configPath, hookPath];
18606
+ };
18607
+ const buildAgentHookScript = () => [
18608
+ "#!/bin/sh",
18609
+ "set -u",
18610
+ "",
18611
+ "input_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook.XXXXXX\")",
18612
+ "output_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook-output.XXXXXX\")",
18613
+ "trap 'rm -f \"$input_file\" \"$output_file\"' EXIT",
18614
+ "cat > \"$input_file\"",
18615
+ "",
18616
+ "script_dir=$(CDPATH= cd \"$(dirname \"$0\")\" && pwd)",
18617
+ "project_root=${CLAUDE_PROJECT_DIR:-}",
18618
+ "if [ -z \"$project_root\" ]; then",
18619
+ " project_root=$(CDPATH= cd \"$script_dir/../..\" && pwd)",
18620
+ "fi",
18621
+ "if ! cd \"$project_root\"; then",
18622
+ " exit 0",
18623
+ "fi",
18624
+ "",
18625
+ "should_scan() {",
18626
+ " if ! command -v node >/dev/null 2>&1; then",
18627
+ " return 0",
18628
+ " fi",
18629
+ "",
18630
+ " node - \"$input_file\" <<'NODE'",
18631
+ "const fs = require('node:fs');",
18632
+ "const inputPath = process.argv[2];",
18633
+ "const editToolNames = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'ApplyPatch']);",
18634
+ "try {",
18635
+ " const input = JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18636
+ " const eventName = input.hook_event_name || input.eventName || input.event_name;",
18637
+ " if (eventName === 'PostToolBatch') {",
18638
+ " const toolCalls = Array.isArray(input.tool_calls) ? input.tool_calls : [];",
18639
+ " process.exit(toolCalls.some((toolCall) => editToolNames.has(toolCall.tool_name)) ? 0 : 10);",
18640
+ " }",
18641
+ " const toolName = input.tool_name || input.toolName || input.tool;",
18642
+ " process.exit(!toolName || editToolNames.has(toolName) ? 0 : 10);",
18643
+ "} catch {",
18644
+ " process.exit(0);",
18645
+ "}",
18646
+ "NODE",
18647
+ "}",
18648
+ "",
18649
+ "run_react_doctor() {",
18650
+ " if [ -x ./node_modules/.bin/react-doctor ]; then",
18651
+ " ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
18652
+ " return",
18653
+ " fi",
18654
+ "",
18655
+ " if command -v react-doctor >/dev/null 2>&1; then",
18656
+ " react-doctor --verbose --diff --blocking warning --no-score",
18657
+ " return",
18658
+ " fi",
18659
+ "",
18660
+ " if command -v pnpm >/dev/null 2>&1; then",
18661
+ " pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
18662
+ " return",
18663
+ " fi",
18664
+ "",
18665
+ " if command -v npx >/dev/null 2>&1; then",
18666
+ " npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
18667
+ " return",
18668
+ " fi",
18669
+ "",
18670
+ " printf '%s\\n' 'react-doctor: command not found; skipping agent hook scan.'",
18671
+ " return 0",
18672
+ "}",
18673
+ "",
18674
+ "if ! should_scan; then",
18675
+ " exit 0",
18676
+ "fi",
18677
+ "",
18678
+ "if run_react_doctor > \"$output_file\" 2>&1; then",
18679
+ " exit 0",
18680
+ "fi",
18681
+ "",
18682
+ "node - \"$input_file\" \"$output_file\" <<'NODE'",
18683
+ "const fs = require('node:fs');",
18684
+ "const inputPath = process.argv[2];",
18685
+ "const outputPath = process.argv[3];",
18686
+ "const readInput = () => {",
18687
+ " try {",
18688
+ " return JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18689
+ " } catch {",
18690
+ " return {};",
18691
+ " }",
18692
+ "};",
18693
+ "const input = readInput();",
18694
+ "const scanOutput = fs.readFileSync(outputPath, 'utf8').trim();",
18695
+ "if (!scanOutput) process.exit(0);",
18696
+ "const message = `React Doctor found issues in the changed files. Review this output and fix the regressions before finishing. For confirmed issues that cannot be fixed now, create GitHub issues with the rule, file/line, confidence, impact, and proposed fix.\\n\\n${scanOutput}`;",
18697
+ "if (input.hook_event_name === 'PostToolBatch') {",
18698
+ " console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolBatch', additionalContext: message } }));",
18699
+ "} else {",
18700
+ " console.log(JSON.stringify({ additional_context: message }));",
18701
+ "}",
18702
+ "NODE",
18703
+ ""
18704
+ ].join("\n");
18705
+ const installReactDoctorAgentHooks = (options) => {
18706
+ const installedAgents = [];
18707
+ const files = [];
18708
+ const requestedAgents = options.agents.filter(isSupportedAgent);
18709
+ for (const agent of requestedAgents) {
18710
+ if (agent === CLAUDE_AGENT) {
18711
+ files.push(...installClaudeHook(options.projectRoot));
18712
+ installedAgents.push(agent);
18713
+ }
18714
+ if (agent === CURSOR_AGENT) {
18715
+ files.push(...installCursorHook(options.projectRoot));
18716
+ installedAgents.push(agent);
18717
+ }
18729
18718
  }
18719
+ return {
18720
+ installedAgents,
18721
+ files
18722
+ };
18730
18723
  };
18731
- const detectPackageManager = (projectRoot) => {
18732
- let currentDirectory = path$1.resolve(projectRoot);
18733
- while (true) {
18734
- const packageJson = readPackageJson(currentDirectory);
18735
- if (isRecord(packageJson) && typeof packageJson.packageManager === "string") {
18736
- const packageManagerName = packageJson.packageManager.split("@")[0];
18737
- if (packageManagerName === "pnpm" || packageManagerName === "yarn" || packageManagerName === "bun" || packageManagerName === "npm") return packageManagerName;
18738
- }
18739
- const parentDirectory = path$1.dirname(currentDirectory);
18740
- if (parentDirectory === currentDirectory) break;
18741
- currentDirectory = parentDirectory;
18724
+ //#endregion
18725
+ //#region src/cli/utils/install-git-hook-file.ts
18726
+ const REACT_DOCTOR_BLOCK_START = "# react-doctor hook start";
18727
+ const REACT_DOCTOR_BLOCK_END = "# react-doctor hook end";
18728
+ const REACT_DOCTOR_BLOCK_PATTERN = new RegExp(`(?:${REACT_DOCTOR_BLOCK_START}[\\s\\S]*?${REACT_DOCTOR_BLOCK_END}\\n?|# react-doctor hook launcher start[\\s\\S]*?# react-doctor hook launcher end\\n?)`);
18729
+ const SHEBANG = "#!/bin/sh";
18730
+ const SHEBANG_PREFIX = "#!";
18731
+ const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
18732
+ const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
18733
+ const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
18734
+ const buildReactDoctorHookBlock = () => [
18735
+ REACT_DOCTOR_BLOCK_START,
18736
+ "react_doctor_scan_staged_files() {",
18737
+ ` if [ -x "${LOCAL_REACT_DOCTOR_BIN}" ]; then`,
18738
+ ` "${LOCAL_REACT_DOCTOR_BIN}" ${REACT_DOCTOR_COMMAND.replace("react-doctor ", "")}`,
18739
+ " return",
18740
+ " fi",
18741
+ "",
18742
+ " if command -v react-doctor >/dev/null 2>&1; then",
18743
+ ` ${REACT_DOCTOR_COMMAND}`,
18744
+ " return",
18745
+ " fi",
18746
+ "",
18747
+ " if command -v pnpm >/dev/null 2>&1; then",
18748
+ ` ${PNPM_REACT_DOCTOR_COMMAND}`,
18749
+ " return",
18750
+ " fi",
18751
+ "",
18752
+ " if command -v npx >/dev/null 2>&1; then",
18753
+ ` ${NPX_REACT_DOCTOR_COMMAND}`,
18754
+ " return",
18755
+ " fi",
18756
+ "",
18757
+ " printf '%s\\n' \"react-doctor: command not found; skipping staged scan.\"",
18758
+ "}",
18759
+ "",
18760
+ "react_doctor_output=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-hook.XXXXXX\")",
18761
+ "if react_doctor_scan_staged_files > \"$react_doctor_output\" 2>&1; then",
18762
+ " rm -f \"$react_doctor_output\"",
18763
+ "else",
18764
+ " rm -f \"$react_doctor_output\"",
18765
+ ` printf '%s\\n' "React Doctor found staged regressions." "Run ${REACT_DOCTOR_COMMAND} to inspect." "Want them fixed? Ask your agent to run that command and resolve the findings." >&2`,
18766
+ "fi",
18767
+ REACT_DOCTOR_BLOCK_END
18768
+ ].join("\n");
18769
+ const mergeHookContent = (existingContent) => {
18770
+ const hookBlock = `${buildReactDoctorHookBlock()}\n`;
18771
+ if (REACT_DOCTOR_BLOCK_PATTERN.test(existingContent)) return ensureTrailingNewline(existingContent.replace(REACT_DOCTOR_BLOCK_PATTERN, hookBlock));
18772
+ if (existingContent.length === 0) return `${SHEBANG}\n\n${hookBlock}`;
18773
+ const normalizedExistingContent = ensureTrailingNewline(existingContent);
18774
+ if (normalizedExistingContent.startsWith(SHEBANG_PREFIX)) {
18775
+ const [shebangLine, ...remainingLines] = normalizedExistingContent.split("\n");
18776
+ return [
18777
+ shebangLine,
18778
+ "",
18779
+ hookBlock.trimEnd(),
18780
+ ...remainingLines
18781
+ ].join("\n");
18742
18782
  }
18743
- const lockfileDirectory = findNearestFileDirectory(projectRoot, PACKAGE_MANAGER_LOCKFILES.map((lockfile) => lockfile.fileName));
18744
- return PACKAGE_MANAGER_LOCKFILES.find((lockfile) => lockfileDirectory !== null && fs$1.existsSync(path$1.join(lockfileDirectory, lockfile.fileName)))?.packageManager ?? "npm";
18783
+ return `${SHEBANG}\n\n${hookBlock}${normalizedExistingContent}`;
18745
18784
  };
18746
- const packageManagerNeedsWorkspaceFlag = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, "pnpm-workspace.yaml")) || findNearestFileDirectory(projectRoot, ["pnpm-workspace.yaml"]) !== null;
18747
- const buildInstallCommand = (projectRoot) => {
18748
- const packageManager = detectPackageManager(projectRoot);
18749
- const packageSpecifier = `${DOCTOR_PACKAGE_NAME}@latest`;
18750
- if (packageManager === "npm") return {
18751
- command: "npm",
18752
- args: [
18753
- "install",
18754
- "--save-dev",
18755
- packageSpecifier
18756
- ],
18757
- cwd: projectRoot
18758
- };
18759
- if (packageManager === "yarn") return {
18760
- command: "yarn",
18761
- args: [
18762
- "add",
18763
- "--dev",
18764
- packageSpecifier
18765
- ],
18766
- cwd: projectRoot
18767
- };
18768
- if (packageManager === "bun") return {
18769
- command: "bun",
18770
- args: [
18771
- "add",
18772
- "--dev",
18773
- packageSpecifier
18774
- ],
18775
- cwd: projectRoot
18776
- };
18785
+ const removeLegacyManagedRunner = (projectRoot) => {
18786
+ const runnerPath = path$1.join(projectRoot, LEGACY_HOOK_RUNNER_RELATIVE_PATH);
18787
+ fs$1.rmSync(runnerPath, { force: true });
18788
+ for (const directory of [path$1.dirname(runnerPath), path$1.join(projectRoot, ".react-doctor")]) try {
18789
+ fs$1.rmdirSync(directory);
18790
+ } catch {}
18791
+ };
18792
+ const installDirectGitHook = (options) => {
18793
+ const didHookExist = fs$1.existsSync(options.hookPath);
18794
+ const nextContent = mergeHookContent(didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "");
18795
+ if (options.hooksPathConfig !== void 0) runGit(options.projectRoot, [
18796
+ "config",
18797
+ "core.hooksPath",
18798
+ options.hooksPathConfig
18799
+ ]);
18800
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18801
+ fs$1.writeFileSync(options.hookPath, nextContent);
18802
+ fs$1.chmodSync(options.hookPath, 493);
18803
+ removeLegacyManagedRunner(options.projectRoot);
18777
18804
  return {
18778
- command: "pnpm",
18779
- args: [
18780
- "add",
18781
- "--save-dev",
18782
- ...packageManagerNeedsWorkspaceFlag(projectRoot) ? ["-w"] : [],
18783
- packageSpecifier
18784
- ],
18785
- cwd: projectRoot
18805
+ hookPath: options.hookPath,
18806
+ kind: options.kind ?? "git",
18807
+ status: didHookExist ? "updated" : "created"
18786
18808
  };
18787
18809
  };
18788
- const execFileAsync$1 = promisify(execFile);
18789
- const defaultInstallDependencyRunner = async (input) => {
18790
- await execFileAsync$1(input.command, [...input.args], {
18791
- cwd: input.cwd,
18792
- env: {
18793
- ...process.env,
18794
- REACT_DOCTOR_INSTALL: "1"
18795
- },
18796
- shell: process.platform === "win32"
18797
- });
18810
+ //#endregion
18811
+ //#region src/cli/utils/install-git-hook-config-managers.ts
18812
+ const appendStringCommand = (existingCommand) => {
18813
+ const existingCommandText = typeof existingCommand === "string" ? existingCommand : Array.isArray(existingCommand) ? existingCommand.filter((entry) => typeof entry === "string").join("\n") : "";
18814
+ return existingCommandText.includes("react-doctor --staged --blocking warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
18798
18815
  };
18799
- const isSupplyChainTrustError = (error) => {
18800
- const candidate = error;
18801
- const haystack = [
18802
- candidate?.stderr,
18803
- candidate?.stdout,
18804
- candidate?.message
18805
- ].map((part) => String(part ?? "")).join("\n");
18806
- return /ERR_PNPM_TRUST_DOWNGRADE|trust downgrade/i.test(haystack);
18816
+ const appendArrayCommand = (existingCommands) => {
18817
+ const commands = Array.isArray(existingCommands) ? existingCommands.filter((entry) => typeof entry === "string") : typeof existingCommands === "string" ? [existingCommands] : [];
18818
+ return commands.some((command) => command.includes("react-doctor --staged --blocking warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
18807
18819
  };
18808
- const formatInstallCommand = (input) => [input.command, ...input.args].join(" ");
18809
- const installReactDoctorDependency = async (options) => {
18820
+ const installPackageJsonHook = (options, strategy) => {
18821
+ const packageJsonPath = getPackageJsonPath(options.projectRoot);
18822
+ const didHookExist = fs$1.existsSync(packageJsonPath);
18810
18823
  const packageJson = readPackageJson(options.projectRoot);
18811
- if (!isRecord(packageJson)) return {
18812
- dependencyStatus: "skipped",
18813
- dependencyReason: "missing-or-invalid-package-json"
18814
- };
18815
- if (hasDoctorDependency(packageJson)) return { dependencyStatus: "existing" };
18816
- if (packageJson.devDependencies !== void 0 && !isRecord(packageJson.devDependencies)) return {
18817
- dependencyStatus: "skipped",
18818
- dependencyReason: "invalid-dev-dependencies"
18819
- };
18820
- const runnerInput = buildInstallCommand(options.projectRoot);
18821
- try {
18822
- await (options.runner ?? defaultInstallDependencyRunner)(runnerInput);
18823
- } catch (error) {
18824
- return {
18825
- dependencyStatus: "skipped",
18826
- dependencyReason: isSupplyChainTrustError(error) ? "trust-policy-blocked" : "install-command-failed",
18827
- installCommand: formatInstallCommand(runnerInput)
18828
- };
18824
+ const nextPackageJson = isRecord(packageJson) ? { ...packageJson } : {};
18825
+ const parentKeys = strategy.path.slice(0, -1);
18826
+ const leafKey = strategy.path[strategy.path.length - 1];
18827
+ let parent = nextPackageJson;
18828
+ for (const key of parentKeys) {
18829
+ const existing = parent[key];
18830
+ const cloned = isRecord(existing) ? { ...existing } : {};
18831
+ parent[key] = cloned;
18832
+ parent = cloned;
18829
18833
  }
18830
- return { dependencyStatus: "created" };
18834
+ parent[leafKey] = strategy.leafShape === "array" ? appendArrayCommand(parent[leafKey]) : appendStringCommand(parent[leafKey]);
18835
+ writeJsonFile$1(packageJsonPath, nextPackageJson);
18836
+ removeLegacyManagedRunner(options.projectRoot);
18837
+ return {
18838
+ hookPath: packageJsonPath,
18839
+ kind: strategy.kind,
18840
+ status: didHookExist ? "updated" : "created"
18841
+ };
18831
18842
  };
18832
- const buildManualGitHookTarget = (hookPath, projectRoot) => ({
18833
- hookPath,
18834
- runnerRoot: projectRoot,
18835
- kind: "git"
18843
+ const installSimpleGitHooks = (options) => installPackageJsonHook(options, {
18844
+ kind: "simple-git-hooks",
18845
+ path: ["simple-git-hooks", "pre-commit"],
18846
+ leafShape: "string"
18847
+ });
18848
+ const installGhooks = (options) => installPackageJsonHook(options, {
18849
+ kind: "ghooks",
18850
+ path: [
18851
+ "config",
18852
+ "ghooks",
18853
+ "pre-commit"
18854
+ ],
18855
+ leafShape: "string"
18856
+ });
18857
+ const installPreCommitNpm = (options) => installPackageJsonHook(options, {
18858
+ kind: "pre-commit-npm",
18859
+ path: ["pre-commit"],
18860
+ leafShape: "array"
18861
+ });
18862
+ const installPrettyQuick = (options) => installPackageJsonHook(options, {
18863
+ kind: "pretty-quick",
18864
+ path: ["gitHooks", "pre-commit"],
18865
+ leafShape: "string"
18836
18866
  });
18837
- const formatGitHookInstallMessage = (hookResult) => {
18838
- if (CONFIG_ONLY_GIT_HOOK_KINDS.has(hookResult.kind)) return `React Doctor pre-commit config ${hookResult.status} at ${hookResult.hookPath}. Run your hook manager's install command if hooks are not already installed.`;
18839
- return `React Doctor pre-commit hook ${hookResult.status} at ${hookResult.hookPath}.`;
18840
- };
18841
- const formatDoctorScriptInstallMessage = (scriptResult) => {
18842
- const messages = [];
18843
- const scriptName = scriptResult.scriptName ?? "doctor";
18844
- if (scriptResult.scriptStatus === "created") messages.push(`Added package script: ${scriptName}.`);
18845
- else if (scriptResult.scriptStatus === "existing") messages.push(`Package script already exists: ${scriptName}.`);
18846
- else if (scriptResult.scriptReason === "script-names-taken") messages.push("Skipped package script: doctor and react-doctor are already taken.");
18847
- else if (scriptResult.scriptReason === "doctor-script-taken") messages.push("Skipped package script: doctor and react-doctor scripts already exist.");
18848
- else if (scriptResult.scriptReason === "invalid-scripts") messages.push(`Skipped package script: scripts field is not an object.`);
18849
- else messages.push("Skipped package script: package.json missing or invalid.");
18850
- return messages.join(" ");
18851
- };
18852
- const formatDependencyInstallMessage = (result) => {
18853
- if (result.dependencyStatus === "created") return "Installed dev dependency: react-doctor.";
18854
- if (result.dependencyStatus === "existing") return "React Doctor dependency already exists.";
18855
- if (result.dependencyReason === "invalid-dev-dependencies") return "Skipped dev dependency install: devDependencies field is not an object.";
18856
- if (result.dependencyReason === "trust-policy-blocked") return "Local install skipped by your package manager's supply-chain trust policy (safe to ignore for pre-release packages).";
18857
- if (result.dependencyReason === "install-command-failed") return "Local install failed: your package manager rejected the command.";
18858
- return "Skipped dev dependency install: package.json missing or invalid.";
18867
+ const installYorkie = (options) => installPackageJsonHook(options, {
18868
+ kind: "yorkie",
18869
+ path: ["gitHooks", "pre-commit"],
18870
+ leafShape: "string"
18871
+ });
18872
+ const installGitHooksJs = (options) => installPackageJsonHook(options, {
18873
+ kind: "git-hooks-js",
18874
+ path: ["git-hooks", "pre-commit"],
18875
+ leafShape: "string"
18876
+ });
18877
+ const appendIndentedBlockToTopLevelSection = (content, sectionName, block) => {
18878
+ const normalizedContent = ensureTrailingNewline(content);
18879
+ const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(normalizedContent);
18880
+ if (match === null) return ensureTrailingNewline([
18881
+ normalizedContent.trimEnd(),
18882
+ "",
18883
+ `${sectionName}:`,
18884
+ ...block,
18885
+ ""
18886
+ ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18887
+ const sectionStartIndex = match.index;
18888
+ const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18889
+ nextSectionPattern.lastIndex = sectionStartIndex + match[0].length;
18890
+ let nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18891
+ while (nextSectionMatch !== null && nextSectionMatch.index === sectionStartIndex) nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18892
+ const insertIndex = nextSectionMatch?.index ?? normalizedContent.length;
18893
+ const prefix = normalizedContent.slice(0, insertIndex).trimEnd();
18894
+ const suffix = normalizedContent.slice(insertIndex);
18895
+ return ensureTrailingNewline([
18896
+ prefix,
18897
+ ...block,
18898
+ suffix.trimStart()
18899
+ ].join("\n"));
18859
18900
  };
18860
- const buildDependencyFollowUp = (result) => {
18861
- if (result.dependencyReason !== "trust-policy-blocked" && result.dependencyReason !== "install-command-failed") return;
18862
- return ` React Doctor still works via \`npx react-doctor\`. To install locally: ${result.installCommand ?? `npm install --save-dev react-doctor@latest`}`;
18901
+ const findTopLevelSectionRange = (content, sectionName) => {
18902
+ const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(content);
18903
+ if (match === null) return null;
18904
+ const headerLineEndIndex = content.indexOf("\n", match.index);
18905
+ const headerEndIndex = headerLineEndIndex === -1 ? match.index + match[0].length : headerLineEndIndex + 1;
18906
+ const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18907
+ nextSectionPattern.lastIndex = headerEndIndex;
18908
+ return {
18909
+ headerEndIndex,
18910
+ contentEndIndex: nextSectionPattern.exec(content)?.index ?? content.length
18911
+ };
18863
18912
  };
18864
- const installReactDoctorScriptStep = (projectRoot) => {
18865
- const scriptSpinner = spinner("Installing React Doctor package script...").start();
18866
- try {
18867
- const scriptResult = installDoctorScript({ projectRoot });
18868
- scriptSpinner.succeed(formatDoctorScriptInstallMessage(scriptResult));
18869
- } catch (error) {
18870
- scriptSpinner.fail("Failed to install React Doctor package script.");
18871
- throw error;
18872
- }
18913
+ const appendLefthookCommand = (content) => {
18914
+ const normalizedContent = ensureTrailingNewline(content);
18915
+ const sectionRange = findTopLevelSectionRange(normalizedContent, "pre-commit");
18916
+ const reactDoctorCommandBlock = [
18917
+ " react-doctor:",
18918
+ ` run: ${NON_BLOCKING_REACT_DOCTOR_COMMAND}`,
18919
+ ""
18920
+ ];
18921
+ if (sectionRange === null) return ensureTrailingNewline([
18922
+ normalizedContent.trimEnd(),
18923
+ "",
18924
+ "pre-commit:",
18925
+ " commands:",
18926
+ ...reactDoctorCommandBlock
18927
+ ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18928
+ const sectionContent = normalizedContent.slice(sectionRange.headerEndIndex, sectionRange.contentEndIndex);
18929
+ const commandsMatch = /^ commands:\s*$/m.exec(sectionContent);
18930
+ const insertIndex = commandsMatch === null ? sectionRange.headerEndIndex : sectionRange.headerEndIndex + sectionContent.indexOf(commandsMatch[0]) + commandsMatch[0].length + 1;
18931
+ const insertBlock = commandsMatch === null ? [" commands:", ...reactDoctorCommandBlock].join("\n") : reactDoctorCommandBlock.join("\n");
18932
+ return ensureTrailingNewline(`${normalizedContent.slice(0, insertIndex)}${insertBlock}${normalizedContent.slice(insertIndex)}`);
18873
18933
  };
18874
- const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) => {
18875
- installReactDoctorScriptStep(projectRoot);
18876
- const dependencySpinner = spinner("Installing React Doctor package...").start();
18877
- try {
18878
- const dependencyResult = await installReactDoctorDependency({
18879
- projectRoot,
18880
- runner: dependencyRunner
18881
- });
18882
- recordCount(METRIC.installDependency, 1, {
18883
- status: dependencyResult.dependencyStatus,
18884
- reason: dependencyResult.dependencyReason ?? null,
18885
- packageManager: detectPackageManager(projectRoot)
18886
- });
18887
- if (dependencyResult.dependencyStatus === "skipped") {
18888
- const message = formatDependencyInstallMessage(dependencyResult);
18889
- if (dependencyResult.dependencyReason === "trust-policy-blocked") dependencySpinner.warn(message);
18890
- else dependencySpinner.fail(message);
18891
- const followUp = buildDependencyFollowUp(dependencyResult);
18892
- if (followUp !== void 0) cliLogger.dim(followUp);
18893
- return dependencyResult;
18894
- }
18895
- dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
18896
- return dependencyResult;
18897
- } catch (error) {
18898
- dependencySpinner.fail("Failed to install React Doctor package.");
18899
- throw error;
18934
+ const installLefthook = (options) => {
18935
+ const didHookExist = fs$1.existsSync(options.hookPath);
18936
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18937
+ if (!existingContent.includes("react-doctor")) {
18938
+ const nextContent = appendLefthookCommand(existingContent);
18939
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18940
+ fs$1.writeFileSync(options.hookPath, nextContent);
18900
18941
  }
18942
+ removeLegacyManagedRunner(options.projectRoot);
18943
+ return {
18944
+ hookPath: options.hookPath,
18945
+ kind: "lefthook",
18946
+ status: didHookExist ? "updated" : "created"
18947
+ };
18901
18948
  };
18902
- const getSkillSourceDirectory = () => {
18903
- const distDirectory = path$1.dirname(fileURLToPath(import.meta.url));
18904
- return path$1.join(distDirectory, "skills", SKILL_NAME);
18905
- };
18906
- const findBundledSiblingSkills = (primarySkillDir) => {
18907
- const skillsParent = path$1.dirname(primarySkillDir);
18908
- if (!fs$1.existsSync(skillsParent)) return [];
18909
- const resolvedPrimary = path$1.resolve(primarySkillDir);
18910
- return fs$1.readdirSync(skillsParent, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => ({
18911
- name: entry.name,
18912
- source: path$1.join(skillsParent, entry.name)
18913
- })).filter((sibling) => path$1.resolve(sibling.source) !== resolvedPrimary && fs$1.existsSync(path$1.join(sibling.source, SKILL_MANIFEST_FILE)));
18914
- };
18915
- const installBundledSiblingSkills = async (primarySkillDir, agents, projectRoot) => {
18916
- const installedSkillNames = [];
18917
- for (const sibling of findBundledSiblingSkills(primarySkillDir)) {
18918
- const result = await installSkillsFromSource({
18919
- source: sibling.source,
18920
- agents: [...agents],
18921
- cwd: projectRoot,
18922
- mode: "copy"
18923
- });
18924
- if (result.failed.length > 0) throw new Error(result.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
18925
- if (result.skills.length > 0) installedSkillNames.push(sibling.name);
18949
+ const installPreCommit = (options) => {
18950
+ const didHookExist = fs$1.existsSync(options.hookPath);
18951
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18952
+ if (!existingContent.includes("id: react-doctor")) {
18953
+ const hasReposKey = /^repos:\s*$/m.test(existingContent);
18954
+ const localHookBlock = [
18955
+ " - repo: local",
18956
+ " hooks:",
18957
+ " - id: react-doctor",
18958
+ " name: react-doctor",
18959
+ ` entry: sh -c '${NON_BLOCKING_REACT_DOCTOR_COMMAND}'`,
18960
+ " language: system",
18961
+ " pass_filenames: false",
18962
+ ""
18963
+ ].join("\n");
18964
+ const nextContent = hasReposKey ? `${ensureTrailingNewline(existingContent)}${localHookBlock}` : `repos:\n${localHookBlock}`;
18965
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18966
+ fs$1.writeFileSync(options.hookPath, nextContent);
18926
18967
  }
18927
- return installedSkillNames;
18968
+ removeLegacyManagedRunner(options.projectRoot);
18969
+ return {
18970
+ hookPath: options.hookPath,
18971
+ kind: "pre-commit",
18972
+ status: didHookExist ? "updated" : "created"
18973
+ };
18928
18974
  };
18929
- const canInstallNativeAgentHooks = (agents) => agents.some((agent) => agent === "claude-code" || agent === "cursor");
18930
- const runInstallReactDoctor = async (options = {}) => {
18931
- const requestedProjectRoot = options.projectRoot ?? process.cwd();
18932
- const projectRoot = findNearestPackageDirectory(requestedProjectRoot) ?? requestedProjectRoot;
18933
- const sourceDir = options.sourceDir ?? getSkillSourceDirectory();
18934
- if (!fs$1.existsSync(path$1.join(sourceDir, SKILL_MANIFEST_FILE))) {
18935
- cliLogger.error(`Could not locate the ${SKILL_NAME} skill bundled with this package.`);
18936
- process.exitCode = 1;
18937
- return;
18938
- }
18939
- const detectedAgents = options.detectedAgents ?? await detectAvailableAgents();
18940
- if (detectedAgents.length === 0) {
18941
- cliLogger.error("No supported coding agents detected.");
18942
- cliLogger.dim(" Looked for binaries on PATH (claude, codex, cursor, droid, gemini, copilot, opencode, pi)");
18943
- cliLogger.dim(" and config dirs in $HOME (~/.claude, ~/.cursor, ~/.codex, ~/.gemini, ...).");
18944
- process.exitCode = 1;
18945
- return;
18946
- }
18947
- const skipPrompts = shouldSkipPrompts({ yes: options.yes });
18948
- const gitHookTarget = options.gitHookPath === void 0 ? detectGitHookTarget(projectRoot) : options.gitHookPath === null ? null : buildManualGitHookTarget(options.gitHookPath, projectRoot);
18949
- const gitHookPath = gitHookTarget?.hookPath;
18950
- const promptOptions = options.onPromptCancel === void 0 ? {} : { onCancel: options.onPromptCancel };
18951
- const prompt = options.prompt ?? prompts;
18952
- const selectedAgents = skipPrompts ? detectedAgents : (await prompt({
18953
- type: "multiselect",
18954
- name: "agents",
18955
- message: `Install the ${highlighter.info(`/react-doctor`)} skill for:`,
18956
- choices: detectedAgents.map((agent) => ({
18957
- title: getSkillAgentConfig(agent).displayName,
18958
- value: agent,
18959
- selected: true
18960
- })),
18961
- instructions: false,
18962
- min: 1
18963
- }, promptOptions)).agents ?? [];
18964
- if (selectedAgents.length === 0) return;
18965
- const workflowTargetPath = getReactDoctorWorkflowPath(projectRoot);
18966
- const canInstallWorkflow = !isReactDoctorWorkflowInstalled(projectRoot);
18967
- const setupActionChoices = [
18968
- ...gitHookPath === null || gitHookPath === void 0 ? [] : [{
18969
- title: "Pre-commit hook",
18970
- description: "Check staged changes before each commit",
18971
- value: SETUP_OPTION_GIT_HOOK,
18972
- selected: true
18973
- }],
18974
- ...canInstallNativeAgentHooks(selectedAgents) ? [{
18975
- title: "Agent hooks",
18976
- description: "Ask Claude Code or Cursor to scan after code edits",
18977
- value: SETUP_OPTION_AGENT_HOOKS,
18978
- selected: Boolean(options.agentHooks)
18979
- }] : [],
18980
- ...canInstallWorkflow ? [{
18981
- title: "GitHub Actions workflow",
18982
- description: "Scan pull requests in CI",
18983
- value: SETUP_OPTION_WORKFLOW,
18984
- selected: true
18985
- }] : []
18986
- ];
18987
- const setupChoices = setupActionChoices.length === 0 ? [] : [{
18988
- title: "Skip optional setup",
18989
- description: "Install only the agent skill and package setup",
18990
- value: SETUP_OPTION_SKIP,
18991
- selected: false
18992
- }, ...setupActionChoices];
18993
- const selectedSetupOptions = skipPrompts || setupChoices.length === 0 ? [] : (await prompt({
18994
- type: "multiselect",
18995
- name: "setupOptions",
18996
- message: "Select additional React Doctor setup:",
18997
- choices: setupChoices,
18998
- instructions: false
18999
- }, promptOptions)).setupOptions ?? [];
19000
- const selectedSetupActions = selectedSetupOptions.filter((setupOption) => setupOption !== SETUP_OPTION_SKIP);
19001
- const didSkipOptionalSetup = selectedSetupActions.length === 0 && selectedSetupOptions.includes(SETUP_OPTION_SKIP);
19002
- const shouldInstallGitHook = gitHookPath != null && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_GIT_HOOK));
19003
- const shouldInstallAgentHooks = Boolean(options.agentHooks) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_AGENT_HOOKS);
19004
- const shouldInstallWorkflow = canInstallWorkflow && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_WORKFLOW));
19005
- if (options.dryRun) {
19006
- cliLogger.log(`Dry run — would install ${SKILL_NAME} skill for:`);
19007
- for (const agent of selectedAgents) cliLogger.dim(` - ${getSkillAgentConfig(agent).displayName}`);
19008
- cliLogger.dim(` Source: ${sourceDir}`);
19009
- for (const sibling of findBundledSiblingSkills(sourceDir)) cliLogger.dim(` Also installs skill: ${sibling.name}`);
19010
- cliLogger.dim(" Package script: doctor (or react-doctor if doctor exists)");
19011
- cliLogger.dim(" Dev dependency: react-doctor");
19012
- if (shouldInstallGitHook) cliLogger.dim(` Git hook: ${gitHookPath}`);
19013
- if (shouldInstallAgentHooks) cliLogger.dim(" Agent hooks: Claude Code / Cursor when selected");
19014
- if (shouldInstallWorkflow) cliLogger.dim(` GitHub Actions workflow: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19015
- return;
19016
- }
19017
- const installSpinner = spinner(`Installing ${SKILL_NAME} skill...`).start();
19018
- try {
19019
- const installResult = await installSkillsFromSource({
19020
- source: sourceDir,
19021
- agents: selectedAgents,
19022
- cwd: projectRoot,
19023
- mode: "copy"
19024
- });
19025
- if (installResult.skills.length === 0) throw new Error(`Could not parse ${SKILL_MANIFEST_FILE} for ${SKILL_NAME} (missing or invalid frontmatter).`);
19026
- if (installResult.failed.length > 0) throw new Error(installResult.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
19027
- installSpinner.succeed(`${SKILL_NAME} skill installed for ${selectedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19028
- } catch (error) {
19029
- installSpinner.fail(`Failed to install ${SKILL_NAME} skill.`);
19030
- throw error;
19031
- }
19032
- try {
19033
- const installedSiblingSkills = await installBundledSiblingSkills(sourceDir, selectedAgents, projectRoot);
19034
- if (installedSiblingSkills.length > 0) cliLogger.dim(` Also installed the ${installedSiblingSkills.join(", ")} skill.`);
19035
- } catch {
19036
- cliLogger.dim(" Skipped bundled sibling skills (install error).");
19037
- }
19038
- const dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
19039
- if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) {
19040
- const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
19041
- try {
19042
- const hookResult = installReactDoctorGitHook({
19043
- hookPath: gitHookTarget.hookPath,
19044
- projectRoot: gitHookTarget.runnerRoot,
19045
- kind: gitHookTarget.kind,
19046
- hooksPathConfig: gitHookTarget.hooksPathConfig
19047
- });
19048
- hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
19049
- recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
19050
- } catch (error) {
19051
- hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
19052
- throw error;
19053
- }
18975
+ const installOvercommit = (options) => {
18976
+ const didHookExist = fs$1.existsSync(options.hookPath);
18977
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18978
+ if (!existingContent.includes("ReactDoctor")) {
18979
+ const nextContent = appendIndentedBlockToTopLevelSection(existingContent, "PreCommit", [
18980
+ " ReactDoctor:",
18981
+ " enabled: true",
18982
+ ` command: ['sh', '-c', '${NON_BLOCKING_REACT_DOCTOR_COMMAND}']`,
18983
+ ""
18984
+ ]);
18985
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18986
+ fs$1.writeFileSync(options.hookPath, nextContent);
19054
18987
  }
19055
- if (shouldInstallAgentHooks) {
19056
- const hookSpinner = spinner("Installing React Doctor agent hooks...").start();
19057
- try {
19058
- const hookResult = installReactDoctorAgentHooks({
19059
- projectRoot,
19060
- agents: selectedAgents
19061
- });
19062
- if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
19063
- else {
19064
- hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19065
- recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
19066
- }
19067
- } catch (error) {
19068
- hookSpinner.fail("Failed to install React Doctor agent hooks.");
19069
- throw error;
19070
- }
18988
+ removeLegacyManagedRunner(options.projectRoot);
18989
+ return {
18990
+ hookPath: options.hookPath,
18991
+ kind: "overcommit",
18992
+ status: didHookExist ? "updated" : "created"
18993
+ };
18994
+ };
18995
+ //#endregion
18996
+ //#region src/cli/utils/install-git-hook.ts
18997
+ const isHuskyProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".husky")) || packageHasDependency(projectRoot, "husky");
18998
+ const isVitePlusProject = (projectRoot) => packageHasDependency(projectRoot, "vite-plus");
18999
+ const isSimpleGitHooksProject = (projectRoot) => {
19000
+ const packageJson = readPackageJson(projectRoot);
19001
+ return isRecord(packageJson) && isRecord(packageJson["simple-git-hooks"]) || packageHasDependency(projectRoot, "simple-git-hooks") || fs$1.existsSync(path$1.join(projectRoot, ".simple-git-hooks.cjs"));
19002
+ };
19003
+ const getLefthookConfigPath = (projectRoot) => {
19004
+ for (const fileName of LEFTHOOK_CONFIG_FILES) {
19005
+ const filePath = path$1.join(projectRoot, fileName);
19006
+ if (fs$1.existsSync(filePath)) return filePath;
19071
19007
  }
19072
- let didInstallWorkflow = false;
19073
- if (shouldInstallWorkflow) didInstallWorkflow = reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
19074
- recordCount(METRIC.installCompleted, 1, {
19075
- agentsCount: selectedAgents.length,
19076
- gitHook: shouldInstallGitHook,
19077
- agentHooks: shouldInstallAgentHooks,
19078
- workflow: didInstallWorkflow,
19079
- dependencyStatus: dependencyResult.dependencyStatus,
19080
- packageManager: detectPackageManager(projectRoot)
19081
- });
19082
- for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
19008
+ return packageHasDependency(projectRoot, "lefthook") ? path$1.join(projectRoot, LEFTHOOK_CONFIG_FILES[0] ?? "lefthook.yml") : null;
19009
+ };
19010
+ const isPreCommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, PRE_COMMIT_CONFIG_FILE));
19011
+ const isOvercommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".overcommit.yml")) || packageHasDependency(projectRoot, "overcommit");
19012
+ const isYorkieProject = (projectRoot) => packageHasRecordKey(projectRoot, "gitHooks") || packageHasDependency(projectRoot, "yorkie");
19013
+ const isGhooksProject = (projectRoot) => packageHasDependency(projectRoot, "ghooks") || packageHasNestedRecordKey(projectRoot, "config", "ghooks");
19014
+ const isGitHooksJsProject = (projectRoot) => packageHasRecordKey(projectRoot, "git-hooks") || packageHasDependency(projectRoot, "git-hooks-js");
19015
+ const isPreCommitNpmProject = (projectRoot) => packageHasDependency(projectRoot, "pre-commit");
19016
+ const isPrettyQuickProject = (projectRoot) => packageHasDependency(projectRoot, "pretty-quick");
19017
+ const detectGitHookTarget = (projectRoot) => {
19018
+ if (runGit(projectRoot, ["rev-parse", "--is-inside-work-tree"]) !== "true") return null;
19019
+ const topLevel = runGit(projectRoot, ["rev-parse", "--show-toplevel"]) ?? projectRoot;
19020
+ const configuredHooksPath = runGit(projectRoot, [
19021
+ "config",
19022
+ "--path",
19023
+ "--get",
19024
+ "core.hooksPath"
19025
+ ]);
19026
+ if (configuredHooksPath !== null && configuredHooksPath.length > 0) return {
19027
+ hookPath: path$1.join(resolveGitPath(topLevel, configuredHooksPath), HOOK_FILE_NAME),
19028
+ runnerRoot: topLevel,
19029
+ kind: "configured"
19030
+ };
19031
+ if (isHuskyProject(topLevel)) return {
19032
+ hookPath: path$1.join(topLevel, HUSKY_HOOKS_PATH, HOOK_FILE_NAME),
19033
+ runnerRoot: topLevel,
19034
+ kind: "husky",
19035
+ hooksPathConfig: HUSKY_HOOKS_PATH
19036
+ };
19037
+ if (isVitePlusProject(topLevel)) return {
19038
+ hookPath: path$1.join(topLevel, VITE_PLUS_HOOKS_PATH, HOOK_FILE_NAME),
19039
+ runnerRoot: topLevel,
19040
+ kind: "vite-plus",
19041
+ hooksPathConfig: VITE_PLUS_HOOKS_PATH
19042
+ };
19043
+ if (isSimpleGitHooksProject(topLevel)) return {
19044
+ hookPath: path$1.join(topLevel, "package.json"),
19045
+ runnerRoot: topLevel,
19046
+ kind: "simple-git-hooks"
19047
+ };
19048
+ const lefthookConfigPath = getLefthookConfigPath(topLevel);
19049
+ if (lefthookConfigPath !== null) return {
19050
+ hookPath: lefthookConfigPath,
19051
+ runnerRoot: topLevel,
19052
+ kind: "lefthook"
19053
+ };
19054
+ if (isPreCommitProject(topLevel)) return {
19055
+ hookPath: path$1.join(topLevel, PRE_COMMIT_CONFIG_FILE),
19056
+ runnerRoot: topLevel,
19057
+ kind: "pre-commit"
19058
+ };
19059
+ if (isOvercommitProject(topLevel)) return {
19060
+ hookPath: path$1.join(topLevel, OVERCOMMIT_CONFIG_FILE),
19061
+ runnerRoot: topLevel,
19062
+ kind: "overcommit"
19063
+ };
19064
+ if (isYorkieProject(topLevel)) return {
19065
+ hookPath: getPackageJsonPath(topLevel),
19066
+ runnerRoot: topLevel,
19067
+ kind: "yorkie"
19068
+ };
19069
+ if (isGhooksProject(topLevel)) return {
19070
+ hookPath: getPackageJsonPath(topLevel),
19071
+ runnerRoot: topLevel,
19072
+ kind: "ghooks"
19073
+ };
19074
+ if (isGitHooksJsProject(topLevel)) return {
19075
+ hookPath: getPackageJsonPath(topLevel),
19076
+ runnerRoot: topLevel,
19077
+ kind: "git-hooks-js"
19078
+ };
19079
+ if (isPreCommitNpmProject(topLevel)) return {
19080
+ hookPath: getPackageJsonPath(topLevel),
19081
+ runnerRoot: topLevel,
19082
+ kind: "pre-commit-npm"
19083
+ };
19084
+ if (isPrettyQuickProject(topLevel)) return {
19085
+ hookPath: getPackageJsonPath(topLevel),
19086
+ runnerRoot: topLevel,
19087
+ kind: "pretty-quick"
19088
+ };
19089
+ const hookPath = runGit(projectRoot, [
19090
+ "rev-parse",
19091
+ "--git-path",
19092
+ HOOK_RELATIVE_PATH
19093
+ ]);
19094
+ if (hookPath === null || hookPath.length === 0) return null;
19095
+ return {
19096
+ hookPath: resolveGitPath(projectRoot, hookPath),
19097
+ runnerRoot: topLevel,
19098
+ kind: "git"
19099
+ };
19100
+ };
19101
+ const installReactDoctorGitHook = (options) => {
19102
+ if (options.kind === "simple-git-hooks") return installSimpleGitHooks(options);
19103
+ if (options.kind === "lefthook") return installLefthook(options);
19104
+ if (options.kind === "pre-commit") return installPreCommit(options);
19105
+ if (options.kind === "overcommit") return installOvercommit(options);
19106
+ if (options.kind === "yorkie") return installYorkie(options);
19107
+ if (options.kind === "ghooks") return installGhooks(options);
19108
+ if (options.kind === "git-hooks-js") return installGitHooksJs(options);
19109
+ if (options.kind === "pre-commit-npm") return installPreCommitNpm(options);
19110
+ if (options.kind === "pretty-quick") return installPrettyQuick(options);
19111
+ return installDirectGitHook(options);
19083
19112
  };
19084
19113
  //#endregion
19085
- //#region src/cli/utils/hash-project-root.ts
19086
- const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
19114
+ //#region src/cli/utils/should-skip-prompts.ts
19115
+ const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
19087
19116
  //#endregion
19088
- //#region src/cli/utils/action-upgrade-prompt.ts
19089
- const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
19090
- const getActionUpgradeStore = (options = {}) => new Conf({
19091
- projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
19092
- cwd: options.cwd
19093
- });
19094
- const hasHandledActionUpgrade = (projectRoot, storeOptions = {}) => {
19095
- try {
19096
- const upgrades = getActionUpgradeStore(storeOptions).get("actionUpgrades", {});
19097
- return Boolean(upgrades[hashProjectRoot(projectRoot)]);
19098
- } catch {
19099
- return true;
19117
+ //#region src/cli/utils/install-react-doctor.ts
19118
+ const SETUP_OPTION_GIT_HOOK = "git-hook";
19119
+ const SETUP_OPTION_AGENT_HOOKS = "agent-hooks";
19120
+ const SETUP_OPTION_SKIP = "skip";
19121
+ const CONFIG_ONLY_GIT_HOOK_KINDS = new Set([
19122
+ "ghooks",
19123
+ "git-hooks-js",
19124
+ "lefthook",
19125
+ "overcommit",
19126
+ "pre-commit",
19127
+ "pre-commit-npm",
19128
+ "pretty-quick",
19129
+ "simple-git-hooks",
19130
+ "yorkie"
19131
+ ]);
19132
+ const PACKAGE_MANAGER_LOCKFILES = [
19133
+ {
19134
+ packageManager: "pnpm",
19135
+ fileName: "pnpm-lock.yaml"
19136
+ },
19137
+ {
19138
+ packageManager: "yarn",
19139
+ fileName: "yarn.lock"
19140
+ },
19141
+ {
19142
+ packageManager: "bun",
19143
+ fileName: "bun.lockb"
19144
+ },
19145
+ {
19146
+ packageManager: "bun",
19147
+ fileName: "bun.lock"
19148
+ },
19149
+ {
19150
+ packageManager: "npm",
19151
+ fileName: "package-lock.json"
19100
19152
  }
19101
- };
19102
- const recordActionUpgradeDecision = (projectRoot, outcome, storeOptions = {}) => {
19103
- try {
19104
- const store = getActionUpgradeStore(storeOptions);
19105
- const upgrades = store.get("actionUpgrades", {});
19106
- store.set("actionUpgrades", {
19107
- ...upgrades,
19108
- [hashProjectRoot(projectRoot)]: {
19109
- rootDirectory: path$1.resolve(projectRoot),
19110
- outcome,
19111
- at: (/* @__PURE__ */ new Date()).toISOString()
19112
- }
19113
- });
19114
- return true;
19115
- } catch {
19116
- return false;
19153
+ ];
19154
+ const findNearestFileDirectory = (startDirectory, fileNames) => {
19155
+ let currentDirectory = path$1.resolve(startDirectory);
19156
+ while (true) {
19157
+ if (fileNames.some((fileName) => fs$1.existsSync(path$1.join(currentDirectory, fileName)))) return currentDirectory;
19158
+ const parentDirectory = path$1.dirname(currentDirectory);
19159
+ if (parentDirectory === currentDirectory) return null;
19160
+ currentDirectory = parentDirectory;
19117
19161
  }
19118
19162
  };
19119
- //#endregion
19120
- //#region src/cli/utils/install-skill-for-agent.ts
19121
- const installReactDoctorSkillForAgent = async (agent, projectRoot) => {
19122
- const source = getSkillSourceDirectory();
19123
- if (!fs$1.existsSync(path$1.join(source, SKILL_MANIFEST_FILE))) return false;
19124
- const result = await installSkillsFromSource({
19125
- source,
19126
- agents: [agent],
19127
- cwd: projectRoot,
19128
- mode: "copy"
19129
- });
19130
- return result.skills.length > 0 && result.failed.length === 0;
19163
+ const detectPackageManager = (projectRoot) => {
19164
+ let currentDirectory = path$1.resolve(projectRoot);
19165
+ while (true) {
19166
+ const packageJson = readPackageJson(currentDirectory);
19167
+ if (isRecord(packageJson) && typeof packageJson.packageManager === "string") {
19168
+ const packageManagerName = packageJson.packageManager.split("@")[0];
19169
+ if (packageManagerName === "pnpm" || packageManagerName === "yarn" || packageManagerName === "bun" || packageManagerName === "npm") return packageManagerName;
19170
+ }
19171
+ const parentDirectory = path$1.dirname(currentDirectory);
19172
+ if (parentDirectory === currentDirectory) break;
19173
+ currentDirectory = parentDirectory;
19174
+ }
19175
+ const lockfileDirectory = findNearestFileDirectory(projectRoot, PACKAGE_MANAGER_LOCKFILES.map((lockfile) => lockfile.fileName));
19176
+ return PACKAGE_MANAGER_LOCKFILES.find((lockfile) => lockfileDirectory !== null && fs$1.existsSync(path$1.join(lockfileDirectory, lockfile.fileName)))?.packageManager ?? "npm";
19131
19177
  };
19132
- //#endregion
19133
- //#region src/cli/utils/open-url.ts
19134
- const resolveOpenCommand = (url) => {
19135
- if (process$1.platform === "darwin") return {
19136
- command: "open",
19137
- args: [url]
19178
+ const packageManagerNeedsWorkspaceFlag = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, "pnpm-workspace.yaml")) || findNearestFileDirectory(projectRoot, ["pnpm-workspace.yaml"]) !== null;
19179
+ const buildInstallCommand = (projectRoot) => {
19180
+ const packageManager = detectPackageManager(projectRoot);
19181
+ const packageSpecifier = `${DOCTOR_PACKAGE_NAME}@latest`;
19182
+ if (packageManager === "npm") return {
19183
+ command: "npm",
19184
+ args: [
19185
+ "install",
19186
+ "--save-dev",
19187
+ packageSpecifier
19188
+ ],
19189
+ cwd: projectRoot
19138
19190
  };
19139
- if (process$1.platform === "win32") return {
19140
- command: "cmd",
19191
+ if (packageManager === "yarn") return {
19192
+ command: "yarn",
19141
19193
  args: [
19142
- "/c",
19143
- "start",
19144
- "",
19145
- url
19146
- ]
19194
+ "add",
19195
+ "--dev",
19196
+ packageSpecifier
19197
+ ],
19198
+ cwd: projectRoot
19199
+ };
19200
+ if (packageManager === "bun") return {
19201
+ command: "bun",
19202
+ args: [
19203
+ "add",
19204
+ "--dev",
19205
+ packageSpecifier
19206
+ ],
19207
+ cwd: projectRoot
19147
19208
  };
19148
19209
  return {
19149
- command: "xdg-open",
19150
- args: [url]
19210
+ command: "pnpm",
19211
+ args: [
19212
+ "add",
19213
+ "--save-dev",
19214
+ ...packageManagerNeedsWorkspaceFlag(projectRoot) ? ["-w"] : [],
19215
+ packageSpecifier
19216
+ ],
19217
+ cwd: projectRoot
19151
19218
  };
19152
19219
  };
19153
- const openUrl = (url) => {
19154
- try {
19155
- const { command, args } = resolveOpenCommand(url);
19156
- const child = spawn(command, args, {
19157
- detached: true,
19158
- stdio: "ignore"
19159
- });
19160
- child.on("error", () => {});
19161
- child.unref();
19162
- return true;
19163
- } catch {
19164
- return false;
19165
- }
19166
- };
19167
- //#endregion
19168
- //#region src/cli/utils/open-workflow-pull-request.ts
19169
- const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
19170
- const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
19171
- const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
19172
- const DEFAULT_PR_BODY = `Adds a [React Doctor](https://www.react.doctor) scan to every pull request and every push to the default branch. The workflow file is documented inline.
19173
-
19174
- Docs: https://www.react.doctor/ci`;
19175
19220
  const execFileAsync = promisify(execFile);
19176
- const run = async (command, args, cwd) => {
19221
+ const defaultInstallDependencyRunner = async (input) => {
19222
+ await execFileAsync(input.command, [...input.args], {
19223
+ cwd: input.cwd,
19224
+ env: {
19225
+ ...process.env,
19226
+ REACT_DOCTOR_INSTALL: "1"
19227
+ },
19228
+ shell: process.platform === "win32"
19229
+ });
19230
+ };
19231
+ const isSupplyChainTrustError = (error) => {
19232
+ const candidate = error;
19233
+ const haystack = [
19234
+ candidate?.stderr,
19235
+ candidate?.stdout,
19236
+ candidate?.message
19237
+ ].map((part) => String(part ?? "")).join("\n");
19238
+ return /ERR_PNPM_TRUST_DOWNGRADE|trust downgrade/i.test(haystack);
19239
+ };
19240
+ const formatInstallCommand = (input) => [input.command, ...input.args].join(" ");
19241
+ const installReactDoctorDependency = async (options) => {
19242
+ const packageJson = readPackageJson(options.projectRoot);
19243
+ if (!isRecord(packageJson)) return {
19244
+ dependencyStatus: "skipped",
19245
+ dependencyReason: "missing-or-invalid-package-json"
19246
+ };
19247
+ if (hasDoctorDependency(packageJson)) return { dependencyStatus: "existing" };
19248
+ if (packageJson.devDependencies !== void 0 && !isRecord(packageJson.devDependencies)) return {
19249
+ dependencyStatus: "skipped",
19250
+ dependencyReason: "invalid-dev-dependencies"
19251
+ };
19252
+ const runnerInput = buildInstallCommand(options.projectRoot);
19177
19253
  try {
19178
- const { stdout, stderr } = await execFileAsync(command, [...args], {
19179
- cwd,
19180
- encoding: "utf8"
19181
- });
19182
- return {
19183
- success: true,
19184
- stdout: stdout.trim(),
19185
- stderr: stderr.trim()
19186
- };
19254
+ await (options.runner ?? defaultInstallDependencyRunner)(runnerInput);
19187
19255
  } catch (error) {
19188
- const failure = error;
19189
19256
  return {
19190
- success: false,
19191
- stdout: (failure.stdout ?? "").trim(),
19192
- stderr: (failure.stderr ?? "").trim()
19257
+ dependencyStatus: "skipped",
19258
+ dependencyReason: isSupplyChainTrustError(error) ? "trust-policy-blocked" : "install-command-failed",
19259
+ installCommand: formatInstallCommand(runnerInput)
19193
19260
  };
19194
19261
  }
19262
+ return { dependencyStatus: "created" };
19195
19263
  };
19196
- const detectDefaultBranch = async (cwd) => {
19197
- const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
19198
- if (symRef.success) {
19199
- const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
19200
- if (branchMatch) return branchMatch[1];
19201
- }
19202
- if ((await run("git", [
19203
- "rev-parse",
19204
- "--verify",
19205
- "origin/main"
19206
- ], cwd)).success) return "main";
19207
- if ((await run("git", [
19208
- "rev-parse",
19209
- "--verify",
19210
- "origin/master"
19211
- ], cwd)).success) return "master";
19212
- return null;
19264
+ const buildManualGitHookTarget = (hookPath, projectRoot) => ({
19265
+ hookPath,
19266
+ runnerRoot: projectRoot,
19267
+ kind: "git"
19268
+ });
19269
+ const formatGitHookInstallMessage = (hookResult) => {
19270
+ if (CONFIG_ONLY_GIT_HOOK_KINDS.has(hookResult.kind)) return `React Doctor pre-commit config ${hookResult.status} at ${hookResult.hookPath}. Run your hook manager's install command if hooks are not already installed.`;
19271
+ return `React Doctor pre-commit hook ${hookResult.status} at ${hookResult.hookPath}.`;
19213
19272
  };
19214
- const findUniqueBranchName = async (cwd) => {
19215
- if (!(await run("git", [
19216
- "rev-parse",
19217
- "--verify",
19218
- NEW_BRANCH_PREFIX
19219
- ], cwd)).success) return NEW_BRANCH_PREFIX;
19220
- return `${NEW_BRANCH_PREFIX}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:T]/g, "")}`;
19273
+ const formatDependencyInstallMessage = (result) => {
19274
+ if (result.dependencyStatus === "created") return "Installed dev dependency: react-doctor.";
19275
+ if (result.dependencyStatus === "existing") return "React Doctor dependency already exists.";
19276
+ if (result.dependencyReason === "invalid-dev-dependencies") return "Skipped dev dependency install: devDependencies field is not an object.";
19277
+ if (result.dependencyReason === "trust-policy-blocked") return "Local install skipped by your package manager's supply-chain trust policy (safe to ignore for pre-release packages).";
19278
+ if (result.dependencyReason === "install-command-failed") return "Local install failed: your package manager rejected the command.";
19279
+ return "Skipped dev dependency install: package.json missing or invalid.";
19221
19280
  };
19222
- const openWorkflowPullRequest = async (params) => {
19223
- const workflowPath = path$1.resolve(params.workflowPath);
19224
- const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
19225
- const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
19226
- const prBody = params.prBody ?? DEFAULT_PR_BODY;
19227
- const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
19228
- if (!repoRootProbe.success) return {
19229
- status: "not-attempted",
19230
- reason: "not-a-git-repo"
19231
- };
19232
- const cwd = repoRootProbe.stdout;
19233
- if (!isCommandAvailable("gh")) return {
19234
- status: "not-attempted",
19235
- reason: "gh-not-installed"
19236
- };
19237
- if (!(await run("gh", ["auth", "status"], cwd)).success) return {
19238
- status: "not-attempted",
19239
- reason: "gh-not-authenticated"
19240
- };
19241
- const defaultBranch = await detectDefaultBranch(cwd);
19242
- if (!defaultBranch) return {
19243
- status: "not-attempted",
19244
- reason: "no-default-branch"
19245
- };
19246
- const previousBranchProbe = await run("git", [
19247
- "rev-parse",
19248
- "--abbrev-ref",
19249
- "HEAD"
19250
- ], cwd);
19251
- if (!previousBranchProbe.success || previousBranchProbe.stdout === "HEAD") return {
19252
- status: "not-attempted",
19253
- reason: "detached-head"
19254
- };
19255
- const previousBranch = previousBranchProbe.stdout;
19256
- await run("git", [
19257
- "fetch",
19258
- "origin",
19259
- defaultBranch
19260
- ], cwd);
19261
- const newBranch = await findUniqueBranchName(cwd);
19262
- if (!(await run("git", [
19263
- "checkout",
19264
- "-b",
19265
- newBranch,
19266
- `origin/${defaultBranch}`
19267
- ], cwd)).success) return {
19268
- status: "not-attempted",
19269
- reason: "checkout-failed"
19270
- };
19271
- const restoreToPreviousBranch = async (deleteNewBranch) => {
19272
- await run("git", ["checkout", previousBranch], cwd);
19273
- if (deleteNewBranch) await run("git", [
19274
- "branch",
19275
- "-D",
19276
- newBranch
19277
- ], cwd);
19278
- };
19279
- if (!(await run("git", [
19280
- "add",
19281
- "--",
19282
- path$1.relative(cwd, workflowPath)
19283
- ], cwd)).success) {
19284
- await restoreToPreviousBranch(true);
19285
- return {
19286
- status: "not-attempted",
19287
- reason: "git-add-failed"
19288
- };
19281
+ const buildDependencyFollowUp = (result) => {
19282
+ if (result.dependencyReason !== "trust-policy-blocked" && result.dependencyReason !== "install-command-failed") return;
19283
+ return ` React Doctor still works via \`npx react-doctor\`. To install locally: ${result.installCommand ?? `npm install --save-dev react-doctor@latest`}`;
19284
+ };
19285
+ const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) => {
19286
+ installReactDoctorScriptStep(projectRoot);
19287
+ const dependencySpinner = spinner("Installing React Doctor package...").start();
19288
+ try {
19289
+ const dependencyResult = await installReactDoctorDependency({
19290
+ projectRoot,
19291
+ runner: dependencyRunner
19292
+ });
19293
+ recordCount(METRIC.installDependency, 1, {
19294
+ status: dependencyResult.dependencyStatus,
19295
+ reason: dependencyResult.dependencyReason ?? null,
19296
+ packageManager: detectPackageManager(projectRoot)
19297
+ });
19298
+ if (dependencyResult.dependencyStatus === "skipped") {
19299
+ const message = formatDependencyInstallMessage(dependencyResult);
19300
+ if (dependencyResult.dependencyReason === "trust-policy-blocked") dependencySpinner.warn(message);
19301
+ else dependencySpinner.fail(message);
19302
+ const followUp = buildDependencyFollowUp(dependencyResult);
19303
+ if (followUp !== void 0) cliLogger.dim(followUp);
19304
+ return dependencyResult;
19305
+ }
19306
+ dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
19307
+ return dependencyResult;
19308
+ } catch (error) {
19309
+ dependencySpinner.fail("Failed to install React Doctor package.");
19310
+ throw error;
19311
+ }
19312
+ };
19313
+ const getSkillSourceDirectory = () => {
19314
+ const distDirectory = path$1.dirname(fileURLToPath(import.meta.url));
19315
+ return path$1.join(distDirectory, "skills", SKILL_NAME);
19316
+ };
19317
+ const canInstallNativeAgentHooks = (agents) => agents.some((agent) => agent === "claude-code" || agent === "cursor");
19318
+ const installReactDoctorSkillStep = async (sourceDir, selectedAgents, projectRoot) => {
19319
+ const installSpinner = spinner(`Installing ${SKILL_NAME} skill...`).start();
19320
+ try {
19321
+ const installResult = await installSkillsFromSource({
19322
+ source: sourceDir,
19323
+ agents: selectedAgents,
19324
+ cwd: projectRoot,
19325
+ mode: "copy"
19326
+ });
19327
+ if (installResult.skills.length === 0) throw new Error(`Could not parse ${SKILL_MANIFEST_FILE} for ${SKILL_NAME} (missing or invalid frontmatter).`);
19328
+ if (installResult.failed.length > 0) throw new Error(installResult.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
19329
+ installSpinner.succeed(`${SKILL_NAME} skill installed for ${selectedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19330
+ } catch (error) {
19331
+ installSpinner.fail(`Failed to install ${SKILL_NAME} skill.`);
19332
+ throw error;
19289
19333
  }
19290
- if (!(await run("git", [
19291
- "commit",
19292
- "-m",
19293
- commitMessage
19294
- ], cwd)).success) {
19295
- await restoreToPreviousBranch(true);
19296
- return {
19297
- status: "not-attempted",
19298
- reason: "git-commit-failed"
19299
- };
19334
+ };
19335
+ const installReactDoctorGitHookStep = (gitHookTarget) => {
19336
+ const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
19337
+ try {
19338
+ const hookResult = installReactDoctorGitHook({
19339
+ hookPath: gitHookTarget.hookPath,
19340
+ projectRoot: gitHookTarget.runnerRoot,
19341
+ kind: gitHookTarget.kind,
19342
+ hooksPathConfig: gitHookTarget.hooksPathConfig
19343
+ });
19344
+ hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
19345
+ recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
19346
+ } catch (error) {
19347
+ hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
19348
+ throw error;
19300
19349
  }
19301
- if (!(await run("git", [
19302
- "push",
19303
- "-u",
19304
- "origin",
19305
- newBranch
19306
- ], cwd)).success) {
19307
- await restoreToPreviousBranch(true);
19308
- return {
19309
- status: "not-attempted",
19310
- reason: "git-push-failed"
19311
- };
19350
+ };
19351
+ const installReactDoctorAgentHooksStep = (projectRoot, selectedAgents) => {
19352
+ const hookSpinner = spinner("Installing React Doctor agent hooks...").start();
19353
+ try {
19354
+ const hookResult = installReactDoctorAgentHooks({
19355
+ projectRoot,
19356
+ agents: selectedAgents
19357
+ });
19358
+ if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
19359
+ else {
19360
+ hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19361
+ recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
19362
+ }
19363
+ } catch (error) {
19364
+ hookSpinner.fail("Failed to install React Doctor agent hooks.");
19365
+ throw error;
19312
19366
  }
19313
- const prCreate = await run("gh", [
19314
- "pr",
19315
- "create",
19316
- "--title",
19317
- prTitle,
19318
- "--body",
19319
- prBody,
19320
- "--base",
19321
- defaultBranch,
19322
- "--head",
19323
- newBranch
19324
- ], cwd);
19325
- await restoreToPreviousBranch(false);
19326
- if (!prCreate.success) return {
19327
- status: "branch-pushed",
19328
- branch: newBranch
19329
- };
19330
- return {
19331
- status: "pr-opened",
19332
- url: prCreate.stdout.split(/\r?\n/).filter(Boolean).pop() ?? ""
19333
- };
19334
19367
  };
19335
- const stageWorkflowFile = async (params) => {
19336
- const workflowPath = path$1.resolve(params.workflowPath);
19337
- const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
19338
- if (!repoRootProbe.success) return false;
19339
- return (await run("git", [
19340
- "add",
19341
- "--",
19342
- path$1.relative(repoRootProbe.stdout, workflowPath)
19343
- ], repoRootProbe.stdout)).success;
19368
+ const installReactDoctorWorkflowStep = (projectRoot) => {
19369
+ return reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
19370
+ };
19371
+ const upgradeReactDoctorWorkflowStep = (projectRoot) => {
19372
+ const workflowSpinner = spinner("Upgrading GitHub Actions workflow to v2...").start();
19373
+ const upgradeResult = upgradeReactDoctorWorkflowInPlace(projectRoot);
19374
+ if (upgradeResult.status === "failed") {
19375
+ workflowSpinner.fail("Couldn't update the GitHub Actions workflow.");
19376
+ return false;
19377
+ }
19378
+ if (upgradeResult.status === "not-needed") {
19379
+ workflowSpinner.succeed("GitHub Actions workflow already up to date.");
19380
+ return false;
19381
+ }
19382
+ workflowSpinner.succeed(`Upgraded the GitHub Actions workflow to v2 at ${path$1.relative(projectRoot, upgradeResult.workflowPath)}.`);
19383
+ recordCount(METRIC.installWorkflow, 1, { kind: "upgrade" });
19384
+ return true;
19385
+ };
19386
+ const runInstallReactDoctor = async (options = {}) => {
19387
+ const requestedProjectRoot = options.projectRoot ?? process.cwd();
19388
+ const projectRoot = findNearestPackageDirectory(requestedProjectRoot) ?? requestedProjectRoot;
19389
+ const sourceDir = options.sourceDir ?? getSkillSourceDirectory();
19390
+ if (!fs$1.existsSync(path$1.join(sourceDir, SKILL_MANIFEST_FILE))) {
19391
+ cliLogger.error(`Could not locate the ${SKILL_NAME} skill bundled with this package.`);
19392
+ process.exitCode = 1;
19393
+ return;
19394
+ }
19395
+ const detectedAgents = options.detectedAgents ?? await detectAvailableAgents();
19396
+ if (detectedAgents.length === 0) {
19397
+ cliLogger.error("No supported coding agents detected.");
19398
+ cliLogger.dim(" Looked for binaries on PATH (claude, codex, cursor, droid, gemini, copilot, opencode, pi)");
19399
+ cliLogger.dim(" and config dirs in $HOME (~/.claude, ~/.cursor, ~/.codex, ~/.gemini, ...).");
19400
+ process.exitCode = 1;
19401
+ return;
19402
+ }
19403
+ const skipPrompts = shouldSkipPrompts({ yes: options.yes });
19404
+ const gitHookTarget = options.gitHookPath === void 0 ? detectGitHookTarget(projectRoot) : options.gitHookPath === null ? null : buildManualGitHookTarget(options.gitHookPath, projectRoot);
19405
+ const gitHookPath = gitHookTarget?.hookPath;
19406
+ const promptOptions = options.onPromptCancel === void 0 ? {} : { onCancel: options.onPromptCancel };
19407
+ const prompt = options.prompt ?? prompts;
19408
+ const workflowTargetPath = getReactDoctorWorkflowPath(projectRoot);
19409
+ const existingWorkflow = readReactDoctorWorkflow(projectRoot);
19410
+ const canInstallWorkflow = !fs$1.existsSync(workflowTargetPath);
19411
+ const canUpgradeWorkflow = existingWorkflow !== null && workflowUsesV1Action(existingWorkflow.content) && !hasHandledActionUpgrade(projectRoot);
19412
+ const shouldInstallWorkflow = canInstallWorkflow && (Boolean(options.yes) || !skipPrompts && await askAddToGitHubActions(prompt) === "yes");
19413
+ const upgradePromptOutcome = canUpgradeWorkflow && !options.yes && !skipPrompts ? await askUpgradeActionVersion(prompt) : null;
19414
+ const shouldUpgradeWorkflow = canUpgradeWorkflow && (Boolean(options.yes) || upgradePromptOutcome === "yes");
19415
+ if (upgradePromptOutcome === "no" && !options.dryRun) recordActionUpgradeDecision(projectRoot, "declined");
19416
+ const selectedAgents = skipPrompts ? detectedAgents : (await prompt({
19417
+ type: "multiselect",
19418
+ name: "agents",
19419
+ message: `Install the ${highlighter.info(`/react-doctor`)} skill for:`,
19420
+ choices: detectedAgents.map((agent) => ({
19421
+ title: getSkillAgentConfig(agent).displayName,
19422
+ value: agent,
19423
+ selected: true
19424
+ })),
19425
+ instructions: false,
19426
+ min: 1
19427
+ }, promptOptions)).agents ?? [];
19428
+ if (selectedAgents.length === 0) return;
19429
+ let dependencyResult;
19430
+ if (!options.dryRun) {
19431
+ await installReactDoctorSkillStep(sourceDir, selectedAgents, projectRoot);
19432
+ dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
19433
+ }
19434
+ let didInstallWorkflow = false;
19435
+ if (!options.dryRun && (shouldInstallWorkflow || shouldUpgradeWorkflow)) {
19436
+ cliLogger.break();
19437
+ if (shouldInstallWorkflow) didInstallWorkflow = installReactDoctorWorkflowStep(projectRoot);
19438
+ else if (upgradeReactDoctorWorkflowStep(projectRoot)) recordActionUpgradeDecision(projectRoot, "accepted");
19439
+ }
19440
+ const setupActionChoices = [...gitHookPath === null || gitHookPath === void 0 ? [] : [{
19441
+ title: "Pre-commit hook",
19442
+ description: "Check staged changes before each commit",
19443
+ value: SETUP_OPTION_GIT_HOOK,
19444
+ selected: true
19445
+ }], ...canInstallNativeAgentHooks(selectedAgents) ? [{
19446
+ title: "Agent hooks",
19447
+ description: "Ask Claude Code or Cursor to scan after code edits",
19448
+ value: SETUP_OPTION_AGENT_HOOKS,
19449
+ selected: Boolean(options.agentHooks)
19450
+ }] : []];
19451
+ const setupChoices = setupActionChoices.length === 0 ? [] : [{
19452
+ title: "Skip optional setup",
19453
+ description: "Install only the agent skill and package setup",
19454
+ value: SETUP_OPTION_SKIP,
19455
+ selected: false
19456
+ }, ...setupActionChoices];
19457
+ if (setupChoices.length > 0 && !options.dryRun) cliLogger.break();
19458
+ const selectedSetupOptions = skipPrompts || setupChoices.length === 0 ? [] : (await prompt({
19459
+ type: "multiselect",
19460
+ name: "setupOptions",
19461
+ message: "Select additional React Doctor setup:",
19462
+ choices: setupChoices,
19463
+ instructions: false
19464
+ }, promptOptions)).setupOptions ?? [];
19465
+ const selectedSetupActions = selectedSetupOptions.filter((setupOption) => setupOption !== SETUP_OPTION_SKIP);
19466
+ const didSkipOptionalSetup = selectedSetupActions.length === 0 && selectedSetupOptions.includes(SETUP_OPTION_SKIP);
19467
+ const shouldInstallGitHook = gitHookPath != null && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_GIT_HOOK));
19468
+ const shouldInstallAgentHooks = Boolean(options.agentHooks) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_AGENT_HOOKS);
19469
+ if (!options.dryRun) {
19470
+ if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) installReactDoctorGitHookStep(gitHookTarget);
19471
+ if (shouldInstallAgentHooks) installReactDoctorAgentHooksStep(projectRoot, selectedAgents);
19472
+ }
19473
+ if (options.dryRun) {
19474
+ cliLogger.log(`Dry run — would install ${SKILL_NAME} skill for:`);
19475
+ for (const agent of selectedAgents) cliLogger.dim(` - ${getSkillAgentConfig(agent).displayName}`);
19476
+ cliLogger.dim(` Source: ${sourceDir}`);
19477
+ cliLogger.dim(" Package script: doctor (or react-doctor if doctor exists)");
19478
+ cliLogger.dim(" Dev dependency: react-doctor");
19479
+ if (shouldInstallGitHook) cliLogger.dim(` Git hook: ${gitHookPath}`);
19480
+ if (shouldInstallAgentHooks) cliLogger.dim(" Agent hooks: Claude Code / Cursor when selected");
19481
+ if (shouldInstallWorkflow) cliLogger.dim(` GitHub Actions workflow: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19482
+ if (shouldUpgradeWorkflow) cliLogger.dim(` Upgrade GitHub Actions workflow to v2: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19483
+ return;
19484
+ }
19485
+ recordCount(METRIC.installCompleted, 1, {
19486
+ agentsCount: selectedAgents.length,
19487
+ gitHook: shouldInstallGitHook,
19488
+ agentHooks: shouldInstallAgentHooks,
19489
+ workflow: didInstallWorkflow,
19490
+ dependencyStatus: dependencyResult?.dependencyStatus ?? "skipped",
19491
+ packageManager: detectPackageManager(projectRoot)
19492
+ });
19493
+ for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
19494
+ };
19495
+ //#endregion
19496
+ //#region src/cli/utils/install-skill-for-agent.ts
19497
+ const installReactDoctorSkillForAgent = async (agent, projectRoot) => {
19498
+ const source = getSkillSourceDirectory();
19499
+ if (!fs$1.existsSync(path$1.join(source, SKILL_MANIFEST_FILE))) return false;
19500
+ const result = await installSkillsFromSource({
19501
+ source,
19502
+ agents: [agent],
19503
+ cwd: projectRoot,
19504
+ mode: "copy"
19505
+ });
19506
+ return result.skills.length > 0 && result.failed.length === 0;
19344
19507
  };
19345
19508
  //#endregion
19346
19509
  //#region src/cli/utils/launch-agent.ts
@@ -19431,9 +19594,6 @@ const copyToClipboard = (text) => {
19431
19594
  };
19432
19595
  //#endregion
19433
19596
  //#region src/cli/utils/handoff-to-agent.ts
19434
- const CI_YES_CHOICE = "ci-yes";
19435
- const CI_LEARN_MORE_CHOICE = "ci-learn-more";
19436
- const CI_NO_CHOICE = "ci-no";
19437
19597
  const CLIPBOARD_CHOICE = "clipboard";
19438
19598
  const SKIP_CHOICE = "skip";
19439
19599
  const printPayload = (payload) => {
@@ -19442,59 +19602,11 @@ const printPayload = (payload) => {
19442
19602
  cliLogger.log(payload);
19443
19603
  cliLogger.log(highlighter.dim("──────────────────────"));
19444
19604
  };
19445
- const setUpGitHubActions = async (rootDirectory) => {
19446
- const projectRoot = findNearestPackageDirectory(rootDirectory) ?? rootDirectory;
19447
- try {
19448
- installReactDoctorScriptStep(projectRoot);
19449
- } catch {}
19450
- const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
19451
- const workflowResult = installReactDoctorWorkflow(projectRoot);
19452
- reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
19453
- cliLogger.break();
19454
- if (workflowResult.status === "failed") {
19455
- cliLogger.log(` Couldn't set up GitHub Actions automatically. Follow the guide at ${highlighter.info(CI_URL)}`);
19456
- return;
19457
- }
19458
- if (workflowResult.status === "created") {
19459
- const pullRequestSpinner = spinner("Opening a pull request for review...").start();
19460
- const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
19461
- if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
19462
- else if (pullRequestResult.status === "branch-pushed") pullRequestSpinner.warn(`Pushed branch ${highlighter.bold(pullRequestResult.branch)} but couldn't open a PR. Open one with: gh pr create --head ${pullRequestResult.branch}`);
19463
- else {
19464
- pullRequestSpinner.stop();
19465
- if (await stageWorkflowFile({ workflowPath: workflowResult.workflowPath })) cliLogger.log(` Staged the workflow file. Commit it to start scanning every pull request.`);
19466
- else cliLogger.log(" React Doctor will now scan every new pull request automatically.");
19467
- }
19468
- }
19469
- cliLogger.log(` Learn more: ${highlighter.info(CI_URL)}`);
19470
- };
19471
- const UPGRADE_YES_CHOICE = "upgrade-yes";
19472
- const UPGRADE_NO_CHOICE = "upgrade-no";
19473
19605
  const UPGRADE_COMMIT_MESSAGE = "ci: upgrade React Doctor GitHub Action to v2";
19474
19606
  const UPGRADE_PR_TITLE = "Upgrade React Doctor Action to v2";
19475
19607
  const UPGRADE_PR_BODY = `Bumps the React Doctor GitHub Actions workflow to the action's latest major, \`millionco/react-doctor@v2\`.
19476
19608
 
19477
19609
  Docs: https://www.react.doctor/ci`;
19478
- const askUpgradeActionVersion = async () => {
19479
- const { upgradeChoice } = await prompts({
19480
- type: "select",
19481
- name: "upgradeChoice",
19482
- message: "A new major of the React Doctor Action (v2) is out. Upgrade this repo's workflow?",
19483
- hint: " ",
19484
- choices: [{
19485
- title: "Yes (recommended)",
19486
- description: "Open a PR bumping the workflow to millionco/react-doctor@v2",
19487
- value: UPGRADE_YES_CHOICE
19488
- }, {
19489
- title: "No, thanks",
19490
- description: "Keep @v1 — won't ask again for this repo",
19491
- value: UPGRADE_NO_CHOICE
19492
- }],
19493
- initial: 0
19494
- }, { onCancel: () => true });
19495
- if (upgradeChoice === void 0) return "cancel";
19496
- return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
19497
- };
19498
19610
  const upgradeGitHubActionsWorkflow = async (workflow) => {
19499
19611
  const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
19500
19612
  if (!changed) return false;
@@ -19539,46 +19651,6 @@ const maybeOfferActionUpgrade = async (projectRoot) => {
19539
19651
  }
19540
19652
  if (await upgradeGitHubActionsWorkflow(workflow)) recordActionUpgradeDecision(projectRoot, "accepted");
19541
19653
  };
19542
- const SGR_BOLD_OFF = "\x1B[22m";
19543
- const ciQuestionMessage = [
19544
- "Add React Doctor to GitHub Actions?",
19545
- `${SGR_BOLD_OFF} ${highlighter.dim("Scan every pull request to prevent new React issues while you fix the backlog.")}`,
19546
- `${SGR_BOLD_OFF} ${highlighter.dim(`Used by teams at ${CI_TRUST_COMPANIES}.`)}`
19547
- ].join("\n");
19548
- const askAddToGitHubActions = async () => {
19549
- while (true) {
19550
- const { ciChoice } = await prompts({
19551
- type: "select",
19552
- name: "ciChoice",
19553
- message: ciQuestionMessage,
19554
- hint: " ",
19555
- choices: [
19556
- {
19557
- title: "Yes (recommended)",
19558
- description: "Adds the workflow file and a doctor package script",
19559
- value: CI_YES_CHOICE
19560
- },
19561
- {
19562
- title: "Learn more",
19563
- description: highlighter.info(CI_URL),
19564
- value: CI_LEARN_MORE_CHOICE
19565
- },
19566
- {
19567
- title: "No, thanks",
19568
- description: "Continue to the agent handoff",
19569
- value: CI_NO_CHOICE
19570
- }
19571
- ],
19572
- initial: 0
19573
- }, { onCancel: () => true });
19574
- if (ciChoice === void 0) return "cancel";
19575
- if (ciChoice === CI_YES_CHOICE) return "yes";
19576
- if (ciChoice === CI_NO_CHOICE) return "no";
19577
- const opened = openUrl(CI_URL);
19578
- cliLogger.log(opened ? `Opened ${highlighter.info(CI_URL)} in your browser.` : `Visit ${highlighter.info(CI_URL)} to learn more.`);
19579
- cliLogger.break();
19580
- }
19581
- };
19582
19654
  const detectLaunchableAgents = async () => {
19583
19655
  const detected = new Set(await detectAvailableAgents());
19584
19656
  return Object.keys(CLI_AGENT_BINARIES).filter((agentId) => detected.has(agentId) && isCommandAvailable(CLI_AGENT_BINARIES[agentId]));
@@ -19595,7 +19667,7 @@ const handoffToAgent = async (input) => {
19595
19667
  });
19596
19668
  if (ciOutcome === "cancel") return;
19597
19669
  if (ciOutcome === "yes") {
19598
- await setUpGitHubActions(input.rootDirectory);
19670
+ await setUpGitHubActions({ rootDirectory: input.rootDirectory });
19599
19671
  cliLogger.break();
19600
19672
  }
19601
19673
  } else await maybeOfferActionUpgrade(projectRootForCi);
@@ -19746,6 +19818,14 @@ const HAPPY_FACE_LINES = [
19746
19818
  "│ ▽ │",
19747
19819
  "└─────┘"
19748
19820
  ];
19821
+ const FACE_INDENT = " ";
19822
+ const FACE_PREFIX_WIDTH = 2 + (HAPPY_FACE_LINES[0]?.length ?? 0) + 2;
19823
+ const clampToColumns = (text, maxColumns) => {
19824
+ if (maxColumns <= 0) return "";
19825
+ if (text.length <= maxColumns) return text;
19826
+ if (maxColumns === 1) return "…";
19827
+ return `${text.slice(0, maxColumns - 1).trimEnd()}…`;
19828
+ };
19749
19829
  const typeLine = (linePrefix, text, style, charDelayMs) => Effect.gen(function* () {
19750
19830
  const characters = [...text];
19751
19831
  for (let length = 1; length <= characters.length; length += 1) {
@@ -19759,13 +19839,17 @@ const playWelcomeScene = (options = {}) => Effect.gen(function* () {
19759
19839
  const interLineDelayMs = 250 / speedMultiplier;
19760
19840
  const explanationHoldMs = WELCOME_EXPLANATION_HOLD_MS / speedMultiplier;
19761
19841
  const face = HAPPY_FACE_LINES.map((line) => highlighter.success(line));
19762
- const mouthPrefix = ` ${face[2] ?? ""} `;
19763
- yield* writeStdout(`\n${face.map((line) => ` ${line}`).join("\n")}\n`);
19842
+ const mouthPrefix = `${FACE_INDENT}${face[2] ?? ""}${FACE_INDENT}`;
19843
+ const terminalColumns = process.stdout.columns;
19844
+ const availableTextColumns = terminalColumns && terminalColumns > 0 ? Math.max(0, terminalColumns - FACE_PREFIX_WIDTH - 1) : Number.POSITIVE_INFINITY;
19845
+ const greeting = clampToColumns("Welcome to React Doctor", availableTextColumns);
19846
+ const tagline = clampToColumns("I diagnose your React code for bugs, security & performance.", availableTextColumns);
19847
+ yield* writeStdout(`\n${face.map((line) => `${FACE_INDENT}${line}`).join("\n")}\n`);
19764
19848
  yield* writeStdout("\x1B[3A");
19765
- yield* typeLine(` ${face[1] ?? ""} `, "Welcome to React Doctor", (fragment) => highlighter.bold(fragment), charDelayMs);
19849
+ yield* typeLine(`${FACE_INDENT}${face[1] ?? ""}${FACE_INDENT}`, greeting, (fragment) => highlighter.bold(fragment), charDelayMs);
19766
19850
  yield* Effect.sleep(interLineDelayMs);
19767
19851
  yield* writeStdout("\x1B[1B");
19768
- yield* typeLine(mouthPrefix, "I diagnose your React code for bugs, security & performance.", (fragment) => highlighter.dim(fragment), charDelayMs);
19852
+ yield* typeLine(mouthPrefix, tagline, (fragment) => highlighter.dim(fragment), charDelayMs);
19769
19853
  yield* Effect.sleep(explanationHoldMs);
19770
19854
  yield* writeStdout("\x1B[3A\r\x1B[0J");
19771
19855
  });
@@ -19874,8 +19958,9 @@ const findLowestScoredScan = (completedScans) => {
19874
19958
  };
19875
19959
  const printMultiProjectSummary = (input) => Effect.gen(function* () {
19876
19960
  const { completedScans, userConfig, verbose, isOffline, projectName } = input;
19961
+ const categoryFilters = input.categoryFilters ?? /* @__PURE__ */ new Set();
19877
19962
  const animateRender = !verbose && canAnimateOnboarding(process.stdout);
19878
- const surfaceDiagnostics = filterDiagnosticsForSurface(completedScans.flatMap((scan) => scan.result.diagnostics), "cli", userConfig);
19963
+ const displayDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface(completedScans.flatMap((scan) => scan.result.diagnostics), "cli", userConfig), categoryFilters);
19879
19964
  const projectRootByDiagnostic = /* @__PURE__ */ new WeakMap();
19880
19965
  for (const scan of completedScans) for (const diagnostic of scan.result.diagnostics) projectRootByDiagnostic.set(diagnostic, scan.result.project.rootDirectory);
19881
19966
  const resolveDiagnosticSourceRoot = (diagnostic) => projectRootByDiagnostic.get(diagnostic) ?? "";
@@ -19889,29 +19974,30 @@ const printMultiProjectSummary = (input) => Effect.gen(function* () {
19889
19974
  const totalScannedFileCount = uniqueScannedFilePaths.size + fileCountFromScansWithoutPaths;
19890
19975
  const totalScanElapsedMilliseconds = completedScans.reduce((sum, scan) => sum + (scan.result.scanElapsedMilliseconds ?? scan.result.elapsedMilliseconds), 0);
19891
19976
  yield* Console.log(`${highlighter.success("✔")} Scanned ${totalScannedFileCount} ${totalScannedFileCount === 1 ? "file" : "files"} in ${formatElapsedTime(totalScanElapsedMilliseconds)}`);
19892
- if (surfaceDiagnostics.length > 0) {
19977
+ if (displayDiagnostics.length > 0) {
19893
19978
  yield* Console.log("");
19894
- yield* printDiagnostics(surfaceDiagnostics, verbose, resolveDiagnosticSourceRoot, buildRulePriorityMap(completedScans.map((scan) => scan.result.score)), isCodingAgentEnvironment(), { animateCountUp: animateRender });
19979
+ yield* printDiagnostics(displayDiagnostics, verbose, resolveDiagnosticSourceRoot, buildRulePriorityMap(completedScans.map((scan) => scan.result.score)), isCodingAgentEnvironment(), { animateCountUp: animateRender });
19895
19980
  }
19896
19981
  const lowestScoredScan = findLowestScoredScan(completedScans);
19897
19982
  const aggregateScore = lowestScoredScan?.result.score ?? null;
19898
19983
  const totalSourceFileCount = completedScans.reduce((sum, scan) => sum + scan.result.project.sourceFileCount, 0);
19899
19984
  yield* printSummary({
19900
- diagnostics: surfaceDiagnostics,
19985
+ diagnostics: displayDiagnostics,
19901
19986
  elapsedMilliseconds: completedScans.reduce((sum, scan) => sum + scan.result.elapsedMilliseconds, 0),
19902
19987
  scoreResult: aggregateScore,
19903
- potentialScore: lowestScoredScan ? yield* Effect.promise(() => computeProjectedScore(surfaceDiagnostics, lowestScoredScan.result.diagnostics, lowestScoredScan.result.score)) : null,
19988
+ potentialScore: lowestScoredScan ? yield* Effect.promise(() => computeProjectedScore(displayDiagnostics, filterDiagnosticsForSurface(lowestScoredScan.result.diagnostics, "cli", userConfig), lowestScoredScan.result.score)) : null,
19904
19989
  totalSourceFileCount,
19905
19990
  noScoreMessage: "Score unavailable.",
19906
19991
  verbose,
19907
19992
  animateProjection: animateRender
19908
19993
  });
19909
19994
  const entries = completedScans.map((scan) => {
19910
- const errorCount = scan.result.diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
19995
+ const projectDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface([...scan.result.diagnostics], "cli", userConfig), categoryFilters);
19996
+ const errorCount = projectDiagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
19911
19997
  return {
19912
19998
  projectName: scan.result.project.projectName,
19913
19999
  score: scan.result.score?.score ?? null,
19914
- issueCount: scan.result.diagnostics.length,
20000
+ issueCount: projectDiagnostics.length,
19915
20001
  errorCount
19916
20002
  };
19917
20003
  });
@@ -19919,7 +20005,7 @@ const printMultiProjectSummary = (input) => Effect.gen(function* () {
19919
20005
  yield* Console.log("");
19920
20006
  for (const entry of entries) yield* Console.log(buildSummaryLine(entry, longestProjectNameLength));
19921
20007
  yield* printFooter({
19922
- diagnostics: surfaceDiagnostics,
20008
+ diagnostics: displayDiagnostics,
19923
20009
  scoreResult: aggregateScore,
19924
20010
  projectName,
19925
20011
  isOffline
@@ -20009,7 +20095,8 @@ const resolveCliInspectOptions = (flags, userConfig) => {
20009
20095
  noScore: flags.score === false || flags.telemetry === false || (userConfig?.noScore ?? false),
20010
20096
  isCi: isCiEnvironment(),
20011
20097
  silent: Boolean(flags.json),
20012
- concurrency: resolveParallelFlag(flags.parallel)
20098
+ concurrency: resolveParallelFlag(flags.parallel),
20099
+ categoryFilters: resolveCliCategories(flags.category)
20013
20100
  };
20014
20101
  };
20015
20102
  //#endregion
@@ -20262,6 +20349,16 @@ const validateModeFlags = (flags) => {
20262
20349
  };
20263
20350
  //#endregion
20264
20351
  //#region src/cli/commands/inspect.ts
20352
+ const filterCompletedScansByCategories = (completedScans, categoryFilters) => {
20353
+ if (categoryFilters.size === 0) return [...completedScans];
20354
+ return completedScans.map((scan) => ({
20355
+ ...scan,
20356
+ result: {
20357
+ ...scan.result,
20358
+ diagnostics: filterDiagnosticsByCategories(scan.result.diagnostics, categoryFilters)
20359
+ }
20360
+ }));
20361
+ };
20265
20362
  /**
20266
20363
  * Post-scan finalization shared by the staged-arm and project-loop
20267
20364
  * paths of `inspectAction`: emit the JSON report (when in JSON mode)
@@ -20274,6 +20371,7 @@ const finalizeScans = (input) => {
20274
20371
  const baselineComputed = input.completedScans.length > 0 && input.completedScans.every((scan) => scan.result.baselineDelta !== void 0);
20275
20372
  const baselineDegraded = input.baselineIntended && !baselineComputed;
20276
20373
  const mode = baselineDegraded ? "diff" : input.mode;
20374
+ const jsonCompletedScans = filterCompletedScansByCategories(input.completedScans, input.categoryFilters);
20277
20375
  if (input.isJsonMode) {
20278
20376
  const baseline = baselineComputed && baselineDeltas.length > 0 ? {
20279
20377
  baseRef: baselineDeltas[0].baseRef,
@@ -20285,7 +20383,7 @@ const finalizeScans = (input) => {
20285
20383
  directory: input.resolvedDirectory,
20286
20384
  mode,
20287
20385
  diff: input.diff,
20288
- scans: input.completedScans,
20386
+ scans: jsonCompletedScans,
20289
20387
  totalElapsedMilliseconds: performance.now() - input.startTime,
20290
20388
  baseline
20291
20389
  }));
@@ -20359,6 +20457,7 @@ const inspectAction = async (directory, flags) => {
20359
20457
  await Effect.runPromise(playWelcomeScene({ speedMultiplier: isReturningUser ? 2 : 1 }));
20360
20458
  } else Effect.runSync(printBrandedHeader);
20361
20459
  const scanOptions = resolveCliInspectOptions(flags, userConfig);
20460
+ const categoryFilters = new Set(scanOptions.categoryFilters ?? []);
20362
20461
  const skipPrompts = shouldSkipPrompts({
20363
20462
  yes: flags.yes,
20364
20463
  json: flags.json
@@ -20419,6 +20518,7 @@ const inspectAction = async (directory, flags) => {
20419
20518
  isJsonMode,
20420
20519
  isScoreOnly,
20421
20520
  flags,
20521
+ categoryFilters,
20422
20522
  userConfig,
20423
20523
  resolvedDirectory,
20424
20524
  startTime
@@ -20478,6 +20578,7 @@ const inspectAction = async (directory, flags) => {
20478
20578
  const shouldShowShareLink = !scanOptions.noScore && (userConfig?.share ?? true) && !scanOptions.isCi;
20479
20579
  await Effect.runPromise(printMultiProjectSummary({
20480
20580
  completedScans,
20581
+ categoryFilters,
20481
20582
  userConfig,
20482
20583
  verbose: Boolean(flags.verbose),
20483
20584
  isOffline: !shouldShowShareLink,
@@ -20493,14 +20594,15 @@ const inspectAction = async (directory, flags) => {
20493
20594
  isJsonMode,
20494
20595
  isScoreOnly,
20495
20596
  flags,
20597
+ categoryFilters,
20496
20598
  userConfig,
20497
20599
  resolvedDirectory,
20498
20600
  startTime
20499
20601
  });
20500
- const surfaceDiagnostics = filterDiagnosticsForSurface(allDiagnostics, scanOptions.outputSurface ?? "cli", userConfig);
20501
- if (!isQuiet && !skipPrompts && process.stdout.isTTY === true && !isCiOrCodingAgentEnvironment() && surfaceDiagnostics.length > 0) {
20602
+ const selectedSurfaceDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface(allDiagnostics, scanOptions.outputSurface ?? "cli", userConfig), categoryFilters);
20603
+ if (!isQuiet && !skipPrompts && process.stdout.isTTY === true && !isCiOrCodingAgentEnvironment() && selectedSurfaceDiagnostics.length > 0) {
20502
20604
  await handoffToAgent({
20503
- diagnostics: surfaceDiagnostics,
20605
+ diagnostics: selectedSurfaceDiagnostics,
20504
20606
  projectName: path$1.basename(resolvedDirectory),
20505
20607
  rootDirectory: resolvedDirectory,
20506
20608
  interactive: true
@@ -20931,7 +21033,7 @@ const rulesListAction = async (options) => {
20931
21033
  });
20932
21034
  const catalog = buildRuleCatalog();
20933
21035
  const config = validateConfigTypes((await resolveRuleConfigTarget(resolveProjectRoot(options))).config);
20934
- const categoryFilter = options.category?.toLowerCase();
21036
+ const categoryFilter = typeof options.category === "string" ? options.category.toLowerCase() : void 0;
20935
21037
  const frameworkFilter = options.framework?.toLowerCase();
20936
21038
  const rows = catalog.filter((entry) => {
20937
21039
  if (categoryFilter && entry.category.toLowerCase() !== categoryFilter) return false;
@@ -21294,6 +21396,7 @@ const ROOT_FLAG_SPEC = {
21294
21396
  "--yes"
21295
21397
  ]),
21296
21398
  longOptionsWithRequiredValues: new Set([
21399
+ "--category",
21297
21400
  "--changed-files-from",
21298
21401
  "--blocking",
21299
21402
  "--fail-on",
@@ -21450,6 +21553,7 @@ ${formatExampleLines([
21450
21553
  ["react-doctor ./apps/web", "scan a specific directory"],
21451
21554
  ["react-doctor --diff main", "scan only files changed vs. main"],
21452
21555
  ["react-doctor --staged", "scan staged files (pre-commit hook)"],
21556
+ ["react-doctor --category Security", "show only one diagnostic category"],
21453
21557
  ["react-doctor --blocking warning", "fail CI on warnings too (default: error)"],
21454
21558
  ["react-doctor --json > report.json", "write a machine-readable report"],
21455
21559
  ["react-doctor why src/App.tsx:42", "explain why a rule fired there"],
@@ -21478,7 +21582,8 @@ ${formatExampleLines([
21478
21582
  ${highlighter.dim("Learn more:")}
21479
21583
  ${highlighter.info(CANONICAL_GITHUB_URL)}
21480
21584
  `;
21481
- const program = new Command().name("react-doctor").description("Diagnose React codebase health").version(VERSION, "-v, --version", "display the version number").argument("[directory]", "project directory to scan", ".").option("--lint", "enable linting").option("--no-lint", "skip linting").option("--dead-code", "enable dead-code analysis (default)").option("--no-dead-code", "skip dead-code analysis (unused files / exports / dependencies, circular imports)").option("--verbose", "show every rule and per-file details (default shows top 3 rules)").option("--score", "output only the score").option("--json", "output a single structured JSON report (suppresses other output)").option("--json-compact", "with --json, emit compact JSON (no indentation)").option("-y, --yes", "skip prompts, scan all workspace projects").option("--no-parallel", "lint serially with one worker (default: parallel across CPU cores; set the worker count with REACT_DOCTOR_PARALLEL)").option("--project <name>", "select workspace project (comma-separated for multiple)").option("--diff [base]", "scan only files changed vs base branch (pass `false` to force a full scan, overriding config)").addOption(new Option$1("--changed-files-from <file>", "scan source files listed in a newline-delimited changed-files file").hideHelp()).option("--no-score", "skip the score API, the share URL, and crash reporting").option("--no-telemetry", "alias for --no-score (skip the score API, share URL, and crash reporting)").option("--staged", "scan only staged (git index) files for pre-commit hooks").option("--blocking <level>", "severity that fails CI: error (default), warning, or none (advisory)").addOption(new Option$1("--fail-on <level>", "[deprecated] alias for --blocking <level>").hideHelp()).option("--no-respect-inline-disables", "audit mode: neutralize inline lint suppressions before scanning").option("--warnings", "show warning-severity diagnostics (default)").option("--no-warnings", "hide warning-severity diagnostics (errors only)").option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").addHelpText("after", renderRootHelpEpilog);
21585
+ const collectCategoryOption = (value, previousValues) => [...previousValues ?? [], value];
21586
+ const program = new Command().name("react-doctor").description("Diagnose React codebase health").version(VERSION, "-v, --version", "display the version number").argument("[directory]", "project directory to scan", ".").option("--lint", "enable linting").option("--no-lint", "skip linting").option("--dead-code", "enable dead-code analysis (default)").option("--no-dead-code", "skip dead-code analysis (unused files / exports / dependencies, circular imports)").option("--verbose", "show every rule and per-file details (default shows top 3 rules)").option("--score", "output only the score").option("--json", "output a single structured JSON report (suppresses other output)").option("--json-compact", "with --json, emit compact JSON (no indentation)").option("-y, --yes", "skip prompts, scan all workspace projects").option("--no-parallel", "lint serially with one worker (default: parallel across CPU cores; set the worker count with REACT_DOCTOR_PARALLEL)").option("--project <name>", "select workspace project (comma-separated for multiple)").option("--diff [base]", "scan only files changed vs base branch (pass `false` to force a full scan, overriding config)").addOption(new Option$1("--changed-files-from <file>", "scan source files listed in a newline-delimited changed-files file").hideHelp()).option("--no-score", "skip the score API, the share URL, and crash reporting").addOption(new Option$1("--category <category>", "only show diagnostics in a category (repeatable; e.g. Security)").argParser(collectCategoryOption)).option("--no-telemetry", "alias for --no-score (skip the score API, share URL, and crash reporting)").option("--staged", "scan only staged (git index) files for pre-commit hooks").option("--blocking <level>", "severity that fails CI: error (default), warning, or none (advisory)").addOption(new Option$1("--fail-on <level>", "[deprecated] alias for --blocking <level>").hideHelp()).option("--no-respect-inline-disables", "audit mode: neutralize inline lint suppressions before scanning").option("--warnings", "show warning-severity diagnostics (default)").option("--no-warnings", "hide warning-severity diagnostics (errors only)").option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").addHelpText("after", renderRootHelpEpilog);
21482
21587
  program.action(inspectAction);
21483
21588
  program.command("why <location>").description("Explain why a rule fired (or why a suppression didn't apply) at a file:line").option("--project <name>", "select workspace project (comma-separated for multiple)").option("-c, --cwd <cwd>", "working directory", process.cwd()).option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").action((location, options) => whyAction(location, options));
21484
21589
  program.command("install").alias("setup").description("Install the react-doctor skill into your coding agents and optional git hook").option("-y, --yes", "skip prompts, install for all detected agents").option("--dry-run", "show what would be installed without writing files").option("--agent-hooks", "install native non-blocking agent hooks for Claude Code and Cursor").option("-c, --cwd <cwd>", "working directory", process.cwd()).option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").addHelpText("after", renderInstallHelpEpilog).action(installAction);
@@ -21521,4 +21626,4 @@ Promise.resolve().then(() => assertNoRemovedFlags(process.argv)).then(() => prog
21521
21626
  export {};
21522
21627
 
21523
21628
  //# sourceMappingURL=cli.js.map
21524
- //# debugId=1486eaee-ed07-5eef-a9d7-51293140e237
21629
+ //# debugId=d1b95aab-fa59-5a23-83a0-37e1ff08b002