@ezetgalaxy/titan 26.8.3 → 26.9.1

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.
Files changed (106) hide show
  1. package/README.md +76 -17
  2. package/index.js +118 -29
  3. package/package.json +1 -2
  4. package/templates/extension/README.md +104 -104
  5. package/templates/extension/index.js +27 -27
  6. package/templates/extension/jsconfig.json +12 -12
  7. package/templates/extension/native/Cargo.toml +9 -9
  8. package/templates/extension/native/src/lib.rs +5 -5
  9. package/templates/extension/package.json +20 -20
  10. package/templates/extension/titan.json +17 -17
  11. package/templates/js/Dockerfile +66 -66
  12. package/templates/js/_dockerignore +3 -3
  13. package/templates/js/_gitignore +1 -0
  14. package/templates/js/app/actions/hello.js +5 -5
  15. package/templates/js/app/titan.d.ts +87 -87
  16. package/templates/js/jsconfig.json +18 -18
  17. package/templates/js/server/src/action_management.rs +131 -131
  18. package/templates/js/server/src/errors.rs +10 -10
  19. package/templates/js/server/src/extensions.rs +989 -989
  20. package/templates/js/server/src/utils.rs +33 -33
  21. package/templates/js/titan/bundle.js +78 -78
  22. package/templates/js/titan/dev.js +9 -1
  23. package/templates/js/titan/titan.js +122 -122
  24. package/templates/{rust → rust-js}/Dockerfile +66 -66
  25. package/templates/{rust → rust-js}/_dockerignore +3 -3
  26. package/templates/{rust → rust-js}/_gitignore +1 -0
  27. package/templates/{rust → rust-js}/app/actions/hello.js +5 -5
  28. package/templates/{rust → rust-js}/app/actions/rust_hello.rs +14 -14
  29. package/templates/{rust → rust-js}/app/titan.d.ts +101 -101
  30. package/templates/{rust → rust-js}/jsconfig.json +18 -18
  31. package/templates/{rust → rust-js}/package.json +1 -1
  32. package/templates/{rust → rust-js}/server/src/action_management.rs +131 -131
  33. package/templates/{rust → rust-js}/server/src/errors.rs +10 -10
  34. package/templates/{rust → rust-js}/server/src/extensions.rs +989 -989
  35. package/templates/{rust → rust-js}/server/src/utils.rs +33 -33
  36. package/templates/{rust → rust-js}/titan/dev.js +9 -1
  37. package/templates/rust-ts/Dockerfile +66 -0
  38. package/templates/rust-ts/_dockerignore +3 -0
  39. package/templates/rust-ts/_gitignore +38 -0
  40. package/templates/rust-ts/app/actions/hello.ts +11 -0
  41. package/templates/rust-ts/app/actions/rust_hello.rs +14 -0
  42. package/templates/rust-ts/app/app.ts +11 -0
  43. package/templates/rust-ts/package.json +14 -0
  44. package/templates/rust-ts/server/Cargo.lock +2869 -0
  45. package/templates/rust-ts/server/Cargo.toml +39 -0
  46. package/templates/rust-ts/server/src/action_management.rs +131 -0
  47. package/templates/rust-ts/server/src/errors.rs +51 -0
  48. package/templates/rust-ts/server/src/extensions.rs +989 -0
  49. package/templates/rust-ts/server/src/main.rs +468 -0
  50. package/templates/rust-ts/server/src/utils.rs +33 -0
  51. package/templates/rust-ts/titan/bundle.js +163 -0
  52. package/templates/rust-ts/titan/dev.js +402 -0
  53. package/templates/rust-ts/titan/titan.d.ts +117 -0
  54. package/templates/rust-ts/titan/titan.js +122 -0
  55. package/templates/rust-ts/tsconfig.json +21 -0
  56. package/templates/ts/Dockerfile +40 -0
  57. package/templates/ts/_dockerignore +3 -0
  58. package/templates/ts/_gitignore +38 -0
  59. package/templates/ts/app/actions/hello.ts +11 -0
  60. package/templates/ts/app/app.ts +10 -0
  61. package/templates/ts/package.json +26 -0
  62. package/templates/ts/server/Cargo.lock +2869 -0
  63. package/templates/ts/server/Cargo.toml +27 -0
  64. package/templates/ts/server/src/action_management.rs +131 -0
  65. package/templates/ts/server/src/errors.rs +51 -0
  66. package/templates/ts/server/src/extensions.rs +989 -0
  67. package/templates/ts/server/src/main.rs +437 -0
  68. package/templates/ts/server/src/utils.rs +33 -0
  69. package/templates/ts/titan/builder.js +121 -0
  70. package/templates/ts/titan/bundle.js +76 -0
  71. package/templates/ts/titan/dev.js +402 -0
  72. package/templates/ts/titan/runtime.js +1 -0
  73. package/templates/ts/titan/titan.d.ts +117 -0
  74. package/templates/ts/titan/titan.js +122 -0
  75. package/templates/ts/tsconfig.json +16 -0
  76. package/titanpl-sdk/README.md +109 -109
  77. package/titanpl-sdk/bin/run.js +251 -254
  78. package/titanpl-sdk/index.d.ts +46 -46
  79. package/titanpl-sdk/index.js +5 -5
  80. package/titanpl-sdk/package.json +32 -32
  81. package/titanpl-sdk/templates/.dockerignore +3 -3
  82. package/titanpl-sdk/templates/Dockerfile +53 -53
  83. package/titanpl-sdk/templates/app/actions/hello.js +5 -5
  84. package/titanpl-sdk/templates/app/titan.d.ts +87 -87
  85. package/titanpl-sdk/templates/jsconfig.json +18 -18
  86. package/titanpl-sdk/templates/server/src/action_management.rs +131 -131
  87. package/titanpl-sdk/templates/server/src/errors.rs +10 -10
  88. package/titanpl-sdk/templates/server/src/extensions.rs +640 -640
  89. package/titanpl-sdk/templates/server/src/utils.rs +33 -33
  90. package/titanpl-sdk/templates/titan/bundle.js +65 -65
  91. package/titanpl-sdk/templates/titan/dev.js +113 -113
  92. package/titanpl-sdk/templates/titan/titan.js +98 -98
  93. package/templates/js/server/action_map.json +0 -3
  94. package/templates/js/server/actions/hello.jsbundle +0 -48
  95. package/templates/js/server/routes.json +0 -16
  96. package/templates/rust/server/action_map.json +0 -3
  97. package/templates/rust/server/actions/hello.jsbundle +0 -47
  98. package/templates/rust/server/routes.json +0 -22
  99. package/templates/rust/server/src/actions_rust/mod.rs +0 -19
  100. package/templates/rust/server/src/actions_rust/rust_hello.rs +0 -14
  101. /package/templates/{rust → rust-js}/app/app.js +0 -0
  102. /package/templates/{rust → rust-js}/server/Cargo.lock +0 -0
  103. /package/templates/{rust → rust-js}/server/Cargo.toml +0 -0
  104. /package/templates/{rust → rust-js}/server/src/main.rs +0 -0
  105. /package/templates/{rust → rust-js}/titan/bundle.js +0 -0
  106. /package/templates/{rust → rust-js}/titan/titan.js +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
+ 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(&params).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,121 @@
1
+ import { bundle } from "./bundle.js";
2
+ import fs from "fs";
3
+ import path from "path";
4
+
5
+ const cyan = (t) => `\x1b[36m${t}\x1b[0m`;
6
+ const green = (t) => `\x1b[32m${t}\x1b[0m`;
7
+
8
+ const routes = {};
9
+ const dynamicRoutes = {};
10
+ const actionMap = {};
11
+
12
+ function addRoute(method, route) {
13
+ const key = `${method.toUpperCase()}:${route}`;
14
+
15
+
16
+ return {
17
+ reply(value) {
18
+ routes[key] = {
19
+ type: typeof value === "object" ? "json" : "text",
20
+ value
21
+ };
22
+ },
23
+
24
+ action(name) {
25
+ if (route.includes(":")) {
26
+ if (!dynamicRoutes[method]) dynamicRoutes[method] = [];
27
+ dynamicRoutes[method].push({
28
+ method: method.toUpperCase(),
29
+ pattern: route,
30
+ action: name
31
+ });
32
+ } else {
33
+ routes[key] = {
34
+ type: "action",
35
+ value: name
36
+ };
37
+ actionMap[key] = name;
38
+ }
39
+ }
40
+ };
41
+ }
42
+
43
+ /**
44
+ * @typedef {Object} RouteHandler
45
+ * @property {(value: any) => void} reply - Send a direct response
46
+ * @property {(name: string) => void} action - Bind to a server-side action
47
+ */
48
+
49
+ /**
50
+ * Titan App Builder
51
+ */
52
+ const t = {
53
+ /**
54
+ * Define a GET route
55
+ * @param {string} route
56
+ * @returns {RouteHandler}
57
+ */
58
+ get(route) {
59
+ return addRoute("GET", route);
60
+ },
61
+
62
+ /**
63
+ * Define a POST route
64
+ * @param {string} route
65
+ * @returns {RouteHandler}
66
+ */
67
+ post(route) {
68
+ return addRoute("POST", route);
69
+ },
70
+
71
+ log(module, msg) {
72
+ console.log(`[\x1b[35m${module}\x1b[0m] ${msg}`);
73
+ },
74
+
75
+ /**
76
+ * Start the Titan Server
77
+ * @param {number} [port=3000]
78
+ * @param {string} [msg=""]
79
+ */
80
+ async start(port = 3000, msg = "") {
81
+ try {
82
+ console.log(cyan("[Titan] Preparing runtime..."));
83
+ await bundle();
84
+
85
+ const base = path.join(process.cwd(), "server");
86
+ if (!fs.existsSync(base)) {
87
+ fs.mkdirSync(base, { recursive: true });
88
+ }
89
+
90
+ const routesPath = path.join(base, "routes.json");
91
+ const actionMapPath = path.join(base, "action_map.json");
92
+
93
+ fs.writeFileSync(
94
+ routesPath,
95
+ JSON.stringify(
96
+ {
97
+ __config: { port },
98
+ routes,
99
+ __dynamic_routes: Object.values(dynamicRoutes).flat()
100
+ },
101
+ null,
102
+ 2
103
+ )
104
+ );
105
+
106
+ fs.writeFileSync(
107
+ actionMapPath,
108
+ JSON.stringify(actionMap, null, 2)
109
+ );
110
+
111
+ console.log(green("✔ Titan metadata written successfully"));
112
+ if (msg) console.log(cyan(msg));
113
+
114
+ } catch (e) {
115
+ console.error(`\x1b[31m[Titan] Build Error: ${e.message}\x1b[0m`);
116
+ process.exit(1);
117
+ }
118
+ }
119
+ };
120
+
121
+ export default t;
@@ -0,0 +1,76 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import esbuild from "esbuild";
4
+
5
+ export async function bundle() {
6
+ const root = process.cwd();
7
+ const actionsDir = path.join(root, "app", "actions");
8
+ const outDir = path.join(root, "server", "actions");
9
+
10
+ const start = Date.now();
11
+ await bundleJs(actionsDir, outDir);
12
+ // console.log(`[Titan] Bundle finished in ${((Date.now() - start) / 1000).toFixed(2)}s`);
13
+ }
14
+
15
+ async function bundleJs(actionsDir, outDir) {
16
+ // console.log("[Titan] Bundling JS actions...");
17
+
18
+ fs.mkdirSync(outDir, { recursive: true });
19
+
20
+ // Clean old bundles
21
+ const oldFiles = fs.readdirSync(outDir);
22
+ for (const file of oldFiles) {
23
+ fs.unlinkSync(path.join(outDir, file));
24
+ }
25
+
26
+ const files = fs.readdirSync(actionsDir).filter(f => f.endsWith(".js") || f.endsWith(".ts"));
27
+ if (files.length === 0) return;
28
+
29
+ // console.log(`[Titan] Bundling ${files.length} JS actions...`);
30
+
31
+ for (const file of files) {
32
+ const actionName = path.basename(file, path.extname(file));
33
+
34
+ const entry = path.join(actionsDir, file);
35
+
36
+ // Rust runtime expects `.jsbundle` extension — consistent with previous design
37
+ const outfile = path.join(outDir, actionName + ".jsbundle");
38
+
39
+ // console.log(`[Titan] Bundling ${entry} → ${outfile}`);
40
+
41
+ await esbuild.build({
42
+ entryPoints: [entry],
43
+ outfile,
44
+ bundle: true,
45
+ format: "iife",
46
+ globalName: "__titan_exports",
47
+ platform: "neutral",
48
+ target: "es2020",
49
+ logLevel: "silent",
50
+ banner: {
51
+ js: "const defineAction = (fn) => fn;"
52
+ },
53
+
54
+ footer: {
55
+ js: `
56
+ (function () {
57
+ const fn =
58
+ __titan_exports["${actionName}"] ||
59
+ __titan_exports.default;
60
+
61
+ if (typeof fn !== "function") {
62
+ throw new Error("[Titan] Action '${actionName}' not found or not a function");
63
+ }
64
+
65
+ globalThis["${actionName}"] = function(request_arg) {
66
+ globalThis.req = request_arg;
67
+ return fn(request_arg);
68
+ };
69
+ })();
70
+ `
71
+ }
72
+ });
73
+ }
74
+
75
+ // console.log("[Titan] JS Bundling finished.");
76
+ }