@ezetgalaxy/titan 26.7.5 → 26.8.2
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 +86 -200
- package/index.js +87 -23
- package/package.json +4 -3
- package/templates/js/_gitignore +37 -0
- package/templates/{package.json → js/package.json} +3 -0
- package/templates/{server → js/server}/actions/hello.jsbundle +4 -1
- package/templates/{server → js/server}/src/extensions.rs +149 -17
- package/templates/{server → js/server}/src/main.rs +1 -6
- package/templates/{titan → js/titan}/bundle.js +22 -9
- package/templates/js/titan/dev.js +258 -0
- package/templates/js/titan/titan.js +122 -0
- package/templates/rust/Dockerfile +66 -0
- package/templates/rust/_dockerignore +3 -0
- package/templates/rust/_gitignore +37 -0
- package/templates/rust/app/actions/hello.js +5 -0
- package/templates/rust/app/actions/rust_hello.rs +14 -0
- package/templates/rust/app/app.js +11 -0
- package/templates/rust/app/titan.d.ts +101 -0
- package/templates/rust/jsconfig.json +19 -0
- package/templates/rust/package.json +13 -0
- package/templates/rust/server/Cargo.lock +2869 -0
- package/templates/rust/server/Cargo.toml +39 -0
- package/templates/rust/server/action_map.json +3 -0
- package/templates/rust/server/actions/hello.jsbundle +47 -0
- package/templates/rust/server/routes.json +22 -0
- package/templates/rust/server/src/action_management.rs +131 -0
- package/templates/rust/server/src/actions_rust/mod.rs +19 -0
- package/templates/rust/server/src/actions_rust/rust_hello.rs +14 -0
- package/templates/rust/server/src/errors.rs +10 -0
- package/templates/rust/server/src/extensions.rs +989 -0
- package/templates/rust/server/src/main.rs +437 -0
- package/templates/rust/server/src/utils.rs +33 -0
- package/templates/rust/titan/bundle.js +157 -0
- package/templates/rust/titan/dev.js +266 -0
- package/templates/{titan → rust/titan}/titan.js +122 -98
- package/titanpl-sdk/templates/Dockerfile +4 -17
- package/titanpl-sdk/templates/server/src/extensions.rs +218 -423
- package/titanpl-sdk/templates/server/src/main.rs +68 -134
- package/templates/_gitignore +0 -25
- package/templates/titan/dev.js +0 -144
- /package/templates/{Dockerfile → js/Dockerfile} +0 -0
- /package/templates/{.dockerignore → js/_dockerignore} +0 -0
- /package/templates/{app → js/app}/actions/hello.js +0 -0
- /package/templates/{app → js/app}/app.js +0 -0
- /package/templates/{app → js/app}/titan.d.ts +0 -0
- /package/templates/{jsconfig.json → js/jsconfig.json} +0 -0
- /package/templates/{server → js/server}/Cargo.lock +0 -0
- /package/templates/{server → js/server}/Cargo.toml +0 -0
- /package/templates/{server → js/server}/action_map.json +0 -0
- /package/templates/{server → js/server}/routes.json +0 -0
- /package/templates/{server → js/server}/src/action_management.rs +0 -0
- /package/templates/{server → js/server}/src/errors.rs +0 -0
- /package/templates/{server → js/server}/src/utils.rs +0 -0
|
@@ -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
|
+
|
|
17
|
+
mod action_management;
|
|
18
|
+
mod extensions;
|
|
19
|
+
mod actions_rust;
|
|
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 (No body consumption yet)
|
|
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
|
+
// ROUTE RESOLUTION
|
|
64
|
+
// ---------------------------
|
|
65
|
+
let mut params: HashMap<String, String> = HashMap::new();
|
|
66
|
+
let mut action_name: Option<String> = None;
|
|
67
|
+
|
|
68
|
+
// Exact route
|
|
69
|
+
if let Some(route) = state.routes.get(&key) {
|
|
70
|
+
route_kind = "exact";
|
|
71
|
+
if route.r#type == "action" {
|
|
72
|
+
let name = route.value.as_str().unwrap_or("unknown").to_string();
|
|
73
|
+
route_label = name.clone();
|
|
74
|
+
action_name = Some(name);
|
|
75
|
+
} else if route.r#type == "json" {
|
|
76
|
+
let elapsed = start.elapsed();
|
|
77
|
+
println!(
|
|
78
|
+
"{} {} {} {}",
|
|
79
|
+
blue("[Titan]"),
|
|
80
|
+
white(&format!("{} {}", method, path)),
|
|
81
|
+
white("→ json"),
|
|
82
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
83
|
+
);
|
|
84
|
+
return Json(route.value.clone()).into_response();
|
|
85
|
+
} else if let Some(s) = route.value.as_str() {
|
|
86
|
+
let elapsed = start.elapsed();
|
|
87
|
+
println!(
|
|
88
|
+
"{} {} {} {}",
|
|
89
|
+
blue("[Titan]"),
|
|
90
|
+
white(&format!("{} {}", method, path)),
|
|
91
|
+
white("→ reply"),
|
|
92
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
93
|
+
);
|
|
94
|
+
return s.to_string().into_response();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Dynamic route
|
|
99
|
+
if action_name.is_none() {
|
|
100
|
+
if let Some((action, p)) =
|
|
101
|
+
match_dynamic_route(&method, &path, state.dynamic_routes.as_slice())
|
|
102
|
+
{
|
|
103
|
+
route_kind = "dynamic";
|
|
104
|
+
route_label = action.clone();
|
|
105
|
+
action_name = Some(action);
|
|
106
|
+
params = p;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ---------------------------
|
|
111
|
+
// RUST ACTION CHECK
|
|
112
|
+
// ---------------------------
|
|
113
|
+
if let Some(name) = &action_name {
|
|
114
|
+
if let Some(rust_action) = actions_rust::get_action(name) {
|
|
115
|
+
let elapsed = start.elapsed();
|
|
116
|
+
match route_kind {
|
|
117
|
+
"dynamic" => println!(
|
|
118
|
+
"{} {} {} {} {} {}",
|
|
119
|
+
blue("[Titan]"),
|
|
120
|
+
green(&format!("{} {}", method, path)),
|
|
121
|
+
white("→"),
|
|
122
|
+
green(&route_label),
|
|
123
|
+
white("(rust)"),
|
|
124
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
125
|
+
),
|
|
126
|
+
"exact" => println!(
|
|
127
|
+
"{} {} {} {} {} {}",
|
|
128
|
+
blue("[Titan]"),
|
|
129
|
+
white(&format!("{} {}", method, path)),
|
|
130
|
+
white("→"),
|
|
131
|
+
yellow(&route_label),
|
|
132
|
+
white("(rust)"),
|
|
133
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
134
|
+
),
|
|
135
|
+
_ => {}
|
|
136
|
+
}
|
|
137
|
+
return rust_action(req).await.into_response();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ---------------------------
|
|
142
|
+
// QUERY PARSING (For JS)
|
|
143
|
+
// ---------------------------
|
|
144
|
+
let query: HashMap<String, String> = req
|
|
145
|
+
.uri()
|
|
146
|
+
.query()
|
|
147
|
+
.map(|q| {
|
|
148
|
+
q.split('&')
|
|
149
|
+
.filter_map(|pair| {
|
|
150
|
+
let mut it = pair.splitn(2, '=');
|
|
151
|
+
Some((it.next()?.to_string(), it.next().unwrap_or("").to_string()))
|
|
152
|
+
})
|
|
153
|
+
.collect()
|
|
154
|
+
})
|
|
155
|
+
.unwrap_or_default();
|
|
156
|
+
|
|
157
|
+
// ---------------------------
|
|
158
|
+
// HEADERS & BODY (CONSUME REQ)
|
|
159
|
+
// ---------------------------
|
|
160
|
+
let (parts, body) = req.into_parts();
|
|
161
|
+
|
|
162
|
+
let headers = parts
|
|
163
|
+
.headers
|
|
164
|
+
.iter()
|
|
165
|
+
.map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
|
|
166
|
+
.collect::<HashMap<String, String>>();
|
|
167
|
+
|
|
168
|
+
let body_bytes = match to_bytes(body, usize::MAX).await {
|
|
169
|
+
Ok(b) => b,
|
|
170
|
+
Err(_) => return (StatusCode::BAD_REQUEST, "Failed to read request body").into_response(),
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
let body_str = String::from_utf8_lossy(&body_bytes).to_string();
|
|
174
|
+
let body_json: Value = if body_str.is_empty() {
|
|
175
|
+
Value::Null
|
|
176
|
+
} else {
|
|
177
|
+
serde_json::from_str(&body_str).unwrap_or(Value::String(body_str))
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
let action_name = match action_name {
|
|
181
|
+
Some(a) => a,
|
|
182
|
+
None => {
|
|
183
|
+
let elapsed = start.elapsed();
|
|
184
|
+
println!(
|
|
185
|
+
"{} {} {} {}",
|
|
186
|
+
blue("[Titan]"),
|
|
187
|
+
white(&format!("{} {}", method, path)),
|
|
188
|
+
white("→ 404"),
|
|
189
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
190
|
+
);
|
|
191
|
+
return (StatusCode::NOT_FOUND, "Not Found").into_response();
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
// ---------------------------
|
|
196
|
+
// LOAD JS ACTION
|
|
197
|
+
// ---------------------------
|
|
198
|
+
let resolved = resolve_actions_dir();
|
|
199
|
+
let actions_dir = resolved
|
|
200
|
+
.exists()
|
|
201
|
+
.then(|| resolved)
|
|
202
|
+
.or_else(|| find_actions_dir(&state.project_root))
|
|
203
|
+
.unwrap();
|
|
204
|
+
|
|
205
|
+
let mut action_path = actions_dir.join(format!("{}.jsbundle", action_name));
|
|
206
|
+
if !action_path.exists() {
|
|
207
|
+
let js_path = actions_dir.join(format!("{}.js", action_name));
|
|
208
|
+
if js_path.exists() {
|
|
209
|
+
action_path = js_path;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
let js_code =
|
|
214
|
+
match fs::read_to_string(&action_path) {
|
|
215
|
+
Ok(c) => c,
|
|
216
|
+
Err(_) => return (
|
|
217
|
+
StatusCode::INTERNAL_SERVER_ERROR,
|
|
218
|
+
Json(
|
|
219
|
+
serde_json::json!({"error": "Action bundle not found", "action": action_name}),
|
|
220
|
+
),
|
|
221
|
+
)
|
|
222
|
+
.into_response(),
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
// ---------------------------
|
|
226
|
+
// EXECUTE IN V8
|
|
227
|
+
// ---------------------------
|
|
228
|
+
let env_json = std::env::vars()
|
|
229
|
+
.map(|(k, v)| (k, Value::String(v)))
|
|
230
|
+
.collect::<serde_json::Map<_, _>>();
|
|
231
|
+
|
|
232
|
+
let injected = format!(
|
|
233
|
+
r#"
|
|
234
|
+
globalThis.process = {{ env: {} }};
|
|
235
|
+
const __titan_req = {{
|
|
236
|
+
body: {},
|
|
237
|
+
method: "{}",
|
|
238
|
+
path: "{}",
|
|
239
|
+
headers: {},
|
|
240
|
+
params: {},
|
|
241
|
+
query: {}
|
|
242
|
+
}};
|
|
243
|
+
(function() {{
|
|
244
|
+
{}
|
|
245
|
+
}})(); // Run the bundle
|
|
246
|
+
// Call the action
|
|
247
|
+
if (typeof globalThis["{}"] === 'function') {{
|
|
248
|
+
globalThis["{}"](__titan_req);
|
|
249
|
+
}} else {{
|
|
250
|
+
throw new Error("Action function '{}' not found in bundle");
|
|
251
|
+
}}
|
|
252
|
+
"#,
|
|
253
|
+
Value::Object(env_json).to_string(),
|
|
254
|
+
body_json.to_string(),
|
|
255
|
+
method,
|
|
256
|
+
path,
|
|
257
|
+
serde_json::to_string(&headers).unwrap(),
|
|
258
|
+
serde_json::to_string(¶ms).unwrap(),
|
|
259
|
+
serde_json::to_string(&query).unwrap(),
|
|
260
|
+
js_code,
|
|
261
|
+
action_name,
|
|
262
|
+
action_name,
|
|
263
|
+
action_name
|
|
264
|
+
);
|
|
265
|
+
|
|
266
|
+
// Run V8 in a blocking task safely?
|
|
267
|
+
// Axum handlers are async. V8 operations should be blocking.
|
|
268
|
+
// We can use `task::spawn_blocking`.
|
|
269
|
+
let root = state.project_root.clone();
|
|
270
|
+
let action_name_for_v8 = action_name.clone();
|
|
271
|
+
|
|
272
|
+
let result_json: Value = tokio::task::spawn_blocking(move || {
|
|
273
|
+
let isolate = &mut v8::Isolate::new(v8::CreateParams::default());
|
|
274
|
+
let handle_scope = &mut v8::HandleScope::new(isolate);
|
|
275
|
+
let context = v8::Context::new(handle_scope, v8::ContextOptions::default());
|
|
276
|
+
let scope = &mut v8::ContextScope::new(handle_scope, context);
|
|
277
|
+
|
|
278
|
+
let global = context.global(scope);
|
|
279
|
+
|
|
280
|
+
// Inject extensions (t.read, etc)
|
|
281
|
+
inject_extensions(scope, global);
|
|
282
|
+
|
|
283
|
+
// Set metadata globals
|
|
284
|
+
let root_str = v8::String::new(scope, root.to_str().unwrap_or(".")).unwrap();
|
|
285
|
+
let root_key = v8::String::new(scope, "__titan_root").unwrap();
|
|
286
|
+
global.set(scope, root_key.into(), root_str.into());
|
|
287
|
+
|
|
288
|
+
let action_str = v8::String::new(scope, &action_name_for_v8).unwrap();
|
|
289
|
+
let action_key = v8::String::new(scope, "__titan_action").unwrap();
|
|
290
|
+
global.set(scope, action_key.into(), action_str.into());
|
|
291
|
+
|
|
292
|
+
let source = v8::String::new(scope, &injected).unwrap();
|
|
293
|
+
|
|
294
|
+
let try_catch = &mut v8::TryCatch::new(scope);
|
|
295
|
+
|
|
296
|
+
let script = match v8::Script::compile(try_catch, source, None) {
|
|
297
|
+
Some(s) => s,
|
|
298
|
+
None => {
|
|
299
|
+
let err = try_catch.message().unwrap();
|
|
300
|
+
let msg = err.get(try_catch).to_rust_string_lossy(try_catch);
|
|
301
|
+
return serde_json::json!({ "error": msg, "phase": "compile" });
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
let result = script.run(try_catch);
|
|
306
|
+
|
|
307
|
+
match result {
|
|
308
|
+
Some(val) => {
|
|
309
|
+
// Convert v8 Value to Serde JSON
|
|
310
|
+
// Minimal impl: stringify
|
|
311
|
+
let json_obj = v8::json::stringify(try_catch, val).unwrap();
|
|
312
|
+
let json_str = json_obj.to_rust_string_lossy(try_catch);
|
|
313
|
+
serde_json::from_str(&json_str).unwrap_or(Value::Null)
|
|
314
|
+
}
|
|
315
|
+
None => {
|
|
316
|
+
let err = try_catch.message().unwrap();
|
|
317
|
+
let msg = err.get(try_catch).to_rust_string_lossy(try_catch);
|
|
318
|
+
serde_json::json!({ "error": msg, "phase": "execution" })
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
})
|
|
322
|
+
.await
|
|
323
|
+
.unwrap_or(serde_json::json!({"error": "V8 task failed"}));
|
|
324
|
+
|
|
325
|
+
// ---------------------------
|
|
326
|
+
// FINAL LOG
|
|
327
|
+
// ---------------------------
|
|
328
|
+
let elapsed = start.elapsed();
|
|
329
|
+
|
|
330
|
+
// Check for errors in result
|
|
331
|
+
if let Some(err) = result_json.get("error") {
|
|
332
|
+
println!(
|
|
333
|
+
"{} {} {} {}",
|
|
334
|
+
blue("[Titan]"),
|
|
335
|
+
red(&format!("{} {}", method, path)),
|
|
336
|
+
red("→ error"),
|
|
337
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
338
|
+
);
|
|
339
|
+
println!("{}", red(err.as_str().unwrap_or("Unknown")));
|
|
340
|
+
return (StatusCode::INTERNAL_SERVER_ERROR, Json(result_json)).into_response();
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
match route_kind {
|
|
344
|
+
"dynamic" => println!(
|
|
345
|
+
"{} {} {} {} {} {}",
|
|
346
|
+
blue("[Titan]"),
|
|
347
|
+
green(&format!("{} {}", method, path)),
|
|
348
|
+
white("→"),
|
|
349
|
+
green(&route_label),
|
|
350
|
+
white("(dynamic)"),
|
|
351
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
352
|
+
),
|
|
353
|
+
"exact" => println!(
|
|
354
|
+
"{} {} {} {} {}",
|
|
355
|
+
blue("[Titan]"),
|
|
356
|
+
white(&format!("{} {}", method, path)),
|
|
357
|
+
white("→"),
|
|
358
|
+
yellow(&route_label),
|
|
359
|
+
gray(&format!("in {:.2?}", elapsed))
|
|
360
|
+
),
|
|
361
|
+
_ => {}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
Json(result_json).into_response()
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// Entrypoint ---------------------------------------------------------------
|
|
368
|
+
|
|
369
|
+
#[tokio::main]
|
|
370
|
+
async fn main() -> Result<()> {
|
|
371
|
+
dotenvy::dotenv().ok();
|
|
372
|
+
init_v8(); // Init platform once
|
|
373
|
+
|
|
374
|
+
// Load routes.json
|
|
375
|
+
let raw = fs::read_to_string("./routes.json").unwrap_or_else(|_| "{}".to_string());
|
|
376
|
+
let json: Value = serde_json::from_str(&raw).unwrap_or_default();
|
|
377
|
+
|
|
378
|
+
let port = json["__config"]["port"].as_u64().unwrap_or(3000);
|
|
379
|
+
let routes_json = json["routes"].clone();
|
|
380
|
+
let map: HashMap<String, RouteVal> = serde_json::from_value(routes_json).unwrap_or_default();
|
|
381
|
+
let dynamic_routes: Vec<DynamicRoute> =
|
|
382
|
+
serde_json::from_value(json["__dynamic_routes"].clone()).unwrap_or_default();
|
|
383
|
+
|
|
384
|
+
// Identify project root (where .ext or node_modules lives)
|
|
385
|
+
let project_root = resolve_project_root();
|
|
386
|
+
|
|
387
|
+
let state = AppState {
|
|
388
|
+
routes: Arc::new(map),
|
|
389
|
+
dynamic_routes: Arc::new(dynamic_routes),
|
|
390
|
+
project_root: project_root.clone(),
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
// Load extensions
|
|
394
|
+
extensions::load_project_extensions(project_root.clone());
|
|
395
|
+
|
|
396
|
+
let app = Router::new()
|
|
397
|
+
.route("/", any(root_route))
|
|
398
|
+
.fallback(any(dynamic_route))
|
|
399
|
+
.with_state(state);
|
|
400
|
+
|
|
401
|
+
let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).await?;
|
|
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,157 @@
|
|
|
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
|
+
const rustOutDir = path.join(root, "server", "src", "actions_rust");
|
|
9
|
+
|
|
10
|
+
export async function bundle() {
|
|
11
|
+
const start = Date.now();
|
|
12
|
+
await bundleJs();
|
|
13
|
+
await bundleRust();
|
|
14
|
+
// console.log(`[Titan] Bundle finished in ${((Date.now() - start) / 1000).toFixed(2)}s`);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async function bundleJs() {
|
|
18
|
+
// console.log("[Titan] Bundling JS actions...");
|
|
19
|
+
|
|
20
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
21
|
+
|
|
22
|
+
// Clean old bundles
|
|
23
|
+
const oldFiles = fs.readdirSync(outDir);
|
|
24
|
+
for (const file of oldFiles) {
|
|
25
|
+
fs.unlinkSync(path.join(outDir, file));
|
|
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
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function bundleRust() {
|
|
81
|
+
// console.log("[Titan] Bundling Rust actions...");
|
|
82
|
+
|
|
83
|
+
if (!fs.existsSync(rustOutDir)) {
|
|
84
|
+
fs.mkdirSync(rustOutDir, { recursive: true });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Clean old rust actions
|
|
88
|
+
for (const file of fs.readdirSync(rustOutDir)) {
|
|
89
|
+
fs.unlinkSync(path.join(rustOutDir, file));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const files = fs.readdirSync(actionsDir).filter(f => f.endsWith(".rs"));
|
|
93
|
+
if (files.length > 0) {
|
|
94
|
+
// console.log(`[Titan] Bundling ${files.length} Rust actions...`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const modules = [];
|
|
98
|
+
|
|
99
|
+
for (const file of files) {
|
|
100
|
+
const actionName = path.basename(file, ".rs");
|
|
101
|
+
const entry = path.join(actionsDir, file);
|
|
102
|
+
let outfile = path.join(rustOutDir, file);
|
|
103
|
+
|
|
104
|
+
let content = fs.readFileSync(entry, 'utf-8');
|
|
105
|
+
|
|
106
|
+
// Prepend implicit imports if not present
|
|
107
|
+
let finalContent = content;
|
|
108
|
+
if (!content.includes("use crate::extensions::t;")) {
|
|
109
|
+
finalContent = "use crate::extensions::t;\n" + content;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Basic validation - check if it has a run function
|
|
113
|
+
if (!content.includes("async fn run")) {
|
|
114
|
+
console.warn(`[Titan] Warning: ${file} does not appear to have an 'async fn run'. It might fail to compile.`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
fs.writeFileSync(outfile, finalContent);
|
|
118
|
+
modules.push(actionName);
|
|
119
|
+
// console.log(`[Titan] Copied Rust action ${actionName}`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Generate mod.rs
|
|
123
|
+
let modContent = `// Auto-generated by Titan. Do not edit.
|
|
124
|
+
use axum::response::IntoResponse;
|
|
125
|
+
use axum::http::Request;
|
|
126
|
+
use axum::body::Body;
|
|
127
|
+
use std::future::Future;
|
|
128
|
+
use std::pin::Pin;
|
|
129
|
+
|
|
130
|
+
`;
|
|
131
|
+
|
|
132
|
+
// Add mod declarations
|
|
133
|
+
for (const mod of modules) {
|
|
134
|
+
modContent += `pub mod ${mod};\n`;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
modContent += `
|
|
138
|
+
pub type ActionFn = fn(Request<Body>) -> Pin<Box<dyn Future<Output = axum::response::Response> + Send>>;
|
|
139
|
+
|
|
140
|
+
pub fn get_action(name: &str) -> Option<ActionFn> {
|
|
141
|
+
match name {
|
|
142
|
+
`;
|
|
143
|
+
|
|
144
|
+
for (const mod of modules) {
|
|
145
|
+
modContent += ` "${mod}" => Some(|req| Box::pin(async move {
|
|
146
|
+
${mod}::run(req).await.into_response()
|
|
147
|
+
})),\n`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
modContent += ` _ => None
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
`;
|
|
154
|
+
|
|
155
|
+
fs.writeFileSync(path.join(rustOutDir, "mod.rs"), modContent);
|
|
156
|
+
// console.log("[Titan] Rust Bundling finished.");
|
|
157
|
+
}
|