forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.rs
More file actions
340 lines (295 loc) · 11.8 KB
/
middleware.rs
File metadata and controls
340 lines (295 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
use std::future::IntoFuture;
use anyhow::{bail, Context, Result};
use next_core::{
all_assets_from_entries,
middleware::get_middleware_module,
next_edge::entry::wrap_edge_entry,
next_manifests::{EdgeFunctionDefinition, MiddlewareMatcher, MiddlewaresManifestV2, Regions},
next_server::{get_server_runtime_entries, ServerContextType},
util::{parse_config_from_source, MiddlewareMatcherKind},
};
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{Completion, ResolvedVc, Value, Vc};
use turbo_tasks_fs::{self, File, FileContent, FileSystemPath};
use turbopack_core::{
asset::AssetContent,
chunk::{availability_info::AvailabilityInfo, ChunkingContextExt, EvaluatableAsset},
context::AssetContext,
module::{Module, Modules},
output::OutputAssets,
reference_type::{EntryReferenceSubType, ReferenceType},
source::Source,
virtual_output::VirtualOutputAsset,
};
use turbopack_ecmascript::chunk::EcmascriptChunkPlaceable;
use crate::{
paths::{
all_paths_in_root, all_server_paths, get_asset_paths_from_root, get_js_paths_from_root,
get_wasm_paths_from_root, paths_to_bindings, wasm_paths_to_bindings,
},
project::Project,
route::{Endpoint, WrittenEndpoint},
};
#[turbo_tasks::value]
pub struct MiddlewareEndpoint {
project: ResolvedVc<Project>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
source: ResolvedVc<Box<dyn Source>>,
app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>,
}
#[turbo_tasks::value_impl]
impl MiddlewareEndpoint {
#[turbo_tasks::function]
pub fn new(
project: ResolvedVc<Project>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
source: ResolvedVc<Box<dyn Source>>,
app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>,
) -> Vc<Self> {
Self {
project,
asset_context,
source,
app_dir,
ecmascript_client_reference_transition_name,
}
.cell()
}
#[turbo_tasks::function]
async fn entry_module(&self) -> Vc<Box<dyn Module>> {
let userland_module = self
.asset_context
.process(
*self.source,
Value::new(ReferenceType::Entry(EntryReferenceSubType::Middleware)),
)
.module();
let module = get_middleware_module(
*self.asset_context,
self.project.project_path(),
userland_module,
);
wrap_edge_entry(
*self.asset_context,
self.project.project_path(),
module,
"middleware".into(),
)
}
#[turbo_tasks::function]
async fn edge_files(self: Vc<Self>) -> Result<Vc<OutputAssets>> {
let this = self.await?;
let module = self.entry_module();
let evaluatable_assets = get_server_runtime_entries(
Value::new(ServerContextType::Middleware {
app_dir: this.app_dir,
ecmascript_client_reference_transition_name: this
.ecmascript_client_reference_transition_name,
}),
this.project.next_mode(),
)
.resolve_entries(*this.asset_context);
let mut evaluatable_assets = evaluatable_assets.await?.clone_value();
let Some(module) =
Vc::try_resolve_downcast::<Box<dyn EcmascriptChunkPlaceable>>(module).await?
else {
bail!("Entry module must be evaluatable");
};
let evaluatable = Vc::try_resolve_sidecast::<Box<dyn EvaluatableAsset>>(module)
.await?
.context("Entry module must be evaluatable")?;
evaluatable_assets.push(evaluatable.to_resolved().await?);
let evaluatable_assets = Vc::cell(evaluatable_assets);
let module_graph = this.project.module_graph_for_entries(evaluatable_assets);
let edge_chunking_context = this.project.edge_chunking_context(false);
let edge_files = edge_chunking_context.evaluated_chunk_group_assets(
module.ident(),
evaluatable_assets,
module_graph,
Value::new(AvailabilityInfo::Root),
);
Ok(edge_files)
}
#[turbo_tasks::function]
async fn output_assets(self: Vc<Self>) -> Result<Vc<OutputAssets>> {
let this = self.await?;
let userland_module = self.userland_module();
let config = parse_config_from_source(userland_module);
let edge_files = self.edge_files();
let mut output_assets = edge_files.await?.clone_value();
let node_root = this.project.node_root();
let node_root_value = node_root.await?;
let file_paths_from_root = get_js_paths_from_root(&node_root_value, &output_assets).await?;
let all_output_assets = all_assets_from_entries(edge_files).await?;
let wasm_paths_from_root =
get_wasm_paths_from_root(&node_root_value, &all_output_assets).await?;
let all_assets = get_asset_paths_from_root(&node_root_value, &all_output_assets).await?;
// Awaited later for parallelism
let config = config.await?;
let regions = if let Some(regions) = config.regions.as_ref() {
if regions.len() == 1 {
regions
.first()
.map(|region| Regions::Single(region.clone()))
} else {
Some(Regions::Multiple(regions.clone()))
}
} else {
None
};
let next_config = this.project.next_config().await?;
let has_i18n = next_config.i18n.is_some();
let has_i18n_locales = next_config
.i18n
.as_ref()
.map(|i18n| i18n.locales.len() > 1)
.unwrap_or(false);
let base_path = next_config.base_path.as_ref();
let matchers = if let Some(matchers) = config.matcher.as_ref() {
matchers
.iter()
.map(|matcher| {
let mut matcher = match matcher {
MiddlewareMatcherKind::Str(matcher) => MiddlewareMatcher {
original_source: matcher.as_str().into(),
..Default::default()
},
MiddlewareMatcherKind::Matcher(matcher) => matcher.clone(),
};
// Mirrors implementation in get-page-static-info.ts getMiddlewareMatchers
let mut source = matcher.original_source.to_string();
let is_root = source == "/";
let has_locale = matcher.locale;
if has_i18n_locales && has_locale {
if is_root {
source.clear();
}
source.insert_str(0, "/:nextInternalLocale((?!_next/)[^/.]{1,})");
}
if is_root {
source.push('(');
if has_i18n {
source.push_str("|\\\\.json|");
}
source.push_str("/?index|/?index\\\\.json)?")
} else {
source.push_str("{(\\\\.json)}?")
};
source.insert_str(0, "/:nextData(_next/data/[^/]{1,})?");
if let Some(base_path) = base_path {
source.insert_str(0, base_path);
}
// TODO: The implementation of getMiddlewareMatchers outputs a regex here using
// path-to-regexp. Currently there is no equivalent of that so it post-processes
// this value to the relevant regex in manifest-loader.ts
matcher.regexp = Some(RcStr::from(source));
matcher
})
.collect()
} else {
vec![MiddlewareMatcher {
regexp: Some("^/.*$".into()),
original_source: "/:path*".into(),
..Default::default()
}]
};
let edge_function_definition = EdgeFunctionDefinition {
files: file_paths_from_root,
wasm: wasm_paths_to_bindings(wasm_paths_from_root),
assets: paths_to_bindings(all_assets),
name: "middleware".into(),
page: "/".into(),
regions,
matchers,
env: this.project.edge_env().await?.clone_value(),
};
let middleware_manifest_v2 = MiddlewaresManifestV2 {
middleware: [("/".into(), edge_function_definition)]
.into_iter()
.collect(),
..Default::default()
};
let middleware_manifest_v2 = VirtualOutputAsset::new(
node_root.join("server/middleware/middleware-manifest.json".into()),
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(
&middleware_manifest_v2,
)?))
.cell(),
),
)
.to_resolved()
.await?;
output_assets.push(ResolvedVc::upcast(middleware_manifest_v2));
Ok(Vc::cell(output_assets))
}
#[turbo_tasks::function]
fn userland_module(&self) -> Vc<Box<dyn Module>> {
self.asset_context
.process(
*self.source,
Value::new(ReferenceType::Entry(EntryReferenceSubType::Middleware)),
)
.module()
}
}
#[turbo_tasks::value_impl]
impl Endpoint for MiddlewareEndpoint {
#[turbo_tasks::function]
async fn write_to_disk(self: ResolvedVc<Self>) -> Result<Vc<WrittenEndpoint>> {
let span = tracing::info_span!("middleware endpoint");
async move {
let this = self.await?;
let output_assets_op = output_assets_operation(self);
let output_assets = output_assets_op.connect();
let _ = output_assets.resolve().await?;
let _ = this
.project
.emit_all_output_assets(output_assets_op)
.resolve()
.await?;
let (server_paths, client_paths) = if this.project.next_mode().await?.is_development() {
let node_root = this.project.node_root();
let server_paths = all_server_paths(output_assets, node_root)
.await?
.clone_value();
// Middleware could in theory have a client path (e.g. `new URL`).
let client_relative_root = this.project.client_relative_path();
let client_paths = all_paths_in_root(output_assets, client_relative_root)
.into_future()
.instrument(tracing::info_span!("client_paths"))
.await?
.clone_value();
(server_paths, client_paths)
} else {
(vec![], vec![])
};
Ok(WrittenEndpoint::Edge {
server_paths,
client_paths,
}
.cell())
}
.instrument(span)
.await
}
#[turbo_tasks::function]
async fn server_changed(self: Vc<Self>) -> Result<Vc<Completion>> {
Ok(self.await?.project.server_changed(self.output_assets()))
}
#[turbo_tasks::function]
fn client_changed(self: Vc<Self>) -> Vc<Completion> {
Completion::immutable()
}
#[turbo_tasks::function]
async fn root_modules(self: Vc<Self>) -> Result<Vc<Modules>> {
Ok(Vc::cell(vec![self.entry_module().to_resolved().await?]))
}
}
#[turbo_tasks::function(operation)]
fn output_assets_operation(endpoint: ResolvedVc<MiddlewareEndpoint>) -> Vc<OutputAssets> {
endpoint.output_assets()
}