domma-cms 1.27.3 → 1.28.1

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 (62) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/CLAUDE.md +2 -2
  3. package/admin/js/app.js +4 -4
  4. package/admin/js/lib/chats-arrange.js +2 -0
  5. package/admin/js/lib/launchers-arrange.js +2 -0
  6. package/admin/js/lib/menu-item-help.js +1 -1
  7. package/admin/js/lib/page-image-hosts.js +2 -2
  8. package/admin/js/lib/shortcode-form.js +6 -6
  9. package/admin/js/lib/shortcode-registry.js +1 -1
  10. package/admin/js/templates/chat-knowledge.html +96 -0
  11. package/admin/js/templates/chats.html +146 -0
  12. package/admin/js/templates/docs/usage-chat.html +96 -0
  13. package/admin/js/templates/docs/usage-launchers.html +83 -0
  14. package/admin/js/templates/docs/usage-media.html +14 -0
  15. package/admin/js/templates/docs/usage-navigation.html +3 -0
  16. package/admin/js/templates/docs/usage-shortcodes.html +8 -0
  17. package/admin/js/templates/documentation.html +8 -0
  18. package/admin/js/templates/launchers.html +105 -0
  19. package/admin/js/views/chat-knowledge.js +60 -0
  20. package/admin/js/views/chats.js +53 -0
  21. package/admin/js/views/doc-pages.js +1 -1
  22. package/admin/js/views/index.js +1 -1
  23. package/admin/js/views/launchers.js +230 -0
  24. package/admin/js/views/menu-editor.js +22 -22
  25. package/admin/js/views/page-editor.js +10 -10
  26. package/docs/DommaFeatures.md +30 -0
  27. package/docs/markdown-shortcodes.md +69 -16
  28. package/package.json +1 -1
  29. package/public/css/image-zoom.css +1 -0
  30. package/public/css/launcher-chat.css +1 -0
  31. package/public/css/launchers.css +1 -0
  32. package/public/css/site.css +1 -1
  33. package/public/js/image-zoom.mjs +30 -0
  34. package/public/js/launcher-chat.mjs +47 -0
  35. package/public/js/launcher-settings.mjs +2 -0
  36. package/public/js/launchers.mjs +12 -0
  37. package/public/js/motion-control.mjs +1 -1
  38. package/public/js/site.js +1 -1
  39. package/server/routes/api/chat.js +203 -0
  40. package/server/routes/api/chats.js +235 -0
  41. package/server/routes/api/launchers.js +50 -0
  42. package/server/routes/launcher-public.js +96 -0
  43. package/server/server.js +33 -0
  44. package/server/services/adapterRegistry.js +4 -4
  45. package/server/services/adapters/FileAdapter.js +18 -0
  46. package/server/services/adapters/MongoAdapter.js +14 -0
  47. package/server/services/chat/conversation.js +458 -0
  48. package/server/services/chat/launcher-bridge.js +73 -0
  49. package/server/services/chat/matcher.js +324 -0
  50. package/server/services/chat/settings.js +118 -0
  51. package/server/services/chat/store.js +532 -0
  52. package/server/services/collectionAccess.js +16 -0
  53. package/server/services/docs.js +2 -0
  54. package/server/services/launchers.js +172 -0
  55. package/server/services/markdown.js +175 -4
  56. package/server/services/number-fields-migration.js +4 -0
  57. package/server/services/permissionRegistry.js +12 -0
  58. package/server/services/presetCollections.js +75 -2
  59. package/server/services/renderer.js +86 -18
  60. package/server/services/roles.js +1 -1
  61. package/server/services/tools.js +1 -0
  62. package/server/templates/page.html +4 -2
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Launchers - discs pinned to the window that open a page, a form, a block or
3
+ * a chat (Content > Launchers, admin/js/views/launchers.js).
4
+ *
5
+ * Stored in `config/launchers.json` as `{launchers: [...]}` - the site's own
6
+ * file, which the updater never touches. The shape and every rule about it is
7
+ * public/js/launcher-settings.mjs (pure, shared with the admin and the page);
8
+ * this module reads and writes the file, decides which launchers a page gets,
9
+ * and builds what the renderer injects.
10
+ *
11
+ * The Tool can be switched off (services/tools.js CORE_TOOLS `launchers`): off,
12
+ * no page carries a launcher and /_launcher/<id> answers 404, while the file
13
+ * and every launcher in it are kept.
14
+ *
15
+ * @module services/launchers
16
+ */
17
+ import {getConfig, saveConfig} from '../config.js';
18
+ import * as cache from './cache/index.js';
19
+ import {isToolEnabled} from './tools.js';
20
+ import {
21
+ LAUNCHER_ID_RE, launcherReady, launcherShowsOn, normaliseLauncher, normaliseLaunchers, publicLauncher
22
+ } from '../../public/js/launcher-settings.mjs';
23
+
24
+ /** Every cached page carries this tag (routes/public.js), so a save reaches them all. */
25
+ export const LAUNCHERS_CACHE_TAG = 'site';
26
+
27
+ /** Bumped by hand when launchers.mjs or launchers.css changes - the updater replaces public/ wholesale. */
28
+ export const LAUNCHERS_ASSET_V = '20261101-launchers-covering';
29
+
30
+ /** @returns {object[]} the stored launchers, normalised, in order; none when the file is missing or broken */
31
+ export function getLaunchers() {
32
+ try {
33
+ return normaliseLaunchers(getConfig('launchers'));
34
+ } catch {
35
+ return [];
36
+ }
37
+ }
38
+
39
+ /** @param {string} id @returns {object|null} */
40
+ export function getLauncher(id) {
41
+ if (typeof id !== 'string' || !LAUNCHER_ID_RE.test(id)) return null;
42
+ return getLaunchers().find(l => l.id === id) || null;
43
+ }
44
+
45
+ async function invalidatePages() {
46
+ try {
47
+ await cache.invalidateTags([LAUNCHERS_CACHE_TAG]);
48
+ } catch (err) {
49
+ console.warn(`[launchers] Page cache not invalidated: ${err.message}`);
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Save the whole list (the admin sends it whole: order, on/off and edits are
55
+ * one write, so two tabs cannot interleave half-lists).
56
+ *
57
+ * @param {object[]} list
58
+ * @returns {Promise<object[]>} what was stored
59
+ */
60
+ export async function saveLaunchers(list) {
61
+ const next = normaliseLaunchers(Array.isArray(list) ? list : []);
62
+ saveConfig('launchers', {launchers: next});
63
+ await invalidatePages();
64
+ return next;
65
+ }
66
+
67
+ /**
68
+ * Change one launcher (a patch over the stored one) - the list's on/off switch.
69
+ *
70
+ * @returns {Promise<object|null>} the stored launcher, or null when there is no such id
71
+ */
72
+ export async function updateLauncher(id, patch) {
73
+ const list = getLaunchers();
74
+ const at = list.findIndex(l => l.id === id);
75
+ if (at === -1) return null;
76
+ list[at] = normaliseLauncher({...list[at], ...(patch || {}), id});
77
+ const saved = await saveLaunchers(list);
78
+ return saved.find(l => l.id === id) || null;
79
+ }
80
+
81
+ /** @returns {boolean} the Tool is on (config/tools.json) */
82
+ export function launchersOn() {
83
+ try { return isToolEnabled('launchers'); } catch { return true; }
84
+ }
85
+
86
+ /**
87
+ * The launchers a page gets: switched on, with something to open, meant for
88
+ * this page and this viewer. Empty while the Tool is off.
89
+ *
90
+ * The page cache keys on the viewer's roles (routes/public.js), so a
91
+ * signed-in-only launcher never reaches an anonymous visitor's cached copy.
92
+ *
93
+ * @param {string} urlPath
94
+ * @param {object|null} user - the resolved viewer
95
+ * @returns {object[]} publicLauncher() objects
96
+ */
97
+ export function launchersForPage(urlPath, user) {
98
+ if (!launchersOn()) return [];
99
+ return getLaunchers()
100
+ .filter(l => launcherReady(l) && launcherShowsOn(l, urlPath, Boolean(user)))
101
+ .map(publicLauncher);
102
+ }
103
+
104
+ /**
105
+ * The enabled launchers whose action is a chat - the chat routes refuse to
106
+ * open a conversation when there is none (or the Tool is off).
107
+ *
108
+ * @returns {Promise<object[]>} normalised launchers
109
+ */
110
+ export async function chatLaunchers() {
111
+ if (!launchersOn()) return [];
112
+ return getLaunchers().filter(l => l.enabled && l.action.type === 'chat');
113
+ }
114
+
115
+ /**
116
+ * The stylesheet and script a page needs for its launchers, or nothing at all
117
+ * when it has none.
118
+ *
119
+ * @param {string} urlPath
120
+ * @param {object|null} user
121
+ * @returns {{headTag: string, bodyTag: string}}
122
+ */
123
+ export function buildLauncherAssets(urlPath, user) {
124
+ let list = [];
125
+ try {
126
+ list = launchersForPage(urlPath, user);
127
+ } catch (err) {
128
+ console.warn(`[launchers] Skipped: ${err.message}`);
129
+ }
130
+ if (!list.length) return {headTag: '', bodyTag: ''};
131
+ // Every `<` escaped: a label holding `<!--<script` must not change how the parser reads the page.
132
+ const json = JSON.stringify(list).replace(/</g, '\\u003c');
133
+ return {
134
+ headTag: `<link rel="stylesheet" href="/public/css/launchers.css?v=${LAUNCHERS_ASSET_V}">`,
135
+ bodyTag: `<script>window.__CMS_LAUNCHERS__ = ${json};</script>\n`
136
+ + `<script src="/public/js/launchers.mjs?v=${LAUNCHERS_ASSET_V}" type="module"></script>`
137
+ };
138
+ }
139
+
140
+ /**
141
+ * The sidebar badge (GET /api/launchers/_count): how many launchers there are,
142
+ * with the ones switched off and the ones switched on with nothing to open
143
+ * called out - a launcher that never appears is the one thing here worth a
144
+ * second look. Plain text throughout: the popover sets it with textContent.
145
+ *
146
+ * @param {object[]} [list]
147
+ * @returns {{count: number, label: string, tone: string, details: object}}
148
+ */
149
+ export function launchersBadge(list = getLaunchers(), toolOn = launchersOn()) {
150
+ const n = list.length;
151
+ const off = list.filter(l => !l.enabled);
152
+ const empty = list.filter(l => l.enabled && !launcherReady(l));
153
+ const bits = [!toolOn && 'the Tool is switched off', off.length && `${off.length} off`,
154
+ empty.length && `${empty.length} with nothing to open`].filter(Boolean);
155
+ const where = (l) => [l.position, l.action.type, l.enabled ? '' : 'off', empty.includes(l) ? 'nothing to open' : '']
156
+ .filter(Boolean).join(' · ');
157
+ return {
158
+ count: n,
159
+ label: `${n} launcher${n === 1 ? '' : 's'}${bits.length ? `, ${bits.join(', ')}` : ''}`,
160
+ tone: empty.length || !toolOn ? 'attention' : 'info',
161
+ details: {
162
+ title: 'Launchers',
163
+ rows: [
164
+ {label: 'On', value: String(n - off.length)},
165
+ {label: 'Off', value: String(off.length)},
166
+ {label: 'Nothing to open', value: String(empty.length), ...(empty.length && {tone: 'danger'})}
167
+ ],
168
+ items: list.slice(0, 8).map(l => ({text: l.name, meta: where(l), ...(empty.includes(l) && {tone: 'danger'})})),
169
+ empty: 'No launchers yet.'
170
+ }
171
+ };
172
+ }
@@ -37,7 +37,7 @@ const BLOCKS_DIR = path.resolve(__dirname_md, '../../content/blocks');
37
37
  export const BUILTIN_SHORTCODES = new Set([
38
38
  'block', 'collection', 'view', 'dconfig', 'component', 'tabs', 'tab',
39
39
  'accordion', 'item', 'carousel', 'slide', 'countdown', 'timeline',
40
- 'event', 'listgroup', 'spacer', 'center', 'icon', 'demo', 'embed', 'form', 'hero', 'table', 'badge',
40
+ 'event', 'listgroup', 'spacer', 'center', 'icon', 'demo', 'embed', 'image', 'form', 'hero', 'table', 'badge',
41
41
  'text', 'button', 'link', 'cta', 'grid', 'row', 'col', 'card', 'box',
42
42
  'banner', 'slideover', 'menu',
43
43
  // effects
@@ -3242,7 +3242,7 @@ function renderLegacyCard(attrs, body, markedInstance, escAttr) {
3242
3242
  */
3243
3243
  function processInlineShortcodes(markdown) {
3244
3244
  return processCtaBlocks(processLinkBlocks(processButtonBlocks(
3245
- processTextBlocks(processBadgeBlocks(markdown))
3245
+ processTextBlocks(processBadgeBlocks(processImageBlocks(markdown)))
3246
3246
  )));
3247
3247
  }
3248
3248
 
@@ -4393,6 +4393,177 @@ function processEmbedBlocks(markdown) {
4393
4393
  ));
4394
4394
  }
4395
4395
 
4396
+ // ─── [image] - a picture with options, optionally zoomable ─────────────────
4397
+
4398
+ const IMAGE_ALIGNS = ['left', 'center', 'right', 'float-left', 'float-right'];
4399
+ const IMAGE_FITS = ['cover', 'contain', 'fill', 'none', 'scale-down'];
4400
+ const IMAGE_SIZES = ['none', 'sm', 'md', 'lg'];
4401
+ const IMAGE_RADII = ['none', 'sm', 'md', 'lg', 'full'];
4402
+
4403
+ /** Attribute text, escaped, with brackets made inert so nothing re-reads it as a shortcode. */
4404
+ const _imageText = (v) => escapeAttr(String(v)).replace(/\[/g, '&#91;').replace(/\]/g, '&#93;');
4405
+
4406
+ /** A flag written as `zoom`, `zoom="true"`, `zoom="yes"` or `zoom="1"`. */
4407
+ const _imageFlag = (v) => v === true || ['true', 'yes', '1', 'on'].includes(String(v ?? '').trim().toLowerCase());
4408
+
4409
+ /**
4410
+ * A CSS length from an author's value: a bare number is pixels; px, %, rem, em,
4411
+ * vw, vh and ch are kept; `auto` is kept. Anything else is dropped (it would be
4412
+ * written into a style attribute).
4413
+ *
4414
+ * @param {*} v
4415
+ * @returns {string} '' when unusable
4416
+ */
4417
+ export function imageLength(v) {
4418
+ const s = String(v ?? '').trim().toLowerCase();
4419
+ if (s === 'auto') return s;
4420
+ const m = s.match(/^(\d+(?:\.\d+)?)(px|%|rem|em|vw|vh|ch)?$/);
4421
+ if (!m || Number(m[1]) === 0) return '';
4422
+ return m[1] + (m[2] || 'px');
4423
+ }
4424
+
4425
+ /**
4426
+ * An address an <img> or link may use: a path, http(s), or protocol-relative
4427
+ * `//host/…` (which takes the page's own scheme). `javascript:`,
4428
+ * `data:` and every other scheme are refused, as are values with quotes or
4429
+ * angle brackets. Spaces are encoded, as Insert → Image always did.
4430
+ *
4431
+ * @param {*} v
4432
+ * @returns {string} '' when refused
4433
+ */
4434
+ export function imageAddress(v) {
4435
+ const s = String(v ?? '').trim();
4436
+ if (!s || /["'<>`\\]/.test(s) || /[\u0000-\u001f]/.test(s)) return '';
4437
+ const scheme = s.match(/^([a-z][a-z0-9+.-]*):/i);
4438
+ if (scheme && !['http', 'https'].includes(scheme[1].toLowerCase())) return '';
4439
+ return s.replace(/ /g, '%20');
4440
+ }
4441
+
4442
+ /**
4443
+ * Render one [image] shortcode.
4444
+ *
4445
+ * A figure when the tag has its line to itself, so the caption can sit under
4446
+ * it; otherwise (in a sentence, a list item, a table cell) an inline span
4447
+ * holding just the picture - a figure inside a paragraph is not valid HTML.
4448
+ * Everything is on one line so a table row survives.
4449
+ *
4450
+ * `link` wins over `zoom`: a picture that goes somewhere when clicked cannot
4451
+ * also open the zoom view, so the zoom flag is ignored on a linked image.
4452
+ * The zoom view itself is public/js/image-zoom.mjs, which the renderer loads
4453
+ * only when the page has a `data-dm-zoom` picture.
4454
+ *
4455
+ * @param {object} attrs - parsed shortcode attributes
4456
+ * @param {{inline?: boolean}} [opts]
4457
+ * @returns {string}
4458
+ */
4459
+ export function renderImage(attrs = {}, opts = {}) {
4460
+ const src = imageAddress(attrs.src ?? attrs.url);
4461
+ if (!src) return '<span class="dm-image-missing">⚠ Image: give it a src (a /media/… path or an https:// address).</span>';
4462
+ const inline = !!opts.inline;
4463
+
4464
+ const classes = ['dm-image'];
4465
+ if (inline) classes.push('dm-image--inline');
4466
+ const align = String(attrs.align || '').toLowerCase();
4467
+ if (IMAGE_ALIGNS.includes(align)) classes.push(`dm-image--${align}`);
4468
+ const shadow = String(attrs.shadow || '').toLowerCase();
4469
+ if (IMAGE_SIZES.includes(shadow) && shadow !== 'none') classes.push(`dm-image--shadow-${shadow}`);
4470
+ if (_imageFlag(attrs.border)) classes.push('dm-image--border');
4471
+ const radiusWord = String(attrs.radius || '').toLowerCase();
4472
+ const radiusLen = IMAGE_RADII.includes(radiusWord) ? '' : imageLength(attrs.radius);
4473
+ if (IMAGE_RADII.includes(radiusWord) && radiusWord !== 'none') classes.push(`dm-image--radius-${radiusWord}`);
4474
+ const link = imageAddress(attrs.link);
4475
+ const zoom = !link && _imageFlag(attrs.zoom);
4476
+ if (zoom) classes.push('dm-image--zoom');
4477
+
4478
+ const boxStyle = [];
4479
+ const width = imageLength(attrs.width);
4480
+ if (width && width !== 'auto') boxStyle.push(`width:${width}`);
4481
+
4482
+ const imgStyle = [];
4483
+ const maxWidth = imageLength(attrs['max-width']);
4484
+ if (maxWidth && maxWidth !== 'auto') imgStyle.push(`max-width:min(100%,${maxWidth})`);
4485
+ const height = imageLength(attrs.height);
4486
+ if (height && height !== 'auto') {
4487
+ imgStyle.push(`height:${height}`);
4488
+ classes.push('dm-image--height');
4489
+ }
4490
+ const fit = String(attrs.fit || '').toLowerCase();
4491
+ if (IMAGE_FITS.includes(fit)) imgStyle.push(`object-fit:${fit}`);
4492
+ else if (height && height !== 'auto') imgStyle.push('object-fit:cover');
4493
+ if (radiusLen && radiusLen !== 'auto') imgStyle.push(`border-radius:${radiusLen}`);
4494
+ // The author's own classes last.
4495
+ if (attrs.class) classes.push(...String(attrs.class).split(/\s+/).filter(c => /^[\w-]+$/.test(c)));
4496
+
4497
+ const alt = attrs.alt === true ? '' : String(attrs.alt ?? '');
4498
+ const caption = attrs.caption === true ? '' : String(attrs.caption ?? '').trim();
4499
+ const title = attrs.title === true ? '' : String(attrs.title ?? '').trim();
4500
+ const loading = String(attrs.loading || '').toLowerCase() === 'eager' ? 'eager' : 'lazy';
4501
+
4502
+ let img = `<img class="dm-image-img" src="${escapeAttr(src)}" alt="${_imageText(alt)}"`;
4503
+ if (title) img += ` title="${_imageText(title)}"`;
4504
+ img += ` loading="${loading}"`;
4505
+ if (imgStyle.length) img += ` style="${imgStyle.join(';')}"`;
4506
+ if (zoom) {
4507
+ const full = imageAddress(attrs['zoom-src']) || src;
4508
+ img += ` data-dm-zoom="1" data-zoom-src="${escapeAttr(full)}"`;
4509
+ const group = String(attrs.group ?? '').trim();
4510
+ if (group && group !== 'true') img += ` data-zoom-group="${_imageText(group.slice(0, 60))}"`;
4511
+ if (caption) img += ` data-zoom-caption="${_imageText(caption)}"`;
4512
+ }
4513
+ img += '>';
4514
+
4515
+ if (link) {
4516
+ const target = String(attrs.target || '').toLowerCase();
4517
+ const blank = target === '_blank' || target === 'blank' || target === 'new';
4518
+ img = `<a class="dm-image-link" href="${escapeAttr(link)}"${blank ? ' target="_blank" rel="noopener noreferrer"' : ''}>${img}</a>`;
4519
+ }
4520
+
4521
+ // The frame shrinks to the picture, so the zoom hint sits on its corner, not the column's.
4522
+ img = `<span class="dm-image-frame">${img}</span>`;
4523
+ const id = /^[A-Za-z][\w-]*$/.test(String(attrs.id || '')) ? ` id="${attrs.id}"` : '';
4524
+ const style = boxStyle.length ? ` style="${boxStyle.join(';')}"` : '';
4525
+ const tag = inline ? 'span' : 'figure';
4526
+ const cap = !inline && caption ? `<figcaption class="dm-image-caption">${_imageText(caption)}</figcaption>` : '';
4527
+ return `<${tag} class="${classes.join(' ')}"${id}${style}>${img}${cap}</${tag}>`;
4528
+ }
4529
+
4530
+ /**
4531
+ * Pre-process [image] self-closing shortcodes.
4532
+ *
4533
+ * Syntax:
4534
+ * [image src="/media/screen.png" alt="The settings screen" zoom="true" /]
4535
+ * [image src="/media/a.png" caption="Step 1" width="480" align="center" zoom group="tour" /]
4536
+ *
4537
+ * Attributes: src (required), alt, caption, title, width, max-width, height,
4538
+ * fit, align (left|center|right|float-left|float-right), radius, border,
4539
+ * shadow, loading (lazy|eager), link, target, zoom, zoom-src, group, class, id.
4540
+ * See renderImage() and docs/markdown-shortcodes.md.
4541
+ *
4542
+ * Runs in the main pipeline beside [embed] and through processInlineShortcodes(),
4543
+ * so it works inside every container that renders its own body (cards, grids,
4544
+ * tabs, accordions, slideovers, effects).
4545
+ *
4546
+ * @param {string} markdown
4547
+ * @returns {string}
4548
+ */
4549
+ export function processImageBlocks(markdown) {
4550
+ if (!/\[image[\s/]/i.test(markdown)) return markdown;
4551
+ const {scrubbed, restore} = scrubCodeRegions(markdown);
4552
+ // Attributes or a `/` make it the shortcode. A bare [image] is left alone: it is a
4553
+ // Markdown reference label (`![Shot][image]`, `[image]: /media/shot.png`) or prose.
4554
+ return restore(scrubbed.replace(/\[image(?=[\s/])((?:"[^"]*"|'[^']*'|[^\]"'])*?)\/?\]/gi, (match, attrStr, offset, whole) => {
4555
+ const lineStart = whole.lastIndexOf('\n', offset - 1) + 1;
4556
+ const nl = whole.indexOf('\n', offset + match.length);
4557
+ const lineEnd = nl === -1 ? whole.length : nl;
4558
+ const before = whole.slice(lineStart, offset);
4559
+ const alone = !before.trim() && !whole.slice(offset + match.length, lineEnd).trim();
4560
+ const html = renderImage(parseShortcodeAttrs(attrStr || ''), {inline: !alone});
4561
+ // On its own line the figure keeps the line's indent, so one indented under a list
4562
+ // item stays inside that item instead of ending the list.
4563
+ return alone ? `\n${before}${html}\n` : html;
4564
+ }));
4565
+ }
4566
+
4396
4567
  /**
4397
4568
  * Pre-process [form] self-closing shortcodes before running through marked.
4398
4569
  *
@@ -5032,7 +5203,7 @@ export async function parseMarkdown(raw, opts = {}) {
5032
5203
  // with "Shortcode Nesting Rules" in CLAUDE.md and docs/markdown-shortcodes.md):
5033
5204
  // beforeParse → components ([component] / <dm-*>) → collection → view → block (+ short tags) → menu
5034
5205
  // → dconfig → effects → plugin shortcodes → tabs → accordion → carousel → countdown → timeline
5035
- // → listgroup → spacer → center → icon → demo → embed → form → hero → table
5206
+ // → listgroup → spacer → center → icon → demo → embed → image → form → hero → table
5036
5207
  // → badge → text → button → link → cta → grid → card (+ box) → banner → slideover
5037
5208
  // → marked → sanitize → afterParse
5038
5209
  // Comments must be removed before shortcodes are expanded. Protect code
@@ -5070,7 +5241,7 @@ export async function parseMarkdown(raw, opts = {}) {
5070
5241
  const withCenter = processCenterBlocks(withSwitcher);
5071
5242
  const withIcon = processIconBlocks(withCenter);
5072
5243
  const withDemo = processDemoBlocks(withIcon);
5073
- const withEmbed = processEmbedBlocks(withDemo);
5244
+ const withEmbed = processImageBlocks(processEmbedBlocks(withDemo));
5074
5245
  const withForm = await processFormBlocks(withEmbed, tagSet);
5075
5246
  const withHero = processHeroBlocks(withForm);
5076
5247
  const withTable = processTableBlocks(withHero);
@@ -21,6 +21,7 @@ import fs from 'fs/promises';
21
21
  import path from 'path';
22
22
  import {config} from '../config.js';
23
23
  import {numberFieldNames, numberFromText, withNumbers} from './entryValues.js';
24
+ import {CHAT_PRESET_SLUGS} from './presetCollections.js';
24
25
 
25
26
  export const MIGRATION_ID = 'number-field-types';
26
27
 
@@ -69,6 +70,9 @@ export async function migrateNumberFields({markerPath = defaultMarkerPath(), for
69
70
  for (const schema of await listCollections()) {
70
71
  const names = numberFieldNames(schema);
71
72
  if (!names.length) continue;
73
+ // The chat presets came after 0.78.0, so nothing stored text in them - and they declare
74
+ // MongoDB, which a site without it would leave "pending" at every start.
75
+ if (CHAT_PRESET_SLUGS.includes(schema.slug)) continue;
72
76
  try {
73
77
  const adapter = await getAdapter(schema.slug);
74
78
  // A MongoDB collection whose connection is down resolves to the file adapter,
@@ -295,6 +295,18 @@ export const REGISTRY = [
295
295
  group: 'Tools',
296
296
  actions: [{key: 'read', label: 'Use', description: 'Use Calculator'}]
297
297
  },
298
+ {
299
+ key: 'chats',
300
+ label: 'Chats',
301
+ description: 'Visitor chat from a Launcher: the inbox of chats, answering visitors, and the bot\'s Knowledge.',
302
+ icon: 'message-circle',
303
+ group: 'Tools',
304
+ actions: [
305
+ {key: 'read', label: 'View', description: 'See the chats and what visitors asked'},
306
+ {key: 'reply', label: 'Answer', description: 'Answer visitors, close chats and show as available'},
307
+ {key: 'manage', label: 'Manage', description: 'Edit the Knowledge, the unanswered list and the chat settings; delete chats'}
308
+ ]
309
+ },
298
310
  {
299
311
  key: 'plugins',
300
312
  label: 'Plugins',
@@ -12,6 +12,16 @@ const COLLECTIONS_DIR = path.resolve(config.content.collectionsDir);
12
12
  // contacts, enquiries, feedback, notes, categories, posts, comments, to-do
13
13
  // have been removed - they belong to plugins and are seeded on plugin enable.
14
14
 
15
+ /** A chat preset: system-managed, no public API, MongoDB where the site can have it. */
16
+ function chatPreset(slug, title, description, fields) {
17
+ const closed = {enabled: false, access: 'admin'};
18
+ return [{
19
+ slug, title, description, preset: true, systemManaged: true, fields,
20
+ api: {create: closed, read: closed, update: closed, delete: closed},
21
+ storage: {adapter: 'mongodb', connection: 'default'}
22
+ }];
23
+ }
24
+
15
25
  const PRESETS = [
16
26
  {
17
27
  slug: 'notifications',
@@ -460,7 +470,60 @@ const PRESETS = [
460
470
  "adapter": "file"
461
471
  },
462
472
  "preset": true
463
- }
473
+ },
474
+ // ---- Chat (Launchers' chat: the bot's Knowledge, visitor chats) ------
475
+ // Site data, not anyone's own, but stored like the user-data presets: in
476
+ // MongoDB where the site has a working connection and these hold no rows in
477
+ // files, otherwise files (MONGO_ELIGIBLE_PRESET_SLUGS below). Read and written
478
+ // through services/chat/store.js; the generic collections API needs
479
+ // chats.manage for them (collectionAccess.js).
480
+ ...chatPreset('chat-knowledge', 'Chat Knowledge', 'What the chat bot knows: questions, the other ways people ask them, and the answers.', [
481
+ {name: 'question', label: 'Question', type: 'text', required: true},
482
+ {name: 'alternatives', label: 'Other ways of asking', type: 'textarea'},
483
+ {name: 'keywords', label: 'Keywords', type: 'text'},
484
+ {name: 'answer', label: 'Answer', type: 'textarea', required: true},
485
+ {name: 'links', label: 'Links', type: 'json'},
486
+ {name: 'enabled', label: 'Enabled', type: 'boolean', default: true},
487
+ {name: 'hits', label: 'Times answered', type: 'number', default: 0},
488
+ {name: 'lastUsedAt', label: 'Last answered', type: 'datetime'},
489
+ {name: 'sample', label: 'Example entry', type: 'boolean', default: false}
490
+ ]),
491
+ ...chatPreset('chat-sessions', 'Chat Sessions', 'Visitor chats: who, where, and whether someone is waiting.', [
492
+ {name: 'tokenHash', label: 'Token hash', type: 'hidden', required: true},
493
+ {name: 'launcherId', label: 'Launcher', type: 'text'},
494
+ {name: 'status', label: 'Status', type: 'select', options: ['bot', 'waiting', 'open', 'message', 'closed'], default: 'bot'},
495
+ {name: 'visitorName', label: 'Name', type: 'text'},
496
+ {name: 'visitorEmail', label: 'Email', type: 'text'},
497
+ {name: 'page', label: 'Page', type: 'text'},
498
+ {name: 'summary', label: 'First question', type: 'text'},
499
+ {name: 'count', label: 'Messages', type: 'number', default: 0},
500
+ {name: 'unread', label: 'Unread by staff', type: 'number', default: 0},
501
+ {name: 'misses', label: 'Unanswered in a row', type: 'number', default: 0},
502
+ {name: 'askDetails', label: 'Details asked for', type: 'boolean', default: false},
503
+ {name: 'assignedTo', label: 'Answered by (id)', type: 'text'},
504
+ {name: 'assignedName', label: 'Answered by', type: 'text'},
505
+ {name: 'lastAt', label: 'Last activity', type: 'datetime'},
506
+ {name: 'waitingSince', label: 'Waiting since', type: 'datetime'},
507
+ {name: 'closedAt', label: 'Closed', type: 'datetime'}
508
+ ]),
509
+ ...chatPreset('chat-messages', 'Chat Messages', 'Every message of every visitor chat, in order.', [
510
+ {name: 'sessionId', label: 'Chat', type: 'text', required: true},
511
+ {name: 'n', label: 'Number', type: 'number', required: true},
512
+ {name: 'from', label: 'From', type: 'select', options: ['visitor', 'bot', 'staff', 'system'], required: true},
513
+ {name: 'text', label: 'Text', type: 'textarea'},
514
+ {name: 'answerId', label: 'Knowledge entry', type: 'text'},
515
+ {name: 'suggestions', label: 'Suggestions', type: 'json'},
516
+ {name: 'staffName', label: 'Staff name', type: 'text'}
517
+ ]),
518
+ ...chatPreset('chat-unanswered', 'Chat Unanswered', 'Questions the chat bot could not answer, for turning into Knowledge.', [
519
+ {name: 'text', label: 'Question', type: 'text', required: true},
520
+ {name: 'key', label: 'Normalised', type: 'hidden'},
521
+ {name: 'count', label: 'Times asked', type: 'number', default: 1},
522
+ {name: 'best', label: 'Closest entry', type: 'text'},
523
+ {name: 'firstAt', label: 'First asked', type: 'datetime'},
524
+ {name: 'lastAt', label: 'Last asked', type: 'datetime'},
525
+ {name: 'done', label: 'Dealt with', type: 'boolean', default: false}
526
+ ])
464
527
  ];
465
528
 
466
529
  /** Slugs exported for use in adapterRegistry and the delete guard. */
@@ -476,7 +539,17 @@ export const PRESET_COLLECTION_SLUGS = PRESETS.map(p => p.slug);
476
539
  */
477
540
  export const USER_DATA_PRESET_SLUGS = Object.freeze(['notes-notes', 'todo-items', 'contacts-contacts', 'contacts-groups']);
478
541
 
479
- const USER_DATA = new Set(USER_DATA_PRESET_SLUGS);
542
+ /** The chat presets (services/chat/store.js). */
543
+ export const CHAT_PRESET_SLUGS = Object.freeze(['chat-knowledge', 'chat-sessions', 'chat-messages', 'chat-unanswered']);
544
+
545
+ /**
546
+ * The presets that may live in MongoDB (adapterRegistry.js resolveUserDataPreset):
547
+ * the user-data presets and the chat ones. Their `storage` block survives the
548
+ * reseed below, so a storage move sticks.
549
+ */
550
+ export const MONGO_ELIGIBLE_PRESET_SLUGS = Object.freeze([...USER_DATA_PRESET_SLUGS, ...CHAT_PRESET_SLUGS]);
551
+
552
+ const USER_DATA = new Set(MONGO_ELIGIBLE_PRESET_SLUGS);
480
553
 
481
554
  /** A storage block worth keeping from an existing schema.json, or null. */
482
555
  async function keptStorage(schemaPath) {