create-heresay 0.2.13 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-heresay",
3
- "version": "0.2.13",
3
+ "version": "0.2.15",
4
4
  "description": "Set up your own Heresay: in-app feedback that every report gets a hearing. Creates a Firebase project in your Google account and deploys the dashboard, API and SDK to it.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/release/VERSION CHANGED
@@ -1 +1 @@
1
- 0.2.13
1
+ 0.2.15
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
7
7
  import { CLAIM_TTL_MS, LIMITS, PLATFORMS, isPlatform, } from './types.js';
8
+ import { notify } from './notifications.js';
8
9
  const json = (status, body) => ({ status, body });
9
10
  const str = (v, max) => {
10
11
  if (typeof v !== 'string')
@@ -264,6 +265,7 @@ export async function agent(p, req, deps, body, prompt, createProject, toReporte
264
265
  if (refused)
265
266
  return json(409, { error: `in progress in ${refused}`, claimed_by: refused });
266
267
  deps.log('api.brief_handed_off', { from: repoName, to, report_id: t.id });
268
+ await notify('handoff', app, t.id, deps);
267
269
  return json(200, { brief: summary(t, app, now) });
268
270
  }
269
271
  if (p[2] === 'fixed') {
@@ -1,5 +1,6 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
2
  import { agent, normaliseRepo, reposFor, tokens } from './agent.js';
3
+ import { notificationSettings, notify } from './notifications.js';
3
4
  import { LIMITS, PLATFORMS, REPORT_ORDER, REPORT_TYPES, isFramework, isPlatform, isReportType, isSignIn, toReporterView, } from './types.js';
4
5
  /**
5
6
  * Fixed windows. The public endpoint has no login, so each of these is a separate line of
@@ -137,7 +138,12 @@ async function route(req, deps) {
137
138
  return preflight(req);
138
139
  // Coding agents, with a per-repo token instead of a person's sign-in.
139
140
  if (p[0] === 'agent') {
140
- return agent(p.slice(1), req, deps, parseBody(req.body), agentPrompt, (by, body) => createProject({ email: by, role: 'member', added_at: '', added_by: null }, { ...req, body }, deps), async (project, id, note, by) => transitionRes(await deps.store.move(project.id, id, 'accepted', 'fixed', { fix_note: note, triaged_by: by, updated_at: new Date(deps.now()).toISOString() })));
141
+ return agent(p.slice(1), req, deps, parseBody(req.body), agentPrompt, (by, body) => createProject({ email: by, role: 'member', added_at: '', added_by: null }, { ...req, body }, deps), async (project, id, note, by) => {
142
+ const result = await deps.store.move(project.id, id, 'accepted', 'fixed', { fix_note: note, triaged_by: by, updated_at: new Date(deps.now()).toISOString() });
143
+ if (result.ok)
144
+ await notify('fixed', project, id, deps);
145
+ return transitionRes(result);
146
+ });
141
147
  }
142
148
  // The team, signed in to the dashboard.
143
149
  const who = await caller(req, deps);
@@ -156,6 +162,11 @@ async function route(req, deps) {
156
162
  }
157
163
  if (p[0] === 'team')
158
164
  return team(p, member, req, deps);
165
+ if (p[0] === 'notifications') {
166
+ if (member.role !== 'owner')
167
+ return json(403, { error: 'Only an owner can manage notifications.' });
168
+ return notificationSettings(p, req, deps, parseBody(req.body));
169
+ }
159
170
  if (p[0] === 'agent-tokens')
160
171
  return tokens(p, member, req, deps, parseBody(req.body));
161
172
  if (p[0] === 'projects' && p.length === 1) {
@@ -328,6 +339,7 @@ async function submit(req, deps) {
328
339
  await deps.store.updateProject(project.id, { framework: report.context.framework, framework_detected: true });
329
340
  }
330
341
  deps.log('api.report_created', { project_id: project.id, report_id: report.id, type: report.type });
342
+ await notify('new_report', project, report.id, deps);
331
343
  return json(201, { report: toReporterView(report) }, headers);
332
344
  }
333
345
  /**
@@ -532,6 +544,9 @@ async function triage(project, report_id, action, uid, req, deps) {
532
544
  return json(404, { error: 'not found' });
533
545
  }
534
546
  deps.log('api.report_triaged', { project_id: project.id, report_id, action, ok: t.ok });
547
+ if (t.ok && (action === 'accept' || action === 'fixed')) {
548
+ await notify(action === 'accept' ? 'accepted' : 'fixed', project, report_id, deps);
549
+ }
535
550
  return transitionRes(t);
536
551
  }
537
552
  //# sourceMappingURL=handler.js.map
@@ -0,0 +1,205 @@
1
+ export const NOTIFICATION_EVENTS = ['new_report', 'accepted', 'fixed', 'handoff'];
2
+ export const defaultNotifications = () => ({
3
+ events: { new_report: true, accepted: false, fixed: true, handoff: true },
4
+ telegram: { enabled: false, token: null, chat_id: '' },
5
+ cliq: { enabled: false, token: null, endpoint: '' },
6
+ });
7
+ /** Credentials never leave the server, including in save responses. */
8
+ export function notificationView(settings) {
9
+ return {
10
+ events: settings.events,
11
+ telegram: { enabled: settings.telegram.enabled, configured: !!settings.telegram.token, chat_id: settings.telegram.chat_id },
12
+ cliq: { enabled: settings.cliq.enabled, configured: !!settings.cliq.token, endpoint: settings.cliq.endpoint },
13
+ };
14
+ }
15
+ class SettingsError extends Error {
16
+ }
17
+ const object = (v) => {
18
+ if (!v || typeof v !== 'object' || Array.isArray(v))
19
+ throw new SettingsError('Invalid notification settings.');
20
+ return v;
21
+ };
22
+ const field = (v, max) => {
23
+ if (typeof v !== 'string' || v.length > max)
24
+ throw new SettingsError('Invalid notification field.');
25
+ return v.trim();
26
+ };
27
+ const boolean = (v) => {
28
+ if (typeof v !== 'boolean')
29
+ throw new SettingsError('Notification switches must be true or false.');
30
+ return v;
31
+ };
32
+ /** Only Zoho's message endpoints; redirects and arbitrary webhook hosts are not allowed. */
33
+ const CLIQ_HOSTS = new Set([
34
+ 'cliq.zoho.com', 'cliq.zoho.in', 'cliq.zoho.eu', 'cliq.zoho.com.au',
35
+ 'cliq.zoho.jp', 'cliq.zohocloud.ca', 'cliq.zoho.com.cn', 'cliq.zoho.sa',
36
+ 'cliq.zoho.uk', 'cliq.zoho.ae', 'cliq.zoho.sg',
37
+ ]);
38
+ export function validCliqEndpoint(endpoint) {
39
+ try {
40
+ const u = new URL(endpoint);
41
+ return u.protocol === 'https:' && !u.username && !u.password && !u.port && !u.search && !u.hash
42
+ && CLIQ_HOSTS.has(u.hostname)
43
+ && /^\/api\/v2\/(bots|channelsbyname)\/[A-Za-z0-9_-]+\/message$/.test(u.pathname);
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
49
+ /** Patch inside updateInstance: blank/omitted tokens retain the saved secret; null removes it. */
50
+ export function patchNotifications(current, body) {
51
+ const next = structuredClone(current);
52
+ if (body.events !== undefined) {
53
+ const events = object(body.events);
54
+ for (const event of NOTIFICATION_EVENTS)
55
+ if (events[event] !== undefined)
56
+ next.events[event] = boolean(events[event]);
57
+ }
58
+ for (const provider of ['telegram', 'cliq']) {
59
+ if (body[provider] === undefined)
60
+ continue;
61
+ const patch = object(body[provider]);
62
+ const target = next[provider];
63
+ if (patch.enabled !== undefined)
64
+ target.enabled = boolean(patch.enabled);
65
+ if (patch.token === null)
66
+ target.token = null;
67
+ else if (patch.token !== undefined) {
68
+ const token = field(patch.token, 512);
69
+ if (token) {
70
+ if (provider === 'telegram' ? !/^\d+:[A-Za-z0-9_-]{20,}$/.test(token) : !/^[A-Za-z0-9._-]+$/.test(token)) {
71
+ throw new SettingsError(`Invalid ${provider === 'telegram' ? 'Telegram bot' : 'Cliq webhook'} token.`);
72
+ }
73
+ target.token = token;
74
+ }
75
+ }
76
+ if (provider === 'telegram' && patch.chat_id !== undefined)
77
+ next.telegram.chat_id = field(patch.chat_id, 100);
78
+ if (provider === 'cliq' && patch.endpoint !== undefined)
79
+ next.cliq.endpoint = field(patch.endpoint, 300);
80
+ }
81
+ if (next.telegram.chat_id && !/^(?:-?\d+|@[A-Za-z][A-Za-z0-9_]{4,})$/.test(next.telegram.chat_id)) {
82
+ throw new SettingsError('Enter a Telegram chat ID or @channel username.');
83
+ }
84
+ if (next.cliq.endpoint && !validCliqEndpoint(next.cliq.endpoint)) {
85
+ throw new SettingsError('Use a Zoho Cliq bot or channel message endpoint, without a query string.');
86
+ }
87
+ if (next.telegram.enabled && (!next.telegram.token || !next.telegram.chat_id)) {
88
+ throw new SettingsError('Telegram needs a bot token and a chat ID.');
89
+ }
90
+ if (next.cliq.enabled && (!next.cliq.token || !next.cliq.endpoint)) {
91
+ throw new SettingsError('Cliq needs a webhook token and a message endpoint.');
92
+ }
93
+ return next;
94
+ }
95
+ export async function notificationSettings(p, req, deps, body) {
96
+ const json = (status, body) => ({ status, body, headers: { 'cache-control': 'no-store' } });
97
+ if (p.length === 1 && req.method === 'GET') {
98
+ const settings = (await deps.store.getInstance()).notifications ?? defaultNotifications();
99
+ return json(200, { notifications: notificationView(settings) });
100
+ }
101
+ if (p.length === 1 && req.method === 'PATCH') {
102
+ try {
103
+ const instance = await deps.store.updateInstance((cur) => ({
104
+ ...cur, notifications: patchNotifications(cur.notifications ?? defaultNotifications(), body),
105
+ }));
106
+ return json(200, { notifications: notificationView(instance.notifications) });
107
+ }
108
+ catch (error) {
109
+ // Validation messages are ours; never expose backend exceptions or credentials.
110
+ if (error instanceof SettingsError) {
111
+ return json(400, { error: error.message });
112
+ }
113
+ throw error;
114
+ }
115
+ }
116
+ if (p.length === 2 && p[1] === 'test' && req.method === 'POST') {
117
+ const provider = body.provider;
118
+ if (provider !== 'telegram' && provider !== 'cliq')
119
+ return json(400, { error: 'Choose Telegram or Cliq.' });
120
+ const settings = (await deps.store.getInstance()).notifications ?? defaultNotifications();
121
+ const target = settings[provider];
122
+ if (!target.enabled)
123
+ return json(400, { error: 'Save and enable this destination first.' });
124
+ const now = deps.now(), start = Math.floor(now / 60_000) * 60_000;
125
+ if (!await deps.store.hit(`notification-test:${provider}:${start}`, 3, start + 60_000)) {
126
+ return json(429, { error: 'Wait a minute before sending another test.' });
127
+ }
128
+ if (!deps.sendNotification)
129
+ return json(503, { error: 'Notification delivery is unavailable.' });
130
+ try {
131
+ await deps.sendNotification(provider, target, 'Heresay notifications are connected. You will receive the events selected in Notifications.');
132
+ return json(200, { ok: true });
133
+ }
134
+ catch {
135
+ return json(502, { error: 'Test could not be delivered. Check the token, destination, and bot permissions, then try again.' });
136
+ }
137
+ }
138
+ return json(404, { error: 'not found' });
139
+ }
140
+ /** Metadata only: open reports and reporter details must never flow into an integration. */
141
+ export async function notify(event, project, reportId, deps) {
142
+ try {
143
+ const settings = (await deps.store.getInstance())?.notifications;
144
+ if (!settings?.events[event] || !deps.sendNotification)
145
+ return;
146
+ const labels = {
147
+ new_report: 'A new report needs your review', accepted: 'A report was accepted for a coding agent',
148
+ fixed: 'A report was marked fixed', handoff: 'A coding agent handed off a report',
149
+ };
150
+ const origin = deps.selfOrigins?.[0];
151
+ const text = `Heresay: ${labels[event]}.\nApp: ${project.name}\nReport: ${reportId}`
152
+ + (origin ? `\n${origin}/app/#/apps/${encodeURIComponent(project.id)}` : '');
153
+ await Promise.all(['telegram', 'cliq'].map(async (provider) => {
154
+ if (!settings[provider].enabled)
155
+ return;
156
+ try {
157
+ await deps.sendNotification(provider, settings[provider], text);
158
+ deps.log('api.notification_sent', { provider, notification_event: event, project_id: project.id, report_id: reportId });
159
+ }
160
+ catch {
161
+ // Transport errors may contain credential-bearing URLs. Never log those errors.
162
+ deps.log('api.notification_failed', { provider, notification_event: event, project_id: project.id, report_id: reportId });
163
+ }
164
+ }));
165
+ }
166
+ catch {
167
+ // A notification outage must not turn a saved report/status change into a failed request.
168
+ deps.log('api.notification_failed', { notification_event: event, project_id: project.id, report_id: reportId });
169
+ }
170
+ }
171
+ /** Shared HTTP transport; a backend adapter supplies this to the portable core. */
172
+ export function notificationSender(http = fetch) {
173
+ return async (provider, destination, text) => {
174
+ let url, body;
175
+ if (!destination.token)
176
+ throw new Error('Notification token missing.');
177
+ if (provider === 'telegram' && 'chat_id' in destination) {
178
+ url = `https://api.telegram.org/bot${destination.token}/sendMessage`;
179
+ body = { chat_id: destination.chat_id, text, link_preview_options: { is_disabled: true } };
180
+ }
181
+ else if (provider === 'cliq' && 'endpoint' in destination && validCliqEndpoint(destination.endpoint)) {
182
+ const u = new URL(destination.endpoint);
183
+ u.searchParams.set('zapikey', destination.token);
184
+ url = u.href;
185
+ body = { text };
186
+ }
187
+ else {
188
+ throw new Error('Invalid notification destination.');
189
+ }
190
+ // Await within the request so serverless runtimes cannot stop before delivery. Bounded,
191
+ // with no retries: report creation and triage are never rolled back by a provider outage.
192
+ const response = await http(url, {
193
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
194
+ signal: AbortSignal.timeout(5000), redirect: 'error',
195
+ });
196
+ if (!response.ok)
197
+ throw new Error('Notification provider rejected the message.');
198
+ if (provider === 'telegram') {
199
+ const result = await response.json();
200
+ if (result.ok !== true)
201
+ throw new Error('Telegram rejected the message.');
202
+ }
203
+ };
204
+ }
205
+ //# sourceMappingURL=notifications.js.map
@@ -1,3 +1,3 @@
1
1
  /** The Heresay release. Bumped by the release script; the CLI and /v1/health report it. */
2
- export const VERSION = '0.2.13';
2
+ export const VERSION = '0.2.15';
3
3
  //# sourceMappingURL=version.js.map
@@ -8,6 +8,7 @@ import { auth, db } from './admin.js';
8
8
  import { FirestoreStore } from './firestore-store.js';
9
9
  import { handle } from '../../core/handler.js';
10
10
  import { VERSION } from '../../core/version.js';
11
+ import { notificationSender } from '../../core/notifications.js';
11
12
  const deps = {
12
13
  store: new FirestoreStore(db),
13
14
  async verifyIdToken(token) {
@@ -23,6 +24,7 @@ const deps = {
23
24
  log: (event, fields) => logger.info(event, { event, ...fields }),
24
25
  version: VERSION,
25
26
  selfOrigins: selfOrigins(),
27
+ sendNotification: notificationSender(),
26
28
  };
27
29
  function selfOrigins() {
28
30
  const id = process.env.GCLOUD_PROJECT;
@@ -9,7 +9,7 @@
9
9
  "scripts": {
10
10
  "build": "tsc -p tsconfig.json",
11
11
  "typecheck": "tsc -p tsconfig.json --noEmit",
12
- "test": "tsc -p tsconfig.test.json && node --test 'lib-test/test/handler.test.js' 'lib-test/test/agent.test.js' 'lib-test/test/store-memory.test.js'",
12
+ "test": "tsc -p tsconfig.test.json && node --test 'lib-test/test/handler.test.js' 'lib-test/test/agent.test.js' 'lib-test/test/notifications.test.js' 'lib-test/test/store-memory.test.js'",
13
13
  "build:test": "tsc -p tsconfig.test.json"
14
14
  },
15
15
  "dependencies": {
@@ -44,6 +44,7 @@
44
44
  <nav class="tabs" aria-label="Main">
45
45
  <a href="#/" data-nav="apps">Apps</a>
46
46
  <a href="#/team" data-nav="team">Team</a>
47
+ <a href="#/notifications" data-nav="notifications">Notifications</a>
47
48
  </nav>
48
49
  <span class="spacer"></span>
49
50
  <span id="who" class="who"></span>
@@ -134,7 +134,7 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
134
134
  @media (prefers-reduced-motion: reduce) { .wait::before { animation:none; } }
135
135
  /* loading: the Glance mark, faded in late so quick loads never flash it */
136
136
  .loading { display:grid; place-items:center; padding:12vh 0; animation:loading-in .2s .3s both; }
137
- .loading img { width:56px; height:56px; }
137
+ .loading img { width:96px; height:96px; }
138
138
  .loading.boot { padding-top:30vh; }
139
139
  .loading:not(.boot):not(:only-child) { display:none; }
140
140
  @keyframes loading-in { from { opacity:0; } }
@@ -328,3 +328,17 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
328
328
  .am-titlebar i { width:11px; height:11px; border-radius:50%; background:#ff5f57; } .am-titlebar i:nth-child(2) { background:#febc2e; } .am-titlebar i:nth-child(3) { background:#28c840; }
329
329
  .am-titlebar span { flex:1; text-align:center; margin-right:40px; }
330
330
  .am-mac .am-content h3 { font-size:22px; }
331
+
332
+ /* notification settings */
333
+ .notification-form { max-width:none; }
334
+ .notification-form .notification-choice { display:flex; align-items:flex-start; gap:12px; margin:14px 0; }
335
+ .notification-choice input[type=checkbox] { width:18px; height:18px; flex:none; margin:3px 0 0; accent-color:var(--acc); }
336
+ .notification-choice .hint { display:block; margin:2px 0 0; }
337
+ .notification-form input[type=text], .notification-form input[type=password] { width:100%; min-width:0; }
338
+ .notification-form .row { margin-top:22px; }
339
+ @media (max-width:600px) {
340
+ .top { flex-wrap:wrap; gap:8px 12px; padding:12px 16px; }
341
+ .top .tabs { order:5; width:100%; }
342
+ .top .tabs a { padding:6px 10px; }
343
+ .top .who { max-width:130px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
344
+ }
@@ -200,13 +200,15 @@
200
200
  var query = new URLSearchParams(hash.split('?')[1] || '');
201
201
  var parts = hash.split('?')[0].split('/').filter(Boolean);
202
202
  document.querySelectorAll('[data-nav]').forEach(function (a) {
203
- a.setAttribute('aria-current', String((parts[0] === 'team') === (a.dataset.nav === 'team')));
203
+ var active = parts[0] === 'team' || parts[0] === 'notifications' ? parts[0] : 'apps';
204
+ a.setAttribute('aria-current', String(active === a.dataset.nav));
204
205
  });
205
206
  var view = $('view');
206
207
  view.textContent = '';
207
208
  view.appendChild(loading());
208
209
  view.classList.remove('wide');
209
210
  if (parts[0] === 'team') return teamView(view);
211
+ if (parts[0] === 'notifications') return notificationsView(view);
210
212
  if (parts[0] === 'connect') return connectView(view, query);
211
213
  if (parts[0] === 'new') return newAppView(view, parts[1], query);
212
214
  if (parts[0] === 'apps' && parts[1]) {
@@ -815,7 +817,7 @@
815
817
  var pos = cfg.position || 'bottomTrailing';
816
818
  var place = (/top/.test(pos) ? 'top:' + (off + (mac ? 34 : 54)) + 'px;' : 'bottom:' + (off + (mac ? 0 : 20)) + 'px;') +
817
819
  (pos === 'bottom' ? 'left:50%;transform:translateX(-50%);' : /Leading/.test(pos) ? 'left:' + off + 'px;' : 'right:' + off + 'px;');
818
- var sz = { small: [11, 10, 6, 13], large: [16, 18, 12, 21] }[cfg.size] || [13, 14, 9, 17];
820
+ var sz = { small: [11, 10, 6, 16], large: [16, 18, 12, 26] }[cfg.size] || [13, 14, 9, 21];
819
821
  var neutral = cfg.fill === 'neutral';
820
822
  var icon = cfg.button === 'icon';
821
823
  var btnDark = dark || darkMode;
@@ -831,7 +833,7 @@
831
833
  return '<div class="am-type"><span class="am-ti" style="color:' + acc + ';background:' + acc + '1f">' + TYPE_ICON[t] + '</span><span><b>' + esc(tw[0]) + '</b><i>' + esc(tw[1]) + '</i></span></div>';
832
834
  }).join('');
833
835
  var tabs = [w.tabs[0], w.tabs[1]].concat(cfg.showsPreferences === 'false' ? [] : [w.tabs[2]]);
834
- var powered = '<div class="am-powered">' + mark(markC, 11) + esc(w.powered) + '</div>';
836
+ var powered = '<div class="am-powered">' + mark(markC, 14) + esc(w.powered) + '</div>';
835
837
  var head = '<div class="am-head">' + mark(markC, 28) + '<div><b>' + esc(w.sendFeedback) + '</b><span>' + esc(fmt(w.straight, { app: productName(p) })) + '</span></div>' + (mac ? '' : '<em>✕</em>') + '</div>' +
836
838
  '<div class="am-seg">' + tabs.map(function (t, i) { return '<span' + (i === 0 ? ' class="on"' : '') + '>' + esc(t) + '</span>'; }).join('') + '</div>';
837
839
  var form = '<div class="am-body"><p class="am-lab">' + esc(w.what) + '</p><div class="am-types' + (mac ? ' grid' : '') + '">' + typeCards + '</div>' +
@@ -1536,6 +1538,117 @@
1536
1538
  repo.focus();
1537
1539
  }
1538
1540
 
1541
+ // ---- notifications ---------------------------------------------------------------------
1542
+
1543
+ function notificationsView(view) {
1544
+ view.appendChild(el('div', { class: 'head' }, [el('h1', { text: 'Notifications' })]));
1545
+ view.appendChild(el('p', { class: 'mute', text: 'Know when a report needs a hearing, or when work moves forward. These settings apply to every app in this Heresay.' }));
1546
+ if (me.role !== 'owner') {
1547
+ view.appendChild(el('section', { class: 'card' }, [el('p', { text: 'An owner can connect Telegram or Zoho Cliq and choose which events your team receives.' }), el('a', { href: '#/team', text: 'See team owners' })]));
1548
+ return;
1549
+ }
1550
+ var content = el('div');
1551
+ view.appendChild(content);
1552
+ api('GET', '/notifications').then(function (b) {
1553
+ var settings = b.notifications;
1554
+ var choices = [
1555
+ ['new_report', 'New reports', 'A new report is waiting for a person to review it.'],
1556
+ ['accepted', 'Accepted reports', 'A person approved a report for a coding agent.'],
1557
+ ['fixed', 'Reports marked fixed', 'A teammate or coding agent marked a report fixed.'],
1558
+ ['handoff', 'Agent handoffs', 'An agent handed accepted work to another repo.'],
1559
+ ];
1560
+ var eventInputs = {};
1561
+ var eventsMsg = el('p', { role: 'status' });
1562
+ var eventSave = el('button', { class: 'btn primary', type: 'submit', text: 'Save events' });
1563
+ var eventsForm = el('form', { class: 'form notification-form' }, choices.map(function (choice) {
1564
+ var input = eventInputs[choice[0]] = el('input', { type: 'checkbox', name: choice[0], checked: settings.events[choice[0]] });
1565
+ return el('label', { class: 'notification-choice' }, [input, el('span', {}, [el('b', { text: choice[1] }), el('span', { class: 'hint', text: choice[2] })])]);
1566
+ }).concat([el('div', { class: 'row' }, [eventSave]), eventsMsg]));
1567
+ eventsForm.onsubmit = function (e) {
1568
+ e.preventDefault();
1569
+ var events = {};
1570
+ Object.keys(eventInputs).forEach(function (key) { events[key] = eventInputs[key].checked; eventInputs[key].disabled = true; });
1571
+ eventSave.disabled = true;
1572
+ eventsMsg.className = 'hint'; eventsMsg.textContent = 'Saving…';
1573
+ api('PATCH', '/notifications', { events: events }).then(function () {
1574
+ eventsMsg.className = 'ok-msg'; eventsMsg.textContent = 'Notification events saved.';
1575
+ }).catch(function (x) { eventsMsg.className = 'err'; eventsMsg.textContent = x.message; }).finally(function () {
1576
+ eventSave.disabled = false;
1577
+ Object.keys(eventInputs).forEach(function (key) { eventInputs[key].disabled = false; });
1578
+ });
1579
+ };
1580
+ content.appendChild(el('section', { class: 'card' }, [el('h2', { text: 'When to notify' }), eventsForm]));
1581
+ content.appendChild(el('p', { class: 'hint', text: 'Alerts include the app name, event, report ID, and a link to the dashboard. Reporter text and contact details stay in Heresay.' }));
1582
+ destination('telegram', 'Telegram', settings.telegram);
1583
+ destination('cliq', 'Zoho Cliq', settings.cliq);
1584
+
1585
+ function destination(provider, title, saved) {
1586
+ var telegram = provider === 'telegram', dirty = false;
1587
+ var enabled = el('input', { type: 'checkbox', name: provider + '_enabled', checked: saved.enabled });
1588
+ var token = el('input', { type: 'password', name: provider + '_token', maxlength: 512, autocomplete: 'new-password', spellcheck: 'false' });
1589
+ var address = el('input', { type: 'text', name: telegram ? 'chat_id' : 'endpoint', value: telegram ? saved.chat_id : saved.endpoint, maxlength: telegram ? 100 : 300, autocomplete: 'off', spellcheck: 'false', placeholder: telegram ? '-1001234567890 or @yourchannel' : 'https://cliq.zoho.com/api/v2/channelsbyname/team/message' });
1590
+ var tokenHint = el('p', { class: 'hint' });
1591
+ var message = el('p', { role: 'status' });
1592
+ var save = el('button', { class: 'btn primary', type: 'submit', text: 'Save ' + title });
1593
+ var test = el('button', { class: 'btn', type: 'button', text: 'Send test notification' });
1594
+ var remove = el('button', { class: 'btn ghost', type: 'button', text: 'Disconnect' });
1595
+ var form = el('form', { class: 'form notification-form' }, [
1596
+ el('label', { class: 'notification-choice' }, [enabled, el('b', { text: 'Enable ' + title + ' notifications' })]),
1597
+ el('label', {}, [telegram ? 'Bot token' : 'Webhook token', token]), tokenHint,
1598
+ el('label', {}, [telegram ? 'Chat ID or channel username' : 'Message endpoint', address]),
1599
+ el('p', { class: 'hint' }, telegram
1600
+ ? ['Create a bot with BotFather, start a conversation with it (or add it to your group), and enter the target chat ID. For a channel, add the bot as an administrator. ', el('a', { href: 'https://core.telegram.org/bots/tutorial', target: '_blank', rel: 'noopener noreferrer', text: 'Telegram setup guide' })]
1601
+ : ['In Cliq, open Bots & Tools → Webhook Tokens and generate a token. Use the bot or channel message endpoint from Get Webhook URL, without the ?zapikey part. Use your region’s Cliq domain. ', el('a', { href: 'https://www.zoho.com/cliq/help/platform/webhook-tokens.html', target: '_blank', rel: 'noopener noreferrer', text: 'Cliq setup guide' })]),
1602
+ el('div', { class: 'row' }, [save, test, remove]), message,
1603
+ ]);
1604
+ function refresh() {
1605
+ token.placeholder = saved.configured ? 'Leave blank to keep the saved token' : 'Paste your token';
1606
+ tokenHint.textContent = saved.configured ? 'A token is saved. Paste a new one to replace it.' : 'Your token is saved on the server and is never displayed here.';
1607
+ test.disabled = dirty || !saved.enabled;
1608
+ remove.disabled = !saved.configured;
1609
+ }
1610
+ function busy(on) {
1611
+ form.querySelectorAll('input, button').forEach(function (control) { control.disabled = on; });
1612
+ if (!on) refresh();
1613
+ }
1614
+ function feedback(text, bad) { message.className = bad ? 'err' : 'ok-msg'; message.textContent = text; }
1615
+ form.oninput = function () { dirty = true; test.disabled = true; feedback('Save your changes before sending a test.'); };
1616
+ form.onsubmit = function (e) {
1617
+ e.preventDefault();
1618
+ var patch = { enabled: enabled.checked, token: token.value.trim() };
1619
+ patch[telegram ? 'chat_id' : 'endpoint'] = address.value.trim();
1620
+ var body = {}; body[provider] = patch;
1621
+ busy(true); feedback('Saving…');
1622
+ api('PATCH', '/notifications', body).then(function (result) {
1623
+ saved = result.notifications[provider]; dirty = false; token.value = '';
1624
+ feedback(title + ' settings saved. Send a test to check delivery.');
1625
+ }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
1626
+ };
1627
+ test.onclick = function () {
1628
+ busy(true); feedback('Sending a test…');
1629
+ api('POST', '/notifications/test', { provider: provider }).then(function () {
1630
+ feedback('Test notification sent. Check ' + title + '.');
1631
+ }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
1632
+ };
1633
+ remove.onclick = function () {
1634
+ var body = {}, patch = { enabled: false, token: null };
1635
+ patch[telegram ? 'chat_id' : 'endpoint'] = '';
1636
+ body[provider] = patch;
1637
+ busy(true); feedback('Disconnecting…');
1638
+ api('PATCH', '/notifications', body).then(function (result) {
1639
+ saved = result.notifications[provider]; dirty = false; enabled.checked = false; token.value = ''; address.value = '';
1640
+ feedback(title + ' disconnected. The saved token was removed.');
1641
+ }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
1642
+ };
1643
+ refresh();
1644
+ content.appendChild(el('section', { class: 'card' }, [el('h2', { text: title }), form]));
1645
+ }
1646
+ }).catch(function (x) {
1647
+ content.appendChild(el('p', { class: 'err', role: 'alert', text: x.message }));
1648
+ content.appendChild(el('button', { class: 'btn', text: 'Retry', onclick: function () { route(); } }));
1649
+ });
1650
+ }
1651
+
1539
1652
  // ---- team ------------------------------------------------------------------------------
1540
1653
 
1541
1654
  function teamView(view) {
@@ -452,8 +452,8 @@
452
452
  'box-shadow:0 4px 14px rgba(0,0,0,.18);cursor:pointer;font-weight:600;white-space:nowrap}',
453
453
  '.fab.r{right:var(--fb-x)}.fab.l{left:var(--fb-x)}.fab.c{left:50%;transform:translateX(-50%)}',
454
454
  '.fab.b{bottom:var(--fb-y)}.fab.t{top:var(--fb-y)}',
455
- '.fab.sz-small{padding:6px 10px;font-size:12.5px}.fab.sz-small svg{width:14px;height:14px}',
456
- '.fab.sz-large{padding:12px 18px;font-size:16px}.fab.sz-large svg{width:22px;height:22px}',
455
+ '.fab.sz-small{padding:6px 10px;font-size:12.5px}.fab.sz-small svg{width:17px;height:17px}',
456
+ '.fab.sz-large{padding:12px 18px;font-size:16px}.fab.sz-large svg{width:27px;height:27px}',
457
457
  '.fab.st-icon{padding:10px;border-radius:50%}.fab.st-icon.sz-small{padding:7px}.fab.st-icon.sz-large{padding:13px}',
458
458
  '.fab.st-icon .lbl{display:none}',
459
459
  '.fab.st-tab{writing-mode:vertical-rl;top:50%;bottom:auto;transform:translateY(-50%);padding:14px 8px;right:0;border-radius:10px 0 0 10px;border-right:0}',
@@ -522,7 +522,7 @@
522
522
  '.small{font-size:12px;color:var(--fb-mute)}',
523
523
  '.send{padding:9px 16px;border:0;border-radius:10px;background:var(--fb-acc);color:var(--fb-acc-fg);font-weight:600;cursor:pointer}',
524
524
  '.send[disabled]{opacity:.5;cursor:default}',
525
- '.send.busy{opacity:1;display:inline-flex;align-items:center;gap:7px}.send .mark{color:var(--fb-acc-fg)}.send .eye{fill:var(--fb-acc)}',
525
+ '.send.busy{opacity:1;display:inline-flex;align-items:center;gap:7px}.send .mark{color:var(--fb-acc-fg)}.send .mark svg{width:20px;height:20px}.send .eye{fill:var(--fb-acc)}',
526
526
  // The loader: the mark's eyes look left, look right, blink (brand/svg/loaders/heresay-loader-glance.svg, faster).
527
527
  '.glance svg *{transform-box:view-box}.glance .eyes{animation:fb-look 1.6s ease-in-out infinite}.glance .e{animation:fb-blink 1.6s infinite}',
528
528
  '@keyframes fb-look{0%,10%{transform:none}25%,40%{transform:translate(-9px,1px)}55%,70%{transform:translate(9px,-1px)}85%,100%{transform:none}}',
@@ -541,7 +541,7 @@
541
541
  '.by{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-top:14px;padding-top:10px;',
542
542
  'border-top:1px solid var(--fb-line);font-size:11.5px;color:var(--fb-mute)}',
543
543
  '.by a{display:inline-flex;align-items:center;gap:4px;margin-left:auto;color:inherit;text-decoration:none;font-weight:600;white-space:nowrap}',
544
- '.by a:hover{text-decoration:underline}.by .mark svg{width:13px;height:13px}',
544
+ '.by a:hover{text-decoration:underline}.by .mark svg{width:16px;height:16px}',
545
545
  ].join('');
546
546
 
547
547
  /**
@@ -594,7 +594,7 @@
594
594
  function markEl(glance) {
595
595
  var s = document.createElement('span');
596
596
  s.className = glance ? 'mark glance' : 'mark';
597
- s.innerHTML = '<svg viewBox="0 0 200 200" width="18" height="18" aria-hidden="true"><path d="M174 100L177 105L180 110L181 116L180 121L178 126L174 131L169 134L164 137L159 139L154 141L149 143L146 146L143 149L141 154L139 159L137 164L134 169L131 174L126 178L121 180L116 181L110 180L105 177L100 174L95 170L91 167L87 164L83 163L79 162L74 162L69 163L63 164L57 164L51 164L46 162L41 159L38 154L36 149L36 143L36 137L37 131L38 126L38 121L37 117L36 113L33 109L30 105L26 100L23 95L20 90L19 84L20 79L22 74L26 69L31 66L36 63L41 61L46 59L51 57L54 54L57 51L59 46L61 41L63 36L66 31L69 26L74 22L79 20L84 19L90 20L95 23L100 26L105 30L109 33L113 36L117 37L121 38L126 38L131 37L137 36L143 36L149 36L154 38L159 41L162 46L164 51L164 57L164 63L163 69L162 74L162 79L163 83L164 87L167 91L170 95Z" fill="currentColor"/><g class="eyes"><g class="e" style="transform-origin:80px 106px"><path class="eye" d="M-13 12 C-13 -8 -2 -24 17 -32 L20 -25 C8 -18 2 -9 3 -1 A13 13 0 1 1 -13 12 Z" transform="translate(80 106) rotate(-24) scale(1.25)"/></g><g class="e" style="transform-origin:124px 101px"><path class="eye" d="M-13 12 C-13 -8 -2 -24 17 -32 L20 -25 C8 -18 2 -9 3 -1 A13 13 0 1 1 -13 12 Z" transform="translate(124 101) rotate(-24) scale(1.25)"/></g></g></svg>';
597
+ s.innerHTML = '<svg viewBox="0 0 200 200" width="22" height="22" aria-hidden="true"><path d="M174 100L177 105L180 110L181 116L180 121L178 126L174 131L169 134L164 137L159 139L154 141L149 143L146 146L143 149L141 154L139 159L137 164L134 169L131 174L126 178L121 180L116 181L110 180L105 177L100 174L95 170L91 167L87 164L83 163L79 162L74 162L69 163L63 164L57 164L51 164L46 162L41 159L38 154L36 149L36 143L36 137L37 131L38 126L38 121L37 117L36 113L33 109L30 105L26 100L23 95L20 90L19 84L20 79L22 74L26 69L31 66L36 63L41 61L46 59L51 57L54 54L57 51L59 46L61 41L63 36L66 31L69 26L74 22L79 20L84 19L90 20L95 23L100 26L105 30L109 33L113 36L117 37L121 38L126 38L131 37L137 36L143 36L149 36L154 38L159 41L162 46L164 51L164 57L164 63L163 69L162 74L162 79L163 83L164 87L167 91L170 95Z" fill="currentColor"/><g class="eyes"><g class="e" style="transform-origin:80px 106px"><path class="eye" d="M-13 12 C-13 -8 -2 -24 17 -32 L20 -25 C8 -18 2 -9 3 -1 A13 13 0 1 1 -13 12 Z" transform="translate(80 106) rotate(-24) scale(1.25)"/></g><g class="e" style="transform-origin:124px 101px"><path class="eye" d="M-13 12 C-13 -8 -2 -24 17 -32 L20 -25 C8 -18 2 -9 3 -1 A13 13 0 1 1 -13 12 Z" transform="translate(124 101) rotate(-24) scale(1.25)"/></g></g></svg>';
598
598
  return s;
599
599
  }
600
600