prepareURLs.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file at
  6. * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
  7. */
  8. const url = require('url')
  9. const { chalk } = require('@vue/cli-shared-utils')
  10. const address = require('address')
  11. const defaultGateway = require('default-gateway')
  12. module.exports = function prepareUrls (protocol, host, port, pathname = '/') {
  13. const formatUrl = hostname =>
  14. url.format({
  15. protocol,
  16. hostname,
  17. port,
  18. pathname
  19. })
  20. const prettyPrintUrl = hostname =>
  21. url.format({
  22. protocol,
  23. hostname,
  24. port: chalk.bold(port),
  25. pathname
  26. })
  27. const isUnspecifiedHost = host === '0.0.0.0' || host === '::'
  28. let prettyHost, lanUrlForConfig
  29. let lanUrlForTerminal = chalk.gray('unavailable')
  30. if (isUnspecifiedHost) {
  31. prettyHost = 'localhost'
  32. try {
  33. // This can only return an IPv4 address
  34. const result = defaultGateway.v4.sync()
  35. lanUrlForConfig = address.ip(result && result.interface)
  36. if (lanUrlForConfig) {
  37. // Check if the address is a private ip
  38. // https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
  39. if (
  40. /^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(
  41. lanUrlForConfig
  42. )
  43. ) {
  44. // Address is private, format it for later use
  45. lanUrlForTerminal = prettyPrintUrl(lanUrlForConfig)
  46. } else {
  47. // Address is not private, so we will discard it
  48. lanUrlForConfig = undefined
  49. }
  50. }
  51. } catch (_e) {
  52. // ignored
  53. }
  54. } else {
  55. prettyHost = host
  56. lanUrlForConfig = host
  57. lanUrlForTerminal = prettyPrintUrl(lanUrlForConfig)
  58. }
  59. const localUrlForTerminal = prettyPrintUrl(prettyHost)
  60. const localUrlForBrowser = formatUrl(prettyHost)
  61. return {
  62. lanUrlForConfig,
  63. lanUrlForTerminal,
  64. localUrlForTerminal,
  65. localUrlForBrowser
  66. }
  67. }