Repository navigation
Architecture
M3rcena edited this page Nov 1, 2026
·
3 revisions
This document details the internal design, session lifecycle, WebSocket protocol, and database storage adapters of @m3rcena/bridge.
@m3rcena/bridge operates as a central gateway connecting Discord bot processes to web dashboards, REST APIs, and external microservices.
┌─────────────────────────────────────────────────────────────┐
│ Discord Bot Server │
│ ┌───────────────────────┐ ┌───────────────────────┐ │
│ │ @m3rcena/weky │ │ @m3rcena/eco │ │
│ └───────────┬───────────┘ └───────────┬───────────┘ │
│ │ bridge.use() │ bridge.use() │
│ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ M3rcenaBridge │ │
│ │ • Action Router • Presence Scope • Storage │ │
│ └────────────────────────────┬────────────────────────────┘ │
│ │ │
│ ┌────────────────────────────▼────────────────────────────┐ │
│ │ BridgeServer │ │
│ │ HTTP REST Endpoints | WebSocket Gateway │ │
│ └────────────────────────────┬────────────────────────────┘ │
└──────────────────────────────┼──────────────────────────────┘
│
WebSocket / REST Traffic
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Web Dashboard (Browser) │
│ React / Next.js / Vue / Svelte │
│ @m3rcena/bridge/client │
└─────────────────────────────────────────────────────────────┘
import { M3rcenaBridge } from "@m3rcena/bridge";
const bridge = new M3rcenaBridge({
database: "sqlite",
autoCleanEndedSessions: false,
sessionTimeoutMs: 30 * 60 * 1000,
requireOnlinePresenceForAudio: false,
notifyUpdates: true,
});| Option | Type | Default | Description |
|---|---|---|---|
database |
BridgeDatabaseConfig |
"memory" |
Database storage mode: "sqlite", "prisma", "json", or configuration object. |
storage |
BridgeStorageAdapter |
MemoryStorageAdapter |
Custom storage adapter instance. |
autoCleanEndedSessions |
boolean |
false |
Automatically purge ended sessions (isEnded: true) from storage. |
sessionTimeoutMs |
number |
1800000 (30m) |
Inactivity period before sessions are expired. |
requireOnlinePresenceForAudio |
boolean |
false |
Dispatches audio cues only to users who are online on the dashboard. |
notifyUpdates |
boolean |
true |
Log styled terminal update notification box on startup. |
@m3rcena/bridge supports in-memory, native SQLite, Prisma ORM, and JSON storage:
export type BridgeDatabaseConfig =
| "sqlite"
| "memory"
| "json"
| { type: "sqlite"; path?: string }
| { type: "prisma"; client: any; model?: string; autoMigrate?: boolean }
| { type: "json"; path?: string }
| { type: "memory" };Node.js 22+ native SQLite engine with WAL mode and indexing:
import { M3rcenaBridge } from "@m3rcena/bridge";
const bridge = new M3rcenaBridge({
database: "sqlite", // Automatically initializes ./bridge.sqlite
// Or with custom path:
database: {
type: "sqlite",
path: "./data/bridge.sqlite",
},
});Pass your existing PrismaClient instance. If your database hasn't compiled models yet, @m3rcena/bridge automatically creates the tables and executes queries seamlessly:
import { PrismaClient } from "@prisma/client";
import { M3rcenaBridge, applyPrismaBridgeModel } from "@m3rcena/bridge";
const prisma = new PrismaClient();
// Optional: Programmatically append Bridge models to schema.prisma
applyPrismaBridgeModel();
const bridge = new M3rcenaBridge({
database: {
type: "prisma",
client: prisma,
autoMigrate: true, // Auto-creates tables if missing
},
});If you prefer to manage database schemas manually or with npx prisma migrate dev, use the schema snippet below:
model BridgeSession {
id String @id
module String?
state String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model BridgeKeyValue {
key String @id
value String
updatedAt DateTime @updatedAt
}CREATE TABLE IF NOT EXISTS "BridgeSession" (
"id" VARCHAR(191) PRIMARY KEY,
"module" VARCHAR(191),
"state" TEXT NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS "BridgeKeyValue" (
"key" VARCHAR(191) PRIMARY KEY,
"value" TEXT NOT NULL,
"updatedAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_bridge_sessions_module ON "BridgeSession" ("module");CREATE TABLE IF NOT EXISTS `BridgeSession` (
`id` VARCHAR(191) PRIMARY KEY,
`module` VARCHAR(191),
`state` LONGTEXT NOT NULL,
`createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_bridge_sessions_module (`module`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `BridgeKeyValue` (
`key` VARCHAR(191) PRIMARY KEY,
`value` LONGTEXT NOT NULL,
`updatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;CREATE TABLE IF NOT EXISTS bridge_sessions (
id TEXT PRIMARY KEY,
module TEXT,
state TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS bridge_data (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_bridge_sessions_module ON bridge_sessions (module);import { M3rcenaBridge } from "@m3rcena/bridge";
const bridge = new M3rcenaBridge({
database: "json", // Defaults to ./bridge-data.json
// Or:
database: {
type: "json",
path: "./data/bridge.json",
},
});Implement BridgeStorageAdapter for Redis or MongoDB:
import { BridgeStorageAdapter, BridgeSession } from "@m3rcena/bridge";
export class RedisBridgeStorage implements BridgeStorageAdapter {
constructor(private redis: any) {}
async getSession(id: string): Promise<BridgeSession | null> {
const raw = await this.redis.get(`bridge:session:${id}`);
return raw ? JSON.parse(raw) : null;
}
async saveSession(session: BridgeSession): Promise<void> {
await this.redis.set(`bridge:session:${session.id}`, JSON.stringify(session), "EX", 3600);
}
async removeSession(id: string): Promise<void> {
await this.redis.del(`bridge:session:${id}`);
}
async getAllSessions(): Promise<BridgeSession[]> {
return [];
}
async saveData(key: string, value: any): Promise<void> {
await this.redis.set(`bridge:kv:${key}`, JSON.stringify(value));
}
async getData(key: string): Promise<any> {
const raw = await this.redis.get(`bridge:kv:${key}`);
return raw ? JSON.parse(raw) : null;
}
}
Built with ❤️ by M3rcena Development • @m3rcena/bridge v14.28.1 • Licensed under Apache-2.0
GitHub: M3rcena/m3rcena-bridge • NPM: @m3rcena/bridge
GitHub: M3rcena/m3rcena-bridge • NPM: @m3rcena/bridge
- Connecting @m3rcena/weky
- Connecting @m3rcena/eco
- Mounting Custom Routers
- Universal Mounting Standard
- Standalone HTTP & WebSocket Server
- Attaching to Express / Fastify / Next.js
- Complete REST API Route Reference
- Real-Time WebSocket Frame Specification
- Browser & Node Client
- React Hooks & useBridgeSession
- Handling Audio Cues & Haptics
- Sending Inbound Moves