Unverified Commit 59e9b433 authored by Leah's avatar Leah Committed by GitHub

allow using the `nodejs` runtime for route handlers when using turbopack (#48791)

### What?
We previously ran all route handlers with the edge runtime, which means
you can't use built in node.js modules

With this PR, the runtime can be selected as documented in the next.js
docs

Fixes WEB-873
parent e7c9d3c0
// PAGE and PATHNAME is set from rust code
declare const PAGE: string, PATHNAME: string
import { EdgeRouteModuleWrapper } from 'next/dist/server/web/edge-route-module-wrapper' import { EdgeRouteModuleWrapper } from 'next/dist/server/web/edge-route-module-wrapper'
import RouteModule from 'ROUTE_MODULE' import RouteModule from 'ROUTE_MODULE'
import * as userland from 'ENTRY' import * as userland from 'ENTRY'
import { PAGE, PATHNAME } from 'BOOTSTRAP_CONFIG'
// TODO: (wyattjoh) - perform the option construction in Rust to allow other modules to accept different options // TODO: (wyattjoh) - perform the option construction in Rust to allow other modules to accept different options
const routeModule = new RouteModule({ const routeModule = new RouteModule({
......
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../../internal/api-server-handler'
import 'next/dist/server/node-polyfill-fetch.js'
import { join } from 'path'
import { parse as parseUrl } from 'node:url'
import {
NodeNextRequest,
NodeNextResponse,
} from 'next/dist/server/base-http/node'
import { runEdgeFunction } from '../../internal/edge'
import { attachRequestMeta } from '../../internal/next-request-helpers'
import chunkGroup from 'ROUTE_CHUNK_GROUP'
startHandler(async ({ request, response, query, params, path }) => {
const req = new NodeNextRequest(request)
const res = new NodeNextResponse(response)
const parsedUrl = parseUrl(req.url!, true)
attachRequestMeta(req, parsedUrl, request.headers.host!)
const edgeInfo = {
name: 'edge',
paths: chunkGroup.map((chunk) =>
join(process.cwd(), '.next/server/app', chunk)
),
wasm: [],
env: Object.keys(process.env),
assets: [],
}
await runEdgeFunction({
edgeInfo,
outputDir: 'app',
req,
res,
query,
params,
path,
onWarning(warning) {
console.warn(warning)
},
})
})
// IPC need to be the first import to allow it to catch errors happening during // IPC need to be the first import to allow it to catch errors happening during
// the other imports // the other imports
import startHandler from '../../internal/api-server-handler' import startHandler from '../../internal/api-server-handler'
import { runEdgeFunction } from '../../internal/edge'
import { join } from 'path' import '../../polyfill/app-polyfills'
import 'next/dist/server/node-polyfill-fetch.js' import { parse as parseUrl } from 'node:url'
import chunkGroup from 'ROUTE_CHUNK_GROUP'
import { import {
NodeNextRequest, NodeNextRequest,
NodeNextResponse, NodeNextResponse,
} from 'next/dist/server/base-http/node' } from 'next/dist/server/base-http/node'
import { sendResponse } from 'next/dist/server/send-response'
import { NextRequestAdapter } from 'next/dist/server/web/spec-extension/adapters/next-request'
import { RouteHandlerManagerContext } from 'next/dist/server/future/route-handler-managers/route-handler-manager'
import { attachRequestMeta } from '../../internal/next-request-helpers'
import RouteModule from 'ROUTE_MODULE'
import * as userland from 'ENTRY'
import { PAGE, PATHNAME } from 'BOOTSTRAP_CONFIG'
const routeModule = new RouteModule({
userland,
pathname: PATHNAME,
resolvedPagePath: `app/${PAGE}`,
nextConfigOutput: undefined,
})
startHandler(async ({ request, response, query, params, path }) => { startHandler(async ({ request, response, query, params, path }) => {
const edgeInfo = { const req = new NodeNextRequest(request)
name: 'edge', const res = new NodeNextResponse(response)
paths: chunkGroup.map((chunk) =>
join(process.cwd(), '.next/server/app', chunk) const parsedUrl = parseUrl(req.url!, true)
), attachRequestMeta(req, parsedUrl, request.headers.host!)
wasm: [],
env: Object.keys(process.env), const context: RouteHandlerManagerContext = {
assets: [],
}
await runEdgeFunction({
edgeInfo,
outputDir: 'app',
req: new NodeNextRequest(request),
res: new NodeNextResponse(response),
query,
params, params,
path, staticGenerationContext: {
onWarning(warning) { supportsDynamicHTML: true,
console.warn(warning)
}, },
}) }
const routeResponse = await routeModule.handle(
NextRequestAdapter.fromNodeNextRequest(req),
context
)
await sendResponse(req, res, routeResponse)
}) })
declare const NAME: string
declare const PAGE: string
import { adapter, enhanceGlobals } from 'next/dist/server/web/adapter' import { adapter, enhanceGlobals } from 'next/dist/server/web/adapter'
import { NAME, PAGE } from 'BOOTSTRAP_CONFIG'
enhanceGlobals() enhanceGlobals()
......
...@@ -4,16 +4,21 @@ import startHandler from '../internal/api-server-handler' ...@@ -4,16 +4,21 @@ import startHandler from '../internal/api-server-handler'
import 'next/dist/server/node-polyfill-fetch.js' import 'next/dist/server/node-polyfill-fetch.js'
import * as allExports from 'INNER' import { parse as parseQuery } from 'node:querystring'
import { parse as parseUrl } from 'node:url'
import { apiResolver } from 'next/dist/server/api-utils/node' import { apiResolver } from 'next/dist/server/api-utils/node'
import { import {
NodeNextRequest, NodeNextRequest,
NodeNextResponse, NodeNextResponse,
} from 'next/dist/server/base-http/node' } from 'next/dist/server/base-http/node'
import { parse } from 'node:querystring'
import { attachRequestMeta } from '../internal/next-request-helpers'
import * as allExports from 'INNER'
startHandler(({ request, response, query, params, path }) => { startHandler(({ request, response, query, params, path }) => {
const parsedQuery = parse(query) const parsedQuery = parseQuery(query)
const mergedQuery = { ...parsedQuery, ...params } const mergedQuery = { ...parsedQuery, ...params }
...@@ -21,6 +26,9 @@ startHandler(({ request, response, query, params, path }) => { ...@@ -21,6 +26,9 @@ startHandler(({ request, response, query, params, path }) => {
const req = new NodeNextRequest(request) const req = new NodeNextRequest(request)
const res = new NodeNextResponse(response) const res = new NodeNextResponse(response)
const parsedUrl = parseUrl(req.url!, true)
attachRequestMeta(req, parsedUrl, request.headers.host!)
return apiResolver( return apiResolver(
req.originalRequest, req.originalRequest,
res.originalResponse, res.originalResponse,
......
// IPC need to be the first import to allow it to catch errors happening during // IPC need to be the first import to allow it to catch errors happening during
// the other imports // the other imports
import startHandler from '../internal/api-server-handler' import startHandler from '../internal/api-server-handler'
import { runEdgeFunction } from '../internal/edge'
import { join } from 'path'
import 'next/dist/server/node-polyfill-fetch.js' import 'next/dist/server/node-polyfill-fetch.js'
import chunkGroup from 'INNER_EDGE_CHUNK_GROUP' import { join } from 'node:path'
import { parse as parseUrl } from 'node:url'
import { import {
NodeNextRequest, NodeNextRequest,
NodeNextResponse, NodeNextResponse,
} from 'next/dist/server/base-http/node' } from 'next/dist/server/base-http/node'
import { attachRequestMeta } from '../internal/next-request-helpers'
import { runEdgeFunction } from '../internal/edge'
import chunkGroup from 'INNER_EDGE_CHUNK_GROUP'
startHandler(async ({ request, response, query, params, path }) => { startHandler(async ({ request, response, query, params, path }) => {
const req = new NodeNextRequest(request)
const res = new NodeNextResponse(response)
const parsedUrl = parseUrl(req.url!, true)
attachRequestMeta(req, parsedUrl, request.headers.host!)
const edgeInfo = { const edgeInfo = {
name: 'edge', name: 'edge',
paths: chunkGroup.map((chunk: string) => paths: chunkGroup.map((chunk: string) =>
...@@ -24,11 +33,12 @@ startHandler(async ({ request, response, query, params, path }) => { ...@@ -24,11 +33,12 @@ startHandler(async ({ request, response, query, params, path }) => {
env: Object.keys(process.env), env: Object.keys(process.env),
assets: [], assets: [],
} }
await runEdgeFunction({ await runEdgeFunction({
edgeInfo, edgeInfo,
outputDir: 'pages', outputDir: 'pages',
req: new NodeNextRequest(request), req,
res: new NodeNextResponse(response), res,
query, query,
params, params,
path, path,
......
...@@ -2,13 +2,15 @@ ...@@ -2,13 +2,15 @@
// the other imports // the other imports
import { IPC } from '@vercel/turbopack-node/ipc/index' import { IPC } from '@vercel/turbopack-node/ipc/index'
import type { RenderData } from 'types/turbopack'
import type { Ipc } from '@vercel/turbopack-node/ipc/index'
import type { ClientRequest, IncomingMessage, Server } from 'node:http' import type { ClientRequest, IncomingMessage, Server } from 'node:http'
import type { ServerResponse } from 'node:http' import type { ServerResponse } from 'node:http'
import { Buffer } from 'node:buffer'
import type { Ipc } from '@vercel/turbopack-node/ipc/index'
import type { RenderData } from 'types/turbopack'
import { createServer, makeRequest } from '../internal/server' import { createServer, makeRequest } from '../internal/server'
import { toPairs } from '../internal/headers' import { toPairs } from '../internal/headers'
import { Buffer } from 'node:buffer'
const ipc = IPC as Ipc<IpcIncomingMessage, IpcOutgoingMessage> const ipc = IPC as Ipc<IpcIncomingMessage, IpcOutgoingMessage>
......
import { TLSSocket } from 'tls'
import {
addRequestMeta,
NextUrlWithParsedQuery,
} from 'next/dist/server/request-meta'
import { NodeNextRequest } from 'next/dist/server/base-http/node'
import { BaseNextRequest } from 'next/dist/server/base-http'
import { getCloneableBody } from 'next/dist/server/body-streams'
export function attachRequestMeta(
req: BaseNextRequest,
parsedUrl: NextUrlWithParsedQuery,
host: string
) {
const protocol = (
(req as NodeNextRequest).originalRequest?.socket as TLSSocket
)?.encrypted
? 'https'
: 'http'
const initUrl = `${protocol}://${host}${req.url}`
addRequestMeta(req, '__NEXT_INIT_URL', initUrl)
addRequestMeta(req, '__NEXT_INIT_QUERY', { ...parsedUrl.query })
addRequestMeta(req, '_protocol', protocol)
addRequestMeta(req, '__NEXT_CLONABLE_BODY', getCloneableBody(req.body))
}
...@@ -71,6 +71,12 @@ declare module 'ROUTE_MODULE' { ...@@ -71,6 +71,12 @@ declare module 'ROUTE_MODULE' {
} }
} }
declare module 'BOOTSTRAP_CONFIG' {
export const NAME: string
export const PAGE: string
export const PATHNAME: string
}
declare module 'CLIENT_MODULE' { declare module 'CLIENT_MODULE' {
export const __turbopack_module_id__: string export const __turbopack_module_id__: string
} }
......
use std::ops::Deref;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use swc_core::{
common::{source_map::Pos, Span, Spanned},
ecma::ast::{Expr, Ident, Program},
};
use turbo_binding::turbopack::{
core::{
asset::{Asset, AssetVc},
ident::AssetIdentVc,
issue::{
Issue, IssueSeverity, IssueSeverityVc, IssueSourceVc, IssueVc, OptionIssueSourceVc,
},
},
ecmascript::{
analyzer::{graph::EvalContext, JsValue},
parse::ParseResult,
EcmascriptModuleAssetVc,
},
};
use turbo_tasks::{primitives::StringVc, trace::TraceRawVcs};
use turbo_tasks_fs::FileSystemPathVc;
use crate::util::NextRuntime;
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, TraceRawVcs, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum NextSegmentDynamic {
#[default]
Auto,
ForceDynamic,
Error,
ForceStatic,
}
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, TraceRawVcs, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum NextSegmentFetchCache {
#[default]
Auto,
DefaultCache,
OnlyCache,
ForceCache,
DefaultNoStore,
OnlyNoStore,
ForceNoStore,
}
#[turbo_tasks::value]
#[derive(Debug)]
#[serde(rename_all = "camelCase")]
pub struct NextSegmentConfig {
pub dynamic: NextSegmentDynamic,
pub dynamic_params: bool,
pub revalidate: bool,
pub fetch_cache: NextSegmentFetchCache,
pub runtime: NextRuntime,
pub referred_region: String,
}
#[turbo_tasks::value_impl]
impl NextSegmentConfigVc {
#[turbo_tasks::function]
pub fn default() -> Self {
NextSegmentConfig::default().cell()
}
}
impl Default for NextSegmentConfig {
fn default() -> Self {
NextSegmentConfig {
dynamic: Default::default(),
dynamic_params: true,
revalidate: false,
fetch_cache: Default::default(),
runtime: Default::default(),
referred_region: "auto".to_string(),
}
}
}
/// An issue that occurred while parsing the app segment config.
#[turbo_tasks::value(shared)]
pub struct NextSegmentConfigParsingIssue {
ident: AssetIdentVc,
detail: StringVc,
source: IssueSourceVc,
}
#[turbo_tasks::value_impl]
impl Issue for NextSegmentConfigParsingIssue {
#[turbo_tasks::function]
fn severity(&self) -> IssueSeverityVc {
IssueSeverity::Warning.into()
}
#[turbo_tasks::function]
fn title(&self) -> StringVc {
StringVc::cell("Unable to parse config export in source file".to_string())
}
#[turbo_tasks::function]
fn category(&self) -> StringVc {
StringVc::cell("parsing".to_string())
}
#[turbo_tasks::function]
fn context(&self) -> FileSystemPathVc {
self.ident.path()
}
#[turbo_tasks::function]
fn description(&self) -> StringVc {
StringVc::cell(
"The exported configuration object in a source file need to have a very specific \
format from which some properties can be statically parsed at compiled-time."
.to_string(),
)
}
#[turbo_tasks::function]
fn detail(&self) -> StringVc {
self.detail
}
#[turbo_tasks::function]
fn documentation_link(&self) -> StringVc {
StringVc::cell("https://beta.nextjs.org/docs/api-reference/segment-config".to_string())
}
#[turbo_tasks::function]
fn source(&self) -> OptionIssueSourceVc {
OptionIssueSourceVc::some(self.source)
}
}
#[turbo_tasks::function]
pub async fn parse_segment_config_from_source(
module_asset: AssetVc,
) -> Result<NextSegmentConfigVc> {
let Some(ecmascript_asset) = EcmascriptModuleAssetVc::resolve_from(module_asset).await? else {
return Ok(NextSegmentConfigVc::default());
};
let ParseResult::Ok {
program: Program::Module(module),
eval_context,
..
} = &*ecmascript_asset.parse().await? else {
return Ok(NextSegmentConfigVc::default());
};
let mut config = NextSegmentConfig::default();
for item in &module.body {
let Some(decl) = item
.as_module_decl()
.and_then(|mod_decl| mod_decl.as_export_decl())
.and_then(|export_decl| export_decl.decl.as_var()) else {
continue;
};
for decl in &decl.decls {
let Some(ident) = decl
.name
.as_ident()
.map(|ident| ident.deref())
else {
continue;
};
if let Some(init) = decl.init.as_ref() {
parse_config_value(module_asset, &mut config, ident, init, eval_context);
}
}
}
Ok(config.cell())
}
fn issue_source(source: AssetVc, span: Span) -> IssueSourceVc {
IssueSourceVc::from_byte_offset(source, span.lo.to_usize(), span.hi.to_usize())
}
fn parse_config_value(
module_asset: AssetVc,
config: &mut NextSegmentConfig,
ident: &Ident,
init: &Expr,
eval_context: &EvalContext,
) {
let span = init.span();
let invalid_config = |detail: &str, value: &JsValue| {
let (explainer, hints) = value.explain(2, 0);
NextSegmentConfigParsingIssue {
ident: module_asset.ident(),
detail: StringVc::cell(format!("{detail} Got {explainer}.{hints}")),
source: issue_source(module_asset, span),
}
.cell()
.as_issue()
.emit();
};
match &*ident.sym {
"dynamic" => {
let value = eval_context.eval(init);
let Some(val) = value.as_str() else {
return invalid_config("`dynamic` needs to be a static string", &value);
};
config.dynamic = match serde_json::from_value(Value::String(val.to_string())) {
Ok(dynamic) => dynamic,
Err(err) => {
return invalid_config(
&format!("`dynamic` has an invalid value: {}", err),
&value,
)
}
};
}
"dynamicParams" => {
let value = eval_context.eval(init);
let Some(val) = value.as_bool() else {
return invalid_config("`dynamicParams` needs to be a static boolean", &value);
};
config.dynamic_params = val;
}
"revalidate" => {
let value = eval_context.eval(init);
let Some(val) = value.as_bool() else {
return invalid_config("`revalidate` needs to be a static boolean", &value);
};
config.revalidate = val;
}
"fetchCache" => {
let value = eval_context.eval(init);
let Some(val) = value.as_str() else {
return invalid_config("`fetchCache` needs to be a static string", &value);
};
config.fetch_cache = match serde_json::from_value(Value::String(val.to_string())) {
Ok(fetch_cache) => fetch_cache,
Err(err) => {
return invalid_config(
&format!("`fetchCache` has an invalid value: {}", err),
&value,
)
}
};
}
"runtime" => {
let value = eval_context.eval(init);
let Some(val) = value.as_str() else {
return invalid_config("`runtime` needs to be a static string", &value);
};
config.runtime = match serde_json::from_value(Value::String(val.to_string())) {
Ok(runtime) => runtime,
Err(err) => {
return invalid_config(
&format!("`runtime` has an invalid value: {}", err),
&value,
)
}
};
}
"preferredRegion" => {
let value = eval_context.eval(init);
let Some(val) = value.as_str() else {
return invalid_config("`preferredRegion` needs to be a static string", &value);
};
config.referred_region = val.to_string();
}
_ => {}
}
}
...@@ -64,12 +64,14 @@ use turbo_tasks::{primitives::JsonValueVc, TryJoinIterExt, ValueToString}; ...@@ -64,12 +64,14 @@ use turbo_tasks::{primitives::JsonValueVc, TryJoinIterExt, ValueToString};
use crate::{ use crate::{
app_render::next_layout_entry_transition::NextServerComponentTransition, app_render::next_layout_entry_transition::NextServerComponentTransition,
app_segment_config::parse_segment_config_from_source,
app_structure::{ app_structure::{
get_entrypoints, get_global_metadata, Components, Entrypoint, GlobalMetadataVc, LoaderTree, get_entrypoints, get_global_metadata, Components, Entrypoint, GlobalMetadataVc, LoaderTree,
LoaderTreeVc, Metadata, MetadataItem, MetadataWithAltItem, OptionAppDirVc, LoaderTreeVc, Metadata, MetadataItem, MetadataWithAltItem, OptionAppDirVc,
}, },
asset_helpers::as_es_module_asset, asset_helpers::as_es_module_asset,
embed_js::{next_js_file, next_js_file_path}, bootstrap::{route_bootstrap, BootstrapConfigVc},
embed_js::{next_asset, next_js_file, next_js_file_path},
env::env_for_js, env::env_for_js,
fallback::get_fallback_page, fallback::get_fallback_page,
next_client::{ next_client::{
...@@ -96,7 +98,7 @@ use crate::{ ...@@ -96,7 +98,7 @@ use crate::{
get_server_compile_time_info, get_server_module_options_context, get_server_compile_time_info, get_server_module_options_context,
get_server_resolve_options_context, ServerContextType, get_server_resolve_options_context, ServerContextType,
}, },
util::render_data, util::{render_data, NextRuntime},
}; };
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -224,7 +226,7 @@ fn next_layout_entry_transition( ...@@ -224,7 +226,7 @@ fn next_layout_entry_transition(
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn next_route_transition( fn next_edge_route_transition(
project_path: FileSystemPathVc, project_path: FileSystemPathVc,
app_dir: FileSystemPathVc, app_dir: FileSystemPathVc,
server_root: FileSystemPathVc, server_root: FileSystemPathVc,
...@@ -260,7 +262,7 @@ fn next_route_transition( ...@@ -260,7 +262,7 @@ fn next_route_transition(
edge_resolve_options_context, edge_resolve_options_context,
output_path, output_path,
base_path: app_dir, base_path: app_dir,
bootstrap_file: next_js_file("entry/app/route-bootstrap.ts"), bootstrap_asset: next_asset("entry/app/edge-route-bootstrap.ts"),
entry_name: "edge".to_string(), entry_name: "edge".to_string(),
} }
.cell() .cell()
...@@ -285,8 +287,8 @@ fn app_context( ...@@ -285,8 +287,8 @@ fn app_context(
let mut transitions = HashMap::new(); let mut transitions = HashMap::new();
transitions.insert( transitions.insert(
"next-route".to_string(), "next-edge-route".to_string(),
next_route_transition( next_edge_route_transition(
project_path, project_path,
app_dir, app_dir,
server_root, server_root,
...@@ -1002,7 +1004,6 @@ impl AppRouteVc { ...@@ -1002,7 +1004,6 @@ impl AppRouteVc {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn entry(self) -> Result<NodeRenderingEntryVc> { async fn entry(self) -> Result<NodeRenderingEntryVc> {
let this = self.await?; let this = self.await?;
let internal_asset = SourceAssetVc::new(next_js_file_path("entry/app/route.ts"));
let chunking_context = DevChunkingContextVc::builder( let chunking_context = DevChunkingContextVc::builder(
this.project_path, this.project_path,
...@@ -1016,10 +1017,49 @@ impl AppRouteVc { ...@@ -1016,10 +1017,49 @@ impl AppRouteVc {
.reference_chunk_source_maps(false) .reference_chunk_source_maps(false)
.build(); .build();
let entry = this.context.with_transition("next-route").process( let entry_source_asset = SourceAssetVc::new(this.entry_path);
SourceAssetVc::new(this.entry_path).into(), let entry_asset = this.context.process(
entry_source_asset.into(),
Value::new(ReferenceType::Entry(EntryReferenceSubType::AppRoute)), Value::new(ReferenceType::Entry(EntryReferenceSubType::AppRoute)),
); );
let config = parse_segment_config_from_source(entry_asset);
let module = match config.await?.runtime {
NextRuntime::NodeJs => {
let bootstrap_asset = next_asset("entry/app/route.ts");
route_bootstrap(
entry_asset,
this.context,
this.project_path,
bootstrap_asset,
BootstrapConfigVc::empty(),
)
}
NextRuntime::Edge => {
let internal_asset = next_asset("entry/app/edge-route.ts");
let entry = this.context.with_transition("next-edge-route").process(
entry_source_asset.into(),
Value::new(ReferenceType::Entry(EntryReferenceSubType::AppRoute)),
);
EcmascriptModuleAssetVc::new_with_inner_assets(
internal_asset,
this.context,
Value::new(EcmascriptModuleAssetType::Typescript),
EcmascriptInputTransformsVc::cell(vec![EcmascriptInputTransform::TypeScript {
use_define_for_class_fields: false,
}]),
Default::default(),
this.context.compile_time_info(),
InnerAssetsVc::cell(indexmap! {
"ROUTE_CHUNK_GROUP".to_string() => entry
}),
)
}
};
Ok(NodeRenderingEntry { Ok(NodeRenderingEntry {
runtime_entries: EvaluatableAssetsVc::cell( runtime_entries: EvaluatableAssetsVc::cell(
this.runtime_entries this.runtime_entries
...@@ -1028,19 +1068,7 @@ impl AppRouteVc { ...@@ -1028,19 +1068,7 @@ impl AppRouteVc {
.map(|entry| EvaluatableAssetVc::from_asset(*entry, this.context)) .map(|entry| EvaluatableAssetVc::from_asset(*entry, this.context))
.collect(), .collect(),
), ),
module: EcmascriptModuleAssetVc::new_with_inner_assets( module,
internal_asset.into(),
this.context,
Value::new(EcmascriptModuleAssetType::Typescript),
EcmascriptInputTransformsVc::cell(vec![EcmascriptInputTransform::TypeScript {
use_define_for_class_fields: false,
}]),
Default::default(),
this.context.compile_time_info(),
InnerAssetsVc::cell(indexmap! {
"ROUTE_CHUNK_GROUP".to_string() => entry
}),
),
chunking_context, chunking_context,
intermediate_output_path: this.intermediate_output_path, intermediate_output_path: this.intermediate_output_path,
output_root: this.output_root, output_root: this.output_root,
......
use anyhow::{bail, Context, Result};
use indexmap::{indexmap, IndexMap};
use turbo_binding::turbopack::{
core::{
asset::{Asset, AssetVc},
context::{AssetContext, AssetContextVc},
issue::{IssueSeverity, OptionIssueSourceVc},
reference_type::EcmaScriptModulesReferenceSubType,
resolve::parse::RequestVc,
virtual_asset::VirtualAssetVc,
},
ecmascript::{
resolve::esm_resolve, utils::StringifyJs, EcmascriptInputTransform,
EcmascriptInputTransformsVc, EcmascriptModuleAssetType, EcmascriptModuleAssetVc,
InnerAssetsVc,
},
};
use turbo_tasks::Value;
use turbo_tasks_fs::{File, FileSystemPathVc};
use crate::asset_helpers::as_es_module_asset;
#[turbo_tasks::function]
pub async fn route_bootstrap(
asset: AssetVc,
context: AssetContextVc,
base_path: FileSystemPathVc,
bootstrap_asset: AssetVc,
config: BootstrapConfigVc,
) -> Result<EcmascriptModuleAssetVc> {
let resolve_origin = if let Some(m) = EcmascriptModuleAssetVc::resolve_from(asset).await? {
m.as_resolve_origin()
} else {
bail!("asset does not represent an ecmascript module");
};
// TODO: this is where you'd switch the route kind to the one you need
let route_module_kind = "app-route";
let resolved_route_module_asset = esm_resolve(
resolve_origin,
RequestVc::parse_string(format!(
"next/dist/server/future/route-modules/{}/module",
route_module_kind
)),
Value::new(EcmaScriptModulesReferenceSubType::Undefined),
OptionIssueSourceVc::none(),
IssueSeverity::Error.cell(),
);
let route_module_asset = match &*resolved_route_module_asset.first_asset().await? {
Some(a) => *a,
None => bail!("could not find app asset"),
};
Ok(bootstrap(
asset,
context,
base_path,
bootstrap_asset,
InnerAssetsVc::cell(indexmap! {
"ROUTE_MODULE".to_string() => route_module_asset,
}),
config,
))
}
#[turbo_tasks::value(transparent)]
pub struct BootstrapConfig(IndexMap<String, String>);
#[turbo_tasks::value_impl]
impl BootstrapConfigVc {
#[turbo_tasks::function]
pub fn empty() -> Self {
BootstrapConfigVc::cell(IndexMap::new())
}
}
#[turbo_tasks::function]
pub async fn bootstrap(
asset: AssetVc,
context: AssetContextVc,
base_path: FileSystemPathVc,
bootstrap_asset: AssetVc,
inner_assets: InnerAssetsVc,
config: BootstrapConfigVc,
) -> Result<EcmascriptModuleAssetVc> {
let path = asset.ident().path().await?;
let path = base_path
.await?
.get_path_to(&path)
.context("asset is not in base_path")?;
let path = if let Some((name, ext)) = path.rsplit_once('.') {
if !ext.contains('/') {
name
} else {
path
}
} else {
path
};
let pathname = normalize_app_page_to_pathname(path);
let mut config = config.await?.clone_value();
config.insert("PAGE".to_string(), path.to_string());
config.insert("PATHNAME".to_string(), pathname);
let config_asset = as_es_module_asset(
VirtualAssetVc::new(
asset.ident().path().join("bootstrap-config.ts"),
File::from(
config
.iter()
.map(|(k, v)| format!("export const {} = {};\n", k, StringifyJs(v)))
.collect::<Vec<_>>()
.join(""),
)
.into(),
)
.as_asset(),
context,
)
.as_asset();
let mut inner_assets = inner_assets.await?.clone_value();
inner_assets.insert("ENTRY".to_string(), asset);
inner_assets.insert("BOOTSTRAP_CONFIG".to_string(), config_asset);
let asset = EcmascriptModuleAssetVc::new_with_inner_assets(
bootstrap_asset,
context,
Value::new(EcmascriptModuleAssetType::Typescript),
EcmascriptInputTransformsVc::cell(vec![EcmascriptInputTransform::TypeScript {
use_define_for_class_fields: false,
}]),
Default::default(),
context.compile_time_info(),
InnerAssetsVc::cell(inner_assets),
);
Ok(asset)
}
/// This normalizes an app page to a pathname.
fn normalize_app_page_to_pathname(page: &str) -> String {
// Split the page string by '/' and collect it into a Vec<&str>.
let segments: Vec<&str> = page.split('/').collect();
let segment_count = segments.len();
let mut pathname = String::new();
for (index, segment) in segments.into_iter().enumerate() {
// If a segment is empty, return the current pathname without modification.
if segment.is_empty()
// If a segment starts with '(' and ends with ')', return the current pathname
// without modification, effectively ignoring the segment.
|| (segment.starts_with('(') && segment.ends_with(')'))
// If a segment starts with '@', return the current pathname without
// modification, effectively ignoring the segment.
|| segment.starts_with('@')
// If the segment is "page" or "route" and it's the last one, return the current
// pathname without modification, effectively ignoring the segment.
|| ((segment == "page" || segment == "route") && index == segment_count - 1)
{
continue;
}
pathname.push('/');
// Replace '%5F' with '_' in the segment only if it's present at the beginning
// using the `replace` method.
if let Some(rest) = segment.strip_prefix("%5F") {
pathname.push('_');
pathname.push_str(rest);
} else {
pathname.push_str(segment);
}
}
pathname
}
#[cfg(test)]
mod tests {
use super::normalize_app_page_to_pathname;
#[test]
fn test_normalize() {
assert_eq!(
normalize_app_page_to_pathname("/some/[route]/route"),
"/some/[route]"
);
assert_eq!(
normalize_app_page_to_pathname("/another/route/(dashboard)/inside/page"),
"/another/route/inside"
);
}
#[test]
fn test_leading_slash() {
assert_eq!(
normalize_app_page_to_pathname("no/leading/slash"),
"/no/leading/slash"
);
}
#[test]
fn test_ignore_empty_segments() {
assert_eq!(
normalize_app_page_to_pathname("/ignore//empty///segments"),
"/ignore/empty/segments"
);
}
#[test]
fn test_ignore_groups() {
assert_eq!(
normalize_app_page_to_pathname("/ignore/(group)/segments"),
"/ignore/segments"
);
}
#[test]
fn test_ignore_parallel_segments() {
assert_eq!(
normalize_app_page_to_pathname("/ignore/@parallel/segments"),
"/ignore/segments"
);
}
#[test]
fn test_replace_percent_5f() {
assert_eq!(
normalize_app_page_to_pathname("/replace%5Fwith_underscore"),
"/replace%5Fwith_underscore"
);
assert_eq!(
normalize_app_page_to_pathname("/%5Freplace%5Fwith_underscore"),
"/_replace%5Fwith_underscore"
);
assert_eq!(
normalize_app_page_to_pathname(
"/replace%5Fwith_underscore/%5Freplace%5Fwith_underscore"
),
"/replace%5Fwith_underscore/_replace%5Fwith_underscore"
);
}
#[test]
fn test_complex_example() {
assert_eq!(
normalize_app_page_to_pathname("/test/@parallel/(group)//segments/page"),
"/test/segments"
);
}
}
...@@ -3,10 +3,12 @@ ...@@ -3,10 +3,12 @@
#![feature(box_syntax)] #![feature(box_syntax)]
mod app_render; mod app_render;
mod app_segment_config;
mod app_source; mod app_source;
pub mod app_structure; pub mod app_structure;
mod asset_helpers; mod asset_helpers;
mod babel; mod babel;
mod bootstrap;
mod embed_js; mod embed_js;
pub mod env; pub mod env;
mod fallback; mod fallback;
......
use anyhow::{anyhow, bail, Result}; use anyhow::Result;
use indexmap::indexmap; use indexmap::indexmap;
use turbo_binding::{ use turbo_binding::{
turbo::{ turbo::tasks_fs::FileSystemPathVc,
tasks::Value,
tasks_fs::{rope::RopeBuilder, File, FileContent, FileContentVc, FileSystemPathVc},
},
turbopack::{ turbopack::{
core::{ core::{asset::AssetVc, chunk::ChunkingContextVc, compile_time_info::CompileTimeInfoVc},
asset::{Asset, AssetVc}, ecmascript::chunk_group_files_asset::ChunkGroupFilesAsset,
chunk::ChunkingContextVc,
compile_time_info::CompileTimeInfoVc,
context::AssetContext,
issue::{IssueSeverity, OptionIssueSourceVc},
reference_type::EcmaScriptModulesReferenceSubType,
resolve::parse::RequestVc,
virtual_asset::VirtualAssetVc,
},
ecmascript::{
chunk_group_files_asset::ChunkGroupFilesAsset, resolve::esm_resolve,
utils::StringifyJs, EcmascriptInputTransform, EcmascriptInputTransformsVc,
EcmascriptModuleAssetType, EcmascriptModuleAssetVc, InnerAssetsVc,
},
turbopack::{ turbopack::{
module_options::ModuleOptionsContextVc, module_options::ModuleOptionsContextVc,
resolve_options_context::ResolveOptionsContextVc, resolve_options_context::ResolveOptionsContextVc,
...@@ -30,6 +14,8 @@ use turbo_binding::{ ...@@ -30,6 +14,8 @@ use turbo_binding::{
}, },
}; };
use crate::bootstrap::{route_bootstrap, BootstrapConfigVc};
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct NextEdgeTransition { pub struct NextEdgeTransition {
pub edge_compile_time_info: CompileTimeInfoVc, pub edge_compile_time_info: CompileTimeInfoVc,
...@@ -38,7 +24,7 @@ pub struct NextEdgeTransition { ...@@ -38,7 +24,7 @@ pub struct NextEdgeTransition {
pub edge_resolve_options_context: ResolveOptionsContextVc, pub edge_resolve_options_context: ResolveOptionsContextVc,
pub output_path: FileSystemPathVc, pub output_path: FileSystemPathVc,
pub base_path: FileSystemPathVc, pub base_path: FileSystemPathVc,
pub bootstrap_file: FileContentVc, pub bootstrap_asset: AssetVc,
pub entry_name: String, pub entry_name: String,
} }
...@@ -74,78 +60,13 @@ impl Transition for NextEdgeTransition { ...@@ -74,78 +60,13 @@ impl Transition for NextEdgeTransition {
asset: AssetVc, asset: AssetVc,
context: ModuleAssetContextVc, context: ModuleAssetContextVc,
) -> Result<AssetVc> { ) -> Result<AssetVc> {
let FileContent::Content(base) = &*self.bootstrap_file.await? else { let new_asset = route_bootstrap(
bail!("runtime code not found"); asset,
};
let path = asset.ident().path().await?;
let path = self
.base_path
.await?
.get_path_to(&path)
.ok_or_else(|| anyhow!("asset is not in base_path"))?;
let path = if let Some((name, ext)) = path.rsplit_once('.') {
if !ext.contains('/') {
name
} else {
path
}
} else {
path
};
let resolve_origin = if let Some(m) = EcmascriptModuleAssetVc::resolve_from(asset).await? {
m.as_resolve_origin()
} else {
bail!("asset does not represent an ecmascript module");
};
// TODO: this is where you'd switch the route kind to the one you need
let route_module_kind = "app-route";
let pathname = normalize_app_page_to_pathname(path);
let mut new_content = RopeBuilder::from(
format!(
"const NAME={};\nconst PAGE = {};\nconst PATHNAME = {};\n",
StringifyJs(&self.entry_name),
StringifyJs(path),
StringifyJs(&pathname),
)
.into_bytes(),
);
new_content.concat(base.content());
let file = File::from(new_content.build());
let virtual_asset = VirtualAssetVc::new(
asset.ident().path().join("next-edge-bootstrap.ts"),
FileContent::Content(file).cell().into(),
);
let resolved_route_module_asset = esm_resolve(
resolve_origin,
RequestVc::parse_string(format!(
"next/dist/server/future/route-modules/{}/module",
route_module_kind
)),
Value::new(EcmaScriptModulesReferenceSubType::Undefined),
OptionIssueSourceVc::none(),
IssueSeverity::Error.cell(),
);
let route_module_asset = match &*resolved_route_module_asset.first_asset().await? {
Some(a) => *a,
None => bail!("could not find app asset"),
};
let new_asset = EcmascriptModuleAssetVc::new_with_inner_assets(
virtual_asset.into(),
context.into(), context.into(),
Value::new(EcmascriptModuleAssetType::Typescript), self.base_path,
EcmascriptInputTransformsVc::cell(vec![EcmascriptInputTransform::TypeScript { self.bootstrap_asset,
use_define_for_class_fields: false, BootstrapConfigVc::cell(indexmap! {
}]), "NAME".to_string() => self.entry_name.clone(),
Default::default(),
context.compile_time_info(),
InnerAssetsVc::cell(indexmap! {
"ENTRY".to_string() => asset,
"ROUTE_MODULE".to_string() => route_module_asset
}), }),
); );
...@@ -159,116 +80,3 @@ impl Transition for NextEdgeTransition { ...@@ -159,116 +80,3 @@ impl Transition for NextEdgeTransition {
Ok(asset.cell().into()) Ok(asset.cell().into())
} }
} }
/// This normalizes an app page to a pathname.
fn normalize_app_page_to_pathname(page: &str) -> String {
// Split the page string by '/' and collect it into a Vec<&str>.
let segments: Vec<&str> = page.split('/').collect();
let segment_count = segments.len();
let mut pathname = String::new();
for (index, segment) in segments.into_iter().enumerate() {
// If a segment is empty, return the current pathname without modification.
if segment.is_empty()
// If a segment starts with '(' and ends with ')', return the current pathname
// without modification, effectively ignoring the segment.
|| (segment.starts_with('(') && segment.ends_with(')'))
// If a segment starts with '@', return the current pathname without
// modification, effectively ignoring the segment.
|| segment.starts_with('@')
// If the segment is "page" or "route" and it's the last one, return the current
// pathname without modification, effectively ignoring the segment.
|| ((segment == "page" || segment == "route") && index == segment_count - 1)
{
continue;
}
pathname.push('/');
// Replace '%5F' with '_' in the segment only if it's present at the beginning
// using the `replace` method.
if let Some(rest) = segment.strip_prefix("%5F") {
pathname.push('_');
pathname.push_str(rest);
} else {
pathname.push_str(segment);
}
}
pathname
}
#[cfg(test)]
mod tests {
use super::normalize_app_page_to_pathname;
#[test]
fn test_normalize() {
assert_eq!(
normalize_app_page_to_pathname("/some/[route]/route"),
"/some/[route]"
);
assert_eq!(
normalize_app_page_to_pathname("/another/route/(dashboard)/inside/page"),
"/another/route/inside"
);
}
#[test]
fn test_leading_slash() {
assert_eq!(
normalize_app_page_to_pathname("no/leading/slash"),
"/no/leading/slash"
);
}
#[test]
fn test_ignore_empty_segments() {
assert_eq!(
normalize_app_page_to_pathname("/ignore//empty///segments"),
"/ignore/empty/segments"
);
}
#[test]
fn test_ignore_groups() {
assert_eq!(
normalize_app_page_to_pathname("/ignore/(group)/segments"),
"/ignore/segments"
);
}
#[test]
fn test_ignore_parallel_segments() {
assert_eq!(
normalize_app_page_to_pathname("/ignore/@parallel/segments"),
"/ignore/segments"
);
}
#[test]
fn test_replace_percent_5f() {
assert_eq!(
normalize_app_page_to_pathname("/replace%5Fwith_underscore"),
"/replace%5Fwith_underscore"
);
assert_eq!(
normalize_app_page_to_pathname("/%5Freplace%5Fwith_underscore"),
"/_replace%5Fwith_underscore"
);
assert_eq!(
normalize_app_page_to_pathname(
"/replace%5Fwith_underscore/%5Freplace%5Fwith_underscore"
),
"/replace%5Fwith_underscore/_replace%5Fwith_underscore"
);
}
#[test]
fn test_complex_example() {
assert_eq!(
normalize_app_page_to_pathname("/test/@parallel/(group)//segments/page"),
"/test/segments"
);
}
}
...@@ -49,7 +49,7 @@ use turbo_tasks::{ ...@@ -49,7 +49,7 @@ use turbo_tasks::{
}; };
use crate::{ use crate::{
embed_js::{next_asset, next_js_file}, embed_js::next_asset,
env::env_for_js, env::env_for_js,
fallback::get_fallback_page, fallback::get_fallback_page,
next_client::{ next_client::{
...@@ -164,7 +164,7 @@ pub async fn create_page_source( ...@@ -164,7 +164,7 @@ pub async fn create_page_source(
edge_resolve_options_context, edge_resolve_options_context,
output_path, output_path,
base_path: project_path, base_path: project_path,
bootstrap_file: next_js_file("entry/edge-bootstrap.ts"), bootstrap_asset: next_asset("entry/edge-bootstrap.ts"),
entry_name: "edge".to_string(), entry_name: "edge".to_string(),
} }
.cell() .cell()
......
...@@ -46,7 +46,7 @@ use turbo_tasks_fs::json::parse_json_with_source_context; ...@@ -46,7 +46,7 @@ use turbo_tasks_fs::json::parse_json_with_source_context;
use crate::{ use crate::{
asset_helpers::as_es_module_asset, asset_helpers::as_es_module_asset,
embed_js::{next_asset, next_js_file}, embed_js::next_asset,
next_config::NextConfigVc, next_config::NextConfigVc,
next_edge::{ next_edge::{
context::{get_edge_compile_time_info, get_edge_resolve_options_context}, context::{get_edge_compile_time_info, get_edge_resolve_options_context},
...@@ -287,7 +287,7 @@ fn edge_transition_map( ...@@ -287,7 +287,7 @@ fn edge_transition_map(
edge_resolve_options_context, edge_resolve_options_context,
output_path: output_path.root(), output_path: output_path.root(),
base_path: project_path, base_path: project_path,
bootstrap_file: next_js_file("entry/edge-bootstrap.ts"), bootstrap_asset: next_asset("entry/edge-bootstrap.ts"),
entry_name: "middleware".to_string(), entry_name: "middleware".to_string(),
} }
.cell() .cell()
......
...@@ -94,9 +94,11 @@ pub async fn foreign_code_context_condition(next_config: NextConfigVc) -> Result ...@@ -94,9 +94,11 @@ pub async fn foreign_code_context_condition(next_config: NextConfigVc) -> Result
} }
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, TraceRawVcs, Serialize, Deserialize)] #[derive(Default, PartialEq, Eq, Clone, Copy, Debug, TraceRawVcs, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NextRuntime { pub enum NextRuntime {
#[default] #[default]
NodeJs, NodeJs,
#[serde(alias = "experimental-edge")]
Edge, Edge,
} }
...@@ -117,7 +119,7 @@ impl NextSourceConfigVc { ...@@ -117,7 +119,7 @@ impl NextSourceConfigVc {
} }
} }
/// An issue that occurred while resolving the React Refresh runtime module. /// An issue that occurred while parsing the page config.
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct NextSourceConfigParsingIssue { pub struct NextSourceConfigParsingIssue {
ident: AssetIdentVc, ident: AssetIdentVc,
......
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/server/lib/mock-request.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"stream\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"stream\"\nPath where resolving has started: [project]/packages/next/dist/server/lib/mock-request.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/server/lib/mock-request.js",
},
start: SourcePos {
line: 26,
column: 56,
},
end: SourcePos {
line: 26,
column: 73,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route-WEB-869/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/compiled/raw-body/index.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"stream\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"stream\"\nPath where resolving has started: [project]/packages/next/dist/compiled/raw-body/index.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/compiled/raw-body/index.js",
},
start: SourcePos {
line: 50,
column: 702,
},
end: SourcePos {
line: 50,
column: 719,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route-WEB-869/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/server/api-utils/node.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"stream\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"stream\"\nPath where resolving has started: [project]/packages/next/dist/server/api-utils/node.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/server/api-utils/node.js",
},
start: SourcePos {
line: 30,
column: 17,
},
end: SourcePos {
line: 30,
column: 34,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route-WEB-869/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/compiled/raw-body/index.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"path\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"path\"\nPath where resolving has started: [project]/packages/next/dist/compiled/raw-body/index.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/compiled/raw-body/index.js",
},
start: SourcePos {
line: 50,
column: 654,
},
end: SourcePos {
line: 50,
column: 669,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route-WEB-869/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/server/api-utils/node.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"querystring\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"querystring\"\nPath where resolving has started: [project]/packages/next/dist/server/api-utils/node.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/server/api-utils/node.js",
},
start: SourcePos {
line: 154,
column: 20,
},
end: SourcePos {
line: 154,
column: 42,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route-WEB-869/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/compiled/jsonwebtoken/index.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"stream\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"stream\"\nPath where resolving has started: [project]/packages/next/dist/compiled/jsonwebtoken/index.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/compiled/jsonwebtoken/index.js",
},
start: SourcePos {
line: 10,
column: 1097,
},
end: SourcePos {
line: 10,
column: 1114,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route-WEB-869/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
...@@ -21,3 +21,5 @@ export const POST = helloHandler ...@@ -21,3 +21,5 @@ export const POST = helloHandler
export const PUT = helloHandler export const PUT = helloHandler
export const DELETE = helloHandler export const DELETE = helloHandler
export const PATCH = helloHandler export const PATCH = helloHandler
export const runtime = 'experimental-edge'
import { NextResponse } from 'next/server'
import { generateKey } from 'crypto'
import { promisify } from 'util'
const generate = promisify(generateKey)
export async function GET(): Promise<Response> {
const key = await generate('hmac', { length: 64 })
return NextResponse.json({ data: key.type })
}
...@@ -2,24 +2,33 @@ ...@@ -2,24 +2,33 @@
import { useEffect } from 'react' import { useEffect } from 'react'
function test() {
it('should make a GET request', async () => {
const res = await fetch('/world')
const text = await res.text()
expect(text).toEqual('hello world')
expect(res.headers.get('method')).toEqual('GET')
}, 20000)
it('should make a POST request', async () => {
const res = await fetch('/route.js', {
method: 'POST',
})
const text = await res.text()
expect(text).toEqual('hello route.js')
expect(res.headers.get('method')).toEqual('POST')
}, 20000)
it('should make a GET request to /api/crypto which should support node builtins', async () => {
const res = await fetch('/api/crypto')
const text = await res.text()
expect(text).toEqual('{"data":"secret"}')
}, 20000)
}
export default function Test() { export default function Test() {
useEffect(() => { useEffect(() => {
import('@turbo/pack-test-harness').then(() => { import('@turbo/pack-test-harness').then(() => test())
it('should make a GET request', async () => {
const res = await fetch('/world')
const text = await res.text()
expect(text).toEqual('hello world')
expect(res.headers.get('method')).toEqual('GET')
}, 20000)
it('should make a POST request', async () => {
const res = await fetch('/route.js', {
method: 'POST',
})
const text = await res.text()
expect(text).toEqual('hello route.js')
expect(res.headers.get('method')).toEqual('POST')
}, 20000)
})
return () => {} return () => {}
}, []) }, [])
} }
PlainIssue { PlainIssue {
severity: Error, severity: Warning,
context: "[project]/packages/next/dist/compiled/jsonwebtoken/index.js", context: "[project]/packages/next/dist/compiled/edge-runtime/index.js",
category: "resolve", category: "parse",
title: "Error resolving commonjs request", title: "error TP1003 require.resolve(???*0*, {\"paths\": [???*1*]}) is not statically analyse-able",
description: "unable to resolve module \"crypto\"", description: "- *0* arguments[1]\n ⚠\u{fe0f} function calls are not analysed yet\n- *1* ???*2*[\"dirname\"](a)\n ⚠\u{fe0f} unknown callee object\n- *2* ???(17)\n ⚠\u{fe0f} unknown callee",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"crypto\"\nPath where resolving has started: [project]/packages/next/dist/compiled/jsonwebtoken/index.js\nType of request: commonjs request\nImport map: No import map entry\n", detail: "",
documentation_link: "", documentation_link: "",
source: Some( source: Some(
PlainIssueSource { PlainIssueSource {
asset: PlainAsset { asset: PlainAsset {
ident: "[project]/packages/next/dist/compiled/jsonwebtoken/index.js", ident: "[project]/packages/next/dist/compiled/edge-runtime/index.js",
}, },
start: SourcePos { start: SourcePos {
line: 10, line: 0,
column: 978, column: 6730,
}, },
end: SourcePos { end: SourcePos {
line: 10, line: 0,
column: 995, column: 6730,
}, },
}, },
), ),
...@@ -26,9 +26,9 @@ PlainIssue { ...@@ -26,9 +26,9 @@ PlainIssue {
[ [
PlainIssueProcessingPathItem { PlainIssueProcessingPathItem {
context: Some( context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route-WEB-869/input/app", "[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route/input/app",
), ),
description: "Next.js App Route /[slug]", description: "Next.js App Route /api/crypto",
}, },
], ],
), ),
......
PlainIssue { PlainIssue {
severity: Error, severity: Warning,
context: "[project]/packages/next/dist/server/crypto-utils.js", context: "[project]/packages/next/dist/compiled/@edge-runtime/primitives/crypto.js",
category: "resolve", category: "parse",
title: "Error resolving commonjs request", title: "lint TP1200 passing an ID to AMD define() is not yet fully supported",
description: "unable to resolve module \"crypto\"", description: "",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"crypto\"\nPath where resolving has started: [project]/packages/next/dist/server/crypto-utils.js\nType of request: commonjs request\nImport map: No import map entry\n", detail: "",
documentation_link: "", documentation_link: "",
source: Some( source: Some(
PlainIssueSource { PlainIssueSource {
asset: PlainAsset { asset: PlainAsset {
ident: "[project]/packages/next/dist/server/crypto-utils.js", ident: "[project]/packages/next/dist/compiled/@edge-runtime/primitives/crypto.js",
}, },
start: SourcePos { start: SourcePos {
line: 22, line: 70,
column: 56, column: 8,
}, },
end: SourcePos { end: SourcePos {
line: 22, line: 70,
column: 73, column: 8,
}, },
}, },
), ),
...@@ -26,9 +26,9 @@ PlainIssue { ...@@ -26,9 +26,9 @@ PlainIssue {
[ [
PlainIssueProcessingPathItem { PlainIssueProcessingPathItem {
context: Some( context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route-WEB-869/input/app", "[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route/input/app",
), ),
description: "Next.js App Route /[slug]", description: "Next.js App Route /api/crypto",
}, },
], ],
), ),
......
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