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,235 @@
1
+ /**
2
+ * Chats - the staff side of visitor chat (admin #/launchers/chats and
3
+ * #/launchers/knowledge). Behind the Launchers switch (toolGate in server.js).
4
+ *
5
+ * chats.read:
6
+ * GET /api/chats/_count - the sidebar badge: chats that need staff
7
+ * GET /api/chats?view=active|closed - the inbox, plus who is available
8
+ * GET /api/chats/:id?after=N - one chat and its messages (marks it read for repliers)
9
+ * GET /api/chats/knowledge - every Knowledge entry
10
+ * POST /api/chats/knowledge/test - {text}: what the bot would answer, with scores
11
+ * GET /api/chats/unanswered - questions the bot could not answer
12
+ * GET /api/chats/settings - site-wide chat settings
13
+ * chats.reply:
14
+ * POST /api/chats/presence - {available}: "I can take chats" (sent every 30s by the inbox)
15
+ * POST /api/chats/:id/reply - {text}
16
+ * POST /api/chats/:id/close
17
+ * chats.manage:
18
+ * DELETE /api/chats/:id
19
+ * POST /api/chats/knowledge, PUT/DELETE /api/chats/knowledge/:id
20
+ * POST /api/chats/knowledge/remove-examples
21
+ * POST /api/chats/unanswered/:id/done {done}, DELETE /api/chats/unanswered/:id
22
+ * PUT /api/chats/settings
23
+ */
24
+ import {authenticate as defaultAuthenticate, requirePermission as defaultRequirePermission} from '../../middleware/auth.js';
25
+ import {ago, clip, plural} from '../../services/sidebarBadges.js';
26
+ import {match} from '../../services/chat/matcher.js';
27
+ import {
28
+ checkIn, checkOut, createKnowledge, getSession, knowledgeIndex, listKnowledge, listSessions, listUnanswered,
29
+ messagesAfter, presenceOf, removeExampleKnowledge, removeKnowledge, removeUnanswered, setUnansweredDone,
30
+ staffAvailable, updateKnowledge
31
+ } from '../../services/chat/store.js';
32
+ import {
33
+ needsStaff, staffCloses, staffDeletes, staffMessage, staffReplies, staffSeen, staffSummary
34
+ } from '../../services/chat/conversation.js';
35
+ import {CHAT_DEFAULTS, readChatSettings, saveChatSettings} from '../../services/chat/settings.js';
36
+ import {chatLauncherSummary} from '../../services/chat/launcher-bridge.js';
37
+ import {CONFIDENCE} from '../../services/chat/matcher.js';
38
+
39
+ const ID = /^[A-Za-z0-9_-]{1,64}$/;
40
+ const int = (v) => (Number.isFinite(Number(v)) ? Math.trunc(Number(v)) : 0);
41
+ const userId = (request) => request.user?.id ?? request.user?.sub ?? null;
42
+
43
+ /** Badge answers are asked for every minute from every admin tab: kept for a few seconds. */
44
+ let countCache = null;
45
+ const COUNT_MS = 5000;
46
+ export function _resetCountCache() { countCache = null; }
47
+
48
+ /**
49
+ * The badge from the chats that need staff.
50
+ *
51
+ * @param {object[]} entries - chat-sessions entries
52
+ * @param {number} [at]
53
+ */
54
+ export function chatBadge(entries, at = Date.now()) {
55
+ const items = entries.filter(e => needsStaff(e.data)).map(e => staffSummary(e, at));
56
+ const waiting = items.filter(c => c.status === 'waiting');
57
+ const messages = items.filter(c => c.status === 'message');
58
+ const unread = items.filter(c => c.status === 'open');
59
+ // Red only when someone has been left waiting; a live dot while a visitor is waiting now.
60
+ const overdue = waiting.some(c => c.waitingMs >= 5 * 60_000);
61
+ const tone = overdue ? 'danger' : waiting.length ? 'live' : 'info';
62
+ const label = waiting.length ? `${plural(waiting.length, 'visitor')} waiting`
63
+ : messages.length ? plural(messages.length, 'message') + ' to answer'
64
+ : plural(unread.length, 'chat') + ' with new messages';
65
+ return {
66
+ count: items.length, label, tone,
67
+ details: {
68
+ title: 'Chats',
69
+ rows: [
70
+ {label: 'Waiting for a person', value: String(waiting.length), ...(overdue && {tone: 'danger'})},
71
+ {label: 'Messages left', value: String(messages.length)},
72
+ {label: 'Unread replies', value: String(unread.length)},
73
+ {label: 'Staff available', value: String(staffAvailable(at).length)}
74
+ ],
75
+ items: items.slice(0, 4).map(c => ({
76
+ text: clip(`${c.name || 'Visitor'}: ${c.summary || '(no question yet)'}`),
77
+ meta: c.status === 'waiting' ? `waiting ${ago(c.waitingSince, at)}` : `${c.status === 'message' ? 'left a message' : 'replied'} ${ago(c.lastAt, at)}`,
78
+ ...(c.status === 'waiting' && c.waitingMs >= 5 * 60_000 && {tone: 'danger'})
79
+ })),
80
+ empty: 'Nobody is waiting.'
81
+ }
82
+ };
83
+ }
84
+
85
+ export async function chatsRoutes(fastify, opts = {}) {
86
+ const authenticate = opts.authenticate || defaultAuthenticate;
87
+ const requirePermission = opts.requirePermission || defaultRequirePermission;
88
+ const can = (action) => ({preHandler: [authenticate, requirePermission('chats', action)]});
89
+ /** Whether the caller holds chats.<action> (for what GET does besides reading). */
90
+ const holds = async (request, action) => {
91
+ if (opts.holds) return opts.holds(request, action);
92
+ const {holds: h} = await import('../../services/collectionAccess.js');
93
+ return h(request.user, 'chats', action);
94
+ };
95
+
96
+ fastify.get('/_count', can('read'), async () => {
97
+ if (countCache && Date.now() - countCache.at < COUNT_MS) return countCache.answer;
98
+ const answer = chatBadge(await listSessions({statuses: ['waiting', 'open', 'message']}));
99
+ countCache = {at: Date.now(), answer};
100
+ return answer;
101
+ });
102
+
103
+ fastify.get('/', can('read'), async (request) => {
104
+ const view = ['active', 'closed', 'all'].includes(request.query?.view) ? request.query.view : 'active';
105
+ const statuses = view === 'active' ? ['bot', 'waiting', 'open', 'message'] : view === 'closed' ? ['closed'] : null;
106
+ const at = Date.now();
107
+ const items = (await listSessions({statuses})).map(e => staffSummary(e, at));
108
+ const me = presenceOf(userId(request));
109
+ return {
110
+ items: items.slice(0, 500), total: items.length,
111
+ available: staffAvailable(at).map(s => s.name || 'Someone'),
112
+ me: {available: Boolean(me?.available)},
113
+ launchers: await chatLauncherSummary()
114
+ };
115
+ });
116
+
117
+ fastify.post('/presence', can('reply'), async (request) => {
118
+ const available = request.body?.available !== false;
119
+ const id = userId(request);
120
+ if (request.body?.leaving === true) checkOut(id);
121
+ else checkIn(id, {name: request.user?.name || request.user?.username || '', available});
122
+ return {available: Boolean(presenceOf(id)?.available), online: staffAvailable().length};
123
+ });
124
+
125
+ // ---- Knowledge -----------------------------------------------------------
126
+
127
+ fastify.get('/knowledge', can('read'), async () => ({items: await listKnowledge()}));
128
+
129
+ fastify.post('/knowledge/test', can('read'), async (request) => {
130
+ const text = String(request.body?.text ?? '').slice(0, 1000);
131
+ const {index, byId} = await knowledgeIndex();
132
+ const confidence = CONFIDENCE[request.body?.confidence] ? request.body.confidence : readChatSettings().confidence;
133
+ const r = match(index, text, {confidence});
134
+ return {
135
+ kind: r.kind, confidence,
136
+ answer: r.kind === 'answer' ? {id: r.best.id, question: r.best.question, answer: byId.get(r.best.id)?.answer || '', score: r.best.score} : null,
137
+ suggestions: r.suggestions.map(s => ({id: s.id, question: s.question, score: s.score})),
138
+ ranked: r.ranked.slice(0, 5),
139
+ thresholds: CONFIDENCE[confidence]
140
+ };
141
+ });
142
+
143
+ fastify.post('/knowledge', can('manage'), async (request, reply) => {
144
+ const {item, error} = await createKnowledge(request.body || {}, userId(request));
145
+ if (error) return reply.code(400).send({error});
146
+ // Made from an unanswered question: that one is dealt with.
147
+ const from = request.body?.fromUnanswered;
148
+ if (typeof from === 'string' && ID.test(from)) await setUnansweredDone(from, true).catch(() => null);
149
+ return reply.code(201).send(item);
150
+ });
151
+
152
+ fastify.post('/knowledge/remove-examples', can('manage'), async () => ({removed: await removeExampleKnowledge()}));
153
+
154
+ fastify.put('/knowledge/:kid', can('manage'), async (request, reply) => {
155
+ if (!ID.test(request.params.kid)) return reply.code(404).send({error: 'Entry not found'});
156
+ const {item, error, missing} = await updateKnowledge(request.params.kid, request.body || {});
157
+ if (missing) return reply.code(404).send({error: 'Entry not found'});
158
+ if (error) return reply.code(400).send({error});
159
+ return item;
160
+ });
161
+
162
+ fastify.delete('/knowledge/:kid', can('manage'), async (request, reply) => {
163
+ if (!ID.test(request.params.kid) || !await removeKnowledge(request.params.kid)) return reply.code(404).send({error: 'Entry not found'});
164
+ return {ok: true};
165
+ });
166
+
167
+ // ---- Unanswered ----------------------------------------------------------
168
+
169
+ fastify.get('/unanswered', can('read'), async (request) => ({
170
+ items: await listUnanswered({includeDone: request.query?.done === '1'})
171
+ }));
172
+
173
+ fastify.post('/unanswered/:uid/done', can('manage'), async (request, reply) => {
174
+ if (!ID.test(request.params.uid)) return reply.code(404).send({error: 'Not found'});
175
+ const item = await setUnansweredDone(request.params.uid, request.body?.done !== false);
176
+ return item || reply.code(404).send({error: 'Not found'});
177
+ });
178
+
179
+ fastify.delete('/unanswered/:uid', can('manage'), async (request, reply) => {
180
+ if (!ID.test(request.params.uid) || !await removeUnanswered(request.params.uid)) return reply.code(404).send({error: 'Not found'});
181
+ return {ok: true};
182
+ });
183
+
184
+ // ---- Settings ------------------------------------------------------------
185
+
186
+ fastify.get('/settings', can('read'), async () => ({settings: readChatSettings(), defaults: CHAT_DEFAULTS}));
187
+
188
+ fastify.put('/settings', can('manage'), async (request) => ({settings: saveChatSettings(request.body || {})}));
189
+
190
+ // ---- One chat (after the static paths) -----------------------------------
191
+
192
+ fastify.get('/:id', can('read'), async (request, reply) => {
193
+ const {id} = request.params;
194
+ if (!ID.test(id)) return reply.code(404).send({error: 'Chat not found'});
195
+ let session = await getSession(id, {fresh: true});
196
+ if (!session) return reply.code(404).send({error: 'Chat not found'});
197
+ // Someone who can answer has now seen it; a read-only viewer leaves it unread.
198
+ if (int(session.data.unread) && await holds(request, 'reply')) {
199
+ session = (await staffSeen(id)).session || session;
200
+ countCache = null;
201
+ }
202
+ const {byId} = await knowledgeIndex();
203
+ const messages = await messagesAfter(id, Math.max(0, int(request.query?.after)));
204
+ return {chat: staffSummary(session), messages: messages.map(m => staffMessage(m, byId))};
205
+ });
206
+
207
+ fastify.post('/:id/reply', can('reply'), async (request, reply) => {
208
+ const {id} = request.params;
209
+ if (!ID.test(id)) return reply.code(404).send({error: 'Chat not found'});
210
+ const user = {id: userId(request), name: request.user?.name || request.user?.username || ''};
211
+ const result = await staffReplies(id, user, request.body?.text);
212
+ if (result.error) return reply.code(result.code || 400).send({error: result.error});
213
+ countCache = null;
214
+ checkIn(user.id, {name: user.name, available: presenceOf(user.id)?.available ?? true});
215
+ return {chat: staffSummary(result.session)};
216
+ });
217
+
218
+ fastify.post('/:id/close', can('reply'), async (request, reply) => {
219
+ const {id} = request.params;
220
+ if (!ID.test(id)) return reply.code(404).send({error: 'Chat not found'});
221
+ const result = await staffCloses(id);
222
+ if (result.error) return reply.code(result.code || 400).send({error: result.error});
223
+ countCache = null;
224
+ return {chat: staffSummary(result.session)};
225
+ });
226
+
227
+ fastify.delete('/:id', can('manage'), async (request, reply) => {
228
+ const {id} = request.params;
229
+ if (!ID.test(id)) return reply.code(404).send({error: 'Chat not found'});
230
+ const {ok} = await staffDeletes(id);
231
+ if (!ok) return reply.code(404).send({error: 'Chat not found'});
232
+ countCache = null;
233
+ return {ok: true};
234
+ });
235
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Launchers API (Content > Launchers - services/launchers.js). Registered at
3
+ * /api/launchers behind the Tool's switch (toolGate), so it answers 404 while
4
+ * Launchers is switched off.
5
+ *
6
+ * GET /api/launchers/items - every launcher, in order (settings.read)
7
+ * PUT /api/launchers/items - {launchers: [...]}: the whole list - edits, order, on/off (settings.update)
8
+ * PATCH /api/launchers/items/:id - a patch over one launcher, e.g. {enabled: false} (settings.update)
9
+ * GET /api/launchers/_count - the sidebar badge (settings.read)
10
+ *
11
+ * The page body a launcher opens is not here: it is /_launcher/<id>
12
+ * (routes/launcher-public.js), a page of its own the panel frames.
13
+ */
14
+ import {
15
+ authenticate as defaultAuthenticate,
16
+ requirePermission as defaultRequirePermission
17
+ } from '../../middleware/auth.js';
18
+ import {getLaunchers, launchersBadge, saveLaunchers, updateLauncher} from '../../services/launchers.js';
19
+
20
+ /** Far more than any site will want, and small enough that a runaway client cannot write megabytes into every page. */
21
+ const MAX_LAUNCHERS = 100;
22
+
23
+ /**
24
+ * @param {import('fastify').FastifyInstance} fastify
25
+ * @param {{authenticate?: Function, requirePermission?: Function}} [opts] - DI for tests
26
+ */
27
+ export async function launchersRoutes(fastify, opts = {}) {
28
+ const authenticate = opts.authenticate || defaultAuthenticate;
29
+ const requirePermission = opts.requirePermission || defaultRequirePermission;
30
+ const canRead = {preHandler: [authenticate, requirePermission('settings', 'read')]};
31
+ const canUpdate = {preHandler: [authenticate, requirePermission('settings', 'update')]};
32
+
33
+ fastify.get('/items', canRead, async () => ({launchers: getLaunchers()}));
34
+
35
+ fastify.put('/items', canUpdate, async (request, reply) => {
36
+ const list = request.body?.launchers;
37
+ if (!Array.isArray(list)) return reply.status(400).send({error: 'Send {launchers: [...]}'});
38
+ if (list.length > MAX_LAUNCHERS) return reply.status(400).send({error: `At most ${MAX_LAUNCHERS} launchers`});
39
+ return {launchers: await saveLaunchers(list)};
40
+ });
41
+
42
+ fastify.patch('/items/:id', canUpdate, async (request, reply) => {
43
+ const patch = request.body && typeof request.body === 'object' && !Array.isArray(request.body) ? request.body : {};
44
+ const saved = await updateLauncher(request.params.id, patch);
45
+ if (!saved) return reply.status(404).send({error: 'No such launcher'});
46
+ return {launcher: saved};
47
+ });
48
+
49
+ fastify.get('/_count', canRead, async () => launchersBadge());
50
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * What a launcher's panel shows (services/launchers.js):
3
+ *
4
+ * GET /_launcher/<id> the launcher's page, form or block, drawn as a page of
5
+ * its own with the body alone (renderPage `embed`) - the
6
+ * panel puts it in an iframe, so the page's own scripts,
7
+ * forms and components start exactly as they do anywhere
8
+ *
9
+ * The address names the LAUNCHER, never a page: a visitor cannot use it to
10
+ * reach any page but the one the site chose, and that page's own rules still
11
+ * decide - a draft, a page in a switched-off project, a missing page or one the
12
+ * viewer may not see answer 404 (403 would say that something is there). A
13
+ * launcher that is off, meant for signed-in people only (or signed-out ones
14
+ * only) and not this viewer, a chat launcher, or the Tool switched off: 404.
15
+ *
16
+ * Never cached and never indexed: what it shows depends on the viewer, and it
17
+ * is not a page anyone should land on from a search.
18
+ *
19
+ * @module routes/launcher-public
20
+ */
21
+ import {getBaseUrl} from './public.js';
22
+ import {getLauncher, launchersOn} from '../services/launchers.js';
23
+ import {launcherReady} from '../../public/js/launcher-settings.mjs';
24
+ import {resolvePublishedPage} from '../services/pagePublishing.js';
25
+ import {buildPreviewPage, getPage} from '../services/content.js';
26
+ import {renderPage} from '../services/renderer.js';
27
+ import {resolveViewer as defaultResolveViewer} from '../services/viewerSession.js';
28
+ import {newSessionCookie, validSessionCookie} from '../services/shortcodeExpiry.js';
29
+
30
+ const NOT_FOUND = '<!DOCTYPE html><html lang="en-GB"><head><meta charset="UTF-8"><title>Not available</title>'
31
+ + '<style>body{font-family:system-ui,sans-serif;margin:0;padding:2rem;color:#666;text-align:center}</style></head>'
32
+ + '<body><p>This is not available right now.</p></body></html>';
33
+
34
+ /**
35
+ * The page object a launcher shows, or null when this viewer gets nothing.
36
+ *
37
+ * @param {object} launcher - normalised
38
+ * @param {object|null} viewer
39
+ * @param {object} [expiry] - the shortcode-expiry context for a page that has expiring parts
40
+ * @returns {Promise<object|null>}
41
+ */
42
+ export async function launcherPage(launcher, viewer, expiry = null) {
43
+ const {kind, ref} = launcher.action;
44
+ if (kind === 'page') {
45
+ const verdict = await resolvePublishedPage(ref, viewer, {allowDrafts: false});
46
+ if (verdict.status !== 'ok') return null;
47
+ const page = verdict.page;
48
+ const withViewer = await getPage(page.urlPath, {user: viewer, ...(expiry && page.hasExpiry && {expiry: expiry()})});
49
+ return withViewer || page;
50
+ }
51
+ // A form or a block: the same shortcode a page would carry, drawn the same way.
52
+ const body = kind === 'form' ? `[form name="${ref}" /]` : `[block template="${ref}" /]`;
53
+ return buildPreviewPage(`/_launcher/${launcher.id}`, {title: launcher.action.title || launcher.label, layout: 'blank'},
54
+ body, {user: viewer});
55
+ }
56
+
57
+ /**
58
+ * @param {import('fastify').FastifyInstance} fastify
59
+ * @param {{resolveViewer?: Function}} [opts] - DI for tests
60
+ */
61
+ export async function launcherPublicRoutes(fastify, opts = {}) {
62
+ const resolveViewer = opts.resolveViewer || defaultResolveViewer;
63
+
64
+ fastify.get('/_launcher/:id', async (request, reply) => {
65
+ reply.header('cache-control', 'no-store, private');
66
+ reply.header('x-robots-tag', 'noindex, nofollow');
67
+ // Only this site may frame it.
68
+ reply.header('content-security-policy', "frame-ancestors 'self'");
69
+ reply.type('text/html; charset=utf-8');
70
+
71
+ const launcher = launchersOn() ? getLauncher(request.params.id) : null;
72
+ const viewer = await resolveViewer(request);
73
+ const forViewer = launcher && launcher.enabled && launcher.action.type !== 'chat' && launcherReady(launcher)
74
+ && !(launcher.audience === 'signed-in' && !viewer) && !(launcher.audience === 'signed-out' && viewer);
75
+ if (!forViewer) return reply.status(404).send(NOT_FOUND);
76
+
77
+ // Expiring shortcodes are counted per visitor - the same cookie the page route uses.
78
+ const expiry = () => {
79
+ const cookies = Object.fromEntries(String(request.headers.cookie || '').split(';').map(part => {
80
+ const at = part.indexOf('=');
81
+ return at < 0 ? ['', ''] : [part.slice(0, at).trim(), part.slice(at + 1).trim()];
82
+ }));
83
+ let sessionId = validSessionCookie(cookies.dm_shortcode_session, process.env.JWT_SECRET);
84
+ if (!sessionId) {
85
+ const fresh = newSessionCookie(process.env.JWT_SECRET);
86
+ sessionId = fresh.id;
87
+ reply.header('set-cookie', `dm_shortcode_session=${fresh.value}; Path=/; HttpOnly; SameSite=Lax${request.protocol === 'https' ? '; Secure' : ''}`);
88
+ }
89
+ return {ip: request.ip || '', sessionId, secret: process.env.JWT_SECRET};
90
+ };
91
+
92
+ const page = await launcherPage(launcher, viewer, expiry);
93
+ if (!page) return reply.status(404).send(NOT_FOUND);
94
+ return reply.send(await renderPage(page, {embed: true, user: viewer, baseUrl: getBaseUrl(request)}));
95
+ });
96
+ }
package/server/server.js CHANGED
@@ -598,6 +598,9 @@ await app.register(toolGate('notes', notesRoutes), {prefix: '/api/notes'});
598
598
  await app.register(toolGate('todo', todoRoutes), {prefix: '/api/todo'});
599
599
  const {calculatorRoutes} = await import('./routes/api/calculator.js');
600
600
  await app.register(toolGate('calculator', calculatorRoutes), {prefix: '/api/calculator'});
601
+ // Launchers: the admin's API here; what a launcher opens is /_launcher/<id> (registered with the public routes).
602
+ const {launchersRoutes} = await import('./routes/api/launchers.js');
603
+ await app.register(toolGate('launchers', launchersRoutes), {prefix: '/api/launchers'});
601
604
  await app.register(toolGate('analytics', analyticsRoutes), {prefix: '/api/analytics'});
602
605
  await app.register(toolGate('contacts', contactsRoutes), {prefix: '/api/contacts'});
603
606
  // SEO (0.90.0; the `seo` plugin in 0.89.0): a global plugin - its redirect guard
@@ -609,6 +612,14 @@ await app.register(toolGate('contacts', contactsRoutes), {prefix: '/api/contacts
609
612
  await app.register(seoPlugin, {enabled: isToolEnabled('seo'), getBaseUrl, rolesService});
610
613
  }
611
614
  await app.register(toolGate('seo', seoRoutes), {prefix: '/api/seo'});
615
+ // Chat - the chat launcher's bot and live chat (services/chat). Behind the Launchers switch:
616
+ // the visitor API also answers 404 for any launcher that is not an enabled chat launcher.
617
+ {
618
+ const {chatPublicRoutes} = await import('./routes/api/chat.js');
619
+ const {chatsRoutes} = await import('./routes/api/chats.js');
620
+ await app.register(toolGate('launchers', chatPublicRoutes), {prefix: '/api/chat'});
621
+ await app.register(toolGate('launchers', chatsRoutes), {prefix: '/api/chats'});
622
+ }
612
623
  // Import from WordPress (services/wpImport): its API behind the Tool switch, and - always,
613
624
  // whatever the switch - the hook that answers WordPress's query addresses (/?p=12) from what
614
625
  // an import made: those redirects are part of the migrated site, not of the Tool.
@@ -665,6 +676,9 @@ const coreToolItems = [
665
676
  {text: 'SEO', url: '#/seo', icon: 'search', permission: 'seo', countUrl: '/api/seo/count'}
666
677
  ];
667
678
  for (const item of coreToolItems) toolEntry(item.permission, item);
679
+ // Launchers sit in Content beside Menus and Context Menus; switched off, no entry (toolEntry).
680
+ if (isToolEnabled('launchers')) registerSidebarItem({folder: 'content', item: {source: 'Built in', text: 'Launchers', url: '#/launchers', icon: 'rocket', permission: 'settings', countUrl: '/api/launchers/_count', inventory: true}});
681
+ else if (isToolStaffOnly('launchers')) registerSidebarItem({folder: 'content', item: {source: 'Built in', text: 'Launchers', url: '#/launchers', icon: 'rocket', permission: 'settings', countUrl: '/api/launchers/_count', inventory: true, staffOnly: true}});
668
682
  toolEntry('wordpress-import', {text: 'Import from WordPress', url: '#/wordpress-import', icon: 'download', permission: 'import', countUrl: '/api/import/wordpress/count', inventory: true});
669
683
  // Todo's to-dos on the calendar (registered when routes/api/todo.js loads).
670
684
  if (!isToolEnabled('todo')) {
@@ -706,6 +720,8 @@ registerSidebarItem({folder: 'system', item: {source: 'Built in', text: 'Plugins
706
720
  registerSidebarItem({folder: 'system', item: {source: 'Built in', text: 'API Tokens', url: '#/api-tokens', icon: 'key', permission: 'api-tokens', countUrl: '/api/api-tokens/_count'}});
707
721
  // Search now lives in Appearance; keep its route for existing bookmarks.
708
722
  hideSidebarUrl('#/search');
723
+ // Chats: visitors waiting for a person, messages left, unread replies (Launchers' chat).
724
+ if (isToolEnabled('launchers')) registerSidebarItem({folder: 'content', item: {source: 'Built in', text: 'Chats', url: '#/launchers/chats', icon: 'message-circle', permission: 'chats', countUrl: '/api/chats/_count'}});
709
725
  registerSidebarItem({folder: 'content', item: {source: 'Built in', text: 'Content API', url: '#/content-api', icon: 'file-text', permission: 'settings', countUrl: '/api/content-api/_count', inventory: true}});
710
726
  // Documentation pages added after the sidebar menu was seeded (0.93.1). The menu is
711
727
  // seeded once, so new pages reach existing sites only by registering here. The two
@@ -715,6 +731,8 @@ registerSidebarItem({folder: 'Usage', item: {source: 'Built in', text: 'Blocks',
715
731
  registerSidebarItem({folder: 'Usage', item: {source: 'Built in', text: 'Built-in Tools', url: '#/docs/usage/tools', icon: 'tool'}});
716
732
  registerSidebarItem({folder: 'Usage', item: {source: 'Built in', text: 'Dashboard', url: '#/docs/usage/dashboard', icon: 'home'}});
717
733
  registerSidebarItem({folder: 'Usage', item: {source: 'Built in', text: 'Search Engines & AI', url: '#/docs/usage/search-engines', icon: 'search'}});
734
+ registerSidebarItem({folder: 'Usage', item: {source: 'Built in', text: 'Launchers', url: '#/docs/usage/launchers', icon: 'rocket'}});
735
+ registerSidebarItem({folder: 'Usage', item: {source: 'Built in', text: 'Chat & Knowledge', url: '#/docs/usage/chat', icon: 'message-circle'}});
718
736
  registerSidebarItem({folder: 'Usage', item: {source: 'Built in', text: 'Editions & Licences', url: '#/docs/usage/editions', icon: 'key'}});
719
737
  registerSidebarItem({folder: 'API Reference', item: {source: 'Built in', text: 'Forms', url: '#/docs/api/forms', icon: 'layout'}});
720
738
  registerSidebarItem({folder: 'API Reference', item: {source: 'Built in', text: 'Scaffold', url: '#/docs/api/scaffold', icon: 'package'}});
@@ -725,6 +743,18 @@ registerSidebarItem({folder: 'API Reference', item: {source: 'Built in', text: '
725
743
  // Core's notification sources, before plugins add theirs (0.80).
726
744
  const {registerCoreSources} = await import('./services/notification-sources.js');
727
745
  await registerCoreSources();
746
+ // Visitor chat: its notification source, the example Knowledge (once per site) and the hourly tidy-up.
747
+ try {
748
+ const {registerChatSource, startChatSweep} = await import('./services/chat/conversation.js');
749
+ registerChatSource();
750
+ const {seedExampleKnowledge} = await import('./services/chat/store.js');
751
+ const {exampleSeedMarker} = await import('./services/chat/settings.js');
752
+ const added = await seedExampleKnowledge(exampleSeedMarker);
753
+ if (added) app.log.info(`[chat] Added ${added} example Knowledge entries.`);
754
+ if (isToolEnabled('launchers')) startChatSweep({log: app.log});
755
+ } catch (err) {
756
+ app.log.warn(`[chat] Start-up skipped: ${err.message}`);
757
+ }
728
758
  // "Your password was changed" to the account holder, on every change (services/passwordReset.js).
729
759
  (await import('./services/passwordReset.js')).registerPasswordChangeNotice({log: app.log});
730
760
 
@@ -781,6 +811,9 @@ await app.register(outreachPublicRoutes);
781
811
  // Before the pages: /favicon.* must never reach the page router.
782
812
  const { faviconRoutes } = await import('./routes/favicon.js');
783
813
  await app.register(faviconRoutes);
814
+ // Before the catch-all: /_launcher/<id> is what a launcher's panel frames.
815
+ const {launcherPublicRoutes} = await import('./routes/launcher-public.js');
816
+ await app.register(launcherPublicRoutes);
784
817
  const { publicRoutes } = await import('./routes/public.js');
785
818
  await app.register(publicRoutes);
786
819
 
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * Resolution order:
7
7
  * 1. System presets (roles, user profiles, projects, ...) → always FileAdapter
8
- * 2. User-data presets (Notes, Todo, Contacts) → MongoDB only when declared,
8
+ * 2. User-data presets (Notes, Todo, Contacts) and the chat presets → MongoDB only when declared,
9
9
  * the connection works, and the files hold none of its rows; else files
10
10
  * (resolveUserDataPreset below)
11
11
  * 3. schema.json `storage.adapter` field:
@@ -15,10 +15,10 @@
15
15
  * Adapters are cached per slug. Call `invalidate(slug)` after a schema update.
16
16
  */
17
17
  import fileAdapter from './adapters/FileAdapter.js';
18
- import {PRESET_COLLECTION_SLUGS, USER_DATA_PRESET_SLUGS} from './presetCollections.js';
18
+ import {MONGO_ELIGIBLE_PRESET_SLUGS, PRESET_COLLECTION_SLUGS} from './presetCollections.js';
19
19
 
20
- /** People's own data (Notes, Todo, Contacts): MongoDB when the site can have it. */
21
- const USER_DATA_SLUGS = new Set(USER_DATA_PRESET_SLUGS);
20
+ /** People's own data (Notes, Todo, Contacts) and the chat presets: MongoDB when the site can have it. */
21
+ const USER_DATA_SLUGS = new Set(MONGO_ELIGIBLE_PRESET_SLUGS);
22
22
 
23
23
  /** Collections that must always use file-based storage (system presets). */
24
24
  const PRESET_SLUGS = new Set(['roles', 'user-profiles', ...PRESET_COLLECTION_SLUGS.filter(s => !USER_DATA_SLUGS.has(s))]);
@@ -180,6 +180,24 @@ export class FileAdapter {
180
180
  });
181
181
  }
182
182
 
183
+ /**
184
+ * Delete the entries with these ids in one write. Ids not there are ignored.
185
+ *
186
+ * @param {string} slug
187
+ * @param {string[]} entryIds
188
+ * @returns {Promise<number>} how many were deleted
189
+ */
190
+ async removeMany(slug, entryIds) {
191
+ const gone = new Set(entryIds);
192
+ if (!gone.size) return 0;
193
+ return locked(slug, async () => {
194
+ const entries = await read(slug);
195
+ const kept = entries.filter(e => !gone.has(e.id));
196
+ if (kept.length !== entries.length) await write(slug, kept);
197
+ return entries.length - kept.length;
198
+ });
199
+ }
200
+
183
201
  /**
184
202
  * Delete all entries in a collection.
185
203
  *
@@ -204,6 +204,20 @@ export class MongoAdapter {
204
204
  if (result.deletedCount === 0) throw new Error('Entry not found');
205
205
  }
206
206
 
207
+ /**
208
+ * Delete the entries with these ids in one request. Ids not there are ignored.
209
+ *
210
+ * @param {string} slug
211
+ * @param {string[]} entryIds
212
+ * @returns {Promise<number>} how many were deleted
213
+ */
214
+ async removeMany(slug, entryIds) {
215
+ const ids = [...new Set(entryIds)].map(idOf);
216
+ if (!ids.length) return 0;
217
+ const col = await this._col(slug);
218
+ return (await col.deleteMany({id: {$in: ids}})).deletedCount;
219
+ }
220
+
207
221
  /**
208
222
  * Delete all entries in a collection.
209
223
  *