Skip to content

WebSocket

Part of the Server API — not a stable public interface yet; see the note there.

Live state travels over a WebSocket on the same port. Any path upgrades; the web client connects to the server root.

The WebSocket is for the game as it is played: what changes on the table, pushed as it happens, and the quick writes of play — a drag, a door, a roll, a sheet’s change to its character. Creating and deleting things — entities, combatants, content, files — is REST’s; a client on the socket calls it with the same access token. Both follow the same access rules, and a write the socket shares with REST, such as updateCombatant, is checked by the same rules.

Every message, in both directions, is one JSON envelope:

{ "name": "tokenMoved", "data": { "…": "…" }, "requestId": "…", "responseId": "…" }
Field Notes
name What the event reports or requests — determines the shape of data
data The payload; its type follows from name
requestId Set by a client on a request it wants an answer to; unique on its connection
responseId Echoes the requestId of the request being answered

Every event carrying a requestId gets exactly one answer with that responseId: the reply its name documents, or requestFailed { code, message }. An event without a requestId is a notification and is never answered. An answer can be an ordinary event too: the answer to subscribeEntity is an entityUpdated, which says what the event is with name and what it answers with responseId.

Map and game-client events follow the same rule. One that changes a stored object is answered with that object: updateToken with tokenUpdated, measurement events with measurementUpdated, area-effect events with areaEffectUpdated (as updateCombatant is with combatantUpdated). One that changes nothing stored — a drag, a door, the pointer, clientUpdated, a deletion — is answered with its own name and empty data once the app has taken it. Drags and the pointer are sent many times a second, so a client usually sends them without a requestId.

code tells a client what happened, and message is for people:

code Meaning
unknownEvent The app doesn’t know the event’s name
unsupportedEvent The app knows the name, but doesn’t take it on this connection
invalidRequest The event’s data is missing something or can’t be read
unsupportedApi The api of a subscribeEntity is newer than this app speaks
noSuchEntity No entity has that id
notSubscribed An updateEntity for an entity the client doesn’t follow
unauthenticated The client hasn’t signed in and may not do this, or the access token it sent isn’t valid; see Signing in
notAllowed The client is signed in, but may not do this
noSchema The entity type has no model schema, or it failed to load
refused A batch of ops was refused; errors says why, see Entity subscriptions
failed The app could not complete the request

Names ending in Updated, Created or Deleted are the app broadcasting a change. Names in the imperative — createMessage, updateDoor — are a client asking for one. The payloads of the sheet protocol’s events are documented on this page, which is the reference for them. The generated WSEvent page describes the envelope and the app’s model payloads; it is built from the app’s source and can lag behind.

A message a client sends can be up to 1 MB, in one frame or in fragments. A larger one closes the connection with code 1009. What the app sends has no limit.

The app turns on TCP keepalive for every connection. Once a connection has been quiet for a minute, the system checks it every 10 seconds and closes it after five checks go unanswered. A client that vanished is let go within about two minutes, and routers keep a quiet connection open through port forwarding. The app sends no WebSocket pings. A client that needs to notice a dead connection sooner sends a request and closes the socket when no answer comes.

On connect, the app sends an app event carrying its version and build.

Browsers can’t set headers on a WebSocket, so a client signs its connection in with an event, the first thing it sends, with the access token from POST /api/session or an API key:

→ { "name": "authenticate", "requestId": "a1", "data": { "accessToken": "ept_4mQ…" } }
← { "name": "authenticated", "responseId": "a1", "data": { "role": "player", "permissions": ["read", "write"], "name": "Shelly", "player": { "id": "9B81…", "name": "Shelly", "color": "#E0FF00" }, "characters": [{ "id": "6F0A…", "name": "Aria", "kind": "Character" }] } }

authenticated describes the session as GET /api/session does, a player’s characters included. When those change — the GM assigns or unassigns a party member, or plays another campaign — the app sends each signed-in player’s connection sessionUpdated, unasked, with the same payload, which replaces what the client holds. A token that isn’t valid is answered requestFailed with unauthenticated, and the connection stays as it was; authenticate without accessToken signs it back out to a guest. A connection that never signs in is a guest’s: it watches, or — while guests need the guest code — gets nothing but answers until it signs in.

A signed-in connection is named by its account: its messages and rolls carry the player’s name and colour, whatever it sends in clientUpdated or a message.

When the credential behind a connection is gone — the player got a new code, their sign-in was turned off, they were deleted, the key was revoked — the app closes the connection with code 4401. The client reconnects as a guest and must sign in again; the web client asks for the code. Turning the guest code on closes every connection that hasn’t signed in the same way, so clients learn they now need a code (auth.guest in GET /api/server says code).

A request the connection may not make is refused with unauthenticated for a guest and notAllowed once signed in — also a map event while the GM has remote interaction turned off. Notifications, which carry no requestId, are dropped without an answer.

A tool sends its API key in the same event. The field is still accessToken:

→ { "name": "authenticate", "requestId": "a1", "data": { "accessToken": "epk_…" } }
← { "name": "authenticated", "responseId": "a1", "data": { "role": "integration", "permissions": ["read", "write"], "name": "Stream Deck" } }

A key has no player or characters, and never gets sessionUpdated.

This script signs in with a key and prints every broadcast. It runs in a browser page or in Node.js 22 or later, which both have WebSocket built in:

const ws = new WebSocket('ws://192.168.1.42:8080/');
const pending = new Map();
let nextId = 0;
// Sends a request and resolves with the data of its answer.
function request(name, data) {
const requestId = String(++nextId);
ws.send(JSON.stringify({ name, data, requestId }));
return new Promise((resolve, reject) => pending.set(requestId, { resolve, reject }));
}
ws.addEventListener('open', async () => {
try {
const session = await request('authenticate', { accessToken: 'epk_…' });
console.log(`Signed in as ${session.name} (${session.role})`);
} catch (error) {
console.error('Sign-in failed:', error.message);
ws.close();
}
});
ws.addEventListener('message', (event) => {
const { name, data, responseId } = JSON.parse(event.data);
const waiting = responseId && pending.get(responseId);
if (waiting) {
pending.delete(responseId);
if (name === 'requestFailed') waiting.reject(new Error(`${data.code}: ${data.message}`));
else waiting.resolve(data);
return;
}
console.log(name, data); // app, gameUpdated, tokenMoved, messageCreated, …
});
ws.addEventListener('close', (event) => {
if (event.code === 4401) console.log('The key was revoked: get a new one');
});

Send authenticate first, as soon as the socket opens. While guests need the guest code, nothing is broadcast to the connection until it is signed in. Once signed in, request sends any event in Events a client can send. For example, a key with write can advance the combat:

await request('gameAction', { action: 'next' });

Map events — tokenMoved, updateToken, updateDoor, pointerUpdated, measurements and area effects — need a client that may play: a player, a shared table or the GM. A guest’s are dropped, and the app tells such a connection the map isn’t interactive: its interactionUpdated and screenUpdated events, and screen.interaction in GET /api, say none, whatever the setting is, so older web clients stop offering drags too.

The remote interaction setting then applies to everyone who may play: none drops their map events, all lets them move any token, and token lets a player move only the tokens they control — a shared table, the whole party’s.

What a map event may change follows REST, where writing a map object needs write on everything. A client that has it — the GM, an API key with write — changes any field of a token with updateToken. A player changes only a token’s rotation and path, on a token they may move; any other key is refused with notAllowed, and nothing is changed. Measurement and area-effect events reach only the map being shown, and a player changes or deletes only an area effect a token they may move gave off, never the GM’s own.

Which tokens a player controls is said by each token’s controlledBy, set by the GM in the app’s token editor:

controlledBy Who moves the token with token
absent Whoever plays its character: its entityId is one of their characters
"all" Every signed-in player
a player id That player only, even when the token is another player’s character

Both fields are on every token the server sends — in GET /api, token broadcasts and /api/tokens — so a client can offer exactly the drags the app accepts: a player id in controlledBy is compared with player.id of the session. Neither can be changed by a client.

The sheet protocol’s version is the api a client names in subscribeEntity: 1 today. A subscription runs at the version it asks for, or is refused with unsupportedApi.

Within a version the app only adds: new keys in states and answers, new events, new error codes, new optional fields in requests. A client stays compatible by:

  • ignoring keys and events it doesn’t know;
  • treating a requestFailed code it doesn’t know as a refusal;
  • sending only the fields documented here, since a field the app doesn’t know yet may mean something later.

A change that would break a client written to this page comes as a new version, and the app keeps speaking the old one. The sheet SDK follows the same rule: /_app/js/ep.js speaks version 1, and a later version ships as a new file.

Browsers don’t apply CORS to WebSockets, so the app checks the Origin a browser sends with the upgrade and accepts:

Origin For
None Clients that aren’t browsers: native apps, scripts, command-line tools
The address the request went to The app’s own pages: the web client, sheets
localhost, loopback addresses A page on the same machine, such as a sheet’s dev server
Private and link-local addresses, .local names A page served from another machine on your network

Any other page is refused, null included (a sandboxed frame or a local file), and the upgrade gets an ordinary HTTP response instead, so the browser reports a failed connection.

Port forwarding and dynamic DNS names work unchanged: players who open the app’s pages at your public address connect at that same address, and the browser names it in both Origin and Host. A web client you serve yourself must be on your network (by address or a .local name). A page on a public server is refused even when it connects to your public address. A reverse proxy must pass on the Host the browser sent (with nginx, proxy_set_header Host $host;), or the app’s own pages are refused through it.

Anything not listed here is ignored, even when the app knows the name — and refused with requestFailed when it carries a requestId. The events marked both work the same in the app’s web views (below); the others are for connected game clients only.

Event Payload Where Effect
authenticate { accessToken? } socket Signs the connection in, or out without a token; answered with authenticated. Send it first; see Signing in
clientUpdated Client socket Registers the client’s name, color, device and screen size. Send it after signing in — a client identifying itself with a non-normal runMode becomes a player display. The name is what the log shows for a guest’s messages and rolls; a signed-in client keeps its account’s
mapViewportUpdated Frame socket Reports where this client is looking, so the app can show its viewport
tokenMoved Movement socket Drags a token; see The map
updateDoor Door socket Opens or closes a door, recomputing line of sight; see The map
pointerUpdated Pointer socket Moves this client’s shared pointer; see The map
createMeasurement Measurement socket Adds a measurement to the map shown; answered with measurementUpdated; see The map
updateMeasurement / deleteMeasurement { id, … } / { id } socket Changes or removes a measurement on the map shown; see The map
createAreaEffect AreaEffect socket Adds an area effect to the map shown, its source a token on that map; answered with areaEffectUpdated; see The map
updateAreaEffect / deleteAreaEffect { id, … } / { id } socket Changes or removes an area effect on the map shown; see The map
updateToken { id, … } socket Merges changes into a token by id: a player only its rotation and path, a client that may write the map any field; see The map
subscribeEntity { id, api, labels? } both Follows an entity; see Entity subscriptions
unsubscribeEntity { id } both Stops following an entity
updateEntity { id, ops } both Applies a batch of ops to a subscribed entity; see Entity subscriptions
queryEntities { entity, search?, where?, sort?, keys?, ids?, offset?, limit? } both Lists a page of library entries; answered with entitiesQueried { entries, total }, see Listing entries
pickEntity { entity } both Lets the user pick library entries in the app’s own list; answered with entityPicked. Needs someone at the app, so a socket gets unsupportedEvent; see Listing entries
rollDice { formula, label?, type?, mode?, creature?, rolls?, customize? } both Rolls dice and logs the roll, or logs dice the client threw itself; answered with diceRolled, see Rolling dice
createMessage Message both Posts to the shared log, rolling a /roll command in it; answered with messageCreated on requestId
updateCombatant { id, … } both Changes a combatant by id, the rest a JSON merge patch checked as PATCH /api/combatants/{id} checks it; answered with combatantUpdated on requestId, or requestFailed (noSuchEntity, notAllowed, refused with errors)
listRollOptions { formula, label?, type? } both Lists what a roll link’s menu offers; answered with rollOptionsListed, see Roll menus
gameAction { action } both Runs the combat — start, stop, next, previous, roll-initiative — as POST /api/game/{action}; answered with gameUpdated, see Running the combat
endTurn { combatantId } both Ends that combatant’s turn, as POST /api/game/end-turn; a player their own character’s; answered with gameUpdated, see Running the combat
updateResource { id, add } or { id, value } both Changes a game resource of the campaign being played; answered with resourcesUpdated, see Game resources
subscribeResources {} both Asks for the game resources the client may see; answered with resourcesUpdated, and a web view gets it after every change from then on, see Game resources
trackedObjectCreated / trackedObjectUpdated / trackedObjectDeleted / trackedObjectsUpdated TrackedObject socket Reports physical objects tracked on a table-top display
Group Events
Game state gameUpdated, combatantUpdated, resourcesUpdated, systemPaused
Player screen screenUpdated, interactionUpdated, reload
Map mapUpdated, mapLoaded, mapFrameUpdated, mapFitScreen, mapFocus, mapVideoControlUpdated
Map objects tokenUpdated, tokensUpdated, markerUpdated, markersUpdated, tileUpdated, tilesUpdated, lightUpdated, lightsUpdated, areaEffectUpdated, areaEffectsUpdated, measurementUpdated, measurementsUpdated
Movement tokenMoved, markerMoved, tileMoved
Overlays fogUpdated, drawingsUpdated, lineOfSightUpdated, pointerUpdated
Log messageCreated, messagesUpdated
Clients clientConnected, clientDisconnected, clientUpdated, app
Object tracking trackedObjectCreated, trackedObjectUpdated, trackedObjectDeleted, trackedObjectsUpdated

Broadcasts go to every connected client that may read, including the one whose action caused them. A connection without a credential gets none while guests need the guest code, until it signs in, as GET /api is a 401 for it. entityUpdated and entityDeleted are not broadcast: they go only to clients subscribed to the entity (see below).

Hidden tokens, combatants and markers are broadcast like any other, with hidden: true: hiding is what the table shows, not access, and a client decides what to draw. REST reads them the same way; see Visibility.

resourcesUpdated carries the whole game.resources list from GET /api after any change, and replaces what the client holds; see Game resources. gameUpdated carries resources only when it carries the whole game, as GET /api does, and then the same list.

One event carries the system’s game resources, whatever the reason: resourcesUpdated, with the whole list the client may see, each entry in the shape of game.resources. It is the broadcast after every change, the answer to subscribeResources, and the answer to updateResource, and it always replaces what the client holds.

Which resources a client sees follows its access, as over REST: a client that reads everything — the GM, an API key, and the app’s web views, which run on the GM’s device — sees them all; anyone else sees the players’ ones, without a countdown at 0, which is not running yet.

subscribeResources asks for the list:

→ { "name": "subscribeResources", "requestId": "r19", "data": {} }
← { "name": "resourcesUpdated", "responseId": "r19", "data": [{ "id": "fear", "type": "counter", "label": "Fear", "min": 0, "max": 12, "value": 4 }] }

A socket gets the broadcast after every change whether it asked or not, so for it this is only a read. A web view gets no broadcasts, and follows the resources once it has sent this: the same resourcesUpdated arrives after every change, without a responseId, until its page goes. With no campaign being played the list is empty.

updateResource changes one resource in the campaign being played — a sheet giving the GM a Fear when a roll goes with Fear:

→ { "name": "updateResource", "requestId": "r20", "data": { "id": "fear", "add": 1 } }
← { "name": "resourcesUpdated", "responseId": "r20", "data": [{ "id": "fear", "type": "counter", "label": "Fear", "min": 0, "max": 12, "value": 5 }] }
Field Notes
id Required. The resource’s id in the system’s config.json
add A whole number to change the value by, negative to lower it
value A whole number to set the value to

Send exactly one of add and value. The value is kept within the resource’s min and max, so Fear at 12 stays at 12, and add is applied by the app to the value it holds, so two clients adding at once both count. The answer is the list as it is now, the changed resource in it — unless it is a countdown the client no longer sees, at 0; everyone else learns of the change from the resourcesUpdated broadcast, the bottom bar and the player display included.

Like updateEntity, a request needs a requestId: one without is ignored and not applied. Both, neither, a value that isn’t a whole number, or another key is invalidRequest. A client that doesn’t read everything can change only resources the players see; any other id, GM-only ones included, is refused as unknown (invalidRequest, no such resource), so it can’t learn that a GM-only resource exists. A client that reads everything, the app’s web views among them, can change them all. With no campaign being played the request fails with failed.

Two events run the combat, by the rules of their REST counterparts, and both answer with gameUpdated carrying where the combat stands — the same payload every client gets as a broadcast after a turn changes:

→ { "name": "endTurn", "requestId": "t7", "data": { "combatantId": "c41a…" } }
← { "name": "gameUpdated", "responseId": "t7", "data": { "started": true, "round": 2, "turn": 3, "combatantId": "9b02…", "initiativeId": "77e1…" } }
  • gameAction { action } is the GM’s controls: start, stop, next, previous and roll-initiative, as POST /api/game/{action}. It needs write on everything. A turn that can’t move — combat not started, nobody in the order — is refused; an unknown action is invalidRequest.
  • endTurn { combatantId } is a player saying they are done, as POST /api/game/end-turn. A player may end their own character’s turn; a combatant with no entity needs write on everything. It names whose turn ends, so a double tap or the GM moving the turn meanwhile can’t skip anyone: a turn that isn’t that combatant’s any more is refused. Use it, not next, for an End turn button — the app decides what comes after, today the next combatant’s turn.

A client follows an entity by subscribing to it, and gets the entity’s whole state as entityUpdated then and after every change — whoever made it: this client, another browser, a form or the combat bar in the app. Character sheets work this way, in the app and in a browser.

→ { "name": "subscribeEntity", "requestId": "r1", "data": { "id": "k3x9…", "api": 1 } }
← { "name": "entityUpdated", "responseId": "r1", "data": { "id": "k3x9…", "client": "browser", "system": { "id": "dragonbane", "version": "1.2.0", "labels": { "…": "…" } }, "env": { "…": "…" }, "model": { "…": "…" }, "derived": { "…": "…" } } }
Field of entityUpdated Notes
id The entity
model The entity as stored: nothing computed, nothing left out. A link to another object is its id, combatantId. The model schema decides what can be written, never what is sent
derived What the app and the system’s transforms add to or change in the model (the view): the transforms’ values, and reference, location, source, sourceFormatted, locationFormatted and footer. Objects are compared key by key; a changed value or list is sent whole; a key the view removes is null. Lay it over model to get the view
writable Only in the answer to subscribeEntity: whether this client may change the entity — false for a watching guest, or a player’s look at someone else’s character. A hint for drawing the sheet read-only; every write is still checked
client, system, env, schema Only in the answer to subscribeEntity: where the client runs, app or browser; the loaded system as { id, version, labels }, with its labels (below); the view environment; and the address of the entity type’s runtime schema (/systems/{system}/cache/schemas/{label}.json?v=…), which a client can check writes with before sending them — when the type has a schema

The labels are { language, strings, enums }: the system’s strings in its language by key, with English for any key the language lacks, and every enum key’s label by enum — for sheets, which have no template filters to localize with. A client that has them or doesn’t need them subscribes with labels: false, and the first state leaves them out.

api is the protocol version the client speaks, 1 when it is left out. A version newer than the app’s is refused with unsupportedApi, and one that isn’t a number with invalidRequest. The answer doesn’t repeat it: a subscription runs at the version it asked for, or is refused.

A client may subscribe only to an entity it may see; any other is answered noSuchEntity, as if it didn’t exist.

State arrives in order, so the last entityUpdated received is the current one. When the entity is deleted, subscribers get entityDeleted { id } and the subscription ends; it also ends when the client disconnects.

In the app’s web views, a sheet gets the entity’s first state before it loads, labels included, so it can draw the entity at once rather than after the subscription answers: window.encounterplusStartingState, set at document start to the data of the entityUpdated that answers subscribeEntity. Template views get no starting state: they are rendered with the entity, and one that follows it subscribes like any other client.

window.encounterplusStartingState // { id: "k3x9…", client: "app", system: {…}, env: {…}, schema: "…", model: {…}, derived: {…} }

The state the subscription then answers with is the same one unless the entity changed in between, so a client can compare the two to tell. A page should check id first: the web view keeps the state for the entity it last loaded a sheet of. Browsers get no starting state, and draw the entity once the subscription answers.

A subscribed client changes the entity with a batch of ops, applied whole or not at all. An update needs a requestId, and the state that includes it answers with that responseId:

→ { "name": "updateEntity", "requestId": "r7", "data": { "id": "k3x9…", "ops": [
{ "op": "test", "path": "data.weapons[0]", "value": { "name": "Dagger" } },
{ "op": "set", "path": "data.weapons[0].broken", "value": true }
] } }
← { "name": "entityUpdated", "responseId": "r7", "data": { "id": "k3x9…", "model": { "…": "…" }, "derived": { "…": "…" } } }
Op Fields Effect
set path, value Writes a value, creating missing objects on the way (never list items). null, or "" for anything but text, removes the key
remove path Removes a key (nothing happens when it is missing) or a list item
insert path, value, index? Inserts an object into a list, at the end without index; creates a missing list. In a list with ids the item keeps an id it brings or gets a new one
move path, index Moves a list item within its list; index is its position afterwards
test path, value Checks a value without writing; null expects the key to be missing
increment path, value Changes a number by value, negative to lower it, counting from the value stored now — so two clients’ changes both count — and from 0 when there is none. The result is kept within the declared min and max rather than refused. Only integer and number fields; a whole-number field takes whole numbers
embed path, ref, keys, index? Adds a copy of a library entry — ref is its reference, /item/axe — to a list of references, or puts it in a single reference field: the entry’s name, ref as its reference, and the listed keys of its data (its description as descr when the data has none). The entry must be of the kind the schema’s ref declares, and the keys declared

Paths start at data: data.hp.current, data.actions[2].name (a list item by position), data.items[k3x9].quantity (by id, in a list with ids). Every value is checked and converted against the entity type’s model schema, and paths it doesn’t declare are refused; an entity type without a schema refuses every batch.

Beside data, two of the entity’s own fields can be written, with set and test only: name, text that isn’t empty (it is trimmed), and notes, text, removed by null or "". A rename leaves the entity’s slug, and so its address, as it is. They go in the same batch as data ops, applied whole or not at all. Any other path outside data is invalidPath. A key the schema doesn’t declare is still sent in model: the schema decides what can be written, never what can be read.

The other subscribers get the same state without a responseId. A refused batch is answered with requestFailed:

← { "name": "requestFailed", "responseId": "r7", "data": { "code": "refused", "message": "the update was refused", "errors": [
{ "index": 1, "path": "data.hp.current", "code": "outOfRange", "message": "data.hp.current: must be between 0 and 30" }
] } }

index is the failing op; each error’s code is one of invalidPath, undeclared, notWritable, invalidValue, outOfRange, invalidKey, invalidSelector, duplicateId, invalidOp, missingItem, notAList, invalidIndex, testFailed, notAReference and missingSource. requestFailed without errors answers a request that could not be handled at all, and its code says why: noSuchEntity, notSubscribed, noSchema, notAllowed or unauthenticated for a client that may not change the entity, or invalidRequest for an update without ops. An update without a requestId is ignored and not applied, since nothing could answer it.

Entries to embed are found with queryEntities, or picked by the user with pickEntity.

A client lists library entries to build its own picker — a dialog, a dropdown, a list of spells to learn — with queryEntities, and gets one page of them with the number of matches in all. Only entries the client may see are listed and counted, here, in pickEntity and over REST:

→ { "name": "queryEntities", "requestId": "r9", "data": {
"entity": "Item", "search": "a", "where": { "type": "weapon", "data.skill": ["axes", "swords"] },
"sort": "name", "keys": ["data.skill", "data.weight"], "limit": 20 } }
← { "name": "entitiesQueried", "responseId": "r9", "data": { "total": 2, "entries": [
{ "id": "…", "name": "Axe", "kind": "Item", "type": "weapon", "reference": "/module/rules/item/axe", "source": "Core",
"image": "/modules/rules/items/axe.webp", "tags": ["metal"], "data": { "skill": "axes", "weight": 2 } },
{ "id": "…", "name": "Broadsword", "kind": "Item", "type": "weapon", "reference": "/module/rules/item/broadsword", "source": "Core",
"data": { "skill": "swords", "weight": 2 } }
] } }
Field Notes
entity Required. The entity kind as the system’s definitions name it (Item, not a label); the loaded system’s entries of that kind and of the kinds extending it are listed
search Part of the name, any case
where An object of paths and what their values must be, every one holding: a value to equal, a list to equal one of, or operators. Paths are name, type, kind, source, tags, or anything under data.. Values are text, numbers and booleans; numbers compare as numbers (2 matches 2.0) and never as booleans, text exactly, and a stored list (tags) matches when any of its items does. A missing value, null, "" and [] are no value, which equals nothing
sort A path, as for where, descending with a - prefix: -data.weight. Numbers sort as numbers and text in Finder order; entries without the value go last. Name order when left out
keys Paths each entry carries, so a picker can show columns without fetching every entry: data. paths in its data, stored values, and view. paths in its view, values the app computes through the system’s transforms (view.data.evasion). "list", alone or in the list, stands for the data. paths the system’s list of the kind filters, groups and sorts by (its filters.json) — what a picker shows without knowing the system; a kind without filters has none. Computed values cost more: the app works them out for the page it answers, never for the whole kind, which is also why where and sort read stored values only
ids Only these entries — for showing what a sheet already holds
offset, limit The page: from offset (0), up to limit entries (50 when left out, at most 200)

An entry is { id, name, kind, type?, reference, source?, detail?, image?, icon?, tags?, visibility?, data?, view? }. reference is as a copy of the entry holds it — what embed takes as ref. detail is the line under the name in the app’s library list, the system’s collection.detail for the kind in config.json, so a picker can show the same. image is an address the page reaches the file at, in the app and in a browser alike; icon is a game icon (gi-…) as it is, or such an address. visibility is the entry’s own setting, gm or players, left out when it follows its type and its module or campaign — see Visibility. A client that sees only what players may see never gets a hidden entry. pickEntity answers with the same entries.

A where value can be an object of operators instead, which must all hold — so { "gte": 1, "lte": 3 } is a range:

"where": {
"data.level": { "gte": 1, "lte": 3 },
"data.school": { "nin": ["necromancy", "illusion"] },
"data.ritual": { "exists": true }
}
Operator Operand Keeps an entry when its value…
ne a value isn’t equal to it. No value passes; a stored list passes when no item is equal
nin a list of values is equal to none of them. No value passes; a stored list passes when no item is equal to one
lt, lte, gt, gte a number is a number below, at most, above or at least it. Text, booleans and no value never pass; a stored list passes when any item does
exists true or false has a value, or has none. null, "" and [] count as none, as a cleared form field leaves them

To keep entries that have a value and aren’t one of a list, put exists beside nin: { "nin": ["cantrip"], "exists": true }. There is no OR across paths, no case-insensitive or partial match outside search, and no “every item of a list” test.

A query is plain data, matched by the app; it never runs code. A value of the wrong type is refused with invalidRequest naming the problem rather than read as a default — an operand of the wrong type, an unknown operator, an empty operator object, or null as a value (use { "exists": false }). REST lists the same pages with GET /api/{collection}.

Picking. pickEntity { entity } shows the app’s own library list and is answered with entityPicked { entities }, the entries the user picked, none when they cancelled. It needs someone at the app, so only the app’s web views can make it: a socket gets unsupportedEvent, and lists entries for its own picker instead.

rollDice rolls dice, logs the roll and answers with it, the same on a socket and in the app’s web views:

→ { "name": "rollDice", "requestId": "r13", "data": { "formula": "1d20+2", "label": "Awareness", "type": "check" } }
← { "name": "diceRolled", "responseId": "r13", "data": { "roll": { "name": "Awareness", "type": "check", "formula": "1d20 + 2", "result": 16, "detail": "(14) + 2",
"dice": [{ "formula": "1d20", "faces": 20, "result": 14, "rolls": [{ "value": 14 }] }] } } }
Field Notes
formula Required. A formula that can’t be rolled is refused with invalidRequest
label The roll’s name, as the log shows it
type attack, damage, heal, check or save; an unknown type is left out
mode public or private. In the app’s web views it overrides the app’s roll mode setting, which applies when it is left out; a socket’s rolls are always public for now
creature Who the roll is for, as the log shows it. In the app’s web views it defaults to the entity the view shows
rolls Dice the client threw itself — see below
customize true opens the app’s advanced dice roller with the formula, for the GM to change and roll — the roll menu’s Customize… item. The answer carries no roll: what is rolled there is the GM’s own, logged by the roller. Only the app’s web views can, a socket gets unsupportedEvent

Who throws the dice. Without rolls, the app does:

  • In the app’s web views the dice roller shows, and the answer is the first roll to finish. roll is left out when the user closed the roller first, or the view was already showing something.
  • On a socket the app rolls without showing anything — the app’s screen belongs to the GM, and a player’s roll must not interrupt it — and the roll appears in the log under the client’s name.

With rolls, the client threw its own dice — 3D dice in its page, physical dice read off a table — and the app only checks them and computes the result:

→ { "name": "rollDice", "requestId": "r14", "data": { "formula": "2d20kh1 + 1d6", "label": "Longsword", "type": "attack", "rolls": [[4, 17], [3]] } }
← { "name": "diceRolled", "responseId": "r14", "data": { "roll": { "name": "Longsword", "type": "attack", "formula": "2d20kh1 + 1d6", "result": 20, "clientThrown": true,
"dice": [{ "formula": "2d20kh1", "faces": 20, "result": 17, "rolls": [{ "value": 4, "dropped": true }, { "value": 17 }] },
{ "formula": "1d6", "faces": 6, "result": 3, "rolls": [{ "value": 3 }] }] } } }

rolls has one list of faces per dice term, in the formula’s order, each holding every die thrown for the term in the order thrown. A term’s own dice come first; dice its modifiers add — an explosion (!), a reroll (r) — are taken from the rest, so a client that throws exploding dice sends the extra dice too. The total is always the app’s, computed from the faces with the formula’s modifiers and arithmetic, never taken from the client. Faces that don’t fit — a list per term missing or extra, a face the die doesn’t have, too few or too many dice — are refused with invalidRequest saying which. The roll is logged marked as thrown by the client, and the answer carries clientThrown: true.

The answer. A roll carries its dice as dice, one group per dice term in the formula’s order: { formula, label?, faces, result, rolls }, with every die thrown in rolls as { value } and dropped: true on one that doesn’t count — kept out by kh or kl, rerolled, or a failure. label is the term’s label, Hope for 1d12[Hope], and formula the term without it. detail is the same dice as text, for people; don’t read values out of it.

When the game system reads an outcome from the labelled dice (dice.outcomes), the roll carries it as outcome: { id, label, color? } — Daggerheart’s { "id": "hope", "label": "With Hope", "color": "#e8b931" }. Branch on id; label is localized text to show. A roll the system reads no outcome from has none.

Every client gets the logged roll as messageCreated too, the roller included, with content holding the roll and its dice — so a client with 3D dice can replay another client’s throw to the same faces. A private roll is answered but not logged.

listRollOptions asks what a roll link’s menu offers — the menu ep-ui.js draws on a right-click or a long press:

→ { "name": "listRollOptions", "requestId": "r15", "data": { "formula": "1d12[Hope] + 1d12[Fear] + 2", "label": "Agility" } }
← { "name": "rollOptionsListed", "responseId": "r15", "data": { "options": [
{ "id": "roll", "label": "Roll", "formula": "1d12[Hope] + 1d12[Fear] + 2" },
{ "id": "advantage", "label": "Advantage", "formula": "1d12[Hope] + 1d12[Fear] + 2 + 1d6[Advantage]" },
{ "id": "private", "label": "Roll Privately", "formula": "1d12[Hope] + 1d12[Fear] + 2", "mode": "private", "group": "gm" },
{ "id": "customize", "label": "Customize…", "formula": "1d12[Hope] + 1d12[Fear] + 2", "customize": true, "group": "gm" } ] } }

The plain roll comes first, with the formula as sent, then the system’s dice.options that apply to the roll, each with the formula it rolls. In the app’s own web views the GM’s items come last, group: "gm": the plain roll in the other roll mode, with that mode, and Customize…, customize: true, which opens the advanced dice roller with the formula. A socket’s rolls are always public and it has no roller, so it gets none. A formula that can’t be rolled is refused with invalidRequest.

Choosing an item is a rollDice with its formula, and its mode or customize when it has one: the options change only what is rolled.

From the chat. A /roll command (or /r) posted with createMessage is still rolled and logged, and a request is answered with the logged message:

→ { "name": "createMessage", "requestId": "r12", "data": { "type": "command", "content": "/roll 1d20 [Awareness]", "creature": "Brin" } }
← { "name": "messageCreated", "responseId": "r12", "data": { "id": "…", "type": "roll", "creature": "Brin", "created": "…",
"content": { "name": "Awareness", "formula": "1d20", "result": 14, "detail": "(14)", "dice": [{ "…": "…" }] } } }

The text in brackets names the roll, optionally with a type after a colon — [Longsword: attack]; the name can be left out, [: attack]. A command the app can’t read is still logged, as a chat message saying so ("Invalid expression", "Invalid command"), and that message is the answer, so check type before reading a result. This is for chat; a sheet rolls with rollDice.

A page in the app speaks the same protocol without a socket: the events are the same, and only how they travel differs. It sends each event as JSON text to the API message handler, and gets every answer back as an encounterplus:message event on its window, with the app’s event as detail:

window.addEventListener('encounterplus:message', (event) => {
const { name, responseId, data } = event.detail
})
window.webkit.messageHandlers.API.postMessage(JSON.stringify({ name: 'subscribeEntity', requestId: 'r1', data: { id } }))

Events arrive in order, as on a socket. The app takes every event marked both in Events a client can send — entity subscriptions, queryEntities, pickEntity, rollDice, createMessage and updateCombatant — and handles each exactly as it does for a socket; the difference is that a web view has someone at the app, so pickEntity shows the library list and rollDice shows the dice roller. Map and client events are answered with unsupportedEvent, and the page gets no broadcasts: it isn’t a connected game client. Its rolls and messages are the GM’s in the log.

A plain link to a content address — <a href="/item/axe"> — opens the entry’s card over the view in the app; in a browser it is an ordinary link to the rendered entry.

Movement events carry a state, because a drag is a stream of messages rather than one:

State Meaning
start The drag began
control The position is updating continuously
end The drag finished; commit the position
block The host refused the move; return the object to where it was
cancel The sender abandoned the drag

A client sending a drag should expect block and be ready to snap back.