V1.14.0: spell slots, rests, and a level-up checklist

- Spell slots. Every class that casts has a slot tracker, worked out
  from class and level: the full-caster table for bards, clerics,
  druids, sorcerers and wizards, the half-caster table for paladins and
  rangers (from level 2), and a warlock's few slots of one level. It is
  in the Spellcasting card on the sheet and in the character panel, and
  the party overview has a column for it. A player presses Use to spend
  a slot; only the DM gives one back.
- Rests. The DM's "Rest…" button, beside the character list and on the
  party overview, rests any of the party at once. A short rest shows
  which Hit Dice each character can roll and heals from what they
  rolled (typed in, or rolled by the site), and gives a warlock their
  slots. A long rest puts back HP, every spell slot and half the level
  in Hit Dice, and clears temp HP.
- Hit Dice are counted: one per level, shown on the sheet, the panel
  and the party overview.
- Level Up. "Level Up…" on a sheet takes a character up one level with
  the whole checklist: the new max HP and a full heal, the class's new
  special abilities for levels 2 to 10, a Boon where the level grants
  one (Toughened raises Extra AC, Hardy gives temp HP now and after
  each long rest), fresh spell slots and new spells, and the free
  upgrade of one standard weapon.
- A level typed into the Level field still writes down what the class
  gains on the way up, and leaves a line where a Boon is owed.
- The docs cover all of it, with a generated list of what each class
  gains at each level. The Hollowcrown seed's note no longer says to
  track spell slots on paper.
- New migration: spent spell slots and Hit Dice on a character.
- All packages at version 1.14.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-10 10:47:56 +02:00
co-authored by Claude Opus 5.5
parent 3a867fd1a1
commit e9f8169286
34 changed files with 2855 additions and 61 deletions
+256
View File
@@ -2813,3 +2813,259 @@ describe('a campaign from a world seed', () => {
expect((await request(app).get('/campaigns').set(auth)).body.campaigns).toEqual([]);
});
});
// A built character's class is whatever the dice offered. These tests need a
// particular one, at a particular level, so it is set straight on the row.
async function buildAs(campaignId, auth, name, characterClass, level = 1) {
const characterId = await buildCharacter(campaignId, auth, name);
await prisma.character.update({ where: { id: characterId }, data: { characterClass, level, conScore: 14, specialAbilities: null } });
return characterId;
}
describe('spell slots', () => {
itIfDb('come from class and level; the player spends one, only the DM gives one back', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('slots');
const characterId = await buildAs(campaign.id, playerAuth, 'Merla', 'WIZARD', 3);
const slots = (auth, body) => request(app).post(`/characters/${characterId}/spell-slots`).set(auth).send(body);
const levels = (res) => res.body.character.sheet.spellSlots.levels;
const sheet = (await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character.sheet;
expect(sheet.spellSlots).toMatchObject({ kind: 'FULL', restoresOn: 'LONG' });
expect(sheet.spellSlots.levels).toEqual([
{ level: 1, max: 4, used: 0, remaining: 4 },
{ level: 2, max: 2, used: 0, remaining: 2 },
]);
// The player casts: one slot at a time.
const cast = await slots(playerAuth, { action: 'use', level: 2 });
expect(cast.status).toBe(200);
expect(levels(cast)[1]).toEqual({ level: 2, max: 2, used: 1, remaining: 1 });
expect((await slots(playerAuth, { action: 'use', level: 2 })).status).toBe(200);
const none = await slots(playerAuth, { action: 'use', level: 2 });
expect(none.status).toBe(400);
expect(none.body.error).toMatch(/no 2nd-level spell slots left/);
// A slot level the character does not have.
expect((await slots(playerAuth, { action: 'use', level: 3 })).status).toBe(400);
expect((await slots(playerAuth, { action: 'use', level: 0 })).status).toBe(400);
// Getting one back is the DM's.
expect((await slots(playerAuth, { action: 'set', level: 2, used: 0 })).status).toBe(403);
expect((await slots(playerAuth, { action: 'restore' })).status).toBe(403);
const back = await slots(dmAuth, { action: 'set', level: 2, used: 1 });
expect(levels(back)[1].remaining).toBe(1);
// The DM can spend one for the player too, and never sets more than there are.
expect(levels(await slots(dmAuth, { action: 'use', level: 1 }))[0].used).toBe(1);
expect(levels(await slots(dmAuth, { action: 'set', level: 1, used: 9 }))[0].used).toBe(4);
expect(levels(await slots(dmAuth, { action: 'restore' })).map((s) => s.used)).toEqual([0, 0]);
// The party list and the character panel show them too.
await slots(playerAuth, { action: 'use', level: 1 });
const listed = (await request(app).get(`/campaigns/${campaign.id}/characters`).set(dmAuth)).body.characters.find((c) => c.id === characterId);
expect(listed.spellSlots.levels[0].remaining).toBe(3);
expect(listed.hitDice).toMatchObject({ size: 6, count: 3, remaining: 3, conModifier: expect.any(Number) });
const quick = (await request(app).get(`/characters/${characterId}/quick-stats`).set(playerAuth)).body.quickStats;
expect(quick.spellSlots.levels[0].remaining).toBe(3);
// Dropping a level takes the slots it gave with it, spent ones included.
await slots(playerAuth, { action: 'use', level: 2 });
const lower = (await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ level: 1 })).body.character;
expect(lower.sheet.spellSlots.levels).toEqual([{ level: 1, max: 2, used: 1, remaining: 1 }]);
const higher = (await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ level: 5 })).body.character;
expect(higher.sheet.spellSlots.levels.map((s) => [s.max, s.used])).toEqual([[4, 1], [3, 0], [2, 0]]);
});
itIfDb('are not there for a class without spells', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('noslots');
const characterId = await buildAs(campaign.id, playerAuth, 'Brakk', 'FIGHTER', 5);
expect((await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character.sheet.spellSlots).toBeNull();
const res = await request(app).post(`/characters/${characterId}/spell-slots`).set(dmAuth).send({ action: 'use', level: 1 });
expect(res.status).toBe(400);
expect(res.body.error).toMatch(/no spell slots/);
});
});
describe('rests', () => {
itIfDb('a long rest gives back HP, spell slots and half the Hit Dice', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('longrest');
const wizardId = await buildAs(campaign.id, playerAuth, 'Merla', 'WIZARD', 4);
const fighterId = await buildAs(campaign.id, dmAuth, 'Brakk', 'FIGHTER', 4);
const get = async (id) => (await request(app).get(`/characters/${id}`).set(dmAuth)).body.character;
await request(app).patch(`/characters/${wizardId}`).set(dmAuth).send({ currentHp: 2, tempHp: 3, hitDiceUsed: 4 });
for (const level of [1, 1, 2]) await request(app).post(`/characters/${wizardId}/spell-slots`).set(playerAuth).send({ action: 'use', level });
await request(app).patch(`/characters/${fighterId}`).set(dmAuth).send({ currentHp: 5 });
const rest = (body) => request(app).post(`/campaigns/${campaign.id}/rest`).set(dmAuth).send(body);
// Only the DM calls a rest, and only for this campaign's characters.
expect((await request(app).post(`/campaigns/${campaign.id}/rest`).set(playerAuth).send({ type: 'LONG', characters: [{ characterId: wizardId }] })).status).toBe(403);
expect((await rest({ type: 'LONG', characters: [{ characterId: 'nobody' }] })).status).toBe(400);
expect((await rest({ type: 'NAP', characters: [{ characterId: wizardId }] })).status).toBe(400);
// Only the wizard rests.
const res = await rest({ type: 'LONG', characters: [{ characterId: wizardId }] });
expect(res.status).toBe(200);
expect(res.body.results).toHaveLength(1);
const wizard = await get(wizardId);
expect(res.body.results[0]).toMatchObject({ characterId: wizardId, name: 'Merla', skipped: null, hpBefore: 2, hpAfter: wizard.sheet.hp.max, slotsRestored: true });
expect(res.body.results[0].hitDice).toMatchObject({ regained: 2, left: 2, of: 4 });
expect(wizard.currentHp).toBe(wizard.sheet.hp.max);
expect(wizard.tempHp).toBe(0);
expect(wizard.sheet.hitDice).toMatchObject({ used: 2, remaining: 2 });
expect(wizard.sheet.spellSlots.levels.every((s) => s.used === 0)).toBe(true);
expect((await get(fighterId)).currentHp).toBe(5);
// The dead get nothing from a rest.
await request(app).patch(`/characters/${fighterId}`).set(dmAuth).send({ currentHp: -999 });
const both = await rest({ type: 'LONG', characters: [{ characterId: wizardId }, { characterId: fighterId }] });
expect(both.body.results.find((r) => r.characterId === fighterId).skipped).toMatch(/dead/);
expect((await get(fighterId)).deathSaves.state).toBe('DEAD');
});
itIfDb('a short rest spends Hit Dice to heal, and gives a warlock their slots', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('shortrest');
const fighterId = await buildAs(campaign.id, playerAuth, 'Brakk', 'FIGHTER', 4);
const warlockId = await buildAs(campaign.id, dmAuth, 'Vex', 'WARLOCK', 4);
const get = async (id) => (await request(app).get(`/characters/${id}`).set(dmAuth)).body.character;
const rest = (characters) => request(app).post(`/campaigns/${campaign.id}/rest`).set(dmAuth).send({ type: 'SHORT', characters });
await request(app).patch(`/characters/${fighterId}`).set(dmAuth).send({ currentHp: 1 });
await request(app).patch(`/characters/${warlockId}`).set(dmAuth).send({ currentHp: 1 });
await request(app).post(`/characters/${warlockId}/spell-slots`).set(dmAuth).send({ action: 'use', level: 2 });
const con = (await get(fighterId)).sheet.abilities.CON.modifier;
// More dice than there are, or a total the dice cannot show: nothing is written for anyone.
expect((await rest([{ characterId: warlockId }, { characterId: fighterId, hitDice: 5, rolled: 20 }])).status).toBe(400);
expect((await rest([{ characterId: fighterId, hitDice: 2, rolled: 21 }])).status).toBe(400);
expect((await get(warlockId)).sheet.spellSlots.levels[0].used).toBe(1);
// Two d10s rolled at the table for 9; the warlock spends none.
const res = await rest([{ characterId: fighterId, hitDice: 2, rolled: 9 }, { characterId: warlockId }]);
expect(res.status).toBe(200);
const fighterResult = res.body.results.find((r) => r.characterId === fighterId);
expect(fighterResult).toMatchObject({ hpBefore: 1, hpAfter: 1 + 9 + 2 * con, slotsRestored: false });
expect(fighterResult.hitDice).toMatchObject({ size: 10, spent: 2, total: 9, conBonus: 2 * con, left: 2, of: 4, rolls: null });
const fighter = await get(fighterId);
expect(fighter.currentHp).toBe(1 + 9 + 2 * con);
expect(fighter.sheet.hitDice).toMatchObject({ used: 2, remaining: 2 });
const warlockResult = res.body.results.find((r) => r.characterId === warlockId);
expect(warlockResult).toMatchObject({ hpBefore: 1, hpAfter: 1, slotsRestored: true });
expect((await get(warlockId)).sheet.spellSlots.levels[0].used).toBe(0);
// With no total given the site rolls the dice itself.
const rolled = (await rest([{ characterId: fighterId, hitDice: 1 }])).body.results[0];
expect(rolled.hitDice.rolls).toHaveLength(1);
expect(rolled.hitDice.rolls[0]).toBeGreaterThanOrEqual(1);
expect(rolled.hitDice.rolls[0]).toBeLessThanOrEqual(10);
expect(rolled.hitDice.left).toBe(1);
expect((await get(fighterId)).currentHp).toBe(Math.min(fighter.sheet.hp.max, fighter.currentHp + rolled.hitDice.rolls[0] + con));
});
});
describe('levelling up', () => {
itIfDb('raises the level, heals to the new maximum and writes down the new features', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('levelup');
const characterId = await buildAs(campaign.id, playerAuth, 'Brakk', 'FIGHTER');
await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ currentHp: 1 });
const levelUp = (auth, body = {}) => request(app).post(`/characters/${characterId}/level-up`).set(auth).send(body);
// Levelling is the DM's, and so is looking at what it brings.
expect((await levelUp(playerAuth)).status).toBe(403);
expect((await request(app).get(`/characters/${characterId}/level-up`).set(playerAuth)).status).toBe(403);
const plan = (await request(app).get(`/characters/${characterId}/level-up`).set(dmAuth)).body.plan;
expect(plan).toMatchObject({ fromLevel: 1, toLevel: 2, boon: null, spells: null, spellSlots: null });
expect(plan.features.map((f) => f.name)).toEqual(['Action Surge']);
expect(plan.maxHp.to).toBeGreaterThan(plan.maxHp.from);
const res = await levelUp(dmAuth);
expect(res.status).toBe(200);
const character = res.body.character;
expect(character.level).toBe(2);
expect(character.sheet.hp.max).toBe(plan.maxHp.to);
expect(character.currentHp).toBe(plan.maxHp.to);
expect(character.specialAbilities).toBe('Action Surge — Once per short rest, take one extra action on your turn.');
// Level 4 grants a Boon, which has to be picked.
await levelUp(dmAuth);
expect((await levelUp(dmAuth)).status).toBe(400);
expect((await levelUp(dmAuth, { boon: 'FLIGHT' })).status).toBe(400);
const toughened = (await levelUp(dmAuth, { boon: 'TOUGHENED' })).body.character;
expect(toughened.level).toBe(4);
expect(toughened.armorBonus).toBe(character.armorBonus + 1);
expect(toughened.specialAbilities).toMatch(/^Toughened — \+1 AC/m);
expect(toughened.specialAbilities).toMatch(/^Improved Critical — /m);
// Level 5 has no Boon to give; level 6 (a fighter's third) will not give Toughened twice.
expect((await levelUp(dmAuth, { boon: 'HARDY' })).status).toBe(400);
await levelUp(dmAuth);
const again = await levelUp(dmAuth, { boon: 'TOUGHENED' });
expect(again.status).toBe(400);
expect(again.body.error).toMatch(/only once/);
const hardy = (await levelUp(dmAuth, { boon: 'HARDY' })).body.character;
expect(hardy.level).toBe(6);
expect(hardy.tempHp).toBe(5);
// A long rest takes temp HP away, but Hardy's comes back.
await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ tempHp: 0 });
const rested = await request(app).post(`/campaigns/${campaign.id}/rest`).set(dmAuth).send({ type: 'LONG', characters: [{ characterId }] });
expect(rested.body.results[0].tempHp).toBe(5);
});
itIfDb('gives the free weapon upgrade, new spells and fresh slots', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('levelgear');
const characterId = await buildAs(campaign.id, playerAuth, 'Merla', 'WIZARD');
const weaponId = (await request(app).post(`/campaigns/${campaign.id}/weapons/from-library`).set(dmAuth).send({ key: 'dagger' })).body.weapon.id;
await request(app).post(`/characters/${characterId}/weapons`).set(dmAuth).send({ weaponId });
const spell = (name, level) => request(app).post(`/campaigns/${campaign.id}/spells`).set(dmAuth).send({ name, level });
const boltId = (await spell('Test Bolt', 1)).body.spell.id;
const wardId = (await spell('Test Ward', 1)).body.spell.id;
await request(app).post(`/characters/${characterId}/spells`).set(dmAuth).send({ spellId: boltId });
await request(app).post(`/characters/${characterId}/spell-slots`).set(playerAuth).send({ action: 'use', level: 1 });
const other = await setupCampaign('levelgear-other');
const foreignSpellId = (await request(app).post(`/campaigns/${other.campaign.id}/spells`).set(other.dmAuth).send({ name: 'Elsewhere', level: 1 })).body.spell.id;
const plan = (await request(app).get(`/characters/${characterId}/level-up`).set(dmAuth)).body.plan;
expect(plan.spells).toEqual({ maxSpellLevel: 1, unlocksSpellLevel: null, newSpells: 2, newCantrips: 0 });
expect(plan.spellSlots.levels).toEqual([{ level: 1, max: 3, used: 0, remaining: 3 }]);
expect(plan.weapons).toEqual([expect.objectContaining({ weaponId, level: 1, damageDice: '1d4', nextDamageDice: '1d6' })]);
const levelUp = (body) => request(app).post(`/characters/${characterId}/level-up`).set(dmAuth).send(body);
expect((await levelUp({ weaponId: 'not-held' })).status).toBe(400);
expect((await levelUp({ spellIds: [foreignSpellId] })).status).toBe(400);
// A spell already known is simply kept.
const character = (await levelUp({ weaponId, spellIds: [boltId, wardId] })).body.character;
expect(character.level).toBe(2);
expect(character.weapons[0]).toMatchObject({ weaponId, level: 2, scaledDamageDice: '1d6' });
expect(character.spells.map((s) => s.spell.name).sort()).toEqual(['Test Bolt', 'Test Ward']);
expect(character.sheet.spellSlots.levels).toEqual([{ level: 1, max: 3, used: 0, remaining: 3 }]);
// The weapon is now as high as its holder, so it has no upgrade to take at level 3... until they get there.
const next = (await request(app).get(`/characters/${characterId}/level-up`).set(dmAuth)).body.plan;
expect(next.weapons).toHaveLength(1);
expect(next.spells.unlocksSpellLevel).toBe(2);
});
itIfDb('a level set by hand still writes down what the class gains', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('levelset');
const characterId = await buildAs(campaign.id, playerAuth, 'Sly', 'ROGUE');
await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ specialAbilities: 'Sneak Attack — Once per turn, deal an extra 1d6 damage.' });
const patch = (body) => request(app).patch(`/characters/${characterId}`).set(dmAuth).send(body);
const lines = (await patch({ level: 4 })).body.character.specialAbilities.split('\n');
expect(lines[0]).toMatch(/^Sneak Attack — .*2d6/);
expect(lines).toContainEqual(expect.stringMatching(/^Cunning Action — /));
expect(lines).toContainEqual(expect.stringMatching(/^Boon \(level 4\) — Choose one/));
// Going down takes nothing away, and coming back up adds nothing twice.
await patch({ level: 1 });
expect((await patch({ level: 4 })).body.character.specialAbilities.split('\n')).toEqual(lines);
// Text sent along with the level is taken as it is.
expect((await patch({ level: 5, specialAbilities: 'Mine.' })).body.character.specialAbilities).toBe('Mine.');
// Level 20 is the top.
await patch({ level: 20 });
expect((await request(app).post(`/characters/${characterId}/level-up`).set(dmAuth).send({})).status).toBe(400);
});
});
+79 -3
View File
@@ -4,11 +4,13 @@ const prisma = require('../db');
const { requireAuth } = require('../middleware/auth');
const { requireCampaignMember, requireDM } = require('../middleware/campaignAccess');
const { generateInviteCode } = require('../utils/inviteCode');
const { computeCharacterSheet, GEAR_STATS, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL } = require('../game/calculations');
const { SHEET_INCLUDE, settleHp } = require('../utils/sheet');
const { computeCharacterSheet, GEAR_STATS, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL, MAX_LEVEL } = require('../game/calculations');
const { rollDie } = require('../game/buildFlow');
const { SHEET_INCLUDE, sheetOf, settleHp } = require('../utils/sheet');
const { WEAPON_LIBRARY, ITEM_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../game/data/library');
const { visitedLocationIds } = require('../utils/locations');
const { deathSaveInfo } = require('../utils/hp');
const { deathSaveInfo, lifeState } = require('../utils/hp');
const { hitDiceProblem, shortRest, longRest } = require('../utils/rest');
const { CURRENCIES } = require('../utils/grants');
const { findSeed, normalizeCode, CODE_LENGTH } = require('../seeds');
const { createCampaignFromSeed } = require('../seeds/createCampaign');
@@ -237,6 +239,11 @@ function characterSummary(character) {
cash: character.cash,
maxHp: character.buildStage === 'COMPLETE' ? sheet.hp.max : null,
armorClass: character.buildStage === 'COMPLETE' ? sheet.armorClass : null,
// What is left to spend before the next rest: the slot tracker (null for
// a character with no spell slots) and Hit Dice, with the Constitution
// modifier each die healed is rolled with.
spellSlots: character.buildStage === 'COMPLETE' ? sheet.spellSlots : null,
hitDice: character.buildStage === 'COMPLETE' ? { ...sheet.hitDice, conModifier: sheet.abilities.CON.modifier } : null,
currentLocationId: character.currentLocationId,
currentLocationName: character.currentLocation ? character.currentLocation.name : null,
};
@@ -315,6 +322,75 @@ router.post('/:id/characters', requireCampaignMember(), async (req, res, next) =
}
});
// ---------------------------------------------------------------------------
// Rests — the DM rests any of the party at once (utils/rest.js)
// ---------------------------------------------------------------------------
const restSchema = z.object({
type: z.enum(['SHORT', 'LONG']),
characters: z
.array(
z.object({
characterId: z.string(),
// A short rest only: how many Hit Dice this character spends, and what
// they added up to if they were rolled at the table. Left out, the
// dice are rolled here.
hitDice: z.number().int().min(0).max(MAX_LEVEL).default(0),
rolled: z.number().int().min(0).max(1000).nullable().optional(),
})
)
.min(1)
.max(200),
});
// A long rest puts HP, spell slots and half the Hit Dice back. A short rest
// spends Hit Dice to heal and gives a warlock their slots. Nothing is written
// unless every character asked for can take the rest as asked. The answer
// says what happened to each, in the party's order.
router.post('/:id/rest', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = restSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { type } = parsed.data;
const asked = new Map(parsed.data.characters.map((entry) => [entry.characterId, entry]));
const characters = await prisma.character.findMany({
where: { id: { in: [...asked.keys()] }, campaignId: req.campaign.id, buildStage: 'COMPLETE' },
include: SHEET_INCLUDE,
orderBy: { createdAt: 'asc' },
});
if (characters.length !== asked.size) {
return res.status(400).json({ error: 'Pick finished characters from this campaign.' });
}
const outcomes = [];
for (const character of characters) {
const who = { characterId: character.id, name: character.name };
const sheet = sheetOf(character);
if (lifeState(character) === 'DEAD') {
outcomes.push({ ...who, skipped: `${character.name} is dead: a rest does nothing for them.` });
} else if (type === 'LONG') {
outcomes.push({ ...who, skipped: null, ...longRest(character, sheet) });
} else {
const { hitDice: dice, rolled = null } = asked.get(character.id);
const problem = hitDiceProblem(character, sheet, dice, rolled);
if (problem) return res.status(400).json({ error: problem });
const rolls = dice > 0 && rolled == null ? Array.from({ length: dice }, () => rollDie(sheet.hitDice.size)) : null;
outcomes.push({ ...who, skipped: null, ...shortRest(character, sheet, { dice, rolls, rolled }) });
}
}
const rested = outcomes.filter((outcome) => outcome.data);
await prisma.$transaction(rested.map((outcome) => prisma.character.update({ where: { id: outcome.characterId }, data: outcome.data })));
const io = req.app.get('io');
for (const { characterId } of rested) io.to(`campaign:${req.campaign.id}`).emit('character:updated', { characterId });
res.json({ type, results: outcomes.map(({ data, result, ...who }) => ({ ...who, ...result })) });
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Weapons (campaign-level pool; the DM manages it and sees all of it)
// ---------------------------------------------------------------------------
+196 -5
View File
@@ -11,9 +11,13 @@ const {
getClassSpellcastingAbility,
scaledDamageDice,
canUseGear,
spellSlotState,
MAX_GEAR_LEVEL,
MAX_LEVEL,
MAX_SLOT_LEVEL,
ABILITIES,
} = require('../game/calculations');
const { LevelUpError, advance, levelUpPlan } = require('../game/levelUp');
const {
rollDie,
rollAbilityScore,
@@ -31,7 +35,7 @@ const characterOptions = require('../game/data/characterOptions');
const { SKILLS } = require('../game/data/skills');
const { CURRENCIES, COINS, COIN_VALUE, COIN_COLUMN, InsufficientGoldError, adjustGold, spendCoins, worthInGold, giveGear } = require('../utils/grants');
const { recordVisits } = require('../utils/locations');
const { SHEET_INCLUDE, settleHp } = require('../utils/sheet');
const { SHEET_INCLUDE, sheetOf, settleHp } = require('../utils/sheet');
const { absorbDamage, NO_DEATH_SAVES, lifeState, deathSaveInfo, settleDeathSaves, changeHp, rollDeathSave } = require('../utils/hp');
const router = express.Router();
@@ -158,8 +162,9 @@ const patchCharacterSchema = z.object({
appearance: z.string().max(4000).nullable().optional(),
privateNotes: z.string().max(4000).nullable().optional(),
currentLocationId: z.string().nullable().optional(),
level: z.number().int().min(1).max(20).optional(),
level: z.number().int().min(1).max(MAX_LEVEL).optional(),
xp: z.number().int().min(0).optional(),
hitDiceUsed: z.number().int().min(0).max(MAX_LEVEL).optional(),
});
// Progression and placement are the DM's call, and so is rewriting what the
@@ -168,8 +173,9 @@ const patchCharacterSchema = z.object({
// a player cannot heal or hurt their own character. The owning player can
// edit the rest of their own sheet. Gold is not patchable at all — it only
// moves through the ledger (POST /:id/gold). The armor bonus is the DM's
// adjustment on top of what equipped gear gives, so it is the DM's too.
const DM_ONLY_PATCH_FIELDS = ['currentHp', 'tempHp', 'level', 'xp', 'currentLocationId', 'speedOverride', 'armorBonus', 'specialAbilities', 'background', 'appearance'];
// adjustment on top of what equipped gear gives, so it is the DM's too. Hit
// Dice are spent on a rest, which the DM runs.
const DM_ONLY_PATCH_FIELDS = ['currentHp', 'tempHp', 'level', 'xp', 'currentLocationId', 'speedOverride', 'armorBonus', 'specialAbilities', 'background', 'appearance', 'hitDiceUsed'];
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
@@ -184,7 +190,30 @@ router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, n
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
if (!req.isDM && DM_ONLY_PATCH_FIELDS.some((field) => parsed.data[field] !== undefined)) {
return res.status(403).json({ error: 'Only the DM can change HP, temp HP, level, XP, speed, armor bonus, location, special abilities, background or appearance.' });
return res.status(403).json({ error: 'Only the DM can change HP, temp HP, Hit Dice, level, XP, speed, armor bonus, location, special abilities, background or appearance.' });
}
const newLevel = parsed.data.level ?? req.character.level;
if (parsed.data.level !== undefined || parsed.data.hitDiceUsed !== undefined) {
// A character has one Hit Die per level, so none can be spent beyond that.
parsed.data.hitDiceUsed = Math.min(parsed.data.hitDiceUsed ?? req.character.hitDiceUsed, newLevel);
}
if (newLevel !== req.character.level) {
// Spent slots of a level the character no longer has are forgotten.
const slots = spellSlotState(req.character.characterClass, newLevel, req.character.spellSlotsUsed);
const tally = [];
for (const slot of slots ? slots.levels : []) tally[slot.level - 1] = slot.used;
parsed.data.spellSlotsUsed = Array.from(tally, (used) => used || 0);
}
if (req.character.buildStage === 'COMPLETE' && newLevel > req.character.level && parsed.data.specialAbilities === undefined) {
// Setting a higher level by hand still writes down what the class gains
// on the way there. A Boon is left as a line saying one is owed: picking
// it is part of levelling up properly (POST /:id/level-up).
let abilities = req.character.specialAbilities;
for (let level = req.character.level + 1; level <= newLevel; level++) {
abilities = advance(abilities, req.character.characterClass, level).specialAbilities;
}
parsed.data.specialAbilities = abilities;
}
// Damage is soaked by temp HP before it reaches real HP — unless this
@@ -307,6 +336,166 @@ router.post('/:id/death-saves', requireCharacterAccess({ write: true }), async (
}
});
// ---------------------------------------------------------------------------
// Spell slots — the slot tracker. How many slots there are comes from class
// and level (game/calculations.js); the character row keeps how many are spent.
// ---------------------------------------------------------------------------
const ORDINALS = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th'];
const slotLevelSchema = z.number().int().min(1).max(MAX_SLOT_LEVEL);
const spellSlotSchema = z.discriminatedUnion('action', [
// Casting a spell: one slot of that level is spent.
z.object({ action: z.literal('use'), level: slotLevelSchema }),
// The DM setting how many of a level are spent: giving one back, or fixing a mistake.
z.object({ action: z.literal('set'), level: slotLevelSchema, used: z.number().int().min(0).max(9) }),
// The DM giving every slot back.
z.object({ action: z.literal('restore') }),
]);
// The owning player spends their own slots, one at a time. Getting one back
// is the DM's: by hand here, or for everyone with a rest
// (POST /campaigns/:id/rest).
router.post('/:id/spell-slots', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
const parsed = spellSlotSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { character } = req;
if (character.buildStage !== 'COMPLETE') return res.status(400).json({ error: 'Character build is not finished yet.' });
const input = parsed.data;
if (input.action !== 'use' && !req.isDM) {
return res.status(403).json({ error: 'Only the DM can give a spell slot back.' });
}
const slots = spellSlotState(character.characterClass, character.level, character.spellSlotsUsed);
if (!slots) return res.status(400).json({ error: `${character.name} has no spell slots.` });
// The stored tally, squared up with what the class has at this level.
const used = Array.from({ length: slots.levels[slots.levels.length - 1].level }, (_, i) => {
const slot = slots.levels.find((s) => s.level === i + 1);
return slot ? slot.used : 0;
});
if (input.action === 'restore') {
used.fill(0);
} else {
const slot = slots.levels.find((s) => s.level === input.level);
if (!slot) return res.status(400).json({ error: `${character.name} has no ${ORDINALS[input.level - 1]}-level spell slots.` });
if (input.action === 'use') {
if (slot.remaining === 0) {
return res.status(400).json({
error: `${character.name} has no ${ORDINALS[input.level - 1]}-level spell slots left. They come back on a ${slots.restoresOn === 'SHORT' ? 'short or long' : 'long'} rest.`,
});
}
used[input.level - 1] = slot.used + 1;
} else {
used[input.level - 1] = Math.min(input.used, slot.max);
}
}
await prisma.character.update({ where: { id: character.id }, data: { spellSlotsUsed: used } });
const full = await loadFullCharacter(character.id);
emitCharacterUpdated(req);
res.json({ character: serializeCharacter(full, req.isOwner) });
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Levelling up — one level at a time, with the checklist that goes with it
// (game/levelUp.js): the new level, full HP, the class's new special
// abilities, a Boon where the level grants one, new spells, fresh spell slots
// and the free weapon upgrade.
// ---------------------------------------------------------------------------
// Answers the request and returns false when this character cannot be levelled up.
function canLevelUp(req, res, character) {
let refusal = null;
if (!req.isDM) refusal = [403, 'Only the DM can level a character up.'];
else if (character.buildStage !== 'COMPLETE') refusal = [400, 'Character build is not finished yet.'];
else if (character.level >= MAX_LEVEL) refusal = [400, `${character.name} is already level ${MAX_LEVEL}, the highest there is.`];
if (refusal) res.status(refusal[0]).json({ error: refusal[1] });
return !refusal;
}
// What the next level brings, for the DM to look over before saying yes.
router.get('/:id/level-up', requireCharacterAccess(), async (req, res, next) => {
try {
const character = await loadFullCharacter(req.character.id);
if (!canLevelUp(req, res, character)) return;
const plan = levelUpPlan(character);
const after = sheetOf({ ...character, level: plan.toLevel, spellSlotsUsed: [] });
res.json({ plan: { ...plan, maxHp: { from: sheetOf(character).hp.max, to: after.hp.max }, spellSlots: after.spellSlots } });
} catch (err) {
next(err);
}
});
const levelUpSchema = z.object({
boon: z.string().optional(), // which Boon, at a level that grants one
weaponId: z.string().nullable().optional(), // the weapon that gets the free upgrade
spellIds: z.array(z.string()).max(50).default([]), // spells newly granted
});
router.post('/:id/level-up', requireCharacterAccess({ write: true }), async (req, res, next) => {
try {
const parsed = levelUpSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { boon, weaponId, spellIds } = parsed.data;
const character = await loadFullCharacter(req.character.id);
if (!canLevelUp(req, res, character)) return;
const plan = levelUpPlan(character);
if (plan.boon && !boon) return res.status(400).json({ error: `Level ${plan.toLevel} grants a Boon: pick one.` });
if (!plan.boon && boon) return res.status(400).json({ error: `Level ${plan.toLevel} does not grant a Boon.` });
if (weaponId && !plan.weapons.some((w) => w.weaponId === weaponId)) {
return res.status(400).json({ error: 'That weapon cannot take the free upgrade: it has to be one this character holds, of standard growth, below their new level.' });
}
const spellsFound = await prisma.spell.count({ where: { id: { in: spellIds }, campaignId: character.campaignId } });
if (new Set(spellIds).size !== spellIds.length || spellsFound !== spellIds.length) {
return res.status(400).json({ error: "Pick the new spells from this campaign's spell list, each once." });
}
let gained;
try {
gained = advance(character.specialAbilities, character.characterClass, plan.toLevel, boon);
} catch (err) {
if (!(err instanceof LevelUpError)) throw err;
return res.status(400).json({ error: err.message });
}
const armorBonus = clamp(character.armorBonus + gained.armorBonus, -30, 30);
const maxHp = sheetOf({ ...character, level: plan.toLevel, armorBonus }).hp.max;
await prisma.$transaction(async (tx) => {
if (weaponId) {
await tx.characterWeapon.update({
where: { characterId_weaponId: { characterId: character.id, weaponId } },
data: { level: { increment: 1 } },
});
}
await tx.characterSpell.createMany({ data: spellIds.map((spellId) => ({ characterId: character.id, spellId })), skipDuplicates: true });
await tx.character.update({
where: { id: character.id },
data: {
level: plan.toLevel,
specialAbilities: gained.specialAbilities,
armorBonus,
tempHp: Math.max(character.tempHp, gained.tempHp),
spellSlotsUsed: [],
// The new maximum, and healed to it. Levelling does not raise the dead.
...(lifeState(character) === 'DEAD' ? {} : { currentHp: maxHp, ...NO_DEATH_SAVES }),
},
});
});
const full = await loadFullCharacter(character.id);
emitCharacterUpdated(req);
res.json({ character: serializeCharacter(full, req.isOwner) });
} catch (err) {
next(err);
}
});
router.delete('/:id', requireCharacterAccess(), async (req, res, next) => {
try {
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
@@ -955,6 +1144,8 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
speed: sheet.speed,
proficiencyBonus: sheet.proficiencyBonus,
spellcasting: sheet.spellcasting,
spellSlots: sheet.spellSlots,
hitDice: sheet.hitDice,
passivePerception: sheet.passivePerception,
abilities: sheet.abilities,
specialAbilities: character.specialAbilities,