1import { execSync } from 'child_process';
2import dns from 'dns';
3import url from 'url';
4
5/** Determine if you should use yarn offline or not */
6export async function isYarnOfflineAsync(): Promise<boolean> {
7  if (await isUrlAvailableAsync('registry.yarnpkg.com')) {
8    return false;
9  }
10
11  const proxy = getNpmProxy();
12
13  if (!proxy) {
14    return true;
15  }
16
17  const { hostname } = url.parse(proxy);
18  if (!hostname) {
19    return true;
20  }
21
22  return !(await isUrlAvailableAsync(hostname));
23}
24
25/** Exposed for testing */
26export function getNpmProxy(): string | null {
27  if (process.env.https_proxy) {
28    return process.env.https_proxy ?? null;
29  }
30
31  try {
32    const httpsProxy = execSync('npm config get https-proxy').toString().trim();
33    return httpsProxy !== 'null' ? httpsProxy : null;
34  } catch {
35    return null;
36  }
37}
38
39function isUrlAvailableAsync(url: string): Promise<boolean> {
40  return new Promise<boolean>((resolve) => {
41    dns.lookup(url, (err) => {
42      resolve(!err);
43    });
44  });
45}
46