@zeyos/zx 5.5.0 → 5.7.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 (235) hide show
  1. package/CHANGELOG.md +210 -0
  2. package/README.md +73 -7
  3. package/bin/zx-css.js +328 -0
  4. package/dist/types/components/account-menu/account-menu.d.ts +4 -2
  5. package/dist/types/components/activity-list/activity-list.d.ts +14 -8
  6. package/dist/types/components/agent-thread/ag-ui.d.ts +340 -0
  7. package/dist/types/components/agent-thread/agent-thread.d.ts +711 -0
  8. package/dist/types/components/agent-thread/ui-message-stream.d.ts +401 -0
  9. package/dist/types/components/app-sidebar/app-sidebar.d.ts +14 -8
  10. package/dist/types/components/approval-card/approval-card.d.ts +596 -0
  11. package/dist/types/components/avatar/avatar.d.ts +91 -4
  12. package/dist/types/components/block-view/block-view.d.ts +205 -0
  13. package/dist/types/components/breadcrumb/breadcrumb.d.ts +3 -3
  14. package/dist/types/components/calendar/calendar-model.d.ts +9 -2
  15. package/dist/types/components/calendar/calendar.d.ts +12 -4
  16. package/dist/types/components/chart/chart.d.ts +25 -13
  17. package/dist/types/components/code-editor/code-editor.d.ts +7 -2
  18. package/dist/types/components/composer/composer.d.ts +938 -0
  19. package/dist/types/components/composer/queue.d.ts +76 -0
  20. package/dist/types/components/copy/copy-button.d.ts +6 -4
  21. package/dist/types/components/copy/copy-input.d.ts +10 -6
  22. package/dist/types/components/datebox/date-range-box.d.ts +33 -0
  23. package/dist/types/components/datebox/placeholder.d.ts +7 -0
  24. package/dist/types/components/dock/dock.d.ts +12 -3
  25. package/dist/types/components/entity-ref/entity-ref.d.ts +5 -3
  26. package/dist/types/components/field-upload/field-upload.d.ts +3 -2
  27. package/dist/types/components/file-item/file-item.d.ts +3 -2
  28. package/dist/types/components/file-list/file-list.d.ts +14 -8
  29. package/dist/types/components/filter/filter-model.d.ts +31 -1
  30. package/dist/types/components/filter/filter.d.ts +20 -2
  31. package/dist/types/components/finder/finder.d.ts +14 -6
  32. package/dist/types/components/flag/flag.d.ts +99 -0
  33. package/dist/types/components/grid/grid.d.ts +1 -1
  34. package/dist/types/components/kanban-view/kanban-view.d.ts +8 -66
  35. package/dist/types/components/launcher/launcher.d.ts +2 -0
  36. package/dist/types/components/multi-value-editor/multi-value-editor.d.ts +3 -2
  37. package/dist/types/components/number-field/number-field.d.ts +17 -6
  38. package/dist/types/components/prompt-starters/prompt-starters.d.ts +107 -0
  39. package/dist/types/components/prose/prose.d.ts +9 -6
  40. package/dist/types/components/questionnaire/conditions.d.ts +270 -0
  41. package/dist/types/components/questionnaire/items.d.ts +52 -30
  42. package/dist/types/components/questionnaire/questionnaire.d.ts +44 -4
  43. package/dist/types/components/rating/rating.d.ts +5 -3
  44. package/dist/types/components/run-status/run-status.d.ts +393 -0
  45. package/dist/types/components/run-trace/run-trace.d.ts +624 -0
  46. package/dist/types/components/select/country.d.ts +106 -0
  47. package/dist/types/components/select/field-adapter.d.ts +2 -1
  48. package/dist/types/components/select/locale.d.ts +102 -0
  49. package/dist/types/components/select/select.d.ts +41 -2
  50. package/dist/types/components/slider/slider.d.ts +1 -0
  51. package/dist/types/components/sort-control/sort-control.d.ts +7 -3
  52. package/dist/types/components/source-list/source-list.d.ts +179 -0
  53. package/dist/types/components/split-view/split-view.d.ts +5 -3
  54. package/dist/types/components/surface/catalog.d.ts +260 -0
  55. package/dist/types/components/surface/elicit.d.ts +81 -0
  56. package/dist/types/components/surface/mcp.d.ts +165 -0
  57. package/dist/types/components/surface/schema.d.ts +314 -0
  58. package/dist/types/components/surface/stream.d.ts +118 -0
  59. package/dist/types/components/surface/surface.d.ts +718 -0
  60. package/dist/types/components/surface/text.d.ts +277 -0
  61. package/dist/types/components/surface/validate.d.ts +339 -0
  62. package/dist/types/components/table/table.d.ts +55 -3
  63. package/dist/types/components/table/window.d.ts +203 -0
  64. package/dist/types/components/toolbar/toolbar.d.ts +10 -6
  65. package/dist/types/components/tooltip/tooltip.d.ts +2 -2
  66. package/dist/types/components/tree/tree.d.ts +20 -13
  67. package/dist/types/core/component.d.ts +10 -0
  68. package/dist/types/core/date.d.ts +8 -1
  69. package/dist/types/core/dom.d.ts +1 -0
  70. package/dist/types/core/http.d.ts +10 -0
  71. package/dist/types/core/i18n.d.ts +38 -0
  72. package/dist/types/core/messages.d.ts +479 -1
  73. package/dist/types/core/storage.d.ts +7 -2
  74. package/dist/types/elements/define.d.ts +21 -46
  75. package/dist/types/elements/definitions.d.ts +147 -0
  76. package/dist/types/elements/kit.d.ts +7 -0
  77. package/dist/types/elements/reflect.d.ts +6 -3
  78. package/dist/types/index.d.ts +18 -1
  79. package/dist/types/internal/agent-model.d.ts +587 -0
  80. package/dist/types/internal/date-locale.d.ts +7 -0
  81. package/dist/types/internal/highlight.d.ts +24 -0
  82. package/dist/types/internal/json-patch.d.ts +146 -0
  83. package/dist/types/internal/presence-loop.d.ts +148 -0
  84. package/dist/types/locales/de.d.ts +13 -0
  85. package/dist/types/locales/en.d.ts +2 -0
  86. package/dist/types/locales/index.d.ts +823 -0
  87. package/dist/types/zeyos/view.d.ts +8 -1
  88. package/dist/zx-zeyos.esm.js +20505 -18748
  89. package/dist/zx-zeyos.esm.min.js +5 -5
  90. package/dist/zx.core.css +1276 -0
  91. package/dist/zx.core.min.css +1 -0
  92. package/dist/zx.css +2424 -134
  93. package/dist/zx.esm.js +46167 -28468
  94. package/dist/zx.esm.min.js +40 -8
  95. package/dist/zx.global.js +46167 -28468
  96. package/dist/zx.global.min.js +40 -8
  97. package/dist/zx.layered.css +17302 -0
  98. package/dist/zx.layered.min.css +1 -0
  99. package/dist/zx.min.css +1 -1
  100. package/docs/agent-catalog.json +12501 -0
  101. package/docs/agent-surfaces.md +340 -0
  102. package/docs/api.json +2057 -166
  103. package/docs/llms.md +1458 -58
  104. package/docs/llms.txt +38 -8
  105. package/package.json +29 -6
  106. package/src/components/account-menu/account-menu.js +6 -3
  107. package/src/components/activity-item/activity-item.js +2 -1
  108. package/src/components/activity-list/activity-list.js +16 -10
  109. package/src/components/agent-thread/ag-ui.js +1439 -0
  110. package/src/components/agent-thread/agent-thread.css +417 -0
  111. package/src/components/agent-thread/agent-thread.js +1670 -0
  112. package/src/components/agent-thread/ui-message-stream.js +1281 -0
  113. package/src/components/app-sidebar/app-sidebar.js +18 -8
  114. package/src/components/approval-card/approval-card.css +289 -0
  115. package/src/components/approval-card/approval-card.js +1378 -0
  116. package/src/components/avatar/avatar.css +56 -1
  117. package/src/components/avatar/avatar.js +148 -26
  118. package/src/components/block-view/block-view.css +300 -0
  119. package/src/components/block-view/block-view.js +524 -0
  120. package/src/components/breadcrumb/breadcrumb.js +8 -5
  121. package/src/components/calendar/calendar-model.js +8 -2
  122. package/src/components/calendar/calendar.js +53 -18
  123. package/src/components/chart/chart.js +54 -23
  124. package/src/components/code-editor/code-editor.js +45 -8
  125. package/src/components/code-editor/field-adapter.js +1 -1
  126. package/src/components/composer/composer.css +482 -0
  127. package/src/components/composer/composer.js +1815 -0
  128. package/src/components/composer/queue.js +78 -0
  129. package/src/components/context-menu/context-menu.js +12 -1
  130. package/src/components/copy/copy-button.js +9 -7
  131. package/src/components/copy/copy-input.js +10 -6
  132. package/src/components/date-picker/date-picker.js +2 -1
  133. package/src/components/date-picker/date-range-picker.js +8 -7
  134. package/src/components/datebox/date-range-box.js +3 -9
  135. package/src/components/datebox/datebox.js +18 -21
  136. package/src/components/datebox/placeholder.js +18 -0
  137. package/src/components/dialog/dialog.js +1 -1
  138. package/src/components/dock/dock.js +34 -13
  139. package/src/components/entity-ref/entity-ref.js +16 -5
  140. package/src/components/field-upload/field-upload.js +81 -38
  141. package/src/components/file-item/file-item.js +70 -40
  142. package/src/components/file-list/file-list.js +15 -9
  143. package/src/components/filter/filter-model.js +46 -8
  144. package/src/components/filter/filter.css +3 -3
  145. package/src/components/filter/filter.js +29 -10
  146. package/src/components/filter-panel/filter-panel.js +13 -5
  147. package/src/components/finder/finder.js +50 -26
  148. package/src/components/flag/flag.css +40 -0
  149. package/src/components/flag/flag.js +177 -0
  150. package/src/components/form/form.js +1 -1
  151. package/src/components/grid/grid.js +22 -8
  152. package/src/components/kanban-view/kanban-view.js +51 -81
  153. package/src/components/launcher/launcher.js +17 -2
  154. package/src/components/list-toolbar/list-toolbar.js +2 -1
  155. package/src/components/master-panel/master-panel.js +1 -1
  156. package/src/components/menu-button/menu-button.js +4 -0
  157. package/src/components/message/message.js +3 -0
  158. package/src/components/multi-value-editor/multi-value-editor.js +10 -9
  159. package/src/components/navigation-bar/navigation-bar.js +3 -3
  160. package/src/components/number-field/number-field.js +29 -13
  161. package/src/components/prompt-starters/prompt-starters.css +91 -0
  162. package/src/components/prompt-starters/prompt-starters.js +206 -0
  163. package/src/components/prose/prose.js +14 -10
  164. package/src/components/questionnaire/conditions.js +666 -0
  165. package/src/components/questionnaire/items.js +150 -41
  166. package/src/components/questionnaire/questionnaire.js +126 -32
  167. package/src/components/rating/rating.js +5 -4
  168. package/src/components/run-status/run-status.css +208 -0
  169. package/src/components/run-status/run-status.js +782 -0
  170. package/src/components/run-trace/run-trace.css +443 -0
  171. package/src/components/run-trace/run-trace.js +1209 -0
  172. package/src/components/select/country.js +136 -0
  173. package/src/components/select/field-adapter.js +7 -2
  174. package/src/components/select/locale.js +219 -0
  175. package/src/components/select/select.css +20 -22
  176. package/src/components/select/select.js +94 -12
  177. package/src/components/sheet/sheet-stack.js +10 -1
  178. package/src/components/slider/slider.js +7 -2
  179. package/src/components/sort-control/sort-control.js +15 -5
  180. package/src/components/source-list/source-list.css +208 -0
  181. package/src/components/source-list/source-list.js +358 -0
  182. package/src/components/split-view/split-view.js +5 -3
  183. package/src/components/surface/catalog.js +1334 -0
  184. package/src/components/surface/elicit.js +107 -0
  185. package/src/components/surface/mcp.js +243 -0
  186. package/src/components/surface/schema.js +644 -0
  187. package/src/components/surface/stream.js +245 -0
  188. package/src/components/surface/surface.css +308 -0
  189. package/src/components/surface/surface.js +2291 -0
  190. package/src/components/surface/text.js +513 -0
  191. package/src/components/surface/validate.js +2218 -0
  192. package/src/components/tabbox/tabbox.js +9 -0
  193. package/src/components/table/table.css +63 -3
  194. package/src/components/table/table.js +167 -28
  195. package/src/components/table/window.js +317 -0
  196. package/src/components/toolbar/toolbar.js +12 -7
  197. package/src/components/tooltip/tooltip.css +2 -3
  198. package/src/components/tooltip/tooltip.js +32 -5
  199. package/src/components/tree/tree.js +53 -23
  200. package/src/core/component.js +25 -1
  201. package/src/core/date.js +62 -16
  202. package/src/core/dom.js +22 -2
  203. package/src/core/format.js +15 -13
  204. package/src/core/http.js +29 -20
  205. package/src/core/i18n.js +83 -10
  206. package/src/core/keyboard.js +79 -8
  207. package/src/core/messages.js +519 -2
  208. package/src/core/overlay-host.js +1 -0
  209. package/src/core/storage.js +59 -6
  210. package/src/elements/define.js +178 -130
  211. package/src/elements/definitions.js +229 -0
  212. package/src/elements/kit.js +444 -0
  213. package/src/elements/reflect.js +8 -3
  214. package/src/index.js +18 -1
  215. package/src/internal/agent-model.js +488 -0
  216. package/src/internal/date-locale.js +11 -0
  217. package/src/internal/highlight.js +104 -0
  218. package/src/internal/json-patch.js +405 -0
  219. package/src/internal/presence-loop.js +343 -0
  220. package/src/locales/de.js +911 -0
  221. package/src/locales/en.js +2 -0
  222. package/src/locales/index.js +7 -0
  223. package/src/zeyos/calendar.js +2 -1
  224. package/src/zeyos/form.js +2 -1
  225. package/src/zeyos/launcher.js +7 -6
  226. package/src/zeyos/module-bar.js +2 -1
  227. package/src/zeyos/schema.js +37 -23
  228. package/src/zeyos/select.js +4 -3
  229. package/src/zeyos/table.js +2 -13
  230. package/src/zeyos/view.js +57 -17
  231. package/styles/core.css +11 -0
  232. package/styles/tokens/semantic.css +1 -0
  233. package/styles/zeyos.css +2 -0
  234. package/styles/zx.css +11 -8
  235. package/styles/zx.layered.css +1 -0
@@ -0,0 +1,513 @@
1
+ // @ts-check
2
+ /**
3
+ * Pure helpers around a surface's reply: which inputs are visible, the reply's shape per intent,
4
+ * and the receipt as plain text.
5
+ *
6
+ * The module touches no DOM, so a server can build the same receipt for its audit log, or check
7
+ * which inputs a reply may carry, with the code the page used.
8
+ */
9
+ import { getLanguage, printf, translate } from '../../core/i18n.js';
10
+ import { defaultMessages } from '../../core/messages.js';
11
+ import { getPointer } from '../../internal/json-patch.js';
12
+ import { evaluate, isEmptyAnswer } from '../questionnaire/conditions.js';
13
+ import { resolveFlow } from '../questionnaire/items.js';
14
+ import { CATALOG, REPLY_VERSION, RESERVED_ACTIONS } from './catalog.js';
15
+ import { choicesOf } from './schema.js';
16
+ import { validateDocument } from './validate.js';
17
+
18
+ /** @typedef {import('./validate.js').SurfaceDocument} SurfaceDocument */
19
+ /** @typedef {import('./validate.js').SurfaceNode} SurfaceNode */
20
+ /** @typedef {import('./validate.js').SurfaceAction} SurfaceAction */
21
+ /** @typedef {import('./catalog.js').SurfaceIntent} SurfaceIntent */
22
+
23
+ /**
24
+ * How the person confirmed the action: `clicked` in a confirmation dialog, `typed` the text a
25
+ * type-to-confirm dialog asked for, or `null` when the application's policy asked for nothing, or
26
+ * the surface was closed.
27
+ * @typedef {'clicked'|'typed'|null} ReplyConfirmation
28
+ */
29
+
30
+ /**
31
+ * Why a surface ended without an action of its own: closed by the person, superseded by a newer
32
+ * surface, stopped with its run, or destroyed unanswered.
33
+ * @typedef {'cancelled'|'escape'|'closed'|'superseded'|'stopped'|'destroyed'|string} ReplyReason
34
+ */
35
+
36
+ /**
37
+ * What every surface ends in, exactly once. It records what the page did; it proves nothing, so
38
+ * the application's server runs its policy again for the named tool before acting.
39
+ * @typedef {Object} SurfaceReply
40
+ * @property {'reply/1'} zx The reply format.
41
+ * @property {string|null} surface The surface's id; `null` when a surface that never began had
42
+ * no valid id to name.
43
+ * @property {string} action The action taken: an action id of the surface's own, a default one
44
+ * (`submit`, `confirm`, `approve`, `reject`), or `cancel` / `dismiss` when it was closed.
45
+ * @property {string} key The idempotency key, `<surface>#<action>` (`#<action>` without a surface
46
+ * id): the same answer twice has the same key, so a server acts on it once.
47
+ * @property {Record<string, unknown>} values The visible inputs' values by name; `{answers, path}`
48
+ * for a questionnaire; `{}` for `show`, `confirm`, `reject` and a closed surface.
49
+ * @property {ReplyConfirmation} confirmation How the person confirmed.
50
+ * @property {string} at Local ISO date-time of the answer, `YYYY-MM-DDTHH:MM:SS`.
51
+ * @property {string} [token] The application's token, unchanged; only when it gave one.
52
+ * @property {string[]} [removed] The ids of actions the application's policy denied, which were
53
+ * not drawn; only when there were any.
54
+ * @property {ReplyReason} [reason] Why a closing reply (`cancel`, `dismiss`) was sent.
55
+ */
56
+
57
+ /**
58
+ * What `createReply()` takes.
59
+ * @typedef {Object} ReplyDetails
60
+ * @property {string} action The action id.
61
+ * @property {Record<string, unknown>} [values] The values, before they are shaped for the intent.
62
+ * @property {ReplyConfirmation} [confirmation=null]
63
+ * @property {string|null} [token=null]
64
+ * @property {string[]} [removed=[]]
65
+ * @property {ReplyReason} [reason]
66
+ * @property {Date|string} [at] The time of the answer; now when left out.
67
+ */
68
+
69
+ /**
70
+ * Which nodes and inputs of a surface are visible for a set of answers.
71
+ * @typedef {Object} SurfaceVisibility
72
+ * @property {Set<string>} hiddenNodes Ids of nodes hidden by their own condition or an ancestor's.
73
+ * @property {Map<string, Set<string>>} hiddenFields Per `fields` node, the properties hidden by
74
+ * their `x-zx.visible` (not counting a hidden node).
75
+ * @property {string[]} names The visible inputs' names, in the order they are declared.
76
+ * @property {Map<string, string>} owners The node holding each input name.
77
+ */
78
+
79
+ /**
80
+ * The English texts of every message the surface shows: the `surface.*` entries of the library's
81
+ * catalogue, read from it so there is one source. A host translates them through the Surface's
82
+ * `msg` option or its translator; `surfaceText()` takes a `msg` function.
83
+ * @type {Readonly<Record<string, string>>}
84
+ */
85
+ export const SURFACE_MESSAGES = Object.freeze(Object.fromEntries(
86
+ Object.entries(defaultMessages).filter(([key]) => key.startsWith('surface.'))
87
+ ));
88
+
89
+ /** The verdict word of each action the format names, by action id. */
90
+ const VERDICT_KEYS = Object.freeze({
91
+ submit: 'surface.submitted',
92
+ confirm: 'surface.confirmed',
93
+ approve: 'surface.approved',
94
+ reject: 'surface.rejected',
95
+ cancel: 'surface.cancelled',
96
+ dismiss: 'surface.dismissed'
97
+ });
98
+
99
+ /** Actions that close a surface rather than answer it. */
100
+ export const CLOSING_ACTIONS = RESERVED_ACTIONS;
101
+
102
+ /** Actions whose reply carries no values: the closing ones and a rejection. */
103
+ const VALUELESS_ACTIONS = new Set([...CLOSING_ACTIONS, 'reject']);
104
+
105
+ /** Intents whose reply carries no values whatever the action. */
106
+ const VALUELESS_INTENTS = new Set(['show', 'confirm']);
107
+
108
+ /**
109
+ * The English message for a key, with `%1`, `%2`, … filled in. The default `msg` of
110
+ * `surfaceText()`.
111
+ * @param {string} key
112
+ * @param {...unknown} args
113
+ * @returns {string}
114
+ */
115
+ export function surfaceMessage(key, ...args) {
116
+ const text = /** @type {Record<string, string>} */ (SURFACE_MESSAGES)[key] ?? key;
117
+ return text.replace(/%(\d+)/g, (match, digit) => {
118
+ const value = args[Number(digit) - 1];
119
+ return value === undefined ? match : String(value);
120
+ });
121
+ }
122
+
123
+ /**
124
+ * A message resolver that answers the way a Surface's own `msg()` does: the `msg` table for the
125
+ * active language, then its flat entries, then the host translator (`setTranslator()`), then the
126
+ * English catalogue, then the key.
127
+ * @param {Record<string, any>|null|undefined} msg The `msg` option, flat or by language.
128
+ * @param {string} [lang] The language; `getLanguage()` when absent, read at each call.
129
+ * @returns {(key: string, ...args: unknown[]) => string}
130
+ */
131
+ export function messageResolver(msg, lang) {
132
+ const own = msg && typeof msg === 'object' && !Array.isArray(msg) ? msg : null;
133
+ return (key, ...args) => {
134
+ const active = lang ?? getLanguage();
135
+ const table = own && own[active] && typeof own[active] === 'object' ? own[active] : null;
136
+ const value = table && typeof table[key] === 'string' ? table[key]
137
+ : own && Object.hasOwn(own, key) && typeof own[key] === 'string' ? own[key] : null;
138
+ return value !== null ? printf(value, args) : translate(key, args);
139
+ };
140
+ }
141
+
142
+ /**
143
+ * Escapes the characters inline text reads as markup (`*`, `` ` ``, `[`, `\`), so untrusted text
144
+ * — a server's message, an address — is drawn exactly as given by a `text` node. With `max`, the
145
+ * escaped text is cut to at most that many characters, never between an escape and the character
146
+ * it escapes, nor inside a surrogate pair.
147
+ * @param {string} value
148
+ * @param {number} [max=Infinity] The most characters the result may hold.
149
+ * @returns {string}
150
+ */
151
+ export function plainInline(value, max = Infinity) {
152
+ const escaped = String(value).replace(INLINE_MARKUP, '\\$&');
153
+ if (escaped.length <= max) return escaped;
154
+ let out = '';
155
+ for (const char of String(value)) {
156
+ const piece = INLINE_MARKUP_CHAR.test(char) ? `\\${char}` : char;
157
+ if (out.length + piece.length > max) break;
158
+ out += piece;
159
+ }
160
+ return out;
161
+ }
162
+
163
+ /** The characters inline text reads as markup. */
164
+ const INLINE_MARKUP = /[*`[\\]/g;
165
+ const INLINE_MARKUP_CHAR = /^[*`[\\]$/;
166
+
167
+ /**
168
+ * Reads a node property, resolving a `{"$data": "/pointer"}` binding against the surface data.
169
+ * @param {SurfaceNode} node
170
+ * @param {string} prop
171
+ * @param {unknown} data
172
+ * @returns {unknown} The value, or `undefined` when it is absent or its pointer finds nothing.
173
+ */
174
+ export function readProp(node, prop, data) {
175
+ const value = node[prop];
176
+ if (isObject(value) && typeof value.$data === 'string' && Object.keys(value).length === 1) {
177
+ try {
178
+ return getPointer(data ?? {}, value.$data);
179
+ } catch {
180
+ return undefined;
181
+ }
182
+ }
183
+ return value;
184
+ }
185
+
186
+ /**
187
+ * The input names a node declares, in order: a `fields` node's schema properties, or the `name`
188
+ * of any other input node (a table only while it is selectable).
189
+ * @param {SurfaceNode} node
190
+ * @param {unknown} data
191
+ * @returns {string[]}
192
+ */
193
+ export function inputNames(node, data) {
194
+ const entry = Object.hasOwn(CATALOG.nodes, node.type) ? CATALOG.nodes[node.type] : null;
195
+ if (!entry?.input) return [];
196
+ if (node.type === 'fields') {
197
+ const schema = readProp(node, 'schema', data);
198
+ return isObject(schema) && isObject(schema.properties) ? Object.keys(schema.properties) : [];
199
+ }
200
+ if (node.type === 'table' && !readProp(node, 'selectable', data)) return [];
201
+ if (node.type === 'questionnaire') return [];
202
+ return typeof node.name === 'string' ? [node.name] : [];
203
+ }
204
+
205
+ /**
206
+ * Decides which nodes and inputs are visible, walking the tree depth first from `root` as the
207
+ * conditions are declared. A condition sees only the answers of visible inputs that come before
208
+ * it, so hiding an input also hides what depends on it. A malformed condition counts as true:
209
+ * the node stays visible, as validation reports it.
210
+ * @param {SurfaceDocument|{root: string[], nodes: SurfaceNode[]|Map<string, SurfaceNode>, data?: unknown}} document
211
+ * @param {Record<string, unknown>} answers The inputs' values by name, hidden ones included.
212
+ * @returns {SurfaceVisibility}
213
+ */
214
+ export function surfaceVisibility(document, answers) {
215
+ const nodes = document.nodes instanceof Map
216
+ ? document.nodes
217
+ : new Map((Array.isArray(document.nodes) ? document.nodes : []).map((node) => [node.id, node]));
218
+ const data = document.data ?? {};
219
+ /** @type {SurfaceVisibility} */
220
+ const result = { hiddenNodes: new Set(), hiddenFields: new Map(), names: [], owners: new Map() };
221
+ /** @type {Record<string, unknown>} */
222
+ const seen = {};
223
+ const source = isObject(answers) ? answers : {};
224
+ /** @type {Set<string>} Inputs met so far, visible or not. */
225
+ const declared = new Set();
226
+ const holds = (/** @type {unknown} */ condition) => {
227
+ if (!isObject(condition)) return true;
228
+ // A condition naming an input that has not arrived (yet) leaves its node visible.
229
+ if (conditionFields(condition).some((field) => !declared.has(field))) return true;
230
+ try {
231
+ return evaluate(/** @type {any} */ (condition), seen);
232
+ } catch {
233
+ return true;
234
+ }
235
+ };
236
+ const visited = new Set();
237
+ /** @param {string} id @param {boolean} parentVisible @param {number} depth */
238
+ const walk = (id, parentVisible, depth) => {
239
+ if (visited.has(id) || depth > 64) return;
240
+ visited.add(id);
241
+ const node = nodes.get(id);
242
+ if (!node) return;
243
+ const visible = parentVisible && holds(node.visible);
244
+ if (!visible) result.hiddenNodes.add(id);
245
+ if (node.type === 'fields') {
246
+ const schema = readProp(node, 'schema', data);
247
+ /** @type {Set<string>} */
248
+ const hidden = new Set();
249
+ const properties = isObject(schema) && isObject(schema.properties) ? schema.properties : {};
250
+ for (const [name, property] of Object.entries(properties)) {
251
+ const shown = visible && holds(isObject(property) ? property['x-zx']?.visible : undefined);
252
+ if (visible && !shown) hidden.add(name);
253
+ result.owners.set(name, id);
254
+ declared.add(name);
255
+ if (shown) {
256
+ result.names.push(name);
257
+ if (Object.hasOwn(source, name)) seen[name] = source[name];
258
+ }
259
+ }
260
+ result.hiddenFields.set(id, hidden);
261
+ } else {
262
+ for (const name of inputNames(node, data)) {
263
+ result.owners.set(name, id);
264
+ declared.add(name);
265
+ if (!visible) continue;
266
+ result.names.push(name);
267
+ if (Object.hasOwn(source, name)) seen[name] = source[name];
268
+ }
269
+ }
270
+ if (Array.isArray(node.children)) for (const child of node.children) walk(child, visible, depth + 1);
271
+ };
272
+ for (const id of Array.isArray(document.root) ? document.root : []) walk(id, true, 1);
273
+ return result;
274
+ }
275
+
276
+ /**
277
+ * The input names a condition refers to, at any depth.
278
+ * @param {unknown} condition
279
+ * @param {number} [depth=0]
280
+ * @returns {string[]}
281
+ */
282
+ function conditionFields(condition, depth = 0) {
283
+ if (!isObject(condition) || depth > 8) return [];
284
+ if (typeof condition.field === 'string') return [condition.field];
285
+ /** @type {string[]} */
286
+ const out = [];
287
+ for (const key of ['all', 'any']) {
288
+ if (Array.isArray(condition[key])) for (const entry of condition[key]) out.push(...conditionFields(entry, depth + 1));
289
+ }
290
+ if (Object.hasOwn(condition, 'not')) out.push(...conditionFields(condition.not, depth + 1));
291
+ return out;
292
+ }
293
+
294
+ /**
295
+ * Builds a reply. Values are shaped for the intent: `show` and `confirm` reply `{}`, as do
296
+ * `reject` and a closed surface; a questionnaire's `submit` keeps `{answers, path}` for the steps
297
+ * visible for those answers; every other reply keeps only the inputs that are visible for the
298
+ * values given, so a hidden input never leaves the page.
299
+ * @param {SurfaceDocument} document The surface, as validated.
300
+ * @param {ReplyDetails} details
301
+ * @returns {SurfaceReply}
302
+ */
303
+ export function createReply(document, details) {
304
+ const action = String(details.action);
305
+ const intent = document.intent;
306
+ const given = isObject(details.values) ? details.values : {};
307
+ /** @type {Record<string, unknown>} */
308
+ let values = {};
309
+ if (!intent || VALUELESS_INTENTS.has(intent) || VALUELESS_ACTIONS.has(action)) {
310
+ values = {};
311
+ } else if (intent === 'questionnaire') {
312
+ values = isObject(given.answers) ? visibleSteps(questionnaireSteps(document), given.answers, Array.isArray(given.path) ? given.path : []) : {};
313
+ } else {
314
+ const { names } = surfaceVisibility(document, given);
315
+ for (const name of names) {
316
+ if (Object.hasOwn(given, name) && given[name] !== undefined) values[name] = clone(given[name]);
317
+ }
318
+ }
319
+ /** @type {SurfaceReply} */
320
+ const reply = {
321
+ zx: /** @type {'reply/1'} */ (REPLY_VERSION),
322
+ surface: document.surface,
323
+ action,
324
+ key: `${document.surface}#${action}`,
325
+ values,
326
+ confirmation: CLOSING_ACTIONS.includes(action) ? null : details.confirmation ?? null,
327
+ at: localDateTime(details.at instanceof Date ? details.at : typeof details.at === 'string' ? details.at : new Date())
328
+ };
329
+ if (typeof details.token === 'string') reply.token = details.token;
330
+ if (Array.isArray(details.removed) && details.removed.length) reply.removed = [...details.removed];
331
+ if (details.reason && CLOSING_ACTIONS.includes(action)) reply.reason = details.reason;
332
+ return reply;
333
+ }
334
+
335
+ /**
336
+ * Options of `surfaceText()`.
337
+ * @typedef {Object} SurfaceTextOptions
338
+ * @property {(key: string, ...args: unknown[]) => string} [msg] Resolves a message key; English
339
+ * by default (`SURFACE_MESSAGES`).
340
+ * @property {Iterable<string>|null} [entities=null] The record entities the document may name, as
341
+ * the Surface's `resolve.entities`.
342
+ */
343
+
344
+ /**
345
+ * The receipt of an answered surface as plain text, for an audit log or a notification: the
346
+ * title, each answered value under its label (choice and enum titles rather than raw values), the
347
+ * selected rows by their row id, the verdict and the time. Inputs hidden for the reply's values
348
+ * are never included, whatever the reply carries. Pure.
349
+ * @param {SurfaceDocument} document The surface, as given to the Surface or from `toDocument()`.
350
+ * @param {SurfaceReply} reply Its reply.
351
+ * @param {SurfaceTextOptions} [options]
352
+ * @returns {string} Lines separated by `\n`.
353
+ */
354
+ export function surfaceText(document, reply, options = {}) {
355
+ const msg = typeof options.msg === 'function' ? options.msg : surfaceMessage;
356
+ const checked = validateDocument(document, CATALOG, { entities: options.entities ?? null }).document;
357
+ const doc = /** @type {SurfaceDocument} */ (checked ?? { zx: 'surface/1', surface: '', intent: null, root: [], nodes: [] });
358
+ const values = isObject(reply?.values) ? reply.values : {};
359
+ /** @type {string[]} */
360
+ const lines = [];
361
+ if (doc.title) lines.push(doc.title);
362
+ const nodes = new Map(doc.nodes.map((node) => [node.id, node]));
363
+ const data = doc.data ?? {};
364
+ const action = typeof reply?.action === 'string' ? reply.action : '';
365
+ const answered = Boolean(doc.intent) && !VALUELESS_INTENTS.has(/** @type {string} */ (doc.intent)) && !VALUELESS_ACTIONS.has(action);
366
+
367
+ if (answered && doc.intent === 'questionnaire') {
368
+ const steps = questionnaireSteps(doc);
369
+ const given = isObject(values.answers) ? values.answers : {};
370
+ const { answers, path } = visibleSteps(steps, given, Array.isArray(values.path) ? values.path : Object.keys(given));
371
+ for (const name of path) {
372
+ const step = steps.find((entry) => isObject(entry) && entry.name === name);
373
+ if (!step || !Object.hasOwn(answers, name)) continue;
374
+ const choices = Array.isArray(step.choices) ? step.choices.map((choice) => [choice.value, choice.label]) : [];
375
+ lines.push(`${step.prompt}: ${display(answers[name], choices, msg)}`);
376
+ }
377
+ } else if (answered) {
378
+ const visibility = surfaceVisibility(doc, values);
379
+ for (const name of visibility.names) {
380
+ if (!Object.hasOwn(values, name) || isEmptyAnswer(values[name])) continue;
381
+ const node = nodes.get(/** @type {string} */ (visibility.owners.get(name)));
382
+ if (!node) continue;
383
+ lines.push(answerLine(node, name, values[name], data, msg));
384
+ }
385
+ }
386
+ const time = typeof reply?.at === 'string' ? reply.at.replace('T', ' ').replace(/:\d\d(?:\.\d+)?$/, '') : '';
387
+ const verdict = verdictText(action, doc.actions ?? [], msg);
388
+ lines.push(time ? msg('surface.verdictAt', verdict, time) : verdict);
389
+ return lines.join('\n');
390
+ }
391
+
392
+ /**
393
+ * The verdict of an action: "Submitted", "Cancelled", …, or "Chose “<label>”" for an action of
394
+ * the surface's own.
395
+ * @param {string} action
396
+ * @param {SurfaceAction[]} actions The surface's own actions.
397
+ * @param {(key: string, ...args: unknown[]) => string} [msg]
398
+ * @returns {string}
399
+ */
400
+ export function verdictText(action, actions, msg = surfaceMessage) {
401
+ // A closing word is never a surface's own: it could otherwise name what closing it meant.
402
+ const own = Array.isArray(actions) && !CLOSING_ACTIONS.includes(action) ? actions.find((entry) => entry.id === action) : null;
403
+ if (own) return msg('surface.chose', own.label);
404
+ return Object.hasOwn(VERDICT_KEYS, action) ? msg(VERDICT_KEYS[/** @type {keyof typeof VERDICT_KEYS} */ (action)]) : action;
405
+ }
406
+
407
+ /**
408
+ * The steps of a surface's questionnaire.
409
+ * @param {{nodes?: unknown, data?: unknown}} document
410
+ * @returns {Array<Record<string, any>>}
411
+ */
412
+ function questionnaireSteps(document) {
413
+ const nodes = document.nodes instanceof Map ? [...document.nodes.values()] : Array.isArray(document.nodes) ? document.nodes : [];
414
+ const node = nodes.find((entry) => entry.type === 'questionnaire');
415
+ const steps = node ? readProp(node, 'steps', document.data) : null;
416
+ return Array.isArray(steps) ? steps : [];
417
+ }
418
+
419
+ /**
420
+ * A questionnaire's answers and path, limited to the steps visible for those answers, by the
421
+ * Questionnaire's own rule. Without steps to read, what was given stands.
422
+ * @param {Array<Record<string, any>>} steps @param {Record<string, unknown>} answers @param {string[]} path
423
+ * @returns {{answers: Record<string, unknown>, path: string[]}}
424
+ */
425
+ export function visibleSteps(steps, answers, path) {
426
+ if (!steps.length) return { answers: clone(answers), path: [...path] };
427
+ const flow = resolveFlow(/** @type {any} */ (steps), answers);
428
+ const names = new Set(flow.visible.map((step) => step.name));
429
+ return { answers: clone(flow.answers), path: path.filter((name) => names.has(name)) };
430
+ }
431
+
432
+ /**
433
+ * One answered value with its label.
434
+ * @param {SurfaceNode} node @param {string} name @param {unknown} value @param {unknown} data
435
+ * @param {(key: string, ...args: unknown[]) => string} msg
436
+ * @returns {string}
437
+ */
438
+ function answerLine(node, name, value, data, msg) {
439
+ switch (node.type) {
440
+ case 'fields': {
441
+ const schema = /** @type {any} */ (readProp(node, 'schema', data));
442
+ const property = schema?.properties?.[name] ?? {};
443
+ const label = typeof property.title === 'string' && property.title ? property.title : name;
444
+ return `${label}: ${display(value, choicesOf(property), msg)}`;
445
+ }
446
+ case 'choice': {
447
+ const choices = readProp(node, 'choices', data);
448
+ const list = Array.isArray(choices) ? choices.map((choice) => [choice.value, choice.label]) : [];
449
+ return `${labelOf(node, name, data)}: ${display(value, list, msg)}`;
450
+ }
451
+ case 'diff': {
452
+ const rows = readProp(node, 'rows', data);
453
+ const accepted = Array.isArray(value) ? value : [value];
454
+ const changes = (Array.isArray(rows) ? rows : [])
455
+ .filter((row) => accepted.includes(row.id))
456
+ .map((row) => `${row.label} (${cellText(row.before, msg)} → ${cellText(row.after, msg)})`);
457
+ return `${labelOf(node, name, data)}: ${changes.length ? changes.join('; ') : msg('surface.noAnswer')}`;
458
+ }
459
+ default:
460
+ return `${labelOf(node, name, data)}: ${display(value, [], msg)}`;
461
+ }
462
+ }
463
+
464
+ /** @param {SurfaceNode} node @param {string} name @param {unknown} data @returns {string} */
465
+ function labelOf(node, name, data) {
466
+ const label = readProp(node, 'label', data);
467
+ return typeof label === 'string' && label ? label : name;
468
+ }
469
+
470
+ /**
471
+ * @param {unknown} value @param {Array<[unknown, unknown]>|unknown[][]} choices
472
+ * @param {(key: string, ...args: unknown[]) => string} msg
473
+ * @returns {string}
474
+ */
475
+ function display(value, choices, msg) {
476
+ const title = (/** @type {unknown} */ entry) => {
477
+ const match = choices.find((choice) => choice[0] === entry);
478
+ return match ? String(match[1]) : cellText(entry, msg);
479
+ };
480
+ if (Array.isArray(value)) return value.length ? value.map(title).join(', ') : msg('surface.noAnswer');
481
+ return title(value);
482
+ }
483
+
484
+ /** @param {unknown} value @param {(key: string, ...args: unknown[]) => string} msg @returns {string} */
485
+ function cellText(value, msg) {
486
+ if (value === true) return msg('surface.yes');
487
+ if (value === false) return msg('surface.no');
488
+ if (value === null || value === undefined || value === '') return msg('surface.noAnswer');
489
+ if (isObject(value) && typeof value.id === 'string') return value.id;
490
+ return String(value);
491
+ }
492
+
493
+ /**
494
+ * A local ISO date-time without a zone, `YYYY-MM-DDTHH:MM:SS`.
495
+ * @param {Date|string} value
496
+ * @returns {string}
497
+ */
498
+ export function localDateTime(value) {
499
+ if (typeof value === 'string') return value;
500
+ const pad = (/** @type {number} */ number) => String(number).padStart(2, '0');
501
+ return `${String(value.getFullYear()).padStart(4, '0')}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`
502
+ + `T${pad(value.getHours())}:${pad(value.getMinutes())}:${pad(value.getSeconds())}`;
503
+ }
504
+
505
+ /** @template T @param {T} value @returns {T} */
506
+ function clone(value) {
507
+ return value === undefined ? value : JSON.parse(JSON.stringify(value));
508
+ }
509
+
510
+ /** @param {unknown} value @returns {value is Record<string, any>} */
511
+ function isObject(value) {
512
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
513
+ }