1use std::path::Path;
16
17use fallow_extract::JsText as _;
18use fallow_graph::graph::{EffectiveExportResolution, ExportNamespace, ModuleGraph};
19use fallow_types::discover::FileId;
20use fallow_types::extract::ImportedName;
21use oxc_ast::ast::{
22 Argument, ArrowFunctionBody, ArrowFunctionExpression, BindingPattern, CallExpression,
23 Declaration, ExportDefaultDeclaration, Expression, Function, ImportDeclaration,
24 ImportDeclarationSpecifier, ModuleExportName, NewExpression, ObjectPropertyKind, Program,
25 Statement, VariableDeclarator,
26};
27use oxc_ast_visit::{Visit, walk};
28use rustc_hash::{FxHashMap, FxHashSet};
29
30use crate::module_graph::RetainedModuleGraph;
31
32const ELYSIA_PACKAGE: &str = "elysia";
34
35const ELYSIA_METHODS: &[(&str, Option<&str>)] = &[
38 ("get", Some("GET")),
39 ("head", Some("HEAD")),
40 ("post", Some("POST")),
41 ("put", Some("PUT")),
42 ("patch", Some("PATCH")),
43 ("delete", Some("DELETE")),
44 ("options", Some("OPTIONS")),
45 ("all", None),
46];
47
48const ROUTE_CALL_METHODS: &[&str] = &["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
51
52const FILE_ROUTE_FUNCTIONS: &[&str] = &[
54 "createFileRoute",
55 "createLazyFileRoute",
56 "createServerFileRoute",
57];
58
59const MAX_MOUNT_DEPTH: usize = 16;
62
63const MAX_PREFIXES_PER_INSTANCE: usize = 32;
66
67#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct CodeRoute {
70 pub file_id: FileId,
72 pub pattern: String,
74 pub method: Option<&'static str>,
76}
77
78#[must_use]
82pub fn file_route_id(path: &Path, source: &str) -> Option<String> {
83 if !source.contains("FileRoute") {
84 return None;
85 }
86 let source_type = oxc_span::SourceType::from_path(path).unwrap_or_default();
87 fallow_extract::parse_bounded_or_default(source, source_type, |parsed| {
88 let mut finder = FileRouteFinder::default();
89 finder.visit_program(&parsed.program);
90 finder.route_id
91 })
92}
93
94#[derive(Default)]
95struct FileRouteFinder {
96 route_id: Option<String>,
97}
98
99impl<'a> Visit<'a> for FileRouteFinder {
100 fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
101 if self.route_id.is_some() {
102 return;
103 }
104 if let Expression::Identifier(callee) = &call.callee
105 && FILE_ROUTE_FUNCTIONS.contains(&callee.name.as_str())
106 {
107 self.route_id = call.arguments.first().and_then(literal_argument);
108 return;
109 }
110 walk::walk_call_expression(self, call);
111 }
112}
113
114#[must_use]
120pub fn elysia_routes(graph: &RetainedModuleGraph) -> Vec<CodeRoute> {
121 let graph = graph.as_graph();
122 let mut file_ids: Vec<FileId> = graph
123 .package_usage
124 .get(ELYSIA_PACKAGE)
125 .into_iter()
126 .chain(graph.type_only_package_usage.get(ELYSIA_PACKAGE))
127 .flatten()
128 .copied()
129 .collect();
130 file_ids.sort_unstable_by_key(|id| id.0);
131 file_ids.dedup();
132
133 let mut files: FxHashMap<FileId, ElysiaFile> = FxHashMap::default();
134 for file_id in file_ids {
135 let Some(module) = graph.modules.get(file_id.0 as usize) else {
136 continue;
137 };
138 let Ok(source) = std::fs::read_to_string(&module.path) else {
139 continue;
140 };
141 let parsed = elysia_file(&module.path, &source);
142 if !parsed.is_empty() {
143 files.insert(file_id, parsed);
144 }
145 }
146 resolve_elysia_routes(graph, &files)
147}
148
149#[derive(Debug, Default, PartialEq, Eq)]
151struct ElysiaFile {
152 instance_count: usize,
153 exports: Vec<(String, usize)>,
155 routes: Vec<LocalRoute>,
156 mounts: Vec<Mount>,
157}
158
159impl ElysiaFile {
160 const fn is_empty(&self) -> bool {
161 self.instance_count == 0
162 }
163}
164
165#[derive(Debug, Clone, PartialEq, Eq)]
167struct LocalRoute {
168 instance: usize,
169 method: Option<&'static str>,
170 path: String,
171 handler: Reference,
172}
173
174#[derive(Debug, Clone, PartialEq, Eq)]
178struct Mount {
179 parent: usize,
180 base: Option<String>,
181 child: Child,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq)]
185enum Child {
186 Local(usize),
188 Binding(Reference),
190}
191
192#[derive(Debug, Clone, PartialEq, Eq)]
194enum Reference {
195 Here,
197 Name {
199 local: String,
200 member: Option<String>,
201 },
202}
203
204#[derive(Debug, Clone)]
207struct AppRef {
208 instance: usize,
209 base: Option<String>,
210}
211
212fn elysia_file(path: &Path, source: &str) -> ElysiaFile {
213 let source_type = oxc_span::SourceType::from_path(path).unwrap_or_default();
214 fallow_extract::parse_bounded_or_default(source, source_type, |parsed| {
215 let mut collector = ElysiaCollector::default();
216 collector.visit_program(&parsed.program);
217 collector.collect_exports(&parsed.program);
218 collector.file
219 })
220}
221
222#[derive(Default)]
223struct ElysiaCollector {
224 file: ElysiaFile,
225 class_names: FxHashSet<String>,
227 bindings: Vec<(String, AppRef)>,
229}
230
231impl ElysiaCollector {
232 fn binding(&self, name: &str) -> Option<&AppRef> {
233 self.bindings
234 .iter()
235 .rev()
236 .find_map(|(bound, app)| (bound == name).then_some(app))
237 }
238
239 fn collect_exports(&mut self, program: &Program<'_>) {
240 for statement in &program.body {
241 match statement {
242 Statement::ExportDeclaration(export) => {
243 let Declaration::VariableDeclaration(decl) = &export.declaration else {
244 continue;
245 };
246 for declarator in &decl.declarations {
247 if let BindingPattern::BindingIdentifier(id) = &declarator.id {
248 self.export_binding(id.name.as_str(), id.name.as_str());
249 }
250 }
251 }
252 Statement::ExportNamedDeclaration(export) => {
253 for specifier in &export.specifiers {
254 let local = module_export_name(&specifier.local);
255 let exported = module_export_name(&specifier.exported);
256 self.export_binding(&local, &exported);
257 }
258 }
259 Statement::ExportDefaultDeclaration(export) => {
260 if let Some(Expression::Identifier(id)) = export.declaration.as_expression() {
261 self.export_binding(id.name.as_str(), "default");
262 }
263 }
264 _ => {}
265 }
266 }
267 }
268
269 fn export_binding(&mut self, local: &str, exported: &str) {
270 if let Some(app) = self.binding(local) {
271 let instance = app.instance;
272 self.push_export(exported, instance);
273 }
274 }
275
276 fn push_export(&mut self, exported: &str, instance: usize) {
277 if !self.file.exports.iter().any(|(name, _)| name == exported) {
278 self.file.exports.push((exported.to_owned(), instance));
279 }
280 }
281
282 fn app(&mut self, expr: &Expression<'_>) -> Option<AppRef> {
285 match expr.get_inner_expression() {
286 Expression::NewExpression(new) => self.app_new(new),
287 Expression::Identifier(id) => self.binding(id.name.as_str()).cloned(),
288 Expression::CallExpression(call) => self.app_call(call),
289 _ => None,
290 }
291 }
292
293 fn app_new(&mut self, new: &NewExpression<'_>) -> Option<AppRef> {
294 let Expression::Identifier(callee) = &new.callee else {
295 return None;
296 };
297 if !self.class_names.contains(callee.name.as_str()) {
298 return None;
299 }
300 let instance = self.file.instance_count;
301 self.file.instance_count += 1;
302 Some(AppRef {
303 instance,
304 base: constructor_prefix(new.arguments.first()),
305 })
306 }
307
308 fn app_call(&mut self, call: &CallExpression<'_>) -> Option<AppRef> {
309 let Expression::StaticMemberExpression(member) = &call.callee else {
310 return None;
311 };
312 let app = self.app(&member.object)?;
313 let method = member.property.name.as_str();
314 if let Some(&(_, http)) = ELYSIA_METHODS.iter().find(|(name, _)| *name == method) {
315 self.push_route(&app, http, call.arguments.first(), call.arguments.get(1));
316 } else {
317 match method {
318 "route" => self.route_call(&app, call),
319 "group" => self.group_call(&app, call),
320 "guard" => {
321 if call.arguments.len() >= 2
322 && let Some(callback) = call.arguments.last()
323 {
324 self.callback_body(callback, app.clone());
325 }
326 }
327 "use" => {
328 if let Some(argument) = call.arguments.first() {
329 self.use_call(&app, argument);
330 }
331 }
332 _ => {}
333 }
334 }
335 Some(app)
336 }
337
338 fn route_call(&mut self, app: &AppRef, call: &CallExpression<'_>) {
339 let Some(method) = call.arguments.first().and_then(literal_argument) else {
340 return;
341 };
342 let upper = method.to_ascii_uppercase();
343 let Some(http) = ROUTE_CALL_METHODS.iter().find(|m| **m == upper) else {
344 return;
345 };
346 self.push_route(
347 app,
348 Some(http),
349 call.arguments.get(1),
350 call.arguments.get(2),
351 );
352 }
353
354 fn push_route(
355 &mut self,
356 app: &AppRef,
357 method: Option<&'static str>,
358 path: Option<&Argument<'_>>,
359 handler: Option<&Argument<'_>>,
360 ) {
361 let (Some(base), Some(path)) = (&app.base, path.and_then(literal_argument)) else {
362 return;
363 };
364 self.file.routes.push(LocalRoute {
365 instance: app.instance,
366 method,
367 path: join_path(base, &path),
368 handler: handler.map_or(Reference::Here, reference),
369 });
370 }
371
372 fn group_call(&mut self, app: &AppRef, call: &CallExpression<'_>) {
373 let Some(callback) = call.arguments.last() else {
374 return;
375 };
376 if call.arguments.len() < 2 {
377 return;
378 }
379 let prefix = call.arguments.first().and_then(literal_argument);
380 let base = match (&app.base, prefix) {
381 (Some(base), Some(prefix)) => Some(join_path(base, &prefix)),
382 _ => None,
383 };
384 self.callback_body(
385 callback,
386 AppRef {
387 instance: app.instance,
388 base,
389 },
390 );
391 }
392
393 fn use_call(&mut self, app: &AppRef, argument: &Argument<'_>) {
394 let child = match argument {
395 Argument::Identifier(id) => match self.binding(id.name.as_str()) {
396 Some(child) => Child::Local(child.instance),
397 None => Child::Binding(reference(argument)),
398 },
399 Argument::StaticMemberExpression(_) => Child::Binding(reference(argument)),
400 Argument::ArrowFunctionExpression(_) | Argument::FunctionExpression(_) => {
401 self.callback_body(argument, app.clone());
403 return;
404 }
405 _ => {
406 let Some(expr) = argument.as_expression() else {
407 return;
408 };
409 let Some(child) = self.app(expr) else {
410 return;
411 };
412 Child::Local(child.instance)
413 }
414 };
415 self.file.mounts.push(Mount {
416 parent: app.instance,
417 base: app.base.clone(),
418 child,
419 });
420 }
421
422 fn callback_body(&mut self, callback: &Argument<'_>, app: AppRef) {
424 let depth = self.bindings.len();
425 match callback {
426 Argument::ArrowFunctionExpression(arrow) => {
427 if let Some(name) = first_param_name_arrow(arrow) {
428 self.bindings.push((name, app));
429 }
430 match &arrow.body {
431 ArrowFunctionBody::FunctionBody(body) => self.visit_function_body(body),
432 body => {
433 if let Some(expr) = body.as_expression() {
434 self.visit_expression(expr);
435 }
436 }
437 }
438 }
439 Argument::FunctionExpression(function) => {
440 if let Some(name) = first_param_name_function(function) {
441 self.bindings.push((name, app));
442 }
443 if let Some(body) = &function.body {
444 self.visit_function_body(body);
445 }
446 }
447 _ => {}
448 }
449 self.bindings.truncate(depth);
450 }
451}
452
453impl<'a> Visit<'a> for ElysiaCollector {
454 fn visit_import_declaration(&mut self, decl: &ImportDeclaration<'a>) {
455 if decl.source.value.text() != ELYSIA_PACKAGE {
456 return;
457 }
458 for specifier in decl.specifiers.iter().flatten() {
459 match specifier {
460 ImportDeclarationSpecifier::ImportSpecifier(specifier)
461 if specifier.imported.name().as_str() == "Elysia" =>
462 {
463 self.class_names.insert(specifier.local.name.to_string());
464 }
465 ImportDeclarationSpecifier::ImportDefaultSpecifier(specifier) => {
466 self.class_names.insert(specifier.local.name.to_string());
467 }
468 _ => {}
469 }
470 }
471 }
472
473 fn visit_variable_declarator(&mut self, declarator: &VariableDeclarator<'a>) {
474 let Some(init) = &declarator.init else {
475 return;
476 };
477 match self.app(init) {
478 Some(app) => {
479 if let BindingPattern::BindingIdentifier(id) = &declarator.id {
480 self.bindings.push((id.name.to_string(), app));
481 }
482 }
483 None => walk::walk_variable_declarator(self, declarator),
484 }
485 }
486
487 fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
488 if self.app_call(call).is_none() {
489 walk::walk_call_expression(self, call);
490 }
491 }
492
493 fn visit_new_expression(&mut self, new: &NewExpression<'a>) {
494 if self.app_new(new).is_none() {
495 walk::walk_new_expression(self, new);
496 }
497 }
498
499 fn visit_export_default_declaration(&mut self, decl: &ExportDefaultDeclaration<'a>) {
500 let Some(expr) = decl.declaration.as_expression() else {
501 walk::walk_export_default_declaration(self, decl);
502 return;
503 };
504 if matches!(expr, Expression::Identifier(_)) {
505 return;
506 }
507 match self.app(expr) {
508 Some(app) => self.push_export("default", app.instance),
509 None => walk::walk_export_default_declaration(self, decl),
510 }
511 }
512}
513
514fn constructor_prefix(options: Option<&Argument<'_>>) -> Option<String> {
517 let Some(options) = options else {
518 return Some(String::new());
519 };
520 let Argument::ObjectExpression(object) = options else {
521 return None;
522 };
523 for property in &object.properties {
524 match property {
525 ObjectPropertyKind::ObjectProperty(property) => {
526 if property
527 .key
528 .static_name()
529 .is_some_and(|name| name.text() == "prefix")
530 {
531 return literal_expression(&property.value)
532 .map(|prefix| join_path("", &prefix));
533 }
534 }
535 ObjectPropertyKind::SpreadProperty(_) => return None,
536 }
537 }
538 Some(String::new())
539}
540
541fn join_path(base: &str, path: &str) -> String {
544 if path.is_empty() || path.starts_with('/') {
545 format!("{base}{path}")
546 } else {
547 format!("{base}/{path}")
548 }
549}
550
551fn finish_pattern(path: &str) -> String {
554 let trimmed = path.trim_end_matches('/');
555 if trimmed.is_empty() {
556 "/".to_owned()
557 } else if trimmed.starts_with('/') {
558 trimmed.to_owned()
559 } else {
560 format!("/{trimmed}")
561 }
562}
563
564fn literal_argument(argument: &Argument<'_>) -> Option<String> {
565 argument.as_expression().and_then(literal_expression)
566}
567
568fn literal_expression(expr: &Expression<'_>) -> Option<String> {
571 match expr.get_inner_expression() {
572 Expression::StringLiteral(literal) => Some(literal.value.text().into_owned()),
573 Expression::TemplateLiteral(template) if template.expressions.is_empty() => template
574 .quasis
575 .first()
576 .map(|quasi| quasi.value.raw.to_string()),
577 _ => None,
578 }
579}
580
581fn reference(argument: &Argument<'_>) -> Reference {
582 let Some(expr) = argument.as_expression() else {
583 return Reference::Here;
584 };
585 match expr.get_inner_expression() {
586 Expression::Identifier(id) => Reference::Name {
587 local: id.name.to_string(),
588 member: None,
589 },
590 Expression::StaticMemberExpression(member) => match &member.object {
591 Expression::Identifier(object) => Reference::Name {
592 local: object.name.to_string(),
593 member: Some(member.property.name.to_string()),
594 },
595 _ => Reference::Here,
596 },
597 _ => Reference::Here,
598 }
599}
600
601fn first_param_name_arrow(arrow: &ArrowFunctionExpression<'_>) -> Option<String> {
602 binding_name(&arrow.params.items.first()?.pattern)
603}
604
605fn first_param_name_function(function: &Function<'_>) -> Option<String> {
606 binding_name(&function.params.items.first()?.pattern)
607}
608
609fn binding_name(pattern: &BindingPattern<'_>) -> Option<String> {
610 match pattern {
611 BindingPattern::BindingIdentifier(id) => Some(id.name.to_string()),
612 _ => None,
613 }
614}
615
616fn module_export_name(name: &ModuleExportName<'_>) -> String {
617 match name {
618 ModuleExportName::IdentifierName(id) => id.name.to_string(),
619 ModuleExportName::IdentifierReference(id) => id.name.to_string(),
620 ModuleExportName::StringLiteral(literal) => literal.value.text().into_owned(),
621 }
622}
623
624type InstanceKey = (FileId, usize);
626
627fn resolve_elysia_routes(
629 graph: &ModuleGraph,
630 files: &FxHashMap<FileId, ElysiaFile>,
631) -> Vec<CodeRoute> {
632 let imports: FxHashMap<FileId, FxHashMap<String, (FileId, ImportedName)>> = files
633 .keys()
634 .map(|&file_id| (file_id, import_bindings(graph, file_id)))
635 .collect();
636 let resolve = |file_id: FileId, reference: &Reference| -> Option<(FileId, Option<String>)> {
637 let Reference::Name { local, member } = reference else {
638 return None;
639 };
640 let (target, imported) = imports.get(&file_id)?.get(local)?;
641 let name = match imported {
642 ImportedName::Named(name) => name.clone(),
643 ImportedName::Default => "default".to_owned(),
644 ImportedName::Namespace => member.clone()?,
645 ImportedName::SideEffect => return None,
646 };
647 let origin = match graph.resolve_export(*target, &name, ExportNamespace::Value) {
648 EffectiveExportResolution::Unique(binding) => binding.origin_file(),
649 EffectiveExportResolution::Missing | EffectiveExportResolution::Ambiguous => *target,
650 };
651 Some((origin, Some(name)))
652 };
653
654 let mut parents: FxHashMap<InstanceKey, Vec<(InstanceKey, Option<String>)>> =
655 FxHashMap::default();
656 for (&file_id, file) in files {
657 for mount in &file.mounts {
658 let child = match &mount.child {
659 Child::Local(instance) => Some((file_id, *instance)),
660 Child::Binding(reference) => {
661 resolve(file_id, reference).and_then(|(origin, name)| {
662 let name = name?;
663 files
664 .get(&origin)?
665 .exports
666 .iter()
667 .find_map(|(export, instance)| {
668 (*export == name).then_some((origin, *instance))
669 })
670 })
671 }
672 };
673 if let Some(child) = child {
674 parents
675 .entry(child)
676 .or_default()
677 .push(((file_id, mount.parent), mount.base.clone()));
678 }
679 }
680 }
681
682 let mut prefixes: FxHashMap<InstanceKey, Vec<String>> = FxHashMap::default();
683 let mut visiting: FxHashSet<InstanceKey> = FxHashSet::default();
684 let mut routes = Vec::new();
685 let mut file_ids: Vec<&FileId> = files.keys().collect();
686 file_ids.sort_unstable_by_key(|id| id.0);
687 for &file_id in file_ids {
688 let file = &files[&file_id];
689 for route in &file.routes {
690 let key = (file_id, route.instance);
691 let instance_prefixes = mount_prefixes(key, &parents, &mut prefixes, &mut visiting);
692 let handler_file =
693 resolve(file_id, &route.handler).map_or(file_id, |(origin, _)| origin);
694 for prefix in instance_prefixes {
695 routes.push(CodeRoute {
696 file_id: handler_file,
697 pattern: finish_pattern(&format!("{prefix}{}", route.path)),
698 method: route.method,
699 });
700 }
701 }
702 }
703 routes.sort_by(|a, b| {
704 a.pattern
705 .cmp(&b.pattern)
706 .then_with(|| a.method.cmp(&b.method))
707 .then_with(|| a.file_id.0.cmp(&b.file_id.0))
708 });
709 routes.dedup();
710 routes
711}
712
713fn mount_prefixes(
723 key: InstanceKey,
724 parents: &FxHashMap<InstanceKey, Vec<(InstanceKey, Option<String>)>>,
725 memo: &mut FxHashMap<InstanceKey, Vec<String>>,
726 visiting: &mut FxHashSet<InstanceKey>,
727) -> Vec<String> {
728 if let Some(known) = memo.get(&key) {
729 return known.clone();
730 }
731 let Some(mounts) = parents.get(&key) else {
732 return vec![String::new()];
733 };
734 if visiting.len() >= MAX_MOUNT_DEPTH || !visiting.insert(key) {
735 return Vec::new();
736 }
737 let mut out: Vec<String> = Vec::new();
738 'mounts: for (parent, base) in mounts {
739 let Some(base) = base else {
740 continue;
741 };
742 for prefix in mount_prefixes(*parent, parents, memo, visiting) {
743 let joined = format!("{prefix}{base}");
744 if !out.contains(&joined) {
745 out.push(joined);
746 if out.len() == MAX_PREFIXES_PER_INSTANCE {
747 break 'mounts;
748 }
749 }
750 }
751 }
752 visiting.remove(&key);
753 memo.insert(key, out.clone());
754 out
755}
756
757fn import_bindings(
760 graph: &ModuleGraph,
761 file_id: FileId,
762) -> FxHashMap<String, (FileId, ImportedName)> {
763 let mut out = FxHashMap::default();
764 for (target, symbols) in graph.outgoing_symbol_edges(file_id) {
765 for symbol in symbols.iter().filter(|symbol| !symbol.is_type_only) {
766 out.entry(symbol.local_name.clone())
767 .or_insert_with(|| (target, symbol.imported_name.clone()));
768 }
769 }
770 out
771}
772
773#[cfg(test)]
774mod tests;