V1.12.0: worlds from a code, shops and cash in the seeds, up-to-date packages
- A DM can start a campaign from a ready-made world by typing its six-character code: "+ New Campaign" on the Campaigns page, then "Or start from a ready-made world". The whole world is built in one go with them as its DM: locations, weapons, items, spells, monsters, NPCs, encounters and notes. ALDENF is Aldenfell, HOLLOW is Hollowcrown. - A world is one file in /backend/seeds. Drop another in and its code works straight away, with no restart. "npm run seeds:check" lists every world, or what is wrong with one: a misspelt field, a name used twice, an encounter pointing at something the file does not have. A file with a mistake in it is never offered. docs/SEEDS.md has the format. - A seed can now hold everything a campaign can: gear effects, an NPC's wares and exchange rate, things for sale at an encounter, and rewards in silver, copper and cash. - The database seed creates the admin account and nothing else. The Aldenfell and Hollowcrown seed commands are gone: worlds come from codes. - Hollowcrown follows the V3 book: 4 starting items and 3 things equipped, the book's effects on every weapon and item, armor as items (library, modern and magic), worn gear at the book's levels, damage types on monsters, ten shop scenes with prices and stock, five money changers, Meridian loot as cash and mixed hoards as gold, silver and copper. - Aldenfell: the Shield and Leather Armor change AC, Mireille and the Founding Fair stalls sell things, and the book's missing scenes are in (E5, E7, E15, E16, E18, E23-24, E26, the Drowned Shrine, Sevrisk's Hollow, a wyvern pass). The locket is found with Investigation, as the book has it. - Packages are up to date: Prisma 7 (with the pg driver adapter and a prisma.config.js that holds the database URL), Express 5, zod 4, dotenv 18, jest 30, bcrypt 6 and TypeScript 7. "npm audit" finds nothing. Install scripts are approved for Prisma and bcrypt. On a server: "npm install", then "npm run deploy". - The frontend's five lint warnings are fixed; useAuth and usePagination have files of their own. - All packages at version 1.12.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
// D&D Campaign Manager — Prisma schema
|
||||
// Postgres. Run `npx prisma migrate dev --name init` after `DATABASE_URL` is set,
|
||||
// then `npx prisma db seed` using the seed script built from /seed-data/*.json
|
||||
// (see CLAUDE_BUILD_PROMPT.md, "Database" section).
|
||||
// Postgres. The connection (DATABASE_URL) is set in prisma.config.js, not here.
|
||||
// Run `npx prisma migrate dev` then `npx prisma generate`; `npx prisma db seed`
|
||||
// adds the admin account (prisma/seed.js). Worlds are created in the app from
|
||||
// the seeds in /backend/seeds.
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
@@ -9,7 +10,6 @@ generator client {
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
// Adds the Hollowcrown: The Rift Between Worlds campaign
|
||||
// (seed-data/hollowcrown.js) for the admin account. Not part of the default
|
||||
// seed — run it on its own:
|
||||
//
|
||||
// npm run seed:hollowcrown
|
||||
//
|
||||
// Like every seed it only adds (see seedCampaign.js): it never touches other
|
||||
// campaigns, and does nothing if the admin already has an active Hollowcrown.
|
||||
const { run, fromLibrary } = require('./seedCampaign');
|
||||
const { WEAPON_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../src/game/data/library');
|
||||
const hollowcrown = require('../seed-data/hollowcrown.js');
|
||||
|
||||
const startingSpells = new Set(hollowcrown.startingSpells);
|
||||
for (const key of startingSpells) fromLibrary(SPELL_LIBRARY, key); // fail early on a misspelt key
|
||||
|
||||
run({
|
||||
...hollowcrown,
|
||||
// The book's starting picks come from the site library; its modern relics
|
||||
// and magic weapons are never starting options.
|
||||
weapons: [
|
||||
...hollowcrown.libraryWeapons.map((key) => fromLibrary(WEAPON_LIBRARY, key, { isStartingOption: true })),
|
||||
...hollowcrown.weapons,
|
||||
],
|
||||
// The whole spell library goes in, so a spell is there to hand out the
|
||||
// moment a character unlocks it; only the book's Session 0 list is offered
|
||||
// in the builder.
|
||||
spells: [
|
||||
...SPELL_LIBRARY.map(({ key }) => fromLibrary(SPELL_LIBRARY, key, { isStartingOption: startingSpells.has(key) })),
|
||||
...hollowcrown.spells,
|
||||
],
|
||||
monsters: [...hollowcrown.libraryMonsters.map((key) => fromLibrary(MONSTER_LIBRARY, key)), ...hollowcrown.monsters],
|
||||
});
|
||||
+48
-26
@@ -1,32 +1,54 @@
|
||||
// The default seed: the Aldenfell campaign (seed-data/aldenfell.js) for the
|
||||
// admin account. See seedCampaign.js for what a seed does and why it is safe
|
||||
// to run against a live database.
|
||||
// The database seed: makes sure the admin account exists, and nothing else.
|
||||
//
|
||||
// npx prisma db seed add what is missing
|
||||
// npx prisma db seed create the admin account if it is missing
|
||||
// npx prisma db seed -- --reset DESTRUCTIVE: delete every user, campaign,
|
||||
// character, note, etc. first
|
||||
//
|
||||
// Other campaigns have their own command (npm run seed:hollowcrown).
|
||||
// It only ever adds, so it is safe against a live database: an existing
|
||||
// account, and its password, is left alone. SEED_ADMIN_EMAIL /
|
||||
// SEED_ADMIN_PASSWORD / SEED_ADMIN_NAME override the account that is created.
|
||||
//
|
||||
// Species/classes/skills are NOT seeded as rows — they're fixed game-rule
|
||||
// tables ported into src/game/data/*.js, as is the default weapon/spell/monster
|
||||
// library DMs pull from. The default weapons (seed-data/weapons.json) ARE
|
||||
// seeded, into the campaign, since weapons are per-campaign in the schema.
|
||||
const { run, fromLibrary } = require('./seedCampaign');
|
||||
const { SPELL_LIBRARY } = require('../src/game/data/library');
|
||||
const defaultWeapons = require('../seed-data/weapons.json');
|
||||
const aldenfell = require('../seed-data/aldenfell.js');
|
||||
// Worlds are not seeded here. A campaign is created in the app, blank or from
|
||||
// one of the world seeds in /backend/seeds by its code (docs/SEEDS.md).
|
||||
//
|
||||
// Species/classes/skills are not rows either: they are fixed game-rule tables
|
||||
// in src/game/data/*.js, as is the library DMs pull weapons, items, spells
|
||||
// and monsters from.
|
||||
const bcrypt = require('bcrypt');
|
||||
const prisma = require('../src/db');
|
||||
const { loadSeeds } = require('../src/seeds');
|
||||
|
||||
run(
|
||||
{
|
||||
...aldenfell,
|
||||
// Everyday weapons are what a new character picks from; the rest are earned.
|
||||
weapons: [...defaultWeapons.map((w) => ({ ...w, isStartingOption: true })), ...aldenfell.weapons],
|
||||
items: aldenfell.items.map(({ starting, ...item }) => ({ ...item, isStartingOption: Boolean(starting) })),
|
||||
spells: [
|
||||
...aldenfell.spells.starting.map((key) => fromLibrary(SPELL_LIBRARY, key, { isStartingOption: true })),
|
||||
...aldenfell.spells.earned.map((key) => fromLibrary(SPELL_LIBRARY, key, { isStartingOption: false })),
|
||||
],
|
||||
},
|
||||
{ reset: process.argv.includes('--reset') },
|
||||
);
|
||||
const ADMIN_EMAIL = process.env.SEED_ADMIN_EMAIL || 'joshua@crosscode.co.za';
|
||||
const ADMIN_PASSWORD = process.env.SEED_ADMIN_PASSWORD || '12345678';
|
||||
const ADMIN_NAME = process.env.SEED_ADMIN_NAME || 'Joshua';
|
||||
|
||||
async function seed({ reset = false } = {}) {
|
||||
if (reset) {
|
||||
// Truncating the two roots cascades through every table that references them.
|
||||
await prisma.$executeRawUnsafe('TRUNCATE TABLE "users", "campaigns" RESTART IDENTITY CASCADE');
|
||||
console.log('Database reset: every user and campaign was deleted.');
|
||||
}
|
||||
|
||||
if (await prisma.user.findUnique({ where: { email: ADMIN_EMAIL } })) {
|
||||
console.log(`Admin account ${ADMIN_EMAIL} already exists — left as it is.`);
|
||||
} else {
|
||||
await prisma.user.create({
|
||||
data: { email: ADMIN_EMAIL, passwordHash: await bcrypt.hash(ADMIN_PASSWORD, 12), displayName: ADMIN_NAME },
|
||||
});
|
||||
console.log(`Admin/DM login created: ${ADMIN_EMAIL} / ${ADMIN_PASSWORD}`);
|
||||
console.log(' Change that password from the account page ("Account" in the navigation) once you are logged in.');
|
||||
}
|
||||
|
||||
const worlds = loadSeeds().filter((world) => !world.error);
|
||||
if (worlds.length) {
|
||||
console.log('Worlds to start a campaign from (Campaigns → New Campaign → world code):');
|
||||
for (const { code, seed: world } of worlds) console.log(` ${code} ${world.campaign.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
seed({ reset: process.argv.includes('--reset') })
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(() => prisma.$disconnect());
|
||||
|
||||
@@ -1,210 +0,0 @@
|
||||
// Shared by the campaign seeds (seed.js, seed-hollowcrown.js): makes sure the
|
||||
// admin account exists, then adds one fully-built campaign for it.
|
||||
//
|
||||
// A seed only ever ADDS, so it is safe against a live database. The admin
|
||||
// account is created if it is missing (an existing one, and its password, is
|
||||
// left alone), and the campaign is added unless that account already owns an
|
||||
// active campaign of the same name. To get a fresh copy, archive or delete the
|
||||
// old one in the app and run the seed again.
|
||||
//
|
||||
// SEED_ADMIN_EMAIL / SEED_ADMIN_PASSWORD / SEED_ADMIN_NAME override the
|
||||
// account that is created.
|
||||
//
|
||||
// `content` is one campaign, with every pool as rows shaped like the Prisma
|
||||
// models minus ids:
|
||||
// campaign, locations, weapons, items, spells, monsters, npcs,
|
||||
// sharedNotes, dmNotes (note bodies, in reading order), and
|
||||
// encounters, in the order they should list:
|
||||
// { name, mode, description, dmNotes,
|
||||
// location: a location's name (optional) — where the scene is,
|
||||
// monsters: [[monster name, count, display name?, max HP?], ...],
|
||||
// npcs: [NPC name | { name, hp }, ...],
|
||||
// rewards: [{ gold } | { weapon } | { item }, each with optional
|
||||
// quantity, level (defaults to the entry's starting level)
|
||||
// and note] }
|
||||
const bcrypt = require('bcrypt');
|
||||
const { PrismaClient } = require('@prisma/client');
|
||||
const { generateInviteCode } = require('../src/utils/inviteCode');
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
const ADMIN_EMAIL = process.env.SEED_ADMIN_EMAIL || 'joshua@crosscode.co.za';
|
||||
const ADMIN_PASSWORD = process.env.SEED_ADMIN_PASSWORD || '12345678';
|
||||
const ADMIN_NAME = process.env.SEED_ADMIN_NAME || 'Joshua';
|
||||
|
||||
// Notes list newest-first on screen, so they are stamped a second apart,
|
||||
// backwards: the first entry in the seed data is the one at the top.
|
||||
function bookOrder(index) {
|
||||
return new Date(Date.now() - index * 1000);
|
||||
}
|
||||
|
||||
function byName(rows) {
|
||||
return new Map(rows.map((row) => [row.name, row]));
|
||||
}
|
||||
|
||||
function lookup(map, name, what, encounterName) {
|
||||
const row = map.get(name);
|
||||
if (!row) throw new Error(`Encounter "${encounterName}" references unknown ${what} "${name}"`);
|
||||
return row;
|
||||
}
|
||||
|
||||
async function createCampaign(db, admin, content) {
|
||||
const campaign = await db.campaign.create({
|
||||
data: {
|
||||
...content.campaign,
|
||||
inviteCode: generateInviteCode(),
|
||||
ownerId: admin.id,
|
||||
members: { create: { userId: admin.id, role: 'DM' } },
|
||||
},
|
||||
});
|
||||
const campaignId = campaign.id;
|
||||
const inCampaign = (rows) => rows.map((row) => ({ ...row, campaignId }));
|
||||
|
||||
await db.location.createMany({ data: inCampaign(content.locations) });
|
||||
await db.weapon.createMany({ data: inCampaign(content.weapons) });
|
||||
await db.item.createMany({ data: inCampaign(content.items) });
|
||||
await db.spell.createMany({ data: inCampaign(content.spells) });
|
||||
await db.monster.createMany({ data: inCampaign(content.monsters) });
|
||||
await db.npc.createMany({ data: inCampaign(content.npcs) });
|
||||
|
||||
const monsters = byName(await db.monster.findMany({ where: { campaignId } }));
|
||||
const npcs = byName(await db.npc.findMany({ where: { campaignId } }));
|
||||
const weapons = byName(await db.weapon.findMany({ where: { campaignId } }));
|
||||
const items = byName(await db.item.findMany({ where: { campaignId } }));
|
||||
const locations = byName(await db.location.findMany({ where: { campaignId } }));
|
||||
|
||||
let rewardCount = 0;
|
||||
for (const [index, enc] of content.encounters.entries()) {
|
||||
const participants = [];
|
||||
for (const [name, count, displayName, hp] of enc.monsters || []) {
|
||||
const monster = lookup(monsters, name, 'monster', enc.name);
|
||||
const label = displayName || monster.name;
|
||||
const maxHp = hp ?? monster.maxHp;
|
||||
for (let i = 1; i <= count; i++) {
|
||||
participants.push({
|
||||
monsterId: monster.id,
|
||||
displayName: count > 1 ? `${label} #${i}` : label,
|
||||
currentHp: maxHp,
|
||||
maxHp,
|
||||
isMonster: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const entry of enc.npcs || []) {
|
||||
const { name, hp } = typeof entry === 'string' ? { name: entry } : entry;
|
||||
const npc = lookup(npcs, name, 'NPC', enc.name);
|
||||
// An NPC with no combat stats takes part with no hit points to track.
|
||||
const maxHp = hp ?? npc.maxHp ?? 0;
|
||||
participants.push({ npcId: npc.id, displayName: npc.name, currentHp: maxHp, maxHp, isMonster: false });
|
||||
}
|
||||
|
||||
// Rewards list oldest-first, so these are stamped forwards.
|
||||
const rewards = (enc.rewards || []).map(({ gold, weapon, item, quantity, level, note }, i) => {
|
||||
const createdAt = new Date(Date.now() + i);
|
||||
if (gold) return { type: 'GOLD', gold, note, createdAt };
|
||||
const entry = weapon ? lookup(weapons, weapon, 'weapon', enc.name) : lookup(items, item, 'item', enc.name);
|
||||
return {
|
||||
type: weapon ? 'WEAPON' : 'ITEM',
|
||||
[weapon ? 'weaponId' : 'itemId']: entry.id,
|
||||
quantity: quantity ?? 1,
|
||||
level: Math.max(level ?? entry.minLevel, entry.minLevel),
|
||||
note,
|
||||
createdAt,
|
||||
};
|
||||
});
|
||||
rewardCount += rewards.length;
|
||||
|
||||
await db.encounter.create({
|
||||
data: {
|
||||
campaignId,
|
||||
name: enc.name,
|
||||
mode: enc.mode,
|
||||
description: enc.description,
|
||||
dmNotes: enc.dmNotes,
|
||||
locationId: enc.location ? lookup(locations, enc.location, 'location', enc.name).id : null,
|
||||
sortOrder: index,
|
||||
participants: { create: participants },
|
||||
rewards: { create: rewards },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const notes = [
|
||||
...content.sharedNotes.map((body) => ({ body, visibility: 'SHARED' })),
|
||||
...content.dmNotes.map((body) => ({ body, visibility: 'DM_ONLY' })),
|
||||
];
|
||||
await db.note.createMany({
|
||||
data: notes.map((n, i) => ({ ...n, campaignId, authorId: admin.id, createdAt: bookOrder(i) })),
|
||||
});
|
||||
|
||||
const starting = (rows) => rows.filter((row) => row.isStartingOption).length;
|
||||
console.log(` Campaign: ${campaign.name} — invite code ${campaign.inviteCode}`);
|
||||
console.log(
|
||||
` ${content.weapons.length} weapons (${starting(content.weapons)} starting), ${content.items.length} items ` +
|
||||
`(${starting(content.items)} starting), ${content.spells.length} spells (${starting(content.spells)} starting), ` +
|
||||
`${content.locations.length} locations`,
|
||||
);
|
||||
console.log(
|
||||
` ${content.monsters.length} monsters, ${content.npcs.length} NPCs, ${content.encounters.length} encounters ` +
|
||||
`(${rewardCount} rewards lined up), ${notes.length} notes`,
|
||||
);
|
||||
}
|
||||
|
||||
async function resetDatabase() {
|
||||
// Truncating the two roots cascades through every table that references them.
|
||||
await prisma.$executeRawUnsafe('TRUNCATE TABLE "users", "campaigns" RESTART IDENTITY CASCADE');
|
||||
}
|
||||
|
||||
// `reset` is DESTRUCTIVE: every user, campaign, character, note, etc. is
|
||||
// deleted before anything is added.
|
||||
async function seed(content, { reset = false } = {}) {
|
||||
if (reset) {
|
||||
await resetDatabase();
|
||||
console.log('Database reset: every user and campaign was deleted.');
|
||||
}
|
||||
|
||||
let admin = await prisma.user.findUnique({ where: { email: ADMIN_EMAIL } });
|
||||
if (admin) {
|
||||
console.log(`Admin account ${ADMIN_EMAIL} already exists — left as it is.`);
|
||||
} else {
|
||||
admin = await prisma.user.create({
|
||||
data: { email: ADMIN_EMAIL, passwordHash: await bcrypt.hash(ADMIN_PASSWORD, 12), displayName: ADMIN_NAME },
|
||||
});
|
||||
console.log(`Admin/DM login created: ${ADMIN_EMAIL} / ${ADMIN_PASSWORD}`);
|
||||
console.log(' Change that password from the account page (click your name, top right) once you are logged in.');
|
||||
}
|
||||
|
||||
const existing = await prisma.campaign.findFirst({
|
||||
where: { ownerId: admin.id, name: content.campaign.name, archivedAt: null },
|
||||
});
|
||||
if (existing) {
|
||||
console.log(`${ADMIN_EMAIL} already has an active "${existing.name}" campaign — nothing added.`);
|
||||
console.log(' For a fresh copy, archive or delete it under Campaign Settings and run the seed again.');
|
||||
return;
|
||||
}
|
||||
|
||||
// One transaction, so a failed seed doesn't leave half a campaign behind.
|
||||
console.log('Seeding campaign...');
|
||||
await prisma.$transaction((tx) => createCampaign(tx, admin, content), { timeout: 120000, maxWait: 20000 });
|
||||
console.log('Seed complete.');
|
||||
}
|
||||
|
||||
// Runs a seed script to completion: exit code 1 on failure, connection closed either way.
|
||||
function run(content, options) {
|
||||
return seed(content, options)
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(() => prisma.$disconnect());
|
||||
}
|
||||
|
||||
// A copy of a library entry as a pool row: its `key` and picker-only tags dropped.
|
||||
function fromLibrary(library, key, extra = {}) {
|
||||
const template = library.find((entry) => entry.key === key);
|
||||
if (!template) throw new Error(`Unknown library entry "${key}"`);
|
||||
const { key: _key, category, classes, ...row } = template;
|
||||
return { ...row, ...extra };
|
||||
}
|
||||
|
||||
module.exports = { run, fromLibrary };
|
||||
Reference in New Issue
Block a user