v0.8.2 — every district opens on a Depot, and the docs are pages now
A second-digit bump for a playtest read back against the save file. Nine questions were asked of one three-Day game; three were bugs, three were the rules working and undocumented, three were decisions. Every save on the test server was replayed against this build BEFORE release, which is how the cost of each rule was known before it was chosen rather than discovered after. EVERY DISTRICT OPENS ON A DEPOT. A Whistle Post has one A/D track and is not a Passenger Facility, so the opening of every game was spent unable to work a passenger and one arrival away from a collision. Two A/D tracks and passengers from Stage 1 now; "Players start with Whistle Posts, not Depots" is the harder game, set when the game is created. The deck follows the choice — starting on Depots the four Depot upgrade cards are left out, because an upgrade must be to the next tier and a Depot card at a table of Depots is a dead draw. How much easier it is showed up as a test failure rather than an argument: the cue-coverage pool needed widening from 24 seeded games to 60 before it held one collision. NO SAVE WAS STRANDED BY IT, which took care. This is the one house rule that changes how a game is DEALT rather than how it plays, so replaying a save under the wrong opening is a different railroad from intent one — silently, with no error. `withSavedOpening` fills it on the replay paths ONLY. Putting it in the resolver instead made a fresh Cutthroat game deal Whistle Posts and read as Custom, which is how the distinction was found. THREE BUGS, ALL REPORTED FROM ONE GAME AND ALL CONFIRMED ON ITS SAVE. An Office held TWO TRAINS ON ONE A/D TRACK. The capacity test passed with nothing standing, the train the Interlocking had been holding at the Limits was moved into the free slot, and the arriving train was pushed in after it without anyone asking again whether there was room — so the collision §8.3 calls for never happened. The held train keeps priority; the newcomer now takes the consequence it would have met had the held train arrived first. THE HISTORY FROZE, permanently, and the log cap was not really the cause. Each seat's "what have I sent you" bookmark was an INDEX into an array the game trims, so once a seat's bookmark reached the limit the slice returned nothing for the rest of the game — at a different moment per seat, because each holds its own. That game's log ended at exactly the cap. Lines carry a sequence number now, which survives trimming; proven by pushing twice the cap through a simulated seat. §8.1 ASKED THE WRONG QUESTION TWICE. "Trains may pass" returned `clear` before the Subdivision was looked at, so a train entering a Double Track was released however busy the rest of it was — that, not anything about Control Points, is what let Train 8 out with no ruling. And a train standing at an Office was invisible to the scan, so one about to re-enter the very Subdivision being entered counted for nothing. Capacity is the test, not presence: a Depot with a track free is not in the way; a Whistle Post with its one track taken is. THINGS THAT HAPPENED SILENTLY NOW SAY SO — a train held against a facing one, a train released from the Limits (a side effect of somebody else's arrival, so it simply appeared at the Office), and the train an Interlocking is holding, whose explanatory tooltip has existed since #99 with NO renderer ever reading the flag. WHERE A MOVE IS REFUSED, AND WHY. `exploreMoves` decides where the rails go and the pick-up restrictions are enforced afterwards in `check`, so a square the rails reached and the card forbade was reachable, un-offered, and absent from the block list with nothing said. Those squares are blocked with the rule that blocks them now, and the reasons are got by ASKING `check` rather than re-deriving: a second implementation of the rules is exactly the failure the block list exists to avoid. A train may also always recover its own caboose — X13 prints "may drop but not pick up anything", and a train needs its caboose to be made up, so one that parted with it could never legally leave again. RULES DECIDED IN SEPTEMBER AND APPLIED HERE. A Modifier must sit square against its host, no diagonals. A passenger Modifier may not be played at a Whistle Post. Both were built, measured, held back for a fortnight so a playtest could finish, and applied now. A Second Section costs its card: `SECOND_SECTION` was declared in content.ts and never dealt, so the action was free and the bot ordered 26 accidental ones in a measured round. The card is dealt and spent — gating on a card the deck never holds would have deleted the mechanic rather than fixed it. THE DOCUMENTATION IS A SET OF PAGES, not five text files served as text/plain — a card reference is mostly tables, and as plain text a table is rows of pipes. Markdown is still the one copy; the build renders it, and publishes the .md beside each page. No Markdown library: this project has no runtime dependencies and one would be a poor first. The pages add what Markdown cannot carry without drifting — a nav across the set, a contents list built from the headings actually rendered, an anchor on every heading, a 70-character measure, and tables that are tables. They print as ink on paper. The references caught up with the rules, checked rather than assumed: two statements had gone from stale to misleading (the Quickstart told a new player to "get a Depot down as soon as one appears"), and four rules nobody could look up are written down — the Office tier table, §8.1 in practice, what the Circus Train pays for, and that a Realignment can be a card with no legal target. Adding one card to the deck reshuffles every seeded deal, which broke five fixtures. Each was a seed meaning "a game like this" — TODO #84, exactly — so seeds moved and pools widened rather than assertions weakening, and the clearance fixture pins its terrain the way `enhancements.test.ts` already does. The three published replays were re-recorded. Closes TODO #40, #42a, #108, #109 and #110. 1046 fast tests and 35 sim tests pass. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MUizFYCMHRWhbWwXhp7WPR
This commit is contained in:
co-authored by
Claude Opus 5
parent
517238a727
commit
3befc420da
@@ -1,31 +1,22 @@
|
||||
/**
|
||||
* Generate `docs/rules/as-built.md` — what the cards say, as the code actually has them.
|
||||
* Generate the card tables inside `docs/home-deck.md` and `docs/mainline-deck.md`.
|
||||
*
|
||||
* WHY THIS IS GENERATED RATHER THAN WRITTEN.
|
||||
* WHY GENERATED RATHER THAN WRITTEN. Nothing fails when a hand-written table falls behind a
|
||||
* constant, so the tables are emitted from the same exported catalogues the engine instantiates
|
||||
* from, and `test/card-reference.test.ts` re-runs this generator and asserts the checked-in docs
|
||||
* match. Change a card face and the suite goes red until the docs are regenerated.
|
||||
*
|
||||
* Every other file in `docs/rules/` is a historical record and says so: `rules-v0.1.md` is a
|
||||
* faithful transcription of the prototype PDFs, `open-questions.md` is the gap tracker,
|
||||
* `rules-v0.2.md` and `card-reference.md` both carry SUPERSEDED banners. None of them describes the
|
||||
* game as built, and none of them should be edited to — the record is worth more intact than
|
||||
* patched.
|
||||
* EACH TABLE LANDS UNDER THE SECTION IT BELONGS TO, between a marker pair the deck documents carry:
|
||||
*
|
||||
* So there was no current reference at all, and `content.ts` spent several releases pointing at
|
||||
* `card-reference.md` as "the place that now carries what the cards say" while that file's own
|
||||
* banner said "do not use its numbers". A reader following the code's advice landed on the v0.4.5
|
||||
* deck: twelve numbered trains, "3 / 4 Mail-Express, 3 coaches", against a `content.ts` whose train
|
||||
* 3 is the Express with two freight cars and a per-location freight rule.
|
||||
* <!-- BEGIN CARDS: track --> …generated… <!-- END CARDS: track -->
|
||||
*
|
||||
* A HAND-WRITTEN REPLACEMENT WOULD HAVE DRIFTED THE SAME WAY, and for the same reason: nothing
|
||||
* fails when a table falls behind a constant. So the reference is emitted from the same exported
|
||||
* catalogues the engine instantiates from, and `test/card-reference.test.ts` re-runs this generator
|
||||
* and asserts the checked-in file matches byte for byte. Change a card face and the suite goes red
|
||||
* until the doc is regenerated — which is the only mechanism this project has found that keeps a
|
||||
* document honest.
|
||||
* Everything around the markers is hand-written and is never touched. Only the Mainline card table
|
||||
* goes to `mainline-deck.md`; every other table belongs to the Home Office deck.
|
||||
*
|
||||
* `npm run build:cards` writes it. Nothing at runtime reads it; it is for people.
|
||||
* `npm run build:cards` writes them. Nothing at runtime reads them; they are for people.
|
||||
*/
|
||||
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
@@ -70,40 +61,17 @@ const trainRow = (t: TrainProfile): string =>
|
||||
`| ${t.isExtra ? 'X' : ''}${t.number} | ${t.name} | ${t.speed} | ` +
|
||||
`${t.direction === 'playerChoice' ? "player's choice" : t.direction} | ${consistOf(t.consist)} | ${rulesOf(t.rules)} |`;
|
||||
|
||||
const lines: string[] = [];
|
||||
const w = (s = ''): void => void lines.push(s);
|
||||
/** Generated blocks, keyed by the marker name the deck documents wrap them in. */
|
||||
const blocks = new Map<string, string[]>();
|
||||
let current: string[] = [];
|
||||
/** Start a new generated block. Everything `w` writes lands here until the next `section`. */
|
||||
const section = (key: string): void => {
|
||||
current = [];
|
||||
blocks.set(key, current);
|
||||
};
|
||||
const w = (s = ''): void => void current.push(s);
|
||||
|
||||
w('# Station Master — the cards as built');
|
||||
w();
|
||||
w('> **Generated from `src/engine/content.ts` by `scripts/build-card-reference.ts`. Do not edit by');
|
||||
w('> hand** — `npm run build:cards` rewrites it, and `test/card-reference.test.ts` fails if this file');
|
||||
w('> and the code disagree.');
|
||||
w();
|
||||
w('This is the one file in `docs/rules/` that describes the game **as it currently is**. Everything');
|
||||
w('else in this directory is a historical record and marked as such: [`rules-v0.1.md`](rules-v0.1.md)');
|
||||
w('transcribes the prototype PDFs, [`open-questions.md`](open-questions.md) tracks how the gaps in');
|
||||
w('them were decided, and [`rules-v0.2.md`](rules-v0.2.md) and');
|
||||
w('[`card-reference.md`](card-reference.md) both describe superseded card sets. Read those for the');
|
||||
w('reasoning; read this for the numbers.');
|
||||
w();
|
||||
w('The engine instantiates from the same constants this is emitted from, so a disagreement between');
|
||||
w('this page and the game is a bug in the generator, not a stale table.');
|
||||
w();
|
||||
w('**No card counts appear here, deliberately** (TODO #15a, Jesse 2026-08-22): the counts move with');
|
||||
w('play balance, so a document that prints them is answering a question that will have a different');
|
||||
w('answer next retune. Where a count matters it is a yes/no — whether the deck deals the card at');
|
||||
w('all — which is a fact about the design rather than about the current tuning.');
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Trains');
|
||||
w();
|
||||
w(`${TIMETABLED_TRAINS.length} timetabled and ${EXTRA_TRAINS.length} Extras, ${ALL_TRAINS.length} in all.`);
|
||||
w('Odd numbers run west, even run east; a pair shares a class and is the same card face in two');
|
||||
w('directions. A Crew Tray holds four pieces and a caboose counts toward the four, which is why no');
|
||||
w('train with a caboose carries more than three revenue cars.');
|
||||
w();
|
||||
section('trains');
|
||||
w('### Timetabled');
|
||||
w();
|
||||
w('| # | Class | Speed | Runs | Consist | Printed rules |');
|
||||
@@ -116,16 +84,7 @@ w('| # | Class | Speed | Runs | Consist | Printed rules |');
|
||||
w('| ---: | --- | --- | --- | --- | --- |');
|
||||
for (const t of EXTRA_TRAINS) w(trainRow(t));
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Mainline cards');
|
||||
w();
|
||||
w('A card is divided into **regions**, and a train advances one region per Stage — so the regions a');
|
||||
w('card prints are what it costs to cross. Where a train *enters* is what the rules move: a fast');
|
||||
w('train on Hilly, a Heavy Grade with Helpers, or a card whose back region is a siding rather than');
|
||||
w('part of the road all change the entry point rather than the card\'s length.');
|
||||
w();
|
||||
section('mainline');
|
||||
w('| Card | Regions | Default entry | Fast / slow entry | Trains may pass | Extra may start |');
|
||||
w('| --- | ---: | ---: | --- | :---: | :---: |');
|
||||
for (const m of MAINLINE_PROFILES) {
|
||||
@@ -138,11 +97,7 @@ w('the Division and are not dealt. What each card does, in the words the game us
|
||||
w();
|
||||
for (const m of MAINLINE_PROFILES) w(`- **${m.name}** — ${mainlineDescription(m.kind)}`);
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Office cards');
|
||||
w();
|
||||
section('office');
|
||||
w('Upgrades are strictly sequential — no skipping a tier — so a Terminal needs all three cards in');
|
||||
w('order. Green slots are outbound passengers, red are inbound, and the design gives slots **equal**');
|
||||
w('to Porters rather than one more.');
|
||||
@@ -157,11 +112,7 @@ w();
|
||||
w(`Whistle Posts are a fixed supply of ${WHISTLE_POST_SUPPLY} outside the deck, and Limits signs a`);
|
||||
w(`supply of ${LIMITS_SUPPLY}.`);
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Freight facilities');
|
||||
w();
|
||||
section('facilities');
|
||||
w('Each lists the car types it works, which way its traffic flows, and the industries it may not sit');
|
||||
w('beside. **Every lockout pair is a producer and the consumer of the same commodity** — you may');
|
||||
w('build one end of a chain or the other, never both, which is what forces traffic to run between');
|
||||
@@ -177,11 +128,7 @@ for (const f of INDUSTRY_PROFILES) {
|
||||
w(`| ${f.name} | ${f.carTypes.join(', ')} | ${f.flow} | ${f.baseOut} | ${f.baseIn} | ${f.baseLoaders} | ${lo} |`);
|
||||
}
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Modifier cards');
|
||||
w();
|
||||
section('modifiers');
|
||||
w('Each sits beside a host and raises one of its capacities. `office` as a host means any Passenger');
|
||||
w('Facility — so a modifier that adds a green slot to an Office adds nothing to a Whistle Post, which');
|
||||
w('is not one.');
|
||||
@@ -195,15 +142,7 @@ for (const m of MODIFIER_PROFILES) {
|
||||
w(`| ${m.name} | ${hosts} | ${m.addOut || '—'} | ${m.addIn || '—'} | ${m.addLoaders || '—'} | ${m.addPorters || '—'} |`);
|
||||
}
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Track cards');
|
||||
w();
|
||||
w('Track is **in the Home Office deck** and is drawn and played like any other card — not a separate');
|
||||
w('per-player supply. Operational Rail is the flag that says a train may stop on the card; a turnout');
|
||||
w('may be run through but not stopped on.');
|
||||
w();
|
||||
section('track');
|
||||
w('| Track | Geometry | Hand | Operational rail | Move cost | Dealt |');
|
||||
w('| --- | --- | --- | :---: | ---: | :---: |');
|
||||
for (const t of TRACK_CARDS) {
|
||||
@@ -212,11 +151,7 @@ for (const t of TRACK_CARDS) {
|
||||
w();
|
||||
w('A row marked "no" is a shape the engine understands but the deck does not currently print.');
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Enhancements');
|
||||
w();
|
||||
section('enhancements');
|
||||
w('The column that only the implementation can fill in: **whether the printed effect actually');
|
||||
w('resolves yet.** `live` is read during play; `dormantSolo` is implemented at the point of attack');
|
||||
w('but the attack is an opponent-directed card held out of every deck, so nothing reaches it in a');
|
||||
@@ -235,11 +170,7 @@ for (const r of ENHANCEMENT_RULES) {
|
||||
w(`| ${card?.name ?? r.key} | ${r.placement} | ${needs} | **${r.effect}** |`);
|
||||
}
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Opponent-directed cards, and what answers them');
|
||||
w();
|
||||
section('opponent');
|
||||
w('**None of these is dealt in any deck today.** A card that can only be played at another player');
|
||||
w('has no legal target in a solitaire game, and a defence with nothing to defend against is as dead');
|
||||
w('a draw as the attack — so both halves are held out until the attacks are implemented. They are');
|
||||
@@ -264,5 +195,33 @@ w('| --- | --- | --- | --- |');
|
||||
for (const c of MAINLINE_MODIFIER_CARDS) w(`| ${c.name} | ${c.placement} | ${c.effect} | ${c.answers ?? '—'} |`);
|
||||
w();
|
||||
|
||||
writeFileSync(join(root, 'docs/rules/as-built.md'), `${lines.join('\n')}\n`);
|
||||
console.log(`built -> docs/rules/as-built.md (${lines.length} lines)`);
|
||||
/**
|
||||
* Splice each block into its document, between the markers that name it.
|
||||
*
|
||||
* Strict on purpose: a block with nowhere to go, or a marker pair with no block, is a mistake that
|
||||
* would otherwise show up as a silently missing table. Both throw.
|
||||
*/
|
||||
const WHERE: Record<string, string> = {
|
||||
mainline: 'docs/mainline-deck.md',
|
||||
};
|
||||
const DEFAULT_DOC = 'docs/home-deck.md';
|
||||
|
||||
const edited = new Map<string, string>();
|
||||
for (const [key, body] of blocks) {
|
||||
const rel = WHERE[key] ?? DEFAULT_DOC;
|
||||
const text = edited.get(rel) ?? readFileSync(join(root, rel), 'utf8');
|
||||
const begin = `<!-- BEGIN CARDS: ${key} -->`;
|
||||
const finish = `<!-- END CARDS: ${key} -->`;
|
||||
const from = text.indexOf(begin);
|
||||
const to = text.indexOf(finish);
|
||||
if (from < 0 || to < 0) throw new Error(`${rel} has no markers for "${key}" — expected ${begin} … ${finish}`);
|
||||
if (to < from) throw new Error(`${rel}: markers for "${key}" are the wrong way round`);
|
||||
// Trailing blank lines are trimmed so the block sits the same way however the section ends.
|
||||
const inner = body.join('\n').replace(/\n+$/, '');
|
||||
edited.set(rel, `${text.slice(0, from + begin.length)}\n${inner}\n${text.slice(to)}`);
|
||||
}
|
||||
|
||||
for (const [rel, text] of edited) {
|
||||
writeFileSync(join(root, rel), text);
|
||||
console.log(`built -> ${rel}`);
|
||||
}
|
||||
|
||||
+47
-31
@@ -14,6 +14,9 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync,
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { DOC_PAGES, docPage } from './docs-page.ts';
|
||||
import { renderMarkdown } from './markdown.ts';
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
/**
|
||||
* Overridable so a test can point the build at an isolated directory instead of the shared
|
||||
@@ -189,41 +192,46 @@ if (existsSync(imageSrc)) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The player-facing documentation, published beside the game so a tester can reach it from the box.
|
||||
* The player-facing documentation, RENDERED and published beside the game.
|
||||
*
|
||||
* COPIED, NOT RE-WRITTEN. The Markdown in `docs/` is the one copy; a hand-written HTML twin would
|
||||
* drift from it on the first edit, which is the whole lesson of TODO #15a and of the 2026-09-20
|
||||
* documentation pass that found four references a month out of date.
|
||||
* MARKDOWN IS STILL THE ONE COPY. `docs/*.md` is what is written and reviewed; this turns it into
|
||||
* a page at build time. A hand-written HTML twin would drift from it on the first edit, which is
|
||||
* the whole lesson of TODO #15a and of the documentation pass that found four references a month
|
||||
* out of date.
|
||||
*
|
||||
* THE WHOLE SET, NOT ONLY THE QUICKSTART. v0.8.0.16 published the guide alone, and the guide's own
|
||||
* §8 "Where to read more" links five further documents by relative path — so every one of them
|
||||
* 404'd on the package (verified on the box: 5 of 6 paths missing). Publishing the guide without
|
||||
* what it points at is the same broken-link failure the test below was written to catch, one hop
|
||||
* further out. The names are kept exactly as the guide writes them, because those links are what
|
||||
* has to resolve.
|
||||
* WHY RENDER AT ALL. They were served as `text/plain`, which is honest and unreadable: a card
|
||||
* reference is mostly tables, and as plain text a table is rows of pipes. That was TODO #109, taken
|
||||
* deliberately as the short version to get the references in front of testers for one round.
|
||||
*
|
||||
* SERVED AS PLAIN TEXT for now, which is honest rather than good: tables render as pipes and the
|
||||
* links do not click. Rendering them into styled pages needs a small Markdown converter and is
|
||||
* filed as TODO #109 — this is the version that gets the references in front of testers for this
|
||||
* round rather than leaving them without any.
|
||||
* NO MARKDOWN LIBRARY. `scripts/markdown.ts` covers the subset these five documents use, and this
|
||||
* project has no runtime dependencies at all — one would be a poor first.
|
||||
*
|
||||
* PUBLISHED UNDER THEIR OWN NAMES, which since v0.8.0.17 carry no version: the documents are kept
|
||||
* current with every release rather than published as editions, so `docs/rules.md` is served as
|
||||
* `rules.md` and the splash page and the This Game card link it by that name. Four of them were
|
||||
* `StationMaster-<name>-v0.4.5.md` until then — the prototype edition they were first written
|
||||
* against, never the version they described.
|
||||
* THE `.md` IS PUBLISHED TOO, beside the page. It costs nothing, it is what a reader who wants the
|
||||
* source or a diff actually wants, and it keeps every link that was handed out while the documents
|
||||
* were served as text working rather than 404ing.
|
||||
*/
|
||||
const GUIDE_DOCS: readonly string[] = [
|
||||
'quickstart.md',
|
||||
'rules.md',
|
||||
'home-deck.md',
|
||||
'mainline-deck.md',
|
||||
'components.md',
|
||||
// Generated by `build:cards` and checked in; a test fails when it disagrees with the code, which
|
||||
// is why it is the one reference that has never drifted. Its `rules/` directory is preserved
|
||||
// because that is the path the Quickstart links it by.
|
||||
'rules/as-built.md',
|
||||
];
|
||||
const GUIDE_DOCS: readonly string[] = DOC_PAGES.map((d) => `${d.slug}.md`);
|
||||
|
||||
/** `rules.md` → `rules.html`, so a link between documents lands on the rendered page. */
|
||||
const docLink = (href: string): string =>
|
||||
/^https?:/.test(href) || href.startsWith('#') ? href : href.replace(/\.md(#|$)/, '.html$1');
|
||||
|
||||
/**
|
||||
* The title and version line, lifted out of the Markdown body.
|
||||
*
|
||||
* The documents open with `# Title` then `**Version x.y.z** · date`, and the page draws both in its
|
||||
* own header — so rendering them again in the body would print each twice. Taken by pattern rather
|
||||
* than by line count, and the body is only trimmed where the pattern actually matched.
|
||||
*/
|
||||
function splitHead(src: string): { title: string; version: string; body: string } {
|
||||
const m = /^#\s+(.+?)\n+\*\*Version\s+([^*]+)\*\*\s*·\s*([^\n]+)\n/.exec(src);
|
||||
if (!m) return { title: 'Station Master', version: '', body: src };
|
||||
return {
|
||||
title: m[1]!.replace(/^Station Master\s*[—-]\s*/, '').trim(),
|
||||
version: `<b>Version ${m[2]!.trim()}</b> · ${m[3]!.trim()}`,
|
||||
body: src.slice(m[0].length),
|
||||
};
|
||||
}
|
||||
|
||||
for (const rel of GUIDE_DOCS) {
|
||||
const src = join(root, 'docs', rel);
|
||||
@@ -233,9 +241,17 @@ for (const rel of GUIDE_DOCS) {
|
||||
console.error(`WARNING: docs/${rel} is missing — a published link will 404`);
|
||||
continue;
|
||||
}
|
||||
const md = readFileSync(src, 'utf8');
|
||||
const out = join(dist, rel);
|
||||
mkdirSync(dirname(out), { recursive: true });
|
||||
copyFileSync(src, out);
|
||||
writeFileSync(out, md);
|
||||
|
||||
const { title, version, body } = splitHead(md);
|
||||
const { html, headings } = renderMarkdown(body, docLink);
|
||||
writeFileSync(
|
||||
join(dist, rel.replace(/\.md$/, '.html')),
|
||||
docPage({ slug: rel.replace(/\.md$/, ''), title, version, body: html, headings }),
|
||||
);
|
||||
}
|
||||
|
||||
// A tiny note for whoever unzips this later and wonders what it needs.
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* The page a documentation file is rendered into.
|
||||
*
|
||||
* ONE TEMPLATE FOR ALL FIVE, so the guide reads as one publication rather than five files that
|
||||
* happen to be linked. It carries the same dark palette, the same type and the same blue as the
|
||||
* game, because a player arrives here from the board and should not feel they have left the site.
|
||||
*
|
||||
* WHAT THE PAGE ADDS OVER THE MARKDOWN, and why each is here rather than in the source:
|
||||
*
|
||||
* - a **nav** across the five documents, so the set is navigable from any one of them. The
|
||||
* Markdown cannot carry this: it would have to be repeated in every file and would drift.
|
||||
* - a **contents list** built from the headings actually rendered, so it cannot fall out of step
|
||||
* with the document the way a hand-written one does.
|
||||
* - **anchors** on every heading, so a section can be linked to in a bug report.
|
||||
* - a **measure** of about 70 characters. Long lines are the single biggest thing making plain
|
||||
* text hard to read, and these documents are long.
|
||||
*
|
||||
* PRINTS SANELY TOO: the nav and contents drop out, the palette goes to ink on paper, and tables
|
||||
* keep their rules. A rules reference is a thing people print.
|
||||
*/
|
||||
|
||||
import type { Heading } from './markdown.ts';
|
||||
|
||||
export type DocPage = {
|
||||
/** Published filename, without the extension — also the nav's identity for "you are here". */
|
||||
slug: string;
|
||||
/** What the nav calls it. */
|
||||
nav: string;
|
||||
};
|
||||
|
||||
export const DOC_PAGES: readonly DocPage[] = [
|
||||
{ slug: 'quickstart', nav: 'Quickstart' },
|
||||
{ slug: 'rules', nav: 'Rules' },
|
||||
{ slug: 'home-deck', nav: 'Home deck' },
|
||||
{ slug: 'mainline-deck', nav: 'Mainline deck' },
|
||||
{ slug: 'components', nav: 'Components' },
|
||||
];
|
||||
|
||||
export const DOCS_CSS = `
|
||||
:root{
|
||||
--bg:#12161c; --panel:#161b22; --line:#2c333d; --fg:#cfd6e0; --dim:#8b94a3;
|
||||
--head:#cfe0f5; --link:#5aa9e6; --accent:#9fb6d8; --rule:#39424e;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
html{scroll-behavior:smooth}
|
||||
body{
|
||||
margin:0;background:var(--bg);color:var(--fg);
|
||||
font:15px/1.65 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
|
||||
-webkit-text-size-adjust:100%;
|
||||
}
|
||||
a{color:var(--link)}
|
||||
a:hover{color:#9fd0f5}
|
||||
|
||||
/* THE NAV. Sticky, because these documents are long and the set has to stay reachable from the
|
||||
middle of one. Horizontally scrollable on a phone rather than wrapping into three rows. */
|
||||
.docnav{
|
||||
position:sticky;top:0;z-index:5;background:var(--panel);border-bottom:1px solid var(--line);
|
||||
display:flex;align-items:center;gap:4px;padding:8px 16px;overflow-x:auto;
|
||||
}
|
||||
.docnav .home{color:var(--head);font-weight:700;margin-right:10px;text-decoration:none;white-space:nowrap}
|
||||
.docnav a.tab{
|
||||
color:var(--dim);text-decoration:none;padding:4px 10px;border-radius:6px;white-space:nowrap;
|
||||
border:1px solid transparent;font-size:13px;
|
||||
}
|
||||
.docnav a.tab:hover{color:var(--fg);background:#1f2733}
|
||||
.docnav a.tab[aria-current="page"]{color:#f2e6cf;background:#2b3444;border-color:#c8912f}
|
||||
|
||||
.wrap{max-width:78ch;margin:0 auto;padding:22px 16px 72px}
|
||||
|
||||
/* THE HEADER — what this document is and which build it describes, lifted out of the prose so the
|
||||
version is the first thing on the page, as the process rules require. */
|
||||
.dochead{border-bottom:1px solid var(--rule);padding-bottom:12px;margin-bottom:8px}
|
||||
.dochead h1{margin:0 0 6px;font-size:26px;line-height:1.25;color:var(--head);letter-spacing:.01em}
|
||||
.dochead .ver{color:var(--dim);font-size:13px}
|
||||
.dochead .ver b{color:#c8912f;font-weight:700}
|
||||
|
||||
/* CONTENTS, built from the headings actually rendered. Collapsed by default on a phone. */
|
||||
.toc{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:10px 14px;margin:18px 0 26px}
|
||||
.toc summary{cursor:pointer;color:var(--accent);font-size:13px;font-weight:600;letter-spacing:.04em;text-transform:uppercase}
|
||||
.toc ol{list-style:none;margin:10px 0 2px;padding:0;columns:2;column-gap:26px}
|
||||
.toc li{margin:0 0 4px;break-inside:avoid}
|
||||
.toc li.l3{padding-left:14px;font-size:13px}
|
||||
.toc a{text-decoration:none;color:var(--fg)}
|
||||
.toc a:hover{color:var(--link)}
|
||||
@media (max-width:640px){.toc ol{columns:1}}
|
||||
|
||||
h2,h3,h4{color:var(--head);line-height:1.3;margin:28px 0 8px}
|
||||
h2{font-size:20px;border-bottom:1px solid var(--rule);padding-bottom:5px}
|
||||
h3{font-size:16px}
|
||||
h4{font-size:14px;color:var(--accent);text-transform:uppercase;letter-spacing:.05em}
|
||||
p{margin:0 0 12px}
|
||||
strong{color:#e8eef7}
|
||||
hr{border:none;border-top:1px solid var(--rule);margin:26px 0}
|
||||
|
||||
/* The anchor beside a heading: invisible until the heading is hovered, so it never competes with
|
||||
the words but is always there to copy. */
|
||||
.anchor{margin-left:.45em;color:var(--rule);text-decoration:none;font-weight:400;opacity:0}
|
||||
h1:hover .anchor,h2:hover .anchor,h3:hover .anchor,h4:hover .anchor{opacity:1}
|
||||
.anchor:hover{color:var(--link)}
|
||||
|
||||
ul,ol{margin:0 0 12px;padding-left:22px}
|
||||
li{margin:0 0 5px}
|
||||
li>ul,li>ol{margin-top:5px}
|
||||
|
||||
code{background:#1d232c;border:1px solid var(--line);border-radius:4px;padding:1px 5px;
|
||||
font:13px ui-monospace,SFMono-Regular,Menlo,monospace;color:#e0c89a}
|
||||
pre{background:#1d232c;border:1px solid var(--line);border-radius:7px;padding:12px 14px;overflow-x:auto}
|
||||
pre code{background:none;border:none;padding:0;color:var(--fg)}
|
||||
|
||||
blockquote{
|
||||
margin:16px 0;padding:10px 14px;background:#181f28;
|
||||
border-left:3px solid #c8912f;border-radius:0 7px 7px 0;
|
||||
}
|
||||
blockquote > :last-child{margin-bottom:0}
|
||||
|
||||
/* TABLES THAT LOOK LIKE TABLES. This is the whole reason the documentation is rendered rather than
|
||||
served as text: a card reference is mostly tables, and as plain text they are rows of pipes. */
|
||||
.tablewrap{overflow-x:auto;margin:0 0 16px;border:1px solid var(--line);border-radius:8px}
|
||||
table{border-collapse:collapse;width:100%;font-size:14px}
|
||||
thead th{
|
||||
background:#1f2733;color:var(--accent);text-align:left;font-weight:600;
|
||||
padding:8px 12px;border-bottom:1px solid var(--line);white-space:nowrap;
|
||||
}
|
||||
td{padding:7px 12px;border-bottom:1px solid #222a34;vertical-align:top}
|
||||
tbody tr:last-child td{border-bottom:none}
|
||||
tbody tr:nth-child(even){background:#151a21}
|
||||
tbody tr:hover{background:#1b222b}
|
||||
.ta-right{text-align:right;font-variant-numeric:tabular-nums}
|
||||
.ta-center{text-align:center}
|
||||
th.ta-right,th.ta-center{text-align:inherit}
|
||||
|
||||
footer{margin-top:40px;padding-top:14px;border-top:1px solid var(--rule);color:var(--dim);font-size:12px}
|
||||
footer a{color:var(--accent)}
|
||||
|
||||
@media print{
|
||||
.docnav,.toc,.anchor{display:none}
|
||||
body{background:#fff;color:#111;font-size:11pt}
|
||||
h1,h2,h3,h4,strong{color:#000}
|
||||
a{color:#000;text-decoration:underline}
|
||||
.wrap{max-width:none;padding:0}
|
||||
.tablewrap{border-color:#999}
|
||||
thead th{background:#eee;color:#000;border-bottom-color:#999}
|
||||
td{border-bottom-color:#ccc}
|
||||
tbody tr:nth-child(even){background:#f6f6f6}
|
||||
blockquote{background:#f4f4f4;border-left-color:#888}
|
||||
code,pre{background:#f4f4f4;border-color:#ccc;color:#111}
|
||||
}
|
||||
`;
|
||||
|
||||
/** The contents list, from the headings the renderer actually produced. */
|
||||
function toc(headings: readonly Heading[]): string {
|
||||
// h2 and h3 only: h1 is the page title, and h4 is a label inside a section rather than a place.
|
||||
const items = headings.filter((h) => h.level === 2 || h.level === 3);
|
||||
if (items.length < 3) return '';
|
||||
const lis = items
|
||||
.map((h) => `<li class="l${h.level}"><a href="#${h.id}">${h.text.replace(/&/g, '&').replace(/</g, '<')}</a></li>`)
|
||||
.join('');
|
||||
return `<details class="toc" open><summary>On this page</summary><ol>${lis}</ol></details>`;
|
||||
}
|
||||
|
||||
export function docPage(opts: {
|
||||
slug: string;
|
||||
title: string;
|
||||
version: string;
|
||||
body: string;
|
||||
headings: readonly Heading[];
|
||||
}): string {
|
||||
const tabs = DOC_PAGES.map(
|
||||
(d) =>
|
||||
`<a class="tab" href="./${d.slug}.html"${d.slug === opts.slug ? ' aria-current="page"' : ''}>${d.nav}</a>`,
|
||||
).join('');
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>${opts.title} — Station Master</title>
|
||||
<style>${DOCS_CSS}</style>
|
||||
</head>
|
||||
<body>
|
||||
<nav class="docnav"><a class="home" href="./index.html">Station Master</a>${tabs}</nav>
|
||||
<div class="wrap">
|
||||
<header class="dochead">
|
||||
<h1>${opts.title}</h1>
|
||||
<div class="ver">${opts.version}</div>
|
||||
</header>
|
||||
${toc(opts.headings)}
|
||||
${opts.body}
|
||||
<footer>
|
||||
Station Master — <a href="./index.html">back to the game</a> ·
|
||||
these references are kept current with every release.
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
/**
|
||||
* A small Markdown renderer, for the player-facing documentation only.
|
||||
*
|
||||
* WHY NOT A LIBRARY. This project has no runtime dependencies at all, and the guide uses a small,
|
||||
* known subset of Markdown — headings, paragraphs, lists, tables, links, code spans, block quotes
|
||||
* and rules. A Markdown library would be the first dependency in the tree, pulled in to render five
|
||||
* files whose whole vocabulary fits below. `docs/` is written by hand, not by users, so this does
|
||||
* not have to survive hostile input; it has to render what those five documents actually contain
|
||||
* and fail loudly on anything else.
|
||||
*
|
||||
* WHY NOT HAND-WRITTEN HTML. The Markdown is the one copy (TODO #15a). An HTML twin drifts from it
|
||||
* on the first edit, which is the failure the whole documentation pass was about.
|
||||
*
|
||||
* ESCAPING IS UNCONDITIONAL. Every scrap of text goes through `esc` before any markup is added, and
|
||||
* the inline pass only ever inserts tags around already-escaped content. A `<` in the prose is a
|
||||
* less-than sign, not the start of an element — there is no raw-HTML passthrough, deliberately.
|
||||
*/
|
||||
|
||||
/** HTML-escape. Ampersand first, or it double-escapes the entities added after it. */
|
||||
export function esc(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
/** A heading found while rendering, for the contents list the page builds from it. */
|
||||
export type Heading = { level: number; text: string; id: string };
|
||||
|
||||
/**
|
||||
* `## 3. The shape of a Stage` → `the-shape-of-a-stage`.
|
||||
*
|
||||
* The leading number is dropped: it is a position in the document, and a link that carries it
|
||||
* breaks when a section is inserted above. Duplicate slugs get a numeric suffix rather than
|
||||
* silently pointing at the first one.
|
||||
*/
|
||||
function slug(text: string, taken: Set<string>): string {
|
||||
const base =
|
||||
text
|
||||
.toLowerCase()
|
||||
// A whole section number, dotted or not: "4.2 Local Operations" and "7. FAQ" both lose it.
|
||||
.replace(/^\d+(?:\.\d+)*[.)]?\s+/, '')
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '') || 'section';
|
||||
let id = base;
|
||||
for (let n = 2; taken.has(id); n++) id = `${base}-${n}`;
|
||||
taken.add(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline markup, applied to text that is ALREADY escaped.
|
||||
*
|
||||
* Order matters: code spans are taken out first and put back last, so `**` inside backticks stays
|
||||
* literal. That is not a corner case here — the rules reference quotes field names like
|
||||
* `**Version**` when describing the page header.
|
||||
*/
|
||||
function inline(escaped: string, linkHref: (href: string) => string): string {
|
||||
const code: string[] = [];
|
||||
let s = escaped.replace(/`([^`]+)`/g, (_m, body: string) => {
|
||||
code.push(`<code>${body}</code>`);
|
||||
return `\u0000${code.length - 1}\u0000`;
|
||||
});
|
||||
|
||||
// Links: [text](target). The target is rewritten so a link between documents lands on the
|
||||
// rendered page rather than the Markdown source.
|
||||
s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_m, text: string, href: string) => {
|
||||
const target = linkHref(href);
|
||||
const external = /^https?:/.test(target);
|
||||
return `<a href="${target}"${external ? ' target="_blank" rel="noopener"' : ''}>${text}</a>`;
|
||||
});
|
||||
|
||||
// Bold before italic, or `**x**` is read as an empty italic wrapping a bold.
|
||||
s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
|
||||
s = s.replace(/(^|[\s(])\*([^*\n]+)\*/g, '$1<em>$2</em>');
|
||||
|
||||
return s.replace(/\u0000(\d+)\u0000/g, (_m, i: string) => code[Number(i)]!);
|
||||
}
|
||||
|
||||
/** One table row's cells, from `| a | b |`. */
|
||||
function cells(line: string): string[] {
|
||||
return line
|
||||
.replace(/^\s*\|/, '')
|
||||
.replace(/\|\s*$/, '')
|
||||
.split('|')
|
||||
.map((c) => c.trim());
|
||||
}
|
||||
|
||||
/** `---`, `:--`, `--:` and `:-:` → the CSS alignment a column wants. */
|
||||
function alignments(sep: string): (string | null)[] {
|
||||
return cells(sep).map((c) => {
|
||||
const left = c.startsWith(':');
|
||||
const right = c.endsWith(':');
|
||||
if (left && right) return 'center';
|
||||
if (right) return 'right';
|
||||
if (left) return 'left';
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
const isTableSep = (line: string): boolean => /^\s*\|?[\s:|-]+\|[\s:|-]*$/.test(line) && line.includes('-');
|
||||
|
||||
export type Rendered = { html: string; headings: Heading[] };
|
||||
|
||||
/**
|
||||
* Render a Markdown document to HTML.
|
||||
*
|
||||
* `linkHref` rewrites link targets — the build uses it to send `rules.md` to `rules.html` — and
|
||||
* defaults to leaving them alone so the function is testable on its own.
|
||||
*/
|
||||
export function renderMarkdown(src: string, linkHref: (href: string) => string = (h) => h): Rendered {
|
||||
const lines = src.replace(/\r\n/g, '\n').split('\n');
|
||||
const out: string[] = [];
|
||||
const headings: Heading[] = [];
|
||||
const taken = new Set<string>();
|
||||
const ln = (s: string): void => void out.push(s);
|
||||
const text = (s: string): string => inline(esc(s), linkHref);
|
||||
|
||||
let i = 0;
|
||||
while (i < lines.length) {
|
||||
const line = lines[i]!;
|
||||
|
||||
// The generated-card markers, and any other HTML comment: structural, never shown.
|
||||
if (/^\s*<!--/.test(line)) {
|
||||
while (i < lines.length && !lines[i]!.includes('-->')) i++;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.trim() === '') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) {
|
||||
ln('<hr>');
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
|
||||
if (heading) {
|
||||
const level = heading[1]!.length;
|
||||
const raw = heading[2]!.trim();
|
||||
const id = slug(raw, taken);
|
||||
headings.push({ level, text: raw.replace(/[*`]/g, ''), id });
|
||||
// The anchor is a link to itself, so a section can be pointed at without a separate widget.
|
||||
ln(
|
||||
`<h${level} id="${id}">${text(raw)}` +
|
||||
`<a class="anchor" href="#${id}" aria-label="Link to this section">#</a></h${level}>`,
|
||||
);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Fenced code.
|
||||
if (/^\s*```/.test(line)) {
|
||||
i++;
|
||||
const body: string[] = [];
|
||||
while (i < lines.length && !/^\s*```/.test(lines[i]!)) body.push(lines[i++]!);
|
||||
i++;
|
||||
ln(`<pre><code>${esc(body.join('\n'))}</code></pre>`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Tables: a header row, an alignment row, then body rows.
|
||||
if (line.includes('|') && i + 1 < lines.length && isTableSep(lines[i + 1]!)) {
|
||||
const head = cells(line);
|
||||
const align = alignments(lines[i + 1]!);
|
||||
i += 2;
|
||||
const body: string[][] = [];
|
||||
while (i < lines.length && lines[i]!.includes('|') && lines[i]!.trim() !== '') body.push(cells(lines[i++]!));
|
||||
const th = head
|
||||
.map((c, n) => `<th${align[n] ? ` class="ta-${align[n]}"` : ''}>${text(c)}</th>`)
|
||||
.join('');
|
||||
const rows = body
|
||||
.map(
|
||||
(r) =>
|
||||
'<tr>' +
|
||||
r.map((c, n) => `<td${align[n] ? ` class="ta-${align[n]}"` : ''}>${text(c)}</td>`).join('') +
|
||||
'</tr>',
|
||||
)
|
||||
.join('');
|
||||
// Wrapped so a wide table scrolls inside the page rather than widening it on a phone.
|
||||
ln(`<div class="tablewrap"><table><thead><tr>${th}</tr></thead><tbody>${rows}</tbody></table></div>`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Block quote: consecutive `>` lines, rendered through this same function so a quote may hold
|
||||
// a list or a table — the rules reference puts both inside one.
|
||||
if (/^\s*>/.test(line)) {
|
||||
const body: string[] = [];
|
||||
while (i < lines.length && /^\s*>/.test(lines[i]!)) body.push(lines[i++]!.replace(/^\s*>\s?/, ''));
|
||||
ln(`<blockquote>${renderMarkdown(body.join('\n'), linkHref).html}</blockquote>`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Lists. A bullet or a number opens one; continuation lines are indented under their item.
|
||||
const bullet = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(line);
|
||||
if (bullet) {
|
||||
const ordered = /\d/.test(bullet[2]!);
|
||||
const baseIndent = bullet[1]!.length;
|
||||
const items: string[] = [];
|
||||
let current: string[] | null = null;
|
||||
while (i < lines.length) {
|
||||
const l = lines[i]!;
|
||||
if (l.trim() === '') {
|
||||
// A blank line ends the list unless the next line is still inside it.
|
||||
const next = lines[i + 1] ?? '';
|
||||
const continues = /^(\s*)([-*+]|\d+[.)])\s+/.test(next) || /^\s{2,}\S/.test(next);
|
||||
if (!continues) break;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
const m = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(l);
|
||||
if (m && m[1]!.length <= baseIndent) {
|
||||
if (current) items.push(current.join(' '));
|
||||
current = [m[3]!];
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (m || /^\s{2,}\S/.test(l)) {
|
||||
// A nested item or a wrapped continuation. Nesting is rendered by recursion on the block.
|
||||
if (!current) break;
|
||||
current.push(l.trim());
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (current) items.push(current.join(' '));
|
||||
const tag = ordered ? 'ol' : 'ul';
|
||||
ln(`<${tag}>${items.map((it) => `<li>${text(it)}</li>`).join('')}</${tag}>`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Anything else is a paragraph, running to the next blank line or block opener.
|
||||
const para: string[] = [];
|
||||
while (i < lines.length) {
|
||||
const l = lines[i]!;
|
||||
if (
|
||||
l.trim() === '' ||
|
||||
/^(#{1,6})\s/.test(l) ||
|
||||
/^\s*>/.test(l) ||
|
||||
/^\s*```/.test(l) ||
|
||||
/^\s*<!--/.test(l) ||
|
||||
/^\s*(---|\*\*\*|___)\s*$/.test(l) ||
|
||||
/^(\s*)([-*+]|\d+[.)])\s+/.test(l) ||
|
||||
(l.includes('|') && isTableSep(lines[i + 1] ?? ''))
|
||||
) {
|
||||
break;
|
||||
}
|
||||
para.push(l.trim());
|
||||
i++;
|
||||
}
|
||||
if (para.length) ln(`<p>${text(para.join(' '))}</p>`);
|
||||
}
|
||||
|
||||
return { html: out.join('\n'), headings };
|
||||
}
|
||||
Reference in New Issue
Block a user