index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. 'use strict';
  2. var required = require('requires-port')
  3. , qs = require('querystringify')
  4. , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:[\\/]+/
  5. , protocolre = /^([a-z][a-z0-9.+-]*:)?([\\/]{1,})?([\S\s]*)/i
  6. , whitespace = '[\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF]'
  7. , left = new RegExp('^'+ whitespace +'+');
  8. /**
  9. * Trim a given string.
  10. *
  11. * @param {String} str String to trim.
  12. * @public
  13. */
  14. function trimLeft(str) {
  15. return (str ? str : '').toString().replace(left, '');
  16. }
  17. /**
  18. * These are the parse rules for the URL parser, it informs the parser
  19. * about:
  20. *
  21. * 0. The char it Needs to parse, if it's a string it should be done using
  22. * indexOf, RegExp using exec and NaN means set as current value.
  23. * 1. The property we should set when parsing this value.
  24. * 2. Indication if it's backwards or forward parsing, when set as number it's
  25. * the value of extra chars that should be split off.
  26. * 3. Inherit from location if non existing in the parser.
  27. * 4. `toLowerCase` the resulting value.
  28. */
  29. var rules = [
  30. ['#', 'hash'], // Extract from the back.
  31. ['?', 'query'], // Extract from the back.
  32. function sanitize(address) { // Sanitize what is left of the address
  33. return address.replace('\\', '/');
  34. },
  35. ['/', 'pathname'], // Extract from the back.
  36. ['@', 'auth', 1], // Extract from the front.
  37. [NaN, 'host', undefined, 1, 1], // Set left over value.
  38. [/:(\d+)$/, 'port', undefined, 1], // RegExp the back.
  39. [NaN, 'hostname', undefined, 1, 1] // Set left over.
  40. ];
  41. /**
  42. * These properties should not be copied or inherited from. This is only needed
  43. * for all non blob URL's as a blob URL does not include a hash, only the
  44. * origin.
  45. *
  46. * @type {Object}
  47. * @private
  48. */
  49. var ignore = { hash: 1, query: 1 };
  50. /**
  51. * The location object differs when your code is loaded through a normal page,
  52. * Worker or through a worker using a blob. And with the blobble begins the
  53. * trouble as the location object will contain the URL of the blob, not the
  54. * location of the page where our code is loaded in. The actual origin is
  55. * encoded in the `pathname` so we can thankfully generate a good "default"
  56. * location from it so we can generate proper relative URL's again.
  57. *
  58. * @param {Object|String} loc Optional default location object.
  59. * @returns {Object} lolcation object.
  60. * @public
  61. */
  62. function lolcation(loc) {
  63. var globalVar;
  64. if (typeof window !== 'undefined') globalVar = window;
  65. else if (typeof global !== 'undefined') globalVar = global;
  66. else if (typeof self !== 'undefined') globalVar = self;
  67. else globalVar = {};
  68. var location = globalVar.location || {};
  69. loc = loc || location;
  70. var finaldestination = {}
  71. , type = typeof loc
  72. , key;
  73. if ('blob:' === loc.protocol) {
  74. finaldestination = new Url(unescape(loc.pathname), {});
  75. } else if ('string' === type) {
  76. finaldestination = new Url(loc, {});
  77. for (key in ignore) delete finaldestination[key];
  78. } else if ('object' === type) {
  79. for (key in loc) {
  80. if (key in ignore) continue;
  81. finaldestination[key] = loc[key];
  82. }
  83. if (finaldestination.slashes === undefined) {
  84. finaldestination.slashes = slashes.test(loc.href);
  85. }
  86. }
  87. return finaldestination;
  88. }
  89. /**
  90. * @typedef ProtocolExtract
  91. * @type Object
  92. * @property {String} protocol Protocol matched in the URL, in lowercase.
  93. * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
  94. * @property {String} rest Rest of the URL that is not part of the protocol.
  95. */
  96. /**
  97. * Extract protocol information from a URL with/without double slash ("//").
  98. *
  99. * @param {String} address URL we want to extract from.
  100. * @return {ProtocolExtract} Extracted information.
  101. * @private
  102. */
  103. function extractProtocol(address) {
  104. address = trimLeft(address);
  105. var match = protocolre.exec(address)
  106. , protocol = match[1] ? match[1].toLowerCase() : ''
  107. , slashes = !!(match[2] && match[2].length >= 2)
  108. , rest = match[2] && match[2].length === 1 ? '/' + match[3] : match[3];
  109. return {
  110. protocol: protocol,
  111. slashes: slashes,
  112. rest: rest
  113. };
  114. }
  115. /**
  116. * Resolve a relative URL pathname against a base URL pathname.
  117. *
  118. * @param {String} relative Pathname of the relative URL.
  119. * @param {String} base Pathname of the base URL.
  120. * @return {String} Resolved pathname.
  121. * @private
  122. */
  123. function resolve(relative, base) {
  124. if (relative === '') return base;
  125. var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
  126. , i = path.length
  127. , last = path[i - 1]
  128. , unshift = false
  129. , up = 0;
  130. while (i--) {
  131. if (path[i] === '.') {
  132. path.splice(i, 1);
  133. } else if (path[i] === '..') {
  134. path.splice(i, 1);
  135. up++;
  136. } else if (up) {
  137. if (i === 0) unshift = true;
  138. path.splice(i, 1);
  139. up--;
  140. }
  141. }
  142. if (unshift) path.unshift('');
  143. if (last === '.' || last === '..') path.push('');
  144. return path.join('/');
  145. }
  146. /**
  147. * The actual URL instance. Instead of returning an object we've opted-in to
  148. * create an actual constructor as it's much more memory efficient and
  149. * faster and it pleases my OCD.
  150. *
  151. * It is worth noting that we should not use `URL` as class name to prevent
  152. * clashes with the global URL instance that got introduced in browsers.
  153. *
  154. * @constructor
  155. * @param {String} address URL we want to parse.
  156. * @param {Object|String} [location] Location defaults for relative paths.
  157. * @param {Boolean|Function} [parser] Parser for the query string.
  158. * @private
  159. */
  160. function Url(address, location, parser) {
  161. address = trimLeft(address);
  162. if (!(this instanceof Url)) {
  163. return new Url(address, location, parser);
  164. }
  165. var relative, extracted, parse, instruction, index, key
  166. , instructions = rules.slice()
  167. , type = typeof location
  168. , url = this
  169. , i = 0;
  170. //
  171. // The following if statements allows this module two have compatibility with
  172. // 2 different API:
  173. //
  174. // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
  175. // where the boolean indicates that the query string should also be parsed.
  176. //
  177. // 2. The `URL` interface of the browser which accepts a URL, object as
  178. // arguments. The supplied object will be used as default values / fall-back
  179. // for relative paths.
  180. //
  181. if ('object' !== type && 'string' !== type) {
  182. parser = location;
  183. location = null;
  184. }
  185. if (parser && 'function' !== typeof parser) parser = qs.parse;
  186. location = lolcation(location);
  187. //
  188. // Extract protocol information before running the instructions.
  189. //
  190. extracted = extractProtocol(address || '');
  191. relative = !extracted.protocol && !extracted.slashes;
  192. url.slashes = extracted.slashes || relative && location.slashes;
  193. url.protocol = extracted.protocol || location.protocol || '';
  194. address = extracted.rest;
  195. //
  196. // When the authority component is absent the URL starts with a path
  197. // component.
  198. //
  199. if (!extracted.slashes) instructions[3] = [/(.*)/, 'pathname'];
  200. for (; i < instructions.length; i++) {
  201. instruction = instructions[i];
  202. if (typeof instruction === 'function') {
  203. address = instruction(address);
  204. continue;
  205. }
  206. parse = instruction[0];
  207. key = instruction[1];
  208. if (parse !== parse) {
  209. url[key] = address;
  210. } else if ('string' === typeof parse) {
  211. if (~(index = address.indexOf(parse))) {
  212. if ('number' === typeof instruction[2]) {
  213. url[key] = address.slice(0, index);
  214. address = address.slice(index + instruction[2]);
  215. } else {
  216. url[key] = address.slice(index);
  217. address = address.slice(0, index);
  218. }
  219. }
  220. } else if ((index = parse.exec(address))) {
  221. url[key] = index[1];
  222. address = address.slice(0, index.index);
  223. }
  224. url[key] = url[key] || (
  225. relative && instruction[3] ? location[key] || '' : ''
  226. );
  227. //
  228. // Hostname, host and protocol should be lowercased so they can be used to
  229. // create a proper `origin`.
  230. //
  231. if (instruction[4]) url[key] = url[key].toLowerCase();
  232. }
  233. //
  234. // Also parse the supplied query string in to an object. If we're supplied
  235. // with a custom parser as function use that instead of the default build-in
  236. // parser.
  237. //
  238. if (parser) url.query = parser(url.query);
  239. //
  240. // If the URL is relative, resolve the pathname against the base URL.
  241. //
  242. if (
  243. relative
  244. && location.slashes
  245. && url.pathname.charAt(0) !== '/'
  246. && (url.pathname !== '' || location.pathname !== '')
  247. ) {
  248. url.pathname = resolve(url.pathname, location.pathname);
  249. }
  250. //
  251. // Default to a / for pathname if none exists. This normalizes the URL
  252. // to always have a /
  253. //
  254. if (url.pathname.charAt(0) !== '/' && url.hostname) {
  255. url.pathname = '/' + url.pathname;
  256. }
  257. //
  258. // We should not add port numbers if they are already the default port number
  259. // for a given protocol. As the host also contains the port number we're going
  260. // override it with the hostname which contains no port number.
  261. //
  262. if (!required(url.port, url.protocol)) {
  263. url.host = url.hostname;
  264. url.port = '';
  265. }
  266. //
  267. // Parse down the `auth` for the username and password.
  268. //
  269. url.username = url.password = '';
  270. if (url.auth) {
  271. instruction = url.auth.split(':');
  272. url.username = instruction[0] || '';
  273. url.password = instruction[1] || '';
  274. }
  275. url.origin = url.protocol && url.host && url.protocol !== 'file:'
  276. ? url.protocol +'//'+ url.host
  277. : 'null';
  278. //
  279. // The href is just the compiled result.
  280. //
  281. url.href = url.toString();
  282. }
  283. /**
  284. * This is convenience method for changing properties in the URL instance to
  285. * insure that they all propagate correctly.
  286. *
  287. * @param {String} part Property we need to adjust.
  288. * @param {Mixed} value The newly assigned value.
  289. * @param {Boolean|Function} fn When setting the query, it will be the function
  290. * used to parse the query.
  291. * When setting the protocol, double slash will be
  292. * removed from the final url if it is true.
  293. * @returns {URL} URL instance for chaining.
  294. * @public
  295. */
  296. function set(part, value, fn) {
  297. var url = this;
  298. switch (part) {
  299. case 'query':
  300. if ('string' === typeof value && value.length) {
  301. value = (fn || qs.parse)(value);
  302. }
  303. url[part] = value;
  304. break;
  305. case 'port':
  306. url[part] = value;
  307. if (!required(value, url.protocol)) {
  308. url.host = url.hostname;
  309. url[part] = '';
  310. } else if (value) {
  311. url.host = url.hostname +':'+ value;
  312. }
  313. break;
  314. case 'hostname':
  315. url[part] = value;
  316. if (url.port) value += ':'+ url.port;
  317. url.host = value;
  318. break;
  319. case 'host':
  320. url[part] = value;
  321. if (/:\d+$/.test(value)) {
  322. value = value.split(':');
  323. url.port = value.pop();
  324. url.hostname = value.join(':');
  325. } else {
  326. url.hostname = value;
  327. url.port = '';
  328. }
  329. break;
  330. case 'protocol':
  331. url.protocol = value.toLowerCase();
  332. url.slashes = !fn;
  333. break;
  334. case 'pathname':
  335. case 'hash':
  336. if (value) {
  337. var char = part === 'pathname' ? '/' : '#';
  338. url[part] = value.charAt(0) !== char ? char + value : value;
  339. } else {
  340. url[part] = value;
  341. }
  342. break;
  343. default:
  344. url[part] = value;
  345. }
  346. for (var i = 0; i < rules.length; i++) {
  347. var ins = rules[i];
  348. if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
  349. }
  350. url.origin = url.protocol && url.host && url.protocol !== 'file:'
  351. ? url.protocol +'//'+ url.host
  352. : 'null';
  353. url.href = url.toString();
  354. return url;
  355. }
  356. /**
  357. * Transform the properties back in to a valid and full URL string.
  358. *
  359. * @param {Function} stringify Optional query stringify function.
  360. * @returns {String} Compiled version of the URL.
  361. * @public
  362. */
  363. function toString(stringify) {
  364. if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;
  365. var query
  366. , url = this
  367. , protocol = url.protocol;
  368. if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';
  369. var result = protocol + (url.slashes ? '//' : '');
  370. if (url.username) {
  371. result += url.username;
  372. if (url.password) result += ':'+ url.password;
  373. result += '@';
  374. }
  375. result += url.host + url.pathname;
  376. query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  377. if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;
  378. if (url.hash) result += url.hash;
  379. return result;
  380. }
  381. Url.prototype = { set: set, toString: toString };
  382. //
  383. // Expose the URL parser and some additional properties that might be useful for
  384. // others or testing.
  385. //
  386. Url.extractProtocol = extractProtocol;
  387. Url.location = lolcation;
  388. Url.trimLeft = trimLeft;
  389. Url.qs = qs;
  390. module.exports = Url;