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.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +168 -2
  3. package/bin/verso.js +16 -0
  4. package/editor/door.js +139 -0
  5. package/editor/editor.js +1880 -0
  6. package/editor/elevate.css +2158 -0
  7. package/editor/ext-attrs.js +87 -0
  8. package/editor/ext-blocks.js +422 -0
  9. package/editor/ext-builder.js +819 -0
  10. package/editor/ext-channels.js +574 -0
  11. package/editor/ext-components.js +160 -0
  12. package/editor/ext-history.js +242 -0
  13. package/editor/ext-palette.js +307 -0
  14. package/editor/ext-people.js +345 -0
  15. package/editor/ext-repeaters.js +143 -0
  16. package/editor/ext-screens.js +94 -0
  17. package/editor/ext-site-settings.js +318 -0
  18. package/editor/ext-site-view.js +632 -0
  19. package/editor/ext-tokens.js +1195 -0
  20. package/editor/new-page.js +252 -0
  21. package/editor/rich.js +23 -0
  22. package/package.json +69 -4
  23. package/src/blocks.js +269 -0
  24. package/src/box.js +339 -0
  25. package/src/build.js +210 -0
  26. package/src/cli.js +161 -0
  27. package/src/color.js +137 -0
  28. package/src/components.js +223 -0
  29. package/src/elevate.js +74 -0
  30. package/src/errors.js +46 -0
  31. package/src/extensions/README.md +70 -0
  32. package/src/extensions/blocks.js +294 -0
  33. package/src/extensions/builder.js +734 -0
  34. package/src/extensions/channels.js +341 -0
  35. package/src/extensions/components.js +141 -0
  36. package/src/extensions/history.js +169 -0
  37. package/src/extensions/palette.js +31 -0
  38. package/src/extensions/people.js +113 -0
  39. package/src/extensions/site-settings.js +251 -0
  40. package/src/extensions/site-view.js +381 -0
  41. package/src/extensions/tags.js +15 -0
  42. package/src/extensions/tokens.js +587 -0
  43. package/src/fonts.js +139 -0
  44. package/src/git.js +419 -0
  45. package/src/html-edit.js +942 -0
  46. package/src/images.js +116 -0
  47. package/src/people.js +286 -0
  48. package/src/rich.js +124 -0
  49. package/src/scaffold.js +185 -0
  50. package/src/screens.js +65 -0
  51. package/src/server.js +693 -0
  52. package/src/site.js +618 -0
  53. package/src/template.js +915 -0
  54. package/src/video.js +29 -0
  55. package/starter/Dockerfile +20 -0
  56. package/starter/README.md +49 -0
  57. package/starter/blocks/call-to-action.html +6 -0
  58. package/starter/blocks/features.html +15 -0
  59. package/starter/blocks/hero.html +8 -0
  60. package/starter/blocks/image-and-text.html +8 -0
  61. package/starter/blocks/latest-posts.html +20 -0
  62. package/starter/blocks/post-index.html +30 -0
  63. package/starter/blocks/quote.html +9 -0
  64. package/starter/blocks/site-footer.html +8 -0
  65. package/starter/blocks/site-nav.html +8 -0
  66. package/starter/blocks/tag-list.html +10 -0
  67. package/starter/blocks/tagged-posts.html +19 -0
  68. package/starter/blocks/team.html +15 -0
  69. package/starter/blocks/text.html +4 -0
  70. package/starter/content/404/page.json +21 -0
  71. package/starter/content/about/page.json +65 -0
  72. package/starter/content/journal/designing-for-the-morning-shift/body.html +22 -0
  73. package/starter/content/journal/designing-for-the-morning-shift/checklist.jpg +0 -0
  74. package/starter/content/journal/designing-for-the-morning-shift/cover.jpg +0 -0
  75. package/starter/content/journal/designing-for-the-morning-shift/page.json +17 -0
  76. package/starter/content/journal/page.json +19 -0
  77. package/starter/content/journal/the-first-week/body.html +17 -0
  78. package/starter/content/journal/the-first-week/cover.jpg +0 -0
  79. package/starter/content/journal/the-first-week/page.json +17 -0
  80. package/starter/content/journal/the-first-week/wall-of-cards.jpg +0 -0
  81. package/starter/content/page.json +94 -0
  82. package/starter/content/site.json +88 -0
  83. package/starter/content/studio-table.jpg +0 -0
  84. package/starter/content/topics/page.json +27 -0
  85. package/starter/dockerignore +5 -0
  86. package/starter/elevate/config/design.ts +30 -0
  87. package/starter/elevate/config/elevate.ts +16 -0
  88. package/starter/elevate/config/syntax.ts +6 -0
  89. package/starter/elevate/design/site.ts +9 -0
  90. package/starter/elevate/design/tokens.json +20 -0
  91. package/starter/elevate/extend/fonts.css +1 -0
  92. package/starter/gitignore +6 -0
  93. package/starter/netlify.toml +5 -0
  94. package/starter/parts/.gitkeep +0 -0
  95. package/starter/public/favicon.svg +1 -0
  96. package/starter/templates/page.html +20 -0
  97. package/starter/templates/page.layout.json +23 -0
  98. package/starter/templates/post.html +65 -0
  99. package/starter/verso.defaults.json +33 -0
  100. package/starter-blank/blocks/site-footer.html +3 -0
  101. package/starter-blank/blocks/site-nav.html +8 -0
  102. package/starter-blank/blocks/text.html +4 -0
  103. package/starter-blank/content/404/page.json +18 -0
  104. package/starter-blank/content/page.json +18 -0
  105. package/starter-blank/content/site.json +36 -0
  106. package/starter-blank/elevate/design/tokens.json +10 -0
  107. package/starter-blank/templates/page.html +17 -0
  108. package/starter-blank/verso.defaults.json +26 -0
@@ -0,0 +1,587 @@
1
+ // Design tokens, edited visually. The site's own tokens live in
2
+ // elevate/design/tokens.json, one map per Elevate token type, which
3
+ // elevate/config/design.ts spreads after Elevate's defaults. Fonts go in
4
+ // public/fonts/ with their @font-face rules in elevate/extend/fonts.css.
5
+
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+ import { loadElevate } from '../elevate.js';
9
+ import { VersoError } from '../errors.js';
10
+ import { ramp, rampReport, fluid, parseHex } from '../color.js';
11
+ import { fontAxes, fontFacts } from '../fonts.js';
12
+ import { PICKERS, applyPick, currentPick } from '../html-edit.js';
13
+ import { DEFAULT_LABELS, SCREEN_NAME, SCREEN_WIDTH, widthPx, readScreenLabels, screensFor, usesScreen, dropScreen } from '../screens.js';
14
+
15
+ // Text styles: how rich text looks, kept as classes in verso.json "rich".
16
+ // The elements, in the words the panel uses, in the order it lists them.
17
+ export const TEXT_STYLES = [
18
+ ['p', 'Paragraphs', 'Text'],
19
+ ['h2', 'Large headings', 'Text'],
20
+ ['h3', 'Medium headings', 'Text'],
21
+ ['h4', 'Small headings', 'Text'],
22
+ ['a', 'Links', 'Text'],
23
+ ['strong', 'Bold text', 'Text'],
24
+ ['em', 'Italic text', 'Text'],
25
+ ['ul', 'Bulleted lists', 'Lists'],
26
+ ['ol', 'Numbered lists', 'Lists'],
27
+ ['li', 'List items', 'Lists'],
28
+ ['blockquote', 'Quotes', 'Blocks of text'],
29
+ ['aside', 'Callouts', 'Blocks of text'],
30
+ ['code', 'Inline code', 'Code'],
31
+ ['pre', 'Code blocks', 'Code'],
32
+ ['pre code', 'Code inside code blocks', 'Code'],
33
+ ['figure', 'Figures', 'Pictures and video'],
34
+ ['img', 'Images', 'Pictures and video'],
35
+ ['figcaption', 'Captions', 'Pictures and video'],
36
+ ['iframe', 'Videos', 'Pictures and video'],
37
+ ['table', 'Tables', 'Tables'],
38
+ ['tr', 'Table rows', 'Tables'],
39
+ ['th', 'Table headings', 'Tables'],
40
+ ['td', 'Table cells', 'Tables'],
41
+ ];
42
+ // The pickers a text style offers. Spacing above and below are their own,
43
+ // added here if the shared picker list doesn't have them yet.
44
+ PICKERS['margin-top'] = PICKERS['margin-top'] || { prop: 'mg-t', type: 'SpacingToken' };
45
+ PICKERS['margin-bottom'] = PICKERS['margin-bottom'] || { prop: 'mg-b', type: 'SpacingToken' };
46
+ const STYLE_PICKERS = ['family', 'size', 'weight', 'text-color', 'leading', 'margin-top', 'margin-bottom', 'background', 'padding', 'radius'];
47
+
48
+ const TYPES = ['ColorToken', 'FontSizeToken', 'FontFamilyToken', 'SpacingToken', 'ShadowToken', 'GradientToken'];
49
+ const NAME = /^[a-z][a-z0-9-]*(\+[1-4])?$/;
50
+ const TOKENS_FILE = 'elevate/design/tokens.json';
51
+ const FONTS_CSS = 'elevate/extend/fonts.css';
52
+
53
+ const FONT_KINDS = { wOF2: 'woff2', wOFF: 'woff', OTTO: 'otf' };
54
+ const sniffFont = (b) => {
55
+ if (b.length < 4) return null;
56
+ const tag = b.slice(0, 4).toString('latin1');
57
+ if (FONT_KINDS[tag]) return FONT_KINDS[tag];
58
+ if (tag === 'true' || (b[0] === 0 && b[1] === 1 && b[2] === 0 && b[3] === 0)) return 'ttf';
59
+ return null;
60
+ };
61
+ const FONT_FORMAT = { woff2: 'woff2', woff: 'woff', otf: 'opentype', ttf: 'truetype' };
62
+
63
+ const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
64
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
65
+
66
+ // Where a file is, in the words the editor uses: "block" Hero, "page type" Post.
67
+ const words = (s) => s.replace(/[-_]+/g, ' ').replace(/^./, (c) => c.toUpperCase());
68
+ function placeOf(file) {
69
+ const m = /^(blocks|templates|parts|components)\/(.+)\.(html|json)$/.exec(file);
70
+ if (!m) return { group: 'file', label: file };
71
+ const group = { blocks: 'block', templates: 'page type', parts: 'shared part', components: 'component' }[m[1]];
72
+ return { group, label: words(m[2].split('/').pop()) };
73
+ }
74
+
75
+ // Every file whose class strings can use a token.
76
+ function classFiles(root) {
77
+ const out = [];
78
+ const walk = (dir) => {
79
+ if (!fs.existsSync(dir)) return;
80
+ fs.readdirSync(dir, { withFileTypes: true }).forEach((e) => {
81
+ if (e.name.startsWith('.') || e.name === 'node_modules') return;
82
+ const full = path.join(dir, e.name);
83
+ if (e.isDirectory()) walk(full);
84
+ else if (e.name.endsWith('.html')) out.push(full);
85
+ });
86
+ };
87
+ walk(path.join(root, 'templates'));
88
+ walk(path.join(root, 'blocks'));
89
+ walk(path.join(root, 'components'));
90
+ return out;
91
+ }
92
+
93
+ const CLASS_ATTR = /\bclass\s*=\s*(["'])([^"']*)\1/g;
94
+
95
+ export async function setup(ctx) {
96
+ const { root } = ctx;
97
+ const rel = (p) => path.relative(root, p).split(path.sep).join('/');
98
+ const tokensPath = path.join(root, TOKENS_FILE);
99
+
100
+ const readTokens = () => {
101
+ if (!fs.existsSync(tokensPath)) return {};
102
+ try {
103
+ return JSON.parse(fs.readFileSync(tokensPath, 'utf8'));
104
+ } catch {
105
+ throw new VersoError(`${TOKENS_FILE} isn't valid JSON, so the design tokens can't be changed.`, { file: TOKENS_FILE });
106
+ }
107
+ };
108
+
109
+ const designLoadsTokens = () => {
110
+ const design = path.join(root, 'elevate/config/design.ts');
111
+ return fs.existsSync(design) && /design\/tokens\.json/.test(fs.readFileSync(design, 'utf8'));
112
+ };
113
+
114
+ // Writes a file Verso changed itself, so the watcher doesn't reload the
115
+ // page; Verso recompiles and tells the editor to swap the stylesheet.
116
+ const write = (file, text) => {
117
+ fs.mkdirSync(path.dirname(file), { recursive: true });
118
+ fs.writeFileSync(file, text, 'utf8');
119
+ ctx.written.set(rel(file), ctx.hash(Buffer.from(text, 'utf8')));
120
+ };
121
+
122
+ const writeTokens = async (tokens) => {
123
+ if (!designLoadsTokens()) {
124
+ throw new VersoError('This site\'s Elevate settings don\'t load the design tokens file yet.', {
125
+ file: 'elevate/config/design.ts',
126
+ hint: 'Add `import tokens from "../design/tokens.json";` and spread `...tokens.ColorToken` (and the other types) into each map.',
127
+ });
128
+ }
129
+ const clean = {};
130
+ [...TYPES, 'BreakPointToken'].forEach((t) => { if (tokens[t] && Object.keys(tokens[t]).length) clean[t] = tokens[t]; });
131
+ write(tokensPath, JSON.stringify(clean, null, 2) + '\n');
132
+ await ctx.compile({ reload: true });
133
+ ctx.broadcast({ type: 'css' });
134
+ return ctx.cssError ? (ctx.cssError.toJSON ? ctx.cssError.toJSON() : { message: ctx.cssError.message }) : null;
135
+ };
136
+
137
+ const describe = async () => (await loadElevate(root)).describe();
138
+
139
+ // ── Screen sizes ──
140
+ // Sites made before Verso could edit screen sizes read Elevate's defaults
141
+ // in design.ts; the line is changed to read tokens.json first.
142
+ const designPath = path.join(root, 'elevate/config/design.ts');
143
+ const designLoadsScreens = () => fs.existsSync(designPath) && /tokens\.BreakPointToken/.test(fs.readFileSync(designPath, 'utf8'));
144
+ const letDesignLoadScreens = () => {
145
+ if (designLoadsScreens()) return;
146
+ const text = fs.existsSync(designPath) ? fs.readFileSync(designPath, 'utf8') : '';
147
+ const next = text.replace(/BreakPointToken:\s*breakpoints\s*,/, 'BreakPointToken: tokens.BreakPointToken ?? breakpoints,');
148
+ if (next === text || !designLoadsTokens()) {
149
+ throw new VersoError('This site\'s Elevate settings set the screen sizes themselves, so Verso can\'t change them.', {
150
+ file: 'elevate/config/design.ts',
151
+ hint: 'Make the BreakPointToken line read `BreakPointToken: tokens.BreakPointToken ?? breakpoints,`.',
152
+ });
153
+ }
154
+ write(designPath, next);
155
+ };
156
+ // Where each screen size is used: class strings with its /name/ marker.
157
+ const screenUsage = (name) => {
158
+ const found = [];
159
+ classFiles(root).forEach((file) => {
160
+ const text = fs.readFileSync(file, 'utf8');
161
+ for (const m of text.matchAll(CLASS_ATTR)) {
162
+ if (usesScreen(m[2], name)) found.push({ file: rel(file), line: text.slice(0, m.index).split('\n').length, classes: m[2].trim(), ...placeOf(rel(file)) });
163
+ }
164
+ });
165
+ if (fs.existsSync(versoPath)) {
166
+ const config = JSON.parse(fs.readFileSync(versoPath, 'utf8'));
167
+ Object.entries(config.rich || {}).forEach(([tag, classes]) => {
168
+ if (usesScreen(classes, name)) found.push({ file: 'verso.json', line: null, classes, where: `rich text <${tag}>`, group: 'article text', label: (TEXT_STYLES.find(([t]) => t === tag) || [tag, tag])[1] });
169
+ });
170
+ }
171
+ return found;
172
+ };
173
+ // Takes a screen size out of every class string, with its classes.
174
+ const dropScreenEverywhere = (name) => {
175
+ const changed = [];
176
+ classFiles(root).forEach((file) => {
177
+ const text = fs.readFileSync(file, 'utf8');
178
+ const next = text.replace(CLASS_ATTR, (whole, q, classes) => (usesScreen(classes, name) ? whole.replace(classes, dropScreen(classes, name)) : whole));
179
+ if (next !== text) { write(file, next); changed.push(rel(file)); }
180
+ });
181
+ if (fs.existsSync(versoPath)) {
182
+ const config = JSON.parse(fs.readFileSync(versoPath, 'utf8'));
183
+ let touched = false;
184
+ Object.keys(config.rich || {}).forEach((tag) => {
185
+ if (usesScreen(config.rich[tag], name)) { config.rich[tag] = dropScreen(config.rich[tag], name); touched = true; }
186
+ });
187
+ if (touched) { write(versoPath, JSON.stringify(config, null, 2) + '\n'); changed.push('verso.json'); }
188
+ }
189
+ return changed;
190
+ };
191
+ const writeScreenLabels = (labels) => {
192
+ const config = readConfigFile();
193
+ const keep = Object.fromEntries(Object.entries(labels).filter(([n, l]) => l && l !== DEFAULT_LABELS[n]));
194
+ if (Object.keys(keep).length) config.screens = keep; else delete config.screens;
195
+ write(versoPath, JSON.stringify(config, null, 2) + '\n');
196
+ };
197
+ const screensReport = (d) => screensFor(d.breakpoints, readScreenLabels(root)).map((s) => ({ ...s, used: screenUsage(s.name).length }));
198
+
199
+ // Prefix keys like "round-" or "from-": a token can follow them.
200
+ const prefixes = (d) => {
201
+ const set = new Set();
202
+ Object.values(d.rules).forEach((r) => Object.keys(r).forEach((k) => { if (k.endsWith('-')) set.add(k); }));
203
+ return [...set];
204
+ };
205
+
206
+ // A pattern for one token name used as a modifier inside a class string.
207
+ const modifierPattern = (name, pre) =>
208
+ new RegExp(`(^|[\\s:_\\[])((?:${pre.map(escapeRe).join('|') || '(?!)'})?)${escapeRe(name)}(?=$|[\\s:_\\]])`, 'g');
209
+
210
+ const usage = async (name, d) => {
211
+ d = d || (await describe());
212
+ const re = modifierPattern(name, prefixes(d));
213
+ const found = [];
214
+ classFiles(root).forEach((file) => {
215
+ const text = fs.readFileSync(file, 'utf8');
216
+ for (const m of text.matchAll(CLASS_ATTR)) {
217
+ re.lastIndex = 0;
218
+ if (re.test(m[2])) {
219
+ const line = text.slice(0, m.index).split('\n').length;
220
+ found.push({ file: rel(file), line, classes: m[2].trim(), ...placeOf(rel(file)) });
221
+ }
222
+ }
223
+ });
224
+ const versoPath = path.join(root, 'verso.json');
225
+ if (fs.existsSync(versoPath)) {
226
+ const config = JSON.parse(fs.readFileSync(versoPath, 'utf8'));
227
+ Object.entries(config.rich || {}).forEach(([tag, classes]) => {
228
+ re.lastIndex = 0;
229
+ if (re.test(classes)) found.push({ file: 'verso.json', line: null, classes, where: `rich text <${tag}>`, group: 'article text', label: (TEXT_STYLES.find(([t]) => t === tag) || [tag, tag])[1] });
230
+ });
231
+ }
232
+ return found;
233
+ };
234
+
235
+ const rename = async (from, to, d) => {
236
+ const re = modifierPattern(from, prefixes(d));
237
+ const changed = [];
238
+ classFiles(root).forEach((file) => {
239
+ const text = fs.readFileSync(file, 'utf8');
240
+ const next = text.replace(CLASS_ATTR, (whole, q, classes) => whole.replace(classes, classes.replace(re, (m0, lead, pre) => `${lead}${pre}${to}`)));
241
+ if (next !== text) { write(file, next); changed.push(rel(file)); }
242
+ });
243
+ const versoPath = path.join(root, 'verso.json');
244
+ if (fs.existsSync(versoPath)) {
245
+ const config = JSON.parse(fs.readFileSync(versoPath, 'utf8'));
246
+ let touched = false;
247
+ Object.keys(config.rich || {}).forEach((tag) => {
248
+ const next = config.rich[tag].replace(re, (m0, lead, pre) => `${lead}${pre}${to}`);
249
+ if (next !== config.rich[tag]) { config.rich[tag] = next; touched = true; }
250
+ });
251
+ if (touched) { write(versoPath, JSON.stringify(config, null, 2) + '\n'); changed.push('verso.json'); }
252
+ }
253
+ return changed;
254
+ };
255
+
256
+ const checkName = (type, name, d, { override = false } = {}) => {
257
+ if (!TYPES.includes(type)) throw new VersoError(`"${type}" isn't a token type Verso can edit.`);
258
+ if (!NAME.test(String(name))) throw new VersoError(`"${name}" can't be a token name. Use lowercase letters, numbers and dashes, starting with a letter.`);
259
+ const own = readTokens()[type] || {};
260
+ if (!override && !(name in own) && d.tokens[type] && name in d.tokens[type]) {
261
+ throw new VersoError(`"${name}" is already one of Elevate's ${typeLabel(type)}. Pick another name, or choose to replace it.`);
262
+ }
263
+ };
264
+
265
+ const ensureFontsExtend = () => {
266
+ const configPath = path.join(root, 'elevate/config/elevate.ts');
267
+ if (!fs.existsSync(configPath)) return;
268
+ const text = fs.readFileSync(configPath, 'utf8');
269
+ if (text.includes('extend/fonts.css')) return;
270
+ const next = text.replace(/Extend:\s*\[([^\]]*)\]/, (m, inner) => {
271
+ const items = inner.trim() ? `${inner.trim().replace(/,\s*$/, '')}, './${FONTS_CSS}'` : `'./${FONTS_CSS}'`;
272
+ return `Extend: [${items}]`;
273
+ });
274
+ if (next !== text) write(configPath, next);
275
+ };
276
+
277
+ const fail = (res, err, status = 400) => ctx.sendJSON(res, status, { ok: false, message: err.message, hint: err.hint || null });
278
+
279
+ // ── Text styles ──
280
+ const versoPath = path.join(root, 'verso.json');
281
+ const readConfigFile = () => {
282
+ try {
283
+ return JSON.parse(fs.readFileSync(versoPath, 'utf8'));
284
+ } catch {
285
+ throw new VersoError('verso.json isn\'t valid JSON, so text styles can\'t be changed.', { file: 'verso.json' });
286
+ }
287
+ };
288
+ const textStyles = (d, rich) => TEXT_STYLES.map(([tag, label, group]) => {
289
+ const classes = String(rich[tag] || '');
290
+ return { tag, label, group, classes, picks: Object.fromEntries(STYLE_PICKERS.map((pk) => [pk, currentPick(classes, pk, null, d)])) };
291
+ });
292
+ const styleOptions = (d) => {
293
+ const names = (type, keep = () => true) => Object.entries(d.tokens[type] || {}).filter(([n]) => keep(n)).map(([name, value]) => ({ name, value: String(value) }));
294
+ const spacing = names('SpacingToken', (n) => /^(d\d+|c\d+|0|px)$/.test(n));
295
+ // The site's own colours first; Elevate's ramps after, marked, so the
296
+ // panel can tuck them away.
297
+ const defaults = elevateColorNames();
298
+ const colours = names('ColorToken').map((o) => ({ ...o, elevate: defaults.has(o.name) }))
299
+ .sort((a, b) => Number(a.elevate) - Number(b.elevate));
300
+ return {
301
+ family: names('FontFamilyToken'), size: names('FontSizeToken'), weight: names('FontWeightToken'),
302
+ 'text-color': colours, background: colours, leading: names('LineHeightToken'),
303
+ 'margin-top': spacing, 'margin-bottom': spacing, padding: spacing, radius: spacing,
304
+ };
305
+ };
306
+ // The names of Elevate's own colour ramps, read from its design file.
307
+ const elevateColorNames = () => {
308
+ const file = path.join(root, 'elevate/core/system/design/colors.ts');
309
+ if (!fs.existsSync(file)) return new Set();
310
+ return new Set([...fs.readFileSync(file, 'utf8').matchAll(/^\s*'?([a-z][\w+-]*)'?\s*:/gm)].map((m) => m[1]));
311
+ };
312
+ // Saves one element's classes in verso.json, in place, after Elevate
313
+ // agrees they're valid; then recompiles and swaps the stylesheet.
314
+ const saveTextStyle = async (tag, next) => {
315
+ const api = await loadElevate(root);
316
+ const bad = api.validate(next).problems[0];
317
+ if (bad) throw new VersoError(`"${bad.token}" isn't a class Elevate can use: ${bad.message}`);
318
+ const config = readConfigFile();
319
+ config.rich = config.rich && typeof config.rich === 'object' ? config.rich : {};
320
+ if (next.trim()) config.rich[tag] = next.trim(); else delete config.rich[tag];
321
+ write(versoPath, JSON.stringify(config, null, 2) + '\n');
322
+ await ctx.compile({});
323
+ ctx.broadcast({ type: 'css' });
324
+ return ctx.cssError ? (ctx.cssError.toJSON ? ctx.cssError.toJSON() : { message: ctx.cssError.message }) : null;
325
+ };
326
+
327
+ return {
328
+ editorData: () => ({ tokensReady: designLoadsTokens() }),
329
+
330
+ async handle(req, res, url) {
331
+ const p = url.pathname;
332
+ if (!p.startsWith('/__verso/tokens') && p !== '/__verso/fonts') return false;
333
+ try {
334
+ if (p === '/__verso/tokens' && req.method === 'GET') {
335
+ const d = await describe();
336
+ const own = readTokens();
337
+ const counts = {};
338
+ for (const type of TYPES) {
339
+ for (const name of Object.keys(own[type] || {})) counts[name] = (await usage(name, d)).length;
340
+ }
341
+ ctx.sendJSON(res, 200, { ok: true, ready: designLoadsTokens(), tokens: Object.fromEntries(TYPES.map((t) => [t, d.tokens[t] || {}])), own, usage: counts });
342
+ return true;
343
+ }
344
+ if (p === '/__verso/tokens/text-styles' && req.method === 'GET') {
345
+ const d = await describe();
346
+ ctx.sendJSON(res, 200, { ok: true, styles: textStyles(d, readConfigFile().rich || {}), options: styleOptions(d) });
347
+ return true;
348
+ }
349
+ if (p === '/__verso/tokens/text-styles' && req.method === 'POST') {
350
+ const body = await ctx.readBody(req);
351
+ const tag = String(body.tag || '');
352
+ if (!TEXT_STYLES.some(([t]) => t === tag)) throw new VersoError(`"${tag}" isn't a kind of text Verso styles.`);
353
+ const d = await describe();
354
+ const current = String((readConfigFile().rich || {})[tag] || '');
355
+ let next;
356
+ if (typeof body.classes === 'string') {
357
+ if (/[<>"{}]/.test(body.classes)) throw new VersoError('Classes can\'t contain < > " { or }.');
358
+ next = body.classes.replace(/\s+/g, ' ').trim();
359
+ } else {
360
+ if (!STYLE_PICKERS.includes(body.picker)) throw new VersoError(`"${body.picker}" isn't something a text style can change.`);
361
+ const value = body.value == null || body.value === '' ? null : String(body.value);
362
+ if (value !== null && !styleOptions(d)[body.picker].some((o) => o.name === value)) throw new VersoError(`"${value}" isn't one of this site's tokens for that.`);
363
+ next = applyPick(current, body.picker, value, null, d).replace(/\s+/g, ' ').trim();
364
+ }
365
+ const cssProblem = await saveTextStyle(tag, next);
366
+ const style = textStyles(d, { [tag]: next }).find((x) => x.tag === tag);
367
+ ctx.sendJSON(res, 200, { ok: true, style, cssProblem });
368
+ return true;
369
+ }
370
+ if (p === '/__verso/tokens/screens' && req.method === 'GET') {
371
+ const d = await describe();
372
+ ctx.sendJSON(res, 200, { ok: true, ready: designLoadsTokens(), screens: screensReport(d) });
373
+ return true;
374
+ }
375
+ if (p === '/__verso/tokens/screens/usage' && req.method === 'GET') {
376
+ ctx.sendJSON(res, 200, { ok: true, usage: screenUsage(String(url.searchParams.get('name') || '')) });
377
+ return true;
378
+ }
379
+ if (p === '/__verso/tokens/usage' && req.method === 'GET') {
380
+ ctx.sendJSON(res, 200, { ok: true, usage: await usage(String(url.searchParams.get('name') || '')) });
381
+ return true;
382
+ }
383
+ if (req.method !== 'POST') return false;
384
+
385
+ if (p === '/__verso/tokens/ramp' && url.searchParams.get('preview') === '1') {
386
+ const body = await ctx.readBody(req);
387
+ if (!parseHex(body.hex)) throw new VersoError(`"${body.hex}" isn't a colour. Use a hex value like #B8471F.`);
388
+ ctx.sendJSON(res, 200, { ok: true, steps: rampReport(ramp(String(body.name || 'brand'), body.hex)) });
389
+ return true;
390
+ }
391
+
392
+ if (p === '/__verso/fonts') {
393
+ // Anything the form leaves alone is read from the file itself.
394
+ const buffer = await ctx.readRaw(req);
395
+ const kind = sniffFont(buffer);
396
+ if (!kind) throw new VersoError('That file isn\'t a font Verso can use. Use WOFF2 (best), WOFF, TTF or OTF.');
397
+ const facts = fontFacts(buffer, kind);
398
+ const asked = (key) => { const v = String(url.searchParams.get(key) || '').trim(); return v && v !== 'auto' ? v : ''; };
399
+ const family = asked('family') || facts.family || '';
400
+ const weight = asked('weight') || facts.weight || '400';
401
+ const style = (asked('style') || facts.style) === 'italic' ? 'italic' : 'normal';
402
+ const kindOfFace = asked('fallback') || facts.fallback || 'sans';
403
+ const fallback = kindOfFace === 'serif' ? 'Georgia, serif' : kindOfFace === 'mono' ? 'ui-monospace, monospace' : 'ui-sans-serif, system-ui, sans-serif';
404
+ if (!family || !/^[\w .'-]{1,60}$/.test(family)) throw new VersoError('This file doesn\'t say what the font is called. Give it a family name, like "Fraunces", and drop it again.');
405
+ if (!/^[1-9]00$/.test(weight)) throw new VersoError('The weight should be a number from 100 to 900.');
406
+ const d = await describe();
407
+ const name = slug(family);
408
+ // A variable font is one file for a range of weights.
409
+ const axes = fontAxes(buffer, kind);
410
+ const range = axes?.wght && axes.wght[0] !== axes.wght[1] ? axes.wght : null;
411
+ const fileName = `${name}-${range ? 'variable' : weight}${style === 'italic' ? '-italic' : ''}.${kind}`;
412
+ const fontPath = path.join(root, 'public', 'fonts', fileName);
413
+ fs.mkdirSync(path.dirname(fontPath), { recursive: true });
414
+ fs.writeFileSync(fontPath, buffer);
415
+ ctx.written.set(rel(fontPath), ctx.hash(buffer));
416
+ const cssPath = path.join(root, FONTS_CSS);
417
+ const rule = `@font-face { font-family: '${family}'; src: url('/fonts/${fileName}') format('${FONT_FORMAT[kind]}'); font-weight: ${range ? `${range[0]} ${range[1]}` : weight}; font-style: ${style}; font-display: swap; }`;
418
+ const existing = fs.existsSync(cssPath) ? fs.readFileSync(cssPath, 'utf8') : '/* Fonts added in Verso. Each file is in public/fonts/. */\n';
419
+ const lines = existing.split('\n').filter((l) => !l.includes(`url('/fonts/${fileName}')`));
420
+ write(cssPath, `${lines.join('\n').trimEnd()}\n${rule}\n`);
421
+ ensureFontsExtend();
422
+ const tokens = readTokens();
423
+ tokens.FontFamilyToken = tokens.FontFamilyToken || {};
424
+ if (!tokens.FontFamilyToken[name]) {
425
+ if (d.tokens.FontFamilyToken?.[name]) throw new VersoError(`"${name}" is already one of Elevate's font families. Give the font another name.`);
426
+ tokens.FontFamilyToken[name] = `'${family}', ${fallback}`;
427
+ }
428
+ const cssProblem = await writeTokens(tokens);
429
+ ctx.sendJSON(res, 200, { ok: true, name, family, weight, style, file: `public/fonts/${fileName}`, weights: range, cssProblem });
430
+ return true;
431
+ }
432
+
433
+ const body = await ctx.readBody(req);
434
+ const d = await describe();
435
+ const tokens = readTokens();
436
+
437
+ if (p === '/__verso/tokens') {
438
+ const { type, name } = body;
439
+ const value = String(body.value ?? '').trim();
440
+ checkName(type, name, d, { override: body.override === true });
441
+ if (!value) throw new VersoError('Give the token a value.');
442
+ if (/[;{}<>]/.test(value)) throw new VersoError('That value has characters CSS values can\'t contain here: ; { } < >');
443
+ if (type === 'ColorToken' && !parseHex(value) && !/^(rgb|hsl|oklch|oklab|color|var)\(/i.test(value)) throw new VersoError(`"${value}" isn't a colour. Use a hex value like #B8471F, or a CSS variable like var(--paper).`);
444
+ tokens[type] = { ...(tokens[type] || {}), [name]: value };
445
+ ctx.sendJSON(res, 200, { ok: true, cssProblem: await writeTokens(tokens) });
446
+ return true;
447
+ }
448
+
449
+ if (p === '/__verso/tokens/ramp') {
450
+ const name = String(body.name || '');
451
+ if (!parseHex(body.hex)) throw new VersoError(`"${body.hex}" isn't a colour. Use a hex value like #B8471F.`);
452
+ const steps = ramp(name, body.hex);
453
+ Object.keys(steps).forEach((key) => checkName('ColorToken', key, d, { override: body.override === true }));
454
+ tokens.ColorToken = { ...(tokens.ColorToken || {}), ...steps };
455
+ ctx.sendJSON(res, 200, { ok: true, steps: rampReport(steps), cssProblem: await writeTokens(tokens) });
456
+ return true;
457
+ }
458
+
459
+ if (p === '/__verso/tokens/fluid') {
460
+ const name = String(body.name || '');
461
+ checkName('FontSizeToken', name, d, { override: body.override === true });
462
+ let value;
463
+ try { value = fluid(body.min, body.max); } catch (e) { throw new VersoError(e.message); }
464
+ tokens.FontSizeToken = { ...(tokens.FontSizeToken || {}), [name]: value };
465
+ ctx.sendJSON(res, 200, { ok: true, value, cssProblem: await writeTokens(tokens) });
466
+ return true;
467
+ }
468
+
469
+ if (p === '/__verso/tokens/rename') {
470
+ const { type, from, to } = body;
471
+ if (!tokens[type] || !(from in tokens[type])) throw new VersoError(`"${from}" isn't one of this site's own tokens, so Verso won't rename it.`);
472
+ checkName(type, to, d);
473
+ if (to in tokens[type]) throw new VersoError(`There's already a token called "${to}".`);
474
+ const changed = await rename(from, to, d);
475
+ tokens[type] = Object.fromEntries(Object.entries(tokens[type]).map(([k, v]) => [k === from ? to : k, v]));
476
+ const cssProblem = await writeTokens(tokens);
477
+ ctx.broadcast({ type: 'reload', files: changed });
478
+ ctx.sendJSON(res, 200, { ok: true, changed, cssProblem });
479
+ return true;
480
+ }
481
+
482
+ if (p === '/__verso/tokens/screens') {
483
+ // { action: 'save', name?, label, width } changes or adds one;
484
+ // { action: 'remove', name, force? } takes one away.
485
+ const current = screensFor(d.breakpoints, readScreenLabels(root));
486
+ const labels = Object.fromEntries(current.map((s) => [s.name, s.label]));
487
+ const widths = Object.fromEntries(current.map((s) => [s.name, s.minWidth]));
488
+ const label = String(body.label ?? '').replace(/\s+/g, ' ').trim().slice(0, 40);
489
+ // Elevate reads a site's own screen sizes from 1.3.0 on.
490
+ const [maj, min] = String(d.elevate || '0.0').split('.').map(Number);
491
+ if (maj < 1 || (maj === 1 && min < 3)) {
492
+ throw new VersoError(`This site has Elevate ${d.elevate || '(an old version)'}, which can't change screen sizes. Elevate 1.3 or later can.`, {
493
+ hint: 'In the site folder, run "npm install elevate-framework@latest", then "npx elevate-framework prepare".',
494
+ });
495
+ }
496
+ if (body.action === 'save') {
497
+ const width = String(body.width ?? '').trim().replace(/^(\d+(\.\d+)?)$/, '$1px');
498
+ if (!label) throw new VersoError('Give the screen size a name, like "Tablets".');
499
+ if (!SCREEN_WIDTH.test(width)) throw new VersoError(`"${body.width}" isn't a width. Use pixels, like 768, or rem, like 48rem.`);
500
+ const px = widthPx(width);
501
+ if (px < 240 || px > 5000) throw new VersoError('A screen size has to start somewhere between 240 and 5000 pixels wide.');
502
+ let name = body.name ? String(body.name) : '';
503
+ if (name && !(name in widths)) throw new VersoError(`There's no screen size called "${name}".`);
504
+ if (!name) {
505
+ // "Wide screens" → wide-screens; long names keep whole words.
506
+ let base = label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'screen';
507
+ while (base.length > 12 && base.includes('-')) base = base.slice(0, base.lastIndexOf('-'));
508
+ base = base.slice(0, 12);
509
+ name = /^[a-z0-9]/.test(base) ? base : `s-${base}`.slice(0, 10);
510
+ for (let i = 2; name in widths; i += 1) name = `${base.slice(0, 10)}${i}`;
511
+ }
512
+ if (!SCREEN_NAME.test(name)) throw new VersoError(`"${name}" can't be a screen size's name.`);
513
+ const clash = current.find((s) => s.name !== name && s.px === px);
514
+ if (clash) throw new VersoError(`${clash.label} already starts at ${px}px. Pick another width.`);
515
+ if (Object.entries(labels).some(([n, l]) => n !== name && l.toLowerCase() === label.toLowerCase())) throw new VersoError(`There's already a screen size called "${label}".`);
516
+ letDesignLoadScreens();
517
+ widths[name] = width;
518
+ labels[name] = label;
519
+ tokens.BreakPointToken = Object.fromEntries(Object.entries(widths).sort((a, b) => widthPx(a[1]) - widthPx(b[1])));
520
+ writeScreenLabels(labels);
521
+ const cssProblem = await writeTokens(tokens);
522
+ ctx.sendJSON(res, 200, { ok: true, name, cssProblem });
523
+ return true;
524
+ }
525
+ if (body.action === 'remove') {
526
+ const name = String(body.name || '');
527
+ if (!(name in widths)) throw new VersoError(`There's no screen size called "${name}".`);
528
+ if (current.length === 1) throw new VersoError('A site needs at least one screen size besides the smallest.');
529
+ const used = screenUsage(name);
530
+ if (used.length && body.force !== true) {
531
+ ctx.sendJSON(res, 409, { ok: false, message: `${labels[name]} is used in ${used.length} place${used.length === 1 ? '' : 's'}. Removing it also removes the styles set for it there.`, usage: used });
532
+ return true;
533
+ }
534
+ letDesignLoadScreens();
535
+ const changed = used.length ? dropScreenEverywhere(name) : [];
536
+ delete widths[name];
537
+ delete labels[name];
538
+ tokens.BreakPointToken = widths;
539
+ writeScreenLabels(labels);
540
+ const cssProblem = await writeTokens(tokens);
541
+ if (changed.length) ctx.broadcast({ type: 'reload', files: changed });
542
+ ctx.sendJSON(res, 200, { ok: true, changed, cssProblem });
543
+ return true;
544
+ }
545
+ throw new VersoError('Verso didn\'t understand that change to the screen sizes.');
546
+ }
547
+
548
+ if (p === '/__verso/tokens/remove') {
549
+ const { type, name } = body;
550
+ if (!tokens[type] || !(name in tokens[type])) throw new VersoError(`"${name}" isn't one of this site's own tokens.`);
551
+ const used = await usage(name, d);
552
+ if (used.length && body.force !== true) {
553
+ ctx.sendJSON(res, 409, { ok: false, message: `"${name}" is still used in ${used.length} place${used.length === 1 ? '' : 's'}. Change those first, or rename the token instead.`, usage: used });
554
+ return true;
555
+ }
556
+ // A font added here goes with its files and @font-face rules.
557
+ const fontFamily = type === 'FontFamilyToken' ? /^'([^']+)'/.exec(String(tokens[type][name]))?.[1] : null;
558
+ const cssPath = path.join(root, FONTS_CSS);
559
+ if (fontFamily && fs.existsSync(cssPath)) {
560
+ const lines = fs.readFileSync(cssPath, 'utf8').split('\n');
561
+ const gone = lines.filter((l) => l.includes(`font-family: '${fontFamily}';`));
562
+ if (gone.length) {
563
+ write(cssPath, `${lines.filter((l) => !gone.includes(l)).join('\n').trimEnd()}\n`);
564
+ gone.forEach((l) => {
565
+ const file = /url\('\/fonts\/([^']+)'\)/.exec(l)?.[1];
566
+ if (file && !/[\\/]/.test(file)) fs.rmSync(path.join(root, 'public', 'fonts', file), { force: true });
567
+ });
568
+ }
569
+ }
570
+ delete tokens[type][name];
571
+ ctx.sendJSON(res, 200, { ok: true, cssProblem: await writeTokens(tokens) });
572
+ return true;
573
+ }
574
+ return false;
575
+ } catch (err) {
576
+ if (!(err instanceof VersoError)) throw err;
577
+ fail(res, err);
578
+ return true;
579
+ }
580
+ },
581
+ };
582
+ }
583
+
584
+ const typeLabel = (type) => ({
585
+ ColorToken: 'colours', FontSizeToken: 'sizes', FontFamilyToken: 'font families',
586
+ SpacingToken: 'spacing steps', ShadowToken: 'shadows', GradientToken: 'gradients',
587
+ }[type] || 'tokens');