This document provides comprehensive documentation of all APIs available in Kimera.js.
kimeraLaunch the interactive REPL (Read-Eval-Print Loop).
kimera
Behavior:
Ctrl+C, Ctrl+D, or by calling close()Example:
$ kimera
Kimera 0.2.0
Exit using Ctrl+C or Ctrl+D
> const x = 10
undefined
> x * 2
20
> console.log("Hello!")
Hello!
undefined
> const add = (a, b) => a + b
undefined
> add(5, 3)
8
kimera run [file]Execute a JavaScript or TypeScript file.
kimera run <file> [flags]
Arguments:
file (required) - Path to the JavaScript (.js) or TypeScript (.ts) file to
executeFlags:
--fs - Allow filesystem access (required for Kimera.readFile() and Kimera.writeFile())--net - Allow network access (required for fetch())--env - Allow environment variable access (required for Kimera.getEnv() and Kimera.setEnv())Examples:
# Run a JavaScript file (no permissions)
kimera run script.js
# Run a TypeScript file with type annotations
kimera run app.ts
# Run with permission flags
kimera run script.js --fs # Filesystem only
kimera run script.js --net # Network only
kimera run script.js --env # Environment variables only
kimera run script.js --fs --net --env # All permissions
Error Handling:
The command returns proper exit codes:
0 - Success1 - Error (file not found, syntax error, runtime error)Error messages are formatted with context:
$ kimera run missing.js
Error: failed to run file: failed to read file "missing.js": open missing.js: no such file or directory
kimera versionDisplay the version of Kimera.js.
kimera version
Output:
Kimera 0.2.0
kimera help / kimera --helpDisplay help information about available commands.
kimera --help
Output:
Kimera is a modern JavaScript/TypeScript runtime that provides a REPL
and file execution capabilities.
Usage:
kimera [flags]
kimera [command]
Available Commands:
help Help about any command
run Run a JavaScript or TypeScript file
version Print the version information
Flags:
-h, --help help for kimera
Use "kimera [command] --help" for more information about a command.
console.log(...args)Prints messages to standard output.
Parameters:
...args - Any number of arguments to printExample:
console.log("Hello");
console.log("Multiple", "arguments");
console.log("Value:", 42);
console.log(`Template: ${1 + 1}`);
The Kimera object provides file system operations.
Kimera.readFile(filePath)Reads the entire contents of a file as a string.
Parameters:
filePath (string) - Path to the file to readReturns:
Throws:
Example:
// Read a text file
const content = Kimera.readFile("./data.txt");
console.log(content);
// Read with error handling
try {
const data = Kimera.readFile("./config.json");
console.log(data);
} catch (error) {
console.log("Failed to read file");
}
Kimera.writeFile(filePath, content)Writes content to a file, creating it if it doesn't exist or overwriting if it does.
Parameters:
filePath (string) - Path to the file to writecontent (string) - Content to write to the fileReturns:
Throws:
Example:
// Write simple text
Kimera.writeFile("output.txt", "Hello World!");
// Write multi-line content
const data = "Line 1\nLine 2\nLine 3";
Kimera.writeFile("multiline.txt", data);
// Overwrite existing file
Kimera.writeFile("existing.txt", "New content");
// Write with error handling
try {
Kimera.writeFile("/protected/file.txt", "data");
} catch (error) {
console.log("Permission denied");
}
Note: File system operations require the --fs flag:
kimera run script.js --fs
The Kimera object provides environment variable operations.
Kimera.getEnv(varName)Reads the value of an environment variable.
Parameters:
varName (string) - Name of the environment variable to readReturns:
Throws:
--env flag)Example:
// Read an environment variable
const path = Kimera.getEnv("PATH");
console.log("PATH:", path);
// Check if a variable exists
const myVar = Kimera.getEnv("MY_VAR");
if (myVar) {
console.log("MY_VAR is set to:", myVar);
} else {
console.log("MY_VAR is not set");
}
// With error handling
try {
const home = Kimera.getEnv("HOME");
console.log("Home directory:", home);
} catch (error) {
console.log("Environment access denied");
}
Kimera.setEnv(varName, value)Sets the value of an environment variable in the current process.
Parameters:
varName (string) - Name of the environment variable to setvalue (string) - Value to set the environment variable toReturns:
Throws:
--env flag)Example:
// Set an environment variable
Kimera.setEnv("MY_VAR", "my_value");
// Verify it was set
const value = Kimera.getEnv("MY_VAR");
console.log(value); // "my_value"
// Set with error handling
try {
Kimera.setEnv("CONFIG_PATH", "/etc/config");
console.log("Environment variable set successfully");
} catch (error) {
console.log("Failed to set environment variable");
}
Note: Environment variable operations require the --env flag:
kimera run script.js --env
The Kimera object provides HTTP server functionality for building web servers and APIs.
Kimera.createServer(handler)Creates an HTTP server with the specified request handler function.
Parameters:
handler (function) - A function that receives a request object and returns a response objectRequest Object:
method (string) - HTTP method (GET, POST, PUT, DELETE, etc.)url (string) - Full URL path including query stringpath (string) - URL path without query stringquery (string) - Query string portion of the URLheaders (object) - Request headers as key-value pairsbody (string) - Request body as a stringResponse Object (returned by handler):
status (number) - HTTP status code (default: 200)headers (object) - Response headers as key-value pairsbody (string) - Response body contentReturns:
listen(port) and close() methodsExample:
// Create a simple HTTP server
const server = Kimera.createServer((request) => {
console.log(`${request.method} ${request.path}`);
return {
status: 200,
headers: {
"Content-Type": "text/plain",
},
body: "Hello, World!",
};
});
// Start listening on port 8080
server.listen(8080);
server.listen(port)Starts the HTTP server listening on the specified port.
Parameters:
port (number) - Port number to listen on (1-65535)Returns:
Example:
const server = Kimera.createServer((request) => {
return {
status: 200,
headers: { "Content-Type": "text/html" },
body: "<h1>Welcome</h1>",
};
});
server.listen(3000);
console.log("Server running on port 3000"); // This won't execute until server stops
server.close()Stops the HTTP server and releases the port.
Returns:
Example:
const server = Kimera.createServer((request) => {
if (request.path === "/shutdown") {
server.close(); // Stop the server
return {
status: 200,
body: "Server shutting down",
};
}
return { status: 200, body: "OK" };
});
server.listen(8080);
HTTP Server Examples:
Route Handling:
const server = Kimera.createServer((request) => {
// Route based on path
if (request.path === "/") {
return {
status: 200,
headers: { "Content-Type": "text/html" },
body: "<h1>Home Page</h1>",
};
}
if (request.path === "/api") {
return {
status: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: "API endpoint" }),
};
}
// 404 for unknown routes
return {
status: 404,
headers: { "Content-Type": "text/plain" },
body: "Not Found",
};
});
server.listen(8080);
HTTP Method Handling:
const server = Kimera.createServer((request) => {
if (request.path === "/data") {
if (request.method === "GET") {
return {
status: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items: [1, 2, 3] }),
};
}
if (request.method === "POST") {
return {
status: 201,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
message: "Created",
received: request.body
}),
};
}
return {
status: 405,
body: "Method Not Allowed",
};
}
return { status: 404, body: "Not Found" };
});
server.listen(8080);
Note: HTTP server operations require the --net flag:
kimera run server.js --net
close()Exits the Kimera runtime immediately.
Example:
console.log("Before exit");
close();
console.log("This won't print");
Kimera provides the following global objects:
console - Console logging APIKimera - File system, environment variables, HTTP server, and runtime APIclose() - Function to exit the runtimefetch() - HTTP client for making web requestsKimera.js supports modern JavaScript (ES6+) including:
Arrow Functions
const add = (a, b) => a + b;
Template Literals
const name = "World";
console.log(`Hello, ${name}!`);
Async/Await
const asyncFunc = async () => {
return "result";
};
asyncFunc().then(console.log);
Destructuring
const obj = { a: 1, b: 2 };
const { a, b } = obj;
Spread Operator
const arr = [1, 2, 3];
const arr2 = [...arr, 4, 5];
For...of Loops
for (const item of [1, 2, 3]) {
console.log(item);
}
Full TypeScript support with automatic transpilation:
// Type annotations
const greet = (name: string): string => {
return `Hello, ${name}!`;
};
// Interfaces
interface User {
name: string;
age: number;
}
const user: User = {
name: "Alice",
age: 30,
};
// Generics
function identity<T>(arg: T): T {
return arg;
}
Note: TypeScript is transpiled to JavaScript using esbuild, so type checking happens at transpilation time, not runtime.
All file operations and runtime errors can be caught using try-catch:
try {
const content = Kimera.readFile("missing.txt");
} catch (error) {
console.log("Error occurred:", error);
}
try {
Kimera.writeFile("/root/protected.txt", "data");
} catch (error) {
console.log("Permission denied");
}
Always handle file errors: Use try-catch blocks when reading or writing files
try {
const data = Kimera.readFile(filename);
} catch (error) {
console.log("File operation failed");
}
Use async/await for cleaner code: Kimera supports modern async patterns
const main = async () => {
// Your async code here
};
main();
Leverage TypeScript for type safety: Use .ts files for better development experience
interface Config {
port: number;
host: string;
}
Kimera uses Go's idiomatic error handling patterns:
fmt.Errorf with %werrors.Is and errors.AsExample error flow:
Error: failed to run file: failed to read file "script.js": open script.js: no such file or directory
[cmd layer] [core layer] [os layer]
deferkimera run command creates a fresh runtime (isolation)Current limitations of Kimera.js:
// Read a file and count lines
const content = Kimera.readFile("data.txt");
const lines = content.split("\n");
console.log(`File has ${lines.length} lines`);
Run with:
kimera run script.js --fs
const logMessage = (message) => {
const timestamp = new Date().toISOString();
const logEntry = `[${timestamp}] ${message}\n`;
try {
// Append to log (read existing, append, write back)
let existingLog = "";
try {
existingLog = Kimera.readFile("app.log");
} catch (e) {
// File doesn't exist yet, that's okay
}
Kimera.writeFile("app.log", existingLog + logEntry);
} catch (error) {
console.log("Failed to write log");
}
};
logMessage("Application started");
logMessage("Processing data");
Run with:
kimera run script.js --fs
interface FileData {
content: string;
lines: number;
}
const analyzeFile = (path: string): FileData => {
const content: string = Kimera.readFile(path);
const lines: number = content.split("\n").length;
return { content, lines };
};
const result = analyzeFile("data.txt");
console.log(`Lines: ${result.lines}`);
Run with:
kimera run script.ts --fs
// Create a REST API server
const server = Kimera.createServer((request) => {
console.log(`${request.method} ${request.path}`);
// CORS headers for API
const headers = {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
};
// Route: GET /users
if (request.path === "/users" && request.method === "GET") {
return {
status: 200,
headers,
body: JSON.stringify([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
]),
};
}
// Route: POST /users
if (request.path === "/users" && request.method === "POST") {
const newUser = JSON.parse(request.body);
return {
status: 201,
headers,
body: JSON.stringify({
id: 3,
...newUser,
created: true
}),
};
}
// Route: GET /health
if (request.path === "/health") {
return {
status: 200,
headers,
body: JSON.stringify({ status: "healthy", uptime: Date.now() }),
};
}
// 404 for unknown routes
return {
status: 404,
headers,
body: JSON.stringify({ error: "Not Found" }),
};
});
console.log("API server starting on port 3000...");
server.listen(3000);
Run with:
kimera run api.js --net
Test with:
curl http://localhost:3000/users
curl -X POST -d '{"name":"Charlie"}' http://localhost:3000/users
curl http://localhost:3000/health