CyborgShell - API Guide

Table of Contents

Overview

The CyborgShell API provides a minimal but powerful set of functions for building both console-based and full-screen applications. All API functions are accessed through the api object.

Basic Usage Pattern:

api.print("Hello World!");
api.print("Enter your name:");
api.input("", function(strName) {
    api.print("Hello, " + strName + "!");
});

Application Types

Console Applications

Console applications use api.print() and api.input() to interact with the user through the CyborgShell terminal interface.

// Simple console application
10 api.print("Welcome to my program!");
20 api.print("What's your name?");
30 api.input("", function(strName) {
40     api.print("Nice to meet you, " + strName + "!");
50 });
run

Full-Screen Applications

Full-screen applications bypass the console and create their own UI directly in the browser DOM. See the included 3d.js example for a complete full-screen 3D application.

Example: 3d.js Pattern

// Full-screen application pattern
function main() {
    // Create full-screen canvas
    var canvas = document.createElement('canvas');
    $(canvas).css({
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%'
    });
    $('body').append(canvas);
    
    // Your application logic here...
}
main();

Screen and Output Functions

api.print()

api.print(str, forceLTR, reverseRTL)

Output text to the console.

Parameter Type Description
str string Text to output
forceLTR boolean Optional. Force left-to-right text direction
reverseRTL boolean Optional. Reverse right-to-left text
// Basic usage
api.print("Hello World!");

// Multiple lines
api.print("Line 1");
api.print("Line 2");
api.print("Line 3");

api.input()

api.input(defaultValue, callback)

Get user input from the console.

Parameter Type Description
defaultValue string Default value pre-filled in input (usually empty string "")
callback function Function called with user input as parameter

Important: The first parameter is the default value, not a prompt! Use api.print() to show your prompt first.

// Get user input (correct pattern)
api.print("Enter your age:");
api.input("", function(strAge) {
    api.print("You are " + strAge + " years old");
});

// With default value
api.print("Enter your name:");
api.input("Guest", function(strName) {
    api.print("Hello " + strName);
});

// Chain multiple inputs
api.print("First name:");
api.input("", function(strFirst) {
    api.print("Last name:");
    api.input("", function(strLast) {
        api.print("Hello " + strFirst + " " + strLast);
    });
});

api.cls()

api.cls()

Clear the console screen.

// Clear screen
api.cls();
api.print("Fresh screen!");

api.errorOutput()

api.errorOutput(errorMessage)

Output an error message to the console.

// Display error
api.errorOutput("An error occurred!");

// Error handling pattern
try {
    // risky operation
} catch(e) {
    api.errorOutput("Error: " + e.message);
}

File Functions

api.saveFile()

api.saveFile(filename, data, callback)

Save data to cloud storage (requires login).

Parameter Type Description
filename string Name of file to save
data object/string Data to save (will be JSON stringified)
callback function Called with response object on completion
// Save to cloud
var objData = {
    name: "John",
    score: 100
};

api.saveFile("mydata", objData, function(response) {
    if (response) {
        api.print("Saved successfully!");
    } else {
        api.errorOutput("Save failed: " + response.error);
    }
});

api.loadFile()

api.loadFile(filename, callback)

Load data from cloud storage (requires login).

// Load from cloud
api.loadFile("mydata", function(response) {
    if (response) {
        var objData = response;
        api.print("Name: " + objData.name);
        api.print("Score: " + objData.score);
    } else {
        api.errorOutput("Load failed: " + response.error);
    }
});

api.saveLocalData()

api.saveLocalData(filename, data, callback)

Save data to browser local storage (no login required).

// Save locally
var objSettings = {
    theme: "dark",
    fontSize: 14
};

api.saveLocalData("settings", objSettings, function(success) {
    if (success) {
        api.print("Settings saved locally!");
    }
});

api.loadLocalData()

api.loadLocalData(filename, callback)

Load data from browser local storage.

// Load locally
api.loadLocalData("settings", function(response) {
    if (response) {
        var objSettings = response;
        api.print("Theme: " + objSettings.theme);
        api.print("Font Size: " + objSettings.fontSize);
    }
});

Note: Cloud functions (saveFile/loadFile) require user login. Local functions (saveLocalData/loadLocalData) work without login but data is browser-specific.

Data/Database Functions

CyborgShell includes a simple in-memory database system for managing structured data.

api.createDatabase()

api.createDatabase()

Initialize the database system. Call this once before using other database functions.

// Initialize database
api.createDatabase();

api.appendTable()

api.appendTable(tableName, jsonArray)

Add records to a table.

// Create and populate a table
api.createDatabase();

var arrPeople = [
    { name: "Alice", age: 30, city: "New York" },
    { name: "Bob", age: 25, city: "London" },
    { name: "Charlie", age: 35, city: "New York" }
];

api.appendTable("people", arrPeople);
api.print("Added " + arrPeople.length + " records");

api.createIndex()

api.createIndex(tableName, fieldName, ascending)

Create an index on a field for faster searching.

Parameter Type Description
tableName string Name of the table
fieldName string Field to index
ascending boolean true for ascending, false for descending
// Create indexes
api.createIndex("people", "name", true);    // Ascending by name
api.createIndex("people", "age", false);    // Descending by age
api.createIndex("people", "city", true);    // Ascending by city

api.findData()

api.findData(tableName, fieldName, value)

Find the first record matching the value. Returns the record object or undefined.

// Find by exact match
var objPerson = api.findData("people", "name", "Alice");
if (objPerson) {
    api.print("Found: " + objPerson.name + ", Age: " + objPerson.age);
} else {
    api.print("Not found");
}

// Find first record (pass empty string)
var objFirst = api.findData("people", "name", "");
api.print("First person: " + objFirst.name);

api.nextData()

api.nextData(tableName, fieldName)

Get the next record after the current cursor position. Returns the record object or undefined.

// Iterate through all records
api.findData("people", "name", "");  // Position at first
var objRecord = api.nextData("people", "name");
while (objRecord) {
    api.print(objRecord.name + " - " + objRecord.age);
    objRecord = api.nextData("people", "name");
}

// Find all people named "Alice"
api.findData("people", "name", "Alice");
var objPerson = api.findData("people", "name", "Alice");
while (objPerson) {
    api.print("Age: " + objPerson.age);
    objPerson = api.nextData("people", "name");
}

api.truncateTable()

api.truncateTable(tableName)

Delete all records from a table.

// Clear table
api.truncateTable("people");
api.print("Table cleared");

api.dropIndex()

api.dropIndex(tableName, fieldName)

Remove an index from a field.

// Remove index
api.dropIndex("people", "age");

Complete Database Example

// Complete database workflow
api.createDatabase();

// Add data
var arrEmployees = [
    { id: 1, name: "Alice", dept: "Sales", salary: 50000 },
    { id: 2, name: "Bob", dept: "Engineering", salary: 75000 },
    { id: 3, name: "Charlie", dept: "Sales", salary: 55000 },
    { id: 4, name: "Diana", dept: "Engineering", salary: 80000 }
];
api.appendTable("employees", arrEmployees);

// Create indexes
api.createIndex("employees", "dept", true);
api.createIndex("employees", "salary", false);  // Descending

// Find all in Sales department
api.print("Sales Department:");
var objEmp = api.findData("employees", "dept", "Sales");
while (objEmp) {
    api.print("  " + objEmp.name + ": $" + objEmp.salary);
    objEmp = api.nextData("employees", "dept");
}

// List all by salary (highest first)
api.print("\nBy Salary:");
objEmp = api.findData("employees", "salary", "");
while (objEmp) {
    api.print("  " + objEmp.name + ": $" + objEmp.salary);
    objEmp = api.nextData("employees", "salary");
}

Utility Functions

api.getGUID()

api.getGUID()

Generate a unique GUID (Globally Unique Identifier).

// Generate unique IDs
var strID = api.getGUID();
api.print("Generated ID: " + strID);
// Output: "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"

api.debugObject()

api.debugObject(object, recurse, indent)

Print object properties for debugging.

Parameter Type Description
object object Object to debug
recurse boolean Optional. true to show nested objects (default: true)
indent string Optional. Indentation string (default: '')
// Debug an object
var objPerson = {
    name: "Alice",
    age: 30,
    address: {
        city: "New York",
        zip: "10001"
    }
};

api.debugObject(objPerson);
// Output:
// name: Alice
// age: 30
// address:
//  city: New York
//  zip: 10001

// Non-recursive (shallow)
api.debugObject(objPerson, false);
// Output:
// name: Alice
// age: 30
// address: Object

api.escapeValue()

api.escapeValue(value)

Escape special characters in a string value (used internally by database functions).

// Escape special characters
var strSafe = api.escapeValue("User input: $100");
api.print(strSafe);

Tab Functions

api.getTabHandler()

api.getTabHandler(callback)

Get a tab handler for inter-tab communication. Advanced feature for multi-window applications.

// Create tab handler
var objTabHandler = api.getTabHandler(function(queue, message, data) {
    api.print("Received: " + message);
});

// Open new tab
var objNewWindow = objTabHandler.createTab("index.php");

// Broadcast to all tabs
objTabHandler.broadcast("myqueue", "Hello tabs!", { data: 123 });

Complete Examples

Example 1: Simple Calculator

10 api.cls();
20 api.print("=== Calculator ===");
30 api.print("Enter first number:");
40 api.input("", function(strA) {
45     api.print(strA);
50     api.print("Enter second number:");
60     api.input("", function(strB) {
65         api.print(strB);
70         var intA = parseInt(strA);
80         var intB = parseInt(strB);
90         api.print("Sum: " + (intA + intB));
100        api.print("Product: " + (intA * intB));
110    });
120 });

Example 2: Address Book

10 api.createDatabase();
20 
30 function addContact() {
40     api.print("Name:");
50     api.input("", function(strName) {
55         api.print(strName);
60         api.print("Phone:");
70         api.input("", function(strPhone) {
75         api.print(strPhone);
80             api.print("Email:");
90             api.input("", function(strEmail) {
95             api.print(strEmail);
100                var objContact = {
110                    id: api.getGUID(),
120                    name: strName,
130                    phone: strPhone,
140                    email: strEmail
150                };
160                api.appendTable("contacts", [objContact]);
170                api.print("Contact added!");
180                showMenu();
190            });
200        });
210    });
220 }
230 
240 function listContacts() {
250     api.print("\n=== Contacts ===");
260     var objContact = api.findData("contacts", "name", "");
270     if (!objContact) {
280         api.print("No contacts found");
290     }
300     while (objContact) {
310         api.print(objContact.name + " - " + objContact.phone + " - " + objContact.email);
320         objContact = api.nextData("contacts", "name");
330     }
340     showMenu();
350 }
360 
370 function showMenu() {
380     api.print("\n1. Add Contact");
390     api.print("2. List Contacts");
400     api.print("3. Quit");
410     api.print("Choice:");
420     api.input("", function(strChoice) {
430         if (strChoice === "1") addContact();
440         else if (strChoice === "2") listContacts();
450         else if (strChoice === "3") api.print("Goodbye!");
460         else showMenu();
470     });
480 }
490 
500 api.cls();
510 api.print("=== Address Book ===");
520 api.createIndex("contacts", "name", true);
530 showMenu();

Example 3: Data Persistence

10 api.cls();
20 
30 function saveScore() {
40     api.print("Your name:");
50     api.input("", function(strName) {
55         api.print(strName);
60         api.print("Your score:");
70         api.input("", function(strScore) {
75             api.print(strScore);
80             var objData = {
90                 name: strName,
100                score: parseInt(strScore),
110                date: new Date().toISOString()
120            };
130            api.saveLocalData("highscore", objData, function(success) {
140                if (success) {
150                    api.print("Score saved!");
160                }
170                showMenu();
180            });
190        });
200    });
210 }
220 
230 function loadScore() {
240     api.loadLocalData("highscore", function(response) {
250         if (response) {
260             var objData = response;
270             api.print("\nHigh Score:");
280             api.print("Name: " + objData.name);
290             api.print("Score: " + objData.score);
300             api.print("Date: " + objData.date);
310         } else {
320             api.print("No high score saved yet");
330         }
340         showMenu();
350     });
360 }
370 
380 function showMenu() {
390     api.print("\n1. Save Score");
400     api.print("2. Load Score");
410     api.print("3. Quit");
420     api.print("Choice:");
430     api.input("", function(strChoice) {
440         if (strChoice === "1") saveScore();
450         else if (strChoice === "2") loadScore();
460         else if (strChoice === "3") api.print("Goodbye!");
470         else showMenu();
480     });
490 }
500 
510 api.print("=== Score Tracker ===");
520 showMenu();

Example 4: Full-Screen Application (Pattern from 3d.js)

function main() {
    // Load external library
    function includeScript(strURL, cbSuccess) {
        if (!globals.loadedScripts) {
            globals.loadedScripts = {};
        }
        
        if (globals.loadedScripts[strURL]) {
            cbSuccess();
        } else {
            $.ajax({
                url: strURL,
                dataType: 'script',
                cache: true,
                success: function() {
                    globals.loadedScripts[strURL] = true;
                    cbSuccess();
                }
            });
        }
    }
    
    includeScript('https://cdn.example.com/library.js', function() {
        // Create full-screen canvas
        var canvas = document.createElement('canvas');
        $(canvas).css({
            position: 'fixed',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            'z-index': 9999
        });
        $('body').append(canvas);
        
        // Add close button
        var closeBtn = $('<div>X</div>');
        closeBtn.css({
            position: 'fixed',
            top: '10px',
            right: '10px',
            'font-size': '24px',
            cursor: 'pointer',
            'z-index': 10000
        });
        closeBtn.click(function() {
            $(canvas).remove();
            $(closeBtn).remove();
        });
        $('body').append(closeBtn);
        
        // Your rendering/animation code here
        var ctx = canvas.getContext('2d');
        function animate() {
            // Animation logic
            requestAnimationFrame(animate);
        }
        animate();
    });
}

main();

Best Practices

Console Applications

Database Operations

File Operations

Full-Screen Applications

Limitations and Notes

Next Steps