Plugin System
Extend PaindaProtocol with custom plugins. Plugins get full access to lifecycle hooks and can expose public APIs for other plugins.
Creating a Plugin
import type { PPPlugin } from "@painda/core";
const myPlugin: PPPlugin<{ debug: boolean }> = {
name: "my-plugin",
version: "1.0.0",
dependencies: [], // Other plugins required
install(ctx, options) {
// Register middleware
ctx.use((socket, next) => {
if (options?.debug) ctx.log("New connection:", socket.id);
next();
});
// Expose API for other plugins
ctx.expose({
getStats: () => ({ clients: ctx.getClientCount() }),
});
// Return lifecycle hooks
return {
onConnect: (socket) => { /* ... */ },
onDisconnect: (socket) => { /* ... */ },
onMessage: (socket, msg) => {
// Return false to block the message
if (msg.type === "banned") return false;
},
onSend: (socket, msg) => {
// Transform outgoing messages
return { ...msg, payload: { ...msg.payload, ts: Date.now() } };
},
onShutdown: () => { /* cleanup */ },
};
},
};
server.register(myPlugin, { debug: true });Lifecycle Hooks
| Hook | When |
|---|---|
| onConnect | After middleware, before handlers |
| onDisconnect | Client disconnected |
| onMessage | Every incoming message (return false to block) |
| onSend | Before encoding outgoing message |
| onRoomJoin / onRoomLeave | Room membership changes |
| onShutdown | Server is shutting down |
| onError | Server errors |
Next: Typed Rooms