soma-core 1.0.1 → 1.0.2

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 (227) hide show
  1. package/app/SomaPageClient.tsx +336 -0
  2. package/app/api/[...path]/route.ts +9 -85
  3. package/app/api/page/route.ts +18 -16
  4. package/app/api/soma-manifest/route.ts +39 -0
  5. package/app/components/SomaHydrationShell.tsx +23 -0
  6. package/app/layout.tsx +2 -2
  7. package/app/loading.tsx +5 -0
  8. package/app/page.tsx +19 -128
  9. package/bin/soma-lsp.cjs +195 -0
  10. package/bin/soma-sync.cjs +3 -0
  11. package/bin/soma.cjs +14 -2
  12. package/core/api/IService.ts +6 -10
  13. package/core/api/load-host-service.ts +72 -0
  14. package/core/api/service-path.ts +39 -0
  15. package/core/base/SomaEntity.ts +3 -10
  16. package/core/base/SomaLocaleOnlyPageRoot.ts +3 -4
  17. package/core/base/SomaPageRootBase.ts +20 -3
  18. package/core/base/decorators/Event.ts +23 -0
  19. package/core/base/decorators/Locale.ts +35 -0
  20. package/core/base/decorators/Page.ts +16 -0
  21. package/core/base/decorators/Show.ts +20 -0
  22. package/core/base/decorators/ShowList.ts +34 -0
  23. package/core/base/decorators/index.ts +5 -0
  24. package/core/base/index.ts +2 -0
  25. package/core/base/runAsync.ts +32 -0
  26. package/core/compiler/full-manifest-builder.ts +33 -7
  27. package/core/compiler/host-config-sync.cjs +38 -0
  28. package/core/compiler/manifest-compiler.ts +3 -2
  29. package/core/compiler/page-base-resolver.ts +23 -0
  30. package/core/compiler/precompiled-manifest-loader.ts +34 -0
  31. package/core/compiler/rollup-plugin-soma.ts +45 -0
  32. package/core/compiler/rspack-plugin-soma.js +33 -0
  33. package/core/compiler/soma-manifest-webpack-plugin.js +72 -0
  34. package/core/compiler/soma-precompile.js +3513 -0
  35. package/core/compiler/soma-precompile.ts +52 -6
  36. package/core/compiler/soma-rspack-yaml-loader.js +22 -0
  37. package/core/compiler/soma-webpack-loader.js +7 -1
  38. package/core/compiler/vite-plugin-soma.ts +11 -1
  39. package/core/container/IContainerAdapter.ts +36 -0
  40. package/core/container/MiniProgramContainerAdapter.ts +190 -0
  41. package/core/container/ReactNativeContainerAdapter.ts +189 -0
  42. package/core/container/SomaContainerAdapter.ts +17 -6
  43. package/core/diagnostics/SomaDiagnostics.ts +1 -1
  44. package/core/diagnostics/SomaTelemetry.ts +100 -0
  45. package/core/diagnostics/telemetry-context.ts +15 -0
  46. package/core/engine/asset-resolver.ts +39 -4
  47. package/core/engine/dom-renderer.ts +9 -11
  48. package/core/engine/event-engine.ts +110 -41
  49. package/core/engine/on-change-engine.ts +71 -0
  50. package/core/engine/property-watcher.ts +117 -0
  51. package/core/engine/reactive-proxy.ts +11 -5
  52. package/core/engine/render-engine.ts +97 -11
  53. package/core/engine/runtime-builder.ts +88 -11
  54. package/core/engine/scope-resolver.ts +65 -9
  55. package/core/engine/soma-bootstrap.ts +448 -244
  56. package/core/engine/style-binder.ts +423 -0
  57. package/core/engine/theme-variables.ts +37 -0
  58. package/core/engine/timer-engine.ts +92 -0
  59. package/core/engine/trigger-engine.ts +55 -0
  60. package/core/host/resolve-host-bootstrap.ts +28 -0
  61. package/core/host/soma-bootstrap-host.stub.ts +4 -0
  62. package/core/index.ts +33 -2
  63. package/core/infra/auth/TokenAuthService.ts +17 -3
  64. package/core/infra/http/IHttpClient.ts +11 -1
  65. package/core/infra/http/SomaHttpService.ts +89 -31
  66. package/core/infra/i18n/DefaultI18n.ts +6 -18
  67. package/core/infra/i18n/II18n.ts +2 -3
  68. package/core/infra/notify/DomNotifyService.ts +98 -0
  69. package/core/infra/notify/INotifyTheme.ts +22 -0
  70. package/core/infra/realtime/IRealtimeService.ts +23 -0
  71. package/core/infra/realtime/IRealtimeTransport.ts +9 -0
  72. package/core/infra/realtime/SomaRealtimeService.ts +95 -0
  73. package/core/infra/realtime/SseRealtimeTransport.ts +36 -0
  74. package/core/infra/realtime/WebSocketRealtimeTransport.ts +102 -0
  75. package/core/infra/router/router-path.ts +28 -0
  76. package/core/infra/storage/SessionStorageService.ts +59 -0
  77. package/core/lsp/cross-file-diagnostics.cjs +160 -0
  78. package/core/lsp/event-yaml-completion.cjs +106 -0
  79. package/core/lsp/extra-completion.cjs +64 -0
  80. package/core/lsp/lsp-navigation.cjs +191 -0
  81. package/core/lsp/ui-yaml-completion.cjs +170 -0
  82. package/core/manifest/manifest-contract.ts +12 -0
  83. package/core/middleware/createPermissionMiddleware.ts +37 -0
  84. package/core/parser/annotation-extractor.ts +113 -0
  85. package/core/parser/pipeline-parser.ts +344 -276
  86. package/core/parser/style-config-parser.ts +340 -0
  87. package/core/parser/timer-parser.ts +70 -0
  88. package/core/parser/trigger-parser.ts +90 -0
  89. package/core/parser/ui-config-parser.ts +73 -1
  90. package/core/quality/SomaQualityRegistry.ts +68 -0
  91. package/core/runtime/SomaRuntimeServices.ts +100 -0
  92. package/core/runtime/SomaSnapshotStore.ts +5 -3
  93. package/core/types/domain.types.ts +5 -2
  94. package/core/types/event.types.ts +82 -57
  95. package/core/types/manifest.types.ts +2 -0
  96. package/core/types/style-config.types.ts +76 -0
  97. package/core/types/timer.types.ts +23 -0
  98. package/core/types/trigger.types.ts +14 -0
  99. package/core/types/ui-config.types.ts +9 -0
  100. package/core/types/watcher.types.ts +29 -0
  101. package/dist/cli/soma.js +23 -23
  102. package/dist/core/index.cjs +8968 -0
  103. package/dist/diagnostics/telemetry.cjs +105 -0
  104. package/dist/preview-export.cjs +3401 -0
  105. package/dist/tsconfig.types.tsbuildinfo +1 -0
  106. package/dist/types/api/IService.d.ts +28 -0
  107. package/dist/types/api/load-host-service.d.ts +5 -0
  108. package/dist/types/api/service-path.d.ts +13 -0
  109. package/dist/types/base/SomaApi.d.ts +5 -0
  110. package/dist/types/base/SomaDict.d.ts +89 -0
  111. package/dist/types/base/SomaEntity.d.ts +15 -0
  112. package/dist/types/base/SomaHttpClient.d.ts +66 -0
  113. package/dist/types/base/SomaLocaleOnlyPageRoot.d.ts +3 -0
  114. package/dist/types/base/SomaPageRootBase.d.ts +49 -0
  115. package/dist/types/base/SomaValidator.d.ts +55 -0
  116. package/dist/types/base/decorators/Event.d.ts +10 -0
  117. package/dist/types/base/decorators/Locale.d.ts +9 -0
  118. package/dist/types/base/decorators/Page.d.ts +4 -0
  119. package/dist/types/base/decorators/Show.d.ts +7 -0
  120. package/dist/types/base/decorators/ShowList.d.ts +12 -0
  121. package/dist/types/base/decorators/index.d.ts +5 -0
  122. package/dist/types/base/index.d.ts +9 -0
  123. package/dist/types/base/runAsync.d.ts +12 -0
  124. package/dist/types/compiler/full-manifest-builder.d.ts +35 -0
  125. package/dist/types/compiler/manifest-compiler.d.ts +29 -0
  126. package/dist/types/compiler/page-base-resolver.d.ts +6 -0
  127. package/dist/types/compiler/precompiled-manifest-loader.d.ts +5 -0
  128. package/dist/types/compiler/rollup-plugin-soma.d.ts +14 -0
  129. package/dist/types/compiler/route-builder.d.ts +12 -0
  130. package/dist/types/compiler/soma-precompile.d.ts +40 -0
  131. package/dist/types/compiler/vite-plugin-soma.d.ts +34 -0
  132. package/dist/types/container/IContainerAdapter.d.ts +30 -0
  133. package/dist/types/container/MiniProgramContainerAdapter.d.ts +52 -0
  134. package/dist/types/container/ReactNativeContainerAdapter.d.ts +47 -0
  135. package/dist/types/container/SomaContainerAdapter.d.ts +30 -0
  136. package/dist/types/diagnostics/SomaDiagnostics.d.ts +64 -0
  137. package/dist/types/diagnostics/SomaTelemetry.d.ts +32 -0
  138. package/dist/types/diagnostics/telemetry-context.d.ts +4 -0
  139. package/dist/types/engine/asset-resolver.d.ts +17 -0
  140. package/dist/types/engine/dom-renderer.d.ts +35 -0
  141. package/dist/types/engine/event-engine.d.ts +64 -0
  142. package/dist/types/engine/lis.d.ts +10 -0
  143. package/dist/types/engine/on-change-engine.d.ts +16 -0
  144. package/dist/types/engine/property-watcher.d.ts +18 -0
  145. package/dist/types/engine/reactive-proxy.d.ts +58 -0
  146. package/dist/types/engine/render-engine.d.ts +73 -0
  147. package/dist/types/engine/runtime-builder.d.ts +58 -0
  148. package/dist/types/engine/scope-resolver.d.ts +90 -0
  149. package/dist/types/engine/soma-bootstrap.d.ts +112 -0
  150. package/dist/types/engine/style-binder.d.ts +81 -0
  151. package/dist/types/engine/theme-variables.d.ts +3 -0
  152. package/dist/types/engine/timer-engine.d.ts +19 -0
  153. package/dist/types/engine/trigger-engine.d.ts +16 -0
  154. package/dist/types/host/resolve-host-bootstrap.d.ts +11 -0
  155. package/dist/types/host/soma-bootstrap-host.stub.d.ts +3 -0
  156. package/dist/types/index.d.ts +35 -0
  157. package/dist/types/infra/auth/IAuthService.d.ts +12 -0
  158. package/dist/types/infra/auth/TokenAuthService.d.ts +26 -0
  159. package/dist/types/infra/cache/ICache.d.ts +12 -0
  160. package/dist/types/infra/cache/MemoryCache.d.ts +14 -0
  161. package/dist/types/infra/cache/ServerFileCache.d.ts +37 -0
  162. package/dist/types/infra/config/IConfig.d.ts +9 -0
  163. package/dist/types/infra/config/SomaConfig.d.ts +21 -0
  164. package/dist/types/infra/event-bus/IEventBus.d.ts +8 -0
  165. package/dist/types/infra/event-bus/SomaEventBus.d.ts +9 -0
  166. package/dist/types/infra/http/IHttpClient.d.ts +28 -0
  167. package/dist/types/infra/http/SomaHttpService.d.ts +27 -0
  168. package/dist/types/infra/i18n/DefaultI18n.d.ts +7 -0
  169. package/dist/types/infra/i18n/II18n.d.ts +6 -0
  170. package/dist/types/infra/logger/ConsoleLogger.d.ts +14 -0
  171. package/dist/types/infra/logger/ILogger.d.ts +17 -0
  172. package/dist/types/infra/notify/DefaultNotifyService.d.ts +16 -0
  173. package/dist/types/infra/notify/DomNotifyService.d.ts +16 -0
  174. package/dist/types/infra/notify/INotifyService.d.ts +12 -0
  175. package/dist/types/infra/notify/INotifyTheme.d.ts +12 -0
  176. package/dist/types/infra/permission/IPermission.d.ts +10 -0
  177. package/dist/types/infra/permission/SomaPermission.d.ts +19 -0
  178. package/dist/types/infra/realtime/IRealtimeService.d.ts +13 -0
  179. package/dist/types/infra/realtime/IRealtimeTransport.d.ts +8 -0
  180. package/dist/types/infra/realtime/SomaRealtimeService.d.ts +20 -0
  181. package/dist/types/infra/realtime/SseRealtimeTransport.d.ts +11 -0
  182. package/dist/types/infra/realtime/WebSocketRealtimeTransport.d.ts +30 -0
  183. package/dist/types/infra/router/IRouter.d.ts +16 -0
  184. package/dist/types/infra/router/SomaRouter.d.ts +18 -0
  185. package/dist/types/infra/router/router-path.d.ts +6 -0
  186. package/dist/types/infra/storage/IStorageService.d.ts +7 -0
  187. package/dist/types/infra/storage/MemoryStorageService.d.ts +15 -0
  188. package/dist/types/infra/storage/SessionStorageService.d.ts +14 -0
  189. package/dist/types/infra/timer/ITimer.d.ts +13 -0
  190. package/dist/types/infra/timer/SomaTimer.d.ts +21 -0
  191. package/dist/types/manifest/manifest-contract.d.ts +4 -0
  192. package/dist/types/middleware/SomaMiddlewareChain.d.ts +6 -0
  193. package/dist/types/middleware/createPermissionMiddleware.d.ts +14 -0
  194. package/dist/types/parser/annotation-extractor.d.ts +12 -0
  195. package/dist/types/parser/pipeline-parser.d.ts +62 -0
  196. package/dist/types/parser/style-config-parser.d.ts +20 -0
  197. package/dist/types/parser/timer-parser.d.ts +6 -0
  198. package/dist/types/parser/trigger-parser.d.ts +13 -0
  199. package/dist/types/parser/ui-config-parser.d.ts +34 -0
  200. package/dist/types/parser/yaml-loader.d.ts +21 -0
  201. package/dist/types/quality/SomaQualityRegistry.d.ts +31 -0
  202. package/dist/types/runtime/SomaRuntimeServices.d.ts +35 -0
  203. package/dist/types/runtime/SomaSnapshotStore.d.ts +13 -0
  204. package/dist/types/scheduler/SomaScheduler.d.ts +25 -0
  205. package/dist/types/types/domain.types.d.ts +82 -0
  206. package/dist/types/types/engine.types.d.ts +22 -0
  207. package/dist/types/types/event.types.d.ts +61 -0
  208. package/dist/types/types/keyboard.types.d.ts +4 -0
  209. package/dist/types/types/manifest.types.d.ts +29 -0
  210. package/dist/types/types/scheduler.types.d.ts +8 -0
  211. package/dist/types/types/style-config.types.d.ts +62 -0
  212. package/dist/types/types/timer.types.d.ts +19 -0
  213. package/dist/types/types/trigger.types.d.ts +12 -0
  214. package/dist/types/types/ui-config.types.d.ts +85 -0
  215. package/dist/types/types/watcher.types.d.ts +24 -0
  216. package/dist/types/validation/contract-validator.d.ts +40 -0
  217. package/editor/vscode/extension.js +39 -0
  218. package/editor/vscode/language-configuration.json +17 -0
  219. package/editor/vscode/package.json +98 -0
  220. package/editor/vscode/syntaxes/soma-event-yaml.tmLanguage.json +30 -0
  221. package/editor/vscode/syntaxes/soma-ui-yaml.tmLanguage.json +42 -0
  222. package/global.d.ts +19 -0
  223. package/next.config.js +9 -4
  224. package/package.json +53 -16
  225. package/tailwind.config.ts +26 -7
  226. package/tsconfig.json +6 -2
  227. package/core/router/RouteHandler.ts +0 -93
@@ -0,0 +1,102 @@
1
+ import type { IRealtimeTransport, RealtimeMessageHandler } from './IRealtimeTransport';
2
+
3
+ export interface WebSocketRealtimeOptions {
4
+ reconnect?: boolean;
5
+ maxRetries?: number;
6
+ heartbeatMs?: number;
7
+ }
8
+
9
+ /** 浏览器 WebSocket 实时传输(支持重连与心跳) */
10
+ export class WebSocketRealtimeTransport implements IRealtimeTransport {
11
+ readonly kind = 'websocket' as const;
12
+ private socket: WebSocket | null = null;
13
+ private handlers = new Set<RealtimeMessageHandler>();
14
+ private url = '';
15
+ private closedByUser = false;
16
+ private retries = 0;
17
+ private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
18
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
19
+ private readonly reconnect: boolean;
20
+ private readonly maxRetries: number;
21
+ private readonly heartbeatMs: number;
22
+
23
+ constructor(options?: WebSocketRealtimeOptions) {
24
+ this.reconnect = options?.reconnect ?? false;
25
+ this.maxRetries = options?.maxRetries ?? 8;
26
+ this.heartbeatMs = options?.heartbeatMs ?? 0;
27
+ }
28
+
29
+ connect(url: string): void {
30
+ this.url = url;
31
+ this.closedByUser = false;
32
+ this.openSocket();
33
+ }
34
+
35
+ disconnect(): void {
36
+ this.closedByUser = true;
37
+ this.clearTimers();
38
+ this.socket?.close();
39
+ this.socket = null;
40
+ }
41
+
42
+ onMessage(handler: RealtimeMessageHandler): () => void {
43
+ this.handlers.add(handler);
44
+ return () => this.handlers.delete(handler);
45
+ }
46
+
47
+ isConnected(): boolean {
48
+ return this.socket !== null && this.socket.readyState === WebSocket.OPEN;
49
+ }
50
+
51
+ send(data: unknown): void {
52
+ if (this.socket?.readyState === WebSocket.OPEN) {
53
+ this.socket.send(JSON.stringify(data));
54
+ }
55
+ }
56
+
57
+ private openSocket(): void {
58
+ if (typeof WebSocket === 'undefined') return;
59
+ this.socket?.close();
60
+ this.socket = new WebSocket(this.url);
61
+ this.socket.onopen = () => {
62
+ this.retries = 0;
63
+ this.startHeartbeat();
64
+ };
65
+ this.socket.onmessage = (ev) => {
66
+ try {
67
+ const data = JSON.parse(String(ev.data));
68
+ if (data?.type === 'ping') return;
69
+ for (const h of this.handlers) h(data);
70
+ } catch {
71
+ for (const h of this.handlers) h(ev.data);
72
+ }
73
+ };
74
+ this.socket.onclose = () => {
75
+ this.clearHeartbeat();
76
+ if (!this.closedByUser && this.reconnect && this.retries < this.maxRetries) {
77
+ const delay = Math.min(1000 * 2 ** this.retries, 15000);
78
+ this.retries += 1;
79
+ this.reconnectTimer = setTimeout(() => this.openSocket(), delay);
80
+ }
81
+ };
82
+ }
83
+
84
+ private startHeartbeat(): void {
85
+ if (!this.heartbeatMs) return;
86
+ this.clearHeartbeat();
87
+ this.heartbeatTimer = setInterval(() => {
88
+ this.send({ type: 'ping' });
89
+ }, this.heartbeatMs);
90
+ }
91
+
92
+ private clearHeartbeat(): void {
93
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
94
+ this.heartbeatTimer = null;
95
+ }
96
+
97
+ private clearTimers(): void {
98
+ this.clearHeartbeat();
99
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
100
+ this.reconnectTimer = null;
101
+ }
102
+ }
@@ -0,0 +1,28 @@
1
+ /** Strip query/hash for router utilities */
2
+ export function pathOnly(url: string): string {
3
+ const raw = url.split('?')[0]?.split('#')[0] || '/';
4
+ return raw.replace(/\/$/, '') || '/';
5
+ }
6
+
7
+ /** Browser location pathname + search (includes ?id= etc.) */
8
+ export function getBrowserUrlPath(): string {
9
+ if (typeof globalThis === 'undefined' || !('location' in globalThis)) {
10
+ return '/';
11
+ }
12
+ const loc = globalThis.location;
13
+ return `${loc.pathname}${loc.search}`;
14
+ }
15
+
16
+ /** Read a query parameter from router path or the browser address bar */
17
+ export function readQueryParam(key: string, routerPath?: string): string {
18
+ let qs = '';
19
+ const path = routerPath ?? '';
20
+ const qIdx = path.indexOf('?');
21
+ if (qIdx >= 0) {
22
+ qs = path.slice(qIdx + 1);
23
+ } else if (typeof globalThis !== 'undefined' && 'location' in globalThis) {
24
+ qs = globalThis.location.search.replace(/^\?/, '');
25
+ }
26
+ if (!qs) return '';
27
+ return new URLSearchParams(qs).get(key) ?? '';
28
+ }
@@ -0,0 +1,59 @@
1
+ import { IStorageService } from './IStorageService';
2
+
3
+ interface StoredEntry<T = unknown> {
4
+ value: T;
5
+ expiresAt: number | null;
6
+ }
7
+
8
+ /**
9
+ * 浏览器 sessionStorage 实现 — 同标签页内跨页面导航保持登录态。
10
+ * 非浏览器环境回退到进程内 Map。
11
+ */
12
+ export class SessionStorageService implements IStorageService {
13
+ private fallback = new Map<string, string>();
14
+
15
+ private get session(): Storage | null {
16
+ if (typeof sessionStorage === 'undefined') return null;
17
+ return sessionStorage;
18
+ }
19
+
20
+ get<T>(key: string): T | null {
21
+ const raw = this.session?.getItem(key) ?? this.fallback.get(key);
22
+ if (raw == null) return null;
23
+
24
+ try {
25
+ const entry = JSON.parse(raw) as StoredEntry<T>;
26
+ if (entry.expiresAt !== null && Date.now() > entry.expiresAt) {
27
+ this.remove(key);
28
+ return null;
29
+ }
30
+ return entry.value;
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ set<T>(key: string, value: T, ttl?: number): void {
37
+ const payload = JSON.stringify({
38
+ value,
39
+ expiresAt: ttl !== undefined && ttl > 0 ? Date.now() + ttl : null,
40
+ } satisfies StoredEntry<T>);
41
+
42
+ if (this.session) this.session.setItem(key, payload);
43
+ else this.fallback.set(key, payload);
44
+ }
45
+
46
+ remove(key: string): void {
47
+ this.session?.removeItem(key);
48
+ this.fallback.delete(key);
49
+ }
50
+
51
+ clear(): void {
52
+ this.session?.clear();
53
+ this.fallback.clear();
54
+ }
55
+
56
+ has(key: string): boolean {
57
+ return this.get(key) !== null;
58
+ }
59
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * LSP 跨文件锚点一致性诊断
3
+ * html data-soma-id ↔ _ui.yaml show ↔ _event.yaml 事件锚点
4
+ */
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const yaml = require('js-yaml');
8
+
9
+ function extractSomaIdsFromHtml(html) {
10
+ const ids = new Set();
11
+ for (const m of html.matchAll(/data-soma-id=["']([^"']+)["']/g)) {
12
+ ids.add(m[1]);
13
+ }
14
+ return ids;
15
+ }
16
+
17
+ function extractShowKeys(uiYaml) {
18
+ const keys = new Set();
19
+ try {
20
+ const doc = yaml.load(uiYaml);
21
+ if (doc?.show && typeof doc.show === 'object') {
22
+ for (const k of Object.keys(doc.show)) keys.add(k);
23
+ }
24
+ } catch {
25
+ /* invalid yaml */
26
+ }
27
+ return keys;
28
+ }
29
+
30
+ function extractEventIds(eventYaml) {
31
+ const ids = new Set();
32
+ for (const line of eventYaml.split('\n')) {
33
+ const trimmed = line.trim();
34
+ if (!trimmed || trimmed.startsWith('#')) continue;
35
+ const dot = trimmed.indexOf('.');
36
+ if (dot > 0) ids.add(trimmed.slice(0, dot));
37
+ }
38
+ return ids;
39
+ }
40
+
41
+ function collectHtmlPages(htmlDir) {
42
+ const pages = [];
43
+ if (!fs.existsSync(htmlDir)) return pages;
44
+ function walk(dir, prefix = '') {
45
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
46
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
47
+ const full = path.join(dir, entry.name);
48
+ if (entry.isDirectory()) walk(full, rel);
49
+ else if (entry.name.endsWith('.html')) pages.push(rel.replace(/\.html$/, ''));
50
+ }
51
+ }
52
+ walk(htmlDir);
53
+ return pages;
54
+ }
55
+
56
+ function findAnchorInHtml(html, somaId) {
57
+ const re = new RegExp(`data-soma-id=["']${somaId.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}["']`, 'm');
58
+ const m = re.exec(html);
59
+ if (!m) return null;
60
+ const before = html.slice(0, m.index);
61
+ const line = before.split('\n').length - 1;
62
+ const character = m.index - before.lastIndexOf('\n') - 1;
63
+ return { line, character, length: m[0].length };
64
+ }
65
+
66
+ function findKeyInYaml(yamlText, key) {
67
+ const re = new RegExp(`^\\s{0,4}${key.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\s*:`, 'm');
68
+ const m = re.exec(yamlText);
69
+ if (!m) return null;
70
+ const before = yamlText.slice(0, m.index);
71
+ const line = before.split('\n').length - 1;
72
+ const character = m.index - before.lastIndexOf('\n') - 1;
73
+ return { line, character, length: key.length };
74
+ }
75
+
76
+ function rangeFromLoc(loc) {
77
+ if (!loc) return { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } };
78
+ return {
79
+ start: { line: loc.line, character: loc.character },
80
+ end: { line: loc.line, character: loc.character + loc.length },
81
+ };
82
+ }
83
+
84
+ function lintAnchorConsistency(hostDir) {
85
+ const htmlDir = path.join(hostDir, 'html');
86
+ const diagnostics = [];
87
+
88
+ for (const base of collectHtmlPages(htmlDir)) {
89
+ const htmlPath = path.join(htmlDir, `${base}.html`);
90
+ const uiPath = path.join(hostDir, 'ui', `${base}_ui.yaml`);
91
+ const eventPath = path.join(hostDir, 'event', `${base}_event.yaml`);
92
+ const uri = `file://${htmlPath}`;
93
+
94
+ if (!fs.existsSync(htmlPath)) continue;
95
+ const html = fs.readFileSync(htmlPath, 'utf8');
96
+ const htmlIds = extractSomaIdsFromHtml(html);
97
+
98
+ const uiYaml = fs.existsSync(uiPath) ? fs.readFileSync(uiPath, 'utf8') : '';
99
+ const eventYaml = fs.existsSync(eventPath) ? fs.readFileSync(eventPath, 'utf8') : '';
100
+ const showKeys = extractShowKeys(uiYaml);
101
+ const eventIds = extractEventIds(eventYaml);
102
+
103
+ for (const id of htmlIds) {
104
+ if (uiYaml && showKeys.size > 0 && !showKeys.has(id)) {
105
+ diagnostics.push({
106
+ uri,
107
+ range: rangeFromLoc(findAnchorInHtml(html, id)),
108
+ severity: 2,
109
+ code: 'orphan-html-anchor',
110
+ source: 'soma-cross-file',
111
+ message: `[${base}] HTML 锚点 "${id}" 未在 ${base}_ui.yaml show 中声明`,
112
+ });
113
+ }
114
+ }
115
+
116
+ for (const id of showKeys) {
117
+ if (!htmlIds.has(id)) {
118
+ diagnostics.push({
119
+ uri: `file://${uiPath}`,
120
+ range: rangeFromLoc(findKeyInYaml(uiYaml, id)),
121
+ severity: 2,
122
+ code: 'missing-html-anchor',
123
+ source: 'soma-cross-file',
124
+ message: `[${base}] ui show "${id}" 在 HTML 中无 data-soma-id`,
125
+ });
126
+ }
127
+ }
128
+
129
+ for (const id of eventIds) {
130
+ if (!htmlIds.has(id)) {
131
+ const eventYamlText = fs.existsSync(eventPath) ? fs.readFileSync(eventPath, 'utf8') : eventYaml;
132
+ const loc = eventYamlText
133
+ ? (() => {
134
+ const re = new RegExp(`^\\s*${id.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\.`, 'm');
135
+ const m = re.exec(eventYamlText);
136
+ if (!m) return null;
137
+ const before = eventYamlText.slice(0, m.index);
138
+ return {
139
+ line: before.split('\n').length - 1,
140
+ character: 0,
141
+ length: id.length,
142
+ };
143
+ })()
144
+ : null;
145
+ diagnostics.push({
146
+ uri: `file://${eventPath}`,
147
+ range: rangeFromLoc(loc),
148
+ severity: 1,
149
+ code: 'orphan-event-anchor',
150
+ source: 'soma-cross-file',
151
+ message: `[${base}] event "${id}" 在 HTML 中无对应 data-soma-id`,
152
+ });
153
+ }
154
+ }
155
+ }
156
+
157
+ return diagnostics;
158
+ }
159
+
160
+ module.exports = { lintAnchorConsistency, extractSomaIdsFromHtml, extractShowKeys, extractEventIds };
@@ -0,0 +1,106 @@
1
+ /**
2
+ * _event.yaml 智能补全:锚点事件、事件类型、domain 方法
3
+ */
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+
7
+ const EVENT_TYPES = ['UI_REFRESH', 'NAV_ACTION', 'NAV_STATIC', 'UI_INTERACT', 'CONFIRM'];
8
+ const TRIGGERS = ['click', 'input', 'change', 'keydown.enter', 'submit'];
9
+
10
+ function extractSomaIdsFromHtml(html) {
11
+ const ids = new Set();
12
+ for (const m of html.matchAll(/data-soma-id=["']([^"']+)["']/g)) {
13
+ ids.add(m[1]);
14
+ }
15
+ return [...ids].sort();
16
+ }
17
+
18
+ function scanDomainMethods(hostDir, pageBase) {
19
+ const methods = [];
20
+ const classPath = path.join(hostDir, 'domain', 'ui', `${pageBase}Class.ts`);
21
+ if (!fs.existsSync(classPath)) return methods;
22
+ const src = fs.readFileSync(classPath, 'utf8');
23
+ for (const m of src.matchAll(/^\s+async\s+(\w+)\s*\(/gm)) methods.push(m[1]);
24
+ for (const m of src.matchAll(/^\s+(\w+)\s*\([^)]*\)\s*[:{]/gm)) {
25
+ if (!['constructor', 'onMount', 'onUnmount'].includes(m[1])) methods.push(m[1]);
26
+ }
27
+ return [...new Set(methods)].sort();
28
+ }
29
+
30
+ function pageBaseFromUri(uri, hostDir) {
31
+ if (!uri) return null;
32
+ const filePath = decodeURIComponent(uri.replace(/^file:\/\//, ''));
33
+ if (hostDir) {
34
+ const hostRoot = path.resolve(hostDir);
35
+ const resolved = path.resolve(filePath);
36
+ if (resolved.startsWith(hostRoot)) {
37
+ const rel = path.relative(hostRoot, resolved);
38
+ const mm = rel.match(/^event[/\\](.+)_event\.yaml$/);
39
+ if (mm) return mm[1].replace(/\\/g, '/');
40
+ }
41
+ }
42
+ const name = path.basename(filePath);
43
+ const m = name.match(/^(.+)_event\.yaml$/);
44
+ return m ? m[1] : null;
45
+ }
46
+
47
+ function linePrefix(text, position) {
48
+ const lines = text.split('\n');
49
+ return (lines[position.line] ?? '').slice(0, position.character);
50
+ }
51
+
52
+ function completionItem(label, detail, kind = 10) {
53
+ return { label, kind, detail, insertText: label };
54
+ }
55
+
56
+ function getEventYamlCompletions(hostDir, uri, text, position) {
57
+ const pageBase = pageBaseFromUri(uri, hostDir);
58
+ if (!pageBase) return [];
59
+
60
+ const prefix = linePrefix(text, position);
61
+ const trimmed = prefix.trim();
62
+ const items = [];
63
+
64
+ const htmlPath = path.join(hostDir, 'html', `${pageBase}.html`);
65
+ const somaIds = fs.existsSync(htmlPath) ? extractSomaIdsFromHtml(fs.readFileSync(htmlPath, 'utf8')) : [];
66
+ const methods = scanDomainMethods(hostDir, pageBase);
67
+
68
+ const anchorPartial = trimmed.match(/^([\w@]+)?$/);
69
+ if (anchorPartial && !trimmed.includes(':') && !trimmed.includes('|')) {
70
+ for (const id of somaIds) {
71
+ for (const trig of TRIGGERS) {
72
+ const label = `${id}.${trig}`;
73
+ if (!trimmed || label.startsWith(trimmed)) {
74
+ items.push(completionItem(`${label}: `, '事件锚点', 5));
75
+ }
76
+ }
77
+ }
78
+ return items;
79
+ }
80
+
81
+ const afterColon = prefix.match(/:\s*(\w*)$/);
82
+ if (afterColon) {
83
+ const partial = afterColon[1] ?? '';
84
+ for (const t of EVENT_TYPES) {
85
+ if (!partial || t.startsWith(partial)) {
86
+ items.push(completionItem(`${t} | `, '事件类型', 14));
87
+ }
88
+ }
89
+ return items;
90
+ }
91
+
92
+ const afterPipe = prefix.match(/\|\s*(page\.)?(\w*)$/);
93
+ if (afterPipe) {
94
+ const partial = afterPipe[2] ?? '';
95
+ for (const m of methods) {
96
+ if (!partial || m.startsWith(partial)) {
97
+ items.push(completionItem(`page.${m}`, 'domain 方法', 2));
98
+ }
99
+ }
100
+ return items;
101
+ }
102
+
103
+ return items;
104
+ }
105
+
106
+ module.exports = { getEventYamlCompletions, EVENT_TYPES, TRIGGERS };
@@ -0,0 +1,64 @@
1
+ /**
2
+ * locale.yaml 与 html data-soma-id 补全
3
+ */
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const yaml = require('js-yaml');
7
+
8
+ const ANCHOR_PREFIXES = ['btn_', 'input_', 'txt_', 'list_', 'section_', 'nav_', 'link_', 'hero_'];
9
+
10
+ function loadLocaleKeys(hostDir) {
11
+ const localePath = path.join(hostDir, 'config', 'locale.yaml');
12
+ if (!fs.existsSync(localePath)) return [];
13
+ try {
14
+ const doc = yaml.load(fs.readFileSync(localePath, 'utf8'));
15
+ return Object.keys(doc ?? {}).sort();
16
+ } catch {
17
+ return [];
18
+ }
19
+ }
20
+
21
+ function getLocaleYamlCompletions(hostDir, _uri, text, position) {
22
+ const prefix = (text.split('\n')[position.line] ?? '').slice(0, position.character);
23
+ const keyPartial = prefix.match(/^([\w_]+)$/)?.[1] ?? '';
24
+ const keys = loadLocaleKeys(hostDir);
25
+ return keys
26
+ .filter((k) => !keyPartial || k.startsWith(keyPartial))
27
+ .map((k) => ({ label: `${k}: `, kind: 12, detail: 'locale.yaml 文案键' }));
28
+ }
29
+
30
+ function getHtmlAnchorCompletions(hostDir, uri, text, position) {
31
+ const filePath = decodeURIComponent(uri.replace(/^file:\/\//, ''));
32
+ const pageBase = path.basename(filePath, '.html');
33
+ const uiPath = path.join(hostDir, 'ui', `${pageBase}_ui.yaml`);
34
+ const existing = new Set();
35
+ for (const m of text.matchAll(/data-soma-id=["']([^"']+)["']/g)) existing.add(m[1]);
36
+
37
+ const suggestions = [];
38
+ if (fs.existsSync(uiPath)) {
39
+ try {
40
+ const doc = yaml.load(fs.readFileSync(uiPath, 'utf8'));
41
+ if (doc?.show) {
42
+ for (const k of Object.keys(doc.show)) {
43
+ if (!existing.has(k)) {
44
+ suggestions.push({ label: `data-soma-id="${k}"`, kind: 5, detail: 'ui.yaml show 键' });
45
+ }
46
+ }
47
+ }
48
+ } catch {
49
+ /* ignore */
50
+ }
51
+ }
52
+
53
+ const line = text.split('\n')[position.line] ?? '';
54
+ const partial = line.match(/data-soma-id=["']([\w_]*)$/)?.[1] ?? '';
55
+ for (const p of ANCHOR_PREFIXES) {
56
+ const id = `${p}new`;
57
+ if (!partial || id.startsWith(partial)) {
58
+ suggestions.push({ label: `data-soma-id="${id}"`, kind: 5, detail: '命名建议' });
59
+ }
60
+ }
61
+ return suggestions;
62
+ }
63
+
64
+ module.exports = { getLocaleYamlCompletions, getHtmlAnchorCompletions, loadLocaleKeys };