soma-core 1.4.0 → 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 (121) 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 +2041 -19
  6. package/core/build/component/component-graph.ts +208 -0
  7. package/core/build/eject/component-eject.ts +473 -0
  8. package/core/build/eject/component-upgrade.ts +359 -0
  9. package/core/build/layout/constraint-solver.ts +235 -0
  10. package/core/build/layout/css-emitter.ts +116 -0
  11. package/core/build/layout/page-layout.ts +85 -0
  12. package/core/build/pack/pack-init.ts +265 -0
  13. package/core/client/base/SomaPageRootBase.ts +61 -0
  14. package/core/client/component/ai-catalog.ts +79 -4
  15. package/core/client/component/component-defaults.ts +100 -0
  16. package/core/client/component/component-definition.types.ts +39 -0
  17. package/core/client/component/component-manager.ts +79 -4
  18. package/core/client/component/component-pack.ts +126 -2
  19. package/core/client/component/keyboard-matrix.ts +144 -0
  20. package/core/client/component/pack-styles.ts +59 -1
  21. package/core/client/component/style-features.ts +131 -0
  22. package/core/client/component/theme-component-tokens.ts +83 -0
  23. package/core/client/data/data-object-resolver.ts +407 -4
  24. package/core/client/data/reaction-engine.ts +176 -0
  25. package/core/client/data/window-engine.ts +477 -0
  26. package/core/client/engine/event-engine.ts +98 -0
  27. package/core/client/engine/soma-bootstrap.ts +265 -5
  28. package/core/client/engine/step-runner.ts +134 -0
  29. package/core/client/parser/blocks/page-parser.ts +15 -1
  30. package/core/client/parser/blocks/use-parser.ts +5 -12
  31. package/core/client/parser/data-config-parser.ts +316 -8
  32. package/core/client/parser/duration.ts +16 -0
  33. package/core/client/parser/layout-parser.ts +157 -0
  34. package/core/client/parser/page-state-parser.ts +166 -0
  35. package/core/client/parser/pipeline-parser.ts +76 -1
  36. package/core/client/parser/reaction-parser.ts +459 -0
  37. package/core/client/parser/reaction-sugar.ts +47 -0
  38. package/core/client/parser/step-parser.ts +359 -0
  39. package/core/client/parser/ui-config-parser.ts +59 -0
  40. package/core/client/parser/window-parser.ts +294 -0
  41. package/core/client/theme/theme-engine.ts +102 -2
  42. package/core/index.ts +163 -0
  43. package/core/shared/block-errors.ts +11 -0
  44. package/core/shared/calc/coerce.ts +29 -0
  45. package/core/shared/calc/errors.ts +43 -0
  46. package/core/shared/calc/evaluator.ts +101 -0
  47. package/core/shared/calc/index.ts +12 -0
  48. package/core/shared/calc/lexer.ts +194 -0
  49. package/core/shared/calc/parser.ts +204 -0
  50. package/core/shared/calc/typer.ts +184 -0
  51. package/core/shared/path-algebra.ts +169 -0
  52. package/core/shared/predicates/index.ts +527 -0
  53. package/core/shared/types/component-contract.types.ts +128 -2
  54. package/core/shared/types/data-config.types.ts +120 -1
  55. package/core/shared/types/domain.types.ts +13 -0
  56. package/core/shared/types/event.types.ts +22 -2
  57. package/core/shared/types/layout-constraint.types.ts +73 -0
  58. package/core/shared/types/page-state.types.ts +60 -0
  59. package/core/shared/types/reaction.types.ts +144 -0
  60. package/core/shared/types/step.types.ts +91 -0
  61. package/core/shared/types/ui-config.types.ts +18 -0
  62. package/core/shared/types/window.types.ts +177 -0
  63. package/dist/cli/soma.js +13 -1
  64. package/dist/core/index.cjs +4684 -349
  65. package/dist/types/build/blocks/block-container.d.ts +1 -6
  66. package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -0
  67. package/dist/types/build/component/component-graph.d.ts +85 -0
  68. package/dist/types/build/eject/component-eject.d.ts +121 -0
  69. package/dist/types/build/eject/component-upgrade.d.ts +43 -0
  70. package/dist/types/build/layout/constraint-solver.d.ts +36 -0
  71. package/dist/types/build/layout/css-emitter.d.ts +18 -0
  72. package/dist/types/build/layout/page-layout.d.ts +24 -0
  73. package/dist/types/build/pack/pack-init.d.ts +8 -0
  74. package/dist/types/client/base/SomaPageRootBase.d.ts +28 -0
  75. package/dist/types/client/component/ai-catalog.d.ts +24 -1
  76. package/dist/types/client/component/component-defaults.d.ts +15 -0
  77. package/dist/types/client/component/component-definition.types.d.ts +38 -0
  78. package/dist/types/client/component/component-manager.d.ts +36 -0
  79. package/dist/types/client/component/component-pack.d.ts +32 -2
  80. package/dist/types/client/component/keyboard-matrix.d.ts +24 -0
  81. package/dist/types/client/component/pack-styles.d.ts +21 -0
  82. package/dist/types/client/component/style-features.d.ts +26 -0
  83. package/dist/types/client/component/theme-component-tokens.d.ts +14 -0
  84. package/dist/types/client/data/data-object-resolver.d.ts +106 -1
  85. package/dist/types/client/data/reaction-engine.d.ts +21 -0
  86. package/dist/types/client/data/window-engine.d.ts +27 -0
  87. package/dist/types/client/engine/event-engine.d.ts +15 -0
  88. package/dist/types/client/engine/soma-bootstrap.d.ts +70 -0
  89. package/dist/types/client/engine/step-runner.d.ts +24 -0
  90. package/dist/types/client/parser/blocks/use-parser.d.ts +2 -2
  91. package/dist/types/client/parser/duration.d.ts +1 -0
  92. package/dist/types/client/parser/layout-parser.d.ts +9 -0
  93. package/dist/types/client/parser/page-state-parser.d.ts +32 -0
  94. package/dist/types/client/parser/reaction-parser.d.ts +16 -0
  95. package/dist/types/client/parser/reaction-sugar.d.ts +13 -0
  96. package/dist/types/client/parser/step-parser.d.ts +23 -0
  97. package/dist/types/client/parser/ui-config-parser.d.ts +5 -0
  98. package/dist/types/client/parser/window-parser.d.ts +25 -0
  99. package/dist/types/client/theme/theme-engine.d.ts +26 -0
  100. package/dist/types/index.d.ts +32 -2
  101. package/dist/types/shared/block-errors.d.ts +5 -0
  102. package/dist/types/shared/calc/coerce.d.ts +4 -0
  103. package/dist/types/shared/calc/errors.d.ts +14 -0
  104. package/dist/types/shared/calc/evaluator.d.ts +2 -0
  105. package/dist/types/shared/calc/index.d.ts +6 -0
  106. package/dist/types/shared/calc/lexer.d.ts +20 -0
  107. package/dist/types/shared/calc/parser.d.ts +49 -0
  108. package/dist/types/shared/calc/typer.d.ts +16 -0
  109. package/dist/types/shared/path-algebra.d.ts +56 -0
  110. package/dist/types/shared/predicates/index.d.ts +79 -0
  111. package/dist/types/shared/types/component-contract.types.d.ts +112 -0
  112. package/dist/types/shared/types/data-config.types.d.ts +115 -1
  113. package/dist/types/shared/types/domain.types.d.ts +12 -0
  114. package/dist/types/shared/types/event.types.d.ts +8 -2
  115. package/dist/types/shared/types/layout-constraint.types.d.ts +52 -0
  116. package/dist/types/shared/types/page-state.types.d.ts +49 -0
  117. package/dist/types/shared/types/reaction.types.d.ts +115 -0
  118. package/dist/types/shared/types/step.types.d.ts +76 -0
  119. package/dist/types/shared/types/ui-config.types.d.ts +18 -0
  120. package/dist/types/shared/types/window.types.d.ts +171 -0
  121. package/package.json +2 -1
@@ -34,11 +34,24 @@ import { createDefaultRuntimeServices } from '../runtime/SomaRuntimeServices';
34
34
  import { getBrowserUrlPath, readQueryParam } from '../infra/router/router-path';
35
35
  import { parseDataYaml } from '../parser/data-config-parser';
36
36
  import { SomaDataObjectResolver } from '../data/data-object-resolver';
37
+ import type {
38
+ SomaDataPort,
39
+ SomaDataSubmitResult,
40
+ } from '../../shared/types/data-config.types';
37
41
  import type { SomaDataConfig, SomaDataDicts } from '../../shared/types/data-config.types';
38
42
  import type { WatchCallback, WatcherOptions } from '../../shared/types/watcher.types';
43
+ import type { SomaStepGraph } from '../../shared/types/step.types';
44
+ import type { SomaPageState, SomaPageStateConfig } from '../../shared/types/page-state.types';
45
+ import { decodePageState, encodePageState, parseStateValue } from '../parser/page-state-parser';
46
+ import { injectStyleOnce } from '../component/pack-styles';
39
47
  import type { SomaComponentDefinition } from '../component/component-definition.types';
40
48
  import { SomaComponentRegistry } from '../component/component-registry';
41
49
  import { SomaComponentManager } from '../component/component-manager';
50
+ import {
51
+ validateComponentDefaults,
52
+ type SomaComponentDefaults,
53
+ } from '../component/component-defaults';
54
+ import { validateStyleFeatures } from '../component/style-features';
42
55
  import { SomaPipeRegistry, type SomaPipeFn } from '../pipes/pipe-registry';
43
56
  import { applyTheme, type SomaThemeInput } from '../theme/theme-engine';
44
57
  import {
@@ -135,6 +148,26 @@ export interface SomaBootstrapOptions {
135
148
  * 对该 Host 的所有页面生效;页面资产 components 同名时覆盖 Host 级定义。
136
149
  */
137
150
  components?: Record<string, SomaComponentDefinition>;
151
+ /**
152
+ * Host 级默认 props(REQ-009 M-2):组件名 → { prop: 默认值 }。
153
+ * 「本站所有表格都要 size: sm」这类站点级口径的落点,
154
+ * 优先级为「页面声明 > 本表 > 契约 default」。
155
+ * 键与值在 bootstrap 期按契约逐条校验,未知组件 / 未知 prop / 枚举外值一律抛。
156
+ */
157
+ componentDefaults?: SomaComponentDefaults;
158
+ /** 组件样式注入的 CSP nonce(透传给特性分片注入,M-3) */
159
+ componentStyleNonce?: string | null;
160
+ /**
161
+ * 具名动作注册表(REQ-010 F-20 / AO-3):`{ 名字: 实现 }`。
162
+ *
163
+ * 声明里写 `do: ACTION | exportOrders`,实现登记在这里。这是 amis `custom(script)`
164
+ * 的替代——同样能接任意 Host 逻辑,但它**有名字、要注册、未注册即在 bootstrap 期抛**,
165
+ * 声明层因此仍然零脚本、CSP 仍然不需要 unsafe-eval。
166
+ *
167
+ * 装配期会把页面里出现的每一个 `ACTION | <名字>` 对着这张表查一遍:
168
+ * 对不上就抛。留到运行期才发现的话,那是用户点了按钮之后什么都没发生。
169
+ */
170
+ actions?: Record<string, (payload: Record<string, unknown>) => Promise<unknown> | unknown>;
138
171
  /**
139
172
  * Host 自定义格式化管道(模块 7 U4):{ 管道名: 纯函数 },与内置管道合并。
140
173
  * 内置:money / tpl / date / percent / plural。
@@ -206,6 +239,13 @@ export class SomaBootstrap {
206
239
  private domainInstance: SomaPageRoot | null = null;
207
240
  private componentManager: SomaComponentManager | null = null;
208
241
  private hostComponents: Record<string, SomaComponentDefinition> = {};
242
+ private componentDefaults?: SomaComponentDefaults;
243
+ /**
244
+ * 当前页的数据对象解析器(写通道 §8.4 的真身)。
245
+ * 它在 loadDataObjects 里被换掉——每次重取都是一个新解析器。
246
+ */
247
+ private dataResolver: SomaDataObjectResolver | null = null;
248
+ private componentStyleNonce?: string | null;
209
249
  private pipeRegistry: SomaPipeRegistry;
210
250
  /** 阶梯词汇表:Host 级注册,对该 Host 全部页面生效;未注册时恒为 undefined */
211
251
  private readonly adaptiveVocabulary?: SomaAdaptiveVocabulary;
@@ -224,6 +264,9 @@ export class SomaBootstrap {
224
264
  private readonly errorReporting: SomaBootstrapErrorReporting | null;
225
265
  /** 错误采集句柄:mount 时装、cleanup 时摘,生命周期与页面严格同寿 */
226
266
  private errorReporter: SomaErrorReporterHandle | null = null;
267
+ /** 具名动作注册表(AO-3);构造期定下,运行中不换 */
268
+ private readonly namedActions: Record<string, (payload: Record<string, unknown>) => Promise<unknown> | unknown>;
269
+
227
270
  constructor(options: SomaBootstrapOptions = {}) {
228
271
  this.adapter = options.adapter ?? new SomaContainerAdapter();
229
272
  this.scheduler = options.scheduler ?? new SomaScheduler();
@@ -233,6 +276,11 @@ export class SomaBootstrap {
233
276
  this.assetResolver = options.assetResolver
234
277
  ?? new SomaAssetResolver(undefined, { adaptiveVocabulary: this.adaptiveVocabulary });
235
278
  this.hostComponents = options.components ?? {};
279
+ this.componentDefaults = options.componentDefaults;
280
+ this.componentStyleNonce = options.componentStyleNonce ?? null;
281
+ // 复制一份:注册表在页面生命周期内不该被调用方改到(换掉的后果是
282
+ // "解析期查过、运行期又不在了",而那条路径只有抛异常一个出口)
283
+ this.namedActions = { ...(options.actions ?? {}) };
236
284
  this.pipeRegistry = new SomaPipeRegistry(options.pipes);
237
285
  // 复制一份:身份会随 setErrorReportingPage 变,不该改到调用方手里的对象
238
286
  this.errorReporting = options.errorReporting ? { ...options.errorReporting } : null;
@@ -630,12 +678,22 @@ export class SomaBootstrap {
630
678
  // api 声明允许写全路径(如 /api/order/detail):与 http 服务 baseURL 重叠时去重,
631
679
  // 避免拼出 /api/api/... 的双前缀
632
680
  const baseURL = String(services.config.get('apiBaseUrl') ?? '/api');
681
+ const strip = (url: string): string =>
682
+ baseURL && baseURL !== '/' && url.startsWith(`${baseURL}/`) ? url.slice(baseURL.length) : url;
683
+ const writeVerb = (verb: 'post' | 'put' | 'patch') => {
684
+ const fn = (services.http as unknown as Record<string, unknown>)[verb];
685
+ if (typeof fn !== 'function') return undefined;
686
+ return <T,>(url: string, body?: unknown) =>
687
+ (fn as (u: string, b?: unknown) => Promise<T>).call(services.http, strip(url), body);
688
+ };
633
689
  const http = {
634
690
  get: <T,>(url: string, requestConfig?: { params?: Record<string, string> }) =>
635
- services.http.get<T>(
636
- baseURL && baseURL !== '/' && url.startsWith(`${baseURL}/`) ? url.slice(baseURL.length) : url,
637
- requestConfig,
638
- ),
691
+ services.http.get<T>(strip(url), requestConfig),
692
+ // 写通道(M-5):Host 的 http 没实现某个动词时留 undefined,
693
+ // resolver.submit 会给出「本 Host 的 http 不支持它」而不是静默失败
694
+ post: writeVerb('post'),
695
+ put: writeVerb('put'),
696
+ patch: writeVerb('patch'),
639
697
  };
640
698
 
641
699
  const task = Promise.resolve()
@@ -647,6 +705,14 @@ export class SomaBootstrap {
647
705
  pipes: this.pipeRegistry,
648
706
  locale: () => instance._locale as Record<string, unknown> | undefined,
649
707
  });
708
+ // 解析器换新:组件手里的 data 端口是稳定壳,调用时才取当前解析器(见 buildComponentServices)
709
+ this.dataResolver = resolver;
710
+ // 窗口是**自己会动**的:滚动触发取数、取数完成换行,这些都不经过页面的
711
+ // 事件通道。不接这一下,滚动之后行取回来了但一帧都不重渲。
712
+ resolver.setWindowChangeHandler(() => {
713
+ this.renderEngine?.render();
714
+ this.componentManager?.refreshAll();
715
+ });
650
716
  return resolver.resolve();
651
717
  })
652
718
  .then((result) => {
@@ -654,6 +720,10 @@ export class SomaBootstrap {
654
720
  this.dataDicts = result.dicts;
655
721
  this.domainInstance.data = result.objects;
656
722
  this.renderEngine?.render();
723
+ // 自治组件有自己的渲染引擎,页面重渲进不去。数据对象刚刚才到,
724
+ // 而它们(FormConsole 的字典与回填、DetailConsole 的字段…)在挂载那一刻
725
+ // 读到的是空字典——不推这一下,它们会一直显示挂载时的空表单。
726
+ this.componentManager?.refreshAll();
657
727
  })
658
728
  .catch((error) => {
659
729
  console.error('[soma-core][数据] 数据对象解析失败(data 保持空对象):', error);
@@ -685,6 +755,179 @@ export class SomaBootstrap {
685
755
  }
686
756
  }
687
757
 
758
+ /**
759
+ * 组件可见的服务表:页面运行时服务 + data 端口(M-5)。
760
+ *
761
+ * data 不住在 `_services` 里,因为它不是 Domain 的能力而是**数据对象层的能力**——
762
+ * Domain 用 `this.data.*` 读、用 `_reloadData` 重取,不需要这个端口。
763
+ * 它只为自治组件而生,并且仍受 services 白名单管辖(组件不声明就拿不到)。
764
+ */
765
+ private buildComponentServices(): Record<string, unknown> | undefined {
766
+ const base = this.domainInstance?._services as unknown as Record<string, unknown> | undefined;
767
+ if (!base) return undefined;
768
+ // 端口必须是**稳定壳**:组件实例在 activate 时就把 services 抓在手里,
769
+ // 而数据解析器要到 loadDataObjects 之后才存在,且每次重取都换一个新的。
770
+ // 直接注入解析器的话,组件会永久持有第一个(甚至是 null)。
771
+ return { ...base, data: this.createStableDataPort() };
772
+ }
773
+
774
+ /**
775
+ * 页面态装配(REQ-010 F-37)。
776
+ *
777
+ * 三个来源按优先级取:**URL > initial_state > 空**。
778
+ * URL 在最前是因为它是"用户此刻明确要求看到的那一屏"(分享链接、书签、回退按钮),
779
+ * 而 `initial_state` 只是作者写的缺省。反过来的话,分享链接打开后会被缺省覆盖,
780
+ * 而那正是分享链接唯一的用途。
781
+ *
782
+ * 版本对不上的 URL 状态整份丢弃并 warn 一次:恢复一份旧结构的状态会让界面进入
783
+ * 一个谁都没设计过的样子,而那种坏法是静默的(列还在、但顺序是乱的)。
784
+ */
785
+ /**
786
+ * 约束布局产物注入(REQ-011 接线 / CL-4)。
787
+ *
788
+ * 运行时只认 `layout_css`——构建期解好的 CSS——按宿主类名注入一次。
789
+ * 收到的若是 `layout` 声明本身而没有产物,说明这页没走 `compilePageDeclaration`
790
+ * (直接把源 YAML 喂给了浏览器)。这里**不**代为求解:求解器在 core/build/,
791
+ * 进 client 就等于把「运行期零求解」这条结构性承诺撤回去。只把这件事说出来。
792
+ */
793
+ private installLayoutCss(uiConfig: UiConfig): void {
794
+ if (uiConfig.layoutCss) {
795
+ injectStyleOnce(
796
+ `layout:${uiConfig.bind.obj}`,
797
+ uiConfig.layoutCss,
798
+ { nonce: this.componentStyleNonce ?? null },
799
+ );
800
+ return;
801
+ }
802
+ if (uiConfig.layout && Object.keys(uiConfig.layout).length > 0) {
803
+ console.warn(
804
+ `[soma-core][布局] 页面 "${uiConfig.bind.obj}" 声明了 layout: 段但没有构建期产物(layout_css)——`
805
+ + '声明未经 compilePageDeclaration 求解,本页不会产生任何布局样式。'
806
+ + '求解只在构建期发生(Registry 发布 / Host 预编译),运行时不代算。',
807
+ );
808
+ }
809
+ }
810
+
811
+ private installPageState(config: SomaPageStateConfig | undefined): void {
812
+ const instance = this.domainInstance;
813
+ if (!instance) return;
814
+ instance._pageStateConfig = config ?? null;
815
+ if (!config) {
816
+ instance._pageState = null;
817
+ return;
818
+ }
819
+
820
+ let state: SomaPageState | null = null;
821
+ if (config.url === true) {
822
+ const encoded = readQueryParam('s', this.routerPath());
823
+ if (encoded !== '' && encoded !== undefined) {
824
+ const decoded = decodePageState(encoded);
825
+ if (decoded === null) {
826
+ console.warn('[soma-core][引擎] URL 里的状态串解不开,已忽略(链接可能被截断)');
827
+ } else if (decoded.version !== config.version) {
828
+ console.warn(
829
+ `[soma-core][引擎] URL 里的状态是版本 ${decoded.version},本页是版本 ${config.version},已整份丢弃。`
830
+ + '恢复一份旧结构的状态会让界面进入一个谁都没设计过的样子,而那种坏法是看不出来的。',
831
+ );
832
+ } else {
833
+ state = parseStateValue(decoded, 'url.s', config, (message) => {
834
+ throw new Error(message);
835
+ });
836
+ }
837
+ }
838
+ }
839
+ if (state === null && config.initial_state !== undefined) {
840
+ state = config.initial_state;
841
+ }
842
+ instance._pageState = state ?? { version: config.version };
843
+
844
+ // 状态变了就同步 URL(`replaceState`,不进历史栈)。
845
+ // 用 pushState 的话,改一次排序就多一条历史记录,后退键会变成"撤销排序"——
846
+ // 那不是用户按后退时想要的。
847
+ if (config.url === true) {
848
+ instance.onStateUpdated?.((next: SomaPageState) => {
849
+ try {
850
+ const url = new URL(globalThis.location?.href ?? 'http://localhost/');
851
+ url.searchParams.set('s', encodePageState(next));
852
+ globalThis.history?.replaceState?.(null, '', url.toString());
853
+ } catch {
854
+ /* 非浏览器环境(SSR / 测试):状态仍在内存里,只是不落 URL */
855
+ }
856
+ });
857
+ }
858
+ }
859
+
860
+ /** 当前路由路径;无 router 时回落 location */
861
+ private routerPath(): string {
862
+ const router = this.domainInstance?._services?.router;
863
+ return router?.getCurrentPath?.() ?? globalThis.location?.search ?? '';
864
+ }
865
+
866
+ /**
867
+ * 页面里用到的每一个 `ACTION | <名字>` 都必须在注册表里(AO-3)。
868
+ *
869
+ * 为什么在装配期查而不是运行期:运行期查的话,一个拼错的动作名要等到用户
870
+ * 点了那个按钮才暴露,而暴露的形式是"点了没反应"——最难报障也最难复现的一种。
871
+ */
872
+ private assertNamedActionsResolvable(events: readonly ParsedEvent[]): void {
873
+ const missing = new Map<string, string[]>();
874
+ const check = (name: string, where: string): void => {
875
+ if (name === '' || this.namedActions[name] !== undefined) return;
876
+ const list = missing.get(name) ?? [];
877
+ list.push(where);
878
+ missing.set(name, list);
879
+ };
880
+ const walkSteps = (steps: SomaStepGraph['steps'], where: string): void => {
881
+ for (const step of steps) {
882
+ const pipes = [
883
+ ...(step.pipeline ? [step.pipeline] : []),
884
+ ...(step.branches ?? []).map((branch) => branch.pipeline),
885
+ ];
886
+ for (const pipe of pipes) {
887
+ if (pipe.type === 'ACTION') check(String(pipe.funcPath ?? ''), where);
888
+ }
889
+ if (step.children) walkSteps(step.children, where);
890
+ }
891
+ };
892
+ for (const event of events) {
893
+ const where = `${event.somaId}.${event.domEvent}`;
894
+ if (event.type === 'ACTION') check(String(event.funcPath ?? ''), where);
895
+ if (event.steps) walkSteps(event.steps.steps, where);
896
+ }
897
+ if (missing.size === 0) return;
898
+ const known = Object.keys(this.namedActions).join(' / ') || '(一个都没注册)';
899
+ const lines = [...missing.entries()]
900
+ .map(([name, wheres]) => ` "${name}" —— 用在 ${wheres.join('、')}`)
901
+ .join('\n');
902
+ throw new Error(
903
+ `[SomaBootstrap] 页面用到了未注册的具名动作:\n${lines}\n`
904
+ + ` 已注册:${known}\n`
905
+ + ' 在 configureSomaBootstrap 的 options.actions 里登记它们。'
906
+ + '具名动作是 custom(script) 的替代:实现在 Host 代码里、有名字、可审计。',
907
+ );
908
+ }
909
+
910
+ /** 稳定的 data 端口壳:每次调用现取当前解析器 */
911
+ private createStableDataPort(): SomaDataPort {
912
+ const noResolver = (action: string): SomaDataSubmitResult => ({
913
+ ok: false,
914
+ message: `数据对象尚未就绪,无法${action}(本页可能没有声明 *_data.yaml)`,
915
+ });
916
+ return {
917
+ getObject: (name) => this.dataResolver?.getObject(name),
918
+ getDict: (name) => this.dataResolver?.getDict(name) ?? {},
919
+ getReactions: (name) => this.dataResolver?.getReactions(name) ?? null,
920
+ window: (name) => this.dataResolver?.window(name) ?? null,
921
+ submit: async (name, model, mode) =>
922
+ this.dataResolver
923
+ ? this.dataResolver.submit(name, model, mode)
924
+ : noResolver(`提交 "${name}"`),
925
+ reload: async (names) => {
926
+ await this.dataResolver?.reload(names);
927
+ },
928
+ };
929
+ }
930
+
688
931
  /** 组件管理器装配:无 components 资产时保持 null,组件能力整体旁路 */
689
932
  private setupComponentManager(
690
933
  container: HTMLElement,
@@ -721,6 +964,16 @@ export class SomaBootstrap {
721
964
  return;
722
965
  }
723
966
 
967
+ // 两道装配期闸门(REQ-009 P0):都在首屏之前跑,坏声明不进渲染。
968
+ const featureIssues = Object.values(defs).flatMap((definition) => validateStyleFeatures(definition));
969
+ if (featureIssues.length > 0) {
970
+ throw new Error(
971
+ `[soma-core][组件] 特性分片声明有 ${featureIssues.length} 处问题:`
972
+ + `\n${featureIssues.map((issue) => ` · ${issue}`).join('\n')}`,
973
+ );
974
+ }
975
+ validateComponentDefaults(this.componentDefaults, defs);
976
+
724
977
  const registry = new SomaComponentRegistry();
725
978
  registry.registerAll(defs);
726
979
  this.componentManager = new SomaComponentManager({
@@ -728,6 +981,8 @@ export class SomaBootstrap {
728
981
  scheduler: this.scheduler,
729
982
  diagnostics: this.diagnostics,
730
983
  pipeRegistry: this.pipeRegistry,
984
+ componentDefaults: this.componentDefaults,
985
+ styleOptions: { nonce: this.componentStyleNonce ?? null },
731
986
  });
732
987
  this.componentManager.prepare(container, uiConfig);
733
988
  }
@@ -764,6 +1019,11 @@ export class SomaBootstrap {
764
1019
  this.renderEngine = runtime.renderEngine;
765
1020
  this.runtimeResolver = runtime.resolver;
766
1021
  this.eventEngine = runtime.eventEngine;
1022
+ // 具名动作下发 + 装配期对账(AO-3)
1023
+ this.eventEngine.setNamedActions(this.namedActions);
1024
+ this.assertNamedActionsResolvable(parsed.eventConfig);
1025
+ this.installPageState(parsed.uiConfig.state);
1026
+ this.installLayoutCss(parsed.uiConfig);
767
1027
  this.styleBinder = runtime.styleBinder;
768
1028
  this.propertyWatcher = runtime.propertyWatcher;
769
1029
  this.onChangeEngine = runtime.onChangeEngine;
@@ -777,7 +1037,7 @@ export class SomaBootstrap {
777
1037
  eventEngine: runtime.eventEngine,
778
1038
  resolver: runtime.resolver,
779
1039
  manifest: runtime.manifest,
780
- services: this.domainInstance._services as unknown as Record<string, unknown> | undefined,
1040
+ services: this.buildComponentServices(),
781
1041
  });
782
1042
 
783
1043
  // 界面中途提交接线:Domain 在长任务里调 `this.publishUi()` 时,
@@ -0,0 +1,134 @@
1
+ // 动作编排运行时(REQ-010 S4)——按编译好的图走一遍。
2
+ //
3
+ // 这里刻意很短:难的部分(可终止性、槽的可见性、并行分支不互引)在解析期就判完了,
4
+ // 运行期只需要照着走。这正是「编排图是纯数据」的收益——
5
+ // 如果编排是一段脚本,这些判断就只能在运行时做,也就是只能在出事之后做。
6
+ //
7
+ // 一条纪律:**输出槽只活在本次事件里**。事件一结束就销毁,绝不写进页面状态。
8
+ // 写进去的话,「这个值是谁放的」就取决于用户最近点过什么——那正是 amis 的运行时数据链
9
+ // 难以排查的根源。
10
+
11
+ import { evaluatePredicate } from '../../shared/predicates';
12
+ import type { SomaFieldPredicate } from '../../shared/predicates';
13
+ import type { ParsedEvent } from '../../shared/types/event.types';
14
+ import type { SomaCompiledStep, SomaStepGraph } from '../../shared/types/step.types';
15
+
16
+ export interface StepRunContext {
17
+ /** 事件载荷:`when` 的字段来源之一 */
18
+ payload: Record<string, unknown>;
19
+ /** 执行一条已解析的管道;返回值进输出槽 */
20
+ dispatch(pipeline: Omit<ParsedEvent, 'somaId' | 'domEvent'>): Promise<unknown>;
21
+ /** bootstrap 注册的具名动作 */
22
+ actions?: Record<string, (payload: Record<string, unknown>) => Promise<unknown> | unknown>;
23
+ /** 出错落点;不给就 console.error */
24
+ onError?(message: string, detail: { step: number; cause: unknown }): void;
25
+ }
26
+
27
+ export interface StepRunResult {
28
+ /** 实际执行过的步骤序号(顺序即执行序,`goto` 会让它跳号) */
29
+ executed: number[];
30
+ /** 事件结束时的槽(仅用于测试与诊断;运行期不外泄) */
31
+ slots: Record<string, unknown>;
32
+ /** 是否被 on_error: stop 中断 */
33
+ stopped: boolean;
34
+ }
35
+
36
+ export async function runSteps(
37
+ graph: SomaStepGraph,
38
+ ctx: StepRunContext,
39
+ ): Promise<StepRunResult> {
40
+ const slots: Record<string, unknown> = {};
41
+ const executed: number[] = [];
42
+ let stopped = false;
43
+
44
+ const report = (message: string, step: number, cause: unknown): void => {
45
+ if (ctx.onError) ctx.onError(message, { step, cause });
46
+ else console.error(`[soma-core][引擎] 第 ${step + 1} 步失败:${message}`, cause);
47
+ };
48
+
49
+ /** `when` 的取值面:事件载荷 ⊕ 当前槽。槽在后,同名时槽赢(它更晚、更具体) */
50
+ const scope = (extra?: Record<string, unknown>): Record<string, unknown> =>
51
+ ({ ...ctx.payload, ...slots, ...extra });
52
+
53
+ const holds = (when: SomaFieldPredicate | undefined, extra?: Record<string, unknown>): boolean =>
54
+ when === undefined || evaluatePredicate(when, scope(extra), {});
55
+
56
+ const call = async (
57
+ pipeline: Omit<ParsedEvent, 'somaId' | 'domEvent'>,
58
+ ): Promise<unknown> => {
59
+ if (pipeline.type === 'ACTION') {
60
+ const name = String(pipeline.funcPath ?? '');
61
+ const action = ctx.actions?.[name];
62
+ if (typeof action !== 'function') {
63
+ // 解析期与 bootstrap 期都查过一遍,走到这里说明注册表在运行中被换过。
64
+ // 抛而不是静默跳过:一个"没执行但也没报错"的动作是排查不出来的。
65
+ throw new Error(`具名动作 "${name}" 未注册`);
66
+ }
67
+ return action(scope());
68
+ }
69
+ return ctx.dispatch(pipeline);
70
+ };
71
+
72
+ /**
73
+ * 走一串步骤。
74
+ *
75
+ * `goto` 只在同一层内跳(解析期保证它只向后),所以这里用一个下标游标而不是递归,
76
+ * 跳转就是把游标挪过去。
77
+ */
78
+ const walk = async (list: SomaCompiledStep[], extra?: Record<string, unknown>): Promise<void> => {
79
+ let cursor = 0;
80
+ while (cursor < list.length) {
81
+ if (stopped) return;
82
+ const step = list[cursor];
83
+
84
+ if (!holds(step.when, extra)) {
85
+ cursor += 1;
86
+ continue;
87
+ }
88
+ executed.push(step.index);
89
+
90
+ try {
91
+ if (step.kind === 'do') {
92
+ const value = await call(step.pipeline!);
93
+ if (step.output !== undefined) slots[step.output] = value;
94
+ } else if (step.kind === 'switch') {
95
+ // 取**第一个**成立的分支。otherwise 解析期已保证在末尾,所以顺序扫即可。
96
+ const branch = (step.branches ?? []).find((item) => item.otherwise || holds(item.when, extra));
97
+ if (branch !== undefined) {
98
+ const value = await call(branch.pipeline);
99
+ if (branch.output !== undefined) slots[branch.output] = value;
100
+ }
101
+ } else if (step.kind === 'parallel') {
102
+ // 分支之间不互引槽(解析期已判),所以真并行是安全的
103
+ await Promise.all((step.children ?? []).map((child) => walk([child], extra)));
104
+ } else if (step.kind === 'for_each') {
105
+ const source = scope(extra)[step.over!];
106
+ const items = Array.isArray(source) ? source : [];
107
+ for (const item of items) {
108
+ if (stopped) break;
109
+ // 项名只在体内可见:出了循环体就没了,不写进 slots
110
+ await walk(step.children ?? [], { ...extra, [step.as!]: item });
111
+ }
112
+ }
113
+ } catch (cause) {
114
+ const message = cause instanceof Error ? cause.message : String(cause);
115
+ report(message, step.index, cause);
116
+ if (step.onError === 'continue') {
117
+ cursor += 1;
118
+ continue;
119
+ }
120
+ if (step.onError.startsWith('goto:')) {
121
+ // 声明里的序号是**从 1 起**的人类序号,游标是从 0 起的下标
122
+ cursor = Number(step.onError.slice(5)) - 1;
123
+ continue;
124
+ }
125
+ stopped = true;
126
+ return;
127
+ }
128
+ cursor += 1;
129
+ }
130
+ };
131
+
132
+ await walk(graph.steps);
133
+ return { executed, slots, stopped };
134
+ }
@@ -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,