Skip to content

Commit

Permalink
Merge 24e02cc into cf8b88b
Browse files Browse the repository at this point in the history
  • Loading branch information
jridgewell authored Feb 25, 2023
2 parents cf8b88b + 24e02cc commit a054105
Show file tree
Hide file tree
Showing 7 changed files with 107 additions and 32 deletions.
3 changes: 2 additions & 1 deletion crates/next-core/js/src/entry/edge-bootstrap.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
declare const NAME: string;
declare const PAGE: string;

import { adapter, enhanceGlobals } from "next/dist/server/web/adapter";
Expand All @@ -15,7 +16,7 @@ if (typeof handler !== "function") {

// @ts-ignore
globalThis._ENTRIES = {
middleware_edge: {
[`middleware_${NAME}`]: {
default: function (opts: any) {
return adapter({
...opts,
Expand Down
18 changes: 6 additions & 12 deletions crates/next-core/js/src/entry/router.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import type { Ipc } from "@vercel/turbopack-next/ipc/index";
import type { IncomingMessage, ServerResponse } from "node:http";
import { Buffer } from "node:buffer";
import { join } from "node:path";
import { createServer, makeRequest } from "@vercel/turbopack-next/ipc/server";
import { toPairs } from "@vercel/turbopack-next/internal/headers";
import { makeResolver } from "next/dist/server/router.js";
import { makeResolver } from "next/dist/server/lib/route-resolver";
import loadConfig from "next/dist/server/config";
import { PHASE_DEVELOPMENT_SERVER } from "next/dist/shared/lib/constants";

import "next/dist/server/node-polyfill-fetch.js";

import middlewareChunkGroup from "MIDDLEWARE_CHUNK_GROUP";
import middlewareConfig from "MIDDLEWARE_CONFIG";

type RouterRequest = {
method: string;
Expand Down Expand Up @@ -74,16 +74,10 @@ async function getResolveRoute(
true
);

const edgeInfo = {
name: "edge",
paths: middlewareChunkGroup.map((chunk: string) =>
join(process.cwd(), chunk)
),
wasm: [],
env: [],
assets: [],
};
return await makeResolver(dir, nextConfig, edgeInfo);
return await makeResolver(dir, nextConfig, {
files: middlewareChunkGroup,
matcher: middlewareConfig.matcher,
});
}

export default async function route(
Expand Down
1 change: 1 addition & 0 deletions crates/next-core/src/app_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ fn next_route_transition(
output_path,
base_path: app_dir,
bootstrap_file: next_js_file("entry/app/route-bootstrap.ts"),
entry_name: "edge".to_string(),
}
.cell()
.into()
Expand Down
11 changes: 9 additions & 2 deletions crates/next-core/src/next_edge/transition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub struct NextEdgeTransition {
pub output_path: FileSystemPathVc,
pub base_path: FileSystemPathVc,
pub bootstrap_file: FileContentVc,
pub entry_name: String,
}

#[turbo_tasks::value_impl]
Expand Down Expand Up @@ -81,8 +82,14 @@ impl Transition for NextEdgeTransition {
} else {
path
};
let mut new_content =
RopeBuilder::from(format!("const PAGE = {};\n", stringify_js(path)).into_bytes());
let mut new_content = RopeBuilder::from(
format!(
"const NAME={};\nconst PAGE = {};\n",
stringify_js(&self.entry_name),
stringify_js(path)
)
.into_bytes(),
);
new_content.concat(base.content());
let file = File::from(new_content.build());
let virtual_asset = VirtualAssetVc::new(
Expand Down
1 change: 1 addition & 0 deletions crates/next-core/src/page_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ pub async fn create_page_source(
output_path,
base_path: project_path,
bootstrap_file: next_js_file("entry/edge-bootstrap.ts"),
entry_name: "edge".to_string(),
}
.cell()
.into();
Expand Down
58 changes: 42 additions & 16 deletions crates/next-core/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::collections::HashMap;

use anyhow::{bail, Result};
use serde::Deserialize;
use serde_json::json;
use turbo_tasks::{
primitives::{JsonValueVc, StringsVc},
CompletionVc, Value,
Expand Down Expand Up @@ -40,6 +41,7 @@ use crate::{
},
next_import_map::get_next_build_import_map,
next_server::context::ServerContextType,
util::{parse_config_from_source, NextSourceConfigVc},
};

#[turbo_tasks::function]
Expand Down Expand Up @@ -194,26 +196,49 @@ async fn config_assets(
// is no middleware file, then we need to generate a default empty manifest
// and we cannot process it with the next-edge transition because it
// requires a real file for some reason.
let middleware_manifest = match &*middleware_config {
Some(c) => context.with_transition("next-edge").process(
c.as_asset(),
Value::new(ReferenceType::EcmaScriptModules(
EcmaScriptModulesReferenceSubType::Undefined,
)),
),
None => as_es_module_asset(
VirtualAssetVc::new(
project_path.join("middleware.js"),
File::from("export default [];").into(),
let (manifest, config) = match &*middleware_config {
Some(c) => {
let manifest = context.with_transition("next-edge").process(
c.as_asset(),
Value::new(ReferenceType::EcmaScriptModules(
EcmaScriptModulesReferenceSubType::Undefined,
)),
);
let config = parse_config_from_source(c.as_asset());
(manifest, config)
}
None => {
let manifest = as_es_module_asset(
VirtualAssetVc::new(
project_path.join("middleware.js"),
File::from("export default [];").into(),
)
.as_asset(),
context,
)
.as_asset(),
context,
.as_asset();
let config = NextSourceConfigVc::default();
(manifest, config)
}
};

let config_asset = as_es_module_asset(
VirtualAssetVc::new(
project_path.join("middleware_config.js"),
File::from(format!(
"export default {};",
json!({ "matcher": &config.await?.matcher })
))
.into(),
)
.as_asset(),
};
context,
)
.as_asset();

let mut inner = HashMap::new();
inner.insert("MIDDLEWARE_CHUNK_GROUP".to_string(), middleware_manifest);
inner.insert("MIDDLEWARE_CHUNK_GROUP".to_string(), manifest);
inner.insert("MIDDLEWARE_CONFIG".to_string(), config_asset);
Ok(InnerAssetsVc::cell(inner))
}

Expand Down Expand Up @@ -262,9 +287,10 @@ fn edge_transition_map(
edge_compile_time_info,
edge_chunking_context,
edge_resolve_options_context,
output_path,
output_path: output_path.root(),
base_path: project_path,
bootstrap_file: next_js_file("entry/edge-bootstrap.ts"),
entry_name: "middleware".to_string(),
}
.cell()
.into();
Expand Down
47 changes: 46 additions & 1 deletion crates/next-core/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,17 @@ pub enum NextRuntime {
#[derive(Default)]
pub struct NextSourceConfig {
pub runtime: NextRuntime,

/// Middleware router matchers
pub matcher: Option<Vec<String>>,
}

#[turbo_tasks::value_impl]
impl NextSourceConfigVc {
#[turbo_tasks::function]
pub fn default() -> Self {
NextSourceConfig::default().cell()
}
}

/// An issue that occurred while resolving the React Refresh runtime module.
Expand Down Expand Up @@ -179,7 +190,7 @@ pub async fn parse_config_from_source(module_asset: AssetVc) -> Result<NextSourc
}
}
}
Ok(NextSourceConfig::default().cell())
Ok(NextSourceConfigVc::default())
}

fn parse_config_from_js_value(module_asset: AssetVc, value: &JsValue) -> NextSourceConfig {
Expand Down Expand Up @@ -229,6 +240,40 @@ fn parse_config_from_js_value(module_asset: AssetVc, value: &JsValue) -> NextSou
);
}
}
if key == "matcher" {
let mut matchers = vec![];
match value {
JsValue::Constant(matcher) => {
if let Some(matcher) = matcher.as_str() {
matchers.push(matcher.to_string());
} else {
invalid_config(
"The matcher property must be a string or array of \
strings",
value,
);
}
}
JsValue::Array { items, .. } => {
for item in items {
if let Some(matcher) = item.as_str() {
matchers.push(matcher.to_string());
} else {
invalid_config(
"The matcher property must be a string or array \
of strings",
value,
);
}
}
}
_ => invalid_config(
"The matcher property must be a string or array of strings",
value,
),
}
config.matcher = Some(matchers);
}
} else {
invalid_config(
"The exported config object must not contain non-constant strings.",
Expand Down

0 comments on commit a054105

Please sign in to comment.