soma-kit 0.1.10 → 0.1.12

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 (302) hide show
  1. package/README.md +103 -110
  2. package/bin/soma-kit.mjs +1 -1
  3. package/bin/soma.mjs +22 -0
  4. package/package.json +13 -7
  5. package/packs/finance/reconcile-board.ts +5 -2
  6. package/packs/finance/reconcile-desk/compile.ts +3 -2
  7. package/spec/generated/kit-app.schema.json +776 -38
  8. package/spec/generated/kit-page.schema.json +1613 -224
  9. package/spec/kit-grammar.json +770 -529
  10. package/spec/kit-grammar.schema.json +1962 -392
  11. package/src/app/app-config.ts +371 -347
  12. package/src/app/component-gate.ts +12 -15
  13. package/src/app/compose-apps.ts +79 -8
  14. package/src/app/define-kit-actions.ts +245 -41
  15. package/src/app/define-kit-app.ts +174 -31
  16. package/src/app/define-kit-view.ts +100 -0
  17. package/src/app/envelope.ts +1 -161
  18. package/src/app/index.ts +13 -2
  19. package/src/app/kit-view-context.ts +290 -0
  20. package/src/app/notify-renderer.ts +1 -115
  21. package/src/app/paged-list-adapter.ts +1 -240
  22. package/src/app/server-pages.ts +8 -2
  23. package/src/app/server.ts +491 -101
  24. package/src/app/submit.types.ts +1 -1
  25. package/src/app/theme-endpoint.ts +63 -0
  26. package/src/app/theme-runtime-shared.ts +1 -0
  27. package/src/app/theme-runtime.ts +663 -0
  28. package/src/base/action-busy.ts +2 -2
  29. package/src/base/action-gate.ts +4 -255
  30. package/src/base/action-slots.ts +47 -0
  31. package/src/base/alert.ts +5 -3
  32. package/src/base/avatar.ts +2 -2
  33. package/src/base/button.ts +46 -29
  34. package/src/base/cascader.ts +11 -12
  35. package/src/base/check-core.ts +1 -1
  36. package/src/base/choice.ts +28 -26
  37. package/src/base/class-candidates.ts +17 -0
  38. package/src/base/color-picker.ts +6 -6
  39. package/src/base/combobox.ts +5 -3
  40. package/src/base/command-palette.ts +9 -5
  41. package/src/base/countdown.ts +1 -1
  42. package/src/base/date-range.ts +25 -11
  43. package/src/base/date.ts +85 -17
  44. package/src/base/divider.ts +2 -2
  45. package/src/base/fab.ts +11 -4
  46. package/src/base/image.ts +1 -1
  47. package/src/base/index.ts +9 -3
  48. package/src/base/input.ts +42 -13
  49. package/src/base/kbd.ts +3 -1
  50. package/src/base/link.ts +4 -4
  51. package/src/base/listbox-core.ts +50 -30
  52. package/src/base/loading-gate.ts +133 -0
  53. package/src/base/mentions.ts +5 -5
  54. package/src/base/menu-button.ts +6 -1
  55. package/src/base/menu-core.ts +4 -0
  56. package/src/base/motion/aura.ts +2 -2
  57. package/src/base/motion/hover-3d.ts +2 -2
  58. package/src/base/motion/hover-gallery.ts +2 -2
  59. package/src/base/motion/marquee.ts +2 -2
  60. package/src/base/motion/text-rotate.ts +2 -2
  61. package/src/base/number.ts +93 -80
  62. package/src/base/otp.ts +4 -1
  63. package/src/base/permission-gate.ts +6 -0
  64. package/src/base/popover.ts +40 -8
  65. package/src/base/popup.ts +79 -14
  66. package/src/base/price-text.ts +2 -2
  67. package/src/base/progress.ts +2 -2
  68. package/src/base/qr-code.ts +4 -4
  69. package/src/base/qty-stepper.ts +9 -3
  70. package/src/base/range.ts +2 -2
  71. package/src/base/rating.ts +1 -1
  72. package/src/base/segmented.ts +4 -0
  73. package/src/base/select.ts +4 -3
  74. package/src/base/shared.ts +221 -29
  75. package/src/base/swap.ts +4 -1
  76. package/src/base/switch.ts +1 -1
  77. package/src/base/tag-input.ts +14 -10
  78. package/src/base/tag.ts +5 -1
  79. package/src/base/text.ts +39 -6
  80. package/src/base/textarea.ts +37 -11
  81. package/src/base/time-picker.ts +12 -9
  82. package/src/base/tree-select.ts +15 -8
  83. package/src/base/upload.ts +34 -5
  84. package/src/base/virtual-list.ts +107 -1
  85. package/src/biz/approval-desk/compile.ts +23 -41
  86. package/src/biz/auth-panel/compile.ts +37 -52
  87. package/src/biz/auth-panel/index.ts +1 -1
  88. package/src/biz/category-crud/compile.ts +22 -36
  89. package/src/biz/checkout-page/compile.ts +21 -5
  90. package/src/biz/compose.ts +13 -27
  91. package/src/biz/define.ts +5 -4
  92. package/src/biz/import-wizard/compile.ts +22 -26
  93. package/src/biz/import-wizard/hub.ts +126 -61
  94. package/src/biz/import-wizard/shell.ts +3 -3
  95. package/src/biz/index.ts +3 -3
  96. package/src/biz/landing-page/compile.ts +19 -3
  97. package/src/biz/link/hub.ts +49 -20
  98. package/src/biz/link/shared.ts +115 -118
  99. package/src/biz/master-sub/compile.ts +31 -44
  100. package/src/biz/multi-board/compile.ts +34 -49
  101. package/src/biz/multi-board/index.ts +18 -1
  102. package/src/biz/multi-board/shell.ts +24 -15
  103. package/src/biz/notification-center/compile.ts +21 -33
  104. package/src/biz/page-templates/domain-templates.ts +80 -13
  105. package/src/biz/page-templates/result-page/compile.ts +11 -2
  106. package/src/biz/page-templates/shared.ts +34 -36
  107. package/src/biz/record-detail/compile.ts +47 -42
  108. package/src/biz/record-detail/index.ts +11 -1
  109. package/src/biz/settings-center/compile.ts +6 -5
  110. package/src/biz/shared/action-host.ts +91 -211
  111. package/src/biz/shared/compile-helpers.ts +80 -0
  112. package/src/biz/shared/coordinator.ts +486 -83
  113. package/src/biz/shared/index.ts +8 -2
  114. package/src/biz/shared/overlay-shell.ts +80 -0
  115. package/src/biz/shared/pipes.ts +43 -30
  116. package/src/biz/shared/remove-key.ts +6 -0
  117. package/src/biz/shared/remove-wire.ts +29 -0
  118. package/src/biz/shared/runtime-hub.ts +216 -24
  119. package/src/biz/single-form/compile.ts +15 -37
  120. package/src/biz/standard-crud/compile.ts +62 -107
  121. package/src/biz/standard-crud/shell.ts +16 -66
  122. package/src/biz/step-form/compile.ts +26 -97
  123. package/src/biz/step-form/hub.ts +34 -41
  124. package/src/biz/types.ts +4 -3
  125. package/src/cli/core-imports.ts +54 -0
  126. package/src/cli/kit-cli.ts +130 -26
  127. package/src/cli/kit-init.ts +222 -0
  128. package/src/cli/service-endpoint-check.ts +425 -0
  129. package/src/cli/source-path-check.d.mts +17 -0
  130. package/src/cli/source-path-check.mjs +334 -0
  131. package/src/cli/view-writes.ts +752 -0
  132. package/src/compile/action-host-attach.ts +21 -29
  133. package/src/compile/closed-set.ts +509 -0
  134. package/src/compile/compile-page.ts +219 -72
  135. package/src/compile/component-candidates.ts +1 -1
  136. package/src/compile/hints.ts +30 -1
  137. package/src/compile/index.ts +1 -0
  138. package/src/compile/kit-error.ts +1 -0
  139. package/src/compile/locate.ts +21 -1
  140. package/src/compile/parse.ts +370 -41
  141. package/src/compile/redirect.ts +6 -2
  142. package/src/compile/styles.ts +35 -2
  143. package/src/compile/types.ts +18 -2
  144. package/src/compile/view-check.ts +151 -0
  145. package/src/data/amount-breakdown.ts +2 -2
  146. package/src/data/anchor-nav.ts +2 -2
  147. package/src/data/approval-flow.ts +2 -2
  148. package/src/data/assignment-picker.ts +40 -29
  149. package/src/data/async-result-panel.ts +62 -6
  150. package/src/data/breadcrumbs.ts +2 -2
  151. package/src/data/calendar.ts +22 -25
  152. package/src/data/carousel.ts +5 -2
  153. package/src/data/chart.ts +42 -34
  154. package/src/data/checklist.ts +2 -2
  155. package/src/data/code-view.ts +4 -2
  156. package/src/data/comment-thread.ts +5 -2
  157. package/src/data/confirm-dialog.ts +10 -0
  158. package/src/data/context-menu.ts +29 -37
  159. package/src/data/d9-util.ts +2 -18
  160. package/src/data/diff.ts +4 -2
  161. package/src/data/dock.ts +2 -2
  162. package/src/data/embed.ts +2 -1
  163. package/src/data/field-mapper.ts +31 -26
  164. package/src/data/flow-editor-contract.ts +1 -1
  165. package/src/data/flow-editor.ts +89 -100
  166. package/src/data/flow-node-options.ts +90 -0
  167. package/src/data/flow-remote-options.ts +0 -103
  168. package/src/data/footer.ts +2 -2
  169. package/src/data/form-draft-registry.ts +2 -4
  170. package/src/data/gantt.ts +14 -17
  171. package/src/data/hero.ts +2 -2
  172. package/src/data/image-viewer.ts +20 -26
  173. package/src/data/index.ts +0 -2
  174. package/src/data/item-list.ts +31 -22
  175. package/src/data/kanban.ts +43 -42
  176. package/src/data/media-grid.ts +14 -19
  177. package/src/data/menu.ts +2 -2
  178. package/src/data/mockup.ts +2 -2
  179. package/src/data/modal-dialog.ts +22 -18
  180. package/src/data/navbar.ts +7 -2
  181. package/src/data/notify-renderer.ts +235 -0
  182. package/src/data/object-form.ts +1036 -648
  183. package/src/data/pager.ts +65 -29
  184. package/src/data/permission-matrix.ts +20 -21
  185. package/src/data/permission-tree.ts +28 -26
  186. package/src/data/pricing-table.ts +9 -3
  187. package/src/data/reaction-bar.ts +77 -88
  188. package/src/data/read-rollback.ts +73 -0
  189. package/src/data/record-card.ts +3 -3
  190. package/src/data/record-picker.ts +93 -50
  191. package/src/data/redirect.ts +32 -32
  192. package/src/data/remote-options.ts +13 -6
  193. package/src/data/request-console.ts +5 -3
  194. package/src/data/resident.ts +2 -1
  195. package/src/data/result-panel.ts +4 -2
  196. package/src/data/rich-text.ts +45 -55
  197. package/src/data/row-editor.ts +285 -52
  198. package/src/data/rule-builder.ts +18 -12
  199. package/src/data/shape-util.ts +4 -0
  200. package/src/data/stat-group.ts +243 -101
  201. package/src/data/static-registry.ts +22 -11
  202. package/src/data/steps.ts +2 -2
  203. package/src/data/survey.ts +24 -29
  204. package/src/data/system-switcher.ts +2 -2
  205. package/src/data/timeline.ts +2 -2
  206. package/src/data/tour-guide.ts +22 -29
  207. package/src/data/transfer.ts +27 -23
  208. package/src/data/tree-table.ts +96 -48
  209. package/src/data/tree.ts +27 -34
  210. package/src/data/trend-line.ts +6 -24
  211. package/src/data/virtual-rows.ts +118 -76
  212. package/src/data/watermark.ts +2 -2
  213. package/src/data/wrap.ts +63 -38
  214. package/src/frames/blank-frame.ts +1 -0
  215. package/src/frames/index.ts +2 -2
  216. package/src/frames/page-bar.ts +12 -11
  217. package/src/frames/page-header.ts +14 -5
  218. package/src/frames/page-status.ts +2 -2
  219. package/src/frames/shared.ts +23 -17
  220. package/src/frames/single-frame.ts +1 -0
  221. package/src/frames/split-frame/shell.ts +5 -5
  222. package/src/frames/split-frame/wiring.ts +2 -2
  223. package/src/frames/tabs-frame/shell.ts +2 -13
  224. package/src/frames/tabs-frame/wiring.ts +4 -8
  225. package/src/frames/top-main-frame.ts +1 -0
  226. package/src/frames/types.ts +13 -2
  227. package/src/frames/workspace-frame/extras.ts +20 -4
  228. package/src/frames/workspace-frame/index.ts +1 -1
  229. package/src/frames/workspace-frame/shell.ts +1 -0
  230. package/src/frames/workspace-frame/state.ts +13 -6
  231. package/src/frames/workspace-frame/view.ts +119 -25
  232. package/src/generated/kit-grammar-runtime.ts +430 -366
  233. package/src/generated/page-origin.ts +0 -11
  234. package/src/i18n/kit-text.ts +23 -27
  235. package/src/index.ts +2 -1
  236. package/src/object-renderer/action-gate.ts +11 -147
  237. package/src/object-renderer/arrange.ts +71 -77
  238. package/src/object-renderer/collapse-wiring.ts +2 -2
  239. package/src/object-renderer/collection-expand.ts +2 -2
  240. package/src/object-renderer/collection-parts.ts +216 -100
  241. package/src/object-renderer/collection-table.ts +180 -42
  242. package/src/object-renderer/collection.ts +95 -79
  243. package/src/object-renderer/compile-data.ts +85 -100
  244. package/src/object-renderer/crud-bridge.ts +32 -0
  245. package/src/object-renderer/defaults.ts +8 -14
  246. package/src/object-renderer/display-checks.ts +3 -24
  247. package/src/object-renderer/emit-events.ts +186 -172
  248. package/src/object-renderer/emit-object.ts +15 -2
  249. package/src/object-renderer/emit-static.ts +174 -132
  250. package/src/object-renderer/field-value.ts +593 -396
  251. package/src/object-renderer/filter-reload.ts +70 -0
  252. package/src/object-renderer/form-detail.ts +112 -2
  253. package/src/object-renderer/index.ts +26 -0
  254. package/src/object-renderer/key-field.ts +12 -0
  255. package/src/object-renderer/linkage.ts +7 -270
  256. package/src/object-renderer/merge-class.ts +18 -1
  257. package/src/object-renderer/path-pick.ts +27 -0
  258. package/src/object-renderer/render-object.ts +405 -86
  259. package/src/object-renderer/request-actions.ts +230 -249
  260. package/src/object-renderer/table-actions.ts +195 -95
  261. package/src/object-renderer/table-summary.ts +2 -2
  262. package/src/object-renderer/table-tools.ts +418 -84
  263. package/src/object-renderer/types.ts +128 -122
  264. package/src/object-renderer/view-binding.ts +196 -0
  265. package/src/page-target/ai-surface.ts +37 -0
  266. package/src/page-target/compile.ts +48 -8
  267. package/src/page-target/index.ts +8 -1
  268. package/src/page-target/intent-schema.ts +154 -28
  269. package/src/page-target/target.ts +257 -50
  270. package/src/page-target/writer-policy.ts +14 -3
  271. package/src/recipes/container.ts +165 -0
  272. package/src/recipes/control.ts +219 -0
  273. package/src/recipes/index.ts +263 -0
  274. package/src/recipes/overlay.ts +182 -0
  275. package/src/recipes/state.ts +70 -0
  276. package/src/recipes/table-row.ts +51 -0
  277. package/src/recipes/typography.ts +87 -0
  278. package/src/shared/action-field-guard.ts +41 -0
  279. package/src/shared/envelope.ts +207 -0
  280. package/src/shared/escape.ts +57 -0
  281. package/src/shared/kit-error.ts +21 -0
  282. package/src/shared/paged-list-adapter.ts +240 -0
  283. package/src/shared/path-guard.ts +127 -0
  284. package/src/shared/theme-runtime-shared.ts +175 -0
  285. package/src/shared/view-info.ts +10 -0
  286. package/src/theme/index.ts +12 -0
  287. package/src/theme/kit-theme-text.ts +1 -1
  288. package/src/theme/kit-theme.css +38 -1
  289. package/src/theme/kit-theme.tpl +38 -1
  290. package/src/theme/nine-dim-structure.ts +77 -0
  291. package/src/theme/surface-layers.ts +97 -0
  292. package/src/theme/theme-tokens.ts +85 -79
  293. package/src/theme/theme-types.ts +71 -0
  294. package/src/theme/typography.ts +17 -17
  295. package/src/biz/shared/step-values.ts +0 -25
  296. package/src/biz/step-form/steps-ref.ts +0 -112
  297. package/src/data/options-bus.ts +0 -24
  298. package/src/data/prompt-dialog.ts +0 -235
  299. package/src/object-renderer/adopt-gate.ts +0 -333
  300. package/src/object-renderer/field-policy.ts +0 -89
  301. package/src/object-renderer/outcome-draft.ts +0 -61
  302. package/src/theme/nine-dim-palettes.ts +0 -1278
@@ -0,0 +1,752 @@
1
+ // data 对象扫描编译的检查层(`soma kit check`):扫描应用里所有定义展示对象(defineKitView)的源文件(含 `*.view.*` 及 soma.app.ts 引用的视图文件),
2
+ // 以 defineKitView 的返回类(state 初值扫出的形状)为准,核对方法体里对数组成员的写入:
3
+ // KIT-VIEW-003 展示对象方法里 ctx.form / ctx.request / ctx.data / ctx.reload 引用的对象名或动作 id 不在绑定页面的 objects / behavior.actions 中
4
+ // KIT-VIEW-008 数组成员原地变异(push / splice / sort …)、下标赋值、元素字段赋值、length 赋值——core 不代理数组,不会触发刷新
5
+ // KIT-VIEW-009 把对象成员赋给另一个成员(view.a = view.b)——同一对象挂多路径,刷新错位(state 初值引用同一对象在定义期同码拒绝)
6
+ // 判据(变异方法名单、接收者、形状推导、扫描)只在 soma-foundation/view-state 一份(名单真源 soma-design/spec/pipeline/view-state-rules.json),
7
+ // 与类型层(ReadonlyArray)、运行时 dev 层(core 代理抛 CORE-REACTIVE-WRITE)同判据。
8
+ // 局限:词法扫描,不做数据流(经局部变量转手后的写入不识别),详见 scanViewMethodWrites 注释;漏的由类型层与 dev 层兜底。
9
+ import {
10
+ blankCommentsAndStrings,
11
+ inferStateShape,
12
+ mergeStateShapes,
13
+ scanViewMethodWrites,
14
+ VIEW_REPLACE_HINT,
15
+ type ViewStateShape,
16
+ } from 'soma-foundation/view-state';
17
+ import type { KitDiagnostic } from '../object-renderer/types';
18
+ import { readKitViewInfo } from '../shared/view-info';
19
+ import { isRelativePathValue } from '../shared/path-guard';
20
+ import { scanPathSourceUsages } from './source-path-check.mjs';
21
+
22
+ const SKIP_DIRS = new Set(['node_modules', 'tests', 'test', 'dist', 'build', 'coverage']);
23
+ const SOURCE_FILE = /\.[cm]?[jt]sx?$/;
24
+ const VIEW_FILE = /\.view\.[cm]?[jt]sx?$/;
25
+ const DEFINE_KIT_VIEW_CALL = /\bdefineKitView\s*(?:<[\s\S]*?>)?\s*\(/;
26
+
27
+ export interface KitPageTargetSummary {
28
+ readonly viewName: string;
29
+ readonly pageFile: string;
30
+ readonly objects: ReadonlySet<string>;
31
+ readonly actionsByObject: ReadonlyMap<string, ReadonlySet<string>>;
32
+ }
33
+
34
+ const isRec = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object' && !Array.isArray(v);
35
+
36
+ /** 从已解析的页面 YAML 对象提取绑定展示对象的页面对象名集合与各对象的动作 id 集合 */
37
+ export function extractPageTargetFromParsed(raw: unknown, pageFile: string): KitPageTargetSummary | undefined {
38
+ if (!isRec(raw) || !isRec(raw.page)) return undefined;
39
+ const viewName = typeof raw.page.view === 'string' && raw.page.view.trim() !== '' ? raw.page.view.trim() : undefined;
40
+ if (viewName === undefined) return undefined;
41
+
42
+ const objects = new Set<string>();
43
+ const actionsByObject = new Map<string, Set<string>>();
44
+
45
+ const ensureObj = (name: string): Set<string> => {
46
+ objects.add(name);
47
+ let set = actionsByObject.get(name);
48
+ if (set === undefined) {
49
+ set = new Set<string>();
50
+ actionsByObject.set(name, set);
51
+ }
52
+ return set;
53
+ };
54
+
55
+ const recordObjectDecl = (objDecl: Record<string, unknown>, names: readonly string[]): void => {
56
+ const sets = names.filter((n) => n !== '').map((n) => ensureObj(n));
57
+ const behavior = isRec(objDecl.behavior) ? objDecl.behavior : undefined;
58
+ const actions = behavior && Array.isArray(behavior.actions) ? behavior.actions : [];
59
+ for (const act of actions) {
60
+ if (isRec(act) && typeof act.id === 'string' && act.id.trim() !== '') {
61
+ for (const s of sets) s.add(act.id.trim());
62
+ }
63
+ }
64
+ };
65
+
66
+ const isObjectDecl = (v: unknown): v is Record<string, unknown> =>
67
+ isRec(v) && ('schema' in v || 'behavior' in v || 'view' in v || 'title' in v);
68
+
69
+ const inspectProduct = (product: unknown, slotPrefix?: string): void => {
70
+ if (!isRec(product) || !isRec(product.objects)) return;
71
+ for (const [role, val] of Object.entries(product.objects)) {
72
+ if (!isRec(val)) continue;
73
+ if (role === 'overlays') {
74
+ for (const [ovName, ovDecl] of Object.entries(val)) {
75
+ if (isRec(ovDecl)) {
76
+ recordObjectDecl(ovDecl, [ovName, ...(slotPrefix ? [`${slotPrefix}_${ovName}`] : [])]);
77
+ }
78
+ }
79
+ } else if (!('schema' in val) && !('behavior' in val) && !('view' in val) && Object.keys(val).length > 0 && Object.values(val).every(isRec)) {
80
+ ensureObj(role);
81
+ for (const [subName, subDecl] of Object.entries(val)) {
82
+ if (isRec(subDecl)) {
83
+ recordObjectDecl(subDecl, [subName, `${role}_${subName}`, ...(slotPrefix ? [`${slotPrefix}_${subName}`] : [])]);
84
+ }
85
+ }
86
+ } else if (isObjectDecl(val)) {
87
+ recordObjectDecl(val, [role, ...(slotPrefix ? [`${slotPrefix}_${role}`] : [])]);
88
+ }
89
+ }
90
+ };
91
+
92
+ if (isRec(raw.product)) inspectProduct(raw.product, 'main');
93
+ if (isRec(raw.frame) && isRec(raw.frame.slots)) {
94
+ for (const [slot, slotVal] of Object.entries(raw.frame.slots)) {
95
+ if (Array.isArray(slotVal)) {
96
+ for (const tab of slotVal) {
97
+ if (isRec(tab) && isRec(tab.product)) {
98
+ inspectProduct(tab.product, typeof tab.id === 'string' ? tab.id : slot);
99
+ }
100
+ }
101
+ } else if (isRec(slotVal)) {
102
+ inspectProduct(slotVal, slot);
103
+ }
104
+ }
105
+ }
106
+
107
+ return { viewName, pageFile, objects, actionsByObject };
108
+ }
109
+
110
+ /** 抹除单行与多行注释,但完整保留字符串字面量与换行符(字符下标、行号、列号与原文本 100% 对齐) */
111
+ function stripCommentsKeepStrings(source: string): string {
112
+ const chars = Array.from(source);
113
+ const n = chars.length;
114
+ let i = 0;
115
+ while (i < n) {
116
+ const ch = chars[i]!;
117
+ const next = i + 1 < n ? chars[i + 1] : '';
118
+ if (ch === '/' && next === '/') {
119
+ chars[i] = ' ';
120
+ chars[i + 1] = ' ';
121
+ i += 2;
122
+ while (i < n && chars[i] !== '\n') {
123
+ chars[i] = ' ';
124
+ i++;
125
+ }
126
+ continue;
127
+ }
128
+ if (ch === '/' && next === '*') {
129
+ chars[i] = ' ';
130
+ chars[i + 1] = ' ';
131
+ i += 2;
132
+ while (i < n && !(chars[i] === '*' && i + 1 < n && chars[i + 1] === '/')) {
133
+ if (chars[i] !== '\n') chars[i] = ' ';
134
+ i++;
135
+ }
136
+ if (i + 1 < n) {
137
+ chars[i] = ' ';
138
+ chars[i + 1] = ' ';
139
+ i += 2;
140
+ }
141
+ continue;
142
+ }
143
+ if (ch === "'" || ch === '"' || ch === '`') {
144
+ const quote = ch;
145
+ i++;
146
+ while (i < n && chars[i] !== quote) {
147
+ if (chars[i] === '\\' && i + 1 < n) {
148
+ i += 2;
149
+ continue;
150
+ }
151
+ i++;
152
+ }
153
+ if (i < n) i++;
154
+ continue;
155
+ }
156
+ i++;
157
+ }
158
+ return chars.join('');
159
+ }
160
+
161
+ function lineColAt(source: string, index: number): { line: number; column: number } {
162
+ let line = 1;
163
+ let lastNewline = -1;
164
+ for (let i = 0; i < index && i < source.length; i++) {
165
+ if (source.charCodeAt(i) === 10) {
166
+ line++;
167
+ lastNewline = i;
168
+ }
169
+ }
170
+ return { line, column: index - lastNewline };
171
+ }
172
+
173
+ /** 在已抹除注释和字符串的文本中配对括号,返回匹配的右括号下标(未找到返回 -1) */
174
+ function findMatchingBracket(clean: string, openIndex: number, openChar: string, closeChar: string): number {
175
+ let depth = 0;
176
+ for (let i = openIndex; i < clean.length; i++) {
177
+ const ch = clean[i]!;
178
+ if (ch === openChar) depth++;
179
+ else if (ch === closeChar) {
180
+ depth--;
181
+ if (depth === 0) return i;
182
+ }
183
+ }
184
+ return -1;
185
+ }
186
+
187
+ /**
188
+ * 扫描展示对象方法源码中的 ctx.form('对象名') / ctx.request('对象名', '动作id') / ctx.data('对象名') / ctx.reload('对象名')
189
+ * (含 cascadeOptions / watchDraftFlag / debouncedReload),对照绑定页面的 objects 与 behavior.actions 核对;
190
+ * 不匹配报 KIT-VIEW-003(含文件名、行号与写错的对象名/动作 id)。
191
+ */
192
+ export function checkKitViewTargetRefs(
193
+ file: string,
194
+ source: string,
195
+ pageTargets: ReadonlyMap<string, KitPageTargetSummary> | KitPageTargetSummary,
196
+ fallbackViewName?: string,
197
+ ): KitDiagnostic[] {
198
+ const targetMap: ReadonlyMap<string, KitPageTargetSummary> =
199
+ 'viewName' in pageTargets ? new Map([[pageTargets.viewName, pageTargets]]) : pageTargets;
200
+ if (targetMap.size === 0) return [];
201
+
202
+ const clean = blankCommentsAndStrings(source);
203
+ const codeWithStrings = stripCommentsKeepStrings(source);
204
+ const diagnostics: KitDiagnostic[] = [];
205
+
206
+ // 找出所有 defineKitView({ ... }) 块;若源码未包 defineKitView,则按整段源码扫描
207
+ const blocks: Array<{ start: number; end: number; viewName?: string }> = [];
208
+ const callRe = /\bdefineKitView\s*(?:<[\s\S]*?>)?\s*\(\s*\{/g;
209
+ for (const m of clean.matchAll(callRe)) {
210
+ const callIdx = m.index ?? 0;
211
+ const braceStart = callIdx + m[0].length - 1;
212
+ const braceEnd = findMatchingBracket(clean, braceStart, '{', '}');
213
+ if (braceEnd === -1) continue;
214
+ const sliceWithStrings = codeWithStrings.slice(braceStart, braceEnd + 1);
215
+ const nameMatch = /\bname\s*:\s*['"]([A-Za-z_$][\w$]*)['"]/.exec(sliceWithStrings);
216
+ const prefix = codeWithStrings.slice(Math.max(0, callIdx - 120), callIdx);
217
+ const varMatch = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*$/.exec(prefix);
218
+ const inferredName = nameMatch?.[1] ?? varMatch?.[1] ?? fallbackViewName;
219
+ blocks.push({ start: braceStart, end: braceEnd + 1, ...(inferredName !== undefined ? { viewName: inferredName } : {}) });
220
+ }
221
+ if (blocks.length === 0) {
222
+ const singleTarget = targetMap.size === 1 ? [...targetMap.keys()][0] : undefined;
223
+ blocks.push({
224
+ start: 0,
225
+ end: codeWithStrings.length,
226
+ ...(fallbackViewName !== undefined ? { viewName: fallbackViewName } : singleTarget !== undefined ? { viewName: singleTarget } : {}),
227
+ });
228
+ }
229
+
230
+ const displayObjects = (target: KitPageTargetSummary): string => {
231
+ const primary = [...target.objects].filter((k) => !k.includes('_'));
232
+ const list = primary.length > 0 ? primary : [...target.objects];
233
+ return list.join(' / ') || '无';
234
+ };
235
+
236
+ const reportBadObject = (target: KitPageTargetSummary, method: string, objName: string, absIndex: number): void => {
237
+ const pos = lineColAt(source, absIndex);
238
+ const avail = displayObjects(target);
239
+ diagnostics.push({
240
+ code: 'KIT-VIEW-003',
241
+ path: `${file}:${pos.line}`,
242
+ file,
243
+ line: pos.line,
244
+ column: pos.column,
245
+ message: `展示对象 ${target.viewName} 中 ctx.${method}("${objName}") 引用的对象名 "${objName}" 不在本页(${target.pageFile})的 objects 中(已声明:${avail})`,
246
+ hint: `将对象名 "${objName}" 改为页面 ${target.pageFile} 中已声明的对象(${avail})`,
247
+ });
248
+ };
249
+
250
+ for (const block of blocks) {
251
+ const target = block.viewName !== undefined ? targetMap.get(block.viewName) : undefined;
252
+ if (target === undefined) continue;
253
+ const segment = codeWithStrings.slice(block.start, block.end);
254
+
255
+ // 1. ctx.form('obj') / ctx.data('obj') / ctx.cascadeOptions('obj', ...) / ctx.watchDraftFlag('obj', ...)
256
+ const singleObjRe = /\bctx\s*\.\s*(form|data|cascadeOptions|watchDraftFlag)\s*\(\s*(['"`])([^'"`\\]*)\2/g;
257
+ for (const m of segment.matchAll(singleObjRe)) {
258
+ const method = m[1]!;
259
+ const objName = m[3]!;
260
+ if (objName.includes('${')) continue;
261
+ if (!target.objects.has(objName)) {
262
+ reportBadObject(target, method, objName, block.start + (m.index ?? 0));
263
+ }
264
+ }
265
+
266
+ // 2. ctx.reload('obj') 或 ctx.reload(['obj1', 'obj2'])
267
+ const reloadRe = /\bctx\s*\.\s*reload\s*\(\s*(\[[^\]]*\]|(['"`])[^'"`\\]*\2)/g;
268
+ for (const m of segment.matchAll(reloadRe)) {
269
+ const argText = m[1]!;
270
+ const argStart = block.start + (m.index ?? 0) + m[0].indexOf(argText);
271
+ const strRe = /(['"`])([^'"`\\]*)\1/g;
272
+ for (const sm of argText.matchAll(strRe)) {
273
+ const objName = sm[2]!;
274
+ if (objName.includes('${')) continue;
275
+ if (!target.objects.has(objName)) {
276
+ reportBadObject(target, 'reload', objName, argStart + (sm.index ?? 0));
277
+ }
278
+ }
279
+ }
280
+
281
+ // 3. ctx.debouncedReload(ms, 'obj')
282
+ const debouncedReloadRe = /\bctx\s*\.\s*debouncedReload\s*\(\s*[^,)]+,\s*(['"`])([^'"`\\]*)\1/g;
283
+ for (const m of segment.matchAll(debouncedReloadRe)) {
284
+ const objName = m[2]!;
285
+ if (objName.includes('${')) continue;
286
+ if (!target.objects.has(objName)) {
287
+ reportBadObject(target, 'debouncedReload', objName, block.start + (m.index ?? 0));
288
+ }
289
+ }
290
+
291
+ // 4. ctx.request('obj', 'actionId')
292
+ const requestRe = /\bctx\s*\.\s*request\s*\(\s*(['"`])([^'"`\\]*)\1(?:\s*,\s*(['"`])([^'"`\\]*)\3)?/g;
293
+ for (const m of segment.matchAll(requestRe)) {
294
+ const objName = m[2]!;
295
+ const actionId = m[4];
296
+ const absIndex = block.start + (m.index ?? 0);
297
+ if (objName.includes('${')) continue;
298
+ if (!target.objects.has(objName)) {
299
+ reportBadObject(target, 'request', objName, absIndex);
300
+ continue;
301
+ }
302
+ if (actionId !== undefined && !actionId.includes('${')) {
303
+ const actions = target.actionsByObject.get(objName);
304
+ if (actions === undefined || !actions.has(actionId)) {
305
+ const pos = lineColAt(source, absIndex);
306
+ const availActions = actions && actions.size > 0 ? [...actions].join(' / ') : '无';
307
+ diagnostics.push({
308
+ code: 'KIT-VIEW-003',
309
+ path: `${file}:${pos.line}`,
310
+ file,
311
+ line: pos.line,
312
+ column: pos.column,
313
+ message: `展示对象 ${target.viewName} 中 ctx.request("${objName}", "${actionId}") 引用的动作 id "${actionId}" 不在页面 ${target.pageFile} 对象 "${objName}" 的 behavior.actions 中(已声明:${availActions})`,
314
+ hint:
315
+ actions && actions.size > 0
316
+ ? `将动作 id "${actionId}" 改为对象 "${objName}" 已声明的动作(${availActions})`
317
+ : `在页面 ${target.pageFile} 的对象 "${objName}.behavior.actions" 中声明 id: ${actionId} 的动作`,
318
+ });
319
+ }
320
+ }
321
+ }
322
+ }
323
+
324
+ return diagnostics;
325
+ }
326
+
327
+ /** 从已抹除注释和字符串的 state 对象字面量内部文本解析出供 inferStateShape 使用的骨架对象 */
328
+ function parseStateObjectBody(body: string): Record<string, unknown> {
329
+ const out: Record<string, unknown> = {};
330
+ let i = 0;
331
+ const n = body.length;
332
+ while (i < n) {
333
+ while (i < n && /[\s,;]/.test(body[i]!)) i++;
334
+ if (i >= n) break;
335
+ const rest = body.slice(i);
336
+ const propMatch = /^([A-Za-z_$][\w$]*)\s*:/.exec(rest);
337
+ if (propMatch === null) {
338
+ // 跳过非标准属性项直到下一个顶层逗号
339
+ let parenDepth = 0;
340
+ let angleDepth = 0;
341
+ while (i < n) {
342
+ const c = body[i]!;
343
+ if (c === '(' || c === '[' || c === '{') parenDepth++;
344
+ else if (c === ')' || c === ']' || c === '}') parenDepth = Math.max(0, parenDepth - 1);
345
+ else if (c === '<') angleDepth++;
346
+ else if (c === '>') angleDepth = Math.max(0, angleDepth - 1);
347
+ else if (c === ',' && parenDepth === 0 && angleDepth === 0) { i++; break; }
348
+ i++;
349
+ }
350
+ continue;
351
+ }
352
+ const key = propMatch[1]!;
353
+ i += propMatch[0].length;
354
+ while (i < n && /\s/.test(body[i]!)) i++;
355
+ if (i >= n) break;
356
+ const ch = body[i]!;
357
+ if (ch === '[') {
358
+ const end = findMatchingBracket(body, i, '[', ']');
359
+ out[key] = [];
360
+ i = end === -1 ? n : end + 1;
361
+ } else if (ch === '{') {
362
+ const end = findMatchingBracket(body, i, '{', '}');
363
+ if (end === -1) {
364
+ out[key] = {};
365
+ i = n;
366
+ } else {
367
+ out[key] = parseStateObjectBody(body.slice(i + 1, end));
368
+ i = end + 1;
369
+ }
370
+ } else {
371
+ out[key] = 0;
372
+ }
373
+ // 跳过属性值后缀(如 `as Array<{ value: string }>`)直到下一个顶层逗号
374
+ let parenDepth = 0;
375
+ let angleDepth = 0;
376
+ while (i < n) {
377
+ const c = body[i]!;
378
+ if (c === '(' || c === '[' || c === '{') parenDepth++;
379
+ else if (c === ')' || c === ']' || c === '}') parenDepth = Math.max(0, parenDepth - 1);
380
+ else if (c === '<') angleDepth++;
381
+ else if (c === '>') angleDepth = Math.max(0, angleDepth - 1);
382
+ else if (c === ',' && parenDepth === 0 && angleDepth === 0) { i++; break; }
383
+ i++;
384
+ }
385
+ }
386
+ return out;
387
+ }
388
+
389
+ /** 从源码中静态提取全部 defineKitView({ ... state: { ... } }) 的形状表(兜底未导出或模块未执行时的静态检查) */
390
+ function extractDefineKitViewShapes(source: string): ViewStateShape[] {
391
+ const clean = blankCommentsAndStrings(source);
392
+ if (!DEFINE_KIT_VIEW_CALL.test(clean)) return [];
393
+ const shapes: ViewStateShape[] = [];
394
+ const callRe = /\bdefineKitView\s*(?:<[\s\S]*?>)?\s*\(\s*\{/g;
395
+ for (const m of clean.matchAll(callRe)) {
396
+ const braceStart = (m.index ?? 0) + m[0].length - 1;
397
+ const braceEnd = findMatchingBracket(clean, braceStart, '{', '}');
398
+ if (braceEnd === -1) continue;
399
+ const defBody = clean.slice(braceStart + 1, braceEnd);
400
+ // 在 defineKitView 配置对象的顶层查找 state: { ... }
401
+ let depth = 0;
402
+ for (let i = 0; i < defBody.length; i++) {
403
+ const ch = defBody[i]!;
404
+ if (ch === '(' || ch === '[' || ch === '{') { depth++; continue; }
405
+ if (ch === ')' || ch === ']' || ch === '}') { depth = Math.max(0, depth - 1); continue; }
406
+ if (depth === 0) {
407
+ const sub = defBody.slice(i);
408
+ const stateMatch = /^state\s*:\s*\{/.exec(sub);
409
+ if (stateMatch !== null && (i === 0 || !/[\w$]/.test(defBody[i - 1]!))) {
410
+ const stateOpen = i + stateMatch[0].length - 1;
411
+ const stateClose = findMatchingBracket(defBody, stateOpen, '{', '}');
412
+ if (stateClose !== -1) {
413
+ const stateObj = parseStateObjectBody(defBody.slice(stateOpen + 1, stateClose));
414
+ shapes.push(inferStateShape(stateObj));
415
+ }
416
+ break;
417
+ }
418
+ }
419
+ }
420
+ }
421
+ return shapes;
422
+ }
423
+
424
+ /** 从任意模块导出值(含直接导出、default、数组、对象、defineKitApp 返回的 registry/options.views)中提取全部展示对象类 */
425
+ function collectViewClasses(value: unknown, seen = new Set<unknown>()): unknown[] {
426
+ if (value === null || value === undefined || seen.has(value)) return [];
427
+ seen.add(value);
428
+ if (readKitViewInfo(value) !== undefined) return [value];
429
+ if (Array.isArray(value)) return value.flatMap((item) => collectViewClasses(item, seen));
430
+ if (typeof value === 'object') {
431
+ const rec = value as Record<string, unknown>;
432
+ const out: unknown[] = [];
433
+ if (rec.registry !== null && typeof rec.registry === 'object') {
434
+ out.push(...collectViewClasses((rec.registry as Record<string, unknown>).views, seen));
435
+ }
436
+ if (rec.options !== null && typeof rec.options === 'object') {
437
+ out.push(...collectViewClasses((rec.options as Record<string, unknown>).views, seen));
438
+ }
439
+ for (const v of Object.values(rec)) {
440
+ if (readKitViewInfo(v) !== undefined) out.push(v);
441
+ else if (Array.isArray(v)) out.push(...collectViewClasses(v, seen));
442
+ else if (v !== null && typeof v === 'object' && (v as { kind?: unknown }).kind === 'soma-app') {
443
+ out.push(...collectViewClasses(v, seen));
444
+ }
445
+ }
446
+ return out;
447
+ }
448
+ return [];
449
+ }
450
+
451
+ /** 解析相对模块路径对应的实际源文件绝对路径 */
452
+ function resolveLocalModule(
453
+ pathMod: typeof import('node:path'),
454
+ fsMod: typeof import('node:fs'),
455
+ fromDir: string,
456
+ specifier: string,
457
+ ): string | undefined {
458
+ if (!specifier.startsWith('.')) return undefined;
459
+ const base = pathMod.resolve(fromDir, specifier);
460
+ const candidates = [
461
+ base,
462
+ `${base}.ts`,
463
+ `${base}.mts`,
464
+ `${base}.cts`,
465
+ `${base}.js`,
466
+ `${base}.mjs`,
467
+ `${base}.cjs`,
468
+ pathMod.join(base, 'index.ts'),
469
+ pathMod.join(base, 'index.js'),
470
+ ];
471
+ for (const cand of candidates) {
472
+ try {
473
+ if (fsMod.existsSync(cand) && fsMod.statSync(cand).isFile()) return cand;
474
+ } catch {
475
+ // ignore
476
+ }
477
+ }
478
+ return undefined;
479
+ }
480
+
481
+ /**
482
+ * 扫描 soma.app.ts 中登记的展示对象(兼容 `views: [OrderView]` 数组与 `views: { OrderView }` / `views: { OrderView: OrderView }` 对象),
483
+ * 反查它们 import 的源文件以及按类名登记的 KitViewClass。
484
+ */
485
+ function inspectSomaAppViews(
486
+ pathMod: typeof import('node:path'),
487
+ fsMod: typeof import('node:fs'),
488
+ root: string,
489
+ load: (file: string) => unknown,
490
+ ): { viewFiles: Set<string>; classesByFile: Map<string, unknown[]>; classesByName: Map<string, unknown> } {
491
+ const viewFiles = new Set<string>();
492
+ const classesByFile = new Map<string, unknown[]>();
493
+ const classesByName = new Map<string, unknown>();
494
+ const appFile = ['soma.app.ts', 'soma.app.mts', 'soma.app.js', 'soma.app.mjs']
495
+ .map((n) => pathMod.join(root, n))
496
+ .find((p) => { try { return fsMod.existsSync(p); } catch { return false; } });
497
+ if (appFile === undefined) return { viewFiles, classesByFile, classesByName };
498
+
499
+ try {
500
+ const appMod = load(appFile);
501
+ for (const cls of collectViewClasses(appMod)) {
502
+ const info = readKitViewInfo(cls);
503
+ if (info !== undefined) classesByName.set(info.name, cls);
504
+ }
505
+ } catch {
506
+ // soma.app.ts 装载异常交由 checkApp 汇报
507
+ }
508
+
509
+ let appSource: string;
510
+ try {
511
+ appSource = fsMod.readFileSync(appFile, 'utf8');
512
+ } catch {
513
+ return { viewFiles, classesByFile, classesByName };
514
+ }
515
+
516
+ // 解析 import 语句:本地标识符 -> 源文件绝对路径
517
+ const importMap = new Map<string, string>();
518
+ const importRe = /\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s+['"]([^'"]+)['"]/g;
519
+ for (const m of appSource.matchAll(importRe)) {
520
+ const clause = m[1]!;
521
+ const spec = m[2]!;
522
+ const resolved = resolveLocalModule(pathMod, fsMod, pathMod.dirname(appFile), spec);
523
+ if (resolved === undefined) continue;
524
+ const namedMatch = /\{([^}]*)\}/.exec(clause);
525
+ if (namedMatch !== null) {
526
+ for (const part of namedMatch[1]!.split(',')) {
527
+ const tokens = part.trim().replace(/^type\s+/, '').split(/\s+as\s+/);
528
+ const local = (tokens[1] ?? tokens[0] ?? '').trim();
529
+ if (/^[A-Za-z_$][\w$]*$/.test(local)) importMap.set(local, resolved);
530
+ }
531
+ }
532
+ const defaultPart = clause.replace(/\{[^}]*\}/, '').replace(',', '').trim();
533
+ if (/^[A-Za-z_$][\w$]*$/.test(defaultPart)) importMap.set(defaultPart, resolved);
534
+ }
535
+
536
+ // 解析 views: [OrderView, ...] 或 views: { OrderView, ... } 中引用的标识符
537
+ const cleanApp = blankCommentsAndStrings(appSource);
538
+ const viewsRe = /\bviews\s*:\s*(\[|\{)/g;
539
+ for (const m of cleanApp.matchAll(viewsRe)) {
540
+ const openChar = m[1]!;
541
+ const closeChar = openChar === '[' ? ']' : '}';
542
+ const openIdx = (m.index ?? 0) + m[0].length - 1;
543
+ const closeIdx = findMatchingBracket(cleanApp, openIdx, openChar, closeChar);
544
+ if (closeIdx === -1) continue;
545
+ const body = cleanApp.slice(openIdx + 1, closeIdx);
546
+ for (const rawEntry of body.split(',')) {
547
+ const entry = rawEntry.trim();
548
+ if (entry === '') continue;
549
+ // 兼容数组项 `OrderView`、对象简写 `OrderView`、对象键值 `OrderView: MyOrderView`
550
+ const parts = entry.split(':').map((s) => s.trim());
551
+ const keyIdent = parts[0]!;
552
+ const valIdent = parts[1] ?? parts[0]!;
553
+ const targetFile = importMap.get(valIdent) ?? importMap.get(keyIdent);
554
+ if (targetFile !== undefined) {
555
+ viewFiles.add(targetFile);
556
+ const cls = classesByName.get(keyIdent) ?? classesByName.get(valIdent);
557
+ if (cls !== undefined) {
558
+ const list = classesByFile.get(targetFile) ?? [];
559
+ if (!list.includes(cls)) list.push(cls);
560
+ classesByFile.set(targetFile, list);
561
+ }
562
+ }
563
+ }
564
+ }
565
+
566
+ return { viewFiles, classesByFile, classesByName };
567
+ }
568
+
569
+ /** 扫描应用根下全部 .kit.yaml 页面,构建 viewName -> KitPageTargetSummary 表 */
570
+ async function collectAppPageTargets(
571
+ pathMod: typeof import('node:path'),
572
+ fsMod: typeof import('node:fs'),
573
+ root: string,
574
+ ): Promise<Map<string, KitPageTargetSummary>> {
575
+ const targets = new Map<string, KitPageTargetSummary>();
576
+ let parseSomaDsl: ((text: string, kind: 'ui') => { ok: boolean; value?: unknown }) | undefined;
577
+ try {
578
+ const runtime = await import('soma-core/server/runtime');
579
+ parseSomaDsl = runtime.parseSomaDsl;
580
+ } catch {
581
+ return targets;
582
+ }
583
+
584
+ const walkPages = (dir: string): void => {
585
+ let entries: import('node:fs').Dirent[];
586
+ try {
587
+ entries = fsMod.readdirSync(dir, { withFileTypes: true });
588
+ } catch {
589
+ return;
590
+ }
591
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
592
+ if (e.name.startsWith('.') || SKIP_DIRS.has(e.name)) continue;
593
+ const full = pathMod.join(dir, e.name);
594
+ if (e.isDirectory()) {
595
+ walkPages(full);
596
+ continue;
597
+ }
598
+ if (!e.isFile() || !e.name.endsWith('.kit.yaml')) continue;
599
+ let text: string;
600
+ try {
601
+ text = fsMod.readFileSync(full, 'utf8');
602
+ } catch {
603
+ continue;
604
+ }
605
+ const parsed = parseSomaDsl!(text, 'ui');
606
+ if (!parsed.ok) continue;
607
+ const relFile = pathMod.relative(root, full).split(pathMod.sep).join('/');
608
+ const summary = extractPageTargetFromParsed(parsed.value, relFile);
609
+ if (summary !== undefined && !targets.has(summary.viewName)) {
610
+ targets.set(summary.viewName, summary);
611
+ }
612
+ }
613
+ };
614
+ walkPages(root);
615
+ return targets;
616
+ }
617
+
618
+
619
+ /**
620
+ * 扫描应用 TS/JS 源码中的路径违规(供 `soma kit check` 与单测直接调用):
621
+ * 1. 字符串字面量出现宿主机系统绝对路径(/Users/...、/home/...、C:\...、file://... 等);
622
+ * 2. ctx.http.*、http.*、fetch、ctx.navigate 传入 './...' 或 '../...' 等相对路径;
623
+ * 3. fs.* 直接传入 './...' 或 '../...' 裸相对路径。
624
+ */
625
+ export function scanKitSourcePaths(file: string, source: string): KitDiagnostic[] {
626
+ return scanPathSourceUsages(source, {
627
+ fileName: file,
628
+ isInvalidUrl: (value, allowExternalHref) => isRelativePathValue(value, { allowExternalHref }),
629
+ })
630
+ .sort((a, b) => a.index - b.index)
631
+ .map((issue): KitDiagnostic => {
632
+ const pos = lineColAt(source, issue.index);
633
+ const at = { path: `${file}:${pos.line}`, file, line: pos.line, column: pos.column };
634
+ if (issue.kind === 'url') {
635
+ return {
636
+ code: 'KIT-APP-001', ...at,
637
+ message: `${issue.callee}("${issue.value}") 路径不合法;URL 必须是安全站内路径(以单个 / 开头),或该调用允许的外链`,
638
+ hint: '使用以单个 / 开头的站内路径;检查点段、百分号编码与 URL 语境',
639
+ };
640
+ }
641
+ const kind = issue.pathKind === 'absolute' ? '硬编码绝对路径' : '裸相对路径';
642
+ return {
643
+ code: 'KIT-APP-001', ...at,
644
+ message: `${issue.callee}("${issue.value}") 文件系统路径违规:禁止直接传入${kind};请基于显式基准路径通过 path.join / path.resolve 拼接`,
645
+ hint: '先声明显式基准路径(如 const baseDir = path.dirname(fileURLToPath(import.meta.url))),再用 path.join(baseDir, ...) 拼接',
646
+ };
647
+ });
648
+ }
649
+
650
+ /** 把一份源码与它定义的展示对象类交给扫描,返回带码诊断(纯函数,内存可测) */
651
+ export function checkKitViewSource(
652
+ file: string,
653
+ source: string,
654
+ viewClasses: readonly unknown[],
655
+ pageTargets?: ReadonlyMap<string, KitPageTargetSummary> | KitPageTargetSummary,
656
+ ): KitDiagnostic[] {
657
+ const classes = collectViewClasses(viewClasses);
658
+ const infos = classes.map((c) => readKitViewInfo(c)).filter((x): x is NonNullable<typeof x> => x !== undefined);
659
+ const shapes = [...infos.map((i) => i.shape), ...extractDefineKitViewShapes(source)];
660
+ const diags: KitDiagnostic[] = [];
661
+ if (shapes.length > 0) {
662
+ const shape = mergeStateShapes(shapes);
663
+ diags.push(
664
+ ...scanViewMethodWrites(source, shape).map((f): KitDiagnostic => {
665
+ const at = { path: `${file}:${f.line}`, file, line: f.line, column: f.column };
666
+ if (f.kind === 'object-alias') {
667
+ return {
668
+ code: 'KIT-VIEW-009', ...at,
669
+ message: `把对象成员 ${f.source} 赋给 ${f.member}:同一对象挂在两个路径下,经后者写入会上报成前者,刷新错位`,
670
+ hint: `赋浅拷贝:view.${f.member} = { ...view.${f.source} }`,
671
+ };
672
+ }
673
+ const what = f.kind === 'array-mutate' ? `对数组成员 ${f.member} 原地调用 ${f.method}()` : `对数组成员 ${f.member} 做下标 / 元素字段 / length 写入`;
674
+ return { code: 'KIT-VIEW-008', ...at, message: `${what}:core 不代理数组,这样写不会触发刷新`, hint: VIEW_REPLACE_HINT };
675
+ }),
676
+ );
677
+ }
678
+ if (pageTargets !== undefined) {
679
+ diags.push(...checkKitViewTargetRefs(file, source, pageTargets, infos[0]?.name));
680
+ }
681
+ diags.push(...scanKitSourcePaths(file, source));
682
+ return diags;
683
+ }
684
+
685
+ /**
686
+ * 扫描应用根下全部定义展示对象的源文件(含 `*.view.*`、任意含 `defineKitView` 调用的 `.ts/.js` 文件及 `soma.app.ts` 引用的展示对象文件);
687
+ * load 与 `soma kit check` 装载 soma.app.ts 同一个加载器。
688
+ */
689
+ export async function scanKitViewWrites(appDir: string, load: (file: string) => unknown): Promise<KitDiagnostic[]> {
690
+ const path = await import(/* webpackIgnore: true */ 'node:path');
691
+ const fs = await import(/* webpackIgnore: true */ 'node:fs');
692
+ const root = path.resolve(appDir);
693
+ const { viewFiles, classesByFile, classesByName } = inspectSomaAppViews(path, fs, root, load);
694
+ const pageTargets = await collectAppPageTargets(path, fs, root);
695
+ const out: KitDiagnostic[] = [];
696
+ const scanned = new Set<string>();
697
+
698
+ const scanFile = (full: string, isExplicitViewFile: boolean): void => {
699
+ if (scanned.has(full)) return;
700
+ let text: string;
701
+ try {
702
+ text = fs.readFileSync(full, 'utf8');
703
+ } catch {
704
+ return;
705
+ }
706
+ const hasCall = DEFINE_KIT_VIEW_CALL.test(blankCommentsAndStrings(text));
707
+ const file = path.relative(root, full).split(path.sep).join('/');
708
+ if (!isExplicitViewFile && !hasCall && !viewFiles.has(full)) {
709
+ scanned.add(full);
710
+ out.push(...scanKitSourcePaths(file, text));
711
+ return;
712
+ }
713
+ scanned.add(full);
714
+
715
+ const classes: unknown[] = [...(classesByFile.get(full) ?? [])];
716
+ try {
717
+ const mod = load(full);
718
+ for (const cls of collectViewClasses(mod)) {
719
+ if (!classes.includes(cls)) classes.push(cls);
720
+ }
721
+ } catch {
722
+ // 装载失败由装配步骤(KIT-APP-011 / KIT-VIEW-005 / KIT-VIEW-009)报,此处仍可由源码形状兜底扫描
723
+ }
724
+ if (classesByName.size > 0 && hasCall) {
725
+ for (const m of text.matchAll(/\bname\s*:\s*['"]([A-Z][A-Za-z0-9]*View)['"]/g)) {
726
+ const cls = classesByName.get(m[1]!);
727
+ if (cls !== undefined && !classes.includes(cls)) classes.push(cls);
728
+ }
729
+ }
730
+ out.push(...checkKitViewSource(file, text, classes, pageTargets));
731
+ };
732
+
733
+ const walk = (dir: string): void => {
734
+ let entries: import('node:fs').Dirent[];
735
+ try {
736
+ entries = fs.readdirSync(dir, { withFileTypes: true });
737
+ } catch {
738
+ return;
739
+ }
740
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
741
+ const full = path.join(dir, e.name);
742
+ if (e.isDirectory()) {
743
+ if (!SKIP_DIRS.has(e.name) && !e.name.startsWith('.')) walk(full);
744
+ continue;
745
+ }
746
+ if (!SOURCE_FILE.test(e.name) || /\.d\.[cm]?ts$/.test(e.name)) continue;
747
+ scanFile(full, VIEW_FILE.test(e.name));
748
+ }
749
+ };
750
+ walk(root);
751
+ return out;
752
+ }