soma-core 2.2.4 → 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 +44 -9
  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
@@ -1,24 +1,38 @@
1
1
  // core/client/parser/style-config-parser.ts — SOMA 样式配置解析器
2
2
  // 负责将 _style.yaml 解析后的原始对象转换为类型安全的 StyleConfig 结构
3
3
 
4
+ import { SomaError } from '../../shared/soma-error';
4
5
  import type {
5
6
  SomaStyleViolationKind,
6
7
  StyleConfig,
7
- StyleStateRule,
8
+ StyleTierBinding,
8
9
  StyleTransition,
9
10
  TransitionTrigger,
10
11
  } from '../../shared/types/style-config.types';
12
+ import {
13
+ SOMA_STYLE_COMPARE_KEYS,
14
+ SOMA_STYLE_COMPARE_REMEDY,
15
+ SOMA_STYLE_TIER_KEYS,
16
+ SOMA_STYLE_TIER_MAX,
17
+ SOMA_STYLE_TIER_NAME_PATTERN,
18
+ isPureBindPath,
19
+ isTierName,
20
+ type SomaPureBindingCode,
21
+ } from '../../shared/pure-binding';
11
22
 
12
23
  // ─── 错误类 ───────────────────────────────────────────────────────────────────
13
24
 
14
- export class SomaStyleConfigError extends Error {
25
+ export class SomaStyleConfigError extends SomaError {
15
26
  public readonly path: string;
16
27
  /** 违规类别;仅结构化校验失败时缺省(那类失败没有"类别"可言) */
17
28
  public readonly kind?: SomaStyleViolationKind;
29
+ /** 纯绑定违规码(样式比较形);其余解析错误无码 */
30
+ public readonly code?: SomaPureBindingCode;
18
31
 
19
- constructor(message: string, path: string = '', kind?: SomaStyleViolationKind) {
32
+ constructor(message: string, path: string = '', kind?: SomaStyleViolationKind, code?: SomaPureBindingCode) {
20
33
  const prefix = path ? ` (路径: ${path})` : '';
21
- super(`[SOMA StyleConfigParser] ${message}${prefix}`);
34
+ super(`[SOMA StyleConfigParser] ${code ? `[${code}] ` : ''}${message}${prefix}`);
35
+ this.code = code;
22
36
  this.name = 'SomaStyleConfigError';
23
37
  this.path = path;
24
38
  this.kind = kind;
@@ -86,20 +100,24 @@ function assertNoLayoutClasses(
86
100
  }
87
101
  }
88
102
 
89
- // ─── 内部校验函数 ─────────────────────────────────────────────────────────────
103
+ // ─── 键闭集(宽进改严:闭集外的键一律报错,不静默忽略) ─────────────────────────
90
104
 
91
- function isValidConditionPath(path: string): boolean {
92
- if (!path) return false;
93
- // 纯属性路径:仅允许 字母/数字/下划线 + 点分隔
94
- return /^[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*$/.test(path);
95
- }
105
+ const STYLE_TOP_KEYS = new Set(['host', 'base', 'states', 'transitions', 'themes']);
106
+ const TRANSITION_KEYS = new Set(['trigger', 'apply']);
96
107
 
97
- function isPrimitiveValue(value: unknown): value is string | number | boolean | null {
98
- if (value === null) return true;
99
- const t = typeof value;
100
- return t === 'string' || t === 'number' || t === 'boolean';
108
+ function assertClosedKeys(obj: Record<string, unknown>, allowed: ReadonlySet<string>, what: string, path: string): void {
109
+ for (const key of Object.keys(obj)) {
110
+ if (!allowed.has(key)) {
111
+ throw new SomaStyleConfigError(
112
+ `${what}有未知键 "${key}"(支持: ${[...allowed].join(' / ')});样式只做视觉翻译,条件求值与逻辑归展示对象 / 业务对象`,
113
+ path ? `${path}.${key}` : key,
114
+ );
115
+ }
116
+ }
101
117
  }
102
118
 
119
+ // ─── 内部校验函数 ─────────────────────────────────────────────────────────────
120
+
103
121
  function validateSomaId(somaId: string, path: string): void {
104
122
  if (!somaId || typeof somaId !== 'string') {
105
123
  throw new SomaStyleConfigError(`data-soma-id 不能为空`, path);
@@ -129,74 +147,79 @@ function parseBase(raw: unknown, path: string): Record<string, string> {
129
147
  return result;
130
148
  }
131
149
 
132
- // ─── states 解析 ──────────────────────────────────────────────────────────────
150
+ // ─── 类名档位绑定(states / active_state 共用) ────────────────────────────────
133
151
 
134
- function parseStateRule(raw: unknown, path: string): StyleStateRule {
135
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
136
- throw new SomaStyleConfigError(`状态规则必须是对象`, path);
152
+ /**
153
+ * 解析 `{ bind, tiers }`:bind 是展示对象成员的纯路径,tiers 是 档位名 → 类名串 的闭集映射。
154
+ * 旧的 `condition` + `value` 比较形一律拒收(CORE-STYLE-COMPARE-FORBIDDEN),不留兼容。
155
+ */
156
+ function parseTierBinding(obj: Record<string, unknown>, path: string, extraKeys: readonly string[]): StyleTierBinding {
157
+ for (const key of Object.keys(obj)) {
158
+ if (SOMA_STYLE_COMPARE_KEYS.has(key)) {
159
+ throw new SomaStyleConfigError(
160
+ `样式不做比较:不再支持 "${key}"(原「condition 路径 == value 时加类」形态已删除);${SOMA_STYLE_COMPARE_REMEDY}`,
161
+ `${path}.${key}`,
162
+ undefined,
163
+ 'CORE-STYLE-COMPARE-FORBIDDEN',
164
+ );
165
+ }
137
166
  }
167
+ assertClosedKeys(obj, new Set([...SOMA_STYLE_TIER_KEYS, ...extraKeys]), '类名档位绑定', path);
138
168
 
139
- const obj = raw as Record<string, unknown>;
140
-
141
- // condition
142
- if (!obj.condition || typeof obj.condition !== 'string') {
169
+ if (!isPureBindPath(obj.bind)) {
143
170
  throw new SomaStyleConfigError(
144
- `condition 必须是非空字符串,当前值: ${JSON.stringify(obj.condition)}`,
145
- path,
171
+ `bind 必须是展示对象成员的纯路径(如 "page.statusTier"),禁止取反 / 管道 / 运算符,当前值: ${JSON.stringify(obj.bind)}`,
172
+ `${path}.bind`,
146
173
  );
147
174
  }
148
- if (!isValidConditionPath(obj.condition)) {
149
- throw new SomaStyleConfigError(
150
- `condition 必须是纯属性路径(如 "a.b.c"),禁止包含运算符,当前值: "${obj.condition}"`,
151
- path,
152
- );
153
- }
154
-
155
- // value
156
- if (!('value' in obj)) {
157
- throw new SomaStyleConfigError(`缺少必填字段 value`, path);
175
+ if (!obj.tiers || typeof obj.tiers !== 'object' || Array.isArray(obj.tiers)) {
176
+ throw new SomaStyleConfigError(`tiers 必须是对象(档位名 → 类名串)`, `${path}.tiers`);
158
177
  }
159
- if (!isPrimitiveValue(obj.value)) {
178
+ const entries = Object.entries(obj.tiers as Record<string, unknown>);
179
+ if (entries.length === 0 || entries.length > SOMA_STYLE_TIER_MAX) {
160
180
  throw new SomaStyleConfigError(
161
- `value 必须是基础类型(string/number/boolean/null),当前值: ${JSON.stringify(obj.value)}`,
162
- path,
181
+ `tiers 的档位数必须在 1 ~ ${SOMA_STYLE_TIER_MAX} 之间,当前 ${entries.length}`,
182
+ `${path}.tiers`,
163
183
  );
164
184
  }
165
-
166
- // apply
167
- if (!obj.apply || typeof obj.apply !== 'string') {
168
- throw new SomaStyleConfigError(
169
- `apply 必须是非空 CSS 类名字符串,当前值: ${JSON.stringify(obj.apply)}`,
170
- path,
171
- );
185
+ const tiers: Record<string, string> = {};
186
+ for (const [tier, classes] of entries) {
187
+ if (!isTierName(tier)) {
188
+ throw new SomaStyleConfigError(
189
+ `档位名 "${tier}" 不合闭集形态(${SOMA_STYLE_TIER_NAME_PATTERN})`,
190
+ `${path}.tiers.${tier}`,
191
+ );
192
+ }
193
+ if (typeof classes !== 'string' || !classes.trim()) {
194
+ throw new SomaStyleConfigError(
195
+ `档位 "${tier}" 的值必须是非空 CSS 类名字符串,当前值: ${JSON.stringify(classes)}`,
196
+ `${path}.tiers.${tier}`,
197
+ );
198
+ }
199
+ assertNoLayoutClasses(classes, `${path}.tiers.${tier}`, true);
200
+ tiers[tier] = classes;
172
201
  }
173
- assertNoLayoutClasses(obj.apply, `${path}.apply`, true);
174
-
175
- return {
176
- condition: obj.condition,
177
- value: obj.value as string | number | boolean | null,
178
- apply: obj.apply,
179
- };
202
+ return { bind: obj.bind, tiers };
180
203
  }
181
204
 
182
- function parseStates(raw: unknown, path: string): Record<string, StyleStateRule[]> {
205
+ // ─── states 解析 ──────────────────────────────────────────────────────────────
206
+
207
+ function parseStates(raw: unknown, path: string): Record<string, StyleTierBinding> {
183
208
  if (!raw) return {};
184
209
  if (typeof raw !== 'object' || Array.isArray(raw)) {
185
- throw new SomaStyleConfigError(`states 必须是对象(somaId → 规则数组)`, path);
210
+ throw new SomaStyleConfigError(`states 必须是对象(somaId → { bind, tiers })`, path);
186
211
  }
187
212
 
188
- const result: Record<string, StyleStateRule[]> = {};
189
- for (const [somaId, rules] of Object.entries(raw as Record<string, unknown>)) {
213
+ const result: Record<string, StyleTierBinding> = {};
214
+ for (const [somaId, binding] of Object.entries(raw as Record<string, unknown>)) {
190
215
  validateSomaId(somaId, `${path}.${somaId}`);
191
- if (!Array.isArray(rules)) {
216
+ if (!binding || typeof binding !== 'object' || Array.isArray(binding)) {
192
217
  throw new SomaStyleConfigError(
193
- `states.${somaId} 的值必须是数组,当前类型: ${typeof rules}`,
218
+ `states.${somaId} 的值必须是 { bind, tiers } 对象(原规则数组形态已删除)`,
194
219
  `${path}.${somaId}`,
195
220
  );
196
221
  }
197
- result[somaId] = rules.map((rule, idx) =>
198
- parseStateRule(rule, `${path}.${somaId}[${idx}]`),
199
- );
222
+ result[somaId] = parseTierBinding(binding as Record<string, unknown>, `${path}.${somaId}`, []);
200
223
  }
201
224
  return result;
202
225
  }
@@ -224,6 +247,20 @@ function parseTransition(raw: unknown, somaId: string, path: string): StyleTrans
224
247
  );
225
248
  }
226
249
 
250
+ // active_state:纯绑定(bind + tiers),不再有 apply / condition / value
251
+ if (obj.trigger === 'active_state') {
252
+ const { trigger: _trigger, ...rest } = obj;
253
+ if ('apply' in rest && !Object.keys(rest).some((key) => SOMA_STYLE_COMPARE_KEYS.has(key))) {
254
+ throw new SomaStyleConfigError(
255
+ `active_state 用 tiers 给出各档位类名,不再有 apply;${SOMA_STYLE_COMPARE_REMEDY}`,
256
+ `${path}.apply`,
257
+ );
258
+ }
259
+ return { trigger: 'active_state', ...parseTierBinding(rest, path, []) };
260
+ }
261
+
262
+ assertClosedKeys(obj, TRANSITION_KEYS, '过渡配置', path);
263
+
227
264
  // apply
228
265
  if (!obj.apply || typeof obj.apply !== 'string') {
229
266
  throw new SomaStyleConfigError(
@@ -233,42 +270,10 @@ function parseTransition(raw: unknown, somaId: string, path: string): StyleTrans
233
270
  }
234
271
  assertNoLayoutClasses(obj.apply, `${path}.apply`, true);
235
272
 
236
- const result: StyleTransition = {
237
- trigger: obj.trigger as TransitionTrigger,
273
+ return {
274
+ trigger: obj.trigger as Exclude<TransitionTrigger, 'active_state'>,
238
275
  apply: obj.apply,
239
276
  };
240
-
241
- // active_state 专有字段
242
- if (obj.trigger === 'active_state') {
243
- if (!obj.condition || typeof obj.condition !== 'string') {
244
- throw new SomaStyleConfigError(
245
- `active_state 类型的 trigger 必须提供 condition 字段`,
246
- path,
247
- );
248
- }
249
- if (!isValidConditionPath(obj.condition)) {
250
- throw new SomaStyleConfigError(
251
- `condition 必须是纯属性路径,当前值: "${obj.condition}"`,
252
- path,
253
- );
254
- }
255
- if (!('value' in obj)) {
256
- throw new SomaStyleConfigError(
257
- `active_state 类型的 trigger 必须提供 value 字段`,
258
- path,
259
- );
260
- }
261
- if (!isPrimitiveValue(obj.value)) {
262
- throw new SomaStyleConfigError(
263
- `value 必须是基础类型,当前值: ${JSON.stringify(obj.value)}`,
264
- path,
265
- );
266
- }
267
- result.condition = obj.condition;
268
- result.value = obj.value as string | number | boolean | null;
269
- }
270
-
271
- return result;
272
277
  }
273
278
 
274
279
  function parseTransitions(raw: unknown, path: string): Record<string, StyleTransition> {
@@ -293,7 +298,7 @@ function parseTransitions(raw: unknown, path: string): Record<string, StyleTrans
293
298
  * 校验规则:
294
299
  * - host 必须是非空字符串
295
300
  * - base 的值必须是纯 CSS 类名字符串;core 不解析也不编译具体类名
296
- * - states 的 condition 必须是纯属性路径,value 必须是基础类型
301
+ * - states / transitions.active_state 是纯绑定:`bind` 纯路径 + `tiers` 档位闭集(成员的值就是档位名),不再有 condition / value 比较
297
302
  * - transitions 的 trigger 必须是有效枚举值
298
303
  * - base 命中布局类模式即失败;states / transitions 放行显隐对(F-06)
299
304
  * - themes 段已退役(主题是编译期事,T19):写了内容就明确拒收,不静默丢弃(空表等于没写)
@@ -308,6 +313,7 @@ export function parseStyleConfig(raw: unknown): StyleConfig {
308
313
  }
309
314
 
310
315
  const obj = raw as Record<string, unknown>;
316
+ assertClosedKeys(obj, STYLE_TOP_KEYS, '样式配置', '');
311
317
 
312
318
  // host
313
319
  if (!obj.host || typeof obj.host !== 'string') {
@@ -16,6 +16,11 @@ function parseTimerItem(raw: unknown, index: number): ParsedTimer {
16
16
  }
17
17
 
18
18
  const item = raw as Record<string, unknown>;
19
+ for (const key of Object.keys(item)) {
20
+ if (!['id', 'tick', 'interval', 'delay', 'once'].includes(key)) {
21
+ throw new SomaTimerParseError(`timers[${index}] 有未知键 "${key}"(支持: id / tick / interval / delay / once);定时器只触发管道,条件判断归 Domain`);
22
+ }
23
+ }
19
24
 
20
25
  if (typeof item.id !== 'string' || !item.id.trim()) {
21
26
  throw new SomaTimerParseError(`timers[${index}].id 必须是非空字符串`);
@@ -68,3 +73,19 @@ export function compileTimer(timer: ParsedTimer): import('../../shared/types/tim
68
73
  eventKey: `tick:${somaId}`,
69
74
  };
70
75
  }
76
+
77
+ /** 从 event 配置根对象分离 timers 与事件声明(`triggers` 已删除:它不再是保留键,写了按事件声明形态报错) */
78
+ export function splitEventConfigRaw(raw: unknown): {
79
+ eventsRaw: Record<string, unknown>;
80
+ timers: ParsedTimer[];
81
+ } {
82
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
83
+ return { eventsRaw: {}, timers: [] };
84
+ }
85
+
86
+ const { timers: timersRaw, ...eventsRaw } = raw as Record<string, unknown>;
87
+ return {
88
+ eventsRaw,
89
+ timers: parseTimers(timersRaw),
90
+ };
91
+ }
@@ -1,6 +1,7 @@
1
1
  // core/client/parser/ui-config-parser.ts — SOMA UI 配置解析器
2
2
  // 负责将 YAML 解析后的原始对象转换为类型安全的 UiConfig 结构
3
3
 
4
+ import { SomaError } from '../../shared/soma-error';
4
5
  import type {
5
6
  UiConfig,
6
7
  ShowMapping,
@@ -12,7 +13,6 @@ import type {
12
13
  } from '../../shared/types/ui-config.types';
13
14
  import { SOMA_FRAGMENTS_FORMAT } from '../../shared/types/ui-config.types';
14
15
  import { SOMA_FRAGMENTS_KEY } from '../../shared/fragments-section';
15
- import { inspectShowWhen, isShowWhenObject, type SomaShowWhen } from '../../shared/show-when';
16
16
  import type { OnChangeRule } from '../../shared/types/watcher.types';
17
17
  import type { SomaScopeDecl, SomaScopeGateDecl, SomaScopeMirrorDecl, SomaScopeSliceDecl } from '../../shared/types/region-scope.types';
18
18
  import { formatScopeIssues, validateScopeDecls } from '../../shared/region-scope-decl';
@@ -22,6 +22,14 @@ import {
22
22
  scopesConflictMessage,
23
23
  } from '../../shared/page-scopes';
24
24
  import { parsePageState } from './page-state-parser';
25
+ import {
26
+ findNegatedPathIn,
27
+ hasNegationPrefix,
28
+ isPureRolePath,
29
+ negationMessage,
30
+ roleByMessage,
31
+ type SomaPureBindingCode,
32
+ } from '../../shared/pure-binding';
25
33
 
26
34
  // ─── 错误类 ───────────────────────────────────────────────────────────────────
27
35
 
@@ -29,14 +37,17 @@ import { parsePageState } from './page-state-parser';
29
37
  * UI 配置解析错误
30
38
  * 携带错误路径信息以便定位问题
31
39
  */
32
- export class SomaUiConfigError extends Error {
40
+ export class SomaUiConfigError extends SomaError {
33
41
  public readonly path: string;
42
+ /** 纯绑定违规码(取反 / role_by 非纯路径);其余解析错误无码 */
43
+ public readonly code?: SomaPureBindingCode;
34
44
 
35
- constructor(message: string, path: string = '') {
45
+ constructor(message: string, path: string = '', code?: SomaPureBindingCode) {
36
46
  const prefix = path ? ` (路径: ${path})` : '';
37
- super(`[SOMA UiConfigParser] ${message}${prefix}`);
47
+ super(`[SOMA UiConfigParser] ${code ? `[${code}] ` : ''}${message}${prefix}`);
38
48
  this.name = 'SomaUiConfigError';
39
49
  this.path = path;
50
+ this.code = code;
40
51
  }
41
52
  }
42
53
 
@@ -61,10 +72,28 @@ export interface SomaUiConfigParseOptions {
61
72
  * @param path - 当前路径(用于错误信息)
62
73
  * @throws SomaUiConfigError 校验失败时抛出
63
74
  */
75
+ /** 键闭集:闭集外的键一律报错(页面只做视觉与纯绑定,逻辑写法不会被静默忽略) */
76
+ function assertClosedUiKeys(obj: object, allowed: readonly string[], what: string, path: string): void {
77
+ for (const key of Object.keys(obj)) {
78
+ if (!allowed.includes(key)) {
79
+ throw new SomaUiConfigError(
80
+ `${what}有未知键 "${key}"(支持: ${allowed.join(' / ')});页面不求值、不判断、不派生,逻辑归展示对象 / 业务对象`,
81
+ `${path}.${key}`,
82
+ );
83
+ }
84
+ }
85
+ }
86
+
87
+ const BIND_KEYS = ['obj', 'var', 'onChange', 'role_by', 'key', 'repeatPlanId', 'collectionSlot'] as const;
88
+ const ONCHANGE_KEYS = ['condition', 'callback', 'refresh', 'debounce'] as const;
89
+ const NESTED_SHOW_KEYS = ['bind', 'show', 'props', 'when'] as const;
90
+ const EXTENDED_SHOW_KEYS = ['text', 'model', 'when', 'class', 'show', 'props'] as const;
91
+
64
92
  function validateBind(bind: any, path: string): asserts bind is BindDeclaration {
65
93
  if (!bind || typeof bind !== 'object') {
66
94
  throw new SomaUiConfigError(`bind 必须是对象`, path);
67
95
  }
96
+ assertClosedUiKeys(bind, BIND_KEYS, 'bind ', path);
68
97
 
69
98
  if (!bind.obj || typeof bind.obj !== 'string') {
70
99
  throw new SomaUiConfigError(
@@ -80,6 +109,10 @@ function validateBind(bind: any, path: string): asserts bind is BindDeclaration
80
109
  );
81
110
  }
82
111
 
112
+ if (bind.role_by !== undefined && !isPureRolePath(bind.role_by)) {
113
+ throw new SomaUiConfigError(roleByMessage(bind.role_by), `${path}.role_by`, 'CORE-PAGE-ROLE-BY-INVALID');
114
+ }
115
+
83
116
  if ('onChange' in bind && bind.onChange !== undefined) {
84
117
  parseOnChangeRules(bind.onChange, `${path}.onChange`);
85
118
  }
@@ -111,6 +144,7 @@ function parseOnChangeRules(raw: unknown, path: string): OnChangeRule[] {
111
144
  }
112
145
 
113
146
  const rule = item as Record<string, unknown>;
147
+ assertClosedUiKeys(rule, ONCHANGE_KEYS, 'onChange 条目', itemPath);
114
148
  if (typeof rule.condition !== 'string' || !rule.condition.trim()) {
115
149
  throw new SomaUiConfigError('condition 必须是非空字符串', itemPath);
116
150
  }
@@ -151,6 +185,9 @@ function parseInitProps(raw: unknown, path: string): Record<string, unknown> {
151
185
  if (!key.trim()) {
152
186
  throw new SomaUiConfigError('initProps 的键不能为空', path);
153
187
  }
188
+ if (key.split('.').some((part) => ['__proto__', 'prototype', 'constructor'].includes(part))) {
189
+ throw new SomaUiConfigError(`initProps 的键 "${key}" 含不安全路径段`, path);
190
+ }
154
191
  result[key] = value;
155
192
  }
156
193
  return result;
@@ -179,20 +216,28 @@ function isExtendedShowValue(value: any): boolean {
179
216
 
180
217
  // ─── show 映射解析 ────────────────────────────────────────────────────────────
181
218
 
182
- /** `when` 的值:字符串原样;对象谓词 `{ field, op, value? }` 过闭集校验后原样保留 */
183
- function parseWhenValue(raw: unknown, path: string): SomaShowWhen {
184
- if (typeof raw === 'string') return raw;
185
- if (isShowWhenObject(raw)) {
186
- const issues = inspectShowWhen(raw, 'when');
187
- if (issues.length > 0) throw new SomaUiConfigError(issues.join(';'), path);
188
- return { ...raw };
219
+ /** `when` 的值:只许纯路径字符串(绑定展示对象给出的布尔值);对象谓词等其它形态一律拒收 */
220
+ function parseWhenValue(raw: unknown, path: string): string {
221
+ if (typeof raw === 'string') {
222
+ if (hasNegationPrefix(raw)) {
223
+ throw new SomaUiConfigError(negationMessage('when', raw), path, 'CORE-PAGE-NEGATE-FORBIDDEN');
224
+ }
225
+ return raw;
189
226
  }
190
227
  throw new SomaUiConfigError(
191
- `when 必须是字符串或 { field, op, value? } 对象,当前值: ${JSON.stringify(raw)}`,
228
+ `when 必须是路径字符串(页面不求值,布尔值由展示对象给出),当前值: ${JSON.stringify(raw)}`,
192
229
  path,
193
230
  );
194
231
  }
195
232
 
233
+ /** props 值里不许有 `!path` 取反(普通文字如 `!关闭` 不是路径,放行) */
234
+ function assertNoNegatedProps(props: unknown, path: string): void {
235
+ const hit = findNegatedPathIn(props);
236
+ if (hit) {
237
+ throw new SomaUiConfigError(negationMessage(`props.${hit.at}`, hit.value), `${path}.props`, 'CORE-PAGE-NEGATE-FORBIDDEN');
238
+ }
239
+ }
240
+
196
241
  /**
197
242
  * 递归解析 show 映射
198
243
  *
@@ -230,6 +275,7 @@ function parseShowMapping(rawShow: any, path: string, options?: SomaUiConfigPars
230
275
  } else if (isNestedShowMapping(value)) {
231
276
  // 嵌套绑定:含 bind + show
232
277
  const nestedPath = `${currentPath}.bind`;
278
+ assertClosedUiKeys(value, NESTED_SHOW_KEYS, '嵌套绑定', currentPath);
233
279
  validateBind(value.bind, nestedPath);
234
280
  if (value.bind.collectionSlot !== undefined && options?.collectionBindingStage !== 'definition-source') {
235
281
  throw new SomaUiConfigError('collectionSlot 仅允许受信组件定义源;运行时必须使用准备计划', nestedPath);
@@ -253,12 +299,14 @@ function parseShowMapping(rawShow: any, path: string, options?: SomaUiConfigPars
253
299
  if (!value.props || typeof value.props !== 'object' || Array.isArray(value.props)) {
254
300
  throw new SomaUiConfigError('props 必须是对象', currentPath);
255
301
  }
302
+ assertNoNegatedProps(value.props, currentPath);
256
303
  nested.props = { ...value.props };
257
304
  }
258
305
 
259
306
  result[key] = nested;
260
307
  } else if (typeof value === 'object' && value !== null && isExtendedShowValue(value)) {
261
308
  // 扩展绑定:含 text / model / when / class / show
309
+ assertClosedUiKeys(value, EXTENDED_SHOW_KEYS, '展示绑定', currentPath);
262
310
  const extended: ExtendedShowValue = {};
263
311
 
264
312
  if ('text' in value && value.text !== undefined) {
@@ -301,6 +349,9 @@ function parseShowMapping(rawShow: any, path: string, options?: SomaUiConfigPars
301
349
  `${currentPath}.class`,
302
350
  );
303
351
  }
352
+ if (hasNegationPrefix(condition)) {
353
+ throw new SomaUiConfigError(negationMessage(`class "${className}"`, condition), `${currentPath}.class`, 'CORE-PAGE-NEGATE-FORBIDDEN');
354
+ }
304
355
  classMap[className] = condition;
305
356
  }
306
357
  extended.class = classMap;
@@ -317,6 +368,7 @@ function parseShowMapping(rawShow: any, path: string, options?: SomaUiConfigPars
317
368
  currentPath,
318
369
  );
319
370
  }
371
+ assertNoNegatedProps(value.props as Record<string, unknown>, currentPath);
320
372
  extended.props = { ...(value.props as Record<string, unknown>) };
321
373
  }
322
374
 
@@ -136,7 +136,7 @@ export function createGeneratedPagePreview(
136
136
  artifact: compiled.artifact,
137
137
  uiYaml: '', eventYaml: '', styleYaml: '', DomainClass: getPreviewPageRoot(),
138
138
  uiConfig: compiled.uiConfig as never, eventConfig: compiled.eventConfig as never,
139
- triggerConfig: compiled.triggerConfig as never, timerConfig: compiled.timerConfig as never,
139
+ timerConfig: compiled.timerConfig as never,
140
140
  ...(compiled.styleConfig !== undefined ? { styleConfig: compiled.styleConfig as never } : {}),
141
141
  ...(compiled.dataConfig !== undefined ? { dataConfig: compiled.dataConfig as never } : {}),
142
142
  ...(compiled.compiledStyles !== undefined ? { compiledStyles: compiled.compiledStyles as never } : {}),
@@ -46,6 +46,7 @@ import { createIdentityPort, type SomaIdentityPort, type SomaIdentityProvider }
46
46
  import { createAppConfigPort, type SomaAppConfigPort } from '../infra/config/feature-flags';
47
47
  import { createShortcutRegistry, shortcutsDesign } from './shortcuts';
48
48
  import type { SomaShortcutRegistry } from '../../shared/types/write-runtime.types';
49
+ import { SOMA_PIPELINE_HOST_HTTP_REQUEST_TIMEOUT_MS } from 'soma-foundation/values';
49
50
 
50
51
  /** Runtime infrastructure injected into domain instances by bootstrap */
51
52
  export interface SomaRuntimeServices extends SomaRuntimeServicesBase {
@@ -200,7 +201,7 @@ export function createDefaultRuntimeServices(options?: {
200
201
  const router = new SomaRouter(options?.initialPath ?? '/');
201
202
  const http = new SomaHttpService({
202
203
  baseURL: String(config.get('apiBaseUrl') ?? '/api'),
203
- timeout: Number(config.get('requestTimeout') ?? 30000),
204
+ timeout: Number(config.get('requestTimeout') ?? SOMA_PIPELINE_HOST_HTTP_REQUEST_TIMEOUT_MS),
204
205
  defaultHeaders: () => ({
205
206
  'x-soma-page-href': router.getCurrentPath().split('#')[0].split('?')[0] || '/',
206
207
  }),
@@ -27,6 +27,11 @@ export class SomaSnapshotStore {
27
27
  return snapshot.id;
28
28
  }
29
29
 
30
+ /** 释放一条快照(不存在则什么也不做):热替换等内部流程用完自己 capture 的快照即释放,不占环形容量 */
31
+ release(id: number): void {
32
+ this.snapshots = this.snapshots.filter((item) => item.id !== id);
33
+ }
34
+
30
35
  restore(id: number, root: Record<string, any>): void {
31
36
  const snapshot = this.snapshots.find((item) => item.id === id);
32
37
  if (!snapshot) {
@@ -11,7 +11,7 @@
11
11
  // 可诊断性,并在控制台给出可定位的告警。
12
12
 
13
13
  /** 会被浏览器当作 URL 加载/跳转的属性 */
14
- const URL_BEARING_ATTRS = new Set([
14
+ export const URL_BEARING_ATTR_NAMES = [
15
15
  'href',
16
16
  'src',
17
17
  'srcset',
@@ -22,25 +22,68 @@ const URL_BEARING_ATTRS = new Set([
22
22
  'xlink:href',
23
23
  'ping',
24
24
  'background',
25
- ]);
25
+ ] as const;
26
+
27
+ export const URL_BEARING_ATTRS: ReadonlySet<string> = new Set(URL_BEARING_ATTR_NAMES);
26
28
 
27
29
  /** 危险伪协议:命中即阻断 */
28
- const BLOCKED_SCHEMES = ['javascript:', 'vbscript:', 'data:', 'file:', 'blob:'];
30
+ export const BLOCKED_SCHEMES = ['javascript:', 'vbscript:', 'data:', 'file:', 'blob:'] as const;
31
+
32
+ /** 纯位图图片 data URI:在媒体展示属性(src/srcset/poster/background)上安全 */
33
+ const SAFE_RASTER_DATA_URI = /^data:image\/(png|jpe?g|gif|webp|avif);base64,/i;
29
34
 
30
- /** data: 的白名单例外——图片类 data URI 在 src 上是常见且安全的用法 */
35
+ /** svg+xml data URI:即使是媒体展示也仅限 src/poster/background(不放行 srcset,更绝不在导航/提交属性上放行) */
36
+ const SAFE_SVG_DATA_URI = /^data:image\/svg\+xml;base64,/i;
37
+
38
+ /** data: 的白名单例外——图片类 data URI 全集(用于 resolveSafeUrl 的 allowDataImage) */
31
39
  const SAFE_DATA_URI = /^data:image\/(png|jpe?g|gif|webp|avif|svg\+xml);base64,/i;
32
40
 
33
41
  /** 拦截后写入的安全占位值 */
34
42
  export const BLOCKED_URL_PLACEHOLDER = 'about:blank';
35
43
 
36
- function normalize(value: string): string {
37
- // 去除所有空白与控制字符(浏览器解析 URL 时会忽略 tab / 换行,"java\nscript:" 仍是 javascript:),再小写
38
- return value.replace(/[\u0000-\u0020\u007f-\u009f\s]/g, '').toLowerCase();
44
+ /**
45
+ * 解码基础 HTML 实体(命名实体 &colon; / &tab; / &newline;、十进制 &#...; 与十六进制 &#x...;)
46
+ * 用于防范利用 HTML 实体编码混淆伪协议前缀绕过安全检查。
47
+ */
48
+ export function decodeHtmlEntities(str: string): string {
49
+ return str
50
+ .replace(/&(?:colon|tab|newline);/gi, (match) => {
51
+ const lower = match.toLowerCase();
52
+ if (lower === '&colon;') return ':';
53
+ if (lower === '&tab;') return '\t';
54
+ if (lower === '&newline;') return '\n';
55
+ return match;
56
+ })
57
+ .replace(/&#x([0-9a-fA-F]+);?/g, (_, hex) => {
58
+ try {
59
+ const cp = parseInt(hex, 16);
60
+ return cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : '';
61
+ } catch {
62
+ return '';
63
+ }
64
+ })
65
+ .replace(/&#([0-9]+);?/g, (_, dec) => {
66
+ try {
67
+ const cp = parseInt(dec, 10);
68
+ return cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : '';
69
+ } catch {
70
+ return '';
71
+ }
72
+ });
73
+ }
74
+
75
+ /**
76
+ * 归一化 URL 文本:先解码 HTML 实体,再去除所有空白与控制字符,再小写。
77
+ */
78
+ export function normalizeUrlValue(value: string): string {
79
+ return decodeHtmlEntities(value)
80
+ .replace(/[\u0000-\u0020\u007f-\u009f\s]/g, '')
81
+ .toLowerCase();
39
82
  }
40
83
 
41
84
  /** URL 的协议名(小写、不含冒号);相对地址或无协议返回 null。判定核:hasBlockedScheme 与 resolveSafeUrl 共用 */
42
85
  export function urlSchemeOf(value: string): string | null {
43
- const matched = /^([a-z][a-z0-9+.-]*):/.exec(normalize(value));
86
+ const matched = /^([a-z][a-z0-9+.-]*):/.exec(normalizeUrlValue(value));
44
87
  return matched ? matched[1] : null;
45
88
  }
46
89
 
@@ -49,16 +92,33 @@ export function isEventHandlerAttribute(attrName: string): boolean {
49
92
  return /^on[a-z]+$/i.test(attrName);
50
93
  }
51
94
 
95
+ /**
96
+ * 判断是否属于受允许的 data: URI 白名单例外:
97
+ * 仅对纯媒体展示属性(src/srcset/poster/background)生效,且对 svg+xml 仅限 src/poster/background;
98
+ * 导航与提交属性(href/action/formaction/xlink:href/data/ping)上绝不放行任何 data: 协议。
99
+ */
100
+ function isAllowedDataUri(attrLower: string, value: string): boolean {
101
+ const trimmed = value.trim();
102
+ if (['src', 'srcset', 'poster', 'background'].includes(attrLower) && SAFE_RASTER_DATA_URI.test(trimmed)) {
103
+ return true;
104
+ }
105
+ if (['src', 'poster', 'background'].includes(attrLower) && SAFE_SVG_DATA_URI.test(trimmed)) {
106
+ return true;
107
+ }
108
+ return false;
109
+ }
110
+
52
111
  /** 该属性值是否含危险 scheme */
53
112
  export function hasBlockedScheme(attrName: string, value: string): boolean {
54
- if (!URL_BEARING_ATTRS.has(attrName.toLowerCase())) {
113
+ const attrLower = attrName.toLowerCase();
114
+ if (!URL_BEARING_ATTRS.has(attrLower)) {
55
115
  return false;
56
116
  }
57
- if (SAFE_DATA_URI.test(value.trim())) {
117
+ if (isAllowedDataUri(attrLower, value)) {
58
118
  return false;
59
119
  }
60
120
  const scheme = urlSchemeOf(value);
61
- return scheme !== null && BLOCKED_SCHEMES.includes(`${scheme}:`);
121
+ return scheme !== null && (BLOCKED_SCHEMES as readonly string[]).includes(`${scheme}:`);
62
122
  }
63
123
 
64
124
  /** 任何策略下都不放行的协议 */