soma-core 1.5.1 → 2.0.0

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 (173) hide show
  1. package/app/SomaPageClient.tsx +28 -9
  2. package/app/soma/manifest/route.ts +3 -0
  3. package/bin/migrate.cjs +71 -1
  4. package/bin/soma-lsp.cjs +8 -1
  5. package/core/build/blocks/block-compile.ts +23 -5
  6. package/core/build/compiler/full-manifest-builder.ts +15 -0
  7. package/core/build/compiler/page-assets.ts +17 -1
  8. package/core/build/compiler/page-declaration-compiler.ts +67 -11
  9. package/core/build/compiler/precompiled-manifest-loader.ts +7 -0
  10. package/core/build/compiler/soma-manifest-webpack-plugin.js +7 -0
  11. package/core/build/compiler/soma-precompile.js +212 -21
  12. package/core/build/component/package-loader.ts +35 -4
  13. package/core/build/component-tree/artifact-codec.ts +192 -0
  14. package/core/build/component-tree/binding-bridge.ts +272 -0
  15. package/core/build/component-tree/collection-binding-lowerer.ts +65 -0
  16. package/core/build/component-tree/definition-preparation.ts +320 -0
  17. package/core/build/component-tree/migration-files.ts +214 -0
  18. package/core/build/component-tree/migration.ts +170 -0
  19. package/core/build/component-tree/parser.ts +362 -0
  20. package/core/build/component-tree/registry-snapshot.ts +317 -0
  21. package/core/build/component-tree/source-preflight.ts +132 -0
  22. package/core/build/component-tree/structure-topology.ts +63 -0
  23. package/core/build/component-tree/validator.ts +318 -0
  24. package/core/build/eject/component-eject.ts +1 -0
  25. package/core/build/lsp/component-tree-service.ts +79 -0
  26. package/core/build/lsp/component-tree.cjs +42 -0
  27. package/core/build/lsp/cross-file-diagnostics.cjs +15 -3
  28. package/core/build/lsp/extra-completion.cjs +7 -0
  29. package/core/client/adaptive/observer-pool.ts +122 -8
  30. package/core/client/compiler/manifest-compiler.ts +48 -5
  31. package/core/client/component/ai-catalog.ts +41 -3
  32. package/core/client/component/catalog-examples.ts +60 -0
  33. package/core/client/component/component-defaults.ts +1 -1
  34. package/core/client/component/component-definition.types.ts +9 -0
  35. package/core/client/component/component-expander.ts +22 -6
  36. package/core/client/component/component-manager.ts +881 -45
  37. package/core/client/component/component-pack.ts +1 -1
  38. package/core/client/component/component-registry.ts +11 -2
  39. package/core/client/component/scoped-adapter.ts +29 -2
  40. package/core/client/component/structure-adapter.ts +207 -0
  41. package/core/client/component/verify-pack.ts +21 -1
  42. package/core/client/container/SomaContainerAdapter.ts +103 -2
  43. package/core/client/data/data-object-resolver.ts +45 -1
  44. package/core/client/engine/asset-resolver.ts +1 -1
  45. package/core/client/engine/dom-renderer.ts +712 -26
  46. package/core/client/engine/event-engine.ts +328 -21
  47. package/core/client/engine/property-watcher.ts +164 -18
  48. package/core/client/engine/reactive-proxy.ts +194 -23
  49. package/core/client/engine/render-engine.ts +120 -11
  50. package/core/client/engine/row-range.ts +62 -0
  51. package/core/client/engine/row-scope.ts +77 -0
  52. package/core/client/engine/runtime-builder.ts +2 -0
  53. package/core/client/engine/scope-resolver.ts +3 -3
  54. package/core/client/engine/soma-bootstrap.ts +176 -17
  55. package/core/client/parser/adaptive-parser.ts +1 -1
  56. package/core/client/parser/annotation-extractor.ts +1 -1
  57. package/core/client/parser/blocks/page-parser.ts +53 -3
  58. package/core/client/parser/blocks/use-parser.ts +21 -6
  59. package/core/client/parser/data-config-parser.ts +1 -1
  60. package/core/client/parser/pipeline-parser.ts +252 -15
  61. package/core/client/parser/style-config-parser.ts +1 -1
  62. package/core/client/parser/timer-parser.ts +1 -1
  63. package/core/client/parser/trigger-parser.ts +1 -1
  64. package/core/client/parser/ui-config-parser.ts +39 -7
  65. package/core/client/pipes/pipe-registry.ts +45 -4
  66. package/core/client/registry/declaration-renderer.ts +32 -24
  67. package/core/client/registry/remote-page.ts +1 -1
  68. package/core/client/runtime/SomaSnapshotStore.ts +1 -1
  69. package/core/client/scheduler/SomaScheduler.ts +1 -1
  70. package/core/client/security/attribute-presence.ts +3 -0
  71. package/core/client/theme/harmony.ts +135 -13
  72. package/core/client/theme/scene-tokens.ts +17 -2
  73. package/core/client/theme/theme-axes.ts +43 -6
  74. package/core/client/theme/theme-engine.ts +921 -126
  75. package/core/client/validation/contract-validator.ts +2 -2
  76. package/core/index.ts +3 -0
  77. package/core/server/host/page-markup-config.ts +42 -0
  78. package/core/server/host/published-page-artifact-cache.ts +36 -4
  79. package/core/server/host/published-page-assets.ts +13 -7
  80. package/core/server/host/resolve-host-tree-context.ts +43 -0
  81. package/core/server/host/server-page-assets.ts +23 -4
  82. package/core/server/host/soma-page-compile.ts +10 -0
  83. package/core/server/mock/node/cli.mjs +3 -3
  84. package/core/server/page-declaration.ts +7 -0
  85. package/core/server/registry/declaration-precompiler.ts +35 -3
  86. package/core/server/registry/page-registry-repository.ts +31 -3
  87. package/core/server/registry/page-registry-store.ts +64 -7
  88. package/core/server/registry/publish-asset-pin.ts +6 -1
  89. package/core/server/registry/services/pages/Get.ts +11 -6
  90. package/core/server/registry/validation/compile-gate.ts +10 -1
  91. package/core/shared/component-tree-artifact.ts +237 -0
  92. package/core/shared/component-tree-errors.ts +52 -0
  93. package/core/shared/path-algebra.ts +1 -1
  94. package/core/shared/types/component-contract.types.ts +51 -0
  95. package/core/shared/types/component-tree-artifact.types.ts +121 -0
  96. package/core/shared/types/component-tree.types.ts +170 -0
  97. package/core/shared/types/engine.types.ts +5 -0
  98. package/core/shared/types/event.types.ts +8 -4
  99. package/core/shared/types/manifest.types.ts +4 -0
  100. package/core/shared/types/ui-config.types.ts +8 -0
  101. package/dist/cli/soma.js +1 -1
  102. package/dist/core/index.cjs +14508 -11358
  103. package/dist/lsp/component-tree.cjs +20997 -0
  104. package/dist/types/build/blocks/block-compile.d.ts +10 -1
  105. package/dist/types/build/compiler/full-manifest-builder.d.ts +9 -0
  106. package/dist/types/build/compiler/page-assets.d.ts +6 -1
  107. package/dist/types/build/compiler/page-declaration-compiler.d.ts +11 -1
  108. package/dist/types/build/component/package-loader.d.ts +4 -1
  109. package/dist/types/build/component-tree/artifact-codec.d.ts +50 -0
  110. package/dist/types/build/component-tree/binding-bridge.d.ts +19 -0
  111. package/dist/types/build/component-tree/collection-binding-lowerer.d.ts +18 -0
  112. package/dist/types/build/component-tree/definition-preparation.d.ts +11 -0
  113. package/dist/types/build/component-tree/migration-files.d.ts +35 -0
  114. package/dist/types/build/component-tree/migration.d.ts +28 -0
  115. package/dist/types/build/component-tree/parser.d.ts +13 -0
  116. package/dist/types/build/component-tree/registry-snapshot.d.ts +15 -0
  117. package/dist/types/build/component-tree/source-preflight.d.ts +22 -0
  118. package/dist/types/build/component-tree/structure-topology.d.ts +7 -0
  119. package/dist/types/build/component-tree/validator.d.ts +9 -0
  120. package/dist/types/build/lsp/component-tree-service.d.ts +34 -0
  121. package/dist/types/client/adaptive/observer-pool.d.ts +9 -2
  122. package/dist/types/client/compiler/manifest-compiler.d.ts +11 -2
  123. package/dist/types/client/component/ai-catalog.d.ts +18 -1
  124. package/dist/types/client/component/catalog-examples.d.ts +18 -0
  125. package/dist/types/client/component/component-definition.types.d.ts +9 -0
  126. package/dist/types/client/component/component-expander.d.ts +2 -1
  127. package/dist/types/client/component/component-manager.d.ts +97 -0
  128. package/dist/types/client/component/scoped-adapter.d.ts +1 -0
  129. package/dist/types/client/component/structure-adapter.d.ts +17 -0
  130. package/dist/types/client/container/SomaContainerAdapter.d.ts +8 -0
  131. package/dist/types/client/data/data-object-resolver.d.ts +19 -0
  132. package/dist/types/client/engine/dom-renderer.d.ts +125 -2
  133. package/dist/types/client/engine/event-engine.d.ts +62 -3
  134. package/dist/types/client/engine/property-watcher.d.ts +41 -1
  135. package/dist/types/client/engine/reactive-proxy.d.ts +42 -2
  136. package/dist/types/client/engine/render-engine.d.ts +55 -3
  137. package/dist/types/client/engine/row-range.d.ts +13 -0
  138. package/dist/types/client/engine/row-scope.d.ts +20 -0
  139. package/dist/types/client/engine/runtime-builder.d.ts +1 -0
  140. package/dist/types/client/engine/soma-bootstrap.d.ts +4 -1
  141. package/dist/types/client/parser/blocks/use-parser.d.ts +18 -0
  142. package/dist/types/client/parser/pipeline-parser.d.ts +12 -4
  143. package/dist/types/client/parser/ui-config-parser.d.ts +2 -0
  144. package/dist/types/client/pipes/pipe-registry.d.ts +39 -1
  145. package/dist/types/client/registry/declaration-renderer.d.ts +5 -1
  146. package/dist/types/client/registry/remote-page.d.ts +1 -1
  147. package/dist/types/client/theme/harmony.d.ts +44 -2
  148. package/dist/types/client/theme/scene-tokens.d.ts +11 -1
  149. package/dist/types/client/theme/theme-axes.d.ts +36 -6
  150. package/dist/types/index.d.ts +3 -1
  151. package/dist/types/server/host/page-markup-config.d.ts +6 -0
  152. package/dist/types/server/host/published-page-artifact-cache.d.ts +9 -1
  153. package/dist/types/server/host/published-page-assets.d.ts +5 -3
  154. package/dist/types/server/host/resolve-host-tree-context.d.ts +8 -0
  155. package/dist/types/server/host/server-page-assets.d.ts +6 -0
  156. package/dist/types/server/host/soma-page-compile.d.ts +10 -1
  157. package/dist/types/server/page-declaration.d.ts +6 -0
  158. package/dist/types/server/registry/declaration-precompiler.d.ts +8 -3
  159. package/dist/types/server/registry/page-registry-repository.d.ts +5 -0
  160. package/dist/types/server/registry/page-registry-store.d.ts +11 -1
  161. package/dist/types/server/registry/publish-asset-pin.d.ts +4 -0
  162. package/dist/types/server/registry/validation/compile-gate.d.ts +4 -1
  163. package/dist/types/shared/component-tree-artifact.d.ts +5 -0
  164. package/dist/types/shared/component-tree-errors.d.ts +22 -0
  165. package/dist/types/shared/types/component-contract.types.d.ts +42 -0
  166. package/dist/types/shared/types/component-tree-artifact.types.d.ts +104 -0
  167. package/dist/types/shared/types/component-tree.types.d.ts +149 -0
  168. package/dist/types/shared/types/engine.types.d.ts +5 -0
  169. package/dist/types/shared/types/event.types.d.ts +8 -4
  170. package/dist/types/shared/types/manifest.types.d.ts +4 -0
  171. package/dist/types/shared/types/ui-config.types.d.ts +8 -0
  172. package/package.json +5 -4
  173. package/dist/preview-export.cjs +0 -3401
@@ -2,6 +2,7 @@
2
2
  // 属性变更观察者注册表 — RenderEngine.watch / onChange / triggers 共用
3
3
 
4
4
  import type { WatchCallback, WatcherOptions } from '../../shared/types/watcher.types';
5
+ import { unwrapReactive } from './reactive-proxy';
5
6
 
6
7
  interface WatcherEntry {
7
8
  id: number;
@@ -11,13 +12,32 @@ interface WatcherEntry {
11
12
  callback: WatchCallback;
12
13
  debounce?: number;
13
14
  timer?: ReturnType<typeof setTimeout>;
15
+ /** 取消监听时置真:本轮通知发的是一张快照,取消掉的这枚还留在快照里,靠这个标记跳过 */
16
+ disposed?: boolean;
14
17
  }
15
18
 
16
19
  let nextWatcherId = 1;
17
20
 
21
+ /**
22
+ * 通知同步重入的层数上限。
23
+ *
24
+ * 回调里回写了自己(或自己祖先)监听得到的路径就是一个环。最常见的那条写法:
25
+ * `bind.onChange: { condition: q.rows, callback: refetch }`,而 `refetch()` 里
26
+ * `this.q = { page: this.q.page, rows: 新数组 }`——祖先分支开通之前这条是哑的
27
+ * (改 `q` 不惊动盯 `q.rows` 的),现在一发就是一圈。每轮重查拿回来的都是**新数组**,
28
+ * 值是真变了,下面那道"值没变就不发"的闸门拦不住它,拦得住的只有层数:
29
+ * 不拦就是 400 来圈之后 `RangeError: Maximum call stack size exceeded`,整页崩掉;
30
+ * 拦住就是控制台一条点名路径与链路的错误,页面还活着。
31
+ * 正常链路(A 变 → 回调改 B → B 的监听者改 C)现实里三五层顶天,50 层只可能是环。
32
+ * 只管同步重入:回调里有 await 的话栈本来就不会叠起来(那是另一种转不停,这里够不着)。
33
+ */
34
+ const MAX_NOTIFY_DEPTH = 50;
35
+
18
36
  export class SomaPropertyWatcher {
19
37
  private entries: WatcherEntry[] = [];
20
38
  private root: object = {};
39
+ /** 正在下发的路径栈:长度就是重入层数,撞闸时顺带把链路打出来 */
40
+ private notifyStack: string[] = [];
21
41
 
22
42
  setRoot(root: object): void {
23
43
  this.root = root;
@@ -48,44 +68,160 @@ export class SomaPropertyWatcher {
48
68
 
49
69
  return () => {
50
70
  if (entry.timer) clearTimeout(entry.timer);
71
+ entry.disposed = true;
51
72
  this.entries = this.entries.filter((e) => e.id !== entry.id);
52
73
  };
53
74
  }
54
75
 
55
76
  /** Proxy set trap 驱动:通知所有匹配的 watcher */
56
77
  notify(changedPath: string, newValue: unknown, oldValue: unknown): void {
57
- for (const entry of this.entries) {
58
- if (!this.matches(entry.watchPath, changedPath, entry.prefix, entry.glob)) {
59
- continue;
60
- }
78
+ // 重入闸:见 MAX_NOTIFY_DEPTH。截断这一发,不抛——抛出去会顺着回调栈把页面别处的写入一起带倒。
79
+ if (this.notifyStack.length >= MAX_NOTIFY_DEPTH) {
80
+ console.error(
81
+ `[soma-core][引擎] 通知重入 ${MAX_NOTIFY_DEPTH} 层,"${changedPath}" 这一发不再下发:`
82
+ + '多半是 watch / bind.onChange 的回调回写了自己监听的路径。最近的链路:'
83
+ + `${this.notifyStack.slice(-6).join(' → ')} → ${changedPath}`,
84
+ );
85
+ return;
86
+ }
61
87
 
62
- if (entry.debounce && entry.debounce > 0) {
63
- if (entry.timer) clearTimeout(entry.timer);
64
- entry.timer = setTimeout(() => {
65
- entry.timer = undefined;
66
- void this.invoke(entry, newValue, oldValue, changedPath);
67
- }, entry.debounce);
68
- } else {
69
- void this.invoke(entry, newValue, oldValue, changedPath);
88
+ // 先拍快照再发。entries 是活数组:回调里重渲挂上新的行内实例时,component-manager 会当场
89
+ // watch 一条子路径,边发边追进来的那枚本轮不该被叫(它要的值就是正在下发的这个)。
90
+ const snapshot = this.entries.slice();
91
+ this.notifyStack.push(changedPath);
92
+ try {
93
+ for (const entry of snapshot) {
94
+ // 快照拍完之后被取消的(回调里卸掉了一个行内实例)不再叫:作用域都拆了
95
+ if (entry.disposed) {
96
+ continue;
97
+ }
98
+
99
+ const hit = this.resolveHit(entry, changedPath, newValue, oldValue);
100
+ if (!hit) {
101
+ continue;
102
+ }
103
+
104
+ if (entry.debounce && entry.debounce > 0) {
105
+ if (entry.timer) clearTimeout(entry.timer);
106
+ entry.timer = setTimeout(() => {
107
+ entry.timer = undefined;
108
+ void this.invoke(entry, hit.newValue, hit.oldValue, hit.path);
109
+ }, entry.debounce);
110
+ } else {
111
+ void this.invoke(entry, hit.newValue, hit.oldValue, hit.path);
112
+ }
70
113
  }
114
+ } finally {
115
+ this.notifyStack.pop();
71
116
  }
72
117
  }
73
118
 
74
119
  destroy(): void {
75
120
  for (const entry of this.entries) {
76
121
  if (entry.timer) clearTimeout(entry.timer);
122
+ entry.disposed = true;
77
123
  }
78
124
  this.entries = [];
79
125
  }
80
126
 
81
- private matches(watchPath: string, changedPath: string, prefix: boolean, glob: boolean): boolean {
82
- if (glob || watchPath.includes('*')) {
83
- return matchGlobPath(watchPath, changedPath);
127
+ /**
128
+ * 这条变更该不该下发给这个监听者,以及下发什么值、报哪条路径。
129
+ *
130
+ * 路径关系只有四种,逐一对上:
131
+ *
132
+ * 1. **同一条路径**(改 `form.title`,盯 `form.title`):原样下发。
133
+ * 2. **改的在监听路径底下**(改 `form.title`,盯 `form`):只有前缀监听者要,
134
+ * 值与 `ctx.path` 都用变更点自己的——`prefix: false` 的(`bind.onChange`、`triggers`)
135
+ * 明说了只认这一条路径,不能被子孙吵醒。
136
+ * 3. **改的是监听路径的祖先**(改 `form`,盯 `form.title`):**过去这一路整个是哑的**。
137
+ * `page.form = { title: '新' }` 之后,绑 `page.form.title` 的组件 props 停在旧值,
138
+ * 行内实例读页面路径的那份订阅(component-manager 的 rowPageWatches)同样停住——
139
+ * 页面不报错,只是不动。本条现在照样下发,而且**不分 prefix**:
140
+ * 父被整体换掉时,`form.title` 这条路径上的值是真的变了,
141
+ * "只认这一条路径"的监听者更该收到,`bind.onChange` / `triggers` 过去一并漏了。
142
+ * 4. **毫无关系**:不发。
143
+ *
144
+ * 第 3 条的三个细节:
145
+ * - **下发的是子路径自己的新值**,从新父对象里按剩余段重新取(不是把父对象塞给子监听者),
146
+ * 旧值同样从旧父对象里取——`ctx.path` 于是仍然和 `newValue` 描述同一个位置;
147
+ * 父被换成 `null` / `undefined`,或新父对象里根本没这个键,取到的就是 `undefined`。
148
+ * - **值没变就不发**:父换了一个新壳、子路径上还是同一个东西(`this.form = { ...this.form }`
149
+ * 这种为强制重渲写的整体替换),下发一遍只是白跑一轮重解析。判据是 `Object.is`,
150
+ * **对象与数组按引用相等也算没变**——这里**不能照搬代理层 `sameScalarValue` 的口径**
151
+ * (那边对象一律算变了):代理层比的是"这个键被写了什么",引用替换本身就是 SOMA 的更新信号;
152
+ * 这条比的是"父换了壳之后,子路径上还是不是同一个东西",引用没动就是没动。
153
+ * 硬判成变了的代价是自激:`bind.onChange: q.rows → refetch()`、`refetch` 又整体换掉 `q`,
154
+ * 一发一圈,实测 400 圈爆栈;退一步说,50 个实例 × 6 条 prop 源路径只改一个标量字段,
155
+ * 也会从 50 次 setProps 涨到 200 次(`rows` / `cols` / `meta` 引用没动却全量重渲)。
156
+ * 真环(每轮值都新)另有 MAX_NOTIFY_DEPTH 那道层数闸兜着。
157
+ * 旧值那一侧读得出来才敢判;读旧值抛异常时当没有旧值,照发(见下一条)。
158
+ * batch 收口的旧值现在是**真旧值**(reactive-proxy 的 endBatch 发的是 batch 内第一次写之前
159
+ * 的那个),所以 batch 里的整体替换和非 batch 走同一把尺子,不再因为"没有旧值"整个漏判。
160
+ * - **旧值读不出来不吞通知**:旧父对象上的访问器抛了,只说明"没有旧值可比",
161
+ * 新值明明读得到,照样下发(过去两次读共用一个 try,旧值一抛,整条通知连同新值一起没了)。
162
+ * - **通配符监听者不走这条**:`page.*.status` 在父被替换时该派发哪几条具体路径,
163
+ * 得把新父对象整个枚举一遍才知道,通知量不可控;维持原状(只按等长分段匹配)。
164
+ */
165
+ private resolveHit(
166
+ entry: WatcherEntry,
167
+ changedPath: string,
168
+ newValue: unknown,
169
+ oldValue: unknown,
170
+ ): { newValue: unknown; oldValue: unknown; path: string } | null {
171
+ const watchPath = entry.watchPath;
172
+
173
+ if (entry.glob || watchPath.includes('*')) {
174
+ return matchGlobPath(watchPath, changedPath)
175
+ ? { newValue, oldValue, path: changedPath }
176
+ : null;
84
177
  }
85
- if (!prefix) {
86
- return watchPath === changedPath;
178
+
179
+ // 1. 同一条路径
180
+ if (changedPath === watchPath) {
181
+ return { newValue, oldValue, path: changedPath };
182
+ }
183
+
184
+ // 2. 改的在监听路径底下。补一个点再比,分段就分干净了:
185
+ // 盯 `form`、改 `formX` 时 `"formX".startsWith("form.")` 为假,同级相似名字不会误播。
186
+ if (entry.prefix && changedPath.startsWith(`${watchPath}.`)) {
187
+ return { newValue, oldValue, path: changedPath };
87
188
  }
88
- return changedPath === watchPath || changedPath.startsWith(`${watchPath}.`);
189
+
190
+ // 3. 改的是监听路径的祖先(同样补点分段,改 `formX` 不会惊动盯 `form.title` 的)
191
+ if (!watchPath.startsWith(`${changedPath}.`)) {
192
+ return null;
193
+ }
194
+
195
+ const rest = watchPath.slice(changedPath.length + 1);
196
+
197
+ let childNew: unknown;
198
+ try {
199
+ childNew = readSubPath(newValue, rest);
200
+ } catch (e) {
201
+ // 新父对象上的访问器抛了:这一条没有值可发,只能不发。吞掉只影响这一个监听者,
202
+ // 不吞会把这一轮剩下的监听者一起带走。
203
+ console.error(`[soma-core][引擎] read new "${watchPath}" after "${changedPath}" changed:`, e);
204
+ return null;
205
+ }
206
+
207
+ // 旧值单独一个 try:它只用来判"值没变",读不出来就当没有旧值,新值照发。
208
+ let childOld: unknown;
209
+ let oldReadable = true;
210
+ try {
211
+ childOld = readSubPath(oldValue, rest);
212
+ } catch (e) {
213
+ console.error(`[soma-core][引擎] read old "${watchPath}" after "${changedPath}" changed:`, e);
214
+ childOld = undefined;
215
+ oldReadable = false;
216
+ }
217
+
218
+ // 比之前先剥壳:新父对象是页面自己拼的字面量,`{ meta: this.form.meta }` 里放着的是读的时候
219
+ // 套上的那层代理,旧父对象上放着的是原始对象——不剥就把同一个对象判成两个,白发一轮。
220
+ if (oldReadable && Object.is(unwrapReactive(childOld), unwrapReactive(childNew))) {
221
+ return null;
222
+ }
223
+
224
+ return { newValue: childNew, oldValue: childOld, path: watchPath };
89
225
  }
90
226
 
91
227
  private async invoke(
@@ -102,6 +238,16 @@ export class SomaPropertyWatcher {
102
238
  }
103
239
  }
104
240
 
241
+ /** 从父对象上按剩余路径段取值;中途断了(null / undefined)就是 undefined */
242
+ function readSubPath(parent: unknown, rest: string): unknown {
243
+ let current: any = parent;
244
+ for (const seg of rest.split('.')) {
245
+ if (current === null || current === undefined) return undefined;
246
+ current = current[seg];
247
+ }
248
+ return current;
249
+ }
250
+
105
251
  /** 通配符路径匹配:`*` 匹配单段(如 a.*.c 匹配 a.b.c) */
106
252
  export function matchGlobPath(pattern: string, path: string): boolean {
107
253
  const patternParts = pattern.split('.');
@@ -6,6 +6,107 @@ const ARRAY_MUTATING_METHODS = new Set([
6
6
  'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill',
7
7
  ]);
8
8
 
9
+ /**
10
+ * 数组变异守卫开不开:**按环境判定,不再默认开着**。
11
+ *
12
+ * 这条告警是写给开发者看的("就地 push 不触发更新,请改引用替换"),生产页面上没人读它,
13
+ * 却要为它付两笔账:每读一次数组就 new 一个 Proxy,以及每次就地改都往控制台灌一条 warn。
14
+ * 过去构造参数写死 `devMode = true`,而 soma-bootstrap 建代理时只传两参(第 560 / 660 行),
15
+ * 于是所有生产页面都开着。
16
+ *
17
+ * 判据顺序与 data-object-resolver 的 isSomaMockEnabled 同一套路:
18
+ * 1. `globalThis.SOMA_DEV_GUARD`——宿主 / 控制台的显式开关,真假都认(线上想临时查一次就置真);
19
+ * 2. 构建期注入的 `NODE_ENV`——非 production 即开。打包器把这个成员表达式整体换成字面量,
20
+ * 生产包里这一段连同守卫分支一起被摇掉;
21
+ * 3. 两样都拿不到(纯浏览器、没有打包器 define)——**当生产处理,关**。
22
+ * 没有判据时宁可少一条开发期告警,也不给生产页面留下上面那两笔账;
23
+ * 要在这种环境里开,置 `globalThis.SOMA_DEV_GUARD = true` 即可。
24
+ */
25
+ export function isSomaArrayGuardEnabled(): boolean {
26
+ const flag = (globalThis as Record<string, unknown>).SOMA_DEV_GUARD;
27
+ if (flag !== undefined) return flag === true || flag === '1' || flag === 'true';
28
+ let env: string | undefined;
29
+ try {
30
+ env = typeof process !== 'undefined' && process.env ? process.env.NODE_ENV : undefined;
31
+ } catch {
32
+ env = undefined; // 浏览器里根本没有 process
33
+ }
34
+ return env !== undefined && env !== 'production';
35
+ }
36
+
37
+ /**
38
+ * 数组守卫代理 → 它包着的那个原始数组。
39
+ *
40
+ * set 陷阱存回 target 之前据此剥壳。不剥的话,第 15 行写明的那条合法写法
41
+ * (`const a = this.list; a.push(x); this.list = a`)会把守卫代理**本身**存进 target,
42
+ * 下一次读再包一层:每叠一层,同一次 push 就多播报一条告警、多一层读取转发,
43
+ * 而且永远剥不掉(`util.types.isProxy(实例.list)` 从此恒为真)。
44
+ * 键是弱引用,守卫代理没人引用时自动失效,不占账。
45
+ */
46
+ const ARRAY_GUARD_TARGETS = new WeakMap<object, any[]>();
47
+
48
+ /** 剥掉数组守卫的壳拿回原始数组;循环是为了把已经叠起来的多层一次剥净(非守卫值原样返回) */
49
+ function unwrapArrayGuard(value: any): any {
50
+ let current = value;
51
+ let raw = ARRAY_GUARD_TARGETS.get(current);
52
+ while (raw !== undefined) {
53
+ current = raw;
54
+ raw = ARRAY_GUARD_TARGETS.get(current);
55
+ }
56
+ return current;
57
+ }
58
+
59
+ /**
60
+ * 响应式 Proxy → 它包着的那个原始对象。与 ARRAY_GUARD_TARGETS 同一个用途,治的是同一种病:
61
+ * **读出来的那层壳被原样存了回去**。
62
+ *
63
+ * `this.form = { meta: this.form.meta, rows: this.form.rows }`(为强制重渲写的整体替换)里,
64
+ * `this.form.meta` 读出来是一层子 Proxy,被塞进新的对象字面量——set 陷阱只剥最外层那个值,
65
+ * 字面量里面的剥不到。于是下一次读 `form.meta` 时 get 陷阱又包一层,克隆几次就叠几层:
66
+ * 叠 10 层之后写一笔 `form.meta.x`,同一条路径要发 11 遍通知(每遍都带一轮 schedulePatch、
67
+ * 样式绑定与全量 watch)。把子对象挪到另一条路径(`this.other = this.form.meta`)更直接:
68
+ * 写 `other.x` 一笔,旧壳按自己烙进去的老路径也报一条 `form.meta.x`,路径是错的。
69
+ * 所以读的时候先剥回原始对象再按当前路径包壳,写的时候也剥。
70
+ * 键是弱引用,壳没人引用时自动失效,不占账。
71
+ */
72
+ const REACTIVE_PROXY_TARGETS = new WeakMap<object, any>();
73
+
74
+ /**
75
+ * 剥掉响应式 Proxy 的壳拿回原始对象;循环是为了把已经叠起来的多层一次剥净(非代理值原样返回)。
76
+ *
77
+ * property-watcher 判"父被换掉之后子路径上的值到底变没变"时也要用:它拿到的是 onChange 发来的
78
+ * 裸对象图,`newValue.meta` 上放着的可能正是上面说的那层壳,不剥就会把"同一个对象"判成两个。
79
+ */
80
+ export function unwrapReactive(value: any): any {
81
+ let current = value;
82
+ let raw = REACTIVE_PROXY_TARGETS.get(current);
83
+ while (raw !== undefined) {
84
+ current = raw;
85
+ raw = REACTIVE_PROXY_TARGETS.get(current);
86
+ }
87
+ return current;
88
+ }
89
+
90
+ /**
91
+ * 写进去的值算不算"跟原来一样":**只认基本类型**(string / number / boolean / null / undefined /
92
+ * symbol / bigint,按 `Object.is`,所以 NaN 写 NaN 算一样、0 写 -0 算变了)。
93
+ *
94
+ * 对象、数组、函数一律算变了,哪怕引用一模一样。因为 SOMA 的对象与数组不靠内部劫持、就靠**引用替换**
95
+ * 触发更新(见 shouldSkip 与 wrapArrayDevGuard 的告警文案),下面两种写法都是真实变化:
96
+ * - 拿到引用就地改完再赋回去:`const a = this.list; a.push(x); this.list = a`;
97
+ * `this.selected.add(x); this.selected = this.selected`(Set / Map / Date 跳过代理,就地改是常规用法);
98
+ * - 内容一字不改的整体替换:`this.kpiCards = [...this.kpiCards]`,专门用来强制重渲——
99
+ * 数据没变、外部尺寸变了(soma-ui KPI 卡的宽度适配就是这么触发的)。
100
+ * 按内容比(逐元素 / 逐字段)比按引用比更糟:上面两种写法会被一起判成"没变",通知全丢。
101
+ *
102
+ * 所以代理层只吃下"同一个标量又写了一遍"这一类,别的交给各写入点自己的口径(见 set 陷阱里的说明)。
103
+ */
104
+ function sameScalarValue(oldValue: unknown, value: unknown): boolean {
105
+ if (value !== null && (typeof value === 'object' || typeof value === 'function')) return false;
106
+ if (oldValue !== null && (typeof oldValue === 'object' || typeof oldValue === 'function')) return false;
107
+ return Object.is(oldValue, value);
108
+ }
109
+
9
110
  /**
10
111
  * SOMA 响应式代理
11
112
  *
@@ -13,14 +114,23 @@ const ARRAY_MUTATING_METHODS = new Set([
13
114
  * - 使用 WeakMap 缓存,同一对象只创建一个 Proxy
14
115
  * - 跳过内置类型(Set/Map/Date 等);数组通过引用替换触发更新
15
116
  * - 函数绑定到 Proxy receiver,确保 this 正确
16
- * - devMode 开启时,数组变异方法调用会发出 warn(提示改用引用替换)
117
+ * - 同一个标量写第二遍不通知(见 sameScalarValue);对象与数组照旧写了就通知
118
+ * - devMode 开启时,数组变异方法调用会发出 warn(提示改用引用替换);
119
+ * 默认值由 isSomaArrayGuardEnabled() 按环境给,生产页面上是关的
17
120
  */
18
121
  export class SomaReactiveProxy {
19
122
  /** 原始对象 → Proxy 实例的缓存(仅用于顶层 wrap 调用) */
20
123
  private cache = new WeakMap<object, any>();
21
124
 
22
- /** 子对象 Proxy 缓存:避免每次 get 嵌套对象都 new Proxy() */
23
- private childProxyCache = new WeakMap<object, any>();
125
+ /**
126
+ * 子对象 Proxy 缓存:避免每次 get 嵌套对象都 new Proxy()。
127
+ *
128
+ * 按**原始对象 → 路径 → 壳**两层存,不是一个对象一个壳:路径是烙进壳里的(handler 的 basePath
129
+ * 决定它把变更报成哪条路径),同一个对象挂在两条路径下(`this.current = this.form.meta`)就得有
130
+ * 两个壳,否则写 `current.x` 会被报成 `form.meta.x`,盯 `current.x` 的绑定永远不动。
131
+ * 键是弱引用,对象没了整张路径表一起没。
132
+ */
133
+ private childProxyCache = new WeakMap<object, Map<string, any>>();
24
134
 
25
135
  /** 变更回调(可延迟设置) */
26
136
  private onChange: ((path: string, value: any, oldValue: any) => void) | null = null;
@@ -30,7 +140,9 @@ export class SomaReactiveProxy {
30
140
  constructor(
31
141
  onChange?: (path: string, value: any, oldValue: any) => void,
32
142
  diagnostics?: SomaDiagnostics,
33
- devMode: boolean = true,
143
+ // 不传就按环境判定(见 isSomaArrayGuardEnabled)。显式传参照旧压过环境:
144
+ // 测试要稳定复现告警就传 true,engine-factory 那样只想要干净输出就传 false。
145
+ devMode: boolean = isSomaArrayGuardEnabled(),
34
146
  ) {
35
147
  this.onChange = onChange ?? null;
36
148
  this.diagnostics = diagnostics ?? null;
@@ -45,7 +157,8 @@ export class SomaReactiveProxy {
45
157
  // ─── 批量变更支持 ──────────────────────────────────────
46
158
 
47
159
  private batchDepth = 0;
48
- private batchedPaths = new Map<string, any>();
160
+ /** batch 内攒下的变更:路径 → { 最后写进去的值, 这一批开始前的旧值 } */
161
+ private batchedPaths = new Map<string, { value: any; oldValue: any }>();
49
162
 
50
163
  /**
51
164
  * 开始批量变更事务。
@@ -59,6 +172,12 @@ export class SomaReactiveProxy {
59
172
  /**
60
173
  * 结束批量变更事务。
61
174
  * 最外层 endBatch 时,一次性触发所有收集的变更路径的 onChange 回调。
175
+ *
176
+ * 第三个参数发的是**这一批开始前**的旧值(同一条路径在批里写了三遍,旧值仍是进批之前那个)。
177
+ * 过去这里恒发 `undefined`:batch 里的 watch / bind.onChange 拿到的第二个参数与非 batch 路径
178
+ * 对不上(页面代码只能靠"是不是在 batch 里"来猜),property-watcher 那条"父被换掉但子路径上的值
179
+ * 没变就不发"的闸门也因为拿不到旧值而整个失效——批里做一次值一个没变的克隆替换,
180
+ * 所有子路径监听者全被叫醒。
62
181
  */
63
182
  endBatch(): void {
64
183
  if (this.batchDepth <= 0) return;
@@ -69,9 +188,9 @@ export class SomaReactiveProxy {
69
188
  this.batchedPaths.clear();
70
189
 
71
190
  // 一次性触发所有变更通知
72
- for (const [path, value] of paths) {
191
+ for (const [path, change] of paths) {
73
192
  try {
74
- if (this.onChange) this.onChange(path, value, undefined);
193
+ if (this.onChange) this.onChange(path, change.value, change.oldValue);
75
194
  } catch (e) {
76
195
  console.error('[soma-core][引擎] batch onChange error:', e);
77
196
  }
@@ -106,6 +225,7 @@ export class SomaReactiveProxy {
106
225
 
107
226
  const proxy = new Proxy(obj, this.createHandler(basePath));
108
227
  this.cache.set(obj, proxy);
228
+ REACTIVE_PROXY_TARGETS.set(proxy, obj);
109
229
  return proxy;
110
230
  }
111
231
 
@@ -137,29 +257,46 @@ export class SomaReactiveProxy {
137
257
  return value.bind(receiver);
138
258
  }
139
259
 
260
+ // 存进来的可能本身就是一层壳(页面把读出来的子对象塞回了新的对象字面量,
261
+ // set 陷阱只剥得到最外层那个值)。先剥回原始对象,再按**当前**路径包:
262
+ // 不剥就是每克隆一次父对象多叠一层壳,读写都顺着叠起来的层数翻倍(见 REACTIVE_PROXY_TARGETS)。
263
+ const bare = unwrapReactive(value);
264
+
140
265
  // 数组:dev 模式下拦截变异方法,发出警告
141
- if (Array.isArray(value) && self.devMode) {
142
- return self.wrapArrayDevGuard(value, basePath ? `${basePath}.${String(prop)}` : String(prop));
266
+ if (Array.isArray(bare) && self.devMode) {
267
+ return self.wrapArrayDevGuard(bare, basePath ? `${basePath}.${String(prop)}` : String(prop));
143
268
  }
144
269
 
145
- // 嵌套对象返回 Proxy 包装版本(缓存子 Proxy 减少 GC 压力)
146
- if (!self.shouldSkip(value)) {
147
- const cachedChild = self.childProxyCache.get(value);
270
+ // 嵌套对象返回 Proxy 包装版本(按路径缓存子 Proxy 减少 GC 压力)
271
+ if (!self.shouldSkip(bare)) {
272
+ const childPath = basePath ? `${basePath}.${String(prop)}` : String(prop);
273
+ let byPath = self.childProxyCache.get(bare);
274
+ const cachedChild = byPath?.get(childPath);
148
275
  if (cachedChild) return cachedChild;
149
276
 
150
- const childPath = basePath ? `${basePath}.${String(prop)}` : String(prop);
151
- const childProxy = new Proxy(value, self.createHandler(childPath));
152
- self.childProxyCache.set(value, childProxy);
277
+ const childProxy = new Proxy(bare, self.createHandler(childPath));
278
+ if (!byPath) {
279
+ byPath = new Map<string, any>();
280
+ self.childProxyCache.set(bare, byPath);
281
+ }
282
+ byPath.set(childPath, childProxy);
283
+ REACTIVE_PROXY_TARGETS.set(childProxy, bare);
153
284
  return childProxy;
154
285
  }
155
286
 
156
- return value;
287
+ return bare;
157
288
  },
158
289
 
159
290
  set(target: any, prop: string | symbol, value: any, receiver: any): boolean {
160
291
  const key = String(prop);
161
292
  const path = basePath ? `${basePath}.${key}` : key;
162
293
 
294
+ // 存回 target 的必须是原始数组 / 原始对象,不是读出来时套的那两层壳:
295
+ // dev 守卫壳(见 ARRAY_GUARD_TARGETS)与响应式代理壳(见 REACTIVE_PROXY_TARGETS)。
296
+ // 不剥壳的话壳会一层层叠上去,同一次 push 越报越多条,同一笔嵌套写越报越多遍,且再也剥不掉。
297
+ // 壳本身不受影响:下一次读照样现包一层新的,push 仍然报一条。
298
+ const raw = unwrapReactive(unwrapArrayGuard(value));
299
+
163
300
  // 旧值的子 Proxy 缓存失效
164
301
  const oldValue = Reflect.get(target, prop, receiver);
165
302
  if (oldValue != null && typeof oldValue === 'object') {
@@ -167,17 +304,40 @@ export class SomaReactiveProxy {
167
304
  }
168
305
 
169
306
  // accessor 内的 this 必须保持为 Proxy,派生赋值才能继续经过响应式层。
170
- const assigned = Reflect.set(target, prop, value, receiver);
307
+ const assigned = Reflect.set(target, prop, raw, receiver);
171
308
  if (!assigned) return false;
172
309
 
173
- // 通知变更(带异常防护)
310
+ // 同一个标量又写了一遍:不通知,也不记 mutation。
311
+ // 写入点不止一条路(控件回写、组件 model prop 回写、处理器里幂等的重算、定时器重算、
312
+ // 数据层回填),每条都可能把同一个值再写一遍;通知一次就带着 schedulePatch(整轮绑定重渲)、
313
+ // 样式绑定、watch / onChange / triggers 全跑一遍,mutation 环形缓冲(200 条)也被这些
314
+ // 空写刷掉,真正的变更反而看不见了。
315
+ // 比较用写入前读到的值与要写的值,与三处写入点的口径一致(都是"路径上现值 vs 要写的值")。
316
+ // 赋值已经做完了:访问器 setter 该跑的副作用一次不少,setter 内部往别的键的赋值也照常各自通知,
317
+ // 这里省掉的只是这一条路径上的那次通知。
318
+ //
319
+ // 这一层**不能替掉**已有的三处去重,它们各自还管着这一层够不到的地方,别当成重复删掉:
320
+ // - dom-renderer 的 `sameModelValue`(syncModel 回写前):多选每次从控件读出来都是新数组,
321
+ // 只能按元素比;数组在这一层一律算变了,比不了。而且那条路去重是为了"不写",
322
+ // 写进来再不通知救不回它挡掉的那次写。
323
+ // - component-manager 的 `installModelProps`(作用域根上的访问器):实例作用域根是普通对象、
324
+ // 根本没有代理,这一层管不到。
325
+ // - component-manager 的 `createModelWriter`(按绑定路径回写前):回写目标可能是父实例的
326
+ // 作用域根(`writeBoundPath`,普通对象 + 整树重渲),同样不经这一层。
327
+ if (sameScalarValue(oldValue, raw)) return true;
328
+
329
+ // 通知变更(带异常防护)。往下游发的也是剥过壳的原始值:
330
+ // 存的是什么,通知的就该是什么,渲染/watch 那边不必再多穿一层守卫。
174
331
  try {
175
- self.diagnostics?.recordMutation(path, value);
332
+ self.diagnostics?.recordMutation(path, raw);
176
333
  if (self.batchDepth > 0) {
177
- // batch 模式:收集变更路径,延迟到 endBatch 统一触发
178
- self.batchedPaths.set(path, value);
334
+ // batch 模式:收集变更路径,延迟到 endBatch 统一触发。
335
+ // 旧值只在这条路径**第一次**进批时记,后面几遍覆盖新值不动旧值:
336
+ // 一批收口只发一条通知,那条通知的旧值就该是进批之前的值(见 endBatch)。
337
+ const pending = self.batchedPaths.get(path);
338
+ self.batchedPaths.set(path, { value: raw, oldValue: pending ? pending.oldValue : oldValue });
179
339
  } else if (self.onChange) {
180
- self.onChange(path, value, oldValue);
340
+ self.onChange(path, raw, oldValue);
181
341
  }
182
342
  } catch (e) {
183
343
  console.error('[soma-core][引擎] onChange error:', e);
@@ -194,7 +354,7 @@ export class SomaReactiveProxy {
194
354
  * 不缓存,每次 get 都创建新 Proxy,保证 arrayPath 路径准确。
195
355
  */
196
356
  private wrapArrayDevGuard(arr: any[], arrayPath: string): any[] {
197
- return new Proxy(arr, {
357
+ const guard = new Proxy(arr, {
198
358
  get(target, prop) {
199
359
  const value = Reflect.get(target, prop);
200
360
  if (typeof prop === 'string' && ARRAY_MUTATING_METHODS.has(prop) && typeof value === 'function') {
@@ -209,6 +369,9 @@ export class SomaReactiveProxy {
209
369
  return value;
210
370
  },
211
371
  });
372
+ // 登记壳与芯的对应关系,供 set 陷阱存回前剥壳
373
+ ARRAY_GUARD_TARGETS.set(guard, arr);
374
+ return guard;
212
375
  }
213
376
 
214
377
  /** 判断对象是否应跳过代理 */
@@ -216,6 +379,14 @@ export class SomaReactiveProxy {
216
379
  if (obj == null) return true;
217
380
  if (Array.isArray(obj)) return true; // 数组不代理,通过引用替换触发更新
218
381
  if (typeof Storage !== 'undefined' && obj instanceof Storage) return true;
382
+ // 文件对象:原生 Blob / File / FileList 的访问器带内部槽 brand check,
383
+ // 经 Proxy 读一律 `TypeError: Illegal invocation`——页面写完
384
+ // `this.file = e.target.files[0]`,下一句读 .name / .size 就炸(jsdom 用私有字段,
385
+ // 报的是另一句话,同一个病)。File 继承自 Blob,两个都点名是因为运行环境未必两个都有:
386
+ // 浏览器与 jsdom 三个齐全,Node 只有 Blob / File,所以逐个 typeof 判存在再 instanceof。
387
+ if (typeof Blob !== 'undefined' && obj instanceof Blob) return true;
388
+ if (typeof File !== 'undefined' && obj instanceof File) return true;
389
+ if (typeof FileList !== 'undefined' && obj instanceof FileList) return true;
219
390
  return (
220
391
  obj instanceof Set ||
221
392
  obj instanceof Map ||