// Tests for the sidebar's "force import from Foundry" button (Syndria98/dragonroll#77): // right-clicking an actor or an item offers to pull the whole actor list or item // directory of the linked world over. The campaign asks its own backend, which reads // the world's snapshot off the bridge and writes every document through the writers a // sync push uses — so a row the campaign already holds is written over instead of // imported a second time, and the answer counts the rows it made apart from the ones it // wrote over, which is what the confirmation toast says. // // The repository root installs no dependencies, so nothing here is required the way the // backend itself does it. The import route runs in a stubbed `require` against a fake // bridge and fake writers, and those writers are then loaded for real and run against // fake models, like tests/item-folder-sync.test.js does. The sidebar is a Vue component // this repository cannot build, so its checks read the source, like // tests/item-sheet-window.test.js does. // // 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 read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8"); const repoRequire = (relative) => require(path.join(__dirname, "..", relative)); const sidebarSource = read("frontend", "app", "components", "partials", "ContentSidebar.vue"); // --- The import route, against a fake bridge and fake writers --------------------- const LINKED_CAMPAIGN = { _id: "campaign-1", id: "campaign-1", foundryWorldId: "world-1" }; // What the bridge answers for a whole list: the bridge wraps what the world published // in `{status, data, world}`, and the route unwraps `data` again. function bridgeSnapshot(data, world = { id: "world-1", title: "Curse of Strahd" }) { return { status: 200, data: { status: "ok", data, world, syncedAt: "2026-10-15T10:00:00.000Z" } }; } // The foundry route with every require stubbed. `campaign` is what the caller owns // (`null` for a campaign that is not theirs), `answers` maps the bridge path to its // answer — an Error stands for a bridge that cannot be reached — and `mapping` says // what a world document becomes in the campaign: a new row or one it already had. function loadImportRoute({ campaign = LINKED_CAMPAIGN, answers = {}, mapping = () => ({ created: true }), } = {}) { const routes = new Map(); const router = { get: (route, ...handlers) => routes.set(`GET ${route}`, handlers), post: (route, ...handlers) => routes.set(`POST ${route}`, handlers), }; const asked = { bridgePaths: [], campaignFilters: [] }; const written = { actors: [], items: [] }; const requireStub = (id) => { if (id === "express") return { Router: () => router }; if (id === "../services/foundry") { return { requestFoundry: async (bridgePath) => { asked.bridgePaths.push(bridgePath); const answer = answers[bridgePath]; if (answer instanceof Error) throw answer; // A bridge with nothing to answer is one no GM client has published to. return answer ?? { status: 503, data: { status: "error", msg: "foundry.not-ready" } }; }, }; } if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js")); if (id === "../models/Campaign") { return { findOne: (filter) => { asked.campaignFilters.push(filter); const query = { select: () => query, lean: () => Promise.resolve(campaign ?? null) }; return query; }, }; } if (id === "./foundry-link") { return { saveFoundryActor: async (own, source) => { written.actors.push(source); return mapping(source); }, saveFoundryItem: async (own, source) => { written.items.push(source); return mapping(source); }, }; } throw new Error(`require("${id}") is not stubbed`); }; const moduleStub = { exports: {} }; vm.compileFunction(read("backend", "src", "routes", "foundry.js"), ["require", "module", "exports"])( requireStub, moduleStub, moduleStub.exports ); async function importFrom(body, user = { id: "user-1" }) { const handlers = routes.get("POST /import"); assert.ok(handlers, "POST /import is not mounted"); const res = { payload: null, json(payload) { this.payload = payload; } }; await handlers[handlers.length - 1]({ body, user }, res); return res.payload; } return { importFrom, asked, written }; } const TWO_ACTORS = [ { _id: "actor-1", name: "Thalia", type: "character" }, { _id: "actor-2", name: "Grimnir", type: "npc" }, ]; test("the import pulls the world's actors and counts them new against updated", async () => { const route = loadImportRoute({ answers: { "api/actors": bridgeSnapshot(TWO_ACTORS) }, mapping: (source) => ({ created: source._id === "actor-2" }), }); const response = await route.importFrom({ campaign: "campaign-1", kind: "actors" }); assert.deepEqual(route.asked.bridgePaths, ["api/actors"], "the actors are read off the bridge"); assert.deepEqual(route.asked.campaignFilters[0], { _id: "campaign-1", createdBy: "user-1" }, "only the campaign the caller holds is imported"); assert.deepEqual(route.written.actors.map((source) => source.name), ["Thalia", "Grimnir"]); assert.deepEqual(response, { status: "ok", kind: "actors", imported: 1, updated: 1 }); }); test("the item import pulls the world's item directory", async () => { const route = loadImportRoute({ answers: { "api/items": bridgeSnapshot([{ _id: "item-1", name: "Longsword", type: "weapon" }]) }, }); const response = await route.importFrom({ campaign: "campaign-1", kind: "items" }); assert.deepEqual(route.asked.bridgePaths, ["api/items"], "the bridge's world items, not its actors"); assert.equal(route.written.items.length, 1); assert.equal(route.written.actors.length, 0); assert.deepEqual(response, { status: "ok", kind: "items", imported: 1, updated: 0 }); }); test("only the actor and item lists can be imported", async () => { for (const kind of [undefined, "maps", "notes", "everything"]) { const route = loadImportRoute(); const response = await route.importFrom({ campaign: "campaign-1", kind }); assert.equal(response.msg, "errors.missing-data", `"${kind}" is not a list to import`); assert.deepEqual(route.asked.bridgePaths, [], "nothing is asked of the bridge for it"); } }); test("a campaign the caller does not hold is not imported", async () => { const route = loadImportRoute({ campaign: null }); const response = await route.importFrom({ campaign: "someone-elses-campaign", kind: "actors" }); assert.equal(response.msg, "errors.notfound"); assert.deepEqual(route.asked.bridgePaths, [], "the bridge is not asked for somebody else's world"); }); test("a campaign with no linked world is told so, and nothing is written", async () => { const route = loadImportRoute({ campaign: { _id: "campaign-1" } }); const response = await route.importFrom({ campaign: "campaign-1", kind: "items" }); assert.equal(response.msg, "foundry.errors.import-not-linked"); assert.deepEqual(route.asked.bridgePaths, []); assert.deepEqual(route.written.items, []); }); test("another world's snapshot is not written into the campaign", async () => { const route = loadImportRoute({ answers: { "api/actors": bridgeSnapshot(TWO_ACTORS, { id: "world-2", title: "Another World" }) }, }); const response = await route.importFrom({ campaign: "campaign-1", kind: "actors" }); assert.equal(response.msg, "foundry.errors.import-world-mismatch"); assert.deepEqual(route.written.actors, [], "the bridge keeps one world's snapshot at a time"); }); test("a bridge that is not there says so instead of importing nothing", async () => { const notSetUp = loadImportRoute({ answers: { "api/actors": Object.assign(new Error("Foundry API is not configured."), { code: "FOUNDRY_NOT_CONFIGURED" }) }, }); const unreachable = loadImportRoute({ answers: { "api/actors": new Error("ECONNREFUSED") } }); const noSnapshotYet = loadImportRoute(); // answers nothing → the bridge's own 503 for (const route of [notSetUp, unreachable, noSnapshotYet]) { const response = await route.importFrom({ campaign: "campaign-1", kind: "actors" }); assert.equal(response.msg, "foundry.errors.import-unavailable"); assert.deepEqual(route.written.actors, []); } }); test("a world document that maps to nothing is not counted", async () => { const route = loadImportRoute({ answers: { "api/items": bridgeSnapshot([ { _id: "item-1", name: "Longsword", type: "weapon" }, { _id: "spell-1", name: "Magic Missile", type: "spell" }, ]) }, // what is not gear maps to nothing, exactly like a sync push skips it mapping: (source) => (source.type === "spell" ? null : { created: true }), }); const response = await route.importFrom({ campaign: "campaign-1", kind: "items" }); assert.equal(route.written.items.length, 2, "every world document is offered to the writer"); assert.deepEqual(response, { status: "ok", kind: "items", imported: 1, updated: 0 }); }); // --- The writers, against fake models: existing rows are written over, not doubled --- 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 writers use: equality, $or and $exists. 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; 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) { 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))); return model; } // The sync route loaded for its writers: the same functions the world's pushes and the // campaign's import run through, here against rows the campaign already holds. function loadFoundryWriters({ seed = {} } = {}) { const campaign = { _id: "campaign-1", id: "campaign-1", foundryWorldId: "world-1" }; 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)), "../models/Map": fakeModel("map", seeded(seed.maps)), }; const requireStub = (id) => { if (id === "express") return { Router: () => ({ get: () => {}, post: () => {} }) }; if (id.startsWith("node:")) return require(id); 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 repoRequire(path.join("backend", "src", "services", "actor-foundry.js")); 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 (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.js")); if (id === "../services/service-links") return { unlinkFoundryWorld: async () => {} }; 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 ); return { campaign, models, writers: moduleStub.exports }; } test("the writers a sync push uses are the ones an import writes through", () => { const { writers } = loadFoundryWriters(); assert.equal(typeof writers.saveFoundryActor, "function"); assert.equal(typeof writers.saveFoundryItem, "function"); }); test("an imported actor the campaign already has is written over, not made again", async () => { const sync = loadFoundryWriters({ seed: { actors: [{ _id: "actor-1", name: "Thalia the old", foundryActorId: "actor-1", level: 1 }] }, }); const worldActor = { _id: "actor-1", name: "Thalia", type: "character", system: { details: { level: 3 } } }; const first = await sync.writers.saveFoundryActor(sync.campaign, worldActor); const second = await sync.writers.saveFoundryActor(sync.campaign, worldActor); assert.equal(sync.models["../models/Actor"].rows.length, 1, "the world's actor stands in one row"); assert.equal(first.created, false, "the row was already there"); assert.equal(second.created, false); assert.equal(sync.models["../models/Actor"].rows[0].name, "Thalia", "a force import writes the world over the row"); assert.equal(sync.models["../models/Actor"].rows[0].level, 3); }); test("an actor the world has never been seen as becomes one row, and the next import updates it", async () => { const sync = loadFoundryWriters(); const worldActor = { _id: "actor-9", name: "Grimnir", type: "npc", system: { details: { cr: 2 } } }; const made = await sync.writers.saveFoundryActor(sync.campaign, worldActor); const again = await sync.writers.saveFoundryActor(sync.campaign, worldActor); assert.equal(made.created, true, "the first import makes the row"); assert.equal(again.created, false, "the one after it only writes it over"); assert.equal(sync.models["../models/Actor"].rows.length, 1); assert.equal(sync.models["../models/Actor"].rows[0].foundryActorId, "actor-9"); }); // A forced sync from the module's context menu (Syndria98/dragonroll#96) replaces // everything the campaign holds for the actor; a live change is a merge and leaves the // fields the world says nothing about to the campaign. test("a forced actor sync clears what the campaign wrote; a live change keeps it", async () => { const sync = loadFoundryWriters({ seed: { actors: [{ _id: "actor-1", name: "Thalia", foundryActorId: "actor-1", traits: "A trait the campaign wrote", tools: ["Thieves' tools"], languages: ["Elvish"], skills: { perception: true }, savingThrows: { dex: true }, currency: { gp: 50 }, }] }, }); // The world says nothing about any of those: the fields a live edit leaves out. const worldActor = { _id: "actor-1", name: "Thalia", type: "character", system: {} }; await sync.writers.saveFoundryActor(sync.campaign, worldActor, false, false); let row = sync.models["../models/Actor"].rows[0]; assert.equal(row.traits, "A trait the campaign wrote", "a live push leaves what the campaign wrote alone"); assert.deepEqual(row.tools, ["Thieves' tools"]); assert.deepEqual(row.languages, ["Elvish"]); assert.deepEqual(row.skills, { perception: true }); assert.deepEqual(row.savingThrows, { dex: true }); assert.deepEqual(row.currency, { gp: 50 }); await sync.writers.saveFoundryActor(sync.campaign, worldActor, false, true); row = sync.models["../models/Actor"].rows[0]; assert.equal(row.name, "Thalia", "the actor is still the one the world sent"); assert.equal(row.traits, "", "a forced sync clears the trait the campaign wrote"); assert.deepEqual(row.tools, [], "and the tools, languages, skills, saving throws and coin it held"); assert.deepEqual(row.languages, []); assert.deepEqual(row.skills, {}); assert.deepEqual(row.savingThrows, {}); assert.deepEqual(row.currency, {}); }); test("a hand-made item folds into the import instead of doubling, and keeps being updated", async () => { const sync = loadFoundryWriters({ seed: { items: [{ _id: "item-1", name: "Longsword", quantity: 1 }] }, }); const worldItem = { _id: "sword-9", name: "Longsword", type: "weapon", system: { quantity: 4, weight: 3, rarity: "rare" } }; const made = await sync.writers.saveFoundryItem(sync.campaign, worldItem); const again = await sync.writers.saveFoundryItem(sync.campaign, worldItem); const rows = sync.models["../models/Item"].rows; assert.equal(rows.length, 1, "the campaign's own row is the world item's row"); assert.equal(made.created, false, "adopting a row the campaign made is not importing it new"); assert.equal(again.created, false); assert.equal(rows[0].foundryItemId, "sword-9"); assert.equal(rows[0].quantity, 4, "and the force import writes the world over it"); assert.equal(rows[0].rarity, "rare"); }); // --- The sidebar: the button, and the toast it leaves behind ---------------------- const entryMenu = /function showEntryMenu[\s\S]*?\n\}/.exec(sidebarSource)?.[0] ?? ""; const importer = /async function forceImportFromFoundry[\s\S]*?\n\}/.exec(sidebarSource)?.[0] ?? ""; test("the actor and item rows offer a force import in their right-click menu", () => { assert.ok(entryMenu, "the sidebar has an entry menu"); assert.match(entryMenu, /if \(entityType === ['"]actor['"] \|\| entityType === ['"]item['"]\)/, "the offer belongs to the two lists mirroring a world, not the maps"); assert.match(entryMenu, /t\(['"]campaigns\.foundry-import\.run['"]\)/); assert.match(entryMenu, /action: \(\) => \{ HideContextMenu\(\); forceImportFromFoundry\(entityType\); \}/); }); test("the import is asked for once, says what landed, and reads the list back", async () => { assert.ok(importer, "the sidebar has the import"); assert.match(importer, /if \(!campaignId\.value \|\| !section \|\| importingFoundry\.value\) return;/, "clicking a row again while the world is on its way does not start a second import"); assert.match(importer, /Server\(\)\.post\(['"]\/foundry\/import['"], \{ campaign: campaignId\.value, kind: section \}\)/); assert.match(importer, /DisplayToast\(['"]green['"], t\(['"]campaigns\.foundry-import\.done['"]/); assert.match(importer, /imported: response\.data\.imported \?\? 0/); assert.match(importer, /updated: response\.data\.updated \?\? 0/); assert.match(importer, /await fetchCampaignEntries\(section\)/, "what arrived is read back into the list"); // the failed import says what the backend said, the way the other windows do assert.match(importer, /DisplayToast\(['"]red['"], t\(response\.data\.msg \|\| ['"]campaigns\.foundry-import\.error['"]\)/); }); test("every locale has the strings of the button, its toast and its errors", () => { for (const locale of ["en", "es", "ca"]) { const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json")); for (const key of ["run", "done", "error"]) { assert.ok(campaigns["foundry-import"]?.[key], `${locale} is missing campaigns.foundry-import.${key}`); } const foundry = JSON.parse(read("frontend", "i18n", "locales", locale, "foundry.json")); for (const key of ["import-not-linked", "import-unavailable", "import-world-mismatch"]) { assert.ok(foundry.errors?.[key], `${locale} is missing foundry.errors.${key}`); } } });