soma-core 2.2.5 → 2.2.7

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 (283) 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 +1972 -3312
  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/IContainerAdapter.ts +4 -0
  26. package/core/client/container/SomaContainerAdapter.ts +52 -3
  27. package/core/client/data/data-object-resolver.ts +523 -184
  28. package/core/client/data/data-write-actions.ts +79 -15
  29. package/core/client/data/format-config.ts +3 -1
  30. package/core/client/data/region-scope-port.ts +11 -0
  31. package/core/client/engine/asset-resolver.ts +2 -5
  32. package/core/client/engine/dom-renderer.ts +7 -40
  33. package/core/client/engine/event-engine.ts +29 -108
  34. package/core/client/engine/property-watcher.ts +1 -1
  35. package/core/client/engine/reactive-proxy.ts +78 -17
  36. package/core/client/engine/runtime-builder.ts +0 -14
  37. package/core/client/engine/scope-resolver.ts +18 -0
  38. package/core/client/engine/soma-bootstrap.ts +387 -99
  39. package/core/client/engine/style-binder.ts +49 -106
  40. package/core/client/engine/timer-engine.ts +11 -1
  41. package/core/client/host-bridge/load-host-domain-class.ts +2 -1
  42. package/core/client/infra/http/SomaHttpService.ts +15 -4
  43. package/core/client/infra/i18n/pack-locales.ts +2 -2
  44. package/core/client/infra/notify/DefaultNotifyService.ts +2 -2
  45. package/core/client/mount/domain-rule.ts +7 -3
  46. package/core/client/mount/mount-page.ts +38 -5
  47. package/core/client/mount/types.ts +2 -0
  48. package/core/client/parser/confirm-spec.ts +100 -7
  49. package/core/client/parser/data-config-parser.ts +28 -211
  50. package/core/client/parser/pipeline-parser.ts +16 -60
  51. package/core/client/parser/style-config-parser.ts +101 -95
  52. package/core/client/parser/timer-parser.ts +21 -0
  53. package/core/client/parser/ui-config-parser.ts +64 -12
  54. package/core/client/registry/declaration-renderer.ts +1 -1
  55. package/core/client/render-ports/hide-transition.ts +9 -0
  56. package/core/client/render-ports/index.ts +4 -0
  57. package/core/client/render-ports/notify-renderer.ts +2 -1
  58. package/core/client/runtime/SomaRuntimeServices.ts +2 -1
  59. package/core/client/runtime/SomaSnapshotStore.ts +5 -0
  60. package/core/client/security/url-guard.ts +71 -11
  61. package/core/client/validation/async-check-registry.ts +2 -1
  62. package/core/client/validation/contract-validator.ts +2 -6
  63. package/core/client/validation/field-rules.ts +3 -13
  64. package/core/client/validation/object-rules.ts +2 -10
  65. package/core/index.ts +17 -39
  66. package/core/inspect/check-product.ts +5 -5
  67. package/core/inspect/runtime.ts +2 -1
  68. package/core/server/api/dispatch-service-api.ts +35 -36
  69. package/core/server/api/load-host-service.ts +8 -4
  70. package/core/server/api/paged-list.ts +259 -0
  71. package/core/server/compile-port.ts +1 -1
  72. package/core/server/host/app-config-composer.ts +2 -1
  73. package/core/server/host/empty-host-bootstrap.mjs +3 -0
  74. package/core/server/host/host-assembly-entry.ts +1 -0
  75. package/core/server/host/host-assembly.ts +50 -3
  76. package/core/server/host/host-caller.ts +2 -1
  77. package/core/server/host/host-dir.ts +9 -0
  78. package/core/server/host/host-response-headers.ts +2 -1
  79. package/core/server/host/invoke-host-request-hook.ts +28 -4
  80. package/core/server/host/published-page-assets.ts +2 -1
  81. package/core/server/host/resolve-host-request-hook.ts +25 -7
  82. package/core/server/host/server-page-assets.ts +4 -4
  83. package/core/server/host/source-aliases.cjs +345 -0
  84. package/core/server/host/source-aliases.ts +32 -0
  85. package/core/server/host/source-packages.cjs +1 -0
  86. package/core/server/host/virtual-pages.ts +3 -2
  87. package/core/server/infra/cache/ServerFileCache.ts +83 -10
  88. package/core/server/node.ts +10 -0
  89. package/core/server/registry/api-registry-store.ts +3 -1
  90. package/core/server/registry/declaration-precompiler.ts +0 -2
  91. package/core/server/registry/page-registry-repository.ts +2 -1
  92. package/core/server/registry/page-registry-store.ts +2 -1
  93. package/core/server/registry/registry-error.ts +6 -1
  94. package/core/server/registry/registry-file-lock.ts +296 -23
  95. package/core/server/registry/request-body-limit.ts +3 -2
  96. package/core/server/registry/validation/declaration-safety-scan.ts +151 -27
  97. package/core/server/runtime-space/access-gate.ts +21 -7
  98. package/core/server/runtime-space/bindings.ts +3 -6
  99. package/core/server/runtime-space/dynamic-pages.ts +181 -49
  100. package/core/server/runtime-space/errors.ts +3 -0
  101. package/core/server/runtime-space/inject.ts +78 -16
  102. package/core/server/runtime-space/page-grants.ts +7 -1
  103. package/core/server/runtime-space/resolve.ts +66 -19
  104. package/core/server/runtime-space/store.ts +32 -3
  105. package/core/server/runtime-space/submit-steps.ts +2 -1
  106. package/core/server/runtime-space/types.ts +3 -1
  107. package/core/shared/component-tree-errors.ts +2 -1
  108. package/core/shared/contract-a11y.ts +1 -1
  109. package/core/shared/contract-sections.ts +2 -2
  110. package/core/shared/core-diagnostic-codes.ts +14 -0
  111. package/core/shared/data-declaration-checks.ts +29 -3
  112. package/core/shared/declaration-keys.ts +1 -1
  113. package/core/shared/engines/engine-error.ts +2 -1
  114. package/core/shared/generation-error.ts +2 -1
  115. package/core/shared/page-envelope.ts +1 -1
  116. package/core/shared/pure-binding.ts +88 -0
  117. package/core/shared/registry-generated/diagnostic-registry-index.ts +21 -19
  118. package/core/shared/registry-generated/diagnostic-registry.ts +170 -177
  119. package/core/shared/registry-generated/limits.ts +65 -13
  120. package/core/shared/registry-generated/std-grammar-completion.ts +0 -4
  121. package/core/shared/registry-generated/std-grammar-views.ts +40 -10
  122. package/core/shared/registry-generated/std-grammar.ts +43 -21
  123. package/core/shared/soma-error.ts +36 -0
  124. package/core/shared/types/compile-port.types.ts +1 -1
  125. package/core/shared/types/data-config.types.ts +20 -18
  126. package/core/shared/types/engine.types.ts +0 -3
  127. package/core/shared/types/event.types.ts +10 -11
  128. package/core/shared/types/generation-error.types.ts +5 -1
  129. package/core/shared/types/host-assembly.types.ts +7 -1
  130. package/core/shared/types/manifest.types.ts +0 -3
  131. package/core/shared/types/region-scope.types.ts +5 -1
  132. package/core/shared/types/scope-manifest.types.ts +0 -2
  133. package/core/shared/types/style-config.types.ts +21 -21
  134. package/core/shared/types/ui-config.types.ts +4 -5
  135. package/core/shared/types/watcher.types.ts +1 -1
  136. package/dist/browser/runtime-bundle.manifest.json +11 -13
  137. package/dist/browser/soma-runtime.js +2733 -2712
  138. package/dist/core/index.cjs +5665 -5534
  139. package/dist/host-native/aot-builder.cjs +330 -1
  140. package/dist/host-native/native-server.cjs +5434 -4726
  141. package/dist/lsp/component-tree.cjs +5868 -7040
  142. package/dist/types/build/compiler/full-manifest-builder.d.ts +0 -2
  143. package/dist/types/build/compiler/page-closure.d.ts +21 -0
  144. package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -4
  145. package/dist/types/build/compiler/soma-precompile.d.ts +1 -3
  146. package/dist/types/build/component-tree/artifact-codec.d.ts +0 -2
  147. package/dist/types/client/a11y/a11y-config.d.ts +2 -1
  148. package/dist/types/client/base/SomaHttpClient.d.ts +1 -1
  149. package/dist/types/client/base/SomaPageRootBase.d.ts +5 -0
  150. package/dist/types/client/base/defineSomaView.d.ts +46 -0
  151. package/dist/types/client/base/index.d.ts +2 -0
  152. package/dist/types/client/base/view-context.d.ts +136 -0
  153. package/dist/types/client/behavior/adapter-collection.d.ts +1 -1
  154. package/dist/types/client/compiler/manifest-compiler.d.ts +0 -3
  155. package/dist/types/client/component/component-definition.types.d.ts +2 -1
  156. package/dist/types/client/component/component-manager.d.ts +29 -0
  157. package/dist/types/client/container/IContainerAdapter.d.ts +3 -0
  158. package/dist/types/client/container/SomaContainerAdapter.d.ts +5 -0
  159. package/dist/types/client/data/data-object-resolver.d.ts +93 -31
  160. package/dist/types/client/data/format-config.d.ts +2 -1
  161. package/dist/types/client/engine/dom-renderer.d.ts +1 -2
  162. package/dist/types/client/engine/event-engine.d.ts +0 -7
  163. package/dist/types/client/engine/reactive-proxy.d.ts +11 -4
  164. package/dist/types/client/engine/runtime-builder.d.ts +0 -4
  165. package/dist/types/client/engine/soma-bootstrap.d.ts +44 -6
  166. package/dist/types/client/engine/style-binder.d.ts +8 -4
  167. package/dist/types/client/host-bridge/load-host-domain-class.d.ts +2 -1
  168. package/dist/types/client/mount/domain-rule.d.ts +2 -0
  169. package/dist/types/client/mount/mount-page.d.ts +2 -1
  170. package/dist/types/client/mount/types.d.ts +2 -0
  171. package/dist/types/client/parser/confirm-spec.d.ts +27 -3
  172. package/dist/types/client/parser/data-config-parser.d.ts +6 -5
  173. package/dist/types/client/parser/style-config-parser.d.ts +7 -3
  174. package/dist/types/client/parser/timer-parser.d.ts +5 -0
  175. package/dist/types/client/parser/ui-config-parser.d.ts +6 -2
  176. package/dist/types/client/render-ports/hide-transition.d.ts +9 -0
  177. package/dist/types/client/render-ports/index.d.ts +4 -0
  178. package/dist/types/client/render-ports/notify-renderer.d.ts +2 -1
  179. package/dist/types/client/runtime/SomaSnapshotStore.d.ts +2 -0
  180. package/dist/types/client/security/url-guard.d.ts +14 -0
  181. package/dist/types/client/validation/async-check-registry.d.ts +2 -1
  182. package/dist/types/client/validation/object-rules.d.ts +0 -5
  183. package/dist/types/index.d.ts +6 -11
  184. package/dist/types/inspect/runtime.d.ts +2 -1
  185. package/dist/types/server/api/dispatch-service-api.d.ts +5 -0
  186. package/dist/types/server/api/load-host-service.d.ts +1 -1
  187. package/dist/types/server/api/paged-list.d.ts +101 -0
  188. package/dist/types/server/compile-port.d.ts +1 -1
  189. package/dist/types/server/host/host-assembly-entry.d.ts +1 -1
  190. package/dist/types/server/host/host-assembly.d.ts +2 -0
  191. package/dist/types/server/host/host-dir.d.ts +2 -0
  192. package/dist/types/server/host/invoke-host-request-hook.d.ts +10 -3
  193. package/dist/types/server/host/published-page-assets.d.ts +2 -1
  194. package/dist/types/server/host/resolve-host-request-hook.d.ts +18 -5
  195. package/dist/types/server/host/server-page-assets.d.ts +2 -1
  196. package/dist/types/server/host/source-aliases.d.cts +53 -0
  197. package/dist/types/server/host/source-aliases.d.ts +30 -0
  198. package/dist/types/server/host/source-packages.d.cts +2 -0
  199. package/dist/types/server/infra/cache/ServerFileCache.d.ts +8 -0
  200. package/dist/types/server/node.d.ts +1 -0
  201. package/dist/types/server/registry/declaration-precompiler.d.ts +0 -1
  202. package/dist/types/server/registry/registry-error.d.ts +5 -1
  203. package/dist/types/server/registry/registry-file-lock.d.ts +30 -0
  204. package/dist/types/server/registry/request-body-limit.d.ts +3 -2
  205. package/dist/types/server/registry/validation/declaration-safety-scan.d.ts +3 -0
  206. package/dist/types/server/runtime-space/access-gate.d.ts +7 -0
  207. package/dist/types/server/runtime-space/bindings.d.ts +3 -2
  208. package/dist/types/server/runtime-space/dynamic-pages.d.ts +6 -1
  209. package/dist/types/server/runtime-space/errors.d.ts +1 -1
  210. package/dist/types/server/runtime-space/resolve.d.ts +2 -0
  211. package/dist/types/server/runtime-space/store.d.ts +8 -1
  212. package/dist/types/server/runtime-space/submit-steps.d.ts +2 -1
  213. package/dist/types/server/runtime-space/types.d.ts +3 -1
  214. package/dist/types/shared/component-tree-errors.d.ts +2 -1
  215. package/dist/types/shared/core-diagnostic-codes.d.ts +1 -1
  216. package/dist/types/shared/declaration-keys.d.ts +1 -1
  217. package/dist/types/shared/engines/engine-error.d.ts +2 -1
  218. package/dist/types/shared/generation-error.d.ts +2 -1
  219. package/dist/types/shared/pure-binding.d.ts +48 -0
  220. package/dist/types/shared/registry-generated/diagnostic-registry.d.ts +149 -158
  221. package/dist/types/shared/registry-generated/limits.d.ts +54 -10
  222. package/dist/types/shared/registry-generated/std-grammar-completion.d.ts +0 -30
  223. package/dist/types/shared/registry-generated/std-grammar-views.d.ts +97 -23
  224. package/dist/types/shared/registry-generated/std-grammar.d.ts +110 -242
  225. package/dist/types/shared/soma-error.d.ts +15 -0
  226. package/dist/types/shared/types/data-config.types.d.ts +17 -17
  227. package/dist/types/shared/types/engine.types.d.ts +0 -3
  228. package/dist/types/shared/types/event.types.d.ts +9 -7
  229. package/dist/types/shared/types/generation-error.types.d.ts +1 -1
  230. package/dist/types/shared/types/host-assembly.types.d.ts +2 -0
  231. package/dist/types/shared/types/manifest.types.d.ts +0 -3
  232. package/dist/types/shared/types/region-scope.types.d.ts +4 -1
  233. package/dist/types/shared/types/scope-manifest.types.d.ts +0 -2
  234. package/dist/types/shared/types/style-config.types.d.ts +17 -19
  235. package/dist/types/shared/types/ui-config.types.d.ts +4 -5
  236. package/host-native/bin/host-native.cjs +22 -1
  237. package/host-native/client/browser-entry.ts +21 -172
  238. package/host-native/src/aot-builder.ts +75 -0
  239. package/host-native/src/host-prepare.ts +39 -5
  240. package/host-native/src/manifest-http.ts +2 -3
  241. package/host-native/src/native-server.ts +812 -174
  242. package/host-native/src/page-http.ts +3 -3
  243. package/host-native/src/public-packages.cjs +0 -1
  244. package/host-native/src/registry-handler.ts +12 -5
  245. package/host-native/src/static-file.ts +203 -53
  246. package/host-native/styles/globals.css +30 -28
  247. package/package.json +14 -2
  248. package/core/client/engine/step-runner.ts +0 -212
  249. package/core/client/engine/trigger-engine.ts +0 -55
  250. package/core/client/format/zoned.ts +0 -10
  251. package/core/client/parser/step-parser.ts +0 -359
  252. package/core/client/parser/trigger-parser.ts +0 -90
  253. package/core/client/parser/value-lang.ts +0 -340
  254. package/core/client/time/instant.ts +0 -2
  255. package/core/shared/calc/coerce.ts +0 -2
  256. package/core/shared/calc/errors.ts +0 -40
  257. package/core/shared/calc/evaluator.ts +0 -113
  258. package/core/shared/calc/index.ts +0 -11
  259. package/core/shared/calc/lexer.ts +0 -189
  260. package/core/shared/calc/parser.ts +0 -193
  261. package/core/shared/calc/typer.ts +0 -171
  262. package/core/shared/date-parts.ts +0 -2
  263. package/core/shared/show-when.ts +0 -77
  264. package/core/shared/types/step.types.ts +0 -91
  265. package/core/shared/types/trigger.types.ts +0 -14
  266. package/dist/types/client/engine/step-runner.d.ts +0 -42
  267. package/dist/types/client/engine/trigger-engine.d.ts +0 -16
  268. package/dist/types/client/format/zoned.d.ts +0 -1
  269. package/dist/types/client/parser/step-parser.d.ts +0 -23
  270. package/dist/types/client/parser/trigger-parser.d.ts +0 -13
  271. package/dist/types/client/parser/value-lang.d.ts +0 -63
  272. package/dist/types/client/time/instant.d.ts +0 -1
  273. package/dist/types/shared/calc/coerce.d.ts +0 -1
  274. package/dist/types/shared/calc/errors.d.ts +0 -14
  275. package/dist/types/shared/calc/evaluator.d.ts +0 -2
  276. package/dist/types/shared/calc/index.d.ts +0 -6
  277. package/dist/types/shared/calc/lexer.d.ts +0 -19
  278. package/dist/types/shared/calc/parser.d.ts +0 -43
  279. package/dist/types/shared/calc/typer.d.ts +0 -11
  280. package/dist/types/shared/date-parts.d.ts +0 -1
  281. package/dist/types/shared/show-when.d.ts +0 -21
  282. package/dist/types/shared/types/step.types.d.ts +0 -76
  283. package/dist/types/shared/types/trigger.types.d.ts +0 -12
@@ -0,0 +1,345 @@
1
+ // 源码根别名的唯一实现(`package.json#soma.sourceRoots`;《core 标准格式与 runtime 空间》P12 同族)。
2
+ //
3
+ // 为什么是 .cjs:构建期(esbuild 插件、host-native 内核、vitest 配置)是 CommonJS / 纯 Node 环境,运行期(TS)经 `source-aliases.ts`
4
+ // 带类型再导出同一份,不再各写一份。「哪些顶层目录是别名」「哪些名字不许占」「与已装包冲突怎么办」只在这里判定。
5
+ //
6
+ // 契约:
7
+ // 声明(`package.json#soma.sourceRoots`,缺省 = 完全不生效、返回空)
8
+ // "auto" → 以 apiRoot(`soma.apiRoot`,缺省回落 webRoot / hostRoot)为源码根
9
+ // "<相对目录>" | string[] → 每项是一个源码根(相对宿主目录,必须落在宿主目录内且存在)
10
+ // { "<别名>": "<相对目录>" } → 显式「别名 → 目录」,目录同样必须落在宿主目录内且存在
11
+ // 源码根形态下,其「一级子目录」各成一个别名:`<dir>/...` 解析到 `<源码根>/<dir>/...`(同 tsconfig `baseUrl` / vite 别名语义)。
12
+ // 只认带斜杠的子路径说明符:裸 `domain`、`kit`、npm 包名、`node:` 内置一概不劫持;没有子路径的 `domain` 仍走原解析。
13
+ // 前缀必须整段匹配(别名 `kit` 不匹配 `kitchen/x`)。
14
+ //
15
+ // 优先级(确定性,与 talent_graph 旧补丁里的 jiti 别名一致):声明的别名先于 node_modules 里的同名包。
16
+ // 宿主 `node_modules/<别名>` 存在且不是指向别名目录的软链 → 诊断 CORE-HOST-ALIAS-SHADOW(warning,别名仍生效,此时该包的
17
+ // `<别名>/...` 子路径说明符在宿主代码里读不到);指向别名目录的软链(旧补丁遗留)视为同一目录、不报。
18
+ // 多个源码根里同名别名:先声明者胜,后者 CORE-HOST-ALIAS-DUPLICATE(warning)。
19
+ //
20
+ // 诊断(error 级由 `getSomaSourceRootAliases` 抛出,不静默降级):
21
+ // CORE-HOST-ALIAS-INVALID error 声明形状不对 / 路径越界或不存在 / 别名名字非法
22
+ // CORE-HOST-ALIAS-RESERVED error 别名占了保留名:`soma` / `soma-*`、`server-only`、`node_modules`、以及带子路径的 Node 内置(`fs`、`path` ...)
23
+ // CORE-HOST-ALIAS-SHADOW warning 见上
24
+ // CORE-HOST-ALIAS-DUPLICATE warning 见上
25
+ // CORE-HOST-ALIAS-TSCONFIG-DRIFT warning tsconfig.json 的 baseUrl 与(auto / 数组形态的)第一个源码根不一致
26
+ //
27
+ // 与 core 的纪律:这里不出现任何 Host / 方言 / 外壳的名字;路径只经 `path.join / path.resolve` 对 hostDir 拼接(G100)。
28
+ const fs = require("node:fs");
29
+ const path = require("node:path");
30
+ const nodeModule = require("node:module");
31
+ const { getSomaHostApiRoot, getSomaHostSourceRoot, resolveSafeChildRoot } = require("./source-packages.cjs");
32
+
33
+ const CODE_INVALID = "CORE-HOST-ALIAS-INVALID";
34
+ const CODE_RESERVED = "CORE-HOST-ALIAS-RESERVED";
35
+ const CODE_SHADOW = "CORE-HOST-ALIAS-SHADOW";
36
+ const CODE_DUPLICATE = "CORE-HOST-ALIAS-DUPLICATE";
37
+ const CODE_TSCONFIG_DRIFT = "CORE-HOST-ALIAS-TSCONFIG-DRIFT";
38
+
39
+ /** 合法别名:字母数字下划线开头,之后允许 `.` `-`;不含斜杠、`@`、`:`、空白 */
40
+ const ALIAS_NAME_RE = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
41
+ const RESERVED_NAMES = new Set(["server-only", "node_modules", "soma"]);
42
+ const BUILTIN_WITH_SUBPATH = new Set(
43
+ nodeModule.builtinModules.filter((m) => m.includes("/")).map((m) => m.slice(0, m.indexOf("/"))),
44
+ );
45
+
46
+ // number-source: limits#/cache/sourceRootAliasCapacity
47
+ const MAX_CACHE = 64;
48
+ /** @type {Map<string, object>} */
49
+ const resolveCache = new Map();
50
+ const warned = new Set();
51
+
52
+ function clearSomaSourceRootCache() {
53
+ resolveCache.clear();
54
+ warned.clear();
55
+ }
56
+
57
+ function readJson(filePath) {
58
+ try {
59
+ if (!fs.existsSync(filePath)) return null;
60
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ /** tsconfig 允许注释与尾逗号:字符串感知地去掉再解析;失败返回 null(漂移检查直接跳过) */
67
+ function readTsconfig(filePath) {
68
+ let raw;
69
+ try {
70
+ raw = fs.readFileSync(filePath, "utf8");
71
+ } catch {
72
+ return null;
73
+ }
74
+ const stripped = raw
75
+ .replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_m, str) => str ?? "")
76
+ .replace(/,(\s*[}\]])/g, "$1");
77
+ try {
78
+ return JSON.parse(stripped);
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ function reservedReason(name) {
85
+ if (name === "soma" || name.startsWith("soma-")) return "与 soma 公开包名空间冲突";
86
+ if (RESERVED_NAMES.has(name)) return "是保留名";
87
+ if (BUILTIN_WITH_SUBPATH.has(name)) return `会劫持 Node 内置子路径(如 ${name}/...)`;
88
+ return null;
89
+ }
90
+
91
+ /** 目录是否真实落在宿主目录内(跟随软链,防越界软链) */
92
+ function realInside(parent, child) {
93
+ try {
94
+ const p = fs.realpathSync(parent);
95
+ const c = fs.realpathSync(child);
96
+ return c === p || c.startsWith(`${p}${path.sep}`);
97
+ } catch {
98
+ return false;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * 解析声明的源码根 → 别名表。纯函数式(只读文件系统),不抛、不打印;结果带诊断。
104
+ * @returns {{ declared: boolean, entries: Array<{ name: string, dir: string }>, aliases: Record<string, string>, diagnostics: Array<{ code: string, severity: "error" | "warning", message: string, name?: string }> }}
105
+ */
106
+ function resolveSomaSourceRoots(hostDir, env = process.env) {
107
+ let normalizedHostDir = path.resolve(hostDir);
108
+ // 传进来的可能是应用根(package 里的子目录,如 <工程>/src/kit)而不是工程根:声明在最近的上级 package.json 里,
109
+ // 向上找到它再解析(别名表属于工程,不属于某个子目录);一路没有 package.json 就按原目录处理(= 未声明)。
110
+ if (!fs.existsSync(path.join(normalizedHostDir, "package.json"))) {
111
+ for (let dir = path.dirname(normalizedHostDir); ; dir = path.dirname(dir)) {
112
+ if (fs.existsSync(path.join(dir, "package.json"))) { normalizedHostDir = dir; break; }
113
+ if (path.dirname(dir) === dir) break;
114
+ }
115
+ }
116
+ const packageJsonPath = path.join(normalizedHostDir, "package.json");
117
+ const stat = fs.statSync(packageJsonPath, { throwIfNoEntry: false });
118
+ const cacheKey = `${normalizedHostDir}\0${env?.SOMA_API_DIR ?? ""}\0${env?.SOMA_WEB_DIR ?? ""}\0${stat ? `${stat.mtimeMs}:${stat.size}` : "none"}`;
119
+ const cached = resolveCache.get(cacheKey);
120
+ if (cached) return cached;
121
+
122
+ const result = compute(normalizedHostDir, env, readJson(packageJsonPath));
123
+ if (resolveCache.size >= MAX_CACHE) resolveCache.delete(resolveCache.keys().next().value);
124
+ resolveCache.set(cacheKey, result);
125
+ return result;
126
+ }
127
+
128
+ function compute(hostDir, env, packageJson) {
129
+ const diagnostics = [];
130
+ const raw = packageJson?.soma?.sourceRoots;
131
+ const empty = { declared: false, entries: [], aliases: {}, diagnostics };
132
+ if (raw === undefined || raw === null) return empty;
133
+
134
+ const invalid = (message) => diagnostics.push({ code: CODE_INVALID, severity: "error", message: `soma.sourceRoots ${message}` });
135
+
136
+ /** 候选:{ name, dir, from } 按声明顺序 */
137
+ const candidates = [];
138
+ let firstRoot = null;
139
+
140
+ const addRoot = (rootDir) => {
141
+ if (firstRoot === null) firstRoot = rootDir;
142
+ let children;
143
+ try {
144
+ children = fs.readdirSync(rootDir, { withFileTypes: true });
145
+ } catch {
146
+ invalid(`的源码根不可读:${rootDir}`);
147
+ return;
148
+ }
149
+ for (const entry of children.sort((a, b) => a.name.localeCompare(b.name))) {
150
+ const full = path.join(rootDir, entry.name);
151
+ const isDir = entry.isDirectory() || (entry.isSymbolicLink() && fs.statSync(full, { throwIfNoEntry: false })?.isDirectory());
152
+ // 隐藏目录、node_modules 与不合法的名字在发现式声明里静默跳过(不是用户写进去的)
153
+ if (!isDir || entry.name.startsWith(".") || entry.name === "node_modules" || !ALIAS_NAME_RE.test(entry.name)) continue;
154
+ candidates.push({ name: entry.name, dir: full });
155
+ }
156
+ };
157
+
158
+ const safeRoot = (rel) => {
159
+ if (typeof rel !== "string" || !rel.trim() || rel.includes("\0")) {
160
+ invalid("的路径必须是非空字符串");
161
+ return null;
162
+ }
163
+ const resolved = path.resolve(hostDir, rel.trim());
164
+ const safe = resolveSafeChildRoot(hostDir, rel);
165
+ // resolveSafeChildRoot 对越界 / 不存在一律回落 parent;回落且并非本来就指向 parent → 拒绝
166
+ if (safe !== resolved || !fs.existsSync(safe) || !fs.statSync(safe).isDirectory() || !realInside(hostDir, safe)) {
167
+ invalid(`的路径 "${rel}" 必须是宿主目录内已存在的目录`);
168
+ return null;
169
+ }
170
+ return safe;
171
+ };
172
+
173
+ if (raw === "auto") {
174
+ const apiRoot = getSomaHostApiRoot(hostDir, env);
175
+ addRoot(apiRoot);
176
+ } else if (typeof raw === "string" || Array.isArray(raw)) {
177
+ for (const rel of Array.isArray(raw) ? raw : [raw]) {
178
+ const root = safeRoot(rel);
179
+ if (root) addRoot(root);
180
+ }
181
+ } else if (typeof raw === "object") {
182
+ for (const [name, rel] of Object.entries(raw)) {
183
+ if (!ALIAS_NAME_RE.test(name)) {
184
+ diagnostics.push({ code: CODE_INVALID, severity: "error", name, message: `别名 "${name}" 不合法(只允许字母数字 _ . -,且不含斜杠)` });
185
+ continue;
186
+ }
187
+ const dir = safeRoot(rel);
188
+ if (dir) candidates.push({ name, dir });
189
+ }
190
+ } else {
191
+ invalid('必须是 "auto"、目录字符串、字符串数组或「别名 → 目录」对象');
192
+ return { ...empty, declared: true };
193
+ }
194
+
195
+ const entries = [];
196
+ const taken = new Map();
197
+ for (const candidate of candidates) {
198
+ const reason = reservedReason(candidate.name);
199
+ if (reason) {
200
+ diagnostics.push({
201
+ code: CODE_RESERVED,
202
+ severity: "error",
203
+ name: candidate.name,
204
+ message: `源码根别名 "${candidate.name}" ${reason},请把该目录改名或移出源码根`,
205
+ });
206
+ continue;
207
+ }
208
+ if (taken.has(candidate.name)) {
209
+ diagnostics.push({
210
+ code: CODE_DUPLICATE,
211
+ severity: "warning",
212
+ name: candidate.name,
213
+ message: `源码根别名 "${candidate.name}" 同时出现在 ${taken.get(candidate.name)} 与 ${candidate.dir},先声明者生效`,
214
+ });
215
+ continue;
216
+ }
217
+ taken.set(candidate.name, candidate.dir);
218
+ entries.push(candidate);
219
+ }
220
+
221
+ for (const { name, dir } of entries) {
222
+ const installed = path.join(hostDir, "node_modules", name);
223
+ const installedStat = fs.lstatSync(installed, { throwIfNoEntry: false });
224
+ if (!installedStat) continue;
225
+ let same = false;
226
+ try {
227
+ same = fs.realpathSync(installed) === fs.realpathSync(dir);
228
+ } catch {
229
+ same = false;
230
+ }
231
+ if (!same) {
232
+ diagnostics.push({
233
+ code: CODE_SHADOW,
234
+ severity: "warning",
235
+ name,
236
+ message: `源码根别名 "${name}" 遮蔽了已安装的包 node_modules/${name}:宿主代码里的 "${name}/..." 一律解析到 ${dir}(声明的别名优先于已装包)`,
237
+ });
238
+ }
239
+ }
240
+
241
+ if (firstRoot !== null) {
242
+ const tsconfig = readTsconfig(path.join(hostDir, "tsconfig.json"));
243
+ const baseUrl = tsconfig?.compilerOptions?.baseUrl;
244
+ if (typeof baseUrl === "string" && path.resolve(hostDir, baseUrl) !== path.resolve(firstRoot)) {
245
+ diagnostics.push({
246
+ code: CODE_TSCONFIG_DRIFT,
247
+ severity: "warning",
248
+ message: `tsconfig.json 的 baseUrl(${baseUrl})与 soma.sourceRoots 的源码根(${path.relative(hostDir, firstRoot) || "."})不一致:编辑器与运行期会解析到不同目录`,
249
+ });
250
+ }
251
+ }
252
+
253
+ const aliases = {};
254
+ for (const { name, dir } of entries) aliases[name] = dir;
255
+ return { declared: true, entries, aliases, diagnostics };
256
+ }
257
+
258
+ function formatDiagnostic(d) {
259
+ return `[soma-core][${d.code}] ${d.message}`;
260
+ }
261
+
262
+ /**
263
+ * 运行期 / 构建期取别名表的统一入口:error 级诊断抛出(带 `code`),warning 级每个宿主每条只打一次。
264
+ * 未声明 → `{}`。
265
+ * @returns {Record<string, string>} 别名 → 绝对目录(无尾斜杠)
266
+ */
267
+ function getSomaSourceRootAliases(hostDir, env = process.env) {
268
+ const resolved = resolveSomaSourceRoots(hostDir, env);
269
+ const errors = resolved.diagnostics.filter((d) => d.severity === "error");
270
+ if (errors.length > 0) {
271
+ const error = new Error(errors.map(formatDiagnostic).join("\n"));
272
+ error.code = errors[0].code;
273
+ error.diagnostics = errors;
274
+ throw error;
275
+ }
276
+ for (const d of resolved.diagnostics) {
277
+ const key = `${path.resolve(hostDir)}\0${d.code}\0${d.name ?? ""}\0${d.message}`;
278
+ if (warned.has(key)) continue;
279
+ warned.add(key);
280
+ // 日志前缀 `[包名][事件域]`(verify:logs):事件域取「引擎」,诊断码跟在后面
281
+ console.warn(`[soma-core][引擎] ${d.code} ${d.message}`);
282
+ }
283
+ return { ...resolved.aliases };
284
+ }
285
+
286
+ /** 说明符 → `{ dir, subpath }`(只认带斜杠的整段前缀匹配);不匹配 → null。供 esbuild 等自己解析的构建器使用 */
287
+ function matchSomaSourceRoot(aliases, specifier) {
288
+ if (typeof specifier !== "string") return null;
289
+ const slash = specifier.indexOf("/");
290
+ if (slash <= 0) return null;
291
+ const name = specifier.slice(0, slash);
292
+ const dir = Object.prototype.hasOwnProperty.call(aliases, name) ? aliases[name] : undefined;
293
+ if (dir === undefined) return null;
294
+ return { name, dir, subpath: specifier.slice(slash + 1) };
295
+ }
296
+
297
+ /** esbuild `onResolve` 的 filter:`^(?:a|b)/`;无别名 → null(调用方不注册钩子,零开销) */
298
+ function somaSourceRootFilter(aliases) {
299
+ const names = Object.keys(aliases);
300
+ if (names.length === 0) return null;
301
+ return new RegExp(`^(?:${names.map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})/`);
302
+ }
303
+
304
+ /** vitest / vite `resolve.alias` 数组:`[{ find: /^name\//, replacement: "<dir>/" }]`;未声明 → [] */
305
+ function somaViteAliases(hostDir, env = process.env) {
306
+ return Object.entries(getSomaSourceRootAliases(hostDir, env)).map(([name, dir]) => ({
307
+ find: new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`),
308
+ replacement: `${dir.split(path.sep).join("/")}/`,
309
+ }));
310
+ }
311
+
312
+ /** core 可选宿主引导模块的说明符(与 core/client/host-bridge/resolve-host-bootstrap.ts 的 HOST_BOOTSTRAP_MODULE 同值) */
313
+ const HOST_BOOTSTRAP_SPECIFIER = "@soma-host/bootstrap/soma-bootstrap";
314
+ const HOST_BOOTSTRAP_CANDIDATES = ["soma-bootstrap.ts", "soma-bootstrap.js", "soma-bootstrap.mjs"];
315
+
316
+ /**
317
+ * vitest / vite 用的完整宿主别名:源码根别名(`somaViteAliases`)+ 可选宿主引导模块。
318
+ * core 对 `@soma-host/bootstrap/soma-bootstrap` 做可选动态 import:原生 Node 下缺失会被捕获(按「无宿主钩子」处理),
319
+ * 但 vite 在转换期就要解析该说明符,宿主没有这个文件时测试直接失败——以前每个应用自己写一个空垫片。
320
+ * 这里统一给出:宿主源码根下有该文件就指向它,没有就指向 core 自带的空模块(与运行期「无钩子」同形)。
321
+ */
322
+ function somaViteHostAliases(hostDir, env = process.env) {
323
+ const sourceRoot = getSomaHostSourceRoot(path.resolve(hostDir), env);
324
+ const found = HOST_BOOTSTRAP_CANDIDATES.map((name) => path.join(sourceRoot, "bootstrap", name)).find((file) => fs.existsSync(file));
325
+ const target = found ?? path.join(__dirname, "empty-host-bootstrap.mjs");
326
+ return [
327
+ ...somaViteAliases(hostDir, env),
328
+ { find: new RegExp(`^${HOST_BOOTSTRAP_SPECIFIER}$`), replacement: target.split(path.sep).join("/") },
329
+ ];
330
+ }
331
+
332
+ module.exports = {
333
+ somaViteHostAliases,
334
+ CODE_INVALID,
335
+ CODE_RESERVED,
336
+ CODE_SHADOW,
337
+ CODE_DUPLICATE,
338
+ CODE_TSCONFIG_DRIFT,
339
+ clearSomaSourceRootCache,
340
+ resolveSomaSourceRoots,
341
+ getSomaSourceRootAliases,
342
+ matchSomaSourceRoot,
343
+ somaSourceRootFilter,
344
+ somaViteAliases,
345
+ };
@@ -0,0 +1,32 @@
1
+ import * as impl from "./source-aliases.cjs";
2
+
3
+ export interface SomaSourceRootDiagnostic {
4
+ readonly code: string;
5
+ readonly severity: "error" | "warning";
6
+ readonly message: string;
7
+ readonly name?: string;
8
+ }
9
+
10
+ export interface SomaSourceRootResolution {
11
+ readonly declared: boolean;
12
+ readonly entries: ReadonlyArray<{ readonly name: string; readonly dir: string }>;
13
+ readonly aliases: Readonly<Record<string, string>>;
14
+ readonly diagnostics: readonly SomaSourceRootDiagnostic[];
15
+ }
16
+
17
+ type Env = Readonly<Record<string, string | undefined>>;
18
+
19
+ /** 实现只有 `source-aliases.cjs` 一份(单实现);这里只补类型再导出,不另写第二份。 */
20
+ export const resolveSomaSourceRoots: (hostDir: string, env?: Env) => SomaSourceRootResolution =
21
+ impl.resolveSomaSourceRoots as never;
22
+
23
+ /** 别名 → 绝对目录;未声明 → `{}`;error 级诊断抛出(带 `code`) */
24
+ export const getSomaSourceRootAliases: (hostDir: string, env?: Env) => Record<string, string> =
25
+ impl.getSomaSourceRootAliases;
26
+
27
+ export const somaViteAliases: (hostDir: string, env?: Env) => Array<{ find: RegExp; replacement: string }> =
28
+ impl.somaViteAliases;
29
+
30
+ /** vitest / vite 的完整宿主别名:源码根别名 + 可选宿主引导模块(宿主没有该文件时指向 core 自带空模块) */
31
+ export const somaViteHostAliases: (hostDir: string, env?: Env) => Array<{ find: RegExp; replacement: string }> =
32
+ impl.somaViteHostAliases as never;
@@ -242,6 +242,7 @@ module.exports = {
242
242
  SOMA_SOURCE_PACKAGES_ENV,
243
243
  getSomaHostSourceRoot,
244
244
  getSomaHostApiRoot,
245
+ resolveSafeChildRoot,
245
246
  clearSomaAssetSourcesCache,
246
247
  getSomaAssetSources,
247
248
  listSomaSourcePackageNames,
@@ -29,6 +29,7 @@ import { runtimeAssetsOfArtifact } from './published-page-assets';
29
29
  import { resolveHostTreeCompileContext } from './resolve-host-tree-context';
30
30
  import { bindPrefixHandler, validateAddress } from '../runtime-space/inject';
31
31
  import { isHostAssemblyReady, loadHostAssemblySync } from './host-assembly';
32
+ import { currentHostDir } from './host-dir';
32
33
 
33
34
  /**
34
35
  * 解析器交回的虚拟页:声明(与 Registry 声明同一个闭集)+ 可选标题。
@@ -99,7 +100,7 @@ const loadedHosts = new Set<string>();
99
100
  * 按 `SOMA_HOST_DIR` 读 Host 装配的 `virtualPages()` 并登记一次。没有目录 / 没有 `soma.app.ts` → 什么也不做;
100
101
  * 装配形状不对在装配读取时已当场抛。
101
102
  */
102
- export function ensureHostVirtualPages(hostDir: string | undefined = process.env.SOMA_HOST_DIR): void {
103
+ export function ensureHostVirtualPages(hostDir: string | undefined = currentHostDir()): void {
103
104
  if (hostDir === undefined || hostDir.trim() === '') return;
104
105
  const key = path.resolve(hostDir);
105
106
  if (loadedHosts.has(key)) return;
@@ -154,7 +155,7 @@ function virtualPageAssets(page: SomaVirtualPage, pagePath: string): Record<stri
154
155
  const { declaration } = page;
155
156
  let treeContext;
156
157
  if (declaration.markup === 'component-tree') {
157
- treeContext = resolveHostTreeCompileContext(process.env.SOMA_HOST_DIR, { pageBase: pagePath });
158
+ treeContext = resolveHostTreeCompileContext(currentHostDir(), { pageBase: pagePath });
158
159
  if (!treeContext) {
159
160
  throw new SomaComponentTreeError({
160
161
  code: 'CT-REGISTRY-CONTEXT', phase: 'artifact', sourceId: '<virtual>', nodePath: 'treeContext',
@@ -1,5 +1,6 @@
1
- import { readFileSync, readdirSync, watch, type FSWatcher } from 'fs';
1
+ import { readFileSync, readdirSync, statSync, watch, type FSWatcher } from 'fs';
2
2
  import { resolve, extname, normalize, sep } from 'path';
3
+ import { SOMA_PIPELINE_LIMITS } from '../../../shared/registry-generated/limits';
3
4
 
4
5
  export interface ServerFileCacheOptions {
5
6
  maxFiles?: number;
@@ -12,6 +13,12 @@ interface FileEntry {
12
13
  bytes: number;
13
14
  }
14
15
 
16
+ /**
17
+ * 每个根「连续失败后至多再重试一次」:结构性上限(连续两次失败即放弃;监听真正投递过变更回调后计数清零),取设计真源 limits.json#cache.watchFailLimit。
18
+ * 缓存类里没有现成的时间间隔字段,故不用退避,改为放弃后绕过缓存。
19
+ */
20
+ const WATCH_FAIL_LIMIT: number = SOMA_PIPELINE_LIMITS.cache.watchFailLimit;
21
+
15
22
  /**
16
23
  * 服务端文件缓存单例(有界 LRU + 监听去重)
17
24
  *
@@ -29,12 +36,18 @@ export class ServerFileCache {
29
36
  private dirCache = new Map<string, string[]>();
30
37
  private watchers: FSWatcher[] = [];
31
38
  private watchedRoots = new Set<string>();
39
+ /** 各根连续的监听失败次数(建立失败或运行中 error);建立成功不清零(递归监听的错误是建立之后才异步到达的),只有该根的监听真正投递过一次变更回调才清零;达到 `WATCH_FAIL_LIMIT` 即放弃该根 */
40
+ private watchFailures = new Map<string, number>();
41
+ /** 放弃监听的根:其下的读取绕过缓存直读磁盘(无人失效时,正确性优先于命中率) */
42
+ private unwatchableRoots = new Set<string>();
32
43
  private currentFileBytes = 0;
33
44
 
34
45
  constructor(options: ServerFileCacheOptions = {}) {
35
- this.maxFiles = options.maxFiles ?? 512;
36
- this.maxFileBytes = options.maxFileBytes ?? 33_554_432;
37
- this.maxDirs = options.maxDirs ?? 256;
46
+ // 缺省值取设计真源 limits.json#cache.serverFile* / serverDir*;构造选项优先
47
+ const { serverFileMaxEntries, serverFileMaxBytes, serverDirMaxEntries } = SOMA_PIPELINE_LIMITS.cache;
48
+ this.maxFiles = options.maxFiles ?? serverFileMaxEntries;
49
+ this.maxFileBytes = options.maxFileBytes ?? serverFileMaxBytes;
50
+ this.maxDirs = options.maxDirs ?? serverDirMaxEntries;
38
51
  }
39
52
 
40
53
  static getInstance(options?: ServerFileCacheOptions): ServerFileCache {
@@ -65,6 +78,7 @@ export class ServerFileCache {
65
78
  */
66
79
  readFile(filePath: string): string {
67
80
  const key = normalize(filePath);
81
+ if (this.isUnwatchable(key)) return readFileSync(filePath, 'utf-8');
68
82
  const cached = this.fileCache.get(key);
69
83
  if (cached !== undefined) {
70
84
  this.fileCache.delete(key);
@@ -120,6 +134,9 @@ export class ServerFileCache {
120
134
  */
121
135
  readDirFiles(dirPath: string, ext: string): string[] {
122
136
  const dirKey = `${normalize(dirPath)}:${ext}`;
137
+ if (this.isUnwatchable(normalize(dirPath))) {
138
+ return readdirSync(dirPath).filter((f) => extname(f) === ext).map((f) => this.readFile(resolve(dirPath, f)));
139
+ }
123
140
  const cached = this.dirCache.get(dirKey);
124
141
  if (cached !== undefined) {
125
142
  this.dirCache.delete(dirKey);
@@ -137,6 +154,7 @@ export class ServerFileCache {
137
154
 
138
155
  readDirNames(dirPath: string, ext: string): string[] {
139
156
  const dirKey = `${normalize(dirPath)}:names:${ext}`;
157
+ if (this.isUnwatchable(normalize(dirPath))) return readdirSync(dirPath).filter((f) => extname(f) === ext);
140
158
  const cached = this.dirCache.get(dirKey);
141
159
  if (cached !== undefined) {
142
160
  this.dirCache.delete(dirKey);
@@ -161,23 +179,56 @@ export class ServerFileCache {
161
179
  this.dirCache.set(key, list);
162
180
  }
163
181
 
164
- /**
165
- * 监听目录变化,自动失效缓存。
166
- * 使用 fs.watch 递归监听;已监听同一目录或其祖先目录时自动去重。
167
- */
168
- watchAndInvalidate(rootDir: string): void {
182
+ private isUnwatchable(p: string): boolean {
183
+ const abs = resolve(p);
184
+ for (const root of this.unwatchableRoots) {
185
+ if (abs === root || abs.startsWith(root.endsWith(sep) ? root : `${root}${sep}`)) return true;
186
+ }
187
+ return false;
188
+ }
189
+
190
+ private recordWatchFailure(root: string): void {
191
+ const count = (this.watchFailures.get(root) ?? 0) + 1;
192
+ this.watchFailures.set(root, count);
193
+ if (count >= WATCH_FAIL_LIMIT) {
194
+ if (!this.unwatchableRoots.has(root)) {
195
+ // 放弃监听必须留痕(不受环境影响),否则文件改动不再失效缓存的原因无从查起
196
+ console.warn(`[soma-core][缓存] 对 ${root} 的监听连续失败 ${count} 次,已放弃监听:该目录下的文件改为每次直读、不进缓存。`);
197
+ }
198
+ this.unwatchableRoots.add(root);
199
+ this.invalidate();
200
+ }
201
+ }
202
+
203
+ /** 该根(或其祖先)当前是否有存活的监听;监听出错被移除后为 false,调用方据此重试 `watchAndInvalidate` */
204
+ isWatching(rootDir: string): boolean {
169
205
  const resolvedRoot = resolve(rootDir);
170
206
  for (const watched of this.watchedRoots) {
171
207
  if (
172
208
  resolvedRoot === watched ||
173
209
  resolvedRoot.startsWith(watched.endsWith(sep) ? watched : `${watched}${sep}`)
174
210
  ) {
175
- return;
211
+ return true;
176
212
  }
177
213
  }
214
+ return false;
215
+ }
216
+
217
+ /**
218
+ * 监听目录变化,自动失效缓存。
219
+ * 使用 fs.watch 递归监听;已监听同一目录或其祖先目录时自动去重。
220
+ */
221
+ watchAndInvalidate(rootDir: string): void {
222
+ const resolvedRoot = resolve(rootDir);
223
+ if (this.isWatching(resolvedRoot) || this.unwatchableRoots.has(resolvedRoot)) return;
178
224
 
179
225
  try {
226
+ // Node 24 / Linux 的递归监听对不存在的目录不再同步抛 ENOENT(静默成功却永不投递事件),
227
+ // 缓存会因此长期服务旧内容;先显式探测,使「根不存在」与旧行为一样走失败登记 + 绕过缓存。
228
+ statSync(resolvedRoot);
180
229
  const watcher = watch(resolvedRoot, { recursive: true }, (_event, filename) => {
230
+ // 监听投递过变更回调,证明它在工作:此前的失败计数作废
231
+ this.watchFailures.delete(resolvedRoot);
181
232
  if (!filename) return;
182
233
 
183
234
  const fullPath = normalize(resolve(resolvedRoot, filename));
@@ -189,9 +240,29 @@ export class ServerFileCache {
189
240
  this.dirCache.clear();
190
241
  });
191
242
 
243
+ // 目录被删或 inotify 耗尽时 FSWatcher 会发 error;无监听器则成为未捕获异常崩进程。
244
+ watcher.on('error', (err: unknown) => {
245
+ console.warn(
246
+ `[soma-core][缓存] fs.watch 出错(${(err as NodeJS.ErrnoException)?.code ?? (err as Error)?.message}),`
247
+ + `已关闭对 ${resolvedRoot} 的监听并清空缓存。`,
248
+ );
249
+ try {
250
+ watcher.close();
251
+ } catch {
252
+ // ignore
253
+ }
254
+ this.watchers = this.watchers.filter((w) => w !== watcher);
255
+ this.watchedRoots.delete(resolvedRoot);
256
+ this.invalidate();
257
+ this.recordWatchFailure(resolvedRoot);
258
+ });
259
+ // 监听器只负责失效缓存,进程是否存活由 HTTP 服务等决定:unref 让它不阻止进程退出(期望行为)
260
+ (watcher as { unref?: () => unknown }).unref?.();
261
+
192
262
  this.watchers.push(watcher);
193
263
  this.watchedRoots.add(resolvedRoot);
194
264
  } catch (e: any) {
265
+ this.recordWatchFailure(resolvedRoot);
195
266
  if (process.env.NODE_ENV !== 'production') {
196
267
  console.warn(
197
268
  `[soma-core][缓存] fs.watch recursive failed (${e.code ?? e.message}). ` +
@@ -231,6 +302,8 @@ export class ServerFileCache {
231
302
  }
232
303
  this.watchers = [];
233
304
  this.watchedRoots.clear();
305
+ this.watchFailures.clear();
306
+ this.unwatchableRoots.clear();
234
307
  ServerFileCache.instance = null;
235
308
  }
236
309
  }
@@ -30,6 +30,16 @@ export {
30
30
  type SomaSourcePageEntry,
31
31
  } from "./host/source-packages";
32
32
 
33
+ // 源码根别名(`package.json#soma.sourceRoots`,单实现 source-aliases.cjs)
34
+ export {
35
+ getSomaSourceRootAliases,
36
+ resolveSomaSourceRoots,
37
+ somaViteAliases,
38
+ somaViteHostAliases,
39
+ type SomaSourceRootDiagnostic,
40
+ type SomaSourceRootResolution,
41
+ } from "./host/source-aliases";
42
+
33
43
  // 页面资产与页面标记配置
34
44
  export {
35
45
  loadSomaServerPageAssets,
@@ -20,7 +20,7 @@ import fs from 'node:fs';
20
20
  import path from 'node:path';
21
21
  import { currentRuntimeLayout } from '../runtime-space/root';
22
22
  import type { SomaDataFieldConfig } from '../../shared/types/data-config.types';
23
- import { withRegistryLock, writeFileAtomic } from './registry-file-lock';
23
+ import { assertRegistryLockOwned, withRegistryLock, writeFileAtomic } from './registry-file-lock';
24
24
  import { RegistryError } from './registry-error';
25
25
  import { scanCredentialLeak } from './validation/credential-ban';
26
26
  import { SOMA_PIPELINE_LIMITS } from '../../shared/registry-generated/limits';
@@ -178,6 +178,8 @@ export class ApiRegistryStore {
178
178
  if (!record) {
179
179
  throw new ApiRegistryError(ApiRegistryErrorCodes.API_NOT_FOUND, `接口未注册:${safeName}`);
180
180
  }
181
+ // 删除同样要先确认锁仍归自己:锁被接管后恢复的旧持有者不能删掉新持有者刚写入的记录
182
+ assertRegistryLockOwned(this.fileOf(safeName));
181
183
  fs.rmSync(this.fileOf(safeName), { force: true });
182
184
  this.cache.delete(safeName);
183
185
  return cloneApiRecord(record);
@@ -56,7 +56,6 @@ export interface CompiledDeclaration extends ComponentTreeRuntimeEnvelope {
56
56
  assetSupplyKey?: string;
57
57
  uiConfig?: unknown;
58
58
  eventConfig?: unknown;
59
- triggerConfig?: unknown;
60
59
  timerConfig?: unknown;
61
60
  styleConfig?: unknown;
62
61
  dataConfig?: unknown;
@@ -123,7 +122,6 @@ export function precompileDeclaration(
123
122
  } : supplyKey ? { assetSupplyKey: supplyKey } : {}),
124
123
  uiConfig: page.uiConfig,
125
124
  eventConfig: page.eventConfig,
126
- triggerConfig: page.triggers,
127
125
  timerConfig: page.timers,
128
126
  ...(page.styleConfig ? { styleConfig: page.styleConfig } : {}),
129
127
  ...(page.dataConfig ? { dataConfig: page.dataConfig } : {}),
@@ -46,6 +46,7 @@ import type { SomaPageGenerationAssets } from '../../shared/types/compile-port.t
46
46
  import type { TreeCompileContext } from '../../shared/types/component-tree.types';
47
47
  import { resolveHostTreeCompileContext } from '../host/resolve-host-tree-context';
48
48
  import { SOMA_PIPELINE_LIMITS } from '../../shared/registry-generated/limits';
49
+ import { currentHostDir } from '../host/host-dir';
49
50
 
50
51
  const MAX_CAS_ATTEMPTS = SOMA_PIPELINE_LIMITS.retry.casAttempts;
51
52
  const AGGREGATE_SCHEMA_VERSION = 1;
@@ -326,7 +327,7 @@ export class ConditionalPageRegistryRepository implements PageRegistryRepository
326
327
  getTreeCompileContext(name: string, app: string): TreeCompileContext | undefined {
327
328
  return this.options.treeContextResolver
328
329
  ? this.options.treeContextResolver(name, app)
329
- : resolveHostTreeCompileContext(process.env.SOMA_HOST_DIR, { pageBase: name, app });
330
+ : resolveHostTreeCompileContext(currentHostDir(), { pageBase: name, app });
330
331
  }
331
332
 
332
333
  async publish(
@@ -57,6 +57,7 @@ import { scanRegionScopes } from './validation/region-scopes';
57
57
  import { SOMA_PIPELINE_LIMITS } from '../../shared/registry-generated/limits';
58
58
  import { validateAddressText } from '../../shared/runtime-address';
59
59
  import { SOMA_PIPELINE_ERROR_CODES } from '../../shared/registry-generated/error-codes';
60
+ import { currentHostDir } from '../host/host-dir';
60
61
 
61
62
  /** 页面名约束:小写字母 / 数字 / 连字符,1~64 位(可直接用作文件名与 URL 片段) */
62
63
  export const PAGE_NAME_PATTERN = /^[a-z0-9-]{1,64}$/;
@@ -408,7 +409,7 @@ export class PageRegistryStore {
408
409
  this.baseDir = path.resolve(options.baseDir ?? currentRuntimeLayout().dirs.pages);
409
410
  this.now = options.now ?? Date.now;
410
411
  this.treeContextResolver = options.treeContextResolver ?? ((name, app) => (
411
- resolveHostTreeCompileContext(process.env.SOMA_HOST_DIR, { pageBase: name, app })
412
+ resolveHostTreeCompileContext(currentHostDir(), { pageBase: name, app })
412
413
  ));
413
414
  }
414
415