titanpl-sdk 0.0.7

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/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2025, Ezet Galaxy
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,101 @@
1
+
2
+ # 🛠️ Titan SDK
3
+
4
+ **The Developer Toolkit for Titan Planet. Type safety, IntelliSense, and Extension Testing.**
5
+
6
+ [![npm version](https://img.shields.io/npm/v/titan-sdk.svg?style=flat-square)](https://www.npmjs.com/package/titan-sdk)
7
+ [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg?style=flat-square)](https://opensource.org/licenses/ISC)
8
+
9
+ ---
10
+
11
+ ## 🌌 Overview
12
+
13
+ **Titan SDK** is NOT the runtime engine itself. It is a **development-only toolkit** designed to bridge the gap between your local coding environment and the native Titan Planet binary.
14
+
15
+ It provides the necessary **Type Definitions** to make your IDE understand the global `t` object and a **Lite Test Harness** to verify your extensions before they ever touch a production binary.
16
+
17
+ > **Note:** The actual implementation of `t.log`, `t.fetch`, and other APIs are embedded directly into the [Titan Planet Binary](https://github.com/ezet-galaxy/-ezetgalaxy-titan). This SDK simply provides the "blueprints" (types) and a "sandbox" (test runner).
18
+
19
+ ---
20
+
21
+ ## ✨ Features
22
+
23
+ - **💎 Blueprint Types (IntelliSense)**: Provides the full TypeScript `index.d.ts` for the global `t` object so you get autocomplete in VS Code and other editors.
24
+ - **🛡️ Static Validation**: Catch parameter mismatches and typos in `t.log`, `t.fetch`, `t.db`, etc., during development.
25
+ - **🔌 Extension Test Harness**: A "lite" version of the Titan runtime that simulates the native environment to test extensions in isolation.
26
+ - **🚀 Zero Production Trace**: This is a `devDependencies` package. It never ships with your binary, keeping your production footprint at literal zero.
27
+
28
+ ---
29
+
30
+ ## 🚀 The Test Harness (Lite Runtime)
31
+
32
+ The SDK includes a specialized **Test Runner** (`titan-sdk`). This is a "lite" version of the Titan ecosystem that acts as a bridge for developers.
33
+
34
+ ### How it works:
35
+ When you run the SDK in an extension folder, it:
36
+ 1. **Scaffolds a Virtual Project**: Creates a temporary, minimal Titan environment in `.titan_test_run`.
37
+ 2. **Native Compilation**: Automatically builds your native Rust code (`native/`) if it exists.
38
+ 3. **Hot-Linking**: Junctions your local extension into the virtual project's `node_modules`.
39
+ 4. **Verification**: Generates a test suite that attempts to call your extension's methods via the real `t` object inside the sandbox.
40
+
41
+ ### Usage:
42
+
43
+ ```bash
44
+ # Inside your extension directory
45
+ npx titan-sdk
46
+ ```
47
+
48
+ ---
49
+
50
+ ## ⌨️ Enabling IntelliSense
51
+
52
+ Since the `t` object is injected globally by the Titan engine at runtime, your IDE won't recognize it by default. The SDK fixes this.
53
+
54
+ 1. **Install the SDK**:
55
+ ```bash
56
+ npm install --save-dev titan-sdk
57
+ ```
58
+
59
+ 2. **Configure Types**:
60
+ Create or update `jsconfig.json` (or `tsconfig.json`) in your project root:
61
+ ```json
62
+ {
63
+ "compilerOptions": {
64
+ "types": ["titan-sdk"]
65
+ }
66
+ }
67
+ ```
68
+
69
+ Now your editor will treat `t` as a first-class citizen:
70
+ ```js
71
+ export function myAction(req) {
72
+ t.log.info("Request received", req.path); // Autocomplete works!
73
+ return { status: "ok" };
74
+ }
75
+ ```
76
+
77
+ ---
78
+
79
+ ## 🧱 What's Included? (Types Only)
80
+
81
+ The SDK provides types for the native APIs provided by the Titan Planet engine:
82
+
83
+ - **`t.log`**: Standardized logging that appears in the Titan binary console.
84
+ - **`t.fetch`**: Types for the high-performance Rust-native network stack.
85
+ - **`t.db`**: Interface for the native PostgreSQL driver.
86
+ - **`t.read`**: Definitions for optimized filesystem reads.
87
+ - **`t.jwt` / `t.password`**: Security helper types.
88
+
89
+ ---
90
+
91
+ ## 🌍 Community & Documentation
92
+
93
+ - **Core Framework**: [Titan Planet](https://github.com/ezet-galaxy/-ezetgalaxy-titan)
94
+ - **Official Docs**: [Titan Planet Docs](https://titan-docs-ez.vercel.app/docs)
95
+ - **Author**: [ezetgalaxy](https://github.com/ezet-galaxy)
96
+
97
+ ---
98
+
99
+ <p align="center">
100
+ Built with ❤️ for the <a href="https://github.com/ezet-galaxy/-ezetgalaxy-titan">Titan Planet</a> ecosystem.
101
+ </p>
package/bin/run.js ADDED
@@ -0,0 +1,254 @@
1
+ #!/usr/bin/env node
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import { execSync } from "child_process";
5
+ import { fileURLToPath } from "url";
6
+
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = path.dirname(__filename);
9
+
10
+ // Helper for colors
11
+ const cyan = (t) => `\x1b[36m${t}\x1b[0m`;
12
+ const green = (t) => `\x1b[32m${t}\x1b[0m`;
13
+ const red = (t) => `\x1b[31m${t}\x1b[0m`;
14
+ const yellow = (t) => `\x1b[33m${t}\x1b[0m`;
15
+
16
+ function copyDir(src, dest) {
17
+ fs.mkdirSync(dest, { recursive: true });
18
+ for (const file of fs.readdirSync(src)) {
19
+ const srcPath = path.join(src, file);
20
+ const destPath = path.join(dest, file);
21
+ if (fs.lstatSync(srcPath).isDirectory()) {
22
+ copyDir(srcPath, destPath);
23
+ } else {
24
+ fs.copyFileSync(srcPath, destPath);
25
+ }
26
+ }
27
+ }
28
+
29
+ function run() {
30
+ console.log(cyan("Titan SDK: Test Runner"));
31
+
32
+ // 1. Validate we are in an extension directory
33
+ const cwd = process.cwd();
34
+ const manifestPath = path.join(cwd, "titan.json");
35
+ if (!fs.existsSync(manifestPath)) {
36
+ console.log(red("Error: titan.json not found. Run this command inside your extension folder."));
37
+ process.exit(1);
38
+ }
39
+
40
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
41
+ const name = manifest.name;
42
+ console.log(green(`Extension: ${name}`));
43
+
44
+ // 2. Build Native Logic (if properly set up)
45
+ const nativeDir = path.join(cwd, "native");
46
+ if (fs.existsSync(nativeDir) && fs.existsSync(path.join(nativeDir, "Cargo.toml"))) {
47
+ console.log(cyan("Building native Rust module..."));
48
+ try {
49
+ execSync("cargo build --release", { cwd: nativeDir, stdio: "inherit" });
50
+ } catch (e) {
51
+ console.log(red("Failed to build native module."));
52
+ process.exit(1);
53
+ }
54
+ }
55
+
56
+ // 3. Create a Test Harness (Mini Titan Project)
57
+ const runDir = path.join(cwd, ".titan_test_run");
58
+ if (fs.existsSync(runDir)) {
59
+ try {
60
+ fs.rmSync(runDir, {
61
+ recursive: true,
62
+ force: true,
63
+ maxRetries: 10,
64
+ retryDelay: 100
65
+ });
66
+ } catch (e) {
67
+ console.log(yellow(`Warning: Could not fully clean ${runDir}. Proceeding anyway...`));
68
+ }
69
+ }
70
+
71
+ // Ensure runDir exists (sometimes rmSync + mkdirSync fails on Windows due to locks)
72
+ if (!fs.existsSync(runDir)) {
73
+ fs.mkdirSync(runDir, { recursive: true });
74
+ }
75
+
76
+ // Create app structure
77
+ const appDir = path.join(runDir, "app");
78
+ fs.mkdirSync(appDir);
79
+
80
+ // Create actions folder (required by Titan build)
81
+ const actionsDir = path.join(appDir, "actions");
82
+ fs.mkdirSync(actionsDir);
83
+
84
+ // Copy titan/ and server/ from templates
85
+ const templatesDir = path.join(__dirname, "..", "templates");
86
+
87
+ const titanSrc = path.join(templatesDir, "titan");
88
+ const titanDest = path.join(runDir, "titan");
89
+ if (fs.existsSync(titanSrc)) {
90
+ console.log(cyan("→ Setting up Titan runtime..."));
91
+ copyDir(titanSrc, titanDest);
92
+ // Double check titan.js exists
93
+ if (!fs.existsSync(path.join(titanDest, "titan.js"))) {
94
+ console.log(red(`Error: Failed to copy titan.js to ${titanDest}`));
95
+ process.exit(1);
96
+ }
97
+ } else {
98
+ console.log(red(`Error: Titan templates not found at ${titanSrc}`));
99
+ process.exit(1);
100
+ }
101
+
102
+ const serverSrc = path.join(templatesDir, "server");
103
+ const serverDest = path.join(runDir, "server");
104
+ if (fs.existsSync(serverSrc)) {
105
+ console.log(cyan("→ Setting up Titan server..."));
106
+ copyDir(serverSrc, serverDest);
107
+ } else {
108
+ console.log(red(`Error: Server templates not found at ${serverSrc}`));
109
+ process.exit(1);
110
+ }
111
+
112
+ // Create package.json for the test harness
113
+ const pkgJson = {
114
+ "type": "module"
115
+ };
116
+ fs.writeFileSync(path.join(runDir, "package.json"), JSON.stringify(pkgJson, null, 2));
117
+
118
+ // Create 'node_modules' to link the extension
119
+ const nmDir = path.join(runDir, "node_modules");
120
+ fs.mkdirSync(nmDir);
121
+
122
+ // Link current extension to node_modules/NAME
123
+ // Use junction for Windows compat without admin rights
124
+ const extDest = path.join(nmDir, name);
125
+ try {
126
+ fs.symlinkSync(cwd, extDest, "junction");
127
+ } catch (e) {
128
+ // Fallback to copy if link fails
129
+ console.log(yellow("Linking failed, copying extension files..."));
130
+ copyDir(cwd, extDest);
131
+ }
132
+
133
+ // Create a test action in app/actions/test.js
134
+ const testAction = `export const test = (req) => {
135
+ const ext = t["${name}"];
136
+
137
+ const results = {
138
+ extension: "${name}",
139
+ loaded: !!ext,
140
+ methods: ext ? Object.keys(ext) : [],
141
+ timestamp: new Date().toISOString()
142
+ };
143
+
144
+ if (ext && ext.hello) {
145
+ try {
146
+ results.hello_test = ext.hello("World");
147
+ } catch(e) {
148
+ results.hello_error = String(e);
149
+ }
150
+ }
151
+
152
+ if (ext && ext.calc) {
153
+ try {
154
+ results.calc_test = ext.calc(15, 25);
155
+ } catch(e) {
156
+ results.calc_error = String(e);
157
+ }
158
+ }
159
+
160
+ return results;
161
+ };
162
+ `;
163
+
164
+ fs.writeFileSync(path.join(actionsDir, "test.js"), testAction);
165
+
166
+ // Create a simple test script in app/app.js
167
+ // This script will be executed by Titan
168
+ const testScript = `import t from "../titan/titan.js";
169
+ import "${name}";
170
+
171
+ // Extension test harness for: ${name}
172
+ const ext = t["${name}"];
173
+
174
+ console.log("---------------------------------------------------");
175
+ console.log("Testing Extension: ${name}");
176
+ console.log("---------------------------------------------------");
177
+
178
+ if (!ext) {
179
+ console.log("ERROR: Extension '${name}' not found in global 't'.");
180
+ } else {
181
+ console.log("✓ Extension loaded successfully!");
182
+ console.log("✓ Available methods:", Object.keys(ext).join(", "));
183
+
184
+ // Try 'hello' if it exists
185
+ if (typeof ext.hello === 'function') {
186
+ console.log("\\nTesting ext.hello('Titan')...");
187
+ try {
188
+ const res = ext.hello("Titan");
189
+ console.log("✓ Result:", res);
190
+ } catch(e) {
191
+ console.log("✗ Error:", e.message);
192
+ }
193
+ }
194
+
195
+ // Try 'calc' if it exists
196
+ if (typeof ext.calc === 'function') {
197
+ console.log("\\nTesting ext.calc(10, 20)...");
198
+ try {
199
+ const res = ext.calc(10, 20);
200
+ console.log("✓ Result:", res);
201
+ } catch(e) {
202
+ console.log("✗ Error:", e.message);
203
+ }
204
+ }
205
+ }
206
+
207
+ console.log("---------------------------------------------------");
208
+ console.log("✓ Test complete!");
209
+ console.log("\\n📍 Routes:");
210
+ console.log(" GET http://localhost:3000/ → Test harness info");
211
+ console.log(" GET http://localhost:3000/test → Extension test results (JSON)");
212
+ console.log("---------------------------------------------------\\n");
213
+
214
+ // Create routes
215
+ t.get("/test").action("test");
216
+ t.get("/").reply("🚀 Extension Test Harness for ${name}\\n\\nVisit /test to see extension test results");
217
+
218
+ await t.start(3000, "Titan Extension Test Running!");
219
+ `;
220
+
221
+ fs.writeFileSync(path.join(appDir, "app.js"), testScript);
222
+
223
+ // Build the app (bundle actions)
224
+ console.log(cyan("Building test app..."));
225
+ try {
226
+ // Ensure we are in runDir and the file exists
227
+ const appJsPath = path.join(runDir, "app", "app.js");
228
+ if (!fs.existsSync(appJsPath)) {
229
+ throw new Error(`app/app.js missing at ${appJsPath}`);
230
+ }
231
+
232
+ execSync("node app/app.js --build", {
233
+ cwd: runDir,
234
+ stdio: "inherit",
235
+ env: { ...process.env, NODE_OPTIONS: "--no-warnings" }
236
+ });
237
+ } catch (e) {
238
+ console.log(red("Failed to build test app. This is expected if your extension has errors."));
239
+ // Don't exit here, attempt to continue to show runtime errors if possible
240
+ }
241
+
242
+ // 4. Run Titan Server using cargo run (like dev mode)
243
+ console.log(green("\x1b[1m\n>>> STARTING EXTENSION TEST >>>\n\x1b[0m"));
244
+
245
+ const serverDir = path.join(runDir, "server");
246
+
247
+ try {
248
+ execSync("cargo run", { cwd: serverDir, stdio: "inherit" });
249
+ } catch (e) {
250
+ console.log(red("Runtime exited."));
251
+ }
252
+ }
253
+
254
+ run();
package/index.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ export { };
2
+
3
+ declare global {
4
+ /**
5
+ * Titan Runtime Global Object
6
+ */
7
+ const t: Titan.Runtime;
8
+ }
9
+
10
+ export namespace Titan {
11
+ interface Runtime {
12
+ /**
13
+ * Log messages to the Titan console
14
+ */
15
+ log: LogInterface;
16
+
17
+ /**
18
+ * Read file content
19
+ */
20
+ read(path: string): string;
21
+
22
+ /**
23
+ * Fetch API wrapper
24
+ */
25
+ fetch(url: string, options?: any): Promise<any>;
26
+
27
+ /**
28
+ * Database operations
29
+ */
30
+ db: {
31
+ query(sql: string, params?: any[]): Promise<any>;
32
+ };
33
+
34
+ /**
35
+ * Titan Extensions
36
+ */
37
+ [key: string]: any;
38
+ }
39
+
40
+ interface LogInterface {
41
+ (...args: any[]): void;
42
+ info(...args: any[]): void;
43
+ warn(...args: any[]): void;
44
+ error(...args: any[]): void;
45
+ }
46
+ }
package/index.js ADDED
@@ -0,0 +1,5 @@
1
+ // Titan SDK
2
+ // This package is primarily for type definitions and development tools.
3
+ // The 't' object is injected globally by the Titan runtime.
4
+
5
+ export const VERSION = "0.0.1";
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "titanpl-sdk",
3
+ "version": "0.0.7",
4
+ "description": "Development SDK for Titan Planet. Provides TypeScript type definitions for the global 't' runtime object and a 'lite' test-harness runtime for building and verifying extensions.",
5
+ "main": "index.js",
6
+ "type": "module",
7
+ "types": "index.d.ts",
8
+ "bin": {
9
+ "titanpl-sdk": "./bin/run.js"
10
+ },
11
+ "files": [
12
+ "bin/",
13
+ "templates/",
14
+ "titan",
15
+ "index.js",
16
+ "index.d.ts",
17
+ "README.md"
18
+ ],
19
+ "keywords": [
20
+ "titan",
21
+ "titan-planet",
22
+ "titanpl-sdk",
23
+ "ezetgalaxy",
24
+ "types",
25
+ "typescript",
26
+ "intellisense",
27
+ "sdk",
28
+ "backend-sdk",
29
+ "extension-development"
30
+ ],
31
+ "license": "ISC"
32
+ }
@@ -0,0 +1,3 @@
1
+ node_modules
2
+ npm-debug.log
3
+ .git
@@ -0,0 +1,53 @@
1
+ # ================================================================
2
+ # STAGE 1 — Build Titan (JS → Rust)
3
+ # ================================================================
4
+ FROM rust:1.91.1 AS builder
5
+
6
+ # Install Node for Titan CLI + bundler
7
+ RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
8
+ && apt-get install -y nodejs
9
+
10
+ # Install Titan CLI (latest)
11
+ RUN npm install -g @ezetgalaxy/titan@latest
12
+
13
+ WORKDIR /app
14
+
15
+ # Copy project files
16
+ COPY . .
17
+
18
+ # Install JS dependencies (needed for Titan DSL + bundler)
19
+ RUN npm install
20
+
21
+ # Build Titan metadata + bundle JS actions
22
+ RUN titan build
23
+
24
+ # Build Rust binary
25
+ RUN cd server && cargo build --release
26
+
27
+
28
+
29
+ # ================================================================
30
+ # STAGE 2 — Runtime Image (Lightweight)
31
+ # ================================================================
32
+ FROM debian:stable-slim
33
+
34
+ WORKDIR /app
35
+
36
+ # Copy Rust binary from builder stage
37
+ COPY --from=builder /app/server/target/release/server ./titan-server
38
+
39
+ # Copy Titan routing metadata
40
+ COPY --from=builder /app/server/routes.json ./routes.json
41
+ COPY --from=builder /app/server/action_map.json ./action_map.json
42
+
43
+ # Copy Titan JS bundles
44
+ RUN mkdir -p /app/actions
45
+ COPY --from=builder /app/server/actions /app/actions
46
+
47
+ COPY --from=builder /app/db /app/assets
48
+
49
+ # Expose Titan port
50
+ EXPOSE 3000
51
+
52
+ # Start Titan
53
+ CMD ["./titan-server"]
@@ -0,0 +1,5 @@
1
+ export const hello = (req) => {
2
+ return {
3
+ message: `Hello from Titan ${req.body.name}`,
4
+ };
5
+ }
@@ -0,0 +1,10 @@
1
+ import t from "../titan/titan.js";
2
+
3
+
4
+
5
+
6
+ t.post("/hello").action("hello") // pass a json payload { "name": "titan" }
7
+
8
+ t.get("/").reply("Ready to land on Titan Planet 🚀");
9
+
10
+ t.start(3000, "Titan Running!");
@@ -0,0 +1,87 @@
1
+ /**
2
+ * TITAN TYPE DEFINITIONS
3
+ * ----------------------
4
+ * These types are globally available in your Titan project.
5
+ */
6
+
7
+ /**
8
+ * The Titan Request Object passed to actions.
9
+ */
10
+ interface TitanRequest {
11
+ body: any;
12
+ method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
13
+ path: string;
14
+ headers: {
15
+ host?: string;
16
+ "content-type"?: string;
17
+ "user-agent"?: string;
18
+ authorization?: string;
19
+ [key: string]: string | undefined;
20
+ };
21
+ params: Record<string, string>;
22
+ query: Record<string, string>;
23
+ }
24
+
25
+ interface DbConnection {
26
+ /**
27
+ * Execute a SQL query.
28
+ * @param sql The SQL query string.
29
+ * @param params (Optional) Parameters for the query ($1, $2, etc).
30
+ */
31
+ query(sql: string, params?: any[]): any[];
32
+ }
33
+
34
+ /**
35
+ * Define a Titan Action with type inference.
36
+ * @example
37
+ * export const hello = defineAction((req) => {
38
+ * return req.headers;
39
+ * });
40
+ */
41
+ declare function defineAction<T>(actionFn: (req: TitanRequest) => T): (req: TitanRequest) => T;
42
+
43
+ /**
44
+ * Titan Runtime Utilities
45
+ */
46
+ declare const t: {
47
+ /**
48
+ * Log messages to the server console with Titan formatting.
49
+ */
50
+ log(...args: any[]): void;
51
+
52
+ /**
53
+ * Read a file contents as string.
54
+ * @param path Relative path to the file from project root.
55
+ */
56
+ read(path: string): string;
57
+
58
+ fetch(url: string, options?: {
59
+ method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
60
+ headers?: Record<string, string>;
61
+ body?: string | object;
62
+ }): {
63
+ ok: boolean;
64
+ status?: number;
65
+ body?: string;
66
+ error?: string;
67
+ };
68
+
69
+ jwt: {
70
+ sign(
71
+ payload: object,
72
+ secret: string,
73
+ options?: { expiresIn?: string | number }
74
+ ): string;
75
+ verify(token: string, secret: string): any;
76
+ };
77
+
78
+ password: {
79
+ hash(password: string): string;
80
+ verify(password: string, hash: string): boolean;
81
+ };
82
+
83
+ db: {
84
+ connect(url: string): DbConnection;
85
+ };
86
+ };
87
+
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "esnext",
4
+ "target": "esnext",
5
+ "checkJs": false,
6
+ "noImplicitAny": false,
7
+ "allowJs": true,
8
+ "moduleResolution": "node",
9
+ "baseUrl": ".",
10
+ "paths": {
11
+ "*": [
12
+ "./app/*"
13
+ ]
14
+ }
15
+ },
16
+ "include": [
17
+ "app/**/*"
18
+ ]
19
+ }