File size: 1,107 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { execSync } from 'node:child_process'
import { lookup } from 'node:dns/promises'
import url from 'node:url'

function getProxy(): string | undefined {
  if (process.env.https_proxy) {
    return process.env.https_proxy
  }

  try {
    const httpsProxy = execSync('npm config get https-proxy').toString().trim()
    return httpsProxy !== 'null' ? httpsProxy : undefined
  } catch (e) {
    return
  }
}

export async function getOnline(): Promise<boolean> {
  try {
    await lookup('registry.yarnpkg.com')
    // If DNS lookup succeeds, we are online
    return true
  } catch {
    // The DNS lookup failed, but we are still fine as long as a proxy has been set
    const proxy = getProxy()
    if (!proxy) {
      return false
    }

    const { hostname } = url.parse(proxy)
    if (!hostname) {
      // Invalid proxy URL
      return false
    }

    try {
      await lookup(hostname)
      // If DNS lookup succeeds for the proxy server, we are online
      return true
    } catch {
      // The DNS lookup for the proxy server also failed, so we are offline
      return false
    }
  }
}