utils.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. 'use strict'
  2. /** @type {(value: string) => boolean} */
  3. const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu)
  4. /** @type {(value: string) => boolean} */
  5. const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u)
  6. /** @type {(value: string) => boolean} */
  7. const isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu)
  8. /** @type {(value: string) => boolean} */
  9. const isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu)
  10. /** @type {(value: string) => boolean} */
  11. const isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u)
  12. /** @type {(value: string) => boolean} */
  13. const isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u)
  14. /** @type {(value: string) => boolean} */
  15. const isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u)
  16. const BYTE_HEX = new Array(256)
  17. {
  18. const HEX_DIGITS = '0123456789ABCDEF'
  19. for (let i = 0; i < 256; i++) {
  20. BYTE_HEX[i] = '%' + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 0xF]
  21. }
  22. }
  23. function percentEncodeNonAscii (cp) {
  24. if (cp < 0x800) {
  25. return BYTE_HEX[0xC0 | (cp >> 6)] +
  26. BYTE_HEX[0x80 | (cp & 0x3F)]
  27. }
  28. if (cp < 0x10000) {
  29. return BYTE_HEX[0xE0 | (cp >> 12)] +
  30. BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] +
  31. BYTE_HEX[0x80 | (cp & 0x3F)]
  32. }
  33. return BYTE_HEX[0xF0 | (cp >> 18)] +
  34. BYTE_HEX[0x80 | ((cp >> 12) & 0x3F)] +
  35. BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] +
  36. BYTE_HEX[0x80 | (cp & 0x3F)]
  37. }
  38. /**
  39. * @param {Array<string>} input
  40. * @returns {string}
  41. */
  42. function stringArrayToHexStripped (input) {
  43. let acc = ''
  44. let code = 0
  45. let i = 0
  46. for (i = 0; i < input.length; i++) {
  47. code = input[i].charCodeAt(0)
  48. if (code === 48) {
  49. continue
  50. }
  51. if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {
  52. return ''
  53. }
  54. acc += input[i]
  55. break
  56. }
  57. for (i += 1; i < input.length; i++) {
  58. code = input[i].charCodeAt(0)
  59. if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {
  60. return ''
  61. }
  62. acc += input[i]
  63. }
  64. return acc
  65. }
  66. /** @type {(value: string) => boolean} */
  67. const isHextet = RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/)
  68. /** @type {(value: string) => boolean} */
  69. const isIPvFuture = RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/)
  70. /** @type {(value: string) => boolean} */
  71. const isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/)
  72. /**
  73. * @param {string} value
  74. * @returns {boolean}
  75. */
  76. const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u)
  77. /**
  78. * @param {string} zone
  79. * @returns {boolean}
  80. */
  81. function isZoneIdentifier (zone) {
  82. if (zone.length === 0) return false
  83. for (let i = 0; i < zone.length; i++) {
  84. if (isZoneCharacter(zone[i])) continue
  85. if (zone[i] === '%' && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) {
  86. i += 2
  87. continue
  88. }
  89. return false
  90. }
  91. return true
  92. }
  93. /**
  94. * Compresses the longest run of zero hextets to "::" per RFC 5952. A run of a
  95. * single zero hextet is left uncompressed. On ties the leftmost run wins.
  96. *
  97. * @param {string[]} hextets
  98. * @returns {string}
  99. */
  100. function compressIPv6ZeroRun (hextets) {
  101. let bestStart = -1
  102. let bestLength = 0
  103. let runStart = -1
  104. let runLength = 0
  105. for (let i = 0; i < hextets.length; i++) {
  106. if (hextets[i] === '0') {
  107. if (runStart === -1) runStart = i
  108. runLength++
  109. if (runLength > bestLength) {
  110. bestLength = runLength
  111. bestStart = runStart
  112. }
  113. } else {
  114. runStart = -1
  115. runLength = 0
  116. }
  117. }
  118. if (bestLength < 2) return hextets.join(':')
  119. const head = hextets.slice(0, bestStart).join(':')
  120. const tail = hextets.slice(bestStart + bestLength).join(':')
  121. return head + '::' + tail
  122. }
  123. /**
  124. * Validates an IPv6 address against the alternatives in RFC 3986 section
  125. * 3.2.2 and returns the same address with leading hextet zeroes removed.
  126. * An embedded IPv4 address counts as two hextets and is only valid at the end.
  127. *
  128. * @param {string} input
  129. * @returns {string|undefined}
  130. */
  131. function normalizeIPv6Address (input) {
  132. const compression = input.indexOf('::')
  133. if (compression !== -1 && input.indexOf('::', compression + 1) !== -1) return undefined
  134. const left = compression === -1 ? input.split(':') : input.slice(0, compression).split(':')
  135. const right = compression === -1 ? [] : input.slice(compression + 2).split(':')
  136. if (compression !== -1) {
  137. if (left.length === 1 && left[0] === '') left.length = 0
  138. if (right.length === 1 && right[0] === '') right.length = 0
  139. }
  140. const parts = left.concat(right)
  141. let hextetCount = 0
  142. for (let i = 0; i < parts.length; i++) {
  143. const part = parts[i]
  144. if (part === '') return undefined
  145. if (part.indexOf('.') !== -1) {
  146. if (i !== parts.length - 1 || (compression !== -1 && right.length === 0) || !isIPv4(part)) return undefined
  147. hextetCount += 2
  148. continue
  149. }
  150. if (!isHextet(part)) return undefined
  151. parts[i] = parseInt(part, 16).toString(16)
  152. hextetCount++
  153. }
  154. if (compression === -1) {
  155. if (hextetCount !== 8) return undefined
  156. return compressIPv6ZeroRun(parts)
  157. }
  158. if (hextetCount >= 8) return undefined
  159. // expand "::" then re-compress the longest run for a canonical result
  160. const expanded = parts.slice(0, left.length)
  161. for (let i = hextetCount; i < 8; i++) expanded.push('0')
  162. for (let i = left.length; i < parts.length; i++) expanded.push(parts[i])
  163. return compressIPv6ZeroRun(expanded)
  164. }
  165. /**
  166. * @typedef {Object} NormalizeIPv6Result
  167. * @property {string} host - The normalized host.
  168. * @property {string} [escapedHost] - The escaped host.
  169. * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.
  170. * @property {boolean} [isIPVFuture] - Indicates if the host is an IPvFuture literal.
  171. * @property {boolean} [error] - Indicates if a bracketed IP literal is malformed.
  172. */
  173. /**
  174. * Validates and normalizes a bracketed IP literal. Raw zone separators remain
  175. * accepted for backwards compatibility, while encoded separators and zone
  176. * contents follow RFC 6874.
  177. *
  178. * @param {string} host
  179. * @returns {NormalizeIPv6Result}
  180. */
  181. function normalizeIPv6 (host) {
  182. const bracketed = host[0] === '[' && host[host.length - 1] === ']'
  183. const hasBracket = host[0] === '[' || host[host.length - 1] === ']'
  184. if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }
  185. let input = bracketed ? host.slice(1, -1) : host
  186. if (bracketed && isIPvFuture(input)) {
  187. input = input.toLowerCase()
  188. return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }
  189. }
  190. if (findToken(input, ':') < 2) {
  191. return { host, isIPV6: false, error: bracketed }
  192. }
  193. let zoneIdentifier = ''
  194. const zoneSeparator = input.indexOf('%')
  195. if (zoneSeparator !== -1) {
  196. const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === '%25' ? 3 : 1
  197. zoneIdentifier = input.slice(zoneSeparator + separatorLength)
  198. if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }
  199. input = input.slice(0, zoneSeparator)
  200. }
  201. const address = normalizeIPv6Address(input)
  202. if (address === undefined) return { host, isIPV6: false, error: true }
  203. return {
  204. host: address + (zoneIdentifier ? '%' + zoneIdentifier : ''),
  205. escapedHost: address + (zoneIdentifier ? '%25' + zoneIdentifier : ''),
  206. isIPV6: true
  207. }
  208. }
  209. /**
  210. * @param {string} str
  211. * @param {string} token
  212. * @returns {number}
  213. */
  214. function findToken (str, token) {
  215. let ind = 0
  216. for (let i = 0; i < str.length; i++) {
  217. if (str[i] === token) ind++
  218. }
  219. return ind
  220. }
  221. /**
  222. * @param {string} path
  223. * @returns {string}
  224. *
  225. * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
  226. */
  227. function removeDotSegments (path) {
  228. let input = path
  229. const output = []
  230. let nextSlash = -1
  231. let len = 0
  232. // eslint-disable-next-line no-cond-assign
  233. while (len = input.length) {
  234. if (len === 1) {
  235. if (input === '.') {
  236. break
  237. } else if (input === '/') {
  238. output.push('/')
  239. break
  240. } else {
  241. output.push(input)
  242. break
  243. }
  244. } else if (len === 2) {
  245. if (input[0] === '.') {
  246. if (input[1] === '.') {
  247. break
  248. } else if (input[1] === '/') {
  249. input = input.slice(2)
  250. continue
  251. }
  252. } else if (input[0] === '/') {
  253. if (input[1] === '.' || input[1] === '/') {
  254. output.push('/')
  255. break
  256. }
  257. }
  258. } else if (len === 3) {
  259. if (input === '/..') {
  260. if (output.length !== 0) {
  261. output.pop()
  262. }
  263. output.push('/')
  264. break
  265. }
  266. }
  267. if (input[0] === '.') {
  268. if (input[1] === '.') {
  269. if (input[2] === '/') {
  270. input = input.slice(3)
  271. continue
  272. }
  273. } else if (input[1] === '/') {
  274. input = input.slice(2)
  275. continue
  276. }
  277. } else if (input[0] === '/') {
  278. if (input[1] === '.') {
  279. if (input[2] === '/') {
  280. input = input.slice(2)
  281. continue
  282. } else if (input[2] === '.') {
  283. if (input[3] === '/') {
  284. input = input.slice(3)
  285. if (output.length !== 0) {
  286. output.pop()
  287. }
  288. continue
  289. }
  290. }
  291. }
  292. }
  293. // Rule 2E: Move normal path segment to output
  294. if ((nextSlash = input.indexOf('/', 1)) === -1) {
  295. output.push(input)
  296. break
  297. } else {
  298. output.push(input.slice(0, nextSlash))
  299. input = input.slice(nextSlash)
  300. }
  301. }
  302. return output.join('')
  303. }
  304. /**
  305. * Re-escape RFC 3986 gen-delims that must not appear literally in the host.
  306. * After the URI regex parses, these characters cannot be literal in the host
  307. * field, so any that appear after decoding came from percent-encoding and
  308. * must be restored to prevent authority structure changes.
  309. *
  310. * @param {string} host
  311. * @param {boolean} isIP - true for IPv4/IPv6 hosts (skip colon re-escaping)
  312. * @returns {string}
  313. */
  314. const HOST_DELIMS = { '@': '%40', '/': '%2F', '?': '%3F', '#': '%23', ':': '%3A' }
  315. const HOST_DELIM_RE = /[@/?#:]/g
  316. const HOST_DELIM_NO_COLON_RE = /[@/?#]/g
  317. function reescapeHostDelimiters (host, isIP) {
  318. const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE
  319. re.lastIndex = 0
  320. return host.replace(re, (ch) => HOST_DELIMS[ch])
  321. }
  322. /**
  323. * Normalizes percent escapes and optionally decodes only unreserved ASCII bytes.
  324. * Reserved delimiters such as `%2F` stay escaped; `%2E` is unreserved.
  325. *
  326. * @param {string} input
  327. * @param {boolean} [decodeUnreserved=false]
  328. * @returns {string}
  329. */
  330. function normalizePercentEncoding (input, decodeUnreserved = false) {
  331. if (input.indexOf('%') === -1) {
  332. return input
  333. }
  334. let output = ''
  335. for (let i = 0; i < input.length; i++) {
  336. if (input[i] === '%' && i + 2 < input.length) {
  337. const hex = input.slice(i + 1, i + 3)
  338. if (isHexPair(hex)) {
  339. const normalizedHex = hex.toUpperCase()
  340. const decoded = String.fromCharCode(parseInt(normalizedHex, 16))
  341. if (decodeUnreserved && isUnreserved(decoded)) {
  342. output += decoded
  343. } else {
  344. output += '%' + normalizedHex
  345. }
  346. i += 2
  347. continue
  348. }
  349. }
  350. output += input[i]
  351. }
  352. return output
  353. }
  354. /**
  355. * Normalizes path data without turning reserved escapes into live path syntax.
  356. * Valid escapes are uppercased, raw unsafe characters are escaped, and only
  357. * unreserved bytes that are not `.` are decoded.
  358. *
  359. * @param {string} input
  360. * @returns {string}
  361. */
  362. function normalizePathEncoding (input) {
  363. let output = ''
  364. for (let i = 0; i < input.length; i++) {
  365. const ch = input[i]
  366. if (ch === '%' && i + 2 < input.length) {
  367. const hex = input.slice(i + 1, i + 3)
  368. if (isHexPair(hex)) {
  369. const normalizedHex = hex.toUpperCase()
  370. const decoded = String.fromCharCode(parseInt(normalizedHex, 16))
  371. if (decoded !== '.' && isUnreserved(decoded)) {
  372. output += decoded
  373. } else {
  374. output += '%' + normalizedHex
  375. }
  376. i += 2
  377. continue
  378. }
  379. }
  380. if (isPathCharacter(ch)) {
  381. output += ch
  382. } else {
  383. const code = input.charCodeAt(i)
  384. if (code < 0x80) {
  385. output += isEscapeSafe(code) ? ch : BYTE_HEX[code]
  386. } else if (code < 0xD800 || code > 0xDFFF) {
  387. output += percentEncodeNonAscii(code)
  388. } else if (code <= 0xDBFF && i + 1 < input.length) {
  389. const low = input.charCodeAt(i + 1)
  390. if (low >= 0xDC00 && low <= 0xDFFF) {
  391. output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))
  392. i++
  393. } else {
  394. output += percentEncodeNonAscii(0xFFFD)
  395. }
  396. } else {
  397. output += percentEncodeNonAscii(0xFFFD)
  398. }
  399. }
  400. }
  401. return output
  402. }
  403. /**
  404. * Serializes a path without rewriting reserved data. Raw RFC 3986 path
  405. * characters remain literal, valid escapes are preserved and uppercased, and
  406. * everything else is UTF-8 percent-encoded. In a path-noscheme, a colon in the
  407. * first segment must be escaped so the result cannot be parsed as a scheme.
  408. *
  409. * @param {string} input
  410. * @param {boolean} [pathNoScheme=false]
  411. * @returns {string}
  412. */
  413. function serializePathEncoding (input, pathNoScheme = false) {
  414. let output = ''
  415. let firstSegment = pathNoScheme && input[0] !== '/'
  416. for (let i = 0; i < input.length; i++) {
  417. const ch = input[i]
  418. if (ch === '%' && i + 2 < input.length) {
  419. const hex = input.slice(i + 1, i + 3)
  420. if (isHexPair(hex)) {
  421. output += '%' + hex.toUpperCase()
  422. i += 2
  423. continue
  424. }
  425. }
  426. if (ch === '/') {
  427. firstSegment = false
  428. }
  429. if (isPathCharacter(ch) && (ch !== ':' || !firstSegment)) {
  430. output += ch
  431. } else {
  432. const code = input.charCodeAt(i)
  433. if (code < 0x80) {
  434. output += BYTE_HEX[code]
  435. } else if (code < 0xD800 || code > 0xDFFF) {
  436. output += percentEncodeNonAscii(code)
  437. } else if (code <= 0xDBFF && i + 1 < input.length) {
  438. const low = input.charCodeAt(i + 1)
  439. if (low >= 0xDC00 && low <= 0xDFFF) {
  440. output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))
  441. i++
  442. } else {
  443. output += percentEncodeNonAscii(0xFFFD)
  444. }
  445. } else {
  446. output += percentEncodeNonAscii(0xFFFD)
  447. }
  448. }
  449. }
  450. return output
  451. }
  452. /**
  453. * Percent-encodes a URI component using its RFC 3986 literal character set.
  454. * Existing valid escapes are preserved and normalized to uppercase hex.
  455. *
  456. * @param {string} input
  457. * @param {(value: string) => boolean} isAllowed
  458. * @returns {string}
  459. */
  460. function encodeComponent (input, isAllowed) {
  461. let output = ''
  462. for (let i = 0; i < input.length; i++) {
  463. const ch = input[i]
  464. if (ch === '%' && i + 2 < input.length) {
  465. const hex = input.slice(i + 1, i + 3)
  466. if (isHexPair(hex)) {
  467. output += '%' + hex.toUpperCase()
  468. i += 2
  469. continue
  470. }
  471. }
  472. if (isAllowed(ch)) {
  473. output += ch
  474. } else {
  475. const code = input.charCodeAt(i)
  476. if (code < 0x80) {
  477. output += BYTE_HEX[code]
  478. } else if (code < 0xD800 || code > 0xDFFF) {
  479. output += percentEncodeNonAscii(code)
  480. } else if (code <= 0xDBFF && i + 1 < input.length) {
  481. const low = input.charCodeAt(i + 1)
  482. if (low >= 0xDC00 && low <= 0xDFFF) {
  483. output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))
  484. i++
  485. } else {
  486. output += percentEncodeNonAscii(0xFFFD)
  487. }
  488. } else {
  489. output += percentEncodeNonAscii(0xFFFD)
  490. }
  491. }
  492. }
  493. return output
  494. }
  495. /**
  496. * Encodes userinfo while preserving its RFC 3986 §3.2.1 literal characters.
  497. * In particular, authority delimiters such as `@`, `/`, `?`, and `#` are data.
  498. *
  499. * @param {string} input
  500. * @returns {string}
  501. */
  502. function encodeUserinfo (input) {
  503. return encodeComponent(input, isUserinfoCharacter)
  504. }
  505. /**
  506. * Encodes query data using the RFC 3986 §3.4 grammar. A literal `#` must be
  507. * escaped because it would otherwise begin the fragment component.
  508. *
  509. * @param {string} input
  510. * @returns {string}
  511. */
  512. function encodeQuery (input) {
  513. return encodeComponent(input, isQueryFragmentCharacter)
  514. }
  515. /**
  516. * Encodes fragment data using the RFC 3986 §3.5 grammar.
  517. *
  518. * @param {string} input
  519. * @returns {string}
  520. */
  521. function encodeFragment (input) {
  522. return encodeComponent(input, isQueryFragmentCharacter)
  523. }
  524. function isEscapeSafe (cp) {
  525. return (
  526. (cp >= 0x30 && cp <= 0x39) ||
  527. (cp >= 0x41 && cp <= 0x5A) ||
  528. (cp >= 0x61 && cp <= 0x7A) ||
  529. cp === 0x2A || cp === 0x2B || cp === 0x2D || cp === 0x2E ||
  530. cp === 0x2F || cp === 0x40 || cp === 0x5F
  531. )
  532. }
  533. /**
  534. * Normalizes the percent-encoding of a query or fragment component.
  535. *
  536. * Like `normalizePathEncoding`, but uses the query/fragment character set
  537. * (which additionally allows `?`) and decodes `.` since it has no dot-segment
  538. * meaning outside of a path.
  539. *
  540. * @param {string} input
  541. * @returns {string}
  542. */
  543. function normalizeQueryFragmentEncoding (input) {
  544. let output = ''
  545. for (let i = 0; i < input.length; i++) {
  546. const ch = input[i]
  547. if (ch === '%' && i + 2 < input.length) {
  548. const hex = input.slice(i + 1, i + 3)
  549. if (isHexPair(hex)) {
  550. const normalizedHex = hex.toUpperCase()
  551. const decoded = String.fromCharCode(parseInt(normalizedHex, 16))
  552. if (isUnreserved(decoded)) {
  553. output += decoded
  554. } else {
  555. output += '%' + normalizedHex
  556. }
  557. i += 2
  558. continue
  559. }
  560. }
  561. if (isQueryFragmentCharacter(ch)) {
  562. output += ch
  563. } else {
  564. const code = input.charCodeAt(i)
  565. if (code < 0x80) {
  566. output += isEscapeSafe(code) ? ch : BYTE_HEX[code]
  567. } else if (code < 0xD800 || code > 0xDFFF) {
  568. output += percentEncodeNonAscii(code)
  569. } else if (code <= 0xDBFF && i + 1 < input.length) {
  570. const low = input.charCodeAt(i + 1)
  571. if (low >= 0xDC00 && low <= 0xDFFF) {
  572. output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))
  573. i++
  574. } else {
  575. output += percentEncodeNonAscii(0xFFFD)
  576. }
  577. } else {
  578. output += percentEncodeNonAscii(0xFFFD)
  579. }
  580. }
  581. }
  582. return output
  583. }
  584. /**
  585. * Escapes a component while preserving existing valid percent escapes.
  586. *
  587. * @param {string} input
  588. * @returns {string}
  589. */
  590. function escapePreservingEscapes (input) {
  591. let output = ''
  592. for (let i = 0; i < input.length; i++) {
  593. if (input[i] === '%' && i + 2 < input.length) {
  594. const hex = input.slice(i + 1, i + 3)
  595. if (isHexPair(hex)) {
  596. output += '%' + hex.toUpperCase()
  597. i += 2
  598. continue
  599. }
  600. }
  601. output += escape(input[i])
  602. }
  603. return output
  604. }
  605. /**
  606. * @param {import('../types/index').URIComponent} component
  607. * @returns {string|undefined}
  608. */
  609. function recomposeAuthority (component) {
  610. const uriTokens = []
  611. if (component.userinfo !== undefined) {
  612. uriTokens.push(encodeUserinfo(component.userinfo))
  613. uriTokens.push('@')
  614. }
  615. if (component.host !== undefined) {
  616. let host = component.host
  617. if (!isIPv4(host)) {
  618. let ipV6res = normalizeIPv6(host)
  619. if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) {
  620. // Decode only unreserved bytes, once. In particular, keep %25 encoded
  621. // so it cannot introduce a second escape during recomposition.
  622. host = normalizePercentEncoding(host, true)
  623. ipV6res = normalizeIPv6(host)
  624. }
  625. if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) {
  626. host = `[${ipV6res.escapedHost}]`
  627. } else {
  628. host = reescapeHostDelimiters(host, false)
  629. }
  630. }
  631. uriTokens.push(host)
  632. }
  633. if (typeof component.port === 'number' || typeof component.port === 'string') {
  634. uriTokens.push(':')
  635. uriTokens.push(String(component.port))
  636. }
  637. return uriTokens.length ? uriTokens.join('') : undefined
  638. };
  639. module.exports = {
  640. nonSimpleDomain,
  641. recomposeAuthority,
  642. reescapeHostDelimiters,
  643. normalizePercentEncoding,
  644. normalizePathEncoding,
  645. serializePathEncoding,
  646. normalizeQueryFragmentEncoding,
  647. encodeUserinfo,
  648. encodeQuery,
  649. encodeFragment,
  650. escapePreservingEscapes,
  651. removeDotSegments,
  652. isIPv4,
  653. isUUID,
  654. normalizeIPv6,
  655. stringArrayToHexStripped
  656. }