soma-core 1.3.3 → 1.3.5

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 (112) hide show
  1. package/README.md +7 -6
  2. package/app/SomaPageClient.tsx +2 -72
  3. package/app/soma/page/route.ts +17 -2
  4. package/bin/soma-lsp.cjs +1 -4
  5. package/core/build/compiler/full-manifest-builder.ts +17 -26
  6. package/core/build/compiler/html-include-expander.ts +56 -0
  7. package/core/build/compiler/page-assets.ts +26 -0
  8. package/core/build/compiler/page-declaration-compiler.ts +85 -0
  9. package/core/build/compiler/rollup-plugin-soma.ts +4 -19
  10. package/core/build/compiler/route-builder.ts +0 -2
  11. package/core/build/compiler/rspack-plugin-soma.js +1 -10
  12. package/core/build/compiler/soma-manifest-webpack-plugin.js +54 -13
  13. package/core/build/compiler/soma-precompile.js +74 -0
  14. package/core/build/compiler/soma-precompile.ts +13 -0
  15. package/core/build/compiler/soma-rspack-yaml-loader.js +5 -11
  16. package/core/build/compiler/soma-webpack-loader.js +6 -21
  17. package/core/build/compiler/vite-plugin-soma.ts +9 -31
  18. package/core/build/component/pack-from-dir.ts +58 -0
  19. package/core/build/component/package-loader.ts +158 -12
  20. package/core/build/eject/plan-eject.ts +15 -21
  21. package/core/build/lsp/cross-file-diagnostics.cjs +82 -113
  22. package/core/build/lsp/extra-completion.cjs +14 -8
  23. package/core/build/lsp/lsp-navigation.cjs +50 -43
  24. package/core/build/lsp/soma-declaration.cjs +85 -0
  25. package/core/build/lsp/ui-yaml-completion.cjs +98 -104
  26. package/core/build/v2/block-compile.ts +200 -0
  27. package/core/build/v2/block-loader.ts +33 -0
  28. package/core/build/v2/html-index.ts +120 -0
  29. package/core/build/v2/migrate-v1.ts +370 -0
  30. package/core/build/v2/soma-file-loader.ts +216 -0
  31. package/core/client/component/ai-catalog.ts +15 -0
  32. package/core/client/component/component-pack.ts +205 -31
  33. package/core/client/component/contract-compat.ts +132 -0
  34. package/core/client/component/example-v2.ts +132 -0
  35. package/core/client/engine/dom-renderer.ts +14 -8
  36. package/core/client/engine/reactive-proxy.ts +8 -7
  37. package/core/client/engine/soma-bootstrap.ts +23 -5
  38. package/core/client/parser/v2/namespace.ts +182 -0
  39. package/core/client/parser/v2/page-parser.ts +359 -0
  40. package/core/client/parser/v2/use-parser.ts +412 -0
  41. package/core/client/parser/value-lang.ts +340 -0
  42. package/core/client/pipes/pipe-registry.ts +1 -1
  43. package/core/client/registry/declaration-renderer.ts +17 -15
  44. package/core/client/registry/page-lifecycle.ts +1 -1
  45. package/core/client/security/attribute-presence.ts +16 -1
  46. package/core/client/theme/harmony.ts +307 -0
  47. package/core/client/theme/scene-tokens.ts +134 -0
  48. package/core/client/theme/theme-axes.ts +228 -0
  49. package/core/client/theme/theme-engine.ts +333 -73
  50. package/core/client/theme/tone-solver.ts +118 -0
  51. package/core/index.ts +74 -2
  52. package/core/server/host/published-page-assets.ts +35 -0
  53. package/core/server/host/server-page-assets.ts +33 -16
  54. package/core/server/host/soma-page-compile.ts +33 -0
  55. package/core/server/index.ts +15 -0
  56. package/core/server/registry/declaration-precompiler.ts +24 -54
  57. package/core/server/registry/page-registry-store.ts +39 -10
  58. package/core/server/registry/services/pages/Get.ts +19 -9
  59. package/core/server/registry/validation/compile-gate.ts +14 -31
  60. package/core/server/registry/validation/cross-check.ts +7 -17
  61. package/core/server/registry/validation/declaration-safety-scan.ts +2 -2
  62. package/core/shared/types/component-contract.types.ts +10 -0
  63. package/dist/core/index.cjs +2144 -155
  64. package/dist/types/build/compiler/full-manifest-builder.d.ts +4 -4
  65. package/dist/types/build/compiler/html-include-expander.d.ts +19 -0
  66. package/dist/types/build/compiler/page-assets.d.ts +3 -0
  67. package/dist/types/build/compiler/page-declaration-compiler.d.ts +33 -0
  68. package/dist/types/build/compiler/rollup-plugin-soma.d.ts +0 -3
  69. package/dist/types/build/compiler/route-builder.d.ts +0 -1
  70. package/dist/types/build/compiler/soma-precompile.d.ts +8 -0
  71. package/dist/types/build/compiler/vite-plugin-soma.d.ts +2 -10
  72. package/dist/types/build/component/pack-from-dir.d.ts +17 -0
  73. package/dist/types/build/component/package-loader.d.ts +33 -2
  74. package/dist/types/build/v2/block-compile.d.ts +28 -0
  75. package/dist/types/build/v2/block-loader.d.ts +9 -0
  76. package/dist/types/build/v2/html-index.d.ts +37 -0
  77. package/dist/types/build/v2/migrate-v1.d.ts +32 -0
  78. package/dist/types/build/v2/soma-file-loader.d.ts +45 -0
  79. package/dist/types/client/component/component-pack.d.ts +23 -3
  80. package/dist/types/client/component/contract-compat.d.ts +16 -0
  81. package/dist/types/client/component/example-v2.d.ts +9 -0
  82. package/dist/types/client/engine/dom-renderer.d.ts +2 -0
  83. package/dist/types/client/engine/soma-bootstrap.d.ts +3 -1
  84. package/dist/types/client/parser/v2/namespace.d.ts +52 -0
  85. package/dist/types/client/parser/v2/page-parser.d.ts +21 -0
  86. package/dist/types/client/parser/v2/use-parser.d.ts +72 -0
  87. package/dist/types/client/parser/value-lang.d.ts +63 -0
  88. package/dist/types/client/registry/declaration-renderer.d.ts +1 -2
  89. package/dist/types/client/theme/harmony.d.ts +77 -0
  90. package/dist/types/client/theme/scene-tokens.d.ts +25 -0
  91. package/dist/types/client/theme/theme-axes.d.ts +81 -0
  92. package/dist/types/client/theme/theme-engine.d.ts +29 -1
  93. package/dist/types/client/theme/tone-solver.d.ts +47 -0
  94. package/dist/types/index.d.ts +13 -2
  95. package/dist/types/server/host/published-page-assets.d.ts +19 -0
  96. package/dist/types/server/host/server-page-assets.d.ts +1 -4
  97. package/dist/types/server/host/soma-page-compile.d.ts +7 -0
  98. package/dist/types/server/index.d.ts +3 -1
  99. package/dist/types/server/registry/declaration-precompiler.d.ts +3 -3
  100. package/dist/types/server/registry/page-registry-store.d.ts +5 -5
  101. package/dist/types/server/registry/validation/compile-gate.d.ts +2 -0
  102. package/dist/types/server/registry/validation/cross-check.d.ts +4 -4
  103. package/dist/types/shared/types/component-contract.types.d.ts +10 -0
  104. package/editor/vscode/package.json +1 -24
  105. package/global.d.ts +1 -11
  106. package/next.config.js +32 -50
  107. package/package.json +3 -2
  108. package/tailwind.config.ts +0 -1
  109. package/tsconfig.json +20 -7
  110. package/core/build/lsp/event-yaml-completion.cjs +0 -106
  111. package/core/client/host-bridge/empty-host/data/README.md +0 -17
  112. package/editor/vscode/syntaxes/soma-event-yaml.tmLanguage.json +0 -30
@@ -55,14 +55,16 @@ export interface SomaPageAssets {
55
55
  includes?: Record<string, string>;
56
56
  DomainClass: new () => SomaPageRoot;
57
57
 
58
- // ── 字符串模式(运行时解析,向后兼容) ──
58
+ // ── 编译后的运行时资产(源声明不得直接进入浏览器) ──
59
59
  uiYaml?: string;
60
+ /** 仅供构建/测试入口携带的外置声明块;mount 本身不读取。 */
61
+ declarationBlocks?: ReadonlyMap<string, string>;
60
62
  eventYaml?: string;
61
63
  styleYaml?: string;
62
64
  localeYaml?: string;
63
65
  appConfigYaml?: string;
64
66
  /**
65
- * 数据对象层声明(*_data.yaml,五件套可选件)。
67
+ * 从统一声明编译出的数据对象运行时资产。
66
68
  * 提供后 bootstrap 在首渲前解析声明、异步取数并注入 page.data,
67
69
  * 完成后触发一次全量渲染;解析/取数失败不阻塞页面(data 保持空对象 + console.error)。
68
70
  * 不提供时加载路径零变化。
@@ -91,6 +93,15 @@ export interface SomaPageAssets {
91
93
  components?: Record<string, SomaComponentDefinition>;
92
94
  }
93
95
 
96
+ /** 浏览器只用于拒绝源声明;不存在旧/新两套执行分派。 */
97
+ function isSomaDeclarationSource(value: string): boolean {
98
+ return value.split('\n').some((line) => {
99
+ const text = line.trim();
100
+ if (!text || text.startsWith('#')) return false;
101
+ return text === '{{';
102
+ });
103
+ }
104
+
94
105
  /**
95
106
  * 错误采集接线声明(可观测性,默认关闭)。
96
107
  *
@@ -246,16 +257,23 @@ export class SomaBootstrap {
246
257
  this.scheduler.setDiagnostics(this.diagnostics);
247
258
  }
248
259
  this.container = container;
260
+ // 源声明只允许在构建/服务端编译;浏览器 mount 只消费运行时资产。
261
+ if (assets.uiYaml && isSomaDeclarationSource(assets.uiYaml)) {
262
+ throw new Error(
263
+ '[SomaBootstrap] 收到未编译的 SOMA DSL 源声明。'
264
+ + '请先用 compilePageAssets(构建/测试)或 Host 页面编译入口生成运行时资产。',
265
+ );
266
+ }
249
267
  this.assets = { ...assets };
250
268
 
251
269
  // 1. 解析资产(委托给 AssetResolver)
252
- const parsed = this.assetResolver.resolve(assets);
270
+ const parsed = this.assetResolver.resolve(this.assets);
253
271
 
254
272
  // 2. 挂载 HTML
255
- this.adapter.mount(container, assets.html, assets.includes);
273
+ this.adapter.mount(container, this.assets.html, this.assets.includes);
256
274
 
257
275
  // 2.5 组件展开(页面引擎构建前:模板注入、锚点作用域化、插槽投影)
258
- this.setupComponentManager(container, assets, parsed.uiConfig);
276
+ this.setupComponentManager(container, this.assets, parsed.uiConfig);
259
277
 
260
278
  // 2.6 主题派生与注入(app.config theme: { brand } 一行换装,缺省旁路)
261
279
  this.applyHostTheme(parsed.appConfig);
@@ -0,0 +1,182 @@
1
+ // v2 解析 · 块作用域与命名空间(REQ-005 F1.3 / F1.4)。
2
+ //
3
+ // 块即命名空间:块内 `data:` 声明的对象名,全局身份自动是 `块id.名`——
4
+ // 书写零前缀,跨块显式全名。两个组件都叫 `orders` 因此互不相干。
5
+ //
6
+ // alias 是块作用域的短名:`queryOrders: /api/admin/orders` 或 `buyer: order.buyer`。
7
+ // 两类按**词法**分流(值以 `/` 开头即 API 别名),不靠猜;编译期整体展开,
8
+ // 清单里只有全名——运行时零查找,第零条公理的兑现点之一。
9
+ //
10
+ // 名字解析顺序是封闭的:alias → 自有 data → 行变量 → page。
11
+ // 多重命中不"按顺序取第一个",而是**报错**:静默择一正是本体系清剿过的失败形态。
12
+
13
+ export class SomaScopeError extends Error {
14
+ constructor(message: string, readonly blockId: string) {
15
+ super(`[soma-core][引擎] ${message}(块: ${blockId})`);
16
+ this.name = 'SomaScopeError';
17
+ }
18
+ }
19
+
20
+ export type AliasKind = 'api' | 'path';
21
+
22
+ export interface AliasEntry {
23
+ kind: AliasKind;
24
+ target: string;
25
+ }
26
+
27
+ export interface BlockScope {
28
+ blockId: string;
29
+ /** 本块 data 段声明或引入的对象名 */
30
+ dataNames: ReadonlySet<string>;
31
+ /** 块作用域别名 */
32
+ aliases: ReadonlyMap<string, AliasEntry>;
33
+ /** 按 HTML 位置可见的行变量(行内组件才有) */
34
+ rowVars: ReadonlySet<string>;
35
+ /** 页面变量固定名 */
36
+ pageVar: string;
37
+ }
38
+
39
+ /** 保留名:不可被 data 名或 alias 遮蔽 */
40
+ const RESERVED = new Set(['page', 'p', 'ctrl']);
41
+ const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
42
+
43
+ export interface BuildScopeInput {
44
+ blockId: string;
45
+ dataNames?: Iterable<string>;
46
+ aliasRaw?: Record<string, unknown>;
47
+ rowVars?: Iterable<string>;
48
+ }
49
+
50
+ export function buildBlockScope(input: BuildScopeInput): BlockScope {
51
+ const blockId = input.blockId;
52
+ const dataNames = new Set(input.dataNames ?? []);
53
+ const rowVars = new Set(input.rowVars ?? []);
54
+ const aliases = new Map<string, AliasEntry>();
55
+
56
+ for (const name of dataNames) {
57
+ if (RESERVED.has(name)) {
58
+ throw new SomaScopeError(`data 对象名 "${name}" 是保留名(page/p/ctrl)`, blockId);
59
+ }
60
+ if (!NAME_RE.test(name)) {
61
+ throw new SomaScopeError(`data 对象名 "${name}" 非法(字母开头,字母数字下划线)`, blockId);
62
+ }
63
+ if (rowVars.has(name)) {
64
+ throw new SomaScopeError(
65
+ `data 对象名 "${name}" 与行变量同名——同一个名字两种含义,解析时无法判定`,
66
+ blockId,
67
+ );
68
+ }
69
+ }
70
+
71
+ for (const [name, raw] of Object.entries(input.aliasRaw ?? {})) {
72
+ if (typeof raw !== 'string' || raw.trim() === '') {
73
+ throw new SomaScopeError(`alias "${name}" 的值必须是非空字符串`, blockId);
74
+ }
75
+ if (!NAME_RE.test(name)) {
76
+ throw new SomaScopeError(`alias 名 "${name}" 非法(字母开头,字母数字下划线)`, blockId);
77
+ }
78
+ if (RESERVED.has(name) || dataNames.has(name) || rowVars.has(name)) {
79
+ throw new SomaScopeError(
80
+ `alias "${name}" 遮蔽了已有名字(保留名/data 对象/行变量)——别名不得改变既有名字的含义`,
81
+ blockId,
82
+ );
83
+ }
84
+ const target = raw.trim();
85
+ const kind: AliasKind = target.startsWith('/') ? 'api' : 'path';
86
+ if (kind === 'path') {
87
+ const head = target.split('.')[0];
88
+ if (aliases.has(head)) {
89
+ throw new SomaScopeError(
90
+ `alias "${name}" 指向另一个别名 "${head}"——别名不得递归(展开顺序会变成隐藏规则)`,
91
+ blockId,
92
+ );
93
+ }
94
+ }
95
+ aliases.set(name, { kind, target });
96
+ }
97
+
98
+ return { blockId, dataNames, aliases, rowVars, pageVar: 'page' };
99
+ }
100
+
101
+ export type ResolvedPath =
102
+ | { kind: 'data'; full: string }
103
+ | { kind: 'row'; full: string }
104
+ | { kind: 'page'; full: string }
105
+ | { kind: 'literal' };
106
+
107
+ /**
108
+ * 路径归属裁决 + 全名还原。
109
+ *
110
+ * 返回 `literal` 表示"首段不在任何作用域内"——由调用方按位置决定它是字面量
111
+ * 还是错误(props 值位允许字面量,绑定位不允许)。
112
+ */
113
+ export function resolvePath(raw: string, scope: BlockScope): ResolvedPath {
114
+ const text = raw.trim();
115
+ if (text === '') return { kind: 'literal' };
116
+
117
+ const segments = text.split('.');
118
+ const head = segments[0];
119
+
120
+ // ① alias(路径别名)先展开——它是书写层的短名,展开后再按正常规则归属
121
+ const alias = scope.aliases.get(head);
122
+ if (alias?.kind === 'path') {
123
+ const expanded = [alias.target, ...segments.slice(1)].join('.');
124
+ return resolvePath(expanded, { ...scope, aliases: new Map() });
125
+ }
126
+
127
+ const inData = scope.dataNames.has(head);
128
+ const inRow = scope.rowVars.has(head);
129
+ const isPage = head === scope.pageVar;
130
+
131
+ const hits = [inData, inRow, isPage].filter(Boolean).length;
132
+ if (hits > 1) {
133
+ const candidates = [
134
+ inData ? `data 对象 ${scope.blockId}.${head}` : '',
135
+ inRow ? `行变量 ${head}` : '',
136
+ isPage ? '页面变量 page' : '',
137
+ ].filter(Boolean);
138
+ throw new SomaScopeError(
139
+ `名字 "${head}" 有歧义,同时匹配 ${candidates.join(' / ')}——请改名以消除歧义`,
140
+ scope.blockId,
141
+ );
142
+ }
143
+
144
+ if (inData) {
145
+ // 块内零前缀 → 全局身份 块id.名
146
+ return { kind: 'data', full: [`${scope.blockId}.${head}`, ...segments.slice(1)].join('.') };
147
+ }
148
+ if (inRow) return { kind: 'row', full: text };
149
+ if (isPage) return { kind: 'page', full: text };
150
+ return { kind: 'literal' };
151
+ }
152
+
153
+ /** API 位的别名展开;非别名原样返回(仍须过注册表白名单,那是另一道闸门) */
154
+ export function resolveApiRef(raw: string, scope: BlockScope): string {
155
+ const text = raw.trim();
156
+ const alias = scope.aliases.get(text);
157
+ if (alias) {
158
+ if (alias.kind !== 'api') {
159
+ throw new SomaScopeError(
160
+ `"${text}" 是路径别名,不能用在 api 位(API 别名的值须以 / 开头)`,
161
+ scope.blockId,
162
+ );
163
+ }
164
+ return alias.target;
165
+ }
166
+ return text;
167
+ }
168
+
169
+ /** 供 value-lang 使用的 hasVar:判定首段是否在作用域内 */
170
+ export function scopeHasVar(scope: BlockScope): (segment: string) => boolean {
171
+ return (segment: string): boolean => {
172
+ const alias = scope.aliases.get(segment);
173
+ if (alias?.kind === 'path') return true;
174
+ return scope.dataNames.has(segment) || scope.rowVars.has(segment) || segment === scope.pageVar;
175
+ };
176
+ }
177
+
178
+ /** 把值里的路径整体还原为全名(供绑定位写入清单) */
179
+ export function expandPath(raw: string, scope: BlockScope): string {
180
+ const resolved = resolvePath(raw, scope);
181
+ return resolved.kind === 'literal' ? raw.trim() : resolved.full;
182
+ }
@@ -0,0 +1,359 @@
1
+ // v2 解析 · page 块(REQ-005 F2)。
2
+ //
3
+ // **产出目标是 v1 等价的 UiConfig**——这是两级编译架构的关键:
4
+ // v2 只是更好写的书写层,编译后交给既有引擎,运行时零新增、零感知。
5
+ //
6
+ // 两处形状转换:
7
+ // 平铺 → 嵌套:`锚点.when` / `锚点.class` 后缀键合并成一个 ExtendedShowValue;
8
+ // each → bind:`each: 路径 as 变量 [by 路径]` 还原成 v1 的 NestedShowMapping。
9
+ //
10
+ // 唯一的缩进理由是列表作用域——when 组与插槽内容一律平铺,
11
+ // 因为编译器手里有 HTML,结构不需要 YAML 再复述一遍。
12
+
13
+ import type {
14
+ BindDeclaration,
15
+ ExtendedShowValue,
16
+ ShowMapping,
17
+ ShowValue,
18
+ UiConfig,
19
+ } from '../../../shared/types/ui-config.types';
20
+ import type { OnChangeRule } from '../../../shared/types/watcher.types';
21
+ import { SomaV2ParseError } from '../../../build/v2/soma-file-loader';
22
+ import { buildBlockScope, expandPath, type BlockScope } from './namespace';
23
+
24
+ const PAGE_KEYS = new Set([
25
+ 'domain', 'locale', 'ui', 'watch', 'event', 'data', 'adaptive', 'alias',
26
+ // initProps:引擎启动前写入的初始值(v1 UiConfig 同名字段的直通)。
27
+ //
28
+ // v2 是照**手写页面**设计的——那里文案住 HTML、初值住 Domain,声明里不需要它。
29
+ // 但 v2 产的是 v1 等价物,而生成链的页面把字面文案内联在 initProps 里
30
+ // (模型出的是组织意图,没有 Domain 可写)。少了这个键,AI 产的页面
31
+ // 就永远迈不过 v2 的门槛——不是"用不上 v2",是"表达不了"。
32
+ 'initProps',
33
+ ]);
34
+ /** 后缀键:平铺书写的高级绑定 */
35
+ const SUFFIXES = ['when', 'model', 'class'] as const;
36
+ type Suffix = (typeof SUFFIXES)[number];
37
+
38
+ export interface PageBlockAst {
39
+ /** v1 等价 UiConfig:直接交既有编译管线 */
40
+ ui: UiConfig;
41
+ /** 事件段原文(交 pipeline-parser,形状与 v1 _event.yaml 一致) */
42
+ eventRaw: Record<string, unknown>;
43
+ /** 数据段原文(页面级共享对象,交数据对象层) */
44
+ dataRaw?: Record<string, unknown>;
45
+ scope: BlockScope;
46
+ }
47
+
48
+ export interface ParsePageInput {
49
+ body: Record<string, unknown>;
50
+ /** 页面内全部锚点(校验引用完整性用) */
51
+ anchors: ReadonlySet<string>;
52
+ /** 组件实例锚点(出现在 ui 段 = 编译错误,指路组件块) */
53
+ instances: ReadonlySet<string>;
54
+ /** 词典键(locale 批量段校验用;缺省不校验) */
55
+ localeKeys?: ReadonlySet<string>;
56
+ }
57
+
58
+ export function parsePageBlock(input: ParsePageInput): PageBlockAst {
59
+ const { body } = input;
60
+ const fail = (message: string): never => {
61
+ throw new SomaV2ParseError(message, 'page');
62
+ };
63
+
64
+ for (const key of Object.keys(body)) {
65
+ if (!PAGE_KEYS.has(key)) {
66
+ fail(`page 块不支持键 "${key}"(可用:${[...PAGE_KEYS].join('/')})`);
67
+ }
68
+ }
69
+
70
+ const domain = body.domain;
71
+ if (typeof domain !== 'string' || domain.trim() === '') {
72
+ fail('page 块缺少 domain(页面 Domain 类名,必填)');
73
+ }
74
+
75
+ const scope = buildBlockScope({
76
+ blockId: 'page',
77
+ dataNames: Object.keys((body.data as Record<string, unknown>) ?? {}),
78
+ aliasRaw: body.alias as Record<string, unknown> | undefined,
79
+ });
80
+
81
+ const show: ShowMapping = {};
82
+
83
+ // ── locale 批量段:镜像文案展开 ─────────────────────────────────────────
84
+ const locale = body.locale;
85
+ if (locale !== undefined) {
86
+ if (!Array.isArray(locale)) fail('locale 必须是名单数组');
87
+ for (const item of locale as unknown[]) {
88
+ const key = String(item);
89
+ if (!input.anchors.has(key)) {
90
+ fail(`locale 名单里的 "${key}" 在 HTML 中没有对应锚点`);
91
+ }
92
+ if (input.localeKeys && !input.localeKeys.has(key)) {
93
+ fail(`locale 名单里的 "${key}" 在词典中没有对应键`);
94
+ }
95
+ show[key] = `page._locale.${key}`;
96
+ }
97
+ }
98
+
99
+ // ── ui 段:平铺解析 ────────────────────────────────────────────────────
100
+ const uiRaw = (body.ui as Record<string, unknown>) ?? {};
101
+ if (typeof uiRaw !== 'object' || Array.isArray(uiRaw)) fail('ui 段必须是映射');
102
+ parseShowLevel(uiRaw, show, scope, input, 'page');
103
+
104
+ // ── watch 段:v1 onChange 换位 ─────────────────────────────────────────
105
+ const bind: BindDeclaration = { obj: String(domain), var: 'page' };
106
+ const watch = body.watch;
107
+ if (watch !== undefined) {
108
+ if (!Array.isArray(watch)) fail('watch 必须是数组');
109
+ const rules: OnChangeRule[] = [];
110
+ for (const item of watch as Array<Record<string, unknown>>) {
111
+ if (!item || typeof item !== 'object') fail('watch 项必须是映射');
112
+ const path = item.path;
113
+ const call = item.call;
114
+ if (typeof path !== 'string' || path.trim() === '') fail('watch 项缺少 path');
115
+ if (typeof call !== 'string' || call.trim() === '') fail('watch 项缺少 call');
116
+ const rule: OnChangeRule = {
117
+ condition: expandPath(String(path), scope),
118
+ callback: String(call).includes('.') ? String(call) : `page.${call}`,
119
+ };
120
+ if (typeof item.debounce === 'number') rule.debounce = item.debounce;
121
+ if (typeof item.refresh === 'boolean') rule.refresh = item.refresh;
122
+ rules.push(rule);
123
+ }
124
+ if (rules.length > 0) bind.onChange = rules;
125
+ }
126
+
127
+ const ui: UiConfig = { bind, show };
128
+ if (body.initProps !== undefined) {
129
+ if (body.initProps === null || typeof body.initProps !== 'object' || Array.isArray(body.initProps)) {
130
+ fail('initProps 必须是映射(键为 var 别名路径,如 page.title)');
131
+ }
132
+ ui.initProps = body.initProps as Record<string, unknown>;
133
+ }
134
+ if (body.adaptive !== undefined) {
135
+ ui.adaptive = body.adaptive as UiConfig['adaptive'];
136
+ }
137
+
138
+ // ── event 段:面向 DOM ─────────────────────────────────────────────────
139
+ const eventRaw = normalizeEventSection(body.event, input, fail);
140
+
141
+ return {
142
+ ui,
143
+ eventRaw,
144
+ ...(body.data ? { dataRaw: body.data as Record<string, unknown> } : {}),
145
+ scope,
146
+ };
147
+ }
148
+
149
+ /** 解析一层 ui 映射(可递归进 each 块) */
150
+ function parseShowLevel(
151
+ raw: Record<string, unknown>,
152
+ target: ShowMapping,
153
+ scope: BlockScope,
154
+ input: ParsePageInput,
155
+ where: string,
156
+ ): void {
157
+ const fail = (message: string): never => {
158
+ throw new SomaV2ParseError(message, 'page');
159
+ };
160
+
161
+ for (const [key, value] of Object.entries(raw)) {
162
+ if (key === 'each') continue; // 由上层处理
163
+
164
+ const { anchor, suffix, attr } = splitKey(key);
165
+
166
+ if (input.instances.has(anchor)) {
167
+ fail(
168
+ `"${anchor}" 是组件实例锚点,不能写在 page 块的 ui 段——`
169
+ + `组件的一切声明住在它自己的块里(顶层写 ${anchor}:)`,
170
+ );
171
+ }
172
+ if (!input.anchors.has(anchor)) {
173
+ fail(`${where} 的 ui 引用了 HTML 中不存在的锚点 "${anchor}"`);
174
+ }
175
+
176
+ // 列表作用域:唯一合法的缩进
177
+ if (isEachBlock(value)) {
178
+ target[anchor] = parseEachBlock(value as Record<string, unknown>, scope, input, anchor);
179
+ continue;
180
+ }
181
+
182
+ if (suffix) {
183
+ const existing = asExtended(target[anchor]);
184
+ applySuffix(existing, suffix, value, scope, fail);
185
+ target[anchor] = existing;
186
+ continue;
187
+ }
188
+
189
+ if (attr) {
190
+ if (value !== null && typeof value === 'object') {
191
+ fail(`"${key}" 的属性绑定值必须是标量路径,不能写映射或数组`);
192
+ }
193
+ target[`${anchor}@${attr}`] = expandValue(value, scope, fail);
194
+ continue;
195
+ }
196
+
197
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
198
+ fail(
199
+ `"${key}" 的值是映射,但 ui 段只允许平铺写法`
200
+ + '(显隐用 锚点.when、条件类用 锚点.class、列表用 each)',
201
+ );
202
+ }
203
+ const expanded = expandValue(value, scope, fail);
204
+ const existing = target[anchor];
205
+ // YAML 映射不保证作者把基础绑定写在高级后缀之前;无论顺序如何,
206
+ // `anchor` 与 `anchor.when` / `anchor.class` 必须汇成同一个扩展绑定。
207
+ if (existing !== undefined && typeof existing === 'object' && !Array.isArray(existing)) {
208
+ (existing as ExtendedShowValue).text = expanded;
209
+ } else {
210
+ target[anchor] = expanded;
211
+ }
212
+ }
213
+ }
214
+
215
+ function isEachBlock(value: unknown): boolean {
216
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
217
+ && typeof (value as Record<string, unknown>).each === 'string';
218
+ }
219
+
220
+ /** `each: 路径 as 变量 [by 路径] [key 字段]` → v1 NestedShowMapping */
221
+ function parseEachBlock(
222
+ block: Record<string, unknown>,
223
+ scope: BlockScope,
224
+ input: ParsePageInput,
225
+ anchor: string,
226
+ ): ShowValue {
227
+ const fail = (message: string): never => {
228
+ throw new SomaV2ParseError(message, 'page');
229
+ };
230
+ const raw = String(block.each);
231
+ const match = /^(\S+)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s+by\s+(\S+))?(?:\s+key\s+(\S+))?$/.exec(raw.trim());
232
+ if (!match) {
233
+ fail(`each 语法错误: "${raw}"(应为 each: 路径 as 变量 [by 路径] [key 字段])`);
234
+ }
235
+ const [, sourcePath, rowVar, byPath] = match!;
236
+
237
+ const bind: BindDeclaration = {
238
+ obj: expandPath(sourcePath, scope),
239
+ var: rowVar,
240
+ };
241
+ if (byPath) bind.role_by = byPath;
242
+
243
+ // 行作用域:行变量加入可见名
244
+ const rowScope: BlockScope = {
245
+ ...scope,
246
+ rowVars: new Set([...scope.rowVars, rowVar]),
247
+ };
248
+
249
+ const childShow: ShowMapping = {};
250
+ const nested: Record<string, unknown> = {};
251
+ for (const [key, value] of Object.entries(block)) {
252
+ if (key === 'each') continue;
253
+ nested[key] = value;
254
+ }
255
+ parseShowLevel(nested, childShow, rowScope, input, `列表 ${anchor}`);
256
+
257
+ return { bind, show: childShow };
258
+ }
259
+
260
+ function splitKey(key: string): { anchor: string; suffix?: Suffix; attr?: string } {
261
+ const atIndex = key.indexOf('@');
262
+ if (atIndex > 0) {
263
+ return { anchor: key.slice(0, atIndex), attr: key.slice(atIndex + 1) };
264
+ }
265
+ const dotIndex = key.lastIndexOf('.');
266
+ if (dotIndex > 0) {
267
+ const tail = key.slice(dotIndex + 1) as Suffix;
268
+ if ((SUFFIXES as readonly string[]).includes(tail)) {
269
+ return { anchor: key.slice(0, dotIndex), suffix: tail };
270
+ }
271
+ }
272
+ return { anchor: key };
273
+ }
274
+
275
+ function asExtended(current: ShowValue | undefined): ExtendedShowValue {
276
+ if (current === undefined) return {};
277
+ if (typeof current === 'string') return { text: current };
278
+ return current as ExtendedShowValue;
279
+ }
280
+
281
+ function applySuffix(
282
+ target: ExtendedShowValue,
283
+ suffix: Suffix,
284
+ value: unknown,
285
+ scope: BlockScope,
286
+ fail: (message: string) => never,
287
+ ): void {
288
+ if (suffix === 'class') {
289
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
290
+ fail('.class 的值必须是 { 类名: 条件路径 } 映射');
291
+ }
292
+ const map: Record<string, string> = {};
293
+ for (const [cls, cond] of Object.entries(value as Record<string, unknown>)) {
294
+ map[cls] = expandCondition(String(cond), scope);
295
+ }
296
+ target.class = map;
297
+ return;
298
+ }
299
+ if (suffix === 'when') {
300
+ target.when = expandCondition(String(value), scope);
301
+ return;
302
+ }
303
+ target.model = expandPath(String(value), scope);
304
+ }
305
+
306
+ /** 条件位:仅支持路径与 `!` 前缀(比较与布尔不进 DSL) */
307
+ function expandCondition(raw: string, scope: BlockScope): string {
308
+ const text = raw.trim();
309
+ const negated = text.startsWith('!');
310
+ const bare = negated ? text.slice(1).trim() : text;
311
+ return `${negated ? '!' : ''}${expandPath(bare, scope)}`;
312
+ }
313
+
314
+ /** 值位:路径整体还原;管道链保留原文(管道段由既有 pipe-registry 解析) */
315
+ function expandValue(value: unknown, scope: BlockScope, fail: (m: string) => never): string {
316
+ if (value === null || value === undefined) fail('绑定值不能为空');
317
+ if (typeof value !== 'string') return String(value);
318
+
319
+ const segments = String(value).split(/\s+\|\s+/);
320
+ segments[0] = expandPath(segments[0], scope);
321
+ return segments.join(' | ');
322
+ }
323
+
324
+ /** event 段:子键 on/timers/triggers;emit 形态在此拦截并指路组件块 */
325
+ function normalizeEventSection(
326
+ raw: unknown,
327
+ input: ParsePageInput,
328
+ fail: (m: string) => never,
329
+ ): Record<string, unknown> {
330
+ if (raw === undefined) return {};
331
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
332
+ fail('event 段必须是映射(子键 on / timers / triggers)');
333
+ }
334
+ const section = raw as Record<string, unknown>;
335
+ for (const key of Object.keys(section)) {
336
+ if (!['on', 'timers', 'triggers'].includes(key)) {
337
+ fail(`page 块的 event 段不支持子键 "${key}"(可用:on / timers / triggers)`);
338
+ }
339
+ }
340
+
341
+ const on = (section.on as Record<string, unknown>) ?? {};
342
+ if (typeof on !== 'object' || Array.isArray(on)) fail('event.on 必须是映射');
343
+
344
+ for (const key of Object.keys(on)) {
345
+ const anchor = key.split('.')[0];
346
+ if (input.instances.has(anchor)) {
347
+ fail(
348
+ `"${key}" 的锚点 "${anchor}" 是组件实例——组件事件(emit 路由)住在该组件块的 event.on 段,`
349
+ + 'page 块的 event 只面向 DOM 事件',
350
+ );
351
+ }
352
+ }
353
+
354
+ // 交给既有 pipeline-parser 的形状:DOM 事件映射 + timers/triggers 原样
355
+ const result: Record<string, unknown> = { ...on };
356
+ if (section.timers !== undefined) result.timers = section.timers;
357
+ if (section.triggers !== undefined) result.triggers = section.triggers;
358
+ return result;
359
+ }