# Paper from TypeScript

> Call Paper's real API from a Minekube game - typed classes from the server jars, null and numbers at the Java boundary, checked exceptions with Jvm, generated Schemas, threads and timers.

Your game sees the server's public JVM through GraalJS, typed by `@minekube/paper-types`. No package ships these types: `mk types` (and `mk dev .` first) generates them from the Paper, Adventure, Brigadier and JOML jars of exactly the [Paper version](https://minekube.com/games/concepts/platform-version) your `vite.config.ts` names, into your project's `types/paper`. Never edit them. Read the types instead of guessing: `types/paper/paper.d.ts` has every class with Paper's own names, overloads, nullability and `@deprecated` marks.

There is no wrapper in between. If something cannot be done through the server's API from TypeScript, it is a missing capability of the runtime: report it to Minekube instead of working around it.

## Classes

- `Java.type("org.bukkit.Material")` returns the class: static fields and methods, enum constants, and `new` for constructors. Nested classes use `$`: `Java.type("org.bukkit.Particle$DustOptions")`. The name is checked against `JavaClasses`.
- Instances are typed by namespace: `org.bukkit.entity.Player`, `org.bukkit.World`. Use these in your signatures.
- `value instanceof Sign` narrows, with `const Sign = Java.type("org.bukkit.block.Sign")`.
- Getters are methods: `player.getName()`, never `player.name`.
- Compare enum constants with `===`: `event.getAction() === Action.RIGHT_CLICK_BLOCK`.
- Parameter names come out as `arg0`, `arg1` when the API jar has none. The JDK classes have real names.

## Values crossing the boundary

- **Null:** methods annotated `@Nullable` return `T | null`. Check for `null`, not `undefined`.
- **Numbers:** a JS number goes into `int`, `long` and `double` parameters when the value fits; `1.5` into an `int` throws. The runtime also converts numbers to `float`, so `new DustOptions(color, 1.4)` works.
- **Strings:** JS strings pass as `String` and `CharSequence`.
- **Functions:** a JS function passes where Java expects a functional interface, such as `Consumer`, `Runnable` or `Predicate`.
- **Collections:** a `java.util.List` indexes like an array (`list[0]`, `list.length`) and iterates with `for…of`. `Java.from(collection)` copies into a JS array; `Java.to(array, "java.lang.String[]")` copies out.
- **Varargs:** pass the values one by one.

## Exceptions and resources: `Jvm`

The types mark what a Java call obliges you to handle, and only `Jvm` from `@minekube/paper` lets you make such a call:

- A method that declares checked exceptions (most of `java.nio.file.Files`, `BufferedReader.readLine`) takes `this: Guarded`. Calling it directly does not compile, even as a statement. `Jvm.attempt(receiver, (guarded) => guarded.method(...))` returns an `Effect` whose failure is the Java exception itself, typed from the declaration.
- A call that hands you something to close (`Files.newBufferedReader`, `Files.lines`, `new FileInputStream(...)`) returns `Resource<A>`. `Jvm.acquire(receiver, (guarded) => ...)` opens it and closes it when the Effect's Scope closes. In a game, that is at the latest when the revision stops.
- The receiver is the object, or the class from `Java.type` for static methods and constructors.

```ts

const Files = Java.type("java.nio.file.Files");
const FileAlreadyExists = Java.type("java.nio.file.FileAlreadyExistsException");

// The first line of saves/scores.txt in the game's data folder.
const firstScore = Effect.gen(function* () {
  const { plugin } = yield* PaperServer;
  const saves = plugin.getDataFolder().toPath().resolve("saves");
  yield* Jvm.attempt(Files, (files) => files.createDirectory(saves)).pipe(
    Effect.catchIf((error) => error instanceof FileAlreadyExists, () => Effect.void),
  );
  const reader = yield* Jvm.acquire(Files, (files) => files.newBufferedReader(saves.resolve("scores.txt")));
  return yield* Jvm.attempt(reader, (open) => open.readLine());
}).pipe(Effect.scoped);
```

Every other Java call stays a plain call. What it throws (`IllegalArgumentException`, `NullPointerException`) is a bug; inside an Effect it becomes a defect, which the runtime reports.

## Data for messages: generated Schemas

Messages, Models and Command args are data. For Java values, use the generated Schemas from `@minekube/paper-types/schemas`; never write your own Schema for a Paper type.

| Java type | `Schemas[...]` | Data form |
| --- | --- | --- |
| `java.util.UUID` | `Schemas["java.util.UUID"]` | A checked UUID string, branded `java.util.UUID` |
| Every enum of the scanned jars (`org.bukkit.Material`, `org.bukkit.Particle`, `org.bukkit.GameMode`, …) | `Schemas["org.bukkit.Material"]` | A union of the constant names |
| Every registry type that is not an enum (`org.bukkit.Sound`, `org.bukkit.block.Biome`, `org.bukkit.enchantments.Enchantment`, …) | `Schemas["org.bukkit.Sound"]` | Its key, such as `minecraft:entity.player.levelup`, branded by class |

`fromJava(className, value)` from `@minekube/paper` turns a Java value into its data form for a message; `toJava(className, data)` turns it back inside a Command. Registry types look their keys up in the server's registry, so convert them in `game.ts`, not in the rules. `Schemas[...].make(...)` builds checked values in tests.

If a Java type you want in a message has no Schema, report it to Minekube.

## Threads and time

- **Game code runs only on the server thread.** Events Paper fires on another thread (the status ping, async chat, pre-login) wait for the server thread and run there, so your handler can still cancel them. They are skipped, with a warning, if the server thread does not answer within a second.
- **The same holds for any JS function you hand to Java**: a `runTaskAsynchronously` task, a `CompletableFuture` callback, a Brigadier command. The runtime runs it on the server thread. Without a result it is queued; with one, the calling thread waits up to a second, then the call fails. So an async task is no way to move work off the tick: JS never runs in parallel.
- **Name the overload** where a method has overloads for several interfaces, such as `runTaskAsynchronously(plugin, Runnable)` and `(plugin, Consumer)`. GraalJS cannot tell which one a JS function means: `scheduler["runTaskAsynchronously(org.bukkit.plugin.Plugin,java.lang.Runnable)"](plugin, () => ...)`.
- **Timers run on server ticks.** `setTimeout` and `setInterval` have 50 ms resolution; `setImmediate` and `queueMicrotask` run before control returns to Paper. Effect's `Schedule` and `Effect.sleep` use these.
- **Every handler, Command start and task is timed.** Above 10 ms the server logs `[<id>] <label> took N ms on the main thread`, with the label's usual time and whether it was a cold first call. Keep work per tick small.

## Other globals

Available: the timers above, `performance.now()`, `console` (goes to the server log), `TextEncoder` and `TextDecoder` (UTF-8), `URL` and `URLSearchParams`, `AbortController`, `fetch` with `Headers`, `Request`, `Response` and `FormData`, and `WebSocket`, and the JDK, for example `java.nio.file.Files` with `plugin.getDataFolder().toPath()`. `fetch` and `WebSocket` are the JDK's HTTP client underneath, and their results and events arrive on the server thread.

Not available: `crypto`. If your game needs it, report it to Minekube as a missing capability.

## Other plugins' APIs

A game can call any plugin on the server, such as LuckPerms. To type it, name the plugin's API in `vite.config.ts`, as its developers publish it on Maven for Java plugins:

```ts title="vite.config.ts"
paper: {
  version: "26.3",
  plugins: ["net.luckperms:api:5.5"],
},
```

`mk types` downloads the API jar from Maven Central, checked by the checksum the repository publishes, and types every class of it with Paper's, into `types/paper`. A plugin that publishes elsewhere names its repository: `{ maven: "me.clip:placeholderapi:2.11.6", repository: "https://repo.extendedclip.com/releases" }`. Then call it like Paper:

```ts
const LuckPermsProvider = Java.type("net.luckperms.api.LuckPermsProvider");
const groups = Effect.sync(() => LuckPermsProvider.get().getGroupManager().getLoadedGroups().size());
```

The types are only the API: the plugin itself runs on the server, so install it there (on the dev server, its jar in `plugins/`). Name the API version that matches the plugin your servers run. The API jar, not the plugin's own jar, because a plugin jar carries its implementation and the libraries it shades, often packed in a jar of its own.

## What the runtime adds

The `PaperServer` service gives `server`, `plugin` and `host`. `host` is the runtime's small API: `getId()`, `getRevision()`, `getPreviousState()`, `listen(...)`, `schedule(...)`, `log(...)` and `report(...)`, which shows red in the chat of operators. `Paper.event`, `Paper.on`, the timers and the recording are built on it; a game rarely needs it directly.

## When the types are wrong

A missing event or class, or wrong nullability, is a bug in the generated types. Report it with the class name and the server's Paper version instead of casting around it.

The runtime itself supports Paper 1.21 and newer with one jar. Only the types depend on the Paper version: those of the version your project names, which `mk server` runs when you start it in the project folder. To move to another one, see [Change the platform version](https://minekube.com/games/versions-and-deployments/platform-version).
