You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.6 KiB

8 years ago
  1. /**
  2. * Module dependencies.
  3. */
  4. var parseuri = require('parseuri');
  5. var debug = require('debug')('socket.io-client:url');
  6. /**
  7. * Module exports.
  8. */
  9. module.exports = url;
  10. /**
  11. * URL parser.
  12. *
  13. * @param {String} url
  14. * @param {Object} An object meant to mimic window.location.
  15. * Defaults to window.location.
  16. * @api public
  17. */
  18. function url (uri, loc) {
  19. var obj = uri;
  20. // default to window.location
  21. loc = loc || global.location;
  22. if (null == uri) uri = loc.protocol + '//' + loc.host;
  23. // relative path support
  24. if ('string' === typeof uri) {
  25. if ('/' === uri.charAt(0)) {
  26. if ('/' === uri.charAt(1)) {
  27. uri = loc.protocol + uri;
  28. } else {
  29. uri = loc.host + uri;
  30. }
  31. }
  32. if (!/^(https?|wss?):\/\//.test(uri)) {
  33. debug('protocol-less url %s', uri);
  34. if ('undefined' !== typeof loc) {
  35. uri = loc.protocol + '//' + uri;
  36. } else {
  37. uri = 'https://' + uri;
  38. }
  39. }
  40. // parse
  41. debug('parse %s', uri);
  42. obj = parseuri(uri);
  43. }
  44. // make sure we treat `localhost:80` and `localhost` equally
  45. if (!obj.port) {
  46. if (/^(http|ws)$/.test(obj.protocol)) {
  47. obj.port = '80';
  48. } else if (/^(http|ws)s$/.test(obj.protocol)) {
  49. obj.port = '443';
  50. }
  51. }
  52. obj.path = obj.path || '/';
  53. var ipv6 = obj.host.indexOf(':') !== -1;
  54. var host = ipv6 ? '[' + obj.host + ']' : obj.host;
  55. // define unique id
  56. obj.id = obj.protocol + '://' + host + ':' + obj.port;
  57. // define href
  58. obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : (':' + obj.port));
  59. return obj;
  60. }