verso-cms 0.0.0-stage → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +168 -2
- package/bin/verso.js +16 -0
- package/editor/door.js +139 -0
- package/editor/editor.js +1880 -0
- package/editor/elevate.css +2158 -0
- package/editor/ext-attrs.js +87 -0
- package/editor/ext-blocks.js +422 -0
- package/editor/ext-builder.js +819 -0
- package/editor/ext-channels.js +574 -0
- package/editor/ext-components.js +160 -0
- package/editor/ext-history.js +242 -0
- package/editor/ext-palette.js +307 -0
- package/editor/ext-people.js +345 -0
- package/editor/ext-repeaters.js +143 -0
- package/editor/ext-screens.js +94 -0
- package/editor/ext-site-settings.js +318 -0
- package/editor/ext-site-view.js +632 -0
- package/editor/ext-tokens.js +1195 -0
- package/editor/new-page.js +252 -0
- package/editor/rich.js +23 -0
- package/package.json +69 -4
- package/src/blocks.js +269 -0
- package/src/box.js +339 -0
- package/src/build.js +210 -0
- package/src/cli.js +161 -0
- package/src/color.js +137 -0
- package/src/components.js +223 -0
- package/src/elevate.js +74 -0
- package/src/errors.js +46 -0
- package/src/extensions/README.md +70 -0
- package/src/extensions/blocks.js +294 -0
- package/src/extensions/builder.js +734 -0
- package/src/extensions/channels.js +341 -0
- package/src/extensions/components.js +141 -0
- package/src/extensions/history.js +169 -0
- package/src/extensions/palette.js +31 -0
- package/src/extensions/people.js +113 -0
- package/src/extensions/site-settings.js +251 -0
- package/src/extensions/site-view.js +381 -0
- package/src/extensions/tags.js +15 -0
- package/src/extensions/tokens.js +587 -0
- package/src/fonts.js +139 -0
- package/src/git.js +419 -0
- package/src/html-edit.js +942 -0
- package/src/images.js +116 -0
- package/src/people.js +286 -0
- package/src/rich.js +124 -0
- package/src/scaffold.js +185 -0
- package/src/screens.js +65 -0
- package/src/server.js +693 -0
- package/src/site.js +618 -0
- package/src/template.js +915 -0
- package/src/video.js +29 -0
- package/starter/Dockerfile +20 -0
- package/starter/README.md +49 -0
- package/starter/blocks/call-to-action.html +6 -0
- package/starter/blocks/features.html +15 -0
- package/starter/blocks/hero.html +8 -0
- package/starter/blocks/image-and-text.html +8 -0
- package/starter/blocks/latest-posts.html +20 -0
- package/starter/blocks/post-index.html +30 -0
- package/starter/blocks/quote.html +9 -0
- package/starter/blocks/site-footer.html +8 -0
- package/starter/blocks/site-nav.html +8 -0
- package/starter/blocks/tag-list.html +10 -0
- package/starter/blocks/tagged-posts.html +19 -0
- package/starter/blocks/team.html +15 -0
- package/starter/blocks/text.html +4 -0
- package/starter/content/404/page.json +21 -0
- package/starter/content/about/page.json +65 -0
- package/starter/content/journal/designing-for-the-morning-shift/body.html +22 -0
- package/starter/content/journal/designing-for-the-morning-shift/checklist.jpg +0 -0
- package/starter/content/journal/designing-for-the-morning-shift/cover.jpg +0 -0
- package/starter/content/journal/designing-for-the-morning-shift/page.json +17 -0
- package/starter/content/journal/page.json +19 -0
- package/starter/content/journal/the-first-week/body.html +17 -0
- package/starter/content/journal/the-first-week/cover.jpg +0 -0
- package/starter/content/journal/the-first-week/page.json +17 -0
- package/starter/content/journal/the-first-week/wall-of-cards.jpg +0 -0
- package/starter/content/page.json +94 -0
- package/starter/content/site.json +88 -0
- package/starter/content/studio-table.jpg +0 -0
- package/starter/content/topics/page.json +27 -0
- package/starter/dockerignore +5 -0
- package/starter/elevate/config/design.ts +30 -0
- package/starter/elevate/config/elevate.ts +16 -0
- package/starter/elevate/config/syntax.ts +6 -0
- package/starter/elevate/design/site.ts +9 -0
- package/starter/elevate/design/tokens.json +20 -0
- package/starter/elevate/extend/fonts.css +1 -0
- package/starter/gitignore +6 -0
- package/starter/netlify.toml +5 -0
- package/starter/parts/.gitkeep +0 -0
- package/starter/public/favicon.svg +1 -0
- package/starter/templates/page.html +20 -0
- package/starter/templates/page.layout.json +23 -0
- package/starter/templates/post.html +65 -0
- package/starter/verso.defaults.json +33 -0
- package/starter-blank/blocks/site-footer.html +3 -0
- package/starter-blank/blocks/site-nav.html +8 -0
- package/starter-blank/blocks/text.html +4 -0
- package/starter-blank/content/404/page.json +18 -0
- package/starter-blank/content/page.json +18 -0
- package/starter-blank/content/site.json +36 -0
- package/starter-blank/elevate/design/tokens.json +10 -0
- package/starter-blank/templates/page.html +17 -0
- package/starter-blank/verso.defaults.json +26 -0
package/src/server.js
ADDED
|
@@ -0,0 +1,693 @@
|
|
|
1
|
+
// verso: the editor. A local web server that shows the real site with an
|
|
2
|
+
// editing layer on top, saves every change to disk as you go, and publishes
|
|
3
|
+
// with git.
|
|
4
|
+
|
|
5
|
+
import http from 'http';
|
|
6
|
+
import fs from 'fs';
|
|
7
|
+
import path from 'path';
|
|
8
|
+
import { createHash } from 'crypto';
|
|
9
|
+
import { fileURLToPath, pathToFileURL } from 'url';
|
|
10
|
+
import { spawn } from 'child_process';
|
|
11
|
+
import chokidar from 'chokidar';
|
|
12
|
+
import { loadSite, readPage, writePage, dirForUrl, checkPage, checkSite, createPage, readConfig, pageImages, listTemplates, slugify, PAGE_FILE, readSiteData, writeSiteData, withSiteBlocks, writePageAndSite, tagPages } from './site.js';
|
|
13
|
+
import { renderPage, escapeHtml, humanize, PLACEHOLDER_IMAGE, setColors, getColors, slugifyTag, uniqueTags } from './template.js';
|
|
14
|
+
import { loadElevate, compileCSS } from './elevate.js';
|
|
15
|
+
import { richClassList, partClassList, searchIndex, sitemap, channelFeeds, rss } from './build.js';
|
|
16
|
+
import { sanitizeRich, richIsEmpty, IMAGE_FILE } from './rich.js';
|
|
17
|
+
import { imageSize, sniffImage } from './images.js';
|
|
18
|
+
import { saveBlockField, blockFieldData } from './blocks.js';
|
|
19
|
+
import { publish, publishSummary, pullLatest } from './git.js';
|
|
20
|
+
import { VersoError, formatError } from './errors.js';
|
|
21
|
+
|
|
22
|
+
import { openBox } from './box.js';
|
|
23
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
24
|
+
const editorDir = path.join(here, '..', 'editor');
|
|
25
|
+
|
|
26
|
+
const TYPES = {
|
|
27
|
+
'.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
|
|
28
|
+
'.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
29
|
+
'.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif', '.ico': 'image/x-icon', '.woff2': 'font/woff2',
|
|
30
|
+
'.woff': 'font/woff', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml', '.pdf': 'application/pdf',
|
|
31
|
+
'.mp4': 'video/mp4', '.webm': 'video/webm',
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const MAX_TEXT = 20000;
|
|
35
|
+
const hash = (data) => createHash('sha1').update(data).digest('hex');
|
|
36
|
+
const MAX_UPLOAD = 25 * 1024 * 1024;
|
|
37
|
+
|
|
38
|
+
export async function startEditor(root, { port = 4321, open = true, log = console.log, box: boxed = false, host: bindTo = '' } = {}) {
|
|
39
|
+
const pulled = await pullLatest(root);
|
|
40
|
+
if (pulled.pulled) log('Pulled the latest version of the site.');
|
|
41
|
+
else if (pulled.reason === 'unpublished') log('You have unpublished changes, so Verso didn\'t pull. Publish them to sync.');
|
|
42
|
+
else if (pulled.reason === 'failed') log(pulled.message);
|
|
43
|
+
|
|
44
|
+
// ════ CSS, compiled by the site's Elevate ════
|
|
45
|
+
let elevate = null;
|
|
46
|
+
let css = '';
|
|
47
|
+
let cssError = null;
|
|
48
|
+
// What Elevate warns about without stopping: sizes written out of order.
|
|
49
|
+
// Shown with the page's other notes; they never block Publish.
|
|
50
|
+
let cssNotes = [];
|
|
51
|
+
const notesFrom = (warnings) => (warnings || []).filter((w) => /^Breakpoint/.test(w)).map((w) => {
|
|
52
|
+
const where = / in (\S+) on line (\d+)/.exec(w);
|
|
53
|
+
const real = where && !where[1].startsWith('(');
|
|
54
|
+
return new VersoError(w.replace(/ in \S+ on line \d+/, '').replace(/^Breakpoints? /, 'Screen sizes ').replace(/\bmarker\b/g, 'size marker'), {
|
|
55
|
+
file: real ? where[1].split(path.sep).join('/') : 'verso.json', line: real ? Number(where[2]) : null, warning: true,
|
|
56
|
+
hint: 'A class after /lg/ only applies from that size up. Move each class behind the right size, smallest first.',
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
let compiling = null;
|
|
60
|
+
let compileAgain = false;
|
|
61
|
+
|
|
62
|
+
const compile = async ({ reload = false } = {}) => {
|
|
63
|
+
if (compiling) {
|
|
64
|
+
compileAgain = true;
|
|
65
|
+
return compiling;
|
|
66
|
+
}
|
|
67
|
+
compiling = (async () => {
|
|
68
|
+
try {
|
|
69
|
+
if (!elevate || reload) elevate = await loadElevate(root);
|
|
70
|
+
let extra = [];
|
|
71
|
+
try { extra = richClassList(readConfig(root)); } catch { /* reported with the page */ }
|
|
72
|
+
try { extra = [...extra, ...partClassList(root)]; } catch { /* a part that can't be read is reported with the page */ }
|
|
73
|
+
try { setColors(elevate.describe().tokens.ColorToken); } catch { /* keep the last colours */ }
|
|
74
|
+
const result = await compileCSS(elevate, extra);
|
|
75
|
+
cssNotes = notesFrom(result.warnings);
|
|
76
|
+
if (result.ok) {
|
|
77
|
+
css = result.css;
|
|
78
|
+
cssError = null;
|
|
79
|
+
} else {
|
|
80
|
+
cssError = result.error;
|
|
81
|
+
}
|
|
82
|
+
} catch (err) {
|
|
83
|
+
cssError = err instanceof VersoError ? err : new VersoError(`Elevate stopped with an error: ${err.message}`);
|
|
84
|
+
}
|
|
85
|
+
})();
|
|
86
|
+
await compiling;
|
|
87
|
+
compiling = null;
|
|
88
|
+
if (compileAgain) {
|
|
89
|
+
compileAgain = false;
|
|
90
|
+
await compile();
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
await compile();
|
|
94
|
+
if (cssError) log(formatError(cssError));
|
|
95
|
+
|
|
96
|
+
// ════ A site in a box ════
|
|
97
|
+
// With verso serve, this same server is the site: visitors get the
|
|
98
|
+
// published pages, and people who sign in get everything below.
|
|
99
|
+
const box = boxed ? await openBox(root, { log }) : null;
|
|
100
|
+
|
|
101
|
+
// ════ Live updates ════
|
|
102
|
+
const clients = new Set();
|
|
103
|
+
const broadcast = (event) => {
|
|
104
|
+
const data = `data: ${JSON.stringify(event)}\n\n`;
|
|
105
|
+
clients.forEach((res) => res.write(data));
|
|
106
|
+
};
|
|
107
|
+
setInterval(() => clients.forEach((res) => res.write(': ping\n\n')), 25000).unref();
|
|
108
|
+
|
|
109
|
+
const written = new Map(); // page files Verso wrote, by content hash
|
|
110
|
+
const relPath = (p) => path.relative(root, p).split(path.sep).join('/');
|
|
111
|
+
const watcher = chokidar.watch(['templates', 'parts', 'blocks', 'components', 'content', 'public', 'verso.json', 'elevate/config', 'elevate/design', 'elevate/rules', 'elevate/extend'].map((p) => path.join(root, p)).filter((p) => fs.existsSync(p)), {
|
|
112
|
+
ignoreInitial: true,
|
|
113
|
+
ignored: (p) => path.basename(p).startsWith('.') || p.endsWith('.tmp'),
|
|
114
|
+
awaitWriteFinish: { stabilityThreshold: 120, pollInterval: 40 },
|
|
115
|
+
});
|
|
116
|
+
let pending = null;
|
|
117
|
+
const changes = new Set();
|
|
118
|
+
const onChange = (file) => {
|
|
119
|
+
const rel = relPath(file);
|
|
120
|
+
if (written.has(rel)) {
|
|
121
|
+
try {
|
|
122
|
+
if (written.get(rel) === hash(fs.readFileSync(file))) return; // our own save
|
|
123
|
+
} catch {
|
|
124
|
+
if (written.get(rel) === 'deleted') return;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
changes.add(rel);
|
|
128
|
+
clearTimeout(pending);
|
|
129
|
+
pending = setTimeout(async () => {
|
|
130
|
+
const list = [...changes];
|
|
131
|
+
changes.clear();
|
|
132
|
+
const system = list.some((r) => r.startsWith('elevate/'));
|
|
133
|
+
// Recompile CSS when anything Elevate reads changes: templates, parts,
|
|
134
|
+
// blocks, the rich map, and the folders in Elevate's own Watch list
|
|
135
|
+
// (scripts in public/js, say).
|
|
136
|
+
const scanned = (r) => r.startsWith('templates/') || r.startsWith('parts/') || r.startsWith('blocks/') || r === 'verso.json' || elevateWatch().some((dir) => r.startsWith(dir) && /\.[a-z]+$/.test(r));
|
|
137
|
+
if (system || list.some(scanned)) await compile({ reload: system && list.some((r) => !r.startsWith('elevate/extend/')) });
|
|
138
|
+
broadcast({ type: 'reload', files: list });
|
|
139
|
+
}, 80);
|
|
140
|
+
};
|
|
141
|
+
watcher.on('all', (event, file) => {
|
|
142
|
+
if (['add', 'change', 'unlink', 'addDir', 'unlinkDir'].includes(event)) onChange(file);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
// The folders Elevate scans for classes, from its config, as "public/js/".
|
|
146
|
+
const elevateWatch = () => {
|
|
147
|
+
try {
|
|
148
|
+
return (elevate?.describe().config.watch || []).map((w) => `${String(w).replace(/^\.\//, '').replace(/\/+$/, '')}/`).filter((w) => w !== '/');
|
|
149
|
+
} catch { return []; }
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
let extensionData = () => ({});
|
|
153
|
+
|
|
154
|
+
// In a box, who a page is being drawn for. Pages are drawn in one go, so
|
|
155
|
+
// this is set just before and cleared just after.
|
|
156
|
+
let asking = null;
|
|
157
|
+
// Parts of the editor that change how the site is built are for owners.
|
|
158
|
+
const OWNER_TOOLS = new Set(['ext-builder.js', 'ext-tokens.js', 'ext-site-settings.js']);
|
|
159
|
+
const editorFiles = () => fs.readdirSync(editorDir).filter((f) => /^ext-[a-z0-9-]+\.js$/.test(f)).sort()
|
|
160
|
+
.filter((f) => (box ? f !== 'ext-people.js' || asking : f !== 'ext-people.js'))
|
|
161
|
+
.filter((f) => !asking || asking.role === 'owner' || !OWNER_TOOLS.has(f));
|
|
162
|
+
const whoData = () => (asking ? { box: true, me: { id: asking.id, name: asking.name, email: asking.email, role: asking.role, initials: asking.initials } } : {});
|
|
163
|
+
|
|
164
|
+
// ════ Pages ════
|
|
165
|
+
// Problems also go to the terminal, once each, for whoever is working in
|
|
166
|
+
// a code editor and not looking at the browser.
|
|
167
|
+
let told = new Set();
|
|
168
|
+
const tell = (problems) => {
|
|
169
|
+
const now = new Set();
|
|
170
|
+
problems.forEach((p) => {
|
|
171
|
+
const key = `${p.file || ''}:${p.line || ''}:${p.message}`;
|
|
172
|
+
now.add(key);
|
|
173
|
+
if (!told.has(key)) log(`\x1b[31m${formatError(p)}\x1b[0m`);
|
|
174
|
+
});
|
|
175
|
+
told = new Set([...told, ...now].filter((k) => now.has(k)));
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
const ownColorNames = () => {
|
|
179
|
+
try {
|
|
180
|
+
return Object.keys(JSON.parse(fs.readFileSync(path.join(root, 'elevate', 'design', 'tokens.json'), 'utf8')).ColorToken || {});
|
|
181
|
+
} catch {
|
|
182
|
+
return [];
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
const pageData = (site, page, template, problems) => {
|
|
187
|
+
const fields = template
|
|
188
|
+
? [...template.fields.values()].map((f) => ({
|
|
189
|
+
name: f.name,
|
|
190
|
+
label: f.label,
|
|
191
|
+
type: f.type,
|
|
192
|
+
tools: f.tools,
|
|
193
|
+
required: f.required,
|
|
194
|
+
onPage: f.contexts.has('text'),
|
|
195
|
+
offPage: f.contexts.has('attr') || f.contexts.has('head'),
|
|
196
|
+
})).filter((f) => f.type !== 'blocks')
|
|
197
|
+
: [];
|
|
198
|
+
// Fields inside blocks are named "@<id>.<field>".
|
|
199
|
+
const inBlocks = blockFieldData(withSiteBlocks({ ...page, blocks: { ...page.blocks } }, site.siteData, template), site.blocks);
|
|
200
|
+
fields.push(...inBlocks.fields);
|
|
201
|
+
// Shared fields used only inside blocks.
|
|
202
|
+
if (template) siteFields(site, template, inBlocks.used).forEach((f) => {
|
|
203
|
+
if (fields.some((x) => x.name === f.name)) return;
|
|
204
|
+
fields.push({ name: f.name, label: f.label, type: f.type, tools: f.tools, required: false, onPage: f.contexts.has('text') || f.contexts.has('attr'), offPage: false });
|
|
205
|
+
});
|
|
206
|
+
return {
|
|
207
|
+
url: page.url,
|
|
208
|
+
label: page.label,
|
|
209
|
+
file: page.file,
|
|
210
|
+
template: page.template,
|
|
211
|
+
templateFile: template ? template.file : `templates/${page.template}.html`,
|
|
212
|
+
siteName: site.config.name,
|
|
213
|
+
title: page.title,
|
|
214
|
+
description: page.description,
|
|
215
|
+
date: page.date,
|
|
216
|
+
values: { ...page.fields, ...inBlocks.values, ...siteValues(site, template, inBlocks.used) },
|
|
217
|
+
tags: page.tags || [],
|
|
218
|
+
tagsOf: page.tagsOf || '',
|
|
219
|
+
blockTypes: [...site.blocks.entries()].map(([name, b]) => ({ name, label: b?.repeaterOf ? b.repeaterOf.label : humanize(name), repeater: !!b?.repeaterOf })),
|
|
220
|
+
rich: site.config.rich,
|
|
221
|
+
images: pageImages(page.dir),
|
|
222
|
+
placeholderImage: PLACEHOLDER_IMAGE,
|
|
223
|
+
// Colours that are themselves variables (like var(--ink)) can't be picked.
|
|
224
|
+
colors: fields.some((f) => f.type === 'color') ? Object.fromEntries(Object.entries(getColors()).filter(([, v]) => !/var\(/.test(String(v)))) : {},
|
|
225
|
+
// A tag's page is made by Verso, so it has no address or folder to change.
|
|
226
|
+
tag: page.tag || '',
|
|
227
|
+
// The colours this site added itself, so pickers can show them first.
|
|
228
|
+
ownColors: fields.some((f) => f.type === 'color') ? ownColorNames() : [],
|
|
229
|
+
draft: page.draft,
|
|
230
|
+
extensions: editorFiles(),
|
|
231
|
+
...whoData(),
|
|
232
|
+
...extensionData(site, page, template),
|
|
233
|
+
templates: listTemplates(root).map((name) => ({ name, label: humanize(name) })),
|
|
234
|
+
fields,
|
|
235
|
+
unused: template ? [...Object.keys(page.fields), ...Object.keys(page.rich)].filter((k) => !template.fields.has(k)) : [],
|
|
236
|
+
problems: problems.map((p) => (p.toJSON ? p.toJSON() : { message: String(p.message || p) })),
|
|
237
|
+
pages: site.pages.map((p) => ({ url: p.url, label: p.label, title: p.title })),
|
|
238
|
+
};
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
// Values of the site fields a template uses, named "site.<name>".
|
|
242
|
+
// Shared fields ({{ site.x }}) from the page's template and from any block.
|
|
243
|
+
const siteFields = (site, template, used = null) => {
|
|
244
|
+
const out = new Map();
|
|
245
|
+
[template, ...[...site.blocks.entries()].filter(([n]) => !used || used.has(n)).map(([, b]) => b)].forEach((t) => t?.fields?.forEach((f) => { if (f.site && f.type !== 'blocks' && !out.has(f.name)) out.set(f.name, f); }));
|
|
246
|
+
return out;
|
|
247
|
+
};
|
|
248
|
+
const siteValues = (site, template, used) => {
|
|
249
|
+
const out = {};
|
|
250
|
+
if (!template) return out;
|
|
251
|
+
siteFields(site, template, used).forEach((f) => {
|
|
252
|
+
const key = f.name.slice(5);
|
|
253
|
+
out[f.name] = f.type === 'rich' ? site.siteData.rich[key] || '' : site.siteData.fields[key] ?? '';
|
|
254
|
+
});
|
|
255
|
+
return out;
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
// A page that can't render, explained, with the editor still on it.
|
|
259
|
+
const problemPage = (site, title, problems, data, text = 'The details are in the panel. This page updates on its own once it\'s fixed.') => `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title>
|
|
260
|
+
<style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#F6F6F4;color:#25262A;font:16px/1.5 ui-sans-serif,system-ui,sans-serif}main{max-width:36rem;padding:3rem 1.5rem}h1{font-size:1.5rem;line-height:1.2;margin:0 0 .75rem}p{margin:0 0 1rem;color:#55565C}</style></head>
|
|
261
|
+
<body><main><h1>${escapeHtml(title)}</h1><p>${escapeHtml(text)}</p></main>
|
|
262
|
+
<script type="application/json" id="verso-data">${JSON.stringify({ ...data, problems: problems.map((p) => (p.toJSON ? p.toJSON() : { message: p.message })) }).replace(/</g, '\\u003c')}</script>
|
|
263
|
+
<script type="module" src="/__verso/editor.js"></script></body></html>`;
|
|
264
|
+
|
|
265
|
+
const renderUrl = (url) => {
|
|
266
|
+
const site = loadSite(root);
|
|
267
|
+
// Page 2 of a split list (/journal/page/2/) and the pages a tag home
|
|
268
|
+
// makes (/journal/tags/design/) are shown with the editor of the page
|
|
269
|
+
// they come from, so edits land there.
|
|
270
|
+
let shown = null;
|
|
271
|
+
let paging = null;
|
|
272
|
+
const split = /^(.*\/)page\/(\d+)\/$/.exec(url);
|
|
273
|
+
const lookupUrl = split ? split[1] : url;
|
|
274
|
+
if (split) paging = { number: Number(split[2]) };
|
|
275
|
+
// While editing, tags pages are made for drafts too, so they can be seen.
|
|
276
|
+
const virtual = tagPages(site.pages, { drafts: true }).find((p) => p.url === lookupUrl);
|
|
277
|
+
const dir = virtual ? virtual.dir : dirForUrl(root, lookupUrl);
|
|
278
|
+
const page = dir && site.pages.find((p) => p.dir === dir);
|
|
279
|
+
if (virtual) shown = virtual;
|
|
280
|
+
const base = { url, label: 'Not found', extensions: editorFiles(), ...whoData(), siteName: site.config.name, fields: [], values: {}, unused: [], templates: listTemplates(root).map((name) => ({ name, label: humanize(name) })), pages: site.pages.map((p) => ({ url: p.url, label: p.label, title: p.title })) };
|
|
281
|
+
if (!page) {
|
|
282
|
+
const broken = site.pageErrors.find((e) => dir && e.file === relPath(path.join(dir, PAGE_FILE)));
|
|
283
|
+
if (broken) return { status: 200, html: problemPage(site, 'This page can\'t be read', [broken], base) };
|
|
284
|
+
// A dead link isn't something to fix in the site, so no problem badge.
|
|
285
|
+
return { status: 404, html: problemPage(site, 'There\'s no page here', [], base, `Nothing is at ${url}. Pick a page from the page menu, or make a new one there.`) };
|
|
286
|
+
}
|
|
287
|
+
const templateError = site.templateErrors.get(page.template);
|
|
288
|
+
if (templateError) {
|
|
289
|
+
tell([templateError]);
|
|
290
|
+
return { status: 200, html: problemPage(site, 'This page\'s template has a problem', [templateError], { ...base, label: page.label }) };
|
|
291
|
+
}
|
|
292
|
+
const template = site.templates.get(page.template);
|
|
293
|
+
const problems = checkPage(root, page, template, { strict: false, blocks: site.blocks });
|
|
294
|
+
tell(problems);
|
|
295
|
+
if (!template) return { status: 200, html: problemPage(site, 'This page has no template', problems, { ...base, label: page.label }) };
|
|
296
|
+
if (cssError) problems.push(cssError);
|
|
297
|
+
problems.push(...cssNotes);
|
|
298
|
+
const html = renderPage(template, shown || page, {
|
|
299
|
+
mode: 'editor', siteName: site.config.name, editor: pageData(site, page, template, problems),
|
|
300
|
+
pages: site.pages, rich: site.config.rich, locale: site.config.locale, imageSize, blocks: site.blocks, paging,
|
|
301
|
+
});
|
|
302
|
+
return { status: 200, html };
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
// ════ Saving ════
|
|
306
|
+
// Every change is checked against the template before it's written, so
|
|
307
|
+
// nothing the editor sends can leave the page in a state the build rejects
|
|
308
|
+
// for reasons other than empty required fields.
|
|
309
|
+
const save = (body) => {
|
|
310
|
+
const dir = dirForUrl(root, String(body.url || ''));
|
|
311
|
+
if (!dir || !fs.existsSync(path.join(dir, PAGE_FILE))) throw new VersoError('That page no longer exists.');
|
|
312
|
+
const site = loadSite(root);
|
|
313
|
+
const own = readPage(root, dir);
|
|
314
|
+
const template = site.templates.get(own.template);
|
|
315
|
+
const page = withSiteBlocks(own, site.siteData, template);
|
|
316
|
+
if (!template) throw new VersoError('This page\'s template can\'t be read right now, so the change wasn\'t saved.');
|
|
317
|
+
const clean = (value, max) => String(value).replace(/\r?\n+/g, ' ').slice(0, max);
|
|
318
|
+
const siteChanges = { fields: {}, rich: {} };
|
|
319
|
+
if (body.fields && typeof body.fields === 'object') {
|
|
320
|
+
Object.entries(body.fields).forEach(([name, value]) => {
|
|
321
|
+
if (name.startsWith('@')) {
|
|
322
|
+
saveBlockField(page, site.blocks, name, value, { clean, exists: (f) => fs.existsSync(path.join(dir, f)) });
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
if (name.startsWith('site.')) {
|
|
326
|
+
const field = siteFields(site, template).get(name);
|
|
327
|
+
if (!field) throw new VersoError(`"${name}" isn't a field on this page.`);
|
|
328
|
+
const key = name.slice(5);
|
|
329
|
+
if (typeof value !== 'string') throw new VersoError(`"${field.label}" must be text.`);
|
|
330
|
+
if (field.type === 'rich') {
|
|
331
|
+
const html = sanitizeRich(value.slice(0, 2 * 1024 * 1024), field.tools);
|
|
332
|
+
if (!richIsEmpty(html)) siteChanges.rich[key] = html; else siteChanges.rich[key] = null;
|
|
333
|
+
} else siteChanges.fields[key] = clean(value, MAX_TEXT);
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
const field = template.fields.get(name);
|
|
337
|
+
if (!field || field.type === 'blocks') throw new VersoError(`"${name}" isn't a field on this page.`);
|
|
338
|
+
if (field.type === 'text') {
|
|
339
|
+
if (typeof value !== 'string') throw new VersoError(`"${field.label}" must be text.`);
|
|
340
|
+
page.fields[name] = clean(value, MAX_TEXT);
|
|
341
|
+
} else if (field.type === 'rich') {
|
|
342
|
+
if (typeof value !== 'string') throw new VersoError(`"${field.label}" must be rich text.`);
|
|
343
|
+
const html = sanitizeRich(value.slice(0, 2 * 1024 * 1024), field.tools);
|
|
344
|
+
if (!richIsEmpty(html)) page.rich[name] = html;
|
|
345
|
+
else delete page.rich[name];
|
|
346
|
+
} else if (field.type === 'color') {
|
|
347
|
+
if (value === null) { delete page.fields[name]; return; }
|
|
348
|
+
if (!value || typeof value.color !== 'string' || !(value.color in getColors())) throw new VersoError(`"${field.label}" must be one of the site's colours.`);
|
|
349
|
+
page.fields[name] = { color: value.color };
|
|
350
|
+
} else if (field.type === 'image') {
|
|
351
|
+
if (value === null) { delete page.fields[name]; return; }
|
|
352
|
+
if (typeof value !== 'object' || typeof value.file !== 'string') throw new VersoError(`"${field.label}" must be an image.`);
|
|
353
|
+
if (value.file && (!IMAGE_FILE.test(value.file) || !fs.existsSync(path.join(dir, value.file)))) throw new VersoError(`The image for "${field.label}" isn't in this page's folder. Choose it again.`);
|
|
354
|
+
page.fields[name] = { file: value.file, alt: clean(value.alt || '', 1000) };
|
|
355
|
+
}
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
if (typeof body.title === 'string') page.title = clean(body.title, 300);
|
|
359
|
+
if (typeof body.description === 'string') page.description = clean(body.description, 1000);
|
|
360
|
+
if (typeof body.date === 'string') {
|
|
361
|
+
if (body.date && !/^\d{4}-\d{2}-\d{2}$/.test(body.date)) throw new VersoError('That date should look like 2026-11-16.');
|
|
362
|
+
page.date = body.date;
|
|
363
|
+
}
|
|
364
|
+
if (typeof body.tagsOf === 'string') {
|
|
365
|
+
const folder = body.tagsOf.replace(/^\/+|\/+$/g, '');
|
|
366
|
+
if (folder && !fs.existsSync(path.join(root, 'content', ...folder.split('/')))) throw new VersoError(`There's no folder content/${folder}/ for this page to list the tags of.`);
|
|
367
|
+
page.tagsOf = folder;
|
|
368
|
+
}
|
|
369
|
+
if (Array.isArray(body.tags)) {
|
|
370
|
+
page.tags = uniqueTags(body.tags.filter((t) => typeof t === 'string').map((t) => clean(t, 80))).slice(0, 50);
|
|
371
|
+
}
|
|
372
|
+
if (Object.keys(siteChanges.fields).length || Object.keys(siteChanges.rich).length) {
|
|
373
|
+
const data = readSiteData(root);
|
|
374
|
+
Object.assign(data.fields, siteChanges.fields);
|
|
375
|
+
Object.entries(siteChanges.rich).forEach(([k, v]) => { if (v == null) delete data.rich[k]; else data.rich[k] = v; });
|
|
376
|
+
Object.entries(writeSiteData(root, data)).forEach(([rel, text]) => written.set(rel, hash(Buffer.from(text, 'utf8'))));
|
|
377
|
+
}
|
|
378
|
+
if (Array.isArray(body.remove)) {
|
|
379
|
+
body.remove.forEach((name) => {
|
|
380
|
+
if (template.fields.has(name)) throw new VersoError(`"${name}" is still used by the template, so it can't be removed.`);
|
|
381
|
+
delete page.fields[name];
|
|
382
|
+
delete page.rich[name];
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
const before = Object.keys(readPage(root, dir).rich);
|
|
386
|
+
const files = writePageAndSite(root, page);
|
|
387
|
+
Object.entries(files).forEach(([rel, text]) => written.set(rel, hash(Buffer.from(text, 'utf8'))));
|
|
388
|
+
before.filter((n) => !(n in page.rich)).forEach((n) => written.set(relPath(path.join(dir, `${n}.html`)), 'deleted'));
|
|
389
|
+
return page;
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
// ════ Uploads ════
|
|
393
|
+
// Images are kept in the page's own folder, so they move with the page.
|
|
394
|
+
// The type comes from the file's bytes, not its name.
|
|
395
|
+
const upload = (url, name, buffer) => {
|
|
396
|
+
const dir = dirForUrl(root, url);
|
|
397
|
+
if (!dir || !fs.existsSync(path.join(dir, PAGE_FILE))) throw new VersoError('That page no longer exists.');
|
|
398
|
+
if (!buffer.length) throw new VersoError('That file is empty.');
|
|
399
|
+
if (buffer.length > MAX_UPLOAD) throw new VersoError('That image is over 25 MB. Make it smaller and try again.');
|
|
400
|
+
const kind = sniffImage(buffer);
|
|
401
|
+
if (!kind) throw new VersoError('That file isn\'t an image Verso can use. Use a JPEG, PNG, GIF, WebP or AVIF.');
|
|
402
|
+
const base = slugify(String(name || '').replace(/\.[^.]*$/, '')) || 'image';
|
|
403
|
+
let file = `${base}.${kind}`;
|
|
404
|
+
for (let n = 2; fs.existsSync(path.join(dir, file)); n++) {
|
|
405
|
+
if (hash(fs.readFileSync(path.join(dir, file))) === hash(buffer)) break; // same image again: reuse it
|
|
406
|
+
file = `${base}-${n}.${kind}`;
|
|
407
|
+
}
|
|
408
|
+
const full = path.join(dir, file);
|
|
409
|
+
if (!fs.existsSync(full)) {
|
|
410
|
+
written.set(relPath(full), hash(buffer));
|
|
411
|
+
fs.writeFileSync(full, buffer);
|
|
412
|
+
}
|
|
413
|
+
const size = imageSize({ dir }, file);
|
|
414
|
+
return { file, url: `${urlForDirSafe(dir)}${encodeURIComponent(file)}`, width: size?.width, height: size?.height };
|
|
415
|
+
};
|
|
416
|
+
const urlForDirSafe = (dir) => {
|
|
417
|
+
const parts = path.relative(path.join(root, 'content'), dir).split(path.sep).filter(Boolean);
|
|
418
|
+
return parts.length ? `/${parts.join('/')}/` : '/';
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
// A template shown with a real page that uses it, or empty with placeholders.
|
|
422
|
+
const preview = (name) => {
|
|
423
|
+
const site = loadSite(root);
|
|
424
|
+
const template = site.templates.get(name);
|
|
425
|
+
if (!template) return null;
|
|
426
|
+
const example = site.pages.find((p) => p.template === name);
|
|
427
|
+
const page = example || { url: '/', dir: root, label: humanize(name), title: '', description: '', date: '', fields: {}, rich: {} };
|
|
428
|
+
return renderPage(template, page, { mode: 'editor', siteName: site.config.name, pages: site.pages, rich: site.config.rich, locale: site.config.locale, imageSize, blocks: site.blocks });
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
// ════ HTTP ════
|
|
432
|
+
const readBody = (req) =>
|
|
433
|
+
new Promise((resolve, reject) => {
|
|
434
|
+
let size = 0;
|
|
435
|
+
const chunks = [];
|
|
436
|
+
req.on('data', (c) => {
|
|
437
|
+
size += c.length;
|
|
438
|
+
if (size > 2 * 1024 * 1024) reject(new VersoError('That change is too large to save.'));
|
|
439
|
+
else chunks.push(c);
|
|
440
|
+
});
|
|
441
|
+
req.on('end', () => {
|
|
442
|
+
try {
|
|
443
|
+
resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {});
|
|
444
|
+
} catch {
|
|
445
|
+
reject(new VersoError('The editor sent something Verso couldn\'t read.'));
|
|
446
|
+
}
|
|
447
|
+
});
|
|
448
|
+
req.on('error', reject);
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
const readRaw = (req) =>
|
|
452
|
+
new Promise((resolve, reject) => {
|
|
453
|
+
let size = 0;
|
|
454
|
+
const chunks = [];
|
|
455
|
+
req.on('data', (c) => {
|
|
456
|
+
size += c.length;
|
|
457
|
+
if (size > MAX_UPLOAD) { reject(new VersoError('That image is over 25 MB. Make it smaller and try again.')); req.destroy(); } else chunks.push(c);
|
|
458
|
+
});
|
|
459
|
+
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
460
|
+
req.on('error', reject);
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
const send = (res, status, body, type = 'text/html; charset=utf-8') => {
|
|
464
|
+
// A picture someone uploaded is never allowed to run as a page.
|
|
465
|
+
const extra = String(type).startsWith('image/svg') ? { 'Content-Security-Policy': "script-src 'none'; sandbox" } : {};
|
|
466
|
+
res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', ...extra });
|
|
467
|
+
res.end(body);
|
|
468
|
+
};
|
|
469
|
+
const sendJSON = (res, status, body) => send(res, status, JSON.stringify(body), 'application/json');
|
|
470
|
+
|
|
471
|
+
// ════ Extensions ════
|
|
472
|
+
// Each file in src/extensions/ adds routes and editor data. See
|
|
473
|
+
// src/extensions/README.md.
|
|
474
|
+
const extensionDir = path.join(here, 'extensions');
|
|
475
|
+
const extensions = [];
|
|
476
|
+
const ctx = {
|
|
477
|
+
root, broadcast, written, hash, relPath, send, sendJSON, readBody, readRaw, compile, renderUrl, box,
|
|
478
|
+
get css() { return css; }, get cssError() { return cssError; },
|
|
479
|
+
};
|
|
480
|
+
for (const f of fs.existsSync(extensionDir) ? fs.readdirSync(extensionDir).filter((n) => n.endsWith('.js')).sort() : []) {
|
|
481
|
+
const mod = await import(pathToFileURL(path.join(extensionDir, f)).href);
|
|
482
|
+
if (typeof mod.setup === 'function') extensions.push({ name: f, ...(await mod.setup(ctx)) });
|
|
483
|
+
}
|
|
484
|
+
extensionData = (site, page, template) => Object.assign({}, ...extensions.map((e) => (e.editorData ? e.editorData(site, page, template) : {})));
|
|
485
|
+
|
|
486
|
+
const server = http.createServer(async (req, res) => {
|
|
487
|
+
const url = new URL(req.url, 'http://localhost');
|
|
488
|
+
const p = url.pathname;
|
|
489
|
+
try {
|
|
490
|
+
if (box) {
|
|
491
|
+
// The box decides who this is. Visitors and the sign-in pages are
|
|
492
|
+
// answered there; only signed-in people get any further.
|
|
493
|
+
const pass = await box.gate(req, res, url);
|
|
494
|
+
if (pass.done) return;
|
|
495
|
+
req.me = pass.me;
|
|
496
|
+
// Tell everyone else's editor when this person changes something.
|
|
497
|
+
if (req.me && req.method !== 'GET' && req.method !== 'HEAD' && p.startsWith('/__verso/') && p !== '/__verso/people/here') {
|
|
498
|
+
let from = '';
|
|
499
|
+
try { from = new URL(req.headers.referer).pathname; } catch { /* no page to name */ }
|
|
500
|
+
res.on('finish', () => {
|
|
501
|
+
if (res.statusCode < 400) broadcast({ type: 'changed', tab: String(req.headers['x-verso-tab'] || ''), by: req.me.id, name: req.me.name, page: from, what: p.slice('/__verso/'.length) });
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
} else {
|
|
505
|
+
// Only this computer may talk to the editor.
|
|
506
|
+
const host = (req.headers.host || '').split(':')[0];
|
|
507
|
+
if (!['localhost', '127.0.0.1', '[::1]'].includes(host)) return send(res, 403, 'Forbidden', 'text/plain');
|
|
508
|
+
if (req.method === 'POST' && req.headers.origin && !/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(req.headers.origin)) {
|
|
509
|
+
return send(res, 403, 'Forbidden', 'text/plain');
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
if (p === '/__verso/editor.js') return send(res, 200, fs.readFileSync(path.join(editorDir, 'editor.js')), TYPES['.js']);
|
|
514
|
+
if (p === '/__verso/elevate.css') return send(res, 200, fs.readFileSync(path.join(editorDir, 'elevate.css')), TYPES['.css']);
|
|
515
|
+
if (p === '/elevate.css') return send(res, 200, css, TYPES['.css']);
|
|
516
|
+
// What the build writes beside the pages, made fresh, so scripts that
|
|
517
|
+
// fetch them work while editing too.
|
|
518
|
+
if (p === '/pages.json' || p === '/sitemap.xml') {
|
|
519
|
+
const site = loadSite(root);
|
|
520
|
+
const body = p === '/pages.json' ? searchIndex(site) : sitemap(site);
|
|
521
|
+
if (body) return send(res, 200, body, p === '/pages.json' ? TYPES['.json'] || 'application/json; charset=utf-8' : 'application/xml; charset=utf-8');
|
|
522
|
+
}
|
|
523
|
+
if (p.endsWith('/feed.xml')) {
|
|
524
|
+
const site = loadSite(root);
|
|
525
|
+
const feed = channelFeeds(site).find((f) => f.url === p);
|
|
526
|
+
if (feed) return send(res, 200, rss(site, feed), 'application/rss+xml; charset=utf-8');
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
if (p === '/__verso/events') {
|
|
530
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' });
|
|
531
|
+
res.write(': connected\n\n');
|
|
532
|
+
clients.add(res);
|
|
533
|
+
req.on('close', () => clients.delete(res));
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
if (p === '/__verso/status' && req.method === 'GET') return sendJSON(res, 200, { ...(await publishSummary(root)), live: !!box });
|
|
538
|
+
if (p === '/__verso/pages' && req.method === 'GET') {
|
|
539
|
+
const site = loadSite(root);
|
|
540
|
+
return sendJSON(res, 200, { pages: site.pages.map((pg) => ({ url: pg.url, label: pg.label, title: pg.title })) });
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
if (p === '/__verso/save' && req.method === 'POST') {
|
|
544
|
+
try {
|
|
545
|
+
save(await readBody(req));
|
|
546
|
+
return sendJSON(res, 200, { ok: true });
|
|
547
|
+
} catch (err) {
|
|
548
|
+
if (!(err instanceof VersoError)) throw err;
|
|
549
|
+
return sendJSON(res, 400, { ok: false, message: err.message });
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
if (p === '/__verso/publish' && req.method === 'POST') {
|
|
554
|
+
// Never publish something the host's build would reject.
|
|
555
|
+
const problems = checkSite(loadSite(root)).filter((e) => !e.warning);
|
|
556
|
+
if (cssError) problems.push(cssError);
|
|
557
|
+
if (problems.length) {
|
|
558
|
+
return sendJSON(res, 409, {
|
|
559
|
+
ok: false,
|
|
560
|
+
problems: problems.map((e) => (e.toJSON ? e.toJSON() : { message: e.message })),
|
|
561
|
+
message: problems.length === 1 ? 'One thing needs fixing before this can be published. It\'s shown at the top right.' : `${problems.length} things need fixing before this can be published. They're shown at the top right.`,
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
const asked = await readBody(req).catch(() => ({}));
|
|
565
|
+
let result = await publish(root, { note: typeof asked?.note === 'string' ? asked.note : '', author: req.me || null });
|
|
566
|
+
// In a box, a restore point is the publish: the pages visitors get
|
|
567
|
+
// are rebuilt from it now. A repository, if there is one, is a copy.
|
|
568
|
+
if (box && (result.committed || (result.ok && !result.nothing) || box.liveError)) {
|
|
569
|
+
const built = await box.rebuild();
|
|
570
|
+
if (!built.ok) {
|
|
571
|
+
log(`\x1b[31m${formatError(built.error)}\x1b[0m`);
|
|
572
|
+
result = { ok: false, committed: result.committed, message: 'A restore point was saved, but the published pages couldn\'t be rebuilt, so visitors still see the last version. The reason is in the server\'s log.' };
|
|
573
|
+
} else if (result.ok) {
|
|
574
|
+
result = { ...result, message: 'Published. It\'s live now.' };
|
|
575
|
+
} else if (!result.conflict) {
|
|
576
|
+
result = { ok: true, committed: result.committed, copy: false, message: 'Published, and it\'s live now. The copy in the repository wasn\'t updated, so press Publish again later to send it.' };
|
|
577
|
+
}
|
|
578
|
+
if (req.me && result.ok) broadcast({ type: 'published', by: req.me.id, name: req.me.name, tab: String(req.headers['x-verso-tab'] || '') });
|
|
579
|
+
}
|
|
580
|
+
broadcast({ type: 'status' });
|
|
581
|
+
return sendJSON(res, result.ok ? 200 : 409, result);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
if (p === '/__verso/upload' && req.method === 'POST') {
|
|
585
|
+
try {
|
|
586
|
+
return sendJSON(res, 200, { ok: true, ...upload(url.searchParams.get('url') || '/', url.searchParams.get('name') || '', await readRaw(req)) });
|
|
587
|
+
} catch (err) {
|
|
588
|
+
if (!(err instanceof VersoError)) throw err;
|
|
589
|
+
return sendJSON(res, 400, { ok: false, message: err.message });
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if (p === '/__verso/pages' && req.method === 'POST') {
|
|
594
|
+
try {
|
|
595
|
+
const body = await readBody(req);
|
|
596
|
+
const page = createPage(root, { parent: String(body.parent || '/'), name: String(body.name || ''), template: String(body.template || '') });
|
|
597
|
+
written.set(page.file, hash(fs.readFileSync(path.join(page.dir, PAGE_FILE))));
|
|
598
|
+
broadcast({ type: 'pages' });
|
|
599
|
+
return sendJSON(res, 200, { ok: true, url: page.url });
|
|
600
|
+
} catch (err) {
|
|
601
|
+
if (!(err instanceof VersoError)) throw err;
|
|
602
|
+
return sendJSON(res, 400, { ok: false, message: err.message });
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
if (p.startsWith('/__verso/preview/')) {
|
|
607
|
+
const html = preview(decodeURIComponent(p.slice('/__verso/preview/'.length).replace(/\/$/, '')));
|
|
608
|
+
return html ? send(res, 200, html) : send(res, 404, 'Not found', 'text/plain');
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// The editor's own modules, from a fixed list, and its extensions (ext-*.js).
|
|
612
|
+
const editorModule = /^\/__verso\/(editor|rich|new-page|ext-[a-z0-9-]+)\.js$/.exec(p);
|
|
613
|
+
if (editorModule && fs.existsSync(path.join(editorDir, `${editorModule[1]}.js`))) return send(res, 200, fs.readFileSync(path.join(editorDir, `${editorModule[1]}.js`)), TYPES['.js']);
|
|
614
|
+
|
|
615
|
+
for (const ext of extensions) {
|
|
616
|
+
if (ext.handle && (await ext.handle(req, res, url))) return;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
if (p.startsWith('/__verso/')) return send(res, 404, 'Not found', 'text/plain');
|
|
620
|
+
|
|
621
|
+
// Images kept in a page's folder
|
|
622
|
+
if (IMAGE_FILE.test(decodeURIComponent(path.basename(p)))) {
|
|
623
|
+
const dir = dirForUrl(root, path.dirname(p) + '/');
|
|
624
|
+
const file = dir && path.join(dir, decodeURIComponent(path.basename(p)));
|
|
625
|
+
if (file && fs.existsSync(file) && fs.statSync(file).isFile()) {
|
|
626
|
+
return send(res, 200, fs.readFileSync(file), TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream');
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// Files from public/
|
|
631
|
+
if (path.extname(p)) {
|
|
632
|
+
const file = path.join(root, 'public', ...decodeURIComponent(p).split('/').filter((s) => s && s !== '..'));
|
|
633
|
+
if (file.startsWith(path.join(root, 'public')) && fs.existsSync(file) && fs.statSync(file).isFile()) {
|
|
634
|
+
return send(res, 200, fs.readFileSync(file), TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream');
|
|
635
|
+
}
|
|
636
|
+
return send(res, 404, 'Not found', 'text/plain');
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
if (!p.endsWith('/')) {
|
|
640
|
+
res.writeHead(301, { Location: `${p}/${url.search}` });
|
|
641
|
+
return res.end();
|
|
642
|
+
}
|
|
643
|
+
asking = req.me || null;
|
|
644
|
+
let page;
|
|
645
|
+
try { page = renderUrl(p); } finally { asking = null; }
|
|
646
|
+
return send(res, page.status, page.html);
|
|
647
|
+
} catch (err) {
|
|
648
|
+
const message = err instanceof VersoError ? err.message : `Something went wrong in Verso: ${err.message}`;
|
|
649
|
+
if (!(err instanceof VersoError)) log(err.stack || err);
|
|
650
|
+
if (p.startsWith('/__verso/')) return sendJSON(res, 500, { ok: false, message });
|
|
651
|
+
return send(res, 500, `<!DOCTYPE html><title>Verso</title><body style="font:16px system-ui;padding:3rem"><h1 style="font-size:1.25rem">Verso hit a problem</h1><p>${escapeHtml(message)}</p></body>`);
|
|
652
|
+
}
|
|
653
|
+
});
|
|
654
|
+
|
|
655
|
+
const listen = (tryPort) =>
|
|
656
|
+
new Promise((resolve, reject) => {
|
|
657
|
+
const onError = (err) => {
|
|
658
|
+
server.off('listening', onListening);
|
|
659
|
+
if (err.code === 'EADDRINUSE' && tryPort < port + 20 && !box) resolve(listen(tryPort + 1));
|
|
660
|
+
else reject(err);
|
|
661
|
+
};
|
|
662
|
+
const onListening = () => {
|
|
663
|
+
server.off('error', onError);
|
|
664
|
+
resolve(tryPort);
|
|
665
|
+
};
|
|
666
|
+
server.once('error', onError);
|
|
667
|
+
server.once('listening', onListening);
|
|
668
|
+
server.listen(tryPort, box ? bindTo || '0.0.0.0' : '127.0.0.1');
|
|
669
|
+
});
|
|
670
|
+
const actual = await listen(port);
|
|
671
|
+
const address = `http://localhost:${actual}/`;
|
|
672
|
+
|
|
673
|
+
if (open && !box) {
|
|
674
|
+
const [cmd, args] =
|
|
675
|
+
process.platform === 'darwin' ? ['open', [address]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', address]] : ['xdg-open', [address]];
|
|
676
|
+
try {
|
|
677
|
+
spawn(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
|
|
678
|
+
} catch {
|
|
679
|
+
// Opening a browser is a convenience; the address is printed either way.
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
return {
|
|
684
|
+
url: address,
|
|
685
|
+
port: actual,
|
|
686
|
+
box,
|
|
687
|
+
close: async () => {
|
|
688
|
+
clients.forEach((c) => c.end());
|
|
689
|
+
await watcher.close();
|
|
690
|
+
await new Promise((r) => server.close(r));
|
|
691
|
+
},
|
|
692
|
+
};
|
|
693
|
+
}
|