@percy/cli-doctor 1.31.10-beta.2 → 1.31.10

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @percy/cli-doctor
2
2
 
3
- > Percy CLI sub-command that diagnoses network readiness for running Percy builds.
3
+ > Percy CLI sub-command that diagnoses network, authentication, configuration, and CI readiness for running Percy builds.
4
4
 
5
5
  ---
6
6
 
@@ -30,10 +30,14 @@ percy doctor [options]
30
30
  Options:
31
31
  --proxy-server <url> Proxy server to test alongside direct connectivity
32
32
  e.g. http://proxy.corp.example.com:8080
33
- --url <urls> Extra URL(s) to probe (comma-separated)
34
- --timeout <ms> Per-request timeout in milliseconds (default: 10000)
35
- --fix Automatically apply suggested Percy config fixes
36
- -v, --verbose Log everything
33
+ --url <url> URL to open in Chrome for network activity analysis
34
+ (default: https://percy.io)
35
+ --timeout <ms> Per-request timeout in milliseconds
36
+ (default: 10000, max: 300000)
37
+ --quick Run only connectivity, SSL, and token auth checks
38
+ (~4 seconds instead of a full diagnostic run)
39
+ --output-json <path> Write the full diagnostic report to a JSON file
40
+ -v, --verbose Show detailed debug output
37
41
  -h, --help Show help
38
42
  ```
39
43
 
@@ -41,20 +45,64 @@ Options:
41
45
 
42
46
  ## What it checks
43
47
 
44
- ### 1 · SSL / TLS
48
+ ### 1 · Configuration Validation
45
49
 
46
- | Scenario | Outcome |
50
+ Detects and validates Percy configuration files (`.percy.yml`, `.percy.yaml`, `percy.config.js`, etc.) via cosmiconfig:
51
+
52
+ - Reports file location and format
53
+ - Warns on missing or outdated `version` field (recommends version 2)
54
+ - Detects project-type/config mismatches (e.g., automate-only keys like `fullPage` used with a web token)
55
+
56
+ | Category | Meaning |
47
57
  |---|---|
48
- | `NODE_TLS_REJECT_UNAUTHORIZED=0` is set | **Warning** – SSL verification is disabled globally |
49
- | SSL certificate error connecting to percy.io | **Fail** – likely a MITM proxy/VPN; suggests remediation |
50
- | SSL handshake succeeds | **Pass** |
58
+ | `config_not_found` | No Percy config file detected |
59
+ | `config_found` | Config file located and loaded |
60
+ | `config_parse_error` | Config file has YAML/JSON syntax errors |
61
+ | `config_version_invalid` | `version` field is missing or non-numeric |
62
+ | `config_version_outdated` | Config uses an outdated version (< 2) |
63
+ | `config_key_automate_only` | Config contains Automate-only keys but token is not Automate |
64
+ | `config_key_web_only` | Config contains Web-only keys but token is not a Web token |
65
+
66
+ ### 2 · CI Environment Detection
51
67
 
52
- When a certificate error is detected, the command:
53
- * Prints actionable suggestions (contact network admin, add proxy cert to trust store)
54
- * With `--fix`: patches the nearest `.percy.yml` to add `ssl: { rejectUnauthorized: false }`
55
- * When running interactively in a TTY: offers an inline yes/no prompt
68
+ Detects your CI provider and validates CI-related settings:
56
69
 
57
- ### 2 · Network Connectivity
70
+ - Identifies 10+ CI systems (GitHub Actions, GitLab CI, Jenkins, CircleCI, Travis, etc.)
71
+ - Validates git availability for commit/branch detection
72
+ - Checks parallel build configuration (`PERCY_PARALLEL_TOTAL` + `PERCY_PARALLEL_NONCE`)
73
+
74
+ | Category | Meaning |
75
+ |---|---|
76
+ | `ci_not_detected` | Not running in a CI environment |
77
+ | `ci_detected` | CI system identified |
78
+ | `ci_commit_missing` | Commit SHA could not be detected |
79
+ | `ci_commit_found` | Commit SHA available |
80
+ | `ci_branch_missing` | Branch name could not be detected |
81
+ | `ci_parallel_nonce_missing` | `PERCY_PARALLEL_TOTAL` set without `PERCY_PARALLEL_NONCE` |
82
+ | `ci_parallel_config_valid` | Both parallel env vars are set correctly |
83
+ | `ci_git_available` | Git repository detected |
84
+ | `ci_git_check_skipped` | Git check suppressed via `PERCY_SKIP_GIT_CHECK=true` |
85
+ | `ci_git_unavailable` | Git not installed or not in a git repository |
86
+
87
+ ### 3 · Environment Variable Audit
88
+
89
+ Inventories all Percy-specific environment variables:
90
+
91
+ - Lists all set `PERCY_*` vars (names only — values are never exposed)
92
+ - Validates `PERCY_PARALLEL_TOTAL` is a positive integer
93
+ - Flags manual overrides (`PERCY_COMMIT`, `PERCY_BRANCH`, `PERCY_PULL_REQUEST`)
94
+ - Warns when `NODE_TLS_REJECT_UNAUTHORIZED=0` disables SSL validation
95
+
96
+ | Category | Meaning |
97
+ |---|---|
98
+ | `env_system_info` | OS, Node version, CPU, and RAM summary |
99
+ | `env_no_percy_vars` | No `PERCY_*` environment variables detected |
100
+ | `env_vars_listed` | Lists names of all set `PERCY_*` variables |
101
+ | `env_parallel_total_invalid` | `PERCY_PARALLEL_TOTAL` is not a valid positive integer |
102
+ | `env_manual_overrides` | Manual override vars active (e.g. `PERCY_COMMIT`, `PERCY_BRANCH`) |
103
+ | `env_tls_disabled` | `NODE_TLS_REJECT_UNAUTHORIZED=0` — SSL validation globally disabled |
104
+
105
+ ### 4 · Network Connectivity
58
106
 
59
107
  Probes each required Percy / BrowserStack domain:
60
108
 
@@ -70,7 +118,18 @@ Failure modes are classified as:
70
118
  * **ETIMEDOUT / ECONNRESET** → Firewall dropping packets; list CIDRs to whitelist
71
119
  * **via proxy only** → Proxy required, suggests setting `HTTPS_PROXY`
72
120
 
73
- ### 3 · Proxy Detection
121
+ ### 5 · SSL / TLS
122
+
123
+ | Scenario | Outcome |
124
+ |---|---|
125
+ | `NODE_TLS_REJECT_UNAUTHORIZED=0` is set | **Warning** – SSL verification is disabled globally |
126
+ | SSL certificate error connecting to percy.io | **Fail** – likely a MITM proxy/VPN; suggests remediation |
127
+ | SSL handshake succeeds | **Pass** |
128
+
129
+ When a certificate error is detected, the command prints actionable suggestions
130
+ (contact network admin, add proxy cert to trust store, set `NODE_EXTRA_CA_CERTS`).
131
+
132
+ ### 6 · Proxy Detection
74
133
 
75
134
  Detects proxy configuration from (in priority order):
76
135
 
@@ -83,7 +142,7 @@ Detects proxy configuration from (in priority order):
83
142
  Each discovered proxy is validated by attempting connections to percy.io and
84
143
  browserstack.com through it.
85
144
 
86
- ### 4 · PAC / WPAD Auto-Proxy Configuration
145
+ ### 7 · PAC / WPAD Auto-Proxy Configuration
87
146
 
88
147
  Detects PAC file URLs from:
89
148
 
@@ -103,12 +162,72 @@ using shims for all standard PAC helper functions. The result of
103
162
  If a PAC file routes percy.io through a proxy the command surfaces the exact
104
163
  `HTTPS_PROXY=…` export statement to add to your CI environment.
105
164
 
165
+ ### 8 · Token Authentication
166
+
167
+ Validates the `PERCY_TOKEN` environment variable:
168
+
169
+ - **Presence**: Checks the token is set
170
+ - **Format**: Detects project type from token prefix (`web_`, `auto_`, `app_`, `ss_`, `vmw_`, `res_`) and suggests the correct CLI command
171
+ - **Authentication**: Makes a live API call to `percy.io/api/v1/tokens` to verify the token is valid (uses proxy if one was discovered in earlier checks)
172
+
173
+ Token values are **never** included in output — only the project type and pass/fail status.
174
+
175
+ | Category | Meaning |
176
+ |---|---|
177
+ | `token_missing` | `PERCY_TOKEN` is not set or is blank |
178
+ | `token_type_info` | Token prefix decoded — project type and suggested CLI command |
179
+ | `token_auth_pass` | Token authenticated successfully; role shown |
180
+ | `token_auth_fail` | Token rejected (HTTP 401 or 403) |
181
+ | `token_auth_unexpected_status` | Percy API returned an unexpected HTTP status |
182
+ | `token_auth_network_error` | Could not reach Percy API to validate token |
183
+ | `check_skipped` | Token validation skipped because percy.io is unreachable |
184
+
185
+ ### 9 · Browser Network (Chrome CDP)
186
+
187
+ Launches headless Chrome to test end-to-end network connectivity through the browser process, including proxy and PAC resolution as Chrome would see it.
188
+
189
+ ---
190
+
191
+ ## Quick Mode
192
+
193
+ Use `--quick` to run only the essential checks (connectivity, SSL, and token auth) in ~4 seconds:
194
+
195
+ ```sh
196
+ npx percy doctor --quick
197
+ ```
198
+
199
+ This is useful for fast triage in CI pipelines or when you just want to verify your token and network are working.
200
+
201
+ ---
202
+
203
+ ## Auto-Doctor on Build Failure
204
+
205
+ Set `PERCY_AUTO_DOCTOR=true` to automatically run diagnostics when a Percy build fails:
206
+
207
+ ```sh
208
+ export PERCY_AUTO_DOCTOR=true
209
+ npx percy exec -- your-test-command
210
+ ```
211
+
212
+ When enabled, a build failure triggers a diagnostic run and prints actionable findings inline. This is opt-in and has no effect on successful builds.
213
+
106
214
  ---
107
215
 
108
216
  ## Example output
109
217
 
110
218
  ```
111
- Percy Doctor — network readiness check
219
+ Percy Doctor — diagnostic check
220
+
221
+ ── Configuration
222
+ ℹ Configuration file detected: /project/.percy.yml
223
+ ✔ Config version: 2 (current)
224
+
225
+ ── CI Environment
226
+ ℹ CI system detected: GitHub Actions
227
+ ✔ Git is available for commit detection.
228
+
229
+ ── Environment Variables
230
+ ℹ Percy environment variables set: PERCY_TOKEN, PERCY_PARALLEL_TOTAL
112
231
 
113
232
  ── SSL / TLS
114
233
  ✔ SSL handshake with percy.io succeeded (47ms).
@@ -124,30 +243,16 @@ If a PAC file routes percy.io through a proxy the command surfaces the exact
124
243
  ── PAC / Auto-Proxy Configuration
125
244
  ℹ No PAC (Proxy Auto-Configuration) file detected.
126
245
 
127
- ✔ All 6 checks passed
128
- ```
129
-
130
- ---
246
+ ── Token Authentication
247
+ ℹ Token detected (project type: web). Use `percy exec` to run snapshots.
248
+ ✔ Token authentication successful.
131
249
 
132
- ## Configuration fix (`--fix`)
250
+ ── Browser Network
251
+ ✔ Chrome loaded percy.io successfully.
133
252
 
134
- When the doctor detects an SSL certificate error it can automatically patch the
135
- nearest Percy configuration file (`.percy.yml` / `.percy.yaml`):
136
-
137
- ```sh
138
- percy doctor --fix
139
- ```
140
-
141
- This appends the following snippet to your config:
142
-
143
- ```yaml
144
- ssl:
145
- rejectUnauthorized: false
253
+ ✔ 8 passed · 0 warnings · 0 failures (4.2s)
146
254
  ```
147
255
 
148
- > **Note**: disabling SSL verification is a security trade-off. Use it only
149
- > when your network proxy performs SSL inspection and you trust the proxy's CA.
150
-
151
256
  ---
152
257
 
153
258
  ## License
@@ -0,0 +1,145 @@
1
+ import { httpProber } from '../utils/http.js';
2
+
3
+ // Strip raw token value from error messages to prevent credential leakage.
4
+ // Uses split/join instead of replaceAll for Node.js 14 compatibility.
5
+ function sanitizeError(msg) {
6
+ var _process$env$PERCY_TO;
7
+ /* istanbul ignore next */
8
+ if (!msg) return msg;
9
+ let sanitized = msg.replace(/Token token=[^\s,;)']*/gi, 'Token token=***');
10
+ /* istanbul ignore next */
11
+ const token = (_process$env$PERCY_TO = process.env.PERCY_TOKEN) === null || _process$env$PERCY_TO === void 0 ? void 0 : _process$env$PERCY_TO.trim();
12
+ /* istanbul ignore next */
13
+ if (token) sanitized = sanitized.split(token).join('***');
14
+ return sanitized;
15
+ }
16
+
17
+ /**
18
+ * Validate PERCY_TOKEN presence and authenticate against the Percy API.
19
+ * Uses GET /api/v1/token to obtain token type and role directly from the API —
20
+ * no client-side prefix splitting required.
21
+ *
22
+ * @param {object} [options]
23
+ * @param {string} [options.proxyUrl] - Proxy for API call (from ctx.bestProxy)
24
+ * @param {number} [options.timeout] - Request timeout ms
25
+ * @param {string} [options.apiBaseUrl] - Base URL for token API (for testing)
26
+ * @returns {Promise<Finding[]>}
27
+ */
28
+ export async function checkAuth(options = {}) {
29
+ var _process$env$PERCY_TO2;
30
+ const {
31
+ proxyUrl,
32
+ timeout = 10000,
33
+ apiBaseUrl = 'https://percy.io'
34
+ } = options;
35
+ const findings = [];
36
+ const token = (_process$env$PERCY_TO2 = process.env.PERCY_TOKEN) === null || _process$env$PERCY_TO2 === void 0 ? void 0 : _process$env$PERCY_TO2.trim();
37
+
38
+ // 1. Presence check
39
+ if (!token) {
40
+ findings.push({
41
+ category: 'token_missing',
42
+ status: 'fail',
43
+ message: 'PERCY_TOKEN is not set.',
44
+ suggestions: ['Set PERCY_TOKEN in your environment: export PERCY_TOKEN=<your-token>', 'Get your token from: https://percy.io → Project Settings → API Token', 'In CI, add PERCY_TOKEN as a secret environment variable.']
45
+ });
46
+ return findings;
47
+ }
48
+
49
+ // 2. Authentication test — GET /api/v1/token returns type + role on 200,
50
+ // 401 for invalid/expired token, 403 for forbidden.
51
+ try {
52
+ const result = await httpProber.probeUrl(`${apiBaseUrl}/api/v1/tokens/details`, {
53
+ proxyUrl,
54
+ timeout,
55
+ method: 'GET',
56
+ headers: {
57
+ Authorization: `Token token=${token}`
58
+ }
59
+ });
60
+ const httpStatus = result.status;
61
+ if (httpStatus === 200) {
62
+ // Parse project-token-type and role from response body
63
+ let projectTokenType = 'unknown';
64
+ let role = 'unknown';
65
+ try {
66
+ var _body$data, _body$data2;
67
+ /* istanbul ignore next */
68
+ const body = typeof result.body === 'string' ? JSON.parse(result.body)
69
+ /* istanbul ignore next */ : result.body;
70
+ /* istanbul ignore next */
71
+ projectTokenType = (body === null || body === void 0 || (_body$data = body.data) === null || _body$data === void 0 || (_body$data = _body$data.attributes) === null || _body$data === void 0 ? void 0 : _body$data['project-token-type']) ?? 'unknown';
72
+ /* istanbul ignore next */
73
+ role = (body === null || body === void 0 || (_body$data2 = body.data) === null || _body$data2 === void 0 || (_body$data2 = _body$data2.attributes) === null || _body$data2 === void 0 ? void 0 : _body$data2.role) ?? 'unknown';
74
+ } catch {
75
+ // Malformed JSON — leave defaults, still a pass
76
+ }
77
+ const cmd = projectTokenType === 'app' ? 'percy app:exec' : 'percy exec';
78
+
79
+ // DR-002: token type info (NEVER emit the token value)
80
+ findings.push({
81
+ category: 'token_type_info',
82
+ status: 'info',
83
+ message: `Token type: ${projectTokenType}. Use \`${cmd}\` to run snapshots.`,
84
+ metadata: {
85
+ projectTokenType,
86
+ role
87
+ }
88
+ });
89
+
90
+ // DR-003: authentication pass with role and actionable hints
91
+ const suggestions = [];
92
+ if (role === 'read_only') {
93
+ suggestions.push('This token cannot create Percy builds. Use a master or write_only token in CI.');
94
+ } else if (role === 'write_only') {
95
+ suggestions.push('This token can create builds but cannot read results via the API.');
96
+ }
97
+ findings.push({
98
+ category: 'token_auth_pass',
99
+ status: 'pass',
100
+ message: `Token authentication successful — role: ${role}.`,
101
+ ...(suggestions.length > 0 && {
102
+ suggestions
103
+ })
104
+ });
105
+ } else if (httpStatus === 401) {
106
+ findings.push({
107
+ category: 'token_auth_fail',
108
+ status: 'fail',
109
+ message: 'Token authentication failed (HTTP 401 Unauthorized).',
110
+ suggestions: ['Your token may be expired, revoked, or incorrectly copied.', 'Get a new token from: https://percy.io → Project Settings → API Token', 'Ensure the full token is set (no truncation from copy-paste).']
111
+ });
112
+ } else if (httpStatus === 403) {
113
+ findings.push({
114
+ category: 'token_auth_fail',
115
+ status: 'fail',
116
+ message: 'Token access denied (HTTP 403 Forbidden).',
117
+ suggestions: ['The token may exist but is not authorized for this operation.', 'Verify you are using the correct token for your project.', 'Get your token from: https://percy.io → Project Settings → API Token']
118
+ });
119
+ } else if (!httpStatus || httpStatus === 0) {
120
+ // Network error — couldn't reach the API at all
121
+ findings.push({
122
+ category: 'token_auth_network_error',
123
+ status: 'warn',
124
+ message: `Token auth check could not reach Percy API: ${sanitizeError(result.error)}`,
125
+ suggestions: ['This may be a network issue rather than a token issue.', 'See the Connectivity and Proxy sections for network diagnostics.']
126
+ });
127
+ } else {
128
+ // Unexpected status code
129
+ findings.push({
130
+ category: 'token_auth_unexpected_status',
131
+ status: 'warn',
132
+ message: `Token auth returned unexpected HTTP ${httpStatus}.`,
133
+ suggestions: ['This may indicate a Percy API issue. Try again later.', 'If persistent, contact Percy support with this diagnostic output.']
134
+ });
135
+ }
136
+ } catch (err) {
137
+ findings.push({
138
+ category: 'token_auth_network_error',
139
+ status: 'warn',
140
+ message: `Token auth check could not reach Percy API: ${sanitizeError(err.message)}`,
141
+ suggestions: ['This may be a network issue rather than a token issue.', 'See the Connectivity and Proxy sections for network diagnostics.']
142
+ });
143
+ }
144
+ return findings;
145
+ }
@@ -0,0 +1,106 @@
1
+ import { search as defaultSearch } from '@percy/config';
2
+ import { tokenType } from '@percy/client';
3
+
4
+ /**
5
+ * Validate Percy configuration file presence, format, and content.
6
+ * Plain async function — matches monorepo functional style.
7
+ *
8
+ * @param {object} [options]
9
+ * @param {function} [options.searchFn] - Config search function (for testing)
10
+ * @returns {Promise<Finding[]>}
11
+ */
12
+ export async function checkConfig(options = {}) {
13
+ var _result, _process$env$PERCY_TO;
14
+ const {
15
+ searchFn = defaultSearch
16
+ } = options;
17
+ const findings = [];
18
+
19
+ // 1. Detect config files using cosmiconfig (same as @percy/config)
20
+ let result;
21
+ try {
22
+ result = searchFn();
23
+ } catch (err) {
24
+ findings.push({
25
+ category: 'config_parse_error',
26
+ status: 'fail',
27
+ message: `Config file could not be loaded: ${err.message}`,
28
+ suggestions: ['Check for YAML/JSON syntax errors in your config file.', 'Run: percy config:validate for detailed error output.']
29
+ });
30
+ return findings;
31
+ }
32
+ if (!((_result = result) !== null && _result !== void 0 && _result.config)) {
33
+ findings.push({
34
+ category: 'config_not_found',
35
+ status: 'info',
36
+ message: 'No Percy configuration file detected.',
37
+ suggestions: ['Percy works with default settings when no config file is present.', 'Create .percy.yml to customize snapshot widths, CSS, and other options.']
38
+ });
39
+ return findings;
40
+ }
41
+
42
+ // 2. Config file found
43
+ findings.push({
44
+ category: 'config_found',
45
+ status: 'pass',
46
+ message: `Configuration file found: ${result.filepath}`
47
+ });
48
+
49
+ // 3. Version check
50
+ const version = parseInt(result.config.version, 10);
51
+ if (Number.isNaN(version)) {
52
+ findings.push({
53
+ category: 'config_version_invalid',
54
+ status: 'warn',
55
+ message: 'Configuration file has missing or invalid version.',
56
+ suggestions: ['Add `version: 2` to the top of your Percy config file.']
57
+ });
58
+ } else if (version < 2) {
59
+ findings.push({
60
+ category: 'config_version_outdated',
61
+ status: 'warn',
62
+ message: `Configuration file uses an outdated format (version ${version}).`,
63
+ suggestions: ['Run: percy config:migrate to update to the latest format.']
64
+ });
65
+ }
66
+
67
+ // 4. Check for project-type-specific config mismatches
68
+ // @percy/config silently deletes keys with onlyAutomate/onlyWeb constraints
69
+ // when the token doesn't match. Surface this to the user.
70
+ const token = (_process$env$PERCY_TO = process.env.PERCY_TOKEN) === null || _process$env$PERCY_TO === void 0 ? void 0 : _process$env$PERCY_TO.trim();
71
+ if (token && result.config) {
72
+ const prefix = token.split('_')[0];
73
+ /* istanbul ignore next */
74
+ const projectType = tokenType(prefix);
75
+ const isAutomate = prefix === 'auto';
76
+
77
+ // Keys that only work with automate tokens
78
+ const automateOnlyKeys = ['fullPage', 'freezeAnimation', 'freezeAnimatedImage', 'freezeAnimatedImageOptions', 'ignoreRegions', 'considerRegions'];
79
+ // Keys that only work with web tokens (not automate, not app)
80
+ const webOnlyKeys = ['waitForTimeout', 'waitForSelector'];
81
+ const snapshotConfig = result.config.snapshot || {};
82
+ if (!isAutomate) {
83
+ const mismatched = automateOnlyKeys.filter(k => snapshotConfig[k] !== undefined);
84
+ if (mismatched.length > 0) {
85
+ findings.push({
86
+ category: 'config_key_automate_only',
87
+ status: 'warn',
88
+ message: `Config keys only supported for Automate projects: ${mismatched.join(', ')}. Your token is for "${projectType}" project type.`,
89
+ suggestions: ['These config keys will be silently ignored for your project type.', 'Remove them from your config or use an Automate project token.']
90
+ });
91
+ }
92
+ }
93
+ if (projectType !== 'web') {
94
+ const mismatched = webOnlyKeys.filter(k => snapshotConfig[k] !== undefined);
95
+ if (mismatched.length > 0) {
96
+ findings.push({
97
+ category: 'config_key_web_only',
98
+ status: 'warn',
99
+ message: `Config keys only supported for Web projects: ${mismatched.join(', ')}. Your token is for "${projectType}" project type.`,
100
+ suggestions: ['These config keys will be silently ignored for your project type.', 'Remove them from your config or use a Web project token.']
101
+ });
102
+ }
103
+ }
104
+ }
105
+ return findings;
106
+ }
@@ -0,0 +1,230 @@
1
+ import PercyEnv from '@percy/env';
2
+ import cp from 'child_process';
3
+ import Monitoring from '@percy/monitoring';
4
+
5
+ /**
6
+ * Combined check: Percy environment variable audit + CI environment detection.
7
+ *
8
+ * - Percy env vars are captured via @percy/monitoring (getPercyEnv / logSystemInfo).
9
+ * - System info (OS, CPU, memory, disk) is captured via monitoring.logSystemInfo()
10
+ * and surfaced as a env_system_info finding.
11
+ * - CI detection and validation (commit SHA, branch, parallel config, git) is
12
+ * merged in from the former ci.js — call ONE function for the whole analysis.
13
+ *
14
+ * SECURITY: Environment variable VALUES are never emitted in findings.
15
+ * Only variable NAMES and validation status are reported.
16
+ *
17
+ * Dependency injection for testing:
18
+ * - monitoringInstance substitute a mock Monitoring instance
19
+ * - percyEnv substitute a mock PercyEnv-like object
20
+ * (must expose .ci, .commit, .branch getters)
21
+ *
22
+ * @param {object} [options]
23
+ * @param {object} [options.monitoringInstance] - Monitoring instance (for testing)
24
+ * @param {object} [options.percyEnv] - PercyEnv-like object (for testing)
25
+ * @returns {Promise<Finding[]>}
26
+ */
27
+ export async function checkEnvAndCI({
28
+ monitoringInstance,
29
+ percyEnv: percyEnvArg
30
+ } = {}) {
31
+ var _systemInfo;
32
+ const findings = [];
33
+
34
+ // ── PART A: System info + Percy env vars via @percy/monitoring ────────────
35
+
36
+ const monitoring = monitoringInstance ?? new Monitoring();
37
+
38
+ // logSystemInfo now returns details AND emits debug logs.
39
+ let systemInfo = null;
40
+ try {
41
+ systemInfo = await monitoring.logSystemInfo();
42
+ } catch {
43
+ // Non-fatal: system info is best-effort.
44
+ }
45
+
46
+ // Use percyEnvs from systemInfo if available; fallback to reading process.env
47
+ // directly. This ensures env vars set at runtime (e.g. in tests via withEnv)
48
+ // are always picked up without requiring monitoring to reflect them.
49
+ function getPercyEnvFromProcess() {
50
+ return Object.fromEntries(Object.entries(process.env).filter(([k]) => k.startsWith('PERCY_') && !k.toLowerCase().includes('token')));
51
+ }
52
+ const percyEnvObj = ((_systemInfo = systemInfo) === null || _systemInfo === void 0 ? void 0 : _systemInfo.percyEnvs) ?? getPercyEnvFromProcess();
53
+ const nonTokenPercyVarNames = Object.keys(percyEnvObj);
54
+
55
+ // PERCY_TOKEN is excluded from getPercyEnv() by design (token filter).
56
+ // Detect its presence separately — NAME only, never value.
57
+ const hasToken = (process.env.PERCY_TOKEN ?? '').trim().length > 0;
58
+ const allSetVarNames = hasToken ? ['PERCY_TOKEN', ...nonTokenPercyVarNames] : nonTokenPercyVarNames;
59
+
60
+ // env_system_info: System info (sourced from monitoring.logSystemInfo return value)
61
+ /* istanbul ignore if */
62
+ if (systemInfo) {
63
+ var _systemInfo$memory, _systemInfo$cpu, _systemInfo$os, _systemInfo$os2;
64
+ const memGb = ((_systemInfo$memory = systemInfo.memory) === null || _systemInfo$memory === void 0 ? void 0 : _systemInfo$memory.totalGb) != null ? systemInfo.memory.totalGb.toFixed(1) : 'N/A';
65
+ const cores = ((_systemInfo$cpu = systemInfo.cpu) === null || _systemInfo$cpu === void 0 ? void 0 : _systemInfo$cpu.cores) ?? 'N/A';
66
+ const platform = ((_systemInfo$os = systemInfo.os) === null || _systemInfo$os === void 0 ? void 0 : _systemInfo$os.platform) ?? process.platform;
67
+ const release = ((_systemInfo$os2 = systemInfo.os) === null || _systemInfo$os2 === void 0 ? void 0 : _systemInfo$os2.release) ?? 'N/A';
68
+ findings.push({
69
+ category: 'env_system_info',
70
+ status: 'info',
71
+ message: `System: ${platform} ${release}, Node ${process.version}, ${cores} CPU core(s), ${memGb}GB RAM`,
72
+ metadata: {
73
+ os: systemInfo.os,
74
+ cpu: systemInfo.cpu,
75
+ disk: systemInfo.disk,
76
+ memory: systemInfo.memory,
77
+ containerInfo: systemInfo.containerInfo
78
+ }
79
+ });
80
+ }
81
+
82
+ // env_no_percy_vars/301: Percy env var listing
83
+ if (allSetVarNames.length === 0) {
84
+ findings.push({
85
+ category: 'env_no_percy_vars',
86
+ status: 'info',
87
+ message: 'No Percy-specific environment variables detected (only PERCY_TOKEN is required).'
88
+ });
89
+ } else {
90
+ findings.push({
91
+ category: 'env_vars_listed',
92
+ status: 'info',
93
+ message: `Percy environment variables set: ${allSetVarNames.join(', ')}`
94
+ });
95
+ }
96
+
97
+ // env_parallel_total_invalid: Validate PERCY_PARALLEL_TOTAL format
98
+ if (process.env.PERCY_PARALLEL_TOTAL) {
99
+ const val = Number(process.env.PERCY_PARALLEL_TOTAL);
100
+ if (!Number.isInteger(val) || val <= 0) {
101
+ findings.push({
102
+ category: 'env_parallel_total_invalid',
103
+ status: 'fail',
104
+ message: 'PERCY_PARALLEL_TOTAL is not a valid positive integer.',
105
+ suggestions: ['Set PERCY_PARALLEL_TOTAL to a positive integer (e.g., 4).', 'This controls how many parallel Percy build shards to expect.']
106
+ });
107
+ }
108
+ }
109
+
110
+ // env_manual_overrides: Warn about manual overrides
111
+ const overrideVars = ['PERCY_COMMIT', 'PERCY_BRANCH', 'PERCY_PULL_REQUEST', 'PERCY_TARGET_COMMIT', 'PERCY_TARGET_BRANCH'];
112
+ const activeOverrides = overrideVars.filter(k => process.env[k]);
113
+ if (activeOverrides.length > 0) {
114
+ findings.push({
115
+ category: 'env_manual_overrides',
116
+ status: 'info',
117
+ message: `Manual overrides active: ${activeOverrides.join(', ')} — these override CI-detected values.`
118
+ });
119
+ }
120
+
121
+ // env_tls_disabled: Detect NODE_TLS_REJECT_UNAUTHORIZED=0
122
+ if (process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0') {
123
+ findings.push({
124
+ category: 'env_tls_disabled',
125
+ status: 'warn',
126
+ message: 'NODE_TLS_REJECT_UNAUTHORIZED=0 — SSL certificate validation is globally disabled.',
127
+ suggestions: ['This disables ALL SSL certificate validation for this process.', 'Use NODE_EXTRA_CA_CERTS=/path/to/ca.crt for a safer permanent fix.', 'Only use NODE_TLS_REJECT_UNAUTHORIZED=0 for temporary debugging.']
128
+ });
129
+ }
130
+
131
+ // ── PART B: CI environment check ─────────────────────────────────────────
132
+ // Uses injected percyEnv for testability, or creates a fresh PercyEnv that
133
+ // reads from process.env. Injection prevents GITHUB_EVENT_PATH caching
134
+ // issues when running tests inside actual CI environments.
135
+
136
+ const env = percyEnvArg ?? new PercyEnv();
137
+
138
+ // ci_not_detected: Not in CI
139
+ if (!env.ci) {
140
+ findings.push({
141
+ category: 'ci_not_detected',
142
+ status: 'info',
143
+ message: 'Not running in a CI environment (local machine).',
144
+ suggestions: ['Percy doctor is most useful when run in your CI pipeline.']
145
+ });
146
+ return findings;
147
+ }
148
+
149
+ // ci_detected: CI system detected
150
+ findings.push({
151
+ category: 'ci_detected',
152
+ status: 'pass',
153
+ message: `CI system detected: ${env.ci}`
154
+ });
155
+
156
+ // ci_commit_missing/203: Commit SHA
157
+ const commit = env.commit;
158
+ if (!commit) {
159
+ findings.push({
160
+ category: 'ci_commit_missing',
161
+ status: 'warn',
162
+ message: 'Could not detect commit SHA from CI environment.',
163
+ suggestions: ['Percy needs a commit SHA for baseline comparison.', 'Set PERCY_COMMIT=<sha> as a fallback.']
164
+ });
165
+ } else {
166
+ findings.push({
167
+ category: 'ci_commit_found',
168
+ status: 'pass',
169
+ message: `Commit SHA: ${commit.slice(0, 12)}...`
170
+ });
171
+ }
172
+
173
+ // ci_branch_missing: Branch
174
+ const branch = env.branch;
175
+ if (!branch) {
176
+ findings.push({
177
+ category: 'ci_branch_missing',
178
+ status: 'warn',
179
+ message: 'Could not detect branch name from CI environment.',
180
+ suggestions: ['Set PERCY_BRANCH=<branch-name> as a fallback.']
181
+ });
182
+ }
183
+
184
+ // ci_parallel_nonce_missing/206: Parallel config
185
+ if (process.env.PERCY_PARALLEL_TOTAL) {
186
+ if (!process.env.PERCY_PARALLEL_NONCE) {
187
+ findings.push({
188
+ category: 'ci_parallel_nonce_missing',
189
+ status: 'warn',
190
+ message: 'PERCY_PARALLEL_TOTAL is set but PERCY_PARALLEL_NONCE is missing.',
191
+ suggestions: ['Both PERCY_PARALLEL_TOTAL and PERCY_PARALLEL_NONCE must be set for parallel builds.', 'The nonce should be unique per build run (e.g., CI build number).']
192
+ });
193
+ } else {
194
+ findings.push({
195
+ category: 'ci_parallel_config_valid',
196
+ status: 'pass',
197
+ message: 'Parallel build configuration detected (PERCY_PARALLEL_TOTAL and PERCY_PARALLEL_NONCE are set).'
198
+ });
199
+ }
200
+ }
201
+
202
+ // ci_git_available/208/209: Git availability
203
+ try {
204
+ cp.execSync('git rev-parse --is-inside-work-tree', {
205
+ timeout: 5000,
206
+ stdio: 'pipe'
207
+ });
208
+ findings.push({
209
+ category: 'ci_git_available',
210
+ status: 'pass',
211
+ message: 'Git repository detected.'
212
+ });
213
+ } catch {
214
+ if (process.env.PERCY_SKIP_GIT_CHECK === 'true') {
215
+ findings.push({
216
+ category: 'ci_git_check_skipped',
217
+ status: 'info',
218
+ message: 'PERCY_SKIP_GIT_CHECK=true — git validation skipped.'
219
+ });
220
+ } else {
221
+ findings.push({
222
+ category: 'ci_git_unavailable',
223
+ status: 'warn',
224
+ message: 'Git is not available or not in a git repository.',
225
+ suggestions: ['Percy uses git to detect commit and branch information.', 'Install git or set PERCY_COMMIT and PERCY_BRANCH manually.', 'Or set PERCY_SKIP_GIT_CHECK=true to suppress this warning.']
226
+ });
227
+ }
228
+ }
229
+ return findings;
230
+ }
package/dist/doctor.js CHANGED
@@ -2,13 +2,13 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import os from 'os';
4
4
  import command from '@percy/cli-command';
5
- import { captureProxyEnv, redactProxyUrl, runConnectivityAndSSL, runProxyCheck, runPACCheck, runBrowserCheck } from './utils/helpers.js';
6
- import { checkLine, print } from './utils/reporter.js';
5
+ import { captureProxyEnv, redactProxyUrl, runConnectivityAndSSL, runProxyCheck, runPACCheck, runBrowserCheck, runAuthCheck, runConfigCheck, runEnvAuditCheck } from './utils/helpers.js';
6
+ import { checkLine, summaryBanner, print } from './utils/reporter.js';
7
7
  import { getPackageJSON } from '@percy/cli-command/utils';
8
8
  const pkg = getPackageJSON(import.meta.url);
9
9
  export const doctor = command('doctor', {
10
10
  description: 'Diagnose network connectivity and configuration for Percy builds',
11
- examples: ['$0', '$0 --proxy-server http://proxy.corp.example.com:8080', '$0 --url https://my-staging.example.com', '$0 --output-json ./percy-doctor.json'],
11
+ examples: ['$0', '$0 --quick', '$0 --proxy-server http://proxy.corp.example.com:8080', '$0 --url https://my-staging.example.com', '$0 --output-json ./percy-doctor.json'],
12
12
  flags: [{
13
13
  name: 'proxy-server',
14
14
  description: 'Proxy server URL to test alongside direct connectivity (e.g. http://proxy:8080)',
@@ -28,6 +28,11 @@ export const doctor = command('doctor', {
28
28
  description: 'Write the full diagnostic report to a JSON file',
29
29
  type: 'string',
30
30
  attribute: 'outputJson'
31
+ }, {
32
+ name: 'quick',
33
+ description: 'Run only connectivity, SSL, and token checks (~4s)',
34
+ type: 'boolean',
35
+ default: false
31
36
  }]
32
37
  }, async ({
33
38
  flags,
@@ -35,16 +40,32 @@ export const doctor = command('doctor', {
35
40
  exit
36
41
  }) => {
37
42
  var _flags$url;
43
+ const startTime = Date.now();
38
44
  const proxyUrl = flags.proxyServer || process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null;
39
- const timeout = parseInt(flags.timeout ?? '10000', 10);
40
- if (isNaN(timeout) || timeout <= 0) {
41
- log.error('--timeout must be a positive integer (milliseconds)');
45
+ const MAX_TIMEOUT = 300000; // 5 minutes
46
+ const rawTimeout = Number(flags.timeout ?? '10000');
47
+ const timeout = Number.isInteger(rawTimeout) ? rawTimeout : NaN;
48
+ if (isNaN(timeout) || timeout <= 0 || timeout > MAX_TIMEOUT) {
49
+ log.error(`--timeout must be a positive integer up to ${MAX_TIMEOUT}ms (5 minutes)`);
42
50
  return exit(1, '--timeout must be a positive integer', false);
43
51
  }
44
52
  const targetUrl = ((_flags$url = flags.url) === null || _flags$url === void 0 ? void 0 : _flags$url.trim()) || 'https://percy.io';
45
53
  const jsonOutputPath = flags.outputJson ?? null;
54
+ const mode = flags.quick ? 'quick' : 'default';
55
+
56
+ // Inter-check context — plain data object
57
+ const ctx = {
58
+ proxyUrl,
59
+ timeout,
60
+ targetUrl,
61
+ discoveredProxies: [],
62
+ connectivityOk: null,
63
+ pacResolvedProxy: null
64
+ };
46
65
  const report = {
66
+ version: '1.0.0',
47
67
  timestamp: new Date().toISOString(),
68
+ mode,
48
69
  environment: {
49
70
  percyCLIVersion: pkg.version,
50
71
  platform: process.platform,
@@ -55,32 +76,107 @@ export const doctor = command('doctor', {
55
76
  },
56
77
  checks: {}
57
78
  };
58
- print(log, '\n Percy Doctor — network readiness check\n');
79
+ print(log, `\n Percy Doctor — diagnostic check${mode === 'quick' ? ' (quick mode)' : ''}\n`);
59
80
  if (proxyUrl) {
60
81
  print(log, checkLine('info', `Proxy in use: ${redactProxyUrl(proxyUrl)}`));
61
82
  print(log, '');
62
83
  }
84
+
85
+ // NOTE: Phase 1-4 orchestration is mirrored in runDiagnostics() (helpers.js).
86
+ // If you change phase ordering or add checks here, update runDiagnostics() too.
87
+ // Phase 1: Independent checks (parallel with allSettled) — skip in quick mode
88
+ // CI is merged into runEnvAuditCheck (see env-audit.js + helpers.js).
89
+ if (mode !== 'quick') {
90
+ var _phase1Results$0$reas, _phase1Results$1$reas;
91
+ const phase1Results = await Promise.allSettled([runConfigCheck(), runEnvAuditCheck()]);
92
+ report.checks.config = phase1Results[0].status === 'fulfilled' ? phase1Results[0].value.config : {
93
+ status: 'fail',
94
+ findings: [{
95
+ status: 'fail',
96
+ message: (_phase1Results$0$reas = phase1Results[0].reason) === null || _phase1Results$0$reas === void 0 ? void 0 : _phase1Results$0$reas.message
97
+ }]
98
+ };
99
+ report.checks.envAudit = phase1Results[1].status === 'fulfilled' ? phase1Results[1].value.envAudit : {
100
+ status: 'fail',
101
+ findings: [{
102
+ status: 'fail',
103
+ message: (_phase1Results$1$reas = phase1Results[1].reason) === null || _phase1Results$1$reas === void 0 ? void 0 : _phase1Results$1$reas.message
104
+ }]
105
+ };
106
+ }
107
+
108
+ // Phase 2: Network checks (sequential — order matters for output readability)
63
109
  const {
64
110
  connectivity,
65
111
  ssl
66
112
  } = await runConnectivityAndSSL(proxyUrl, timeout);
67
113
  report.checks.connectivity = connectivity;
68
114
  report.checks.ssl = ssl;
69
- const {
70
- proxy
71
- } = await runProxyCheck(timeout);
72
- report.checks.proxy = proxy;
73
- const {
74
- pac
75
- } = await runPACCheck();
76
- report.checks.pac = pac;
77
- const {
78
- browser
79
- } = await runBrowserCheck(targetUrl, proxyUrl, timeout);
80
- report.checks.browser = browser;
115
+ ctx.connectivityOk = connectivity.status !== 'fail';
116
+ if (mode !== 'quick') {
117
+ var _find;
118
+ const {
119
+ proxy
120
+ } = await runProxyCheck(timeout);
121
+ report.checks.proxy = proxy;
122
+ ctx.discoveredProxies = (proxy.findings ?? []).filter(f => {
123
+ var _f$proxyValidation;
124
+ return f.proxyUrl && ((_f$proxyValidation = f.proxyValidation) === null || _f$proxyValidation === void 0 ? void 0 : _f$proxyValidation.status) === 'pass';
125
+ }).map(f => ({
126
+ url: f.proxyUrl,
127
+ source: f.source
128
+ }));
129
+ const {
130
+ pac
131
+ } = await runPACCheck();
132
+ report.checks.pac = pac;
133
+ ctx.pacResolvedProxy = ((_find = (pac.findings ?? []).find(f => f.detectedProxyUrl)) === null || _find === void 0 ? void 0 : _find.detectedProxyUrl) ?? null;
134
+ }
135
+
136
+ // Phase 3: Token auth (depends on connectivity + proxy discovery)
137
+ if (mode === 'quick' && !ctx.connectivityOk) {
138
+ report.checks.auth = {
139
+ status: 'skip',
140
+ findings: [{
141
+ category: 'check_skipped',
142
+ status: 'skip',
143
+ message: 'Token validation skipped — percy.io is unreachable.',
144
+ suggestions: ['Fix connectivity issues first, then re-run percy doctor.']
145
+ }]
146
+ };
147
+ } else {
148
+ const {
149
+ auth
150
+ } = await runAuthCheck(ctx);
151
+ report.checks.auth = auth;
152
+ }
153
+
154
+ // Phase 4: Browser network analysis — skip in quick mode
155
+ if (mode !== 'quick') {
156
+ var _ctx$discoveredProxie;
157
+ const bestProxy = ctx.proxyUrl || ((_ctx$discoveredProxie = ctx.discoveredProxies[0]) === null || _ctx$discoveredProxie === void 0 ? void 0 : _ctx$discoveredProxie.url) || ctx.pacResolvedProxy || null;
158
+ const {
159
+ browser
160
+ } = await runBrowserCheck(targetUrl, bestProxy, timeout);
161
+ report.checks.browser = browser;
162
+ }
163
+ const counts = {
164
+ passed: 0,
165
+ warned: 0,
166
+ failed: 0
167
+ };
168
+ for (const c of Object.values(report.checks)) {
169
+ if ((c === null || c === void 0 ? void 0 : c.status) === 'pass') counts.passed++;else if ((c === null || c === void 0 ? void 0 : c.status) === 'warn') counts.warned++;else if ((c === null || c === void 0 ? void 0 : c.status) === 'fail') counts.failed++;
170
+ }
81
171
  report.summary = {
82
- overall: Object.values(report.checks).some(c => (c === null || c === void 0 ? void 0 : c.status) === 'fail') ? 'fail' : Object.values(report.checks).some(c => (c === null || c === void 0 ? void 0 : c.status) === 'warn') ? 'warn' : 'pass'
172
+ overall: counts.failed > 0 ? 'fail' : counts.warned > 0 ? 'warn' : 'pass',
173
+ passed: counts.passed,
174
+ warned: counts.warned,
175
+ failed: counts.failed,
176
+ durationMs: Date.now() - startTime
83
177
  };
178
+ print(log, summaryBanner(counts.passed, counts.warned, counts.failed));
179
+ print(log, ` Completed in ${((Date.now() - startTime) / 1000).toFixed(1)}s\n`);
84
180
  if (jsonOutputPath) {
85
181
  try {
86
182
  // cli-doctor runs inside the customer's own CI environment; jsonOutputPath is a
@@ -62,6 +62,42 @@ export function captureProxyEnv() {
62
62
  return out;
63
63
  }
64
64
 
65
+ // ─── Section runner factory ──────────────────────────────────────────────────
66
+ // Generic runner that reduces boilerplate for each check section.
67
+
68
+ /**
69
+ * Generic section runner factory. Reduces boilerplate for each check.
70
+ * @param {string} sectionName - Display name for the section header
71
+ * @param {string} checkKey - Key in the report.checks object
72
+ * @param {Function} checkFn - Async function returning findings array
73
+ * @returns {Promise<object>} - { [checkKey]: { status, findings, durationMs } }
74
+ */
75
+ export async function runSection(sectionName, checkKey, checkFn) {
76
+ const log = logger('percy:doctor');
77
+ print(log, sectionHeader(sectionName));
78
+ let findings = [];
79
+ const start = Date.now();
80
+ try {
81
+ findings = await checkFn();
82
+ } catch (err) {
83
+ /* istanbul ignore next */
84
+ log.error(`${sectionName} check failed unexpectedly: ${err.message}`);
85
+ /* istanbul ignore next */
86
+ findings = [{
87
+ status: 'fail',
88
+ message: err.message
89
+ }];
90
+ }
91
+ renderFindings(findings, log);
92
+ return {
93
+ [checkKey]: {
94
+ status: sectionStatus(findings),
95
+ findings,
96
+ durationMs: Date.now() - start
97
+ }
98
+ };
99
+ }
100
+
65
101
  // ─── Section runners ──────────────────────────────────────────────────────────
66
102
  // Each function receives only the data it needs (proxyUrl, timeout, targetUrl).
67
103
  // It creates its own logger and checker internally, then returns its results.
@@ -267,33 +303,108 @@ export async function runBrowserCheck(targetUrl = 'https://percy.io', proxyUrl =
267
303
  export async function runDiagnostics({
268
304
  proxyUrl,
269
305
  timeout = 10000,
270
- targetUrl = 'https://percy.io'
306
+ targetUrl = 'https://percy.io',
307
+ mode = 'default'
271
308
  } = {}) {
309
+ const MAX_TIMEOUT = 300000; // 5 minutes
272
310
  const parsedTimeout = Number(timeout);
273
- if (!Number.isInteger(parsedTimeout) || parsedTimeout <= 0) {
274
- throw new Error('--timeout must be a positive integer (milliseconds)');
311
+ if (!Number.isInteger(parsedTimeout) || parsedTimeout <= 0 || parsedTimeout > MAX_TIMEOUT) {
312
+ throw new Error(`--timeout must be a positive integer up to ${MAX_TIMEOUT}ms (5 minutes)`);
275
313
  }
276
314
  const report = {
277
315
  checks: {}
278
316
  };
317
+
318
+ // NOTE: Phase 1-4 orchestration is mirrored in doctor.js CLI handler.
319
+ // If you change phase ordering or add checks here, update doctor.js too.
320
+ // Phase 1: Independent checks — skip in quick mode
321
+ // CI is merged into runEnvAuditCheck (see env-audit.js + helpers.js).
322
+ /* istanbul ignore next */
323
+ if (mode !== 'quick') {
324
+ var _phase1Results$0$reas, _phase1Results$1$reas;
325
+ const phase1Results = await Promise.allSettled([runConfigCheck(), runEnvAuditCheck()]);
326
+ /* istanbul ignore next */
327
+ report.checks.config = phase1Results[0].status === 'fulfilled' ? phase1Results[0].value.config : {
328
+ status: 'fail',
329
+ findings: [{
330
+ status: 'fail',
331
+ message: (_phase1Results$0$reas = phase1Results[0].reason) === null || _phase1Results$0$reas === void 0 ? void 0 : _phase1Results$0$reas.message
332
+ }]
333
+ };
334
+ /* istanbul ignore next */
335
+ report.checks.envAudit = phase1Results[1].status === 'fulfilled' ? phase1Results[1].value.envAudit : {
336
+ status: 'fail',
337
+ findings: [{
338
+ status: 'fail',
339
+ message: (_phase1Results$1$reas = phase1Results[1].reason) === null || _phase1Results$1$reas === void 0 ? void 0 : _phase1Results$1$reas.message
340
+ }]
341
+ };
342
+ }
343
+
344
+ // Phase 2: Network checks
279
345
  const {
280
346
  connectivity,
281
347
  ssl
282
348
  } = await runConnectivityAndSSL(proxyUrl, parsedTimeout);
283
349
  report.checks.connectivity = connectivity;
284
350
  report.checks.ssl = ssl;
285
- const {
286
- proxy
287
- } = await runProxyCheck(parsedTimeout);
288
- report.checks.proxy = proxy;
289
- const {
290
- pac
291
- } = await runPACCheck();
292
- report.checks.pac = pac;
293
- const {
294
- browser
295
- } = await runBrowserCheck(targetUrl, proxyUrl, parsedTimeout);
296
- report.checks.browser = browser;
351
+ const connectivityOk = connectivity.status !== 'fail';
352
+ let bestProxy = proxyUrl;
353
+
354
+ /* istanbul ignore next */
355
+ if (mode !== 'quick') {
356
+ var _find, _discoveredProxies$;
357
+ const {
358
+ proxy
359
+ } = await runProxyCheck(parsedTimeout);
360
+ report.checks.proxy = proxy;
361
+ /* istanbul ignore next */
362
+ const discoveredProxies = (proxy.findings ?? []).filter(f => {
363
+ var _f$proxyValidation;
364
+ return f.proxyUrl && ((_f$proxyValidation = f.proxyValidation) === null || _f$proxyValidation === void 0 ? void 0 : _f$proxyValidation.status) === 'pass';
365
+ }).map(f => ({
366
+ url: f.proxyUrl,
367
+ source: f.source
368
+ }));
369
+ const {
370
+ pac
371
+ } = await runPACCheck();
372
+ report.checks.pac = pac;
373
+ /* istanbul ignore next */
374
+ const pacResolvedProxy = ((_find = (pac.findings ?? []).find(f => f.detectedProxyUrl)) === null || _find === void 0 ? void 0 : _find.detectedProxyUrl) ?? null;
375
+ bestProxy = proxyUrl || ((_discoveredProxies$ = discoveredProxies[0]) === null || _discoveredProxies$ === void 0 ? void 0 : _discoveredProxies$.url) || pacResolvedProxy || null;
376
+ }
377
+
378
+ // Phase 3: Token auth
379
+ /* istanbul ignore next */
380
+ if (mode === 'quick' && !connectivityOk) {
381
+ report.checks.auth = {
382
+ status: 'skip',
383
+ findings: [{
384
+ category: 'check_skipped',
385
+ status: 'skip',
386
+ message: 'Token validation skipped — percy.io is unreachable.',
387
+ suggestions: ['Fix connectivity issues first, then re-run percy doctor.']
388
+ }]
389
+ };
390
+ } else {
391
+ const {
392
+ auth
393
+ } = await runAuthCheck({
394
+ bestProxy,
395
+ timeout: parsedTimeout
396
+ });
397
+ report.checks.auth = auth;
398
+ }
399
+
400
+ // Phase 4: Browser — skip in quick mode
401
+ /* istanbul ignore next */
402
+ if (mode !== 'quick') {
403
+ const {
404
+ browser
405
+ } = await runBrowserCheck(targetUrl, bestProxy, parsedTimeout);
406
+ report.checks.browser = browser;
407
+ }
297
408
  const hasFail = Object.values(report.checks).some(c => (c === null || c === void 0 ? void 0 : c.status) === 'fail');
298
409
  const hasWarn = Object.values(report.checks).some(c => (c === null || c === void 0 ? void 0 : c.status) === 'warn');
299
410
  return {
@@ -379,4 +490,44 @@ export function _renderBrowserResults(log, browserResult, proxyUrl) {
379
490
  print(log, checkLine('fail', `Percy domain(s) unreachable from Chrome: ${criticalBlocked.map(d => d.hostname).join(', ')}`));
380
491
  print(log, suggestionList([proxyUrl ? 'Ensure the proxy allows outbound HTTPS to percy.io and browserstack.com.' : 'Set HTTPS_PROXY if you are behind a corporate proxy.', 'Contact your network team to whitelist: percy.io, www.browserstack.com, hub.browserstack.com.']));
381
492
  }
493
+ }
494
+
495
+ // ─── New check runners (Phase 3-6) ──────────────────────────────────────────
496
+
497
+ /**
498
+ * Run the token auth check.
499
+ * @param {object} ctx - Doctor context with bestProxy, timeout
500
+ * @returns {Promise<{ auth: object }>}
501
+ */
502
+ /* istanbul ignore next */
503
+ export async function runAuthCheck(ctx = {}) {
504
+ const authModule = await import('../checks/auth.js');
505
+ return runSection('Token Authentication', 'auth', () => authModule.checkAuth({
506
+ proxyUrl: ctx.bestProxy,
507
+ timeout: ctx.timeout
508
+ }));
509
+ }
510
+
511
+ /**
512
+ * Run the config validation check.
513
+ * @returns {Promise<{ config: object }>}
514
+ */
515
+ export async function runConfigCheck() {
516
+ const {
517
+ checkConfig
518
+ } = await import('../checks/config.js');
519
+ return runSection('Percy Configuration', 'config', () => checkConfig());
520
+ }
521
+
522
+ /**
523
+ * Run the combined environment-variable audit + CI environment check.
524
+ * CI detection is merged into checkEnvAndCI (env-audit.js); calling
525
+ * this single runner covers both sections.
526
+ * @returns {Promise<{ envAudit: object }>}
527
+ */
528
+ export async function runEnvAuditCheck() {
529
+ const {
530
+ checkEnvAndCI
531
+ } = await import('../checks/env-audit.js');
532
+ return runSection('Environment & CI', 'envAudit', () => checkEnvAndCI());
382
533
  }
@@ -21,6 +21,7 @@ const DEFAULT_TIMEOUT = 10000;
21
21
  * @property {string} error - Error message if request failed
22
22
  * @property {string} errorCode - Node.js error code (e.g. CERT_HAS_EXPIRED)
23
23
  * @property {number} latencyMs - Round-trip time in milliseconds
24
+ * @property {string} body - Response body as UTF-8 string
24
25
  */
25
26
  var _HttpProber_brand = /*#__PURE__*/new WeakSet();
26
27
  export class HttpProber {
@@ -50,7 +51,8 @@ export class HttpProber {
50
51
  const {
51
52
  proxyUrl,
52
53
  timeout = DEFAULT_TIMEOUT,
53
- method = 'HEAD'
54
+ method = 'HEAD',
55
+ headers = {}
54
56
  } = options;
55
57
  const start = Date.now();
56
58
  try {
@@ -58,7 +60,8 @@ export class HttpProber {
58
60
  const proxy = proxyUrl ? new URL(proxyUrl) : null;
59
61
  const result = await _assertClassBrand(_HttpProber_brand, this, _makeRequest).call(this, url, proxy, {
60
62
  timeout,
61
- method
63
+ method,
64
+ headers
62
65
  });
63
66
  result.latencyMs = Date.now() - start;
64
67
  return result;
@@ -87,18 +90,24 @@ export class HttpProber {
87
90
  }
88
91
  function _makeRequest(url, proxy, {
89
92
  timeout,
90
- method
93
+ method,
94
+ headers
91
95
  }) {
92
96
  // ── common response resolver ──────────────────────────────────────────────
93
97
  function resolveResponse(res, resolve) {
94
- res.resume(); // drain body
95
98
  const status = res.statusCode;
96
- resolve({
97
- ok: status >= 200 && status < 400,
98
- status,
99
- error: null,
100
- errorCode: null,
101
- responseHeaders: res.headers
99
+ const chunks = [];
100
+ res.on('data', chunk => chunks.push(chunk));
101
+ res.on('end', () => {
102
+ const body = Buffer.concat(chunks).toString('utf8');
103
+ resolve({
104
+ ok: status >= 200 && status < 400,
105
+ status,
106
+ error: null,
107
+ errorCode: null,
108
+ responseHeaders: res.headers,
109
+ body
110
+ });
102
111
  });
103
112
  }
104
113
 
@@ -136,6 +145,8 @@ function _makeRequest(url, proxy, {
136
145
  } catch {/* ignore */}
137
146
  reject(err);
138
147
  };
148
+
149
+ /* istanbul ignore next */
139
150
  const pass = result => {
140
151
  /* istanbul ignore next */
141
152
  if (settled) return;
@@ -167,20 +178,32 @@ function _makeRequest(url, proxy, {
167
178
  servername: url.hostname
168
179
  });
169
180
  tlsSock.on('error', fail);
181
+ /* istanbul ignore next */
170
182
  tlsSock.on('secureConnect', () => {
171
183
  const req = https.request({
172
184
  createConnection: () => tlsSock,
173
185
  hostname: url.hostname,
174
186
  port: targetPort,
175
187
  path: url.pathname + url.search,
176
- method
177
- }, res => pass({
178
- ok: res.statusCode >= 200 && res.statusCode < 400,
179
- status: res.statusCode,
180
- error: null,
181
- errorCode: null,
182
- responseHeaders: res.headers
183
- }));
188
+ method,
189
+ headers
190
+ }, /* istanbul ignore next */
191
+ res => {
192
+ const status = res.statusCode;
193
+ const chunks = [];
194
+ res.on('data', chunk => chunks.push(chunk));
195
+ res.on('end', () => {
196
+ const body = Buffer.concat(chunks).toString('utf8');
197
+ pass({
198
+ ok: status >= 200 && status < 400,
199
+ status,
200
+ error: null,
201
+ errorCode: null,
202
+ responseHeaders: res.headers,
203
+ body
204
+ });
205
+ });
206
+ });
184
207
  req.on('error', fail);
185
208
  req.end();
186
209
  });
@@ -204,6 +227,7 @@ function _makeRequest(url, proxy, {
204
227
  timeout,
205
228
  headers: {
206
229
  Host: url.hostname,
230
+ ...headers,
207
231
  ...(proxy.username ? {
208
232
  'Proxy-Authorization': `Basic ${Buffer.from(`${proxy.username}:${proxy.password}`).toString('base64')}`
209
233
  } : {})
@@ -237,7 +261,8 @@ function _makeRequest(url, proxy, {
237
261
  port,
238
262
  path: url.pathname + url.search,
239
263
  method,
240
- timeout
264
+ timeout,
265
+ headers
241
266
  }, res => resolveResponse(res, resolve));
242
267
  req.on('timeout', () => {
243
268
  req.destroy();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@percy/cli-doctor",
3
- "version": "1.31.10-beta.2",
3
+ "version": "1.31.10",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -9,7 +9,7 @@
9
9
  },
10
10
  "publishConfig": {
11
11
  "access": "public",
12
- "tag": "beta"
12
+ "tag": "latest"
13
13
  },
14
14
  "engines": {
15
15
  "node": ">=14"
@@ -20,14 +20,7 @@
20
20
  "main": "./dist/index.js",
21
21
  "type": "module",
22
22
  "exports": {
23
- ".": "./dist/index.js",
24
- "./src/utils/http.js": "./src/utils/http.js",
25
- "./src/utils/reporter.js": "./src/utils/reporter.js",
26
- "./src/utils/helpers.js": "./src/utils/helpers.js",
27
- "./src/checks/connectivity.js": "./src/checks/connectivity.js",
28
- "./src/checks/proxy.js": "./src/checks/proxy.js",
29
- "./src/checks/pac.js": "./src/checks/pac.js",
30
- "./src/checks/browser.js": "./src/checks/browser.js"
23
+ ".": "./dist/index.js"
31
24
  },
32
25
  "scripts": {
33
26
  "build": "node ../../scripts/build",
@@ -42,11 +35,15 @@
42
35
  ]
43
36
  },
44
37
  "dependencies": {
45
- "@percy/cli-command": "1.31.10-beta.2",
46
- "@percy/core": "1.31.10-beta.2",
47
- "@percy/logger": "1.31.10-beta.2",
38
+ "@percy/cli-command": "1.31.10",
39
+ "@percy/client": "1.31.10",
40
+ "@percy/config": "1.31.10",
41
+ "@percy/core": "1.31.10",
42
+ "@percy/env": "1.31.10",
43
+ "@percy/logger": "1.31.10",
44
+ "@percy/monitoring": "1.31.10",
48
45
  "minimatch": "^9.0.0",
49
46
  "ws": "^8.17.1"
50
47
  },
51
- "gitHead": "8bf5f2027eaf29f3fac43c4b786d85b00eab65b2"
48
+ "gitHead": "f7d26d7bfc3021edbbf34ea713421f4d47eae054"
52
49
  }