Foundry and discord bot
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m51s

This commit is contained in:
2026-10-11 22:26:29 +02:00
parent a2b512699a
commit 1402045001
65 changed files with 5962 additions and 144 deletions

View File

@@ -0,0 +1,111 @@
# Dragonroll Foundry integration
Foundry modules run in the game client, so the module cannot bind an HTTP port on the Foundry host.
This integration uses a small companion bridge process on that host:
1. A linked GM client syncs character Actors directly with the Dragonroll campaign.
2. The module publishes the active world's actor and item snapshot to the optional bridge.
3. The bridge serves authenticated HTTP read endpoints that Dragonroll proxies under `/api/foundry/*`.
The Foundry module uses the client-side package API and hooks documented by Foundry: [module development](https://foundryvtt.com/article/module-development/).
## 1. Install the Foundry module
Copy the contents of this directory into
`{Foundry user data}/Data/modules/dragonroll-foundry/`. Restart Foundry, then enable **Dragonroll
Foundry API** in the world's module settings.
After linking a campaign, the module stores a client-only token for character synchronization that
persists across Foundry restarts. If the optional bridge is configured, Dragonroll also sends its
connection settings to the module.
Existing clients continue using their saved bridge URL and publish token automatically. The module
publishes at world startup and after actor or item changes, and sends a lightweight heartbeat once a
minute. Its local JavaScript API remains available at
`game.modules.get("dragonroll-foundry").api`.
## Link a Foundry world to a Dragonroll campaign
Open the campaign's **Settings → Integrations** tab in Dragonroll and create a pairing code. In the
Foundry module settings, set **Dragonroll Endpoint** if you use a different Dragonroll server; it
defaults to `https://dragonroll.aranroig.com` and the module adds `/api` automatically. Paste the
code into **Dragonroll Campaign Pairing Code** and save. Codes expire after ten minutes and can only
be used once.
Both sides of the pairing survive restarts: Dragonroll keeps a pending code on the campaign so the
settings screen re-displays it after a page reload, the window being closed, or a server restart
(until it expires or is used), and the Foundry module keeps a code it could not redeem yet — for
example one pasted while Dragonroll was restarting — retrying it at world startup and once a minute
until the world finishes linking.
For a local backend, use `http://localhost:5000`; the module omits `/api` and the backend accepts
the local pairing route at its root. Character synchronization works without the optional snapshot
bridge. Configure that bridge only if you also need the read-only world snapshot API described below.
The campaign settings show the linked world's title and system. A Foundry world can be linked to
only one campaign at a time. The pairing endpoint accepts cross-origin requests from the Foundry
client and uses the one-time code instead of a Dragonroll login token.
## Character synchronization
After linking, the GM client imports Foundry character, NPC, and creature Actors into the campaign.
Creates, updates, and deletes sync in either direction; Dragonroll changes are applied in Foundry
within about five seconds. The module currently creates Dragonroll characters in D&D 5e Foundry
worlds. After updating an already-linked world to a version with character sync, create a fresh
pairing code and enter it in Foundry once to issue the sync token.
## 2. Run the bridge on the Foundry host
The bridge uses only Node.js built-in modules and requires Node 18 or newer. Set separate random
tokens for backend reads and Foundry snapshot publishing, then start it:
```sh
export DRAGONROLL_FOUNDRY_READ_TOKEN='replace-with-a-long-random-read-token'
export DRAGONROLL_FOUNDRY_PUSH_TOKEN='replace-with-a-different-long-random-publish-token'
export DRAGONROLL_FOUNDRY_ALLOWED_ORIGINS='https://vtt.example.com'
export DRAGONROLL_FOUNDRY_HOST='0.0.0.0'
export DRAGONROLL_FOUNDRY_PORT='8787'
npm start --prefix foundry/bridge
```
Put the bridge behind HTTPS when it is reachable outside a trusted private network. The Foundry
browser origin must be listed in `DRAGONROLL_FOUNDRY_ALLOWED_ORIGINS`; separate multiple origins with
commas. The bridge binds to `0.0.0.0` by default so Dragonroll can reach it on another host. Restrict
network access to the bridge port to Dragonroll and Foundry clients. If the reverse proxy serves the
bridge under a path prefix, configure it to strip that prefix before forwarding requests to port 8787.
## 3. Configure Dragonroll's backend
Set these variables in the backend environment. `FOUNDRY_API_URL` is the bridge base URL reachable
by the backend, without an API path. `FOUNDRY_API_CLIENT_URL` is optional and overrides the bridge
URL sent to Foundry clients when they cannot reach the backend's bridge URL (for example, when the
backend uses a private network address). `FOUNDRY_API_PUSH_TOKEN` must match the bridge's
`DRAGONROLL_FOUNDRY_PUSH_TOKEN`:
```sh
FOUNDRY_API_URL='https://vtt.example.com/dragonroll-bridge/'
FOUNDRY_API_CLIENT_URL='https://vtt.example.com/dragonroll-bridge/'
FOUNDRY_API_TOKEN='replace-with-the-bridge-read-token'
FOUNDRY_API_PUSH_TOKEN='replace-with-the-bridge-publish-token'
```
The backend exposes these JWT-protected routes when the optional snapshot bridge is configured:
| Dragonroll route | Data |
|---|---|
| `GET /api/foundry/world` | Active Foundry world metadata |
| `GET /api/foundry/actors` | All world actors |
| `GET /api/foundry/characters` | Actors with type `character` |
| `GET /api/foundry/actors/:id` | One actor |
| `GET /api/foundry/actors/:id/items` | Items embedded in an actor |
| `GET /api/foundry/items` | World-level items |
| `GET /api/foundry/items/:id` | One world-level item |
The bridge exposes the matching routes under `/api/*`, plus `GET /health`. Data routes require
`Authorization: Bearer <read-token>`. Responses contain `{ status: "ok", data, world, syncedAt,
ageSeconds, stale }`. The snapshot stays in memory; `stale` becomes true when the bridge has not
received a GM heartbeat for more than two minutes. The bridge returns `503 foundry.not-ready` until a
configured GM client has published its first snapshot.
World-level items come from Foundry's `game.items`; actor inventories come from each actor's embedded
items collection. The API returns plain document data snapshots. This is a read-only integration: it
does not create or update Foundry documents, and it does not persist the bridge cache across restarts.

View File

@@ -0,0 +1,12 @@
{
"name": "dragonroll-foundry-bridge",
"private": true,
"version": "0.1.0",
"description": "Authenticated HTTP bridge between a Foundry client module and Dragonroll.",
"scripts": {
"start": "node server.js"
},
"engines": {
"node": ">=18"
}
}

View File

@@ -0,0 +1,233 @@
const http = require("node:http");
const { timingSafeEqual } = require("node:crypto");
const host = process.env.DRAGONROLL_FOUNDRY_HOST || "0.0.0.0";
const port = Number(process.env.DRAGONROLL_FOUNDRY_PORT || 8787);
const readToken = process.env.DRAGONROLL_FOUNDRY_READ_TOKEN;
const pushToken = process.env.DRAGONROLL_FOUNDRY_PUSH_TOKEN;
const allowedOrigins = new Set(
(process.env.DRAGONROLL_FOUNDRY_ALLOWED_ORIGINS || "http://localhost:30000")
.split(",")
.map((origin) => origin.trim())
.filter(Boolean),
);
const maxBodySize = 50 * 1024 * 1024;
if (!readToken || !pushToken) {
throw new Error("Set DRAGONROLL_FOUNDRY_READ_TOKEN and DRAGONROLL_FOUNDRY_PUSH_TOKEN before starting the bridge.");
}
let snapshot = null;
function sendJson(response, status, body) {
response.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
response.end(JSON.stringify(body));
}
function setCorsHeaders(request, response) {
const origin = request.headers.origin;
if (!origin) return true;
if (!allowedOrigins.has(origin)) return false;
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
response.setHeader("Vary", "Origin");
return true;
}
function hasBearerToken(request, expectedToken) {
const match = /^Bearer\s+(.+)$/i.exec(request.headers.authorization || "");
if (!match) return false;
const actual = Buffer.from(match[1]);
const expected = Buffer.from(expectedToken);
return actual.length === expected.length && timingSafeEqual(actual, expected);
}
function readJson(request) {
return new Promise((resolve, reject) => {
const chunks = [];
let bytes = 0;
let tooLarge = false;
request.on("data", (chunk) => {
bytes += chunk.length;
if (bytes > maxBodySize) {
tooLarge = true;
chunks.length = 0;
return;
}
if (!tooLarge) chunks.push(chunk);
});
request.on("end", () => {
if (tooLarge) {
reject(Object.assign(new Error("Snapshot is too large."), { status: 413 }));
return;
}
try {
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
} catch {
reject(Object.assign(new Error("Request body must be valid JSON."), { status: 400 }));
}
});
request.on("error", reject);
});
}
function currentSnapshot(response) {
if (!snapshot) {
sendJson(response, 503, { status: "error", msg: "foundry.not-ready" });
return null;
}
return snapshot;
}
function sendData(response, data, current) {
const ageMs = Date.now() - current.syncedAtMs;
sendJson(response, 200, {
status: "ok",
data,
world: current.world,
syncedAt: new Date(current.syncedAtMs).toISOString(),
ageSeconds: Math.floor(ageMs / 1000),
stale: ageMs > 120000,
});
}
function decodePathSegment(segment) {
try {
return decodeURIComponent(segment);
} catch {
return null;
}
}
const server = http.createServer(async (request, response) => {
if (!setCorsHeaders(request, response)) {
sendJson(response, 403, { status: "error", msg: "foundry.origin-not-allowed" });
return;
}
if (request.method === "OPTIONS") {
response.writeHead(204);
response.end();
return;
}
const pathname = new URL(request.url, "http://localhost").pathname;
if (request.method === "GET" && pathname === "/health") {
sendJson(response, 200, {
status: "ok",
ready: Boolean(snapshot),
syncedAt: snapshot ? new Date(snapshot.syncedAtMs).toISOString() : null,
});
return;
}
if (request.method === "POST" && pathname === "/internal/snapshot") {
if (!hasBearerToken(request, pushToken)) {
sendJson(response, 401, { status: "error", msg: "unauthorized" });
return;
}
try {
const body = await readJson(request);
if (!body.world?.id || !Array.isArray(body.actors) || !Array.isArray(body.items)
|| !body.actorItems || typeof body.actorItems !== "object" || Array.isArray(body.actorItems)) {
sendJson(response, 400, { status: "error", msg: "foundry.invalid-snapshot" });
return;
}
snapshot = {
world: body.world,
actors: body.actors,
items: body.items,
actorItems: body.actorItems,
syncedAtMs: Date.now(),
};
sendJson(response, 200, { status: "ok", syncedAt: new Date(snapshot.syncedAtMs).toISOString() });
} catch (error) {
sendJson(response, error.status || 400, { status: "error", msg: "foundry.invalid-snapshot" });
}
return;
}
if (request.method === "POST" && pathname === "/internal/heartbeat") {
if (!hasBearerToken(request, pushToken)) {
sendJson(response, 401, { status: "error", msg: "unauthorized" });
return;
}
try {
const body = await readJson(request);
if (!snapshot || !body.worldId || snapshot.world.id !== body.worldId) {
sendJson(response, 409, { status: "error", msg: "foundry.not-ready" });
return;
}
snapshot.syncedAtMs = Date.now();
sendJson(response, 200, { status: "ok", syncedAt: new Date(snapshot.syncedAtMs).toISOString() });
} catch (error) {
sendJson(response, error.status || 400, { status: "error", msg: "foundry.invalid-heartbeat" });
}
return;
}
if (request.method !== "GET" || !pathname.startsWith("/api/")) {
sendJson(response, 404, { status: "error", msg: "errors.notfound" });
return;
}
if (!hasBearerToken(request, readToken)) {
sendJson(response, 401, { status: "error", msg: "unauthorized" });
return;
}
const current = currentSnapshot(response);
if (!current) return;
if (pathname === "/api/world") return sendData(response, current.world, current);
if (pathname === "/api/actors") return sendData(response, current.actors, current);
if (pathname === "/api/characters") {
return sendData(response, current.actors.filter((actor) => actor.type === "character"), current);
}
if (pathname === "/api/items") return sendData(response, current.items, current);
const actorItemsMatch = /^\/api\/actors\/([^/]+)\/items$/.exec(pathname);
if (actorItemsMatch) {
const actorId = decodePathSegment(actorItemsMatch[1]);
if (!actorId) return sendJson(response, 400, { status: "error", msg: "errors.missing-data" });
const actor = current.actors.find((entry) => entry._id === actorId || entry.id === actorId);
if (!actor) return sendJson(response, 404, { status: "error", msg: "errors.notfound" });
return sendData(response, current.actorItems[actorId] || [], current);
}
const actorMatch = /^\/api\/actors\/([^/]+)$/.exec(pathname);
if (actorMatch) {
const actorId = decodePathSegment(actorMatch[1]);
if (!actorId) return sendJson(response, 400, { status: "error", msg: "errors.missing-data" });
const actor = current.actors.find((entry) => entry._id === actorId || entry.id === actorId);
if (!actor) return sendJson(response, 404, { status: "error", msg: "errors.notfound" });
return sendData(response, actor, current);
}
const itemMatch = /^\/api\/items\/([^/]+)$/.exec(pathname);
if (itemMatch) {
const itemId = decodePathSegment(itemMatch[1]);
if (!itemId) return sendJson(response, 400, { status: "error", msg: "errors.missing-data" });
const item = current.items.find((entry) => entry._id === itemId || entry.id === itemId);
if (!item) return sendJson(response, 404, { status: "error", msg: "errors.notfound" });
return sendData(response, item, current);
}
sendJson(response, 404, { status: "error", msg: "errors.notfound" });
});
server.listen(port, host, () => {
console.info(`Dragonroll Foundry bridge listening on ${host}:${port}`);
});

View File

@@ -0,0 +1,14 @@
{
"id": "dragonroll-foundry",
"title": "Dragonroll Foundry API",
"description": "Links a Foundry world to a Dragonroll campaign and exposes a client-side API for world data.",
"version": "0.3.0",
"library": true,
"compatibility": {
"minimum": "12",
"verified": "14"
},
"esmodules": [
"scripts/api.js"
]
}

View File

@@ -0,0 +1,731 @@
const MODULE_ID = "dragonroll-foundry";
const SETTING_BRIDGE_URL = "bridgeUrl";
const SETTING_PUSH_TOKEN = "pushToken";
const SETTING_BRIDGE_CONFIG = "bridgeConfig";
const SETTING_DRAGONROLL_API_URL = "dragonrollApiUrl";
const SETTING_LINK_CODE = "linkCode";
const SETTING_SYNC_TOKEN = "syncToken";
let syncTimeout;
let syncInProgress = false;
let syncRequested = false;
let handlingLinkCode = false;
let updatingLinkCodeSetting = false;
let linkRetriesDisabled = false;
const FATAL_LINK_ERRORS = new Set([
"foundry.errors.link-expired",
"foundry.errors.world-already-linked",
]);
let actorSyncTimeout;
let characterSyncRunning = false;
let actorSyncErrorLogged = false;
const syncingActorIds = new Set();
const queuedActorChanges = new Map();
function getCollectionContents(collection, collectionName) {
if (!collection) {
throw new Error(`Foundry ${collectionName} collection is not available yet.`);
}
return collection.contents;
}
function toPlainData(document) {
return document?.toObject() ?? null;
}
const api = Object.freeze({
/** Return metadata for the currently loaded world. */
getWorld() {
if (!game.world) return null;
return {
id: game.world.id,
title: game.world.title,
system: game.system.id,
url: window.location.origin,
};
},
/** Return plain data snapshots for all Actor documents in the active world. */
getActors() {
return getCollectionContents(game.actors, "actor").map(toPlainData);
},
/** Return plain data snapshots for Actors whose system type is `character`. */
getCharacters() {
return getCollectionContents(game.actors, "actor")
.filter((actor) => actor.type === "character")
.map(toPlainData);
},
/** Return one Actor snapshot, or null when its id is not in the active world. */
getActor(actorId) {
return toPlainData(game.actors?.get(actorId));
},
/** Return plain data snapshots for world-level Item documents. */
getItems() {
return getCollectionContents(game.items, "item").map(toPlainData);
},
/** Return one world-level Item snapshot, or null when its id is not in the active world. */
getItem(itemId) {
return toPlainData(game.items?.get(itemId));
},
/** Return embedded Item snapshots belonging to an Actor, or null if the Actor is missing. */
getActorItems(actorId) {
const actor = game.actors?.get(actorId);
if (!actor) return null;
return getCollectionContents(actor.items, "actor item").map(toPlainData);
},
});
Hooks.once("init", () => {
game.settings.register(MODULE_ID, SETTING_BRIDGE_URL, {
name: "Legacy bridge URL",
scope: "client",
config: false,
type: String,
default: "",
});
game.settings.register(MODULE_ID, SETTING_PUSH_TOKEN, {
name: "Legacy bridge publish token",
scope: "client",
config: false,
type: String,
default: "",
});
game.settings.register(MODULE_ID, SETTING_BRIDGE_CONFIG, {
name: "Bridge configuration",
scope: "client",
config: false,
type: Object,
default: {},
});
game.settings.register(MODULE_ID, SETTING_SYNC_TOKEN, {
name: "Character sync token",
scope: "client",
config: false,
type: String,
default: "",
});
game.settings.register(MODULE_ID, SETTING_DRAGONROLL_API_URL, {
name: "Dragonroll Endpoint",
hint: "The Dragonroll server URL. The API path is added automatically.",
scope: "client",
config: true,
type: String,
default: "https://dragonroll.aranroig.com",
});
game.settings.register(MODULE_ID, SETTING_LINK_CODE, {
name: "Dragonroll Campaign Pairing Code",
hint: "Paste a pairing code created in Dragonroll campaign settings.",
scope: "client",
config: true,
type: String,
default: "",
onChange: handleLinkCodeChange,
});
const module = game.modules.get(MODULE_ID);
if (!module) {
console.warn(`${MODULE_ID} | Could not register the public API: module was not found.`);
return;
}
module.api = api;
console.info(`${MODULE_ID} | Public API registered.`);
});
function dragonrollEndpoint(path) {
const endpoint = game.settings.get(MODULE_ID, SETTING_DRAGONROLL_API_URL)?.trim();
if (!endpoint) throw new Error("Set the Dragonroll endpoint in the Dragonroll Foundry module settings first.");
const apiBase = new URL(endpoint);
const basePath = apiBase.pathname.replace(/\/+$/, "");
const isLocalBackend = ["localhost", "127.0.0.1", "[::1]"].includes(apiBase.hostname)
&& apiBase.port === "5000";
const hasApiPath = basePath.endsWith("/api");
apiBase.pathname = `${hasApiPath || isLocalBackend ? basePath : `${basePath}/api`}/`;
apiBase.search = "";
apiBase.hash = "";
return new URL(path.replace(/^\/+/, ""), apiBase);
}
async function postDragonroll(path, body, token = "") {
const headers = { "Content-Type": "application/json" };
if (token) headers.Authorization = `Bearer ${token}`;
const response = await fetch(dragonrollEndpoint(path), {
method: "POST",
headers,
body: JSON.stringify(body),
});
const result = await response.json();
if (!response.ok || result.status !== "ok") {
throw new Error(result.msg || `Dragonroll returned HTTP ${response.status}.`);
}
return result;
}
async function getDragonroll(path, token) {
const response = await fetch(dragonrollEndpoint(path), {
headers: { Authorization: `Bearer ${token}` },
});
const result = await response.json();
if (!response.ok || result.status !== "ok") {
throw new Error(result.msg || `Dragonroll returned HTTP ${response.status}.`);
}
return result;
}
function linkErrorMessage(error) {
const messages = {
"foundry.errors.link-expired": "The pairing code is invalid, expired, or already used.",
"foundry.errors.world-already-linked": "This Foundry world is already linked to another campaign.",
};
return messages[error.message] || error.message;
}
async function setLinkCode(value) {
updatingLinkCodeSetting = true;
try {
await game.settings.set(MODULE_ID, SETTING_LINK_CODE, value);
} finally {
updatingLinkCodeSetting = false;
}
}
function handleLinkCodeChange(value) {
if (updatingLinkCodeSetting || handlingLinkCode || !value?.trim()) return;
linkRetriesDisabled = false;
completeDragonrollCampaignLink(value.trim());
}
async function completeDragonrollCampaignLink(code, options = {}) {
if (handlingLinkCode) return;
handlingLinkCode = true;
const notifyOnError = options.notifyOnError !== false;
try {
if (!game.user?.isGM || !game.world) throw new Error("Open the world as a GM to link it.");
const result = await postDragonroll("foundry/link/complete", { code, world: api.getWorld() });
let syncTokenStored = false;
if (result.syncToken) {
try {
await game.settings.set(MODULE_ID, SETTING_SYNC_TOKEN, result.syncToken);
syncTokenStored = true;
} catch (error) {
console.error(`${MODULE_ID} | Could not save the character sync token.`, error);
}
}
if (result.bridgeConfig?.url && result.bridgeConfig?.pushToken) {
try {
await game.settings.set(MODULE_ID, SETTING_BRIDGE_CONFIG, result.bridgeConfig);
} catch (error) {
console.error(`${MODULE_ID} | Could not save the bridge configuration.`, error);
ui.notifications?.warn("The world was linked, but its bridge settings could not be saved on this client.");
}
}
// Keep an unprocessed pairing code in the setting when its sync token could
// not be saved, so the retry below can complete the link again.
if (syncTokenStored || !result.syncToken) await setLinkCode("");
if (!syncTokenStored) {
ui.notifications?.warn("The world was linked, but character sync is unavailable. Update Dragonroll and link the world again.");
}
scheduleSnapshotSync(0);
setTimeout(initializeCharacterSync, 0);
ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign.");
} catch (error) {
console.error(`${MODULE_ID} | Could not complete the campaign link.`, error);
// Expired or already-used codes will never redeem, so stop the background
// retry; any error keeps retrying (the Dragonroll server may be restarting).
linkRetriesDisabled = FATAL_LINK_ERRORS.has(error.message);
if (notifyOnError) ui.notifications?.error(linkErrorMessage(error));
} finally {
handlingLinkCode = false;
}
}
// A pairing code entered while the Dragonroll server was unreachable (or just
// before Foundry restarted) stays in the setting; redeem it on world start so
// the connection survives restarts without typing the code in again.
async function resumePendingDragonrollLink(options = {}) {
if (handlingLinkCode || !game.user?.isGM || !game.world) return;
const code = game.settings.get(MODULE_ID, SETTING_LINK_CODE)?.trim();
if (code) await completeDragonrollCampaignLink(code, options);
}
function scheduleSnapshotSync(delay = 500) {
clearTimeout(syncTimeout);
syncTimeout = setTimeout(publishSnapshot, delay);
}
function getBridgeConfig() {
const configured = game.settings.get(MODULE_ID, SETTING_BRIDGE_CONFIG);
if (configured?.url?.trim() && configured?.pushToken?.trim()) return configured;
const legacy = {
url: game.settings.get(MODULE_ID, SETTING_BRIDGE_URL)?.trim(),
pushToken: game.settings.get(MODULE_ID, SETTING_PUSH_TOKEN)?.trim(),
};
return legacy.url && legacy.pushToken ? legacy : null;
}
function getSyncToken() {
return game.settings.get(MODULE_ID, SETTING_SYNC_TOKEN)?.trim() || "";
}
function dragonrollActorId(actor) {
return actor.getFlag?.(MODULE_ID, "actorId") || actor.flags?.[MODULE_ID]?.actorId || "";
}
function serializeFoundryActor(actor) {
const data = {
...toPlainData(actor),
items: actor.items?.contents?.map(toPlainData) || [],
};
if (data.img && !/^(https?:|data:|\/\/)/i.test(data.img)) {
data.img = new URL(data.img, window.location.origin).toString();
}
return data;
}
function isSupportedCharacterActor(actor) {
const savedType = actor.getFlag?.(MODULE_ID, "actorType") || actor.flags?.[MODULE_ID]?.actorType;
return ["character", "npc", "creature"].includes(savedType || actor.type);
}
async function markActorItemsAsSynced(actor) {
const updates = actor.items.contents
.filter((item) => !item.getFlag?.(MODULE_ID, "syncedItem"))
.map((item) => ({
_id: item.id,
[`flags.${MODULE_ID}.syncedItem`]: true,
}));
if (updates.length) {
await withActorSyncSuppressed(actor, () => actor.updateEmbeddedDocuments("Item", updates));
}
}
async function withActorSyncSuppressed(actor, callback) {
if (!actor?.id) return callback();
syncingActorIds.add(actor.id);
try {
return await callback();
} finally {
syncingActorIds.delete(actor.id);
}
}
async function setDragonrollActorId(actor, actorId) {
if (!actor || !actorId) return;
await withActorSyncSuppressed(actor, () => actor.update({
[`flags.${MODULE_ID}.actorId`]: String(actorId),
[`flags.${MODULE_ID}.syncMutation`]: false,
}));
}
function reportActorSyncError(error) {
if (actorSyncErrorLogged) return;
actorSyncErrorLogged = true;
console.warn(`${MODULE_ID} | Character sync failed and will retry.`, error);
}
async function pushFoundryActors(actors, fullSync = false) {
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || (!actors.length && !fullSync)) return;
if (game.system.id !== "dnd5e") {
throw new Error("Character sync currently requires the D&D 5e Foundry system.");
}
const supportedActors = actors.filter(isSupportedCharacterActor);
for (const actor of supportedActors) await markActorItemsAsSynced(actor);
const result = await postDragonroll("foundry/sync/snapshot", {
worldId: game.world.id,
actors: supportedActors.map(serializeFoundryActor),
fullSync,
}, token);
for (const mapping of result.actors || []) {
const actor = game.actors.get(mapping.foundryActorId);
if (actor && dragonrollActorId(actor) !== mapping.actorId) {
await setDragonrollActorId(actor, mapping.actorId);
}
}
actorSyncErrorLogged = false;
}
async function deleteDragonrollActor(foundryActorId) {
const token = getSyncToken();
if (!token || !game.world || !foundryActorId) return;
await postDragonroll("foundry/sync/delete", {
worldId: game.world.id,
foundryActorId,
}, token);
}
function queueActorChange(kind, actor) {
if (!actor || !game.user?.isGM || !getSyncToken()) return;
if (syncingActorIds.has(actor.id) || actor.flags?.[MODULE_ID]?.syncMutation) return;
queuedActorChanges.set(actor.id, { kind, actor });
clearTimeout(actorSyncTimeout);
actorSyncTimeout = setTimeout(flushActorChanges, 400);
}
async function flushActorChanges() {
const changes = [...queuedActorChanges.values()];
queuedActorChanges.clear();
const deleted = changes.filter((change) => change.kind === "delete");
const changed = changes.filter((change) => change.kind !== "delete");
try {
for (const change of deleted) await deleteDragonrollActor(change.actor.id);
await pushFoundryActors(changed.map((change) => change.actor));
} catch (error) {
reportActorSyncError(error);
for (const change of changes) queuedActorChanges.set(change.actor.id, change);
clearTimeout(actorSyncTimeout);
actorSyncTimeout = setTimeout(flushActorChanges, 5000);
}
}
function getDragonrollImageUrl(image) {
if (!image) return "";
if (/^(https?:|data:|\/\/)/i.test(image)) return image;
const endpoint = new URL(game.settings.get(MODULE_ID, SETTING_DRAGONROLL_API_URL));
const basePath = endpoint.pathname.replace(/\/+$/, "");
endpoint.pathname = `${basePath.endsWith("/api") ? basePath : `${basePath}/api`}/public/${encodeURIComponent(image)}`;
endpoint.search = "";
endpoint.hash = "";
return endpoint.toString();
}
function makeFoundryCharacterData(entry) {
const stats = entry.abilityScores || {};
const items = [];
if (entry.className) items.push({ name: entry.className, type: "class", system: { levels: Number(entry.level) || 1 } });
if (entry.subclass) items.push({ name: entry.subclass, type: "subclass" });
if (entry.background) items.push({ name: entry.background, type: "background" });
for (const name of String(entry.spells || "").split("\n").map((value) => value.trim()).filter(Boolean)) {
items.push({ name, type: "spell" });
}
for (const item of entry.inventory || []) {
if (!item.name?.trim()) continue;
items.push({
name: item.name.trim(),
type: "loot",
system: { quantity: Number(item.quantity) || 1, weight: { value: Number(item.weight) || 0 } },
});
}
return {
name: entry.name,
type: entry.type === "character" ? "character" : "npc",
img: getDragonrollImageUrl(entry.image) || undefined,
system: {
details: {
race: entry.species || "",
level: Number(entry.level) || 1,
background: entry.background || "",
biography: { value: entry.description || "" },
cr: entry.challengeRating || "",
},
abilities: Object.fromEntries(["str", "dex", "con", "int", "wis", "cha"].map((key) => [
key,
{ value: Number(stats[key]) || 10 },
])),
attributes: {
ac: { value: Number(entry.armorClass) || 10 },
movement: { walk: Number(entry.speed) || 30 },
},
},
items,
flags: { [MODULE_ID]: {
actorId: String(entry._id),
actorType: entry.type,
traits: entry.traits || "",
proficiencies: entry.proficiencies || "",
syncMutation: true,
} },
};
}
function documentValue(document, path) {
return path.split(".").reduce((value, key) => value?.[key], document);
}
function characterUpdateData(entry) {
const stats = entry.abilityScores || {};
const updates = {
name: entry.name,
img: getDragonrollImageUrl(entry.image) || "icons/svg/mystery-man.svg",
"system.details.race": entry.species || "",
"system.details.level": Number(entry.level) || 1,
"system.details.background": entry.background || "",
"system.details.biography.value": entry.description || "",
"system.details.cr": entry.challengeRating || "",
[`flags.${MODULE_ID}.traits`]: entry.traits || "",
[`flags.${MODULE_ID}.proficiencies`]: entry.proficiencies || "",
"system.attributes.ac.value": Number(entry.armorClass) || 10,
"system.attributes.movement.walk": Number(entry.speed) || 30,
};
for (const key of ["str", "dex", "con", "int", "wis", "cha"]) {
updates[`system.abilities.${key}.value`] = Number(stats[key]) || 10;
}
return updates;
}
async function reconcileEmbeddedItems(actor, entry) {
const desired = [];
if (entry.className) desired.push({ type: "class", name: entry.className, system: { levels: Number(entry.level) || 1 } });
if (entry.subclass) desired.push({ type: "subclass", name: entry.subclass });
if (entry.background) desired.push({ type: "background", name: entry.background });
for (const name of String(entry.spells || "").split("\n").map((value) => value.trim()).filter(Boolean)) {
desired.push({ type: "spell", name });
}
for (const item of entry.inventory || []) {
if (item.name?.trim()) desired.push({
type: "loot",
name: item.name.trim(),
system: { quantity: Number(item.quantity) || 1, weight: { value: Number(item.weight) || 0 } },
});
}
const retainedIds = new Set();
for (const wanted of desired) {
const existing = actor.items.contents.find((item) => item.name === wanted.name
&& item.type === wanted.type && item.getFlag?.(MODULE_ID, "syncedItem"))
|| actor.items.contents.find((item) => item.name === wanted.name
&& item.getFlag?.(MODULE_ID, "syncedItem"));
if (existing) {
retainedIds.add(existing.id);
const update = { _id: existing.id };
const expected = { name: wanted.name };
if (wanted.system?.levels !== undefined) expected["system.levels"] = wanted.system.levels;
if (wanted.system?.quantity !== undefined) expected["system.quantity"] = wanted.system.quantity;
if (wanted.system?.weight?.value !== undefined) expected["system.weight.value"] = wanted.system.weight.value;
let changed = false;
for (const [key, value] of Object.entries(expected)) {
if (documentValue(existing, key) !== value) {
update[key] = value;
changed = true;
}
}
if (changed) await actor.updateEmbeddedDocuments("Item", [update]);
} else {
const created = await actor.createEmbeddedDocuments("Item", [{
...wanted,
flags: { [MODULE_ID]: { syncedItem: true } },
}]);
for (const item of created) retainedIds.add(item.id);
}
}
const staleItemIds = actor.items.contents
.filter((item) => item.getFlag?.(MODULE_ID, "syncedItem") && !retainedIds.has(item.id))
.map((item) => item.id);
if (staleItemIds.length) await actor.deleteEmbeddedDocuments("Item", staleItemIds);
}
async function applyDragonrollCharacter(actor, entry) {
const updates = characterUpdateData(entry);
const changed = Object.entries(updates).some(([key, value]) => documentValue(actor, key) !== value);
await withActorSyncSuppressed(actor, async () => {
if (changed) await actor.update(updates);
await reconcileEmbeddedItems(actor, entry);
if (dragonrollActorId(actor) !== String(entry._id)
|| actor.getFlag?.(MODULE_ID, "actorType") !== entry.type) {
await actor.update({
[`flags.${MODULE_ID}.actorId`]: String(entry._id),
[`flags.${MODULE_ID}.actorType`]: entry.type,
});
}
});
}
async function mapDragonrollActor(actorId, foundryActorId) {
const token = getSyncToken();
return postDragonroll("foundry/sync/map", {
worldId: game.world.id,
actorId: String(actorId),
foundryActorId: String(foundryActorId),
}, token);
}
async function createFoundryCharacter(entry) {
if (game.system.id !== "dnd5e") {
throw new Error("Character sync currently requires the D&D 5e Foundry system.");
}
const actor = await Actor.create(makeFoundryCharacterData(entry), { renderSheet: false });
if (!actor) return;
await withActorSyncSuppressed(actor, async () => {
await actor.update({ [`flags.${MODULE_ID}.syncMutation`]: false });
});
await mapDragonrollActor(entry._id, actor.id);
}
async function reconcileDragonrollCharacters() {
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || characterSyncRunning) return;
characterSyncRunning = true;
try {
if (game.system.id !== "dnd5e") {
throw new Error("Character sync currently requires the D&D 5e Foundry system.");
}
const result = await getDragonroll("foundry/sync/characters", token);
const remoteActors = result.actors || [];
const remoteById = new Map(remoteActors.map((actor) => [String(actor._id), actor]));
const localByRemoteId = new Map(game.actors.contents
.map((actor) => [String(dragonrollActorId(actor)), actor])
.filter(([actorId]) => actorId));
const retainedFoundryIds = new Set();
for (const entry of remoteActors) {
let actor = entry.foundryActorId ? game.actors.get(entry.foundryActorId) : null;
if (!actor) actor = localByRemoteId.get(String(entry._id));
if (actor) {
retainedFoundryIds.add(actor.id);
await applyDragonrollCharacter(actor, entry);
if (!entry.foundryActorId) await mapDragonrollActor(entry._id, actor.id);
} else {
await createFoundryCharacter(entry);
}
}
for (const actor of game.actors.contents) {
const actorId = dragonrollActorId(actor);
if (!actorId || retainedFoundryIds.has(actor.id) || remoteById.has(String(actorId))) continue;
await withActorSyncSuppressed(actor, () => actor.delete());
}
actorSyncErrorLogged = false;
} catch (error) {
reportActorSyncError(error);
} finally {
characterSyncRunning = false;
}
}
async function initializeCharacterSync() {
if (!getSyncToken() || !game.user?.isGM || !game.world) return;
try {
await pushFoundryActors(game.actors.contents, true);
await reconcileDragonrollCharacters();
} catch (error) {
reportActorSyncError(error);
scheduleDragonrollCharacterSync(15000);
}
}
function queueFoundryActorChange(kind, actor) {
if (kind !== "delete" && (actor.flags?.[MODULE_ID]?.syncMutation || syncingActorIds.has(actor.id))) return;
queueActorChange(kind, actor);
}
async function publishSnapshot() {
if (!game.user?.isGM || !game.world) return;
if (syncInProgress) {
syncRequested = true;
return;
}
const bridgeConfig = getBridgeConfig();
if (!bridgeConfig) return;
syncInProgress = true;
try {
const actorItems = Object.fromEntries(
game.actors.contents.map((actor) => [
actor.id,
actor.items.contents.map(toPlainData),
]),
);
const response = await fetch(new URL("internal/snapshot", `${bridgeConfig.url.replace(/\/+$/, "")}/`), {
method: "POST",
headers: {
"Authorization": `Bearer ${bridgeConfig.pushToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
world: api.getWorld(),
actors: api.getActors(),
items: api.getItems(),
actorItems,
}),
});
if (!response.ok) {
throw new Error(`Bridge returned HTTP ${response.status}.`);
}
} catch (error) {
console.error(`${MODULE_ID} | Could not publish the world snapshot.`, error);
scheduleSnapshotSync(15000);
} finally {
syncInProgress = false;
if (syncRequested) {
syncRequested = false;
scheduleSnapshotSync();
}
}
}
async function publishHeartbeat() {
if (!game.user?.isGM || !game.world) return;
const bridgeConfig = getBridgeConfig();
if (!bridgeConfig) return;
try {
const response = await fetch(new URL("internal/heartbeat", `${bridgeConfig.url.replace(/\/+$/, "")}/`), {
method: "POST",
headers: {
"Authorization": `Bearer ${bridgeConfig.pushToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ worldId: game.world.id }),
});
if (response.status === 409 || response.status === 503) {
scheduleSnapshotSync(0);
return;
}
if (!response.ok) throw new Error(`Bridge returned HTTP ${response.status}.`);
} catch (error) {
console.warn(`${MODULE_ID} | Bridge heartbeat failed.`, error);
scheduleSnapshotSync(15000);
}
}
Hooks.once("ready", () => {
resumePendingDragonrollLink();
setInterval(() => {
if (linkRetriesDisabled) return;
resumePendingDragonrollLink({ notifyOnError: false });
}, 60000);
scheduleSnapshotSync(0);
setInterval(publishHeartbeat, 60000);
setTimeout(initializeCharacterSync, 1000);
setInterval(reconcileDragonrollCharacters, 5000);
for (const event of [
"createActor", "updateActor", "deleteActor",
"createItem", "updateItem", "deleteItem",
]) {
Hooks.on(event, (document) => {
scheduleSnapshotSync();
const actor = document.documentName === "Actor" ? document : document.parent;
if (actor?.documentName === "Actor") {
queueFoundryActorChange(event.startsWith("delete") ? "delete" : "upsert", actor);
}
});
}
});