react-doctor 0.4.2-dev.727894a → 0.4.2-dev.829655c

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]="2ea4b3e1-2440-54c8-ae15-199dbd57bbe6")}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";
@@ -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",
@@ -12247,7 +12247,7 @@ const makeNoopConsole = () => ({
12247
12247
  });
12248
12248
  //#endregion
12249
12249
  //#region src/cli/utils/version.ts
12250
- const VERSION = "0.4.2-dev.727894a";
12250
+ const VERSION = "0.4.2-dev.829655c";
12251
12251
  //#endregion
12252
12252
  //#region src/cli/utils/json-mode.ts
12253
12253
  let context = null;
@@ -12605,13 +12605,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
12605
12605
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
12606
12606
  * standard `SENTRY_RELEASE` override.
12607
12607
  */
12608
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.2-dev.727894a`;
12608
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.2-dev.829655c`;
12609
12609
  /**
12610
12610
  * Deployment environment shown in Sentry's environment filter. Defaults to
12611
12611
  * `production` for tagged releases and `development` for dev/unbuilt versions,
12612
12612
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
12613
12613
  */
12614
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.2-dev.727894a") ? "development" : "production");
12614
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.2-dev.829655c") ? "development" : "production");
12615
12615
  /**
12616
12616
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
12617
12617
  * (set to `0` to disable tracing) and falls back to
@@ -16473,8 +16473,22 @@ const buildCodeFrame = (input) => {
16473
16473
  });
16474
16474
  };
16475
16475
  //#endregion
16476
+ //#region src/cli/utils/resolve-measure-width.ts
16477
+ const resolveClampedWidth = (input) => {
16478
+ const terminalColumns = process.stdout.columns;
16479
+ if (!terminalColumns || terminalColumns <= 0) return input.fullWidth;
16480
+ const availableColumns = terminalColumns - input.reservedColumns;
16481
+ return Math.max(input.minWidth, Math.min(input.fullWidth, availableColumns));
16482
+ };
16483
+ const resolveMeasureWidth = (reservedColumns = 0) => resolveClampedWidth({
16484
+ reservedColumns,
16485
+ fullWidth: 60,
16486
+ minWidth: 24
16487
+ });
16488
+ //#endregion
16476
16489
  //#region src/cli/utils/build-section-divider.ts
16477
- const buildSectionDivider = () => highlighter.dim(` ${"─".repeat(60)}`);
16490
+ const DIVIDER_INDENT = " ";
16491
+ const buildSectionDivider = () => highlighter.dim(`${DIVIDER_INDENT}${"─".repeat(resolveMeasureWidth(2))}`);
16478
16492
  //#endregion
16479
16493
  //#region src/cli/utils/indent-multiline-text.ts
16480
16494
  const indentMultilineText = (text, linePrefix) => text.split("\n").map((lineText) => `${linePrefix}${lineText}`).join("\n");
@@ -16634,7 +16648,10 @@ const buildDiagnosticClusterLines = (cluster, resolveSourceRoot, renderCodeFrame
16634
16648
  endLine: isMultiSite ? cluster.endLine : void 0,
16635
16649
  rootDirectory: resolveSourceRoot(lead)
16636
16650
  }) : null;
16637
- if (codeFrame) lines.push(indentMultilineText(boxText(codeFrame, 60), TOP_ERROR_DETAIL_INDENT));
16651
+ if (codeFrame) {
16652
+ const boxInnerWidth = resolveMeasureWidth(8);
16653
+ lines.push(indentMultilineText(boxText(codeFrame, boxInnerWidth), TOP_ERROR_DETAIL_INDENT));
16654
+ }
16638
16655
  const seenHints = /* @__PURE__ */ new Set();
16639
16656
  for (const diagnostic of cluster.diagnostics) if (diagnostic.suppressionHint && !seenHints.has(diagnostic.suppressionHint)) {
16640
16657
  seenHints.add(diagnostic.suppressionHint);
@@ -16652,8 +16669,8 @@ const buildRuleDetailBlock = (ruleKey, ruleDiagnostics, resolveSourceRoot, rende
16652
16669
  const learnMoreLine = formatLearnMoreLine(representative);
16653
16670
  if (learnMoreLine) lines.push(`${TOP_ERROR_DETAIL_INDENT}${highlighter.info(learnMoreLine)}`);
16654
16671
  }
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}`));
16672
+ if (!renderEverySite) for (const explanationLine of wrapTextToWidth(representative.message, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
16673
+ if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
16657
16674
  if (renderEverySite && isAgentEnvironment) {
16658
16675
  const fixRecipeLine = formatFixRecipeLine(representative);
16659
16676
  if (fixRecipeLine) lines.push(highlighter.gray(`${TOP_ERROR_DETAIL_INDENT}${fixRecipeLine}`));
@@ -16847,14 +16864,21 @@ const RAINBOW_HUE_SHIFT_PER_FRAME = 9;
16847
16864
  const RAINBOW_GRADIENT_WIDTH = 80;
16848
16865
  const RAINBOW_OKLCH_LIGHTNESS = .638;
16849
16866
  const RAINBOW_OKLCH_CHROMA = .129;
16867
+ const FACE_BOX_TOP_BORDER = "┌─────┐";
16868
+ const SCORE_RIGHT_COLUMN_OFFSET = 11;
16869
+ const getScoreBarWidth = () => resolveClampedWidth({
16870
+ reservedColumns: SCORE_RIGHT_COLUMN_OFFSET + 1,
16871
+ fullWidth: 50,
16872
+ minWidth: 10
16873
+ });
16850
16874
  const buildScoreBarSegments = (filledCount) => {
16851
- const emptyCount = 50 - filledCount;
16875
+ const emptyCount = Math.max(0, getScoreBarWidth() - filledCount);
16852
16876
  return {
16853
16877
  filledSegment: "█".repeat(filledCount),
16854
16878
  emptySegment: "░".repeat(emptyCount)
16855
16879
  };
16856
16880
  };
16857
- const getFilledCount = (score) => Math.round(score / 100 * 50);
16881
+ const getFilledCount = (score) => Math.round(score / 100 * getScoreBarWidth());
16858
16882
  const joinScoreHeaderFrame = (lines) => `${lines[0]}\n\r${lines[1]}\n\r${lines[2]}\n\r${lines[3]}\n`;
16859
16883
  const buildRawScoreBar = (displayScore) => {
16860
16884
  const { filledSegment, emptySegment } = buildScoreBarSegments(getFilledCount(displayScore));
@@ -16890,10 +16914,11 @@ const buildScoreBar = (displayScore, colorScore = displayScore) => {
16890
16914
  return colorizeByScore(filledSegment, colorScore) + highlighter.dim(emptySegment);
16891
16915
  };
16892
16916
  const buildProjectedScoreBar = (currentScore, potentialScore) => {
16917
+ const barWidth = getScoreBarWidth();
16893
16918
  const currentFill = getFilledCount(currentScore);
16894
- const potentialFill = Math.min(getFilledCount(potentialScore), 50);
16919
+ const potentialFill = Math.min(getFilledCount(potentialScore), barWidth);
16895
16920
  const gainCount = Math.max(0, potentialFill - currentFill);
16896
- const emptyCount = Math.max(0, 50 - currentFill - gainCount);
16921
+ const emptyCount = Math.max(0, barWidth - currentFill - gainCount);
16897
16922
  return colorizeByScore("█".repeat(currentFill), currentScore) + highlighter.dim(colorizeByScore("▓".repeat(gainCount), currentScore)) + highlighter.dim("░".repeat(emptyCount));
16898
16923
  };
16899
16924
  const getDoctorFace = (score) => {
@@ -16906,7 +16931,7 @@ const RAW_BRANDING_LINE = "React Doctor (https://react.doctor)";
16906
16931
  const buildRawFaceLines = (score) => {
16907
16932
  const [eyes, mouth] = getDoctorFace(score);
16908
16933
  return [
16909
- "┌─────┐",
16934
+ FACE_BOX_TOP_BORDER,
16910
16935
  `│ ${eyes} │`,
16911
16936
  `│ ${mouth} │`,
16912
16937
  "└─────┘"
@@ -17048,6 +17073,11 @@ const writeDiagnosticsDirectory = (diagnostics) => {
17048
17073
  };
17049
17074
  //#endregion
17050
17075
  //#region src/cli/utils/render-summary.ts
17076
+ const FOOTER_DESCRIPTION_INDENT = " ";
17077
+ const printFooterDescription = (description) => Effect.gen(function* () {
17078
+ const wrapWidth = resolveMeasureWidth(2);
17079
+ for (const line of wrapTextToWidth(description, wrapWidth)) yield* Console.log(highlighter.dim(`${FOOTER_DESCRIPTION_INDENT}${line}`));
17080
+ });
17051
17081
  const buildShareUrl = (diagnostics, scoreResult, projectName) => {
17052
17082
  const errorCount = diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
17053
17083
  const warningCount = diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length;
@@ -17067,14 +17097,14 @@ const printFooter = (input) => Effect.gen(function* () {
17067
17097
  if (!input.isOffline) {
17068
17098
  const shareUrl = buildShareUrl(input.diagnostics, input.scoreResult, input.projectName);
17069
17099
  yield* Console.log(` ${highlighter.bold("Share:")} ${highlighter.info(shareUrl)}`);
17070
- yield* Console.log(highlighter.dim(" Tell others how you did on socials"));
17100
+ yield* printFooterDescription("Tell others how you did on socials");
17071
17101
  yield* Console.log("");
17072
17102
  }
17073
17103
  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"));
17104
+ yield* printFooterDescription("Learn more about fixing issues, setting up CI/CD, and configuring rules with a config file");
17075
17105
  yield* Console.log("");
17076
17106
  yield* Console.log(` ${highlighter.bold("GitHub:")} ${highlighter.info(CANONICAL_GITHUB_URL)}`);
17077
- yield* Console.log(highlighter.dim(" Report issues and star the repository!"));
17107
+ yield* printFooterDescription("Report issues and star the repository!");
17078
17108
  });
17079
17109
  const printSummary = (input) => Effect.gen(function* () {
17080
17110
  if (input.scoreResult) {
@@ -17980,190 +18010,24 @@ const installDoctorScript = (options) => {
17980
18010
  ...scriptTarget.reason !== void 0 ? { scriptReason: scriptTarget.reason } : {}
17981
18011
  };
17982
18012
  };
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];
18013
+ const formatDoctorScriptInstallMessage = (scriptResult) => {
18014
+ const scriptName = scriptResult.scriptName ?? "doctor";
18015
+ if (scriptResult.scriptStatus === "created") return `Added package script: ${scriptName}.`;
18016
+ if (scriptResult.scriptStatus === "existing") return `Package script already exists: ${scriptName}.`;
18017
+ if (scriptResult.scriptReason === "script-names-taken") return "Skipped package script: doctor and react-doctor are already taken.";
18018
+ if (scriptResult.scriptReason === "doctor-script-taken") return "Skipped package script: doctor and react-doctor scripts already exist.";
18019
+ if (scriptResult.scriptReason === "invalid-scripts") return "Skipped package script: scripts field is not an object.";
18020
+ return "Skipped package script: package.json missing or invalid.";
18050
18021
  };
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
- }
18022
+ const installReactDoctorScriptStep = (projectRoot) => {
18023
+ const scriptSpinner = spinner("Installing React Doctor package script...").start();
18024
+ try {
18025
+ const scriptResult = installDoctorScript({ projectRoot });
18026
+ scriptSpinner.succeed(formatDoctorScriptInstallMessage(scriptResult));
18027
+ } catch (error) {
18028
+ scriptSpinner.fail("Failed to install React Doctor package script.");
18029
+ throw error;
18162
18030
  }
18163
- return {
18164
- installedAgents,
18165
- files
18166
- };
18167
18031
  };
18168
18032
  //#endregion
18169
18033
  //#region src/cli/utils/install-github-workflow.ts
@@ -18176,37 +18040,20 @@ const buildWorkflowContent = () => `# React Doctor — finds security, performan
18176
18040
  name: React Doctor
18177
18041
 
18178
18042
  on:
18043
+ # 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
18044
  pull_request:
18180
18045
  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.
18046
+ # Scans \`main\` on every push to track the health-score trend and catch regressions that slipped past PR review.
18186
18047
  push:
18187
18048
  branches: [main]
18188
18049
 
18189
18050
  permissions:
18190
- # \`actions/checkout\` needs this to read the repo source.
18191
18051
  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
18052
  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
18053
  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
18054
  statuses: write
18207
18055
 
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.
18056
+ # 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
18057
  concurrency:
18211
18058
  group: react-doctor-\${{ github.event.pull_request.number || github.ref }}
18212
18059
  cancel-in-progress: true
@@ -18273,1074 +18120,1359 @@ const installReactDoctorWorkflow = (projectRoot) => {
18273
18120
  };
18274
18121
  }
18275
18122
  };
18123
+ const upgradeReactDoctorWorkflowInPlace = (projectRoot) => {
18124
+ const workflow = readReactDoctorWorkflow(projectRoot);
18125
+ if (!workflow) return {
18126
+ status: "not-needed",
18127
+ workflowPath: getReactDoctorWorkflowPath(projectRoot)
18128
+ };
18129
+ const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
18130
+ if (!changed) return {
18131
+ status: "not-needed",
18132
+ workflowPath: workflow.workflowPath
18133
+ };
18134
+ try {
18135
+ fs$1.writeFileSync(workflow.workflowPath, content);
18136
+ return {
18137
+ status: "upgraded",
18138
+ workflowPath: workflow.workflowPath
18139
+ };
18140
+ } catch {
18141
+ return {
18142
+ status: "failed",
18143
+ workflowPath: workflow.workflowPath
18144
+ };
18145
+ }
18146
+ };
18276
18147
  //#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;
18148
+ //#region src/cli/utils/hash-project-root.ts
18149
+ const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
18150
+ //#endregion
18151
+ //#region src/cli/utils/action-upgrade-prompt.ts
18152
+ const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
18153
+ const getActionUpgradeStore = (options = {}) => new Conf({
18154
+ projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
18155
+ cwd: options.cwd
18156
+ });
18157
+ const hasHandledActionUpgrade = (projectRoot, storeOptions = {}) => {
18158
+ try {
18159
+ const upgrades = getActionUpgradeStore(storeOptions).get("actionUpgrades", {});
18160
+ return Boolean(upgrades[hashProjectRoot(projectRoot)]);
18161
+ } catch {
18162
+ return true;
18282
18163
  }
18283
- if (result.status === "exists") {
18284
- workflowSpinner.succeed("GitHub Actions workflow already configured.");
18164
+ };
18165
+ const recordActionUpgradeDecision = (projectRoot, outcome, storeOptions = {}) => {
18166
+ try {
18167
+ const store = getActionUpgradeStore(storeOptions);
18168
+ const upgrades = store.get("actionUpgrades", {});
18169
+ store.set("actionUpgrades", {
18170
+ ...upgrades,
18171
+ [hashProjectRoot(projectRoot)]: {
18172
+ rootDirectory: path$1.resolve(projectRoot),
18173
+ outcome,
18174
+ at: (/* @__PURE__ */ new Date()).toISOString()
18175
+ }
18176
+ });
18177
+ return true;
18178
+ } catch {
18285
18179
  return false;
18286
18180
  }
18287
- workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18288
- recordCount(METRIC.installWorkflow, 1);
18289
- return true;
18290
18181
  };
18291
18182
  //#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,
18183
+ //#region src/cli/utils/open-url.ts
18184
+ const resolveOpenCommand = (url) => {
18185
+ if (process$1.platform === "darwin") return {
18186
+ command: "open",
18187
+ args: [url]
18188
+ };
18189
+ if (process$1.platform === "win32") return {
18190
+ command: "cmd",
18191
+ args: [
18192
+ "/c",
18193
+ "start",
18345
18194
  "",
18346
- hookBlock.trimEnd(),
18347
- ...remainingLines
18348
- ].join("\n");
18349
- }
18350
- return `${SHEBANG}\n\n${hookBlock}${normalizedExistingContent}`;
18351
- };
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 {}
18358
- };
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);
18195
+ url
18196
+ ]
18197
+ };
18371
18198
  return {
18372
- hookPath: options.hookPath,
18373
- kind: options.kind ?? "git",
18374
- status: didHookExist ? "updated" : "created"
18199
+ command: "xdg-open",
18200
+ args: [url]
18375
18201
  };
18376
18202
  };
18203
+ const openUrl = (url) => {
18204
+ try {
18205
+ const { command, args } = resolveOpenCommand(url);
18206
+ const child = spawn(command, args, {
18207
+ detached: true,
18208
+ stdio: "ignore"
18209
+ });
18210
+ child.on("error", () => {});
18211
+ child.unref();
18212
+ return true;
18213
+ } catch {
18214
+ return false;
18215
+ }
18216
+ };
18377
18217
  //#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");
18218
+ //#region src/cli/utils/ask-add-to-github-actions.ts
18219
+ const CI_YES_CHOICE = "ci-yes";
18220
+ const CI_LEARN_MORE_CHOICE = "ci-learn-more";
18221
+ const CI_NO_CHOICE = "ci-no";
18222
+ const SGR_BOLD_OFF = "\x1B[22m";
18223
+ const ciQuestionMessage = [
18224
+ "Add React Doctor to GitHub Actions?",
18225
+ `${SGR_BOLD_OFF} ${highlighter.dim("Scan every pull request to prevent new React issues while you fix the backlog.")}`,
18226
+ `${SGR_BOLD_OFF} ${highlighter.dim(`Used by teams at ${CI_TRUST_COMPANIES}.`)}`
18227
+ ].join("\n");
18228
+ const askAddToGitHubActions = async (prompt = prompts) => {
18229
+ while (true) {
18230
+ const { ciChoice } = await prompt({
18231
+ type: "select",
18232
+ name: "ciChoice",
18233
+ message: ciQuestionMessage,
18234
+ hint: " ",
18235
+ choices: [
18236
+ {
18237
+ title: "Yes",
18238
+ description: "Adds the workflow file and a doctor package script",
18239
+ value: CI_YES_CHOICE
18240
+ },
18241
+ {
18242
+ title: "Learn more",
18243
+ description: "Opens the docs page in your browser",
18244
+ value: CI_LEARN_MORE_CHOICE
18245
+ },
18246
+ {
18247
+ title: "No",
18248
+ description: "Skip for now",
18249
+ value: CI_NO_CHOICE
18250
+ }
18251
+ ],
18252
+ initial: 0
18253
+ }, { onCancel: () => true });
18254
+ if (ciChoice === void 0) return "cancel";
18255
+ if (ciChoice === CI_YES_CHOICE) return "yes";
18256
+ if (ciChoice === CI_NO_CHOICE) return "no";
18257
+ const opened = openUrl(GITHUB_ACTIONS_SETUP_URL);
18258
+ cliLogger.log(opened ? `Opened ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} in your browser.` : `Visit ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} to learn more.`);
18259
+ cliLogger.break();
18260
+ }
18382
18261
  };
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];
18262
+ //#endregion
18263
+ //#region src/cli/utils/ask-upgrade-action-version.ts
18264
+ const UPGRADE_YES_CHOICE = "upgrade-yes";
18265
+ const UPGRADE_NO_CHOICE = "upgrade-no";
18266
+ const askUpgradeActionVersion = async (prompt = prompts) => {
18267
+ const { upgradeChoice } = await prompt({
18268
+ type: "select",
18269
+ name: "upgradeChoice",
18270
+ message: "A new major of the React Doctor Action (v2) is out. Upgrade this repo's workflow?",
18271
+ hint: " ",
18272
+ choices: [{
18273
+ title: "Yes (recommended)",
18274
+ description: "Bump the workflow to millionco/react-doctor@v2",
18275
+ value: UPGRADE_YES_CHOICE
18276
+ }, {
18277
+ title: "No, thanks",
18278
+ description: "Keep @v1 — won't ask again for this repo",
18279
+ value: UPGRADE_NO_CHOICE
18280
+ }],
18281
+ initial: 0
18282
+ }, { onCancel: () => true });
18283
+ if (upgradeChoice === void 0) return "cancel";
18284
+ return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
18386
18285
  };
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;
18286
+ //#endregion
18287
+ //#region src/cli/utils/open-workflow-pull-request.ts
18288
+ const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
18289
+ const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
18290
+ const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
18291
+ 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.
18292
+
18293
+ Docs: https://www.react.doctor/ci`;
18294
+ const execFileAsync$1 = promisify(execFile);
18295
+ const run = async (command, args, cwd) => {
18296
+ try {
18297
+ const { stdout, stderr } = await execFileAsync$1(command, [...args], {
18298
+ cwd,
18299
+ encoding: "utf8"
18300
+ });
18301
+ return {
18302
+ success: true,
18303
+ stdout: stdout.trim(),
18304
+ stderr: stderr.trim()
18305
+ };
18306
+ } catch (error) {
18307
+ const failure = error;
18308
+ return {
18309
+ success: false,
18310
+ stdout: (failure.stdout ?? "").trim(),
18311
+ stderr: (failure.stderr ?? "").trim()
18312
+ };
18400
18313
  }
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
18314
  };
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);
18315
+ const detectDefaultBranch = async (cwd) => {
18316
+ const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
18317
+ if (symRef.success) {
18318
+ const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
18319
+ if (branchMatch) return branchMatch[1];
18554
18320
  }
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"));
18321
+ if ((await run("git", [
18322
+ "rev-parse",
18323
+ "--verify",
18324
+ "origin/main"
18325
+ ], cwd)).success) return "main";
18326
+ if ((await run("git", [
18327
+ "rev-parse",
18328
+ "--verify",
18329
+ "origin/master"
18330
+ ], cwd)).success) return "master";
18331
+ return null;
18569
18332
  };
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;
18333
+ const findUniqueBranchName = async (cwd) => {
18334
+ if (!(await run("git", [
18335
+ "rev-parse",
18336
+ "--verify",
18337
+ NEW_BRANCH_PREFIX
18338
+ ], cwd)).success) return NEW_BRANCH_PREFIX;
18339
+ return `${NEW_BRANCH_PREFIX}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:T]/g, "")}`;
18576
18340
  };
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
18609
- };
18610
- if (isSimpleGitHooksProject(topLevel)) return {
18611
- hookPath: path$1.join(topLevel, "package.json"),
18612
- runnerRoot: topLevel,
18613
- kind: "simple-git-hooks"
18341
+ const openWorkflowPullRequest = async (params) => {
18342
+ const workflowPath = path$1.resolve(params.workflowPath);
18343
+ const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
18344
+ const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
18345
+ const prBody = params.prBody ?? DEFAULT_PR_BODY;
18346
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18347
+ if (!repoRootProbe.success) return {
18348
+ status: "not-attempted",
18349
+ reason: "not-a-git-repo"
18614
18350
  };
18615
- const lefthookConfigPath = getLefthookConfigPath(topLevel);
18616
- if (lefthookConfigPath !== null) return {
18617
- hookPath: lefthookConfigPath,
18618
- runnerRoot: topLevel,
18619
- kind: "lefthook"
18351
+ const cwd = repoRootProbe.stdout;
18352
+ if (!isCommandAvailable("gh")) return {
18353
+ status: "not-attempted",
18354
+ reason: "gh-not-installed"
18620
18355
  };
18621
- if (isPreCommitProject(topLevel)) return {
18622
- hookPath: path$1.join(topLevel, PRE_COMMIT_CONFIG_FILE),
18623
- runnerRoot: topLevel,
18624
- kind: "pre-commit"
18356
+ if (!(await run("gh", ["auth", "status"], cwd)).success) return {
18357
+ status: "not-attempted",
18358
+ reason: "gh-not-authenticated"
18625
18359
  };
18626
- if (isOvercommitProject(topLevel)) return {
18627
- hookPath: path$1.join(topLevel, OVERCOMMIT_CONFIG_FILE),
18628
- runnerRoot: topLevel,
18629
- kind: "overcommit"
18360
+ const defaultBranch = await detectDefaultBranch(cwd);
18361
+ if (!defaultBranch) return {
18362
+ status: "not-attempted",
18363
+ reason: "no-default-branch"
18630
18364
  };
18631
- if (isYorkieProject(topLevel)) return {
18632
- hookPath: getPackageJsonPath(topLevel),
18633
- runnerRoot: topLevel,
18634
- kind: "yorkie"
18365
+ const previousBranchProbe = await run("git", [
18366
+ "rev-parse",
18367
+ "--abbrev-ref",
18368
+ "HEAD"
18369
+ ], cwd);
18370
+ if (!previousBranchProbe.success || previousBranchProbe.stdout === "HEAD") return {
18371
+ status: "not-attempted",
18372
+ reason: "detached-head"
18635
18373
  };
18636
- if (isGhooksProject(topLevel)) return {
18637
- hookPath: getPackageJsonPath(topLevel),
18638
- runnerRoot: topLevel,
18639
- kind: "ghooks"
18374
+ const previousBranch = previousBranchProbe.stdout;
18375
+ await run("git", [
18376
+ "fetch",
18377
+ "origin",
18378
+ defaultBranch
18379
+ ], cwd);
18380
+ const newBranch = await findUniqueBranchName(cwd);
18381
+ if (!(await run("git", [
18382
+ "checkout",
18383
+ "-b",
18384
+ newBranch,
18385
+ `origin/${defaultBranch}`
18386
+ ], cwd)).success) return {
18387
+ status: "not-attempted",
18388
+ reason: "checkout-failed"
18640
18389
  };
18641
- if (isGitHooksJsProject(topLevel)) return {
18642
- hookPath: getPackageJsonPath(topLevel),
18643
- runnerRoot: topLevel,
18644
- kind: "git-hooks-js"
18390
+ const restoreToPreviousBranch = async (deleteNewBranch) => {
18391
+ await run("git", ["checkout", previousBranch], cwd);
18392
+ if (deleteNewBranch) await run("git", [
18393
+ "branch",
18394
+ "-D",
18395
+ newBranch
18396
+ ], cwd);
18645
18397
  };
18646
- if (isPreCommitNpmProject(topLevel)) return {
18647
- hookPath: getPackageJsonPath(topLevel),
18648
- runnerRoot: topLevel,
18649
- kind: "pre-commit-npm"
18650
- };
18651
- if (isPrettyQuickProject(topLevel)) return {
18652
- hookPath: getPackageJsonPath(topLevel),
18653
- runnerRoot: topLevel,
18654
- kind: "pretty-quick"
18398
+ if (!(await run("git", [
18399
+ "add",
18400
+ "--",
18401
+ path$1.relative(cwd, workflowPath)
18402
+ ], cwd)).success) {
18403
+ await restoreToPreviousBranch(true);
18404
+ return {
18405
+ status: "not-attempted",
18406
+ reason: "git-add-failed"
18407
+ };
18408
+ }
18409
+ if (!(await run("git", [
18410
+ "commit",
18411
+ "-m",
18412
+ commitMessage
18413
+ ], cwd)).success) {
18414
+ await restoreToPreviousBranch(true);
18415
+ return {
18416
+ status: "not-attempted",
18417
+ reason: "git-commit-failed"
18418
+ };
18419
+ }
18420
+ if (!(await run("git", [
18421
+ "push",
18422
+ "-u",
18423
+ "origin",
18424
+ newBranch
18425
+ ], cwd)).success) {
18426
+ await restoreToPreviousBranch(true);
18427
+ return {
18428
+ status: "not-attempted",
18429
+ reason: "git-push-failed"
18430
+ };
18431
+ }
18432
+ const prCreate = await run("gh", [
18433
+ "pr",
18434
+ "create",
18435
+ "--title",
18436
+ prTitle,
18437
+ "--body",
18438
+ prBody,
18439
+ "--base",
18440
+ defaultBranch,
18441
+ "--head",
18442
+ newBranch
18443
+ ], cwd);
18444
+ await restoreToPreviousBranch(false);
18445
+ if (!prCreate.success) return {
18446
+ status: "branch-pushed",
18447
+ branch: newBranch
18655
18448
  };
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
18449
  return {
18663
- hookPath: resolveGitPath(projectRoot, hookPath),
18664
- runnerRoot: topLevel,
18665
- kind: "git"
18450
+ status: "pr-opened",
18451
+ url: prCreate.stdout.split(/\r?\n/).filter(Boolean).pop() ?? ""
18666
18452
  };
18667
18453
  };
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);
18454
+ const stageWorkflowFile = async (params) => {
18455
+ const workflowPath = path$1.resolve(params.workflowPath);
18456
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18457
+ if (!repoRootProbe.success) return false;
18458
+ return (await run("git", [
18459
+ "add",
18460
+ "--",
18461
+ path$1.relative(repoRootProbe.stdout, workflowPath)
18462
+ ], repoRootProbe.stdout)).success;
18679
18463
  };
18680
18464
  //#endregion
18681
- //#region src/cli/utils/should-skip-prompts.ts
18682
- const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
18683
- //#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"
18465
+ //#region src/cli/utils/report-workflow-result.ts
18466
+ const reportWorkflowResult = (workflowSpinner, result, projectRoot) => {
18467
+ if (result.status === "failed") {
18468
+ workflowSpinner.fail("Couldn't write the GitHub Actions workflow.");
18469
+ return false;
18720
18470
  }
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;
18471
+ if (result.status === "exists") {
18472
+ workflowSpinner.succeed("GitHub Actions workflow already configured.");
18473
+ return false;
18729
18474
  }
18475
+ workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18476
+ recordCount(METRIC.installWorkflow, 1);
18477
+ return true;
18730
18478
  };
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;
18479
+ //#endregion
18480
+ //#region src/cli/utils/set-up-github-actions.ts
18481
+ const setUpGitHubActions = async (options) => {
18482
+ const projectRoot = findNearestPackageDirectory(options.rootDirectory) ?? options.rootDirectory;
18483
+ try {
18484
+ installReactDoctorScriptStep(projectRoot);
18485
+ } catch {}
18486
+ const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
18487
+ const workflowResult = installReactDoctorWorkflow(projectRoot);
18488
+ const didCreateWorkflow = reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
18489
+ cliLogger.break();
18490
+ if (workflowResult.status === "failed") {
18491
+ cliLogger.log(` Couldn't set up GitHub Actions automatically. Follow the guide at ${highlighter.info(CI_URL)}`);
18492
+ return false;
18493
+ }
18494
+ if (workflowResult.status === "created") {
18495
+ const pullRequestSpinner = spinner("Opening a pull request for review...").start();
18496
+ const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
18497
+ if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
18498
+ 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}`);
18499
+ else {
18500
+ pullRequestSpinner.stop();
18501
+ const didStage = await stageWorkflowFile({ workflowPath: workflowResult.workflowPath });
18502
+ 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.");
18738
18503
  }
18739
- const parentDirectory = path$1.dirname(currentDirectory);
18740
- if (parentDirectory === currentDirectory) break;
18741
- currentDirectory = parentDirectory;
18742
18504
  }
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";
18505
+ cliLogger.log(` Learn more: ${highlighter.info(CI_URL)}`);
18506
+ return didCreateWorkflow;
18745
18507
  };
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
- };
18777
- return {
18778
- command: "pnpm",
18779
- args: [
18780
- "add",
18781
- "--save-dev",
18782
- ...packageManagerNeedsWorkspaceFlag(projectRoot) ? ["-w"] : [],
18783
- packageSpecifier
18784
- ],
18785
- cwd: projectRoot
18786
- };
18508
+ //#endregion
18509
+ //#region src/cli/utils/install-agent-hooks.ts
18510
+ const CLAUDE_AGENT = "claude-code";
18511
+ const CURSOR_AGENT = "cursor";
18512
+ const CLAUDE_SETTINGS_RELATIVE_PATH = ".claude/settings.json";
18513
+ const CLAUDE_HOOK_RELATIVE_PATH = ".claude/hooks/react-doctor.sh";
18514
+ const CLAUDE_HOOK_COMMAND = "sh \"$CLAUDE_PROJECT_DIR/.claude/hooks/react-doctor.sh\"";
18515
+ const CURSOR_HOOKS_RELATIVE_PATH = ".cursor/hooks.json";
18516
+ const CURSOR_HOOK_RELATIVE_PATH = ".cursor/hooks/react-doctor.sh";
18517
+ const CURSOR_HOOK_MATCHER = "Write|Edit|MultiEdit|ApplyPatch";
18518
+ const CURSOR_HOOKS_SCHEMA_VERSION = 1;
18519
+ const JSON_INDENT_SPACES$1 = 2;
18520
+ const isSupportedAgent = (agent) => agent === CLAUDE_AGENT || agent === CURSOR_AGENT;
18521
+ const readJsonFile = (filePath, fallback) => {
18522
+ if (!fs$1.existsSync(filePath)) return fallback;
18523
+ const content = fs$1.readFileSync(filePath, "utf8").trim();
18524
+ if (content.length === 0) return fallback;
18525
+ return JSON.parse(content);
18787
18526
  };
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
- });
18527
+ const writeJsonFile = (filePath, value) => {
18528
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18529
+ fs$1.writeFileSync(filePath, `${JSON.stringify(value, null, JSON_INDENT_SPACES$1)}\n`);
18798
18530
  };
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);
18807
- };
18808
- const formatInstallCommand = (input) => [input.command, ...input.args].join(" ");
18809
- const installReactDoctorDependency = async (options) => {
18810
- 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
- };
18829
- }
18830
- return { dependencyStatus: "created" };
18831
- };
18832
- const buildManualGitHookTarget = (hookPath, projectRoot) => ({
18833
- hookPath,
18834
- runnerRoot: projectRoot,
18835
- kind: "git"
18836
- });
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(" ");
18531
+ const writeHookScript = (filePath) => {
18532
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18533
+ fs$1.writeFileSync(filePath, buildAgentHookScript());
18534
+ fs$1.chmodSync(filePath, 493);
18851
18535
  };
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.";
18536
+ const hasClaudeHookCommand = (groups) => groups.some((group) => (group.hooks ?? []).some((hook) => hook.command === CLAUDE_HOOK_COMMAND));
18537
+ const installClaudeHook = (projectRoot) => {
18538
+ const settingsPath = path$1.join(projectRoot, CLAUDE_SETTINGS_RELATIVE_PATH);
18539
+ const hookPath = path$1.join(projectRoot, CLAUDE_HOOK_RELATIVE_PATH);
18540
+ const settings = readJsonFile(settingsPath, {});
18541
+ const hooks = { ...settings.hooks ?? {} };
18542
+ const postToolBatchHooks = [...hooks.PostToolBatch ?? []];
18543
+ if (!hasClaudeHookCommand(postToolBatchHooks)) postToolBatchHooks.push({ hooks: [{
18544
+ type: "command",
18545
+ command: CLAUDE_HOOK_COMMAND
18546
+ }] });
18547
+ hooks.PostToolBatch = postToolBatchHooks;
18548
+ writeJsonFile(settingsPath, {
18549
+ ...settings,
18550
+ hooks
18551
+ });
18552
+ writeHookScript(hookPath);
18553
+ return [settingsPath, hookPath];
18859
18554
  };
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`}`;
18555
+ const hasCursorHookCommand = (handlers) => handlers.some((handler) => handler.command === CURSOR_HOOK_RELATIVE_PATH);
18556
+ const installCursorHook = (projectRoot) => {
18557
+ const configPath = path$1.join(projectRoot, CURSOR_HOOKS_RELATIVE_PATH);
18558
+ const hookPath = path$1.join(projectRoot, CURSOR_HOOK_RELATIVE_PATH);
18559
+ const config = readJsonFile(configPath, {});
18560
+ const hooks = { ...config.hooks ?? {} };
18561
+ const postToolUseHooks = [...hooks.postToolUse ?? []];
18562
+ if (!hasCursorHookCommand(postToolUseHooks)) postToolUseHooks.push({
18563
+ command: CURSOR_HOOK_RELATIVE_PATH,
18564
+ matcher: CURSOR_HOOK_MATCHER,
18565
+ timeout: 120
18566
+ });
18567
+ hooks.postToolUse = postToolUseHooks;
18568
+ writeJsonFile(configPath, {
18569
+ ...config,
18570
+ version: config.version ?? CURSOR_HOOKS_SCHEMA_VERSION,
18571
+ hooks
18572
+ });
18573
+ writeHookScript(hookPath);
18574
+ return [configPath, hookPath];
18863
18575
  };
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;
18576
+ const buildAgentHookScript = () => [
18577
+ "#!/bin/sh",
18578
+ "set -u",
18579
+ "",
18580
+ "input_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook.XXXXXX\")",
18581
+ "output_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook-output.XXXXXX\")",
18582
+ "trap 'rm -f \"$input_file\" \"$output_file\"' EXIT",
18583
+ "cat > \"$input_file\"",
18584
+ "",
18585
+ "script_dir=$(CDPATH= cd \"$(dirname \"$0\")\" && pwd)",
18586
+ "project_root=${CLAUDE_PROJECT_DIR:-}",
18587
+ "if [ -z \"$project_root\" ]; then",
18588
+ " project_root=$(CDPATH= cd \"$script_dir/../..\" && pwd)",
18589
+ "fi",
18590
+ "if ! cd \"$project_root\"; then",
18591
+ " exit 0",
18592
+ "fi",
18593
+ "",
18594
+ "should_scan() {",
18595
+ " if ! command -v node >/dev/null 2>&1; then",
18596
+ " return 0",
18597
+ " fi",
18598
+ "",
18599
+ " node - \"$input_file\" <<'NODE'",
18600
+ "const fs = require('node:fs');",
18601
+ "const inputPath = process.argv[2];",
18602
+ "const editToolNames = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'ApplyPatch']);",
18603
+ "try {",
18604
+ " const input = JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18605
+ " const eventName = input.hook_event_name || input.eventName || input.event_name;",
18606
+ " if (eventName === 'PostToolBatch') {",
18607
+ " const toolCalls = Array.isArray(input.tool_calls) ? input.tool_calls : [];",
18608
+ " process.exit(toolCalls.some((toolCall) => editToolNames.has(toolCall.tool_name)) ? 0 : 10);",
18609
+ " }",
18610
+ " const toolName = input.tool_name || input.toolName || input.tool;",
18611
+ " process.exit(!toolName || editToolNames.has(toolName) ? 0 : 10);",
18612
+ "} catch {",
18613
+ " process.exit(0);",
18614
+ "}",
18615
+ "NODE",
18616
+ "}",
18617
+ "",
18618
+ "run_react_doctor() {",
18619
+ " if [ -x ./node_modules/.bin/react-doctor ]; then",
18620
+ " ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
18621
+ " return",
18622
+ " fi",
18623
+ "",
18624
+ " if command -v react-doctor >/dev/null 2>&1; then",
18625
+ " react-doctor --verbose --diff --blocking warning --no-score",
18626
+ " return",
18627
+ " fi",
18628
+ "",
18629
+ " if command -v pnpm >/dev/null 2>&1; then",
18630
+ " pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
18631
+ " return",
18632
+ " fi",
18633
+ "",
18634
+ " if command -v npx >/dev/null 2>&1; then",
18635
+ " npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
18636
+ " return",
18637
+ " fi",
18638
+ "",
18639
+ " printf '%s\\n' 'react-doctor: command not found; skipping agent hook scan.'",
18640
+ " return 0",
18641
+ "}",
18642
+ "",
18643
+ "if ! should_scan; then",
18644
+ " exit 0",
18645
+ "fi",
18646
+ "",
18647
+ "if run_react_doctor > \"$output_file\" 2>&1; then",
18648
+ " exit 0",
18649
+ "fi",
18650
+ "",
18651
+ "node - \"$input_file\" \"$output_file\" <<'NODE'",
18652
+ "const fs = require('node:fs');",
18653
+ "const inputPath = process.argv[2];",
18654
+ "const outputPath = process.argv[3];",
18655
+ "const readInput = () => {",
18656
+ " try {",
18657
+ " return JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18658
+ " } catch {",
18659
+ " return {};",
18660
+ " }",
18661
+ "};",
18662
+ "const input = readInput();",
18663
+ "const scanOutput = fs.readFileSync(outputPath, 'utf8').trim();",
18664
+ "if (!scanOutput) process.exit(0);",
18665
+ "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}`;",
18666
+ "if (input.hook_event_name === 'PostToolBatch') {",
18667
+ " console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolBatch', additionalContext: message } }));",
18668
+ "} else {",
18669
+ " console.log(JSON.stringify({ additional_context: message }));",
18670
+ "}",
18671
+ "NODE",
18672
+ ""
18673
+ ].join("\n");
18674
+ const installReactDoctorAgentHooks = (options) => {
18675
+ const installedAgents = [];
18676
+ const files = [];
18677
+ const requestedAgents = options.agents.filter(isSupportedAgent);
18678
+ for (const agent of requestedAgents) {
18679
+ if (agent === CLAUDE_AGENT) {
18680
+ files.push(...installClaudeHook(options.projectRoot));
18681
+ installedAgents.push(agent);
18682
+ }
18683
+ if (agent === CURSOR_AGENT) {
18684
+ files.push(...installCursorHook(options.projectRoot));
18685
+ installedAgents.push(agent);
18686
+ }
18872
18687
  }
18688
+ return {
18689
+ installedAgents,
18690
+ files
18691
+ };
18873
18692
  };
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;
18693
+ //#endregion
18694
+ //#region src/cli/utils/install-git-hook-file.ts
18695
+ const REACT_DOCTOR_BLOCK_START = "# react-doctor hook start";
18696
+ const REACT_DOCTOR_BLOCK_END = "# react-doctor hook end";
18697
+ 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?)`);
18698
+ const SHEBANG = "#!/bin/sh";
18699
+ const SHEBANG_PREFIX = "#!";
18700
+ const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
18701
+ const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
18702
+ const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
18703
+ const buildReactDoctorHookBlock = () => [
18704
+ REACT_DOCTOR_BLOCK_START,
18705
+ "react_doctor_scan_staged_files() {",
18706
+ ` if [ -x "${LOCAL_REACT_DOCTOR_BIN}" ]; then`,
18707
+ ` "${LOCAL_REACT_DOCTOR_BIN}" ${REACT_DOCTOR_COMMAND.replace("react-doctor ", "")}`,
18708
+ " return",
18709
+ " fi",
18710
+ "",
18711
+ " if command -v react-doctor >/dev/null 2>&1; then",
18712
+ ` ${REACT_DOCTOR_COMMAND}`,
18713
+ " return",
18714
+ " fi",
18715
+ "",
18716
+ " if command -v pnpm >/dev/null 2>&1; then",
18717
+ ` ${PNPM_REACT_DOCTOR_COMMAND}`,
18718
+ " return",
18719
+ " fi",
18720
+ "",
18721
+ " if command -v npx >/dev/null 2>&1; then",
18722
+ ` ${NPX_REACT_DOCTOR_COMMAND}`,
18723
+ " return",
18724
+ " fi",
18725
+ "",
18726
+ " printf '%s\\n' \"react-doctor: command not found; skipping staged scan.\"",
18727
+ "}",
18728
+ "",
18729
+ "react_doctor_output=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-hook.XXXXXX\")",
18730
+ "if react_doctor_scan_staged_files > \"$react_doctor_output\" 2>&1; then",
18731
+ " rm -f \"$react_doctor_output\"",
18732
+ "else",
18733
+ " rm -f \"$react_doctor_output\"",
18734
+ ` 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`,
18735
+ "fi",
18736
+ REACT_DOCTOR_BLOCK_END
18737
+ ].join("\n");
18738
+ const mergeHookContent = (existingContent) => {
18739
+ const hookBlock = `${buildReactDoctorHookBlock()}\n`;
18740
+ if (REACT_DOCTOR_BLOCK_PATTERN.test(existingContent)) return ensureTrailingNewline(existingContent.replace(REACT_DOCTOR_BLOCK_PATTERN, hookBlock));
18741
+ if (existingContent.length === 0) return `${SHEBANG}\n\n${hookBlock}`;
18742
+ const normalizedExistingContent = ensureTrailingNewline(existingContent);
18743
+ if (normalizedExistingContent.startsWith(SHEBANG_PREFIX)) {
18744
+ const [shebangLine, ...remainingLines] = normalizedExistingContent.split("\n");
18745
+ return [
18746
+ shebangLine,
18747
+ "",
18748
+ hookBlock.trimEnd(),
18749
+ ...remainingLines
18750
+ ].join("\n");
18900
18751
  }
18752
+ return `${SHEBANG}\n\n${hookBlock}${normalizedExistingContent}`;
18753
+ };
18754
+ const removeLegacyManagedRunner = (projectRoot) => {
18755
+ const runnerPath = path$1.join(projectRoot, LEGACY_HOOK_RUNNER_RELATIVE_PATH);
18756
+ fs$1.rmSync(runnerPath, { force: true });
18757
+ for (const directory of [path$1.dirname(runnerPath), path$1.join(projectRoot, ".react-doctor")]) try {
18758
+ fs$1.rmdirSync(directory);
18759
+ } catch {}
18760
+ };
18761
+ const installDirectGitHook = (options) => {
18762
+ const didHookExist = fs$1.existsSync(options.hookPath);
18763
+ const nextContent = mergeHookContent(didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "");
18764
+ if (options.hooksPathConfig !== void 0) runGit(options.projectRoot, [
18765
+ "config",
18766
+ "core.hooksPath",
18767
+ options.hooksPathConfig
18768
+ ]);
18769
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18770
+ fs$1.writeFileSync(options.hookPath, nextContent);
18771
+ fs$1.chmodSync(options.hookPath, 493);
18772
+ removeLegacyManagedRunner(options.projectRoot);
18773
+ return {
18774
+ hookPath: options.hookPath,
18775
+ kind: options.kind ?? "git",
18776
+ status: didHookExist ? "updated" : "created"
18777
+ };
18901
18778
  };
18902
- const getSkillSourceDirectory = () => {
18903
- const distDirectory = path$1.dirname(fileURLToPath(import.meta.url));
18904
- return path$1.join(distDirectory, "skills", SKILL_NAME);
18779
+ //#endregion
18780
+ //#region src/cli/utils/install-git-hook-config-managers.ts
18781
+ const appendStringCommand = (existingCommand) => {
18782
+ const existingCommandText = typeof existingCommand === "string" ? existingCommand : Array.isArray(existingCommand) ? existingCommand.filter((entry) => typeof entry === "string").join("\n") : "";
18783
+ return existingCommandText.includes("react-doctor --staged --blocking warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
18905
18784
  };
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);
18926
- }
18927
- return installedSkillNames;
18785
+ const appendArrayCommand = (existingCommands) => {
18786
+ const commands = Array.isArray(existingCommands) ? existingCommands.filter((entry) => typeof entry === "string") : typeof existingCommands === "string" ? [existingCommands] : [];
18787
+ return commands.some((command) => command.includes("react-doctor --staged --blocking warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
18928
18788
  };
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;
18789
+ const installPackageJsonHook = (options, strategy) => {
18790
+ const packageJsonPath = getPackageJsonPath(options.projectRoot);
18791
+ const didHookExist = fs$1.existsSync(packageJsonPath);
18792
+ const packageJson = readPackageJson(options.projectRoot);
18793
+ const nextPackageJson = isRecord(packageJson) ? { ...packageJson } : {};
18794
+ const parentKeys = strategy.path.slice(0, -1);
18795
+ const leafKey = strategy.path[strategy.path.length - 1];
18796
+ let parent = nextPackageJson;
18797
+ for (const key of parentKeys) {
18798
+ const existing = parent[key];
18799
+ const cloned = isRecord(existing) ? { ...existing } : {};
18800
+ parent[key] = cloned;
18801
+ parent = cloned;
18946
18802
  }
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
- }] : []
18803
+ parent[leafKey] = strategy.leafShape === "array" ? appendArrayCommand(parent[leafKey]) : appendStringCommand(parent[leafKey]);
18804
+ writeJsonFile$1(packageJsonPath, nextPackageJson);
18805
+ removeLegacyManagedRunner(options.projectRoot);
18806
+ return {
18807
+ hookPath: packageJsonPath,
18808
+ kind: strategy.kind,
18809
+ status: didHookExist ? "updated" : "created"
18810
+ };
18811
+ };
18812
+ const installSimpleGitHooks = (options) => installPackageJsonHook(options, {
18813
+ kind: "simple-git-hooks",
18814
+ path: ["simple-git-hooks", "pre-commit"],
18815
+ leafShape: "string"
18816
+ });
18817
+ const installGhooks = (options) => installPackageJsonHook(options, {
18818
+ kind: "ghooks",
18819
+ path: [
18820
+ "config",
18821
+ "ghooks",
18822
+ "pre-commit"
18823
+ ],
18824
+ leafShape: "string"
18825
+ });
18826
+ const installPreCommitNpm = (options) => installPackageJsonHook(options, {
18827
+ kind: "pre-commit-npm",
18828
+ path: ["pre-commit"],
18829
+ leafShape: "array"
18830
+ });
18831
+ const installPrettyQuick = (options) => installPackageJsonHook(options, {
18832
+ kind: "pretty-quick",
18833
+ path: ["gitHooks", "pre-commit"],
18834
+ leafShape: "string"
18835
+ });
18836
+ const installYorkie = (options) => installPackageJsonHook(options, {
18837
+ kind: "yorkie",
18838
+ path: ["gitHooks", "pre-commit"],
18839
+ leafShape: "string"
18840
+ });
18841
+ const installGitHooksJs = (options) => installPackageJsonHook(options, {
18842
+ kind: "git-hooks-js",
18843
+ path: ["git-hooks", "pre-commit"],
18844
+ leafShape: "string"
18845
+ });
18846
+ const appendIndentedBlockToTopLevelSection = (content, sectionName, block) => {
18847
+ const normalizedContent = ensureTrailingNewline(content);
18848
+ const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(normalizedContent);
18849
+ if (match === null) return ensureTrailingNewline([
18850
+ normalizedContent.trimEnd(),
18851
+ "",
18852
+ `${sectionName}:`,
18853
+ ...block,
18854
+ ""
18855
+ ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18856
+ const sectionStartIndex = match.index;
18857
+ const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18858
+ nextSectionPattern.lastIndex = sectionStartIndex + match[0].length;
18859
+ let nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18860
+ while (nextSectionMatch !== null && nextSectionMatch.index === sectionStartIndex) nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18861
+ const insertIndex = nextSectionMatch?.index ?? normalizedContent.length;
18862
+ const prefix = normalizedContent.slice(0, insertIndex).trimEnd();
18863
+ const suffix = normalizedContent.slice(insertIndex);
18864
+ return ensureTrailingNewline([
18865
+ prefix,
18866
+ ...block,
18867
+ suffix.trimStart()
18868
+ ].join("\n"));
18869
+ };
18870
+ const findTopLevelSectionRange = (content, sectionName) => {
18871
+ const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(content);
18872
+ if (match === null) return null;
18873
+ const headerLineEndIndex = content.indexOf("\n", match.index);
18874
+ const headerEndIndex = headerLineEndIndex === -1 ? match.index + match[0].length : headerLineEndIndex + 1;
18875
+ const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18876
+ nextSectionPattern.lastIndex = headerEndIndex;
18877
+ return {
18878
+ headerEndIndex,
18879
+ contentEndIndex: nextSectionPattern.exec(content)?.index ?? content.length
18880
+ };
18881
+ };
18882
+ const appendLefthookCommand = (content) => {
18883
+ const normalizedContent = ensureTrailingNewline(content);
18884
+ const sectionRange = findTopLevelSectionRange(normalizedContent, "pre-commit");
18885
+ const reactDoctorCommandBlock = [
18886
+ " react-doctor:",
18887
+ ` run: ${NON_BLOCKING_REACT_DOCTOR_COMMAND}`,
18888
+ ""
18986
18889
  ];
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).");
18890
+ if (sectionRange === null) return ensureTrailingNewline([
18891
+ normalizedContent.trimEnd(),
18892
+ "",
18893
+ "pre-commit:",
18894
+ " commands:",
18895
+ ...reactDoctorCommandBlock
18896
+ ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18897
+ const sectionContent = normalizedContent.slice(sectionRange.headerEndIndex, sectionRange.contentEndIndex);
18898
+ const commandsMatch = /^ commands:\s*$/m.exec(sectionContent);
18899
+ const insertIndex = commandsMatch === null ? sectionRange.headerEndIndex : sectionRange.headerEndIndex + sectionContent.indexOf(commandsMatch[0]) + commandsMatch[0].length + 1;
18900
+ const insertBlock = commandsMatch === null ? [" commands:", ...reactDoctorCommandBlock].join("\n") : reactDoctorCommandBlock.join("\n");
18901
+ return ensureTrailingNewline(`${normalizedContent.slice(0, insertIndex)}${insertBlock}${normalizedContent.slice(insertIndex)}`);
18902
+ };
18903
+ const installLefthook = (options) => {
18904
+ const didHookExist = fs$1.existsSync(options.hookPath);
18905
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18906
+ if (!existingContent.includes("react-doctor")) {
18907
+ const nextContent = appendLefthookCommand(existingContent);
18908
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18909
+ fs$1.writeFileSync(options.hookPath, nextContent);
19037
18910
  }
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
- }
18911
+ removeLegacyManagedRunner(options.projectRoot);
18912
+ return {
18913
+ hookPath: options.hookPath,
18914
+ kind: "lefthook",
18915
+ status: didHookExist ? "updated" : "created"
18916
+ };
18917
+ };
18918
+ const installPreCommit = (options) => {
18919
+ const didHookExist = fs$1.existsSync(options.hookPath);
18920
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18921
+ if (!existingContent.includes("id: react-doctor")) {
18922
+ const hasReposKey = /^repos:\s*$/m.test(existingContent);
18923
+ const localHookBlock = [
18924
+ " - repo: local",
18925
+ " hooks:",
18926
+ " - id: react-doctor",
18927
+ " name: react-doctor",
18928
+ ` entry: sh -c '${NON_BLOCKING_REACT_DOCTOR_COMMAND}'`,
18929
+ " language: system",
18930
+ " pass_filenames: false",
18931
+ ""
18932
+ ].join("\n");
18933
+ const nextContent = hasReposKey ? `${ensureTrailingNewline(existingContent)}${localHookBlock}` : `repos:\n${localHookBlock}`;
18934
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18935
+ fs$1.writeFileSync(options.hookPath, nextContent);
19054
18936
  }
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
- }
18937
+ removeLegacyManagedRunner(options.projectRoot);
18938
+ return {
18939
+ hookPath: options.hookPath,
18940
+ kind: "pre-commit",
18941
+ status: didHookExist ? "updated" : "created"
18942
+ };
18943
+ };
18944
+ const installOvercommit = (options) => {
18945
+ const didHookExist = fs$1.existsSync(options.hookPath);
18946
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18947
+ if (!existingContent.includes("ReactDoctor")) {
18948
+ const nextContent = appendIndentedBlockToTopLevelSection(existingContent, "PreCommit", [
18949
+ " ReactDoctor:",
18950
+ " enabled: true",
18951
+ ` command: ['sh', '-c', '${NON_BLOCKING_REACT_DOCTOR_COMMAND}']`,
18952
+ ""
18953
+ ]);
18954
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18955
+ fs$1.writeFileSync(options.hookPath, nextContent);
19071
18956
  }
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 });
18957
+ removeLegacyManagedRunner(options.projectRoot);
18958
+ return {
18959
+ hookPath: options.hookPath,
18960
+ kind: "overcommit",
18961
+ status: didHookExist ? "updated" : "created"
18962
+ };
19083
18963
  };
19084
18964
  //#endregion
19085
- //#region src/cli/utils/hash-project-root.ts
19086
- const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
19087
- //#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;
19100
- }
18965
+ //#region src/cli/utils/install-git-hook.ts
18966
+ const isHuskyProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".husky")) || packageHasDependency(projectRoot, "husky");
18967
+ const isVitePlusProject = (projectRoot) => packageHasDependency(projectRoot, "vite-plus");
18968
+ const isSimpleGitHooksProject = (projectRoot) => {
18969
+ const packageJson = readPackageJson(projectRoot);
18970
+ return isRecord(packageJson) && isRecord(packageJson["simple-git-hooks"]) || packageHasDependency(projectRoot, "simple-git-hooks") || fs$1.existsSync(path$1.join(projectRoot, ".simple-git-hooks.cjs"));
19101
18971
  };
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;
18972
+ const getLefthookConfigPath = (projectRoot) => {
18973
+ for (const fileName of LEFTHOOK_CONFIG_FILES) {
18974
+ const filePath = path$1.join(projectRoot, fileName);
18975
+ if (fs$1.existsSync(filePath)) return filePath;
19117
18976
  }
18977
+ return packageHasDependency(projectRoot, "lefthook") ? path$1.join(projectRoot, LEFTHOOK_CONFIG_FILES[0] ?? "lefthook.yml") : null;
19118
18978
  };
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;
18979
+ const isPreCommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, PRE_COMMIT_CONFIG_FILE));
18980
+ const isOvercommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".overcommit.yml")) || packageHasDependency(projectRoot, "overcommit");
18981
+ const isYorkieProject = (projectRoot) => packageHasRecordKey(projectRoot, "gitHooks") || packageHasDependency(projectRoot, "yorkie");
18982
+ const isGhooksProject = (projectRoot) => packageHasDependency(projectRoot, "ghooks") || packageHasNestedRecordKey(projectRoot, "config", "ghooks");
18983
+ const isGitHooksJsProject = (projectRoot) => packageHasRecordKey(projectRoot, "git-hooks") || packageHasDependency(projectRoot, "git-hooks-js");
18984
+ const isPreCommitNpmProject = (projectRoot) => packageHasDependency(projectRoot, "pre-commit");
18985
+ const isPrettyQuickProject = (projectRoot) => packageHasDependency(projectRoot, "pretty-quick");
18986
+ const detectGitHookTarget = (projectRoot) => {
18987
+ if (runGit(projectRoot, ["rev-parse", "--is-inside-work-tree"]) !== "true") return null;
18988
+ const topLevel = runGit(projectRoot, ["rev-parse", "--show-toplevel"]) ?? projectRoot;
18989
+ const configuredHooksPath = runGit(projectRoot, [
18990
+ "config",
18991
+ "--path",
18992
+ "--get",
18993
+ "core.hooksPath"
18994
+ ]);
18995
+ if (configuredHooksPath !== null && configuredHooksPath.length > 0) return {
18996
+ hookPath: path$1.join(resolveGitPath(topLevel, configuredHooksPath), HOOK_FILE_NAME),
18997
+ runnerRoot: topLevel,
18998
+ kind: "configured"
18999
+ };
19000
+ if (isHuskyProject(topLevel)) return {
19001
+ hookPath: path$1.join(topLevel, HUSKY_HOOKS_PATH, HOOK_FILE_NAME),
19002
+ runnerRoot: topLevel,
19003
+ kind: "husky",
19004
+ hooksPathConfig: HUSKY_HOOKS_PATH
19005
+ };
19006
+ if (isVitePlusProject(topLevel)) return {
19007
+ hookPath: path$1.join(topLevel, VITE_PLUS_HOOKS_PATH, HOOK_FILE_NAME),
19008
+ runnerRoot: topLevel,
19009
+ kind: "vite-plus",
19010
+ hooksPathConfig: VITE_PLUS_HOOKS_PATH
19011
+ };
19012
+ if (isSimpleGitHooksProject(topLevel)) return {
19013
+ hookPath: path$1.join(topLevel, "package.json"),
19014
+ runnerRoot: topLevel,
19015
+ kind: "simple-git-hooks"
19016
+ };
19017
+ const lefthookConfigPath = getLefthookConfigPath(topLevel);
19018
+ if (lefthookConfigPath !== null) return {
19019
+ hookPath: lefthookConfigPath,
19020
+ runnerRoot: topLevel,
19021
+ kind: "lefthook"
19022
+ };
19023
+ if (isPreCommitProject(topLevel)) return {
19024
+ hookPath: path$1.join(topLevel, PRE_COMMIT_CONFIG_FILE),
19025
+ runnerRoot: topLevel,
19026
+ kind: "pre-commit"
19027
+ };
19028
+ if (isOvercommitProject(topLevel)) return {
19029
+ hookPath: path$1.join(topLevel, OVERCOMMIT_CONFIG_FILE),
19030
+ runnerRoot: topLevel,
19031
+ kind: "overcommit"
19032
+ };
19033
+ if (isYorkieProject(topLevel)) return {
19034
+ hookPath: getPackageJsonPath(topLevel),
19035
+ runnerRoot: topLevel,
19036
+ kind: "yorkie"
19037
+ };
19038
+ if (isGhooksProject(topLevel)) return {
19039
+ hookPath: getPackageJsonPath(topLevel),
19040
+ runnerRoot: topLevel,
19041
+ kind: "ghooks"
19042
+ };
19043
+ if (isGitHooksJsProject(topLevel)) return {
19044
+ hookPath: getPackageJsonPath(topLevel),
19045
+ runnerRoot: topLevel,
19046
+ kind: "git-hooks-js"
19047
+ };
19048
+ if (isPreCommitNpmProject(topLevel)) return {
19049
+ hookPath: getPackageJsonPath(topLevel),
19050
+ runnerRoot: topLevel,
19051
+ kind: "pre-commit-npm"
19052
+ };
19053
+ if (isPrettyQuickProject(topLevel)) return {
19054
+ hookPath: getPackageJsonPath(topLevel),
19055
+ runnerRoot: topLevel,
19056
+ kind: "pretty-quick"
19057
+ };
19058
+ const hookPath = runGit(projectRoot, [
19059
+ "rev-parse",
19060
+ "--git-path",
19061
+ HOOK_RELATIVE_PATH
19062
+ ]);
19063
+ if (hookPath === null || hookPath.length === 0) return null;
19064
+ return {
19065
+ hookPath: resolveGitPath(projectRoot, hookPath),
19066
+ runnerRoot: topLevel,
19067
+ kind: "git"
19068
+ };
19069
+ };
19070
+ const installReactDoctorGitHook = (options) => {
19071
+ if (options.kind === "simple-git-hooks") return installSimpleGitHooks(options);
19072
+ if (options.kind === "lefthook") return installLefthook(options);
19073
+ if (options.kind === "pre-commit") return installPreCommit(options);
19074
+ if (options.kind === "overcommit") return installOvercommit(options);
19075
+ if (options.kind === "yorkie") return installYorkie(options);
19076
+ if (options.kind === "ghooks") return installGhooks(options);
19077
+ if (options.kind === "git-hooks-js") return installGitHooksJs(options);
19078
+ if (options.kind === "pre-commit-npm") return installPreCommitNpm(options);
19079
+ if (options.kind === "pretty-quick") return installPrettyQuick(options);
19080
+ return installDirectGitHook(options);
19131
19081
  };
19132
19082
  //#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]
19083
+ //#region src/cli/utils/should-skip-prompts.ts
19084
+ const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
19085
+ //#endregion
19086
+ //#region src/cli/utils/install-react-doctor.ts
19087
+ const SETUP_OPTION_GIT_HOOK = "git-hook";
19088
+ const SETUP_OPTION_AGENT_HOOKS = "agent-hooks";
19089
+ const SETUP_OPTION_SKIP = "skip";
19090
+ const CONFIG_ONLY_GIT_HOOK_KINDS = new Set([
19091
+ "ghooks",
19092
+ "git-hooks-js",
19093
+ "lefthook",
19094
+ "overcommit",
19095
+ "pre-commit",
19096
+ "pre-commit-npm",
19097
+ "pretty-quick",
19098
+ "simple-git-hooks",
19099
+ "yorkie"
19100
+ ]);
19101
+ const PACKAGE_MANAGER_LOCKFILES = [
19102
+ {
19103
+ packageManager: "pnpm",
19104
+ fileName: "pnpm-lock.yaml"
19105
+ },
19106
+ {
19107
+ packageManager: "yarn",
19108
+ fileName: "yarn.lock"
19109
+ },
19110
+ {
19111
+ packageManager: "bun",
19112
+ fileName: "bun.lockb"
19113
+ },
19114
+ {
19115
+ packageManager: "bun",
19116
+ fileName: "bun.lock"
19117
+ },
19118
+ {
19119
+ packageManager: "npm",
19120
+ fileName: "package-lock.json"
19121
+ }
19122
+ ];
19123
+ const findNearestFileDirectory = (startDirectory, fileNames) => {
19124
+ let currentDirectory = path$1.resolve(startDirectory);
19125
+ while (true) {
19126
+ if (fileNames.some((fileName) => fs$1.existsSync(path$1.join(currentDirectory, fileName)))) return currentDirectory;
19127
+ const parentDirectory = path$1.dirname(currentDirectory);
19128
+ if (parentDirectory === currentDirectory) return null;
19129
+ currentDirectory = parentDirectory;
19130
+ }
19131
+ };
19132
+ const detectPackageManager = (projectRoot) => {
19133
+ let currentDirectory = path$1.resolve(projectRoot);
19134
+ while (true) {
19135
+ const packageJson = readPackageJson(currentDirectory);
19136
+ if (isRecord(packageJson) && typeof packageJson.packageManager === "string") {
19137
+ const packageManagerName = packageJson.packageManager.split("@")[0];
19138
+ if (packageManagerName === "pnpm" || packageManagerName === "yarn" || packageManagerName === "bun" || packageManagerName === "npm") return packageManagerName;
19139
+ }
19140
+ const parentDirectory = path$1.dirname(currentDirectory);
19141
+ if (parentDirectory === currentDirectory) break;
19142
+ currentDirectory = parentDirectory;
19143
+ }
19144
+ const lockfileDirectory = findNearestFileDirectory(projectRoot, PACKAGE_MANAGER_LOCKFILES.map((lockfile) => lockfile.fileName));
19145
+ return PACKAGE_MANAGER_LOCKFILES.find((lockfile) => lockfileDirectory !== null && fs$1.existsSync(path$1.join(lockfileDirectory, lockfile.fileName)))?.packageManager ?? "npm";
19146
+ };
19147
+ const packageManagerNeedsWorkspaceFlag = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, "pnpm-workspace.yaml")) || findNearestFileDirectory(projectRoot, ["pnpm-workspace.yaml"]) !== null;
19148
+ const buildInstallCommand = (projectRoot) => {
19149
+ const packageManager = detectPackageManager(projectRoot);
19150
+ const packageSpecifier = `${DOCTOR_PACKAGE_NAME}@latest`;
19151
+ if (packageManager === "npm") return {
19152
+ command: "npm",
19153
+ args: [
19154
+ "install",
19155
+ "--save-dev",
19156
+ packageSpecifier
19157
+ ],
19158
+ cwd: projectRoot
19138
19159
  };
19139
- if (process$1.platform === "win32") return {
19140
- command: "cmd",
19160
+ if (packageManager === "yarn") return {
19161
+ command: "yarn",
19141
19162
  args: [
19142
- "/c",
19143
- "start",
19144
- "",
19145
- url
19146
- ]
19163
+ "add",
19164
+ "--dev",
19165
+ packageSpecifier
19166
+ ],
19167
+ cwd: projectRoot
19168
+ };
19169
+ if (packageManager === "bun") return {
19170
+ command: "bun",
19171
+ args: [
19172
+ "add",
19173
+ "--dev",
19174
+ packageSpecifier
19175
+ ],
19176
+ cwd: projectRoot
19147
19177
  };
19148
19178
  return {
19149
- command: "xdg-open",
19150
- args: [url]
19179
+ command: "pnpm",
19180
+ args: [
19181
+ "add",
19182
+ "--save-dev",
19183
+ ...packageManagerNeedsWorkspaceFlag(projectRoot) ? ["-w"] : [],
19184
+ packageSpecifier
19185
+ ],
19186
+ cwd: projectRoot
19151
19187
  };
19152
19188
  };
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
19189
  const execFileAsync = promisify(execFile);
19176
- const run = async (command, args, cwd) => {
19190
+ const defaultInstallDependencyRunner = async (input) => {
19191
+ await execFileAsync(input.command, [...input.args], {
19192
+ cwd: input.cwd,
19193
+ env: {
19194
+ ...process.env,
19195
+ REACT_DOCTOR_INSTALL: "1"
19196
+ },
19197
+ shell: process.platform === "win32"
19198
+ });
19199
+ };
19200
+ const isSupplyChainTrustError = (error) => {
19201
+ const candidate = error;
19202
+ const haystack = [
19203
+ candidate?.stderr,
19204
+ candidate?.stdout,
19205
+ candidate?.message
19206
+ ].map((part) => String(part ?? "")).join("\n");
19207
+ return /ERR_PNPM_TRUST_DOWNGRADE|trust downgrade/i.test(haystack);
19208
+ };
19209
+ const formatInstallCommand = (input) => [input.command, ...input.args].join(" ");
19210
+ const installReactDoctorDependency = async (options) => {
19211
+ const packageJson = readPackageJson(options.projectRoot);
19212
+ if (!isRecord(packageJson)) return {
19213
+ dependencyStatus: "skipped",
19214
+ dependencyReason: "missing-or-invalid-package-json"
19215
+ };
19216
+ if (hasDoctorDependency(packageJson)) return { dependencyStatus: "existing" };
19217
+ if (packageJson.devDependencies !== void 0 && !isRecord(packageJson.devDependencies)) return {
19218
+ dependencyStatus: "skipped",
19219
+ dependencyReason: "invalid-dev-dependencies"
19220
+ };
19221
+ const runnerInput = buildInstallCommand(options.projectRoot);
19177
19222
  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
- };
19223
+ await (options.runner ?? defaultInstallDependencyRunner)(runnerInput);
19187
19224
  } catch (error) {
19188
- const failure = error;
19189
19225
  return {
19190
- success: false,
19191
- stdout: (failure.stdout ?? "").trim(),
19192
- stderr: (failure.stderr ?? "").trim()
19226
+ dependencyStatus: "skipped",
19227
+ dependencyReason: isSupplyChainTrustError(error) ? "trust-policy-blocked" : "install-command-failed",
19228
+ installCommand: formatInstallCommand(runnerInput)
19193
19229
  };
19194
19230
  }
19231
+ return { dependencyStatus: "created" };
19195
19232
  };
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;
19233
+ const buildManualGitHookTarget = (hookPath, projectRoot) => ({
19234
+ hookPath,
19235
+ runnerRoot: projectRoot,
19236
+ kind: "git"
19237
+ });
19238
+ const formatGitHookInstallMessage = (hookResult) => {
19239
+ 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.`;
19240
+ return `React Doctor pre-commit hook ${hookResult.status} at ${hookResult.hookPath}.`;
19213
19241
  };
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, "")}`;
19242
+ const formatDependencyInstallMessage = (result) => {
19243
+ if (result.dependencyStatus === "created") return "Installed dev dependency: react-doctor.";
19244
+ if (result.dependencyStatus === "existing") return "React Doctor dependency already exists.";
19245
+ if (result.dependencyReason === "invalid-dev-dependencies") return "Skipped dev dependency install: devDependencies field is not an object.";
19246
+ 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).";
19247
+ if (result.dependencyReason === "install-command-failed") return "Local install failed: your package manager rejected the command.";
19248
+ return "Skipped dev dependency install: package.json missing or invalid.";
19221
19249
  };
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
- };
19250
+ const buildDependencyFollowUp = (result) => {
19251
+ if (result.dependencyReason !== "trust-policy-blocked" && result.dependencyReason !== "install-command-failed") return;
19252
+ return ` React Doctor still works via \`npx react-doctor\`. To install locally: ${result.installCommand ?? `npm install --save-dev react-doctor@latest`}`;
19253
+ };
19254
+ const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) => {
19255
+ installReactDoctorScriptStep(projectRoot);
19256
+ const dependencySpinner = spinner("Installing React Doctor package...").start();
19257
+ try {
19258
+ const dependencyResult = await installReactDoctorDependency({
19259
+ projectRoot,
19260
+ runner: dependencyRunner
19261
+ });
19262
+ recordCount(METRIC.installDependency, 1, {
19263
+ status: dependencyResult.dependencyStatus,
19264
+ reason: dependencyResult.dependencyReason ?? null,
19265
+ packageManager: detectPackageManager(projectRoot)
19266
+ });
19267
+ if (dependencyResult.dependencyStatus === "skipped") {
19268
+ const message = formatDependencyInstallMessage(dependencyResult);
19269
+ if (dependencyResult.dependencyReason === "trust-policy-blocked") dependencySpinner.warn(message);
19270
+ else dependencySpinner.fail(message);
19271
+ const followUp = buildDependencyFollowUp(dependencyResult);
19272
+ if (followUp !== void 0) cliLogger.dim(followUp);
19273
+ return dependencyResult;
19274
+ }
19275
+ dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
19276
+ return dependencyResult;
19277
+ } catch (error) {
19278
+ dependencySpinner.fail("Failed to install React Doctor package.");
19279
+ throw error;
19280
+ }
19281
+ };
19282
+ const getSkillSourceDirectory = () => {
19283
+ const distDirectory = path$1.dirname(fileURLToPath(import.meta.url));
19284
+ return path$1.join(distDirectory, "skills", SKILL_NAME);
19285
+ };
19286
+ const canInstallNativeAgentHooks = (agents) => agents.some((agent) => agent === "claude-code" || agent === "cursor");
19287
+ const installReactDoctorSkillStep = async (sourceDir, selectedAgents, projectRoot) => {
19288
+ const installSpinner = spinner(`Installing ${SKILL_NAME} skill...`).start();
19289
+ try {
19290
+ const installResult = await installSkillsFromSource({
19291
+ source: sourceDir,
19292
+ agents: selectedAgents,
19293
+ cwd: projectRoot,
19294
+ mode: "copy"
19295
+ });
19296
+ if (installResult.skills.length === 0) throw new Error(`Could not parse ${SKILL_MANIFEST_FILE} for ${SKILL_NAME} (missing or invalid frontmatter).`);
19297
+ if (installResult.failed.length > 0) throw new Error(installResult.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
19298
+ installSpinner.succeed(`${SKILL_NAME} skill installed for ${selectedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19299
+ } catch (error) {
19300
+ installSpinner.fail(`Failed to install ${SKILL_NAME} skill.`);
19301
+ throw error;
19289
19302
  }
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
- };
19303
+ };
19304
+ const installReactDoctorGitHookStep = (gitHookTarget) => {
19305
+ const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
19306
+ try {
19307
+ const hookResult = installReactDoctorGitHook({
19308
+ hookPath: gitHookTarget.hookPath,
19309
+ projectRoot: gitHookTarget.runnerRoot,
19310
+ kind: gitHookTarget.kind,
19311
+ hooksPathConfig: gitHookTarget.hooksPathConfig
19312
+ });
19313
+ hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
19314
+ recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
19315
+ } catch (error) {
19316
+ hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
19317
+ throw error;
19300
19318
  }
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
- };
19319
+ };
19320
+ const installReactDoctorAgentHooksStep = (projectRoot, selectedAgents) => {
19321
+ const hookSpinner = spinner("Installing React Doctor agent hooks...").start();
19322
+ try {
19323
+ const hookResult = installReactDoctorAgentHooks({
19324
+ projectRoot,
19325
+ agents: selectedAgents
19326
+ });
19327
+ if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
19328
+ else {
19329
+ hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19330
+ recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
19331
+ }
19332
+ } catch (error) {
19333
+ hookSpinner.fail("Failed to install React Doctor agent hooks.");
19334
+ throw error;
19312
19335
  }
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
19336
  };
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;
19337
+ const installReactDoctorWorkflowStep = (projectRoot) => {
19338
+ return reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
19339
+ };
19340
+ const upgradeReactDoctorWorkflowStep = (projectRoot) => {
19341
+ const workflowSpinner = spinner("Upgrading GitHub Actions workflow to v2...").start();
19342
+ const upgradeResult = upgradeReactDoctorWorkflowInPlace(projectRoot);
19343
+ if (upgradeResult.status === "failed") {
19344
+ workflowSpinner.fail("Couldn't update the GitHub Actions workflow.");
19345
+ return false;
19346
+ }
19347
+ if (upgradeResult.status === "not-needed") {
19348
+ workflowSpinner.succeed("GitHub Actions workflow already up to date.");
19349
+ return false;
19350
+ }
19351
+ workflowSpinner.succeed(`Upgraded the GitHub Actions workflow to v2 at ${path$1.relative(projectRoot, upgradeResult.workflowPath)}.`);
19352
+ recordCount(METRIC.installWorkflow, 1, { kind: "upgrade" });
19353
+ return true;
19354
+ };
19355
+ const runInstallReactDoctor = async (options = {}) => {
19356
+ const requestedProjectRoot = options.projectRoot ?? process.cwd();
19357
+ const projectRoot = findNearestPackageDirectory(requestedProjectRoot) ?? requestedProjectRoot;
19358
+ const sourceDir = options.sourceDir ?? getSkillSourceDirectory();
19359
+ if (!fs$1.existsSync(path$1.join(sourceDir, SKILL_MANIFEST_FILE))) {
19360
+ cliLogger.error(`Could not locate the ${SKILL_NAME} skill bundled with this package.`);
19361
+ process.exitCode = 1;
19362
+ return;
19363
+ }
19364
+ const detectedAgents = options.detectedAgents ?? await detectAvailableAgents();
19365
+ if (detectedAgents.length === 0) {
19366
+ cliLogger.error("No supported coding agents detected.");
19367
+ cliLogger.dim(" Looked for binaries on PATH (claude, codex, cursor, droid, gemini, copilot, opencode, pi)");
19368
+ cliLogger.dim(" and config dirs in $HOME (~/.claude, ~/.cursor, ~/.codex, ~/.gemini, ...).");
19369
+ process.exitCode = 1;
19370
+ return;
19371
+ }
19372
+ const skipPrompts = shouldSkipPrompts({ yes: options.yes });
19373
+ const gitHookTarget = options.gitHookPath === void 0 ? detectGitHookTarget(projectRoot) : options.gitHookPath === null ? null : buildManualGitHookTarget(options.gitHookPath, projectRoot);
19374
+ const gitHookPath = gitHookTarget?.hookPath;
19375
+ const promptOptions = options.onPromptCancel === void 0 ? {} : { onCancel: options.onPromptCancel };
19376
+ const prompt = options.prompt ?? prompts;
19377
+ const workflowTargetPath = getReactDoctorWorkflowPath(projectRoot);
19378
+ const existingWorkflow = readReactDoctorWorkflow(projectRoot);
19379
+ const canInstallWorkflow = !fs$1.existsSync(workflowTargetPath);
19380
+ const canUpgradeWorkflow = existingWorkflow !== null && workflowUsesV1Action(existingWorkflow.content) && !hasHandledActionUpgrade(projectRoot);
19381
+ const shouldInstallWorkflow = canInstallWorkflow && (Boolean(options.yes) || !skipPrompts && await askAddToGitHubActions(prompt) === "yes");
19382
+ const upgradePromptOutcome = canUpgradeWorkflow && !options.yes && !skipPrompts ? await askUpgradeActionVersion(prompt) : null;
19383
+ const shouldUpgradeWorkflow = canUpgradeWorkflow && (Boolean(options.yes) || upgradePromptOutcome === "yes");
19384
+ if (upgradePromptOutcome === "no" && !options.dryRun) recordActionUpgradeDecision(projectRoot, "declined");
19385
+ const selectedAgents = skipPrompts ? detectedAgents : (await prompt({
19386
+ type: "multiselect",
19387
+ name: "agents",
19388
+ message: `Install the ${highlighter.info(`/react-doctor`)} skill for:`,
19389
+ choices: detectedAgents.map((agent) => ({
19390
+ title: getSkillAgentConfig(agent).displayName,
19391
+ value: agent,
19392
+ selected: true
19393
+ })),
19394
+ instructions: false,
19395
+ min: 1
19396
+ }, promptOptions)).agents ?? [];
19397
+ if (selectedAgents.length === 0) return;
19398
+ let dependencyResult;
19399
+ if (!options.dryRun) {
19400
+ await installReactDoctorSkillStep(sourceDir, selectedAgents, projectRoot);
19401
+ dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
19402
+ }
19403
+ let didInstallWorkflow = false;
19404
+ if (!options.dryRun && (shouldInstallWorkflow || shouldUpgradeWorkflow)) {
19405
+ cliLogger.break();
19406
+ if (shouldInstallWorkflow) didInstallWorkflow = installReactDoctorWorkflowStep(projectRoot);
19407
+ else if (upgradeReactDoctorWorkflowStep(projectRoot)) recordActionUpgradeDecision(projectRoot, "accepted");
19408
+ }
19409
+ const setupActionChoices = [...gitHookPath === null || gitHookPath === void 0 ? [] : [{
19410
+ title: "Pre-commit hook",
19411
+ description: "Check staged changes before each commit",
19412
+ value: SETUP_OPTION_GIT_HOOK,
19413
+ selected: true
19414
+ }], ...canInstallNativeAgentHooks(selectedAgents) ? [{
19415
+ title: "Agent hooks",
19416
+ description: "Ask Claude Code or Cursor to scan after code edits",
19417
+ value: SETUP_OPTION_AGENT_HOOKS,
19418
+ selected: Boolean(options.agentHooks)
19419
+ }] : []];
19420
+ const setupChoices = setupActionChoices.length === 0 ? [] : [{
19421
+ title: "Skip optional setup",
19422
+ description: "Install only the agent skill and package setup",
19423
+ value: SETUP_OPTION_SKIP,
19424
+ selected: false
19425
+ }, ...setupActionChoices];
19426
+ if (setupChoices.length > 0 && !options.dryRun) cliLogger.break();
19427
+ const selectedSetupOptions = skipPrompts || setupChoices.length === 0 ? [] : (await prompt({
19428
+ type: "multiselect",
19429
+ name: "setupOptions",
19430
+ message: "Select additional React Doctor setup:",
19431
+ choices: setupChoices,
19432
+ instructions: false
19433
+ }, promptOptions)).setupOptions ?? [];
19434
+ const selectedSetupActions = selectedSetupOptions.filter((setupOption) => setupOption !== SETUP_OPTION_SKIP);
19435
+ const didSkipOptionalSetup = selectedSetupActions.length === 0 && selectedSetupOptions.includes(SETUP_OPTION_SKIP);
19436
+ const shouldInstallGitHook = gitHookPath != null && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_GIT_HOOK));
19437
+ const shouldInstallAgentHooks = Boolean(options.agentHooks) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_AGENT_HOOKS);
19438
+ if (!options.dryRun) {
19439
+ if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) installReactDoctorGitHookStep(gitHookTarget);
19440
+ if (shouldInstallAgentHooks) installReactDoctorAgentHooksStep(projectRoot, selectedAgents);
19441
+ }
19442
+ if (options.dryRun) {
19443
+ cliLogger.log(`Dry run — would install ${SKILL_NAME} skill for:`);
19444
+ for (const agent of selectedAgents) cliLogger.dim(` - ${getSkillAgentConfig(agent).displayName}`);
19445
+ cliLogger.dim(` Source: ${sourceDir}`);
19446
+ cliLogger.dim(" Package script: doctor (or react-doctor if doctor exists)");
19447
+ cliLogger.dim(" Dev dependency: react-doctor");
19448
+ if (shouldInstallGitHook) cliLogger.dim(` Git hook: ${gitHookPath}`);
19449
+ if (shouldInstallAgentHooks) cliLogger.dim(" Agent hooks: Claude Code / Cursor when selected");
19450
+ if (shouldInstallWorkflow) cliLogger.dim(` GitHub Actions workflow: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19451
+ if (shouldUpgradeWorkflow) cliLogger.dim(` Upgrade GitHub Actions workflow to v2: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19452
+ return;
19453
+ }
19454
+ recordCount(METRIC.installCompleted, 1, {
19455
+ agentsCount: selectedAgents.length,
19456
+ gitHook: shouldInstallGitHook,
19457
+ agentHooks: shouldInstallAgentHooks,
19458
+ workflow: didInstallWorkflow,
19459
+ dependencyStatus: dependencyResult?.dependencyStatus ?? "skipped",
19460
+ packageManager: detectPackageManager(projectRoot)
19461
+ });
19462
+ for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
19463
+ };
19464
+ //#endregion
19465
+ //#region src/cli/utils/install-skill-for-agent.ts
19466
+ const installReactDoctorSkillForAgent = async (agent, projectRoot) => {
19467
+ const source = getSkillSourceDirectory();
19468
+ if (!fs$1.existsSync(path$1.join(source, SKILL_MANIFEST_FILE))) return false;
19469
+ const result = await installSkillsFromSource({
19470
+ source,
19471
+ agents: [agent],
19472
+ cwd: projectRoot,
19473
+ mode: "copy"
19474
+ });
19475
+ return result.skills.length > 0 && result.failed.length === 0;
19344
19476
  };
19345
19477
  //#endregion
19346
19478
  //#region src/cli/utils/launch-agent.ts
@@ -19431,9 +19563,6 @@ const copyToClipboard = (text) => {
19431
19563
  };
19432
19564
  //#endregion
19433
19565
  //#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
19566
  const CLIPBOARD_CHOICE = "clipboard";
19438
19567
  const SKIP_CHOICE = "skip";
19439
19568
  const printPayload = (payload) => {
@@ -19442,59 +19571,11 @@ const printPayload = (payload) => {
19442
19571
  cliLogger.log(payload);
19443
19572
  cliLogger.log(highlighter.dim("──────────────────────"));
19444
19573
  };
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
19574
  const UPGRADE_COMMIT_MESSAGE = "ci: upgrade React Doctor GitHub Action to v2";
19474
19575
  const UPGRADE_PR_TITLE = "Upgrade React Doctor Action to v2";
19475
19576
  const UPGRADE_PR_BODY = `Bumps the React Doctor GitHub Actions workflow to the action's latest major, \`millionco/react-doctor@v2\`.
19476
19577
 
19477
19578
  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
19579
  const upgradeGitHubActionsWorkflow = async (workflow) => {
19499
19580
  const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
19500
19581
  if (!changed) return false;
@@ -19539,46 +19620,6 @@ const maybeOfferActionUpgrade = async (projectRoot) => {
19539
19620
  }
19540
19621
  if (await upgradeGitHubActionsWorkflow(workflow)) recordActionUpgradeDecision(projectRoot, "accepted");
19541
19622
  };
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
19623
  const detectLaunchableAgents = async () => {
19583
19624
  const detected = new Set(await detectAvailableAgents());
19584
19625
  return Object.keys(CLI_AGENT_BINARIES).filter((agentId) => detected.has(agentId) && isCommandAvailable(CLI_AGENT_BINARIES[agentId]));
@@ -19595,7 +19636,7 @@ const handoffToAgent = async (input) => {
19595
19636
  });
19596
19637
  if (ciOutcome === "cancel") return;
19597
19638
  if (ciOutcome === "yes") {
19598
- await setUpGitHubActions(input.rootDirectory);
19639
+ await setUpGitHubActions({ rootDirectory: input.rootDirectory });
19599
19640
  cliLogger.break();
19600
19641
  }
19601
19642
  } else await maybeOfferActionUpgrade(projectRootForCi);
@@ -19746,6 +19787,14 @@ const HAPPY_FACE_LINES = [
19746
19787
  "│ ▽ │",
19747
19788
  "└─────┘"
19748
19789
  ];
19790
+ const FACE_INDENT = " ";
19791
+ const FACE_PREFIX_WIDTH = 2 + (HAPPY_FACE_LINES[0]?.length ?? 0) + 2;
19792
+ const clampToColumns = (text, maxColumns) => {
19793
+ if (maxColumns <= 0) return "";
19794
+ if (text.length <= maxColumns) return text;
19795
+ if (maxColumns === 1) return "…";
19796
+ return `${text.slice(0, maxColumns - 1).trimEnd()}…`;
19797
+ };
19749
19798
  const typeLine = (linePrefix, text, style, charDelayMs) => Effect.gen(function* () {
19750
19799
  const characters = [...text];
19751
19800
  for (let length = 1; length <= characters.length; length += 1) {
@@ -19759,13 +19808,17 @@ const playWelcomeScene = (options = {}) => Effect.gen(function* () {
19759
19808
  const interLineDelayMs = 250 / speedMultiplier;
19760
19809
  const explanationHoldMs = WELCOME_EXPLANATION_HOLD_MS / speedMultiplier;
19761
19810
  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`);
19811
+ const mouthPrefix = `${FACE_INDENT}${face[2] ?? ""}${FACE_INDENT}`;
19812
+ const terminalColumns = process.stdout.columns;
19813
+ const availableTextColumns = terminalColumns && terminalColumns > 0 ? Math.max(0, terminalColumns - FACE_PREFIX_WIDTH - 1) : Number.POSITIVE_INFINITY;
19814
+ const greeting = clampToColumns("Welcome to React Doctor", availableTextColumns);
19815
+ const tagline = clampToColumns("I diagnose your React code for bugs, security & performance.", availableTextColumns);
19816
+ yield* writeStdout(`\n${face.map((line) => `${FACE_INDENT}${line}`).join("\n")}\n`);
19764
19817
  yield* writeStdout("\x1B[3A");
19765
- yield* typeLine(` ${face[1] ?? ""} `, "Welcome to React Doctor", (fragment) => highlighter.bold(fragment), charDelayMs);
19818
+ yield* typeLine(`${FACE_INDENT}${face[1] ?? ""}${FACE_INDENT}`, greeting, (fragment) => highlighter.bold(fragment), charDelayMs);
19766
19819
  yield* Effect.sleep(interLineDelayMs);
19767
19820
  yield* writeStdout("\x1B[1B");
19768
- yield* typeLine(mouthPrefix, "I diagnose your React code for bugs, security & performance.", (fragment) => highlighter.dim(fragment), charDelayMs);
19821
+ yield* typeLine(mouthPrefix, tagline, (fragment) => highlighter.dim(fragment), charDelayMs);
19769
19822
  yield* Effect.sleep(explanationHoldMs);
19770
19823
  yield* writeStdout("\x1B[3A\r\x1B[0J");
19771
19824
  });
@@ -21521,4 +21574,4 @@ Promise.resolve().then(() => assertNoRemovedFlags(process.argv)).then(() => prog
21521
21574
  export {};
21522
21575
 
21523
21576
  //# sourceMappingURL=cli.js.map
21524
- //# debugId=1486eaee-ed07-5eef-a9d7-51293140e237
21577
+ //# debugId=2ea4b3e1-2440-54c8-ae15-199dbd57bbe6