// Tests for the campaign's notes reaching the Foundry world as journal pages
// (Syndria98/dragonroll#98): every Dragonroll note stands as a page of the one
// journal the world calls "Dragonroll", written by the module and kept in step with
// the campaign. The copy runs one way — notes are written in Dragonroll — so the
// backend answers with the notes and remembers each note's page; the module reads
// them, renders the markdown, and prunes the page of a note the campaign deleted.
//
// Both sides are loaded the way the other Foundry tests do it: the sync route runs
// against a stubbed `require` (models answer with plain objects and a small filter
// matcher), and the Foundry module is loaded into a `node:vm` context holding
// stubbed Foundry globals (`game.journals` and `JournalEntry` included) with fake
// timers, like tests/item-folder-sync.test.js.
//
// 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 read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const repoRequire = (relative) => require(path.join(__dirname, "..", relative));
// --- The sync route against stubbed models -------------------------------------
// A mongoose query answers whatever `await query` and `query.lean()` answer with, and
// lets `select()`, `sort()` and `limit()` sit in between.
function mongooseQuery(value) {
const result = {
select: () => result,
sort: () => result,
limit: (count) => mongooseQuery(value.slice(0, count)),
lean: () => Promise.resolve(value),
then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected),
};
return result;
}
// Enough of the query language the note routes use: equality, $or, $in, $nin,
// $exists, $ne. Anything else is a filter this test did not expect and says so.
function matches(document, filter = {}) {
return Object.entries(filter).every(([key, expected]) => {
if (key === "$or") return expected.some((part) => matches(document, part));
const value = document?.[key];
if (expected && typeof expected === "object" && !Array.isArray(expected)) {
return Object.entries(expected).every(([operator, wanted]) => {
if (operator === "$exists") return (value !== undefined && value !== null) === wanted;
if (operator === "$in") return wanted.some((entry) => String(value) === String(entry));
if (operator === "$nin") return !wanted.some((entry) => String(value) === String(entry));
if (operator === "$ne") return String(value ?? "") !== String(wanted ?? "");
throw new Error(`filter operator "${key}.${operator}" is not stubbed`);
});
}
return String(value ?? "") === String(expected ?? "");
});
}
function fakeModel(table, seed = [], campaignId) {
const rows = [];
let counter = 0;
function Document(data = {}) {
counter += 1;
this._id = `${table}-${counter}`;
this.isNew = true;
this.foundryNames = [];
Object.assign(this, data);
}
Document.prototype.save = async function save() {
if (this.isNew) rows.push(this);
this.isNew = false;
return this;
};
Object.defineProperty(Document.prototype, "id", { get() { return this._id; } });
for (const data of seed) {
// A seeded row belongs to the campaign the requests are made against unless the
// seed says otherwise: the routes scope every lookup by campaign.
const row = new Document({ campaign: campaignId, ...data });
row.isNew = false;
rows.push(row);
}
const model = function Model(data) { return new Document(data); };
model.rows = rows;
model.findOne = async (filter) => rows.find((row) => matches(row, filter)) ?? null;
model.find = (filter) => mongooseQuery(rows.filter((row) => matches(row, filter)));
model.deleteOne = async (filter) => {
const hit = rows.filter((row) => matches(row, filter));
for (const row of hit) rows.splice(rows.indexOf(row), 1);
return { deletedCount: hit.length };
};
model.deleteMany = async (filter) => {
const hit = rows.filter((row) => matches(row, filter));
for (const row of hit) rows.splice(rows.indexOf(row), 1);
return { deletedCount: hit.length };
};
model.updateMany = async (filter, update) => {
const hit = rows.filter((row) => matches(row, filter));
for (const row of hit) Object.assign(row, update.$set ?? {});
return { modifiedCount: hit.length };
};
return model;
}
// The Foundry sync route with every model it requires stubbed. `seed` pre-fills the
// tables with documents the campaign already holds.
function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
const routes = new Map();
const router = {
get: (route, ...handlers) => routes.set(`GET ${route}`, handlers),
post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
};
const campaign = { _id: "campaign-1", id: "campaign-1", name: "Test Campaign", foundryWorldId: worldId };
const seeded = (rows = []) => rows.map((row) => ({ campaign: campaign._id, ...row }));
const models = {
"../models/Actor": fakeModel("actor", seeded(seed.actors)),
"../models/Item": fakeModel("item", seeded(seed.items)),
"../models/Folder": fakeModel("folder", seeded(seed.folders)),
"../models/Note": fakeModel("note", seeded(seed.notes)),
};
const requireStub = (id) => {
if (id === "express") return { Router: () => router };
if (id.startsWith("node:")) return require(id); // crypto: the sync token is hashed, not stubbed
if (id === "mongoose") return { isValidObjectId: (value) => typeof value === "string" && value.length > 20 };
if (id === "../models/Campaign") return { findOne: async () => campaign };
if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) };
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
const moduleStub = { exports: {} };
vm.compileFunction(read("backend", "src", "routes", "foundry-link.js"), ["require", "module", "exports"])(
requireStub, moduleStub, moduleStub.exports
);
async function call(route, body = {}) {
const handlers = routes.get(route);
assert.ok(handlers, `${route} is not mounted`);
const res = { payload: null, json(payload) { this.payload = payload; }, set: () => {} };
const req = { body, get: (name) => (String(name).toLowerCase() === "authorization" ? "Bearer sync-token" : "") };
await handlers[handlers.length - 1](req, res);
return res.payload;
}
return { call, models, campaign };
}
// --- The sync route: the notes it answers and the page ids it keeps ---------------
test("the world reads the campaign's notes with their content and page mapping", async () => {
const sync = loadSyncRoute({
seed: {
notes: [
{ _id: "note-1", title: "Session 1", content: "**The start**", foundryPageId: "page-9" },
{ _id: "note-2", title: "Tavern Brawl", content: "- rope" },
],
},
});
const response = await sync.call("GET /sync/notes");
assert.equal(response.status, "ok");
assert.deepEqual(response.notes.map((note) => note.title), ["Session 1", "Tavern Brawl"]);
assert.equal(response.notes[0].content, "**The start**", "the markdown source travels: the module renders it");
assert.equal(response.notes[0].foundryPageId, "page-9", "and the note says which page it already stands as");
});
test("mapping a note to the page the module made keeps them paired", async () => {
const sync = loadSyncRoute({ seed: { notes: [{ _id: "note-1", title: "Session 1", content: "hi" }] } });
const response = await sync.call("POST /sync/map-note", {
worldId: "world-1", noteId: "note-1", foundryPageId: "page-9",
});
assert.equal(response.status, "ok");
assert.equal(sync.models["../models/Note"].rows[0].foundryPageId, "page-9");
// Mapping the same pair again is the module checking, not a conflict.
const again = await sync.call("POST /sync/map-note", {
worldId: "world-1", noteId: "note-1", foundryPageId: "page-9",
});
assert.equal(again.status, "ok");
});
test("a page already mapped to another note is refused", async () => {
const sync = loadSyncRoute({
seed: {
notes: [
{ _id: "note-1", title: "Session 1", content: "hi", foundryPageId: "page-9" },
{ _id: "note-2", title: "Tavern Brawl", content: "ho" },
],
},
});
const response = await sync.call("POST /sync/map-note", {
worldId: "world-1", noteId: "note-2", foundryPageId: "page-9",
});
assert.equal(response.status, "error");
assert.equal(response.msg, "foundry.errors.note-already-synced");
assert.equal(sync.models["../models/Note"].rows.find((row) => row._id === "note-2").foundryPageId, undefined,
"the first note keeps its page");
});
test("map-note wants this world's note and a page for it", async () => {
const sync = loadSyncRoute({ seed: { notes: [{ _id: "note-1", title: "Session 1", content: "hi" }] } });
assert.equal((await sync.call("POST /sync/map-note", { worldId: "world-1" })).msg, "errors.missing-data");
assert.equal((await sync.call("POST /sync/map-note", { noteId: "note-1", foundryPageId: "page-9" })).msg, "errors.missing-data",
"another world cannot map this campaign's note");
const gone = await sync.call("POST /sync/map-note", {
worldId: "world-1", noteId: "note-gone", foundryPageId: "page-9",
});
assert.equal(gone.msg, "errors.notfound");
});
// --- The Foundry module writes the journal ---------------------------------------
// Foundry's `update` takes dotted paths ("flags.dragonroll-foundry.noteId"); an
// embedded document's own id is not a path to set.
function writeFoundryPaths(target, data) {
for (const [key, value] of Object.entries(data)) {
if (key === "_id") continue;
const parts = key.split(".");
const last = parts.pop();
let node = target;
for (const part of parts) node = node[part] ??= {};
node[last] = value;
}
return target;
}
function makeWorld({ markdown = true } = {}) {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
timers: new Map(),
intervals: new Map(),
// What Dragonroll answers the notes reconcile with. Mapping a page answers
// like the real backend: the note keeps the page id, so later reads carry it.
remoteNotes: [],
nextId: 1,
};
const journals = [];
const makePage = (journal, data = {}) => {
const page = {
id: `page-${state.nextId++}`,
documentName: "JournalEntryPage",
name: data.name,
text: { content: data.text?.content ?? "" },
flags: data.flags ?? {},
writes: 0,
getFlag(module, key) { return this.flags?.[module]?.[key]; },
async update(update) {
page.writes += 1;
writeFoundryPaths(page, update);
return page;
},
async delete() {
const index = journal.pages.contents.indexOf(page);
if (index >= 0) journal.pages.contents.splice(index, 1);
},
};
return page;
};
const makeJournal = (data = {}) => {
const pages = [];
return {
id: `journal-${state.nextId++}`,
name: data.name,
documentName: "JournalEntry",
flags: data.flags ?? {},
getFlag(module, key) { return this.flags?.[module]?.[key]; },
pages: { contents: pages, get: (id) => pages.find((page) => page.id === id) },
async update(update) { return writeFoundryPaths(this, update); },
async createEmbeddedDocuments(documentName, docs) {
assert.equal(documentName, "JournalEntryPage", "the notes' pages are journal pages");
// Foundry's own page validation refuses a page without a name.
for (const doc of docs) assert.ok(doc.name, "a journal page needs a non-empty name");
const created = docs.map((doc) => makePage(this, doc));
pages.push(...created);
return created;
},
};
};
const settingsStore = { autoSync: true, 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() {}, warn() {}, error() {} } },
Hooks: {
once(name, fn) { state.hooks.set(name, [fn]); },
on(name, fn) { state.hooks.set(name, [...(state.hooks.get(name) || []), fn]); },
},
setTimeout: (fn, delay = 0) => {
const id = state.nextId++;
state.timers.set(id, { fn, delay });
return id;
},
clearTimeout: (id) => state.timers.delete(id),
setInterval: (fn, delay = 0) => {
// Recorded, never run by itself: tests ask for a periodic reconcile with
// `runIntervals`, so the ones watching single pushes stay on their own.
const id = state.nextId++;
state.intervals.set(id, { fn, delay });
return id;
},
clearInterval: (id) => state.intervals.delete(id),
fetch: async (url, options = {}) => {
const href = String(url);
const body = options.body ? JSON.parse(options.body) : null;
state.requests.push({ href, method: options.method, body });
if (href.includes("foundry/sync/map-note")) {
const note = state.remoteNotes.find((entry) => String(entry._id) === String(body.noteId));
if (note) note.foundryPageId = body.foundryPageId;
return { ok: true, status: 200, json: async () => ({ status: "ok", note }) };
}
if (href.includes("foundry/sync/notes")) {
return { ok: true, status: 200, json: async () => ({ status: "ok", notes: state.remoteNotes }) };
}
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
},
Actor: { async create() { return null; } },
Item: { async create() { return null; } },
JournalEntry: {
async create(data) {
const journal = makeJournal(data);
journals.push(journal);
return [journal];
},
},
};
if (markdown) sandbox.TextEditor = { _getMarkdown: (md) => `
a & b < c
line two
second para
", "escaped paragraphs instead of nothing, until this Foundry offers a renderer", ); }); test("autosync off: the campaign's notes are not written into the world", async () => { const world = await makeWorld().linkedSetup(); await world.game.settings.set(MODULE_ID, "autoSync", false); world.remoteNotes = [sessionNote()]; await world.runIntervals(); assert.deepEqual(world.journals(), [], "no journal is made"); assert.deepEqual(world.notesReads(), [], "and the campaign is not even asked"); });