Skip to content

Commit

Permalink
fix: correctly handle data URL with hashes. (nodejs#2475)
Browse files Browse the repository at this point in the history
* fix: correctly handle data URL with hashes.

* fix: lint

* test: better name

* suggestion change

* perf: avoid substring

* fixup

* test: better
  • Loading branch information
tsctx authored and crysmags committed Feb 27, 2024
1 parent 23455ba commit c384bd8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
13 changes: 5 additions & 8 deletions lib/fetch/dataURL.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,17 +119,14 @@ function dataURLProcessor (dataURL) {
* @param {boolean} excludeFragment
*/
function URLSerializer (url, excludeFragment = false) {
const href = url.href

if (!excludeFragment) {
return href
return url.href
}

const hash = href.lastIndexOf('#')
if (hash === -1) {
return href
}
return href.slice(0, hash)
const href = url.href
const hashLength = url.hash.length

return hashLength === 0 ? href : href.substring(0, href.length - hashLength)
}

// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
Expand Down
21 changes: 21 additions & 0 deletions test/fetch/data-uri.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,24 @@ test('https://domain.com/?', (t) => {
const serialized = URLSerializer(new URL(domain))
t.equal(serialized, domain)
})

// https://github.com/nodejs/undici/issues/2474
test('hash url', (t) => {
t.plan(1)
const domain = 'https://domain.com/#a#b'
const url = new URL(domain)
const serialized = URLSerializer(url, true)
t.equal(serialized, url.href.substring(0, url.href.length - url.hash.length))
})

// https://github.com/nodejs/undici/issues/2474
test('data url that includes the hash', async (t) => {
t.plan(1)
const dataURL = 'data:,node#js#'
try {
const res = await fetch(dataURL)
t.equal(await res.text(), 'node')
} catch (error) {
t.fail(`failed to fetch ${dataURL}`)
}
})

0 comments on commit c384bd8

Please sign in to comment.