Welcome to mirror list, hosted at ThFree Co, Russian Federation.

open-url.js « utils « lib - github.com/npm/cli.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a38a881b56943c00939ed2c1bd1475c56cf8ed16 (plain)
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
47
48
'use strict'
const npm = require('../npm.js')
const output = require('./output.js')
const opener = require('opener')

const {URL} = require('url')

const isUrlValid = url => {
  try {
    return /^https?:$/.test(new URL(url).protocol)
  } catch (_) {
    return false
  }
}

// attempt to open URL in web-browser, print address otherwise:
module.exports = function open (url, errMsg, cb, browser = npm.config.get('browser')) {
  function printAlternateMsg () {
    const json = npm.config.get('json')
    const alternateMsg = json
      ? JSON.stringify({
        title: errMsg,
        url
      }, null, 2)
      : `${errMsg}:\n  ${url}\n`

    output(alternateMsg)
  }

  if (browser === false) {
    printAlternateMsg()
    return cb()
  }

  if (!isUrlValid(url)) {
    return cb(new Error('Invalid URL: ' + url))
  }

  const command = browser === true ? null : browser
  opener(url, { command }, (er) => {
    if (er && er.code === 'ENOENT') {
      printAlternateMsg()
      return cb()
    } else {
      return cb(er)
    }
  })
}