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
@@ -18,7 +18,7 @@ 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 { SomaBlockParseError } from '../../../build/blocks/block-container';
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([
@@ -30,6 +30,14 @@ const PAGE_KEYS = new Set([
30
30
  // (模型出的是组织意图,没有 Domain 可写)。少了这个键,AI 产的页面
31
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;
@@ -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);
@@ -8,7 +8,11 @@
8
8
  // emit 路由进事件清单。soma-core 运行时对"块"一无所知,也不需要知道。
9
9
 
10
10
  import type { ExtendedShowValue } from '../../../shared/types/ui-config.types';
11
- import { SomaBlockParseError } from '../../../build/blocks/block-container';
11
+ import { SomaBlockParseError } from '../../../shared/block-errors';
12
+ import { parseDuration } from '../duration';
13
+
14
+ // 时长解析搬到 `../duration`(client 侧);这里保留导出,既有导入不破
15
+ export { parseDuration };
12
16
  import {
13
17
  SOMA_DATA_FIELD_TYPES,
14
18
  SOMA_DATA_FIELD_TYPE_ALIASES,
@@ -292,17 +296,6 @@ function parseField(
292
296
  };
293
297
  }
294
298
 
295
- /** `30s` → 30000;单位封闭 ms/s/m,无单位报错(不猜) */
296
- export function parseDuration(raw: string, where: string, fail: (m: string) => never): number {
297
- const match = /^(\d+(?:\.\d+)?)(ms|s|m)$/.exec(raw.trim());
298
- if (!match) {
299
- fail(`${where} 的时长 "${raw}" 非法——形如 500ms / 30s / 5m(单位必填,不猜)`);
300
- }
301
- const value = Number(match![1]);
302
- const unit = match![2];
303
- return unit === 'ms' ? value : unit === 's' ? value * 1000 : value * 60000;
304
- }
305
-
306
299
  function parseEventSection(
307
300
  raw: unknown,
308
301
  blockId: string,
@@ -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
+ }
@@ -0,0 +1,157 @@
1
+ // `layout:` 段解析(REQ-010 S3)——约束布局的声明入口。
2
+ //
3
+ // 词汇是闭集(sizing 三档、priority 四档、wrap 三档、align 七档),
4
+ // 所以「这个布局解不解得出」在**声明期**就有答案:求解器对八档容器宽各解一次,
5
+ // 任一档不可满足就当场指出是哪两条声明打架。
6
+ //
7
+ // 对比手写容器查询:作者要在四五段查询里各写一遍 flex 值,段与段之间的一致性靠人维护,
8
+ // 而它们坏起来是"某一档下侧栏比 min 还窄"——只有把窗口拖到那一档才看得见。
9
+
10
+ import {
11
+ SOMA_LAYOUT_ALIGNS,
12
+ SOMA_LAYOUT_PRIORITIES,
13
+ type SomaAlign,
14
+ type SomaLayoutConstraint,
15
+ type SomaLayoutNodeConstraint,
16
+ type SomaPriority,
17
+ type SomaSizing,
18
+ type SomaWrap,
19
+ } from '../../shared/types/layout-constraint.types';
20
+
21
+ export interface LayoutParseInput {
22
+ raw: unknown;
23
+ path: string;
24
+ }
25
+
26
+ export interface LayoutParseDeps {
27
+ fail(message: string, path: string): never;
28
+ }
29
+
30
+ const SIZINGS = new Set<string>(['fixed', 'hug', 'fill']);
31
+ const WRAPS = new Set<string>(['none', 'below', 'reel']);
32
+ const NODE_KEYS = new Set(['sizing', 'width', 'min', 'max', 'priority']);
33
+ const SECTION_KEYS = new Set(['gap', 'wrap', 'align', 'container_name', 'nodes']);
34
+ const NAME_PATTERN = /^[a-z][a-z0-9_]*$/;
35
+
36
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
37
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
38
+ }
39
+
40
+ export function parseLayoutConstraint(
41
+ input: LayoutParseInput,
42
+ deps: LayoutParseDeps,
43
+ ): SomaLayoutConstraint {
44
+ const { raw, path } = input;
45
+ const fail: (message: string, at: string) => never = deps.fail;
46
+
47
+ if (!isPlainObject(raw)) fail('layout 必须是映射', path);
48
+
49
+ // 两种写法:显式 `nodes: { … }`,或把子项直接摊在段上(更常见也更短)。
50
+ // 摊平写法要把已知的段级键排除掉——否则 `gap` 会被当成一个叫 gap 的子项,
51
+ // 而那个"子项"没有 sizing,报错会指向一个作者根本没写的东西。
52
+ const explicit = isPlainObject(raw.nodes) ? (raw.nodes as Record<string, unknown>) : null;
53
+ const source = explicit ?? Object.fromEntries(
54
+ Object.entries(raw).filter(([key]) => !SECTION_KEYS.has(key)),
55
+ );
56
+
57
+ if (explicit === null) {
58
+ for (const key of Object.keys(raw)) {
59
+ if (SECTION_KEYS.has(key)) continue;
60
+ if (!NAME_PATTERN.test(key)) {
61
+ fail(
62
+ `${path}.${key} 既不是段级键(${[...SECTION_KEYS].join(' / ')}),`
63
+ + '也不是合法子项名(小写字母开头、下划线分隔)',
64
+ `${path}.${key}`,
65
+ );
66
+ }
67
+ }
68
+ }
69
+
70
+ const nodes: Record<string, SomaLayoutNodeConstraint> = {};
71
+ for (const [name, rawNode] of Object.entries(source)) {
72
+ const at = `${path}.${name}`;
73
+ if (!isPlainObject(rawNode)) fail(`${at} 必须是映射`, at);
74
+ for (const key of Object.keys(rawNode)) {
75
+ if (!NODE_KEYS.has(key)) {
76
+ fail(`${at} 有未知键 "${key}"(支持: ${[...NODE_KEYS].join(' / ')})`, `${at}.${key}`);
77
+ }
78
+ }
79
+ const sizing = String(rawNode.sizing ?? '');
80
+ if (!SIZINGS.has(sizing)) {
81
+ fail(
82
+ `${at}.sizing 只能是 ${[...SIZINGS].join(' / ')}(收到 ${JSON.stringify(rawNode.sizing)})`
83
+ + '——fixed 是"就这么宽",hug 是"内容多宽我多宽",fill 是"剩下的给我"',
84
+ `${at}.sizing`,
85
+ );
86
+ }
87
+ const node: SomaLayoutNodeConstraint = { sizing: sizing as SomaSizing };
88
+ for (const key of ['width', 'min', 'max'] as const) {
89
+ if (rawNode[key] === undefined) continue;
90
+ const literal = String(rawNode[key]);
91
+ if (!/^\d+(?:\.\d+)?(rem|%|cqi)$/.test(literal)) {
92
+ fail(
93
+ `${at}.${key} 的长度 "${literal}" 非法——只认 rem / % / cqi(单位必填,不猜)`,
94
+ `${at}.${key}`,
95
+ );
96
+ }
97
+ node[key] = literal;
98
+ }
99
+ if (rawNode.priority !== undefined) {
100
+ const priority = Number(rawNode.priority);
101
+ if (!(SOMA_LAYOUT_PRIORITIES as readonly number[]).includes(priority)) {
102
+ fail(
103
+ `${at}.priority 只能是 ${SOMA_LAYOUT_PRIORITIES.join(' / ')}(收到 ${String(rawNode.priority)})`
104
+ + '——250 是"我愿意被拉大",750 是"我不愿意被压小",1000 是不可违反',
105
+ `${at}.priority`,
106
+ );
107
+ }
108
+ node.priority = priority as SomaPriority;
109
+ }
110
+ nodes[name] = node;
111
+ }
112
+
113
+ if (Object.keys(nodes).length === 0) {
114
+ fail(`${path} 至少要有一个子项`, path);
115
+ }
116
+
117
+ const constraint: SomaLayoutConstraint = { nodes };
118
+
119
+ if (raw.gap !== undefined) {
120
+ const gap = String(raw.gap);
121
+ if (!/^\d+(?:\.\d+)?(rem|%|cqi)$/.test(gap)) {
122
+ fail(`${path}.gap 的长度 "${gap}" 非法——只认 rem / % / cqi`, `${path}.gap`);
123
+ }
124
+ constraint.gap = gap;
125
+ }
126
+ if (raw.wrap !== undefined) {
127
+ const wrap = String(raw.wrap);
128
+ if (!WRAPS.has(wrap)) {
129
+ fail(`${path}.wrap 只能是 ${[...WRAPS].join(' / ')}(收到 ${JSON.stringify(raw.wrap)})`, `${path}.wrap`);
130
+ }
131
+ constraint.wrap = wrap as SomaWrap;
132
+ }
133
+ if (raw.align !== undefined) {
134
+ const align = String(raw.align);
135
+ if (!(SOMA_LAYOUT_ALIGNS as readonly string[]).includes(align)) {
136
+ fail(
137
+ `${path}.align 只能是 ${SOMA_LAYOUT_ALIGNS.join(' / ')}(收到 ${JSON.stringify(raw.align)})`,
138
+ `${path}.align`,
139
+ );
140
+ }
141
+ constraint.align = align as SomaAlign;
142
+ }
143
+ if (raw.container_name !== undefined) {
144
+ const containerName = String(raw.container_name);
145
+ // 具名容器要能被子孙的 `@container <name> (…)` 引用,所以它必须是一个合法的 CSS 标识符
146
+ if (!/^[a-z][a-z0-9-]*$/.test(containerName)) {
147
+ fail(
148
+ `${path}.container_name "${containerName}" 不是合法的容器名`
149
+ + '(小写字母开头、连字符分隔;它要出现在 CSS 的 container-name 上)',
150
+ `${path}.container_name`,
151
+ );
152
+ }
153
+ constraint.container_name = containerName;
154
+ }
155
+
156
+ return constraint;
157
+ }