@pubdoor/dmv
v0.4.2
Published
The Dungeon Master's Vault 5e rules engine, compiled from ClojureScript
Readme
@pubdoor/dmv
This package is the 5e rules engine from Dungeon Master's Vault, compiled from ClojureScript to one ES module. It builds a character from its saved choices and returns the computed sheet: ability scores, armor class, hit points, spells, and the selections still open. It evaluates the 2014 rules and contains SRD 5.1 content only.
Install
npm install --save-exact @pubdoor/dmvThe package is public on npm, so you need no token and no .npmrc. Pin an
exact version, as --save-exact does. See Versions.
The package is ESM only. Load it with import from an ES module: a .mjs
file, or a project with "type": "module". CommonJS require is not
supported.
Evaluate a character
import { emptyCharacter, evaluate } from "@pubdoor/dmv";
const { built, selections } = evaluate(emptyCharacter());
console.log(built.classes); // ["barbarian"]
console.log(built["armor-class"]); // 12
console.log(built["max-hit-points"]); // 13
console.log(selections.length); // 17A character is a strict entity in Transit-JSON, the format the old app
saves. Store it as it is, and change it only with the functions below.
fixtures/README.md
describes the fields of built.
Exported functions
The package exports the functions below. types/index.d.ts holds their
full signatures and the types.
evaluate(entity, options?)builds a character and returns{ built, selections }.importCharacter(entity)migrates a character saved by the old app, as Transit-JSON or as the old server's EDN, and returns{ entity, legacyId }. Pass.entityto the other functions.readServerEdn(text)reads an old server response, which is EDN, into an array of values. Use it for the character list and the custom magic items.exportCharacter(entity)serializes a character as the old app saves it.emptyCharacter()returns the builder's new character, a level 1 barbarian.select(entity, path, optionKey, options?)selects an option.deselect(entity, path, optionKey, options?)removes a selected option.setValue(entity, key, value)sets a character value, such as"character-name".setField(entity, path, value, options?)sets an option's value, such as hit points or an ability score.addLevel(entity, classKey, options?)adds a level to a class.removeLevel(entity, classKey, options?)removes the highest level of a class.setClass(entity, index, classKey, options?)replaces a class with another at level 1.addClass(entity, classKey, options?)adds a class at level 1.removeClass(entity, classKey, options?)removes a class.addStartingEquipment(entity, backgroundKey, options?)replaces the background starting equipment.addInventoryItem(entity, selectionKey, itemKey)adds an item to an inventory selection.removeInventoryItem(entity, selectionKey, itemKey)removes an item from an inventory selection.increaseAbility(entity, path, abilityKey, options?)adds one to an ability in an ability score improvement.decreaseAbility(entity, path, abilityKey, options?)removes one pick of an ability from an ability score improvement.autofill(entity, options?)fills a character at random, as the builder's random character button does.parseOrcbrew(text, options?)reads an.orcbrewfile through the old importer and returns{ success, data, log, conflicts, skipped }.datais homebrew, the packs as verbose Transit-JSON keyed by pack name:options.existingwith the file merged in, as the old app merged it. Two forms that the old engine ignored are fixed on import, each fix logged inlog.changes: an ability key such as:conbecomes:orcpub.dnd.e5.character/conin a race'sabilities, a feat'sability-increasesandprereqs, a class'sprofssave, a class's or subclass'sspellcastingability, and a:spelllevel-modifier'sability(normalized-ability-key). Askill-optionsormulticlass-skill-optionswithoutchoosegetschoose1, the builder's default (defaulted-choose).validateForExport(homebrew, options?)checks packs before export, as the old app's export buttons did, and checks each item's key, pack, and nils. It returns{ valid, packs, filled }.filledis the homebrew with those items repaired and with placeholders for missing required fields, which the old app's "export anyway" wrote.orcbrewToEdn(homebrew, options?)returns.orcbrewtext: all packs as the old app'sall-content.orcbrew, or withoptions.packone pack alone.options.prettypretty-prints it.renameKey(homebrew, { pack, contentType, from, to })renames one item's key in one pack, as the old conflict modal's rename did, and returns the new homebrew. It also rewrites the pack's references to the item: a class's subclasses, the spells that list it, and the classes and subclasses that use its spell list; a race's subraces and the feats that require it; a selection'slevel-selections. Pass aKeyConflict'scontent-type,key, and suggested key. Saved characters keep the old key, soreconcileMissingContentreports them for a remap. A subclass is the exception: its option takes its key from the name, so a character keeps its pick, and the builtlevels.<class>.subclassstays the same.reconcileMissingContent(entity, homebrew?, options?)checks every option key in a character against the template for homebrew, or for the SRD alone, and returns{ hasMissing, items, unresolvedOptions }.itemslists each race, subrace, background, class, subclass, or feat that does not resolve, with the old app's suggestions from the loaded packs.unresolvedOptionslists any other choice that does not resolve under a parent that does, such as a custom magic item whenoptions.magicItemsdoes not hold it. The entity is not changed.buildTemplate(homebrew?, options?)builds the template for homebrew, or for the SRD alone, and returns{ summary, shape, content }: the top-level selections and their option keys, the template's structure without functions, and the content lists, such as races and classes.keys.selectionKeys(homebrew?, options?)andkeys.optionKeys(homebrew?, options?)return every selection key and every option key in the template for homebrew, or for the SRD alone, once each and sorted. Saved characters and.orcbrewfiles refer to content by these keys.validate.race(record),validate.spell(record), and the other validators check one homebrew item as the old builders' save did, and return{ ok, problems, item }. See the validators section.
Each mutation returns a new entity. It throws with the reason when the old builder would refuse the same change.
Content lists
The build writes the SRD content as JSON files next to the engine, so that pages such as a spell list can load content without the engine. Import a list by its file name:
const { default: spells } = await import("@pubdoor/dmv/content/spells.json", {
with: { type: "json" },
});
console.log(spells.length); // 319| File | Items | What each item holds |
|---|---|---|
| classes.json | 12 | Key and name. The choices are in buildTemplate().shape |
| races.json | 9 | The race, its subraces, and its traits |
| backgrounds.json | 1 | The background |
| feats.json | 1 | Key and name |
| languages.json | 16 | Key and name |
| spells.json | 319 | The spell |
| monsters.json | 317 | The monster |
| magic-items.json | 805 | The magic item. A weapon or armor item becomes one item per base weapon or armor, as the builder lists them |
| weapons.json | 40 | The weapon. An SRD weapon has its weight in pounds, as a number; the sling has none. A magic weapon has the weight of its base weapon |
| ammunition.json | 5 | The ammunition |
| armor.json | 14 | The armor or shield |
| equipment.json | 162 | The gear, tool, pack, mount, or vehicle |
| treasure.json | 11 | The coin or gem |
Keywords are "ns/name" strings, as in built. Functions and the
engine's modifiers and selections are left out. The lists hold the SRD
only: homebrew content is in the homebrew itself.
The ./content/*.json export has no types condition, so TypeScript does
not apply the package's types to these imports. To use the types in
types/index.d.ts, cast each import to its ContentLists entry:
import type { ContentLists } from "@pubdoor/dmv";
const spells = (await import("@pubdoor/dmv/content/spells.json", { with: { type: "json" } }))
.default as ContentLists["spells"];Load the engine as an async chunk
dist/pubdoor.js is large, so load it with a dynamic import() behind a
splash screen, not with a static import in the app's entry chunk:
const engine = await import("@pubdoor/dmv");A bundler such as Vite then puts the engine in its own chunk, which the browser caches between visits. Pages that need only content lists import the JSON files and never load the engine.
Bundle size
On the :advanced release build, dist/pubdoor.js is about 1.5 MiB, or
about 400 KiB gzipped. The 13 files in dist/content/ add about 1.5 MiB,
which the engine never loads. monsters.json is about 470 KiB of that.
Before ORC-42, dist/pubdoor.js was about 2 MiB and held the monsters.
test/bundle.test.ts logs the exact sizes in CI and fails if
dist/pubdoor.js grows past its budget.
The build leaves these namespaces out of dist/pubdoor.js:
character/random.cljc, everything under templates/, pdf_spec.cljc,
char_decision_tree.cljc, and the monster list in monsters.cljc.
test/bundle.test.ts checks each one.
The rules option
evaluate, autofill, and every mutation with an options argument take
{ rules }. The only value is "2014", which is the default. Any other
value throws.
The homebrew option
evaluate, autofill, and the mutations also take { homebrew }: the
loaded .orcbrew packs, keyed by pack name, as verbose Transit-JSON. To
load a file, pass the current homebrew to parseOrcbrew as
options.existing and replace it with the result's data. parseOrcbrew
merges the file in as the old app did, so do not merge packs yourself.
Without the option, characters build against the SRD only. The engine
rebuilds its template only when the homebrew or the magic items change.
The magic items option
evaluate, autofill, the mutations, buildTemplate, keys, and
reconcileMissingContent also take { magicItems }: the user's custom
magic items, as readServerEdn returns them for the old server's
GET /dnd/5e/items. Pass that array as it is. The old app gave the same
response to its template without change. With the option, the template's
Magic Weapons, Magic Armor, and Other Magic Items selections list the
custom items, so a character can carry and equip them, and an equipped
item's modifiers and bonuses apply. A weapon or armor with subtypes
becomes one option for each base item that matches, keyed
<name>-<base>, such as emberbrand-longsword. Without the option, a
character that carries a custom item builds without it, and
reconcileMissingContent reports the item.
The validators
validate has one validator for each type that the old builders saved:
race, subrace, class, subclass, background, feat, spell,
language, invocation, boon, selection, monster, encounter, and
magicItem. Each takes one record, as Transit-JSON text or its parsed value,
and checks it with the spec that the old save used. It reports every
problem, also when the old spec stopped at the first. It does not fill
placeholders for missing fields, so a missing name is reported, and a
spell needs a level and a school.
The result is { ok, problems, item }. Each problem is { path, reason,
pred }. path is the field's path, such as ["options", 0, "name"].
reason is "missing" (also for a blank string), "invalid", or
"duplicate"; a selection reports "duplicate" for two options whose
names have the same key.
item is the record to store. When it has no key, its key is set from
the name, then its text is normalized, as the old save did. An existing
key is kept, so a save does not undo renameKey. When the name is
missing, the missing key is not reported, because it comes from the name.
A magic item is returned as it is, because the old server stored it so. A
builder can show each problem next to its field and save item when ok
is true.
Versions
The package follows semver. Every engine patch or facade addition bumps the version. Pin an exact version, because a new version can change sheet values.
Build and test from source
The build needs Node and a JDK, because shadow-cljs runs on the JVM. JDK 21
works. The package compiles the engine in place from ../src/cljc and
../src/cljs, so build it inside a clone of the repository.
cd engine-js
npm ci
npm run build # writes dist/pubdoor.js and dist/content/*.json
npm test # tsc --noEmit, then the vitest golden tests against ../fixturestest/private-export.test.ts imports a real all-content.orcbrew and
compares the result with its committed summary, and
test/validate.test.ts checks that each of its items passes. They run
only when the
export is at fixtures/orcbrew/private/all-content3.orcbrew, which git
ignores. See fixtures/README.md, Private exports.
test/content-identity.test.ts is the contract C3 check. It fails when
key derivation changes: when a fixture character's option keys stop
resolving, when a fixture pack refers to a class, race, or selection that
does not exist, or when the SRD template's keys differ from the baseline.
Publish a version
Publishing is manual. You must be a member of the pubdoor npm org, and
you need a JDK on your path, because the build compiles the ClojureScript
on the JVM. CI uses Java 21.
Set
versioninpackage.json.Run
npm install --package-lock-only.Commit the change and merge it to
pubdoor.Check out
pubdoorand pull the merged commit.Run the publish wizard:
engine-js/scripts/publish.shThe wizard checks the checkout, the npm registry, and the tags. It logs you in to npm, then builds and tests the package. It publishes the package, and it tags the commit
pubdoor-v<version>and pushes the tag. It asks you to confirm before it publishes and before it pushes the tag. If your account uses two-factor authentication, npm asks for a one-time password.
License
EPL-2.0, the same license as the rest of the repository. dist/pubdoor.js
bundles third-party libraries, which THIRD-PARTY-NOTICES lists with their
licenses.
