@praxisui/core 10.0.0-rc.7 → 10.0.0-rc.70

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.
@@ -1,3 +1,5 @@
1
+ import { InjectionToken } from '@angular/core';
2
+
1
3
  function normalizeFieldAccessMetadata(value) {
2
4
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
3
5
  return undefined;
@@ -88,6 +90,14 @@ const VISUALIZATION_KINDS = new Set([
88
90
  'bullet',
89
91
  'delta',
90
92
  'processFlow',
93
+ 'waterfall',
94
+ ]);
95
+ const WATERFALL_ROLES = new Set([
96
+ 'start',
97
+ 'increase',
98
+ 'decrease',
99
+ 'subtotal',
100
+ 'total',
91
101
  ]);
92
102
  const VISUALIZATION_SURFACES = new Set([
93
103
  'table-cell',
@@ -111,6 +121,10 @@ const VISUALIZATION_TONES = new Set([
111
121
  'danger',
112
122
  'critical',
113
123
  ]);
124
+ const VISUALIZATION_SCALE_SCOPES = new Set([
125
+ 'row',
126
+ 'page',
127
+ ]);
114
128
  const TABLE_SAFE_KINDS = new Set([
115
129
  'line',
116
130
  'area',
@@ -122,6 +136,7 @@ const TABLE_SAFE_KINDS = new Set([
122
136
  'bullet',
123
137
  'delta',
124
138
  'processFlow',
139
+ 'waterfall',
125
140
  ]);
126
141
  const TABLE_CELL_RECOMMENDED_KINDS = new Set([
127
142
  'delta',
@@ -143,7 +158,7 @@ function getPraxisTableCellVisualizationConstraint(kind) {
143
158
  return 'row-density';
144
159
  if (kind === 'processFlow')
145
160
  return 'step-labels';
146
- if (kind === 'line' || kind === 'area' || kind === 'column') {
161
+ if (kind === 'line' || kind === 'area' || kind === 'column' || kind === 'waterfall') {
147
162
  return 'horizontal-space';
148
163
  }
149
164
  return null;
@@ -163,8 +178,8 @@ function resolvePraxisMicroVisualizationTone(value, thresholds, fallbackTone) {
163
178
  if (value === undefined || value === null || !Array.isArray(thresholds) || thresholds.length === 0) {
164
179
  return fallbackTone ? { tone: fallbackTone } : undefined;
165
180
  }
166
- const num = typeof value === 'number' ? value : Number(value);
167
- const isNum = Number.isFinite(num);
181
+ const num = toFiniteNumber(value);
182
+ const isNum = num !== undefined;
168
183
  // 1. Pass 1: Correspondencia discreta (equals) tem prioridade maxima
169
184
  for (const t of thresholds) {
170
185
  if (!t || !t.tone || t.equals === undefined) {
@@ -173,7 +188,8 @@ function resolvePraxisMicroVisualizationTone(value, thresholds, fallbackTone) {
173
188
  if (t.equals === value || String(t.equals) === String(value)) {
174
189
  return { tone: t.tone, label: t.label, matchedThreshold: t };
175
190
  }
176
- if (isNum && Number.isFinite(Number(t.equals)) && Number(t.equals) === num) {
191
+ const eqNum = toFiniteNumber(t.equals);
192
+ if (isNum && eqNum !== undefined && eqNum === num) {
177
193
  return { tone: t.tone, label: t.label, matchedThreshold: t };
178
194
  }
179
195
  }
@@ -207,6 +223,313 @@ function resolvePraxisMicroVisualizationTone(value, thresholds, fallbackTone) {
207
223
  }
208
224
  return fallbackTone ? { tone: fallbackTone } : undefined;
209
225
  }
226
+ const STACKED_BAR_TONE_PAINT = {
227
+ info: 'var(--prx-micro-tone-info, var(--p-table-state-info-fg, var(--md-sys-color-primary, #0a6eb4)))',
228
+ success: 'var(--prx-micro-tone-success, var(--p-table-state-success-fg, #1b7a43))',
229
+ warning: 'var(--prx-micro-tone-warning, var(--p-table-state-warning-fg, #92400e))',
230
+ danger: 'var(--prx-micro-tone-danger, var(--p-table-state-danger-fg, var(--md-sys-color-error, #c62828)))',
231
+ critical: 'var(--prx-micro-tone-critical, var(--prx-micro-tone-danger, var(--p-table-state-danger-fg, var(--md-sys-color-error, #9f1239))))',
232
+ neutral: 'var(--prx-micro-tone-neutral, var(--md-sys-color-secondary, #5c6b73))',
233
+ };
234
+ function normalizePraxisHexColor(value) {
235
+ if (typeof value !== 'string') {
236
+ return undefined;
237
+ }
238
+ const trimmed = value.trim();
239
+ const match = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(trimmed);
240
+ if (!match) {
241
+ return undefined;
242
+ }
243
+ const raw = match[1].toLowerCase();
244
+ if (raw.length === 3) {
245
+ return `#${raw[0]}${raw[0]}${raw[1]}${raw[1]}${raw[2]}${raw[2]}`;
246
+ }
247
+ return `#${raw}`;
248
+ }
249
+ function getPraxisStackedBarPaintStyle(segment, fallbackTone = 'neutral') {
250
+ const hex = normalizePraxisHexColor(segment?.color);
251
+ const resolvedTone = normalizeEnum$1(segment?.tone, VISUALIZATION_TONES) ??
252
+ normalizeEnum$1(fallbackTone, VISUALIZATION_TONES) ??
253
+ 'neutral';
254
+ const paint = hex ?? STACKED_BAR_TONE_PAINT[resolvedTone];
255
+ return {
256
+ '--prx-micro-category-color': paint,
257
+ color: paint,
258
+ };
259
+ }
260
+ function isVisualizationEntrySuppressed(entry) {
261
+ if (!entry || typeof entry !== 'object') {
262
+ return false;
263
+ }
264
+ const obj = entry;
265
+ return (obj.suppressed === true
266
+ || obj.privacySuppressed === true
267
+ || (obj.value === null && obj.state === 'suppressed'));
268
+ }
269
+ function countSuppressedEntries(entries) {
270
+ if (!Array.isArray(entries)) {
271
+ return 0;
272
+ }
273
+ let count = 0;
274
+ for (const entry of entries) {
275
+ if (isVisualizationEntrySuppressed(entry)) {
276
+ count += 1;
277
+ }
278
+ }
279
+ return count;
280
+ }
281
+ function resolvePreservedSuppressedCount(value) {
282
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
283
+ ? Math.trunc(value)
284
+ : 0;
285
+ }
286
+ function resolvePraxisStackedBarSegments(visualization) {
287
+ if (!visualization || visualization.kind !== 'stackedBar') {
288
+ return [];
289
+ }
290
+ if (Array.isArray(visualization.segments) && visualization.segments.length > 0) {
291
+ return visualization.segments.filter((seg) => !isVisualizationEntrySuppressed(seg));
292
+ }
293
+ if (Array.isArray(visualization.items) && visualization.items.length > 0) {
294
+ const mapped = [];
295
+ for (let i = 0; i < visualization.items.length; i++) {
296
+ if (!Object.prototype.hasOwnProperty.call(visualization.items, i)) {
297
+ return [];
298
+ }
299
+ const item = visualization.items[i];
300
+ if (!item) {
301
+ return [];
302
+ }
303
+ if (isVisualizationEntrySuppressed(item)) {
304
+ continue;
305
+ }
306
+ if (typeof item.value !== 'number' || !Number.isFinite(item.value) || item.value < 0) {
307
+ return [];
308
+ }
309
+ const hex = normalizePraxisHexColor(item.color);
310
+ mapped.push({
311
+ value: item.value,
312
+ ...(item.label ? { label: item.label } : {}),
313
+ ...(item.tone ? { tone: item.tone } : {}),
314
+ ...(hex ? { color: hex } : {}),
315
+ });
316
+ }
317
+ return mapped;
318
+ }
319
+ return [];
320
+ }
321
+ function resolvePraxisStackedBarTotal(segments, explicitTotal) {
322
+ if (typeof explicitTotal === 'number' && Number.isFinite(explicitTotal) && explicitTotal >= 0) {
323
+ return explicitTotal;
324
+ }
325
+ return compensatedSum(segments.map((segment) => segment.value));
326
+ }
327
+ function computePraxisStackedBarSegmentWidthPct(value, resolvedTotal) {
328
+ if (!Number.isFinite(value) || value <= 0 || !Number.isFinite(resolvedTotal) || resolvedTotal <= 0) {
329
+ return 0;
330
+ }
331
+ return Math.max(0, Math.min(100, (value / resolvedTotal) * 100));
332
+ }
333
+ function formatPraxisStackedBarPercentage(value, resolvedTotal, locale) {
334
+ const pct = computePraxisStackedBarSegmentWidthPct(value, resolvedTotal);
335
+ const maximumFractionDigits = pct === 0 ? 0 : pct < 0.1 ? 3 : pct < 1 ? 2 : 1;
336
+ return `${new Intl.NumberFormat(locale || undefined, { maximumFractionDigits }).format(pct)}%`;
337
+ }
338
+ function resolvePraxisStackedBarAriaLabel(visualization, segments, resolvedTotal, locale) {
339
+ if (visualization.ariaLabel) {
340
+ return visualization.ariaLabel;
341
+ }
342
+ if (segments.length > 0 &&
343
+ segments.every((segment) => typeof segment.label === 'string' && segment.label.trim().length > 0)) {
344
+ const prefix = visualization.title || visualization.fallbackText;
345
+ const summary = segments
346
+ .map((segment) => `${segment.label} ${formatPraxisStackedBarPercentage(segment.value, resolvedTotal, locale)}`)
347
+ .join(', ');
348
+ return `${prefix}: ${summary}`;
349
+ }
350
+ return visualization.fallbackText;
351
+ }
352
+ function compensatedSum(values) {
353
+ let sum = 0;
354
+ let compensation = 0;
355
+ for (let i = 0; i < values.length; i++) {
356
+ const value = values[i];
357
+ const next = sum + value;
358
+ if (Math.abs(sum) >= Math.abs(value)) {
359
+ compensation += (sum - next) + value;
360
+ }
361
+ else {
362
+ compensation += (value - next) + sum;
363
+ }
364
+ sum = next;
365
+ }
366
+ return sum + compensation;
367
+ }
368
+ function normalizeStackedBarDistribution(value, surface) {
369
+ const isTableCell = surface === 'table-cell';
370
+ const hasSegmentsProp = value.segments !== undefined;
371
+ const hasItemsProp = value.items !== undefined;
372
+ const hasExplicitTotalProp = Object.prototype.hasOwnProperty.call(value, 'total') &&
373
+ value.total !== undefined &&
374
+ value.total !== null;
375
+ const hasDeferredExpr = Boolean(normalizeExpression(value.segmentsExpr, 'segmentsExpr') ||
376
+ normalizeExpression(value.itemsExpr, 'itemsExpr'));
377
+ const rawTitle = isTableCell ? undefined : normalizeText$1(value.title);
378
+ if (!hasSegmentsProp && !hasItemsProp) {
379
+ const explicitTotal = hasExplicitTotalProp ? toFiniteNumber(value.total) : undefined;
380
+ const validDeferredTotal = !hasExplicitTotalProp || (explicitTotal !== undefined && explicitTotal >= 0);
381
+ if (!validDeferredTotal) {
382
+ return {
383
+ valid: false,
384
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
385
+ };
386
+ }
387
+ if (!isTableCell && value.legend === true && !hasDeferredExpr) {
388
+ return {
389
+ valid: false,
390
+ legend: false,
391
+ };
392
+ }
393
+ return {
394
+ valid: hasDeferredExpr,
395
+ ...(explicitTotal !== undefined ? { total: explicitTotal } : {}),
396
+ ...(rawTitle && hasDeferredExpr ? { title: rawTitle } : {}),
397
+ ...(typeof value.legend === 'boolean'
398
+ ? { legend: isTableCell ? false : value.legend }
399
+ : {}),
400
+ };
401
+ }
402
+ const rawEntries = hasSegmentsProp ? value.segments : value.items;
403
+ if (!Array.isArray(rawEntries) || rawEntries.length === 0) {
404
+ return {
405
+ valid: false,
406
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
407
+ };
408
+ }
409
+ const parsedSegments = [];
410
+ const parsedItems = [];
411
+ const preservedSuppressedCount = resolvePreservedSuppressedCount(value.suppressedCount);
412
+ let suppressedCount = 0;
413
+ for (let i = 0; i < rawEntries.length; i++) {
414
+ if (!Object.prototype.hasOwnProperty.call(rawEntries, i)) {
415
+ return {
416
+ valid: false,
417
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
418
+ };
419
+ }
420
+ const rawEntry = rawEntries[i];
421
+ if (typeof rawEntry === 'number' || typeof rawEntry === 'string') {
422
+ const num = toFiniteNumber(rawEntry);
423
+ if (num === undefined || num < 0) {
424
+ return {
425
+ valid: false,
426
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
427
+ };
428
+ }
429
+ parsedSegments.push({ value: num });
430
+ parsedItems.push({ value: num });
431
+ continue;
432
+ }
433
+ if (!rawEntry || typeof rawEntry !== 'object') {
434
+ return {
435
+ valid: false,
436
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
437
+ };
438
+ }
439
+ const entryObj = rawEntry;
440
+ if (isVisualizationEntrySuppressed(entryObj)) {
441
+ suppressedCount += 1;
442
+ continue;
443
+ }
444
+ const num = toFiniteNumber(entryObj.value);
445
+ if (num === undefined || num < 0) {
446
+ return {
447
+ valid: false,
448
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
449
+ };
450
+ }
451
+ const label = normalizeText$1(entryObj.label);
452
+ const entryTone = normalizeEnum$1(entryObj.tone, VISUALIZATION_TONES);
453
+ const entryColor = normalizePraxisHexColor(entryObj.color);
454
+ const id = normalizeText$1(entryObj.id);
455
+ const icon = normalizeText$1(entryObj.icon);
456
+ const state = normalizeText$1(entryObj.state);
457
+ parsedSegments.push({
458
+ value: num,
459
+ ...(label ? { label } : {}),
460
+ ...(entryTone ? { tone: entryTone } : {}),
461
+ ...(entryColor ? { color: entryColor } : {}),
462
+ });
463
+ parsedItems.push({
464
+ value: num,
465
+ ...(id ? { id } : {}),
466
+ ...(label ? { label } : {}),
467
+ ...(icon ? { icon } : {}),
468
+ ...(state ? { state } : {}),
469
+ ...(entryTone ? { tone: entryTone } : {}),
470
+ ...(entryColor ? { color: entryColor } : {}),
471
+ });
472
+ }
473
+ const effectiveSuppressedCount = Math.max(preservedSuppressedCount, suppressedCount);
474
+ if (parsedSegments.length === 0) {
475
+ return {
476
+ valid: false,
477
+ ...(effectiveSuppressedCount > 0 ? { suppressedCount: effectiveSuppressedCount } : {}),
478
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
479
+ };
480
+ }
481
+ const sum = compensatedSum(parsedSegments.map((entry) => entry.value));
482
+ if (!Number.isFinite(sum) || sum < 0) {
483
+ return {
484
+ valid: false,
485
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
486
+ };
487
+ }
488
+ let validatedTotal;
489
+ if (hasExplicitTotalProp) {
490
+ const explicitTotal = toFiniteNumber(value.total);
491
+ if (explicitTotal === undefined || !Number.isFinite(explicitTotal) || explicitTotal < 0) {
492
+ return {
493
+ valid: false,
494
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
495
+ };
496
+ }
497
+ if (explicitTotal === 0 && sum > 0) {
498
+ return {
499
+ valid: false,
500
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
501
+ };
502
+ }
503
+ if (explicitTotal > 0) {
504
+ const tolerance = Math.max(4, parsedSegments.length) * Number.EPSILON * Math.max(sum, explicitTotal);
505
+ if (sum - explicitTotal > tolerance) {
506
+ return {
507
+ valid: false,
508
+ ...(typeof value.legend === 'boolean' ? { legend: false } : {}),
509
+ };
510
+ }
511
+ }
512
+ validatedTotal = explicitTotal;
513
+ }
514
+ const normalizedLegend = typeof value.legend === 'boolean' ? (isTableCell ? false : value.legend) : undefined;
515
+ if (!isTableCell && normalizedLegend === true) {
516
+ const allLabeled = parsedSegments.every((entry) => typeof entry.label === 'string' && entry.label.length > 0);
517
+ if (!allLabeled) {
518
+ return {
519
+ valid: false,
520
+ legend: false,
521
+ };
522
+ }
523
+ }
524
+ return {
525
+ valid: true,
526
+ ...(hasSegmentsProp ? { segments: parsedSegments } : { items: parsedItems }),
527
+ ...(validatedTotal !== undefined ? { total: validatedTotal } : {}),
528
+ ...(effectiveSuppressedCount > 0 ? { suppressedCount: effectiveSuppressedCount } : {}),
529
+ ...(rawTitle ? { title: rawTitle } : {}),
530
+ ...(normalizedLegend !== undefined ? { legend: normalizedLegend } : {}),
531
+ };
532
+ }
210
533
  function normalizePraxisPresentationVisualization(value) {
211
534
  if (!value || typeof value !== 'object') {
212
535
  return undefined;
@@ -218,23 +541,30 @@ function normalizePraxisPresentationVisualization(value) {
218
541
  }
219
542
  const surface = normalizeEnum$1(value.surface, VISUALIZATION_SURFACES);
220
543
  const size = normalizeEnum$1(value.size, VISUALIZATION_SIZES);
544
+ const scaleScope = normalizeEnum$1(value.scaleScope, VISUALIZATION_SCALE_SCOPES);
221
545
  const tone = normalizeEnum$1(value.tone, VISUALIZATION_TONES);
222
546
  const ariaLabel = normalizeText$1(value.ariaLabel);
223
547
  const valueSuffix = normalizeText$1(value.valueSuffix);
548
+ const normalizedTargetLabel = normalizeText$1(value.targetLabel);
224
549
  const thresholdsObj = normalizeThresholds(value.thresholds);
550
+ const isTableCell = surface === 'table-cell';
551
+ const normalizedPointsObj = normalizePoints(value.points);
225
552
  let resolvedTone = tone;
226
553
  let resolvedAriaLabel = ariaLabel;
227
554
  if (!resolvedTone && thresholdsObj?.thresholds?.length) {
228
555
  let evalVal = value.value;
229
- if (evalVal === undefined && Array.isArray(value.points) && value.points.length > 0) {
230
- const last = value.points[value.points.length - 1];
231
- if (last && typeof last === 'object' && Number.isFinite(last.value)) {
232
- evalVal = last.value;
233
- }
556
+ if (evalVal === undefined && normalizedPointsObj?.points?.length) {
557
+ evalVal = normalizedPointsObj.points[normalizedPointsObj.points.length - 1].value;
234
558
  }
235
559
  else if (Array.isArray(evalVal) && evalVal.length > 0) {
236
- const last = evalVal[evalVal.length - 1];
237
- evalVal = typeof last === 'object' && last !== null && 'value' in last ? last.value : last;
560
+ const visibleVals = evalVal.filter((entry) => !isVisualizationEntrySuppressed(entry));
561
+ if (visibleVals.length > 0) {
562
+ const last = visibleVals[visibleVals.length - 1];
563
+ evalVal = typeof last === 'object' && last !== null && 'value' in last ? last.value : last;
564
+ }
565
+ else {
566
+ evalVal = undefined;
567
+ }
238
568
  }
239
569
  if (evalVal !== undefined && evalVal !== null) {
240
570
  const resolution = resolvePraxisMicroVisualizationTone(evalVal, thresholdsObj.thresholds);
@@ -246,11 +576,71 @@ function normalizePraxisPresentationVisualization(value) {
246
576
  }
247
577
  }
248
578
  }
579
+ if (kind === 'stackedBar') {
580
+ const stacked = normalizeStackedBarDistribution(value, surface);
581
+ const stackedSuppressedCount = Math.max(stacked.suppressedCount ?? 0, countSuppressedEntries(value.points));
582
+ return {
583
+ kind,
584
+ fallbackText,
585
+ ...(surface ? { surface } : {}),
586
+ ...(size ? { size } : {}),
587
+ ...(scaleScope ? { scaleScope } : {}),
588
+ ...(stacked.title ? { title: stacked.title } : {}),
589
+ ...(normalizeExpression(value.titleExpr, 'titleExpr') ?? {}),
590
+ ...(stacked.legend !== undefined ? { legend: stacked.legend } : {}),
591
+ ...(resolvedTone ? { tone: resolvedTone } : {}),
592
+ ...(resolvedAriaLabel ? { ariaLabel: resolvedAriaLabel } : {}),
593
+ ...(valueSuffix ? { valueSuffix } : {}),
594
+ ...(typeof value.compactValue === 'boolean' ? { compactValue: value.compactValue } : {}),
595
+ ...(Object.prototype.hasOwnProperty.call(value, 'value') ? { value: value.value } : {}),
596
+ ...(normalizeExpression(value.valueExpr, 'valueExpr') ?? {}),
597
+ ...(normalizeExpression(value.valueSuffixExpr, 'valueSuffixExpr') ?? {}),
598
+ ...(normalizeNumber(value.min, 'min') ?? {}),
599
+ ...(normalizeExpression(value.minExpr, 'minExpr') ?? {}),
600
+ ...(normalizeNumber(value.max, 'max') ?? {}),
601
+ ...(normalizeExpression(value.maxExpr, 'maxExpr') ?? {}),
602
+ ...(stacked.total !== undefined ? { total: stacked.total } : {}),
603
+ ...(normalizeExpression(value.totalExpr, 'totalExpr') ?? {}),
604
+ ...(normalizeNumber(value.target, 'target') ?? {}),
605
+ ...(normalizeExpression(value.targetExpr, 'targetExpr') ?? {}),
606
+ ...(normalizedTargetLabel ? { targetLabel: normalizedTargetLabel } : {}),
607
+ ...(normalizeExpression(value.targetLabelExpr, 'targetLabelExpr') ?? {}),
608
+ ...(normalizeNumber(value.baseline, 'baseline') ?? {}),
609
+ ...(normalizeExpression(value.baselineExpr, 'baselineExpr') ?? {}),
610
+ ...(normalizedPointsObj ?? {}),
611
+ ...(normalizeExpression(value.pointsExpr, 'pointsExpr') ?? {}),
612
+ ...(stacked.segments ? { segments: stacked.segments } : {}),
613
+ ...(normalizeExpression(value.segmentsExpr, 'segmentsExpr') ?? {}),
614
+ ...(normalizeThresholds(value.thresholds) ?? {}),
615
+ ...(normalizeExpression(value.thresholdsExpr, 'thresholdsExpr') ?? {}),
616
+ ...(stacked.items ? { items: stacked.items } : {}),
617
+ ...(stackedSuppressedCount > 0 ? { suppressedCount: stackedSuppressedCount } : {}),
618
+ ...(normalizeExpression(value.itemsExpr, 'itemsExpr') ?? {}),
619
+ ...(normalizeExpression(value.toneExpr, 'toneExpr') ?? {}),
620
+ ...(value.stepLabelWidth !== undefined && (typeof value.stepLabelWidth === 'number' || typeof value.stepLabelWidth === 'string')
621
+ ? { stepLabelWidth: value.stepLabelWidth }
622
+ : {}),
623
+ ...(typeof value.stepLabelLineClamp === 'number' && Number.isFinite(value.stepLabelLineClamp)
624
+ ? { stepLabelLineClamp: value.stepLabelLineClamp }
625
+ : {}),
626
+ ...(normalizeExpression(value.ariaLabelExpr, 'ariaLabelExpr') ?? {}),
627
+ ...(normalizeExpression(value.fallbackTextExpr, 'fallbackTextExpr') ?? {}),
628
+ };
629
+ }
630
+ const normalizedTitle = isTableCell ? undefined : normalizeText$1(value.title);
631
+ const normalizedLegend = typeof value.legend === 'boolean' ? (isTableCell ? false : value.legend) : undefined;
632
+ const suppressedCount = Math.max(resolvePreservedSuppressedCount(value.suppressedCount), countSuppressedEntries(value.points)
633
+ + countSuppressedEntries(value.items)
634
+ + countSuppressedEntries(value.segments));
249
635
  return {
250
636
  kind,
251
637
  fallbackText,
252
638
  ...(surface ? { surface } : {}),
253
639
  ...(size ? { size } : {}),
640
+ ...(scaleScope ? { scaleScope } : {}),
641
+ ...(normalizedTitle ? { title: normalizedTitle } : {}),
642
+ ...(normalizeExpression(value.titleExpr, 'titleExpr') ?? {}),
643
+ ...(normalizedLegend !== undefined ? { legend: normalizedLegend } : {}),
254
644
  ...(resolvedTone ? { tone: resolvedTone } : {}),
255
645
  ...(resolvedAriaLabel ? { ariaLabel: resolvedAriaLabel } : {}),
256
646
  ...(valueSuffix ? { valueSuffix } : {}),
@@ -258,19 +648,26 @@ function normalizePraxisPresentationVisualization(value) {
258
648
  ...(Object.prototype.hasOwnProperty.call(value, 'value') ? { value: value.value } : {}),
259
649
  ...(normalizeExpression(value.valueExpr, 'valueExpr') ?? {}),
260
650
  ...(normalizeExpression(value.valueSuffixExpr, 'valueSuffixExpr') ?? {}),
651
+ ...(normalizeNumber(value.min, 'min') ?? {}),
652
+ ...(normalizeExpression(value.minExpr, 'minExpr') ?? {}),
653
+ ...(normalizeNumber(value.max, 'max') ?? {}),
654
+ ...(normalizeExpression(value.maxExpr, 'maxExpr') ?? {}),
261
655
  ...(normalizeNumber(value.total, 'total') ?? {}),
262
656
  ...(normalizeExpression(value.totalExpr, 'totalExpr') ?? {}),
263
657
  ...(normalizeNumber(value.target, 'target') ?? {}),
264
658
  ...(normalizeExpression(value.targetExpr, 'targetExpr') ?? {}),
659
+ ...(normalizedTargetLabel ? { targetLabel: normalizedTargetLabel } : {}),
660
+ ...(normalizeExpression(value.targetLabelExpr, 'targetLabelExpr') ?? {}),
265
661
  ...(normalizeNumber(value.baseline, 'baseline') ?? {}),
266
662
  ...(normalizeExpression(value.baselineExpr, 'baselineExpr') ?? {}),
267
- ...(normalizePoints(value.points) ?? {}),
663
+ ...(normalizedPointsObj ?? {}),
268
664
  ...(normalizeExpression(value.pointsExpr, 'pointsExpr') ?? {}),
269
665
  ...(normalizeSegments(value.segments) ?? {}),
270
666
  ...(normalizeExpression(value.segmentsExpr, 'segmentsExpr') ?? {}),
271
667
  ...(normalizeThresholds(value.thresholds) ?? {}),
272
668
  ...(normalizeExpression(value.thresholdsExpr, 'thresholdsExpr') ?? {}),
273
669
  ...(normalizeItems(value.items) ?? {}),
670
+ ...(suppressedCount > 0 ? { suppressedCount } : {}),
274
671
  ...(normalizeExpression(value.itemsExpr, 'itemsExpr') ?? {}),
275
672
  ...(normalizeExpression(value.toneExpr, 'toneExpr') ?? {}),
276
673
  ...(value.stepLabelWidth !== undefined && (typeof value.stepLabelWidth === 'number' || typeof value.stepLabelWidth === 'string')
@@ -287,202 +684,63 @@ function isPraxisPresentationVisualizationTableSafe(value) {
287
684
  const normalized = normalizePraxisPresentationVisualization(value);
288
685
  return !!normalized && TABLE_SAFE_KINDS.has(normalized.kind);
289
686
  }
290
- function renderPraxisPresentationVisualizationHtml(value, options = {}) {
291
- const visualization = normalizePraxisPresentationVisualization(value);
292
- if (!visualization) {
293
- return '';
294
- }
295
- switch (visualization.kind) {
296
- case 'comparison':
297
- return renderComparisonVisualizationHtml(visualization, options);
298
- case 'stackedBar':
299
- return renderStackedBarVisualizationHtml(visualization, options);
300
- case 'bullet':
301
- return renderBulletVisualizationHtml(visualization, options);
302
- case 'delta':
303
- return renderDeltaVisualizationHtml(visualization, options);
304
- case 'radial':
305
- return renderRadialVisualizationHtml(visualization, options);
306
- case 'harveyBall':
307
- return renderHarveyBallVisualizationHtml(visualization, options);
308
- case 'line':
309
- return renderLineVisualizationHtml(visualization, options);
310
- case 'area':
311
- return renderAreaVisualizationHtml(visualization, options);
312
- case 'column':
313
- return renderColumnVisualizationHtml(visualization, options);
314
- case 'processFlow':
315
- return renderProcessFlowVisualizationHtml(visualization, options);
687
+ /**
688
+ * Returns a luminous 3-stop directional color ramp (`[highlight, mid, deep]`)
689
+ * for radial arcs, sector dials, and precision micro-visualizations.
690
+ */
691
+ function getPraxisMicroToneGradientStops(tone) {
692
+ switch (tone) {
693
+ case 'success':
694
+ return ['#bef264', '#22c55e', '#15803d'];
695
+ case 'info':
696
+ return ['#93c5fd', '#3b82f6', '#3730a3'];
697
+ case 'warning':
698
+ return ['#fde047', '#f59e0b', '#b45309'];
699
+ case 'danger':
700
+ case 'critical':
701
+ return ['#fda4af', '#f43f5e', '#be123c'];
702
+ case 'neutral':
316
703
  default:
317
- return `<span class="pfx-micro-viz__fallback">${escapeHtml(visualization.fallbackText)}</span>`;
318
- }
319
- }
320
- function renderComparisonVisualizationHtml(visualization, options) {
321
- const points = visualization.points ?? [];
322
- if (points.length === 0) {
323
- return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
324
- }
325
- const max = Math.max(1, ...points.map((point) => Math.max(0, point.value)));
326
- const rows = points
327
- .map((point) => {
328
- const width = percent(point.value, max);
329
- return `
330
- <span class="pfx-micro-viz__row" data-tone="${escapeHtml(point.tone ?? visualization.tone ?? 'info')}">
331
- <span class="pfx-micro-viz__label">${escapeHtml(point.label ?? '')}</span>
332
- <span class="pfx-micro-viz__track">
333
- <span class="pfx-micro-viz__bar" style="width:${width}%"></span>
334
- </span>
335
- <span class="pfx-micro-viz__value">${escapeHtml(formatMicroNumber(point.value, options.locale))}</span>
336
- </span>`;
337
- })
338
- .join('');
339
- return `<span class="pfx-micro-viz" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">${rows}</span>`;
340
- }
341
- function renderStackedBarVisualizationHtml(visualization, options) {
342
- const segments = visualization.segments ?? [];
343
- if (segments.length === 0) {
344
- return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
345
- }
346
- const total = visualization.total && visualization.total > 0
347
- ? visualization.total
348
- : Math.max(1, segments.reduce((sum, segment) => sum + Math.max(0, segment.value), 0));
349
- const bars = segments
350
- .map((segment) => `
351
- <span
352
- class="pfx-micro-viz__segment"
353
- data-tone="${escapeHtml(segment.tone ?? visualization.tone ?? 'info')}"
354
- style="width:${percent(segment.value, total)}%"
355
- title="${escapeHtml(`${segment.label ?? ''} ${formatMicroNumber(segment.value, options.locale)}`.trim())}"
356
- ></span>`)
357
- .join('');
358
- const meta = segments
359
- .slice(0, 3)
360
- .map((segment) => `<span>${escapeHtml(segment.label ?? '')}: ${escapeHtml(formatMicroNumber(segment.value, options.locale))}</span>`)
361
- .join('');
362
- return `
363
- <span class="pfx-micro-viz" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
364
- <span class="pfx-micro-viz__segments">${bars}</span>
365
- <span class="pfx-micro-viz__meta">${meta}</span>
366
- </span>`;
367
- }
368
- function resolveBulletMax(visualization) {
369
- const thresholds = visualization.thresholds ?? [];
370
- const thresholdValues = thresholds
371
- .map(t => t.value ?? t.max ?? t.min ?? 0)
372
- .filter((v) => Number.isFinite(v) && v > 0);
373
- const values = [
374
- toFiniteNumber(visualization.value) ?? 0,
375
- visualization.target ?? 0,
376
- visualization.total ?? 0,
377
- ...thresholdValues
378
- ].filter((v) => Number.isFinite(v) && v > 0);
379
- return Math.max(...values, 100);
380
- }
381
- function renderBulletVisualizationHtml(visualization, options) {
382
- const currentValue = toFiniteNumber(visualization.value);
383
- if (currentValue === undefined) {
384
- return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
385
- }
386
- const max = resolveBulletMax(visualization);
387
- const target = toFiniteNumber(visualization.target);
388
- const targetLeft = target === undefined ? null : percent(target, max);
389
- const isTable = visualization.surface === 'table-cell';
390
- // thresholds: sort ascending by boundary value so bands draw continuously regardless of declaration order
391
- const thresholds = visualization.thresholds ?? [];
392
- const sortedThresholds = [...thresholds].sort((a, b) => {
393
- const aVal = a.value ?? a.max ?? a.min ?? 0;
394
- const bVal = b.value ?? b.max ?? b.min ?? 0;
395
- return aVal - bVal;
396
- });
397
- let previous = 0;
398
- const bands = sortedThresholds.map(t => {
399
- const tVal = t.value ?? t.max ?? t.min ?? 0;
400
- const current = Math.max(tVal, previous);
401
- const left = max > 0 ? percent(previous, max) : '0';
402
- const width = max > 0 ? percent(current - previous, max) : '0';
403
- previous = current;
404
- return { left, width, tone: t.tone ?? 'info' };
405
- }).filter(b => parseFloat(b.width) > 0);
406
- const bandsHtml = bands.map(b => `<span class="pfx-micro-bullet__range" data-tone="${escapeHtml(b.tone)}" style="left: ${b.left}%; width: ${b.width}%;"></span>`).join('');
407
- const topHtml = isTable ? '' : `
408
- <div class="pfx-micro-bullet__top">
409
- <span class="pfx-micro-bullet__label">${escapeHtml(visualization.fallbackText)}</span>
410
- <span class="pfx-micro-bullet__value">
411
- ${escapeHtml(formatMicroNumber(currentValue, options.locale))}
412
- ${target === undefined ? '' : `<span class="pfx-micro-bullet__target-val">/ Target: ${escapeHtml(formatMicroNumber(target, options.locale))}</span>`}
413
- </span>
414
- </div>`;
415
- const bottomHtml = isTable ? '' : `
416
- <div class="pfx-micro-bullet__bottom">
417
- <span>${escapeHtml(formatMicroNumber(visualization.baseline ?? 0, options.locale))}</span>
418
- <span>${escapeHtml(formatMicroNumber(max, options.locale))}</span>
419
- </div>`;
420
- const showCompactValue = isTable && visualization.compactValue !== false;
421
- const compactValueHtml = showCompactValue
422
- ? `<span class="pfx-micro-bullet__compact-value">${escapeHtml(formatMicroNumber(currentValue, options.locale))}${escapeHtml(visualization.valueSuffix ?? '')}</span>`
423
- : '';
424
- return `
425
- <span class="pfx-micro-viz pfx-micro-viz__bullet" data-tone="${escapeHtml(visualization.tone ?? 'info')}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
426
- ${topHtml}
427
- <span class="pfx-micro-bullet__track">
428
- ${bandsHtml}
429
- <span class="pfx-micro-bullet__actual" data-tone="${escapeHtml(visualization.tone ?? 'info')}" style="width: ${percent(currentValue, max)}%;"></span>
430
- ${targetLeft === null ? '' : `<span class="pfx-micro-bullet__target" style="left: ${targetLeft}%;"></span>`}
431
- </span>
432
- ${bottomHtml}
433
- ${compactValueHtml}
434
- </span>`;
435
- }
436
- function renderDeltaVisualizationHtml(visualization, options) {
437
- const value = toFiniteNumber(visualization.value);
438
- const direction = value === undefined ? 'neutral' : value < 0 ? 'down' : value > 0 ? 'up' : 'neutral';
439
- const symbol = direction === 'up' ? '&#9650;' : direction === 'down' ? '&#9660;' : '&rarr;';
440
- const tone = visualization.tone ??
441
- (value === undefined
442
- ? 'neutral'
443
- : value < 0
444
- ? 'danger'
445
- : value > 0
446
- ? 'success'
447
- : 'neutral');
448
- const valueSuffix = visualization.valueSuffix ?? '';
449
- const text = value === undefined
450
- ? visualization.fallbackText
451
- : `${formatMicroNumber(Math.abs(value), options.locale)}${valueSuffix}`;
452
- const directionLabel = direction === 'up'
453
- ? 'up'
454
- : direction === 'down'
455
- ? 'down'
456
- : 'stable';
457
- const aria = visualization.ariaLabel ?? `${visualization.fallbackText}: ${directionLabel} ${text}`;
458
- return `
459
- <span class="pfx-micro-viz pfx-micro-viz__delta" data-tone="${escapeHtml(tone)}" data-direction="${escapeHtml(direction)}" role="img" aria-label="${escapeHtml(aria)}">
460
- <span class="pfx-micro-viz__delta-symbol" aria-hidden="true">${symbol}</span>
461
- <span>${escapeHtml(text)}</span>
462
- </span>`;
463
- }
464
- function percent(value, total) {
465
- if (!Number.isFinite(value) || !Number.isFinite(total) || total <= 0) {
466
- return '0';
467
- }
468
- return Math.max(0, Math.min(100, (value / total) * 100)).toFixed(2);
704
+ return ['#cbd5e1', '#64748b', '#334155'];
705
+ }
469
706
  }
470
707
  function toFiniteNumber(value) {
471
- return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
708
+ if (typeof value === 'number') {
709
+ return Number.isFinite(value) ? value : undefined;
710
+ }
711
+ if (typeof value === 'string') {
712
+ const trimmed = value.trim();
713
+ if (!trimmed) {
714
+ return undefined;
715
+ }
716
+ const parsed = Number(trimmed);
717
+ return Number.isFinite(parsed) ? parsed : undefined;
718
+ }
719
+ return undefined;
472
720
  }
473
- function formatMicroNumber(value, locale) {
721
+ function formatVisualizationMetricValue(value, options, compactValue = false, suffix = '') {
722
+ if (typeof options.formatValue === 'function') {
723
+ const custom = options.formatValue(value, compactValue);
724
+ if (typeof custom === 'string' && custom.trim().length > 0) {
725
+ return suffix && !custom.endsWith(suffix) ? `${custom}${suffix}` : custom;
726
+ }
727
+ }
728
+ return `${formatMicroNumber(value, options.locale, compactValue)}${suffix}`;
729
+ }
730
+ function formatMicroNumber(value, locale, compactValue = false) {
731
+ if (compactValue && Math.abs(value) >= 1000) {
732
+ return new Intl.NumberFormat(locale || undefined, {
733
+ notation: 'compact',
734
+ compactDisplay: 'short',
735
+ maximumFractionDigits: 1,
736
+ }).format(value);
737
+ }
738
+ const abs = Math.abs(value);
739
+ const hasFraction = Math.abs(value - Math.trunc(value)) > 1e-6;
474
740
  return new Intl.NumberFormat(locale || undefined, {
475
- maximumFractionDigits: Math.abs(value) < 10 ? 2 : 0,
741
+ maximumFractionDigits: abs < 10 ? 2 : hasFraction && abs < 1000 ? 1 : 0,
476
742
  }).format(value);
477
743
  }
478
- function escapeHtml(value) {
479
- return String(value ?? '')
480
- .replace(/&/g, '&amp;')
481
- .replace(/</g, '&lt;')
482
- .replace(/>/g, '&gt;')
483
- .replace(/"/g, '&quot;')
484
- .replace(/'/g, '&#39;');
485
- }
486
744
  function normalizePoints(value) {
487
745
  const points = normalizeNumericEntries(value);
488
746
  return points.length ? { points } : undefined;
@@ -545,21 +803,31 @@ function normalizeNumericEntries(value) {
545
803
  }
546
804
  return value
547
805
  .map((item) => {
548
- if (!item || typeof item !== 'object' || !Number.isFinite(item.value)) {
806
+ if (typeof item === 'number' || typeof item === 'string') {
807
+ const num = toFiniteNumber(item);
808
+ return num !== undefined ? { value: num } : null;
809
+ }
810
+ if (!item || typeof item !== 'object' || isVisualizationEntrySuppressed(item)) {
811
+ return null;
812
+ }
813
+ const num = toFiniteNumber(item.value);
814
+ if (num === undefined) {
549
815
  return null;
550
816
  }
551
817
  const label = normalizeText$1(item.label);
552
818
  const tone = normalizeEnum$1(item.tone, VISUALIZATION_TONES);
819
+ const color = normalizePraxisHexColor(item.color);
553
820
  return {
554
- value: item.value,
821
+ value: num,
555
822
  ...(label ? { label } : {}),
556
823
  ...(tone ? { tone } : {}),
824
+ ...(color ? { color } : {}),
557
825
  };
558
826
  })
559
827
  .filter((item) => !!item);
560
828
  }
561
829
  function normalizeVisualizationItem(item) {
562
- if (!item || typeof item !== 'object') {
830
+ if (!item || typeof item !== 'object' || isVisualizationEntrySuppressed(item)) {
563
831
  return null;
564
832
  }
565
833
  const id = normalizeText$1(item.id);
@@ -567,8 +835,10 @@ function normalizeVisualizationItem(item) {
567
835
  const icon = normalizeText$1(item.icon);
568
836
  const state = normalizeText$1(item.state);
569
837
  const tone = normalizeEnum$1(item.tone, VISUALIZATION_TONES);
570
- const normalizedValue = Number.isFinite(item.value) ? item.value : undefined;
571
- if (!id && !label && normalizedValue === undefined && !icon && !state && !tone) {
838
+ const role = normalizeEnum$1(item.role, WATERFALL_ROLES);
839
+ const color = normalizePraxisHexColor(item.color);
840
+ const normalizedValue = toFiniteNumber(item.value);
841
+ if (!id && !label && normalizedValue === undefined && !icon && !state && !tone && !role && !color) {
572
842
  return null;
573
843
  }
574
844
  return {
@@ -578,10 +848,13 @@ function normalizeVisualizationItem(item) {
578
848
  ...(icon ? { icon } : {}),
579
849
  ...(state ? { state } : {}),
580
850
  ...(tone ? { tone } : {}),
851
+ ...(role ? { role } : {}),
852
+ ...(color ? { color } : {}),
581
853
  };
582
854
  }
583
855
  function normalizeNumber(value, key) {
584
- return Number.isFinite(value) ? { [key]: value } : undefined;
856
+ const num = toFiniteNumber(value);
857
+ return num !== undefined ? { [key]: num } : undefined;
585
858
  }
586
859
  function normalizeEnum$1(value, allowed) {
587
860
  if (typeof value !== 'string') {
@@ -597,296 +870,620 @@ function normalizeText$1(value) {
597
870
  const trimmed = value.trim();
598
871
  return trimmed.length ? trimmed : undefined;
599
872
  }
600
- function renderRadialVisualizationHtml(visualization, options) {
601
- const value = toFiniteNumber(visualization.value);
602
- if (value === undefined) {
603
- return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
604
- }
605
- const total = visualization.total && visualization.total > 0 ? visualization.total : 100;
606
- const pct = Math.max(0, Math.min(100, (value / total) * 100));
607
- const tone = visualization.tone ?? 'info';
608
- const dashArray = `${pct.toFixed(1)}, 100`;
609
- const pctText = `${Math.round(pct)}%`;
610
- const aria = visualization.ariaLabel ?? `${visualization.fallbackText} (${pctText})`;
611
- const isTable = visualization.surface === 'table-cell';
612
- const svgText = isTable
613
- ? ''
614
- : `<text x="18" y="21" class="pfx-micro-radial-svg__text">${escapeHtml(pctText)}</text>`;
615
- const externalText = isTable
616
- ? `<span class="pfx-micro-radial-value">${escapeHtml(pctText)}</span>`
617
- : '';
618
- return `
619
- <span class="pfx-micro-viz pfx-micro-viz__radial" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(aria)}">
620
- <svg class="pfx-micro-radial-svg" viewBox="0 0 36 36">
621
- <circle class="pfx-micro-radial-svg__track" cx="18" cy="18" r="15.9155" />
622
- <circle class="pfx-micro-radial-svg__bar" cx="18" cy="18" r="15.9155" stroke-dasharray="${dashArray}" transform="rotate(-90 18 18)" />
623
- ${svgText}
624
- </svg>
625
- ${externalText}
626
- </span>`;
627
- }
628
- function renderHarveyBallVisualizationHtml(visualization, options) {
629
- const value = toFiniteNumber(visualization.value);
630
- if (value === undefined) {
631
- return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
632
- }
633
- const total = visualization.total && visualization.total > 0 ? visualization.total : 100;
634
- const pct = Math.max(0, Math.min(100, (value / total) * 100));
635
- const tone = visualization.tone ?? 'info';
636
- const strokeLength = pct * 0.50265;
637
- const dashArray = `${strokeLength.toFixed(3)} 50.265`;
638
- const aria = visualization.ariaLabel ?? `${visualization.fallbackText} (${Math.round(pct)}%)`;
639
- return `
640
- <span class="pfx-micro-viz pfx-micro-viz__harvey" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(aria)}">
641
- <svg class="pfx-micro-harvey-svg" viewBox="0 0 36 36">
642
- <circle class="pfx-micro-harvey-svg__track" cx="18" cy="18" r="16" />
643
- <circle class="pfx-micro-harvey-svg__bar" cx="18" cy="18" r="8" stroke-dasharray="${dashArray}" transform="rotate(-90 18 18)" />
644
- </svg>
645
- <span class="pfx-micro-harvey-fraction">
646
- <strong>${escapeHtml(formatMicroNumber(value, options.locale))}</strong>
647
- <span class="pfx-separator">/</span>
648
- <span class="pfx-total">${escapeHtml(formatMicroNumber(total, options.locale))}</span>
649
- </span>
650
- </span>`;
651
- }
652
- function getPointsCoordinates(points, width, height, padding) {
653
- if (points.length < 2)
873
+ function formatPraxisWaterfallSignedValue(value, role, options = {}, compactValue = false, suffix = '') {
874
+ const absFormatted = formatVisualizationMetricValue(Math.abs(Number.isFinite(value) ? value : 0), options, compactValue, suffix);
875
+ if (role === 'start' || role === 'subtotal' || role === 'total') {
876
+ const negPrefix = value < 0 ? '-' : '';
877
+ return `= ${negPrefix}${absFormatted}`;
878
+ }
879
+ if (value > 0) {
880
+ return `+${absFormatted}`;
881
+ }
882
+ if (value < 0) {
883
+ return `-${absFormatted}`;
884
+ }
885
+ return absFormatted;
886
+ }
887
+ function resolvePraxisMicroWaterfallSteps(visualization, options = {}) {
888
+ const rawItems = Array.isArray(visualization.items) && visualization.items.length > 0
889
+ ? visualization.items
890
+ : Array.isArray(visualization.points)
891
+ ? visualization.points.map((pt) => typeof pt === 'number'
892
+ ? { value: pt }
893
+ : {
894
+ label: pt.label,
895
+ value: pt.value,
896
+ tone: pt.tone,
897
+ ...(pt.suppressed !== undefined ? { suppressed: pt.suppressed } : {}),
898
+ ...(pt.privacySuppressed !== undefined ? { privacySuppressed: pt.privacySuppressed } : {}),
899
+ })
900
+ : [];
901
+ if (!rawItems.length) {
902
+ return [];
903
+ }
904
+ const suffix = visualization.valueSuffix ?? '';
905
+ const compactValue = visualization.compactValue === true;
906
+ const fallbackAnchorTone = visualization.tone ?? 'info';
907
+ const steps = [];
908
+ let running = 0;
909
+ let hasFiniteNumeric = false;
910
+ let hadSuppressedItems = resolvePreservedSuppressedCount(visualization.suppressedCount) > 0;
911
+ let visibleIncrementCount = 0;
912
+ for (let i = 0; i < rawItems.length; i++) {
913
+ const raw = rawItems[i];
914
+ if (!raw || typeof raw !== 'object') {
915
+ continue;
916
+ }
917
+ if (isVisualizationEntrySuppressed(raw)) {
918
+ hadSuppressedItems = true;
919
+ continue;
920
+ }
921
+ const rawNumeric = toFiniteNumber(raw.value);
922
+ if (rawNumeric !== undefined) {
923
+ hasFiniteNumeric = true;
924
+ }
925
+ const explicitRole = normalizeEnum$1(raw.role, WATERFALL_ROLES);
926
+ const role = explicitRole
927
+ ?? (steps.length === 0 ? 'start' : (rawNumeric ?? 0) < 0 ? 'decrease' : 'increase');
928
+ if (rawNumeric === undefined && role !== 'subtotal' && role !== 'total') {
929
+ continue;
930
+ }
931
+ if (role !== 'subtotal' && role !== 'total') {
932
+ visibleIncrementCount += 1;
933
+ }
934
+ let start = running;
935
+ let end = running;
936
+ let delta = 0;
937
+ let resolvedValue = rawNumeric ?? running;
938
+ if (role === 'start') {
939
+ start = 0;
940
+ end = rawNumeric ?? 0;
941
+ delta = end;
942
+ running = end;
943
+ resolvedValue = end;
944
+ }
945
+ else if (role === 'subtotal' || role === 'total') {
946
+ const targetEnd = hadSuppressedItems ? running : (rawNumeric ?? running);
947
+ start = 0;
948
+ end = targetEnd;
949
+ delta = targetEnd;
950
+ running = targetEnd;
951
+ resolvedValue = targetEnd;
952
+ }
953
+ else if (role === 'decrease') {
954
+ delta = -Math.abs(rawNumeric ?? 0);
955
+ start = running;
956
+ end = running + delta;
957
+ running = end;
958
+ resolvedValue = delta;
959
+ }
960
+ else {
961
+ delta = Math.abs(rawNumeric ?? 0);
962
+ start = running;
963
+ end = running + delta;
964
+ running = end;
965
+ resolvedValue = delta;
966
+ }
967
+ const defaultTone = role === 'increase'
968
+ ? 'success'
969
+ : role === 'decrease'
970
+ ? 'danger'
971
+ : role === 'start'
972
+ ? 'neutral'
973
+ : fallbackAnchorTone;
974
+ const tone = normalizeEnum$1(raw.tone, VISUALIZATION_TONES) ?? defaultTone;
975
+ const label = normalizeText$1(raw.label) ?? normalizeText$1(raw.id) ?? `#${steps.length + 1}`;
976
+ const signedText = formatPraxisWaterfallSignedValue(role === 'start' || role === 'subtotal' || role === 'total' ? end : delta, role, options, compactValue, suffix);
977
+ const endText = formatVisualizationMetricValue(Math.abs(end), options, compactValue, suffix);
978
+ const signedEndText = `${end < 0 ? '-' : ''}${endText}`;
979
+ const readout = role === 'start' || role === 'subtotal' || role === 'total'
980
+ ? `${label}: ${signedText}`
981
+ : `${label}: ${signedText} (=> ${signedEndText})`;
982
+ steps.push({
983
+ ...(raw.id ? { id: raw.id } : {}),
984
+ label,
985
+ value: resolvedValue,
986
+ start,
987
+ end,
988
+ delta,
989
+ role,
990
+ tone,
991
+ ...(raw.color ? { color: raw.color } : {}),
992
+ signedText,
993
+ readout,
994
+ });
995
+ }
996
+ if (!hasFiniteNumeric || (hadSuppressedItems && visibleIncrementCount === 0)) {
654
997
  return [];
655
- const values = points.map(p => p.value);
656
- const minVal = Math.min(...values);
657
- const maxVal = Math.max(...values);
658
- const valRange = maxVal - minVal === 0 ? 1 : maxVal - minVal;
659
- return points.map((p, index) => {
660
- const x = padding + (index / (points.length - 1)) * (width - 2 * padding);
661
- const y = height - padding - ((p.value - minVal) / valRange) * (height - 2 * padding);
662
- return { x, y };
998
+ }
999
+ return steps;
1000
+ }
1001
+
1002
+ const PRAXIS_QUICK_VIEW_PRESENTER = new InjectionToken('PRAXIS_QUICK_VIEW_PRESENTER');
1003
+ const PRAXIS_QUICK_VIEW_BODY_RENDERER = new InjectionToken('PRAXIS_QUICK_VIEW_BODY_RENDERER');
1004
+ const FORBIDDEN_BINDING_KEYS = new Set([
1005
+ 'element',
1006
+ 'nativeElement',
1007
+ 'anchor',
1008
+ 'hostElement',
1009
+ 'focusOrigin',
1010
+ 'getViewportRect',
1011
+ 'nodes',
1012
+ 'document',
1013
+ 'action',
1014
+ 'actions',
1015
+ 'ctaAction',
1016
+ 'overrideAction',
1017
+ 'route',
1018
+ 'href',
1019
+ 'payload',
1020
+ 'hostCapabilities',
1021
+ ]);
1022
+ const RESOURCE_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
1023
+ /**
1024
+ * Detecta se um valor candidato à serialização contém referências efêmeras de DOM ou funções.
1025
+ */
1026
+ function containsEphemeralQuickViewRuntimeValue(value, visited = new Set()) {
1027
+ if (!value || typeof value !== 'object') {
1028
+ return typeof value === 'function';
1029
+ }
1030
+ if (visited.has(value)) {
1031
+ return false;
1032
+ }
1033
+ visited.add(value);
1034
+ if (typeof Element !== 'undefined' && value instanceof Element) {
1035
+ return true;
1036
+ }
1037
+ if (typeof value.nodeType === 'number' &&
1038
+ typeof value.nodeName === 'string') {
1039
+ return true;
1040
+ }
1041
+ if (Array.isArray(value)) {
1042
+ return value.some((item) => containsEphemeralQuickViewRuntimeValue(item, visited));
1043
+ }
1044
+ for (const [key, entry] of Object.entries(value)) {
1045
+ if (key === 'element' ||
1046
+ key === 'nativeElement' ||
1047
+ key === 'hostElement' ||
1048
+ key === 'focusOrigin' ||
1049
+ typeof entry === 'function') {
1050
+ return true;
1051
+ }
1052
+ if (containsEphemeralQuickViewRuntimeValue(entry, visited)) {
1053
+ return true;
1054
+ }
1055
+ }
1056
+ return false;
1057
+ }
1058
+ function normalizeResourceRecordOpenReference(candidate) {
1059
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
1060
+ return null;
1061
+ }
1062
+ const record = candidate;
1063
+ const target = record['target'] && typeof record['target'] === 'object' && !Array.isArray(record['target'])
1064
+ ? record['target']
1065
+ : null;
1066
+ const sourceIdentityField = typeof record['sourceIdentityField'] === 'string'
1067
+ ? record['sourceIdentityField'].trim()
1068
+ : '';
1069
+ const resourceKey = typeof target?.['resourceKey'] === 'string'
1070
+ ? target['resourceKey'].trim()
1071
+ : '';
1072
+ const surfaceId = typeof target?.['surfaceId'] === 'string'
1073
+ ? target['surfaceId'].trim()
1074
+ : '';
1075
+ if (!sourceIdentityField ||
1076
+ sourceIdentityField.length > 200 ||
1077
+ !RESOURCE_KEY_PATTERN.test(resourceKey) ||
1078
+ !surfaceId ||
1079
+ surfaceId.length > 200) {
1080
+ return null;
1081
+ }
1082
+ return {
1083
+ sourceIdentityField,
1084
+ target: {
1085
+ resourceKey,
1086
+ surfaceId,
1087
+ },
1088
+ };
1089
+ }
1090
+ /**
1091
+ * Valida e normaliza um `ResourceQuickViewBinding` de forma fail-closed.
1092
+ */
1093
+ function validateResourceQuickViewBinding(value) {
1094
+ const diagnostics = [];
1095
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
1096
+ return {
1097
+ valid: false,
1098
+ binding: null,
1099
+ diagnostics: ['Quick View binding must be a non-null object.'],
1100
+ };
1101
+ }
1102
+ const record = value;
1103
+ for (const forbiddenKey of FORBIDDEN_BINDING_KEYS) {
1104
+ if (forbiddenKey in record && record[forbiddenKey] !== undefined) {
1105
+ diagnostics.push(`Quick View binding cannot contain runtime, inline document or action override property "${forbiddenKey}".`);
1106
+ }
1107
+ }
1108
+ if (containsEphemeralQuickViewRuntimeValue(record)) {
1109
+ diagnostics.push('Quick View binding cannot contain DOM elements or functions.');
1110
+ }
1111
+ const rawRecordOpen = record['recordOpen'];
1112
+ if (!rawRecordOpen || typeof rawRecordOpen !== 'object' || Array.isArray(rawRecordOpen)) {
1113
+ diagnostics.push('Quick View binding requires a valid "recordOpen" object.');
1114
+ }
1115
+ else {
1116
+ const recordOpenObj = rawRecordOpen;
1117
+ for (const forbiddenKey of FORBIDDEN_BINDING_KEYS) {
1118
+ if (forbiddenKey in recordOpenObj && recordOpenObj[forbiddenKey] !== undefined) {
1119
+ diagnostics.push(`Quick View recordOpen cannot contain override property "${forbiddenKey}".`);
1120
+ }
1121
+ }
1122
+ if ('presentation' in recordOpenObj && recordOpenObj['presentation'] === 'popover') {
1123
+ diagnostics.push('Quick View recordOpen cannot declare "popover" presentation.');
1124
+ }
1125
+ }
1126
+ let previewSurfaceId;
1127
+ const rawPreviewSurfaceId = record['previewSurfaceId'];
1128
+ if (rawPreviewSurfaceId !== undefined && rawPreviewSurfaceId !== null) {
1129
+ if (typeof rawPreviewSurfaceId === 'string' &&
1130
+ rawPreviewSurfaceId.trim().length > 0 &&
1131
+ rawPreviewSurfaceId.trim().length <= 200) {
1132
+ previewSurfaceId = rawPreviewSurfaceId.trim();
1133
+ }
1134
+ else {
1135
+ diagnostics.push('Quick View previewSurfaceId must be a non-empty string up to 200 characters.');
1136
+ }
1137
+ }
1138
+ let detailPresentation;
1139
+ const rawDetailPresentation = record['detailPresentation'];
1140
+ if (rawDetailPresentation !== undefined && rawDetailPresentation !== null) {
1141
+ if (rawDetailPresentation === 'drawer' || rawDetailPresentation === 'modal') {
1142
+ detailPresentation = rawDetailPresentation;
1143
+ }
1144
+ else {
1145
+ diagnostics.push(`Quick View detailPresentation must be "drawer" or "modal"; received "${String(rawDetailPresentation)}".`);
1146
+ }
1147
+ }
1148
+ const normalizedRecordOpen = normalizeResourceRecordOpenReference(rawRecordOpen);
1149
+ if (!normalizedRecordOpen) {
1150
+ diagnostics.push('Quick View recordOpen must declare non-empty sourceIdentityField and target.{resourceKey, surfaceId}.');
1151
+ }
1152
+ let normalizedContentRef;
1153
+ const rawContentRef = record['contentRef'];
1154
+ if (rawContentRef !== undefined && rawContentRef !== null) {
1155
+ if (typeof rawContentRef !== 'object' || Array.isArray(rawContentRef)) {
1156
+ diagnostics.push('Quick View contentRef must be an object reference to a rich-block preset.');
1157
+ }
1158
+ else {
1159
+ const refObj = rawContentRef;
1160
+ const kind = typeof refObj['kind'] === 'string' ? refObj['kind'].trim() : '';
1161
+ const namespace = typeof refObj['namespace'] === 'string' ? refObj['namespace'].trim() : '';
1162
+ const presetId = typeof refObj['presetId'] === 'string' ? refObj['presetId'].trim() : '';
1163
+ const version = typeof refObj['version'] === 'string' ? refObj['version'].trim() : '';
1164
+ if (kind !== 'rich-block') {
1165
+ diagnostics.push(`Quick View contentRef.kind must be "rich-block"; received "${kind || 'empty'}".`);
1166
+ }
1167
+ if (!namespace) {
1168
+ diagnostics.push('Quick View contentRef.namespace must be a non-empty string.');
1169
+ }
1170
+ if (!presetId) {
1171
+ diagnostics.push('Quick View contentRef.presetId must be a non-empty string.');
1172
+ }
1173
+ if (!version) {
1174
+ diagnostics.push('Quick View contentRef.version must be explicitly declared.');
1175
+ }
1176
+ if ('nodes' in refObj || 'inputs' in refObj || 'action' in refObj) {
1177
+ diagnostics.push('Quick View contentRef cannot embed inline nodes, inputs or actions.');
1178
+ }
1179
+ if (kind === 'rich-block' &&
1180
+ namespace &&
1181
+ presetId &&
1182
+ version &&
1183
+ !('nodes' in refObj || 'inputs' in refObj || 'action' in refObj)) {
1184
+ normalizedContentRef = {
1185
+ kind: 'rich-block',
1186
+ namespace,
1187
+ presetId,
1188
+ version,
1189
+ };
1190
+ }
1191
+ }
1192
+ }
1193
+ if (diagnostics.length > 0 || !normalizedRecordOpen) {
1194
+ return {
1195
+ valid: false,
1196
+ binding: null,
1197
+ diagnostics,
1198
+ };
1199
+ }
1200
+ return {
1201
+ valid: true,
1202
+ binding: {
1203
+ recordOpen: normalizedRecordOpen,
1204
+ ...(previewSurfaceId ? { previewSurfaceId } : {}),
1205
+ ...(normalizedContentRef ? { contentRef: normalizedContentRef } : {}),
1206
+ ...(detailPresentation ? { detailPresentation } : {}),
1207
+ },
1208
+ diagnostics: [],
1209
+ };
1210
+ }
1211
+ function normalizeResourceQuickViewBinding(value) {
1212
+ return validateResourceQuickViewBinding(value).binding;
1213
+ }
1214
+ /**
1215
+ * Resolve ou sintetiza de forma determinística o `ResourceQuickViewBinding` de um campo
1216
+ * (`FieldDefinition` ou `FieldMetadata`), priorizando:
1217
+ * 1. `field.quickView` explícito;
1218
+ * 2. `field.presentation.interactions.quickView` explícito;
1219
+ * 3. síntese automática a partir de `field.resourceReference` ou `field.optionSource.detail`.
1220
+ *
1221
+ * Protege contra colisão de `valueField`/`optionSource.valuePropertyPath` (`'id'` da opção)
1222
+ * com o identificador da própria entidade pai quando o campo de origem possui outro nome
1223
+ * (ex.: `cargoId`, `fornecedorId`).
1224
+ */
1225
+ function resolveFieldQuickViewBinding(candidate) {
1226
+ if (!candidate || typeof candidate !== 'object') {
1227
+ return null;
1228
+ }
1229
+ const explicitQuickView = normalizeResourceQuickViewBinding(candidate.quickView);
1230
+ if (explicitQuickView) {
1231
+ return explicitQuickView;
1232
+ }
1233
+ const presentationQuickView = normalizeResourceQuickViewBinding(candidate.presentation?.interactions?.quickView);
1234
+ if (presentationQuickView) {
1235
+ return presentationQuickView;
1236
+ }
1237
+ const fieldName = typeof candidate.name === 'string' ? candidate.name.trim() : '';
1238
+ const rawValueField = typeof candidate.valueField === 'string' ? candidate.valueField.trim() : '';
1239
+ const optionValueProperty = typeof candidate.optionSource?.valuePropertyPath === 'string' &&
1240
+ candidate.optionSource.valuePropertyPath.trim().length > 0
1241
+ ? candidate.optionSource.valuePropertyPath.trim()
1242
+ : 'id';
1243
+ // Quando o campo possui optionSource e seu nome não coincide com rawValueField, um valueField
1244
+ // igual a 'id'/'value'/'key' ou a optionValueProperty (ex.: 'numero', 'codigo') refere-se à
1245
+ // chave do OptionDTO e nunca ao campo irmão 'id' do registro pai.
1246
+ const isOptionKeyAlias = rawValueField === 'id' ||
1247
+ rawValueField === 'value' ||
1248
+ rawValueField === 'key' ||
1249
+ rawValueField === optionValueProperty;
1250
+ const effectiveSiblingValueField = rawValueField &&
1251
+ (!candidate.optionSource ||
1252
+ fieldName === rawValueField ||
1253
+ !isOptionKeyAlias)
1254
+ ? rawValueField
1255
+ : '';
1256
+ const refCandidate = candidate.resourceReference?.resourceKey
1257
+ ? {
1258
+ resourceKey: candidate.resourceReference.resourceKey,
1259
+ sourceIdentityField: (typeof candidate.resourceReference.valueField === 'string'
1260
+ ? candidate.resourceReference.valueField.trim()
1261
+ : '') ||
1262
+ effectiveSiblingValueField ||
1263
+ fieldName,
1264
+ surfaceId: candidate.resourceReference.surfaceId || 'detail',
1265
+ previewSurfaceId: candidate.resourceReference.previewSurfaceId,
1266
+ detailPresentation: candidate.resourceReference.detailPresentation === 'drawer' ||
1267
+ candidate.resourceReference.detailPresentation === 'modal'
1268
+ ? candidate.resourceReference.detailPresentation
1269
+ : undefined,
1270
+ }
1271
+ : candidate.optionSource?.detail?.resourceKey
1272
+ ? {
1273
+ resourceKey: candidate.optionSource.detail.resourceKey,
1274
+ sourceIdentityField: effectiveSiblingValueField || fieldName,
1275
+ surfaceId: candidate.optionSource.detail.surfaceId || 'detail',
1276
+ previewSurfaceId: candidate.optionSource.detail.previewSurfaceId,
1277
+ detailPresentation: candidate.optionSource.detail.presentation === 'drawer' ||
1278
+ candidate.optionSource.detail.presentation === 'modal'
1279
+ ? candidate.optionSource.detail.presentation
1280
+ : undefined,
1281
+ }
1282
+ : undefined;
1283
+ if (!refCandidate || !refCandidate.sourceIdentityField) {
1284
+ return null;
1285
+ }
1286
+ return normalizeResourceQuickViewBinding({
1287
+ recordOpen: {
1288
+ sourceIdentityField: refCandidate.sourceIdentityField,
1289
+ target: {
1290
+ resourceKey: refCandidate.resourceKey,
1291
+ surfaceId: refCandidate.surfaceId || 'detail',
1292
+ },
1293
+ },
1294
+ ...(refCandidate.previewSurfaceId
1295
+ ? { previewSurfaceId: refCandidate.previewSurfaceId }
1296
+ : {}),
1297
+ ...(refCandidate.detailPresentation
1298
+ ? { detailPresentation: refCandidate.detailPresentation }
1299
+ : {}),
663
1300
  });
664
1301
  }
665
- function renderLineVisualizationHtml(visualization, options) {
666
- const points = visualization.points ?? [];
667
- const tone = visualization.tone ?? 'info';
668
- if (points.length < 2) {
669
- return renderFallbackVisualizationHtml(visualization, tone);
670
- }
671
- const width = 100;
672
- const height = 30;
673
- const padding = 4;
674
- const coords = getPointsCoordinates(points, width, height, padding);
675
- const pathD = coords.map((c, i) => `${i === 0 ? 'M' : 'L'} ${c.x.toFixed(1)} ${c.y.toFixed(1)}`).join(' ');
676
- // Highlight extreme/boundary values
677
- let minIdx = 0;
678
- let maxIdx = 0;
679
- for (let i = 1; i < points.length; i++) {
680
- if (points[i].value < points[minIdx].value)
681
- minIdx = i;
682
- if (points[i].value > points[maxIdx].value)
683
- maxIdx = i;
684
- }
685
- const markers = [
686
- { x: coords[0].x, y: coords[0].y, tone: points[0].tone ?? tone },
687
- { x: coords[coords.length - 1].x, y: coords[coords.length - 1].y, tone: points[points.length - 1].tone ?? tone }
688
- ];
689
- if (minIdx !== 0 && minIdx !== coords.length - 1) {
690
- markers.push({ x: coords[minIdx].x, y: coords[minIdx].y, tone: points[minIdx].tone ?? 'danger' });
691
- }
692
- if (maxIdx !== 0 && maxIdx !== coords.length - 1) {
693
- markers.push({ x: coords[maxIdx].x, y: coords[maxIdx].y, tone: points[maxIdx].tone ?? 'success' });
694
- }
695
- const circlesHtml = markers.map(c => `<circle cx="${c.x.toFixed(1)}" cy="${c.y.toFixed(1)}" r="2.5" class="pfx-micro-trend__marker" data-tone="${escapeHtml(c.tone)}" />`).join('');
696
- const isTable = visualization.surface === 'table-cell';
697
- const firstPoint = points[0];
698
- const lastPoint = points[points.length - 1];
699
- const leftHtml = isTable ? '' : `
700
- <div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--start">
701
- <span class="pfx-micro-trend__value">${escapeHtml(formatMicroNumber(firstPoint.value, options.locale))}</span>
702
- ${firstPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(firstPoint.label)}</span>` : ''}
703
- </div>`;
704
- const rightHtml = isTable ? '' : `
705
- <div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--end">
706
- <span class="pfx-micro-trend__value">${escapeHtml(formatMicroNumber(lastPoint.value, options.locale))}</span>
707
- ${lastPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(lastPoint.label)}</span>` : ''}
708
- </div>`;
709
- return `
710
- <span class="pfx-micro-viz-container">
711
- ${leftHtml}
712
- <span class="pfx-micro-viz pfx-micro-viz__line" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
713
- <svg class="pfx-micro-line__svg" viewBox="0 0 100 30">
714
- <path class="pfx-micro-line__path" d="${pathD}" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
715
- ${circlesHtml}
716
- </svg>
717
- </span>
718
- ${rightHtml}
719
- </span>`;
720
- }
721
- function renderAreaVisualizationHtml(visualization, options) {
722
- const points = visualization.points ?? [];
723
- const tone = visualization.tone ?? 'info';
724
- if (points.length < 2) {
725
- return renderFallbackVisualizationHtml(visualization, tone);
726
- }
727
- const width = 100;
728
- const height = 30;
729
- const padding = 4;
730
- const coords = getPointsCoordinates(points, width, height, padding);
731
- const lineD = coords.map((c, i) => `${i === 0 ? 'M' : 'L'} ${c.x.toFixed(1)} ${c.y.toFixed(1)}`).join(' ');
732
- const firstX = coords[0].x.toFixed(1);
733
- const lastX = coords[coords.length - 1].x.toFixed(1);
734
- const areaD = `${lineD} L ${lastX} ${height} L ${firstX} ${height} Z`;
735
- // Highlight extreme/boundary values
736
- let minIdx = 0;
737
- let maxIdx = 0;
738
- for (let i = 1; i < points.length; i++) {
739
- if (points[i].value < points[minIdx].value)
740
- minIdx = i;
741
- if (points[i].value > points[maxIdx].value)
742
- maxIdx = i;
743
- }
744
- const markers = [
745
- { x: coords[0].x, y: coords[0].y, tone: points[0].tone ?? tone },
746
- { x: coords[coords.length - 1].x, y: coords[coords.length - 1].y, tone: points[points.length - 1].tone ?? tone }
747
- ];
748
- if (minIdx !== 0 && minIdx !== coords.length - 1) {
749
- markers.push({ x: coords[minIdx].x, y: coords[minIdx].y, tone: points[minIdx].tone ?? 'danger' });
750
- }
751
- if (maxIdx !== 0 && maxIdx !== coords.length - 1) {
752
- markers.push({ x: coords[maxIdx].x, y: coords[maxIdx].y, tone: points[maxIdx].tone ?? 'success' });
753
- }
754
- const circlesHtml = markers.map(c => `<circle cx="${c.x.toFixed(1)}" cy="${c.y.toFixed(1)}" r="2.5" class="pfx-micro-trend__marker" data-tone="${escapeHtml(c.tone)}" />`).join('');
755
- const isTable = visualization.surface === 'table-cell';
756
- const firstPoint = points[0];
757
- const lastPoint = points[points.length - 1];
758
- const leftHtml = isTable ? '' : `
759
- <div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--start">
760
- <span class="pfx-micro-trend__value">${escapeHtml(formatMicroNumber(firstPoint.value, options.locale))}</span>
761
- ${firstPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(firstPoint.label)}</span>` : ''}
762
- </div>`;
763
- const rightHtml = isTable ? '' : `
764
- <div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--end">
765
- <span class="pfx-micro-trend__value">${escapeHtml(formatMicroNumber(lastPoint.value, options.locale))}</span>
766
- ${lastPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(lastPoint.label)}</span>` : ''}
767
- </div>`;
768
- return `
769
- <span class="pfx-micro-viz-container">
770
- ${leftHtml}
771
- <span class="pfx-micro-viz pfx-micro-viz__area" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
772
- <svg class="pfx-micro-area__svg" viewBox="0 0 100 30">
773
- <path class="pfx-micro-area__fill" d="${areaD}" fill="currentColor" fill-opacity="0.15" />
774
- <path class="pfx-micro-area__path" d="${lineD}" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
775
- ${circlesHtml}
776
- </svg>
777
- </span>
778
- ${rightHtml}
779
- </span>`;
780
- }
781
- function renderColumnVisualizationHtml(visualization, options) {
782
- const points = visualization.points ?? [];
783
- const tone = visualization.tone ?? 'info';
784
- if (points.length === 0) {
785
- return renderFallbackVisualizationHtml(visualization, tone);
786
- }
787
- const width = 100;
788
- const height = 30;
789
- const padding = 4;
790
- const values = points.map(p => p.value);
791
- const maxVal = Math.max(...values, 0);
792
- const minVal = Math.min(...values, 0);
793
- const valRange = maxVal - minVal === 0 ? 1 : maxVal - minVal;
794
- const colWidth = Math.max(2, (width - 2 * padding) / points.length - 2);
795
- const columnsHtml = points.map((p, i) => {
796
- const x = padding + i * ((width - 2 * padding) / points.length) + 1;
797
- const rectHeight = Math.max(2, ((p.value - minVal) / valRange) * (height - 2 * padding));
798
- const rectY = height - padding - rectHeight;
799
- const itemTone = p.tone ??
800
- (visualization.thresholds?.length
801
- ? resolvePraxisMicroVisualizationTone(p.value, visualization.thresholds)?.tone ?? tone
802
- : tone);
803
- return `<rect class="pfx-micro-column__bar" x="${x.toFixed(1)}" y="${rectY.toFixed(1)}" width="${colWidth.toFixed(1)}" height="${rectHeight.toFixed(1)}" fill="currentColor" data-tone="${escapeHtml(itemTone)}" />`;
804
- }).join('');
805
- const isTable = visualization.surface === 'table-cell';
806
- const firstPoint = points[0];
807
- const lastPoint = points[points.length - 1];
808
- const leftHtml = isTable ? '' : `
809
- <div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--start">
810
- <span class="pfx-micro-trend__value">${escapeHtml(formatMicroNumber(firstPoint.value, options.locale))}</span>
811
- ${firstPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(firstPoint.label)}</span>` : ''}
812
- </div>`;
813
- const rightHtml = isTable ? '' : `
814
- <div class="pfx-micro-trend__label-col pfx-micro-trend__label-col--end">
815
- <span class="pfx-micro-trend__value">${escapeHtml(formatMicroNumber(lastPoint.value, options.locale))}</span>
816
- ${lastPoint.label ? `<span class="pfx-micro-trend__label">${escapeHtml(lastPoint.label)}</span>` : ''}
817
- </div>`;
818
- return `
819
- <span class="pfx-micro-viz-container">
820
- ${leftHtml}
821
- <span class="pfx-micro-viz pfx-micro-viz__column" data-tone="${escapeHtml(tone)}" role="img" aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}">
822
- <svg class="pfx-micro-column__svg" viewBox="0 0 100 30">
823
- ${columnsHtml}
824
- </svg>
825
- </span>
826
- ${rightHtml}
827
- </span>`;
828
- }
829
- function renderProcessFlowVisualizationHtml(visualization, options) {
830
- const items = visualization.items ?? [];
831
- if (items.length === 0) {
832
- return renderFallbackVisualizationHtml(visualization, visualization.tone ?? 'neutral');
833
- }
834
- const isTable = visualization.surface === 'table-cell';
835
- const stepLabels = items.map((item, index) => item.label ?? item.id ?? `${index + 1}`);
836
- const aria = visualization.ariaLabel ?? `${visualization.fallbackText}: ${stepLabels.join(' > ')}`;
837
- const labelStyleAttr = [];
838
- if (visualization.stepLabelWidth !== undefined) {
839
- const widthVal = typeof visualization.stepLabelWidth === 'number'
840
- ? `${visualization.stepLabelWidth}px`
841
- : String(visualization.stepLabelWidth);
842
- labelStyleAttr.push(`inline-size: ${escapeHtml(widthVal)}; max-width: ${escapeHtml(widthVal)};`);
843
- }
844
- if (visualization.stepLabelLineClamp !== undefined) {
845
- labelStyleAttr.push(`-webkit-line-clamp: ${visualization.stepLabelLineClamp};`);
846
- }
847
- const labelInlineStyle = labelStyleAttr.length ? ` style="${labelStyleAttr.join(' ')}"` : '';
848
- const stepsHtml = items.map((item, index) => {
849
- const itemTone = item.tone ?? 'neutral';
850
- const itemState = item.state ?? '';
851
- const isLast = index === items.length - 1;
852
- const itemLabel = stepLabels[index];
853
- const label = !isTable && item.label ? `<span class="pfx-micro-step__label"${labelInlineStyle}>${escapeHtml(item.label)}</span>` : '';
854
- const connector = !isLast ? `<span class="pfx-micro-step__connector" data-tone="${escapeHtml(itemTone)}"></span>` : '';
855
- const stepCircle = `
856
- <span class="pfx-micro-step__node" data-tone="${escapeHtml(itemTone)}" aria-hidden="true">
857
- ${item.icon ? `<span class="material-icons pfx-micro-step__icon" aria-hidden="true">${escapeHtml(item.icon)}</span>` : `${index + 1}`}
858
- </span>`;
859
- return `
860
- <div class="pfx-micro-step" data-state="${escapeHtml(itemState)}" data-tone="${escapeHtml(itemTone)}">
861
- <div class="pfx-micro-step__node-wrapper" title="${escapeHtml(itemLabel)}">
862
- ${stepCircle}
863
- ${label}
864
- </div>
865
- ${connector}
866
- </div>`;
867
- }).join('');
868
- return `
869
- <span class="pfx-micro-viz pfx-micro-viz__process" role="img" aria-label="${escapeHtml(aria)}">
870
- ${stepsHtml}
871
- </span>`;
872
- }
873
- function renderFallbackVisualizationHtml(visualization, tone) {
874
- return `
875
- <span
876
- class="pfx-micro-viz pfx-micro-viz__fallback"
877
- data-tone="${escapeHtml(tone)}"
878
- role="img"
879
- aria-label="${escapeHtml(visualization.ariaLabel ?? visualization.fallbackText)}"
880
- >${escapeHtml(visualization.fallbackText)}</span>`;
1302
+ /**
1303
+ * Reconcilia o `ResourceQuickViewBinding` entre a definição base do servidor e uma
1304
+ * customização local persistida:
1305
+ * - Um `local` indefinido, nulo ou inválido nunca apaga o binding canônico do servidor (`base`).
1306
+ * - Quando o campo possui binding canônico do servidor (`base`), `base.recordOpen`
1307
+ * (recurso de destino, `surfaceId` e `sourceIdentityField`) permanece autoritativo
1308
+ * do servidor, permitindo que o `local` customize apenas preferências visuais de UX
1309
+ * (`trigger`, `previewSurfaceId`, `detailPresentation`).
1310
+ */
1311
+ function reconcileFieldQuickViewBinding(base, local) {
1312
+ const normalizedBase = normalizeResourceQuickViewBinding(base);
1313
+ const normalizedLocal = normalizeResourceQuickViewBinding(local);
1314
+ if (normalizedBase && normalizedLocal) {
1315
+ return {
1316
+ ...normalizedBase,
1317
+ ...normalizedLocal,
1318
+ recordOpen: normalizedBase.recordOpen,
1319
+ };
1320
+ }
1321
+ return normalizedLocal ?? normalizedBase ?? undefined;
1322
+ }
1323
+ function readQuickViewFieldOrPath(target, path) {
1324
+ if (Object.prototype.hasOwnProperty.call(target, path)) {
1325
+ return target[path];
1326
+ }
1327
+ if (!path.includes('.')) {
1328
+ return undefined;
1329
+ }
1330
+ return path.split('.').reduce((acc, segment) => {
1331
+ if (!acc || typeof acc !== 'object' || Array.isArray(acc)) {
1332
+ return undefined;
1333
+ }
1334
+ return Object.prototype.hasOwnProperty.call(acc, segment)
1335
+ ? acc[segment]
1336
+ : undefined;
1337
+ }, target);
1338
+ }
1339
+ /**
1340
+ * Resolve de forma determinística o alvo (`resourceKey`, `surfaceId`, `previewSurfaceId`, `identity`)
1341
+ * a partir de um `ResourceQuickViewBinding` e de um registro candidato (`sourceRecord`).
1342
+ */
1343
+ function resolveResourceQuickViewTarget(binding, sourceRecord) {
1344
+ const normalized = normalizeResourceQuickViewBinding(binding);
1345
+ if (!normalized ||
1346
+ !sourceRecord ||
1347
+ typeof sourceRecord !== 'object' ||
1348
+ Array.isArray(sourceRecord)) {
1349
+ return null;
1350
+ }
1351
+ const record = sourceRecord;
1352
+ const sourceField = normalized.recordOpen.sourceIdentityField;
1353
+ let candidate = readQuickViewFieldOrPath(record, sourceField);
1354
+ if (candidate === undefined) {
1355
+ for (const envelopeKey of ['row', 'item', 'values']) {
1356
+ const nested = record[envelopeKey];
1357
+ if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
1358
+ candidate = readQuickViewFieldOrPath(nested, sourceField);
1359
+ if (candidate !== undefined) {
1360
+ break;
1361
+ }
1362
+ }
1363
+ }
1364
+ }
1365
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
1366
+ const candidateObj = candidate;
1367
+ candidate =
1368
+ candidateObj['id'] ?? candidateObj['value'] ?? candidateObj['key'];
1369
+ }
1370
+ if (typeof candidate === 'number' && Number.isFinite(candidate)) {
1371
+ return {
1372
+ resourceKey: normalized.recordOpen.target.resourceKey,
1373
+ surfaceId: normalized.recordOpen.target.surfaceId,
1374
+ previewSurfaceId: normalized.previewSurfaceId || normalized.recordOpen.target.surfaceId,
1375
+ identity: candidate,
1376
+ };
1377
+ }
1378
+ if (typeof candidate === 'string' && candidate.trim().length > 0) {
1379
+ return {
1380
+ resourceKey: normalized.recordOpen.target.resourceKey,
1381
+ surfaceId: normalized.recordOpen.target.surfaceId,
1382
+ previewSurfaceId: normalized.previewSurfaceId || normalized.recordOpen.target.surfaceId,
1383
+ identity: candidate.trim(),
1384
+ };
1385
+ }
1386
+ return null;
1387
+ }
1388
+ /**
1389
+ * Verifica se a âncora efêmera de runtime permanece conectada e visível na viewport.
1390
+ */
1391
+ function isResourceQuickViewAnchorValid(anchor, trigger) {
1392
+ if (!anchor || typeof anchor !== 'object') {
1393
+ return false;
1394
+ }
1395
+ if (typeof anchor.isValid === 'function' && !anchor.isValid()) {
1396
+ return false;
1397
+ }
1398
+ const viewportWidth = typeof window !== 'undefined' && Number.isFinite(window.innerWidth) && window.innerWidth > 0
1399
+ ? window.innerWidth
1400
+ : 1920;
1401
+ const viewportHeight = typeof window !== 'undefined' && Number.isFinite(window.innerHeight) && window.innerHeight > 0
1402
+ ? window.innerHeight
1403
+ : 1080;
1404
+ if (anchor.kind === 'element') {
1405
+ const el = anchor.element;
1406
+ if (!el || typeof el.getBoundingClientRect !== 'function' || el.isConnected === false) {
1407
+ return false;
1408
+ }
1409
+ const rect = el.getBoundingClientRect();
1410
+ if (!Number.isFinite(rect.left) || !Number.isFinite(rect.top)) {
1411
+ return false;
1412
+ }
1413
+ if (rect.width === 0 && rect.height === 0) {
1414
+ return false;
1415
+ }
1416
+ const edgeTolerance = trigger === 'focus-shortcut' || trigger === 'explicit-button' ? 96 : 0;
1417
+ return (rect.bottom >= -edgeTolerance &&
1418
+ rect.right >= -edgeTolerance &&
1419
+ rect.top <= viewportHeight + edgeTolerance &&
1420
+ rect.left <= viewportWidth + edgeTolerance);
1421
+ }
1422
+ if (anchor.kind === 'virtual-rect') {
1423
+ if (!anchor.anchorKey || !anchor.anchorKey.trim()) {
1424
+ return false;
1425
+ }
1426
+ if (anchor.hostElement && anchor.hostElement.isConnected === false) {
1427
+ return false;
1428
+ }
1429
+ if (typeof anchor.getViewportRect !== 'function') {
1430
+ return false;
1431
+ }
1432
+ const rect = anchor.getViewportRect();
1433
+ if (!rect ||
1434
+ !Number.isFinite(rect.x) ||
1435
+ !Number.isFinite(rect.y) ||
1436
+ !Number.isFinite(rect.width) ||
1437
+ !Number.isFinite(rect.height) ||
1438
+ rect.width < 0 ||
1439
+ rect.height < 0) {
1440
+ return false;
1441
+ }
1442
+ const right = rect.right ?? rect.x + rect.width;
1443
+ const bottom = rect.bottom ?? rect.y + rect.height;
1444
+ const left = rect.left ?? rect.x;
1445
+ const top = rect.top ?? rect.y;
1446
+ return (bottom >= 0 &&
1447
+ right >= 0 &&
1448
+ top <= viewportHeight &&
1449
+ left <= viewportWidth);
1450
+ }
1451
+ return false;
1452
+ }
1453
+ function resolveQuickViewAnchorKey(anchor) {
1454
+ if (anchor.kind === 'virtual-rect') {
1455
+ return anchor.anchorKey.trim();
1456
+ }
1457
+ const explicit = anchor.anchorKey?.trim();
1458
+ if (explicit) {
1459
+ return explicit;
1460
+ }
1461
+ const focusKey = anchor.element?.getAttribute?.('data-praxis-focus-key')?.trim();
1462
+ if (focusKey) {
1463
+ return focusKey;
1464
+ }
1465
+ const id = anchor.element?.id?.trim();
1466
+ if (id) {
1467
+ return `element:${id}`;
1468
+ }
1469
+ return 'element:anonymous';
881
1470
  }
882
1471
 
883
1472
  const TONES = new Set([
884
1473
  'neutral',
1474
+ 'primary',
1475
+ 'secondary',
885
1476
  'info',
886
1477
  'success',
887
1478
  'warning',
888
1479
  'danger',
889
1480
  ]);
1481
+ const TONE_ALIASES = {
1482
+ muted: 'neutral',
1483
+ positive: 'success',
1484
+ critical: 'danger',
1485
+ negative: 'danger',
1486
+ };
890
1487
  const APPEARANCES = new Set([
891
1488
  'plain',
892
1489
  'soft',
@@ -923,6 +1520,9 @@ function resolveFieldPresentation(base, rules, context = {}, options = {}) {
923
1520
  ...effect,
924
1521
  };
925
1522
  matchedRule = true;
1523
+ if (options.matchPolicy === 'first') {
1524
+ break;
1525
+ }
926
1526
  }
927
1527
  return matchedRule ? { ...resolved, matchedRule } : resolved;
928
1528
  }
@@ -937,8 +1537,8 @@ function normalizeFieldPresentation(value) {
937
1537
  const label = normalizeText(value.label);
938
1538
  const badge = normalizeText(value.badge);
939
1539
  const tooltip = normalizeText(value.tooltip);
940
- const prefix = normalizeText(value.prefix);
941
- const suffix = normalizeText(value.suffix);
1540
+ const prefix = normalizeAffix$1(value.prefix);
1541
+ const suffix = normalizeAffix$1(value.suffix);
942
1542
  const iconTrue = normalizeText(value.iconTrue);
943
1543
  const iconFalse = normalizeText(value.iconFalse);
944
1544
  const toneTrue = normalizeTone(value.toneTrue);
@@ -971,6 +1571,42 @@ function normalizeFieldPresentation(value) {
971
1571
  : {}),
972
1572
  };
973
1573
  }
1574
+ function normalizeFieldPresentationRules(value) {
1575
+ if (!Array.isArray(value) || value.length === 0) {
1576
+ return undefined;
1577
+ }
1578
+ const normalized = [];
1579
+ for (const candidate of value) {
1580
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
1581
+ continue;
1582
+ }
1583
+ const rule = candidate;
1584
+ if (!Object.prototype.hasOwnProperty.call(rule, 'when')) {
1585
+ continue;
1586
+ }
1587
+ const when = rule['when'];
1588
+ if (when === undefined) {
1589
+ continue;
1590
+ }
1591
+ const normalizedSet = rule['set'] && typeof rule['set'] === 'object' && !Array.isArray(rule['set'])
1592
+ ? normalizeFieldPresentation(rule['set'])
1593
+ : undefined;
1594
+ const normalizedEffect = rule['effect'] && typeof rule['effect'] === 'object' && !Array.isArray(rule['effect'])
1595
+ ? normalizeFieldPresentation(rule['effect'])
1596
+ : undefined;
1597
+ const hasSet = !!normalizedSet && Object.keys(normalizedSet).length > 0;
1598
+ const hasEffect = !!normalizedEffect && Object.keys(normalizedEffect).length > 0;
1599
+ if (!hasSet && !hasEffect) {
1600
+ continue;
1601
+ }
1602
+ normalized.push({
1603
+ when,
1604
+ ...(hasSet ? { set: normalizedSet } : {}),
1605
+ ...(hasEffect ? { effect: normalizedEffect } : {}),
1606
+ });
1607
+ }
1608
+ return normalized.length > 0 ? normalized : undefined;
1609
+ }
974
1610
  function matchesPresentationRule(rule, context, jsonLogic) {
975
1611
  try {
976
1612
  const result = jsonLogic.evaluate(rule.when, context);
@@ -978,15 +1614,87 @@ function matchesPresentationRule(rule, context, jsonLogic) {
978
1614
  ? jsonLogic.truthy(result)
979
1615
  : Boolean(result);
980
1616
  }
981
- catch {
1617
+ catch {
1618
+ return false;
1619
+ }
1620
+ }
1621
+ function normalizePresenter(value) {
1622
+ return normalizeEnum(value, PRESENTERS);
1623
+ }
1624
+ function normalizeTone(value) {
1625
+ if (typeof value !== 'string') {
1626
+ return undefined;
1627
+ }
1628
+ const normalized = value.trim().toLowerCase();
1629
+ if (!normalized) {
1630
+ return undefined;
1631
+ }
1632
+ if (TONES.has(normalized)) {
1633
+ return normalized;
1634
+ }
1635
+ return TONE_ALIASES[normalized];
1636
+ }
1637
+ const MASKED_TOKEN_SYMBOL_REGEX = /\*{2,}|•{2,}|■{2,}|█{2,}/;
1638
+ const MASKED_TOKEN_LABEL_REGEX = /^\[?\s*(MASKED|REDACTED|PROTEGIDO|OCULTO|ANONIMIZADO)\s*\]?$/i;
1639
+ /**
1640
+ * Identifies masked or redacted display values produced by privacy/LGPD governance policies.
1641
+ */
1642
+ function isMaskedPresentationToken(value) {
1643
+ if (value === null || value === undefined) {
1644
+ return false;
1645
+ }
1646
+ const candidate = String(value).trim();
1647
+ if (!candidate) {
982
1648
  return false;
983
1649
  }
1650
+ return MASKED_TOKEN_SYMBOL_REGEX.test(candidate) || MASKED_TOKEN_LABEL_REGEX.test(candidate);
984
1651
  }
985
- function normalizePresenter(value) {
986
- return normalizeEnum(value, PRESENTERS);
1652
+ /**
1653
+ * Resolves visual prefix/suffix affixes around non-empty display text while:
1654
+ * - returning `null` for null/blank text (preventing orphan affixes),
1655
+ * - suppressing affixes on LGPD-masked tokens,
1656
+ * - avoiding affix duplication when the formatted text already carries the affix.
1657
+ */
1658
+ function resolveAffixedPresentationParts(rawText, affixes) {
1659
+ if (rawText === null || rawText === undefined) {
1660
+ return null;
1661
+ }
1662
+ const text = String(rawText).trim();
1663
+ if (!text) {
1664
+ return null;
1665
+ }
1666
+ if (isMaskedPresentationToken(text)) {
1667
+ return {
1668
+ text,
1669
+ prefix: null,
1670
+ suffix: null,
1671
+ masked: true,
1672
+ };
1673
+ }
1674
+ const candidatePrefix = typeof affixes?.prefix === 'string' && affixes.prefix.trim().length > 0
1675
+ ? affixes.prefix
1676
+ : null;
1677
+ const candidateSuffix = typeof affixes?.suffix === 'string' && affixes.suffix.trim().length > 0
1678
+ ? affixes.suffix
1679
+ : null;
1680
+ const prefix = candidatePrefix && !text.startsWith(candidatePrefix) ? candidatePrefix : null;
1681
+ const suffix = candidateSuffix && !text.endsWith(candidateSuffix) ? candidateSuffix : null;
1682
+ return {
1683
+ text,
1684
+ prefix,
1685
+ suffix,
1686
+ masked: false,
1687
+ };
987
1688
  }
988
- function normalizeTone(value) {
989
- return normalizeEnum(value, TONES);
1689
+ /**
1690
+ * Formats non-empty display text with deduplicated visual affixes, omitting affixes on masked tokens.
1691
+ */
1692
+ function formatAffixedPresentationText(rawText, affixes) {
1693
+ const parts = resolveAffixedPresentationParts(rawText, affixes);
1694
+ if (!parts) {
1695
+ return null;
1696
+ }
1697
+ return `${parts.prefix ?? ''}${parts.text}${parts.suffix ?? ''}`;
990
1698
  }
991
1699
  function normalizeAppearance(value) {
992
1700
  return normalizeEnum(value, APPEARANCES);
@@ -1005,15 +1713,479 @@ function normalizeText(value) {
1005
1713
  const trimmed = value.trim();
1006
1714
  return trimmed.length ? trimmed : undefined;
1007
1715
  }
1716
+ function normalizeAffix$1(value) {
1717
+ return typeof value === 'string' && value.trim().length > 0 ? value : undefined;
1718
+ }
1008
1719
  function normalizeInteractions(value) {
1720
+ const quickView = normalizeResourceQuickViewBinding(value.quickView);
1009
1721
  return {
1010
1722
  ...(value.copy === true ? { copy: true } : {}),
1011
1723
  ...(value.details === true ? { details: true } : {}),
1012
1724
  ...(value.expand === true ? { expand: true } : {}),
1013
1725
  ...(value.link === true ? { link: true } : {}),
1726
+ ...(quickView ? { quickView } : {}),
1014
1727
  };
1015
1728
  }
1016
1729
 
1730
+ /** Converts UI tokens only under declared scalar items; invalid input is never dropped or partially converted. */
1731
+ function normalizeScalarArrayValue(value, items) {
1732
+ if (items.enum !== undefined && !isScalarEnum(items.enum))
1733
+ return { valid: false, invalidIndices: [-1] };
1734
+ if (value == null)
1735
+ return { valid: true, value };
1736
+ if (!Array.isArray(value))
1737
+ return { valid: false, invalidIndices: [-1] };
1738
+ const converted = [];
1739
+ const invalidIndices = [];
1740
+ for (let index = 0; index < value.length; index += 1) {
1741
+ const item = normalizeItem(value[index], items);
1742
+ if (item === undefined || items.enum && !items.enum.some(candidate => candidate === item))
1743
+ invalidIndices.push(index);
1744
+ else
1745
+ converted.push(item);
1746
+ }
1747
+ return invalidIndices.length ? { valid: false, invalidIndices } : { valid: true, value: converted };
1748
+ }
1749
+ function normalizeItem(value, items) {
1750
+ if (value == null)
1751
+ return undefined;
1752
+ if (items.type === 'boolean') {
1753
+ if (typeof value === 'boolean')
1754
+ return value;
1755
+ return value === 'true' ? true : value === 'false' ? false : undefined;
1756
+ }
1757
+ if (items.type === 'integer' || items.type === 'number') {
1758
+ const number = typeof value === 'number' ? value : typeof value === 'string' &&
1759
+ /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(value) ? Number(value) : NaN;
1760
+ if (!Number.isFinite(number) || items.type === 'integer' && !Number.isSafeInteger(number))
1761
+ return undefined;
1762
+ return number;
1763
+ }
1764
+ if (items.type !== 'string')
1765
+ return undefined;
1766
+ if (items.format === 'date') {
1767
+ if (value instanceof Date) {
1768
+ if (Number.isNaN(value.getTime()))
1769
+ return undefined;
1770
+ const date = `${String(value.getFullYear()).padStart(4, '0')}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`;
1771
+ return isIsoDate(date) ? date : undefined;
1772
+ }
1773
+ return typeof value === 'string' && isIsoDate(value) ? value : undefined;
1774
+ }
1775
+ if (items.format === 'date-time') {
1776
+ if (value instanceof Date)
1777
+ return Number.isNaN(value.getTime()) ? undefined : value.toISOString();
1778
+ return typeof value === 'string' && isIsoDateTime(value) ? value : undefined;
1779
+ }
1780
+ return typeof value === 'string' ? value : undefined;
1781
+ }
1782
+ function isIsoDate(value) {
1783
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
1784
+ if (!match)
1785
+ return false;
1786
+ const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
1787
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
1788
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
1789
+ return month >= 1 && month <= 12 && day >= 1 && day <= days[month - 1];
1790
+ }
1791
+ function isIsoDateTime(value) {
1792
+ const match = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(?:Z|([+-])(\d{2}):(\d{2}))?$/.exec(value);
1793
+ if (!match || !isIsoDate(match[1]))
1794
+ return false;
1795
+ if (Number(match[2]) > 23 || Number(match[3]) > 59 || Number(match[4] ?? 0) > 59)
1796
+ return false;
1797
+ const offsetHours = Number(match[7] ?? 0), offsetMinutes = Number(match[8] ?? 0);
1798
+ return offsetHours <= 18 && offsetMinutes <= 59 && (offsetHours !== 18 || offsetMinutes === 0);
1799
+ }
1800
+ /** Internal admission of the scalar subset already published in JSON Schema items. */
1801
+ function normalizeScalarItemsSchema(value) {
1802
+ if (!value || typeof value !== 'object' || Array.isArray(value))
1803
+ return undefined;
1804
+ const record = value;
1805
+ if (typeof record['type'] !== 'string' || !['string', 'integer', 'number', 'boolean'].includes(record['type']))
1806
+ return undefined;
1807
+ const result = { type: record['type'] };
1808
+ if (typeof record['format'] === 'string')
1809
+ result.format = record['format'];
1810
+ if (record['enum'] !== undefined) {
1811
+ if (!isScalarEnum(record['enum']))
1812
+ throw new TypeError('Scalar items enum must contain JSON scalar values.');
1813
+ result.enum = [...record['enum']];
1814
+ }
1815
+ return result;
1816
+ }
1817
+ function isScalarEnum(value) {
1818
+ return Array.isArray(value) && value.length > 0 && value.every(item => item === null || typeof item === 'string' || typeof item === 'boolean' || typeof item === 'number' && Number.isFinite(item));
1819
+ }
1820
+
1821
+ /**
1822
+ * Enum que define os tipos de controle (`CONTROL_TYPE`) disponíveis para a apresentação dos campos de formulário.
1823
+ *
1824
+ * O `CONTROL_TYPE` especifica o tipo de elemento de UI (User Interface) que será usado para capturar ou exibir dados do campo.
1825
+ * Essa configuração permite que a camada de apresentação saiba como renderizar o campo e oferecer a interação adequada ao usuário.
1826
+ * Em casos onde o `CONTROL_TYPE` não é especificado, a camada de apresentação pode usar o valor de `TYPE` (definido em `FieldDataType`)
1827
+ * para decidir o controle mais adequado de forma automática.
1828
+ */
1829
+ const FieldControlType = {
1830
+ AI_PROMPT: 'aiPrompt',
1831
+ APP_BAR: 'appBar',
1832
+ ARC_GAUGE: 'arcGauge',
1833
+ ARRAY_INPUT: 'array',
1834
+ ASYNC_SELECT: 'async-select',
1835
+ AUTO_COMPLETE: 'autoComplete',
1836
+ AVATAR: 'avatar',
1837
+ BARCODE_GENERATOR: 'barcodeGenerator',
1838
+ BOTTOM_NAVIGATION: 'bottomNavigation',
1839
+ BREADCRUMB: 'breadcrumb',
1840
+ BUTTON: 'button',
1841
+ BUTTON_TOGGLE: 'buttonToggle',
1842
+ CALENDAR: 'calendar',
1843
+ CARD: 'card',
1844
+ CHECKBOX: 'checkbox',
1845
+ CHIP_INPUT: 'chipInput',
1846
+ CHIP_LIST: 'chipList',
1847
+ CIRCULAR_GAUGE: 'circularGauge',
1848
+ COLOR_GRADIENT: 'colorGradient',
1849
+ CPF_CNPJ_INPUT: 'cpfCnpjInput',
1850
+ COLOR_PALETTE: 'colorPalette',
1851
+ COLOR_PICKER: 'colorPicker',
1852
+ COLOR_INPUT: 'color',
1853
+ CRON_BUILDER: 'cronBuilder',
1854
+ CONTEXT_MENU: 'contextMenu',
1855
+ CONVERSATIONAL_UI: 'conversationalUI',
1856
+ CURRENCY_INPUT: 'currency',
1857
+ DATE_INPUT: 'dateInput',
1858
+ DATE_PICKER: 'date',
1859
+ DATE_RANGE: 'dateRange',
1860
+ DATE_TIME_PICKER: 'dateTime',
1861
+ DATE_TIME_RANGE: 'dateTimeRange',
1862
+ DATETIME_LOCAL_INPUT: 'dateTimeLocal',
1863
+ DIALOG: 'dialog',
1864
+ DRAWER: 'drawer',
1865
+ DROP_DOWN_TREE: 'dropDownTree',
1866
+ EMAIL_INPUT: 'email',
1867
+ ENTITY_LOOKUP: 'entityLookup',
1868
+ EXPANSION_PANEL: 'expansionPanel',
1869
+ FILE_SAVER: 'fileSaver',
1870
+ FILE_SELECT: 'fileSelect',
1871
+ FILE_UPLOAD: 'upload',
1872
+ FILTER: 'filter',
1873
+ FLOATING_LABEL: 'floatingLabel',
1874
+ FLOATING_ACTION_BUTTON: 'floatingActionButton',
1875
+ GRID: 'grid',
1876
+ GRID_LAYOUT: 'gridLayout',
1877
+ INPUT: 'input',
1878
+ INLINE_SELECT: 'inlineSelect',
1879
+ INLINE_SEARCHABLE_SELECT: 'inlineSearchableSelect',
1880
+ INLINE_ASYNC_SELECT: 'inlineAsyncSelect',
1881
+ INLINE_ENTITY_LOOKUP: 'inlineEntityLookup',
1882
+ INLINE_AUTOCOMPLETE: 'inlineAutocomplete',
1883
+ INLINE_INPUT: 'inlineInput',
1884
+ INLINE_PHONE: 'inlinePhone',
1885
+ INLINE_NUMBER: 'inlineNumber',
1886
+ INLINE_CURRENCY: 'inlineCurrency',
1887
+ INLINE_CURRENCY_RANGE: 'inlineCurrencyRange',
1888
+ INLINE_MULTISELECT: 'inlineMultiSelect',
1889
+ INLINE_TOGGLE: 'inlineToggle',
1890
+ INLINE_RANGE: 'inlineRange',
1891
+ INLINE_PERIOD_RANGE: 'inlinePeriodRange',
1892
+ INLINE_YEAR_RANGE: 'inlineYearRange',
1893
+ INLINE_MONTH_RANGE: 'inlineMonthRange',
1894
+ INLINE_DATE: 'inlineDate',
1895
+ INLINE_DATE_RANGE: 'inlineDateRange',
1896
+ INLINE_TIME: 'inlineTime',
1897
+ INLINE_TIME_RANGE: 'inlineTimeRange',
1898
+ INLINE_TREE_SELECT: 'inlineTreeSelect',
1899
+ INLINE_RATING: 'inlineRating',
1900
+ INLINE_DISTANCE_RADIUS: 'inlineDistanceRadius',
1901
+ INLINE_PIPELINE_STATUS: 'inlinePipelineStatus',
1902
+ INLINE_SCORE_PRIORITY: 'inlineScorePriority',
1903
+ INLINE_RELATIVE_PERIOD: 'inlineRelativePeriod',
1904
+ INLINE_SENTIMENT: 'inlineSentiment',
1905
+ INLINE_COLOR_LABEL: 'inlineColorLabel',
1906
+ LINEAR_GAUGE: 'linearGauge',
1907
+ LIST_VIEW: 'listView',
1908
+ MAP: 'map',
1909
+ MASKED_TEXT_BOX: 'maskedTextBox',
1910
+ MONTH_INPUT: 'month',
1911
+ MULTI_COLUMN_COMBO_BOX: 'multiColumnComboBox',
1912
+ MULTI_SELECT: 'multiSelect',
1913
+ MULTI_SELECT_TREE: 'multiSelectTree',
1914
+ TRANSFER_LIST: 'transferList',
1915
+ NOTIFICATION: 'notification',
1916
+ NUMERIC_TEXT_BOX: 'numericTextBox',
1917
+ PAGER: 'pager',
1918
+ PAGINATOR: 'paginator',
1919
+ PASSWORD: 'password',
1920
+ PDF_VIEWER: 'pdfViewer',
1921
+ PHONE: 'phone',
1922
+ PIVOT_GRID: 'pivotGrid',
1923
+ POPUP: 'popup',
1924
+ PROGRESS_BAR: 'progressBar',
1925
+ PROGRESS_SPINNER: 'progressSpinner',
1926
+ QR_CODE: 'qrCode',
1927
+ RADIO: 'radio',
1928
+ RADIAL_GAUGE: 'radialGauge',
1929
+ RANGE_SLIDER: 'rangeSlider',
1930
+ PRICE_RANGE: 'priceRange',
1931
+ RATING: 'rating',
1932
+ RICH_TEXT_EDITOR: 'richTextEditor',
1933
+ RIPPLE: 'ripple',
1934
+ SCROLL_VIEW: 'scrollView',
1935
+ SEARCH_INPUT: 'search',
1936
+ SEARCHABLE_SELECT: 'searchable-select',
1937
+ SELECTION_LIST: 'selectionList',
1938
+ SELECT: 'select',
1939
+ SIGNATURE: 'signature',
1940
+ SLIDER: 'slider',
1941
+ SORTABLE: 'sortable',
1942
+ SORTABLE_TABLE: 'sortableTable',
1943
+ SPLITTER: 'splitter',
1944
+ SPREADSHEET: 'spreadsheet',
1945
+ STACK_LAYOUT: 'stackLayout',
1946
+ STEP_BAR: 'stepBar',
1947
+ STEPPER: 'stepper',
1948
+ SVG_ICON: 'svgIcon',
1949
+ TABS: 'tabs',
1950
+ TEXTAREA: 'textarea',
1951
+ TIME_INPUT: 'time',
1952
+ TIME_PICKER: 'timePicker',
1953
+ TIME_RANGE: 'timeRange',
1954
+ TIMELINE: 'timeline',
1955
+ TOGGLE: 'toggle',
1956
+ TOOLBAR: 'toolbar',
1957
+ TOOLTIP: 'tooltip',
1958
+ TREE_VIEW: 'treeView',
1959
+ TREE_SELECT: 'treeSelect',
1960
+ TYPOGRAPHY: 'typography',
1961
+ URL_INPUT: 'url',
1962
+ WEEK_INPUT: 'week',
1963
+ WINDOW: 'window',
1964
+ YEAR_INPUT: 'year',
1965
+ };
1966
+
1967
+ const INLINE_FILTER_CONTROL_TYPES = Object.freeze({
1968
+ SELECT: FieldControlType.INLINE_SELECT,
1969
+ SEARCHABLE_SELECT: FieldControlType.INLINE_SEARCHABLE_SELECT,
1970
+ ASYNC_SELECT: FieldControlType.INLINE_ASYNC_SELECT,
1971
+ ENTITY_LOOKUP: FieldControlType.INLINE_ENTITY_LOOKUP,
1972
+ AUTOCOMPLETE: FieldControlType.INLINE_AUTOCOMPLETE,
1973
+ NUMBER: FieldControlType.INLINE_NUMBER,
1974
+ CURRENCY: FieldControlType.INLINE_CURRENCY,
1975
+ CURRENCY_RANGE: FieldControlType.INLINE_CURRENCY_RANGE,
1976
+ MULTI_SELECT: FieldControlType.INLINE_MULTISELECT,
1977
+ INPUT: FieldControlType.INLINE_INPUT,
1978
+ PHONE: FieldControlType.INLINE_PHONE,
1979
+ TOGGLE: FieldControlType.INLINE_TOGGLE,
1980
+ RANGE: FieldControlType.INLINE_RANGE,
1981
+ PERIOD_RANGE: FieldControlType.INLINE_PERIOD_RANGE,
1982
+ YEAR_RANGE: FieldControlType.INLINE_YEAR_RANGE,
1983
+ MONTH_RANGE: FieldControlType.INLINE_MONTH_RANGE,
1984
+ DATE: FieldControlType.INLINE_DATE,
1985
+ DATE_RANGE: FieldControlType.INLINE_DATE_RANGE,
1986
+ TIME: FieldControlType.INLINE_TIME,
1987
+ TIME_RANGE: FieldControlType.INLINE_TIME_RANGE,
1988
+ TREE_SELECT: FieldControlType.INLINE_TREE_SELECT,
1989
+ RATING: FieldControlType.INLINE_RATING,
1990
+ DISTANCE_RADIUS: FieldControlType.INLINE_DISTANCE_RADIUS,
1991
+ PIPELINE_STATUS: FieldControlType.INLINE_PIPELINE_STATUS,
1992
+ SCORE_PRIORITY: FieldControlType.INLINE_SCORE_PRIORITY,
1993
+ RELATIVE_PERIOD: FieldControlType.INLINE_RELATIVE_PERIOD,
1994
+ SENTIMENT: FieldControlType.INLINE_SENTIMENT,
1995
+ COLOR_LABEL: FieldControlType.INLINE_COLOR_LABEL,
1996
+ });
1997
+ const INLINE_FILTER_CONTROL_TYPE_VALUES = Object.freeze(Object.values(INLINE_FILTER_CONTROL_TYPES));
1998
+ const INLINE_FILTER_CONTROL_TYPE_SET = new Set(INLINE_FILTER_CONTROL_TYPE_VALUES);
1999
+ function normalizeInlineControlTypeToken(value) {
2000
+ return String(value || '')
2001
+ .trim()
2002
+ .toLowerCase()
2003
+ .replace(/[-_\s]/g, '');
2004
+ }
2005
+ const INLINE_FILTER_CANONICAL_TOKEN_TO_CONTROL_TYPE_MAP = {
2006
+ inlineselect: INLINE_FILTER_CONTROL_TYPES.SELECT,
2007
+ inlinesearchableselect: INLINE_FILTER_CONTROL_TYPES.SEARCHABLE_SELECT,
2008
+ inlineasyncselect: INLINE_FILTER_CONTROL_TYPES.ASYNC_SELECT,
2009
+ inlineentitylookup: INLINE_FILTER_CONTROL_TYPES.ENTITY_LOOKUP,
2010
+ inlineautocomplete: INLINE_FILTER_CONTROL_TYPES.AUTOCOMPLETE,
2011
+ inlinenumber: INLINE_FILTER_CONTROL_TYPES.NUMBER,
2012
+ inlinecurrency: INLINE_FILTER_CONTROL_TYPES.CURRENCY,
2013
+ inlinecurrencyrange: INLINE_FILTER_CONTROL_TYPES.CURRENCY_RANGE,
2014
+ inlinemultiselect: INLINE_FILTER_CONTROL_TYPES.MULTI_SELECT,
2015
+ inlineinput: INLINE_FILTER_CONTROL_TYPES.INPUT,
2016
+ inlinephone: INLINE_FILTER_CONTROL_TYPES.PHONE,
2017
+ inlinetoggle: INLINE_FILTER_CONTROL_TYPES.TOGGLE,
2018
+ inlinerange: INLINE_FILTER_CONTROL_TYPES.RANGE,
2019
+ inlineperiodrange: INLINE_FILTER_CONTROL_TYPES.PERIOD_RANGE,
2020
+ inlineyearrange: INLINE_FILTER_CONTROL_TYPES.YEAR_RANGE,
2021
+ inlinemonthrange: INLINE_FILTER_CONTROL_TYPES.MONTH_RANGE,
2022
+ inlinedate: INLINE_FILTER_CONTROL_TYPES.DATE,
2023
+ inlinedaterange: INLINE_FILTER_CONTROL_TYPES.DATE_RANGE,
2024
+ inlinetime: INLINE_FILTER_CONTROL_TYPES.TIME,
2025
+ inlinetimerange: INLINE_FILTER_CONTROL_TYPES.TIME_RANGE,
2026
+ inlinetreeselect: INLINE_FILTER_CONTROL_TYPES.TREE_SELECT,
2027
+ inlinerating: INLINE_FILTER_CONTROL_TYPES.RATING,
2028
+ inlinedistanceradius: INLINE_FILTER_CONTROL_TYPES.DISTANCE_RADIUS,
2029
+ inlinepipelinestatus: INLINE_FILTER_CONTROL_TYPES.PIPELINE_STATUS,
2030
+ inlinescorepriority: INLINE_FILTER_CONTROL_TYPES.SCORE_PRIORITY,
2031
+ inlinerelativeperiod: INLINE_FILTER_CONTROL_TYPES.RELATIVE_PERIOD,
2032
+ inlinesentiment: INLINE_FILTER_CONTROL_TYPES.SENTIMENT,
2033
+ inlinecolorlabel: INLINE_FILTER_CONTROL_TYPES.COLOR_LABEL,
2034
+ };
2035
+ const INLINE_FILTER_ALIAS_TOKEN_MAP = {};
2036
+ for (const [token, controlType] of Object.entries(INLINE_FILTER_CANONICAL_TOKEN_TO_CONTROL_TYPE_MAP)) {
2037
+ INLINE_FILTER_ALIAS_TOKEN_MAP[`filter${token}`] = controlType;
2038
+ INLINE_FILTER_ALIAS_TOKEN_MAP[`pdxfilter${token}`] = controlType;
2039
+ }
2040
+ const INLINE_FILTER_TOKEN_TO_CONTROL_TYPE = Object.freeze({
2041
+ ...INLINE_FILTER_CANONICAL_TOKEN_TO_CONTROL_TYPE_MAP,
2042
+ ...INLINE_FILTER_ALIAS_TOKEN_MAP,
2043
+ });
2044
+ const INLINE_FILTER_ALIAS_TOKENS = Object.freeze(Object.keys(INLINE_FILTER_ALIAS_TOKEN_MAP));
2045
+ const INLINE_FILTER_CANONICAL_TOKEN_TO_BASE_CONTROL_TYPE_MAP = {
2046
+ inlineselect: FieldControlType.SELECT,
2047
+ inlinesearchableselect: FieldControlType.SEARCHABLE_SELECT,
2048
+ inlineasyncselect: FieldControlType.ASYNC_SELECT,
2049
+ inlineentitylookup: FieldControlType.ENTITY_LOOKUP,
2050
+ inlineautocomplete: FieldControlType.AUTO_COMPLETE,
2051
+ inlinenumber: FieldControlType.NUMERIC_TEXT_BOX,
2052
+ inlinecurrency: FieldControlType.CURRENCY_INPUT,
2053
+ inlinecurrencyrange: FieldControlType.PRICE_RANGE,
2054
+ inlinemultiselect: FieldControlType.MULTI_SELECT,
2055
+ inlineinput: FieldControlType.INPUT,
2056
+ inlinephone: FieldControlType.PHONE,
2057
+ inlinetoggle: FieldControlType.TOGGLE,
2058
+ inlinerange: FieldControlType.RANGE_SLIDER,
2059
+ inlineperiodrange: FieldControlType.RANGE_SLIDER,
2060
+ inlineyearrange: FieldControlType.YEAR_INPUT,
2061
+ inlinemonthrange: FieldControlType.MONTH_INPUT,
2062
+ inlinedate: FieldControlType.DATE_PICKER,
2063
+ inlinedaterange: FieldControlType.DATE_RANGE,
2064
+ inlinetime: FieldControlType.TIME_PICKER,
2065
+ inlinetimerange: FieldControlType.TIME_RANGE,
2066
+ inlinetreeselect: FieldControlType.TREE_SELECT,
2067
+ inlinerating: FieldControlType.RATING,
2068
+ inlinedistanceradius: FieldControlType.INLINE_DISTANCE_RADIUS,
2069
+ inlinepipelinestatus: FieldControlType.INLINE_PIPELINE_STATUS,
2070
+ inlinescorepriority: FieldControlType.INLINE_SCORE_PRIORITY,
2071
+ inlinerelativeperiod: FieldControlType.INLINE_RELATIVE_PERIOD,
2072
+ inlinesentiment: FieldControlType.INLINE_SENTIMENT,
2073
+ inlinecolorlabel: FieldControlType.INLINE_COLOR_LABEL,
2074
+ };
2075
+ const INLINE_FILTER_ALIAS_TOKEN_TO_BASE_CONTROL_TYPE_MAP = {};
2076
+ for (const [aliasToken, controlType] of Object.entries(INLINE_FILTER_ALIAS_TOKEN_MAP)) {
2077
+ const canonicalToken = aliasToken.startsWith('pdxfilter')
2078
+ ? aliasToken.replace(/^pdxfilter/, '')
2079
+ : aliasToken.replace(/^filter/, '');
2080
+ const baseControlType = INLINE_FILTER_CANONICAL_TOKEN_TO_BASE_CONTROL_TYPE_MAP[canonicalToken];
2081
+ if (baseControlType) {
2082
+ INLINE_FILTER_ALIAS_TOKEN_TO_BASE_CONTROL_TYPE_MAP[aliasToken] = baseControlType;
2083
+ }
2084
+ }
2085
+ const INLINE_FILTER_TOKEN_TO_BASE_CONTROL_TYPE = Object.freeze({
2086
+ ...INLINE_FILTER_CANONICAL_TOKEN_TO_BASE_CONTROL_TYPE_MAP,
2087
+ ...INLINE_FILTER_ALIAS_TOKEN_TO_BASE_CONTROL_TYPE_MAP,
2088
+ });
2089
+ function resolveInlineFilterControlType(value) {
2090
+ const token = normalizeInlineControlTypeToken(value);
2091
+ if (!token)
2092
+ return undefined;
2093
+ return INLINE_FILTER_TOKEN_TO_CONTROL_TYPE[token];
2094
+ }
2095
+ function resolveInlineFilterControlTypeToBaseControlType(value) {
2096
+ const token = normalizeInlineControlTypeToken(value);
2097
+ if (!token)
2098
+ return undefined;
2099
+ return INLINE_FILTER_TOKEN_TO_BASE_CONTROL_TYPE[token];
2100
+ }
2101
+ function isInlineFilterControlType(value) {
2102
+ return INLINE_FILTER_CONTROL_TYPE_SET.has(String(value || '').trim());
2103
+ }
2104
+
2105
+ function toUpperSnakeCase(raw) {
2106
+ return raw
2107
+ .trim()
2108
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
2109
+ .replace(/[-\s]+/g, '_')
2110
+ .replace(/__+/g, '_')
2111
+ .toUpperCase();
2112
+ }
2113
+ function normalizeControlTypeToken(value) {
2114
+ return String(value || '')
2115
+ .trim()
2116
+ .toLowerCase()
2117
+ .replace(/[-_\s]/g, '');
2118
+ }
2119
+ const CONTROL_TYPE_TOKEN_TO_KEY = Object.entries(FieldControlType).reduce((acc, [key, controlTypeValue]) => {
2120
+ acc[normalizeControlTypeToken(key)] = key;
2121
+ acc[normalizeControlTypeToken(controlTypeValue)] = key;
2122
+ return acc;
2123
+ }, {});
2124
+ const ALIAS_TOKEN_TO_CONTROL_TYPE = {
2125
+ // Legacy/common synonyms
2126
+ searchable: FieldControlType.SEARCHABLE_SELECT,
2127
+ searchableinput: FieldControlType.SEARCHABLE_SELECT,
2128
+ searchableselect: FieldControlType.SEARCHABLE_SELECT,
2129
+ materialsearchableselect: FieldControlType.SEARCHABLE_SELECT,
2130
+ asyncselect: FieldControlType.ASYNC_SELECT,
2131
+ materialasyncselect: FieldControlType.ASYNC_SELECT,
2132
+ entitylookup: FieldControlType.ENTITY_LOOKUP,
2133
+ materialentitylookup: FieldControlType.ENTITY_LOOKUP,
2134
+ autocomplete: FieldControlType.AUTO_COMPLETE,
2135
+ multiselect: FieldControlType.MULTI_SELECT,
2136
+ multiselecttree: FieldControlType.MULTI_SELECT_TREE,
2137
+ treeselect: FieldControlType.TREE_SELECT,
2138
+ datepicker: FieldControlType.DATE_PICKER,
2139
+ daterange: FieldControlType.DATE_RANGE,
2140
+ datetime: FieldControlType.DATETIME_LOCAL_INPUT,
2141
+ timepicker: FieldControlType.TIME_PICKER,
2142
+ timerange: FieldControlType.TIME_RANGE,
2143
+ pricerange: FieldControlType.PRICE_RANGE,
2144
+ rangeslider: FieldControlType.RANGE_SLIDER,
2145
+ number: FieldControlType.NUMERIC_TEXT_BOX,
2146
+ numeric: FieldControlType.NUMERIC_TEXT_BOX,
2147
+ currencyinput: FieldControlType.CURRENCY_INPUT,
2148
+ switch: FieldControlType.TOGGLE,
2149
+ radiogroup: FieldControlType.RADIO,
2150
+ checkboxgroup: FieldControlType.CHECKBOX,
2151
+ chiplist: FieldControlType.CHIP_LIST,
2152
+ chipinput: FieldControlType.CHIP_INPUT,
2153
+ searchinput: FieldControlType.SEARCH_INPUT,
2154
+ };
2155
+ function normalizeControlTypeKey(value) {
2156
+ const token = normalizeControlTypeToken(value);
2157
+ if (!token)
2158
+ return '';
2159
+ const resolvedKey = CONTROL_TYPE_TOKEN_TO_KEY[token];
2160
+ if (resolvedKey)
2161
+ return resolvedKey;
2162
+ return toUpperSnakeCase(String(value || ''));
2163
+ }
2164
+ function resolveControlTypeAlias(value, fallback = FieldControlType.INPUT) {
2165
+ const raw = String(value || '').trim();
2166
+ if (!raw)
2167
+ return fallback;
2168
+ const token = normalizeControlTypeToken(raw);
2169
+ const inlineAliased = INLINE_FILTER_TOKEN_TO_BASE_CONTROL_TYPE[token];
2170
+ if (inlineAliased)
2171
+ return inlineAliased;
2172
+ const aliased = ALIAS_TOKEN_TO_CONTROL_TYPE[token];
2173
+ if (aliased)
2174
+ return aliased;
2175
+ const resolvedKey = CONTROL_TYPE_TOKEN_TO_KEY[token];
2176
+ if (resolvedKey) {
2177
+ return FieldControlType[resolvedKey];
2178
+ }
2179
+ return raw;
2180
+ }
2181
+
2182
+ const MAX_OPTION_SOURCE_DEPTH = 3;
2183
+ // Mirrors the backend custom-field key policy. Ordinary static field names are
2184
+ // outside this boundary; custom keys must be safe across all runtime consumers.
2185
+ const RESERVED_CUSTOM_FIELD_KEYS = new Set([
2186
+ 'constructor', 'prototype', 'hasOwnProperty', 'isPrototypeOf',
2187
+ 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf',
2188
+ ]);
1017
2189
  const VALUE_PRESENTATION_TYPES = new Set([
1018
2190
  'string',
1019
2191
  'number',
@@ -1262,6 +2434,33 @@ class SchemaNormalizationKernel {
1262
2434
  }
1263
2435
  return false;
1264
2436
  }
2437
+ parseOptionalBoolean(value) {
2438
+ if (typeof value === 'boolean') {
2439
+ return value;
2440
+ }
2441
+ if (typeof value === 'string') {
2442
+ const normalized = value.trim().toLowerCase();
2443
+ if (normalized === 'true') {
2444
+ return true;
2445
+ }
2446
+ if (normalized === 'false') {
2447
+ return false;
2448
+ }
2449
+ }
2450
+ return undefined;
2451
+ }
2452
+ parseOptionalFiniteNumber(value) {
2453
+ if (typeof value === 'number' && Number.isFinite(value)) {
2454
+ return value;
2455
+ }
2456
+ if (typeof value === 'string' && value.trim().length > 0) {
2457
+ const parsed = Number(value);
2458
+ if (Number.isFinite(parsed)) {
2459
+ return parsed;
2460
+ }
2461
+ }
2462
+ return undefined;
2463
+ }
1265
2464
  /** Ensure an array of strings from various inputs. */
1266
2465
  parseStringArray(value) {
1267
2466
  if (Array.isArray(value)) {
@@ -1278,6 +2477,41 @@ class SchemaNormalizationKernel {
1278
2477
  .filter((v) => v.length > 0);
1279
2478
  return normalized.filter((v, index) => normalized.indexOf(v) === index);
1280
2479
  }
2480
+ parseDependsOn(value) {
2481
+ const rawItems = Array.isArray(value)
2482
+ ? value
2483
+ : typeof value === 'string'
2484
+ ? value.split(',')
2485
+ : [];
2486
+ const normalized = rawItems
2487
+ .map((item) => (typeof item === 'string' ? item.trim() : ''))
2488
+ .filter((item) => item.length > 0);
2489
+ return normalized.filter((item, index) => normalized.indexOf(item) === index);
2490
+ }
2491
+ parseStrictStringRecord(value) {
2492
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
2493
+ return undefined;
2494
+ }
2495
+ const normalized = Object.entries(value)
2496
+ .reduce((acc, [key, mapValue]) => {
2497
+ if (typeof mapValue !== 'string') {
2498
+ return acc;
2499
+ }
2500
+ const normalizedKey = String(key).trim();
2501
+ if (!normalizedKey ||
2502
+ normalizedKey === '__proto__' ||
2503
+ normalizedKey === 'constructor' ||
2504
+ normalizedKey === 'prototype') {
2505
+ return acc;
2506
+ }
2507
+ const normalizedValue = mapValue.trim();
2508
+ if (normalizedValue) {
2509
+ acc[normalizedKey] = normalizedValue;
2510
+ }
2511
+ return acc;
2512
+ }, {});
2513
+ return Object.keys(normalized).length ? normalized : undefined;
2514
+ }
1281
2515
  parseStringRecord(value) {
1282
2516
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1283
2517
  return undefined;
@@ -1365,9 +2599,15 @@ class SchemaNormalizationKernel {
1365
2599
  if (value.kind !== undefined) {
1366
2600
  detail.kind = String(value.kind);
1367
2601
  }
2602
+ if (value.resourceKey !== undefined && String(value.resourceKey).trim().length > 0) {
2603
+ detail.resourceKey = String(value.resourceKey).trim();
2604
+ }
1368
2605
  if (value.surfaceId !== undefined) {
1369
2606
  detail.surfaceId = String(value.surfaceId);
1370
2607
  }
2608
+ if (value.previewSurfaceId !== undefined && String(value.previewSurfaceId).trim().length > 0) {
2609
+ detail.previewSurfaceId = String(value.previewSurfaceId).trim();
2610
+ }
1371
2611
  if (value.presentation !== undefined) {
1372
2612
  detail.presentation = String(value.presentation);
1373
2613
  }
@@ -1392,6 +2632,11 @@ class SchemaNormalizationKernel {
1392
2632
  'resultLayout',
1393
2633
  'primaryPropertyPath',
1394
2634
  'avatarPropertyPath',
2635
+ 'detailActionLabel',
2636
+ 'quickViewActionLabel',
2637
+ 'copyCodeActionLabel',
2638
+ 'copyIdActionLabel',
2639
+ 'createActionLabel',
1395
2640
  ];
1396
2641
  stringKeys.forEach((key) => {
1397
2642
  if (value[key] !== undefined) {
@@ -1429,6 +2674,10 @@ class SchemaNormalizationKernel {
1429
2674
  if (value.maxVisibleBadges !== undefined && !Number.isNaN(Number(value.maxVisibleBadges))) {
1430
2675
  display.maxVisibleBadges = Number(value.maxVisibleBadges);
1431
2676
  }
2677
+ const actions = this.parseLookupActions(value.actions);
2678
+ if (actions) {
2679
+ display.actions = actions;
2680
+ }
1432
2681
  return Object.keys(display).length ? display : undefined;
1433
2682
  }
1434
2683
  parseLookupDisplayField(value) {
@@ -1443,6 +2692,28 @@ class SchemaNormalizationKernel {
1443
2692
  });
1444
2693
  return Object.keys(field).length ? field : undefined;
1445
2694
  }
2695
+ parseLookupActions(value) {
2696
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
2697
+ return undefined;
2698
+ }
2699
+ const actions = {};
2700
+ if (value.showDetail !== undefined) {
2701
+ actions.showDetail = this.parseBoolean(value.showDetail);
2702
+ }
2703
+ if (value.showQuickView !== undefined) {
2704
+ actions.showQuickView = this.parseBoolean(value.showQuickView);
2705
+ }
2706
+ if (value.showCopyCode !== undefined) {
2707
+ actions.showCopyCode = this.parseBoolean(value.showCopyCode);
2708
+ }
2709
+ if (value.showCopyId !== undefined) {
2710
+ actions.showCopyId = this.parseBoolean(value.showCopyId);
2711
+ }
2712
+ if (value.showCreate !== undefined) {
2713
+ actions.showCreate = this.parseBoolean(value.showCreate);
2714
+ }
2715
+ return Object.keys(actions).length ? actions : undefined;
2716
+ }
1446
2717
  parseLookupCreate(value) {
1447
2718
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1448
2719
  return undefined;
@@ -1498,10 +2769,13 @@ class SchemaNormalizationKernel {
1498
2769
  }
1499
2770
  const dialog = {};
1500
2771
  if (value.enabled !== undefined) {
1501
- dialog.enabled = this.parseBoolean(value.enabled);
2772
+ const enabled = this.parseOptionalBoolean(value.enabled);
2773
+ if (enabled !== undefined) {
2774
+ dialog.enabled = enabled;
2775
+ }
1502
2776
  }
1503
- if (value.title !== undefined) {
1504
- const title = String(value.title).trim();
2777
+ if (typeof value.title === 'string') {
2778
+ const title = value.title.trim();
1505
2779
  if (title) {
1506
2780
  dialog.title = title;
1507
2781
  }
@@ -1513,13 +2787,22 @@ class SchemaNormalizationKernel {
1513
2787
  }
1514
2788
  }
1515
2789
  if (value.previewPanel !== undefined) {
1516
- dialog.previewPanel = this.parseBoolean(value.previewPanel);
2790
+ const previewPanel = this.parseOptionalBoolean(value.previewPanel);
2791
+ if (previewPanel !== undefined) {
2792
+ dialog.previewPanel = previewPanel;
2793
+ }
1517
2794
  }
1518
2795
  if (value.allowColumnChooser !== undefined) {
1519
- dialog.allowColumnChooser = this.parseBoolean(value.allowColumnChooser);
2796
+ const allowColumnChooser = this.parseOptionalBoolean(value.allowColumnChooser);
2797
+ if (allowColumnChooser !== undefined) {
2798
+ dialog.allowColumnChooser = allowColumnChooser;
2799
+ }
1520
2800
  }
1521
2801
  if (value.allowSavedViews !== undefined) {
1522
- dialog.allowSavedViews = this.parseBoolean(value.allowSavedViews);
2802
+ const allowSavedViews = this.parseOptionalBoolean(value.allowSavedViews);
2803
+ if (allowSavedViews !== undefined) {
2804
+ dialog.allowSavedViews = allowSavedViews;
2805
+ }
1523
2806
  }
1524
2807
  if (Array.isArray(value.resultColumns)) {
1525
2808
  const resultColumns = value.resultColumns
@@ -1529,20 +2812,20 @@ class SchemaNormalizationKernel {
1529
2812
  dialog.resultColumns = resultColumns;
1530
2813
  }
1531
2814
  }
1532
- if (value.openActionLabel !== undefined) {
1533
- const openActionLabel = String(value.openActionLabel).trim();
2815
+ if (typeof value.openActionLabel === 'string') {
2816
+ const openActionLabel = value.openActionLabel.trim();
1534
2817
  if (openActionLabel) {
1535
2818
  dialog.openActionLabel = openActionLabel;
1536
2819
  }
1537
2820
  }
1538
- if (value.applyActionLabel !== undefined) {
1539
- const applyActionLabel = String(value.applyActionLabel).trim();
2821
+ if (typeof value.applyActionLabel === 'string') {
2822
+ const applyActionLabel = value.applyActionLabel.trim();
1540
2823
  if (applyActionLabel) {
1541
2824
  dialog.applyActionLabel = applyActionLabel;
1542
2825
  }
1543
2826
  }
1544
- if (value.cancelActionLabel !== undefined) {
1545
- const cancelActionLabel = String(value.cancelActionLabel).trim();
2827
+ if (typeof value.cancelActionLabel === 'string') {
2828
+ const cancelActionLabel = value.cancelActionLabel.trim();
1546
2829
  if (cancelActionLabel) {
1547
2830
  dialog.cancelActionLabel = cancelActionLabel;
1548
2831
  }
@@ -1553,19 +2836,19 @@ class SchemaNormalizationKernel {
1553
2836
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1554
2837
  return undefined;
1555
2838
  }
1556
- const field = String(value.field ?? '').trim();
2839
+ const field = typeof value.field === 'string' ? value.field.trim() : '';
1557
2840
  if (!field) {
1558
2841
  return undefined;
1559
2842
  }
1560
2843
  const column = { field };
1561
- if (value.label !== undefined) {
1562
- const label = String(value.label).trim();
2844
+ if (typeof value.label === 'string') {
2845
+ const label = value.label.trim();
1563
2846
  if (label) {
1564
2847
  column.label = label;
1565
2848
  }
1566
2849
  }
1567
- if (value.kind !== undefined) {
1568
- const kind = String(value.kind).trim();
2850
+ if (typeof value.kind === 'string') {
2851
+ const kind = value.kind.trim();
1569
2852
  if (kind === 'code' ||
1570
2853
  kind === 'label' ||
1571
2854
  kind === 'description' ||
@@ -1575,15 +2858,137 @@ class SchemaNormalizationKernel {
1575
2858
  column.kind = kind;
1576
2859
  }
1577
2860
  }
1578
- if (value.width !== undefined) {
1579
- const width = String(value.width).trim();
2861
+ if (typeof value.width === 'string') {
2862
+ const width = value.width.trim();
1580
2863
  if (width) {
1581
2864
  column.width = width;
1582
2865
  }
1583
2866
  }
1584
2867
  return column;
1585
2868
  }
1586
- parseLookupFilterDefinition(value) {
2869
+ mergeLookupDialog(base, override) {
2870
+ const merged = {
2871
+ ...(this.parseLookupDialog(base) ?? {}),
2872
+ ...(this.parseLookupDialog(override) ?? {}),
2873
+ };
2874
+ return Object.keys(merged).length ? merged : undefined;
2875
+ }
2876
+ parseLookupFilterOptions(value) {
2877
+ if (!Array.isArray(value)) {
2878
+ return undefined;
2879
+ }
2880
+ const options = [];
2881
+ const seen = new Set();
2882
+ for (const item of value) {
2883
+ if (typeof item === 'string' ||
2884
+ typeof item === 'number' ||
2885
+ typeof item === 'boolean') {
2886
+ let parsedValue;
2887
+ if (typeof item === 'string') {
2888
+ const trimmed = item.trim();
2889
+ if (!trimmed) {
2890
+ continue;
2891
+ }
2892
+ parsedValue = trimmed;
2893
+ }
2894
+ else if (typeof item === 'number') {
2895
+ if (!Number.isFinite(item)) {
2896
+ continue;
2897
+ }
2898
+ parsedValue = item;
2899
+ }
2900
+ else {
2901
+ parsedValue = item;
2902
+ }
2903
+ const dedupeKey = `${typeof parsedValue}:${String(parsedValue)}`;
2904
+ if (seen.has(dedupeKey)) {
2905
+ continue;
2906
+ }
2907
+ seen.add(dedupeKey);
2908
+ options.push({
2909
+ value: parsedValue,
2910
+ label: String(parsedValue),
2911
+ });
2912
+ continue;
2913
+ }
2914
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
2915
+ continue;
2916
+ }
2917
+ const raw = item;
2918
+ const isLegacyKeyValue = raw['key'] !== undefined &&
2919
+ raw['key'] !== null &&
2920
+ raw['label'] === undefined &&
2921
+ raw['text'] === undefined &&
2922
+ typeof raw['value'] === 'string' &&
2923
+ raw['key'] !== raw['value'];
2924
+ const rawValue = isLegacyKeyValue
2925
+ ? raw['key']
2926
+ : raw['value'] !== undefined && raw['value'] !== null
2927
+ ? raw['value']
2928
+ : raw['key'];
2929
+ const rawLabel = isLegacyKeyValue
2930
+ ? raw['value']
2931
+ : raw['label'] ?? raw['text'];
2932
+ let parsedValue;
2933
+ if (typeof rawValue === 'string') {
2934
+ const trimmed = rawValue.trim();
2935
+ if (!trimmed) {
2936
+ continue;
2937
+ }
2938
+ parsedValue = trimmed;
2939
+ }
2940
+ else if (typeof rawValue === 'number') {
2941
+ if (!Number.isFinite(rawValue)) {
2942
+ continue;
2943
+ }
2944
+ parsedValue = rawValue;
2945
+ }
2946
+ else if (typeof rawValue === 'boolean') {
2947
+ parsedValue = rawValue;
2948
+ }
2949
+ else {
2950
+ continue;
2951
+ }
2952
+ const dedupeKey = `${typeof parsedValue}:${String(parsedValue)}`;
2953
+ if (seen.has(dedupeKey)) {
2954
+ continue;
2955
+ }
2956
+ seen.add(dedupeKey);
2957
+ let label;
2958
+ if (typeof rawLabel === 'string' && rawLabel.trim().length > 0) {
2959
+ label = rawLabel.trim();
2960
+ }
2961
+ else if ((typeof rawLabel === 'number' && Number.isFinite(rawLabel)) ||
2962
+ typeof rawLabel === 'boolean') {
2963
+ label = String(rawLabel);
2964
+ }
2965
+ else {
2966
+ label = String(parsedValue);
2967
+ }
2968
+ const option = {
2969
+ value: parsedValue,
2970
+ label,
2971
+ };
2972
+ if (typeof raw['icon'] === 'string' && raw['icon'].trim()) {
2973
+ option.icon = raw['icon'].trim();
2974
+ }
2975
+ if (typeof raw['tone'] === 'string' && raw['tone'].trim()) {
2976
+ option.tone = raw['tone'].trim();
2977
+ }
2978
+ if (typeof raw['description'] === 'string' && raw['description'].trim()) {
2979
+ option.description = raw['description'].trim();
2980
+ }
2981
+ if (raw['disabled'] !== undefined) {
2982
+ const disabled = this.parseOptionalBoolean(raw['disabled']);
2983
+ if (disabled !== undefined) {
2984
+ option.disabled = disabled;
2985
+ }
2986
+ }
2987
+ options.push(option);
2988
+ }
2989
+ return options.length ? options : undefined;
2990
+ }
2991
+ parseLookupFilterDefinition(value, optionSourceDepth = 0, visitedOptionSources = new Set()) {
1587
2992
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1588
2993
  return undefined;
1589
2994
  }
@@ -1608,8 +3013,38 @@ class SchemaNormalizationKernel {
1608
3013
  if (defaultOperator && operators.includes(defaultOperator)) {
1609
3014
  definition.defaultOperator = defaultOperator;
1610
3015
  }
1611
- if (value.optionsSource !== undefined) {
1612
- const optionsSource = String(value.optionsSource).trim();
3016
+ if (value.options !== undefined) {
3017
+ const options = this.parseLookupFilterOptions(value.options);
3018
+ if (options) {
3019
+ definition.options = options;
3020
+ }
3021
+ }
3022
+ if (typeof value.optionSource === 'string') {
3023
+ const optionSource = value.optionSource.trim();
3024
+ if (optionSource) {
3025
+ definition.optionSource = optionSource;
3026
+ }
3027
+ }
3028
+ else if (value.optionSource &&
3029
+ typeof value.optionSource === 'object' &&
3030
+ !Array.isArray(value.optionSource)) {
3031
+ const optionSource = this.parseOptionSource(value.optionSource, optionSourceDepth + 1, visitedOptionSources);
3032
+ if (optionSource) {
3033
+ definition.optionSource = optionSource;
3034
+ }
3035
+ }
3036
+ if (value.dependsOn !== undefined) {
3037
+ const dependsOn = this.parseDependsOn(value.dependsOn);
3038
+ if (dependsOn.length) {
3039
+ definition.dependsOn = dependsOn;
3040
+ }
3041
+ }
3042
+ const dependencyFilterMap = this.parseStrictStringRecord(value.dependencyFilterMap);
3043
+ if (dependencyFilterMap) {
3044
+ definition.dependencyFilterMap = dependencyFilterMap;
3045
+ }
3046
+ if (typeof value.optionsSource === 'string') {
3047
+ const optionsSource = value.optionsSource.trim();
1613
3048
  if (optionsSource) {
1614
3049
  definition.optionsSource = optionsSource;
1615
3050
  }
@@ -1643,7 +3078,7 @@ class SchemaNormalizationKernel {
1643
3078
  }, {});
1644
3079
  return Object.keys(normalized).length ? normalized : undefined;
1645
3080
  }
1646
- parseLookupFiltering(value) {
3081
+ parseLookupFiltering(value, optionSourceDepth = 0, visitedOptionSources = new Set()) {
1647
3082
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
1648
3083
  return undefined;
1649
3084
  }
@@ -1651,7 +3086,7 @@ class SchemaNormalizationKernel {
1651
3086
  if (value.availableFilters !== undefined) {
1652
3087
  const availableFilters = Array.isArray(value.availableFilters)
1653
3088
  ? value.availableFilters
1654
- .map((item) => this.parseLookupFilterDefinition(item))
3089
+ .map((item) => this.parseLookupFilterDefinition(item, optionSourceDepth, visitedOptionSources))
1655
3090
  .filter((item) => !!item)
1656
3091
  : [];
1657
3092
  if (availableFilters.length) {
@@ -1737,6 +3172,12 @@ class SchemaNormalizationKernel {
1737
3172
  filtering.searchStrategies = searchStrategies;
1738
3173
  }
1739
3174
  }
3175
+ if (typeof value.defaultSearchStrategy === 'string') {
3176
+ const defaultSearchStrategy = value.defaultSearchStrategy.trim();
3177
+ if (defaultSearchStrategy) {
3178
+ filtering.defaultSearchStrategy = defaultSearchStrategy;
3179
+ }
3180
+ }
1740
3181
  return Object.keys(filtering).length ? filtering : undefined;
1741
3182
  }
1742
3183
  /** Parse option arrays into `{ key, value }` objects with label preservation. */
@@ -1767,16 +3208,23 @@ class SchemaNormalizationKernel {
1767
3208
  return { key: String(opt), value: String(opt) };
1768
3209
  });
1769
3210
  }
1770
- parseOptionSource(value) {
1771
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
3211
+ parseOptionSource(value, depth = 0, visited = new Set()) {
3212
+ if (!value ||
3213
+ typeof value !== 'object' ||
3214
+ Array.isArray(value) ||
3215
+ depth > MAX_OPTION_SOURCE_DEPTH ||
3216
+ visited.has(value)) {
1772
3217
  return undefined;
1773
3218
  }
1774
- const optionSource = {
1775
- key: String(value.key ?? '').trim(),
1776
- };
1777
- if (!optionSource.key) {
3219
+ const key = String(value.key ?? '').trim();
3220
+ if (!key) {
1778
3221
  return undefined;
1779
3222
  }
3223
+ const nextVisited = new Set(visited);
3224
+ nextVisited.add(value);
3225
+ const optionSource = {
3226
+ key,
3227
+ };
1780
3228
  if (value.type !== undefined) {
1781
3229
  const optionSourceType = this.parseOptionSourceType(value.type);
1782
3230
  if (optionSourceType) {
@@ -1820,12 +3268,12 @@ class SchemaNormalizationKernel {
1820
3268
  optionSource.searchPropertyPaths = this.parseStringArray(value.searchPropertyPaths);
1821
3269
  }
1822
3270
  if (value.dependsOn !== undefined) {
1823
- const dependsOn = this.parseNonBlankStringArray(value.dependsOn);
3271
+ const dependsOn = this.parseDependsOn(value.dependsOn);
1824
3272
  if (dependsOn.length) {
1825
3273
  optionSource.dependsOn = dependsOn;
1826
3274
  }
1827
3275
  }
1828
- const dependencyFilterMap = this.parseStringRecord(value.dependencyFilterMap);
3276
+ const dependencyFilterMap = this.parseStrictStringRecord(value.dependencyFilterMap);
1829
3277
  if (dependencyFilterMap) {
1830
3278
  optionSource.dependencyFilterMap = dependencyFilterMap;
1831
3279
  }
@@ -1849,10 +3297,14 @@ class SchemaNormalizationKernel {
1849
3297
  if (create) {
1850
3298
  optionSource.create = create;
1851
3299
  }
1852
- const filtering = this.parseLookupFiltering(value.filtering);
3300
+ const filtering = this.parseLookupFiltering(value.filtering, depth, nextVisited);
1853
3301
  if (filtering) {
1854
3302
  optionSource.filtering = filtering;
1855
3303
  }
3304
+ const dialog = this.parseLookupDialog(value.dialog);
3305
+ if (dialog) {
3306
+ optionSource.dialog = dialog;
3307
+ }
1856
3308
  if (value.excludeSelfField !== undefined) {
1857
3309
  optionSource.excludeSelfField = this.parseBoolean(value.excludeSelfField);
1858
3310
  }
@@ -1898,6 +3350,34 @@ class SchemaNormalizationKernel {
1898
3350
  const normalized = String(value ?? '').trim();
1899
3351
  return OPTION_SOURCE_INVALID_SORT_POLICIES.has(normalized) ? normalized : undefined;
1900
3352
  }
3353
+ parseResourceReference(value) {
3354
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
3355
+ return undefined;
3356
+ }
3357
+ const raw = value;
3358
+ const resourceKey = String(raw['resourceKey'] ?? '').trim();
3359
+ if (!resourceKey) {
3360
+ return undefined;
3361
+ }
3362
+ const ref = { resourceKey };
3363
+ const valueField = String(raw['valueField'] ?? '').trim();
3364
+ if (valueField) {
3365
+ ref.valueField = valueField;
3366
+ }
3367
+ const surfaceId = String(raw['surfaceId'] ?? '').trim();
3368
+ if (surfaceId) {
3369
+ ref.surfaceId = surfaceId;
3370
+ }
3371
+ const previewSurfaceId = String(raw['previewSurfaceId'] ?? '').trim();
3372
+ if (previewSurfaceId) {
3373
+ ref.previewSurfaceId = previewSurfaceId;
3374
+ }
3375
+ const detailPresentation = String(raw['detailPresentation'] ?? '').trim();
3376
+ if (detailPresentation === 'drawer' || detailPresentation === 'modal') {
3377
+ ref.detailPresentation = detailPresentation;
3378
+ }
3379
+ return ref;
3380
+ }
1901
3381
  parseLookupOpenDetailMode(value) {
1902
3382
  const normalized = String(value ?? '').trim();
1903
3383
  return LOOKUP_OPEN_DETAIL_MODES.has(normalized) ? normalized : undefined;
@@ -2015,10 +3495,14 @@ class SchemaNormalizationKernel {
2015
3495
  out.maxLength = Number(ui.maxLength);
2016
3496
  if (ui.maxLengthMessage !== undefined)
2017
3497
  out.maxLengthMessage = ui.maxLengthMessage;
2018
- if (ui.min !== undefined)
2019
- out.min = Number(ui.min);
2020
- if (ui.max !== undefined)
2021
- out.max = Number(ui.max);
3498
+ if (ui.min !== undefined) {
3499
+ const parsedMin = Number(ui.min);
3500
+ out.min = Number.isFinite(parsedMin) ? parsedMin : String(ui.min).trim();
3501
+ }
3502
+ if (ui.max !== undefined) {
3503
+ const parsedMax = Number(ui.max);
3504
+ out.max = Number.isFinite(parsedMax) ? parsedMax : String(ui.max).trim();
3505
+ }
2022
3506
  if (ui.minMessage !== undefined)
2023
3507
  out.minMessage = ui.minMessage;
2024
3508
  if (ui.maxMessage !== undefined)
@@ -2150,32 +3634,269 @@ class SchemaNormalizationKernel {
2150
3634
  }
2151
3635
  return undefined;
2152
3636
  }
2153
- isNumericSchemaType(type) {
2154
- const token = String(type ?? '').trim().toLowerCase();
2155
- return ['number', 'integer', 'int', 'float', 'double', 'decimal'].includes(token);
3637
+ isNumericSchemaType(type) {
3638
+ const token = String(type ?? '').trim().toLowerCase();
3639
+ return ['number', 'integer', 'int', 'float', 'double', 'decimal'].includes(token);
3640
+ }
3641
+ resolveNumericFormatToken(prop, ui, resolvedType) {
3642
+ if (ui?.numberFormat?.percentage === true || ui?.['numberFormat.percentage'] === true) {
3643
+ return 'percent';
3644
+ }
3645
+ const explicitUiFormat = this.resolveNonEmptyStringToken(ui?.numericFormat, ui?.numberFormat?.style, ui?.['numberFormat.style']);
3646
+ if (explicitUiFormat) {
3647
+ return explicitUiFormat;
3648
+ }
3649
+ const typeToken = resolvedType ?? prop?.type;
3650
+ if (!this.isNumericSchemaType(typeToken)) {
3651
+ return undefined;
3652
+ }
3653
+ const explicitFormat = this.resolveNonEmptyStringToken(ui?.format, prop?.format);
3654
+ if (explicitFormat) {
3655
+ return explicitFormat;
3656
+ }
3657
+ if (String(prop?.type ?? '').trim().toLowerCase() === 'integer') {
3658
+ return 'integer';
3659
+ }
3660
+ return undefined;
3661
+ }
3662
+ /**
3663
+ * Converte o schema bruto do backend (OpenAPI + x-ui) em FieldDefinition[] tipado.
3664
+ * Regras:
3665
+ * - Ignora propriedades sem x-ui.
3666
+ * - Garante ordenação por 'order' quando presente.
3667
+ * - Funções condicionais/transformações sempre viram funções reais.
3668
+ *
3669
+ * @param schema Objeto OpenAPI/JSON Schema com properties e x-ui por propriedade.
3670
+ * @returns FieldDefinition[] prontos para mapeamento/uso no restante do sistema.
3671
+ */
3672
+ normalizeSchema(schema) {
3673
+ return this.normalizeSchemaWithRoot(schema, schema);
3674
+ }
3675
+ /**
3676
+ * Extrai metadados estruturais de nível raiz (`x-ui` no objeto schema),
3677
+ * cobrindo `formLayout`, `progression`, `timeline`, `schedule`, `hierarchy`,
3678
+ * `calculationMemory`, `contextBinding` e `resourceState`.
3679
+ */
3680
+ extractRootUiMetadata(schema) {
3681
+ const ui = schema &&
3682
+ typeof schema === 'object' &&
3683
+ !Array.isArray(schema) &&
3684
+ schema['x-ui'] &&
3685
+ typeof schema['x-ui'] === 'object' &&
3686
+ !Array.isArray(schema['x-ui'])
3687
+ ? schema['x-ui']
3688
+ : undefined;
3689
+ if (!ui) {
3690
+ return null;
3691
+ }
3692
+ const out = {};
3693
+ const formLayout = this.parseSchemaFormLayout(ui['formLayout']);
3694
+ if (formLayout)
3695
+ out.formLayout = formLayout;
3696
+ if (ui['progression'] && typeof ui['progression'] === 'object' && !Array.isArray(ui['progression'])) {
3697
+ out.progression = this.clonePlain(ui['progression']);
3698
+ }
3699
+ if (ui['timeline'] && typeof ui['timeline'] === 'object' && !Array.isArray(ui['timeline'])) {
3700
+ out.timeline = this.clonePlain(ui['timeline']);
3701
+ }
3702
+ if (ui['timelineLanes'] && typeof ui['timelineLanes'] === 'object' && !Array.isArray(ui['timelineLanes'])) {
3703
+ out.timelineLanes = this.clonePlain(ui['timelineLanes']);
3704
+ }
3705
+ if (ui['schedule'] && typeof ui['schedule'] === 'object' && !Array.isArray(ui['schedule'])) {
3706
+ out.schedule = this.clonePlain(ui['schedule']);
3707
+ }
3708
+ if (ui['hierarchy'] && typeof ui['hierarchy'] === 'object' && !Array.isArray(ui['hierarchy'])) {
3709
+ out.hierarchy = this.clonePlain(ui['hierarchy']);
3710
+ }
3711
+ if (ui['relationshipGraph'] && typeof ui['relationshipGraph'] === 'object' && !Array.isArray(ui['relationshipGraph'])) {
3712
+ out.relationshipGraph = this.clonePlain(ui['relationshipGraph']);
3713
+ }
3714
+ if (ui['calculationMemory'] && typeof ui['calculationMemory'] === 'object' && !Array.isArray(ui['calculationMemory'])) {
3715
+ out.calculationMemory = this.clonePlain(ui['calculationMemory']);
3716
+ }
3717
+ const contextBinding = this.parseContextBinding(ui['contextBinding']);
3718
+ if (contextBinding)
3719
+ out.contextBinding = contextBinding;
3720
+ const resourceState = this.parseResourceState(ui['resourceState']);
3721
+ if (resourceState)
3722
+ out.resourceState = resourceState;
3723
+ return Object.keys(out).length > 0 ? out : null;
3724
+ }
3725
+ parseSchemaFormLayout(raw) {
3726
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
3727
+ return undefined;
3728
+ }
3729
+ const record = raw;
3730
+ const rawMode = String(record['mode'] ?? 'flat').trim().toLowerCase();
3731
+ const mode = rawMode === 'tabs' || rawMode === 'accordion' || rawMode === 'stepper' || rawMode === 'flat'
3732
+ ? rawMode
3733
+ : rawMode === 'vertical'
3734
+ ? 'flat'
3735
+ : 'flat';
3736
+ const defaultTabId = typeof record['defaultTabId'] === 'string' && record['defaultTabId'].trim()
3737
+ ? record['defaultTabId'].trim()
3738
+ : undefined;
3739
+ const rawTabsAppearance = typeof record['tabsAppearance'] === 'string'
3740
+ ? record['tabsAppearance'].trim().toLowerCase()
3741
+ : '';
3742
+ const tabsAppearance = rawTabsAppearance === 'pills' ||
3743
+ rawTabsAppearance === 'underline' ||
3744
+ rawTabsAppearance === 'buttons'
3745
+ ? rawTabsAppearance
3746
+ : undefined;
3747
+ const accordionMulti = this.parseOptionalBoolean(record['accordionMulti']);
3748
+ const hideSectionHeaderInTabs = this.parseOptionalBoolean(record['hideSectionHeaderInTabs']);
3749
+ const hideSectionHeaderInStepper = this.parseOptionalBoolean(record['hideSectionHeaderInStepper']);
3750
+ const rawStepperInReadMode = typeof record['stepperInReadMode'] === 'string'
3751
+ ? record['stepperInReadMode'].trim().toLowerCase()
3752
+ : '';
3753
+ const stepperInReadMode = rawStepperInReadMode === 'presentation' ||
3754
+ rawStepperInReadMode === 'all' ||
3755
+ rawStepperInReadMode === 'none'
3756
+ ? rawStepperInReadMode
3757
+ : undefined;
3758
+ const stepperReviewStep = this.parseOptionalBoolean(record['stepperReviewStep']);
3759
+ const rawSections = Array.isArray(record['sections']) ? record['sections'] : [];
3760
+ const sections = [];
3761
+ for (let idx = 0; idx < rawSections.length; idx++) {
3762
+ const entry = rawSections[idx];
3763
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
3764
+ continue;
3765
+ const item = entry;
3766
+ const id = String(item['id'] ?? '').trim();
3767
+ const title = String(item['title'] ?? '').trim();
3768
+ if (!id || !title)
3769
+ continue;
3770
+ const orderNum = Number(item['order']);
3771
+ const subtitle = typeof item['subtitle'] === 'string' && item['subtitle'].trim() ? item['subtitle'].trim() : undefined;
3772
+ const icon = typeof item['icon'] === 'string' && item['icon'].trim() ? item['icon'].trim() : undefined;
3773
+ const groups = this.parseNonBlankStringArray(item['groups']);
3774
+ const optional = this.parseOptionalBoolean(item['optional']);
3775
+ sections.push({
3776
+ id,
3777
+ title,
3778
+ ...(subtitle ? { subtitle } : {}),
3779
+ ...(icon ? { icon } : {}),
3780
+ order: Number.isFinite(orderNum) ? orderNum : idx,
3781
+ ...(groups.length ? { groups } : {}),
3782
+ ...(optional !== undefined ? { optional } : {}),
3783
+ });
3784
+ }
3785
+ sections.sort((a, b) => a.order - b.order);
3786
+ const rawSteps = Array.isArray(record['steps']) ? record['steps'] : [];
3787
+ const steps = [];
3788
+ for (const entry of rawSteps) {
3789
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
3790
+ continue;
3791
+ const item = entry;
3792
+ const id = String(item['id'] ?? '').trim();
3793
+ const label = String(item['label'] ?? '').trim() || id;
3794
+ const sectionIds = this.parseNonBlankStringArray(item['sectionIds']);
3795
+ if (!id || !sectionIds.length)
3796
+ continue;
3797
+ const description = typeof item['description'] === 'string' && item['description'].trim()
3798
+ ? item['description'].trim()
3799
+ : undefined;
3800
+ const icon = typeof item['icon'] === 'string' && item['icon'].trim()
3801
+ ? item['icon'].trim()
3802
+ : undefined;
3803
+ const optional = this.parseOptionalBoolean(item['optional']);
3804
+ const disabled = this.parseOptionalBoolean(item['disabled']);
3805
+ const tooltip = typeof item['tooltip'] === 'string' && item['tooltip'].trim()
3806
+ ? item['tooltip'].trim()
3807
+ : undefined;
3808
+ const rawBadge = item['badge'];
3809
+ const badge = typeof rawBadge === 'string'
3810
+ ? (rawBadge.trim() ? rawBadge.trim() : undefined)
3811
+ : typeof rawBadge === 'number' && Number.isFinite(rawBadge)
3812
+ ? rawBadge
3813
+ : undefined;
3814
+ steps.push({
3815
+ id,
3816
+ label,
3817
+ ...(description ? { description } : {}),
3818
+ ...(icon ? { icon } : {}),
3819
+ sectionIds,
3820
+ ...(optional !== undefined ? { optional } : {}),
3821
+ ...(badge !== undefined ? { badge } : {}),
3822
+ ...(disabled !== undefined ? { disabled } : {}),
3823
+ ...(tooltip ? { tooltip } : {}),
3824
+ });
3825
+ }
3826
+ return {
3827
+ mode,
3828
+ ...(defaultTabId ? { defaultTabId } : {}),
3829
+ ...(tabsAppearance ? { tabsAppearance } : {}),
3830
+ ...(accordionMulti !== undefined ? { accordionMulti } : {}),
3831
+ ...(hideSectionHeaderInTabs !== undefined ? { hideSectionHeaderInTabs } : {}),
3832
+ ...(hideSectionHeaderInStepper !== undefined ? { hideSectionHeaderInStepper } : {}),
3833
+ ...(stepperInReadMode ? { stepperInReadMode } : {}),
3834
+ ...(stepperReviewStep !== undefined ? { stepperReviewStep } : {}),
3835
+ ...(sections.length ? { sections } : {}),
3836
+ ...(steps.length ? { steps } : {}),
3837
+ };
3838
+ }
3839
+ parseContextBinding(raw) {
3840
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
3841
+ return undefined;
3842
+ }
3843
+ const record = raw;
3844
+ const dim = String(record['dimension'] ?? '').trim().toLowerCase();
3845
+ if (dim !== 'organization' &&
3846
+ dim !== 'company_group' &&
3847
+ dim !== 'unit' &&
3848
+ dim !== 'person' &&
3849
+ dim !== 'bond' &&
3850
+ dim !== 'contract') {
3851
+ return undefined;
3852
+ }
3853
+ const targetField = typeof record['targetField'] === 'string' && record['targetField'].trim()
3854
+ ? record['targetField'].trim()
3855
+ : undefined;
3856
+ return {
3857
+ dimension: dim,
3858
+ lockWhenActive: this.parseBoolean(record['lockWhenActive']),
3859
+ ...(targetField ? { targetField } : {}),
3860
+ };
2156
3861
  }
2157
- resolveNumericFormatToken(prop, ui, resolvedType) {
2158
- const typeToken = resolvedType ?? prop?.type;
2159
- if (!this.isNumericSchemaType(typeToken)) {
3862
+ parseResourceState(raw) {
3863
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
2160
3864
  return undefined;
2161
3865
  }
2162
- if (ui?.numberFormat?.percentage === true || ui?.['numberFormat.percentage'] === true) {
2163
- return 'percent';
3866
+ const record = raw;
3867
+ const initialStates = this.parseNonBlankStringArray(record['initialStates']);
3868
+ const putMutableStates = this.parseNonBlankStringArray(record['putMutableStates']);
3869
+ if (!initialStates.length && !putMutableStates.length) {
3870
+ return undefined;
2164
3871
  }
2165
- return this.resolveNonEmptyStringToken(ui?.numericFormat, ui?.format, ui?.numberFormat?.style, ui?.['numberFormat.style'], prop?.format);
3872
+ return {
3873
+ ...(initialStates.length ? { initialStates } : {}),
3874
+ ...(putMutableStates.length ? { putMutableStates } : {}),
3875
+ };
2166
3876
  }
2167
- /**
2168
- * Converte o schema bruto do backend (OpenAPI + x-ui) em FieldDefinition[] tipado.
2169
- * Regras:
2170
- * - Ignora propriedades sem x-ui.
2171
- * - Garante ordenação por 'order' quando presente.
2172
- * - Funções condicionais/transformações sempre viram funções reais.
2173
- *
2174
- * @param schema Objeto OpenAPI/JSON Schema com properties e x-ui por propriedade.
2175
- * @returns FieldDefinition[] prontos para mapeamento/uso no restante do sistema.
2176
- */
2177
- normalizeSchema(schema) {
2178
- return this.normalizeSchemaWithRoot(schema, schema);
3877
+ parseMicroVisualization(raw) {
3878
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
3879
+ return undefined;
3880
+ }
3881
+ const normalized = normalizePraxisPresentationVisualization(raw);
3882
+ if (normalized) {
3883
+ return normalized;
3884
+ }
3885
+ const clone = this.clonePlain(raw);
3886
+ if (typeof clone['kind'] === 'string' && clone['kind'].trim()) {
3887
+ const rawKind = clone['kind'].trim();
3888
+ const upper = rawKind.toUpperCase();
3889
+ if (upper === 'HARVEY_BALL')
3890
+ clone['kind'] = 'harveyBall';
3891
+ else if (upper === 'STACKED_BAR')
3892
+ clone['kind'] = 'stackedBar';
3893
+ else if (upper === 'PROCESS_FLOW')
3894
+ clone['kind'] = 'processFlow';
3895
+ else if (upper === upper && /^[A-Z_]+$/.test(rawKind))
3896
+ clone['kind'] = rawKind.toLowerCase();
3897
+ return clone;
3898
+ }
3899
+ return undefined;
2179
3900
  }
2180
3901
  normalizeSchemaWithRoot(schema, rootSchema) {
2181
3902
  if (!schema || typeof schema !== 'object') {
@@ -2195,16 +3916,62 @@ class SchemaNormalizationKernel {
2195
3916
  !Array.isArray(prop['x-ui'])
2196
3917
  ? prop['x-ui']
2197
3918
  : undefined;
3919
+ const hasChildProperties = prop?.properties &&
3920
+ typeof prop.properties === 'object' &&
3921
+ !Array.isArray(prop.properties);
3922
+ const isCustomFieldsContainer = ui?.customFieldsContainer === true ||
3923
+ (name === 'customFields' && prop?.type === 'object' && hasChildProperties);
3924
+ if (isCustomFieldsContainer) {
3925
+ if (hasChildProperties) {
3926
+ for (const key of Object.keys(prop.properties)) {
3927
+ if (RESERVED_CUSTOM_FIELD_KEYS.has(key)) {
3928
+ throw new Error(`Unsupported custom field key "${name}.${key}". Publish a key admitted by the canonical backend custom-field policy.`);
3929
+ }
3930
+ }
3931
+ const parentAccess = normalizeFieldAccessMetadata(ui?.fieldAccess);
3932
+ for (const childField of this.normalizeSchemaWithRoot(prop, rootSchema)) {
3933
+ const originalKey = childField.name;
3934
+ if (parentAccess && childField.fieldAccess &&
3935
+ !this.haveEquivalentFieldAccess(parentAccess, childField.fieldAccess)) {
3936
+ throw new Error(`Conflicting fieldAccess on custom-field container "${name}" and child "${originalKey}". Publish the effective access policy on each leaf field.`);
3937
+ }
3938
+ fields.push({
3939
+ ...childField,
3940
+ name: `${name}.${originalKey}`,
3941
+ customField: true,
3942
+ customFieldKey: childField.customFieldKey ?? originalKey,
3943
+ customFieldScope: childField.customFieldScope ?? 'tenant',
3944
+ ...(ui?.disabled !== undefined && this.parseBoolean(ui.disabled) ? { disabled: true } : {}),
3945
+ ...(ui?.readOnly !== undefined && this.parseBoolean(ui.readOnly) ? { readOnly: true } : {}),
3946
+ ...(ui?.formHidden !== undefined && this.parseBoolean(ui.formHidden) ? { formHidden: true } : {}),
3947
+ ...(parentAccess && !childField.fieldAccess ? { fieldAccess: normalizeFieldAccessMetadata(parentAccess) } : {}),
3948
+ });
3949
+ }
3950
+ }
3951
+ // The container is wire structure, never an independent field control.
3952
+ continue;
3953
+ }
2198
3954
  // Skip properties without x-ui metadata
2199
3955
  if (!ui || Object.keys(ui).length === 0) {
2200
3956
  continue;
2201
3957
  }
2202
3958
  const field = { name };
3959
+ if (ui.customField !== undefined) {
3960
+ field.customField = this.parseBoolean(ui.customField);
3961
+ }
3962
+ if (ui.customFieldKey != null) {
3963
+ field.customFieldKey = String(ui.customFieldKey);
3964
+ }
3965
+ if (ui.customFieldScope != null) {
3966
+ field.customFieldScope = String(ui.customFieldScope);
3967
+ }
2203
3968
  // -------------------------------------------------------------------
2204
3969
  // Basic information
2205
3970
  // -------------------------------------------------------------------
2206
3971
  field.label = ui.label ?? prop.title ?? name;
2207
- field.type = this.resolveFieldType(prop, ui);
3972
+ field.type = this.resolveFieldType(prop, ui, rootSchema);
3973
+ if (field.type === 'array')
3974
+ field.items = normalizeScalarItemsSchema(prop?.items);
2208
3975
  const numericFormat = this.resolveNumericFormatToken(prop, ui, field.type);
2209
3976
  if (numericFormat) {
2210
3977
  field.numericFormat = numericFormat;
@@ -2218,9 +3985,25 @@ class SchemaNormalizationKernel {
2218
3985
  if (Object.keys(presentation).length > 0) {
2219
3986
  field.presentation = presentation;
2220
3987
  }
3988
+ const presentationRules = normalizeFieldPresentationRules(ui.presentationRules);
3989
+ if (presentationRules?.length) {
3990
+ field.presentationRules = presentationRules;
3991
+ }
2221
3992
  if (ui.controlType) {
2222
3993
  field.controlType = ui.controlType;
2223
3994
  }
3995
+ if (this.isCanonicalMonetaryRangeUnion(prop, rootSchema)) {
3996
+ field.type = 'array';
3997
+ const controlToken = normalizeControlTypeToken(field.controlType);
3998
+ const isInlineCurrencyRange = controlToken === 'inlinecurrencyrange' ||
3999
+ resolveInlineFilterControlType(field.controlType) === 'inlineCurrencyRange';
4000
+ if (!isInlineCurrencyRange) {
4001
+ field.controlType = 'priceRange';
4002
+ }
4003
+ }
4004
+ if (this.inferRequireTwoBoundsFromUnion(prop, rootSchema)) {
4005
+ field.requireTwoBounds = true;
4006
+ }
2224
4007
  if (field.controlType === 'array' || ui.array !== undefined) {
2225
4008
  const arrayConfig = this.normalizeArrayConfig(ui, prop, rootSchema);
2226
4009
  if (arrayConfig) {
@@ -2314,6 +4097,40 @@ class SchemaNormalizationKernel {
2314
4097
  if (condRequired !== undefined) {
2315
4098
  field.conditionalRequired = condRequired;
2316
4099
  }
4100
+ if (ui.conditionalReadOnly !== undefined && ui.conditionalReadOnly !== null) {
4101
+ if (typeof ui.conditionalReadOnly === 'string') {
4102
+ const trimmed = ui.conditionalReadOnly.trim();
4103
+ if (trimmed) {
4104
+ field.conditionalReadOnly = trimmed;
4105
+ }
4106
+ }
4107
+ else {
4108
+ const condReadOnly = this.parseJsonLogicExpression(ui.conditionalReadOnly, name, 'x-ui.conditionalReadOnly');
4109
+ if (condReadOnly !== undefined) {
4110
+ field.conditionalReadOnly = condReadOnly;
4111
+ }
4112
+ }
4113
+ }
4114
+ if (ui.colSpan !== undefined) {
4115
+ const parsedSpan = this.parseOptionalFiniteNumber(ui.colSpan);
4116
+ if (parsedSpan !== undefined) {
4117
+ field.colSpan = Math.min(12, Math.max(1, Math.trunc(parsedSpan)));
4118
+ }
4119
+ }
4120
+ const contextBinding = this.parseContextBinding(ui.contextBinding);
4121
+ if (contextBinding) {
4122
+ field.contextBinding = contextBinding;
4123
+ }
4124
+ if (ui.draftCleared !== undefined) {
4125
+ const parsedDraftCleared = this.parseOptionalBoolean(ui.draftCleared);
4126
+ if (parsedDraftCleared !== undefined) {
4127
+ field.draftCleared = parsedDraftCleared;
4128
+ }
4129
+ }
4130
+ const resourceState = this.parseResourceState(ui.resourceState);
4131
+ if (resourceState) {
4132
+ field.resourceState = resourceState;
4133
+ }
2317
4134
  const transformFn = this.parseTransformFunction(ui.transformValueFunction);
2318
4135
  if (transformFn) {
2319
4136
  field.transformValueFunction = transformFn;
@@ -2328,9 +4145,57 @@ class SchemaNormalizationKernel {
2328
4145
  if (ui.tableHidden !== undefined) {
2329
4146
  field.tableHidden = this.parseBoolean(ui.tableHidden);
2330
4147
  }
4148
+ if (ui.tableOrder !== undefined) {
4149
+ const parsedTableOrder = this.parseOptionalFiniteNumber(ui.tableOrder);
4150
+ if (parsedTableOrder !== undefined) {
4151
+ field.tableOrder = parsedTableOrder;
4152
+ }
4153
+ }
4154
+ if (ui.pinned !== undefined && typeof ui.pinned === 'string') {
4155
+ const pinned = ui.pinned.trim().toLowerCase();
4156
+ if (pinned === 'start' || pinned === 'end') {
4157
+ field.pinned = pinned;
4158
+ }
4159
+ }
4160
+ if (ui.primarySearch !== undefined) {
4161
+ const primarySearch = this.parseOptionalBoolean(ui.primarySearch);
4162
+ if (primarySearch !== undefined) {
4163
+ field.primarySearch = primarySearch;
4164
+ }
4165
+ }
4166
+ if (ui.inlineFilter !== undefined) {
4167
+ const inlineFilter = this.parseOptionalBoolean(ui.inlineFilter);
4168
+ if (inlineFilter !== undefined) {
4169
+ field.inlineFilter = inlineFilter;
4170
+ }
4171
+ }
4172
+ if (ui.inline !== undefined) {
4173
+ const inline = this.parseOptionalBoolean(ui.inline);
4174
+ if (inline !== undefined) {
4175
+ field.inline = inline;
4176
+ }
4177
+ }
4178
+ if (ui.microVisualization !== undefined) {
4179
+ const microVisualization = this.parseMicroVisualization(ui.microVisualization);
4180
+ if (microVisualization) {
4181
+ field.microVisualization = microVisualization;
4182
+ }
4183
+ }
2331
4184
  if (ui.formHidden !== undefined) {
2332
4185
  field.formHidden = this.parseBoolean(ui.formHidden);
2333
4186
  }
4187
+ if (ui.quickViewVisible !== undefined) {
4188
+ const quickViewVisible = this.parseOptionalBoolean(ui.quickViewVisible);
4189
+ if (quickViewVisible !== undefined) {
4190
+ field.quickViewVisible = quickViewVisible;
4191
+ }
4192
+ }
4193
+ if (ui.quickViewOrder !== undefined) {
4194
+ const quickViewOrder = this.parseOptionalFiniteNumber(ui.quickViewOrder);
4195
+ if (quickViewOrder !== undefined) {
4196
+ field.quickViewOrder = quickViewOrder;
4197
+ }
4198
+ }
2334
4199
  if (ui.width !== undefined) {
2335
4200
  field.width = ui.width;
2336
4201
  }
@@ -2414,6 +4279,9 @@ class SchemaNormalizationKernel {
2414
4279
  if (ui.options !== undefined) {
2415
4280
  field.options = this.parseOptions(ui.options);
2416
4281
  }
4282
+ if (Array.isArray(prop?.enum) && prop.enum.length > 0 && field.enumValues === undefined) {
4283
+ field.enumValues = [...prop.enum];
4284
+ }
2417
4285
  if (ui.optionGroups !== undefined) {
2418
4286
  field.optionGroups = this.parseOptions(ui.optionGroups);
2419
4287
  }
@@ -2431,11 +4299,11 @@ class SchemaNormalizationKernel {
2431
4299
  if (optionSource) {
2432
4300
  // Java metadata publishes cascade context beside optionSource. Keep the
2433
4301
  // runtime contract canonical by materializing it inside optionSource.
2434
- const dependsOn = this.parseNonBlankStringArray(ui.dependsOn);
4302
+ const dependsOn = this.parseDependsOn(ui.dependsOn);
2435
4303
  if (!optionSource.dependsOn?.length && dependsOn.length) {
2436
4304
  optionSource.dependsOn = dependsOn;
2437
4305
  }
2438
- const dependencyFilterMap = this.parseStringRecord(ui.dependencyFilterMap);
4306
+ const dependencyFilterMap = this.parseStrictStringRecord(ui.dependencyFilterMap);
2439
4307
  if (!optionSource.dependencyFilterMap &&
2440
4308
  dependencyFilterMap) {
2441
4309
  optionSource.dependencyFilterMap = dependencyFilterMap;
@@ -2452,6 +4320,24 @@ class SchemaNormalizationKernel {
2452
4320
  if (ui.filterField !== undefined) {
2453
4321
  field.filterField = ui.filterField;
2454
4322
  }
4323
+ if (ui.resourceReference !== undefined) {
4324
+ const resourceReference = this.parseResourceReference(ui.resourceReference);
4325
+ if (resourceReference) {
4326
+ field.resourceReference = resourceReference;
4327
+ }
4328
+ }
4329
+ if (ui.quickView !== undefined) {
4330
+ const explicitQuickView = normalizeResourceQuickViewBinding(ui.quickView);
4331
+ if (explicitQuickView) {
4332
+ field.quickView = explicitQuickView;
4333
+ }
4334
+ }
4335
+ if (!field.quickView) {
4336
+ const synthesized = resolveFieldQuickViewBinding(field);
4337
+ if (synthesized) {
4338
+ field.quickView = synthesized;
4339
+ }
4340
+ }
2455
4341
  if (ui.multiple !== undefined) {
2456
4342
  field.multiple = this.parseBoolean(ui.multiple);
2457
4343
  }
@@ -2464,11 +4350,10 @@ class SchemaNormalizationKernel {
2464
4350
  if (ui.filter !== undefined) {
2465
4351
  field.filter = ui.filter;
2466
4352
  }
2467
- if (ui.dialog !== undefined) {
2468
- const dialog = this.parseLookupDialog(ui.dialog);
2469
- if (dialog) {
2470
- field.dialog = dialog;
2471
- }
4353
+ const explicitDialog = ui.dialog !== undefined ? this.parseLookupDialog(ui.dialog) : undefined;
4354
+ const resolvedDialog = this.mergeLookupDialog(field.optionSource?.dialog, explicitDialog);
4355
+ if (resolvedDialog) {
4356
+ field.dialog = resolvedDialog;
2472
4357
  }
2473
4358
  if (ui.detailActionLabel !== undefined) {
2474
4359
  const detailActionLabel = String(ui.detailActionLabel).trim();
@@ -2476,6 +4361,12 @@ class SchemaNormalizationKernel {
2476
4361
  field.detailActionLabel = detailActionLabel;
2477
4362
  }
2478
4363
  }
4364
+ if (ui.quickViewActionLabel !== undefined) {
4365
+ const quickViewActionLabel = String(ui.quickViewActionLabel).trim();
4366
+ if (quickViewActionLabel) {
4367
+ field.quickViewActionLabel = quickViewActionLabel;
4368
+ }
4369
+ }
2479
4370
  if (ui.copyCodeActionLabel !== undefined) {
2480
4371
  const copyCodeActionLabel = String(ui.copyCodeActionLabel).trim();
2481
4372
  if (copyCodeActionLabel) {
@@ -2499,6 +4390,9 @@ class SchemaNormalizationKernel {
2499
4390
  if (ui.actions.showDetail !== undefined) {
2500
4391
  actions.showDetail = this.parseBoolean(ui.actions.showDetail);
2501
4392
  }
4393
+ if (ui.actions.showQuickView !== undefined) {
4394
+ actions.showQuickView = this.parseBoolean(ui.actions.showQuickView);
4395
+ }
2502
4396
  if (ui.actions.showCopyCode !== undefined) {
2503
4397
  actions.showCopyCode = this.parseBoolean(ui.actions.showCopyCode);
2504
4398
  }
@@ -2530,10 +4424,22 @@ class SchemaNormalizationKernel {
2530
4424
  field.numericStep = Number(ui.numericStep);
2531
4425
  }
2532
4426
  if (ui.numericMin !== undefined) {
2533
- field.numericMin = Number(ui.numericMin);
4427
+ const parsedMin = Number(ui.numericMin);
4428
+ if (Number.isFinite(parsedMin)) {
4429
+ field.numericMin = parsedMin;
4430
+ }
4431
+ else if (field.min === undefined && String(ui.numericMin).trim().length > 0) {
4432
+ field.min = String(ui.numericMin).trim();
4433
+ }
2534
4434
  }
2535
4435
  if (ui.numericMax !== undefined) {
2536
- field.numericMax = Number(ui.numericMax);
4436
+ const parsedMax = Number(ui.numericMax);
4437
+ if (Number.isFinite(parsedMax)) {
4438
+ field.numericMax = parsedMax;
4439
+ }
4440
+ else if (field.max === undefined && String(ui.numericMax).trim().length > 0) {
4441
+ field.max = String(ui.numericMax).trim();
4442
+ }
2537
4443
  }
2538
4444
  if (ui.numericMaxLength !== undefined) {
2539
4445
  field.numericMaxLength = Number(ui.numericMaxLength);
@@ -2541,8 +4447,419 @@ class SchemaNormalizationKernel {
2541
4447
  if (ui.buttons !== undefined) {
2542
4448
  field.buttons = this.parseButtons(ui.buttons);
2543
4449
  }
4450
+ if (ui.valueLabelDisplay !== undefined) {
4451
+ const normalizedValueLabelDisplay = typeof ui.valueLabelDisplay === 'string'
4452
+ ? ui.valueLabelDisplay.trim().toLowerCase()
4453
+ : '';
4454
+ if (normalizedValueLabelDisplay === 'off' ||
4455
+ normalizedValueLabelDisplay === 'auto' ||
4456
+ normalizedValueLabelDisplay === 'on') {
4457
+ field.valueLabelDisplay = normalizedValueLabelDisplay;
4458
+ }
4459
+ }
4460
+ const sliderBooleanKeys = [
4461
+ 'thumbLabel',
4462
+ 'discrete',
4463
+ 'showInputs',
4464
+ 'showInlineInputs',
4465
+ 'showCurrencySymbol',
4466
+ 'disableThumbSwap',
4467
+ 'vertical',
4468
+ 'invert',
4469
+ ];
4470
+ for (const key of sliderBooleanKeys) {
4471
+ if (ui[key] !== undefined) {
4472
+ const parsed = this.parseOptionalBoolean(ui[key]);
4473
+ if (parsed !== undefined) {
4474
+ field[key] = parsed;
4475
+ }
4476
+ }
4477
+ }
4478
+ for (const guideKey of ['showTicks', 'showAnchors']) {
4479
+ const rawGuide = ui[guideKey];
4480
+ if (rawGuide !== undefined) {
4481
+ const parsedGuide = this.parseOptionalBoolean(rawGuide);
4482
+ if (parsedGuide !== undefined) {
4483
+ field[guideKey] = parsedGuide;
4484
+ }
4485
+ else if (typeof rawGuide === 'string' &&
4486
+ rawGuide.trim().toLowerCase() === 'auto') {
4487
+ field[guideKey] = 'auto';
4488
+ }
4489
+ }
4490
+ }
4491
+ const sliderNumberKeys = [
4492
+ 'sliderStep',
4493
+ 'shiftStep',
4494
+ 'minDistance',
4495
+ 'maxDistance',
4496
+ 'decimalPlaces',
4497
+ ];
4498
+ for (const key of sliderNumberKeys) {
4499
+ if (ui[key] !== undefined) {
4500
+ const parsed = this.parseOptionalFiniteNumber(ui[key]);
4501
+ if (parsed !== undefined) {
4502
+ field[key] = parsed;
4503
+ }
4504
+ }
4505
+ }
4506
+ // -------------------------------------------------------------------
4507
+ // Inline filter and specialized control metadata (x-ui)
4508
+ // -------------------------------------------------------------------
4509
+ const inlinePassThroughKeys = [
4510
+ 'prefixIcon',
4511
+ 'suffixIcon',
4512
+ 'prefixIconColor',
4513
+ 'suffixIconColor',
4514
+ 'chipLeadingIcon',
4515
+ 'chipTrailingIcon',
4516
+ 'chipLeadingIconColor',
4517
+ 'chipTrailingIconColor',
4518
+ 'clearIcon',
4519
+ 'clearIconColor',
4520
+ 'showQuickClear',
4521
+ 'clearable',
4522
+ 'inlineAutoSize',
4523
+ 'inlineAutoSizeMaxPx',
4524
+ 'inlineAutoSizeMaxVw',
4525
+ 'inlineOverlay',
4526
+ 'inlineChipDisplay',
4527
+ 'inlineChipSummaryTemplate',
4528
+ 'inlineChipUnitLabel',
4529
+ 'inlinePanelTitle',
4530
+ 'inlinePanelSubtitle',
4531
+ 'inlinePanelIcon',
4532
+ 'inlinePanelIconColor',
4533
+ 'inlineQuickPresets',
4534
+ 'inlineQuickPresetsApplyMode',
4535
+ 'inlineTexts',
4536
+ 'shortcuts',
4537
+ 'showShortcuts',
4538
+ 'quickPresets',
4539
+ 'quickPresetsAuto',
4540
+ 'quickPresetsLabels',
4541
+ 'granularity',
4542
+ 'defaultGranularity',
4543
+ 'selectionGrid',
4544
+ 'showSlider',
4545
+ 'minPeriod',
4546
+ 'maxPeriod',
4547
+ 'minYear',
4548
+ 'maxYear',
4549
+ 'minTime',
4550
+ 'maxTime',
4551
+ 'stepMinute',
4552
+ 'stepMinutes',
4553
+ 'interval',
4554
+ 'inlineTimeTrackShifts',
4555
+ 'inlineTrackShifts',
4556
+ 'trackShifts',
4557
+ 'minDistanceMinutes',
4558
+ 'maxDistanceMinutes',
4559
+ 'startField',
4560
+ 'endField',
4561
+ 'startLabel',
4562
+ 'endLabel',
4563
+ 'startPlaceholder',
4564
+ 'endPlaceholder',
4565
+ 'inputMinLabel',
4566
+ 'inputMaxLabel',
4567
+ 'inputExactLabel',
4568
+ 'startMin',
4569
+ 'startMax',
4570
+ 'endMin',
4571
+ 'endMax',
4572
+ 'startMinMessage',
4573
+ 'startMaxMessage',
4574
+ 'endMinMessage',
4575
+ 'endMaxMessage',
4576
+ 'endMinOffset',
4577
+ 'endMinOffsetMessage',
4578
+ 'startMaxOffset',
4579
+ 'startMaxOffsetMessage',
4580
+ 'maxVisibleChips',
4581
+ 'maxVisibleBadges',
4582
+ 'showSelectAll',
4583
+ 'selectAllLabel',
4584
+ 'clearSelectionLabel',
4585
+ 'searchPlaceholder',
4586
+ 'noResultsText',
4587
+ 'allowSelectAll',
4588
+ 'governedPaletteRef',
4589
+ 'palette',
4590
+ 'paletteColors',
4591
+ 'paletteSettings',
4592
+ 'documentType',
4593
+ 'version',
4594
+ 'nodes',
4595
+ 'nodeIdField',
4596
+ 'parentIdField',
4597
+ 'childrenField',
4598
+ 'lazyLoad',
4599
+ 'marks',
4600
+ 'semanticBands',
4601
+ 'distribution',
4602
+ 'inlineDistribution',
4603
+ 'track',
4604
+ 'trueLabel',
4605
+ 'falseLabel',
4606
+ 'labelTrue',
4607
+ 'labelFalse',
4608
+ 'iconTrue',
4609
+ 'iconFalse',
4610
+ 'tone',
4611
+ 'toneTrue',
4612
+ 'toneFalse',
4613
+ 'booleanFormat',
4614
+ 'displayFormat',
4615
+ 'currency',
4616
+ 'currencyCode',
4617
+ 'currencyPosition',
4618
+ 'thousandSeparator',
4619
+ 'thousandsSeparator',
4620
+ 'decimalSeparator',
4621
+ 'allowNegative',
4622
+ 'operatorModes',
4623
+ 'defaultOperatorMode',
4624
+ 'requireTwoBounds',
4625
+ 'locale',
4626
+ 'precision',
4627
+ 'initialsField',
4628
+ 'optionLabelKey',
4629
+ 'optionValueKey',
4630
+ 'extraProperties',
4631
+ 'rangeMode',
4632
+ 'maxRating',
4633
+ 'ratingMin',
4634
+ 'ratingMax',
4635
+ 'itemsCount',
4636
+ 'ratingStep',
4637
+ 'allowHalf',
4638
+ 'ratingAllowHalf',
4639
+ 'ratingPrecision',
4640
+ 'ratingIcon',
4641
+ 'ratingEmptyIcon',
4642
+ 'ratingHalfIcon',
4643
+ 'ratingActiveIcon',
4644
+ 'ratingInactiveIcon',
4645
+ 'ratingTone',
4646
+ 'ratingToneColors',
4647
+ 'ratingColors',
4648
+ 'starColors',
4649
+ 'ratingLowColor',
4650
+ 'ratingMidColor',
4651
+ 'ratingHighColor',
4652
+ 'ratingGradientLowColor',
4653
+ 'ratingGradientMidColor',
4654
+ 'ratingGradientHighColor',
4655
+ 'ratingToneLowColor',
4656
+ 'ratingToneMidColor',
4657
+ 'ratingToneHighColor',
4658
+ 'ratingBadgeColor',
4659
+ 'ratingBadgeIcon',
4660
+ 'ratingBadgeIconColor',
4661
+ 'ratingIndicatorColor',
4662
+ 'ratingLabels',
4663
+ 'distanceUnit',
4664
+ 'distanceBaseUnit',
4665
+ 'distanceUnits',
4666
+ 'distanceAllowUnitToggle',
4667
+ 'distanceUnitLabels',
4668
+ 'distanceDisplayDecimals',
4669
+ 'distanceDecimalsKm',
4670
+ 'distanceDecimalsMi',
4671
+ 'distancePresets',
4672
+ 'distanceSubtitle',
4673
+ 'distanceIcon',
4674
+ 'distanceStart',
4675
+ 'distanceEnd',
4676
+ 'radiusMin',
4677
+ 'radiusMax',
4678
+ 'radiusStep',
4679
+ 'radiusMode',
4680
+ 'distanceSliderStep',
4681
+ 'distanceRadialRings',
4682
+ 'distanceAccentColor',
4683
+ 'distanceRingColor',
4684
+ 'distanceTrackColor',
4685
+ 'distanceGlowColor',
4686
+ 'distanceGradientLowColor',
4687
+ 'distanceGradientMidColor',
4688
+ 'distanceGradientHighColor',
4689
+ 'distanceRangeBandOpacity',
4690
+ 'pipelineOptions',
4691
+ 'pipelineColors',
4692
+ 'pipelineTexts',
4693
+ 'scoreBands',
4694
+ 'priorityBands',
4695
+ 'severityBands',
4696
+ 'scorePalette',
4697
+ 'scoreTexts',
4698
+ 'scoreSubtitle',
4699
+ 'scoreUnit',
4700
+ 'scoreDisplayDecimals',
4701
+ 'scoreShowScaleLabels',
4702
+ 'scoreShowBandChips',
4703
+ 'scoreRangeSeparator',
4704
+ 'scoreGradientLowColor',
4705
+ 'scoreGradientMidColor',
4706
+ 'scoreGradientHighColor',
4707
+ 'scoreValueFallbackColor',
4708
+ 'scoreEmptyGradient',
4709
+ 'scoreIcon',
4710
+ 'scoreBandsAriaLabel',
4711
+ 'scoreBandAriaLabelTemplate',
4712
+ 'scoreMin',
4713
+ 'scoreMax',
4714
+ 'scoreStep',
4715
+ 'scoreMode',
4716
+ 'scoreSliderStep',
4717
+ 'relativePeriodOptions',
4718
+ 'relativePeriodPresets',
4719
+ 'relativePeriodTexts',
4720
+ 'sentimentOptions',
4721
+ 'sentimentPalette',
4722
+ 'sentimentTexts',
4723
+ 'colorLabelOptions',
4724
+ 'colorLabelPalette',
4725
+ 'colorLabelTexts',
4726
+ 'timeOptions',
4727
+ 'inlineTimeQuickPresets',
4728
+ 'inlineVisualStyle',
4729
+ 'percentPresets',
4730
+ 'numberFormat',
4731
+ 'valueLabelFormat',
4732
+ 'scale',
4733
+ 'optionSubtitleKey',
4734
+ 'optionWeightKey',
4735
+ 'optionColorKey',
4736
+ 'optionIconKey',
4737
+ 'optionEmojiKey',
4738
+ 'panelSearchIcon',
4739
+ 'panelSearchIconColor',
4740
+ 'panelResetIcon',
4741
+ 'panelResetIconColor',
4742
+ 'optionSelectedIcon',
4743
+ 'optionSelectedIconColor',
4744
+ 'columns',
4745
+ 'pipelineTitle',
4746
+ 'pipelineSubtitle',
4747
+ 'pipelineMode',
4748
+ 'pipelineMultiple',
4749
+ 'pipelineSearchable',
4750
+ 'pipelineSearchPlaceholder',
4751
+ 'pipelineOptionSubtitleKey',
4752
+ 'pipelineOptionWeightKey',
4753
+ 'pipelineOptionColorKey',
4754
+ 'pipelineShowBar',
4755
+ 'pipelineShowSelectionPills',
4756
+ 'pipelineShowSelectAll',
4757
+ 'pipelineSelectAllText',
4758
+ 'pipelineShowClearAction',
4759
+ 'pipelineClearActionText',
4760
+ 'pipelineChipMaxVisible',
4761
+ 'statusColors',
4762
+ 'pipelineGradientLowColor',
4763
+ 'pipelineGradientMidColor',
4764
+ 'pipelineGradientHighColor',
4765
+ 'pipelineEmptyStateText',
4766
+ 'pipelineSelectionActionsAriaLabel',
4767
+ 'pipelineOptionsGroupAriaLabelMultiple',
4768
+ 'pipelineOptionsGroupAriaLabelSingle',
4769
+ 'pipelineSelectionPillsAriaLabel',
4770
+ 'pipelineBarAriaLabelEmpty',
4771
+ 'pipelineBarAriaLabelSelected',
4772
+ 'pipelineIcon',
4773
+ 'pipelineSearchIcon',
4774
+ 'pipelineSearchIconColor',
4775
+ 'relativePeriodTitle',
4776
+ 'relativePeriodSubtitle',
4777
+ 'relativePeriodShowProgress',
4778
+ 'relativePeriodProgressGradientLowColor',
4779
+ 'relativePeriodProgressGradientMidColor',
4780
+ 'relativePeriodProgressGradientHighColor',
4781
+ 'relativePeriodColumns',
4782
+ 'relativePeriodCloseOnSelect',
4783
+ 'relativePeriodMultiple',
4784
+ 'relativePeriodSearchable',
4785
+ 'relativePeriodIcon',
4786
+ 'relativePeriodIconKey',
4787
+ 'relativePeriodSubtitleKey',
4788
+ 'relativePeriodSelectedIcon',
4789
+ 'relativePeriodSelectedIconColor',
4790
+ 'relativePeriodOptionsAriaLabel',
4791
+ 'relativePeriodProgressEmptyLabel',
4792
+ 'relativePeriodEmptyStateText',
4793
+ 'sentimentTitle',
4794
+ 'sentimentSubtitle',
4795
+ 'sentimentGradientLowColor',
4796
+ 'sentimentGradientMidColor',
4797
+ 'sentimentGradientHighColor',
4798
+ 'sentimentShowBar',
4799
+ 'sentimentAnimatedEmoji',
4800
+ 'sentimentCloseOnSelect',
4801
+ 'sentimentMultiple',
4802
+ 'sentimentShowSelectionPills',
4803
+ 'sentimentIcon',
4804
+ 'sentimentColorKey',
4805
+ 'sentimentEmojiKey',
4806
+ 'sentimentOptionsAriaLabel',
4807
+ 'sentimentSelectionPillsAriaLabel',
4808
+ 'sentimentEmptyStateText',
4809
+ 'colorLabelTitle',
4810
+ 'colorLabelSubtitle',
4811
+ 'colorLabelMultiple',
4812
+ 'colorLabelColumns',
4813
+ 'colorLabelShowSelectedBadges',
4814
+ 'colorLabelCloseOnSelect',
4815
+ 'colorLabelSelectionTitle',
4816
+ 'colorLabelIcon',
4817
+ 'colorLabelSelectedIcon',
4818
+ 'colorLabelSelectedIconColor',
4819
+ 'colorLabelBadgeRemoveIcon',
4820
+ 'colorLabelBadgeRemoveIconColor',
4821
+ 'colorLabelColorKey',
4822
+ 'colorLabelOptionsAriaLabel',
4823
+ 'colorLabelSelectionBadgesAriaLabel',
4824
+ 'colorLabelRemoveSelectionAriaLabel',
4825
+ 'colorLabelEmptyStateText',
4826
+ 'startAriaLabel',
4827
+ 'endAriaLabel',
4828
+ 'inlineQuickPresetsAriaLabel',
4829
+ 'inlineQuickPresetsCancelLabel',
4830
+ 'inlineQuickPresetsCancelAriaLabel',
4831
+ 'inlineQuickPresetsApplyLabel',
4832
+ 'inlineQuickPresetsApplyAriaLabel',
4833
+ 'shortcutsPosition',
4834
+ 'applyOnShortcutClick',
4835
+ 'i18nShortcuts',
4836
+ 'startView',
4837
+ 'startAt',
4838
+ 'touchUi',
4839
+ 'minDate',
4840
+ 'maxDate',
4841
+ ];
4842
+ for (const key of inlinePassThroughKeys) {
4843
+ if (ui[key] !== undefined && field[key] === undefined) {
4844
+ field[key] = ui[key];
4845
+ }
4846
+ }
2544
4847
  fields.push(field);
2545
4848
  }
4849
+ if (fields.length === 0 &&
4850
+ properties['parameters'] &&
4851
+ typeof properties['parameters'] === 'object' &&
4852
+ !Array.isArray(properties['parameters'])) {
4853
+ const parametersProp = properties['parameters'];
4854
+ const resolvedParametersSchema = this.resolveSchemaRef(parametersProp.$ref, rootSchema) ?? parametersProp;
4855
+ if (resolvedParametersSchema &&
4856
+ typeof resolvedParametersSchema === 'object' &&
4857
+ resolvedParametersSchema !== schema &&
4858
+ resolvedParametersSchema.properties &&
4859
+ typeof resolvedParametersSchema.properties === 'object') {
4860
+ return this.normalizeObjectSchema(resolvedParametersSchema, rootSchema);
4861
+ }
4862
+ }
2546
4863
  // Order by the optional 'order' property when present
2547
4864
  fields.sort((a, b) => {
2548
4865
  const orderA = a.order ?? Number.MAX_SAFE_INTEGER;
@@ -2551,29 +4868,177 @@ class SchemaNormalizationKernel {
2551
4868
  });
2552
4869
  return fields;
2553
4870
  }
2554
- resolveFieldType(prop, ui) {
4871
+ haveEquivalentFieldAccess(left, right) {
4872
+ const identity = (access) => JSON.stringify([
4873
+ [...(access.visibleForAuthorities ?? [])].sort(),
4874
+ [...(access.editableForAuthorities ?? [])].sort(),
4875
+ ]);
4876
+ return identity(left) === identity(right);
4877
+ }
4878
+ resolveSchemaNode(node, rootSchema, visited = new Set()) {
4879
+ if (!node || typeof node !== 'object' || Array.isArray(node)) {
4880
+ return node;
4881
+ }
4882
+ const ref = typeof node.$ref === 'string' ? node.$ref.trim() : '';
4883
+ if (!ref || visited.has(ref)) {
4884
+ return node;
4885
+ }
4886
+ const resolved = this.resolveSchemaRef(ref, rootSchema);
4887
+ if (!resolved || typeof resolved !== 'object' || Array.isArray(resolved)) {
4888
+ return node;
4889
+ }
4890
+ const nextVisited = new Set(visited);
4891
+ nextVisited.add(ref);
4892
+ const resolvedDeep = this.resolveSchemaNode(resolved, rootSchema, nextVisited);
4893
+ const { $ref: _ignoredRef, ...rest } = node;
4894
+ return {
4895
+ ...(resolvedDeep && typeof resolvedDeep === 'object' ? resolvedDeep : {}),
4896
+ ...rest,
4897
+ };
4898
+ }
4899
+ extractSchemaNonNullTypes(node) {
4900
+ if (!node || typeof node !== 'object') {
4901
+ return [];
4902
+ }
4903
+ const collected = [];
4904
+ const pushType = (raw) => {
4905
+ if (typeof raw !== 'string') {
4906
+ return;
4907
+ }
4908
+ const normalized = raw.trim().toLowerCase();
4909
+ if (normalized && normalized !== 'null' && !collected.includes(normalized)) {
4910
+ collected.push(normalized);
4911
+ }
4912
+ };
4913
+ const pushFrom = (raw) => {
4914
+ if (typeof raw === 'string') {
4915
+ pushType(raw);
4916
+ }
4917
+ else if (Array.isArray(raw)) {
4918
+ for (const item of raw) {
4919
+ pushType(item);
4920
+ }
4921
+ }
4922
+ else if (raw instanceof Set) {
4923
+ for (const item of raw) {
4924
+ pushType(item);
4925
+ }
4926
+ }
4927
+ };
4928
+ pushFrom(node.type);
4929
+ pushFrom(node.types);
4930
+ return collected;
4931
+ }
4932
+ extractUnionVariants(prop, rootSchema) {
4933
+ const resolvedProp = this.resolveSchemaNode(prop, rootSchema);
4934
+ if (!resolvedProp || typeof resolvedProp !== 'object' || Array.isArray(resolvedProp)) {
4935
+ return [];
4936
+ }
4937
+ const rawVariants = [
4938
+ ...(Array.isArray(resolvedProp.oneOf) ? resolvedProp.oneOf : []),
4939
+ ...(Array.isArray(resolvedProp.anyOf) ? resolvedProp.anyOf : []),
4940
+ ];
4941
+ return rawVariants
4942
+ .filter((variant) => variant && typeof variant === 'object' && !Array.isArray(variant))
4943
+ .map((variant) => this.resolveSchemaNode(variant, rootSchema));
4944
+ }
4945
+ isArrayVariant(variant) {
4946
+ return this.extractSchemaNonNullTypes(variant).includes('array');
4947
+ }
4948
+ isObjectVariant(variant) {
4949
+ const types = this.extractSchemaNonNullTypes(variant);
4950
+ return (types.includes('object') ||
4951
+ (types.length === 0 &&
4952
+ !!variant?.properties &&
4953
+ typeof variant.properties === 'object' &&
4954
+ !Array.isArray(variant.properties)));
4955
+ }
4956
+ isCanonicalMonetaryRangeUnion(prop, rootSchema) {
4957
+ const variants = this.extractUnionVariants(prop, rootSchema);
4958
+ if (variants.length === 0) {
4959
+ return false;
4960
+ }
4961
+ const hasArrayBranch = variants.some((variant) => this.isArrayVariant(variant));
4962
+ if (!hasArrayBranch) {
4963
+ return false;
4964
+ }
4965
+ return variants.some((variant) => {
4966
+ if (!this.isObjectVariant(variant)) {
4967
+ return false;
4968
+ }
4969
+ const props = variant?.properties;
4970
+ if (!props || typeof props !== 'object' || Array.isArray(props)) {
4971
+ return false;
4972
+ }
4973
+ return (Object.prototype.hasOwnProperty.call(props, 'minPrice') &&
4974
+ props.minPrice != null &&
4975
+ Object.prototype.hasOwnProperty.call(props, 'maxPrice') &&
4976
+ props.maxPrice != null);
4977
+ });
4978
+ }
4979
+ inferRequireTwoBoundsFromUnion(prop, rootSchema) {
4980
+ const variants = this.extractUnionVariants(prop, rootSchema);
4981
+ if (variants.length === 0) {
4982
+ return false;
4983
+ }
4984
+ const requiredPairs = [
4985
+ ['minPrice', 'maxPrice'],
4986
+ ['min', 'max'],
4987
+ ['startDate', 'endDate'],
4988
+ ];
4989
+ for (const variant of variants) {
4990
+ if (this.isArrayVariant(variant) && Number(variant?.minItems) === 2) {
4991
+ return true;
4992
+ }
4993
+ if (this.isObjectVariant(variant) && Array.isArray(variant?.required)) {
4994
+ const requiredSet = new Set(variant.required.filter((entry) => typeof entry === 'string'));
4995
+ if (requiredPairs.some(([lower, upper]) => requiredSet.has(lower) && requiredSet.has(upper))) {
4996
+ return true;
4997
+ }
4998
+ }
4999
+ }
5000
+ return false;
5001
+ }
5002
+ resolveFieldType(prop, ui, rootSchema) {
5003
+ if (this.isCanonicalMonetaryRangeUnion(prop, rootSchema)) {
5004
+ return 'array';
5005
+ }
2555
5006
  if (ui?.type !== undefined && ui?.type !== null && String(ui.type).trim() !== '') {
2556
5007
  return String(ui.type);
2557
5008
  }
2558
5009
  if (String(ui?.controlType ?? '').trim() === 'array') {
2559
5010
  return 'array';
2560
5011
  }
2561
- if (prop?.type) {
2562
- return String(prop.type);
5012
+ const resolvedProp = this.resolveSchemaNode(prop, rootSchema);
5013
+ const propTypes = this.extractSchemaNonNullTypes(resolvedProp);
5014
+ if (propTypes.length === 1) {
5015
+ return propTypes[0];
5016
+ }
5017
+ if (resolvedProp?.type && !Array.isArray(resolvedProp.type)) {
5018
+ return String(resolvedProp.type);
2563
5019
  }
2564
- const variants = [
2565
- ...(Array.isArray(prop?.oneOf) ? prop.oneOf : []),
2566
- ...(Array.isArray(prop?.anyOf) ? prop.anyOf : []),
2567
- ].filter((variant) => variant && typeof variant === 'object');
2568
- const nonNullTypes = Array.from(new Set(variants
2569
- .map((variant) => (typeof variant.type === 'string' ? variant.type.trim() : ''))
2570
- .filter((type) => !!type && type !== 'null')));
5020
+ const variants = this.extractUnionVariants(prop, rootSchema);
5021
+ const nonNullTypes = Array.from(new Set(variants.flatMap((variant) => this.extractSchemaNonNullTypes(variant))));
2571
5022
  if (nonNullTypes.length === 1) {
2572
5023
  return nonNullTypes[0];
2573
5024
  }
2574
5025
  // Compatibilidade para schemas de range publicados como oneOf(array|object).
2575
5026
  const controlToken = String(ui?.controlType || '').trim().toLowerCase().replace(/[^a-z0-9]/g, '');
2576
- const isRangeControl = ['daterange', 'datetimerange', 'rangeslider', 'pricerange'].includes(controlToken);
5027
+ const isRangeControl = [
5028
+ 'daterange',
5029
+ 'datetimerange',
5030
+ 'rangeslider',
5031
+ 'pricerange',
5032
+ 'inlinerange',
5033
+ 'inlinecurrencyrange',
5034
+ 'inlinedaterange',
5035
+ 'inlineperiodrange',
5036
+ 'inlineyearrange',
5037
+ 'inlinemonthrange',
5038
+ 'inlinetimerange',
5039
+ 'inlinedistanceradius',
5040
+ 'inlinescorepriority',
5041
+ ].includes(controlToken);
2577
5042
  if (isRangeControl && nonNullTypes.includes('array')) {
2578
5043
  return 'array';
2579
5044
  }
@@ -2589,6 +5054,10 @@ class SchemaNormalizationKernel {
2589
5054
  function normalizeSchemaFields(schema) {
2590
5055
  return new SchemaNormalizationKernel().normalizeSchema(schema);
2591
5056
  }
5057
+ /** Extracts root-level `x-ui` metadata blocks (`formLayout`, `progression`, `timeline`, `schedule`, `hierarchy`, `calculationMemory`). */
5058
+ function extractSchemaRootUiMetadata(schema) {
5059
+ return new SchemaNormalizationKernel().extractRootUiMetadata(schema);
5060
+ }
2592
5061
 
2593
5062
  function isObject(value) {
2594
5063
  return value != null && typeof value === 'object' && !Array.isArray(value);
@@ -2667,8 +5136,19 @@ function clone(v) {
2667
5136
 
2668
5137
  function buildBaseColumnFromDef(def) {
2669
5138
  const type = resolveColumnTypeFromFieldDefinition(def);
2670
- const format = type === 'string' ? resolveTextMaskFormatFromFieldDefinition(def) : undefined;
2671
- const renderer = resolveRendererFromFieldPresentation(def);
5139
+ const format = resolveFormatFromFieldDefinition(def, type);
5140
+ const valueMapping = resolveSchemaValueMappingFromFieldDefinition(def);
5141
+ const renderer = resolveRendererFromFieldDefinition(def);
5142
+ const conditionalRenderers = resolveConditionalRenderersFromFieldDefinition(def);
5143
+ const quickView = resolveQuickViewFromFieldDefinition(def);
5144
+ const isAvatar = renderer?.type === 'avatar';
5145
+ const explicitWidth = firstNonEmptyString(def.width);
5146
+ const resolvedOrder = typeof def.tableOrder === 'number'
5147
+ ? def.tableOrder
5148
+ : typeof def.order === 'number'
5149
+ ? def.order
5150
+ : undefined;
5151
+ const sticky = def.pinned ?? def.sticky;
2672
5152
  return {
2673
5153
  field: def.name,
2674
5154
  header: def.label || def.name,
@@ -2677,9 +5157,15 @@ function buildBaseColumnFromDef(def) {
2677
5157
  sortable: def.sortable !== false,
2678
5158
  filterable: def.filterable === true,
2679
5159
  resizable: true,
2680
- order: typeof def.order === 'number' ? def.order : undefined,
5160
+ ...(sticky !== undefined ? { sticky } : {}),
5161
+ order: resolvedOrder,
5162
+ ...(explicitWidth ? { width: explicitWidth } : isAvatar ? { width: '56px' } : {}),
5163
+ ...(isAvatar ? { align: 'center' } : {}),
2681
5164
  ...(format ? { format } : {}),
5165
+ ...(valueMapping ? { valueMapping } : {}),
2682
5166
  ...(renderer ? { renderer } : {}),
5167
+ ...(conditionalRenderers?.length ? { conditionalRenderers } : {}),
5168
+ ...(quickView ? { quickView } : {}),
2683
5169
  };
2684
5170
  }
2685
5171
  function applyLocalCustomizations(baseCol, localCol) {
@@ -2706,18 +5192,40 @@ function applyLocalCustomizations(baseCol, localCol) {
2706
5192
  result.headerStyle = localCol.headerStyle ?? baseCol.headerStyle;
2707
5193
  result.cssClass = localCol.cssClass ?? baseCol.cssClass;
2708
5194
  result.headerCssClass = localCol.headerCssClass ?? baseCol.headerCssClass;
5195
+ const resolvedQuickView = reconcileFieldQuickViewBinding(baseCol.quickView, localCol.quickView);
5196
+ if (resolvedQuickView) {
5197
+ result.quickView = resolvedQuickView;
5198
+ }
5199
+ else {
5200
+ delete result.quickView;
5201
+ }
2709
5202
  // If server type changed, drop potentially incompatible formatting/renderers.
2710
5203
  if (!typeChanged) {
2711
5204
  result.format = localCol.format ?? baseCol.format;
2712
5205
  result.valueMapping = localCol.valueMapping ?? baseCol.valueMapping;
2713
- result.renderer = localCol.renderer ?? baseCol.renderer;
5206
+ result.renderer = normalizeColumnRendererQuickView(localCol.renderer ?? baseCol.renderer);
5207
+ const resolvedConditionalRenderers = localCol.conditionalRenderers?.length
5208
+ ? localCol.conditionalRenderers
5209
+ : baseCol.conditionalRenderers;
5210
+ if (resolvedConditionalRenderers?.length) {
5211
+ result.conditionalRenderers = resolvedConditionalRenderers;
5212
+ }
5213
+ else {
5214
+ delete result.conditionalRenderers;
5215
+ }
2714
5216
  }
2715
5217
  else {
2716
5218
  // Drop local presentation that may be incompatible with the new server type,
2717
5219
  // but keep canonical server presentation for the resolved type.
2718
5220
  result.format = baseCol.format;
2719
5221
  result.valueMapping = baseCol.valueMapping;
2720
- result.renderer = undefined;
5222
+ result.renderer = normalizeColumnRendererQuickView(baseCol.renderer);
5223
+ if (baseCol.conditionalRenderers?.length) {
5224
+ result.conditionalRenderers = baseCol.conditionalRenderers;
5225
+ }
5226
+ else {
5227
+ delete result.conditionalRenderers;
5228
+ }
2721
5229
  }
2722
5230
  return result;
2723
5231
  }
@@ -2729,6 +5237,10 @@ function reconcileTableConfig(layout, serverDefs) {
2729
5237
  const localCol = localByField.get(base.field);
2730
5238
  return localCol ? applyLocalCustomizations(base, localCol) : base;
2731
5239
  });
5240
+ if (serverDefs.some((d) => typeof d.tableOrder === 'number')) {
5241
+ mergedColumns.sort((a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) -
5242
+ (b.order ?? Number.MAX_SAFE_INTEGER));
5243
+ }
2732
5244
  const serverFields = new Set(serverDefs.map((d) => d.name));
2733
5245
  const orphans = (local.columns || []).filter((c) => !serverFields.has(c.field));
2734
5246
  const hiddenOrphans = orphans.map((c) => ({ ...c, visible: false }));
@@ -2773,8 +5285,11 @@ function resolveSemanticColumnTypeFromFieldDefinition(def) {
2773
5285
  return 'string';
2774
5286
  if (numericFormat === 'currency' || controlType === 'currency')
2775
5287
  return 'currency';
2776
- if (numericFormat === 'percent' || numericFormat === 'percentage')
5288
+ if (numericFormat === 'percent' ||
5289
+ numericFormat === 'percentage' ||
5290
+ numericFormat === 'fraction') {
2777
5291
  return 'percentage';
5292
+ }
2778
5293
  if (numericFormat === 'date' || numericFormat === 'datetime')
2779
5294
  return 'date';
2780
5295
  if (controlType === 'numerictextbox' || controlType === 'inlinenumber')
@@ -2831,25 +5346,320 @@ function resolveTextMaskFormat(value) {
2831
5346
  const hasInvalidMaskLetters = /[A-WYZa-wyz]/.test(format);
2832
5347
  return hasMaskTokens && !hasInvalidMaskLetters ? format : undefined;
2833
5348
  }
2834
- function resolveRendererFromFieldPresentation(def) {
2835
- const presentation = def.presentation;
5349
+ function resolveFormatFromFieldDefinition(def, type) {
5350
+ if (type === 'string') {
5351
+ return resolveTextMaskFormatFromFieldDefinition(def);
5352
+ }
5353
+ if (type === 'currency') {
5354
+ return resolveSchemaCurrencyFormatFromFieldDefinition(def);
5355
+ }
5356
+ if (type === 'date') {
5357
+ return (firstNonEmptyString(def.displayFormat) ??
5358
+ firstNonEmptyString(def.extraProperties?.displayFormat));
5359
+ }
5360
+ if (type === 'boolean') {
5361
+ return resolveSchemaBooleanFormatFromFieldDefinition(def);
5362
+ }
5363
+ if (type === 'number') {
5364
+ const schemaDataType = normalizePresentationToken(def.type);
5365
+ const schemaFormat = normalizePresentationToken(def.format);
5366
+ const numericFormat = normalizePresentationToken(def.numericFormat ?? def.extraProperties?.numericFormat);
5367
+ if (schemaDataType === 'integer' ||
5368
+ schemaFormat === 'integer' ||
5369
+ schemaFormat === 'int32' ||
5370
+ schemaFormat === 'int64' ||
5371
+ numericFormat === 'integer' ||
5372
+ numericFormat === 'int32' ||
5373
+ numericFormat === 'int64') {
5374
+ return '1.0-0';
5375
+ }
5376
+ if (numericFormat === 'auto') {
5377
+ return undefined;
5378
+ }
5379
+ const explicitDecimals = firstFiniteNumber(def.decimalPlaces) ??
5380
+ firstFiniteNumber(def.extraProperties?.decimalPlaces);
5381
+ if (explicitDecimals !== undefined && explicitDecimals >= 0) {
5382
+ const decimals = Math.trunc(explicitDecimals);
5383
+ return `1.${decimals}-${decimals}`;
5384
+ }
5385
+ }
5386
+ return undefined;
5387
+ }
5388
+ function resolveSchemaCurrencyFormatFromFieldDefinition(def) {
5389
+ const currency = firstNonEmptyString(def.currency) ??
5390
+ firstNonEmptyString(def.extraProperties?.currency) ??
5391
+ 'BRL';
5392
+ const decimalPlaces = firstFiniteNumber(def.decimalPlaces) ??
5393
+ firstFiniteNumber(def.extraProperties?.decimalPlaces) ??
5394
+ 2;
5395
+ return `${currency}|symbol|${decimalPlaces}`;
5396
+ }
5397
+ function resolveSchemaBooleanFormatFromFieldDefinition(def) {
5398
+ const explicit = firstNonEmptyString(def.booleanFormat) ??
5399
+ firstNonEmptyString(def.extraProperties?.booleanFormat);
5400
+ if (explicit)
5401
+ return explicit;
5402
+ const trueLabel = firstNonEmptyString(def.trueLabel) ??
5403
+ firstNonEmptyString(def.labelTrue) ??
5404
+ firstNonEmptyString(def.presentation?.labelTrue) ??
5405
+ firstNonEmptyString(def.extraProperties?.trueLabel) ??
5406
+ firstNonEmptyString(def.extraProperties?.labelTrue);
5407
+ const falseLabel = firstNonEmptyString(def.falseLabel) ??
5408
+ firstNonEmptyString(def.labelFalse) ??
5409
+ firstNonEmptyString(def.presentation?.labelFalse) ??
5410
+ firstNonEmptyString(def.extraProperties?.falseLabel) ??
5411
+ firstNonEmptyString(def.extraProperties?.labelFalse);
5412
+ if (trueLabel || falseLabel) {
5413
+ const effectiveTrue = trueLabel || 'Sim';
5414
+ const effectiveFalse = falseLabel || 'Não';
5415
+ const tNorm = normalizePresentationToken(effectiveTrue);
5416
+ const fNorm = normalizePresentationToken(effectiveFalse);
5417
+ if (tNorm === 'ativo' && fNorm === 'inativo')
5418
+ return 'active-inactive';
5419
+ if (tNorm === 'sim' && (fNorm === 'nao' || fNorm === 'não'))
5420
+ return 'yes-no';
5421
+ return `custom|${effectiveTrue}|${effectiveFalse}`;
5422
+ }
5423
+ const name = normalizePresentationToken(def.name);
5424
+ if (name === 'ativo' || name === 'active' || name.endsWith('ativo')) {
5425
+ return 'active-inactive';
5426
+ }
5427
+ return undefined;
5428
+ }
5429
+ function resolveSchemaValueMappingFromFieldDefinition(def) {
5430
+ const explicit = def.valueMapping;
5431
+ if (explicit && typeof explicit === 'object' && !Array.isArray(explicit)) {
5432
+ const normalized = Object.entries(explicit).reduce((acc, [key, value]) => {
5433
+ if (key && typeof value === 'string' && value.trim()) {
5434
+ acc[key] = value.trim();
5435
+ }
5436
+ return acc;
5437
+ }, {});
5438
+ if (Object.keys(normalized).length > 0)
5439
+ return normalized;
5440
+ }
5441
+ const options = Array.isArray(def.options) ? def.options : [];
5442
+ if (options.length > 0) {
5443
+ const valueKey = firstNonEmptyString(def.optionValueKey) ?? 'key';
5444
+ const labelKey = firstNonEmptyString(def.optionLabelKey) ?? 'value';
5445
+ const mapping = options.reduce((acc, option) => {
5446
+ if (!option || typeof option !== 'object')
5447
+ return acc;
5448
+ const record = option;
5449
+ const value = record[valueKey] ?? record.key ?? record.id ?? record.value;
5450
+ const label = record[labelKey] ?? record.label ?? record.value ?? record.name;
5451
+ if (value !== undefined && value !== null && label !== undefined && label !== null) {
5452
+ acc[String(value)] = String(label);
5453
+ }
5454
+ return acc;
5455
+ }, {});
5456
+ if (Object.keys(mapping).length > 0)
5457
+ return mapping;
5458
+ }
5459
+ const enumValues = Array.isArray(def.enumValues)
5460
+ ? def.enumValues
5461
+ .map((v) => (v != null ? String(v).trim() : ''))
5462
+ .filter((v) => v.length > 0)
5463
+ : [];
5464
+ if (enumValues.length > 0) {
5465
+ return enumValues.reduce((acc, value) => {
5466
+ acc[value] = humanizeSchemaEnumValue(value);
5467
+ return acc;
5468
+ }, {});
5469
+ }
5470
+ return undefined;
5471
+ }
5472
+ function humanizeSchemaEnumValue(value) {
5473
+ return value
5474
+ .toLowerCase()
5475
+ .split(/[_\-\s]+/)
5476
+ .filter(Boolean)
5477
+ .map((part, index) => (index === 0 ? `${part.charAt(0).toUpperCase()}${part.slice(1)}` : part))
5478
+ .join(' ');
5479
+ }
5480
+ function resolveQuickViewFromFieldDefinition(def) {
5481
+ return (resolveFieldQuickViewBinding(def) ??
5482
+ normalizeResourceQuickViewBinding(def['extraProperties'] && typeof def['extraProperties'] === 'object' ? def['extraProperties']['quickView'] : undefined) ??
5483
+ undefined);
5484
+ }
5485
+ function normalizeColumnRendererQuickView(renderer) {
5486
+ if (!renderer || typeof renderer !== 'object') {
5487
+ return renderer;
5488
+ }
5489
+ const next = { ...renderer };
5490
+ if (next.link && typeof next.link === 'object') {
5491
+ const qv = normalizeResourceQuickViewBinding(next.link.quickView);
5492
+ next.link = { ...next.link };
5493
+ if (qv) {
5494
+ next.link.quickView = qv;
5495
+ }
5496
+ else {
5497
+ delete next.link.quickView;
5498
+ }
5499
+ }
5500
+ if (next.badge && typeof next.badge === 'object') {
5501
+ const qv = normalizeResourceQuickViewBinding(next.badge.quickView);
5502
+ next.badge = { ...next.badge };
5503
+ if (qv) {
5504
+ next.badge.quickView = qv;
5505
+ }
5506
+ else {
5507
+ delete next.badge.quickView;
5508
+ }
5509
+ }
5510
+ if (next.chip && typeof next.chip === 'object') {
5511
+ const qv = normalizeResourceQuickViewBinding(next.chip.quickView);
5512
+ next.chip = { ...next.chip };
5513
+ if (qv) {
5514
+ next.chip.quickView = qv;
5515
+ }
5516
+ else {
5517
+ delete next.chip.quickView;
5518
+ }
5519
+ }
5520
+ if (next.icon && typeof next.icon === 'object') {
5521
+ const qv = normalizeResourceQuickViewBinding(next.icon.quickView);
5522
+ next.icon = { ...next.icon };
5523
+ if (qv) {
5524
+ next.icon.quickView = qv;
5525
+ }
5526
+ else {
5527
+ delete next.icon.quickView;
5528
+ }
5529
+ }
5530
+ if (next.compose && typeof next.compose === 'object' && Array.isArray(next.compose.items)) {
5531
+ next.compose = {
5532
+ ...next.compose,
5533
+ items: next.compose.items.map((item) => {
5534
+ if (!item || typeof item !== 'object')
5535
+ return item;
5536
+ if (item.type === 'value') {
5537
+ const qv = normalizeResourceQuickViewBinding(item.quickView);
5538
+ const cloned = { ...item };
5539
+ if (qv)
5540
+ cloned.quickView = qv;
5541
+ else
5542
+ delete cloned.quickView;
5543
+ return cloned;
5544
+ }
5545
+ if (item.type === 'link' && item.link) {
5546
+ const qv = normalizeResourceQuickViewBinding(item.link.quickView);
5547
+ const link = { ...item.link };
5548
+ if (qv)
5549
+ link.quickView = qv;
5550
+ else
5551
+ delete link.quickView;
5552
+ return { ...item, link };
5553
+ }
5554
+ if (item.type === 'badge' && item.badge) {
5555
+ const qv = normalizeResourceQuickViewBinding(item.badge.quickView);
5556
+ const badge = { ...item.badge };
5557
+ if (qv)
5558
+ badge.quickView = qv;
5559
+ else
5560
+ delete badge.quickView;
5561
+ return { ...item, badge };
5562
+ }
5563
+ if (item.type === 'chip' && item.chip) {
5564
+ const qv = normalizeResourceQuickViewBinding(item.chip.quickView);
5565
+ const chip = { ...item.chip };
5566
+ if (qv)
5567
+ chip.quickView = qv;
5568
+ else
5569
+ delete chip.quickView;
5570
+ return { ...item, chip };
5571
+ }
5572
+ if (item.type === 'icon' && item.icon) {
5573
+ const qv = normalizeResourceQuickViewBinding(item.icon.quickView);
5574
+ const icon = { ...item.icon };
5575
+ if (qv)
5576
+ icon.quickView = qv;
5577
+ else
5578
+ delete icon.quickView;
5579
+ return { ...item, icon };
5580
+ }
5581
+ return item;
5582
+ }),
5583
+ };
5584
+ }
5585
+ return next;
5586
+ }
5587
+ function resolveRendererFromFieldDefinition(def) {
5588
+ const presentationRenderer = resolveRendererFromFieldPresentation(def);
5589
+ if (presentationRenderer)
5590
+ return presentationRenderer;
5591
+ if (isPraxisPresentationVisualizationTableSafe(def.microVisualization)) {
5592
+ return {
5593
+ type: 'microVisualization',
5594
+ microVisualization: {
5595
+ visualization: def.microVisualization,
5596
+ },
5597
+ };
5598
+ }
5599
+ if (normalizePresentationToken(def.controlType) === 'avatar') {
5600
+ const initialsField = firstNonEmptyString(def.initialsField) ??
5601
+ firstNonEmptyString(def.extraProperties?.initialsField) ??
5602
+ 'nomeCompleto';
5603
+ return {
5604
+ type: 'avatar',
5605
+ avatar: {
5606
+ srcField: def.name,
5607
+ initialsField,
5608
+ shape: 'circle',
5609
+ size: 32,
5610
+ },
5611
+ };
5612
+ }
5613
+ return undefined;
5614
+ }
5615
+ function resolveSchemaConditionalRenderers(def, options) {
5616
+ return resolveConditionalRenderersFromFieldDefinition(def, options);
5617
+ }
5618
+ function buildSchemaSemanticColumnRenderer(def, presentationOverride, options) {
5619
+ return resolveRendererFromFieldPresentation(def, presentationOverride, options);
5620
+ }
5621
+ function resolveRendererFromFieldPresentation(def, presentationOverride, options) {
5622
+ const presentation = presentationOverride ?? def.presentation;
2836
5623
  if (!presentation || typeof presentation !== 'object')
2837
5624
  return undefined;
5625
+ if (presentation.presenter === 'microVisualization' &&
5626
+ isPraxisPresentationVisualizationTableSafe(presentation.visualization)) {
5627
+ return {
5628
+ type: 'microVisualization',
5629
+ microVisualization: {
5630
+ visualization: presentation.visualization,
5631
+ },
5632
+ };
5633
+ }
2838
5634
  const presenter = normalizePresentationToken(presentation.presenter ?? presentation.variant);
2839
5635
  const color = resolveSemanticPresentationColor(presentation.tone);
2840
5636
  const variant = resolveSemanticPresentationVariant(presentation.appearance);
2841
5637
  const icon = firstNonEmptyString(presentation.icon);
2842
5638
  const tooltipText = firstNonEmptyString(presentation.tooltip);
2843
5639
  const tooltip = tooltipText ? { text: tooltipText } : undefined;
5640
+ const fixedText = firstNonEmptyString(presentation.label);
5641
+ const affixes = resolveSemanticPresentationAffixes(presentation);
5642
+ const includeUndefinedFields = options?.includeUndefinedBadgeChipFields === true;
5643
+ const includeUndefinedText = options?.includeUndefinedBadgeChipText === true;
5644
+ const allowTextPresenterAsIconValue = options?.allowTextPresenterAsIconValue !== false;
2844
5645
  if (presenter === 'chip') {
2845
5646
  return {
2846
5647
  type: 'chip',
2847
5648
  chip: {
2848
- textField: def.name,
2849
- ...(color ? { color } : {}),
2850
- ...(variant ? { variant } : {}),
2851
- ...(icon ? { icon } : {}),
2852
- ...(tooltip ? { tooltip } : {}),
5649
+ ...(includeUndefinedText
5650
+ ? { text: fixedText }
5651
+ : fixedText !== undefined
5652
+ ? { text: fixedText }
5653
+ : {}),
5654
+ textField: fixedText ? undefined : def.name,
5655
+ ...(includeUndefinedFields ? { color, icon, variant, tooltip } : {
5656
+ ...(color ? { color } : {}),
5657
+ ...(variant ? { variant } : {}),
5658
+ ...(icon ? { icon } : {}),
5659
+ ...(tooltip ? { tooltip } : {}),
5660
+ }),
5661
+ ...(affixes.prefix ? { prefix: affixes.prefix } : {}),
5662
+ ...(affixes.suffix ? { suffix: affixes.suffix } : {}),
2853
5663
  },
2854
5664
  };
2855
5665
  }
@@ -2857,58 +5667,176 @@ function resolveRendererFromFieldPresentation(def) {
2857
5667
  return {
2858
5668
  type: 'badge',
2859
5669
  badge: {
2860
- textField: def.name,
5670
+ ...(includeUndefinedText
5671
+ ? { text: fixedText }
5672
+ : fixedText !== undefined
5673
+ ? { text: fixedText }
5674
+ : {}),
5675
+ textField: fixedText ? undefined : def.name,
5676
+ ...(includeUndefinedFields ? { color, icon, variant, tooltip } : {
5677
+ ...(color ? { color } : {}),
5678
+ ...(variant ? { variant } : {}),
5679
+ ...(icon ? { icon } : {}),
5680
+ ...(tooltip ? { tooltip } : {}),
5681
+ }),
5682
+ ...(affixes.prefix ? { prefix: affixes.prefix } : {}),
5683
+ ...(affixes.suffix ? { suffix: affixes.suffix } : {}),
5684
+ },
5685
+ };
5686
+ }
5687
+ if (presenter === 'progress') {
5688
+ const valueExpr = `= row.${def.name.replace(/\./g, '?.')}`;
5689
+ return {
5690
+ type: 'progress',
5691
+ progress: {
5692
+ valueExpr,
5693
+ showLabel: true,
5694
+ ...(color ? { color } : {}),
5695
+ },
5696
+ };
5697
+ }
5698
+ if (presenter === 'rating') {
5699
+ const valueExpr = `= row.${def.name.replace(/\./g, '?.')}`;
5700
+ return {
5701
+ type: 'rating',
5702
+ rating: {
5703
+ valueExpr,
5704
+ max: 5,
2861
5705
  ...(color ? { color } : {}),
2862
- ...(variant ? { variant } : {}),
2863
- ...(icon ? { icon } : {}),
2864
- ...(tooltip ? { tooltip } : {}),
2865
5706
  },
2866
5707
  };
2867
5708
  }
2868
- if (presenter === 'iconvalue') {
5709
+ if (presenter === 'iconvalue' ||
5710
+ (allowTextPresenterAsIconValue && (presenter === 'text' || !presenter))) {
2869
5711
  const rendererIcon = icon || firstNonEmptyString(def.icon);
2870
- const affixes = resolveSemanticPresentationAffixes(presentation);
2871
5712
  const hasAffixes = !!(affixes.prefix || affixes.suffix);
2872
5713
  if (!rendererIcon && !hasAffixes)
2873
5714
  return undefined;
5715
+ if (affixes.prefix || affixes.suffix || tooltipText) {
5716
+ return {
5717
+ type: 'icon',
5718
+ icon: {
5719
+ ...(!hasAffixes && rendererIcon ? { name: rendererIcon } : {}),
5720
+ textField: def.name,
5721
+ ...(color ? { color } : {}),
5722
+ ...(tooltipText ? { ariaLabel: tooltipText } : {}),
5723
+ ...(tooltip ? { tooltip } : {}),
5724
+ ...affixes,
5725
+ },
5726
+ };
5727
+ }
5728
+ if (!rendererIcon)
5729
+ return undefined;
2874
5730
  return {
2875
- type: 'icon',
2876
- icon: {
2877
- ...(rendererIcon && !hasAffixes ? { name: rendererIcon } : {}),
2878
- textField: def.name,
2879
- ...(tooltipText ? { ariaLabel: tooltipText } : {}),
2880
- ...affixes,
5731
+ type: 'compose',
5732
+ compose: {
5733
+ items: [
5734
+ {
5735
+ type: 'icon',
5736
+ icon: {
5737
+ name: rendererIcon,
5738
+ ...(color ? { color } : {}),
5739
+ ...(def.label ? { ariaLabel: def.label } : {}),
5740
+ },
5741
+ },
5742
+ {
5743
+ type: 'value',
5744
+ field: def.name,
5745
+ },
5746
+ ],
5747
+ layout: {
5748
+ direction: 'row',
5749
+ gap: 6,
5750
+ align: 'center',
5751
+ },
2881
5752
  },
2882
5753
  };
2883
5754
  }
2884
5755
  return undefined;
2885
5756
  }
5757
+ function resolveConditionalRenderersFromFieldDefinition(def, options) {
5758
+ const rules = def.presentationRules;
5759
+ if (!Array.isArray(rules) || rules.length === 0)
5760
+ return undefined;
5761
+ const basePresentation = def.presentation && typeof def.presentation === 'object' ? def.presentation : {};
5762
+ const basePresenter = basePresentation.presenter ?? basePresentation.variant;
5763
+ const out = [];
5764
+ rules.forEach((rule, index) => {
5765
+ if (!rule || typeof rule !== 'object' || rule.when === undefined)
5766
+ return;
5767
+ const effect = rule.set ?? rule.effect;
5768
+ if (!effect || typeof effect !== 'object')
5769
+ return;
5770
+ const resolvedPresenter = effect.presenter ?? effect.variant ?? basePresenter;
5771
+ const effectivePresentation = {
5772
+ ...basePresentation,
5773
+ ...effect,
5774
+ ...(resolvedPresenter ? { presenter: resolvedPresenter } : {}),
5775
+ };
5776
+ const renderer = resolveRendererFromFieldPresentation(def, effectivePresentation, options);
5777
+ const tooltipText = firstNonEmptyString(effectivePresentation.tooltip);
5778
+ const tooltip = tooltipText ? { text: tooltipText } : undefined;
5779
+ if (!renderer && !tooltip)
5780
+ return;
5781
+ out.push({
5782
+ id: `schema-presentation-rule-${index}`,
5783
+ condition: rule.when,
5784
+ ...(renderer ? { renderer } : {}),
5785
+ ...(tooltip ? { tooltip } : {}),
5786
+ });
5787
+ });
5788
+ return out.length > 0 ? out : undefined;
5789
+ }
2886
5790
  function resolveSemanticPresentationColor(tone) {
2887
5791
  const normalized = normalizePresentationToken(tone);
2888
- if (!normalized || normalized === 'neutral')
5792
+ if (!normalized)
2889
5793
  return undefined;
2890
- return normalized === 'danger' ? 'warn' : normalized;
5794
+ if (normalized === 'neutral' || normalized === 'muted')
5795
+ return 'basic';
5796
+ if (normalized === 'positive')
5797
+ return 'success';
5798
+ if (normalized === 'warning')
5799
+ return 'warning';
5800
+ if (normalized === 'danger' || normalized === 'critical' || normalized === 'negative') {
5801
+ return 'warn';
5802
+ }
5803
+ return normalized;
2891
5804
  }
2892
5805
  function resolveSemanticPresentationVariant(appearance) {
2893
5806
  const normalized = normalizePresentationToken(appearance);
2894
- return normalized === 'filled' || normalized === 'outlined' || normalized === 'soft'
5807
+ return normalized === 'filled' ||
5808
+ normalized === 'outlined' ||
5809
+ normalized === 'soft' ||
5810
+ normalized === 'plain'
2895
5811
  ? normalized
2896
5812
  : undefined;
2897
5813
  }
2898
5814
  function resolveSemanticPresentationAffixes(presentation) {
2899
- const prefix = firstNonEmptyString(presentation.prefix);
2900
- const suffix = firstNonEmptyString(presentation.suffix);
5815
+ const prefix = normalizeAffix(presentation.prefix);
5816
+ const suffix = normalizeAffix(presentation.suffix);
2901
5817
  return {
2902
5818
  ...(prefix ? { prefix } : {}),
2903
5819
  ...(suffix ? { suffix } : {}),
2904
5820
  };
2905
5821
  }
5822
+ function normalizePresentationAffix(value) {
5823
+ return typeof value === 'string' && value.trim().length > 0 ? value : undefined;
5824
+ }
5825
+ function normalizeAffix(value) {
5826
+ return normalizePresentationAffix(value);
5827
+ }
2906
5828
  function firstNonEmptyString(value) {
2907
5829
  if (typeof value !== 'string')
2908
5830
  return undefined;
2909
5831
  const trimmed = value.trim();
2910
5832
  return trimmed ? trimmed : undefined;
2911
5833
  }
5834
+ function firstFiniteNumber(value) {
5835
+ if (value === null || value === undefined || value === '')
5836
+ return undefined;
5837
+ const numeric = typeof value === 'number' ? value : Number(value);
5838
+ return Number.isFinite(numeric) ? numeric : undefined;
5839
+ }
2912
5840
  function normalizePresentationToken(value) {
2913
5841
  return String(value ?? '').trim().toLowerCase().replace(/[\s_-]+/g, '');
2914
5842
  }
@@ -2943,4 +5871,4 @@ function isTextualControlType(value) {
2943
5871
  * Generated bundle index. Do not edit.
2944
5872
  */
2945
5873
 
2946
- export { deepMerge, isPraxisPresentationVisualizationTableSafe, normalizeSchemaFields, resolveColumnTypeFromFieldDefinition, resolveTextMaskFormatFromFieldDefinition };
5874
+ export { buildSchemaSemanticColumnRenderer, deepMerge, isPraxisPresentationVisualizationTableSafe, normalizePresentationAffix, normalizeSchemaFields, resolveColumnTypeFromFieldDefinition, resolveSchemaConditionalRenderers, resolveTextMaskFormatFromFieldDefinition };