Files
dragonroll/tests/foundry-icon-picker.test.js
Gitea OpenCode Agent 06144e1623
All checks were successful
Test / test (push) Successful in 2s
Fix issue #74: Foundry's icons are not available: its bridge is not set up, or it cannot be reached right now.
2026-10-15 19:24:18 +00:00

240 lines
14 KiB
JavaScript

// Tests for Syndria98/dragonroll#65: picking an item's icon opens a window that asks
// where the icon comes from — upload one from this device, or load one from the icon
// library the linked Foundry world ships in its data directory's `icons/` folder.
// That library runs into the thousands, so it is listed one folder per request, with
// its icons paged and its thumbnails lazy to load.
//
// The icon listing helpers are a pure CommonJS service, so they are required and called
// directly. The windows and the bridge live in files this repository installs no
// dependencies for, so those checks read the sources, like tests/map-viewer.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 read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const iconService = require(path.join(__dirname, "..", "backend", "src", "services", "foundry-icons"));
const foundryService = require(path.join(__dirname, "..", "backend", "src", "services", "foundry"));
const http = require("node:http");
const windowDefsSource = read("frontend", "app", "services", "WindowDefinitions.js");
const itemWindowSource = read("frontend", "app", "components", "windows", "ItemSheetWindow.vue");
const sourceWindowSource = read("frontend", "app", "components", "windows", "ItemIconSourceWindow.vue");
const foundryIconsSource = read("frontend", "app", "components", "windows", "FoundryIconPickerWindow.vue");
const foundryRouteSource = read("backend", "src", "routes", "foundry.js");
const bridgeSource = read("dragonroll-foundry", "bridge", "server.js");
// --- The listing service: what the browser may ask for, and what it gets back ------
test("icon listings always stay inside Foundry's icon root", () => {
assert.equal(iconService.ICON_ROOT, "icons");
assert.equal(iconService.normalizeIconDirectory(""), "icons");
assert.equal(iconService.normalizeIconDirectory(undefined), "icons");
assert.equal(iconService.normalizeIconDirectory("/icons/svg/"), "icons/svg");
assert.equal(iconService.normalizeIconDirectory("icons/sfdcc/axes"), "icons/sfdcc/axes");
assert.equal(iconService.normalizeIconDirectory("icons/./svg"), "icons/svg");
// nothing that leaves `icons/` is a folder this route will list
assert.equal(iconService.normalizeIconDirectory("icons/../secret"), null);
assert.equal(iconService.normalizeIconDirectory("../etc"), null);
assert.equal(iconService.normalizeIconDirectory("systems/dnd5e/icons"), null);
assert.equal(iconService.parentIconDirectory("icons/svg/axes"), "icons/svg");
assert.equal(iconService.parentIconDirectory("icons"), null);
});
test("icons are listed a page at a time, bounded", () => {
assert.deepEqual(iconService.readIconListingPage({}), { limit: iconService.DEFAULT_ICON_PAGE_SIZE, offset: 0 });
assert.deepEqual(iconService.readIconListingPage({ limit: "20", offset: "240" }), { limit: 20, offset: 240 });
// a caller cannot ask for the whole library at once, or for a page before the first
assert.equal(iconService.readIconListingPage({ limit: "99999" }).limit, iconService.MAX_ICON_PAGE_SIZE);
assert.equal(iconService.readIconListingPage({ offset: "-10" }).offset, 0);
});
test("only image files become icons, and they load from the world's own address", () => {
const listing = iconService.shapeIconListing({
base: "https://vtt.example.com/",
dir: "icons/svg",
listing: {
directories: ["icons/svg/creature", "icons/svg/creature", "icons/svg"],
files: ["icons/svg/dice.svg", "icons/svg/sword.png", "icons/svg/readme.txt", "stray.md"],
offset: 0,
next: 120,
},
});
assert.equal(listing.dir, "icons/svg");
assert.equal(listing.parent, "icons");
assert.deepEqual(listing.folders.map((folder) => folder.path), ["icons/svg/creature"]);
assert.deepEqual(listing.folders.map((folder) => folder.name), ["creature"]);
assert.deepEqual(listing.files.map((icon) => icon.path), ["icons/svg/dice.svg", "icons/svg/sword.png"]);
assert.equal(listing.files[0].name, "dice.svg");
assert.equal(listing.files[0].url, "https://vtt.example.com/icons/svg/dice.svg");
assert.equal(listing.next, 120);
});
test("an icon path with spaces still gives the browser a loadable url", () => {
assert.equal(
iconService.joinFoundryAssetUrl("http://vtt.test:30000", "icons/sfdcc/axes/halberd sword.svg"),
"http://vtt.test:30000/icons/sfdcc/axes/halberd%20sword.svg"
);
assert.equal(iconService.joinFoundryAssetUrl("", "icons/svg/dice.svg"), "");
});
// --- The backend route ------------------------------------------------------------
test("the foundry proxy lists one icon folder for one of the caller's campaigns", () => {
assert.match(foundryRouteSource, /router\.get\(["']\/icons["'], async \(req, res\)/);
const route = /router\.get\(["']\/icons[\s\S]*?module\.exports/.exec(foundryRouteSource)?.[0] ?? foundryRouteSource;
// the campaign is where the world address is kept, so it has to be the caller's own
assert.match(route, /findOwnedCampaign\(req\.query\.campaign, req\.user\.id\)/);
assert.match(foundryRouteSource, /Campaign\.findOne\(\{\s*_id:\s*campaignId,\s*createdBy:\s*userId\s*\}\)/);
assert.match(route, /campaign\.settings\?\.integrations\?\.foundryUrl/);
assert.match(route, /requestFoundry\(`api\/icons\?\$\{query\}`\)/);
// a folder outside the icon root is refused before it reaches the Foundry host
assert.match(route, /const dir = normalizeIconDirectory\(req\.query\.dir\);/);
});
// --- The bridge on the Foundry host ------------------------------------------------
test("the bridge lists a core icon folder and never leaves the icon root", () => {
assert.match(bridgeSource, /const dataPath = \(process\.env\.DRAGONROLL_FOUNDRY_DATA_PATH \|\| ""\)\.trim\(\);/);
assert.match(bridgeSource, /if \(pathname === "\/api\/icons"\) return sendIconListing\(request, response\);/);
assert.match(bridgeSource, /if \(!dataPath\) return sendJson\(response, 503, \{ status: "error", msg: "foundry\.errors\.icons-unavailable" \}\);/);
const normalize = /function normalizeIconDirectory\(input\) \{[\s\S]*?\n\}/.exec(bridgeSource)?.[0] ?? "";
assert.match(normalize, /segments\.includes\("\.\."\) \|\| segments\[0\] !== iconRoot/);
// the answer is one folder plus the offset of the next page of its icons
assert.match(bridgeSource, /directories\.sort\(\(a, b\) => a\.localeCompare\(b\)\);/);
assert.match(bridgeSource, /const page = files\.slice\(offset, offset \+ limit\);/);
assert.match(bridgeSource, /next: offset \+ page\.length < files\.length \? offset \+ page\.length : null,/);
});
// --- The windows -------------------------------------------------------------------
test("choosing an icon opens its own window from the item sheet", () => {
assert.match(windowDefsSource, /item_icon_source:\s*{\s*title:[^}]*ItemIconSourceWindow\.vue/s);
assert.match(windowDefsSource, /foundry_icons:\s*{\s*title:[^}]*FoundryIconPickerWindow\.vue/s);
// the item window asks where the icon comes from instead of opening a file dialog
assert.match(itemWindowSource, /CreateChildWindow\(id, ['"]item_icon_source['"]/);
assert.doesNotMatch(itemWindowSource, /type="file"/);
});
test("the icon source window offers uploading and Foundry, and uploads the local file", () => {
assert.match(sourceWindowSource, /\$t\(['"]campaigns\.item\.icon-picker\.upload['"]\)/);
assert.match(sourceWindowSource, /\$t\(['"]campaigns\.item\.icon-picker\.foundry['"]\)/);
// upload: a local file, sent through the item route like the character sheet does its photo
assert.match(sourceWindowSource, /type="file" accept="image\/\*"/);
assert.match(sourceWindowSource, /\/item\/upload-image\?item=\$\{itemId\}/);
assert.match(sourceWindowSource, /formData\.append\(['"]image['"], file\)/);
// and it hands the item over to the icon browser, as its child window
assert.match(sourceWindowSource, /CreateChildWindow\(id, ['"]foundry_icons['"]/);
});
test("the icon browser browses the world's icons folder by folder", () => {
assert.match(foundryIconsSource, /\/foundry\/icons\?\$\{params\.toString\(\)\}/);
// one folder per request: navigating a folder asks for it, and going up asks for its parent
assert.match(foundryIconsSource, /Load\(ICON_ROOT\)/);
assert.match(foundryIconsSource, /@click="Load\(folder\.path\)"/);
assert.match(foundryIconsSource, /Load\(listing\.value\.parent \|\| ICON_ROOT\)/);
// lazy in every way that matters: a page of icons at a time, thumbnails fetched when seen
assert.match(foundryIconsSource, /if \(offset\) params\.set\(['"]offset['"], String\(offset\)\)/);
assert.match(foundryIconsSource, /@click="Load\(listing\.dir, listing\.next\)"/);
assert.match(foundryIconsSource, /loading="lazy"/);
// picking an icon stores the world's url and tells the item window about it
assert.match(foundryIconsSource, /Server\(\)\.post\(['"]\/item\/update['"], \{ id: itemId, image: icon\.url \}\)/);
assert.match(foundryIconsSource, /emitter\.emit\(['"]campaign-entry-updated['"], \{ entityType: ['"]item['"], entry: response\.data\.item \}\)/);
assert.match(foundryIconsSource, /ClearWindow\(\{ type: ['"]item_icon_source['"] \}\)/);
});
// --- The bridge the backend reads the icon library through (issue #74) --------
//
// The icon window reaches the world's `icons/` folder through the backend, which
// in turn reads the bridge that the world already pushes its snapshot to. When
// that push works the campaign reads as connected, so a read that still reports
// the bridge as unset is the bug this guards against.
// Set the bridge environment for one call and put it back exactly as it was.
function withBridgeEnv(env, run) {
const keys = ["FOUNDRY_API_URL", "FOUNDRY_API_CLIENT_URL", "FOUNDRY_API_TOKEN"];
const saved = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
for (const key of keys) {
if (env[key] === undefined) delete process.env[key];
else process.env[key] = env[key];
}
return Promise.resolve()
.then(run)
.finally(() => {
for (const key of keys) {
if (saved[key] === undefined) delete process.env[key];
else process.env[key] = saved[key];
}
});
}
test("a connected world answers icon reads through the bridge set under the client URL", async () => {
// A world that connects and syncs is often configured with FOUNDRY_API_CLIENT_URL
// alone — the address its own client reaches. The backend read falls back to it,
// so the icon window is not told its bridge is unset while the world is right there.
const answers = [];
const bridge = http.createServer((request, response) => {
answers.push(request.url);
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify({ status: "ok", dir: "icons", directories: ["icons/svg"], files: [], offset: 0, next: null }));
});
await new Promise((resolve) => bridge.listen(0, "127.0.0.1", resolve));
const clientUrl = `http://127.0.0.1:${bridge.address().port}/`;
try {
const result = await withBridgeEnv(
{ FOUNDRY_API_URL: undefined, FOUNDRY_API_CLIENT_URL: clientUrl, FOUNDRY_API_TOKEN: "read-token" },
() => foundryService.requestFoundry("api/icons?dir=icons&offset=0&limit=120"),
);
assert.equal(result.status, 200);
assert.equal(result.data.status, "ok");
assert.equal(answers.length, 1);
assert.match(answers[0], /^\/api\/icons\?/);
} finally {
await new Promise((resolve) => bridge.close(resolve));
}
});
test("without a bridge under either name a read says it is not configured", async () => {
const error = await withBridgeEnv(
{ FOUNDRY_API_URL: undefined, FOUNDRY_API_CLIENT_URL: undefined, FOUNDRY_API_TOKEN: undefined },
() => foundryService.requestFoundry("api/icons?dir=icons").then(() => null, (err) => err),
);
assert.equal(error?.code, "FOUNDRY_NOT_CONFIGURED");
});
test("the icon window says what actually failed instead of always blaming the bridge", () => {
// axios rejects a non-2xx answer, so the catch reads the route's own i18n key
// off the response: a campaign with no world address is told as much rather
// than as a bridge that is not set up.
assert.match(foundryIconsSource, /requestError\.response\?\.data\?\.msg/);
assert.match(foundryIconsSource, /requestError\.response\?\.data\?\.msg \|\| ['"]foundry\.errors\.icons-unavailable['"]/);
});
// --- Strings -----------------------------------------------------------------------
test("every locale names the icon windows and their controls", () => {
for (const locale of ["en", "es", "ca"]) {
const windows = JSON.parse(read("frontend", "i18n", "locales", locale, "windows.json"));
for (const key of ["icon-source", "foundry-icons"]) {
assert.ok(windows[key], `${locale} is missing the ${key} window title`);
}
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
for (const key of ["intro", "upload", "upload-hint", "foundry", "foundry-hint"]) {
assert.ok(campaigns.item?.["icon-picker"]?.[key], `${locale} is missing campaigns.item.icon-picker.${key}`);
}
const foundry = JSON.parse(read("frontend", "i18n", "locales", locale, "foundry.json"));
for (const key of ["loading", "empty", "load-more", "up"]) {
assert.ok(foundry.icons?.[key], `${locale} is missing foundry.icons.${key}`);
}
for (const key of ["icons-unavailable", "icons-no-world-url"]) {
assert.ok(foundry.errors?.[key], `${locale} is missing foundry.errors.${key}`);
}
}
});