soma-kit 0.1.16 → 0.1.18

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.
@@ -17,7 +17,10 @@ import type { SomaHostAssembly } from 'soma-core/server/host-assembly';
17
17
  import { createKitBaseComponents, KIT_BASE_COMPONENTS } from '../base/index';
18
18
  import { bizDataComponents, KIT_BIZ_DATA_COMPONENTS } from '../biz/data-components';
19
19
  import { KIT_BIZ_COMPONENT_NAMES, KIT_FRAME_NAMES } from '../biz/names';
20
+ import { isDefinedKitBizComponent } from '../biz/define';
20
21
  import type { KitBizDefinition } from '../biz/types';
22
+ import { hasInternalLabMark } from './internal-lab';
23
+ import { checkClasses } from '../shared/merge-class';
21
24
  import type { KitThemeConfig } from '../theme/theme-tokens';
22
25
  import type { KitAppDicts, KitAppEntities, KitAppTheme } from './app-config';
23
26
  import { parseKitAppEnvelopeFromYaml, registerKitAppDefaultEnvelope, type KitEnvelope } from '../shared/envelope';
@@ -140,6 +143,8 @@ export interface KitAppRegistry {
140
143
  bizComponents: Record<string, KitBizDefinition>;
141
144
  frames: Record<string, KitFrameDefinition>;
142
145
  appCandidates: readonly string[];
146
+ /** 自定义业务组件自携的私有协作数据组件(已实例化,并入浏览器组件表;页面不可直接选用) */
147
+ bizDataComponents: Record<string, SomaComponentDefinition>;
143
148
  /** 领域包的协作数据组件(已实例化,并入浏览器组件表;页面不可直接选用) */
144
149
  packDataComponents: Record<string, SomaComponentDefinition>;
145
150
  /** 已登记的领域包名 */
@@ -211,6 +216,16 @@ export function buildAppRegistry(options: DefineKitAppOptions): KitAppRegistry {
211
216
  kitFail('KIT-APP-001', 'pagesDir', pagesDiags[0]!.message, '改为相对应用根的页面子目录名(如 pages),严禁 ./、../ 或宿主机系统绝对路径');
212
217
  }
213
218
  }
219
+ const allowLab = hasInternalLabMark(options);
220
+ const rawBaseNames = Object.keys(options.baseComponents ?? {});
221
+ if (!allowLab && rawBaseNames.length > 0) {
222
+ kitFail(
223
+ 'KIT-APP-016',
224
+ `baseComponents.${rawBaseNames[0]!}`,
225
+ `禁止业务应用注册非业务/非数据的野生基础组件(baseComponents:${rawBaseNames.join('、')});基础控件一律复用框架官方闭集`,
226
+ '外部界面扩展仅开放两档:① 业务组件 bizComponents(defineKitBizComponent,可自带私有 dataComponents);② 纯数据驱动自定义数据组件 staticObjectComponents(一份数据一个组件、数据进事件出,供业务组件 DSL 槽位按名选用)',
227
+ );
228
+ }
214
229
  const allow = new Set(options.overrides ?? []);
215
230
  const builtinBase = new Set<string>(Object.keys(KIT_BASE_COMPONENTS));
216
231
  const baseComponents: KitAppRegistry['baseComponents'] = {};
@@ -219,7 +234,7 @@ export function buildAppRegistry(options: DefineKitAppOptions): KitAppRegistry {
219
234
  if (builtinBase.has(name) && !allow.has(name)) kitFail('KIT-APP-007', `baseComponents.${name}`, `基础组件 "${name}" 已内置;要覆盖请在 overrides 点名`, `换一个 App 开头的新名字,或在 defineKitApp 的 overrides 里加入 "${name}"`);
220
235
  const def = instantiate(name, input);
221
236
  if (def.contract['layer'] !== 'basic') kitFail('KIT-APP-006', `baseComponents.${name}`, `应用基础组件 ${name} 的契约 layer 必须是 basic`, '契约 layer 改为 basic;业务含数据的组件请登记到 staticObjectComponents');
222
- assertSinglePathComponent(name, def);
237
+ assertSinglePathComponent(name, def, { strictBizOnly: !allowLab });
223
238
  baseComponents[name] = def;
224
239
  }
225
240
 
@@ -233,7 +248,7 @@ export function buildAppRegistry(options: DefineKitAppOptions): KitAppRegistry {
233
248
  const spec = isSpec(input);
234
249
  const def = instantiate(name, spec ? input.define : input);
235
250
  if (def.contract['layer'] !== 'data') kitFail('KIT-APP-006', `staticObjectComponents.${name}`, `应用数据组件 ${name} 的契约 layer 必须是 data`, '契约 layer 改为 data;纯展示小件请登记到 baseComponents');
236
- assertSinglePathComponent(name, def);
251
+ assertSinglePathComponent(name, def, { strictBizOnly: !allowLab });
237
252
  staticComponents[name] = spec ? { definition: def, accept: input.accept } : { definition: def };
238
253
  }
239
254
 
@@ -285,12 +300,62 @@ export function buildAppRegistry(options: DefineKitAppOptions): KitAppRegistry {
285
300
  }
286
301
  }
287
302
 
288
- // 业务组件 / 页面框与内置同名:必须在 overrides 点名,不静默覆盖;登记名必须等于定义的 kind
303
+ // 业务组件 / 页面框与内置同名:必须在 overrides 点名,不静默覆盖;登记名必须等于定义的 kind,且必须经 defineKitBizComponent 构造
304
+ const bizDataComponentsMap: Record<string, SomaComponentDefinition> = {};
305
+ const bizCandidates: string[] = [];
306
+ const builtinBizData = new Set<string>(Object.keys(KIT_BIZ_DATA_COMPONENTS));
289
307
  for (const [name, def] of Object.entries(options.bizComponents ?? {})) {
290
308
  if (def === null || typeof def !== 'object' || def.kind !== name) kitFail('KIT-APP-009', `bizComponents.${name}`, `业务组件登记名 "${name}" 与定义的 kind 不一致`, '登记名必须等于定义的 kind');
309
+ if (!isDefinedKitBizComponent(def)) {
310
+ kitFail(
311
+ 'KIT-APP-019',
312
+ `bizComponents.${name}`,
313
+ `业务组件 "${name}" 未通过 defineKitBizComponent(...) 构造,禁止以裸对象绕过业务组件契约`,
314
+ '使用 defineKitBizComponent({ kind, roles, areas, dataComponents?, candidates?, compile }) 定义后再登记至 bizComponents',
315
+ );
316
+ }
291
317
  if (KIT_BIZ_COMPONENT_NAMES.includes(name) && !allow.has(name)) {
292
318
  kitFail('KIT-APP-007', `bizComponents.${name}`, `业务组件 "${name}" 已内置;要覆盖请在 overrides 点名`, `换一个新名字,或在 defineKitApp 的 overrides 里加入 "${name}"`);
293
319
  }
320
+ for (const [compName, compInput] of Object.entries(def.dataComponents ?? {})) {
321
+ if (
322
+ builtinBase.has(compName)
323
+ || KIT_STATIC_BUILTIN_NAMES.includes(compName)
324
+ || KIT_BIZ_COMPONENT_NAMES.includes(compName)
325
+ || builtinBizData.has(compName)
326
+ || compName in baseComponents
327
+ || compName in staticComponents
328
+ || compName in bizDataComponentsMap
329
+ ) {
330
+ kitFail(
331
+ 'KIT-APP-007',
332
+ `bizComponents.${name}.dataComponents.${compName}`,
333
+ `业务组件 ${name} 的私有协作数据组件 "${compName}" 与内置或已登记组件重名`,
334
+ `为 ${name} 的私有协作组件更换唯一不冲突的名称`,
335
+ );
336
+ }
337
+ const compDef = instantiate(compName, compInput);
338
+ if (compDef.contract['layer'] !== 'data') {
339
+ kitFail(
340
+ 'KIT-APP-006',
341
+ `bizComponents.${name}.dataComponents.${compName}`,
342
+ `业务组件 ${name} 的私有协作数据组件 ${compName} 的契约 layer 必须是 data`,
343
+ '契约 layer 改为 data;业务组件私有交互内核须通过 data 层组件承接业务数据',
344
+ );
345
+ }
346
+ assertSinglePathComponent(compName, compDef, { strictBizOnly: !allowLab });
347
+ bizDataComponentsMap[compName] = compDef;
348
+ }
349
+ for (const rawCand of def.candidates ?? []) {
350
+ for (const tok of rawCand.split(/\s+/)) {
351
+ if (tok === '') continue;
352
+ const bad = checkClasses(tok, `bizComponents.${name}.candidates`);
353
+ if (bad.length > 0) {
354
+ kitFail('KIT-COMP-003', `bizComponents.${name}.candidates`, `业务组件 ${name} 的候选类 "${tok}" 非法:${bad[0]!.message}`, '候选类只能用刻度内的 Tailwind 类,不写方括号任意值');
355
+ }
356
+ bizCandidates.push(tok);
357
+ }
358
+ }
294
359
  }
295
360
  for (const [name, def] of Object.entries(options.frames ?? {})) {
296
361
  if (def === null || typeof def !== 'object' || def.kind !== name) kitFail('KIT-APP-009', `frames.${name}`, `页面框登记名 "${name}" 与定义的 kind 不一致`, '登记名必须等于定义的 kind');
@@ -300,9 +365,9 @@ export function buildAppRegistry(options: DefineKitAppOptions): KitAppRegistry {
300
365
  }
301
366
  const bizComponents: Record<string, KitBizDefinition> = { ...(options.bizComponents ?? {}) };
302
367
  const packDataComponents: Record<string, SomaComponentDefinition> = {};
303
- const candidates = new Set<string>(options.appCandidates ?? []);
368
+ const candidates = new Set<string>([...(options.appCandidates ?? []), ...bizCandidates]);
304
369
  const packNames: string[] = [];
305
- mergePacks(options.packs ?? [], { baseComponents, staticComponents, bizComponents, packDataComponents, candidates, packNames });
370
+ mergePacks(options.packs ?? [], { baseComponents, staticComponents, bizComponents, bizDataComponents: bizDataComponentsMap, packDataComponents, candidates, packNames });
306
371
 
307
372
  return {
308
373
  baseComponents,
@@ -312,7 +377,8 @@ export function buildAppRegistry(options: DefineKitAppOptions): KitAppRegistry {
312
377
  viewInfos,
313
378
  bizComponents,
314
379
  frames: { ...(options.frames ?? {}) },
315
- appCandidates: options.packs !== undefined && options.packs.length > 0 ? [...candidates] : (options.appCandidates ?? []),
380
+ appCandidates: (options.packs !== undefined && options.packs.length > 0) || bizCandidates.length > 0 ? [...candidates] : (options.appCandidates ?? []),
381
+ bizDataComponents: bizDataComponentsMap,
316
382
  packDataComponents,
317
383
  packNames,
318
384
  appEnvelope,
@@ -323,6 +389,7 @@ interface PackMergeTarget {
323
389
  baseComponents: KitAppRegistry['baseComponents'];
324
390
  staticComponents: KitAppRegistry['staticComponents'];
325
391
  bizComponents: Record<string, KitBizDefinition>;
392
+ bizDataComponents: Record<string, SomaComponentDefinition>;
326
393
  packDataComponents: Record<string, SomaComponentDefinition>;
327
394
  candidates: Set<string>;
328
395
  packNames: string[];
@@ -344,6 +411,7 @@ function mergePacks(packs: readonly KitPack[], t: PackMergeTarget): void {
344
411
  for (const n of Object.keys(t.baseComponents)) taken.set(n, '应用基础组件');
345
412
  for (const n of Object.keys(t.staticComponents)) taken.set(n, '应用数据组件');
346
413
  for (const n of Object.keys(t.bizComponents)) taken.set(n, '应用业务组件');
414
+ for (const n of Object.keys(t.bizDataComponents)) taken.set(n, '业务组件私有协作数据组件');
347
415
 
348
416
  const claim = (name: string, path: string, who: string): boolean => {
349
417
  const prev = taken.get(name);
@@ -410,6 +478,7 @@ export function buildBrowserMount(registry: KitAppRegistry): KitBrowserMount {
410
478
  // 业务组件壳与页面框层依赖的协作常驻组件与内置数据组件同表;内置名不与应用名冲突(应用名须 App 开头)
411
479
  const components: Record<string, SomaComponentDefinition> = { ...base, ...data, ...createKitFrameResidentComponents(), ...bizDataComponents() };
412
480
  for (const [name, entry] of Object.entries(registry.staticComponents)) components[name] = entry.definition;
481
+ for (const [name, def] of Object.entries(registry.bizDataComponents)) components[name] = def;
413
482
  for (const [name, def] of Object.entries(registry.packDataComponents)) components[name] = def;
414
483
  // 应用登记项同名覆盖内置时,常驻表优先(core 以 components 为准),不再按需加载内置版
415
484
  return { components, lazyComponents: { ...KIT_STATIC_LAZY_LOADERS }, actions: { ...registry.actions }, pageRoots: { ...registry.views } };
@@ -0,0 +1,90 @@
1
+ // 仓内内部实验室豁免判定(内部私有模块,严禁从 soma-kit/app 或 package.json#exports 导出)。
2
+ //
3
+ // 安全闭环:
4
+ // 1. 仓内单测通过 withInternalLabMode(options) 将夹具对象登记进进程内私有 WeakSet,外部代码拿不到该函数;
5
+ // 2. 仓内视觉实验室 soma-kit-demo 需跨浏览器与服务端双面运行且不能深导入 soma-kit/src/**,
6
+ // 故在其 defineKitApp 选项上标注非公开符号 KIT_INTERNAL_DEMO_MARK;
7
+ // 3. 服务端 assembleKitServer 必须调用 verifyInternalLabRoot 对该符号做目录物理验真
8
+ // (package.json 的 name === 'soma-kit-demo'、private === true 且同级存在 ../soma-kit/spec/kit-grammar.json),
9
+ // 且非真实验室应用的源码 AST 门禁(KIT-APP-018)直接拦截 Symbol.for('soma-kit.*') 字面量,外部应用 0 绕过口。
10
+ //
11
+ // 注意:本模块会被 define-kit-app.ts 静态引入(进浏览器包),顶层严禁静态 import node:* 或 typescript。
12
+
13
+ import type { DefineKitAppOptions } from './define-kit-app';
14
+ import type { KitDiagnostic } from '../object-renderer/types';
15
+
16
+ const INTERNAL_LAB_OPTIONS = new WeakSet<object>();
17
+
18
+ /** 仓内视觉实验室(soma-kit-demo)专用内部标记;外部应用伪造将被服务端物理验真与 AST 门禁双杀(KIT-APP-018) */
19
+ export const KIT_INTERNAL_DEMO_MARK = Symbol.for('soma-kit.internal.monorepo-demo');
20
+
21
+ /** 仅限 soma-kit 仓内单测使用:标记测试夹具选项处于内部实验室模式(走私有 WeakSet,不泄漏公开字段) */
22
+ export function withInternalLabMode<T extends DefineKitAppOptions>(options: T): T {
23
+ INTERNAL_LAB_OPTIONS.add(options);
24
+ return options;
25
+ }
26
+
27
+ /** 判定选项是否通过仓内私有 WeakSet 登记为内部实验室测试夹具 */
28
+ export function isInternalLabOptions(options: unknown): boolean {
29
+ return typeof options === 'object' && options !== null && INTERNAL_LAB_OPTIONS.has(options);
30
+ }
31
+
32
+ /** 判定选项对象是否携带仓内演示应用标记(浏览器期只作形态判断,服务端必须经 verifyInternalLabRoot 物理验真) */
33
+ export function hasInternalDemoMark(options: unknown): boolean {
34
+ return typeof options === 'object' && options !== null && (options as Record<symbol, unknown>)[KIT_INTERNAL_DEMO_MARK] === true;
35
+ }
36
+
37
+ /** 浏览器/同步装配期快速判断(WeakSet 测试夹具或带仓内演示标记);最终可信裁决由服务端 verifyInternalLabRoot 做出 */
38
+ export function hasInternalLabMark(options: unknown): boolean {
39
+ return isInternalLabOptions(options) || hasInternalDemoMark(options);
40
+ }
41
+
42
+ /** 服务端物理验真:仅当 root 确系本仓库同级 soma-kit-demo 时返回 true */
43
+ export async function isMonorepoKitDemoRoot(
44
+ root: string,
45
+ fs: typeof import('node:fs/promises'),
46
+ path: typeof import('node:path'),
47
+ ): Promise<boolean> {
48
+ try {
49
+ const pkgText = await fs.readFile(path.join(root, 'package.json'), 'utf8');
50
+ const pkg = JSON.parse(pkgText) as { name?: unknown; private?: unknown };
51
+ if (pkg.name !== 'soma-kit-demo' || pkg.private !== true) return false;
52
+ const siblingGrammar = path.resolve(root, '..', 'soma-kit', 'spec', 'kit-grammar.json');
53
+ await fs.access(siblingGrammar);
54
+ return true;
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * 服务端实验室身份物理验真:
62
+ * - WeakSet 登记的仓内单测夹具直接放行;
63
+ * - 携带 KIT_INTERNAL_DEMO_MARK 的应用必须通过 soma-kit-demo 物理目录验真,伪造即产出 KIT-APP-018 硬诊断并取消豁免。
64
+ */
65
+ export async function verifyInternalLabRoot(
66
+ root: string,
67
+ options: unknown,
68
+ fs: typeof import('node:fs/promises'),
69
+ path: typeof import('node:path'),
70
+ ): Promise<{ readonly internalLab: boolean; readonly diagnostics: KitDiagnostic[] }> {
71
+ if (isInternalLabOptions(options)) {
72
+ return { internalLab: true, diagnostics: [] };
73
+ }
74
+ if (hasInternalDemoMark(options)) {
75
+ const ok = await isMonorepoKitDemoRoot(root, fs, path);
76
+ if (ok) return { internalLab: true, diagnostics: [] };
77
+ return {
78
+ internalLab: false,
79
+ diagnostics: [
80
+ {
81
+ code: 'KIT-APP-018',
82
+ path: 'soma.app.ts',
83
+ message: '检测到非框架内部实验室应用伪造内部实验室符号(Symbol.for("soma-kit.internal.monorepo-demo")),已拒绝豁免',
84
+ hint: '移除伪造的内部符号标记,并将自定义界面封装为标准业务组件(defineKitBizComponent + bizComponents)',
85
+ },
86
+ ],
87
+ };
88
+ }
89
+ return { internalLab: false, diagnostics: [] };
90
+ }
package/src/app/server.ts CHANGED
@@ -28,6 +28,7 @@ import { kitThemeShardUsageOfPage, mergeKitThemeShardUsage, sameKitThemeShardUsa
28
28
  import type { KitThemeUsage } from '../shared/theme-usage';
29
29
  import { parseAppConfig, checkRemovedThemeKeys, migrateKitRuntimeTheme, parseKitTheme, type KitAppTheme } from './app-config';
30
30
  import { scanAppComponentSources } from './component-gate';
31
+ import { verifyInternalLabRoot } from './internal-lab';
31
32
  import { handleKitThemeRequest } from './theme-endpoint';
32
33
  import type { DefineKitAppOptions, KitAppRegistry } from './define-kit-app';
33
34
  import { KIT_PAGE_OWNER, KIT_TIER_FACTS_MISSING, createKitServerPages, kitRuntimePageFactsOfVersion, type KitRuntimePageFacts, type KitRuntimePagePlan } from './server-pages';
@@ -743,17 +744,48 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
743
744
  const path = await nodePath();
744
745
  const fs = await nodeFs();
745
746
  const root = await resolveKitAppRoot(options.root, path);
747
+ const labCheck = await verifyInternalLabRoot(root, options, fs, path);
748
+ const internalLab = labCheck.internalLab;
746
749
 
747
750
  // 1 kit.app.yaml
748
751
  const appFile = path.join(root, options.app ?? 'kit.app.yaml');
749
752
  const appText = await readIfExists(appFile);
750
- const diagnostics: KitDiagnostic[] = [];
753
+ const diagnostics: KitDiagnostic[] = [...labCheck.diagnostics];
751
754
  const parsedAppYaml = appText === undefined ? undefined : await parseYaml(appText, 'kit.app.yaml', diagnostics);
752
755
  const config = parseAppConfig(parsedAppYaml, diagnostics);
753
756
 
754
- // 2 与代码登记对账(两边都要有)
755
- for (const name of Object.keys(config.baseComponents)) {
756
- if (!(name in registry.baseComponents)) diagnostics.push({ code: 'KIT-APP-001', path: `baseComponents.${name}`, message: `kit.app.yaml 登记了基础组件 ${name},soma.app.ts 没有提供实现` });
757
+ if (!internalLab) {
758
+ for (const name of Object.keys(options.baseComponents ?? {})) {
759
+ diagnostics.push({
760
+ code: 'KIT-APP-016',
761
+ path: `baseComponents.${name}`,
762
+ message: `禁止业务应用注册非业务/非数据的野生基础组件 ${name}(baseComponents);基础控件一律复用框架官方闭集`,
763
+ hint: '改用 bizComponents(defineKitBizComponent,可自带私有 dataComponents)或纯数据驱动自定义数据组件 staticObjectComponents',
764
+ });
765
+ }
766
+ for (const name of Object.keys(config.baseComponents)) {
767
+ diagnostics.push({
768
+ code: 'KIT-APP-016',
769
+ path: `kit.app.yaml.baseComponents.${name}`,
770
+ message: `禁止在 kit.app.yaml 中声明非业务/非数据的野生基础组件 ${name}(baseComponents);基础控件一律复用框架官方闭集`,
771
+ hint: '删除 kit.app.yaml#baseComponents,改用业务组件 bizComponents 或纯数据驱动数据组件 staticObjectComponents',
772
+ });
773
+ }
774
+ if (config.style !== undefined) {
775
+ diagnostics.push({
776
+ code: 'KIT-APP-017',
777
+ path: 'kit.app.yaml.style',
778
+ message: `禁止在 kit.app.yaml 中通过 style: "${config.style}" 引入野生样式表;样式必须由框架主题求解引擎统一生成`,
779
+ hint: '删除 kit.app.yaml#style,改用 kit.app.yaml#theme 14 维主题 DSL 声明配色、字阶、圆角与层次',
780
+ });
781
+ }
782
+ }
783
+
784
+ // 2 与代码登记对账(两边都要有;非实验室应用的 baseComponents 已由 KIT-APP-016 拒收,staticObjectComponents 照常对账)
785
+ if (internalLab) {
786
+ for (const name of Object.keys(config.baseComponents)) {
787
+ if (!(name in registry.baseComponents)) diagnostics.push({ code: 'KIT-APP-001', path: `baseComponents.${name}`, message: `kit.app.yaml 登记了基础组件 ${name},soma.app.ts 没有提供实现` });
788
+ }
757
789
  }
758
790
  // 只在代码里登记(kit.app.yaml#baseComponents 没有条目):不报错,按代码登记即可(不往配置对象里写东西)
759
791
  const staticContracts: Record<string, { accept: 'single' | 'list'; emits: readonly string[]; props: readonly string[]; propTypes: Readonly<Record<string, string>>; composition?: KitCompositionRole }> = {};
@@ -777,12 +809,12 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
777
809
  staticContracts[name] = { accept, emits: Object.keys(entry.definition.contract.emits ?? {}), props: Object.keys(entry.definition.contract.props ?? {}), propTypes: staticPropTypesOf(entry.definition), ...(role !== undefined ? { composition: role } : {}) };
778
810
  }
779
811
  }
780
- const sourceGateDiagnostics = await scanAppComponentSources(root);
812
+ const sourceGateDiagnostics = await scanAppComponentSources(root, { internalLab });
781
813
  diagnostics.push(...sourceGateDiagnostics);
782
814
 
783
- // 3 主题头(不在此处提前抛错,确保后面页面的编译诊断也能一次收集报全)
815
+ // 3 主题头(不在此处提前抛错,确保后面页面的编译诊断也能一次收集报全;非实验室应用禁止 kit.app.yaml#style,已报 KIT-APP-017)
784
816
  let themeCss = KIT_DEFAULT_THEME_CSS;
785
- if (config.style !== undefined) {
817
+ if (internalLab && config.style !== undefined) {
786
818
  const text = await readIfExists(path.resolve(root, config.style));
787
819
  if (text === undefined) {
788
820
  diagnostics.push({ code: 'KIT-APP-001', path: 'style', message: `找不到 ${config.style}` });
@@ -881,6 +913,7 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
881
913
  const componentDefinitions = {
882
914
  ...registry.baseComponents,
883
915
  ...Object.fromEntries(Object.entries(registry.staticComponents).map(([n, e]) => [n, e.definition])),
916
+ ...registry.bizDataComponents,
884
917
  ...registry.packDataComponents,
885
918
  };
886
919
  // 应用组件契约上的静态自报声明 → 页面线的补登表来源(逐组件校验、坏组件隔离告警);没有任何合法声明时不写这个键
package/src/biz/define.ts CHANGED
@@ -1,10 +1,17 @@
1
1
  // defineKitBizComponent:登记一个业务组件定义。只做形状自检,不做编译。
2
- // 业务组件的 kind 必须是 PascalCase;roles 至少一个必填角色;areas 不得重名。
2
+ // 业务组件的 kind 必须是 PascalCase;roles 至少一个必填角色;areas 不得重名;
3
+ // 可选携带私有协作数据组件(dataComponents)与 Tailwind 候选类(candidates)。
3
4
 
4
5
  import type { KitBizDefinition } from './types';
5
6
  import { kitFail } from '../shared/kit-error';
6
7
 
7
8
  const KIND = /^[A-Z][A-Za-z0-9]*$/;
9
+ const DEFINED_BIZ_COMPONENTS = new WeakSet<KitBizDefinition>();
10
+
11
+ /** 判定对象是否经 defineKitBizComponent(...) 合法构造(用于装配期 KIT-APP-019 校验) */
12
+ export function isDefinedKitBizComponent(def: unknown): def is KitBizDefinition {
13
+ return def !== null && typeof def === 'object' && DEFINED_BIZ_COMPONENTS.has(def as KitBizDefinition);
14
+ }
8
15
 
9
16
  export function defineKitBizComponent(def: KitBizDefinition): KitBizDefinition {
10
17
  if (!KIND.test(def.kind)) {
@@ -17,8 +24,30 @@ export function defineKitBizComponent(def: KitBizDefinition): KitBizDefinition {
17
24
  if (new Set(def.areas).size !== def.areas.length) {
18
25
  kitFail('KIT-COMP-002', `bizComponents.${def.kind}.areas`, `业务组件 ${def.kind} 的 areas 有重名`, 'areas 里每个区域名只写一次');
19
26
  }
27
+ if (def.dataComponents !== undefined) {
28
+ if (def.dataComponents === null || typeof def.dataComponents !== 'object' || Array.isArray(def.dataComponents)) {
29
+ kitFail('KIT-COMP-002', `bizComponents.${def.kind}.dataComponents`, `业务组件 ${def.kind} 的 dataComponents 必须是 { 组件名: 组件定义或工厂函数 } 对象`, '传入私有协作数据组件映射对象,或省略该字段');
30
+ }
31
+ for (const [compName, compVal] of Object.entries(def.dataComponents)) {
32
+ if (!KIND.test(compName)) {
33
+ kitFail('KIT-COMP-002', `bizComponents.${def.kind}.dataComponents.${compName}`, `业务组件 ${def.kind} 的私有协作组件名必须是 PascalCase,收到 "${compName}"`, '改成大写字母开头的驼峰名,如 AnnotationCanvasCore');
34
+ }
35
+ const validComp =
36
+ typeof compVal === 'function'
37
+ || (typeof compVal === 'object' && compVal !== null && (compVal as { contract?: unknown }).contract !== undefined);
38
+ if (!validComp) {
39
+ kitFail('KIT-COMP-002', `bizComponents.${def.kind}.dataComponents.${compName}`, `业务组件 ${def.kind} 的私有协作组件 "${compName}" 必须是组件定义(含 contract)或返回它的函数`, '传入 defineComponent(...) 返回值或 () => defineComponent(...) 工厂函数');
40
+ }
41
+ }
42
+ }
43
+ if (def.candidates !== undefined) {
44
+ if (!Array.isArray(def.candidates) || !def.candidates.every((c) => typeof c === 'string')) {
45
+ kitFail('KIT-COMP-002', `bizComponents.${def.kind}.candidates`, `业务组件 ${def.kind} 的 candidates 必须是字符串数组`, '传入 Tailwind 候选类字符串数组,如 ["flex", "gap-section"]');
46
+ }
47
+ }
20
48
  if (typeof def.compile !== 'function') {
21
49
  kitFail('KIT-COMP-002', `bizComponents.${def.kind}.compile`, `业务组件 ${def.kind} 缺 compile()`, '提供 compile(input, ctx) 返回片段');
22
50
  }
51
+ DEFINED_BIZ_COMPONENTS.add(def);
23
52
  return def;
24
53
  }
@@ -10,10 +10,10 @@ import { KIT_SIZE_SPEC } from 'soma-foundation/kit-limits';
10
10
  import { KIT_TIPS_SCOPE_ATTR } from '../../base/hint-tips';
11
11
  import { kitFixedPaneClass, kitListPaneClass, type KitListLayout } from '../../recipes/page-width';
12
12
  import { mergeClass } from '../../shared/merge-class';
13
- import { KIT_FACE_HEAD_CLASS, KIT_MS_ASIDE_IDLE_ATTR, KIT_MS_BACK_ATTR, KIT_MS_ROOT_ATTR, KIT_MS_VIEW_LIST_ATTR, KIT_SHELL_FLAT_MARK, kitShellRecipe } from '../../recipes/container';
13
+ import { KIT_FACE_HEAD_CLASS, KIT_MS_ASIDE_IDLE_ATTR, KIT_MS_BACK_ATTR, KIT_MS_ROOT_ATTR, KIT_MS_VIEW_LIST_ATTR, KIT_SHELL_FLAT_MARK } from '../../recipes/container';
14
14
  import { KIT_STATE_DESC_CLASS, KIT_STATE_EMPTY_BOX } from '../../recipes/placeholder';
15
15
  import { KIT_STRIP_HEAD_CLASS, KIT_STRIP_HEAD_MIN_CLASS } from '../../recipes/strip';
16
- import { KIT_DIVIDER_HEAD_CLASS, kitDividerVariantRecipe } from '../../recipes/divider';
16
+ import { KIT_DIVIDER_HEAD_CLASS, kitDividerRecipe, kitDividerVariantRecipe } from '../../recipes/divider';
17
17
  import { kitSurfaceRecipe } from '../../recipes/surface';
18
18
  import { kitTypographyRecipe } from '../../recipes/typography';
19
19
  import { kitActionRecipe } from '../../recipes/emphasis';
@@ -36,9 +36,6 @@ import type { KitStripProjection } from '../../object-renderer/action-group';
36
36
  export const MASTER_SUB_AREAS = ['root', 'masterList', 'masterSummary', 'subWorkspace', 'subBlock', 'aside', 'dialog'] as const;
37
37
  export type MasterSubArea = (typeof MASTER_SUB_AREAS)[number];
38
38
 
39
- /** 卡片外观(圆角 + 容器边界色 + 凸起底 + 浅阴影):一份配方,三栏与区块同源,随九维边界维度变化 */
40
- const CARD = kitShellRecipe();
41
-
42
39
  /** 左窗格定档的输入(编译期由主列表的条目样本 / 表格列轨推出,见 compile.ts 的 paneSampleOf) */
43
40
  export type MasterPaneSample = Omit<ArrangePaneWidthInput, 'withAside'>;
44
41
 
@@ -75,7 +72,7 @@ export function masterSubSplit(sample: MasterPaneSample, withAside: boolean, lay
75
72
  row: 'flex-row flex-wrap',
76
73
  left: 'w-full group-data-kit-ms-detail/ms:hidden',
77
74
  right: 'flex-1 group-data-kit-ms-list/ms:hidden',
78
- aside: 'w-full group-data-kit-ms-list/ms:hidden',
75
+ aside: ['w-full group-data-kit-ms-list/ms:hidden', kitDividerRecipe('top')].join(' '),
79
76
  tier: null,
80
77
  px: plan.px,
81
78
  fits: plan.fits,
@@ -92,7 +89,7 @@ export function masterSubSplit(sample: MasterPaneSample, withAside: boolean, lay
92
89
  row: ['flex-row flex-wrap', `@${TA}:flex-nowrap`, kitDividerVariantRecipe('end', `@${T}:*:first`)].join(' '),
93
90
  left: `${kitListPaneClass(plan.px, T)} @max-${T}:w-full @max-${T}:group-data-kit-ms-detail/ms:hidden`,
94
91
  right: `flex-1 @max-${T}:group-data-kit-ms-list/ms:hidden`,
95
- aside: `${kitFixedPaneClass(M.pane.sideRailPx, TA)} @max-${TA}:w-full @max-${T}:group-data-kit-ms-list/ms:hidden`,
92
+ aside: [kitFixedPaneClass(M.pane.sideRailPx, TA), `@max-${TA}:w-full`, `@max-${T}:group-data-kit-ms-list/ms:hidden`, kitDividerVariantRecipe('start', `@${TA}`), kitDividerVariantRecipe('top', `@max-${TA}`)].join(' '),
96
93
  tier: T,
97
94
  px: plan.px,
98
95
  fits: plan.fits,
@@ -145,7 +142,7 @@ export const MASTER_SUB_CLASS = {
145
142
  emptyBox: mergeClass(KIT_STATE_EMPTY_BOX, 'flex-1 flex-col items-center justify-center min-h-60 py-12 text-center gap-cluster px-card'),
146
143
  emptyText: KIT_STATE_DESC_CLASS,
147
144
  // self-start:辅助栏(结果 / 说明)按内容定高,不拉成与最高一栏等高的一整列空白卡
148
- asideBase: mergeClass('self-start flex min-w-0 flex-col gap-section p-card group-data-kit-aside-idle/ms:hidden', CARD),
145
+ asideBase: 'self-start flex min-w-0 flex-col gap-section p-card group-data-kit-aside-idle/ms:hidden',
149
146
  } as const;
150
147
 
151
148
  /** 「返回」钮:文字钮(三级强调)+ 左箭头图标,与其它窗格头动作同一套控件配方 */
@@ -320,7 +317,7 @@ export function masterSubHtml(
320
317
  const aside = !withAside ? ''
321
318
  : nx !== undefined
322
319
  ? `<aside data-soma-id="${esc(kitObjectAnchor(nx.aside))}"${cls(kitNeutralClass(mergeClass(`${S.aside} ${MASTER_SUB_CLASS.asideBase}`, areaClass.aside)))}>${parts.aside}</aside>`
323
- : `<aside ${KIT_ATTR_CONTAINER}="card"${cls(mergeClass(`${S.aside} ${MASTER_SUB_CLASS.asideBase}`, areaClass.aside))}${FLAT}>${parts.aside}</aside>`;
320
+ : `<aside ${KIT_ATTR_CONTAINER}="plain"${cls(mergeClass(`${S.aside} ${MASTER_SUB_CLASS.asideBase}`, areaClass.aside))}${FLAT}>${parts.aside}</aside>`;
324
321
  const root = mergeClass(mergeClass(MASTER_SUB_CLASS.root, areaClass.root), extra);
325
322
  const msAttrs = ` ${KIT_MS_ROOT_ATTR}="" ${KIT_MS_VIEW_LIST_ATTR}=""${withAside && parts.asideIdleInit === true ? ` ${KIT_MS_ASIDE_IDLE_ATTR}=""` : ''}${nx !== undefined ? insetNone : ''}`;
326
323
  // 新模式:分窗格的那张面是业务组件节点自己(层级角色由布局写到根锚点 __ms_root 上),分栏行只留结构类(面框、窗格中缝由取值表给)
@@ -148,7 +148,28 @@ export function splitTitleRow(html: string): [string, string] {
148
148
  return ['', html];
149
149
  }
150
150
 
151
- export function filterToolbarRow(filter: string, toolbar: string, inlineMeta?: string | null): string {
151
+ /**
152
+ * 判定工具栏片段最外层动作组宿主(带 data-kit-action-group)自身是否声明为容器查询宿主(@container):
153
+ * 只检查最外层动作组开标签的 class 词元,避免工具栏内部任意子元素带 @container 时被误判成查询容器工具列。
154
+ */
155
+ function isQueryActionGroupHost(toolbar: string): boolean {
156
+ const attrAt = toolbar.indexOf(`${KIT_ATTR_ACTION_GROUP}=`);
157
+ if (attrAt < 0) return false;
158
+ const open = toolbar.lastIndexOf('<div', attrAt);
159
+ const close = toolbar.indexOf('>', attrAt);
160
+ if (open < 0 || close < 0 || toolbar.indexOf('>', open) !== close) return false;
161
+ const openTag = toolbar.slice(open, close + 1);
162
+ const clsMatch = /\bclass="([^"]*)"/.exec(openTag);
163
+ if (clsMatch === null) return false;
164
+ return clsMatch[1]!.split(/\s+/).includes('@container');
165
+ }
166
+
167
+ export function filterToolbarRow(
168
+ filter: string,
169
+ toolbar: string,
170
+ inlineMeta?: string | null,
171
+ options?: { readonly queryToolbar?: boolean },
172
+ ): string {
152
173
  const C = KIT_FILTER_TOOLBAR_CLASS;
153
174
  // 标签占位(与「标签在上」的筛选表单的控件行对齐)只在筛选带标签时才要;工具条式筛选没有标签行,占位会把主操作压低半行
154
175
  const pad = filter.includes(KIT_FILTER_TOOLBAR_MARK) ? '' : `<span class="${C.pad}" aria-hidden="true">&nbsp;</span>`;
@@ -159,7 +180,8 @@ export function filterToolbarRow(filter: string, toolbar: string, inlineMeta?: s
159
180
  const filterBody = inlineMeta !== undefined && inlineMeta !== null && inlineMeta !== ''
160
181
  ? wrapFilterWithInlineMeta(filter, inlineMeta)
161
182
  : filter;
162
- const toolsClass = toolbar.includes('@container') ? C.toolsQuery : C.tools;
183
+ const isQuery = options?.queryToolbar ?? isQueryActionGroupHost(toolbar);
184
+ const toolsClass = isQuery ? C.toolsQuery : C.tools;
163
185
  return `<div class="${row}"><div class="${C.filter}">${filterBody}</div>`
164
186
  + `<div class="${toolsClass}">${pad}${toolbar}</div></div>`;
165
187
  }
package/src/biz/types.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  // 它不是组件层:编译器按 `product.kind` 查 `KIT_BIZ_COMPONENTS`,把页面传入的各对象交给 `compile`,
5
5
  // 得到一个 KitFragment(HTML + `_ui.yaml` 片段 + `_event.yaml` 片段 + 候选类 + 诊断),再交页面框装入。
6
6
 
7
+ import type { SomaComponentDefinition } from 'soma-core';
7
8
  import type { ArrangePageEnvelopeSurfaceKind, ArrangePageEnvelopeTier } from 'soma-foundation/arrange';
8
9
  import type { KitObject } from '../object-renderer/types';
9
10
  import type { KitListLayout } from '../recipes/page-width';
@@ -141,5 +142,12 @@ export interface KitBizDefinition {
141
142
  * 页面模式推导的版心(兼容自定义业务组件旧口;内置组件优先使用声明式 envelope 特征)。
142
143
  */
143
144
  pageMaxWidth?: string;
145
+ /**
146
+ * 业务组件私有的协作数据组件(浏览器运行期交互内核,如批注画布、泳道图等):
147
+ * 装配时自动实例化并并入浏览器组件表,但**不**暴露到页面 `*.kit.yaml` 的 `staticComponent` 选用表中。
148
+ */
149
+ dataComponents?: Readonly<Record<string, SomaComponentDefinition | (() => SomaComponentDefinition)>>;
150
+ /** 业务组件及其私有协作数据组件用到的 Tailwind 候选类(装配时自动合并入应用候选类) */
151
+ candidates?: readonly string[];
144
152
  compile(input: KitBizInput, ctx: KitBizContext): KitFragment;
145
153
  }
@@ -1,6 +1,6 @@
1
1
  // 生成物,不得改写:由 soma-kit/scripts/build-kit-grammar-runtime.mjs 从 spec/kit-grammar.json 抽出。
2
2
  // 浏览器侧只读这份运行期切片(闭集与限值);编译侧读完整真源。改真源后运行 `npm run grammar:runtime -w soma-kit` 重新生成。
3
- // 真源指纹 sha256:6793a8321f898a266dccf5a2a8b9987d2024bd27cccf1e34c36c8ba36c9d4b11
3
+ // 真源指纹 sha256:90ec5184ad50b6f7883453fb235c402ad194efe51506c441b2b61a0f95f0d52d
4
4
 
5
5
  export const KIT_GRAMMAR_RUNTIME = {
6
6
  "i18n": {
@@ -510,6 +510,10 @@ export const KIT_GRAMMAR_RUNTIME = {
510
510
  "KIT-APP-013": "应用代码直接 import \"soma-core\" 或 \"soma-core/*\"(含 import type、export … from、动态 import、require);应用唯一的接触面是 soma-kit/app(tests/ 与 test/ 目录豁免)",
511
511
  "KIT-APP-014": "应用组件的 controllerFactory 必须由 createKitController((api) => ({ ... })) 生成(不接受纯声明式无控制器组件或手写工厂)",
512
512
  "KIT-APP-015": "应用违反双平面与四层分层边界(R-APP-1/2/3):客户端面(web/、soma.app.ts、views/、actions/、components/)静态引用了服务端面(bff/、api/、config/、soma.server.*),或服务端面反向引用客户端面,或 shared/ 引用了端侧或 Node 内置模块,或 BFF 下层(foundation/、domain/)反向引用上层,或页面视图 views/*.view.ts 之间横向互引",
513
+ "KIT-APP-016": "业务应用禁止注册非业务/非数据的野生 baseComponents(基础控件一律复用官方闭集);外部界面扩展仅开放两档:① 业务组件 bizComponents(静态画布 + 按 DSL 装配,可自带私有 dataComponents);② 纯数据驱动自定义数据组件 staticObjectComponents(一份数据一个组件、数据进事件出,供业务组件 DSL 槽位按名选用)",
514
+ "KIT-APP-017": "禁止野生样式表与野生页面 HTML:应用目录不得出现 .css / .scss / .less / .sass / .styl 文件或在源码中 import / export / require 样式表,kit.app.yaml 不得配置 style: 外链样式,且 pages/、src/web/、views/、components/ 下不得手写 .html / .htm;样式外观统一走 kit.app.yaml#theme 14 维 DSL 与 Tailwind 刻度类",
515
+ "KIT-APP-018": "禁止命令式浮层、非组件 DOM 构造与伪造框架内部符号:全应用禁止调用 .showModal() / .showPopover() / createElement('dialog') / document.body.append* 及引用或伪造 Symbol.for('soma-kit.*');components/ 之外的源码禁止调用 createElement / createElementNS / insertAdjacentHTML 或写入 innerHTML / outerHTML",
516
+ "KIT-APP-019": "自定义业务组件或其私有协作组件违反纯声明式装数据契约:业务组件未经 defineKitBizComponent 构造、组件源码内手写 <table> / <thead> / <form> / <dialog> 或直接调用 fetch() / new XMLHttpRequest,或业务组件源码硬编码 '/api/...' 接口路径(必须从页面 input.objects 的 behavior.from 与具名动作读取)",
513
517
  "KIT-COMP-002": "业务组件定义非法:名字不是 PascalCase、没有必填角色槽、areas 重名、缺 compile(),或 composeKitBizComponents 的子部件 / 角色映射不成立",
514
518
  "KIT-COMP-003": "组件候选类 / rootClass / slotClass 含非法 Tailwind 类(不在刻度内或带方括号任意值)",
515
519
  "KIT-COMP-004": "数据组件定义 / 包装 / 登记非法:缺 define()、accept 不是 single / list、被包装组件无控制器、登记名与契约名不一致、layer 不是 data、事件名不是 snake_case,或 composeKitDataComponents 没有子部件",
@@ -2249,7 +2253,7 @@ export const KIT_GRAMMAR_RUNTIME = {
2249
2253
  "cardsList": "grid gap-4",
2250
2254
  "cardsItem": "rounded-card border-edge border-border-container bg-surface p-card transition-shadow hover:shadow-sm",
2251
2255
  "stackList": "flex flex-col gap-4",
2252
- "stackItem": "rounded-card border-edge border-border-container bg-surface p-3 shadow-xs",
2256
+ "stackItem": "rounded-card border-edge border-border-container bg-surface p-3",
2253
2257
  "compactList": "@container flex flex-col",
2254
2258
  "compactItem": "inset-row flex flex-wrap items-center gap-x-3 gap-y-1 px-3 in-data-kit-axis:px-card py-2 border-b-hairline border-border-subtle last:border-b-0 text-sm text-fg transition-colors hover:bg-state-layer-row-hover active:bg-state-layer-press data-kit-selected:bg-state-layer-selected data-kit-selected:sel-bar data-kit-selected:hover:bg-state-layer-tonal-hover data-kit-fresh:bg-primary-soft",
2255
2259
  "compactBody": "flex min-w-40 flex-1 flex-col gap-0.5",
@@ -512,10 +512,9 @@ export function createKitTableActions(): SomaComponentDefinition {
512
512
  let renderedEcho = '';
513
513
  // 最近一次渲染时动作数组的权限判定签名(权限异步到达 / 收回 / 切换判定器时仅在结果变化时重绘)
514
514
  let renderedPerm = '';
515
- const permStateOf = (p: KitProps): string => {
515
+ const permStateOf = (p: KitProps, check = permissionCheckerOf(api as unknown as any)): string => {
516
516
  const items = itemsOf(p.actions);
517
517
  if (!items.some((item) => item.permission !== undefined)) return '';
518
- const check = permissionCheckerOf(api as unknown as any);
519
518
  return items.map((item) => (item.permission !== undefined && check !== null ? (check(item.permission) ? '1' : '0') : '-')).join('');
520
519
  };
521
520
  // 在途期间按钮被禁用会丢焦点:记下用户点的是哪个控件,落定恢复后还给它(仅当焦点已落到 body)
@@ -670,7 +669,7 @@ export function createKitTableActions(): SomaComponentDefinition {
670
669
  const check = permissionCheckerOf(api as unknown as any);
671
670
  const busy = removeBusyOf(p);
672
671
  renderedBusy = busy;
673
- renderedPerm = permStateOf(p);
672
+ renderedPerm = permStateOf(p, check);
674
673
  // 保存回声:所在行容器打 / 摘 data-kit-fresh(行类的 data-kit-fresh 变体画底色,摘掉时 transition-colors 淡出);
675
674
  // 常规行里正被置顶的那条记录隐去(置顶行容器里的副本不隐),不出现两份。只改行容器属性、不动本组件内容,放在签名跳过之前
676
675
  const echo = rowEchoState(p, root);
@@ -704,8 +703,7 @@ export function createKitTableActions(): SomaComponentDefinition {
704
703
  const selState = Array.isArray(p.selected) ? (p.selected.some((r) => rowKeyOf(r, keyF) === rowKeyOf(p.row, keyF)) ? 1 : 0) : -1;
705
704
  const pickedRows = selectedRowsOf(p.picked);
706
705
  const pickState = pickedRows === null ? -1 : (pickedRows.some((r) => rowKeyOf(r, keyF) === rowKeyOf(p.row, keyF)) ? 1 : 0);
707
- const perms = itemsOf(p.actions).map((item) => (item.permission !== undefined && check !== null ? (check(item.permission) ? 1 : 0) : -1));
708
- return JSON.stringify([rest, selState, pickState, perms]) + (busy ? '|busy' : '') + (locked ? '|lock' : '');
706
+ return JSON.stringify([rest, selState, pickState, renderedPerm]) + (busy ? '|busy' : '') + (locked ? '|lock' : '');
709
707
  } catch {
710
708
  return null; // 含环等不可序列化:不跳过
711
709
  }