soma-core 1.4.0 → 1.4.2

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 (132) hide show
  1. package/README.md +1 -1
  2. package/core/build/blocks/block-compile.ts +31 -2
  3. package/core/build/blocks/block-container.ts +2 -11
  4. package/core/build/compiler/page-declaration-compiler.ts +30 -2
  5. package/core/build/compiler/soma-precompile.js +2053 -23
  6. package/core/build/component/component-graph.ts +208 -0
  7. package/core/build/component/package-loader.ts +32 -0
  8. package/core/build/eject/component-eject.ts +473 -0
  9. package/core/build/eject/component-upgrade.ts +359 -0
  10. package/core/build/layout/constraint-solver.ts +235 -0
  11. package/core/build/layout/css-emitter.ts +116 -0
  12. package/core/build/layout/page-layout.ts +85 -0
  13. package/core/build/pack/pack-init.ts +270 -0
  14. package/core/client/base/SomaHttpClient.ts +34 -1
  15. package/core/client/base/SomaPageRootBase.ts +61 -0
  16. package/core/client/component/ai-catalog.ts +121 -4
  17. package/core/client/component/component-defaults.ts +100 -0
  18. package/core/client/component/component-definition.types.ts +39 -0
  19. package/core/client/component/component-manager.ts +79 -4
  20. package/core/client/component/component-pack.ts +126 -2
  21. package/core/client/component/keyboard-matrix.ts +144 -0
  22. package/core/client/component/pack-styles.ts +59 -1
  23. package/core/client/component/style-features.ts +131 -0
  24. package/core/client/component/theme-component-tokens.ts +83 -0
  25. package/core/client/component/verify-pack.ts +120 -1
  26. package/core/client/container/SomaContainerAdapter.ts +6 -2
  27. package/core/client/data/data-object-resolver.ts +407 -4
  28. package/core/client/data/reaction-engine.ts +176 -0
  29. package/core/client/data/window-engine.ts +477 -0
  30. package/core/client/engine/event-engine.ts +98 -0
  31. package/core/client/engine/soma-bootstrap.ts +265 -5
  32. package/core/client/engine/step-runner.ts +134 -0
  33. package/core/client/infra/http/SomaHttpService.ts +2 -2
  34. package/core/client/parser/blocks/page-parser.ts +15 -1
  35. package/core/client/parser/blocks/use-parser.ts +5 -12
  36. package/core/client/parser/data-config-parser.ts +316 -8
  37. package/core/client/parser/duration.ts +16 -0
  38. package/core/client/parser/layout-parser.ts +157 -0
  39. package/core/client/parser/page-state-parser.ts +166 -0
  40. package/core/client/parser/pipeline-parser.ts +76 -1
  41. package/core/client/parser/reaction-parser.ts +459 -0
  42. package/core/client/parser/reaction-sugar.ts +47 -0
  43. package/core/client/parser/step-parser.ts +359 -0
  44. package/core/client/parser/ui-config-parser.ts +59 -0
  45. package/core/client/parser/window-parser.ts +294 -0
  46. package/core/client/theme/theme-engine.ts +102 -2
  47. package/core/index.ts +184 -0
  48. package/core/shared/block-errors.ts +11 -0
  49. package/core/shared/calc/coerce.ts +29 -0
  50. package/core/shared/calc/errors.ts +43 -0
  51. package/core/shared/calc/evaluator.ts +101 -0
  52. package/core/shared/calc/index.ts +12 -0
  53. package/core/shared/calc/lexer.ts +194 -0
  54. package/core/shared/calc/parser.ts +204 -0
  55. package/core/shared/calc/typer.ts +184 -0
  56. package/core/shared/component/derive-sample.ts +105 -0
  57. package/core/shared/component/field-lines.ts +473 -0
  58. package/core/shared/path-algebra.ts +169 -0
  59. package/core/shared/predicates/index.ts +527 -0
  60. package/core/shared/types/component-contract.types.ts +151 -9
  61. package/core/shared/types/data-config.types.ts +120 -1
  62. package/core/shared/types/domain.types.ts +13 -0
  63. package/core/shared/types/event.types.ts +22 -2
  64. package/core/shared/types/layout-constraint.types.ts +73 -0
  65. package/core/shared/types/page-state.types.ts +60 -0
  66. package/core/shared/types/reaction.types.ts +144 -0
  67. package/core/shared/types/step.types.ts +91 -0
  68. package/core/shared/types/ui-config.types.ts +18 -0
  69. package/core/shared/types/window.types.ts +177 -0
  70. package/dist/cli/soma.js +13 -1
  71. package/dist/core/index.cjs +5529 -631
  72. package/dist/types/build/blocks/block-container.d.ts +1 -6
  73. package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -0
  74. package/dist/types/build/component/component-graph.d.ts +85 -0
  75. package/dist/types/build/eject/component-eject.d.ts +121 -0
  76. package/dist/types/build/eject/component-upgrade.d.ts +43 -0
  77. package/dist/types/build/layout/constraint-solver.d.ts +36 -0
  78. package/dist/types/build/layout/css-emitter.d.ts +18 -0
  79. package/dist/types/build/layout/page-layout.d.ts +24 -0
  80. package/dist/types/build/pack/pack-init.d.ts +8 -0
  81. package/dist/types/client/base/SomaHttpClient.d.ts +8 -0
  82. package/dist/types/client/base/SomaPageRootBase.d.ts +28 -0
  83. package/dist/types/client/component/ai-catalog.d.ts +33 -1
  84. package/dist/types/client/component/component-defaults.d.ts +15 -0
  85. package/dist/types/client/component/component-definition.types.d.ts +38 -0
  86. package/dist/types/client/component/component-manager.d.ts +36 -0
  87. package/dist/types/client/component/component-pack.d.ts +32 -2
  88. package/dist/types/client/component/keyboard-matrix.d.ts +24 -0
  89. package/dist/types/client/component/pack-styles.d.ts +21 -0
  90. package/dist/types/client/component/style-features.d.ts +26 -0
  91. package/dist/types/client/component/theme-component-tokens.d.ts +14 -0
  92. package/dist/types/client/component/verify-pack.d.ts +10 -0
  93. package/dist/types/client/data/data-object-resolver.d.ts +106 -1
  94. package/dist/types/client/data/reaction-engine.d.ts +21 -0
  95. package/dist/types/client/data/window-engine.d.ts +27 -0
  96. package/dist/types/client/engine/event-engine.d.ts +15 -0
  97. package/dist/types/client/engine/soma-bootstrap.d.ts +70 -0
  98. package/dist/types/client/engine/step-runner.d.ts +24 -0
  99. package/dist/types/client/parser/blocks/use-parser.d.ts +2 -2
  100. package/dist/types/client/parser/duration.d.ts +1 -0
  101. package/dist/types/client/parser/layout-parser.d.ts +9 -0
  102. package/dist/types/client/parser/page-state-parser.d.ts +32 -0
  103. package/dist/types/client/parser/reaction-parser.d.ts +16 -0
  104. package/dist/types/client/parser/reaction-sugar.d.ts +13 -0
  105. package/dist/types/client/parser/step-parser.d.ts +23 -0
  106. package/dist/types/client/parser/ui-config-parser.d.ts +5 -0
  107. package/dist/types/client/parser/window-parser.d.ts +25 -0
  108. package/dist/types/client/theme/theme-engine.d.ts +26 -0
  109. package/dist/types/index.d.ts +35 -2
  110. package/dist/types/shared/block-errors.d.ts +5 -0
  111. package/dist/types/shared/calc/coerce.d.ts +4 -0
  112. package/dist/types/shared/calc/errors.d.ts +14 -0
  113. package/dist/types/shared/calc/evaluator.d.ts +2 -0
  114. package/dist/types/shared/calc/index.d.ts +6 -0
  115. package/dist/types/shared/calc/lexer.d.ts +20 -0
  116. package/dist/types/shared/calc/parser.d.ts +49 -0
  117. package/dist/types/shared/calc/typer.d.ts +16 -0
  118. package/dist/types/shared/component/derive-sample.d.ts +23 -0
  119. package/dist/types/shared/component/field-lines.d.ts +19 -0
  120. package/dist/types/shared/path-algebra.d.ts +56 -0
  121. package/dist/types/shared/predicates/index.d.ts +79 -0
  122. package/dist/types/shared/types/component-contract.types.d.ts +134 -6
  123. package/dist/types/shared/types/data-config.types.d.ts +115 -1
  124. package/dist/types/shared/types/domain.types.d.ts +12 -0
  125. package/dist/types/shared/types/event.types.d.ts +8 -2
  126. package/dist/types/shared/types/layout-constraint.types.d.ts +52 -0
  127. package/dist/types/shared/types/page-state.types.d.ts +49 -0
  128. package/dist/types/shared/types/reaction.types.d.ts +115 -0
  129. package/dist/types/shared/types/step.types.d.ts +76 -0
  130. package/dist/types/shared/types/ui-config.types.d.ts +18 -0
  131. package/dist/types/shared/types/window.types.d.ts +171 -0
  132. package/package.json +3 -2
@@ -0,0 +1,116 @@
1
+ // 约束解 → CSS(REQ-010 S3 / CL-2)。
2
+ //
3
+ // 产物只含**容器查询 + flex**,零视口媒体查询。这不是风格偏好:
4
+ // 一个侧栏该多宽取决于**它所在的那个容器**有多宽,而不是浏览器窗口有多宽。
5
+ // 同一个组件放进抽屉里和放在主区里,视口是同一个、可用宽度差三倍——
6
+ // 用视口断点写的布局在前者里必然错,而错法是"在某些页面上看着怪"。
7
+
8
+ import { CONTAINER_STEPS, type SomaLayoutConstraintError } from './constraint-solver';
9
+ import type { SomaLayoutPlan, SomaWrap } from '../../shared/types/layout-constraint.types';
10
+
11
+ /** align 词汇 → CSS。两个轴分开:主轴用 justify-content,交叉轴用 align-items */
12
+ const ALIGN_MAIN: Record<string, string> = {
13
+ space_between: 'space-between',
14
+ space_evenly: 'space-evenly',
15
+ space_around: 'space-around',
16
+ };
17
+ const ALIGN_CROSS: Record<string, string> = {
18
+ start: 'flex-start',
19
+ center: 'center',
20
+ end: 'flex-end',
21
+ baseline: 'baseline',
22
+ };
23
+
24
+ export interface EmitOptions {
25
+ /** 组根选择器,如 `.soma-sidebar-pair` */
26
+ root: string;
27
+ /** 子项名 → 选择器;不给时按 `${root} > [data-soma-slot="<名>"]` */
28
+ selectorOf?(name: string): string;
29
+ }
30
+
31
+ /**
32
+ * 产出该组的全部 CSS。
33
+ *
34
+ * 结构:一条基线规则(最窄档的解)+ 每个更宽档一条容器查询。
35
+ * 基线取**最窄档**而不是最宽档:容器查询是 `min-width` 向上覆盖的,
36
+ * 基线必须是"什么查询都没命中时"的样子,也就是最窄的那一档。
37
+ * 取最宽档当基线的话,不支持容器查询的浏览器会拿到宽屏布局塞进窄容器。
38
+ */
39
+ export function emitLayoutCss(plan: SomaLayoutPlan, options: EmitOptions): string {
40
+ const { root } = options;
41
+ const selectorOf = options.selectorOf
42
+ ?? ((name: string) => `${root} > [data-soma-slot="${name}"]`);
43
+
44
+ const wrap: SomaWrap = plan.constraint.wrap ?? 'none';
45
+ const align = plan.constraint.align;
46
+ const gap = plan.constraint.gap;
47
+
48
+ const containerRule = [
49
+ `${root} {`,
50
+ ' display: flex;',
51
+ // 具名容器(§5.4):子孙的 `@container <name> (…)` 靠它寻址
52
+ plan.constraint.container_name === undefined
53
+ ? ' container-type: inline-size;'
54
+ : ` container: ${plan.constraint.container_name} / inline-size;`,
55
+ gap === undefined ? null : ` gap: ${gap};`,
56
+ align !== undefined && ALIGN_MAIN[align] !== undefined
57
+ ? ` justify-content: ${ALIGN_MAIN[align]};`
58
+ : null,
59
+ align !== undefined && ALIGN_CROSS[align] !== undefined
60
+ ? ` align-items: ${ALIGN_CROSS[align]};`
61
+ : null,
62
+ wrap === 'reel' ? ' overflow-inline: auto;' : null,
63
+ '}',
64
+ ].filter((line) => line !== null).join('\n');
65
+
66
+ const ruleFor = (index: number): string => {
67
+ const solution = plan.solutions[index];
68
+ const lines: string[] = [];
69
+ // 换行档:整组切竖排。用 flex-wrap 而不是改 flex-direction,
70
+ // 是为了让 gap 与对齐在两种形态下是同一套值(改方向会把主轴交叉轴对调)
71
+ if (solution.wrapped && wrap === 'below') {
72
+ lines.push(`${root} { flex-wrap: wrap; }`);
73
+ } else if (wrap !== 'reel') {
74
+ lines.push(`${root} { flex-wrap: nowrap; }`);
75
+ }
76
+ for (const [name, width] of Object.entries(solution.widths)) {
77
+ const node = plan.constraint.nodes[name];
78
+ const selector = selectorOf(name);
79
+ if (node.sizing === 'hug') {
80
+ // hug 的宽度由内容决定:不写具体值,只保证它不被拉伸也不被压缩
81
+ lines.push(`${selector} { flex: 0 0 auto; }`);
82
+ continue;
83
+ }
84
+ const basis = `${width}rem`;
85
+ const grow = node.sizing === 'fill' ? '1 1' : '0 0';
86
+ const bounds = [
87
+ node.min === undefined ? null : `min-inline-size: ${node.min};`,
88
+ node.max === undefined ? null : `max-inline-size: ${node.max};`,
89
+ ].filter((part) => part !== null).join(' ');
90
+ // 换行档上宽度全给 100%:竖排之后每项独占一行,留着解出来的 rem 值
91
+ // 会让第二行的项莫名其妙只占半行宽
92
+ const declaration = solution.wrapped && wrap === 'below'
93
+ ? `flex: 1 1 100%;`
94
+ : `flex: ${grow} ${basis};`;
95
+ lines.push(`${selector} { ${declaration}${bounds === '' ? '' : ` ${bounds}`} }`);
96
+ }
97
+ return lines.join('\n');
98
+ };
99
+
100
+ const blocks: string[] = [containerRule, ruleFor(0)];
101
+ for (let index = 1; index < plan.solutions.length; index += 1) {
102
+ const [, rem] = CONTAINER_STEPS[index];
103
+ const body = ruleFor(index);
104
+ // 与上一档逐字节相同就不出这一条:八档各写一遍会让产物涨到四倍,
105
+ // 而其中大半是重复的(min/max 夹住之后,相邻档的解经常一样)
106
+ if (body === ruleFor(index - 1)) continue;
107
+ blocks.push(`@container (min-width: ${rem}rem) {\n${indent(body)}\n}`);
108
+ }
109
+ return blocks.join('\n');
110
+ }
111
+
112
+ function indent(text: string): string {
113
+ return text.split('\n').map((line) => (line === '' ? line : ` ${line}`)).join('\n');
114
+ }
115
+
116
+ export type { SomaLayoutConstraintError };
@@ -0,0 +1,85 @@
1
+ // 页面级 `layout:` 段的构建期编译(REQ-011 接线)——声明 → 求解 → CSS 产物。
2
+ //
3
+ // ── 它接的是哪一条断线 ──────────────────────────────────────────────────
4
+ // REQ-010 S3 把求解器(constraint-solver)与产出器(css-emitter)都做好了,
5
+ // 也把 `layout:` 的解析器放进了 client——但三者之间没有任何调用关系:
6
+ // 页面写了 `layout:`,编译链原样丢弃,浏览器什么也收不到,而且不报错。
7
+ // 这与 REQ-008 抓出的"字段字典解析出来了、一步没走到组件"是同一类坏法。
8
+ //
9
+ // 这里把它们串成一条:锚点校验 → 每个锚点求解八档 → 产出容器查询 CSS →
10
+ // 交给编译器写进运行时资产的 `layout_css`。求解只在这里发生(CL-4),
11
+ // 运行时收到的已经是 CSS。
12
+
13
+ import type { HtmlAnchorIndex } from '../blocks/html-index';
14
+ import type { SomaLayoutConstraint } from '../../shared/types/layout-constraint.types';
15
+ import { parseLayoutConstraint } from '../../client/parser/layout-parser';
16
+ import { solveLayout } from './constraint-solver';
17
+ import { emitLayoutCss } from './css-emitter';
18
+
19
+ export class SomaPageLayoutError extends Error {
20
+ constructor(message: string, readonly path: string) {
21
+ super(`[soma-core][布局] ${message}(${path})`);
22
+ this.name = 'SomaPageLayoutError';
23
+ }
24
+ }
25
+
26
+ export interface CompilePageLayoutInput {
27
+ /** 页面块直通的原文(或已解析的约束表;两种都收,解析是幂等的) */
28
+ raw: unknown;
29
+ htmlIndex: HtmlAnchorIndex;
30
+ /** 宿主类名:选择器前缀,避免同文档里两页同名锚点互相串样式 */
31
+ hostClass: string;
32
+ }
33
+
34
+ export interface CompiledPageLayout {
35
+ constraints: Record<string, SomaLayoutConstraint>;
36
+ css: string;
37
+ }
38
+
39
+ const fail = (message: string, path: string): never => {
40
+ throw new SomaPageLayoutError(message, path);
41
+ };
42
+
43
+ /** 锚点选择器:页面级锚点在运行时保留 `data-soma-id` */
44
+ function anchorSelector(hostClass: string, anchor: string): string {
45
+ return `[data-soma-host="${hostClass}"] [data-soma-id="${anchor}"]`;
46
+ }
47
+
48
+ /**
49
+ * 编译整页的 `layout:` 段。
50
+ *
51
+ * 锚点与子项名都对着 HTML 锚点索引核:写错一个字母的表现是"某一行的布局
52
+ * 完全没生效",页面上看着只是排得松一点——只有在这里指名才有人发现。
53
+ */
54
+ export function compilePageLayout(input: CompilePageLayoutInput): CompiledPageLayout {
55
+ const { raw, htmlIndex, hostClass } = input;
56
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
57
+ fail('layout 必须是映射:{ <锚点id>: { gap, wrap, <子项>: { sizing, … } } }', 'layout');
58
+ }
59
+
60
+ const constraints: Record<string, SomaLayoutConstraint> = {};
61
+ const chunks: string[] = [];
62
+ for (const [anchor, spec] of Object.entries(raw as Record<string, unknown>)) {
63
+ const path = `layout.${anchor}`;
64
+ if (!htmlIndex.anchors.has(anchor)) {
65
+ fail(`锚点 "${anchor}" 不存在于 HTML(data-soma-id)`, path);
66
+ }
67
+ const constraint = parseLayoutConstraint({ raw: spec, path }, { fail });
68
+ for (const child of Object.keys(constraint.nodes)) {
69
+ if (!htmlIndex.anchors.has(child)) {
70
+ fail(`子项 "${child}" 不是页面锚点——它必须是 "${anchor}" 的直接子元素且带 data-soma-id`, `${path}.${child}`);
71
+ }
72
+ }
73
+ // 不可满足时 solveLayout 抛 SomaLayoutConstraintError(指名两条打架的声明)——原样上抛:
74
+ // 它的错误文案已经是给作者看的形状,再包一层只会把关键信息推到第二行。
75
+ const plan = solveLayout(constraint, path);
76
+ const root = anchorSelector(hostClass, anchor);
77
+ chunks.push(emitLayoutCss(plan, {
78
+ root,
79
+ selectorOf: (name) => `${root} > [data-soma-id="${name}"]`,
80
+ }));
81
+ constraints[anchor] = constraint;
82
+ }
83
+
84
+ return { constraints, css: chunks.join('\n') };
85
+ }
@@ -0,0 +1,270 @@
1
+ // `soma pack init <名字>` —— 组件包脚手架(REQ-009 EC-3)。
2
+ //
3
+ // 此前 `soma-pack-starter/` 是「复制这个目录」的模板。复制模板的问题不是麻烦,
4
+ // 是**复制出来的东西停在复制那一刻**:starter 里预置的自检闸门升级了,
5
+ // 已经复制出去的包不会跟着升级,而且没人知道自己落后了。
6
+ //
7
+ // 脚手架生成的包默认带两条自检:verifyComponentPack(裸色值 / 物理方向 / 缺 ai 段…)
8
+ // 与组件令牌接线检查。第三方包从第一天起就受和官方组件同一把尺子管。
9
+
10
+ export interface PackInitFile {
11
+ path: string;
12
+ content: string;
13
+ }
14
+
15
+ export class PackInitError extends Error {
16
+ constructor(message: string) {
17
+ super(`[soma pack init] ${message}`);
18
+ this.name = 'PackInitError';
19
+ }
20
+ }
21
+
22
+ /** 包名规则与 composeComponentPacks 的 PACK_NAME_PATTERN 一致 */
23
+ const PACK_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
24
+
25
+ function camelOf(packName: string): string {
26
+ return packName.replace(/-([a-z0-9])/g, (_, char: string) => char.toUpperCase());
27
+ }
28
+
29
+ function pascalOf(packName: string): string {
30
+ const camel = camelOf(packName);
31
+ return camel.charAt(0).toUpperCase() + camel.slice(1);
32
+ }
33
+
34
+ function toKebab(name: string): string {
35
+ return name
36
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
37
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
38
+ .toLowerCase();
39
+ }
40
+
41
+ export function planPackInit(packName: string): PackInitFile[] {
42
+ if (!PACK_NAME_PATTERN.test(packName)) {
43
+ throw new PackInitError(
44
+ `包名 "${packName}" 必须匹配 [a-z][a-z0-9-]*(与合成期的包名规则一致)`,
45
+ );
46
+ }
47
+ const componentName = `${pascalOf(packName)}Card`;
48
+ const componentKebab = toKebab(componentName);
49
+ const packVar = camelOf(packName);
50
+
51
+ return [
52
+ { path: 'package.json', content: renderPackageJson(packName) },
53
+ { path: 'src/index.ts', content: renderIndex(packName, packVar, componentName) },
54
+ { path: 'src/components.ts', content: renderComponents(componentName, componentKebab) },
55
+ { path: 'src/styles.ts', content: renderStyles(componentName, componentKebab) },
56
+ { path: 'tests/pack.test.ts', content: renderTest(packName, packVar, componentName, componentKebab) },
57
+ { path: 'README.md', content: renderReadme(packName, packVar, componentName) },
58
+ ];
59
+ }
60
+
61
+ function renderPackageJson(packName: string): string {
62
+ return `${JSON.stringify({
63
+ name: packName,
64
+ version: '0.1.0',
65
+ private: true,
66
+ type: 'module',
67
+ main: './src/index.ts',
68
+ types: './src/index.ts',
69
+ exports: { '.': './src/index.ts' },
70
+ scripts: { test: 'vitest run', typecheck: 'tsc --noEmit' },
71
+ peerDependencies: { 'soma-core': '*', 'soma-ui': '*' },
72
+ }, null, 2)}\n`;
73
+ }
74
+
75
+ function renderIndex(packName: string, packVar: string, componentName: string): string {
76
+ return [
77
+ `// ${packName} —— 第三方业务组件包。`,
78
+ '//',
79
+ '// 交给宿主的是一个完整描述:组件表 + 按需样式 + 给 AI 目录的写作规范补充。',
80
+ `// 宿主用 composeComponentPacks([somaUiPack, ${packVar}]) 合成,`,
81
+ '// 重名默认拒收、来源可追溯、覆盖前过契约兼容闸门——与官方组件同一套纪律。',
82
+ '',
83
+ "import type { SomaComponentPack } from 'soma-core';",
84
+ `import { create${componentName}Def } from './components';`,
85
+ "import { PACK_STYLES } from './styles';",
86
+ '',
87
+ `export const ${packVar}: SomaComponentPack = {`,
88
+ ` name: '${packName}',`,
89
+ " version: '0.1.0',",
90
+ ' components: {',
91
+ ` ${componentName}: create${componentName}Def(),`,
92
+ ' },',
93
+ ' styles: {',
94
+ ` components: { ${componentName}: PACK_STYLES.${componentName} },`,
95
+ ' // 给别的包的组件打样式微调(M-4);不需要就删掉这一段。',
96
+ " // patches: { DataTable: '.soma-data-table__cell{padding-block:2px}' },",
97
+ ' },',
98
+ ' catalogConventions: [',
99
+ ` '### ${packName} 的组件写作约定',`,
100
+ " '',",
101
+ " '写在这里的话会跟着组件一起进 AI 的上下文——',",
102
+ " '组件包对自己的组件有话要说时,那些话必须到得了模型手里,否则等于没写。',",
103
+ " ].join('\\n'),",
104
+ ' meta: {',
105
+ ` description: '${packName} 业务组件包',`,
106
+ " license: 'UNLICENSED',",
107
+ ' },',
108
+ '};',
109
+ '',
110
+ `export default ${packVar};`,
111
+ '',
112
+ ].join('\n');
113
+ }
114
+
115
+ function renderComponents(componentName: string, kebab: string): string {
116
+ return [
117
+ "import type { SomaComponentDefinition } from 'soma-core';",
118
+ "import { somaEmits, somaFields, somaSlots } from 'soma-core';",
119
+ '',
120
+ '/**',
121
+ ' * 示例业务组件。solution 层的四维设计判据(深度 / 组合 / 完备 / 可操作)见',
122
+ ' * soma-ui/doc《soma 业务组件商用级写作规范》——新组件至少满足其中三项。',
123
+ ' */',
124
+ `export function create${componentName}Def(): SomaComponentDefinition {`,
125
+ ' return {',
126
+ ' contract: {',
127
+ ` name: '${componentName}',`,
128
+ " layer: 'solution',",
129
+ " version: '0.1.0',",
130
+ " geometry: 'surface',",
131
+ " description: '示例卡片:把一类业务场景整套打包,一个声明落一个完整业务功能',",
132
+ ' // 字段行写法(REQ-012):一行一个字段,缩进即嵌套,示例值就在行尾。',
133
+ ' // 示例值不是装饰——组件橱窗、视觉矩阵与 AI 拿到的样张都由它派生,',
134
+ ' // 缺了它这个组件在橱窗里只有一个空壳(verifyComponentPack 会点名)。',
135
+ ' props: somaFields`',
136
+ " title: string, 卡片标题, 默认 \"\", 示例 本周待跟进",
137
+ ' items: array<object>, 条目列表, 默认 []',
138
+ ' id: string, 条目编号, 必填, 示例 T-1001',
139
+ ' label: string, 条目文案, 必填, 示例 杭州云汀科技 · 周四回访',
140
+ ' status: enum(todo|doing|done), 条目状态, 默认 todo, 示例 doing',
141
+ ' loading: boolean, 加载态, 默认 false',
142
+ ' `,',
143
+ ' emits: somaEmits`',
144
+ ' action: 用户触发了卡片上的动作(业务处置归页面)',
145
+ ' key: string, 动作标识',
146
+ ' `,',
147
+ ' slots: somaSlots`',
148
+ ' footer: 底部动作区,宿主接手时用它',
149
+ ' `,',
150
+ ' // 组件级令牌(M-1):组件自己声明的可调旋钮。',
151
+ ' // default 必须引用语义令牌——组件令牌是语义令牌的收窄,不是新的真源。',
152
+ ' tokens: {',
153
+ " radius: { default: 'var(--soma-radius-surface)', desc: '卡片圆角' },",
154
+ " padding: { default: 'var(--soma-space-4)', desc: '卡片内边距' },",
155
+ ' },',
156
+ ' ai: {',
157
+ " when_to_use: '需要在页面上呈现一组同构业务条目并允许逐条处置时',",
158
+ " when_not_to_use: '只是展示纯文本列表时用 SimpleList;要排序筛选用 DataTable',",
159
+ ' example: [',
160
+ ` '<div data-soma-component="${componentName}" data-soma-id="card"></div>',`,
161
+ " 'card: { props: { title: 待办, items: \"{{page.data.items}}\" } }',",
162
+ " 'card.action: NAV_ACTION | page.handleAction',",
163
+ " ].join('\\n'),",
164
+ " anti_patterns: ['不要在组件里判断业务规则——组件只呈现页面/服务端给的事实并上抛意图'],",
165
+ ' },',
166
+ ' },',
167
+ ' templateHtml: [',
168
+ ` '<section data-soma-id="root" class="soma-${kebab}">',`,
169
+ ` '<h3 data-soma-id="title" class="soma-${kebab}__title"></h3>',`,
170
+ ` '<div data-soma-slot-outlet="footer"></div>',`,
171
+ " '</section>',",
172
+ " ].join(''),",
173
+ ' uiConfig: {',
174
+ " bind: { obj: '__component', var: 'p' },",
175
+ " show: { title: 'p.title' },",
176
+ ' },',
177
+ ' };',
178
+ '}',
179
+ '',
180
+ ].join('\n');
181
+ }
182
+
183
+ function renderStyles(componentName: string, kebab: string): string {
184
+ return [
185
+ '// 按需装配的样式分片:组件首次实例化时才注入,页面只为用到的组件付钱。',
186
+ '//',
187
+ '// 三条纪律(与官方组件同一套闸门):',
188
+ '// · 颜色只能来自 --soma-* 令牌,不写裸色值(写了换肤就失效,而且不报错);',
189
+ '// · 只用逻辑方向属性(inline-start / inline-end),不写 left / right(RTL 会错位);',
190
+ '// · 契约里声明过的组件令牌要真的被样式用上,否则那个旋钮拧了没反应。',
191
+ '',
192
+ 'export const PACK_STYLES = {',
193
+ ` ${componentName}: [`,
194
+ ` '.soma-${kebab}{',`,
195
+ ` ' border-radius: var(--soma-${kebab}-radius);',`,
196
+ ` ' padding: var(--soma-${kebab}-padding);',`,
197
+ " ' background: var(--soma-surface-1);',",
198
+ " ' color: var(--soma-text-primary);',",
199
+ " '}',",
200
+ ` '.soma-${kebab}__title{',`,
201
+ " ' margin-block: 0 var(--soma-space-2);',",
202
+ " '}',",
203
+ " ].join(''),",
204
+ '};',
205
+ '',
206
+ ].join('\n');
207
+ }
208
+
209
+ function renderTest(packName: string, packVar: string, componentName: string, kebab: string): string {
210
+ return [
211
+ '// 包自检:第三方包从第一天起就受和官方组件同一把尺子管。',
212
+ "import { describe, expect, it } from 'vitest';",
213
+ "import { composeComponentPacks, verifyComponentPack } from 'soma-core';",
214
+ `import { ${packVar} } from '../src/index';`,
215
+ '',
216
+ `describe('${packName} 组件包', () => {`,
217
+ " it('过 verifyComponentPack:裸色值 / 物理方向属性 / 缺 ai 段 / 无默认值的可选 prop 全部拦下', () => {",
218
+ ` expect(verifyComponentPack(${packVar})).toEqual([]);`,
219
+ ' });',
220
+ '',
221
+ " it('能被合成,来源可追溯', () => {",
222
+ ` const composed = composeComponentPacks([${packVar}], { lazyStyles: false });`,
223
+ ` expect(composed.provenance.${componentName}).toBe('${packName}');`,
224
+ ' });',
225
+ '',
226
+ " it('契约声明的每个组件令牌都被样式分片真的用上了(拧了有反应)', () => {",
227
+ ` const def = ${packVar}.components.${componentName};`,
228
+ ` const css = ${packVar}.styles?.components?.${componentName} ?? '';`,
229
+ ' for (const key of Object.keys(def.contract.tokens ?? {})) {',
230
+ ` expect(css).toContain(\`var(--soma-${kebab}-\${key})\`);`,
231
+ ' }',
232
+ ' });',
233
+ '});',
234
+ '',
235
+ ].join('\n');
236
+ }
237
+
238
+ function renderReadme(packName: string, packVar: string, componentName: string): string {
239
+ return [
240
+ `# ${packName}`,
241
+ '',
242
+ `由 \`soma pack init ${packName}\` 生成的组件包骨架。`,
243
+ '',
244
+ '## 接进宿主',
245
+ '',
246
+ '```ts',
247
+ '// bootstrap/soma-bootstrap.ts',
248
+ "import { composeComponentPacks } from 'soma-core';",
249
+ "import { createSomaUiComponentPack } from 'soma-ui/component-pack';",
250
+ `import { ${packVar} } from '${packName}';`,
251
+ '',
252
+ `const composed = composeComponentPacks([createSomaUiComponentPack(), ${packVar}]);`,
253
+ 'export function configureSomaBootstrap() {',
254
+ ' return { components: composed.components };',
255
+ '}',
256
+ '```',
257
+ '',
258
+ '## 想改官方组件时,三条路怎么选',
259
+ '',
260
+ '| 诉求 | 走哪条 |',
261
+ '|---|---|',
262
+ '| 圆角 / 高度 / 颜色不合适 | 主题的 `components` 段调组件令牌 |',
263
+ '| 90% 合适,要挪一处间距、藏一个次要元素 | 样式补丁 `styles.patches` |',
264
+ '| 要改的是**行为** | `soma component eject <组件名>`,之后在本包里维护 |',
265
+ '| 要的是一个全新业务组件 | 直接写进本包的 `components` |',
266
+ '',
267
+ `\`${componentName}\` 是示例,按需替换或删除。`,
268
+ '',
269
+ ].join('\n');
270
+ }
@@ -15,6 +15,36 @@ export interface SomaHttpClientConfig {
15
15
  defaultHeaders?: Record<string, string> | (() => Record<string, string>);
16
16
  }
17
17
 
18
+ /** 错误正文带进异常消息的长度上限:够看清服务端文案,又不至于把整页 HTML 错误页塞进日志 */
19
+ const ERROR_BODY_MAX_LENGTH = 500;
20
+
21
+ /**
22
+ * 从错误响应正文里提炼一句可读文案。
23
+ *
24
+ * 服务端精心写的结构化错误(`{ ok: false, error: "未知组件:X" }`)才是调用方要的信息,
25
+ * 只留 statusText 等于把它整条丢掉。正文也可能是 HTML 错误页或空串,
26
+ * 因此 JSON 解析必须容错——解析失败只是"没有结构化字段",不该把请求变成另一种崩法。
27
+ */
28
+ export function describeHttpErrorBody(body: string, statusText: string): string {
29
+ const text = (body ?? '').trim();
30
+ if (text === '') return statusText;
31
+
32
+ let message = text;
33
+ try {
34
+ const parsed = JSON.parse(text);
35
+ if (parsed && typeof parsed === 'object') {
36
+ const field = (parsed as Record<string, unknown>).error ?? (parsed as Record<string, unknown>).message;
37
+ if (typeof field === 'string' && field.trim() !== '') message = field.trim();
38
+ }
39
+ } catch {
40
+ // 非 JSON(HTML 错误页、纯文本)就用正文原文
41
+ }
42
+
43
+ return message.length > ERROR_BODY_MAX_LENGTH
44
+ ? `${message.slice(0, ERROR_BODY_MAX_LENGTH)}…`
45
+ : message;
46
+ }
47
+
18
48
  /**
19
49
  * SomaHttpClient — API 请求封装
20
50
  *
@@ -116,7 +146,10 @@ export class SomaHttpClient {
116
146
  const res = await fetch(url, options);
117
147
 
118
148
  if (!res.ok) {
119
- throw new Error(`HTTP ${res.status}: ${res.statusText}`);
149
+ const errorBody = typeof res.text === 'function'
150
+ ? await res.text().catch(() => '')
151
+ : '';
152
+ throw new Error(`HTTP ${res.status}: ${describeHttpErrorBody(errorBody, res.statusText)}`);
120
153
  }
121
154
 
122
155
  return (await res.json()) as T;
@@ -2,6 +2,7 @@
2
2
  // 不依赖任何 DOM API,可在 Node.js 环境下独立运行
3
3
 
4
4
  import type { SomaPageRoot, SomaAppConfig } from '../../shared/types/domain.types';
5
+ import type { SomaPageState, SomaPageStateConfig } from '../../shared/types/page-state.types';
5
6
  import type { SomaRuntimeServices } from '../runtime/SomaRuntimeServices';
6
7
  import { readQueryParam } from '../infra/router/router-path';
7
8
  import { runAsync as runAsyncUtil } from './runAsync';
@@ -50,6 +51,20 @@ export abstract class SomaPageRootBase implements SomaPageRoot {
50
51
  /** 由 bootstrap 注入的数据对象重取钩子(无 *_data.yaml 声明时保持未定义) */
51
52
  _reloadData?: () => Promise<void>;
52
53
 
54
+ /**
55
+ * 页面态(REQ-010 F-37):排序 / 过滤 / 选择 / 列显隐与列序 / 密度 / 展开。
56
+ *
57
+ * 分享链接、用户偏好、审计回放共用这一份结构。它以**非枚举**属性挂载——
58
+ * 与 `data` 同一理由:页面状态快照与序列化不该把它算进业务字段。
59
+ */
60
+ _pageState!: SomaPageState | null;
61
+
62
+ /** 由 bootstrap 注入:`state:` 段的声明(没声明时为 null) */
63
+ _pageStateConfig?: SomaPageStateConfig | null;
64
+
65
+ /** 状态变化的订阅者(组件与 Host 都可以听) */
66
+ private _stateListeners?: Array<(state: SomaPageState) => void>;
67
+
53
68
  constructor() {
54
69
  // 字段声明会在构造早期定义可枚举属性,此处重定义为非枚举(configurable 保持 true)
55
70
  Object.defineProperty(this, 'data', {
@@ -58,6 +73,52 @@ export abstract class SomaPageRootBase implements SomaPageRoot {
58
73
  enumerable: false,
59
74
  configurable: true,
60
75
  });
76
+ Object.defineProperty(this, '_pageState', {
77
+ value: null,
78
+ writable: true,
79
+ enumerable: false,
80
+ configurable: true,
81
+ });
82
+ }
83
+
84
+ /**
85
+ * 当前页面态。没声明 `state:` 段时返回 null——**不是空对象**:
86
+ * 空对象会让调用方以为「有状态,只是都是缺省」,于是把它序列化进分享链接,
87
+ * 而链接打开后什么都恢复不了。null 说的是「这一页没有可序列化的状态」。
88
+ */
89
+ getState(): SomaPageState | null {
90
+ return this._pageState;
91
+ }
92
+
93
+ /**
94
+ * 整份替换页面态并通知订阅者。
95
+ *
96
+ * 整份替换而不是深合并:合并语义在「选择态从三行变成零行」这类清空操作上
97
+ * 是表达不出来的(少写一个键与写一个空数组在合并下是同一件事)。
98
+ * 要改一块就先 `getState()` 拿全份、改完再交回来——那是显式的。
99
+ */
100
+ setState(next: SomaPageState): void {
101
+ this._pageState = next;
102
+ for (const listener of this._stateListeners ?? []) listener(next);
103
+ }
104
+
105
+ /** 订阅页面态变化;返回退订函数 */
106
+ onStateUpdated(listener: (state: SomaPageState) => void): () => void {
107
+ if (!this._stateListeners) {
108
+ Object.defineProperty(this, '_stateListeners', {
109
+ value: [],
110
+ writable: true,
111
+ enumerable: false,
112
+ configurable: true,
113
+ });
114
+ }
115
+ this._stateListeners!.push(listener);
116
+ return () => {
117
+ const list = this._stateListeners;
118
+ if (!list) return;
119
+ const at = list.indexOf(listener);
120
+ if (at !== -1) list.splice(at, 1);
121
+ };
61
122
  }
62
123
 
63
124
  /**