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,324 @@
1
+ /**
2
+ * The chat bot's matcher - how a visitor's words find a Knowledge entry. No AI:
3
+ * plain text handling a person can follow and a test can pin.
4
+ *
5
+ * normalise lower case, accents off, contractions spelled out, punctuation gone
6
+ * tokens words minus stop words, lightly stemmed, folded onto a synonym's
7
+ * head word ("costs", "fee", "charges" -> "price")
8
+ * buildIndex every entry's question and alternative phrasings as token sets,
9
+ * its keywords, and how rare each token is across the whole base
10
+ * match scores each entry against the question and decides:
11
+ * answer - one entry is a confident, clear winner
12
+ * suggest - near misses: "Did you mean ...?" (top three)
13
+ * none - nothing close; the caller logs it as unanswered
14
+ * plus three conversational kinds checked first: handover ("can I
15
+ * talk to a person"), greeting ("hi") and thanks ("cheers").
16
+ *
17
+ * A phrasing's score blends how much of the QUESTION it covers with how much of
18
+ * the PHRASING the question covers, both weighted by rarity (a match on "parking"
19
+ * says more than a match on "time"). A phrasing found whole inside the question
20
+ * (or the reverse) adds a bonus, and so does each of the entry's keywords the
21
+ * question uses. A one-letter typo in a longer word still counts, at a discount.
22
+ *
23
+ * Pure: no I/O. Tested in tests/services/chat-matcher.test.js.
24
+ *
25
+ * @module services/chat/matcher
26
+ */
27
+
28
+ /** Words that say nothing about what is being asked. */
29
+ export const STOP_WORDS = new Set(`a about above after again all am an and any are as at be been before being
30
+ below between both but by can could did do does doing down during each few for from further had has have having
31
+ he her here hers herself him himself his how i if in into is it its itself just let me more most my myself no nor
32
+ not now of off on once only or other our ours ourselves out over own please same she should so some such than
33
+ that the their theirs them themselves then there these they this those through to too under until up very was we
34
+ were what when which while who whom why will with would you your yours yourself yourselves hi hello hey
35
+ thanks thank tell know want like need get got im ive id youre dont cant wont also may might must shall us one
36
+ any anything something someone ok okay yes yeah`.split(/\s+/));
37
+
38
+ /**
39
+ * Words that mean the same thing to a visitor, folded onto the first of each
40
+ * group. Stemmed before lookup, so list base forms.
41
+ */
42
+ export const SYNONYM_GROUPS = [
43
+ ['price', 'cost', 'fee', 'charge', 'rate', 'pricing', 'expensive', 'cheap', 'tariff', 'quote'],
44
+ ['open', 'opening', 'hour', 'close', 'closing', 'shut', 'timing'],
45
+ ['book', 'booking', 'appointment', 'reserve', 'reservation', 'schedule', 'slot'],
46
+ ['contact', 'email', 'phone', 'call', 'ring', 'telephone', 'reach', 'number'],
47
+ ['deliver', 'delivery', 'shipping', 'ship', 'postage', 'post', 'dispatch', 'courier'],
48
+ ['refund', 'return', 'reimburse', 'cancel', 'cancellation'],
49
+ ['location', 'address', 'where', 'directions', 'located', 'map', 'postcode'],
50
+ ['park', 'parking', 'car'],
51
+ ['pay', 'payment', 'card', 'cash', 'invoice', 'bill', 'paypal'],
52
+ ['account', 'login', 'signin', 'password', 'register', 'signup'],
53
+ ['job', 'career', 'vacancy', 'hiring', 'recruit'],
54
+ ['help', 'support', 'problem', 'issue', 'trouble', 'broken', 'fault']
55
+ ];
56
+
57
+ /** "can I talk to a person", "real human please", "live agent". */
58
+ const HANDOVER = [
59
+ /\b(?:talk|speak|chat|connect|transfer|put)\b.{0,24}\b(?:person|human|someone|somebody|agent|staff|operator|representative|advisor|adviser|team|real|people|member|you)\b/,
60
+ /\b(?:real|live|actual)\s+(?:person|human|agent|chat|people|someone)\b/,
61
+ /^(?:human|person|agent|operator|representative|staff)(?:\s+please)?$/,
62
+ /\bnot\s+(?:a\s+)?(?:bot|robot|machine)\b/,
63
+ /\bcustomer\s+(?:service|services|support)\b/
64
+ ];
65
+
66
+ const GREETING = /^(?:hi|hello|hey|hiya|howdy|yo|good\s+(?:morning|afternoon|evening|day))(?:\s+(?:there|all|everyone|team))?$/;
67
+ const THANKS = /^(?:thanks?|thank\s+you|thankyou|ta|cheers|many\s+thanks|thanks\s+a\s+lot|great\s+thanks?|perfect|brilliant|lovely)(?:\s+(?:very\s+much|so\s+much|a\s+lot|again|mate))?$/;
68
+
69
+ const CONTRACTIONS = [
70
+ [/\bwhat's\b/g, 'what is'], [/\bwhere's\b/g, 'where is'], [/\bwhen's\b/g, 'when is'], [/\bhow's\b/g, 'how is'],
71
+ [/\bit's\b/g, 'it is'], [/\bthat's\b/g, 'that is'], [/\bthere's\b/g, 'there is'], [/\blet's\b/g, 'let us'],
72
+ [/\bcan't\b/g, 'can not'], [/\bwon't\b/g, 'will not'], [/\bshan't\b/g, 'shall not'], [/n't\b/g, ' not'],
73
+ [/'re\b/g, ' are'], [/'ve\b/g, ' have'], [/'ll\b/g, ' will'], [/'d\b/g, ' would'], [/\bi'm\b/g, 'i am']
74
+ ];
75
+
76
+ /**
77
+ * Lower case, accents off, curly quotes straightened, contractions spelled
78
+ * out, everything that is not a letter, digit or space turned into a space.
79
+ *
80
+ * @param {string} text
81
+ * @returns {string}
82
+ */
83
+ export function normalise(text) {
84
+ let s = String(text ?? '').toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '');
85
+ s = s.replace(/[‘’ʼ`]/g, "'");
86
+ for (const [re, to] of CONTRACTIONS) s = s.replace(re, to);
87
+ return s.replace(/[^a-z0-9\s]+/g, ' ').replace(/\s+/g, ' ').trim();
88
+ }
89
+
90
+ /**
91
+ * A light English stemmer: enough that "bookings", "booked" and "booking" meet
92
+ * at "book", without a full Porter stemmer's surprises on short words.
93
+ *
94
+ * @param {string} word - already normalised
95
+ * @returns {string}
96
+ */
97
+ export function stem(word) {
98
+ let w = String(word || '');
99
+ if (w.length <= 3 || /^\d+$/.test(w)) return w;
100
+ if (w.endsWith('ies') && w.length > 4) return w.slice(0, -3) + 'y';
101
+ if (w.endsWith('sses')) return w.slice(0, -2);
102
+ if (/(?:ches|shes|xes|zes)$/.test(w)) w = w.slice(0, -2);
103
+ else if (w.endsWith('s') && !/(?:ss|us|is|ous)$/.test(w)) w = w.slice(0, -1);
104
+ if (w.length > 5 && w.endsWith('ing')) w = undouble(w.slice(0, -3));
105
+ else if (w.length > 4 && w.endsWith('ed') && !w.endsWith('eed')) w = undouble(w.slice(0, -2));
106
+ else if (w.length > 5 && w.endsWith('ly')) w = w.slice(0, -2);
107
+ return w;
108
+ }
109
+
110
+ /** "stopp" -> "stop", "shipp" -> "ship"; leaves "fall", "pass", "buzz" alone. */
111
+ function undouble(w) {
112
+ return /([^aeiouslz])\1$/.test(w) ? w.slice(0, -1) : w;
113
+ }
114
+
115
+ /**
116
+ * The synonym table as stem -> head stem.
117
+ *
118
+ * @param {string[][]} [groups]
119
+ * @returns {Map<string, string>}
120
+ */
121
+ export function synonymMap(groups = SYNONYM_GROUPS) {
122
+ const map = new Map();
123
+ for (const group of groups) {
124
+ if (!Array.isArray(group) || !group.length) continue;
125
+ const head = stem(normalise(group[0]));
126
+ for (const word of group) {
127
+ for (const part of normalise(word).split(' ')) if (part) map.set(stem(part), head);
128
+ }
129
+ }
130
+ return map;
131
+ }
132
+
133
+ const DEFAULT_SYNONYMS = synonymMap();
134
+
135
+ /**
136
+ * The words that carry meaning, stemmed and folded onto synonyms.
137
+ *
138
+ * @param {string} text
139
+ * @param {{synonyms?: Map<string, string>}} [opts]
140
+ * @returns {string[]} in order, repeats removed
141
+ */
142
+ export function tokens(text, {synonyms = DEFAULT_SYNONYMS} = {}) {
143
+ const out = [];
144
+ const seen = new Set();
145
+ for (const word of normalise(text).split(' ')) {
146
+ if (!word || STOP_WORDS.has(word)) continue;
147
+ const s = stem(word);
148
+ const t = synonyms.get(s) || s;
149
+ if (t && !seen.has(t)) { seen.add(t); out.push(t); }
150
+ }
151
+ return out;
152
+ }
153
+
154
+ /** Split a stored list (array, or text one per line / comma separated) into clean strings. */
155
+ export function listOf(value, separators = /\r?\n/) {
156
+ const raw = Array.isArray(value) ? value : String(value ?? '').split(separators);
157
+ return raw.map(v => String(v ?? '').trim()).filter(Boolean);
158
+ }
159
+
160
+ /**
161
+ * Precompute what match() needs from the Knowledge entries. Disabled entries
162
+ * and ones with no question or answer are left out.
163
+ *
164
+ * @param {Array<{id: string, question: string, alternatives?: string|string[], keywords?: string|string[], answer?: string, enabled?: *}>} entries
165
+ * @param {{synonyms?: Map<string, string>}} [opts]
166
+ * @returns {{entries: object[], idf: Map<string, number>, synonyms: Map<string, string>}}
167
+ */
168
+ export function buildIndex(entries, {synonyms = DEFAULT_SYNONYMS} = {}) {
169
+ const usable = (Array.isArray(entries) ? entries : []).filter(e => e && isOn(e.enabled)
170
+ && String(e.question || '').trim() && String(e.answer || '').trim());
171
+ const indexed = usable.map(e => {
172
+ const phrasings = [e.question, ...listOf(e.alternatives)].map(p => ({
173
+ text: normalise(p),
174
+ tokens: new Set(tokens(p, {synonyms}))
175
+ })).filter(p => p.tokens.size);
176
+ const keywords = new Set(listOf(e.keywords, /[\n,]/).flatMap(k => tokens(k, {synonyms})));
177
+ return {id: e.id, question: String(e.question).trim(), phrasings, keywords};
178
+ }).filter(e => e.phrasings.length);
179
+
180
+ // Rarity across entries (not phrasings): a word every entry uses is noise.
181
+ const df = new Map();
182
+ for (const e of indexed) {
183
+ const seen = new Set();
184
+ for (const p of e.phrasings) for (const t of p.tokens) seen.add(t);
185
+ for (const t of e.keywords) seen.add(t);
186
+ for (const t of seen) df.set(t, (df.get(t) || 0) + 1);
187
+ }
188
+ const n = indexed.length || 1;
189
+ const idf = new Map([...df].map(([t, d]) => [t, 1 + Math.log((n + 1) / (d + 0.5))]));
190
+ return {entries: indexed, idf, synonyms};
191
+ }
192
+
193
+ /**
194
+ * Stored booleans arrive as true, "true", "on", 1 (Mongo and the admin's
195
+ * checkbox disagree). Anything not plainly off counts as on - an entry is
196
+ * enabled unless someone switched it off.
197
+ */
198
+ export function isOn(value) {
199
+ if (value === undefined || value === null || value === '') return true;
200
+ return !['false', '0', 'off', 'no'].includes(String(value).trim().toLowerCase()) && value !== false && value !== 0;
201
+ }
202
+
203
+ /** At most one edit (change, insert or delete) apart. */
204
+ export function oneEditApart(a, b) {
205
+ if (a === b) return true;
206
+ const la = a.length;
207
+ const lb = b.length;
208
+ if (Math.abs(la - lb) > 1) return false;
209
+ let i = 0;
210
+ let j = 0;
211
+ let edits = 0;
212
+ while (i < la && j < lb) {
213
+ if (a[i] === b[j]) { i++; j++; continue; }
214
+ if (++edits > 1) return false;
215
+ if (la > lb) i++;
216
+ else if (lb > la) j++;
217
+ else { i++; j++; }
218
+ }
219
+ return edits + (la - i) + (lb - j) <= 1;
220
+ }
221
+
222
+ /** How strongly a question word meets a phrasing word: 1 exact, 0.8 a typo apart (long words only), else 0. */
223
+ function meet(q, p) {
224
+ if (q === p) return 1;
225
+ if (q.length >= 5 && p.length >= 5 && oneEditApart(q, p)) return 0.8;
226
+ return 0;
227
+ }
228
+
229
+ const weight = (idf, t) => idf.get(t) ?? 1 + Math.log(2);
230
+
231
+ /**
232
+ * Score one phrasing against the question's tokens.
233
+ *
234
+ * @returns {number} 0..1
235
+ */
236
+ function scorePhrasing(qTokens, qText, phrasing, idf) {
237
+ let hit = 0;
238
+ let qTotal = 0;
239
+ for (const q of qTokens) {
240
+ const w = weight(idf, q);
241
+ qTotal += w;
242
+ let best = 0;
243
+ for (const p of phrasing.tokens) {
244
+ best = Math.max(best, meet(q, p));
245
+ if (best === 1) break;
246
+ }
247
+ hit += w * best;
248
+ }
249
+ let pTotal = 0;
250
+ for (const p of phrasing.tokens) pTotal += weight(idf, p);
251
+ if (!qTotal || !pTotal || !hit) return 0;
252
+ const coverQ = hit / qTotal;
253
+ const coverP = Math.min(1, hit / pTotal);
254
+ let score = 0.55 * coverQ + 0.45 * coverP;
255
+ // The phrasing said whole inside the question, or the question inside it.
256
+ const t = phrasing.text;
257
+ if (t && qText && t.length >= 4 && (qText.includes(t) || (qText.length >= 8 && t.includes(qText)))) score += 0.2;
258
+ return Math.min(1, score);
259
+ }
260
+
261
+ /** The thresholds, by how sure the bot must be before answering. */
262
+ export const CONFIDENCE = Object.freeze({
263
+ strict: {answerAt: 0.7, suggestAt: 0.4, margin: 0.12},
264
+ balanced: {answerAt: 0.58, suggestAt: 0.3, margin: 0.08},
265
+ relaxed: {answerAt: 0.48, suggestAt: 0.24, margin: 0.05}
266
+ });
267
+
268
+ /**
269
+ * What kind of message this is before any Knowledge is consulted.
270
+ *
271
+ * @param {string} text
272
+ * @returns {'handover'|'greeting'|'thanks'|null}
273
+ */
274
+ export function intentOf(text) {
275
+ const s = normalise(text);
276
+ if (!s) return null;
277
+ if (HANDOVER.some(re => re.test(s))) return 'handover';
278
+ if (GREETING.test(s)) return 'greeting';
279
+ if (THANKS.test(s)) return 'thanks';
280
+ return null;
281
+ }
282
+
283
+ /**
284
+ * Find the Knowledge entry for a visitor's question.
285
+ *
286
+ * @param {ReturnType<typeof buildIndex>} index
287
+ * @param {string} text
288
+ * @param {{confidence?: 'strict'|'balanced'|'relaxed', limit?: number}} [opts]
289
+ * @returns {{kind: 'handover'|'greeting'|'thanks'|'answer'|'suggest'|'none',
290
+ * best: {id: string, question: string, score: number}|null,
291
+ * suggestions: Array<{id: string, question: string, score: number}>,
292
+ * ranked: Array<{id: string, question: string, score: number}>}}
293
+ */
294
+ export function match(index, text, {confidence = 'balanced', limit = 3} = {}) {
295
+ const empty = {best: null, suggestions: [], ranked: []};
296
+ const intent = intentOf(text);
297
+ if (intent) return {kind: intent, ...empty};
298
+
299
+ const t = CONFIDENCE[confidence] || CONFIDENCE.balanced;
300
+ const qText = normalise(text);
301
+ const qTokens = tokens(text, {synonyms: index?.synonyms || DEFAULT_SYNONYMS});
302
+ if (!qTokens.length || !index?.entries?.length) return {kind: 'none', ...empty};
303
+
304
+ const ranked = index.entries.map(e => {
305
+ let score = 0;
306
+ for (const p of e.phrasings) score = Math.max(score, scorePhrasing(qTokens, qText, p, index.idf));
307
+ // Keywords nudge, they never carry an answer on their own.
308
+ if (score > 0 && e.keywords.size) {
309
+ const used = qTokens.filter(q => e.keywords.has(q)).length;
310
+ score = Math.min(1, score + Math.min(0.24, used * 0.12));
311
+ } else if (!score && e.keywords.size && qTokens.some(q => e.keywords.has(q))) {
312
+ score = 0.25;
313
+ }
314
+ return {id: e.id, question: e.question, score: Math.round(score * 1000) / 1000};
315
+ }).filter(r => r.score > 0).sort((a, b) => b.score - a.score || a.question.localeCompare(b.question));
316
+
317
+ const [first, second] = ranked;
318
+ if (first && first.score >= t.answerAt && (!second || first.score - second.score >= t.margin)) {
319
+ return {kind: 'answer', best: first, suggestions: [], ranked};
320
+ }
321
+ const suggestions = ranked.filter(r => r.score >= t.suggestAt).slice(0, Math.max(1, limit));
322
+ if (suggestions.length) return {kind: 'suggest', best: first, suggestions, ranked};
323
+ return {kind: 'none', best: first || null, suggestions: [], ranked};
324
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Chat settings - two kinds.
3
+ *
4
+ * Site-wide (`config/chat.json`, Chats > settings cog): how sure the bot must
5
+ * be, how long chats are kept, how staff are named to visitors.
6
+ * Per launcher (the launcher's `chat` block, set in Launchers): greeting, the
7
+ * bot's name, whether the bot answers, whether people can ask for staff, and
8
+ * when to ask for a name and email.
9
+ *
10
+ * Both normalised here (whitelisted and clamped, never merged), and both read
11
+ * server-side for every visitor request: what the browser was given is a copy
12
+ * for drawing, never trusted. No I/O except readChatSettings/saveChatSettings.
13
+ *
14
+ * @module services/chat/settings
15
+ */
16
+ import {getConfig, saveConfig} from '../../config.js';
17
+ import {CONFIDENCE} from './matcher.js';
18
+
19
+ export const CHAT_DEFAULTS = Object.freeze({
20
+ confidence: 'balanced',
21
+ retentionDays: 90,
22
+ staffName: 'first',
23
+ // New chats the whole site takes in an hour, from everyone together.
24
+ maxNewChatsPerHour: 300
25
+ });
26
+ export const NEW_CHATS_MIN = 10;
27
+ export const NEW_CHATS_MAX = 10000;
28
+ export const STAFF_NAMES = ['first', 'full', 'team'];
29
+ export const RETENTION_MIN = 7;
30
+ export const RETENTION_MAX = 730;
31
+
32
+ /** The per-launcher chat block. */
33
+ export const LAUNCHER_CHAT_DEFAULTS = Object.freeze({
34
+ greeting: 'Hi! Ask me anything about us - or ask to talk to a person.',
35
+ botName: 'Assistant',
36
+ bot: true,
37
+ staff: true,
38
+ askDetails: 'offline'
39
+ });
40
+ export const ASK_DETAILS = ['offline', 'always', 'never'];
41
+ export const GREETING_MAX = 300;
42
+ export const BOT_NAME_MAX = 40;
43
+
44
+ const clip = (v, max, fallback) => {
45
+ const s = typeof v === 'string' ? v.trim().replace(/\s+/g, ' ').slice(0, max) : '';
46
+ return s || fallback;
47
+ };
48
+ const flag = (v, fallback) => (v === undefined || v === null ? fallback : !(v === false || v === 'false' || v === 0 || v === '0' || v === 'off'));
49
+
50
+ /**
51
+ * @param {object} [raw] - config/chat.json
52
+ * @returns {{confidence: string, retentionDays: number, staffName: string, maxNewChatsPerHour: number}}
53
+ */
54
+ export function normaliseChatSettings(raw) {
55
+ const r = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
56
+ const days = Number(r.retentionDays);
57
+ const perHour = Number(r.maxNewChatsPerHour);
58
+ return {
59
+ confidence: Object.hasOwn(CONFIDENCE, r.confidence) ? r.confidence : CHAT_DEFAULTS.confidence,
60
+ retentionDays: Number.isFinite(days) ? Math.min(RETENTION_MAX, Math.max(RETENTION_MIN, Math.round(days))) : CHAT_DEFAULTS.retentionDays,
61
+ staffName: STAFF_NAMES.includes(r.staffName) ? r.staffName : CHAT_DEFAULTS.staffName,
62
+ maxNewChatsPerHour: Number.isFinite(perHour) ? Math.min(NEW_CHATS_MAX, Math.max(NEW_CHATS_MIN, Math.round(perHour))) : CHAT_DEFAULTS.maxNewChatsPerHour
63
+ };
64
+ }
65
+
66
+ /**
67
+ * @param {object} [raw] - a launcher's `chat` block
68
+ * @returns {{greeting: string, botName: string, bot: boolean, staff: boolean, askDetails: string}}
69
+ */
70
+ export function normaliseLauncherChat(raw) {
71
+ const r = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
72
+ return {
73
+ greeting: clip(r.greeting, GREETING_MAX, LAUNCHER_CHAT_DEFAULTS.greeting),
74
+ botName: clip(r.botName, BOT_NAME_MAX, LAUNCHER_CHAT_DEFAULTS.botName),
75
+ bot: flag(r.bot, true),
76
+ staff: flag(r.staff, true),
77
+ askDetails: ASK_DETAILS.includes(r.askDetails) ? r.askDetails : LAUNCHER_CHAT_DEFAULTS.askDetails
78
+ };
79
+ }
80
+
81
+ function readRaw() {
82
+ try {
83
+ const raw = getConfig('chat');
84
+ return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
85
+ } catch {
86
+ return {};
87
+ }
88
+ }
89
+
90
+ export function readChatSettings() {
91
+ return normaliseChatSettings(readRaw());
92
+ }
93
+
94
+ export function saveChatSettings(raw) {
95
+ const stored = readRaw();
96
+ const settings = normaliseChatSettings({...stored, ...(raw && typeof raw === 'object' ? raw : {})});
97
+ saveConfig('chat', {...settings, ...(stored.examplesSeeded && {examplesSeeded: stored.examplesSeeded})});
98
+ return settings;
99
+ }
100
+
101
+ /** Whether the example Knowledge was offered on this site yet (config/chat.json `examplesSeeded`). */
102
+ export const exampleSeedMarker = {
103
+ seeded: () => Boolean(readRaw().examplesSeeded),
104
+ markSeeded: () => saveConfig('chat', {...readChatSettings(), examplesSeeded: new Date().toISOString()})
105
+ };
106
+
107
+ /**
108
+ * What a visitor sees as the staff member's name.
109
+ *
110
+ * @param {{name?: string, username?: string, email?: string}} user
111
+ * @param {string} mode - STAFF_NAMES
112
+ */
113
+ export function staffDisplayName(user, mode = CHAT_DEFAULTS.staffName) {
114
+ if (mode === 'team') return 'The team';
115
+ const full = String(user?.name || user?.username || '').trim().replace(/\s+/g, ' ');
116
+ if (!full) return 'The team';
117
+ return (mode === 'full' ? full : full.split(' ')[0]).slice(0, 40);
118
+ }