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