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
@@ -16,7 +16,7 @@ import { itemMask, LOV_CHECKED, lovContains, MULTI_VALUE, ratingMax, splitValues
16
16
  import { formatNumber, isPlainNumber } from '../numformat.ts';
17
17
  import { conditionHolds } from './logic.ts';
18
18
  import { runPluginProcess } from './plugins.ts';
19
- import { BACKGROUND_TYPES, downloadFile, sendPushProcess, workflowProcess, type ChainConfig } from './processes.ts';
19
+ import { BACKGROUND_TYPES, downloadFile, sendEmailProcess, sendPushProcess, workflowProcess, type ChainConfig } from './processes.ts';
20
20
  import { bindValues, dbg, publicError, stripSemicolon, substitute, timed, toState, type Errors, type PageContext } from './context.ts';
21
21
 
22
22
  const ident = pg.escapeIdentifier;
@@ -35,6 +35,16 @@ export async function resolveTable(c: Client, name: string) {
35
35
 
36
36
  const formItems = (ctx: PageContext, r: Region) => ctx.page.items.filter((i) => i.region_id === r.id && i.source_column);
37
37
 
38
+ /**
39
+ * (076) Lost update detection: on unless the form's attributes say
40
+ * {"lost_update": false}. The checksum covers the form's columns except files.
41
+ */
42
+ const detectsLostUpdates = (r: Region) => (r.config as { lost_update?: unknown } | null)?.lost_update !== false;
43
+ const versionColumns = (ctx: PageContext, r: Region) =>
44
+ [...new Set(formItems(ctx, r).filter((i) => i.type !== 'file').map((i) => i.source_column!))].sort();
45
+ const rowVersion = async (c: Client, table: string, r: Region, columns: string[], pk: string, lock: boolean) =>
46
+ ((await c.query('select meta.row_version($1::regclass, $2, $3, $4, $5) as v', [table, r.pk_column, String(pk), columns, lock])).rows[0]?.v as string | null) ?? null;
47
+
38
48
  export function clearPageItems(ctx: PageContext) {
39
49
  for (const i of ctx.page.items) delete ctx.session.state[i.name];
40
50
  }
@@ -90,6 +100,10 @@ export async function fetchForms(ctx: PageContext) {
90
100
  continue;
91
101
  }
92
102
  items.forEach((item, idx) => (ctx.session.state[item.name] = toState(res.rows[0][idx])));
103
+ if (detectsLostUpdates(r)) {
104
+ const v = await savepoint(c, () => rowVersion(c, table, r, versionColumns(ctx, r), pk, false));
105
+ if (v) (ctx.rowVersions ??= new Map()).set(r.id, v);
106
+ }
93
107
  } catch (e) {
94
108
  ctx.errors.page.push(await publicError(ctx, e, `fetch of ${r.title ?? 'form'}`));
95
109
  }
@@ -305,6 +319,16 @@ async function formDml(ctx: PageContext, p: Process): Promise<string | null> {
305
319
  }
306
320
 
307
321
  if (pk === null) throw new Error(ctx.locale.t('form.no_record'));
322
+ // (076) the row is locked, and refused when someone changed it since the page was shown
323
+ const shown = ctx.rowVersions?.get(r.id);
324
+ if (shown && detectsLostUpdates(r)) {
325
+ const now = await rowVersion(c, table, r, versionColumns(ctx, r), pk, true);
326
+ if (now === null) throw new ProcessFailed(ctx.locale.t('form.changed'), null);
327
+ if (now !== shown) {
328
+ dbg(ctx, 2, 'process', `lost update prevented: the row of "${r.title ?? 'form'}" changed since the page was shown`);
329
+ throw new ProcessFailed(ctx.locale.t('form.lost_update'), null);
330
+ }
331
+ }
308
332
  if (op === 'update') {
309
333
  if (assignments.length) {
310
334
  const res = await c.query(`update ${table} set ${assignments.map(([col, v]) => `${col} = ${v}`).join(', ')} where ${pkCol} = ${literal(pk)}`);
@@ -511,6 +535,7 @@ async function runOneStep(ctx: PageContext, p: Process, names: Set<string>, dept
511
535
  case 'invoke_api': return await invokeApi(ctx, p, names);
512
536
  case 'workflow': return await workflowProcess(ctx, p, names);
513
537
  case 'send_push': return await sendPushProcess(ctx, p);
538
+ case 'send_email': return await sendEmailProcess(ctx, p);
514
539
  case 'ai_generate': return (await runAiProcess(ctx, p, names)).message;
515
540
  case 'plugin': return await runPluginProcess(ctx, p.config, p.name);
516
541
  case 'download':
@@ -0,0 +1,128 @@
1
+ // Feedback (APEX: Feedback), migration 084. With the application's feedback
2
+ // setting on, the navigation bar links to GET /a/:alias/:page/feedback: a
3
+ // form for a comment, an idea or a problem about that page (an optional
4
+ // rating), and the user's own earlier feedback with the developers' answers.
5
+ // Developers answer in the builder (src/builder/feedback.ts).
6
+ //
7
+ // The page's own access rules apply (no feedback about a page the user may
8
+ // not open). Feedback is stored with the user, page, session and browser
9
+ // name; at most FEEDBACK_PER_HOUR per session. Everything shown is escaped.
10
+ import type { FastifyInstance, FastifyReply } from 'fastify';
11
+ import { appTx, runtime } from '../db.ts';
12
+ import { html, raw } from '../html.ts';
13
+ import { icon } from '../icons.ts';
14
+ import { saveState } from '../session.ts';
15
+ import { checkPageAccess, Forbidden } from './authz.ts';
16
+ import type { PageContext } from './context.ts';
17
+ import type { ListNode } from './lists.ts';
18
+ import { chrome } from './render.ts';
19
+
20
+ type Loader = (req: any, reply: FastifyReply) => Promise<PageContext | null>;
21
+ type Tx = (ctx: PageContext) => Parameters<typeof appTx>[0];
22
+
23
+ const KINDS = ['comment', 'idea', 'problem'] as const;
24
+ export const FEEDBACK_PER_HOUR = 10;
25
+ const MAX_TEXT = 4000;
26
+
27
+ /** The navigation bar's Feedback entry (when the application asks for it). */
28
+ export function feedbackNode(ctx: PageContext): ListNode | null {
29
+ if (!ctx.app.feedback || ctx.dialog) return null;
30
+ return {
31
+ label: ctx.locale.t('feedback.link'), href: `${ctx.base}/${ctx.page.page_no}/feedback`, modal: false, external: false,
32
+ icon: 'chat', badge: null, description: null, current: false, inTrail: false, children: [],
33
+ };
34
+ }
35
+
36
+ const when = (d: string | Date) => new Date(d).toISOString().slice(0, 16).replace('T', ' ');
37
+
38
+ export function feedbackRoutes(app: FastifyInstance, loadContext: Loader, txContext: Tx) {
39
+ const page = async (ctx: PageContext, reply: FastifyReply, status: number, notice: { ok: boolean; text: string } | null, draft: { kind?: string; rating?: string; body?: string } = {}) => {
40
+ const t = ctx.locale.t;
41
+ const mine = ctx.user === 'nobody' ? [] : (await runtime.query(
42
+ `select page_no, kind, rating, body, status, response, responded_at, created_at from meta.feedback
43
+ where app_id = $1 and lower(username) = lower($2) order by created_at desc limit 50`, [ctx.app.id, ctx.user])).rows;
44
+ const status_ = (s: string) => t(`feedback.status.${s}` as never);
45
+ const main = html`<div class="t-titlebar"><h1>${t('feedback.title')}</h1></div>
46
+ <div class="t-content feedback-page">
47
+ <div class="messages" aria-live="polite">${notice ? html`<div class="alert ${notice.ok ? 'alert-success' : 'alert-error'}" role="${notice.ok ? 'status' : 'alert'}">${notice.text}</div>` : ''}</div>
48
+ <section class="region region-standard"><div class="region-body">
49
+ <p class="u-mt0">${t('feedback.intro', { page: ctx.page.title ?? ctx.page.name })}</p>
50
+ <form method="post" action="${ctx.base}/${ctx.page.page_no}/feedback" class="feedback-form">
51
+ <input type="hidden" name="__csrf" value="${ctx.session.csrf_token}">
52
+ <fieldset class="field"><legend class="label">${t('feedback.kind')}</legend>
53
+ <div class="choices">${KINDS.map((k) => html`<label class="check"><input type="radio" name="kind" value="${k}"${(draft.kind ?? 'comment') === k ? raw(' checked') : ''}> ${t(`feedback.kind.${k}` as never)}</label>`)}</div>
54
+ </fieldset>
55
+ <div class="field"><label class="label" for="feedback_rating">${t('feedback.rating')}</label>
56
+ <select id="feedback_rating" name="rating"><option value="">–</option>${[5, 4, 3, 2, 1].map((n) =>
57
+ html`<option value="${n}"${draft.rating === String(n) ? raw(' selected') : ''}>${'★'.repeat(n)}</option>`)}</select></div>
58
+ <div class="field" data-wide><label class="label" for="feedback_body">${t('feedback.text')}<span class="req" aria-hidden="true">*</span></label>
59
+ <textarea id="feedback_body" name="body" rows="6" maxlength="${MAX_TEXT}" required>${draft.body ?? ''}</textarea></div>
60
+ <div class="buttons"><a class="btn" href="${ctx.base}/${ctx.page.page_no}">${t('feedback.back')}</a><button class="btn btn-hot">${icon('send')} ${t('feedback.send')}</button></div>
61
+ </form>
62
+ </div></section>
63
+ ${ctx.user === 'nobody' ? '' : html`<section class="region region-standard"><header class="region-header"><h2>${t('feedback.mine')}</h2></header><div class="region-body">
64
+ ${mine.length ? html`<ul class="feedback-list">${mine.map((f) => html`<li>
65
+ <div class="feedback-meta"><span class="tag">${t(`feedback.kind.${f.kind}` as never)}</span> <span class="tag${f.status === 'done' ? ' tag-ok' : ''}">${status_(f.status)}</span>
66
+ <span class="muted">${when(f.created_at)}${f.page_no ? ` · ${t('feedback.page', { page: String(f.page_no) })}` : ''}${f.rating ? ` · ${'★'.repeat(f.rating)}` : ''}</span></div>
67
+ <p class="feedback-body">${f.body}</p>
68
+ ${f.response ? html`<div class="feedback-response"><strong>${t('feedback.response')}</strong><p>${f.response}</p></div>` : ''}
69
+ </li>`)}</ul>` : html`<p class="muted">${t('feedback.none')}</p>`}
70
+ </div></section>`}
71
+ </div>`;
72
+ ctx.vis = { regions: new Set(), items: new Set(), editable: new Set(), buttons: new Map(), dynamicActions: new Set() };
73
+ const body = await appTx(txContext(ctx), async (c) => {
74
+ ctx.client = c;
75
+ return chrome(ctx, main, t('feedback.title'));
76
+ });
77
+ await saveState(ctx.session);
78
+ return reply.code(status).type('text/html').send(body);
79
+ };
80
+
81
+ /** The context of a feedback request: the application allows feedback and the user may open the page. */
82
+ const context = async (req: any, reply: FastifyReply) => {
83
+ const ctx = await loadContext(req, reply);
84
+ if (!ctx) return null;
85
+ if (!ctx.app.feedback) {
86
+ reply.code(404).type('text/plain').send('Not found');
87
+ return null;
88
+ }
89
+ try {
90
+ await appTx(txContext(ctx), async (c) => {
91
+ ctx.client = c;
92
+ await checkPageAccess(ctx);
93
+ });
94
+ } catch (e) {
95
+ if (e instanceof Forbidden) {
96
+ reply.code(403).type('text/plain').send(e.message);
97
+ return null;
98
+ }
99
+ throw e;
100
+ }
101
+ return ctx;
102
+ };
103
+
104
+ app.get('/a/:alias/:page/feedback', async (req, reply) => {
105
+ const ctx = await context(req, reply);
106
+ if (!ctx) return;
107
+ return page(ctx, reply, 200, null);
108
+ });
109
+
110
+ app.post('/a/:alias/:page/feedback', async (req: any, reply) => {
111
+ const ctx = await context(req, reply);
112
+ if (!ctx) return;
113
+ const t = ctx.locale.t;
114
+ const b = req.body ?? {};
115
+ if (b.__csrf !== ctx.session.csrf_token) return page(ctx, reply, 403, { ok: false, text: t('error.session_reload') });
116
+ const kind = (KINDS as readonly string[]).includes(b.kind) ? b.kind : 'comment';
117
+ const rating = /^[1-5]$/.test(String(b.rating ?? '')) ? Number(b.rating) : null;
118
+ const text = String(b.body ?? '').replace(/\r\n?/g, '\n').trim();
119
+ if (!text || text.length > MAX_TEXT) return page(ctx, reply, 422, { ok: false, text: t('feedback.required') }, { kind, rating: b.rating, body: text.slice(0, MAX_TEXT) });
120
+ const recent = (await runtime.one<{ n: number }>(
121
+ `select count(*)::int as n from meta.feedback where app_id = $1 and session_id = $2 and created_at > now() - interval '1 hour'`, [ctx.app.id, ctx.session.id]))!.n;
122
+ if (recent >= FEEDBACK_PER_HOUR) return page(ctx, reply, 429, { ok: false, text: t('feedback.too_many') }, { kind, rating: b.rating, body: text });
123
+ await runtime.query(
124
+ `insert into meta.feedback (app_id, page_no, username, session_id, kind, rating, body, user_agent) values ($1, $2, $3, $4, $5, $6, $7, $8)`,
125
+ [ctx.app.id, ctx.page.page_no, ctx.user, ctx.session.id, kind, rating, text, String(req.headers['user-agent'] ?? '').slice(0, 300) || null]);
126
+ return page(ctx, reply, 200, { ok: true, text: t('feedback.thanks') });
127
+ });
128
+ }
@@ -11,6 +11,7 @@ import { restSql } from './rest-sources.ts';
11
11
  import { markdownHtml, sanitizeHtml } from '../richtext.ts';
12
12
  import { qrSvg, type Ecc } from '../qrcode.ts';
13
13
  import { formatNumber, isPlainNumber, maskError } from '../numformat.ts';
14
+ import { addressControl, imageControl } from './data-items.ts';
14
15
 
15
16
  const TRUTHY = new Set(['true', 't', 'on', '1', 'yes', 'y']);
16
17
  export const isTruthy = (v: string | null | undefined) => !!v && TRUTHY.has(v.toLowerCase());
@@ -230,6 +231,8 @@ export async function renderItem(ctx: PageContext, item: Item, hiddenByDa = fals
230
231
  control = await fileControl(ctx, item, editable, aria);
231
232
  } else if (item.type === 'qrcode') {
232
233
  control = qrControl(ctx, item, value);
234
+ } else if (item.type === 'image') {
235
+ control = imageControl(ctx, item, value);
233
236
  } else if (!editable && (item.type === 'richtext' || item.type === 'markdown')) {
234
237
  // rebuilt from the allow-list every time: the value may come from the table, not from this form
235
238
  control = html`<div class="display-value rich-text" id="${id}">${raw((item.type === 'markdown' ? markdownHtml(value) : sanitizeHtml(value)) || ' ')}</div>`;
@@ -372,6 +375,9 @@ export async function renderItem(ctx: PageContext, item: Item, hiddenByDa = fals
372
375
  </div>`;
373
376
  break;
374
377
  }
378
+ case 'address':
379
+ control = addressControl(ctx, item, value, aria);
380
+ break;
375
381
  case 'location':
376
382
  // "lat,lng"; app.js fills it from the device (geolocation) with the button
377
383
  control = html`<div class="input-with-button"><input type="text" id="${id}" name="${id}" value="${value}" inputmode="decimal" placeholder="52.01160,4.35710"${aria}>
@@ -412,6 +418,8 @@ export async function renderItem(ctx: PageContext, item: Item, hiddenByDa = fals
412
418
  const attrs = raw(
413
419
  [
414
420
  item.config?.submit_on_change ? 'data-submit-on-change' : '',
421
+ // (077) left out of "warn on unsaved changes"
422
+ item.config?.warn_unsaved === false ? 'data-no-warn' : '',
415
423
  item.config?.cascade_parents ? `data-cascade="${String(item.config.cascade_parents).replace(/[^A-Z0-9_,]/gi, '')}"` : '',
416
424
  hiddenByDa ? 'hidden' : '',
417
425
  item.config?.wide || item.type === 'textarea' || item.type === 'richtext' || item.type === 'markdown' || templateClasses('item', item.template_options).includes(' to-stretch') ? 'data-wide' : '',
@@ -1,7 +1,9 @@
1
1
  import { zipSync, type Zippable } from 'fflate';
2
2
  import { applyBinds } from '../binds.ts';
3
+ import { esc } from '../html.ts';
3
4
  import type { Process } from '../metadata.ts';
4
5
  import { bindValues, stripSemicolon, substitute, toState, type PageContext } from './context.ts';
6
+ import { exportDownload, exportProblems, type ExportConfig } from './data-export.ts';
5
7
 
6
8
  // Declarative page processes of migration 039: download (a file from a
7
9
  // query), workflow (start / terminate / retry) and the configuration checks
@@ -18,7 +20,7 @@ export interface Download {
18
20
  inline: boolean;
19
21
  }
20
22
 
21
- interface DownloadConfig {
23
+ interface DownloadConfig extends ExportConfig {
22
24
  content_column?: string;
23
25
  filename_column?: string;
24
26
  mime_column?: string;
@@ -60,6 +62,8 @@ export function downloadProblems(conf: unknown): string[] {
60
62
  if (c[k] !== undefined && !(typeof c[k] === 'string' && COLUMN.test(c[k] as string))) out.push(`"${k}" is a column name of the query.`);
61
63
  if (c.zip_name !== undefined && typeof c.zip_name !== 'string') out.push('"zip_name" is a file name.');
62
64
  if (c.disposition !== undefined && !['attachment', 'inline'].includes(c.disposition as string)) out.push('"disposition" is attachment or inline.');
65
+ // (086) the rows as a file
66
+ out.push(...exportProblems(c));
63
67
  return out;
64
68
  }
65
69
 
@@ -78,6 +82,8 @@ export async function downloadFile(ctx: PageContext, p: Process): Promise<Downlo
78
82
  const conf = (p.config ?? {}) as DownloadConfig;
79
83
  const problems = downloadProblems(conf);
80
84
  if (problems.length) throw new Error(`Process "${p.name}": ${problems.join(' ')}`);
85
+ // (086) {"export": "xlsx"}: the query's rows as a file, not a file from the query
86
+ if (conf.export) return exportDownload(ctx, p, conf);
81
87
  const sql = stripSemicolon(applyBinds(p.code ?? '', bindValues(ctx)));
82
88
  if (!sql) throw new Error(`Process "${p.name}" needs a query in its code.`);
83
89
  const c = ctx.client!;
@@ -169,7 +175,7 @@ export function chainProblems(conf: unknown): string[] {
169
175
  }
170
176
 
171
177
  /** Process types a background chain can run (nothing that needs the request: forms, grids, uploads, files). */
172
- export const BACKGROUND_TYPES = new Set<Process['type']>(['sql', 'invoke_api', 'workflow', 'chain', 'send_push']);
178
+ export const BACKGROUND_TYPES = new Set<Process['type']>(['sql', 'invoke_api', 'workflow', 'chain', 'send_push', 'send_email']);
173
179
 
174
180
  // ---------------------------------------------------------------- workflows
175
181
 
@@ -241,6 +247,7 @@ export function processProblems(type: string, conf: unknown): string[] {
241
247
  if (type === 'chain') return chainProblems(conf);
242
248
  if (type === 'workflow') return workflowProblems(conf);
243
249
  if (type === 'send_push') return sendPushProblems(conf);
250
+ if (type === 'send_email') return sendEmailProblems(conf);
244
251
  return [];
245
252
  }
246
253
 
@@ -288,3 +295,77 @@ export async function sendPushProcess(ctx: PageContext, p: Process): Promise<str
288
295
  ]);
289
296
  return p.success_message ?? null;
290
297
  }
298
+
299
+ // ---------------------------------------------------------------- send_email (081)
300
+
301
+ interface SendEmailConfig {
302
+ to: string;
303
+ cc?: string;
304
+ bcc?: string;
305
+ from?: string;
306
+ reply_to?: string;
307
+ subject?: string;
308
+ body?: string;
309
+ body_html?: string;
310
+ template?: string;
311
+ placeholders?: Record<string, string>;
312
+ attachments?: string;
313
+ }
314
+
315
+ const PLACEHOLDER = /^[A-Za-z][A-Za-z0-9_]{0,59}$/;
316
+
317
+ export function sendEmailProblems(conf: unknown): string[] {
318
+ const c = (conf ?? {}) as Record<string, any>;
319
+ const out: string[] = [];
320
+ const text = (k: string) => c[k] !== undefined && typeof c[k] !== 'string' && out.push(`"${k}" is text.`);
321
+ if (typeof c.to !== 'string' || !c.to.trim()) out.push('"to" is the recipients, e.g. "&P5_EMAIL." (several: separated by commas).');
322
+ for (const k of ['cc', 'bcc', 'from', 'reply_to', 'subject', 'body', 'body_html', 'template', 'attachments']) text(k);
323
+ if (c.template !== undefined) {
324
+ if (typeof c.template === 'string' && !/^[A-Za-z][A-Za-z0-9_]{0,59}$/.test(c.template)) out.push('"template" is the name of an e-mail template (Shared Components → E-mail templates).');
325
+ if (c.subject !== undefined || c.body !== undefined || c.body_html !== undefined) out.push('With a "template", the subject and bodies come from it: leave out "subject", "body" and "body_html".');
326
+ } else {
327
+ if (typeof c.subject !== 'string' || !c.subject.trim()) out.push('"subject" is required (or a "template").');
328
+ if (c.body === undefined && c.body_html === undefined) out.push('"body" (plain text) or "body_html" is required (or a "template").');
329
+ }
330
+ if (c.placeholders !== undefined && (typeof c.placeholders !== 'object' || Array.isArray(c.placeholders) || c.placeholders === null
331
+ || Object.entries(c.placeholders).some(([k, v]) => !PLACEHOLDER.test(k) || typeof v !== 'string')))
332
+ out.push('"placeholders" maps the template\'s #NAMES# to values, e.g. {"NAME": "&P5_NAME."}.');
333
+ if (typeof c.attachments === 'string' && !/^\s*(select|with)\b/i.test(c.attachments)) out.push('"attachments" is a SELECT of content (bytea), filename and mime.');
334
+ return out;
335
+ }
336
+
337
+ /**
338
+ * send_email (APEX: Send E-Mail): queues a mail with meta.send_mail or
339
+ * meta.send_mail_template in the page's transaction, so it is sent only when
340
+ * the submit commits. Values take &ITEM. substitutions (escaped in the HTML
341
+ * body); "attachments" is a SELECT (binds allowed) of content, filename and
342
+ * mime, one attachment per row.
343
+ */
344
+ export async function sendEmailProcess(ctx: PageContext, p: Process): Promise<string | null> {
345
+ const conf = (p.config ?? {}) as unknown as SendEmailConfig;
346
+ const problems = sendEmailProblems(conf);
347
+ if (problems.length) throw new Error(`Process "${p.name}": ${problems.join(' ')}`);
348
+ const value = (s: string | undefined) => (s === undefined ? null : substitute(s, ctx, (x) => x));
349
+ const c = ctx.client!;
350
+ let id: string;
351
+ if (conf.template) {
352
+ const placeholders = Object.fromEntries(Object.entries(conf.placeholders ?? {}).map(([k, v]) => [k.toUpperCase(), value(v) ?? '']));
353
+ id = (await c.query('select meta.send_mail_template($1, $2::jsonb, $3, $4, $5, $6, $7)::text as id', [
354
+ conf.template, JSON.stringify(placeholders), value(conf.to), value(conf.cc), value(conf.bcc), value(conf.from), value(conf.reply_to),
355
+ ])).rows[0].id;
356
+ } else {
357
+ id = (await c.query('select meta.send_mail($1, $2, $3, $4, $5, $6, $7, $8)::text as id', [
358
+ value(conf.to), value(conf.subject), value(conf.body),
359
+ conf.body_html === undefined ? null : substitute(conf.body_html, ctx, esc),
360
+ value(conf.from), value(conf.cc), value(conf.bcc), value(conf.reply_to),
361
+ ])).rows[0].id;
362
+ }
363
+ if (conf.attachments) {
364
+ const rows = (await c.query(stripSemicolon(applyBinds(conf.attachments, bindValues(ctx))))).rows as Record<string, unknown>[];
365
+ for (const row of rows) {
366
+ const get = (name: string) => Object.entries(row).find(([k]) => k.toLowerCase() === name)?.[1];
367
+ await c.query('select meta.add_mail_attachment($1, $2, $3, $4)', [id, get('content'), get('filename') ?? 'attachment', get('mime') ?? 'application/octet-stream']);
368
+ }
369
+ }
370
+ return p.success_message ?? null;
371
+ }
@@ -31,6 +31,8 @@ import { cacheKey, cacheOf, lazyOf, renderCaching, useCached } from './region-ca
31
31
  import { resolveRestRegion } from './rest-sources.ts';
32
32
  import { templateClasses } from './template-options.ts';
33
33
  import { renderPluginRegion } from './plugins.ts';
34
+ import { renderUrlRegion } from './url-region.ts';
35
+ import { renderSearch } from './search.ts';
34
36
 
35
37
  // ---------------------------------------------------------------- buttons
36
38
 
@@ -351,6 +353,12 @@ async function renderBody(ctx: PageContext, r: Region, hidden: Set<string>): Pro
351
353
  case 'ai_assistant':
352
354
  body = await renderAssistant(ctx, r);
353
355
  break;
356
+ case 'url':
357
+ body = renderUrlRegion(ctx, r);
358
+ break;
359
+ case 'search':
360
+ body = await renderSearch(ctx, r);
361
+ break;
354
362
  case 'dynamic':
355
363
  // A SELECT returning HTML (like APEX "PL/SQL Dynamic Content"). The
356
364
  // developer's SQL produces trusted markup; escape data with meta.html_escape().
@@ -19,6 +19,10 @@ import { renderItems } from './items.ts';
19
19
  import { buttonsFor, renderRegion } from './regions.ts';
20
20
  import { listTree, navbarMarkup, navMarkup } from './lists.ts';
21
21
  import { aiInputs, aiOutputs, aiProcessOf } from './ai.ts';
22
+ import { frameOrigins } from './url-region.ts';
23
+ import { devbarHtml } from './devbar.ts';
24
+ import { feedbackNode } from './feedback.ts';
25
+ import { sessionLimits } from '../session.ts';
22
26
 
23
27
  // ---------------------------------------------------------------- dynamic actions
24
28
 
@@ -241,7 +245,10 @@ export async function chrome(ctx: PageContext, main: Raw, title: string) {
241
245
  const signedIn = ctx.user !== 'nobody';
242
246
  const topNav = ctx.app.theme?.nav === 'top';
243
247
  const nav = await navTree(ctx, topNav);
244
- const navbarNodes = ctx.app.navbar_list ? await listTree(ctx, ctx.app.navbar_list) : null;
248
+ const listNodes = ctx.app.navbar_list ? await listTree(ctx, ctx.app.navbar_list) : null;
249
+ // (084) the Feedback entry, after the application's own navigation bar list
250
+ const feedback = feedbackNode(ctx);
251
+ const navbarNodes = listNodes || feedback ? [...(listNodes ?? []), ...(feedback ? [feedback] : [])] : null;
245
252
  const navbar = navbarNodes ? navbarMarkup(navbarNodes, t('list.navbar')) : '';
246
253
  return documentShell(
247
254
  `${title} · ${ctx.app.name}`,
@@ -276,7 +283,8 @@ export async function chrome(ctx: PageContext, main: Raw, title: string) {
276
283
  <nav id="t-nav" class="t-nav" aria-label="Main"><ul>${nav}</ul></nav>
277
284
  <a href="#" class="t-nav-backdrop" tabindex="-1" aria-hidden="true"></a>
278
285
  <main class="t-main" id="main">${main}</main>
279
- </div>`,
286
+ </div>
287
+ ${devbarHtml(ctx)}`,
280
288
  `t-app${topNav ? ' nav-top' : ''}`,
281
289
  { 'data-base': ctx.base, 'data-page': String(ctx.page.page_no), ...pwaBody(ctx.app, ctx.user), ...(await pushBody(ctx.app, ctx.session.username)) },
282
290
  html`${pageStyle(ctx)}${pwaHead(ctx.app)}${mapHead(ctx)}${staticHead(ctx)}`,
@@ -293,17 +301,31 @@ function formKeys(ctx: PageContext) {
293
301
  .filter((r) => r.type === 'form' && r.pk_item && ctx.vis!.regions.has(r.id))
294
302
  .map((r) => {
295
303
  const pk = ctx.session.state[r.pk_item!] ?? '';
296
- return html`<input type="hidden" name="__pk_${r.id}" value="${pk}"><input type="hidden" name="__pkcs_${r.id}" value="${urlChecksum(ctx.app.id, ctx.page.page_no, ctx.user, { [`F${r.id}`]: pk })}">`;
304
+ const version = pk === '' ? undefined : ctx.rowVersions?.get(r.id);
305
+ return html`<input type="hidden" name="__pk_${r.id}" value="${pk}"><input type="hidden" name="__pkcs_${r.id}" value="${urlChecksum(ctx.app.id, ctx.page.page_no, ctx.user, { [`F${r.id}`]: pk })}">${
306
+ version ? html`<input type="hidden" name="__rv_${r.id}" value="${version}">` : ''}`;
297
307
  });
298
308
  }
299
309
 
300
310
  /** Texts app.js shows (offline banner and queue, location and scan buttons), in the page's language. */
301
311
  const CLIENT_TEXTS = ['pwa.offline_banner', 'pwa.queued', 'pwa.queue_waiting', 'pwa.send_now', 'pwa.discard', 'pwa.status.waiting',
302
- 'pwa.status.signin', 'pwa.status.invalid', 'pwa.status.error', 'item.locate_error', 'item.scan_close', 'common.dismiss',
312
+ 'pwa.status.signin', 'pwa.status.invalid', 'pwa.status.error', 'item.locate_error', 'item.address_none', 'item.address_error', 'item.scan_close', 'common.dismiss',
303
313
  'crop.title', 'crop.apply', 'crop.skip', 'crop.help',
304
- 'push.turn_on', 'push.turn_off', 'push.on', 'push.off', 'push.blocked', 'push.unsupported', 'push.failed'] as const;
314
+ 'push.turn_on', 'push.turn_off', 'push.on', 'push.off', 'push.blocked', 'push.unsupported', 'push.failed', 'page.unsaved_changes', 'page.link_copied',
315
+ 'session.warning', 'session.stay', 'session.max', 'session.ended', 'login.sign_in_link'] as const;
305
316
  export const clientTexts = (ctx: PageContext) => Object.fromEntries(CLIENT_TEXTS.map((k) => [k, ctx.locale.t(k)]));
306
317
 
318
+ /**
319
+ * (085) The session timeout warning: when a signed-in session ends (idle time from now, or its
320
+ * maximum length) and how long before that the page warns. Null: no warning.
321
+ */
322
+ function sessionMeta(ctx: PageContext) {
323
+ const warn = Number(ctx.app.session_warning_seconds ?? 120);
324
+ if (!warn || ctx.dialog || !ctx.session.username || ctx.app.authentication === 'none' || ctx.app.authentication === 'header') return null;
325
+ const { idleMinutes, maxHours } = sessionLimits();
326
+ return { idle: idleMinutes * 60, maxEnd: ctx.session.created_ms ? Math.round(ctx.session.created_ms + maxHours * 3600_000) : null, warn, extend: `${ctx.base}/session/extend` };
327
+ }
328
+
307
329
  /** The current page's URL (for returning after a preference change). */
308
330
  const here = (ctx: PageContext) => `${ctx.base}/${ctx.page.page_no}`;
309
331
 
@@ -321,6 +343,8 @@ export async function renderPage(ctx: PageContext) {
321
343
  const pageItems = await renderItems(ctx, ctx.page.items.filter((i) => i.region_id === null), hidden);
322
344
  const regions = [];
323
345
  for (const r of ctx.page.regions) regions.push(await renderRegion(ctx, r, hidden));
346
+ // (078) the origins of the page's URL regions (also those a refresh or lazy load shows later)
347
+ for (const o of frameOrigins(ctx.page.regions.filter((r) => ctx.vis!.regions.has(r.id)))) ctx.frameSrc?.add(o);
324
348
  const title = substitute(ctx.page.title ?? ctx.page.name, ctx, (v) => v);
325
349
  const crumbs = ctx.dialog ? [] : await breadcrumb(ctx);
326
350
  const das = dynamicActionsJson(ctx);
@@ -340,7 +364,9 @@ export async function renderPage(ctx: PageContext) {
340
364
  ? html`<div class="alert alert-error" role="alert">${t('error.correct_below')}</div>`
341
365
  : ''}
342
366
  </div>
343
- <form method="post" class="page-form" action="${ctx.base}/${ctx.page.page_no}"${ctx.page.items.some((i) => i.type === 'file') ? raw(' enctype="multipart/form-data"') : ''} novalidate>
367
+ <form method="post" class="page-form" action="${ctx.base}/${ctx.page.page_no}"${ctx.page.items.some((i) => i.type === 'file') ? raw(' enctype="multipart/form-data"') : ''}${
368
+ // (077) shown again after a failed submit: the values on the page are not saved yet
369
+ ctx.page.warn_unsaved ? raw(` data-warn-unsaved="${ctx.body ? 'changed' : 'on'}"`) : ''} novalidate>
344
370
  <input type="hidden" name="__csrf" value="${ctx.session.csrf_token}">
345
371
  <input type="hidden" name="__submit_id" value="${randomUUID()}">
346
372
  ${formKeys(ctx)}
@@ -353,7 +379,7 @@ export async function renderPage(ctx: PageContext) {
353
379
  ${ctx.detached}
354
380
  </div>
355
381
  <script type="application/json" id="pgkiln-meta">${raw(
356
- JSON.stringify({ csrf: ctx.session.csrf_token, das, texts: clientTexts(ctx), dialogs: dialogShapes(ctx), ...timeZoneMeta(ctx) }).replace(/</g, '\\u003c'),
382
+ JSON.stringify({ csrf: ctx.session.csrf_token, das, texts: clientTexts(ctx), dialogs: dialogShapes(ctx), ...timeZoneMeta(ctx), session: sessionMeta(ctx) }).replace(/</g, '\\u003c'),
357
383
  )}</script>`;
358
384
  return chrome(ctx, main, title);
359
385
  }
@@ -1,3 +1,4 @@
1
+ import { availabilityRefusal } from './availability.ts';
1
2
  import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
2
3
  import { jwtVerify } from 'jose';
3
4
  import pg from 'pg';
@@ -147,6 +148,9 @@ async function handle(req: FastifyRequest, reply: FastifyReply) {
147
148
  const query = req.query as Record<string, string | string[]>;
148
149
  try {
149
150
  const who = await caller(req, a, h.auth === 'public');
151
+ // (083) the application's availability (no builder session here: developers only means nobody)
152
+ const refusal = availabilityRefusal(a, { username: who.user === 'nobody' ? null : who.user, developer: false });
153
+ if (refusal) throw new RestError(refusal.status, refusal.message ?? english(refusal.key));
150
154
  const binds: BindValues = {};
151
155
  for (const [k, v] of Object.entries(query)) binds[k.toUpperCase()] = Array.isArray(v) ? v[0] : v;
152
156
  const body = req.body;
@@ -16,7 +16,7 @@ import { passwordDaysLeft, passwordProblem } from '../accounts.ts';
16
16
  import { english, type Translate } from '../i18n.ts';
17
17
  import { checksumValid, loginWindowMinutes, urlChecksum } from '../security.ts';
18
18
  import { enabledProviders, finishSignIn, loadProvider, ssoAccess, SsoError, startSignIn, type SsoResult } from '../sso.ts';
19
- import { clientIp, createSession, destroySession, getSession, loginThrottled, logActivity, saveState, takeFlash, type Session } from '../session.ts';
19
+ import { sessionLimits, clientIp, createSession, destroySession, getSession, loginThrottled, logActivity, saveState, takeFlash, type Session } from '../session.ts';
20
20
  import { checkPageAccess, computeVisibility, Forbidden, isAuthorized } from './authz.ts';
21
21
  import { bindValues, dbg, publicError, stripSemicolon, timed, toState, writeOut, type PageContext } from './context.ts';
22
22
  import { startDebug } from '../debug.ts';
@@ -43,6 +43,11 @@ import { renderDocument } from './documents.ts';
43
43
  import { pwaHead } from './pwa.ts';
44
44
  import { resolveLocale, THEME_COOKIE, translateApp, translatePage, validTimeZone, type Locale } from './locale.ts';
45
45
  import { chrome, dialogClosePage, languagePicker, renderPage } from './render.ts';
46
+ import { devbarOf, devbarRoutes, sessionDebugLevel } from './devbar.ts';
47
+ import { availabilityRefusal } from './availability.ts';
48
+ import { feedbackRoutes } from './feedback.ts';
49
+ import { dataItemRoutes, loadPreferences, savePreferences } from './data-items.ts';
50
+ import { ajaxRoutes } from './ajax.ts';
46
51
 
47
52
  const XLSX_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
48
53
 
@@ -252,8 +257,24 @@ export async function loadContext(req: Req, reply: FastifyReply, { json = false,
252
257
  else reply.redirect(`${base}/login?next=${encodeURIComponent(req.url)}`);
253
258
  return null;
254
259
  }
255
- // debug messages (src/debug.ts): only when the application's debug level is on
256
- const debug = startDebug(req, app);
260
+ // debug messages (src/debug.ts): when the application's debug level is on, or (079) the developer
261
+ // toolbar switched it on for this session
262
+ const debug = startDebug(req, { id: app.id, debug_level: Math.max(Number(app.debug_level ?? 0), sessionDebugLevel(session)) });
263
+ // (079) the developer toolbar: a builder session of a developer of this application in the same browser
264
+ const devbar = await devbarOf(req, app.id);
265
+ // (083) the application's availability: unavailable, developers only, or restricted to named users
266
+ const refusal = availabilityRefusal(app, { username: session.username, developer: !!devbar });
267
+ if (refusal) {
268
+ if (refusal.signIn) {
269
+ if (json) reply.code(401).send({ error: locale.t('error.session_ended') });
270
+ else reply.redirect(`${base}/login?next=${encodeURIComponent(req.url)}`);
271
+ return null;
272
+ }
273
+ const text = refusal.message ?? locale.t(refusal.key);
274
+ if (json) reply.code(refusal.status).send({ error: text });
275
+ else simplePage(reply, refusal.status, locale.t('app.unavailable_title'), text, undefined, locale);
276
+ return null;
277
+ }
257
278
  if (debug) {
258
279
  debug.pageNo = page.page_no;
259
280
  debug.username = user;
@@ -262,6 +283,7 @@ export async function loadContext(req: Req, reply: FastifyReply, { json = false,
262
283
  }
263
284
  return {
264
285
  debug,
286
+ devbar,
265
287
  app,
266
288
  page,
267
289
  session,
@@ -278,6 +300,8 @@ export async function loadContext(req: Req, reply: FastifyReply, { json = false,
278
300
  detached: [],
279
301
  css: new PageCss(),
280
302
  nonce: req.cspNonce,
303
+ frameSrc: req.frameSrc,
304
+ imgSrc: req.imgSrc,
281
305
  locale,
282
306
  };
283
307
  }
@@ -400,6 +424,8 @@ export async function runtimeRoutes(app: FastifyInstance) {
400
424
  ctx.client = c;
401
425
  await timed(ctx, 4, 'page', 'page authorization', () => checkPageAccess(ctx));
402
426
  await timed(ctx, 4, 'page', 'application processes (before page)', () => runAppProcesses(ctx, 'before_page'));
427
+ // (086) items kept per user: their values from the user's preferences
428
+ await loadPreferences(ctx);
403
429
  // before header (as in APEX): branches, then computations and processes
404
430
  if (!docName && !downloadKey) {
405
431
  const to = await branchTarget(ctx, 'before_header');
@@ -495,6 +521,9 @@ export async function runtimeRoutes(app: FastifyInstance) {
495
521
  const cs = body[`__pkcs_${r.id}`];
496
522
  if (typeof pk === 'string' && typeof cs === 'string' && checksumValid(urlChecksum(ctx.app.id, ctx.page.page_no, ctx.user, { [`F${r.id}`]: pk }), cs))
497
523
  ctx.session.state[r.pk_item] = pk === '' ? null : pk;
524
+ // (076) the checksum of the row as it was shown (lost update detection in form_dml)
525
+ const rv = body[`__rv_${r.id}`];
526
+ if (typeof rv === 'string' && /^[0-9a-f]{32}$/.test(rv)) (ctx.rowVersions ??= new Map()).set(r.id, rv);
498
527
  }
499
528
 
500
529
  let messages: string[] = [];
@@ -516,7 +545,10 @@ export async function runtimeRoutes(app: FastifyInstance) {
516
545
  applyPostedItems(ctx, body);
517
546
  await applyUploads(ctx, files, body, txContext);
518
547
  if (Object.keys(ctx.errors.items).length) throw new ValidationFailed(ctx.errors);
519
- if (!pressed) return undefined;
548
+ if (!pressed) {
549
+ await savePreferences(ctx);
550
+ return undefined;
551
+ }
520
552
  ctx.request = pressed.name;
521
553
  snapshot = { ...ctx.session.state };
522
554
  try {
@@ -531,6 +563,8 @@ export async function runtimeRoutes(app: FastifyInstance) {
531
563
  // after processing: the first branch that applies; else the button's target page
532
564
  branchTo = await branchTarget(ctx, 'after_processing');
533
565
  if (branchTo) dbg(ctx, 4, 'branch', `after processing: ${branchTo.split('?')[0]}`);
566
+ // (086) items kept per user: saved with the page's changes
567
+ await savePreferences(ctx);
534
568
  return pressed;
535
569
  });
536
570
  } catch (e) {
@@ -569,6 +603,22 @@ export async function runtimeRoutes(app: FastifyInstance) {
569
603
 
570
604
  // ---------------------------------------------------------------- file downloads
571
605
  fileRoutes(app, loadContext, txContext, forbidden);
606
+ // (079) the developer toolbar's session state viewer and actions
607
+ devbarRoutes(app, loadContext);
608
+ // (084) users' feedback
609
+ feedbackRoutes(app, loadContext, txContext);
610
+ // (086) display image items' pictures, address items' geocoder
611
+ dataItemRoutes(app, loadContext, txContext);
612
+ // (085) Ajax callbacks and the dynamic action "download"
613
+ ajaxRoutes(app, loadContext, txContext, applyPostedItems);
614
+ // (085) "Stay signed in" of the session timeout warning: the session's last activity is now
615
+ app.post('/a/:alias/session/extend', async (req: Req, reply) => {
616
+ const a = await loadApp(req.params.alias);
617
+ if (!a) return reply.code(404).send({ ok: false });
618
+ const session = await getSession(req, reply, a.id, `/a/${a.alias}`);
619
+ if (!session.username || req.body?.__csrf !== session.csrf_token) return reply.code(401).send({ ok: false });
620
+ return reply.header('cache-control', 'no-store').send({ ok: true, idle: sessionLimits().idleMinutes * 60 });
621
+ });
572
622
 
573
623
  // ---------------------------------------------------------------- dynamic actions (AJAX)
574
624
  app.post('/a/:alias/:page/da/:id', async (req: Req, reply) => {
@@ -748,7 +798,8 @@ export async function runtimeRoutes(app: FastifyInstance) {
748
798
  if (masters.length) selected = applyRowSelection(ctx);
749
799
  const vis = await computeVisibility(ctx);
750
800
  const detail = masters.some((m) => vis.regions.has(m.id));
751
- if (!r || !(lazyOf(r) || detail) || !vis.regions.has(r.id)) throw new Forbidden(ctx.locale.t('error.access_denied'));
801
+ // (080) a search region: its results for the text typed so far
802
+ if (!r || !(lazyOf(r) || detail || r.type === 'search') || !vis.regions.has(r.id)) throw new Forbidden(ctx.locale.t('error.access_denied'));
752
803
  ctx.loadNow = r.id;
753
804
  const markup = (await renderRegion(ctx, r)).toString();
754
805
  return { html: markup, css: ctx.css.text, detached: ctx.detached.map(String).join('') };
@@ -1079,6 +1130,9 @@ export async function runtimeRoutes(app: FastifyInstance) {
1079
1130
  const a0 = await loadApp(req.params.alias);
1080
1131
  if (!a0) return simplePage(reply, 404, english('error.not_found'), english('error.app_not_found', { app: req.params.alias }));
1081
1132
  if (a0.authentication === 'none') return reply.redirect(`/a/${a0.alias}`);
1133
+ // (083) unavailable or for developers only: no sign-in form either (restricted: users sign in, then are checked)
1134
+ const closed = availabilityRefusal(a0, { username: 'x', developer: !!(await devbarOf(req, a0.id)) });
1135
+ if (closed && closed.status === 503) return simplePage(reply, 503, english('app.unavailable_title'), closed.message ?? english(closed.key));
1082
1136
  // header authentication has no sign-in form: the proxy signs the user in on any page
1083
1137
  if (a0.authentication === 'header') return reply.redirect(safeNext(a0, req.query.next));
1084
1138
  const session = await getSession(req, reply, a0.id, `/a/${a0.alias}`);