Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ export type CSSWalkEntry =
/** Normalized: lowercased, whitespace collapsed, e.g. `stylesheet alternate`. */
rel: string
disabled?: string
media?: string
/** The stylesheet text, only for a loaded link that had no recorded network response
* (cache hit, service worker, late tracking), obtained by fetching it again. */
fetched_css?: string
}
| { type: 'import'; href: string; media: string }
| { type: 'inline'; css: string }
| { type: 'adopted'; css: string }
| { type: 'style'; css: string }
Expand Down Expand Up @@ -65,7 +67,36 @@ export async function read_page_css(
}
}

// Follows the @import rules of a sheet and the sheets they load. A cross-origin sheet does
// not expose its rules, so a condition inside one is not found.
function visit_imports(sheet: CSSStyleSheet) {
let rules: CSSRuleList
try {
rules = sheet.cssRules
} catch {
return
}
for (const rule of rules) {
if (!(rule instanceof CSSImportRule)) {
continue
}
const media = rule.media.mediaText
if (media) {
const href =
rule.styleSheet?.href ?? new URL(rule.href, sheet.href ?? document.baseURI).href
found.push({ type: 'import', href, media })
}
if (rule.styleSheet) {
visit_imports(rule.styleSheet)
}
}
}

async function visit(root: Document | ShadowRoot) {
for (const sheet of root.styleSheets) {
visit_imports(sheet)
}

for (const sheet of root.adoptedStyleSheets) {
if (seen_sheets.has(sheet)) {
continue
Expand Down Expand Up @@ -105,6 +136,7 @@ export async function read_page_css(
.filter(Boolean)
.join(' '),
disabled: link.getAttribute('disabled') ?? undefined,
media: link.getAttribute('media') ?? undefined,
fetched_css,
})
if (shipped_css !== undefined && link.sheet !== null) {
Expand Down
3 changes: 3 additions & 0 deletions src/css-source.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export type CSSLinkSource = CSSSourceBase & {
/** The resolved absolute URL of the <link>'s href. */
href: string
rel: string
/** The media condition of the `<link>`, as written in its attribute. */
media?: string
disabled?: string
}
Expand All @@ -23,6 +24,8 @@ export type CSSImportSource = CSSSourceBase & {
type: 'import'
/** The resolved absolute URL that the @import rule points at. */
href: string
/** The media condition of the `@import` rule, as the browser serializes it. Not found for a
* rule inside a cross-origin stylesheet, whose rules the page cannot read. */
media?: string
}

Expand Down
15 changes: 12 additions & 3 deletions src/dom-css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@ import type {
import { read_page_css, type CSSWalkEntry } from './browser.ts'
import type { OnScrapeError, PageLike } from './types.ts'

/** The attributes of a `<link>` that the network response of its stylesheet does not carry. */
export type LinkAttributes = { rel: string; disabled?: string; media?: string }

/** What the DOM walk found: the `<link>`s the network cross-check needs to classify responses,
* the links that had to be fetched again because no response was recorded, and every other
* source, already in output order. */
export interface DOMCSS {
links: Map<string, { rel: string; disabled?: string }>
links: Map<string, LinkAttributes>
import_media: Map<string, string>
fetched_links: CSSLinkSource[]
sources: CSSSource[]
}
Expand All @@ -26,7 +30,8 @@ export async function collect_dom_css(
shipped_by_url: Record<string, string>,
on_error?: OnScrapeError,
): Promise<DOMCSS> {
const links = new Map<string, { rel: string; disabled?: string }>()
const links = new Map<string, LinkAttributes>()
const import_media = new Map<string, string>()
const fetched_links: CSSLinkSource[] = []
const inline_sources: CSSInlineSource[] = []
const style_sources: CSSStyleSource[] = []
Expand All @@ -46,7 +51,7 @@ export async function collect_dom_css(
const seen_adopted_css = new Set<string>()
for (const entry of entries) {
if (entry.type === 'link') {
links.set(entry.href, { rel: entry.rel, disabled: entry.disabled })
links.set(entry.href, { rel: entry.rel, disabled: entry.disabled, media: entry.media })
if (entry.fetched_css !== undefined) {
fetched_links.push({
type: 'link',
Expand All @@ -55,8 +60,11 @@ export async function collect_dom_css(
rel: entry.rel,
css: entry.fetched_css,
disabled: entry.disabled,
media: entry.media,
})
}
} else if (entry.type === 'import') {
import_media.set(entry.href, entry.media)
} else if (entry.type === 'inline') {
inline_sources.push({ type: 'inline', url: frame_url, css: entry.css })
} else if (entry.type === 'style') {
Expand All @@ -72,6 +80,7 @@ export async function collect_dom_css(

return {
links,
import_media,
fetched_links,
sources: [...adopted_sources, ...style_sources, ...cssom_sources, ...inline_sources],
}
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export async function collect_css(
}

const dom = await collect_dom_css(page, shipped_by_url, options.on_error)
const network_sources = cross_check_network_responses(stylesheets, dom.links)
const network_sources = cross_check_network_responses(stylesheets, dom.links, dom.import_media)

return [...network_sources, ...dom.fetched_links, ...dom.sources]
}
Expand Down
16 changes: 13 additions & 3 deletions src/network-css.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { CSSImportSource, CSSLinkSource } from './css-source.types.ts'
import type { LinkAttributes } from './dom-css.ts'
import type { OnScrapeError, PageLike, ResponseLike } from './types.ts'

/** Whether a response is a successful, CSS-typed stylesheet response. */
Expand Down Expand Up @@ -79,7 +80,8 @@ export async function read_responses(
}

/** Turns the read responses into sources: a response whose URL is a `<link>` in the DOM
* becomes a link source (carrying its `rel` and `disabled` state), anything else an import source.
* becomes a link source (carrying its `rel`, `disabled` state and `media`), anything else an
* import source (carrying the `media` of its `@import` rule).
*
* Adopted sheets are intentionally not cross-referenced against these. A constructed
* CSSStyleSheet has no URL, and its cssText is serialized by the browser (e.g. `#bb5555`
Expand All @@ -88,7 +90,8 @@ export async function read_responses(
* would fix this, but real-world impact is expected to be low. */
export function cross_check_network_responses(
stylesheets: FetchedStylesheet[],
links: Map<string, { rel: string; disabled?: string }>,
links: Map<string, LinkAttributes>,
import_media: Map<string, string>,
): Array<CSSLinkSource | CSSImportSource> {
return stylesheets.map(({ url, css }) => {
const link = links.get(url)
Expand All @@ -100,8 +103,15 @@ export function cross_check_network_responses(
rel: link.rel,
css,
disabled: link.disabled,
media: link.media,
} satisfies CSSLinkSource
}
return { type: 'import', href: url, url, css } satisfies CSSImportSource
return {
type: 'import',
href: url,
url,
css,
media: import_media.get(url),
} satisfies CSSImportSource
})
}
14 changes: 14 additions & 0 deletions test/fixtures/import/media-style-element/expected.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"type": "import",
"href": "/import/media-style-element/print.css",
"url": "/import/media-style-element/print.css",
"css": ".print {\n\tcolor: #000000;\n}\n",
"media": "print"
},
{
"type": "style",
"url": "/import/media-style-element/index.html",
"css": "\n\t\t\t@import url('print.css') print;\n\t\t"
}
]
12 changes: 12 additions & 0 deletions test/fixtures/import/media-style-element/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<style>
@import url('print.css') print;
</style>
</head>
<body>
<p>@import with a media condition in a style element</p>
</body>
</html>
3 changes: 3 additions & 0 deletions test/fixtures/import/media-style-element/print.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.print {
color: #000000;
}
3 changes: 2 additions & 1 deletion test/fixtures/import/media/expected.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"type": "import",
"href": "/import/media/imported-dark.css",
"url": "/import/media/imported-dark.css",
"css": ".imported-dark {\n\tcolor: #994444;\n}\n"
"css": ".imported-dark {\n\tcolor: #994444;\n}\n",
"media": "(prefers-color-scheme: dark)"
}
]
6 changes: 4 additions & 2 deletions test/fixtures/link/media-dark/expected.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
"href": "/link/media-dark/light.css",
"url": "/link/media-dark/light.css",
"rel": "stylesheet",
"css": ".scheme-light {\n\tcolor: #eeeeee;\n}\n"
"css": ".scheme-light {\n\tcolor: #eeeeee;\n}\n",
"media": "(prefers-color-scheme: light)"
},
{
"type": "link",
"href": "/link/media-dark/dark.css",
"url": "/link/media-dark/dark.css",
"rel": "stylesheet",
"css": ".scheme-dark {\n\tcolor: #111111;\n}\n"
"css": ".scheme-dark {\n\tcolor: #111111;\n}\n",
"media": "(prefers-color-scheme: dark)"
}
]
6 changes: 4 additions & 2 deletions test/fixtures/link/media-forced-colors/expected.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
"href": "/link/media-forced-colors/normal.css",
"url": "/link/media-forced-colors/normal.css",
"rel": "stylesheet",
"css": ".colors-normal {\n\tcolor: #cc5555;\n}\n"
"css": ".colors-normal {\n\tcolor: #cc5555;\n}\n",
"media": "(forced-colors: none)"
},
{
"type": "link",
"href": "/link/media-forced-colors/forced.css",
"url": "/link/media-forced-colors/forced.css",
"rel": "stylesheet",
"css": ".colors-forced {\n\tcolor: #cc6666;\n}\n"
"css": ".colors-forced {\n\tcolor: #cc6666;\n}\n",
"media": "(forced-colors: active)"
}
]
6 changes: 4 additions & 2 deletions test/fixtures/link/media-reduced-motion/expected.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
"href": "/link/media-reduced-motion/motion.css",
"url": "/link/media-reduced-motion/motion.css",
"rel": "stylesheet",
"css": ".motion-ok {\n\tcolor: #bb3333;\n}\n"
"css": ".motion-ok {\n\tcolor: #bb3333;\n}\n",
"media": "(prefers-reduced-motion: no-preference)"
},
{
"type": "link",
"href": "/link/media-reduced-motion/reduced.css",
"url": "/link/media-reduced-motion/reduced.css",
"rel": "stylesheet",
"css": ".motion-reduced {\n\tcolor: #bb4444;\n}\n"
"css": ".motion-reduced {\n\tcolor: #bb4444;\n}\n",
"media": "(prefers-reduced-motion: reduce)"
}
]
5 changes: 5 additions & 0 deletions test/integration/import.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ describe('@import', () => {
expect(result).toEqual(load_expected_sources(server, 'import/media'))
})

test('@import with a media condition in a <style> element', async () => {
const result = await scrape_css(page, `${server.url}/import/media-style-element/index.html`)
expect(result).toEqual(load_expected_sources(server, 'import/media-style-element'))
})

test('@import with a supports() condition', async () => {
const result = await scrape_css(page, `${server.url}/import/supports/index.html`)
expect(result).toEqual(load_expected_sources(server, 'import/supports'))
Expand Down
Loading