domma-cms 1.30.1 → 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.
Files changed (50) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/CLAUDE.md +36 -1
  3. package/admin/js/api.js +1 -1
  4. package/admin/js/lib/block-packs.js +26 -0
  5. package/admin/js/lib/block-tags.js +6 -1
  6. package/admin/js/lib/blocks-arrange.js +1 -1
  7. package/admin/js/lib/collection-editor-arrange.js +1 -1
  8. package/admin/js/lib/collection-entries-arrange.js +1 -1
  9. package/admin/js/lib/collections-arrange.js +1 -1
  10. package/admin/js/lib/list-tags-arrange.js +1 -1
  11. package/admin/js/lib/list-tags.js +9 -7
  12. package/admin/js/lib/pages-arrange.js +1 -1
  13. package/admin/js/lib/shortcode-context-menu.js +1 -1
  14. package/admin/js/lib/shortcode-form.js +7 -4
  15. package/admin/js/templates/blocks.html +5 -3
  16. package/admin/js/templates/collections.html +12 -2
  17. package/admin/js/templates/docs/usage-blocks.html +28 -1
  18. package/admin/js/templates/pages.html +5 -3
  19. package/admin/js/views/blocks.js +5 -4
  20. package/admin/js/views/collection-editor.js +10 -4
  21. package/admin/js/views/collection-entries.js +2 -2
  22. package/admin/js/views/collections.js +6 -5
  23. package/admin/js/views/page-editor.js +1 -1
  24. package/admin/js/views/pages.js +4 -4
  25. package/docs/DommaFeatures.md +156 -5
  26. package/docs/api-reference.md +8 -6
  27. package/docs/markdown-shortcodes.md +22 -1
  28. package/docs/starter-blocks.md +70 -1
  29. package/package.json +1 -1
  30. package/public/css/site.css +1 -1
  31. package/public/js/collection-browser.js +1 -1
  32. package/server/blocks/catalog.json +6 -0
  33. package/server/blocks/domma-block-cushion-card.css +30 -0
  34. package/server/blocks/domma-block-cushion-card.html +11 -0
  35. package/server/blocks/domma-block-cushion-card.meta.json +7 -0
  36. package/server/routes/api/block-packs.js +55 -0
  37. package/server/routes/api/blocks.js +16 -2
  38. package/server/routes/api/collections.js +9 -1
  39. package/server/routes/api/list-tags.js +35 -10
  40. package/server/routes/api/pages.js +16 -2
  41. package/server/services/block-pack-assets.js +6 -0
  42. package/server/services/block-packs.js +291 -0
  43. package/server/services/block-slots.js +43 -0
  44. package/server/services/block-write-lock.js +44 -0
  45. package/server/services/blocks.js +18 -3
  46. package/server/services/collections.js +6 -0
  47. package/server/services/listTags.js +243 -47
  48. package/server/services/markdown.js +105 -8
  49. package/server/services/starter-block-packs.js +22 -0
  50. package/server/templates/page.html +2 -2
@@ -1,16 +1,28 @@
1
1
  /**
2
- * List tags - admin-only labels that link pages (or blocks) together so the
3
- * Pages and Blocks lists can be narrowed to one tag. Nothing on the public
2
+ * List tags - admin-only labels that link pages, blocks or collections
3
+ * together so their lists can be narrowed to one tag. Nothing on the public
4
4
  * site reads them.
5
5
  *
6
- * An item may carry several. They live on the item itself: a page's
7
- * frontmatter `adminTags`, a block's sidecar `meta.adminTags`. A page's own
8
- * `tags` are a different thing - editorial, public (search, the Content API) -
9
- * and are never touched here.
6
+ * An item may carry several. Pages and blocks keep them on the item itself: a
7
+ * page's frontmatter `adminTags`, a block's sidecar `meta.adminTags`. A page's
8
+ * own `tags` are a different thing - editorial, public (search, the Content
9
+ * API) - and are never touched here. Collections keep theirs in
10
+ * config/list-tags.json (`collectionTags: {slug: [tags]}`), NOT in schema.json:
11
+ * seedAll() rewrites preset schemas on every boot and system collections are
12
+ * fixed. A stale entry for a collection that is gone is ignored, and deleting
13
+ * a collection drops its entry (dropCollectionTags).
10
14
  *
11
- * config/list-tags.json keeps the names per kind (`{pages: [], blocks: []}`)
12
- * so a tag can exist before anything wears it; a tag found on an item but not
13
- * in the file is still listed. Absence of the file = no names yet.
15
+ * config/list-tags.json keeps the names per kind (`{pages: [], blocks: [],
16
+ * collections: []}`) so a tag can exist before anything wears it; a tag found
17
+ * on an item but not in the file is still listed. Absence of the file = no
18
+ * names yet.
19
+ *
20
+ * Tool tags: every item a Tool owns wears that Tool's display name as a tag,
21
+ * derived on each read and never stored - a collection's `plugin` (or, for the
22
+ * built-in Tools' preset collections, PRESET_TOOL_COLLECTIONS), a block's
23
+ * `meta.plugin`, a page's frontmatter `plugin`. They list with `tool: true`;
24
+ * nobody can add, rename or delete one, and a manual tag may not take a Tool
25
+ * tag's name.
14
26
  *
15
27
  * Tagging is metadata, not an edit: a page's tags are written without a
16
28
  * revision and without moving its updatedAt.
@@ -18,11 +30,24 @@
18
30
  import {getConfig, saveConfig} from '../config.js';
19
31
  import {getPage, listPages, setPageFrontmatter} from './content.js';
20
32
  import {getBlock, listBlocks, setBlockMeta} from './blocks.js';
33
+ import {getCollection, listCollections} from './collections.js';
34
+ import {CORE_TOOLS} from './tools.js';
21
35
 
22
- export const KINDS = ['pages', 'blocks'];
36
+ export const KINDS = ['pages', 'blocks', 'collections'];
23
37
  export const MAX_TAG = 40;
24
38
  const CONFIG_NAME = 'list-tags';
25
39
 
40
+ /**
41
+ * The built-in Tools' preset collections, which carry no `plugin` of their own.
42
+ * Mirrored in admin/js/lib/list-tags-arrange.js (the admin cannot import server code).
43
+ */
44
+ export const PRESET_TOOL_COLLECTIONS = Object.freeze({
45
+ 'notes-notes': 'notes',
46
+ 'todo-items': 'todo',
47
+ 'contacts-contacts': 'contacts',
48
+ 'contacts-groups': 'contacts'
49
+ });
50
+
26
51
  /** One tag name as stored: trimmed, inner whitespace collapsed, capped. '' when unusable. */
27
52
  export function normaliseTag(name) {
28
53
  if (typeof name !== 'string') return '';
@@ -53,99 +78,252 @@ function assertKind(kind) {
53
78
  throw err;
54
79
  }
55
80
 
81
+ function badTag(message) {
82
+ const err = new Error(message);
83
+ err.code = 'BAD_TAG';
84
+ return err;
85
+ }
86
+
87
+ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
88
+
89
+ /** The collection tag map, cleaned: slug-shaped keys only, no empty lists. */
90
+ function cleanTagMap(map) {
91
+ const out = {};
92
+ if (!map || typeof map !== 'object' || Array.isArray(map)) return out;
93
+ for (const [slug, list] of Object.entries(map)) {
94
+ if (UNSAFE_KEYS.has(slug) || !/^[a-z0-9][a-z0-9_-]*$/i.test(slug)) continue;
95
+ const clean = cleanTagList(list);
96
+ if (clean.length) out[slug] = clean;
97
+ }
98
+ return out;
99
+ }
100
+
56
101
  function readRegistry() {
57
102
  let raw = {};
58
103
  try {
59
104
  raw = getConfig(CONFIG_NAME);
60
105
  } catch { /* absent or unreadable = no names yet */ }
61
- return Object.fromEntries(KINDS.map(k => [k, cleanTagList(raw?.[k])]));
106
+ return {
107
+ ...Object.fromEntries(KINDS.map(k => [k, cleanTagList(raw?.[k])])),
108
+ collectionTags: cleanTagMap(raw?.collectionTags)
109
+ };
62
110
  }
63
111
 
64
112
  function writeRegistry(reg) {
65
- saveConfig(CONFIG_NAME, Object.fromEntries(KINDS.map(k => [k, cleanTagList(reg[k])])));
113
+ saveConfig(CONFIG_NAME, {
114
+ ...Object.fromEntries(KINDS.map(k => [k, cleanTagList(reg[k])])),
115
+ collectionTags: cleanTagMap(reg.collectionTags)
116
+ });
117
+ }
118
+
119
+ /** Every collection's stored list tags, `{slug: [tags]}` - GET /api/collections puts them on each row. */
120
+ export function collectionTagMap() {
121
+ return readRegistry().collectionTags;
66
122
  }
67
123
 
68
- /** The items of a kind as `{id, tags}`, through the same listers the routes use. */
124
+ // ---- Tool tags ----
125
+
126
+ /** An unknown plugin's tag from its slug: "scraper-pro" -> "Scraper Pro". */
127
+ export function titleCaseSlug(slug) {
128
+ return String(slug || '').split(/[-_\s]+/).filter(Boolean).map(w => w[0].toUpperCase() + w.slice(1)).join(' ');
129
+ }
130
+
131
+ /** The slug of the Tool that owns an item of a kind, or ''. */
132
+ export function ownerOf(kind, raw) {
133
+ if (!raw) return '';
134
+ let owner = '';
135
+ if (kind === 'collections') owner = raw.plugin || PRESET_TOOL_COLLECTIONS[raw.slug] || '';
136
+ else if (kind === 'blocks') owner = raw.meta?.plugin || '';
137
+ else owner = raw.plugin || '';
138
+ return typeof owner === 'string' ? owner : '';
139
+ }
140
+
141
+ const TOOL_NAMES_TTL = 30_000;
142
+ let toolNamesCache = null;
143
+
144
+ /**
145
+ * Every Tool's display name by slug: the built-in Tools (services/tools.js),
146
+ * then each plugin manifest's `displayName`. Cached briefly - every list load
147
+ * asks, and discoverPlugins() reads every manifest.
148
+ *
149
+ * @returns {Promise<Object.<string, string>>}
150
+ */
151
+ export async function toolNames() {
152
+ if (toolNamesCache && Date.now() - toolNamesCache.at < TOOL_NAMES_TTL) return toolNamesCache.names;
153
+ const names = Object.fromEntries(CORE_TOOLS.map(t => [t.name, t.displayName]));
154
+ try {
155
+ const {discoverPlugins} = await import('./plugins.js');
156
+ for (const p of await discoverPlugins()) {
157
+ const display = typeof p.displayName === 'string' ? normaliseTag(p.displayName) : '';
158
+ if (display && typeof p.name === 'string') names[p.name] = display;
159
+ }
160
+ } catch { /* no plugins folder: the built-in names are enough */ }
161
+ toolNamesCache = {at: Date.now(), names};
162
+ return names;
163
+ }
164
+
165
+ /** Forget the cached Tool names (tests; after a plugin install). */
166
+ export function invalidateToolNames() { toolNamesCache = null; }
167
+
168
+ /** The Tool tag an item wears, or ''. */
169
+ function toolTagFor(kind, raw, names) {
170
+ const owner = ownerOf(kind, raw);
171
+ return owner ? normaliseTag(names[owner] || titleCaseSlug(owner)) : '';
172
+ }
173
+
174
+ /** The items of a kind as `{id, tags, raw}`, through the same listers the routes use. */
69
175
  async function items(kind) {
70
176
  if (kind === 'pages') return (await listPages()).map(p => ({id: p.urlPath, tags: cleanTagList(p.adminTags), raw: p}));
177
+ if (kind === 'collections') {
178
+ const map = readRegistry().collectionTags;
179
+ return (await listCollections()).map(c => ({id: c.slug, tags: cleanTagList(map[c.slug]), raw: c}));
180
+ }
71
181
  return (await listBlocks()).map(b => ({id: b.name, tags: cleanTagList(b.meta?.adminTags), raw: b}));
72
182
  }
73
183
 
74
184
  async function writeItemTags(kind, id, tags) {
75
185
  const clean = cleanTagList(tags);
76
186
  if (kind === 'pages') await setPageFrontmatter(id, {adminTags: clean.length ? clean : undefined});
77
- else await setBlockMeta(id, {adminTags: clean.length ? clean : undefined});
187
+ else if (kind === 'collections') {
188
+ const reg = readRegistry();
189
+ if (clean.length) reg.collectionTags[id] = clean;
190
+ else delete reg.collectionTags[id];
191
+ writeRegistry(reg);
192
+ } else await setBlockMeta(id, {adminTags: clean.length ? clean : undefined});
78
193
  return clean;
79
194
  }
80
195
 
81
196
  /**
82
- * Every tag of a kind with how many items wear it: the registry's names in
83
- * alphabetical order, plus any name only found on items.
197
+ * Names a manual tag may not take, lower-cased: every known Tool's display
198
+ * name, plus the Tool tags worn by items of `kind` (an unknown plugin's
199
+ * title-cased slug).
200
+ */
201
+ async function reservedNames(kind) {
202
+ const names = await toolNames();
203
+ const out = new Set(Object.values(names).map(n => normaliseTag(n).toLowerCase()));
204
+ for (const it of await items(kind)) {
205
+ const t = toolTagFor(kind, it.raw, names);
206
+ if (t) out.add(t.toLowerCase());
207
+ }
208
+ return out;
209
+ }
210
+
211
+ /** The Tool tags items of `kind` actually wear, lower-cased - the ones that cannot be renamed or deleted. */
212
+ async function wornToolTags(kind) {
213
+ const names = await toolNames();
214
+ const out = new Set();
215
+ for (const it of await items(kind)) {
216
+ const t = toolTagFor(kind, it.raw, names);
217
+ if (t) out.add(t.toLowerCase());
218
+ }
219
+ return out;
220
+ }
221
+
222
+ /**
223
+ * The manual tags an admin save may store: the incoming list without any
224
+ * Tool's name - except names the item already wore (a tag kept from before a
225
+ * Tool took its name). For saves that do not go through the tag routes (a page
226
+ * or block saved from its editor).
227
+ */
228
+ export async function keepManualTags(kind, incoming, stored = []) {
229
+ if (!Array.isArray(incoming)) return incoming;
230
+ const reserved = await reservedNames(kind);
231
+ const had = cleanTagList(stored);
232
+ return cleanTagList(incoming).filter(t => !reserved.has(t.toLowerCase()) || had.some(h => same(h, t)));
233
+ }
234
+
235
+ async function assertNotToolName(kind, list) {
236
+ if (!list.length) return;
237
+ const reserved = await reservedNames(kind);
238
+ const clash = list.find(t => reserved.has(normaliseTag(t).toLowerCase()));
239
+ if (clash) throw badTag(`"${normaliseTag(clash)}" is a Tool's tag - the Tool adds it itself. Pick another name.`);
240
+ }
241
+
242
+ /**
243
+ * Every tag of a kind with how many items wear it: the registry's names, any
244
+ * name only found on items, and the Tool tags (`tool: true`) of the Tools that
245
+ * own any visible item - alphabetical. An item wearing a manual tag spelled
246
+ * like its own Tool tag counts once.
84
247
  *
85
248
  * @param {string} kind
86
249
  * @param {(item: object) => boolean} [visible] - the caller's scope filter
87
- * @returns {Promise<{name: string, count: number}[]>}
250
+ * @returns {Promise<{name: string, count: number, tool?: true}[]>}
88
251
  */
89
252
  export async function listTags(kind, visible = () => true) {
90
253
  assertKind(kind);
91
254
  const names = [...readRegistry()[kind]];
255
+ const tools = [];
92
256
  const counts = new Map();
257
+ const nameMap = await toolNames();
93
258
  for (const it of await items(kind)) {
94
259
  if (!visible(it.raw)) continue;
95
- for (const t of it.tags) {
96
- const known = names.find(n => same(n, t));
97
- if (!known) names.push(t);
98
- const key = (known || t).toLowerCase();
260
+ const toolTag = toolTagFor(kind, it.raw, nameMap);
261
+ if (toolTag && !tools.some(n => same(n, toolTag))) tools.push(toolTag);
262
+ for (const t of cleanTagList([...(toolTag ? [toolTag] : []), ...it.tags])) {
263
+ if (!same(t, toolTag) && !names.some(n => same(n, t))) names.push(t);
264
+ const key = t.toLowerCase();
99
265
  counts.set(key, (counts.get(key) || 0) + 1);
100
266
  }
101
267
  }
102
- return cleanTagList(names)
268
+ const isTool = (n) => tools.some(t => same(t, n));
269
+ return cleanTagList([...tools, ...names])
103
270
  .sort((a, b) => a.localeCompare(b, undefined, {sensitivity: 'base'}))
104
- .map(name => ({name, count: counts.get(name.toLowerCase()) || 0}));
271
+ .map(name => ({name, count: counts.get(name.toLowerCase()) || 0, ...(isTool(name) && {tool: true})}));
105
272
  }
106
273
 
107
274
  /** Add a name to the registry (no item changes). Returns the stored spelling. */
108
275
  async function addTagNow(kind, name) {
109
276
  assertKind(kind);
110
277
  const tag = normaliseTag(name);
111
- if (!tag) {
112
- const err = new Error('A tag needs a name.');
113
- err.code = 'BAD_TAG';
114
- throw err;
115
- }
278
+ if (!tag) throw badTag('A tag needs a name.');
116
279
  const reg = readRegistry();
117
280
  const existing = reg[kind].find(n => same(n, tag));
118
281
  if (existing) return existing;
282
+ await assertNotToolName(kind, [tag]);
119
283
  reg[kind].push(tag);
120
284
  writeRegistry(reg);
121
285
  return tag;
122
286
  }
123
287
 
288
+ /** One item's stored (manual) tags, or null when the item does not exist. */
289
+ async function storedTags(kind, id) {
290
+ if (kind === 'pages') {
291
+ const page = await getPage(id);
292
+ return page ? cleanTagList(page.adminTags) : null;
293
+ }
294
+ if (kind === 'collections') {
295
+ const schema = await getCollection(id).catch(() => null);
296
+ return schema ? cleanTagList(readRegistry().collectionTags[id]) : null;
297
+ }
298
+ const block = await getBlock(id).catch(() => null);
299
+ return block ? cleanTagList(block.meta?.adminTags) : null;
300
+ }
301
+
124
302
  /**
125
303
  * Change one item's tags: `tags` replaces the list, `add` / `remove` patch the
126
304
  * stored one (read afresh here, so two quick changes from the menu both land).
127
- * Names it brings that the registry lacks are added to it.
305
+ * Names it brings that the registry lacks are added to it. A name the item
306
+ * does not wear yet may not be a Tool tag's.
128
307
  *
129
308
  * @param {string} kind
130
- * @param {string} id - urlPath or block name
309
+ * @param {string} id - urlPath, block name or collection slug
131
310
  * @param {{tags?: string[], add?: string[], remove?: string[]}} change
132
311
  * @returns {Promise<string[]>} the stored list
133
312
  */
134
313
  async function changeItemTagsNow(kind, id, {tags, add = [], remove = []} = {}) {
135
314
  assertKind(kind);
136
- let next;
137
- if (Array.isArray(tags)) next = tags;
138
- else {
139
- const item = kind === 'pages' ? await getPage(id) : await getBlock(id).catch(() => null);
140
- if (!item) {
141
- const err = new Error(`Not found: ${id}`);
142
- err.code = 'ENOENT';
143
- throw err;
144
- }
145
- const stored = cleanTagList(kind === 'pages' ? item.adminTags : item.meta?.adminTags);
146
- next = [...stored, ...(Array.isArray(add) ? add : [])]
147
- .filter(t => !(Array.isArray(remove) ? remove : []).some(r => same(r, t)));
315
+ const stored = await storedTags(kind, id);
316
+ if (!stored) {
317
+ const err = new Error(`Not found: ${id}`);
318
+ err.code = 'ENOENT';
319
+ throw err;
148
320
  }
321
+ const next = Array.isArray(tags) ? tags
322
+ : [...stored, ...(Array.isArray(add) ? add : [])]
323
+ .filter(t => !(Array.isArray(remove) ? remove : []).some(r => same(r, t)));
324
+ // Only names the item does not already wear are checked: a manual tag stored
325
+ // before a Tool took its name can still be kept or removed.
326
+ await assertNotToolName(kind, cleanTagList(next).filter(t => !stored.some(s => same(s, t))));
149
327
  const clean = await writeItemTags(kind, id, next);
150
328
  const reg = readRegistry();
151
329
  const fresh = clean.filter(t => !reg[kind].some(n => same(n, t)));
@@ -159,18 +337,21 @@ async function changeItemTagsNow(kind, id, {tags, add = [], remove = []} = {}) {
159
337
  /**
160
338
  * Rename a tag on every item the caller may see. Renaming onto an existing
161
339
  * tag merges the two. An item outside the caller's projects keeps the old
162
- * name, which then still lists (found on an item).
340
+ * name, which then still lists (found on an item). A Tool tag is neither
341
+ * renamed nor a rename's target.
163
342
  *
164
343
  * @returns {Promise<{name: string, changed: number}>}
165
344
  */
166
345
  async function renameTagNow(kind, from, to, visible = () => true) {
167
346
  assertKind(kind);
168
347
  const target = normaliseTag(to);
169
- if (!target) {
170
- const err = new Error('A tag needs a name.');
171
- err.code = 'BAD_TAG';
172
- throw err;
348
+ if (!target) throw badTag('A tag needs a name.');
349
+ // Only a Tool tag items of this kind wear is fixed; a manual tag that happens to share a Tool's name
350
+ // (made before that Tool existed) can still be renamed away or deleted.
351
+ if ((await wornToolTags(kind)).has(normaliseTag(from).toLowerCase())) {
352
+ throw badTag('A Tool\'s tag is added by the Tool - it cannot be renamed.');
173
353
  }
354
+ await assertNotToolName(kind, [target]);
174
355
  let changed = 0;
175
356
  for (const it of await items(kind)) {
176
357
  if (!visible(it.raw) || !it.tags.some(t => same(t, from))) continue;
@@ -185,11 +366,15 @@ async function renameTagNow(kind, from, to, visible = () => true) {
185
366
 
186
367
  /**
187
368
  * Delete a tag: it comes off every item the caller may see. The items stay.
369
+ * A Tool tag cannot be deleted.
188
370
  *
189
371
  * @returns {Promise<{changed: number}>}
190
372
  */
191
373
  async function deleteTagNow(kind, name, visible = () => true) {
192
374
  assertKind(kind);
375
+ if ((await wornToolTags(kind)).has(normaliseTag(name).toLowerCase())) {
376
+ throw badTag('A Tool\'s tag is added by the Tool - it cannot be deleted.');
377
+ }
193
378
  let changed = 0;
194
379
  for (const it of await items(kind)) {
195
380
  if (!visible(it.raw) || !it.tags.some(t => same(t, name))) continue;
@@ -202,6 +387,15 @@ async function deleteTagNow(kind, name, visible = () => true) {
202
387
  return {changed};
203
388
  }
204
389
 
390
+ /** A collection is gone: drop its entry from the tag map. */
391
+ function dropCollectionTagsNow(slug) {
392
+ const reg = readRegistry();
393
+ if (!Object.hasOwn(reg.collectionTags, slug)) return false;
394
+ delete reg.collectionTags[slug];
395
+ writeRegistry(reg);
396
+ return true;
397
+ }
398
+
205
399
  // Every change runs one after another: each is a read-modify-write of item
206
400
  // files and the registry, and two interleaved (a rename while someone tags a
207
401
  // page) would lose one of them.
@@ -218,3 +412,5 @@ export const changeItemTags = (kind, id, change) => serial(() => changeItemTagsN
218
412
  export const setItemTags = (kind, id, tags) => changeItemTags(kind, id, {tags});
219
413
  export const renameTag = (kind, from, to, visible) => serial(() => renameTagNow(kind, from, to, visible));
220
414
  export const deleteTag = (kind, name, visible) => serial(() => deleteTagNow(kind, name, visible));
415
+ /** A collection was deleted: its tags go too. Resolves true when it had some. */
416
+ export const dropCollectionTags = (slug) => serial(() => dropCollectionTagsNow(slug));
@@ -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 renderBlockFromAttrs(tmpl, attrs, blockName = '') {
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
- const rendered = fillTemplateLines(tmpl, (_, rawKey, key, fmt) => {
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
  /**
@@ -1748,6 +1836,10 @@ export async function renderCollectionFragment(attrs, { extraFilter = null, scop
1748
1836
  let fields = schema.fields || [];
1749
1837
  if (fieldFilter?.length) {
1750
1838
  fields = fieldFilter.map(name => fields.find(f => f.name === name) || { name, label: name });
1839
+ } else {
1840
+ // A field marked "not in lists" (listHidden) is left out unless fields="" names it.
1841
+ const shown = fields.filter(f => f.listHidden !== true);
1842
+ if (shown.length) fields = shown;
1751
1843
  }
1752
1844
  if (!fields.length && entries.length) {
1753
1845
  fields = Object.keys(entries[0].data || {}).map(k => ({ name: k, label: k }));
@@ -5218,6 +5310,7 @@ export function sanitizePageHtml(html) {
5218
5310
  * (a row-scoped `[view]`), so it must not share a role-keyed cache entry.
5219
5311
  */
5220
5312
  export async function parseMarkdown(raw, opts = {}) {
5313
+ opts = {...opts, [SLOT_BUDGET]:opts[SLOT_BUDGET] || {remaining:500}};
5221
5314
  const {data, content: written} = matter(raw);
5222
5315
  const content = unindentShortTags(written);
5223
5316
 
@@ -5238,10 +5331,14 @@ export async function parseMarkdown(raw, opts = {}) {
5238
5331
  const expiry = await applyShortcodeExpiry(expirySafe.scrubbed, {
5239
5332
  ...(opts.expiry || {}), urlPath: opts.urlPath || '/', parseAttrs: parseShortcodeAttrs
5240
5333
  });
5241
- const preprocessed = applyTransforms('markdown:beforeParse', expirySafe.restore(expiry.markdown));
5242
- const {output: withComponents, used: usedComponents} = collectAndRewriteComponents(preprocessed);
5334
+ const visible = expirySafe.restore(expiry.markdown);
5335
+ const preprocessed = opts[SLOT_FRAGMENT] ? visible : applyTransforms('markdown:beforeParse', visible);
5243
5336
  const tagSet = new Set();
5244
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);
5245
5342
  const withCollection = await processCollectionBlocks(withComponents, tagSet);
5246
5343
  const withView = await processViewBlocks(withCollection, tagSet, opts.user || null, flags);
5247
5344
  const withStaticBlock = await processStaticBlocks(withView, tagSet);
@@ -5276,11 +5373,11 @@ export async function parseMarkdown(raw, opts = {}) {
5276
5373
  const withCard = processCardBlocks(withGrid);
5277
5374
  const withBanner = processBannerBlocks(withCard);
5278
5375
  const withSlideover = processSlideoverBlocks(withBanner);
5279
- const rendered = marked.parse(withSlideover);
5376
+ const rendered = slots.restore(marked.parse(withSlideover));
5280
5377
 
5281
5378
  const sanitized = sanitizePageHtml(rendered);
5282
5379
 
5283
- const html = applyTransforms('markdown:afterParse', sanitized);
5380
+ const html = opts[SLOT_FRAGMENT] ? sanitized : applyTransforms('markdown:afterParse', sanitized);
5284
5381
 
5285
5382
  // Only emit component scripts for components that actually exist - missing
5286
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
+ }
@@ -25,7 +25,7 @@
25
25
  <link rel="stylesheet" href="/dist/domma/themes/domma-themes.css">
26
26
 
27
27
  <!-- Site CSS -->
28
- <link rel="stylesheet" href="/public/css/site.css?v=20261031-image-shortcode">
28
+ <link rel="stylesheet" href="/public/css/site.css?v=20261102-cb-full-width">
29
29
  <link rel="stylesheet" href="/public/css/forms.css?v=20261031-forms-reduce-motion">
30
30
  <!-- Menu item hover / current-page effects. Loaded after site.css so a
31
31
  menu's own highlight wins over the blanket link styling there. -->
@@ -183,7 +183,7 @@
183
183
  searchable / filterable / sortable / paginate attributes) -->
184
184
  <!-- Its range-filter arithmetic; a module that runs first and sets window.DommaCollectionRange -->
185
185
  <script src="/public/js/collection-range.mjs?v=20261025-range-slider" type="module"></script>
186
- <script src="/public/js/collection-browser.js?v=20261025-range-slider" defer></script>
186
+ <script src="/public/js/collection-browser.js?v=20261102-cb-full-width" defer></script>
187
187
  <!-- Core Forms logic engine (must run before forms.js and site.js) -->
188
188
  <script src="/public/js/form-logic-engine.js?v=20261031-forms-reduce-motion" defer></script>
189
189