@ezetgalaxy/titan 26.8.2 → 26.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -25
- package/index.js +62 -15
- package/package.json +2 -2
- package/templates/extension/README.md +104 -104
- package/templates/extension/index.js +27 -27
- package/templates/extension/jsconfig.json +12 -12
- package/templates/extension/native/Cargo.toml +9 -9
- package/templates/extension/native/src/lib.rs +5 -5
- package/templates/extension/package.json +20 -20
- package/templates/extension/titan.json +17 -17
- package/templates/js/Dockerfile +66 -66
- package/templates/js/_dockerignore +3 -3
- package/templates/js/_gitignore +1 -0
- package/templates/js/app/actions/hello.js +5 -5
- package/templates/js/app/titan.d.ts +87 -87
- package/templates/js/jsconfig.json +18 -18
- package/templates/js/server/src/action_management.rs +131 -131
- package/templates/js/server/src/errors.rs +10 -10
- package/templates/js/server/src/extensions.rs +989 -989
- package/templates/js/server/src/utils.rs +33 -33
- package/templates/js/titan/bundle.js +78 -78
- package/templates/js/titan/dev.js +35 -3
- package/templates/js/titan/titan.js +122 -122
- package/templates/rust/Dockerfile +66 -66
- package/templates/rust/_dockerignore +3 -3
- package/templates/rust/_gitignore +1 -0
- package/templates/rust/app/actions/hello.js +5 -5
- package/templates/rust/app/actions/rust_hello.rs +14 -14
- package/templates/rust/app/titan.d.ts +101 -101
- package/templates/rust/jsconfig.json +18 -18
- package/templates/rust/server/src/action_management.rs +131 -131
- package/templates/rust/server/src/errors.rs +10 -10
- package/templates/rust/server/src/extensions.rs +989 -989
- package/templates/rust/server/src/utils.rs +33 -33
- package/templates/rust/titan/dev.js +36 -12
- package/templates/rust-ts/Dockerfile +66 -0
- package/templates/rust-ts/_dockerignore +3 -0
- package/templates/rust-ts/_gitignore +38 -0
- package/templates/rust-ts/app/actions/hello.ts +5 -0
- package/templates/rust-ts/app/actions/rust_hello.rs +14 -0
- package/templates/rust-ts/app/app.ts +11 -0
- package/templates/rust-ts/app/titan.d.ts +101 -0
- package/templates/rust-ts/package.json +14 -0
- package/templates/rust-ts/server/Cargo.lock +2869 -0
- package/templates/rust-ts/server/Cargo.toml +39 -0
- package/templates/rust-ts/server/src/action_management.rs +131 -0
- package/templates/rust-ts/server/src/errors.rs +51 -0
- package/templates/rust-ts/server/src/extensions.rs +989 -0
- package/templates/rust-ts/server/src/main.rs +468 -0
- package/templates/rust-ts/server/src/utils.rs +33 -0
- package/templates/rust-ts/titan/bundle.js +157 -0
- package/templates/rust-ts/titan/dev.js +402 -0
- package/templates/rust-ts/titan/titan.js +122 -0
- package/templates/rust-ts/tsconfig.json +21 -0
- package/templates/ts/Dockerfile +66 -0
- package/templates/ts/_dockerignore +3 -0
- package/templates/ts/_gitignore +38 -0
- package/templates/ts/app/actions/hello.ts +9 -0
- package/templates/ts/app/app.ts +10 -0
- package/templates/ts/app/titan.d.ts +102 -0
- package/templates/ts/package.json +26 -0
- package/templates/ts/server/Cargo.lock +2869 -0
- package/templates/ts/server/Cargo.toml +27 -0
- package/templates/ts/server/src/action_management.rs +131 -0
- package/templates/ts/server/src/errors.rs +51 -0
- package/templates/ts/server/src/extensions.rs +989 -0
- package/templates/ts/server/src/main.rs +437 -0
- package/templates/ts/server/src/utils.rs +33 -0
- package/templates/ts/titan/bundle.js +78 -0
- package/templates/ts/titan/dev.js +402 -0
- package/templates/ts/titan/titan.js +122 -0
- package/templates/ts/tsconfig.json +16 -0
- package/titanpl-sdk/README.md +109 -109
- package/titanpl-sdk/bin/run.js +254 -254
- package/titanpl-sdk/index.d.ts +46 -46
- package/titanpl-sdk/index.js +5 -5
- package/titanpl-sdk/package.json +32 -32
- package/titanpl-sdk/templates/.dockerignore +3 -3
- package/titanpl-sdk/templates/Dockerfile +53 -53
- package/titanpl-sdk/templates/app/actions/hello.js +5 -5
- package/titanpl-sdk/templates/app/titan.d.ts +87 -87
- package/titanpl-sdk/templates/jsconfig.json +18 -18
- package/titanpl-sdk/templates/server/src/action_management.rs +131 -131
- package/titanpl-sdk/templates/server/src/errors.rs +10 -10
- package/titanpl-sdk/templates/server/src/extensions.rs +640 -640
- package/titanpl-sdk/templates/server/src/utils.rs +33 -33
- package/titanpl-sdk/templates/titan/bundle.js +65 -65
- package/titanpl-sdk/templates/titan/dev.js +113 -113
- package/titanpl-sdk/templates/titan/titan.js +98 -98
- package/templates/js/server/action_map.json +0 -3
- package/templates/js/server/actions/hello.jsbundle +0 -48
- package/templates/js/server/routes.json +0 -16
- package/templates/rust/server/action_map.json +0 -3
- package/templates/rust/server/actions/hello.jsbundle +0 -47
- package/templates/rust/server/routes.json +0 -22
- package/templates/rust/server/src/actions_rust/mod.rs +0 -19
- package/templates/rust/server/src/actions_rust/rust_hello.rs +0 -14
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
use anyhow::Result;
|
|
2
|
+
use axum::{
|
|
3
|
+
Router,
|
|
4
|
+
body::{Body, to_bytes},
|
|
5
|
+
extract::State,
|
|
6
|
+
http::{Request, StatusCode},
|
|
7
|
+
response::{IntoResponse, Json},
|
|
8
|
+
routing::any,
|
|
9
|
+
};
|
|
10
|
+
use serde_json::Value;
|
|
11
|
+
use std::time::Instant;
|
|
12
|
+
use std::{collections::HashMap, fs, path::PathBuf, sync::Arc};
|
|
13
|
+
use tokio::net::TcpListener;
|
|
14
|
+
|
|
15
|
+
mod utils;
|
|
16
|
+
mod errors;
|
|
17
|
+
|
|
18
|
+
mod action_management;
|
|
19
|
+
mod extensions;
|
|
20
|
+
|
|
21
|
+
use action_management::{
|
|
22
|
+
DynamicRoute, RouteVal, find_actions_dir, match_dynamic_route, resolve_actions_dir,
|
|
23
|
+
};
|
|
24
|
+
use extensions::{init_v8, inject_extensions};
|
|
25
|
+
use utils::{blue, gray, green, red, white, yellow};
|
|
26
|
+
|
|
27
|
+
#[derive(Clone)]
|
|
28
|
+
struct AppState {
|
|
29
|
+
routes: Arc<HashMap<String, RouteVal>>,
|
|
30
|
+
dynamic_routes: Arc<Vec<DynamicRoute>>,
|
|
31
|
+
project_root: PathBuf,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Root/dynamic handlers -----------------------------------------------------
|
|
35
|
+
|
|
36
|
+
async fn root_route(state: State<AppState>, req: Request<Body>) -> impl IntoResponse {
|
|
37
|
+
dynamic_handler_inner(state, req).await
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async fn dynamic_route(state: State<AppState>, req: Request<Body>) -> impl IntoResponse {
|
|
41
|
+
dynamic_handler_inner(state, req).await
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async fn dynamic_handler_inner(
|
|
45
|
+
State(state): State<AppState>,
|
|
46
|
+
req: Request<Body>,
|
|
47
|
+
) -> impl IntoResponse {
|
|
48
|
+
// ---------------------------
|
|
49
|
+
// BASIC REQUEST INFO
|
|
50
|
+
// ---------------------------
|
|
51
|
+
let method = req.method().as_str().to_uppercase();
|
|
52
|
+
let path = req.uri().path().to_string();
|
|
53
|
+
let key = format!("{}:{}", method, path);
|
|
54
|
+
|
|
55
|
+
// ---------------------------
|
|
56
|
+
// TIMER + LOG META
|
|
57
|
+
// ---------------------------
|
|
58
|
+
let start = Instant::now();
|
|
59
|
+
let mut route_label = String::from("not_found");
|
|
60
|
+
let mut route_kind = "none"; // exact | dynamic | reply
|
|
61
|
+
|
|
62
|
+
// ---------------------------
|
|
63
|
+
// QUERY PARSING
|
|
64
|
+
// ---------------------------
|
|
65
|
+
let query: HashMap<String, String> = req
|
|
66
|
+
.uri()
|
|
67
|
+
.query()
|
|
68
|
+
.map(|q| {
|
|
69
|
+
q.split('&')
|
|
70
|
+
.filter_map(|pair| {
|
|
71
|
+
let mut it = pair.splitn(2, '=');
|
|
72
|
+
Some((it.next()?.to_string(), it.next().unwrap_or("").to_string()))
|
|
73
|
+
})
|
|
74
|
+
.collect()
|
|
75
|
+
})
|
|
76
|
+
.unwrap_or_default();
|
|
77
|
+
|
|
78
|
+
// ---------------------------
|
|
79
|
+
// HEADERS & BODY
|
|
80
|
+
// ---------------------------
|
|
81
|
+
let (parts, body) = req.into_parts();
|
|
82
|
+
|
|
83
|
+
let headers = parts
|
|
84
|
+
.headers
|
|
85
|
+
.iter()
|
|
86
|
+
.map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
|
|
87
|
+
.collect::<HashMap<String, String>>();
|
|
88
|
+
|
|
89
|
+
let body_bytes = match to_bytes(body, usize::MAX).await {
|
|
90
|
+
Ok(b) => b,
|
|
91
|
+
Err(_) => return (StatusCode::BAD_REQUEST, "Failed to read request body").into_response(),
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
let body_str = String::from_utf8_lossy(&body_bytes).to_string();
|
|
95
|
+
let body_json: Value = if body_str.is_empty() {
|
|
96
|
+
Value::Null
|
|
97
|
+
} else {
|
|
98
|
+
serde_json::from_str(&body_str).unwrap_or(Value::String(body_str))
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
// ---------------------------
|
|
102
|
+
// ROUTE RESOLUTION
|
|
103
|
+
// ---------------------------
|
|
104
|
+
let mut params: HashMap<String, String> = HashMap::new();
|
|
105
|
+
let mut action_name: Option<String> = None;
|
|
106
|
+
|
|
107
|
+
// Exact route
|
|
108
|
+
if let Some(route) = state.routes.get(&key) {
|
|
109
|
+
route_kind = "exact";
|
|
110
|
+
if route.r#type == "action" {
|
|
111
|
+
let name = route.value.as_str().unwrap_or("unknown").to_string();
|
|
112
|
+
route_label = name.clone();
|
|
113
|
+
action_name = Some(name);
|
|
114
|
+
} else if route.r#type == "json" {
|
|
115
|
+
let elapsed = start.elapsed();
|
|
116
|
+
println!(
|
|
117
|
+
"{} {} {} {}",
|
|
118
|
+
blue("[Titan]"),
|
|
119
|
+
white(&format!("{} {}", method, path)),
|
|
120
|
+
white("→ json"),
|
|
121
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
122
|
+
);
|
|
123
|
+
return Json(route.value.clone()).into_response();
|
|
124
|
+
} else if let Some(s) = route.value.as_str() {
|
|
125
|
+
let elapsed = start.elapsed();
|
|
126
|
+
println!(
|
|
127
|
+
"{} {} {} {}",
|
|
128
|
+
blue("[Titan]"),
|
|
129
|
+
white(&format!("{} {}", method, path)),
|
|
130
|
+
white("→ reply"),
|
|
131
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
132
|
+
);
|
|
133
|
+
return s.to_string().into_response();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Dynamic route
|
|
138
|
+
if action_name.is_none() {
|
|
139
|
+
if let Some((action, p)) =
|
|
140
|
+
match_dynamic_route(&method, &path, state.dynamic_routes.as_slice())
|
|
141
|
+
{
|
|
142
|
+
route_kind = "dynamic";
|
|
143
|
+
route_label = action.clone();
|
|
144
|
+
action_name = Some(action);
|
|
145
|
+
params = p;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
let action_name = match action_name {
|
|
150
|
+
Some(a) => a,
|
|
151
|
+
None => {
|
|
152
|
+
let elapsed = start.elapsed();
|
|
153
|
+
println!(
|
|
154
|
+
"{} {} {} {}",
|
|
155
|
+
blue("[Titan]"),
|
|
156
|
+
white(&format!("{} {}", method, path)),
|
|
157
|
+
white("→ 404"),
|
|
158
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
159
|
+
);
|
|
160
|
+
return (StatusCode::NOT_FOUND, "Not Found").into_response();
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
// ---------------------------
|
|
165
|
+
// LOAD ACTION
|
|
166
|
+
// ---------------------------
|
|
167
|
+
let resolved = resolve_actions_dir();
|
|
168
|
+
let actions_dir = resolved
|
|
169
|
+
.exists()
|
|
170
|
+
.then(|| resolved)
|
|
171
|
+
.or_else(|| find_actions_dir(&state.project_root))
|
|
172
|
+
.unwrap();
|
|
173
|
+
|
|
174
|
+
let mut action_path = actions_dir.join(format!("{}.jsbundle", action_name));
|
|
175
|
+
if !action_path.exists() {
|
|
176
|
+
let js_path = actions_dir.join(format!("{}.js", action_name));
|
|
177
|
+
if js_path.exists() {
|
|
178
|
+
action_path = js_path;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
let js_code =
|
|
183
|
+
match fs::read_to_string(&action_path) {
|
|
184
|
+
Ok(c) => c,
|
|
185
|
+
Err(_) => return (
|
|
186
|
+
StatusCode::INTERNAL_SERVER_ERROR,
|
|
187
|
+
Json(
|
|
188
|
+
serde_json::json!({"error": "Action bundle not found", "action": action_name}),
|
|
189
|
+
),
|
|
190
|
+
)
|
|
191
|
+
.into_response(),
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
// ---------------------------
|
|
195
|
+
// EXECUTE IN V8
|
|
196
|
+
// ---------------------------
|
|
197
|
+
let env_json = std::env::vars()
|
|
198
|
+
.map(|(k, v)| (k, Value::String(v)))
|
|
199
|
+
.collect::<serde_json::Map<_, _>>();
|
|
200
|
+
|
|
201
|
+
let injected = format!(
|
|
202
|
+
r#"
|
|
203
|
+
globalThis.process = {{ env: {} }};
|
|
204
|
+
const __titan_req = {{
|
|
205
|
+
body: {},
|
|
206
|
+
method: "{}",
|
|
207
|
+
path: "{}",
|
|
208
|
+
headers: {},
|
|
209
|
+
params: {},
|
|
210
|
+
query: {}
|
|
211
|
+
}};
|
|
212
|
+
(function() {{
|
|
213
|
+
{}
|
|
214
|
+
}})(); // Run the bundle
|
|
215
|
+
// Call the action
|
|
216
|
+
if (typeof globalThis["{}"] === 'function') {{
|
|
217
|
+
globalThis["{}"](__titan_req);
|
|
218
|
+
}} else {{
|
|
219
|
+
throw new Error("Action function '{}' not found in bundle");
|
|
220
|
+
}}
|
|
221
|
+
"#,
|
|
222
|
+
Value::Object(env_json).to_string(),
|
|
223
|
+
body_json.to_string(),
|
|
224
|
+
method,
|
|
225
|
+
path,
|
|
226
|
+
serde_json::to_string(&headers).unwrap(),
|
|
227
|
+
serde_json::to_string(¶ms).unwrap(),
|
|
228
|
+
serde_json::to_string(&query).unwrap(),
|
|
229
|
+
js_code,
|
|
230
|
+
action_name,
|
|
231
|
+
action_name,
|
|
232
|
+
action_name
|
|
233
|
+
);
|
|
234
|
+
|
|
235
|
+
// Run V8 in a blocking task safely?
|
|
236
|
+
// Axum handlers are async. V8 operations should be blocking.
|
|
237
|
+
// We can use `task::spawn_blocking`.
|
|
238
|
+
let root = state.project_root.clone();
|
|
239
|
+
let action_name_for_v8 = action_name.clone();
|
|
240
|
+
|
|
241
|
+
let result_json: Value = tokio::task::spawn_blocking(move || {
|
|
242
|
+
let isolate = &mut v8::Isolate::new(v8::CreateParams::default());
|
|
243
|
+
let handle_scope = &mut v8::HandleScope::new(isolate);
|
|
244
|
+
let context = v8::Context::new(handle_scope, v8::ContextOptions::default());
|
|
245
|
+
let scope = &mut v8::ContextScope::new(handle_scope, context);
|
|
246
|
+
|
|
247
|
+
let global = context.global(scope);
|
|
248
|
+
|
|
249
|
+
// Inject extensions (t.read, etc)
|
|
250
|
+
inject_extensions(scope, global);
|
|
251
|
+
|
|
252
|
+
// Set metadata globals
|
|
253
|
+
let root_str = v8::String::new(scope, root.to_str().unwrap_or(".")).unwrap();
|
|
254
|
+
let root_key = v8::String::new(scope, "__titan_root").unwrap();
|
|
255
|
+
global.set(scope, root_key.into(), root_str.into());
|
|
256
|
+
|
|
257
|
+
let action_str = v8::String::new(scope, &action_name_for_v8).unwrap();
|
|
258
|
+
let action_key = v8::String::new(scope, "__titan_action").unwrap();
|
|
259
|
+
global.set(scope, action_key.into(), action_str.into());
|
|
260
|
+
|
|
261
|
+
let try_catch = &mut v8::TryCatch::new(scope);
|
|
262
|
+
|
|
263
|
+
let source = v8::String::new(try_catch, &injected).unwrap();
|
|
264
|
+
let resource_name = v8::String::new(try_catch, &format!("app/actions/{}.ts", action_name_for_v8)).unwrap();
|
|
265
|
+
let source_map_url = v8::String::new(try_catch, "").unwrap();
|
|
266
|
+
|
|
267
|
+
let origin = v8::ScriptOrigin::new(
|
|
268
|
+
try_catch,
|
|
269
|
+
resource_name.into(),
|
|
270
|
+
0, // line offset
|
|
271
|
+
0, // column offset
|
|
272
|
+
false, // is_shared_cross_origin
|
|
273
|
+
123, // script_id
|
|
274
|
+
None, // source_map_url
|
|
275
|
+
true, // is_opaque
|
|
276
|
+
false, // is_wasm
|
|
277
|
+
false, // is_module
|
|
278
|
+
None,
|
|
279
|
+
);
|
|
280
|
+
|
|
281
|
+
let script = match v8::Script::compile(try_catch, source, Some(&origin)) {
|
|
282
|
+
Some(s) => s,
|
|
283
|
+
None => {
|
|
284
|
+
let msg = crate::errors::format_v8_error(try_catch, &action_name_for_v8);
|
|
285
|
+
return serde_json::json!({ "error": msg, "phase": "compile" });
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
let result = script.run(try_catch);
|
|
290
|
+
|
|
291
|
+
match result {
|
|
292
|
+
Some(val) => {
|
|
293
|
+
// Convert v8 Value to Serde JSON
|
|
294
|
+
// Minimal impl: stringify
|
|
295
|
+
let json_obj = v8::json::stringify(try_catch, val).unwrap();
|
|
296
|
+
let json_str = json_obj.to_rust_string_lossy(try_catch);
|
|
297
|
+
serde_json::from_str(&json_str).unwrap_or(Value::Null)
|
|
298
|
+
}
|
|
299
|
+
None => {
|
|
300
|
+
let msg = crate::errors::format_v8_error(try_catch, &action_name_for_v8);
|
|
301
|
+
serde_json::json!({ "error": msg, "phase": "execution" })
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
})
|
|
305
|
+
.await
|
|
306
|
+
.unwrap_or(serde_json::json!({"error": "V8 task failed"}));
|
|
307
|
+
|
|
308
|
+
// ---------------------------
|
|
309
|
+
// FINAL LOG
|
|
310
|
+
// ---------------------------
|
|
311
|
+
let elapsed = start.elapsed();
|
|
312
|
+
|
|
313
|
+
// Check for errors in result
|
|
314
|
+
if let Some(err) = result_json.get("error") {
|
|
315
|
+
println!(
|
|
316
|
+
"{} {} {} {}",
|
|
317
|
+
blue("[Titan]"),
|
|
318
|
+
red(&format!("{} {}", method, path)),
|
|
319
|
+
red("→ error"),
|
|
320
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
321
|
+
);
|
|
322
|
+
println!("{}", red(err.as_str().unwrap_or("Unknown")));
|
|
323
|
+
return (StatusCode::INTERNAL_SERVER_ERROR, Json(result_json)).into_response();
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
match route_kind {
|
|
327
|
+
"dynamic" => println!(
|
|
328
|
+
"{} {} {} {} {} {}",
|
|
329
|
+
blue("[Titan]"),
|
|
330
|
+
green(&format!("{} {}", method, path)),
|
|
331
|
+
white("→"),
|
|
332
|
+
green(&route_label),
|
|
333
|
+
white("(dynamic)"),
|
|
334
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
335
|
+
),
|
|
336
|
+
"exact" => println!(
|
|
337
|
+
"{} {} {} {} {}",
|
|
338
|
+
blue("[Titan]"),
|
|
339
|
+
white(&format!("{} {}", method, path)),
|
|
340
|
+
white("→"),
|
|
341
|
+
yellow(&route_label),
|
|
342
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
343
|
+
),
|
|
344
|
+
_ => {}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
Json(result_json).into_response()
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Entrypoint ---------------------------------------------------------------
|
|
351
|
+
|
|
352
|
+
#[tokio::main]
|
|
353
|
+
async fn main() -> Result<()> {
|
|
354
|
+
dotenvy::dotenv().ok();
|
|
355
|
+
init_v8(); // Init platform once
|
|
356
|
+
|
|
357
|
+
// Load routes.json
|
|
358
|
+
let raw = fs::read_to_string("./routes.json").unwrap_or_else(|_| "{}".to_string());
|
|
359
|
+
let json: Value = serde_json::from_str(&raw).unwrap_or_default();
|
|
360
|
+
|
|
361
|
+
let port = json["__config"]["port"].as_u64().unwrap_or(3000);
|
|
362
|
+
let routes_json = json["routes"].clone();
|
|
363
|
+
let map: HashMap<String, RouteVal> = serde_json::from_value(routes_json).unwrap_or_default();
|
|
364
|
+
let dynamic_routes: Vec<DynamicRoute> =
|
|
365
|
+
serde_json::from_value(json["__dynamic_routes"].clone()).unwrap_or_default();
|
|
366
|
+
|
|
367
|
+
// Identify project root (where .ext or node_modules lives)
|
|
368
|
+
let project_root = resolve_project_root();
|
|
369
|
+
|
|
370
|
+
let state = AppState {
|
|
371
|
+
routes: Arc::new(map),
|
|
372
|
+
dynamic_routes: Arc::new(dynamic_routes),
|
|
373
|
+
project_root: project_root.clone(),
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
// Load extensions
|
|
377
|
+
extensions::load_project_extensions(project_root.clone());
|
|
378
|
+
|
|
379
|
+
let app = Router::new()
|
|
380
|
+
.route("/", any(root_route))
|
|
381
|
+
.fallback(any(dynamic_route))
|
|
382
|
+
.with_state(state);
|
|
383
|
+
|
|
384
|
+
let listener = loop {
|
|
385
|
+
match TcpListener::bind(format!("0.0.0.0:{}", port)).await {
|
|
386
|
+
Ok(l) => break l,
|
|
387
|
+
Err(e) => {
|
|
388
|
+
if e.kind() == std::io::ErrorKind::AddrInUse {
|
|
389
|
+
println!(
|
|
390
|
+
"{} {}",
|
|
391
|
+
utils::yellow("[Titan]"),
|
|
392
|
+
utils::gray("Port in use, waiting for orbit to clear...")
|
|
393
|
+
);
|
|
394
|
+
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
return Err(e.into());
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
println!(
|
|
404
|
+
"\x1b[38;5;39mTitan server running at:\x1b[0m http://localhost:{}",
|
|
405
|
+
port
|
|
406
|
+
);
|
|
407
|
+
|
|
408
|
+
axum::serve(listener, app).await?;
|
|
409
|
+
Ok(())
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
fn resolve_project_root() -> PathBuf {
|
|
413
|
+
// 1. Check CWD (preferred for local dev/tooling)
|
|
414
|
+
if let Ok(cwd) = std::env::current_dir() {
|
|
415
|
+
if cwd.join("node_modules").exists()
|
|
416
|
+
|| cwd.join("package.json").exists()
|
|
417
|
+
|| cwd.join(".ext").exists()
|
|
418
|
+
{
|
|
419
|
+
return cwd;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// 2. Check executable persistence (Docker / Production)
|
|
424
|
+
// Walk up from the executable to find .ext or node_modules
|
|
425
|
+
if let Ok(exe) = std::env::current_exe() {
|
|
426
|
+
let mut current = exe.parent();
|
|
427
|
+
while let Some(dir) = current {
|
|
428
|
+
if dir.join(".ext").exists() || dir.join("node_modules").exists() {
|
|
429
|
+
return dir.to_path_buf();
|
|
430
|
+
}
|
|
431
|
+
current = dir.parent();
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// 3. Fallback to CWD
|
|
436
|
+
std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
|
|
437
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
pub fn blue(s: &str) -> String {
|
|
2
|
+
format!("\x1b[38;5;39m{}\x1b[0m", s)
|
|
3
|
+
}
|
|
4
|
+
pub fn white(s: &str) -> String {
|
|
5
|
+
format!("\x1b[39m{}\x1b[0m", s)
|
|
6
|
+
}
|
|
7
|
+
pub fn yellow(s: &str) -> String {
|
|
8
|
+
format!("\x1b[33m{}\x1b[0m", s)
|
|
9
|
+
}
|
|
10
|
+
pub fn green(s: &str) -> String {
|
|
11
|
+
format!("\x1b[32m{}\x1b[0m", s)
|
|
12
|
+
}
|
|
13
|
+
pub fn gray(s: &str) -> String {
|
|
14
|
+
format!("\x1b[90m{}\x1b[0m", s)
|
|
15
|
+
}
|
|
16
|
+
pub fn red(s: &str) -> String {
|
|
17
|
+
format!("\x1b[31m{}\x1b[0m", s)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
pub fn parse_expires_in(value: &str) -> Option<u64> {
|
|
21
|
+
let (num, unit) = value.split_at(value.len() - 1);
|
|
22
|
+
let n: u64 = num.parse().ok()?;
|
|
23
|
+
|
|
24
|
+
match unit {
|
|
25
|
+
"s" => Some(n),
|
|
26
|
+
"m" => Some(n * 60),
|
|
27
|
+
"h" => Some(n * 60 * 60),
|
|
28
|
+
"d" => Some(n * 60 * 60 * 24),
|
|
29
|
+
_ => None,
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import esbuild from "esbuild";
|
|
4
|
+
|
|
5
|
+
const root = process.cwd();
|
|
6
|
+
const actionsDir = path.join(root, "app", "actions");
|
|
7
|
+
const outDir = path.join(root, "server", "actions");
|
|
8
|
+
|
|
9
|
+
export async function bundle() {
|
|
10
|
+
const start = Date.now();
|
|
11
|
+
await bundleJs();
|
|
12
|
+
// console.log(`[Titan] Bundle finished in ${((Date.now() - start) / 1000).toFixed(2)}s`);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function bundleJs() {
|
|
16
|
+
// console.log("[Titan] Bundling JS actions...");
|
|
17
|
+
|
|
18
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
19
|
+
|
|
20
|
+
// Clean old bundles
|
|
21
|
+
if (fs.existsSync(outDir)) {
|
|
22
|
+
const oldFiles = fs.readdirSync(outDir);
|
|
23
|
+
for (const file of oldFiles) {
|
|
24
|
+
fs.unlinkSync(path.join(outDir, file));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const files = fs.readdirSync(actionsDir).filter(f => f.endsWith(".js") || f.endsWith(".ts"));
|
|
29
|
+
if (files.length === 0) return;
|
|
30
|
+
|
|
31
|
+
// console.log(`[Titan] Bundling ${files.length} JS actions...`);
|
|
32
|
+
|
|
33
|
+
for (const file of files) {
|
|
34
|
+
const actionName = path.basename(file, path.extname(file));
|
|
35
|
+
|
|
36
|
+
const entry = path.join(actionsDir, file);
|
|
37
|
+
|
|
38
|
+
// Rust runtime expects `.jsbundle` extension — consistent with previous design
|
|
39
|
+
const outfile = path.join(outDir, actionName + ".jsbundle");
|
|
40
|
+
|
|
41
|
+
// console.log(`[Titan] Bundling ${entry} → ${outfile}`);
|
|
42
|
+
|
|
43
|
+
await esbuild.build({
|
|
44
|
+
entryPoints: [entry],
|
|
45
|
+
outfile,
|
|
46
|
+
bundle: true,
|
|
47
|
+
format: "iife",
|
|
48
|
+
globalName: "__titan_exports",
|
|
49
|
+
platform: "neutral",
|
|
50
|
+
target: "es2020",
|
|
51
|
+
logLevel: "silent",
|
|
52
|
+
banner: {
|
|
53
|
+
js: "const defineAction = (fn) => fn;"
|
|
54
|
+
},
|
|
55
|
+
|
|
56
|
+
footer: {
|
|
57
|
+
js: `
|
|
58
|
+
(function () {
|
|
59
|
+
const fn =
|
|
60
|
+
__titan_exports["${actionName}"] ||
|
|
61
|
+
__titan_exports.default;
|
|
62
|
+
|
|
63
|
+
if (typeof fn !== "function") {
|
|
64
|
+
throw new Error("[Titan] Action '${actionName}' not found or not a function");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
globalThis["${actionName}"] = function(request_arg) {
|
|
68
|
+
globalThis.req = request_arg;
|
|
69
|
+
return fn(request_arg);
|
|
70
|
+
};
|
|
71
|
+
})();
|
|
72
|
+
`
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// console.log("[Titan] JS Bundling finished.");
|
|
78
|
+
}
|