resolve-uri.mjs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. // Matches the scheme of a URL, eg "http://"
  2. const schemeRegex = /^[\w+.-]+:\/\//;
  3. /**
  4. * Matches the parts of a URL:
  5. * 1. Scheme, including ":", guaranteed.
  6. * 2. User/password, including "@", optional.
  7. * 3. Host, guaranteed.
  8. * 4. Port, including ":", optional.
  9. * 5. Path, including "/", optional.
  10. */
  11. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?/;
  12. /**
  13. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  14. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  15. *
  16. * 1. Host, optional.
  17. * 2. Path, which may inclue "/", guaranteed.
  18. */
  19. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/]*)?)?(\/?.*)/i;
  20. function isAbsoluteUrl(input) {
  21. return schemeRegex.test(input);
  22. }
  23. function isSchemeRelativeUrl(input) {
  24. return input.startsWith('//');
  25. }
  26. function isAbsolutePath(input) {
  27. return input.startsWith('/');
  28. }
  29. function isFileUrl(input) {
  30. return input.startsWith('file:');
  31. }
  32. function parseAbsoluteUrl(input) {
  33. const match = urlRegex.exec(input);
  34. return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/');
  35. }
  36. function parseFileUrl(input) {
  37. const match = fileRegex.exec(input);
  38. const path = match[2];
  39. return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path);
  40. }
  41. function makeUrl(scheme, user, host, port, path) {
  42. return {
  43. scheme,
  44. user,
  45. host,
  46. port,
  47. path,
  48. relativePath: false,
  49. };
  50. }
  51. function parseUrl(input) {
  52. if (isSchemeRelativeUrl(input)) {
  53. const url = parseAbsoluteUrl('http:' + input);
  54. url.scheme = '';
  55. return url;
  56. }
  57. if (isAbsolutePath(input)) {
  58. const url = parseAbsoluteUrl('http://foo.com' + input);
  59. url.scheme = '';
  60. url.host = '';
  61. return url;
  62. }
  63. if (isFileUrl(input))
  64. return parseFileUrl(input);
  65. if (isAbsoluteUrl(input))
  66. return parseAbsoluteUrl(input);
  67. const url = parseAbsoluteUrl('http://foo.com/' + input);
  68. url.scheme = '';
  69. url.host = '';
  70. url.relativePath = true;
  71. return url;
  72. }
  73. function stripPathFilename(path) {
  74. // If a path ends with a parent directory "..", then it's a relative path with excess parent
  75. // paths. It's not a file, so we can't strip it.
  76. if (path.endsWith('/..'))
  77. return path;
  78. const index = path.lastIndexOf('/');
  79. return path.slice(0, index + 1);
  80. }
  81. function mergePaths(url, base) {
  82. // If we're not a relative path, then we're an absolute path, and it doesn't matter what base is.
  83. if (!url.relativePath)
  84. return;
  85. normalizePath(base);
  86. // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
  87. // path).
  88. if (url.path === '/') {
  89. url.path = base.path;
  90. }
  91. else {
  92. // Resolution happens relative to the base path's directory, not the file.
  93. url.path = stripPathFilename(base.path) + url.path;
  94. }
  95. // If the base path is absolute, then our path is now absolute too.
  96. url.relativePath = base.relativePath;
  97. }
  98. /**
  99. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  100. * "foo/.". We need to normalize to a standard representation.
  101. */
  102. function normalizePath(url) {
  103. const { relativePath } = url;
  104. const pieces = url.path.split('/');
  105. // We need to preserve the first piece always, so that we output a leading slash. The item at
  106. // pieces[0] is an empty string.
  107. let pointer = 1;
  108. // Positive is the number of real directories we've output, used for popping a parent directory.
  109. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
  110. let positive = 0;
  111. // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
  112. // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
  113. // real directory, we won't need to append, unless the other conditions happen again.
  114. let addTrailingSlash = false;
  115. for (let i = 1; i < pieces.length; i++) {
  116. const piece = pieces[i];
  117. // An empty directory, could be a trailing slash, or just a double "//" in the path.
  118. if (!piece) {
  119. addTrailingSlash = true;
  120. continue;
  121. }
  122. // If we encounter a real directory, then we don't need to append anymore.
  123. addTrailingSlash = false;
  124. // A current directory, which we can always drop.
  125. if (piece === '.')
  126. continue;
  127. // A parent directory, we need to see if there are any real directories we can pop. Else, we
  128. // have an excess of parents, and we'll need to keep the "..".
  129. if (piece === '..') {
  130. if (positive) {
  131. addTrailingSlash = true;
  132. positive--;
  133. pointer--;
  134. }
  135. else if (relativePath) {
  136. // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
  137. // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
  138. pieces[pointer++] = piece;
  139. }
  140. continue;
  141. }
  142. // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
  143. // any popped or dropped directories.
  144. pieces[pointer++] = piece;
  145. positive++;
  146. }
  147. let path = '';
  148. for (let i = 1; i < pointer; i++) {
  149. path += '/' + pieces[i];
  150. }
  151. if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
  152. path += '/';
  153. }
  154. url.path = path;
  155. }
  156. /**
  157. * Attempts to resolve `input` URL/path relative to `base`.
  158. */
  159. function resolve(input, base) {
  160. if (!input && !base)
  161. return '';
  162. const url = parseUrl(input);
  163. // If we have a base, and the input isn't already an absolute URL, then we need to merge.
  164. if (base && !url.scheme) {
  165. const baseUrl = parseUrl(base);
  166. url.scheme = baseUrl.scheme;
  167. // If there's no host, then we were just a path.
  168. if (!url.host) {
  169. // The host, user, and port are joined, you can't copy one without the others.
  170. url.user = baseUrl.user;
  171. url.host = baseUrl.host;
  172. url.port = baseUrl.port;
  173. }
  174. mergePaths(url, baseUrl);
  175. }
  176. normalizePath(url);
  177. // If the input (and base, if there was one) are both relative, then we need to output a relative.
  178. if (url.relativePath) {
  179. // The first char is always a "/".
  180. const path = url.path.slice(1);
  181. if (!path)
  182. return '.';
  183. // If base started with a leading ".", or there is no base and input started with a ".", then we
  184. // need to ensure that the relative path starts with a ".". We don't know if relative starts
  185. // with a "..", though, so check before prepending.
  186. const keepRelative = (base || input).startsWith('.');
  187. return !keepRelative || path.startsWith('.') ? path : './' + path;
  188. }
  189. // If there's no host (and no scheme/user/port), then we need to output an absolute path.
  190. if (!url.scheme && !url.host)
  191. return url.path;
  192. // We're outputting either an absolute URL, or a protocol relative one.
  193. return `${url.scheme}//${url.user}${url.host}${url.port}${url.path}`;
  194. }
  195. export { resolve as default };
  196. //# sourceMappingURL=resolve-uri.mjs.map