@sparkelf/dsh-genui 0.0.0-stage → 0.11.4-patch.1

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 (210) hide show
  1. package/CHANGELOG.md +597 -0
  2. package/LICENSE +21 -0
  3. package/README.md +292 -2
  4. package/README.zh-CN.md +307 -0
  5. package/SKILL.md +261 -0
  6. package/cordis.patch.yml +9 -0
  7. package/demo-prompts.md +118 -0
  8. package/lib/assets/echarts-core.js +43 -0
  9. package/lib/assets/echarts-full.js +72 -0
  10. package/lib/assets/mermaid.js +3591 -0
  11. package/lib/assets/standalone-runtime.js +1506 -0
  12. package/lib/assets/three.js +3844 -0
  13. package/lib/client.js +405 -0
  14. package/lib/index.js +5187 -0
  15. package/lib/invariant.js +19 -0
  16. package/lib/types/client/EChartNode.d.ts +13 -0
  17. package/lib/types/client/ErrorBoundary.d.ts +30 -0
  18. package/lib/types/client/GenuiBlock.d.ts +9 -0
  19. package/lib/types/client/PlotBlock.d.ts +44 -0
  20. package/lib/types/client/TemplateDrawer.d.ts +7 -0
  21. package/lib/types/client/achievement-store.d.ts +35 -0
  22. package/lib/types/client/achievement-toast.d.ts +2 -0
  23. package/lib/types/client/achievements.d.ts +63 -0
  24. package/lib/types/client/action-context.d.ts +7 -0
  25. package/lib/types/client/artifact/ExportableGenuiBlock.d.ts +6 -0
  26. package/lib/types/client/artifact/create.d.ts +5 -0
  27. package/lib/types/client/artifact/download.d.ts +9 -0
  28. package/lib/types/client/artifact/html.d.ts +5 -0
  29. package/lib/types/client/artifact/index.d.ts +8 -0
  30. package/lib/types/client/artifact/json.d.ts +3 -0
  31. package/lib/types/client/artifact/parse.d.ts +3 -0
  32. package/lib/types/client/artifact/portability.d.ts +4 -0
  33. package/lib/types/client/artifact/standalone-theme.d.ts +2 -0
  34. package/lib/types/client/artifact/types.d.ts +33 -0
  35. package/lib/types/client/asset-echarts-core.d.ts +1 -0
  36. package/lib/types/client/asset-echarts.d.ts +17 -0
  37. package/lib/types/client/asset-loader.d.ts +33 -0
  38. package/lib/types/client/asset-mermaid.d.ts +1 -0
  39. package/lib/types/client/asset-three.d.ts +1 -0
  40. package/lib/types/client/blocks/advanced.d.ts +101 -0
  41. package/lib/types/client/blocks/basic.d.ts +22 -0
  42. package/lib/types/client/blocks/charts.d.ts +53 -0
  43. package/lib/types/client/blocks/checkbox.d.ts +17 -0
  44. package/lib/types/client/blocks/diagram/geometry.d.ts +73 -0
  45. package/lib/types/client/blocks/diagram/index.d.ts +5 -0
  46. package/lib/types/client/blocks/diagram/layout.d.ts +41 -0
  47. package/lib/types/client/blocks/diagram/theme.d.ts +37 -0
  48. package/lib/types/client/blocks/forms.d.ts +77 -0
  49. package/lib/types/client/blocks/image.d.ts +6 -0
  50. package/lib/types/client/blocks/render-node.d.ts +10 -0
  51. package/lib/types/client/blocks/state.d.ts +63 -0
  52. package/lib/types/client/blocks/svg.d.ts +4 -0
  53. package/lib/types/client/dom-fence.d.ts +30 -0
  54. package/lib/types/client/echarts-engine.d.ts +4 -0
  55. package/lib/types/client/echarts-lazy.d.ts +18 -0
  56. package/lib/types/client/embed.d.ts +10 -0
  57. package/lib/types/client/fence-render.d.ts +106 -0
  58. package/lib/types/client/gallery.d.ts +7 -0
  59. package/lib/types/client/genui-runtime/diagnostics.d.ts +18 -0
  60. package/lib/types/client/genui-runtime/index.d.ts +1 -0
  61. package/lib/types/client/genui-runtime/limits.d.ts +54 -0
  62. package/lib/types/client/genui-runtime/normalize.d.ts +15 -0
  63. package/lib/types/client/genui-runtime/schema.d.ts +87 -0
  64. package/lib/types/client/genui-runtime/value-utils.d.ts +18 -0
  65. package/lib/types/client/guard.d.ts +144 -0
  66. package/lib/types/client/i18n/en.d.ts +307 -0
  67. package/lib/types/client/i18n/index.d.ts +44 -0
  68. package/lib/types/client/i18n/runtime.d.ts +64 -0
  69. package/lib/types/client/i18n/zh.d.ts +8 -0
  70. package/lib/types/client/index.d.ts +36 -0
  71. package/lib/types/client/inline.d.ts +5 -0
  72. package/lib/types/client/interaction-store.d.ts +48 -0
  73. package/lib/types/client/mermaid-core.d.ts +8 -0
  74. package/lib/types/client/mermaid-lazy.d.ts +9 -0
  75. package/lib/types/client/mermaid-safe.d.ts +52 -0
  76. package/lib/types/client/panel-command.d.ts +34 -0
  77. package/lib/types/client/panel-store.d.ts +94 -0
  78. package/lib/types/client/panel.d.ts +18 -0
  79. package/lib/types/client/parse-partial.d.ts +63 -0
  80. package/lib/types/client/primitive-adapter.d.ts +4 -0
  81. package/lib/types/client/primitive-labels.d.ts +18 -0
  82. package/lib/types/client/safe-math.d.ts +43 -0
  83. package/lib/types/client/scene3d-core.d.ts +21 -0
  84. package/lib/types/client/scene3d-lazy.d.ts +8 -0
  85. package/lib/types/client/session-resolver.d.ts +8 -0
  86. package/lib/types/client/source-fence.d.ts +29 -0
  87. package/lib/types/client/spec.d.ts +709 -0
  88. package/lib/types/client/standalone/asset-loader.d.ts +2 -0
  89. package/lib/types/client/standalone/bootstrap-types.d.ts +9 -0
  90. package/lib/types/client/standalone/katex-style.d.ts +1 -0
  91. package/lib/types/client/standalone/primitive-adapter.d.ts +54 -0
  92. package/lib/types/client/standalone/runtime.d.ts +2 -0
  93. package/lib/types/client/submission-registry.d.ts +51 -0
  94. package/lib/types/client/svg-fence.d.ts +2 -0
  95. package/lib/types/client/table-details.d.ts +20 -0
  96. package/lib/types/client/templates.d.ts +41 -0
  97. package/lib/types/client/toolview.d.ts +7 -0
  98. package/lib/types/client/walk-spec.d.ts +3 -0
  99. package/lib/types/index.d.ts +1 -0
  100. package/lib/types/plugin/chart-contract.d.ts +9 -0
  101. package/lib/types/plugin/fence-feedback.d.ts +151 -0
  102. package/lib/types/plugin/genui-diagnostic.d.ts +13 -0
  103. package/lib/types/plugin/index.d.ts +35 -0
  104. package/lib/types/plugin/inline-content-diagnostic.d.ts +8 -0
  105. package/lib/types/plugin/invariant.d.ts +15 -0
  106. package/lib/types/plugin/tool.d.ts +27 -0
  107. package/lib/types/shared/fence-repair.d.ts +78 -0
  108. package/lib/types/shared/fence-resolve.d.ts +39 -0
  109. package/package.json +249 -4
  110. package/src/client/EChartNode.tsx +466 -0
  111. package/src/client/ErrorBoundary.tsx +67 -0
  112. package/src/client/GenuiBlock.module.css +2221 -0
  113. package/src/client/GenuiBlock.tsx +235 -0
  114. package/src/client/PlotBlock.module.css +171 -0
  115. package/src/client/PlotBlock.tsx +492 -0
  116. package/src/client/TemplateDrawer.module.css +152 -0
  117. package/src/client/TemplateDrawer.tsx +147 -0
  118. package/src/client/achievement-store.ts +151 -0
  119. package/src/client/achievement-toast.tsx +71 -0
  120. package/src/client/achievements.ts +160 -0
  121. package/src/client/action-context.ts +32 -0
  122. package/src/client/artifact/ArtifactExport.module.css +64 -0
  123. package/src/client/artifact/ExportableGenuiBlock.tsx +100 -0
  124. package/src/client/artifact/create.ts +69 -0
  125. package/src/client/artifact/download.ts +42 -0
  126. package/src/client/artifact/html.ts +157 -0
  127. package/src/client/artifact/index.ts +15 -0
  128. package/src/client/artifact/json.ts +6 -0
  129. package/src/client/artifact/parse.ts +32 -0
  130. package/src/client/artifact/portability.ts +47 -0
  131. package/src/client/artifact/standalone-theme.ts +94 -0
  132. package/src/client/artifact/types.ts +44 -0
  133. package/src/client/asset-echarts-core.ts +39 -0
  134. package/src/client/asset-echarts.ts +27 -0
  135. package/src/client/asset-loader.ts +96 -0
  136. package/src/client/asset-mermaid.ts +13 -0
  137. package/src/client/asset-three.ts +12 -0
  138. package/src/client/blocks/advanced.tsx +537 -0
  139. package/src/client/blocks/basic.tsx +121 -0
  140. package/src/client/blocks/charts.tsx +999 -0
  141. package/src/client/blocks/checkbox.tsx +61 -0
  142. package/src/client/blocks/diagram/geometry.ts +151 -0
  143. package/src/client/blocks/diagram/index.tsx +293 -0
  144. package/src/client/blocks/diagram/layout.ts +202 -0
  145. package/src/client/blocks/diagram/theme.ts +127 -0
  146. package/src/client/blocks/forms.tsx +531 -0
  147. package/src/client/blocks/image.tsx +28 -0
  148. package/src/client/blocks/render-node.tsx +494 -0
  149. package/src/client/blocks/state.ts +65 -0
  150. package/src/client/blocks/svg.tsx +66 -0
  151. package/src/client/dom-fence.tsx +1123 -0
  152. package/src/client/echarts-engine.ts +9 -0
  153. package/src/client/echarts-lazy.ts +41 -0
  154. package/src/client/embed.ts +19 -0
  155. package/src/client/fence-render.tsx +266 -0
  156. package/src/client/gallery.ts +215 -0
  157. package/src/client/genui-runtime/diagnostics.ts +165 -0
  158. package/src/client/genui-runtime/index.ts +1 -0
  159. package/src/client/genui-runtime/limits.ts +54 -0
  160. package/src/client/genui-runtime/normalize.ts +329 -0
  161. package/src/client/genui-runtime/schema.ts +352 -0
  162. package/src/client/genui-runtime/value-utils.ts +67 -0
  163. package/src/client/guard.ts +1965 -0
  164. package/src/client/i18n/en.ts +335 -0
  165. package/src/client/i18n/index.ts +125 -0
  166. package/src/client/i18n/runtime.ts +130 -0
  167. package/src/client/i18n/zh.ts +330 -0
  168. package/src/client/index.tsx +228 -0
  169. package/src/client/inline.ts +106 -0
  170. package/src/client/interaction-store.ts +127 -0
  171. package/src/client/mermaid-core.ts +158 -0
  172. package/src/client/mermaid-lazy.ts +31 -0
  173. package/src/client/mermaid-safe.ts +122 -0
  174. package/src/client/panel-command.ts +138 -0
  175. package/src/client/panel-store.ts +471 -0
  176. package/src/client/panel.tsx +287 -0
  177. package/src/client/parse-partial.ts +170 -0
  178. package/src/client/primitive-adapter.ts +13 -0
  179. package/src/client/primitive-labels.ts +55 -0
  180. package/src/client/safe-math.ts +298 -0
  181. package/src/client/scene3d-core.ts +195 -0
  182. package/src/client/scene3d-lazy.ts +26 -0
  183. package/src/client/session-resolver.ts +33 -0
  184. package/src/client/source-fence.ts +70 -0
  185. package/src/client/spec.ts +896 -0
  186. package/src/client/standalone/asset-loader.ts +9 -0
  187. package/src/client/standalone/bootstrap-types.ts +11 -0
  188. package/src/client/standalone/katex-style.ts +1 -0
  189. package/src/client/standalone/primitive-adapter.tsx +94 -0
  190. package/src/client/standalone/runtime.tsx +27 -0
  191. package/src/client/submission-registry.ts +150 -0
  192. package/src/client/svg-fence.tsx +39 -0
  193. package/src/client/table-details.ts +151 -0
  194. package/src/client/templates.ts +322 -0
  195. package/src/client/toolview.tsx +67 -0
  196. package/src/client/walk-spec.ts +43 -0
  197. package/src/css-modules.d.ts +5 -0
  198. package/src/index.ts +9 -0
  199. package/src/plugin/chart-contract.ts +13 -0
  200. package/src/plugin/fence-feedback.ts +655 -0
  201. package/src/plugin/genui-diagnostic.ts +112 -0
  202. package/src/plugin/index.ts +224 -0
  203. package/src/plugin/inline-content-diagnostic.ts +178 -0
  204. package/src/plugin/invariant.ts +30 -0
  205. package/src/plugin/node-shims.d.ts +31 -0
  206. package/src/plugin/tool.ts +424 -0
  207. package/src/shared/fence-repair.ts +536 -0
  208. package/src/shared/fence-resolve.ts +80 -0
  209. package/tsconfig.json +35 -0
  210. package/tsdown.config.ts +275 -0
@@ -0,0 +1,1965 @@
1
+ /**
2
+ * GenUI spec guard: resource limits, structural validation, and deterministic
3
+ * repair for ```dsh-ui fence specs.
4
+ *
5
+ * The renderer path runs every fence body through `repairGenuiSpec` before
6
+ * rendering, so a pathological or hostile spec — deep nesting, thousands of
7
+ * nodes, oversized strings, out-of-range numbers — degrades gracefully instead
8
+ * of stalling the UI. Repair is deterministic and prefix-stable: a component
9
+ * that survives repair of a partial stream keeps its position when later
10
+ * chunks arrive, so streaming re-renders stay consistent.
11
+ *
12
+ * Policy:
13
+ * - Unknown node `type`s pass through untouched (plugin-registered custom
14
+ * components via `registerGenuiComponent` are opaque to this package).
15
+ * - Known types: required fields must have the right type or the node is
16
+ * dropped; numbers are clamped into range; strings truncated; arrays
17
+ * sliced to their caps; containers recursed with a depth budget.
18
+ * - The whole spec carries a node budget; once exhausted, remaining siblings
19
+ * are elided.
20
+ */
21
+ import type { GenuiFileTreeNode, GenuiList, GenuiNode, GenuiPlot, GenuiPlotSeries, GenuiScene3D, GenuiSpec, GenuiDiagram, GenuiDiagramTheme, GenuiDiagramKind } from './spec.ts'
22
+ import { isComponentRoot, wrapSingleComponentRoot } from './spec.ts'
23
+ import {
24
+ BADGE_TONES, BUTTON_TONES, CALLOUT_TONES, CARD_TONES, CHART_KINDS, COMPONENT_SCHEMAS, HERO_TONES,
25
+ DIAGRAM_EDGE_KINDS, DIAGRAM_KINDS, DIAGRAM_NODE_TYPES, DIAGRAM_ROUTES, DIAGRAM_VARIANTS,
26
+ ECHART_PRESETS, FILE_TYPES, GENUI_NATIVE_TYPES, GENUI_SPEC_SCHEMA, INPUT_TYPES,
27
+ MEDIA_ASPECT_RATIOS, MESH_SHAPES, PLOT_KINDS, PROGRESS_VARIANTS, TABLE_CELL_TYPES, TEXT_SIZES,
28
+ } from './genui-runtime/schema.ts'
29
+ import type { ComponentFieldKind, ComponentRecordSchema, ComponentSchema } from './genui-runtime/schema.ts'
30
+ import { normalizeGenuiSpec } from './genui-runtime/normalize.ts'
31
+ import { diagnoseUnknownGenuiFields } from './genui-runtime/diagnostics.ts'
32
+ import type { GenuiDiagnostic } from './genui-runtime/diagnostics.ts'
33
+ import { GENUI_LIMITS } from './genui-runtime/limits.ts'
34
+ import { analyzeSubmissionRegistry } from './submission-registry.ts'
35
+ import { isTableDetailReachable, prepareTableRows, tableRowsForDetails } from './table-details.ts'
36
+ import { color, enu, int, num, obj, opt, safeHref, safeMediaSrc, str } from './genui-runtime/value-utils.ts'
37
+
38
+ /** Result of `validateGenuiSpec`. */
39
+ export interface GenuiValidation {
40
+ ok: boolean
41
+ /** Human-readable problems, empty when `ok`. */
42
+ errors: string[]
43
+ }
44
+
45
+ /* ---------------- schema field helpers ---------------- */
46
+
47
+ function fieldKindMatches(value: unknown, kind: ComponentFieldKind): boolean {
48
+ switch (kind) {
49
+ case 'string': return typeof value === 'string'
50
+ case 'string-or-null': return value === null || typeof value === 'string'
51
+ case 'number': return typeof value === 'number' && Number.isFinite(value)
52
+ case 'boolean': return typeof value === 'boolean'
53
+ case 'nodes': return Array.isArray(value)
54
+ case 'array': return Array.isArray(value)
55
+ case 'object': return obj(value) !== undefined
56
+ case 'unknown': return true
57
+ }
58
+ }
59
+
60
+ function fieldKindLabel(kind: ComponentFieldKind): string {
61
+ switch (kind) {
62
+ case 'string-or-null': return 'a string or null'
63
+ case 'number': return 'a finite number'
64
+ case 'boolean': return 'a boolean'
65
+ case 'nodes': case 'array': return 'an array'
66
+ case 'object': return 'an object'
67
+ case 'unknown': return 'a value'
68
+ default: return 'a string'
69
+ }
70
+ }
71
+
72
+ /** Detect an existing field diagnostic using both canonical and legacy messages. */
73
+ function hasFieldError(errors: readonly string[], at: string, field: string): boolean {
74
+ return errors.some(error =>
75
+ error.startsWith(`${at}.${field} `) || error.includes(`'${field}'`) || error.includes(`requires ${field}`))
76
+ }
77
+
78
+ /** Validate present fields against the runtime schema without duplicating errors. */
79
+ function validateSchemaFieldKinds(
80
+ value: Record<string, unknown>,
81
+ at: string,
82
+ definition: ComponentSchema,
83
+ errors: string[],
84
+ excludedFields: readonly string[] = [],
85
+ ): void {
86
+ for (const [field, kind] of Object.entries(definition.fields)) {
87
+ if (excludedFields.includes(field) || value[field] === undefined) continue
88
+ if (!fieldKindMatches(value[field], kind) && !hasFieldError(errors, at, field)) {
89
+ errors.push(`${at}.${field} must be ${fieldKindLabel(kind)}`)
90
+ }
91
+ }
92
+ for (const [field, values] of Object.entries(definition.enums)) {
93
+ if (excludedFields.includes(field) || value[field] === undefined || !fieldKindMatches(value[field], 'string')) continue
94
+ if (!values.includes(value[field] as string) && !hasFieldError(errors, at, field)) {
95
+ errors.push(`${at}.${field} must be one of ${values.join(', ')}`)
96
+ }
97
+ }
98
+ }
99
+
100
+ /** Validate one schema-declared nested record and all records below it. */
101
+ function validateRecordSchema(
102
+ value: unknown,
103
+ at: string,
104
+ definition: ComponentRecordSchema,
105
+ errors: string[],
106
+ ): void {
107
+ const holder = obj(value)
108
+ if (holder === undefined) {
109
+ errors.push(`${at} must be an object`)
110
+ return
111
+ }
112
+ for (const field of definition.required) {
113
+ const kind = definition.fields[field]
114
+ if (holder[field] === undefined) {
115
+ if (!hasFieldError(errors, at, field)) errors.push(`${at}: requires ${field}${kind === undefined ? '' : ` (${fieldKindLabel(kind)})`}`)
116
+ } else if (kind !== undefined && !fieldKindMatches(holder[field], kind)) {
117
+ if (!hasFieldError(errors, at, field)) errors.push(`${at}.${field} must be ${fieldKindLabel(kind)}`)
118
+ }
119
+ }
120
+ for (const [field, kind] of Object.entries(definition.fields)) {
121
+ if (holder[field] !== undefined && !fieldKindMatches(holder[field], kind)) {
122
+ if (!hasFieldError(errors, at, field)) errors.push(`${at}.${field} must be ${fieldKindLabel(kind)}`)
123
+ }
124
+ }
125
+ for (const [field, values] of Object.entries(definition.enums)) {
126
+ if (holder[field] !== undefined && typeof holder[field] === 'string' && !values.includes(holder[field])) {
127
+ if (!hasFieldError(errors, at, field)) errors.push(`${at}.${field} must be one of ${values.join(', ')}`)
128
+ }
129
+ }
130
+ for (const [field, nested] of Object.entries(definition.nested)) {
131
+ const nestedValue = holder[field]
132
+ if (nestedValue === undefined) continue
133
+ if (Array.isArray(nestedValue)) {
134
+ nestedValue.forEach((item, index) => validateRecordSchema(item, `${at}.${field}[${index}]`, nested, errors))
135
+ } else {
136
+ validateRecordSchema(nestedValue, `${at}.${field}`, nested, errors)
137
+ }
138
+ }
139
+ }
140
+
141
+ /** Validate registry-declared nested records before repair can discard them. */
142
+ function validateNestedRecordSchemas(
143
+ value: Record<string, unknown>,
144
+ at: string,
145
+ definition: ComponentSchema,
146
+ errors: string[],
147
+ ): void {
148
+ for (const [field, nested] of Object.entries(definition.nested)) {
149
+ const nestedValue = value[field]
150
+ if (nestedValue === undefined) continue
151
+ if (Array.isArray(nestedValue)) {
152
+ nestedValue.forEach((item, index) => validateRecordSchema(item, `${at}.${field}[${index}]`, nested, errors))
153
+ } else {
154
+ validateRecordSchema(nestedValue, `${at}.${field}`, nested, errors)
155
+ }
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Does this table state its columns implicitly, in a 2D `rows`/`data` body?
161
+ * Repair turns the leading row into the header (see `deriveTableColumns`), so
162
+ * validation must not report the missing `columns` that repair is about to
163
+ * supply — while still reporting it for bodies repair cannot read (a scalar
164
+ * `rows`, an empty array, a 1D list).
165
+ */
166
+ function hasDerivableTableColumns(value: Record<string, unknown>): boolean {
167
+ const rows = value.rows !== undefined ? value.rows : value.data
168
+ if (!Array.isArray(rows) || rows.length === 0) return false
169
+ return Array.isArray(rows[0])
170
+ }
171
+
172
+ /** Validate the registry-declared presence and primitive shape of a native node. */
173
+ function validateRegistryFields(
174
+ value: Record<string, unknown>,
175
+ at: string,
176
+ definition: ComponentSchema,
177
+ errors: string[],
178
+ ): void {
179
+ const type = String(value.type)
180
+ const alreadyReported = (field: string): boolean => hasFieldError(errors, at, field)
181
+ const derivableField = type === 'table' && hasDerivableTableColumns(value) ? 'columns' : null
182
+ for (const field of definition.required) {
183
+ const kind = definition.fields[field]
184
+ if (kind === undefined || value[field] === undefined) {
185
+ if (field !== derivableField && !alreadyReported(field)) errors.push(`${at}: type '${type}' requires ${field}${kind === undefined ? '' : ` (${fieldKindLabel(kind)})`}`)
186
+ continue
187
+ }
188
+ if (!fieldKindMatches(value[field], kind) && !alreadyReported(field)) errors.push(`${at}.${field} must be ${fieldKindLabel(kind)}`)
189
+ }
190
+ validateSchemaFieldKinds(value, at, definition, errors, ['type'])
191
+ for (const group of definition.oneOfRequired) {
192
+ if (!group.some(field => value[field] !== undefined)
193
+ && !errors.some(error => error.includes(`requires ${group.join(' or ')}`))) {
194
+ errors.push(`${at}: type '${type}' requires one of ${group.join(' or ')}`)
195
+ }
196
+ }
197
+ for (const rule of definition.conditionalRequired) {
198
+ if (value[rule.when.field] !== rule.when.equals) continue
199
+ for (const field of rule.required) {
200
+ if (value[field] === undefined && !alreadyReported(field)) {
201
+ errors.push(`${at}: type '${type}' requires ${field}${rule.message === undefined ? '' : ` (${rule.message})`}`)
202
+ }
203
+ }
204
+ }
205
+ validateNestedRecordSchemas(value, at, definition, errors)
206
+ }
207
+
208
+ /* ---------------- repair ---------------- */
209
+
210
+ interface RepairCtx {
211
+ /** Nodes left in the budget; 0 stops the walk. */
212
+ remaining: number
213
+ }
214
+
215
+ /** Walk `list` with the shared node budget; drops invalid entries. */
216
+ function repairItems(list: unknown, ctx: RepairCtx, depth: number): GenuiNode[] {
217
+ if (!Array.isArray(list)) return []
218
+ const out: GenuiNode[] = []
219
+ for (const item of list) {
220
+ if (ctx.remaining <= 0) break
221
+ ctx.remaining -= 1
222
+ const node = repairNode(item, ctx, depth)
223
+ if (node !== null) out.push(node)
224
+ }
225
+ return out
226
+ }
227
+
228
+ /** Optional explicit palette: up to 12 validated colour values. */
229
+ function paletteValues(v: unknown): string[] | undefined {
230
+ if (!Array.isArray(v)) return undefined
231
+ const out: string[] = []
232
+ for (const item of v.slice(0, 12)) {
233
+ const value = color(item)
234
+ if (value === undefined) continue
235
+ out.push(value)
236
+ }
237
+ return out.length > 0 ? out : undefined
238
+ }
239
+
240
+ /** Optional `stat.spark` series: finite numbers only, 2..60 points. */
241
+ function sparkValues(v: unknown): number[] | undefined {
242
+ if (!Array.isArray(v)) return undefined
243
+ const out: number[] = []
244
+ for (const item of v.slice(0, 60)) {
245
+ const n = typeof item === 'number' ? item : Number(item)
246
+ if (!Number.isFinite(n)) return undefined
247
+ out.push(n)
248
+ }
249
+ return out.length >= 2 ? out : undefined
250
+ }
251
+
252
+ /** Layout hints are component-agnostic: `span` survives repair on ANY node
253
+ * (the renderer applies it inside a grid). Kept out of the per-case switches
254
+ * so a new component type cannot forget it. */
255
+ function repairNode(value: unknown, ctx: RepairCtx, depth: number): GenuiNode | null {
256
+ const node = repairNodeFields(value, ctx, depth)
257
+ if (node === null) return null
258
+ const span = int(obj(value)?.span, 2, 12)
259
+ return span === undefined ? node : ({ ...node, span } as GenuiNode)
260
+ }
261
+
262
+ function repairNodeFields(value: unknown, ctx: RepairCtx, depth: number): GenuiNode | null {
263
+ if (depth > GENUI_LIMITS.maxDepth) return null
264
+ const v = obj(value)
265
+ if (v === undefined) return null
266
+ const type = v.type
267
+ if (typeof type !== 'string') return null
268
+ switch (type) {
269
+ case 'text': {
270
+ const content = str(v.content, GENUI_LIMITS.maxString) ?? str(v.text, GENUI_LIMITS.maxString)
271
+ if (content === undefined) return null
272
+ return { type: 'text', content, ...opt('size', enu(v.size, TEXT_SIZES)), ...opt('center', v.center === true ? true : undefined) }
273
+ }
274
+ case 'row': {
275
+ return { type: 'row', items: repairItems(v.items, ctx, depth + 1), ...opt('wrap', v.wrap === true ? true : undefined), ...opt('spacer', v.spacer === true ? true : undefined) }
276
+ }
277
+ case 'col': {
278
+ return { type: 'col', items: repairItems(v.items, ctx, depth + 1), ...opt('gap', num(v.gap, 0, 96)) }
279
+ }
280
+ case 'grid': {
281
+ return { type: 'grid', cols: int(v.cols, 1, GENUI_LIMITS.maxGridCols) ?? 1, items: repairItems(v.items, ctx, depth + 1) }
282
+ }
283
+ case 'card': {
284
+ return {
285
+ type: 'card',
286
+ items: repairItems(v.items, ctx, depth + 1),
287
+ ...opt('title', str(v.title, GENUI_LIMITS.maxString)),
288
+ ...opt('tone', enu(v.tone, CARD_TONES)),
289
+ ...opt('accent', color(v.accent)),
290
+ }
291
+ }
292
+ case 'button': {
293
+ const label = str(v.label, GENUI_LIMITS.maxString)
294
+ if (label === undefined) return null
295
+ return {
296
+ type: 'button', label,
297
+ ...opt('tone', enu(v.tone, BUTTON_TONES)),
298
+ ...opt('full', v.full === true ? true : undefined),
299
+ ...opt('small', v.small === true ? true : undefined),
300
+ ...opt('icon', str(v.icon, 64)),
301
+ ...opt('action', str(v.action, 200)),
302
+ }
303
+ }
304
+ case 'input': {
305
+ return {
306
+ type: 'input',
307
+ ...opt('label', str(v.label, GENUI_LIMITS.maxString)),
308
+ ...opt('placeholder', str(v.placeholder, GENUI_LIMITS.maxString)),
309
+ ...opt('value', str(v.value, GENUI_LIMITS.maxString)),
310
+ ...opt('inputType', enu(v.inputType, INPUT_TYPES)),
311
+ ...opt('action', str(v.action, 200)),
312
+ ...opt('id', str(v.id, 200)),
313
+ }
314
+ }
315
+ case 'select': {
316
+ const options = repairStrings(v.options, GENUI_LIMITS.maxOptions, GENUI_LIMITS.maxString)
317
+ if (options === undefined) return null
318
+ return {
319
+ type: 'select', options,
320
+ ...opt('label', str(v.label, GENUI_LIMITS.maxString)),
321
+ ...opt('action', str(v.action, 200)),
322
+ ...opt('selected', int(v.selected, 0, options.length - 1)),
323
+ ...opt('id', str(v.id, 200)),
324
+ }
325
+ }
326
+ case 'checkbox': {
327
+ const label = str(v.label, GENUI_LIMITS.maxString)
328
+ if (label === undefined) return null
329
+ return {
330
+ type: 'checkbox', label,
331
+ ...opt('checked', v.checked === true ? true : undefined),
332
+ ...opt('action', str(v.action, 200)),
333
+ ...opt('group', str(v.group, 200)),
334
+ }
335
+ }
336
+ case 'link': {
337
+ const label = str(v.label, GENUI_LIMITS.maxString)
338
+ if (label === undefined) return null
339
+ return { type: 'link', label, ...opt('href', safeHref(v.href)) }
340
+ }
341
+ case 'image': {
342
+ const src = safeMediaSrc(v.src)
343
+ if (src === undefined) return null
344
+ return {
345
+ type: 'image', src,
346
+ ...opt('alt', str(v.alt, GENUI_LIMITS.maxString)),
347
+ }
348
+ }
349
+ case 'audio': {
350
+ const src = safeMediaSrc(v.src)
351
+ if (src === undefined) return null
352
+ return {
353
+ type: 'audio', src,
354
+ ...opt('alt', str(v.alt, GENUI_LIMITS.maxString)),
355
+ ...opt('loop', v.loop === true ? true : undefined),
356
+ }
357
+ }
358
+ case 'video': {
359
+ const src = safeMediaSrc(v.src)
360
+ if (src === undefined) return null
361
+ return {
362
+ type: 'video', src,
363
+ ...opt('alt', str(v.alt, GENUI_LIMITS.maxString)),
364
+ ...opt('poster', safeMediaSrc(v.poster)),
365
+ ...opt('loop', v.loop === true ? true : undefined),
366
+ ...opt('muted', v.muted === true ? true : undefined),
367
+ ...opt('aspectRatio', enu(v.aspectRatio, MEDIA_ASPECT_RATIOS)),
368
+ }
369
+ }
370
+ case 'badge': {
371
+ const label = str(v.label, GENUI_LIMITS.maxString) ?? str(v.text, GENUI_LIMITS.maxString) ?? str(v.value, GENUI_LIMITS.maxString)
372
+ if (label === undefined) return null
373
+ return { type: 'badge', label, ...opt('tone', enu(v.tone, BADGE_TONES)), ...opt('icon', str(v.icon, 64)) }
374
+ }
375
+ case 'hero': {
376
+ const title = str(v.title, GENUI_LIMITS.maxString)
377
+ if (title === undefined) return null
378
+ return {
379
+ type: 'hero', title,
380
+ ...opt('subtitle', str(v.subtitle, GENUI_LIMITS.maxString)),
381
+ ...opt('value', str(v.value, 128)),
382
+ ...opt('label', str(v.label, GENUI_LIMITS.maxString)),
383
+ ...opt('delta', str(v.delta, 64)),
384
+ ...opt('spark', sparkValues(v.spark)),
385
+ ...opt('tone', enu(v.tone, HERO_TONES)),
386
+ }
387
+ }
388
+ case 'stat': {
389
+ const label = str(v.label, GENUI_LIMITS.maxString)
390
+ const value = str(v.value, 128)
391
+ if (label === undefined || value === undefined) return null
392
+ return {
393
+ type: 'stat', label, value,
394
+ ...opt('delta', str(v.delta, 64)),
395
+ ...opt('spark', sparkValues(v.spark)),
396
+ ...opt('size', v.size === 'hero' ? 'hero' as const : undefined),
397
+ }
398
+ }
399
+ case 'progress': {
400
+ const value = num(v.value, 0, 100)
401
+ if (value === undefined) return null
402
+ return {
403
+ type: 'progress', value,
404
+ ...opt('label', str(v.label, GENUI_LIMITS.maxString)),
405
+ ...opt('valueLabel', str(v.valueLabel, 64)),
406
+ ...opt('variant', enu(v.variant, PROGRESS_VARIANTS)),
407
+ ...opt('target', num(v.target, 0, 100)),
408
+ }
409
+ }
410
+ case 'divider': return { type: 'divider' }
411
+ case 'spacer': return { type: 'spacer' }
412
+ case 'avatar': {
413
+ const name = str(v.name, 64)
414
+ if (name === undefined) return null
415
+ return { type: 'avatar', name, ...opt('color', color(v.color)) }
416
+ }
417
+ case 'list': {
418
+ const items = repairListItems(v.items, GENUI_LIMITS.maxListItems, ctx, depth + 1)
419
+ if (items === undefined) return null
420
+ return { type: 'list', items, ...opt('filter', str(v.filter, 64)) }
421
+ }
422
+ case 'table': {
423
+ const prepared = prepareTableRows(v)
424
+ if (prepared === null) return null
425
+ const { columns, rows } = prepared
426
+ // Optional per-column cell types; unknown entries degrade to 'text'.
427
+ const rawTypes = Array.isArray(v.types) ? v.types : undefined
428
+ const types = rawTypes === undefined
429
+ ? undefined
430
+ : columns.map((_c, i) => {
431
+ const raw = rawTypes[i]
432
+ return typeof raw === 'string' && (TABLE_CELL_TYPES as readonly string[]).includes(raw)
433
+ ? raw as typeof TABLE_CELL_TYPES[number]
434
+ : 'text'
435
+ })
436
+ // Master-detail payload: positionally aligned with `rows`. Entries that
437
+ // repair to nothing stay null so the renderer never shows an empty
438
+ // expander; extra entries beyond the row count are dropped.
439
+ const rawDetails = Array.isArray(v.details) ? v.details : undefined
440
+ const details = rawDetails === undefined
441
+ ? undefined
442
+ : rows.map((_row, i) => {
443
+ if (!isTableDetailReachable({ columns, rows, types }, i)) return null
444
+ const entry = repairItems(rawDetails[i], ctx, depth + 1)
445
+ return entry.length === 0 ? null : entry
446
+ })
447
+ return {
448
+ type: 'table', columns, rows,
449
+ ...opt('types', types),
450
+ ...opt('total', v.total === true ? true : undefined),
451
+ ...opt('export', v.export === true ? true : undefined),
452
+ ...opt('filter', str(v.filter, 64)),
453
+ ...opt('filterColumn', int(v.filterColumn, 0, GENUI_LIMITS.maxTableCols - 1)),
454
+ ...opt('sortField', str(v.sortField, 64)),
455
+ ...opt('details', details !== undefined && details.some(d => d !== null) ? details : undefined),
456
+ }
457
+ }
458
+ case 'chart': {
459
+ const data = repairChartData(v.data, GENUI_LIMITS.maxChartPoints)
460
+ const series = Array.isArray(v.series) ? repairSeries(v.series, GENUI_LIMITS.maxPlotSeries, GENUI_LIMITS.maxChartPoints) : undefined
461
+ // `data` is required by the type but grouped bars may ship `series`
462
+ // alone; a series-only chart gets an empty data array (the renderer
463
+ // reads `series` in that case).
464
+ if (data === undefined && series === undefined) return null
465
+ return {
466
+ type: 'chart', data: data ?? [],
467
+ ...opt('kind', enu(v.kind, CHART_KINDS)),
468
+ ...opt('series', series),
469
+ ...opt('horizontal', v.horizontal === true ? true : undefined),
470
+ ...opt('stacked', v.stacked === true ? true : undefined),
471
+ ...opt('filter', str(v.filter, 64)),
472
+ ...opt('palette', paletteValues(v.palette)),
473
+ }
474
+ }
475
+ case 'tabs': {
476
+ const tabs = repairTabs(v.tabs, ctx, depth)
477
+ if (tabs === undefined) return null
478
+ return { type: 'tabs', tabs }
479
+ }
480
+ case 'plot': {
481
+ const series = repairPlotSeries(v.series, GENUI_LIMITS.maxPlotSeries)
482
+ if (series === undefined) return null
483
+ return {
484
+ type: 'plot', series,
485
+ ...opt('xMin', num(v.xMin, -1e6, 1e6)),
486
+ ...opt('xMax', num(v.xMax, -1e6, 1e6)),
487
+ ...opt('yMin', num(v.yMin, -1e9, 1e9)),
488
+ ...opt('yMax', num(v.yMax, -1e9, 1e9)),
489
+ ...opt('title', str(v.title, GENUI_LIMITS.maxString)),
490
+ }
491
+ }
492
+ case 'callout': {
493
+ const content = str(v.content, GENUI_LIMITS.maxString)
494
+ if (content === undefined) return null
495
+ return { type: 'callout', content, ...opt('tone', enu(v.tone, CALLOUT_TONES)), ...opt('title', str(v.title, GENUI_LIMITS.maxString)) }
496
+ }
497
+ case 'steps': {
498
+ const steps = repairSteps(v.steps)
499
+ if (steps === undefined) return null
500
+ return { type: 'steps', steps, ...opt('current', int(v.current, 0, steps.length)) }
501
+ }
502
+ case 'keyvalue': {
503
+ const pairs = repairPairs(v.pairs, GENUI_LIMITS.maxKeyValuePairs)
504
+ if (pairs === undefined) return null
505
+ return { type: 'keyvalue', pairs }
506
+ }
507
+ case 'diff': {
508
+ const diffs = repairDiffs(v.diffs)
509
+ if (diffs === undefined) return null
510
+ return { type: 'diff', diffs }
511
+ }
512
+ case 'json': {
513
+ // Any JSON value is acceptable; only the node itself is validated.
514
+ if (!('value' in v)) return null
515
+ return { type: 'json', value: v.value }
516
+ }
517
+ case 'code': {
518
+ const code = str(v.code, GENUI_LIMITS.maxCode)
519
+ if (code === undefined) return null
520
+ return { type: 'code', code, ...opt('lang', str(v.lang, 64)) }
521
+ }
522
+ case 'radio': {
523
+ const options = repairStrings(v.options, GENUI_LIMITS.maxOptions, GENUI_LIMITS.maxString)
524
+ if (options === undefined) return null
525
+ return {
526
+ type: 'radio', options,
527
+ ...opt('label', str(v.label, GENUI_LIMITS.maxString)),
528
+ ...opt('selected', int(v.selected, 0, options.length - 1)),
529
+ ...opt('action', str(v.action, 200)),
530
+ ...opt('group', str(v.group, 200)),
531
+ // answer: option index (number) or label (string); out-of-range
532
+ // indices are DROPPED (clamping would silently grade against the
533
+ // wrong option)
534
+ ...opt('answer', typeof v.answer === 'number' && Number.isFinite(v.answer)
535
+ && v.answer >= 0 && v.answer < options.length
536
+ ? Math.trunc(v.answer)
537
+ : typeof v.answer === 'string' ? v.answer.slice(0, 512) : undefined),
538
+ ...opt('explanation', str(v.explanation, GENUI_LIMITS.maxString)),
539
+ }
540
+ }
541
+ case 'submit': {
542
+ const label = str(v.label, GENUI_LIMITS.maxString)
543
+ // 本地判卷可以不设置 action;不满足判卷条件时,渲染器会禁用无 action 的按钮。
544
+ const action = str(v.action, 200)
545
+ if (label === undefined) return null
546
+ return {
547
+ type: 'submit', label,
548
+ ...opt('action', action),
549
+ ...opt('resetAction', str(v.resetAction, 200)),
550
+ ...opt('groups', repairStrings(v.groups, GENUI_LIMITS.maxOptions, 200)),
551
+ }
552
+ }
553
+ case 'switch': {
554
+ const label = str(v.label, GENUI_LIMITS.maxString)
555
+ if (label === undefined) return null
556
+ return { type: 'switch', label, ...opt('checked', v.checked === true ? true : undefined), ...opt('action', str(v.action, 200)) }
557
+ }
558
+ case 'slider': {
559
+ const min = num(v.min, -1e9, 1e9) ?? 0
560
+ const max = num(v.max, -1e9, 1e9) ?? 100
561
+ const lo = Math.min(min, max)
562
+ const hi = Math.max(min, max)
563
+ const step = num(v.step, 1e-9, Math.max(hi - lo, 1e-9))
564
+ const value = num(v.value, lo, hi) ?? lo
565
+ return {
566
+ type: 'slider',
567
+ min: lo,
568
+ max: hi,
569
+ ...opt('step', step),
570
+ value,
571
+ ...opt('label', str(v.label, GENUI_LIMITS.maxString)),
572
+ ...opt('action', str(v.action, 200)),
573
+ ...opt('id', str(v.id, 200)),
574
+ }
575
+ }
576
+ case 'textarea': {
577
+ return {
578
+ type: 'textarea',
579
+ ...opt('label', str(v.label, GENUI_LIMITS.maxString)),
580
+ ...opt('placeholder', str(v.placeholder, GENUI_LIMITS.maxString)),
581
+ ...opt('rows', int(v.rows, 1, 30)),
582
+ ...opt('value', str(v.value, GENUI_LIMITS.maxString)),
583
+ ...opt('action', str(v.action, 200)),
584
+ ...opt('id', str(v.id, 200)),
585
+ }
586
+ }
587
+ case 'accordion': {
588
+ const items = repairAccordion(v.items, ctx, depth)
589
+ if (items === undefined) return null
590
+ return { type: 'accordion', items }
591
+ }
592
+ case 'copy': {
593
+ const text = str(v.text, GENUI_LIMITS.maxCode)
594
+ if (text === undefined) return null
595
+ return { type: 'copy', text, ...opt('label', str(v.label, 128)) }
596
+ }
597
+ case 'svg': {
598
+ const code = str(v.code, GENUI_LIMITS.maxCode)
599
+ if (code === undefined) return null
600
+ return { type: 'svg', code, ...opt('title', str(v.title, GENUI_LIMITS.maxString)), ...opt('height', int(v.height, 100, 800)) }
601
+ }
602
+ case 'mermaid': {
603
+ const code = str(v.code, GENUI_LIMITS.maxMermaid)
604
+ if (code === undefined) return null
605
+ return { type: 'mermaid', code }
606
+ }
607
+ case 'scene3d': {
608
+ const meshes = repairMeshes(v.meshes)
609
+ if (meshes === undefined) return null
610
+ return { type: 'scene3d', meshes, ...opt('title', str(v.title, GENUI_LIMITS.maxString)), ...opt('ambient', num(v.ambient, 0, 2)), ...opt('background', color(v.background)) }
611
+ }
612
+ case 'diagram': {
613
+ const repaired = repairDiagram(v)
614
+ return repaired
615
+ }
616
+ case 'timeline': {
617
+ const items = repairTimeline(v.items, GENUI_LIMITS.maxTimelineItems)
618
+ if (items === undefined) return null
619
+ return { type: 'timeline', items }
620
+ }
621
+ case 'file-tree': {
622
+ const items = repairTree(v.items, GENUI_LIMITS.maxListItems)
623
+ if (items === undefined) return null
624
+ return { type: 'file-tree', items }
625
+ }
626
+ case 'breadcrumb': {
627
+ const items = repairStrings(v.items, GENUI_LIMITS.maxBreadcrumbItems, GENUI_LIMITS.maxString)
628
+ if (items === undefined) return null
629
+ return { type: 'breadcrumb', items }
630
+ }
631
+ case 'quiz': {
632
+ const question = str(v.question, GENUI_LIMITS.maxString)
633
+ const options = repairQuizOptions(v.options, v.answer)
634
+ if (question === undefined || options === undefined) return null
635
+ return {
636
+ type: 'quiz', question, options,
637
+ ...opt('explanation', str(v.explanation, GENUI_LIMITS.maxString)),
638
+ ...opt('id', str(v.id, 200)),
639
+ ...opt('action', str(v.action, 200)),
640
+ }
641
+ }
642
+ case 'echart': {
643
+ // Preset shorthand data/series reuse the chart repair helpers.
644
+ const data = v.data !== undefined ? repairChartData(v.data, GENUI_LIMITS.maxChartPoints) : undefined
645
+ const series = v.series !== undefined && Array.isArray(v.series)
646
+ ? repairSeries(v.series, GENUI_LIMITS.maxPlotSeries, GENUI_LIMITS.maxChartPoints)
647
+ : undefined
648
+ // sankey / graph edges: `from`/`to` must be strings, `value` a number.
649
+ const links = Array.isArray(v.links)
650
+ ? v.links.slice(0, GENUI_LIMITS.maxChartPoints).flatMap(entry => {
651
+ const e = obj(entry)
652
+ const from = e === undefined ? undefined : str(e.from, 64)
653
+ const to = e === undefined ? undefined : str(e.to, 64)
654
+ if (from === undefined || to === undefined) return []
655
+ return [{ from, to, ...opt('value', num(e!.value, 0, 1e9)) }]
656
+ })
657
+ : undefined
658
+ // Full option: depth-bounded pass-through (the model writes the ECharts
659
+ // option object; the guard walks it to cap nesting but does not
660
+ // validate ECharts semantics — that is echarts' own job).
661
+ const sanitized = v.option !== undefined
662
+ ? sanitizeEChartOption(v.option, 0, { count: GENUI_LIMITS.maxEChartOptionNodes })
663
+ : undefined
664
+ // A chart option root is always a plain object; a scalar root is
665
+ // invalid, so degrade to preset/data/series handling (option dropped).
666
+ const option: Record<string, unknown> | undefined =
667
+ sanitized === undefined || typeof sanitized !== 'object' || sanitized === null || Array.isArray(sanitized)
668
+ ? undefined
669
+ : sanitized as Record<string, unknown>
670
+ // At least one of preset+data, links or option must be present.
671
+ if (option === undefined && data === undefined && series === undefined
672
+ && (links === undefined || links.length === 0)) return null
673
+ return {
674
+ type: 'echart',
675
+ ...opt('title', str(v.title, GENUI_LIMITS.maxString)),
676
+ ...opt('height', int(v.height, 100, 800)),
677
+ ...opt('preset', enu(v.preset, ECHART_PRESETS)),
678
+ ...opt('data', data),
679
+ ...opt('series', series),
680
+ ...opt('links', links !== undefined && links.length > 0 ? links : undefined),
681
+ ...opt('palette', paletteValues(v.palette)),
682
+ ...opt('option', option),
683
+ }
684
+ }
685
+ default:
686
+ // Plugin-registered custom node types are opaque to the guard: pass
687
+ // through unchanged (the renderer's default branch resolves them).
688
+ return value as GenuiNode
689
+ }
690
+ }
691
+
692
+ /* ---------------- per-type sub-repairers ---------------- */
693
+
694
+ function repairStrings(v: unknown, cap: number, strCap: number): string[] | undefined {
695
+ if (!Array.isArray(v)) return undefined
696
+ const out: string[] = []
697
+ for (const item of v) {
698
+ if (out.length >= cap) break
699
+ if (typeof item === 'string') {
700
+ out.push(item.slice(0, strCap))
701
+ } else if (item !== null && typeof item === 'object') {
702
+ // 兼容模型误用对象数组(如把 ask_user_question 的 {label,description}
703
+ // 格式错用到 select/radio 的 options)——提取可读字段,而不是静默丢
704
+ // 掉整个选项,让用户看到「选项没列举出来」的空列表。
705
+ const o = item as Record<string, unknown>
706
+ const s = typeof o.label === 'string' ? o.label
707
+ : typeof o.value === 'string' ? o.value
708
+ : typeof o.title === 'string' ? o.title
709
+ : JSON.stringify(item)
710
+ out.push(s.slice(0, strCap))
711
+ }
712
+ }
713
+ return out
714
+ }
715
+
716
+ function repairListItems(
717
+ v: unknown,
718
+ cap: number,
719
+ ctx: RepairCtx,
720
+ depth: number,
721
+ ): GenuiList['items'] | undefined {
722
+ if (!Array.isArray(v)) return undefined
723
+ const out: GenuiList['items'] = []
724
+ for (const item of v) {
725
+ if (out.length >= cap) break
726
+ if (typeof item === 'string') {
727
+ out.push(item.slice(0, GENUI_LIMITS.maxString))
728
+ continue
729
+ }
730
+ const o = obj(item)
731
+ if (o !== undefined && typeof o.type === 'string') {
732
+ // Typed children are GenuiNodes: charge them against the shared node
733
+ // budget (module header promise — exhausted budget elides remaining
734
+ // siblings). Strings and {title,desc} objects are list-item shapes,
735
+ // not nodes, so they never consume budget.
736
+ if (ctx.remaining <= 0) break
737
+ ctx.remaining -= 1
738
+ const node = repairNode(o, ctx, depth)
739
+ if (node !== null) out.push(node)
740
+ continue
741
+ }
742
+ const title = o === undefined ? undefined : str(o.title, GENUI_LIMITS.maxString)
743
+ if (title !== undefined) {
744
+ out.push({ title, ...opt('desc', str(o?.desc, GENUI_LIMITS.maxString)) })
745
+ }
746
+ }
747
+ return out
748
+ }
749
+
750
+ function repairChartData(v: unknown, cap: number): Array<{ label: string; value: number; color?: string }> | undefined {
751
+ if (!Array.isArray(v)) return undefined
752
+ const out: Array<{ label: string; value: number; color?: string }> = []
753
+ for (const datum of v) {
754
+ if (out.length >= cap) break
755
+ const o = obj(datum)
756
+ const label = o === undefined ? undefined : str(o.label, 128)
757
+ const value = o === undefined ? undefined : num(o.value, -1e12, 1e12)
758
+ if (label === undefined || value === undefined) continue
759
+ out.push({ label, value, ...opt('color', o === undefined ? undefined : color(o.color)) })
760
+ }
761
+ return out
762
+ }
763
+
764
+ function repairSeries(v: unknown, cap: number, pointCap: number): Array<{ label: string; color?: string; data: Array<{ label: string; value: number; color?: string }> }> | undefined {
765
+ if (!Array.isArray(v)) return undefined
766
+ const out: Array<{ label: string; color?: string; data: Array<{ label: string; value: number; color?: string }> }> = []
767
+ for (const s of v) {
768
+ if (out.length >= cap) break
769
+ const o = obj(s)
770
+ const label = o === undefined ? undefined : str(o.label, 128)
771
+ const data = o === undefined ? undefined : repairChartData(o.data, pointCap)
772
+ if (label === undefined || data === undefined) continue
773
+ out.push({ label, data, ...opt('color', o === undefined ? undefined : color(o.color)) })
774
+ }
775
+ return out
776
+ }
777
+
778
+ function repairTabs(v: unknown, ctx: RepairCtx, depth: number): Array<{ label: string; items: GenuiNode[] }> | undefined {
779
+ if (!Array.isArray(v)) return undefined
780
+ const out: Array<{ label: string; items: GenuiNode[] }> = []
781
+ for (const tab of v) {
782
+ if (out.length >= GENUI_LIMITS.maxTabs) break
783
+ const o = obj(tab)
784
+ const label = o === undefined ? undefined : str(o.label, 128)
785
+ if (label === undefined || o === undefined) continue
786
+ // `content` is accepted as an `items` alias (single component or array) —
787
+ // models routinely emit tabs[].content and losing it empties every tab.
788
+ const rawItems = o.items !== undefined ? o.items
789
+ : o.content !== undefined ? (Array.isArray(o.content) ? o.content : [o.content])
790
+ : undefined
791
+ out.push({ label, items: repairItems(rawItems, ctx, depth + 1) })
792
+ }
793
+ return out
794
+ }
795
+
796
+ function repairPlotSeries(v: unknown, cap: number): GenuiPlot['series'] | undefined {
797
+ if (!Array.isArray(v)) return undefined
798
+ const out: GenuiPlot['series'] = []
799
+ for (const s of v) {
800
+ if (out.length >= cap) break
801
+ const o = obj(s)
802
+ const expr = o === undefined ? undefined : str(o.expr, 512)
803
+ if (expr === undefined || o === undefined) continue
804
+ const params: NonNullable<GenuiPlotSeries['params']> = []
805
+ if (Array.isArray(o.params)) {
806
+ for (const p of o.params) {
807
+ if (params.length >= GENUI_LIMITS.maxPlotParams) break
808
+ const po = obj(p)
809
+ const name = po === undefined ? undefined : str(po.name, 64)
810
+ const value = po === undefined ? undefined : num(po.value, -1e9, 1e9)
811
+ if (name === undefined || value === undefined) continue
812
+ params.push({
813
+ name, value,
814
+ ...opt('min', po === undefined ? undefined : num(po.min, -1e9, 1e9)),
815
+ ...opt('max', po === undefined ? undefined : num(po.max, -1e9, 1e9)),
816
+ ...opt('step', po === undefined ? undefined : num(po.step, 1e-9, 1e9)),
817
+ ...opt('animateTo', po === undefined ? undefined : num(po.animateTo, -1e9, 1e9)),
818
+ ...opt('durationMs', po === undefined ? undefined : num(po.durationMs, 1, 120_000)),
819
+ ...opt('loop', po === undefined ? undefined : po.loop === true ? true : undefined),
820
+ })
821
+ }
822
+ }
823
+ out.push({ expr, ...opt('label', str(o.label, 128)), ...opt('color', color(o.color)), ...opt('kind', enu(o.kind, PLOT_KINDS)), ...opt('params', params.length > 0 ? params : undefined) })
824
+ }
825
+ return out
826
+ }
827
+
828
+ function repairSteps(v: unknown): Array<{ title: string; desc?: string }> | undefined {
829
+ if (!Array.isArray(v)) return undefined
830
+ const out: Array<{ title: string; desc?: string }> = []
831
+ for (const s of v) {
832
+ if (out.length >= GENUI_LIMITS.maxSteps) break
833
+ const o = obj(s)
834
+ const title = o === undefined ? undefined : str(o.title, 256)
835
+ if (title === undefined) continue
836
+ out.push({ title, ...opt('desc', o === undefined ? undefined : str(o.desc, GENUI_LIMITS.maxString)) })
837
+ }
838
+ return out
839
+ }
840
+
841
+ function repairPairs(v: unknown, cap: number): Array<{ key: string; value: string }> | undefined {
842
+ if (!Array.isArray(v)) return undefined
843
+ const out: Array<{ key: string; value: string }> = []
844
+ for (const p of v) {
845
+ if (out.length >= cap) break
846
+ const o = obj(p)
847
+ const key = o === undefined ? undefined : str(o.key, 256)
848
+ const value = o === undefined ? undefined : str(o.value, GENUI_LIMITS.maxString)
849
+ if (key === undefined || value === undefined) continue
850
+ out.push({ key, value })
851
+ }
852
+ return out
853
+ }
854
+
855
+ function repairDiffs(v: unknown): Array<{ path: string; oldText: string | null; newText: string }> | undefined {
856
+ if (!Array.isArray(v)) return undefined
857
+ const out: Array<{ path: string; oldText: string | null; newText: string }> = []
858
+ for (const d of v) {
859
+ if (out.length >= 24) break
860
+ const o = obj(d)
861
+ const path = o === undefined ? undefined : str(o.path, 1024)
862
+ const newText = o === undefined ? undefined : str(o.newText, 20_000)
863
+ if (path === undefined || newText === undefined) continue
864
+ const old = o === undefined ? undefined : o.oldText
865
+ out.push({ path, newText, oldText: old === null || typeof old !== 'string' ? null : old.slice(0, 20_000) })
866
+ }
867
+ return out
868
+ }
869
+
870
+ function repairAccordion(v: unknown, ctx: RepairCtx, depth: number): Array<{ title: string; items: GenuiNode[] }> | undefined {
871
+ if (!Array.isArray(v)) return undefined
872
+ const out: Array<{ title: string; items: GenuiNode[] }> = []
873
+ for (const item of v) {
874
+ if (out.length >= GENUI_LIMITS.maxAccordionItems) break
875
+ const o = obj(item)
876
+ const title = o === undefined ? undefined : str(o.title, 256)
877
+ if (title === undefined || o === undefined) continue
878
+ out.push({ title, items: repairItems(o.items, ctx, depth + 1) })
879
+ }
880
+ return out
881
+ }
882
+
883
+ function repairMeshes(v: unknown): GenuiScene3D['meshes'] | undefined {
884
+ if (!Array.isArray(v)) return undefined
885
+ const out: GenuiScene3D['meshes'] = []
886
+ for (const m of v) {
887
+ if (out.length >= GENUI_LIMITS.maxMeshes) break
888
+ const o = obj(m)
889
+ const shape = o === undefined ? undefined : enu(o.shape, MESH_SHAPES)
890
+ if (shape === undefined) continue
891
+ const scale = o === undefined ? undefined : num(o.scale, -1e6, 1e6) ?? tuple3(o.scale)
892
+ const size = o === undefined ? undefined : num(o.size, -1e6, 1e6) ?? tuple3(o.size)
893
+ out.push({
894
+ shape,
895
+ ...opt('color', o === undefined ? undefined : color(o.color)),
896
+ ...opt('position', o === undefined ? undefined : tuple3(o.position)),
897
+ ...opt('rotation', o === undefined ? undefined : tuple3(o.rotation)),
898
+ ...opt('scale', scale),
899
+ ...opt('size', size),
900
+ })
901
+ }
902
+ return out
903
+ }
904
+
905
+ function tuple3(v: unknown): [number, number, number] | undefined {
906
+ if (!Array.isArray(v) || v.length !== 3) return undefined
907
+ const [a, b, c] = v
908
+ if (typeof a !== 'number' || !Number.isFinite(a) || typeof b !== 'number' || !Number.isFinite(b)
909
+ || typeof c !== 'number' || !Number.isFinite(c)) return undefined
910
+ return [Math.min(1e6, Math.max(-1e6, a)), Math.min(1e6, Math.max(-1e6, b)), Math.min(1e6, Math.max(-1e6, c))]
911
+ }
912
+
913
+ /* ---------------- diagram (editorial) sub-repairers ---------------- */
914
+
915
+ /** Clamp a coordinate/size to the 4px editorial grid. */
916
+ function grid4(v: number, min: number, max: number): number {
917
+ return Math.min(max, Math.max(min, Math.round(v / 4) * 4))
918
+ }
919
+
920
+ function repairDiagramNodes(v: unknown): GenuiDiagram['nodes'] | undefined {
921
+ if (!Array.isArray(v)) return undefined
922
+ const out: GenuiDiagram['nodes'] = []
923
+ const seen = new Set<string>()
924
+ for (const raw of v) {
925
+ if (out.length >= GENUI_LIMITS.maxDiagramNodes) break
926
+ const o = obj(raw)
927
+ if (o === undefined) continue
928
+ const id = str(o.id, 128)
929
+ const label = str(o.label, GENUI_LIMITS.maxString)
930
+ if (id === undefined || label === undefined) continue
931
+ if (seen.has(id)) continue
932
+ seen.add(id)
933
+ const nodeType = enu(o.type, DIAGRAM_NODE_TYPES)
934
+ // Coordinate fields are clamped to a sane canvas and rounded to 4px.
935
+ const x = o.x === undefined ? undefined : grid4(num(o.x, -1e6, 1e6) ?? 0, 0, 1e6)
936
+ const y = o.y === undefined ? undefined : grid4(num(o.y, -1e6, 1e6) ?? 0, 0, 1e6)
937
+ const w = o.w === undefined ? undefined : grid4(num(o.w, -1e6, 1e6) ?? 96, 40, 2000)
938
+ const h = o.h === undefined ? undefined : grid4(num(o.h, -1e6, 1e6) ?? 48, 24, 1200)
939
+ out.push({
940
+ id, label,
941
+ ...opt('sub', str(o.sub, 256)),
942
+ ...opt('type', nodeType),
943
+ ...opt('x', x),
944
+ ...opt('y', y),
945
+ ...opt('w', w),
946
+ ...opt('h', h),
947
+ ...opt('tag', str(o.tag, 32)),
948
+ })
949
+ }
950
+ return out
951
+ }
952
+
953
+ function repairDiagramEdges(v: unknown): GenuiDiagram['edges'] | undefined {
954
+ if (v === undefined) return []
955
+ if (!Array.isArray(v)) return undefined
956
+ const out: GenuiDiagram['edges'] = []
957
+ for (const raw of v) {
958
+ if (out.length >= GENUI_LIMITS.maxDiagramEdges) break
959
+ const o = obj(raw)
960
+ if (o === undefined) continue
961
+ const from = str(o.from, 128)
962
+ const to = str(o.to, 128)
963
+ if (from === undefined || to === undefined) continue
964
+ out.push({
965
+ from, to,
966
+ ...opt('label', str(o.label, GENUI_LIMITS.maxDiagramLabel)),
967
+ ...opt('kind', enu(o.kind, DIAGRAM_EDGE_KINDS)),
968
+ ...opt('route', enu(o.route, DIAGRAM_ROUTES)),
969
+ })
970
+ }
971
+ return out
972
+ }
973
+
974
+ function repairDiagramTheme(v: unknown): GenuiDiagramTheme | undefined {
975
+ const o = obj(v)
976
+ if (o === undefined) return undefined
977
+ const out: GenuiDiagramTheme = {}
978
+ for (const key of ['paper', 'paper-2', 'ink', 'muted', 'soft', 'rule', 'accent', 'accent-tint', 'link'] as const) {
979
+ const c = color(o[key])
980
+ if (c !== undefined) out[key] = c
981
+ }
982
+ return Object.keys(out).length === 0 ? undefined : out
983
+ }
984
+
985
+ function repairDiagramZones(v: unknown): GenuiDiagram['zones'] | undefined {
986
+ if (v === undefined) return []
987
+ if (!Array.isArray(v)) return undefined
988
+ const out: GenuiDiagram['zones'] = []
989
+ for (const raw of v) {
990
+ if (out.length >= GENUI_LIMITS.maxDiagramZones) break
991
+ const o = obj(raw)
992
+ if (o === undefined) continue
993
+ const label = str(o.label, 64)
994
+ if (label === undefined) continue
995
+ out.push({
996
+ label,
997
+ ...opt('x', o.x === undefined ? undefined : grid4(num(o.x, -1e6, 1e6) ?? 0, 0, 1e6)),
998
+ ...opt('y', o.y === undefined ? undefined : grid4(num(o.y, -1e6, 1e6) ?? 0, 0, 1e6)),
999
+ ...opt('w', o.w === undefined ? undefined : grid4(num(o.w, -1e6, 1e6) ?? 100, 40, 2000)),
1000
+ ...opt('h', o.h === undefined ? undefined : grid4(num(o.h, -1e6, 1e6) ?? 100, 40, 1200)),
1001
+ })
1002
+ }
1003
+ return out
1004
+ }
1005
+
1006
+ function repairDiagram(v: unknown): GenuiDiagram | null {
1007
+ const o = obj(v)
1008
+ if (o === undefined) return null
1009
+ const kind = enu(o.kind, DIAGRAM_KINDS as unknown as readonly GenuiDiagramKind[])
1010
+ if (kind === undefined) return null
1011
+ const nodes = repairDiagramNodes(o.nodes)
1012
+ if (nodes === undefined) return null
1013
+ const edges = repairDiagramEdges(o.edges)
1014
+ if (edges === undefined) return null
1015
+ const zones = repairDiagramZones(o.zones)
1016
+ if (zones === undefined) return null
1017
+ return {
1018
+ // `zones` is optional: emitting `zones: []` made every diagram node differ
1019
+ // from its input for no reason (and broke the "gallery survives the guard
1020
+ // unchanged" contract).
1021
+ type: 'diagram', kind, nodes, edges,
1022
+ ...opt('zones', zones.length > 0 ? zones : undefined),
1023
+ ...opt('variant', enu(o.variant, DIAGRAM_VARIANTS)),
1024
+ ...opt('title', str(o.title, 256)),
1025
+ ...opt('theme', repairDiagramTheme(o.theme)),
1026
+ }
1027
+ }
1028
+
1029
+ function repairTimeline(v: unknown, cap: number): Array<{ title: string; desc?: string; time?: string }> | undefined {
1030
+ if (!Array.isArray(v)) return undefined
1031
+ const out: Array<{ title: string; desc?: string; time?: string }> = []
1032
+ for (const item of v) {
1033
+ if (out.length >= cap) break
1034
+ const o = obj(item)
1035
+ const title = o === undefined ? undefined : str(o.title, 256)
1036
+ if (title === undefined) continue
1037
+ out.push({
1038
+ title,
1039
+ ...opt('desc', o === undefined ? undefined : str(o.desc, GENUI_LIMITS.maxString)),
1040
+ ...opt('time', o === undefined ? undefined : str(o.time, 128)),
1041
+ })
1042
+ }
1043
+ return out
1044
+ }
1045
+
1046
+ function repairTree(v: unknown, cap: number): GenuiFileTreeNode[] | undefined {
1047
+ // Recursion is bounded by GENUI_LIMITS.maxTreeDepth (see the inner walk).
1048
+ return walkTree(v, cap, GENUI_LIMITS.maxTreeDepth)
1049
+ }
1050
+
1051
+ function walkTree(v: unknown, cap: number, depthLeft: number): GenuiFileTreeNode[] | undefined {
1052
+ if (!Array.isArray(v)) return undefined
1053
+ const out: GenuiFileTreeNode[] = []
1054
+ for (const item of v) {
1055
+ if (out.length >= cap) break
1056
+ const o = obj(item)
1057
+ const name = o === undefined ? undefined : str(o.name, 256)
1058
+ if (name === undefined) continue
1059
+ const children = o !== undefined && depthLeft > 0 && Array.isArray(o.children) ? walkTree(o.children, cap, depthLeft - 1) : undefined
1060
+ out.push({ name, ...opt('type', o === undefined ? undefined : enu(o.type, FILE_TYPES)), ...opt('children', children) })
1061
+ }
1062
+ return out
1063
+ }
1064
+
1065
+ function repairQuizOptions(v: unknown, answer?: unknown): Array<{ label: string; correct?: boolean; feedback?: string }> | undefined {
1066
+ if (!Array.isArray(v)) return undefined
1067
+ const out: Array<{ label: string; correct?: boolean; feedback?: string }> = []
1068
+ for (const optItem of v) {
1069
+ if (out.length >= GENUI_LIMITS.maxQuizOptions) break
1070
+ const o = obj(optItem)
1071
+ const label = typeof optItem === 'string' ? str(optItem, 512) : o === undefined ? undefined : str(o.label, 512)
1072
+ if (label === undefined) continue
1073
+ out.push({
1074
+ label,
1075
+ ...opt('correct', o === undefined ? undefined : o.correct === true ? true : undefined),
1076
+ ...opt('feedback', o === undefined ? undefined : str(o.feedback, GENUI_LIMITS.maxString)),
1077
+ })
1078
+ }
1079
+ // Nothing recoverable (empty array, all-non-string non-object items): return
1080
+ // undefined rather than an empty list, so repairNode drops the whole quiz
1081
+ // instead of half-rendering a question with no options — the same
1082
+ // silently-unusable state the string-options case produces when kept.
1083
+ if (out.length === 0) return undefined
1084
+
1085
+ // The canonical quiz shape stores correctness on each option. Models
1086
+ // commonly emit the simpler { options: string[], answer } form; only
1087
+ // use that alias when no canonical correct marker was supplied.
1088
+ if (out.some(option => option.correct === true)) return out
1089
+ const answerIndex = typeof answer === 'number' && Number.isFinite(answer)
1090
+ ? Math.trunc(answer)
1091
+ : typeof answer === 'string'
1092
+ ? out.findIndex(option => option.label === answer.slice(0, 512))
1093
+ : -1
1094
+ if (answerIndex < 0 || answerIndex >= out.length) return out
1095
+ return out.map((option, index) => index === answerIndex ? { ...option, correct: true } : option)
1096
+ }
1097
+
1098
+ /**
1099
+ * Patterns that indicate HTML/script injection in a string field. ECharts
1100
+ * default `tooltip.renderMode: 'html'` writes tooltip content via
1101
+ * `innerHTML`; even with renderMode forced to 'richText' (see below),
1102
+ * filtering these patterns is defense-in-depth — a model (or a
1103
+ * prompt-injected model) should never emit `<script>`, `onerror=`, or
1104
+ * `javascript:` inside a chart option string.
1105
+ */
1106
+ const ECHART_HTML_DANGER_RE = /<(?:script|img|svg|iframe|video|audio|object|embed|source)\b|on[a-z]+\s*=|javascript:/i
1107
+
1108
+ /**
1109
+ * Mutable budget counter for the sanitize walk — passed by reference so
1110
+ * every recursion shares one pool.
1111
+ */
1112
+ interface EChartSanitizeBudget { count: number }
1113
+
1114
+ /**
1115
+ * Sanitize an ECharts option object: depth-bounded, budget-bounded
1116
+ * pass-through that strips dangerous values (functions, `url()` in styles,
1117
+ * HTML/script injection patterns in strings) but preserves the object shape
1118
+ * ECharts needs. Scalars are KEPT: ECharts options are full of them,
1119
+ * including inside `data` arrays (`data: [120, 150, 180]`,
1120
+ * `xAxis.data: ['1月', '2月']`). Previously a scalar hit the plain-object
1121
+ * gate below and returned undefined, so every primitive-valued array was
1122
+ * filtered to empty and dropped — a chart with a full `option` rendered
1123
+ * with empty series (blank canvas). This is a safety walk, not an ECharts
1124
+ * semantic validator.
1125
+ *
1126
+ * Security: `tooltip.renderMode` is forced to `'richText'` on every tooltip
1127
+ * object. ECharts' default `'html'` mode writes tooltip content via
1128
+ * `innerHTML`, which is an XSS vector when the option originates from model
1129
+ * output — a prompt-injected model could emit
1130
+ * `{"tooltip":{"formatter":"<img src=x onerror=...>"}}` and execute
1131
+ * arbitrary script. `richText` renders as text, never touching innerHTML.
1132
+ */
1133
+ function sanitizeEChartOption(v: unknown, depth: number, budget: EChartSanitizeBudget): unknown {
1134
+ if (budget.count <= 0) return undefined
1135
+ budget.count -= 1
1136
+ if (depth > GENUI_LIMITS.maxEChartOptionDepth) return undefined
1137
+ // Scalars pass through: numbers/strings/booleans/null are legal ECharts
1138
+ // values both as object fields and as array elements.
1139
+ if (typeof v === 'string') {
1140
+ const s = v.slice(0, GENUI_LIMITS.maxString)
1141
+ // Reject strings containing HTML/script injection patterns or CSS url()
1142
+ // (exfiltration channel). Preserves legitimate ECharts string values
1143
+ // (labels, plain-text formatter templates, etc.).
1144
+ if (s.toLowerCase().includes('url(') || ECHART_HTML_DANGER_RE.test(s)) return undefined
1145
+ return s
1146
+ }
1147
+ if (typeof v === 'number' && Number.isFinite(v)) return v
1148
+ if (typeof v === 'boolean') return v
1149
+ if (v === null) return null
1150
+ if (Array.isArray(v)) {
1151
+ const cap = Math.min(v.length, GENUI_LIMITS.maxEChartArrayLen)
1152
+ const arr: unknown[] = []
1153
+ for (let i = 0; i < cap; i++) {
1154
+ const s = sanitizeEChartOption(v[i], depth + 1, budget)
1155
+ if (s !== undefined) arr.push(s)
1156
+ }
1157
+ return arr.length > 0 || v.length === 0 ? arr : undefined
1158
+ }
1159
+ const o = obj(v)
1160
+ if (o === undefined) return undefined
1161
+ const out: Record<string, unknown> = {}
1162
+ for (const [key, val] of Object.entries(o)) {
1163
+ const s = sanitizeEChartOption(val, depth + 1, budget)
1164
+ if (s === undefined) continue
1165
+ // Force tooltip.renderMode: 'richText' to prevent ECharts from writing
1166
+ // tooltip content via innerHTML (the default 'html' mode is an XSS
1167
+ // vector when the option comes from model output).
1168
+ if (key === 'tooltip' && typeof s === 'object' && s !== null && !Array.isArray(s)) {
1169
+ (s as Record<string, unknown>).renderMode = 'richText'
1170
+ }
1171
+ out[key] = s
1172
+ }
1173
+ // Empty axes/tooltip enable ECharts defaults; an empty data array clears it.
1174
+ // Keep intentional empties, while still dropping objects stripped by guards.
1175
+ return Object.keys(out).length > 0 || Object.keys(o).length === 0 ? out : undefined
1176
+ }
1177
+
1178
+ /**
1179
+ * Deterministically repair a raw spec value into a renderable GenuiSpec.
1180
+ * Returns null only when the root is not an object with an `items` array
1181
+ * (a bare component root is wrapped into a col first — the documented fence
1182
+ * vocabulary allows single-component bodies); every other defect is healed by
1183
+ * dropping/clamping/truncating. Idempotent: repairing a repaired spec is a
1184
+ * no-op.
1185
+ */
1186
+ function repairCanonicalGenuiSpec(value: unknown): GenuiSpec | null {
1187
+ const v = obj(value)
1188
+ if (v === undefined) return null
1189
+ // A bare component root (including data components whose `items` is their
1190
+ // record list — steps/list/timeline/…) wraps first; the wrapper is a plain
1191
+ // spec, so this recursion cannot wrap twice (issue #172).
1192
+ if (isComponentRoot(value)) {
1193
+ const wrapped = wrapSingleComponentRoot(value)
1194
+ if (wrapped === null) return null
1195
+ return repairCanonicalGenuiSpec(wrapped)
1196
+ }
1197
+ if (!Array.isArray(v.items)) return null
1198
+ const ctx: RepairCtx = { remaining: GENUI_LIMITS.maxNodes }
1199
+ return {
1200
+ ...opt('title', str(v.title, GENUI_LIMITS.maxString)),
1201
+ ...opt('gap', num(v.gap, 0, 96)),
1202
+ ...opt('panel', v.panel === true ? true : undefined),
1203
+ ...opt('append', v.append === true ? true : undefined),
1204
+ items: repairItems(v.items, ctx, 0),
1205
+ }
1206
+ }
1207
+
1208
+ /**
1209
+ * Deterministically repair a raw spec into a renderable GenuiSpec.
1210
+ *
1211
+ * Alias normalization is performed before the existing resource, type, and
1212
+ * security repair rules. The result remains idempotent and keeps the legacy
1213
+ * public API used by the fence renderer and client components.
1214
+ *
1215
+ * @param value - Raw GenUI spec or bare component.
1216
+ * @returns Repaired canonical spec, or null for an invalid root.
1217
+ */
1218
+ export function repairGenuiSpec(value: unknown): GenuiSpec | null {
1219
+ return repairCanonicalGenuiSpec(normalizeGenuiSpec(value).value)
1220
+ }
1221
+
1222
+ /* ---------------- validation ---------------- */
1223
+
1224
+ /**
1225
+ * Count the nodes of a spec tree (every item, descending into tabs /
1226
+ * accordion / file-tree / list containers — the same descent
1227
+ * `validateGenuiSpec` walks). Shared by the panel fold (node-budget gate)
1228
+ * and validation, so the panel never runs a second, divergent traversal.
1229
+ * `cap` bounds the walk for hostile inputs; the panel passes
1230
+ * `PANEL_LIMITS.maxNodes + 1` to detect overflow without counting the whole
1231
+ * tree.
1232
+ */
1233
+ export function countGenuiNodes(value: unknown, cap = Number.POSITIVE_INFINITY): number {
1234
+ let count = 0
1235
+ const walk = (list: unknown): void => {
1236
+ if (!Array.isArray(list)) return
1237
+ for (const item of list) {
1238
+ if (count >= cap) return
1239
+ count += 1
1240
+ const v = obj(item)
1241
+ if (v === undefined) continue
1242
+ if (v.type === 'tabs' && Array.isArray(v.tabs)) {
1243
+ for (const t of v.tabs) {
1244
+ if (count >= cap) return
1245
+ const to = obj(t)
1246
+ if (to !== undefined) walk(to.items)
1247
+ }
1248
+ } else if (v.type === 'accordion' && Array.isArray(v.items)) {
1249
+ for (const it of v.items) {
1250
+ if (count >= cap) return
1251
+ const io = obj(it)
1252
+ if (io !== undefined) walk(io.items)
1253
+ }
1254
+ } else if ((v.type === 'row' || v.type === 'col' || v.type === 'grid' || v.type === 'card') && Array.isArray(v.items)) {
1255
+ // Layout containers hold real children; skipping them undercounted
1256
+ // the tree and hid silent drops from validate_dsh_ui (issue #42).
1257
+ walk(v.items)
1258
+ } else if (v.type === 'file-tree') {
1259
+ // file-tree.items are data records, not GenUI children.
1260
+ } else if (v.type === 'list' && Array.isArray(v.items)) {
1261
+ // Typed list children are nodes too (repair charges them against the
1262
+ // budget); strings and {title,desc} shapes are skipped.
1263
+ for (const li of v.items) {
1264
+ if (count >= cap) return
1265
+ const lo = obj(li)
1266
+ if (lo !== undefined && typeof lo.type === 'string') walk([lo])
1267
+ }
1268
+ } else if (v.type === 'table' && Array.isArray(v.details)) {
1269
+ const rowCount = tableRowsForDetails(v).length
1270
+ for (let rowIndex = 0; rowIndex < Math.min(v.details.length, rowCount); rowIndex++) {
1271
+ if (count >= cap) return
1272
+ const detail = v.details[rowIndex]
1273
+ if (Array.isArray(detail) && isTableDetailReachable(v, rowIndex)) walk(detail)
1274
+ }
1275
+ }
1276
+ }
1277
+ }
1278
+ const root = obj(value)
1279
+ walk(root === undefined ? [] : root.items)
1280
+ return count
1281
+ }
1282
+
1283
+ /** Every white-listed node `type`. Keep in sync with the repairNode switch —
1284
+ * validate_dsh_ui uses it to tell declared GenUI nodes apart from unrelated
1285
+ * `"type"` strings (e.g. file-tree's `{type:'file'}` children). */
1286
+ export const GENUI_NODE_TYPES: ReadonlySet<string> = GENUI_NATIVE_TYPES
1287
+
1288
+ /**
1289
+ * Visit and count declared nodes in a raw spec tree: objects whose `type` is a
1290
+ * white-listed string, descending the same containers `countGenuiNodes`
1291
+ * walks. Callers can inspect field semantics or compare the count with the
1292
+ * repaired tree without maintaining another traversal.
1293
+ */
1294
+ function visitDeclaredGenuiNodes(
1295
+ value: unknown,
1296
+ cap: number,
1297
+ visit: (node: Record<string, unknown>, at: string) => void,
1298
+ ): number {
1299
+ let count = 0
1300
+ const declared = (candidate: unknown): boolean => {
1301
+ const o = obj(candidate)
1302
+ return o !== undefined && typeof o.type === 'string' && GENUI_NODE_TYPES.has(o.type)
1303
+ }
1304
+ function walk(list: unknown, path: string): void {
1305
+ if (!Array.isArray(list)) return
1306
+ for (let index = 0; index < list.length; index++) {
1307
+ walkNode(list[index], `${path}[${index}]`)
1308
+ if (count >= cap) return
1309
+ }
1310
+ }
1311
+ function walkNode(item: unknown, at: string): void {
1312
+ if (count >= cap || !declared(item)) return
1313
+ const v = obj(item)
1314
+ if (v === undefined) return
1315
+ count += 1
1316
+ visit(v, at)
1317
+ if (v.type === 'tabs' && Array.isArray(v.tabs)) {
1318
+ for (let tab = 0; tab < v.tabs.length; tab++) {
1319
+ walkItemsOf(v.tabs[tab], `${at}.tabs[${tab}]`)
1320
+ }
1321
+ } else if (v.type === 'accordion' && Array.isArray(v.items)) {
1322
+ for (let row = 0; row < v.items.length; row++) {
1323
+ walkItemsOf(v.items[row], `${at}.items[${row}]`)
1324
+ }
1325
+ } else if ((v.type === 'row' || v.type === 'col' || v.type === 'grid' || v.type === 'card') && Array.isArray(v.items)) {
1326
+ walk(v.items, `${at}.items`)
1327
+ } else if (v.type === 'list' && Array.isArray(v.items)) {
1328
+ for (let row = 0; row < v.items.length; row++) {
1329
+ walkNode(v.items[row], `${at}.items[${row}]`)
1330
+ }
1331
+ } else if (v.type === 'table' && Array.isArray(v.details)) {
1332
+ const rowCount = tableRowsForDetails(v).length
1333
+ for (let row = 0; row < Math.min(v.details.length, rowCount); row++) {
1334
+ if (Array.isArray(v.details[row]) && isTableDetailReachable(v, row)) walk(v.details[row], `${at}.details[${row}]`)
1335
+ }
1336
+ }
1337
+ }
1338
+ function walkItemsOf(holder: unknown, path: string): void {
1339
+ const o = obj(holder)
1340
+ if (o === undefined) return
1341
+ const items = o.items !== undefined ? o.items : o.content
1342
+ if (Array.isArray(items)) walk(items, `${path}.items`)
1343
+ else walkNode(items, `${path}.items`)
1344
+ }
1345
+ const root = obj(value)
1346
+ if (root === undefined) return count
1347
+ // Component root: the root itself is the declared node, whether or not it
1348
+ // carries an `items` data array (issue #172).
1349
+ if (isComponentRoot(root) && declared(value)) walkNode(value, 'spec')
1350
+ else walk(root.items, 'items')
1351
+ return count
1352
+ }
1353
+
1354
+ /**
1355
+ * Count white-listed nodes declared by a raw spec before repair drops invalid entries.
1356
+ * @param value - raw GenUI spec.
1357
+ * @param cap - traversal ceiling.
1358
+ * @returns declared node count up to the ceiling.
1359
+ */
1360
+ export function countDeclaredGenuiNodes(value: unknown, cap = Number.POSITIVE_INFINITY): number {
1361
+ return visitDeclaredGenuiNodes(value, cap, () => {})
1362
+ }
1363
+
1364
+ /** Count native nodes that survived repair, excluding opaque custom nodes. */
1365
+ export function countRenderedNativeGenuiNodes(value: unknown, cap = Number.POSITIVE_INFINITY): number {
1366
+ return countDeclaredGenuiNodes(value, cap)
1367
+ }
1368
+
1369
+ /**
1370
+ * Return field-level chart errors without changing other repairable component families.
1371
+ * @param value - raw GenUI spec.
1372
+ * @returns chart semantic errors in tree order.
1373
+ */
1374
+ export function validateGenuiChartSemantics(value: unknown): string[] {
1375
+ const errors: string[] = []
1376
+ visitDeclaredGenuiNodes(value, GENUI_LIMITS.maxNodes + 1, (node, at) => {
1377
+ if (node.type !== 'chart') return
1378
+ validateChartNode(node, at, errors)
1379
+ })
1380
+ return errors
1381
+ }
1382
+
1383
+ /**
1384
+ * Validate a raw spec value against the white list and limits, collecting
1385
+ * human-readable problems. Unlike repair this never mutates: it is a
1386
+ * diagnostic for tests and tooling. Unknown `type`s are reported (a plugin
1387
+ * custom type is valid only when a renderer is registered — the guard cannot
1388
+ * know, so it flags them as warnings).
1389
+ *
1390
+ * @param value - 未经过别名转换的 GenUI 文档。
1391
+ * @returns 完整结构与字段校验结果。
1392
+ */
1393
+ export function validateCanonicalGenuiSpec(value: unknown): GenuiValidation {
1394
+ const errors: string[] = []
1395
+ const v = obj(value)
1396
+ if (v === undefined) return { ok: false, errors: ['spec root must be an object'] }
1397
+ // Single-component root: validate through the wrapped form so the tool
1398
+ // agrees with the renderer about what is a valid fence body.
1399
+ if (isComponentRoot(value)) {
1400
+ const wrapped = wrapSingleComponentRoot(value)
1401
+ if (wrapped !== null) return validateCanonicalGenuiSpec(wrapped)
1402
+ return { ok: false, errors: ['spec.items must be an array'] }
1403
+ }
1404
+ if (!Array.isArray(v.items)) return { ok: false, errors: ['spec.items must be an array'] }
1405
+ validateSchemaFieldKinds(v, 'spec', GENUI_SPEC_SCHEMA, errors, ['items'])
1406
+ let count = 0
1407
+ let capped = false
1408
+ const walk = (list: unknown, depth: number, path: string): void => {
1409
+ if (capped) return
1410
+ if (!Array.isArray(list)) {
1411
+ errors.push(`${path} must be an array`)
1412
+ return
1413
+ }
1414
+ for (let i = 0; i < list.length; i++) {
1415
+ if (capped || count >= GENUI_LIMITS.maxNodes) {
1416
+ if (!capped) {
1417
+ errors.push(`spec exceeds ${GENUI_LIMITS.maxNodes} nodes; tail elided`)
1418
+ capped = true
1419
+ }
1420
+ return
1421
+ }
1422
+ count += 1
1423
+ const at = `${path}[${i}]`
1424
+ validateNode(list[i], depth, at, errors, walk)
1425
+ }
1426
+ }
1427
+ walk(v.items, 0, 'items')
1428
+ if (errors.length === 0) errors.push(...analyzeSubmissionRegistry(v as unknown as GenuiSpec).diagnostics)
1429
+ const uniqueErrors = [...new Set(errors)]
1430
+ return { ok: uniqueErrors.length === 0, errors: uniqueErrors }
1431
+ }
1432
+
1433
+ /**
1434
+ * Validate a raw GenUI value after deterministic alias normalization.
1435
+ *
1436
+ * Validation therefore only sees canonical fields; repairable aliases do not
1437
+ * produce false required-field errors. Structural and semantic defects remain
1438
+ * errors, while native unknown fields are exposed by the warning diagnostics
1439
+ * returned from `processGenuiSpec`.
1440
+ *
1441
+ * @param value - Raw GenUI spec or bare component.
1442
+ * @returns Validation result with human-readable errors.
1443
+ */
1444
+ export function validateGenuiSpec(value: unknown): GenuiValidation {
1445
+ return validateCanonicalGenuiSpec(normalizeGenuiSpec(value).value)
1446
+ }
1447
+
1448
+ export interface GenuiProcessResult {
1449
+ /** Canonical alias-normalized input value. */
1450
+ value: unknown
1451
+ /** Alias-normalized value, provided as an explicit descriptive alias. */
1452
+ normalized: unknown
1453
+ /** Canonical repaired value consumed by the renderer. */
1454
+ repaired: GenuiSpec | null
1455
+ /** Renderer-facing alias for `repaired`. */
1456
+ spec: GenuiSpec | null
1457
+ /** Structural and semantic validation errors. */
1458
+ errors: string[]
1459
+ /** Alias and native unknown-field warnings. */
1460
+ warnings: GenuiDiagnostic[]
1461
+ /** Native nodes declared in the canonical input, before repair drops. */
1462
+ declaredCount: number
1463
+ /** Nodes present in the repaired tree. */
1464
+ renderedCount: number
1465
+ /** Native nodes declared before repair, excluding custom payloads. */
1466
+ declaredNativeCount: number
1467
+ /** Native nodes present after repair, excluding custom and file-tree data. */
1468
+ renderedNativeCount: number
1469
+ /** All rendered component nodes, including opaque custom nodes. */
1470
+ renderedTotalCount: number
1471
+ }
1472
+
1473
+ /**
1474
+ * Run the shared canonical GenUI pipeline.
1475
+ *
1476
+ * The pipeline normalizes aliases, applies the existing deterministic repair
1477
+ * and security filters, validates the canonical input, and reports native
1478
+ * declarations that disappeared during repair. Custom nodes stay opaque and
1479
+ * do not participate in native unknown-field diagnostics.
1480
+ *
1481
+ * @param value - Raw GenUI spec or bare component.
1482
+ * @returns Canonical input, repaired output, diagnostics, and node counts.
1483
+ */
1484
+ export function processGenuiSpec(value: unknown): GenuiProcessResult {
1485
+ const normalized = normalizeGenuiSpec(value)
1486
+ const repaired = repairCanonicalGenuiSpec(normalized.value)
1487
+ const validation = validateCanonicalGenuiSpec(normalized.value)
1488
+ const declaredNativeCount = countDeclaredGenuiNodes(normalized.value, GENUI_LIMITS.maxNodes + 1)
1489
+ const renderedNativeCount = repaired === null ? 0 : countRenderedNativeGenuiNodes(repaired)
1490
+ const renderedTotalCount = repaired === null ? 0 : countGenuiNodes(repaired)
1491
+ // The shared public validator preserves its historical diagnostic for an
1492
+ // unknown type. The processing pipeline is renderer-aware by contract:
1493
+ // custom nodes stay opaque and must not fail native schema validation.
1494
+ const errors = validation.errors.filter(error => !error.includes(': unknown type '))
1495
+ if (repaired !== null && errors.length === 0) {
1496
+ errors.push(...analyzeSubmissionRegistry(repaired).diagnostics)
1497
+ }
1498
+ if (declaredNativeCount > renderedNativeCount) {
1499
+ errors.push(`repair dropped ${declaredNativeCount - renderedNativeCount} declared native node(s): declared ${declaredNativeCount}, rendered ${renderedNativeCount}`)
1500
+ }
1501
+ return {
1502
+ value: normalized.value,
1503
+ normalized: normalized.value,
1504
+ repaired,
1505
+ spec: repaired,
1506
+ errors: [...new Set(errors)],
1507
+ warnings: [...normalized.warnings, ...diagnoseUnknownGenuiFields(normalized.value)],
1508
+ // Compatibility fields retain their historical meanings: declaredCount
1509
+ // is native declarations, while renderedCount is the total rendered tree.
1510
+ declaredCount: declaredNativeCount,
1511
+ renderedCount: renderedTotalCount,
1512
+ declaredNativeCount,
1513
+ renderedNativeCount,
1514
+ renderedTotalCount,
1515
+ }
1516
+ }
1517
+
1518
+ /** Return whether the only process errors describe an intentional budget tail cut. */
1519
+ export function isIntentionalBudgetCut(processed: GenuiProcessResult): boolean {
1520
+ return processed.errors.length > 0
1521
+ && processed.errors.every(error => error.startsWith('spec exceeds ') || error.startsWith('repair dropped '))
1522
+ && processed.renderedNativeCount === GENUI_LIMITS.maxNodes
1523
+ && processed.declaredNativeCount === GENUI_LIMITS.maxNodes + 1
1524
+ }
1525
+
1526
+ /** Decide whether a repaired spec is safe to expose to any GenUI renderer. */
1527
+ export function isRenderableProcess(processed: GenuiProcessResult): boolean {
1528
+ return processed.spec !== null && (processed.errors.length === 0 || isIntentionalBudgetCut(processed))
1529
+ }
1530
+
1531
+ /* ---------------- partial fence rendering (issue #186) ---------------- */
1532
+
1533
+ /** Longest node or aligned table-detail slot path a validation error points at. */
1534
+ const DECLARED_NODE_PATH_RE = /^(items\[\d+\](?:\.(?:items\[\d+\]|tabs\[\d+\]\.items\[\d+\]|details\[\d+\](?:\[\d+\])?))*)/
1535
+
1536
+ function errorNodePath(error: string): string | null {
1537
+ const match = DECLARED_NODE_PATH_RE.exec(error)
1538
+ return match === null ? null : match[1] ?? null
1539
+ }
1540
+
1541
+ interface NodeSlot {
1542
+ array: unknown[]
1543
+ index: number
1544
+ /** Detail row slots align with table rows; pruning must not shift them. */
1545
+ preserveIndex: boolean
1546
+ }
1547
+
1548
+ /** Where the node or table-detail slot at a validation path lives. */
1549
+ function nodeSlotAt(root: Record<string, unknown>, path: string): NodeSlot | undefined {
1550
+ const steps = [...path.matchAll(/(?:^|\.)(items|tabs|details)\[(\d+)\]|\[(\d+)\]/g)]
1551
+ if (steps.length === 0 || steps[steps.length - 1]![1] === 'tabs') return undefined
1552
+ let current: unknown = root
1553
+ for (let i = 0; i < steps.length; i++) {
1554
+ const step = steps[i]!
1555
+ // A detail child has a second index without a property: details[row][node].
1556
+ const list = step[1] === undefined ? current : obj(current)?.[step[1]]
1557
+ const index = Number(step[2] ?? step[3])
1558
+ if (!Array.isArray(list) || index >= list.length) return undefined
1559
+ if (i === steps.length - 1) return { array: list, index, preserveIndex: step[1] === 'details' }
1560
+ current = list[index]
1561
+ if (current === undefined) return undefined
1562
+ }
1563
+ return undefined
1564
+ }
1565
+
1566
+ /** Deep-clone a JSON value for pruning; null when it cannot round-trip. */
1567
+ function cloneJsonValue(value: unknown): Record<string, unknown> | null {
1568
+ try {
1569
+ return obj(JSON.parse(JSON.stringify(value))) ?? null
1570
+ } catch {
1571
+ return null
1572
+ }
1573
+ }
1574
+
1575
+ /**
1576
+ * Best-effort repair for a spec whose strict validation failed: drop the
1577
+ * declared nodes the errors point at and re-run the whole pipeline once.
1578
+ *
1579
+ * The fence channels call this after the strict gate refuses, so ONE bad
1580
+ * component no longer degrades the whole fence to a code block — the
1581
+ * behaviour the capability map documents ("坏节点静默丢弃…不会拖垮界面") and
1582
+ * that validate_dsh_ui keeps diagnosing for the model. Bounded to a single
1583
+ * retry: a second failing pass is a genuinely pathological tree and keeps
1584
+ * today's full-fence fallback. Chart semantics stay protected the same way —
1585
+ * an undrawable chart is DROPPED here, never repaired into a blank canvas.
1586
+ */
1587
+ export function partialRepairGenuiSpec(processed: GenuiProcessResult): GenuiSpec | null {
1588
+ if (isRenderableProcess(processed)) return processed.spec
1589
+ if (processed.spec === null) return null
1590
+ const root = obj(processed.value)
1591
+ if (root === undefined) return null
1592
+ const paths = new Set<string>()
1593
+ const overhangPaths = new Set<string>()
1594
+ for (const error of processed.errors) {
1595
+ if (error.startsWith('spec exceeds ')) continue
1596
+ const nodePath = errorNodePath(error)
1597
+ if (nodePath === null) continue
1598
+ if (error === `${nodePath}.details must not contain more entries than rows`) {
1599
+ overhangPaths.add(nodePath)
1600
+ } else paths.add(nodePath)
1601
+ }
1602
+ if (paths.size === 0 && overhangPaths.size === 0) return null
1603
+ // Validation wraps a bare component first. Prune the same shape so its
1604
+ // detail paths resolve even when the table is the only declared node.
1605
+ const pruned = cloneJsonValue(isComponentRoot(root) ? wrapSingleComponentRoot(root) : root)
1606
+ if (pruned === null) return null
1607
+ // Resolve every slot BEFORE the first splice: each drop shifts the later
1608
+ // siblings of the same array, so a resolve-after-splice (deepest-first or
1609
+ // not) lands on the wrong row whenever two erroring nodes share a parent.
1610
+ // A resolved slot keeps its own array reference, so a parent drop cannot
1611
+ // invalidate an already-resolved child slot; per array, splicing
1612
+ // highest-index first keeps the remaining indexes valid (issue #190).
1613
+ const slots = [...paths]
1614
+ .map((path) => nodeSlotAt(pruned, path))
1615
+ .filter((slot): slot is NodeSlot => slot !== undefined)
1616
+ const overhangSlots = [...overhangPaths]
1617
+ .map((path) => nodeSlotAt(pruned, path))
1618
+ .filter((slot): slot is NodeSlot => slot !== undefined)
1619
+ // Extra details are unreachable. Mirror table repair's existing truncation
1620
+ // only for this exact diagnostic, then validate the whole candidate again.
1621
+ for (const { array, index } of overhangSlots) {
1622
+ const table = obj(array[index])
1623
+ if (table?.type === 'table' && Array.isArray(table.details)) {
1624
+ table.details.length = Math.min(table.details.length, tableRowsForDetails(table).length)
1625
+ }
1626
+ }
1627
+ const byArray = new Map<unknown[], number[]>()
1628
+ for (const { array, index, preserveIndex } of slots) {
1629
+ if (preserveIndex) {
1630
+ array[index] = null
1631
+ continue
1632
+ }
1633
+ const indexes = byArray.get(array)
1634
+ if (indexes === undefined) byArray.set(array, [index])
1635
+ else indexes.push(index)
1636
+ }
1637
+ for (const [array, indexes] of byArray) {
1638
+ indexes.sort((a, b) => b - a)
1639
+ for (const index of indexes) array.splice(index, 1)
1640
+ }
1641
+ const retry = processGenuiSpec(pruned)
1642
+ if (!isRenderableProcess(retry) || retry.renderedNativeCount === 0) return null
1643
+ return retry.spec
1644
+ }
1645
+
1646
+ type Walker = (list: unknown, depth: number, path: string) => void
1647
+
1648
+ function validateChartData(value: unknown, at: string, errors: string[]): void {
1649
+ if (!Array.isArray(value)) return
1650
+ for (let index = 0; index < value.length; index++) {
1651
+ const datum = obj(value[index])
1652
+ const path = `${at}[${index}]`
1653
+ if (datum === undefined) {
1654
+ errors.push(`${path} must be an object`)
1655
+ continue
1656
+ }
1657
+ if (typeof datum.label !== 'string') errors.push(`${path}.label must be a string`)
1658
+ if (typeof datum.value !== 'number' || !Number.isFinite(datum.value)) {
1659
+ errors.push(`${path}.value must be a finite number`)
1660
+ }
1661
+ if (datum.color !== undefined && typeof datum.color !== 'string') {
1662
+ errors.push(`${path}.color must be a string`)
1663
+ }
1664
+ }
1665
+ }
1666
+
1667
+ function validateChartSeries(value: unknown, at: string, errors: string[]): void {
1668
+ if (!Array.isArray(value)) return
1669
+ for (let index = 0; index < value.length; index++) {
1670
+ const series = obj(value[index])
1671
+ const path = `${at}[${index}]`
1672
+ if (series === undefined) {
1673
+ errors.push(`${path} must be an object`)
1674
+ continue
1675
+ }
1676
+ if (typeof series.label !== 'string') errors.push(`${path}.label must be a string`)
1677
+ if (series.color !== undefined && typeof series.color !== 'string') {
1678
+ errors.push(`${path}.color must be a string`)
1679
+ }
1680
+ if (!Array.isArray(series.data)) errors.push(`${path}.data must be an array`)
1681
+ validateChartData(series.data, `${path}.data`, errors)
1682
+ }
1683
+ }
1684
+
1685
+ function validateChartNode(v: Record<string, unknown>, at: string, errors: string[]): void {
1686
+ if (!Array.isArray(v.data) && !Array.isArray(v.series)) {
1687
+ errors.push(`${at}: type 'chart' requires data or series (array)`)
1688
+ }
1689
+ if (v.variant !== undefined) errors.push(`${at}.variant is unsupported; use kind`)
1690
+ if (v.data !== undefined && !Array.isArray(v.data)) errors.push(`${at}.data must be an array`)
1691
+ if (v.series !== undefined && !Array.isArray(v.series)) errors.push(`${at}.series must be an array`)
1692
+ if (v.kind !== undefined
1693
+ && (typeof v.kind !== 'string'
1694
+ || !CHART_KINDS.includes(v.kind as typeof CHART_KINDS[number]))) {
1695
+ errors.push(`${at}.kind must be bars, line, or donut`)
1696
+ }
1697
+ const kind = v.kind === undefined ? 'bars' : v.kind
1698
+ const series = Array.isArray(v.series) ? v.series : undefined
1699
+ // Grouped bars legitimately carry `data: []` and keep every point in
1700
+ // `series`; only an empty data array with NO series is undrawable.
1701
+ if (Array.isArray(v.data) && v.data.length === 0 && (series === undefined || series.length === 0)) {
1702
+ errors.push(`${at}.data must not be empty`)
1703
+ }
1704
+ if (series !== undefined) {
1705
+ if (series.length === 0) errors.push(`${at}.series must not be empty`)
1706
+ // A line chart accepts `series` (one line per entry); the donut is a
1707
+ // share-of-total shape and stays single-series.
1708
+ if (kind === 'donut') errors.push(`${at}.series is only supported for bars and line`)
1709
+ for (let index = 0; index < series.length; index++) {
1710
+ const entry = obj(series[index])
1711
+ if (entry !== undefined && Array.isArray(entry.data) && entry.data.length === 0) {
1712
+ errors.push(`${at}.series[${index}].data must not be empty`)
1713
+ }
1714
+ }
1715
+ }
1716
+ if (kind === 'donut' && v.data === undefined) {
1717
+ errors.push(`${at}.data is required for donut`)
1718
+ }
1719
+ if (kind === 'line' && v.data === undefined && (series === undefined || series.length === 0)) {
1720
+ errors.push(`${at}.data is required for line (or provide series)`)
1721
+ }
1722
+ validateChartData(v.data, `${at}.data`, errors)
1723
+ validateChartSeries(v.series, `${at}.series`, errors)
1724
+ }
1725
+
1726
+ /** Validate table rows before repair can silently remove malformed cells. */
1727
+ function validateTableRows(value: unknown, at: string, errors: string[]): void {
1728
+ if (!Array.isArray(value)) return
1729
+ for (let rowIndex = 0; rowIndex < value.length; rowIndex++) {
1730
+ const row = value[rowIndex]
1731
+ if (obj(row) !== undefined) continue
1732
+ if (!Array.isArray(row)) {
1733
+ errors.push(`${at}[${rowIndex}] must be an array or object`)
1734
+ continue
1735
+ }
1736
+ for (let cellIndex = 0; cellIndex < row.length; cellIndex++) {
1737
+ const cell = row[cellIndex]
1738
+ if (typeof cell !== 'string' && (typeof cell !== 'number' || !Number.isFinite(cell))) {
1739
+ errors.push(`${at}[${rowIndex}][${cellIndex}] must be a string or finite number`)
1740
+ }
1741
+ }
1742
+ }
1743
+ }
1744
+
1745
+ function validateNode(value: unknown, depth: number, at: string, errors: string[], walk: Walker): void {
1746
+ if (depth > GENUI_LIMITS.maxDepth) {
1747
+ errors.push(`${at}: exceeds max depth ${GENUI_LIMITS.maxDepth}`)
1748
+ return
1749
+ }
1750
+ const v = obj(value)
1751
+ if (v === undefined) {
1752
+ errors.push(`${at}: must be an object`)
1753
+ return
1754
+ }
1755
+ const type = v.type
1756
+ if (typeof type !== 'string') {
1757
+ errors.push(`${at}: missing string 'type'`)
1758
+ return
1759
+ }
1760
+ const isStr = (name: string): void => { if (v[name] !== undefined && typeof v[name] !== 'string') errors.push(`${at}: '${name}' must be a string`) }
1761
+ const isNum = (name: string): void => { if (v[name] !== undefined && (typeof v[name] !== 'number' || !Number.isFinite(v[name]))) errors.push(`${at}: '${name}' must be a finite number`) }
1762
+ switch (type) {
1763
+ case 'text':
1764
+ if (typeof v.content !== 'string' && typeof v.text !== 'string') {
1765
+ errors.push(`${at}: type 'text' requires content or text (string)`)
1766
+ }
1767
+ isStr('content')
1768
+ isStr('text')
1769
+ break
1770
+ case 'row': case 'col': case 'card': case 'grid':
1771
+ if (!Array.isArray(v.items)) errors.push(`${at}: type '${type}' requires items (array)`)
1772
+ walk(v.items, depth + 1, `${at}.items`)
1773
+ if (type === 'grid') isNum('cols')
1774
+ break
1775
+ case 'button': case 'checkbox': case 'link': case 'switch':
1776
+ if (typeof v.label !== 'string') errors.push(`${at}: type '${type}' requires label (string)`)
1777
+ isStr('label')
1778
+ break
1779
+ case 'image': case 'audio': case 'video':
1780
+ if (typeof v.src !== 'string') errors.push(`${at}: type '${type}' requires src (string)`)
1781
+ isStr('src')
1782
+ isStr('alt')
1783
+ if (type === 'video') isStr('poster')
1784
+ break
1785
+ case 'slider':
1786
+ isStr('label')
1787
+ isNum('min'); isNum('max'); isNum('step'); isNum('value')
1788
+ break
1789
+ case 'input': case 'textarea':
1790
+ isStr('label'); isStr('placeholder'); isStr('value')
1791
+ break
1792
+ case 'select': case 'radio':
1793
+ if (!Array.isArray(v.options)) errors.push(`${at}: type '${type}' requires options (array)`)
1794
+ break
1795
+ case 'submit':
1796
+ if (typeof v.label !== 'string') errors.push(`${at}: type 'submit' requires label (string)`)
1797
+ // 本地判卷可以不设置 action;不满足判卷条件时,渲染器会禁用无 action 的按钮。
1798
+ break
1799
+ case 'badge':
1800
+ if (typeof v.label !== 'string' && typeof v.text !== 'string' && typeof v.value !== 'string') {
1801
+ errors.push(`${at}: type 'badge' requires label, text, or value (string)`)
1802
+ }
1803
+ isStr('label')
1804
+ isStr('text')
1805
+ isStr('value')
1806
+ break
1807
+ case 'hero':
1808
+ if (typeof v.title !== 'string') errors.push(`${at}: type 'hero' requires title (string)`)
1809
+ isStr('subtitle')
1810
+ break
1811
+ case 'stat':
1812
+ if (typeof v.label !== 'string') errors.push(`${at}: type 'stat' requires label (string)`)
1813
+ if (typeof v.value !== 'string') errors.push(`${at}: type 'stat' requires value (string)`)
1814
+ isStr('delta')
1815
+ break
1816
+ case 'progress':
1817
+ if (typeof v.value !== 'number' || !Number.isFinite(v.value) || (v.value as number) < 0 || (v.value as number) > 100) {
1818
+ errors.push(`${at}: type 'progress' requires value (number 0..100)`)
1819
+ }
1820
+ isNum('value')
1821
+ break
1822
+ case 'avatar':
1823
+ if (typeof v.name !== 'string') errors.push(`${at}: type 'avatar' requires name (string)`)
1824
+ break
1825
+ case 'list':
1826
+ if (!Array.isArray(v.items)) errors.push(`${at}: type 'list' requires items (array)`)
1827
+ if (Array.isArray(v.items)) {
1828
+ // Descend into typed children so validation agrees with repair and
1829
+ // rendering (they recurse into list items as GenuiNodes). Strings and
1830
+ // {title,desc} list-item shapes are not nodes and are skipped.
1831
+ for (let i = 0; i < v.items.length; i++) {
1832
+ const item = obj(v.items[i])
1833
+ if (item !== undefined && typeof item.type === 'string') {
1834
+ validateNode(item, depth + 1, `${at}.items[${i}]`, errors, walk)
1835
+ }
1836
+ }
1837
+ }
1838
+ break
1839
+ case 'table':
1840
+ // `columns` may be satisfied by the 2D body itself (repair derives the
1841
+ // header from the leading row); only a body that cannot state its
1842
+ // columns is a contract error.
1843
+ if (!Array.isArray(v.columns) && !hasDerivableTableColumns(v)) errors.push(`${at}: type 'table' requires columns (array)`)
1844
+ if (!Array.isArray(v.rows)) errors.push(`${at}: type 'table' requires rows (array)`)
1845
+ if (v.types !== undefined && !Array.isArray(v.types)) {
1846
+ errors.push(`${at}.types must be an array of column cell types`)
1847
+ }
1848
+ if (v.details !== undefined && !Array.isArray(v.details)) {
1849
+ errors.push(`${at}.details must be an array aligned with rows`)
1850
+ }
1851
+ if (Array.isArray(v.details)) {
1852
+ const table = { columns: v.columns, rows: v.rows, types: v.types }
1853
+ const rowCount = tableRowsForDetails(table).length
1854
+ if (v.details.length > rowCount) errors.push(`${at}.details must not contain more entries than rows`)
1855
+ for (let i = 0; i < Math.min(v.details.length, rowCount); i++) {
1856
+ const detail = v.details[i]
1857
+ if (detail === null || !isTableDetailReachable(table, i)) continue
1858
+ if (!Array.isArray(detail)) {
1859
+ errors.push(`${at}.details[${i}] must be an array or null`)
1860
+ continue
1861
+ }
1862
+ walk(detail, depth + 1, `${at}.details[${i}]`)
1863
+ }
1864
+ }
1865
+ validateTableRows(v.rows, `${at}.rows`, errors)
1866
+ break
1867
+ case 'chart':
1868
+ validateChartNode(v, at, errors)
1869
+ break
1870
+ case 'tabs': {
1871
+ if (!Array.isArray(v.tabs)) errors.push(`${at}: type 'tabs' requires tabs (array)`)
1872
+ if (Array.isArray(v.tabs)) {
1873
+ for (let i = 0; i < v.tabs.length; i++) {
1874
+ const t = obj(v.tabs[i])
1875
+ if (t === undefined) { errors.push(`${at}.tabs[${i}] must be an object`); continue }
1876
+ if (typeof t.label !== 'string') errors.push(`${at}.tabs[${i}].label must be a string`)
1877
+ walk(t.items, depth + 1, `${at}.tabs[${i}].items`)
1878
+ }
1879
+ }
1880
+ break
1881
+ }
1882
+ case 'plot':
1883
+ if (!Array.isArray(v.series)) errors.push(`${at}: type 'plot' requires series (array)`)
1884
+ break
1885
+ case 'callout':
1886
+ if (typeof v.content !== 'string') errors.push(`${at}: type 'callout' requires content (string)`)
1887
+ break
1888
+ case 'steps':
1889
+ if (!Array.isArray(v.steps)) errors.push(`${at}: type 'steps' requires steps (array)`)
1890
+ break
1891
+ case 'keyvalue':
1892
+ if (!Array.isArray(v.pairs)) errors.push(`${at}: type 'keyvalue' requires pairs (array)`)
1893
+ break
1894
+ case 'diff':
1895
+ if (!Array.isArray(v.diffs)) errors.push(`${at}: type 'diff' requires diffs (array)`)
1896
+ break
1897
+ case 'json':
1898
+ if (!('value' in v)) errors.push(`${at}: type 'json' requires value`)
1899
+ break
1900
+ case 'code':
1901
+ if (typeof v.code !== 'string') errors.push(`${at}: type 'code' requires code (string)`)
1902
+ break
1903
+ case 'accordion':
1904
+ if (!Array.isArray(v.items)) errors.push(`${at}: type 'accordion' requires items (array)`)
1905
+ if (Array.isArray(v.items)) {
1906
+ for (let i = 0; i < v.items.length; i++) {
1907
+ const item = obj(v.items[i])
1908
+ if (item === undefined) { errors.push(`${at}.items[${i}] must be an object`); continue }
1909
+ if (typeof item.title !== 'string') errors.push(`${at}.items[${i}].title must be a string`)
1910
+ walk(item.items, depth + 1, `${at}.items[${i}].items`)
1911
+ }
1912
+ }
1913
+ break
1914
+ case 'copy':
1915
+ if (typeof v.text !== 'string') errors.push(`${at}: type 'copy' requires text (string)`)
1916
+ break
1917
+ case 'svg':
1918
+ if (typeof v.code !== 'string') errors.push(`${at}: type 'svg' requires code (string)`)
1919
+ isNum('height')
1920
+ break
1921
+ case 'mermaid':
1922
+ if (typeof v.code !== 'string') errors.push(`${at}: type 'mermaid' requires code (string)`)
1923
+ break
1924
+ case 'scene3d':
1925
+ if (!Array.isArray(v.meshes)) errors.push(`${at}: type 'scene3d' requires meshes (array)`)
1926
+ break
1927
+ case 'timeline':
1928
+ if (!Array.isArray(v.items)) errors.push(`${at}: type 'timeline' requires items (array)`)
1929
+ break
1930
+ case 'file-tree':
1931
+ if (!Array.isArray(v.items)) errors.push(`${at}: type 'file-tree' requires items (array)`)
1932
+ break
1933
+ case 'breadcrumb':
1934
+ if (!Array.isArray(v.items)) errors.push(`${at}: type 'breadcrumb' requires items (array)`)
1935
+ break
1936
+ case 'quiz':
1937
+ if (typeof v.question !== 'string') errors.push(`${at}: type 'quiz' requires question (string)`)
1938
+ if (!Array.isArray(v.options)) errors.push(`${at}: type 'quiz' requires options (array)`)
1939
+ break
1940
+ case 'diagram':
1941
+ if (typeof v.kind !== 'string') errors.push(`${at}: type 'diagram' requires kind (string)`)
1942
+ if (!Array.isArray(v.nodes)) errors.push(`${at}: type 'diagram' requires nodes (array)`)
1943
+ if (v.edges !== undefined && !Array.isArray(v.edges)) errors.push(`${at}: type 'diagram' requires edges (array) when present`)
1944
+ break
1945
+
1946
+ case 'echart':
1947
+ // `links` alone is a valid payload: the sankey/graph presets are driven
1948
+ // by edges only. Missing it here rejected the whole fence as
1949
+ // un-renderable (the render gate turns any error into "render nothing").
1950
+ if (v.option === undefined && v.data === undefined && v.series === undefined
1951
+ && (!Array.isArray(v.links) || v.links.length === 0)) {
1952
+ errors.push(`${at}: type 'echart' requires option, data, series, or links`)
1953
+ }
1954
+ isNum('height')
1955
+ break
1956
+ default:
1957
+ // Unknown type: plugin-registered custom nodes are valid when a
1958
+ // renderer exists; the guard cannot know, so report as a warning.
1959
+ errors.push(`${at}: unknown type '${type}' (custom renderer?)`)
1960
+ }
1961
+ const definition = COMPONENT_SCHEMAS[type]
1962
+ if (definition !== undefined) {
1963
+ validateRegistryFields(v, at, definition, errors)
1964
+ }
1965
+ }