url.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.url = void 0;
  7. const parseuri_1 = __importDefault(require("parseuri"));
  8. const debug_1 = __importDefault(require("debug")); // debug()
  9. const debug = debug_1.default("socket.io-client:url"); // debug()
  10. /**
  11. * URL parser.
  12. *
  13. * @param uri - url
  14. * @param path - the request path of the connection
  15. * @param loc - An object meant to mimic window.location.
  16. * Defaults to window.location.
  17. * @public
  18. */
  19. function url(uri, path = "", loc) {
  20. let obj = uri;
  21. // default to window.location
  22. loc = loc || (typeof location !== "undefined" && location);
  23. if (null == uri)
  24. uri = loc.protocol + "//" + loc.host;
  25. // relative path support
  26. if (typeof uri === "string") {
  27. if ("/" === uri.charAt(0)) {
  28. if ("/" === uri.charAt(1)) {
  29. uri = loc.protocol + uri;
  30. }
  31. else {
  32. uri = loc.host + uri;
  33. }
  34. }
  35. if (!/^(https?|wss?):\/\//.test(uri)) {
  36. debug("protocol-less url %s", uri);
  37. if ("undefined" !== typeof loc) {
  38. uri = loc.protocol + "//" + uri;
  39. }
  40. else {
  41. uri = "https://" + uri;
  42. }
  43. }
  44. // parse
  45. debug("parse %s", uri);
  46. obj = parseuri_1.default(uri);
  47. }
  48. // make sure we treat `localhost:80` and `localhost` equally
  49. if (!obj.port) {
  50. if (/^(http|ws)$/.test(obj.protocol)) {
  51. obj.port = "80";
  52. }
  53. else if (/^(http|ws)s$/.test(obj.protocol)) {
  54. obj.port = "443";
  55. }
  56. }
  57. obj.path = obj.path || "/";
  58. const ipv6 = obj.host.indexOf(":") !== -1;
  59. const host = ipv6 ? "[" + obj.host + "]" : obj.host;
  60. // define unique id
  61. obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
  62. // define href
  63. obj.href =
  64. obj.protocol +
  65. "://" +
  66. host +
  67. (loc && loc.port === obj.port ? "" : ":" + obj.port);
  68. return obj;
  69. }
  70. exports.url = url;