soma-core 2.2.5 → 2.2.6

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 (259) hide show
  1. package/README.md +5 -6
  2. package/bin/soma.cjs +2 -2
  3. package/core/build/compiler/flat-page.ts +16 -0
  4. package/core/build/compiler/full-manifest-builder.ts +0 -3
  5. package/core/build/compiler/page-assets.ts +0 -1
  6. package/core/build/compiler/page-closure.ts +245 -0
  7. package/core/build/compiler/page-declaration-compiler.ts +2 -5
  8. package/core/build/compiler/soma-precompile.js +1848 -3244
  9. package/core/build/compiler/soma-precompile.ts +4 -7
  10. package/core/build/component-tree/artifact-codec.ts +4 -8
  11. package/core/build/lsp/soma-declaration.cjs +1 -1
  12. package/core/build/lsp/std-completion.generated.json +3 -3
  13. package/core/client/a11y/a11y-config.ts +2 -1
  14. package/core/client/a11y/dom-id.ts +1 -1
  15. package/core/client/base/SomaHttpClient.ts +11 -3
  16. package/core/client/base/SomaPageRootBase.ts +6 -0
  17. package/core/client/base/defineSomaView.ts +178 -0
  18. package/core/client/base/index.ts +13 -0
  19. package/core/client/base/view-context.ts +328 -0
  20. package/core/client/behavior/adapter-collection.ts +2 -2
  21. package/core/client/compiler/manifest-compiler.ts +5 -36
  22. package/core/client/component/component-definition.types.ts +2 -1
  23. package/core/client/component/component-manager.ts +110 -20
  24. package/core/client/component/structure-adapter.ts +3 -7
  25. package/core/client/container/SomaContainerAdapter.ts +9 -1
  26. package/core/client/data/data-object-resolver.ts +516 -181
  27. package/core/client/data/data-write-actions.ts +79 -15
  28. package/core/client/data/format-config.ts +3 -1
  29. package/core/client/data/region-scope-port.ts +11 -0
  30. package/core/client/engine/asset-resolver.ts +2 -5
  31. package/core/client/engine/dom-renderer.ts +7 -40
  32. package/core/client/engine/event-engine.ts +1 -105
  33. package/core/client/engine/property-watcher.ts +1 -1
  34. package/core/client/engine/reactive-proxy.ts +78 -17
  35. package/core/client/engine/runtime-builder.ts +0 -14
  36. package/core/client/engine/scope-resolver.ts +18 -0
  37. package/core/client/engine/soma-bootstrap.ts +385 -98
  38. package/core/client/engine/style-binder.ts +49 -106
  39. package/core/client/engine/timer-engine.ts +11 -1
  40. package/core/client/host-bridge/load-host-domain-class.ts +2 -1
  41. package/core/client/infra/http/SomaHttpService.ts +15 -4
  42. package/core/client/infra/i18n/pack-locales.ts +2 -2
  43. package/core/client/mount/domain-rule.ts +7 -3
  44. package/core/client/mount/mount-page.ts +38 -5
  45. package/core/client/mount/types.ts +2 -0
  46. package/core/client/parser/confirm-spec.ts +1 -1
  47. package/core/client/parser/data-config-parser.ts +27 -210
  48. package/core/client/parser/pipeline-parser.ts +14 -59
  49. package/core/client/parser/style-config-parser.ts +101 -95
  50. package/core/client/parser/timer-parser.ts +21 -0
  51. package/core/client/parser/ui-config-parser.ts +64 -12
  52. package/core/client/registry/declaration-renderer.ts +1 -1
  53. package/core/client/runtime/SomaRuntimeServices.ts +2 -1
  54. package/core/client/runtime/SomaSnapshotStore.ts +5 -0
  55. package/core/client/security/url-guard.ts +71 -11
  56. package/core/client/validation/async-check-registry.ts +2 -1
  57. package/core/client/validation/contract-validator.ts +2 -6
  58. package/core/client/validation/field-rules.ts +3 -13
  59. package/core/client/validation/object-rules.ts +2 -10
  60. package/core/index.ts +1 -35
  61. package/core/inspect/check-product.ts +5 -5
  62. package/core/inspect/runtime.ts +2 -1
  63. package/core/server/api/dispatch-service-api.ts +35 -36
  64. package/core/server/api/load-host-service.ts +5 -4
  65. package/core/server/compile-port.ts +1 -1
  66. package/core/server/host/app-config-composer.ts +2 -1
  67. package/core/server/host/host-assembly-entry.ts +1 -0
  68. package/core/server/host/host-assembly.ts +47 -3
  69. package/core/server/host/host-caller.ts +2 -1
  70. package/core/server/host/host-dir.ts +9 -0
  71. package/core/server/host/host-response-headers.ts +2 -1
  72. package/core/server/host/invoke-host-request-hook.ts +28 -4
  73. package/core/server/host/published-page-assets.ts +2 -1
  74. package/core/server/host/resolve-host-request-hook.ts +25 -7
  75. package/core/server/host/server-page-assets.ts +4 -4
  76. package/core/server/host/virtual-pages.ts +3 -2
  77. package/core/server/infra/cache/ServerFileCache.ts +79 -9
  78. package/core/server/registry/api-registry-store.ts +3 -1
  79. package/core/server/registry/declaration-precompiler.ts +0 -2
  80. package/core/server/registry/page-registry-repository.ts +2 -1
  81. package/core/server/registry/page-registry-store.ts +2 -1
  82. package/core/server/registry/registry-error.ts +6 -1
  83. package/core/server/registry/registry-file-lock.ts +296 -23
  84. package/core/server/registry/request-body-limit.ts +3 -2
  85. package/core/server/registry/validation/declaration-safety-scan.ts +151 -27
  86. package/core/server/runtime-space/access-gate.ts +21 -7
  87. package/core/server/runtime-space/bindings.ts +3 -6
  88. package/core/server/runtime-space/dynamic-pages.ts +181 -49
  89. package/core/server/runtime-space/errors.ts +3 -0
  90. package/core/server/runtime-space/inject.ts +74 -15
  91. package/core/server/runtime-space/page-grants.ts +7 -1
  92. package/core/server/runtime-space/resolve.ts +66 -19
  93. package/core/server/runtime-space/store.ts +32 -3
  94. package/core/server/runtime-space/submit-steps.ts +2 -1
  95. package/core/server/runtime-space/types.ts +3 -1
  96. package/core/shared/component-tree-errors.ts +2 -1
  97. package/core/shared/contract-a11y.ts +1 -1
  98. package/core/shared/contract-sections.ts +2 -2
  99. package/core/shared/core-diagnostic-codes.ts +8 -0
  100. package/core/shared/declaration-keys.ts +1 -1
  101. package/core/shared/engines/engine-error.ts +2 -1
  102. package/core/shared/generation-error.ts +2 -1
  103. package/core/shared/page-envelope.ts +1 -1
  104. package/core/shared/pure-binding.ts +88 -0
  105. package/core/shared/registry-generated/diagnostic-registry-index.ts +16 -19
  106. package/core/shared/registry-generated/diagnostic-registry.ts +135 -177
  107. package/core/shared/registry-generated/limits.ts +49 -13
  108. package/core/shared/registry-generated/std-grammar-completion.ts +0 -4
  109. package/core/shared/registry-generated/std-grammar-views.ts +40 -10
  110. package/core/shared/registry-generated/std-grammar.ts +42 -20
  111. package/core/shared/soma-error.ts +36 -0
  112. package/core/shared/types/compile-port.types.ts +1 -1
  113. package/core/shared/types/data-config.types.ts +17 -17
  114. package/core/shared/types/engine.types.ts +0 -3
  115. package/core/shared/types/event.types.ts +1 -11
  116. package/core/shared/types/generation-error.types.ts +5 -1
  117. package/core/shared/types/host-assembly.types.ts +7 -1
  118. package/core/shared/types/manifest.types.ts +0 -3
  119. package/core/shared/types/region-scope.types.ts +5 -1
  120. package/core/shared/types/scope-manifest.types.ts +0 -2
  121. package/core/shared/types/style-config.types.ts +21 -21
  122. package/core/shared/types/ui-config.types.ts +4 -5
  123. package/core/shared/types/watcher.types.ts +1 -1
  124. package/dist/browser/runtime-bundle.manifest.json +11 -13
  125. package/dist/browser/soma-runtime.js +2567 -2696
  126. package/dist/core/index.cjs +5446 -5486
  127. package/dist/host-native/aot-builder.cjs +46 -1
  128. package/dist/host-native/native-server.cjs +4879 -4505
  129. package/dist/lsp/component-tree.cjs +5814 -7042
  130. package/dist/types/build/compiler/full-manifest-builder.d.ts +0 -2
  131. package/dist/types/build/compiler/page-closure.d.ts +21 -0
  132. package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -4
  133. package/dist/types/build/compiler/soma-precompile.d.ts +1 -3
  134. package/dist/types/build/component-tree/artifact-codec.d.ts +0 -2
  135. package/dist/types/client/a11y/a11y-config.d.ts +2 -1
  136. package/dist/types/client/base/SomaHttpClient.d.ts +1 -1
  137. package/dist/types/client/base/SomaPageRootBase.d.ts +5 -0
  138. package/dist/types/client/base/defineSomaView.d.ts +46 -0
  139. package/dist/types/client/base/index.d.ts +2 -0
  140. package/dist/types/client/base/view-context.d.ts +136 -0
  141. package/dist/types/client/behavior/adapter-collection.d.ts +1 -1
  142. package/dist/types/client/compiler/manifest-compiler.d.ts +0 -3
  143. package/dist/types/client/component/component-definition.types.d.ts +2 -1
  144. package/dist/types/client/component/component-manager.d.ts +29 -0
  145. package/dist/types/client/data/data-object-resolver.d.ts +91 -31
  146. package/dist/types/client/data/format-config.d.ts +2 -1
  147. package/dist/types/client/engine/dom-renderer.d.ts +1 -2
  148. package/dist/types/client/engine/event-engine.d.ts +0 -7
  149. package/dist/types/client/engine/reactive-proxy.d.ts +11 -4
  150. package/dist/types/client/engine/runtime-builder.d.ts +0 -4
  151. package/dist/types/client/engine/soma-bootstrap.d.ts +44 -6
  152. package/dist/types/client/engine/style-binder.d.ts +8 -4
  153. package/dist/types/client/host-bridge/load-host-domain-class.d.ts +2 -1
  154. package/dist/types/client/mount/domain-rule.d.ts +2 -0
  155. package/dist/types/client/mount/mount-page.d.ts +2 -1
  156. package/dist/types/client/mount/types.d.ts +2 -0
  157. package/dist/types/client/parser/data-config-parser.d.ts +6 -5
  158. package/dist/types/client/parser/style-config-parser.d.ts +7 -3
  159. package/dist/types/client/parser/timer-parser.d.ts +5 -0
  160. package/dist/types/client/parser/ui-config-parser.d.ts +6 -2
  161. package/dist/types/client/runtime/SomaSnapshotStore.d.ts +2 -0
  162. package/dist/types/client/security/url-guard.d.ts +14 -0
  163. package/dist/types/client/validation/async-check-registry.d.ts +2 -1
  164. package/dist/types/client/validation/object-rules.d.ts +0 -5
  165. package/dist/types/index.d.ts +2 -7
  166. package/dist/types/inspect/runtime.d.ts +2 -1
  167. package/dist/types/server/api/dispatch-service-api.d.ts +5 -0
  168. package/dist/types/server/api/load-host-service.d.ts +1 -1
  169. package/dist/types/server/compile-port.d.ts +1 -1
  170. package/dist/types/server/host/host-assembly-entry.d.ts +1 -1
  171. package/dist/types/server/host/host-assembly.d.ts +2 -0
  172. package/dist/types/server/host/host-dir.d.ts +2 -0
  173. package/dist/types/server/host/invoke-host-request-hook.d.ts +10 -3
  174. package/dist/types/server/host/published-page-assets.d.ts +2 -1
  175. package/dist/types/server/host/resolve-host-request-hook.d.ts +18 -5
  176. package/dist/types/server/host/server-page-assets.d.ts +2 -1
  177. package/dist/types/server/infra/cache/ServerFileCache.d.ts +8 -0
  178. package/dist/types/server/registry/declaration-precompiler.d.ts +0 -1
  179. package/dist/types/server/registry/registry-error.d.ts +5 -1
  180. package/dist/types/server/registry/registry-file-lock.d.ts +30 -0
  181. package/dist/types/server/registry/request-body-limit.d.ts +3 -2
  182. package/dist/types/server/registry/validation/declaration-safety-scan.d.ts +3 -0
  183. package/dist/types/server/runtime-space/access-gate.d.ts +7 -0
  184. package/dist/types/server/runtime-space/bindings.d.ts +3 -2
  185. package/dist/types/server/runtime-space/dynamic-pages.d.ts +6 -1
  186. package/dist/types/server/runtime-space/errors.d.ts +1 -1
  187. package/dist/types/server/runtime-space/resolve.d.ts +2 -0
  188. package/dist/types/server/runtime-space/store.d.ts +8 -1
  189. package/dist/types/server/runtime-space/submit-steps.d.ts +2 -1
  190. package/dist/types/server/runtime-space/types.d.ts +3 -1
  191. package/dist/types/shared/component-tree-errors.d.ts +2 -1
  192. package/dist/types/shared/core-diagnostic-codes.d.ts +1 -1
  193. package/dist/types/shared/declaration-keys.d.ts +1 -1
  194. package/dist/types/shared/engines/engine-error.d.ts +2 -1
  195. package/dist/types/shared/generation-error.d.ts +2 -1
  196. package/dist/types/shared/pure-binding.d.ts +48 -0
  197. package/dist/types/shared/registry-generated/diagnostic-registry.d.ts +119 -158
  198. package/dist/types/shared/registry-generated/limits.d.ts +40 -10
  199. package/dist/types/shared/registry-generated/std-grammar-completion.d.ts +0 -30
  200. package/dist/types/shared/registry-generated/std-grammar-views.d.ts +97 -23
  201. package/dist/types/shared/registry-generated/std-grammar.d.ts +109 -241
  202. package/dist/types/shared/soma-error.d.ts +15 -0
  203. package/dist/types/shared/types/data-config.types.d.ts +14 -16
  204. package/dist/types/shared/types/engine.types.d.ts +0 -3
  205. package/dist/types/shared/types/event.types.d.ts +1 -7
  206. package/dist/types/shared/types/generation-error.types.d.ts +1 -1
  207. package/dist/types/shared/types/host-assembly.types.d.ts +2 -0
  208. package/dist/types/shared/types/manifest.types.d.ts +0 -3
  209. package/dist/types/shared/types/region-scope.types.d.ts +4 -1
  210. package/dist/types/shared/types/scope-manifest.types.d.ts +0 -2
  211. package/dist/types/shared/types/style-config.types.d.ts +17 -19
  212. package/dist/types/shared/types/ui-config.types.d.ts +4 -5
  213. package/host-native/bin/host-native.cjs +22 -1
  214. package/host-native/client/browser-entry.ts +21 -172
  215. package/host-native/src/aot-builder.ts +52 -0
  216. package/host-native/src/host-prepare.ts +39 -5
  217. package/host-native/src/manifest-http.ts +2 -3
  218. package/host-native/src/native-server.ts +812 -174
  219. package/host-native/src/page-http.ts +3 -3
  220. package/host-native/src/public-packages.cjs +0 -1
  221. package/host-native/src/registry-handler.ts +12 -5
  222. package/host-native/src/static-file.ts +203 -53
  223. package/package.json +3 -2
  224. package/core/client/engine/step-runner.ts +0 -212
  225. package/core/client/engine/trigger-engine.ts +0 -55
  226. package/core/client/format/zoned.ts +0 -10
  227. package/core/client/parser/step-parser.ts +0 -359
  228. package/core/client/parser/trigger-parser.ts +0 -90
  229. package/core/client/parser/value-lang.ts +0 -340
  230. package/core/client/time/instant.ts +0 -2
  231. package/core/shared/calc/coerce.ts +0 -2
  232. package/core/shared/calc/errors.ts +0 -40
  233. package/core/shared/calc/evaluator.ts +0 -113
  234. package/core/shared/calc/index.ts +0 -11
  235. package/core/shared/calc/lexer.ts +0 -189
  236. package/core/shared/calc/parser.ts +0 -193
  237. package/core/shared/calc/typer.ts +0 -171
  238. package/core/shared/date-parts.ts +0 -2
  239. package/core/shared/show-when.ts +0 -77
  240. package/core/shared/types/step.types.ts +0 -91
  241. package/core/shared/types/trigger.types.ts +0 -14
  242. package/dist/types/client/engine/step-runner.d.ts +0 -42
  243. package/dist/types/client/engine/trigger-engine.d.ts +0 -16
  244. package/dist/types/client/format/zoned.d.ts +0 -1
  245. package/dist/types/client/parser/step-parser.d.ts +0 -23
  246. package/dist/types/client/parser/trigger-parser.d.ts +0 -13
  247. package/dist/types/client/parser/value-lang.d.ts +0 -63
  248. package/dist/types/client/time/instant.d.ts +0 -1
  249. package/dist/types/shared/calc/coerce.d.ts +0 -1
  250. package/dist/types/shared/calc/errors.d.ts +0 -14
  251. package/dist/types/shared/calc/evaluator.d.ts +0 -2
  252. package/dist/types/shared/calc/index.d.ts +0 -6
  253. package/dist/types/shared/calc/lexer.d.ts +0 -19
  254. package/dist/types/shared/calc/parser.d.ts +0 -43
  255. package/dist/types/shared/calc/typer.d.ts +0 -11
  256. package/dist/types/shared/date-parts.d.ts +0 -1
  257. package/dist/types/shared/show-when.d.ts +0 -21
  258. package/dist/types/shared/types/step.types.d.ts +0 -76
  259. package/dist/types/shared/types/trigger.types.d.ts +0 -12
@@ -12,7 +12,6 @@ import { markBootPhase, maybeStartBootTimings } from '../diagnostics/boot-timing
12
12
  import { SomaMiddlewareChain } from '../middleware/SomaMiddlewareChain';
13
13
  import { SomaScheduler } from '../scheduler/SomaScheduler';
14
14
  import type { ParsedEvent, SomaConfirmSpec } from '../../shared/types/event.types';
15
- import type { PropertyTrigger } from '../../shared/types/trigger.types';
16
15
  import type { ParsedTimer } from '../../shared/types/timer.types';
17
16
  import type { StyleConfig } from '../../shared/types/style-config.types';
18
17
  import type { SomaCompiledStyle, UiConfig } from '../../shared/types/ui-config.types';
@@ -36,7 +35,6 @@ import { applyLocaleMetadata } from '../base/decorators/Locale';
36
35
  import { SomaScopeResolver } from './scope-resolver';
37
36
  import type { SomaPropertyWatcher } from './property-watcher';
38
37
  import type { SomaOnChangeEngine } from './on-change-engine';
39
- import type { SomaTriggerEngine } from './trigger-engine';
40
38
  import type { SomaTimerEngine } from './timer-engine';
41
39
  import { createDefaultRuntimeServices } from '../runtime/SomaRuntimeServices';
42
40
  import type { SomaIdentityProvider } from '../infra/identity/identity-port';
@@ -55,7 +53,6 @@ import type { SomaWriteOutcomeStore } from '../data/write-outcome-store';
55
53
  import type { SomaDataPort } from '../../shared/types/data-config.types';
56
54
  import type { SomaDataConfig, SomaDataDicts } from '../../shared/types/data-config.types';
57
55
  import type { WatchCallback, WatcherOptions } from '../../shared/types/watcher.types';
58
- import type { SomaStepGraph } from '../../shared/types/step.types';
59
56
  import type { SomaPageState, SomaPageStateConfig } from '../../shared/types/page-state.types';
60
57
  import { decodePageState, encodePageState, parseStateValue } from '../parser/page-state-parser';
61
58
  import { injectStyleOnce } from '../styles/pack-styles';
@@ -87,6 +84,7 @@ import { SomaComponentManager } from '../component/component-manager';
87
84
  import { applyDegradedRegions } from '../component/region-unavailable';
88
85
  import { SOMA_ANCHOR_SITE_PAGE, anchorDuplicateMessage, anchorSiteOfFragment } from '../../shared/anchor-space';
89
86
  import { SomaLocaleOnlyPageRoot } from '../base/SomaLocaleOnlyPageRoot';
87
+ import type { SomaViewHost } from '../base/view-context';
90
88
  import {
91
89
  validateComponentDefaults,
92
90
  type SomaComponentDefaults,
@@ -151,7 +149,6 @@ export interface SomaPageAssets extends ComponentTreeRuntimeEnvelope {
151
149
  // ── 预编译模式(构建阶段已解析,运行时零开销) ──
152
150
  uiConfig?: UiConfig;
153
151
  eventConfig?: ParsedEvent[];
154
- triggerConfig?: PropertyTrigger[];
155
152
  timerConfig?: ParsedTimer[];
156
153
  styleConfig?: StyleConfig;
157
154
  /**
@@ -567,6 +564,12 @@ export interface SomaBootstrapOptions {
567
564
  * 表形状非法抛 `CORE-ASYNC-CHECK-TABLE`。组件在契约 `services` 声明 `validation`,经 `ctx.services.validation.asyncCheck(name)` 取用。
568
565
  */
569
566
  asyncChecks?: SomaAsyncCheckTable;
567
+ /**
568
+ * 展示对象(页面根类)表:`{ 类名: 类 }`,应用经 `browserMount().pageRoots` 交入。
569
+ * 页面(含按 URL 注入的动态页)的 `domain:`(= `bind.obj`)命中这里时,用这个类实例化页面根;
570
+ * 没命中就是缺省根 `SomaLocaleOnlyPageRoot`。显式交入的 `assets.DomainClass` 优先于本表。
571
+ */
572
+ pageRoots?: Readonly<Record<string, new () => SharedPageRoot>>;
570
573
  /**
571
574
  * Host 自定义格式化管道(模块 7 U4):{ 管道名: 纯函数 },与内置管道合并。
572
575
  * 内置:money / tpl / date / percent / plural。
@@ -595,7 +598,7 @@ export interface SomaBootstrapOptions {
595
598
  shortcuts?: SomaShortcutRegistry;
596
599
  /** 本平台 mod 对应的物理修饰键(mac 传 meta);自建注册中心时用 */
597
600
  shortcutsModKey?: 'ctrl' | 'meta';
598
- /** UI 体系注入的渲染端口(notify 等);缺省全部无头(只记录),soma-ui / soma-lite 入口各给一份 */
601
+ /** UI 体系注入的渲染端口(notify 等);缺省全部无头(只记录),soma-ui / soma-kit 入口各给一份 */
599
602
  renderPorts?: SomaRenderPorts;
600
603
  /** 引擎端口的适配器替换(样式 / 行为 / 表格 / 图表 / 拖放等);未给的槽位用各端口缺省适配器,装配由 UI 体系入口完成 */
601
604
  engines?: Partial<SomaEngineAdapters>;
@@ -645,13 +648,19 @@ function reportToConsole(event: SomaErrorEvent): void {
645
648
  export interface ParsedRuntimeAssets {
646
649
  uiConfig: UiConfig;
647
650
  eventConfig: ParsedEvent[];
648
- triggers: PropertyTrigger[];
649
651
  timers: ParsedTimer[];
650
652
  styleConfig?: StyleConfig;
651
653
  locale: SomaLocaleBundle | Record<string, unknown>;
652
654
  appConfig: unknown;
653
655
  }
654
656
 
657
+ /** 一份(可能由多次请求合并而成的)热替换任务 */
658
+ interface HotSwapJob {
659
+ overrides: Partial<SomaPageAssets>;
660
+ options?: { resetDiagnostics?: boolean; preserveState?: boolean };
661
+ waiters: Array<{ resolve: () => void; reject: (error: unknown) => void }>;
662
+ }
663
+
655
664
  // ─── 生命周期编排器 ──────────────────────────────────────
656
665
 
657
666
  export class SomaBootstrap {
@@ -659,10 +668,10 @@ export class SomaBootstrap {
659
668
  private readonly scheduler: SomaScheduler;
660
669
  private readonly assetResolver: SomaAssetResolver;
661
670
  private readonly runtimeBuilder = new SomaRuntimeBuilder();
671
+ /** 快照库:cleanup 时整库换新(页面已不在,其上未恢复的快照一并释放) */
662
672
  private readonly snapshotStore = new SomaSnapshotStore();
663
673
  private readonly renderMiddleware: SomaMiddlewareChain<SomaRenderMiddlewareContext>;
664
674
  private readonly eventMiddleware: SomaMiddlewareChain<SomaEventMiddlewareContext>;
665
- private routerUnsubscribe: (() => void) | null = null;
666
675
  /** WP3b-C 页面钩子(`state.query` 绑定、`data-soma-motion`)的卸载函数;每次 buildRuntime 重装 */
667
676
  private pageHookDisposers: Array<() => void> = [];
668
677
 
@@ -671,7 +680,6 @@ export class SomaBootstrap {
671
680
  private styleBinder: SomaStyleBinder | null = null;
672
681
  private propertyWatcher: SomaPropertyWatcher | null = null;
673
682
  private onChangeEngine: SomaOnChangeEngine | null = null;
674
- private triggerEngine: SomaTriggerEngine | null = null;
675
683
  private timerEngine: SomaTimerEngine | null = null;
676
684
  private parsedTimers: ParsedTimer[] = [];
677
685
  private runtimeResolver: SomaScopeResolver | null = null;
@@ -687,6 +695,9 @@ export class SomaBootstrap {
687
695
  * 它在 loadDataObjects 里被换掉——每次重取都是一个新解析器。
688
696
  */
689
697
  private dataResolver: SomaDataObjectResolver | null = null;
698
+ /** 展示对象宿主面的订阅表:组件 emit 旁路订阅(键 = `实例id\u0001emit名`)与数据到达监听;跨组件管理器换新、热替换仍有效,卸载时清空 */
699
+ private readonly viewEmitListeners = new Map<string, Set<(payload: unknown) => void>>();
700
+ private readonly viewDataListeners = new Set<() => void>();
690
701
  private dataLoadEpoch = 0;
691
702
  private dataOwnerEpoch = 0;
692
703
  /** 数据端口宿主状态(单一真源):持有写入结果存储与写入事件执行口,端口重建同寿 */
@@ -731,6 +742,12 @@ export class SomaBootstrap {
731
742
  /** 数据对象层:字段字典产物(soma-ui 双态映射消费) */
732
743
  private dataDicts: SomaDataDicts = {};
733
744
  private mounted = false;
745
+ /** hotSwap 代次:每次进入递增,cleanup 也递增;await 之后代次不符即放弃,不再触碰 DOM 与组件 */
746
+ private hotSwapGeneration = 0;
747
+ /** hotSwap 串行化:是否有一轮正在执行 */
748
+ private hotSwapInFlight = false;
749
+ /** hotSwap 串行化:执行期间到来的请求合并成一份(只留最后一次的参数),上一轮结束后再执行;等待者随之落定 */
750
+ private hotSwapPending: HotSwapJob | null = null;
734
751
  private diagnostics: SomaDiagnostics;
735
752
  private readonly observeEnabled: boolean;
736
753
  private observer: SomaRuntimeObserver | null = null;
@@ -743,6 +760,8 @@ export class SomaBootstrap {
743
760
  private errorReporter: SomaErrorReporterHandle | null = null;
744
761
  /** 具名动作注册表(AO-3);构造期定下,运行中不换 */
745
762
  private readonly namedActions: Record<string, (payload: Record<string, unknown>) => Promise<unknown> | unknown>;
763
+ /** 展示对象(Domain 页面类)注册表,见 SomaBootstrapOptions.pageRoots */
764
+ private readonly pageRootClasses: Record<string, new () => SharedPageRoot>;
746
765
  /** 异步字段检查器登记(`services.validation`):构造期复制并验形状,页面生命周期内不变 */
747
766
  private readonly validationService: SomaValidationService;
748
767
  /**
@@ -795,6 +814,7 @@ export class SomaBootstrap {
795
814
  // 复制一份:注册表在页面生命周期内不该被调用方改到(换掉的后果是
796
815
  // "解析期查过、运行期又不在了",而那条路径只有抛异常一个出口)
797
816
  this.namedActions = { ...(options.actions ?? {}) };
817
+ this.pageRootClasses = { ...(options.pageRoots ?? {}) };
798
818
  this.validationService = createAsyncCheckService(options.asyncChecks);
799
819
  this.pipeRegistry = new SomaPipeRegistry(options.pipes);
800
820
  // 内置管道(money / date / percent / plural)读当前显示语言走 Intl
@@ -873,7 +893,7 @@ export class SomaBootstrap {
873
893
  this.bindLocaleSlots(container);
874
894
 
875
895
  // 3. 创建领域实例并注入配置
876
- this.domainInstance = this.createDomainInstance(assets.DomainClass ?? SomaLocaleOnlyPageRoot, parsed, assets.routerPath, assets);
896
+ this.domainInstance = this.createDomainInstance(assets.DomainClass ?? this.domainClassFor(parsed) ?? SomaLocaleOnlyPageRoot, parsed, assets.routerPath, assets);
877
897
 
878
898
  // 3.5 数据对象层(五件套可选件):首渲前解析声明并注入 reloadData 钩子;
879
899
  // 声明非法只告警不阻断挂载(data 保持空对象)
@@ -911,6 +931,12 @@ export class SomaBootstrap {
911
931
  }
912
932
  }
913
933
 
934
+ /**
935
+ * 热替换入口:串行 + 合并。
936
+ * 一轮热替换的破坏性段含 await(buildRuntime),此时再来一轮会 capture 到已被第一轮换掉的实例、保留的状态就丢了;
937
+ * 所以同一时刻只跑一轮,进行中再来的请求排队,多次排队只保留最后一次的参数(被取代的请求随最后一轮一并落定)。
938
+ * 排队的请求轮到时若页面已卸载(或前一轮失败已清理),直接放弃并正常落定,不抛「未挂载」。
939
+ */
914
940
  async hotSwap(
915
941
  overrides: Partial<SomaPageAssets>,
916
942
  options?: { resetDiagnostics?: boolean; preserveState?: boolean },
@@ -918,26 +944,70 @@ export class SomaBootstrap {
918
944
  if (!this.mounted || !this.container || !this.assets || !this.domainInstance) {
919
945
  throw new Error('[SomaBootstrap] Cannot hotSwap before mount');
920
946
  }
947
+ await new Promise<void>((resolve, reject) => {
948
+ const waiter = { resolve, reject };
949
+ if (this.hotSwapInFlight) {
950
+ if (this.hotSwapPending) {
951
+ // 合并而不是覆盖:每次热替换只带局部覆盖(如只换 html、只换样式),排队中的各次改动都要落地;同名项后来者优先,选项取最后一次
952
+ this.hotSwapPending.overrides = { ...this.hotSwapPending.overrides, ...overrides };
953
+ this.hotSwapPending.options = options;
954
+ this.hotSwapPending.waiters.push(waiter);
955
+ } else {
956
+ this.hotSwapPending = { overrides, options, waiters: [waiter] };
957
+ }
958
+ return;
959
+ }
960
+ void this.drainHotSwap({ overrides, options, waiters: [waiter] });
961
+ });
962
+ }
963
+
964
+ private async drainHotSwap(first: HotSwapJob): Promise<void> {
965
+ this.hotSwapInFlight = true;
966
+ let job: HotSwapJob | null = first;
967
+ try {
968
+ while (job) {
969
+ const current: HotSwapJob = job;
970
+ try {
971
+ if (current !== first && (!this.mounted || !this.container)) {
972
+ console.debug('[soma-core][引擎] 排队的 hotSwap 已放弃:页面已卸载');
973
+ } else {
974
+ await this.performHotSwap(current.overrides, current.options);
975
+ }
976
+ for (const waiter of current.waiters) waiter.resolve();
977
+ } catch (error) {
978
+ for (const waiter of current.waiters) waiter.reject(error);
979
+ }
980
+ // 取下一份排队请求(本轮执行期间到来的、已合并的那一份)
981
+ job = this.hotSwapPending;
982
+ this.hotSwapPending = null;
983
+ }
984
+ } finally {
985
+ this.hotSwapInFlight = false;
986
+ }
987
+ }
988
+
989
+ private async performHotSwap(
990
+ overrides: Partial<SomaPageAssets>,
991
+ options?: { resetDiagnostics?: boolean; preserveState?: boolean },
992
+ ): Promise<void> {
993
+ if (!this.mounted || !this.container || !this.assets || !this.domainInstance) {
994
+ throw new Error('[SomaBootstrap] Cannot hotSwap before mount');
995
+ }
996
+ const generation = ++this.hotSwapGeneration;
997
+ const isLive = (): boolean => this.mounted && this.container !== null && generation === this.hotSwapGeneration;
921
998
 
922
999
  const savedLocale =
923
1000
  overrides.locale !== undefined && this.domainInstance._locale
924
1001
  ? { ...this.domainInstance._locale }
925
1002
  : null;
926
1003
 
927
- const snapshotId = options?.preserveState
928
- ? this.snapshotStore.capture(
929
- this.domainInstance,
930
- overrides.locale !== undefined ? { exclude: ['_locale'] } : undefined,
931
- )
932
- : null;
933
-
934
1004
  const merged: SomaPageAssets = {
935
1005
  ...this.assets,
936
1006
  ...overrides,
937
1007
  DomainClass: overrides.DomainClass ?? this.assets.DomainClass,
938
1008
  };
939
1009
  if (this.assets.sourceMarkup === 'component-tree' || merged.sourceMarkup === 'component-tree') {
940
- const compilationFields = ['html', 'uiConfig', 'eventConfig', 'triggerConfig', 'timerConfig',
1010
+ const compilationFields = ['html', 'uiConfig', 'eventConfig', 'timerConfig',
941
1011
  'dataConfig', 'uiYaml', 'eventYaml', 'dataYaml', 'sourceMarkup', 'artifact'] as const;
942
1012
  const updatesCompilation = compilationFields.some((key) => Object.hasOwn(overrides, key));
943
1013
  if (updatesCompilation && (overrides.html === undefined || overrides.sourceMarkup === undefined
@@ -951,13 +1021,17 @@ export class SomaBootstrap {
951
1021
  }
952
1022
  if (updatesCompilation) {
953
1023
  // Remove alternate representations from the previous compile batch.
954
- for (const key of ['uiConfig', 'eventConfig', 'triggerConfig', 'timerConfig', 'dataConfig',
1024
+ for (const key of ['uiConfig', 'eventConfig', 'timerConfig', 'dataConfig',
955
1025
  'uiYaml', 'eventYaml', 'dataYaml', 'artifact'] as const) {
956
1026
  if (!Object.hasOwn(overrides, key)) delete merged[key];
957
1027
  }
958
1028
  }
959
1029
  }
960
1030
  await this.ensureLazyComponents(merged);
1031
+ if (!isLive()) {
1032
+ console.debug('[soma-core][引擎] hotSwap 已放弃:页面已卸载或被更新的热替换取代');
1033
+ return;
1034
+ }
961
1035
  assertPageRuntimeAssets(merged, this.hostComponents);
962
1036
 
963
1037
  if (options?.resetDiagnostics) {
@@ -979,49 +1053,84 @@ export class SomaBootstrap {
979
1053
  // 更坏的是 `document.querySelector` 这类反查会**命中新页面的同名节点**,
980
1054
  // 清理动作落到刚挂上来的新 DOM 上——不报错,还误伤。
981
1055
  // setupComponentManager 里那次 destroy() 是防御性兜底,删这一行会把上述后果全部放回来。
982
- this.componentManager?.destroy();
983
- this.componentManager = null;
984
- this.dataOwnerEpoch += 1;
985
- this.invalidateDataResolver();
1056
+ // 破坏性步骤从这里开始;此前所有可失败的异步 / 校验已完成,失败时旧页面原样可用。
1057
+ // 快照推迟到这里才 capture:此前的放弃 / 抛错路径(卸载、被取代、校验失败)不会留下无人恢复的快照;
1058
+ // 此后无论恢复完成、被放弃还是失败,这条热替换专用的快照都在退出前释放(手动 captureSnapshot 存的不受影响)。
1059
+ // 热替换已串行化,此刻 domainInstance 必是上一轮完整换完的实例。
1060
+ const snapshotId = options?.preserveState
1061
+ ? this.snapshotStore.capture(
1062
+ this.domainInstance,
1063
+ overrides.locale !== undefined ? { exclude: ['_locale'] } : undefined,
1064
+ )
1065
+ : null;
1066
+ const releaseSnapshot = (): void => {
1067
+ if (snapshotId !== null) this.snapshotStore.release(snapshotId);
1068
+ };
1069
+ try {
1070
+ this.componentManager?.destroy();
1071
+ this.componentManager = null;
1072
+ this.dataOwnerEpoch += 1;
1073
+ this.invalidateDataResolver();
1074
+
1075
+ this.releaseLocaleSlots();
1076
+ if (overrides.locale !== undefined) this.loadLocale(parsed.locale);
1077
+ this.adapter.mount(this.container, merged.html, merged.includes);
1078
+ // 与 mount 同序:样式先入、演绎 DOM 再落、作用域声明装入,组件展开最后扫。热替换换的是整份 innerHTML,
1079
+ // 上一版的区域连同它的已注入标记一起没了,所以这里必然是一次真注入。
1080
+ this.installPageStyles(merged, parsed.uiConfig);
1081
+ this.installFragmentHtml(this.container, parsed.uiConfig);
1082
+ this.installRegionScopes(this.container, parsed.uiConfig, parsed.eventConfig);
1083
+ this.setupComponentManager(this.container, merged, parsed.uiConfig);
1084
+ this.bindLocaleSlots(this.container);
1085
+
1086
+ if (overrides.DomainClass) {
1087
+ this.proxy?.dispose();
1088
+ // 更换领域类会新建一整套页面服务(定时器 / HTTP / 实时连接;导航历史、快捷键、文案目录等沿用 bootstrap 的共享实例,不在此释放)。
1089
+ // 旧实例随后被丢弃,其服务只能在这里释放,否则旧定时器 / 在途请求 / 实时连接会泄漏。
1090
+ const oldServices = this.domainInstance?._services;
1091
+ const raw = this.createDomainInstance(merged.DomainClass ?? this.domainClassFor(parsed) ?? SomaLocaleOnlyPageRoot, parsed, merged.routerPath, merged);
1092
+ this.proxy = new SomaReactiveProxy(undefined, this.diagnostics);
1093
+ this.domainInstance = this.proxy.wrap(raw);
1094
+ this.releasePageServices(oldServices);
1095
+ } else {
1096
+ if (!options?.preserveState || overrides.locale !== undefined) {
1097
+ // 词表已在 loadLocale 装入文案目录;`_locale` 是当前显示语言的词条表
1098
+ this.domainInstance._locale = this.localeTable(parsed.locale);
1099
+ }
1100
+ if (parsed.appConfig) {
1101
+ this.domainInstance._config = parsed.appConfig as any;
1102
+ }
1103
+ applyLocaleMetadata(this.domainInstance);
1104
+ // `format:` 的读取点是服务里的配置(装配期装入、config.load 只合并不删键),所以这里整段换掉;
1105
+ // 不换的话热替换后占位 / 时区 / 周起始仍是旧值(缓存按原值身份,新旧值不同即重解)
1106
+ this.domainInstance._services?.config.set('format', nextFormat);
1107
+ }
986
1108
 
987
- this.releaseLocaleSlots();
988
- if (overrides.locale !== undefined) this.loadLocale(parsed.locale);
989
- this.adapter.mount(this.container, merged.html, merged.includes);
990
- // 与 mount 同序:样式先入、演绎 DOM 再落、作用域声明装入,组件展开最后扫。热替换换的是整份 innerHTML,
991
- // 上一版的区域连同它的已注入标记一起没了,所以这里必然是一次真注入。
992
- this.installPageStyles(merged, parsed.uiConfig);
993
- this.installFragmentHtml(this.container, parsed.uiConfig);
994
- this.installRegionScopes(this.container, parsed.uiConfig, parsed.eventConfig);
995
- this.setupComponentManager(this.container, merged, parsed.uiConfig);
996
- this.bindLocaleSlots(this.container);
997
-
998
- if (overrides.DomainClass) {
999
- this.proxy?.dispose();
1000
- const raw = this.createDomainInstance(merged.DomainClass ?? SomaLocaleOnlyPageRoot, parsed, merged.routerPath, merged);
1001
- this.proxy = new SomaReactiveProxy(undefined, this.diagnostics);
1002
- this.domainInstance = this.proxy.wrap(raw);
1003
- } else {
1004
- if (!options?.preserveState || overrides.locale !== undefined) {
1005
- // 词表已在 loadLocale 装入文案目录;`_locale` 是当前显示语言的词条表
1006
- this.domainInstance._locale = this.localeTable(parsed.locale);
1109
+ this.assets = merged;
1110
+ // 新组件取得端口前先替换数据声明;旧端口不能取得新页面的数据写能力。
1111
+ this.prepareDataLayer(this.domainInstance, merged);
1112
+ if (this.dataConfig) {
1113
+ void this.loadDataObjects();
1114
+ }
1115
+ await this.buildRuntime(parsed);
1116
+ if (!isLive()) {
1117
+ console.debug('[soma-core][引擎] hotSwap 在构建运行时后被放弃');
1118
+ releaseSnapshot();
1119
+ return;
1007
1120
  }
1008
- if (parsed.appConfig) {
1009
- this.domainInstance._config = parsed.appConfig as any;
1121
+ this.startDeclarativeTimers();
1122
+ } catch (error) {
1123
+ releaseSnapshot();
1124
+ // 破坏性步骤已开始、旧页面无法恢复:与 mount 失败同一收尾,保证不留 mounted === true 的半成品
1125
+ if (!isLive()) {
1126
+ console.debug('[soma-core][引擎] 已放弃的 hotSwap 失败,忽略:', error);
1127
+ return;
1010
1128
  }
1011
- applyLocaleMetadata(this.domainInstance);
1012
- // `format:` 的读取点是服务里的配置(装配期装入、config.load 只合并不删键),所以这里整段换掉;
1013
- // 不换的话热替换后占位 / 时区 / 周起始仍是旧值(缓存按原值身份,新旧值不同即重解)
1014
- this.domainInstance._services?.config.set('format', nextFormat);
1015
- }
1016
-
1017
- this.assets = merged;
1018
- // 新组件取得端口前先替换数据声明;旧端口不能取得新页面的数据写能力。
1019
- this.prepareDataLayer(this.domainInstance, merged);
1020
- if (this.dataConfig) {
1021
- void this.loadDataObjects();
1129
+ console.error('[soma-core][引擎] 热替换失败:', error);
1130
+ this.captureEngineError(error);
1131
+ this.cleanup();
1132
+ throw error;
1022
1133
  }
1023
- await this.buildRuntime(parsed);
1024
- this.startDeclarativeTimers();
1025
1134
 
1026
1135
  if (snapshotId !== null) {
1027
1136
  try {
@@ -1029,6 +1138,7 @@ export class SomaBootstrap {
1029
1138
  } catch {
1030
1139
  /* snapshot 与新区划不兼容时忽略 */
1031
1140
  }
1141
+ releaseSnapshot();
1032
1142
  if (savedLocale) {
1033
1143
  this.domainInstance._locale = { ...savedLocale, ...this.localeTable(parsed.locale) } as Record<string, string>;
1034
1144
  applyLocaleMetadata(this.domainInstance);
@@ -1067,9 +1177,19 @@ export class SomaBootstrap {
1067
1177
  async unmount(): Promise<void> {
1068
1178
  if (!this.mounted && this.container === null) return;
1069
1179
 
1180
+ // 先中止「卸载开始时已在途」的请求,再调 onUnmount:onUnmount 里发出的保存草稿 / 上报类请求不会被随后的 cleanup 掐掉。
1181
+ this.releaseServiceRequests(this.domainInstance?._services);
1182
+ this.requestsAbortedByUnmount = true;
1070
1183
  try {
1071
1184
  if (this.domainInstance && typeof this.domainInstance.onUnmount === 'function') {
1072
- this.domainInstance.onUnmount();
1185
+ const pending: unknown = this.domainInstance.onUnmount();
1186
+ // 异步 onUnmount 的拒绝没有人接:补 catch 记录(同步抛错由外层 try/catch 处理)
1187
+ if (pending !== null && typeof pending === 'object' && typeof (pending as PromiseLike<unknown>).then === 'function') {
1188
+ void Promise.resolve(pending).catch((error: unknown) => {
1189
+ console.error('[soma-core][引擎] onUnmount 回调异步异常:', error);
1190
+ this.captureEngineError(error);
1191
+ });
1192
+ }
1073
1193
  }
1074
1194
  } catch (error) {
1075
1195
  console.error('[soma-core][引擎] onUnmount 回调异常:', error);
@@ -1240,6 +1360,12 @@ export class SomaBootstrap {
1240
1360
  this.errorReporter?.capture(error, 'runtime');
1241
1361
  }
1242
1362
 
1363
+ /** 展示对象注册表里按页面 `domain`(= `bind.obj`)取类;没登记返回 undefined */
1364
+ private domainClassFor(parsed: ParsedRuntimeAssets): (new () => SharedPageRoot) | undefined {
1365
+ const name = parsed.uiConfig.bind?.obj;
1366
+ return typeof name === 'string' && Object.prototype.hasOwnProperty.call(this.pageRootClasses, name) ? this.pageRootClasses[name] : undefined;
1367
+ }
1368
+
1243
1369
  private createDomainInstance(
1244
1370
  DomainClass: new () => SharedPageRoot,
1245
1371
  parsed: ParsedRuntimeAssets,
@@ -1274,6 +1400,8 @@ export class SomaBootstrap {
1274
1400
  }
1275
1401
 
1276
1402
  this.wireRouter(raw);
1403
+ // 展示对象宿主面(defineSomaView 的 ctx 用):非枚举注入,不进状态序列化
1404
+ Object.defineProperty(raw, '_viewHost', { value: this.createViewHost(raw), enumerable: false, writable: true, configurable: true });
1277
1405
 
1278
1406
  if (parsed.uiConfig.initProps) {
1279
1407
  const preResolver = new SomaScopeResolver();
@@ -1286,6 +1414,84 @@ export class SomaBootstrap {
1286
1414
  return raw;
1287
1415
  }
1288
1416
 
1417
+ /**
1418
+ * 展示对象的宿主面(见 base/view-context.ts):全部复用既有端口——具名动作表、数据解析器、组件管理器、写入结果存储,
1419
+ * 只补两处旁路订阅表(组件 emit、数据到达)。取值一律现取当前对象,页面换代 / 热替换后旧闭包读到的是新页面。
1420
+ */
1421
+ private createViewHost(raw: SomaPageRoot): SomaViewHost {
1422
+ const services = (): NonNullable<SomaPageRoot['_services']> => raw._services as NonNullable<SomaPageRoot['_services']>;
1423
+ const strip = (url: string): string => {
1424
+ const base = String(services().config.get('apiBaseUrl') ?? '/api');
1425
+ return base && base !== '/' && url.startsWith(`${base}/`) ? url.slice(base.length) : url;
1426
+ };
1427
+ const verb = <T,>(name: 'put' | 'patch' | 'delete') => (url: string, body?: unknown): Promise<T> => {
1428
+ const fn = (services().http as unknown as Record<string, unknown>)[name];
1429
+ if (typeof fn !== 'function') return Promise.reject(new Error(`[soma-core][展示对象] 本 Host 的 http 不支持 ${name}`));
1430
+ return (fn as (u: string, b?: unknown) => Promise<T>).call(services().http, strip(url), body);
1431
+ };
1432
+ return {
1433
+ http: {
1434
+ get: (url, config) => services().http.get(strip(url), config),
1435
+ post: (url, body) => services().http.post(strip(url), body as never),
1436
+ put: verb('put'),
1437
+ patch: verb('patch'),
1438
+ delete: (url) => verb<never>('delete')(url),
1439
+ },
1440
+ action: async (name, payload) => {
1441
+ const named = Object.hasOwn(this.namedActions, name) ? this.namedActions[name] : undefined;
1442
+ if (named !== undefined) return named(payload);
1443
+ if (name === 'data.submit' || name === 'data.orderMove') {
1444
+ const engine = this.eventEngine;
1445
+ if (!engine) throw new Error('[soma-core][展示对象] 页面事件引擎尚未就绪,无法执行写入动作');
1446
+ return engine.dispatchAction(name, payload);
1447
+ }
1448
+ throw new Error(`[soma-core][展示对象] 具名动作 "${name}" 没有登记(已登记:${Object.keys(this.namedActions).join(' / ') || '一个都没有'})`);
1449
+ },
1450
+ readData: (name) => this.dataResolver?.getObject(name),
1451
+ readDataStatus: (name) => this.dataResolver?.getObjectReadStatus(name),
1452
+ reloadData: async (names) => {
1453
+ const resolver = this.dataResolver;
1454
+ if (!resolver) return;
1455
+ // 解析器重取完成会走 onReload(换 page.data、重渲、通知数据到达),这里只补轮询的重新武装。
1456
+ // 静默:这是页面领域代码 / 展示层的重取入口,常配合定时器周期刷新,调用方无法表达「用户刚点的」还是「定时触发的」;
1457
+ // 非静默会让每个周期都进入一次读取中再恢复(明暗闪动)。界面交互直接触发的重取(作用域重取动作、组件数据端口、写入后重取)仍是非静默。
1458
+ // 无参(重取全部)走解析器无参分支,不看 silent,行为不变。
1459
+ try {
1460
+ await resolver.reload(names === undefined ? undefined : [...names], { silent: true });
1461
+ } finally {
1462
+ this.dataPolling?.arm(); // 无论重取成败都重新武装轮询
1463
+ }
1464
+ },
1465
+ onData: (listener) => {
1466
+ this.viewDataListeners.add(listener);
1467
+ return () => { this.viewDataListeners.delete(listener); };
1468
+ },
1469
+ componentMounted: (id) => this.componentManager?.findInstance(id) !== undefined,
1470
+ componentProps: (id) => this.componentManager?.findInstance(id)?.readProps(),
1471
+ componentCall: (id, method, args) => {
1472
+ const instance = this.componentManager?.findInstance(id);
1473
+ if (instance === undefined) return { found: false };
1474
+ return instance.callHandle(method, args);
1475
+ },
1476
+ onComponentEmit: (id, emit, listener) => {
1477
+ const key = `${id}\u0001${emit}`;
1478
+ let set = this.viewEmitListeners.get(key);
1479
+ if (set === undefined) { set = new Set(); this.viewEmitListeners.set(key, set); }
1480
+ set.add(listener);
1481
+ return () => { this.viewEmitListeners.get(key)?.delete(listener); };
1482
+ },
1483
+ outcome: (scope) => this.writeOutcomeStore.get(scope),
1484
+ onOutcome: (listener) => this.writeOutcomeStore.subscribe(listener),
1485
+ emitSemantic: (scope, name, payload) => this.regionScopes.emitSemantic(scope, name, payload),
1486
+ };
1487
+ }
1488
+
1489
+ private notifyViewData(): void {
1490
+ for (const listener of [...this.viewDataListeners]) {
1491
+ try { listener(); } catch (error) { console.error('[soma-core][展示对象] 数据到达监听抛错(已隔离):', error); }
1492
+ }
1493
+ }
1494
+
1289
1495
  /**
1290
1496
  * 把取页响应带来的地址参数与查询值装进页面根(E3,姊妹稿 §4.8):`page.params` 冻结(只读,写入被拒;
1291
1497
  * 声明面的写入已在编译期拒收),`page.query` 是可写的普通对象(回写地址栏由 `installDeclaredPageHooks` 的绑定负责)。
@@ -1341,6 +1547,8 @@ export class SomaBootstrap {
1341
1547
  private prepareDataLayer(instance: SomaPageRoot, assets: SomaPageAssets): void {
1342
1548
  this.invalidateDataResolver();
1343
1549
  this.disposeDataSubscriptions();
1550
+ this.viewEmitListeners.clear();
1551
+ this.viewDataListeners.clear();
1344
1552
  this.dataConfig = null;
1345
1553
  this.dataReady = null;
1346
1554
  this.dataDicts = {};
@@ -1381,6 +1589,7 @@ export class SomaBootstrap {
1381
1589
  if (owner !== this.dataOwnerEpoch) return;
1382
1590
  this.renderEngine?.render();
1383
1591
  this.componentManager?.refreshAll();
1592
+ this.notifyViewData();
1384
1593
  },
1385
1594
  onError: (error) => this.captureEngineError(error),
1386
1595
  });
@@ -1439,15 +1648,36 @@ export class SomaBootstrap {
1439
1648
  http,
1440
1649
  query: (key) => readQueryParam(key, services.router.getCurrentPath()),
1441
1650
  page: () => this.domainInstance,
1442
- pipes: this.pipeRegistry,
1443
- locale: () => instance._locale as Record<string, unknown> | undefined,
1444
1651
  identity: services.identity,
1445
1652
  onFetch: this.observer ? (entry) => this.observer?.recordFetch(entry) : undefined,
1446
1653
  onReload: (objects) => {
1447
1654
  if (!isCurrent() || this.dataResolver !== resolver) return;
1448
1655
  instance.data = objects;
1449
- this.renderEngine?.render();
1656
+ // 渲染阶段独立隔离(同 loadDataObjects 成功路径):数据已写回,渲染异常不得让解析器的 reload 以渲染错误拒绝
1657
+ try {
1658
+ this.renderEngine?.render();
1659
+ this.componentManager?.refreshAll();
1660
+ this.notifyViewData();
1661
+ } catch (renderError) {
1662
+ console.error('[soma-core][数据] 数据已落定,但渲染失败(data 保持已取到的数据):', renderError);
1663
+ this.captureEngineError(renderError);
1664
+ }
1665
+ },
1666
+ // 显式重取开始:旧数据 + loading 已挂上(非响应式属性,数据对象本身未换);不整页 render(数据到达时 onReload 再渲染),不取数。
1667
+ // 三句各自的作用:
1668
+ // 1. refreshPropsBoundTo:属性经页面绑定下推的组件,读状态改写不触发监听,按 `data.<对象名>`(resolvePath 归一形态)重推其 props;
1669
+ // 2. refreshAll:自己读数据的组件(控制器 onDataObjectsChange)用现有 props 重渲一次;
1670
+ // 3. notifyViewData:通知视图层重取读状态;
1671
+ // 4. schedulePatch:页面自身 DOM 绑定(`data.<对象>.loading` / `readState` 等)读的也是非响应式的读状态,对象引用不变、代理不触发;
1672
+ // 按 `data.<对象名>`(绑定表 dataPath 归一形态,祖先索引会命中子路径绑定)排一次局部补丁让这些绑定重读,不整页 render。
1673
+ onReadStart: (names) => {
1674
+ if (!isCurrent() || this.dataResolver !== resolver) return;
1675
+ for (const name of names) {
1676
+ this.renderEngine?.schedulePatch(`data.${name}`, instance.data?.[name]);
1677
+ }
1678
+ this.componentManager?.refreshPropsBoundTo(names.map((name) => `data.${name}`));
1450
1679
  this.componentManager?.refreshAll();
1680
+ this.notifyViewData();
1451
1681
  },
1452
1682
  // 401 / 403 → CORE-DATA-FORBIDDEN、外键批取失败 → CORE-DATA-RELATION:进诊断簿(不含角色值与键值)
1453
1683
  onDiagnostic: (diagnostic) => this.diagnostics.recordValidation(
@@ -1461,15 +1691,36 @@ export class SomaBootstrap {
1461
1691
  const task = Promise.resolve()
1462
1692
  .then(async () => {
1463
1693
  if (!isCurrent() || this.dataResolver !== resolver) return;
1694
+ // 首次读取的待定占位:解析落定前 page.data.<对象> 就是带 loading 读状态的空对象,而不是 undefined;
1695
+ // 经页面根整体赋值让响应式生效,并照成功路径渲染一次(渲染异常同样隔离)
1696
+ const placeholders = resolver.initialPlaceholders(instance.data ?? {});
1697
+ if (Object.keys(placeholders).length > 0) {
1698
+ instance.data = { ...(instance.data ?? {}), ...placeholders };
1699
+ try {
1700
+ this.renderEngine?.render();
1701
+ this.componentManager?.refreshAll();
1702
+ this.notifyViewData();
1703
+ } catch (renderError) {
1704
+ console.error('[soma-core][数据] 读取中占位渲染失败(继续取数):', renderError);
1705
+ this.captureEngineError(renderError);
1706
+ }
1707
+ }
1464
1708
  const result = await resolver.resolve();
1465
1709
  if (!isCurrent() || this.dataResolver !== resolver) return;
1466
1710
  this.dataDicts = result.dicts;
1467
1711
  instance.data = result.objects;
1468
- this.renderEngine?.render();
1469
- // 自治组件有自己的渲染引擎,页面重渲进不去。数据对象刚刚才到,
1470
- // 而它们(表单组件的字典与回填、详情组件的字段…)在挂载那一刻
1471
- // 读到的是空字典——不推这一下,它们会一直显示挂载时的空表单。
1472
- this.componentManager?.refreshAll();
1712
+ // 渲染阶段独立隔离:取数已成功,渲染异常不得被当成取数失败而清空 data。
1713
+ try {
1714
+ this.renderEngine?.render();
1715
+ // 自治组件有自己的渲染引擎,页面重渲进不去。数据对象刚刚才到,
1716
+ // 而它们(表单组件的字典与回填、详情组件的字段…)在挂载那一刻
1717
+ // 读到的是空字典——不推这一下,它们会一直显示挂载时的空表单。
1718
+ this.componentManager?.refreshAll();
1719
+ this.notifyViewData();
1720
+ } catch (renderError) {
1721
+ console.error('[soma-core][数据] 数据已落定,但渲染失败(data 保持已取到的数据):', renderError);
1722
+ this.captureEngineError(renderError);
1723
+ }
1473
1724
  this.dataPolling?.arm();
1474
1725
  })
1475
1726
  .catch((error) => {
@@ -1478,7 +1729,12 @@ export class SomaBootstrap {
1478
1729
  this.captureEngineError(error);
1479
1730
  if (isCurrent()) {
1480
1731
  instance.data = {};
1481
- this.renderEngine?.render();
1732
+ try {
1733
+ this.renderEngine?.render();
1734
+ } catch (renderError) {
1735
+ console.error('[soma-core][数据] 数据解析失败后的重渲染也失败:', renderError);
1736
+ this.captureEngineError(renderError);
1737
+ }
1482
1738
  }
1483
1739
  });
1484
1740
 
@@ -1502,6 +1758,16 @@ export class SomaBootstrap {
1502
1758
  return {
1503
1759
  ...base,
1504
1760
  data: this.createStableDataPort(),
1761
+ // 具名动作调用端口:与页面 `ACTION | 名字` 同一张表(browserMount.actions);展示对象 ctx.action 走的也是它
1762
+ actions: {
1763
+ has: (name: string): boolean => Object.hasOwn(this.namedActions, name),
1764
+ run: async (name: string, payload: Record<string, unknown> = {}): Promise<unknown> => {
1765
+ if (!Object.hasOwn(this.namedActions, name)) {
1766
+ throw new Error(`[soma-core][组件] 具名动作 "${name}" 没有登记(已登记:${Object.keys(this.namedActions).join(' / ') || '一个都没有'})`);
1767
+ }
1768
+ return this.namedActions[name]!(payload);
1769
+ },
1770
+ },
1505
1771
  observation: this.observer ?? NOOP_OBSERVATION_CHANNEL,
1506
1772
  // 异步字段检查器:按名取用应用登记的检查器(组件须在契约 services 声明 validation)
1507
1773
  validation: this.validationService,
@@ -1803,9 +2069,15 @@ export class SomaBootstrap {
1803
2069
  + '恢复一份旧结构的状态会让界面进入一个谁都没设计过的样子,而那种坏法是看不出来的。',
1804
2070
  );
1805
2071
  } else {
1806
- state = parseStateValue(decoded, 'url.s', config, (message) => {
1807
- throw new Error(message);
1808
- });
2072
+ try {
2073
+ state = parseStateValue(decoded, 'url.s', config, (message) => {
2074
+ throw new Error(message);
2075
+ });
2076
+ } catch (error) {
2077
+ console.warn(
2078
+ `[soma-core][引擎] URL 里的状态结构非法,已忽略:${error instanceof Error ? error.message : String(error)}`,
2079
+ );
2080
+ }
1809
2081
  }
1810
2082
  }
1811
2083
  }
@@ -1886,8 +2158,7 @@ export class SomaBootstrap {
1886
2158
  builtinActions: Readonly<Record<string, unknown>> | null = null,
1887
2159
  ): void {
1888
2160
  const missing = new Map<string, string[]>();
1889
- // 单条 `ACTION | 名字`(非编排)找不到应用具名动作时退到页面 Domain 同名方法(K1 ⑥,与 event-engine 同一查找序);
1890
- // 编排步骤里的 `do: ACTION | 名字` 只认应用具名动作(step-runner 不回落 Domain)
2161
+ // `ACTION | 名字` 找不到应用具名动作时退到页面 Domain 同名方法(K1 ⑥,与 event-engine 同一查找序)
1891
2162
  const domainHas = (name: string): boolean =>
1892
2163
  domain !== null && typeof (domain as unknown as Record<string, unknown>)[name] === 'function';
1893
2164
  const check = (name: string, where: string, allowDomain = false): void => {
@@ -1897,22 +2168,9 @@ export class SomaBootstrap {
1897
2168
  list.push(where);
1898
2169
  missing.set(name, list);
1899
2170
  };
1900
- const walkSteps = (steps: SomaStepGraph['steps'], where: string): void => {
1901
- for (const step of steps) {
1902
- const pipes = [
1903
- ...(step.pipeline ? [step.pipeline] : []),
1904
- ...(step.branches ?? []).map((branch) => branch.pipeline),
1905
- ];
1906
- for (const pipe of pipes) {
1907
- if (pipe.type === 'ACTION') check(String(pipe.funcPath ?? ''), where);
1908
- }
1909
- if (step.children) walkSteps(step.children, where);
1910
- }
1911
- };
1912
2171
  for (const event of events) {
1913
2172
  const where = `${event.somaId}.${event.domEvent}`;
1914
- if (event.type === 'ACTION') check(String(event.funcPath ?? ''), where, event.steps === undefined);
1915
- if (event.steps) walkSteps(event.steps.steps, where);
2173
+ if (event.type === 'ACTION') check(String(event.funcPath ?? ''), where, true);
1916
2174
  }
1917
2175
  if (missing.size === 0) return;
1918
2176
  const known = Object.keys(this.namedActions).join(' / ') || '(一个都没注册)';
@@ -1923,7 +2181,7 @@ export class SomaBootstrap {
1923
2181
  `[SomaBootstrap] 页面用到了未注册的具名动作:\n${lines}\n`
1924
2182
  + ` 已注册:${known}\n`
1925
2183
  + ' 在 configureSomaBootstrap 的 options.actions(应用 browserMount.actions)里登记它们;'
1926
- + '单条 ACTION 也可以是页面 Domain 的同名方法(编排步骤里的 ACTION 只认登记表)。'
2184
+ + 'ACTION 也可以是页面 Domain 的同名方法。'
1927
2185
  + '具名动作是 custom(script) 的替代:实现在 Host 代码里、有名字、可审计。',
1928
2186
  );
1929
2187
  }
@@ -1950,8 +2208,11 @@ export class SomaBootstrap {
1950
2208
  return result;
1951
2209
  },
1952
2210
  reload: async (names) => {
1953
- await base.reload(names);
1954
- this.dataPolling?.arm();
2211
+ try {
2212
+ await base.reload(names);
2213
+ } finally {
2214
+ this.dataPolling?.arm(); // 无论重取成败都重新武装轮询
2215
+ }
1955
2216
  },
1956
2217
  dispatch: async (name, payload) => {
1957
2218
  if (owner !== this.dataOwnerEpoch) return;
@@ -1968,7 +2229,8 @@ export class SomaBootstrap {
1968
2229
  const config = this.dataConfig;
1969
2230
  if (!resolver || !config) return;
1970
2231
  const reload = names.filter((name) => config.objects[name] !== undefined);
1971
- if (reload.length > 0) await resolver.reload(reload);
2232
+ // 后台重取(轮询 / 订阅推送):静默,不触发读取开始通知
2233
+ if (reload.length > 0) await resolver.reload(reload, { silent: true });
1972
2234
  }
1973
2235
 
1974
2236
  private disposeDataSubscriptions(): void {
@@ -2005,6 +2267,13 @@ export class SomaBootstrap {
2005
2267
  treeArtifact: assets.artifact,
2006
2268
  observer: this.observer ?? undefined,
2007
2269
  i18n: this.localeCatalog,
2270
+ emitTap: (instanceId, emitName, payload) => {
2271
+ const set = this.viewEmitListeners.get(`${instanceId}\u0001${emitName}`);
2272
+ if (set === undefined) return;
2273
+ for (const listener of [...set]) {
2274
+ try { listener(payload); } catch (error) { console.error('[soma-core][展示对象] 组件事件监听抛错(已隔离):', error); }
2275
+ }
2276
+ },
2008
2277
  ...this.confirmGradedOption(),
2009
2278
  });
2010
2279
  this.componentManager.prepare(container, uiConfig);
@@ -2209,7 +2478,6 @@ export class SomaBootstrap {
2209
2478
  this.renderEngine?.destroy();
2210
2479
  this.styleBinder?.destroy();
2211
2480
  this.onChangeEngine?.destroy();
2212
- this.triggerEngine?.destroy();
2213
2481
  this.propertyWatcher?.destroy();
2214
2482
 
2215
2483
  const runtime = this.runtimeBuilder.build({
@@ -2219,7 +2487,6 @@ export class SomaBootstrap {
2219
2487
  ...this.confirmGradedOption(),
2220
2488
  uiConfig: parsed.uiConfig,
2221
2489
  eventConfig: parsed.eventConfig,
2222
- triggers: parsed.triggers,
2223
2490
  timers: parsed.timers,
2224
2491
  styleConfig: parsed.styleConfig,
2225
2492
  proxiedInstance: this.domainInstance,
@@ -2255,7 +2522,6 @@ export class SomaBootstrap {
2255
2522
  this.propertyWatcher = runtime.propertyWatcher;
2256
2523
  this.installDeclaredPageHooks(parsed.uiConfig.state);
2257
2524
  this.onChangeEngine = runtime.onChangeEngine;
2258
- this.triggerEngine = runtime.triggerEngine;
2259
2525
  this.timerEngine = runtime.timerEngine;
2260
2526
 
2261
2527
  // 组件实例挂载(页面引擎就绪后:emit 路由标记、props watch、行内钩子)
@@ -2361,7 +2627,6 @@ export class SomaBootstrap {
2361
2627
  const services = raw._services;
2362
2628
  if (!services) return;
2363
2629
 
2364
- this.routerUnsubscribe?.();
2365
2630
  this.adapter.setNavigateHandler?.((url, options) => {
2366
2631
  void services.router.navigate(url, options?.replace === true ? { replace: true } : undefined);
2367
2632
  });
@@ -2402,9 +2667,35 @@ export class SomaBootstrap {
2402
2667
  }
2403
2668
  }
2404
2669
 
2670
+ /** unmount() 已在 onUnmount 之前中止过在途请求:随后的 cleanup 不再中止(保护 onUnmount 期间发出的请求) */
2671
+ private requestsAbortedByUnmount = false;
2672
+
2673
+ private releaseServiceRequests(services: SomaPageRoot['_services'] | undefined): void {
2674
+ try { services?.http?.abortAll(); } catch (error) { console.warn('[soma-core][引擎] 请求中止失败:', error); }
2675
+ }
2676
+
2677
+ /** 释放一套页面服务:定时器、在途请求、实时连接(各自 try 包裹) */
2678
+ private releasePageServices(services: SomaPageRoot['_services'] | undefined, opts?: { skipRequests?: boolean }): void {
2679
+ try { services?.timer?.clearAll(); } catch (error) { console.warn('[soma-core][引擎] 定时器释放失败:', error); }
2680
+ if (!opts?.skipRequests) this.releaseServiceRequests(services);
2681
+ try { services?.realtime?.disconnectAll(); } catch (error) { console.warn('[soma-core][引擎] 实时连接释放失败:', error); }
2682
+ }
2683
+
2684
+ /**
2685
+ * 收尾。请求中止的语义:来自 unmount() 时已在 onUnmount 之前中止过(`requestsAbortedByUnmount`),这里不再中止,
2686
+ * 以免掐掉 onUnmount 期间发出的请求;来自挂载失败 / 热替换失败等其他路径时照常中止。定时器与实时连接始终在此释放。
2687
+ */
2405
2688
  private cleanup(): void {
2689
+ const skipRequests = this.requestsAbortedByUnmount;
2690
+ this.requestsAbortedByUnmount = false;
2691
+ this.hotSwapGeneration += 1;
2406
2692
  this.teardownObserver();
2407
2693
  this.releaseLocaleSlots();
2694
+ // 页面级服务:定时器与进行中的请求随页面卸载释放(services 每次挂载新建,释放后无复用问题)
2695
+ const pageServices = this.domainInstance?._services;
2696
+ this.releasePageServices(pageServices, { skipRequests });
2697
+ this.viewEmitListeners.clear();
2698
+ this.viewDataListeners.clear();
2408
2699
  this.regionViewsOff?.();
2409
2700
  this.regionViewsOff = null;
2410
2701
  this.regionScopes.clear();
@@ -2420,11 +2711,8 @@ export class SomaBootstrap {
2420
2711
  this.renderEngine?.destroy();
2421
2712
  this.styleBinder?.destroy();
2422
2713
  this.onChangeEngine?.destroy();
2423
- this.triggerEngine?.destroy();
2424
2714
  this.propertyWatcher?.destroy();
2425
2715
 
2426
- this.routerUnsubscribe?.();
2427
- this.routerUnsubscribe = null;
2428
2716
  this.componentRegistry = null;
2429
2717
  this.formatDefaultsCache = null;
2430
2718
  this.disposeDeclaredPageHooks();
@@ -2440,7 +2728,6 @@ export class SomaBootstrap {
2440
2728
  this.renderEngine = null;
2441
2729
  this.styleBinder = null;
2442
2730
  this.onChangeEngine = null;
2443
- this.triggerEngine = null;
2444
2731
  this.timerEngine = null;
2445
2732
  this.parsedTimers = [];
2446
2733
  this.propertyWatcher = null;