8 Commits

Author SHA1 Message Date
Gitea OpenCode Agent
ed0b9af00b Fix issue #17: Foundry Module: Show pairing status 2026-10-14 12:59:26 +00:00
67ca4b0210 Merge pull request 'Fix #10: Add map support' (#11) from ai/issue-10 into master
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m3s
Reviewed-on: #11
2026-10-14 12:08:35 +00:00
ff4090412c Merge branch 'master' into ai/issue-10 2026-10-14 12:08:31 +00:00
445e97f2f8 Merge pull request 'Fix #12: Fix copy foundry code localization' (#13) from ai/issue-12 into master
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 50s
Reviewed-on: #13
2026-10-14 12:01:12 +00:00
dc6a04df8a Merge branch 'master' into ai/issue-12 2026-10-14 12:01:06 +00:00
0799dec5b3 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
2026-10-14 12:00:17 +00:00
Gitea OpenCode Agent
8378e9b3e7 Fix issue #12: Fix copy foundry code localization 2026-10-14 11:57:34 +00:00
Gitea OpenCode Agent
7d19a22a4b Fix issue #8: Sync toggle on foundry 2026-10-13 23:02:43 +00:00
11 changed files with 800 additions and 10 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. - `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. - `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 There is **no** database seeding, no ORM migrations, no linter/formatter config, no Pinia/Vuex, and no
Pinia/Vuex, and no Vue Router pages (see §5.1 — the UI is a window manager, not routed pages). 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`). 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 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) ├── ecosystem.config.js PM2 config (stale: runs `npm start`, which does not exist — see §9)
├── .gitea/workflows/deploy.yml ├── .gitea/workflows/deploy.yml
├── static/media/ README logo images only ├── static/media/ README logo images only
├── tests/ `node --test` tests (Foundry module sync toggle)
├── package.json root: only `concurrently`, used by `npm run dev` ├── package.json root: only `concurrently`, used by `npm run dev`
└── README.md install/run instructions are STALE (see §9) └── 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 dev # frontend only
npm --prefix frontend run build # nuxt build --dotenv .env.production npm --prefix frontend run build # nuxt build --dotenv .env.production
npm --prefix frontend run preview 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. 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). 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 ### Environment files
@@ -233,6 +239,7 @@ not `Campaign.foundryWorldId` (`syncCampaign` / `requestMatchesWorld`). CORS is
| `POST /sync/item-delete` | `{worldId, foundryItemId}` — a world item was deleted | | `POST /sync/item-delete` | `{worldId, foundryItemId}` — a world item was deleted |
| `GET /sync/characters` | Actors the module applies back into Foundry | | `GET /sync/characters` | Actors the module applies back into Foundry |
| `GET /sync/items` | Items the module applies back into Foundry (creates world items for Dragonroll-authored ones) | | `GET /sync/items` | Items the module applies back into Foundry (creates world items for Dragonroll-authored ones) |
| `GET /sync/status` | The campaign a sync token belongs to; the module shows it in its **Dragonroll Pairing Status** setting and treats `unauthorized` as the campaign having unlinked the world |
| `POST /sync/map` / `POST /sync/map-item` | Store the id mapping after the module creates a document | | `POST /sync/map` / `POST /sync/map-item` | Store the id mapping after the module creates a document |
| `POST /sync/delete` | `{worldId, foundryActorId}` | | `POST /sync/delete` | `{worldId, foundryActorId}` |
@@ -248,6 +255,13 @@ Rules worth knowing before editing this:
which the sync skips. which the sync skips.
- **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events - **`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. 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.
- **`pairingStatus` is a setting the module writes, not the GM**: the module settings sentence about
whether this world is connected comes from the stored sync token plus the answer from
`/sync/status` (checked at world start and every minute), and anything typed into it is replaced.
- `Actor.inventory` stays a flattened copy of the actor's embedded items; it is not linked to `Item`. - `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 - `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. bridge, only useful when `FOUNDRY_API_URL` is configured.

View File

@@ -225,6 +225,7 @@ router.post('/link/complete', linkRateLimit, async (req, res) => {
res.set('Cache-Control', 'no-store'); res.set('Cache-Control', 'no-store');
res.json({ res.json({
status: 'ok', status: 'ok',
campaign: { id: campaign.id, name: campaign.name },
world: { id: world.worldId, title: world.worldTitle, system: world.system }, world: { id: world.worldId, title: world.worldTitle, system: world.system },
syncToken, syncToken,
bridgeConfig: bridgeUrl && pushToken ? { url: bridgeUrl, pushToken } : null bridgeConfig: bridgeUrl && pushToken ? { url: bridgeUrl, pushToken } : null
@@ -236,6 +237,26 @@ router.post('/link/complete', linkRateLimit, async (req, res) => {
} }
}); });
// The Foundry module shows this in its settings: the sync token alone only proves
// a link was made once, so the module asks which campaign it belongs to and hears
// back nothing but `unauthorized` once that campaign unlinks the world again.
router.get('/sync/status', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
res.set('Cache-Control', 'no-store');
res.json({
status: 'ok',
campaign: { id: campaign.id, name: campaign.name },
worldId: campaign.foundryWorldId
});
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/sync/snapshot', async (req, res) => { router.post('/sync/snapshot', async (req, res) => {
try { try {
const campaign = await syncCampaign(req, res); const campaign = await syncCampaign(req, res);

View File

@@ -41,6 +41,14 @@ For a local backend, use `http://localhost:5000`; the module omits `/api` and th
the local pairing route at its root. Character synchronization works without the optional snapshot 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. bridge. Configure that bridge only if you also need the read-only world snapshot API described below.
**Dragonroll Pairing Status** in the module settings always says whether this browser holds a pairing
and, once Dragonroll has answered `GET /api/foundry/sync/status`, which campaign the world is
connected to. It is written by the module, not by the GM: it appears as not connected until the world
is paired, names the campaign after a pairing or a check on world start and every minute afterwards,
gives the reason when a pairing code can never be redeemed, and says the world is no longer linked
once the campaign unlinks it. Because both the pairing code and the sync token are client settings,
another browser of the same world reads as not paired.
The campaign settings show the linked world's title and system. A Foundry world can be linked to 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 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. client and uses the one-time code instead of a Dragonroll login token.
@@ -53,6 +61,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 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. 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 ### Items
The campaign's Item list is synchronized with the world's gear, both ways: The campaign's Item list is synchronized with the world's gear, both ways:
@@ -84,6 +111,7 @@ The module calls these Dragonroll routes with the campaign sync token (no Dragon
| `POST /api/foundry/sync/item-delete` | A world item was deleted | | `POST /api/foundry/sync/item-delete` | A world item was deleted |
| `GET /api/foundry/sync/characters` | Characters to apply back in Foundry | | `GET /api/foundry/sync/characters` | Characters to apply back in Foundry |
| `GET /api/foundry/sync/items` | Items to apply back in Foundry | | `GET /api/foundry/sync/items` | Items to apply back in Foundry |
| `GET /api/foundry/sync/status` | The campaign this world's token belongs to, for the module's pairing status |
| `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document | | `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document |
| `POST /api/foundry/sync/delete` | An actor was deleted | | `POST /api/foundry/sync/delete` | An actor was deleted |

View File

@@ -2,7 +2,7 @@
"id": "dragonroll-foundry", "id": "dragonroll-foundry",
"title": "Dragonroll Foundry API", "title": "Dragonroll Foundry API",
"description": "Links a Foundry world to a Dragonroll campaign and exposes a client-side API for world data.", "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, "library": true,
"compatibility": { "compatibility": {
"minimum": "12", "minimum": "12",

View File

@@ -4,7 +4,9 @@ const SETTING_PUSH_TOKEN = "pushToken";
const SETTING_BRIDGE_CONFIG = "bridgeConfig"; const SETTING_BRIDGE_CONFIG = "bridgeConfig";
const SETTING_DRAGONROLL_API_URL = "dragonrollApiUrl"; const SETTING_DRAGONROLL_API_URL = "dragonrollApiUrl";
const SETTING_LINK_CODE = "linkCode"; const SETTING_LINK_CODE = "linkCode";
const SETTING_PAIRING_STATUS = "pairingStatus";
const SETTING_SYNC_TOKEN = "syncToken"; const SETTING_SYNC_TOKEN = "syncToken";
const SETTING_AUTO_SYNC = "autoSync";
let syncTimeout; let syncTimeout;
let syncInProgress = false; let syncInProgress = false;
let syncRequested = false; let syncRequested = false;
@@ -15,6 +17,12 @@ const FATAL_LINK_ERRORS = new Set([
"foundry.errors.link-expired", "foundry.errors.link-expired",
"foundry.errors.world-already-linked", "foundry.errors.world-already-linked",
]); ]);
// Marks a pairing Dragonroll honoured once and no longer accepts: the campaign
// unlinked this world, so the token this client holds is dead.
const PAIRING_REVOKED = "revoked";
let updatingPairingStatus = false;
let linkedCampaignName = "";
let pairingProblem = "";
let actorSyncTimeout; let actorSyncTimeout;
let characterSyncRunning = false; let characterSyncRunning = false;
let actorSyncErrorLogged = false; let actorSyncErrorLogged = false;
@@ -139,6 +147,26 @@ Hooks.once("init", () => {
onChange: handleLinkCodeChange, onChange: handleLinkCodeChange,
}); });
game.settings.register(MODULE_ID, SETTING_PAIRING_STATUS, {
name: "Dragonroll Pairing Status",
hint: "Whether this world is connected to a Dragonroll campaign. The module keeps this text up to date and the pairing lives in the browser of whoever linked the world: there is nothing to set here.",
scope: "client",
config: true,
type: String,
default: "",
onChange: handlePairingStatusChange,
});
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); const module = game.modules.get(MODULE_ID);
if (!module) { if (!module) {
console.warn(`${MODULE_ID} | Could not register the public API: module was not found.`); console.warn(`${MODULE_ID} | Could not register the public API: module was not found.`);
@@ -210,6 +238,9 @@ async function setLinkCode(value) {
function handleLinkCodeChange(value) { function handleLinkCodeChange(value) {
if (updatingLinkCodeSetting || handlingLinkCode || !value?.trim()) return; if (updatingLinkCodeSetting || handlingLinkCode || !value?.trim()) return;
linkRetriesDisabled = false; linkRetriesDisabled = false;
// A code typed by hand supersedes whatever went wrong with the last one.
pairingProblem = "";
setPairingStatus(pairingStatusText());
completeDragonrollCampaignLink(value.trim()); completeDragonrollCampaignLink(value.trim());
} }
@@ -246,13 +277,19 @@ async function completeDragonrollCampaignLink(code, options = {}) {
scheduleSnapshotSync(0); scheduleSnapshotSync(0);
setTimeout(initializeCharacterSync, 0); setTimeout(initializeCharacterSync, 0);
setTimeout(reconcileDragonrollItems, 2000); setTimeout(reconcileDragonrollItems, 2000);
linkedCampaignName = String(result.campaign?.name || "").trim();
ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign."); ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign.");
await setPairingStatus(pairingStatusText());
} catch (error) { } catch (error) {
console.error(`${MODULE_ID} | Could not complete the campaign link.`, error); console.error(`${MODULE_ID} | Could not complete the campaign link.`, error);
// Expired or already-used codes will never redeem, so stop the background // Expired or already-used codes will never redeem, so stop the background
// retry; any error keeps retrying (the Dragonroll server may be restarting). // retry; any error keeps retrying (the Dragonroll server may be restarting).
linkRetriesDisabled = FATAL_LINK_ERRORS.has(error.message); linkRetriesDisabled = FATAL_LINK_ERRORS.has(error.message);
// Only a code that can never be redeemed belongs in the status: while the
// retry is still running, waiting for Dragonroll is the honest text.
if (linkRetriesDisabled) pairingProblem = linkErrorMessage(error);
if (notifyOnError) ui.notifications?.error(linkErrorMessage(error)); if (notifyOnError) ui.notifications?.error(linkErrorMessage(error));
await setPairingStatus(pairingStatusText());
} finally { } finally {
handlingLinkCode = false; handlingLinkCode = false;
} }
@@ -267,6 +304,69 @@ async function resumePendingDragonrollLink(options = {}) {
if (code) await completeDragonrollCampaignLink(code, options); if (code) await completeDragonrollCampaignLink(code, options);
} }
// --- Pairing status --------------------------------------------------------
// The pairing status is the sentence the module settings show. Everything in it
// comes from this client plus what Dragonroll last said about its token, so it
// reads correctly from the first frame and is corrected by refreshPairingStatus.
function pairingStatusText() {
if (pairingProblem === PAIRING_REVOKED) {
return "Not connected: this world is no longer linked to the Dragonroll campaign it was paired with. Create a new pairing code there to link it again.";
}
if (getSyncToken()) {
return linkedCampaignName
? `Connected to the Dragonroll campaign "${linkedCampaignName}".`
: "Connected to a Dragonroll campaign.";
}
if (pairingProblem) return `Not connected: Dragonroll did not accept that pairing code (${pairingProblem})`;
if (game.settings.get(MODULE_ID, SETTING_LINK_CODE)?.trim()) {
return "Not connected yet: waiting for Dragonroll to accept this pairing code.";
}
return "Not connected to a Dragonroll campaign. Paste a pairing code from that campaign's settings to link this world.";
}
async function setPairingStatus(text) {
if (game.settings.get(MODULE_ID, SETTING_PAIRING_STATUS) === text) return;
updatingPairingStatus = true;
try {
await game.settings.set(MODULE_ID, SETTING_PAIRING_STATUS, text);
} catch (error) {
console.warn(`${MODULE_ID} | Could not store the Dragonroll pairing status.`, error);
} finally {
updatingPairingStatus = false;
}
}
// Nothing is configured here: anything typed into the status is replaced by the
// status the module actually has.
function handlePairingStatusChange() {
if (updatingPairingStatus) return;
setPairingStatus(pairingStatusText());
}
// A token in this client only proves the world was paired once. Ask Dragonroll
// which campaign that token belongs to, and hear back when the campaign has
// unlinked this world again in the meantime.
async function refreshPairingStatus() {
const token = getSyncToken();
if (!token) {
linkedCampaignName = "";
await setPairingStatus(pairingStatusText());
return;
}
try {
const result = await getDragonroll("foundry/sync/status", token);
linkedCampaignName = String(result.campaign?.name || "").trim();
if (pairingProblem === PAIRING_REVOKED) pairingProblem = "";
} catch (error) {
// An unauthorized token is a campaign that unlinked this world. Any other
// failure (an unreachable Dragonroll, or one old enough to have no status
// route) says nothing about the pairing, so keep showing what we know.
if (error.message === "unauthorized") pairingProblem = PAIRING_REVOKED;
}
await setPairingStatus(pairingStatusText());
}
function scheduleSnapshotSync(delay = 500) { function scheduleSnapshotSync(delay = 500) {
clearTimeout(syncTimeout); clearTimeout(syncTimeout);
syncTimeout = setTimeout(publishSnapshot, delay); syncTimeout = setTimeout(publishSnapshot, delay);
@@ -287,6 +387,35 @@ function getSyncToken() {
return game.settings.get(MODULE_ID, SETTING_SYNC_TOKEN)?.trim() || ""; 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) { function dragonrollActorId(actor) {
return actor.getFlag?.(MODULE_ID, "actorId") || actor.flags?.[MODULE_ID]?.actorId || ""; return actor.getFlag?.(MODULE_ID, "actorId") || actor.flags?.[MODULE_ID]?.actorId || "";
} }
@@ -380,6 +509,34 @@ async function deleteDragonrollActor(foundryActorId) {
}, token); }, 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) { function queueActorChange(kind, actor) {
if (!actor || !game.user?.isGM || !getSyncToken()) return; if (!actor || !game.user?.isGM || !getSyncToken()) return;
if (syncingActorIds.has(actor.id) || actor.flags?.[MODULE_ID]?.syncMutation) return; if (syncingActorIds.has(actor.id) || actor.flags?.[MODULE_ID]?.syncMutation) return;
@@ -389,6 +546,9 @@ function queueActorChange(kind, actor) {
actorSyncTimeout = setTimeout(flushActorChanges, 400); actorSyncTimeout = setTimeout(flushActorChanges, 400);
} }
async function flushActorChanges() { 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()]; const changes = [...queuedActorChanges.values()];
queuedActorChanges.clear(); queuedActorChanges.clear();
const deleted = changes.filter((change) => change.kind === "delete"); const deleted = changes.filter((change) => change.kind === "delete");
@@ -518,6 +678,8 @@ function queueFoundryItemChange(kind, item) {
} }
async function flushItemChanges() { async function flushItemChanges() {
// Autosync off: the queued edits wait here, like the actor changes do.
if (!isAutoSyncEnabled()) return;
const changes = [...queuedItemChanges.values()]; const changes = [...queuedItemChanges.values()];
queuedItemChanges.clear(); queuedItemChanges.clear();
const deleted = changes.filter((change) => change.kind === "delete"); const deleted = changes.filter((change) => change.kind === "delete");
@@ -616,7 +778,7 @@ async function createFoundryWorldItem(entry) {
async function reconcileDragonrollItems() { async function reconcileDragonrollItems() {
const token = getSyncToken(); const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || itemSyncRunning) return; if (!token || !game.user?.isGM || !game.world || itemSyncRunning || !isAutoSyncEnabled()) return;
itemSyncRunning = true; itemSyncRunning = true;
try { try {
if (game.system.id !== "dnd5e") { if (game.system.id !== "dnd5e") {
@@ -847,7 +1009,7 @@ async function createFoundryCharacter(entry) {
async function reconcileDragonrollCharacters() { async function reconcileDragonrollCharacters() {
const token = getSyncToken(); const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || characterSyncRunning) return; if (!token || !game.user?.isGM || !game.world || characterSyncRunning || !isAutoSyncEnabled()) return;
characterSyncRunning = true; characterSyncRunning = true;
try { try {
if (game.system.id !== "dnd5e") { if (game.system.id !== "dnd5e") {
@@ -887,7 +1049,7 @@ async function reconcileDragonrollCharacters() {
} }
async function initializeCharacterSync() { async function initializeCharacterSync() {
if (!getSyncToken() || !game.user?.isGM || !game.world) return; if (!getSyncToken() || !game.user?.isGM || !game.world || !isAutoSyncEnabled()) return;
try { try {
await pushFoundryActors(game.actors.contents, true); await pushFoundryActors(game.actors.contents, true);
await reconcileDragonrollCharacters(); await reconcileDragonrollCharacters();
@@ -978,11 +1140,12 @@ async function publishHeartbeat() {
} }
Hooks.once("ready", () => { Hooks.once("ready", () => {
resumePendingDragonrollLink(); resumePendingDragonrollLink().then(refreshPairingStatus);
setInterval(() => { setInterval(() => {
if (linkRetriesDisabled) return; if (linkRetriesDisabled) return;
resumePendingDragonrollLink({ notifyOnError: false }); resumePendingDragonrollLink({ notifyOnError: false });
}, 60000); }, 60000);
setInterval(refreshPairingStatus, 60000);
scheduleSnapshotSync(0); scheduleSnapshotSync(0);
setInterval(publishHeartbeat, 60000); setInterval(publishHeartbeat, 60000);
setTimeout(initializeCharacterSync, 1000); setTimeout(initializeCharacterSync, 1000);
@@ -1016,3 +1179,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

@@ -17,6 +17,7 @@
"saved": "S'ha desat la configuració de la campanya.", "saved": "S'ha desat la configuració de la campanya.",
"linked": "S'ha enllaçat el món de Foundry amb aquesta campanya.", "linked": "S'ha enllaçat el món de Foundry amb aquesta campanya.",
"unlinked": "S'ha desenllaçat el món de Foundry d'aquesta campanya.", "unlinked": "S'ha desenllaçat el món de Foundry d'aquesta campanya.",
"copy-code": "Copia el codi",
"code-copied": "S'ha copiat el codi d'enllaç.", "code-copied": "S'ha copiat el codi d'enllaç.",
"saving": "Desant...", "saving": "Desant...",
"errors": { "errors": {

View File

@@ -21,6 +21,7 @@
"saved": "Campaign settings saved.", "saved": "Campaign settings saved.",
"linked": "Foundry world linked to this campaign.", "linked": "Foundry world linked to this campaign.",
"unlinked": "Foundry world unlinked from this campaign.", "unlinked": "Foundry world unlinked from this campaign.",
"copy-code": "Copy code",
"code-copied": "Pairing code copied.", "code-copied": "Pairing code copied.",
"saving": "Saving...", "saving": "Saving...",
"errors": { "errors": {

View File

@@ -17,6 +17,7 @@
"saved": "Se han guardado los ajustes de la campaña.", "saved": "Se han guardado los ajustes de la campaña.",
"linked": "El mundo de Foundry se ha vinculado a esta campaña.", "linked": "El mundo de Foundry se ha vinculado a esta campaña.",
"unlinked": "Se ha desvinculado el mundo de Foundry de esta campaña.", "unlinked": "Se ha desvinculado el mundo de Foundry de esta campaña.",
"copy-code": "Copiar código",
"code-copied": "Código de vinculación copiado.", "code-copied": "Código de vinculación copiado.",
"saving": "Guardando...", "saving": "Guardando...",
"errors": { "errors": {

View File

@@ -3,6 +3,7 @@
"concurrently": "^9.2.1" "concurrently": "^9.2.1"
}, },
"scripts": { "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,230 @@
// Tests for the pairing status the Dragonroll Foundry module shows in its
// settings (Syndria98/dragonroll#17). Like foundry-sync-toggle.test.js, the module
// script runs inside a `node:vm` context of stubbed Foundry globals; here each
// test also decides what Dragonroll answers, because the status is that answer
// plus what this client holds (its sync token and any pairing code).
//
// 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",
);
const LINKED_CAMPAIGN = { id: "campaign-1", name: "Curse of Strahd" };
// The stub starts as a world that finished pairing (`syncToken: ""` is one that
// never did). `answers` maps a route fragment to the JSON Dragonroll replies
// with; a route that is not listed answers `{status:"ok"}`, and one mapped to
// null answers HTML, like a Dragonroll old enough not to have that route at all.
function makeStubWorld({ syncToken = "sync-token-1", linkCode = "", answers = {} } = {}) {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
notifications: [],
};
const settingsStore = {
autoSync: true,
syncToken,
linkCode,
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);
},
},
// The pairing status never waits on a timer: it is written when the world is
// ready and whenever a pairing attempt answers, so dropping these keeps the
// snapshot and reconcile loops out of these tests.
setTimeout: () => 0,
clearTimeout: () => {},
setInterval: () => 0,
clearInterval: () => {},
fetch: async (url, options = {}) => {
const href = String(url);
state.requests.push({
href,
method: options.method,
authorization: options.headers?.Authorization || "",
});
const route = Object.keys(answers).find((fragment) => href.includes(fragment));
const payload = route ? answers[route] : { status: "ok" };
if (payload === null) {
return { ok: false, status: 404, json: async () => { throw new SyntaxError("Unexpected token < in JSON."); } };
}
return { ok: true, status: 200, json: async () => payload };
},
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: [], get: () => null },
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.status = () => settingsStore.pairingStatus;
state.statusRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync/status"));
// The module's own awaits run in the vm's promise intrinsics, so a few turns of
// the event loop are what it takes for a written status to be observable.
state.settle = async () => {
for (let round = 0; round < 10; round += 1) await new Promise((resolve) => setImmediate(resolve));
};
state.fire = async (name, ...args) => {
for (const handler of state.hooks.get(name) || []) await handler(...args);
await state.settle();
};
state.configure = async (key, value) => {
await sandbox.game.settings.set(MODULE_ID, key, value);
await state.settle();
};
state.start = async () => {
await state.fire("init");
await state.fire("ready");
return state;
};
return state;
}
test("the pairing status is a setting the module configures", async () => {
const world = await makeStubWorld().start();
const setting = world.registered.get("pairingStatus");
assert.equal(setting.config, true, "the pairing status appears in the module settings");
assert.equal(setting.type.name, "String", "the pairing status is a sentence");
assert.equal(setting.scope, "client", "the pairing status belongs to this client, like the token it comes from");
});
test("a world that was never paired says it is not connected", async () => {
const world = await makeStubWorld({ syncToken: "" }).start();
assert.match(world.status(), /^Not connected/, "an unpaired world says so plainly");
assert.match(world.status(), /Dragonroll campaign/, "and names what it is not connected to");
assert.deepEqual(world.statusRequests(), [], "there is nothing to verify without a sync token");
});
test("a paired world names the Dragonroll campaign it is connected to", async () => {
const world = await makeStubWorld({
answers: { "foundry/sync/status": { status: "ok", campaign: LINKED_CAMPAIGN, worldId: "world-1" } },
}).start();
assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`);
assert.equal(world.statusRequests()[0].authorization, "Bearer sync-token-1", "the campaign is asked with the sync token");
});
test("a campaign that unlinked this world stops being reported as connected", async () => {
const world = await makeStubWorld({
answers: { "foundry/sync/status": { status: "error", msg: "unauthorized" } },
}).start();
assert.match(world.status(), /^Not connected/);
assert.match(world.status(), /no longer linked/);
});
test("an unreachable Dragonroll keeps the pairing this client already knows", async () => {
const world = await makeStubWorld({ answers: { "foundry/sync/status": null } }).start();
assert.equal(world.status(), "Connected to a Dragonroll campaign.",
"a Dragonroll without the status route says nothing, so the token speaks");
});
test("a code that cannot be redeemed explains why the world is not connected", async () => {
const world = await makeStubWorld({
syncToken: "",
answers: { "foundry/link/complete": { status: "error", msg: "foundry.errors.link-expired" } },
});
await world.start();
await world.configure("linkCode", "AN-EXPIRED-CODE");
assert.match(world.status(), /^Not connected/);
assert.match(world.status(), /pairing code is invalid, expired, or already used/);
});
test("a code still waiting on Dragonroll says the pairing is not finished", async () => {
const world = await makeStubWorld({
syncToken: "",
answers: { "foundry/link/complete": { status: "error", msg: "errors.internal" } },
});
await world.start();
await world.configure("linkCode", "A-CODE-TO-RETRY");
assert.equal(world.status(), "Not connected yet: waiting for Dragonroll to accept this pairing code.");
});
test("redeeming a pairing code connects the world to its campaign", async () => {
const world = await makeStubWorld({
syncToken: "",
answers: {
"foundry/link/complete": { status: "ok", campaign: LINKED_CAMPAIGN, syncToken: "sync-token-2" },
},
});
await world.start();
await world.configure("linkCode", "A-FRESH-CODE");
assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`);
assert.equal(world.game.settings.get(MODULE_ID, "linkCode"), "", "a redeemed code is not kept");
});
test("whatever is typed into the status is replaced by the real one", async () => {
const world = await makeStubWorld({
answers: { "foundry/sync/status": { status: "ok", campaign: LINKED_CAMPAIGN, worldId: "world-1" } },
});
await world.start();
await world.configure("pairingStatus", "My own status text");
assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`);
});

View File

@@ -0,0 +1,312 @@
// 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);
// Sync pushes only: the pairing status read lives under the same prefix, and it
// tells nothing about what the world sent.
state.syncRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync")
&& !request.href.includes("foundry/sync/status"));
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");
});