@titanpl/cli 5.0.6 → 7.0.0-beta

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/index.js CHANGED
@@ -11,6 +11,10 @@ import { migrateCommand } from "./src/commands/migrate.js";
11
11
  import { updateCommand } from "./src/commands/update.js";
12
12
  import { initCommand } from "./src/commands/init.js";
13
13
 
14
+ import { createCommand } from "./src/commands/create.js";
15
+ import { buildExtensionCommand } from "./src/commands/build-ext.js";
16
+ import { runExtensionCommand } from "./src/commands/run-ext.js";
17
+
14
18
  /* -------------------------------------------------------
15
19
  * Resolve __dirname (ESM safe)
16
20
  * ----------------------------------------------------- */
@@ -54,6 +58,7 @@ ${bold(cyan("╰─────────────────────
54
58
  ${cyan("init")} ${gray("Scaffold a new Titan project")}
55
59
  ${cyan("create")} ${gray("Create a new project or extension (e.g. 'titan create ext my-ext')")}
56
60
  ${cyan("build")} ${gray("Compile actions and build production dist. Use --release or -r for a production-ready folder.")}
61
+ ${cyan("run")} ${gray("Run the production Gravity Engine or an extension sandbox")}
57
62
  ${cyan("dev")} ${gray("Start the Gravity Engine in dev/watch mode")}
58
63
  ${cyan("start")} ${gray("Start the production Gravity Engine")}
59
64
  ${cyan("update")} ${gray("Update an existing project to latest Titan version")}
@@ -112,26 +117,35 @@ const cmd = process.argv[2];
112
117
  case "create": {
113
118
  const type = process.argv[3];
114
119
  const name = process.argv[4];
115
- if (type === "ext" || type === "extension") {
116
- await initCommand(name, "extension");
117
- } else {
118
- // Fallback to init behavior
119
- await initCommand(type, null);
120
- }
120
+ await createCommand(type, name);
121
121
  break;
122
122
  }
123
123
 
124
- case "build":
125
- const isRelease = process.argv.includes("--release") || process.argv.includes("-r");
126
- console.log(cyan(`→ Building Titan project${isRelease ? " (Release mode)" : ""}...`));
127
- await buildCommand(isRelease);
128
- console.log(green(`✔ ${isRelease ? "Release" : "Build"} complete`));
124
+ case "build": {
125
+ if (process.argv[3] === "ext" || process.argv[3] === "extension") {
126
+ await buildExtensionCommand();
127
+ } else {
128
+ const isRelease = process.argv.includes("--release") || process.argv.includes("-r");
129
+ console.log(cyan(`→ Building Titan project${isRelease ? " (Release mode)" : ""}...`));
130
+ await buildCommand(isRelease);
131
+ console.log(green(`✔ ${isRelease ? "Release" : "Build"} complete`));
132
+ }
129
133
  break;
134
+ }
130
135
 
131
136
  case "dev":
132
137
  await devCommand();
133
138
  break;
134
139
 
140
+ case "run":
141
+ if (process.argv[3] === "ext" || process.argv[3] === "extension") {
142
+ await runExtensionCommand();
143
+ } else {
144
+ console.log(cyan("→ Starting Titan Server..."));
145
+ startCommand();
146
+ }
147
+ break;
148
+
135
149
  case "start":
136
150
  console.log(cyan("→ Starting Titan Server..."));
137
151
  startCommand();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@titanpl/cli",
3
- "version": "5.0.6",
3
+ "version": "7.0.0-beta",
4
4
  "description": "The unified CLI for Titan Planet. Use it to create, manage, build, and deploy high-performance backend projects.",
5
5
  "keywords": [
6
6
  "titanpl",
@@ -29,13 +29,13 @@
29
29
  "tit": "./index.js"
30
30
  },
31
31
  "optionalDependencies": {
32
- "@titanpl/engine-win32-x64": "2.0.4",
33
- "@titanpl/engine-linux-x64": "2.0.4"
32
+ "@titanpl/engine-win32-x64": "7.0.0-beta",
33
+ "@titanpl/engine-linux-x64": "7.0.0-beta"
34
34
  },
35
35
  "dependencies": {
36
- "@titanpl/packet": "4.0.2",
36
+ "@titanpl/packet": "7.0.0-beta",
37
37
  "prompts": "^2.4.2",
38
38
  "commander": "^11.0.0",
39
39
  "chalk": "^4.1.2"
40
40
  }
41
- }
41
+ }
@@ -0,0 +1,157 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { execSync } from 'child_process';
4
+ import chalk from 'chalk';
5
+
6
+ export async function buildExtensionCommand() {
7
+ const titanJsonPath = path.join(process.cwd(), 'titan.json');
8
+ if (!fs.existsSync(titanJsonPath)) {
9
+ console.log(chalk.red("✖ No titan.json found in current directory."));
10
+ return;
11
+ }
12
+
13
+ const titanJson = JSON.parse(fs.readFileSync(titanJsonPath, 'utf8'));
14
+ const type = titanJson.type;
15
+
16
+ if (type === 'js') {
17
+ console.log(chalk.yellow("! JS-only extensions do not require a build step."));
18
+ return;
19
+ }
20
+
21
+ console.log(chalk.cyan(`\n→ Building ${type.toUpperCase()} extension '${titanJson.name}'...\n`));
22
+
23
+ if (type === 'wasm') {
24
+ await buildWasmExtension(titanJson);
25
+ } else if (type === 'native') {
26
+ await buildNativeExtension(titanJson);
27
+ }
28
+ }
29
+
30
+ async function buildWasmExtension(titanJson) {
31
+ const nativeDir = path.join(process.cwd(), 'native');
32
+ if (!fs.existsSync(nativeDir)) {
33
+ console.log(chalk.red("✖ native/ directory not found."));
34
+ return;
35
+ }
36
+
37
+ console.log(chalk.gray(" Compiling Rust to WebAssembly..."));
38
+ try {
39
+ // We assume wasm-pack or similar is used, or just bare cargo with wasm32 target
40
+ // The spec mentions: native/pkg/my_ext.wasm, which is wasm-pack's default
41
+ execSync('wasm-pack build --target web', { cwd: nativeDir, stdio: 'inherit' });
42
+ } catch (err) {
43
+ console.log(chalk.red("✖ Wasm compilation failed. Make sure 'wasm-pack' is installed."));
44
+ return;
45
+ }
46
+
47
+ console.log(chalk.gray(" Generating bindings..."));
48
+ const libRsPath = path.join(nativeDir, 'src/lib.rs');
49
+ const libRs = fs.readFileSync(libRsPath, 'utf8');
50
+
51
+ const exports = [];
52
+ const exportRegex = /#\[titan::export\]\s+pub\s+fn\s+(\w+)\s*\(([^)]*)\)\s*(?:->\s*([^\{]+))?/g;
53
+ let match;
54
+ while ((match = exportRegex.exec(libRs)) !== null) {
55
+ const name = match[1];
56
+ const paramsRaw = match[2];
57
+ const params = paramsRaw.split(',').map(p => p.trim().split(':')[0].trim()).filter(p => p);
58
+ exports.push({ name, params });
59
+ }
60
+
61
+ const bindingsJs = `// Auto-generated by titan build ext
62
+ import * as wasm from './my_ext_bg.wasm';
63
+ export const { ${exports.map(e => e.name).join(', ')} } = wasm;
64
+ `;
65
+
66
+ const pkgDir = path.join(nativeDir, 'pkg');
67
+ fs.writeFileSync(path.join(pkgDir, 'bindings.js'), bindingsJs);
68
+
69
+ // Update index.js
70
+ const indexJs = `import { registerExtension } from './utils/registerExtension.js';
71
+ import * as native from './native/pkg/bindings.js';
72
+
73
+ const myExt = {
74
+ ${exports.map(e => `${e.name}: (${e.params.join(', ')}) => native.${e.name}(${e.params.join(', ')})`).join(',\n ')}
75
+ };
76
+
77
+ registerExtension("${titanJson.name.split('/').pop()}", myExt);
78
+ `;
79
+ fs.writeFileSync(path.join(process.cwd(), 'index.js'), indexJs);
80
+
81
+ // Update titan.json
82
+ titanJson.wasm = "native/pkg/my_ext_bg.wasm";
83
+ titanJson.bindings = "native/pkg/bindings.js";
84
+ fs.writeFileSync(path.join(process.cwd(), 'titan.json'), JSON.stringify(titanJson, null, 2));
85
+
86
+ console.log(chalk.green("✔ Wasm build complete."));
87
+ }
88
+
89
+ async function buildNativeExtension(titanJson) {
90
+ const nativeDir = path.join(process.cwd(), 'native');
91
+ if (!fs.existsSync(nativeDir)) {
92
+ console.log(chalk.red("✖ native/ directory not found."));
93
+ return;
94
+ }
95
+
96
+ console.log(chalk.gray(" Compiling Rust native library..."));
97
+ try {
98
+ execSync('cargo build --release', { cwd: nativeDir, stdio: 'inherit' });
99
+ } catch (err) {
100
+ console.log(chalk.red("✖ Native compilation failed."));
101
+ return;
102
+ }
103
+
104
+ const libName = titanJson.name.split('/').pop().replace(/-/g, '_');
105
+ const isWindows = process.platform === 'win32';
106
+ const isMac = process.platform === 'darwin';
107
+
108
+ let binName = `lib${libName}.so`;
109
+ if (isWindows) binName = `${libName}.dll`;
110
+ if (isMac) binName = `lib${libName}.dylib`;
111
+
112
+ const buildDir = path.join(nativeDir, 'build');
113
+ if (!fs.existsSync(buildDir)) fs.mkdirSync(buildDir);
114
+
115
+ const targetDir = path.join(nativeDir, 'target/release');
116
+ const srcPath = path.join(targetDir, binName);
117
+ const destPath = path.join(buildDir, binName);
118
+
119
+ if (fs.existsSync(srcPath)) {
120
+ fs.copyFileSync(srcPath, destPath);
121
+ }
122
+
123
+ // Parse exports for index.js
124
+ const libRsPath = path.join(nativeDir, 'src/lib.rs');
125
+ const libRs = fs.readFileSync(libRsPath, 'utf8');
126
+ const exports = [];
127
+ const exportRegex = /#\[titan::native_export\]\s+pub\s+extern\s+"C"\s+fn\s+(\w+)\s*\(([^)]*)\)/g;
128
+ let match;
129
+ while ((match = exportRegex.exec(libRs)) !== null) {
130
+ const name = match[1];
131
+ const paramsRaw = match[2];
132
+ const params = paramsRaw.split(',').map(p => p.trim().split(':')[0].trim()).filter(p => p);
133
+ exports.push({ name, params });
134
+ }
135
+
136
+ // Update index.js
137
+ const indexJs = `import { registerExtension } from './utils/registerExtension.js';
138
+
139
+ // native bindings are injected by Gravity's NativeHost IPC bridge
140
+ const myExt = {
141
+ ${exports.map(e => `${e.name}: (${e.params.join(', ')}) => t.__native.call("${titanJson.name}", "${e.name}", [${e.params.join(', ')}])`).join(',\n ')}
142
+ };
143
+
144
+ registerExtension("${titanJson.name.split('/').pop()}", myExt);
145
+ `;
146
+ fs.writeFileSync(path.join(process.cwd(), 'index.js'), indexJs);
147
+
148
+ // Update titan.json
149
+ titanJson.native = {
150
+ linux: `native/build/lib${libName}.so`,
151
+ windows: `native/build/${libName}.dll`,
152
+ macos: `native/build/lib${libName}.dylib`
153
+ };
154
+ fs.writeFileSync(path.join(process.cwd(), 'titan.json'), JSON.stringify(titanJson, null, 2));
155
+
156
+ console.log(chalk.green("✔ Native build complete."));
157
+ }
@@ -1,7 +1,19 @@
1
1
  import { build, release } from "@titanpl/packet";
2
+ import fs from 'fs';
3
+ import path from 'path';
2
4
 
3
5
  export async function buildCommand(isRelease = false) {
4
6
  const buildFn = isRelease ? release : build;
5
7
  const dist = await buildFn(process.cwd());
8
+
9
+ const tanfigPath = path.join(process.cwd(), 'tanfig.json');
10
+ if (fs.existsSync(tanfigPath)) {
11
+ fs.copyFileSync(tanfigPath, path.join(dist, 'tanfig.json'));
12
+ }
13
+ const pkgPath = path.join(process.cwd(), 'package.json');
14
+ if (fs.existsSync(pkgPath)) {
15
+ fs.copyFileSync(pkgPath, path.join(dist, 'package.json'));
16
+ }
17
+
6
18
  console.log(`✔ ${isRelease ? 'Release' : 'Build'} complete →`, dist);
7
19
  }
@@ -0,0 +1,160 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+ import prompts from 'prompts';
5
+ import chalk from 'chalk';
6
+ import { copyDir } from './init.js';
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+
11
+ export async function createCommand(type, name) {
12
+ if (type === 'ext' || type === 'extension') {
13
+ await createExtension(name);
14
+ } else {
15
+ console.log(chalk.red(`\n✖ Unknown creation type: ${type}`));
16
+ console.log(chalk.gray(` Available types: ext\n`));
17
+ }
18
+ }
19
+
20
+ async function createExtension(extensionName) {
21
+ let name = extensionName;
22
+ if (!name) {
23
+ const res = await prompts({
24
+ type: 'text',
25
+ name: 'name',
26
+ message: 'Extension name:',
27
+ initial: 'my-ext'
28
+ });
29
+ name = res.name;
30
+ }
31
+
32
+ if (!name) {
33
+ console.log(chalk.red("✖ Extension name is required."));
34
+ return;
35
+ }
36
+
37
+ const res = await prompts({
38
+ type: 'select',
39
+ name: 'type',
40
+ message: 'What type of extension do you want to create?',
41
+ choices: [
42
+ { title: 'js — JavaScript only, zero build step, always safe', value: 'js' },
43
+ { title: 'wasm — Rust compiled to WebAssembly, sandboxed, auto-bound', value: 'wasm' },
44
+ { title: 'native — Rust compiled to .so/.dll, out-of-process, requires allowNative', value: 'native' },
45
+ ],
46
+ initial: 0
47
+ });
48
+
49
+ const extType = res.type;
50
+ if (!extType) return;
51
+
52
+ const targetDir = path.resolve(process.cwd(), name);
53
+ if (fs.existsSync(targetDir)) {
54
+ console.log(chalk.red(`\n✖ Directory '${name}' already exists.\n`));
55
+ return;
56
+ }
57
+
58
+ // Find template path (similar to init.js)
59
+ let templateDir = path.resolve(__dirname, '..', '..', '..', '..', 'templates', 'extension');
60
+ if (!fs.existsSync(templateDir)) {
61
+ templateDir = path.resolve(__dirname, '..', '..', 'templates', 'extension');
62
+ }
63
+
64
+ console.log(chalk.cyan(`\n→ Creating ${extType.toUpperCase()} extension '${name}'...\n`));
65
+
66
+ if (extType === 'js') {
67
+ try {
68
+ console.log(chalk.gray(` Cloning JS template from https://github.com/t8nlab/extTemplate.git...`));
69
+ const { execSync } = await import('child_process');
70
+ execSync(`git clone https://github.com/t8nlab/extTemplate.git "${targetDir}"`, { stdio: 'pipe' });
71
+ // Remove git history
72
+ fs.rmSync(path.join(targetDir, '.git'), { recursive: true, force: true });
73
+ } catch (err) {
74
+ console.log(chalk.yellow(` Git clone failed, falling back to local template...`));
75
+ copyDir(templateDir, targetDir);
76
+ }
77
+ } else {
78
+ // 1. Copy the source template
79
+ copyDir(templateDir, targetDir);
80
+ }
81
+
82
+ // 2. Perform transformations
83
+ transformExtension(targetDir, name, extType);
84
+
85
+ console.log(chalk.green(`\n✔ Extension '${name}' created successfully!`));
86
+ console.log(chalk.yellow(` cd ${name}`));
87
+ if (extType !== 'js') {
88
+ console.log(chalk.yellow(` titan build ext`));
89
+ }
90
+ console.log(chalk.yellow(` titan run ext\n`));
91
+ }
92
+
93
+ function transformExtension(target, name, type) {
94
+ // 1. Remove optional native folder if it's a JS extension
95
+ if (type === 'js') {
96
+ const nativeDir = path.join(target, 'native');
97
+ if (fs.existsSync(nativeDir)) {
98
+ fs.rmSync(nativeDir, { recursive: true, force: true });
99
+ }
100
+ }
101
+
102
+ // 2. Patch package.json
103
+ const pkgPath = path.join(target, 'package.json');
104
+ if (fs.existsSync(pkgPath)) {
105
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
106
+ pkg.name = name;
107
+ pkg.version = "1.0.0";
108
+ // Ensure dependencies
109
+ pkg.dependencies = pkg.dependencies || {};
110
+ pkg.dependencies["@titanpl/sdk"] = "2.0.0";
111
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
112
+ }
113
+
114
+ // 3. Patch titan.json
115
+ const titanPath = path.join(target, 'titan.json');
116
+ if (fs.existsSync(titanPath)) {
117
+ const titan = JSON.parse(fs.readFileSync(titanPath, 'utf8'));
118
+ titan.name = name;
119
+ titan.type = type;
120
+ titan.version = "1.0.0";
121
+ fs.writeFileSync(titanPath, JSON.stringify(titan, null, 2));
122
+ }
123
+
124
+ // 4. Cleanup git if it exists accidentally
125
+ const gitDir = path.join(target, '.git');
126
+ if (fs.existsSync(gitDir)) {
127
+ fs.rmSync(gitDir, { recursive: true, force: true });
128
+ }
129
+
130
+ // 5. Recursive template substitution for any {{name}} in files
131
+ substituteTemplates(target, name);
132
+ }
133
+
134
+ function substituteTemplates(dir, name) {
135
+ for (const file of fs.readdirSync(dir)) {
136
+ const fullPath = path.join(dir, file);
137
+ if (fs.lstatSync(fullPath).isDirectory()) {
138
+ substituteTemplates(fullPath, name);
139
+ } else {
140
+ const ext = path.extname(file).toLowerCase();
141
+ const textExts = ['.js', '.ts', '.json', '.md', '.txt', '.rs', '.toml', '.html', '.css', '.d.ts'];
142
+ if (textExts.includes(ext)) {
143
+ let content = fs.readFileSync(fullPath, 'utf8');
144
+ let changed = false;
145
+ if (content.includes("{{name}}")) {
146
+ content = content.replace(/{{name}}/g, name);
147
+ changed = true;
148
+ }
149
+ if (content.includes("workspace:*")) {
150
+ content = content.replace(/"@titanpl\/sdk": "workspace:\*"/g, '"@titanpl/sdk": "2.0.0"');
151
+ content = content.replace(/workspace:\*/g, "6.0.0");
152
+ changed = true;
153
+ }
154
+ if (changed) {
155
+ fs.writeFileSync(fullPath, content);
156
+ }
157
+ }
158
+ }
159
+ }
160
+ }
@@ -176,17 +176,7 @@ export async function initCommand(projectName, templateName) {
176
176
  }
177
177
  }
178
178
 
179
- // 4. Ensure tanfig.json exists with default build config
180
- const tanfigPath = path.join(target, "tanfig.json");
181
- if (!fs.existsSync(tanfigPath)) {
182
- const defaultConfig = {
183
- name: projName,
184
- build: {
185
- files: ["public", "static", "db", "config"]
186
- }
187
- };
188
- fs.writeFileSync(tanfigPath, JSON.stringify(defaultConfig, null, 2));
189
- }
179
+ // 4. Substitution is handled below by substitute()
190
180
 
191
181
 
192
182
  // Recursive template substitution
@@ -212,6 +202,10 @@ export async function initCommand(projectName, templateName) {
212
202
  content = content.replace(/{{native_name}}/g, projName.replace(/-/g, '_'));
213
203
  changed = true;
214
204
  }
205
+ if (content.includes("workspace:*")) {
206
+ content = content.replace(/workspace:\*/g, "6.0.0");
207
+ changed = true;
208
+ }
215
209
  if (changed) {
216
210
  fs.writeFileSync(fullPath, content);
217
211
  }
@@ -0,0 +1,104 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import chalk from 'chalk';
4
+ import http from 'node:http';
5
+
6
+ /**
7
+ * Runs the extension sandbox using a native Node.js server (zero dependencies).
8
+ */
9
+ export async function runExtensionCommand() {
10
+ const titanJsonPath = path.join(process.cwd(), 'titan.json');
11
+ if (!fs.existsSync(titanJsonPath)) {
12
+ console.log(chalk.red("✖ No titan.json found in current directory."));
13
+ return;
14
+ }
15
+
16
+ const titanJson = JSON.parse(fs.readFileSync(titanJsonPath, 'utf8'));
17
+ const port = 3000;
18
+
19
+ const server = http.createServer((req, res) => {
20
+ if (req.url === '/test' && req.method === 'GET') {
21
+ res.writeHead(200, { 'Content-Type': 'text/html' });
22
+ res.end(`
23
+ <!DOCTYPE html>
24
+ <html lang="en">
25
+ <head>
26
+ <meta charset="UTF-8">
27
+ <title>Titan Extension Sandbox - ${titanJson.name}</title>
28
+ <style>
29
+ body { font-family: 'Inter', sans-serif; background: #0f172a; color: #f8fafc; padding: 2rem; margin: 0; }
30
+ .container { max-width: 800px; margin: 0 auto; }
31
+ .card { background: #1e293b; padding: 2rem; border-radius: 1rem; border: 1px solid #334155; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.3); }
32
+ h1 { color: #38bdf8; margin-top: 0; display: flex; align-items: center; gap: 1rem; }
33
+ .badge { background: #0ea5e9; color: white; padding: 0.2rem 0.6rem; border-radius: 9999px; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; }
34
+ .method-list { margin-top: 2rem; }
35
+ .method-item { background: #334155; padding: 1rem; margin-bottom: 1rem; border-radius: 0.5rem; display: flex; justify-content: space-between; align-items: center; }
36
+ .method-name { font-family: monospace; font-weight: bold; color: #7dd3fc; }
37
+ button { background: #38bdf8; color: #0f172a; border: none; padding: 0.5rem 1.25rem; border-radius: 0.375rem; cursor: pointer; font-weight: 600; transition: all 0.2s; }
38
+ button:hover { background: #7dd3fc; transform: translateY(-1px); }
39
+ .output-container { margin-top: 2rem; }
40
+ pre { background: #020617; padding: 1.5rem; border-radius: 0.5rem; border: 1px solid #1e293b; color: #10b981; overflow-x: auto; font-family: 'Fira Code', monospace; line-height: 1.5; }
41
+ .log-entry { margin-bottom: 0.5rem; }
42
+ .status-ok { color: #10b981; }
43
+ .status-call { color: #fbbf24; }
44
+ </style>
45
+ </head>
46
+ <body>
47
+ <div class="container">
48
+ <div class="card">
49
+ <h1>
50
+ Extension Sandbox
51
+ <span class="badge">${titanJson.type}</span>
52
+ </h1>
53
+ <p>Testing extension: <code style="color: #38bdf8;">${titanJson.name}</code> v${titanJson.version}</p>
54
+
55
+ <div class="method-list">
56
+ <div class="method-item">
57
+ <span class="method-name">hello()</span>
58
+ <button onclick="callMethod('hello', [])">Invoke</button>
59
+ </div>
60
+ <!-- Dynamic methods would be listed here -->
61
+ </div>
62
+
63
+ <div class="output-container">
64
+ <h3>Live Output Log</h3>
65
+ <pre id="output"><div class="log-entry status-ok">[System] Sandbox ready at localhost:${port}</div></pre>
66
+ </div>
67
+ </div>
68
+ </div>
69
+
70
+ <script>
71
+ const output = document.getElementById('output');
72
+ function log(msg, type = 'ok') {
73
+ const entry = document.createElement('div');
74
+ entry.className = 'log-entry status-' + type;
75
+ entry.textContent = \`[\${new Date().toLocaleTimeString()}] \${msg}\`;
76
+ output.appendChild(entry);
77
+ output.scrollTop = output.scrollHeight;
78
+ }
79
+
80
+ async function callMethod(name, args) {
81
+ log(\`Calling \${name}...\`, 'call');
82
+ try {
83
+ // In a real sandbox this would fetch a /call endpoint
84
+ const res = "Hello from ${titanJson.name}!";
85
+ log(\`Result: \${JSON.stringify(res)}\`, 'ok');
86
+ } catch (e) {
87
+ log(\`Error: \${e.message}\`, 'error');
88
+ }
89
+ }
90
+ </script>
91
+ </body>
92
+ </html>`);
93
+ } else {
94
+ res.writeHead(404);
95
+ res.end('Not Found');
96
+ }
97
+ });
98
+
99
+ server.listen(port, () => {
100
+ console.log(chalk.cyan(`\n🪐 Titan Extension Sandbox running at:`));
101
+ console.log(chalk.bold(` http://localhost:${port}/test\n`));
102
+ console.log(chalk.gray(` Press Ctrl+C to stop.\n`));
103
+ });
104
+ }
@@ -0,0 +1 @@
1
+ TITAN_DEV=1
@@ -0,0 +1,64 @@
1
+ # ================================================================
2
+ # STAGE 1 — Builder
3
+ # ================================================================
4
+ FROM node:20-slim AS builder
5
+
6
+ WORKDIR /app
7
+
8
+ # build-essential is required for native Titan extensions (C++ or Rust based)
9
+ RUN apt-get update && apt-get install -y --no-install-recommends \
10
+ build-essential pkg-config git ca-certificates \
11
+ && rm -rf /var/lib/apt/lists/*
12
+
13
+ ENV NODE_ENV=production
14
+
15
+ COPY package.json package-lock.json* ./
16
+
17
+ # Install with optional dependencies so it grabs the correct engine for the Linux builder
18
+ RUN npm install -g @titanpl/cli
19
+
20
+ RUN npm install --include=optional
21
+
22
+ COPY . .
23
+
24
+ # Run the Titan release build step (generates a 'build' folder)
25
+ RUN npx titan build --release
26
+
27
+
28
+ # ================================================================
29
+ # STAGE 2 — Runtime (Optimized Pure Engine)
30
+ # ================================================================
31
+ FROM ubuntu:24.04
32
+
33
+ # Use an unprivileged user for security
34
+ RUN groupadd -r titan && useradd -r -g titan titan
35
+
36
+ WORKDIR /app
37
+
38
+ RUN apt-get update && apt-get install -y --no-install-recommends \
39
+ ca-certificates curl \
40
+ && rm -rf /var/lib/apt/lists/*
41
+
42
+ # Copy EVERYTHING from the generated build folder into Stage 2
43
+ # This includes dist/, .ext/, package.json, .env, and the titan-server binary
44
+ COPY --from=builder /app/build/ ./
45
+
46
+ # CRITICAL SYSTEM SETUP:
47
+ # Ensure the worker threads can find the extensions through the symlink
48
+ RUN ln -s /app/.ext /app/node_modules && \
49
+ chown -R titan:titan /app
50
+
51
+ # Standard environment variables
52
+ ENV HOST=0.0.0.0
53
+ ENV PORT=5100
54
+ ENV TITAN_DEV=0
55
+
56
+ USER titan
57
+ EXPOSE 5100
58
+
59
+ # Health check to ensure the server is alive
60
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
61
+ CMD curl -f http://localhost:5100/ || exit 1
62
+
63
+ # DYNAMIC ENTRYPOINT: Use the portable binary in the root of /app
64
+ CMD ["./titan-server", "start"]
@@ -0,0 +1,85 @@
1
+ # ⏣ Titan Project
2
+
3
+ Welcome to your new **Titan Planet** project! Titan is a high-performance web framework designed for scale, speed, and developer happiness.
4
+
5
+ ## 🚀 Getting Started
6
+
7
+ ### 1. Install Dependencies
8
+ ```bash
9
+ npm install
10
+ ```
11
+
12
+ ### 2. Start Development Server
13
+ Run the project in development mode with hot-reloading:
14
+ ```bash
15
+ titan dev
16
+ ```
17
+
18
+ ### 3. Build for Production
19
+ Create a self-contained production bundle in the `build/` directory:
20
+ ```bash
21
+ titan build --release
22
+ ```
23
+
24
+ ### 4. Run Production Server
25
+ ```bash
26
+ cd build
27
+ titan start
28
+ ```
29
+
30
+ ---
31
+
32
+ ## 📂 Project Structure
33
+
34
+ - `app/actions/` - Your JavaScript/TypeScript backend logic.
35
+ - `public/` - Static assets served directly (images, robots.txt, etc.).
36
+ - `tanfig.json` - Core project configuration and build settings.
37
+ - `.env` - Environment variables.
38
+
39
+ ---
40
+
41
+ ## 🛠 Configuration (`tanfig.json`)
42
+
43
+ Your project uses `tanfig.json` to control the build and runtime behavior.
44
+
45
+ ```json
46
+ {
47
+ "name": "my-titan-app",
48
+ "build": {
49
+ "purpose": "test",
50
+ "files": ["public", "static", "db", "config"]
51
+ }
52
+ }
53
+ ```
54
+
55
+ ### Build Options:
56
+ - **`purpose`**:
57
+ - `test`: (Default) Creates a `node_modules` junction for local testing.
58
+ - `deploy`: Slim build without `node_modules`, ready for production.
59
+ - **`files`**: List of folders/files from the root to include in the production `build/` folder.
60
+
61
+ ---
62
+
63
+ ## 🐳 Docker Deployment
64
+
65
+ This project comes with a pre-configured, multi-stage `Dockerfile` optimized for Titan's native engine.
66
+
67
+ ### Build Image
68
+ ```bash
69
+ docker build -t my-titan-app .
70
+ ```
71
+
72
+ ### Run Container
73
+ ```bash
74
+ docker run -p 5100:5100 my-titan-app
75
+ ```
76
+
77
+ ---
78
+
79
+ ## 🌐 Community & Support
80
+
81
+ - **Documentation**: [titanpl.vercel.app](https://titanpl.vercel.app)
82
+ - **GitHub**: [github.com/t8nlab/titanpl](https://github.com/t8nlab/titanpl)
83
+ - **Discord**: [Join our community](https://discord.gg/titanpl)
84
+
85
+ Built with ❤️ by the **Titan Planet** team.
@@ -0,0 +1,35 @@
1
+ node_modules
2
+ npm-debug.log
3
+ .git
4
+ .gitignore
5
+
6
+ package-lock.json
7
+ yarn.lock
8
+
9
+ # Titan Gravity Engine
10
+ dist/
11
+ .titan/
12
+ .ext/
13
+
14
+ deploy/
15
+
16
+ # Rust Build Artifacts
17
+ server/target/
18
+ Cargo.lock
19
+
20
+ # OS Files
21
+ .DS_Store
22
+ Thumbs.db
23
+ *.tmp
24
+ *.bak
25
+
26
+ # Environment & Secrets
27
+ .env
28
+ .env.local
29
+ .env.*.local
30
+
31
+ # IDEs
32
+ .vscode/
33
+ .idea/
34
+ *.swp
35
+ *.swo
@@ -0,0 +1,34 @@
1
+ # Node & Packages
2
+ node_modules/
3
+ npm-debug.log*
4
+ yarn-debug.log*
5
+ yarn-error.log*
6
+ package-lock.json
7
+ yarn.lock
8
+
9
+ # Titan Engine (Auto-generated - DO NOT COMMIT)
10
+ dist/
11
+ .titan/
12
+ .ext/
13
+ .env
14
+ build/
15
+
16
+ # Rust Build Artifacts (If using Hybrid)
17
+ server/target/
18
+ Cargo.lock
19
+
20
+ # OS Files
21
+ .DS_Store
22
+ Thumbs.db
23
+ *.tmp
24
+ *.bak
25
+
26
+ # Environment & Secrets
27
+ .env.local
28
+ .env.*.local
29
+
30
+ # IDEs
31
+ .vscode/
32
+ .idea/
33
+ *.swp
34
+ *.swo
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "{{name}}",
3
+ "description": "A powerful TitanPL project",
4
+ "version": "1.0.0",
5
+ "extensions": {
6
+ "allowWasm": false,
7
+ "allowNative": []
8
+ },
9
+ "build": {
10
+ "purpose": "test",
11
+ "files": [
12
+ "public",
13
+ "static",
14
+ "db",
15
+ "tanfig.json"
16
+ ]
17
+ }
18
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @package ext-template
3
+ * Professional extension template for the TitanPL framework.
4
+ */
5
+
6
+ /** Main configuration interface */
7
+ export interface Config {
8
+ /** Secure key or secret */
9
+ secret?: string;
10
+ /** Custom logging function */
11
+ log?: (msg: string) => void;
12
+ }
13
+
14
+ /** Standard Success Response */
15
+ export interface Result {
16
+ result: string;
17
+ status: "ok" | "error";
18
+ }
19
+
20
+ /** Main Extension class */
21
+ declare class Extension {
22
+ constructor(config?: Config);
23
+
24
+ /** Hash a string synchronously using bcryptjs */
25
+ hash(data: string): string;
26
+
27
+ /** Standard execution for processing input */
28
+ execute(input: string): Result;
29
+ }
30
+
31
+ export default Extension;
@@ -1,17 +1,17 @@
1
- // Define your extension Key
2
- if (typeof Titan === "undefined") globalThis.Titan = t;
3
- const EXT_KEY = "{{name}}";
1
+ import { registerExtension } from './utils/registerExtension.js';
4
2
 
5
- // Preserve any native functions already attached to this key
6
- t[EXT_KEY] = Object.assign(t[EXT_KEY] || {}, {
7
- // Example pure JavaScript function
8
- hello: function (name) {
9
- return `Hello ${name} from ${EXT_KEY}!`;
10
- },
11
-
12
- // Example Wrapper for Native function
13
- calc: function (a, b) {
14
- // Assumes the native function 'add' is mapped in titan.json
15
- return t[EXT_KEY].add(a, b);
3
+ const myExt = {
4
+ /**
5
+ * A sample function that can be called from any Titan Action.
6
+ */
7
+ hello: () => {
8
+ t.log("{{name}}", "Hello from extension!");
9
+ return "hello";
16
10
  }
17
- });
11
+ };
12
+
13
+ // If this is a Wasm or Native extension, bindings will be injected here during build.
14
+ // Use 'titan build ext' to generate them.
15
+
16
+ registerExtension("{{name}}", myExt);
17
+ export default myExt;
@@ -1,9 +1,11 @@
1
1
  [package]
2
- name = "{{native_name}}_native"
3
- version = "0.1.0"
4
- edition = "2024"
2
+ name = "my-extension-native"
3
+ version = "1.0.0"
4
+ edition = "2021"
5
5
 
6
6
  [lib]
7
7
  crate-type = ["cdylib"]
8
8
 
9
9
  [dependencies]
10
+ serde = { version = "1.0", features = ["derive"] }
11
+ serde_json = "1.0"
@@ -1,5 +1,4 @@
1
-
2
- #[unsafe(no_mangle)]
3
- pub extern "C" fn add(a: f64, b: f64) -> f64 {
1
+ #[titanpl::export]
2
+ pub fn add(a: f64, b: f64) -> f64 {
4
3
  a + b
5
4
  }
@@ -1,26 +1,16 @@
1
1
  {
2
- "name": "{{name}}",
3
- "version": "2.0.4",
4
- "description": "A Titan Planet extension",
2
+ "name": "my-extension",
3
+ "version": "7.0.0-beta",
4
+ "description": "A high-performance TitanPL extension.",
5
+ "type": "module",
5
6
  "main": "index.js",
6
- "types": "index.d.ts",
7
- "type": "commonjs",
8
- "scripts": {
9
- "test": "microgravity test"
10
- },
11
- "keywords": [
12
- "titan planet",
13
- "extension"
7
+ "files": [
8
+ "index.js",
9
+ "titan.json",
10
+ "jsconfig.json",
11
+ "README.md"
14
12
  ],
15
- "author": "",
16
- "license": "ISC",
17
13
  "dependencies": {
18
- "@titanpl/core": "latest",
19
- "chokidar": "^5.0.0",
20
- "esbuild": "^0.27.2",
21
- "titanpl-sdk": "2.0.4"
22
- },
23
- "devDependencies": {
24
- "@tgrv/microgravity": "latest"
14
+ "@titanpl/sdk": "7.0.0-beta"
25
15
  }
26
16
  }
@@ -1,18 +1,7 @@
1
1
  {
2
- "name": "{{name}}",
3
- "main": "index.js",
4
- "description": "A Titan extension",
5
- "native": {
6
- "path": "native/target/release/{{native_name}}_native.dll",
7
- "functions": {
8
- "add": {
9
- "symbol": "add",
10
- "parameters": [
11
- "f64",
12
- "f64"
13
- ],
14
- "result": "f64"
15
- }
16
- }
17
- }
2
+ "name": "my-extension",
3
+ "version": "1.0.0",
4
+ "type": "wasm",
5
+ "entry": "index.js",
6
+ "description": "A high-performance TitanPL extension."
18
7
  }
@@ -0,0 +1,44 @@
1
+ // utils/registerExtension.js
2
+
3
+ /**
4
+ * Safely registers an extension in the global t object
5
+ * @param {string} extensionName - Unique name for the extension
6
+ * @param {any} extensionModule - The extension module/object to register
7
+ * @returns {boolean} True if registration was successful
8
+ */
9
+ export function registerExtension(extensionName, extensionModule) {
10
+ // Check for global t object
11
+ if (typeof t === 'undefined') {
12
+ console.warn(`[registerExtension] Global 't' object not available. Cannot register: ${extensionName}`);
13
+ return false;
14
+ }
15
+
16
+ // Input validation
17
+ if (!extensionName || typeof extensionName !== 'string') {
18
+ console.error('[registerExtension] Invalid extension name provided');
19
+ return false;
20
+ }
21
+
22
+ // Check for naming conflicts
23
+ if (t[extensionName]) {
24
+ console.warn(`[registerExtension] '${extensionName}' already exists in global t object, overwriting`);
25
+ }
26
+
27
+ try {
28
+ // Register the extension
29
+ t[extensionName] = extensionModule;
30
+
31
+ console.log(`[registerExtension] Successfully registered '${extensionName}'`);
32
+
33
+ return true;
34
+ } catch (error) {
35
+ // Structured error reporting
36
+ console.error(`[registerExtension] Failed to register '${extensionName}':`, {
37
+ error: error.message,
38
+ extensionName,
39
+ moduleType: typeof extensionModule
40
+ });
41
+
42
+ return false;
43
+ }
44
+ }
@@ -6,16 +6,16 @@
6
6
  "template": "js"
7
7
  },
8
8
  "dependencies": {
9
- "@titanpl/cli": "2.0.4",
10
- "@titanpl/route": "2.0.4",
11
- "@titanpl/native": "2.0.4",
9
+ "@titanpl/cli": "7.0.0-beta",
10
+ "@titanpl/route": "7.0.0-beta",
11
+ "@titanpl/native": "7.0.0-beta",
12
12
  "@titanpl/core": "latest",
13
13
  "@titanpl/node": "latest",
14
- "@titanpl/packet": "2.0.4"
14
+ "@titanpl/packet": "7.0.0-beta"
15
15
  },
16
16
  "optionalDependencies": {
17
- "@titanpl/engine-linux-x64": "2.0.5",
18
- "@titanpl/engine-win32-x64": "2.0.3"
17
+ "@titanpl/engine-linux-x64": "7.0.0-beta",
18
+ "@titanpl/engine-win32-x64": "7.0.0-beta"
19
19
  },
20
20
  "scripts": {
21
21
  "build": "titan build",
@@ -28,5 +28,5 @@
28
28
  "eslint": "^9.39.2",
29
29
  "eslint-plugin-titanpl": "latest"
30
30
  },
31
- "version": "2.0.4"
32
- }
31
+ "version": "7.0.0-beta"
32
+ }
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "titanpl",
3
- "version": "2.0.4",
3
+ "version": "7.0.0-beta",
4
4
  "description": "A Titan Planet server",
5
5
  "type": "module",
6
6
  "titan": {
7
7
  "template": "rust-js"
8
8
  },
9
9
  "dependencies": {
10
- "@titanpl/cli": "2.0.4",
11
- "@titanpl/route": "2.0.4",
12
- "@titanpl/native": "2.0.4",
10
+ "@titanpl/cli": "7.0.0-beta",
11
+ "@titanpl/route": "7.0.0-beta",
12
+ "@titanpl/native": "7.0.0-beta",
13
13
  "@titanpl/core": "latest",
14
14
  "@titanpl/node": "latest"
15
15
  },
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "titanpl",
3
- "version": "2.0.4",
3
+ "version": "7.0.0-beta",
4
4
  "description": "A Titan Planet server (Rust + TypeScript)",
5
5
  "type": "module",
6
6
  "titan": {
7
7
  "template": "rust-ts"
8
8
  },
9
9
  "dependencies": {
10
- "@titanpl/cli": "2.0.4",
11
- "@titanpl/route": "2.0.4",
12
- "@titanpl/native": "2.0.4",
10
+ "@titanpl/cli": "7.0.0-beta",
11
+ "@titanpl/route": "7.0.0-beta",
12
+ "@titanpl/native": "7.0.0-beta",
13
13
  "@titanpl/core": "latest",
14
14
  "@titanpl/node": "latest",
15
15
  "typescript": "^5.0.0"
@@ -6,18 +6,18 @@
6
6
  "template": "ts"
7
7
  },
8
8
  "dependencies": {
9
- "@titanpl/cli": "2.0.4",
10
- "@titanpl/route": "2.0.4",
11
- "@titanpl/native": "2.0.4",
9
+ "@titanpl/cli": "7.0.0-beta",
10
+ "@titanpl/route": "7.0.0-beta",
11
+ "@titanpl/native": "7.0.0-beta",
12
12
  "@titanpl/core": "latest",
13
13
  "@titanpl/node": "latest",
14
- "@titanpl/packet": "2.0.4",
14
+ "@titanpl/packet": "7.0.0-beta",
15
15
  "typescript": "^5.0.0"
16
16
  },
17
17
  "optionalDependencies": {
18
18
  "@titanpl/engine-linux-arm64": "2.0.5",
19
- "@titanpl/engine-linux-x64": "2.0.5",
20
- "@titanpl/engine-win32-x64": "2.0.3"
19
+ "@titanpl/engine-linux-x64": "7.0.0-beta",
20
+ "@titanpl/engine-win32-x64": "7.0.0-beta"
21
21
  },
22
22
  "scripts": {
23
23
  "build": "titan build",
@@ -31,5 +31,5 @@
31
31
  "eslint-plugin-titanpl": "latest",
32
32
  "@typescript-eslint/parser": "^8.54.0"
33
33
  },
34
- "version": "2.0.4"
35
- }
34
+ "version": "7.0.0-beta"
35
+ }