Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 24 additions & 0 deletions src/bundler/LinkerContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,30 @@ impl<'a> LinkerContext<'a> {
&& record.source_index.get() != source_index
}

/// The targets to print a CSS chunk with. These must be the targets its
/// stylesheets were minified with (`ParseTask`): nesting, media range syntax
/// and `light-dark()` references are lowered at print time, and the
/// `light-dark()` polyfill is only complete when both halves agree.
///
/// The stylesheets were minified by the transpiler of the graph the chunk's
/// entry point was parsed in. In a server build, an HTML entry point (passed
/// directly or imported from server code) and everything it links go
/// through the client transpiler, so the chunk is printed for browsers;
/// every other entry point's graph uses the build's own target. The entry
/// point's AST target is only trusted for `Browser`: a `#!/usr/bin/env bun`
/// hashbang marks the entry of a browser build `Bun`, and the separate SSR
/// graph marks its files `ServerComponentsSsr`, while the stylesheets of
/// both were still minified with the build's target.
pub(crate) fn css_targets_for_chunk(&self, chunk: &Chunk) -> crate::bun_css::Targets {
let entry_target = self.graph.ast.items_target()[chunk.entry_point.source_index() as usize];
let target = if entry_target == Target::Browser {
Target::Browser
} else {
self.options.target
};
crate::bun_css::Targets::for_bundler_target(target)
}

/// Note: this should call a `MimallocArena` debug hook
/// (`helpCatchMemoryIssues`), but `Graph.heap` is currently
/// `bun_alloc::Arena = bumpalo::Bump`, which has no such hook, so this is a
Expand Down
10 changes: 6 additions & 4 deletions src/bundler/linker_context/generateCompileResultForCssChunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use bun_ast::ImportRecord;
use bun_collections::VecExt;
use bun_threading::thread_pool as ThreadPoolLib;

use crate::bun_css::{BundlerStyleSheet, ImportInfo, LocalsResultsMap, PrinterOptions, Targets};
use crate::bun_css::{BundlerStyleSheet, ImportInfo, LocalsResultsMap, PrinterOptions};

use crate::chunk::{Content, CssImportOrderKind};
use crate::linker_context_mod::LinkerContext;
Expand Down Expand Up @@ -103,12 +103,14 @@ fn generate_compile_result_for_css_chunk_impl(
)
};

let targets = c.css_targets_for_chunk(chunk);

match &css_import.kind {
CssImportOrderKind::Layers(_) => {
let printer_options = PrinterOptions {
// TODO: make this more configurable
minify: c.options.minify_whitespace,
targets: Targets::for_bundler_target(c.options.target),
targets,
..Default::default()
};
match css.to_css_with_writer(
Expand Down Expand Up @@ -151,7 +153,7 @@ fn generate_compile_result_for_css_chunk_impl(
let printer_options = PrinterOptions {
// TODO: make this more configurable
minify: c.options.minify_whitespace,
targets: Targets::for_bundler_target(c.options.target),
targets,
..Default::default()
};
match css.to_css_with_writer(
Expand Down Expand Up @@ -184,7 +186,7 @@ fn generate_compile_result_for_css_chunk_impl(
}
CssImportOrderKind::SourceIndex(idx) => {
let printer_options = PrinterOptions {
targets: Targets::for_bundler_target(c.options.target),
targets,
// TODO: make this more configurable
minify: c.options.minify_whitespace
|| c.options.minify_syntax
Expand Down
5 changes: 3 additions & 2 deletions src/bundler/linker_context/prepareCssAstsForChunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::bun_css::css_parser::{
BundlerSupportsRule, ImportRule, LayerName, LayerStatementRule, Location, ParserOptions,
SmallList,
};
use crate::bun_css::{BundlerStyleSheet, ImportConditions, ImportInfo, PrinterOptions, Targets};
use crate::bun_css::{BundlerStyleSheet, ImportConditions, ImportInfo, PrinterOptions};
use crate::bun_fs::Path;
use bun_ast::{ImportKind, ImportRecord, ImportRecordFlags, ImportRecordTag, Index as AstIndex};
use bun_ast::{Loc, Range};
Expand Down Expand Up @@ -84,6 +84,7 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: &
// across the log write below (split borrow).
let parse_graph = unsafe { &*c.parse_graph };
let asts = c.graph.ast.items_css();
let targets = c.css_targets_for_chunk(chunk);

// Prepare CSS asts
// Remove duplicate rules across files. This must be done in serial, not
Expand Down Expand Up @@ -221,7 +222,7 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: &
});

let printer_options = PrinterOptions {
targets: Targets::for_bundler_target(c.options.target),
targets,
// TODO: make this more configurable
minify: c.options.minify_whitespace
|| c.options.minify_syntax
Expand Down
136 changes: 135 additions & 1 deletion test/bundler/bundler_html.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect } from "bun:test";
import { itBundled } from "./expectBundled";
import { type BundlerTestBundleAPI, itBundled } from "./expectBundled";

describe("bundler", () => {
// Basic test for bundling HTML with JS and CSS
Expand Down Expand Up @@ -1011,4 +1011,138 @@ body {
expect(htmlContent).toMatch(/href=".*\.webmanifest"/);
},
});

// A stylesheet linked from an HTML file is built for the browser even when the
// build itself targets bun or node (the HTML is imported from server code for
// Bun.serve, or passed to a server build as an entry point). Minifying already
// used the default browser targets; printing has to use them too, since
// nesting, media range syntax and light-dark() are only lowered while
// printing. This fixture reaches every place the linker prints CSS:
//
// - the stylesheet itself (nesting, the @media range, light-dark() references)
// - the preserved external @import, whose media condition is printed on its own
// - the external @import behind a conditional internal @import, which is
// printed into a data: URL stylesheet while the chunk is prepared
// - the bare "@layer foo;" left behind by the deduplicated layer import,
// printed together with its wrapping media condition
const browserTargetFiles = {
"/index.html": `
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./styles.css">
</head>
<body></body>
</html>`,
"/styles.css": `
@import "https://example.com/external.css" screen and (width >= 500px);
@import "./dup.css" layer(foo) (width >= 600px);
@import "./other.css";
@import "./dup.css" layer(foo) (width >= 600px);
@import "./nested.css" (width >= 700px);
:root {
color-scheme: light dark;
}
.a {
color: light-dark(white, black);
.b {
color: blue;
}
}
@media (width >= 800px) {
.c {
color: green;
}
}`,
"/dup.css": ".dup { color: red; }",
"/other.css": ".other { color: red; }",
"/nested.css": `
@import "https://example.com/nested.css" (width >= 900px);
.nested { color: red; }`,
};

function expectPrintedForBrowsers(css: string) {
expect(css).toContain(".a .b {");
expect(css).toContain("var(--buncss-light, #fff) var(--buncss-dark, #000)");
expect(css).not.toContain("light-dark(");
expect(css).toContain("@media (min-width: 800px)");
expect(css).toContain('@import "https://example.com/external.css" screen and (min-width: 500px);');
expect(css).toContain(
'@import "data:text/css,@import \\"https://example.com/nested.css\\" (min-width: 900px);" (min-width: 700px);',
);
expect(css).toContain("@media (min-width: 600px) {\n @layer foo;\n}");
expect(css).not.toContain(">=");
}

function readLinkedStylesheet(api: BundlerTestBundleAPI, htmlFile: string) {
const href = api.readFile(htmlFile).match(/href="(.*?\.css)"/)?.[1];
if (!href) throw new Error(`No stylesheet is linked from ${htmlFile}`);
return api.readFile("out/" + href);
}

// Reference: what a browser build prints. The server builds below must print
// the same stylesheet the same way.
itBundled("html/css-browser-targets/browser-build", {
outdir: "out/",
files: browserTargetFiles,
entryPoints: ["/index.html"],
onAfterBundle(api) {
expectPrintedForBrowsers(readLinkedStylesheet(api, "out/index.html"));
},
});

for (const target of ["bun", "node"] as const) {
itBundled(`html/css-browser-targets/imported-from-${target}-build`, {
outdir: "out/",
target,
files: {
...browserTargetFiles,
"/server.ts": `
import html from "./index.html";
console.log(html);`,
},
entryPoints: ["/server.ts"],
onAfterBundle(api) {
expectPrintedForBrowsers(readLinkedStylesheet(api, "out/index.html"));
},
});
}

itBundled("html/css-browser-targets/html-entry-point-of-bun-build", {
outdir: "out/",
target: "bun",
files: browserTargetFiles,
entryPoints: ["/index.html"],
onAfterBundle(api) {
expectPrintedForBrowsers(readLinkedStylesheet(api, "out/index.html"));
},
});

// The same stylesheet imported by the server code itself is part of the bun
// build, not of the browser one: it keeps the build's own (runtime) CSS
// targets for both minifying and printing.
itBundled("html/css-browser-targets/imported-by-server-code-keeps-runtime-targets", {
outdir: "out/",
target: "bun",
files: {
...browserTargetFiles,
"/server.ts": `
import "./styles.css";
console.log("server");`,
},
entryPoints: ["/server.ts"],
onAfterBundle(api) {
const css = api.readFile("out/server.css");
expect(css).toContain("& .b {");
expect(css).toContain("color: light-dark(#fff, #000);");
expect(css).not.toContain("--buncss-light");
expect(css).toContain("@media (width >= 800px)");
expect(css).toContain('@import "https://example.com/external.css" screen and (width >= 500px);');
expect(css).toContain(
'@import "data:text/css,@import \\"https://example.com/nested.css\\" (width >= 900px);" (width >= 700px);',
);
expect(css).toContain("@media (width >= 600px) {\n @layer foo;\n}");
expect(css).not.toContain("min-width");
},
});
});
Loading