soma-core 1.4.0 → 1.4.2

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 (132) hide show
  1. package/README.md +1 -1
  2. package/core/build/blocks/block-compile.ts +31 -2
  3. package/core/build/blocks/block-container.ts +2 -11
  4. package/core/build/compiler/page-declaration-compiler.ts +30 -2
  5. package/core/build/compiler/soma-precompile.js +2053 -23
  6. package/core/build/component/component-graph.ts +208 -0
  7. package/core/build/component/package-loader.ts +32 -0
  8. package/core/build/eject/component-eject.ts +473 -0
  9. package/core/build/eject/component-upgrade.ts +359 -0
  10. package/core/build/layout/constraint-solver.ts +235 -0
  11. package/core/build/layout/css-emitter.ts +116 -0
  12. package/core/build/layout/page-layout.ts +85 -0
  13. package/core/build/pack/pack-init.ts +270 -0
  14. package/core/client/base/SomaHttpClient.ts +34 -1
  15. package/core/client/base/SomaPageRootBase.ts +61 -0
  16. package/core/client/component/ai-catalog.ts +121 -4
  17. package/core/client/component/component-defaults.ts +100 -0
  18. package/core/client/component/component-definition.types.ts +39 -0
  19. package/core/client/component/component-manager.ts +79 -4
  20. package/core/client/component/component-pack.ts +126 -2
  21. package/core/client/component/keyboard-matrix.ts +144 -0
  22. package/core/client/component/pack-styles.ts +59 -1
  23. package/core/client/component/style-features.ts +131 -0
  24. package/core/client/component/theme-component-tokens.ts +83 -0
  25. package/core/client/component/verify-pack.ts +120 -1
  26. package/core/client/container/SomaContainerAdapter.ts +6 -2
  27. package/core/client/data/data-object-resolver.ts +407 -4
  28. package/core/client/data/reaction-engine.ts +176 -0
  29. package/core/client/data/window-engine.ts +477 -0
  30. package/core/client/engine/event-engine.ts +98 -0
  31. package/core/client/engine/soma-bootstrap.ts +265 -5
  32. package/core/client/engine/step-runner.ts +134 -0
  33. package/core/client/infra/http/SomaHttpService.ts +2 -2
  34. package/core/client/parser/blocks/page-parser.ts +15 -1
  35. package/core/client/parser/blocks/use-parser.ts +5 -12
  36. package/core/client/parser/data-config-parser.ts +316 -8
  37. package/core/client/parser/duration.ts +16 -0
  38. package/core/client/parser/layout-parser.ts +157 -0
  39. package/core/client/parser/page-state-parser.ts +166 -0
  40. package/core/client/parser/pipeline-parser.ts +76 -1
  41. package/core/client/parser/reaction-parser.ts +459 -0
  42. package/core/client/parser/reaction-sugar.ts +47 -0
  43. package/core/client/parser/step-parser.ts +359 -0
  44. package/core/client/parser/ui-config-parser.ts +59 -0
  45. package/core/client/parser/window-parser.ts +294 -0
  46. package/core/client/theme/theme-engine.ts +102 -2
  47. package/core/index.ts +184 -0
  48. package/core/shared/block-errors.ts +11 -0
  49. package/core/shared/calc/coerce.ts +29 -0
  50. package/core/shared/calc/errors.ts +43 -0
  51. package/core/shared/calc/evaluator.ts +101 -0
  52. package/core/shared/calc/index.ts +12 -0
  53. package/core/shared/calc/lexer.ts +194 -0
  54. package/core/shared/calc/parser.ts +204 -0
  55. package/core/shared/calc/typer.ts +184 -0
  56. package/core/shared/component/derive-sample.ts +105 -0
  57. package/core/shared/component/field-lines.ts +473 -0
  58. package/core/shared/path-algebra.ts +169 -0
  59. package/core/shared/predicates/index.ts +527 -0
  60. package/core/shared/types/component-contract.types.ts +151 -9
  61. package/core/shared/types/data-config.types.ts +120 -1
  62. package/core/shared/types/domain.types.ts +13 -0
  63. package/core/shared/types/event.types.ts +22 -2
  64. package/core/shared/types/layout-constraint.types.ts +73 -0
  65. package/core/shared/types/page-state.types.ts +60 -0
  66. package/core/shared/types/reaction.types.ts +144 -0
  67. package/core/shared/types/step.types.ts +91 -0
  68. package/core/shared/types/ui-config.types.ts +18 -0
  69. package/core/shared/types/window.types.ts +177 -0
  70. package/dist/cli/soma.js +13 -1
  71. package/dist/core/index.cjs +5529 -631
  72. package/dist/types/build/blocks/block-container.d.ts +1 -6
  73. package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -0
  74. package/dist/types/build/component/component-graph.d.ts +85 -0
  75. package/dist/types/build/eject/component-eject.d.ts +121 -0
  76. package/dist/types/build/eject/component-upgrade.d.ts +43 -0
  77. package/dist/types/build/layout/constraint-solver.d.ts +36 -0
  78. package/dist/types/build/layout/css-emitter.d.ts +18 -0
  79. package/dist/types/build/layout/page-layout.d.ts +24 -0
  80. package/dist/types/build/pack/pack-init.d.ts +8 -0
  81. package/dist/types/client/base/SomaHttpClient.d.ts +8 -0
  82. package/dist/types/client/base/SomaPageRootBase.d.ts +28 -0
  83. package/dist/types/client/component/ai-catalog.d.ts +33 -1
  84. package/dist/types/client/component/component-defaults.d.ts +15 -0
  85. package/dist/types/client/component/component-definition.types.d.ts +38 -0
  86. package/dist/types/client/component/component-manager.d.ts +36 -0
  87. package/dist/types/client/component/component-pack.d.ts +32 -2
  88. package/dist/types/client/component/keyboard-matrix.d.ts +24 -0
  89. package/dist/types/client/component/pack-styles.d.ts +21 -0
  90. package/dist/types/client/component/style-features.d.ts +26 -0
  91. package/dist/types/client/component/theme-component-tokens.d.ts +14 -0
  92. package/dist/types/client/component/verify-pack.d.ts +10 -0
  93. package/dist/types/client/data/data-object-resolver.d.ts +106 -1
  94. package/dist/types/client/data/reaction-engine.d.ts +21 -0
  95. package/dist/types/client/data/window-engine.d.ts +27 -0
  96. package/dist/types/client/engine/event-engine.d.ts +15 -0
  97. package/dist/types/client/engine/soma-bootstrap.d.ts +70 -0
  98. package/dist/types/client/engine/step-runner.d.ts +24 -0
  99. package/dist/types/client/parser/blocks/use-parser.d.ts +2 -2
  100. package/dist/types/client/parser/duration.d.ts +1 -0
  101. package/dist/types/client/parser/layout-parser.d.ts +9 -0
  102. package/dist/types/client/parser/page-state-parser.d.ts +32 -0
  103. package/dist/types/client/parser/reaction-parser.d.ts +16 -0
  104. package/dist/types/client/parser/reaction-sugar.d.ts +13 -0
  105. package/dist/types/client/parser/step-parser.d.ts +23 -0
  106. package/dist/types/client/parser/ui-config-parser.d.ts +5 -0
  107. package/dist/types/client/parser/window-parser.d.ts +25 -0
  108. package/dist/types/client/theme/theme-engine.d.ts +26 -0
  109. package/dist/types/index.d.ts +35 -2
  110. package/dist/types/shared/block-errors.d.ts +5 -0
  111. package/dist/types/shared/calc/coerce.d.ts +4 -0
  112. package/dist/types/shared/calc/errors.d.ts +14 -0
  113. package/dist/types/shared/calc/evaluator.d.ts +2 -0
  114. package/dist/types/shared/calc/index.d.ts +6 -0
  115. package/dist/types/shared/calc/lexer.d.ts +20 -0
  116. package/dist/types/shared/calc/parser.d.ts +49 -0
  117. package/dist/types/shared/calc/typer.d.ts +16 -0
  118. package/dist/types/shared/component/derive-sample.d.ts +23 -0
  119. package/dist/types/shared/component/field-lines.d.ts +19 -0
  120. package/dist/types/shared/path-algebra.d.ts +56 -0
  121. package/dist/types/shared/predicates/index.d.ts +79 -0
  122. package/dist/types/shared/types/component-contract.types.d.ts +134 -6
  123. package/dist/types/shared/types/data-config.types.d.ts +115 -1
  124. package/dist/types/shared/types/domain.types.d.ts +12 -0
  125. package/dist/types/shared/types/event.types.d.ts +8 -2
  126. package/dist/types/shared/types/layout-constraint.types.d.ts +52 -0
  127. package/dist/types/shared/types/page-state.types.d.ts +49 -0
  128. package/dist/types/shared/types/reaction.types.d.ts +115 -0
  129. package/dist/types/shared/types/step.types.d.ts +76 -0
  130. package/dist/types/shared/types/ui-config.types.d.ts +18 -0
  131. package/dist/types/shared/types/window.types.d.ts +171 -0
  132. package/package.json +3 -2
@@ -0,0 +1,527 @@
1
+ // 字段谓词图(REQ-009 F-11 起步,REQ-010 S1 升级为「图」)——「什么时候」的**声明式**表达。
2
+ //
3
+ // ── 为什么住在 soma-core/core/shared 而不是 soma-ui/src/shared ────────────
4
+ // 第一版落在 soma-ui,因为当时唯一的消费者是 FormPanel 的 `visible_when`。
5
+ // REQ-010 之后它有了三个消费者,其中两个在 core:
6
+ // · RG 反应图的 `when`(`core/client/data/reaction-engine.ts`)
7
+ // · DW 数据窗口的过滤 AST 叶子(算子闭集与类型配对同一套)
8
+ // · FormPanel 的 `visible_when` / `disabled_when`(soma-ui,经 `soma-ui/shared/field-predicates` 转出)
9
+ // core 不能反向依赖 ui,而「同一个算子在数据层和 UI 层各判一次且判得不一样」是
10
+ // 这个仓库反复警告的那类缺陷。所以真源下沉到共享层,soma-ui 侧只留一个 re-export
11
+ // 保住既有的公开子路径(`soma-ui/shared/field-predicates`)。
12
+ //
13
+ // 要解决的问题:表单里最常见的第二类逻辑不是「这个值合不合法」(那是 rules 与
14
+ // cross_rules 的活),而是「这个字段现在该不该出现 / 能不能改」——选了「公司」才要填税号、
15
+ // 勾了「开发票」才要填抬头、金额在 1000 到 5000 之间才要审批。Ant 用 `dependencies` +
16
+ // 渲染函数,Formily 用 `x-reactions` + 表达式,amis 用 `${}` 文法——三条路的底部都是 eval
17
+ // (Formily 的编译器就是 `new Function('$root', 'with($root){ return (expr) }')`)。
18
+ // SOMA 有 `verify:no-eval` 硬闸门,所以只能走**封闭谓词**这条路;而这条路走通之后反而是
19
+ // 结构性优势:**引用的字段是字典里的封闭枚举,算子是闭集,于是编译期能建图、能检环、
20
+ // 能把算子与字段类型配对**——对 `enum` 字段写 `gte` 当场报错,这是 JsonLogic / Formily /
21
+ // amis 三家都做不到的事(它们的 `var` 路径是自由字符串,拼错只会静默求值成 undefined)。
22
+ //
23
+ // ── 与第一版(REQ-009 F-11)的差别 ─────────────────────────────────────
24
+ // 第一版:六算子、组合只许一层、无复用、无深取、不认字段类型。
25
+ // 本版(对标 json-rules-engine 的 all/any/not + 具名条件 + path,与 AG Grid 过滤 AST 的算子闭集):
26
+ // · 算子 6 → 12:补 gt / gte / lt / lte / between / matches;
27
+ // · 组合任意深度,并补 none_of(取反)——「(A 且 B) 或 C」不再需要伪造一个字段;
28
+ // · 具名谓词 `{ ref: name }`:同一条「是否 VIP」在十个字段上复用一处声明;
29
+ // · `path` 深取:`{ field: address, path: city }` 读对象字段的子键(只允许 `.` 与 `[n]`);
30
+ // · 校验期可选传入字段类型表:算子与类型配对,越界当场点名。
31
+ // 两个导出的签名**向后兼容**:新增参数全部可选,第一版的调用一字不改。
32
+ //
33
+ // ── 为什么仍然不是表达式语言 ──────────────────────────────────────────
34
+ // 任意深度的 all_of/any_of/none_of 是**布尔代数**,不是编程语言:没有变量绑定、没有
35
+ // 函数、没有循环,求值必然终止且复杂度与声明大小线性。这条边界要守住——
36
+ // 「再多一个 map 算子」就是 JsonLogic 走过的那条滑向图灵完备的路。
37
+
38
+ import { ordinalOf, textOf } from '../calc/coerce';
39
+
40
+ /** 十二个具名算子——封闭集合,不接受任何其他取值 */
41
+ export const SOMA_FIELD_PREDICATE_OPS = [
42
+ 'eq', 'ne', 'in', 'not_in', 'empty', 'not_empty',
43
+ 'gt', 'gte', 'lt', 'lte', 'between', 'matches',
44
+ // 三个文本子串算子(REQ-010 S2)。`matches` 理论上能表达它们(`^华`),但要求写声明的人
45
+ // 去写正则——而「以华开头」是过滤器里最常见的一条,逼人写 `^华` 只会换来一堆
46
+ // 没转义的正则元字符(`.` `(` `+` 出现在业务词里是常态)。这三个算子把转义关在引擎里。
47
+ 'starts_with', 'ends_with', 'contains',
48
+ ] as const;
49
+
50
+ export type SomaFieldPredicateOp = typeof SOMA_FIELD_PREDICATE_OPS[number];
51
+
52
+ /**
53
+ * 算子 × 字段类型的合法配对(校验期用;不传类型表时跳过这一层)。
54
+ *
55
+ * 表是**允许集**而不是禁止集:新加一个字段类型时,它默认什么算子都不能用,
56
+ * 直到有人在这里写下它该支持什么——「默认拒绝」比「默认放行」更不容易埋雷。
57
+ * `text` 与 `enum` 不许比大小:字符串序在业务上几乎从来不是想要的语义
58
+ * ("10" < "9"),而 enum 的 key 之间根本没有序。
59
+ */
60
+ const OPS_BY_KIND: Readonly<Record<string, readonly SomaFieldPredicateOp[]>> = {
61
+ text: ['eq', 'ne', 'in', 'not_in', 'empty', 'not_empty', 'matches', 'starts_with', 'ends_with', 'contains'],
62
+ richtext: ['empty', 'not_empty'],
63
+ url: ['eq', 'ne', 'empty', 'not_empty', 'matches', 'starts_with', 'ends_with', 'contains'],
64
+ enum: ['eq', 'ne', 'in', 'not_in', 'empty', 'not_empty'],
65
+ bool: ['eq', 'ne', 'empty', 'not_empty'],
66
+ int: ['eq', 'ne', 'in', 'not_in', 'empty', 'not_empty', 'gt', 'gte', 'lt', 'lte', 'between'],
67
+ float: ['eq', 'ne', 'in', 'not_in', 'empty', 'not_empty', 'gt', 'gte', 'lt', 'lte', 'between'],
68
+ money: ['eq', 'ne', 'empty', 'not_empty', 'gt', 'gte', 'lt', 'lte', 'between'],
69
+ percent: ['eq', 'ne', 'empty', 'not_empty', 'gt', 'gte', 'lt', 'lte', 'between'],
70
+ progress: ['eq', 'ne', 'empty', 'not_empty', 'gt', 'gte', 'lt', 'lte', 'between'],
71
+ date: ['eq', 'ne', 'empty', 'not_empty', 'gt', 'gte', 'lt', 'lte', 'between'],
72
+ datetime: ['eq', 'ne', 'empty', 'not_empty', 'gt', 'gte', 'lt', 'lte', 'between'],
73
+ image: ['empty', 'not_empty'],
74
+ file: ['empty', 'not_empty'],
75
+ tags: ['in', 'not_in', 'empty', 'not_empty'],
76
+ tree: ['eq', 'ne', 'in', 'not_in', 'empty', 'not_empty'],
77
+ cascade: ['eq', 'ne', 'in', 'not_in', 'empty', 'not_empty'],
78
+ };
79
+
80
+ /** 单条件:某个字段的当前值满足某个算子 */
81
+ export interface SomaFieldCondition {
82
+ /** 被观察字段的 key(必须是同一层里真实存在的字段) */
83
+ field: string;
84
+ op: SomaFieldPredicateOp;
85
+ /**
86
+ * eq/ne/gt/gte/lt/lte 的比较值;in/not_in 的候选数组;between 的 [低, 高](闭区间);
87
+ * matches 的正则源串(不带斜杠与 flag);empty/not_empty 不用
88
+ */
89
+ value?: unknown;
90
+ /**
91
+ * 深取路径:字段值是对象时读它的子键。只允许 `a.b.c` 与 `a[0].b` 两种写法——
92
+ * 它是 JSONPath 的一个极小子集,刻意不支持通配与过滤(那些属于查询语言)。
93
+ */
94
+ path?: string;
95
+ }
96
+
97
+ /** 引用一条具名谓词(在 `predicates:` 表里声明过的名字) */
98
+ export interface SomaFieldPredicateRef {
99
+ ref: string;
100
+ }
101
+
102
+ /** 全部成立 */
103
+ export interface SomaFieldPredicateAllOf {
104
+ all_of: SomaFieldPredicate[];
105
+ }
106
+
107
+ /** 任一成立 */
108
+ export interface SomaFieldPredicateAnyOf {
109
+ any_of: SomaFieldPredicate[];
110
+ }
111
+
112
+ /** 全部不成立(取反) */
113
+ export interface SomaFieldPredicateNoneOf {
114
+ none_of: SomaFieldPredicate[];
115
+ }
116
+
117
+ export type SomaFieldPredicate =
118
+ | SomaFieldCondition
119
+ | SomaFieldPredicateRef
120
+ | SomaFieldPredicateAllOf
121
+ | SomaFieldPredicateAnyOf
122
+ | SomaFieldPredicateNoneOf;
123
+
124
+ /** 具名谓词表:名字 → 谓词。声明一次,到处 `{ ref: 名字 }` */
125
+ export type SomaNamedPredicates = Readonly<Record<string, SomaFieldPredicate>>;
126
+
127
+ /** 校验期可选上下文 */
128
+ export interface SomaPredicateValidateOptions {
129
+ /** 字段名 → 字段类型(来自字典 `type`);给了就做算子 × 类型配对 */
130
+ fieldTypes?: Readonly<Record<string, string | undefined>>;
131
+ /** 具名谓词表;给了才允许 `{ ref }`,且会一并校验被引用的谓词 */
132
+ named?: SomaNamedPredicates;
133
+ }
134
+
135
+ /** 嵌套深度上限:布尔代数不需要更深;深于此几乎必然是把业务规则塞进了声明 */
136
+ const MAX_DEPTH = 8;
137
+
138
+ /**
139
+ * 空值判定:与 `console-kit.validateField` / `form-rules` 完全一致
140
+ * (undefined / null / 空串 / false / 空数组 都算空)。
141
+ *
142
+ * `false` 算空是刻意的:`{ field: invoice, op: not_empty }` 想表达的正是
143
+ * 「开票开关打开了」,而未勾选的开关值就是 `false`。两套空值语义会让
144
+ * 「required 说没填、not_empty 说填了」这种自相矛盾在同一张表单上发生。
145
+ */
146
+ function isEmpty(value: unknown): boolean {
147
+ if (Array.isArray(value)) return value.length === 0;
148
+ return value === undefined || value === null || value === '' || value === false;
149
+ }
150
+
151
+ // 等值类比较一律走字符串(`textOf`,与 calc 共用):声明来自 YAML,`enum` 的 key
152
+ // 可能是数字也可能是字符串,`bool` 从控件读出来是布尔、从接口回来可能是 "true"。
153
+ // 统一成字符串让「声明怎么写都对得上」,而不是逼页面去猜组件的类型口径。
154
+
155
+ function toTextList(value: unknown): string[] {
156
+ return Array.isArray(value) ? value.map(textOf) : [];
157
+ }
158
+
159
+ /**
160
+ * 序比较用的归一直接复用 calc 的 `ordinalOf`。
161
+ *
162
+ * 必须共用而不是各写一份:同一个 `amount`,在 `{ field: amount, op: gt, value: 1000 }`
163
+ * 里被判为「大于 1000」,在 `calc: "[amount] * 0.1"` 里必须也当成同一个数。
164
+ * 两处各归一一次,迟早出现「谓词说大于、算式算成空」这种自相矛盾。
165
+ */
166
+
167
+ function compareOrdinal(actual: unknown, expected: unknown): number | null {
168
+ const a = ordinalOf(actual);
169
+ const b = ordinalOf(expected);
170
+ if (a !== null && b !== null) return a === b ? 0 : (a < b ? -1 : 1);
171
+ const at = textOf(actual);
172
+ const bt = textOf(expected);
173
+ if (at === '' || bt === '') return null;
174
+ return at === bt ? 0 : (at < bt ? -1 : 1);
175
+ }
176
+
177
+ /** `path` 深取:只认 `.` 与 `[n]`,任一环节缺失即 undefined,不抛 */
178
+ function readPath(root: unknown, path: string): unknown {
179
+ let current: unknown = root;
180
+ for (const segment of path.split('.')) {
181
+ if (segment === '') continue;
182
+ const match = segment.match(/^([^[\]]+)?((?:\[\d+\])*)$/);
183
+ if (!match) return undefined;
184
+ if (match[1] !== undefined) {
185
+ if (current === null || typeof current !== 'object') return undefined;
186
+ current = (current as Record<string, unknown>)[match[1]];
187
+ }
188
+ for (const index of match[2].matchAll(/\[(\d+)\]/g)) {
189
+ if (!Array.isArray(current)) return undefined;
190
+ current = current[Number(index[1])];
191
+ }
192
+ }
193
+ return current;
194
+ }
195
+
196
+ /** 正则缓存:同一条 matches 谓词每次求值都 new RegExp 是不必要的开销 */
197
+ const regexCache = new Map<string, RegExp | null>();
198
+
199
+ function regexOf(source: unknown): RegExp | null {
200
+ const key = textOf(source);
201
+ if (regexCache.has(key)) return regexCache.get(key) ?? null;
202
+ let compiled: RegExp | null = null;
203
+ try {
204
+ compiled = new RegExp(key);
205
+ } catch {
206
+ compiled = null;
207
+ }
208
+ regexCache.set(key, compiled);
209
+ return compiled;
210
+ }
211
+
212
+ /** 单条件求值(算子非法 → false:不认识的声明按「不成立」处理,不炸页面) */
213
+ function evaluateCondition(
214
+ condition: SomaFieldCondition,
215
+ values: Record<string, unknown>,
216
+ ): boolean {
217
+ const raw = values[condition.field];
218
+ const actual = condition.path ? readPath(raw, condition.path) : raw;
219
+ switch (condition.op) {
220
+ case 'empty':
221
+ return isEmpty(actual);
222
+ case 'not_empty':
223
+ return !isEmpty(actual);
224
+ case 'eq':
225
+ return textOf(actual) === textOf(condition.value);
226
+ case 'ne':
227
+ return textOf(actual) !== textOf(condition.value);
228
+ case 'in':
229
+ return toTextList(condition.value).includes(textOf(actual));
230
+ case 'not_in':
231
+ return !toTextList(condition.value).includes(textOf(actual));
232
+ case 'gt': {
233
+ const c = compareOrdinal(actual, condition.value);
234
+ return c !== null && c > 0;
235
+ }
236
+ case 'gte': {
237
+ const c = compareOrdinal(actual, condition.value);
238
+ return c !== null && c >= 0;
239
+ }
240
+ case 'lt': {
241
+ const c = compareOrdinal(actual, condition.value);
242
+ return c !== null && c < 0;
243
+ }
244
+ case 'lte': {
245
+ const c = compareOrdinal(actual, condition.value);
246
+ return c !== null && c <= 0;
247
+ }
248
+ case 'between': {
249
+ if (!Array.isArray(condition.value) || condition.value.length !== 2) return false;
250
+ const lo = compareOrdinal(actual, condition.value[0]);
251
+ const hi = compareOrdinal(actual, condition.value[1]);
252
+ return lo !== null && hi !== null && lo >= 0 && hi <= 0;
253
+ }
254
+ case 'matches': {
255
+ const re = regexOf(condition.value);
256
+ return re !== null && re.test(textOf(actual));
257
+ }
258
+ // 子串三兄弟:拿 `value` 当**字面量**比,不当正则——这正是它们存在的理由。
259
+ // 空的 needle 一律按不成立处理:`contains: ""` 对所有行都真,那不是过滤,是没写条件。
260
+ case 'starts_with': {
261
+ const needle = textOf(condition.value);
262
+ return needle !== '' && textOf(actual).startsWith(needle);
263
+ }
264
+ case 'ends_with': {
265
+ const needle = textOf(condition.value);
266
+ return needle !== '' && textOf(actual).endsWith(needle);
267
+ }
268
+ case 'contains': {
269
+ const needle = textOf(condition.value);
270
+ return needle !== '' && textOf(actual).includes(needle);
271
+ }
272
+ default:
273
+ return false;
274
+ }
275
+ }
276
+
277
+ /**
278
+ * 谓词求值。
279
+ *
280
+ * `values` 是**同一层**的值对象:顶层字段传整张表的 values,`item_fields` 的谓词传那一项
281
+ * 自己的对象。`named` 是具名谓词表;`{ ref }` 在这里解析。
282
+ *
283
+ * 环保护:具名谓词互相引用成环时(校验期本该拦下,但运行期不能指望它)按「不成立」处理,
284
+ * 绝不无限递归——一个写错的声明不该把页面挂死。
285
+ */
286
+ export function evaluatePredicate(
287
+ predicate: SomaFieldPredicate | null | undefined,
288
+ values: Record<string, unknown>,
289
+ named?: SomaNamedPredicates,
290
+ ): boolean {
291
+ return evaluateNode(predicate, values, named ?? {}, new Set(), 0);
292
+ }
293
+
294
+ function evaluateNode(
295
+ predicate: unknown,
296
+ values: Record<string, unknown>,
297
+ named: SomaNamedPredicates,
298
+ visiting: Set<string>,
299
+ depth: number,
300
+ ): boolean {
301
+ if (!predicate || typeof predicate !== 'object' || Array.isArray(predicate)) return false;
302
+ if (depth > MAX_DEPTH) return false;
303
+ const box = predicate as Record<string, unknown>;
304
+
305
+ if (typeof box.ref === 'string') {
306
+ const name = box.ref;
307
+ if (visiting.has(name)) return false; // 环:按不成立处理
308
+ const target = named[name];
309
+ if (!target) return false;
310
+ visiting.add(name);
311
+ const result = evaluateNode(target, values, named, visiting, depth + 1);
312
+ visiting.delete(name);
313
+ return result;
314
+ }
315
+ if (Array.isArray(box.all_of)) {
316
+ return box.all_of.length > 0
317
+ && box.all_of.every((item) => evaluateNode(item, values, named, visiting, depth + 1));
318
+ }
319
+ if (Array.isArray(box.any_of)) {
320
+ return box.any_of.some((item) => evaluateNode(item, values, named, visiting, depth + 1));
321
+ }
322
+ if (Array.isArray(box.none_of)) {
323
+ return box.none_of.length > 0
324
+ && !box.none_of.some((item) => evaluateNode(item, values, named, visiting, depth + 1));
325
+ }
326
+ return evaluateCondition(predicate as SomaFieldCondition, values);
327
+ }
328
+
329
+ const PATH_PATTERN = /^[A-Za-z_][\w]*(?:\[\d+\])*(?:\.[A-Za-z_][\w]*(?:\[\d+\])*)*$/;
330
+
331
+ function checkCondition(
332
+ raw: Record<string, unknown>,
333
+ fieldKeys: readonly string[],
334
+ path: string,
335
+ options: SomaPredicateValidateOptions,
336
+ ): string[] {
337
+ const issues: string[] = [];
338
+
339
+ const field = typeof raw.field === 'string' ? raw.field.trim() : '';
340
+ if (field === '') {
341
+ issues.push(`${path}.field 必须是非空字段名`);
342
+ } else if (!fieldKeys.includes(field)) {
343
+ // 这一条是本模块存在的最大理由:表达式语言里「字段名打错一个字母」只会
344
+ // 静默求值成 undefined,字段永远不出现且无人知晓;具名谓词能当场点名。
345
+ issues.push(`${path}.field 引用了不存在的字段 "${field}"`);
346
+ }
347
+
348
+ const op = String(raw.op ?? '');
349
+ if (!(SOMA_FIELD_PREDICATE_OPS as readonly string[]).includes(op)) {
350
+ issues.push(`${path}.op 只能是 ${SOMA_FIELD_PREDICATE_OPS.join(' / ')},收到 "${op}"`);
351
+ return issues;
352
+ }
353
+
354
+ // 算子 × 字段类型配对:这是对方(JsonLogic / Formily / amis)结构上做不到的一步——
355
+ // 它们的字段引用是自由字符串,没有类型可查。有 `path` 时读的是子键,类型未知,跳过配对。
356
+ const kind = options.fieldTypes?.[field];
357
+ if (kind && !raw.path) {
358
+ const allowed = OPS_BY_KIND[kind];
359
+ if (allowed && !allowed.includes(op as SomaFieldPredicateOp)) {
360
+ issues.push(
361
+ `${path}.op="${op}" 不能用在 ${kind} 类型的字段 "${field}" 上`
362
+ + `(该类型允许:${allowed.join(' / ')})`,
363
+ );
364
+ }
365
+ }
366
+
367
+ if (raw.path !== undefined) {
368
+ if (typeof raw.path !== 'string' || !PATH_PATTERN.test(raw.path)) {
369
+ issues.push(`${path}.path 只允许 a.b.c 与 a[0].b 两种写法,收到 ${JSON.stringify(raw.path)}`);
370
+ }
371
+ }
372
+
373
+ const value = raw.value;
374
+ if ((op === 'in' || op === 'not_in') && !Array.isArray(value)) {
375
+ issues.push(`${path}.value 在 op=${op} 时必须是数组`);
376
+ }
377
+ if ((op === 'eq' || op === 'ne' || op === 'gt' || op === 'gte' || op === 'lt' || op === 'lte') && value === undefined) {
378
+ issues.push(`${path}.value 在 op=${op} 时不能省略(要判「有没有值」请用 empty / not_empty)`);
379
+ }
380
+ if (op === 'between' && (!Array.isArray(value) || value.length !== 2)) {
381
+ issues.push(`${path}.value 在 op=between 时必须是 [低, 高] 两元数组`);
382
+ }
383
+ if (op === 'matches') {
384
+ if (typeof value !== 'string' || value === '') {
385
+ issues.push(`${path}.value 在 op=matches 时必须是非空正则源串`);
386
+ } else if (regexOf(value) === null) {
387
+ issues.push(`${path}.value 不是合法正则:${JSON.stringify(value)}`);
388
+ }
389
+ }
390
+ if (op === 'starts_with' || op === 'ends_with' || op === 'contains') {
391
+ // 空串在运行期按不成立处理,但声明期要拒:`contains: ""` 写下来的意思几乎肯定是
392
+ // 「这里还没填」,而不是「一条恒不成立的条件」。让它在声明期就说出来。
393
+ if (typeof value !== 'string' || value === '') {
394
+ issues.push(`${path}.value 在 op=${op} 时必须是非空字符串(它按字面量比对,不是正则)`);
395
+ }
396
+ }
397
+ return issues;
398
+ }
399
+
400
+ /**
401
+ * 谓词静态校验:返回问题清单(空数组 = 通过)。
402
+ *
403
+ * @param fieldKeys 同一层里合法的字段名全集
404
+ * @param path 问题定位用的声明路径(如 `fields[2].visible_when`)
405
+ * @param options 可选:字段类型表(做算子配对)与具名谓词表(允许并校验 `ref`)
406
+ *
407
+ * 调用方拿到非空清单时的正确处置是「当作不成立 + `console.warn` 点名」——
408
+ * 让一个写错的联动声明**看得见**,而不是让字段悄悄消失。
409
+ */
410
+ export function validatePredicate(
411
+ predicate: unknown,
412
+ fieldKeys: readonly string[],
413
+ path: string,
414
+ options: SomaPredicateValidateOptions = {},
415
+ ): string[] {
416
+ if (predicate === undefined || predicate === null) return [];
417
+ return validateNode(predicate, fieldKeys, path, options, new Set(), 0);
418
+ }
419
+
420
+ function validateNode(
421
+ predicate: unknown,
422
+ fieldKeys: readonly string[],
423
+ path: string,
424
+ options: SomaPredicateValidateOptions,
425
+ visiting: Set<string>,
426
+ depth: number,
427
+ ): string[] {
428
+ if (typeof predicate !== 'object' || predicate === null || Array.isArray(predicate)) {
429
+ return [`${path} 必须是谓词对象 { field, op, value? } / { ref } / { all_of | any_of | none_of }`];
430
+ }
431
+ if (depth > MAX_DEPTH) {
432
+ return [`${path} 嵌套超过 ${MAX_DEPTH} 层——布尔代数不需要这么深,这多半是把业务规则塞进了声明`];
433
+ }
434
+ const box = predicate as Record<string, unknown>;
435
+
436
+ if ('ref' in box) {
437
+ const name = typeof box.ref === 'string' ? box.ref.trim() : '';
438
+ if (name === '') return [`${path}.ref 必须是非空的具名谓词名`];
439
+ const named = options.named;
440
+ if (!named) return [`${path} 用了 { ref: "${name}" },但本层没有声明 predicates 表`];
441
+ if (!(name in named)) {
442
+ return [`${path}.ref 引用了不存在的具名谓词 "${name}"(已声明:${Object.keys(named).join(' / ') || '无'})`];
443
+ }
444
+ if (visiting.has(name)) {
445
+ // 环在校验期就拦下:运行期虽然有保护,但一个成环的声明永远不成立,等于没写
446
+ return [`${path}.ref 形成引用环:${[...visiting, name].join(' → ')}`];
447
+ }
448
+ visiting.add(name);
449
+ const issues = validateNode(named[name], fieldKeys, `predicates.${name}`, options, visiting, depth + 1);
450
+ visiting.delete(name);
451
+ return issues;
452
+ }
453
+
454
+ const group = ['all_of', 'any_of', 'none_of'].find((key) => key in box);
455
+ if (group) {
456
+ const members = box[group];
457
+ if (!Array.isArray(members) || members.length === 0) {
458
+ return [`${path}.${group} 必须是非空数组`];
459
+ }
460
+ const extra = ['all_of', 'any_of', 'none_of', 'ref', 'field'].filter((key) => key !== group && key in box);
461
+ if (extra.length > 0) {
462
+ return [`${path} 同时写了 ${group} 与 ${extra.join(' / ')}——一个节点只能是一种形态`];
463
+ }
464
+ return members.flatMap((member, index) =>
465
+ validateNode(member, fieldKeys, `${path}.${group}[${index}]`, options, visiting, depth + 1));
466
+ }
467
+
468
+ return checkCondition(box, fieldKeys, path, options);
469
+ }
470
+
471
+ /**
472
+ * 具名谓词表整体校验:每一条都合法、彼此不成环。
473
+ * 表单在挂载时调一次;问题清单非空时 `console.warn` 点名并把有问题的那几条当作不成立。
474
+ */
475
+ export function validateNamedPredicates(
476
+ named: unknown,
477
+ fieldKeys: readonly string[],
478
+ fieldTypes?: Readonly<Record<string, string | undefined>>,
479
+ ): string[] {
480
+ if (named === undefined || named === null) return [];
481
+ if (typeof named !== 'object' || Array.isArray(named)) return ['predicates 必须是 { 名字: 谓词 } 映射'];
482
+ const table = named as SomaNamedPredicates;
483
+ const options: SomaPredicateValidateOptions = { fieldTypes, named: table };
484
+ return Object.entries(table).flatMap(([name, predicate]) => {
485
+ if (!/^[A-Za-z_][\w]*$/.test(name)) return [`predicates 的键 "${name}" 必须是标识符`];
486
+ return validateNode(predicate, fieldKeys, `predicates.${name}`, options, new Set([name]), 0);
487
+ });
488
+ }
489
+
490
+ /**
491
+ * 收集一条谓词直接或经 ref 间接依赖的全部字段名(去重、声明序)。
492
+ *
493
+ * 这是反应图(REQ-010 S1)建 DAG 的原料:知道「这条反应看哪些字段」,
494
+ * 才能在编译期排出求值顺序、检出环、并回答「改这个字段会牵动哪些反应」。
495
+ * amis / Formily 的依赖是运行时收集的,所以做不到这一步。
496
+ */
497
+ export function collectPredicateFields(
498
+ predicate: SomaFieldPredicate | null | undefined,
499
+ named?: SomaNamedPredicates,
500
+ ): string[] {
501
+ const out: string[] = [];
502
+ const seen = new Set<string>();
503
+ const visitingRefs = new Set<string>();
504
+ const walk = (node: unknown, depth: number): void => {
505
+ if (!node || typeof node !== 'object' || Array.isArray(node) || depth > MAX_DEPTH) return;
506
+ const box = node as Record<string, unknown>;
507
+ if (typeof box.ref === 'string') {
508
+ if (visitingRefs.has(box.ref)) return;
509
+ visitingRefs.add(box.ref);
510
+ walk(named?.[box.ref], depth + 1);
511
+ visitingRefs.delete(box.ref);
512
+ return;
513
+ }
514
+ for (const group of ['all_of', 'any_of', 'none_of'] as const) {
515
+ if (Array.isArray(box[group])) {
516
+ for (const member of box[group] as unknown[]) walk(member, depth + 1);
517
+ return;
518
+ }
519
+ }
520
+ if (typeof box.field === 'string' && box.field !== '' && !seen.has(box.field)) {
521
+ seen.add(box.field);
522
+ out.push(box.field);
523
+ }
524
+ };
525
+ walk(predicate, 0);
526
+ return out;
527
+ }