1mod discover;
2#[cfg(test)]
3mod mod_test;
4mod parser;
5mod tree;
6#[cfg(test)]
7mod tree_test;
8
9use std::cell::RefCell;
10use std::fs;
11use std::io;
12use std::sync::MutexGuard;
13
14pub use discover::*;
15pub use parser::*;
16pub use tree::*;
17
18use crate::utils::import;
19use crate::utils::{join_paths, relative_path};
20use crate::walker::WalkerLeaf;
21
22pub struct HttpLeaf;
24
25impl HttpLeaf {
26 pub fn get_content(this: &MutexGuard<'_, WalkerLeaf>) -> io::Result<String> {
27 fs::read_to_string(&this.file_path)
28 }
29
30 pub fn resolve_import<P: AsRef<str>>(
31 this: &MutexGuard<'_, WalkerLeaf>,
32 path: P,
33 ) -> Option<String> {
34 let path = path.as_ref().to_string();
35 match path.chars().nth(0) {
36 Some(char) if char == '.' || char == '/' => {
37 let absolute = if char == '.' {
38 let input_dirname = this.file_path.parent()?;
39 join_paths(path, input_dirname)
40 } else {
41 path
42 };
43
44 let output_dirname = this.output_path.parent()?;
45
46 relative_path(absolute, output_dirname).map(|path| path.display().to_string())
47 }
48 _ => Some(path),
49 }
50 }
51
52 fn get_imports(
53 this: &MutexGuard<'_, WalkerLeaf>,
54 content: String,
55 ) -> Result<(String, String), HttpParseError> {
56 let content = RefCell::new(content);
57
58 let mut imports: Vec<String> = vec![];
59
60 loop {
61 let mut content_mut = content.borrow_mut();
62 let import_idx = match &content_mut.find("import") {
63 Some(idx) => idx.clone(),
64 None => break,
65 };
66
67 let content = &content_mut[(import_idx + "import ".len())..];
68 let quote_idx = match &content.find("\"") {
69 Some(idx) => idx.clone(),
70 None => break,
71 };
72
73 let inner = if quote_idx < " from ".len() {
74 None
75 } else {
76 let from_idx = match &content.find("from") {
77 Some(idx) => idx.clone(),
78 None => {
79 return Err(HttpParseError::InvalidSyntax(
80 this.rel_path.clone(),
81 "Malformed import. Missing 'from' keyword".to_string(),
82 ))
83 }
84 };
85 Some(&content[..(from_idx - 1)])
86 };
87
88 let last_quote_idx = match &content.chars().skip(quote_idx + 1).position(|c| c == '"') {
89 Some(idx) => idx.clone(),
90 None => {
91 return Err(HttpParseError::InvalidSyntax(
92 this.rel_path.clone(),
93 "Malformed import. Missing closing quote.".to_string(),
94 ))
95 }
96 };
97
98 let out_idx = quote_idx + last_quote_idx + 2;
99 let path = &content[(quote_idx + 1)..(out_idx - 1)];
100 let path = Self::resolve_import(this, path).unwrap();
101 let import_statement = if let Some(inner) = inner {
102 import(inner, path)
103 } else {
104 import("{}", path)
105 };
106 let content = &content[(out_idx)..];
107 *content_mut = content.to_string();
108
109 imports.push(import_statement);
110 }
111
112 let content = content.borrow();
113 Ok((imports.join(";\n"), content.to_string()))
114 }
115
116 fn get_handlers(
117 this: &MutexGuard<'_, WalkerLeaf>,
118 content: String,
119 ) -> Result<(String, String), HttpParseError> {
120 let (handlers, content) = match http_parse(content, this.file_path.display().to_string()) {
121 Ok(h) => h,
122 Err(e) => return Err(e),
123 };
124 let handlers: Vec<String> = handlers
125 .borrow()
126 .iter()
127 .map(|handler| {
128 let if_condition = match &handler.method {
129 &HTTPMethod::ANY => None,
130 &HTTPMethod::GET => Some("GET"),
131 &HTTPMethod::POST => Some("POST"),
132 &HTTPMethod::PATCH => Some("PATCH"),
133 &HTTPMethod::DELETE => Some("DELETE"),
134 &HTTPMethod::OPTIONS => Some("OPTIONS"),
135 };
136
137 if let Some(if_condition) = if_condition {
138 format!(
139 "if ({}.method == \"{}\") {{\n{}\n}}",
140 REQ_PARAM, if_condition, &handler.body
141 )
142 } else {
143 handler.body.to_string()
144 }
145 })
146 .collect();
147 Ok((handlers.join("\n"), content))
148 }
149
150 pub fn get_parts(
151 this: &MutexGuard<'_, WalkerLeaf>,
152 ) -> Result<(String, String, String), HttpParseError> {
153 let content = match Self::get_content(this) {
154 Ok(c) => c,
155 Err(_) => return Err(HttpParseError::Empty(this.rel_path.clone())),
156 };
157
158 let (imports, content) = Self::get_imports(this, content)?;
159 let (handlers, content) = Self::get_handlers(this, content)?;
160
161 return Ok((imports, handlers, content));
162 }
163
164 pub fn generate_file(this: &MutexGuard<'_, WalkerLeaf>) -> Result<String, HttpParseError> {
165 let leaf_parts = Self::get_parts(this)?;
166
167 let leaf_imports = leaf_parts.0;
168 let leaf_content = leaf_parts.2;
169 let leaf_handlers = leaf_parts.1;
170 let is_empty_handlers = String::is_empty(&leaf_handlers);
171 let imports = "import * as $_Densky_Runtime_$ from \"densky/runtime.ts\";";
172 let imports = format!("{imports}\n{leaf_imports}");
173 let top_content = format!("{imports}\n{leaf_content}");
174
175 let handler_content = if is_empty_handlers {
176 String::new()
177 } else {
178 leaf_handlers
179 };
180
181 let (pretty, _) = prettify_js::prettyprint(
182 format!(
183 "// deno-lint-ignore-file
184 // File auto-generated by Densky Framework
185 {top_content}
186 (!!Deno.env.has(\"DENSKY_MODULES_LOAD_DEBUG\")) && console.log(\"[Module Load Debug]\", import.meta.url);
187 export default async function(__req_param__: $_Densky_Runtime_$.HTTPRequest) {{
188 {handler_content}
189 }}",
190 )
191 .as_str(),
192 );
193
194 return Ok(pretty);
195 }
196}