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

Move Pages API rendering into bundle #52149

Merged
merged 25 commits into from
Jul 21, 2023
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
db61ef2
feat: move api rendering into bundle
wyattjoh Jul 3, 2023
2e76cdf
fix: revert change to context structure
wyattjoh Jul 3, 2023
9115852
fix: embed route build info to resolve tracing bug
wyattjoh Jul 3, 2023
9ba9810
Merge branch 'canary' into wyattjoh/NEXT-986
wyattjoh Jul 3, 2023
d4293d8
Merge branch 'canary' into wyattjoh/NEXT-986
wyattjoh Jul 4, 2023
5a237a7
Merge branch 'canary' into wyattjoh/NEXT-986
wyattjoh Jul 4, 2023
4889600
feat: improve error messaging around route loading
wyattjoh Jul 4, 2023
f0d4525
Merge branch 'canary' into wyattjoh/NEXT-986
wyattjoh Jul 4, 2023
6e04025
Merge branch 'canary' into wyattjoh/NEXT-986
timneutkens Jul 6, 2023
2848ce5
Merge branch 'canary' into wyattjoh/NEXT-986
wyattjoh Jul 7, 2023
d681831
Merge branch 'canary' into wyattjoh/NEXT-986
wyattjoh Jul 12, 2023
750c776
Merge branch 'canary' into wyattjoh/NEXT-986
wyattjoh Jul 12, 2023
a5fb25d
refactor: simplified imports for Document, App
wyattjoh Jul 13, 2023
850b7cc
fix: fixed import order to preserve side-effect invocation order
wyattjoh Jul 13, 2023
7dff5b8
feat: add support to emit routeModule in Turbopack builds
wyattjoh Jul 13, 2023
31941d3
Merge branch 'canary' into wyattjoh/NEXT-986
wyattjoh Jul 14, 2023
90f3fc7
feat: refactored code generator
wyattjoh Jul 14, 2023
989dd95
fix: fixed incorrect module
wyattjoh Jul 14, 2023
ef8255d
Merge branch 'canary' into wyattjoh/NEXT-986
wyattjoh Jul 14, 2023
c0576dc
Merge branch 'canary' into wyattjoh/NEXT-986
wyattjoh Jul 17, 2023
642bc57
fix: review updates to rust
wyattjoh Jul 17, 2023
647187c
fix: rust linting
wyattjoh Jul 17, 2023
041cd60
Merge branch 'canary' into wyattjoh/NEXT-986
wyattjoh Jul 19, 2023
8cc3eeb
Merge branch 'canary' into wyattjoh/NEXT-986
wyattjoh Jul 19, 2023
e8b2319
Merge branch 'canary' into wyattjoh/NEXT-986
ijjk Jul 21, 2023
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
146 changes: 142 additions & 4 deletions packages/next-swc/crates/next-build/src/next_pages/page_entries.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
use std::io::Write;

use anyhow::{bail, Result};
use indexmap::indexmap;
use indoc::writedoc;
use next_core::{
create_page_loader_entry_module, get_asset_path_from_pathname,
mode::NextMode,
Expand All @@ -20,17 +24,23 @@ use next_core::{
};
use turbo_tasks::Vc;
use turbopack_binding::{
turbo::{tasks::Value, tasks_env::ProcessEnv, tasks_fs::FileSystemPath},
turbo::{
tasks::Value,
tasks_env::ProcessEnv,
tasks_fs::{rope::RopeBuilder, File, FileSystemPath},
},
turbopack::{
build::BuildChunkingContext,
core::{
asset::AssetContent,
chunk::{ChunkableModule, ChunkingContext, EvaluatableAssets},
compile_time_info::CompileTimeInfo,
context::AssetContext,
file_source::FileSource,
output::OutputAsset,
reference_type::{EntryReferenceSubType, ReferenceType},
source::Source,
virtual_source::VirtualSource,
},
ecmascript::{
chunk::{EcmascriptChunkPlaceable, EcmascriptChunkingContext},
Expand Down Expand Up @@ -191,6 +201,8 @@ async fn get_page_entries_for_root_directory(
Vc::upcast(FileSource::new(app.project_path)),
next_router_root,
app.next_router_path,
app.original_path,
PathType::Page,
));

// This only makes sense on the server.
Expand All @@ -201,6 +213,8 @@ async fn get_page_entries_for_root_directory(
Vc::upcast(FileSource::new(document.project_path)),
next_router_root,
document.next_router_path,
document.original_path,
PathType::Page,
));

// This only makes sense on both the client and the server, but they should map
Expand All @@ -212,6 +226,8 @@ async fn get_page_entries_for_root_directory(
Vc::upcast(FileSource::new(error.project_path)),
next_router_root,
error.next_router_path,
error.original_path,
PathType::Page,
));

if let Some(api) = api {
Expand All @@ -221,6 +237,7 @@ async fn get_page_entries_for_root_directory(
api,
next_router_root,
&mut entries,
PathType::PagesAPI,
)
.await?;
}
Expand All @@ -232,6 +249,7 @@ async fn get_page_entries_for_root_directory(
pages,
next_router_root,
&mut entries,
PathType::Page,
)
.await?;
}
Expand All @@ -246,6 +264,7 @@ async fn get_page_entries_for_directory(
pages_structure: Vc<PagesDirectoryStructure>,
next_router_root: Vc<FileSystemPath>,
entries: &mut Vec<Vc<PageEntry>>,
path_type: PathType,
) -> Result<()> {
let PagesDirectoryStructure {
ref items,
Expand All @@ -257,14 +276,16 @@ async fn get_page_entries_for_directory(
let PagesStructureItem {
project_path,
next_router_path,
original_path: _,
original_path,
} = *item.await?;
entries.push(get_page_entry_for_file(
ssr_module_context,
client_module_context,
Vc::upcast(FileSource::new(project_path)),
next_router_root,
next_router_path,
original_path,
path_type,
));
}

Expand All @@ -275,6 +296,7 @@ async fn get_page_entries_for_directory(
*child,
next_router_root,
entries,
path_type,
)
.await?;
}
Expand All @@ -300,13 +322,129 @@ async fn get_page_entry_for_file(
source: Vc<Box<dyn Source>>,
next_router_root: Vc<FileSystemPath>,
next_router_path: Vc<FileSystemPath>,
next_original_path: Vc<FileSystemPath>,
path_type: PathType,
) -> Result<Vc<PageEntry>> {
let reference_type = Value::new(ReferenceType::Entry(EntryReferenceSubType::Page));
let reference_type = Value::new(ReferenceType::Entry(match path_type {
PathType::Page => EntryReferenceSubType::Page,
PathType::PagesAPI => EntryReferenceSubType::PagesApi,
_ => bail!("Invalid path type"),
}));

let pathname = pathname_for_path(next_router_root, next_router_path, path_type);

let pathname = pathname_for_path(next_router_root, next_router_path, PathType::Page);
let definition_page = format!("/{}", next_original_path.await?);
let definition_pathname = pathname.await?;

let ssr_module = ssr_module_context.process(source, reference_type.clone());

let mut result = RopeBuilder::default();

match path_type {
PathType::Page => {
// Sourced from https://github.com/vercel/next.js/blob/2848ce51d1552633119c89ab49ff7fe2e4e91c91/packages/next/src/build/webpack/loaders/next-route-loader/index.ts
Copy link
Member

@sokra sokra Jul 15, 2023

Choose a reason for hiding this comment

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

Instead of copying the code for turbopack and webpack, you can put that code into a shared JS file.
This can be imported in turobpack, and a webpack can read the file and replace "INNER" with string replace

Copy link
Member Author

Choose a reason for hiding this comment

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

If we put this into a JS file, we can't perform the following:

// When we're building the instrumentation page (only when the
// instrumentation file conflicts with a page also labeled
// /instrumentation) hoist the `register` method.
if definition_page == "/instrumentation" || definition_page == "/src/instrumentation" {
writeln!(
result,
r#"export const register = hoist(userland, "register")"#
)?;
}

Or

${
// When we're building the instrumentation page (only when the
// instrumentation file conflicts with a page also labeled
// /instrumentation) hoist the `register` method.
isInstrumentationHookFile(page)
? 'export const register = hoist(userland, "register")'
: ''
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Reading the file from disk will give us a RopeVc, which we can then use to build another rope that we can concatenate into.

writedoc!(
result,
r#"
import RouteModule from "next/dist/server/future/route-modules/pages/module"
import {{ hoist }} from "next/dist/build/webpack/loaders/next-route-loader/helpers"

import Document from "@vercel/turbopack-next/pages/_document"
import App from "@vercel/turbopack-next/pages/_app"

import * as userland from "INNER"

export default hoist(userland, "default")

export const getStaticProps = hoist(userland, "getStaticProps")
export const getStaticPaths = hoist(userland, "getStaticPaths")
export const getServerSideProps = hoist(userland, "getServerSideProps")
export const config = hoist(userland, "config")
export const reportWebVitals = hoist(userland, "reportWebVitals")

export const unstable_getStaticProps = hoist(userland, "unstable_getStaticProps")
export const unstable_getStaticPaths = hoist(userland, "unstable_getStaticPaths")
export const unstable_getStaticParams = hoist(userland, "unstable_getStaticParams")
export const unstable_getServerProps = hoist(userland, "unstable_getServerProps")
export const unstable_getServerSideProps = hoist(userland, "unstable_getServerSideProps")

export const routeModule = new RouteModule({{
definition: {{
kind: "PAGES",
page: "{definition_page}",
pathname: "{definition_pathname}",
// The following aren't used in production, but are
// required for the RouteModule constructor.
bundlePath: "",
filename: "",
}},
components: {{
App,
Document,
}},
userland,
}})
"#
)?;

// When we're building the instrumentation page (only when the
// instrumentation file conflicts with a page also labeled
// /instrumentation) hoist the `register` method.
if definition_page == "/instrumentation" || definition_page == "/src/instrumentation" {
writeln!(
result,
r#"export const register = hoist(userland, "register")"#
)?;
}
}
PathType::PagesAPI => {
// Sourced from https://github.com/vercel/next.js/blob/2848ce51d1552633119c89ab49ff7fe2e4e91c91/packages/next/src/build/webpack/loaders/next-route-loader/index.ts
writedoc!(
result,
r#"
import RouteModule from "next/dist/server/future/route-modules/pages-api/module"
import {{ hoist }} from "next/dist/build/webpack/loaders/next-route-loader/helpers"

import * as userland from "INNER"

export default hoist(userland, "default")
export const config = hoist(userland, "config")

export const routeModule = new RouteModule({{
definition: {{
kind: "PAGES_API",
page: "{definition_page}",
pathname: "{definition_pathname}",
// The following aren't used in production, but are
// required for the RouteModule constructor.
bundlePath: "",
filename: "",
}},
userland,
}})
"#
)?;
}
_ => bail!("Invalid path type"),
};

let file = File::from(result.build());

let asset = VirtualSource::new(
source.ident().path().join(match path_type {
PathType::Page => "pages-entry.tsx".to_string(),
PathType::PagesAPI => "pages-api-entry.tsx".to_string(),
_ => bail!("Invalid path type"),
}),
AssetContent::file(file.into()),
);
let ssr_module = ssr_module_context.process(
Vc::upcast(asset),
Value::new(ReferenceType::Internal(Vc::cell(indexmap! {
"INNER".to_string() => ssr_module,
}))),
);

let client_module = create_page_loader_entry_module(client_module_context, source, pathname);

let Some(client_module) =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
// the other imports
import startHandler from '../internal/page-server-handler'

import App from '@vercel/turbopack-next/pages/_app'
import Document from '@vercel/turbopack-next/pages/_document'
import App from '@vercel/turbopack-next/pages/_app'

import chunkGroup from 'INNER_CLIENT_CHUNK_GROUP'

Expand Down
1 change: 1 addition & 0 deletions packages/next-swc/crates/next-core/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ use crate::next_config::{NextConfig, OutputType};
#[derive(Debug, Clone, Copy, PartialEq, Eq, TaskInput)]
pub enum PathType {
Page,
PagesAPI,
Data,
}

Expand Down
18 changes: 14 additions & 4 deletions packages/next/src/build/entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ import { fileExists } from '../lib/file-exists'
import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader'
import { isInternalComponent } from '../lib/is-internal-component'
import { isStaticMetadataRouteFile } from '../lib/metadata/is-metadata-route'
import { RouteKind } from '../server/future/route-kind'
import { encodeToBase64 } from './webpack/loaders/utils'

export async function getStaticInfoIncludingLayouts({
isInsideAppDir,
Expand Down Expand Up @@ -589,23 +591,31 @@ export async function createEntrypoints(
assetPrefix: config.assetPrefix,
nextConfigOutput: config.output,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: Buffer.from(
JSON.stringify(staticInfo.middleware || {})
).toString('base64'),
middlewareConfig: encodeToBase64(staticInfo.middleware || {}),
})
} else if (isInstrumentationHookFile(page) && pagesType === 'root') {
server[serverBundlePath.replace('src/', '')] = {
import: absolutePagePath,
// the '../' is needed to make sure the file is not chunked
filename: `../${INSTRUMENTATION_HOOK_FILENAME}.js`,
}
} else if (isAPIRoute(page)) {
server[serverBundlePath] = [
getRouteLoaderEntry({
kind: RouteKind.PAGES_API,
page,
absolutePagePath,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: staticInfo.middleware || {},
}),
]
} else if (
!isAPIRoute(page) &&
!isMiddlewareFile(page) &&
!isInternalComponent(absolutePagePath)
) {
server[serverBundlePath] = [
getRouteLoaderEntry({
kind: RouteKind.PAGES,
page,
pages,
absolutePagePath,
Expand Down
26 changes: 14 additions & 12 deletions packages/next/src/build/webpack/loaders/get-module-build-info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,25 @@ import type {
} from '../../analysis/get-page-static-info'
import { webpack } from 'next/dist/compiled/webpack/webpack'

export type ModuleBuildInfo = {
nextEdgeMiddleware?: EdgeMiddlewareMeta
nextEdgeApiFunction?: EdgeMiddlewareMeta
nextEdgeSSR?: EdgeSSRMeta
nextWasmMiddlewareBinding?: AssetBinding
nextAssetMiddlewareBinding?: AssetBinding
usingIndirectEval?: boolean | Set<string>
route?: RouteMeta
importLocByPath?: Map<string, any>
rootDir?: string
rsc?: RSCMeta
}

/**
* A getter for module build info that casts to the type it should have.
* We also expose here types to make easier to use it.
*/
export function getModuleBuildInfo(webpackModule: webpack.Module) {
return webpackModule.buildInfo as {
nextEdgeMiddleware?: EdgeMiddlewareMeta
nextEdgeApiFunction?: EdgeMiddlewareMeta
nextEdgeSSR?: EdgeSSRMeta
nextWasmMiddlewareBinding?: AssetBinding
nextAssetMiddlewareBinding?: AssetBinding
usingIndirectEval?: boolean | Set<string>
route?: RouteMeta
importLocByPath?: Map<string, any>
rootDir?: string
rsc?: RSCMeta
}
return webpackModule.buildInfo as ModuleBuildInfo
}

export interface RSCMeta {
Expand Down
Loading