soma-kit 0.1.18 → 0.1.19

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 (53) hide show
  1. package/package.json +1 -1
  2. package/spec/generated/kit-page.schema.json +11 -1
  3. package/spec/kit-grammar.json +133 -13
  4. package/spec/kit-grammar.schema.json +4 -0
  5. package/src/app/component-gate.ts +247 -16
  6. package/src/app/index.ts +4 -1
  7. package/src/app/kit-view-context.ts +44 -2
  8. package/src/app/server.ts +11 -2
  9. package/src/biz/compose.ts +66 -0
  10. package/src/biz/define.ts +8 -0
  11. package/src/biz/index.ts +1 -0
  12. package/src/biz/layout-contracts.ts +119 -4
  13. package/src/biz/link/hub.ts +31 -0
  14. package/src/biz/master-sub/compile.ts +45 -3
  15. package/src/biz/master-sub/index.ts +3 -1
  16. package/src/biz/record-detail/compile.ts +120 -10
  17. package/src/biz/shared/coordinator.ts +245 -48
  18. package/src/biz/shared/index.ts +5 -1
  19. package/src/biz/shared/object-aliases.ts +14 -3
  20. package/src/biz/shared/overlay-compile.ts +56 -5
  21. package/src/biz/shared/overlay-shell.ts +5 -2
  22. package/src/biz/shared/page-form.ts +9 -5
  23. package/src/biz/shared/page-overlay-host.ts +126 -0
  24. package/src/biz/shared/page-overlay-names.ts +27 -0
  25. package/src/biz/shared/runtime-hub.ts +37 -2
  26. package/src/biz/single-form/compile.ts +60 -5
  27. package/src/biz/single-form/index.ts +2 -1
  28. package/src/biz/standard-crud/compile.ts +9 -2
  29. package/src/biz/types.ts +18 -0
  30. package/src/cli/kit-cli.ts +1 -0
  31. package/src/cli/view-writes.ts +130 -3
  32. package/src/compile/compile-page.ts +49 -4
  33. package/src/compile/page-pipeline.ts +4 -0
  34. package/src/compile/parse.ts +14 -0
  35. package/src/compile/stages.ts +5 -4
  36. package/src/compile/types.ts +1 -1
  37. package/src/compile/view-check.ts +49 -17
  38. package/src/data/comment-thread.ts +78 -18
  39. package/src/data/navbar.ts +4 -0
  40. package/src/data/object-form.ts +17 -3
  41. package/src/data/prompt-dialog.ts +102 -15
  42. package/src/frames/page-header.ts +11 -2
  43. package/src/frames/shared.ts +6 -0
  44. package/src/frames/types.ts +2 -0
  45. package/src/generated/kit-grammar-runtime.ts +43 -5
  46. package/src/i18n/kit-text.ts +1 -0
  47. package/src/object-renderer/request-actions.ts +145 -17
  48. package/src/object-renderer/types.ts +7 -0
  49. package/src/shared/dom-attrs-registry.ts +5 -3
  50. package/src/shared/dom-attrs.ts +2 -0
  51. package/src/spatial/declared-actions.ts +6 -3
  52. package/src/spatial/emit.ts +1 -1
  53. package/src/spatial/expand.ts +7 -2
@@ -153,12 +153,12 @@ const FORBIDDEN_IMPERATIVE_OVERLAY_PATTERNS: readonly ForbiddenRule[] = [
153
153
  {
154
154
  id: 'show-modal',
155
155
  pattern: /\.\s*showModal\s*\(/,
156
- message: '禁止调用 showModal() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer)或框架浮层端口',
156
+ message: '禁止调用 showModal() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer),由 ctx.openOverlay / builtin: openOverlay 打开',
157
157
  },
158
158
  {
159
159
  id: 'show-popover',
160
160
  pattern: /\.\s*showPopover\s*\(/,
161
- message: '禁止调用 showPopover() 打开命令式原生浮层;请改用页面声明 overlays 或框架浮层端口',
161
+ message: '禁止调用 showPopover() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer),由 ctx.openOverlay / builtin: openOverlay 打开',
162
162
  },
163
163
  {
164
164
  id: 'create-dialog',
@@ -168,10 +168,28 @@ const FORBIDDEN_IMPERATIVE_OVERLAY_PATTERNS: readonly ForbiddenRule[] = [
168
168
  {
169
169
  id: 'body-append-portal',
170
170
  pattern: /\bdocument\s*\.\s*body\s*\.\s*(?:appendChild|append|prepend|insertAdjacentHTML|insertAdjacentElement)\s*\(/,
171
- message: '禁止向 document.body 命令式挂载浮层或野生 DOM 节点;浮层必须通过页面 overlays 或框架浮层端口托管',
171
+ message: '禁止向 document.body 命令式挂载浮层或野生 DOM 节点;浮层必须通过页面 overlays 声明托管',
172
172
  },
173
173
  ];
174
174
 
175
+ /**
176
+ * 框架内部的命令式浮层原语(soma-kit/data 导出;框架内 ctx.confirm / ctx.prompt / 记录选择器在用):
177
+ * 应用源码导入或调用报 KIT-APP-020(0.1.19 过渡期告警,进 deprecations;0.2.0 并入 KIT-APP-018)
178
+ */
179
+ const KIT_IMPERATIVE_OVERLAY_PORTS: ReadonlySet<string> = new Set(['mountKitModal', 'mountKitDrawer']);
180
+ /** 命令式浮层原语所在模块(主导出在 soma-kit/data;soma-kit 根入口 src/index.ts 当前未再导出,保留作历史/别名兜底) */
181
+ const KIT_PORT_MODULES: ReadonlySet<string> = new Set(['soma-kit/data', 'soma-kit']);
182
+ const MSG_IMPERATIVE_PORT = '应用代码不再命令式开窗(mountKitModal / mountKitDrawer 是框架内部原语):窗口在页面 overlays(或 page.overlays)声明,由展示对象 ctx.openOverlay / ctx.closeOverlay 开关,简单确认与输入用 ctx.confirm / ctx.prompt';
183
+ const HINT_IMPERATIVE_PORT = '把窗口内容写成浮层的 view(表单用 view.form,草稿要保留写 draft: keep;异形内容用数据组件 view.summary.staticComponent),开窗改为 builtin: openOverlay 或 ctx.openOverlay(名)';
184
+
185
+ /** KIT-APP-019 的 fetch 允许去处(相对应用根),提示语与 hint 共用 */
186
+ const IO_DIRS_TEXT = 'api/ bff/ actions/ server/ src/bff/ src/web/actions/ soma.server.*,或 defineKitActions / requestHook / startup / services 内';
187
+ const MSG_NON_IO_FETCH = `非 IO 目录禁止直接调用 fetch() 绕过数据与动作管道(允许目录:${IO_DIRS_TEXT})`;
188
+ const MSG_NON_IO_XHR = `非 IO 目录禁止使用 new XMLHttpRequest 绕过数据与动作管道(允许目录:${IO_DIRS_TEXT})`;
189
+ const HINT_NON_IO_NET = '数据读取走页面 behavior.from,写操作走 defineKitActions 具名动作;浏览器侧传输封装与 SSE 读取器放 actions/(如 actions/transport/)';
190
+ const MSG_VIEW_FETCH = '展示对象目录(views/)直接调用 fetch() / new XMLHttpRequest 绕过了 ctx.http 只读面与 ctx.request 写通道(过渡期告警,0.2.0 并入 KIT-APP-019)';
191
+ const HINT_VIEW_FETCH = '读用 ctx.http.get,写用 ctx.request(对象, 动作 id, 载荷) 或具名动作;传输封装放 actions/(如 actions/transport/)';
192
+
175
193
  const FORBIDDEN_STRUCTURED_OR_NET_PATTERNS: readonly ForbiddenRule[] = [
176
194
  {
177
195
  id: 'raw-table-tag',
@@ -191,7 +209,7 @@ const FORBIDDEN_STRUCTURED_OR_NET_PATTERNS: readonly ForbiddenRule[] = [
191
209
  {
192
210
  id: 'raw-dialog-tag',
193
211
  pattern: /<\s*dialog(?=[\s>/])/i,
194
- message: '禁止在自定义组件中手写 <dialog> 浮层;请改用页面声明 overlays(dialog / drawer)或框架浮层端口',
212
+ message: '禁止在自定义组件中手写 <dialog> 浮层;请改用页面声明 overlays(dialog / drawer),由 ctx.openOverlay / builtin: openOverlay 打开',
195
213
  },
196
214
  {
197
215
  id: 'raw-fetch-call',
@@ -268,12 +286,12 @@ export function assertSinglePathComponent(
268
286
  if (opts?.strictBizOnly !== false) {
269
287
  const tplOverlayHits = typeof def.templateHtml === 'string' ? findRuleHits(def.templateHtml, FORBIDDEN_IMPERATIVE_OVERLAY_PATTERNS) : [];
270
288
  if (tplOverlayHits.length > 0) {
271
- kitFail('KIT-APP-018', `components.${name}.templateHtml`, `应用组件 ${name} 的 templateHtml 违规:${tplOverlayHits[0]!.message}`, '浮层改由页面 *.kit.yaml 的 overlays 声明或框架浮层端口托管');
289
+ kitFail('KIT-APP-018', `components.${name}.templateHtml`, `应用组件 ${name} 的 templateHtml 违规:${tplOverlayHits[0]!.message}`, '浮层改由页面 *.kit.yaml 的 overlays(或 page.overlays)声明');
272
290
  }
273
291
  if (ctrlSrc !== '') {
274
292
  const ctrlOverlayHits = findRuleHits(ctrlSrc, FORBIDDEN_IMPERATIVE_OVERLAY_PATTERNS);
275
293
  if (ctrlOverlayHits.length > 0) {
276
- kitFail('KIT-APP-018', `components.${name}.controller`, `应用组件 ${name} 的控制器违规:${ctrlOverlayHits[0]!.message}`, '浮层改由页面 *.kit.yaml 的 overlays 声明或框架浮层端口托管');
294
+ kitFail('KIT-APP-018', `components.${name}.controller`, `应用组件 ${name} 的控制器违规:${ctrlOverlayHits[0]!.message}`, '浮层改由页面 *.kit.yaml 的 overlays(或 page.overlays)声明');
277
295
  }
278
296
  }
279
297
  const tplStructHits = typeof def.templateHtml === 'string' ? findRuleHits(def.templateHtml, FORBIDDEN_STRUCTURED_OR_NET_PATTERNS) : [];
@@ -370,7 +388,7 @@ const HTML_STRUCTURE_FORBIDDEN_RULES: readonly ForbiddenRule[] = [
370
388
  {
371
389
  id: 'raw-dialog-tag',
372
390
  pattern: /<\s*dialog(?=[\s>/])/i,
373
- message: '禁止在自定义组件中手写 <dialog> 浮层;请改用页面声明 overlays(dialog / drawer)或框架浮层端口',
391
+ message: '禁止在自定义组件中手写 <dialog> 浮层;请改用页面声明 overlays(dialog / drawer),由 ctx.openOverlay / builtin: openOverlay 打开',
374
392
  },
375
393
  ];
376
394
 
@@ -415,6 +433,49 @@ function propertyAccessName(ts: TsModule, node: import('typescript').Expression)
415
433
  return undefined;
416
434
  }
417
435
 
436
+ function unwrapExpr(ts: TsModule, expr: import('typescript').Expression): import('typescript').Expression {
437
+ let cur = expr;
438
+ while (true) {
439
+ if (
440
+ ts.isParenthesizedExpression(cur)
441
+ || ts.isAsExpression(cur)
442
+ || ts.isTypeAssertionExpression(cur)
443
+ || ts.isNonNullExpression(cur)
444
+ || (typeof ts.isSatisfiesExpression === 'function' && ts.isSatisfiesExpression(cur))
445
+ ) {
446
+ cur = cur.expression;
447
+ continue;
448
+ }
449
+ break;
450
+ }
451
+ return cur;
452
+ }
453
+
454
+ function propertyNameText(ts: TsModule, name: import('typescript').PropertyName): string | undefined {
455
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return name.text;
456
+ if (ts.isComputedPropertyName(name) && ts.isStringLiteralLike(name.expression)) return name.expression.text;
457
+ return undefined;
458
+ }
459
+
460
+ function bindingElementPropName(ts: TsModule, el: import('typescript').BindingElement): string | undefined {
461
+ if (el.propertyName !== undefined) return propertyNameText(ts, el.propertyName);
462
+ return ts.isIdentifier(el.name) ? el.name.text : undefined;
463
+ }
464
+
465
+ function isPortModuleLoad(ts: TsModule, expr: import('typescript').Expression, allowAwait: boolean): boolean {
466
+ let cur = unwrapExpr(ts, expr);
467
+ if (allowAwait && ts.isAwaitExpression(cur)) {
468
+ cur = unwrapExpr(ts, cur.expression);
469
+ }
470
+ if (!ts.isCallExpression(cur) || cur.arguments.length < 1 || !ts.isStringLiteralLike(cur.arguments[0])) {
471
+ return false;
472
+ }
473
+ const spec = cur.arguments[0].text;
474
+ if (!KIT_PORT_MODULES.has(spec)) return false;
475
+ return cur.expression.kind === ts.SyntaxKind.ImportKeyword
476
+ || (ts.isIdentifier(cur.expression) && cur.expression.text === 'require');
477
+ }
478
+
418
479
  function isDocumentBodyExpr(ts: TsModule, node: import('typescript').Expression): boolean {
419
480
  if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isTypeAssertionExpression(node)) {
420
481
  return isDocumentBodyExpr(ts, node.expression);
@@ -480,6 +541,11 @@ interface AstScanFlags {
480
541
  readonly inComponentsDir: boolean;
481
542
  readonly isNonCompAllowedIoDir: boolean;
482
543
  readonly internalLab: boolean;
544
+ /**
545
+ * 展示对象目录(views/、src/web/views/):直接 fetch / XMLHttpRequest 报 KIT-APP-021(过渡期告警)而不是放行。
546
+ * 其余检查仍按 IO 目录口径(结构标签检查不扩到 views/,本版不把现有通过的写法变成错误)
547
+ */
548
+ readonly isViewDir?: boolean;
483
549
  /** 仅 internalLab 时用于区分 *.css.ts 模块导入与真实 .css 样式表导入 */
484
550
  readonly isInternalTsModuleSpecifier?: (spec: string) => boolean;
485
551
  }
@@ -491,9 +557,106 @@ function scanSourceWithAst(
491
557
  flags: AstScanFlags,
492
558
  ): AstScanHit[] {
493
559
  const { inComponentsDir, isNonCompAllowedIoDir, internalLab, isInternalTsModuleSpecifier } = flags;
560
+ const isViewDir = !internalLab && flags.isViewDir === true;
494
561
  const sourceFile = ts.createSourceFile(fullPath, code, ts.ScriptTarget.Latest, true, scriptKindForFile(ts, fullPath));
495
562
  const hasBizComponentDef = !internalLab && fileDefinesBizComponent(ts, sourceFile);
496
563
  const checkComponentPurity = !internalLab && !isNonCompAllowedIoDir;
564
+ // KIT-APP-020:本文件从 soma-kit/data(或 soma-kit)导入/加载的命令式浮层原语的本地名(含 as 改名、解构重命名、require/动态 import)与命名空间名;
565
+ // 调用与属性访问判定只认这些名字,不误伤应用里自己写的同名函数
566
+ const localPortNames = new Set<string>();
567
+ const portNamespaces = new Set<string>();
568
+ const isPortNamespaceExpr = (expr: import('typescript').Expression): boolean => {
569
+ const e = unwrapExpr(ts, expr);
570
+ return isPortModuleLoad(ts, e, true) || (ts.isIdentifier(e) && portNamespaces.has(e.text));
571
+ };
572
+ const isPortMemberAccess = (expr: import('typescript').Expression): boolean => {
573
+ const e = unwrapExpr(ts, expr);
574
+ if (!(ts.isPropertyAccessExpression(e) || ts.isElementAccessExpression(e))) return false;
575
+ const prop = propertyAccessName(ts, e);
576
+ return prop !== undefined && KIT_IMPERATIVE_OVERLAY_PORTS.has(prop) && isPortNamespaceExpr(e.expression);
577
+ };
578
+ const collectBindingPatternPorts = (pattern: import('typescript').ObjectBindingPattern): void => {
579
+ for (const el of pattern.elements) {
580
+ const prop = bindingElementPropName(ts, el);
581
+ if (prop !== undefined && KIT_IMPERATIVE_OVERLAY_PORTS.has(prop) && ts.isIdentifier(el.name)) {
582
+ localPortNames.add(el.name.text);
583
+ }
584
+ }
585
+ };
586
+ const collectObjectLiteralAssignPorts = (objLit: import('typescript').ObjectLiteralExpression): void => {
587
+ for (const prop of objLit.properties) {
588
+ if (ts.isShorthandPropertyAssignment(prop)) {
589
+ if (KIT_IMPERATIVE_OVERLAY_PORTS.has(prop.name.text)) localPortNames.add(prop.name.text);
590
+ } else if (ts.isPropertyAssignment(prop)) {
591
+ const key = propertyNameText(ts, prop.name);
592
+ if (key !== undefined && KIT_IMPERATIVE_OVERLAY_PORTS.has(key)) {
593
+ const target = unwrapExpr(ts, prop.initializer);
594
+ if (ts.isIdentifier(target)) localPortNames.add(target.text);
595
+ }
596
+ }
597
+ }
598
+ };
599
+ if (!internalLab) {
600
+ const collectPortBindings = (node: import('typescript').Node): void => {
601
+ if (ts.isTypeNode(node) || ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) return;
602
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && KIT_PORT_MODULES.has(node.moduleSpecifier.text)) {
603
+ const named = node.importClause?.namedBindings;
604
+ if (named !== undefined) {
605
+ if (ts.isNamespaceImport(named)) {
606
+ portNamespaces.add(named.name.text);
607
+ } else {
608
+ for (const el of named.elements) {
609
+ if (KIT_IMPERATIVE_OVERLAY_PORTS.has((el.propertyName ?? el.name).text)) localPortNames.add(el.name.text);
610
+ }
611
+ }
612
+ }
613
+ } else if (
614
+ ts.isImportEqualsDeclaration(node)
615
+ && ts.isExternalModuleReference(node.moduleReference)
616
+ && ts.isStringLiteral(node.moduleReference.expression)
617
+ && KIT_PORT_MODULES.has(node.moduleReference.expression.text)
618
+ ) {
619
+ portNamespaces.add(node.name.text);
620
+ } else if (ts.isVariableDeclaration(node) && node.initializer !== undefined) {
621
+ if (isPortNamespaceExpr(node.initializer)) {
622
+ if (ts.isIdentifier(node.name)) portNamespaces.add(node.name.text);
623
+ else if (ts.isObjectBindingPattern(node.name)) collectBindingPatternPorts(node.name);
624
+ } else if (isPortMemberAccess(node.initializer) && ts.isIdentifier(node.name)) {
625
+ localPortNames.add(node.name.text);
626
+ } else if (ts.isIdentifier(node.name)) {
627
+ const init = unwrapExpr(ts, node.initializer);
628
+ if (ts.isIdentifier(init) && localPortNames.has(init.text)) localPortNames.add(node.name.text);
629
+ }
630
+ } else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
631
+ const left = unwrapExpr(ts, node.left);
632
+ if (isPortNamespaceExpr(node.right)) {
633
+ if (ts.isIdentifier(left)) portNamespaces.add(left.text);
634
+ else if (ts.isObjectLiteralExpression(left)) collectObjectLiteralAssignPorts(left);
635
+ } else if (isPortMemberAccess(node.right) && ts.isIdentifier(left)) {
636
+ localPortNames.add(left.text);
637
+ }
638
+ } else if (
639
+ ts.isCallExpression(node)
640
+ && (ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))
641
+ && propertyAccessName(ts, node.expression) === 'then'
642
+ && isPortModuleLoad(ts, node.expression.expression, false)
643
+ && node.arguments.length >= 1
644
+ ) {
645
+ const cb = unwrapExpr(ts, node.arguments[0]!);
646
+ if ((ts.isArrowFunction(cb) || ts.isFunctionExpression(cb)) && cb.parameters.length >= 1) {
647
+ const p0 = cb.parameters[0]!.name;
648
+ if (ts.isIdentifier(p0)) portNamespaces.add(p0.text);
649
+ else if (ts.isObjectBindingPattern(p0)) collectBindingPatternPorts(p0);
650
+ }
651
+ }
652
+ ts.forEachChild(node, collectPortBindings);
653
+ };
654
+ for (let pass = 0; pass < 3; pass++) {
655
+ const before = localPortNames.size + portNamespaces.size;
656
+ collectPortBindings(sourceFile);
657
+ if (localPortNames.size + portNamespaces.size === before) break;
658
+ }
659
+ }
497
660
  const hits: AstScanHit[] = [];
498
661
  const seen = new Set<string>();
499
662
 
@@ -564,6 +727,45 @@ function scanSourceWithAst(
564
727
  checkCssSpecifier(node.moduleReference.expression, node.moduleReference.expression.text);
565
728
  }
566
729
 
730
+ // 0b. KIT-APP-020(非 internalLab,过渡期告警):从 soma-kit/data 或 soma-kit 导入/再导出/解构/访问命令式浮层原语
731
+ if (!internalLab) {
732
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && KIT_PORT_MODULES.has(node.moduleSpecifier.text)) {
733
+ const named = node.importClause?.namedBindings;
734
+ if (named !== undefined && ts.isNamedImports(named)) {
735
+ for (const el of named.elements) {
736
+ if (KIT_IMPERATIVE_OVERLAY_PORTS.has((el.propertyName ?? el.name).text)) pushHit('KIT-APP-020', el, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
737
+ }
738
+ }
739
+ } else if (ts.isExportDeclaration(node) && node.moduleSpecifier !== undefined && ts.isStringLiteral(node.moduleSpecifier) && KIT_PORT_MODULES.has(node.moduleSpecifier.text)) {
740
+ const clause = node.exportClause;
741
+ if (clause !== undefined && ts.isNamedExports(clause)) {
742
+ for (const el of clause.elements) {
743
+ if (KIT_IMPERATIVE_OVERLAY_PORTS.has((el.propertyName ?? el.name).text)) pushHit('KIT-APP-020', el, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
744
+ }
745
+ }
746
+ } else if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name) && node.initializer !== undefined && isPortNamespaceExpr(node.initializer)) {
747
+ for (const el of node.name.elements) {
748
+ const prop = bindingElementPropName(ts, el);
749
+ if (prop !== undefined && KIT_IMPERATIVE_OVERLAY_PORTS.has(prop)) pushHit('KIT-APP-020', el, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
750
+ }
751
+ } else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken && isPortNamespaceExpr(node.right)) {
752
+ const left = unwrapExpr(ts, node.left);
753
+ if (ts.isObjectLiteralExpression(left)) {
754
+ for (const prop of left.properties) {
755
+ const key = ts.isShorthandPropertyAssignment(prop)
756
+ ? prop.name.text
757
+ : (ts.isPropertyAssignment(prop) ? propertyNameText(ts, prop.name) : undefined);
758
+ if (key !== undefined && KIT_IMPERATIVE_OVERLAY_PORTS.has(key)) pushHit('KIT-APP-020', prop, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
759
+ }
760
+ }
761
+ } else if (
762
+ (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
763
+ && isPortMemberAccess(node)
764
+ ) {
765
+ pushHit('KIT-APP-020', node, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
766
+ }
767
+ }
768
+
567
769
  // 1. AST .style / ['style'] 访问(全应用禁止,KIT-APP-005)
568
770
  if (
569
771
  (ts.isPropertyAccessExpression(node) && node.name.text === 'style')
@@ -598,9 +800,30 @@ function scanSourceWithAst(
598
800
  // 3b. KIT-APP-018(非 internalLab):全应用禁命令式浮层、document.body 挂载与伪造 Symbol.for('soma-kit.*')
599
801
  if (!internalLab) {
600
802
  if (calleeName === 'showModal') {
601
- pushHit('KIT-APP-018', node, '禁止调用 showModal() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer)或框架浮层端口', '移除命令式 showModal,改用页面 overlays 声明');
803
+ pushHit('KIT-APP-018', node, '禁止调用 showModal() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer),由 ctx.openOverlay / builtin: openOverlay 打开', '移除命令式 showModal,改用页面 overlays 声明');
602
804
  } else if (calleeName === 'showPopover') {
603
- pushHit('KIT-APP-018', node, '禁止调用 showPopover() 打开命令式原生浮层;请改用页面声明 overlays 或框架浮层端口', '移除命令式 showPopover,改用页面 overlays 或框架浮层端口');
805
+ pushHit('KIT-APP-018', node, '禁止调用 showPopover() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer),由 ctx.openOverlay / builtin: openOverlay 打开', '移除命令式 showPopover,改用页面 overlays 声明');
806
+ }
807
+ // KIT-APP-020(过渡期告警):调用本文件从 soma-kit/data(或 soma-kit)导入/加载的 mountKitModal / mountKitDrawer(含改名、解构、命名空间点访问与计算属性访问、.then 回调解构)
808
+ const callExpr = unwrapExpr(ts, node.expression);
809
+ const portCall = (ts.isIdentifier(callExpr) && localPortNames.has(callExpr.text)) || isPortMemberAccess(callExpr);
810
+ if (portCall) pushHit('KIT-APP-020', node, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
811
+ if (
812
+ (ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))
813
+ && propertyAccessName(ts, node.expression) === 'then'
814
+ && isPortModuleLoad(ts, node.expression.expression, false)
815
+ && node.arguments.length >= 1
816
+ ) {
817
+ const cb = unwrapExpr(ts, node.arguments[0]!);
818
+ if ((ts.isArrowFunction(cb) || ts.isFunctionExpression(cb)) && cb.parameters.length >= 1) {
819
+ const p0 = cb.parameters[0]!.name;
820
+ if (ts.isObjectBindingPattern(p0)) {
821
+ for (const el of p0.elements) {
822
+ const prop = bindingElementPropName(ts, el);
823
+ if (prop !== undefined && KIT_IMPERATIVE_OVERLAY_PORTS.has(prop)) pushHit('KIT-APP-020', el, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
824
+ }
825
+ }
826
+ }
604
827
  }
605
828
  if (
606
829
  (ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))
@@ -608,7 +831,7 @@ function scanSourceWithAst(
608
831
  && BODY_MUTATION_METHODS.has(calleeName)
609
832
  && isDocumentBodyExpr(ts, node.expression.expression)
610
833
  ) {
611
- pushHit('KIT-APP-018', node, `禁止调用 document.body.${calleeName}() 命令式挂载浮层或野生 DOM 节点`, '浮层必须通过页面 overlays 或框架浮层端口托管');
834
+ pushHit('KIT-APP-018', node, `禁止调用 document.body.${calleeName}() 命令式挂载浮层或野生 DOM 节点`, '浮层必须通过页面 overlays 声明托管');
612
835
  }
613
836
  if (isSymbolForCall(ts, node) && node.arguments.length >= 1) {
614
837
  const symKey = extractStaticHtmlText(ts, node.arguments[0]!);
@@ -618,9 +841,10 @@ function scanSourceWithAst(
618
841
  }
619
842
  }
620
843
 
621
- // 3c. KIT-APP-019(非 internalLab):组件源码禁直接调用 fetch()
622
- if (checkComponentPurity && !insideActionOrHook && isGlobalFetchCall(ts, node)) {
623
- pushHit('KIT-APP-019', node, '禁止在组件源码中直接调用 fetch() 绕过数据与动作管道;数据读取请通过页面 behavior.from,写操作请通过 defineKitActions 具名动作', '移除组件内 fetch(),改由页面 YAML 的 behavior.from 与 defineKitActions 驱动数据');
844
+ // 3c. KIT-APP-019(非 internalLab):非 IO 目录禁直接调用 fetch();展示对象目录(views/)改报 KIT-APP-021(过渡期告警)
845
+ if (!insideActionOrHook && isGlobalFetchCall(ts, node)) {
846
+ if (isViewDir) pushHit('KIT-APP-021', node, MSG_VIEW_FETCH, HINT_VIEW_FETCH);
847
+ else if (checkComponentPurity) pushHit('KIT-APP-019', node, MSG_NON_IO_FETCH, HINT_NON_IO_NET);
624
848
  }
625
849
 
626
850
  // 3d. KIT-APP-005 + KIT-APP-018(DOM 构造与属性操作)
@@ -662,8 +886,9 @@ function scanSourceWithAst(
662
886
  if (!inComponentsDir && node.expression.text === 'CSSStyleSheet') {
663
887
  pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
664
888
  }
665
- if (checkComponentPurity && !insideActionOrHook && node.expression.text === 'XMLHttpRequest') {
666
- pushHit('KIT-APP-019', node, '禁止在组件源码中使用 new XMLHttpRequest 绕过数据与动作管道;请改用页面 behavior.from 与 defineKitActions', '移除组件内 XMLHttpRequest,改由页面数据契约与具名动作驱动');
889
+ if (!insideActionOrHook && node.expression.text === 'XMLHttpRequest') {
890
+ if (isViewDir) pushHit('KIT-APP-021', node, MSG_VIEW_FETCH, HINT_VIEW_FETCH);
891
+ else if (checkComponentPurity) pushHit('KIT-APP-019', node, MSG_NON_IO_XHR, HINT_NON_IO_NET);
667
892
  }
668
893
  }
669
894
 
@@ -736,7 +961,10 @@ function scanSourceWithAst(
736
961
  * 1) KIT-APP-005(全应用始终生效):非标原生控件、<style>、AST `.style` 访问、`setAttribute('style', ...)`、`innerHTML`/`outerHTML`/`templateHtml` 内联 `style="..."` 或 `on*`、`.onclick =`;非 `components/` 禁 `.className`/`.classList`/`setAttribute('class', ...)`/`CSSStyleSheet`/`addEventListener`;
737
962
  * 2) KIT-APP-017(全应用始终生效):禁野生 CSS(.css/.scss/.less/.sass/.styl 文件与 import/require)及 `pages/`、`src/web/`、`views/`、`components/` 下手写 `.html`/`.htm`;
738
963
  * 3) KIT-APP-018(非 `internalLab` 生效):全应用禁命令式浮层(showModal/showPopover/createElement('dialog')/document.body.append*)与伪造 `Symbol.for('soma-kit.*')`;非 `components/` 禁 `createElement`/`createElementNS`/`innerHTML`/`outerHTML`/`insertAdjacentHTML`;
739
- * 4) KIT-APP-019(非 `internalLab` 生效):组件源码禁手写 `<table>`/`<thead>`/`<form>`/`<dialog>` 与直接 `fetch()`/`new XMLHttpRequest`;`defineKitBizComponent` 文件禁硬编码 `'/api/...'`。
964
+ * 3b) KIT-APP-020(非 `internalLab`,过渡期告警,装配时进 deprecations):应用源码从 `soma-kit/data` / `soma-kit` 导入或调用 `mountKitModal` / `mountKitDrawer`;
965
+ * 4) KIT-APP-019(非 `internalLab` 生效):非 IO 目录禁手写 `<table>`/`<thead>`/`<form>`/`<dialog>` 与直接 `fetch()`/`new XMLHttpRequest`
966
+ * (IO 目录:`api/` `bff/` `actions/` `server/` `src/bff/` `src/web/actions/` `soma.server.*`,及 defineKitActions / requestHook / startup / services 内;`views/` 与 `src/web/views/` 仅对 `KIT-APP-019` 豁免结构标签,其直接网络请求交由下述 `KIT-APP-021` 告警处理);`defineKitBizComponent` 文件禁硬编码 `'/api/...'`;
967
+ * 4b) KIT-APP-021(非 `internalLab`,过渡期告警,装配时进 deprecations):展示对象目录(`views/`、`src/web/views/`)直接 `fetch()`/`new XMLHttpRequest`。
740
968
  */
741
969
  export async function scanAppComponentSources(
742
970
  root: string,
@@ -819,10 +1047,13 @@ export async function scanAppComponentSources(
819
1047
  || rel.startsWith('server/')
820
1048
  || /^soma\.server\./.test(rel)
821
1049
  || /\/soma\.server\./.test(rel);
1050
+ // 展示对象目录:仍算 IO 目录(结构标签等检查口径不变),但其中直接 fetch / XMLHttpRequest 报 KIT-APP-021(过渡期告警,0.2.0 并入 019)
1051
+ const isViewDir = rel.startsWith('views/') || rel.startsWith('src/web/views/');
822
1052
  for (const hit of scanSourceWithAst(ts, full, code, {
823
1053
  inComponentsDir,
824
1054
  isNonCompAllowedIoDir,
825
1055
  internalLab,
1056
+ isViewDir,
826
1057
  ...(isInternalTsModuleSpecifier !== undefined ? { isInternalTsModuleSpecifier } : {}),
827
1058
  })) {
828
1059
  diagnostics.push({
package/src/app/index.ts CHANGED
@@ -10,7 +10,7 @@ export type {
10
10
  export { defineKitPack, KitPackError, packPrefix } from './define-kit-pack';
11
11
  export { defineKitView } from './define-kit-view';
12
12
  export type { KitViewClass, KitViewDefinition } from './define-kit-view';
13
- export type { KitViewHttp, KitViewContext, KitFormHandle, KitFormHandleSlot, KitFormChange, KitRequestDone, KitViewConfirmOptions, KitViewPromptSpec } from './kit-view-context';
13
+ export type { KitViewHttp, KitViewContext, KitFormHandle, KitFormHandleSlot, KitFormChange, KitRequestDone, KitViewConfirmOptions, KitViewPromptSpec, KitOpenOverlayOptions } from './kit-view-context';
14
14
  export type { KitPack, KitPackInput, KitPackStaticComponent } from './define-kit-pack';
15
15
  /** 应用组件契约顶层 selfReport 段(编译期静态自报声明)的形状:页面线据它补登应用组件的组件部件、宿主、自管布局与取色事实 */
16
16
  export type { KitComponentSelfDecl } from '../spatial/self-report';
@@ -50,6 +50,9 @@ export type { ComposeKitAppsOptions } from './compose-apps';
50
50
 
51
51
  // 应用自定义业务组件 / 页面框所需的公开类型与函数(K1-4)
52
52
  export { defineKitBizComponent } from '../biz/define';
53
+ // 应用业务组件的版式契约(defineKitBizComponent({ layoutContract: kitLayoutContract({...}) }),消除「没有版式契约」类 KIT-PAGE-GATE-006)
54
+ export { kitLayoutContract, kitLayoutContractProblems } from '../biz/layout-contracts';
55
+ export type { KitBizLayoutContract, KitLayoutContractInput, KitRoleLayout } from '../biz/layout-contracts';
53
56
  export { wrapKitBizComponent, composeKitBizComponents } from '../biz/compose';
54
57
  export type { WrapBizOptions, WrapBizShellContext, ComposeBizPart, ComposeBizOptions, ComposeBizShellContext } from '../biz/compose';
55
58
  export { wrapKitDataComponent, composeKitDataComponents, mapKeys } from '../data/wrap';
@@ -18,7 +18,7 @@ import { KIT_ACT_SCOPE, requestSemanticName } from '../object-renderer/request-a
18
18
  import type { KitRequestSpec } from '../object-renderer/request-actions';
19
19
  import { KIT_GRAMMAR } from '../object-renderer/defaults';
20
20
  import { getKitAppEnvelope, unwrapEnvelope, type KitEnvelope } from '../shared/envelope';
21
- import { kitActionExtras, openKitHubCreate, type KitNotifyTone } from '../biz/shared/runtime-hub';
21
+ import { closeKitHubOverlay, kitActionExtras, openKitHubCreate, openKitHubOverlay, type KitNotifyTone } from '../biz/shared/runtime-hub';
22
22
  import { runtimeNoticeText } from '../object-renderer/form-notify';
23
23
  import { askKitConfirm, type KitConfirmOptions } from '../data/confirm-dialog';
24
24
  import { askKitPrompt, type KitPromptOptions } from '../data/prompt-dialog';
@@ -48,6 +48,11 @@ export interface KitFormHandle {
48
48
  /** 草稿快照(未挂载 {}) */
49
49
  values(): Record<string, unknown>;
50
50
  dirty(): boolean;
51
+ /**
52
+ * 放弃这张表单的未保存修改,还原到当前初值(与用户确认「放弃修改」同一条通道:不清详情、不重发请求);表单未挂载 / 筛选栏返回 false。
53
+ * 浮层写了 draft: keep 时,草稿保留到提交成功或显式放弃——本方法就是显式放弃之一(另一个是 ctx.closeOverlay(名, { discard: true }))
54
+ */
55
+ discard(): boolean;
51
56
  /** 本表单所属页面的有效业务信封(表单 prop 编译期带入;未挂载 / 未声明为 undefined) */
52
57
  envelope(): KitEnvelope | undefined;
53
58
  /** 写草稿字段值(与用户输入同一条通道:即时校验、draft_change、重绘);表单未挂载 / 字段不在草稿里返回 false */
@@ -82,6 +87,14 @@ export type KitViewConfirmOptions = Omit<KitConfirmOptions, 'message' | 'at' | '
82
87
  /** ctx.prompt 的声明(同 askKitPrompt,去掉调用方元素 / 中止信号 / 无 DOM 结果) */
83
88
  export type KitViewPromptSpec = Omit<KitPromptOptions, 'at' | 'signal' | 'whenNoDom'>;
84
89
 
90
+ /** ctx.openOverlay 的选项 */
91
+ export interface KitOpenOverlayOptions {
92
+ /** 以这一行打开(浮层表单按编辑、读接口带该行主键);不给 = 无行打开(表单按新建) */
93
+ readonly row?: Readonly<Record<string, unknown>>;
94
+ /** 无行打开时的初值(盖在组件级预填之上;给了 row 时忽略) */
95
+ readonly values?: Readonly<Record<string, unknown>>;
96
+ }
97
+
85
98
  /** ctx.notify 的语气闭集 */
86
99
  export const KIT_VIEW_NOTIFY_TONES: readonly KitNotifyTone[] = Object.freeze(['info', 'success', 'warning', 'danger']);
87
100
 
@@ -116,7 +129,7 @@ export interface KitViewContext extends SomaViewContext {
116
129
  /**
117
130
  * 某个对象的表单句柄;第二参 `slot` 选这个对象的哪个可编辑视图:缺省 `'form'`(编辑表单),`'filter'` 是筛选栏草稿(同样的 values / set / onChange / onField;
118
131
  * 与 `ctx.view(对象, 'filter')` 同一个槽名与同一个锚点,对象既有 form 又有 filter 时靠它区分)。筛选栏的字段项写 `options: view.<成员>` 后,
119
- * 展示对象在 `onField` 里取数并整体替换引用写入成员、用 `set(下级, '')` 清下级值,与 form 同一套写法。对象名契约(ctx.form / data / reload / request / openCreate / cascadeOptions / watchDraftFlag / debouncedReload 通用;ctx.onOutcome 写对象名时指这个对象表单的写入结果):
132
+ * 展示对象在 `onField` 里取数并整体替换引用写入成员、用 `set(下级, '')` 清下级值,与 form 同一套写法。对象名契约(ctx.form / data / reload / request / openCreate / openOverlay / closeOverlay / cascadeOptions / watchDraftFlag / debouncedReload 通用;ctx.onOutcome 写对象名时指这个对象表单的写入结果):
120
133
  * 页面里声明的对象名(YAML 里写的键,如 `config`、`entity`;弹窗表单也用同一个名字),整页有多个同名对象(如两个页签都有 `entity`)时写限定名 `<页签 id>.<对象名>`
121
134
  * (如 `instances.entity`);运行期名(`instances_entity`、`register_step_config`)向后兼容、原样放行。解析与 `soma kit check` 同源(biz/shared/object-aliases.ts)。
122
135
  */
@@ -174,6 +187,18 @@ export interface KitViewContext extends SomaViewContext {
174
187
  * 触发它的按钮写 `submit: view.<方法>`(动作事件绑展示对象方法),方法里调 `ctx.openCreate(对象, 初值)`。
175
188
  */
176
189
  openCreate(object: string, values?: Readonly<Record<string, unknown>>): boolean;
190
+ /**
191
+ * 打开本页声明的浮层(product.objects.overlays.<名> 或页面级 page.overlays.<名>;只读、表单、数据组件内容都可以):
192
+ * 给 `row` 以该行打开(表单按编辑、读接口带该行主键),不给按无行打开(表单按新建,`values` 为初值,盖在组件级预填之上)。
193
+ * 与 `builtin: openOverlay` 同一条通道(焦点、层栈、草稿规则、提交后关窗都一样)。名字按对象名契约解析(声明名 / 限定名 <页签 id 或槽名>.<名>,
194
+ * 页面级浮层的限定名是 `kit_page.<名>` / 运行期名);名字不是本页浮层、所属协调组件没装上、或浮层正在提交返回 false(`soma kit check` 报 KIT-VIEW-013)
195
+ */
196
+ openOverlay(name: string, options?: KitOpenOverlayOptions): boolean;
197
+ /**
198
+ * 关闭这个浮层(它此刻打开着才有效,否则返回 false):缺省等同用户点「取消」(draft: discard 有未保存修改先问;draft: keep 不问、保留草稿);
199
+ * `{ discard: true }` 不问并放弃草稿(含 draft: keep 保留的)
200
+ */
201
+ closeOverlay(name: string, options?: { readonly discard?: boolean }): boolean;
177
202
  /**
178
203
  * kit 自绘确认对话框(取代浏览器原生 confirm;全 kit 同一份实现,焦点陷阱 / Esc / 回焦由浮层端口管):
179
204
  * 确认 = true,取消 / Esc / 点遮罩 = false。页面卸载时对话框随之关闭并 resolve(false)。
@@ -265,6 +290,11 @@ function formHandle(ctx: SomaViewContext, object: string, slot: KitFormHandleSlo
265
290
  return raw ?? {};
266
291
  },
267
292
  dirty: () => comp?.call<boolean>('dirty') === true,
293
+ discard: () => {
294
+ const raw = comp?.call<boolean>('discard');
295
+ if (raw === undefined) warnMissing();
296
+ return raw === true;
297
+ },
268
298
  envelope: () => comp?.call<KitEnvelope | undefined>('envelope') ?? undefined,
269
299
  set: (field, value) => {
270
300
  const raw = comp?.call<boolean>('set', field, value);
@@ -358,6 +388,18 @@ export function extendKitViewContext(ctx: SomaViewContext, viewName?: string): K
358
388
  } },
359
389
  openCreate: { value: (object: string, values: Readonly<Record<string, unknown>> = {}): boolean =>
360
390
  typeof object === 'string' && object.trim() !== '' && openKitHubCreate(nameOf(object, 'openCreate'), { ...values }) },
391
+ openOverlay: { value: (name: string, options: KitOpenOverlayOptions = {}): boolean => {
392
+ if (typeof name !== 'string' || name.trim() === '') return false;
393
+ const ok = openKitHubOverlay(nameOf(name, 'openOverlay'), options.row !== undefined
394
+ ? { row: { ...options.row } }
395
+ : { ...(options.values !== undefined ? { values: { ...options.values } } : {}) });
396
+ if (!ok && isDevEnv()) console.warn(`[soma-kit][view] ctx.openOverlay("${name}") 没有打开:名字不是本页声明的浮层、所属业务组件未装上,或浮层正在提交`);
397
+ return ok;
398
+ } },
399
+ closeOverlay: { value: (name: string, options: { readonly discard?: boolean } = {}): boolean => {
400
+ if (typeof name !== 'string' || name.trim() === '') return false;
401
+ return closeKitHubOverlay(nameOf(name, 'closeOverlay'), options.discard === true ? { discard: true } : {});
402
+ } },
361
403
  data: { value: <T = unknown>(name: string): SomaViewDataHandle<T> => ctx.data<T>(nameOf(name, 'data')) },
362
404
  reload: { value: (names?: readonly string[]): Promise<void> => ctx.reload(namesOf(names, 'reload')) },
363
405
  confirm: { value: (message: string, options: KitViewConfirmOptions = {}): Promise<boolean> =>
package/src/app/server.ts CHANGED
@@ -810,7 +810,16 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
810
810
  }
811
811
  }
812
812
  const sourceGateDiagnostics = await scanAppComponentSources(root, { internalLab });
813
- diagnostics.push(...sourceGateDiagnostics);
813
+ // 告警级的源码门禁(KIT-APP-020 命令式浮层原语、KIT-APP-021 展示对象目录裸 fetch):过渡期不挡装配,进弃用提示段(--strict 才算失败)
814
+ const SOURCE_GATE_WARN: ReadonlySet<string> = new Set(['KIT-APP-020', 'KIT-APP-021']);
815
+ diagnostics.push(...sourceGateDiagnostics.filter((d) => !SOURCE_GATE_WARN.has(d.code)));
816
+ const sourceGateAdvisories: KitAdvisory[] = sourceGateDiagnostics
817
+ .filter((d) => SOURCE_GATE_WARN.has(d.code))
818
+ .map((d) => {
819
+ const [file = '', lineText] = d.path.split(':');
820
+ const line = lineText !== undefined ? Number(lineText) : NaN;
821
+ return { code: d.code, severity: 'warn' as const, path: d.path, file, ...(Number.isInteger(line) ? { line } : {}), message: d.message, hint: d.hint ?? '' };
822
+ });
814
823
 
815
824
  // 3 主题头(不在此处提前抛错,确保后面页面的编译诊断也能一次收集报全;非实验室应用禁止 kit.app.yaml#style,已报 KIT-APP-017)
816
825
  let themeCss = KIT_DEFAULT_THEME_CSS;
@@ -979,7 +988,7 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
979
988
  const deprecations: KitAdvisory[] = [];
980
989
  /** 页面文件 → 界面规则来源记录(每条规则最终生效的命中;只有用到规则的页有) */
981
990
  const lookReports = new Map<string, readonly KitLookReportRow[]>();
982
- deprecations.push(...themeGateAdvisories, ...selfReportAdvisories);
991
+ deprecations.push(...themeGateAdvisories, ...selfReportAdvisories, ...sourceGateAdvisories);
983
992
  /** next 下组合核对的输入:页面地址 → 版面事实(编译出的页取 pageAttrs,缓存命中的页取旁记,已登记的运行期提交页取版本号里的事实戳) */
984
993
  const tierPages = new Map<string, KitTierCompatFrameFacts>();
985
994
  let tierPagesMissing = 0;
@@ -12,6 +12,13 @@ import { defineKitBizComponent } from './define';
12
12
  import { validateBizAreaClass } from './shared/compile-helpers';
13
13
  import type { KitBizContext, KitBizDefinition, KitBizEnvelopeTrait, KitBizInput, KitBizRole } from './types';
14
14
  import { kitFail } from '../shared/kit-error';
15
+ import { KIT_BIZ_LAYOUT_CONTRACTS, kitLayoutContract, kitLayoutContractProblems, kitRebaseLayoutContract, type KitBizLayoutContract } from './layout-contracts';
16
+
17
+ /** 组件的版式契约来源:内置冻结表优先,其次组件定义上声明的 layoutContract;都没有为 undefined */
18
+ function contractOfDef(def: KitBizDefinition): KitBizLayoutContract | undefined {
19
+ if (Object.hasOwn(KIT_BIZ_LAYOUT_CONTRACTS, def.kind)) return KIT_BIZ_LAYOUT_CONTRACTS[def.kind]!;
20
+ return def.layoutContract ?? undefined;
21
+ }
15
22
 
16
23
  export interface WrapBizShellContext {
17
24
  input: KitBizInput;
@@ -31,6 +38,12 @@ export interface WrapBizOptions {
31
38
  acceptConfig?: boolean;
32
39
  /** 可选:覆写底层业务组件的声明式版心特征;缺省透传 inner.envelope */
33
40
  envelope?: KitBizEnvelopeTrait;
41
+ /**
42
+ * 可选:版式契约(规则同 defineKitBizComponent 的 layoutContract,不合法报 KIT-COMP-007)。
43
+ * 缺省继承 inner 的契约(内置冻结表或 inner.layoutContract);roles 被重定义时只在新角色都在旧契约里时继承(按新角色裁剪),
44
+ * 裁剪后不合法(如依附目标被裁掉)则不继承;null = 不声明(取 FREE)
45
+ */
46
+ layoutContract?: KitBizLayoutContract | null;
34
47
  /** 包装层写死的 Tailwind 类串或类名列表(自动校验并并入产物 candidates) */
35
48
  candidates?: readonly string[];
36
49
  /**
@@ -61,11 +74,39 @@ export function wrapKitBizComponent(inner: KitBizDefinition, options: WrapBizOpt
61
74
  }
62
75
 
63
76
  const resolvedEnvelope = options.envelope ?? inner.envelope;
77
+ // 版式契约:显式给了用显式的(定义期校验、不合法抛 KIT-COMP-007);没给则继承 inner 的(角色被重定义时按新角色裁剪),继承结果不合法就不继承(与改前同为 FREE)
78
+ const innerContract = contractOfDef(inner);
79
+ const wrapRoles = options.roles ?? inner.roles;
80
+ let inherited: KitBizLayoutContract | undefined;
81
+ if (innerContract !== undefined) {
82
+ if (options.roles === undefined) {
83
+ inherited = innerContract;
84
+ } else if (Object.keys(wrapRoles).every((r) => Object.hasOwn(innerContract.roles, r))) {
85
+ const keptRoles = Object.freeze(Object.fromEntries(Object.keys(wrapRoles).map((r) => [r, innerContract.roles[r]!])));
86
+ if (innerContract.exclusiveGroups !== undefined) {
87
+ const used = new Set(Object.values(keptRoles).map((r) => r.exclusiveGroup).filter((g): g is string => g !== undefined));
88
+ const filteredEntries = Object.entries(innerContract.exclusiveGroups).filter(([g]) => used.has(g));
89
+ const remainingKinds = filteredEntries.map(([, e]) => e);
90
+ if (filteredEntries.length <= 1 && remainingKinds.includes(innerContract.exclusive)) {
91
+ const { exclusiveGroups: _drop, ...rest } = innerContract;
92
+ inherited = Object.freeze({ ...rest, roles: keptRoles });
93
+ } else {
94
+ inherited = Object.freeze({ ...innerContract, roles: keptRoles, exclusiveGroups: Object.freeze(Object.fromEntries(filteredEntries)) });
95
+ }
96
+ } else {
97
+ inherited = Object.freeze({ ...innerContract, roles: keptRoles });
98
+ }
99
+ }
100
+ }
101
+ const resolvedContract = options.layoutContract !== undefined
102
+ ? options.layoutContract
103
+ : inherited !== undefined && kitLayoutContractProblems(options.kind, wrapRoles, inherited).length === 0 ? inherited : undefined;
64
104
  return defineKitBizComponent({
65
105
  kind: options.kind,
66
106
  roles: options.roles ?? inner.roles,
67
107
  areas: allAreas,
68
108
  acceptConfig: options.acceptConfig ?? true,
109
+ ...(resolvedContract !== undefined ? { layoutContract: resolvedContract } : {}),
69
110
  ...(resolvedEnvelope !== undefined ? { envelope: resolvedEnvelope } : {}),
70
111
  ...(resolvedEnvelope === undefined && inner.pageMaxWidth !== undefined ? { pageMaxWidth: inner.pageMaxWidth } : {}),
71
112
  compile(input: KitBizInput, ctx: KitBizContext): KitFragment {
@@ -169,6 +210,12 @@ export interface ComposeBizOptions {
169
210
  acceptConfig?: boolean;
170
211
  /** 复合外壳写死的 Tailwind 类串或类名列表(自动校验并并入 candidates) */
171
212
  candidates?: readonly string[];
213
+ /**
214
+ * 可选:版式契约(规则同 defineKitBizComponent 的 layoutContract,不合法报 KIT-COMP-007)。
215
+ * 缺省:只有一个子部件且它有契约时合成——角色按 roleMap 改名、锚点按子部件前缀改写(kitRebaseLayoutContract)、互斥组加子部件前缀、
216
+ * 排法 / 互斥 / 版面事实沿用该子部件;多个子部件时排法与互斥没有确定解,不合成(取 FREE),需要契约请显式给。null = 不声明
217
+ */
218
+ layoutContract?: KitBizLayoutContract | null;
172
219
  /** 将各子部件生成的 HTML(`partHtml[partKey]`)装入写死的复合网格/边框外壳中 */
173
220
  renderShell: (partHtml: Record<string, string>, ctx: ComposeBizShellContext) => string;
174
221
  }
@@ -213,6 +260,24 @@ export function composeKitBizComponents(options: ComposeBizOptions): KitBizDefin
213
260
  const badRoot = checkClasses(baseRootClass, `${options.kind}.rootClass`);
214
261
  if (badRoot.length > 0) kitFail('KIT-COMP-003', `${options.kind}.rootClass`, `${options.kind} 的 rootClass 非法:${badRoot[0]!.message}`, 'rootClass 只能用刻度内的 Tailwind 类');
215
262
 
263
+ // 版式契约:显式给了用显式的;没给且只有一个子部件、它有契约时合成(合成结果不合法就不合成,与改前同为 FREE)
264
+ let composed: KitBizLayoutContract | undefined;
265
+ if (options.layoutContract === undefined && partEntries.length === 1) {
266
+ const [key, p] = partEntries[0]!;
267
+ const c = contractOfDef(p.component);
268
+ if (c !== undefined) {
269
+ const rb = kitRebaseLayoutContract(c, p.roleMap, key);
270
+ const candidate = kitLayoutContract({
271
+ arrange: c.arrange, exclusive: c.exclusive, defaultSelected: c.defaultSelected, roles: rb.roles,
272
+ ...(Object.keys(rb.exclusiveGroups).length > 0 ? { exclusiveGroups: rb.exclusiveGroups } : {}),
273
+ ...(rb.overlayAnchor !== undefined && p.forwardOverlays === true ? { overlayAnchor: rb.overlayAnchor } : {}),
274
+ frameFacts: { ...c.frameFacts },
275
+ });
276
+ if (kitLayoutContractProblems(options.kind, roles, candidate).length === 0) composed = candidate;
277
+ }
278
+ }
279
+ const resolvedContract = options.layoutContract !== undefined ? options.layoutContract : composed;
280
+
216
281
  const areas = [...new Set(['root', ...(options.areas ?? [])])];
217
282
  const areaSet = new Set<string>(areas);
218
283
  const extraTokens = splitCandidateTokens([baseRootClass, ...(options.candidates ?? [])]);
@@ -226,6 +291,7 @@ export function composeKitBizComponents(options: ComposeBizOptions): KitBizDefin
226
291
  roles,
227
292
  areas,
228
293
  acceptConfig: options.acceptConfig ?? true,
294
+ ...(resolvedContract !== undefined ? { layoutContract: resolvedContract } : {}),
229
295
  compile(input: KitBizInput, ctx: KitBizContext): KitFragment {
230
296
  const diagnostics: KitDiagnostic[] = [];
231
297
  const areaMap = input.areaClass ?? {};