Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for app global and segment 404 pages #49085

Merged
merged 18 commits into from
May 3, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ declare global {
}

import type { Ipc } from '@vercel/turbopack-node/ipc/index'
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { IncomingMessage } from 'node:http'
import type {
ClientCSSReferenceManifest,
ClientReferenceManifest,
Expand All @@ -25,13 +25,13 @@ import type { RenderOpts } from 'next/dist/server/app-render/types'

import { renderToHTMLOrFlight } from 'next/dist/server/app-render/app-render'
import { RSC_VARY_HEADER } from 'next/dist/client/components/app-router-headers'
import { ServerResponseShim } from '../internal/http'
import { headersFromEntries } from '../internal/headers'
import { parse, ParsedUrlQuery } from 'node:querystring'
import { PassThrough } from 'node:stream'
;('TURBOPACK { transition: next-layout-entry; chunking-type: isolatedParallel }')
// @ts-ignore
import layoutEntry from './app/layout-entry'
import { createServerResponse } from '../internal/http'

globalThis.__next_require__ = (data) => {
const [, , ssr_id] = JSON.parse(data)
Expand Down Expand Up @@ -91,7 +91,7 @@ const MIME_TEXT_HTML_UTF8 = 'text/html; charset=utf-8'
ipc.send({
type: 'headers',
data: {
status: 200,
status: result.statusCode,
headers: result.headers,
},
})
Expand Down Expand Up @@ -124,8 +124,6 @@ type LoaderTree = [
]

async function runOperation(renderData: RenderData) {
let tree: LoaderTree = LOADER_TREE

const proxyMethodsForModule = (
id: string
): ProxyHandler<ClientReferenceManifest['ssrModuleMapping']> => {
Expand Down Expand Up @@ -251,7 +249,9 @@ async function runOperation(renderData: RenderData) {
method: renderData.method,
headers: headersFromEntries(renderData.rawHeaders),
} as any
const res: ServerResponse = new ServerResponseShim(req) as any

const res = createServerResponse(req, renderData.path)

const query = parse(renderData.rawQuery)
const renderOpt: Omit<
RenderOpts,
Expand Down Expand Up @@ -304,6 +304,7 @@ async function runOperation(renderData: RenderData) {
body.write(result.toUnchunkedString())
}
return {
statusCode: res.statusCode,
headers: [
['Content-Type', result.contentType() ?? MIME_TEXT_HTML_UTF8],
['Vary', RSC_VARY_HEADER],
Expand Down
28 changes: 27 additions & 1 deletion packages/next-swc/crates/next-core/js/src/internal/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http'
*
* @type {ServerResponse}
*/
export class ServerResponseShim {
class ServerResponseShim {
headersSent = false
#headers: Map<string, number | string | ReadonlyArray<string>> = new Map()
#statusCode: number = 200
Expand Down Expand Up @@ -112,3 +112,29 @@ export class ServerResponseShim {
throw new Error('writeProcessing is not implemented')
}
}

function getStatusCodeForPath(pathname: string): number {
if (pathname === '/404' || pathname === '/_error') {
return 404
}

return 200
}

/**
* Creates a `ServerResponse` object for a given request and pathname.
*/
export function createServerResponse(
req: IncomingMessage,
pathname: string
): ServerResponse {
const statusCode = getStatusCodeForPath(pathname)

const res = new ServerResponseShim(req) as any

// For pages, setting the status code on the response object is necessary for
// `Error.getInitialProps` to detect the status code.
res.statusCode = statusCode

return res as ServerResponse
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import { buildStaticPaths } from 'next/dist/build/utils'
import type { BuildManifest } from 'next/dist/server/get-page-files'
import type { ReactLoadableManifest } from 'next/dist/server/load-components'

import { ServerResponseShim } from './http'
import { headersFromEntries } from './headers'
import { createServerResponse } from './http'
import type { Ipc } from '@vercel/turbopack-node/ipc/index'
import type { RenderData } from 'types/turbopack'
import type { ChunkGroup } from 'types/next'
Expand Down Expand Up @@ -220,19 +220,7 @@ export default function startHandler({
method: 'GET',
headers: headersFromEntries(renderData.rawHeaders),
} as any
const res: ServerResponse = new ServerResponseShim(req) as any

// Both _error and 404 should receive a 404 status code.
const statusCode =
renderData.path === '/404'
? 404
: renderData.path === '/_error'
? 404
: 200

// Setting the status code on the response object is necessary for
// `Error.getInitialProps` to detect the status code.
res.statusCode = statusCode
const res: ServerResponse = createServerResponse(req, renderData.path)

const parsedQuery = parse(renderData.rawQuery)
const query = { ...parsedQuery, ...renderData.params }
Expand Down Expand Up @@ -298,7 +286,7 @@ export default function startHandler({
const pageData = renderResult.metadata().pageData
return {
type: 'response',
statusCode,
statusCode: res.statusCode,
headers: [['Content-Type', MIME_APPLICATION_JAVASCRIPT]],
// Page data is only returned if the page had getXxyProps.
body: JSON.stringify(pageData === undefined ? {} : pageData),
Expand All @@ -316,7 +304,7 @@ export default function startHandler({

return {
type: 'response',
statusCode,
statusCode: res.statusCode,
headers: [
['Content-Type', renderResult.contentType() ?? MIME_TEXT_HTML_UTF8],
],
Expand Down
70 changes: 67 additions & 3 deletions packages/next-swc/crates/next-core/src/app_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ use crate::{
transition::NextEdgeTransition,
},
next_image::module::{BlurPlaceholderMode, StructuredImageModuleType},
next_route_matcher::NextParamsMatcherVc,
next_route_matcher::{NextFallbackMatcherVc, NextParamsMatcherVc},
next_server::context::{
get_server_compile_time_info, get_server_module_options_context,
get_server_resolve_options_context, ServerContextType,
Expand Down Expand Up @@ -426,8 +426,8 @@ pub async fn create_app_source(
);
let render_data = render_data(next_config);

let sources = entrypoints
.await?
let entrypoints = entrypoints.await?;
let mut sources: Vec<_> = entrypoints
.iter()
.map(|(pathname, &loader_tree)| match loader_tree {
Entrypoint::AppPage { loader_tree } => create_app_page_source_for_route(
Expand Down Expand Up @@ -464,6 +464,27 @@ pub async fn create_app_source(
)))
.collect();

if let Some(&Entrypoint::AppPage { loader_tree }) = entrypoints.get("/") {
if let Some(_) = loader_tree.await?.components.await?.not_found {
// Only add a source for the app 404 page if a top-level not-found page is
// defined. Otherwise, the 404 page is handled by the pages logic.
let not_found_page_source = create_app_not_found_page_source(
loader_tree,
context_ssr,
context,
project_path,
app_dir,
env,
server_root,
server_runtime_entries,
fallback_page,
output_path,
render_data,
);
sources.push(not_found_page_source);
}
}

Ok(CombinedContentSource { sources }.cell().into())
}

Expand Down Expand Up @@ -555,6 +576,49 @@ async fn create_app_page_source_for_route(
Ok(source.issue_context(app_dir, &format!("Next.js App Page Route {pathname}")))
}

#[allow(clippy::too_many_arguments)]
#[turbo_tasks::function]
async fn create_app_not_found_page_source(
loader_tree: LoaderTreeVc,
context_ssr: AssetContextVc,
context: AssetContextVc,
project_path: FileSystemPathVc,
app_dir: FileSystemPathVc,
env: ProcessEnvVc,
server_root: FileSystemPathVc,
runtime_entries: AssetsVc,
fallback_page: DevHtmlAssetVc,
intermediate_output_path_root: FileSystemPathVc,
render_data: JsonValueVc,
) -> Result<ContentSourceVc> {
let pathname_vc = StringVc::cell("/404".to_string());

let source = create_node_rendered_source(
project_path,
env,
SpecificityVc::not_found(),
server_root,
NextFallbackMatcherVc::new().into(),
pathname_vc,
AppRenderer {
runtime_entries,
app_dir,
context_ssr,
context,
server_root,
project_path,
intermediate_output_path: intermediate_output_path_root,
loader_tree,
}
.cell()
.into(),
fallback_page,
render_data,
);

Ok(source.issue_context(app_dir, &format!("Next.js App Page Route /404")))
}

#[allow(clippy::too_many_arguments)]
#[turbo_tasks::function]
async fn create_app_route_source_for_route(
Expand Down
4 changes: 2 additions & 2 deletions packages/next-swc/crates/next-core/src/app_structure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ impl Components {
template: a.template.or(b.template),
not_found: a.not_found.or(b.not_found),
default: a.default.or(b.default),
route: a.default.or(b.route),
route: a.route.or(b.route),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes an unrelated bug.

metadata: Metadata::merge(&a.metadata, &b.metadata),
}
}
Expand Down Expand Up @@ -552,7 +552,7 @@ pub fn get_entrypoints(app_dir: FileSystemPathVc, page_extensions: StringsVc) ->
}

#[turbo_tasks::function]
pub fn directory_tree_to_entrypoints(
fn directory_tree_to_entrypoints(
app_dir: FileSystemPathVc,
directory_tree: DirectoryTreeVc,
) -> EntrypointsVc {
Expand Down
8 changes: 1 addition & 7 deletions packages/next-swc/crates/next-core/src/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,7 @@ impl DevManifestContentSourceVc {
let mut routes = routes
.into_iter()
.flatten()
.map(|s| {
if !s.starts_with('/') {
format!("/{}", s)
} else {
s.to_string()
}
})
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is no longer necessary as .get_pathname() will always return a pathname with a leading /.

.map(|route| route.clone_value())
.collect::<Vec<_>>();

routes.sort_by_cached_key(|s| s.split('/').map(PageSortKey::from).collect::<Vec<_>>());
Expand Down