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
package/src/cli.js ADDED
@@ -0,0 +1,161 @@
1
+ // verso open the editor for the site in this folder
2
+ // verso build build the static site into dist/
3
+ // verso new <folder> start a new site
4
+ // verso serve run the site for the internet, with sign-in at /edit
5
+ // verso owner make a link that adds an owner to a served site
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { findRoot } from './site.js';
11
+ import { formatError, VersoError } from './errors.js';
12
+
13
+ const own = JSON.parse(fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8'));
14
+ const red = (s) => (process.stdout.isTTY ? `\x1b[31m${s}\x1b[0m` : s);
15
+
16
+ const USAGE = `Verso ${own.version}
17
+
18
+ verso Open the editor for the site in this folder
19
+ verso build Build the site into dist/
20
+ verso new <folder> Start a new site in <folder>
21
+ verso serve Run the site for the internet: visitors see the published
22
+ pages, and people sign in at /edit to change them
23
+ verso owner Write a link that makes someone an owner of a served site
24
+
25
+ Options
26
+ --port=4321 The port to use. The editor takes the next free one if it's
27
+ busy; "serve" uses $PORT or 8080 and stops if it's taken
28
+ --data=<folder> With "serve": a folder that's kept between restarts, for
29
+ hosts that give the site a separate disk (or set VERSO_DATA)
30
+ --no-open Don't open the browser
31
+ --blank With "new": start with one plain page instead of the example site
32
+ --no-install With "new": skip npm install
33
+ --help, --version
34
+ `;
35
+
36
+ const fail = (err) => {
37
+ if (err instanceof VersoError || err?.name === 'VersoErrors') console.error(red(formatError(err)));
38
+ else console.error(red(`× Verso hit a problem it didn't expect: ${err?.stack || err}`));
39
+ process.exit(1);
40
+ };
41
+
42
+ // Flags, with or without "=": --port=5000 and --port 5000 both work.
43
+ const argv = process.argv.slice(2);
44
+ const flags = new Map();
45
+ const words = [];
46
+ for (let i = 0; i < argv.length; i++) {
47
+ const a = argv[i];
48
+ if (!a.startsWith('--')) { words.push(a); continue; }
49
+ const [key, value] = a.slice(2).split(/=(.*)/s);
50
+ if (value !== undefined) flags.set(key, value);
51
+ else if (['port', 'data', 'host'].includes(key) && argv[i + 1] && !argv[i + 1].startsWith('--')) flags.set(key, argv[++i]);
52
+ else flags.set(key, true);
53
+ }
54
+ const known = ['port', 'open', 'no-open', 'no-install', 'blank', 'help', 'version', 'data', 'host'];
55
+ const [command = 'dev', ...rest] = words;
56
+
57
+ const siteRoot = () => {
58
+ const root = findRoot();
59
+ if (!root) {
60
+ fail(new VersoError("This folder isn't a Verso site, because there's no verso.json here or above it.", {
61
+ hint: 'To start one, run: npx verso-cms new my-site',
62
+ }));
63
+ }
64
+ process.chdir(root);
65
+ return root;
66
+ };
67
+
68
+ // Elevate's compiler lives in elevate/core. A site fresh from git or from
69
+ // "verso new --no-install" doesn't have it yet, so put it in.
70
+ const ensureElevate = async (root) => {
71
+ if (fs.existsSync(path.join(root, 'elevate', 'core'))) return;
72
+ const { prepareElevate } = await import('./scaffold.js');
73
+ console.log(' Setting up Elevate for this site…');
74
+ const result = await prepareElevate(root);
75
+ if (!result.ok) {
76
+ throw new VersoError(result.missing ? "Elevate isn't installed in this site yet." : `Elevate couldn't be set up: ${result.output.trim()}`, {
77
+ hint: result.missing ? 'Run "npm install" in this folder, then try again.' : undefined,
78
+ });
79
+ }
80
+ };
81
+
82
+ try {
83
+ const unknown = [...flags.keys()].filter((k) => !known.includes(k));
84
+ if (flags.has('help') || command === 'help') {
85
+ console.log(USAGE);
86
+ } else if (flags.has('version') || command === 'version') {
87
+ console.log(own.version);
88
+ } else if (unknown.length) {
89
+ fail(new VersoError(`--${unknown[0]} isn't a Verso option.`, { hint: 'Run verso --help to see them.' }));
90
+ } else if (command === 'new') {
91
+ const { createSite } = await import('./scaffold.js');
92
+ await createSite(rest[0], { install: !flags.has('no-install'), blank: flags.has('blank') });
93
+ } else if (command === 'build') {
94
+ const { buildSite } = await import('./build.js');
95
+ const root = siteRoot();
96
+ await ensureElevate(root);
97
+ const result = await buildSite(root);
98
+ result.warnings.forEach((w) => console.warn(w));
99
+ const extra = [
100
+ result.tagPages ? `${result.tagPages} tag page${result.tagPages === 1 ? '' : 's'}` : '',
101
+ result.listPages ? `${result.listPages} more page${result.listPages === 1 ? '' : 's'} of lists` : '',
102
+ ].filter(Boolean);
103
+ const pages = `${result.pages} page${result.pages === 1 ? '' : 's'}`;
104
+ console.log(`√ Built ${extra.length ? `${pages}, ${extra.join(' and ')}` : pages} into ${result.out}/ in ${result.ms} ms.`);
105
+ } else if (command === 'dev' || command === 'edit') {
106
+ let port = 4321;
107
+ if (flags.has('port')) {
108
+ port = Number(flags.get('port'));
109
+ if (!Number.isInteger(port) || port < 1 || port > 65535) fail(new VersoError(`"${flags.get('port')}" isn't a port.`, { hint: 'Use a number, like --port=3000.' }));
110
+ }
111
+ const { startEditor } = await import('./server.js');
112
+ const root = siteRoot();
113
+ await ensureElevate(root);
114
+ const editor = await startEditor(root, { open: !flags.has('no-open'), port });
115
+ const moved = editor.port !== port ? ` Port ${port} was busy, so Verso is on ${editor.port}.\n` : '';
116
+ console.log(`\n Verso is editing ${root}\n ${editor.url}\n${moved}\n Press Ctrl+C to stop.\n`);
117
+ const stop = async () => {
118
+ await editor.close();
119
+ process.exit(0);
120
+ };
121
+ process.on('SIGINT', stop);
122
+ process.on('SIGTERM', stop);
123
+ } else if (command === 'serve') {
124
+ let port = Number(flags.get('port') || process.env.PORT || 8080);
125
+ if (!Number.isInteger(port) || port < 1 || port > 65535) fail(new VersoError(`"${flags.get('port') || process.env.PORT}" isn't a port.`, { hint: 'Use a number, like --port=8080.' }));
126
+ const { startEditor } = await import('./server.js');
127
+ let root = siteRoot();
128
+ const data = flags.get('data') || process.env.VERSO_DATA;
129
+ if (data && data !== true) {
130
+ const { moveIn } = await import('./box.js');
131
+ root = moveIn(root, data, { log: (m) => console.log(` ${m}`) });
132
+ process.chdir(root);
133
+ }
134
+ await ensureElevate(root);
135
+ let site;
136
+ try {
137
+ site = await startEditor(root, { open: false, port, box: true, host: typeof flags.get('host') === 'string' ? flags.get('host') : '', log: (m) => console.log(` ${m}`) });
138
+ } catch (err) {
139
+ if (err?.code === 'EADDRINUSE') fail(new VersoError(`Port ${port} is already in use.`, { hint: 'Stop what\'s using it, or pick another with --port.' }));
140
+ throw err;
141
+ }
142
+ const { box } = site;
143
+ console.log(`\n Verso is serving ${root}\n on port ${site.port}. Visitors see the published site; people sign in at /edit.\n`);
144
+ if (box.first) console.log(' This is the first start in this folder. If the site has been running before,\n its host isn\'t keeping files between restarts: give it a disk and set VERSO_DATA.\n');
145
+ else console.log(` Started ${box.record.starts} times since ${box.record.first.slice(0, 10)}, with its files kept.\n`);
146
+ if (!box.people.any()) console.log(` Nobody can edit yet. To become the first owner, open:\n\n http://localhost:${site.port}${box.setupLink()}\n\n (put the site's real address in place of localhost)\n`);
147
+ const stop = async () => { await site.close(); process.exit(0); };
148
+ process.on('SIGINT', stop);
149
+ process.on('SIGTERM', stop);
150
+ } else if (command === 'owner') {
151
+ const { openPeople } = await import('./people.js');
152
+ const data = flags.get('data') || process.env.VERSO_DATA;
153
+ const root = data && data !== true && fs.existsSync(path.join(path.resolve(data), 'site', 'verso.json')) ? path.join(path.resolve(data), 'site') : siteRoot();
154
+ const link = openPeople(root).setupLink();
155
+ console.log(`\n Add this to the end of the site's address and open it:\n\n ${link}\n\n It makes one new owner, works once, and lasts seven days.\n`);
156
+ } else {
157
+ fail(new VersoError(`"${command}" isn't a Verso command.`, { hint: 'Use verso, verso build, verso serve or verso new <folder>. Run verso --help for more.' }));
158
+ }
159
+ } catch (err) {
160
+ fail(err);
161
+ }
package/src/color.js ADDED
@@ -0,0 +1,137 @@
1
+ // Colour maths for the token editor: hex ↔ OKLCH, nine-step ramps named the
2
+ // way Elevate names its own (name-4 … name … name+4, dark to light), and WCAG
3
+ // contrast.
4
+
5
+ const clamp01 = (x) => Math.min(1, Math.max(0, x));
6
+ const toLinear = (c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
7
+ const toGamma = (c) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);
8
+
9
+ export function parseHex(hex) {
10
+ const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(hex).trim());
11
+ if (!m) return null;
12
+ let h = m[1];
13
+ if (h.length === 3) h = h.split('').map((c) => c + c).join('');
14
+ return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16) / 255);
15
+ }
16
+
17
+ export const toHex = ([r, g, b]) =>
18
+ `#${[r, g, b].map((c) => Math.round(clamp01(c) * 255).toString(16).padStart(2, '0')).join('').toUpperCase()}`;
19
+
20
+ export function rgbToOklch([r, g, b]) {
21
+ const [lr, lg, lb] = [r, g, b].map(toLinear);
22
+ const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb);
23
+ const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb);
24
+ const s = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb);
25
+ const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
26
+ const a = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
27
+ const bb = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
28
+ const C = Math.hypot(a, bb);
29
+ let H = (Math.atan2(bb, a) * 180) / Math.PI;
30
+ if (H < 0) H += 360;
31
+ return { l: L, c: C, h: H };
32
+ }
33
+
34
+ // Returns linear-light-free sRGB, possibly out of gamut (components outside 0–1).
35
+ export function oklchToRgb({ l, c, h }) {
36
+ const a = c * Math.cos((h * Math.PI) / 180);
37
+ const b = c * Math.sin((h * Math.PI) / 180);
38
+ const l_ = (l + 0.3963377774 * a + 0.2158037573 * b) ** 3;
39
+ const m_ = (l - 0.1055613458 * a - 0.0638541728 * b) ** 3;
40
+ const s_ = (l - 0.0894841775 * a - 1.291485548 * b) ** 3;
41
+ const r = 4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_;
42
+ const g = -1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_;
43
+ const bl = -0.0041960863 * l_ - 0.7034186147 * m_ + 1.707614701 * s_;
44
+ return [r, g, bl].map(toGamma);
45
+ }
46
+
47
+ const inGamut = (rgb) => rgb.every((c) => c >= -0.0005 && c <= 1.0005);
48
+
49
+ // Lowers chroma until the colour fits in sRGB, keeping lightness and hue.
50
+ export function fitGamut({ l, c, h }) {
51
+ if (inGamut(oklchToRgb({ l, c, h }))) return { l, c, h };
52
+ let lo = 0;
53
+ let hi = c;
54
+ for (let i = 0; i < 24; i++) {
55
+ const mid = (lo + hi) / 2;
56
+ if (inGamut(oklchToRgb({ l, c: mid, h }))) lo = mid;
57
+ else hi = mid;
58
+ }
59
+ return { l, c: lo, h };
60
+ }
61
+
62
+ export const hexToOklch = (hex) => {
63
+ const rgb = parseHex(hex);
64
+ return rgb ? rgbToOklch(rgb) : null;
65
+ };
66
+ export const oklchToHex = (lch) => toHex(oklchToRgb(fitGamut(lch)));
67
+
68
+ export function luminance(hex) {
69
+ const [r, g, b] = parseHex(hex).map(toLinear);
70
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
71
+ }
72
+
73
+ export function contrast(a, b) {
74
+ const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p);
75
+ return (x + 0.05) / (y + 0.05);
76
+ }
77
+
78
+ // The darkest and lightest lightness in Elevate's default ramps.
79
+ const DARKEST = 0.22;
80
+ const LIGHTEST = 0.95;
81
+
82
+ // Nine steps around one colour. The colour itself is the middle step, and
83
+ // the steps on each side are evenly spaced in perceived lightness out to
84
+ // Elevate's darkest and lightest. Chroma eases off towards the ends, so the
85
+ // palest and deepest steps stay clean, and every step fits in sRGB.
86
+ export function ramp(name, hex) {
87
+ const base = hexToOklch(hex);
88
+ if (!base) throw new Error(`"${hex}" isn't a colour. Use a hex value like #B8471F.`);
89
+ const steps = {};
90
+ const L = Math.min(Math.max(base.l, DARKEST + 0.1), LIGHTEST - 0.1);
91
+ for (let i = -4; i <= 4; i++) {
92
+ const key = i === 0 ? name : `${name}${i > 0 ? '+' : ''}${i}`;
93
+ if (i === 0) {
94
+ steps[key] = toHex(parseHex(hex));
95
+ continue;
96
+ }
97
+ const t = Math.abs(i) / 4;
98
+ const l = i < 0 ? L + (DARKEST - L) * t : L + (LIGHTEST - L) * t;
99
+ const c = base.c * (1 - 0.55 * t * t) * (i > 0 ? 1 - 0.35 * t : 1);
100
+ steps[key] = oklchToHex({ l, c, h: base.h });
101
+ }
102
+ return steps;
103
+ }
104
+
105
+ // Ramp steps in order, dark to light, with contrast against white and the
106
+ // darkest step, so the editor can show which steps take white or dark text.
107
+ export function rampReport(steps) {
108
+ const entries = Object.entries(steps);
109
+ const darkest = entries[0][1];
110
+ return entries.map(([key, value]) => ({
111
+ name: key,
112
+ value,
113
+ onWhite: Math.round(contrast(value, '#FFFFFF') * 100) / 100,
114
+ onDarkest: Math.round(contrast(value, darkest) * 100) / 100,
115
+ }));
116
+ }
117
+
118
+ // "1.5rem" or "24px" → rem number
119
+ export function toRem(size) {
120
+ const m = /^\s*(\d*\.?\d+)\s*(rem|px)?\s*$/i.exec(String(size));
121
+ if (!m) return null;
122
+ const n = Number(m[1]);
123
+ return (m[2] || 'rem').toLowerCase() === 'px' ? n / 16 : n;
124
+ }
125
+
126
+ const round = (n) => Math.round(n * 10000) / 10000;
127
+
128
+ // A size that grows smoothly from min on a 20rem screen to max on an 80rem one.
129
+ export function fluid(min, max, from = 20, to = 80) {
130
+ const a = toRem(min);
131
+ const b = toRem(max);
132
+ if (a == null || b == null) throw new Error('Sizes should look like 1.5rem or 24px.');
133
+ const slope = (b - a) / (to - from);
134
+ const intercept = a - slope * from;
135
+ const [lo, hi] = a <= b ? [a, b] : [b, a];
136
+ return `clamp(${round(lo)}rem, ${round(intercept)}rem + ${round(slope * 100)}vw, ${round(hi)}rem)`;
137
+ }
@@ -0,0 +1,223 @@
1
+ // Components: an arrangement of blocks saved as a file, used on many pages.
2
+ //
3
+ // components/<name>.json
4
+ // {
5
+ // "name": "pricing", "label": "Pricing",
6
+ // "tree": [ { "block": "grid", "key": "k1", "blocks": { "items": [ { "block": "card", "key": "k2" } ] } } ],
7
+ // "shared": { "k2.title": "…" }, locked fields: the same on every page
8
+ // "defaults": { "k1.heading": "…" } what a new instance starts with
9
+ // }
10
+ //
11
+ // The structure is shared: change the file and every page follows. A page
12
+ // holds an instance, { "id", "component", "fields": { "<key>.<field>": … } },
13
+ // with its own content. For rendering, checking and editing, an instance is
14
+ // expanded into ordinary blocks whose ids are "<instance id>-<key>", so the
15
+ // rest of Verso treats them like any other block.
16
+
17
+ import fs from 'fs';
18
+ import path from 'path';
19
+ import { VersoError } from './errors.js';
20
+ import { humanize } from './template.js';
21
+ import { newId } from './blocks.js';
22
+
23
+ const NAME = /^[a-z0-9][a-z0-9-]*$/;
24
+ const rel = (root, p) => path.relative(root, p).split(path.sep).join('/');
25
+
26
+ export const componentFile = (root, name) => path.join(root, 'components', `${name}.json`);
27
+
28
+ export function listComponents(root) {
29
+ const dir = path.join(root, 'components');
30
+ const found = new Map();
31
+ const errors = [];
32
+ if (!fs.existsSync(dir)) return { components: found, errors };
33
+ fs.readdirSync(dir).filter((f) => f.endsWith('.json')).sort().forEach((f) => {
34
+ const name = f.slice(0, -5);
35
+ const file = path.join(dir, f);
36
+ try {
37
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
38
+ if (!Array.isArray(data.tree)) throw new Error('no tree');
39
+ found.set(name, {
40
+ name,
41
+ label: typeof data.label === 'string' && data.label ? data.label : humanize(name),
42
+ tree: data.tree,
43
+ shared: data.shared && typeof data.shared === 'object' ? data.shared : {},
44
+ defaults: data.defaults && typeof data.defaults === 'object' ? data.defaults : {},
45
+ file: rel(root, file),
46
+ });
47
+ } catch {
48
+ errors.push(new VersoError(`This component file can't be read. It should be JSON with a "tree" of blocks.`, { file: rel(root, file) }));
49
+ }
50
+ });
51
+ return { components: found, errors };
52
+ }
53
+
54
+ export function writeComponent(root, comp) {
55
+ const file = componentFile(root, comp.name);
56
+ fs.mkdirSync(path.dirname(file), { recursive: true });
57
+ const data = { name: comp.name, label: comp.label, tree: comp.tree, shared: comp.shared || {}, defaults: comp.defaults || {} };
58
+ const text = JSON.stringify(data, null, 2) + '\n';
59
+ const tmp = `${file}.${process.pid}.tmp`;
60
+ fs.writeFileSync(tmp, text, 'utf8');
61
+ fs.renameSync(tmp, file);
62
+ return { rel: rel(root, file), text };
63
+ }
64
+
65
+ // ════ The tree ════
66
+
67
+ export function walkTree(tree, fn, parent = null, slot = null) {
68
+ (tree || []).forEach((node, index, list) => {
69
+ fn(node, list, index, parent, slot);
70
+ Object.entries(node.blocks || {}).forEach(([s, kids]) => walkTree(kids, fn, node, s));
71
+ });
72
+ }
73
+
74
+ export function findNode(comp, key) {
75
+ let found = null;
76
+ walkTree(comp.tree, (node, list, index, parent, slot) => {
77
+ if (!found && node.key === key) found = { node, list, index, parent, slot };
78
+ });
79
+ return found;
80
+ }
81
+
82
+ export function nextKey(comp) {
83
+ let max = 0;
84
+ walkTree(comp.tree, (node) => {
85
+ const n = Number(/^k(\d+)$/.exec(node.key || '')?.[1] || 0);
86
+ if (n > max) max = n;
87
+ });
88
+ return `k${max + 1}`;
89
+ }
90
+
91
+ // ════ Expanding an instance into blocks ════
92
+
93
+ const valuesFor = (comp, inst, key) => {
94
+ const fields = {};
95
+ const locked = new Set();
96
+ const take = (bag, mark) => Object.entries(bag || {}).forEach(([k, v]) => {
97
+ if (!k.startsWith(`${key}.`)) return;
98
+ const f = k.slice(key.length + 1);
99
+ fields[f] = v;
100
+ if (mark) locked.add(f);
101
+ });
102
+ take(comp.defaults);
103
+ take(inst.fields);
104
+ take(comp.shared, true);
105
+ return { fields, locked };
106
+ };
107
+
108
+ function expandInstance(inst, comp, components) {
109
+ const build = (node, top) => {
110
+ const { fields, locked } = valuesFor(comp, inst, node.key);
111
+ const blocks = {};
112
+ Object.entries(node.blocks || {}).forEach(([slot, kids]) => { blocks[slot] = kids.map((k) => build(k, false)); });
113
+ return {
114
+ id: `${inst.id}-${node.key}`,
115
+ block: node.block,
116
+ fields,
117
+ blocks,
118
+ part: { instance: inst.id, component: comp.name, label: comp.label, key: node.key, top, locked: [...locked] },
119
+ };
120
+ };
121
+ void components;
122
+ return comp.tree.map((node) => build(node, true));
123
+ }
124
+
125
+ // A slot's list as it renders: component instances become their blocks.
126
+ export function expandList(list, components) {
127
+ if (!Array.isArray(list)) return [];
128
+ return list.flatMap((item) => {
129
+ if (item && typeof item.component === 'string') {
130
+ const comp = components?.get(item.component);
131
+ if (!comp) return [{ id: item.id, block: '', missingComponent: item.component, fields: {}, blocks: {} }];
132
+ return expandInstance(item, comp, components);
133
+ }
134
+ if (!item || typeof item !== 'object') return [item];
135
+ const blocks = {};
136
+ Object.entries(item.blocks || {}).forEach(([slot, kids]) => { blocks[slot] = expandList(kids, components); });
137
+ return [{ ...item, blocks }];
138
+ });
139
+ }
140
+
141
+ export function expandBlocks(blocks, components) {
142
+ const out = {};
143
+ Object.entries(blocks || {}).forEach(([slot, list]) => { out[slot] = expandList(list, components); });
144
+ return out;
145
+ }
146
+
147
+ // Finds what an expanded id ("<instance id>-<key>") points at on a page.
148
+ export function findPart(page, id, components) {
149
+ let found = null;
150
+ const visit = (blocks) => Object.values(blocks || {}).forEach((list) => {
151
+ if (!Array.isArray(list)) return;
152
+ list.forEach((item) => {
153
+ if (found || !item) return;
154
+ if (item.component && id.startsWith(`${item.id}-`)) {
155
+ const comp = components?.get(item.component);
156
+ const key = id.slice(item.id.length + 1);
157
+ const node = comp && findNode(comp, key);
158
+ if (node) found = { inst: item, comp, key, ...node };
159
+ }
160
+ visit(item.blocks);
161
+ });
162
+ });
163
+ visit(page.blocks);
164
+ return found;
165
+ }
166
+
167
+ // The top-level block names of a component, for checking a slot's allow-list.
168
+ export const topBlocks = (comp) => comp.tree.map((n) => n.block);
169
+
170
+ // ════ Saving a block as a component, and detaching ════
171
+
172
+ export function componentFromBlock(inst, { name, label, blockTemplates }) {
173
+ if (!NAME.test(name)) throw new VersoError('Give the component a name with letters, numbers and dashes, like "pricing" or "team-grid".');
174
+ const comp = { name, label: label || humanize(name), tree: [], shared: {}, defaults: {} };
175
+ const fields = {};
176
+ let n = 0;
177
+ const convert = (b) => {
178
+ n += 1;
179
+ const key = `k${n}`;
180
+ const node = { block: b.block, key };
181
+ const tpl = blockTemplates?.get(b.block);
182
+ Object.entries(b.fields || {}).forEach(([f, v]) => {
183
+ fields[`${key}.${f}`] = v;
184
+ // New instances start with this text, but not its images: those live in this page's folder.
185
+ if (tpl?.fields.get(f)?.type !== 'image') comp.defaults[`${key}.${f}`] = v;
186
+ });
187
+ const kids = Object.entries(b.blocks || {}).filter(([, list]) => Array.isArray(list) && list.length);
188
+ if (kids.length) {
189
+ node.blocks = {};
190
+ kids.forEach(([slot, list]) => { node.blocks[slot] = list.filter((x) => x && !x.component).map(convert); });
191
+ }
192
+ return node;
193
+ };
194
+ if (inst.component) throw new VersoError('That\'s already a component.');
195
+ comp.tree.push(convert(inst));
196
+ return { comp, instance: { id: inst.id, component: name, fields } };
197
+ }
198
+
199
+ // Turns an instance back into plain blocks with their current content.
200
+ export function detachInstance(inst, comp) {
201
+ const build = (node) => {
202
+ const { fields } = valuesFor(comp, inst, node.key);
203
+ const b = { id: newId(), block: node.block, fields };
204
+ const kids = Object.entries(node.blocks || {});
205
+ if (kids.length) {
206
+ b.blocks = {};
207
+ kids.forEach(([slot, list]) => { b.blocks[slot] = list.map(build); });
208
+ }
209
+ return b;
210
+ };
211
+ return comp.tree.map(build);
212
+ }
213
+
214
+ // Every instance of a component across the site's pages, for "used on" notes.
215
+ export function usesOf(pages, name) {
216
+ const out = [];
217
+ const visit = (blocks, page) => Object.values(blocks || {}).forEach((list) => (list || []).forEach((item) => {
218
+ if (item?.component === name) out.push(page);
219
+ visit(item?.blocks, page);
220
+ }));
221
+ pages.forEach((p) => visit(p.blocks, p));
222
+ return [...new Set(out)];
223
+ }
package/src/elevate.js ADDED
@@ -0,0 +1,74 @@
1
+ // Verso compiles CSS with the site's own copy of Elevate, through its API
2
+ // (elevate/core/api.ts). tsImport loads a fresh copy each call, so a token or
3
+ // config change is picked up by loading again.
4
+
5
+ import fs from 'fs';
6
+ import path from 'path';
7
+ import { pathToFileURL } from 'url';
8
+ import { tsImport } from 'tsx/esm/api';
9
+ import { VersoError } from './errors.js';
10
+
11
+ export async function loadElevate(root) {
12
+ const entry = path.join(root, 'elevate', 'core', 'api.ts');
13
+ if (!fs.existsSync(entry)) {
14
+ throw new VersoError("Elevate isn't set up in this site, so there's no CSS to build.", {
15
+ file: 'elevate/',
16
+ hint: 'Run "npx elevate-framework prepare" in the site folder.',
17
+ });
18
+ }
19
+ const api = await tsImport(pathToFileURL(entry).href, import.meta.url);
20
+ if (typeof api.build !== 'function') {
21
+ throw new VersoError('This copy of Elevate is too old for Verso. Verso needs Elevate 1.2 or later.', {
22
+ file: 'elevate/core/',
23
+ hint: 'Run "npm install elevate-framework@latest" and then "npx elevate-framework prepare".',
24
+ });
25
+ }
26
+ return api;
27
+ }
28
+
29
+ const summarize = (message) =>
30
+ (String(message || '').trim().split('\n').find((l) => l.trim()) || '')
31
+ .replace(/^[A-Za-z /-]+:\s+(?=[A-Z"])/, '')
32
+ .replace(/ in \S+ on line \d+/, '')
33
+ .trim();
34
+
35
+ // Elevate stops at the first bad class and names its file and line. Verso
36
+ // then checks the class list on that line, so the message names the class.
37
+ export function elevateError(api, message) {
38
+ const text = String(message || '').trim();
39
+ const where = / in (\S+) on line (\d+)/.exec(text);
40
+ const file = where ? where[1].split(path.sep).join('/') : null;
41
+ const line = where ? Number(where[2]) : null;
42
+ let culprit = null;
43
+ if (file && line) {
44
+ try {
45
+ const instance = api.scan().find((i) => i.file.split(path.sep).join('/') === file && i.lineNumber === line);
46
+ const problem = instance && api.validate(instance.rawValue || instance.classes.join(' ')).problems[0];
47
+ if (problem) culprit = problem;
48
+ } catch {
49
+ // Fall back to Elevate's own words.
50
+ }
51
+ }
52
+ const sentence = summarize(culprit ? culprit.message : text);
53
+ return new VersoError(culprit ? `The class "${culprit.token}" isn't valid. ${sentence}` : `Elevate can't compile a class. ${sentence}`, {
54
+ file,
55
+ line,
56
+ hint: culprit && /Unrecognized property/.test(culprit.message)
57
+ ? 'Change or remove that class. If it\'s a class for CSS of your own, start its name with a hyphen, like -card, and Elevate leaves it alone.'
58
+ : 'Change or remove that class in the template.',
59
+ });
60
+ }
61
+
62
+ // extra: class strings that live outside templates, like the rich text map
63
+ // in verso.json, so Elevate compiles them too.
64
+ export async function compileCSS(api, extra = []) {
65
+ const bad = [];
66
+ extra.forEach(({ classes, where, file, line }) => {
67
+ const problem = api.validate(classes).problems[0];
68
+ if (problem) bad.push(new VersoError(`The class "${problem.token}" isn't valid. ${summarize(problem.message)}`, { file: file || 'verso.json', line: line || null, hint: file ? 'Change or remove that class.' : `In ${where}.` }));
69
+ });
70
+ if (bad.length) return { ok: false, error: bad[0], warnings: [] };
71
+ const result = await api.build({ write: false, extra: extra.map((e) => e.classes) });
72
+ if (!result.ok) return { ok: false, error: elevateError(api, result.error), warnings: result.warnings };
73
+ return { ok: true, css: result.css, warnings: result.warnings };
74
+ }
package/src/errors.js ADDED
@@ -0,0 +1,46 @@
1
+ // Errors that read like a sentence and say where to look.
2
+
3
+ export class VersoError extends Error {
4
+ // A warning is worth saying but doesn't stop a build or a publish.
5
+ constructor(message, { file = null, line = null, hint = null, warning = false } = {}) {
6
+ super(message);
7
+ this.name = 'VersoError';
8
+ this.file = file;
9
+ this.line = line;
10
+ this.hint = hint;
11
+ this.warning = warning;
12
+ }
13
+
14
+ // "templates/home.html, line 12" or just the file.
15
+ get where() {
16
+ if (!this.file) return '';
17
+ return this.line ? `${this.file}, line ${this.line}` : this.file;
18
+ }
19
+
20
+ toJSON() {
21
+ return { message: this.message, file: this.file, line: this.line, hint: this.hint, where: this.where, ...(this.warning ? { warning: true } : {}) };
22
+ }
23
+ }
24
+
25
+ // Several problems found in one pass, reported together.
26
+ export class VersoErrors extends Error {
27
+ constructor(errors) {
28
+ super(errors.map((e) => e.message).join('\n'));
29
+ this.name = 'VersoErrors';
30
+ this.errors = errors;
31
+ }
32
+ }
33
+
34
+ export const lineAt = (text, index) => text.slice(0, index).split('\n').length;
35
+
36
+ // For the terminal.
37
+ export function formatError(error) {
38
+ const list = error instanceof VersoErrors ? error.errors : [error];
39
+ return list
40
+ .map((e) => {
41
+ const where = e.where ? `${e.where}\n ` : '';
42
+ const hint = e.hint ? `\n ${e.hint}` : '';
43
+ return `× ${where}${e.message}${hint}`;
44
+ })
45
+ .join('\n\n');
46
+ }