{"id":"endarke/unite","name":"unite","scope":"endarke","platform":"roblox","description":"Unite is a light-weight efficient framework that grants opportunity for customizability.","version":"2.0.0","latest":"2.0.0","versions":["0.1.0","0.1.1","0.2.0","0.3.0","0.3.1","0.3.2","1.0.0-rc-1","1.0.0-s","1.0.0","1.1.0","1.2.0-s","1.2.0","1.3.0","1.4.0","2.0.0-rc.1","2.0.0-rc.2","2.0.0"],"license":"MPL-2.0","licenseRating":"caution","licenseCaveats":["File-level copyleft: if you modify this package's own source files, those modified files must be made available under MPL-2.0. Using it unmodified in a closed-source game is fine."],"licenseVerified":true,"dependencies":{},"integrity":"1c7be8ad9e2c967556ee201081b2fe8e226826863917cb03c76f928b2a4f16d7","likes":0,"downloads":0,"install":"forest install endarke/unite","url":"https://forest.dev/p/roblox/endarke/unite","files":"https://api.forest.dev/ai/package/roblox/endarke/unite/files","readme":"# Unite\n\nA lightweight Roblox framework: server **systems**, client **handlers**, and buffer-based networking built in. No dependencies.\n\n```toml\n[dependencies]\nUnite = \"endarke/unite@2.0.0\"\n```\n\n## Systems and handlers\n\n```luau\n-- Server: src/Server/Systems/CombatSystem.luau\nlocal CombatSystem = Unite.createSystem {\n    name = 'CombatSystem',\n    network = {\n        -- Packets\n        hit = Unite.createPacket(Unite.struct {\n            target = Unite.inst,\n            damage = Unite.uint16\n        }),\n        aim = Unite.createUnreliablePacket(Unite.vec3),\n        ready = Unite.createPacket(),\n\n        -- Queries\n        getStats = Unite.createQuery(Unite.nothing, Unite.struct {\n            level = Unite.uint8,\n            title = Unite.string\n        }),\n    },\n}\n\nfunction CombatSystem:start(): ()\n    -- Listeners\n    self.network.ready.listen(function(_, player: Player): ()\n        self.network.hit.sendTo({\n            target = workspace.Dummy,\n            damage = 10\n        }, player)\n    end)\n\n    self.network.getStats.listen(function(_, player: Player): any\n        return {\n            level = 5,\n            title = player.Name\n        }\n    end)\nend\n\nreturn CombatSystem\n```\n\n```luau\n-- Client: src/Client/Handlers/CombatHandler.luau\nlocal CombatHandler = Unite.createHandler {\n    name = 'CombatHandler',\n}\n\nfunction CombatHandler:init(): ()\n    -- Network & Queries\n    self._combatNetwork = Unite.network.CombatSystem\nend\n\nfunction CombatHandler:start(): ()\n    -- Listeners\n    self._combatNetwork.hit.listen(function(data): ()\n        print(data.target, data.damage)\n    end)\n\n    self._combatNetwork.ready.send()\n\n    local stats = self._combatNetwork.getStats.invoke()\nend\n\nreturn CombatHandler\n```\n\nBoot each side once: `Unite.start(script.Systems, true)` / `Unite.start(script.Handlers, true)` (`true` also loads subfolders).\n\n- `init()` runs for every system first (they may yield; Unite waits), then every `start()` is spawned. `Unite.start` returns once the `start()`s are running, so a `start()` with a `while true do` loop is fine. `Unite.awaitStart()` waits for that point from anywhere.\n- A module that fails to load, or an `init()` that errors, is reported with its path; the rest keep loading. A system whose `init()` errored doesn't get `start()`.\n- `Unite.getSystem(name)` / `Unite.getHandler(name)` work from `init()` onward and error (with a suggestion) for unknown names.\n\n## Players\n\n```luau\nfunction DataSystem:start(): ()\n    Unite.playerAdded(function(player: Player): ()\n        self.load(player)\n    end)\n\n    Unite.playerRemoving(function(player: Player): ()\n        self.save(player)\n    end)\nend\n```\n\n`Unite.playerAdded` runs once for every player already in the game and every player who joins later; `Unite.playerRemoving` runs for every player who leaves (only ones `playerAdded` saw). Each callback runs in its own thread, so it can yield, and errors are reported without stopping the others. Both return a disconnect function and work on either side.\n\n## Getting a network on the client\n\n| | |\n|---|---|\n| `Unite.network.CombatSystem` | Never yields. Works anywhere in handler modules (even at the top), because `Unite.start` waits for the server's networks before loading handlers. |\n| `Unite.connectSystemNetwork('CombatSystem')` | Waits for the network to arrive (up to `networkTimeout`). |\n\nOn the server, `Unite.network.CombatSystem` returns any system's network.\n\n## Packets\n\n| Server | Client | Both |\n|---|---|---|\n| `sendTo(data, player)` | `send(data)` | `listen(fn)` → disconnect function |\n| `sendToAll(data)` | | `listenOnce(fn)` → disconnect function |\n| `sendToList(data, players)` | | `wait()` → `data, player` |\n| `sendToAllExcept(data, player or players)` | | `disconnectAll()` |\n\n- Reliable packets keep their order per player, even when `sendTo` and `sendToAll` are mixed in a frame.\n- Messages that arrive before anything listens are kept (up to 256) and delivered to the first listener.\n- `Unite.createUnreliablePacket` sends over an `UnreliableRemoteEvent`. Batches are split to stay under Roblox's 1000 byte limit; a single message that can never fit is dropped with a one-time warning.\n- `Unite.createPacket()` with no data type is a signal with no data.\n- `Unite.createPacket(type, { rateLimit = 10 })` caps how many times a second each player can send it; extra messages are dropped and reported through `onViolation`. Works on queries too (`createQuery(request, response, { rateLimit = 2 })`).\n- Methods work with `.` or `:`.\n\n## Queries\n\n`query.listen(function(request, player) return response end)` on the server; `query.invoke(request)` on the client. `invoke` raises a descriptive error if the handler errors, returns an invalid response, or nothing answers within `queryTimeout`.\n\n## States\n\nA state is a value the server owns and clients mirror. Only the fields that changed are sent.\n\n```luau\nroundState = Unite.createState(Unite.struct {\n    phase = RacePhase,\n    round = Unite.uint16,\n    leader = Unite.optional(Unite.string)\n}),\n```\n\n| Server | Client |\n|---|---|\n| `set(value, player?)` replaces the value | `get()` → current value (frozen) or `nil` |\n| `patch(changes, player?)` changes some fields | `observe(fn)` → runs now with the current value, then on every change |\n| `get(player?)` → what you set | `listen(fn(value, previous))` on change |\n\nWithout a player, the state is shared by everyone and players who join later get the current value automatically. With a player, each player has their own. Setting the same value again sends nothing. Use `set` to clear an optional field (a `nil` in a `patch` table is just a missing key).\n\n## Shared networks\n\nTo get types on the client, define a network in a shared module both sides require:\n\n```luau\nreturn Unite.defineNetwork('Chat', {\n    message = Unite.createPacket(Unite.struct {\n        text = Unite.string,\n        channel = Unite.optional(Unite.string)\n    }),\n})\n```\n\nThe server publishes it; the client checks its definition against the server's and errors with both layouts if they don't match.\n\n## Cross-server signals\n\n```luau\nlocal Announcement = Unite.createCrossServerSignal('announcement', Unite.struct {\n    text = Unite.string\n})\n\nAnnouncement.listen(function(data, sender): ()\n    print(data.text, sender.jobId)\nend)\n\nAnnouncement.send({\n    text = 'Hello'\n})\n```\n\n`send` reaches every other server, `sendToAll` every server including this one, and `sendTo(data, jobId)` one server.\n\nLeave out the data type to send any JSON-friendly value. All signals share one MessagingService subscription, messages sent close together go out as one compressed publish, and a server running a different data type for the same signal ignores the message instead of misreading it. In Studio, signals only reach the current server unless `crossServerInStudio` is on.\n\n### Cross-server queries\n\n```luau\nlocal FindPlayer = Unite.createCrossServerQuery('findPlayer', Unite.float64, Unite.string)\n\nFindPlayer.listen(function(userId: number): string?\n    if not Players:GetPlayerByUserId(userId) then return end\n\n    return Unite.getServerId()\nend)\n\nlocal jobId = FindPlayer.invoke(userId)\n```\n\n| | |\n|---|---|\n| `invoke(request)` | First answer from any server (including this one), or `nil` after `crossServerTimeout`. Handlers that return `nil` stay quiet. |\n| `invoke(request, jobId)` | Ask one server; errors if it doesn't answer. |\n| `invokeAll(request)` | Every answer that arrives within `crossServerTimeout`, as `{ { jobId, response } }`. |\n\n## Data types\n\n`bool`, `uint8`, `uint16`, `uint32`, `int8`, `int16`, `int32`, `float32`, `float64`, `string`, `buff`, `vec2`, `vec3`, `color3`, `cframe`, `inst`, `unknown`, `nothing`, and `struct { }`, `array(t)`, `map(k, v)`, `optional(t)`.\n\nStrings, buffers, arrays and maps have no 65535 limit. `inst` and `unknown` travel next to the buffer (any number per frame). `color3` is 1 byte per channel, clamped to 0–1.\n\n### Compact types\n\n| Type | Bytes | Precision |\n|---|---|---|\n| `float16` | 2 | about 3 significant digits, up to ±65504 |\n| `vec2f16` / `vec3f16` | 4 / 6 | same per axis; for velocities, directions, offsets |\n| `angle` | 2 | 0.0001 radians, read back in -π to π |\n| `cframeCompact` | 18 (vs 24) | exact float32 position, rotation within 0.0002 |\n\n### Enums\n\n```luau\n-- ReplicatedStorage/Shared/Enums/RacePhase.luau\nreturn Unite.enum('RacePhase', {\n    'lobby',\n    'countdown',\n    'racing',\n    'results'\n})\n```\n\nAn enum value is 1 byte (2 past 256 values) instead of a whole string. Use it as a data type (`phase = RacePhase`) and as a typo-safe set of names: `RacePhase.racing == 'racing'`, while `RacePhase.racng` errors with a suggestion. Add a value by adding a line; since clients read the layout from the server, order changes can't desync them. Every enum is also in `Unite.enums.RacePhase`, including on the client, which gets the server's enums through the networks that use them. `Unite.enum(Enum.Material)` sends any Roblox enum in 1–3 bytes.\n\n## Configuration\n\n`Unite.configure { ... }`, on either side:\n\n| Option | Default | |\n|---|---|---|\n| `validate` | Studio only | Check outgoing data before sending for exact error paths (`data.target.position should be a Vector3, got nil`). Failed sends are always explained, even when off. |\n| `queryTimeout` | `10` | Seconds a client waits for a query answer. |\n| `networkTimeout` | `10` | Seconds `connectSystemNetwork` waits for a network. |\n| `incomingBytesPerSecond` / `incomingBurstBytes` | `32768` / `65536` | Per-player byte limit on what the server accepts. |\n| `incomingMessagesPerSecond` / `incomingBurstMessages` | `1000` / `2000` | Per-player message limit, so floods of tiny messages can't run listeners thousands of times. |\n| `maxPendingQueries` | `32` | Queries one player can have waiting at once. |\n| `rejectNonFinite` | `true` | Server drops client data containing NaN or infinite numbers. |\n| `exposeServerErrors` | Studio only | Send query handler error text to the client. |\n| `crossServerInStudio` | `false` | Let Studio use MessagingService. |\n| `crossServerTimeout` | `5` | Seconds cross-server queries wait for answers. |\n| `stats` | `false` | Count messages and bytes per endpoint (see below). |\n| `onViolation` | none | `function(player, reason)` for bad or excessive client data. |\n\n## Stats\n\nWith `stats` on, `Unite.getStats()` returns `{ seconds, endpoints = { ['CombatSystem.hit'] = { sent, sentBytes, received, receivedBytes } } }` since the last `Unite.clearStats()`. Bytes are the serialized size per call. When off, it costs one check per message.\n\n## What the server protects against\n\nClients can send anything, so the server treats every byte as hostile:\n\n- Wrong types, oversized lengths and truncated data are rejected before anything is allocated. The batch is dropped, the player is reported (rate-limited in the output), and the server keeps running.\n- A batch can't make the server do unbounded work: lengths are checked against the bytes that arrived, empty items are capped per batch, and both bytes and messages per second are limited per player.\n- NaN and infinite numbers are rejected (`rejectNonFinite`), so they can't reach parts or physics.\n- Listener and handler errors run in their own threads and are printed at most once a second per endpoint, so an exploiter can't lag the server through the output.\n- Queries are capped per player (`maxPendingQueries`) and endpoints can have their own `rateLimit`.\n\nKick or flag players from `onViolation`. Networking that can't be crashed removes the usual trigger for duplication exploits, but trades should still be safe at the data layer: save or lock both sides before granting items (session locking, as ProfileStore does).\n\n## Editor support\n\nWith [Luau Language Server](https://marketplace.visualstudio.com/items?itemName=JohnnyMorganz.luau-lsp), the whole Unite API autocompletes and is typed, including a system's own network (`CombatSystem.network.hit.sendTo(data: { damage: number, target: Instance }, player)`) and `self` inside `init`/`start`.\n\nNetworks looked up by name on the client (`Unite.network.X`, `connectSystemNetwork('X')`), systems from `getSystem`, and enum values can't be typed statically. The **Unite Tools** VS Code extension in [`extension/`](extension/README.md) fills that in by reading your workspace: completions, hovers, go to definition, typo warnings and snippets.\n\n## Upgrading from 1.x\n\n- ByteNet-Max is no longer a dependency; the packet API (`sendTo(data, player)`, `listen`, `invoke`, ...) is unchanged.\n- `Unite.start` no longer waits for `start()` methods to finish.\n- `Unite.getSystem` / `getHandler` error on unknown names instead of returning `nil`.\n- `connectSystemNetwork` no longer requires `Unite.start` to have run.\n","readmeTruncated":false}