Fix issue #77: Add a "force import from foundry" context button
All checks were successful
Test / test (push) Successful in 2s

This commit is contained in:
Gitea OpenCode Agent
2026-10-15 18:16:47 +00:00
parent a8a1e0ca41
commit f928f13544
11 changed files with 537 additions and 9 deletions

View File

@@ -99,7 +99,7 @@ campaign, and handlers check ownership with a `userOwnsCampaign(campaignId, user
- `actor` — `list`, `create`, `update` (partial, ownership checked), `upload-image?actor=` (multipart), `delete`
- `item` — `list`, `create`, `update` (partial), `delete`
- `map` — `list`, `create` (multipart `image` or JSON), `update` (multipart to replace the photo), `delete`, `pin` (`{id,note,x,y}`, re-pinning moves the marker), `unpin` (`{id,pin}`), `place-token` (`{id,actor,x,y}`, snapped to a cell centre, re-placing moves the token), `remove-token` (`{id,token}`)
- `foundry` — read-only proxy over the bridge (`/world`, `/actors`, `/characters`, `/items`, `/actors/:id`, `/items/:id`, `/actors/:id/items`), needs `FOUNDRY_API_URL`; `/icons?campaign=&dir=&offset=` lists one folder of the world's core `icons/` library (the bridge reads it from `DRAGONROLL_FOUNDRY_DATA_PATH`) and answers `{dir, parent, folders, files[{path,name,url}], next}`, the icons paged so the library stays lazy to load
- `foundry` — read-only proxy over the bridge (`/world`, `/actors`, `/characters`, `/items`, `/actors/:id`, `/items/:id`, `/actors/:id/items`), needs `FOUNDRY_API_URL`; `POST /import` (`{campaign, kind: 'actors'|'items'}`, the sidebar's "force import from Foundry") pulls that world's whole list off the bridge through the sync's writers, so rows the campaign already has are written over, and answers `{imported, updated}`; `/icons?campaign=&dir=&offset=` lists one folder of the world's core `icons/` library (the bridge reads it from `DRAGONROLL_FOUNDRY_DATA_PATH`) and answers `{dir, parent, folders, files[{path,name,url}], next}`, the icons paged so the library stays lazy to load
## 4. Service integrations (Foundry, Discord, Obsidian)
@@ -121,7 +121,7 @@ the JWT guard; CORS opened for it): `snapshot` (actors + world items, `fullSync`
- **Item folders mirror the world's item directory** (`Folder.foundryFolderId`, target `item`): every push carries the whole tree and the world owns its names and nesting. `color` is the one field the campaign sets too, so it travels back with the folders `GET /foundry/sync/items` answers with (`{items, folders}`) and the module writes it onto the world's folder.
- **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events overwrite. Only a full snapshot can prune.
- **Autosync is a Foundry-side setting** (`autoSync`, on by default): off = no CRUD push, no periodic reconcile, no startup snapshot; the actor directory's *Dragonroll: Force Sync* still upserts the selection (`fullSync:false`).
- `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only bridge.
- `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only bridge. Its one write, `POST /import`, pulls the bridge's actors or world items into the campaign through the same writers as a sync push.
## 5. Frontend

View File

@@ -62,11 +62,14 @@ async function saveFoundryActor(campaign, source, fullSync = false) {
: new Actor({ campaign: campaign._id });
}
actor.foundryActorId = foundryActorId;
// `created` says whether this row is new: whoever imports a whole world counts
// the rows it made apart from the ones it only wrote over.
const created = actor.isNew;
// A full snapshot runs when a GM reconnects. Preserve existing Dragonroll
// edits then; live Foundry change events continue to overwrite normally.
if (!fullSync || actor.isNew) Object.assign(actor, fields);
await actor.save();
return { foundryActorId, actorId: actor.id };
return { foundryActorId, actorId: actor.id, created };
}
// The campaign's item list mirrors the world's item directory and nothing else
@@ -105,6 +108,9 @@ async function saveFoundryItem(campaign, source, fullSync = false, folders = nul
}
item.foundryItemId = foundryItemId;
// `created` says whether this row is new: whoever imports a whole world counts
// the rows it made apart from the ones it only wrote over.
const created = item.isNew;
if (!fullSync || item.isNew) Object.assign(item, fields);
// Foundry's own icon is kept on every save, not only when the edits above
// land: the item window offers it back after the user picked their own.
@@ -120,7 +126,7 @@ async function saveFoundryItem(campaign, source, fullSync = false, folders = nul
const folder = resolveFoundryItemFolder(source, folders);
if (folder !== undefined) item.folder = folder;
await item.save();
return { foundryItemId, itemId: item.id };
return { foundryItemId, itemId: item.id, created };
}
async function syncFoundryItems(campaign, sources, fullSync = false, folders = null) {
@@ -447,3 +453,9 @@ router.post('/sync/map-item', async (req, res) => {
});
module.exports = router;
// The writers every Foundry document goes through: the sync pushes above, and the
// force import a campaign asks for from its sidebar (routes/foundry.js). One set of
// rules decides which campaign row a world document owns, so pulling a world over
// twice updates its rows instead of doubling them.
module.exports.saveFoundryActor = saveFoundryActor;
module.exports.saveFoundryItem = saveFoundryItem;

View File

@@ -4,12 +4,17 @@ const { requestFoundry } = require('../services/foundry');
const { normalizeIconDirectory, readIconListingPage, shapeIconListing } = require('../services/foundry-icons');
const Campaign = require('../models/Campaign');
// The writers a Foundry document is stored through, shared with the sync pushes the
// linked module sends (routes/foundry-link.js) so both write a world's rows by the
// same rules.
const { saveFoundryActor, saveFoundryItem } = require('./foundry-link');
// The world address the icons are loaded from is kept on the campaign, so an icon
// listing is always asked for one of the caller's own campaigns.
// listing is always asked for one of the caller's own campaigns. The linked world's
// id travels along: an import has to know whose data it is pulling over.
async function findOwnedCampaign(campaignId, userId) {
if (!campaignId) return null;
return Campaign.findOne({ _id: campaignId, createdBy: userId }).select('settings').lean();
return Campaign.findOne({ _id: campaignId, createdBy: userId }).select('settings foundryWorldId').lean();
}
async function proxy(path, res) {
@@ -34,6 +39,63 @@ router.get('/actors/:id/items', (req, res) => proxy(`api/actors/${encodeURICompo
router.get('/actors/:id', (req, res) => proxy(`api/actors/${encodeURIComponent(req.params.id)}`, res));
router.get('/items/:id', (req, res) => proxy(`api/items/${encodeURIComponent(req.params.id)}`, res));
// Force import (Syndria98/dragonroll#77): the sidebar's "force import from Foundry"
// pulls the whole actor list or item directory of the world the bridge is showing
// right now. The documents go through the writers the module's own snapshot push
// uses, so a world document lands on the row it owns: what the campaign already has
// is written over, not imported a second time. Nothing is pruned here — only a full
// snapshot from the module sees the whole world, so dropping rows the world let go of
// stays that snapshot's job.
router.post('/import', async (req, res) => {
try {
const kind = ['actors', 'items'].includes(req.body?.kind) ? req.body.kind : null;
if (!kind) return res.json({ status: 'error', msg: 'errors.missing-data' });
const campaign = await findOwnedCampaign(req.body.campaign, req.user.id);
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!campaign.foundryWorldId) {
return res.json({ status: 'error', msg: 'foundry.errors.import-not-linked' });
}
// The bridge answers `{status, data, world}`: `data` holds the world's actors
// or its world-level items, in the shape the module published them in.
let snapshot;
try {
snapshot = await requestFoundry(`api/${kind}`);
} catch (err) {
if (err.code !== 'FOUNDRY_NOT_CONFIGURED') console.error(err);
return res.json({ status: 'error', msg: 'foundry.errors.import-unavailable' });
}
if (snapshot.status !== 200 || snapshot.data?.status !== 'ok' || !Array.isArray(snapshot.data.data)) {
return res.json({ status: 'error', msg: 'foundry.errors.import-unavailable' });
}
// The bridge keeps one world's snapshot at a time, so a campaign linked to
// another world must not be filled with it. A bridge that does not say whose
// world it holds is taken at its word: only a known mismatch stops the import.
if (snapshot.data.world?.id && snapshot.data.world.id !== campaign.foundryWorldId) {
return res.json({ status: 'error', msg: 'foundry.errors.import-world-mismatch' });
}
let imported = 0;
let updated = 0;
for (const source of snapshot.data.data) {
// An actor without a name, or a world document that is not gear, maps to
// nothing and is skipped exactly like a sync push skips it.
const mapping = kind === 'actors'
? await saveFoundryActor(campaign, source)
: await saveFoundryItem(campaign, source);
if (!mapping) continue;
if (mapping.created) imported += 1;
else updated += 1;
}
res.json({ status: 'ok', kind, imported, updated });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// Foundry's core icon library: the `icons/` folder of the world's data directory.
// One folder per request, and the icons inside it paged, because that library runs
// into the thousands and the window only ever shows where the user is standing.

View File

@@ -8,6 +8,7 @@ import { emitter } from '~/services/Emitter';
import { BuildColorMenu } from '~/services/EntryColors';
import { BuildItemRows } from '~/services/ItemFolders';
import Server, { getBaseUrl } from '~/services/Server';
import { DisplayToast } from '~/services/Toaster';
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu';
import { ACTOR_DRAG_TYPE } from '~/services/MapTokens';
@@ -29,6 +30,9 @@ const entryFolders = { actor: ref([]), item: ref([]), map: ref([]) };
const collapsedFolderIds = ref([]);
const loadingNotes = ref(false);
const loadingEntries = ref(false);
// An import of the whole linked world takes a moment, and clicking the row again while
// it runs must not start a second one.
const importingFoundry = ref(false);
const notesError = ref('');
const entriesError = ref('');
const sidebarCollapsed = ref(false);
@@ -309,6 +313,35 @@ function editMap(map) {
CreateWindow('create_map', { campaign: campaignId.value, entry: map });
}
// The one sidebar action that asks the linked world instead of the campaign's own rows
// (Syndria98/dragonroll#77): the backend reads what the Foundry bridge is showing and
// writes every actor or item of it through the writers a sync push uses, so the rows
// the campaign already has are written over and only the world's new ones are made.
// The list is read back once the answer is in, so whatever arrived is on screen, and
// the toast says how the world landed.
async function forceImportFromFoundry(entityType) {
const section = sectionForTarget(entityType);
if (!campaignId.value || !section || importingFoundry.value) return;
importingFoundry.value = true;
try {
const response = await Server().post('/foundry/import', { campaign: campaignId.value, kind: section });
if (response.data.status !== 'ok') {
DisplayToast('red', t(response.data.msg || 'campaigns.foundry-import.error'), 3000);
return;
}
DisplayToast('green', t('campaigns.foundry-import.done', {
imported: response.data.imported ?? 0,
updated: response.data.updated ?? 0
}), 3000);
await fetchCampaignEntries(section);
} catch (error) {
DisplayToast('red', t('campaigns.foundry-import.error'), 3000);
} finally {
importingFoundry.value = false;
}
}
function showEntryMenu(entry, entityType) {
const list = entryLists[entityType];
const menuItems = [];
@@ -328,6 +361,18 @@ function showEntryMenu(entry, entityType) {
});
}
// The actor and item lists mirror a linked Foundry world, so their rows also offer
// to pull the whole world over: this row is not sent or fetched on its own, the
// section's whole list is imported and the rows already in it are only updated.
if (entityType === 'actor' || entityType === 'item') {
menuItems.push({ divider: true });
menuItems.push({
name: t('campaigns.foundry-import.run'),
icon: '/icons/iconoir/regular/import.svg',
action: () => { HideContextMenu(); forceImportFromFoundry(entityType); }
});
}
// Rows of every section can be filed into a folder of their own list, like a note
// into a folder of the note tree.
menuItems.push({

View File

@@ -49,6 +49,11 @@
"rename": "Canvia el nom", "color": "Color", "default": "Per defecte", "delete": "Suprimeix la carpeta",
"move-to": "Mou a carpeta...", "root": "Arrel"
},
"foundry-import": {
"run": "Força la importació des del Foundry",
"done": "Importat del Foundry: {imported} nous, {updated} actualitzats.",
"error": "No s'ha pogut importar des del món del Foundry vinculat."
},
"states": {
"loading": "Carregant...", "loading-notes": "Carregant notes...", "empty-notes": "Encara no hi ha notes en aquesta campanya.",
"empty-actors": "Encara no hi ha actors ni personatges.", "empty-items": "Encara no hi ha objectes en aquesta campanya.",

View File

@@ -5,7 +5,10 @@
"actor-already-synced": "Un altre actor d'aquesta campanya ja està sincronitzat amb aquell actor del Foundry.",
"item-already-synced": "Un altre objecte d'aquesta campanya ja està sincronitzat amb aquell objecte del Foundry.",
"icons-unavailable": "Les icones del Foundry no són disponibles: el seu bridge no està configurat o ara mateix no hi arriba.",
"icons-no-world-url": "Aquesta campanya no té adreça del món del Foundry. Definiu-la als ajustos de la campanya, a la pestanya d'integracions."
"icons-no-world-url": "Aquesta campanya no té adreça del món del Foundry. Definiu-la als ajustos de la campanya, a la pestanya d'integracions.",
"import-not-linked": "Aquesta campanya no té cap món del Foundry vinculat. Connecteu-ne un als ajustos de la campanya, a la pestanya d'integracions.",
"import-unavailable": "Les dades del Foundry no són disponibles: el seu bridge no està configurat, ara mateix no hi arriba o el seu món encara no ha publicat res.",
"import-world-mismatch": "El bridge del Foundry està mostrant un món diferent del que aquesta campanya té vinculat."
},
"icons": {
"path": "Carpeta d'icones",

View File

@@ -53,6 +53,11 @@
"rename": "Rename", "color": "Color", "default": "Default", "delete": "Delete folder",
"move-to": "Move to folder...", "root": "Root"
},
"foundry-import": {
"run": "Force import from Foundry",
"done": "Imported from Foundry: {imported} new, {updated} updated.",
"error": "Unable to import from the linked Foundry world."
},
"states": {
"loading": "Loading...", "loading-notes": "Loading notes...", "empty-notes": "No notes in this campaign yet.",
"empty-actors": "No actors or characters yet.", "empty-items": "No items in this campaign yet.",

View File

@@ -5,7 +5,10 @@
"actor-already-synced": "Another actor in this campaign is already synced with that Foundry actor.",
"item-already-synced": "Another item in this campaign is already synced with that Foundry item.",
"icons-unavailable": "Foundry's icons are not available: its bridge is not set up, or it cannot be reached right now.",
"icons-no-world-url": "This campaign has no Foundry world address. Set it under campaign settings, in the Integrations tab."
"icons-no-world-url": "This campaign has no Foundry world address. Set it under campaign settings, in the Integrations tab.",
"import-not-linked": "This campaign has no Foundry world linked to it. Connect one under campaign settings, in the Integrations tab.",
"import-unavailable": "Foundry's data is not available: its bridge is not set up, it cannot be reached right now, or its world has not published anything yet.",
"import-world-mismatch": "The Foundry bridge is showing another world than the one this campaign is linked to."
},
"icons": {
"path": "Icon folder",

View File

@@ -49,6 +49,11 @@
"rename": "Renombrar", "color": "Color", "default": "Por defecto", "delete": "Eliminar carpeta",
"move-to": "Mover a carpeta...", "root": "Raíz"
},
"foundry-import": {
"run": "Forzar importación desde Foundry",
"done": "Importado desde Foundry: {imported} nuevos, {updated} actualizados.",
"error": "No se ha podido importar desde el mundo de Foundry vinculado."
},
"states": {
"loading": "Cargando...", "loading-notes": "Cargando notas...", "empty-notes": "Aún no hay notas en esta campaña.",
"empty-actors": "Aún no hay actores ni personajes.", "empty-items": "Aún no hay objetos en esta campaña.",

View File

@@ -5,7 +5,10 @@
"actor-already-synced": "Otro actor de esta campaña ya está sincronizado con ese actor de Foundry.",
"item-already-synced": "Otro objeto de esta campaña ya está sincronizado con ese objeto de Foundry.",
"icons-unavailable": "Los iconos de Foundry no están disponibles: su bridge no está configurado o no es accesible ahora.",
"icons-no-world-url": "Esta campaña no tiene dirección del mundo de Foundry. Defínala en los ajustes de la campaña, en la pestaña de integraciones."
"icons-no-world-url": "Esta campaña no tiene dirección del mundo de Foundry. Defínala en los ajustes de la campaña, en la pestaña de integraciones.",
"import-not-linked": "Esta campaña no tiene ningún mundo de Foundry vinculado. Conecte uno en los ajustes de la campaña, en la pestaña de integraciones.",
"import-unavailable": "Los datos de Foundry no están disponibles: su bridge no está configurado, no es accesible ahora o su mundo todavía no ha publicado nada.",
"import-world-mismatch": "El bridge de Foundry está mostrando un mundo distinto del que esta campaña tiene vinculado."
},
"icons": {
"path": "Carpeta de iconos",

View File

@@ -0,0 +1,385 @@
// 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)),
};
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 (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");
});
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}`);
}
}
});