Merge pull request 'Fix #8: Sync toggle on foundry' (#9) from ai/issue-8 into master
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 50s

Reviewed-on: #9
This commit was merged in pull request #9.
This commit is contained in:
2026-10-14 12:00:17 +00:00
6 changed files with 439 additions and 9 deletions

View File

@@ -12,8 +12,10 @@ dice widgets, shared markdown, sounds). It is a two-app monorepo:
- `backend/` — Node + **Express 5** + **Mongoose 9** (MongoDB) REST API, JWT auth. CommonJS.
- `frontend/` — **Nuxt 4 / Vue 3** client (Composition API, `<script setup>`), SCSS, axios, marked, mitt, motion.
There is **no** database seeding, no ORM migrations, no test suite, no linter/formatter config, no
Pinia/Vuex, and no Vue Router pages (see §5.1 — the UI is a window manager, not routed pages).
There is **no** database seeding, no ORM migrations, no linter/formatter config, no Pinia/Vuex, and no
Vue Router pages (see §5.1 — the UI is a window manager, not routed pages). The only automated tests
are `tests/*.test.js` (`npm test`, Node's built-in runner), which exercise the Foundry module's sync
logic against stubbed Foundry globals.
Git: default branch `master`, hosted on a self-hosted Gitea (`git.aranroig.com/BinarySandia04/Dragonroll`).
CI (`.gitea/workflows/deploy.yml`) builds two Docker images on every push to `master`, pushes them to
@@ -31,6 +33,7 @@ dragonroll/
├── ecosystem.config.js PM2 config (stale: runs `npm start`, which does not exist — see §9)
├── .gitea/workflows/deploy.yml
├── static/media/ README logo images only
├── tests/ `node --test` tests (Foundry module sync toggle)
├── package.json root: only `concurrently`, used by `npm run dev`
└── README.md install/run instructions are STALE (see §9)
```
@@ -49,10 +52,13 @@ npm --prefix backend run dev # backend only
npm --prefix frontend run dev # frontend only
npm --prefix frontend run build # nuxt build --dotenv .env.production
npm --prefix frontend run preview
npm test # node --test tests/ (Foundry module sync logic, no dependencies)
```
There is no `start` script in either package, no test command, and no lint command.
Verification = run the dev server and exercise the flow (`/api/test` returns a JSON hello).
There is no `start` script in either package and no lint command.
Verification = run the dev server and exercise the flow (`/api/test` returns a JSON hello);
`npm test` covers the Foundry character/item sync toggle and per-actor force sync.
### Environment files
@@ -240,6 +246,10 @@ Rules worth knowing before editing this:
which the sync skips.
- **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events
overwrite. Item pruning requires the full snapshot, since only it sees world items and actor copies.
- **Autosync is a Foundry-side switch** (`autoSync` client setting, on by default): when off, the
module queues no CRUD push, runs no periodic reconcile and sends no startup snapshot; the actor
directory's `Dragonroll: Force Sync` entry still pushes the selected actors as an upsert
(`fullSync:false`, so it never prunes). The read-only bridge snapshot is not gated by it.
- `Actor.inventory` stays a flattened copy of the actor's embedded items; it is not linked to `Item`.
- `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only
bridge, only useful when `FOUNDRY_API_URL` is configured.

View File

@@ -53,6 +53,25 @@ within about five seconds. The module currently creates Dragonroll characters in
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.
### Auto-sync, and sending one actor on purpose
**Dragonroll Auto-sync** in the module settings (on by default) is what keeps the campaign and this
world in step: actors and world items the GM creates, updates or deletes are sent to Dragonroll, and
both sides reconcile every few seconds. Turn it off to stop synchronizing altogether — nothing is
sent to the campaign, and Dragonroll stops rewriting those documents in Foundry, so the campaign
keeps whatever it already holds. Turn it back on to reconcile both sides again; the Foundry edits
queued while it was off are sent as the world catches up.
With autosync off — or any time a single character needs to cross over right now — right-click an
actor (or several selected ones) in the Foundry actor directory and pick **Dragonroll: Force Sync**.
Those actors, together with the gear carried inside them, are pushed to the campaign immediately even
when autosync is off. It is an upsert only: it never prunes the campaign's other actors, which a full
snapshot does and a forced sync never claims to. Actors Dragonroll does not import (anything that is
not a character, NPC or creature) are refused with a notification.
The optional read-only snapshot bridge is not affected: it keeps publishing the world snapshot behind
`/api/foundry/*`, which is never written into the campaign.
### Items
The campaign's Item list is synchronized with the world's gear, both ways:

View File

@@ -2,7 +2,7 @@
"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",
"version": "0.4.0",
"library": true,
"compatibility": {
"minimum": "12",

View File

@@ -5,6 +5,7 @@ const SETTING_BRIDGE_CONFIG = "bridgeConfig";
const SETTING_DRAGONROLL_API_URL = "dragonrollApiUrl";
const SETTING_LINK_CODE = "linkCode";
const SETTING_SYNC_TOKEN = "syncToken";
const SETTING_AUTO_SYNC = "autoSync";
let syncTimeout;
let syncInProgress = false;
let syncRequested = false;
@@ -139,6 +140,16 @@ Hooks.once("init", () => {
onChange: handleLinkCodeChange,
});
game.settings.register(MODULE_ID, SETTING_AUTO_SYNC, {
name: "Dragonroll Auto-sync",
hint: "Keep the linked Dragonroll campaign in step with this world as its actors and items change. Turn this off to stop synchronizing; the actor directory's Dragonroll: Force Sync entry then sends an actor over only when you ask for it.",
scope: "client",
config: true,
type: Boolean,
default: true,
onChange: handleAutoSyncChange,
});
const module = game.modules.get(MODULE_ID);
if (!module) {
console.warn(`${MODULE_ID} | Could not register the public API: module was not found.`);
@@ -287,6 +298,35 @@ function getSyncToken() {
return game.settings.get(MODULE_ID, SETTING_SYNC_TOKEN)?.trim() || "";
}
// Autosync is what the module has always done: every Foundry create, update and
// delete pushes to Dragonroll, and both sides reconcile on a timer. When it is
// off, nothing syncs on its own and only a forced actor sync reaches Dragonroll.
function isAutoSyncEnabled() {
return game.settings.get(MODULE_ID, SETTING_AUTO_SYNC) !== false;
}
function handleAutoSyncChange(value) {
if (value === false) {
clearTimeout(actorSyncTimeout);
clearTimeout(itemSyncTimeout);
return;
}
if (!game.user?.isGM || !getSyncToken()) return;
// Switching it back on converges both sides again, then the changes queued
// while autosync was off are pushed so this world's state wins over them.
initializeCharacterSync();
reconcileDragonrollItems();
if (queuedActorChanges.size) {
clearTimeout(actorSyncTimeout);
actorSyncTimeout = setTimeout(flushActorChanges, 400);
}
if (queuedItemChanges.size) {
clearTimeout(itemSyncTimeout);
itemSyncTimeout = setTimeout(flushItemChanges, 400);
}
}
function dragonrollActorId(actor) {
return actor.getFlag?.(MODULE_ID, "actorId") || actor.flags?.[MODULE_ID]?.actorId || "";
}
@@ -380,6 +420,34 @@ async function deleteDragonrollActor(foundryActorId) {
}, token);
}
// Sending actors on purpose, whether or not autosync is on: this is the push the
// GM asks for. It upserts those actors only, so unlike a full snapshot it never
// prunes anything else the campaign holds.
async function forceSyncActorsToDragonroll(actors) {
if (!game.user?.isGM || !game.world || !actors.length) return;
if (!getSyncToken()) {
ui.notifications?.warn("Link this world to a Dragonroll campaign before syncing actors to it.");
return;
}
const supported = actors.filter(isSupportedCharacterActor);
const refused = actors.filter((actor) => !supported.includes(actor));
if (refused.length) {
ui.notifications?.warn(`${refused.map((actor) => actor.name).join(", ")} ${refused.length === 1 ? "is" : "are"} not a character, NPC or creature: Dragonroll does not import ${refused.length === 1 ? "it" : "them"}.`);
}
if (!supported.length) return;
try {
await pushFoundryActors(supported);
ui.notifications?.info(supported.length === 1
? `${supported[0].name} was sent to the Dragonroll campaign.`
: `${supported.length} actors were sent to the Dragonroll campaign.`);
} catch (error) {
console.error(`${MODULE_ID} | Could not force sync the selected actors.`, error);
ui.notifications?.error(`Dragonroll sync failed: ${error.message}`);
}
}
function queueActorChange(kind, actor) {
if (!actor || !game.user?.isGM || !getSyncToken()) return;
if (syncingActorIds.has(actor.id) || actor.flags?.[MODULE_ID]?.syncMutation) return;
@@ -389,6 +457,9 @@ function queueActorChange(kind, actor) {
actorSyncTimeout = setTimeout(flushActorChanges, 400);
}
async function flushActorChanges() {
// Autosync may have been switched off while changes were queued: keep them
// waiting so turning it back on still sends them.
if (!isAutoSyncEnabled()) return;
const changes = [...queuedActorChanges.values()];
queuedActorChanges.clear();
const deleted = changes.filter((change) => change.kind === "delete");
@@ -518,6 +589,8 @@ function queueFoundryItemChange(kind, item) {
}
async function flushItemChanges() {
// Autosync off: the queued edits wait here, like the actor changes do.
if (!isAutoSyncEnabled()) return;
const changes = [...queuedItemChanges.values()];
queuedItemChanges.clear();
const deleted = changes.filter((change) => change.kind === "delete");
@@ -616,7 +689,7 @@ async function createFoundryWorldItem(entry) {
async function reconcileDragonrollItems() {
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || itemSyncRunning) return;
if (!token || !game.user?.isGM || !game.world || itemSyncRunning || !isAutoSyncEnabled()) return;
itemSyncRunning = true;
try {
if (game.system.id !== "dnd5e") {
@@ -847,7 +920,7 @@ async function createFoundryCharacter(entry) {
async function reconcileDragonrollCharacters() {
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || characterSyncRunning) return;
if (!token || !game.user?.isGM || !game.world || characterSyncRunning || !isAutoSyncEnabled()) return;
characterSyncRunning = true;
try {
if (game.system.id !== "dnd5e") {
@@ -887,7 +960,7 @@ async function reconcileDragonrollCharacters() {
}
async function initializeCharacterSync() {
if (!getSyncToken() || !game.user?.isGM || !game.world) return;
if (!getSyncToken() || !game.user?.isGM || !game.world || !isAutoSyncEnabled()) return;
try {
await pushFoundryActors(game.actors.contents, true);
await reconcileDragonrollCharacters();
@@ -1016,3 +1089,21 @@ Hooks.once("ready", () => {
});
}
});
// A GM sends selected actors to Dragonroll from the actor directory's context
// menu. This works with autosync on and off: it is the one push done on purpose.
Hooks.on("getActorDirectoryEntryContext", (html, options) => {
if (!game.user?.isGM || !getSyncToken()) return;
options.push({
name: "Dragonroll: Force Sync",
icon: '<i class="fa-solid fa-rotate"></i>',
// Array.from: the selected entries are jQuery in Foundry 12 and a plain
// array afterwards, and both are array-like.
callback: (entries) => forceSyncActorsToDragonroll(
Array.from(entries || [])
.map((entry) => game.actors?.get(entry.dataset?.actorId))
.filter(Boolean),
),
});
});

View File

@@ -3,6 +3,7 @@
"concurrently": "^9.2.1"
},
"scripts": {
"dev": "concurrently -k -n BACKEND,FRONTEND,DISCORD-BOT,FOUNDRY -c blue,green,yellow,magenta \"DEBUG=* npm --prefix backend run dev\" \"npm --prefix frontend run dev\" \"npm --prefix discord-bot start\" \"node scripts/run-foundry.js\""
"dev": "concurrently -k -n BACKEND,FRONTEND,DISCORD-BOT,FOUNDRY -c blue,green,yellow,magenta \"DEBUG=* npm --prefix backend run dev\" \"npm --prefix frontend run dev\" \"npm --prefix discord-bot start\" \"node scripts/run-foundry.js\"",
"test": "node --test tests/"
}
}

View File

@@ -0,0 +1,309 @@
// Tests for the Dragonroll Foundry module's sync toggle and per-actor force sync
// (Syndria98/dragonroll#8). The module is a Foundry client script with no module
// wrapper, so it is loaded into a `node:vm` context holding stubbed Foundry
// globals (`game`, `Hooks`, `ui`, `fetch`) with fake timers: that makes every
// queued push, retry and reconcile observable without a running Foundry VTT.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const MODULE_ID = "dragonroll-foundry";
const MODULE_SOURCE = fs.readFileSync(
path.join(__dirname, "..", "dragonroll-foundry", "scripts", "api.js"),
"utf8",
);
function stubDocument(id, name, extra = {}) {
return {
id,
name,
flags: {},
getFlag(module, key) { return this.flags?.[module]?.[key]; },
async update(data) {
for (const [key, value] of Object.entries(data)) {
const parts = key.split(".");
const last = parts.pop();
let target = this;
for (const part of parts) target = target[part] ??= {};
target[last] = value;
}
return this;
},
toObject() {
return {
_id: this.id,
name: this.name,
type: this.type,
img: "icons/svg/mystery-man.svg",
flags: this.flags,
...(this.system ? { system: this.system } : {}),
};
},
...extra,
};
}
function makeWorldItem(id, name) {
return stubDocument(id, name, {
documentName: "Item",
type: "weapon",
parent: null,
system: { properties: { value: [] }, quantity: 1, weight: 3, rarity: "common" },
});
}
function makeStubWorld({ autoSync = true } = {}) {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
notifications: [],
timers: new Map(),
nextTimerId: 1,
};
const actors = [
stubDocument("actor-1", "Thalia", { documentName: "Actor", type: "character", items: { contents: [] } }),
stubDocument("actor-2", "Grunt", { documentName: "Actor", type: "npc", items: { contents: [] } }),
];
const settingsStore = {
autoSync,
syncToken: "sync-token-1",
dragonrollApiUrl: "http://backend.test:5000",
};
const sandbox = {
console: { log() {}, info() {}, warn() {}, error() {} },
URL,
CONFIG: {},
window: { location: { origin: "http://vtt.test" } },
ui: {
notifications: {
info: (text) => state.notifications.push(["info", text]),
warn: (text) => state.notifications.push(["warn", text]),
error: (text) => state.notifications.push(["error", text]),
},
},
Hooks: {
once(name, fn) { state.hooks.set(name, [fn]); },
on(name, fn) {
const handlers = state.hooks.get(name) || [];
handlers.push(fn);
state.hooks.set(name, handlers);
},
},
// Fake timers: the module debounces and retries with setTimeout, so the tests
// decide when those callbacks run instead of waiting on the wall clock.
setTimeout: (fn, delay = 0) => {
const id = state.nextTimerId++;
state.timers.set(id, { fn, delay });
return id;
},
clearTimeout: (id) => state.timers.delete(id),
setInterval: () => 0,
clearInterval: () => {},
fetch: async (url, options = {}) => {
state.requests.push({
href: String(url),
method: options.method,
body: options.body ? JSON.parse(options.body) : null,
});
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
},
Actor: { async create() { return null; } },
Item: { async create() { return null; } },
};
sandbox.game = {
user: { isGM: true },
world: { id: "world-1", title: "Test World" },
system: { id: "dnd5e" },
modules: { get: () => ({}) },
actors: { contents: actors, get: (id) => actors.find((actor) => actor.id === id) },
items: { contents: [], get: () => null },
settings: {
register(module, key, definition) {
state.registered.set(key, definition);
if (!(key in settingsStore)) settingsStore[key] = definition.default;
},
get(module, key) { return settingsStore[key]; },
async set(module, key, value) {
settingsStore[key] = value;
await state.registered.get(key)?.onChange?.(value);
},
},
};
vm.createContext(sandbox);
vm.runInContext(MODULE_SOURCE, sandbox);
state.game = sandbox.game;
state.actor = (id) => actors.find((document) => document.id === id);
state.syncRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync"));
state.fire = async (name, ...args) => {
for (const handler of state.hooks.get(name) || []) await handler(...args);
await drain();
};
state.runTimers = async () => {
for (let round = 0; round < 6; round += 1) {
if (!state.timers.size && round > 2) break;
const due = [...state.timers.values()];
state.timers.clear();
for (const timer of due) await timer.fn();
await drain();
}
};
async function drain() {
await new Promise((resolve) => setImmediate(resolve));
}
state.linkedSetup = async () => {
await state.fire("init");
await state.fire("ready");
await state.runTimers();
state.requests.length = 0;
return state;
};
return state;
}
async function forceSyncActors(world, ...actorIds) {
const options = [];
await world.fire("getActorDirectoryEntryContext", null, options);
const entry = options.find((option) => option.name === "Dragonroll: Force Sync");
assert.ok(entry, "Dragonroll: Force Sync is offered in the actor directory context menu");
await entry.callback(actorIds.map((actorId) => ({ dataset: { actorId } })));
await world.runTimers();
}
test("auto-sync is a module setting that is on by default", async () => {
const world = makeStubWorld();
await world.fire("init");
const setting = world.registered.get("autoSync");
assert.equal(setting.default, true, "autosync is on by default");
assert.equal(setting.config, true, "autosync appears in the module settings");
assert.equal(world.game.settings.get(MODULE_ID, "autoSync"), true);
});
test("autosync on: Foundry CRUD events keep syncing with Dragonroll", async () => {
const world = await makeStubWorld().linkedSetup();
await world.fire("updateActor", world.actor("actor-1"));
await world.runTimers();
const pushes = world.syncRequests();
assert.equal(pushes.length, 1);
assert.equal(pushes[0].body.actors[0]._id, "actor-1");
});
test("autosync off: CRUD requests stop syncing", async () => {
const world = await makeStubWorld().linkedSetup();
await world.game.settings.set(MODULE_ID, "autoSync", false);
await world.fire("updateActor", world.actor("actor-1"));
await world.fire("deleteActor", world.actor("actor-2"));
await world.fire("createItem", makeWorldItem("item-1", "Longsword"));
await world.runTimers();
assert.deepEqual(world.syncRequests(), []);
});
test("edits made while autosync is off are delivered when it is turned back on", async () => {
const world = await makeStubWorld().linkedSetup();
await world.game.settings.set(MODULE_ID, "autoSync", false);
await world.fire("updateActor", world.actor("actor-1"));
await world.fire("createItem", makeWorldItem("item-1", "Longsword"));
await world.runTimers();
assert.deepEqual(world.syncRequests(), []);
await world.game.settings.set(MODULE_ID, "autoSync", true);
await world.runTimers();
const pushes = world.syncRequests();
assert.ok(pushes.some((request) => request.body?.fullSync === false
&& request.body.actors?.some((actor) => actor._id === "actor-1")),
"the actor edit queued while autosync was off is sent");
assert.ok(pushes.some((request) => request.href.includes("foundry/sync/item-snapshot")
&& request.body.items.some((item) => item._id === "item-1")),
"the item edit queued while autosync was off is sent");
});
test("autosync off at world start: no snapshot and no reconcile", async () => {
const world = makeStubWorld({ autoSync: false });
await world.fire("init");
await world.fire("ready");
await world.runTimers();
assert.deepEqual(world.syncRequests(), []);
});
test("force sync sends selected actors to Dragonroll even with autosync off", async () => {
const world = await makeStubWorld().linkedSetup();
await world.game.settings.set(MODULE_ID, "autoSync", false);
await forceSyncActors(world, "actor-2");
const pushes = world.syncRequests();
assert.equal(pushes.length, 1);
assert.equal(pushes[0].body.fullSync, false, "a forced actor never prunes the campaign");
assert.deepEqual(pushes[0].body.actors.map((actor) => actor._id), ["actor-2"]);
assert.deepEqual(world.notifications.filter(([kind]) => kind !== "info"), []);
});
test("force sync sends every selected actor in one push", async () => {
const world = await makeStubWorld().linkedSetup();
await world.game.settings.set(MODULE_ID, "autoSync", false);
await forceSyncActors(world, "actor-1", "actor-2");
const pushes = world.syncRequests();
assert.equal(pushes.length, 1);
assert.deepEqual(pushes[0].body.actors.map((actor) => actor._id), ["actor-1", "actor-2"]);
});
test("force sync also works while autosync is on", async () => {
const world = await makeStubWorld().linkedSetup();
await forceSyncActors(world, "actor-1");
assert.deepEqual(world.syncRequests()[0]?.body.actors.map((actor) => actor._id), ["actor-1"]);
});
test("force sync refuses an actor Dragonroll does not import", async () => {
const world = makeStubWorld({ autoSync: false });
await world.fire("init");
const cart = stubDocument("actor-3", "Cart", { documentName: "Actor", type: "vehicle", items: { contents: [] } });
world.game.actors.contents.push(cart);
await forceSyncActors(world, "actor-3");
assert.deepEqual(world.syncRequests(), []);
assert.ok(world.notifications.some(([kind, text]) => kind === "warn" && text.includes("Cart")));
});
test("turning autosync back on reconciles both sides again", async () => {
const world = makeStubWorld({ autoSync: false });
await world.fire("init");
await world.fire("ready");
await world.runTimers();
assert.deepEqual(world.syncRequests(), []);
await world.game.settings.set(MODULE_ID, "autoSync", true);
await world.runTimers();
assert.ok(world.syncRequests().some((request) => request.body?.fullSync === true),
"the world sends its full snapshot again");
assert.ok(world.requests.some((request) => request.href.includes("foundry/sync/characters")),
"Dragonroll documents are applied back into the world");
});