Unverified Commit d2aa1b63 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[backport] Fix missing styled-jsx styles in Pages Router SSR on adapter builds (#97302)

Backports #96632 ("Fix missing styled-jsx styles in Pages Router SSR on
adapter builds") to `next-16-3`.

Cherry-picked from 2049354a with no
conflicts.

### Verification on this branch

- `cargo check -p next-api`, `cargo clippy -p next-api`, `cargo fmt
--check -p next-api` — clean
- `pnpm --filter=next types` — clean
- `test/production/adapter-styled-jsx` — passes with both Turbopack and
webpack
- `test/production/adapter-root`, `adapter-config`,
`adapter-config-i18n` — pass (no regression from the `trace_endpoint`
signature change)

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
Co-authored-by: 's avatarvercel-fleet[bot] <308483924+vercel-fleet[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent fc7ae172
......@@ -2061,6 +2061,7 @@ impl AppEndpoint {
Some(app_function_name(&app_entry.original_name).into()),
*module_graphs.full,
Vc::cell(entry_modules),
this.app_project.project().additional_traced_modules(),
))
}
}
......
......@@ -206,6 +206,7 @@ impl InstrumentationEndpoint {
None,
this.project.module_graph(*userland_module),
Vc::cell(vec![userland_module]),
this.project.additional_traced_modules(),
))
}
}
......
......@@ -345,6 +345,7 @@ impl MiddlewareEndpoint {
None,
this.project.module_graph(*userland_module),
Vc::cell(vec![userland_module]),
this.project.additional_traced_modules(),
))
}
}
......
......@@ -23,6 +23,48 @@ use turbopack_resolve::ecmascript::cjs_resolve;
use crate::{nft::traced_modules_for_entries, project::Project};
/// The modules `next/dist/server/require-hook` resolves its aliased requests to at runtime
/// (currently all of styled-jsx), so that the Pages Router renderer and user code share a single
/// `styled-jsx` module instance (see that file for why they otherwise wouldn't). Nothing in any
/// module graph references these - user code only ever imports its own copy of `styled-jsx` - so
/// whatever assembles a deployment's file list has to include them explicitly, or the hook fails
/// to register its aliases and all styled-jsx styles silently disappear from the server-rendered
/// HTML.
///
/// Used by the server NFTs below and, so that they are part of every endpoint's trace regardless
/// of how the output is assembled, by [`Project::additional_traced_modules`].
#[turbo_tasks::function]
pub(crate) async fn require_hook_modules(project_path: FileSystemPath) -> Result<Vc<Modules>> {
let asset_context = Vc::upcast(externals_tracing_module_context(
get_tracing_compile_time_info(),
false,
));
let next_resolve_origin = Vc::upcast(PlainResolveOrigin::new(
asset_context,
get_next_package(project_path).await?.join("_")?,
));
Ok(Vc::cell(
["styled-jsx", "styled-jsx/style", "styled-jsx/style.js"]
.into_iter()
.map(async |request| {
Ok(cjs_resolve(
next_resolve_origin,
Request::parse_string(request.into()),
CommonJsReferenceSubType::Undefined,
None,
ResolveErrorMode::Error,
)
.await?
.primary_modules()
.await?
.into_iter())
})
.try_flat_join()
.await?,
))
}
#[turbo_tasks::task_input]
#[derive(PartialEq, Eq, TraceRawVcs, Debug, Clone, Hash, Encode, Decode)]
enum ServerNftType {
......@@ -33,8 +75,12 @@ enum ServerNftType {
#[turbo_tasks::function]
pub async fn next_server_nft_assets(project: Vc<Project>) -> Result<Vc<OutputAssets>> {
if *project.next_config().is_using_adapter().await? {
// When using an adapter, we don't need to generate any server NFTs as build-complete
// doesn't use them at all.
// When using an adapter, `next-server.js.nft.json` / `next-minimal-server.js.nft.json` are
// not needed: they exist for `output: 'standalone'` (see `copyTracedFiles`), while an
// adapter assembles the deployment from the per-endpoint NFTs in build-complete.ts. What
// those two files trace on top of the endpoints - the `styled-jsx` modules the require hook
// needs at runtime - is part of every endpoint's trace via
// `Project::additional_traced_modules`, so nothing is lost here.
return Ok(Vc::cell(vec![]));
}
......@@ -218,9 +264,6 @@ impl ServerNftJsonAsset {
get_next_package(project_path.clone()).await?.join("_")?,
));
// These are used by packages/next/src/server/require-hook.ts
let shared_entries = ["styled-jsx", "styled-jsx/style", "styled-jsx/style.js"];
let entries = match self.ty {
ServerNftType::Full => Either::Left(
if is_standalone {
......@@ -242,25 +285,33 @@ impl ServerNftJsonAsset {
)),
};
// The modules the require hook needs are part of every endpoint's trace (see
// `Project::additional_traced_modules`), but `next-server.js` / `next-minimal-server.js`
// are traced on their own for `output: 'standalone'`, so they have to be added here too.
let hook_modules = require_hook_modules(project_path).owned().await?;
Ok(Vc::cell(
shared_entries
hook_modules
.into_iter()
.chain(entries)
.map(async |path| {
Ok(cjs_resolve(
next_resolve_origin,
Request::parse_string(path.into()),
CommonJsReferenceSubType::Undefined,
None,
ResolveErrorMode::Error,
)
.await?
.primary_modules()
.await?
.into_iter())
})
.try_flat_join()
.await?,
.chain(
entries
.map(async |path| {
Ok(cjs_resolve(
next_resolve_origin,
Request::parse_string(path.into()),
CommonJsReferenceSubType::Undefined,
None,
ResolveErrorMode::Error,
)
.await?
.primary_modules()
.await?
.into_iter())
})
.try_flat_join()
.await?,
)
.collect(),
))
}
......
......@@ -56,12 +56,19 @@ impl EndpointTraceResult {
}
}
/// Traces the files an endpoint needs at runtime.
///
/// `traced_entries` are modules that have to be traced even though nothing in `entry_modules`
/// references them, i.e. [`Project::additional_traced_modules`] - or
/// [`Project::pages_traced_modules`] for pages endpoints, which additionally need the modules the
/// require hook resolves at runtime.
#[turbo_tasks::function]
pub async fn trace_endpoint(
project: ResolvedVc<Project>,
page_name: Option<RcStr>,
module_graph: ResolvedVc<ModuleGraph>,
entry_modules: Vc<Modules>,
traced_entries: Vc<Modules>,
) -> Result<Vc<EndpointTraceResult>> {
let span = tracing::info_span!("trace endpoint", path = debug(&page_name));
async {
......@@ -73,8 +80,6 @@ pub async fn trace_endpoint(
.output_file_tracing_includes(project_path.clone())
.await?;
let traced_entries = project.additional_traced_modules();
// Collect referenced assets and externals from module graph
let all_modules = traced_modules_for_entries(
*module_graph,
......
......@@ -1619,6 +1619,9 @@ impl PageEndpoint {
Some(pages_function_name(&this.original_name).into()),
ssr_module_graph,
Vc::cell(vec![ssr_module]),
// The Pages Router renderer resolves `styled-jsx` through the require hook at
// runtime, so those modules have to be traced for pages endpoints.
this.pages_project.project().pages_traced_modules(),
))
}
}
......
......@@ -102,6 +102,7 @@ use crate::{
entrypoints::Entrypoints,
instrumentation::InstrumentationEndpoint,
middleware::MiddlewareEndpoint,
next_server_nft::require_hook_modules,
pages::PagesProject,
route::{
Endpoint, EndpointGroup, EndpointGroupEntry, EndpointGroupKey, EndpointGroups, Endpoints,
......@@ -1452,7 +1453,10 @@ impl Project {
.chain(std::iter::once(self.client_main_modules().owned().await?))
.chain(std::iter::once(GraphEntries::new(
vec![],
self.additional_traced_modules().owned().await?,
// The superset of what any endpoint traces, so that these modules and their
// references are part of the graph. Which endpoint actually traces them is
// decided by what is passed to `trace_endpoint`.
self.pages_traced_modules().owned().await?,
))),
);
......@@ -2841,6 +2845,26 @@ impl Project {
.await?,
))
}
/// [`Project::additional_traced_modules`] plus the modules
/// `next/dist/server/require-hook` resolves at runtime. Only the Pages Router needs the
/// latter, so this is the traced module list for pages endpoints, while other endpoints use
/// [`Project::additional_traced_modules`].
#[turbo_tasks::function]
pub async fn pages_traced_modules(self: Vc<Self>) -> Result<Vc<Modules>> {
let hook_modules = require_hook_modules(self.project_path().owned().await?)
.owned()
.await?;
Ok(Vc::cell(
self.additional_traced_modules()
.owned()
.await?
.into_iter()
.chain(hook_modules)
.collect(),
))
}
}
/// Scales down or shuts down the Node.js process pool after module graph computation.
......
......@@ -2410,7 +2410,7 @@ async function getSharedNodeAssets({
salt
)
// Turbopack handles this automatically and these files are listed in the nft.json files.
// Turbopack traces these itself, they are listed in the nft.json files.
if (bundler !== Bundler.Turbopack) {
const { nodeFileTrace } =
require('next/dist/compiled/@vercel/nft') as typeof import('next/dist/compiled/@vercel/nft')
......@@ -2443,6 +2443,8 @@ async function getSharedNodeAssets({
require.resolve('next/dist/server/node-environment'),
require.resolve('next/dist/server/require-hook'),
require.resolve('next/dist/server/node-polyfill-crypto'),
// Nothing references these, the require hook resolves them at runtime.
// Turbopack traces them via `Project::pages_traced_modules`.
...Object.values(defaultOverrides).filter((item) => path.extname(item)),
]
......
import path from 'path'
import fs from 'fs'
import { createRequire } from 'module'
import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
type BuildComplete = Parameters<NextAdapter['onBuildComplete']>[0]
describe('adapter output - styled-jsx', () => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixture'),
skipStart: true,
// This asserts on the output an adapter is handed locally (`build-complete.json`) and runs the
// app with only the files from that output, so it has to build and serve locally.
skipDeployment: true,
dependencies: {
// A version that does not dedupe with the one Next.js depends on, so the app gets its own
// copy of styled-jsx next to Next.js' copy. That is the case where the require hook in
// next/dist/server/require-hook is load-bearing: without it, user code and the Pages Router
// renderer end up with two styled-jsx instances, the style registry never receives anything
// and every style is silently missing from the server-rendered HTML.
'styled-jsx': '5.1.7',
},
})
if (skipped) return
let buildComplete: BuildComplete
/** Absolute paths of the files the adapter declares for the `/index` pages function. */
let declaredAssets: Set<string>
/** The files the require hook resolves, i.e. what it needs to be able to register its aliases. */
let requireHookFiles: string[]
beforeAll(async () => {
await next.build()
buildComplete = await next.readJSON('build-complete.json')
const indexOutput = buildComplete.outputs.pages.find(
(output) => output.id === '/index'
)
if (!indexOutput) {
throw new Error('missing pages output for /index')
}
declaredAssets = new Set(Object.values(indexOutput.assets))
// Resolve the same way next/dist/server/require-hook does at runtime: the aliases it registers
// (`defaultOverrides`), resolved from Next.js' own location inside the app that was built.
// Note that requiring the hook installs it in this process, which is what Next.js does at
// runtime as well.
const appRequire = createRequire(path.join(next.testDir, 'noop.js'))
const requireHookPath = appRequire.resolve('next/dist/server/require-hook')
const { defaultOverrides } = appRequire(
requireHookPath
) as typeof import('next/dist/server/require-hook')
const hookRequire = createRequire(requireHookPath)
requireHookFiles = [
...new Set(
Object.keys(defaultOverrides).map((request) =>
hookRequire.resolve(request)
)
),
]
})
it('should include the files the require hook resolves in the pages function output', async () => {
// Turbopack traces these via `Project::pages_traced_modules`, webpack via
// `getSharedNodeAssets` in build-complete.ts - either way they have to end up in the
// function's assets, otherwise the require hook can't dedupe styled-jsx at runtime.
expect(requireHookFiles.length).toBeGreaterThan(0)
for (const file of requireHookFiles) {
expect(Array.from(declaredAssets)).toContain(file)
}
})
it('should server render styled-jsx styles with only the declared assets present', async () => {
// Reduce styled-jsx to exactly what the build declared, i.e. what a deployment built from this
// output would contain. If a file the require hook resolves is missing, the hook fails, user
// code and the renderer load two different styled-jsx copies and the styles silently disappear
// from the SSR HTML - while the `jsx-*` class names are still rendered.
function removeUndeclaredFiles(dir: string) {
if (!fs.existsSync(dir)) return
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const entryPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
removeUndeclaredFiles(entryPath)
} else if (!declaredAssets.has(entryPath)) {
fs.rmSync(entryPath)
}
}
}
removeUndeclaredFiles(path.join(next.testDir, 'node_modules/styled-jsx'))
removeUndeclaredFiles(
path.join(next.testDir, 'node_modules/next/node_modules/styled-jsx')
)
await next.start()
const html = await next.render('/')
expect(html).toContain('<style id="__jsx-')
expect(html).toMatch(/color:\s*rebeccapurple/)
})
})
import fs from 'fs'
// @ts-check
/** @type {import('next').NextAdapter } */
const myAdapter = {
name: 'my-styled-jsx-adapter',
onBuildComplete: async (ctx) => {
await fs.promises.writeFile(
'build-complete.json',
JSON.stringify(ctx, null, 2)
)
},
}
export default myAdapter
/** @type {import('next').NextConfig} */
const nextConfig = {
adapterPath: require.resolve('./my-adapter.mjs'),
outputFileTracingRoot: __dirname,
turbopack: { root: __dirname },
}
module.exports = nextConfig
export default function Page({ color }) {
return (
<div>
<p className="hello">hello styled-jsx</p>
<style jsx>{`
.hello {
color: ${color};
}
`}</style>
</div>
)
}
export function getServerSideProps() {
return { props: { color: 'rebeccapurple' } }
}
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