index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. 'use strict'
  2. const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require('./lib/utils')
  3. const { SCHEMES, getSchemeHandler } = require('./lib/schemes')
  4. /**
  5. * @template {import('./types/index').URIComponent|string} T
  6. * @param {T} uri
  7. * @param {import('./types/index').Options} [options]
  8. * @returns {T}
  9. */
  10. function normalize (uri, options) {
  11. if (typeof uri === 'string') {
  12. uri = /** @type {T} */ (normalizeString(uri, options))
  13. } else if (typeof uri === 'object') {
  14. uri = /** @type {T} */ (parse(serialize(uri, options), options))
  15. }
  16. return uri
  17. }
  18. /**
  19. * @param {string} baseURI
  20. * @param {string} relativeURI
  21. * @param {import('./types/index').Options} [options]
  22. * @returns {string}
  23. */
  24. function resolve (baseURI, relativeURI, options) {
  25. const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' }
  26. const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true)
  27. schemelessOptions.skipEscape = true
  28. return serialize(resolved, schemelessOptions)
  29. }
  30. /**
  31. * @param {import ('./types/index').URIComponent} base
  32. * @param {import ('./types/index').URIComponent} relative
  33. * @param {import('./types/index').Options} [options]
  34. * @param {boolean} [skipNormalization=false]
  35. * @returns {import ('./types/index').URIComponent}
  36. */
  37. function resolveComponent (base, relative, options, skipNormalization) {
  38. /** @type {import('./types/index').URIComponent} */
  39. const target = {}
  40. if (!skipNormalization) {
  41. base = parse(serialize(base, options), options) // normalize base component
  42. relative = parse(serialize(relative, options), options) // normalize relative component
  43. }
  44. options = options || {}
  45. if (!options.tolerant && relative.scheme) {
  46. target.scheme = relative.scheme
  47. // target.authority = relative.authority;
  48. target.userinfo = relative.userinfo
  49. target.host = relative.host
  50. target.port = relative.port
  51. target.path = removeDotSegments(relative.path || '')
  52. target.query = relative.query
  53. } else {
  54. if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
  55. // target.authority = relative.authority;
  56. target.userinfo = relative.userinfo
  57. target.host = relative.host
  58. target.port = relative.port
  59. target.path = removeDotSegments(relative.path || '')
  60. target.query = relative.query
  61. } else {
  62. if (!relative.path) {
  63. target.path = base.path
  64. if (relative.query !== undefined) {
  65. target.query = relative.query
  66. } else {
  67. target.query = base.query
  68. }
  69. } else {
  70. if (relative.path[0] === '/') {
  71. target.path = removeDotSegments(relative.path)
  72. } else {
  73. if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
  74. target.path = '/' + relative.path
  75. } else if (!base.path) {
  76. target.path = relative.path
  77. } else {
  78. target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path
  79. }
  80. target.path = removeDotSegments(target.path)
  81. }
  82. target.query = relative.query
  83. }
  84. // target.authority = base.authority;
  85. target.userinfo = base.userinfo
  86. target.host = base.host
  87. target.port = base.port
  88. }
  89. target.scheme = base.scheme
  90. }
  91. target.fragment = relative.fragment
  92. return target
  93. }
  94. /**
  95. * @param {import ('./types/index').URIComponent|string} uriA
  96. * @param {import ('./types/index').URIComponent|string} uriB
  97. * @param {import ('./types/index').Options} options
  98. * @returns {boolean}
  99. */
  100. function equal (uriA, uriB, options) {
  101. const normalizedA = normalizeComparableURI(uriA, options)
  102. const normalizedB = normalizeComparableURI(uriB, options)
  103. return normalizedA !== undefined && normalizedB !== undefined && normalizedA.toLowerCase() === normalizedB.toLowerCase()
  104. }
  105. /**
  106. * @param {Readonly<import('./types/index').URIComponent>} cmpts
  107. * @param {import('./types/index').Options} [opts]
  108. * @returns {string}
  109. */
  110. function serialize (cmpts, opts) {
  111. const component = {
  112. host: cmpts.host,
  113. scheme: cmpts.scheme,
  114. userinfo: cmpts.userinfo,
  115. port: cmpts.port,
  116. path: cmpts.path,
  117. query: cmpts.query,
  118. nid: cmpts.nid,
  119. nss: cmpts.nss,
  120. uuid: cmpts.uuid,
  121. fragment: cmpts.fragment,
  122. reference: cmpts.reference,
  123. resourceName: cmpts.resourceName,
  124. secure: cmpts.secure,
  125. error: ''
  126. }
  127. const options = Object.assign({}, opts)
  128. const uriTokens = []
  129. // find scheme handler
  130. const schemeHandler = getSchemeHandler(options.scheme || component.scheme)
  131. // perform scheme specific serialization
  132. if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options)
  133. if (component.path !== undefined) {
  134. if (!options.skipEscape) {
  135. component.path = escapePreservingEscapes(component.path)
  136. if (component.scheme !== undefined) {
  137. component.path = component.path.split('%3A').join(':')
  138. }
  139. } else {
  140. component.path = normalizePercentEncoding(component.path)
  141. }
  142. }
  143. if (options.reference !== 'suffix' && component.scheme) {
  144. uriTokens.push(component.scheme, ':')
  145. }
  146. const authority = recomposeAuthority(component)
  147. if (authority !== undefined) {
  148. if (options.reference !== 'suffix') {
  149. uriTokens.push('//')
  150. }
  151. uriTokens.push(authority)
  152. if (component.path && component.path[0] !== '/') {
  153. uriTokens.push('/')
  154. }
  155. }
  156. if (component.path !== undefined) {
  157. let s = component.path
  158. if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
  159. s = removeDotSegments(s)
  160. }
  161. if (
  162. authority === undefined &&
  163. s[0] === '/' &&
  164. s[1] === '/'
  165. ) {
  166. // don't allow the path to start with "//"
  167. s = '/%2F' + s.slice(2)
  168. }
  169. uriTokens.push(s)
  170. }
  171. if (component.query !== undefined) {
  172. uriTokens.push('?', component.query)
  173. }
  174. if (component.fragment !== undefined) {
  175. uriTokens.push('#', component.fragment)
  176. }
  177. return uriTokens.join('')
  178. }
  179. const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u
  180. /**
  181. * @param {import('./types/index').URIComponent} parsed
  182. * @param {RegExpMatchArray} matches
  183. * @returns {string|undefined}
  184. */
  185. function getParseError (parsed, matches) {
  186. if (matches[2] !== undefined && parsed.path && parsed.path[0] !== '/') {
  187. return 'URI path must start with "/" when authority is present.'
  188. }
  189. if (typeof parsed.port === 'number' && (parsed.port < 0 || parsed.port > 65535)) {
  190. return 'URI port is malformed.'
  191. }
  192. return undefined
  193. }
  194. /**
  195. * @param {string} uri
  196. * @param {import('./types/index').Options} [opts]
  197. * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean }}
  198. */
  199. function parseWithStatus (uri, opts) {
  200. const options = Object.assign({}, opts)
  201. /** @type {import('./types/index').URIComponent} */
  202. const parsed = {
  203. scheme: undefined,
  204. userinfo: undefined,
  205. host: '',
  206. port: undefined,
  207. path: '',
  208. query: undefined,
  209. fragment: undefined
  210. }
  211. let malformedAuthorityOrPort = false
  212. let isIP = false
  213. if (options.reference === 'suffix') {
  214. if (options.scheme) {
  215. uri = options.scheme + ':' + uri
  216. } else {
  217. uri = '//' + uri
  218. }
  219. }
  220. const matches = uri.match(URI_PARSE)
  221. if (matches) {
  222. // store each component
  223. parsed.scheme = matches[1]
  224. parsed.userinfo = matches[3]
  225. parsed.host = matches[4]
  226. parsed.port = parseInt(matches[5], 10)
  227. parsed.path = matches[6] || ''
  228. parsed.query = matches[7]
  229. parsed.fragment = matches[8]
  230. // fix port number
  231. if (isNaN(parsed.port)) {
  232. parsed.port = matches[5]
  233. }
  234. const parseError = getParseError(parsed, matches)
  235. if (parseError !== undefined) {
  236. parsed.error = parsed.error || parseError
  237. malformedAuthorityOrPort = true
  238. }
  239. if (parsed.host) {
  240. const ipv4result = isIPv4(parsed.host)
  241. if (ipv4result === false) {
  242. const ipv6result = normalizeIPv6(parsed.host)
  243. parsed.host = ipv6result.host.toLowerCase()
  244. isIP = ipv6result.isIPV6
  245. } else {
  246. isIP = true
  247. }
  248. }
  249. if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {
  250. parsed.reference = 'same-document'
  251. } else if (parsed.scheme === undefined) {
  252. parsed.reference = 'relative'
  253. } else if (parsed.fragment === undefined) {
  254. parsed.reference = 'absolute'
  255. } else {
  256. parsed.reference = 'uri'
  257. }
  258. // check for reference errors
  259. if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {
  260. parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'
  261. }
  262. // find scheme handler
  263. const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme)
  264. // check if scheme can't handle IRIs
  265. if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
  266. // if host component is a domain name
  267. if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) {
  268. // convert Unicode IDN -> ASCII IDN
  269. try {
  270. parsed.host = URL.domainToASCII(parsed.host.toLowerCase())
  271. } catch (e) {
  272. parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e
  273. }
  274. }
  275. // convert IRI -> URI
  276. }
  277. if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {
  278. if (uri.indexOf('%') !== -1) {
  279. if (parsed.scheme !== undefined) {
  280. parsed.scheme = unescape(parsed.scheme)
  281. }
  282. if (parsed.host !== undefined) {
  283. parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP)
  284. }
  285. }
  286. if (parsed.path) {
  287. parsed.path = normalizePathEncoding(parsed.path)
  288. }
  289. if (parsed.fragment) {
  290. try {
  291. parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment))
  292. } catch {
  293. parsed.error = parsed.error || 'URI malformed'
  294. }
  295. }
  296. }
  297. // perform scheme specific parsing
  298. if (schemeHandler && schemeHandler.parse) {
  299. schemeHandler.parse(parsed, options)
  300. }
  301. } else {
  302. parsed.error = parsed.error || 'URI can not be parsed.'
  303. }
  304. return { parsed, malformedAuthorityOrPort }
  305. }
  306. /**
  307. * @param {string} uri
  308. * @param {import('./types/index').Options} [opts]
  309. * @returns
  310. */
  311. function parse (uri, opts) {
  312. return parseWithStatus(uri, opts).parsed
  313. }
  314. /**
  315. * @param {string} uri
  316. * @param {import('./types/index').Options} [opts]
  317. * @returns {string}
  318. */
  319. function normalizeString (uri, opts) {
  320. return normalizeStringWithStatus(uri, opts).normalized
  321. }
  322. /**
  323. * @param {string} uri
  324. * @param {import('./types/index').Options} [opts]
  325. * @returns {{ normalized: string, malformedAuthorityOrPort: boolean }}
  326. */
  327. function normalizeStringWithStatus (uri, opts) {
  328. const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts)
  329. return {
  330. normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts),
  331. malformedAuthorityOrPort
  332. }
  333. }
  334. /**
  335. * @param {import ('./types/index').URIComponent|string} uri
  336. * @param {import('./types/index').Options} [opts]
  337. * @returns {string|undefined}
  338. */
  339. function normalizeComparableURI (uri, opts) {
  340. if (typeof uri === 'string') {
  341. const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts)
  342. return malformedAuthorityOrPort ? undefined : normalized
  343. }
  344. if (typeof uri === 'object') {
  345. return serialize(uri, opts)
  346. }
  347. }
  348. const fastUri = {
  349. SCHEMES,
  350. normalize,
  351. resolve,
  352. resolveComponent,
  353. equal,
  354. serialize,
  355. parse
  356. }
  357. module.exports = fastUri
  358. module.exports.default = fastUri
  359. module.exports.fastUri = fastUri