soma-core 1.3.5 → 1.4.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 (169) hide show
  1. package/README.md +20 -7
  2. package/app/SomaPageClient.tsx +4 -4
  3. package/app/components/SomaHostPage.tsx +5 -5
  4. package/app/components/SomaHydrationShell.tsx +4 -7
  5. package/app/globals.css +126 -3
  6. package/core/build/{v2 → blocks}/block-compile.ts +47 -18
  7. package/core/build/{v2/soma-file-loader.ts → blocks/block-container.ts} +28 -37
  8. package/core/build/{v2 → blocks}/block-loader.ts +1 -1
  9. package/core/build/{v2 → blocks}/html-index.ts +1 -1
  10. package/core/build/{v2/migrate-v1.ts → blocks/migrate-flat.ts} +27 -27
  11. package/core/build/compiler/host-config-sync.cjs +2 -9
  12. package/core/build/compiler/page-declaration-compiler.ts +32 -4
  13. package/core/build/compiler/soma-manifest-webpack-plugin.js +1 -1
  14. package/core/build/compiler/soma-precompile.js +2057 -35
  15. package/core/build/compiler/soma-precompile.ts +2 -2
  16. package/core/build/component/component-graph.ts +208 -0
  17. package/core/build/eject/component-eject.ts +473 -0
  18. package/core/build/eject/component-upgrade.ts +359 -0
  19. package/core/build/layout/constraint-solver.ts +235 -0
  20. package/core/build/layout/css-emitter.ts +116 -0
  21. package/core/build/layout/page-layout.ts +85 -0
  22. package/core/build/pack/pack-init.ts +265 -0
  23. package/core/client/base/SomaPageRootBase.ts +61 -0
  24. package/core/client/component/ai-catalog.ts +83 -8
  25. package/core/client/component/component-defaults.ts +100 -0
  26. package/core/client/component/component-definition.types.ts +39 -0
  27. package/core/client/component/component-manager.ts +79 -4
  28. package/core/client/component/component-pack.ts +126 -2
  29. package/core/client/component/contract-compat.ts +32 -3
  30. package/core/client/component/{example-v2.ts → example-blocks.ts} +19 -19
  31. package/core/client/component/keyboard-matrix.ts +144 -0
  32. package/core/client/component/pack-styles.ts +59 -1
  33. package/core/client/component/style-features.ts +131 -0
  34. package/core/client/component/theme-component-tokens.ts +83 -0
  35. package/core/client/data/data-object-resolver.ts +407 -4
  36. package/core/client/data/reaction-engine.ts +176 -0
  37. package/core/client/data/window-engine.ts +477 -0
  38. package/core/client/engine/event-engine.ts +98 -0
  39. package/core/client/engine/soma-bootstrap.ts +286 -7
  40. package/core/client/engine/step-runner.ts +134 -0
  41. package/core/client/engine/style-binder.ts +1 -1
  42. package/core/client/infra/notify/DomNotifyService.ts +2 -1
  43. package/core/client/infra/notify/INotifyTheme.ts +1 -1
  44. package/core/client/parser/{v2 → blocks}/namespace.ts +1 -1
  45. package/core/client/parser/{v2 → blocks}/page-parser.ts +30 -16
  46. package/core/client/parser/{v2 → blocks}/use-parser.ts +24 -25
  47. package/core/client/parser/data-config-parser.ts +316 -8
  48. package/core/client/parser/duration.ts +16 -0
  49. package/core/client/parser/layout-parser.ts +157 -0
  50. package/core/client/parser/page-state-parser.ts +166 -0
  51. package/core/client/parser/pipeline-parser.ts +76 -1
  52. package/core/client/parser/reaction-parser.ts +459 -0
  53. package/core/client/parser/reaction-sugar.ts +47 -0
  54. package/core/client/parser/step-parser.ts +359 -0
  55. package/core/client/parser/style-config-parser.ts +7 -7
  56. package/core/client/parser/ui-config-parser.ts +59 -0
  57. package/core/client/parser/value-lang.ts +1 -1
  58. package/core/client/parser/window-parser.ts +294 -0
  59. package/core/client/registry/index.ts +8 -0
  60. package/core/client/theme/theme-engine.ts +144 -16
  61. package/core/client/typography/typography-base.ts +1 -1
  62. package/core/index.ts +188 -13
  63. package/core/server/host/csp-nonce-metadata.ts +1 -1
  64. package/core/server/host/published-page-assets.ts +3 -8
  65. package/core/server/host/soma-page-compile.ts +1 -1
  66. package/core/server/index.ts +2 -2
  67. package/core/shared/block-errors.ts +11 -0
  68. package/core/shared/calc/coerce.ts +29 -0
  69. package/core/shared/calc/errors.ts +43 -0
  70. package/core/shared/calc/evaluator.ts +101 -0
  71. package/core/shared/calc/index.ts +12 -0
  72. package/core/shared/calc/lexer.ts +194 -0
  73. package/core/shared/calc/parser.ts +204 -0
  74. package/core/shared/calc/typer.ts +184 -0
  75. package/core/shared/path-algebra.ts +169 -0
  76. package/core/shared/predicates/index.ts +527 -0
  77. package/core/shared/published-page-route.ts +61 -0
  78. package/core/shared/types/adaptive.types.ts +1 -1
  79. package/core/shared/types/component-contract.types.ts +128 -2
  80. package/core/shared/types/data-config.types.ts +149 -2
  81. package/core/shared/types/domain.types.ts +13 -0
  82. package/core/shared/types/event.types.ts +22 -2
  83. package/core/shared/types/layout-constraint.types.ts +73 -0
  84. package/core/shared/types/page-state.types.ts +60 -0
  85. package/core/shared/types/reaction.types.ts +144 -0
  86. package/core/shared/types/scope-manifest.types.ts +11 -15
  87. package/core/shared/types/step.types.ts +91 -0
  88. package/core/shared/types/style-config.types.ts +4 -4
  89. package/core/shared/types/ui-config.types.ts +18 -0
  90. package/core/shared/types/window.types.ts +177 -0
  91. package/dist/cli/soma.js +28 -3
  92. package/dist/core/index.cjs +4829 -405
  93. package/dist/types/build/{v2 → blocks}/block-compile.d.ts +7 -7
  94. package/dist/types/build/{v2/soma-file-loader.d.ts → blocks/block-container.d.ts} +6 -11
  95. package/dist/types/build/{v2/migrate-v1.d.ts → blocks/migrate-flat.d.ts} +6 -6
  96. package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -0
  97. package/dist/types/build/component/component-graph.d.ts +85 -0
  98. package/dist/types/build/eject/component-eject.d.ts +121 -0
  99. package/dist/types/build/eject/component-upgrade.d.ts +43 -0
  100. package/dist/types/build/layout/constraint-solver.d.ts +36 -0
  101. package/dist/types/build/layout/css-emitter.d.ts +18 -0
  102. package/dist/types/build/layout/page-layout.d.ts +24 -0
  103. package/dist/types/build/pack/pack-init.d.ts +8 -0
  104. package/dist/types/client/base/SomaPageRootBase.d.ts +28 -0
  105. package/dist/types/client/component/ai-catalog.d.ts +24 -1
  106. package/dist/types/client/component/component-defaults.d.ts +15 -0
  107. package/dist/types/client/component/component-definition.types.d.ts +38 -0
  108. package/dist/types/client/component/component-manager.d.ts +36 -0
  109. package/dist/types/client/component/component-pack.d.ts +32 -2
  110. package/dist/types/client/component/contract-compat.d.ts +2 -2
  111. package/dist/types/client/component/example-blocks.d.ts +9 -0
  112. package/dist/types/client/component/keyboard-matrix.d.ts +24 -0
  113. package/dist/types/client/component/pack-styles.d.ts +21 -0
  114. package/dist/types/client/component/style-features.d.ts +26 -0
  115. package/dist/types/client/component/theme-component-tokens.d.ts +14 -0
  116. package/dist/types/client/data/data-object-resolver.d.ts +106 -1
  117. package/dist/types/client/data/reaction-engine.d.ts +21 -0
  118. package/dist/types/client/data/window-engine.d.ts +27 -0
  119. package/dist/types/client/engine/event-engine.d.ts +15 -0
  120. package/dist/types/client/engine/soma-bootstrap.d.ts +70 -0
  121. package/dist/types/client/engine/step-runner.d.ts +24 -0
  122. package/dist/types/client/infra/notify/DomNotifyService.d.ts +2 -1
  123. package/dist/types/client/infra/notify/INotifyTheme.d.ts +1 -1
  124. package/dist/types/client/parser/{v2 → blocks}/page-parser.d.ts +2 -2
  125. package/dist/types/client/parser/{v2 → blocks}/use-parser.d.ts +3 -3
  126. package/dist/types/client/parser/duration.d.ts +1 -0
  127. package/dist/types/client/parser/layout-parser.d.ts +9 -0
  128. package/dist/types/client/parser/page-state-parser.d.ts +32 -0
  129. package/dist/types/client/parser/reaction-parser.d.ts +16 -0
  130. package/dist/types/client/parser/reaction-sugar.d.ts +13 -0
  131. package/dist/types/client/parser/step-parser.d.ts +23 -0
  132. package/dist/types/client/parser/style-config-parser.d.ts +1 -1
  133. package/dist/types/client/parser/ui-config-parser.d.ts +5 -0
  134. package/dist/types/client/parser/window-parser.d.ts +25 -0
  135. package/dist/types/client/registry/index.d.ts +1 -0
  136. package/dist/types/client/theme/theme-engine.d.ts +37 -0
  137. package/dist/types/index.d.ts +40 -9
  138. package/dist/types/server/host/published-page-assets.d.ts +3 -2
  139. package/dist/types/server/index.d.ts +1 -1
  140. package/dist/types/shared/block-errors.d.ts +5 -0
  141. package/dist/types/shared/calc/coerce.d.ts +4 -0
  142. package/dist/types/shared/calc/errors.d.ts +14 -0
  143. package/dist/types/shared/calc/evaluator.d.ts +2 -0
  144. package/dist/types/shared/calc/index.d.ts +6 -0
  145. package/dist/types/shared/calc/lexer.d.ts +20 -0
  146. package/dist/types/shared/calc/parser.d.ts +49 -0
  147. package/dist/types/shared/calc/typer.d.ts +16 -0
  148. package/dist/types/shared/path-algebra.d.ts +56 -0
  149. package/dist/types/shared/predicates/index.d.ts +79 -0
  150. package/dist/types/shared/published-page-route.d.ts +21 -0
  151. package/dist/types/shared/types/component-contract.types.d.ts +112 -0
  152. package/dist/types/shared/types/data-config.types.d.ts +132 -2
  153. package/dist/types/shared/types/domain.types.d.ts +12 -0
  154. package/dist/types/shared/types/event.types.d.ts +8 -2
  155. package/dist/types/shared/types/layout-constraint.types.d.ts +52 -0
  156. package/dist/types/shared/types/page-state.types.d.ts +49 -0
  157. package/dist/types/shared/types/reaction.types.d.ts +115 -0
  158. package/dist/types/shared/types/scope-manifest.types.d.ts +11 -11
  159. package/dist/types/shared/types/step.types.d.ts +76 -0
  160. package/dist/types/shared/types/style-config.types.d.ts +4 -4
  161. package/dist/types/shared/types/ui-config.types.d.ts +18 -0
  162. package/dist/types/shared/types/window.types.d.ts +171 -0
  163. package/package.json +2 -6
  164. package/dist/types/client/component/example-v2.d.ts +0 -9
  165. package/postcss.config.js +0 -6
  166. package/tailwind.config.ts +0 -43
  167. /package/dist/types/build/{v2 → blocks}/block-loader.d.ts +0 -0
  168. /package/dist/types/build/{v2 → blocks}/html-index.d.ts +0 -0
  169. /package/dist/types/client/parser/{v2 → blocks}/namespace.d.ts +0 -0
@@ -1,11 +1,11 @@
1
- // v2 解析 · page 块(REQ-005 F2)。
1
+ // 块解析 · page 块(REQ-005 F2)。
2
2
  //
3
- // **产出目标是 v1 等价的 UiConfig**——这是两级编译架构的关键:
4
- // v2 只是更好写的书写层,编译后交给既有引擎,运行时零新增、零感知。
3
+ // **产出目标是 平铺等价的 UiConfig**——这是两级编译架构的关键:
4
+ // 块声明只是更好写的书写层,编译后交给既有引擎,运行时零新增、零感知。
5
5
  //
6
6
  // 两处形状转换:
7
7
  // 平铺 → 嵌套:`锚点.when` / `锚点.class` 后缀键合并成一个 ExtendedShowValue;
8
- // each → bind:`each: 路径 as 变量 [by 路径]` 还原成 v1 的 NestedShowMapping。
8
+ // each → bind:`each: 路径 as 变量 [by 路径]` 还原成 平铺的 NestedShowMapping。
9
9
  //
10
10
  // 唯一的缩进理由是列表作用域——when 组与插槽内容一律平铺,
11
11
  // 因为编译器手里有 HTML,结构不需要 YAML 再复述一遍。
@@ -18,27 +18,35 @@ import type {
18
18
  UiConfig,
19
19
  } from '../../../shared/types/ui-config.types';
20
20
  import type { OnChangeRule } from '../../../shared/types/watcher.types';
21
- import { SomaV2ParseError } from '../../../build/v2/soma-file-loader';
21
+ import { SomaBlockParseError } from '../../../shared/block-errors';
22
22
  import { buildBlockScope, expandPath, type BlockScope } from './namespace';
23
23
 
24
24
  const PAGE_KEYS = new Set([
25
25
  'domain', 'locale', 'ui', 'watch', 'event', 'data', 'adaptive', 'alias',
26
- // initProps:引擎启动前写入的初始值(v1 UiConfig 同名字段的直通)。
26
+ // initProps:引擎启动前写入的初始值(平铺 UiConfig 同名字段的直通)。
27
27
  //
28
- // v2 是照**手写页面**设计的——那里文案住 HTML、初值住 Domain,声明里不需要它。
29
- // 但 v2 产的是 v1 等价物,而生成链的页面把字面文案内联在 initProps 里
28
+ // 块声明是照**手写页面**设计的——那里文案住 HTML、初值住 Domain,声明里不需要它。
29
+ // 但块声明产的是平铺等价物,而生成链的页面把字面文案内联在 initProps 里
30
30
  // (模型出的是组织意图,没有 Domain 可写)。少了这个键,AI 产的页面
31
- // 就永远迈不过 v2 的门槛——不是"用不上 v2",是"表达不了"。
31
+ // 就永远迈不过块声明的门槛——不是"用不上块声明",是"表达不了"。
32
32
  'initProps',
33
+ // state / layout(REQ-010 F-37 / S3,REQ-011 补接线):两个平铺 UiConfig 保留键的直通。
34
+ //
35
+ // 此前 PAGE_KEYS 没有它们——而 compilePageDeclaration 只收块声明,于是《声明语法手册》
36
+ // 里写着的 `state:` 在任何一张真正发布的页面上都写不进去("page 块不支持键 state"),
37
+ // 只有测试里直接喂平铺 YAML 的路径能用。文档承诺了一件真实页面做不到的事。
38
+ // 这里只直通原文;形状校验在 parseUiConfig(运行时)与 compilePageDeclaration(构建期)各做一次。
39
+ 'state',
40
+ 'layout',
33
41
  ]);
34
42
  /** 后缀键:平铺书写的高级绑定 */
35
43
  const SUFFIXES = ['when', 'model', 'class'] as const;
36
44
  type Suffix = (typeof SUFFIXES)[number];
37
45
 
38
46
  export interface PageBlockAst {
39
- /** v1 等价 UiConfig:直接交既有编译管线 */
47
+ /** 平铺等价 UiConfig:直接交既有编译管线 */
40
48
  ui: UiConfig;
41
- /** 事件段原文(交 pipeline-parser,形状与 v1 _event.yaml 一致) */
49
+ /** 事件段原文(交 pipeline-parser,形状与平铺 _event.yaml 一致) */
42
50
  eventRaw: Record<string, unknown>;
43
51
  /** 数据段原文(页面级共享对象,交数据对象层) */
44
52
  dataRaw?: Record<string, unknown>;
@@ -58,7 +66,7 @@ export interface ParsePageInput {
58
66
  export function parsePageBlock(input: ParsePageInput): PageBlockAst {
59
67
  const { body } = input;
60
68
  const fail = (message: string): never => {
61
- throw new SomaV2ParseError(message, 'page');
69
+ throw new SomaBlockParseError(message, 'page');
62
70
  };
63
71
 
64
72
  for (const key of Object.keys(body)) {
@@ -101,7 +109,7 @@ export function parsePageBlock(input: ParsePageInput): PageBlockAst {
101
109
  if (typeof uiRaw !== 'object' || Array.isArray(uiRaw)) fail('ui 段必须是映射');
102
110
  parseShowLevel(uiRaw, show, scope, input, 'page');
103
111
 
104
- // ── watch 段:v1 onChange 换位 ─────────────────────────────────────────
112
+ // ── watch 段:平铺 onChange 换位 ─────────────────────────────────────────
105
113
  const bind: BindDeclaration = { obj: String(domain), var: 'page' };
106
114
  const watch = body.watch;
107
115
  if (watch !== undefined) {
@@ -134,6 +142,12 @@ export function parsePageBlock(input: ParsePageInput): PageBlockAst {
134
142
  if (body.adaptive !== undefined) {
135
143
  ui.adaptive = body.adaptive as UiConfig['adaptive'];
136
144
  }
145
+ if (body.state !== undefined) {
146
+ ui.state = body.state as UiConfig['state'];
147
+ }
148
+ if (body.layout !== undefined) {
149
+ ui.layout = body.layout as UiConfig['layout'];
150
+ }
137
151
 
138
152
  // ── event 段:面向 DOM ─────────────────────────────────────────────────
139
153
  const eventRaw = normalizeEventSection(body.event, input, fail);
@@ -155,7 +169,7 @@ function parseShowLevel(
155
169
  where: string,
156
170
  ): void {
157
171
  const fail = (message: string): never => {
158
- throw new SomaV2ParseError(message, 'page');
172
+ throw new SomaBlockParseError(message, 'page');
159
173
  };
160
174
 
161
175
  for (const [key, value] of Object.entries(raw)) {
@@ -217,7 +231,7 @@ function isEachBlock(value: unknown): boolean {
217
231
  && typeof (value as Record<string, unknown>).each === 'string';
218
232
  }
219
233
 
220
- /** `each: 路径 as 变量 [by 路径] [key 字段]` → v1 NestedShowMapping */
234
+ /** `each: 路径 as 变量 [by 路径] [key 字段]` → 平铺 NestedShowMapping */
221
235
  function parseEachBlock(
222
236
  block: Record<string, unknown>,
223
237
  scope: BlockScope,
@@ -225,7 +239,7 @@ function parseEachBlock(
225
239
  anchor: string,
226
240
  ): ShowValue {
227
241
  const fail = (message: string): never => {
228
- throw new SomaV2ParseError(message, 'page');
242
+ throw new SomaBlockParseError(message, 'page');
229
243
  };
230
244
  const raw = String(block.each);
231
245
  const match = /^(\S+)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s+by\s+(\S+))?(?:\s+key\s+(\S+))?$/.exec(raw.trim());
@@ -1,14 +1,22 @@
1
- // v2 解析 · 组件块(REQ-005 F3)。
1
+ // 块解析 · 组件块(REQ-005 F3)。
2
2
  //
3
3
  // 一个实例 = 一个块,块体是该组件的**全部**:data(三通道 + 字段字典)、
4
4
  // ui(props / Row 体系)、event(actions 定义 + on 路由)。
5
5
  // 不自包含就是耦合——复杂场景一来三处拼装,复杂度没有地方搬进业务组件。
6
6
  //
7
- // 产出仍是 v1 等价物:props 进 UiConfig.show 的 ExtendedShowValue.props,
7
+ // 产出仍是 平铺等价物:props 进 UiConfig.show 的 ExtendedShowValue.props,
8
8
  // emit 路由进事件清单。soma-core 运行时对"块"一无所知,也不需要知道。
9
9
 
10
10
  import type { ExtendedShowValue } from '../../../shared/types/ui-config.types';
11
- import { SomaV2ParseError } from '../../../build/v2/soma-file-loader';
11
+ import { SomaBlockParseError } from '../../../shared/block-errors';
12
+ import { parseDuration } from '../duration';
13
+
14
+ // 时长解析搬到 `../duration`(client 侧);这里保留导出,既有导入不破
15
+ export { parseDuration };
16
+ import {
17
+ SOMA_DATA_FIELD_TYPES,
18
+ SOMA_DATA_FIELD_TYPE_ALIASES,
19
+ } from '../../../shared/types/data-config.types';
12
20
  import {
13
21
  buildBlockScope,
14
22
  expandPath,
@@ -23,11 +31,10 @@ const ACTION_KEYS = new Set([
23
31
  'label', 'handler', 'change', 'confirm', 'permission', 'tone', 'when', 'disabled_reason',
24
32
  ]);
25
33
  const FIELD_KEYS = new Set(['name', 'type', 'values', 'permission', 'rules']);
26
- const FIELD_TYPES = new Set([
27
- 'text', 'int', 'number', 'money', 'date', 'enum', 'bool', 'percent',
28
- // progress 与 percent 同数据两种读法:前者出进度条,后者出文字(见 soma-ui 类型渲染表)
29
- 'progress',
30
- ]);
34
+ // 字段类型不在这里再抄一份:唯一真源是 shared/types/data-config.types.ts 的
35
+ // SomaDataFieldType。此前这里手写了一套 9 型,与数据对象层的 11 型已经漂开——
36
+ // `type: url` 在块声明里被拒收,`type: percent` 能过解析器却在 soma-ui 侧没有映射。
37
+ const FIELD_TYPES = new Set(SOMA_DATA_FIELD_TYPES);
31
38
 
32
39
  export interface DataObjectDecl {
33
40
  localName: string;
@@ -78,7 +85,7 @@ export interface UseBlockAst {
78
85
  /** emit 路由:emit 名 → Pipeline 表达式 */
79
86
  emitRoutes: Record<string, string>;
80
87
  scope: BlockScope;
81
- /** 供 v1 编译管线消费的 props 形态 */
88
+ /** 供既有编译管线消费的 props 形态 */
82
89
  toShowValue(): ExtendedShowValue;
83
90
  }
84
91
 
@@ -94,7 +101,7 @@ export interface ParseUseInput {
94
101
  export function parseUseBlock(input: ParseUseInput): UseBlockAst {
95
102
  const { blockId, body } = input;
96
103
  const fail = (message: string): never => {
97
- throw new SomaV2ParseError(message, blockId);
104
+ throw new SomaBlockParseError(message, blockId);
98
105
  };
99
106
 
100
107
  for (const key of Object.keys(body)) {
@@ -255,10 +262,13 @@ function parseField(
255
262
  fail(`字段 ${objectName}.${fieldName} 不支持键 "${key}"(可用:${[...FIELD_KEYS].join('/')})`);
256
263
  }
257
264
  }
258
- const type = String(field.type ?? '');
259
- if (!FIELD_TYPES.has(type)) {
265
+ const declaredType = String(field.type ?? '');
266
+ // 别名归一(number → float):两边都有存量声明,所以两种拼写都收,
267
+ // 但产物里只留规范名,下游不必再判第二种写法
268
+ const type = SOMA_DATA_FIELD_TYPE_ALIASES[declaredType] ?? declaredType;
269
+ if (!FIELD_TYPES.has(declaredType)) {
260
270
  fail(
261
- `字段 ${objectName}.${fieldName} 的 type "${type}" 非法`
271
+ `字段 ${objectName}.${fieldName} 的 type "${declaredType}" 非法`
262
272
  + `(封闭集:${[...FIELD_TYPES].join('/')})`,
263
273
  );
264
274
  }
@@ -286,17 +296,6 @@ function parseField(
286
296
  };
287
297
  }
288
298
 
289
- /** `30s` → 30000;单位封闭 ms/s/m,无单位报错(不猜) */
290
- export function parseDuration(raw: string, where: string, fail: (m: string) => never): number {
291
- const match = /^(\d+(?:\.\d+)?)(ms|s|m)$/.exec(raw.trim());
292
- if (!match) {
293
- fail(`${where} 的时长 "${raw}" 非法——形如 500ms / 30s / 5m(单位必填,不猜)`);
294
- }
295
- const value = Number(match![1]);
296
- const unit = match![2];
297
- return unit === 'ms' ? value : unit === 's' ? value * 1000 : value * 60000;
298
- }
299
-
300
299
  function parseEventSection(
301
300
  raw: unknown,
302
301
  blockId: string,
@@ -356,7 +355,7 @@ function parseEventSection(
356
355
  return { actions, emitRoutes };
357
356
  }
358
357
 
359
- /** funcPath 不含点 → 自动补 page.(v1 onChange 既有先例) */
358
+ /** funcPath 不含点 → 自动补 page.(平铺 onChange 既有先例) */
360
359
  function withPageDefault(funcPath: string): string {
361
360
  return funcPath.includes('.') ? funcPath : `page.${funcPath}`;
362
361
  }
@@ -14,7 +14,24 @@ import type {
14
14
  SomaDataFieldType,
15
15
  SomaDataObjectConfig,
16
16
  SomaDataSourceConfig,
17
+ SomaDataWriteConfig,
18
+ SomaDataWriteEndpoint,
17
19
  } from '../../shared/types/data-config.types';
20
+ import {
21
+ SOMA_DATA_FIELD_TYPES,
22
+ SOMA_DATA_FIELD_TYPE_ALIASES,
23
+ } from '../../shared/types/data-config.types';
24
+ import { validateNamedPredicates } from '../../shared/predicates';
25
+ import { parseReactions } from './reaction-parser';
26
+ import { parseWindow } from './window-parser';
27
+ import {
28
+ assertCalcResultType,
29
+ collectCalcRefs,
30
+ inferCalcType,
31
+ parseCalc,
32
+ SomaCalcSyntaxError,
33
+ SomaCalcTypeError,
34
+ } from '../../shared/calc';
18
35
 
19
36
  // ─── 错误类 ───────────────────────────────────────────────────────────────────
20
37
 
@@ -31,10 +48,15 @@ export class SomaDataConfigError extends Error {
31
48
 
32
49
  // ─── 常量 ─────────────────────────────────────────────────────────────────────
33
50
 
34
- const VALID_FIELD_TYPES = new Set<SomaDataFieldType>([
35
- 'text', 'int', 'float', 'money', 'bool', 'enum',
36
- 'date', 'datetime', 'image', 'url', 'richtext',
37
- ]);
51
+ /**
52
+ * 合法字段类型:**直接消费唯一真源**,不再手抄一份。
53
+ *
54
+ * 此前这里是一份手写副本,而它已经漂了——真源加了 `percent` / `progress` 之后
55
+ * 这份没跟上,于是 `type: percent` 在块声明里能过、在 `_data.yaml` 里被拒收,
56
+ * 同一个词在同一个仓库里有两个答案。`data-config.types.ts` 的头注释写着
57
+ * 「这是字段类型的唯一真源」并点名了三份抄本;这里是被漏掉的第四份。
58
+ */
59
+ const VALID_FIELD_TYPES = new Set<string>(SOMA_DATA_FIELD_TYPES);
38
60
 
39
61
  const VALID_PERMISSIONS = new Set<SomaDataFieldPermission>(['r', 'w']);
40
62
 
@@ -277,13 +299,14 @@ function parseField(raw: unknown, path: string): SomaDataFieldConfig {
277
299
  }
278
300
  field.name = value;
279
301
  } else if (key === 'type') {
280
- if (typeof value !== 'string' || !VALID_FIELD_TYPES.has(value as SomaDataFieldType)) {
302
+ if (typeof value !== 'string' || !VALID_FIELD_TYPES.has(value)) {
281
303
  throw new SomaDataConfigError(
282
304
  `非法的字段类型 "${String(value)}"(支持: ${[...VALID_FIELD_TYPES].join(' / ')})`,
283
305
  `${path}.type`,
284
306
  );
285
307
  }
286
- field.type = value as SomaDataFieldType;
308
+ // 别名归一(`number` → `float`):词汇表只认一个概念,归一由解析器做
309
+ field.type = (SOMA_DATA_FIELD_TYPE_ALIASES[value] ?? value) as SomaDataFieldType;
287
310
  } else if (key === 'permission') {
288
311
  if (typeof value !== 'string' || !VALID_PERMISSIONS.has(value as SomaDataFieldPermission)) {
289
312
  throw new SomaDataConfigError(
@@ -299,9 +322,16 @@ function parseField(raw: unknown, path: string): SomaDataFieldConfig {
299
322
  field.rules = value.map((rule, index) => parseRule(rule, `${path}.rules[${index}]`));
300
323
  } else if (key === 'options') {
301
324
  field.options = parseOptions(value, `${path}.options`);
325
+ } else if (key === 'calc') {
326
+ if (typeof value !== 'string' || value.trim() === '') {
327
+ throw new SomaDataConfigError('calc 必须是非空表达式字符串', `${path}.calc`);
328
+ }
329
+ // 表达式本身在这里还校验不了:它引用的是**兄弟字段**,而兄弟还没解析完。
330
+ // 留到 validateDerivedFields 那一遍统一对账。
331
+ field.calc = value;
302
332
  } else {
303
333
  throw new SomaDataConfigError(
304
- `未知的字典字段 "${key}"(支持: name / type / permission / rules / options)`,
334
+ `未知的字典字段 "${key}"(支持: name / type / permission / rules / options / calc)`,
305
335
  `${path}.${key}`,
306
336
  );
307
337
  }
@@ -309,6 +339,219 @@ function parseField(raw: unknown, path: string): SomaDataFieldConfig {
309
339
  return field;
310
340
  }
311
341
 
342
+ /** 派生列能落进哪些字段类型——与 calc 的结果类型对账表同源 */
343
+ const CALC_WRITABLE_TYPES = new Set([
344
+ 'int', 'float', 'money', 'percent', 'progress', 'text', 'url', 'enum', 'date', 'datetime',
345
+ ]);
346
+
347
+ /**
348
+ * 派生列对账(REQ-010 F-10):表达式引用的字段要在同一本字典里,
349
+ * 推出来的结果类型要与声明的 `type` 一致,且派生列之间不能成环。
350
+ *
351
+ * 权限在这里被**强制**改成 `r`:一个算出来的字段如果还开着编辑口,用户改完保存,
352
+ * 后端存下来,下一次取数又被表达式覆盖回去——数据看上去随机丢失,且没有任何报错。
353
+ * 与其在文档里写「记得设成只读」,不如让它没有第二种可能。
354
+ */
355
+ function validateDerivedFields(
356
+ fields: Record<string, SomaDataFieldConfig>,
357
+ path: string,
358
+ ): void {
359
+ const derived = Object.keys(fields).filter((key) => fields[key].calc !== undefined);
360
+ if (derived.length === 0) return;
361
+
362
+ const fieldTypes: Record<string, string | undefined> = Object.fromEntries(
363
+ Object.keys(fields).map((key) => [key, fields[key].type]),
364
+ );
365
+ const refsOf: Record<string, string[]> = {};
366
+
367
+ for (const key of derived) {
368
+ const at = `${path}.${key}.calc`;
369
+ const source = fields[key].calc!;
370
+ const declared = fields[key].type ?? 'text';
371
+ if (!CALC_WRITABLE_TYPES.has(declared)) {
372
+ throw new SomaDataConfigError(
373
+ `calc 算不出 ${declared} 类型的值(字段 "${key}")`,
374
+ at,
375
+ );
376
+ }
377
+ try {
378
+ const node = parseCalc(source);
379
+ const ctx = { fieldTypes, source };
380
+ assertCalcResultType(inferCalcType(node, ctx), declared, ctx, node);
381
+ const refs = collectCalcRefs(node);
382
+ for (const ref of refs) {
383
+ if (!(ref in fields)) {
384
+ throw new SomaDataConfigError(
385
+ `calc 引用了不存在的字段 "${ref}"(本对象字典:${Object.keys(fields).join(' / ')})`,
386
+ at,
387
+ );
388
+ }
389
+ if (ref === key) {
390
+ throw new SomaDataConfigError(`calc 引用了它自己(字段 "${key}")`, at);
391
+ }
392
+ }
393
+ refsOf[key] = refs;
394
+ } catch (error) {
395
+ if (error instanceof SomaCalcSyntaxError || error instanceof SomaCalcTypeError) {
396
+ throw new SomaDataConfigError(error.message, at);
397
+ }
398
+ throw error;
399
+ }
400
+ // 权限恒为 r:见上文
401
+ fields[key].permission = 'r';
402
+ }
403
+
404
+ // 派生列之间成环(profit 引用 margin、margin 引用 profit):求值会无限递归。
405
+ // 深度优先找回边,报错要打印整条路径——只说"成环了",作者得自己去把链条走一遍。
406
+ const state: Record<string, 'visiting' | 'done'> = {};
407
+ const stack: string[] = [];
408
+ const walk = (key: string): void => {
409
+ if (state[key] === 'done') return;
410
+ if (state[key] === 'visiting') {
411
+ const from = stack.indexOf(key);
412
+ throw new SomaDataConfigError(
413
+ `派生列成环:${[...stack.slice(from), key].join(' → ')}`,
414
+ `${path}.${key}.calc`,
415
+ );
416
+ }
417
+ state[key] = 'visiting';
418
+ stack.push(key);
419
+ for (const ref of refsOf[key] ?? []) {
420
+ if (refsOf[ref] !== undefined) walk(ref);
421
+ }
422
+ stack.pop();
423
+ state[key] = 'done';
424
+ };
425
+ for (const key of derived) walk(key);
426
+ }
427
+
428
+ const WRITE_METHODS = new Set(['POST', 'PUT', 'PATCH']);
429
+
430
+ /**
431
+ * 解析写通道声明(§8.7 声明期闸门,fail fast 不吞)。
432
+ *
433
+ * 为什么这些都要在声明期拦:写通道的错法全部是**静默**的——
434
+ * map 指向一个不存在的字段,请求体里就少一个键,后端收到一份不完整的数据仍会返回 200;
435
+ * version 指错字段,乐观锁形同虚设;reload 指向不存在的对象,提交后页面不刷新。
436
+ * 这几类在运行期都不报错,只是数据悄悄错了。
437
+ */
438
+ function parseWrite(
439
+ raw: unknown,
440
+ fields: Record<string, SomaDataFieldConfig>,
441
+ path: string,
442
+ objectNames: Set<string>,
443
+ ): SomaDataWriteConfig {
444
+ assertPlainObject(raw, 'write', path);
445
+ const write: SomaDataWriteConfig = {};
446
+
447
+ for (const [key, value] of Object.entries(raw)) {
448
+ if (key === 'create' || key === 'update') {
449
+ write[key] = parseWriteEndpoint(value, `${path}.${key}`);
450
+ } else if (key === 'version') {
451
+ if (typeof value !== 'string' || !value.trim()) {
452
+ throw new SomaDataConfigError('version 必须是非空字段名', `${path}.version`);
453
+ }
454
+ if (!(value in fields)) {
455
+ throw new SomaDataConfigError(
456
+ `version 指向字段 "${value}",但字典里没有它`
457
+ + '(乐观锁位必须在字典里声明,否则它不会随请求体上行)',
458
+ `${path}.version`,
459
+ );
460
+ }
461
+ write.version = value;
462
+ } else if (key === 'map') {
463
+ assertPlainObject(value, 'map', `${path}.map`);
464
+ const map: Record<string, string> = {};
465
+ for (const [formKey, bodyKey] of Object.entries(value)) {
466
+ if (!(formKey in fields)) {
467
+ throw new SomaDataConfigError(
468
+ `map 的键 "${formKey}" 不在字典里(只能给声明过的字段改名)`,
469
+ `${path}.map.${formKey}`,
470
+ );
471
+ }
472
+ if (fields[formKey].permission === 'r') {
473
+ throw new SomaDataConfigError(
474
+ `map 的键 "${formKey}" 是只读字段(permission: r)——只读字段不进请求体,改名没有意义`,
475
+ `${path}.map.${formKey}`,
476
+ );
477
+ }
478
+ if (typeof bodyKey !== 'string' || !bodyKey.trim()) {
479
+ throw new SomaDataConfigError(`map 的值必须是非空的请求体键名`, `${path}.map.${formKey}`);
480
+ }
481
+ map[formKey] = bodyKey;
482
+ }
483
+ write.map = map;
484
+ } else if (key === 'only') {
485
+ if (!Array.isArray(value) || value.length === 0) {
486
+ throw new SomaDataConfigError('only 必须是非空字段名数组', `${path}.only`);
487
+ }
488
+ for (const fieldKey of value) {
489
+ if (typeof fieldKey !== 'string' || !(fieldKey in fields)) {
490
+ throw new SomaDataConfigError(
491
+ `only 里的 "${String(fieldKey)}" 不在字段字典里`
492
+ + `(本对象字典:${Object.keys(fields).join(' / ') || '空'})`,
493
+ `${path}.only`,
494
+ );
495
+ }
496
+ }
497
+ write.only = (value as unknown[]).map(String);
498
+ } else if (key === 'reload') {
499
+ if (value === 'self' || value === 'all') {
500
+ write.reload = value;
501
+ } else if (Array.isArray(value)) {
502
+ for (const objectName of value) {
503
+ if (typeof objectName !== 'string' || !objectNames.has(objectName)) {
504
+ throw new SomaDataConfigError(
505
+ `reload 指向数据对象 "${String(objectName)}",但本页没有声明它`,
506
+ `${path}.reload`,
507
+ );
508
+ }
509
+ }
510
+ write.reload = [...value];
511
+ } else {
512
+ throw new SomaDataConfigError(
513
+ `reload 必须是 'self' / 'all' / 数据对象名数组`,
514
+ `${path}.reload`,
515
+ );
516
+ }
517
+ } else {
518
+ throw new SomaDataConfigError(
519
+ `未知的 write 字段 "${key}"(支持: create / update / version / map / only / reload)`,
520
+ `${path}.${key}`,
521
+ );
522
+ }
523
+ }
524
+
525
+ if (!write.create && !write.update) {
526
+ throw new SomaDataConfigError(
527
+ 'write 至少要声明 create 或 update 之一(两个都没有的写通道不写任何东西)',
528
+ path,
529
+ );
530
+ }
531
+ return write;
532
+ }
533
+
534
+ function parseWriteEndpoint(raw: unknown, path: string): SomaDataWriteEndpoint {
535
+ assertPlainObject(raw, '写端点', path);
536
+ const api = (raw as Record<string, unknown>).api;
537
+ const method = (raw as Record<string, unknown>).method ?? 'POST';
538
+ if (typeof api !== 'string' || !api.trim()) {
539
+ throw new SomaDataConfigError('写端点缺少 api(后端接口是唯一数据边界)', `${path}.api`);
540
+ }
541
+ if (typeof method !== 'string' || !WRITE_METHODS.has(method)) {
542
+ throw new SomaDataConfigError(
543
+ `method "${String(method)}" 不在白名单内(POST / PUT / PATCH)`,
544
+ `${path}.method`,
545
+ );
546
+ }
547
+ for (const key of Object.keys(raw as Record<string, unknown>)) {
548
+ if (key !== 'api' && key !== 'method') {
549
+ throw new SomaDataConfigError(`未知的写端点字段 "${key}"(支持: api / method)`, `${path}.${key}`);
550
+ }
551
+ }
552
+ return { api, method: method as SomaDataWriteEndpoint['method'] };
553
+ }
554
+
312
555
  function parseObject(
313
556
  name: string,
314
557
  raw: unknown,
@@ -322,6 +565,10 @@ function parseObject(
322
565
 
323
566
  const deps = new Set<string>();
324
567
  const config: SomaDataObjectConfig = { name, from: [], deps: [] };
568
+ let writeRaw: unknown;
569
+ let predicatesRaw: unknown;
570
+ let reactionsRaw: unknown;
571
+ let windowRaw: unknown;
325
572
 
326
573
  for (const [key, value] of Object.entries(raw)) {
327
574
  if (key === 'from') {
@@ -339,17 +586,78 @@ function parseObject(
339
586
  for (const [fieldName, fieldRaw] of Object.entries(value)) {
340
587
  fields[fieldName] = parseField(fieldRaw, `${path}.fields.${fieldName}`);
341
588
  }
589
+ validateDerivedFields(fields, `${path}.fields`);
342
590
  config.fields = fields;
343
591
  } else if (key === 'mock') {
344
592
  config.mock = value;
593
+ } else if (key === 'write') {
594
+ writeRaw = value;
595
+ } else if (key === 'predicates') {
596
+ predicatesRaw = value;
597
+ } else if (key === 'reactions') {
598
+ reactionsRaw = value;
599
+ } else if (key === 'window') {
600
+ windowRaw = value;
345
601
  } else {
346
602
  throw new SomaDataConfigError(
347
- `未知的声明字段 "${key}"(支持: from / transform / fields / mock)`,
603
+ `未知的声明字段 "${key}"(支持: from / transform / fields / mock / write / predicates / reactions / window)`,
348
604
  `${path}.${key}`,
349
605
  );
350
606
  }
351
607
  }
352
608
 
609
+ // write / predicates / reactions 都必须在 fields 之后解析:它们的每条规则都要对着字典校验
610
+ if (writeRaw !== undefined) {
611
+ config.write = parseWrite(writeRaw, config.fields ?? {}, `${path}.write`, objectNames);
612
+ }
613
+
614
+ // 具名谓词表(REQ-010 S1b):一条判断声明一次,多处 { ref } 复用
615
+ const fields = config.fields ?? {};
616
+ const fieldKeys = Object.keys(fields);
617
+ const fieldTypes: Record<string, string | undefined> = Object.fromEntries(
618
+ fieldKeys.map((key) => [key, fields[key].type]),
619
+ );
620
+ if (predicatesRaw !== undefined) {
621
+ const issues = validateNamedPredicates(predicatesRaw, fieldKeys, fieldTypes);
622
+ if (issues.length > 0) {
623
+ throw new SomaDataConfigError(issues.join(';'), `${path}.predicates`);
624
+ }
625
+ config.predicates = predicatesRaw as SomaDataObjectConfig['predicates'];
626
+ }
627
+
628
+ if (reactionsRaw !== undefined) {
629
+ config.reactions = parseReactions(
630
+ {
631
+ raw: reactionsRaw,
632
+ fields,
633
+ named: config.predicates ?? {},
634
+ // 回溯表要知道每个字段来自哪个接口。字段与接口的对应在声明里是隐式的
635
+ // (一个 from 拉回来一整个对象),所以退而记「本对象的第一个接口」——
636
+ // 比不给强:排障时至少知道该去看哪个接口。
637
+ sourceApiOf: Object.fromEntries(fieldKeys.map((key) => [key, config.from[0]?.api])),
638
+ path: `${path}.reactions`,
639
+ },
640
+ {
641
+ fail(message: string, at: string): never {
642
+ throw new SomaDataConfigError(message, at);
643
+ },
644
+ },
645
+ );
646
+ }
647
+
648
+ // 数据窗口(REQ-010 S2):同样要字典就位——过滤叶子的算子要与字段类型配对,
649
+ // 聚合函数要与字段类型配对,字典哈希本身就是字典算出来的
650
+ if (windowRaw !== undefined) {
651
+ config.window = parseWindow(
652
+ { raw: windowRaw, fields, path: `${path}.window` },
653
+ {
654
+ fail(message: string, at: string): never {
655
+ throw new SomaDataConfigError(message, at);
656
+ },
657
+ },
658
+ );
659
+ }
660
+
353
661
  // 无接口预览对象:允许缺省 from,但必须提供 mock 样本兜底
354
662
  if (config.from.length === 0 && config.mock === undefined) {
355
663
  throw new SomaDataConfigError(`缺少 from 取数来源(仅声明 mock 样本的预览对象可省略)`, `${path}.from`);
@@ -0,0 +1,16 @@
1
+ // 时长字面量解析——`30s` → 30000。单位闭集 ms / s / m,无单位报错(不猜)。
2
+ //
3
+ // 单独成文件是为了守住 client / build 边界:`window-parser`(client)此前从
4
+ // `blocks/use-parser` 借这个函数,而 use-parser 引着 build 侧的 `SomaBlockParseError`——
5
+ // 于是运行时依赖图里出现一条 client → build 的边,`verify:client-boundary` 一直红着。
6
+ // 同一个函数被两边用,就把它放在两边都能引的地方。
7
+
8
+ export function parseDuration(raw: string, where: string, fail: (m: string) => never): number {
9
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m)$/.exec(raw.trim());
10
+ if (!match) {
11
+ fail(`${where} 的时长 "${raw}" 非法——形如 500ms / 30s / 5m(单位必填,不猜)`);
12
+ }
13
+ const value = Number(match![1]);
14
+ const unit = match![2];
15
+ return unit === 'ms' ? value : unit === 's' ? value * 1000 : value * 60000;
16
+ }