getUrlFromParts.js 1014 B

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * Create a valid URL from parsed URL parts.
  3. * @param {import('./getSocketUrlParts').SocketUrlParts} urlParts The parsed URL parts.
  4. * @param {import('./getWDSMetadata').WDSMetaObj} [metadata] The parsed WDS metadata object.
  5. * @returns {string} The generated URL.
  6. */
  7. function urlFromParts(urlParts, metadata) {
  8. if (typeof metadata === 'undefined') {
  9. metadata = {};
  10. }
  11. let fullProtocol = 'http:';
  12. if (urlParts.protocol) {
  13. fullProtocol = urlParts.protocol;
  14. }
  15. if (metadata.enforceWs) {
  16. fullProtocol = fullProtocol.replace(/^(?:http|.+-extension|file)/i, 'ws');
  17. }
  18. fullProtocol = fullProtocol + '//';
  19. let fullHost = urlParts.hostname;
  20. if (urlParts.auth) {
  21. const fullAuth = urlParts.auth.split(':').map(encodeURIComponent).join(':') + '@';
  22. fullHost = fullAuth + fullHost;
  23. }
  24. if (urlParts.port) {
  25. fullHost = fullHost + ':' + urlParts.port;
  26. }
  27. const url = new URL(urlParts.pathname, fullProtocol + fullHost);
  28. return url.href;
  29. }
  30. module.exports = urlFromParts;