@percy/cli-doctor 1.31.10-beta.1

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.
@@ -0,0 +1,382 @@
1
+ import { ConnectivityChecker } from '../checks/connectivity.js';
2
+ import { ProxyDetector } from '../checks/proxy.js';
3
+ import { PACDetector } from '../checks/pac.js';
4
+ import { BrowserChecker } from '../checks/browser.js';
5
+ import logger from '@percy/logger';
6
+ import { sectionHeader, checkLine, suggestionList, renderFindings, sectionStatus, print } from './reporter.js';
7
+
8
+ // Percy/BrowserStack hostnames that count toward the browser-check pass/fail.
9
+ // 3rd-party domains (ads, analytics, social) being blocked is normal and
10
+ // has no impact on Percy builds.
11
+ export const PERCY_DOMAINS = new Set(['percy.io', 'www.browserstack.com', 'hub.browserstack.com']);
12
+
13
+ // ─── Utility helpers ──────────────────────────────────────────────────────────
14
+
15
+ /**
16
+ * Redact credentials (username:password) from a proxy URL so it can be safely
17
+ * logged or written to reports without exposing secrets.
18
+ * e.g. "http://user:pass@proxy.corp.com:8080" → "http://***:***@proxy.corp.com:8080"
19
+ */
20
+ export function redactProxyUrl(rawUrl) {
21
+ if (!rawUrl) return rawUrl;
22
+ try {
23
+ const u = new URL(rawUrl);
24
+ if (u.username || u.password) {
25
+ u.username = '***';
26
+ u.password = '***';
27
+ }
28
+ return u.toString();
29
+ } catch {
30
+ return rawUrl;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Collect all proxy-related and Percy browser environment variables that are
36
+ * currently set, returning them as a plain object for the JSON report.
37
+ * Proxy URLs are redacted to avoid leaking credentials.
38
+ */
39
+ export function captureProxyEnv() {
40
+ const proxyKeys = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy'];
41
+ const otherKeys = ['NO_PROXY', 'no_proxy', 'NODE_TLS_REJECT_UNAUTHORIZED', 'NODE_EXTRA_CA_CERTS', 'PERCY_BROWSER_EXECUTABLE'];
42
+ const out = {};
43
+ // On Windows env var names are case-insensitive, so HTTPS_PROXY and
44
+ // https_proxy resolve to the same underlying slot. Track already-emitted
45
+ // lowercase keys to avoid producing duplicate entries (e.g. both HTTPS_PROXY
46
+ // and https_proxy) when only one distinct variable exists.
47
+ const seenLower = new Set();
48
+ for (const k of proxyKeys) {
49
+ const lower = k.toLowerCase();
50
+ if (process.env[k] !== undefined && !seenLower.has(lower)) {
51
+ seenLower.add(lower);
52
+ out[k] = redactProxyUrl(process.env[k]);
53
+ }
54
+ }
55
+ for (const k of otherKeys) {
56
+ const lower = k.toLowerCase();
57
+ if (process.env[k] !== undefined && !seenLower.has(lower)) {
58
+ seenLower.add(lower);
59
+ out[k] = process.env[k];
60
+ }
61
+ }
62
+ return out;
63
+ }
64
+
65
+ // ─── Section runners ──────────────────────────────────────────────────────────
66
+ // Each function receives only the data it needs (proxyUrl, timeout, targetUrl).
67
+ // It creates its own logger and checker internally, then returns its results.
68
+ // doctor.js (and runDiagnostics) assembles report.checks from the return values.
69
+
70
+ /**
71
+ * Sections 1 + 2: Network Connectivity and SSL/TLS.
72
+ *
73
+ * Both checks probe percy.io; checkConnectivityAndSSL runs them sharing the
74
+ * same request — no duplicate HTTP roundtrip in the common case.
75
+ *
76
+ * @param {string} [proxyUrl] - Proxy URL to use for outbound requests
77
+ * @param {number} [timeout] - Per-request timeout ms (default: 10000)
78
+ * @returns {{ connectivity: object, ssl: object }}
79
+ */
80
+ export async function runConnectivityAndSSL(proxyUrl, timeout = 10000) {
81
+ const log = logger('percy:doctor');
82
+ const connectivityChecker = new ConnectivityChecker();
83
+ print(log, sectionHeader('Network Connectivity'));
84
+ let connectivityFindings = [];
85
+ let sslFindings = [];
86
+ try {
87
+ ({
88
+ connectivityFindings,
89
+ sslFindings
90
+ } = await connectivityChecker.checkConnectivityAndSSL({
91
+ proxyUrl,
92
+ timeout
93
+ }));
94
+ } catch (err) {
95
+ log.error(`Connectivity/SSL check failed unexpectedly: ${err.message}`);
96
+ connectivityFindings = [{
97
+ status: 'fail',
98
+ message: err.message
99
+ }];
100
+ }
101
+ renderFindings(connectivityFindings, log);
102
+
103
+ // ── SSL / TLS ──────────────────────────────────────────────────────────────
104
+ print(log, sectionHeader('SSL / TLS'));
105
+ renderFindings(sslFindings, log);
106
+ return {
107
+ connectivity: {
108
+ status: sectionStatus(connectivityFindings),
109
+ findings: connectivityFindings
110
+ },
111
+ ssl: {
112
+ status: sectionStatus(sslFindings),
113
+ findings: sslFindings
114
+ }
115
+ };
116
+ }
117
+
118
+ /**
119
+ * Section 3: Proxy Configuration
120
+ * env vars → system settings → header fingerprinting → port scan →
121
+ * process inspection → WPAD
122
+ *
123
+ * @param {number} [timeout] - Per-request timeout ms (default: 10000)
124
+ * @returns {{ proxy: object }}
125
+ */
126
+ export async function runProxyCheck(timeout = 10000) {
127
+ const log = logger('percy:doctor');
128
+ const proxyDetector = new ProxyDetector();
129
+ print(log, sectionHeader('Proxy Configuration'));
130
+ print(log, checkLine('info', 'Scanning for proxy configuration and validating discovered proxies...'));
131
+ let proxyFindings = [];
132
+ try {
133
+ proxyFindings = await proxyDetector.detectProxy({
134
+ timeout,
135
+ testProxy: true
136
+ });
137
+ } catch (err) {
138
+ log.error(`Proxy detection failed unexpectedly: ${err.message}`);
139
+ proxyFindings = [{
140
+ status: 'fail',
141
+ message: err.message
142
+ }];
143
+ }
144
+ renderFindings(proxyFindings, log);
145
+ return {
146
+ proxy: {
147
+ status: sectionStatus(proxyFindings),
148
+ findings: proxyFindings
149
+ }
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Section 4: PAC / Auto-Proxy Configuration
155
+ * Detects PAC files from macOS, Linux, Windows, Chrome, Firefox.
156
+ *
157
+ * @returns {{ pac: object }}
158
+ */
159
+ export async function runPACCheck() {
160
+ const log = logger('percy:doctor');
161
+ const pacDetector = new PACDetector();
162
+ print(log, sectionHeader('PAC / Auto-Proxy Configuration'));
163
+ let pacFindings = [];
164
+ try {
165
+ pacFindings = await pacDetector.detectPAC();
166
+ } catch (err) {
167
+ log.error(`PAC detection failed unexpectedly: ${err.message}`);
168
+ pacFindings = [{
169
+ status: 'fail',
170
+ message: err.message
171
+ }];
172
+ }
173
+ renderFindings(pacFindings, log);
174
+ const actionablePac = pacFindings.find(f => f.detectedProxyUrl);
175
+ if (actionablePac) {
176
+ print(log, checkLine('warn', 'Action required: PAC file routes percy.io through a proxy.'));
177
+ print(log, suggestionList([`Add to your CI environment: HTTPS_PROXY=${actionablePac.detectedProxyUrl}`, `Or run: percy doctor --proxy-server ${actionablePac.detectedProxyUrl}`]));
178
+ }
179
+ return {
180
+ pac: {
181
+ status: sectionStatus(pacFindings),
182
+ findings: pacFindings
183
+ }
184
+ };
185
+ }
186
+
187
+ /**
188
+ * Section 5: Browser Network Analysis
189
+ * Launches Chrome, navigates to targetUrl, captures all network activity.
190
+ * If proxyUrl is supplied, runs the capture twice and compares.
191
+ *
192
+ * @param {string} [targetUrl] - URL to open in Chrome (default: https://percy.io)
193
+ * @param {string} [proxyUrl] - Proxy URL to test alongside direct connectivity
194
+ * @param {number} [timeout] - Base timeout ms; browser gets max(timeout, 30000)
195
+ * @returns {{ browser: object }}
196
+ */
197
+ export async function runBrowserCheck(targetUrl = 'https://percy.io', proxyUrl = null, timeout = 10000) {
198
+ const log = logger('percy:doctor');
199
+ const browserChecker = new BrowserChecker();
200
+ print(log, sectionHeader('Browser Network Analysis'));
201
+ if (proxyUrl) {
202
+ print(log, checkLine('info', `Opening ${targetUrl} in Chrome — running direct and proxy (${redactProxyUrl(proxyUrl)}) captures in parallel…`));
203
+ } else {
204
+ print(log, checkLine('info', `Opening ${targetUrl} in Chrome to capture network activity…`));
205
+ }
206
+ let browserResult = null;
207
+ try {
208
+ browserResult = await browserChecker.checkBrowserNetwork({
209
+ targetUrl,
210
+ proxyUrl,
211
+ timeout: Math.max(timeout, 30000),
212
+ // browsers need more time
213
+ headless: true
214
+ });
215
+ if (!browserResult.chromePath) {
216
+ // Chrome not found — non-fatal skip
217
+ print(log, checkLine('warn', 'Chrome not found — skipping browser network analysis.'));
218
+ print(log, suggestionList(['Install Google Chrome or set PERCY_BROWSER_EXECUTABLE to the path of a Chromium-based browser.', 'npm install @percy/cli will install a bundled Chromium.']));
219
+ } else {
220
+ for (const note of browserResult.notes ?? []) {
221
+ var _note$suggestions;
222
+ /* istanbul ignore next */
223
+ print(log, checkLine(note.status ?? 'info', note.message));
224
+ /* istanbul ignore next */
225
+ if ((_note$suggestions = note.suggestions) !== null && _note$suggestions !== void 0 && _note$suggestions.length) {
226
+ /* istanbul ignore next */
227
+ print(log, suggestionList(note.suggestions));
228
+ }
229
+ }
230
+ _renderBrowserResults(log, browserResult, proxyUrl);
231
+ }
232
+ } catch (err) {
233
+ log.error(`Browser analysis failed unexpectedly: ${err.message}`);
234
+ // Non-fatal — browser analysis is best-effort
235
+ }
236
+ return {
237
+ browser: browserResult ? {
238
+ status: browserResult.error ? 'warn' : sectionStatus((browserResult.domainSummary ?? []).filter(d => PERCY_DOMAINS.has(d.hostname)).map(d => ({
239
+ status: d.status
240
+ }))),
241
+ chromePath: browserResult.chromePath,
242
+ targetUrl: browserResult.targetUrl,
243
+ domainSummary: browserResult.domainSummary ?? [],
244
+ proxyHeaders: browserResult.proxyHeaders ?? [],
245
+ notes: browserResult.notes ?? [],
246
+ navMs: browserResult.navMs,
247
+ error: browserResult.error ?? null
248
+ } : {
249
+ status: 'skip',
250
+ error: 'Browser analysis not attempted'
251
+ }
252
+ };
253
+ }
254
+
255
+ /**
256
+ * Run all Percy doctor checks programmatically.
257
+ * Can be imported and called from other Percy packages to diagnose network
258
+ * connectivity issues on demand.
259
+ *
260
+ * @param {object} [options]
261
+ * @param {object} options.log - Percy logger instance
262
+ * @param {string} [options.proxyUrl] - Proxy URL to test
263
+ * @param {number} [options.timeout] - Per-request timeout ms (default: 10000)
264
+ * @param {string} [options.targetUrl] - URL to open in Chrome (default: https://percy.io)
265
+ * @returns {Promise<{ checks: object, hasFail: boolean, hasWarn: boolean }>}
266
+ */
267
+ export async function runDiagnostics({
268
+ proxyUrl,
269
+ timeout = 10000,
270
+ targetUrl = 'https://percy.io'
271
+ } = {}) {
272
+ const parsedTimeout = Number(timeout);
273
+ if (!Number.isInteger(parsedTimeout) || parsedTimeout <= 0) {
274
+ throw new Error('--timeout must be a positive integer (milliseconds)');
275
+ }
276
+ const report = {
277
+ checks: {}
278
+ };
279
+ const {
280
+ connectivity,
281
+ ssl
282
+ } = await runConnectivityAndSSL(proxyUrl, parsedTimeout);
283
+ report.checks.connectivity = connectivity;
284
+ 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;
297
+ const hasFail = Object.values(report.checks).some(c => (c === null || c === void 0 ? void 0 : c.status) === 'fail');
298
+ const hasWarn = Object.values(report.checks).some(c => (c === null || c === void 0 ? void 0 : c.status) === 'warn');
299
+ return {
300
+ checks: report.checks,
301
+ hasFail,
302
+ hasWarn
303
+ };
304
+ }
305
+
306
+ // ─── Private rendering helpers ────────────────────────────────────────────────
307
+
308
+ /**
309
+ * Render the domain table, proxy-header list, and update the tally for the
310
+ * browser section. Only Percy/BrowserStack domains count toward pass/fail.
311
+ */
312
+ export function _renderBrowserResults(log, browserResult, proxyUrl) {
313
+ var _browserResult$proxyH;
314
+ if (browserResult.error) {
315
+ print(log, checkLine('info', `Browser capture note: ${browserResult.error}`));
316
+ }
317
+ const allRows = browserResult.domainSummary ?? [];
318
+ const hasProxy = !!proxyUrl && allRows.some(d => d.viaProxy !== null);
319
+ if (allRows.length) {
320
+ print(log, '');
321
+ if (hasProxy) {
322
+ // ── Two-column table: Direct | Via Proxy ──────────────────────────────
323
+ print(log, ' Domains loaded by Chrome (direct vs via proxy):');
324
+ print(log, ` ${'─'.repeat(72)}`);
325
+ print(log, ` ${'Hostname'.padEnd(35)} ${'Direct'.padEnd(12)} ${'Via Proxy'.padEnd(12)} HTTP`);
326
+ print(log, ` ${'─'.repeat(72)}`);
327
+ for (const d of allRows) {
328
+ var _d$direct, _d$viaProxy;
329
+ const directLabel = d.direct ? d.direct.reachable ? 'reachable' : 'failed' : '—';
330
+ const proxyLabel = d.viaProxy ? d.viaProxy.reachable ? 'reachable' : d.viaProxy.errors.some(e => /PROXY_AUTH|407/i.test(e)) ? 'auth-required' : d.viaProxy.errors.some(e => /ERR_PROXY_CONNECTION_FAILED|ERR_TUNNEL_CONNECTION/i.test(e)) ? 'no-proxy' : d.viaProxy.errors.some(e => /ERR_CERT|ERR_SSL|CERTIFICATE|TLS/i.test(e)) ? 'cert-error' : d.viaProxy.blocked ? 'blocked' : d.viaProxy.sampleStatus != null && d.viaProxy.sampleStatus >= 400 ? `http-${d.viaProxy.sampleStatus}` : 'failed' : '—';
331
+ const httpCode = String(((_d$direct = d.direct) === null || _d$direct === void 0 ? void 0 : _d$direct.sampleStatus) ?? ((_d$viaProxy = d.viaProxy) === null || _d$viaProxy === void 0 ? void 0 : _d$viaProxy.sampleStatus) ?? '—');
332
+ const icon = {
333
+ pass: '\u2714',
334
+ warn: '\u26a0',
335
+ fail: '\u2716',
336
+ skip: '\u2013'
337
+ }[d.status] ?? '\u2139';
338
+ const hostDisplay = d.hostname.length > 34 ? d.hostname.slice(0, 32) + '\u2026' : d.hostname;
339
+ print(log, ` ${icon} ${hostDisplay.padEnd(34)} ${directLabel.padEnd(12)} ${proxyLabel.padEnd(12)} ${httpCode}`);
340
+ }
341
+ print(log, ` ${'─'.repeat(72)}`);
342
+ } else {
343
+ // ── Single-column table: Status ───────────────────────────────────────
344
+ print(log, ' Domains loaded by Chrome:');
345
+ print(log, ` ${'─'.repeat(62)}`);
346
+ print(log, ` ${'Hostname'.padEnd(40)} ${'Status'.padEnd(10)} HTTP`);
347
+ print(log, ` ${'─'.repeat(62)}`);
348
+ for (const d of allRows) {
349
+ var _d$direct2, _d$direct3;
350
+ const statusLabel = (_d$direct2 = d.direct) !== null && _d$direct2 !== void 0 && _d$direct2.reachable ? 'reachable' : 'blocked';
351
+ const httpCode = String(((_d$direct3 = d.direct) === null || _d$direct3 === void 0 ? void 0 : _d$direct3.sampleStatus) ?? '—');
352
+ const icon = {
353
+ pass: '\u2714',
354
+ warn: '\u26a0',
355
+ fail: '\u2716',
356
+ skip: '\u2013'
357
+ }[d.status] ?? '\u2139';
358
+ const hostDisplay = d.hostname.length > 39 ? d.hostname.slice(0, 37) + '\u2026' : d.hostname;
359
+ print(log, ` ${icon} ${hostDisplay.padEnd(39)} ${statusLabel.padEnd(10)} ${httpCode}`);
360
+ }
361
+ print(log, ` ${'─'.repeat(62)}`);
362
+ }
363
+ }
364
+ if ((_browserResult$proxyH = browserResult.proxyHeaders) !== null && _browserResult$proxyH !== void 0 && _browserResult$proxyH.length) {
365
+ print(log, '');
366
+ print(log, checkLine('warn', 'Proxy-indicating headers seen in browser traffic:'));
367
+ for (const h of browserResult.proxyHeaders.slice(0, 5)) {
368
+ print(log, ` ${h}`);
369
+ }
370
+ }
371
+
372
+ // Tally: only Percy/BrowserStack domains count.
373
+ const criticalBlocked = allRows.filter(d => PERCY_DOMAINS.has(d.hostname) && d.status === 'fail');
374
+ if (!allRows.length) {
375
+ print(log, checkLine('warn', 'No network requests captured from Chrome.'));
376
+ } else if (criticalBlocked.length === 0) {
377
+ print(log, checkLine('pass', 'Percy/BrowserStack domains are reachable from Chrome.'));
378
+ } else {
379
+ print(log, checkLine('fail', `Percy domain(s) unreachable from Chrome: ${criticalBlocked.map(d => d.hostname).join(', ')}`));
380
+ 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
+ }
382
+ }
@@ -0,0 +1,252 @@
1
+ function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }
2
+ function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
3
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
4
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
5
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
6
+ function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
7
+ import https from 'https';
8
+ import http from 'http';
9
+ import net from 'net';
10
+ import tls from 'tls';
11
+ import { URL } from 'url';
12
+
13
+ // Default request timeout (10 seconds)
14
+ const DEFAULT_TIMEOUT = 10000;
15
+
16
+ /**
17
+ * Probe result object
18
+ * @typedef {object} ProbeResult
19
+ * @property {boolean} ok - True if request succeeded (2xx/3xx)
20
+ * @property {number} status - HTTP status code (0 if no response)
21
+ * @property {string} error - Error message if request failed
22
+ * @property {string} errorCode - Node.js error code (e.g. CERT_HAS_EXPIRED)
23
+ * @property {number} latencyMs - Round-trip time in milliseconds
24
+ */
25
+ var _HttpProber_brand = /*#__PURE__*/new WeakSet();
26
+ export class HttpProber {
27
+ constructor() {
28
+ /**
29
+ * Unified request dispatcher. Routes to the right transport based on whether
30
+ * a proxy is present and whether the target URL uses HTTPS.
31
+ *
32
+ * • no proxy → direct HTTP or HTTPS
33
+ * • proxy + HTTPS target → CONNECT tunnel → TLS → HTTPS request
34
+ * • proxy + HTTP target → plain HTTP request with absolute-URI to proxy
35
+ */
36
+ _classPrivateMethodInitSpec(this, _HttpProber_brand);
37
+ }
38
+ /**
39
+ * Make a probe HTTP/HTTPS request, resolving with a ProbeResult rather than
40
+ * throwing so callers can inspect what went wrong.
41
+ *
42
+ * @param {string} targetUrl
43
+ * @param {object} [options]
44
+ * @param {string} [options.proxyUrl] - http(s)://host:port proxy
45
+ * @param {number} [options.timeout] - ms before abort (default 10 000)
46
+ * @param {string} [options.method] - HTTP verb (default HEAD)
47
+ * @returns {Promise<ProbeResult>}
48
+ */
49
+ async probeUrl(targetUrl, options = {}) {
50
+ const {
51
+ proxyUrl,
52
+ timeout = DEFAULT_TIMEOUT,
53
+ method = 'HEAD'
54
+ } = options;
55
+ const start = Date.now();
56
+ try {
57
+ const url = new URL(targetUrl);
58
+ const proxy = proxyUrl ? new URL(proxyUrl) : null;
59
+ const result = await _assertClassBrand(_HttpProber_brand, this, _makeRequest).call(this, url, proxy, {
60
+ timeout,
61
+ method
62
+ });
63
+ result.latencyMs = Date.now() - start;
64
+ return result;
65
+ } catch (err) {
66
+ return {
67
+ ok: false,
68
+ status: 0,
69
+ error: err.message,
70
+ errorCode: /* istanbul ignore next */err.code ?? 'UNKNOWN',
71
+ latencyMs: Date.now() - start
72
+ };
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Returns true when the probe result carries an SSL/TLS error code.
78
+ *
79
+ * @param {ProbeResult} result
80
+ * @returns {boolean}
81
+ */
82
+ isSslError(result) {
83
+ if (!result || !result.errorCode) return false;
84
+ if (HttpProber.SSL_ERROR_CODES.has(result.errorCode)) return true;
85
+ return result.errorCode.includes('CERT') || result.errorCode.includes('SSL');
86
+ }
87
+ }
88
+ function _makeRequest(url, proxy, {
89
+ timeout,
90
+ method
91
+ }) {
92
+ // ── common response resolver ──────────────────────────────────────────────
93
+ function resolveResponse(res, resolve) {
94
+ res.resume(); // drain body
95
+ const status = res.statusCode;
96
+ resolve({
97
+ ok: status >= 200 && status < 400,
98
+ status,
99
+ error: null,
100
+ errorCode: null,
101
+ responseHeaders: res.headers
102
+ });
103
+ }
104
+
105
+ // ── common timeout error ──────────────────────────────────────────────────
106
+ function timeoutError(label) {
107
+ return Object.assign(new Error(`${label} timed out after ${timeout}ms`), {
108
+ code: 'ETIMEDOUT'
109
+ });
110
+ }
111
+
112
+ // ─────────────────────────────────────────────────────────────────────────
113
+ // (A) HTTPS via CONNECT proxy tunnel
114
+ // ─────────────────────────────────────────────────────────────────────────
115
+ if (proxy && url.protocol === 'https:') {
116
+ return new Promise((resolve, reject) => {
117
+ const proxyPort = parseInt(proxy.port, 10) || (proxy.protocol === 'https:' ? 443 : 8080);
118
+ const targetPort = parseInt(url.port, 10) || 443;
119
+ const socket = net.connect({
120
+ host: proxy.hostname,
121
+ port: proxyPort
122
+ });
123
+ let tlsSock = null;
124
+ let settled = false;
125
+ const fail = err => {
126
+ /* istanbul ignore next */
127
+ if (settled) return;
128
+ settled = true;
129
+ clearTimeout(timer);
130
+ try {
131
+ var _tlsSock;
132
+ (_tlsSock = tlsSock) === null || _tlsSock === void 0 || _tlsSock.destroy();
133
+ } catch {/* ignore */}
134
+ try {
135
+ socket.destroy();
136
+ } catch {/* ignore */}
137
+ reject(err);
138
+ };
139
+ const pass = result => {
140
+ /* istanbul ignore next */
141
+ if (settled) return;
142
+ settled = true;
143
+ clearTimeout(timer);
144
+ resolve(result);
145
+ };
146
+ const timer = setTimeout(() => {
147
+ fail(timeoutError('Proxy CONNECT'));
148
+ }, timeout);
149
+ socket.on('error', fail);
150
+ socket.on('connect', () => {
151
+ const authHeader = proxy.username ? `Proxy-Authorization: Basic ${Buffer.from(`${proxy.username}:${proxy.password}`).toString('base64')}\r\n` : '';
152
+ socket.write(`CONNECT ${url.hostname}:${targetPort} HTTP/1.1\r\n` + `Host: ${url.hostname}:${targetPort}\r\n` + authHeader + '\r\n');
153
+ let response = '';
154
+ socket.on('data', chunk => {
155
+ response += chunk.toString();
156
+ if (!response.includes('\r\n\r\n')) return;
157
+ const statusLine = response.split('\r\n')[0];
158
+ const statusCode = parseInt(statusLine.split(' ')[1], 10);
159
+ if (statusCode !== 200) {
160
+ return fail(Object.assign(new Error(`Proxy CONNECT failed: ${statusLine}`), {
161
+ code: 'EPROXY'
162
+ }));
163
+ }
164
+ socket.removeAllListeners('data');
165
+ tlsSock = tls.connect({
166
+ socket,
167
+ servername: url.hostname
168
+ });
169
+ tlsSock.on('error', fail);
170
+ tlsSock.on('secureConnect', () => {
171
+ const req = https.request({
172
+ createConnection: () => tlsSock,
173
+ hostname: url.hostname,
174
+ port: targetPort,
175
+ 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
+ }));
184
+ req.on('error', fail);
185
+ req.end();
186
+ });
187
+ });
188
+ });
189
+ });
190
+ }
191
+
192
+ // ─────────────────────────────────────────────────────────────────────────
193
+ // (B) HTTP via proxy (plain absolute-URI request, no tunnelling)
194
+ // ─────────────────────────────────────────────────────────────────────────
195
+ if (proxy && url.protocol === 'http:') {
196
+ return new Promise((resolve, reject) => {
197
+ const proxyPort = parseInt(proxy.port, 10) || 8080;
198
+ const req = http.request({
199
+ hostname: proxy.hostname,
200
+ port: proxyPort,
201
+ path: url.href,
202
+ // absolute URI
203
+ method,
204
+ timeout,
205
+ headers: {
206
+ Host: url.hostname,
207
+ ...(proxy.username ? {
208
+ 'Proxy-Authorization': `Basic ${Buffer.from(`${proxy.username}:${proxy.password}`).toString('base64')}`
209
+ } : {})
210
+ }
211
+ }, res => {
212
+ if (res.statusCode === 407) {
213
+ res.resume();
214
+ return reject(Object.assign(new Error('Proxy CONNECT failed: HTTP/1.1 407 Proxy Authentication Required'), {
215
+ code: 'EPROXY'
216
+ }));
217
+ }
218
+ resolveResponse(res, resolve);
219
+ });
220
+ req.on('timeout', () => {
221
+ req.destroy();
222
+ reject(timeoutError('Request'));
223
+ });
224
+ req.on('error', reject);
225
+ req.end();
226
+ });
227
+ }
228
+
229
+ // ─────────────────────────────────────────────────────────────────────────
230
+ // (C) Direct HTTP or HTTPS (no proxy)
231
+ // ─────────────────────────────────────────────────────────────────────────
232
+ return new Promise((resolve, reject) => {
233
+ const driver = url.protocol === 'https:' ? https : http;
234
+ const port = url.port || (url.protocol === 'https:' ? 443 : 80);
235
+ const req = driver.request({
236
+ hostname: url.hostname,
237
+ port,
238
+ path: url.pathname + url.search,
239
+ method,
240
+ timeout
241
+ }, res => resolveResponse(res, resolve));
242
+ req.on('timeout', () => {
243
+ req.destroy();
244
+ reject(timeoutError('Request'));
245
+ });
246
+ req.on('error', reject);
247
+ req.end();
248
+ });
249
+ }
250
+ // SSL-related error codes emitted by Node's TLS/crypto layer
251
+ _defineProperty(HttpProber, "SSL_ERROR_CODES", new Set(['CERT_HAS_EXPIRED', 'CERT_NOT_YET_VALID', 'CERT_REVOKED', 'DEPTH_ZERO_SELF_SIGNED_CERT', 'ERR_TLS_CERT_ALTNAME_INVALID', 'SELF_SIGNED_CERT_IN_CHAIN', 'UNABLE_TO_GET_ISSUER_CERT', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY']));
252
+ export const httpProber = new HttpProber();