Things
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m6s

This commit is contained in:
2026-10-13 22:50:51 +02:00
parent 50828af674
commit af76cf1050
18 changed files with 847 additions and 86 deletions

View File

@@ -20,6 +20,11 @@ let characterSyncRunning = false;
let actorSyncErrorLogged = false;
const syncingActorIds = new Set();
const queuedActorChanges = new Map();
let itemSyncTimeout;
let itemSyncRunning = false;
let itemSyncErrorLogged = false;
const syncingItemIds = new Set();
const queuedItemChanges = new Map();
function getCollectionContents(collection, collectionName) {
if (!collection) {
@@ -240,6 +245,7 @@ async function completeDragonrollCampaignLink(code, options = {}) {
}
scheduleSnapshotSync(0);
setTimeout(initializeCharacterSync, 0);
setTimeout(reconcileDragonrollItems, 2000);
ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign.");
} catch (error) {
console.error(`${MODULE_ID} | Could not complete the campaign link.`, error);
@@ -349,6 +355,9 @@ async function pushFoundryActors(actors, fullSync = false) {
const result = await postDragonroll("foundry/sync/snapshot", {
worldId: game.world.id,
actors: supportedActors.map(serializeFoundryActor),
// Dragonroll deduplicates by name, so sending the world directory next to
// the actor copies keeps a single Item per piece of gear.
items: getWorldItemSnapshots(),
fullSync,
}, token);
@@ -358,6 +367,7 @@ async function pushFoundryActors(actors, fullSync = false) {
await setDragonrollActorId(actor, mapping.actorId);
}
}
await rememberItemMappings(result.items);
actorSyncErrorLogged = false;
}
@@ -378,7 +388,6 @@ function queueActorChange(kind, actor) {
clearTimeout(actorSyncTimeout);
actorSyncTimeout = setTimeout(flushActorChanges, 400);
}
async function flushActorChanges() {
const changes = [...queuedActorChanges.values()];
queuedActorChanges.clear();
@@ -396,6 +405,269 @@ async function flushActorChanges() {
}
}
// --- World item sync -------------------------------------------------------
// Items embedded in an actor travel with that actor's snapshot; the items below
// handle the world-level item directory (game.items) in both directions.
function itemPropertyLabels(item) {
const values = item.system?.properties?.value;
if (!Array.isArray(values) || !values.length || game.system?.id !== "dnd5e") return [];
const propertyConfigs = [
CONFIG.DND5E?.weaponProperties,
CONFIG.DND5E?.armorProperties,
CONFIG.DND5E?.toolProperties,
CONFIG.DND5E?.consumableProperties,
];
return values
.map((key) => {
for (const config of propertyConfigs) {
const label = config?.[key]?.label;
if (label) return String(label).toLowerCase();
}
return typeof key === "string" ? key : "";
})
.filter(Boolean);
}
function serializeFoundryItem(item) {
const data = toPlainData(item);
if (!data) return null;
if (data.img && !/^(https?:|data:|\/\/)/i.test(data.img)) {
data.img = new URL(data.img, window.location.origin).toString();
}
// Dragonroll shows plain property text; send Foundry's own labels when present
// so keys such as "ver" do not end up in its Item list.
const properties = itemPropertyLabels(item);
if (properties.length) data.dragonroll = { properties };
return data;
}
function getWorldItemSnapshots() {
return (game.items?.contents || []).map(serializeFoundryItem).filter(Boolean);
}
function dragonrollItemIdOf(item) {
return item.getFlag?.(MODULE_ID, "itemId") || item.flags?.[MODULE_ID]?.itemId || "";
}
async function withItemSyncSuppressed(item, callback) {
if (!item?.id) return callback();
syncingItemIds.add(item.id);
try {
return await callback();
} finally {
syncingItemIds.delete(item.id);
}
}
async function setDragonrollItemId(item, itemId) {
if (!item || !itemId) return;
await withItemSyncSuppressed(item, () => item.update({
[`flags.${MODULE_ID}.itemId`]: String(itemId),
[`flags.${MODULE_ID}.syncMutation`]: false,
}));
}
async function rememberItemMappings(mappings) {
for (const mapping of mappings || []) {
const item = game.items?.get(mapping.foundryItemId);
if (item && String(dragonrollItemIdOf(item)) !== String(mapping.itemId)) {
await setDragonrollItemId(item, mapping.itemId);
}
}
}
function reportItemSyncError(error) {
if (itemSyncErrorLogged) return;
itemSyncErrorLogged = true;
console.warn(`${MODULE_ID} | Item sync failed and will retry.`, error);
}
// Item pushes are upserts only: the full world snapshot sent with the actors
// owns pruning, because it is the only one that sees every embedded copy.
async function pushFoundryItems(items) {
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || !items.length) return;
const result = await postDragonroll("foundry/sync/item-snapshot", {
worldId: game.world.id,
items: items.map(serializeFoundryItem).filter(Boolean),
}, token);
await rememberItemMappings(result.items);
itemSyncErrorLogged = false;
}
async function deleteDragonrollItem(foundryItemId) {
const token = getSyncToken();
if (!token || !game.world || !foundryItemId) return;
await postDragonroll("foundry/sync/item-delete", {
worldId: game.world.id,
foundryItemId,
}, token);
}
function queueFoundryItemChange(kind, item) {
if (!item || !game.user?.isGM || !getSyncToken()) return;
if (syncingItemIds.has(item.id) || item.flags?.[MODULE_ID]?.syncMutation) return;
queuedItemChanges.set(item.id, { kind, item });
clearTimeout(itemSyncTimeout);
itemSyncTimeout = setTimeout(flushItemChanges, 400);
}
async function flushItemChanges() {
const changes = [...queuedItemChanges.values()];
queuedItemChanges.clear();
const deleted = changes.filter((change) => change.kind === "delete");
const changed = changes.filter((change) => change.kind !== "delete");
try {
for (const change of deleted) await deleteDragonrollItem(change.item.id);
if (changed.length) await pushFoundryItems(changed.map((change) => change.item));
} catch (error) {
reportItemSyncError(error);
for (const change of changes) queuedItemChanges.set(change.item.id, change);
clearTimeout(itemSyncTimeout);
itemSyncTimeout = setTimeout(flushItemChanges, 5000);
}
}
const CATEGORY_TO_FOUNDRY_ITEM_TYPE = {
weapon: "weapon",
armor: "equipment",
shield: "equipment",
consumable: "consumable",
tool: "tool",
"adventuring-gear": "loot",
"magic-item": "loot",
treasure: "loot",
other: "loot",
};
const RARITY_TO_FOUNDRY_VALUE = {
common: "common",
uncommon: "uncommon",
rare: "rare",
"very-rare": "veryRare",
legendary: "legendary",
artifact: "artifact",
};
function makeFoundryItemData(entry) {
const type = CATEGORY_TO_FOUNDRY_ITEM_TYPE[entry.category] || "loot";
const data = {
name: String(entry.name || "").trim(),
type,
system: {
quantity: Number(entry.quantity) || 1,
weight: Number(entry.weight) || 0,
rarity: RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common",
description: { value: entry.description || "" },
},
flags: { [MODULE_ID]: { itemId: String(entry._id), syncMutation: true } },
};
if (type === "equipment") data.system.armor = { type: entry.category === "shield" ? "shield" : "medium" };
return data;
}
function foundryItemUpdateData(entry) {
return {
name: String(entry.name || "").trim(),
"system.quantity": Number(entry.quantity) || 1,
"system.weight": Number(entry.weight) || 0,
"system.rarity": RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common",
"system.description.value": entry.description || "",
};
}
async function applyDragonrollItem(item, entry) {
const updates = foundryItemUpdateData(entry);
const changed = Object.entries(updates).some(([key, value]) => documentValue(item, key) !== value);
await withItemSyncSuppressed(item, async () => {
if (changed) await item.update(updates);
if (dragonrollItemIdOf(item) !== String(entry._id)) {
await item.update({ [`flags.${MODULE_ID}.itemId`]: String(entry._id) });
}
});
}
async function mapDragonrollItem(itemId, foundryItemId) {
const token = getSyncToken();
return postDragonroll("foundry/sync/map-item", {
worldId: game.world.id,
itemId: String(itemId),
foundryItemId: String(foundryItemId),
}, token);
}
async function createFoundryWorldItem(entry) {
const data = makeFoundryItemData(entry);
if (!data.name) return;
const item = await Item.create(data);
if (!item) return;
await withItemSyncSuppressed(item, async () => {
await item.update({ [`flags.${MODULE_ID}.syncMutation`]: false });
});
await mapDragonrollItem(entry._id, item.id);
}
async function reconcileDragonrollItems() {
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || itemSyncRunning) return;
itemSyncRunning = true;
try {
if (game.system.id !== "dnd5e") {
throw new Error("Item sync currently requires the D&D 5e Foundry system.");
}
const result = await getDragonroll("foundry/sync/items", token);
const remoteItems = result.items || [];
const remoteById = new Map(remoteItems.map((entry) => [String(entry._id), entry]));
const localByRemoteId = new Map(game.items.contents
.map((item) => [String(dragonrollItemIdOf(item)), item])
.filter(([itemId]) => itemId));
const retainedFoundryIds = new Set();
for (const entry of remoteItems) {
let item = entry.foundryItemId ? game.items.get(entry.foundryItemId) : null;
if (!item) item = localByRemoteId.get(String(entry._id));
if (item) {
retainedFoundryIds.add(item.id);
await applyDragonrollItem(item, entry);
if (!entry.foundryItemId) await mapDragonrollItem(entry._id, item.id);
} else if (entry.foundryItemId) {
// Imported gear that only exists inside an actor's inventory: its actor
// snapshot owns it, so cloning it into the world would duplicate it.
continue;
} else {
// A Dragonroll item named like an unmapped Foundry item maps to that
// document instead of adding a second copy of the same gear.
const sameName = game.items.contents.find((candidate) => candidate.name === String(entry.name).trim()
&& !dragonrollItemIdOf(candidate));
if (sameName) {
retainedFoundryIds.add(sameName.id);
await mapDragonrollItem(entry._id, sameName.id);
} else {
await createFoundryWorldItem(entry);
}
}
}
for (const item of game.items.contents) {
const itemId = dragonrollItemIdOf(item);
if (!itemId || retainedFoundryIds.has(item.id) || remoteById.has(String(itemId))) continue;
await withItemSyncSuppressed(item, () => item.delete());
}
itemSyncErrorLogged = false;
} catch (error) {
reportItemSyncError(error);
} finally {
itemSyncRunning = false;
}
}
function getDragonrollImageUrl(image) {
if (!image) return "";
if (/^(https?:|data:|\/\/)/i.test(image)) return image;
@@ -715,6 +987,10 @@ Hooks.once("ready", () => {
setInterval(publishHeartbeat, 60000);
setTimeout(initializeCharacterSync, 1000);
setInterval(reconcileDragonrollCharacters, 5000);
// Items reconcile after the character snapshot has landed so Dragonroll has
// already seen the world directory when it starts sending its own items back.
setTimeout(reconcileDragonrollItems, 2000);
setInterval(reconcileDragonrollItems, 5000);
for (const event of [
"createActor", "updateActor", "deleteActor",
@@ -722,10 +998,21 @@ Hooks.once("ready", () => {
]) {
Hooks.on(event, (document) => {
scheduleSnapshotSync();
const actor = document.documentName === "Actor" ? document : document.parent;
if (actor?.documentName === "Actor") {
queueFoundryActorChange(event.startsWith("delete") ? "delete" : "upsert", actor);
const isDelete = event.startsWith("delete");
if (document.documentName === "Actor") {
queueFoundryActorChange(isDelete ? "delete" : "upsert", document);
return;
}
if (document.documentName !== "Item") return;
// Items embedded in an actor travel with that actor's snapshot: adding or
// removing one only changes the actor, never deletes it.
if (document.parent?.documentName === "Actor") {
queueFoundryActorChange("upsert", document.parent);
return;
}
queueFoundryItemChange(isDelete ? "delete" : "upsert", document);
});
}
});