@onekeyfe/react-native-native-list 6.7.0-7 → 6.7.0-8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/SPEC.md CHANGED
@@ -182,6 +182,45 @@ All twelve templates have their own renderer family: Message, Rail, MediaTile,
182
182
  Action, System, Activity, DataRow, MetricCard, Market, Identity, SectionHeader and
183
183
  WalletGroup. Same-key family changes must replace the incompatible host. OneKeyImage owns image caches; NativeList owns row/slot binding identity.
184
184
 
185
+ Keys are opaque strings and MUST contain at least one non-whitespace character.
186
+ Leading and trailing whitespace is valid and MUST be preserved in snapshots,
187
+ patches, selection and emitted events on
188
+ iOS, Android and Web. The SDK MUST NOT trim or otherwise normalize keys;
189
+ `token` and `token ` identify different rows. Duplicate checks use the exact
190
+ string. This rule applies to all key fields validated by the shared protocol;
191
+ section index titles retain their separate development-only
192
+ no-surrounding-whitespace assertion.
193
+ The 256-code-unit key limit is a development assertion, not a production limit.
194
+
195
+ ### Validation environments and rejected input
196
+
197
+ Development builds (`__DEV__ === true`) run the complete snapshot and patch
198
+ contract assertions. Production builds run only serialization, required data
199
+ shape, supported renderer, finite geometry, identity and patch consistency
200
+ guards. Display budgets and style allowlists are development assertions.
201
+ Typography token resolution runs in both environments. Production treats empty
202
+ optional image URIs as missing images, preserving the existing visual fallback.
203
+ An empty optional image field omitted from a patch is a no-op, matching its
204
+ serialized native payload. Sparkline sample arrays retain their existing
205
+ 256-sample resource bound because the Web renderer passes samples as function
206
+ arguments; this protects the runtime's argument limit.
207
+
208
+ The component and Web engine contain input validation failures in both modes:
209
+ initial invalid input renders an empty list; rejected later snapshots or patch
210
+ batches preserve the last accepted state and are not dispatched to native.
211
+ Rejection emits a diagnostic without including row keys, text or image URLs.
212
+ Explicit calls to the exported validation functions still throw on rejected
213
+ input, so development tooling can inspect the full contract failure. Rejection
214
+ does not imply that the requested update succeeded. No row identity is trimmed,
215
+ truncated or regenerated, and no invalid row is silently dropped from a batch.
216
+
217
+ Status: implemented. Development/production JS regressions pass, including
218
+ native wrappers for iOS/Android and the Web DOM engine. Real Swift XCTest on an
219
+ iOS 27 simulator and Android instrumentation on API 35 verify production
220
+ serialization, normalized typography, opaque identities and duplicate-key
221
+ protection against the shipping native parsers. Full app/device rendering and
222
+ gesture acceptance remain separate from these input-boundary checks.
223
+
185
224
  ## Platform contract
186
225
 
187
226
  All platforms expose the same bounded style properties and public semantics.
@@ -238,13 +277,15 @@ state, all templates and container text, and retained selection/scroll behavior.
238
277
  ## Failures, fallback and limits
239
278
 
240
279
  Snapshot validation rejects malformed/duplicate-key input without partial
241
- application. Template field/array bounds and image fallback behavior are defined
280
+ application, through the contained failure behavior above. Development-only
281
+ template field/array bounds and image fallback behavior are defined
242
282
  in [ROW_TEMPLATES.md](ROW_TEMPLATES.md), [README.md](../README.md) and
243
283
  [DESIGN.md](DESIGN.md). This change adds the style surface's limits, defined in
244
284
  [STYLE_SPEC.md](STYLE_SPEC.md) §3.3/§4/§5: numeric bounds, `#RRGGBB`/`#RRGGBBAA`
245
285
  colors (including `listStyle.separator.color`), `groupCornerRadius` `0…40`, and
246
- rejection of any undeclared or unknown nested style key by `validateSnapshot`
247
- and `validatePatches`, where extra keys used to be ignored. It adds no retry
286
+ development-time rejection of undeclared or unknown nested style keys by
287
+ `validateSnapshot` and `validatePatches`. Production renderers ignore unsupported
288
+ style properties while minimum protocol guards remain active. It adds no retry
248
289
  policy or automatic layout correction.
249
290
 
250
291
  ## Performance and resources
@@ -1,14 +1,14 @@
1
1
  "use strict";
2
2
 
3
3
  import { useNativeListFontFamiliesJson } from "./fonts.js";
4
- import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
4
+ import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
5
5
  import { OneKeyImageCache, OneKeyImageCachePolicy } from '@onekeyfe/react-native-image';
6
6
  import { NativeAvatarPrefetchModel, NativeAvatarPrefetchQueue } from "./avatarPrefetch.js";
7
7
  import { Platform, View } from 'react-native';
8
8
  import { callback, getHostComponent } from 'react-native-nitro-modules';
9
9
  import { isSelectableRow } from "./selection.js";
10
10
  import { normalizeIndexScroll, normalizeKeyScroll, normalizePositionScroll, resolveLocationIndex, scrollFailure, validateOffset } from "./scrolling.js";
11
- import { applyRowPatches, serializePatches, serializeSnapshot } from "./validation.js";
11
+ import { applyRowPatches, containNativeListInput, emptyNativeListSnapshot, serializePatches, validatePatches, validateSnapshot } from "./validation.js";
12
12
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
13
13
  const NativeListConfig = require('../nitrogen/generated/shared/json/NativeListConfig.json');
14
14
  const NativeListHost = getHostComponent('NativeList', () => NativeListConfig);
@@ -27,7 +27,7 @@ function parsePayload(payloadJson) {
27
27
  return JSON.parse(payloadJson);
28
28
  }
29
29
  export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
30
- snapshot,
30
+ snapshot: inputSnapshot,
31
31
  listHeader,
32
32
  listFooter,
33
33
  listEmpty,
@@ -55,15 +55,21 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
55
55
  initialScrollViewOffset,
56
56
  ...viewProps
57
57
  }, forwardedRef) {
58
+ const snapshotRef = useRef(emptyNativeListSnapshot());
59
+ const initializedSnapshot = useRef(false);
60
+ const hasContainerSlots = Boolean(listHeader || listEmpty || listFooter);
61
+ const prepareSnapshot = useCallback(next => {
62
+ const accepted = validateSnapshot(next);
63
+ if (hasContainerSlots && accepted.layout.orientation === 'horizontal') throw new Error('NativeList container slots require vertical orientation');
64
+ return accepted;
65
+ }, [hasContainerSlots]);
66
+ const snapshot = useMemo(() => containNativeListInput(() => prepareSnapshot(inputSnapshot)) ?? snapshotRef.current, [inputSnapshot, prepareSnapshot]);
58
67
  const fontFamiliesJson = useNativeListFontFamiliesJson();
59
68
  const [slotHeights, setSlotHeights] = useState([0, 0, 0]);
60
69
  const [topOverlayHeight, setTopOverlayHeight] = useState(0);
61
70
  const hasTopOverlay = Platform?.OS === 'ios' && parseInt(String(Platform.Version), 10) >= 26 && (topScrollEdgeEffect === 'hard' || topScrollEdgeEffect === 'soft') && topOverlay != null;
62
71
  const containerSlotHeightsJson = JSON.stringify(slotHeights);
63
72
  const slotInset = snapshot.layout.contentPaddingHorizontal ?? snapshot.layout.contentPadding ?? 0;
64
- if (snapshot.layout.orientation === 'horizontal' && (listHeader || listEmpty || listFooter)) {
65
- throw new Error('NativeList container slots require vertical orientation');
66
- }
67
73
  const slotContents = [listHeader, listEmpty, listFooter];
68
74
  const normalizedKeyboardShouldPersistTaps = keyboardShouldPersistTaps === true ? 'always' : keyboardShouldPersistTaps === false ? 'never' : keyboardShouldPersistTaps;
69
75
  const nativeRef = useRef(null);
@@ -89,7 +95,7 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
89
95
  onRefresh,
90
96
  onScrollToIndexFailed
91
97
  };
92
- const scrollPositionThresholdsJson = useMemo(() => {
98
+ const scrollPositionThresholdsJson = useMemo(() => containNativeListInput(() => {
93
99
  if (!scrollPositionThresholds || scrollPositionThresholds.enabled === false) return '';
94
100
  const {
95
101
  start,
@@ -102,15 +108,18 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
102
108
  start,
103
109
  end
104
110
  });
105
- }, [scrollPositionThresholds]);
106
- const snapshotJson = useMemo(() => serializeSnapshot(snapshot), [snapshot]);
107
- const snapshotRef = useRef(snapshot);
111
+ }) ?? '', [scrollPositionThresholds]);
112
+ const snapshotJson = useMemo(() => JSON.stringify(snapshot), [snapshot]);
108
113
  const previousSnapshotJsonRef = useRef(snapshotJson);
109
114
  const snapshotChanged = previousSnapshotJsonRef.current !== snapshotJson;
110
115
  if (snapshotChanged) {
111
116
  snapshotRef.current = snapshot;
112
117
  previousSnapshotJsonRef.current = snapshotJson;
113
118
  }
119
+ if (!initializedSnapshot.current) {
120
+ snapshotRef.current = snapshot;
121
+ initializedSnapshot.current = true;
122
+ }
114
123
  // OneKey patch: range events already cross the bridge only when row indices
115
124
  // change. Prefetch is optional work; scrolling and visible loads stay native.
116
125
  const avatarQueueRef = useRef(null);
@@ -142,7 +151,7 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
142
151
  useEffect(() => {
143
152
  updateAvatarPrefetchRef.current();
144
153
  }, [snapshot]);
145
- const initialScrollRef = useRef(initialScrollIndex === undefined && initialScrollKey === undefined ? undefined : initialScrollIndex !== undefined ? normalizeIndexScroll({
154
+ const initialScrollRef = useRef(containNativeListInput(() => initialScrollIndex === undefined && initialScrollKey === undefined ? undefined : initialScrollIndex !== undefined ? normalizeIndexScroll({
146
155
  index: initialScrollIndex,
147
156
  animated: false,
148
157
  viewPosition: initialScrollViewPosition,
@@ -154,7 +163,7 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
154
163
  viewPosition: initialScrollViewPosition,
155
164
  viewOffset: initialScrollViewOffset
156
165
  }, 'start')
157
- });
166
+ }));
158
167
  const didApplyInitialScroll = useRef(false);
159
168
  const emitIndexFailure = (index, reason) => {
160
169
  callbacksRef.current.onScrollToIndexFailed?.(scrollFailure(snapshotRef.current.rows, index, reason));
@@ -180,27 +189,37 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
180
189
  applyInitialScrollCallbackRef.current = applyInitialScroll;
181
190
  useImperativeHandle(forwardedRef, () => ({
182
191
  applySnapshot(nextSnapshot) {
183
- const nextSnapshotJson = serializeSnapshot(nextSnapshot);
192
+ const accepted = containNativeListInput(() => prepareSnapshot(nextSnapshot));
193
+ if (!accepted) return;
194
+ const nextSnapshotJson = JSON.stringify(accepted);
184
195
  nativeRef.current?.applySnapshot(nextSnapshotJson);
185
- snapshotRef.current = nextSnapshot;
196
+ snapshotRef.current = accepted;
186
197
  if (nativeRef.current && avatarLifecycle.current !== 'unmounted') {
187
- avatarModelRef.current?.replaceSnapshot(nextSnapshot.rows);
198
+ avatarModelRef.current?.replaceSnapshot(accepted.rows);
188
199
  updateAvatarPrefetchRef.current();
189
200
  }
190
201
  },
191
202
  applyPatches(patches) {
192
- if (patches.length === 0) return;
193
- const nextSnapshot = applyRowPatches(snapshotRef.current, patches);
203
+ const accepted = containNativeListInput(() => {
204
+ const normalized = validatePatches(patches);
205
+ return {
206
+ patches: normalized,
207
+ snapshot: applyRowPatches(snapshotRef.current, normalized),
208
+ json: serializePatches(normalized)
209
+ };
210
+ });
211
+ if (!accepted || accepted.patches.length === 0) return;
212
+ const nextSnapshot = accepted.snapshot;
194
213
  const native = nativeRef.current;
195
214
  const dispatch = native ? () => {
196
- native.applyPatches(serializePatches(patches));
215
+ native.applyPatches(accepted.json);
197
216
  snapshotRef.current = nextSnapshot;
198
217
  } : undefined;
199
218
  if (avatarLifecycle.current === 'unmounted') {
200
219
  dispatch?.();
201
220
  return;
202
221
  }
203
- if (avatarModelRef.current?.applyPatches(patches, dispatch)) updateAvatarPrefetchRef.current();
222
+ if (avatarModelRef.current?.applyPatches(accepted.patches, dispatch)) updateAvatarPrefetchRef.current();
204
223
  },
205
224
  reconcileSelection(selectedKeys) {
206
225
  nativeRef.current?.reconcileSelection(JSON.stringify(selectedKeys));
@@ -4,7 +4,7 @@ import { useNativeListFontFamiliesJson } from "./fonts.js";
4
4
  import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
5
5
  import { View } from 'react-native';
6
6
  import { normalizeIndexScroll, normalizeKeyScroll, normalizePositionScroll, resolveLocationIndex, scrollFailure, validateOffset } from "./scrolling.js";
7
- import { applyRowPatches, validateSnapshot } from "./validation.js";
7
+ import { applyRowPatches, containNativeListInput, emptyNativeListSnapshot, validatePatches, validateSnapshot } from "./validation.js";
8
8
  import { NativeListWebEngine } from "./web/NativeListWebEngine.js";
9
9
  import { acquireNativeListAvatar, canonicalNativeListAvatarUri } from "./web/NativeListWebAvatarCache.js";
10
10
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
@@ -22,14 +22,14 @@ export function preloadNativeListAvatarImages(sources) {
22
22
  }))).then(results => results.every(Boolean));
23
23
  }
24
24
  export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
25
- snapshot,
25
+ snapshot: inputSnapshot,
26
26
  listHeader,
27
27
  listEmpty,
28
28
  listFooter,
29
29
  topOverlay: _topOverlay,
30
30
  topScrollEdgeEffect: _topScrollEdgeEffect,
31
31
  webScrollHost,
32
- webStickyInset = 0,
32
+ webStickyInset: inputStickyInset = 0,
33
33
  scrollPositionThresholds: _scrollPositionThresholds,
34
34
  onScrollPositionThresholdChange: _onScrollPositionThresholdChange,
35
35
  webVirtualizationEnabled = true,
@@ -50,6 +50,14 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
50
50
  initialScrollViewOffset,
51
51
  ...viewProps
52
52
  }, forwardedRef) {
53
+ const acceptedSnapshotRef = useRef(emptyNativeListSnapshot());
54
+ const initializedSnapshot = useRef(false);
55
+ const webStickyInset = useMemo(() => containNativeListInput(() => {
56
+ if (!Number.isFinite(inputStickyInset) || inputStickyInset < 0) throw new Error('webStickyInset must be finite and non-negative');
57
+ return inputStickyInset;
58
+ }) ?? 0, [inputStickyInset]);
59
+ const preparedSnapshot = useMemo(() => containNativeListInput(() => validateSnapshot(inputSnapshot)), [inputSnapshot]);
60
+ const snapshot = preparedSnapshot ?? acceptedSnapshotRef.current;
53
61
  const fontFamiliesJson = useNativeListFontFamiliesJson();
54
62
  const fontFamiliesJsonRef = useRef(fontFamiliesJson);
55
63
  fontFamiliesJsonRef.current = fontFamiliesJson;
@@ -93,19 +101,23 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
93
101
  useSlotLayoutRef.current ||= webScrollHost !== undefined || listHeader !== undefined || listEmpty !== undefined || listFooter !== undefined;
94
102
  const useSlotLayout = useSlotLayoutRef.current;
95
103
  const resolvedScrollHost = webScrollHost === undefined ? useSlotLayout ? ownedScrollHost : undefined : webScrollHost;
96
- if (!Number.isFinite(webStickyInset) || webStickyInset < 0) throw new Error('webStickyInset must be finite and non-negative');
97
104
  const engineRef = useRef(undefined);
98
105
  const webVirtualizationEnabledRef = useRef(webVirtualizationEnabled);
99
106
  webVirtualizationEnabledRef.current = webVirtualizationEnabled;
100
- const validatedSnapshot = useMemo(() => normalizeWebSnapshot(snapshot, hasEmptySlot, useSlotLayout), [snapshot, hasEmptySlot, useSlotLayout]);
107
+ const validatedSnapshot = useMemo(() => containNativeListInput(() => normalizeWebSnapshot(snapshot, hasEmptySlot, useSlotLayout)) ?? acceptedSnapshotRef.current, [snapshot, hasEmptySlot, useSlotLayout]);
101
108
  const snapshotRef = useRef(validatedSnapshot);
102
109
  const snapshotPropRef = useRef(validatedSnapshot);
103
110
  // An imperative snapshot survives host mounting until the snapshot prop changes.
104
111
  if (snapshotPropRef.current !== validatedSnapshot) {
105
112
  snapshotPropRef.current = validatedSnapshot;
106
113
  snapshotRef.current = validatedSnapshot;
114
+ acceptedSnapshotRef.current = validatedSnapshot;
107
115
  synchronizeSlots(snapshot);
108
116
  }
117
+ if (!initializedSnapshot.current) {
118
+ acceptedSnapshotRef.current = validatedSnapshot;
119
+ initializedSnapshot.current = true;
120
+ }
109
121
  const appliedSnapshotRef = useRef(undefined);
110
122
  const callbacksRef = useRef({});
111
123
  callbacksRef.current = {
@@ -118,7 +130,7 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
118
130
  onRefresh,
119
131
  onScrollToIndexFailed
120
132
  };
121
- const initialScrollRef = useRef(initialScrollIndex === undefined && initialScrollKey === undefined ? undefined : initialScrollIndex !== undefined ? normalizeIndexScroll({
133
+ const initialScrollRef = useRef(containNativeListInput(() => initialScrollIndex === undefined && initialScrollKey === undefined ? undefined : initialScrollIndex !== undefined ? normalizeIndexScroll({
122
134
  index: initialScrollIndex,
123
135
  animated: false,
124
136
  viewPosition: initialScrollViewPosition,
@@ -130,7 +142,7 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
130
142
  viewPosition: initialScrollViewPosition,
131
143
  viewOffset: initialScrollViewOffset
132
144
  }, 'start')
133
- });
145
+ }));
134
146
  const didApplyInitialScroll = useRef(false);
135
147
  const scrollOptionsRef = useRef({
136
148
  stickyInset: webStickyInset,
@@ -142,11 +154,12 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
142
154
  };
143
155
  useEffect(() => {
144
156
  if (!host || resolvedScrollHost === null || useSlotLayout && !contentBounds) return;
145
- const engine = new NativeListWebEngine(host, snapshotRef.current, callbacksRef.current, webVirtualizationEnabledRef.current, webSectionIndexContainerRef?.current, fontFamiliesJsonRef.current, {
157
+ const engine = containNativeListInput(() => new NativeListWebEngine(host, snapshotRef.current, callbacksRef.current, webVirtualizationEnabledRef.current, webSectionIndexContainerRef?.current, fontFamiliesJsonRef.current, {
146
158
  scrollHost: resolvedScrollHost,
147
159
  contentBounds: contentBounds ?? undefined,
148
160
  ...scrollOptionsRef.current
149
- });
161
+ }));
162
+ if (!engine) return;
150
163
  host.style.height = '';
151
164
  engineRef.current = engine;
152
165
  appliedSnapshotRef.current = snapshotRef.current;
@@ -185,19 +198,26 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
185
198
  };
186
199
  useImperativeHandle(forwardedRef, () => ({
187
200
  applySnapshot(nextSnapshot) {
188
- const next = normalizeWebSnapshot(nextSnapshot);
201
+ const next = containNativeListInput(() => normalizeWebSnapshot(nextSnapshot));
202
+ if (!next) return;
189
203
  engineRef.current?.applySnapshot(next);
190
204
  snapshotRef.current = next;
205
+ acceptedSnapshotRef.current = next;
191
206
  appliedSnapshotRef.current = next;
192
- synchronizeSlots(nextSnapshot);
207
+ synchronizeSlots(next);
193
208
  },
194
209
  applyPatches(patches) {
195
- if (patches.length > 0) {
210
+ const accepted = containNativeListInput(() => validatePatches(patches));
211
+ if (accepted && accepted.length > 0) {
196
212
  const engine = engineRef.current;
197
213
  if (engine) {
198
- engine.applyPatches(patches);
214
+ engine.applyPatches(accepted);
199
215
  snapshotRef.current = engine.currentSnapshot();
200
- } else snapshotRef.current = applyRowPatches(snapshotRef.current, patches);
216
+ } else {
217
+ const next = containNativeListInput(() => applyRowPatches(snapshotRef.current, accepted));
218
+ if (next) snapshotRef.current = next;
219
+ }
220
+ acceptedSnapshotRef.current = snapshotRef.current;
201
221
  }
202
222
  },
203
223
  reconcileSelection(selectedKeys) {
@@ -12,8 +12,40 @@ const MAX_HEADER_LENGTH = 4096;
12
12
  const MAX_SPACER_HEIGHT = 512;
13
13
  const MAX_SECTION_INDEX_TITLE_LENGTH = 8;
14
14
  const MAX_MARKET_BADGES = 3;
15
+ function isDevelopment() {
16
+ return typeof __DEV__ !== 'undefined' && __DEV__;
17
+ }
18
+ class NativeListInputError extends Error {
19
+ constructor(path, reason) {
20
+ super(`NativeList ${path}: ${reason}`);
21
+ this.path = path;
22
+ this.reason = reason;
23
+ }
24
+ }
15
25
  function fail(path, message) {
16
- throw new Error(`NativeList ${path}: ${message}`);
26
+ throw new NativeListInputError(path, message);
27
+ }
28
+
29
+ /** Component boundaries report locations, never caller-controlled payload values. */
30
+ export function containNativeListInput(operation) {
31
+ try {
32
+ return operation();
33
+ } catch (error) {
34
+ const path = error instanceof NativeListInputError ? error.path : 'input';
35
+ const reason = isDevelopment() && error instanceof NativeListInputError ? `: ${error.reason.split('"')[0].trim()}` : '';
36
+ console.warn(`NativeList rejected invalid input at ${path}${reason}`);
37
+ return undefined;
38
+ }
39
+ }
40
+ export function emptyNativeListSnapshot() {
41
+ return {
42
+ schemaVersion: 1,
43
+ generation: 0,
44
+ layout: {
45
+ kind: 'linear'
46
+ },
47
+ rows: []
48
+ };
17
49
  }
18
50
  function assertPlainSerializable(value, path, seen) {
19
51
  if (value === null || value === undefined) return;
@@ -39,10 +71,9 @@ function assertPlainSerializable(value, path, seen) {
39
71
  seen.delete(objectValue);
40
72
  }
41
73
  function assertKey(key, path) {
42
- if (typeof key !== 'string' || key.length === 0 || key.length > MAX_KEY_LENGTH) {
43
- fail(path, `must be a non-empty string no longer than ${MAX_KEY_LENGTH} characters`);
74
+ if (typeof key !== 'string' || key.trim().length === 0 || key.length > MAX_KEY_LENGTH) {
75
+ fail(path, `must be a non-blank string no longer than ${MAX_KEY_LENGTH} characters`);
44
76
  }
45
- if (key.trim() !== key) fail(path, 'must not have leading or trailing whitespace');
46
77
  }
47
78
  function assertText(text, path) {
48
79
  if (text === undefined) return;
@@ -906,7 +937,7 @@ function assertMediaPreview(value, path) {
906
937
  fail(`${path}.probeOrder`, 'must contain one or two distinct image/video candidates');
907
938
  }
908
939
  }
909
- export function validateSnapshot(snapshot) {
940
+ function assertSnapshotContract(snapshot) {
910
941
  if (snapshot.capabilities?.refreshTriggerDistance !== undefined && (!Number.isFinite(snapshot.capabilities.refreshTriggerDistance) || snapshot.capabilities.refreshTriggerDistance <= 0)) fail('capabilities.refreshTriggerDistance', 'must be a positive finite number');
911
942
  assertPlainSerializable(snapshot, 'snapshot', new Set());
912
943
  assertText(snapshot.theme?.imageFallbackBackground, 'theme.imageFallbackBackground');
@@ -978,7 +1009,170 @@ export function validateSnapshot(snapshot) {
978
1009
  if (snapshot.selection?.mode === 'single' && selectedKeys.size > 1) {
979
1010
  fail('snapshot.selection.selectedKeys', 'supports at most one key in single mode');
980
1011
  }
981
- return normalizeSnapshotStyles(snapshot);
1012
+ return snapshot;
1013
+ }
1014
+ function protocolObject(value, path) {
1015
+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail(path, 'must be an object');
1016
+ return value;
1017
+ }
1018
+ function protocolKey(value, path) {
1019
+ if (typeof value !== 'string' || value.trim().length === 0) fail(path, 'must be a non-blank string');
1020
+ }
1021
+ const PROTOCOL_ARRAY_FIELDS = new Set(['columns', 'cells', 'points', 'images', 'overlays', 'badges', 'trailing', 'footerActions', 'amounts', 'metrics', 'children', 'subtitleSegments', 'titleMatch', 'selectedKeys', 'segments', 'hoverSecondary', 'hoverImages', 'secondaryBadges', 'fallbackUris', 'probeOrder', 'priceSegments', 'textSegments', 'secondaryTextSegments', 'primaryTextSegments']);
1022
+ const PROTOCOL_NUMBER_FIELDS = new Set(['height', 'width', 'fontSize', 'lineHeight', 'opacity', 'offsetY', 'offsetX', 'cornerRadius', 'borderWidth', 'horizontalPadding', 'verticalPadding', 'leadingGap', 'lineGap', 'titleBadgeGap', 'trailingGap', 'start', 'end', 'padding', 'offset', 'overscan', 'minWidth', 'flex', 'paddingStart', 'paddingEnd', 'changeWidth', 'changeHeight', 'changeCornerRadius', 'contentTrailingGap', 'subtitleTrailingPadding', 'partGap', 'contentPadding', 'contentPaddingHorizontal', 'contentPaddingTop', 'contentPaddingBottom', 'itemSpacing', 'gridColumns']);
1023
+
1024
+ /** Validate only shapes that renderers dereference, not display budgets. */
1025
+ function assertProtocolFields(value, path, parentField = '') {
1026
+ if (value === undefined || value === null || typeof value !== 'object') return;
1027
+ if (Array.isArray(value)) {
1028
+ for (const [index, item] of value.entries()) {
1029
+ const itemPath = `${path}[${index}]`;
1030
+ if (['selectedKeys', 'fallbackUris', 'probeOrder'].includes(parentField)) {
1031
+ if (typeof item !== 'string') fail(itemPath, 'must be a string');
1032
+ } else if (parentField === 'points') {
1033
+ if (typeof item !== 'number') fail(itemPath, 'must be a finite number');
1034
+ } else if (parentField === 'hoverImages' && item === null) continue;else protocolObject(item, itemPath);
1035
+ assertProtocolFields(item, itemPath, parentField);
1036
+ }
1037
+ return;
1038
+ }
1039
+ const object = value;
1040
+ if (!path.includes('.style.') && ['image', 'networkImage', 'thumbnail', 'images', 'hoverImages'].includes(parentField) && typeof object.uri !== 'string') fail(`${path}.uri`, 'must be a string');
1041
+ Object.entries(value).forEach(([field, item]) => {
1042
+ if (item === undefined) return;
1043
+ const fieldPath = `${path}.${field}`;
1044
+ if (!path.endsWith('.style') && PROTOCOL_ARRAY_FIELDS.has(field) && !Array.isArray(item)) fail(fieldPath, 'must be an array');
1045
+ if (PROTOCOL_NUMBER_FIELDS.has(field) && typeof item !== 'number') fail(fieldPath, 'must be a finite number');
1046
+ if (PROTOCOL_NUMBER_FIELDS.has(field) && typeof item === 'number' && item < 0 && !['offsetX', 'offsetY'].includes(field)) fail(fieldPath, 'must be non-negative');
1047
+ if (field === 'key' || field === 'sectionKey' || field === 'actionKey' || field.endsWith('ActionKey')) protocolKey(item, fieldPath);
1048
+ if ((field === 'uri' || field === 'fallbackUri') && typeof item !== 'string') fail(fieldPath, 'must be a string');
1049
+ if (field === 'style' && !(item === 'subscript' && /[Ss]egments\[/.test(path)) || field === 'container') protocolObject(item, fieldPath);
1050
+ if (path.endsWith('.style') && ['title', 'subtitle', 'tertiary', 'body', 'time', 'price', 'change', 'columns', 'columnSecondary', 'value', 'valueSecondary', 'badge', 'description', 'status', 'primaryAmount', 'secondaryAmount', 'trend', 'message', 'actionText'].includes(field)) protocolObject(item, fieldPath);
1051
+ assertProtocolFields(item, fieldPath, field);
1052
+ });
1053
+ }
1054
+ function assertRowProtocol(row, path) {
1055
+ protocolObject(row, path);
1056
+ assertRowType(row.type, path);
1057
+ protocolKey(row.key, `${path}.key`);
1058
+ assertProtocolFields(row, path);
1059
+ for (const field of ['leading', 'visual', 'secondaryLeading']) {
1060
+ const visual = row[field];
1061
+ if (visual !== undefined || field === 'leading' && (row.type === 'identity' || row.type === 'market')) {
1062
+ const object = protocolObject(visual, `${path}.${field}`);
1063
+ if (object.kind === 'stackedImages' && !Array.isArray(object.images)) fail(`${path}.${field}.images`, 'must be an array');
1064
+ }
1065
+ }
1066
+ for (const field of ['title', 'subtitle', 'tertiary', 'body', 'time', 'price', 'indexTitle']) {
1067
+ const value = row[field];
1068
+ if (value !== undefined && typeof value !== 'string') fail(`${path}.${field}`, 'must be a string');
1069
+ }
1070
+ if (row.height !== undefined && row.height < 0) fail(`${path}.height`, 'must be non-negative');
1071
+ if (row.type === 'identity') {
1072
+ let end = 0;
1073
+ row.titleMatch?.forEach(match => {
1074
+ if (!Number.isInteger(match.start) || !Number.isInteger(match.end) || match.start < end || match.end <= match.start || match.end > row.title.length) fail(`${path}.titleMatch`, 'invalid text range');
1075
+ end = match.end;
1076
+ });
1077
+ }
1078
+ if (row.type === 'mediaTile' && row.media) {
1079
+ protocolObject(row.media.source, `${path}.media.source`);
1080
+ if (!Array.isArray(row.media.probeOrder)) fail(`${path}.media.probeOrder`, 'must be an array');
1081
+ }
1082
+ if (row.type === 'walletGroup') {
1083
+ protocolObject(row.parent, `${path}.parent`);
1084
+ if (!Array.isArray(row.children)) fail(`${path}.children`, 'must be an array');
1085
+ const members = [row.parent, ...row.children];
1086
+ const keys = new Set();
1087
+ if (row.parent.key !== row.key) fail(`${path}.parent.key`, 'must match its group');
1088
+ members.forEach((member, index) => {
1089
+ assertRowProtocol(member, `${path}.members[${index}]`);
1090
+ if (member.type !== 'identity' || keys.has(member.key)) fail(path, 'invalid wallet member identity');
1091
+ keys.add(member.key);
1092
+ });
1093
+ }
1094
+ if (row.type === 'dataRow' && !Array.isArray(row.columns)) fail(`${path}.columns`, 'must be an array');
1095
+ if (row.type === 'market') {
1096
+ protocolObject(row.change, `${path}.change`);
1097
+ if (row.webTable) {
1098
+ const {
1099
+ columns,
1100
+ cells
1101
+ } = row.webTable;
1102
+ if (!Array.isArray(columns) || !Array.isArray(cells) || columns.length !== cells.length) fail(`${path}.webTable`, 'columns and cells must match');
1103
+ const keys = new Set();
1104
+ columns.forEach((column, index) => {
1105
+ protocolKey(column.key, `${path}.webTable.columns[${index}].key`);
1106
+ if (keys.has(column.key) || cells[index]?.key !== column.key) fail(`${path}.webTable`, 'invalid column identity');
1107
+ keys.add(column.key);
1108
+ const cell = cells[index];
1109
+ if (!['favorite', 'asset', 'text', 'sparkline'].includes(cell.kind)) fail(`${path}.webTable.cells[${index}]`, 'unsupported cell kind');
1110
+ if (cell.kind === 'asset') protocolObject(cell.title, `${path}.webTable.cells[${index}].title`);
1111
+ if ((cell.kind === 'asset' || cell.kind === 'text') && cell.secondary !== undefined && !Array.isArray(cell.secondary)) fail(`${path}.webTable.cells[${index}].secondary`, 'must be an array');
1112
+ if (cell.kind === 'text' && !Array.isArray(cell.primary)) fail(`${path}.webTable.cells[${index}].primary`, 'must be an array');
1113
+ // The Web renderer spreads samples into Math.min/Math.max.
1114
+ if (cell.kind === 'sparkline' && (!Array.isArray(cell.points) || cell.points.length > 256)) fail(`${path}.webTable.cells[${index}].points`, 'must be an array of at most 256 samples');
1115
+ });
1116
+ }
1117
+ }
1118
+ }
1119
+ function assertSnapshotProtocol(snapshot) {
1120
+ protocolObject(snapshot, 'snapshot');
1121
+ if (snapshot.schemaVersion !== 1) fail('snapshot.schemaVersion', 'must be 1');
1122
+ if (!Number.isSafeInteger(snapshot.generation) || snapshot.generation < 0) fail('snapshot.generation', 'must be a non-negative safe integer');
1123
+ protocolObject(snapshot.layout, 'snapshot.layout');
1124
+ assertProtocolFields(snapshot.layout, 'snapshot.layout');
1125
+ if (snapshot.layout.orientation !== undefined && !['vertical', 'horizontal'].includes(snapshot.layout.orientation)) fail('snapshot.layout.orientation', 'is not supported');
1126
+ if (!['linear', 'sectioned', 'grid', 'table'].includes(snapshot.layout.kind)) fail('snapshot.layout.kind', 'is not supported');
1127
+ if (!Array.isArray(snapshot.rows)) fail('snapshot.rows', 'must be an array');
1128
+ if (snapshot.layout.kind === 'grid' && (!Number.isInteger(snapshot.layout.gridColumns) || (snapshot.layout.gridColumns ?? 0) < 1 || (snapshot.layout.gridColumns ?? 0) > 7)) fail('snapshot.layout.gridColumns', 'must be an integer from 1 to 7');
1129
+ const keys = new Set();
1130
+ for (const [index, row] of snapshot.rows.entries()) {
1131
+ assertRowProtocol(row, `rows[${index}]`);
1132
+ if (keys.has(row.key)) fail(`rows[${index}].key`, 'duplicate row identity');
1133
+ keys.add(row.key);
1134
+ }
1135
+ if (snapshot.emptyState) assertRowProtocol(snapshot.emptyState, 'emptyState');
1136
+ if (snapshot.fixedFooter) assertRowProtocol(snapshot.fixedFooter, 'fixedFooter');
1137
+ if (snapshot.selection) {
1138
+ if (!Array.isArray(snapshot.selection.selectedKeys)) fail('snapshot.selection.selectedKeys', 'must be an array');
1139
+ snapshot.selection.selectedKeys.forEach(key => {
1140
+ if (!keys.has(key)) fail('snapshot.selection.selectedKeys', 'unknown row identity');
1141
+ });
1142
+ }
1143
+ }
1144
+
1145
+ /** Empty optional image descriptors must take the same path as absent images. */
1146
+ function normalizeEmptyImages(value, field = '') {
1147
+ if (!value || typeof value !== 'object') return value;
1148
+ if (Array.isArray(value)) {
1149
+ const next = value.map(item => normalizeEmptyImages(item));
1150
+ const filtered = field === 'images' ? next.filter(item => item !== undefined) : next.map(item => item === undefined ? null : item);
1151
+ return filtered.length === value.length && filtered.every((item, index) => item === value[index]) ? value : filtered;
1152
+ }
1153
+ const object = value;
1154
+ if (typeof object.uri === 'string' && !object.uri.trim() && 'width' in object && 'height' in object) return undefined;
1155
+ let changed = false;
1156
+ const next = {
1157
+ ...object
1158
+ };
1159
+ Object.entries(object).forEach(([key, item]) => {
1160
+ const normalized = normalizeEmptyImages(item, key);
1161
+ if (normalized !== item) {
1162
+ // Omitted JSON patch fields must also be absent from the JS merge.
1163
+ if (field === 'changes' && normalized === undefined) delete next[key];else next[key] = normalized;
1164
+ changed = true;
1165
+ }
1166
+ });
1167
+ if (field === 'media' && next.source === undefined) return undefined;
1168
+ return changed ? next : value;
1169
+ }
1170
+ export function validateSnapshot(snapshot) {
1171
+ assertPlainSerializable(snapshot, 'snapshot', new Set());
1172
+ if (isDevelopment()) assertSnapshotContract(snapshot);
1173
+ const normalized = isDevelopment() ? snapshot : normalizeEmptyImages(snapshot);
1174
+ assertSnapshotProtocol(normalized);
1175
+ return normalizeSnapshotStyles(normalized);
982
1176
  }
983
1177
 
984
1178
  /**
@@ -1159,17 +1353,25 @@ function assertPatchChanges(patch, index) {
1159
1353
  }
1160
1354
  export function validatePatches(patches) {
1161
1355
  assertPlainSerializable(patches, 'patches', new Set());
1356
+ if (!Array.isArray(patches)) fail('patches', 'must be an array');
1162
1357
  const keys = new Set();
1163
- patches.forEach((patch, index) => {
1164
- assertKey(patch.key, `patches[${index}].key`);
1358
+ for (const [index, patch] of patches.entries()) {
1359
+ protocolObject(patch, `patches[${index}]`);
1360
+ protocolKey(patch.key, `patches[${index}].key`);
1165
1361
  if (keys.has(patch.key)) fail(`patches[${index}].key`, `duplicate key "${patch.key}"`);
1166
1362
  keys.add(patch.key);
1363
+ protocolObject(patch.changes, `patches[${index}].changes`);
1364
+ assertRowType(patch.type, `patches[${index}]`);
1365
+ assertProtocolFields(patch.changes, `patches[${index}].changes`);
1366
+ if (!isDevelopment()) continue;
1367
+ assertKey(patch.key, `patches[${index}].key`);
1167
1368
  if (Object.keys(patch.changes).length === 0) {
1168
1369
  fail(`patches[${index}].changes`, 'must contain at least one field');
1169
1370
  }
1170
1371
  assertPatchChanges(patch, index);
1171
- });
1172
- return normalizePatchStyles(patches);
1372
+ }
1373
+ const normalized = isDevelopment() ? patches : normalizeEmptyImages(patches);
1374
+ return normalizePatchStyles(normalized.filter(patch => Object.keys(patch.changes).length > 0));
1173
1375
  }
1174
1376
 
1175
1377
  /** Patches reach the native side without passing through a snapshot. */
@@ -1192,10 +1394,10 @@ function normalizePatchStyles(patches) {
1192
1394
  return changed ? next : patches;
1193
1395
  }
1194
1396
  export function applyRowPatches(snapshot, patches) {
1195
- validatePatches(patches);
1196
- const patchByKey = new Map(patches.map(patch => [patch.key, patch]));
1397
+ const normalizedPatches = validatePatches(patches);
1398
+ const patchByKey = new Map(normalizedPatches.map(patch => [patch.key, patch]));
1197
1399
  const knownKeys = new Set(snapshot.rows.map(row => row.key));
1198
- patches.forEach(patch => {
1400
+ normalizedPatches.forEach(patch => {
1199
1401
  if (!knownKeys.has(patch.key)) fail('patches', `unknown row key "${patch.key}"`);
1200
1402
  });
1201
1403
  const rows = snapshot.rows.map(row => {