# Network bundles

> Program the Velocity proxy in front of your Minecraft servers in TypeScript and Effect - /lobby, kick fallback and routing - swapped on save while players stay connected, on a local dev network.

A network bundle is the proxy's behavior: where players land, `/lobby`, what happens when a server kicks them, routing between servers. It is TypeScript and Effect UI in `network/`, running inside Velocity, and it is built like a game: rules without the proxy, a proxy half that calls Velocity's own API, and Stories and replays as tests. Saving swaps it while everyone stays connected.

## Create a network project

```sh
mk init my-network --network
```

`--network` creates a lobby network: `/lobby` (and `/hub`) sends players to the lobby, and a kick from another server sends them back to it with an explanation. `--game --network` creates both halves in one project.

| Path | Holds |
| --- | --- |
| `network/Lobby.ts` | The rules: `Component.define(...).logic(...)` and the Command declarations. No Java. |
| `network/velocity.ts` | The proxy half: Velocity events and commands to messages, Command implementations, `export default Network.make(...)` |
| `network/Lobby.test.ts` | Stories and replays |
| `recordings/network/*.ndjson` | Real sessions from the proxy, replayed by the tests |

## Run the dev network

A network bundle runs on the dev network: a relay, a Velocity proxy and two Paper servers on your machine. Start it with `mk server --network --accept-eula`, then run `mk dev .` in the project. [Run the dev network](https://minekube.com/games/local-development/dev-network) explains each part and its port.

## The rules

The rules know nothing about Velocity. A player is their UUID in its generated data form, and a server is its name.

```ts title="network/Lobby.ts"

// The network's rules, with no proxy in sight: this module imports no Java, so its tests run in Bun.
// Players are what Velocity identifies them by, `Player.getUniqueId()`, in its generated data form.
const PlayerId = Schemas["java.util.UUID"];

export const LobbyMessage = UiSchema.TaggedEnum({
  /** A player ran `/lobby` while on `from` (null between servers). */
  AskedForLobby: { player: PlayerId, from: Schema.NullOr(Schema.String) },
  /** A backend kicked a player who was playing on it; the proxy sends them to the lobby. */
  Kicked: { player: PlayerId, from: Schema.String, reason: Schema.String },
  /** How a connection to `server` ended. */
  Connected: { player: PlayerId, server: Schema.String, ok: Schema.Boolean },
});

/** Moves a player to `server`. */
export class Connect extends Command.Service<Connect>()("network/Connect", {
  args: { player: PlayerId, server: Schema.String },
  success: LobbyMessage,
}) {}

/** Shows a player a line in chat. */
export class Tell extends Command.Service<Tell>()("network/Tell", { args: { player: PlayerId, text: Schema.String } }) {}

export const Lobby = Component.define({
  name: "Lobby",
  model: Schema.Struct({
    /** The server players fall back to: `/lobby` and every kick lead there. */
    lobby: Schema.String,
  }),
  message: LobbyMessage,
}).logic({
  init: ($) => $.set({ lobby: "lobby" }),
  update: {
    AskedForLobby: ($, { player, from }) =>
      from === $.model.lobby
        ? $.run(Tell.make({ player, text: "You are already in the lobby." }))
        : $.run(Tell.make({ player, text: "Sending you to the lobby." }), Connect.make({ player, server: $.model.lobby })),
    Kicked: ($, { player, from, reason }) => $.run(Tell.make({ player, text: `${from} kicked you (${reason}). You are back in the lobby.` })),
    Connected: ($, { player, server, ok }) => ok ? $.model : $.run(Tell.make({ player, text: `${server} is not reachable right now.` })),
  },
});
```

## The proxy half

`Network.component(logic).make({ subscriptions, view })` mounts the rules on the proxy, as `Minecraft.component` does on a Paper server; `Network.mount(...)` and `Network.make(...)` make it the bundle. Each Command is a layer that calls Velocity's API through the `Velocity` service: `{ proxy, plugin, host }`. Classes are typed from the Velocity API jar (`@minekube/velocity`), and values such as UUIDs go through `@minekube/velocity/schemas`.

```ts title="network/velocity.ts"

// The proxy half: Velocity's events and commands become Lobby messages, and the Lobby's Commands call Velocity.
// `mk dev .` installs this on the dev network's proxy (`mk server --network`) and swaps it on every save.
const Component = Java.type("net.kyori.adventure.text.Component");
const NamedTextColor = Java.type("net.kyori.adventure.text.format.NamedTextColor");
const PlainText = Java.type("net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer");
const Player = Java.type("com.velocitypowered.api.proxy.Player");
const RedirectPlayer = Java.type("com.velocitypowered.api.event.player.KickedFromServerEvent$RedirectPlayer");

const uuid = (player: com.velocitypowered.api.proxy.Player) => fromJava("java.util.UUID", player.getUniqueId());

const LobbyNetwork = Network.component(Lobby).make({
  subscriptions: ($) => [
    Network.command("lobby", (context) => {
      const source = context.getSource();
      if (!(source instanceof Player)) return undefined;
      const current = source.getCurrentServer();
      return LobbyMessage.AskedForLobby({ player: uuid(source), from: current.isPresent() ? current.get().getServerInfo().getName() : null });
    }, { aliases: ["hub"] }),
    Network.event("com.velocitypowered.api.event.player.KickedFromServerEvent", (event) => {
      const from = event.getServer().getServerInfo().getName();
      // A kick while joining leaves the player where they were, and one from the lobby itself is Velocity's to handle.
      if (event.kickedDuringServerConnect() || from === $.model.lobby) return undefined;
      const reason = event.getServerKickReason();
      return LobbyMessage.Kicked({
        player: uuid(event.getPlayer()),
        from,
        reason: reason.isPresent() ? PlainText.plainText().serialize(reason.get()) : "no reason given",
      });
    }, {
      // The event's result: where Velocity sends the player. An empty message, because `Kicked` tells them.
      result: (event, { proxy }) => {
        const lobby = proxy.getServer($.model.lobby);
        return lobby.isPresent() ? RedirectPlayer.create(lobby.get(), Component.empty()) : event.getResult();
      },
    }),
  ],
  view: () => View.text(""),
});

const Commands = Layer.mergeAll(
  Tell.toLayer(Effect.gen(function* () {
    const { proxy } = yield* Velocity;
    return ({ player, text }) =>
      Effect.sync(() => {
        const target = proxy.getPlayer(toJava("java.util.UUID", player));
        if (target.isPresent()) target.get().sendMessage(Component.text(text, NamedTextColor.GOLD));
      });
  })),
  Connect.toLayer(Effect.gen(function* () {
    const { proxy } = yield* Velocity;
    return ({ player, server }) =>
      Effect.gen(function* () {
        const target = proxy.getPlayer(toJava("java.util.UUID", player));
        const registered = proxy.getServer(server);
        if (!target.isPresent() || !registered.isPresent()) return LobbyMessage.Connected({ player, server, ok: false });
        const result = yield* Network.future(target.get().createConnectionRequest(registered.get()).connect());
        return LobbyMessage.Connected({ player, server, ok: result.isSuccessful() });
      }).pipe(Effect.orElseSucceed(() => LobbyMessage.Connected({ player, server, ok: false })));
  })),
);

export default Network.make(Network.mount(LobbyNetwork, {}).pipe(Effect.provide(Commands)));
```

### Commands and events

- **`Network.command(name, (context) => message, { aliases })`** registers `/<name>` while the subscription lives. `context.getSource()` is the player or the console; return `undefined` to ignore a run. The command is gone when the revision stops.
- **`Network.event(eventClass, (event) => message, { result, order })`** turns a Velocity event into a message. Velocity waits while `toMessage` runs and the message is handled, so `result: (event, velocity) => ...` can decide the event: it returns what the event's `setResult` takes. For `KickedFromServerEvent`, `RedirectPlayer.create(server, Component.empty())` sends the player there, with an empty component because your own `Tell` explains it. `result` runs only when `toMessage` returned a message.
- **`Network.on(eventClass, handler)`, `Network.register(meta, command)`** (any command kind) **and `Network.channel(identifier)`** are the Effect forms for code outside a component. All of them end with the revision.
- **`Network.future(completableFuture)`** waits for a future that Velocity completes on its own threads, such as `player.createConnectionRequest(server).connect()`. Its failure is the Java exception.

### Threads

Velocity has no main thread; the runtime gives bundles one, `Minekube Bundles`. Your handlers, your commands and the JS functions you hand to Velocity (a `buildTask` runnable, a `thenAccept` callback, a Brigadier node) all run there. Without a result they are queued; with one, Velocity's thread waits up to a second. JS never runs in parallel, so keep handlers short.

Where a method has overloads for several interfaces, such as `Scheduler.buildTask(plugin, Runnable)` and `(plugin, Consumer)`, name the overload: `scheduler["buildTask(java.lang.Object,java.lang.Runnable)"](plugin, () => ...)`.

## Tests and recordings

`network/Lobby.test.ts` tests the rules with Stories, exactly like a game's [tests](https://minekube.com/games/testing/):

```ts title="network/Lobby.test.ts"

const PlayerId = Schemas["java.util.UUID"];
const alex = PlayerId.make("b2fd8387-c4d5-3f70-bdad-86ce5faea46a");

describe("Lobby rules", () => {
  test("/lobby from another server sends the player to the lobby", () => {
    Story.start(Lobby, {})
      .send(LobbyMessage.AskedForLobby({ player: alex, from: "arena" }))
      .expectExact(Tell.make({ player: alex, text: "Sending you to the lobby." }), Connect.make({ player: alex, server: "lobby" }));
  });

  test("/lobby in the lobby only says so", () => {
    Story.start(Lobby, {})
      .send(LobbyMessage.AskedForLobby({ player: alex, from: "lobby" }))
      .expectExact(Tell.make({ player: alex, text: "You are already in the lobby." }));
  });
});
```

The proxy records every revision in its `plugins/minekube/recordings/<bundle>/`. Copy a recording into `recordings/network/`, and `bun test` replays it through your current rules with `decodeRecording` from `@minekube/network/testing`.

## Rules for a network bundle

- **Velocity's API as it is**, like Paper's in a game. No wrappers.
- **No plugin code.** A network feature is a bundle. If Velocity's API cannot do it from TypeScript, report the missing capability to Minekube.
- **The rules import no Java.** `network/velocity.ts` is the only file that touches Velocity.
