url.js 1.7 KB

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