@crombolo/server 0.60.0 → 0.62.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.
@@ -28,7 +28,8 @@ import {
28
28
  import type { ExtensionDescription } from '@crombolo/extension/runner'
29
29
  import { RawHtml } from '@crombolo/render'
30
30
  import type { Kysely } from 'kysely'
31
- import type { BundleLog, ServerBundle } from './bundles.ts'
31
+ import type { BundleCaller, BundleLog, ServerBundle } from './bundles.ts'
32
+ import { type ActivityRecorder, personOf, timed } from './extension-activity.ts'
32
33
  import { extensionSqlProblem } from './extension-sql.ts'
33
34
 
34
35
  /** The Deno binary the `deno` package installed for this platform, or `CROMBOLO_DENO`. */
@@ -66,7 +67,8 @@ export async function buildExtension(
66
67
  siteDir: string,
67
68
  outDir: string,
68
69
  ): Promise<string> {
69
- const entryFile = Bun.resolveSync(pkg.packageName, siteDir)
70
+ // From its own root when it has one (story 326), so its dependencies resolve from there.
71
+ const entryFile = Bun.resolveSync(pkg.packageName, pkg.root ?? siteDir)
70
72
  // As the build sees it: a workspace link resolves to its real place.
71
73
  const backOffice = `${join(realpathSync(pkg.directory), BACKOFFICE_DIR)}${sep}`
72
74
  mkdirSync(outDir, { recursive: true })
@@ -232,6 +234,8 @@ export interface ExtensionProcessOptions {
232
234
  /** Stopped after this long without a call, unless it serves routes. */
233
235
  idleMs?: number
234
236
  memoryMb?: number
237
+ /** Where what it does is recorded for the activity view (story 327). */
238
+ activity?: ActivityRecorder
235
239
  }
236
240
 
237
241
  const START_TIMEOUT_MS = 30_000
@@ -254,6 +258,8 @@ export class ExtensionProcess {
254
258
  #lastCrash = 0
255
259
  #idle: ReturnType<typeof setTimeout> | undefined
256
260
  #stderr: string[] = []
261
+ /** Settles once the running process's error output has been read to its end. */
262
+ #errorsRead: Promise<void> = Promise.resolve()
257
263
  #stopped = false
258
264
 
259
265
  constructor(options: ExtensionProcessOptions) {
@@ -319,7 +325,7 @@ export class ExtensionProcess {
319
325
  )
320
326
  this.#child = child
321
327
  this.#stderr = []
322
- this.#readErrors(child.stderr as ReadableStream<Uint8Array>)
328
+ this.#errorsRead = this.#readErrors(child.stderr as ReadableStream<Uint8Array>)
323
329
  const ready = new Promise<void>((resolve, reject) => {
324
330
  this.#replies.set(0, {
325
331
  resolve: (description) => {
@@ -330,6 +336,9 @@ export class ExtensionProcess {
330
336
  })
331
337
  })
332
338
  this.#listen(child)
339
+ // A process that died as it started cannot take its first message. Failing to send it is
340
+ // not the reason to report: `#listen` sees the exit and rejects `ready` with what the
341
+ // extension itself wrote on its way out.
333
342
  this.#send({ t: 'init', settings: this.#options.settings, dialect: this.#options.dialect })
334
343
  const timer = setTimeout(
335
344
  () =>
@@ -352,11 +361,15 @@ export class ExtensionProcess {
352
361
 
353
362
  async #readErrors(stream: ReadableStream<Uint8Array>) {
354
363
  const decoder = new TextDecoder()
355
- for await (const chunk of stream) {
356
- for (const line of decoder.decode(chunk).split('\n').filter(Boolean)) {
357
- this.#stderr.push(line)
358
- if (this.#stderr.length > 20) this.#stderr.shift()
364
+ try {
365
+ for await (const chunk of stream) {
366
+ for (const line of decoder.decode(chunk).split('\n').filter(Boolean)) {
367
+ this.#stderr.push(line)
368
+ if (this.#stderr.length > 20) this.#stderr.shift()
369
+ }
359
370
  }
371
+ } catch {
372
+ // A stream torn down with its process has nothing more to say.
360
373
  }
361
374
  }
362
375
 
@@ -378,6 +391,8 @@ export class ExtensionProcess {
378
391
  this.#kill()
379
392
  }
380
393
  const code = await exited
394
+ // What it wrote on its way out is the reason it stopped: read it all before saying so.
395
+ await Promise.race([this.#errorsRead, Bun.sleep(1000)])
381
396
  if (this.#child !== child) return
382
397
  this.#child = undefined
383
398
  if (!this.#stopped) {
@@ -403,12 +418,24 @@ export class ExtensionProcess {
403
418
  this.#replies.clear()
404
419
  }
405
420
 
421
+ /**
422
+ * Writes a frame to the process. A process that has exited cannot take one, and
423
+ * that is not an error to raise here: `#listen` sees the exit, and rejects every
424
+ * call waiting on it with the extension's own words.
425
+ */
406
426
  #send(frame: Frame) {
407
427
  const child = this.#child
408
428
  if (!child) return
409
429
  const sink = child.stdin as import('bun').FileSink
410
- sink.write(frameBytes(frame))
411
- sink.flush()
430
+ const quiet = (result: unknown) => {
431
+ if (result instanceof Promise) result.catch(() => {})
432
+ }
433
+ try {
434
+ quiet(sink.write(frameBytes(frame)))
435
+ quiet(sink.flush())
436
+ } catch {
437
+ // Its input is closed: the process has gone, or is going.
438
+ }
412
439
  }
413
440
 
414
441
  #kill() {
@@ -716,12 +743,43 @@ export class ExtensionProcess {
716
743
  })
717
744
  const problem = extensionSqlProblem(compiled.sql, this.#options.dialect)
718
745
  if (problem) throw new Error(problem)
719
- return target.executeQuery(compiled)
746
+ const result = await target.executeQuery(compiled)
747
+ // Story 327: the table and how many rows, never the statement or its values.
748
+ const activity = this.#options.activity
749
+ if (activity) {
750
+ const words = compiled.sql.trim().toLowerCase()
751
+ const table = TABLE_OF.exec(compiled.sql)?.[1] ?? null
752
+ const writes = /^(insert|update|delete|replace)\b/.exec(words)?.[1]
753
+ activity.record({
754
+ extensionId: this.id,
755
+ personKey: null,
756
+ personName: null,
757
+ kind: writes ? 'rows' : 'read',
758
+ area: table,
759
+ verb: writes ?? 'select',
760
+ // The rows when the driver says, one statement when it does not.
761
+ count: writes
762
+ ? Number(
763
+ result.numAffectedRows ?? (result as { numChangedRows?: bigint }).numChangedRows ?? 1,
764
+ )
765
+ : 1,
766
+ outcome: 'ok',
767
+ })
768
+ }
769
+ return result
770
+ }
771
+
772
+ /** What it does is recorded, when the site keeps its activity (story 327). */
773
+ get activity(): ActivityRecorder | undefined {
774
+ return this.#options.activity
720
775
  }
721
776
  }
722
777
 
723
778
  const ROLLBACK = Symbol('rollback')
724
779
 
780
+ /** The first table a statement names after `into`, `update` or `from`, quoted or not. */
781
+ const TABLE_OF = /\b(?:into|update|from)\s+["`]?([A-Za-z_][\w.]*)["`]?/i
782
+
725
783
  /**
726
784
  * The extension, as the CMS mounts it: what it described, with each handler
727
785
  * sending its call to the process. The host's checks run on this as they do on
@@ -738,30 +796,41 @@ export function isolatedBundle(process: ExtensionProcess): ServerBundle {
738
796
  const cookies = request.headers.has('cookie')
739
797
  ? [...(context.cookies ?? [])].map(([name, cookie]) => [name, cookie.value])
740
798
  : []
741
- const { value, response } = await process.call(
742
- 'route',
799
+ const { value, response } = await timed(
800
+ process.activity,
743
801
  {
744
- route: index,
745
- method,
746
- cookies,
747
- request: {
748
- url: request.url,
749
- method: request.method,
750
- headers: [...request.headers],
751
- hasBody: request.body !== null,
752
- },
753
- },
754
- {
755
- params: context.params,
756
- url: context.url,
757
- setCookie: context.setCookie,
758
- member: context.member,
759
- signal: context.signal,
760
- bundle: context.bundle,
761
- caller: context.caller,
762
- principal: context.principal,
802
+ extensionId: d.id,
803
+ ...personOf(context.caller as BundleCaller | undefined),
804
+ kind: 'call',
805
+ area: `route ${d.routes[index]?.path ?? index}`,
806
+ verb: method,
763
807
  },
764
- { request },
808
+ () =>
809
+ process.call(
810
+ 'route',
811
+ {
812
+ route: index,
813
+ method,
814
+ cookies,
815
+ request: {
816
+ url: request.url,
817
+ method: request.method,
818
+ headers: [...request.headers],
819
+ hasBody: request.body !== null,
820
+ },
821
+ },
822
+ {
823
+ params: context.params,
824
+ url: context.url,
825
+ setCookie: context.setCookie,
826
+ member: context.member,
827
+ signal: context.signal,
828
+ bundle: context.bundle,
829
+ caller: context.caller,
830
+ principal: context.principal,
831
+ },
832
+ { request },
833
+ ),
765
834
  )
766
835
  return response ?? value
767
836
  }
@@ -818,7 +887,19 @@ export function isolatedBundle(process: ExtensionProcess): ServerBundle {
818
887
  d.events.map((alias) => [
819
888
  alias,
820
889
  async (context: { signal?: AbortSignal }) =>
821
- (await process.call('event', { name: alias }, context)).value as never,
890
+ (
891
+ await timed(
892
+ process.activity,
893
+ {
894
+ extensionId: d.id,
895
+ personKey: null,
896
+ personName: null,
897
+ kind: 'call',
898
+ area: `event ${alias}`,
899
+ },
900
+ () => process.call('event', { name: alias }, context),
901
+ )
902
+ ).value as never,
822
903
  ]),
823
904
  ),
824
905
  }
@@ -829,13 +910,67 @@ export function isolatedBundle(process: ExtensionProcess): ServerBundle {
829
910
  d.jobs.map((name) => [
830
911
  name,
831
912
  async (payload: unknown, context: unknown) =>
832
- (await process.call('job', { name }, { payload, context }, { timeoutMs: null }))
833
- .value,
913
+ (
914
+ await timed(
915
+ process.activity,
916
+ {
917
+ extensionId: d.id,
918
+ personKey: null,
919
+ personName: null,
920
+ kind: 'call',
921
+ area: `job ${name}`,
922
+ },
923
+ () => process.call('job', { name }, { payload, context }, { timeoutMs: null }),
924
+ )
925
+ ).value,
834
926
  ]),
835
927
  ),
836
928
  }
837
929
  : {}),
838
930
  ...(d.schedules ? { schedules: d.schedules as ServerBundle['schedules'] } : {}),
931
+ ...((d.screens ?? []).length > 0
932
+ ? {
933
+ screens: Object.fromEntries(
934
+ (d.screens ?? []).map((screen) => {
935
+ const handler =
936
+ (action?: string) =>
937
+ async (context: { signal?: AbortSignal } & Record<string, unknown>) =>
938
+ (
939
+ await timed(
940
+ process.activity,
941
+ {
942
+ extensionId: d.id,
943
+ ...personOf(context.caller as BundleCaller | undefined),
944
+ kind: 'screen',
945
+ area: screen.id,
946
+ verb: action ?? 'view',
947
+ },
948
+ () =>
949
+ process.call(
950
+ 'screen',
951
+ { screen: screen.id, ...(action ? { action } : {}) },
952
+ {
953
+ bundle: context.bundle,
954
+ caller: context.caller,
955
+ principal: context.principal,
956
+ state: context.state,
957
+ input: context.input,
958
+ signal: context.signal,
959
+ },
960
+ ),
961
+ )
962
+ ).value as never
963
+ return [
964
+ screen.id,
965
+ {
966
+ view: handler(),
967
+ actions: Object.fromEntries(screen.actions.map((name) => [name, handler(name)])),
968
+ },
969
+ ]
970
+ }),
971
+ ) as unknown as ServerBundle['screens'],
972
+ }
973
+ : {}),
839
974
  ...(d.workflows.length > 0
840
975
  ? {
841
976
  forms: {
@@ -0,0 +1,383 @@
1
+ /**
2
+ * What an extension's screen answered, held to the catalogue before it leaves
3
+ * the server (story 323): unknown nodes dropped, every displayed string a
4
+ * string, links kept only to places that cannot run script. The back office
5
+ * renders the result as text, so this is the first of two checks, not the only
6
+ * one. docs/extensions.md, "Screens".
7
+ */
8
+ import type {
9
+ Button,
10
+ Cell,
11
+ Condition,
12
+ Field,
13
+ Node,
14
+ Row,
15
+ Screen,
16
+ ScreenResult,
17
+ ScreenValue,
18
+ ScreenValues,
19
+ Search,
20
+ Tab,
21
+ } from '@crombolo/extension/screens'
22
+
23
+ const NODE_TYPES = new Set([
24
+ 'table',
25
+ 'form',
26
+ 'button',
27
+ 'notice',
28
+ 'problem',
29
+ 'empty',
30
+ 'tabs',
31
+ 'progress',
32
+ ])
33
+ const FIELD_KINDS = new Set([
34
+ 'text',
35
+ 'number',
36
+ 'boolean',
37
+ 'choice',
38
+ 'page',
39
+ 'media',
40
+ 'member',
41
+ 'secret',
42
+ 'list',
43
+ ])
44
+ /** What a list's rows may hold (story 329). */
45
+ const LIST_SUB_KINDS = new Set(['text', 'number', 'boolean', 'choice'])
46
+ const LOOKS = new Set(['primary', 'secondary', 'danger'])
47
+ const TAG_LOOKS = new Set(['default', 'primary', 'secondary', 'positive', 'danger'])
48
+ const LIMIT = { rows: 1000, nodes: 200, fields: 100, text: 10_000 }
49
+
50
+ type Raw = Record<string, unknown>
51
+ const isRecord = (value: unknown): value is Raw =>
52
+ typeof value === 'object' && value !== null && !Array.isArray(value)
53
+
54
+ /** A displayed string: a primitive as text, anything else empty. */
55
+ const text = (value: unknown): string => {
56
+ if (typeof value === 'string') return value.slice(0, LIMIT.text)
57
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value)
58
+ return ''
59
+ }
60
+ const optionalText = (value: unknown): string | undefined =>
61
+ value === undefined || value === null ? undefined : text(value)
62
+ const finite = (value: unknown): number | undefined =>
63
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined
64
+ const list = (value: unknown, max: number): unknown[] =>
65
+ Array.isArray(value) ? value.slice(0, max) : []
66
+
67
+ /** A link the back office may follow: http, https, or a path of its own. */
68
+ export function safeScreenHref(href: unknown): string | undefined {
69
+ if (typeof href !== 'string') return undefined
70
+ const trimmed = href.trim()
71
+ if (/^https?:\/\//i.test(trimmed)) return trimmed
72
+ if (/^section\//.test(trimmed)) return trimmed
73
+ // One slash: a path on this site. Two would be another host.
74
+ if (/^\/(?!\/)/.test(trimmed) && !trimmed.includes('\\')) return trimmed
75
+ return undefined
76
+ }
77
+
78
+ const value = (raw: unknown): ScreenValue | undefined => {
79
+ if (raw === null) return null
80
+ if (typeof raw === 'string') return raw.slice(0, LIMIT.text)
81
+ if (typeof raw === 'number') return Number.isFinite(raw) ? raw : undefined
82
+ if (typeof raw === 'boolean') return raw
83
+ if (Array.isArray(raw)) {
84
+ if (raw.every((item) => typeof item === 'string')) return raw as string[]
85
+ // A list field's rows: plain objects of primitives, nothing deeper.
86
+ return raw.slice(0, LIMIT.rows).flatMap((item) => {
87
+ if (!isRecord(item)) return []
88
+ const row: Record<string, string | number | boolean | null> = {}
89
+ for (const [key, cell] of Object.entries(item).slice(0, LIMIT.fields))
90
+ if (
91
+ cell === null ||
92
+ typeof cell === 'string' ||
93
+ typeof cell === 'boolean' ||
94
+ (typeof cell === 'number' && Number.isFinite(cell))
95
+ )
96
+ row[key] = typeof cell === 'string' ? cell.slice(0, LIMIT.text) : cell
97
+ return [row]
98
+ })
99
+ }
100
+ return undefined
101
+ }
102
+
103
+ /** A plain object of values, as a form holds and an action is sent. */
104
+ export function screenValues(raw: unknown): ScreenValues {
105
+ if (!isRecord(raw)) return {}
106
+ const out: Record<string, ScreenValue> = {}
107
+ for (const [key, entry] of Object.entries(raw).slice(0, LIMIT.fields)) {
108
+ const kept = value(entry)
109
+ if (kept !== undefined) out[key] = kept
110
+ }
111
+ return out
112
+ }
113
+
114
+ const condition = (raw: unknown): Condition | undefined => {
115
+ if (!isRecord(raw) || typeof raw.field !== 'string') return undefined
116
+ const out: Condition = { field: raw.field }
117
+ const equals = value(raw.equals)
118
+ if (raw.equals !== undefined && equals !== undefined) out.equals = equals
119
+ if (Array.isArray(raw.oneOf))
120
+ out.oneOf = raw.oneOf.map(value).filter((v): v is ScreenValue => v !== undefined)
121
+ if (raw.notEmpty === true) out.notEmpty = true
122
+ return out
123
+ }
124
+
125
+ interface Seen {
126
+ dropped: Set<string>
127
+ }
128
+
129
+ const button = (raw: unknown, seen: Seen): Button | undefined => {
130
+ if (!isRecord(raw) || raw.type !== 'button' || typeof raw.action !== 'string') {
131
+ if (isRecord(raw)) seen.dropped.add(String(raw.type ?? 'unnamed'))
132
+ return undefined
133
+ }
134
+ const out: Button = { type: 'button', label: text(raw.label), action: raw.action }
135
+ if (raw.input !== undefined) out.input = screenValues(raw.input)
136
+ if (typeof raw.look === 'string' && LOOKS.has(raw.look)) out.look = raw.look as Button['look']
137
+ const confirm = optionalText(raw.confirm)
138
+ if (confirm) out.confirm = confirm
139
+ if (raw.submit === true) out.submit = true
140
+ if (raw.disabled === true) out.disabled = true
141
+ return out
142
+ }
143
+
144
+ const buttons = (raw: unknown, seen: Seen): Button[] =>
145
+ list(raw, LIMIT.nodes)
146
+ .map((entry) => button(entry, seen))
147
+ .filter((entry): entry is Button => entry !== undefined)
148
+
149
+ const cell = (raw: unknown): Cell => {
150
+ if (!isRecord(raw)) return { type: 'text', text: text(raw) }
151
+ switch (raw.type) {
152
+ case 'code':
153
+ return { type: 'code', text: text(raw.text) }
154
+ case 'tag':
155
+ return {
156
+ type: 'tag',
157
+ text: text(raw.text),
158
+ ...(typeof raw.look === 'string' && TAG_LOOKS.has(raw.look)
159
+ ? { look: raw.look as 'default' }
160
+ : {}),
161
+ }
162
+ case 'link': {
163
+ const href = safeScreenHref(raw.href)
164
+ // A link to anywhere else is still shown, as the words it carried.
165
+ return href
166
+ ? { type: 'link', text: text(raw.text), href }
167
+ : { type: 'text', text: text(raw.text) }
168
+ }
169
+ case 'date': {
170
+ const at = new Date(text(raw.value))
171
+ return Number.isNaN(at.getTime())
172
+ ? { type: 'text', text: '' }
173
+ : { type: 'date', value: at.toISOString() }
174
+ }
175
+ default:
176
+ return { type: 'text', text: text(raw.text) }
177
+ }
178
+ }
179
+
180
+ const field = (raw: unknown, seen: Seen, inList = false): Field | undefined => {
181
+ if (!isRecord(raw) || typeof raw.name !== 'string' || typeof raw.kind !== 'string') {
182
+ return undefined
183
+ }
184
+ if (!FIELD_KINDS.has(raw.kind) || (inList && !LIST_SUB_KINDS.has(raw.kind))) {
185
+ seen.dropped.add(inList ? `field ${raw.kind} in a list` : `field ${raw.kind}`)
186
+ return undefined
187
+ }
188
+ const base: Record<string, unknown> = { kind: raw.kind, name: raw.name, label: text(raw.label) }
189
+ const hint = optionalText(raw.hint)
190
+ if (hint) base.hint = hint
191
+ const placeholder = optionalText(raw.placeholder)
192
+ if (placeholder) base.placeholder = placeholder
193
+ if (raw.required === true) base.required = true
194
+ if (raw.readOnly === true) base.readOnly = true
195
+ const visible = condition(raw.visibleWhen)
196
+ if (visible) base.visibleWhen = visible
197
+ const hints = list(raw.hints, LIMIT.fields).flatMap((entry) => {
198
+ if (!isRecord(entry)) return []
199
+ const when = condition(entry.when)
200
+ return when ? [{ when, text: text(entry.text) }] : []
201
+ })
202
+ if (hints.length > 0) base.hints = hints
203
+ switch (raw.kind) {
204
+ case 'text': {
205
+ if (raw.multiline === true) base.multiline = true
206
+ if (typeof raw.pattern === 'string') {
207
+ try {
208
+ new RegExp(raw.pattern, 'u')
209
+ base.pattern = raw.pattern
210
+ } catch {}
211
+ }
212
+ for (const key of ['minLength', 'maxLength'] as const) {
213
+ const n = finite(raw[key])
214
+ if (n !== undefined && n >= 0) base[key] = Math.floor(n)
215
+ }
216
+ break
217
+ }
218
+ case 'number':
219
+ for (const key of ['min', 'max', 'step'] as const) {
220
+ const n = finite(raw[key])
221
+ if (n !== undefined) base[key] = n
222
+ }
223
+ break
224
+ case 'list': {
225
+ base.fields = list(raw.fields, LIMIT.fields)
226
+ .map((entry) => field(entry, seen, true))
227
+ .filter((entry): entry is Field => entry !== undefined)
228
+ const label = optionalText(raw.addLabel)
229
+ if (label) base.addLabel = label
230
+ for (const key of ['min', 'max'] as const) {
231
+ const n = finite(raw[key])
232
+ if (n !== undefined && n >= 0) base[key] = Math.floor(n)
233
+ }
234
+ break
235
+ }
236
+ case 'choice':
237
+ base.options = list(raw.options, LIMIT.rows).flatMap((option) =>
238
+ isRecord(option) && typeof option.value === 'string'
239
+ ? [{ value: option.value, label: text(option.label) }]
240
+ : [],
241
+ )
242
+ break
243
+ }
244
+ return base as unknown as Field
245
+ }
246
+
247
+ const node = (raw: unknown, seen: Seen, inTab: boolean): Node | undefined => {
248
+ if (!isRecord(raw)) return undefined
249
+ const type = String(raw.type ?? '')
250
+ if (!NODE_TYPES.has(type) || (inTab && type === 'tabs')) {
251
+ seen.dropped.add(inTab && type === 'tabs' ? 'tabs inside tabs' : type || 'unnamed')
252
+ return undefined
253
+ }
254
+ switch (type) {
255
+ case 'table':
256
+ return {
257
+ type: 'table',
258
+ columns: list(raw.columns, 50).map(text),
259
+ rows: list(raw.rows, LIMIT.rows).flatMap((entry): Row[] =>
260
+ isRecord(entry)
261
+ ? [
262
+ {
263
+ key: text(entry.key),
264
+ cells: list(entry.cells, 50).map(cell),
265
+ ...(entry.actions ? { actions: buttons(entry.actions, seen) } : {}),
266
+ },
267
+ ]
268
+ : [],
269
+ ),
270
+ }
271
+ case 'form': {
272
+ const fields = list(raw.fields, LIMIT.fields)
273
+ .map((entry) => field(entry, seen))
274
+ .filter((entry): entry is Field => entry !== undefined)
275
+ // A secret is never sent to the browser, whatever the extension put in it.
276
+ const secrets = new Set(fields.filter((f) => f.kind === 'secret').map((f) => f.name))
277
+ const values = Object.fromEntries(
278
+ Object.entries(screenValues(raw.values)).filter(([key]) => !secrets.has(key)),
279
+ )
280
+ const title = optionalText(raw.title)
281
+ return {
282
+ type: 'form',
283
+ fields,
284
+ values,
285
+ actions: buttons(raw.actions, seen),
286
+ ...(title ? { title } : {}),
287
+ }
288
+ }
289
+ case 'button':
290
+ return button(raw, seen)
291
+ case 'notice':
292
+ return { type: 'notice', text: text(raw.text) }
293
+ case 'problem':
294
+ return { type: 'problem', text: text(raw.text) }
295
+ case 'empty': {
296
+ const body = optionalText(raw.text)
297
+ return {
298
+ type: 'empty',
299
+ title: text(raw.title),
300
+ ...(body ? { text: body } : {}),
301
+ ...(raw.actions ? { actions: buttons(raw.actions, seen) } : {}),
302
+ }
303
+ }
304
+ case 'progress': {
305
+ const label = optionalText(raw.label)
306
+ const at = finite(raw.value)
307
+ return {
308
+ type: 'progress',
309
+ ...(label ? { label } : {}),
310
+ ...(at !== undefined ? { value: Math.min(100, Math.max(0, at)) } : {}),
311
+ }
312
+ }
313
+ case 'tabs':
314
+ return {
315
+ type: 'tabs',
316
+ tabs: list(raw.tabs, 20).flatMap((entry): Tab[] =>
317
+ isRecord(entry)
318
+ ? [
319
+ {
320
+ id: text(entry.id),
321
+ label: text(entry.label),
322
+ body: nodes(entry.body, seen, true) as Tab['body'],
323
+ },
324
+ ]
325
+ : [],
326
+ ),
327
+ }
328
+ }
329
+ return undefined
330
+ }
331
+
332
+ const nodes = (raw: unknown, seen: Seen, inTab = false): Node[] =>
333
+ list(raw, LIMIT.nodes)
334
+ .map((entry) => node(entry, seen, inTab))
335
+ .filter((entry): entry is Node => entry !== undefined)
336
+
337
+ const toolbarItem = (raw: unknown, seen: Seen): Button | Search | undefined => {
338
+ if (isRecord(raw) && raw.type === 'search' && typeof raw.action === 'string') {
339
+ const placeholder = optionalText(raw.placeholder)
340
+ const current = optionalText(raw.value)
341
+ return {
342
+ type: 'search',
343
+ action: raw.action,
344
+ ...(placeholder ? { placeholder } : {}),
345
+ ...(current !== undefined ? { value: current } : {}),
346
+ }
347
+ }
348
+ return button(raw, seen)
349
+ }
350
+
351
+ /**
352
+ * A view's or an action's answer, held to the catalogue. `dropped` names what
353
+ * was left out, for the extension's log; it is never shown.
354
+ */
355
+ export function normaliseScreenResult(answer: unknown): {
356
+ result: ScreenResult
357
+ dropped: string[]
358
+ } {
359
+ const seen: Seen = { dropped: new Set() }
360
+ const raw = isRecord(answer) && answer.type !== 'screen' ? answer.screen : answer
361
+ const outer = isRecord(answer) && answer.type !== 'screen' ? answer : {}
362
+ const source = isRecord(raw) ? raw : {}
363
+ const screen: Screen = {
364
+ type: 'screen',
365
+ title: text(source.title),
366
+ body: nodes(source.body, seen),
367
+ }
368
+ const toolbar = list(source.toolbar, 20)
369
+ .map((entry) => toolbarItem(entry, seen))
370
+ .filter((entry): entry is Button | Search => entry !== undefined)
371
+ if (toolbar.length > 0) screen.toolbar = toolbar
372
+ const result: ScreenResult = { screen }
373
+ if (isRecord(outer.state)) {
374
+ try {
375
+ result.state = JSON.parse(JSON.stringify(outer.state))
376
+ } catch {
377
+ seen.dropped.add('state that is not plain data')
378
+ }
379
+ }
380
+ const notice = optionalText(outer.notice)
381
+ if (notice) result.notice = notice
382
+ return { result, dropped: [...seen.dropped] }
383
+ }