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.
@@ -1,14 +1,17 @@
1
- // 应用扩展组件的唯一接入路径门禁(KIT-APP-004 / KIT-APP-005)。
1
+ // 应用扩展组件的唯一接入路径与防逃逸硬门禁(KIT-APP-004 / KIT-APP-005 / KIT-APP-014 / KIT-APP-017 / KIT-APP-018 / KIT-APP-019)。
2
2
  //
3
- // 设计原则:接入 soma-kit 只有一条路,禁止应用组件绕过标准组件库与样式编译管线:
4
- // 1) KIT-APP-004:所有登记进 baseComponents / staticObjectComponents 的 App* 组件,必须经
3
+ // 设计原则:接入 soma-kit 只有一条路,禁止应用绕过业务组件与样式编译管线:
4
+ // 1) KIT-APP-004:所有登记的自定义组件(含业务组件私有 dataComponents),必须经
5
5
  // wrapKitDataComponent、composeKitDataComponents 或 declareKitUses 显式登记依赖组件与候选类元数据;
6
6
  // 声明的 uses 必须是真实存在的内置组件名,own 候选类必须通过 checkClasses 校验(禁方括号任意值)。
7
7
  // 2) KIT-APP-005:严禁应用组件在 templateHtml、控制器或源码中私自拼写已被 soma-kit
8
8
  // 标准组件接管的原生表单控件(原生 <select>、原生 <input type="range">、原生 <input type="date|datetime-local|time|month|week">),
9
9
  // 严禁在 TS/HTML 中书写内联 style / 操作 .style / setAttribute('style', ...),
10
10
  // 也严禁在非组件 TS(views/actions/api/soma.app.ts 等)中操作 .className / .classList 或手绑 addEventListener 等 DOM 事件。
11
- // 下拉一律走 Select / Combobox / mountKitSelectField,滑块一律走 Range,日期时间一律走 Date / DateRange / TimePicker。
11
+ // 3) KIT-APP-017:全应用零野生 CSS(.css/.scss/.less/.sass/.styl 文件与 import/require)与野生页面 HTML(pages/src/web/views/components 下 .html/.htm)。
12
+ // 4) KIT-APP-018:禁命令式浮层(showModal / showPopover / createElement('dialog') / document.body.append*)、
13
+ // 禁非组件目录 DOM 构造(createElement / createElementNS / innerHTML / outerHTML / insertAdjacentHTML)与禁伪造 Symbol.for('soma-kit.*')。
14
+ // 5) KIT-APP-019:禁组件内手写 <table>/<thead>/<form>/<dialog> 与裸 fetch / XMLHttpRequest,禁业务组件源码硬编码 '/api/...'。
12
15
 
13
16
  import type { SomaComponentDefinition } from 'soma-core';
14
17
  import { KIT_BASE_COMPONENTS } from '../base/index';
@@ -146,11 +149,89 @@ export function findForbiddenNativeControls(text: string): Array<{ line: number;
146
149
  return hits;
147
150
  }
148
151
 
152
+ const FORBIDDEN_IMPERATIVE_OVERLAY_PATTERNS: readonly ForbiddenRule[] = [
153
+ {
154
+ id: 'show-modal',
155
+ pattern: /\.\s*showModal\s*\(/,
156
+ message: '禁止调用 showModal() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer)或框架浮层端口',
157
+ },
158
+ {
159
+ id: 'show-popover',
160
+ pattern: /\.\s*showPopover\s*\(/,
161
+ message: '禁止调用 showPopover() 打开命令式原生浮层;请改用页面声明 overlays 或框架浮层端口',
162
+ },
163
+ {
164
+ id: 'create-dialog',
165
+ pattern: /\bcreateElement\s*\(\s*['"`]dialog['"`]\s*\)/i,
166
+ message: '禁止调用 createElement("dialog") 创建命令式浮层;请改用页面声明 overlays(dialog / drawer)',
167
+ },
168
+ {
169
+ id: 'body-append-portal',
170
+ pattern: /\bdocument\s*\.\s*body\s*\.\s*(?:appendChild|append|prepend|insertAdjacentHTML|insertAdjacentElement)\s*\(/,
171
+ message: '禁止向 document.body 命令式挂载浮层或野生 DOM 节点;浮层必须通过页面 overlays 或框架浮层端口托管',
172
+ },
173
+ ];
174
+
175
+ const FORBIDDEN_STRUCTURED_OR_NET_PATTERNS: readonly ForbiddenRule[] = [
176
+ {
177
+ id: 'raw-table-tag',
178
+ pattern: /<\s*table(?=[\s>/])/i,
179
+ message: '禁止在自定义组件中手写 <table> 规整表格;请使用 soma-kit 标准集合表格(view.list)与业务组件装数据',
180
+ },
181
+ {
182
+ id: 'raw-thead-tag',
183
+ pattern: /<\s*thead(?=[\s>/])/i,
184
+ message: '禁止在自定义组件中手写 <thead> 规整表头;请使用 soma-kit 标准集合表格(view.list)与业务组件装数据',
185
+ },
186
+ {
187
+ id: 'raw-form-tag',
188
+ pattern: /<\s*form(?=[\s>/])/i,
189
+ message: '禁止在自定义组件中手写 <form> 表单;请使用 soma-kit 标准表单(view.form / KitObjectForm)与业务组件装数据',
190
+ },
191
+ {
192
+ id: 'raw-dialog-tag',
193
+ pattern: /<\s*dialog(?=[\s>/])/i,
194
+ message: '禁止在自定义组件中手写 <dialog> 浮层;请改用页面声明 overlays(dialog / drawer)或框架浮层端口',
195
+ },
196
+ {
197
+ id: 'raw-fetch-call',
198
+ pattern: /(?:^|[^.\w$])fetch\s*\(|\b(?:window|globalThis|self)\s*\.\s*fetch\s*\(/,
199
+ message: '禁止在组件源码中直接调用 fetch() 绕过数据与动作管道;数据读取请通过页面 behavior.from,写操作请通过 defineKitActions 具名动作',
200
+ },
201
+ {
202
+ id: 'raw-xhr',
203
+ pattern: /\bnew\s+XMLHttpRequest\b/,
204
+ message: '禁止在组件源码中使用 new XMLHttpRequest 绕过数据与动作管道;请改用页面 behavior.from 与 defineKitActions',
205
+ },
206
+ ];
207
+
208
+ function findRuleHits(text: string, rules: readonly ForbiddenRule[]): Array<{ line: number; message: string }> {
209
+ const cleaned = stripCodeComments(text);
210
+ const lines = cleaned.split('\n');
211
+ const hits: Array<{ line: number; message: string }> = [];
212
+ for (let idx = 0; idx < lines.length; idx++) {
213
+ const line = lines[idx]!;
214
+ for (const rule of rules) {
215
+ if (rule.pattern.test(line)) {
216
+ hits.push({ line: idx + 1, message: rule.message });
217
+ break;
218
+ }
219
+ }
220
+ }
221
+ return hits;
222
+ }
223
+
149
224
  /**
150
225
  * 装配期同步校验单个应用扩展组件(浏览器与服务端共用):
151
- * 拦截未经唯一接入路径包装声明的野生组件(KIT-APP-004)与私造非标原生控件(KIT-APP-005)。
226
+ * 拦截未经唯一接入路径包装声明的野生组件(KIT-APP-004)、无标准控制器(KIT-APP-014)、
227
+ * 私造非标原生控件/内联样式(KIT-APP-005);
228
+ * 严格业务组件模式下(strictBizOnly !== false)额外拦截命令式浮层(KIT-APP-018)及手写 table/form/dialog/裸 fetch(KIT-APP-019)。
152
229
  */
153
- export function assertSinglePathComponent(name: string, def: SomaComponentDefinition): void {
230
+ export function assertSinglePathComponent(
231
+ name: string,
232
+ def: SomaComponentDefinition,
233
+ opts?: { readonly strictBizOnly?: boolean },
234
+ ): void {
154
235
  const meta = wrappedCandidateSource(def);
155
236
  if (meta === undefined) {
156
237
  kitFail('KIT-APP-004', `components.${name}`, `应用组件 ${name} 未经唯一接入路径声明:必须通过 wrapKitDataComponent / composeKitDataComponents 包装组合,或经 declareKitUses(${name}, uses, candidates) 显式登记依赖组件与候选类`, `用 wrapKitDataComponent 包装,或在定义处调用 declareKitUses(${name}, uses, candidates)`);
@@ -176,12 +257,36 @@ export function assertSinglePathComponent(name: string, def: SomaComponentDefini
176
257
  if (tplHits.length > 0) {
177
258
  kitFail('KIT-APP-005', `components.${name}.templateHtml`, `应用组件 ${name} 的 templateHtml 违规:${tplHits[0]!.message}`, '改用 soma-kit 标准组件(Select / Slider / DatePicker 等),不手写原生控件');
178
259
  }
179
- if (typeof def.controllerFactory === 'function') {
180
- const fnHits = findForbiddenNativeControls(getKitControllerSource(def.controllerFactory));
260
+ const ctrlSrc = typeof def.controllerFactory === 'function' ? getKitControllerSource(def.controllerFactory) : '';
261
+ if (ctrlSrc !== '') {
262
+ const fnHits = findForbiddenNativeControls(ctrlSrc);
181
263
  if (fnHits.length > 0) {
182
264
  kitFail('KIT-APP-005', `components.${name}.controller`, `应用组件 ${name} 的控制器违规:${fnHits[0]!.message}`, '控制器里不要创建原生控件,改用 soma-kit 标准组件');
183
265
  }
184
266
  }
267
+
268
+ if (opts?.strictBizOnly !== false) {
269
+ const tplOverlayHits = typeof def.templateHtml === 'string' ? findRuleHits(def.templateHtml, FORBIDDEN_IMPERATIVE_OVERLAY_PATTERNS) : [];
270
+ if (tplOverlayHits.length > 0) {
271
+ kitFail('KIT-APP-018', `components.${name}.templateHtml`, `应用组件 ${name} 的 templateHtml 违规:${tplOverlayHits[0]!.message}`, '浮层改由页面 *.kit.yaml 的 overlays 声明或框架浮层端口托管');
272
+ }
273
+ if (ctrlSrc !== '') {
274
+ const ctrlOverlayHits = findRuleHits(ctrlSrc, FORBIDDEN_IMPERATIVE_OVERLAY_PATTERNS);
275
+ if (ctrlOverlayHits.length > 0) {
276
+ kitFail('KIT-APP-018', `components.${name}.controller`, `应用组件 ${name} 的控制器违规:${ctrlOverlayHits[0]!.message}`, '浮层改由页面 *.kit.yaml 的 overlays 声明或框架浮层端口托管');
277
+ }
278
+ }
279
+ const tplStructHits = typeof def.templateHtml === 'string' ? findRuleHits(def.templateHtml, FORBIDDEN_STRUCTURED_OR_NET_PATTERNS) : [];
280
+ if (tplStructHits.length > 0) {
281
+ kitFail('KIT-APP-019', `components.${name}.templateHtml`, `应用组件 ${name} 的 templateHtml 违规:${tplStructHits[0]!.message}`, '表格/表单/浮层改用标准数据视图与页面 overlays;数据与写操作经 behavior.from 与 defineKitActions 注入');
282
+ }
283
+ if (ctrlSrc !== '') {
284
+ const ctrlStructHits = findRuleHits(ctrlSrc, FORBIDDEN_STRUCTURED_OR_NET_PATTERNS);
285
+ if (ctrlStructHits.length > 0) {
286
+ kitFail('KIT-APP-019', `components.${name}.controller`, `应用组件 ${name} 的控制器违规:${ctrlStructHits[0]!.message}`, '表格/表单/浮层改用标准数据视图与页面 overlays;数据与写操作经 behavior.from 与 defineKitActions 注入');
287
+ }
288
+ }
289
+ }
185
290
  }
186
291
 
187
292
  const SKIP_SCAN_DIRS = new Set([
@@ -246,6 +351,37 @@ const HTML_INLINE_ATTR_RULES: readonly ForbiddenRule[] = [
246
351
  },
247
352
  ];
248
353
 
354
+ const HTML_STRUCTURE_FORBIDDEN_RULES: readonly ForbiddenRule[] = [
355
+ {
356
+ id: 'raw-table-tag',
357
+ pattern: /<\s*table(?=[\s>/])/i,
358
+ message: '禁止在自定义组件中手写 <table> 规整表格;请使用 soma-kit 标准集合表格(view.list)与业务组件装数据',
359
+ },
360
+ {
361
+ id: 'raw-thead-tag',
362
+ pattern: /<\s*thead(?=[\s>/])/i,
363
+ message: '禁止在自定义组件中手写 <thead> 规整表头;请使用 soma-kit 标准集合表格(view.list)与业务组件装数据',
364
+ },
365
+ {
366
+ id: 'raw-form-tag',
367
+ pattern: /<\s*form(?=[\s>/])/i,
368
+ message: '禁止在自定义组件中手写 <form> 表单;请使用 soma-kit 标准表单(view.form / KitObjectForm)与业务组件装数据',
369
+ },
370
+ {
371
+ id: 'raw-dialog-tag',
372
+ pattern: /<\s*dialog(?=[\s>/])/i,
373
+ message: '禁止在自定义组件中手写 <dialog> 浮层;请改用页面声明 overlays(dialog / drawer)或框架浮层端口',
374
+ },
375
+ ];
376
+
377
+ const CSS_FILE_EXT_RE = /\.(?:css|scss|less|sass|styl)$/i;
378
+ const CSS_IMPORT_SPEC_RE = /\.(?:css|scss|less|sass|styl)(?:[?#].*)?$/i;
379
+ const HTML_FILE_EXT_RE = /\.(?:html|htm)$/i;
380
+ const WILD_HTML_DIR_RE = /^(?:pages|src\/web|views|components)\//;
381
+ const BODY_MUTATION_METHODS = new Set(['appendChild', 'append', 'prepend', 'insertAdjacentHTML', 'insertAdjacentElement']);
382
+ const HARDCODED_API_PATH_RE = /(?:^|[\s:=,'"(`])\/api(?:\/[A-Za-z0-9_./:-]*|$)|\bhttps?:\/\/[^\s'"`]*\/api(?:\/|$)/;
383
+ const APP_HOOK_PROP_NAMES = new Set(['actions', 'requestHook', 'startup', 'services']);
384
+
249
385
  type TsModule = typeof import('typescript');
250
386
 
251
387
  function scriptKindForFile(ts: TsModule, fileName: string): import('typescript').ScriptKind {
@@ -279,108 +415,275 @@ function propertyAccessName(ts: TsModule, node: import('typescript').Expression)
279
415
  return undefined;
280
416
  }
281
417
 
418
+ function isDocumentBodyExpr(ts: TsModule, node: import('typescript').Expression): boolean {
419
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isTypeAssertionExpression(node)) {
420
+ return isDocumentBodyExpr(ts, node.expression);
421
+ }
422
+ if (propertyAccessName(ts, node) !== 'body') return false;
423
+ const base = ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? node.expression : undefined;
424
+ if (base === undefined) return false;
425
+ if (ts.isIdentifier(base) && base.text === 'document') return true;
426
+ if ((ts.isPropertyAccessExpression(base) || ts.isElementAccessExpression(base)) && propertyAccessName(ts, base) === 'document') {
427
+ return ts.isIdentifier(base.expression) && (base.expression.text === 'window' || base.expression.text === 'globalThis' || base.expression.text === 'self');
428
+ }
429
+ return false;
430
+ }
431
+
432
+ function isSymbolForCall(ts: TsModule, node: import('typescript').CallExpression): boolean {
433
+ const expr = node.expression;
434
+ if (!(ts.isPropertyAccessExpression(expr) || ts.isElementAccessExpression(expr))) return false;
435
+ if (propertyAccessName(ts, expr) !== 'for') return false;
436
+ const base = expr.expression;
437
+ if (ts.isIdentifier(base) && base.text === 'Symbol') return true;
438
+ if ((ts.isPropertyAccessExpression(base) || ts.isElementAccessExpression(base)) && propertyAccessName(ts, base) === 'Symbol') {
439
+ return ts.isIdentifier(base.expression) && (base.expression.text === 'globalThis' || base.expression.text === 'window' || base.expression.text === 'self');
440
+ }
441
+ return false;
442
+ }
443
+
444
+ function isGlobalFetchCall(ts: TsModule, node: import('typescript').CallExpression): boolean {
445
+ const expr = node.expression;
446
+ if (ts.isIdentifier(expr) && expr.text === 'fetch') return true;
447
+ if ((ts.isPropertyAccessExpression(expr) || ts.isElementAccessExpression(expr)) && propertyAccessName(ts, expr) === 'fetch') {
448
+ return ts.isIdentifier(expr.expression) && (expr.expression.text === 'window' || expr.expression.text === 'globalThis' || expr.expression.text === 'self');
449
+ }
450
+ return false;
451
+ }
452
+
453
+ function fileDefinesBizComponent(ts: TsModule, sourceFile: import('typescript').SourceFile): boolean {
454
+ let found = false;
455
+ const scan = (node: import('typescript').Node): void => {
456
+ if (found) return;
457
+ if (ts.isCallExpression(node)) {
458
+ const callee = ts.isIdentifier(node.expression)
459
+ ? node.expression.text
460
+ : propertyAccessName(ts, node.expression);
461
+ if (callee === 'defineKitBizComponent') {
462
+ found = true;
463
+ return;
464
+ }
465
+ }
466
+ ts.forEachChild(node, scan);
467
+ };
468
+ scan(sourceFile);
469
+ return found;
470
+ }
471
+
472
+ interface AstScanHit {
473
+ readonly code: string;
474
+ readonly line: number;
475
+ readonly message: string;
476
+ readonly hint?: string;
477
+ }
478
+
479
+ interface AstScanFlags {
480
+ readonly inComponentsDir: boolean;
481
+ readonly isNonCompAllowedIoDir: boolean;
482
+ readonly internalLab: boolean;
483
+ /** 仅 internalLab 时用于区分 *.css.ts 模块导入与真实 .css 样式表导入 */
484
+ readonly isInternalTsModuleSpecifier?: (spec: string) => boolean;
485
+ }
486
+
282
487
  function scanSourceWithAst(
283
488
  ts: TsModule,
284
489
  fullPath: string,
285
490
  code: string,
286
- inComponentsDir: boolean,
287
- ): Array<{ line: number; message: string }> {
491
+ flags: AstScanFlags,
492
+ ): AstScanHit[] {
493
+ const { inComponentsDir, isNonCompAllowedIoDir, internalLab, isInternalTsModuleSpecifier } = flags;
288
494
  const sourceFile = ts.createSourceFile(fullPath, code, ts.ScriptTarget.Latest, true, scriptKindForFile(ts, fullPath));
289
- const hits: Array<{ line: number; message: string }> = [];
495
+ const hasBizComponentDef = !internalLab && fileDefinesBizComponent(ts, sourceFile);
496
+ const checkComponentPurity = !internalLab && !isNonCompAllowedIoDir;
497
+ const hits: AstScanHit[] = [];
290
498
  const seen = new Set<string>();
291
499
 
292
- const pushHit = (node: import('typescript').Node, message: string): void => {
500
+ const pushHit = (codeId: string, node: import('typescript').Node, message: string, hint?: string): void => {
293
501
  const line = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
294
- const key = `${line}:${message}`;
502
+ const key = `${codeId}:${line}:${message}`;
295
503
  if (seen.has(key)) return;
296
504
  seen.add(key);
297
- hits.push({ line, message });
505
+ hits.push(hint !== undefined ? { code: codeId, line, message, hint } : { code: codeId, line, message });
298
506
  };
299
507
 
300
- const checkHtmlString = (node: import('typescript').Node, html: string, includeInlineAttrs: boolean): void => {
508
+ const checkHtmlString = (
509
+ node: import('typescript').Node,
510
+ html: string,
511
+ includeInlineAttrs: boolean,
512
+ checkStructuredTags: boolean,
513
+ ): void => {
301
514
  if (!html) return;
302
515
  if (includeInlineAttrs) {
303
516
  for (const rule of HTML_INLINE_ATTR_RULES) {
304
- if (rule.pattern.test(html)) pushHit(node, rule.message);
517
+ if (rule.pattern.test(html)) pushHit('KIT-APP-005', node, rule.message);
305
518
  }
306
519
  }
307
520
  for (const rule of HTML_TAG_FORBIDDEN_RULES) {
308
- if (rule.pattern.test(html)) pushHit(node, rule.message);
521
+ if (rule.pattern.test(html)) pushHit('KIT-APP-005', node, rule.message);
522
+ }
523
+ if (checkStructuredTags) {
524
+ for (const rule of HTML_STRUCTURE_FORBIDDEN_RULES) {
525
+ if (rule.pattern.test(html)) {
526
+ pushHit(
527
+ 'KIT-APP-019',
528
+ node,
529
+ rule.message,
530
+ '规整表格/表单/浮层须由页面声明(view.list / view.form / overlays)与标准业务组件渲染',
531
+ );
532
+ }
533
+ }
309
534
  }
310
535
  };
311
536
 
312
- const visit = (node: import('typescript').Node, insideFunction: boolean): void => {
537
+ const checkCssSpecifier = (node: import('typescript').Node, spec: string): void => {
538
+ if (CSS_IMPORT_SPEC_RE.test(spec)) {
539
+ if (internalLab && isInternalTsModuleSpecifier?.(spec) === true) return;
540
+ pushHit(
541
+ 'KIT-APP-017',
542
+ node,
543
+ `禁止在源码中导入野生样式表 "${spec}";样式必须由框架主题求解引擎与 Tailwind 刻度类统一生成`,
544
+ '删除样式表导入,改用 kit.app.yaml#theme 14 维 DSL 与组件候选类',
545
+ );
546
+ }
547
+ };
548
+
549
+ const visit = (node: import('typescript').Node, insideFunction: boolean, insideActionOrHook: boolean): void => {
313
550
  if (ts.isTypeNode(node) || ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) {
314
551
  return;
315
552
  }
316
553
 
317
- // 1. AST .style / ['style'] 访问(全应用禁止)
554
+ // 0. KIT-APP-017:静态 import / export / import = require 野生 CSS 文件
555
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
556
+ checkCssSpecifier(node.moduleSpecifier, node.moduleSpecifier.text);
557
+ } else if (ts.isExportDeclaration(node) && node.moduleSpecifier !== undefined && ts.isStringLiteral(node.moduleSpecifier)) {
558
+ checkCssSpecifier(node.moduleSpecifier, node.moduleSpecifier.text);
559
+ } else if (
560
+ ts.isImportEqualsDeclaration(node)
561
+ && ts.isExternalModuleReference(node.moduleReference)
562
+ && ts.isStringLiteral(node.moduleReference.expression)
563
+ ) {
564
+ checkCssSpecifier(node.moduleReference.expression, node.moduleReference.expression.text);
565
+ }
566
+
567
+ // 1. AST .style / ['style'] 访问(全应用禁止,KIT-APP-005)
318
568
  if (
319
569
  (ts.isPropertyAccessExpression(node) && node.name.text === 'style')
320
570
  || (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression) && node.argumentExpression.text === 'style')
321
571
  ) {
322
- pushHit(node, MSG_STYLE_PROP);
572
+ pushHit('KIT-APP-005', node, MSG_STYLE_PROP);
323
573
  }
324
574
 
325
- // 2. AST 非组件目录禁止操作 .className / .classList
575
+ // 2. AST 非组件目录禁止操作 .className / .classList(KIT-APP-005)
326
576
  if (!inComponentsDir) {
327
577
  const propName = ts.isPropertyAccessExpression(node)
328
578
  ? node.name.text
329
579
  : (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression) ? node.argumentExpression.text : undefined);
330
580
  if (propName === 'className' || propName === 'classList') {
331
- pushHit(node, MSG_NON_COMP_CLASS);
581
+ pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
332
582
  }
333
583
  }
334
584
 
335
585
  // 3. AST 函数调用检查
336
586
  if (ts.isCallExpression(node)) {
587
+ // 3a. KIT-APP-017:动态 import('...css') / require('...css')
588
+ if (node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
589
+ checkCssSpecifier(node.arguments[0], node.arguments[0].text);
590
+ } else if (ts.isIdentifier(node.expression) && node.expression.text === 'require' && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
591
+ checkCssSpecifier(node.arguments[0], node.arguments[0].text);
592
+ }
593
+
337
594
  const calleeName = ts.isIdentifier(node.expression)
338
595
  ? node.expression.text
339
- : (ts.isPropertyAccessExpression(node.expression) ? node.expression.name.text : undefined);
596
+ : propertyAccessName(ts, node.expression);
597
+
598
+ // 3b. KIT-APP-018(非 internalLab):全应用禁命令式浮层、document.body 挂载与伪造 Symbol.for('soma-kit.*')
599
+ if (!internalLab) {
600
+ if (calleeName === 'showModal') {
601
+ pushHit('KIT-APP-018', node, '禁止调用 showModal() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer)或框架浮层端口', '移除命令式 showModal,改用页面 overlays 声明');
602
+ } else if (calleeName === 'showPopover') {
603
+ pushHit('KIT-APP-018', node, '禁止调用 showPopover() 打开命令式原生浮层;请改用页面声明 overlays 或框架浮层端口', '移除命令式 showPopover,改用页面 overlays 或框架浮层端口');
604
+ }
605
+ if (
606
+ (ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))
607
+ && calleeName !== undefined
608
+ && BODY_MUTATION_METHODS.has(calleeName)
609
+ && isDocumentBodyExpr(ts, node.expression.expression)
610
+ ) {
611
+ pushHit('KIT-APP-018', node, `禁止调用 document.body.${calleeName}() 命令式挂载浮层或野生 DOM 节点`, '浮层必须通过页面 overlays 或框架浮层端口托管');
612
+ }
613
+ if (isSymbolForCall(ts, node) && node.arguments.length >= 1) {
614
+ const symKey = extractStaticHtmlText(ts, node.arguments[0]!);
615
+ if (symKey.startsWith('soma-kit.')) {
616
+ pushHit('KIT-APP-018', node, `禁止在应用源码中引用或伪造 soma-kit 内部符号 Symbol.for("${symKey}")`, '移除内部符号调用,业务定制一律通过 defineKitBizComponent 登记至 bizComponents');
617
+ }
618
+ }
619
+ }
620
+
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 驱动数据');
624
+ }
340
625
 
626
+ // 3d. KIT-APP-005 + KIT-APP-018(DOM 构造与属性操作)
341
627
  if (calleeName === 'setAttribute' && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
342
628
  const attr = node.arguments[0].text.toLowerCase();
343
- if (attr === 'style') pushHit(node, MSG_SET_ATTR_STYLE);
344
- if (!inComponentsDir && attr === 'class') pushHit(node, MSG_NON_COMP_CLASS);
629
+ if (attr === 'style') pushHit('KIT-APP-005', node, MSG_SET_ATTR_STYLE);
630
+ if (!inComponentsDir && attr === 'class') pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
345
631
  } else if (calleeName === 'setAttributeNS' && node.arguments.length >= 2 && ts.isStringLiteralLike(node.arguments[1])) {
346
632
  const attr = node.arguments[1].text.toLowerCase();
347
- if (attr === 'style') pushHit(node, MSG_SET_ATTR_STYLE);
348
- if (!inComponentsDir && attr === 'class') pushHit(node, MSG_NON_COMP_CLASS);
349
- } else if (calleeName === 'createElement' && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
350
- const tag = node.arguments[0].text.toLowerCase();
633
+ if (attr === 'style') pushHit('KIT-APP-005', node, MSG_SET_ATTR_STYLE);
634
+ if (!inComponentsDir && attr === 'class') pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
635
+ } else if (calleeName === 'createElement') {
636
+ const tag = node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0]) ? node.arguments[0].text.toLowerCase() : undefined;
351
637
  if (tag === 'style') {
352
- pushHit(node, '禁止调用 createElement("style") 动态注入样式表;请统一使用 Tailwind 候选类与 --soma-* 设计令牌');
638
+ pushHit('KIT-APP-005', node, '禁止调用 createElement("style") 动态注入样式表;请统一使用 Tailwind 候选类与 --soma-* 设计令牌');
353
639
  } else if (tag === 'select') {
354
- pushHit(node, '禁止调用 createElement("select") 创建原生下拉框;请改用 mountKitSelectField 或 Select 组件');
640
+ pushHit('KIT-APP-005', node, '禁止调用 createElement("select") 创建原生下拉框;请改用 mountKitSelectField 或 Select 组件');
641
+ } else if (!internalLab && tag === 'dialog') {
642
+ pushHit('KIT-APP-018', node, '禁止调用 createElement("dialog") 创建命令式浮层;请改用页面声明 overlays(dialog / drawer)', '使用页面 *.kit.yaml 的 overlays 声明浮层');
643
+ } else if (!internalLab && !inComponentsDir) {
644
+ pushHit('KIT-APP-018', node, '非组件源码(components/ 之外)禁止调用 createElement() 命令式构造 DOM;界面必须封装为业务组件及其私有协作组件', '将视图交互内核移入 components/ 下并作为业务组件的 dataComponents 注册');
355
645
  }
646
+ } else if (!internalLab && !inComponentsDir && calleeName === 'createElementNS') {
647
+ pushHit('KIT-APP-018', node, '非组件源码(components/ 之外)禁止调用 createElementNS() 命令式构造 DOM;界面必须封装为业务组件及其私有协作组件', '将 SVG/画布交互内核移入 components/ 下并作为业务组件的 dataComponents 注册');
356
648
  } else if (calleeName === 'insertAdjacentHTML' && node.arguments.length >= 2) {
357
- checkHtmlString(node.arguments[1]!, extractStaticHtmlText(ts, node.arguments[1]!), true);
649
+ checkHtmlString(node.arguments[1]!, extractStaticHtmlText(ts, node.arguments[1]!), true, checkComponentPurity && !insideActionOrHook);
650
+ if (!internalLab && !inComponentsDir) {
651
+ pushHit('KIT-APP-018', node, '非组件源码(components/ 之外)禁止调用 insertAdjacentHTML() 写入野生 DOM;界面必须封装为业务组件', '移除非组件目录中的 DOM 写入逻辑');
652
+ }
358
653
  } else if (!inComponentsDir && (calleeName === 'addEventListener' || calleeName === 'removeEventListener' || calleeName === 'dispatchEvent')) {
359
- pushHit(node, MSG_NON_COMP_EVENT);
654
+ pushHit('KIT-APP-005', node, MSG_NON_COMP_EVENT);
360
655
  } else if (!inComponentsDir && calleeName === 'insertRule') {
361
- pushHit(node, MSG_NON_COMP_CLASS);
656
+ pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
362
657
  }
363
658
  }
364
659
 
365
- // 4. AST new CSSStyleSheet()(非组件目录禁止)
366
- if (!inComponentsDir && ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'CSSStyleSheet') {
367
- pushHit(node, MSG_NON_COMP_CLASS);
660
+ // 4. AST new CSSStyleSheet() / new XMLHttpRequest()
661
+ if (ts.isNewExpression(node) && ts.isIdentifier(node.expression)) {
662
+ if (!inComponentsDir && node.expression.text === 'CSSStyleSheet') {
663
+ pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
664
+ }
665
+ if (checkComponentPurity && !insideActionOrHook && node.expression.text === 'XMLHttpRequest') {
666
+ pushHit('KIT-APP-019', node, '禁止在组件源码中使用 new XMLHttpRequest 绕过数据与动作管道;请改用页面 behavior.from 与 defineKitActions', '移除组件内 XMLHttpRequest,改由页面数据契约与具名动作驱动');
667
+ }
368
668
  }
369
669
 
370
670
  // 5. AST 赋值表达式检查(innerHTML / outerHTML / .on* = / .type = 'range'|'date')
371
671
  if (ts.isBinaryExpression(node) && (node.operatorToken.kind === ts.SyntaxKind.EqualsToken || node.operatorToken.kind === ts.SyntaxKind.PlusEqualsToken)) {
372
672
  const leftName = propertyAccessName(ts, node.left);
373
673
  if (leftName === 'innerHTML' || leftName === 'outerHTML') {
374
- checkHtmlString(node.right, extractStaticHtmlText(ts, node.right), true);
674
+ checkHtmlString(node.right, extractStaticHtmlText(ts, node.right), true, checkComponentPurity && !insideActionOrHook);
675
+ if (!internalLab && !inComponentsDir) {
676
+ pushHit('KIT-APP-018', node, `非组件源码(components/ 之外)禁止写入 .${leftName} 构造野生 DOM;界面必须封装为业务组件`, '将交互视图封装为业务组件及其私有协作组件');
677
+ }
375
678
  } else if (node.operatorToken.kind === ts.SyntaxKind.EqualsToken && leftName !== undefined) {
376
679
  if (DOM_INLINE_ON_EVENTS.has(leftName)) {
377
- pushHit(node, MSG_INLINE_ON_EVENT);
680
+ pushHit('KIT-APP-005', node, MSG_INLINE_ON_EVENT);
378
681
  } else if (leftName === 'type' && ts.isStringLiteralLike(node.right)) {
379
682
  const val = node.right.text.toLowerCase();
380
683
  if (val === 'range') {
381
- pushHit(node, '禁止设置 input.type = "range" 创建原生滑块;请改用 soma-kit 标准组件 Range');
684
+ pushHit('KIT-APP-005', node, '禁止设置 input.type = "range" 创建原生滑块;请改用 soma-kit 标准组件 Range');
382
685
  } else if (/^(?:date|datetime-local|time|month|week)$/.test(val)) {
383
- pushHit(node, '禁止设置原生日期/时间 input.type;请改用 soma-kit 标准组件 Date / DateRange / TimePicker');
686
+ pushHit('KIT-APP-005', node, '禁止设置原生日期/时间 input.type;请改用 soma-kit 标准组件 Date / DateRange / TimePicker');
384
687
  }
385
688
  }
386
689
  }
@@ -390,30 +693,56 @@ function scanSourceWithAst(
390
693
  if (ts.isPropertyAssignment(node)) {
391
694
  const propName = ts.isIdentifier(node.name) || ts.isStringLiteral(node.name) ? node.name.text : undefined;
392
695
  if (propName === 'templateHtml') {
393
- checkHtmlString(node.initializer, extractStaticHtmlText(ts, node.initializer), true);
696
+ checkHtmlString(node.initializer, extractStaticHtmlText(ts, node.initializer), true, checkComponentPurity && !insideActionOrHook);
394
697
  }
395
698
  }
396
699
 
397
- // 7. 函数体内的字符串/模板字面量中的原生控件标签(如 renderSneaky 返回 `<select>...`),不误伤顶层纯数据字典
700
+ // 7. 函数体内的字符串/模板字面量检查(不误伤顶层纯数据字典)
398
701
  if (insideFunction && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateExpression(node))) {
399
- checkHtmlString(node, extractStaticHtmlText(ts, node), false);
702
+ const text = extractStaticHtmlText(ts, node);
703
+ checkHtmlString(node, text, false, checkComponentPurity && !insideActionOrHook);
704
+ if (hasBizComponentDef && !insideActionOrHook && HARDCODED_API_PATH_RE.test(text)) {
705
+ pushHit(
706
+ 'KIT-APP-019',
707
+ node,
708
+ '禁止在业务组件源码中硬编码 "/api/..." 接口路径;业务组件必须纯声明式装数据,接口地址须从页面传入的 input.objects(behavior.from / actions)读取',
709
+ '移除硬编码接口路径,改为从 input.objects 读取页面声明的 behavior.from 或具名动作',
710
+ );
711
+ }
712
+ }
713
+
714
+ let nextInsideActionOrHook = insideActionOrHook;
715
+ if (!nextInsideActionOrHook) {
716
+ if (ts.isCallExpression(node)) {
717
+ const callName = ts.isIdentifier(node.expression) ? node.expression.text : propertyAccessName(ts, node.expression);
718
+ if (callName === 'defineKitActions') nextInsideActionOrHook = true;
719
+ } else if (ts.isPropertyAssignment(node)) {
720
+ const propName = ts.isIdentifier(node.name) || ts.isStringLiteral(node.name) ? node.name.text : undefined;
721
+ if (propName !== undefined && APP_HOOK_PROP_NAMES.has(propName)) nextInsideActionOrHook = true;
722
+ }
400
723
  }
401
724
 
402
725
  const nextInsideFunction = insideFunction || ts.isFunctionLike(node);
403
- ts.forEachChild(node, (child) => visit(child, nextInsideFunction));
726
+ ts.forEachChild(node, (child) => visit(child, nextInsideFunction, nextInsideActionOrHook));
404
727
  };
405
728
 
406
- visit(sourceFile, false);
729
+ visit(sourceFile, false, false);
407
730
  return hits;
408
731
  }
409
732
 
410
733
  /**
411
- * 服务端编译与 `soma kit check` 全量源码 AST 门禁:
412
- * 递归扫描应用根目录 `<root>` 下全部 `.ts` / `.tsx` / `.js` / `.mjs` 源码(跳过 `node_modules` / `dist` / `tests` / `.soma` 等),
413
- * 1) 全应用禁止:非标原生控件、<style>、AST `.style` 访问、`setAttribute('style', ...)`、`innerHTML`/`outerHTML`/`templateHtml` 内联 `style="..."` 或 `on*`、`.onclick =` 等赋值;
414
- * 2) 非 `components/` 目录(如 `views/**`、`actions/**`、`api/**`、`soma.app.ts`)额外禁止:操作 `.className` / `.classList` / `setAttribute('class', ...)` / `CSSStyleSheet` 与手绑 `addEventListener`。
734
+ * 服务端编译与 `soma kit check` 全量源码文件与 AST 门禁:
735
+ * 递归扫描应用根目录 `<root>`(跳过 `node_modules` / `dist` / `tests` / `.soma` 等):
736
+ * 1) KIT-APP-005(全应用始终生效):非标原生控件、<style>、AST `.style` 访问、`setAttribute('style', ...)`、`innerHTML`/`outerHTML`/`templateHtml` 内联 `style="..."` 或 `on*`、`.onclick =`;非 `components/` 禁 `.className`/`.classList`/`setAttribute('class', ...)`/`CSSStyleSheet`/`addEventListener`;
737
+ * 2) KIT-APP-017(全应用始终生效):禁野生 CSS(.css/.scss/.less/.sass/.styl 文件与 import/require)及 `pages/`、`src/web/`、`views/`、`components/` 下手写 `.html`/`.htm`;
738
+ * 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/...'`。
415
740
  */
416
- export async function scanAppComponentSources(root: string): Promise<KitDiagnostic[]> {
741
+ export async function scanAppComponentSources(
742
+ root: string,
743
+ opts?: { readonly internalLab?: boolean },
744
+ ): Promise<KitDiagnostic[]> {
745
+ const internalLab = opts?.internalLab === true;
417
746
  const fsSpec = 'node:fs/promises';
418
747
  const pathSpec = 'node:path';
419
748
  const tsSpec = 'typescript';
@@ -439,15 +768,68 @@ export async function scanAppComponentSources(root: string): Promise<KitDiagnost
439
768
  await walk(full);
440
769
  continue;
441
770
  }
771
+ const rel = path.relative(root, full).split(path.sep).join('/');
772
+
773
+ // KIT-APP-017:应用目录内零野生 CSS 文件
774
+ if (CSS_FILE_EXT_RE.test(entry.name)) {
775
+ diagnostics.push({
776
+ code: 'KIT-APP-017',
777
+ path: rel,
778
+ message: `禁止在应用目录放置野生样式表文件 "${rel}";样式必须由框架主题引擎与 Tailwind 刻度类统一生成`,
779
+ hint: '删除自定义 CSS/SCSS/LESS 文件,改用 kit.app.yaml#theme 14 维主题 DSL 声明外观',
780
+ });
781
+ continue;
782
+ }
783
+
784
+ // KIT-APP-017:pages/、src/web/、views/、components/ 禁止手写野生 .html/.htm(跳过 public/)
785
+ if (HTML_FILE_EXT_RE.test(entry.name) && WILD_HTML_DIR_RE.test(rel) && !rel.startsWith('public/') && !rel.includes('/public/')) {
786
+ diagnostics.push({
787
+ code: 'KIT-APP-017',
788
+ path: rel,
789
+ message: `禁止在源码目录手写野生 HTML 文件 "${rel}";页面必须通过 pages/*.kit.yaml 声明式编译生成`,
790
+ hint: '删除手写 HTML 文件,改用 pages/*.kit.yaml + 业务组件声明页面',
791
+ });
792
+ continue;
793
+ }
794
+
442
795
  if (!/\.(?:ts|tsx|js|mjs)$/.test(entry.name) || entry.name.endsWith('.d.ts')) continue;
443
796
  const code = await fs.readFile(full, 'utf8');
444
- const rel = path.relative(root, full).split(path.sep).join('/');
445
- const inComponentsDir = rel === 'components' || rel.startsWith('components/');
446
- for (const hit of scanSourceWithAst(ts, full, code, inComponentsDir)) {
797
+ const siblingNames = internalLab ? new Set(entries.filter((e) => !e.isDirectory()).map((e) => e.name)) : undefined;
798
+ const isInternalTsModuleSpecifier = internalLab
799
+ ? (spec: string): boolean => {
800
+ if (!spec.startsWith('./')) return false;
801
+ const base = spec.slice(2);
802
+ if (base.includes('/')) return false;
803
+ return siblingNames!.has(`${base}.ts`) || siblingNames!.has(`${base}.tsx`) || siblingNames!.has(`${base}.mts`);
804
+ }
805
+ : undefined;
806
+ const inComponentsDir =
807
+ rel === 'components'
808
+ || rel.startsWith('components/')
809
+ || rel === 'src/web/components'
810
+ || rel.startsWith('src/web/components/');
811
+ const isNonCompAllowedIoDir =
812
+ rel.startsWith('api/')
813
+ || rel.startsWith('bff/')
814
+ || rel.startsWith('actions/')
815
+ || rel.startsWith('views/')
816
+ || rel.startsWith('src/bff/')
817
+ || rel.startsWith('src/web/actions/')
818
+ || rel.startsWith('src/web/views/')
819
+ || rel.startsWith('server/')
820
+ || /^soma\.server\./.test(rel)
821
+ || /\/soma\.server\./.test(rel);
822
+ for (const hit of scanSourceWithAst(ts, full, code, {
823
+ inComponentsDir,
824
+ isNonCompAllowedIoDir,
825
+ internalLab,
826
+ ...(isInternalTsModuleSpecifier !== undefined ? { isInternalTsModuleSpecifier } : {}),
827
+ })) {
447
828
  diagnostics.push({
448
- code: 'KIT-APP-005',
829
+ code: hit.code,
449
830
  path: `${rel}:${hit.line}`,
450
831
  message: hit.message,
832
+ ...(hit.hint !== undefined ? { hint: hit.hint } : {}),
451
833
  });
452
834
  }
453
835
  }