• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1const readline = require('readline')
2const open = require('./open-url.js')
3
4function print (npm, title, url) {
5  const json = npm.config.get('json')
6
7  const message = json ? JSON.stringify({ title, url }) : `${title}:\n${url}`
8
9  npm.output(message)
10}
11
12// Prompt to open URL in browser if possible
13const promptOpen = async (npm, url, title, prompt, emitter) => {
14  const browser = npm.config.get('browser')
15  const isInteractive = process.stdin.isTTY === true && process.stdout.isTTY === true
16
17  try {
18    if (!/^https?:$/.test(new URL(url).protocol)) {
19      throw new Error()
20    }
21  } catch (_) {
22    throw new Error('Invalid URL: ' + url)
23  }
24
25  print(npm, title, url)
26
27  if (browser === false || !isInteractive) {
28    return
29  }
30
31  const rl = readline.createInterface({
32    input: process.stdin,
33    output: process.stdout,
34  })
35
36  const tryOpen = await new Promise(resolve => {
37    rl.on('SIGINT', () => {
38      rl.close()
39      resolve('SIGINT')
40    })
41
42    rl.question(prompt, () => {
43      resolve(true)
44    })
45
46    if (emitter && emitter.addListener) {
47      emitter.addListener('abort', () => {
48        rl.close()
49
50        // clear the prompt line
51        npm.output('')
52
53        resolve(false)
54      })
55    }
56  })
57
58  if (tryOpen === 'SIGINT') {
59    throw new Error('canceled')
60  }
61
62  if (!tryOpen) {
63    return
64  }
65
66  await open(npm, url, 'Browser unavailable.  Please open the URL manually')
67}
68
69module.exports = promptOpen
70