pgkiln 0.45.0 → 0.47.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 (93) hide show
  1. package/db/migrations/106_form_designer.sql +102 -0
  2. package/db/migrations/107_app_version.sql +9 -0
  3. package/db/migrations/108_sql_history.sql +25 -0
  4. package/docs/apex-feature-parity.md +33 -4
  5. package/docs/guide/03-builder.md +123 -28
  6. package/docs/guide/04-pages-and-regions.md +74 -2
  7. package/docs/guide/05-items.md +14 -2
  8. package/docs/guide/08-security.md +1 -1
  9. package/docs/guide/09-reference.md +1 -1
  10. package/docs/guide/10-tutorial.md +1 -1
  11. package/docs/guide/11-from-apex.md +2 -1
  12. package/docs/guide/12-development.md +26 -3
  13. package/docs/guide/16-files.md +2 -2
  14. package/examples/hr/hr_61_form_designer.sql +80 -0
  15. package/package.json +1 -1
  16. package/public/app.css +62 -2
  17. package/public/app.js +244 -35
  18. package/public/builder.css +21 -1
  19. package/public/builder.js +67 -0
  20. package/public/sw.js +2 -1
  21. package/public/worksheet.css +244 -0
  22. package/public/worksheet.js +665 -0
  23. package/src/app.ts +9 -1
  24. package/src/builder/ai-builder.ts +3 -3
  25. package/src/builder/appwizard.ts +22 -6
  26. package/src/builder/arrange.ts +33 -12
  27. package/src/builder/code-editor.ts +1 -1
  28. package/src/builder/components.ts +1 -1
  29. package/src/builder/designer.ts +44 -17
  30. package/src/builder/errors.ts +65 -0
  31. package/src/builder/form-designer.ts +229 -0
  32. package/src/builder/locks.ts +6 -0
  33. package/src/builder/newapp.ts +2 -1
  34. package/src/builder/object-actions.ts +166 -0
  35. package/src/builder/object-browser.ts +111 -33
  36. package/src/builder/querybuilder.ts +1 -1
  37. package/src/builder/region-help.ts +2 -0
  38. package/src/builder/region-settings.ts +2 -0
  39. package/src/builder/reporter.ts +1 -1
  40. package/src/builder/routes.ts +7 -5
  41. package/src/builder/sampledata.ts +2 -2
  42. package/src/builder/scripts.ts +3 -3
  43. package/src/builder/search.ts +3 -3
  44. package/src/builder/shared.ts +2 -2
  45. package/src/builder/sql.ts +15 -73
  46. package/src/builder/table-editor.ts +219 -0
  47. package/src/builder/ui.ts +5 -3
  48. package/src/builder/unload.ts +8 -4
  49. package/src/builder/worksheet.ts +569 -0
  50. package/src/builder/workspaces.ts +1 -1
  51. package/src/cli/replace.ts +10 -0
  52. package/src/i18n/ar.ts +62 -0
  53. package/src/i18n/cs.ts +62 -0
  54. package/src/i18n/da.ts +62 -0
  55. package/src/i18n/de.ts +62 -0
  56. package/src/i18n/el.ts +62 -0
  57. package/src/i18n/es.ts +62 -0
  58. package/src/i18n/fi.ts +62 -0
  59. package/src/i18n/fr.ts +62 -0
  60. package/src/i18n/he.ts +62 -0
  61. package/src/i18n/it.ts +62 -0
  62. package/src/i18n/ja.ts +62 -0
  63. package/src/i18n/ko.ts +62 -0
  64. package/src/i18n/nb.ts +62 -0
  65. package/src/i18n/pl.ts +62 -0
  66. package/src/i18n/pt.ts +62 -0
  67. package/src/i18n/ru.ts +62 -0
  68. package/src/i18n/sv.ts +62 -0
  69. package/src/i18n/tr.ts +62 -0
  70. package/src/i18n/uk.ts +62 -0
  71. package/src/i18n/zh.ts +62 -0
  72. package/src/i18n.ts +124 -0
  73. package/src/metadata.ts +4 -2
  74. package/src/runtime/devbar.ts +1 -1
  75. package/src/runtime/facet-state.ts +10 -5
  76. package/src/runtime/facets.ts +29 -5
  77. package/src/runtime/form-designer.ts +676 -0
  78. package/src/runtime/grid.ts +15 -8
  79. package/src/runtime/items.ts +33 -21
  80. package/src/runtime/lists.ts +1 -1
  81. package/src/runtime/pdf.ts +2 -1
  82. package/src/runtime/regions.ts +4 -0
  83. package/src/runtime/render.ts +7 -3
  84. package/src/runtime/report.ts +2 -2
  85. package/src/runtime/routes.ts +3 -1
  86. package/src/runtime/smart-filters.ts +2 -1
  87. package/src/runtime/tasks.ts +6 -3
  88. package/src/sqlformat.ts +208 -0
  89. package/src/sqlplan.ts +133 -0
  90. package/src/sqlscript.ts +6 -2
  91. package/src/sqlworksheet.ts +278 -0
  92. package/src/tabledef.ts +226 -0
  93. package/src/unload.ts +14 -3
package/src/app.ts CHANGED
@@ -49,6 +49,9 @@ import { accountRoutes } from './runtime/account.ts';
49
49
  import { taskRoutes } from './runtime/tasks.ts';
50
50
  import { dataReporterRoutes } from './runtime/data-reporter.ts';
51
51
  import { reporterBuilderRoutes } from './builder/reporter.ts';
52
+ import { formDesignerRoutes } from './runtime/form-designer.ts';
53
+ import { formDesignerBuilderRoutes } from './builder/form-designer.ts';
54
+ import { builderErrorPages, builderServerError } from './builder/errors.ts';
52
55
  import { workflowRoutes } from './runtime/workflows.ts';
53
56
  import { pwaRoutes } from './runtime/pwa.ts';
54
57
  import { pushRoutes } from './runtime/push.ts';
@@ -138,10 +141,13 @@ export async function buildApp(opts: { logger?: boolean } = {}) {
138
141
  });
139
142
  // An id in the URL that isn't a number (or is too big) fails in PostgreSQL:
140
143
  // that's a page that doesn't exist, not a server error.
141
- app.setErrorHandler((err: Error & { code?: string }, _req, reply) => {
144
+ app.setErrorHandler((err: Error & { code?: string }, req, reply) => {
142
145
  if (err.code === '22P02' || err.code === '22003') return reply.code(404).type('text/plain').send('Not found');
146
+ // (sprint 86) a browser on a builder page gets an HTML error page
147
+ if (builderServerError(req, reply, err)) return reply;
143
148
  return reply.send(err);
144
149
  });
150
+ builderErrorPages(app);
145
151
  await app.register(cookie);
146
152
  await app.register(formbody, { bodyLimit: 5 * 1024 * 1024 });
147
153
  // file upload items; oversized files are cut off and reported, not thrown
@@ -223,6 +229,8 @@ export async function buildApp(opts: { logger?: boolean } = {}) {
223
229
  await app.register(codeEditorRoutes);
224
230
  await app.register(dataReporterRoutes);
225
231
  await app.register(reporterBuilderRoutes);
232
+ await app.register(formDesignerRoutes);
233
+ await app.register(formDesignerBuilderRoutes);
226
234
  await app.register(sampleDataRoutes);
227
235
  await app.register(assistantRoutes);
228
236
  await app.register(aiFilterRoutes);
@@ -15,7 +15,7 @@ import { WIZARD_KINDS, wizardTables } from './wizards.ts';
15
15
  // App Builder AI (migration 062), with the AI service an administrator
16
16
  // chooses for the builder (meta.builder_ai):
17
17
  // - SQL Workshop → AI: SQL from a question (shown, never run: the developer
18
- // may run it in SQL Commands), and an explanation of a query or an error;
18
+ // may run it in the SQL Worksheet), and an explanation of a query or an error;
19
19
  // - SQL Workshop → AI → Describe tables: descriptions of tables and columns
20
20
  // for the model (meta.ai_table_note, optionally also COMMENT ON), typed or
21
21
  // drafted by AI from the names and types (never from the data) and
@@ -148,7 +148,7 @@ async function workshopPage(s: Session, reply: FastifyReply, out: { question?: s
148
148
  ${out.result ?? ''}
149
149
  <div class="columns">
150
150
  ${region('SQL from a question', html`
151
- <p class="muted u-mt0">The answer is shown, never run: check it, then run it in SQL Commands if you want.</p>
151
+ <p class="muted u-mt0">The answer is shown, never run: check it, then run it in the SQL Worksheet if you want.</p>
152
152
  <form method="post" action="${BASE}/sql/ai/sql">${csrf(s)}
153
153
  <div class="form-grid">${select('schema', 'Schema', out.schema ?? list[0] ?? '', list)}</div>
154
154
  <div class="field"><label class="label" for="f_question">Question</label>
@@ -324,7 +324,7 @@ export async function aiBuilderRoutes(app: FastifyInstance) {
324
324
  <form method="post" action="${BASE}/sql">${csrf(s)}
325
325
  <div class="field"><label class="label" for="f_ai_sql">SQL (not run)</label>
326
326
  <textarea id="f_ai_sql" name="sql" class="code sql-editor" rows="10" spellcheck="false" data-code="plpgsql">${sql}</textarea></div>
327
- <div class="buttons"><button class="btn">Run in SQL Commands</button></div>
327
+ <div class="buttons"><button class="btn">Run in the SQL Worksheet</button></div>
328
328
  </form>`);
329
329
  } catch (e) {
330
330
  result = errorBox(e);
@@ -50,6 +50,9 @@ interface Relation {
50
50
  calendar: boolean;
51
51
  /** (sprint 73) a table with a foreign key to this one, for master-detail */
52
52
  detail: boolean;
53
+ /** (sprint 87) row level security is on, with this many policies */
54
+ rls: boolean;
55
+ policies: number;
53
56
  }
54
57
 
55
58
  /** The tables, partitioned tables, views and materialized views of a schema (not partitions). */
@@ -59,7 +62,8 @@ export async function schemaRelations(schema: string): Promise<Relation[]> {
59
62
  `select c.relname, meta.wizard_table_label(c.oid) as label, case when c.relkind in ('v', 'm') then 'view' else 'table' end as kind,
60
63
  meta.wizard_pk(c.oid) as pk, case when c.reltuples >= 0 then c.reltuples::bigint end as rows,
61
64
  meta.wizard_defaults('calendar', c.oid) ->> 'start' is not null as calendar,
62
- meta.wizard_pk(c.oid) is not null and meta.wizard_defaults('master_detail', c.oid) ->> 'detail' is not null as detail
65
+ meta.wizard_pk(c.oid) is not null and meta.wizard_defaults('master_detail', c.oid) ->> 'detail' is not null as detail,
66
+ c.relrowsecurity as rls, (select count(*)::int from pg_policy p where p.polrelid = c.oid) as policies
63
67
  from pg_class c join pg_namespace n on n.oid = c.relnamespace
64
68
  where n.nspname = $1 and c.relkind in ('r', 'p', 'v', 'm') and not c.relispartition
65
69
  order by c.relkind in ('v', 'm'), c.relname`,
@@ -311,6 +315,16 @@ const SOURCES: [string, string, string, string][] = [
311
315
  ['gallery', 'grid', 'From the App Gallery', 'A starter application'],
312
316
  ];
313
317
 
318
+ /**
319
+ * (sprint 87) A table's row level security, before the application is created: on with its number
320
+ * of policies, or on without any (the application's role then sees no rows unless it owns the table).
321
+ */
322
+ const rlsBadge = (r: Relation) =>
323
+ !r.rls ? ''
324
+ : r.policies > 0
325
+ ? html` <span class="tag aw-rls" title="Row level security is on (${r.policies} ${r.policies === 1 ? 'policy' : 'policies'}): each user sees only the rows the policies allow">${icon('shield')} RLS · ${r.policies}</span>`
326
+ : html` <span class="tag tag-error aw-rls" title="Row level security is on without policies: the application's role sees no rows (unless it owns the table or bypasses row level security)">${icon('shield')} RLS, no policies</span>`;
327
+
314
328
  async function createPage(s: Session, reply: FastifyReply, schema: string, b: Body | null, message: Raw | '' = '') {
315
329
  const schemas = await appSchemas();
316
330
  const known = schemas.includes(schema);
@@ -334,8 +348,8 @@ async function createPage(s: Session, reply: FastifyReply, schema: string, b: Bo
334
348
  'The application\'s parsing schema. Choose a schema to get a page per table and view; a new schema is named after the alias.')}</div>
335
349
  <div class="buttons"><button class="btn">${icon('search')} Show its tables</button></div></form>`)}
336
350
  <form method="post" action="${BASE}/apps" data-progress="Creating the application and its pages…">${csrf(s)}
337
- <input type="hidden" name="schema" value="${known ? schema : ''}"><input type="hidden" name="features" value="1">
338
- ${known ? html`<input type="hidden" name="tables" value="1">` : ''}
351
+ <input type="hidden" name="features" value="1">
352
+ <div id="aw-schema-fields"><input type="hidden" name="schema" value="${known ? schema : ''}">${known ? html`<input type="hidden" name="tables" value="1">` : ''}</div>
339
353
  ${region('Application', html`<div class="form-grid">
340
354
  <div class="field"><label class="label" for="f_name">Name</label>
341
355
  <input id="f_name" name="name" value="${v('name', suggested)}" required data-select-once></div>
@@ -354,14 +368,16 @@ async function createPage(s: Session, reply: FastifyReply, schema: string, b: Bo
354
368
  ? relations.map((r, i) => html`<li><input type="hidden" name="t_${i}" value="${r.relname}">
355
369
  <label class="aw-page-kind" for="f_k_${i}">${icon(r.kind === 'view' ? 'eye' : 'table')} ${r.label}</label>
356
370
  <select id="f_k_${i}" name="k_${i}">${kindsFor(r).map((k) => html`<option value="${k}"${k === kindOf(r, i) ? raw(' selected') : ''}>${PAGE_KINDS[k]}</option>`)}</select>
357
- <small class="muted"><code>${r.relname}</code> · ${r.kind === 'view' ? 'view' : rows(r)}${r.kind === 'table' && !r.pk ? ', no single-column key: no form' : ''}${Number(r.rows ?? 0) > LARGE_TABLE ? ': a paged grid' : ''}</small></li>`)
371
+ <small class="muted"><code>${r.relname}</code> · ${r.kind === 'view' ? 'view' : rows(r)}${r.kind === 'table' && !r.pk ? ', no single-column key: no form' : ''}${Number(r.rows ?? 0) > LARGE_TABLE ? ': a paged grid' : ''}</small>${rlsBadge(r)}</li>`)
358
372
  : html`<li class="muted">${schema} has no tables or views.</li>`
359
373
  : html`<li class="muted">Choose a schema under Data for a page per table, or add pages with the page wizards later.</li>`}
360
374
  </ul>
361
- ${known ? check('chart', 'Dashboard: a chart per table with the number of rows per parent row (a foreign key) or per value of a column whose values repeat', b ? b.chart === 'true' : true) : ''}`)}
375
+ ${known ? check('chart', 'Dashboard: a chart per table with the number of rows per parent row (a foreign key) or per value of a column whose values repeat', b ? b.chart === 'true' : true) : ''}`, '', 'aw-pages')}
362
376
  ${region('Features', html`<div class="aw-features">${FEATURES.map(([k, label, help]) => check(`f_${k}`, label, features[k], help))}</div>`)}
363
377
  ${region('Settings', html`<div class="form-grid">
364
- ${input('alias', 'Alias (URL)', v('alias', known ? await aliasFor(schema) : ''), { required: true, help: 'lowercase, e.g. inventory → /a/inventory' })}
378
+ <div class="field"><label class="label" for="f_alias">Alias (URL)</label>
379
+ <input id="f_alias" name="alias" value="${v('alias', known ? await aliasFor(schema) : '')}" required pattern="[a-z][a-z0-9_\-]*" maxlength="50" data-derive-from="f_name"${b && b.alias ? raw(' data-edited') : ''}>
380
+ <small class="help">lowercase, e.g. inventory → /a/inventory; follows the name until you change it</small></div>
365
381
  ${select('authentication', 'Authentication', v('authentication', 'app_users'), [['app_users', 'App users (login page)'], ['none', 'None (public)']])}
366
382
  ${input('admin_user', 'First user', v('admin_user', ''), { placeholder: 'e.g. your name', help: 'Gets the admin role. An existing account in Users is reused.' })}
367
383
  ${input('admin_password', 'Password', '', { type: 'password', auto: 'new-password', help: 'For a new account; at least 8 characters.' })}
@@ -17,6 +17,8 @@ import { BASE, developer, flash, type Req } from './ui.ts';
17
17
  export const LAYOUT_KINDS = ['region', 'item', 'button'] as const;
18
18
  export type LayoutKind = (typeof LAYOUT_KINDS)[number];
19
19
  const isKind = (k: unknown): k is LayoutKind => (LAYOUT_KINDS as readonly unknown[]).includes(k);
20
+ /** (sprint 90) The components with a build option, which can be commented out. */
21
+ const COMMENTABLE = new Set(['region', 'item', 'button', 'dynamic_action', 'validation', 'process', 'computation', 'branch']);
20
22
 
21
23
  const options = (kind: string, field: string) => COMPONENTS[kind].fields.find((f) => f.name === field)!.options!.filter(Boolean);
22
24
  export const REGION_TYPES = () => options('region', 'type');
@@ -38,22 +40,22 @@ export const BOTTOM_SLOTS = ['previous', 'close', 'delete', 'next'];
38
40
 
39
41
  /** Gallery names and icons. */
40
42
  export const REGION_LABELS: Record<string, [string, string]> = {
41
- report: ['Interactive report', 'table'], grid: ['Interactive grid', 'grid'], form: ['Form', 'file'], chart: ['Chart', 'chart'],
42
- cards: ['Cards', 'layers'], calendar: ['Calendar', 'calendar'], facets: ['Faceted search', 'filter'], smart_filters: ['Smart filters', 'search'], display_selector: ['Region display selector', 'menu'], tasks: ['Task list', 'inbox'],
43
- workflows: ['Workflow console', 'activity'], map: ['Map', 'map'], tree: ['Tree', 'org'], static: ['Static content', 'region'], dynamic: ['Dynamic content', 'code'],
44
- template_component: ['Template component', 'layers'], list: ['List', 'list'], data_reporter: ['Data Reporter', 'table'],
45
- ai_assistant: ['AI assistant', 'bolt'], url: ['URL', 'link'], search: ['Search', 'search'],
43
+ report: ['Interactive Report', 'table'], grid: ['Interactive Grid', 'grid'], form: ['Form', 'file'], chart: ['Chart', 'chart'],
44
+ cards: ['Cards', 'layers'], calendar: ['Calendar', 'calendar'], facets: ['Faceted Search', 'filter'], smart_filters: ['Smart Filters', 'search'], display_selector: ['Region Display Selector', 'menu'], tasks: ['Task List', 'inbox'],
45
+ workflows: ['Workflow Console', 'activity'], map: ['Map', 'map'], tree: ['Tree', 'org'], static: ['Static Content', 'region'], dynamic: ['Dynamic Content', 'code'],
46
+ template_component: ['Template Component', 'layers'], list: ['List', 'list'], data_reporter: ['Data Reporter', 'table'], form_designer: ['Form Designer', 'file'],
47
+ ai_assistant: ['AI Assistant', 'bolt'], url: ['URL', 'link'], search: ['Search', 'search'], login: ['Login', 'lock'], plugin: ['Plug-in', 'layers'],
46
48
  };
47
49
  export const ITEM_LABELS: Record<string, [string, string]> = {
48
- text: ['Text field', 'item'], textarea: ['Text area', 'item'], number: ['Number field', 'item'], date: ['Date picker', 'calendar'],
49
- datetime: ['Date and time', 'clock'], select: ['Select list', 'list'], popup_lov: ['Popup LOV', 'search'], radio: ['Radio group', 'check'],
50
- checkbox: ['Checkbox', 'check'], switch: ['Switch', 'check'], checkbox_group: ['Checkbox group', 'check'], multiselect: ['Multi select', 'list'],
51
- email: ['E-mail', 'inbox'], tel: ['Phone number', 'item'], url: ['URL', 'item'], color: ['Color picker', 'item'], file: ['File upload', 'upload'],
52
- location: ['Location', 'map'], richtext: ['Rich text editor', 'edit'], markdown: ['Markdown editor', 'code'], rating: ['Star rating', 'check'],
53
- combobox: ['Combobox (tags)', 'list'], daterange: ['Date range', 'calendar'], qrcode: ['QR code', 'scan'], image: ['Display image', 'file'], address: ['Geocoded address', 'map'], hidden: ['Hidden', 'item'], display: ['Display only', 'file'], password: ['Password', 'key'],
50
+ text: ['Text Field', 'item'], textarea: ['Text Area', 'item'], number: ['Number Field', 'item'], date: ['Date Picker', 'calendar'],
51
+ datetime: ['Date and Time', 'clock'], select: ['Select List', 'list'], popup_lov: ['Popup LOV', 'search'], radio: ['Radio Group', 'check'],
52
+ checkbox: ['Checkbox', 'check'], switch: ['Switch', 'check'], checkbox_group: ['Checkbox Group', 'check'], multiselect: ['Multi Select', 'list'],
53
+ email: ['E-mail', 'inbox'], tel: ['Phone Number', 'item'], url: ['URL', 'item'], color: ['Color Picker', 'item'], file: ['File Upload', 'upload'],
54
+ location: ['Location', 'map'], richtext: ['Rich Text Editor', 'edit'], markdown: ['Markdown Editor', 'code'], rating: ['Star Rating', 'check'],
55
+ combobox: ['Combobox (Tags)', 'list'], daterange: ['Date Range', 'calendar'], qrcode: ['QR Code', 'scan'], image: ['Display Image', 'file'], address: ['Geocoded Address', 'map'], hidden: ['Hidden', 'item'], display: ['Display Only', 'file'], password: ['Password', 'key'],
54
56
  };
55
57
  export const BUTTON_LABELS: Record<string, [string, string]> = {
56
- submit: ['Submit page', 'button'], redirect: ['Redirect to page', 'button'], da: ['Dynamic action', 'bolt'], document: ['Download document', 'download'],
58
+ submit: ['Submit Page', 'button'], redirect: ['Redirect to Page', 'button'], da: ['Dynamic Action', 'bolt'], document: ['Download Document', 'download'],
57
59
  };
58
60
 
59
61
  /** A working starting point per region type, so a new region renders straight away. */
@@ -351,6 +353,25 @@ export async function arrangeRoutes(app: FastifyInstance) {
351
353
  });
352
354
 
353
355
  // (sprint 77) the rendering tree's menu: Duplicate, Copy to other Page
356
+ // (sprint 90, PD-4; APEX: Comment Out) a component left out of the page by the build option COMMENTED_OUT (made with
357
+ // the status Exclude when first needed); Uncomment takes it off again. Not a layout change: the undo history stays.
358
+ route('comment', async (_s, pid, b) => {
359
+ const kind = b.kind ?? '';
360
+ const id = int(b.id);
361
+ if (!COMMENTABLE.has(kind) || id === null) throw new LayoutError(400, 'Unknown component.');
362
+ const on = b.on !== 'false';
363
+ const done = await owner.tx(async (c) => {
364
+ if (on)
365
+ await c.query(
366
+ `insert into meta.build_option (app_id, name, status, description)
367
+ select app_id, 'COMMENTED_OUT', 'exclude', 'Components commented out in the page designer' from meta.page where id = $1
368
+ on conflict (app_id, name) do nothing`, [pid]);
369
+ return (await c.query(`update ${COMPONENTS[kind].table} set build_option = $3 where id = $1 and page_id = $2 and ${on ? 'true' : `build_option = 'COMMENTED_OUT'`}`, [id, pid, on ? 'COMMENTED_OUT' : null])).rowCount;
370
+ });
371
+ if (!done) throw new LayoutError(404, 'Unknown component.');
372
+ return { sel: `${kind}-${id}`, message: `${COMPONENTS[kind].label} ${on ? 'commented out: it stays in the page designer and is left out of the page (build option COMMENTED_OUT)' : 'back on the page'}.` };
373
+ });
374
+
354
375
  route('duplicate', async (s, pid, b) => {
355
376
  const kind = b.kind;
356
377
  const id = int(b.id);
@@ -39,7 +39,7 @@ const CHECKS: Record<string, SqlShape> = {
39
39
  const CHECK_SWITCH: Record<string, string> = {
40
40
  'dynamic_action.code': 'action:set_value=select,*=statements',
41
41
  'process.code': 'type:sql=statements,*=none',
42
- 'region.source': 'type:static=none,form=none,facets=none,smart_filters=none,display_selector=none,tasks=none,workflows=none,list=none,data_reporter=none,ai_assistant=none,*=select',
42
+ 'region.source': 'type:static=none,form=none,facets=none,smart_filters=none,display_selector=none,tasks=none,workflows=none,list=none,data_reporter=none,form_designer=none,ai_assistant=none,*=select',
43
43
  'computation.expression': 'type:sql_query=select,*=none',
44
44
  'app_computation.expression': 'type:sql_query=select,*=none',
45
45
  'computation.condition_expr': 'condition_type:sql=boolean,exists=select,not_exists=select,*=none',
@@ -107,7 +107,7 @@ export const COMPONENTS: Record<string, ComponentSpec> = {
107
107
  { name: 'title', common: true, label: 'Title', kind: 'text', group: 'Identification' },
108
108
  { name: 'static_id', label: 'Static ID', kind: 'text', group: 'Identification',
109
109
  help: 'Optional, unique on the page: lower case letters, digits, _ and -, starting with a letter. Names the region in exported files (so renaming it keeps them) and is data-static-id on the page, for CSS and JavaScript.' },
110
- { name: 'type', common: true, label: 'Type', kind: 'select', options: ['report', 'grid', 'form', 'login', 'chart', 'cards', 'calendar', 'facets', 'smart_filters', 'display_selector', 'tasks', 'workflows', 'map', 'tree', 'template_component', 'list', 'static', 'dynamic', 'data_reporter', 'ai_assistant', 'plugin', 'url', 'search'], group: 'Identification' },
110
+ { name: 'type', common: true, label: 'Type', kind: 'select', options: ['report', 'grid', 'form', 'login', 'chart', 'cards', 'calendar', 'facets', 'smart_filters', 'display_selector', 'tasks', 'workflows', 'map', 'tree', 'template_component', 'list', 'static', 'dynamic', 'data_reporter', 'form_designer', 'ai_assistant', 'plugin', 'url', 'search'], group: 'Identification' },
111
111
  { name: 'source', common: true, label: 'Source', kind: 'code', wide: true, group: 'Source',
112
112
  help: 'report/grid: a SELECT (use :ITEM binds) · chart: label column + one numeric column per series · cards: title, subtitle, body, badge, icon · calendar: start_date, end_date, title · map: lat and lng (or location "lat,lng"), title, body, geojson · tree: id, parent_id, label, icon · template_component: any SELECT (its columns are #COLUMN# in the template), or empty for one instance · dynamic: a SELECT returning HTML (escape with meta.html_escape) · static: HTML with &ITEM. substitutions · url: the page to show, https://host/path?q=&P1_ITEM. (the host is written out; items are URL-encoded) or a path on this server (/a/other/1).' },
113
113
  { name: 'rest_source', label: 'REST data source', kind: 'rest_source', group: 'Source',
@@ -1,9 +1,11 @@
1
- import type { FastifyInstance } from 'fastify';
1
+ import type { FastifyInstance, FastifyReply } from 'fastify';
2
2
  import { owner } from '../db.ts';
3
3
  import { html, raw, type Raw } from '../html.ts';
4
4
  import { icon } from '../icons.ts';
5
5
  import { COMPONENTS } from './components.ts';
6
- import { back, BASE, bicon, csrf, developer, flash, input, select, send, shell, type Req } from './ui.ts';
6
+ import { back, BASE, bicon, csrf, designerUrl, developer, flash, input, select, send, shell, type Req } from './ui.ts';
7
+ import { wantsHtml } from './errors.ts';
8
+ import type { Session } from '../session.ts';
7
9
  import { buildOptionChoices, componentForm, lookups, saveComponent } from './forms.ts';
8
10
  import { regionConfigHelp } from './region-help.ts';
9
11
  import { parseIncludes } from './static-files.ts';
@@ -47,16 +49,35 @@ export async function designerRoutes(app: FastifyInstance) {
47
49
  const appId = /^\d{1,9}$/.test(req.params.id) ? Number(req.params.id) : null;
48
50
  const no = /^\d{1,9}$/.test(req.query.page ?? '') ? Number(req.query.page) : -1;
49
51
  const p = appId === null ? null : await owner.one('select id from meta.page where app_id = $1 and page_no = $2', [appId, no]);
50
- if (p) return reply.redirect(`${BASE}/pages/${p.id}`, 303);
52
+ if (p) return reply.redirect(designerUrl(appId!, no), 303);
51
53
  flash(s, `There is no page ${req.query.page ?? ''}.`, 'error');
52
54
  return back(reply, s, appId === null ? BASE : `${BASE}/apps/${appId}`);
53
55
  });
54
56
 
55
57
  // ---------------------------------------------------------------- page designer
58
+ // (sprint 86) its address is the application's id and the page's number; a browser that opens the
59
+ // internal id (an old bookmark, a redirect after saving) is sent there with the same query
60
+ app.get(`${BASE}/apps/:app/pages/:no`, async (req: Req, reply) => {
61
+ const s = await developer(req, reply);
62
+ if (!s) return;
63
+ const page = /^\d{1,9}$/.test(req.params.app) && /^\d{1,9}$/.test(req.params.no)
64
+ ? await owner.one<{ id: number }>('select id from meta.page where app_id = $1 and page_no = $2', [req.params.app, req.params.no])
65
+ : undefined;
66
+ if (!page) return reply.code(404).send('Not found');
67
+ return pageDesigner(req, reply, s, page.id);
68
+ });
56
69
  app.get(`${BASE}/pages/:pid`, async (req: Req, reply) => {
57
70
  const s = await developer(req, reply);
58
71
  if (!s) return;
59
- const p = await owner.one('select p.*, a.alias, a.name as app_name from meta.page p join meta.app a on a.id = p.app_id where p.id = $1', [req.params.pid]);
72
+ if (wantsHtml(req) && /^\d{1,9}$/.test(req.params.pid)) {
73
+ const p = await owner.one<{ app_id: number; page_no: number }>('select app_id, page_no from meta.page where id = $1', [req.params.pid]);
74
+ if (p) return reply.redirect(designerUrl(p.app_id, p.page_no, req.url.split('?')[1] ?? ''), 302);
75
+ }
76
+ return pageDesigner(req, reply, s, req.params.pid);
77
+ });
78
+
79
+ async function pageDesigner(req: Req, reply: FastifyReply, s: Session, pid: number | string) {
80
+ const p = await owner.one('select p.*, a.alias, a.name as app_name from meta.page p join meta.app a on a.id = p.app_id where p.id = $1', [pid]);
60
81
  if (!p) return reply.code(404).send('Not found');
61
82
  const rows: Record<string, any[]> = {};
62
83
  for (const kind of PAGE_KINDS) rows[kind] = (await owner.query(`select * from ${COMPONENTS[kind].table} where page_id = $1 order by seq, id`, [p.id])).rows;
@@ -73,7 +94,9 @@ export async function designerRoutes(app: FastifyInstance) {
73
94
  const sel = req.query.c ?? '';
74
95
  const newKind = PAGE_KINDS.includes(req.query.new ?? '') ? req.query.new : '';
75
96
  const [kind, cid] = sel.split('-');
76
- const url = (q: string) => `${BASE}/pages/${p.id}${q ? `?${q}` : ''}`;
97
+ const url = (q: string) => designerUrl(p.app_id, p.page_no, q);
98
+ // the page's forms post to its internal id (a page number can change)
99
+ const post = `${BASE}/pages/${p.id}`;
77
100
  const isSel = (key: string) => sel === key || (key === 'page' && !sel && !newKind);
78
101
  const cur = (key: string) => (isSel(key) ? raw(' aria-current="true"') : '');
79
102
  const badges = (r: any) => html`${r.authz ? html`<span class="pd-tag" title="Authorization: ${r.authz}">${icon('shield')}<span class="sr-only">Authorization ${r.authz}</span></span>` : ''}${r.condition || r.readonly_condition || r.condition_type ? html`<span class="pd-tag" title="Has a condition">${icon('filter')}<span class="sr-only">Has a condition</span></span>` : ''}${r.build_option ? html`<span class="pd-tag" title="Build option: ${r.build_option}">${icon('settings')}<span class="sr-only">Build option ${r.build_option}</span></span>` : ''}`;
@@ -81,8 +104,10 @@ export async function designerRoutes(app: FastifyInstance) {
81
104
 
82
105
  // ------------------------------------------------------------ left: component tree
83
106
  // (sprint 77) data-kind and data-id: the node's context menu (Duplicate, Copy to other page, Delete…) and icon colour
107
+ // (sprint 90) a commented-out component: struck through in the tree, Uncomment in its menu
108
+ const commented = (r: any) => (r.build_option === 'COMMENTED_OUT' ? raw(' data-commented') : '');
84
109
  const leaf = (k: string, r: any, ic: Raw | '', label: string, note = '') =>
85
- html`<li><a class="pd-node" href="${url(`c=${k}-${r.id}`)}"${cur(`${k}-${r.id}`)} data-kind="${k}" data-id="${r.id}">${ic}<span class="pd-label">${label}</span>${badges(r)}${note ? html`<span class="pd-note">${note}</span>` : ''}</a></li>`;
110
+ html`<li><a class="pd-node" href="${url(`c=${k}-${r.id}`)}"${cur(`${k}-${r.id}`)} data-kind="${k}" data-id="${r.id}"${commented(r)}>${ic}<span class="pd-label">${label}</span>${badges(r)}${note ? html`<span class="pd-note">${note}</span>` : ''}</a></li>`;
86
111
  const folder = (label: string, children: Raw[] | Raw, open = true) =>
87
112
  html`<li${open ? '' : raw(' data-collapsed')}><span class="pd-node pd-folder"><span class="pd-label">${label}</span></span><ul>${children}</ul></li>`;
88
113
  const none = (text: string) => html`<li class="pd-empty">${text}</li>`;
@@ -95,7 +120,7 @@ export async function designerRoutes(app: FastifyInstance) {
95
120
  const bySlot = ['region', ...TOP_SLOTS, ...BOTTOM_SLOTS].map((sl) => [sl, buttons.filter((b) => (b.slot ?? 'region') === sl)] as const).filter(([, list]) => list.length);
96
121
  const kids = [...(items.length ? [folder('Items', items.map(itemLeaf))] : []),
97
122
  ...bySlot.map(([sl, list]) => folder(sl === 'region' ? 'Buttons' : `Buttons: ${SLOT_LABELS[sl]}`, list.map(buttonLeaf)))];
98
- return html`<li><a class="pd-node" href="${url(`c=region-${r.id}`)}"${cur(`region-${r.id}`)} data-kind="region" data-id="${r.id}" data-position="${r.position ?? ''}" data-next="${next?.id ?? ''}">${bicon(regionIcon(r.type))}<span class="pd-label">${regionTitle(r)}</span>${badges(r)}<span class="pd-note">${r.type}</span></a>${kids.length ? html`<ul>${kids}</ul>` : ''}</li>`;
123
+ return html`<li><a class="pd-node" href="${url(`c=region-${r.id}`)}"${cur(`region-${r.id}`)} data-kind="region" data-id="${r.id}" data-position="${r.position ?? ''}" data-next="${next?.id ?? ''}"${commented(r)}>${bicon(regionIcon(r.type))}<span class="pd-label">${regionTitle(r)}</span>${badges(r)}<span class="pd-note">${r.type}</span></a>${kids.length ? html`<ul>${kids}</ul>` : ''}</li>`;
99
124
  };
100
125
  // (sprint 77, APEX: the rendering tree by display position) the page template's positions, and others in use
101
126
  const treeSide = p.page_template === 'left_side_column' ? 'left' : p.page_template === 'right_side_column' ? 'right' : null;
@@ -129,7 +154,7 @@ export async function designerRoutes(app: FastifyInstance) {
129
154
  </ul></li>
130
155
  </ul>
131
156
  <dialog class="pd-dialog" id="pd-copy-dialog" aria-labelledby="pd-copy-title">
132
- <form method="post" action="${url('')}/layout/copy">${csrf(s)}<input type="hidden" name="kind" value=""><input type="hidden" name="id" value="">
157
+ <form method="post" action="${post}/layout/copy">${csrf(s)}<input type="hidden" name="kind" value=""><input type="hidden" name="id" value="">
133
158
  <h2 id="pd-copy-title">Copy to other page</h2>
134
159
  <p class="muted" data-copy-what></p>
135
160
  <div class="field"><label class="label" for="pd-copy-page">Page</label>
@@ -226,7 +251,7 @@ export async function designerRoutes(app: FastifyInstance) {
226
251
  ${side === 'left' || extra('left') ? zone('left') : ''}${zone('body')}${side === 'right' || extra('right') ? zone('right') : ''}
227
252
  </div>${zone('footer')}`;
228
253
  const gallery = (k: 'region' | 'item' | 'button', types: string[], labels: Record<string, [string, string]>) =>
229
- html`<ul class="pd-gallery-list" aria-label="${COMPONENTS[k].plural}">${types.map((t) => html`<li><a class="pd-gal" href="${url(`new=${k}&type=${t}`)}" draggable="true" data-new="${k}" data-type="${t}" title="Drag onto the layout, or open to create">${bicon(labels[t]?.[1] ?? k)}<span>${labels[t]?.[0] ?? t}</span></a></li>`)}</ul>`;
254
+ html`<ul class="pd-gallery-list" aria-label="${COMPONENTS[k].plural}">${types.map((t) => html`<li><a class="pd-gal" href="${url(`new=${k}&type=${t}`)}" draggable="true" data-new="${k}" data-type="${t}" title="${labels[t]?.[0] ?? t}: drag onto the layout, or open to create">${bicon(labels[t]?.[1] ?? k)}<span>${labels[t]?.[0] ?? t}</span></a></li>`)}</ul>`;
230
255
  const layout = html`
231
256
  <div class="pd-canvas-bar" role="toolbar" aria-label="Layout">
232
257
  <button type="button" class="tb-btn" data-zoom="-1" title="Zoom out" hidden>${bicon('zoom-out')}<span class="sr-only">Zoom out</span></button>
@@ -294,7 +319,7 @@ export async function designerRoutes(app: FastifyInstance) {
294
319
  let hasForm = true;
295
320
  const peTabs = (panels: Raw[]) => html`<div class="pd-tabs" data-tabs="pd-right" data-tabs-remember aria-label="Properties">${panels}</div>`;
296
321
  const moveForm = (k: string, id: number, fields: Raw, button: Raw, title: string) =>
297
- html`<form method="post" action="${url('')}/layout/move" class="pe-arrange-form">${csrf(s)}<input type="hidden" name="kind" value="${k}"><input type="hidden" name="id" value="${id}">${fields}<button class="tb-btn" title="${title}">${button}</button></form>`;
322
+ html`<form method="post" action="${post}/layout/move" class="pe-arrange-form">${csrf(s)}<input type="hidden" name="kind" value="${k}"><input type="hidden" name="id" value="${id}">${fields}<button class="tb-btn" title="${title}">${button}</button></form>`;
298
323
  if (newKind) {
299
324
  const spec = COMPONENTS[newKind];
300
325
  const lastSeq = Math.max(0, ...rows[newKind].map((r) => r.seq));
@@ -325,9 +350,9 @@ export async function designerRoutes(app: FastifyInstance) {
325
350
  ${moveForm(kind, row.id, html`<input type="hidden" name="dir" value="up">`, html`${bicon('arrow-up')}<span class="sr-only">Move up</span>`, 'Move up (earlier in the sequence)')}
326
351
  ${moveForm(kind, row.id, html`<input type="hidden" name="dir" value="down">`, html`${bicon('arrow-down')}<span class="sr-only">Move down</span>`, 'Move down (later in the sequence)')}
327
352
  ${kind === 'region'
328
- ? html`<form method="post" action="${url('')}/layout/span" class="pe-arrange-form">${csrf(s)}<input type="hidden" name="id" value="${row.id}"><input type="hidden" name="delta" value="-1"><button class="tb-btn" title="Narrower (one column less)"${row.columns <= 1 ? raw(' disabled') : ''}>${bicon('narrow')}<span class="sr-only">Narrower</span></button></form>
353
+ ? html`<form method="post" action="${post}/layout/span" class="pe-arrange-form">${csrf(s)}<input type="hidden" name="id" value="${row.id}"><input type="hidden" name="delta" value="-1"><button class="tb-btn" title="Narrower (one column less)"${row.columns <= 1 ? raw(' disabled') : ''}>${bicon('narrow')}<span class="sr-only">Narrower</span></button></form>
329
354
  <span class="pe-span" title="Column span">${row.columns}/12</span>
330
- <form method="post" action="${url('')}/layout/span" class="pe-arrange-form">${csrf(s)}<input type="hidden" name="id" value="${row.id}"><input type="hidden" name="delta" value="1"><button class="tb-btn" title="Wider (one column more)"${row.columns >= 12 ? raw(' disabled') : ''}>${bicon('wide')}<span class="sr-only">Wider</span></button></form>`
355
+ <form method="post" action="${post}/layout/span" class="pe-arrange-form">${csrf(s)}<input type="hidden" name="id" value="${row.id}"><input type="hidden" name="delta" value="1"><button class="tb-btn" title="Wider (one column more)"${row.columns >= 12 ? raw(' disabled') : ''}>${bicon('wide')}<span class="sr-only">Wider</span></button></form>`
331
356
  : moveForm(kind, row.id, html`<label class="sr-only" for="pe-move-region">Move to region</label><select id="pe-move-region" name="region">${regionOptions}</select>`, html`<span>Move</span>`, 'Move to the end of this region')}
332
357
  </div>`;
333
358
  }
@@ -395,7 +420,7 @@ export async function designerRoutes(app: FastifyInstance) {
395
420
  const next = pages[idx + 1];
396
421
  const h = undoState(s, p.id);
397
422
  const tbForm = (op: string, ic: string, label: string, title: string | null) =>
398
- html`<form method="post" action="${url('')}/layout/${op}" class="tb-form">${csrf(s)}<button class="tb-btn" title="${title ? `${label}: ${title}` : `Nothing to ${label.toLowerCase()}`}"${title ? '' : raw(' disabled')}>${bicon(ic)}<span class="sr-only">${label}</span></button></form>`;
423
+ html`<form method="post" action="${post}/layout/${op}" class="tb-form">${csrf(s)}<button class="tb-btn" title="${title ? `${label}: ${title}` : `Nothing to ${label.toLowerCase()}`}"${title ? '' : raw(' disabled')}>${bicon(ic)}<span class="sr-only">${label}</span></button></form>`;
399
424
  const createMenu = html`<details class="menu tb-menu">
400
425
  <summary class="tb-btn" title="Create">${icon('plus')}${bicon('down', 'icon tb-caret')}<span class="sr-only">Create</span></summary>
401
426
  <div class="menu-panel align-right"><div class="menu-section menu-links">
@@ -415,7 +440,7 @@ export async function designerRoutes(app: FastifyInstance) {
415
440
  </div></div></details>`;
416
441
  const toolbar = html`
417
442
  <div class="tb-group pd-pagenav" role="group" aria-label="Page">
418
- ${prev ? html`<a class="tb-btn" href="${BASE}/pages/${prev.id}" title="Previous page: ${prev.page_no}. ${prev.name}">${bicon('left')}<span class="sr-only">Previous page</span></a>` : html`<span class="tb-btn" aria-disabled="true">${bicon('left')}</span>`}
443
+ ${prev ? html`<a class="tb-btn" href="${designerUrl(p.app_id, prev.page_no)}" title="Previous page: ${prev.page_no}. ${prev.name}">${bicon('left')}<span class="sr-only">Previous page</span></a>` : html`<span class="tb-btn" aria-disabled="true">${bicon('left')}</span>`}
419
444
  <form method="get" action="${BASE}/apps/${p.app_id}/goto" class="tb-form pd-goto-no">
420
445
  <label class="sr-only" for="pd-goto-no">Page number (Enter goes there)</label>
421
446
  <input id="pd-goto-no" name="page" type="number" min="0" max="999999999" step="1" value="${p.page_no}" inputmode="numeric" title="Page number: type or step to a number, then Enter">
@@ -425,7 +450,7 @@ export async function designerRoutes(app: FastifyInstance) {
425
450
  <select id="pd-goto" name="page" data-autosubmit>${pages.map((x) => html`<option value="${x.page_no}"${x.id === p.id ? raw(' selected') : ''}>${x.page_no} · ${x.name}</option>`)}</select>
426
451
  <button class="tb-btn tb-text pd-goto-go">Go</button>
427
452
  </form>
428
- ${next ? html`<a class="tb-btn" href="${BASE}/pages/${next.id}" title="Next page: ${next.page_no}. ${next.name}">${bicon('right')}<span class="sr-only">Next page</span></a>` : html`<span class="tb-btn" aria-disabled="true">${bicon('right')}</span>`}
453
+ ${next ? html`<a class="tb-btn" href="${designerUrl(p.app_id, next.page_no)}" title="Next page: ${next.page_no}. ${next.name}">${bicon('right')}<span class="sr-only">Next page</span></a>` : html`<span class="tb-btn" aria-disabled="true">${bicon('right')}</span>`}
429
454
  </div>
430
455
  <div class="tb-group tb-undo" role="group" aria-label="History">${tbForm('undo', 'undo', 'Undo', h.undo)}${tbForm('redo', 'redo', 'Redo', h.redo)}</div>
431
456
  <div class="tb-group tb-menus">${createMenu}${utilMenu}</div>
@@ -442,7 +467,7 @@ export async function designerRoutes(app: FastifyInstance) {
442
467
  <section class="pd-pane pd-right tab-panel" id="pd-p-props" data-tab${pane === 'pd-p-props' ? raw(' data-tab-active') : ''}><h2 class="tab-title pd-pane-title"><span>Properties</span></h2>${right}</section>
443
468
  </div>`;
444
469
  return send(reply, s, shell(s, `Page ${p.page_no}`, [['App Builder', BASE], [p.app_name, `${BASE}/apps/${p.app_id}`], [`Page ${p.page_no}: ${p.name}`]], main, 'apps', { toolbar, full: true }));
445
- });
470
+ }
446
471
 
447
472
  // (sprint 59) Quick edit from the developer toolbar: an item or button of the page by its name
448
473
  app.get(`${BASE}/pages/:pid/quick`, async (req: Req, reply) => {
@@ -452,7 +477,9 @@ export async function designerRoutes(app: FastifyInstance) {
452
477
  const q = req.query ?? {};
453
478
  const [kind, table, name] = q.item ? ['item', 'meta.item', String(q.item).toUpperCase()] : q.button ? ['button', 'meta.button', String(q.button).toUpperCase()] : [null, null, null];
454
479
  const row = kind ? await owner.one(`select id from ${table} where page_id = $1 and name = $2 order by id limit 1`, [req.params.pid, name]) : null;
455
- return reply.redirect(`${BASE}/pages/${req.params.pid}${row ? `?c=${kind}-${row.id}` : ''}`);
480
+ const page = await owner.one<{ app_id: number; page_no: number }>('select app_id, page_no from meta.page where id = $1', [req.params.pid]);
481
+ if (!page) return reply.code(404).send('Not found');
482
+ return reply.redirect(designerUrl(page.app_id, page.page_no, row ? `c=${kind}-${row.id}` : ''));
456
483
  });
457
484
 
458
485
  app.post(`${BASE}/pages/:pid`, async (req: Req, reply) => {
@@ -0,0 +1,65 @@
1
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
2
+ import { html } from '../html.ts';
3
+ import { documentShell } from '../layout.ts';
4
+ import { BASE, THEME_COOKIE, validTheme } from './ui.ts';
5
+
6
+ // (sprint 86) The builder's error pages: a browser that opens an address under /builder that
7
+ // doesn't exist (or an application or page that doesn't, or not for this developer), or that
8
+ // meets a server error, gets an HTML page in the builder's theme with a way back, instead of
9
+ // JSON or plain text. Requests from scripts (fetch, the layout canvas) keep their plain answers.
10
+
11
+ /** A browser's navigation (it asks for HTML), not a script's request. */
12
+ export const wantsHtml = (req: FastifyRequest) =>
13
+ (req.method === 'GET' || req.method === 'HEAD') && /\btext\/html\b/.test(String(req.headers.accept ?? '')) && req.headers['x-requested-with'] === undefined;
14
+
15
+ const isBuilder = (url: string) => url === BASE || url.startsWith(`${BASE}/`) || url.startsWith(`${BASE}?`);
16
+
17
+ const TEXTS: Record<number, { title: string; text: string }> = {
18
+ 404: { title: 'Page not found', text: 'There is nothing at this address in the App Builder. The application or page may have been deleted, or belongs to a workspace you are not a member of.' },
19
+ 500: { title: 'Something went wrong', text: 'The App Builder could not show this page because of an error on the server. It has been logged; try again, or go back.' },
20
+ };
21
+
22
+ /** The error page for a status (404, or 500 for any server error). */
23
+ export function builderErrorPage(req: FastifyRequest, status: number) {
24
+ const { title, text } = TEXTS[status >= 500 ? 500 : 404];
25
+ const theme = validTheme((req.cookies as Record<string, string> | undefined)?.[THEME_COOKIE]) ?? 'auto';
26
+ return documentShell(
27
+ `${title} · App Builder`,
28
+ html`<main class="t-error" id="main"><div class="card"><h1>${title}</h1><p>${text}</p>
29
+ <p class="muted">${status >= 500 ? 'Error' : 'Not found'}: <code>${req.url.split('?')[0].slice(0, 200)}</code></p>
30
+ <p><a class="btn btn-hot" href="${BASE}">App Builder home</a></p></div></main>`,
31
+ 'login-body',
32
+ {},
33
+ '',
34
+ { theme },
35
+ );
36
+ }
37
+
38
+ const sendPage = (req: FastifyRequest, reply: FastifyReply, status: number) =>
39
+ reply.code(status).type('text/html; charset=utf-8').header('cache-control', 'no-store').send(builderErrorPage(req, status));
40
+
41
+ /**
42
+ * The hooks (registered on the root instance): unknown builder addresses, the builder's own
43
+ * "Not found" answers and server errors become HTML pages for browsers.
44
+ */
45
+ export function builderErrorPages(app: FastifyInstance) {
46
+ app.setNotFoundHandler((req, reply) => {
47
+ if (isBuilder(req.url) && wantsHtml(req)) return sendPage(req, reply, 404);
48
+ return reply.code(404).send({ message: `Route ${req.method}:${req.url} not found`, error: 'Not Found', statusCode: 404 });
49
+ });
50
+ // a route's own plain "Not found" (an id that doesn't exist, another workspace's application)
51
+ app.addHook('onSend', async (req, reply, payload) => {
52
+ if (reply.statusCode !== 404 || !isBuilder(req.url) || !wantsHtml(req)) return payload;
53
+ if (!/^text\/plain\b/.test(String(reply.getHeader('content-type') ?? ''))) return payload;
54
+ reply.type('text/html; charset=utf-8');
55
+ return builderErrorPage(req, 404);
56
+ });
57
+ }
58
+
59
+ /** For the root error handler: a server error on a builder page a browser opened, as HTML (true: sent). */
60
+ export function builderServerError(req: FastifyRequest, reply: FastifyReply, err: Error & { statusCode?: number }) {
61
+ if (!isBuilder(req.url) || !wantsHtml(req) || (err.statusCode !== undefined && err.statusCode < 500)) return false;
62
+ req.log.error(err);
63
+ sendPage(req, reply, 500);
64
+ return true;
65
+ }