@fengwk/kchart 0.0.0-stage → 0.1.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 (201) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE.md +11 -0
  4. package/README.md +68 -2
  5. package/README.zh-CN.md +69 -0
  6. package/dist/LICENSE +21 -0
  7. package/dist/NOTICE.md +11 -0
  8. package/dist/assets/ICONS-LICENSE.txt +53 -0
  9. package/dist/assets/maps/LICENSE.md +75 -0
  10. package/dist/assets/maps/METADATA.md +9 -0
  11. package/dist/assets/maps/REGIONS.md +28 -0
  12. package/dist/assets/maps/us-states.geojson +1 -0
  13. package/dist/assets/maps/world.geojson +1 -0
  14. package/dist/esm/_virtual/_kchart-families.js +48 -0
  15. package/dist/esm/_virtual/_rolldown/runtime.js +12 -0
  16. package/dist/esm/assets/icons.js +11 -0
  17. package/dist/esm/assets/maps/us-states.js +3 -0
  18. package/dist/esm/assets/maps/world.js +3 -0
  19. package/dist/esm/assets/themes/claude.js +69 -0
  20. package/dist/esm/assets/themes/cloudmusic.js +62 -0
  21. package/dist/esm/assets/themes/kanagawa.js +67 -0
  22. package/dist/esm/assets/themes/obsidian.js +67 -0
  23. package/dist/esm/assets/themes/paper.js +61 -0
  24. package/dist/esm/assets/themes/terminal.js +60 -0
  25. package/dist/esm/assets/themes/tokyo.js +62 -0
  26. package/dist/esm/chart/basic.js +1313 -0
  27. package/dist/esm/chart/catalog.js +476 -0
  28. package/dist/esm/chart/composition.js +844 -0
  29. package/dist/esm/chart/context.js +189 -0
  30. package/dist/esm/chart/distribution.js +442 -0
  31. package/dist/esm/chart/fields.js +67 -0
  32. package/dist/esm/chart/maps.js +563 -0
  33. package/dist/esm/chart/mindmap.js +629 -0
  34. package/dist/esm/chart/multivariate.js +1229 -0
  35. package/dist/esm/chart/registry.js +108 -0
  36. package/dist/esm/chart/relations.js +949 -0
  37. package/dist/esm/chart/spec.js +1415 -0
  38. package/dist/esm/chart/stat-compare.js +302 -0
  39. package/dist/esm/chart/stat-trend.js +181 -0
  40. package/dist/esm/chart/statistics.js +1007 -0
  41. package/dist/esm/chart/unit-variants.js +645 -0
  42. package/dist/esm/chart/variants.js +552 -0
  43. package/dist/esm/core/color.js +197 -0
  44. package/dist/esm/core/context.js +256 -0
  45. package/dist/esm/core/diagnostics.js +23 -0
  46. package/dist/esm/core/format.js +167 -0
  47. package/dist/esm/core/geometry.js +130 -0
  48. package/dist/esm/core/icon-data.js +5 -0
  49. package/dist/esm/core/icons.js +173 -0
  50. package/dist/esm/core/scale.js +112 -0
  51. package/dist/esm/core/scene.js +234 -0
  52. package/dist/esm/core/svg.js +89 -0
  53. package/dist/esm/core/text.js +184 -0
  54. package/dist/esm/core/theme.js +318 -0
  55. package/dist/esm/diagram/agentflow.js +596 -0
  56. package/dist/esm/diagram/architecture.js +729 -0
  57. package/dist/esm/diagram/block.js +988 -0
  58. package/dist/esm/diagram/blocks.js +687 -0
  59. package/dist/esm/diagram/c4.js +1002 -0
  60. package/dist/esm/diagram/class.js +1158 -0
  61. package/dist/esm/diagram/cynefin.js +749 -0
  62. package/dist/esm/diagram/emphasis.js +7 -0
  63. package/dist/esm/diagram/er.js +657 -0
  64. package/dist/esm/diagram/eventmodeling.js +948 -0
  65. package/dist/esm/diagram/gantt-date.js +323 -0
  66. package/dist/esm/diagram/gantt.js +661 -0
  67. package/dist/esm/diagram/gitgraph.js +472 -0
  68. package/dist/esm/diagram/graph-layout.js +4046 -0
  69. package/dist/esm/diagram/graph-parse.js +1366 -0
  70. package/dist/esm/diagram/graph-route.js +490 -0
  71. package/dist/esm/diagram/graph.js +553 -0
  72. package/dist/esm/diagram/ishikawa.js +496 -0
  73. package/dist/esm/diagram/journey.js +512 -0
  74. package/dist/esm/diagram/kanban.js +280 -0
  75. package/dist/esm/diagram/label.js +56 -0
  76. package/dist/esm/diagram/layers.js +385 -0
  77. package/dist/esm/diagram/map-label.js +44 -0
  78. package/dist/esm/diagram/mindmap.js +277 -0
  79. package/dist/esm/diagram/numeric-composition.js +78 -0
  80. package/dist/esm/diagram/numeric-model.js +86 -0
  81. package/dist/esm/diagram/numeric-parse.js +205 -0
  82. package/dist/esm/diagram/numeric-radar.js +355 -0
  83. package/dist/esm/diagram/numeric-sankey.js +201 -0
  84. package/dist/esm/diagram/numeric-xy.js +422 -0
  85. package/dist/esm/diagram/packet.js +175 -0
  86. package/dist/esm/diagram/presentation.js +252 -0
  87. package/dist/esm/diagram/quadrant.js +297 -0
  88. package/dist/esm/diagram/railroad-parse.js +465 -0
  89. package/dist/esm/diagram/railroad.js +294 -0
  90. package/dist/esm/diagram/registry.js +296 -0
  91. package/dist/esm/diagram/relations.js +966 -0
  92. package/dist/esm/diagram/requirement.js +341 -0
  93. package/dist/esm/diagram/sequence.js +1228 -0
  94. package/dist/esm/diagram/shapes.js +366 -0
  95. package/dist/esm/diagram/source.js +538 -0
  96. package/dist/esm/diagram/support.js +153 -0
  97. package/dist/esm/diagram/swimlane-mermaid.js +140 -0
  98. package/dist/esm/diagram/swimlane.js +1186 -0
  99. package/dist/esm/diagram/time.js +748 -0
  100. package/dist/esm/diagram/timeline.js +376 -0
  101. package/dist/esm/diagram/tree-family-icon.js +22 -0
  102. package/dist/esm/diagram/treeview.js +293 -0
  103. package/dist/esm/diagram/usecase.js +852 -0
  104. package/dist/esm/diagram/venn.js +1038 -0
  105. package/dist/esm/diagram/wardley.js +838 -0
  106. package/dist/esm/index.d.ts +133 -0
  107. package/dist/esm/index.js +92 -0
  108. package/dist/esm/interaction.js +561 -0
  109. package/dist/esm/mermaid.d.ts +28 -0
  110. package/dist/esm/mermaid.js +70 -0
  111. package/dist/esm/node.d.ts +68 -0
  112. package/dist/esm/node.js +373 -0
  113. package/dist/esm/package.json +1 -0
  114. package/dist/esm/page-api.js +65 -0
  115. package/dist/esm/runtime.js +352 -0
  116. package/dist/esm/src/families.js +209 -0
  117. package/dist/page-api.js +1 -0
  118. package/dist/units/chart/basic.js +1 -0
  119. package/dist/units/chart/catalog.js +1 -0
  120. package/dist/units/chart/composition.js +1 -0
  121. package/dist/units/chart/context.js +1 -0
  122. package/dist/units/chart/distribution.js +1 -0
  123. package/dist/units/chart/fields.js +1 -0
  124. package/dist/units/chart/maps.js +1 -0
  125. package/dist/units/chart/mindmap.js +1 -0
  126. package/dist/units/chart/multivariate.js +1 -0
  127. package/dist/units/chart/registry.js +1 -0
  128. package/dist/units/chart/relations.js +1 -0
  129. package/dist/units/chart/spec.js +3 -0
  130. package/dist/units/chart/stat-compare.js +1 -0
  131. package/dist/units/chart/stat-trend.js +1 -0
  132. package/dist/units/chart/statistics.js +1 -0
  133. package/dist/units/chart/unit-variants.js +1 -0
  134. package/dist/units/chart/variants.js +1 -0
  135. package/dist/units/core/color.js +1 -0
  136. package/dist/units/core/context.js +1 -0
  137. package/dist/units/core/diagnostics.js +1 -0
  138. package/dist/units/core/format.js +1 -0
  139. package/dist/units/core/geometry.js +1 -0
  140. package/dist/units/core/icon-data.js +1 -0
  141. package/dist/units/core/icons.js +1 -0
  142. package/dist/units/core/scale.js +1 -0
  143. package/dist/units/core/scene.js +1 -0
  144. package/dist/units/core/svg.js +1 -0
  145. package/dist/units/core/text.js +2 -0
  146. package/dist/units/core/theme.js +1 -0
  147. package/dist/units/diagram/agentflow.js +12 -0
  148. package/dist/units/diagram/architecture.js +4 -0
  149. package/dist/units/diagram/block.js +2 -0
  150. package/dist/units/diagram/blocks.js +2 -0
  151. package/dist/units/diagram/c4.js +6 -0
  152. package/dist/units/diagram/class.js +5 -0
  153. package/dist/units/diagram/cynefin.js +4 -0
  154. package/dist/units/diagram/emphasis.js +1 -0
  155. package/dist/units/diagram/er.js +9 -0
  156. package/dist/units/diagram/eventmodeling.js +5 -0
  157. package/dist/units/diagram/gantt-date.js +1 -0
  158. package/dist/units/diagram/gantt.js +3 -0
  159. package/dist/units/diagram/gitgraph.js +2 -0
  160. package/dist/units/diagram/graph-layout.js +4 -0
  161. package/dist/units/diagram/graph-parse.js +9 -0
  162. package/dist/units/diagram/graph-route.js +1 -0
  163. package/dist/units/diagram/graph.js +1 -0
  164. package/dist/units/diagram/ishikawa.js +2 -0
  165. package/dist/units/diagram/journey.js +5 -0
  166. package/dist/units/diagram/kanban.js +2 -0
  167. package/dist/units/diagram/label.js +4 -0
  168. package/dist/units/diagram/layers.js +1 -0
  169. package/dist/units/diagram/map-label.js +1 -0
  170. package/dist/units/diagram/mindmap.js +2 -0
  171. package/dist/units/diagram/numeric-composition.js +1 -0
  172. package/dist/units/diagram/numeric-model.js +1 -0
  173. package/dist/units/diagram/numeric-parse.js +2 -0
  174. package/dist/units/diagram/numeric-radar.js +3 -0
  175. package/dist/units/diagram/numeric-sankey.js +2 -0
  176. package/dist/units/diagram/numeric-xy.js +2 -0
  177. package/dist/units/diagram/packet.js +2 -0
  178. package/dist/units/diagram/presentation.js +2 -0
  179. package/dist/units/diagram/quadrant.js +2 -0
  180. package/dist/units/diagram/railroad-parse.js +4 -0
  181. package/dist/units/diagram/railroad.js +1 -0
  182. package/dist/units/diagram/registry.js +2 -0
  183. package/dist/units/diagram/relations.js +3 -0
  184. package/dist/units/diagram/requirement.js +3 -0
  185. package/dist/units/diagram/sequence.js +2 -0
  186. package/dist/units/diagram/shapes.js +60 -0
  187. package/dist/units/diagram/source.js +20 -0
  188. package/dist/units/diagram/support.js +3 -0
  189. package/dist/units/diagram/swimlane-mermaid.js +3 -0
  190. package/dist/units/diagram/swimlane.js +2 -0
  191. package/dist/units/diagram/time.js +3 -0
  192. package/dist/units/diagram/timeline.js +2 -0
  193. package/dist/units/diagram/tree-family-icon.js +1 -0
  194. package/dist/units/diagram/treeview.js +2 -0
  195. package/dist/units/diagram/usecase.js +3 -0
  196. package/dist/units/diagram/venn.js +2 -0
  197. package/dist/units/diagram/wardley.js +4 -0
  198. package/dist/units/interaction.js +1 -0
  199. package/dist/units/runtime.js +1 -0
  200. package/dist/units.json +712 -0
  201. package/package.json +30 -4
@@ -0,0 +1,1415 @@
1
+ import { __exportAll } from "../_virtual/_rolldown/runtime.js";
2
+ import { catalog } from "./catalog.js";
3
+ // src/chart/spec.js
4
+ var spec_exports = /* @__PURE__ */ __exportAll({
5
+ parse: () => parse,
6
+ schema: () => schema,
7
+ sizeBudget: () => sizeBudget,
8
+ validate: () => validate
9
+ });
10
+ var TOP = /* @__PURE__ */ new Set([
11
+ "chart",
12
+ "title",
13
+ "subtitle",
14
+ "source",
15
+ "note",
16
+ "data",
17
+ "encode",
18
+ "fields",
19
+ "unit",
20
+ "variant",
21
+ "layout",
22
+ "sort",
23
+ "emphasis",
24
+ "annotations",
25
+ "interaction",
26
+ "stack",
27
+ "unitMark",
28
+ "range",
29
+ "start",
30
+ "layers",
31
+ "period",
32
+ "directed",
33
+ ...Object.values(catalog).flatMap((c) => Object.keys(c.special))
34
+ ]);
35
+ var NODE_SHAPES = [
36
+ "rect",
37
+ "rounded",
38
+ "circle",
39
+ "bang",
40
+ "cloud",
41
+ "hexagon",
42
+ "none"
43
+ ];
44
+ var ENCODE = /* @__PURE__ */ new Set([
45
+ "category",
46
+ "value",
47
+ "series",
48
+ "id",
49
+ "lower",
50
+ "upper",
51
+ "intensity",
52
+ "panel",
53
+ "actual",
54
+ "target",
55
+ "before",
56
+ "after",
57
+ "open",
58
+ "close",
59
+ "low",
60
+ "high",
61
+ "delta",
62
+ "count",
63
+ "q1",
64
+ "median",
65
+ "q3",
66
+ "outliers",
67
+ "density",
68
+ "x",
69
+ "y",
70
+ "size",
71
+ "label",
72
+ "row",
73
+ "column",
74
+ "date",
75
+ "rank",
76
+ "dimensions",
77
+ "start",
78
+ "region",
79
+ "longitude",
80
+ "latitude"
81
+ ]);
82
+ var FIELD_KEYS = /* @__PURE__ */ new Set([
83
+ "label",
84
+ "type",
85
+ "unit",
86
+ "format",
87
+ "decimals",
88
+ "domain",
89
+ "scale"
90
+ ]);
91
+ var ALL_EMPHASIS = [
92
+ "rows",
93
+ "fields",
94
+ "series"
95
+ ];
96
+ var ROW_EMPHASIS = ["rows"];
97
+ var SERIES_EMPHASIS = ["fields", "series"];
98
+ var EMPHASIS = {
99
+ line: {
100
+ "": ALL_EMPHASIS,
101
+ counter: ALL_EMPHASIS,
102
+ barcode: ROW_EMPHASIS
103
+ },
104
+ area: { "": ALL_EMPHASIS },
105
+ bar: {
106
+ "": ALL_EMPHASIS,
107
+ solid: ALL_EMPHASIS,
108
+ lollipop: ROW_EMPHASIS,
109
+ rungs: ROW_EMPHASIS,
110
+ pictorial: ROW_EMPHASIS
111
+ },
112
+ column: {
113
+ "": ALL_EMPHASIS,
114
+ solid: ALL_EMPHASIS,
115
+ lollipop: ROW_EMPHASIS,
116
+ rungs: ROW_EMPHASIS,
117
+ pictorial: ROW_EMPHASIS
118
+ },
119
+ share: {
120
+ "": SERIES_EMPHASIS,
121
+ solid: SERIES_EMPHASIS
122
+ },
123
+ funnel: {
124
+ "": ROW_EMPHASIS,
125
+ bars: ROW_EMPHASIS
126
+ }
127
+ };
128
+ var err = (errors, path, message, fix = "请按图型契约修正字段或数据。", code = "BAD_KCHART", loc) => errors.push({
129
+ code,
130
+ path,
131
+ message,
132
+ fix,
133
+ ...loc ? { location: loc } : {}
134
+ });
135
+ var obj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
136
+ var finite = (v) => typeof v === "number" && Number.isFinite(v);
137
+ var ptr = (p) => p.map((x) => `/${String(x).replace(/~/g, "~0").replace(/\//g, "~1")}`).join("");
138
+ var keys = (value, allowed, path, errors) => {
139
+ if (!obj(value)) {
140
+ err(errors, path, "必须是对象");
141
+ return;
142
+ }
143
+ for (const key of Object.keys(value)) if (!allowed.has(key)) err(errors, `${path}/${key}`, "未知字段");
144
+ };
145
+ var safeDate = (v, type) => {
146
+ if (typeof v !== "string") return false;
147
+ if (type === "month") return /^\d{4}-(0[1-9]|1[0-2])$/.test(v);
148
+ if (type === "date") {
149
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(v)) return false;
150
+ const d = /* @__PURE__ */ new Date(`${v}T00:00:00Z`);
151
+ return Number.isFinite(d.getTime()) && d.toISOString().slice(0, 10) === v;
152
+ }
153
+ if (type === "datetime") return /^\d{4}-\d\d-\d\dT.*(?:Z|[+-]\d\d:\d\d)$/.test(v) && safeDate(v.slice(0, 10), "date") && Number.isFinite(Date.parse(v));
154
+ return true;
155
+ };
156
+ var sizeBudget = Symbol("size budget");
157
+ function validate(spec) {
158
+ const errors = [];
159
+ if (!obj(spec)) {
160
+ err(errors, "", "声明必须是对象");
161
+ return {
162
+ errors,
163
+ data: null
164
+ };
165
+ }
166
+ for (const field of Object.keys(spec)) {
167
+ if (TOP.has(field)) continue;
168
+ if (field === "id") err(errors, "/id", "图表声明不接受根级 id", "移除根级 id;要标识数据行时,若图型支持,使用 encode.id 映射到行字段。");
169
+ else err(errors, ptr([field]), "未知字段");
170
+ }
171
+ const c = typeof spec.chart === "string" ? catalog[spec.chart] : void 0;
172
+ if (!c) err(errors, "/chart", "未知图型", "chart 必须是注册图型名。");
173
+ for (const k of [
174
+ "title",
175
+ "subtitle",
176
+ "source",
177
+ "note",
178
+ "unit"
179
+ ]) if (spec[k] !== void 0 && typeof spec[k] !== "string") err(errors, `/${k}`, "必须是字符串");
180
+ if (spec.unit === "%") err(errors, "/unit", "根 unit 不可写 %", "比例数据请用 fields.<字段>.format=percent。");
181
+ if (spec.data === void 0) err(errors, "/data", "必填字段缺失");
182
+ if (c) {
183
+ const shapeOk = c.shape === "table" ? Array.isArray(spec.data) && spec.data.length > 0 && spec.data.every(obj) : c.shape === "tree" ? obj(spec.data) : c.shape === "network" ? obj(spec.data) && Array.isArray(spec.data.nodes) && Array.isArray(spec.data.edges) : c.shape === "paths" ? obj(spec.data) && Array.isArray(spec.data.stages) && Array.isArray(spec.data.nodes) && Array.isArray(spec.data.paths) : obj(spec.data) && obj(spec.data.map) && Array.isArray(spec.data.rows);
184
+ if (!shapeOk) err(errors, "/data", `数据必须匹配 ${c.shape} 形状`);
185
+ const errorsBeforeEncode = errors.length;
186
+ if (c.shape === "table") {
187
+ if (!obj(spec.encode)) err(errors, "/encode", "必须提供角色映射");
188
+ else {
189
+ keys(spec.encode, ENCODE, "/encode", errors);
190
+ for (const role of c.required) if (spec.encode[role] === void 0) err(errors, `/encode/${role}`, "必填角色缺失");
191
+ for (const role of Object.keys(spec.encode)) if (![...c.required, ...c.optional].includes(role)) err(errors, `/encode/${role}`, "该图型不支持此角色");
192
+ for (const role of [...c.required, ...c.optional]) if (spec.encode[role] !== void 0) {
193
+ const value = spec.encode[role];
194
+ const allowsArray = c.arrayRoles.includes(role);
195
+ if (role === "dimensions") {
196
+ if (!Array.isArray(value) || !value.length || !value.every((x) => typeof x === "string" && x)) err(errors, `/encode/${role}`, "dimensions须为非空字段名数组");
197
+ } else if (allowsArray) {
198
+ if (!(typeof value === "string" && value || Array.isArray(value) && value.length && value.every((x) => typeof x === "string" && x))) err(errors, `/encode/${role}`, "须为非空字段名或字段名数组");
199
+ } else if (typeof value !== "string" || !value) err(errors, `/encode/${role}`, "必须是单个非空字段名");
200
+ }
201
+ }
202
+ } else if (c.shape === "geo") {
203
+ if (!obj(spec.encode)) err(errors, "/encode", "地图必须提供角色映射");
204
+ else {
205
+ keys(spec.encode, ENCODE, "/encode", errors);
206
+ for (const role of c.required) if (spec.encode[role] === void 0) err(errors, `/encode/${role}`, "必填角色缺失");
207
+ for (const [role, value] of Object.entries(spec.encode)) if (![...c.required, ...c.optional].includes(role)) err(errors, `/encode/${role}`, "该地图不支持此角色");
208
+ else if (typeof value !== "string" || !value) err(errors, `/encode/${role}`, "必须是单个非空字段名");
209
+ }
210
+ } else if (spec.encode !== void 0) err(errors, "/encode", "该图型不使用 encode");
211
+ const encodeOk = errors.length === errorsBeforeEncode;
212
+ const layersOk = c.name !== "combo" || Array.isArray(spec.layers) && spec.layers.every((layer) => obj(layer) && typeof layer.field === "string");
213
+ const commonFields = /* @__PURE__ */ new Set([
214
+ "chart",
215
+ "title",
216
+ "subtitle",
217
+ "source",
218
+ "note",
219
+ "data",
220
+ "fields",
221
+ "unit",
222
+ "sort",
223
+ "emphasis",
224
+ "annotations",
225
+ "interaction",
226
+ "encode"
227
+ ]);
228
+ for (const field of Object.keys(spec)) if (TOP.has(field) && !commonFields.has(field) && c.special[field] === void 0 && !(field === "unitMark" && [
229
+ "bar",
230
+ "column",
231
+ "dumbbell",
232
+ "waterfall",
233
+ "histogram"
234
+ ].includes(c.name))) err(errors, `/${field}`, `图型 ${c.name} 不支持此参数`);
235
+ for (const field of c.requiredSpecial) if (spec[field] === void 0) err(errors, `/${field}`, "必填专用字段缺失");
236
+ for (const [field, allowed] of Object.entries(c.special)) {
237
+ const v = spec[field];
238
+ if (v === void 0) {
239
+ if (allowed === "range") err(errors, `/${field}`, "必填专用字段缺失");
240
+ continue;
241
+ }
242
+ if (Array.isArray(allowed) && !allowed.includes(v)) err(errors, `/${field}`, `必须为 ${allowed.join("、")} 中的一项`);
243
+ else if (allowed === "boolean" && typeof v !== "boolean") err(errors, `/${field}`, "必须是布尔值");
244
+ else if (allowed === "number" && !finite(v)) err(errors, `/${field}`, "必须是有限数");
245
+ else if (field === "rings" && (!Number.isInteger(v) || v < 2 || v > 8)) err(errors, `/${field}`, "必须是 2 至 8 的整数");
246
+ else if (allowed === "year" && (typeof v !== "string" || !/^\d{4}$/.test(v))) err(errors, `/${field}`, "必须是YYYY年份");
247
+ else if (allowed === "range" && !(Array.isArray(v) && v.length === 2 && v.every(finite) && v[0] < v[1])) err(errors, `/${field}`, "必须是递增的有限数范围");
248
+ else if (allowed === "layers" && (!Array.isArray(v) || !v.length || v.some((x) => !obj(x) || ![
249
+ "line",
250
+ "area",
251
+ "column"
252
+ ].includes(x.mark) || typeof x.field !== "string" || !["left", "right"].includes(x.axis)))) err(errors, `/${field}`, "必须是有效 layers 数组");
253
+ }
254
+ if (spec.unitMark !== void 0) {
255
+ keys(spec.unitMark, /* @__PURE__ */ new Set([
256
+ "value",
257
+ "label",
258
+ "icon"
259
+ ]), "/unitMark", errors);
260
+ if (!obj(spec.unitMark) || !finite(spec.unitMark.value) || spec.unitMark.value <= 0 || typeof spec.unitMark.label !== "string" || !spec.unitMark.label) err(errors, "/unitMark", "unitMark须含正有限value及非空label");
261
+ if (spec.variant === "rungs" && spec.unitMark?.icon !== void 0) err(errors, "/unitMark/icon", "rungs不支持icon");
262
+ if (spec.variant === "pictorial" && (typeof spec.unitMark?.icon !== "string" || !spec.unitMark.icon)) err(errors, "/unitMark/icon", "pictorial必须指定受控icon ID");
263
+ }
264
+ if (["rungs", "pictorial"].includes(spec.variant) && spec.unitMark === void 0) err(errors, "/unitMark", "该变体必须声明unitMark");
265
+ if (spec.unitMark !== void 0 && ![
266
+ "bar",
267
+ "column",
268
+ "dumbbell",
269
+ "waterfall",
270
+ "histogram"
271
+ ].includes(c.name)) err(errors, "/unitMark", "该图型不支持unitMark");
272
+ if (shapeOk && c.shape === "tree") checkTree(spec.data, c.name, errors, spec[sizeBudget]);
273
+ if (shapeOk && c.shape === "network") checkNetwork(spec.data, spec.chart, errors, spec.tolerant === true);
274
+ if (shapeOk && c.shape === "paths") checkPaths(spec.data, errors);
275
+ if (c.shape === "geo" && spec.data?.map) {
276
+ const m = spec.data.map;
277
+ const builtin = obj(m) && Object.keys(m).length === 1 && ["world", "us-states"].includes(m.asset);
278
+ const external = obj(m) && obj(m.geojson) && m.geojson.type === "FeatureCollection" && Array.isArray(m.geojson.features) && typeof m.idProperty === "string" && Object.keys(m).every((k) => ["geojson", "idProperty"].includes(k));
279
+ if (!builtin && !external) err(errors, "/data/map", "map须是world、us-states或GeoJSON FeatureCollection");
280
+ if (external) {
281
+ const ids = /* @__PURE__ */ new Set();
282
+ for (const [i, f] of m.geojson.features.entries()) {
283
+ if (!obj(f) || f.type !== "Feature" || !obj(f.properties) || !obj(f.geometry) || !["Polygon", "MultiPolygon"].includes(f.geometry.type)) {
284
+ err(errors, `/data/map/geojson/features/${i}`, "地图仅支持带properties的Polygon/MultiPolygon Feature");
285
+ continue;
286
+ }
287
+ const id = f.properties[m.idProperty];
288
+ if (typeof id !== "string" || !id || ids.has(id)) err(errors, `/data/map/geojson/features/${i}/properties/${m.idProperty}`, "地图地区键须唯一非空字符串");
289
+ ids.add(id);
290
+ }
291
+ }
292
+ }
293
+ if (c.shape === "table" && shapeOk && encodeOk && layersOk) checkTable(spec, c, errors);
294
+ if (c.shape === "geo" && shapeOk && encodeOk) checkGeoRows(spec, c, errors);
295
+ }
296
+ if (spec.fields !== void 0) {
297
+ if (!obj(spec.fields)) err(errors, "/fields", "必须是对象");
298
+ else for (const [name, f] of Object.entries(spec.fields)) {
299
+ keys(f, FIELD_KEYS, `/fields/${name}`, errors);
300
+ if (!obj(f)) continue;
301
+ if (f.label !== void 0 && typeof f.label !== "string") err(errors, `/fields/${name}/label`, "必须是字符串");
302
+ if (f.type !== void 0 && ![
303
+ "number",
304
+ "category",
305
+ "date",
306
+ "month",
307
+ "datetime"
308
+ ].includes(f.type)) err(errors, `/fields/${name}/type`, "无效字段类型");
309
+ if (f.format !== void 0 && !["number", "percent"].includes(f.format)) err(errors, `/fields/${name}/format`, "无效数值格式");
310
+ if (f.unit !== void 0 && typeof f.unit !== "string") err(errors, `/fields/${name}/unit`, "必须是字符串");
311
+ if (f.unit !== void 0 && f.format === "percent") err(errors, `/fields/${name}`, "percent已隐含%单位,不可再声明unit");
312
+ if (f.decimals !== void 0 && (!Number.isInteger(f.decimals) || f.decimals < 0 || f.decimals > 6)) err(errors, `/fields/${name}/decimals`, "必须是0至6的整数");
313
+ if (f.scale !== void 0 && !["linear", "log"].includes(f.scale)) err(errors, `/fields/${name}/scale`, "无效scale");
314
+ if (f.domain !== void 0) {
315
+ const d = f.domain;
316
+ if (!(Array.isArray(d) && (d.length === 2 && d.every(finite) && d[0] < d[1] || d.every((x) => typeof x === "string") && new Set(d).size === d.length))) err(errors, `/fields/${name}/domain`, "domain须为递增数值范围或无重复分类序列");
317
+ }
318
+ }
319
+ }
320
+ if (spec.unit !== void 0 && spec.fields && Object.values(spec.fields).some((f) => obj(f) && (f.unit !== void 0 || f.format === "percent"))) err(errors, "/unit", "根 unit 与字段级 unit/percent 冲突");
321
+ if (spec.unit !== void 0 && ["radial-share", "split-compare"].includes(spec.chart)) err(errors, "/unit", "该图型不支持根 unit,须分别声明字段单位或格式");
322
+ if (spec.sort !== void 0) {
323
+ keys(spec.sort, /* @__PURE__ */ new Set(["field", "direction"]), "/sort", errors);
324
+ if (!obj(spec.sort) || typeof spec.sort.field !== "string" || !["asc", "desc"].includes(spec.sort.direction)) err(errors, "/sort", "须为 {field,direction:asc|desc}");
325
+ if (![
326
+ "bar",
327
+ "column",
328
+ "pie",
329
+ "donut",
330
+ "radial-share",
331
+ "rose",
332
+ "tally"
333
+ ].includes(spec.chart)) err(errors, "/sort", "该图型不支持排序");
334
+ if (obj(spec.encode) && spec.sort?.field) {
335
+ const vals = spec.encode.value;
336
+ const category = spec.encode.category;
337
+ if (Array.isArray(vals) && vals.length !== 1) err(errors, "/sort", "多系列图不能排序");
338
+ if (![category, ...Array.isArray(vals) ? vals : [vals]].includes(spec.sort.field)) err(errors, "/sort/field", "sort.field必须是实际category或value字段");
339
+ }
340
+ }
341
+ if (spec.interaction !== void 0) {
342
+ if (!Array.isArray(spec.interaction) || spec.interaction.some((action) => ![
343
+ "inspect",
344
+ "legend",
345
+ "focus",
346
+ "pan-zoom",
347
+ "drag",
348
+ "collapse"
349
+ ].includes(action))) err(errors, "/interaction", "包含无效交互");
350
+ else for (const action of spec.interaction) if (!(action === "inspect" || action === "legend" && [
351
+ "line",
352
+ "area",
353
+ "bar",
354
+ "column",
355
+ "scatter"
356
+ ].includes(spec.chart) || action === "focus" && [
357
+ "network",
358
+ "sankey",
359
+ "threads",
360
+ "tree",
361
+ "mindmap",
362
+ "parallel"
363
+ ].includes(spec.chart) || action === "pan-zoom" && [
364
+ "network",
365
+ "tree",
366
+ "mindmap",
367
+ "sankey",
368
+ "threads",
369
+ "choropleth",
370
+ "geo-scatter"
371
+ ].includes(spec.chart) || action === "drag" && spec.chart === "network" && spec.layout === "force" || action === "collapse" && ["tree", "mindmap"].includes(spec.chart))) err(errors, "/interaction", `该图型不支持 ${action}`);
372
+ if (Array.isArray(spec.interaction) && spec.interaction.includes("drag") && !spec.interaction.includes("pan-zoom")) err(errors, "/interaction", "drag必须搭配pan-zoom");
373
+ }
374
+ if (spec.annotations !== void 0) {
375
+ const allowedCharts = [
376
+ "line",
377
+ "area",
378
+ "bar",
379
+ "column",
380
+ "scatter",
381
+ "combo",
382
+ "interval",
383
+ "histogram",
384
+ "candlestick"
385
+ ];
386
+ if (!Array.isArray(spec.annotations)) err(errors, "/annotations", "必须是数组");
387
+ else for (const [i, annotation] of spec.annotations.entries()) {
388
+ const path = `/annotations/${i}`;
389
+ if (!obj(annotation) || ![
390
+ "rule",
391
+ "band",
392
+ "note"
393
+ ].includes(annotation.kind)) {
394
+ err(errors, path, "无效注释");
395
+ continue;
396
+ }
397
+ const allowedKeys = annotation.kind === "rule" ? [
398
+ "kind",
399
+ "field",
400
+ "value",
401
+ "label"
402
+ ] : annotation.kind === "band" ? [
403
+ "kind",
404
+ "field",
405
+ "from",
406
+ "to",
407
+ "label"
408
+ ] : [
409
+ "kind",
410
+ "record",
411
+ "field",
412
+ "text"
413
+ ];
414
+ keys(annotation, new Set(allowedKeys), path, errors);
415
+ if (!allowedCharts.includes(spec.chart)) err(errors, path, `${spec.chart}不支持annotations`);
416
+ if (annotation.kind === "rule" && (!finite(annotation.value) || typeof annotation.field !== "string")) err(errors, path, "rule须指定数值field和value");
417
+ if (annotation.kind === "band" && (!finite(annotation.from) || !finite(annotation.to) || annotation.from >= annotation.to || typeof annotation.field !== "string")) err(errors, path, "band须指定field及递增数值边界");
418
+ if (annotation.kind === "note" && (typeof annotation.record !== "string" || typeof annotation.field !== "string" || typeof annotation.text !== "string" || !obj(spec.encode) || !spec.encode.id)) err(errors, path, "note须通过encode.id引用记录并提供field/text");
419
+ if (annotation.label !== void 0 && typeof annotation.label !== "string" || annotation.text !== void 0 && typeof annotation.text !== "string") err(errors, path, "注释label/text须为纯文本");
420
+ const enc = spec.encode || {};
421
+ const scalarFields = Object.entries(enc).filter(([role, value]) => typeof value === "string" && ![
422
+ "category",
423
+ "series",
424
+ "id",
425
+ "panel",
426
+ "label",
427
+ "row",
428
+ "column",
429
+ "date"
430
+ ].includes(role)).map(([, value]) => value);
431
+ if (Array.isArray(enc.value)) scalarFields.push(...enc.value);
432
+ if (Array.isArray(spec.layers)) scalarFields.push(...spec.layers.filter(obj).map((layer) => layer.field));
433
+ if (typeof annotation.field === "string" && !scalarFields.includes(annotation.field)) err(errors, `${path}/field`, "注释字段必须是本图已引用的标量数值角色");
434
+ if (spec.chart === "histogram" && typeof annotation.field === "string" && !["lower", "upper"].some((role) => enc[role] === annotation.field)) err(errors, `${path}/field`, "histogram注释只允许lower或upper");
435
+ if (annotation.kind === "note" && Array.isArray(spec.data)) {
436
+ const idField = enc.id;
437
+ if (!spec.data.some((row) => row?.[idField] === annotation.record)) err(errors, `${path}/record`, "note引用的record id不存在");
438
+ }
439
+ }
440
+ }
441
+ if (spec.emphasis !== void 0) {
442
+ const kind = Object.keys(obj(spec.emphasis) ? spec.emphasis : {});
443
+ const values = kind.length === 1 ? spec.emphasis[kind[0]] : null;
444
+ const supported = EMPHASIS[spec.chart]?.[spec.variant ?? ""] || [];
445
+ const target = `${spec.chart}${spec.variant ? ` 的 ${spec.variant} 变体` : ""}`;
446
+ if (kind.length !== 1 || !ALL_EMPHASIS.includes(kind[0]) || !Array.isArray(values)) err(errors, "/emphasis", "强调须在 rows、fields、series 中选一种身份数组");
447
+ else if (!supported.includes(kind[0])) err(errors, "/emphasis", supported.length ? `${target}只绘制 ${supported.join("、")} 强调` : `${target}不绘制强调`, supported.length ? `改用 ${supported.join(" 或 ")}` : "删去 emphasis;改用 line、area、bar、column、share 或 funnel,或用标题、注释指出重点");
448
+ else {
449
+ const enc = spec.encode || {};
450
+ let actual = [];
451
+ if (kind[0] === "rows" && Array.isArray(spec.data) && enc.id) actual = spec.data.map((row) => row?.[enc.id]);
452
+ if (kind[0] === "fields" && Array.isArray(enc.value)) actual = enc.value;
453
+ if (kind[0] === "series" && Array.isArray(spec.data) && enc.series) actual = spec.data.map((row) => row?.[enc.series]);
454
+ if (kind[0] === "series" && Array.isArray(enc.value)) actual = enc.value;
455
+ if (!actual.length || values.some((value) => !actual.includes(value)) || new Set(values).size !== values.length) err(errors, "/emphasis", `强调引用不存在或重复的${kind[0]}`);
456
+ if (kind[0] === "rows" && !enc.id || kind[0] === "fields" && !Array.isArray(enc.value)) err(errors, "/emphasis", `该图型不支持${kind[0]}强调`);
457
+ }
458
+ }
459
+ return {
460
+ errors,
461
+ data: errors.length ? null : spec
462
+ };
463
+ }
464
+ function checkGeoRows(spec, chart, errors) {
465
+ const { encode, data: { rows } } = spec;
466
+ for (const [i, row] of rows.entries()) {
467
+ const path = `/data/rows/${i}`;
468
+ if (!obj(row)) {
469
+ err(errors, path, "地图记录必须是对象");
470
+ continue;
471
+ }
472
+ for (const role of [...chart.required, ...chart.optional]) {
473
+ const field = encode[role];
474
+ if (field === void 0) continue;
475
+ if (!Object.hasOwn(row, field)) err(errors, `/encode/${role}`, `引用字段不存在:${field}`);
476
+ else if ([
477
+ "longitude",
478
+ "latitude",
479
+ "value"
480
+ ].includes(role)) {
481
+ const value = row[field];
482
+ const fieldPath = ptr([
483
+ "data",
484
+ "rows",
485
+ i,
486
+ field
487
+ ]);
488
+ if (!finite(value) && !(role === "value" && value === null)) err(errors, fieldPath, "数值角色必须是有限数");
489
+ else if (role === "longitude" && Math.abs(value) > 180 || role === "latitude" && Math.abs(value) > 90) err(errors, fieldPath, "经纬度超出合法范围");
490
+ }
491
+ }
492
+ }
493
+ }
494
+ function checkTable(s, c, e) {
495
+ const enc = s.encode, names = [];
496
+ for (const [role, val] of Object.entries(enc)) names.push(...Array.isArray(val) ? val : typeof val === "string" ? [val] : []);
497
+ if (s.chart === "combo" && Array.isArray(s.layers)) for (const l of s.layers) names.push(l.field);
498
+ const fields = Object.assign(Object.create(null), Object.fromEntries(Object.entries(obj(s.fields) ? s.fields : {}).filter(([, field]) => obj(field))));
499
+ for (const name of names) if (!s.data.every((row) => Object.hasOwn(row, name))) err(e, "/encode", `引用字段不存在:${name}`, "请修正 encode 字段名。");
500
+ for (const [i, row] of s.data.entries()) for (const [k, value] of Object.entries(row)) if (!(value === null || typeof value === "string" || typeof value === "boolean" || finite(value) || Array.isArray(value) && ["density", "outliers"].some((role) => s.encode?.[role] === k))) err(e, `/data/${i}/${k}`, "记录值必须是标量或图型明确允许的数组");
501
+ for (const [name, meta] of Object.entries(fields)) if (!s.data.some((row) => Object.hasOwn(row, name))) err(e, `/fields/${name}`, "元数据字段不在数据中");
502
+ validateFieldMeta(s, fields, enc, e);
503
+ for (const [role, name] of Object.entries(enc)) if (typeof name === "string" && (role === "date" || fields[name] && [
504
+ "date",
505
+ "month",
506
+ "datetime"
507
+ ].includes(fields[name].type))) {
508
+ for (const [i, row] of s.data.entries()) if (!safeDate(row[name], role === "date" ? "date" : fields[name].type)) err(e, `/data/${i}/${name}`, "非法日期或时间值");
509
+ }
510
+ const nonNumericRoles = /* @__PURE__ */ new Set([
511
+ "category",
512
+ "series",
513
+ "id",
514
+ "panel",
515
+ "label",
516
+ "row",
517
+ "column",
518
+ "date"
519
+ ]);
520
+ if (s.chart === "launch-fan" && [
521
+ "date",
522
+ "month",
523
+ "datetime"
524
+ ].includes(fields[enc.start]?.type)) nonNumericRoles.add("start");
525
+ if (s.chart === "launch-fan" && ![
526
+ "number",
527
+ "date",
528
+ "month",
529
+ "datetime"
530
+ ].includes(fields[enc.start]?.type)) err(e, `/fields/${enc.start}/type`, "launch-fan.start必须显式声明number或时间类型");
531
+ const values = [.../* @__PURE__ */ new Set([...Object.entries(enc).filter(([role]) => !nonNumericRoles.has(role)).flatMap(([, name]) => Array.isArray(name) ? name : typeof name === "string" ? [name] : []), ...s.chart === "combo" && Array.isArray(s.layers) ? s.layers.map((layer) => layer.field) : []])];
532
+ for (const [i, row] of s.data.entries()) for (const name of values) if (Object.hasOwn(row, name)) {
533
+ const v = row[name];
534
+ if (v === null && ![
535
+ "line",
536
+ "area",
537
+ "sparkline",
538
+ "small-multiples",
539
+ "bump",
540
+ "combo"
541
+ ].includes(s.chart)) err(e, `/data/${i}/${name}`, "该图型不允许数值缺失");
542
+ if (v !== null && !finite(v) && !(Array.isArray(v) && ["density", "outliers"].some((r) => enc[r] === name))) err(e, `/data/${i}/${name}`, "数值角色必须是有限JSON number或允许的数组");
543
+ const type = fields[name]?.type;
544
+ if (type && [
545
+ "date",
546
+ "month",
547
+ "datetime"
548
+ ].includes(type) && !safeDate(v, type)) err(e, `/data/${i}/${name}`, "非法日期或时间值");
549
+ if (fields[name]?.scale === "log" && finite(v) && v <= 0) err(e, `/data/${i}/${name}`, "log数值必须大于0");
550
+ }
551
+ for (const role of ["id"]) if (typeof enc[role] === "string") unique(s.data.map((r) => r[enc[role]]), `/encode/${role}`, e, true);
552
+ if (c.encodeForms.length && !c.encodeForms.some((form) => form.length === Object.keys(enc).filter((k) => k === "value" || k === "panel").length && form.every((k) => Object.hasOwn(enc, k)))) err(e, "/encode", "small-multiples须使用value[]宽表或value+panel长表");
553
+ if (s.chart === "small-multiples" && (enc.panel ? Array.isArray(enc.value) : !Array.isArray(enc.value))) err(e, "/encode", "宽表value须为字段数组;长表value须为单个字段并配panel");
554
+ if (Array.isArray(enc.value) && enc.value.length > 6) err(e, "/encode/value", "最多支持6个度量系列");
555
+ if (["radar", "parallel"].includes(s.chart) && (enc.dimensions?.length < 3 || enc.dimensions?.length > 6)) err(e, "/encode/dimensions", "radar至少3维,parallel为3至6维");
556
+ if (s.chart === "radar") {
557
+ for (const name of enc.dimensions || []) if (!fields[name]?.domain) err(e, `/fields/${name}/domain`, `${s.chart}的每个维度都必须显式声明domain`);
558
+ }
559
+ if (enc.category && !["strip", "scatter"].includes(s.chart)) {
560
+ const seen = /* @__PURE__ */ new Set();
561
+ for (const row of s.data) {
562
+ const key = [row[enc.category], enc.series ? row[enc.series] : s.chart === "small-multiples" ? row[enc.panel] : null];
563
+ const k = JSON.stringify(key);
564
+ if (seen.has(k)) err(e, "/data", "重复的category/series组合");
565
+ seen.add(k);
566
+ }
567
+ }
568
+ if ([
569
+ "interval",
570
+ "bullet",
571
+ "dumbbell",
572
+ "slope",
573
+ "candlestick"
574
+ ].includes(s.chart)) for (const [i, r] of s.data.entries()) {
575
+ const value = (role) => finite(r[enc[role]]) ? r[enc[role]] : NaN;
576
+ if (s.chart === "interval" && !(value("low") <= value("high") && (enc.value === void 0 || value("value") >= value("low") && value("value") <= value("high")))) err(e, `/data/${i}`, "interval须满足low≤value≤high");
577
+ if (s.chart === "candlestick" && !(value("low") <= Math.min(value("open"), value("close")) && Math.max(value("open"), value("close")) <= value("high"))) err(e, `/data/${i}`, "candlestick须满足low≤open/close≤high");
578
+ if (s.chart === "bullet" && [enc.actual, enc.target].some((field) => finite(r[field]) && r[field] < 0)) err(e, `/data/${i}`, "bullet数值须非负");
579
+ }
580
+ if (s.chart === "histogram") {
581
+ let previous = null;
582
+ for (const [i, row] of s.data.entries()) {
583
+ const lo = row[enc.lower], hi = row[enc.upper], count = row[enc.count];
584
+ if (!(finite(lo) && finite(hi) && lo < hi && (previous === null || lo === previous) && finite(count) && count >= 0)) err(e, `/data/${i}`, "histogram箱须连续精确接壤、递增且count非负");
585
+ previous = hi;
586
+ }
587
+ if (s.variant === "rungs" && s.data.length > 1 && s.data.every((row) => finite(row[enc.lower]) && finite(row[enc.upper]))) {
588
+ const width = s.data[0][enc.upper] - s.data[0][enc.lower];
589
+ if (s.data.some((row) => Math.abs(row[enc.upper] - row[enc.lower] - width) > Math.max(1, Math.abs(width)) * 1e-9)) err(e, "/data", "histogram rungs要求等宽分箱;不等宽时请使用默认实心直方图");
590
+ }
591
+ }
592
+ if (s.chart === "calendar") {
593
+ const dates = /* @__PURE__ */ new Set();
594
+ for (const [i, row] of s.data.entries()) {
595
+ const date = row[enc.date];
596
+ if (typeof date === "string" && date.slice(0, 4) !== s.period) err(e, `/data/${i}/${enc.date}`, "calendar日期须属于period指定年份");
597
+ if (dates.has(date)) err(e, `/data/${i}/${enc.date}`, "calendar日期重复");
598
+ dates.add(date);
599
+ }
600
+ }
601
+ if (["line", "area"].includes(s.chart) && (enc.lower || enc.upper)) {
602
+ if (!enc.lower || !enc.upper || Array.isArray(enc.value) || enc.series || s.stack) err(e, "/encode", "区间lower/upper仅支持非堆叠单度量");
603
+ if (enc.lower && enc.upper) for (const [i, row] of s.data.entries()) {
604
+ const lo = row[enc.lower], hi = row[enc.upper], value = row[enc.value];
605
+ if (!(lo === null && hi === null && value === null || finite(lo) && finite(hi) && finite(value) && lo <= value && value <= hi)) err(e, `/data/${i}`, "lower/value/upper须同时缺失或满足lower≤value≤upper");
606
+ }
607
+ }
608
+ if (s.chart === "heatmap" || s.chart === "bubble-matrix") {
609
+ const cells = /* @__PURE__ */ new Set();
610
+ for (const [i, row] of s.data.entries()) {
611
+ const cell = JSON.stringify([row[enc.row], row[enc.column]]);
612
+ if (cells.has(cell)) err(e, `/data/${i}`, "矩阵单元格重复");
613
+ cells.add(cell);
614
+ }
615
+ }
616
+ if (["boxplot", "violin"].includes(s.chart)) checkStats(s, e);
617
+ checkTableLimits(s, e);
618
+ const valueFields = Array.isArray(enc.value) ? enc.value : typeof enc.value === "string" ? [enc.value] : [];
619
+ if (s.stack === "percent" && valueFields.some((f) => s.data.some((r) => finite(r[f]) && r[f] < 0))) err(e, "/data", "percent stack不允许负值");
620
+ if ([
621
+ "share",
622
+ "pie",
623
+ "donut",
624
+ "radial-share",
625
+ "rose",
626
+ "funnel",
627
+ "waffle",
628
+ "tally",
629
+ "bullet",
630
+ "stream"
631
+ ].includes(s.chart) || [
632
+ "bar",
633
+ "column",
634
+ "dumbbell"
635
+ ].includes(s.chart) && ["rungs", "pictorial"].includes(s.variant)) {
636
+ for (const f of valueFields) if (s.data.some((r) => finite(r[f]) && r[f] < 0)) err(e, "/data", "该图型或变体数值不可为负");
637
+ }
638
+ if (s.chart === "bump") {
639
+ for (const [i, row] of s.data.entries()) if (row[enc.rank] !== null && (!Number.isInteger(row[enc.rank]) || row[enc.rank] < 1)) err(e, `/data/${i}/${enc.rank}`, "rank必须是正整数或null");
640
+ }
641
+ if (s.chart === "launch-fan" && s.data.some((row) => finite(row[enc.value]) && row[enc.value] < 0)) err(e, "/data", "launch-fan当前量必须非负");
642
+ if (s.chart === "bubble-matrix" && s.data.some((row) => finite(row[enc.value]) && row[enc.value] < 0)) err(e, "/data", "气泡矩阵面积值必须非负");
643
+ if (s.chart === "radial-share") for (const role of ["value", "intensity"]) {
644
+ const name = enc[role], meta = fields[name];
645
+ if (!obj(meta) || meta.unit === void 0 && meta.format !== "percent") err(e, `/fields/${name}`, "份额和强度必须分别声明单位或比例格式");
646
+ if (s.data.some((row) => finite(row[name]) && row[name] < 0) || !s.data.some((row) => finite(row[name]) && row[name] > 0)) err(e, `/encode/${role}`, "份额和强度须非负且各至少一个正值");
647
+ if (meta?.domain && meta.domain[0] !== 0) err(e, `/fields/${name}/domain`, "强度/份额范围必须从0开始");
648
+ }
649
+ if (s.chart === "heatmap" && s.variant === "arc") {
650
+ const meta = fields[enc.value];
651
+ if (meta?.format !== "percent" && !(Array.isArray(meta?.domain) && meta.domain[0] === 0 && meta.domain[1] > 0)) err(e, `/fields/${enc.value}`, "arc须使用比例格式或从0开始的数值范围");
652
+ if (s.data.some((row) => finite(row[enc.value]) && (row[enc.value] < 0 || meta?.format === "percent" && row[enc.value] > 1))) err(e, "/data", "arc数值必须位于0至整弧范围");
653
+ }
654
+ if (s.chart === "combo" && Array.isArray(s.layers)) {
655
+ if (s.layers.length > 6 || !s.layers.some((layer) => layer.axis === "left")) err(e, "/layers", "combo最多6层且必须有left轴");
656
+ unique(s.layers.map((layer) => layer.field), "/layers/field", e, true);
657
+ for (const [i, layer] of s.layers.entries()) keys(layer, /* @__PURE__ */ new Set([
658
+ "mark",
659
+ "field",
660
+ "axis"
661
+ ]), `/layers/${i}`, e);
662
+ }
663
+ if (s.chart === "dumbbell" && s.variant === "rungs") {
664
+ for (const role of ["before", "after"]) if (s.data.some((r) => finite(r[enc[role]]) && r[enc[role]] < 0)) err(e, "/data", `rungs的${role}须非负`);
665
+ }
666
+ if (s.chart === "tally") {
667
+ if (fields[enc.value]?.format !== "percent") err(e, `/fields/${enc.value}/format`, "tally数值字段必须format=percent");
668
+ if (s.data.some((r) => !finite(r[enc.value]) || r[enc.value] < 0 || r[enc.value] > 1)) err(e, "/data", "tally每项须在0至1之间");
669
+ }
670
+ if (s.chart === "funnel") {
671
+ let previous = Infinity;
672
+ for (const [i, row] of s.data.entries()) {
673
+ const value = row[enc.value];
674
+ if (!finite(value) || value < 0 || value > previous || i === 0 && value <= 0) err(e, `/data/${i}/${enc.value}`, "funnel须非负递减且首步大于0");
675
+ if (finite(value)) previous = value;
676
+ }
677
+ }
678
+ if (s.chart === "gauge") {
679
+ if (s.data.length !== 1) err(e, "/data", "gauge必须恰有一条记录");
680
+ else if (Array.isArray(s.range) && s.range.length === 2 && s.range.every(finite)) for (const role of ["value", "target"]) {
681
+ const value = s.data[0][enc[role]];
682
+ if (enc[role] && finite(value) && (value < s.range[0] || value > s.range[1])) err(e, `/data/0/${enc[role]}`, "gauge值与target必须位于range内");
683
+ }
684
+ }
685
+ if (["scatter", "strip"].includes(s.chart) && enc.size && s.data.some((r) => finite(r[enc.size]) && r[enc.size] < 0)) err(e, "/data", "size必须非负");
686
+ if (s.chart === "radar" && valueFields.length && s.data.some((r) => finite(r[enc.value]) && r[enc.value] < 0)) err(e, "/data", "radar维度值须非负");
687
+ }
688
+ function validateFieldMeta(s, fields, enc, e) {
689
+ const numeric = /* @__PURE__ */ new Set([...Object.entries(enc).flatMap(([role, value]) => role === "dimensions" && Array.isArray(value) ? value : typeof value === "string" && ![
690
+ "category",
691
+ "series",
692
+ "id",
693
+ "panel",
694
+ "label",
695
+ "row",
696
+ "column",
697
+ "date"
698
+ ].includes(role) ? [value] : Array.isArray(value) ? value : []), ...s.chart === "combo" && Array.isArray(s.layers) ? s.layers.map((layer) => layer.field) : []]);
699
+ const categorical = new Set([
700
+ "category",
701
+ "series",
702
+ "panel",
703
+ "label",
704
+ "row",
705
+ "column",
706
+ "date"
707
+ ].map((role) => enc[role]).filter((x) => typeof x === "string"));
708
+ const domainCharts = /* @__PURE__ */ new Set([
709
+ "line",
710
+ "area",
711
+ "bar",
712
+ "column",
713
+ "sparkline",
714
+ "small-multiples",
715
+ "combo",
716
+ "split-compare",
717
+ "scatter",
718
+ "strip",
719
+ "interval",
720
+ "bullet",
721
+ "dumbbell",
722
+ "slope",
723
+ "histogram",
724
+ "boxplot",
725
+ "violin",
726
+ "candlestick",
727
+ "parallel",
728
+ "radar",
729
+ "heatmap",
730
+ "bubble-matrix",
731
+ "radial-share",
732
+ "bump"
733
+ ]);
734
+ for (const [name, f] of Object.entries(fields)) {
735
+ if (f.domain !== void 0) {
736
+ if (!domainCharts.has(s.chart)) err(e, `/fields/${name}/domain`, "该图型不支持domain");
737
+ if (s.sort && name === enc.category) err(e, "/sort", "分类domain已确定顺序,不能同时sort");
738
+ if (Array.isArray(f.domain) && f.domain.every(finite) && [
739
+ "bar",
740
+ "column",
741
+ "area",
742
+ "bullet",
743
+ "split-compare"
744
+ ].includes(s.chart) && f.domain[0] > 0) err(e, `/fields/${name}/domain`, "面积和柱条度量范围必须包含0");
745
+ if (Array.isArray(f.domain) && f.domain.every(finite) && Array.isArray(s.annotations)) for (const a of s.annotations) {
746
+ if (!obj(a) || a.field !== name || !["rule", "band"].includes(a.kind)) continue;
747
+ if ((a.kind === "rule" ? [a.value] : [a.from, a.to]).some((v) => finite(v) && (v < f.domain[0] || v > f.domain[1]))) err(e, `/fields/${name}/domain`, "domain不得裁剪参考线或参考区间");
748
+ }
749
+ if (Array.isArray(f.domain) && f.domain.length === 2 && f.domain.every(finite)) {
750
+ if (!numeric.has(name)) err(e, `/fields/${name}/domain`, "数值domain只能用于数值角色");
751
+ for (const row of s.data) if (finite(row[name]) && (row[name] < f.domain[0] || row[name] > f.domain[1])) err(e, `/fields/${name}/domain`, "domain不得裁剪数据");
752
+ } else {
753
+ if (!categorical.has(name)) err(e, `/fields/${name}/domain`, "分类domain只能用于分类角色");
754
+ if (Array.isArray(f.domain) && s.data.some((row) => !f.domain.includes(row[name]))) err(e, `/fields/${name}/domain`, "domain必须包含所有实际分类");
755
+ }
756
+ }
757
+ if (f.scale !== void 0) {
758
+ if (!numeric.has(name) || !domainCharts.has(s.chart)) err(e, `/fields/${name}/scale`, "scale仅允许适用图型的数值角色");
759
+ if (f.scale === "log" && ![
760
+ "line",
761
+ "scatter",
762
+ "parallel"
763
+ ].includes(s.chart)) err(e, `/fields/${name}/scale`, "log仅支持line/scatter/parallel");
764
+ if (f.scale === "log" && (s.data.some((row) => finite(row[name]) && row[name] <= 0) || Array.isArray(f.domain) && f.domain.some((v) => finite(v) && v <= 0))) err(e, `/fields/${name}/scale`, "log数据与domain必须大于0");
765
+ if (f.scale === "log" && s.stack) err(e, `/fields/${name}/scale`, "log坐标不支持堆叠");
766
+ }
767
+ if (f.type === "number" && !numeric.has(name) || f.type === "category" && !categorical.has(name)) err(e, `/fields/${name}/type`, "字段type与编码角色不相符");
768
+ }
769
+ const grouped = [...Array.isArray(enc.value) ? enc.value : typeof enc.value === "string" ? [enc.value] : []];
770
+ if (s.chart === "bullet") grouped.push(enc.actual, enc.target);
771
+ if (["dumbbell", "slope"].includes(s.chart)) grouped.push(enc.before, enc.after);
772
+ if (s.chart === "interval") grouped.push(enc.low, enc.high, enc.value);
773
+ if (s.chart === "candlestick") grouped.push(enc.open, enc.close, enc.low, enc.high);
774
+ const rootUnit = typeof s.unit === "string" ? s.unit : "";
775
+ const sig = (name) => {
776
+ const { unit, format } = fields[name] || {};
777
+ return JSON.stringify([typeof unit === "string" ? unit : rootUnit, format === "percent" ? "percent" : "number"]);
778
+ };
779
+ if (grouped.filter(Boolean).length > 1 && new Set(grouped.filter(Boolean).map(sig)).size > 1) err(e, "/fields", "同一坐标轴的可比较度量必须单位和format一致");
780
+ if (s.chart === "combo" && Array.isArray(s.layers)) for (const axis of ["left", "right"]) {
781
+ const names = s.layers.filter((l) => l.axis === axis).map((l) => l.field);
782
+ if (new Set(names.map(sig)).size > 1) err(e, "/layers", `${axis}轴的字段必须单位和format一致`);
783
+ }
784
+ }
785
+ function checkTableLimits(s, e) {
786
+ const enc = s.encode, rows = s.data, uniq = (field) => new Set(rows.map((r) => r[field])).size;
787
+ const categories = enc.category ? uniq(enc.category) : 0;
788
+ const limits = {
789
+ funnel: 6,
790
+ share: 6,
791
+ pie: 6,
792
+ donut: 6,
793
+ "radial-share": 6,
794
+ rose: 6,
795
+ waffle: 6,
796
+ tally: 6,
797
+ bullet: 12,
798
+ dumbbell: 12,
799
+ interval: 12,
800
+ boxplot: 12,
801
+ violin: 12,
802
+ slope: 8,
803
+ waterfall: 16,
804
+ histogram: 40,
805
+ scatter: 1e3,
806
+ strip: 1e3,
807
+ calendar: 366,
808
+ "candlestick": 120,
809
+ "launch-fan": 24
810
+ };
811
+ if (limits[s.chart] !== void 0 && rows.length > limits[s.chart]) err(e, "/data", `${s.chart}最多${limits[s.chart]}条记录`);
812
+ if (["bar", "column"].includes(s.chart)) {
813
+ if (categories > 60 || s.chart === "bar" && categories > 24) err(e, "/data", `${s.chart}类别数超限`);
814
+ if (categories > 24 && (s.chart !== "column" || Array.isArray(enc.value) && enc.value.length !== 1 || enc.series || !["solid", void 0].includes(s.variant))) err(e, "/data", "25至60类仅支持单系列solid通栏column");
815
+ }
816
+ if ([
817
+ "line",
818
+ "area",
819
+ "sparkline",
820
+ "small-multiples",
821
+ "stream",
822
+ "split-compare",
823
+ "combo"
824
+ ].includes(s.chart) && categories > 120) err(e, "/data", "时点最多120");
825
+ if (s.chart === "small-multiples") {
826
+ if ((enc.panel ? uniq(enc.panel) : Array.isArray(enc.value) ? enc.value.length : 0) > 6) err(e, "/data", "small-multiples最多6面板");
827
+ if (enc.panel) {
828
+ const counts = /* @__PURE__ */ new Map();
829
+ for (const r of rows) counts.set(r[enc.panel], (counts.get(r[enc.panel]) || 0) + 1);
830
+ for (const n of counts.values()) if (n > 120) err(e, "/data", "每个small-multiples面板最多120时点");
831
+ }
832
+ }
833
+ if (["heatmap", "bubble-matrix"].includes(s.chart) && (uniq(enc.row) > 24 || uniq(enc.column) > 24)) err(e, "/data", "矩阵每轴最多24类");
834
+ if (s.chart === "radar" || s.chart === "parallel") {
835
+ if (rows.length > 24) err(e, "/data", "多维图最多24实体");
836
+ }
837
+ if (s.chart === "bump" && (uniq(enc.series) > 12 || uniq(enc.category) > 24)) err(e, "/data", "bump最多12实体、24时点");
838
+ }
839
+ function unique(arr, path, e, nonempty = false) {
840
+ const set = /* @__PURE__ */ new Set();
841
+ for (const x of arr) {
842
+ if (nonempty && typeof x !== "string" || x === "" || x === null || x === void 0) err(e, path, "身份必须是非空字符串");
843
+ else if (set.has(x)) err(e, path, `重复身份:${x}`);
844
+ set.add(x);
845
+ }
846
+ }
847
+ function checkStats(s, e) {
848
+ const en = s.encode;
849
+ for (const [i, row] of s.data.entries()) if (s.chart === "boxplot") {
850
+ const values = [
851
+ "low",
852
+ "q1",
853
+ "median",
854
+ "q3",
855
+ "high"
856
+ ].map((key) => row[en[key]]);
857
+ if (values.every(finite) && !(values[0] <= values[1] && values[1] <= values[2] && values[2] <= values[3] && values[3] <= values[4])) err(e, `/data/${i}`, "箱线统计值必须low≤q1≤median≤q3≤high");
858
+ if (en.outliers && Array.isArray(row[en.outliers])) {
859
+ if (row[en.outliers].length > 200) err(e, `/data/${i}/${en.outliers}`, "每组最多200个异常点");
860
+ if (values.every(finite) && row[en.outliers].some((value) => !finite(value) || value >= values[0] && value <= values[4])) err(e, `/data/${i}/${en.outliers}`, "异常值必须严格位于须线之外");
861
+ }
862
+ } else {
863
+ const density = row[en.density], median = row[en.median];
864
+ if (!Array.isArray(density) || density.length < 2 || density.length > 120 || density.some((point) => !Array.isArray(point) || point.length !== 2 || !point.every(finite) || point[1] < 0) || density.some((point, index) => index && point[0] <= density[index - 1][0]) || !finite(median) || density.length && !(median >= density[0][0] && median <= density.at(-1)[0])) {
865
+ err(e, `/data/${i}`, "violin须提供2至120个递增的有限密度采样与范围内中位数");
866
+ continue;
867
+ }
868
+ let integral = 0;
869
+ for (let j = 1; j < density.length; j++) integral += (density[j][0] - density[j - 1][0]) * (density[j][1] + density[j - 1][1]) / 2;
870
+ if (!(integral > 0)) err(e, `/data/${i}/${en.density}`, "violin密度积分必须大于0");
871
+ }
872
+ }
873
+ function checkTree(rootNode, chart, e, budget = {}) {
874
+ const maxDepth = budget.depth ?? 5, maxNodes = budget.nodes ?? 80;
875
+ const ids = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set();
876
+ let count = 0;
877
+ const walk = (node, path, depth) => {
878
+ if (!obj(node)) {
879
+ err(e, path, "树节点必须是对象");
880
+ return 0;
881
+ }
882
+ if (seen.has(node)) {
883
+ err(e, path, "树不允许共享节点或环");
884
+ return finite(node.value) ? node.value : 0;
885
+ }
886
+ seen.add(node);
887
+ if (depth > maxDepth) {
888
+ err(e, path, "超过树深度上限");
889
+ return finite(node.value) ? node.value : 0;
890
+ }
891
+ count++;
892
+ if (typeof node.label !== "string" || !node.label) err(e, `${path}/label`, "节点label必填");
893
+ for (const key of Object.keys(node)) if (![
894
+ "label",
895
+ "children",
896
+ "value",
897
+ "id",
898
+ "icon",
899
+ "note",
900
+ ...["mindmap", "tree"].includes(chart) ? ["status", "shape"] : []
901
+ ].includes(key)) err(e, `${path}/${key}`, "未知节点字段");
902
+ if (node.shape !== void 0 && ["mindmap", "tree"].includes(chart) && !NODE_SHAPES.includes(node.shape)) err(e, `${path}/shape`, "未知节点形状");
903
+ if (node.status !== void 0 && ["mindmap", "tree"].includes(chart) && ![
904
+ "new",
905
+ "info",
906
+ "ok",
907
+ "warn",
908
+ "danger",
909
+ "ext"
910
+ ].includes(node.status)) err(e, `${path}/status`, "无效节点状态");
911
+ if (node.id !== void 0) {
912
+ if (typeof node.id !== "string" || !node.id || ids.has(node.id)) err(e, `${path}/id`, "节点ID须唯一非空");
913
+ ids.add(node.id);
914
+ }
915
+ if (node.value !== void 0 && (!finite(node.value) || node.value < 0)) err(e, `${path}/value`, "节点权重须为非负有限数");
916
+ if (node.children !== void 0 && !Array.isArray(node.children)) err(e, `${path}/children`, "children须为数组");
917
+ const children = Array.isArray(node.children) ? node.children : [];
918
+ const sum = children.reduce((total, child, i) => total + walk(child, `${path}/children/${i}`, depth + 1), 0);
919
+ if (children.length && node.value !== void 0 && finite(node.value) && Math.abs(node.value - sum) > 1e-9 * Math.max(1, node.value, sum)) err(e, `${path}/value`, "父节点value必须等于子树叶子合计");
920
+ if (["treemap", "sunburst"].includes(chart) && !children.length && (!finite(node.value) || node.value < 0)) err(e, path, "层级面积图叶子必须有非负value");
921
+ return finite(node.value) ? node.value : sum;
922
+ };
923
+ walk(rootNode, "/data", 1);
924
+ if (count > maxNodes) err(e, "/data", `超过${maxNodes}节点上限`);
925
+ }
926
+ function checkNetwork(d, chart, e, tolerant = false) {
927
+ const rawNodes = d.nodes || [], rawEdges = d.edges || [];
928
+ rawNodes.forEach((n, i) => {
929
+ if (!obj(n)) err(e, `/data/nodes/${i}`, "节点必须是对象");
930
+ });
931
+ rawEdges.forEach((x, i) => {
932
+ if (!obj(x)) err(e, `/data/edges/${i}`, "边必须是对象");
933
+ });
934
+ const nodes = rawNodes.filter(obj), edges = rawEdges.filter(obj);
935
+ const ids = new Set(nodes.map((n) => n.id));
936
+ unique(nodes.map((n) => n?.id), "/data/nodes/id", e, true);
937
+ for (const [i, n] of rawNodes.entries()) {
938
+ if (!obj(n)) continue;
939
+ for (const k of Object.keys(n)) if (![
940
+ "id",
941
+ "label",
942
+ "group",
943
+ "value",
944
+ "stage",
945
+ "icon",
946
+ "note"
947
+ ].includes(k)) err(e, `/data/nodes/${i}/${k}`, "未知节点字段");
948
+ if (n.label !== void 0 && typeof n.label !== "string") err(e, `/data/nodes/${i}/label`, "label须为字符串");
949
+ if (n.value !== void 0 && !finite(n.value)) err(e, `/data/nodes/${i}/value`, "value须为有限数");
950
+ if (chart === "sankey" && n.value !== void 0) err(e, `/data/nodes/${i}/value`, "sankey禁用node.value");
951
+ if (n.stage !== void 0 && (!Number.isInteger(n.stage) || n.stage < 0)) err(e, `/data/nodes/${i}/stage`, "stage须为非负整数");
952
+ }
953
+ const edgeIds = [];
954
+ for (const [i, x] of rawEdges.entries()) {
955
+ if (!obj(x)) continue;
956
+ for (const k of Object.keys(x)) if (![
957
+ "source",
958
+ "target",
959
+ "id",
960
+ "label",
961
+ "value"
962
+ ].includes(k)) err(e, `/data/edges/${i}/${k}`, "未知边字段");
963
+ if (!ids.has(x.source) || !ids.has(x.target)) err(e, `/data/edges/${i}`, "边必须引用已声明节点");
964
+ if (x.label !== void 0 && typeof x.label !== "string") err(e, `/data/edges/${i}/label`, "label须为字符串");
965
+ if (x.id !== void 0) edgeIds.push(x.id);
966
+ if (chart === "sankey" && (!finite(x.value) || x.value <= 0 || x.source === x.target)) err(e, `/data/edges/${i}/value`, "Sankey边值须为正且不可自环");
967
+ else if (chart === "network" && x.value !== void 0 && !finite(x.value)) err(e, `/data/edges/${i}/value`, "边value须为有限数");
968
+ }
969
+ unique(edgeIds, "/data/edges/id", e, true);
970
+ const pairCounts = /* @__PURE__ */ new Map();
971
+ for (const x of edges) {
972
+ const key = JSON.stringify([x.source, x.target]);
973
+ pairCounts.set(key, (pairCounts.get(key) || 0) + 1);
974
+ }
975
+ for (const [i, x] of rawEdges.entries()) if (obj(x) && pairCounts.get(JSON.stringify([x.source, x.target])) > 1 && x.id === void 0) err(e, `/data/edges/${i}/id`, "平行边必须提供唯一id");
976
+ if (chart === "sankey") {
977
+ const stage = new Map(nodes.map((n) => [n.id, n.stage]));
978
+ const specified = nodes.filter((n) => n.stage !== void 0).length;
979
+ if (specified && specified !== nodes.length) err(e, "/data/nodes", "stage不可部分指定");
980
+ const ins = /* @__PURE__ */ new Map(), outs = /* @__PURE__ */ new Map(), indegree = new Map(nodes.map((n) => [n.id, 0])), next = new Map(nodes.map((n) => [n.id, []]));
981
+ for (const x of edges) {
982
+ if (specified && !(Number.isInteger(stage.get(x.source)) && Number.isInteger(stage.get(x.target)) && stage.get(x.target) > stage.get(x.source))) err(e, "/data/edges", "Sankey边必须指向更高stage");
983
+ if (finite(x.value)) {
984
+ ins.set(x.target, (ins.get(x.target) || 0) + x.value);
985
+ outs.set(x.source, (outs.get(x.source) || 0) + x.value);
986
+ }
987
+ if (ids.has(x.source) && ids.has(x.target)) {
988
+ next.get(x.source).push(x.target);
989
+ indegree.set(x.target, (indegree.get(x.target) || 0) + 1);
990
+ }
991
+ }
992
+ const ready = [...indegree].filter(([, n]) => n === 0).map(([id]) => id);
993
+ let visited = 0;
994
+ while (ready.length) {
995
+ const id = ready.pop();
996
+ visited++;
997
+ for (const to of next.get(id)) {
998
+ indegree.set(to, indegree.get(to) - 1);
999
+ if (indegree.get(to) === 0) ready.push(to);
1000
+ }
1001
+ }
1002
+ if (visited !== nodes.length) err(e, "/data/edges", "Sankey必须是DAG,不允许环");
1003
+ for (const n of nodes) {
1004
+ const a = ins.get(n.id) || 0, b = outs.get(n.id) || 0;
1005
+ if (!tolerant && a && b && Math.abs(a - b) > 1e-9 * Math.max(1, a, b)) err(e, "/data/nodes", "Sankey中间节点流量不守恒");
1006
+ }
1007
+ }
1008
+ }
1009
+ function checkPaths(d, e) {
1010
+ const stages = d.stages.filter(obj), nodes = d.nodes.filter(obj), paths = d.paths.filter(obj);
1011
+ for (const [i, x] of d.stages.entries()) if (!obj(x)) err(e, `/data/stages/${i}`, "stage必须是对象");
1012
+ for (const [i, x] of d.nodes.entries()) if (!obj(x)) err(e, `/data/nodes/${i}`, "path node必须是对象");
1013
+ for (const [i, x] of d.paths.entries()) if (!obj(x)) err(e, `/data/paths/${i}`, "path必须是对象");
1014
+ unique(stages.map((x) => x.id), "/data/stages/id", e, true);
1015
+ unique(nodes.map((x) => x.id), "/data/nodes/id", e, true);
1016
+ unique(paths.map((x) => x.id), "/data/paths/id", e, true);
1017
+ stages.forEach((x, i) => {
1018
+ for (const k of Object.keys(x)) if (!["id", "label"].includes(k)) err(e, `/data/stages/${i}/${k}`, "未知stage字段");
1019
+ if (typeof x.label !== "string") err(e, `/data/stages/${i}/label`, "label必填");
1020
+ });
1021
+ const stage = new Map(stages.map((x, i) => [x.id, i])), nodeMap = new Map(nodes.map((x) => [x.id, x]));
1022
+ nodes.forEach((n, i) => {
1023
+ for (const k of Object.keys(n)) if (![
1024
+ "id",
1025
+ "label",
1026
+ "stage"
1027
+ ].includes(k)) err(e, `/data/nodes/${i}/${k}`, "未知路径节点字段");
1028
+ if (!stage.has(n.stage)) err(e, `/data/nodes/${i}/stage`, "节点stage不存在");
1029
+ if (typeof n.label !== "string") err(e, `/data/nodes/${i}/label`, "label必填");
1030
+ });
1031
+ for (const [i, p] of d.paths.entries()) if (obj(p)) {
1032
+ for (const k of Object.keys(p)) if (![
1033
+ "id",
1034
+ "nodes",
1035
+ "value",
1036
+ "note"
1037
+ ].includes(k)) err(e, `/data/paths/${i}/${k}`, "未知path字段");
1038
+ if (p.note !== void 0 && typeof p.note !== "string") err(e, `/data/paths/${i}/note`, "note须为字符串");
1039
+ if (!Array.isArray(p.nodes) || p.nodes.length < 2) {
1040
+ err(e, `/data/paths/${i}/nodes`, "路径至少包含两个节点");
1041
+ continue;
1042
+ }
1043
+ let prev = -1;
1044
+ for (const id of p.nodes) {
1045
+ const n = nodeMap.get(id), at = stage.get(n?.stage);
1046
+ if (!n || at === void 0 || at <= prev) {
1047
+ err(e, `/data/paths/${i}/nodes`, "路径节点须按阶段严格前进");
1048
+ continue;
1049
+ }
1050
+ prev = at;
1051
+ }
1052
+ if (p.value !== void 0 && (!finite(p.value) || p.value <= 0)) err(e, `/data/paths/${i}/value`, "路径权重须为正有限数");
1053
+ }
1054
+ }
1055
+ function location(text, offset) {
1056
+ const before = text.slice(0, offset);
1057
+ return {
1058
+ offset,
1059
+ line: before.split("\n").length,
1060
+ column: offset - before.lastIndexOf("\n")
1061
+ };
1062
+ }
1063
+ function checkDuplicateKeys(text, errors) {
1064
+ const stack = [];
1065
+ for (const match of text.matchAll(/"(?:[^"\\]|\\.)*"|[{}\[\]:,]|[^\s{}\[\]:,"]+/g)) {
1066
+ const [token] = match;
1067
+ const frame = stack.at(-1);
1068
+ if (token === "}" || token === "]") stack.pop();
1069
+ else if (token === ",") {
1070
+ if (frame.keys) frame.key = void 0;
1071
+ } else if (token !== ":") {
1072
+ if (frame?.keys && frame.key === void 0) {
1073
+ const key = JSON.parse(token);
1074
+ if (frame.keys.has(key)) err(errors, ptr([...stack.slice(1).map((entry) => entry.at), key]), `重复 JSON 属性:${key}`, "删除重复属性并保留唯一值。", "BAD_KCHART", location(text, match.index));
1075
+ frame.keys.add(key);
1076
+ frame.key = key;
1077
+ } else {
1078
+ const at = frame?.keys ? frame.key : frame ? frame.next++ : void 0;
1079
+ if (token === "{") stack.push({
1080
+ at,
1081
+ keys: /* @__PURE__ */ new Set()
1082
+ });
1083
+ if (token === "[") stack.push({
1084
+ at,
1085
+ next: 0
1086
+ });
1087
+ }
1088
+ }
1089
+ }
1090
+ }
1091
+ function parse(text) {
1092
+ const errors = [];
1093
+ if (typeof text !== "string") {
1094
+ err(errors, "", "输入必须是 JSON 文本", "提供合法的 JSON 字符串。");
1095
+ return {
1096
+ errors,
1097
+ data: null
1098
+ };
1099
+ }
1100
+ let spec;
1101
+ try {
1102
+ spec = JSON.parse(text);
1103
+ } catch (cause) {
1104
+ if (!(cause instanceof SyntaxError)) throw cause;
1105
+ const offset = Number(/position (\d+)/.exec(cause.message)?.[1] ?? 0);
1106
+ err(errors, "", `JSON 语法错误:${cause.message}`, "修正 JSON 语法。", "BAD_KCHART", location(text, offset));
1107
+ return {
1108
+ errors,
1109
+ data: null
1110
+ };
1111
+ }
1112
+ checkDuplicateKeys(text, errors);
1113
+ return errors.length ? {
1114
+ errors,
1115
+ data: null
1116
+ } : validate(spec);
1117
+ }
1118
+ function schema(chart) {
1119
+ if (chart !== void 0 && (typeof chart !== "string" || !catalog[chart])) throw new TypeError("未知图型,请从图型目录中选择");
1120
+ const properties = {
1121
+ chart: {
1122
+ type: "string",
1123
+ enum: chart === void 0 ? Object.keys(catalog) : [chart]
1124
+ },
1125
+ title: { type: "string" },
1126
+ subtitle: { type: "string" },
1127
+ source: { type: "string" },
1128
+ note: { type: "string" },
1129
+ unit: {
1130
+ type: "string",
1131
+ not: { const: "%" }
1132
+ },
1133
+ variant: { type: "string" },
1134
+ layout: { type: "string" },
1135
+ data: {},
1136
+ encode: {
1137
+ type: "object",
1138
+ additionalProperties: { type: ["string", "array"] }
1139
+ },
1140
+ fields: {
1141
+ type: "object",
1142
+ additionalProperties: {
1143
+ type: "object",
1144
+ properties: {
1145
+ label: { type: "string" },
1146
+ type: { enum: [
1147
+ "number",
1148
+ "category",
1149
+ "date",
1150
+ "month",
1151
+ "datetime"
1152
+ ] },
1153
+ unit: { type: "string" },
1154
+ format: { enum: ["number", "percent"] },
1155
+ decimals: {
1156
+ type: "integer",
1157
+ minimum: 0,
1158
+ maximum: 6
1159
+ },
1160
+ domain: { type: "array" },
1161
+ scale: { enum: ["linear", "log"] }
1162
+ },
1163
+ additionalProperties: false
1164
+ }
1165
+ },
1166
+ sort: {
1167
+ type: "object",
1168
+ properties: {
1169
+ field: { type: "string" },
1170
+ direction: { enum: ["asc", "desc"] }
1171
+ },
1172
+ required: ["field", "direction"],
1173
+ additionalProperties: false
1174
+ },
1175
+ emphasis: { type: "object" },
1176
+ annotations: { type: "array" },
1177
+ interaction: {
1178
+ type: "array",
1179
+ items: { enum: [
1180
+ "inspect",
1181
+ "legend",
1182
+ "focus",
1183
+ "pan-zoom",
1184
+ "drag",
1185
+ "collapse"
1186
+ ] }
1187
+ },
1188
+ stack: { enum: ["absolute", "percent"] },
1189
+ unitMark: { type: "object" },
1190
+ range: {
1191
+ type: "array",
1192
+ minItems: 2,
1193
+ maxItems: 2,
1194
+ items: { type: "number" }
1195
+ },
1196
+ start: { type: "number" },
1197
+ layers: { type: "array" },
1198
+ period: {
1199
+ type: "string",
1200
+ pattern: "^\\d{4}$"
1201
+ },
1202
+ directed: { type: "boolean" }
1203
+ };
1204
+ const entries = Object.values(catalog).filter((c) => chart === void 0 || c.name === chart);
1205
+ const anyOf = entries.map((c) => {
1206
+ const base = {
1207
+ required: ["chart", "data"],
1208
+ properties: { chart: { const: c.name } }
1209
+ };
1210
+ if (c.shape === "table" || c.shape === "geo") {
1211
+ base.required.push("encode");
1212
+ base.properties.data = c.shape === "table" ? {
1213
+ type: "array",
1214
+ minItems: 1,
1215
+ items: { type: "object" }
1216
+ } : {
1217
+ type: "object",
1218
+ required: ["map", "rows"],
1219
+ properties: {
1220
+ map: { type: "object" },
1221
+ rows: { type: "array" }
1222
+ },
1223
+ additionalProperties: false
1224
+ };
1225
+ const roles = [...c.required, ...c.optional];
1226
+ const roleSchema = (role) => role === "dimensions" ? {
1227
+ type: "array",
1228
+ minItems: 3,
1229
+ items: { type: "string" }
1230
+ } : c.arrayRoles.includes(role) ? { oneOf: [{ type: "string" }, {
1231
+ type: "array",
1232
+ items: { type: "string" },
1233
+ minItems: 1
1234
+ }] } : { type: "string" };
1235
+ base.properties.encode = {
1236
+ type: "object",
1237
+ required: c.required,
1238
+ properties: Object.fromEntries(roles.map((role) => [role, roleSchema(role)])),
1239
+ additionalProperties: false
1240
+ };
1241
+ if (c.encodeForms.length) base.properties.encode.oneOf = c.encodeForms.map((form) => ({
1242
+ required: form,
1243
+ properties: { value: form.includes("panel") ? { type: "string" } : {
1244
+ type: "array",
1245
+ items: { type: "string" },
1246
+ minItems: 1
1247
+ } }
1248
+ }));
1249
+ } else {
1250
+ base.properties.encode = false;
1251
+ base.properties.data = c.shape === "tree" ? {
1252
+ type: "object",
1253
+ required: ["label"]
1254
+ } : c.shape === "network" ? {
1255
+ type: "object",
1256
+ required: ["nodes", "edges"],
1257
+ properties: {
1258
+ nodes: { type: "array" },
1259
+ edges: { type: "array" }
1260
+ },
1261
+ additionalProperties: false
1262
+ } : {
1263
+ type: "object",
1264
+ required: [
1265
+ "stages",
1266
+ "nodes",
1267
+ "paths"
1268
+ ],
1269
+ properties: {
1270
+ stages: { type: "array" },
1271
+ nodes: { type: "array" },
1272
+ paths: { type: "array" }
1273
+ },
1274
+ additionalProperties: false
1275
+ };
1276
+ }
1277
+ return base;
1278
+ });
1279
+ const schemaFor = (value) => Array.isArray(value) ? { enum: value } : value === "boolean" ? { type: "boolean" } : value === "number" ? { type: "number" } : value === "year" ? {
1280
+ type: "string",
1281
+ pattern: "^[0-9]{4}$"
1282
+ } : value === "range" ? {
1283
+ type: "array",
1284
+ minItems: 2,
1285
+ maxItems: 2,
1286
+ items: { type: "number" }
1287
+ } : value === "layers" ? {
1288
+ type: "array",
1289
+ items: {
1290
+ type: "object",
1291
+ required: [
1292
+ "mark",
1293
+ "field",
1294
+ "axis"
1295
+ ],
1296
+ properties: {
1297
+ mark: { enum: [
1298
+ "line",
1299
+ "area",
1300
+ "column"
1301
+ ] },
1302
+ field: { type: "string" },
1303
+ axis: { enum: ["left", "right"] }
1304
+ },
1305
+ additionalProperties: false
1306
+ }
1307
+ } : { type: "string" };
1308
+ const schema = {
1309
+ type: "object",
1310
+ properties,
1311
+ required: ["chart", "data"],
1312
+ additionalProperties: false,
1313
+ anyOf,
1314
+ allOf: entries.map((c) => {
1315
+ const special = Object.fromEntries(Object.entries(c.special).map(([k, v]) => [k, schemaFor(v)]));
1316
+ if (special.rings) special.rings = {
1317
+ type: "integer",
1318
+ minimum: 2,
1319
+ maximum: 8
1320
+ };
1321
+ for (const key of [
1322
+ "tolerant",
1323
+ "showValues",
1324
+ "rings",
1325
+ "graticule",
1326
+ "legend",
1327
+ "sliceLabels"
1328
+ ]) if (special[key]) properties[key] ??= special[key];
1329
+ else special[key] = false;
1330
+ if ([
1331
+ "bar",
1332
+ "column",
1333
+ "dumbbell",
1334
+ "waterfall",
1335
+ "histogram"
1336
+ ].includes(c.name)) special.unitMark = {
1337
+ type: "object",
1338
+ required: ["value", "label"],
1339
+ properties: {
1340
+ value: {
1341
+ type: "number",
1342
+ exclusiveMinimum: 0
1343
+ },
1344
+ label: {
1345
+ type: "string",
1346
+ minLength: 1
1347
+ },
1348
+ icon: { type: "string" }
1349
+ },
1350
+ additionalProperties: false
1351
+ };
1352
+ for (const field of [
1353
+ "variant",
1354
+ "stack",
1355
+ "layout",
1356
+ "directed",
1357
+ "range",
1358
+ "start",
1359
+ "layers",
1360
+ "period",
1361
+ "unitMark"
1362
+ ]) if (special[field] === void 0) special[field] = false;
1363
+ return {
1364
+ if: {
1365
+ properties: { chart: { const: c.name } },
1366
+ required: ["chart"]
1367
+ },
1368
+ then: {
1369
+ properties: special,
1370
+ required: [...c.requiredSpecial, ...Object.entries(c.special).filter(([, v]) => v === "range").map(([k]) => k)]
1371
+ }
1372
+ };
1373
+ })
1374
+ };
1375
+ if (chart === void 0 || chart === "mindmap" || chart === "tree") {
1376
+ const nodeSchema = (chartType) => ({
1377
+ type: "object",
1378
+ required: ["label"],
1379
+ additionalProperties: false,
1380
+ properties: {
1381
+ label: { type: "string" },
1382
+ id: { type: "string" },
1383
+ note: { type: "string" },
1384
+ value: {
1385
+ type: "number",
1386
+ minimum: 0
1387
+ },
1388
+ icon: { type: "string" },
1389
+ status: { enum: [
1390
+ "new",
1391
+ "info",
1392
+ "ok",
1393
+ "warn",
1394
+ "danger",
1395
+ "ext"
1396
+ ] },
1397
+ shape: { enum: NODE_SHAPES },
1398
+ children: {
1399
+ type: "array",
1400
+ items: { $ref: `#/$defs/${chartType}Node` }
1401
+ }
1402
+ }
1403
+ });
1404
+ schema.$defs = {};
1405
+ if (chart === void 0 || chart === "mindmap") schema.$defs.mindmapNode = nodeSchema("mindmap");
1406
+ if (chart === void 0 || chart === "tree") schema.$defs.treeNode = nodeSchema("tree");
1407
+ for (const chartType of ["mindmap", "tree"]) {
1408
+ if (chart !== void 0 && chart !== chartType) continue;
1409
+ const branch = schema.anyOf.find((item) => item.properties.chart.const === chartType);
1410
+ if (branch) branch.properties.data = { $ref: `#/$defs/${chartType}Node` };
1411
+ }
1412
+ }
1413
+ return schema;
1414
+ }
1415
+ export { parse, schema, sizeBudget, spec_exports, validate };