:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(frontend): split the stable build's CSS into cacheable stylesheets (#105821)
Paul D'Ambracb5e952e8dc5
diff --git a/common/esbuilder/cssLoader.mjs b/common/esbuilder/cssLoader.mjsindex 24bbbe148f0c..327f6ab6535f 100644--- a/common/esbuilder/cssLoader.mjs+++ b/common/esbuilder/cssLoader.mjs@@ -127,3 +127,118 @@ export function cssLoaderScript(cssFile, cssFileFallback) {})();`}++export const CSS_LOAD_GLOBAL = 'ESBUILD_LOAD_CSS'++/**+ * Inline loader for the stable build's split stylesheets (see frontend/bin/stableCssPlan.mjs).+ *+ * The eager layers load in order, and `window.ESBUILD_CSS_READY` resolves once all of them apply.+ * `window.ESBUILD_LOAD_CSS(entries)` loads the stylesheets a lazy chunk waits on before it runs.+ * Each entry is `[url, rank]`, where rank is the group's place in the full stylesheet. Lazy+ * stylesheets are inserted in rank order, so the cascade among them does not depend on the order+ * scenes load in. `null` in place of the entries asks for the full stylesheet.+ *+ * When a stable stylesheet fails or stalls, the loader runs `cssLoaderScript` for the full+ * stylesheet, which holds every rule, with its whole retry and reporting ladder. A failure in the+ * stable build therefore ends up where the default build starts. A load that fails for good+ * resolves `false` and is forgotten, so the next attempt fetches again.+ */+export function stableCssLoaderScript(eagerFiles, fullCssFile, fullCssFileFallback) {+ return `+ (function () {+ var fullStylesheet = null;+ var fullStylesheetApplied = false;+ function loadFullStylesheet() {+ if (!fullStylesheet) {+ ${cssLoaderScript(fullCssFile, fullCssFileFallback)}+ fullStylesheet = window.${CSS_READY_GLOBAL}.then(function (applied) {+ if (applied) {+ fullStylesheetApplied = true;+ } else {+ fullStylesheet = null;+ }+ return applied;+ });+ }+ return fullStylesheet;+ }++ var lazyLinks = [];+ function insertLink(link, rank) {+ if (rank === null) {+ document.head.appendChild(link);+ return;+ }+ var before = null;+ for (var i = 0; i < lazyLinks.length; i++) {+ if (lazyLinks[i].rank > rank) { before = lazyLinks[i].link; break; }+ }+ lazyLinks.push({ rank: rank, link: link });+ lazyLinks.sort(function (a, b) { return a.rank - b.rank; });+ if (before) {+ document.head.insertBefore(link, before);+ } else {+ document.head.appendChild(link);+ }+ }++ function loadStylesheet(href, rank) {+ return new Promise(function (resolve) {+ var link = document.createElement("link");+ link.rel = "stylesheet";+ link.crossOrigin = "anonymous";+ link.href = href;+ var timer = setTimeout(function () { resolve(false); }, ${CSS_ATTEMPT_TIMEOUT_MS});+ link.addEventListener("load", function () { clearTimeout(timer); resolve(!!link.sheet); });+ link.addEventListener("error", function () { clearTimeout(timer); resolve(false); });+ insertLink(link, rank);+ });+ }++ var requested = {};+ function loadEntries(entries) {+ return Promise.all(entries.map(function (entry) {+ var url = Array.isArray(entry) ? entry[0] : entry;+ var rank = Array.isArray(entry) ? entry[1] : null;+ if (!requested[url]) {+ requested[url] = loadStylesheet(url, rank).then(function (applied) {+ if (applied) { return true; }+ console.error('[PostHog] Stylesheet did not apply, loading the full stylesheet: ' + url);+ return loadFullStylesheet().then(function (fullApplied) {+ if (!fullApplied) { delete requested[url]; }+ return fullApplied;+ });+ });+ }+ return requested[url];+ })).then(function (results) {+ return results.every(Boolean);+ });+ }+ window.${CSS_LOAD_GLOBAL} = function (entries) {+ // The full stylesheet holds every rule. A split stylesheet inserted after it would+ // override its later rules, so once it applies nothing else is loaded.+ if (fullStylesheetApplied) {+ return Promise.resolve(true);+ }+ if (entries === null) {+ return loadFullStylesheet();+ }+ if (fullStylesheet) {+ // A full load from an earlier fallback is still in flight: wait for it, since a+ // split link inserted now could land after it and reorder the cascade.+ return fullStylesheet.then(function (applied) {+ return applied ? true : loadEntries(entries);+ });+ }+ return loadEntries(entries);+ };++ var eager = ${JSON.stringify(eagerFiles)}.map(function (file) {+ return (window.JS_URL || '') + '/static/' + file;+ });+ window.${CSS_READY_GLOBAL} = window.${CSS_LOAD_GLOBAL}(eager);+ })();+ `+}diff --git a/common/esbuilder/cssLoader.test.ts b/common/esbuilder/cssLoader.test.tsindex 52a7befe742a..73f88b84140e 100644--- a/common/esbuilder/cssLoader.test.ts+++ b/common/esbuilder/cssLoader.test.ts@@ -1,4 +1,4 @@-import { CSS_ATTEMPT_TIMEOUT_MS, cssLoaderScript } from './cssLoader.mjs'+import { CSS_ATTEMPT_TIMEOUT_MS, cssLoaderScript, stableCssLoaderScript } from './cssLoader.mjs'const CSS_FILE = 'index-ABCD1234.css'const CSS_FALLBACK = 'index.css?t=99'@@ -24,10 +24,15 @@ function makeLink(): FakeLink {}}-function runLoader({ cssFileFallback = CSS_FALLBACK, apiKey = 'phc_test' as string | null } = {}): {+function runLoader({+ cssFileFallback = CSS_FALLBACK,+ apiKey = 'phc_test' as string | null,+ script = cssLoaderScript(CSS_FILE, cssFileFallback),+} = {}): {ready: Promise<boolean>links: FakeLink[]beacons: Record<string, any>[]+ win: Record<string, any>} {const links: FakeLink[] = []const beacons: Record<string, any>[] = []@@ -41,7 +46,10 @@ function runLoader({ cssFileFallback = CSS_FALLBACK, apiKey = 'phc_test' as stri}const doc = {createElement: (): FakeLink => makeLink(),- head: { appendChild: (link: FakeLink) => links.push(link) },+ head: {+ appendChild: (link: FakeLink) => links.push(link),+ insertBefore: (link: FakeLink, before: FakeLink) => links.splice(links.indexOf(before), 0, link),+ },}const nav = {sendBeacon: (_url: string, body: string) => {@@ -50,15 +58,14 @@ function runLoader({ cssFileFallback = CSS_FALLBACK, apiKey = 'phc_test' as stri},}// The inline loader runs in the page as a classic script: these are all globals there.- new Function(- 'window',- 'document',- 'navigator',- 'console',- 'fetch',- cssLoaderScript(CSS_FILE, cssFileFallback)- )(win, doc, nav, { error: () => {} }, () => Promise.resolve())- return { ready: win.ESBUILD_CSS_READY, links, beacons }+ new Function('window', 'document', 'navigator', 'console', 'fetch', script)(+ win,+ doc,+ nav,+ { error: () => {} },+ () => Promise.resolve()+ )+ return { ready: win.ESBUILD_CSS_READY, links, beacons, win }}/** A stylesheet that really applied has a `sheet`; a response that is not CSS fires `load` without one. */@@ -150,4 +157,128 @@ describe('css loader script', () => {links[1].dispatch('error')expect(links).toHaveLength(2)})++ // The stable build splits the stylesheet; a split stylesheet that fails must not leave the page+ // unstyled, because the full stylesheet holds every rule.+ it.each([+ ['every split stylesheet applies', false],+ ['a split stylesheet fails', true],+ ])('reports ready when %s', async (_name, splitFails) => {+ const { ready, links } = runLoader({+ script: stableCssLoaderScript(['a-1.css', 'b-2.css'], CSS_FILE, CSS_FALLBACK),+ })+ expect(links.map((link) => link.href)).toEqual([`${STATIC}a-1.css`, `${STATIC}b-2.css`])++ applyStylesheet(links[0])+ if (splitFails) {+ links[1].dispatch('error')+ await Promise.resolve()+ expect(links[2].href).toBe(`${STATIC}${CSS_FILE}`)+ applyStylesheet(links[2])+ } else {+ applyStylesheet(links[1])+ }++ await expect(ready).resolves.toBe(true)+ expect(links).toHaveLength(splitFails ? 3 : 2)+ })++ describe('stable loader for lazy stylesheets', () => {+ const stable = (): ReturnType<typeof runLoader> =>+ runLoader({ script: stableCssLoaderScript(['eager-1.css'], CSS_FILE, CSS_FALLBACK) })+ const lazyLoad = (win: any, entries: [string, number][] | null): Promise<boolean> =>+ (win as any).ESBUILD_LOAD_CSS(entries)++ // Scenes load in any order, but the cascade among their stylesheets must match the full one.+ it('inserts lazy stylesheets in rank order whatever order they load in', () => {+ const { links, win } = stable()+ void lazyLoad(win, [[`${STATIC}later.css`, 20]])+ void lazyLoad(win, [[`${STATIC}earlier.css`, 10]])++ expect(links.map((link) => link.href)).toEqual([+ `${STATIC}eager-1.css`,+ `${STATIC}earlier.css`,+ `${STATIC}later.css`,+ ])+ })++ it('loads the full stylesheet when the chunk cannot resolve its groups, and nothing after it', async () => {+ const { links, win } = stable()+ const loaded = lazyLoad(win, null)++ expect(links[links.length - 1].href).toBe(`${STATIC}${CSS_FILE}`)+ applyStylesheet(links[links.length - 1])+ await expect(loaded).resolves.toBe(true)++ // A split stylesheet after the full one would override its later rules.+ const linksBefore = links.length+ await expect(lazyLoad(win, [[`${STATIC}later.css`, 99]])).resolves.toBe(true)+ expect(links).toHaveLength(linksBefore)+ })++ // A chunk whose styles never load throws so the chunk-load recovery runs; a retry must fetch again.+ it('resolves false when every fallback fails, and fetches again on the next attempt', async () => {+ const { links, win } = stable()+ const failed = lazyLoad(win, [[`${STATIC}scene.css`, 5]])+ links[1].dispatch('error')+ await Promise.resolve()+ for (let attempt = 2; attempt < links.length || attempt < 5; attempt++) {+ links[attempt]?.dispatch('error')+ await Promise.resolve()+ }+ await expect(failed).resolves.toBe(false)++ const linksBefore = links.length+ void lazyLoad(win, [[`${STATIC}scene.css`, 5]])+ expect(links.length).toBeGreaterThan(linksBefore)+ })++ // A second group requested while the full stylesheet is still loading must not insert its own+ // link, because that link would land after the full one already in <head> and could override it.+ it('does not insert a new link while the full-stylesheet fallback is in flight, and resolves once it applies', async () => {+ const { links, win } = stable()+ const firstRequest = lazyLoad(win, [[`${STATIC}scene.css`, 5]])+ links[1].dispatch('error')+ await Promise.resolve()+ const fullLink = links[links.length - 1]+ expect(fullLink.href).toBe(`${STATIC}${CSS_FILE}`)++ const linksBefore = links.length+ const secondRequest = lazyLoad(win, [[`${STATIC}other.css`, 99]])+ expect(links).toHaveLength(linksBefore)++ applyStylesheet(fullLink)+ await expect(firstRequest).resolves.toBe(true)+ await expect(secondRequest).resolves.toBe(true)+ expect(links).toHaveLength(linksBefore)+ })++ // Once every fallback fails, a request that was waiting on it must still get its own stylesheet.+ it('inserts its own stylesheet once every full-stylesheet fallback fails, and resolves to that result', async () => {+ const { links, win } = stable()+ const firstRequest = lazyLoad(win, [[`${STATIC}scene.css`, 5]])+ links[1].dispatch('error')+ await Promise.resolve()++ const linksBefore = links.length+ const secondRequest = lazyLoad(win, [[`${STATIC}other.css`, 99]])+ // The full stylesheet's own retry ladder still runs, but no link for "other.css" yet.+ expect(links.some((link) => link.href === `${STATIC}other.css`)).toBe(false)++ for (let attempt = 2; attempt < links.length || attempt < 5; attempt++) {+ links[attempt]?.dispatch('error')+ await Promise.resolve()+ }+ await expect(firstRequest).resolves.toBe(false)+ await Promise.resolve()+ await Promise.resolve()++ expect(links.length).toBeGreaterThan(linksBefore)+ const otherLink = links[links.length - 1]+ expect(otherLink.href).toBe(`${STATIC}other.css`)++ applyStylesheet(otherLink)+ await expect(secondRequest).resolves.toBe(true)+ })+ })})diff --git a/common/esbuilder/stableChunkNames.mjs b/common/esbuilder/stableChunkNames.mjsindex 00ebeb52b874..d41bfae489ca 100644--- a/common/esbuilder/stableChunkNames.mjs+++ b/common/esbuilder/stableChunkNames.mjs@@ -25,7 +25,7 @@ export const STABLE_NAME_MARKER = 'S'const SOURCE_MAP_COMMENT = /\n\/\/# sourceMappingURL=[^\n]*\s*$/-function shortHash(value) {+export function shortHash(value) {return createHash('sha256').update(value).digest('hex').slice(0, 10).toUpperCase()}@@ -79,7 +79,7 @@ export function stableFileName(originalFile, rewrittenSource) {* Returns, per JS output, its identity, stable file name and rewritten source, plus the import* map.*/-export function planStableChunks(outputs, readSource, distPrefix = 'dist/') {+export function planStableChunks(outputs, readSource, distPrefix = 'dist/', preludes = new Map()) {const jsOutputs = Object.entries(outputs).filter(([outputPath]) => outputPath.endsWith('.js'))const fileOf = (outputPath) => outputPath.slice(distPrefix.length)@@ -108,9 +108,12 @@ export function planStableChunks(outputs, readSource, distPrefix = 'dist/') {// Every replacement preserves length, except an identity collision with a short entry name// (see rewriteChunkSource). When that happens the map's byte offsets no longer line up.const mapValid = source.length === rawSource.replace(SOURCE_MAP_COMMENT, '').length+ // A prelude goes on its own first line, so the map only needs to shift down one line.+ const prelude = preludes.get(outputPath) ?? null+ const finalSource = prelude ? `${prelude}\n${source}` : sourceconst identity = identityByFile.get(file)- const stableFile = stableFileName(file, source)- plan.set(outputPath, { identity, file, stableFile, source, mapValid })+ const stableFile = stableFileName(file, finalSource)+ plan.set(outputPath, { identity, file, stableFile, source: finalSource, mapValid, prelude })imports[`${SPECIFIER_PREFIX}${identity}`] = `static/${stableFile}`}return { plan, imports }@@ -121,14 +124,27 @@ export function planStableChunks(outputs, readSource, distPrefix = 'dist/') {* manifest the backend reads. `chunks` is the chunk map (scene name -> esbuild chunk hashes) and* `entrypoints` the absolute paths of the entry files, as `buildOrWatch` returns them.*/-export function writeStableChunks({ absWorkingDir, outputs, chunks, entrypoints, preloadManifest }) {+export function writeStableChunks({+ absWorkingDir,+ outputs,+ chunks,+ entrypoints,+ preloadManifest,+ preludes = new Map(),+ extraImports = {},+ eagerCss = [],+}) {const distDir = path.resolve(absWorkingDir, 'dist')- const { plan, imports } = planStableChunks(outputs, (outputPath) =>- fs.readFileSync(path.resolve(absWorkingDir, outputPath), 'utf8')+ const { plan, imports } = planStableChunks(+ outputs,+ (outputPath) => fs.readFileSync(path.resolve(absWorkingDir, outputPath), 'utf8'),+ 'dist/',+ preludes)+ Object.assign(imports, extraImports)const stableByFile = new Map([...plan.values()].map((entry) => [entry.file, entry.stableFile]))- for (const { file, stableFile, source, mapValid } of plan.values()) {+ for (const { file, stableFile, source, mapValid, prelude } of plan.values()) {const mapFile = path.resolve(distDir, `${file}.map`)// A rewrite that changed the source's length invalidates the map's byte offsets, so serve// the source with no map rather than one that points at the wrong columns.@@ -137,7 +153,11 @@ export function writeStableChunks({ absWorkingDir, outputs, chunks, entrypoints,path.resolve(distDir, stableFile),hasMap ? `${source}\n//# sourceMappingURL=${stableFile}.map\n` : source)- if (hasMap) {+ if (hasMap && prelude) {+ const map = JSON.parse(fs.readFileSync(mapFile, 'utf8'))+ map.mappings = `;${map.mappings}`+ fs.writeFileSync(path.resolve(distDir, `${stableFile}.map`), JSON.stringify(map))+ } else if (hasMap) {fs.copyFileSync(mapFile, path.resolve(distDir, `${stableFile}.map`))}}@@ -153,11 +173,12 @@ export function writeStableChunks({ absWorkingDir, outputs, chunks, entrypoints,const toStableUrl = (url) => `static/${toStable(url.replace(/^static\//, ''))}`const manifest = {imports,+ eagerCss: eagerCss.map((file) => `static/${file}`),preload: {js: (preloadManifest?.js || []).map(toStableUrl),authenticatedJs: (preloadManifest?.authenticatedJs || []).map(toStableUrl),},}fs.writeFileSync(path.resolve(distDir, 'stable-chunks-manifest.json'), JSON.stringify(manifest))- return { chunks: stableChunks, entrypoints: stableEntrypoints, manifest }+ return { chunks: stableChunks, entrypoints: stableEntrypoints, eagerCss, manifest }}diff --git a/common/esbuilder/stableChunkNames.test.ts b/common/esbuilder/stableChunkNames.test.tsindex e073b11eb063..f5646c701e45 100644--- a/common/esbuilder/stableChunkNames.test.ts+++ b/common/esbuilder/stableChunkNames.test.ts@@ -1,4 +1,8 @@-import { planStableChunks, stableFileName } from './stableChunkNames.mjs'+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import path from 'node:path'++import { planStableChunks, stableFileName, writeStableChunks } from './stableChunkNames.mjs'// Two chunks: an entry that imports a shared chunk, the way esbuild writes them with publicPath /static.const OUTPUTS = {@@ -103,4 +107,61 @@ describe('planStableChunks', () => {expect(() => stableFileName('index.js', 'source')).toThrow(/does not end in the expected/)})})++ // The copied source map is shifted down exactly one line, so the prelude must be a line of its own.+ it('puts a prelude on its own first line and names the chunk by it', () => {+ const sources = entry('export const a=1')+ const withPrelude = planStableChunks(+ OUTPUTS,+ (outputPath: string) => sources[outputPath],+ 'dist/',+ new Map([['dist/Scene-AAAA1111.js', 'await window.ESBUILD_LOAD_CSS([]);']])+ ).plan.get('dist/Scene-AAAA1111.js')!++ expect(withPrelude.source.split('\n')[0]).toBe('await window.ESBUILD_LOAD_CSS([]);')+ expect(withPrelude.stableFile).not.toBe(plan(sources).get('dist/Scene-AAAA1111.js')!.stableFile)+ })++ describe('writeStableChunks', () => {+ const ENTRY_OUTPUTS = {+ 'dist/entry-AAAA1111.js': { entryPoint: 'src/entry.tsx', inputs: { 'src/entry.tsx': {} } },+ }++ function writeAndReadMap(prelude: string | null): unknown {+ const absWorkingDir = mkdtempSync(path.join(tmpdir(), 'stable-chunks-'))+ try {+ const distDir = path.join(absWorkingDir, 'dist')+ mkdirSync(distDir, { recursive: true })+ writeFileSync(path.join(distDir, 'entry-AAAA1111.js'), 'console.log(1)')+ writeFileSync(+ path.join(distDir, 'entry-AAAA1111.js.map'),+ JSON.stringify({ version: 3, mappings: 'AAAA' })+ )++ writeStableChunks({+ absWorkingDir,+ outputs: ENTRY_OUTPUTS,+ chunks: {},+ entrypoints: [],+ preloadManifest: undefined,+ preludes: prelude ? new Map([['dist/entry-AAAA1111.js', prelude]]) : new Map(),+ })++ const stableMapFile = readdirSync(distDir).find(+ (file) => file.startsWith('entry-S') && file.endsWith('.map')+ )!+ return JSON.parse(readFileSync(path.join(distDir, stableMapFile), 'utf8')).mappings+ } finally {+ rmSync(absWorkingDir, { recursive: true, force: true })+ }+ }++ // Pins the map shift so a regression here doesn't only show up as misattributed stack traces.+ it.each([+ ['a prelude chunk', 'await window.ESBUILD_LOAD_CSS([]);', ';AAAA'],+ ['a chunk with no prelude', null, 'AAAA'],+ ])('shifts the written source map by one line for %s', (_name, prelude, expectedMappings) => {+ expect(writeAndReadMap(prelude)).toBe(expectedMappings)+ })+ })})diff --git a/common/esbuilder/utils.mjs b/common/esbuilder/utils.mjsindex cf56333965a2..484e077452c3 100644--- a/common/esbuilder/utils.mjs+++ b/common/esbuilder/utils.mjs@@ -17,7 +17,7 @@ import postcssPresetEnv from 'postcss-preset-env'import ts from 'typescript'import { chunkLoaderScript, chunkMapFileContents, chunkMapFileName } from './chunkLoader.mjs'-import { cssLoaderScript } from './cssLoader.mjs'+import { cssLoaderScript, stableCssLoaderScript } from './cssLoader.mjs'// Re-exported for one-shot builds outside buildInParallel (e.g. the toolbar loader, which is// built after the toolbar app build so it can embed the hashed entry filename). Consumers@@ -87,7 +87,7 @@ export function copyIndexHtml(// Docker image, but serve the js and it's dependencies from e.g. CloudFrontconst buildId = new Date().valueOf()- const bootScript = (chunks, entrypoints, { isStable = false } = {}) => {+ const bootScript = (chunks, entrypoints, { isStable = false, eagerCss = [] } = {}) => {const relativeFiles = entrypoints.map((e) => path.relative(path.resolve(absWorkingDir, 'dist'), e))const jsFile =relativeFiles.length > 0 ? relativeFiles.find((e) => e.endsWith('.js')) : `${entry}.js?t=${buildId}`@@ -147,7 +147,13 @@ export function copyIndexHtml(// Fallback to non-hashed CSS (with cache-busting build ID) when the hashed version fails or// stalls (e.g. CDN returns 403, or the request hangs). Mirrors the JS fallback above.const cssFileFallback = `${entry}.css?t=${buildId}`- const cssLoader = cssFile ? cssLoaderScript(cssFile, cssFileFallback) : ''+ // The stable build links its split eager stylesheets and keeps the full one as its fallback.+ const cssLoader =+ isStable && eagerCss.length > 0+ ? stableCssLoaderScript(eagerCss, cssFile, cssFileFallback)+ : cssFile+ ? cssLoaderScript(cssFile, cssFileFallback)+ : ''return `<script nonce="{{ request.csp_nonce }}" type="application/javascript">// The stylesheet link is added just below, at runtime, so a slow CSS fetch does@@ -163,7 +169,7 @@ export function copyIndexHtml(// With stable chunk names built, the backend picks the boot variant per request. See// stableChunkNames.mjs and the stable_chunks context in posthog/utils.py.const scripts = stable- ? `{% if stable_chunks %}${bootScript(stable.chunks, stable.entrypoints, { isStable: true })}{% else %}${bootScript(chunks, entrypoints)}{% endif %}`+ ? `{% if stable_chunks %}${bootScript(stable.chunks, stable.entrypoints, { isStable: true, eagerCss: stable.eagerCss ?? [] })}{% else %}${bootScript(chunks, entrypoints)}{% endif %}`: bootScript(chunks, entrypoints)fse.writeFileSync(diff --git a/frontend/bin/bootEntries.mjs b/frontend/bin/bootEntries.mjsnew file mode 100644index 000000000000..46b1b1fc7070--- /dev/null+++ b/frontend/bin/bootEntries.mjs@@ -0,0 +1,6 @@+// The boot chain's entry points. check-eager-graph.mjs measures them, and stableCssPlan.mjs puts the+// CSS they import statically into the eager layers, so both must name the same files.+export const ENTRY = 'src/index.tsx'+export const LOGGED_OUT_BOOT = [ENTRY, 'src/scenes/App.tsx', 'src/scenes/bootApp.ts']+export const AUTHENTICATED_SHELL = 'src/scenes/AuthenticatedShell.tsx'+export const BOOT_ENTRIES = [...LOGGED_OUT_BOOT, AUTHENTICATED_SHELL]diff --git a/frontend/bin/check-eager-graph.mjs b/frontend/bin/check-eager-graph.mjsindex 7057c6c36f1b..8caf80a2f801 100644--- a/frontend/bin/check-eager-graph.mjs+++ b/frontend/bin/check-eager-graph.mjs@@ -4,6 +4,8 @@ import fs from 'node:fs'import path from 'node:path'import { fileURLToPath } from 'node:url'+import { AUTHENTICATED_SHELL, ENTRY, LOGGED_OUT_BOOT } from './bootEntries.mjs'+const __dirname = path.dirname(fileURLToPath(import.meta.url))const frontendDir = path.resolve(__dirname, '..')const metaPath = path.join(frontendDir, 'posthog-app-esbuild-meta.json')@@ -36,7 +38,7 @@ const failForbiddenHits = process.argv.includes('--fail-forbidden-hits')// raise a budget only as a conscious, reviewed decision in the PR that needs it.const ROOTS = [{- root: 'src/index.tsx',+ root: ENTRY,label: 'entry (logged-out pages, app bootstrap)',// 2026-09-11: 1.54 MiB eager output (0.18 MiB JS + the 1.36 MiB linked stylesheet, 22 files).// ~20% headroom so routine churn doesn't trip the warn; ratchet down on a split win.@@ -64,7 +66,7 @@ const ROOTS = [{// index.tsx imports App and bootApp as sibling dynamic imports, so neither alone is what// a logged-out page downloads: measure the deduplicated union of all three closures.- root: ['src/index.tsx', 'src/scenes/App.tsx', 'src/scenes/bootApp.ts'],+ root: LOGGED_OUT_BOOT,label: 'logged-out boot: index + App + bootApp (preloaded by every page, including /login)',// The backend preloads the App closure for logged-out pages too (preload-manifest.json// `js`), so this is the whole JS cost of /login. 2026-09-11: 3.51 MiB eager output = 2.14 MiB@@ -87,7 +89,7 @@ const ROOTS = [],},{- root: 'src/scenes/AuthenticatedShell.tsx',+ root: AUTHENTICATED_SHELL,label: 'authenticated shell (every logged-in page)',// 2026-09-11: 8.27 MiB eager output = 6.91 MiB JS (2688 files) + the 1.36 MiB linked// stylesheet. ~15% headroom so routine churn doesn't trip the warn.@@ -274,7 +276,7 @@ function eagerChunkClosure(entry) {// The page links only the src/index.tsx entry's stylesheet (writePreloadManifest in build.mjs). esbuild// gives other chunks a `cssBundle` too, but the browser never downloads those files.-const linkedStylesheet = outputs[entryChunk('src/index.tsx')]?.cssBundle+const linkedStylesheet = outputs[entryChunk(ENTRY)]?.cssBundleconst summaryLines = ['## Eager graph check', '', '| Root | Eager size | Budget | Files |', '| --- | --- | --- | --- |']const report = { roots: [], errors: [], warnings: [] }diff --git a/frontend/bin/stableCss.mjs b/frontend/bin/stableCss.mjsnew file mode 100644index 000000000000..b681182c4aed--- /dev/null+++ b/frontend/bin/stableCss.mjs@@ -0,0 +1,53 @@+import path from 'node:path'++import { commonConfig, esbuildBuild } from '@posthog/esbuilder'++/**+ * Builds every group with the app's own esbuild plugins (Sass, Tailwind, PostCSS), so each+ * stylesheet holds exactly the CSS the entry stylesheet holds for those files. Returns+ * group name -> file name in `dist/`.+ */+export async function buildCssGroups(absWorkingDir, groups) {+ const result = await esbuildBuild({+ ...commonConfig,+ absWorkingDir,+ entryPoints: Object.fromEntries([...groups.keys()].map((name) => [`styles-${name}`, `css-group:${name}`])),+ outdir: path.resolve(absWorkingDir, 'dist'),+ entryNames: '[name]-[hash]',+ bundle: true,+ write: true,+ metafile: true,+ logLevel: 'error',+ plugins: [+ {+ name: 'css-groups',+ setup(build) {+ build.onResolve({ filter: /^css-group:/ }, (args) => ({+ path: args.path.slice('css-group:'.length),+ namespace: 'css-group',+ }))+ build.onLoad({ filter: /.*/, namespace: 'css-group' }, (args) => ({+ contents: groups+ .get(args.path)+ .map((file) => `@import ${JSON.stringify(path.resolve(absWorkingDir, file))};`)+ .join('\n'),+ loader: 'css',+ resolveDir: absWorkingDir,+ }))+ },+ },+ ...commonConfig.plugins,+ ],+ })+ const fileOfGroup = new Map()+ for (const [file, output] of Object.entries(result.metafile.outputs)) {+ const match = output.entryPoint?.match(/^css-group:(.+)$/)+ if (match && file.endsWith('.css')) {+ fileOfGroup.set(match[1], path.basename(file))+ }+ }+ if (fileOfGroup.size !== groups.size) {+ throw new Error(`stable css: built ${fileOfGroup.size} of ${groups.size} stylesheets`)+ }+ return fileOfGroup+}diff --git a/frontend/bin/stableCssPlan.mjs b/frontend/bin/stableCssPlan.mjsnew file mode 100644index 000000000000..e8dc10288102--- /dev/null+++ b/frontend/bin/stableCssPlan.mjs@@ -0,0 +1,180 @@+import { CSS_LOAD_GLOBAL } from '@posthog/esbuilder/cssLoader.mjs'+import { chunkIdentity, shortHash } from '@posthog/esbuilder/stableChunkNames.mjs'++import { BOOT_ENTRIES, ENTRY } from './bootEntries.mjs'++/**+ * Split stylesheets for the stable build.+ *+ * esbuild puts the CSS of every chunk, lazy ones included, into the entry's stylesheet, so every+ * page downloads and parses all of the app's CSS before its first render. This step splits the+ * same CSS into groups and builds each group as its own stylesheet, named by its own content:+ *+ * - Eager layers hold the CSS that the boot chain (entry, App, bootApp, AuthenticatedShell) imports+ * statically. The stable page links them in order before the first render.+ * - Lazy groups hold the rest, grouped by the JS chunks whose modules import it. A lazy entry+ * chunk waits for the groups its static imports need before it runs (see `cssPrelude`).+ *+ * Groups keep today's rule order among themselves, because every group lists its files in the+ * order of the entry stylesheet. Lazy groups load after the eager layers.+ */++export const CSS_SPECIFIER_PREFIX = '@css/'++const isStylesheet = (file) => /\.(css|scss|sass)$/.test(file)++function eagerLayer(file) {+ if (file.endsWith('tailwind/tailwind.css')) {+ return 'eager-tailwind'+ }+ if (file.endsWith('src/styles/global.scss')) {+ return 'eager-global'+ }+ return 'eager-app'+}+const EAGER_ORDER = ['eager-tailwind', 'eager-global', 'eager-app']++/**+ * Plans the groups from the app build's metafile. Pure.+ *+ * Returns `groups` (name -> source files in rule order), `eager` (layer names in link order) and+ * `lazyGroupsByEntry` (lazy entry output path -> the lazy groups its static imports need).+ */+export function planCssGroups({ inputs, outputs }, bootEntries = BOOT_ENTRIES) {+ const entryOutput = (entryPoint) =>+ Object.keys(outputs).find((file) => outputs[file].entryPoint === entryPoint && file.endsWith('.js'))+ const linkedStylesheet = outputs[entryOutput(ENTRY)]?.cssBundle+ if (!linkedStylesheet) {+ throw new Error('stable css: the entry has no stylesheet to split')+ }+ const order = Object.keys(outputs[linkedStylesheet].inputs)+ const rank = new Map(order.map((file, index) => [file, index]))++ const boot = new Set(bootEntries.filter((entry) => inputs[entry]))+ for (const queue = [...boot]; queue.length; ) {+ for (const imported of inputs[queue.shift()].imports || []) {+ if (imported.kind === 'import-statement' && inputs[imported.path] && !boot.has(imported.path)) {+ boot.add(imported.path)+ queue.push(imported.path)+ }+ }+ }++ const outputOfInput = new Map()+ for (const [file, output] of Object.entries(outputs)) {+ if (file.endsWith('.js')) {+ for (const input of Object.keys(output.inputs)) {+ outputOfInput.set(input, file)+ }+ }+ }+ const ownersOfStylesheet = new Map()+ for (const [file, input] of Object.entries(inputs)) {+ for (const imported of input.imports || []) {+ if (isStylesheet(imported.path) && outputOfInput.has(file)) {+ const owners = ownersOfStylesheet.get(imported.path) ?? new Set()+ owners.add(outputOfInput.get(file))+ ownersOfStylesheet.set(imported.path, owners)+ }+ }+ }++ const groups = new Map()+ const groupsOfChunk = new Map()+ // A lazy group is a run of adjacent files with the same owners, so it holds its rules in the+ // same order as the entry stylesheet. Merging non-adjacent files would move the rules of the+ // files between them. A run is named by its owners' identities, which do not change when code+ // does, and by its first file, so a file added elsewhere does not rename it.+ let previousOwnersKey = null+ let runName = null+ for (const file of order) {+ let name+ if (boot.has(file)) {+ name = eagerLayer(file)+ previousOwnersKey = null+ } else {+ const owners = [...(ownersOfStylesheet.get(file) ?? [])]+ const ownersKey = owners+ .map((owner) => chunkIdentity(outputs[owner]))+ .sort()+ .join('\n')+ if (ownersKey !== previousOwnersKey) {+ runName = `lazy-${shortHash(`${ownersKey}\n${file}`)}`+ previousOwnersKey = ownersKey+ }+ name = runName+ for (const owner of owners) {+ const names = groupsOfChunk.get(owner) ?? new Set()+ names.add(name)+ groupsOfChunk.set(owner, names)+ }+ }+ groups.set(name, [...(groups.get(name) ?? []), file])+ }++ // The layers link in EAGER_ORDER, which only matches the cascade while the boot stylesheets come+ // in that order in the entry stylesheet. Fail the build rather than reorder rules silently.+ const layerIndexes = order.filter((file) => boot.has(file)).map((file) => EAGER_ORDER.indexOf(eagerLayer(file)))+ if (layerIndexes.some((index, i) => i > 0 && index < layerIndexes[i - 1])) {+ throw new Error('stable css: boot stylesheets are not in layer order, so splitting them would reorder rules')+ }++ const firstRank = (name) => rank.get(groups.get(name)[0])+ const lazyGroupsByEntry = new Map()+ const bootOutputs = new Set(bootEntries.map(entryOutput))+ for (const [file, output] of Object.entries(outputs)) {+ if (!file.endsWith('.js') || !output.entryPoint || bootOutputs.has(file)) {+ continue+ }+ const needed = new Set()+ const seen = new Set([file])+ for (const queue = [file]; queue.length; ) {+ const current = queue.shift()+ for (const name of groupsOfChunk.get(current) ?? []) {+ needed.add(name)+ }+ for (const imported of outputs[current].imports || []) {+ if (imported.kind === 'import-statement' && outputs[imported.path] && !seen.has(imported.path)) {+ seen.add(imported.path)+ queue.push(imported.path)+ }+ }+ }+ if (needed.size) {+ lazyGroupsByEntry.set(+ file,+ [...needed].sort((a, b) => firstRank(a) - firstRank(b))+ )+ }+ }++ const eager = EAGER_ORDER.filter((name) => groups.has(name))+ // A lazy prelude would call the undefined window.ESBUILD_LOAD_CSS if there's no eager layer to define it.+ if (lazyGroupsByEntry.size > 0 && eager.length === 0) {+ throw new Error('stable css: lazy chunks need split CSS but no eager layer would define the loader')+ }++ // Each group's place in the entry stylesheet, so the loader can keep lazy groups in that order+ // whatever order scenes load them in.+ const rankOfGroup = new Map([...groups.keys()].map((name) => [name, firstRank(name)]))+ return { groups, eager, lazyGroupsByEntry, rankOfGroup }+}++/**+ * The line a lazy entry chunk starts with: it waits for its stylesheets before any of its code+ * runs, so the chunk never renders unstyled. `import.meta.resolve` reads each group's URL from the+ * import map, and the group's rank tells the loader where to insert it.+ *+ * A browser without `import.meta.resolve` (Chromium 89 to 104 has import maps but not this) gets+ * the full stylesheet instead. When even that fails, the chunk throws a ChunkLoadError, so the+ * app's chunk-load recovery runs, not an unstyled scene.+ */+export function cssPrelude(groupNames, rankOfGroup) {+ const entries = groupNames.map(+ (name) => `[import.meta.resolve(${JSON.stringify(CSS_SPECIFIER_PREFIX + name)}),${rankOfGroup.get(name)}]`+ )+ return (+ `if(!(await window.${CSS_LOAD_GLOBAL}(typeof import.meta.resolve=="function"?[${entries.join(',')}]:null)))` ++ `throw Object.assign(new Error("Stylesheets for this chunk did not load"),{name:"ChunkLoadError"});`+ )+}diff --git a/frontend/bin/stableCssPlan.test.ts b/frontend/bin/stableCssPlan.test.tsnew file mode 100644index 000000000000..8330ec9184d2--- /dev/null+++ b/frontend/bin/stableCssPlan.test.ts@@ -0,0 +1,227 @@+import { CSS_LOAD_GLOBAL } from '@posthog/esbuilder/cssLoader.mjs'++import { cssPrelude, planCssGroups } from './stableCssPlan.mjs'++const imports = (...paths: string[]): { imports: { path: string; kind: string }[] } => ({+ imports: paths.map((path) => ({ path, kind: 'import-statement' })),+})++// A boot chain that imports Tailwind, the global styles and a button stylesheet, and one lazy scene+// that imports its own stylesheet and a shared chunk with a stylesheet of its own.+const METAFILE = {+ inputs: {+ 'src/index.tsx': imports('../common/tailwind/tailwind.css', 'src/styles/global.scss'),+ 'src/scenes/App.tsx': imports('src/lib/Button.scss'),+ 'src/scenes/Scene.tsx': imports('src/lib/Shared.tsx', 'src/scenes/Scene.scss'),+ 'src/lib/Shared.tsx': imports('src/lib/Shared.scss'),+ '../common/tailwind/tailwind.css': imports(),+ 'src/styles/global.scss': imports(),+ 'src/lib/Button.scss': imports(),+ 'src/lib/Shared.scss': imports(),+ 'src/scenes/Scene.scss': imports(),+ },+ outputs: {+ 'dist/index-A.js': {+ entryPoint: 'src/index.tsx',+ cssBundle: 'dist/index-A.css',+ inputs: { 'src/index.tsx': {} },+ },+ 'dist/index-A.css': {+ inputs: {+ '../common/tailwind/tailwind.css': {},+ 'src/styles/global.scss': {},+ 'src/lib/Button.scss': {},+ 'src/lib/Shared.scss': {},+ 'src/scenes/Scene.scss': {},+ },+ },+ 'dist/App-B.js': { entryPoint: 'src/scenes/App.tsx', inputs: { 'src/scenes/App.tsx': {} } },+ 'dist/Scene-C.js': {+ entryPoint: 'src/scenes/Scene.tsx',+ inputs: { 'src/scenes/Scene.tsx': {} },+ imports: [{ path: 'dist/chunk-D.js', kind: 'import-statement' }],+ },+ 'dist/chunk-D.js': { inputs: { 'src/lib/Shared.tsx': {} } },+ },+}++describe('planCssGroups', () => {+ it('links the boot chain CSS as ordered eager layers', () => {+ const { groups, eager } = planCssGroups(METAFILE)++ expect(eager.map((name: string) => groups.get(name))).toEqual([+ ['../common/tailwind/tailwind.css'],+ ['src/styles/global.scss'],+ ['src/lib/Button.scss'],+ ])+ })++ // A scene that did not wait for its shared chunk's stylesheet would render part of itself unstyled.+ it('makes a lazy entry wait for the CSS of the shared chunks it imports, in rule order', () => {+ const { groups, lazyGroupsByEntry } = planCssGroups(METAFILE)++ expect(lazyGroupsByEntry.get('dist/Scene-C.js').map((name: string) => groups.get(name))).toEqual([+ ['src/lib/Shared.scss'],+ ['src/scenes/Scene.scss'],+ ])+ expect(lazyGroupsByEntry.has('dist/App-B.js')).toBe(false)+ })++ it('fails rather than reorder rules when boot stylesheets are out of layer order', () => {+ const outOfOrder = {+ ...METAFILE,+ outputs: {+ ...METAFILE.outputs,+ 'dist/index-A.css': {+ inputs: {+ 'src/styles/global.scss': {},+ '../common/tailwind/tailwind.css': {},+ 'src/lib/Button.scss': {},+ },+ },+ },+ }++ expect(() => planCssGroups(outOfOrder)).toThrow('boot stylesheets are not in layer order')+ })++ // A lazy chunk needs an eager layer to define window.ESBUILD_LOAD_CSS before its prelude can call it.+ it('fails rather than ship a lazy prelude with no eager loader to call', () => {+ const noEagerCss = {+ inputs: {+ 'src/index.tsx': imports(),+ 'src/scenes/App.tsx': imports(),+ 'src/scenes/Scene.tsx': imports('src/scenes/Scene.scss'),+ 'src/scenes/Scene.scss': imports(),+ },+ outputs: {+ 'dist/index-A.js': {+ entryPoint: 'src/index.tsx',+ cssBundle: 'dist/index-A.css',+ inputs: { 'src/index.tsx': {} },+ },+ 'dist/index-A.css': { inputs: { 'src/scenes/Scene.scss': {} } },+ 'dist/App-B.js': { entryPoint: 'src/scenes/App.tsx', inputs: { 'src/scenes/App.tsx': {} } },+ 'dist/Scene-C.js': { entryPoint: 'src/scenes/Scene.tsx', inputs: { 'src/scenes/Scene.tsx': {} } },+ },+ }++ expect(() => planCssGroups(noEagerCss)).toThrow('no eager layer would define the loader')+ })++ // Merging the scene's two stylesheets would move Shared.scss's rules ahead of the second one.+ it('keeps same-owner stylesheets separate when another group sits between them', () => {+ const interleaved = {+ inputs: {+ ...METAFILE.inputs,+ 'src/scenes/Scene.tsx': imports(+ 'src/lib/Shared.tsx',+ 'src/scenes/Scene.scss',+ 'src/scenes/SceneExtra.scss'+ ),+ 'src/scenes/SceneExtra.scss': imports(),+ },+ outputs: {+ ...METAFILE.outputs,+ 'dist/index-A.css': {+ inputs: {+ '../common/tailwind/tailwind.css': {},+ 'src/styles/global.scss': {},+ 'src/lib/Button.scss': {},+ 'src/scenes/Scene.scss': {},+ 'src/lib/Shared.scss': {},+ 'src/scenes/SceneExtra.scss': {},+ },+ },+ },+ }+ const { groups, lazyGroupsByEntry, rankOfGroup } = planCssGroups(interleaved)++ expect(lazyGroupsByEntry.get('dist/Scene-C.js').map((name: string) => groups.get(name))).toEqual([+ ['src/scenes/Scene.scss'],+ ['src/lib/Shared.scss'],+ ['src/scenes/SceneExtra.scss'],+ ])+ // Ranks follow the entry stylesheet's order, so the loader can place a lazy group among others+ // whatever order scenes load them in, even though another chunk's group (Shared.scss) sits+ // between this chunk's own two groups (Scene.scss and SceneExtra.scss).+ const [sceneGroup, sharedGroup, extraGroup] = lazyGroupsByEntry.get('dist/Scene-C.js')+ expect([rankOfGroup.get(sceneGroup), rankOfGroup.get(sharedGroup), rankOfGroup.get(extraGroup)]).toEqual([+ 3, 4, 5,+ ])+ })+})++describe('cssPrelude', () => {+ // A prelude that resolved a wrong URL, dropped a rank, or swapped the ternary branches would+ // still pass planCssGroups' own tests, since those never evaluate the generated string.+ async function runPrelude(+ groupNames: string[],+ rankOfGroup: Map<string, number>,+ {+ hasImportMetaResolve = true,+ loadCss,+ }: { hasImportMetaResolve?: boolean; loadCss: (entries: unknown) => Promise<boolean> }+ ): Promise<{ error?: Error }> {+ const win: Record<string, unknown> = { [CSS_LOAD_GLOBAL]: loadCss }+ const importMeta = hasImportMetaResolve ? { resolve: (specifier: string) => `resolved:${specifier}` } : {}+ // `import.meta` is only valid inside a module, so a plain Function body can't reference it+ // directly: stub it in as a parameter instead. In production this prelude runs inside an+ // ES module chunk, loaded via dynamic import, which a plain Function body can't replicate.+ const body = cssPrelude(groupNames, rankOfGroup).replace(/import\.meta/g, 'importMeta')+ try {+ await new Function('window', 'importMeta', `return (async () => { ${body} })()`)(win, importMeta)+ return {}+ } catch (error) {+ return { error: error as Error }+ }+ }++ it('resolves each group to its import-map URL and rank, in the order given', async () => {+ const rankOfGroup = new Map([+ ['lazy-a', 3],+ ['lazy-b', 1],+ ])+ let seenEntries: unknown+ await runPrelude(['lazy-a', 'lazy-b'], rankOfGroup, {+ loadCss: (entries) => {+ seenEntries = entries+ return Promise.resolve(true)+ },+ })++ expect(seenEntries).toEqual([+ ['resolved:@css/lazy-a', 3],+ ['resolved:@css/lazy-b', 1],+ ])+ })++ it.each([+ { loadResult: true, expectedErrorName: undefined },+ { loadResult: false, expectedErrorName: 'ChunkLoadError' },+ ])(+ 'throws a ChunkLoadError only when the stylesheets fail to load (loadCss resolves $loadResult)',+ async ({ loadResult, expectedErrorName }) => {+ const { error } = await runPrelude(['lazy-a'], new Map([['lazy-a', 0]]), {+ loadCss: () => Promise.resolve(loadResult),+ })++ expect(error?.name).toBe(expectedErrorName)+ }+ )++ // A browser without import.meta.resolve cannot look up group URLs, so the prelude asks for the+ // full stylesheet instead of resolving anything.+ it('requests the full stylesheet instead when import.meta.resolve is unavailable', async () => {+ let seenEntries: unknown = 'not called'+ await runPrelude(['lazy-a'], new Map([['lazy-a', 0]]), {+ hasImportMetaResolve: false,+ loadCss: (entries) => {+ seenEntries = entries+ return Promise.resolve(true)+ },+ })++ expect(seenEntries).toBeNull()+ })+})diff --git a/frontend/build.mjs b/frontend/build.mjsindex e7ea9a2042e0..c22ffb7a0346 100755--- a/frontend/build.mjs+++ b/frontend/build.mjs@@ -16,6 +16,8 @@ import {} from '@posthog/esbuilder'import { writeStableChunks } from '@posthog/esbuilder/stableChunkNames.mjs'+import { buildCssGroups } from './bin/stableCss.mjs'+import { cssPrelude, CSS_SPECIFIER_PREFIX, planCssGroups } from './bin/stableCssPlan.mjs'import { finalizeToolbarBuild, getToolbarAppBuildConfig } from './toolbar-config.mjs'import { WORKER_ENTRIES } from './workers.config.mjs'@@ -113,12 +115,25 @@ await buildInParallel(const preloadManifest = writePreloadManifest(buildResponse.outputs)// A throw here must fail the build: it reaches buildInParallel's catch, which// exits non-zero for non-dev builds. Keep it in this awaited call chain.+ // The stable build also splits the app's CSS: see bin/stableCss.mjs.+ const cssPlan = planCssGroups(buildResponse)+ const cssFiles = await buildCssGroups(__dirname, cssPlan.groups)stable = writeStableChunks({absWorkingDir: __dirname,outputs: buildResponse.outputs,chunks,entrypoints,preloadManifest,+ preludes: new Map(+ [...cssPlan.lazyGroupsByEntry].map(([file, groups]) => [+ file,+ cssPrelude(groups, cssPlan.rankOfGroup),+ ])+ ),+ extraImports: Object.fromEntries(+ [...cssFiles].map(([group, file]) => [`${CSS_SPECIFIER_PREFIX}${group}`, `static/${file}`])+ ),+ eagerCss: cssPlan.eager.map((group) => cssFiles.get(group)),})}writeIndexHtml(chunks, entrypoints, stable)diff --git a/frontend/src/index.html b/frontend/src/index.htmlindex f6c4640c6767..97d127ede7cc 100644--- a/frontend/src/index.html+++ b/frontend/src/index.html@@ -36,6 +36,9 @@{# to a single copy. crossorigin matches the loader's fetch mode so one response is reused. #}<link rel="preload" href="{{ js_url }}/{{ preload_css_url }}" as="style" crossorigin="anonymous">{% endif %}+ {% for url in stable_preload_css_urls %}+ <link rel="preload" href="{{ js_url }}/{{ url }}" as="style" crossorigin="anonymous">+ {% endfor %}{# Stable chunk names (opt-in, see posthog/stable_chunks.py): the import map must come before #}{# the modulepreload hints below, because browsers ignore an import map added after module #}{# loading has started. #}diff --git a/posthog/stable_chunks.py b/posthog/stable_chunks.pyindex b84dbed28981..1ff23d317865 100644--- a/posthog/stable_chunks.py+++ b/posthog/stable_chunks.py@@ -37,6 +37,8 @@ class StableChunks:imports: dict[str, str]preload_js_urls: tuple[str, ...]authenticated_preload_js_urls: tuple[str, ...]+ # The split eager stylesheets, in link order. Empty for a build that does not split its CSS.+ eager_css_urls: tuple[str, ...] = ()def import_map_json(self, js_url: str) -> str:import_map = json.dumps(@@ -65,19 +67,22 @@ def read_stable_chunks_manifest(manifest_path: str) -> Optional[StableChunks]:preload = manifest.get("preload", {})js = preload.get("js", [])authenticated_js = preload.get("authenticatedJs", [])+ eager_css = manifest.get("eagerCss", [])if not (isinstance(imports, dict)and importsand all(isinstance(k, str) and isinstance(v, str) for k, v in imports.items())and isinstance(js, list)and isinstance(authenticated_js, list)- and all(isinstance(url, str) for url in [*js, *authenticated_js])+ and isinstance(eager_css, list)+ and all(isinstance(url, str) for url in [*js, *authenticated_js, *eager_css])):raise ValueError("stable chunks manifest fields have unexpected types")return StableChunks(imports=imports,preload_js_urls=tuple(js),authenticated_preload_js_urls=tuple(authenticated_js),+ eager_css_urls=tuple(eager_css),)except Exception as e:logger.warning("stable_chunks_manifest_unreadable", manifest_path=manifest_path, error=str(e))diff --git a/posthog/test/test_stable_chunks.py b/posthog/test/test_stable_chunks.pyindex d228d8c0fa53..201127675765 100644--- a/posthog/test/test_stable_chunks.py+++ b/posthog/test/test_stable_chunks.py@@ -3,24 +3,28 @@ import tempfilefrom pathlib import Pathfrom posthog.test.base import APIBaseTest+from unittest.mock import patch+from django.contrib.auth.models import AnonymousUserfrom django.contrib.sessions.middleware import SessionMiddlewarefrom django.http import HttpResponse-from django.test import RequestFactory, SimpleTestCase+from django.test import RequestFactory, SimpleTestCase, override_settingsfrom parameterized import parameterizedfrom posthog.stable_chunks import (STABLE_CHUNKS_COOKIE,+ StableChunks,persist_stable_chunks_choice,read_stable_chunks_manifest,stable_chunks_opted_in,)-from posthog.utils import render_template+from posthog.utils import get_context_for_template, render_templateVALID_MANIFEST = {"imports": {"@c/eAAAA": "static/index-S0000000000.js"},"preload": {"js": ["static/index-S0000000000.js"], "authenticatedJs": ["static/chunk-S1111111111.js"]},+ "eagerCss": ["static/styles-eager-tailwind-AAAA1111.css", "static/styles-eager-app-BBBB2222.css"],}@@ -31,6 +35,7 @@ class TestStableChunks(SimpleTestCase):("imports is not a mapping", {**VALID_MANIFEST, "imports": ["static/index.js"]}, False),("empty imports", {**VALID_MANIFEST, "imports": {}}, False),("preload url is not a string", {**VALID_MANIFEST, "preload": {"js": [1], "authenticatedJs": []}}, False),+ ("eager css url is not a string", {**VALID_MANIFEST, "eagerCss": [1]}, False),])def test_manifest_problems_fall_back_to_the_default_build(self, _name, manifest, expect_stable):@@ -46,6 +51,10 @@ class TestStableChunks(SimpleTestCase):"imports": {"@c/eAAAA": "https://cdn.example.com/static/index-S0000000000.js"}}assert stable.preload_urls(include_authenticated_shell=False) == ("static/index-S0000000000.js",)+ assert stable.eager_css_urls == (+ "static/styles-eager-tailwind-AAAA1111.css",+ "static/styles-eager-app-BBBB2222.css",+ )def test_import_map_cannot_close_its_script_tag(self):with tempfile.TemporaryDirectory() as directory:@@ -92,6 +101,39 @@ class TestStableChunks(SimpleTestCase):# Only the server reads the choice, so scripts on the page never need it.assert cookie["httponly"] is True+ def _context_with_stable_chunks(self, stable: StableChunks) -> dict:+ # no-preloaded-app-context and E2E_TESTING skip the request's team/user lookups, which need+ # a database that a SimpleTestCase cannot use.+ request = RequestFactory().get("/?no-preloaded-app-context=1")+ request.user = AnonymousUser()+ with (+ override_settings(E2E_TESTING=True),+ patch("posthog.utils.stable_chunks_for_request", return_value=stable),+ ):+ return get_context_for_template("index.html", request)++ def test_eager_css_urls_replace_the_single_preload_link(self):+ stable = StableChunks(+ imports={"@c/eAAAA": "static/index-S0000000000.js"},+ preload_js_urls=(),+ authenticated_preload_js_urls=(),+ eager_css_urls=("static/styles-eager-tailwind-AAAA1111.css", "static/styles-eager-app-BBBB2222.css"),+ )++ context = self._context_with_stable_chunks(stable)++ assert context["preload_css_url"] == ""+ assert context["stable_preload_css_urls"] == stable.eager_css_urls++ def test_no_eager_css_urls_keeps_the_single_preload_link(self):+ stable = StableChunks(+ imports={"@c/eAAAA": "static/index-S0000000000.js"}, preload_js_urls=(), authenticated_preload_js_urls=()+ )++ context = self._context_with_stable_chunks(stable)++ assert "stable_preload_css_urls" not in context+class TestStableChunksChoiceSurvivesTheRequest(APIBaseTest):@parameterized.expand([("opting in", "1"), ("opting out", "0")])diff --git a/posthog/utils.py b/posthog/utils.pyindex f4bb180a7330..23e5c9fb3aeb 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -751,6 +751,10 @@ def _build_template_context(context["stable_chunks"] = Truecontext["stable_chunks_importmap"] = stable_chunks.import_map_json(context["js_url"])context["preload_js_urls"] = stable_chunks.preload_urls(is_authenticated)+ if stable_chunks.eager_css_urls:+ # The stable page links its split stylesheets and loads the full one only as a fallback.+ context["preload_css_url"] = ""+ context["stable_preload_css_urls"] = stable_chunks.eager_css_urls# Theme for the pre-React shell (critical CSS in index.html), mirroring the app's# themeLogic.isDarkModeOn: anonymous pages are always light, a missing theme_mode# means light, and only "system" defers to prefers-color-scheme.