Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: export universes as Markdown world bibles (#5031)

[._.]/ Adam Eivy574b22287a5b
diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsx
index 0728440e6c..3a72685272 100644
--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx
+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx
@@ -8,7 +8,7 @@
* panel modules.
*/
-import { useCallback, useEffect, useMemo } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link, useLocation, useParams } from 'react-router';
import {
ArrowLeft, BookOpen, FolderTree, ImagePlus, Layers, Loader2,
@@ -16,7 +16,7 @@ import {
} from 'lucide-react';
import InlineConfirmRow from '../ui/InlineConfirmRow';
import toast from '../ui/Toast';
-import { WORLD_CATEGORY_KEY_MAX } from '../../services/api';
+import { exportUniverseMarkdown, WORLD_CATEGORY_KEY_MAX } from '../../services/api';
import useUniverseBucketActions from '../../hooks/useUniverseBucketActions';
import useUniverseDraft from '../../hooks/useUniverseDraft';
import useUniverseExpand from '../../hooks/useUniverseExpand';
@@ -35,6 +35,7 @@ import RenderTab from './RenderTab';
import UniverseBibleTab from './UniverseBibleTab';
import { OtherTab, TrunkView } from './UniverseTrunkPanels';
import { appendImageRefById } from '../../lib/bibleLimits';
+import { downloadBlob } from '../../lib/downloadBlob';
import { totalVariationCount } from '../../lib/universeBuilderCounts';
import {
TAB_BIBLE,
@@ -51,6 +52,13 @@ import {
export { CategoryEditor } from './UniverseCategoryEditor';
export { OtherTab, TrunkView };
+const downloadSlug = (name) => String(name || 'universe')
+ .normalize('NFKD')
+ .replace(/[\u0300-\u036f]/g, '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '') || 'universe';
+
// Universe autocomplete combobox: search existing universes or create one when
// the trimmed query doesn't exactly match any. `onCreate` is wired to a
@@ -103,6 +111,7 @@ export default function UniverseBuilder() {
// treat the `new` sentinel as "no id" (blank draft). Real universe ids are
// UUIDs, so this can never shadow an actual record.
const selectedId = params.universeId && params.universeId !== 'new' ? params.universeId : null;
+ const [exporting, setExporting] = useState(false);
// `goToWorld` preserves `location.search` (e.g. `?tab=&bucket=&series=`) so
// the auto-save → create path doesn't snap the user back to the Bible tab
// after they triggered Generate From Idea from inside Cast/Places/Objects.
@@ -213,6 +222,20 @@ export default function UniverseBuilder() {
flushDraftIfDirty,
});
+ const handleExportMarkdown = useCallback(async () => {
+ if (!selectedId || exporting) return;
+ setExporting(true);
+ const markdown = await exportUniverseMarkdown(selectedId, { silent: true }).catch((error) => {
+ toast.error(error?.message || 'Failed to export universe');
+ return null;
+ });
+ setExporting(false);
+ if (markdown === null) return;
+ const filename = `${downloadSlug(draft.name)}.md`;
+ downloadBlob(markdown, filename, 'text/markdown');
+ toast.success(`Downloaded ${filename}`);
+ }, [draft.name, exporting, selectedId]);
+
// Page-level lightbox + gallery-metadata concern. A single MediaPreview at
// this level covers EVERY thumb on the page: variations, composite sheets,
// canon imageRefs, style probes, and character reference sheets — so clicking
@@ -348,6 +371,15 @@ export default function UniverseBuilder() {
</button>
{selectedId && (
<>
+ <button
+ onClick={handleExportMarkdown}
+ disabled={exporting}
+ className="px-3 py-2 rounded flex items-center gap-2 min-h-[40px] border border-port-border hover:bg-port-card-hover disabled:opacity-50"
+ title="Export universe as Markdown"
+ >
+ {exporting ? <Loader2 size={16} className="animate-spin" /> : <BookOpen size={16} />}
+ {exporting ? 'Exporting…' : 'Export .md'}
+ </button>
<ShareToButton kind="universe" ids={[selectedId]} label="Share" />
<SyncToPeerButton recordKind="universe" recordId={selectedId} label="Sync" />
{draft.origin ? <OriginBadge origin={draft.origin} /> : null}
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index 54daa3b3a1..8ecd73b81f 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -19,6 +19,10 @@ export const WORLD_STYLE_REFERENCES_MAX = 20;
// so request() doesn't also toast — see AGENTS.md "Custom catch ⇒ silent: true".
export const listUniverses = (options = {}) => request('/universe-builder', options);
export const getUniverse = (id, options = {}) => request(`/universe-builder/${encodeURIComponent(id)}`, options);
+export const exportUniverseMarkdown = (id, options = {}) => request(
+ `/universe-builder/${encodeURIComponent(id)}/export/markdown`,
+ { responseType: 'text', ...options },
+);
// `[{ id, name, influences: { embrace[], avoid[] } }]` for every live universe
// that has style tokens. Use this instead of `listUniverses()` whenever a
diff --git a/server/lib/README.md b/server/lib/README.md
index 1d663d5ed7..5cb8e29efd 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -107,6 +107,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `creativeDirectorPresets.js` | Locked-at-creation aspect ratio + quality presets for the Creative Director. |
| `creativeLatitude.js` | The IP-latitude clause every creative LLM request carries (`withCreativeLatitude`, `CREATIVE_LATITUDE_TOKENS`), plus the one creative-vs-operational table both stamp keys are matched against (`isCreativeStage` for stage names, `isCreativeRunSource` for run `source` tags). |
| `universeBibleCompleteness.js` | Is a universe bible entry actually described? The shared per-kind expand-field vocabulary (`BIBLE_EXPAND_FIELDS`, `BIBLE_CORE_FIELDS`) and the `core`/`full` completeness predicates the quota-burn describe job scans with. Pure. |
+| `universeMarkdown.js` | Pure deterministic Universe Builder world-bible export: `universeToMarkdown(record)` plus safe Markdown download filename helpers. |
| `universePromptRenderers.js` | Renderers that turn a universe's `categories` map + canon into prompt context. |
| `writersRoomPresets.js` | Writers Room enums (WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS). |
| `writersRoomStylePresets.js` | Curated style presets for storyboards + universe. |
diff --git a/server/lib/index.js b/server/lib/index.js
index ffbbc9b6cb..d33c95b0a4 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -96,6 +96,7 @@ export * from './streamLines.js';
// back-compat — namespace it so the canonical scenePrompt export wins flat.
export * as storyBible from './storyBible.js';
export * from './universeBibleCompleteness.js';
+export * from './universeMarkdown.js';
export * from './universePromptRenderers.js';
export * from './writersRoomPresets.js';
export * from './writersRoomStylePresets.js';
diff --git a/server/lib/universeMarkdown.js b/server/lib/universeMarkdown.js
new file mode 100644
index 0000000000..ce1942b5c9
--- /dev/null
+++ b/server/lib/universeMarkdown.js
@@ -0,0 +1,234 @@
+/**
+ * Deterministic Markdown serializer for a Universe Builder world bible.
+ *
+ * This module is intentionally pure: it reads a universe-shaped record and
+ * returns text without touching storage, the filesystem, or the network.
+ */
+
+const CANON_ENTRY_FIELD_ORDER = Object.freeze({
+ characters: Object.freeze([
+ 'aliases', 'role', 'pronouns', 'age', 'coreTheme', 'speechAccent',
+ 'speechPattern', 'visualNotes', 'physicalDescription', 'personality',
+ 'background', 'silhouetteNotes', 'postureNotes', 'specialTraits',
+ 'visualIdentity', 'motivations', 'ghost', 'wound', 'lie', 'want', 'need',
+ 'arcType', 'sliders', 'secrets', 'likes', 'dislikes', 'mannerisms',
+ 'relationships', 'skills', 'stats', 'colorPalette', 'props',
+ 'expressions', 'handGestures', 'voiceId', 'wardrobes', 'tags', 'prompt',
+ 'notes', 'evidence', 'firstAppearance', 'imageRefs', 'primaryImageRef',
+ 'referenceSheetImageRef', 'referenceSheets',
+ ]),
+ places: Object.freeze([
+ 'slugline', 'description', 'palette', 'era', 'weather', 'intExt',
+ 'timeOfDay', 'recurringDetails', 'tags', 'prompt', 'notes', 'evidence',
+ 'firstAppearance', 'imageRefs', 'primaryImageRef',
+ ]),
+ objects: Object.freeze([
+ 'aliases', 'description', 'significance', 'attachments', 'tags', 'prompt',
+ 'notes', 'evidence', 'firstAppearance', 'imageRefs', 'primaryImageRef',
+ ]),
+});
+
+const ENTRY_METADATA_FIELDS = new Set([
+ 'id', 'createdAt', 'updatedAt', 'source', 'sourceSeriesId', 'ingredientId',
+ 'deleted', 'deletedAt', 'schemaVersion', 'locked', 'missingFromProse',
+]);
+
+const CANON_SECTIONS = Object.freeze([
+ ['characters', 'Characters'],
+ ['places', 'Places'],
+ ['objects', 'Objects'],
+]);
+
+const compareNames = (left, right) => {
+ const a = String(left).toLowerCase();
+ const b = String(right).toLowerCase();
+ if (a < b) return -1;
+ if (a > b) return 1;
+ const rawA = String(left);
+ const rawB = String(right);
+ return rawA < rawB ? -1 : rawA > rawB ? 1 : 0;
+};
+
+const asTrimmedText = (value) => (typeof value === 'string' ? value.trim() : '');
+
+const hasContent = (value) => {
+ if (value === null || value === undefined) return false;
+ if (typeof value === 'string') return Boolean(value.trim());
+ if (typeof value === 'number' || typeof value === 'boolean') return true;
+ if (Array.isArray(value)) return value.some(hasContent);
+ if (typeof value === 'object') return Object.values(value).some(hasContent);
+ return false;
+};
+
+const formatFieldLabel = (key) => String(key)
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
+ .replace(/[_-]+/g, ' ')
+ .replace(/^./, (char) => char.toUpperCase());
+
+const formatInlineValue = (value) => {
+ if (value === null || value === undefined) return '';
+ if (typeof value === 'string') return value.trim();
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
+ if (Array.isArray(value)) {
+ return value.map(formatInlineValue).filter(Boolean).join(', ');
+ }
+ if (typeof value === 'object') {
+ return Object.entries(value)
+ .sort(([a], [b]) => compareNames(a, b))
+ .map(([key, nested]) => {
+ const rendered = formatInlineValue(nested);
+ return rendered ? `${formatFieldLabel(key)}: ${rendered}` : '';
+ })
+ .filter(Boolean)
+ .join('; ');
+ }
+ return '';
+};
+
+const headingText = (value, fallback) => String(value || fallback)
+ .trim()
+ .replace(/[\r\n]+/g, ' ')
+ .replace(/\s+/g, ' ');
+
+const entryName = (entry, fallback) => headingText(entry?.name || entry?.slugline, fallback);
+
+const orderedEntryKeys = (kind, entry) => {
+ const preferred = CANON_ENTRY_FIELD_ORDER[kind] || [];
+ const preferredKeys = preferred.filter((key) => Object.prototype.hasOwnProperty.call(entry, key));
+ const remainingKeys = Object.keys(entry)
+ .filter((key) => key !== 'name' && !preferred.includes(key) && !ENTRY_METADATA_FIELDS.has(key))
+ .sort(compareNames);
+ return [...preferredKeys, ...remainingKeys];
+};
+
+const renderEntry = (kind, entry, fallback) => {
+ if (!entry || typeof entry !== 'object') return '';
+ const lines = [`### ${entryName(entry, fallback)}`];
+ for (const key of orderedEntryKeys(kind, entry)) {
+ const value = entry[key];
+ if (!hasContent(value)) continue;
+ const rendered = formatInlineValue(value);
+ if (!rendered) continue;
+ lines.push(`**${formatFieldLabel(key)}:** ${rendered}`);
+ }
+ return lines.join('\n');
+};
+
+const renderCanonSection = (key, title, record) => {
+ const entries = Array.isArray(record?.[key]) ? record[key] : [];
+ if (entries.length === 0) return '';
+ const renderedEntries = entries
+ .map((entry, index) => renderEntry(key, entry, `${title.slice(0, -1)} ${index + 1}`))
+ .filter(Boolean);
+ return renderedEntries.length ? `## ${title}\n\n${renderedEntries.join('\n\n')}` : '';
+};
+
+const renderCategory = (name, category) => {
+ const variations = Array.isArray(category) ? category : category?.variations;
+ if (!Array.isArray(variations) || variations.length === 0) return '';
+ const lines = [`### ${headingText(name, 'Unnamed Category')}`];
+ if (category?.kind) lines.push(`**Kind:** ${formatInlineValue(category.kind)}`);
+ for (const variation of variations) {
+ if (typeof variation === 'string') {
+ if (variation.trim()) lines.push(`- ${variation.trim()}`);
+ continue;
+ }
+ if (!variation || typeof variation !== 'object') continue;
+ const label = asTrimmedText(variation.label || variation.name);
+ const prompt = asTrimmedText(variation.prompt || variation.description);
+ if (!label && !prompt) continue;
+ if (label && prompt) lines.push(`- **${label}** — ${prompt}`);
+ else lines.push(`- ${label || prompt}`);
+ }
+ return lines.length > 1 ? lines.join('\n') : '';
+};
+
+const renderCategories = (record) => {
+ if (!record?.categories || typeof record.categories !== 'object' || Array.isArray(record.categories)) return '';
+ const categories = Object.entries(record.categories)
+ .sort(([a], [b]) => compareNames(a, b))
+ .map(([name, category]) => renderCategory(name, category))
+ .filter(Boolean);
+ return categories.length ? `## Categories\n\n${categories.join('\n\n')}` : '';
+};
+
+const listValues = (value) => (Array.isArray(value) ? value : [])
+ .map((item) => (typeof item === 'string' ? item.trim() : ''))
+ .filter(Boolean);
+
+const renderInfluences = (record) => {
+ const embrace = listValues(record?.influences?.embrace);
+ const avoid = listValues(record?.influences?.avoid);
+ const lines = [
+ ...embrace.map((value) => `- Embrace: ${value}`),
+ ...avoid.map((value) => `- Avoid: ${value}`),
+ ];
+ return lines.length ? `## Influences\n\n${lines.join('\n')}` : '';
+};
+
+const filenamesFor = (item) => [
+ ...(Array.isArray(item?.imageRefs) ? item.imageRefs : []),
+ ...(typeof item?.filename === 'string' ? [item.filename] : []),
+].map((filename) => filename.trim()).filter(Boolean);
+
+const renderNamedFileList = (title, values, nameKeys) => {
+ if (!Array.isArray(values) || values.length === 0) return '';
+ const lines = values.map((item) => {
+ if (typeof item === 'string') return item.trim();
+ if (!item || typeof item !== 'object') return '';
+ const name = nameKeys.map((key) => asTrimmedText(item[key])).find(Boolean) || '';
+ const filenames = filenamesFor(item);
+ return [name, ...filenames].filter(Boolean).join(' — ');
+ }).filter(Boolean);
+ return lines.length ? `## ${title}\n\n${lines.map((line) => `- ${line}`).join('\n')}` : '';
+};
+
+/**
+ * Convert a universe name to a filesystem-safe, human-readable slug.
+ *
+ * The fallback keeps the download filename useful even for a missing or
+ * non-ASCII-only name while the character whitelist prevents path traversal.
+ */
+export const slugifyUniverseName = (name) => {
+ const value = String(name ?? '')
+ .normalize('NFKD')
+ .replace(/[\u0300-\u036f]/g, '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '');
+ return value || 'universe';
+};
+
+export const universeMarkdownFilename = (name) => `${slugifyUniverseName(name)}.md`;
+
+/**
+ * Serialize one Universe Builder record as a deterministic Markdown world
+ * bible. Canon arrays retain stored order; category names sort alphabetically.
+ *
+ * @param {Record<string, unknown>} record - A sanitized or universe-shaped record.
+ * @returns {string} Markdown text ending in one newline.
+ */
+export function universeToMarkdown(record) {
+ const source = record && typeof record === 'object' ? record : {};
+ const sections = [`# ${headingText(source.name, 'Untitled Universe')}`];
+ const prose = ['logline', 'premise', 'styleNotes']
+ .map((key) => asTrimmedText(source[key]))
+ .filter(Boolean);
+ if (prose.length) sections.push(prose.join('\n\n'));
+
+ for (const [key, title] of CANON_SECTIONS) {
+ const section = renderCanonSection(key, title, source);
+ if (section) sections.push(section);
+ }
+
+ for (const section of [
+ renderCategories(source),
+ renderInfluences(source),
+ renderNamedFileList('Composite Sheets', source.compositeSheets, ['label', 'name']),
+ renderNamedFileList('Style References', source.styleReferences, ['title', 'label', 'name']),
+ ]) {
+ if (section) sections.push(section);
+ }
+
+ return `${sections.join('\n\n').trimEnd()}\n`;
+}
diff --git a/server/lib/universeMarkdown.test.js b/server/lib/universeMarkdown.test.js
new file mode 100644
index 0000000000..fc3b0a2f9a
--- /dev/null
+++ b/server/lib/universeMarkdown.test.js
@@ -0,0 +1,72 @@
+import { describe, expect, it } from 'vitest';
+import { slugifyUniverseName, universeMarkdownFilename, universeToMarkdown } from './universeMarkdown.js';
+
+describe('universeToMarkdown', () => {
+ it('serializes the full world-bible shape in stored order', () => {
+ const markdown = universeToMarkdown({
+ name: 'The Bright World',
+ logline: 'A world beneath two suns.',
+ premise: 'Every map changes when the second sun rises.',
+ styleNotes: 'Painted edges and warm copper light.',
+ characters: [{ name: 'Mira', role: 'Cartographer', physicalDescription: 'Patient and precise.' }],
+ places: [{ name: 'The Archive', description: 'A tower of living maps.' }],
+ objects: [{ name: 'Sun Compass', description: 'Points toward the next dawn.' }],
+ categories: {
+ ziggurats: { kind: 'places', variations: [{ label: 'Old Ziggurat', prompt: 'terraced stone' }] },
+ landscapes: { kind: 'places', variations: [{ label: 'Copper Flats', prompt: 'shimmering salt' }] },
+ },
+ influences: { embrace: ['copper', 'dust'], avoid: ['plastic'] },
+ compositeSheets: [{ label: 'Costume Board', imageRefs: ['costume-board.png'], prompt: 'not exported' }],
+ styleReferences: [{ title: 'Ink Wash', imageRefs: ['ink-wash.png'], prompt: 'not exported' }],
+ });
+
+ expect(markdown).toContain('# The Bright World');
+ expect(markdown).toContain('A world beneath two suns.\n\nEvery map changes when the second sun rises.');
+ expect(markdown).toContain('## Characters\n\n### Mira');
+ expect(markdown).toContain('**Physical Description:** Patient and precise.');
+ expect(markdown).toContain('## Places\n\n### The Archive');
+ expect(markdown).toContain('## Objects\n\n### Sun Compass');
+ expect(markdown).toContain('## Categories\n\n### landscapes');
+ expect(markdown).toContain('### ziggurats');
+ expect(markdown.indexOf('### landscapes')).toBeLessThan(markdown.indexOf('### ziggurats'));
+ expect(markdown).toContain('- Embrace: copper');
+ expect(markdown).toContain('- Avoid: plastic');
+ expect(markdown).toContain('## Composite Sheets\n\n- Costume Board — costume-board.png');
+ expect(markdown).toContain('## Style References\n\n- Ink Wash — ink-wash.png');
+ expect(markdown).not.toContain('not exported');
+ });
+
+ it('omits empty canon sections and auxiliary sections', () => {
+ const markdown = universeToMarkdown({
+ name: 'Empty World',
+ characters: [],
+ places: [],
+ objects: [],
+ categories: {},
+ influences: { embrace: [], avoid: [] },
+ compositeSheets: [],
+ styleReferences: [],
+ });
+
+ expect(markdown).toBe('# Empty World\n');
+ expect(markdown).not.toContain('## Characters');
+ expect(markdown).not.toContain('## Categories');
+ expect(markdown).not.toContain('## Influences');
+ });
+
+ it('tolerates missing optional fields and malformed list values', () => {
+ expect(universeToMarkdown({ name: 'Minimal World' })).toBe('# Minimal World\n');
+ expect(universeToMarkdown(null)).toBe('# Untitled Universe\n');
+ expect(universeToMarkdown({ name: 'Safe', characters: [null, { name: 'One' }] }))
+ .toContain('### One');
+ });
+});
+
+describe('universe markdown filenames', () => {
+ it('slugifies names safely and falls back when no slug remains', () => {
+ expect(slugifyUniverseName('The Bright World / V2!')).toBe('the-bright-world-v2');
+ expect(slugifyUniverseName('Café')).toBe('cafe');
+ expect(slugifyUniverseName('!!!')).toBe('universe');
+ expect(universeMarkdownFilename('The Bright World')).toBe('the-bright-world.md');
+ });
+});
diff --git a/server/routes/universeBuilder/export.js b/server/routes/universeBuilder/export.js
new file mode 100644
index 0000000000..edbe520726
--- /dev/null
+++ b/server/routes/universeBuilder/export.js
@@ -0,0 +1,26 @@
+/**
+ * Universe Builder export routes.
+ *
+ * The route is mounted before crud.js because the CRUD wildcard owns
+ * `GET /:id`; keeping this sub-router ahead of it makes the nested export path
+ * an explicit part of the route contract.
+ */
+
+import { Router } from 'express';
+import { asyncHandler } from '../../lib/errorHandler.js';
+import { universeMarkdownFilename, universeToMarkdown } from '../../lib/universeMarkdown.js';
+import * as svc from '../../services/universeBuilder.js';
+import { mapServiceError } from './shared.js';
+
+const router = Router();
+
+router.get('/:id/export/markdown', asyncHandler(async (req, res) => {
+ const universe = await svc.getUniverse(req.params.id).catch((err) => {
+ throw mapServiceError(err);
+ });
+ res.setHeader('Content-Type', 'text/markdown; charset=utf-8');
+ res.setHeader('Content-Disposition', `attachment; filename="${universeMarkdownFilename(universe.name)}"`);
+ res.send(universeToMarkdown(universe));
+}));
+
+export default router;
diff --git a/server/routes/universeBuilder/index.js b/server/routes/universeBuilder/index.js
index 2b5595c520..27af31abca 100644
--- a/server/routes/universeBuilder/index.js
+++ b/server/routes/universeBuilder/index.js
@@ -24,6 +24,7 @@ import visionRoutes from './vision.js';
import styleReferenceRoutes from './styleReferences.js';
import referenceSheetRoutes from './referenceSheets.js';
import mergeRoutes from './merge.js';
+import exportRoutes from './export.js';
import crudRoutes from './crud.js';
import renderRoutes from './render.js';
import canonRoutes from './canon.js';
@@ -35,6 +36,7 @@ router.use(visionRoutes);
router.use(styleReferenceRoutes);
router.use(referenceSheetRoutes);
router.use(mergeRoutes);
+router.use(exportRoutes);
router.use(crudRoutes);
router.use(renderRoutes);
router.use(canonRoutes);
diff --git a/server/routes/universeBuilder/index.test.js b/server/routes/universeBuilder/index.test.js
index 0c24acd708..678b91dd58 100644
--- a/server/routes/universeBuilder/index.test.js
+++ b/server/routes/universeBuilder/index.test.js
@@ -318,6 +318,32 @@ describe('universe-builder routes', () => {
errSpy.mockRestore();
});
+ it('GET /:id/export/markdown returns a Markdown attachment and 404s when missing', async () => {
+ const app = buildApp();
+ const created = await request(app)
+ .post('/api/universe-builder')
+ .send({
+ name: 'The Bright World',
+ logline: 'A world beneath two suns.',
+ characters: [{ name: 'Mira', physicalDescription: 'A patient cartographer.' }],
+ });
+ expect(created.status).toBe(201);
+
+ const exported = await request(app)
+ .get(`/api/universe-builder/${created.body.id}/export/markdown`);
+ expect(exported.status).toBe(200);
+ expect(exported.headers['content-type']).toMatch(/^text\/markdown; charset=utf-8/);
+ expect(exported.headers['content-disposition']).toBe('attachment; filename="the-bright-world.md"');
+ expect(exported.text).toContain('# The Bright World');
+ expect(exported.text).toContain('### Mira');
+ expect(exported.text).not.toMatch(/\{"id"/);
+
+ const missing = await request(app)
+ .get('/api/universe-builder/does-not-exist/export/markdown');
+ expect(missing.status).toBe(404);
+ expect(missing.body.code).toBe('NOT_FOUND');
+ });
+
it('POST / creates a universe', async () => {
const res = await request(buildApp())
.post('/api/universe-builder')