soma-kit 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -53,7 +53,7 @@ SOMA 的第三条 UI 路线(私有源码包,版本 0.1.0):模板与规
53
53
 
54
54
  `soma-kit` 拥有严密的质量保障网络,全层级代码、编译产物与运行时行为均已通过自动化验证:
55
55
  - **单元测试与集成测试**:全量测试套件通过(**125 个测试文件、1,571 条测试用例全部通过**,零失败);
56
- - **端到端页面回归**:包含 30 页真实业务示例(位于 `tests/fixtures/kit-app/pages/*.kit.yaml`),在真实浏览器与模拟运行时环境下逐页全编译、无诊断、零冲突,页面 URL 唯一,产物四件套完全符合 core 标准规范。
56
+ - **端到端页面回归**:包含 30 页真实业务示例(位于 `../soma-kit-demo/pages/*.kit.yaml`),在真实浏览器与模拟运行时环境下逐页全编译、无诊断、零冲突,页面 URL 唯一,产物四件套完全符合 core 标准规范。
57
57
 
58
58
  ---
59
59
 
@@ -214,7 +214,7 @@ VS Code 用法:装 Red Hat 的 YAML 插件,在工作区或用户 `settings.j
214
214
  }
215
215
  ```
216
216
 
217
- 不想改设置时,在文件首行写相对路径的modeline,示例见 `tests/fixtures/kit-app/`:
217
+ 不想改设置时,在文件首行写相对路径的modeline,示例见 `../soma-kit-demo/`:
218
218
 
219
219
  ```yaml
220
220
  # yaml-language-server: $schema=../../../../spec/generated/kit-page.schema.json
@@ -262,7 +262,7 @@ schema 只做补全与提示,对象内部的字段级语义仍归编译器校
262
262
 
263
263
  ## 表格列模型、工具栏、批量条、合计行与就地编辑(M 波 G2)
264
264
 
265
- 示例页 `/ref/g2`(`tests/fixtures/kit-app/pages/ref-g2.kit.yaml`):一张 14 列订单宽表。
265
+ 示例页 `/ref/g2`(`../soma-kit-demo/pages/ref-g2.kit.yaml`):一张 14 列订单宽表。
266
266
 
267
267
  - 字段新键:`fixed: left | right`(须连续地排在两端)、`align: start | center | end`、`ellipsis: true`(悬停 title 看全文)、`min: 16|20|24|28|32|40|48|56|64|80`(间距刻度)、`editable: true`、`columnFilter: true | enum | text`。写了 `fixed` / `min`、或 `toolbar` 含 `columns`,表格进**滚动模式**(定宽列、sticky 偏移是刻度累加;滚动后固定区边缘出现分隔线与阴影);与 `stickyHeader` 互斥。
268
268
  - 集合新键:`toolbar: [reload, density, columns, export]`(列显隐与行高记在 `localStorage`,键含页面路径与对象名)、`batchActions`(勾选后换成批量条,`confirm` 里 `{n}` 换成个数,确认在条内就地问;需要 `select: multi` 与勾选态来源如 StandardCrud)、`select: { mode, scope: page | all }`、`summary: { label, fields: { 字段: sum | avg | min | max | count } }`(只算当前页)、`edit_mode: cell | row`(保存抛 `cell_edit`,编成 `ACTION | data.submit`;Enter 保存、Esc 取消,校验沿用字段 `rules`)。
@@ -277,7 +277,7 @@ schema 只做补全与提示,对象内部的字段级语义仍归编译器校
277
277
 
278
278
  ## 行操作折叠、条件行类、翻页方式与地址参数(M 波 F3)
279
279
 
280
- 示例页 `/ref/f3`、`/ref/f3-more`、`/ref/f3-infinite`、`/ref/f3-shapes`(`tests/fixtures/kit-app/pages/ref-f3*.kit.yaml`)。
280
+ 示例页 `/ref/f3`、`/ref/f3-more`、`/ref/f3-infinite`、`/ref/f3-shapes`(`../soma-kit-demo/pages/ref-f3*.kit.yaml`)。
281
281
 
282
282
  - 行操作:`when`(行条件不成立按钮不显示)、`more: true`(固定进「更多」菜单);行内最多 3 个按钮,超出自动折叠。
283
283
  - `view.list.rowClassWhen: [{ when, class }]`:按行条件加类(仅 table,至多 4 项,类受 KIT-STYLE-001 约束)。
@@ -292,7 +292,7 @@ schema 只做补全与提示,对象内部的字段级语义仍归编译器校
292
292
 
293
293
  ## 虚拟滚动(N 波 N3)
294
294
 
295
- 示例页 `/ref/n3`(1 万行表格)、`/ref/n3-pick`(5000 项 Select / Combobox)、`/ref/n3-tree`(6252 节点 Tree),数据由服务端生成(`tests/fixtures/kit-app/api/service/ref/n3/**`)。
295
+ 示例页 `/ref/n3`(1 万行表格)、`/ref/n3-pick`(5000 项 Select / Combobox)、`/ref/n3-tree`(6252 节点 Tree),数据由服务端生成(`../soma-kit-demo/api/service/ref/n3/**`)。
296
296
 
297
297
  - 引擎走 core 虚拟滚动端口(`services.engines.virtual`,缺省 `@tanstack/virtual-core` 由 core 动态加载,kit 不 import)。接线在 `src/base/virtual-list.ts`;引擎不可用(未装配 / 加载失败)时回退为普通渲染,控制台只提示一次。
298
298
  - 表格:`collection.virtual: { rowHeight: sm | md | lg, height?: sm | md | lg }`。**行高必须显式给档位名**(不接受像素数字),没写 `rowHeight` 就不虚拟化;表体换成 `KitVirtualRows`,保留表头吸顶、固定列、选择与批量条、合计行(粘底)、就地编辑、键盘(跨窗口)、`aria-rowcount / aria-rowindex`。与 `page.mode: infinite` 不并用(改按 `more` 处理并报 `KIT-OBJ-009`),推荐 `page: false` 一次给全量。不支持 `expand` 与字段级 `action`。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soma-kit",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "SOMA 第三条 UI 路线:写死模板与规则,DSL 显式传入,基础组件 + 数据组件",
5
5
  "type": "module",
6
6
  "exports": {
@@ -45,10 +45,7 @@
45
45
  "dependencies": {
46
46
  "jiti": "1.21.7",
47
47
  "js-yaml": "4.3.2",
48
- "next": "16.4.1",
49
- "react": "18.3.1",
50
- "react-dom": "18.3.1",
51
- "soma-core": "^2.1.6",
48
+ "soma-core": "^2.2.4",
52
49
  "soma-foundation": "^0.1.2",
53
50
  "tailwindcss": "^4.1.0"
54
51
  },
package/src/app/index.ts CHANGED
@@ -52,5 +52,12 @@ export { emptyFragment, mergeFragments, fragmentFromEmit } from '../compile/frag
52
52
  export type { KitFragment } from '../compile/fragment';
53
53
  export type { KitDiagnostic, KitObject } from '../object-renderer/types';
54
54
 
55
- // core 的两个公开类型再导出:kit 应用写自定义组件 / 鉴权选项时不必自己 import soma-core
56
- export type { SomaComponentDefinition, SomaAuthOption } from 'soma-core';
55
+ // core 的公开类型再导出:kit 应用写自定义组件 / 控制器 / 鉴权选项时统一从 soma-kit/app 或 soma-core 取用
56
+ export type {
57
+ SomaComponentDefinition,
58
+ SomaComponentControllerContext,
59
+ SomaComponentControllerFactory,
60
+ SomaComponentServiceName,
61
+ SomaDataPort,
62
+ SomaAuthOption,
63
+ } from 'soma-core';
package/src/app/server.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // 只在服务端 / build 面可达;node 内置模块与 core 服务端子路径全部动态 import,并带 webpackIgnore,
3
3
  // 即便 defineKitApp 的惰性 import 被打进浏览器包图,也不会在解析期报错。
4
4
 
5
+ import { createHash } from 'node:crypto';
5
6
  import { KIT_BASE_COMPONENTS } from '../base/index';
6
7
  import { KIT_STATIC_BUILTIN_SPECS } from '../data/static-registry';
7
8
  import { compileKitPage } from '../compile/compile-page';
@@ -19,6 +20,64 @@ import { KIT_PAGE_OWNER, createKitServerPages } from './server-pages';
19
20
  import type { KitServerPages } from './submit.types';
20
21
 
21
22
  export const KIT_OWNER = KIT_PAGE_OWNER;
23
+ export const KIT_GRAMMAR_VERSION = '0.1.0';
24
+ export const MAX_KIT_PAGE_CACHE = 256;
25
+
26
+ const kitPageCompileCache = new Map<string, KitPageArtifact>();
27
+
28
+ /** 清空页面编译产物缓存(供测试或热重载) */
29
+ export function clearKitPageCompileCache(): void {
30
+ kitPageCompileCache.clear();
31
+ }
32
+
33
+ /** 获取当前页面编译产物缓存条目数(供测试断言) */
34
+ export function getKitPageCompileCacheSize(): number {
35
+ return kitPageCompileCache.size;
36
+ }
37
+
38
+ /** 计算确定性输入指纹 */
39
+ export function computeKitPageCacheKey(
40
+ yamlText: string,
41
+ declaredUrl: string,
42
+ appContext: KitAppContext,
43
+ ): string {
44
+ return createHash('sha256')
45
+ .update(KIT_GRAMMAR_VERSION)
46
+ .update('\0')
47
+ .update(appContext.themeTokensCss ?? '')
48
+ .update('\0')
49
+ .update(appContext.themeCss)
50
+ .update('\0')
51
+ .update(JSON.stringify(appContext.envelope ?? null))
52
+ .update('\0')
53
+ .update(JSON.stringify(appContext.locales ?? null))
54
+ .update('\0')
55
+ .update((appContext.appCandidates ?? []).join('\0'))
56
+ .update('\0')
57
+ .update(declaredUrl)
58
+ .update('\0')
59
+ .update(yamlText)
60
+ .digest('hex');
61
+ }
62
+
63
+ function cloneKitPageArtifact(artifact: KitPageArtifact): KitPageArtifact {
64
+ return {
65
+ url: artifact.url,
66
+ html: artifact.html,
67
+ uiYaml: artifact.uiYaml,
68
+ eventYaml: artifact.eventYaml,
69
+ styles: artifact.styles.map((s) => ({ ...s })),
70
+ version: artifact.version,
71
+ };
72
+ }
73
+
74
+ function deepFreezeKitPageArtifact(artifact: KitPageArtifact): KitPageArtifact {
75
+ for (const s of artifact.styles) {
76
+ Object.freeze(s);
77
+ }
78
+ Object.freeze(artifact.styles);
79
+ return Object.freeze(artifact);
80
+ }
22
81
 
23
82
  export class KitAppAssemblyError extends Error {
24
83
  readonly diagnostics: KitDiagnostic[];
@@ -142,6 +201,14 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
142
201
  }
143
202
  }
144
203
 
204
+ // 共享样式引擎实例:未传 options.styleEngine 时持有一个共享实例挂在 appContext.styleEngine 上
205
+ const customStyleEngine = (options as { styleEngine?: import('soma-core/server/style-engine').SomaStyleEngine }).styleEngine;
206
+ let sharedStyleEngine = customStyleEngine;
207
+ if (sharedStyleEngine === undefined) {
208
+ const { createStyleEnginePort } = await import('soma-core/server/style-engine');
209
+ sharedStyleEngine = createStyleEnginePort();
210
+ }
211
+
145
212
  // 业务信封约定:编译期编进 core 数据声明,服务端薄壳(分页适配等)缺省读同一份
146
213
  setKitAppEnvelope(config.envelope);
147
214
  const appContext: KitAppContext = {
@@ -157,6 +224,7 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
157
224
  bizComponents: registry.bizComponents,
158
225
  frames: registry.frames,
159
226
  appCandidates: registry.appCandidates,
227
+ styleEngine: sharedStyleEngine,
160
228
  componentDefinitions: {
161
229
  ...registry.baseComponents,
162
230
  ...Object.fromEntries(Object.entries(registry.staticComponents).map(([n, e]) => [n, e.definition])),
@@ -177,25 +245,56 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
177
245
  }
178
246
  const artifacts = new Map<string, KitPageArtifact>();
179
247
  const failures: KitDiagnostic[] = [];
248
+ const isCustomStyleEngine = customStyleEngine !== undefined;
249
+
180
250
  for (const { dir, file: name } of pageFiles) {
181
251
  const file = dir === pageDirs[0] ? name : `${path.relative(root, path.join(dir, name)) || name}`;
182
252
  const text = await fs.readFile(path.join(dir, name), 'utf8');
183
- const res = await compileKitPage(text, appContext);
184
- if (res.artifact === undefined || res.diagnostics.length > 0) {
185
- const locate = createYamlLocator(text);
186
- failures.push(...res.diagnostics.map((d) => {
187
- const pos = locate(d.path);
188
- return { ...d, path: `${file}:${d.path}`, file, ...(pos ? { line: pos.line, column: pos.column } : {}) };
189
- }));
190
- // 没产物又没诊断也是失败:不许静默吞掉一页
191
- if (res.diagnostics.length === 0) failures.push({ code: 'KIT-PAGE-004', path: file, message: '页面没有产出产物,也没有给出诊断' });
192
- continue;
253
+
254
+ let artifact: KitPageArtifact | undefined;
255
+ const urlMatch = /^\s*url:\s*['"]?([^\s'"#]+)['"]?/m.exec(text);
256
+ const declaredUrl = urlMatch ? urlMatch[1] : '';
257
+ const cacheKey = !isCustomStyleEngine
258
+ ? computeKitPageCacheKey(text, declaredUrl, appContext)
259
+ : undefined;
260
+
261
+ if (cacheKey !== undefined) {
262
+ const cached = kitPageCompileCache.get(cacheKey);
263
+ if (cached !== undefined) {
264
+ kitPageCompileCache.delete(cacheKey);
265
+ kitPageCompileCache.set(cacheKey, cached);
266
+ artifact = deepFreezeKitPageArtifact(cloneKitPageArtifact(cached));
267
+ }
268
+ }
269
+
270
+ if (artifact === undefined) {
271
+ const res = await compileKitPage(text, appContext);
272
+ if (res.artifact === undefined || res.diagnostics.length > 0) {
273
+ const locate = createYamlLocator(text);
274
+ failures.push(...res.diagnostics.map((d) => {
275
+ const pos = locate(d.path);
276
+ return { ...d, path: `${file}:${d.path}`, file, ...(pos ? { line: pos.line, column: pos.column } : {}) };
277
+ }));
278
+ // 没产物又没诊断也是失败:不许静默吞掉一页
279
+ if (res.diagnostics.length === 0) failures.push({ code: 'KIT-PAGE-004', path: file, message: '页面没有产出产物,也没有给出诊断' });
280
+ continue;
281
+ }
282
+ artifact = res.artifact;
283
+ if (cacheKey !== undefined) {
284
+ while (kitPageCompileCache.size >= MAX_KIT_PAGE_CACHE) {
285
+ const oldest = kitPageCompileCache.keys().next().value;
286
+ if (oldest !== undefined) kitPageCompileCache.delete(oldest);
287
+ else break;
288
+ }
289
+ kitPageCompileCache.set(cacheKey, cloneKitPageArtifact(artifact));
290
+ }
193
291
  }
194
- if (artifacts.has(res.artifact.url)) {
195
- failures.push({ code: 'KIT-PAGE-004', path: file, message: `页面地址 ${res.artifact.url} 重复` });
292
+
293
+ if (artifacts.has(artifact.url)) {
294
+ failures.push({ code: 'KIT-PAGE-004', path: file, message: `页面地址 ${artifact.url} 重复` });
196
295
  continue;
197
296
  }
198
- artifacts.set(res.artifact.url, res.artifact);
297
+ artifacts.set(artifact.url, artifact);
199
298
  }
200
299
  if (failures.length > 0) throw new KitAppAssemblyError('页面编译失败,拒绝启动', failures);
201
300
 
@@ -57,9 +57,11 @@ import { classesInHtml } from '../object-renderer/candidates';
57
57
  import { checkClasses } from '../object-renderer/merge-class';
58
58
  import { KIT_TABLE_ACTIONS_CLASS_CANDIDATES } from '../object-renderer/table-actions';
59
59
  import { KIT_COLLECTION_STATE_CLASS_CANDIDATES, KIT_TABLE_HEAD_CLASS_CANDIDATES } from '../object-renderer/collection-parts';
60
- import { KIT_TABLE_TOOLS_CLASS_CANDIDATES } from '../object-renderer/table-tools';import type { KitDiagnostic } from '../object-renderer/types';
60
+ import { KIT_TABLE_TOOLS_CLASS_CANDIDATES } from '../object-renderer/table-tools';
61
+ import type { KitDiagnostic } from '../object-renderer/types';
61
62
  import { wrappedCandidateSource } from '../data/wrapped-candidates';
62
63
  import type { SomaComponentDefinition } from 'soma-core';
64
+ import type { SomaStyleEngine } from 'soma-core/server/style-engine';
63
65
  import type { KitFragment } from './fragment';
64
66
  import type { KitAppContext } from './types';
65
67
 
@@ -218,6 +220,13 @@ const MARKER_CLASS = /^(group|peer)(\/[A-Za-z0-9_-]+)?$/;
218
220
  /** 块级主题的作用域类(theme/block-theme.ts 写在块根上):它是令牌变量块的选择器,不是工具类,不交样式引擎 */
219
221
  const SCOPE_CLASS = /^soma-scope-[a-z0-9]+(?:-[a-z0-9]+)*$/;
220
222
 
223
+ let defaultStyleEngine: SomaStyleEngine | undefined;
224
+
225
+ /** 清除默认样式引擎实例(供测试重置) */
226
+ export function clearDefaultStyleEngine(): void {
227
+ defaultStyleEngine = undefined;
228
+ }
229
+
221
230
  /** 候选类是否放行:方括号任意值与主题头里没有的键一律不放行(同对象渲染内核的 KIT-STYLE-001 口径) */
222
231
  export function allowCandidate(candidate: string): boolean {
223
232
  return checkClasses(candidate, '').length === 0;
@@ -227,8 +236,11 @@ export function allowCandidate(candidate: string): boolean {
227
236
  export async function compileStyles(candidates: readonly string[], app: KitAppContext, blockThemeCss = ''): Promise<KitStyleResult> {
228
237
  let engine = app.styleEngine;
229
238
  if (engine === undefined) {
230
- const mod = await import('soma-core/server/style-engine');
231
- engine = mod.createStyleEnginePort();
239
+ if (defaultStyleEngine === undefined) {
240
+ const mod = await import('soma-core/server/style-engine');
241
+ defaultStyleEngine = mod.createStyleEnginePort();
242
+ }
243
+ engine = defaultStyleEngine;
232
244
  }
233
245
  // group / peer(含具名 group/x、peer/x)只是变体锚点标记,本身不产生任何样式规则;
234
246
  // 它们留在 HTML 上给 group-hover: / peer-checked: 等变体用,不交样式引擎(否则按 no-rule 拒收)。