MIRROR: javascript for ๐Ÿœ's, a tiny runtime with big ambitions
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

migrate to README.md

+262 -324
+262
README.md
··· 1 + # ๐Ÿœ Ant 2 + 3 + **Ant-sized JavaScript Runtime** 4 + 5 + A minimal embedded JavaScript engine with async/await, promises, modules, and built-in APIs for HTTP servers, timers, crypto, and JSON. 6 + 7 + ๐Ÿ“– [Read the blog post about Ant](https://s.tail.so/js-in-one-month) 8 + 9 + ## Installation 10 + 11 + ```bash 12 + curl -fsSL https://ant.themackabu.com/install | bash 13 + 14 + # or with MbedTLS (darwin only) 15 + curl -fsSL https://ant.themackabu.com/install | MBEDTLS=1 bash 16 + ``` 17 + 18 + ## Build from Source 19 + 20 + ```bash 21 + meson setup build && meson compile -C build 22 + ``` 23 + 24 + ## Quick Example 25 + 26 + See `examples/server/server.js` for a complete server example using `Ant.serve()` with `rou3` routing, parameter handling, and various response types. 27 + 28 + ## Modules 29 + 30 + ### HTTP & Networking 31 + 32 + | API | Description | 33 + | ------------- | ----------------------------------------------- | 34 + | `Ant.serve()` | HTTP server with uv_tcp (TLS support via tlsuv) | 35 + | `fetch()` | HTTP client with TLS support (GET, POST, etc.) | 36 + | URL imports | Import directly from URLs | 37 + 38 + ### Timers & Scheduling (built-in) 39 + 40 + | API | Description | 41 + | ------------------ | ---------------------------------------- | 42 + | `setTimeout()` | Execute callback after delay | 43 + | `setInterval()` | Execute callback repeatedly | 44 + | `setImmediate()` | Execute callback on next event loop tick | 45 + | `clearTimeout()` | Cancel scheduled timeout | 46 + | `clearInterval()` | Cancel scheduled interval | 47 + | `queueMicrotask()` | Queue microtask for execution | 48 + 49 + ### File System 50 + 51 + ```js 52 + import { readFile, writeFile } from 'ant:fs'; 53 + ``` 54 + 55 + **Async:** 56 + `readFile()`, `writeFile()`, `unlink()`, `mkdir()`, `rmdir()`, `readdir()`, `stat()` 57 + 58 + **Sync:** 59 + `readFileSync()`, `writeFileSync()`, `unlinkSync()`, `mkdirSync()`, `rmdirSync()`, `readdirSync()`, `statSync()` 60 + 61 + ### Shell Commands 62 + 63 + ```js 64 + import { $ } from 'ant:shell'; 65 + 66 + const result = await $`ls -la`; 67 + console.log(result.text()); 68 + ``` 69 + 70 + | Property | Description | 71 + | ----------------- | ---------------------------- | 72 + | `result.text()` | Get stdout as string | 73 + | `result.lines()` | Get stdout as array of lines | 74 + | `result.exitCode` | Command exit code | 75 + | `result.stdout` | Raw stdout | 76 + | `result.stderr` | Raw stderr | 77 + 78 + ### Child Process 79 + 80 + ```js 81 + import { spawn, exec } from 'child_process'; 82 + ``` 83 + 84 + `spawn()`, `exec()`, `execSync()`, `spawnSync()`, `fork()`, `kill()` 85 + 86 + Events: `on('exit')`, `on('close')`, `on('error')`, `on('data')` 87 + 88 + ### Readline 89 + 90 + ```js 91 + import { createInterface } from 'readline'; 92 + ``` 93 + 94 + `createInterface()`, `question()`, `on('line')`, `on('close')`, `pause()`, `resume()`, `close()` 95 + 96 + Includes command history with navigation support. 97 + 98 + ### OS 99 + 100 + ```js 101 + import os from 'os'; 102 + ``` 103 + 104 + `arch()`, `platform()`, `type()`, `release()`, `version()`, `hostname()`, `homedir()`, `tmpdir()`, `cpus()`, `totalmem()`, `freemem()`, `uptime()`, `networkInterfaces()`, `userInfo()`, `constants`, `EOL` 105 + 106 + ### Navigator 107 + 108 + ```js 109 + navigator.userAgent; // User agent string 110 + navigator.platform; // Platform string 111 + navigator.hardwareConcurrency; // CPU thread count 112 + navigator.locks; // Web Locks API 113 + ``` 114 + 115 + ### Cryptography 116 + 117 + ```js 118 + crypto.random(); // Secure random number 119 + crypto.randomBytes(); // Generate random bytes 120 + crypto.randomUUID(); // UUID v4 121 + crypto.randomUUIDv7(); // UUID v7 (time-ordered) 122 + crypto.getRandomValues(); // Fill TypedArray with random values 123 + btoa(); // Base64 encoding (built-in) 124 + atob(); // Base64 decoding (built-in) 125 + ``` 126 + 127 + ### Path Utilities 128 + 129 + ```js 130 + import { join, resolve, basename } from 'ant:path'; 131 + ``` 132 + 133 + `basename()`, `dirname()`, `extname()`, `join()`, `resolve()`, `normalize()`, `isAbsolute()` 134 + 135 + ### Process 136 + 137 + ```js 138 + Ant.process.env; // Environment variables (with .env support) 139 + Ant.process.cwd; // Current working directory 140 + Ant.process.argv; // Command line arguments 141 + Ant.process.pid; // Process ID 142 + Ant.process.exit(); // Exit with code 143 + Ant.process.cpuUsage(); // CPU usage statistics 144 + ``` 145 + 146 + ### Performance 147 + 148 + ```js 149 + performance.now(); // High-resolution timestamp 150 + performance.timeOrigin; // Time origin for measurements 151 + ``` 152 + 153 + ### Ant Global 154 + 155 + ```js 156 + Ant.version; // Runtime version 157 + Ant.target; // Build target 158 + Ant.revision; // Git revision 159 + Ant.buildDate; // Build date 160 + Ant.serve(); // Start HTTP server 161 + Ant.signal(); // Register signal handlers 162 + Ant.sleep(); // Sleep in seconds 163 + Ant.msleep(); // Sleep in milliseconds 164 + Ant.usleep(); // Sleep in microseconds 165 + Ant.gc(); // Trigger garbage collection 166 + Ant.alloc(); // Get memory allocation info 167 + Ant.stats(); // Get runtime statistics 168 + Ant.typeof(); // Get internal type name 169 + ``` 170 + 171 + ### Foreign Function Interface (FFI) 172 + 173 + ```js 174 + import { dlopen, define } from 'ant:ffi'; 175 + ``` 176 + 177 + `dlopen()`, `define()`, `alloc()`, `free()`, `read()`, `write()`, `callback()`, `freeCallback()`, `pointer()`, `readPtr()`, `suffix`, `FFIType` 178 + 179 + ### Binary Data 180 + 181 + **Buffers:** `ArrayBuffer`, `SharedArrayBuffer`, `Buffer` 182 + 183 + **TypedArrays:** `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `Float32Array`, `Float64Array`, `BigInt64Array`, `BigUint64Array` 184 + 185 + **Utilities:** `DataView`, `TextEncoder`, `TextDecoder` 186 + 187 + ### Atomic Operations 188 + 189 + ```js 190 + Atomics.add() Atomics.sub() Atomics.and() 191 + Atomics.or() Atomics.xor() Atomics.load() 192 + Atomics.store() Atomics.exchange() Atomics.compareExchange() 193 + Atomics.wait() Atomics.notify() Atomics.isLockFree() 194 + ``` 195 + 196 + ### Web Storage 197 + 198 + **localStorage** (file-persistent): 199 + 200 + ```js 201 + localStorage.setFile('./data.json'); // Required before use 202 + localStorage.setItem('key', 'value'); 203 + localStorage.getItem('key'); 204 + ``` 205 + 206 + **sessionStorage** (in-memory): Same API without `setFile()`. 207 + 208 + ### Module System 209 + 210 + ```js 211 + import 'ant:fs' // Built-in fs module 212 + import 'ant:path' // Built-in path module 213 + import 'ant:shell' // Built-in shell module 214 + import 'ant:ffi' // Built-in FFI module 215 + import 'node:*' // Node.js-style aliases 216 + import from 'https://...' // Import from URLs 217 + import data from './data.json' // JSON imports 218 + import text from './file.txt' // Text imports 219 + ``` 220 + 221 + ## TypeScript Support 222 + 223 + Built-in TypeScript type stripping via oxc (no type checking, strip only): 224 + 225 + ```bash 226 + ./build/ant script.ts 227 + ``` 228 + 229 + Type annotations are stripped at parse time. Full type definitions available in `src/types/`. 230 + 231 + ## JavaScript Features 232 + 233 + ### ES1-ES5 Core 234 + 235 + Automatic Semicolon Insertion (ASI), var hoisting, try/catch/finally, for...in loops, regular expressions, strict mode, `Object.defineProperty()`, `Object.freeze()`/`seal()`/`preventExtensions()`, `Function.prototype.call`/`apply`/`bind`, Array methods (map, filter, reduce, forEach, etc.), String methods, Math object, arguments object, labeled statements. 236 + 237 + ### ES6+ Extensions 238 + 239 + Async/await and Promises, arrow functions, classes with private fields (`#privateField`), template literals, destructuring, spread/rest operators, optional chaining (`?.`), nullish coalescing (`??`), logical assignment (`??=`, `&&=`, `||=`), for...of loops, let/const, BigInt, numeric separators (`1_000_000`), Map/Set/WeakMap/WeakSet, Symbol, Proxy/Reflect, default parameters, computed property names, shebang support. 240 + 241 + ## Concurrency 242 + 243 + - Minicoro-based coroutines for async/await 244 + - Event loop with microtask queue 245 + - Atomic operations for lock-free concurrent programming 246 + - SharedArrayBuffer for shared memory between workers 247 + - Atomics.wait/notify for thread synchronization 248 + - Virtual memory allocation for coroutine stacks 249 + 250 + ## System 251 + 252 + - Signal handlers (SIGINT, SIGTERM, etc.) via `Ant.signal()` 253 + - Mark-copy compacting garbage collector + Boehm-Demers-Weiser 254 + - libuv-based async I/O for files and networking 255 + - TLS support via mbedtls or tlsuv 256 + - LTO (Link Time Optimization) build support 257 + - Gzip compression support for HTTP responses 258 + - Native library integration via FFI 259 + 260 + ## License 261 + 262 + MIT License - See [LICENSE.txt](LICENSE.txt) for details.
-324
README.txt
··· 1 - ANT - Ant sized JavaScript Runtime 2 - ================================== 3 - 4 - A minimal embedded JavaScript engine with async/await, promises, modules, 5 - and built-in APIs for HTTP servers, timers, crypto, and JSON. 6 - Check about my blog post about Ant! https://s.tail.so/js-in-one-month 7 - 8 - INSTALL: 9 - ``` 10 - curl -fsSL https://ant.themackabu.com/install | bash 11 - 12 - # or with MbedTLS (darwin only) 13 - curl -fsSL https://ant.themackabu.com/install | MBEDTLS=1 bash 14 - ``` 15 - 16 - BUILD: 17 - meson setup build && meson compile -C build 18 - 19 - EXAMPLE: 20 - See examples/server/server.js for a good server example using Ant.serve() 21 - with `rou3` routing, parameter handling, and various response types. 22 - 23 - MODULES: 24 - 25 - HTTP & Networking: 26 - - Ant.serve() - HTTP server with uv_tcp (TLS support via tlsuv) 27 - - fetch() - HTTP client with TLS support (GET, POST, etc.) 28 - - URL module imports - Import directly from URLs 29 - 30 - Timers & Scheduling (built-in): 31 - - setTimeout() - Execute callback after delay 32 - - setInterval() - Execute callback repeatedly 33 - - setImmediate() - Execute callback on next event loop tick 34 - - clearTimeout() - Cancel scheduled timeout 35 - - clearInterval() - Cancel scheduled interval 36 - - queueMicrotask() - Queue microtask for execution 37 - 38 - File System (import from 'ant:fs'): 39 - Async: 40 - - readFile() - Read file asynchronously 41 - - writeFile() - Write file asynchronously 42 - - unlink() - Delete file asynchronously 43 - - mkdir() - Create directory asynchronously 44 - - rmdir() - Remove directory asynchronously 45 - - readdir() - Read directory contents asynchronously 46 - - stat() - Get file statistics 47 - Sync: 48 - - readFileSync() - Read file synchronously 49 - - writeFileSync() - Write file synchronously 50 - - unlinkSync() - Delete file synchronously 51 - - mkdirSync() - Create directory synchronously 52 - - rmdirSync() - Remove directory synchronously 53 - - readdirSync() - Read directory contents synchronously 54 - - statSync() - Get file statistics synchronously 55 - 56 - Shell Commands (import { $ } from 'ant:shell'): 57 - - $`command` - Execute shell commands with tagged template literals 58 - - result.text() - Get stdout as string 59 - - result.lines() - Get stdout as array of lines 60 - - result.exitCode - Command exit code 61 - - result.stdout - Raw stdout 62 - - result.stderr - Raw stderr 63 - 64 - Child Process (import from 'child_process'): 65 - - spawn() - Spawn child process with async streaming 66 - - exec() - Execute command and buffer output 67 - - execSync() - Execute command synchronously 68 - - spawnSync() - Spawn synchronous child process 69 - - fork() - Fork module as child process 70 - - ChildProcess events - on('exit'), on('close'), on('error'), on('data') 71 - - kill() - Send signal to child process 72 - 73 - Readline (import from 'readline'): 74 - - createInterface() - Create readline interface 75 - - question() - Prompt for user input with promise support 76 - - on('line') - Handle line input events 77 - - on('close') - Handle interface close 78 - - pause()/resume() - Control input stream 79 - - close() - Close interface 80 - - History support - Command history with navigation 81 - 82 - OS (import from 'os'): 83 - - arch() - CPU architecture (x64, arm64, etc.) 84 - - platform() - Operating system platform 85 - - type() - Operating system name 86 - - release() - OS release version 87 - - version() - OS version string 88 - - hostname() - System hostname 89 - - homedir() - User home directory 90 - - tmpdir() - Temporary directory path 91 - - cpus() - CPU core information 92 - - totalmem() - Total system memory 93 - - freemem() - Free system memory 94 - - uptime() - System uptime in seconds 95 - - networkInterfaces() - Network interface information 96 - - userInfo() - Current user information 97 - - constants - OS signals and errno constants 98 - - EOL - Platform-specific end-of-line marker 99 - 100 - Navigator 101 - - navigator.userAgent - User agent string 102 - - navigator.platform - Platform string 103 - - navigator.hardwareConcurrency - CPU thread count 104 - - navigator.locks - Web Locks API for coordination 105 - 106 - Cryptography (crypto): 107 - - random() - Cryptographically secure random number 108 - - randomBytes() - Generate random bytes 109 - - randomUUID() - Generate UUID v4 110 - - randomUUIDv7() - Generate UUID v7 (time-ordered) 111 - - getRandomValues() - Fill TypedArray with random values 112 - - btoa() - Base64 encoding (built-in) 113 - - atob() - Base64 decoding (built-in) 114 - 115 - Path Utilities (import from 'ant:path'): 116 - - basename() - Get filename from path 117 - - dirname() - Get directory from path 118 - - extname() - Get file extension 119 - - join() - Join path segments 120 - - resolve() - Resolve absolute path 121 - - normalize() - Normalize path 122 - - isAbsolute() - Check if path is absolute 123 - 124 - Process (Ant.process): 125 - - env - Environment variables (with .env file support) 126 - - cwd - Current working directory 127 - - argv - Command line arguments 128 - - pid - Process ID 129 - - exit() - Exit process with code 130 - - cpuUsage() - Get CPU usage statistics 131 - 132 - Performance: 133 - - performance.now() - High-resolution timestamp 134 - - performance.timeOrigin - Time origin for measurements 135 - 136 - Ant Global 137 - - Ant.version - Runtime version 138 - - Ant.target - Build target 139 - - Ant.revision - Git revision 140 - - Ant.buildDate - Build date 141 - - Ant.serve() - Start HTTP server 142 - - Ant.signal() - Register signal handlers 143 - - Ant.sleep() - Sleep in seconds 144 - - Ant.msleep() - Sleep in milliseconds 145 - - Ant.usleep() - Sleep in microseconds 146 - - Ant.gc() - Trigger garbage collection 147 - - Ant.alloc() - Get memory allocation info 148 - - Ant.stats() - Get runtime statistics 149 - - Ant.typeof() - Get internal type name 150 - 151 - JSON: 152 - - JSON.parse() - Parse JSON string 153 - - JSON.stringify() - Stringify to JSON 154 - - console.log() - Log with colored JSON output 155 - - console.error() - Log errors 156 - - console.warn() - Log warnings 157 - - console.dir() - Log objects 158 - 159 - Foreign Function Interface (import from 'ant:ffi'): 160 - - dlopen() - Load dynamic library 161 - - define() - Define C function signature 162 - - alloc() - Allocate memory 163 - - free() - Free memory 164 - - read() - Read from pointer 165 - - write() - Write to pointer 166 - - callback() - Create C callback from JS function 167 - - freeCallback() - Free callback memory 168 - - pointer() - Get pointer from value 169 - - readPtr() - Read pointer value 170 - - suffix - Platform library suffix (.so, .dylib, .dll) 171 - - FFIType - Type constants for FFI 172 - 173 - Binary Data: 174 - - ArrayBuffer - Fixed-length binary data buffer 175 - - SharedArrayBuffer - Shared memory buffer for concurrency 176 - - TypedArrays: 177 - * Int8Array, Uint8Array, Uint8ClampedArray 178 - * Int16Array, Uint16Array 179 - * Int32Array, Uint32Array 180 - * Float32Array, Float64Array 181 - * BigInt64Array, BigUint64Array 182 - - DataView - Low-level interface to ArrayBuffer 183 - - Buffer - Node.js-compatible Buffer (Uint8Array subclass) 184 - - TextEncoder - Encode strings to UTF-8 bytes 185 - - TextDecoder - Decode UTF-8 bytes to strings 186 - 187 - Atomic Operations: 188 - - Atomics.add() - Atomic addition 189 - - Atomics.sub() - Atomic subtraction 190 - - Atomics.and() - Atomic bitwise AND 191 - - Atomics.or() - Atomic bitwise OR 192 - - Atomics.xor() - Atomic bitwise XOR 193 - - Atomics.load() - Atomic load 194 - - Atomics.store() - Atomic store 195 - - Atomics.exchange() - Atomic exchange 196 - - Atomics.compareExchange() - Atomic compare-and-exchange 197 - - Atomics.wait() - Wait for shared memory location 198 - - Atomics.notify() - Notify waiters on shared memory 199 - - Atomics.isLockFree() - Check if size is lock-free 200 - 201 - Events: 202 - - addEventListener() - Register event listener 203 - - removeEventListener() - Remove event listener 204 - - dispatchEvent() - Dispatch custom event 205 - 206 - Web Storage: 207 - localStorage (file-persistent): 208 - - setFile() - Set storage file path (required before use) 209 - - setItem() - Store key-value pair 210 - - getItem() - Retrieve value by key 211 - - removeItem() - Remove key-value pair 212 - - clear() - Clear all stored data 213 - - key() - Get key at index 214 - - length - Number of stored items 215 - 216 - sessionStorage (in-memory, session-scoped): 217 - - setItem() - Store key-value pair 218 - - getItem() - Retrieve value by key 219 - - removeItem() - Remove key-value pair 220 - - clear() - Clear all stored data 221 - - key() - Get key at index 222 - - length - Number of stored items 223 - 224 - URL: 225 - - URL() - Parse and manipulate URLs 226 - - URLSearchParams - Work with query strings 227 - 228 - Symbol: 229 - - Symbol() - Create unique symbol 230 - - Symbol.iterator - Well-known iterator symbol 231 - - Symbol.toStringTag - Well-known toStringTag symbol 232 - 233 - Proxy & Reflect: 234 - - Proxy - Create proxy objects with custom behavior 235 - - Reflect - Object reflection methods 236 - 237 - Module System: 238 - - import() - Dynamic ESM module import 239 - - import.meta.url - Current module URL 240 - - import.meta.dirname - Current module directory 241 - - import.meta.resolve() - Resolve module specifier 242 - - export / import - Static ESM imports/exports 243 - - import 'ant:fs' - Import built-in fs module 244 - - import 'ant:path' - Import built-in path module 245 - - import 'ant:shell' - Import built-in shell module ($`...`) 246 - - import 'ant:ffi' - Import built-in FFI module 247 - - import 'node:*' - Node.js-style module aliases 248 - - import from URL - Import modules from HTTP/HTTPS URLs 249 - - import '.json' - Import JSON files as modules 250 - - import '.txt' - Import text files as strings 251 - 252 - TYPESCRIPT: 253 - Built-in TypeScript type stripping via oxc (no type checking, strip only): 254 - - Run .ts files directly: ./build/ant script.ts 255 - - Type annotations are stripped at parse time 256 - - Full type definitions available in src/types/ 257 - 258 - JAVASCRIPT FEATURES: 259 - Full ES1-ES5 compliance with ES6+ extensions: 260 - 261 - ES1-ES5 Core: 262 - - Automatic Semicolon Insertion (ASI) 263 - - var hoisting and function declarations 264 - - try/catch/finally error handling 265 - - for...in loops and property enumeration 266 - - Regular expressions with full pattern matching 267 - - Strict mode support ("use strict") 268 - - Object.defineProperty() with property descriptors 269 - - Object.defineProperties() for batch property definition 270 - - Object.freeze(), Object.seal(), Object.preventExtensions() 271 - - Object.isFrozen(), Object.isSealed(), Object.isExtensible() 272 - - Function.prototype.call/apply/bind 273 - - Array methods (map, filter, reduce, forEach, sort with comparator, etc.) 274 - - String methods (split, replace, replaceAll, includes, startsWith, etc.) 275 - - Math object with all standard functions 276 - - arguments object with callee support 277 - - Labeled statements and labeled loops (break/continue) 278 - 279 - ES6+ Extensions: 280 - - Async/await and Promises (Promise.all, Promise.race, Promise.any, Promise.resolve, etc.) 281 - - Arrow functions, classes, template literals, destructuring 282 - - Private fields and methods in classes (#privateField) 283 - - Spread operator and rest parameters 284 - - Optional chaining (?.) and nullish coalescing (??) 285 - - Logical assignment operators (??=, &&=, ||=) 286 - - for...of loops with iterables 287 - - let/const block scoping 288 - - BigInt support with arithmetic operations 289 - - Number literals (binary 0b1010, octal 0o755, hex 0xFF) 290 - - Numeric separators (1_000_000) 291 - - Built-in collections: Map, Set, WeakMap, WeakSet 292 - - Getter/setter methods in class expressions (get/set) 293 - - Symbol with well-known symbols (iterator, toStringTag) 294 - - Block-level function declaration hoisting 295 - - Default parameters in functions 296 - - Array and object destructuring with defaults 297 - - Computed property names in object literals 298 - - Shebang support (#!/usr/bin/env ant) 299 - 300 - CONCURRENCY: 301 - - Minicoro-based coroutines for async/await 302 - - Event loop with microtask queue 303 - - Atomic operations for lock-free concurrent programming 304 - - SharedArrayBuffer for shared memory between workers 305 - - Atomics.wait/notify for thread synchronization 306 - - Virtual memory allocation for coroutine stacks 307 - 308 - SYSTEM: 309 - - Signal handlers (SIGINT, SIGTERM, etc.) via Ant.signal() 310 - - Mark-copy compacting garbage collector + Boehm-Demers-Weiser 311 - - Coroutine execution tracking for proper GC 312 - - Forward reference tracking for memory compaction 313 - - Internal slots for efficient object metadata storage 314 - - Property lookup caching with interned strings 315 - - Dynamic memory growth with configurable limits 316 - - Non-configurable properties support (Object.defineProperty) 317 - - Native library integration via FFI 318 - - libuv-based async I/O for files and networking 319 - - TLS support via mbedtls or tlsuv 320 - - LTO (Link Time Optimization) build support 321 - - Gzip compression support for HTTP responses 322 - 323 - LICENSE: 324 - MIT License - See LICENSE.txt for details