@onekeyfe/react-native-native-list 6.7.0-6 → 6.7.0-60

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 (216) hide show
  1. package/README.md +312 -375
  2. package/android/src/main/java/com/onekey/nativelist/HybridNativeList.kt +14 -1
  3. package/android/src/main/java/com/onekey/nativelist/NativeListAccessoryStack.kt +250 -9
  4. package/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt +50 -13
  5. package/android/src/main/java/com/onekey/nativelist/NativeListActivityRenderer.kt +25 -3
  6. package/android/src/main/java/com/onekey/nativelist/NativeListAdapter.kt +17 -1
  7. package/android/src/main/java/com/onekey/nativelist/NativeListButtonGroupRenderer.kt +102 -0
  8. package/android/src/main/java/com/onekey/nativelist/NativeListContainerSlotAdapter.kt +12 -0
  9. package/android/src/main/java/com/onekey/nativelist/NativeListDataRowRenderer.kt +102 -7
  10. package/android/src/main/java/com/onekey/nativelist/NativeListGeneratedIcons.kt +47 -0
  11. package/android/src/main/java/com/onekey/nativelist/NativeListIdentityRenderer.kt +225 -11
  12. package/android/src/main/java/com/onekey/nativelist/NativeListLeadingVisual.kt +152 -33
  13. package/android/src/main/java/com/onekey/nativelist/NativeListMarketRenderer.kt +92 -28
  14. package/android/src/main/java/com/onekey/nativelist/NativeListMediaPlaceholderView.kt +244 -0
  15. package/android/src/main/java/com/onekey/nativelist/NativeListMediaPreviewSlot.kt +66 -31
  16. package/android/src/main/java/com/onekey/nativelist/NativeListMediaTileRenderer.kt +32 -11
  17. package/android/src/main/java/com/onekey/nativelist/NativeListMessageRenderer.kt +25 -0
  18. package/android/src/main/java/com/onekey/nativelist/NativeListModels.kt +209 -3
  19. package/android/src/main/java/com/onekey/nativelist/NativeListPrimitives.kt +120 -287
  20. package/android/src/main/java/com/onekey/nativelist/NativeListRendererRegistry.kt +2 -0
  21. package/android/src/main/java/com/onekey/nativelist/NativeListRendererRowView.kt +7 -0
  22. package/android/src/main/java/com/onekey/nativelist/NativeListResolvedText.kt +8 -3
  23. package/android/src/main/java/com/onekey/nativelist/NativeListSectionHeaderRenderer.kt +69 -0
  24. package/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt +130 -1
  25. package/android/src/main/java/com/onekey/nativelist/NativeListView.kt +1978 -136
  26. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListActivityHostClipPolicyTest.kt +35 -0
  27. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListDescriptionTouchPolicyTest.kt +153 -0
  28. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListIdentityTrailingAxisTest.kt +36 -0
  29. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingSlotFrameTest.kt +68 -0
  30. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingVisualClipPolicyTest.kt +44 -0
  31. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListPressPolicyTest.kt +10 -0
  32. package/docs/ROW_TEMPLATES.md +78 -14
  33. package/docs/SPEC.md +1318 -16
  34. package/docs/STYLE_SPEC.md +18 -0
  35. package/ios/HybridNativeList.swift +21 -2
  36. package/ios/NativeListAccessoryStack.swift +237 -51
  37. package/ios/NativeListActivityDetailsView.swift +43 -16
  38. package/ios/NativeListActivityRenderer.swift +8 -2
  39. package/ios/NativeListButtonGroupRenderer.swift +89 -0
  40. package/ios/NativeListDataRowRenderer.swift +167 -30
  41. package/ios/NativeListDesignAssets.swift +13 -75
  42. package/ios/NativeListGeneratedIcons.swift +55 -0
  43. package/ios/NativeListIconBinding.swift +171 -0
  44. package/ios/NativeListIdentityRenderer.swift +256 -39
  45. package/ios/NativeListLeadingVisual.swift +127 -28
  46. package/ios/NativeListMarketRenderer.swift +120 -31
  47. package/ios/NativeListMediaPlaceholderView.swift +189 -0
  48. package/ios/NativeListMediaPreviewSlot.swift +122 -61
  49. package/ios/NativeListMediaTileRenderer.swift +15 -11
  50. package/ios/NativeListMessageRenderer.swift +34 -1
  51. package/ios/NativeListMetricCardRenderer.swift +4 -2
  52. package/ios/NativeListModels.swift +42 -2
  53. package/ios/NativeListRendererRegistry.swift +1 -0
  54. package/ios/NativeListResolvedText.swift +17 -5
  55. package/ios/NativeListRowHost.swift +14 -0
  56. package/ios/NativeListSectionHeaderRenderer.swift +100 -4
  57. package/ios/NativeListTextLabel.swift +106 -0
  58. package/ios/RNCNativeListView.swift +1097 -60
  59. package/ios/tests/NativeListAccessoryStackTests.swift +101 -0
  60. package/ios/tests/NativeListAccountSelectorLayoutTests.swift +96 -0
  61. package/ios/tests/NativeListActivityPresentationTests.swift +423 -0
  62. package/ios/tests/NativeListIdentityTitleIconLayoutTests.swift +81 -0
  63. package/ios/tests/NativeListLeadingVisualPairBackdropTests.swift +50 -0
  64. package/ios/tests/NativeListLifecycleTests.swift +2959 -4
  65. package/ios/tests/NativeListMarketMetricsTests.swift +117 -0
  66. package/ios/tests/NativeListMediaVisibilityTests.swift +27 -1
  67. package/ios/tests/NativeListSharedIconTests.swift +236 -0
  68. package/lib/module/NativeList.js +236 -38
  69. package/lib/module/NativeList.web.js +163 -45
  70. package/lib/module/index.js +1 -1
  71. package/lib/module/models.js +3 -0
  72. package/lib/module/selection.js +1 -1
  73. package/lib/module/validation.js +1263 -48
  74. package/lib/module/web/NativeListGeneratedIcons.js +31 -0
  75. package/lib/module/web/NativeListWebEngine.js +513 -275
  76. package/lib/module/web/templates/ActivityRowRenderer.js +41 -54
  77. package/lib/module/web/templates/ButtonGroupRowRenderer.js +47 -0
  78. package/lib/module/web/templates/DataRowRenderer.js +56 -5
  79. package/lib/module/web/templates/IdentityRowRenderer.js +161 -7
  80. package/lib/module/web/templates/MarketTableRowRenderer.js +36 -19
  81. package/lib/module/web/templates/MediaTileRowRenderer.js +84 -25
  82. package/lib/module/web/templates/MessageRowRenderer.js +18 -2
  83. package/lib/module/web/templates/RowContainerStyle.js +1 -0
  84. package/lib/module/web/templates/RowRendererRegistry.js +3 -0
  85. package/lib/module/web/templates/SectionHeaderRowRenderer.js +36 -2
  86. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  87. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  88. package/lib/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  89. package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  90. package/lib/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  91. package/lib/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  92. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  93. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  94. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  95. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  96. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  97. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  98. package/lib/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  99. package/lib/typescript/src/NativeList.d.ts +3 -3
  100. package/lib/typescript/src/NativeList.nitro.d.ts +2 -0
  101. package/lib/typescript/src/NativeList.types.d.ts +20 -2
  102. package/lib/typescript/src/index.d.ts +2 -2
  103. package/lib/typescript/src/models.d.ts +134 -17
  104. package/lib/typescript/src/validation.d.ts +20 -0
  105. package/lib/typescript/src/web/NativeListGeneratedIcons.d.ts +2 -0
  106. package/lib/typescript/src/web/NativeListWebEngine.d.ts +32 -1
  107. package/lib/typescript/src/web/templates/ButtonGroupRowRenderer.d.ts +14 -0
  108. package/lib/typescript/src/web/templates/IdentityRowRenderer.d.ts +1 -1
  109. package/lib/typescript/src/web/templates/MessageRowRenderer.d.ts +9 -3
  110. package/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  111. package/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  112. package/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  113. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  114. package/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  115. package/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  116. package/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  117. package/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  118. package/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  119. package/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  120. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  121. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  122. package/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  123. package/package.json +16 -10
  124. package/react-native-native-list.podspec +2 -6
  125. package/scripts/generate-icons.mjs +150 -0
  126. package/scripts/generate-icons.test.mjs +288 -0
  127. package/scripts/native-list-icons.json +260 -0
  128. package/src/NativeList.nitro.ts +2 -0
  129. package/src/NativeList.tsx +439 -91
  130. package/src/NativeList.types.ts +24 -2
  131. package/src/NativeList.web.tsx +286 -88
  132. package/src/index.ts +2 -0
  133. package/src/models.ts +272 -144
  134. package/src/selection.ts +1 -0
  135. package/src/validation.ts +3041 -146
  136. package/src/web/NativeListGeneratedIcons.ts +28 -0
  137. package/src/web/NativeListWebEngine.ts +818 -343
  138. package/src/web/templates/ActivityRowRenderer.ts +71 -91
  139. package/src/web/templates/ButtonGroupRowRenderer.ts +58 -0
  140. package/src/web/templates/DataRowRenderer.ts +121 -20
  141. package/src/web/templates/IdentityRowRenderer.ts +234 -9
  142. package/src/web/templates/MarketTableRowRenderer.ts +53 -33
  143. package/src/web/templates/MediaTileRowRenderer.ts +90 -28
  144. package/src/web/templates/MessageRowRenderer.ts +23 -7
  145. package/src/web/templates/RowContainerStyle.ts +2 -0
  146. package/src/web/templates/RowRendererRegistry.ts +11 -1
  147. package/src/web/templates/SectionHeaderRowRenderer.ts +47 -4
  148. package/ios/Resources/NativeListIcons.xcassets/Contents.json +0 -1
  149. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_bottom.imageset/Contents.json +0 -1
  150. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_bottom.imageset/icon.svg +0 -1
  151. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_top.imageset/Contents.json +0 -1
  152. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_top.imageset/icon.svg +0 -1
  153. package/ios/Resources/NativeListIcons.xcassets/onekey_badge_verified_solid.imageset/Contents.json +0 -1
  154. package/ios/Resources/NativeListIcons.xcassets/onekey_badge_verified_solid.imageset/icon.svg +0 -1
  155. package/ios/Resources/NativeListIcons.xcassets/onekey_chart_trending_up.imageset/Contents.json +0 -1
  156. package/ios/Resources/NativeListIcons.xcassets/onekey_chart_trending_up.imageset/icon.svg +0 -1
  157. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_checked.imageset/Contents.json +0 -1
  158. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_checked.imageset/icon.svg +0 -1
  159. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_indeterminate.imageset/Contents.json +0 -1
  160. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_indeterminate.imageset/icon.svg +0 -1
  161. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_bottom.imageset/Contents.json +0 -1
  162. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_bottom.imageset/icon.svg +0 -1
  163. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_grabber_ver.imageset/Contents.json +0 -1
  164. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_grabber_ver.imageset/icon.svg +0 -1
  165. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_right_small.imageset/Contents.json +0 -1
  166. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_right_small.imageset/icon.svg +0 -1
  167. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_top.imageset/Contents.json +0 -1
  168. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_top.imageset/icon.svg +0 -1
  169. package/ios/Resources/NativeListIcons.xcassets/onekey_dot_hor.imageset/Contents.json +0 -1
  170. package/ios/Resources/NativeListIcons.xcassets/onekey_dot_hor.imageset/icon.svg +0 -1
  171. package/ios/Resources/NativeListIcons.xcassets/onekey_drag.imageset/Contents.json +0 -1
  172. package/ios/Resources/NativeListIcons.xcassets/onekey_drag.imageset/icon.svg +0 -1
  173. package/ios/Resources/NativeListIcons.xcassets/onekey_error_solid.imageset/Contents.json +0 -1
  174. package/ios/Resources/NativeListIcons.xcassets/onekey_error_solid.imageset/icon.svg +0 -1
  175. package/ios/Resources/NativeListIcons.xcassets/onekey_image_square_waves.imageset/Contents.json +0 -1
  176. package/ios/Resources/NativeListIcons.xcassets/onekey_image_square_waves.imageset/icon.svg +0 -1
  177. package/ios/Resources/NativeListIcons.xcassets/onekey_info_circle.imageset/Contents.json +0 -1
  178. package/ios/Resources/NativeListIcons.xcassets/onekey_info_circle.imageset/icon.svg +0 -1
  179. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle.imageset/Contents.json +0 -1
  180. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle.imageset/icon.svg +0 -1
  181. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle_solid.imageset/Contents.json +0 -1
  182. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle_solid.imageset/icon.svg +0 -1
  183. package/ios/Resources/NativeListIcons.xcassets/onekey_pencil.imageset/Contents.json +0 -1
  184. package/ios/Resources/NativeListIcons.xcassets/onekey_pencil.imageset/icon.svg +0 -1
  185. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_circle.imageset/Contents.json +0 -1
  186. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_circle.imageset/icon.svg +0 -1
  187. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_small.imageset/Contents.json +0 -1
  188. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_small.imageset/icon.svg +0 -1
  189. package/ios/Resources/NativeListIcons.xcassets/onekey_questionmark_solid.imageset/Contents.json +0 -1
  190. package/ios/Resources/NativeListIcons.xcassets/onekey_questionmark_solid.imageset/icon.svg +0 -1
  191. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_account_error_custom.imageset/Contents.json +0 -15
  192. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_account_error_custom.imageset/icon.svg +0 -14
  193. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_all_networks_solid.imageset/Contents.json +0 -15
  194. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_all_networks_solid.imageset/icon.svg +0 -12
  195. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_apple_brand.imageset/Contents.json +0 -15
  196. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_apple_brand.imageset/icon.svg +0 -6
  197. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_bot_illus.imageset/Contents.json +0 -15
  198. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_bot_illus.imageset/icon.svg +0 -15
  199. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_crossed_small_solid.imageset/Contents.json +0 -15
  200. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_crossed_small_solid.imageset/icon.svg +0 -3
  201. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_globus_outline.imageset/Contents.json +0 -15
  202. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_globus_outline.imageset/icon.svg +0 -7
  203. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_google_illus.imageset/Contents.json +0 -15
  204. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_google_illus.imageset/icon.svg +0 -18
  205. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_lock_solid.imageset/Contents.json +0 -15
  206. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_lock_solid.imageset/icon.svg +0 -7
  207. package/ios/Resources/NativeListIcons.xcassets/onekey_shield_exclamation.imageset/Contents.json +0 -1
  208. package/ios/Resources/NativeListIcons.xcassets/onekey_shield_exclamation.imageset/icon.svg +0 -1
  209. package/ios/Resources/NativeListIcons.xcassets/onekey_speaker_promote.imageset/Contents.json +0 -1
  210. package/ios/Resources/NativeListIcons.xcassets/onekey_speaker_promote.imageset/icon.svg +0 -1
  211. package/ios/Resources/NativeListIcons.xcassets/onekey_star.imageset/Contents.json +0 -1
  212. package/ios/Resources/NativeListIcons.xcassets/onekey_star.imageset/icon.svg +0 -1
  213. package/ios/Resources/NativeListIcons.xcassets/onekey_star_solid.imageset/Contents.json +0 -1
  214. package/ios/Resources/NativeListIcons.xcassets/onekey_star_solid.imageset/icon.svg +0 -1
  215. package/ios/Resources/NativeListIcons.xcassets/onekey_swap_hor.imageset/Contents.json +0 -1
  216. package/ios/Resources/NativeListIcons.xcassets/onekey_swap_hor.imageset/icon.svg +0 -1
package/src/validation.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { ROW_BOX_STYLE_KEYS_BY_TYPE } from './models';
2
2
  import type {
3
3
  ActivityRow,
4
+ ButtonGroupRow,
4
5
  IdentityRow,
5
6
  ImageSource,
6
7
  LeadingVisual,
@@ -13,10 +14,12 @@ import type {
13
14
  RowBoxStyle,
14
15
  RowModel,
15
16
  RowPatch,
17
+ RowTextHelp,
16
18
  WalletGroupRow,
17
19
  WebMarketTableCell,
18
20
  WebMarketTablePresentation,
19
21
  WebMarketTableText,
22
+ ValueTextSegment,
20
23
  } from './models';
21
24
 
22
25
  const MAX_KEY_LENGTH = 256;
@@ -30,21 +33,68 @@ const MAX_HEADER_LENGTH = 4096;
30
33
  const MAX_SPACER_HEIGHT = 512;
31
34
  const MAX_SECTION_INDEX_TITLE_LENGTH = 8;
32
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;
47
+
48
+ function isDevelopment(): boolean {
49
+ return typeof __DEV__ !== 'undefined' && __DEV__;
50
+ }
51
+
52
+ class NativeListInputError extends Error {
53
+ constructor(readonly path: string, readonly reason: string) {
54
+ super(`NativeList ${path}: ${reason}`);
55
+ }
56
+ }
33
57
 
34
58
  function fail(path: string, message: string): never {
35
- throw new Error(`NativeList ${path}: ${message}`);
59
+ throw new NativeListInputError(path, message);
60
+ }
61
+
62
+ /** Component boundaries report locations, never caller-controlled payload values. */
63
+ export function containNativeListInput<T>(operation: () => T): T | undefined {
64
+ try {
65
+ return operation();
66
+ } catch (error) {
67
+ const path = error instanceof NativeListInputError ? error.path : 'input';
68
+ const reason =
69
+ isDevelopment() && error instanceof NativeListInputError
70
+ ? `: ${error.reason.split('"')[0].trim()}`
71
+ : '';
72
+ console.warn(`NativeList rejected invalid input at ${path}${reason}`);
73
+ return undefined;
74
+ }
75
+ }
76
+
77
+ export function emptyNativeListSnapshot(): NativeListSnapshot {
78
+ return {
79
+ schemaVersion: 1,
80
+ generation: 0,
81
+ layout: { kind: 'linear' },
82
+ rows: [],
83
+ };
36
84
  }
37
85
 
38
86
  function assertPlainSerializable(
39
87
  value: unknown,
40
88
  path: string,
41
- seen: Set<object>
89
+ seen: Set<object>,
90
+ requireFinite = true
42
91
  ): void {
43
92
  if (value === null || value === undefined) return;
44
93
  const valueType = typeof value;
45
94
  if (valueType === 'string' || valueType === 'boolean') return;
46
95
  if (valueType === 'number') {
47
- if (!Number.isFinite(value)) fail(path, 'numbers must be finite');
96
+ if (requireFinite && !Number.isFinite(value))
97
+ fail(path, 'numbers must be finite');
48
98
  return;
49
99
  }
50
100
  if (valueType !== 'object')
@@ -55,16 +105,21 @@ function assertPlainSerializable(
55
105
  seen.add(objectValue);
56
106
  if (Array.isArray(value)) {
57
107
  value.forEach((item, index) =>
58
- assertPlainSerializable(item, `${path}[${index}]`, seen)
108
+ assertPlainSerializable(item, `${path}[${index}]`, seen, requireFinite)
59
109
  );
60
110
  } else {
61
111
  const prototype = Object.getPrototypeOf(value);
62
112
  if (prototype !== Object.prototype && prototype !== null) {
63
113
  fail(path, 'must contain plain objects only');
64
114
  }
65
- Object.entries(value as Record<string, unknown>).forEach(([key, item]) =>
66
- assertPlainSerializable(item, `${path}.${key}`, seen)
67
- );
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
+ });
68
123
  }
69
124
  seen.delete(objectValue);
70
125
  }
@@ -72,16 +127,14 @@ function assertPlainSerializable(
72
127
  function assertKey(key: string, path: string): void {
73
128
  if (
74
129
  typeof key !== 'string' ||
75
- key.length === 0 ||
130
+ key.trim().length === 0 ||
76
131
  key.length > MAX_KEY_LENGTH
77
132
  ) {
78
133
  fail(
79
134
  path,
80
- `must be a non-empty string no longer than ${MAX_KEY_LENGTH} characters`
135
+ `must be a non-blank string no longer than ${MAX_KEY_LENGTH} characters`
81
136
  );
82
137
  }
83
- if (key.trim() !== key)
84
- fail(path, 'must not have leading or trailing whitespace');
85
138
  }
86
139
 
87
140
  function assertText(text: string | undefined, path: string): void {
@@ -188,12 +241,14 @@ const TEXT_STYLE_KEYS_BY_ROW_TYPE: Readonly<
188
241
  metricCard: ['title', 'value', 'subtitle', 'trend'],
189
242
  sectionHeader: ['title', 'subtitle', 'value'],
190
243
  action: ['title', 'value'],
244
+ buttonGroup: [],
191
245
  system: ['title', 'message', 'actionText'],
192
246
  };
193
247
 
194
248
  const EXTRA_STYLE_KEYS_BY_ROW_TYPE: Readonly<
195
249
  Partial<Record<RowModel['type'], readonly string[]>>
196
250
  > = {
251
+ identity: ['leadingContentMaxWidthRatio'],
197
252
  market: [
198
253
  'titleBadgeLayout',
199
254
  'contentTrailingGap',
@@ -202,6 +257,7 @@ const EXTRA_STYLE_KEYS_BY_ROW_TYPE: Readonly<
202
257
  'changeHeight',
203
258
  'changeCornerRadius',
204
259
  ],
260
+ sectionHeader: ['valuePlacement', 'titleDecoration'],
205
261
  };
206
262
 
207
263
  function assertTextStyle(
@@ -460,6 +516,33 @@ function assertRowStyle(row: RowModel, path: string): void {
460
516
  // Market keeps its own richer assertions, driven from assertMarketRow.
461
517
  if (row.type === 'market') return;
462
518
  assertBoxStyle(style as RowBoxStyle, `${path}.style`);
519
+ if (row.type === 'identity') {
520
+ const ratio = (style as IdentityRow['style'])?.leadingContentMaxWidthRatio;
521
+ if (
522
+ ratio !== undefined &&
523
+ (!Number.isFinite(ratio) || ratio <= 0 || ratio > 1)
524
+ )
525
+ fail(
526
+ `${path}.style.leadingContentMaxWidthRatio`,
527
+ 'must be within (0, 1]'
528
+ );
529
+ }
530
+ if (row.type === 'sectionHeader') {
531
+ const sectionStyle = style as Extract<
532
+ RowModel,
533
+ { type: 'sectionHeader' }
534
+ >['style'];
535
+ if (
536
+ sectionStyle?.valuePlacement !== undefined &&
537
+ sectionStyle.valuePlacement !== 'afterTitle'
538
+ )
539
+ fail(`${path}.style.valuePlacement`, 'must be afterTitle');
540
+ if (
541
+ sectionStyle?.titleDecoration !== undefined &&
542
+ !['none', 'dashed'].includes(sectionStyle.titleDecoration)
543
+ )
544
+ fail(`${path}.style.titleDecoration`, 'must be none or dashed');
545
+ }
463
546
  const slots = style as Record<string, NativeListTextStyle | undefined>;
464
547
  textKeys.forEach((key) =>
465
548
  assertTextStyle(slots[key], `${path}.style.${key}`)
@@ -911,8 +994,88 @@ function assertWebMarketTable(
911
994
  });
912
995
  }
913
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
+
914
1051
  function assertMarketRow(row: MarketRow, path: string): void {
915
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
+ }
916
1079
  if (!['token', 'stock', 'perp'].includes(row.variant)) {
917
1080
  fail(`${path}.variant`, 'must be token, stock, or perp');
918
1081
  }
@@ -1017,6 +1180,55 @@ function assertTrailingAccessories(
1017
1180
  ): void {
1018
1181
  accessories?.forEach((accessory, index) => {
1019
1182
  const accessoryPath = `${path}[${index}]`;
1183
+ if (accessory.kind === 'button') {
1184
+ assertUnknownKeys(
1185
+ accessory as Record<string, unknown>,
1186
+ [
1187
+ 'kind',
1188
+ 'label',
1189
+ 'actionKey',
1190
+ 'disabled',
1191
+ 'testID',
1192
+ 'accessibilityLabel',
1193
+ 'textColor',
1194
+ 'backgroundColor',
1195
+ 'pressedBackgroundColor',
1196
+ 'hoverBackgroundColor',
1197
+ 'focusRingColor',
1198
+ ],
1199
+ accessoryPath,
1200
+ 'button key'
1201
+ );
1202
+ if (typeof accessory.label !== 'string' || !accessory.label.trim())
1203
+ fail(`${accessoryPath}.label`, 'must be non-blank');
1204
+ assertKey(accessory.actionKey, `${accessoryPath}.actionKey`);
1205
+ if (
1206
+ accessory.disabled !== undefined &&
1207
+ typeof accessory.disabled !== 'boolean'
1208
+ )
1209
+ fail(`${accessoryPath}.disabled`, 'must be boolean');
1210
+ for (const field of [
1211
+ 'textColor',
1212
+ 'backgroundColor',
1213
+ 'pressedBackgroundColor',
1214
+ 'hoverBackgroundColor',
1215
+ 'focusRingColor',
1216
+ ] as const) {
1217
+ const value = accessory[field];
1218
+ if (
1219
+ value !== undefined &&
1220
+ (typeof value !== 'string' ||
1221
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value))
1222
+ )
1223
+ fail(`${accessoryPath}.${field}`, 'must be #RRGGBB or #RRGGBBAA');
1224
+ }
1225
+ }
1226
+ if (
1227
+ accessory.kind === 'icon' &&
1228
+ accessory.buttonStyle !== undefined &&
1229
+ accessory.buttonStyle !== 'tertiary'
1230
+ )
1231
+ fail(`${accessoryPath}.buttonStyle`, 'must be tertiary');
1020
1232
  if (
1021
1233
  accessory.kind === 'progress' &&
1022
1234
  (accessory.value < 0 || accessory.value > 1)
@@ -1024,14 +1236,188 @@ function assertTrailingAccessories(
1024
1236
  fail(`${accessoryPath}.value`, 'must be within 0...1');
1025
1237
  }
1026
1238
  if (accessory.kind === 'valuePair') {
1239
+ if (
1240
+ accessory.primaryFontWeight !== undefined &&
1241
+ accessory.primaryFontWeight !== 'medium'
1242
+ )
1243
+ fail(
1244
+ `${accessoryPath}.primaryFontWeight`,
1245
+ 'must be medium when provided'
1246
+ );
1247
+ assertTextHelp(accessory.primaryHelp, `${accessoryPath}.primaryHelp`);
1027
1248
  assertTextTone(accessory.primaryTone, `${accessoryPath}.primaryTone`);
1028
1249
  assertTextTone(accessory.secondaryTone, `${accessoryPath}.secondaryTone`);
1250
+ for (const field of [
1251
+ 'primaryTextSegments',
1252
+ 'secondaryTextSegments',
1253
+ ] as const) {
1254
+ const segments = accessory[field];
1255
+ if (segments === undefined) continue;
1256
+ const segmentPath = `${accessoryPath}.${field}`;
1257
+ if (!Array.isArray(segments) || segments.length > 64)
1258
+ fail(segmentPath, 'must be an array of at most 64 segments');
1259
+ let textLength = 0;
1260
+ segments.forEach((segment, segmentIndex) => {
1261
+ const path = `${segmentPath}[${segmentIndex}]`;
1262
+ const entry = protocolObject(segment, path);
1263
+ assertUnknownKeys(entry, ['text', 'style'], path, 'segment key');
1264
+ if (
1265
+ typeof entry.text !== 'string' ||
1266
+ entry.text.length > MAX_TEXT_LENGTH
1267
+ )
1268
+ fail(
1269
+ `${path}.text`,
1270
+ `must be a string no longer than ${MAX_TEXT_LENGTH} characters`
1271
+ );
1272
+ if (entry.style !== undefined && entry.style !== 'subscript')
1273
+ fail(`${path}.style`, 'must be subscript when provided');
1274
+ textLength += entry.text.length;
1275
+ });
1276
+ if (textLength > MAX_TEXT_LENGTH)
1277
+ fail(
1278
+ segmentPath,
1279
+ `total text must be at most ${MAX_TEXT_LENGTH} characters`
1280
+ );
1281
+ }
1282
+ }
1283
+ });
1284
+ }
1285
+
1286
+ function assertTextHelp(help: RowTextHelp | undefined, path: string): void {
1287
+ if (help === undefined) return;
1288
+ const object = protocolObject(help, path);
1289
+ assertUnknownKeys(
1290
+ object,
1291
+ ['actionKey', 'presentation', 'underline'],
1292
+ path,
1293
+ 'help key'
1294
+ );
1295
+ assertKey(help.actionKey, `${path}.actionKey`);
1296
+ if (!['tooltip', 'popover'].includes(help.presentation))
1297
+ fail(`${path}.presentation`, 'must be tooltip or popover');
1298
+ if (help.underline !== undefined && help.underline !== 'dashed')
1299
+ fail(`${path}.underline`, 'must be dashed');
1300
+ }
1301
+
1302
+ function assertButtonGroup(
1303
+ row: Pick<ButtonGroupRow, 'buttons'>,
1304
+ path: string
1305
+ ): void {
1306
+ if (!Array.isArray(row.buttons) || row.buttons.length === 0)
1307
+ fail(`${path}.buttons`, 'must contain at least one button');
1308
+ const keys = new Set<string>();
1309
+ row.buttons.forEach((button, index) => {
1310
+ const itemPath = `${path}.buttons[${index}]`;
1311
+ const object = protocolObject(button, itemPath);
1312
+ assertUnknownKeys(
1313
+ object,
1314
+ [
1315
+ 'key',
1316
+ 'label',
1317
+ 'actionKey',
1318
+ 'disabled',
1319
+ 'loading',
1320
+ 'testID',
1321
+ 'accessibilityLabel',
1322
+ ],
1323
+ itemPath,
1324
+ 'button key'
1325
+ );
1326
+ assertKey(button.key, `${itemPath}.key`);
1327
+ if (keys.has(button.key)) fail(`${itemPath}.key`, 'duplicate button key');
1328
+ keys.add(button.key);
1329
+ if (
1330
+ typeof button.label !== 'string' ||
1331
+ !button.label.trim() ||
1332
+ button.label.length > MAX_TEXT_LENGTH
1333
+ )
1334
+ fail(`${itemPath}.label`, 'must be non-blank bounded text');
1335
+ assertKey(button.actionKey, `${itemPath}.actionKey`);
1336
+ for (const field of ['disabled', 'loading'] as const) {
1337
+ if (button[field] !== undefined && typeof button[field] !== 'boolean')
1338
+ fail(`${itemPath}.${field}`, 'must be boolean');
1339
+ }
1340
+ for (const field of ['testID', 'accessibilityLabel'] as const) {
1341
+ if (button[field] !== undefined && typeof button[field] !== 'string')
1342
+ fail(`${itemPath}.${field}`, 'must be a string');
1029
1343
  }
1030
1344
  });
1031
1345
  }
1032
1346
 
1347
+ function assertIdentityExtras(
1348
+ row: Pick<
1349
+ IdentityRow,
1350
+ 'titleIcon' | 'secondaryTitleIcon' | 'titleImage' | 'trailing' | 'style'
1351
+ >,
1352
+ path: string
1353
+ ): void {
1354
+ for (const field of ['titleIcon', 'secondaryTitleIcon'] as const) {
1355
+ const titleIcon = row[field];
1356
+ if (titleIcon === undefined) continue;
1357
+ const iconPath = `${path}.${field}`;
1358
+ const icon = protocolObject(titleIcon, iconPath);
1359
+ assertUnknownKeys(
1360
+ icon,
1361
+ ['name', 'tintColor', 'accessibilityLabel', 'hoverActionKey'],
1362
+ iconPath,
1363
+ 'title icon key'
1364
+ );
1365
+ if (typeof titleIcon.name !== 'string' || !titleIcon.name.trim())
1366
+ fail(`${iconPath}.name`, 'must be non-blank');
1367
+ if (
1368
+ titleIcon.tintColor !== undefined &&
1369
+ (typeof titleIcon.tintColor !== 'string' ||
1370
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(titleIcon.tintColor))
1371
+ )
1372
+ fail(`${iconPath}.tintColor`, 'must be #RRGGBB or #RRGGBBAA');
1373
+ if (
1374
+ titleIcon.accessibilityLabel !== undefined &&
1375
+ typeof titleIcon.accessibilityLabel !== 'string'
1376
+ )
1377
+ fail(`${iconPath}.accessibilityLabel`, 'must be a string');
1378
+ if (titleIcon.hoverActionKey !== undefined)
1379
+ assertKey(titleIcon.hoverActionKey, `${iconPath}.hoverActionKey`);
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
+ }
1405
+ const ratio = row.style?.leadingContentMaxWidthRatio;
1406
+ if (
1407
+ ratio !== undefined &&
1408
+ (typeof ratio !== 'number' ||
1409
+ !Number.isFinite(ratio) ||
1410
+ ratio <= 0 ||
1411
+ ratio > 1)
1412
+ )
1413
+ fail(`${path}.style.leadingContentMaxWidthRatio`, 'must be within (0, 1]');
1414
+ assertTrailingAccessories(row.trailing, `${path}.trailing`);
1415
+ }
1416
+
1033
1417
  function assertImage(image: ImageSource | undefined, path: string): void {
1034
1418
  if (!image) return;
1419
+ if (!isAllowedImageUri(image.uri))
1420
+ fail(`${path}.uri`, 'unsupported image URI');
1035
1421
  if (!image.uri.trim()) fail(`${path}.uri`, 'must not be empty');
1036
1422
  if (image.fallbackUris !== undefined) {
1037
1423
  if (!Array.isArray(image.fallbackUris))
@@ -1100,6 +1486,24 @@ function assertLeadingVisual(
1100
1486
  assertText(visual.cornerIcon?.name, `${path}.cornerIcon.name`);
1101
1487
  // OneKey patch: validate optional selector overlays at the JSON boundary.
1102
1488
  assertText(visual.fallbackIcon?.name, `${path}.fallbackIcon.name`);
1489
+ if (
1490
+ visual.fallbackTextColor !== undefined &&
1491
+ (typeof visual.fallbackTextColor !== 'string' ||
1492
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(visual.fallbackTextColor))
1493
+ )
1494
+ fail(`${path}.fallbackTextColor`, 'must be a hex color');
1495
+ if (
1496
+ visual.fallbackIcon?.size !== undefined &&
1497
+ (!Number.isFinite(visual.fallbackIcon.size) ||
1498
+ visual.fallbackIcon.size <= 0 ||
1499
+ visual.fallbackIcon.size > 40)
1500
+ )
1501
+ fail(`${path}.fallbackIcon.size`, 'must be within (0, 40]');
1502
+ if (
1503
+ visual.fallbackIcon?.backgroundColor !== undefined &&
1504
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(visual.fallbackIcon.backgroundColor)
1505
+ )
1506
+ fail(`${path}.fallbackIcon.backgroundColor`, 'must be a hex color');
1103
1507
  if ((visual.overlays?.length ?? 0) > 2)
1104
1508
  fail(`${path}.overlays`, 'supports at most two overlays');
1105
1509
  visual.overlays?.forEach((overlay, index) => {
@@ -1159,7 +1563,34 @@ function assertLeadingVisual(
1159
1563
  'must fit inside the overlay'
1160
1564
  );
1161
1565
  assertImage(overlay.image, `${path}.overlays[${index}].image`);
1566
+ if (overlay.fallbackIcon !== undefined && !overlay.image)
1567
+ fail(`${path}.overlays[${index}].fallbackIcon`, 'requires image');
1568
+ if (
1569
+ overlay.fallbackIcon !== undefined &&
1570
+ (typeof overlay.fallbackIcon.name !== 'string' ||
1571
+ !overlay.fallbackIcon.name.trim())
1572
+ )
1573
+ fail(
1574
+ `${path}.overlays[${index}].fallbackIcon.name`,
1575
+ 'must be non-blank'
1576
+ );
1577
+ if (
1578
+ overlay.fallbackIcon?.tintColor !== undefined &&
1579
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(overlay.fallbackIcon.tintColor)
1580
+ )
1581
+ fail(
1582
+ `${path}.overlays[${index}].fallbackIcon.tintColor`,
1583
+ 'must be a hex color'
1584
+ );
1162
1585
  assertText(overlay.text, `${path}.overlays[${index}].text`);
1586
+ if (
1587
+ overlay.fontWeight !== undefined &&
1588
+ !['regular', 'medium', 'semibold', 'bold'].includes(overlay.fontWeight)
1589
+ )
1590
+ fail(
1591
+ `${path}.overlays[${index}].fontWeight`,
1592
+ 'must be regular, medium, semibold, or bold'
1593
+ );
1163
1594
  });
1164
1595
  if (visual.kind === 'token') {
1165
1596
  assertImage(visual.networkImage, `${path}.networkImage`);
@@ -1190,7 +1621,14 @@ function assertVisual(row: RowModel, path: string): void {
1190
1621
  });
1191
1622
  }
1192
1623
 
1624
+ /** The type half of the `descriptionActionStart` contract; the range needs the row. */
1625
+ function isDescriptionActionStart(value: unknown): value is number {
1626
+ return Number.isSafeInteger(value) && (value as number) >= 0;
1627
+ }
1628
+
1193
1629
  function assertActivity(row: Partial<ActivityRow>, path: string): void {
1630
+ if (row.hideLeading !== undefined && typeof row.hideLeading !== 'boolean')
1631
+ fail(`${path}.hideLeading`, 'must be boolean');
1194
1632
  assertText(row.title, `${path}.title`);
1195
1633
  assertText(row.description, `${path}.description`);
1196
1634
  if (
@@ -1200,6 +1638,11 @@ function assertActivity(row: Partial<ActivityRow>, path: string): void {
1200
1638
  fail(`${path}.presentation`, 'must be stacked or table');
1201
1639
  if (row.descriptionActionKey !== undefined)
1202
1640
  assertKey(row.descriptionActionKey, `${path}.descriptionActionKey`);
1641
+ if (
1642
+ row.descriptionActionStart !== undefined &&
1643
+ !isDescriptionActionStart(row.descriptionActionStart)
1644
+ )
1645
+ fail(`${path}.descriptionActionStart`, 'must be a non-negative integer');
1203
1646
  if ((row.amounts?.length ?? 0) > 32)
1204
1647
  fail(`${path}.amounts`, 'supports at most 32 amount lines');
1205
1648
  const amountKeys = new Set<string>();
@@ -1326,6 +1769,7 @@ function assertRow(
1326
1769
  path = `rows[${index}]`
1327
1770
  ): void {
1328
1771
  assertRowType(row.type, path);
1772
+ assertUnknownKeys(row, ROW_FIELDS[row.type], path, 'row key');
1329
1773
  assertKey(row.key, `${path}.key`);
1330
1774
  // OneKey patch: explicit dimensions and opacity cannot corrupt list layout.
1331
1775
  if (row.height !== undefined && (row.height < 0 || row.height > 4096))
@@ -1355,6 +1799,18 @@ function assertRow(
1355
1799
  assertWalletGroup(row, path);
1356
1800
  break;
1357
1801
  case 'identity':
1802
+ if (row.contentHeight !== undefined && row.contentHeight !== 'auto') {
1803
+ fail(`${path}.contentHeight`, 'must be auto');
1804
+ }
1805
+ if (
1806
+ row.subtitleLines !== undefined &&
1807
+ ![0, 1, 2].includes(row.subtitleLines)
1808
+ ) {
1809
+ fail(`${path}.subtitleLines`, 'must be 0, 1, or 2');
1810
+ }
1811
+ if (row.longPressActionKey !== undefined) {
1812
+ assertKey(row.longPressActionKey, `${path}.longPressActionKey`);
1813
+ }
1358
1814
  if (
1359
1815
  row.presentation !== undefined &&
1360
1816
  row.presentation !== 'walletSidebar' &&
@@ -1367,6 +1823,27 @@ function assertRow(
1367
1823
  );
1368
1824
  }
1369
1825
  assertText(row.title, `${path}.title`);
1826
+ if ((row.titleSuffixes?.length ?? 0) > 3)
1827
+ fail(`${path}.titleSuffixes`, 'supports at most 3 suffixes');
1828
+ row.titleSuffixes?.forEach((suffix, index) => {
1829
+ assertText(suffix.text, `${path}.titleSuffixes[${index}].text`);
1830
+ if (!['secondary', 'disabled'].includes(suffix.tone))
1831
+ fail(
1832
+ `${path}.titleSuffixes[${index}].tone`,
1833
+ 'must be secondary or disabled'
1834
+ );
1835
+ if (
1836
+ suffix.maxWidth !== undefined &&
1837
+ (!Number.isFinite(suffix.maxWidth) ||
1838
+ suffix.maxWidth < 0 ||
1839
+ suffix.maxWidth > 4096)
1840
+ )
1841
+ fail(
1842
+ `${path}.titleSuffixes[${index}].maxWidth`,
1843
+ 'must be finite within 0...4096'
1844
+ );
1845
+ });
1846
+ assertIdentityExtras(row, path);
1370
1847
  assertText(row.subtitle, `${path}.subtitle`);
1371
1848
  // OneKey patch: selector text segments truncate independently.
1372
1849
  row.subtitleSegments?.forEach((segment, segmentIndex) => {
@@ -1432,12 +1909,25 @@ function assertRow(
1432
1909
  break;
1433
1910
  case 'activity':
1434
1911
  assertActivity(row, path);
1912
+ // Checked on the complete row only: a patch may carry the offset
1913
+ // without the description it points into.
1914
+ if ((row.descriptionActionStart ?? 0) > (row.description?.length ?? 0))
1915
+ fail(
1916
+ `${path}.descriptionActionStart`,
1917
+ 'must not exceed the description length'
1918
+ );
1435
1919
  break;
1436
1920
  case 'message':
1921
+ if (
1922
+ row.presentation !== undefined &&
1923
+ row.presentation !== 'inlineWarning'
1924
+ ) {
1925
+ fail(`${path}.presentation`, 'must be inlineWarning');
1926
+ }
1437
1927
  assertText(row.title, `${path}.title`);
1438
1928
  assertText(row.body, `${path}.body`);
1439
- if (![1, 2, 3].includes(row.bodyLines ?? 3)) {
1440
- fail(`${path}.bodyLines`, 'must be 1, 2, or 3');
1929
+ if (![0, 1, 2, 3].includes(row.bodyLines ?? 3)) {
1930
+ fail(`${path}.bodyLines`, 'must be 0, 1, 2, or 3');
1441
1931
  }
1442
1932
  assertImage(row.thumbnail, `${path}.thumbnail`);
1443
1933
  break;
@@ -1448,6 +1938,23 @@ function assertRow(
1448
1938
  row.columns.forEach((column, columnIndex) => {
1449
1939
  assertKey(column.key, `${path}.columns[${columnIndex}].key`);
1450
1940
  assertText(column.text, `${path}.columns[${columnIndex}].text`);
1941
+ assertIdentityExtras(column, `${path}.columns[${columnIndex}]`);
1942
+ for (const field of [
1943
+ 'textSegments',
1944
+ 'secondaryTextSegments',
1945
+ ] as const) {
1946
+ column[field]?.forEach((segment, segmentIndex) => {
1947
+ assertText(
1948
+ segment.text,
1949
+ `${path}.columns[${columnIndex}].${field}[${segmentIndex}].text`
1950
+ );
1951
+ if (segment.style !== undefined && segment.style !== 'subscript')
1952
+ fail(
1953
+ `${path}.columns[${columnIndex}].${field}[${segmentIndex}].style`,
1954
+ 'must be subscript'
1955
+ );
1956
+ });
1957
+ }
1451
1958
  assertText(
1452
1959
  column.secondaryLeadingText,
1453
1960
  `${path}.columns[${columnIndex}].secondaryLeadingText`
@@ -1464,6 +1971,13 @@ function assertRow(
1464
1971
  if ((row.badges?.length ?? 0) > MAX_BADGES) {
1465
1972
  fail(`${path}.badges`, `supports at most ${MAX_BADGES} badges`);
1466
1973
  }
1974
+ if ((row.trailing?.length ?? 0) > MAX_TRAILING_ACCESSORIES) {
1975
+ fail(
1976
+ `${path}.trailing`,
1977
+ `supports at most ${MAX_TRAILING_ACCESSORIES} accessories`
1978
+ );
1979
+ }
1980
+ assertTrailingAccessories(row.trailing, `${path}.trailing`);
1467
1981
  break;
1468
1982
  case 'market':
1469
1983
  assertMarketRow(row, path);
@@ -1540,6 +2054,11 @@ function assertRow(
1540
2054
  assertText(row.title, `${path}.title`);
1541
2055
  assertText(row.subtitle, `${path}.subtitle`);
1542
2056
  assertText(row.value, `${path}.value`);
2057
+ if (row.leadingBadge) {
2058
+ assertKey(row.leadingBadge.key, `${path}.leadingBadge.key`);
2059
+ assertText(row.leadingBadge.text, `${path}.leadingBadge.text`);
2060
+ }
2061
+ assertTextHelp(row.valueHelp, `${path}.valueHelp`);
1543
2062
  if (row.valueActionKey !== undefined) {
1544
2063
  assertKey(row.valueActionKey, `${path}.valueActionKey`);
1545
2064
  }
@@ -1572,6 +2091,9 @@ function assertRow(
1572
2091
  }
1573
2092
  assertTrailingAccessories(row.trailing, `${path}.trailing`);
1574
2093
  break;
2094
+ case 'buttonGroup':
2095
+ assertButtonGroup(row, path);
2096
+ break;
1575
2097
  case 'system':
1576
2098
  const presentation = 'presentation' in row ? row.presentation : undefined;
1577
2099
  if (presentation !== undefined && presentation !== 'market') {
@@ -1677,9 +2199,39 @@ function assertMediaPreview(value: unknown, path: string) {
1677
2199
  }
1678
2200
  }
1679
2201
 
1680
- export function validateSnapshot(
2202
+ function assertSnapshotContract(
1681
2203
  snapshot: NativeListSnapshot
1682
2204
  ): NativeListSnapshot {
2205
+ if (snapshot.disclosure !== undefined) {
2206
+ if (typeof snapshot.disclosure.expanded !== 'boolean')
2207
+ fail('snapshot.disclosure.expanded', 'must be a boolean');
2208
+ const inset = snapshot.disclosure.expandedTrailingInset;
2209
+ if (inset !== undefined && (!Number.isFinite(inset) || inset < 0))
2210
+ fail(
2211
+ 'snapshot.disclosure.expandedTrailingInset',
2212
+ 'must be finite and nonnegative'
2213
+ );
2214
+ }
2215
+ if (snapshot.structuralTransition) {
2216
+ assertKey(
2217
+ snapshot.structuralTransition.id,
2218
+ 'snapshot.structuralTransition.id'
2219
+ );
2220
+ if (snapshot.structuralTransition.anchorKey !== undefined)
2221
+ assertKey(
2222
+ snapshot.structuralTransition.anchorKey,
2223
+ 'snapshot.structuralTransition.anchorKey'
2224
+ );
2225
+ const duration = snapshot.structuralTransition.durationMs;
2226
+ if (
2227
+ duration !== undefined &&
2228
+ (!Number.isFinite(duration) || duration < 0 || duration > 2000)
2229
+ )
2230
+ fail(
2231
+ 'snapshot.structuralTransition.durationMs',
2232
+ 'must be finite within 0...2000'
2233
+ );
2234
+ }
1683
2235
  if (
1684
2236
  snapshot.capabilities?.refreshTriggerDistance !== undefined &&
1685
2237
  (!Number.isFinite(snapshot.capabilities.refreshTriggerDistance) ||
@@ -1695,6 +2247,18 @@ export function validateSnapshot(
1695
2247
  snapshot.theme?.imageFallbackBackground,
1696
2248
  'theme.imageFallbackBackground'
1697
2249
  );
2250
+ if (
2251
+ snapshot.theme?.successBackground !== undefined &&
2252
+ (typeof snapshot.theme.successBackground !== 'string' ||
2253
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(snapshot.theme.successBackground))
2254
+ )
2255
+ fail('theme.successBackground', 'must be a hex color');
2256
+ if (
2257
+ snapshot.theme?.rowHoverBackground !== undefined &&
2258
+ (typeof snapshot.theme.rowHoverBackground !== 'string' ||
2259
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(snapshot.theme.rowHoverBackground))
2260
+ )
2261
+ fail('theme.rowHoverBackground', 'must be a hex color');
1698
2262
  if (snapshot.schemaVersion !== 1) fail('snapshot.schemaVersion', 'must be 1');
1699
2263
  if (!Number.isSafeInteger(snapshot.generation) || snapshot.generation < 0) {
1700
2264
  fail('snapshot.generation', 'must be a non-negative safe integer');
@@ -1826,96 +2390,1971 @@ export function validateSnapshot(
1826
2390
  'supports at most one key in single mode'
1827
2391
  );
1828
2392
  }
1829
- return normalizeSnapshotStyles(snapshot);
1830
- }
1831
-
1832
- /**
1833
- * Resolves typography tokens to numbers. Returns the original snapshot when
1834
- * nothing needs resolving, so the common no-style path keeps object identity.
1835
- */
1836
- function normalizeSnapshotStyles(
1837
- snapshot: NativeListSnapshot
1838
- ): NativeListSnapshot {
1839
- let changed = false;
1840
- const rows = snapshot.rows.map((row) => {
1841
- const next = normalizeRowStyles(row);
1842
- if (next !== row) changed = true;
1843
- return next;
1844
- });
1845
- const emptyState = snapshot.emptyState
1846
- ? normalizeRowStyles(snapshot.emptyState)
1847
- : snapshot.emptyState;
1848
- const fixedFooter = snapshot.fixedFooter
1849
- ? normalizeRowStyles(snapshot.fixedFooter)
1850
- : snapshot.fixedFooter;
1851
- if (
1852
- !changed &&
1853
- emptyState === snapshot.emptyState &&
1854
- fixedFooter === snapshot.fixedFooter
1855
- ) {
1856
- return snapshot;
1857
- }
1858
- return { ...snapshot, rows, emptyState, fixedFooter };
2393
+ return snapshot;
1859
2394
  }
1860
2395
 
1861
- function assertPatchChanges(patch: RowPatch, index: number): void {
1862
- const path = `patches[${index}].changes`;
1863
- const patchedStyle = (patch.changes as { style?: unknown }).style;
1864
- if (patchedStyle !== undefined) {
1865
- assertRowStyle({ type: patch.type, style: patchedStyle } as RowModel, path);
1866
- }
1867
- // OneKey patch: partial balance updates retain a valid, current accessibility label.
1868
- if ('accessibilityLabel' in patch.changes) {
1869
- assertText(patch.changes.accessibilityLabel, `${path}.accessibilityLabel`);
1870
- }
1871
- // OneKey patch: partial updates may refer to an existing height but still require a valid policy.
1872
- if (
1873
- 'heightRounding' in patch.changes &&
1874
- patch.changes.heightRounding !== undefined &&
1875
- !['floor', 'nearest'].includes(patch.changes.heightRounding)
1876
- )
1877
- fail(`${path}.heightRounding`, 'must be floor or nearest');
1878
- if (
1879
- patch.changes.revision !== undefined &&
1880
- (!Number.isSafeInteger(patch.changes.revision) ||
1881
- patch.changes.revision < 0)
1882
- ) {
1883
- fail(`${path}.revision`, 'must be a non-negative safe integer');
1884
- }
2396
+ const COMMON_ROW_FIELDS = [
2397
+ 'height',
2398
+ 'heightRounding',
2399
+ 'testID',
2400
+ 'opacity',
2401
+ 'backgroundColor',
2402
+ 'backgroundFullWidth',
2403
+ 'pressDisabled',
2404
+ 'key',
2405
+ 'revision',
2406
+ 'sectionKey',
2407
+ 'groupId',
2408
+ 'groupPosition',
2409
+ 'size',
2410
+ 'density',
2411
+ 'disabled',
2412
+ 'selected',
2413
+ 'accessibilityLabel',
2414
+ 'separator',
2415
+ 'type',
2416
+ 'style',
2417
+ ];
1885
2418
 
1886
- switch (patch.type) {
1887
- case 'identity':
1888
- assertText(patch.changes.title, `${path}.title`);
1889
- assertText(patch.changes.subtitle, `${path}.subtitle`);
1890
- assertText(patch.changes.tertiary, `${path}.tertiary`);
1891
- if (
1892
- patch.changes.tertiaryTone !== undefined &&
1893
- !['secondary', 'info'].includes(patch.changes.tertiaryTone)
1894
- ) {
1895
- fail(`${path}.tertiaryTone`, 'must be secondary or info');
1896
- }
1897
- assertLeadingVisual(patch.changes.leading, `${path}.leading`);
1898
- assertTrailingAccessories(
1899
- patch.changes.leadingAction ? [patch.changes.leadingAction] : undefined,
1900
- `${path}.leadingAction`
1901
- );
1902
- if ((patch.changes.badges?.length ?? 0) > MAX_BADGES) {
1903
- fail(`${path}.badges`, `supports at most ${MAX_BADGES} badges`);
1904
- }
1905
- if ((patch.changes.trailing?.length ?? 0) > MAX_TRAILING_ACCESSORIES) {
1906
- fail(
1907
- `${path}.trailing`,
1908
- `supports at most ${MAX_TRAILING_ACCESSORIES} accessories`
1909
- );
1910
- }
1911
- assertTrailingAccessories(patch.changes.trailing, `${path}.trailing`);
1912
- break;
1913
- case 'rail':
1914
- assertText(patch.changes.title, `${path}.title`);
1915
- assertLeadingVisual(patch.changes.visual, `${path}.visual`);
1916
- break;
1917
- case 'activity':
1918
- assertActivity(patch.changes, path);
2419
+ const ROW_FIELDS: Readonly<Record<string, readonly string[]>> = {
2420
+ identity: [
2421
+ ...COMMON_ROW_FIELDS,
2422
+ 'contentHeight',
2423
+ 'longPressActionKey',
2424
+ 'titleMatch',
2425
+ 'titleActionKey',
2426
+ 'titleActionOnHover',
2427
+ 'subtitleSegments',
2428
+ 'presentation',
2429
+ 'leading',
2430
+ 'leadingAction',
2431
+ 'title',
2432
+ 'titleSuffixes',
2433
+ 'titleIcon',
2434
+ 'secondaryTitleIcon',
2435
+ 'titleImage',
2436
+ 'subtitle',
2437
+ 'tertiary',
2438
+ 'tertiaryTone',
2439
+ 'titleLines',
2440
+ 'subtitleLines',
2441
+ 'badges',
2442
+ 'trailing',
2443
+ 'draggable',
2444
+ ],
2445
+ walletGroup: [...COMMON_ROW_FIELDS, 'parent', 'children', 'draggable'],
2446
+ rail: [
2447
+ ...COMMON_ROW_FIELDS,
2448
+ 'visual',
2449
+ 'title',
2450
+ 'status',
2451
+ 'badge',
2452
+ 'draggable',
2453
+ ],
2454
+ activity: [
2455
+ ...COMMON_ROW_FIELDS,
2456
+ 'leading',
2457
+ 'hideLeading',
2458
+ 'secondaryLeading',
2459
+ 'title',
2460
+ 'description',
2461
+ 'status',
2462
+ 'primaryAmount',
2463
+ 'secondaryAmount',
2464
+ 'amounts',
2465
+ 'badges',
2466
+ 'presentation',
2467
+ 'fee',
2468
+ 'descriptionActionKey',
2469
+ 'descriptionActionStart',
2470
+ 'footerActions',
2471
+ ],
2472
+ message: [
2473
+ ...COMMON_ROW_FIELDS,
2474
+ 'presentation',
2475
+ 'unread',
2476
+ 'leading',
2477
+ 'title',
2478
+ 'body',
2479
+ 'bodyLines',
2480
+ 'time',
2481
+ 'thumbnail',
2482
+ ],
2483
+ dataRow: [
2484
+ ...COMMON_ROW_FIELDS,
2485
+ 'leading',
2486
+ 'columns',
2487
+ 'trailing',
2488
+ 'checkbox',
2489
+ 'index',
2490
+ 'badge',
2491
+ 'badges',
2492
+ 'favorite',
2493
+ 'favoriteActive',
2494
+ ],
2495
+ market: [
2496
+ ...COMMON_ROW_FIELDS,
2497
+ 'variant',
2498
+ 'webTable',
2499
+ 'metrics',
2500
+ 'leadingAction',
2501
+ 'leading',
2502
+ 'title',
2503
+ 'subtitle',
2504
+ 'subtitlePrefix',
2505
+ 'subtitleSegments',
2506
+ 'price',
2507
+ 'priceSegments',
2508
+ 'change',
2509
+ 'badges',
2510
+ 'pressActionKey',
2511
+ 'pressInActionKey',
2512
+ 'longPressActionKey',
2513
+ 'diagnostics',
2514
+ ],
2515
+ mediaTile: [
2516
+ ...COMMON_ROW_FIELDS,
2517
+ 'variant',
2518
+ 'media',
2519
+ 'image',
2520
+ 'imageState',
2521
+ 'networkImage',
2522
+ 'title',
2523
+ 'subtitle',
2524
+ 'badge',
2525
+ 'closeActionKey',
2526
+ ],
2527
+ metricCard: [
2528
+ ...COMMON_ROW_FIELDS,
2529
+ 'variant',
2530
+ 'title',
2531
+ 'value',
2532
+ 'subtitle',
2533
+ 'trend',
2534
+ 'trendTone',
2535
+ 'visual',
2536
+ 'badge',
2537
+ 'metrics',
2538
+ 'progress',
2539
+ ],
2540
+ sectionHeader: [
2541
+ ...COMMON_ROW_FIELDS,
2542
+ 'sticky',
2543
+ 'valueActionTestID',
2544
+ 'valueSegments',
2545
+ 'titleActionKey',
2546
+ 'titleActionOnHover',
2547
+ 'presentation',
2548
+ 'indexTitle',
2549
+ 'variant',
2550
+ 'title',
2551
+ 'leadingBadge',
2552
+ 'titleLoading',
2553
+ 'subtitle',
2554
+ 'value',
2555
+ 'valueHelp',
2556
+ 'valueActionKey',
2557
+ 'titleIcon',
2558
+ 'valueIcon',
2559
+ 'checkbox',
2560
+ ],
2561
+ action: [
2562
+ ...COMMON_ROW_FIELDS,
2563
+ 'presentation',
2564
+ 'title',
2565
+ 'actionKey',
2566
+ 'tone',
2567
+ 'icon',
2568
+ 'checkbox',
2569
+ 'trailing',
2570
+ ],
2571
+ buttonGroup: [...COMMON_ROW_FIELDS, 'buttons'],
2572
+ system: [
2573
+ ...COMMON_ROW_FIELDS,
2574
+ 'variant',
2575
+ 'presentation',
2576
+ 'loadingStyle',
2577
+ 'message',
2578
+ 'actionKey',
2579
+ 'actionText',
2580
+ 'title',
2581
+ 'borderColor',
2582
+ ],
2583
+ };
2584
+
2585
+ const COMMON_PATCH_FIELDS = [
2586
+ 'height',
2587
+ 'heightRounding',
2588
+ 'opacity',
2589
+ 'pressDisabled',
2590
+ 'revision',
2591
+ 'disabled',
2592
+ 'selected',
2593
+ 'accessibilityLabel',
2594
+ 'separator',
2595
+ 'style',
2596
+ ];
2597
+
2598
+ const PATCH_FIELDS: Readonly<Record<string, readonly string[]>> = {
2599
+ identity: [
2600
+ ...COMMON_PATCH_FIELDS,
2601
+ 'contentHeight',
2602
+ 'longPressActionKey',
2603
+ 'titleMatch',
2604
+ 'titleActionKey',
2605
+ 'titleActionOnHover',
2606
+ 'subtitleSegments',
2607
+ 'leading',
2608
+ 'leadingAction',
2609
+ 'title',
2610
+ 'titleSuffixes',
2611
+ 'titleIcon',
2612
+ 'secondaryTitleIcon',
2613
+ 'titleImage',
2614
+ 'subtitle',
2615
+ 'tertiary',
2616
+ 'tertiaryTone',
2617
+ 'subtitleLines',
2618
+ 'badges',
2619
+ 'trailing',
2620
+ ],
2621
+ rail: [...COMMON_PATCH_FIELDS, 'title', 'visual', 'status', 'badge'],
2622
+ activity: [
2623
+ ...COMMON_PATCH_FIELDS,
2624
+ 'presentation',
2625
+ 'leading',
2626
+ 'title',
2627
+ 'badges',
2628
+ 'status',
2629
+ 'hideLeading',
2630
+ 'secondaryLeading',
2631
+ 'description',
2632
+ 'primaryAmount',
2633
+ 'secondaryAmount',
2634
+ 'amounts',
2635
+ 'fee',
2636
+ 'descriptionActionKey',
2637
+ 'descriptionActionStart',
2638
+ 'footerActions',
2639
+ ],
2640
+ message: [
2641
+ ...COMMON_PATCH_FIELDS,
2642
+ 'presentation',
2643
+ 'title',
2644
+ 'unread',
2645
+ 'body',
2646
+ 'bodyLines',
2647
+ 'time',
2648
+ 'thumbnail',
2649
+ ],
2650
+ dataRow: [
2651
+ ...COMMON_PATCH_FIELDS,
2652
+ 'leading',
2653
+ 'badges',
2654
+ 'trailing',
2655
+ 'badge',
2656
+ 'columns',
2657
+ 'checkbox',
2658
+ 'index',
2659
+ 'favorite',
2660
+ 'favoriteActive',
2661
+ ],
2662
+ market: [
2663
+ ...COMMON_PATCH_FIELDS,
2664
+ 'longPressActionKey',
2665
+ 'subtitleSegments',
2666
+ 'leading',
2667
+ 'leadingAction',
2668
+ 'title',
2669
+ 'subtitle',
2670
+ 'badges',
2671
+ 'webTable',
2672
+ 'metrics',
2673
+ 'price',
2674
+ 'priceSegments',
2675
+ 'change',
2676
+ 'pressActionKey',
2677
+ 'pressInActionKey',
2678
+ 'diagnostics',
2679
+ ],
2680
+ mediaTile: [
2681
+ ...COMMON_PATCH_FIELDS,
2682
+ 'title',
2683
+ 'subtitle',
2684
+ 'badge',
2685
+ 'media',
2686
+ 'image',
2687
+ 'imageState',
2688
+ 'networkImage',
2689
+ 'closeActionKey',
2690
+ ],
2691
+ metricCard: [
2692
+ ...COMMON_PATCH_FIELDS,
2693
+ 'title',
2694
+ 'subtitle',
2695
+ 'visual',
2696
+ 'badge',
2697
+ 'variant',
2698
+ 'value',
2699
+ 'trend',
2700
+ 'trendTone',
2701
+ 'metrics',
2702
+ 'progress',
2703
+ ],
2704
+ sectionHeader: [
2705
+ ...COMMON_PATCH_FIELDS,
2706
+ 'titleActionKey',
2707
+ 'titleActionOnHover',
2708
+ 'title',
2709
+ 'titleIcon',
2710
+ 'subtitle',
2711
+ 'checkbox',
2712
+ 'variant',
2713
+ 'value',
2714
+ 'leadingBadge',
2715
+ 'titleLoading',
2716
+ 'valueHelp',
2717
+ 'valueActionKey',
2718
+ 'valueIcon',
2719
+ ],
2720
+ action: [
2721
+ ...COMMON_PATCH_FIELDS,
2722
+ 'title',
2723
+ 'trailing',
2724
+ 'checkbox',
2725
+ 'tone',
2726
+ 'icon',
2727
+ ],
2728
+ buttonGroup: [...COMMON_PATCH_FIELDS, 'buttons'],
2729
+ system: ['revision', 'disabled', 'message'],
2730
+ };
2731
+
2732
+ function protocolObject(value: unknown, path: string): Record<string, unknown> {
2733
+ if (!value || typeof value !== 'object' || Array.isArray(value))
2734
+ fail(path, 'must be an object');
2735
+ return value as Record<string, unknown>;
2736
+ }
2737
+
2738
+ function protocolKey(value: unknown, path: string): void {
2739
+ if (typeof value !== 'string' || value.trim().length === 0)
2740
+ fail(path, 'must be a non-blank string');
2741
+ }
2742
+
2743
+ const PROTOCOL_ARRAY_FIELDS = new Set([
2744
+ 'columns',
2745
+ 'titleSuffixes',
2746
+ 'cells',
2747
+ 'points',
2748
+ 'images',
2749
+ 'overlays',
2750
+ 'badges',
2751
+ 'trailing',
2752
+ 'footerActions',
2753
+ 'buttons',
2754
+ 'amounts',
2755
+ 'metrics',
2756
+ 'children',
2757
+ 'subtitleSegments',
2758
+ 'titleMatch',
2759
+ 'selectedKeys',
2760
+ 'segments',
2761
+ 'hoverSecondary',
2762
+ 'hoverImages',
2763
+ 'secondaryBadges',
2764
+ 'fallbackUris',
2765
+ 'probeOrder',
2766
+ 'priceSegments',
2767
+ 'textSegments',
2768
+ 'secondaryTextSegments',
2769
+ 'primaryTextSegments',
2770
+ ]);
2771
+ const PROTOCOL_NUMBER_FIELDS = new Set([
2772
+ 'leadingContentMaxWidthRatio',
2773
+ 'height',
2774
+ 'width',
2775
+ 'fontSize',
2776
+ 'lineHeight',
2777
+ 'opacity',
2778
+ 'offsetY',
2779
+ 'offsetX',
2780
+ 'cornerRadius',
2781
+ 'borderWidth',
2782
+ 'horizontalPadding',
2783
+ 'verticalPadding',
2784
+ 'leadingGap',
2785
+ 'lineGap',
2786
+ 'titleBadgeGap',
2787
+ 'trailingGap',
2788
+ 'start',
2789
+ 'end',
2790
+ 'padding',
2791
+ 'offset',
2792
+ 'overscan',
2793
+ 'minWidth',
2794
+ 'flex',
2795
+ 'paddingStart',
2796
+ 'paddingEnd',
2797
+ 'changeWidth',
2798
+ 'changeHeight',
2799
+ 'changeCornerRadius',
2800
+ 'contentTrailingGap',
2801
+ 'subtitleTrailingPadding',
2802
+ 'partGap',
2803
+ 'contentPadding',
2804
+ 'contentPaddingHorizontal',
2805
+ 'contentPaddingTop',
2806
+ 'contentPaddingBottom',
2807
+ 'itemSpacing',
2808
+ 'gridColumns',
2809
+ ]);
2810
+
2811
+ /** Validate only shapes that renderers dereference, not display budgets. */
2812
+ function assertProtocolFields(
2813
+ value: unknown,
2814
+ path: string,
2815
+ parentField = ''
2816
+ ): void {
2817
+ if (value === undefined || value === null || typeof value !== 'object')
2818
+ return;
2819
+ if (Array.isArray(value)) {
2820
+ for (const [index, item] of value.entries()) {
2821
+ const itemPath = `${path}[${index}]`;
2822
+ if (
2823
+ ['selectedKeys', 'fallbackUris', 'probeOrder'].includes(parentField)
2824
+ ) {
2825
+ if (typeof item !== 'string') fail(itemPath, 'must be a string');
2826
+ } else if (parentField === 'points') {
2827
+ if (typeof item !== 'number') fail(itemPath, 'must be a finite number');
2828
+ } else if (parentField === 'hoverImages' && item === null) continue;
2829
+ else protocolObject(item, itemPath);
2830
+ assertProtocolFields(item, itemPath, parentField);
2831
+ }
2832
+ return;
2833
+ }
2834
+ const object = value as Record<string, unknown>;
2835
+ if (parentField === 'fallbackIcon') {
2836
+ protocolKey(object.name, `${path}.name`);
2837
+ if (
2838
+ object.size !== undefined &&
2839
+ (typeof object.size !== 'number' ||
2840
+ !Number.isFinite(object.size) ||
2841
+ object.size <= 0 ||
2842
+ object.size > 40)
2843
+ )
2844
+ fail(`${path}.size`, 'must be within (0, 40]');
2845
+ for (const field of ['tintColor', 'backgroundColor'] as const) {
2846
+ const color = object[field];
2847
+ if (
2848
+ color !== undefined &&
2849
+ (typeof color !== 'string' ||
2850
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(color))
2851
+ )
2852
+ fail(`${path}.${field}`, 'must be a hex color');
2853
+ }
2854
+ }
2855
+ if (
2856
+ parentField === 'overlays' &&
2857
+ object.fallbackIcon !== undefined &&
2858
+ !object.image
2859
+ )
2860
+ fail(`${path}.fallbackIcon`, 'requires image');
2861
+ if (
2862
+ !path.includes('.style.') &&
2863
+ ['image', 'networkImage', 'thumbnail', 'images', 'hoverImages'].includes(
2864
+ parentField
2865
+ ) &&
2866
+ typeof object.uri !== 'string'
2867
+ )
2868
+ fail(`${path}.uri`, 'must be a string');
2869
+ Object.entries(value).forEach(([field, item]) => {
2870
+ if (item === undefined) return;
2871
+ if (field === 'headers') {
2872
+ const headers = protocolObject(item, `${path}.headers`);
2873
+ for (const [name, headerValue] of Object.entries(headers)) {
2874
+ if (!name.trim() || typeof headerValue !== 'string')
2875
+ fail(`${path}.headers`, 'must contain string headers');
2876
+ }
2877
+ return;
2878
+ }
2879
+ const fieldPath = `${path}.${field}`;
2880
+ if (
2881
+ !path.endsWith('.style') &&
2882
+ PROTOCOL_ARRAY_FIELDS.has(field) &&
2883
+ !Array.isArray(item)
2884
+ )
2885
+ fail(fieldPath, 'must be an array');
2886
+ if (PROTOCOL_NUMBER_FIELDS.has(field) && typeof item !== 'number')
2887
+ fail(fieldPath, 'must be a finite number');
2888
+ if (
2889
+ PROTOCOL_NUMBER_FIELDS.has(field) &&
2890
+ typeof item === 'number' &&
2891
+ item < 0 &&
2892
+ !['offsetX', 'offsetY'].includes(field)
2893
+ )
2894
+ fail(fieldPath, 'must be non-negative');
2895
+ if (
2896
+ parentField === 'overlays' &&
2897
+ field === 'fontWeight' &&
2898
+ !['regular', 'medium', 'semibold', 'bold'].includes(item as string)
2899
+ )
2900
+ fail(fieldPath, 'must be regular, medium, semibold, or bold');
2901
+ if (field === 'buttonStyle' && item !== 'tertiary')
2902
+ fail(fieldPath, 'must be tertiary');
2903
+ if (field === 'hideLeading' && typeof item !== 'boolean')
2904
+ fail(fieldPath, 'must be boolean');
2905
+ if (
2906
+ field === 'key' ||
2907
+ field === 'sectionKey' ||
2908
+ field === 'groupId' ||
2909
+ field === 'actionKey' ||
2910
+ field.endsWith('ActionKey')
2911
+ )
2912
+ protocolKey(item, fieldPath);
2913
+ if (
2914
+ (field === 'uri' || field === 'fallbackUri') &&
2915
+ typeof item !== 'string'
2916
+ )
2917
+ fail(fieldPath, 'must be a string');
2918
+ if (
2919
+ (field === 'style' &&
2920
+ !(item === 'subscript' && /[Ss]egments\[/.test(path))) ||
2921
+ field === 'container'
2922
+ )
2923
+ protocolObject(item, fieldPath);
2924
+ if (
2925
+ path.endsWith('.style') &&
2926
+ [
2927
+ 'title',
2928
+ 'subtitle',
2929
+ 'tertiary',
2930
+ 'body',
2931
+ 'time',
2932
+ 'price',
2933
+ 'change',
2934
+ 'columns',
2935
+ 'columnSecondary',
2936
+ 'value',
2937
+ 'valueSecondary',
2938
+ 'badge',
2939
+ 'description',
2940
+ 'status',
2941
+ 'primaryAmount',
2942
+ 'secondaryAmount',
2943
+ 'trend',
2944
+ 'message',
2945
+ 'actionText',
2946
+ ].includes(field)
2947
+ )
2948
+ protocolObject(item, fieldPath);
2949
+ assertProtocolFields(item, fieldPath, field);
2950
+ });
2951
+ }
2952
+
2953
+ function assertRowProtocol(row: RowModel, path: string): void {
2954
+ protocolObject(row, path);
2955
+ assertRowType(row.type, path);
2956
+ protocolKey(row.key, `${path}.key`);
2957
+ assertCoreRow(row, path);
2958
+ assertProtocolFields(row, path);
2959
+ for (const field of ['leading', 'visual', 'secondaryLeading'] as const) {
2960
+ const visual = (row as unknown as Record<string, unknown>)[field];
2961
+ if (
2962
+ visual !== undefined ||
2963
+ (field === 'leading' &&
2964
+ (row.type === 'identity' || row.type === 'market'))
2965
+ ) {
2966
+ const object = protocolObject(visual, `${path}.${field}`);
2967
+ if (object.kind === 'stackedImages' && !Array.isArray(object.images))
2968
+ fail(`${path}.${field}.images`, 'must be an array');
2969
+ }
2970
+ }
2971
+ for (const field of [
2972
+ 'title',
2973
+ 'subtitle',
2974
+ 'tertiary',
2975
+ 'body',
2976
+ 'time',
2977
+ 'price',
2978
+ 'indexTitle',
2979
+ ] as const) {
2980
+ const value = (row as unknown as Record<string, unknown>)[field];
2981
+ if (value !== undefined && typeof value !== 'string')
2982
+ fail(`${path}.${field}`, 'must be a string');
2983
+ }
2984
+ if (row.height !== undefined && row.height < 0)
2985
+ fail(`${path}.height`, 'must be non-negative');
2986
+ if (row.type === 'identity') {
2987
+ if (isDevelopment()) assertIdentityExtras(row, path);
2988
+ if (row.titleSuffixes !== undefined && !Array.isArray(row.titleSuffixes))
2989
+ fail(`${path}.titleSuffixes`, 'must be an array');
2990
+ row.titleSuffixes?.forEach((suffix, index) => {
2991
+ protocolObject(suffix, `${path}.titleSuffixes[${index}]`);
2992
+ if (
2993
+ typeof suffix.text !== 'string' ||
2994
+ !['secondary', 'disabled'].includes(suffix.tone)
2995
+ )
2996
+ fail(`${path}.titleSuffixes[${index}]`, 'invalid title suffix');
2997
+ if (
2998
+ suffix.maxWidth !== undefined &&
2999
+ (!Number.isFinite(suffix.maxWidth) ||
3000
+ suffix.maxWidth < 0 ||
3001
+ suffix.maxWidth > 4096)
3002
+ )
3003
+ fail(
3004
+ `${path}.titleSuffixes[${index}].maxWidth`,
3005
+ 'must be finite within 0...4096'
3006
+ );
3007
+ });
3008
+ let end = 0;
3009
+ row.titleMatch?.forEach((match) => {
3010
+ if (
3011
+ !Number.isInteger(match.start) ||
3012
+ !Number.isInteger(match.end) ||
3013
+ match.start < end ||
3014
+ match.end <= match.start ||
3015
+ match.end > row.title.length
3016
+ )
3017
+ fail(`${path}.titleMatch`, 'invalid text range');
3018
+ end = match.end;
3019
+ });
3020
+ }
3021
+ if (row.type === 'buttonGroup' && isDevelopment())
3022
+ assertButtonGroup(row, path);
3023
+ if (row.type === 'sectionHeader' && isDevelopment())
3024
+ assertTextHelp(row.valueHelp, `${path}.valueHelp`);
3025
+ if (row.type === 'mediaTile' && row.media) {
3026
+ protocolObject(row.media.source, `${path}.media.source`);
3027
+ if (!Array.isArray(row.media.probeOrder))
3028
+ fail(`${path}.media.probeOrder`, 'must be an array');
3029
+ }
3030
+ if (row.type === 'walletGroup') {
3031
+ protocolObject(row.parent, `${path}.parent`);
3032
+ if (!Array.isArray(row.children))
3033
+ fail(`${path}.children`, 'must be an array');
3034
+ const members = [row.parent, ...row.children];
3035
+ const keys = new Set<string>();
3036
+ if (row.parent.key !== row.key)
3037
+ fail(`${path}.parent.key`, 'must match its group');
3038
+ members.forEach((member, index) => {
3039
+ assertRowProtocol(member, `${path}.members[${index}]`);
3040
+ if (member.type !== 'identity' || keys.has(member.key))
3041
+ fail(path, 'invalid wallet member identity');
3042
+ keys.add(member.key);
3043
+ });
3044
+ }
3045
+ if (row.type === 'dataRow') {
3046
+ if (!Array.isArray(row.columns))
3047
+ fail(`${path}.columns`, 'must be an array');
3048
+ row.columns.forEach((column, index) => {
3049
+ const columnPath = `${path}.columns[${index}]`;
3050
+ protocolObject(column, columnPath);
3051
+ if (isDevelopment()) assertIdentityExtras(column, columnPath);
3052
+ });
3053
+ if (isDevelopment())
3054
+ assertTrailingAccessories(row.trailing, `${path}.trailing`);
3055
+ }
3056
+ if (row.type === 'market') {
3057
+ protocolObject(row.change, `${path}.change`);
3058
+ assertMarketMetrics(row.metrics, `${path}.metrics`);
3059
+ if (row.webTable) {
3060
+ const { columns, cells } = row.webTable;
3061
+ if (
3062
+ !Array.isArray(columns) ||
3063
+ !Array.isArray(cells) ||
3064
+ columns.length !== cells.length
3065
+ )
3066
+ fail(`${path}.webTable`, 'columns and cells must match');
3067
+ const keys = new Set<string>();
3068
+ columns.forEach((column, index) => {
3069
+ protocolKey(column.key, `${path}.webTable.columns[${index}].key`);
3070
+ if (keys.has(column.key) || cells[index]?.key !== column.key)
3071
+ fail(`${path}.webTable`, 'invalid column identity');
3072
+ keys.add(column.key);
3073
+ const cell = cells[index];
3074
+ if (!['favorite', 'asset', 'text', 'sparkline'].includes(cell.kind))
3075
+ fail(`${path}.webTable.cells[${index}]`, 'unsupported cell kind');
3076
+ if (cell.kind === 'asset')
3077
+ protocolObject(cell.title, `${path}.webTable.cells[${index}].title`);
3078
+ if (
3079
+ (cell.kind === 'asset' || cell.kind === 'text') &&
3080
+ cell.secondary !== undefined &&
3081
+ !Array.isArray(cell.secondary)
3082
+ )
3083
+ fail(
3084
+ `${path}.webTable.cells[${index}].secondary`,
3085
+ 'must be an array'
3086
+ );
3087
+ if (cell.kind === 'text' && !Array.isArray(cell.primary))
3088
+ fail(`${path}.webTable.cells[${index}].primary`, 'must be an array');
3089
+ // The Web renderer spreads samples into Math.min/Math.max.
3090
+ if (
3091
+ cell.kind === 'sparkline' &&
3092
+ (!Array.isArray(cell.points) || cell.points.length > 256)
3093
+ )
3094
+ fail(
3095
+ `${path}.webTable.cells[${index}].points`,
3096
+ 'must be an array of at most 256 samples'
3097
+ );
3098
+ });
3099
+ }
3100
+ }
3101
+ }
3102
+
3103
+ function assertSnapshotProtocol(snapshot: NativeListSnapshot): void {
3104
+ protocolObject(snapshot, 'snapshot');
3105
+ if (snapshot.disclosure !== undefined) {
3106
+ protocolObject(snapshot.disclosure, 'snapshot.disclosure');
3107
+ if (typeof snapshot.disclosure.expanded !== 'boolean')
3108
+ fail('snapshot.disclosure.expanded', 'must be a boolean');
3109
+ const inset = snapshot.disclosure.expandedTrailingInset;
3110
+ if (inset !== undefined && (!Number.isFinite(inset) || inset < 0))
3111
+ fail(
3112
+ 'snapshot.disclosure.expandedTrailingInset',
3113
+ 'must be finite and nonnegative'
3114
+ );
3115
+ }
3116
+ if (snapshot.structuralTransition) {
3117
+ protocolObject(
3118
+ snapshot.structuralTransition,
3119
+ 'snapshot.structuralTransition'
3120
+ );
3121
+ protocolKey(
3122
+ snapshot.structuralTransition.id,
3123
+ 'snapshot.structuralTransition.id'
3124
+ );
3125
+ if (snapshot.structuralTransition.anchorKey !== undefined)
3126
+ protocolKey(
3127
+ snapshot.structuralTransition.anchorKey,
3128
+ 'snapshot.structuralTransition.anchorKey'
3129
+ );
3130
+ const duration = snapshot.structuralTransition.durationMs;
3131
+ if (
3132
+ duration !== undefined &&
3133
+ (!Number.isFinite(duration) || duration < 0 || duration > 2000)
3134
+ )
3135
+ fail(
3136
+ 'snapshot.structuralTransition.durationMs',
3137
+ 'must be finite within 0...2000'
3138
+ );
3139
+ }
3140
+ if (
3141
+ snapshot.theme?.successBackground !== undefined &&
3142
+ (typeof snapshot.theme.successBackground !== 'string' ||
3143
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(snapshot.theme.successBackground))
3144
+ )
3145
+ fail('theme.successBackground', 'must be a hex color');
3146
+ if (
3147
+ snapshot.theme?.rowHoverBackground !== undefined &&
3148
+ (typeof snapshot.theme.rowHoverBackground !== 'string' ||
3149
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(snapshot.theme.rowHoverBackground))
3150
+ )
3151
+ fail('theme.rowHoverBackground', 'must be a hex color');
3152
+ if (snapshot.schemaVersion !== 1) fail('snapshot.schemaVersion', 'must be 1');
3153
+ if (!Number.isSafeInteger(snapshot.generation) || snapshot.generation < 0)
3154
+ fail('snapshot.generation', 'must be a non-negative safe integer');
3155
+ protocolObject(snapshot.layout, 'snapshot.layout');
3156
+ assertProtocolFields(snapshot.layout, 'snapshot.layout');
3157
+ if (
3158
+ snapshot.layout.orientation !== undefined &&
3159
+ !['vertical', 'horizontal'].includes(snapshot.layout.orientation)
3160
+ )
3161
+ fail('snapshot.layout.orientation', 'is not supported');
3162
+ if (!['linear', 'sectioned', 'grid', 'table'].includes(snapshot.layout.kind))
3163
+ fail('snapshot.layout.kind', 'is not supported');
3164
+ if (!Array.isArray(snapshot.rows)) fail('snapshot.rows', 'must be an array');
3165
+ if (
3166
+ snapshot.layout.kind === 'grid' &&
3167
+ (!Number.isInteger(snapshot.layout.gridColumns) ||
3168
+ (snapshot.layout.gridColumns ?? 0) < 1 ||
3169
+ (snapshot.layout.gridColumns ?? 0) > 7)
3170
+ )
3171
+ fail('snapshot.layout.gridColumns', 'must be an integer from 1 to 7');
3172
+ const keys = new Set<string>();
3173
+ for (const [index, row] of snapshot.rows.entries()) {
3174
+ assertRowProtocol(row, `rows[${index}]`);
3175
+ if (keys.has(row.key)) fail(`rows[${index}].key`, 'duplicate row identity');
3176
+ keys.add(row.key);
3177
+ }
3178
+ if (snapshot.emptyState) assertRowProtocol(snapshot.emptyState, 'emptyState');
3179
+ if (snapshot.fixedFooter)
3180
+ assertRowProtocol(snapshot.fixedFooter, 'fixedFooter');
3181
+ if (snapshot.selection) {
3182
+ if (!Array.isArray(snapshot.selection.selectedKeys))
3183
+ fail('snapshot.selection.selectedKeys', 'must be an array');
3184
+ snapshot.selection.selectedKeys.forEach((key) => {
3185
+ if (!keys.has(key))
3186
+ fail('snapshot.selection.selectedKeys', 'unknown row identity');
3187
+ });
3188
+ }
3189
+ }
3190
+
3191
+ function isRecord(value: unknown): value is Record<string, unknown> {
3192
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
3193
+ }
3194
+
3195
+ function isAllowedImageUri(value: unknown): value is string {
3196
+ // Keep native file, content, Photos and bundled-resource URIs alongside web images.
3197
+ // Android Release uses android.resource: instead of Metro's HTTP asset URLs.
3198
+ return (
3199
+ typeof value === 'string' &&
3200
+ value.trim().length > 0 &&
3201
+ (!/^[a-z][a-z\d+.-]*:/i.test(value) ||
3202
+ /^(https?|file|content|ph|assets-library|asset|res|android\.resource|blob|onekey-avatar):/i.test(
3203
+ value
3204
+ ) ||
3205
+ /^data:image\//i.test(value))
3206
+ );
3207
+ }
3208
+
3209
+ const IMAGE_FIELDS = [
3210
+ 'uri',
3211
+ 'width',
3212
+ 'height',
3213
+ 'headers',
3214
+ 'contentFit',
3215
+ 'cachePolicy',
3216
+ 'autoplay',
3217
+ 'optimizeTos',
3218
+ 'overscan',
3219
+ 'loadingStrategy',
3220
+ 'fallbackUri',
3221
+ 'fallbackUris',
3222
+ 'retryTimes',
3223
+ ];
3224
+ const ICON_FIELDS = [
3225
+ 'name',
3226
+ 'tintColor',
3227
+ 'backgroundColor',
3228
+ 'size',
3229
+ 'accessibilityLabel',
3230
+ 'hoverActionKey',
3231
+ ];
3232
+ const VISUAL_FIELDS = [
3233
+ 'kind',
3234
+ 'name',
3235
+ 'image',
3236
+ 'images',
3237
+ 'networkImage',
3238
+ 'shape',
3239
+ 'tintColor',
3240
+ 'backgroundColor',
3241
+ 'fallbackIcon',
3242
+ 'fallbackText',
3243
+ 'fallbackTextColor',
3244
+ 'overlays',
3245
+ 'borderStyle',
3246
+ 'borderColor',
3247
+ 'cornerIcon',
3248
+ ];
3249
+ const TEXT_STYLE_FIELDS = [
3250
+ 'token',
3251
+ 'fontSize',
3252
+ 'fontWeight',
3253
+ 'color',
3254
+ 'lineHeight',
3255
+ 'lines',
3256
+ 'truncate',
3257
+ 'alignment',
3258
+ 'verticalAlignment',
3259
+ 'offsetY',
3260
+ ];
3261
+ const ACCESSORY_FIELDS: Readonly<Record<string, readonly string[]>> = {
3262
+ value: ['kind', 'text', 'secondary', 'textSegments'],
3263
+ valuePair: [
3264
+ 'kind',
3265
+ 'primary',
3266
+ 'secondary',
3267
+ 'primaryFontWeight',
3268
+ 'primaryHelp',
3269
+ 'primaryTextSegments',
3270
+ 'secondaryTextSegments',
3271
+ 'primaryTone',
3272
+ 'secondaryTone',
3273
+ ],
3274
+ button: [
3275
+ 'kind',
3276
+ 'label',
3277
+ 'actionKey',
3278
+ 'disabled',
3279
+ 'testID',
3280
+ 'accessibilityLabel',
3281
+ 'textColor',
3282
+ 'backgroundColor',
3283
+ 'pressedBackgroundColor',
3284
+ 'hoverBackgroundColor',
3285
+ 'focusRingColor',
3286
+ ],
3287
+ icon: [
3288
+ 'kind',
3289
+ 'name',
3290
+ 'tintColor',
3291
+ 'buttonStyle',
3292
+ 'disabled',
3293
+ 'actionKey',
3294
+ 'testID',
3295
+ 'hoverActionKey',
3296
+ 'accessibilityLabel',
3297
+ ],
3298
+ checkbox: ['kind', 'state', 'disabled', 'loading', 'target', 'actionKey'],
3299
+ radio: ['kind', 'checked', 'disabled', 'actionKey'],
3300
+ switch: ['kind', 'value', 'disabled', 'actionKey'],
3301
+ chevron: ['kind', 'actionKey'],
3302
+ menu: ['kind', 'actionKey'],
3303
+ drag: ['kind', 'actionKey'],
3304
+ spinner: ['kind'],
3305
+ progress: ['kind', 'value'],
3306
+ };
3307
+
3308
+ const REQUIRED_ROW_FIELDS: Readonly<Record<string, readonly string[]>> = {
3309
+ identity: ['title', 'leading'],
3310
+ walletGroup: ['parent', 'children'],
3311
+ rail: ['title', 'visual'],
3312
+ activity: ['title', 'leading'],
3313
+ message: ['title', 'body', 'time'],
3314
+ dataRow: ['columns'],
3315
+ market: ['title', 'leading', 'variant', 'price', 'change'],
3316
+ mediaTile: ['title', 'variant'],
3317
+ metricCard: ['title', 'value'],
3318
+ sectionHeader: ['title', 'sectionKey'],
3319
+ action: ['title', 'actionKey'],
3320
+ buttonGroup: ['buttons'],
3321
+ system: ['variant'],
3322
+ };
3323
+
3324
+ function assertCoreRow(row: RowModel, path: string): void {
3325
+ const object = row as unknown as Record<string, unknown>;
3326
+ for (const key of REQUIRED_ROW_FIELDS[row.type]) {
3327
+ const value = object[key];
3328
+ if (value === undefined || value === null)
3329
+ fail(`${path}.${key}`, 'required field');
3330
+ if (
3331
+ ['title', 'body', 'time', 'price', 'value', 'variant'].includes(key) &&
3332
+ typeof value !== 'string'
3333
+ )
3334
+ fail(`${path}.${key}`, 'must be a string');
3335
+ }
3336
+ if (row.type === 'market') {
3337
+ if (!row.price.trim()) fail(`${path}.price`, 'must be nonblank');
3338
+ if (typeof row.change?.text !== 'string')
3339
+ fail(`${path}.change.text`, 'must be a string');
3340
+ }
3341
+ if (row.type === 'activity') {
3342
+ row.amounts?.forEach((amount, index) => {
3343
+ protocolKey(amount.key, `${path}.amounts[${index}].key`);
3344
+ if (typeof amount.text !== 'string')
3345
+ fail(`${path}.amounts[${index}].text`, 'required financial text');
3346
+ });
3347
+ if (row.fee && typeof row.fee.primary !== 'string')
3348
+ fail(`${path}.fee.primary`, 'required financial text');
3349
+ row.footerActions?.forEach((action, index) => {
3350
+ protocolKey(action.key, `${path}.footerActions[${index}].key`);
3351
+ protocolKey(action.label, `${path}.footerActions[${index}].label`);
3352
+ });
3353
+ }
3354
+ if (row.type === 'action') protocolKey(row.actionKey, `${path}.actionKey`);
3355
+ if (row.type === 'sectionHeader')
3356
+ protocolKey(row.sectionKey, `${path}.sectionKey`);
3357
+ if (
3358
+ row.type === 'system' &&
3359
+ ['retry', 'warning', 'noMatch'].includes(row.variant)
3360
+ ) {
3361
+ if (typeof object.message !== 'string')
3362
+ fail(`${path}.message`, 'must be a string');
3363
+ if (row.variant === 'retry')
3364
+ protocolKey(row.actionKey, `${path}.actionKey`);
3365
+ }
3366
+ if (row.type === 'dataRow') {
3367
+ if (!Array.isArray(row.columns) || row.columns.length === 0)
3368
+ fail(`${path}.columns`, 'required columns');
3369
+ row.columns.forEach((column, index) => {
3370
+ protocolObject(column, `${path}.columns[${index}]`);
3371
+ protocolKey(column.key, `${path}.columns[${index}].key`);
3372
+ if (typeof column.text !== 'string')
3373
+ fail(`${path}.columns[${index}].text`, 'must be a string');
3374
+ });
3375
+ }
3376
+ if (row.type === 'buttonGroup') {
3377
+ if (!Array.isArray(row.buttons) || row.buttons.length === 0)
3378
+ fail(`${path}.buttons`, 'required buttons');
3379
+ const keys = new Set<string>();
3380
+ row.buttons.forEach((button, index) => {
3381
+ const field = `${path}.buttons[${index}]`;
3382
+ protocolObject(button, field);
3383
+ protocolKey(button.key, `${field}.key`);
3384
+ protocolKey(button.actionKey, `${field}.actionKey`);
3385
+ protocolKey(button.label, `${field}.label`);
3386
+ if (keys.has(button.key)) fail(field, 'duplicate button identity');
3387
+ keys.add(button.key);
3388
+ });
3389
+ }
3390
+ for (const field of [
3391
+ 'trailing',
3392
+ 'leadingAction',
3393
+ 'titleIcon',
3394
+ 'valueIcon',
3395
+ ] as const) {
3396
+ const value = object[field];
3397
+ if (value === undefined) continue;
3398
+ // Identity title icons are decorative descriptors, not trailing controls.
3399
+ if (field === 'titleIcon' && row.type !== 'sectionHeader') continue;
3400
+ const accessories = field === 'trailing' ? value : [value];
3401
+ if (!Array.isArray(accessories))
3402
+ fail(`${path}.${field}`, 'must be an array');
3403
+ accessories.forEach((accessory, index) => {
3404
+ const entry = protocolObject(accessory, `${path}.${field}[${index}]`);
3405
+ for (const key of entry.kind === 'value'
3406
+ ? ['text']
3407
+ : entry.kind === 'valuePair'
3408
+ ? ['primary', 'secondary']
3409
+ : []) {
3410
+ if (typeof entry[key] !== 'string')
3411
+ fail(`${path}.${field}[${index}].${key}`, 'required financial text');
3412
+ }
3413
+ if (
3414
+ ['button', 'menu', 'switch'].includes(entry.kind as string) ||
3415
+ 'actionKey' in entry
3416
+ ) {
3417
+ protocolKey(entry.actionKey, `${path}.${field}[${index}].actionKey`);
3418
+ if (entry.kind === 'button')
3419
+ protocolKey(entry.label, `${path}.${field}[${index}].label`);
3420
+ }
3421
+ if (entry.kind === 'icon')
3422
+ protocolKey(entry.name, `${path}.${field}[${index}].name`);
3423
+ });
3424
+ }
3425
+ }
3426
+
3427
+ function pickFields(
3428
+ object: Record<string, unknown>,
3429
+ fields: readonly string[]
3430
+ ): Record<string, unknown> {
3431
+ return Object.fromEntries(
3432
+ Object.entries(object).filter(([key]) => fields.includes(key))
3433
+ );
3434
+ }
3435
+
3436
+ function sanitizeImage(value: unknown): Record<string, unknown> | undefined {
3437
+ if (
3438
+ !isRecord(value) ||
3439
+ !isAllowedImageUri(value.uri) ||
3440
+ typeof value.width !== 'number' ||
3441
+ !Number.isFinite(value.width) ||
3442
+ value.width <= 0 ||
3443
+ typeof value.height !== 'number' ||
3444
+ !Number.isFinite(value.height) ||
3445
+ value.height <= 0
3446
+ )
3447
+ return undefined;
3448
+ const next = pickFields(value, IMAGE_FIELDS);
3449
+ next.width = Math.min(MAX_IMAGE_EDGE, value.width);
3450
+ next.height = Math.min(MAX_IMAGE_EDGE, value.height);
3451
+ if (next.headers !== undefined) {
3452
+ if (!isRecord(next.headers)) delete next.headers;
3453
+ else
3454
+ next.headers = Object.fromEntries(
3455
+ Object.entries(next.headers)
3456
+ .filter(
3457
+ ([key, item]) =>
3458
+ key.trim() &&
3459
+ key.length <= MAX_HEADER_LENGTH &&
3460
+ typeof item === 'string' &&
3461
+ item.length <= MAX_HEADER_LENGTH
3462
+ )
3463
+ .slice(0, MAX_IMAGE_HEADERS)
3464
+ );
3465
+ }
3466
+ if (next.fallbackUris !== undefined) {
3467
+ if (Array.isArray(next.fallbackUris))
3468
+ next.fallbackUris = next.fallbackUris.filter(isAllowedImageUri);
3469
+ else delete next.fallbackUris;
3470
+ }
3471
+ if (next.fallbackUri !== undefined && !isAllowedImageUri(next.fallbackUri))
3472
+ delete next.fallbackUri;
3473
+ if (
3474
+ next.overscan !== undefined &&
3475
+ (typeof next.overscan !== 'number' ||
3476
+ !Number.isFinite(next.overscan) ||
3477
+ next.overscan < 1 ||
3478
+ next.overscan > 4)
3479
+ )
3480
+ delete next.overscan;
3481
+ if (
3482
+ next.retryTimes !== undefined &&
3483
+ (typeof next.retryTimes !== 'number' ||
3484
+ !Number.isFinite(next.retryTimes) ||
3485
+ next.retryTimes < 0)
3486
+ )
3487
+ delete next.retryTimes;
3488
+ const options: Readonly<Record<string, readonly string[]>> = {
3489
+ contentFit: ['cover', 'contain', 'fill', 'center'],
3490
+ cachePolicy: ['memory-disk', 'memory', 'disk', 'none'],
3491
+ loadingStrategy: ['static', 'skeleton', 'none'],
3492
+ };
3493
+ for (const [key, allowed] of Object.entries(options))
3494
+ if (next[key] !== undefined && !allowed.includes(next[key] as string))
3495
+ delete next[key];
3496
+ for (const key of ['autoplay', 'optimizeTos'])
3497
+ if (next[key] !== undefined && typeof next[key] !== 'boolean')
3498
+ delete next[key];
3499
+ return next;
3500
+ }
3501
+
3502
+ const NESTED_DECORATION_FIELDS: Readonly<Record<string, readonly string[]>> = {
3503
+ webTable: ['columns', 'cells', 'testID', 'draggable', 'contextMenuActionKey'],
3504
+ columns: [
3505
+ 'key',
3506
+ 'text',
3507
+ 'textSegments',
3508
+ 'titleIcon',
3509
+ 'secondaryTitleIcon',
3510
+ 'secondaryLeadingText',
3511
+ 'secondaryText',
3512
+ 'secondaryTextSegments',
3513
+ 'weight',
3514
+ 'alignment',
3515
+ 'tone',
3516
+ 'secondaryTone',
3517
+ 'width',
3518
+ 'minWidth',
3519
+ 'flex',
3520
+ 'paddingStart',
3521
+ 'paddingEnd',
3522
+ ],
3523
+ cells: [
3524
+ 'key',
3525
+ 'kind',
3526
+ 'active',
3527
+ 'disabled',
3528
+ 'testID',
3529
+ 'hoverActionKey',
3530
+ 'actionKey',
3531
+ 'accessibilityLabel',
3532
+ 'leading',
3533
+ 'title',
3534
+ 'secondary',
3535
+ 'lineGap',
3536
+ 'secondaryBadges',
3537
+ 'hoverImages',
3538
+ 'hoverSecondary',
3539
+ 'hoverActionLabel',
3540
+ 'badges',
3541
+ 'primary',
3542
+ 'partGap',
3543
+ 'points',
3544
+ 'width',
3545
+ 'height',
3546
+ 'strokeColor',
3547
+ 'fillColor',
3548
+ ],
3549
+ badges: [
3550
+ 'key',
3551
+ 'text',
3552
+ 'tone',
3553
+ 'iconName',
3554
+ 'icon',
3555
+ 'textColor',
3556
+ 'backgroundColor',
3557
+ 'actionKey',
3558
+ 'accessibilityLabel',
3559
+ 'style',
3560
+ ],
3561
+ overlays: [
3562
+ 'position',
3563
+ 'size',
3564
+ 'width',
3565
+ 'height',
3566
+ 'padding',
3567
+ 'offset',
3568
+ 'offsetX',
3569
+ 'offsetY',
3570
+ 'image',
3571
+ 'fallbackIcon',
3572
+ 'name',
3573
+ 'text',
3574
+ 'fontWeight',
3575
+ 'tintColor',
3576
+ 'backgroundColor',
3577
+ ],
3578
+ primaryHelp: ['actionKey', 'presentation', 'underline'],
3579
+ valueHelp: ['actionKey', 'presentation', 'underline'],
3580
+ };
3581
+
3582
+ function sanitizeDecoration(value: unknown, field: string): unknown {
3583
+ if (value === undefined || value === null) return undefined;
3584
+ if (
3585
+ !Array.isArray(value) &&
3586
+ [
3587
+ 'image',
3588
+ 'networkImage',
3589
+ 'thumbnail',
3590
+ 'source',
3591
+ 'images',
3592
+ 'hoverImages',
3593
+ ].includes(field)
3594
+ )
3595
+ return sanitizeImage(value);
3596
+ if (
3597
+ [
3598
+ 'titleImage',
3599
+ 'titleIcon',
3600
+ 'secondaryTitleIcon',
3601
+ 'fallbackIcon',
3602
+ 'cornerIcon',
3603
+ 'media',
3604
+ ].includes(field) &&
3605
+ !isRecord(value)
3606
+ )
3607
+ return undefined;
3608
+ if (field === 'style' && typeof value !== 'string' && !isRecord(value))
3609
+ return undefined;
3610
+ if (
3611
+ ['badges', 'overlays'].includes(field) &&
3612
+ !Array.isArray(value) &&
3613
+ !isRecord(value)
3614
+ )
3615
+ return undefined;
3616
+ if (field === 'style' && typeof value === 'string')
3617
+ return value === 'subscript' ? value : undefined;
3618
+ if (Array.isArray(value)) {
3619
+ const items = value.map((item) => sanitizeDecoration(item, field));
3620
+ return field === 'hoverImages'
3621
+ ? items.map((item) => item ?? null)
3622
+ : items.filter((item) => item !== undefined);
3623
+ }
3624
+ if (!isRecord(value)) return value;
3625
+ let object = value;
3626
+ if (field === 'titleImage') {
3627
+ const image = sanitizeImage(value.image);
3628
+ if (!image) return undefined;
3629
+ const edge = Math.min(
3630
+ 40,
3631
+ Math.max(
3632
+ 1,
3633
+ Math.round(Math.min(image.width as number, image.height as number))
3634
+ )
3635
+ );
3636
+ object = {
3637
+ ...pickFields(value, ['image', 'accessibilityLabel', 'hoverActionKey']),
3638
+ image: { ...image, width: edge, height: edge },
3639
+ };
3640
+ } else if (
3641
+ ['titleIcon', 'secondaryTitleIcon', 'fallbackIcon', 'cornerIcon'].includes(
3642
+ field
3643
+ ) &&
3644
+ value.kind === undefined
3645
+ ) {
3646
+ if (typeof value.name !== 'string' || !value.name.trim()) return undefined;
3647
+ object = pickFields(value, ICON_FIELDS);
3648
+ } else if (['leading', 'visual', 'secondaryLeading'].includes(field)) {
3649
+ object = pickFields(value, VISUAL_FIELDS);
3650
+ } else if (field === 'media') {
3651
+ object = pickFields(value, ['source', 'probeOrder']);
3652
+ }
3653
+ if (
3654
+ field === 'trailing' ||
3655
+ (['leadingAction', 'titleIcon', 'valueIcon'].includes(field) &&
3656
+ object.kind !== undefined)
3657
+ ) {
3658
+ const fields = ACCESSORY_FIELDS[object.kind as string];
3659
+ if (fields) object = pickFields(object, fields);
3660
+ } else if (field === 'buttons')
3661
+ object = pickFields(object, [
3662
+ 'key',
3663
+ 'label',
3664
+ 'actionKey',
3665
+ 'disabled',
3666
+ 'loading',
3667
+ 'testID',
3668
+ 'accessibilityLabel',
3669
+ ]);
3670
+ else if (field === 'container')
3671
+ object = pickFields(object, [
3672
+ 'height',
3673
+ 'backgroundColor',
3674
+ 'opacity',
3675
+ 'cornerRadius',
3676
+ 'borderWidth',
3677
+ 'borderColor',
3678
+ 'contentVerticalAlignment',
3679
+ ]);
3680
+ else if (field === 'imageStyle')
3681
+ object = pickFields(object, [
3682
+ 'width',
3683
+ 'height',
3684
+ 'shape',
3685
+ 'cornerRadius',
3686
+ 'contentFit',
3687
+ ]);
3688
+ else if (field === 'style')
3689
+ object = pickFields(object, [
3690
+ ...TEXT_STYLE_FIELDS,
3691
+ 'container',
3692
+ ...new Set(Object.values(ROW_BOX_STYLE_KEYS_BY_TYPE).flat()),
3693
+ ...new Set(Object.values(TEXT_STYLE_KEYS_BY_ROW_TYPE).flat()),
3694
+ ...new Set(Object.values(EXTRA_STYLE_KEYS_BY_ROW_TYPE).flat()),
3695
+ 'height',
3696
+ ]);
3697
+ else if (
3698
+ [
3699
+ 'title',
3700
+ 'subtitle',
3701
+ 'tertiary',
3702
+ 'body',
3703
+ 'time',
3704
+ 'price',
3705
+ 'change',
3706
+ 'value',
3707
+ 'valueSecondary',
3708
+ 'columnSecondary',
3709
+ 'primaryAmount',
3710
+ 'secondaryAmount',
3711
+ 'description',
3712
+ 'status',
3713
+ 'trend',
3714
+ 'message',
3715
+ 'actionText',
3716
+ ].includes(field) &&
3717
+ !('text' in object)
3718
+ ) {
3719
+ object = pickFields(object, TEXT_STYLE_FIELDS);
3720
+ }
3721
+ if (NESTED_DECORATION_FIELDS[field])
3722
+ object = pickFields(object, NESTED_DECORATION_FIELDS[field]);
3723
+ if (
3724
+ [
3725
+ 'textSegments',
3726
+ 'primaryTextSegments',
3727
+ 'secondaryTextSegments',
3728
+ 'priceSegments',
3729
+ 'segments',
3730
+ ].includes(field)
3731
+ )
3732
+ object = pickFields(object, ['text', 'style']);
3733
+ if (field === 'subtitleSegments')
3734
+ object = pickFields(object, [
3735
+ 'text',
3736
+ 'style',
3737
+ 'textSegments',
3738
+ 'tone',
3739
+ 'separatorBefore',
3740
+ ]);
3741
+ const styleObject =
3742
+ ['style', 'imageStyle', 'container'].includes(field) ||
3743
+ TEXT_STYLE_FIELDS.some((key) => key in object);
3744
+ const next: Record<string, unknown> = {};
3745
+ for (const [key, item] of Object.entries(object)) {
3746
+ if (item === undefined || item === null) continue;
3747
+ if (
3748
+ (/color$/i.test(key) || /background$/i.test(key)) &&
3749
+ (typeof item !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(item))
3750
+ )
3751
+ continue;
3752
+ if (
3753
+ /TextSegments$/.test(key) ||
3754
+ [
3755
+ 'textSegments',
3756
+ 'priceSegments',
3757
+ 'subtitleSegments',
3758
+ 'segments',
3759
+ ].includes(key)
3760
+ ) {
3761
+ if (
3762
+ !Array.isArray(item) ||
3763
+ item.some(
3764
+ (segment) => !isRecord(segment) || typeof segment.text !== 'string'
3765
+ )
3766
+ )
3767
+ continue;
3768
+ }
3769
+ if (
3770
+ styleObject &&
3771
+ PROTOCOL_NUMBER_FIELDS.has(key) &&
3772
+ typeof item !== 'number'
3773
+ )
3774
+ continue;
3775
+ if (
3776
+ key === 'token' &&
3777
+ (typeof item !== 'string' || !Object.hasOwn(TYPOGRAPHY_TOKENS, item))
3778
+ )
3779
+ continue;
3780
+ if (
3781
+ key === 'fontWeight' &&
3782
+ !['regular', 'medium', 'semibold', 'bold'].includes(item as string)
3783
+ )
3784
+ continue;
3785
+ if (
3786
+ [
3787
+ 'disabled',
3788
+ 'loading',
3789
+ 'checked',
3790
+ 'selected',
3791
+ 'separator',
3792
+ 'hideLeading',
3793
+ 'pressDisabled',
3794
+ 'draggable',
3795
+ 'active',
3796
+ 'autoplay',
3797
+ ].includes(key) &&
3798
+ typeof item !== 'boolean'
3799
+ )
3800
+ continue;
3801
+ if (key === 'primaryFontWeight' && item !== 'medium') continue;
3802
+ if (key === 'buttonStyle' && item !== 'tertiary') continue;
3803
+ if (key === 'hoverActionKey' && (typeof item !== 'string' || !item.trim()))
3804
+ continue;
3805
+ if (key === 'accessibilityLabel' && typeof item !== 'string') continue;
3806
+ if (
3807
+ (field === 'style' || PROTOCOL_NUMBER_FIELDS.has(key)) &&
3808
+ typeof item !== 'object' &&
3809
+ typeof item === 'number' &&
3810
+ (!Number.isFinite(item) ||
3811
+ (item < 0 && !['offsetX', 'offsetY'].includes(key)))
3812
+ )
3813
+ continue;
3814
+ if (
3815
+ field === 'style' &&
3816
+ PROTOCOL_NUMBER_FIELDS.has(key) &&
3817
+ typeof item !== 'number'
3818
+ )
3819
+ continue;
3820
+ if (
3821
+ key === 'leadingContentMaxWidthRatio' &&
3822
+ (typeof item !== 'number' || item <= 0 || item > 1)
3823
+ )
3824
+ continue;
3825
+ const normalized = sanitizeDecoration(
3826
+ item,
3827
+ field === 'style' && key === 'image' ? 'imageStyle' : key
3828
+ );
3829
+ if (normalized !== undefined) next[key] = normalized;
3830
+ }
3831
+ if (field === 'titleImage') {
3832
+ // The nested image was already normalized with title-specific geometry.
3833
+ if (!next.image) return undefined;
3834
+ }
3835
+ if (field === 'media' && (!next.source || !Array.isArray(next.probeOrder)))
3836
+ return undefined;
3837
+ if (['leading', 'visual', 'secondaryLeading'].includes(field)) {
3838
+ if (next.kind === 'image' && !next.image)
3839
+ return {
3840
+ kind: 'token',
3841
+ ...pickFields(next, [
3842
+ 'fallbackIcon',
3843
+ 'fallbackText',
3844
+ 'fallbackTextColor',
3845
+ ]),
3846
+ };
3847
+ if (
3848
+ next.kind === 'stackedImages' &&
3849
+ (!Array.isArray(next.images) || next.images.length < 2)
3850
+ )
3851
+ return { kind: 'token' };
3852
+ if (
3853
+ next.kind === 'icon' &&
3854
+ (typeof next.name !== 'string' || !next.name.trim())
3855
+ )
3856
+ return { kind: 'token' };
3857
+ if (
3858
+ ![
3859
+ 'token',
3860
+ 'account',
3861
+ 'wallet',
3862
+ 'network',
3863
+ 'image',
3864
+ 'icon',
3865
+ 'stackedImages',
3866
+ ].includes(next.kind as string)
3867
+ )
3868
+ return { kind: 'token' };
3869
+ }
3870
+ if (
3871
+ field === 'overlays' &&
3872
+ (!['topLeft', 'bottomRight'].includes(next.position as string) ||
3873
+ (!next.image && !next.name && !next.text))
3874
+ )
3875
+ return undefined;
3876
+ if (
3877
+ field === 'trailing' &&
3878
+ next.kind === 'icon' &&
3879
+ !('actionKey' in value) &&
3880
+ (typeof next.name !== 'string' || !next.name.trim())
3881
+ )
3882
+ return undefined;
3883
+ if (
3884
+ field === 'trailing' &&
3885
+ ![
3886
+ 'value',
3887
+ 'valuePair',
3888
+ 'button',
3889
+ 'checkbox',
3890
+ 'radio',
3891
+ 'switch',
3892
+ 'chevron',
3893
+ 'menu',
3894
+ 'drag',
3895
+ 'icon',
3896
+ 'spinner',
3897
+ 'progress',
3898
+ ].includes(next.kind as string) &&
3899
+ !('actionKey' in value)
3900
+ )
3901
+ return undefined;
3902
+ if (
3903
+ field === 'badges' &&
3904
+ (typeof next.key !== 'string' ||
3905
+ (!next.text && !next.iconName && !next.icon))
3906
+ )
3907
+ return undefined;
3908
+ if (next.kind === 'sparkline') {
3909
+ const points = Array.isArray(value.points)
3910
+ ? value.points
3911
+ .filter(
3912
+ (point) => typeof point === 'number' && Number.isFinite(point)
3913
+ )
3914
+ .slice(0, 256)
3915
+ : [];
3916
+ // Preserve the table's column identity even when its optional drawing fails.
3917
+ return points.length < 2
3918
+ ? { key: next.key, kind: 'text', primary: [] }
3919
+ : { ...next, points };
3920
+ }
3921
+ return next;
3922
+ }
3923
+
3924
+ function sanitizeMarketMetrics(value: unknown): unknown {
3925
+ if (!Array.isArray(value)) return value;
3926
+ return value.map((metric) => {
3927
+ const next = pickFields(
3928
+ metric as Record<string, unknown>,
3929
+ MARKET_METRIC_FIELDS
3930
+ );
3931
+ for (const field of ['textSegments', 'secondaryTextSegments'] as const) {
3932
+ if (next[field] !== undefined)
3933
+ next[field] = sanitizeDecoration(next[field], field);
3934
+ }
3935
+ return next;
3936
+ });
3937
+ }
3938
+
3939
+ function sanitizeRowForProduction(row: RowModel): RowModel {
3940
+ const object = protocolObject(row, 'row');
3941
+ const fields = ROW_FIELDS[row.type];
3942
+ if (!fields) return row;
3943
+ const next = pickFields(object, fields);
3944
+ for (const [field, value] of Object.entries(next)) {
3945
+ if (
3946
+ (/color$/i.test(field) || /background$/i.test(field)) &&
3947
+ (typeof value !== 'string' ||
3948
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value))
3949
+ ) {
3950
+ delete next[field];
3951
+ continue;
3952
+ }
3953
+ if (field === 'descriptionActionStart') {
3954
+ // Renderers clamp an offset past the text; anything else has no meaning.
3955
+ if (!isDescriptionActionStart(value)) delete next[field];
3956
+ continue;
3957
+ }
3958
+ if (field === 'parent' && isRecord(value))
3959
+ next[field] = sanitizeRowForProduction(value as unknown as RowModel);
3960
+ else if (field === 'children' && Array.isArray(value))
3961
+ next[field] = value.map((child) =>
3962
+ sanitizeRowForProduction(child as RowModel)
3963
+ );
3964
+ else {
3965
+ const normalized =
3966
+ row.type === 'market' && field === 'metrics'
3967
+ ? sanitizeMarketMetrics(value)
3968
+ : sanitizeDecoration(value, field);
3969
+ if (normalized === undefined) delete next[field];
3970
+ else next[field] = normalized;
3971
+ }
3972
+ }
3973
+ if (isRecord(next.style))
3974
+ next.style = pickFields(next.style, [
3975
+ 'container',
3976
+ ...ROW_BOX_STYLE_KEYS_BY_TYPE[row.type],
3977
+ ...(TEXT_STYLE_KEYS_BY_ROW_TYPE[row.type] ?? []),
3978
+ ...(EXTRA_STYLE_KEYS_BY_ROW_TYPE[row.type] ?? []),
3979
+ ]);
3980
+ return sameJsonValue(row, next) ? row : (next as unknown as RowModel);
3981
+ }
3982
+
3983
+ /** Empty images and optional nulls share one meaning before strict assertions. */
3984
+ function normalizeEmptyImages(value: unknown, field = ''): unknown {
3985
+ if (value === null || value === undefined || typeof value !== 'object')
3986
+ return value;
3987
+ if (Array.isArray(value)) {
3988
+ const next = value.map((item) => normalizeEmptyImages(item, field));
3989
+ return next.every((item, index) => item === value[index])
3990
+ ? value
3991
+ : next.filter((item) => item !== undefined);
3992
+ }
3993
+ const object = value as Record<string, unknown>;
3994
+ if (
3995
+ typeof object.uri === 'string' &&
3996
+ !object.uri.trim() &&
3997
+ 'width' in object &&
3998
+ 'height' in object
3999
+ )
4000
+ return undefined;
4001
+ let changed = false;
4002
+ const next: Record<string, unknown> = {};
4003
+ for (const [key, item] of Object.entries(object)) {
4004
+ const optional =
4005
+ object.type &&
4006
+ ![
4007
+ 'key',
4008
+ 'type',
4009
+ ...(REQUIRED_ROW_FIELDS[object.type as string] ?? []),
4010
+ ].includes(key);
4011
+ if (
4012
+ item === undefined ||
4013
+ (item === null &&
4014
+ optional &&
4015
+ !(object.type === 'market' && key === 'metrics')) ||
4016
+ (['priceSegments', 'subtitleSegments'].includes(key) &&
4017
+ Array.isArray(item) &&
4018
+ item.length === 0)
4019
+ ) {
4020
+ changed = true;
4021
+ continue;
4022
+ }
4023
+ const normalized =
4024
+ field === 'headers' ? item : normalizeEmptyImages(item, key);
4025
+ if (normalized !== undefined) next[key] = normalized;
4026
+ if (normalized !== item) changed = true;
4027
+ }
4028
+ if (
4029
+ (field === 'media' &&
4030
+ object.source !== undefined &&
4031
+ next.source === undefined) ||
4032
+ (field === 'titleImage' &&
4033
+ object.image !== undefined &&
4034
+ next.image === undefined)
4035
+ )
4036
+ return undefined;
4037
+ if (
4038
+ ['leading', 'visual', 'secondaryLeading'].includes(field) &&
4039
+ next.kind === 'image' &&
4040
+ !next.image
4041
+ )
4042
+ return { kind: 'token' };
4043
+ if (field === 'overlays' && object.image !== undefined && !next.image)
4044
+ return undefined;
4045
+ return changed ? next : value;
4046
+ }
4047
+
4048
+ function normalizeSnapshotForProduction(
4049
+ snapshot: NativeListSnapshot
4050
+ ): NativeListSnapshot {
4051
+ if (!Array.isArray(snapshot.rows)) return snapshot;
4052
+ let rows = snapshot.rows.map(sanitizeRowForProduction);
4053
+ rows = rows.map((row, index) => {
4054
+ if (!row.groupId) return row;
4055
+ const previous = rows[index - 1]?.groupId === row.groupId;
4056
+ const following = rows[index + 1]?.groupId === row.groupId;
4057
+ return {
4058
+ ...row,
4059
+ groupPosition: previous
4060
+ ? following
4061
+ ? 'middle'
4062
+ : 'last'
4063
+ : following
4064
+ ? 'first'
4065
+ : 'single',
4066
+ };
4067
+ });
4068
+ const next = {
4069
+ ...snapshot,
4070
+ rows,
4071
+ ...(snapshot.emptyState
4072
+ ? {
4073
+ emptyState: sanitizeRowForProduction(
4074
+ snapshot.emptyState
4075
+ ) as NativeListSnapshot['emptyState'],
4076
+ }
4077
+ : {}),
4078
+ ...(snapshot.fixedFooter
4079
+ ? {
4080
+ fixedFooter: sanitizeRowForProduction(
4081
+ snapshot.fixedFooter
4082
+ ) as NativeListSnapshot['fixedFooter'],
4083
+ }
4084
+ : {}),
4085
+ };
4086
+ if (snapshot.theme)
4087
+ next.theme = sanitizeDecoration(
4088
+ snapshot.theme,
4089
+ 'theme'
4090
+ ) as NativeListSnapshot['theme'];
4091
+ if (snapshot.listStyle)
4092
+ next.listStyle = sanitizeDecoration(
4093
+ snapshot.listStyle,
4094
+ 'style'
4095
+ ) as NativeListSnapshot['listStyle'];
4096
+ if (snapshot.selection && Array.isArray(snapshot.selection.selectedKeys)) {
4097
+ const selectable = new Set(
4098
+ rows
4099
+ .filter(
4100
+ (row) =>
4101
+ !row.disabled &&
4102
+ ![
4103
+ 'sectionHeader',
4104
+ 'action',
4105
+ 'system',
4106
+ 'buttonGroup',
4107
+ 'market',
4108
+ 'walletGroup',
4109
+ ].includes(row.type)
4110
+ )
4111
+ .map((row) => row.key)
4112
+ );
4113
+ const selectedKeys = [
4114
+ ...new Set(
4115
+ snapshot.selection.selectedKeys.filter((key) => selectable.has(key))
4116
+ ),
4117
+ ];
4118
+ next.selection = {
4119
+ ...snapshot.selection,
4120
+ selectedKeys:
4121
+ snapshot.selection.mode === 'none'
4122
+ ? []
4123
+ : snapshot.selection.mode === 'single'
4124
+ ? selectedKeys.slice(0, 1)
4125
+ : selectedKeys,
4126
+ };
4127
+ }
4128
+ return sameJsonValue(snapshot, next) ? snapshot : next;
4129
+ }
4130
+
4131
+ export function validateSnapshot(
4132
+ snapshot: NativeListSnapshot
4133
+ ): NativeListSnapshot {
4134
+ assertPlainSerializable(snapshot, 'snapshot', new Set<object>(), false);
4135
+ protocolObject(snapshot, 'snapshot');
4136
+ const normalized = normalizeEmptyImages(snapshot) as NativeListSnapshot;
4137
+ if (Array.isArray(normalized.rows)) {
4138
+ normalized.rows.forEach((row, index) => {
4139
+ if (row.type === 'market')
4140
+ assertMarketMetrics(row.metrics, `snapshot.rows[${index}].metrics`);
4141
+ });
4142
+ }
4143
+ const canonical = isDevelopment()
4144
+ ? normalized
4145
+ : normalizeSnapshotForProduction(normalized);
4146
+ assertPlainSerializable(canonical, 'snapshot', new Set<object>());
4147
+ if (isDevelopment()) assertSnapshotContract(canonical);
4148
+ assertSnapshotProtocol(canonical);
4149
+ return normalizeSnapshotStyles(canonical);
4150
+ }
4151
+
4152
+ const ownedNativeSnapshots = new WeakMap<
4153
+ NativeListSnapshot,
4154
+ ReadonlyMap<string, number>
4155
+ >();
4156
+
4157
+ function capturePlainData<T>(value: T, seen = new Map<object, object>()): T {
4158
+ if (value === null || typeof value !== 'object') return value;
4159
+ const previous = seen.get(value);
4160
+ if (previous) return previous as T;
4161
+ const copy: Record<string, unknown> | unknown[] = Array.isArray(value)
4162
+ ? new Array(value.length)
4163
+ : Object.create(Object.getPrototypeOf(value));
4164
+ seen.set(value, copy);
4165
+ const captureKey = (key: string) => {
4166
+ Object.defineProperty(copy, key, {
4167
+ value: capturePlainData((value as Record<string, unknown>)[key], seen),
4168
+ enumerable: true,
4169
+ writable: true,
4170
+ configurable: true,
4171
+ });
4172
+ };
4173
+ if (Array.isArray(value)) {
4174
+ for (let index = 0; index < value.length; index += 1) {
4175
+ if (index in value) captureKey(String(index));
4176
+ }
4177
+ Object.keys(value).forEach((key) => {
4178
+ const index = Number(key);
4179
+ if (
4180
+ Number.isInteger(index) &&
4181
+ index >= 0 &&
4182
+ index < value.length &&
4183
+ String(index) === key
4184
+ )
4185
+ return;
4186
+ captureKey(key);
4187
+ });
4188
+ } else {
4189
+ Object.keys(value).forEach(captureKey);
4190
+ }
4191
+ return copy as T;
4192
+ }
4193
+
4194
+ function deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {
4195
+ if (value === null || typeof value !== 'object' || seen.has(value))
4196
+ return value;
4197
+ seen.add(value);
4198
+ Object.values(value).forEach((item) => deepFreeze(item, seen));
4199
+ return Object.freeze(value);
4200
+ }
4201
+
4202
+ /** Capture caller data once before validation, including accessor values. */
4203
+ export function captureNativeListInput<T>(value: T): T {
4204
+ return capturePlainData(value);
4205
+ }
4206
+
4207
+ /** Private native-wrapper ownership; exported validators keep their public identity. */
4208
+ export function ownValidatedNativeSnapshot(
4209
+ snapshot: NativeListSnapshot
4210
+ ): NativeListSnapshot {
4211
+ const owned = deepFreeze(snapshot);
4212
+ ownedNativeSnapshots.set(
4213
+ owned,
4214
+ new Map(owned.rows.map((row, index) => [row.key, index]))
4215
+ );
4216
+ return owned;
4217
+ }
4218
+
4219
+ /**
4220
+ * Resolves typography tokens to numbers. Returns the original snapshot when
4221
+ * nothing needs resolving, so the common no-style path keeps object identity.
4222
+ */
4223
+ function normalizeSnapshotStyles(
4224
+ snapshot: NativeListSnapshot
4225
+ ): NativeListSnapshot {
4226
+ let changed = false;
4227
+ const rows = snapshot.rows.map((row) => {
4228
+ const next = normalizeRowStyles(row);
4229
+ if (next !== row) changed = true;
4230
+ return next;
4231
+ });
4232
+ const emptyState = snapshot.emptyState
4233
+ ? normalizeRowStyles(snapshot.emptyState)
4234
+ : snapshot.emptyState;
4235
+ const fixedFooter = snapshot.fixedFooter
4236
+ ? normalizeRowStyles(snapshot.fixedFooter)
4237
+ : snapshot.fixedFooter;
4238
+ if (
4239
+ !changed &&
4240
+ emptyState === snapshot.emptyState &&
4241
+ fixedFooter === snapshot.fixedFooter
4242
+ ) {
4243
+ return snapshot;
4244
+ }
4245
+ return {
4246
+ ...snapshot,
4247
+ rows,
4248
+ ...(emptyState !== undefined ? { emptyState } : {}),
4249
+ ...(fixedFooter !== undefined ? { fixedFooter } : {}),
4250
+ };
4251
+ }
4252
+
4253
+ type PatchValues<Patch = RowPatch> = Patch extends RowPatch
4254
+ ? Omit<Patch, 'changes'> & {
4255
+ changes: {
4256
+ [Key in keyof Patch['changes']]: Exclude<Patch['changes'][Key], null>;
4257
+ };
4258
+ }
4259
+ : never;
4260
+
4261
+ function assertPatchChanges(patch: PatchValues, index: number): void {
4262
+ const path = `patches[${index}].changes`;
4263
+ const patchedStyle = (patch.changes as { style?: unknown }).style;
4264
+ if (patchedStyle !== undefined) {
4265
+ assertRowStyle({ type: patch.type, style: patchedStyle } as RowModel, path);
4266
+ }
4267
+ // OneKey patch: partial balance updates retain a valid, current accessibility label.
4268
+ if ('accessibilityLabel' in patch.changes) {
4269
+ assertText(patch.changes.accessibilityLabel, `${path}.accessibilityLabel`);
4270
+ }
4271
+ // OneKey patch: partial updates may refer to an existing height but still require a valid policy.
4272
+ if (
4273
+ 'heightRounding' in patch.changes &&
4274
+ patch.changes.heightRounding !== undefined &&
4275
+ !['floor', 'nearest'].includes(patch.changes.heightRounding)
4276
+ )
4277
+ fail(`${path}.heightRounding`, 'must be floor or nearest');
4278
+ if (
4279
+ patch.changes.revision !== undefined &&
4280
+ (!Number.isSafeInteger(patch.changes.revision) ||
4281
+ patch.changes.revision < 0)
4282
+ ) {
4283
+ fail(`${path}.revision`, 'must be a non-negative safe integer');
4284
+ }
4285
+
4286
+ switch (patch.type) {
4287
+ case 'identity':
4288
+ if (
4289
+ patch.changes.contentHeight !== undefined &&
4290
+ patch.changes.contentHeight !== 'auto'
4291
+ ) {
4292
+ fail(`${path}.contentHeight`, 'must be auto');
4293
+ }
4294
+ if (
4295
+ patch.changes.subtitleLines !== undefined &&
4296
+ ![0, 1, 2].includes(patch.changes.subtitleLines)
4297
+ ) {
4298
+ fail(`${path}.subtitleLines`, 'must be 0, 1, or 2');
4299
+ }
4300
+ if (patch.changes.longPressActionKey !== undefined) {
4301
+ assertKey(
4302
+ patch.changes.longPressActionKey,
4303
+ `${path}.longPressActionKey`
4304
+ );
4305
+ }
4306
+ assertText(patch.changes.title, `${path}.title`);
4307
+ if ((patch.changes.titleSuffixes?.length ?? 0) > 3)
4308
+ fail(`${path}.titleSuffixes`, 'supports at most 3 suffixes');
4309
+ patch.changes.titleSuffixes?.forEach((suffix, index) => {
4310
+ assertText(suffix.text, `${path}.titleSuffixes[${index}].text`);
4311
+ if (!['secondary', 'disabled'].includes(suffix.tone))
4312
+ fail(
4313
+ `${path}.titleSuffixes[${index}].tone`,
4314
+ 'must be secondary or disabled'
4315
+ );
4316
+ if (
4317
+ suffix.maxWidth !== undefined &&
4318
+ (!Number.isFinite(suffix.maxWidth) ||
4319
+ suffix.maxWidth < 0 ||
4320
+ suffix.maxWidth > 4096)
4321
+ )
4322
+ fail(
4323
+ `${path}.titleSuffixes[${index}].maxWidth`,
4324
+ 'must be finite within 0...4096'
4325
+ );
4326
+ });
4327
+ assertIdentityExtras(patch.changes, path);
4328
+ assertText(patch.changes.subtitle, `${path}.subtitle`);
4329
+ assertText(patch.changes.tertiary, `${path}.tertiary`);
4330
+ if (
4331
+ patch.changes.tertiaryTone !== undefined &&
4332
+ !['secondary', 'info'].includes(patch.changes.tertiaryTone)
4333
+ ) {
4334
+ fail(`${path}.tertiaryTone`, 'must be secondary or info');
4335
+ }
4336
+ assertLeadingVisual(patch.changes.leading, `${path}.leading`);
4337
+ assertTrailingAccessories(
4338
+ patch.changes.leadingAction ? [patch.changes.leadingAction] : undefined,
4339
+ `${path}.leadingAction`
4340
+ );
4341
+ if ((patch.changes.badges?.length ?? 0) > MAX_BADGES) {
4342
+ fail(`${path}.badges`, `supports at most ${MAX_BADGES} badges`);
4343
+ }
4344
+ if ((patch.changes.trailing?.length ?? 0) > MAX_TRAILING_ACCESSORIES) {
4345
+ fail(
4346
+ `${path}.trailing`,
4347
+ `supports at most ${MAX_TRAILING_ACCESSORIES} accessories`
4348
+ );
4349
+ }
4350
+ assertTrailingAccessories(patch.changes.trailing, `${path}.trailing`);
4351
+ break;
4352
+ case 'rail':
4353
+ assertText(patch.changes.title, `${path}.title`);
4354
+ assertLeadingVisual(patch.changes.visual, `${path}.visual`);
4355
+ break;
4356
+ case 'activity':
4357
+ assertActivity(patch.changes, path);
1919
4358
  assertText(patch.changes.title, `${path}.title`);
1920
4359
  assertText(patch.changes.description, `${path}.description`);
1921
4360
  assertText(patch.changes.status, `${path}.status`);
@@ -1934,14 +4373,20 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
1934
4373
  }
1935
4374
  break;
1936
4375
  case 'message':
4376
+ if (
4377
+ patch.changes.presentation !== undefined &&
4378
+ patch.changes.presentation !== 'inlineWarning'
4379
+ ) {
4380
+ fail(`${path}.presentation`, 'must be inlineWarning');
4381
+ }
1937
4382
  assertText(patch.changes.title, `${path}.title`);
1938
4383
  assertText(patch.changes.body, `${path}.body`);
1939
4384
  assertText(patch.changes.time, `${path}.time`);
1940
4385
  if (
1941
4386
  patch.changes.bodyLines !== undefined &&
1942
- ![1, 2, 3].includes(patch.changes.bodyLines)
4387
+ ![0, 1, 2, 3].includes(patch.changes.bodyLines)
1943
4388
  ) {
1944
- fail(`${path}.bodyLines`, 'must be 1, 2, or 3');
4389
+ fail(`${path}.bodyLines`, 'must be 0, 1, 2, or 3');
1945
4390
  }
1946
4391
  assertImage(patch.changes.thumbnail, `${path}.thumbnail`);
1947
4392
  break;
@@ -1955,6 +4400,23 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
1955
4400
  patch.changes.columns?.forEach((column, columnIndex) => {
1956
4401
  assertKey(column.key, `${path}.columns[${columnIndex}].key`);
1957
4402
  assertText(column.text, `${path}.columns[${columnIndex}].text`);
4403
+ assertIdentityExtras(column, `${path}.columns[${columnIndex}]`);
4404
+ for (const field of [
4405
+ 'textSegments',
4406
+ 'secondaryTextSegments',
4407
+ ] as const) {
4408
+ column[field]?.forEach((segment, segmentIndex) => {
4409
+ assertText(
4410
+ segment.text,
4411
+ `${path}.columns[${columnIndex}].${field}[${segmentIndex}].text`
4412
+ );
4413
+ if (segment.style !== undefined && segment.style !== 'subscript')
4414
+ fail(
4415
+ `${path}.columns[${columnIndex}].${field}[${segmentIndex}].style`,
4416
+ 'must be subscript'
4417
+ );
4418
+ });
4419
+ }
1958
4420
  assertText(
1959
4421
  column.secondaryText,
1960
4422
  `${path}.columns[${columnIndex}].secondaryText`
@@ -1967,6 +4429,13 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
1967
4429
  if ((patch.changes.badges?.length ?? 0) > MAX_BADGES) {
1968
4430
  fail(`${path}.badges`, `supports at most ${MAX_BADGES} badges`);
1969
4431
  }
4432
+ if ((patch.changes.trailing?.length ?? 0) > MAX_TRAILING_ACCESSORIES) {
4433
+ fail(
4434
+ `${path}.trailing`,
4435
+ `supports at most ${MAX_TRAILING_ACCESSORIES} accessories`
4436
+ );
4437
+ }
4438
+ assertTrailingAccessories(patch.changes.trailing, `${path}.trailing`);
1970
4439
  break;
1971
4440
  case 'market':
1972
4441
  assertMarketRow(
@@ -2041,6 +4510,14 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
2041
4510
  assertText(patch.changes.title, `${path}.title`);
2042
4511
  assertText(patch.changes.subtitle, `${path}.subtitle`);
2043
4512
  assertText(patch.changes.value, `${path}.value`);
4513
+ if (patch.changes.leadingBadge) {
4514
+ assertKey(patch.changes.leadingBadge.key, `${path}.leadingBadge.key`);
4515
+ assertText(
4516
+ patch.changes.leadingBadge.text,
4517
+ `${path}.leadingBadge.text`
4518
+ );
4519
+ }
4520
+ assertTextHelp(patch.changes.valueHelp, `${path}.valueHelp`);
2044
4521
  if (patch.changes.valueActionKey !== undefined) {
2045
4522
  assertKey(patch.changes.valueActionKey, `${path}.valueActionKey`);
2046
4523
  }
@@ -2063,6 +4540,10 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
2063
4540
  }
2064
4541
  assertTrailingAccessories(patch.changes.trailing, `${path}.trailing`);
2065
4542
  break;
4543
+ case 'buttonGroup':
4544
+ if (patch.changes.buttons !== undefined)
4545
+ assertButtonGroup({ buttons: patch.changes.buttons }, path);
4546
+ break;
2066
4547
  case 'system':
2067
4548
  assertText(patch.changes.message, `${path}.message`);
2068
4549
  break;
@@ -2071,22 +4552,167 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
2071
4552
  }
2072
4553
  }
2073
4554
 
4555
+ function normalizePatch(patch: RowPatch, index: number): RowPatch | undefined {
4556
+ const path = `patches[${index}]`;
4557
+ protocolObject(patch, path);
4558
+ protocolKey(patch.key, `${path}.key`);
4559
+ if (isDevelopment()) assertKey(patch.key, `${path}.key`);
4560
+ assertRowType(patch.type, path);
4561
+ const raw = protocolObject(patch.changes, `${path}.changes`);
4562
+ assertPlainSerializable(raw, `${path}.changes`, new Set<object>(), false);
4563
+ const fields = PATCH_FIELDS[patch.type];
4564
+ const changes: Record<string, unknown> = {};
4565
+ for (const [field, value] of Object.entries(raw)) {
4566
+ if (value === undefined) continue;
4567
+ if (!fields?.includes(field)) {
4568
+ if (isDevelopment())
4569
+ fail(`${path}.changes.${field}`, 'unsupported patch field');
4570
+ continue;
4571
+ }
4572
+ if (value === null) {
4573
+ if (patch.type === 'market' && field === 'metrics')
4574
+ fail(
4575
+ `${path}.changes.metrics`,
4576
+ 'use a full snapshot to remove metrics'
4577
+ );
4578
+ if (
4579
+ REQUIRED_ROW_FIELDS[patch.type].includes(field) ||
4580
+ (patch.type === 'system' && field === 'message')
4581
+ ) {
4582
+ // The concrete system variant is checked after merging with its baseline.
4583
+ if (patch.type !== 'system')
4584
+ fail(`${path}.changes.${field}`, 'required field cannot be cleared');
4585
+ }
4586
+ changes[field] = null;
4587
+ continue;
4588
+ }
4589
+ if (patch.type === 'market' && field === 'metrics')
4590
+ assertMarketMetrics(
4591
+ value as MarketRow['metrics'],
4592
+ `${path}.changes.metrics`
4593
+ );
4594
+ if (
4595
+ ['priceSegments', 'subtitleSegments'].includes(field) &&
4596
+ Array.isArray(value) &&
4597
+ value.length === 0
4598
+ ) {
4599
+ changes[field] = null;
4600
+ continue;
4601
+ }
4602
+ const normalized = normalizeEmptyImages(value, field);
4603
+ if (normalized === undefined) {
4604
+ if (!REQUIRED_ROW_FIELDS[patch.type].includes(field))
4605
+ changes[field] = null;
4606
+ continue;
4607
+ }
4608
+ const canonical = isDevelopment()
4609
+ ? normalized
4610
+ : patch.type === 'market' && field === 'metrics'
4611
+ ? sanitizeMarketMetrics(normalized)
4612
+ : sanitizeDecoration(normalized, field);
4613
+ if (canonical !== undefined) changes[field] = canonical;
4614
+ else if (field === 'titleImage') changes[field] = null;
4615
+ }
4616
+ if (
4617
+ patch.type === 'market' &&
4618
+ Array.isArray(changes.priceSegments) &&
4619
+ changes.priceSegments.length > 0 &&
4620
+ (typeof changes.price !== 'string' || !changes.price.trim())
4621
+ )
4622
+ fail(`${path}.changes.price`, 'is required when priceSegments is updated');
4623
+ if (!isDevelopment()) {
4624
+ const sanitized = sanitizeRowForProduction({
4625
+ type: patch.type,
4626
+ ...changes,
4627
+ } as unknown as RowModel) as unknown as Record<string, unknown>;
4628
+ for (const [field, value] of Object.entries(changes)) {
4629
+ if (value === null) continue;
4630
+ if (sanitized[field] === undefined) delete changes[field];
4631
+ else changes[field] = sanitized[field];
4632
+ }
4633
+ }
4634
+ const values = Object.fromEntries(
4635
+ Object.entries(changes).filter(([, value]) => value !== null)
4636
+ );
4637
+ if (patch.type === 'market' && 'metrics' in changes)
4638
+ assertMarketMetrics(
4639
+ changes.metrics as MarketRow['metrics'],
4640
+ `${path}.changes.metrics`
4641
+ );
4642
+ assertPlainSerializable(values, `${path}.changes`, new Set<object>());
4643
+ assertProtocolFields(values, `${path}.changes`);
4644
+ if (isDevelopment())
4645
+ assertPatchChanges({ ...patch, changes: values } as PatchValues, index);
4646
+ const normalizedPatch = {
4647
+ type: patch.type,
4648
+ key: patch.key,
4649
+ changes,
4650
+ } as RowPatch;
4651
+ return Object.keys(changes).length > 0
4652
+ ? normalizePatchStyles([normalizedPatch])[0]
4653
+ : undefined;
4654
+ }
4655
+
4656
+ function reportRejectedPatch(index: number): void {
4657
+ console.warn(`NativeList rejected invalid patch unit at patches[${index}]`);
4658
+ }
4659
+
2074
4660
  export function validatePatches(
2075
4661
  patches: readonly RowPatch[]
2076
4662
  ): readonly RowPatch[] {
2077
- assertPlainSerializable(patches, 'patches', new Set<object>());
2078
- const keys = new Set<string>();
2079
- patches.forEach((patch, index) => {
2080
- assertKey(patch.key, `patches[${index}].key`);
2081
- if (keys.has(patch.key))
2082
- fail(`patches[${index}].key`, `duplicate key "${patch.key}"`);
2083
- keys.add(patch.key);
2084
- if (Object.keys(patch.changes).length === 0) {
2085
- fail(`patches[${index}].changes`, 'must contain at least one field');
4663
+ if (!Array.isArray(patches)) fail('patches', 'must be an array');
4664
+ const units = new Map<string, { patch: RowPatch; index: number }>();
4665
+ const rejectedKeys = new Set<string>();
4666
+ const reject = (key: string, index: number, error: unknown) => {
4667
+ if (isDevelopment()) throw error;
4668
+ rejectedKeys.add(key);
4669
+ reportRejectedPatch(index);
4670
+ };
4671
+ patches.forEach((input, index) => {
4672
+ const key =
4673
+ isRecord(input) && typeof input.key === 'string' ? input.key : '';
4674
+ try {
4675
+ protocolObject(input, `patches[${index}]`);
4676
+ protocolKey(input.key, `patches[${index}].key`);
4677
+ assertRowType(input.type, `patches[${index}]`);
4678
+ const changes = capturePlainData(
4679
+ protocolObject(input.changes, `patches[${index}].changes`)
4680
+ );
4681
+ assertPlainSerializable(
4682
+ changes,
4683
+ `patches[${index}].changes`,
4684
+ new Set<object>(),
4685
+ false
4686
+ );
4687
+ const previous = units.get(key);
4688
+ if (previous && previous.patch.type !== input.type)
4689
+ fail(`patches[${index}].type`, 'conflicting row types');
4690
+ const defined = Object.fromEntries(
4691
+ Object.entries(changes).filter(([, value]) => value !== undefined)
4692
+ );
4693
+ units.set(key, {
4694
+ index,
4695
+ patch: {
4696
+ key,
4697
+ type: input.type,
4698
+ changes: { ...previous?.patch.changes, ...defined },
4699
+ } as RowPatch,
4700
+ });
4701
+ } catch (error) {
4702
+ reject(key, index, error);
2086
4703
  }
2087
- assertPatchChanges(patch, index);
2088
4704
  });
2089
- return normalizePatchStyles(patches);
4705
+ const accepted: RowPatch[] = [];
4706
+ for (const [key, unit] of units) {
4707
+ if (rejectedKeys.has(key)) continue;
4708
+ try {
4709
+ const patch = normalizePatch(unit.patch, unit.index);
4710
+ if (patch) accepted.push(patch);
4711
+ } catch (error) {
4712
+ reject(key, unit.index, error);
4713
+ }
4714
+ }
4715
+ return accepted;
2090
4716
  }
2091
4717
 
2092
4718
  /** Patches reach the native side without passing through a snapshot. */
@@ -2108,44 +4734,313 @@ function normalizePatchStyles(
2108
4734
  return changed ? next : patches;
2109
4735
  }
2110
4736
 
2111
- export function applyRowPatches(
2112
- snapshot: NativeListSnapshot,
2113
- patches: readonly RowPatch[]
2114
- ): NativeListSnapshot {
2115
- validatePatches(patches);
2116
- const patchByKey = new Map(patches.map((patch) => [patch.key, patch]));
2117
- const knownKeys = new Set(snapshot.rows.map((row) => row.key));
2118
- patches.forEach((patch) => {
2119
- if (!knownKeys.has(patch.key))
2120
- fail('patches', `unknown row key "${patch.key}"`);
2121
- });
2122
- const rows = snapshot.rows.map((row): RowModel => {
2123
- const patch = patchByKey.get(row.key);
2124
- if (!patch) return row;
2125
- if (patch.type !== row.type) {
2126
- fail('patches', `row "${row.key}" is ${row.type}, not ${patch.type}`);
4737
+ const EMPTY_ROW_PATCHES: readonly RowPatch[] = Object.freeze([]);
4738
+
4739
+ function sameJsonValue(left: unknown, right: unknown): boolean {
4740
+ if (left === right) return true;
4741
+ if (left === null || right === null) return false;
4742
+ if (typeof left !== 'object' || typeof right !== 'object') return false;
4743
+ if (Array.isArray(left) || Array.isArray(right)) {
4744
+ return (
4745
+ Array.isArray(left) &&
4746
+ Array.isArray(right) &&
4747
+ left.length === right.length &&
4748
+ left.every((value, index) => sameJsonValue(value, right[index]))
4749
+ );
4750
+ }
4751
+ const leftObject = left as Record<string, unknown>;
4752
+ const rightObject = right as Record<string, unknown>;
4753
+ const leftKeys = Object.keys(leftObject).filter(
4754
+ (key) => leftObject[key] !== undefined
4755
+ );
4756
+ const rightKeys = Object.keys(rightObject).filter(
4757
+ (key) => rightObject[key] !== undefined
4758
+ );
4759
+ return (
4760
+ leftKeys.length === rightKeys.length &&
4761
+ leftKeys.every((key) => sameJsonValue(leftObject[key], rightObject[key]))
4762
+ );
4763
+ }
4764
+
4765
+ function sameOptionalPresence(left: unknown, right: unknown): boolean {
4766
+ return (left === undefined) === (right === undefined);
4767
+ }
4768
+
4769
+ /** Plan value-only patches; callers own valid immutable snapshots and commit state. */
4770
+ export function planNativeListPatches(
4771
+ previous: NativeListSnapshot,
4772
+ next: NativeListSnapshot
4773
+ ): readonly RowPatch[] | undefined {
4774
+ if (previous === next) return EMPTY_ROW_PATCHES;
4775
+ const { rows: previousRows, ...previousMetadata } = previous;
4776
+ const { rows: nextRows, ...nextMetadata } = next;
4777
+ if (
4778
+ previousRows.length !== nextRows.length ||
4779
+ !sameJsonValue(previousMetadata, nextMetadata)
4780
+ )
4781
+ return undefined;
4782
+ if (previousRows === nextRows) return EMPTY_ROW_PATCHES;
4783
+
4784
+ const patches: RowPatch[] = [];
4785
+ for (let index = 0; index < nextRows.length; index += 1) {
4786
+ const oldRow = previousRows[index];
4787
+ const row = nextRows[index];
4788
+ if (oldRow.key !== row.key || oldRow.type !== row.type) return undefined;
4789
+ if (oldRow === row) continue;
4790
+
4791
+ if (oldRow.type === 'identity' && row.type === 'identity') {
4792
+ const {
4793
+ subtitle: oldSubtitle,
4794
+ subtitleSegments: oldSubtitleSegments,
4795
+ trailing: oldTrailing,
4796
+ ...oldMetadata
4797
+ } = oldRow;
4798
+ const { subtitle, subtitleSegments, trailing, ...metadata } = row;
4799
+ if (
4800
+ !sameOptionalPresence(oldSubtitle, subtitle) ||
4801
+ !sameOptionalPresence(oldSubtitleSegments, subtitleSegments) ||
4802
+ !sameOptionalPresence(oldTrailing, trailing) ||
4803
+ !sameJsonValue(oldMetadata, metadata)
4804
+ )
4805
+ return undefined;
4806
+ if (
4807
+ !sameJsonValue(oldSubtitle, subtitle) ||
4808
+ !sameJsonValue(oldSubtitleSegments, subtitleSegments) ||
4809
+ !sameJsonValue(oldTrailing, trailing)
4810
+ ) {
4811
+ patches.push({
4812
+ type: 'identity',
4813
+ key: row.key,
4814
+ changes: { subtitle, subtitleSegments, trailing },
4815
+ });
4816
+ }
4817
+ } else if (oldRow.type === 'dataRow' && row.type === 'dataRow') {
4818
+ const {
4819
+ columns: oldColumns,
4820
+ trailing: oldTrailing,
4821
+ ...oldMetadata
4822
+ } = oldRow;
4823
+ const { columns, trailing, ...metadata } = row;
4824
+ if (
4825
+ !sameOptionalPresence(oldTrailing, trailing) ||
4826
+ !sameJsonValue(oldMetadata, metadata) ||
4827
+ !sameJsonValue(oldColumns[0], columns[0])
4828
+ )
4829
+ return undefined;
4830
+ if (
4831
+ !sameJsonValue(oldColumns.slice(1), columns.slice(1)) ||
4832
+ !sameJsonValue(oldTrailing, trailing)
4833
+ ) {
4834
+ patches.push({
4835
+ type: 'dataRow',
4836
+ key: row.key,
4837
+ changes: { columns, trailing },
4838
+ });
4839
+ }
4840
+ } else if (!sameJsonValue(oldRow, row)) {
4841
+ return undefined;
2127
4842
  }
4843
+ }
4844
+ return patches.length === 0 ? EMPTY_ROW_PATCHES : patches;
4845
+ }
4846
+
4847
+ function mergeAndValidateSingleRow(
4848
+ previous: RowModel,
4849
+ patch: RowPatch,
4850
+ index: number
4851
+ ): { row: RowModel; patch: RowPatch } {
4852
+ if (previous.key !== patch.key)
4853
+ fail(`patches[${index}].key`, 'does not match row identity');
4854
+ if (previous.type !== patch.type)
4855
+ fail(`patches[${index}].type`, 'does not match row type');
4856
+ const changes = { ...patch.changes } as Record<string, unknown>;
4857
+ if (previous.type === 'market') {
4858
+ if (
4859
+ typeof changes.price === 'string' &&
4860
+ !('priceSegments' in changes) &&
4861
+ previous.priceSegments !== undefined
4862
+ )
4863
+ changes.priceSegments = null;
2128
4864
  if (
2129
- row.type === 'market' &&
2130
- row.webTable &&
2131
- patch.type === 'market' &&
2132
- (patch.changes.price !== undefined ||
2133
- patch.changes.priceSegments !== undefined ||
2134
- patch.changes.change !== undefined) &&
2135
- patch.changes.webTable === undefined
4865
+ (previous.webTable !== undefined || 'webTable' in changes) &&
4866
+ ['price', 'priceSegments', 'change'].some((field) => field in changes) &&
4867
+ changes.webTable === undefined
2136
4868
  )
2137
4869
  fail(
2138
- 'patches',
2139
- 'table quote changes must include the visible table cells'
4870
+ `patches[${index}].changes.webTable`,
4871
+ 'table quote changes require visible table cells'
2140
4872
  );
2141
- return {
2142
- ...row,
2143
- ...patch.changes,
2144
- key: row.key,
2145
- type: row.type,
2146
- } as RowModel;
4873
+ }
4874
+ if (previous.type === 'identity' || previous.type === 'market') {
4875
+ if (
4876
+ typeof changes.subtitle === 'string' &&
4877
+ !('subtitleSegments' in changes) &&
4878
+ previous.subtitleSegments !== undefined
4879
+ )
4880
+ changes.subtitleSegments = null;
4881
+ if (
4882
+ Array.isArray(changes.subtitleSegments) &&
4883
+ changes.subtitleSegments.length > 0 &&
4884
+ !('subtitle' in changes) &&
4885
+ previous.subtitle !== undefined
4886
+ )
4887
+ changes.subtitle = null;
4888
+ }
4889
+ // The offset points into one specific description string, so a patch that
4890
+ // replaces the description without restating it falls back to the default.
4891
+ if (
4892
+ previous.type === 'activity' &&
4893
+ 'description' in changes &&
4894
+ changes.description !== previous.description &&
4895
+ !('descriptionActionStart' in changes) &&
4896
+ previous.descriptionActionStart !== undefined
4897
+ )
4898
+ changes.descriptionActionStart = null;
4899
+ const merged = { ...previous } as unknown as Record<string, unknown>;
4900
+ for (const [field, value] of Object.entries(changes)) {
4901
+ if (value === null) delete merged[field];
4902
+ else if (value !== undefined) merged[field] = value;
4903
+ }
4904
+ const next = normalizeRowStyles(merged as unknown as RowModel);
4905
+ assertPlainSerializable(next, `rows[${index}]`, new Set<object>());
4906
+ if (isDevelopment()) assertRow(next, index);
4907
+ assertRowProtocol(next, `rows[${index}]`);
4908
+ return {
4909
+ row: next,
4910
+ patch: { type: patch.type, key: patch.key, changes } as RowPatch,
4911
+ };
4912
+ }
4913
+
4914
+ /** One canonical batch owns both accepted rows and the native wire payload. */
4915
+ export function applyValidatedRowPatches(
4916
+ snapshot: NativeListSnapshot,
4917
+ patches: readonly RowPatch[]
4918
+ ): {
4919
+ patches: readonly RowPatch[];
4920
+ snapshot: NativeListSnapshot;
4921
+ json: string;
4922
+ } {
4923
+ if (!Array.isArray(patches)) fail('patches', 'must be an array');
4924
+ const owned = ownedNativeSnapshots.has(snapshot);
4925
+ const rowIndexes =
4926
+ ownedNativeSnapshots.get(snapshot) ??
4927
+ validatedRowIndexes.get(snapshot) ??
4928
+ new Map(snapshot.rows.map((row, index) => [row.key, index]));
4929
+ validatedRowIndexes.set(snapshot, rowIndexes);
4930
+ const units = new Map<
4931
+ string,
4932
+ { index: number; changes: Record<string, unknown>; type: RowPatch['type'] }
4933
+ >();
4934
+ const rejected = new Set<string>();
4935
+ const rejectedGroups = new Set<string>();
4936
+ const reject = (key: string, index: number, error: unknown) => {
4937
+ if (isDevelopment()) throw error;
4938
+ rejected.add(key);
4939
+ const rowIndex = rowIndexes.get(key);
4940
+ const group =
4941
+ rowIndex === undefined ? undefined : snapshot.rows[rowIndex].groupId;
4942
+ if (group) rejectedGroups.add(group);
4943
+ reportRejectedPatch(index);
4944
+ };
4945
+ patches.forEach((input, index) => {
4946
+ const key =
4947
+ isRecord(input) && typeof input.key === 'string' ? input.key : '';
4948
+ try {
4949
+ protocolObject(input, `patches[${index}]`);
4950
+ protocolKey(input.key, `patches[${index}].key`);
4951
+ const rowIndex = rowIndexes.get(input.key);
4952
+ if (rowIndex === undefined)
4953
+ fail(`patches[${index}].key`, 'unknown row identity');
4954
+ if (snapshot.rows[rowIndex].type !== input.type)
4955
+ fail(`patches[${index}].type`, 'does not match row type');
4956
+ const changes = protocolObject(
4957
+ input.changes,
4958
+ `patches[${index}].changes`
4959
+ );
4960
+ const captured = capturePlainData(changes);
4961
+ assertPlainSerializable(
4962
+ captured,
4963
+ `patches[${index}].changes`,
4964
+ new Set<object>(),
4965
+ false
4966
+ );
4967
+ const previous = units.get(input.key);
4968
+ // Undefined is omitted at every merge, so it cannot overwrite an earlier change.
4969
+ const defined = Object.fromEntries(
4970
+ Object.entries(captured).filter(([, value]) => value !== undefined)
4971
+ );
4972
+ units.set(input.key, {
4973
+ index,
4974
+ type: input.type,
4975
+ changes: { ...previous?.changes, ...defined },
4976
+ });
4977
+ } catch (error) {
4978
+ reject(key, index, error);
4979
+ }
2147
4980
  });
2148
- return validateSnapshot({ ...snapshot, rows });
4981
+ const pending = new Map<string, { row: RowModel; patch: RowPatch }>();
4982
+ for (const [key, unit] of units) {
4983
+ if (rejected.has(key)) continue;
4984
+ try {
4985
+ const patch = normalizePatch(
4986
+ { key, type: unit.type, changes: unit.changes } as RowPatch,
4987
+ unit.index
4988
+ );
4989
+ if (!patch) continue;
4990
+ const merged = mergeAndValidateSingleRow(
4991
+ snapshot.rows[rowIndexes.get(key)!],
4992
+ patch,
4993
+ rowIndexes.get(key)!
4994
+ );
4995
+ if (merged.row.disabled && snapshot.selection?.selectedKeys.includes(key))
4996
+ fail(`patches[${unit.index}]`, 'cannot disable a selected row');
4997
+ pending.set(key, merged);
4998
+ } catch (error) {
4999
+ reject(key, unit.index, error);
5000
+ }
5001
+ }
5002
+ const accepted: RowPatch[] = [];
5003
+ let rows: RowModel[] | undefined;
5004
+ for (const [key, value] of pending) {
5005
+ const index = rowIndexes.get(key)!;
5006
+ const group = snapshot.rows[index].groupId;
5007
+ if (rejected.has(key) || (group && rejectedGroups.has(group))) continue;
5008
+ if (!rows) rows = snapshot.rows.slice();
5009
+ rows[index] = owned ? deepFreeze(value.row) : value.row;
5010
+ accepted.push(owned ? deepFreeze(value.patch) : value.patch);
5011
+ }
5012
+ if (!rows) return { patches: EMPTY_ROW_PATCHES, snapshot, json: '[]' };
5013
+ const next = owned
5014
+ ? Object.freeze({ ...snapshot, rows: Object.freeze(rows) })
5015
+ : { ...snapshot, rows };
5016
+ if (owned) ownedNativeSnapshots.set(next, rowIndexes);
5017
+ else validatedRowIndexes.set(next, rowIndexes);
5018
+ return { patches: accepted, snapshot: next, json: JSON.stringify(accepted) };
5019
+ }
5020
+
5021
+ const validatedRowIndexes = new WeakMap<
5022
+ NativeListSnapshot,
5023
+ ReadonlyMap<string, number>
5024
+ >();
5025
+
5026
+ export function applyOwnedNativePatches(
5027
+ snapshot: NativeListSnapshot,
5028
+ patches: readonly RowPatch[]
5029
+ ) {
5030
+ const owned = ownedNativeSnapshots.has(snapshot)
5031
+ ? snapshot
5032
+ : ownValidatedNativeSnapshot(validateSnapshot(capturePlainData(snapshot)));
5033
+ return applyValidatedRowPatches(owned, patches);
5034
+ }
5035
+
5036
+ export function applyRowPatches(
5037
+ snapshot: NativeListSnapshot,
5038
+ patches: readonly RowPatch[]
5039
+ ): NativeListSnapshot {
5040
+ const baseline = ownedNativeSnapshots.has(snapshot)
5041
+ ? snapshot
5042
+ : validateSnapshot(snapshot);
5043
+ return applyValidatedRowPatches(baseline, patches).snapshot;
2149
5044
  }
2150
5045
 
2151
5046
  export function serializeSnapshot(snapshot: NativeListSnapshot): string {