@onekeyfe/react-native-native-list 6.7.0-20 → 6.7.0-21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt +29 -4
  2. package/android/src/main/java/com/onekey/nativelist/NativeListActivityRenderer.kt +6 -10
  3. package/android/src/main/java/com/onekey/nativelist/NativeListAdapter.kt +17 -1
  4. package/android/src/main/java/com/onekey/nativelist/NativeListDataRowRenderer.kt +15 -0
  5. package/android/src/main/java/com/onekey/nativelist/NativeListIdentityRenderer.kt +33 -2
  6. package/android/src/main/java/com/onekey/nativelist/NativeListMarketRenderer.kt +92 -28
  7. package/android/src/main/java/com/onekey/nativelist/NativeListModels.kt +13 -10
  8. package/android/src/main/java/com/onekey/nativelist/NativeListView.kt +33 -8
  9. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListActivityHostClipPolicyTest.kt +11 -5
  10. package/docs/ROW_TEMPLATES.md +10 -2
  11. package/docs/SPEC.md +270 -42
  12. package/ios/NativeListActivityDetailsView.swift +13 -4
  13. package/ios/NativeListIdentityRenderer.swift +50 -3
  14. package/ios/NativeListMarketRenderer.swift +113 -18
  15. package/ios/RNCNativeListView.swift +21 -3
  16. package/ios/tests/NativeListActivityPresentationTests.swift +97 -0
  17. package/ios/tests/NativeListLifecycleTests.swift +73 -4
  18. package/ios/tests/NativeListMarketMetricsTests.swift +117 -0
  19. package/lib/module/NativeList.js +25 -6
  20. package/lib/module/NativeList.web.js +9 -12
  21. package/lib/module/models.js +2 -0
  22. package/lib/module/validation.js +695 -114
  23. package/lib/module/web/NativeListWebEngine.js +3 -9
  24. package/lib/module/web/templates/IdentityRowRenderer.js +58 -4
  25. package/lib/typescript/src/models.d.ts +27 -14
  26. package/lib/typescript/src/validation.d.ts +7 -2
  27. package/package.json +3 -3
  28. package/src/NativeList.tsx +30 -10
  29. package/src/NativeList.web.tsx +10 -14
  30. package/src/models.ts +158 -153
  31. package/src/validation.ts +1757 -167
  32. package/src/web/NativeListWebEngine.ts +6 -10
  33. package/src/web/templates/IdentityRowRenderer.ts +70 -4
package/src/validation.ts CHANGED
@@ -19,6 +19,7 @@ import type {
19
19
  WebMarketTableCell,
20
20
  WebMarketTablePresentation,
21
21
  WebMarketTableText,
22
+ ValueTextSegment,
22
23
  } from './models';
23
24
 
24
25
  const MAX_KEY_LENGTH = 256;
@@ -32,6 +33,17 @@ const MAX_HEADER_LENGTH = 4096;
32
33
  const MAX_SPACER_HEIGHT = 512;
33
34
  const MAX_SECTION_INDEX_TITLE_LENGTH = 8;
34
35
  const MAX_MARKET_BADGES = 3;
36
+ const MARKET_METRIC_FIELDS = [
37
+ 'key',
38
+ 'text',
39
+ 'textSegments',
40
+ 'secondaryText',
41
+ 'secondaryTextSegments',
42
+ 'weight',
43
+ 'alignment',
44
+ 'tone',
45
+ 'secondaryTone',
46
+ ] as const;
35
47
 
36
48
  function isDevelopment(): boolean {
37
49
  return typeof __DEV__ !== 'undefined' && __DEV__;
@@ -74,13 +86,15 @@ export function emptyNativeListSnapshot(): NativeListSnapshot {
74
86
  function assertPlainSerializable(
75
87
  value: unknown,
76
88
  path: string,
77
- seen: Set<object>
89
+ seen: Set<object>,
90
+ requireFinite = true
78
91
  ): void {
79
92
  if (value === null || value === undefined) return;
80
93
  const valueType = typeof value;
81
94
  if (valueType === 'string' || valueType === 'boolean') return;
82
95
  if (valueType === 'number') {
83
- if (!Number.isFinite(value)) fail(path, 'numbers must be finite');
96
+ if (requireFinite && !Number.isFinite(value))
97
+ fail(path, 'numbers must be finite');
84
98
  return;
85
99
  }
86
100
  if (valueType !== 'object')
@@ -91,16 +105,21 @@ function assertPlainSerializable(
91
105
  seen.add(objectValue);
92
106
  if (Array.isArray(value)) {
93
107
  value.forEach((item, index) =>
94
- assertPlainSerializable(item, `${path}[${index}]`, seen)
108
+ assertPlainSerializable(item, `${path}[${index}]`, seen, requireFinite)
95
109
  );
96
110
  } else {
97
111
  const prototype = Object.getPrototypeOf(value);
98
112
  if (prototype !== Object.prototype && prototype !== null) {
99
113
  fail(path, 'must contain plain objects only');
100
114
  }
101
- Object.entries(value as Record<string, unknown>).forEach(([key, item]) =>
102
- assertPlainSerializable(item, `${path}.${key}`, seen)
103
- );
115
+ Object.entries(value as Record<string, unknown>).forEach(([key, item]) => {
116
+ if (
117
+ key === '__proto__' ||
118
+ (key === 'constructor' && typeof item === 'object')
119
+ )
120
+ fail(path, 'unsafe object key');
121
+ assertPlainSerializable(item, `${path}.${key}`, seen, requireFinite);
122
+ });
104
123
  }
105
124
  seen.delete(objectValue);
106
125
  }
@@ -975,8 +994,88 @@ function assertWebMarketTable(
975
994
  });
976
995
  }
977
996
 
997
+ function assertMarketMetrics(
998
+ metrics: MarketRow['metrics'],
999
+ path: string
1000
+ ): void {
1001
+ if (metrics === undefined) return;
1002
+ if (!Array.isArray(metrics) || ![2, 3].includes(metrics.length))
1003
+ fail(path, 'must contain 2 or 3 columns');
1004
+ const keys = new Set<string>();
1005
+ metrics.forEach(
1006
+ (column: NonNullable<MarketRow['metrics']>[number], index: number) => {
1007
+ const columnPath = `${path}[${index}]`;
1008
+ const value = protocolObject(column, columnPath);
1009
+ protocolKey(value.key, `${columnPath}.key`);
1010
+ if (keys.has(column.key)) fail(`${columnPath}.key`, 'must be unique');
1011
+ keys.add(column.key);
1012
+ if (typeof value.text !== 'string')
1013
+ fail(`${columnPath}.text`, 'must be a string');
1014
+ for (const field of ['textSegments', 'secondaryTextSegments'] as const) {
1015
+ const segments = column[field];
1016
+ if (segments !== undefined && !Array.isArray(segments))
1017
+ fail(`${columnPath}.${field}`, 'must be an array');
1018
+ segments?.forEach((segment: ValueTextSegment, segmentIndex: number) => {
1019
+ const segmentPath = `${columnPath}.${field}[${segmentIndex}]`;
1020
+ protocolObject(segment, segmentPath);
1021
+ if (typeof segment.text !== 'string')
1022
+ fail(`${segmentPath}.text`, 'must be a string');
1023
+ if (segment.style !== undefined && segment.style !== 'subscript')
1024
+ fail(`${segmentPath}.style`, 'must be subscript');
1025
+ });
1026
+ }
1027
+ if (
1028
+ value.weight !== undefined &&
1029
+ ![1, 2, 3].includes(value.weight as number)
1030
+ )
1031
+ fail(`${columnPath}.weight`, 'must be 1, 2, or 3');
1032
+ if (
1033
+ value.alignment !== undefined &&
1034
+ !['start', 'center', 'end'].includes(value.alignment as string)
1035
+ )
1036
+ fail(`${columnPath}.alignment`, 'must be start, center, or end');
1037
+ if (
1038
+ value.secondaryText !== undefined &&
1039
+ typeof value.secondaryText !== 'string'
1040
+ )
1041
+ fail(`${columnPath}.secondaryText`, 'must be a string');
1042
+ assertTextTone(value.tone as string | undefined, `${columnPath}.tone`);
1043
+ assertTextTone(
1044
+ value.secondaryTone as string | undefined,
1045
+ `${columnPath}.secondaryTone`
1046
+ );
1047
+ }
1048
+ );
1049
+ }
1050
+
978
1051
  function assertMarketRow(row: MarketRow, path: string): void {
979
1052
  assertWebMarketTable(row.webTable, `${path}.webTable`);
1053
+ assertMarketMetrics(row.metrics, `${path}.metrics`);
1054
+ if (row.metrics !== undefined) {
1055
+ row.metrics.forEach((column, index) => {
1056
+ const columnPath = `${path}.metrics[${index}]`;
1057
+ const value = protocolObject(column, columnPath);
1058
+ assertUnknownKeys(
1059
+ value,
1060
+ MARKET_METRIC_FIELDS,
1061
+ columnPath,
1062
+ 'Market metric key'
1063
+ );
1064
+ assertKey(column.key, `${columnPath}.key`);
1065
+ assertText(column.text, `${columnPath}.text`);
1066
+ assertText(column.secondaryText, `${columnPath}.secondaryText`);
1067
+ assertTextTone(column.tone, `${columnPath}.tone`);
1068
+ assertTextTone(column.secondaryTone, `${columnPath}.secondaryTone`);
1069
+ for (const field of ['textSegments', 'secondaryTextSegments'] as const) {
1070
+ column[field]?.forEach((segment, segmentIndex) => {
1071
+ const segmentPath = `${columnPath}.${field}[${segmentIndex}]`;
1072
+ assertText(segment.text, `${segmentPath}.text`);
1073
+ if (segment.style !== undefined && segment.style !== 'subscript')
1074
+ fail(`${segmentPath}.style`, 'must be subscript');
1075
+ });
1076
+ }
1077
+ });
1078
+ }
980
1079
  if (!['token', 'stock', 'perp'].includes(row.variant)) {
981
1080
  fail(`${path}.variant`, 'must be token, stock, or perp');
982
1081
  }
@@ -1248,7 +1347,7 @@ function assertButtonGroup(
1248
1347
  function assertIdentityExtras(
1249
1348
  row: Pick<
1250
1349
  IdentityRow,
1251
- 'titleIcon' | 'secondaryTitleIcon' | 'trailing' | 'style'
1350
+ 'titleIcon' | 'secondaryTitleIcon' | 'titleImage' | 'trailing' | 'style'
1252
1351
  >,
1253
1352
  path: string
1254
1353
  ): void {
@@ -1279,6 +1378,30 @@ function assertIdentityExtras(
1279
1378
  if (titleIcon.hoverActionKey !== undefined)
1280
1379
  assertKey(titleIcon.hoverActionKey, `${iconPath}.hoverActionKey`);
1281
1380
  }
1381
+ if (row.titleImage !== undefined) {
1382
+ const imagePath = `${path}.titleImage`;
1383
+ const descriptor = protocolObject(row.titleImage, imagePath);
1384
+ assertUnknownKeys(
1385
+ descriptor,
1386
+ ['image', 'accessibilityLabel', 'hoverActionKey'],
1387
+ imagePath,
1388
+ 'title image key'
1389
+ );
1390
+ protocolObject(row.titleImage.image, `${imagePath}.image`);
1391
+ if (typeof row.titleImage.image.uri !== 'string')
1392
+ fail(`${imagePath}.image.uri`, 'must be a string');
1393
+ assertImage(row.titleImage.image, `${imagePath}.image`);
1394
+ const { width, height } = row.titleImage.image;
1395
+ if (width !== height || width < 1 || width > 40)
1396
+ fail(`${imagePath}.image`, 'must be square within 1...40');
1397
+ if (
1398
+ row.titleImage.accessibilityLabel !== undefined &&
1399
+ typeof row.titleImage.accessibilityLabel !== 'string'
1400
+ )
1401
+ fail(`${imagePath}.accessibilityLabel`, 'must be a string');
1402
+ if (row.titleImage.hoverActionKey !== undefined)
1403
+ assertKey(row.titleImage.hoverActionKey, `${imagePath}.hoverActionKey`);
1404
+ }
1282
1405
  const ratio = row.style?.leadingContentMaxWidthRatio;
1283
1406
  if (
1284
1407
  ratio !== undefined &&
@@ -1293,6 +1416,8 @@ function assertIdentityExtras(
1293
1416
 
1294
1417
  function assertImage(image: ImageSource | undefined, path: string): void {
1295
1418
  if (!image) return;
1419
+ if (!isAllowedImageUri(image.uri))
1420
+ fail(`${path}.uri`, 'unsupported image URI');
1296
1421
  if (!image.uri.trim()) fail(`${path}.uri`, 'must not be empty');
1297
1422
  if (image.fallbackUris !== undefined) {
1298
1423
  if (!Array.isArray(image.fallbackUris))
@@ -1634,6 +1759,7 @@ function assertRow(
1634
1759
  path = `rows[${index}]`
1635
1760
  ): void {
1636
1761
  assertRowType(row.type, path);
1762
+ assertUnknownKeys(row, ROW_FIELDS[row.type], path, 'row key');
1637
1763
  assertKey(row.key, `${path}.key`);
1638
1764
  // OneKey patch: explicit dimensions and opacity cannot corrupt list layout.
1639
1765
  if (row.height !== undefined && (row.height < 0 || row.height > 4096))
@@ -2250,6 +2376,340 @@ function assertSnapshotContract(
2250
2376
  return snapshot;
2251
2377
  }
2252
2378
 
2379
+ const COMMON_ROW_FIELDS = [
2380
+ 'height',
2381
+ 'heightRounding',
2382
+ 'testID',
2383
+ 'opacity',
2384
+ 'backgroundColor',
2385
+ 'backgroundFullWidth',
2386
+ 'pressDisabled',
2387
+ 'key',
2388
+ 'revision',
2389
+ 'sectionKey',
2390
+ 'groupId',
2391
+ 'groupPosition',
2392
+ 'size',
2393
+ 'density',
2394
+ 'disabled',
2395
+ 'selected',
2396
+ 'accessibilityLabel',
2397
+ 'separator',
2398
+ 'type',
2399
+ 'style',
2400
+ ];
2401
+
2402
+ const ROW_FIELDS: Readonly<Record<string, readonly string[]>> = {
2403
+ identity: [
2404
+ ...COMMON_ROW_FIELDS,
2405
+ 'contentHeight',
2406
+ 'longPressActionKey',
2407
+ 'titleMatch',
2408
+ 'titleActionKey',
2409
+ 'titleActionOnHover',
2410
+ 'subtitleSegments',
2411
+ 'presentation',
2412
+ 'leading',
2413
+ 'leadingAction',
2414
+ 'title',
2415
+ 'titleSuffixes',
2416
+ 'titleIcon',
2417
+ 'secondaryTitleIcon',
2418
+ 'titleImage',
2419
+ 'subtitle',
2420
+ 'tertiary',
2421
+ 'tertiaryTone',
2422
+ 'titleLines',
2423
+ 'subtitleLines',
2424
+ 'badges',
2425
+ 'trailing',
2426
+ 'draggable',
2427
+ ],
2428
+ walletGroup: [...COMMON_ROW_FIELDS, 'parent', 'children', 'draggable'],
2429
+ rail: [
2430
+ ...COMMON_ROW_FIELDS,
2431
+ 'visual',
2432
+ 'title',
2433
+ 'status',
2434
+ 'badge',
2435
+ 'draggable',
2436
+ ],
2437
+ activity: [
2438
+ ...COMMON_ROW_FIELDS,
2439
+ 'leading',
2440
+ 'hideLeading',
2441
+ 'secondaryLeading',
2442
+ 'title',
2443
+ 'description',
2444
+ 'status',
2445
+ 'primaryAmount',
2446
+ 'secondaryAmount',
2447
+ 'amounts',
2448
+ 'badges',
2449
+ 'presentation',
2450
+ 'fee',
2451
+ 'descriptionActionKey',
2452
+ 'footerActions',
2453
+ ],
2454
+ message: [
2455
+ ...COMMON_ROW_FIELDS,
2456
+ 'presentation',
2457
+ 'unread',
2458
+ 'leading',
2459
+ 'title',
2460
+ 'body',
2461
+ 'bodyLines',
2462
+ 'time',
2463
+ 'thumbnail',
2464
+ ],
2465
+ dataRow: [
2466
+ ...COMMON_ROW_FIELDS,
2467
+ 'leading',
2468
+ 'columns',
2469
+ 'trailing',
2470
+ 'checkbox',
2471
+ 'index',
2472
+ 'badge',
2473
+ 'badges',
2474
+ 'favorite',
2475
+ 'favoriteActive',
2476
+ ],
2477
+ market: [
2478
+ ...COMMON_ROW_FIELDS,
2479
+ 'variant',
2480
+ 'webTable',
2481
+ 'metrics',
2482
+ 'leadingAction',
2483
+ 'leading',
2484
+ 'title',
2485
+ 'subtitle',
2486
+ 'subtitlePrefix',
2487
+ 'subtitleSegments',
2488
+ 'price',
2489
+ 'priceSegments',
2490
+ 'change',
2491
+ 'badges',
2492
+ 'pressActionKey',
2493
+ 'pressInActionKey',
2494
+ 'longPressActionKey',
2495
+ 'diagnostics',
2496
+ ],
2497
+ mediaTile: [
2498
+ ...COMMON_ROW_FIELDS,
2499
+ 'variant',
2500
+ 'media',
2501
+ 'image',
2502
+ 'imageState',
2503
+ 'networkImage',
2504
+ 'title',
2505
+ 'subtitle',
2506
+ 'badge',
2507
+ 'closeActionKey',
2508
+ ],
2509
+ metricCard: [
2510
+ ...COMMON_ROW_FIELDS,
2511
+ 'variant',
2512
+ 'title',
2513
+ 'value',
2514
+ 'subtitle',
2515
+ 'trend',
2516
+ 'trendTone',
2517
+ 'visual',
2518
+ 'badge',
2519
+ 'metrics',
2520
+ 'progress',
2521
+ ],
2522
+ sectionHeader: [
2523
+ ...COMMON_ROW_FIELDS,
2524
+ 'sticky',
2525
+ 'valueActionTestID',
2526
+ 'valueSegments',
2527
+ 'titleActionKey',
2528
+ 'titleActionOnHover',
2529
+ 'presentation',
2530
+ 'indexTitle',
2531
+ 'variant',
2532
+ 'title',
2533
+ 'leadingBadge',
2534
+ 'titleLoading',
2535
+ 'subtitle',
2536
+ 'value',
2537
+ 'valueHelp',
2538
+ 'valueActionKey',
2539
+ 'titleIcon',
2540
+ 'valueIcon',
2541
+ 'checkbox',
2542
+ ],
2543
+ action: [
2544
+ ...COMMON_ROW_FIELDS,
2545
+ 'presentation',
2546
+ 'title',
2547
+ 'actionKey',
2548
+ 'tone',
2549
+ 'icon',
2550
+ 'checkbox',
2551
+ 'trailing',
2552
+ ],
2553
+ buttonGroup: [...COMMON_ROW_FIELDS, 'buttons'],
2554
+ system: [
2555
+ ...COMMON_ROW_FIELDS,
2556
+ 'variant',
2557
+ 'presentation',
2558
+ 'loadingStyle',
2559
+ 'message',
2560
+ 'actionKey',
2561
+ 'actionText',
2562
+ 'title',
2563
+ 'borderColor',
2564
+ ],
2565
+ };
2566
+
2567
+ const COMMON_PATCH_FIELDS = [
2568
+ 'height',
2569
+ 'heightRounding',
2570
+ 'opacity',
2571
+ 'pressDisabled',
2572
+ 'revision',
2573
+ 'disabled',
2574
+ 'selected',
2575
+ 'accessibilityLabel',
2576
+ 'separator',
2577
+ 'style',
2578
+ ];
2579
+
2580
+ const PATCH_FIELDS: Readonly<Record<string, readonly string[]>> = {
2581
+ identity: [
2582
+ ...COMMON_PATCH_FIELDS,
2583
+ 'contentHeight',
2584
+ 'longPressActionKey',
2585
+ 'titleMatch',
2586
+ 'titleActionKey',
2587
+ 'titleActionOnHover',
2588
+ 'subtitleSegments',
2589
+ 'leading',
2590
+ 'leadingAction',
2591
+ 'title',
2592
+ 'titleSuffixes',
2593
+ 'titleIcon',
2594
+ 'secondaryTitleIcon',
2595
+ 'titleImage',
2596
+ 'subtitle',
2597
+ 'tertiary',
2598
+ 'tertiaryTone',
2599
+ 'subtitleLines',
2600
+ 'badges',
2601
+ 'trailing',
2602
+ ],
2603
+ rail: [...COMMON_PATCH_FIELDS, 'title', 'visual', 'status', 'badge'],
2604
+ activity: [
2605
+ ...COMMON_PATCH_FIELDS,
2606
+ 'presentation',
2607
+ 'leading',
2608
+ 'title',
2609
+ 'badges',
2610
+ 'status',
2611
+ 'hideLeading',
2612
+ 'secondaryLeading',
2613
+ 'description',
2614
+ 'primaryAmount',
2615
+ 'secondaryAmount',
2616
+ 'amounts',
2617
+ 'fee',
2618
+ 'descriptionActionKey',
2619
+ 'footerActions',
2620
+ ],
2621
+ message: [
2622
+ ...COMMON_PATCH_FIELDS,
2623
+ 'presentation',
2624
+ 'title',
2625
+ 'unread',
2626
+ 'body',
2627
+ 'bodyLines',
2628
+ 'time',
2629
+ 'thumbnail',
2630
+ ],
2631
+ dataRow: [
2632
+ ...COMMON_PATCH_FIELDS,
2633
+ 'leading',
2634
+ 'badges',
2635
+ 'trailing',
2636
+ 'badge',
2637
+ 'columns',
2638
+ 'checkbox',
2639
+ 'index',
2640
+ 'favorite',
2641
+ 'favoriteActive',
2642
+ ],
2643
+ market: [
2644
+ ...COMMON_PATCH_FIELDS,
2645
+ 'longPressActionKey',
2646
+ 'subtitleSegments',
2647
+ 'leading',
2648
+ 'leadingAction',
2649
+ 'title',
2650
+ 'subtitle',
2651
+ 'badges',
2652
+ 'webTable',
2653
+ 'metrics',
2654
+ 'price',
2655
+ 'priceSegments',
2656
+ 'change',
2657
+ 'pressActionKey',
2658
+ 'pressInActionKey',
2659
+ 'diagnostics',
2660
+ ],
2661
+ mediaTile: [
2662
+ ...COMMON_PATCH_FIELDS,
2663
+ 'title',
2664
+ 'subtitle',
2665
+ 'badge',
2666
+ 'media',
2667
+ 'image',
2668
+ 'imageState',
2669
+ 'networkImage',
2670
+ 'closeActionKey',
2671
+ ],
2672
+ metricCard: [
2673
+ ...COMMON_PATCH_FIELDS,
2674
+ 'title',
2675
+ 'subtitle',
2676
+ 'visual',
2677
+ 'badge',
2678
+ 'variant',
2679
+ 'value',
2680
+ 'trend',
2681
+ 'trendTone',
2682
+ 'metrics',
2683
+ 'progress',
2684
+ ],
2685
+ sectionHeader: [
2686
+ ...COMMON_PATCH_FIELDS,
2687
+ 'titleActionKey',
2688
+ 'titleActionOnHover',
2689
+ 'title',
2690
+ 'titleIcon',
2691
+ 'subtitle',
2692
+ 'checkbox',
2693
+ 'variant',
2694
+ 'value',
2695
+ 'leadingBadge',
2696
+ 'titleLoading',
2697
+ 'valueHelp',
2698
+ 'valueActionKey',
2699
+ 'valueIcon',
2700
+ ],
2701
+ action: [
2702
+ ...COMMON_PATCH_FIELDS,
2703
+ 'title',
2704
+ 'trailing',
2705
+ 'checkbox',
2706
+ 'tone',
2707
+ 'icon',
2708
+ ],
2709
+ buttonGroup: [...COMMON_PATCH_FIELDS, 'buttons'],
2710
+ system: ['revision', 'disabled', 'message'],
2711
+ };
2712
+
2253
2713
  function protocolObject(value: unknown, path: string): Record<string, unknown> {
2254
2714
  if (!value || typeof value !== 'object' || Array.isArray(value))
2255
2715
  fail(path, 'must be an object');
@@ -2389,6 +2849,14 @@ function assertProtocolFields(
2389
2849
  fail(`${path}.uri`, 'must be a string');
2390
2850
  Object.entries(value).forEach(([field, item]) => {
2391
2851
  if (item === undefined) return;
2852
+ if (field === 'headers') {
2853
+ const headers = protocolObject(item, `${path}.headers`);
2854
+ for (const [name, headerValue] of Object.entries(headers)) {
2855
+ if (!name.trim() || typeof headerValue !== 'string')
2856
+ fail(`${path}.headers`, 'must contain string headers');
2857
+ }
2858
+ return;
2859
+ }
2392
2860
  const fieldPath = `${path}.${field}`;
2393
2861
  if (
2394
2862
  !path.endsWith('.style') &&
@@ -2418,6 +2886,7 @@ function assertProtocolFields(
2418
2886
  if (
2419
2887
  field === 'key' ||
2420
2888
  field === 'sectionKey' ||
2889
+ field === 'groupId' ||
2421
2890
  field === 'actionKey' ||
2422
2891
  field.endsWith('ActionKey')
2423
2892
  )
@@ -2466,6 +2935,7 @@ function assertRowProtocol(row: RowModel, path: string): void {
2466
2935
  protocolObject(row, path);
2467
2936
  assertRowType(row.type, path);
2468
2937
  protocolKey(row.key, `${path}.key`);
2938
+ assertCoreRow(row, path);
2469
2939
  assertProtocolFields(row, path);
2470
2940
  for (const field of ['leading', 'visual', 'secondaryLeading'] as const) {
2471
2941
  const visual = (row as unknown as Record<string, unknown>)[field];
@@ -2495,7 +2965,7 @@ function assertRowProtocol(row: RowModel, path: string): void {
2495
2965
  if (row.height !== undefined && row.height < 0)
2496
2966
  fail(`${path}.height`, 'must be non-negative');
2497
2967
  if (row.type === 'identity') {
2498
- assertIdentityExtras(row, path);
2968
+ if (isDevelopment()) assertIdentityExtras(row, path);
2499
2969
  if (row.titleSuffixes !== undefined && !Array.isArray(row.titleSuffixes))
2500
2970
  fail(`${path}.titleSuffixes`, 'must be an array');
2501
2971
  row.titleSuffixes?.forEach((suffix, index) => {
@@ -2529,8 +2999,9 @@ function assertRowProtocol(row: RowModel, path: string): void {
2529
2999
  end = match.end;
2530
3000
  });
2531
3001
  }
2532
- if (row.type === 'buttonGroup') assertButtonGroup(row, path);
2533
- if (row.type === 'sectionHeader')
3002
+ if (row.type === 'buttonGroup' && isDevelopment())
3003
+ assertButtonGroup(row, path);
3004
+ if (row.type === 'sectionHeader' && isDevelopment())
2534
3005
  assertTextHelp(row.valueHelp, `${path}.valueHelp`);
2535
3006
  if (row.type === 'mediaTile' && row.media) {
2536
3007
  protocolObject(row.media.source, `${path}.media.source`);
@@ -2558,12 +3029,14 @@ function assertRowProtocol(row: RowModel, path: string): void {
2558
3029
  row.columns.forEach((column, index) => {
2559
3030
  const columnPath = `${path}.columns[${index}]`;
2560
3031
  protocolObject(column, columnPath);
2561
- assertIdentityExtras(column, columnPath);
3032
+ if (isDevelopment()) assertIdentityExtras(column, columnPath);
2562
3033
  });
2563
- assertTrailingAccessories(row.trailing, `${path}.trailing`);
3034
+ if (isDevelopment())
3035
+ assertTrailingAccessories(row.trailing, `${path}.trailing`);
2564
3036
  }
2565
3037
  if (row.type === 'market') {
2566
3038
  protocolObject(row.change, `${path}.change`);
3039
+ assertMarketMetrics(row.metrics, `${path}.metrics`);
2567
3040
  if (row.webTable) {
2568
3041
  const { columns, cells } = row.webTable;
2569
3042
  if (
@@ -2696,19 +3169,800 @@ function assertSnapshotProtocol(snapshot: NativeListSnapshot): void {
2696
3169
  }
2697
3170
  }
2698
3171
 
2699
- /** Empty optional image descriptors must take the same path as absent images. */
3172
+ function isRecord(value: unknown): value is Record<string, unknown> {
3173
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
3174
+ }
3175
+
3176
+ function isAllowedImageUri(value: unknown): value is string {
3177
+ return (
3178
+ typeof value === 'string' &&
3179
+ value.trim().length > 0 &&
3180
+ (!/^[a-z][a-z\d+.-]*:/i.test(value) ||
3181
+ /^(https?|file|content|ph|assets-library|asset|res|blob|onekey-avatar):/i.test(
3182
+ value
3183
+ ) ||
3184
+ /^data:image\//i.test(value))
3185
+ );
3186
+ }
3187
+
3188
+ const IMAGE_FIELDS = [
3189
+ 'uri',
3190
+ 'width',
3191
+ 'height',
3192
+ 'headers',
3193
+ 'contentFit',
3194
+ 'cachePolicy',
3195
+ 'autoplay',
3196
+ 'optimizeTos',
3197
+ 'overscan',
3198
+ 'loadingStrategy',
3199
+ 'fallbackUri',
3200
+ 'fallbackUris',
3201
+ 'retryTimes',
3202
+ ];
3203
+ const ICON_FIELDS = [
3204
+ 'name',
3205
+ 'tintColor',
3206
+ 'backgroundColor',
3207
+ 'size',
3208
+ 'accessibilityLabel',
3209
+ 'hoverActionKey',
3210
+ ];
3211
+ const VISUAL_FIELDS = [
3212
+ 'kind',
3213
+ 'name',
3214
+ 'image',
3215
+ 'images',
3216
+ 'networkImage',
3217
+ 'shape',
3218
+ 'tintColor',
3219
+ 'backgroundColor',
3220
+ 'fallbackIcon',
3221
+ 'fallbackText',
3222
+ 'fallbackTextColor',
3223
+ 'overlays',
3224
+ 'borderStyle',
3225
+ 'borderColor',
3226
+ 'cornerIcon',
3227
+ ];
3228
+ const TEXT_STYLE_FIELDS = [
3229
+ 'token',
3230
+ 'fontSize',
3231
+ 'fontWeight',
3232
+ 'color',
3233
+ 'lineHeight',
3234
+ 'lines',
3235
+ 'truncate',
3236
+ 'alignment',
3237
+ 'verticalAlignment',
3238
+ 'offsetY',
3239
+ ];
3240
+ const ACCESSORY_FIELDS: Readonly<Record<string, readonly string[]>> = {
3241
+ value: ['kind', 'text', 'secondary', 'textSegments'],
3242
+ valuePair: [
3243
+ 'kind',
3244
+ 'primary',
3245
+ 'secondary',
3246
+ 'primaryFontWeight',
3247
+ 'primaryHelp',
3248
+ 'primaryTextSegments',
3249
+ 'secondaryTextSegments',
3250
+ 'primaryTone',
3251
+ 'secondaryTone',
3252
+ ],
3253
+ button: [
3254
+ 'kind',
3255
+ 'label',
3256
+ 'actionKey',
3257
+ 'disabled',
3258
+ 'testID',
3259
+ 'accessibilityLabel',
3260
+ 'textColor',
3261
+ 'backgroundColor',
3262
+ 'pressedBackgroundColor',
3263
+ 'hoverBackgroundColor',
3264
+ 'focusRingColor',
3265
+ ],
3266
+ icon: [
3267
+ 'kind',
3268
+ 'name',
3269
+ 'tintColor',
3270
+ 'buttonStyle',
3271
+ 'disabled',
3272
+ 'actionKey',
3273
+ 'testID',
3274
+ 'hoverActionKey',
3275
+ 'accessibilityLabel',
3276
+ ],
3277
+ checkbox: ['kind', 'state', 'disabled', 'loading', 'target', 'actionKey'],
3278
+ radio: ['kind', 'checked', 'disabled', 'actionKey'],
3279
+ switch: ['kind', 'value', 'disabled', 'actionKey'],
3280
+ chevron: ['kind', 'actionKey'],
3281
+ menu: ['kind', 'actionKey'],
3282
+ drag: ['kind', 'actionKey'],
3283
+ spinner: ['kind'],
3284
+ progress: ['kind', 'value'],
3285
+ };
3286
+
3287
+ const REQUIRED_ROW_FIELDS: Readonly<Record<string, readonly string[]>> = {
3288
+ identity: ['title', 'leading'],
3289
+ walletGroup: ['parent', 'children'],
3290
+ rail: ['title', 'visual'],
3291
+ activity: ['title', 'leading'],
3292
+ message: ['title', 'body', 'time'],
3293
+ dataRow: ['columns'],
3294
+ market: ['title', 'leading', 'variant', 'price', 'change'],
3295
+ mediaTile: ['title', 'variant'],
3296
+ metricCard: ['title', 'value'],
3297
+ sectionHeader: ['title', 'sectionKey'],
3298
+ action: ['title', 'actionKey'],
3299
+ buttonGroup: ['buttons'],
3300
+ system: ['variant'],
3301
+ };
3302
+
3303
+ function assertCoreRow(row: RowModel, path: string): void {
3304
+ const object = row as unknown as Record<string, unknown>;
3305
+ for (const key of REQUIRED_ROW_FIELDS[row.type]) {
3306
+ const value = object[key];
3307
+ if (value === undefined || value === null)
3308
+ fail(`${path}.${key}`, 'required field');
3309
+ if (
3310
+ ['title', 'body', 'time', 'price', 'value', 'variant'].includes(key) &&
3311
+ typeof value !== 'string'
3312
+ )
3313
+ fail(`${path}.${key}`, 'must be a string');
3314
+ }
3315
+ if (row.type === 'market') {
3316
+ if (!row.price.trim()) fail(`${path}.price`, 'must be nonblank');
3317
+ if (typeof row.change?.text !== 'string')
3318
+ fail(`${path}.change.text`, 'must be a string');
3319
+ }
3320
+ if (row.type === 'activity') {
3321
+ row.amounts?.forEach((amount, index) => {
3322
+ protocolKey(amount.key, `${path}.amounts[${index}].key`);
3323
+ if (typeof amount.text !== 'string')
3324
+ fail(`${path}.amounts[${index}].text`, 'required financial text');
3325
+ });
3326
+ if (row.fee && typeof row.fee.primary !== 'string')
3327
+ fail(`${path}.fee.primary`, 'required financial text');
3328
+ row.footerActions?.forEach((action, index) => {
3329
+ protocolKey(action.key, `${path}.footerActions[${index}].key`);
3330
+ protocolKey(action.label, `${path}.footerActions[${index}].label`);
3331
+ });
3332
+ }
3333
+ if (row.type === 'action') protocolKey(row.actionKey, `${path}.actionKey`);
3334
+ if (row.type === 'sectionHeader')
3335
+ protocolKey(row.sectionKey, `${path}.sectionKey`);
3336
+ if (
3337
+ row.type === 'system' &&
3338
+ ['retry', 'warning', 'noMatch'].includes(row.variant)
3339
+ ) {
3340
+ if (typeof object.message !== 'string')
3341
+ fail(`${path}.message`, 'must be a string');
3342
+ if (row.variant === 'retry')
3343
+ protocolKey(row.actionKey, `${path}.actionKey`);
3344
+ }
3345
+ if (row.type === 'dataRow') {
3346
+ if (!Array.isArray(row.columns) || row.columns.length === 0)
3347
+ fail(`${path}.columns`, 'required columns');
3348
+ row.columns.forEach((column, index) => {
3349
+ protocolObject(column, `${path}.columns[${index}]`);
3350
+ protocolKey(column.key, `${path}.columns[${index}].key`);
3351
+ if (typeof column.text !== 'string')
3352
+ fail(`${path}.columns[${index}].text`, 'must be a string');
3353
+ });
3354
+ }
3355
+ if (row.type === 'buttonGroup') {
3356
+ if (!Array.isArray(row.buttons) || row.buttons.length === 0)
3357
+ fail(`${path}.buttons`, 'required buttons');
3358
+ const keys = new Set<string>();
3359
+ row.buttons.forEach((button, index) => {
3360
+ const field = `${path}.buttons[${index}]`;
3361
+ protocolObject(button, field);
3362
+ protocolKey(button.key, `${field}.key`);
3363
+ protocolKey(button.actionKey, `${field}.actionKey`);
3364
+ protocolKey(button.label, `${field}.label`);
3365
+ if (keys.has(button.key)) fail(field, 'duplicate button identity');
3366
+ keys.add(button.key);
3367
+ });
3368
+ }
3369
+ for (const field of [
3370
+ 'trailing',
3371
+ 'leadingAction',
3372
+ 'titleIcon',
3373
+ 'valueIcon',
3374
+ ] as const) {
3375
+ const value = object[field];
3376
+ if (value === undefined) continue;
3377
+ // Identity title icons are decorative descriptors, not trailing controls.
3378
+ if (field === 'titleIcon' && row.type !== 'sectionHeader') continue;
3379
+ const accessories = field === 'trailing' ? value : [value];
3380
+ if (!Array.isArray(accessories))
3381
+ fail(`${path}.${field}`, 'must be an array');
3382
+ accessories.forEach((accessory, index) => {
3383
+ const entry = protocolObject(accessory, `${path}.${field}[${index}]`);
3384
+ for (const key of entry.kind === 'value'
3385
+ ? ['text']
3386
+ : entry.kind === 'valuePair'
3387
+ ? ['primary', 'secondary']
3388
+ : []) {
3389
+ if (typeof entry[key] !== 'string')
3390
+ fail(`${path}.${field}[${index}].${key}`, 'required financial text');
3391
+ }
3392
+ if (
3393
+ ['button', 'menu', 'switch'].includes(entry.kind as string) ||
3394
+ 'actionKey' in entry
3395
+ ) {
3396
+ protocolKey(entry.actionKey, `${path}.${field}[${index}].actionKey`);
3397
+ if (entry.kind === 'button')
3398
+ protocolKey(entry.label, `${path}.${field}[${index}].label`);
3399
+ }
3400
+ if (entry.kind === 'icon')
3401
+ protocolKey(entry.name, `${path}.${field}[${index}].name`);
3402
+ });
3403
+ }
3404
+ }
3405
+
3406
+ function pickFields(
3407
+ object: Record<string, unknown>,
3408
+ fields: readonly string[]
3409
+ ): Record<string, unknown> {
3410
+ return Object.fromEntries(
3411
+ Object.entries(object).filter(([key]) => fields.includes(key))
3412
+ );
3413
+ }
3414
+
3415
+ function sanitizeImage(value: unknown): Record<string, unknown> | undefined {
3416
+ if (
3417
+ !isRecord(value) ||
3418
+ !isAllowedImageUri(value.uri) ||
3419
+ typeof value.width !== 'number' ||
3420
+ !Number.isFinite(value.width) ||
3421
+ value.width <= 0 ||
3422
+ typeof value.height !== 'number' ||
3423
+ !Number.isFinite(value.height) ||
3424
+ value.height <= 0
3425
+ )
3426
+ return undefined;
3427
+ const next = pickFields(value, IMAGE_FIELDS);
3428
+ next.width = Math.min(MAX_IMAGE_EDGE, value.width);
3429
+ next.height = Math.min(MAX_IMAGE_EDGE, value.height);
3430
+ if (next.headers !== undefined) {
3431
+ if (!isRecord(next.headers)) delete next.headers;
3432
+ else
3433
+ next.headers = Object.fromEntries(
3434
+ Object.entries(next.headers)
3435
+ .filter(
3436
+ ([key, item]) =>
3437
+ key.trim() &&
3438
+ key.length <= MAX_HEADER_LENGTH &&
3439
+ typeof item === 'string' &&
3440
+ item.length <= MAX_HEADER_LENGTH
3441
+ )
3442
+ .slice(0, MAX_IMAGE_HEADERS)
3443
+ );
3444
+ }
3445
+ if (next.fallbackUris !== undefined) {
3446
+ if (Array.isArray(next.fallbackUris))
3447
+ next.fallbackUris = next.fallbackUris.filter(isAllowedImageUri);
3448
+ else delete next.fallbackUris;
3449
+ }
3450
+ if (next.fallbackUri !== undefined && !isAllowedImageUri(next.fallbackUri))
3451
+ delete next.fallbackUri;
3452
+ if (
3453
+ next.overscan !== undefined &&
3454
+ (typeof next.overscan !== 'number' ||
3455
+ !Number.isFinite(next.overscan) ||
3456
+ next.overscan < 1 ||
3457
+ next.overscan > 4)
3458
+ )
3459
+ delete next.overscan;
3460
+ if (
3461
+ next.retryTimes !== undefined &&
3462
+ (typeof next.retryTimes !== 'number' ||
3463
+ !Number.isFinite(next.retryTimes) ||
3464
+ next.retryTimes < 0)
3465
+ )
3466
+ delete next.retryTimes;
3467
+ const options: Readonly<Record<string, readonly string[]>> = {
3468
+ contentFit: ['cover', 'contain', 'fill', 'center'],
3469
+ cachePolicy: ['memory-disk', 'memory', 'disk', 'none'],
3470
+ loadingStrategy: ['static', 'skeleton', 'none'],
3471
+ };
3472
+ for (const [key, allowed] of Object.entries(options))
3473
+ if (next[key] !== undefined && !allowed.includes(next[key] as string))
3474
+ delete next[key];
3475
+ for (const key of ['autoplay', 'optimizeTos'])
3476
+ if (next[key] !== undefined && typeof next[key] !== 'boolean')
3477
+ delete next[key];
3478
+ return next;
3479
+ }
3480
+
3481
+ const NESTED_DECORATION_FIELDS: Readonly<Record<string, readonly string[]>> = {
3482
+ webTable: ['columns', 'cells', 'testID', 'draggable', 'contextMenuActionKey'],
3483
+ columns: [
3484
+ 'key',
3485
+ 'text',
3486
+ 'textSegments',
3487
+ 'titleIcon',
3488
+ 'secondaryTitleIcon',
3489
+ 'secondaryLeadingText',
3490
+ 'secondaryText',
3491
+ 'secondaryTextSegments',
3492
+ 'weight',
3493
+ 'alignment',
3494
+ 'tone',
3495
+ 'secondaryTone',
3496
+ 'width',
3497
+ 'minWidth',
3498
+ 'flex',
3499
+ 'paddingStart',
3500
+ 'paddingEnd',
3501
+ ],
3502
+ cells: [
3503
+ 'key',
3504
+ 'kind',
3505
+ 'active',
3506
+ 'disabled',
3507
+ 'testID',
3508
+ 'hoverActionKey',
3509
+ 'actionKey',
3510
+ 'accessibilityLabel',
3511
+ 'leading',
3512
+ 'title',
3513
+ 'secondary',
3514
+ 'lineGap',
3515
+ 'secondaryBadges',
3516
+ 'hoverImages',
3517
+ 'hoverSecondary',
3518
+ 'hoverActionLabel',
3519
+ 'badges',
3520
+ 'primary',
3521
+ 'partGap',
3522
+ 'points',
3523
+ 'width',
3524
+ 'height',
3525
+ 'strokeColor',
3526
+ 'fillColor',
3527
+ ],
3528
+ badges: [
3529
+ 'key',
3530
+ 'text',
3531
+ 'tone',
3532
+ 'iconName',
3533
+ 'icon',
3534
+ 'textColor',
3535
+ 'backgroundColor',
3536
+ 'actionKey',
3537
+ 'accessibilityLabel',
3538
+ 'style',
3539
+ ],
3540
+ overlays: [
3541
+ 'position',
3542
+ 'size',
3543
+ 'width',
3544
+ 'height',
3545
+ 'padding',
3546
+ 'offset',
3547
+ 'offsetX',
3548
+ 'offsetY',
3549
+ 'image',
3550
+ 'fallbackIcon',
3551
+ 'name',
3552
+ 'text',
3553
+ 'fontWeight',
3554
+ 'tintColor',
3555
+ 'backgroundColor',
3556
+ ],
3557
+ primaryHelp: ['actionKey', 'presentation', 'underline'],
3558
+ valueHelp: ['actionKey', 'presentation', 'underline'],
3559
+ };
3560
+
3561
+ function sanitizeDecoration(value: unknown, field: string): unknown {
3562
+ if (value === undefined || value === null) return undefined;
3563
+ if (
3564
+ !Array.isArray(value) &&
3565
+ [
3566
+ 'image',
3567
+ 'networkImage',
3568
+ 'thumbnail',
3569
+ 'source',
3570
+ 'images',
3571
+ 'hoverImages',
3572
+ ].includes(field)
3573
+ )
3574
+ return sanitizeImage(value);
3575
+ if (
3576
+ [
3577
+ 'titleImage',
3578
+ 'titleIcon',
3579
+ 'secondaryTitleIcon',
3580
+ 'fallbackIcon',
3581
+ 'cornerIcon',
3582
+ 'media',
3583
+ ].includes(field) &&
3584
+ !isRecord(value)
3585
+ )
3586
+ return undefined;
3587
+ if (field === 'style' && typeof value !== 'string' && !isRecord(value))
3588
+ return undefined;
3589
+ if (
3590
+ ['badges', 'overlays'].includes(field) &&
3591
+ !Array.isArray(value) &&
3592
+ !isRecord(value)
3593
+ )
3594
+ return undefined;
3595
+ if (field === 'style' && typeof value === 'string')
3596
+ return value === 'subscript' ? value : undefined;
3597
+ if (Array.isArray(value)) {
3598
+ const items = value.map((item) => sanitizeDecoration(item, field));
3599
+ return field === 'hoverImages'
3600
+ ? items.map((item) => item ?? null)
3601
+ : items.filter((item) => item !== undefined);
3602
+ }
3603
+ if (!isRecord(value)) return value;
3604
+ let object = value;
3605
+ if (field === 'titleImage') {
3606
+ const image = sanitizeImage(value.image);
3607
+ if (!image) return undefined;
3608
+ const edge = Math.min(
3609
+ 40,
3610
+ Math.max(
3611
+ 1,
3612
+ Math.round(Math.min(image.width as number, image.height as number))
3613
+ )
3614
+ );
3615
+ object = {
3616
+ ...pickFields(value, ['image', 'accessibilityLabel', 'hoverActionKey']),
3617
+ image: { ...image, width: edge, height: edge },
3618
+ };
3619
+ } else if (
3620
+ ['titleIcon', 'secondaryTitleIcon', 'fallbackIcon', 'cornerIcon'].includes(
3621
+ field
3622
+ ) &&
3623
+ value.kind === undefined
3624
+ ) {
3625
+ if (typeof value.name !== 'string' || !value.name.trim()) return undefined;
3626
+ object = pickFields(value, ICON_FIELDS);
3627
+ } else if (['leading', 'visual', 'secondaryLeading'].includes(field)) {
3628
+ object = pickFields(value, VISUAL_FIELDS);
3629
+ } else if (field === 'media') {
3630
+ object = pickFields(value, ['source', 'probeOrder']);
3631
+ }
3632
+ if (
3633
+ field === 'trailing' ||
3634
+ (['leadingAction', 'titleIcon', 'valueIcon'].includes(field) &&
3635
+ object.kind !== undefined)
3636
+ ) {
3637
+ const fields = ACCESSORY_FIELDS[object.kind as string];
3638
+ if (fields) object = pickFields(object, fields);
3639
+ } else if (field === 'buttons')
3640
+ object = pickFields(object, [
3641
+ 'key',
3642
+ 'label',
3643
+ 'actionKey',
3644
+ 'disabled',
3645
+ 'loading',
3646
+ 'testID',
3647
+ 'accessibilityLabel',
3648
+ ]);
3649
+ else if (field === 'container')
3650
+ object = pickFields(object, [
3651
+ 'height',
3652
+ 'backgroundColor',
3653
+ 'opacity',
3654
+ 'cornerRadius',
3655
+ 'borderWidth',
3656
+ 'borderColor',
3657
+ 'contentVerticalAlignment',
3658
+ ]);
3659
+ else if (field === 'imageStyle')
3660
+ object = pickFields(object, [
3661
+ 'width',
3662
+ 'height',
3663
+ 'shape',
3664
+ 'cornerRadius',
3665
+ 'contentFit',
3666
+ ]);
3667
+ else if (field === 'style')
3668
+ object = pickFields(object, [
3669
+ ...TEXT_STYLE_FIELDS,
3670
+ 'container',
3671
+ ...new Set(Object.values(ROW_BOX_STYLE_KEYS_BY_TYPE).flat()),
3672
+ ...new Set(Object.values(TEXT_STYLE_KEYS_BY_ROW_TYPE).flat()),
3673
+ ...new Set(Object.values(EXTRA_STYLE_KEYS_BY_ROW_TYPE).flat()),
3674
+ 'height',
3675
+ ]);
3676
+ else if (
3677
+ [
3678
+ 'title',
3679
+ 'subtitle',
3680
+ 'tertiary',
3681
+ 'body',
3682
+ 'time',
3683
+ 'price',
3684
+ 'change',
3685
+ 'value',
3686
+ 'valueSecondary',
3687
+ 'columnSecondary',
3688
+ 'primaryAmount',
3689
+ 'secondaryAmount',
3690
+ 'description',
3691
+ 'status',
3692
+ 'trend',
3693
+ 'message',
3694
+ 'actionText',
3695
+ ].includes(field) &&
3696
+ !('text' in object)
3697
+ ) {
3698
+ object = pickFields(object, TEXT_STYLE_FIELDS);
3699
+ }
3700
+ if (NESTED_DECORATION_FIELDS[field])
3701
+ object = pickFields(object, NESTED_DECORATION_FIELDS[field]);
3702
+ if (
3703
+ [
3704
+ 'textSegments',
3705
+ 'primaryTextSegments',
3706
+ 'secondaryTextSegments',
3707
+ 'priceSegments',
3708
+ 'segments',
3709
+ ].includes(field)
3710
+ )
3711
+ object = pickFields(object, ['text', 'style']);
3712
+ if (field === 'subtitleSegments')
3713
+ object = pickFields(object, [
3714
+ 'text',
3715
+ 'style',
3716
+ 'textSegments',
3717
+ 'tone',
3718
+ 'separatorBefore',
3719
+ ]);
3720
+ const styleObject =
3721
+ ['style', 'imageStyle', 'container'].includes(field) ||
3722
+ TEXT_STYLE_FIELDS.some((key) => key in object);
3723
+ const next: Record<string, unknown> = {};
3724
+ for (const [key, item] of Object.entries(object)) {
3725
+ if (item === undefined || item === null) continue;
3726
+ if (
3727
+ (/color$/i.test(key) || /background$/i.test(key)) &&
3728
+ (typeof item !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(item))
3729
+ )
3730
+ continue;
3731
+ if (
3732
+ /TextSegments$/.test(key) ||
3733
+ [
3734
+ 'textSegments',
3735
+ 'priceSegments',
3736
+ 'subtitleSegments',
3737
+ 'segments',
3738
+ ].includes(key)
3739
+ ) {
3740
+ if (
3741
+ !Array.isArray(item) ||
3742
+ item.some(
3743
+ (segment) => !isRecord(segment) || typeof segment.text !== 'string'
3744
+ )
3745
+ )
3746
+ continue;
3747
+ }
3748
+ if (
3749
+ styleObject &&
3750
+ PROTOCOL_NUMBER_FIELDS.has(key) &&
3751
+ typeof item !== 'number'
3752
+ )
3753
+ continue;
3754
+ if (
3755
+ key === 'token' &&
3756
+ (typeof item !== 'string' || !Object.hasOwn(TYPOGRAPHY_TOKENS, item))
3757
+ )
3758
+ continue;
3759
+ if (
3760
+ key === 'fontWeight' &&
3761
+ !['regular', 'medium', 'semibold', 'bold'].includes(item as string)
3762
+ )
3763
+ continue;
3764
+ if (
3765
+ [
3766
+ 'disabled',
3767
+ 'loading',
3768
+ 'checked',
3769
+ 'selected',
3770
+ 'separator',
3771
+ 'hideLeading',
3772
+ 'pressDisabled',
3773
+ 'draggable',
3774
+ 'active',
3775
+ 'autoplay',
3776
+ ].includes(key) &&
3777
+ typeof item !== 'boolean'
3778
+ )
3779
+ continue;
3780
+ if (key === 'primaryFontWeight' && item !== 'medium') continue;
3781
+ if (key === 'buttonStyle' && item !== 'tertiary') continue;
3782
+ if (key === 'hoverActionKey' && (typeof item !== 'string' || !item.trim()))
3783
+ continue;
3784
+ if (key === 'accessibilityLabel' && typeof item !== 'string') continue;
3785
+ if (
3786
+ (field === 'style' || PROTOCOL_NUMBER_FIELDS.has(key)) &&
3787
+ typeof item !== 'object' &&
3788
+ typeof item === 'number' &&
3789
+ (!Number.isFinite(item) ||
3790
+ (item < 0 && !['offsetX', 'offsetY'].includes(key)))
3791
+ )
3792
+ continue;
3793
+ if (
3794
+ field === 'style' &&
3795
+ PROTOCOL_NUMBER_FIELDS.has(key) &&
3796
+ typeof item !== 'number'
3797
+ )
3798
+ continue;
3799
+ if (
3800
+ key === 'leadingContentMaxWidthRatio' &&
3801
+ (typeof item !== 'number' || item <= 0 || item > 1)
3802
+ )
3803
+ continue;
3804
+ const normalized = sanitizeDecoration(
3805
+ item,
3806
+ field === 'style' && key === 'image' ? 'imageStyle' : key
3807
+ );
3808
+ if (normalized !== undefined) next[key] = normalized;
3809
+ }
3810
+ if (field === 'titleImage') {
3811
+ // The nested image was already normalized with title-specific geometry.
3812
+ if (!next.image) return undefined;
3813
+ }
3814
+ if (field === 'media' && (!next.source || !Array.isArray(next.probeOrder)))
3815
+ return undefined;
3816
+ if (['leading', 'visual', 'secondaryLeading'].includes(field)) {
3817
+ if (next.kind === 'image' && !next.image)
3818
+ return {
3819
+ kind: 'token',
3820
+ ...pickFields(next, [
3821
+ 'fallbackIcon',
3822
+ 'fallbackText',
3823
+ 'fallbackTextColor',
3824
+ ]),
3825
+ };
3826
+ if (
3827
+ next.kind === 'stackedImages' &&
3828
+ (!Array.isArray(next.images) || next.images.length < 2)
3829
+ )
3830
+ return { kind: 'token' };
3831
+ if (
3832
+ next.kind === 'icon' &&
3833
+ (typeof next.name !== 'string' || !next.name.trim())
3834
+ )
3835
+ return { kind: 'token' };
3836
+ if (
3837
+ ![
3838
+ 'token',
3839
+ 'account',
3840
+ 'wallet',
3841
+ 'network',
3842
+ 'image',
3843
+ 'icon',
3844
+ 'stackedImages',
3845
+ ].includes(next.kind as string)
3846
+ )
3847
+ return { kind: 'token' };
3848
+ }
3849
+ if (
3850
+ field === 'overlays' &&
3851
+ (!['topLeft', 'bottomRight'].includes(next.position as string) ||
3852
+ (!next.image && !next.name && !next.text))
3853
+ )
3854
+ return undefined;
3855
+ if (
3856
+ field === 'trailing' &&
3857
+ next.kind === 'icon' &&
3858
+ !('actionKey' in value) &&
3859
+ (typeof next.name !== 'string' || !next.name.trim())
3860
+ )
3861
+ return undefined;
3862
+ if (
3863
+ field === 'trailing' &&
3864
+ ![
3865
+ 'value',
3866
+ 'valuePair',
3867
+ 'button',
3868
+ 'checkbox',
3869
+ 'radio',
3870
+ 'switch',
3871
+ 'chevron',
3872
+ 'menu',
3873
+ 'drag',
3874
+ 'icon',
3875
+ 'spinner',
3876
+ 'progress',
3877
+ ].includes(next.kind as string) &&
3878
+ !('actionKey' in value)
3879
+ )
3880
+ return undefined;
3881
+ if (
3882
+ field === 'badges' &&
3883
+ (typeof next.key !== 'string' ||
3884
+ (!next.text && !next.iconName && !next.icon))
3885
+ )
3886
+ return undefined;
3887
+ if (next.kind === 'sparkline') {
3888
+ const points = Array.isArray(value.points)
3889
+ ? value.points
3890
+ .filter(
3891
+ (point) => typeof point === 'number' && Number.isFinite(point)
3892
+ )
3893
+ .slice(0, 256)
3894
+ : [];
3895
+ // Preserve the table's column identity even when its optional drawing fails.
3896
+ return points.length < 2
3897
+ ? { key: next.key, kind: 'text', primary: [] }
3898
+ : { ...next, points };
3899
+ }
3900
+ return next;
3901
+ }
3902
+
3903
+ function sanitizeMarketMetrics(value: unknown): unknown {
3904
+ if (!Array.isArray(value)) return value;
3905
+ return value.map((metric) => {
3906
+ const next = pickFields(
3907
+ metric as Record<string, unknown>,
3908
+ MARKET_METRIC_FIELDS
3909
+ );
3910
+ for (const field of ['textSegments', 'secondaryTextSegments'] as const) {
3911
+ if (next[field] !== undefined)
3912
+ next[field] = sanitizeDecoration(next[field], field);
3913
+ }
3914
+ return next;
3915
+ });
3916
+ }
3917
+
3918
+ function sanitizeRowForProduction(row: RowModel): RowModel {
3919
+ const object = protocolObject(row, 'row');
3920
+ const fields = ROW_FIELDS[row.type];
3921
+ if (!fields) return row;
3922
+ const next = pickFields(object, fields);
3923
+ for (const [field, value] of Object.entries(next)) {
3924
+ if (
3925
+ (/color$/i.test(field) || /background$/i.test(field)) &&
3926
+ (typeof value !== 'string' ||
3927
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value))
3928
+ ) {
3929
+ delete next[field];
3930
+ continue;
3931
+ }
3932
+ if (field === 'parent' && isRecord(value))
3933
+ next[field] = sanitizeRowForProduction(value as unknown as RowModel);
3934
+ else if (field === 'children' && Array.isArray(value))
3935
+ next[field] = value.map((child) =>
3936
+ sanitizeRowForProduction(child as RowModel)
3937
+ );
3938
+ else {
3939
+ const normalized =
3940
+ row.type === 'market' && field === 'metrics'
3941
+ ? sanitizeMarketMetrics(value)
3942
+ : sanitizeDecoration(value, field);
3943
+ if (normalized === undefined) delete next[field];
3944
+ else next[field] = normalized;
3945
+ }
3946
+ }
3947
+ if (isRecord(next.style))
3948
+ next.style = pickFields(next.style, [
3949
+ 'container',
3950
+ ...ROW_BOX_STYLE_KEYS_BY_TYPE[row.type],
3951
+ ...(TEXT_STYLE_KEYS_BY_ROW_TYPE[row.type] ?? []),
3952
+ ...(EXTRA_STYLE_KEYS_BY_ROW_TYPE[row.type] ?? []),
3953
+ ]);
3954
+ return sameJsonValue(row, next) ? row : (next as unknown as RowModel);
3955
+ }
3956
+
3957
+ /** Empty images and optional nulls share one meaning before strict assertions. */
2700
3958
  function normalizeEmptyImages(value: unknown, field = ''): unknown {
2701
- if (!value || typeof value !== 'object') return value;
3959
+ if (value === null || value === undefined || typeof value !== 'object')
3960
+ return value;
2702
3961
  if (Array.isArray(value)) {
2703
- const next = value.map((item) => normalizeEmptyImages(item));
2704
- const filtered =
2705
- field === 'images'
2706
- ? next.filter((item) => item !== undefined)
2707
- : next.map((item) => (item === undefined ? null : item));
2708
- return filtered.length === value.length &&
2709
- filtered.every((item, index) => item === value[index])
3962
+ const next = value.map((item) => normalizeEmptyImages(item, field));
3963
+ return next.every((item, index) => item === value[index])
2710
3964
  ? value
2711
- : filtered;
3965
+ : next.filter((item) => item !== undefined);
2712
3966
  }
2713
3967
  const object = value as Record<string, unknown>;
2714
3968
  if (
@@ -2719,30 +3973,154 @@ function normalizeEmptyImages(value: unknown, field = ''): unknown {
2719
3973
  )
2720
3974
  return undefined;
2721
3975
  let changed = false;
2722
- const next = { ...object };
2723
- Object.entries(object).forEach(([key, item]) => {
2724
- const normalized = normalizeEmptyImages(item, key);
2725
- if (normalized !== item) {
2726
- // Omitted JSON patch fields must also be absent from the JS merge.
2727
- if (field === 'changes' && normalized === undefined) delete next[key];
2728
- else next[key] = normalized;
3976
+ const next: Record<string, unknown> = {};
3977
+ for (const [key, item] of Object.entries(object)) {
3978
+ const optional =
3979
+ object.type &&
3980
+ ![
3981
+ 'key',
3982
+ 'type',
3983
+ ...(REQUIRED_ROW_FIELDS[object.type as string] ?? []),
3984
+ ].includes(key);
3985
+ if (
3986
+ item === undefined ||
3987
+ (item === null &&
3988
+ optional &&
3989
+ !(object.type === 'market' && key === 'metrics')) ||
3990
+ (['priceSegments', 'subtitleSegments'].includes(key) &&
3991
+ Array.isArray(item) &&
3992
+ item.length === 0)
3993
+ ) {
2729
3994
  changed = true;
3995
+ continue;
2730
3996
  }
2731
- });
2732
- if (field === 'media' && next.source === undefined) return undefined;
3997
+ const normalized =
3998
+ field === 'headers' ? item : normalizeEmptyImages(item, key);
3999
+ if (normalized !== undefined) next[key] = normalized;
4000
+ if (normalized !== item) changed = true;
4001
+ }
4002
+ if (
4003
+ (field === 'media' &&
4004
+ object.source !== undefined &&
4005
+ next.source === undefined) ||
4006
+ (field === 'titleImage' &&
4007
+ object.image !== undefined &&
4008
+ next.image === undefined)
4009
+ )
4010
+ return undefined;
4011
+ if (
4012
+ ['leading', 'visual', 'secondaryLeading'].includes(field) &&
4013
+ next.kind === 'image' &&
4014
+ !next.image
4015
+ )
4016
+ return { kind: 'token' };
4017
+ if (field === 'overlays' && object.image !== undefined && !next.image)
4018
+ return undefined;
2733
4019
  return changed ? next : value;
2734
4020
  }
2735
4021
 
4022
+ function normalizeSnapshotForProduction(
4023
+ snapshot: NativeListSnapshot
4024
+ ): NativeListSnapshot {
4025
+ if (!Array.isArray(snapshot.rows)) return snapshot;
4026
+ let rows = snapshot.rows.map(sanitizeRowForProduction);
4027
+ rows = rows.map((row, index) => {
4028
+ if (!row.groupId) return row;
4029
+ const previous = rows[index - 1]?.groupId === row.groupId;
4030
+ const following = rows[index + 1]?.groupId === row.groupId;
4031
+ return {
4032
+ ...row,
4033
+ groupPosition: previous
4034
+ ? following
4035
+ ? 'middle'
4036
+ : 'last'
4037
+ : following
4038
+ ? 'first'
4039
+ : 'single',
4040
+ };
4041
+ });
4042
+ const next = {
4043
+ ...snapshot,
4044
+ rows,
4045
+ ...(snapshot.emptyState
4046
+ ? {
4047
+ emptyState: sanitizeRowForProduction(
4048
+ snapshot.emptyState
4049
+ ) as NativeListSnapshot['emptyState'],
4050
+ }
4051
+ : {}),
4052
+ ...(snapshot.fixedFooter
4053
+ ? {
4054
+ fixedFooter: sanitizeRowForProduction(
4055
+ snapshot.fixedFooter
4056
+ ) as NativeListSnapshot['fixedFooter'],
4057
+ }
4058
+ : {}),
4059
+ };
4060
+ if (snapshot.theme)
4061
+ next.theme = sanitizeDecoration(
4062
+ snapshot.theme,
4063
+ 'theme'
4064
+ ) as NativeListSnapshot['theme'];
4065
+ if (snapshot.listStyle)
4066
+ next.listStyle = sanitizeDecoration(
4067
+ snapshot.listStyle,
4068
+ 'style'
4069
+ ) as NativeListSnapshot['listStyle'];
4070
+ if (snapshot.selection && Array.isArray(snapshot.selection.selectedKeys)) {
4071
+ const selectable = new Set(
4072
+ rows
4073
+ .filter(
4074
+ (row) =>
4075
+ !row.disabled &&
4076
+ ![
4077
+ 'sectionHeader',
4078
+ 'action',
4079
+ 'system',
4080
+ 'buttonGroup',
4081
+ 'market',
4082
+ 'walletGroup',
4083
+ ].includes(row.type)
4084
+ )
4085
+ .map((row) => row.key)
4086
+ );
4087
+ const selectedKeys = [
4088
+ ...new Set(
4089
+ snapshot.selection.selectedKeys.filter((key) => selectable.has(key))
4090
+ ),
4091
+ ];
4092
+ next.selection = {
4093
+ ...snapshot.selection,
4094
+ selectedKeys:
4095
+ snapshot.selection.mode === 'none'
4096
+ ? []
4097
+ : snapshot.selection.mode === 'single'
4098
+ ? selectedKeys.slice(0, 1)
4099
+ : selectedKeys,
4100
+ };
4101
+ }
4102
+ return sameJsonValue(snapshot, next) ? snapshot : next;
4103
+ }
4104
+
2736
4105
  export function validateSnapshot(
2737
4106
  snapshot: NativeListSnapshot
2738
4107
  ): NativeListSnapshot {
2739
- assertPlainSerializable(snapshot, 'snapshot', new Set<object>());
2740
- if (isDevelopment()) assertSnapshotContract(snapshot);
2741
- const normalized = isDevelopment()
2742
- ? snapshot
2743
- : (normalizeEmptyImages(snapshot) as NativeListSnapshot);
2744
- assertSnapshotProtocol(normalized);
2745
- return normalizeSnapshotStyles(normalized);
4108
+ assertPlainSerializable(snapshot, 'snapshot', new Set<object>(), false);
4109
+ protocolObject(snapshot, 'snapshot');
4110
+ const normalized = normalizeEmptyImages(snapshot) as NativeListSnapshot;
4111
+ if (Array.isArray(normalized.rows)) {
4112
+ normalized.rows.forEach((row, index) => {
4113
+ if (row.type === 'market')
4114
+ assertMarketMetrics(row.metrics, `snapshot.rows[${index}].metrics`);
4115
+ });
4116
+ }
4117
+ const canonical = isDevelopment()
4118
+ ? normalized
4119
+ : normalizeSnapshotForProduction(normalized);
4120
+ assertPlainSerializable(canonical, 'snapshot', new Set<object>());
4121
+ if (isDevelopment()) assertSnapshotContract(canonical);
4122
+ assertSnapshotProtocol(canonical);
4123
+ return normalizeSnapshotStyles(canonical);
2746
4124
  }
2747
4125
 
2748
4126
  const ownedNativeSnapshots = new WeakMap<
@@ -2838,10 +4216,23 @@ function normalizeSnapshotStyles(
2838
4216
  ) {
2839
4217
  return snapshot;
2840
4218
  }
2841
- return { ...snapshot, rows, emptyState, fixedFooter };
4219
+ return {
4220
+ ...snapshot,
4221
+ rows,
4222
+ ...(emptyState !== undefined ? { emptyState } : {}),
4223
+ ...(fixedFooter !== undefined ? { fixedFooter } : {}),
4224
+ };
2842
4225
  }
2843
4226
 
2844
- function assertPatchChanges(patch: RowPatch, index: number): void {
4227
+ type PatchValues<Patch = RowPatch> = Patch extends RowPatch
4228
+ ? Omit<Patch, 'changes'> & {
4229
+ changes: {
4230
+ [Key in keyof Patch['changes']]: Exclude<Patch['changes'][Key], null>;
4231
+ };
4232
+ }
4233
+ : never;
4234
+
4235
+ function assertPatchChanges(patch: PatchValues, index: number): void {
2845
4236
  const path = `patches[${index}].changes`;
2846
4237
  const patchedStyle = (patch.changes as { style?: unknown }).style;
2847
4238
  if (patchedStyle !== undefined) {
@@ -3135,36 +4526,167 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
3135
4526
  }
3136
4527
  }
3137
4528
 
4529
+ function normalizePatch(patch: RowPatch, index: number): RowPatch | undefined {
4530
+ const path = `patches[${index}]`;
4531
+ protocolObject(patch, path);
4532
+ protocolKey(patch.key, `${path}.key`);
4533
+ if (isDevelopment()) assertKey(patch.key, `${path}.key`);
4534
+ assertRowType(patch.type, path);
4535
+ const raw = protocolObject(patch.changes, `${path}.changes`);
4536
+ assertPlainSerializable(raw, `${path}.changes`, new Set<object>(), false);
4537
+ const fields = PATCH_FIELDS[patch.type];
4538
+ const changes: Record<string, unknown> = {};
4539
+ for (const [field, value] of Object.entries(raw)) {
4540
+ if (value === undefined) continue;
4541
+ if (!fields?.includes(field)) {
4542
+ if (isDevelopment())
4543
+ fail(`${path}.changes.${field}`, 'unsupported patch field');
4544
+ continue;
4545
+ }
4546
+ if (value === null) {
4547
+ if (patch.type === 'market' && field === 'metrics')
4548
+ fail(
4549
+ `${path}.changes.metrics`,
4550
+ 'use a full snapshot to remove metrics'
4551
+ );
4552
+ if (
4553
+ REQUIRED_ROW_FIELDS[patch.type].includes(field) ||
4554
+ (patch.type === 'system' && field === 'message')
4555
+ ) {
4556
+ // The concrete system variant is checked after merging with its baseline.
4557
+ if (patch.type !== 'system')
4558
+ fail(`${path}.changes.${field}`, 'required field cannot be cleared');
4559
+ }
4560
+ changes[field] = null;
4561
+ continue;
4562
+ }
4563
+ if (patch.type === 'market' && field === 'metrics')
4564
+ assertMarketMetrics(
4565
+ value as MarketRow['metrics'],
4566
+ `${path}.changes.metrics`
4567
+ );
4568
+ if (
4569
+ ['priceSegments', 'subtitleSegments'].includes(field) &&
4570
+ Array.isArray(value) &&
4571
+ value.length === 0
4572
+ ) {
4573
+ changes[field] = null;
4574
+ continue;
4575
+ }
4576
+ const normalized = normalizeEmptyImages(value, field);
4577
+ if (normalized === undefined) {
4578
+ if (!REQUIRED_ROW_FIELDS[patch.type].includes(field))
4579
+ changes[field] = null;
4580
+ continue;
4581
+ }
4582
+ const canonical = isDevelopment()
4583
+ ? normalized
4584
+ : patch.type === 'market' && field === 'metrics'
4585
+ ? sanitizeMarketMetrics(normalized)
4586
+ : sanitizeDecoration(normalized, field);
4587
+ if (canonical !== undefined) changes[field] = canonical;
4588
+ else if (field === 'titleImage') changes[field] = null;
4589
+ }
4590
+ if (
4591
+ patch.type === 'market' &&
4592
+ Array.isArray(changes.priceSegments) &&
4593
+ changes.priceSegments.length > 0 &&
4594
+ (typeof changes.price !== 'string' || !changes.price.trim())
4595
+ )
4596
+ fail(`${path}.changes.price`, 'is required when priceSegments is updated');
4597
+ if (!isDevelopment()) {
4598
+ const sanitized = sanitizeRowForProduction({
4599
+ type: patch.type,
4600
+ ...changes,
4601
+ } as unknown as RowModel) as unknown as Record<string, unknown>;
4602
+ for (const [field, value] of Object.entries(changes)) {
4603
+ if (value === null) continue;
4604
+ if (sanitized[field] === undefined) delete changes[field];
4605
+ else changes[field] = sanitized[field];
4606
+ }
4607
+ }
4608
+ const values = Object.fromEntries(
4609
+ Object.entries(changes).filter(([, value]) => value !== null)
4610
+ );
4611
+ if (patch.type === 'market' && 'metrics' in changes)
4612
+ assertMarketMetrics(
4613
+ changes.metrics as MarketRow['metrics'],
4614
+ `${path}.changes.metrics`
4615
+ );
4616
+ assertPlainSerializable(values, `${path}.changes`, new Set<object>());
4617
+ assertProtocolFields(values, `${path}.changes`);
4618
+ if (isDevelopment())
4619
+ assertPatchChanges({ ...patch, changes: values } as PatchValues, index);
4620
+ const normalizedPatch = {
4621
+ type: patch.type,
4622
+ key: patch.key,
4623
+ changes,
4624
+ } as RowPatch;
4625
+ return Object.keys(changes).length > 0
4626
+ ? normalizePatchStyles([normalizedPatch])[0]
4627
+ : undefined;
4628
+ }
4629
+
4630
+ function reportRejectedPatch(index: number): void {
4631
+ console.warn(`NativeList rejected invalid patch unit at patches[${index}]`);
4632
+ }
4633
+
3138
4634
  export function validatePatches(
3139
4635
  patches: readonly RowPatch[]
3140
4636
  ): readonly RowPatch[] {
3141
- assertPlainSerializable(patches, 'patches', new Set<object>());
3142
4637
  if (!Array.isArray(patches)) fail('patches', 'must be an array');
3143
- const keys = new Set<string>();
3144
- for (const [index, patch] of patches.entries()) {
3145
- protocolObject(patch, `patches[${index}]`);
3146
- protocolKey(patch.key, `patches[${index}].key`);
3147
- if (keys.has(patch.key))
3148
- fail(`patches[${index}].key`, `duplicate key "${patch.key}"`);
3149
- keys.add(patch.key);
3150
- protocolObject(patch.changes, `patches[${index}].changes`);
3151
- assertRowType(patch.type, `patches[${index}]`);
3152
- assertProtocolFields(patch.changes, `patches[${index}].changes`);
3153
- if (patch.type === 'identity')
3154
- assertIdentityExtras(patch.changes, `patches[${index}].changes`);
3155
- if (!isDevelopment()) continue;
3156
- assertKey(patch.key, `patches[${index}].key`);
3157
- if (Object.keys(patch.changes).length === 0) {
3158
- fail(`patches[${index}].changes`, 'must contain at least one field');
4638
+ const units = new Map<string, { patch: RowPatch; index: number }>();
4639
+ const rejectedKeys = new Set<string>();
4640
+ const reject = (key: string, index: number, error: unknown) => {
4641
+ if (isDevelopment()) throw error;
4642
+ rejectedKeys.add(key);
4643
+ reportRejectedPatch(index);
4644
+ };
4645
+ patches.forEach((input, index) => {
4646
+ const key =
4647
+ isRecord(input) && typeof input.key === 'string' ? input.key : '';
4648
+ try {
4649
+ protocolObject(input, `patches[${index}]`);
4650
+ protocolKey(input.key, `patches[${index}].key`);
4651
+ assertRowType(input.type, `patches[${index}]`);
4652
+ const changes = capturePlainData(
4653
+ protocolObject(input.changes, `patches[${index}].changes`)
4654
+ );
4655
+ assertPlainSerializable(
4656
+ changes,
4657
+ `patches[${index}].changes`,
4658
+ new Set<object>(),
4659
+ false
4660
+ );
4661
+ const previous = units.get(key);
4662
+ if (previous && previous.patch.type !== input.type)
4663
+ fail(`patches[${index}].type`, 'conflicting row types');
4664
+ const defined = Object.fromEntries(
4665
+ Object.entries(changes).filter(([, value]) => value !== undefined)
4666
+ );
4667
+ units.set(key, {
4668
+ index,
4669
+ patch: {
4670
+ key,
4671
+ type: input.type,
4672
+ changes: { ...previous?.patch.changes, ...defined },
4673
+ } as RowPatch,
4674
+ });
4675
+ } catch (error) {
4676
+ reject(key, index, error);
4677
+ }
4678
+ });
4679
+ const accepted: RowPatch[] = [];
4680
+ for (const [key, unit] of units) {
4681
+ if (rejectedKeys.has(key)) continue;
4682
+ try {
4683
+ const patch = normalizePatch(unit.patch, unit.index);
4684
+ if (patch) accepted.push(patch);
4685
+ } catch (error) {
4686
+ reject(key, unit.index, error);
3159
4687
  }
3160
- assertPatchChanges(patch, index);
3161
4688
  }
3162
- const normalized = isDevelopment()
3163
- ? patches
3164
- : (normalizeEmptyImages(patches) as readonly RowPatch[]);
3165
- return normalizePatchStyles(
3166
- normalized.filter((patch) => Object.keys(patch.changes).length > 0)
3167
- );
4689
+ return accepted;
3168
4690
  }
3169
4691
 
3170
4692
  /** Patches reach the native side without passing through a snapshot. */
@@ -3296,50 +4818,65 @@ export function planNativeListPatches(
3296
4818
  return patches.length === 0 ? EMPTY_ROW_PATCHES : patches;
3297
4819
  }
3298
4820
 
3299
- export function applyRowPatches(
3300
- snapshot: NativeListSnapshot,
3301
- patches: readonly RowPatch[]
3302
- ): NativeListSnapshot {
3303
- const normalizedPatches = validatePatches(patches);
3304
- const patchByKey = new Map(
3305
- normalizedPatches.map((patch) => [patch.key, patch])
3306
- );
3307
- const knownKeys = new Set(snapshot.rows.map((row) => row.key));
3308
- normalizedPatches.forEach((patch) => {
3309
- if (!knownKeys.has(patch.key))
3310
- fail('patches', `unknown row key "${patch.key}"`);
3311
- });
3312
- const rows = snapshot.rows.map((row): RowModel => {
3313
- const patch = patchByKey.get(row.key);
3314
- if (!patch) return row;
3315
- if (patch.type !== row.type) {
3316
- fail('patches', `row "${row.key}" is ${row.type}, not ${patch.type}`);
3317
- }
4821
+ function mergeAndValidateSingleRow(
4822
+ previous: RowModel,
4823
+ patch: RowPatch,
4824
+ index: number
4825
+ ): { row: RowModel; patch: RowPatch } {
4826
+ if (previous.key !== patch.key)
4827
+ fail(`patches[${index}].key`, 'does not match row identity');
4828
+ if (previous.type !== patch.type)
4829
+ fail(`patches[${index}].type`, 'does not match row type');
4830
+ const changes = { ...patch.changes } as Record<string, unknown>;
4831
+ if (previous.type === 'market') {
4832
+ if (
4833
+ typeof changes.price === 'string' &&
4834
+ !('priceSegments' in changes) &&
4835
+ previous.priceSegments !== undefined
4836
+ )
4837
+ changes.priceSegments = null;
3318
4838
  if (
3319
- row.type === 'market' &&
3320
- row.webTable &&
3321
- patch.type === 'market' &&
3322
- (patch.changes.price !== undefined ||
3323
- patch.changes.priceSegments !== undefined ||
3324
- patch.changes.change !== undefined) &&
3325
- patch.changes.webTable === undefined
4839
+ (previous.webTable !== undefined || 'webTable' in changes) &&
4840
+ ['price', 'priceSegments', 'change'].some((field) => field in changes) &&
4841
+ changes.webTable === undefined
3326
4842
  )
3327
4843
  fail(
3328
- 'patches',
3329
- 'table quote changes must include the visible table cells'
4844
+ `patches[${index}].changes.webTable`,
4845
+ 'table quote changes require visible table cells'
3330
4846
  );
3331
- return {
3332
- ...row,
3333
- ...patch.changes,
3334
- key: row.key,
3335
- type: row.type,
3336
- } as RowModel;
3337
- });
3338
- return validateSnapshot({ ...snapshot, rows });
4847
+ }
4848
+ if (previous.type === 'identity' || previous.type === 'market') {
4849
+ if (
4850
+ typeof changes.subtitle === 'string' &&
4851
+ !('subtitleSegments' in changes) &&
4852
+ previous.subtitleSegments !== undefined
4853
+ )
4854
+ changes.subtitleSegments = null;
4855
+ if (
4856
+ Array.isArray(changes.subtitleSegments) &&
4857
+ changes.subtitleSegments.length > 0 &&
4858
+ !('subtitle' in changes) &&
4859
+ previous.subtitle !== undefined
4860
+ )
4861
+ changes.subtitle = null;
4862
+ }
4863
+ const merged = { ...previous } as unknown as Record<string, unknown>;
4864
+ for (const [field, value] of Object.entries(changes)) {
4865
+ if (value === null) delete merged[field];
4866
+ else if (value !== undefined) merged[field] = value;
4867
+ }
4868
+ const next = normalizeRowStyles(merged as unknown as RowModel);
4869
+ assertPlainSerializable(next, `rows[${index}]`, new Set<object>());
4870
+ if (isDevelopment()) assertRow(next, index);
4871
+ assertRowProtocol(next, `rows[${index}]`);
4872
+ return {
4873
+ row: next,
4874
+ patch: { type: patch.type, key: patch.key, changes } as RowPatch,
4875
+ };
3339
4876
  }
3340
4877
 
3341
- /** Native wrapper only: preserve full public validation for unsupported patches. */
3342
- export function applyOwnedNativePatches(
4878
+ /** One canonical batch owns both accepted rows and the native wire payload. */
4879
+ export function applyValidatedRowPatches(
3343
4880
  snapshot: NativeListSnapshot,
3344
4881
  patches: readonly RowPatch[]
3345
4882
  ): {
@@ -3347,74 +4884,127 @@ export function applyOwnedNativePatches(
3347
4884
  snapshot: NativeListSnapshot;
3348
4885
  json: string;
3349
4886
  } {
3350
- const acceptedPatches = deepFreeze(
3351
- validatePatches(capturePlainData(patches))
3352
- );
3353
- const rowIndexes = ownedNativeSnapshots.get(snapshot);
3354
- const canPatchRows =
3355
- rowIndexes !== undefined &&
3356
- acceptedPatches.every((patch) => {
3357
- const index = rowIndexes.get(patch.key);
3358
- if (index === undefined || snapshot.rows[index].type !== patch.type)
3359
- return false;
3360
- const allowed =
3361
- patch.type === 'identity'
3362
- ? ['subtitle', 'subtitleSegments', 'trailing']
3363
- : patch.type === 'dataRow'
3364
- ? ['columns', 'trailing']
3365
- : undefined;
3366
- return (
3367
- allowed !== undefined &&
3368
- Object.entries(patch.changes).every(
3369
- ([key, value]) =>
3370
- allowed.includes(key) &&
3371
- (value !== undefined ||
3372
- (snapshot.rows[index] as unknown as Record<string, unknown>)[
3373
- key
3374
- ] === undefined)
3375
- )
4887
+ if (!Array.isArray(patches)) fail('patches', 'must be an array');
4888
+ const owned = ownedNativeSnapshots.has(snapshot);
4889
+ const rowIndexes =
4890
+ ownedNativeSnapshots.get(snapshot) ??
4891
+ validatedRowIndexes.get(snapshot) ??
4892
+ new Map(snapshot.rows.map((row, index) => [row.key, index]));
4893
+ validatedRowIndexes.set(snapshot, rowIndexes);
4894
+ const units = new Map<
4895
+ string,
4896
+ { index: number; changes: Record<string, unknown>; type: RowPatch['type'] }
4897
+ >();
4898
+ const rejected = new Set<string>();
4899
+ const rejectedGroups = new Set<string>();
4900
+ const reject = (key: string, index: number, error: unknown) => {
4901
+ if (isDevelopment()) throw error;
4902
+ rejected.add(key);
4903
+ const rowIndex = rowIndexes.get(key);
4904
+ const group =
4905
+ rowIndex === undefined ? undefined : snapshot.rows[rowIndex].groupId;
4906
+ if (group) rejectedGroups.add(group);
4907
+ reportRejectedPatch(index);
4908
+ };
4909
+ patches.forEach((input, index) => {
4910
+ const key =
4911
+ isRecord(input) && typeof input.key === 'string' ? input.key : '';
4912
+ try {
4913
+ protocolObject(input, `patches[${index}]`);
4914
+ protocolKey(input.key, `patches[${index}].key`);
4915
+ const rowIndex = rowIndexes.get(input.key);
4916
+ if (rowIndex === undefined)
4917
+ fail(`patches[${index}].key`, 'unknown row identity');
4918
+ if (snapshot.rows[rowIndex].type !== input.type)
4919
+ fail(`patches[${index}].type`, 'does not match row type');
4920
+ const changes = protocolObject(
4921
+ input.changes,
4922
+ `patches[${index}].changes`
3376
4923
  );
3377
- });
3378
- if (!canPatchRows) {
3379
- const baseline = rowIndexes ? snapshot : capturePlainData(snapshot);
3380
- return {
3381
- patches: acceptedPatches,
3382
- snapshot: ownValidatedNativeSnapshot(
3383
- applyRowPatches(baseline, acceptedPatches)
3384
- ),
3385
- json: JSON.stringify(acceptedPatches),
3386
- };
4924
+ const captured = capturePlainData(changes);
4925
+ assertPlainSerializable(
4926
+ captured,
4927
+ `patches[${index}].changes`,
4928
+ new Set<object>(),
4929
+ false
4930
+ );
4931
+ const previous = units.get(input.key);
4932
+ // Undefined is omitted at every merge, so it cannot overwrite an earlier change.
4933
+ const defined = Object.fromEntries(
4934
+ Object.entries(captured).filter(([, value]) => value !== undefined)
4935
+ );
4936
+ units.set(input.key, {
4937
+ index,
4938
+ type: input.type,
4939
+ changes: { ...previous?.changes, ...defined },
4940
+ });
4941
+ } catch (error) {
4942
+ reject(key, index, error);
4943
+ }
4944
+ });
4945
+ const pending = new Map<string, { row: RowModel; patch: RowPatch }>();
4946
+ for (const [key, unit] of units) {
4947
+ if (rejected.has(key)) continue;
4948
+ try {
4949
+ const patch = normalizePatch(
4950
+ { key, type: unit.type, changes: unit.changes } as RowPatch,
4951
+ unit.index
4952
+ );
4953
+ if (!patch) continue;
4954
+ const merged = mergeAndValidateSingleRow(
4955
+ snapshot.rows[rowIndexes.get(key)!],
4956
+ patch,
4957
+ rowIndexes.get(key)!
4958
+ );
4959
+ if (merged.row.disabled && snapshot.selection?.selectedKeys.includes(key))
4960
+ fail(`patches[${unit.index}]`, 'cannot disable a selected row');
4961
+ pending.set(key, merged);
4962
+ } catch (error) {
4963
+ reject(key, unit.index, error);
4964
+ }
3387
4965
  }
4966
+ const accepted: RowPatch[] = [];
4967
+ let rows: RowModel[] | undefined;
4968
+ for (const [key, value] of pending) {
4969
+ const index = rowIndexes.get(key)!;
4970
+ const group = snapshot.rows[index].groupId;
4971
+ if (rejected.has(key) || (group && rejectedGroups.has(group))) continue;
4972
+ if (!rows) rows = snapshot.rows.slice();
4973
+ rows[index] = owned ? deepFreeze(value.row) : value.row;
4974
+ accepted.push(owned ? deepFreeze(value.patch) : value.patch);
4975
+ }
4976
+ if (!rows) return { patches: EMPTY_ROW_PATCHES, snapshot, json: '[]' };
4977
+ const next = owned
4978
+ ? Object.freeze({ ...snapshot, rows: Object.freeze(rows) })
4979
+ : { ...snapshot, rows };
4980
+ if (owned) ownedNativeSnapshots.set(next, rowIndexes);
4981
+ else validatedRowIndexes.set(next, rowIndexes);
4982
+ return { patches: accepted, snapshot: next, json: JSON.stringify(accepted) };
4983
+ }
3388
4984
 
3389
- const nextRows = snapshot.rows.slice();
3390
- for (const patch of acceptedPatches) {
3391
- const index = rowIndexes.get(patch.key)!;
3392
- const previous = nextRows[index];
3393
- const merged = {
3394
- ...previous,
3395
- ...patch.changes,
3396
- key: previous.key,
3397
- type: previous.type,
3398
- } as RowModel;
3399
- const path = `rows[${index}]`;
3400
- assertPlainSerializable(merged, path, new Set<object>());
3401
- if (isDevelopment()) assertRow(merged, index);
3402
- const normalized = isDevelopment()
3403
- ? merged
3404
- : (normalizeEmptyImages(merged) as RowModel);
3405
- assertRowProtocol(normalized, path);
3406
- nextRows[index] = deepFreeze(normalizeRowStyles(normalized));
3407
- }
3408
- const nextSnapshot = Object.freeze({
3409
- ...snapshot,
3410
- rows: Object.freeze(nextRows),
3411
- });
3412
- ownedNativeSnapshots.set(nextSnapshot, rowIndexes);
3413
- return {
3414
- patches: acceptedPatches,
3415
- snapshot: nextSnapshot,
3416
- json: JSON.stringify(acceptedPatches),
3417
- };
4985
+ const validatedRowIndexes = new WeakMap<
4986
+ NativeListSnapshot,
4987
+ ReadonlyMap<string, number>
4988
+ >();
4989
+
4990
+ export function applyOwnedNativePatches(
4991
+ snapshot: NativeListSnapshot,
4992
+ patches: readonly RowPatch[]
4993
+ ) {
4994
+ const owned = ownedNativeSnapshots.has(snapshot)
4995
+ ? snapshot
4996
+ : ownValidatedNativeSnapshot(validateSnapshot(capturePlainData(snapshot)));
4997
+ return applyValidatedRowPatches(owned, patches);
4998
+ }
4999
+
5000
+ export function applyRowPatches(
5001
+ snapshot: NativeListSnapshot,
5002
+ patches: readonly RowPatch[]
5003
+ ): NativeListSnapshot {
5004
+ const baseline = ownedNativeSnapshots.has(snapshot)
5005
+ ? snapshot
5006
+ : validateSnapshot(snapshot);
5007
+ return applyValidatedRowPatches(baseline, patches).snapshot;
3418
5008
  }
3419
5009
 
3420
5010
  export function serializeSnapshot(snapshot: NativeListSnapshot): string {