soma-kit 0.1.5 → 0.1.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soma-kit",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
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.0",
52
49
  "soma-foundation": "^0.1.2",
53
50
  "tailwindcss": "^4.1.0"
54
51
  },
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 拒收)。