pgkiln 0.31.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +2 -2
  2. package/SECURITY.md +10 -0
  3. package/db/migrations/076_form_lost_update.sql +50 -0
  4. package/db/migrations/077_warn_unsaved.sql +41 -0
  5. package/db/migrations/078_url_region.sql +12 -0
  6. package/db/migrations/079_developer_toolbar.sql +53 -0
  7. package/db/migrations/080_search.sql +326 -0
  8. package/db/migrations/081_mail.sql +621 -0
  9. package/db/migrations/082_app_backups.sql +73 -0
  10. package/db/migrations/083_availability.sql +156 -0
  11. package/db/migrations/084_feedback.sql +46 -0
  12. package/db/migrations/085_page_behaviour.sql +65 -0
  13. package/db/migrations/086_data_settings.sql +599 -0
  14. package/docs/apex-feature-parity.md +55 -35
  15. package/docs/guide/01-installation.md +1 -0
  16. package/docs/guide/03-builder.md +118 -2
  17. package/docs/guide/04-pages-and-regions.md +115 -0
  18. package/docs/guide/05-items.md +47 -0
  19. package/docs/guide/06-processing.md +210 -2
  20. package/docs/guide/07-dynamic-actions.md +60 -2
  21. package/docs/guide/08-security.md +13 -2
  22. package/docs/guide/09-reference.md +21 -0
  23. package/docs/guide/11-from-apex.md +5 -1
  24. package/docs/guide/12-development.md +33 -1
  25. package/docs/guide/14-globalization.md +15 -0
  26. package/docs/guide/15-extensions.md +1 -1
  27. package/docs/guide/18-cli.md +30 -1
  28. package/docs/guide/20-ai-agents.md +3 -2
  29. package/examples/hr/hr_50_search.sql +47 -0
  30. package/examples/hr/hr_51_mail.sql +70 -0
  31. package/examples/hr/hr_52_feedback.sql +15 -0
  32. package/examples/hr/hr_53_data_settings.sql +108 -0
  33. package/package.json +3 -1
  34. package/public/app.css +62 -0
  35. package/public/app.js +408 -11
  36. package/public/builder.css +11 -0
  37. package/public/builder.js +27 -0
  38. package/src/app.ts +8 -0
  39. package/src/appfiles.ts +12 -0
  40. package/src/automations.ts +12 -0
  41. package/src/builder/advisor.ts +54 -14
  42. package/src/builder/arrange.ts +2 -2
  43. package/src/builder/availability.ts +74 -0
  44. package/src/builder/backups.ts +134 -0
  45. package/src/builder/components.ts +109 -15
  46. package/src/builder/designer.ts +8 -3
  47. package/src/builder/feedback.ts +82 -0
  48. package/src/builder/forms.ts +4 -1
  49. package/src/builder/home.ts +3 -0
  50. package/src/builder/locks.ts +15 -5
  51. package/src/builder/mail.ts +425 -0
  52. package/src/builder/newapp.ts +1 -1
  53. package/src/builder/region-help.ts +71 -0
  54. package/src/builder/routes.ts +44 -1
  55. package/src/builder/search.ts +4 -4
  56. package/src/builder/shared.ts +3 -2
  57. package/src/builder/ui.ts +7 -1
  58. package/src/cli/apps.ts +46 -5
  59. package/src/cli/main.ts +21 -5
  60. package/src/cli/mcp.ts +16 -4
  61. package/src/cli/replace.ts +36 -4
  62. package/src/geocode.ts +44 -0
  63. package/src/i18n/ar.ts +39 -0
  64. package/src/i18n/cs.ts +39 -0
  65. package/src/i18n/da.ts +39 -0
  66. package/src/i18n/de.ts +39 -0
  67. package/src/i18n/el.ts +39 -0
  68. package/src/i18n/es.ts +39 -0
  69. package/src/i18n/fi.ts +39 -0
  70. package/src/i18n/fr.ts +39 -0
  71. package/src/i18n/he.ts +39 -0
  72. package/src/i18n/it.ts +39 -0
  73. package/src/i18n/ja.ts +39 -0
  74. package/src/i18n/ko.ts +39 -0
  75. package/src/i18n/nb.ts +39 -0
  76. package/src/i18n/pl.ts +39 -0
  77. package/src/i18n/pt.ts +39 -0
  78. package/src/i18n/ru.ts +39 -0
  79. package/src/i18n/sv.ts +39 -0
  80. package/src/i18n/tr.ts +39 -0
  81. package/src/i18n/uk.ts +39 -0
  82. package/src/i18n/zh.ts +39 -0
  83. package/src/i18n.ts +78 -0
  84. package/src/mail/mail.ts +148 -0
  85. package/src/mail/providers.ts +444 -0
  86. package/src/metadata.ts +26 -8
  87. package/src/runtime/ajax.ts +97 -0
  88. package/src/runtime/authz.ts +1 -1
  89. package/src/runtime/availability.ts +37 -0
  90. package/src/runtime/context.ts +46 -6
  91. package/src/runtime/data-export.ts +94 -0
  92. package/src/runtime/data-items.ts +194 -0
  93. package/src/runtime/devbar.ts +182 -0
  94. package/src/runtime/engine.ts +26 -1
  95. package/src/runtime/feedback.ts +128 -0
  96. package/src/runtime/items.ts +8 -0
  97. package/src/runtime/processes.ts +83 -2
  98. package/src/runtime/regions.ts +8 -0
  99. package/src/runtime/render.ts +33 -7
  100. package/src/runtime/rest.ts +4 -0
  101. package/src/runtime/routes.ts +59 -5
  102. package/src/runtime/search.ts +252 -0
  103. package/src/runtime/url-region.ts +93 -0
  104. package/src/security.ts +11 -1
  105. package/src/server.ts +2 -0
  106. package/src/session.ts +8 -2
  107. package/src/workingcopy.ts +2 -2
@@ -0,0 +1,425 @@
1
+ import type { FastifyInstance } from 'fastify';
2
+ import { owner } from '../db.ts';
3
+ import { html, raw } from '../html.ts';
4
+ import { icon } from '../icons.ts';
5
+ import { senderAllowed, sendWith, type MailService } from '../mail/mail.ts';
6
+ import { deliver, MailError, PROVIDER_LABELS, PROVIDERS, settingsProblems, verifyConnection, type Provider, type ServiceSettings } from '../mail/providers.ts';
7
+ import { decryptSecret, encryptSecret, secretKeyConfigured } from '../secrets.ts';
8
+ import { clientIp, logActivity, type Session } from '../session.ts';
9
+ import { isAdmin } from './locks.ts';
10
+ import { back, BASE, csrf, developer, flash, input, region, select, send, shell, type Req } from './ui.ts';
11
+
12
+ // Workspace utilities → Mail services (administrators): the mail services of
13
+ // this installation (SMTP with a password or OAuth2, Microsoft Graph, Amazon
14
+ // SES, Resend, Postmark, SendGrid, Mailgun, or log only), the From addresses
15
+ // each may send as, which applications send through it (with their From
16
+ // address and a daily limit), a test, and the recent mail. Applications →
17
+ // Activity → Mail (developers): the application's mail, with retry and
18
+ // cancel. Secrets are encrypted (src/secrets.ts) and never sent back to the
19
+ // browser.
20
+
21
+ const ADDRESS = /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/;
22
+ const SENDER = /^(@|[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/;
23
+
24
+ const check = (name: string, label: string, on: boolean, help?: string) =>
25
+ html`<div class="field"><label class="check"><input type="checkbox" name="${name}" value="true"${on ? raw(' checked') : ''}> ${label}</label>${help ? html`<small class="help">${help}</small>` : ''}</div>`;
26
+ const when = (d: Date | string | null) => (d ? new Date(d).toISOString().slice(0, 19).replace('T', ' ') : '');
27
+
28
+ const SECRET_LABEL: Record<Provider, string> = {
29
+ smtp: 'Password, or the client secret (OAuth2)', graph: 'Client secret', ses: 'Secret access key', resend: 'API key',
30
+ postmark: 'Server token', sendgrid: 'API key', mailgun: 'API key', log: 'Secret (not used)',
31
+ };
32
+
33
+ /** What each provider is, for the choice of a new service. */
34
+ const PROVIDER_TEXT: Record<Provider, [icon: string, text: string]> = {
35
+ smtp: ['send', 'Any SMTP server or relay. Sign in with a password, or with OAuth2 (Exchange Online, Google Workspace).'],
36
+ graph: ['building', 'Microsoft 365 through the Graph API, as an Entra application with Mail.Send.'],
37
+ ses: ['database', 'Amazon Simple Email Service (API v2), with an IAM access key.'],
38
+ resend: ['send', 'Resend\'s HTTP API, with an API key.'],
39
+ postmark: ['send', 'Postmark\'s HTTP API, with a server token.'],
40
+ sendgrid: ['send', 'SendGrid\'s HTTP API, with an API key.'],
41
+ mailgun: ['send', 'Mailgun\'s HTTP API, with an API key and a sending domain.'],
42
+ log: ['list', 'For development and demos: the server writes each mail to its log and sends nothing.'],
43
+ };
44
+
45
+ /** Step 1 of a new service: choose the provider. */
46
+ function providerChoice() {
47
+ return html`<div class="ab-tiles ab-tiles-wrap">${PROVIDERS.map((p) =>
48
+ html`<a class="ab-tile" href="${BASE}/mail/new?provider=${p}"><span class="ab-tile-icon">${icon(PROVIDER_TEXT[p][0])}</span><strong>${PROVIDER_LABELS[p]}</strong><span>${PROVIDER_TEXT[p][1]}</span></a>`)}</div>`;
49
+ }
50
+
51
+ /** The settings of one provider only, in groups (a new service, or an existing one switching provider). */
52
+ function serviceForm(x: Partial<MailService> & { has_secret?: boolean }, provider: Provider, action: string, csrfField: ReturnType<typeof csrf>, isNew: boolean,
53
+ tried: { ok: boolean; text: string; to?: string; from?: string } | null = null) {
54
+ const s: ServiceSettings = x.provider === provider ? x.settings ?? {} : { default_from: x.settings?.default_from };
55
+ const group = (legend: string, body: unknown, help?: string) =>
56
+ html`<fieldset class="prop-group"><legend>${legend}</legend>${help ? html`<p class="muted u-mt0">${help}</p>` : ''}${body}</fieldset>`;
57
+ const oauth = (scope: string) => html`<div class="form-grid">
58
+ ${input('tenant_id', 'Tenant ID (Microsoft Entra)', s.tenant_id, { placeholder: 'contoso.onmicrosoft.com or its GUID' })}
59
+ ${input('client_id', 'Client (application) ID', s.client_id)}
60
+ ${input('token_url', 'Token URL', s.token_url, { placeholder: 'empty: Microsoft Entra of the tenant', help: 'Another identity provider\'s token endpoint (client credentials grant), e.g. Google\'s.' })}
61
+ ${input('scope', 'Scope', s.scope, { placeholder: `empty: ${scope}` })}
62
+ </div>`;
63
+ const settings =
64
+ provider === 'smtp'
65
+ ? html`${group('SMTP server', html`<div class="form-grid">
66
+ ${input('host', 'Host', s.host, { required: true, placeholder: 'smtp.office365.com' })}
67
+ ${input('port', 'Port', s.port ?? '', { type: 'number', placeholder: '587', help: 'Empty: 587 (STARTTLS) or 465 (TLS).' })}
68
+ ${select('security', 'Security', s.security ?? 'starttls', [['starttls', 'STARTTLS (required)'], ['tls', 'TLS from the start (port 465)'], ['none', 'None (a local relay only)']])}
69
+ ${select('auth', 'Sign-in', s.auth ?? 'password', [['password', 'User name and password'], ['oauth2', 'OAuth2 (XOAUTH2, client credentials)'], ['none', 'None']],
70
+ 'Microsoft 365 no longer takes passwords for SMTP: choose OAuth2 with an Entra application (SMTP.SendAsApp), or the Microsoft 365 (Graph) provider.')}
71
+ ${input('username', 'User name', s.username, { placeholder: 'the mailbox, e.g. noreply@example.com' })}
72
+ </div>${check('tls_verify', 'Check the server\'s certificate', s.tls_verify !== false, 'Switch off only for a relay with a self-signed certificate on your own network.')}`)}
73
+ <details class="prop-group prop-group-more"${s.auth === 'oauth2' ? raw(' open') : ''}><summary>OAuth2 sign-in <span class="muted">(only with Sign-in: OAuth2)</span></summary>${oauth('https://outlook.office365.com/.default')}</details>`
74
+ : provider === 'graph'
75
+ ? group('Microsoft Entra application', html`${oauth('https://graph.microsoft.com/.default')}
76
+ ${check('save_to_sent_items', 'Keep a copy in the mailbox\'s Sent Items', s.save_to_sent_items === true)}`,
77
+ 'An application in Microsoft Entra with a client secret and the application permission Mail.Send, limited to the sending mailboxes.')
78
+ : provider === 'ses'
79
+ ? group('Amazon SES', html`<div class="form-grid">
80
+ ${input('region', 'AWS region', s.region, { required: true, placeholder: 'eu-west-1' })}
81
+ ${input('access_key_id', 'Access key ID', s.access_key_id, { required: true })}</div>`,
82
+ 'An IAM user allowed ses:SendEmail; the From addresses must be verified identities in SES.')
83
+ : provider === 'mailgun'
84
+ ? group('Mailgun', html`<div class="form-grid">
85
+ ${input('domain', 'Sending domain', s.domain, { required: true, placeholder: 'mg.example.com' })}
86
+ ${select('mailgun_region', 'Region', s.mailgun_region ?? 'us', [['us', 'US'], ['eu', 'EU']])}</div>`)
87
+ : provider === 'postmark'
88
+ ? group('Postmark', html`<div class="form-grid">${input('message_stream', 'Message stream', s.message_stream, { placeholder: 'outbound' })}</div>`)
89
+ : '';
90
+ const secret = provider === 'log' ? '' : group(SECRET_LABEL[provider], html`
91
+ ${input('secret', SECRET_LABEL[provider], '', { type: 'password', auto: 'new-password',
92
+ help: x.has_secret && x.provider === provider ? 'A secret is stored (encrypted). It is never shown; type a new one to replace it.' : 'Stored encrypted; never shown again.' })}
93
+ ${x.has_secret ? check('remove_secret', 'Remove the stored secret', false) : ''}
94
+ ${secretKeyConfigured() ? '' : html`<div class="alert alert-error" role="alert">The server has no <code>PGKILN_SECRET_KEY</code>: secrets can't be stored until it is set.</div>`}`);
95
+ const viaHttp = provider !== 'smtp' && provider !== 'log';
96
+ return html`<form method="post" action="${action}" class="mail-service-form">${csrfField}
97
+ <input type="hidden" name="provider" value="${provider}">
98
+ ${group('Service', html`<div class="form-grid">
99
+ ${isNew ? input('name', 'Name', '', { required: true, placeholder: 'e.g. OFFICE365', help: 'Upper case letters, digits and _.' }) : ''}
100
+ ${input('description', 'Description', x.description)}
101
+ </div>${check('enabled', 'Enabled', x.enabled !== false, 'A disabled service sends nothing: mail stays queued until it is enabled, or fails after its retries.')}`)}
102
+ ${group('Senders', html`<div class="form-grid">
103
+ ${input('senders', 'Allowed senders', (x.senders ?? []).join(', '), { required: true, placeholder: 'noreply@example.com, @example.com',
104
+ help: 'The From addresses this service may send as: an address, or @domain for every address of a domain (the provider must accept them too).' })}
105
+ ${input('default_from', 'Default From address', s.default_from, { placeholder: 'noreply@example.com', help: 'For applications that set none.' })}
106
+ </div>`)}
107
+ ${settings}
108
+ ${secret}
109
+ ${viaHttp ? html`<details class="prop-group prop-group-more"${s.base_url ? raw(' open') : ''}><summary>Advanced</summary><div class="form-grid">
110
+ ${input('base_url', 'API base URL', s.base_url, { placeholder: 'empty: the provider\'s own API', help: 'A gateway or proxy that speaks the provider\'s API. Administrators only.' })}</div></details>` : ''}
111
+ ${group('Check before saving', html`
112
+ ${x.id ? html`<input type="hidden" name="service_id" value="${x.id}">` : ''}
113
+ <div class="buttons mail-check-buttons"><button class="btn" formaction="${BASE}/mail/check" formnovalidate name="check" value="connection">${icon('play')} Test connection</button></div>
114
+ <div class="form-grid">
115
+ ${input('test_to', 'Send a test mail to', tried?.to ?? '', { type: 'email', placeholder: 'you@example.com' })}
116
+ ${input('test_from', 'From', tried?.from ?? s.default_from ?? (x.senders ?? []).find((a) => !a.startsWith('@')) ?? '', { type: 'email', help: 'One of the allowed senders.' })}
117
+ </div>
118
+ <div class="buttons mail-check-buttons"><button class="btn" formaction="${BASE}/mail/check" formnovalidate name="check" value="send">${icon('send')} Send test mail</button></div>
119
+ <div class="mail-check-result" role="status" aria-live="polite">${tried ? html`<div class="alert ${tried.ok ? 'alert-success' : 'alert-error'}">${tried.text}</div>` : ''}</div>`,
120
+ `Uses the settings above as they are filled in, without saving them.${x.has_secret ? ' An empty secret field uses the stored secret.' : ''} Test connection signs in (SMTP) or makes a read-only call with the key; a test mail is really sent.`)}
121
+ <div class="buttons">${isNew ? html`<a class="btn" href="${BASE}/mail/new">Choose another provider</a>` : ''}<button class="btn btn-hot">${isNew ? 'Add service' : 'Save'}</button></div>
122
+ </form>`;
123
+ }
124
+
125
+ /** The form's values for the chosen provider, as typed (not checked). */
126
+ function parseForm(b: Record<string, string | undefined>) {
127
+ const provider = (PROVIDERS as readonly string[]).includes(b.provider ?? '') ? (b.provider as Provider) : 'smtp';
128
+ const t = (k: string) => (b[k] ?? '').trim() || undefined;
129
+ const senders = [...new Set((b.senders ?? '').split(/[\s,;]+/).map((x) => x.trim().toLowerCase()).filter(Boolean))];
130
+ const defaultFrom = t('default_from');
131
+ const port = t('port') ? Number(t('port')) : undefined;
132
+ const s: ServiceSettings = { default_from: defaultFrom, base_url: t('base_url') };
133
+ if (provider === 'smtp')
134
+ Object.assign(s, {
135
+ host: t('host'), port, security: ['tls', 'none'].includes(b.security ?? '') ? b.security : 'starttls',
136
+ auth: ['oauth2', 'none'].includes(b.auth ?? '') ? b.auth : 'password', username: t('username'), tls_verify: b.tls_verify === 'true',
137
+ ...(b.auth === 'oauth2' ? { tenant_id: t('tenant_id'), client_id: t('client_id'), token_url: t('token_url'), scope: t('scope') } : {}),
138
+ });
139
+ if (provider === 'graph') Object.assign(s, { tenant_id: t('tenant_id'), client_id: t('client_id'), token_url: t('token_url'), scope: t('scope'), save_to_sent_items: b.save_to_sent_items === 'true' });
140
+ if (provider === 'ses') Object.assign(s, { region: t('region'), access_key_id: t('access_key_id') });
141
+ if (provider === 'mailgun') Object.assign(s, { domain: t('domain'), mailgun_region: b.mailgun_region === 'eu' ? 'eu' : 'us' });
142
+ if (provider === 'postmark') Object.assign(s, { message_stream: t('message_stream') });
143
+ for (const k of Object.keys(s) as (keyof ServiceSettings)[]) if (s[k] === undefined) delete s[k];
144
+ return { provider, settings: s, senders, description: t('description') ?? null, enabled: b.enabled === 'true' };
145
+ }
146
+
147
+ /**
148
+ * The form's values, checked; throws with a message. A check of the connection
149
+ * (opts.connection) needs the provider's settings only, not yet the senders.
150
+ */
151
+ function formValues(b: Record<string, string | undefined>, hasSecret: boolean, opts: { connection?: boolean } = {}) {
152
+ const v = parseForm(b);
153
+ if (!opts.connection || v.senders.length) {
154
+ if (!v.senders.length) throw new Error('Name at least one allowed sender (an address, or @domain).');
155
+ const bad = v.senders.find((x) => !SENDER.test(x));
156
+ if (bad) throw new Error(`"${bad}" is not an address or @domain.`);
157
+ const from = v.settings.default_from;
158
+ if (from && (!ADDRESS.test(from) || !senderAllowed(v.senders, from))) throw new Error('The default From address must be an address the service may send as.');
159
+ }
160
+ const problems = settingsProblems(v.provider, v.settings, hasSecret || !!b.secret);
161
+ if (problems.length) throw new Error(problems.join(' '));
162
+ return v;
163
+ }
164
+
165
+ const STATUS_CLASS: Record<string, string> = { sent: ' tag-ok', queued: '', sending: '', error: ' tag-error', cancelled: '' };
166
+
167
+ const mailTable = (rows: any[], withApp: boolean, actions?: (m: any) => unknown) => html`<div class="table-wrap"><table class="report report-reflow">
168
+ <thead><tr><th>Queued (UTC)</th>${withApp ? html`<th>Application</th>` : ''}<th>To</th><th>Subject</th><th>From</th><th class="num">Attempts</th><th>Status</th>${actions ? html`<th>Actions</th>` : ''}</tr></thead>
169
+ <tbody>${rows.length ? rows.map((m) => html`<tr>
170
+ <td data-label="Queued">${when(m.created_at)}</td>${withApp ? html`<td data-label="Application">${m.app ?? ''}</td>` : ''}
171
+ <td data-label="To" class="u-break">${[...m.to_addresses, ...m.cc_addresses].join(', ')}${m.bcc_addresses.length ? html` <span class="muted">+${m.bcc_addresses.length} bcc</span>` : ''}</td>
172
+ <td data-label="Subject" class="u-break">${m.subject}${m.template ? html` <span class="muted">(${m.template})</span>` : ''}</td>
173
+ <td data-label="From" class="u-break">${m.from_address ?? ''}</td>
174
+ <td class="num" data-label="Attempts">${m.attempts}</td>
175
+ <td data-label="Status"><span class="tag${STATUS_CLASS[m.status] ?? ''}">${m.status}</span>${m.sent_at ? html` <span class="muted">${when(m.sent_at)}</span>` : ''}${m.message ? html`<br><span class="muted u-break">${m.message}</span>` : ''}</td>
176
+ ${actions ? html`<td data-label="Actions">${actions(m)}</td>` : ''}</tr>`)
177
+ : html`<tr><td colspan="${7 + (withApp ? 1 : 0) + (actions ? 1 : 0)}" class="empty">No mail yet.</td></tr>`}</tbody></table></div>`;
178
+
179
+ async function adminOnly(s: Session, reply: any, title: string) {
180
+ if (await isAdmin(s.username)) return true;
181
+ const main = html`<h1 class="u-mb1">${title}</h1><div class="alert alert-error" role="alert">Only administrators configure mail services.</div>`;
182
+ await send(reply.code(403), s, shell(s, title, [['App Builder', BASE], ['Workspace utilities', `${BASE}/utilities`], [title]], main));
183
+ return false;
184
+ }
185
+
186
+ const MAIL_COLUMNS = 'q.id, q.app_id, q.to_addresses, q.cc_addresses, q.bcc_addresses, q.subject, q.template, q.from_address, q.attempts, q.status, q.message, q.created_at, q.sent_at';
187
+
188
+ export async function mailRoutes(app: FastifyInstance) {
189
+ app.get(`${BASE}/mail`, async (req: Req, reply) => {
190
+ const s = await developer(req, reply);
191
+ if (!s || !(await adminOnly(s, reply, 'Mail services'))) return;
192
+ const services = (await owner.query(`select s.id, s.name, s.description, s.provider, s.senders, s.enabled, s.secret_enc is not null as has_secret,
193
+ (select string_agg(a.alias, ', ' order by a.alias) from meta.app_mail_service x join meta.app a on a.id = x.app_id where x.service_id = s.id) as apps
194
+ from meta.mail_service s order by s.name`)).rows;
195
+ const recent = (await owner.query(`select ${MAIL_COLUMNS}, a.alias as app from meta.mail_queue q left join meta.app a on a.id = q.app_id order by q.id desc limit 100`)).rows;
196
+ const main = html`
197
+ <div class="title-row"><h1>Mail services</h1></div>
198
+ <p class="muted u-mt0">How the applications of this installation send e-mail (<code>meta.send_mail()</code> from SQL, the <b>Send e-mail</b> process, e-mail templates). Mail is queued in the application's transaction and sent by the server after it commits. Choose the service of each application on the service's page.</p>
199
+ ${region('Services', html`<div class="table-wrap"><table class="report report-reflow">
200
+ <thead><tr><th>Service</th><th>Provider</th><th>Senders</th><th>Secret</th><th>Applications</th><th>Status</th></tr></thead>
201
+ <tbody>${services.length ? services.map((x) => html`<tr>
202
+ <td data-label="Service"><a href="${BASE}/mail/${x.id}">${x.name}</a>${x.description ? html` <span class="muted">${x.description}</span>` : ''}</td>
203
+ <td data-label="Provider">${PROVIDER_LABELS[x.provider as Provider]}</td>
204
+ <td data-label="Senders" class="u-break">${x.senders.join(', ')}</td>
205
+ <td data-label="Secret">${x.has_secret ? 'stored (encrypted)' : x.provider === 'log' ? '–' : html`<b>missing</b>`}</td>
206
+ <td data-label="Applications">${x.apps ?? html`<span class="muted">none</span>`}</td>
207
+ <td data-label="Status">${x.enabled ? 'enabled' : html`<b>disabled</b>`}</td></tr>`)
208
+ : html`<tr><td colspan="6" class="empty">No mail services yet.</td></tr>`}</tbody></table></div>`,
209
+ html`<a class="btn btn-sm btn-hot" href="${BASE}/mail/new">${icon('plus')} Add service</a>`)}
210
+ ${region('Recent mail', mailTable(recent, true))}`;
211
+ return send(reply, s, shell(s, 'Mail services', [['App Builder', BASE], ['Workspace utilities', `${BASE}/utilities`], ['Mail services']], main));
212
+ });
213
+
214
+ // a new service: choose the provider, then its settings only
215
+ app.get(`${BASE}/mail/new`, async (req: Req, reply) => {
216
+ const s = await developer(req, reply);
217
+ if (!s || !(await adminOnly(s, reply, 'Mail services'))) return;
218
+ const provider = (PROVIDERS as readonly string[]).includes(String(req.query.provider)) ? (req.query.provider as Provider) : null;
219
+ const main = html`<div class="title-row"><h1>Add a mail service</h1></div>
220
+ ${provider
221
+ ? html`<p class="muted u-mt0">Step 2 of 2: <b>${PROVIDER_LABELS[provider]}</b>. ${PROVIDER_TEXT[provider][1]}</p>
222
+ <div class="mail-form-page">${region('Settings', serviceForm({}, provider, `${BASE}/mail`, csrf(s), true))}</div>`
223
+ : html`<p class="muted u-mt0">Step 1 of 2: how should the applications send mail?</p>${providerChoice()}`}`;
224
+ return send(reply, s, shell(s, 'Add a mail service', [['App Builder', BASE], ['Workspace utilities', `${BASE}/utilities`], ['Mail services', `${BASE}/mail`], ['Add']], main));
225
+ });
226
+
227
+ app.post(`${BASE}/mail`, async (req: Req, reply) => {
228
+ const s = await developer(req, reply);
229
+ if (!s || !(await adminOnly(s, reply, 'Mail services'))) return;
230
+ const b = req.body ?? {};
231
+ try {
232
+ const name = (b.name ?? '').trim().toUpperCase();
233
+ if (!/^[A-Z][A-Z0-9_]{0,59}$/.test(name)) throw new Error('The name is upper case letters, digits and _ (e.g. OFFICE365).');
234
+ const v = formValues(b, false);
235
+ const secret = b.secret ? encryptSecret(b.secret) : null;
236
+ const r = await owner.one(
237
+ `insert into meta.mail_service (name, description, provider, settings, senders, enabled, secret_enc) values ($1, $2, $3, $4, $5, $6, $7) returning id`,
238
+ [name, v.description, v.provider, JSON.stringify(v.settings), v.senders, v.enabled, secret]);
239
+ flash(s, 'Mail service added. Choose the applications that send through it below, and test it.');
240
+ return back(reply, s, `${BASE}/mail/${r.id}`);
241
+ } catch (e) {
242
+ flash(s, (e as Error).message.includes('mail_service_name_key') ? 'A service with this name exists already.' : (e as Error).message, 'error');
243
+ return back(reply, s, `${BASE}/mail/new?provider=${encodeURIComponent(String(b.provider ?? ''))}`);
244
+ }
245
+ });
246
+
247
+ app.get(`${BASE}/mail/:id(^\\d+$)`, async (req: Req, reply) => {
248
+ const s = await developer(req, reply);
249
+ if (!s || !(await adminOnly(s, reply, 'Mail services'))) return;
250
+ const x = await owner.one<MailService & { has_secret: boolean }>(
251
+ 'select id, name, description, provider, settings, senders, enabled, secret_enc is not null as has_secret from meta.mail_service where id = $1', [req.params.id]);
252
+ if (!x) return reply.code(404).send('Not found');
253
+ const provider = (PROVIDERS as readonly string[]).includes(String(req.query.provider)) ? (req.query.provider as Provider) : x.provider;
254
+ const apps = (await owner.query(`select a.id, a.alias, a.name, x.service_id, x.from_address, x.max_per_day, o.name as other
255
+ from meta.app a left join meta.app_mail_service x on x.app_id = a.id left join meta.mail_service o on o.id = x.service_id and o.id <> $1
256
+ order by a.alias`, [x.id])).rows;
257
+ const recent = (await owner.query(`select ${MAIL_COLUMNS}, a.alias as app from meta.mail_queue q left join meta.app a on a.id = q.app_id
258
+ where q.service = $1 or q.app_id in (select app_id from meta.app_mail_service where service_id = $2) order by q.id desc limit 50`, [x.name, x.id])).rows;
259
+ const main = html`
260
+ <div class="title-row"><h1 class="mail-name">${x.name}</h1></div>
261
+ <div class="mail-form-page">
262
+ ${region('Settings', html`
263
+ <form method="get" class="provider-switch">${select('provider', 'Provider', provider, PROVIDERS.map((p): [string, string] => [p, PROVIDER_LABELS[p]]),
264
+ provider !== x.provider ? 'Not saved yet: fill in the settings below and save to switch.' : undefined)}<button class="btn btn-sm">Change</button></form>
265
+ ${serviceForm(x, provider, `${BASE}/mail/${x.id}`, csrf(s), false)}
266
+ <form method="post" action="${BASE}/mail/${x.id}/delete" class="danger-zone">${csrf(s)}
267
+ <button class="btn btn-danger" data-confirm="Delete mail service ${x.name}? Its applications can't send mail until they get another one.">Delete service</button></form>`)}
268
+ </div>
269
+ ${region('Applications', html`<p class="muted u-mt0">The applications that send through this service (each application has one), their From address (empty: the service's default) and a limit per day (UTC; empty: none). An application with another service shows it.</p>
270
+ <form method="post" action="${BASE}/mail/${x.id}/apps">${csrf(s)}
271
+ <div class="table-wrap"><table class="report report-reflow"><thead><tr><th>Application</th><th>Sends through this service</th><th>From address</th><th>Mails per day</th></tr></thead>
272
+ <tbody>${apps.length ? apps.map((a) => html`<tr>
273
+ <td data-label="Application">${a.name} <span class="muted">${a.alias}</span></td>
274
+ <td data-label="Sends through this service"><label class="check"><input type="checkbox" name="allow" value="${a.id}"${a.service_id === x.id ? raw(' checked') : ''}> yes</label>${a.other ? html` <span class="muted">now: ${a.other}</span>` : ''}</td>
275
+ <td data-label="From address"><input type="email" name="from_${a.id}" value="${a.service_id === x.id ? a.from_address ?? '' : ''}" aria-label="From address for ${a.alias}"></td>
276
+ <td data-label="Mails per day"><input type="number" min="0" name="max_${a.id}" value="${a.service_id === x.id ? a.max_per_day ?? '' : ''}" aria-label="Mails per day for ${a.alias}"></td></tr>`)
277
+ : html`<tr><td colspan="4" class="empty">No applications.</td></tr>`}</tbody></table></div>
278
+ <div class="buttons"><button class="btn btn-hot">Save</button></div></form>`)}
279
+ ${region('Recent mail', mailTable(recent, true))}`;
280
+ return send(reply, s, shell(s, x.name, [['App Builder', BASE], ['Workspace utilities', `${BASE}/utilities`], ['Mail services', `${BASE}/mail`], [x.name]], main));
281
+ });
282
+
283
+ app.post(`${BASE}/mail/:id(^\\d+$)`, async (req: Req, reply) => {
284
+ const s = await developer(req, reply);
285
+ if (!s || !(await adminOnly(s, reply, 'Mail services'))) return;
286
+ const b = req.body ?? {};
287
+ try {
288
+ const old = await owner.one<{ has_secret: boolean }>('select secret_enc is not null as has_secret from meta.mail_service where id = $1', [req.params.id]);
289
+ if (!old) throw new Error('Not found.');
290
+ const v = formValues(b, old.has_secret && b.remove_secret !== 'true');
291
+ const secret = b.secret ? encryptSecret(b.secret) : null;
292
+ await owner.query(
293
+ `update meta.mail_service set description = $2, provider = $3, settings = $4, senders = $5, enabled = $6, updated_at = now(),
294
+ secret_enc = case when $8 then null when $7::text is null then secret_enc else $7 end
295
+ where id = $1`,
296
+ [req.params.id, v.description, v.provider, JSON.stringify(v.settings), v.senders, v.enabled, secret, b.remove_secret === 'true' && !b.secret]);
297
+ flash(s, 'Mail service saved.');
298
+ } catch (e) {
299
+ flash(s, (e as Error).message, 'error');
300
+ }
301
+ return back(reply, s, `${BASE}/mail/${req.params.id}`);
302
+ });
303
+
304
+ app.post(`${BASE}/mail/:id(^\\d+$)/apps`, async (req: Req, reply) => {
305
+ const s = await developer(req, reply);
306
+ if (!s || !(await adminOnly(s, reply, 'Mail services'))) return;
307
+ const b = req.body as Record<string, string | string[] | undefined>;
308
+ const allow = new Set([b.allow ?? []].flat().map(Number).filter(Number.isInteger));
309
+ try {
310
+ const service = await owner.one<{ senders: string[] }>('select senders from meta.mail_service where id = $1', [req.params.id]);
311
+ if (!service) throw new Error('Not found.');
312
+ await owner.tx(async (c) => {
313
+ const apps = (await c.query<{ id: number }>('select id from meta.app')).rows.map((a) => a.id);
314
+ await c.query('delete from meta.app_mail_service where service_id = $1 and not (app_id = any($2::int[]))', [req.params.id, [...allow]]);
315
+ for (const id of apps.filter((a) => allow.has(a))) {
316
+ const from = String(b[`from_${id}`] ?? '').trim() || null;
317
+ if (from && (!ADDRESS.test(from) || !senderAllowed(service.senders, from))) throw new Error(`${from} is not an address this service may send as.`);
318
+ const max = String(b[`max_${id}`] ?? '').trim();
319
+ if (max && !(Number.isInteger(Number(max)) && Number(max) >= 0)) throw new Error('Mails per day: a whole number of 0 or more (empty: no limit).');
320
+ await c.query(
321
+ `insert into meta.app_mail_service (app_id, service_id, from_address, max_per_day) values ($1, $2, $3, $4)
322
+ on conflict (app_id) do update set service_id = excluded.service_id, from_address = excluded.from_address, max_per_day = excluded.max_per_day`,
323
+ [id, req.params.id, from, max ? Number(max) : null]);
324
+ }
325
+ });
326
+ flash(s, 'Applications saved.');
327
+ } catch (e) {
328
+ flash(s, (e as Error).message, 'error');
329
+ }
330
+ return back(reply, s, `${BASE}/mail/${req.params.id}`);
331
+ });
332
+
333
+ // Test connection / Send test mail: the settings as filled in, not saved (the stored secret when none is typed).
334
+ // JSON for builder.js; without JavaScript the form comes back with its values (the secret must be typed again).
335
+ app.post(`${BASE}/mail/check`, async (req: Req, reply) => {
336
+ const s = await developer(req, reply);
337
+ if (!s || !(await adminOnly(s, reply, 'Mail services'))) return;
338
+ const b = (req.body ?? {}) as Record<string, string | undefined>;
339
+ const id = /^\d{1,9}$/.test(b.service_id ?? '') ? Number(b.service_id) : null;
340
+ const stored = id ? await owner.one<MailService>('select * from meta.mail_service where id = $1', [id]) : null;
341
+ if (id && !stored) return reply.code(404).send('Not found');
342
+ const typed = parseForm(b);
343
+ const to = String(b.test_to ?? '').trim();
344
+ const from = String(b.test_from ?? '').trim();
345
+ let result: { ok: boolean; text: string };
346
+ try {
347
+ const sameProvider = stored?.provider === typed.provider;
348
+ const v = formValues(b, !!(sameProvider && stored?.secret_enc), { connection: b.check !== 'send' });
349
+ let secret: string | null = b.secret || null;
350
+ if (!secret && sameProvider && stored?.secret_enc) {
351
+ try {
352
+ secret = decryptSecret(stored.secret_enc);
353
+ } catch (e) {
354
+ throw new MailError(`The stored secret can't be read: ${(e as Error).message}`, false);
355
+ }
356
+ }
357
+ if (b.check === 'send') {
358
+ if (!ADDRESS.test(to)) throw new MailError('Give the address to send the test mail to.', false);
359
+ if (!ADDRESS.test(from) || !senderAllowed(v.senders, from)) throw new MailError('The From address must be one of the allowed senders.', false);
360
+ const pid = await deliver(v.provider, v.settings, secret, {
361
+ from, to: [to], cc: [], bcc: [], replyTo: null, subject: `pgkiln: test of a mail service (${PROVIDER_LABELS[v.provider]})`,
362
+ text: `This is a test of a pgkiln mail service${stored ? ` (${stored.name})` : ''}, sent from the App Builder by ${s.username}.`, html: null, attachments: [],
363
+ });
364
+ result = { ok: true, text: `The test mail was handed to ${PROVIDER_LABELS[v.provider]}${pid ? ` (its id: ${pid})` : ''}. Check the mailbox of ${to}.` };
365
+ } else result = { ok: true, text: await verifyConnection(v.provider, v.settings, secret) };
366
+ } catch (e) {
367
+ result = { ok: false, text: e instanceof MailError || !(e instanceof TypeError) ? (e as Error).message : 'The check failed.' };
368
+ }
369
+ await logActivity({ username: s.username, event: 'mail_check', ip: clientIp(req), detail: `${b.check === 'send' ? 'send' : 'connection'} ${typed.provider}${stored ? ` ${stored.name}` : ''}: ${result.ok ? 'ok' : 'failed'}` });
370
+ if (String(req.headers.accept ?? '').includes('application/json')) return reply.header('cache-control', 'no-store').send(result);
371
+ const x = { id: stored?.id, name: stored?.name, description: typed.description, provider: typed.provider, settings: typed.settings, senders: typed.senders, enabled: typed.enabled,
372
+ has_secret: !!(stored?.secret_enc && stored.provider === typed.provider) };
373
+ const main = html`<div class="title-row"><h1>${stored ? stored.name : 'Add a mail service'}</h1></div>
374
+ <div class="mail-form-page">${region('Settings', serviceForm(x, typed.provider, stored ? `${BASE}/mail/${stored.id}` : `${BASE}/mail`, csrf(s), !stored, { ...result, to, from }))}</div>`;
375
+ return send(reply, s, shell(s, 'Mail service', [['App Builder', BASE], ['Workspace utilities', `${BASE}/utilities`], ['Mail services', `${BASE}/mail`], [stored?.name ?? 'Add']], main));
376
+ });
377
+
378
+ app.post(`${BASE}/mail/:id(^\\d+$)/delete`, async (req: Req, reply) => {
379
+ const s = await developer(req, reply);
380
+ if (!s || !(await adminOnly(s, reply, 'Mail services'))) return;
381
+ await owner.query('delete from meta.mail_service where id = $1', [req.params.id]);
382
+ flash(s, 'Mail service deleted.');
383
+ return back(reply, s, `${BASE}/mail`);
384
+ });
385
+
386
+ // ---------------------------------------------------------------- per application (developers)
387
+ app.get(`${BASE}/apps/:id(^\\d+$)/mail`, async (req: Req, reply) => {
388
+ const s = await developer(req, reply);
389
+ if (!s) return;
390
+ const a = await owner.one<{ id: number; alias: string; name: string }>('select id, alias, name from meta.app where id = $1', [req.params.id]);
391
+ if (!a) return reply.code(404).send('Not found');
392
+ const service = await owner.one(`select s.name, s.provider, s.enabled, x.from_address, x.max_per_day, s.settings->>'default_from' as default_from
393
+ from meta.app_mail_service x join meta.mail_service s on s.id = x.service_id where x.app_id = $1`, [a.id]);
394
+ const today = (await owner.one(`select count(*)::int as n from meta.mail_queue where app_id = $1 and created_at >= date_trunc('day', now() at time zone 'UTC') at time zone 'UTC' and status <> 'cancelled'`, [a.id])).n;
395
+ const status = String(req.query.status ?? '');
396
+ const rows = (await owner.query(`select ${MAIL_COLUMNS} from meta.mail_queue q where q.app_id = $1 and ($2 = '' or q.status = $2) order by q.id desc limit 200`, [a.id, status])).rows;
397
+ const admin = await isAdmin(s.username);
398
+ const action = (m: any) => m.status === 'error' || m.status === 'cancelled'
399
+ ? html`<form method="post" action="${BASE}/apps/${a.id}/mail/${m.id}/retry">${csrf(s)}<button class="btn btn-sm">Send again</button></form>`
400
+ : m.status === 'queued' ? html`<form method="post" action="${BASE}/apps/${a.id}/mail/${m.id}/cancel">${csrf(s)}<button class="btn btn-sm">Cancel</button></form>` : '';
401
+ const main = html`
402
+ <div class="title-row"><h1 class="mail-name">Mail · ${a.name}</h1></div>
403
+ <p class="muted u-mt0">The mail this application queued (<code>meta.send_mail()</code>, the Send e-mail process), kept 30 days. ${service
404
+ ? html`It sends through <b>${service.name}</b> (${PROVIDER_LABELS[service.provider as Provider]}${service.enabled ? '' : ', disabled'}) as ${service.from_address ?? service.default_from ?? html`<i>no From address</i>`}; today: ${today}${service.max_per_day !== null ? ` of ${service.max_per_day}` : ''}.`
405
+ : html`<b>It may not send mail yet</b>: an administrator chooses its mail service${admin ? html` under <a href="${BASE}/mail">Mail services</a>` : ''}.`}</p>
406
+ <form method="get" class="u-mb1">${select('status', 'Status', status, [['', 'All'], ['queued', 'Queued'], ['sending', 'Sending'], ['sent', 'Sent'], ['error', 'Error'], ['cancelled', 'Cancelled']])}<button class="btn btn-sm">Show</button></form>
407
+ ${region('Mail', mailTable(rows, false, action))}`;
408
+ return send(reply, s, shell(s, `Mail · ${a.name}`, [['App Builder', BASE], [a.name, `${BASE}/apps/${a.id}`], ['Activity', `${BASE}/apps/${a.id}/activity`], ['Mail']], main));
409
+ });
410
+
411
+ const change = (to: 'queued' | 'cancelled', from: string[]) => async (req: Req, reply: any) => {
412
+ const s = await developer(req, reply);
413
+ if (!s) return;
414
+ const r = await owner.query(
415
+ `update meta.mail_queue set status = $3, attempts = case when $3 = 'queued' then 0 else attempts end, not_before = now(),
416
+ message = case when $3 = 'cancelled' then 'Cancelled by ' || $4 else message end
417
+ where id = $1 and app_id = $2 and status = any($5::text[])`,
418
+ [req.params.mid, req.params.id, to, s.username, from]);
419
+ if (r.rowCount && to === 'queued') await owner.query(`select pg_notify('pgkiln_mail', $1)`, [String(req.params.mid)]);
420
+ flash(s, r.rowCount ? (to === 'queued' ? 'The mail is queued again.' : 'The mail is cancelled.') : 'The mail has changed meanwhile.', r.rowCount ? 'ok' : 'error');
421
+ return back(reply, s, `${BASE}/apps/${req.params.id}/mail`);
422
+ };
423
+ app.post(`${BASE}/apps/:id(^\\d+$)/mail/:mid(^\\d+$)/retry`, change('queued', ['error', 'cancelled']));
424
+ app.post(`${BASE}/apps/:id(^\\d+$)/mail/:mid(^\\d+$)/cancel`, change('cancelled', ['queued']));
425
+ }
@@ -106,7 +106,7 @@ export async function startFromBoilerplate(c: Client, appId: number, a: CheckedA
106
106
  const bp = (await c.query<{ alias: string }>(`select alias from meta.app where id = $1 and app_type = 'boilerplate'`, [boilerplateId])).rows[0];
107
107
  if (!bp) throw new Error('Choose a boilerplate application (an application of type Boilerplate).');
108
108
  const doc = (await c.query('select meta.export_app($1) as d', [bp.alias])).rows[0].d;
109
- await replaceApp(c, doc, a.alias);
109
+ await replaceApp(c, doc, a.alias, { backup: null });
110
110
  await c.query(`update meta.app set name = $2, db_role = $3, authentication = $4, app_type = 'standard', api_role = null, updated_at = now() where id = $1`, [
111
111
  appId, a.name, a.role, a.authentication,
112
112
  ]);
@@ -0,0 +1,71 @@
1
+ // The help of a region's Attributes (JSON) in the Page Designer, per region type (sprint 51):
2
+ // an existing region sees only the keys of its own type and a link to its section of the guide;
3
+ // a new region (type not chosen yet) sees all of them. Each entry: the types it applies to
4
+ // ("*": every type) and the text.
5
+
6
+ /** The user guide on the website (chapter 4 and, for tasks and workflows, chapter 6). */
7
+ const GUIDE = 'https://pgkiln.vargar.eu/docs';
8
+
9
+ export const REGION_CONFIG_HELP: [string[], string][] = [
10
+ [['report'], '{"page_size":15,"pagination":"range" (rows X–Y without a total),"keyset":["id"] (with range: Next/Previous seek on these unique columns),"max_rows":10000,"searchable":true,"sortable":true,"interactive":true,"mobile":"reflow"|"scroll","hidden":["col"],"headings":{"col":"Label"},"link":{"column":"id","page":3,"items":{"P3_ID":"#id#"}},"empty":"No rows","pdf":{"layout":"NAME","columns":["col"],"widths":{"col":40},"align":{"col":"right"}}} (pdf widths in mm; layouts under Shared Components → Report layouts)'],
11
+ [['report', 'grid', 'cards'], '{"formats":{"sal":"FML999G990D00","hiredate":"DD-MON-YYYY"}} (number or date format masks per column)'],
12
+ [['chart'], '{"kind":"bar"|"column"|"line"|"area"|"donut","max_rows":1000,"format_mask":"FML999G990"}'],
13
+ [['cards'], '{"style":"metric","link":{...},"max_rows":500}'],
14
+ [['dynamic'], '{"max_rows":1000}'],
15
+ [['grid'], '{"page_size":25,"allow":{"insert":true,"update":true,"delete":true},"readonly":["col"],"columns":{"deptno":{"lov":"LOV:DEPARTMENTS","required":true}},"aggregates":{"sal":["sum","avg"]},"layout":{"order":["col"],"hidden":["col"],"widths":{"col":160},"frozen":1},"row_actions":{"edit":{"page":3,"items":{"P3_ID":"#id#"}},"duplicate":true,"delete":true,"links":[{"label":"…","page":4,"items":{}}]},"select_row":{"column":"id","item":"P1_ID"} (a master),"master":{"item":"P1_ID","column":"parent_id"} (a detail; any region type),"actions":true,"saved_reports":true,"public_reports":"SCHEME"}'],
16
+ [['calendar'], '{"link":{...}}'],
17
+ [['facets'], '{"report":<region id>,"search":true,"facets":[{"column":"job","label":"Job","exclude":true},{"column":"sal","type":"range","ranges":[{"to":1000},{"from":1000}],"custom":true},{"column":"rating","type":"star","max":5}]}'],
18
+ [['smart_filters'], '{"report":<region id>,"suggestions":3,"placeholder":"…","facets":[…as facets]}'],
19
+ [['display_selector'], '{"style":"tabs"|"select","show_all":true,"remember":true}'],
20
+ [['list'], '{"list":"NAME","template":"links"|"badges"|"cards"|"tabs"} (lists under Shared Components → Lists)'],
21
+ [['*'], '{"display_selector":true} puts it in the page\'s display selector'],
22
+ [['report', 'chart', 'cards', 'dynamic', 'tree', 'template_component'], '{"lazy":true} loads it after the page shows, {"cache":{"scope":"user"|"session"|"all","seconds":300}} keeps its HTML (a submit of the page empties it)'],
23
+ [['data_reporter'], '{"sources":[{"id":"orders","label":"Orders","description":"…","schema":"sales","table":"order_v","columns":[{"name":"total","label":"Total","format":"FML999G990D00"}]}],"sharing":true,"share_authz":"SCHEME","page_size":25} (the Data Reporter settings below edit it)'],
24
+ [['ai_assistant'], '{"service":"NAME","system":"…","welcome":"…","context":[{"name":"policy","sql":"select … :AI_PROMPT …"}],"tools":[{"name":"my_leave","description":"…","sql":"select … where status = :STATUS","parameters":{"STATUS":{"type":"string","enum":["PENDING"]}}},{"name":"dept","type":"rest","source":"DEPARTMENT","description":"…"}],"max_rounds":5,"max_turns":20} (the AI assistant settings below edit it)'],
25
+ [['report'], '{"ai_filter":{"service":"NAME"}} adds an "Ask in your own words" box (natural-language filters)'],
26
+ [['plugin'], '{"plugin":"name","attributes":{"NAME":"value"}} (a region plug-in; a Source SELECT feeds its template)'],
27
+ [['form'], '{"lost_update":false} saves without checking that the row is unchanged since it was shown'],
28
+ [['url'], '{"height":480,"sandbox":["allow-scripts","allow-forms","allow-popups","allow-same-origin"] (the default; false: no sandbox),"fullscreen":true}'],
29
+ [['search'], '{"configs":["CUSTOMERS","ORDERS"] (Shared Components → Search configurations; empty: all),"item":"P1_SEARCH" (search with this item\'s value instead of a field of its own),"placeholder":"…","min_length":2,"empty":"No results"}'],
30
+ ];
31
+
32
+ /** Where each region type is described in the guide. */
33
+ const ANCHORS: Record<string, string> = {
34
+ report: 'report-interactive-report',
35
+ grid: 'grid-interactive-grid',
36
+ form: 'form',
37
+ chart: 'chart',
38
+ cards: 'cards',
39
+ calendar: 'calendar',
40
+ facets: 'facets-faceted-search',
41
+ smart_filters: 'smart-filters',
42
+ display_selector: 'display-selector-region-display-selector',
43
+ map: 'map',
44
+ tree: 'tree',
45
+ list: 'list-lists',
46
+ data_reporter: 'data-reporter-data-reporter',
47
+ ai_assistant: 'ai-assistant-ai-assistant',
48
+ template_component: 'template-components',
49
+ static: 'static-and-dynamic-content',
50
+ dynamic: 'static-and-dynamic-content',
51
+ url: 'url-url-region',
52
+ search: 'search-search-region',
53
+ plugin: 'plug-ins-with-their-own-code',
54
+ tasks: 'approvals-and-the-task-list',
55
+ workflows: 'workflows',
56
+ };
57
+
58
+ /** The help of every type (a region whose type isn't known yet). */
59
+ export const ALL_REGION_CONFIG_HELP = REGION_CONFIG_HELP.map(([types, text]) => `${types.includes('*') ? 'any region' : types.join(', ')}: ${text}`).join(' · ');
60
+
61
+ /** The keys of one region type, and where the guide describes it. */
62
+ export function regionConfigHelp(type: string | null | undefined): { text: string; url: string | null } {
63
+ if (!type) return { text: ALL_REGION_CONFIG_HELP, url: null };
64
+ const own = REGION_CONFIG_HELP.filter(([types]) => types.includes(type)).map(([, text]) => text);
65
+ const any = REGION_CONFIG_HELP.filter(([types]) => types.includes('*')).map(([, text]) => `any region: ${text}`);
66
+ const chapter = type === 'tasks' || type === 'workflows' ? 'processing' : 'pages-and-regions';
67
+ return {
68
+ text: [...own, ...any].join(' · ') || 'No attributes of its own.',
69
+ url: ANCHORS[type] ? `${GUIDE}/${chapter}#${ANCHORS[type]}` : null,
70
+ };
71
+ }