@adecore/intelligent-ui 0.38.0 → 0.40.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.
package/src/runtime.ts CHANGED
@@ -50,29 +50,36 @@ export class UiState {
50
50
 
51
51
  sync(block: UiBlock): void {
52
52
  const defaults = copyUiValue(block.defaults, new UiBudget(this.limits)) as Record<string, UiValue>;
53
+
53
54
  if (this.id !== block.id) {
54
55
  this.values = Object.create(null);
55
56
  this.queries = Object.create(null);
56
57
  }
58
+
57
59
  for (const [name, value] of Object.entries(defaults)) {
58
60
  if (this.id !== block.id || !Object.hasOwn(this.defaults, name) || !sameUiValue(this.defaults[name], value)) {
59
61
  this.values[name] = value;
60
62
  }
61
63
  }
64
+
62
65
  for (const name of Object.keys(this.values)) {
63
66
  if (!Object.hasOwn(defaults, name)) {
64
67
  delete this.values[name];
65
68
  }
66
69
  }
70
+
67
71
  for (const name of Object.keys(this.queries)) {
68
72
  if (!Object.hasOwn(block.queries, name) || this.querySignatures[name] !== JSON.stringify(block.queries[name])) {
69
73
  delete this.queries[name];
70
74
  }
71
75
  }
76
+
72
77
  this.querySignatures = Object.create(null);
78
+
73
79
  for (const [name, query] of Object.entries(block.queries)) {
74
80
  this.querySignatures[name] = JSON.stringify(query);
75
81
  }
82
+
76
83
  this.id = block.id;
77
84
  this.defaults = defaults;
78
85
  }
@@ -83,6 +90,7 @@ export class UiState {
83
90
 
84
91
  subscribe(listener: () => void): () => void {
85
92
  this.listeners.add(listener);
93
+
86
94
  return () => this.listeners.delete(listener);
87
95
  }
88
96
 
@@ -94,11 +102,14 @@ export class UiState {
94
102
  if (!Object.hasOwn(this.defaults, name)) {
95
103
  throw new UiFailure('refused_binding', 'Only declared local state can be changed.');
96
104
  }
105
+
97
106
  const next = copyUiValue(value, new UiBudget(this.limits));
98
107
  const initial = this.defaults[name];
108
+
99
109
  if (Array.isArray(next) !== Array.isArray(initial) || typeof next !== typeof initial || (next === null) !== (initial === null)) {
100
110
  throw new UiFailure('invalid_value', 'The state type cannot change.');
101
111
  }
112
+
102
113
  this.values[name] = next;
103
114
  this.changed();
104
115
  }
@@ -107,12 +118,14 @@ export class UiState {
107
118
  if (block.id !== this.id || !Object.hasOwn(block.queries, name) || this.querySignatures[name] !== JSON.stringify(block.queries[name])) {
108
119
  throw new UiFailure('refused_query', 'The query must belong to this block.');
109
120
  }
121
+
110
122
  this.queries[name] = copyUiValue(value, new UiBudget(this.limits));
111
123
  this.changed();
112
124
  }
113
125
 
114
126
  run(action: UiExpression): void {
115
127
  const target = uiActionTarget(action, (name) => Object.hasOwn(this.defaults, name));
128
+
116
129
  if (target === null) {
117
130
  this.values = copyUiValue(this.defaults, new UiBudget(this.limits)) as Record<string, UiValue>;
118
131
  this.changed();
@@ -125,6 +138,7 @@ export class UiState {
125
138
 
126
139
  private changed(): void {
127
140
  this.revision += 1;
141
+
128
142
  for (const listener of this.listeners) {
129
143
  listener();
130
144
  }
@@ -135,17 +149,29 @@ export function evaluateUiBlock(block: UiBlock, state = new UiState(block), limi
135
149
  const budget = new UiBudget(limits);
136
150
  const result: UiEvaluation = { nodes: [], diagnostics: [] };
137
151
  const scope = state.scope();
152
+ const local = uiLocalState(block);
138
153
  let exhausted = false;
154
+
155
+ const report = (error: unknown, node: UiNode): void => {
156
+ if (result.diagnostics.length < budget.limits.diagnostics) {
157
+ result.diagnostics.push(uiDiagnostic(error, node.start, node.end, node.id));
158
+ }
159
+ };
160
+
139
161
  const children = (nodes: UiNode[], variables: Readonly<Record<string, UiValue>>, depth: number, suffix: string): UiViewNode[] => {
140
162
  const output: UiViewNode[] = [];
163
+
141
164
  for (const node of nodes) {
142
165
  if (exhausted) {
143
166
  break;
144
167
  }
168
+
145
169
  output.push(...visit(node, variables, depth, suffix));
146
170
  }
171
+
147
172
  return output;
148
173
  };
174
+
149
175
  const visit = (node: UiNode, variables: Readonly<Record<string, UiValue>>, depth: number, suffix = ''): UiViewNode[] => {
150
176
  const view: UiViewNode = {
151
177
  id: `${node.id}${suffix}`,
@@ -157,90 +183,114 @@ export function evaluateUiBlock(block: UiBlock, state = new UiState(block), limi
157
183
  complete: node.complete,
158
184
  fallback: node.fallback
159
185
  };
186
+
160
187
  try {
161
188
  budget.depth(depth);
162
189
  budget.node();
190
+
163
191
  if (block.catalogVersion !== UI_CATALOG_VERSION || node.error) {
164
192
  throw new UiFailure(node.error ?? 'unknown_catalog', 'This part uses an unsupported UI definition.');
165
193
  }
194
+
166
195
  const props: Record<string, UiValue> = copyUiValue(node.props, budget) as Record<string, UiValue>;
167
196
  const actionProp = uiActionProp(node.type);
197
+
168
198
  for (const [key, expression] of Object.entries(node.expressions)) {
169
199
  if (key !== actionProp) {
170
200
  props[key] = evaluateUiExpression(expression, variables, budget);
171
201
  }
172
202
  }
203
+
173
204
  if (node.type === '$text') {
174
205
  if (typeof props.text !== 'string' && typeof props.text !== 'number' && typeof props.text !== 'boolean' && props.text !== null) {
175
206
  throw new UiFailure('invalid_value', 'Text must be a scalar.');
176
207
  }
208
+
177
209
  view.props = { text: props.text === null ? '' : String(props.text) };
210
+
178
211
  return [view];
179
212
  }
213
+
180
214
  if (!isUiComponent(node.type)) {
181
215
  throw new UiFailure('unknown_component', `Unknown component ${node.type}.`);
182
216
  }
217
+
183
218
  const entry = UI_CATALOG[node.type];
184
219
  const parsed = entry.schema.safeParse(props);
220
+
185
221
  if (!parsed.success) {
186
222
  throw new UiFailure('invalid_props', parsed.error.issues.map((issue) => issue.message).join('; '));
187
223
  }
224
+
188
225
  view.props = parsed.data;
189
226
  const unreadable = node.complete && node.type === 'Event' ? unreadableEventTime(props.at) : null;
227
+
190
228
  // The compiler already warned about a time it could read from the source; this one waited on an Each or a query.
191
229
  if (
192
230
  unreadable !== null &&
193
231
  ![...block.diagnostics, ...result.diagnostics].some((item) => item.code === 'unreadable_time' && item.nodeId === node.id)
194
232
  ) {
195
- if (result.diagnostics.length < budget.limits.diagnostics) {
196
- result.diagnostics.push(uiDiagnostic(unreadable, node.start, node.end, node.id));
197
- }
233
+ report(unreadable, node);
198
234
  }
235
+
199
236
  if (node.type === 'Show') {
200
237
  return props.when ? children(node.children, variables, depth + 1, suffix) : [];
201
238
  }
239
+
202
240
  if (node.type === 'Each') {
203
241
  const items = props.items as UiValue[];
204
242
  const name = props.as as string;
205
243
  const expanded: UiViewNode[] = [];
206
244
  // Reserve all iterations before allocating children, including nested Each blocks.
207
245
  budget.iteration(items.length);
246
+
208
247
  for (let i = 0; i < items.length; i++) {
209
248
  for (const child of node.children) {
210
249
  expanded.push(...visit(child, { ...variables, [name]: items[i] }, depth + 1, `${suffix}:${i}`));
250
+
211
251
  if (exhausted) {
212
252
  throw new UiFailure('budget_exceeded', 'The repeated children exceeded their budget.');
213
253
  }
214
254
  }
215
255
  }
256
+
216
257
  return expanded;
217
258
  }
259
+
218
260
  const bindings: Record<string, UiBinding<unknown>> = Object.create(null);
261
+
219
262
  for (const [key, name] of Object.entries(node.bindings)) {
220
- if (!('binding' in entry) || entry.binding !== key || !uiLocalState(block)(name)) {
263
+ if (!('binding' in entry) || entry.binding !== key || !local(name)) {
221
264
  throw new UiFailure('refused_binding', 'The binding must target declared local input state.');
222
265
  }
266
+
223
267
  bindings[key] = {
224
268
  value: props[key],
225
269
  onValueChange(value: unknown) {
226
270
  if (!node.complete) {
227
271
  return;
228
272
  }
273
+
229
274
  const changed = entry.schema.safeParse({ ...props, [key]: value });
275
+
230
276
  if (changed.success) {
231
277
  state.set(name, value);
232
278
  }
233
279
  }
234
280
  };
235
281
  }
282
+
236
283
  view.bindings = bindings;
237
284
  const action = actionProp === undefined ? undefined : node.expressions[actionProp];
285
+
238
286
  if (action) {
239
- uiActionTarget(action, uiLocalState(block));
287
+ uiActionTarget(action, local);
288
+
240
289
  view.onAction = () => {
241
290
  if (!node.complete || props.disabled === true) {
242
291
  return;
243
292
  }
293
+
244
294
  try {
245
295
  state.run(action);
246
296
  } catch (error) {
@@ -251,48 +301,46 @@ export function evaluateUiBlock(block: UiBlock, state = new UiState(block), limi
251
301
  }
252
302
  };
253
303
  }
304
+
254
305
  view.children = children(node.children, variables, depth + 1, suffix);
306
+
255
307
  if ('count' in entry) {
256
308
  const limit = entry.count as { min: number; max?: number };
257
309
  const kinds = entry.children as readonly string[];
258
310
  const counted = view.children.filter((child) => kinds.includes(child.type)).length;
311
+
259
312
  // What an Each or a Show drew is only known now, so the count the compiler checked on the source is checked again.
260
313
  if (node.complete && counted < limit.min) {
261
314
  throw new UiFailure('invalid_props', `${node.type} needs at least ${limit.min} of ${kinds.join(' or ')}.`);
262
315
  }
316
+
263
317
  if (limit.max !== undefined && counted > limit.max) {
264
318
  let kept = 0;
265
319
  view.children = view.children.filter((child) => !kinds.includes(child.type) || ++kept <= limit.max!);
266
320
  view.omitted = counted - limit.max;
267
- if (result.diagnostics.length < budget.limits.diagnostics) {
268
- result.diagnostics.push(
269
- uiDiagnostic(
270
- new UiFailure('too_many_children', `${node.type} shows its first ${limit.max} of ${kinds.join(' or ')}.`),
271
- node.start,
272
- node.end,
273
- node.id
274
- )
275
- );
276
- }
321
+ report(new UiFailure('too_many_children', `${node.type} shows its first ${limit.max} of ${kinds.join(' or ')}.`), node);
277
322
  }
278
323
  }
324
+
279
325
  return [view];
280
326
  } catch (error) {
281
327
  if (error instanceof UiFailure && error.code === 'budget_exceeded') {
282
328
  exhausted = true;
283
329
  }
330
+
284
331
  view.error = error instanceof UiFailure ? error.code : 'invalid_value';
285
- if (result.diagnostics.length < budget.limits.diagnostics) {
286
- result.diagnostics.push(uiDiagnostic(error, node.start, node.end, node.id));
287
- }
332
+ report(error, node);
333
+
288
334
  return [view];
289
335
  }
290
336
  };
337
+
291
338
  try {
292
339
  result.nodes = children(block.nodes, scope, 0, '');
293
340
  } catch (error) {
294
341
  result.diagnostics = [uiDiagnostic(error, block.start, block.end)];
295
342
  }
343
+
296
344
  return result;
297
345
  }
298
346
 
@@ -306,6 +354,7 @@ export function uiInputValues(block: UiBlock, state: UiState): Record<string, Ui
306
354
  const scope = state.scope();
307
355
  const values: Record<string, UiValue> = Object.create(null);
308
356
  const local = uiLocalState(block);
357
+
309
358
  const actionTarget = (action: UiExpression): string | null => {
310
359
  try {
311
360
  return uiActionTarget(action, local);
@@ -313,29 +362,35 @@ export function uiInputValues(block: UiBlock, state: UiState): Record<string, Ui
313
362
  return null;
314
363
  }
315
364
  };
365
+
316
366
  const visit = (nodes: readonly UiNode[]) => {
317
367
  for (const node of nodes) {
318
368
  if (isUiComponent(node.type) && !node.error && node.complete) {
319
369
  const entry = UI_CATALOG[node.type];
370
+
320
371
  for (const [prop, name] of Object.entries(node.bindings)) {
321
372
  if ('binding' in entry && entry.binding === prop && local(name)) {
322
373
  values[name] = scope[name];
323
374
  }
324
375
  }
376
+
325
377
  const actionProp = uiActionProp(node.type);
326
378
  const target = actionProp && node.expressions[actionProp] ? actionTarget(node.expressions[actionProp]) : null;
379
+
327
380
  if (target !== null) {
328
381
  values[target] = scope[target];
329
382
  }
330
383
  }
384
+
331
385
  visit(node.children);
332
386
  }
333
387
  };
388
+
334
389
  visit(block.nodes);
390
+
335
391
  return values;
336
392
  }
337
393
 
338
- /* The host supplies its stored block; client data can change only declared inputs and Button targets. */
339
394
  function hasError(nodes: readonly UiViewNode[]): boolean {
340
395
  return nodes.some((node) => node.error !== undefined || hasError(node.children));
341
396
  }
@@ -352,9 +407,11 @@ export function uiChoiceLabel(choice: UiViewNode): string | null {
352
407
  if (choice.error !== undefined || !choice.complete || hasError(choice.children)) {
353
408
  return null;
354
409
  }
410
+
355
411
  return labelText(choice.children).replace(/\s+/g, ' ').trim() || null;
356
412
  }
357
413
 
414
+ /* The host supplies its stored block; client data can change only declared inputs and Button targets. */
358
415
  export function resolveUiChoice(
359
416
  block: UiBlock,
360
417
  choiceId: string,
@@ -365,55 +422,74 @@ export function resolveUiChoice(
365
422
  if (!block.complete || block.catalogVersion !== UI_CATALOG_VERSION) {
366
423
  throw new UiFailure('refused_choice', 'Only a completed supported block can send a choice.');
367
424
  }
425
+
368
426
  const values = copyUiValue(input, new UiBudget(limits)) as Record<string, UiValue>;
369
427
  const state = new UiState(block, limits);
428
+
370
429
  for (const [name, value] of Object.entries(queries)) {
371
430
  state.setQuery(name, value, block);
372
431
  }
432
+
373
433
  const allowed = uiInputValues(block, state);
374
434
  const changed = new Set<string>();
435
+
375
436
  for (const [name, value] of Object.entries(values)) {
376
437
  if (!Object.hasOwn(allowed, name)) {
377
438
  throw new UiFailure('refused_binding', 'Only declared input bindings can be submitted.');
378
439
  }
440
+
379
441
  if (!sameUiValue(value, allowed[name])) {
380
442
  state.set(name, value);
381
443
  changed.add(name);
382
444
  }
383
445
  }
446
+
384
447
  const evaluated = evaluateUiBlock(block, state, limits);
448
+
385
449
  if (evaluated.diagnostics.some((diagnostic) => diagnostic.code === 'budget_exceeded')) {
386
450
  throw new UiFailure('budget_exceeded', 'The choice exceeded its evaluation budget.');
387
451
  }
452
+
388
453
  let choice: UiViewNode | undefined;
389
454
  const written = uiCompiledNodes(block.nodes);
455
+
390
456
  const visit = (nodes: readonly UiViewNode[], parent?: string) => {
391
457
  for (const node of nodes) {
392
458
  const source = written.get(node.sourceId ?? node.id);
459
+
393
460
  if (node.error && source && Object.values(source.bindings).some((name) => changed.has(name))) {
394
461
  throw new UiFailure('invalid_value', 'An input value does not match its control.');
395
462
  }
463
+
396
464
  if (node.error || !node.complete) {
397
465
  continue;
398
466
  }
467
+
399
468
  if (node.id === choiceId && node.type === 'Choice' && parent === 'Choices' && node.props.disabled !== true) {
400
469
  choice = node;
401
470
  }
471
+
402
472
  visit(node.children, node.type);
403
473
  }
404
474
  };
475
+
405
476
  visit(evaluated.nodes);
406
477
  const validInputs = uiVisibleInputs(block, evaluated.nodes, state.scope());
478
+
407
479
  if ([...changed].some((name) => !validInputs.has(name))) {
408
480
  throw new UiFailure('invalid_value', 'An input value is outside the visible control’s allowed values.');
409
481
  }
482
+
410
483
  if (!choice) {
411
484
  throw new UiFailure('refused_choice', 'This choice is not available in the current block.');
412
485
  }
486
+
413
487
  const label = uiChoiceLabel(choice);
488
+
414
489
  if (label === null) {
415
490
  throw new UiFailure('refused_choice', hasError(choice.children) ? 'The choice label could not be fully read.' : 'A choice needs a visible label.');
416
491
  }
492
+
417
493
  return {
418
494
  label,
419
495
  values: uiInputValues(block, state),
package/src/stream.ts CHANGED
@@ -35,11 +35,15 @@ export class UiStream {
35
35
  if (this.closed) {
36
36
  return;
37
37
  }
38
+
38
39
  this.pending = { text, latestAttachment };
40
+
39
41
  if (this.timer !== null) {
40
42
  return;
41
43
  }
44
+
42
45
  const delay = Math.max(0, UI_STREAM_INTERVAL_MS - (this.options.clock.now() - this.lastCompiledAt));
46
+
43
47
  if (delay === 0) {
44
48
  this.flush();
45
49
  } else {
@@ -51,15 +55,18 @@ export class UiStream {
51
55
  this.dispose();
52
56
  const blocks = this.compiler.compile(text, { final: true, latestAttachment });
53
57
  this.compiler.clear();
58
+
54
59
  return blocks;
55
60
  }
56
61
 
57
62
  dispose(): void {
58
63
  this.closed = true;
64
+
59
65
  if (this.timer !== null) {
60
66
  this.options.clock.clearTimeout(this.timer.handle);
61
67
  this.timer = null;
62
68
  }
69
+
63
70
  this.pending = null;
64
71
  this.compiler.clear();
65
72
  }
@@ -67,9 +74,11 @@ export class UiStream {
67
74
  private flush(): void {
68
75
  this.timer = null;
69
76
  const pending = this.pending;
77
+
70
78
  if (pending === null || this.closed) {
71
79
  return;
72
80
  }
81
+
73
82
  this.pending = null;
74
83
  this.lastCompiledAt = this.options.clock.now();
75
84
  const blocks = this.compiler.compile(pending.text, { latestAttachment: pending.latestAttachment });