domma-cms 1.31.0 → 1.32.0
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/CHANGELOG.md +6 -0
- package/CLAUDE.md +19 -1
- package/admin/js/lib/block-packs.js +26 -0
- package/admin/js/lib/block-tags.js +6 -1
- package/admin/js/lib/shortcode-context-menu.js +1 -1
- package/admin/js/lib/shortcode-form.js +7 -4
- package/admin/js/templates/docs/usage-blocks.html +28 -1
- package/admin/js/views/blocks.js +4 -4
- package/docs/DommaFeatures.md +87 -8
- package/docs/markdown-shortcodes.md +22 -1
- package/docs/starter-blocks.md +70 -1
- package/package.json +1 -1
- package/server/blocks/catalog.json +6 -0
- package/server/blocks/domma-block-cushion-card.css +30 -0
- package/server/blocks/domma-block-cushion-card.html +11 -0
- package/server/blocks/domma-block-cushion-card.meta.json +7 -0
- package/server/routes/api/block-packs.js +55 -0
- package/server/routes/api/blocks.js +4 -1
- package/server/services/block-pack-assets.js +6 -0
- package/server/services/block-packs.js +291 -0
- package/server/services/block-slots.js +43 -0
- package/server/services/block-write-lock.js +44 -0
- package/server/services/blocks.js +18 -3
- package/server/services/markdown.js +101 -8
- package/server/services/starter-block-packs.js +22 -0
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/** Portable, immutable block packs with conflict-checked installs and rollback. */
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {createHash, randomUUID} from 'node:crypto';
|
|
5
|
+
import {fileURLToPath} from 'node:url';
|
|
6
|
+
import {withBlockWriteLock} from './block-write-lock.js';
|
|
7
|
+
import {blockSlots} from './block-slots.js';
|
|
8
|
+
import {PACK_ASSET_NAME_RE as ASSET, PACK_MEDIA_RE, packAssetFilename} from './block-pack-assets.js';
|
|
9
|
+
|
|
10
|
+
const NAME = /^[a-z0-9][a-z0-9-]{0,79}$/;
|
|
11
|
+
const VERSION = /^\d+\.\d+\.\d+$/;
|
|
12
|
+
const fail = (message, statusCode = 400) => Object.assign(new Error(message), {statusCode});
|
|
13
|
+
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
14
|
+
const fingerprint = block => block ? hash([block.html, block.css]) : null;
|
|
15
|
+
const compare = (a, b) => {
|
|
16
|
+
const aa = a.split('.').map(Number), bb = b.split('.').map(Number);
|
|
17
|
+
for (let i = 0; i < 3; i++) if (aa[i] !== bb[i]) return aa[i] - bb[i];
|
|
18
|
+
return 0;
|
|
19
|
+
};
|
|
20
|
+
function identifier(value, pattern = NAME) {
|
|
21
|
+
if (typeof value !== 'string' || value.length > 80 || (pattern === VERSION && value.length > 32) || !pattern.test(value)) throw fail('Invalid pack, block name or version.');
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
async function readJson(file, fallback) {
|
|
25
|
+
try { return JSON.parse(await fs.readFile(file, 'utf8')); }
|
|
26
|
+
catch (error) { if (error.code === 'ENOENT' && fallback !== undefined) return fallback; throw error; }
|
|
27
|
+
}
|
|
28
|
+
async function atomic(file, value) {
|
|
29
|
+
await fs.mkdir(path.dirname(file), {recursive:true});
|
|
30
|
+
const staging = `${file}.${randomUUID()}.part`;
|
|
31
|
+
try { await fs.writeFile(staging, value); await fs.rename(staging, file); }
|
|
32
|
+
finally { await fs.rm(staging, {force:true}); }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function validatePack(raw) {
|
|
36
|
+
if (!raw || raw.format !== 'domma-block-pack' || ![1,2].includes(raw.schema)) throw fail('Unsupported block pack format.');
|
|
37
|
+
identifier(raw.id); identifier(raw.version, VERSION);
|
|
38
|
+
if (typeof raw.title !== 'string' || !raw.title.trim() || raw.title.length > 120) throw fail('Pack title is required (up to 120 characters).');
|
|
39
|
+
if (!Array.isArray(raw.blocks) || !raw.blocks.length || raw.blocks.length > 100) throw fail('A pack needs 1 to 100 blocks.');
|
|
40
|
+
if (Buffer.byteLength(JSON.stringify(raw)) > 2_000_000) throw fail('Block pack exceeds 2 MB.');
|
|
41
|
+
const names = new Set();
|
|
42
|
+
const blocks = raw.blocks.map(block => {
|
|
43
|
+
identifier(block?.name);
|
|
44
|
+
if (names.has(block.name)) throw fail(`Duplicate block: ${block.name}`);
|
|
45
|
+
names.add(block.name);
|
|
46
|
+
if (typeof block.html !== 'string' || block.html.length > 200_000 || typeof block.css !== 'string' || block.css.length > 50 * 1024) throw fail(`Invalid HTML or CSS for ${block.name}.`);
|
|
47
|
+
return {name:block.name, html:block.html, css:block.css};
|
|
48
|
+
});
|
|
49
|
+
if(raw.assets != null && (!Array.isArray(raw.assets) || raw.assets.length>30)) throw fail('A pack can carry up to 30 media assets.');
|
|
50
|
+
if(raw.assets?.length && raw.schema!==2) throw fail('Bundled media requires pack schema 2.');
|
|
51
|
+
const assetNames=new Set();
|
|
52
|
+
const assets=(raw.assets || []).map(asset=>{
|
|
53
|
+
if(!asset || !ASSET.test(asset.name) || assetNames.has(asset.name) || typeof asset.data!=='string' || asset.data.length>1_400_000) throw fail('Invalid or duplicate pack media asset.');
|
|
54
|
+
const bytes=Buffer.from(asset.data,'base64');
|
|
55
|
+
if(!bytes.length || bytes.length>1_000_000 || bytes.toString('base64')!==asset.data) throw fail('Pack assets need canonical base64 data.');
|
|
56
|
+
assetNames.add(asset.name);
|
|
57
|
+
return {name:asset.name,data:asset.data};
|
|
58
|
+
});
|
|
59
|
+
for(const block of blocks) for(const text of [block.html,block.css]) {
|
|
60
|
+
for(const m of text.matchAll(/pack-asset:([a-zA-Z0-9][a-zA-Z0-9._-]*)/g)) if(!assetNames.has(m[1])) throw fail(`Missing media asset: ${m[1]}`);
|
|
61
|
+
}
|
|
62
|
+
const requires = {...(raw.requires || {})};
|
|
63
|
+
if (raw.requires != null && (typeof raw.requires !== 'object' || Array.isArray(raw.requires))) throw fail('Invalid pack requirements.');
|
|
64
|
+
if (blocks.some(b => blockSlots(b.html).length)) requires.slots ??= 1;
|
|
65
|
+
if (requires.slots != null && requires.slots !== 1) throw fail('This pack requires an unsupported slots version.');
|
|
66
|
+
if (requires.cms != null) identifier(requires.cms, VERSION);
|
|
67
|
+
if (requires.plugins != null && (!Array.isArray(requires.plugins) || requires.plugins.length > 50)) throw fail('Invalid plugin requirements.');
|
|
68
|
+
for (const plugin of requires.plugins || []) identifier(plugin);
|
|
69
|
+
return {format:raw.format, schema:raw.schema, id:raw.id, version:raw.version, title:raw.title.trim(),
|
|
70
|
+
description:String(raw.description || '').slice(0, 1000), requires:{...(requires.cms ? {cms:requires.cms} : {}), ...(requires.slots ? {slots:requires.slots} : {}), ...(requires.plugins?.length ? {plugins:requires.plugins} : {})}, ...(assets.length ? {assets} : {}), blocks};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function createBlockPackStore(root = fileURLToPath(new URL('../../', import.meta.url))) {
|
|
74
|
+
root = path.resolve(root);
|
|
75
|
+
const directory = path.join(root, 'content/blocks');
|
|
76
|
+
const data = path.join(root, 'content/block-packs');
|
|
77
|
+
const serial = fn => withBlockWriteLock(root,fn);
|
|
78
|
+
const releasePath = (id, version) => path.join(data, 'catalogue', identifier(id), `${identifier(version, VERSION)}.json`);
|
|
79
|
+
const statePath = id => path.join(data, 'installed', `${identifier(id)}.json`);
|
|
80
|
+
const pendingPath = id => path.join(data, 'pending', `${identifier(id)}.json`);
|
|
81
|
+
async function block(name) {
|
|
82
|
+
identifier(name);
|
|
83
|
+
try {
|
|
84
|
+
const html = await fs.readFile(path.join(directory, `${name}.html`), 'utf8');
|
|
85
|
+
const css = await fs.readFile(path.join(directory, `${name}.css`), 'utf8').catch(e => { if(e.code === 'ENOENT') return ''; throw e; });
|
|
86
|
+
const meta = await readJson(path.join(directory, `${name}.meta.json`), null);
|
|
87
|
+
return {name, html, css, meta};
|
|
88
|
+
} catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
89
|
+
}
|
|
90
|
+
async function writeBlock(name, value) {
|
|
91
|
+
for (const [extension, content] of [['html',value?.html], ['css',value?.css || null], ['meta.json',value?.meta ? JSON.stringify(value.meta, null, 2)+'\n' : null]]) {
|
|
92
|
+
const file = path.join(directory, `${identifier(name)}.${extension}`);
|
|
93
|
+
if (content == null) await fs.rm(file, {force:true});
|
|
94
|
+
else await atomic(file, content);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
async function published(id, version) {
|
|
98
|
+
try { return validatePack(await readJson(releasePath(id,version))); }
|
|
99
|
+
catch(e) { if(e.code === 'ENOENT') throw fail('Pack version not found.',404); throw e; }
|
|
100
|
+
}
|
|
101
|
+
async function publish(raw) {
|
|
102
|
+
const pack = validatePack(raw);
|
|
103
|
+
return serial(async () => {
|
|
104
|
+
const file = releasePath(pack.id,pack.version);
|
|
105
|
+
const existing = await readJson(file, null);
|
|
106
|
+
if (existing && hash(existing) !== hash(pack)) throw fail('Published versions are immutable. Choose a new version.',409);
|
|
107
|
+
if (!existing) await atomic(file, JSON.stringify(pack, null, 2)+'\n');
|
|
108
|
+
return pack;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
async function list() {
|
|
112
|
+
const ids = await fs.readdir(path.join(data,'catalogue')).catch(e => { if(e.code === 'ENOENT') return []; throw e; });
|
|
113
|
+
const packs = [];
|
|
114
|
+
for (const id of ids.filter(id => NAME.test(id))) {
|
|
115
|
+
const files = await fs.readdir(path.join(data,'catalogue',id));
|
|
116
|
+
const versions = files.filter(n => n.endsWith('.json') && VERSION.test(n.slice(0,-5))).map(n => n.slice(0,-5)).sort(compare).reverse();
|
|
117
|
+
if (!versions.length) continue;
|
|
118
|
+
const latest = await published(id, versions[0]);
|
|
119
|
+
const installed = await readJson(statePath(id), null);
|
|
120
|
+
packs.push({id,title:latest.title,description:latest.description,versions,latest:latest.version,installed:installed?.version || null,blocks:latest.blocks.map(b => b.name)});
|
|
121
|
+
}
|
|
122
|
+
return packs;
|
|
123
|
+
}
|
|
124
|
+
async function assemble({id,version,title,description='',names,requires={},media=[]}) {
|
|
125
|
+
if (!Array.isArray(names) || names.length > 100 || !names.length) throw fail('Choose blocks for this pack.');
|
|
126
|
+
const blocks = [];
|
|
127
|
+
for (const name of names) {
|
|
128
|
+
const current = await block(name);
|
|
129
|
+
if (!current) throw fail(`Block not found: ${name}`,404);
|
|
130
|
+
blocks.push({name:current.name, html:current.html, css:current.css});
|
|
131
|
+
}
|
|
132
|
+
if(!Array.isArray(media) || media.length>30 || new Set(media).size!==media.length) throw fail('Choose up to 30 distinct media files.');
|
|
133
|
+
const mediaConfig=await readJson(path.join(root,'config/content.json'),{});
|
|
134
|
+
const mediaRoot=path.resolve(root,mediaConfig.mediaDir || 'content/media');
|
|
135
|
+
const assets=[];
|
|
136
|
+
for(const file of media) {
|
|
137
|
+
if(typeof file!=='string' || file!==path.basename(file) || file.includes('\\') || file.includes('\0') || !PACK_MEDIA_RE.test(file)) throw fail('Only local raster images and webfonts can be bundled.');
|
|
138
|
+
const stat=await fs.lstat(path.join(mediaRoot,file));
|
|
139
|
+
if(!stat.isFile() || stat.size>1_000_000) throw fail('Media assets must be regular files up to 1 MB.');
|
|
140
|
+
const bytes=await fs.readFile(path.join(mediaRoot,file));
|
|
141
|
+
const name=`media-${assets.length+1}${path.extname(file).toLowerCase()}`;
|
|
142
|
+
assets.push({name,data:bytes.toString('base64')});
|
|
143
|
+
for(const b of blocks) for(const key of ['html','css']) {
|
|
144
|
+
for(const url of new Set([`/media/${file}`,`/media/${encodeURIComponent(file)}`])) b[key]=b[key].replaceAll(url,`pack-asset:${name}`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return publish({format:'domma-block-pack',schema:assets.length ? 2 : 1,id,version,title,description,requires,assets,blocks});
|
|
148
|
+
}
|
|
149
|
+
async function compatibility(pack) {
|
|
150
|
+
const problems = [];
|
|
151
|
+
const pkg = await readJson(path.join(root,'package.json'),null);
|
|
152
|
+
if(!pkg?.version) return ['This site is missing its CMS installation.'];
|
|
153
|
+
if(pack.assets?.length && !await fs.access(path.join(root,'server/services/block-pack-assets.js')).then(()=>true,()=>false)) problems.push('This site needs a CMS update with bundled block pack media support.');
|
|
154
|
+
if (pack.requires.slots && !await fs.access(path.join(root,'server/services/block-slots.js')).then(()=>true,()=>false)) problems.push('This site needs a CMS update with Custom Block slots support.');
|
|
155
|
+
if (pack.requires.cms) {
|
|
156
|
+
const version = VERSION.test(pkg.dependencies?.['domma-cms'] || '') ? pkg.dependencies['domma-cms'] : pkg.version;
|
|
157
|
+
if (compare(version,pack.requires.cms) < 0) problems.push(`Requires CMS ${pack.requires.cms} or later.`);
|
|
158
|
+
}
|
|
159
|
+
for (const plugin of pack.requires.plugins || []) {
|
|
160
|
+
const states = await readJson(path.join(root,'config/plugins.json'),{});
|
|
161
|
+
if (!await readJson(path.join(root,'plugins',plugin,'plugin.json'),null) || states[plugin]?.enabled !== true) problems.push(`Requires plugin ${plugin}, switched on.`);
|
|
162
|
+
}
|
|
163
|
+
return problems;
|
|
164
|
+
}
|
|
165
|
+
async function plan(raw) {
|
|
166
|
+
const pack = validatePack(raw), current = await readJson(statePath(pack.id),null);
|
|
167
|
+
const owners = new Map();
|
|
168
|
+
const installs = await fs.readdir(path.join(data,'installed')).catch(e => { if(e.code === 'ENOENT') return []; throw e; });
|
|
169
|
+
for (const file of installs.filter(n => /^[a-z0-9][a-z0-9-]*\.json$/.test(n))) {
|
|
170
|
+
const state = await readJson(path.join(data,'installed',file));
|
|
171
|
+
if (state.id !== pack.id) for(const name of Object.keys(state.hashes)) owners.set(name,state.id);
|
|
172
|
+
}
|
|
173
|
+
const mediaConfig=await readJson(path.join(root,'config/content.json'),{});
|
|
174
|
+
const mediaRoot=path.resolve(root,mediaConfig.mediaDir || 'content/media');
|
|
175
|
+
const assetChanges=[];
|
|
176
|
+
for(const asset of pack.assets || []) {
|
|
177
|
+
const file=path.join(mediaRoot,packAssetFilename(pack,asset.name));
|
|
178
|
+
const before=await fs.readFile(file).catch(e=>{if(e.code==='ENOENT')return null;throw e;});
|
|
179
|
+
const bytes=Buffer.from(asset.data,'base64');
|
|
180
|
+
assetChanges.push({name:asset.name,file,bytes,before,action:before ? 'unchanged' : 'create',
|
|
181
|
+
conflict:before && !before.equals(bytes) ? `Pack media was locally edited: ${asset.name}` : !before && current?.version===pack.version ? `Pack media was locally deleted: ${asset.name}` : ''});
|
|
182
|
+
}
|
|
183
|
+
const resolve=text=>text.replace(/pack-asset:([a-zA-Z0-9][a-zA-Z0-9._-]*)/g,(_,name)=>{
|
|
184
|
+
if(!assetChanges.some(a=>a.name===name)) throw fail(`Missing media asset: ${name}`);
|
|
185
|
+
return `/media/${packAssetFilename(pack,name)}`;
|
|
186
|
+
});
|
|
187
|
+
const desired = new Map(pack.blocks.map(b => [b.name,{...b,html:resolve(b.html),css:resolve(b.css)}]));
|
|
188
|
+
const names = new Set([...desired.keys(), ...Object.keys(current?.hashes || {})]);
|
|
189
|
+
const changes = [];
|
|
190
|
+
for(const name of names) {
|
|
191
|
+
const before = await block(name), after = desired.get(name) || null;
|
|
192
|
+
const unchanged = fingerprint(before) === fingerprint(after);
|
|
193
|
+
const owned = current && Object.hasOwn(current.hashes,name);
|
|
194
|
+
// A block the site already had (identical, so the pack adopted it) is the site's: a version that
|
|
195
|
+
// leaves it out lets go of it rather than deleting it.
|
|
196
|
+
if (!after && owned && (current.adopted || []).includes(name)) {
|
|
197
|
+
changes.push({name,action:'release',conflict:fingerprint(before) === current.hashes[name] ? '' : 'Locally edited or deleted. Duplicate to customise before updating.',before,after:null,adopted:true});
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
let conflict = '';
|
|
201
|
+
if (owners.has(name)) conflict = `Owned by pack ${owners.get(name)}.`;
|
|
202
|
+
else if (before && !owned && !unchanged) conflict = 'An existing site block uses this name. Duplicate or rename it first.';
|
|
203
|
+
else if (owned && fingerprint(before) !== current.hashes[name]) conflict = 'Locally edited or deleted. Duplicate to customise before updating.';
|
|
204
|
+
changes.push({name,action:unchanged?'unchanged':after?(before?'update':'create'):'remove',conflict,before,after,
|
|
205
|
+
adopted:Boolean(after && ((before && !owned && unchanged) || (owned && (current.adopted || []).includes(name))))});
|
|
206
|
+
}
|
|
207
|
+
return {id:pack.id,version:pack.version,from:current?.version || null,problems:[...await compatibility(pack),...assetChanges.filter(a=>a.conflict).map(a=>a.conflict)],changes,current,pack,assetChanges};
|
|
208
|
+
}
|
|
209
|
+
const summary = p => ({id:p.id,version:p.version,from:p.from,problems:p.problems,assets:p.assetChanges.map(a=>({name:a.name,action:a.action})),changes:p.changes.map(({name,action,conflict}) => ({name,action,conflict})),
|
|
210
|
+
token:hash([p.pack,p.current,p.changes.map(c=>[c.name,c.before]),p.assetChanges.map(a=>[a.name,a.before?.toString('base64')])])});
|
|
211
|
+
async function preview(raw) {
|
|
212
|
+
// Under the write lock, so an interrupted install is undone first and never mistaken for local edits.
|
|
213
|
+
return serial(async () => { await recoverInterrupted(validatePack(raw).id); return summary(await plan(raw)); });
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* An install the process died in the middle of: the blocks it had written are put back from its snapshot (the
|
|
217
|
+
* state file was never moved on), so the site is as it was before and the install can simply be run again.
|
|
218
|
+
*/
|
|
219
|
+
async function recoverInterrupted(id) {
|
|
220
|
+
const pending = await readJson(pendingPath(id),null);
|
|
221
|
+
if (!pending) return false;
|
|
222
|
+
const state = await readJson(statePath(id),null);
|
|
223
|
+
if (!state?.history?.includes(pending.historyId)) {
|
|
224
|
+
const snapshot = await readJson(path.join(data,'history',`${pending.historyId}.json`),null);
|
|
225
|
+
for (const b of snapshot?.blocks || []) await writeBlock(b.name,b.value);
|
|
226
|
+
}
|
|
227
|
+
await fs.rm(pendingPath(id),{force:true});
|
|
228
|
+
return true;
|
|
229
|
+
}
|
|
230
|
+
async function install(raw, token) {
|
|
231
|
+
return serial(async () => {
|
|
232
|
+
await recoverInterrupted(validatePack(raw).id);
|
|
233
|
+
const p = await plan(raw), review = summary(p);
|
|
234
|
+
if (review.token !== token) throw fail('The installation changed. Preview it again before applying.',409);
|
|
235
|
+
if (p.problems.length || p.changes.some(c=>c.conflict)) throw fail('Pack has compatibility issues or local conflicts. Nothing was changed.',409);
|
|
236
|
+
const historyId = randomUUID();
|
|
237
|
+
const snapshot = {id:historyId,packId:p.id,at:new Date().toISOString(),before:p.current,blocks:p.changes.map(c=>({name:c.name,value:c.before})),after:null};
|
|
238
|
+
const next = {id:p.id,version:p.version,hashes:Object.fromEntries(p.changes.filter(c=>c.after).map(c=>[c.name,fingerprint(c.after)])),history:[...(p.current?.history || []),historyId],
|
|
239
|
+
adopted:p.changes.filter(c=>c.after && c.adopted).map(c=>c.name)};
|
|
240
|
+
snapshot.after = next;
|
|
241
|
+
await atomic(path.join(data,'history',`${historyId}.json`),JSON.stringify(snapshot));
|
|
242
|
+
const createdAssets=[];
|
|
243
|
+
try {
|
|
244
|
+
for(const asset of p.assetChanges) if(!asset.before) {await atomic(asset.file,asset.bytes);createdAssets.push(asset.file);}
|
|
245
|
+
await atomic(pendingPath(p.id),JSON.stringify({historyId}));
|
|
246
|
+
for (const c of p.changes) if(!['unchanged','release'].includes(c.action)) await writeBlock(c.name,c.after ? {...c.after,meta:c.before?.meta || null} : null);
|
|
247
|
+
await atomic(statePath(p.id),JSON.stringify(next));
|
|
248
|
+
await fs.rm(pendingPath(p.id),{force:true});
|
|
249
|
+
} catch (error) {
|
|
250
|
+
for(const c of p.changes) if(c.action !== 'release') await writeBlock(c.name,c.before);
|
|
251
|
+
await fs.rm(pendingPath(p.id),{force:true});
|
|
252
|
+
for(const file of createdAssets) await fs.rm(file,{force:true});
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
return {...review,historyId};
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
async function history(id) {
|
|
259
|
+
const state = await readJson(statePath(id),null);
|
|
260
|
+
const rows = [];
|
|
261
|
+
for(const key of state?.history || []) {
|
|
262
|
+
const record = await readJson(path.join(data,'history',`${key}.json`));
|
|
263
|
+
rows.push({id:key,at:record.at,from:record.before?.version || null,to:record.after.version});
|
|
264
|
+
}
|
|
265
|
+
return rows;
|
|
266
|
+
}
|
|
267
|
+
async function rollback(id) {
|
|
268
|
+
return serial(async () => {
|
|
269
|
+
await recoverInterrupted(id);
|
|
270
|
+
const current = await readJson(statePath(id),null);
|
|
271
|
+
if (!current?.history?.length) throw fail('No pack installation to roll back.',404);
|
|
272
|
+
const snapshot = await readJson(path.join(data,'history',`${current.history.at(-1)}.json`));
|
|
273
|
+
for(const name of Object.keys(current.hashes)) if(fingerprint(await block(name)) !== current.hashes[name]) throw fail(`Locally edited block ${name}; rollback cancelled.`,409);
|
|
274
|
+
for(const old of snapshot.blocks) if(!Object.hasOwn(current.hashes,old.name) && await block(old.name)) throw fail(`Block ${old.name} was recreated; rollback cancelled.`,409);
|
|
275
|
+
const before = await Promise.all(snapshot.blocks.map(async b=>({name:b.name,value:await block(b.name)})));
|
|
276
|
+
try {
|
|
277
|
+
for(const b of snapshot.blocks) {
|
|
278
|
+
const now=before.find(row=>row.name===b.name).value;
|
|
279
|
+
await writeBlock(b.name,b.value ? {...b.value,meta:now ? now.meta : b.value.meta} : null);
|
|
280
|
+
}
|
|
281
|
+
if(snapshot.before) await atomic(statePath(id),JSON.stringify(snapshot.before));
|
|
282
|
+
else await fs.rm(statePath(id),{force:true});
|
|
283
|
+
} catch(error) {
|
|
284
|
+
for(const b of before) await writeBlock(b.name,b.value);
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
return {id,version:snapshot.before?.version || null};
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
return {list,publish,published,assemble,preview,install,history,rollback};
|
|
291
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** Balanced block/slot syntax. Templates declare <slot name="body">fallback</slot>. */
|
|
2
|
+
export const SLOT_PATTERN = /<slot(?:\s+name=["']([a-z][\w-]*)["'])?\s*>([\s\S]*?)<\/slot\s*>/gi;
|
|
3
|
+
export function blockSlots(html) {
|
|
4
|
+
return [...new Set([...String(html || '').replace(/<!--[\s\S]*?-->/g, '').matchAll(SLOT_PATTERN)].map(m => m[1] || 'default'))];
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Outermost balanced [name]...[/name] pairs. Quoted brackets are part of attributes; only the supplied container
|
|
9
|
+
* tags take part. A closing tag pairs with the nearest open tag of its name, and opens it skips over are left
|
|
10
|
+
* unpaired: a stray `[my-card]` in prose never stops a later, properly closed call from being found.
|
|
11
|
+
*/
|
|
12
|
+
export function pairedRanges(text, names) {
|
|
13
|
+
const stack = [], pairs = [];
|
|
14
|
+
const re = /\[(\/)?([a-z][\w-]*)(?=[\s/\]])((?:"[^"]*"|'[^']*'|[^\]"'])*?)\]/gi;
|
|
15
|
+
for (const m of text.matchAll(re)) {
|
|
16
|
+
const name = m[2];
|
|
17
|
+
if (!names.has(name) || /\/\s*$/.test(m[3])) continue;
|
|
18
|
+
if (!m[1]) { stack.push({name, start:m.index, bodyStart:m.index + m[0].length, attrs:m[3]}); continue; }
|
|
19
|
+
const at = stack.findLastIndex(open => open.name === name);
|
|
20
|
+
if (at < 0) continue;
|
|
21
|
+
const open = stack[at];
|
|
22
|
+
stack.length = at;
|
|
23
|
+
pairs.push({...open, bodyEnd:m.index, end:m.index + m[0].length});
|
|
24
|
+
}
|
|
25
|
+
return pairs.filter(p => !pairs.some(q => q !== p && q.start < p.start && q.end >= p.end)).sort((a, b) => a.start - b.start);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Extract only direct slots, leaving nested blocks' slots with their owners. */
|
|
29
|
+
export function slotBodies(body, names, attrs) {
|
|
30
|
+
const result = new Map(), plain = [];
|
|
31
|
+
let cursor = 0;
|
|
32
|
+
for (const range of pairedRanges(body, new Set([...names, 'slot']))) {
|
|
33
|
+
if (range.name !== 'slot') continue;
|
|
34
|
+
const name = attrs(range.attrs).name || 'default';
|
|
35
|
+
plain.push(body.slice(cursor, range.start));
|
|
36
|
+
result.set(name, (result.get(name) || '') + body.slice(range.bodyStart, range.bodyEnd));
|
|
37
|
+
cursor = range.end;
|
|
38
|
+
}
|
|
39
|
+
plain.push(body.slice(cursor));
|
|
40
|
+
const rest = plain.join('').trim();
|
|
41
|
+
if (rest) result.set('default', rest);
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Serialise block edits and pack transactions, including a manager writing to a child site. */
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {setTimeout as delay} from 'node:timers/promises';
|
|
5
|
+
const queues=new Map();
|
|
6
|
+
|
|
7
|
+
export async function withBlockWriteLock(root, action) {
|
|
8
|
+
root=path.resolve(root);
|
|
9
|
+
const previous=queues.get(root) || Promise.resolve();
|
|
10
|
+
const run=previous.catch(()=>{}).then(async()=>{
|
|
11
|
+
const lock=path.join(root,'content','.block-write-lock');
|
|
12
|
+
await fs.mkdir(path.dirname(lock),{recursive:true});
|
|
13
|
+
const deadline=Date.now()+5000;
|
|
14
|
+
for(;;) {
|
|
15
|
+
try {await fs.mkdir(lock);break;}
|
|
16
|
+
catch(error) {
|
|
17
|
+
if(error.code!=='EEXIST')throw error;
|
|
18
|
+
// A crashed writer must not leave blocks permanently locked.
|
|
19
|
+
// Held longer than any block write takes: its owner died and its pid may since belong to
|
|
20
|
+
// another process, so the pid check alone would keep every save waiting forever.
|
|
21
|
+
const held=await fs.stat(lock).catch(()=>null);
|
|
22
|
+
if(held && Date.now()-held.mtimeMs>120_000) {await fs.rm(lock,{recursive:true,force:true});continue;}
|
|
23
|
+
try {
|
|
24
|
+
const owner=Number(await fs.readFile(path.join(lock,'owner'),'utf8'));
|
|
25
|
+
if(!Number.isSafeInteger(owner) || owner<=0) throw Object.assign(new Error('Missing lock owner'),{code:'ENOENT'});
|
|
26
|
+
try {process.kill(owner,0);}
|
|
27
|
+
catch(e) {if(e.code==='ESRCH') {await fs.rm(lock,{recursive:true,force:true});continue;}}
|
|
28
|
+
} catch(e) {
|
|
29
|
+
if(e.code==='ENOENT') {
|
|
30
|
+
const stat=await fs.stat(lock).catch(()=>null);
|
|
31
|
+
if(stat && Date.now()-stat.mtimeMs>60_000) {await fs.rm(lock,{recursive:true,force:true});continue;}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if(Date.now()>=deadline)throw Object.assign(new Error('Blocks are being changed by another operation. Try again.'),{statusCode:409});
|
|
35
|
+
await delay(25);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
try {await fs.writeFile(path.join(lock,'owner'),String(process.pid));return await action();}
|
|
39
|
+
finally {await fs.rm(lock,{recursive:true,force:true});}
|
|
40
|
+
});
|
|
41
|
+
queues.set(root,run);
|
|
42
|
+
try {return await run;}
|
|
43
|
+
finally {if(queues.get(root)===run)queues.delete(root);}
|
|
44
|
+
}
|
|
@@ -4,10 +4,12 @@
|
|
|
4
4
|
* Never overwrites existing files during seeding - user customisations are preserved.
|
|
5
5
|
*/
|
|
6
6
|
import fs from 'fs/promises';
|
|
7
|
+
import {withBlockWriteLock} from './block-write-lock.js';
|
|
7
8
|
import path from 'path';
|
|
8
9
|
import {fileURLToPath} from 'url';
|
|
9
10
|
import * as cache from './cache/index.js';
|
|
10
11
|
import {seedStarterBlocks} from './starter-blocks.js';
|
|
12
|
+
import {seedStarterBlockPacks} from './starter-block-packs.js';
|
|
11
13
|
|
|
12
14
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
13
15
|
const BLOCKS_DIR = path.resolve(__dirname, '../../content/blocks');
|
|
@@ -326,7 +328,7 @@ export async function getBlock(name) {
|
|
|
326
328
|
* @returns {Promise<{success: boolean, name: string}>}
|
|
327
329
|
* @throws {Error} With code INVALID_NAME on bad name, or CSS_TOO_LARGE when CSS exceeds cap
|
|
328
330
|
*/
|
|
329
|
-
|
|
331
|
+
async function saveBlockUnlocked(name, content, {bundled, css, meta, createOnly = false} = {}) {
|
|
330
332
|
assertValidName(name);
|
|
331
333
|
if (typeof css === 'string' && css.length > MAX_CSS_SIZE) {
|
|
332
334
|
const err = new Error(`CSS exceeds ${MAX_CSS_SIZE} byte limit`);
|
|
@@ -379,7 +381,7 @@ export async function saveBlock(name, content, {bundled, css, meta, createOnly =
|
|
|
379
381
|
* @returns {Promise<object>} the sidecar as written
|
|
380
382
|
* @throws {Error} With code INVALID_NAME, or ENOENT when the block is not found
|
|
381
383
|
*/
|
|
382
|
-
|
|
384
|
+
async function setBlockMetaUnlocked(name, patch) {
|
|
383
385
|
assertValidName(name);
|
|
384
386
|
await fs.access(blockFilePath(name));
|
|
385
387
|
let meta = {};
|
|
@@ -401,7 +403,7 @@ export async function setBlockMeta(name, patch) {
|
|
|
401
403
|
* @returns {Promise<void>}
|
|
402
404
|
* @throws {Error} With code INVALID_NAME or ENOENT when the block is not found
|
|
403
405
|
*/
|
|
404
|
-
|
|
406
|
+
async function deleteBlockUnlocked(name) {
|
|
405
407
|
assertValidName(name);
|
|
406
408
|
try {
|
|
407
409
|
await fs.unlink(blockFilePath(name));
|
|
@@ -430,9 +432,22 @@ export async function deleteBlock(name) {
|
|
|
430
432
|
*/
|
|
431
433
|
export async function seedDefaultBlocks() {
|
|
432
434
|
await seedStarterBlocks(BLOCKS_DIR);
|
|
435
|
+
await seedStarterBlockPacks();
|
|
433
436
|
for (const [name, content] of Object.entries(BLOCKS)) {
|
|
434
437
|
await seedBlock(name, content);
|
|
435
438
|
}
|
|
436
439
|
const names = Object.keys(BLOCKS).join(', ');
|
|
437
440
|
console.log(`[blocks] Seeded default blocks: ${names}`);
|
|
438
441
|
}
|
|
442
|
+
|
|
443
|
+
export async function saveBlock(...args) {
|
|
444
|
+
return withBlockWriteLock(path.resolve(__dirname, '../..'), () => saveBlockUnlocked(...args));
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export async function setBlockMeta(...args) {
|
|
448
|
+
return withBlockWriteLock(path.resolve(__dirname, '../..'), () => setBlockMetaUnlocked(...args));
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
export async function deleteBlock(...args) {
|
|
452
|
+
return withBlockWriteLock(path.resolve(__dirname, '../..'), () => deleteBlockUnlocked(...args));
|
|
453
|
+
}
|
|
@@ -9,6 +9,8 @@ import {marked} from 'marked';
|
|
|
9
9
|
import sanitizeHtml from 'sanitize-html';
|
|
10
10
|
import {readdir, readFile} from 'fs/promises';
|
|
11
11
|
import {AsyncLocalStorage} from 'node:async_hooks';
|
|
12
|
+
import {randomUUID} from 'node:crypto';
|
|
13
|
+
import {blockSlots, pairedRanges, slotBodies, SLOT_PATTERN} from './block-slots.js';
|
|
12
14
|
import path from 'path';
|
|
13
15
|
import {fileURLToPath} from 'url';
|
|
14
16
|
import {applyTransforms, getSanitizeExtensions, getShortcodeProcessors} from './hooks.js';
|
|
@@ -527,10 +529,10 @@ function renderCollectionBlocks(entries, blockTemplate, emptyMsg, ctaOpts, cols,
|
|
|
527
529
|
return `${styleTag}<div class="${wrapperClass}"${ctx}>\n${items.join('\n')}\n</div>`;
|
|
528
530
|
}
|
|
529
531
|
|
|
530
|
-
function
|
|
532
|
+
function fillBlockAttrs(tmpl, attrs) {
|
|
531
533
|
// Triple-brace raw pass-through and `{{field}}` (optional `:format`, e.g. `{{date:DD MMM YYYY}}`)
|
|
532
534
|
// in one pass, so a raw value is never read again for placeholders.
|
|
533
|
-
|
|
535
|
+
return fillTemplateLines(tmpl, (_, rawKey, key, fmt) => {
|
|
534
536
|
if (rawKey !== undefined) return String(attrs[rawKey] ?? '');
|
|
535
537
|
const raw = attrs[key] ?? '';
|
|
536
538
|
if (fmt) {
|
|
@@ -539,16 +541,100 @@ function renderBlockFromAttrs(tmpl, attrs, blockName = '') {
|
|
|
539
541
|
}
|
|
540
542
|
return escapeHtmlText(raw);
|
|
541
543
|
});
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function renderBlockFromAttrs(tmpl, attrs, blockName = '') {
|
|
547
|
+
const rendered = fillBlockAttrs(tmpl, attrs);
|
|
542
548
|
const extraClass = attrs.class ? ` ${escapeAttr(attrs.class)}` : '';
|
|
543
549
|
const idAttr = attrs.id ? ` id="${escapeAttr(attrs.id)}"` : '';
|
|
544
550
|
const dataBlockAttr = blockName ? ` data-block="${escapeAttr(blockName)}"` : '';
|
|
545
551
|
return `<div class="dm-static-block${extraClass}"${idAttr}${dataBlockAttr}>${rendered}</div>`;
|
|
546
552
|
}
|
|
547
553
|
|
|
554
|
+
// Rich slot content is rendered once, then restored after the outer shortcode pipeline.
|
|
555
|
+
// This prevents code examples and entry data inside a slot from becoming live tags again.
|
|
556
|
+
const SLOT_DEPTH = Symbol('block slot depth');
|
|
557
|
+
const SLOT_BUDGET = Symbol('block slot budget');
|
|
558
|
+
const SLOT_FRAGMENT = Symbol('block slot fragment');
|
|
559
|
+
async function processSlottedBlocks(content, opts, tagSet, flags, usedComponents) {
|
|
560
|
+
const safe = scrubCodeRegions(content, true);
|
|
561
|
+
const names = new Set(['block', ...await getBlockShortTagNames()]);
|
|
562
|
+
const protectedHtml = new Map();
|
|
563
|
+
const nonce = randomUUID();
|
|
564
|
+
const hold = html => {
|
|
565
|
+
const token = `<!--dm-slot-${nonce}-${protectedHtml.size}-->`;
|
|
566
|
+
protectedHtml.set(token, html);
|
|
567
|
+
return token;
|
|
568
|
+
};
|
|
569
|
+
// Paired tags can be nested under tags with the same name. Self-closing slot
|
|
570
|
+
// templates are included too, so their fallback content gets the same renderer.
|
|
571
|
+
const ranges = pairedRanges(safe.scrubbed, names);
|
|
572
|
+
const singles = /\[([a-z][\w-]*)(?=[\s/\]])((?:"[^"]*"|'[^']*'|[^\]"'])*?)\/\]/g;
|
|
573
|
+
for (const m of safe.scrubbed.matchAll(singles)) {
|
|
574
|
+
if (!names.has(m[1]) || ranges.some(r => m.index >= r.start && m.index < r.end)) continue;
|
|
575
|
+
ranges.push({name:m[1], attrs:m[2], start:m.index, end:m.index+m[0].length, self:true});
|
|
576
|
+
}
|
|
577
|
+
let output = safe.scrubbed;
|
|
578
|
+
const innerRestores = [];
|
|
579
|
+
// A paired call whose body is not slot content (no such block, or a block without slots) keeps its body as page
|
|
580
|
+
// content - its own paired calls expanded - so nothing is dropped and no later [block .../] pattern eats into it.
|
|
581
|
+
const keepBody = async (range, head = '') => {
|
|
582
|
+
const inner = await processSlottedBlocks(safe.restore(safe.scrubbed.slice(range.bodyStart, range.bodyEnd)), opts, tagSet, flags, usedComponents);
|
|
583
|
+
innerRestores.push(inner.restore);
|
|
584
|
+
output = output.slice(0, range.start) + head + inner.output + output.slice(range.end);
|
|
585
|
+
};
|
|
586
|
+
for (const range of ranges.sort((a,b) => b.start-a.start)) {
|
|
587
|
+
const attrs = parseShortcodeAttrs(range.attrs);
|
|
588
|
+
const name = range.name === 'block' ? attrs.template : range.name;
|
|
589
|
+
if (!name) { if (!range.self) await keepBody(range); continue; }
|
|
590
|
+
let template, css;
|
|
591
|
+
try { [template, css] = await Promise.all([loadBlockTemplate(name), loadBlockCss(name)]); }
|
|
592
|
+
catch { if (!range.self) await keepBody(range); continue; }
|
|
593
|
+
const hasSlots = blockSlots(template).length > 0;
|
|
594
|
+
if (range.self && !hasSlots) continue;
|
|
595
|
+
if (!hasSlots) { await keepBody(range, `[${range.name}${range.attrs.replace(/\s+$/, '')} /]`); continue; }
|
|
596
|
+
// Past the limits the block renders nothing (as a missing block does) rather than failing the whole page.
|
|
597
|
+
if (--opts[SLOT_BUDGET].remaining < 0 || (opts[SLOT_DEPTH] || 0) >= 24) {
|
|
598
|
+
output = output.slice(0, range.start) + output.slice(range.end);
|
|
599
|
+
continue;
|
|
600
|
+
}
|
|
601
|
+
tagSet.add(`block:${name}`);
|
|
602
|
+
const body = range.self ? '' : safe.scrubbed.slice(range.bodyStart, range.bodyEnd);
|
|
603
|
+
const bodies = slotBodies(body, names, parseShortcodeAttrs);
|
|
604
|
+
const renderedSlots = [];
|
|
605
|
+
// Protect declarations while parameters are filled, then fill each slot separately.
|
|
606
|
+
template = template.replace(SLOT_PATTERN, (_, slotName, fallback) => {
|
|
607
|
+
const key = slotName || 'default';
|
|
608
|
+
const token = `<!--dm-slot-source-${nonce}-${renderedSlots.length}-->`;
|
|
609
|
+
const source = bodies.has(key) ? safe.restore(bodies.get(key)) : fillBlockAttrs(applyTransforms('markdown:beforeParse', safe.restore(fallback)), attrs);
|
|
610
|
+
renderedSlots.push({token, source});
|
|
611
|
+
return token;
|
|
612
|
+
});
|
|
613
|
+
let html = buildBlockStyleTag(name, css) + renderBlockFromAttrs(template, attrs, name);
|
|
614
|
+
for (const slot of renderedSlots) {
|
|
615
|
+
// Prefix a blank line: slot text is a fragment, never YAML frontmatter.
|
|
616
|
+
const rendered = await parseMarkdown('\n' + slot.source, {...opts, [SLOT_DEPTH]:(opts[SLOT_DEPTH] || 0)+1, [SLOT_FRAGMENT]:true});
|
|
617
|
+
for (const tag of rendered.tags) tagSet.add(tag);
|
|
618
|
+
for (const component of rendered.usedComponents) usedComponents.add(component);
|
|
619
|
+
flags.perViewer ||= rendered.perViewer;
|
|
620
|
+
flags.hasExpiry ||= rendered.hasExpiry;
|
|
621
|
+
const held = hold(rendered.html);
|
|
622
|
+
html = html.replace(slot.token, () => held);
|
|
623
|
+
}
|
|
624
|
+
output = output.slice(0, range.start) + html + output.slice(range.end);
|
|
625
|
+
}
|
|
626
|
+
return {output:safe.restore(output), restore:html => {
|
|
627
|
+
// A function, never the string: "$&", "$$" and "$`" in slot content are text, not replacement patterns.
|
|
628
|
+
for (const [token, value] of protectedHtml) html = html.replaceAll(token, () => value);
|
|
629
|
+
for (const restore of innerRestores) html = restore(html);
|
|
630
|
+
return html;
|
|
631
|
+
}};
|
|
632
|
+
}
|
|
633
|
+
|
|
548
634
|
async function getBlockShortTagNames() {
|
|
549
635
|
try {
|
|
550
636
|
const files = await readdir(BLOCKS_DIR);
|
|
551
|
-
return files
|
|
637
|
+
return [...new Set([...files, ...[...(blockOverrides.getStore()?.keys() || [])].map(name => `${name}.html`)])]
|
|
552
638
|
.filter(f => f.endsWith('.html'))
|
|
553
639
|
.map(f => f.slice(0, -5))
|
|
554
640
|
.filter(name => /^[a-z0-9][a-z0-9-]*$/.test(name) && !BUILTIN_SHORTCODES.has(name));
|
|
@@ -566,6 +652,8 @@ async function getBlockShortTagNames() {
|
|
|
566
652
|
* @returns {Promise<string>}
|
|
567
653
|
*/
|
|
568
654
|
async function processStaticBlocks(content, tagSet) {
|
|
655
|
+
const safe = scrubCodeRegions(content, true);
|
|
656
|
+
content = safe.scrubbed;
|
|
569
657
|
// --- [block template="name" .../] ---
|
|
570
658
|
const pattern = /\[block\s+([\s\S]+?)\/\]/g;
|
|
571
659
|
const matches = [...content.matchAll(pattern)];
|
|
@@ -621,7 +709,7 @@ async function processStaticBlocks(content, tagSet) {
|
|
|
621
709
|
}
|
|
622
710
|
}
|
|
623
711
|
|
|
624
|
-
return output;
|
|
712
|
+
return safe.restore(output);
|
|
625
713
|
}
|
|
626
714
|
|
|
627
715
|
/**
|
|
@@ -5222,6 +5310,7 @@ export function sanitizePageHtml(html) {
|
|
|
5222
5310
|
* (a row-scoped `[view]`), so it must not share a role-keyed cache entry.
|
|
5223
5311
|
*/
|
|
5224
5312
|
export async function parseMarkdown(raw, opts = {}) {
|
|
5313
|
+
opts = {...opts, [SLOT_BUDGET]:opts[SLOT_BUDGET] || {remaining:500}};
|
|
5225
5314
|
const {data, content: written} = matter(raw);
|
|
5226
5315
|
const content = unindentShortTags(written);
|
|
5227
5316
|
|
|
@@ -5242,10 +5331,14 @@ export async function parseMarkdown(raw, opts = {}) {
|
|
|
5242
5331
|
const expiry = await applyShortcodeExpiry(expirySafe.scrubbed, {
|
|
5243
5332
|
...(opts.expiry || {}), urlPath: opts.urlPath || '/', parseAttrs: parseShortcodeAttrs
|
|
5244
5333
|
});
|
|
5245
|
-
const
|
|
5246
|
-
const
|
|
5334
|
+
const visible = expirySafe.restore(expiry.markdown);
|
|
5335
|
+
const preprocessed = opts[SLOT_FRAGMENT] ? visible : applyTransforms('markdown:beforeParse', visible);
|
|
5247
5336
|
const tagSet = new Set();
|
|
5248
5337
|
const flags = {perViewer: false, hasExpiry:expiry.hasExpiry};
|
|
5338
|
+
const slotComponents = new Set();
|
|
5339
|
+
const slots = await processSlottedBlocks(preprocessed, opts, tagSet, flags, slotComponents);
|
|
5340
|
+
const {output: withComponents, used: usedComponents} = collectAndRewriteComponents(slots.output);
|
|
5341
|
+
for (const component of slotComponents) usedComponents.add(component);
|
|
5249
5342
|
const withCollection = await processCollectionBlocks(withComponents, tagSet);
|
|
5250
5343
|
const withView = await processViewBlocks(withCollection, tagSet, opts.user || null, flags);
|
|
5251
5344
|
const withStaticBlock = await processStaticBlocks(withView, tagSet);
|
|
@@ -5280,11 +5373,11 @@ export async function parseMarkdown(raw, opts = {}) {
|
|
|
5280
5373
|
const withCard = processCardBlocks(withGrid);
|
|
5281
5374
|
const withBanner = processBannerBlocks(withCard);
|
|
5282
5375
|
const withSlideover = processSlideoverBlocks(withBanner);
|
|
5283
|
-
const rendered = marked.parse(withSlideover);
|
|
5376
|
+
const rendered = slots.restore(marked.parse(withSlideover));
|
|
5284
5377
|
|
|
5285
5378
|
const sanitized = sanitizePageHtml(rendered);
|
|
5286
5379
|
|
|
5287
|
-
const html = applyTransforms('markdown:afterParse', sanitized);
|
|
5380
|
+
const html = opts[SLOT_FRAGMENT] ? sanitized : applyTransforms('markdown:afterParse', sanitized);
|
|
5288
5381
|
|
|
5289
5382
|
// Only emit component scripts for components that actually exist - missing
|
|
5290
5383
|
// references are already harmless (sanitiser strips the tag) but we also
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** The bundled card pack follows the editable library; seeding never replaces a release. */
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import {createBlockPackStore} from './block-packs.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A published version is immutable and every site builds this one from its own server/blocks files, so changing any
|
|
7
|
+
* of these files means a new version here (tests/services/block-packs.test.js holds the files' fingerprint per version).
|
|
8
|
+
*/
|
|
9
|
+
export const DOMMA_CARDS = {version:'1.0.1', names:['domma-block-cushion-card','domma-block-service-card','domma-block-pricing-card','domma-block-team-card','domma-block-testimonial']};
|
|
10
|
+
|
|
11
|
+
export async function seedStarterBlockPacks() {
|
|
12
|
+
const store=createBlockPackStore();
|
|
13
|
+
try { await store.published('domma-cards',DOMMA_CARDS.version);return; }
|
|
14
|
+
catch(error) {if(error.statusCode!==404)throw error;}
|
|
15
|
+
const names=DOMMA_CARDS.names;
|
|
16
|
+
const blocks=[];
|
|
17
|
+
for(const name of names) blocks.push({name,
|
|
18
|
+
html:await fs.readFile(new URL(`../blocks/${name}.html`,import.meta.url),'utf8'),
|
|
19
|
+
css:await fs.readFile(new URL(`../blocks/${name}.css`,import.meta.url),'utf8')});
|
|
20
|
+
await store.publish({format:'domma-block-pack',schema:1,id:'domma-cards',version:DOMMA_CARDS.version,title:'Domma cards',
|
|
21
|
+
description:'Cushion, service, pricing, profile and testimonial designs. Editable parameters with rich content slots on the cushion card.',requires:{slots:1},blocks});
|
|
22
|
+
}
|