Unverified Commit 2251f438 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: avoid document-wide selector scans when probing for chunk tags (#100047)

## Summary

Fixes #99993.

On the first non-runtime load of each chunk URL, Turbopack's browser DOM
runtime checks whether a matching `<script>` or `<link rel=stylesheet>`
already exists. That check was a document-wide `querySelectorAll` with
four attribute and prefix selectors, so its cost grew with the size of
the whole DOM. It runs on the main thread during hydration, roughly once
per chunk. The selectors were also built by interpolating the URL
without escaping: a decoded `"` threw a `SyntaxError`, and a `\` missed
a tag that was already present.

The production loader (`doLoadChunk`) and the dev backend (`unloadChunk`
/ `reloadChunk`) now look tags up with `getElementsByTagName` and plain
string comparison. The helpers are defined once in the DOM backend and
reused by the dev backend, since the runtime files are concatenated
rather than imported as modules.

Matching behavior is otherwise unchanged:
- A tag matches if its raw attribute equals the chunk URL, or starts
with the URL plus `?`, for both the URL and its `decodeURI` form. A
different query string still does not match.
- The stylesheet lookup still requires `rel` to be exactly `stylesheet`
(ASCII case-insensitive). Dev CSS unload still ignores `rel`.
- All matching tags are returned in document order, from both head and
body.
- Results are snapshot arrays, so removing tags while looping over them
is safe.

This lowers the cost per probe but is still proportional to the number
of elements. A URL index that would make it independent of DOM size is
out of scope here.

## Verification

- New e2e test `test/e2e/app-dir/dynamic-chunk-dedupe`, passing with
`pnpm test-start-turbo` and `pnpm test-dev-turbo`:
- The fixture has server-rendered and `ssr: false` dynamic components,
including CSS modules, and sets a `deploymentId` so chunk URLs carry
`?dpl=`.
- It asserts that styles apply, there are no page errors, each chunk is
requested once, and the DOM has no duplicate chunk tags.
- Sanity check: with the lookup deliberately broken, the DOM check
failed on duplicate scripts and a duplicate stylesheet.
- `pnpm test-start-turbo
test/production/chunk-load-failure/chunk-load-failure.test.ts` (retry
path): 3/3
- `pnpm test-dev-turbo test/development/css-hmr-unmounted-chunk
test/development/app-dir/hmr-dynamic-component`: 7/7
- Snapshots regenerated with `UPDATE=1 cargo test -p turbopack-tests
--test snapshot`. Only the runtime change appears in the diff, and
132/132 pass on rerun.
- A Chromium harness compared the old selectors with the new lookups on
36 JS/CSS/unload cases. Results are identical except the `"` and `\`
cases, which now match literally.
- Sampled CPU profile on the issue's reproduction app at 4x CPU
throttling (median of 5): probe time drops from 106.9 to 40.8 ms at
about 4.3k elements, and from 215.9 to 51.6 ms at about 8.3k elements.

<!-- NEXT_JS_LLM -->


<!-- fleet 00169b97-050c-43e3-a74e-5c9141d0996e -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 0fc57c31
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Widgets } from './widgets/widgets'
export default function Page() {
return (
<main>
<Widgets />
</main>
)
}
'use client'
import styles from './styled-client.module.css'
export default function StyledClient() {
return (
<p id="styled-client" className={styles.text}>
styled client
</p>
)
}
'use client'
import styles from './styled-server.module.css'
export default function StyledServer() {
return (
<p id="styled-server" className={styles.text}>
styled server
</p>
)
}
'use client'
export default function WidgetA() {
return <p id="widget-a">widget a</p>
}
'use client'
export default function WidgetB() {
return <p id="widget-b">widget b</p>
}
'use client'
export default function WidgetC() {
return <p id="widget-c">widget c</p>
}
'use client'
import dynamic from 'next/dynamic'
// Each `dynamic()` import becomes its own async chunk. The server-rendered ones
// are already in the DOM as `<script>` / `<link>` tags when the runtime loads
// them during hydration; the `ssr: false` ones are inserted by the runtime.
const WidgetA = dynamic(() => import('./widget-a'))
const WidgetB = dynamic(() => import('./widget-b'))
const WidgetC = dynamic(() => import('./widget-c'))
const StyledServer = dynamic(() => import('./styled-server'))
const StyledClient = dynamic(() => import('./styled-client'), { ssr: false })
export function Widgets() {
return (
<>
<WidgetA />
<WidgetB />
<WidgetC />
<StyledServer />
<StyledClient />
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('dynamic-chunk-dedupe', () => {
const { next, isNextDeploy } = nextTestSetup({
files: __dirname,
// Keep the `deploymentId` from next.config.ts in effect (instead of the
// test harness's immutable assets) so chunk URLs carry `?dpl=`.
disableAutoSkewProtection: true,
})
it('should load every dynamic chunk exactly once', async () => {
const chunkRequests: string[] = []
const pageErrors: Error[] = []
const browser = await next.browser('/', {
beforePageLoad(page) {
page.on('request', (request) => {
const url = new URL(request.url())
if (
url.pathname.includes('/_next/static/') &&
/\.(js|css)$/.test(url.pathname)
) {
chunkRequests.push(url.pathname + url.search)
}
})
page.on('pageerror', (error: Error) => {
pageErrors.push(error)
})
},
})
await retry(async () => {
expect(await browser.elementByCss('#widget-a').text()).toBe('widget a')
expect(await browser.elementByCss('#widget-b').text()).toBe('widget b')
expect(await browser.elementByCss('#widget-c').text()).toBe('widget c')
expect(
await browser.elementByCss('#styled-server').getComputedCss('color')
).toBe('rgb(0, 128, 0)')
expect(
await browser.elementByCss('#styled-client').getComputedCss('color')
).toBe('rgb(0, 0, 255)')
})
expect(pageErrors).toEqual([])
// The chunk loader must recognize the `<script>` / `<link>` tags already in
// the DOM (including their query suffix) instead of requesting them again.
const counts = new Map<string, number>()
for (const request of chunkRequests) {
const pathname = request.split('?')[0]
counts.set(pathname, (counts.get(pathname) ?? 0) + 1)
}
const duplicates = [...counts].filter(([, count]) => count > 1)
expect(duplicates).toEqual([])
// A duplicate tag may be served from the memory cache without a new
// request, so also check the DOM directly.
const duplicateTags = await browser.eval(() => {
const seen = new Map<string, number>()
const elements = document.querySelectorAll(
'script[src*="/_next/static/"], link[rel=stylesheet][href*="/_next/static/"]'
)
for (const element of Array.from(elements)) {
const url = element.getAttribute('src') ?? element.getAttribute('href')
const key = `${element.tagName} ${url!.split('?')[0]}`
seen.set(key, (seen.get(key) ?? 0) + 1)
}
return [...seen].filter(([, count]) => count > 1)
})
expect(duplicateTags).toEqual([])
if (!isNextDeploy) {
// Deployments set their own deployment id.
expect(
chunkRequests.some((url) => url.includes('dpl=dynamic-chunk-dedupe'))
).toBe(true)
}
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
// Chunk URLs carry a `?dpl=` suffix, which the chunk loader must still match
// against the tags already in the DOM. Deployments set their own
// `NEXT_DEPLOYMENT_ID`, which the config must not contradict.
deploymentId: process.env.NEXT_DEPLOYMENT_ID || 'dynamic-chunk-dedupe',
}
export default nextConfig
...@@ -21,14 +21,9 @@ let DEV_BACKEND: DevRuntimeBackend ...@@ -21,14 +21,9 @@ let DEV_BACKEND: DevRuntimeBackend
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0] const baseChunkUrl = chunkUrl.split('?')[0]
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedBaseChunkUrl = decodeURI(baseChunkUrl)
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const links = document.querySelectorAll( for (const link of findChunkLinks(baseChunkUrl)) {
`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`
)
for (const link of Array.from(links)) {
link.remove() link.remove()
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
...@@ -36,10 +31,7 @@ let DEV_BACKEND: DevRuntimeBackend ...@@ -36,10 +31,7 @@ let DEV_BACKEND: DevRuntimeBackend
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from the DOM to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
const scripts = document.querySelectorAll( for (const script of findChunkScripts(baseChunkUrl)) {
`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`
)
for (const script of Array.from(scripts)) {
script.remove() script.remove()
} }
} else { } else {
...@@ -57,10 +49,7 @@ let DEV_BACKEND: DevRuntimeBackend ...@@ -57,10 +49,7 @@ let DEV_BACKEND: DevRuntimeBackend
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0] const baseChunkUrl = chunkUrl.split('?')[0]
const decodedBaseChunkUrl = decodeURI(baseChunkUrl) const previousLinks = findChunkStylesheets(baseChunkUrl)
const previousLinks = document.querySelectorAll(
`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`
)
const link = document.createElement('link') const link = document.createElement('link')
link.rel = 'stylesheet' link.rel = 'stylesheet'
...@@ -98,8 +87,7 @@ let DEV_BACKEND: DevRuntimeBackend ...@@ -98,8 +87,7 @@ let DEV_BACKEND: DevRuntimeBackend
// First load the new CSS, then remove the old ones. This prevents visible // First load the new CSS, then remove the old ones. This prevents visible
// flickering that would happen in-between removing the previous CSS and // flickering that would happen in-between removing the previous CSS and
// loading the new one. // loading the new one.
for (const previousLink of Array.from(previousLinks)) for (const previousLink of previousLinks) previousLink.remove()
previousLink.remove()
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
......
...@@ -17,6 +17,82 @@ function getAssetSuffixFromScriptSrc() { ...@@ -17,6 +17,82 @@ function getAssetSuffixFromScriptSrc() {
return qi >= 0 ? src.slice(qi) : '' return qi >= 0 ? src.slice(qi) : ''
} }
/**
* Whether a `src` / `href` attribute value refers to `url`: either exactly, or
* with an additional query string (e.g. `?dpl=...`). Also matches the decoded
* form of `url`.
*
* TODO(PACK-2140): drop the decoded variant once all filenames are guaranteed
* to be escaped.
*/
function matchesChunkUrl(
value: string | null,
url: string,
decodedUrl: string
): boolean {
return (
value != null &&
(value === url ||
value.startsWith(url + '?') ||
value === decodedUrl ||
value.startsWith(decodedUrl + '?'))
)
}
// These lookups iterate the tag collection and compare attribute values as
// plain strings. A document-wide `querySelectorAll` with attribute selectors
// costs time proportional to the size of the whole DOM on every call, and
// would need the URL to be CSS-escaped.
/**
* Returns all `<script>` elements in the document whose `src` refers to `url`.
*/
function findChunkScripts(url: string): HTMLScriptElement[] {
const decodedUrl = decodeURI(url)
const scripts = document.getElementsByTagName('script')
const result: HTMLScriptElement[] = []
for (let i = 0; i < scripts.length; i++) {
const script = scripts[i]
if (matchesChunkUrl(script.getAttribute('src'), url, decodedUrl)) {
result.push(script)
}
}
return result
}
/**
* Returns all `<link>` elements in the document whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned.
*/
function findChunkLinks(
url: string,
stylesheetsOnly: boolean = false
): HTMLLinkElement[] {
const decodedUrl = decodeURI(url)
const links = document.getElementsByTagName('link')
const result: HTMLLinkElement[] = []
for (let i = 0; i < links.length; i++) {
const link = links[i]
if (
(!stylesheetsOnly ||
link.getAttribute('rel')?.toLowerCase() === 'stylesheet') &&
matchesChunkUrl(link.getAttribute('href'), url, decodedUrl)
) {
result.push(link)
}
}
return result
}
/**
* Returns all `<link rel=stylesheet>` elements in the document whose `href`
* refers to `url`.
*/
function findChunkStylesheets(url: string): HTMLLinkElement[] {
return findChunkLinks(url, true)
}
type ChunkResolver = { type ChunkResolver = {
resolved: boolean resolved: boolean
loadingStarted: boolean loadingStarted: boolean
...@@ -215,13 +291,8 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map() ...@@ -215,13 +291,8 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
) )
} }
} else { } else {
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedChunkUrl = decodeURI(chunkUrl)
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const previousLinks = document.querySelectorAll( const previousLinks = findChunkStylesheets(chunkUrl)
`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`
)
if (previousLinks.length > 0) { if (previousLinks.length > 0) {
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
...@@ -252,11 +323,9 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map() ...@@ -252,11 +323,9 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
document.head.appendChild(createLink()) document.head.appendChild(createLink())
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll( const previousScripts = findChunkScripts(chunkUrl)
`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`
)
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
for (const script of Array.from(previousScripts)) { for (const script of previousScripts) {
script.addEventListener( script.addEventListener(
'error', 'error',
() => { () => {
......
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="bdc42f8b-8d80-c59c-9d6a-5809b45f190d")}catch(e){}}(); ;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="ef69da0e-1e88-28eb-53b3-a456eef8bf15")}catch(e){}}();
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/0rv8_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js", "output/0rv8_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js",
{"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvsq4xsbk.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvsq4xsbk.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
...@@ -2283,6 +2283,56 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2283,6 +2283,56 @@ function getAssetSuffixFromScriptSrc() {
const qi = src.indexOf('?'); const qi = src.indexOf('?');
return qi >= 0 ? src.slice(qi) : ''; return qi >= 0 ? src.slice(qi) : '';
} }
/**
* Whether a `src` / `href` attribute value refers to `url`: either exactly, or
* with an additional query string (e.g. `?dpl=...`). Also matches the decoded
* form of `url`.
*
* TODO(PACK-2140): drop the decoded variant once all filenames are guaranteed
* to be escaped.
*/ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
}
// These lookups iterate the tag collection and compare attribute values as
// plain strings. A document-wide `querySelectorAll` with attribute selectors
// costs time proportional to the size of the whole DOM on every call, and
// would need the URL to be CSS-escaped.
/**
* Returns all `<script>` elements in the document whose `src` refers to `url`.
*/ function findChunkScripts(url) {
const decodedUrl = decodeURI(url);
const scripts = document.getElementsByTagName('script');
const result = [];
for(let i = 0; i < scripts.length; i++){
const script = scripts[i];
if (matchesChunkUrl(script.getAttribute('src'), url, decodedUrl)) {
result.push(script);
}
}
return result;
}
/**
* Returns all `<link>` elements in the document whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url, stylesheetsOnly = false) {
const decodedUrl = decodeURI(url);
const links = document.getElementsByTagName('link');
const result = [];
for(let i = 0; i < links.length; i++){
const link = links[i];
if ((!stylesheetsOnly || link.getAttribute('rel')?.toLowerCase() === 'stylesheet') && matchesChunkUrl(link.getAttribute('href'), url, decodedUrl)) {
result.push(link);
}
}
return result;
}
/**
* Returns all `<link rel=stylesheet>` elements in the document whose `href`
* refers to `url`.
*/ function findChunkStylesheets(url) {
return findChunkLinks(url, true);
}
let BACKEND; let BACKEND;
/** /**
* Maps chunk paths to the corresponding resolver. * Maps chunk paths to the corresponding resolver.
...@@ -2422,10 +2472,8 @@ let BACKEND; ...@@ -2422,10 +2472,8 @@ let BACKEND;
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
} else { } else {
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedChunkUrl = decodeURI(chunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); const previousLinks = findChunkStylesheets(chunkUrl);
if (previousLinks.length > 0) { if (previousLinks.length > 0) {
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
...@@ -2454,9 +2502,9 @@ let BACKEND; ...@@ -2454,9 +2502,9 @@ let BACKEND;
document.head.appendChild(createLink()); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); const previousScripts = findChunkScripts(chunkUrl);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
for (const script of Array.from(previousScripts)){ for (const script of previousScripts){
script.addEventListener('error', ()=>{ script.addEventListener('error', ()=>{
// Drop the failed tag so a retry can re-add it cleanly. // Drop the failed tag so a retry can re-add it cleanly.
script.remove(); script.remove();
...@@ -2505,11 +2553,8 @@ let DEV_BACKEND; ...@@ -2505,11 +2553,8 @@ let DEV_BACKEND;
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0]; const baseChunkUrl = chunkUrl.split('?')[0];
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedBaseChunkUrl = decodeURI(baseChunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const links = document.querySelectorAll(`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`); for (const link of findChunkLinks(baseChunkUrl)){
for (const link of Array.from(links)){
link.remove(); link.remove();
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
...@@ -2517,8 +2562,7 @@ let DEV_BACKEND; ...@@ -2517,8 +2562,7 @@ let DEV_BACKEND;
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from the DOM to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
const scripts = document.querySelectorAll(`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`); for (const script of findChunkScripts(baseChunkUrl)){
for (const script of Array.from(scripts)){
script.remove(); script.remove();
} }
} else { } else {
...@@ -2534,8 +2578,7 @@ let DEV_BACKEND; ...@@ -2534,8 +2578,7 @@ let DEV_BACKEND;
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0]; const baseChunkUrl = chunkUrl.split('?')[0];
const decodedBaseChunkUrl = decodeURI(baseChunkUrl); const previousLinks = findChunkStylesheets(baseChunkUrl);
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`);
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
...@@ -2565,7 +2608,7 @@ let DEV_BACKEND; ...@@ -2565,7 +2608,7 @@ let DEV_BACKEND;
// First load the new CSS, then remove the old ones. This prevents visible // First load the new CSS, then remove the old ones. This prevents visible
// flickering that would happen in-between removing the previous CSS and // flickering that would happen in-between removing the previous CSS and
// loading the new one. // loading the new one.
for (const previousLink of Array.from(previousLinks))previousLink.remove(); for (const previousLink of previousLinks)previousLink.remove();
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolve(); resolve();
...@@ -2610,5 +2653,5 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2610,5 +2653,5 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# debugId=bdc42f8b-8d80-c59c-9d6a-5809b45f190d //# debugId=ef69da0e-1e88-28eb-53b3-a456eef8bf15
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map //# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map
\ No newline at end of file
...@@ -2282,6 +2282,56 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2282,6 +2282,56 @@ function getAssetSuffixFromScriptSrc() {
const qi = src.indexOf('?'); const qi = src.indexOf('?');
return qi >= 0 ? src.slice(qi) : ''; return qi >= 0 ? src.slice(qi) : '';
} }
/**
* Whether a `src` / `href` attribute value refers to `url`: either exactly, or
* with an additional query string (e.g. `?dpl=...`). Also matches the decoded
* form of `url`.
*
* TODO(PACK-2140): drop the decoded variant once all filenames are guaranteed
* to be escaped.
*/ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
}
// These lookups iterate the tag collection and compare attribute values as
// plain strings. A document-wide `querySelectorAll` with attribute selectors
// costs time proportional to the size of the whole DOM on every call, and
// would need the URL to be CSS-escaped.
/**
* Returns all `<script>` elements in the document whose `src` refers to `url`.
*/ function findChunkScripts(url) {
const decodedUrl = decodeURI(url);
const scripts = document.getElementsByTagName('script');
const result = [];
for(let i = 0; i < scripts.length; i++){
const script = scripts[i];
if (matchesChunkUrl(script.getAttribute('src'), url, decodedUrl)) {
result.push(script);
}
}
return result;
}
/**
* Returns all `<link>` elements in the document whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url, stylesheetsOnly = false) {
const decodedUrl = decodeURI(url);
const links = document.getElementsByTagName('link');
const result = [];
for(let i = 0; i < links.length; i++){
const link = links[i];
if ((!stylesheetsOnly || link.getAttribute('rel')?.toLowerCase() === 'stylesheet') && matchesChunkUrl(link.getAttribute('href'), url, decodedUrl)) {
result.push(link);
}
}
return result;
}
/**
* Returns all `<link rel=stylesheet>` elements in the document whose `href`
* refers to `url`.
*/ function findChunkStylesheets(url) {
return findChunkLinks(url, true);
}
let BACKEND; let BACKEND;
/** /**
* Maps chunk paths to the corresponding resolver. * Maps chunk paths to the corresponding resolver.
...@@ -2421,10 +2471,8 @@ let BACKEND; ...@@ -2421,10 +2471,8 @@ let BACKEND;
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
} else { } else {
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedChunkUrl = decodeURI(chunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); const previousLinks = findChunkStylesheets(chunkUrl);
if (previousLinks.length > 0) { if (previousLinks.length > 0) {
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
...@@ -2453,9 +2501,9 @@ let BACKEND; ...@@ -2453,9 +2501,9 @@ let BACKEND;
document.head.appendChild(createLink()); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); const previousScripts = findChunkScripts(chunkUrl);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
for (const script of Array.from(previousScripts)){ for (const script of previousScripts){
script.addEventListener('error', ()=>{ script.addEventListener('error', ()=>{
// Drop the failed tag so a retry can re-add it cleanly. // Drop the failed tag so a retry can re-add it cleanly.
script.remove(); script.remove();
...@@ -2504,11 +2552,8 @@ let DEV_BACKEND; ...@@ -2504,11 +2552,8 @@ let DEV_BACKEND;
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0]; const baseChunkUrl = chunkUrl.split('?')[0];
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedBaseChunkUrl = decodeURI(baseChunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const links = document.querySelectorAll(`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`); for (const link of findChunkLinks(baseChunkUrl)){
for (const link of Array.from(links)){
link.remove(); link.remove();
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
...@@ -2516,8 +2561,7 @@ let DEV_BACKEND; ...@@ -2516,8 +2561,7 @@ let DEV_BACKEND;
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from the DOM to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
const scripts = document.querySelectorAll(`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`); for (const script of findChunkScripts(baseChunkUrl)){
for (const script of Array.from(scripts)){
script.remove(); script.remove();
} }
} else { } else {
...@@ -2533,8 +2577,7 @@ let DEV_BACKEND; ...@@ -2533,8 +2577,7 @@ let DEV_BACKEND;
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0]; const baseChunkUrl = chunkUrl.split('?')[0];
const decodedBaseChunkUrl = decodeURI(baseChunkUrl); const previousLinks = findChunkStylesheets(baseChunkUrl);
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`);
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
...@@ -2564,7 +2607,7 @@ let DEV_BACKEND; ...@@ -2564,7 +2607,7 @@ let DEV_BACKEND;
// First load the new CSS, then remove the old ones. This prevents visible // First load the new CSS, then remove the old ones. This prevents visible
// flickering that would happen in-between removing the previous CSS and // flickering that would happen in-between removing the previous CSS and
// loading the new one. // loading the new one.
for (const previousLink of Array.from(previousLinks))previousLink.remove(); for (const previousLink of previousLinks)previousLink.remove();
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolve(); resolve();
......
...@@ -1765,6 +1765,58 @@ function getAssetSuffixFromScriptSrc() { ...@@ -1765,6 +1765,58 @@ function getAssetSuffixFromScriptSrc() {
var qi = src.indexOf('?'); var qi = src.indexOf('?');
return qi >= 0 ? src.slice(qi) : ''; return qi >= 0 ? src.slice(qi) : '';
} }
/**
* Whether a `src` / `href` attribute value refers to `url`: either exactly, or
* with an additional query string (e.g. `?dpl=...`). Also matches the decoded
* form of `url`.
*
* TODO(PACK-2140): drop the decoded variant once all filenames are guaranteed
* to be escaped.
*/ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
}
// These lookups iterate the tag collection and compare attribute values as
// plain strings. A document-wide `querySelectorAll` with attribute selectors
// costs time proportional to the size of the whole DOM on every call, and
// would need the URL to be CSS-escaped.
/**
* Returns all `<script>` elements in the document whose `src` refers to `url`.
*/ function findChunkScripts(url) {
var decodedUrl = decodeURI(url);
var scripts = document.getElementsByTagName('script');
var result = [];
for(var i = 0; i < scripts.length; i++){
var script = scripts[i];
if (matchesChunkUrl(script.getAttribute('src'), url, decodedUrl)) {
result.push(script);
}
}
return result;
}
/**
* Returns all `<link>` elements in the document whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url) {
var stylesheetsOnly = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
var decodedUrl = decodeURI(url);
var links = document.getElementsByTagName('link');
var result = [];
for(var i = 0; i < links.length; i++){
var _link_getAttribute;
var link = links[i];
if ((!stylesheetsOnly || ((_link_getAttribute = link.getAttribute('rel')) === null || _link_getAttribute === void 0 ? void 0 : _link_getAttribute.toLowerCase()) === 'stylesheet') && matchesChunkUrl(link.getAttribute('href'), url, decodedUrl)) {
result.push(link);
}
}
return result;
}
/**
* Returns all `<link rel=stylesheet>` elements in the document whose `href`
* refers to `url`.
*/ function findChunkStylesheets(url) {
return findChunkLinks(url, true);
}
var BACKEND; var BACKEND;
/** /**
* Maps chunk paths to the corresponding resolver. * Maps chunk paths to the corresponding resolver.
...@@ -1956,10 +2008,8 @@ var BACKEND; ...@@ -1956,10 +2008,8 @@ var BACKEND;
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
} else { } else {
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
var decodedChunkUrl = decodeURI(chunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
var previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); var previousLinks = findChunkStylesheets(chunkUrl);
if (previousLinks.length > 0) { if (previousLinks.length > 0) {
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
...@@ -1990,7 +2040,7 @@ var BACKEND; ...@@ -1990,7 +2040,7 @@ var BACKEND;
document.head.appendChild(createLink()); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
var previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); var previousScripts = findChunkScripts(chunkUrl);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined; var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try { try {
...@@ -2004,7 +2054,7 @@ var BACKEND; ...@@ -2004,7 +2054,7 @@ var BACKEND;
once: true once: true
}); });
}; };
for(var _iterator = Array.from(previousScripts)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop(); for(var _iterator = previousScripts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
} catch (err) { } catch (err) {
_didIteratorError = true; _didIteratorError = true;
_iteratorError = err; _iteratorError = err;
......
...@@ -2282,6 +2282,56 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2282,6 +2282,56 @@ function getAssetSuffixFromScriptSrc() {
const qi = src.indexOf('?'); const qi = src.indexOf('?');
return qi >= 0 ? src.slice(qi) : ''; return qi >= 0 ? src.slice(qi) : '';
} }
/**
* Whether a `src` / `href` attribute value refers to `url`: either exactly, or
* with an additional query string (e.g. `?dpl=...`). Also matches the decoded
* form of `url`.
*
* TODO(PACK-2140): drop the decoded variant once all filenames are guaranteed
* to be escaped.
*/ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
}
// These lookups iterate the tag collection and compare attribute values as
// plain strings. A document-wide `querySelectorAll` with attribute selectors
// costs time proportional to the size of the whole DOM on every call, and
// would need the URL to be CSS-escaped.
/**
* Returns all `<script>` elements in the document whose `src` refers to `url`.
*/ function findChunkScripts(url) {
const decodedUrl = decodeURI(url);
const scripts = document.getElementsByTagName('script');
const result = [];
for(let i = 0; i < scripts.length; i++){
const script = scripts[i];
if (matchesChunkUrl(script.getAttribute('src'), url, decodedUrl)) {
result.push(script);
}
}
return result;
}
/**
* Returns all `<link>` elements in the document whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url, stylesheetsOnly = false) {
const decodedUrl = decodeURI(url);
const links = document.getElementsByTagName('link');
const result = [];
for(let i = 0; i < links.length; i++){
const link = links[i];
if ((!stylesheetsOnly || link.getAttribute('rel')?.toLowerCase() === 'stylesheet') && matchesChunkUrl(link.getAttribute('href'), url, decodedUrl)) {
result.push(link);
}
}
return result;
}
/**
* Returns all `<link rel=stylesheet>` elements in the document whose `href`
* refers to `url`.
*/ function findChunkStylesheets(url) {
return findChunkLinks(url, true);
}
let BACKEND; let BACKEND;
/** /**
* Maps chunk paths to the corresponding resolver. * Maps chunk paths to the corresponding resolver.
...@@ -2421,10 +2471,8 @@ let BACKEND; ...@@ -2421,10 +2471,8 @@ let BACKEND;
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
} else { } else {
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedChunkUrl = decodeURI(chunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); const previousLinks = findChunkStylesheets(chunkUrl);
if (previousLinks.length > 0) { if (previousLinks.length > 0) {
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
...@@ -2453,9 +2501,9 @@ let BACKEND; ...@@ -2453,9 +2501,9 @@ let BACKEND;
document.head.appendChild(createLink()); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); const previousScripts = findChunkScripts(chunkUrl);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
for (const script of Array.from(previousScripts)){ for (const script of previousScripts){
script.addEventListener('error', ()=>{ script.addEventListener('error', ()=>{
// Drop the failed tag so a retry can re-add it cleanly. // Drop the failed tag so a retry can re-add it cleanly.
script.remove(); script.remove();
...@@ -2504,11 +2552,8 @@ let DEV_BACKEND; ...@@ -2504,11 +2552,8 @@ let DEV_BACKEND;
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0]; const baseChunkUrl = chunkUrl.split('?')[0];
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedBaseChunkUrl = decodeURI(baseChunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const links = document.querySelectorAll(`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`); for (const link of findChunkLinks(baseChunkUrl)){
for (const link of Array.from(links)){
link.remove(); link.remove();
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
...@@ -2516,8 +2561,7 @@ let DEV_BACKEND; ...@@ -2516,8 +2561,7 @@ let DEV_BACKEND;
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from the DOM to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
const scripts = document.querySelectorAll(`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`); for (const script of findChunkScripts(baseChunkUrl)){
for (const script of Array.from(scripts)){
script.remove(); script.remove();
} }
} else { } else {
...@@ -2533,8 +2577,7 @@ let DEV_BACKEND; ...@@ -2533,8 +2577,7 @@ let DEV_BACKEND;
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0]; const baseChunkUrl = chunkUrl.split('?')[0];
const decodedBaseChunkUrl = decodeURI(baseChunkUrl); const previousLinks = findChunkStylesheets(baseChunkUrl);
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`);
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
...@@ -2564,7 +2607,7 @@ let DEV_BACKEND; ...@@ -2564,7 +2607,7 @@ let DEV_BACKEND;
// First load the new CSS, then remove the old ones. This prevents visible // First load the new CSS, then remove the old ones. This prevents visible
// flickering that would happen in-between removing the previous CSS and // flickering that would happen in-between removing the previous CSS and
// loading the new one. // loading the new one.
for (const previousLink of Array.from(previousLinks))previousLink.remove(); for (const previousLink of previousLinks)previousLink.remove();
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolve(); resolve();
......
...@@ -2282,6 +2282,56 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2282,6 +2282,56 @@ function getAssetSuffixFromScriptSrc() {
const qi = src.indexOf('?'); const qi = src.indexOf('?');
return qi >= 0 ? src.slice(qi) : ''; return qi >= 0 ? src.slice(qi) : '';
} }
/**
* Whether a `src` / `href` attribute value refers to `url`: either exactly, or
* with an additional query string (e.g. `?dpl=...`). Also matches the decoded
* form of `url`.
*
* TODO(PACK-2140): drop the decoded variant once all filenames are guaranteed
* to be escaped.
*/ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
}
// These lookups iterate the tag collection and compare attribute values as
// plain strings. A document-wide `querySelectorAll` with attribute selectors
// costs time proportional to the size of the whole DOM on every call, and
// would need the URL to be CSS-escaped.
/**
* Returns all `<script>` elements in the document whose `src` refers to `url`.
*/ function findChunkScripts(url) {
const decodedUrl = decodeURI(url);
const scripts = document.getElementsByTagName('script');
const result = [];
for(let i = 0; i < scripts.length; i++){
const script = scripts[i];
if (matchesChunkUrl(script.getAttribute('src'), url, decodedUrl)) {
result.push(script);
}
}
return result;
}
/**
* Returns all `<link>` elements in the document whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url, stylesheetsOnly = false) {
const decodedUrl = decodeURI(url);
const links = document.getElementsByTagName('link');
const result = [];
for(let i = 0; i < links.length; i++){
const link = links[i];
if ((!stylesheetsOnly || link.getAttribute('rel')?.toLowerCase() === 'stylesheet') && matchesChunkUrl(link.getAttribute('href'), url, decodedUrl)) {
result.push(link);
}
}
return result;
}
/**
* Returns all `<link rel=stylesheet>` elements in the document whose `href`
* refers to `url`.
*/ function findChunkStylesheets(url) {
return findChunkLinks(url, true);
}
let BACKEND; let BACKEND;
/** /**
* Maps chunk paths to the corresponding resolver. * Maps chunk paths to the corresponding resolver.
...@@ -2421,10 +2471,8 @@ let BACKEND; ...@@ -2421,10 +2471,8 @@ let BACKEND;
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
} else { } else {
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedChunkUrl = decodeURI(chunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); const previousLinks = findChunkStylesheets(chunkUrl);
if (previousLinks.length > 0) { if (previousLinks.length > 0) {
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
...@@ -2453,9 +2501,9 @@ let BACKEND; ...@@ -2453,9 +2501,9 @@ let BACKEND;
document.head.appendChild(createLink()); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); const previousScripts = findChunkScripts(chunkUrl);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
for (const script of Array.from(previousScripts)){ for (const script of previousScripts){
script.addEventListener('error', ()=>{ script.addEventListener('error', ()=>{
// Drop the failed tag so a retry can re-add it cleanly. // Drop the failed tag so a retry can re-add it cleanly.
script.remove(); script.remove();
...@@ -2504,11 +2552,8 @@ let DEV_BACKEND; ...@@ -2504,11 +2552,8 @@ let DEV_BACKEND;
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0]; const baseChunkUrl = chunkUrl.split('?')[0];
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedBaseChunkUrl = decodeURI(baseChunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const links = document.querySelectorAll(`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`); for (const link of findChunkLinks(baseChunkUrl)){
for (const link of Array.from(links)){
link.remove(); link.remove();
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
...@@ -2516,8 +2561,7 @@ let DEV_BACKEND; ...@@ -2516,8 +2561,7 @@ let DEV_BACKEND;
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from the DOM to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
const scripts = document.querySelectorAll(`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`); for (const script of findChunkScripts(baseChunkUrl)){
for (const script of Array.from(scripts)){
script.remove(); script.remove();
} }
} else { } else {
...@@ -2533,8 +2577,7 @@ let DEV_BACKEND; ...@@ -2533,8 +2577,7 @@ let DEV_BACKEND;
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0]; const baseChunkUrl = chunkUrl.split('?')[0];
const decodedBaseChunkUrl = decodeURI(baseChunkUrl); const previousLinks = findChunkStylesheets(baseChunkUrl);
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`);
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
...@@ -2564,7 +2607,7 @@ let DEV_BACKEND; ...@@ -2564,7 +2607,7 @@ let DEV_BACKEND;
// First load the new CSS, then remove the old ones. This prevents visible // First load the new CSS, then remove the old ones. This prevents visible
// flickering that would happen in-between removing the previous CSS and // flickering that would happen in-between removing the previous CSS and
// loading the new one. // loading the new one.
for (const previousLink of Array.from(previousLinks))previousLink.remove(); for (const previousLink of previousLinks)previousLink.remove();
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolve(); resolve();
......
...@@ -2282,6 +2282,56 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2282,6 +2282,56 @@ function getAssetSuffixFromScriptSrc() {
const qi = src.indexOf('?'); const qi = src.indexOf('?');
return qi >= 0 ? src.slice(qi) : ''; return qi >= 0 ? src.slice(qi) : '';
} }
/**
* Whether a `src` / `href` attribute value refers to `url`: either exactly, or
* with an additional query string (e.g. `?dpl=...`). Also matches the decoded
* form of `url`.
*
* TODO(PACK-2140): drop the decoded variant once all filenames are guaranteed
* to be escaped.
*/ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
}
// These lookups iterate the tag collection and compare attribute values as
// plain strings. A document-wide `querySelectorAll` with attribute selectors
// costs time proportional to the size of the whole DOM on every call, and
// would need the URL to be CSS-escaped.
/**
* Returns all `<script>` elements in the document whose `src` refers to `url`.
*/ function findChunkScripts(url) {
const decodedUrl = decodeURI(url);
const scripts = document.getElementsByTagName('script');
const result = [];
for(let i = 0; i < scripts.length; i++){
const script = scripts[i];
if (matchesChunkUrl(script.getAttribute('src'), url, decodedUrl)) {
result.push(script);
}
}
return result;
}
/**
* Returns all `<link>` elements in the document whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url, stylesheetsOnly = false) {
const decodedUrl = decodeURI(url);
const links = document.getElementsByTagName('link');
const result = [];
for(let i = 0; i < links.length; i++){
const link = links[i];
if ((!stylesheetsOnly || link.getAttribute('rel')?.toLowerCase() === 'stylesheet') && matchesChunkUrl(link.getAttribute('href'), url, decodedUrl)) {
result.push(link);
}
}
return result;
}
/**
* Returns all `<link rel=stylesheet>` elements in the document whose `href`
* refers to `url`.
*/ function findChunkStylesheets(url) {
return findChunkLinks(url, true);
}
let BACKEND; let BACKEND;
/** /**
* Maps chunk paths to the corresponding resolver. * Maps chunk paths to the corresponding resolver.
...@@ -2421,10 +2471,8 @@ let BACKEND; ...@@ -2421,10 +2471,8 @@ let BACKEND;
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
} else { } else {
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedChunkUrl = decodeURI(chunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); const previousLinks = findChunkStylesheets(chunkUrl);
if (previousLinks.length > 0) { if (previousLinks.length > 0) {
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
...@@ -2453,9 +2501,9 @@ let BACKEND; ...@@ -2453,9 +2501,9 @@ let BACKEND;
document.head.appendChild(createLink()); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); const previousScripts = findChunkScripts(chunkUrl);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
for (const script of Array.from(previousScripts)){ for (const script of previousScripts){
script.addEventListener('error', ()=>{ script.addEventListener('error', ()=>{
// Drop the failed tag so a retry can re-add it cleanly. // Drop the failed tag so a retry can re-add it cleanly.
script.remove(); script.remove();
...@@ -2504,11 +2552,8 @@ let DEV_BACKEND; ...@@ -2504,11 +2552,8 @@ let DEV_BACKEND;
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0]; const baseChunkUrl = chunkUrl.split('?')[0];
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedBaseChunkUrl = decodeURI(baseChunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const links = document.querySelectorAll(`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`); for (const link of findChunkLinks(baseChunkUrl)){
for (const link of Array.from(links)){
link.remove(); link.remove();
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
...@@ -2516,8 +2561,7 @@ let DEV_BACKEND; ...@@ -2516,8 +2561,7 @@ let DEV_BACKEND;
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from the DOM to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
const scripts = document.querySelectorAll(`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`); for (const script of findChunkScripts(baseChunkUrl)){
for (const script of Array.from(scripts)){
script.remove(); script.remove();
} }
} else { } else {
...@@ -2533,8 +2577,7 @@ let DEV_BACKEND; ...@@ -2533,8 +2577,7 @@ let DEV_BACKEND;
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0]; const baseChunkUrl = chunkUrl.split('?')[0];
const decodedBaseChunkUrl = decodeURI(baseChunkUrl); const previousLinks = findChunkStylesheets(baseChunkUrl);
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`);
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
...@@ -2564,7 +2607,7 @@ let DEV_BACKEND; ...@@ -2564,7 +2607,7 @@ let DEV_BACKEND;
// First load the new CSS, then remove the old ones. This prevents visible // First load the new CSS, then remove the old ones. This prevents visible
// flickering that would happen in-between removing the previous CSS and // flickering that would happen in-between removing the previous CSS and
// loading the new one. // loading the new one.
for (const previousLink of Array.from(previousLinks))previousLink.remove(); for (const previousLink of previousLinks)previousLink.remove();
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolve(); resolve();
......
...@@ -2282,6 +2282,56 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2282,6 +2282,56 @@ function getAssetSuffixFromScriptSrc() {
const qi = src.indexOf('?'); const qi = src.indexOf('?');
return qi >= 0 ? src.slice(qi) : ''; return qi >= 0 ? src.slice(qi) : '';
} }
/**
* Whether a `src` / `href` attribute value refers to `url`: either exactly, or
* with an additional query string (e.g. `?dpl=...`). Also matches the decoded
* form of `url`.
*
* TODO(PACK-2140): drop the decoded variant once all filenames are guaranteed
* to be escaped.
*/ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
}
// These lookups iterate the tag collection and compare attribute values as
// plain strings. A document-wide `querySelectorAll` with attribute selectors
// costs time proportional to the size of the whole DOM on every call, and
// would need the URL to be CSS-escaped.
/**
* Returns all `<script>` elements in the document whose `src` refers to `url`.
*/ function findChunkScripts(url) {
const decodedUrl = decodeURI(url);
const scripts = document.getElementsByTagName('script');
const result = [];
for(let i = 0; i < scripts.length; i++){
const script = scripts[i];
if (matchesChunkUrl(script.getAttribute('src'), url, decodedUrl)) {
result.push(script);
}
}
return result;
}
/**
* Returns all `<link>` elements in the document whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url, stylesheetsOnly = false) {
const decodedUrl = decodeURI(url);
const links = document.getElementsByTagName('link');
const result = [];
for(let i = 0; i < links.length; i++){
const link = links[i];
if ((!stylesheetsOnly || link.getAttribute('rel')?.toLowerCase() === 'stylesheet') && matchesChunkUrl(link.getAttribute('href'), url, decodedUrl)) {
result.push(link);
}
}
return result;
}
/**
* Returns all `<link rel=stylesheet>` elements in the document whose `href`
* refers to `url`.
*/ function findChunkStylesheets(url) {
return findChunkLinks(url, true);
}
let BACKEND; let BACKEND;
/** /**
* Maps chunk paths to the corresponding resolver. * Maps chunk paths to the corresponding resolver.
...@@ -2421,10 +2471,8 @@ let BACKEND; ...@@ -2421,10 +2471,8 @@ let BACKEND;
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
} else { } else {
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedChunkUrl = decodeURI(chunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); const previousLinks = findChunkStylesheets(chunkUrl);
if (previousLinks.length > 0) { if (previousLinks.length > 0) {
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
...@@ -2453,9 +2501,9 @@ let BACKEND; ...@@ -2453,9 +2501,9 @@ let BACKEND;
document.head.appendChild(createLink()); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); const previousScripts = findChunkScripts(chunkUrl);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
for (const script of Array.from(previousScripts)){ for (const script of previousScripts){
script.addEventListener('error', ()=>{ script.addEventListener('error', ()=>{
// Drop the failed tag so a retry can re-add it cleanly. // Drop the failed tag so a retry can re-add it cleanly.
script.remove(); script.remove();
...@@ -2504,11 +2552,8 @@ let DEV_BACKEND; ...@@ -2504,11 +2552,8 @@ let DEV_BACKEND;
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0]; const baseChunkUrl = chunkUrl.split('?')[0];
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedBaseChunkUrl = decodeURI(baseChunkUrl);
if (isCss(chunkUrl)) { if (isCss(chunkUrl)) {
const links = document.querySelectorAll(`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`); for (const link of findChunkLinks(baseChunkUrl)){
for (const link of Array.from(links)){
link.remove(); link.remove();
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
...@@ -2516,8 +2561,7 @@ let DEV_BACKEND; ...@@ -2516,8 +2561,7 @@ let DEV_BACKEND;
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from the DOM to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
const scripts = document.querySelectorAll(`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`); for (const script of findChunkScripts(baseChunkUrl)){
for (const script of Array.from(scripts)){
script.remove(); script.remove();
} }
} else { } else {
...@@ -2533,8 +2577,7 @@ let DEV_BACKEND; ...@@ -2533,8 +2577,7 @@ let DEV_BACKEND;
// Strip query string so we match links regardless of cache-busting // Strip query string so we match links regardless of cache-busting
// params (e.g. ?ts=) that may differ between HMR updates. // params (e.g. ?ts=) that may differ between HMR updates.
const baseChunkUrl = chunkUrl.split('?')[0]; const baseChunkUrl = chunkUrl.split('?')[0];
const decodedBaseChunkUrl = decodeURI(baseChunkUrl); const previousLinks = findChunkStylesheets(baseChunkUrl);
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`);
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
...@@ -2564,7 +2607,7 @@ let DEV_BACKEND; ...@@ -2564,7 +2607,7 @@ let DEV_BACKEND;
// First load the new CSS, then remove the old ones. This prevents visible // First load the new CSS, then remove the old ones. This prevents visible
// flickering that would happen in-between removing the previous CSS and // flickering that would happen in-between removing the previous CSS and
// loading the new one. // loading the new one.
for (const previousLink of Array.from(previousLinks))previousLink.remove(); for (const previousLink of previousLinks)previousLink.remove();
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolve(); resolve();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment