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/box.js
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
// A site in a box (verso serve): one program that is the site. Visitors get
|
|
2
|
+
// the published pages; people who sign in at /edit get the editor, at the
|
|
3
|
+
// same address. Publish makes a restore point and rebuilds the published
|
|
4
|
+
// pages straight away.
|
|
5
|
+
//
|
|
6
|
+
// The published pages are a build kept in .verso/live. It only ever changes
|
|
7
|
+
// on Publish, so unpublished work is never shown to visitors, even across a
|
|
8
|
+
// restart.
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import zlib from 'node:zlib';
|
|
13
|
+
import { execFile } from 'node:child_process';
|
|
14
|
+
import { openPeople, COOKIE } from './people.js';
|
|
15
|
+
import { buildSite } from './build.js';
|
|
16
|
+
import { gitState } from './git.js';
|
|
17
|
+
import { readConfig } from './site.js';
|
|
18
|
+
import { VersoError, formatError } from './errors.js';
|
|
19
|
+
import { signInPage, notSetUpPage, deadLinkPage, joinPage } from '../editor/door.js';
|
|
20
|
+
|
|
21
|
+
const TYPES = {
|
|
22
|
+
'.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
|
|
23
|
+
'.json': 'application/json; charset=utf-8', '.xml': 'application/xml; charset=utf-8', '.txt': 'text/plain; charset=utf-8', '.svg': 'image/svg+xml',
|
|
24
|
+
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif', '.ico': 'image/x-icon',
|
|
25
|
+
'.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf', '.otf': 'font/otf', '.pdf': 'application/pdf', '.mp4': 'video/mp4', '.webm': 'video/webm',
|
|
26
|
+
'.mp3': 'audio/mpeg', '.webmanifest': 'application/manifest+json', '.map': 'application/json; charset=utf-8',
|
|
27
|
+
};
|
|
28
|
+
const SQUEEZE = /^(text\/|application\/(json|xml|manifest\+json)|image\/svg)/;
|
|
29
|
+
|
|
30
|
+
// What only an owner may change: how the site looks and is put together,
|
|
31
|
+
// and who can edit it. Everything else is open to editors.
|
|
32
|
+
const OWNER_ONLY = [
|
|
33
|
+
/^\/__verso\/builder\//, /^\/__verso\/tokens/, /^\/__verso\/fonts$/, /^\/__verso\/site-settings/, /^\/__verso\/page-types\//,
|
|
34
|
+
/^\/__verso\/channels\/(setup|forget)$/, /^\/__verso\/people\/(invite|role|remove|link|cancel)$/,
|
|
35
|
+
];
|
|
36
|
+
// The few things anyone may load: the stylesheet the sign-in page wears.
|
|
37
|
+
const OPEN = new Set(['/__verso/elevate.css']);
|
|
38
|
+
|
|
39
|
+
const git = (root, args) =>
|
|
40
|
+
new Promise((resolve) => {
|
|
41
|
+
execFile('git', args, { cwd: root, maxBuffer: 20 * 1024 * 1024 }, (error, stdout, stderr) => resolve({ ok: !error, stdout: String(stdout), stderr: String(stderr) }));
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// Hosts that run a program from an image give it a separate disk that
|
|
45
|
+
// survives restarts. Given that disk's folder, the site moves onto it the
|
|
46
|
+
// first time and runs from there ever after; the programs it needs stay
|
|
47
|
+
// with the image, so they're updated by a new deploy.
|
|
48
|
+
export function moveIn(root, data, { log = console.log } = {}) {
|
|
49
|
+
const target = path.join(path.resolve(data), 'site');
|
|
50
|
+
if (path.resolve(root) === target) return target;
|
|
51
|
+
if (!fs.existsSync(path.join(target, 'verso.json'))) {
|
|
52
|
+
fs.mkdirSync(target, { recursive: true });
|
|
53
|
+
const skip = new Set(['node_modules', 'dist', '.verso']);
|
|
54
|
+
fs.readdirSync(root).filter((name) => !skip.has(name)).forEach((name) => fs.cpSync(path.join(root, name), path.join(target, name), { recursive: true }));
|
|
55
|
+
log(`Moved the site onto its own disk, at ${target}.`);
|
|
56
|
+
}
|
|
57
|
+
const modules = path.join(root, 'node_modules');
|
|
58
|
+
const link = path.join(target, 'node_modules');
|
|
59
|
+
if (fs.existsSync(modules)) {
|
|
60
|
+
try { if (fs.lstatSync(link).isSymbolicLink()) fs.unlinkSync(link); } catch { /* not there yet */ }
|
|
61
|
+
if (!fs.existsSync(link)) fs.symlinkSync(modules, link, 'dir');
|
|
62
|
+
}
|
|
63
|
+
return target;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function openBox(root, { log = console.log } = {}) {
|
|
67
|
+
const home = path.join(root, '.verso');
|
|
68
|
+
const liveDir = path.join(home, 'live');
|
|
69
|
+
fs.mkdirSync(home, { recursive: true });
|
|
70
|
+
const people = openPeople(root);
|
|
71
|
+
|
|
72
|
+
// ════ History lives in the box ════
|
|
73
|
+
// A box needs git for Publish and History. A folder that arrives without
|
|
74
|
+
// a repository gets one, with the site as it arrived as the first point.
|
|
75
|
+
let state = await gitState(root);
|
|
76
|
+
if (!state.available) throw new VersoError('Git isn\'t installed here, and a site needs it to keep its history.', { hint: 'Install git on this server, then start again.' });
|
|
77
|
+
// What Verso makes for itself never goes into the site's history, whatever
|
|
78
|
+
// the site's own .gitignore says.
|
|
79
|
+
const keepOut = () => {
|
|
80
|
+
try {
|
|
81
|
+
const exclude = path.join(root, '.git', 'info', 'exclude');
|
|
82
|
+
const now = fs.existsSync(exclude) ? fs.readFileSync(exclude, 'utf8') : '';
|
|
83
|
+
const missing = ['.verso/', '.verso-cache/', 'node_modules/'].filter((line) => !now.split('\n').includes(line));
|
|
84
|
+
if (!missing.length) return;
|
|
85
|
+
fs.mkdirSync(path.dirname(exclude), { recursive: true });
|
|
86
|
+
fs.writeFileSync(exclude, `${now}${now && !now.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`);
|
|
87
|
+
} catch { /* a repository kept somewhere unusual: its .gitignore has to cover it */ }
|
|
88
|
+
};
|
|
89
|
+
if (!state.repo) {
|
|
90
|
+
await git(root, ['init', '--quiet', '-b', 'main']);
|
|
91
|
+
keepOut();
|
|
92
|
+
await git(root, ['add', '-A']);
|
|
93
|
+
await git(root, ['-c', 'user.name=Verso', '-c', 'user.email=verso@localhost', 'commit', '--quiet', '-m', 'The site as it arrived']);
|
|
94
|
+
log('Started this site\'s history.');
|
|
95
|
+
}
|
|
96
|
+
keepOut();
|
|
97
|
+
state = await gitState(root);
|
|
98
|
+
// Git wants a name for its own housekeeping. Each publish carries the
|
|
99
|
+
// name of the person who pressed it; this is only the fallback.
|
|
100
|
+
if (!(await git(root, ['config', 'user.name'])).stdout.trim()) {
|
|
101
|
+
await git(root, ['config', 'user.name', 'Verso']);
|
|
102
|
+
await git(root, ['config', 'user.email', 'verso@localhost']);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// ════ Has this folder been kept? ════
|
|
106
|
+
// Some hosts hand a program a fresh disk on every restart. That would lose
|
|
107
|
+
// every edit, so count the starts and say so plainly when it looks wrong.
|
|
108
|
+
const recordFile = path.join(home, 'box.json');
|
|
109
|
+
let record = null;
|
|
110
|
+
try { record = JSON.parse(fs.readFileSync(recordFile, 'utf8')); } catch { /* first start */ }
|
|
111
|
+
const first = !record;
|
|
112
|
+
record = { first: record?.first || new Date().toISOString(), starts: (record?.starts || 0) + 1, last: new Date().toISOString() };
|
|
113
|
+
fs.writeFileSync(recordFile, `${JSON.stringify(record, null, 2)}\n`);
|
|
114
|
+
|
|
115
|
+
// ════ The published pages ════
|
|
116
|
+
let liveError = null;
|
|
117
|
+
let building = null;
|
|
118
|
+
const rebuild = () => {
|
|
119
|
+
if (building) return building.then(rebuild);
|
|
120
|
+
building = (async () => {
|
|
121
|
+
const next = path.join(home, 'next');
|
|
122
|
+
const old = path.join(home, 'old');
|
|
123
|
+
try {
|
|
124
|
+
fs.rmSync(next, { recursive: true, force: true });
|
|
125
|
+
const result = await buildSite(root, { out: path.join('.verso', 'next') });
|
|
126
|
+
// Swap whole folders, so a visitor never gets half a site.
|
|
127
|
+
fs.rmSync(old, { recursive: true, force: true });
|
|
128
|
+
if (fs.existsSync(liveDir)) fs.renameSync(liveDir, old);
|
|
129
|
+
fs.renameSync(next, liveDir);
|
|
130
|
+
fs.rmSync(old, { recursive: true, force: true });
|
|
131
|
+
squeezed.clear();
|
|
132
|
+
liveError = null;
|
|
133
|
+
return { ok: true, pages: result.pages, ms: result.ms };
|
|
134
|
+
} catch (err) {
|
|
135
|
+
fs.rmSync(next, { recursive: true, force: true });
|
|
136
|
+
liveError = err;
|
|
137
|
+
return { ok: false, error: err };
|
|
138
|
+
}
|
|
139
|
+
})();
|
|
140
|
+
return building.finally(() => { building = null; });
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
// ════ Serving the published pages ════
|
|
144
|
+
const squeezed = new Map(); // file → { stamp, body }
|
|
145
|
+
const serveLive = (req, res, p) => {
|
|
146
|
+
let parts;
|
|
147
|
+
try { parts = decodeURIComponent(p).split('/').filter(Boolean); } catch { parts = ['\0']; }
|
|
148
|
+
const safe = parts.every((s) => s !== '..' && !s.startsWith('.') && !s.includes('\0') && !s.includes('\\'));
|
|
149
|
+
let file = safe ? path.join(liveDir, ...parts) : null;
|
|
150
|
+
let stat = file && fs.existsSync(file) ? fs.statSync(file) : null;
|
|
151
|
+
if (stat?.isDirectory()) {
|
|
152
|
+
if (!p.endsWith('/')) {
|
|
153
|
+
res.writeHead(301, { Location: `${p}/` });
|
|
154
|
+
return res.end();
|
|
155
|
+
}
|
|
156
|
+
file = path.join(file, 'index.html');
|
|
157
|
+
stat = fs.existsSync(file) ? fs.statSync(file) : null;
|
|
158
|
+
}
|
|
159
|
+
let status = 200;
|
|
160
|
+
if (!stat?.isFile()) {
|
|
161
|
+
status = 404;
|
|
162
|
+
file = path.join(liveDir, '404.html');
|
|
163
|
+
stat = fs.existsSync(file) ? fs.statSync(file) : null;
|
|
164
|
+
if (!stat) {
|
|
165
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
166
|
+
return res.end(fs.existsSync(liveDir) ? 'Not found' : 'This site hasn\'t been published yet.');
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const type = TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream';
|
|
170
|
+
const etag = `"${stat.size.toString(36)}-${Math.round(stat.mtimeMs).toString(36)}"`;
|
|
171
|
+
const headers = {
|
|
172
|
+
'Content-Type': type,
|
|
173
|
+
// Pages are always checked for a newer copy, so a Publish shows at once.
|
|
174
|
+
'Cache-Control': type.startsWith('text/html') ? 'no-cache' : 'public, max-age=300',
|
|
175
|
+
ETag: etag,
|
|
176
|
+
'X-Content-Type-Options': 'nosniff',
|
|
177
|
+
};
|
|
178
|
+
// A picture someone uploaded is never allowed to run as a page.
|
|
179
|
+
if (type === 'image/svg+xml') headers['Content-Security-Policy'] = "script-src 'none'; sandbox";
|
|
180
|
+
if (status === 200 && req.headers['if-none-match'] === etag) {
|
|
181
|
+
res.writeHead(304, headers);
|
|
182
|
+
return res.end();
|
|
183
|
+
}
|
|
184
|
+
let body = null;
|
|
185
|
+
if (SQUEEZE.test(type) && stat.size > 1024 && /\bgzip\b/.test(req.headers['accept-encoding'] || '')) {
|
|
186
|
+
const kept = squeezed.get(file);
|
|
187
|
+
if (kept && kept.stamp === etag) body = kept.body;
|
|
188
|
+
else {
|
|
189
|
+
body = zlib.gzipSync(fs.readFileSync(file));
|
|
190
|
+
squeezed.set(file, { stamp: etag, body });
|
|
191
|
+
}
|
|
192
|
+
headers['Content-Encoding'] = 'gzip';
|
|
193
|
+
headers.Vary = 'Accept-Encoding';
|
|
194
|
+
}
|
|
195
|
+
headers['Content-Length'] = body ? body.length : stat.size;
|
|
196
|
+
res.writeHead(status, headers);
|
|
197
|
+
if (req.method === 'HEAD') return res.end();
|
|
198
|
+
if (body) return res.end(body);
|
|
199
|
+
return fs.createReadStream(file).pipe(res);
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
// ════ Who's asking ════
|
|
203
|
+
const cookies = (req) => Object.fromEntries(String(req.headers.cookie || '').split(';').map((c) => c.trim().split(/=(.*)/s).slice(0, 2)).filter((c) => c[0]));
|
|
204
|
+
const secure = (req) => req.socket.encrypted || String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim() === 'https';
|
|
205
|
+
const ip = (req) => String(req.headers['x-forwarded-for'] || '').split(',')[0].trim() || req.socket.remoteAddress || '';
|
|
206
|
+
const cookieHeader = (req, value, maxAge) => `${COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.round(maxAge)}${secure(req) ? '; Secure' : ''}`;
|
|
207
|
+
const who = (req) => people.fromCookie(cookies(req)[COOKIE]);
|
|
208
|
+
// A request that changes something must come from this site's own pages.
|
|
209
|
+
const sameOrigin = (req) => {
|
|
210
|
+
const origin = req.headers.origin;
|
|
211
|
+
// Browsers leave the origin out, or send "null", in a few honest cases;
|
|
212
|
+
// then their own word that the request is same-origin is what counts.
|
|
213
|
+
if (!origin || origin === 'null') return req.headers['sec-fetch-site'] === 'same-origin';
|
|
214
|
+
try {
|
|
215
|
+
const host = new URL(origin).host;
|
|
216
|
+
return host === req.headers.host || host === String(req.headers['x-forwarded-host'] || '').split(',')[0].trim();
|
|
217
|
+
} catch { return false; }
|
|
218
|
+
};
|
|
219
|
+
const siteName = () => { try { return readConfig(root).name; } catch { return 'This site'; } };
|
|
220
|
+
// Only ever send someone back to a page of this site.
|
|
221
|
+
const local = (to) => (typeof to === 'string' && /^\/(?!\/)[^\\]*$/.test(to) && !to.startsWith('/edit') ? to : '/');
|
|
222
|
+
|
|
223
|
+
const readForm = (req) =>
|
|
224
|
+
new Promise((resolve, reject) => {
|
|
225
|
+
let size = 0;
|
|
226
|
+
const chunks = [];
|
|
227
|
+
req.on('data', (c) => { size += c.length; if (size > 16 * 1024) { reject(new VersoError('That was too much to send.')); req.destroy(); } else chunks.push(c); });
|
|
228
|
+
req.on('end', () => resolve(Object.fromEntries(new URLSearchParams(Buffer.concat(chunks).toString('utf8')))));
|
|
229
|
+
req.on('error', reject);
|
|
230
|
+
});
|
|
231
|
+
const page = (res, status, html, extra = {}) => {
|
|
232
|
+
res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Frame-Options': 'DENY', 'Referrer-Policy': 'same-origin', 'X-Content-Type-Options': 'nosniff', ...extra });
|
|
233
|
+
res.end(html);
|
|
234
|
+
};
|
|
235
|
+
const go = (res, to, extra = {}) => { res.writeHead(303, { Location: to, 'Cache-Control': 'no-store', ...extra }); res.end(); };
|
|
236
|
+
const json = (res, status, body) => { res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(body)); };
|
|
237
|
+
|
|
238
|
+
// ════ The door: /edit ════
|
|
239
|
+
const door = async (req, res, url) => {
|
|
240
|
+
const p = url.pathname.replace(/\/+$/, '') || '/edit';
|
|
241
|
+
const site = siteName();
|
|
242
|
+
const me = who(req);
|
|
243
|
+
const post = req.method === 'POST';
|
|
244
|
+
if (post && !sameOrigin(req)) return page(res, 403, deadLinkPage({ site }));
|
|
245
|
+
|
|
246
|
+
if (p === '/edit/out') {
|
|
247
|
+
if (!post) return go(res, '/');
|
|
248
|
+
return go(res, '/', { 'Set-Cookie': cookieHeader(req, '', 0) });
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
if (p === '/edit/join') {
|
|
252
|
+
const form = post ? await readForm(req) : null;
|
|
253
|
+
const token = post ? form.t : url.searchParams.get('t');
|
|
254
|
+
const link = token ? people.peek(token) : null;
|
|
255
|
+
if (!link) return page(res, 404, deadLinkPage({ site }));
|
|
256
|
+
if (!post) return page(res, 200, joinPage({ site, link, token }));
|
|
257
|
+
try {
|
|
258
|
+
const person = await people.accept(token, { name: form.name, email: form.email, password: form.password });
|
|
259
|
+
const cookie = people.cookieFor(person);
|
|
260
|
+
log(`${person.name} ${link.kind === 'reset' ? 'chose a new password' : link.kind === 'setup' ? 'set up editing' : 'joined'}.`);
|
|
261
|
+
return go(res, '/', { 'Set-Cookie': cookieHeader(req, cookie.value, cookie.maxAge) });
|
|
262
|
+
} catch (err) {
|
|
263
|
+
if (!(err instanceof VersoError)) throw err;
|
|
264
|
+
return page(res, 400, joinPage({ site, link, token, error: err.message, values: { name: form.name, email: form.email } }));
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (p === '/edit') {
|
|
269
|
+
const to = local(post ? null : url.searchParams.get('to'));
|
|
270
|
+
if (me && !post) return go(res, to);
|
|
271
|
+
if (!people.any()) return page(res, 200, notSetUpPage({ site }));
|
|
272
|
+
if (!post) return page(res, 200, signInPage({ site, to: to === '/' ? '' : to }));
|
|
273
|
+
const form = await readForm(req);
|
|
274
|
+
try {
|
|
275
|
+
const person = await people.signIn(form.email, form.password, ip(req));
|
|
276
|
+
const cookie = people.cookieFor(person);
|
|
277
|
+
return go(res, local(form.to), { 'Set-Cookie': cookieHeader(req, cookie.value, cookie.maxAge) });
|
|
278
|
+
} catch (err) {
|
|
279
|
+
if (!(err instanceof VersoError)) throw err;
|
|
280
|
+
return page(res, /Too many/.test(err.message) ? 429 : 401, signInPage({ site, error: err.message, email: form.email, to: form.to }));
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return go(res, '/edit');
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
// ════ The gate ════
|
|
287
|
+
// Every request passes through here first. It answers the ones that
|
|
288
|
+
// aren't for the editor, and says who's asking for the ones that are.
|
|
289
|
+
const gate = async (req, res, url) => {
|
|
290
|
+
const p = url.pathname;
|
|
291
|
+
if (p === '/edit' || p.startsWith('/edit/')) { await door(req, res, url); return { done: true }; }
|
|
292
|
+
const me = who(req);
|
|
293
|
+
const reading = req.method === 'GET' || req.method === 'HEAD';
|
|
294
|
+
|
|
295
|
+
if (p.startsWith('/__verso/')) {
|
|
296
|
+
if (OPEN.has(p) && reading) return { me: null };
|
|
297
|
+
if (!me) { json(res, 401, { ok: false, signIn: true, message: 'You\'ve been signed out. Sign in again to keep editing.' }); return { done: true }; }
|
|
298
|
+
if (!reading && !sameOrigin(req)) { json(res, 403, { ok: false, message: 'That request didn\'t come from this site, so it was refused.' }); return { done: true }; }
|
|
299
|
+
if (!reading && me.role !== 'owner' && OWNER_ONLY.some((r) => r.test(p))) {
|
|
300
|
+
json(res, 403, { ok: false, message: 'Only an owner of this site can change that.' });
|
|
301
|
+
return { done: true };
|
|
302
|
+
}
|
|
303
|
+
} else if (!me) {
|
|
304
|
+
if (!reading) { res.writeHead(405, { Allow: 'GET, HEAD' }); res.end(); return { done: true }; }
|
|
305
|
+
serveLive(req, res, p);
|
|
306
|
+
return { done: true };
|
|
307
|
+
}
|
|
308
|
+
if (me?.renew) {
|
|
309
|
+
const cookie = people.cookieFor(me);
|
|
310
|
+
res.setHeader('Set-Cookie', cookieHeader(req, cookie.value, cookie.maxAge));
|
|
311
|
+
}
|
|
312
|
+
return { me };
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
// ════ Starting ════
|
|
316
|
+
// Rebuild the published pages when that can't publish anything by
|
|
317
|
+
// accident: there are none yet, or nothing is waiting to be published.
|
|
318
|
+
const waiting = state.changed.length > 0;
|
|
319
|
+
if (!fs.existsSync(liveDir) || !waiting) {
|
|
320
|
+
const built = await rebuild();
|
|
321
|
+
if (!built.ok) log(`\x1b[31m${formatError(built.error)}\x1b[0m\n The published pages couldn't be built, so ${fs.existsSync(liveDir) ? 'the last good ones are being shown' : 'visitors will see nothing yet'}. Fix this in the editor and publish.`);
|
|
322
|
+
else if (waiting) log('Nothing had been published here yet, so visitors see the site as it is now. Some of it is still waiting for its first Publish.');
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
return {
|
|
326
|
+
people, gate, rebuild, liveDir, record, first,
|
|
327
|
+
get liveError() { return liveError; },
|
|
328
|
+
setupLink: () => people.setupLink(),
|
|
329
|
+
// A fresh session cookie for someone, as a Set-Cookie header.
|
|
330
|
+
cookie: (req, person) => { const c = people.cookieFor(person); return cookieHeader(req, c.value, c.maxAge); },
|
|
331
|
+
// The site's address, for links to send: wherever the person asking is
|
|
332
|
+
// using it right now, which is the one address known to work.
|
|
333
|
+
address: (req) => `${secure(req) ? 'https' : 'http'}://${String(req.headers['x-forwarded-host'] || '').split(',')[0].trim() || req.headers.host}`,
|
|
334
|
+
status: async () => {
|
|
335
|
+
const s = await gitState(root);
|
|
336
|
+
return { since: record.first, starts: record.starts, remote: s.remote ? (await git(root, ['remote', 'get-url', s.remote])).stdout.trim().replace(/\/\/[^@/]+@/, '//') : '' };
|
|
337
|
+
},
|
|
338
|
+
};
|
|
339
|
+
}
|
package/src/build.js
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
// verso build: the static site, in dist/.
|
|
2
|
+
|
|
3
|
+
import fs from 'fs';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
import { loadSite, assertSite, pageImages } from './site.js';
|
|
6
|
+
import { renderPage, setColors, splitPages, pagedUrl, escapeHtml, escapeAttr } from './template.js';
|
|
7
|
+
import { loadElevate, compileCSS } from './elevate.js';
|
|
8
|
+
import { imageSize, resizedCopies, addSrcset } from './images.js';
|
|
9
|
+
import { VersoErrors, formatError } from './errors.js';
|
|
10
|
+
|
|
11
|
+
export const richClassList = (config) =>
|
|
12
|
+
Object.entries(config.rich || {}).map(([tag, classes]) => ({ classes, where: `"rich": { "${tag}": … }` }));
|
|
13
|
+
|
|
14
|
+
// Class strings in parts/, so Elevate compiles them even when its Watch list
|
|
15
|
+
// doesn't name the folder.
|
|
16
|
+
export const partClassList = (root) => {
|
|
17
|
+
const dir = path.join(root, 'parts');
|
|
18
|
+
if (!fs.existsSync(dir)) return [];
|
|
19
|
+
return fs.readdirSync(dir).filter((f) => f.endsWith('.html')).flatMap((f) => {
|
|
20
|
+
const text = fs.readFileSync(path.join(dir, f), 'utf8');
|
|
21
|
+
return [...text.matchAll(/\bclass\s*=\s*"([^"{}]*)"/g)].map((m) => ({ classes: m[1], file: `parts/${f}`, line: text.slice(0, m.index).split('\n').length, where: `parts/${f}` }));
|
|
22
|
+
});
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const live = (site) => site.pages.filter((p) => !p.draft && p.url !== '/404/');
|
|
26
|
+
const plainText = (html) => String(html || '').replace(/<pre\b[^>]*>[\s\S]*?<\/pre>/g, ' ').replace(/<[^>]*>/g, ' ').replace(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/\s+/g, ' ').trim();
|
|
27
|
+
|
|
28
|
+
// A search index: every live page with its words, as plain text. Written as
|
|
29
|
+
// pages.json when verso.json has "index": true.
|
|
30
|
+
export function searchIndex(site) {
|
|
31
|
+
if (!site.config.index) return null;
|
|
32
|
+
return JSON.stringify(live(site).map((p) => ({
|
|
33
|
+
url: `${site.config.base || ''}${p.url}`,
|
|
34
|
+
title: p.title || p.label,
|
|
35
|
+
label: p.label,
|
|
36
|
+
description: p.description,
|
|
37
|
+
date: p.date || '',
|
|
38
|
+
tags: p.tags || [],
|
|
39
|
+
headings: Object.values(p.rich || {}).flatMap((h) => [...String(h).matchAll(/<h[234]\b[^>]*>([\s\S]*?)<\/h[234]>/g)].map((m) => plainText(m[1]))),
|
|
40
|
+
text: plainText([...Object.values(p.fields || {}).filter((v) => typeof v === 'string'), ...Object.values(p.rich || {})].join(' ')).slice(0, 20000),
|
|
41
|
+
})));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// A sitemap, once verso.json says where the site lives.
|
|
45
|
+
export function sitemap(site) {
|
|
46
|
+
if (!site.config.url) return null;
|
|
47
|
+
const urls = [...live(site), ...(site.tagPages || [])].map((p) => ` <url><loc>${site.config.url}${site.config.base || ''}${p.url}</loc>${p.date ? `<lastmod>${p.date}</lastmod>` : ''}</url>`);
|
|
48
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.join('\n')}\n</urlset>\n`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function buildSite(root, { out = 'dist' } = {}) {
|
|
52
|
+
const started = Date.now();
|
|
53
|
+
const site = loadSite(root);
|
|
54
|
+
const notes = assertSite(site);
|
|
55
|
+
|
|
56
|
+
const elevate = await loadElevate(root);
|
|
57
|
+
setColors(elevate.describe().tokens.ColorToken);
|
|
58
|
+
const css = await compileCSS(elevate, [...richClassList(site.config), ...partClassList(root)]);
|
|
59
|
+
if (!css.ok) throw new VersoErrors([css.error]);
|
|
60
|
+
|
|
61
|
+
const dist = path.join(root, out);
|
|
62
|
+
fs.rmSync(dist, { recursive: true, force: true });
|
|
63
|
+
fs.mkdirSync(dist, { recursive: true });
|
|
64
|
+
|
|
65
|
+
const publicDir = path.join(root, 'public');
|
|
66
|
+
if (fs.existsSync(publicDir)) fs.cpSync(publicDir, dist, { recursive: true });
|
|
67
|
+
|
|
68
|
+
const live = site.pages.filter((page) => !page.draft);
|
|
69
|
+
const warnings = [...css.warnings, ...notes.map((n) => formatError(n))];
|
|
70
|
+
const folderFor = (page) => path.join(dist, ...page.url.split('/').filter(Boolean));
|
|
71
|
+
|
|
72
|
+
// Images first: each page's images, with smaller copies of wide ones. The
|
|
73
|
+
// addresses are collected so any page that shows an image (a list of posts
|
|
74
|
+
// showing their covers, say) gets the srcset too.
|
|
75
|
+
const copies = new Map();
|
|
76
|
+
const cacheDir = path.join(root, '.verso-cache', 'images');
|
|
77
|
+
for (const page of live) {
|
|
78
|
+
const folder = folderFor(page);
|
|
79
|
+
fs.mkdirSync(folder, { recursive: true });
|
|
80
|
+
const files = pageImages(page.dir);
|
|
81
|
+
for (const f of files) {
|
|
82
|
+
fs.copyFileSync(path.join(page.dir, f), path.join(folder, f));
|
|
83
|
+
const made = await resizedCopies(path.join(page.dir, f), folder, f, { cacheDir, taken: files, warn: (w) => warnings.push(w) });
|
|
84
|
+
if (made.length) {
|
|
85
|
+
const size = imageSize(page, f);
|
|
86
|
+
const url = (name) => `${page.url}${encodeURIComponent(name)}`;
|
|
87
|
+
copies.set(url(f), [...made.map((m) => `${url(m.file)} ${m.width}w`), `${url(f)} ${size.width}w`].join(', '));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Every page, every tag page, and every page of a split list.
|
|
93
|
+
const feeds = channelFeeds(site);
|
|
94
|
+
const written = [];
|
|
95
|
+
let listPages = 0;
|
|
96
|
+
[...live, ...site.tagPages].forEach((page) => {
|
|
97
|
+
const template = site.templates.get(page.template);
|
|
98
|
+
const options = { mode: 'build', siteName: site.config.name, pages: live, rich: site.config.rich, locale: site.config.locale, imageSize, blocks: site.blocks, feed: feedFor(feeds, page.url) };
|
|
99
|
+
const total = splitPages(template, page, live, site.blocks, site.siteData, { locale: site.config.locale });
|
|
100
|
+
listPages += total - 1;
|
|
101
|
+
for (let n = 1; n <= total; n++) {
|
|
102
|
+
const url = pagedUrl(page.url, n);
|
|
103
|
+
const html = renderPage(template, page, { ...options, paging: { number: n } });
|
|
104
|
+
const folder = path.join(dist, ...url.split('/').filter(Boolean));
|
|
105
|
+
fs.mkdirSync(folder, { recursive: true });
|
|
106
|
+
fs.writeFileSync(path.join(folder, 'index.html'), addSrcset(html, copies), 'utf8');
|
|
107
|
+
written.push(path.join(folder, 'index.html'));
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
// Addresses in the CSS (fonts, background pictures) are written from the
|
|
111
|
+
// stylesheet's own place, so they work when the site lives in a sub-folder.
|
|
112
|
+
fs.writeFileSync(path.join(dist, 'elevate.css'), css.css.replace(/url\((['"]?)\/(?!\/)/g, 'url($1'), 'utf8');
|
|
113
|
+
|
|
114
|
+
// Hosts show /404.html for missing pages; content/404/ makes one.
|
|
115
|
+
const notFound = path.join(dist, '404', 'index.html');
|
|
116
|
+
if (fs.existsSync(notFound)) fs.copyFileSync(notFound, path.join(dist, '404.html'));
|
|
117
|
+
|
|
118
|
+
const index = searchIndex(site);
|
|
119
|
+
if (index) fs.writeFileSync(path.join(dist, 'pages.json'), index, 'utf8');
|
|
120
|
+
const map = sitemap(site);
|
|
121
|
+
if (map) fs.writeFileSync(path.join(dist, 'sitemap.xml'), map, 'utf8');
|
|
122
|
+
feeds.forEach((f) => {
|
|
123
|
+
const folder = path.join(dist, ...f.folder.split('/'));
|
|
124
|
+
fs.mkdirSync(folder, { recursive: true });
|
|
125
|
+
fs.writeFileSync(path.join(folder, 'feed.xml'), rss(site, f), 'utf8');
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
// A site that lives in a sub-folder: every address that starts at the
|
|
129
|
+
// root gets the folder in front.
|
|
130
|
+
if (site.config.base) {
|
|
131
|
+
[...written, path.join(dist, '404.html')].filter((f) => fs.existsSync(f)).forEach((f) => {
|
|
132
|
+
fs.writeFileSync(f, withBase(fs.readFileSync(f, 'utf8'), site.config.base), 'utf8');
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return { pages: live.length, tagPages: site.tagPages.length, listPages, drafts: site.pages.length - live.length, out, ms: Date.now() - started, warnings };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ════ Feeds ════
|
|
140
|
+
// Each channel in verso.json gets an RSS feed at /<folder>/feed.xml, once
|
|
141
|
+
// verso.json has the site's "url".
|
|
142
|
+
export function channelFeeds(site) {
|
|
143
|
+
if (!site.config.url) return [];
|
|
144
|
+
return Object.entries(site.config.channels || {}).map(([folder, c]) => ({
|
|
145
|
+
folder: folder.replace(/^\/+|\/+$/g, ''),
|
|
146
|
+
title: `${(c && c.label) || folder} — ${site.config.name}`,
|
|
147
|
+
})).map((f) => ({ ...f, url: `/${f.folder}/feed.xml` }));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export const feedFor = (feeds, url) => feeds.find((f) => url === `/${f.folder}/` || url.startsWith(`/${f.folder}/`)) || null;
|
|
151
|
+
|
|
152
|
+
const rfc822 = (iso) => (iso ? new Date(`${iso}T12:00:00Z`).toUTCString() : '');
|
|
153
|
+
const xml = (v) => escapeHtml(String(v ?? ''));
|
|
154
|
+
|
|
155
|
+
export function rss(site, feed) {
|
|
156
|
+
const home = `${site.config.url}${site.config.base || ''}`;
|
|
157
|
+
const prefix = `/${feed.folder}/`;
|
|
158
|
+
const depth = prefix.split('/').filter(Boolean).length + 1;
|
|
159
|
+
const items = site.pages
|
|
160
|
+
.filter((p) => !p.draft && !p.tagsOf && p.url.startsWith(prefix) && p.url.split('/').filter(Boolean).length === depth)
|
|
161
|
+
.sort((a, b) => (b.date || '').localeCompare(a.date || ''))
|
|
162
|
+
.slice(0, 30);
|
|
163
|
+
// Feed readers need full addresses: /x becomes https://site/x, and an image
|
|
164
|
+
// kept beside the page (src="photo.jpg") gets the page's address.
|
|
165
|
+
const absolute = (html, pageUrl) => String(html)
|
|
166
|
+
.replace(/(\s(?:src|href))="\/(?!\/)/g, `$1="${home}/`)
|
|
167
|
+
.replace(/(\ssrc)="(?![a-z][a-z0-9+.-]*:|\/|#)([^"]+)"/gi, (m, attr, file) => `${attr}="${home}${pageUrl}${file}"`);
|
|
168
|
+
const entry = (p) => {
|
|
169
|
+
const body = p.rich?.body ?? Object.values(p.rich || {})[0];
|
|
170
|
+
const link = `${home}${p.url}`;
|
|
171
|
+
return [
|
|
172
|
+
' <item>',
|
|
173
|
+
` <title>${xml(p.title || p.label)}</title>`,
|
|
174
|
+
` <link>${xml(link)}</link>`,
|
|
175
|
+
` <guid>${xml(link)}</guid>`,
|
|
176
|
+
p.date ? ` <pubDate>${rfc822(p.date)}</pubDate>` : '',
|
|
177
|
+
p.description ? ` <description>${xml(p.description)}</description>` : '',
|
|
178
|
+
body ? ` <content:encoded><![CDATA[${absolute(body, p.url).replace(/]]>/g, ']]]]><![CDATA[>')}]]></content:encoded>` : '',
|
|
179
|
+
...(p.tags || []).map((t) => ` <category>${xml(t)}</category>`),
|
|
180
|
+
' </item>',
|
|
181
|
+
].filter(Boolean).join('\n');
|
|
182
|
+
};
|
|
183
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
184
|
+
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom">
|
|
185
|
+
<channel>
|
|
186
|
+
<title>${xml(feed.title)}</title>
|
|
187
|
+
<link>${xml(`${home}${prefix}`)}</link>
|
|
188
|
+
<description>${xml(feed.title)}</description>
|
|
189
|
+
<atom:link href="${xml(`${home}${feed.url}`)}" rel="self" type="application/rss+xml"/>
|
|
190
|
+
${items.map(entry).join('\n')}
|
|
191
|
+
</channel>
|
|
192
|
+
</rss>
|
|
193
|
+
`;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ════ Sub-folder hosting ════
|
|
197
|
+
// href, src, srcset and action addresses that start at the root get the base
|
|
198
|
+
// in front. Code samples are left as written, and <html> carries
|
|
199
|
+
// data-base so scripts can build addresses too.
|
|
200
|
+
export function withBase(html, base) {
|
|
201
|
+
const fix = (u) => (u.startsWith('/') && !u.startsWith('//') && !u.startsWith(`${base}/`) ? `${base}${u}` : u);
|
|
202
|
+
const parts = String(html).split(/(<pre\b[\s\S]*?<\/pre>|<code\b[\s\S]*?<\/code>|<script type="application\/json"[\s\S]*?<\/script>)/);
|
|
203
|
+
for (let i = 0; i < parts.length; i += 2) {
|
|
204
|
+
parts[i] = parts[i]
|
|
205
|
+
.replace(/(\s(?:href|src|action|poster))="([^"]*)"/g, (m, attr, u) => `${attr}="${fix(u)}"`)
|
|
206
|
+
.replace(/\ssrcset="([^"]*)"/g, (m, set) => ` srcset="${set.split(',').map((c) => { const [u, ...rest] = c.trim().split(/\s+/); return [fix(u), ...rest].join(' '); }).join(', ')}"`)
|
|
207
|
+
.replace(/<html\b/i, `<html data-base="${escapeAttr(base)}"`);
|
|
208
|
+
}
|
|
209
|
+
return parts.join('');
|
|
210
|
+
}
|