Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
36 changes: 11 additions & 25 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5291,33 +5291,21 @@ pub mod bv2_impl {

let asts = self.graph.ast.slice();
let css_asts = asts.items_css();
// SoA columns are physically disjoint slabs but rustc cannot
// see that through `&Slice`. Route the two columns we mutate (`parts`,
// `import_records`) through `split_raw()` (root-provenance `*mut [T]`,
// no `&mut` intermediate) so the per-index `&mut` does not conflict
// with the `&asts` reads (`css`, `target`). Mirrors the pattern at
// `find_reachable_files` (~L1457). The slab does not resize for the
// duration of this loop and no other `&mut` to these columns exists.
let ast_raw = asts.split_raw();
let parts_col: *mut bun_ast::PartList = ast_raw.parts.cast::<bun_ast::PartList>();
let import_records_col: *mut import_record::List =
ast_raw.import_records.cast::<import_record::List>();
let parts = asts.items_parts();
let all_import_records = asts.items_import_records();

let input_files = self.graph.input_files.slice();
let loaders = input_files.items_loader();
let sources = input_files.items_source();
for index in 1..self.graph.ast.len() {
// SAFETY: `index < ast.len()`; see note above for column aliasing.
let part_list = unsafe { &mut *parts_col.add(index) };
// SAFETY: `index < ast.len()`; see note above for column aliasing.
let import_records = unsafe { &mut *import_records_col.add(index) };
let import_records = &all_import_records[index];
let maybe_css = &css_asts[index];
let target = asts.items_target()[index];
// Dev Server proceeds even with failed files.
// These files are filtered out via the lack of any parts.
//
// Actual empty files will contain a part exporting an empty object.
if part_list.len() != 0 {
if parts[index].len() != 0 {
if maybe_css.is_some() {
// CSS has restrictions on what files can be imported.
// This means the file can become an error after
Expand Down Expand Up @@ -5372,21 +5360,19 @@ pub mod bv2_impl {
}

// Discover all CSS roots.
for record in import_records.as_mut_slice() {
for record in import_records.as_slice() {
if !record.source_index.is_valid() {
continue;
}
if loaders[record.source_index.get() as usize] != Loader::Css {
continue;
}
// SAFETY: `source_index < ast.len()` (validated above); read
// via the raw column ptr so we don't reborrow `asts.parts()`
// while `import_records` (a sibling column) is held `&mut`.
if unsafe {
(*parts_col.add(record.source_index.get() as usize)).len()
} == 0
{
record.source_index = Index::INVALID;
// A CSS file that failed to bundle has no parts and must
// not become a CSS chunk. The record keeps its source
// index: the HTML rewriter and the HMR import conversion
// use it to recognize the import as a stylesheet, and the
// importer's output stays cached after the CSS recovers.
Comment thread
robobun marked this conversation as resolved.
Resolved
if parts[record.source_index.get() as usize].len() == 0 {
continue;
}

Expand Down
142 changes: 141 additions & 1 deletion test/bake/dev/css.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// CSS tests concern bundling bugs with CSS files
import { expect } from "bun:test";
import assert from "node:assert";
import { devTest, emptyHtmlFile, imageFixtures } from "../bake-harness";
import { type Dev, devTest, emptyHtmlFile, imageFixtures } from "../bake-harness";

devTest("css file with syntax error does not kill old styles", {
files: {
Expand Down Expand Up @@ -691,6 +691,146 @@ devTest("css import before create project relative", {
await dev.fetch("/").expect.toContain("HELLO");
},
});
devTest("html route strips its link tag when the stylesheet is bundled alongside a failing version of itself", {
// The route that links a broken stylesheet gets bundled together with it on
// first load, when the route is requested while it is broken, and when the
// HTML file itself is edited while it is broken. The HTML generated by that
// bundle is what gets served once the stylesheet recovers, since only the
// stylesheet is rebuilt then.
files: {
"index.html": emptyHtmlFile({
styles: ["styles.css"],
body: `<div class="a">hello</div>`,
}),
"styles.css": `
.a { color: red; }}
`,
},
async test(dev) {
expect((await dev.fetch("/")).status).toBe(500);
await dev.write(
"styles.css",
`
.a { color: blue; }
`,
);
const recovered = await fetchRouteHtml(dev);
const links = recovered.match(/<link [^>]*>/g);
expect(links).toEqual([expect.stringMatching(injectedStylesheetLink)]);
await dev.fetch(links![0].match(injectedStylesheetLink)![1]).expect.toMatch(/color:\s*#00f/);

// Syntax error, route requested while broken, then recovery.
await dev.write(
"styles.css",
`
.a { color: blue; }}
`,
);
expect((await dev.fetch("/")).status).toBe(500);
await dev.write(
"styles.css",
`
.a { color: green; }
`,
);
expect(await fetchRouteHtml(dev)).toBe(recovered);

// A stylesheet that parses but fails import resolution, HTML file edited
// while broken, then recovery.
await dev.write(
"styles.css",
`
.a { background-image: url(./missing.png); }
`,
);
await dev.writeNoChanges("index.html");
await dev.write(
"styles.css",
`
.a { color: yellow; }
`,
);
expect(await fetchRouteHtml(dev)).toBe(recovered);
},
});
devTest("script importing a stylesheet still boots after the stylesheet fails and recovers", {
// Same three situations as above for a stylesheet imported from JavaScript:
// the module generated for the importer while the stylesheet is broken must
// not list the stylesheet as a JavaScript dependency.
files: {
"index.html": emptyHtmlFile({
scripts: ["index.ts"],
body: `<div class="a">hello</div>`,
}),
"index.ts": `
import "./styles.css";
`,
"styles.css": `
.a { color: red; }}
`,
},
async test(dev) {
expect((await dev.fetch("/")).status).toBe(500);
await dev.write(
"styles.css",
`
.a { color: blue; }
`,
);
{
await using c = await dev.client("/");
await c.style(".a").color.expect.toBe("#00f");
}

await dev.write(
"styles.css",
`
.a { color: blue; }}
`,
);
expect((await dev.fetch("/")).status).toBe(500);
await dev.write(
"styles.css",
`
.a { color: green; }
`,
);
{
await using c = await dev.client("/");
await c.style(".a").color.expect.toBe("green");
}

await dev.write(
"styles.css",
`
.a { background-image: url(./missing.png); }
`,
);
await dev.writeNoChanges("index.ts");
await dev.write(
"styles.css",
`
.a { color: yellow; }
`,
);
{
await using c = await dev.client("/");
await c.style(".a").color.expect.toBe("#ff0");
}
},
});

const injectedStylesheetLink = /^<link rel="stylesheet" href="(\/_bun\/asset\/[0-9a-f]{16}\.css)">$/;

/**
* Serves "/" and masks the route script's URL, which embeds a generation
* number that changes every time the route is re-bundled.
*/
async function fetchRouteHtml(dev: Dev): Promise<string> {
const res = await dev.fetch("/");
expect(res.status).toBe(200);
return (await res.text()).replace(/src="\/_bun\/client\/[^"]*"/, 'src="<route script>"');
}

function extractCssUrl(backgroundImage: string): string {
const url = backgroundImage.match(/url\((['"])(.*?)\1\)/);
Expand Down