{"id":"yakoplayz/switch","name":"switch","scope":"yakoplayz","platform":"roblox","description":"Compact, frame-batched fire/invoke networking over reliable and unreliable remotes.","version":"0.1.1","latest":"0.1.1","versions":["0.1.0","0.1.1"],"license":"MIT","licenseRating":"safe","licenseCaveats":["The package archive does not include its license text; the license is declared in its manifest metadata."],"licenseVerified":false,"dependencies":{},"integrity":"f0656a52c40603fc0490f52ad474f8175b26e2b0fb0aafd22fda03e7d226004b","likes":0,"downloads":0,"install":"forest install yakoplayz/switch","url":"https://forest.dev/p/roblox/yakoplayz/switch","files":"https://api.forest.dev/ai/package/roblox/yakoplayz/switch/files","readme":"# Switch\n\nCompact, zero-dependency, frame-batched fire/invoke networking for Roblox over two shared remotes (`RemoteEvent` and `UnreliableRemoteEvent`).\n\nDesigned for high-throughput multiplayer games, **Switch** routes all client-server traffic across `256` numeric channels (`0`–`255`), automatically batches packets per `Heartbeat`, chunks unreliable payloads under Roblox's `900`-byte MTU, inlines `buffer` payloads directly into binary streams, and provides non-blocking, timeout-safe RPCs (`InvokeServer` / `InvokeClient`).\n\n---\n\n## Features\n\n- **Zero Dependencies**: Self-contained single-file module with full `--!strict` Luau types.\n- **Automatic Frame Batching**: Queues outgoing calls and flushes them in a single remote invocation per `Heartbeat`.\n- **Inline Binary Buffers**: Any `buffer` payload (such as serialized [`Sera`](https://wally.run) packets) is packed directly into the binary header stream with zero table wrapper overhead.\n- **Unreliable MTU Protection**: Automatically splits `Switch.Unreliable` batches into `<= 850`-byte chunks so multi-packet frames never exceed Roblox's `~900`-byte unreliable limit.\n- **Safe RPCs (`InvokeServer` / `InvokeClient`)**: Event-backed request/response calls with configurable timeouts, `xpcall` tracebacks, automatic `PlayerDisconnected` cancellation, and explicit error codes (`\"Timeout\"`, `\"HandlerError\"`, `\"UnhandledChannel\"`, `\"PlayerDisconnected\"`).\n- **Pre-Boot Packet Queuing**: Buffers up to `64` early reliable packets per channel on the client until the first listener binds, without replaying stale packets after a disconnect.\n- **Built-In Flood Protection**: Drops incoming client packets exceeding `120` packets/sec per player.\n\n---\n\n## Installation\n\nAdd `Switch` to your `wally.toml`:\n\n```toml\n[dependencies]\nSwitch = \"yakoplayz/switch@0.1.0\"\n```\n\nThen run `wally install`.\n\n---\n\n## Setup & Initialization\n\n1. **Server (`Server/init.server.luau`)**: Require `Switch` on boot so `_SwitchReliable` and `_SwitchUnreliable` are created before any client joins.\n2. **Client (`Client.client.luau`)**: Call `Switch.Connect()` once on startup before binding listeners or booting services. *(Note: `Switch.Connect()` yields until remotes replicate—do not call it inside a non-yielding loader phase).*\n\n```luau\n-- Server\nlocal ReplicatedStorage = game:GetService(\"ReplicatedStorage\")\nlocal Switch = require(ReplicatedStorage.Packages.Switch)\n```\n\n```luau\n-- Client\nlocal ReplicatedStorage = game:GetService(\"ReplicatedStorage\")\nlocal Switch = require(ReplicatedStorage.Packages.Switch)\n\nSwitch.Connect()\n```\n\n---\n\n## Quick Start\n\n### 1. Define Shared Channels (`Channels.luau`)\nKeep channel IDs (`0`–`255`) in a shared `ModuleScript` so server and client never collide or hardcode raw numbers:\n\n```luau\n--!strict\nreturn table.freeze({\n\tChat = 1,\n\tPosition = 2,\n\tGetProfile = 3,\n})\n```\n\n### 2. One-Way Events (`Fire` & `OnFire`)\n\n```luau\n-- Server\nSwitch.OnServerFire(Channels.Chat, function(player: Player, message: unknown)\n\tif typeof(message) ~= \"string\" or #message > 200 then\n\t\treturn\n\tend\n\tSwitch.FireClient(Channels.Chat, \"All\", `{player.Name}: {message}`)\nend)\n\n-- High-frequency unreliable broadcast\nSwitch.FireClient(Channels.Position, \"All\", positionBuffer, Switch.Unreliable)\n```\n\n```luau\n-- Client\nlocal disconnect = Switch.OnClientFire(Channels.Chat, function(formattedMessage: string)\n\tprint(formattedMessage)\nend)\n\nSwitch.FireServer(Channels.Chat, \"Hello world!\")\n\n-- Call disconnect() (or pass to Janitor:Add) when cleaning up\n```\n\n### 3. Request / Response RPCs (`Invoke` & `OnInvoke`)\n\n```luau\n-- Server\nSwitch.OnServerInvoke(Channels.GetProfile, function(player: Player, _payload: unknown)\n\treturn { coins = 250, level = 5 }\nend)\n```\n\n```luau\n-- Client (must run in a thread that is allowed to yield)\nlocal ok, result = Switch.InvokeServer(Channels.GetProfile, nil, 5)\nif ok then\n\tprint(\"Coins:\", result.coins)\nelse\n\twarn(\"Invoke failed:\", result) -- \"Timeout\" | \"HandlerError\" | \"UnhandledChannel\"\nend\n```\n\n---\n\n## API Reference\n\n### Constants\n\n| Property | Value | Description |\n| :--- | :--- | :--- |\n| `Switch.Reliable` | `0` | Sends packets over the reliable `RemoteEvent` (default). |\n| `Switch.Unreliable` | `1` | Sends packets over the `UnreliableRemoteEvent` (faster, no head-of-line blocking, may drop). |\n\n### Lifecycle\n\n#### `Switch.Connect()`\nBinds the client to Switch's remotes and starts per-frame `Heartbeat` flushing. Yields up to `15` seconds if remotes have not replicated yet. No-op on the server.\n\n### Firing Packets\n\n#### `Switch.FireClient(channelId: number, target: Player | \"All\" | { Player }, payload: any, reliability: number?)`\n*(Server-only)* Queues a one-way packet to a single `Player`, an array of `Player`s, or `\"All\"`. Defaults to `Switch.Reliable`.\n\n#### `Switch.FireServer(channelId: number, payload: any, reliability: number?)`\n*(Client-only)* Queues a one-way packet to the server. Defaults to `Switch.Reliable`.\n\n#### `Switch.OnClientFire(channelId: number, callback: (payload: any) -> ()): () -> ()`\n*(Client-only)* Registers a listener for both reliable and unreliable packets on `channelId`. Flushes any buffered pre-boot reliable packets on first bind. Returns a disconnect function.\n\n#### `Switch.OnServerFire(channelId: number, callback: (player: Player, payload: any) -> ()): () -> ()`\n*(Server-only)* Registers a listener for both reliable and unreliable packets on `channelId`. Returns a disconnect function.\n\n### Invoking (RPCs)\n\n#### `Switch.InvokeServer(channelId: number, payload: any, timeoutSeconds: number?, reliability: number?): (boolean, any)`\n*(Client-only, yields)* Invokes the server and returns `(true, result)` or `(false, errorReason)`. Default timeout is `10` seconds.\n\n#### `Switch.InvokeClient(channelId: number, targetPlayer: Player, payload: any, timeoutSeconds: number?, reliability: number?): (boolean, any)`\n*(Server-only, yields)* Invokes a specific client and returns `(true, result)` or `(false, errorReason)`. Automatically resolves with `(false, \"PlayerDisconnected\")` if the player leaves mid-request.\n\n#### `Switch.OnServerInvoke(channelId: number, callback: (player: Player, payload: any) -> any): () -> ()`\n*(Server-only)* Binds the single RPC handler for `channelId` (warns if overwriting an existing handler). Returns a disconnect function.\n\n#### `Switch.OnClientInvoke(channelId: number, callback: (payload: any) -> any): () -> ()`\n*(Client-only)* Binds the single RPC handler for `channelId` (warns if overwriting an existing handler). Returns a disconnect function.\n\n---\n\n## Recommendations & Best Practices\n\n1. **Pair with `Sera` for High-Frequency Data**: Switch is serialization-agnostic. For 30–60 Hz movement, physics, or combat replication, pack your data into a `buffer` using [`Sera`](https://wally.run) before calling `FireClient` / `FireServer`—Switch will inline the `buffer` directly into its binary stream with zero table overhead.\n2. **Validate Every Client Payload**: Switch validates packet headers and rate limits incoming packets, but **never trusts payload contents**. Always validate types, buffer lengths, `NaN` values (`x ~= x`), and ranges inside `OnServerFire` and `OnServerInvoke`.\n3. **Keep Unreliable Payloads Small**: Multi-packet batches on `Switch.Unreliable` are automatically split under `850` bytes, but an individual payload larger than `~850` bytes will be dropped by Roblox's `UnreliableRemoteEvent`. Use `Switch.Reliable` for large or critical payloads.\n4. **Use Reliable Invokes by Default**: Leave the `reliability` argument omitted (`Switch.Reliable`) on `InvokeServer` / `InvokeClient` unless you specifically want dropped requests/replies to fail with `\"Timeout\"`.\n\n---\n\n## License\n\nMIT\n","readmeTruncated":false}