### Install @bunova/tracing Source: https://github.com/nds-stack/bunova/blob/main/plugins/tracing/README.md Install the tracing plugin using bun. ```bash bun add @bunova/tracing ``` -------------------------------- ### Install @bunova/redis and ioredis Source: https://github.com/nds-stack/bunova/blob/main/plugins/redis/README.md Install the necessary packages using bun. ```bash bun add @bunova/redis ioredis ``` -------------------------------- ### Install @bunova/sqlite Source: https://github.com/nds-stack/bunova/blob/main/plugins/sqlite/README.md Install the plugin using Bun. ```bash bun add @bunova/sqlite ``` -------------------------------- ### Install @bunova/queue Source: https://github.com/nds-stack/bunova/blob/main/plugins/queue/README.md Install the core queue plugin using npm or yarn. ```bash bun add @bunova/queue ``` -------------------------------- ### Install In-Process Plugin Source: https://github.com/nds-stack/bunova/blob/main/README.md Use `runtime.use(plugin, options?)` to install an in-process plugin by providing a plugin object with `name`, `version`, and an `install` function. The `install` function receives a context object and can register its own lifecycle hooks or broadcast messages. ```ts runtime.use({ name: "my-plugin", version: "1.0.0", install(ctx) { ctx.on("ready", () => { /* plugin ready */ }) ctx.broadcast("my-plugin:ready", {}) }, }) ``` -------------------------------- ### Install and Manage Plugins with runtime.use Source: https://context7.com/nds-stack/bunova/llms.txt Use `runtime.use` to install plugins either in-process or as isolated worker processes. Ensure plugins are correctly defined with name, version, and install/uninstall hooks. ```typescript import { runtime } from "bunova" import type { Plugin, PluginContext } from "bunova" // In-process plugin const metricsPlugin: Plugin = { name: "metrics-collector", version: "1.0.0", install(ctx: PluginContext) { ctx.on("ready", () => { ctx.broadcast("metrics:ready", { plugin: "metrics-collector" }) }) ctx.logger?.info("Metrics plugin installed") }, uninstall(ctx: PluginContext) { ctx.logger?.info("Metrics plugin uninstalled") }, } await runtime.boot({ plugins: [metricsPlugin] }) // Or install after boot runtime.use(metricsPlugin) // Worker-isolated plugin — crash-safe subprocess runtime.use("./plugins/redis-monitor.ts", { isolate: true }) // Check installed plugins console.log(runtime.plugins.list) // [{ name: "metrics-collector", version: "1.0.0", installed: true, isolated: false, installedAt: "..." }] ``` -------------------------------- ### Install @bunova/queue with SQLite Persistence Source: https://github.com/nds-stack/bunova/blob/main/plugins/queue/README.md Install the queue plugin along with @nds-stack/bunql for SQLite persistence. ```bash bun add @bunova/queue @nds-stack/bunql ``` -------------------------------- ### Install @bunova/auth Plugin Source: https://github.com/nds-stack/bunova/blob/main/plugins/auth/README.md Install the @bunova/auth package using npm or yarn. ```bash bun add @bunova/auth ``` -------------------------------- ### Initialize Bunova Runtime Source: https://github.com/nds-stack/bunova/blob/main/README.md Import and boot the Bunova runtime. This is the basic setup for integrating Bunova into your application. ```typescript import { runtime } from "bunova" runtime.boot() ``` -------------------------------- ### Install Bunova using Bun Source: https://github.com/nds-stack/bunova/blob/main/README.md Add Bunova as a project dependency using the Bun package manager. ```bash bun add bunova ``` -------------------------------- ### Production API Server with Worker Isolation Source: https://github.com/nds-stack/bunova/blob/main/README.md Example of a production API server setup using Bunova with worker isolation, auto-discovery, and code watching. This configuration boots the runtime with logging, telemetry, discovery, and watch enabled, then starts the server. ```typescript import { runtime } from "bunova" await runtime.boot({ logger: { level: "info" }, telemetry: true, discovery: true, // auto-scan src/workers/ and src/routes/ watch: true, // auto-reload on code changes }) runtime.serve({ port: 3000 }) ``` ```typescript // src/routes/users.ts export default { async fetch(req: Request) { return Response.json({ users: [] }) } } ``` -------------------------------- ### Install @bunova/ws Plugin Source: https://github.com/nds-stack/bunova/blob/main/plugins/ws/README.md Install the @bunova/ws plugin using Bun package manager. ```bash bun add @bunova/ws ``` -------------------------------- ### Recommended Production Runtime Boot Configuration Source: https://github.com/nds-stack/bunova/blob/main/README.md Recommended configuration for booting the Bunova runtime in production. This setup includes enabling info-level logging, telemetry for monitoring, and signals for graceful shutdown. ```typescript await runtime.boot({ logger: { level: "info" }, telemetry: true, // monitor memory and event loop signals: true, // graceful shutdown on SIGTERM }) ``` -------------------------------- ### Initialize Bunova Runtime Source: https://github.com/nds-stack/bunova/blob/main/README.md Call `runtime.boot()` once at your application's entry point. It can be called with no arguments for minimal setup or with an options object to configure logging, environment variable validation, telemetry, and more. ```ts import { runtime } from "bunova" // Minimal runtime.boot() // With options runtime.boot({ logger: { level: "debug" }, env: { schema: { PORT: "port", DB_URL: "url" } }, telemetry: true, signals: true, }) ``` -------------------------------- ### Usage Example for @bunova/ws Plugin Source: https://github.com/nds-stack/bunova/blob/main/plugins/ws/README.md Integrate the wsPlugin with Bunova runtime and a Bun.js WebSocket server. Track WebSocket events and subscribe to connection metrics. ```typescript import { runtime } from "bunova" import { wsPlugin } from "@bunova/ws" const ws = wsPlugin({ label: "chat-ws", interval: 5000 }) runtime.use(ws) runtime.on("ready", () => { Bun.serve({ port: 3000, fetch(req, server) { server.upgrade(req) }, websocket: { open: () => ws.trackOpen(), message: () => ws.trackMessage(), close: () => ws.trackClose(), drain: () => {}, }, }) }) runtime.bus.subscribe("chat-ws:metrics", (m) => { console.log(`WS: ${m.connections} connections, ${m.messages} msg/s`) }) ``` -------------------------------- ### Start Route Server with Worker Isolation Source: https://github.com/nds-stack/bunova/blob/main/README.md Start a Bun.serve with automatic route worker proxying. This enables automatic discovery of routes and spawns them as isolated workers. Use `runtime.serve()` as a drop-in replacement for `Bun.serve()`. ```typescript runtime.boot({ discovery: true }) // scans src/routes/*.ts // Routes are auto-discovered and spawned as isolated workers // runtime.serve() proxies matching requests to route workers runtime.serve({ port: 3000 }) ``` ```typescript // src/routes/users.ts — auto-registered as /users/* pattern export default { async fetch(request: Request): Promise { return new Response("Hello from isolated route worker!") } } ``` -------------------------------- ### runtime.use(plugin, options?) Source: https://github.com/nds-stack/bunova/blob/main/README.md Installs a plugin into the runtime. Plugins can be provided as an in-process object or a file path for worker-isolated execution. This allows for extending the runtime's functionality with custom modules. ```APIDOC ## `runtime.use(plugin, options?)` ### Description Install a plugin at runtime. Accepts a plugin object (in-process) or a file path (worker-isolated). ### Method `runtime.use(plugin, options?) ### Parameters #### plugin - **plugin** (`object | string`) - The plugin object or file path. #### options - **isolate** (`boolean`) - Optional - When `true` and a file path is provided, the plugin is loaded in a separate Bun subprocess. ### In-process plugin (default) ```ts runtime.use({ name: "my-plugin", version: "1.0.0", install(ctx) { ctx.on("ready", () => { /* plugin ready */ }) ctx.broadcast("my-plugin:ready", {}) }, }) ``` ### Worker-isolated plugin (file path) ```ts runtime.use("./plugins/redis-monitor.ts", { isolate: true }) // Spawned as separate Bun process — crash doesn't affect main runtime ``` When `{ isolate: true }` is combined with a file path, the plugin is loaded in a separate Bun subprocess. The plugin file should export a `default` object with `{ name, version, install?, uninstall? }`. ``` -------------------------------- ### runtime.serve(options) Source: https://context7.com/nds-stack/bunova/llms.txt Starts a `Bun.serve` instance that supports automatic route-worker proxying. Requests matching registered route patterns are forwarded to their corresponding isolated route workers. Requests that do not match any pattern are handled by the provided `fetch` fallback function. ```APIDOC ## `runtime.serve(options)` Start a `Bun.serve` instance with automatic route-worker proxying. Requests matching registered route patterns are forwarded to the corresponding isolated route worker; unmatched requests fall through to the provided `fetch` fallback. ```ts import { runtime } from "bunova" await runtime.boot({ discovery: true }) // auto-discovers src/routes/*.ts and registers each as an isolated worker runtime.serve({ port: 3000, fetch(req) { return new Response("Not Found", { status: 404 }) }, }) // src/routes/users.ts — auto-registered as /users/* worker export default { async fetch(request: Request): Promise { return Response.json({ users: [{ id: 1, name: "Alice" }] }) } } // src/routes/api/posts.ts + src/routes/api/comments.ts // → grouped under one "api" worker, dispatched by URL pattern ``` ``` -------------------------------- ### Install Worker-Isolated Plugin Source: https://github.com/nds-stack/bunova/blob/main/README.md Install a plugin as a worker-isolated process by providing a file path and the `{ isolate: true }` option to `runtime.use()`. The plugin file must export a default object with `name`, `version`, and optional `install`/`uninstall` functions. This prevents plugin crashes from affecting the main runtime. ```ts runtime.use("./plugins/redis-monitor.ts", { isolate: true }) // Spawned as separate Bun process — crash doesn't affect main runtime ``` -------------------------------- ### Background Job Worker with Plugin Source: https://github.com/nds-stack/bunova/blob/main/README.md Example of setting up a background job worker with a plugin in Bunova. This snippet shows how to boot the runtime with a queue plugin and then enqueue a job. ```typescript import { runtime } from "bunova" import { queuePlugin } from "@bunova/queue" await runtime.boot({ plugins: [queuePlugin({ maxRetries: 3 })], }) // Enqueue a job const { enqueue } = runtime.plugins.get("@bunova/queue") as any enqueue("send-email", { to: "user@example.com" }) ``` -------------------------------- ### runtime.use(plugin, options?) Source: https://context7.com/nds-stack/bunova/llms.txt Installs a plugin into the Bunova runtime. Plugins can be provided as an inline object or a file path. Options like `{ isolate: true }` allow plugins to run in separate, crash-safe subprocesses. ```APIDOC ## `runtime.use(plugin, options?)` ### Description Installs a plugin into the runtime. Accepts either an inline plugin object (in-process) or a file path string. When `{ isolate: true }` is passed with a file path, the plugin is spawned as a separate Bun subprocess whose crash does not affect the main runtime. ### Parameters #### Path Parameters - **plugin** (Plugin | string) - Required - The plugin object or file path to install. - **options** (object) - Optional - Configuration options for the plugin. - **isolate** (boolean) - Optional - If true, spawns the plugin as an isolated subprocess. ### Request Example ```ts import { runtime } from "bunova" import type { Plugin, PluginContext } from "bunova" // In-process plugin const metricsPlugin: Plugin = { name: "metrics-collector", version: "1.0.0", install(ctx: PluginContext) { ctx.on("ready", () => { ctx.broadcast("metrics:ready", { plugin: "metrics-collector" }) }) ctx.logger?.info("Metrics plugin installed") }, uninstall(ctx: PluginContext) { ctx.logger?.info("Metrics plugin uninstalled") }, } await runtime.boot({ plugins: [metricsPlugin] }) // Or install after boot runtime.use(metricsPlugin) // Worker-isolated plugin — crash-safe subprocess runtime.use("./plugins/redis-monitor.ts", { isolate: true }) // Check installed plugins console.log(runtime.plugins.list) // [{ name: "metrics-collector", version: "1.0.0", installed: true, isolated: false, installedAt: "..." }] ``` ``` -------------------------------- ### Start Bun.serve with Route-Worker Proxying Source: https://context7.com/nds-stack/bunova/llms.txt Initiate a Bun.serve instance using runtime.serve for automatic route-worker proxying. Requests matching registered patterns are forwarded to isolated workers, with unmatched requests falling back to a provided fetch handler. ```typescript import { runtime } from "bunova" await runtime.boot({ discovery: true }) // auto-discovers src/routes/*.ts and registers each as an isolated worker runtime.serve({ port: 3000, fetch(req) { return new Response("Not Found", { status: 404 }) }, }) // src/routes/users.ts — auto-registered as /users/* worker export default { async fetch(request: Request): Promise { return Response.json({ users: [{ id: 1, name: "Alice" }] }) } } // src/routes/api/posts.ts + src/routes/api/comments.ts // → grouped under one "api" worker, dispatched by URL pattern ``` -------------------------------- ### runtime.onMemoryLeak Source: https://context7.com/nds-stack/bunova/llms.txt Starts a memory watchdog that triggers a callback when heap usage exceeds a specified threshold. It returns a `MemoryWatchdog` instance that can be stopped. ```APIDOC ## `runtime.onMemoryLeak(handler, options?)` Start a memory watchdog that fires a callback when heap usage exceeds a threshold. Returns a `MemoryWatchdog` instance that can be stopped. ```ts import { runtime } from "bunova" await runtime.boot({ telemetry: true }) // Default: 200MB threshold, 10s interval const watchdog = runtime.onMemoryLeak(async () => { runtime.logger?.warn("Memory breach detected — restarting workers") runtime.worker.restart() }, { threshold: 500 * 1024 * 1024, // 500MB interval: 5000, // check every 5s }) // Watchdog statistics console.log(watchdog.stats) // { threshold: 524288000, currentUsage: 47185920, breaches: 0, lastBreach: null, active: true } // Manually stop the watchdog watchdog.stop() // Restart it later watchdog.start() ``` ``` -------------------------------- ### Production API Service with Bunova Source: https://github.com/nds-stack/bunova/blob/main/README.md A complete Bunova-powered HTTP API example demonstrating auto-recovery, request tracking, worker isolation, and graceful shutdown. Configure logging, telemetry, discovery, and watch modes during boot. ```typescript import { runtime } from "bunova" async function main() { await runtime.boot({ logger: { level: "info" }, telemetry: { memory: true, eventLoop: true, interval: 10000, // snapshot every 10s }, discovery: true, // auto-detect routes and workers watch: true, // reload on file changes }) // Route-based worker isolation runtime.serve({ port: Number(process.env.PORT) || 3000, fetch(req) { // Fallback handler — for unmatched routes return new Response("Not Found", { status: 404 }) }, }) // Graceful shutdown runtime.on("shutdown", () => { runtime.logger?.info("Server shutting down") }) // Health reporting setInterval(() => { const s = runtime.stats() const m = runtime.metrics.snapshot() runtime.logger?.info("Runtime health", { state: s.state, workers: s.workers, memory: m ? Math.round(m.memory.heapUsed / 1024 / 1024) + "MB" : "N/A", uptime: s.uptime + "ms", }) }, 30000) } main().catch(console.error) ``` -------------------------------- ### Register Lifecycle Hooks Source: https://github.com/nds-stack/bunova/blob/main/README.md Use `runtime.on(event, handler)` to register callbacks for various runtime lifecycle events such as booting, plugin initialization, server starting, application readiness, and shutdown. ```ts runtime.on("boot", () => { /* runtime booting */ }) runtime.on("plugin-init", () => { /* plugins loaded */ }) runtime.on("starting-server", () => { /* server starting */ }) runtime.on("ready", () => { /* application ready */ }) runtime.on("running", () => { /* fully operational */ }) runtime.on("degraded", (reason) => { /* health issue detected */ }) runtime.on("recovering", () => { /* attempting recovery */ }) runtime.on("shutdown", () => { /* cleanup before exit */ }) runtime.on("crash", (err) => { /* unrecoverable error */ }) ``` -------------------------------- ### Start and End Spans with Bunova Tracer Source: https://context7.com/nds-stack/bunova/llms.txt Use `runtime.tracer.start` to begin a span and `runtime.tracer.end` to complete it. Spans can be nested using `parentId`. The tracer collects statistics on span activity. ```typescript import { runtime } from "bunova" await runtime.boot() // Top-level span const rootId = runtime.tracer.start("http.request", undefined, { method: "GET", path: "/users" }) // Nested child span const dbId = runtime.tracer.start("db.query", rootId, { table: "users", sql: "SELECT * FROM users LIMIT 10" }) const rows = await db.query("SELECT * FROM users LIMIT 10") const dbSpan = runtime.tracer.end(dbId) console.log(`DB query took ${dbSpan?.duration?.toFixed(2)}ms`) // DB query took 4.72ms const serializeId = runtime.tracer.start("serialize", rootId) const json = JSON.stringify(rows) runtime.tracer.end(serializeId) const rootSpan = runtime.tracer.end(rootId) console.log(rootSpan) // { id: "trace-1", name: "http.request", startTime: ..., endTime: ..., duration: 7.1, // metadata: { method: "GET", path: "/users" } } // Tracer statistics console.log(runtime.tracer.stats) // { spansStarted: 3, spansCompleted: 3, activeSpans: 0 } ``` -------------------------------- ### Start Memory Leak Watchdog with Bunova Source: https://context7.com/nds-stack/bunova/llms.txt Configure `runtime.onMemoryLeak` to monitor heap usage and trigger a callback when a threshold is exceeded. The watchdog can be manually stopped and restarted. ```typescript import { runtime } from "bunova" await runtime.boot({ telemetry: true }) // Default: 200MB threshold, 10s interval const watchdog = runtime.onMemoryLeak(async () => { runtime.logger?.warn("Memory breach detected — restarting workers") runtime.worker.restart() }, { threshold: 500 * 1024 * 1024, // 500MB interval: 5000, // check every 5s }) // Watchdog statistics console.log(watchdog.stats) // { threshold: 524288000, currentUsage: 47185920, breaches: 0, lastBreach: null, active: true } // Manually stop the watchdog watchdog.stop() // Restart it later watchdog.start() ``` -------------------------------- ### runtime.stats() Source: https://github.com/nds-stack/bunova/blob/main/README.md Retrieves statistics about the current runtime state. This includes information such as the runtime's state, uptime, start time, number of workers, plugins, and telemetry status. ```APIDOC ## `runtime.stats()` ### Description Get runtime statistics. ### Method `runtime.stats() ### Response Example ```json { "state": "ready", "uptime": 12345, "startedAt": "...", "workers": 2, "plugins": 1, "telemetry": true } ``` ``` -------------------------------- ### runtime.on(event, handler) Source: https://github.com/nds-stack/bunova/blob/main/README.md Registers a handler for specific lifecycle events within the runtime. This allows for custom logic to be executed at various stages of the application's lifecycle, such as booting, server starting, or shutdown. ```APIDOC ## `runtime.on(event, handler)` ### Description Register a lifecycle hook. ### Method `runtime.on(event, handler)` ### Parameters #### Event - **event** (`string`) - The name of the event to listen for. - **handler** (`Function`) - The callback function to execute when the event is fired. ### Supported Events - `boot`: Runtime starts initialization - `plugin-init`: Plugins loaded successfully - `starting-server`: About to start server - `ready`: Runtime fully initialized - `running`: Fully operational - `degraded`: Health issue detected - `recovering`: Attempting recovery - `shutdown`: Graceful shutdown initiated - `crash`: Unrecoverable error occurred ### Request Example ```ts runtime.on("boot", () => { /* runtime booting */ }) runtime.on("plugin-init", () => { /* plugins loaded */ }) runtime.on("starting-server", () => { /* server starting */ }) runtime.on("ready", () => { /* application ready */ }) runtime.on("running", () => { /* fully operational */ }) runtime.on("degraded", (reason) => { /* health issue detected */ }) runtime.on("recovering", () => { /* attempting recovery */ }) runtime.on("shutdown", () => { /* cleanup before exit */ }) runtime.on("crash", (err) => { /* unrecoverable error */ }) ``` ``` -------------------------------- ### Get Runtime Metrics with Bunova Source: https://context7.com/nds-stack/bunova/llms.txt Access live process readings and serve monitoring using the runtime.metrics API. This is available even when telemetry is disabled, falling back to live process.memoryUsage() calls. ```typescript import { runtime } from "bunova" await runtime.boot({ telemetry: true }) // Memory const mem = runtime.metrics.memory() console.log(`Heap: ${Math.round(mem.heapUsed / 1024 / 1024)}MB / ${Math.round(mem.heapTotal / 1024 / 1024)}MB`) console.log(`RSS: ${Math.round(mem.rss / 1024 / 1024)}MB`) // Event loop lag const el = runtime.metrics.eventLoop() console.log(`Event loop lag: ${el.lag.toFixed(2)}ms`) // CPU const cpu = runtime.metrics.cpu() console.log(`CPU user: ${cpu.user}µs, system: ${cpu.system}µs`) // Full snapshot const snap = runtime.metrics.snapshot() console.log(snap.timestamp) // HTTP serve metrics (populated via wrapFetch) const serve = runtime.metrics.serve() if (serve) { console.log(`Total requests: ${serve.totalRequests}`) console.log(`Avg duration: ${serve.avgDurationMs.toFixed(2)}ms`) console.log(`Status counts:`, serve.statusCounts) // { 200: 950, 404: 30, 500: 20 } } ``` -------------------------------- ### Get Runtime Statistics Source: https://github.com/nds-stack/bunova/blob/main/README.md Retrieve current runtime statistics, including its state, uptime, start time, worker count, plugin count, and telemetry status, by calling `runtime.stats()`. ```ts const stats = runtime.stats() // { state: "ready", uptime: 12345, startedAt: "...", workers: 2, plugins: 1, telemetry: true } ``` -------------------------------- ### Boot and Serve HTTP Server with Bunova Source: https://context7.com/nds-stack/bunova/llms.txt Use this to initialize a full-featured HTTP server with isolated route workers, automatic file-change reloading, telemetry, and structured logging. ```javascript runtime.boot({ discovery: true, telemetry: true, watch: true }) runtime.serve({ port: 3000 }) ``` -------------------------------- ### runtime.boot(options?) Source: https://context7.com/nds-stack/bunova/llms.txt Initializes the entire Bunova runtime. This method must be called once at the application entry point to set up logging, environment validation, signal handlers, telemetry, plugin loading, auto-discovery, and file watching. ```APIDOC ## `runtime.boot(options?)` ### Description Initializes the entire runtime. Must be called once at application entry. Transitions the runtime through all startup states and sets up logger, env, signals, telemetry, plugins, discovery, and file watching according to the provided options. ### Method `runtime.boot(options?: BootOptions)` ### Parameters #### Options - **logger** (object) - Optional - Logger configuration. Example: `{ level: "info", format: "json" }` - **env** (object) - Optional - Environment variable schema for validation. Example: `{ schema: { PORT: "port", DB_URL: "url" } }` - **telemetry** (object) - Optional - Telemetry configuration. Example: `{ memory: true, cpu: true, interval: 10000 }` - **signals** (boolean) - Optional - Enable automatic handling of SIGINT, SIGTERM, and uncaughtException. Defaults to true. - **discovery** (boolean) - Optional - Enable auto-scanning for plugins, workers, and routes. Defaults to true. - **watch** (object) - Optional - File watching configuration. Example: `{ dirs: ["src", "src/routes"] }` - **plugins** (array) - Optional - An array of plugins to install at boot. ### Request Example ```ts import { runtime } from "bunova" await runtime.boot({ logger: { level: "info", format: "json" }, env: { schema: { PORT: "port", DB_URL: "url", JWT_SECRET: "string" }, }, telemetry: { memory: true, eventLoop: true, cpu: true, interval: 10000, // snapshot every 10s history: 100, }, signals: true, discovery: true, watch: { dirs: ["src", "src/routes"] }, plugins: [], }) console.log(runtime.state) // "running" console.log(runtime.uptime) // milliseconds since boot ``` ### Response Upon successful boot, the runtime state will transition to `running`. ``` -------------------------------- ### runtime.boot(options?) Source: https://github.com/nds-stack/bunova/blob/main/README.md Initializes the Bunova runtime. This function should be called once at the application's entry point. It accepts an optional configuration object for logger, environment variables, telemetry, plugins, signals, discovery, and watch behavior. ```APIDOC ## `runtime.boot(options?)` ### Description Initialize the runtime. Call once at application entry. ### Method `runtime.boot(options?)` ### Parameters #### Options - **logger** (`BunLoggerOptions`) - Optional - Logger configuration from `@nds-stack/bun-logger` - **env** (`{ schema: EnvSchema }`) - Optional - Env schema from `@nds-stack/bun-env` for validation - **telemetry** (`boolean | TelemetryOptions`) - Optional - Enable automatic telemetry collection - **plugins** (`Plugin[]`) - Optional - Plugins to install at boot - **signals** (`boolean`) - Optional - Auto-register SIGINT/SIGTERM/uncaughtException handlers (Default: `true`) - **discovery** (`boolean`) - Optional - Auto-scan src/plugins/, src/workers/, src/routes/ - **watch** (`boolean | { dirs: string[] }`) - Optional - File watcher for boundary reload on change ### Request Example ```ts // Minimal runtime.boot() // With options runtime.boot({ logger: { level: "debug" }, env: { schema: { PORT: "port", DB_URL: "url" } }, telemetry: true, signals: true, }) ``` ``` -------------------------------- ### Run Benchmarks Source: https://github.com/nds-stack/bunova/blob/main/README.md Command to run the performance benchmarks for Bunova. ```bash bun run bench ``` -------------------------------- ### Link Bunova from Source Source: https://github.com/nds-stack/bunova/blob/main/README.md Link Bunova locally for development. First, link the bunova project itself, then link it into your application project. ```bash bun link # from the bunova project directory bun link bunova # in your application project ``` -------------------------------- ### Auto-Discovered Route Worker Source: https://github.com/nds-stack/bunova/blob/main/README.md Example of a route file that is auto-discovered by Bunova. This worker handles requests for the '/users' route and fetches data from a database. ```typescript // src/routes/users.ts — auto-discovered, isolated worker export default { async fetch(req: Request) { const users = await db.query("SELECT * FROM users") return Response.json(users) } } ``` -------------------------------- ### Custom Logger Transport with File Output Source: https://github.com/nds-stack/bunova/blob/main/README.md Configures Bunova to use a custom logger transport that writes logs to a file. Requires installing the '@nds-stack/bun-logger' package. ```typescript import { runtime } from "bunova" import { FileTransport } from "@nds-stack/bun-logger" runtime.boot({ logger: { level: "debug", transports: [new FileTransport({ path: "./app.log" })], }, }) ``` -------------------------------- ### Bunova Queue Plugin Usage Source: https://github.com/nds-stack/bunova/blob/main/plugins/queue/README.md Demonstrates how to initialize the queue plugin, register it with the Bunova runtime, enqueue jobs, process them, and subscribe to job events. ```typescript import { runtime } from "bunova" import { queuePlugin } from "@bunova/queue" const queue = queuePlugin({ pollInterval: 1000, maxRetries: 3, }) runtime.use(queue) // Enqueue a job queue.enqueue("email:send", { to: "user@example.com", template: "welcome" }) // Process jobs queue.process(async (job) => { if (job.type === "email:send") { console.log(`Sending email to ${job.payload.to}`) } }) // Listen for events runtime.bus.subscribe("email:send:started", (event) => { console.log(`Job started: ${event.id}`) }) ``` -------------------------------- ### Distributed Tracing Source: https://github.com/nds-stack/bunova/blob/main/README.md Implement distributed tracing by starting and ending trace spans. This allows for tracking requests across different services and measuring their duration, optionally with metadata. ```typescript const id = runtime.tracer.start("db-query", undefined, { table: "users" }) // ... do work ... runtime.tracer.end(id) // { id, name, duration: 12.3, metadata: { table: "users" } } ``` -------------------------------- ### Configure and Use SQLite Plugin Source: https://context7.com/nds-stack/bunova/llms.txt Set up the SQLite plugin with a database path and monitoring interval. Subscribe to ready, metrics, and error events for the database. ```typescript import { runtime } from "bunova" import { sqlitePlugin } from "@bunova/sqlite" runtime.use(sqlitePlugin({ path: "./data/app.db", label: "app-db", interval: 5000, })) runtime.bus.subscribe("app-db:ready", ({ path }) => console.log(`SQLite ready: ${path}`)) runtime.bus.subscribe("app-db:metrics", ({ writes, reads, queue }) => { console.log(`DB writes: ${writes.total}, reads: ${reads.total}, queue: ${queue}`) }) runtime.bus.subscribe("app-db:error", ({ message }) => console.error("SQLite error:", message)) await runtime.boot() ``` -------------------------------- ### Custom Memory Watchdog Threshold and Control Source: https://github.com/nds-stack/bunova/blob/main/README.md Allows setting a custom threshold for the memory watchdog and provides methods to stop or start the watchdog. The watchdog monitors for memory leaks. ```typescript const watchdog = runtime.onMemoryLeak(() => { console.log("Memory breach detected!") }) watchdog.stop() // Disable when not needed ``` -------------------------------- ### Configure and Use WebSocket Plugin Source: https://context7.com/nds-stack/bunova/llms.txt Set up the WebSocket plugin for connection monitoring. Define a Bun server to handle WebSocket upgrades and track connection events. ```typescript import { runtime } from "bunova" import { wsPlugin } from "@bunova/ws" const ws = wsPlugin({ label: "chat-ws", interval: 3000 }) runtime.use(ws) await runtime.boot() runtime.on("ready", () => { Bun.serve({ port: 3000, fetch(req, server) { if (server.upgrade(req)) return return new Response("Upgrade required", { status: 426 }) }, websocket: { open: (socket) => { ws.trackOpen(); socket.send("Welcome!") }, message: (socket, msg) => { ws.trackMessage(); socket.send(`Echo: ${msg}`) }, close: () => ws.trackClose(), drain: () => {}, }, }) }) runtime.bus.subscribe("chat-ws:metrics", ({ connections, messages, errors }) => { console.log(`WS: ${connections} open, ${messages} messages, ${errors} errors`) }) ``` -------------------------------- ### Production Deployment Script Source: https://github.com/nds-stack/bunova/blob/main/README.md Commands for building and running a Bunova application in production. Includes building the project, running with Bun, and enabling debug flags. ```bash # Build bun run build # outputs to dist/ # Run with Bun bun run src/index.ts # Enable flags BUNOVA_DEBUG=1 bun run src/index.ts ``` -------------------------------- ### Initialize and Use SQLite Plugin Source: https://github.com/nds-stack/bunova/blob/main/plugins/sqlite/README.md Initialize the Bunova runtime and use the sqlitePlugin to manage SQLite databases. Listen for metrics emitted by the plugin. ```typescript import { runtime } from "bunova" import { sqlitePlugin } from "@bunova/sqlite" runtime.boot() runtime.use(sqlitePlugin({ path: "./data/app.db", label: "app-db", interval: 5000, // metrics every 5s })) // Listen for metrics runtime.bus.subscribe("app-db:metrics", (payload) => { console.log("SQLite writes:", payload.writes.total) }) ``` -------------------------------- ### Worker Orchestration Source: https://github.com/nds-stack/bunova/blob/main/README.md Spawn and manage workers with options for count, restart behavior, and maximum restarts. Provides methods to list all workers, get pool statistics, and restart or stop specific workers. ```typescript const worker = await runtime.worker.spawn("./jobs/email.ts", { count: 2, restart: true, maxRestarts: 10, // optional, default 10 }) // { id, path, pid, status: "running", startedAt, restarts } runtime.worker.list() // All workers runtime.worker.stats() // Pool statistics runtime.worker.restart("worker-1") // Restart specific worker runtime.worker.stop("worker-1") // Stop specific worker ``` -------------------------------- ### Get Bunova Runtime Statistics Source: https://context7.com/nds-stack/bunova/llms.txt Call `runtime.stats()` to retrieve a snapshot of the runtime's current operational state, including lifecycle, uptime, and feature flags. This can be used for periodic health reporting. ```typescript import { runtime } from "bunova" await runtime.boot({ telemetry: true, discovery: true, watch: true }) const stats = runtime.stats() console.log(stats) // { // state: "running", // uptime: 5432, // startedAt: "2024-01-01T00:00:00.000Z", // workers: 3, // plugins: 1, // telemetry: true, // watchEnabled: true, // discoveryEnabled: true // } // Periodic health reporting setInterval(() => { const s = runtime.stats() runtime.logger?.info("Health", { state: s.state, workers: s.workers, uptime: s.uptime }) }, 30000) ``` -------------------------------- ### Wrap Bun Fetch Handler for Metrics Source: https://github.com/nds-stack/bunova/blob/main/README.md Wrap your Bun.serve fetch handler to track request metrics. This snippet shows how to boot the runtime, wrap the fetch handler, and serve the application. Later, you can check the collected metrics. ```typescript import { serve } from "bun" runtime.boot() const handler = runtime.wrapFetch(async (request) => { return new Response("Hello!") }) serve({ port: 3000, fetch: handler }) // Later: check metrics runtime.metrics.serve() // { totalRequests: 100, avgDurationMs: 12.3, statusCounts: { 200: 95, 404: 5 } } ``` -------------------------------- ### Initialize and Use Redis Plugin with Bunova Source: https://github.com/nds-stack/bunova/blob/main/plugins/redis/README.md Integrate the redisPlugin into the Bunova runtime, configuring the Redis connection URL, a label for identification, and the metrics interval. It also shows how to subscribe to Redis metrics events. ```typescript import { runtime } from "bunova" import { redisPlugin } from "@bunova/redis" runtime.boot() runtime.use(redisPlugin({ url: "redis://localhost:6379", label: "cache", interval: 5000, })) // Listen for metrics runtime.bus.subscribe("cache:metrics", (payload) => { console.log("Redis status:", payload.status) }) ``` -------------------------------- ### Bootstrap Bun Entry Point as Subprocess Source: https://context7.com/nds-stack/bunova/llms.txt The `bootstrap` function runs a Bun entry file as a subprocess, providing auto-restart on non-zero exit codes. Configure restart behavior, delay, max restarts, and environment variables. ```typescript import { bootstrap } from "bunova" // bootstrap.ts — run this as the outer supervisor bootstrap("src/index.ts", { restart: true, restartDelay: 1000, // 1s before restart maxRestarts: 10, env: { NODE_ENV: "production" }, }) // src/index.ts — the actual application import { runtime } from "bunova" await runtime.boot({ signals: true, telemetry: true }) Bun.serve({ port: 3000, fetch: (req) => new Response("OK") }) ``` ```bash # Run the supervisor bun run bootstrap.ts # [Bunova Bootstrap] Max restarts (10) reached. Exiting. ← after 10 crashes ``` -------------------------------- ### bootstrap Source: https://context7.com/nds-stack/bunova/llms.txt A lightweight supervisor that runs a Bun entry file as a subprocess, automatically restarting it upon non-zero exit codes. It's designed for process-level crash recovery. ```APIDOC ## `bootstrap(entryPoint, options?)` A lightweight supervisor that runs a Bun entry file as a subprocess and auto-restarts it on non-zero exit codes. Designed for crash recovery at the process level, complementing the in-process runtime. ```ts import { bootstrap } from "bunova" // bootstrap.ts — run this as the outer supervisor bootstrap("src/index.ts", { restart: true, restartDelay: 1000, // 1s before restart maxRestarts: 10, env: { NODE_ENV: "production" }, }) // src/index.ts — the actual application import { runtime } from "bunova" await runtime.boot({ signals: true, telemetry: true }) Bun.serve({ port: 3000, fetch: (req) => new Response("OK") }) ``` ```bash # Run the supervisor bun run bootstrap.ts # [Bunova Bootstrap] Max restarts (10) reached. Exiting. ← after 10 crashes ``` ``` -------------------------------- ### Initialize and Use Auth Plugin Source: https://github.com/nds-stack/bunova/blob/main/plugins/auth/README.md Initialize the auth plugin with a JWT secret and use it to verify tokens within the Bunova runtime. Ensure the JWT_SECRET environment variable is set. ```typescript import { runtime } from "bunova" import { authPlugin } from "@bunova/auth" const auth = authPlugin({ secret: process.env.JWT_SECRET, }) runtime.use(auth) runtime.on("ready", async () => { const result = await auth.verify("eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiYWRtaW4ifQ.signature") if (result?.valid) { console.log("User:", result.user) } }) ``` -------------------------------- ### Send Event to Worker-Isolated Plugin Source: https://github.com/nds-stack/bunova/blob/main/README.md Communicate with a worker-isolated plugin using `runtime.pluginSend(name, channel, payload?)`. The plugin receives the event via IPC (stdin) and can respond via stdout broadcasts. Ensure the plugin is installed using `runtime.use` with `{ isolate: true }`. ```ts runtime.use("./plugins/redis.ts", { isolate: true }) runtime.pluginSend("redis", "config:reload", { maxConnections: 10 }) // Plugin worker receives via stdin, can respond via stdout broadcast ``` -------------------------------- ### Configure and Use Redis Plugin Source: https://context7.com/nds-stack/bunova/llms.txt Integrate the Redis plugin, configuring the connection URL and monitoring interval. Subscribe to connection, metrics, and error events. ```typescript import { runtime } from "bunova" import { redisPlugin } from "@bunova/redis" runtime.use(redisPlugin({ url: process.env.REDIS_URL ?? "redis://localhost:6379", label: "cache", interval: 5000, })) runtime.bus.subscribe("cache:ready", ({ url }) => console.log(`Redis connected: ${url}`)) runtime.bus.subscribe("cache:metrics", ({ status }) => console.log("Redis status:", status)) runtime.bus.subscribe("cache:error", ({ message }) => console.error("Redis error:", message)) await runtime.boot() ``` -------------------------------- ### Configure and Use Queue Plugin Source: https://context7.com/nds-stack/bunova/llms.txt Set up the queue plugin with specified poll interval and max retries. Enqueue typed jobs and define handlers to process them. Subscribe to job events for monitoring. ```typescript import { runtime } from "bunova" import { queuePlugin } from "@bunova/queue" const queue = queuePlugin({ pollInterval: 1000, maxRetries: 3 }) runtime.use(queue) await runtime.boot() // Enqueue jobs queue.enqueue("email:send", { to: "alice@example.com", template: "welcome" }) queue.enqueue("report:generate", { userId: 42, format: "pdf" }) // Process jobs queue.process(async (job) => { switch (job.type) { case "email:send": await sendEmail(job.payload.to, job.payload.template) break case "report:generate": await generateReport(job.payload.userId, job.payload.format) break } }) // Listen for job events runtime.bus.subscribe("email:send:started", ({ id }) => console.log(`Job ${id} started`)) runtime.bus.subscribe("queue:enqueued", ({ id, type }) => console.log(`Enqueued ${type} [${id}]`)) ``` -------------------------------- ### Initialize and Use Bunova Tracing Plugin Source: https://github.com/nds-stack/bunova/blob/main/plugins/tracing/README.md Initialize the tracing plugin with a service name and optional HTTP endpoint. Spans can be recorded manually or received via the bus. Ensure the endpoint is correctly configured for HTTP export. ```ts import { runtime } from "bunova" import { tracingPlugin } from "@bunova/tracing" const tracing = tracingPlugin({ serviceName: "api-gateway", endpoint: "http://jaeger:4318/v1/traces", // optional HTTP export }) runtime.use(tracing) // Record spans manually tracing.record("db.query", 12.3, { table: "users" }) tracing.record("http.external", 45.1, { url: "https://api.example.com" }) // Or listen for spans via bus runtime.bus.subscribe("tracing:spans", (payload) => { console.log(`Exported ${payload.spans.length} spans from ${payload.service}`) }) ``` -------------------------------- ### Configure and Use Tracing Plugin Source: https://context7.com/nds-stack/bunova/llms.txt Initialize the tracing plugin with a service name and export endpoint. Record spans manually or via runtime.tracer, and subscribe to span export events. ```typescript import { runtime } from "bunova" import { tracingPlugin } from "@bunova/tracing" const tracing = tracingPlugin({ serviceName: "api-gateway", endpoint: "http://jaeger:4318/v1/traces", }) runtime.use(tracing) await runtime.boot() // Record spans manually via the plugin tracing.record("db.query", 12.3, { table: "users" }) tracing.record("http.external", 45.1, { url: "https://payments.example.com" }) // Or use runtime.tracer directly — the plugin collects and batches them const id = runtime.tracer.start("cache.set", undefined, { key: "user:42" }) await cache.set("user:42", userData) runtime.tracer.end(id) // Listen for batched span exports (every 5s) runtime.bus.subscribe("tracing:spans", ({ service, spans }) => { console.log(`Exported ${spans.length} spans from ${service}`) }) ``` -------------------------------- ### Initialize Bunova Runtime Source: https://context7.com/nds-stack/bunova/llms.txt Initializes the Bunova runtime with various configurations for logging, environment validation, telemetry, signals, discovery, and file watching. Must be called once at application entry. ```typescript import { runtime } from "bunova" await runtime.boot({ logger: { level: "info", format: "json" }, env: { schema: { PORT: "port", DB_URL: "url", JWT_SECRET: "string" }, }, telemetry: { memory: true, eventLoop: true, cpu: true, interval: 10000, // snapshot every 10s history: 100, }, signals: true, // auto-handle SIGINT, SIGTERM, uncaughtException discovery: true, // auto-scan src/plugins/, src/workers/, src/routes/ watch: { dirs: ["src", "src/routes"] }, // reload workers on file change plugins: [], // plugins to install at boot }) console.log(runtime.state) // "running" console.log(runtime.uptime) // milliseconds since boot ``` -------------------------------- ### Crash Recovery (Bootstrap) Source: https://github.com/nds-stack/bunova/blob/main/README.md Configure application bootstrap with automatic restart capabilities, including delay and maximum restart counts for resilience. ```APIDOC ## Crash Recovery (Bootstrap) ### Description Configures the application bootstrap process with options for automatic restarts upon crashing. ### Function - `bootstrap(entryPath, options)` ### Parameters - `entryPath` (string): The path to the main application entry file. - `options` (object) - Optional: - `restart` (boolean): Enable or disable automatic restarts. - `restartDelay` (number): The delay in milliseconds before restarting. - `maxRestarts` (number): The maximum number of restart attempts. ### Example ```ts import { bootstrap } from "bunova" bootstrap("src/index.ts", { restart: true, restartDelay: 1000, maxRestarts: 10, }) ``` ```