soma-core 2.2.7 → 2.2.8

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.
@@ -150,6 +150,28 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {
150
150
  return typeof value === 'object' && value !== null && !Array.isArray(value);
151
151
  }
152
152
 
153
+ /**
154
+ * 提交体里的布尔显式化:字典里 `type: bool` 的字段,新建时缺席或为空(undefined / null / 空串)→ false;
155
+ * 已给出的布尔(true / false)原样保留。没有要改的返回原对象(同一引用)。
156
+ */
157
+ function explicitBooleans(
158
+ fields: Readonly<Record<string, { readonly type?: string }>>,
159
+ model: Readonly<Record<string, unknown>>,
160
+ create: boolean,
161
+ ): Record<string, unknown> {
162
+ let next: Record<string, unknown> | null = null;
163
+ for (const [key, field] of Object.entries(fields)) {
164
+ if (field?.type !== 'bool') continue;
165
+ const present = Object.hasOwn(model, key);
166
+ const value = model[key];
167
+ const blank = value === undefined || value === null || value === '';
168
+ if (present ? !blank : !create) continue;
169
+ next ??= { ...model };
170
+ next[key] = false;
171
+ }
172
+ return next ?? (model as Record<string, unknown>);
173
+ }
174
+
153
175
  /** 按点分路径段读取(任一环节为空即返回 undefined) */
154
176
  function readPath(root: unknown, segments: string[]): unknown {
155
177
  let current: unknown = root;
@@ -675,8 +697,14 @@ export class SomaDataObjectResolver {
675
697
  options: SomaSubmitOptions = {},
676
698
  ): Promise<SomaDataSubmitResult> {
677
699
  const intent = options.intent ?? 'explicit';
678
- const result = await this.submitRaw(name, model, mode, options.identityField, options.signal);
679
- const write = this.config.objects[name]?.write;
700
+ const declared = this.config.objects[name];
701
+ const write = declared?.write;
702
+ // 布尔字段无论真假都显式提交:新建时缺席 / 空的布尔补 false,取消勾选的 false 与勾选的 true 原样上行;
703
+ // 发出去的就是显式化后的这份,不靠后端回落默认值。更新缺席 = 不改,不补
704
+ const sent = write !== undefined && declared?.fields !== undefined && isPlainObject(model)
705
+ ? explicitBooleans(declared.fields, model, (mode ?? this.inferWriteMode(name, write)) === 'create')
706
+ : model;
707
+ const result = await this.submitRaw(name, sent, mode, options.identityField, options.signal);
680
708
  if (!write) return result;
681
709
  if (result.ok) return decorateSuccess(result, write, intent);
682
710
  return decorateFailure(result, intent, { sentToken: readConcurrencyToken(model, write) });
@@ -872,11 +900,14 @@ export class SomaDataObjectResolver {
872
900
  */
873
901
  mapSubmitError(error: unknown, write: SomaDataWriteConfig): Extract<SomaDataSubmitResult, { ok: false }> {
874
902
  const payload = extractErrorPayload(error);
875
- const message = payload.message
903
+ const raw = payload.message
876
904
  ?? (error instanceof Error ? error.message : '提交失败');
877
905
  // 状态码(版本冲突 409 / 412 等):异常或响应上的 status,或 SomaHttpService 写进消息的 `HTTP 409: …`。
878
- // 只补 status,不改写文案——存量调用方按原文案显示。
879
- const status = commandStatusOf(error) ?? splitHttpMessage(message)?.status;
906
+ // 面向使用者的文案只留后端给的可读原因:`HTTP 409:` 前缀剥掉,状态码走结果的 `status` 字段(开发态诊断读它,界面不显示);
907
+ // 前缀后面没有原因时退到通用说法,不把状态码当文案
908
+ const http = splitHttpMessage(raw);
909
+ const message = http === null ? raw : (http.text !== '' ? http.text : '提交失败');
910
+ const status = commandStatusOf(error) ?? http?.status;
880
911
  // 版本冲突带上服务端当前令牌与当前记录(取得不到就不带,调用方退回重读)
881
912
  const conflict = status === 409 || status === 412 ? readConflictState(error, write) : {};
882
913
  const withStatus = status === undefined ? { ...conflict } : { status, ...conflict };
@@ -5,7 +5,7 @@
5
5
  import { SomaEngineError } from '../../../shared/engines/engine-error';
6
6
  import { loadEngineModule, type EngineLoadTelemetry } from '../load';
7
7
  import { COMPONENT_LOADERS, SERIES_IMPLIED_COMPONENTS, SERIES_LOADERS } from './kind-modules';
8
- import type { ChartInit, ChartInstance, ChartPointer, SomaChartAdapter } from './port';
8
+ import type { ChartColumn, ChartInit, ChartInstance, ChartPointer, SomaChartAdapter } from './port';
9
9
 
10
10
  interface Rect { x: number; y: number; width: number; height: number; clone(): Rect; applyTransform(m: ArrayLike<number> | null): void }
11
11
  interface GraphicEl { getBoundingRect(): Rect; getComputedTransform(): ArrayLike<number> | null }
@@ -18,7 +18,17 @@ interface EChartsInstance {
18
18
  resize(opts?: { width: number; height: number }): void;
19
19
  dispose(): void;
20
20
  /** 公开于实例但文档称内部:用来取数据项的图元(假设项,见 §12) */
21
- getModel(): { getSeriesByIndex(i: number): { getData(): { getItemGraphicEl(i: number): GraphicEl | undefined } } | undefined };
21
+ getModel(): {
22
+ getSeriesByIndex(i: number): { getData(): { getItemGraphicEl(i: number): GraphicEl | undefined } } | undefined;
23
+ getComponent(type: string, index: number): unknown;
24
+ };
25
+ getZr(): {
26
+ on(event: string, handler: (e: { offsetX?: number; offsetY?: number }) => void): void;
27
+ off(event: string, handler: (e: { offsetX?: number; offsetY?: number }) => void): void;
28
+ };
29
+ containPixel(finder: Record<string, number>, value: number[]): boolean;
30
+ convertFromPixel(finder: Record<string, number>, value: number[]): number | number[];
31
+ convertToPixel(finder: Record<string, number>, value: number): number | number[];
22
32
  }
23
33
  interface EChartsCore {
24
34
  init(host: HTMLElement, theme: unknown, opts: Record<string, unknown>): EChartsInstance;
@@ -132,6 +142,69 @@ export function createEChartsAdapter(adapterOptions: EChartsAdapterOptions = {})
132
142
  chart.off('mouseout', onOut);
133
143
  };
134
144
  },
145
+ onColumn(handler): () => void {
146
+ // 按坐标轴换算所在列:第一个类目轴(优先 x 轴,其次 y 轴),不依赖系列图元,null 列与列间空白也命中
147
+ const zr = chart.getZr();
148
+ const axisOf = (): { dim: 'x' | 'y'; count: number } | null => {
149
+ const model = chart.getModel();
150
+ for (const dim of ['x', 'y'] as const) {
151
+ const axis = model.getComponent(`${dim}Axis`, 0) as { get(k: string): unknown; getCategories?(): unknown[] } | undefined;
152
+ if (axis !== undefined && axis.get('type') === 'category') {
153
+ // 类目来自系列数据时选项的 xAxis.data 为空(getCategories 只读选项里写的),实际类目在轴刻度的 ordinalMeta 里:优先读它
154
+ const scale = (axis as { axis?: { scale?: { getOrdinalMeta?(): { categories?: unknown[] } | undefined } } }).axis?.scale;
155
+ const metaCats = scale?.getOrdinalMeta?.()?.categories;
156
+ const cats = metaCats !== undefined && metaCats.length > 0 ? metaCats : (axis.getCategories?.() ?? []);
157
+ return { dim, count: cats.length };
158
+ }
159
+ }
160
+ return null;
161
+ };
162
+ const columnAt = (x: number, y: number): ChartColumn | null => {
163
+ const axis = axisOf();
164
+ if (axis === null || axis.count === 0) return null;
165
+ if (!chart.containPixel({ gridIndex: 0 }, [x, y])) return null;
166
+ // 像素 → 数据:二维像素 [x, y] 必须配坐标系 finder(gridIndex)取回 [x 值, y 值];
167
+ // 配单轴 finder(xAxisIndex)时引擎期望的是标量像素,传数组得不到数值(实测列命中恒为 null、读数不随悬停变)
168
+ const raw = chart.convertFromPixel({ gridIndex: 0 }, [x, y]);
169
+ const v = Array.isArray(raw) ? raw[axis.dim === 'x' ? 0 : 1] : raw;
170
+ if (typeof v !== 'number' || !Number.isFinite(v)) return null;
171
+ const dataIndex = Math.min(axis.count - 1, Math.max(0, Math.round(v)));
172
+ return columnAnchor(dataIndex, axis.dim);
173
+ };
174
+ const columnAnchor = (dataIndex: number, dim: 'x' | 'y'): ChartColumn | null => {
175
+ const finder: Record<string, number> = dim === 'x' ? { xAxisIndex: 0 } : { yAxisIndex: 0 };
176
+ const px = chart.convertToPixel(finder, dataIndex);
177
+ const grid = chart.getModel().getComponent('grid', 0) as { coordinateSystem?: { getRect(): Rect } } | undefined;
178
+ const rect = grid?.coordinateSystem?.getRect();
179
+ const along = typeof px === 'number' ? px : Array.isArray(px) ? px[0] : NaN;
180
+ if (!Number.isFinite(along)) return null;
181
+ // 绘图区矩形取不到(引擎内部模型形状随版本变)时锚点的另一轴退到 0:列号才是命中的事实,锚点只用于对齐浮层
182
+ const anchor = dim === 'x' ? { x: along, y: rect?.y ?? 0 } : { x: rect?.x ?? 0, y: along };
183
+ return { dataIndex, anchor };
184
+ };
185
+ const read = (e: { offsetX?: number; offsetY?: number }): ChartColumn | null =>
186
+ typeof e.offsetX === 'number' && typeof e.offsetY === 'number' ? columnAt(e.offsetX, e.offsetY) : null;
187
+ const onMove = (e: { offsetX?: number; offsetY?: number }): void => {
188
+ const c = read(e);
189
+ handler(c === null ? 'leave' : 'hover', c);
190
+ };
191
+ const onClick = (e: { offsetX?: number; offsetY?: number }): void => {
192
+ const c = read(e);
193
+ if (c !== null) handler('click', c);
194
+ };
195
+ const onOut = (): void => handler('leave', null);
196
+ zr.on('mousemove', onMove);
197
+ zr.on('click', onClick);
198
+ zr.on('globalout', onOut);
199
+ let active = true;
200
+ return () => {
201
+ if (!active) return;
202
+ active = false;
203
+ zr.off('mousemove', onMove);
204
+ zr.off('click', onClick);
205
+ zr.off('globalout', onOut);
206
+ };
207
+ },
135
208
  resize(): void {
136
209
  chart.resize(size === undefined ? undefined : { width: size.width, height: size.height });
137
210
  },
@@ -1,6 +1,7 @@
1
1
  // exports `./chart`:图表引擎端口。`createChartPort(adapter?)`:缺省 ECharts 6 适配器(SVG 渲染器,动态加载)。
2
2
  // 入参校验(主题、option、销毁后调用)在 createChartPort 里做,换适配器也一样受约束。
3
3
  export type {
4
+ ChartColumn,
4
5
  ChartInit,
5
6
  ChartInstance,
6
7
  ChartPointer,
@@ -61,6 +62,23 @@ function guard(inner: ChartInstance): ChartInstance {
61
62
  unsubs.add(wrapped);
62
63
  return wrapped;
63
64
  },
65
+ ...(inner.onColumn === undefined
66
+ ? {}
67
+ : {
68
+ onColumn(handler: Parameters<NonNullable<ChartInstance['onColumn']>>[0]) {
69
+ live();
70
+ const off = inner.onColumn!(handler);
71
+ let done = false;
72
+ const wrapped = (): void => {
73
+ if (done) return;
74
+ done = true;
75
+ unsubs.delete(wrapped);
76
+ off();
77
+ };
78
+ unsubs.add(wrapped);
79
+ return wrapped;
80
+ },
81
+ }),
64
82
  resize(): void { live(); inner.resize(); },
65
83
  dispose(): void {
66
84
  if (disposed) return;
@@ -22,7 +22,20 @@ export interface ChartPointer {
22
22
  readonly anchor: { readonly x: number; readonly y: number };
23
23
  }
24
24
 
25
+ /** 指针 / 键盘所在的类目轴列;空值列、列间空白也能命中(与系列是否有图元无关) */
26
+ export interface ChartColumn {
27
+ /** 第一个类目轴上的列序号(与系列 data 下标一致) */
28
+ readonly dataIndex: number;
29
+ /** 该列在容器内的锚点像素(列中心、绘图区顶部) */
30
+ readonly anchor: { readonly x: number; readonly y: number };
31
+ }
32
+
25
33
  export interface ChartInstance {
34
+ /**
35
+ * 指针在绘图区内移动 / 点击 / 离开时按坐标轴换算所在列;落在绘图区外按 leave 处理;无类目轴的图(饼、仪表等)不触发。
36
+ * 可选:旧适配器缺该方法时调用方回落到 `onPointer`(只有带图元的列可交互)。
37
+ */
38
+ onColumn?(handler: (kind: 'hover' | 'click' | 'leave', col: ChartColumn | null) => void): () => void;
26
39
  setOption(option: Readonly<Record<string, unknown>>, mode?: 'merge' | 'replace'): void;
27
40
  /** 键盘漫游驱动 */
28
41
  highlight(p: { seriesIndex: number; dataIndex: number } | null): void;
@@ -8,6 +8,8 @@
8
8
  // 不管:载荷校验与摘要(inject.ts)、取页与编译(resolve.ts)。
9
9
 
10
10
  import { currentHostDir } from '../host/host-dir';
11
+ import { readFlatEnvelope } from '../../build/compiler/flat-page';
12
+ import { SOMA_PAGE_FORMAT_VERSION } from '../../shared/page-envelope';
11
13
  import {
12
14
  addressKindOf,
13
15
  addressShapeKey,
@@ -31,6 +33,9 @@ import type {
31
33
  SomaStandardPageEnvelope,
32
34
  } from './types';
33
35
 
36
+ /** 方言所有者给的版本守卫:`version` 是它随产物给出的不透明版本号;返回 false = 该产物不是本版产出方编的,不得恢复 */
37
+ export type OwnerVersionGuard = (version: string | undefined) => boolean;
38
+
34
39
  /** 前缀解析器交回的东西:标准格式载荷,或兼容旧入口已经拼好的运行时资产(虚拟页的 `artifact` / 声明分支) */
35
40
  export type PrefixPageResult =
36
41
  | { readonly kind: 'page'; readonly page: SomaStandardPage; readonly title?: string }
@@ -74,6 +79,8 @@ interface SpaceState {
74
79
  readonly stores: Map<string, SomaRuntimeStore>;
75
80
  layoutMemo: { readonly signature: string; readonly layout: SomaRuntimeLayout } | null;
76
81
  rootErrorReported: boolean;
82
+ /** owner → 版本守卫(方言所有者登记;core 不解释 version) */
83
+ readonly ownerGuards: Map<string, OwnerVersionGuard>;
77
84
  }
78
85
 
79
86
  const SLOT = Symbol.for('soma-core.runtime-space');
@@ -91,6 +98,7 @@ export function space(): SpaceState {
91
98
  stores: new Map(),
92
99
  layoutMemo: null,
93
100
  rootErrorReported: false,
101
+ ownerGuards: new Map(),
94
102
  });
95
103
  }
96
104
 
@@ -106,6 +114,29 @@ export function resetRuntimeSpace(): void {
106
114
  state.stores.clear();
107
115
  state.layoutMemo = null;
108
116
  state.rootErrorReported = false;
117
+ state.ownerGuards.clear();
118
+ }
119
+
120
+ /**
121
+ * 方言所有者登记版本守卫(升级隐患闸):持久绑定恢复时,owner 相同的条目其 `version` 须被守卫接受,否则丢弃(连绑定文件),
122
+ * 页面由所有者按本版编译器重新注入。登记时已装入的同 owner 持久条目立刻对一遍。core 只存守卫、不解释 version(缓存键 = URL + version)。
123
+ */
124
+ export function registerOwnerVersionGuard(owner: string, guard: OwnerVersionGuard): void {
125
+ const state = space();
126
+ state.ownerGuards.set(owner, guard);
127
+ let dropped = false;
128
+ for (const [key, entry] of state.entries) {
129
+ const binding = entry.binding;
130
+ if (binding.owner !== owner || !binding.persisted || binding.origin !== 'inject' || guard(binding.version)) continue;
131
+ state.entries.delete(key);
132
+ try {
133
+ runtimeStore().removeBinding(binding.address);
134
+ } catch {
135
+ /* 根不可用:没有落盘可清 */
136
+ }
137
+ dropped = true;
138
+ }
139
+ if (dropped) bumpNavGeneration();
109
140
  }
110
141
 
111
142
  // ── 布局与存储 ────────────────────────────────────────────────────────────────
@@ -186,11 +217,26 @@ export function ensureLoaded(): void {
186
217
  console.warn(`[soma-core][引擎] 持久绑定 ${binding.address} 的产物缺失或损坏(${binding.digest.slice(0, 12)}…),已跳过;重新 inject 即可恢复。`);
187
218
  continue;
188
219
  }
220
+ // 恢复的信封与注入口同一读法:载荷 `envelope` 优先,其次 `_ui.yaml` 顶层 `envelope:`
221
+ const envelope = page.envelope ?? (readFlatEnvelope(page.uiYaml) as SomaStandardPageEnvelope | null);
222
+ // 标准格式版本不符的旧产物不恢复:丢弃并清掉绑定文件,由方言所有者重新编译注入(信封可缺:原生页信封是可选的,
223
+ // 缺信封的方言旧产物由落盘格式版本与产出方版本守卫拦下)
224
+ if (page.format !== SOMA_PAGE_FORMAT_VERSION) {
225
+ store.removeBinding(binding.address);
226
+ console.warn(`[soma-core][引擎] 持久绑定 ${binding.address} 的产物标准格式版本不符,已丢弃;由产出方重新编译注入。`);
227
+ continue;
228
+ }
229
+ // 产出方版本指纹闸(见 registerOwnerVersionGuard):已登记守卫且不认这个 version → 丢弃
230
+ const guard = binding.owner === undefined ? undefined : state.ownerGuards.get(binding.owner);
231
+ if (guard !== undefined && !guard(binding.version)) {
232
+ store.removeBinding(binding.address);
233
+ continue;
234
+ }
189
235
  state.generations.set(key, Math.max(state.generations.get(key) ?? 0, binding.generation));
190
236
  state.entries.set(key, {
191
237
  binding: { ...binding, persisted: true },
192
238
  page,
193
- envelope: page.envelope ?? null,
239
+ envelope,
194
240
  prefix: null,
195
241
  registryName: null,
196
242
  mtimeMs: read.mtimeMs,
@@ -4,6 +4,12 @@ import { createHash } from 'node:crypto';
4
4
  import { addressShapeKey } from '../../shared/runtime-address';
5
5
  import type { SomaStandardPage } from './types';
6
6
 
7
+ /**
8
+ * core 落盘产物的格式版本(绑定记录、预热索引与旁档、预热元数据共用)。落盘结构(信封、闸门等)有不兼容变化时递增;
9
+ * 读回时版本不符一律视为无效并丢弃,由方言所有者重新编译注入,不做迁移也不手工清目录。
10
+ */
11
+ export const SOMA_RUNTIME_STORE_FORMAT = 2;
12
+
7
13
  /** 摘要形状:64 位小写十六进制 */
8
14
  export const SOMA_RUNTIME_DIGEST_PATTERN = /^[0-9a-f]{64}$/;
9
15
 
@@ -31,7 +31,7 @@ export {
31
31
  } from './dynamic-pages';
32
32
  export { resolveAddress, loadPageByAddress, listBindings, runtimeSpaceStats, type SomaLoadedPage, type SomaLoadPageOptions } from './resolve';
33
33
  export { SomaRuntimeError, type SomaRuntimeBatchFailure, type SomaRuntimeErrorCode } from './errors';
34
- export { setNavProvider, type NavProvider } from './bindings';
34
+ export { setNavProvider, registerOwnerVersionGuard, type NavProvider, type OwnerVersionGuard } from './bindings';
35
35
  export {
36
36
  registerPage,
37
37
  registerPages,
@@ -15,7 +15,7 @@ import { createHash } from 'node:crypto';
15
15
  import fs from 'node:fs';
16
16
  import path from 'node:path';
17
17
  import { writeFileAtomic } from '../registry/registry-file-lock';
18
- import { bindingFileName, canonicalJson } from './digest';
18
+ import { bindingFileName, canonicalJson, SOMA_RUNTIME_STORE_FORMAT } from './digest';
19
19
  import { resolveSomaRuntimeLayout } from './root';
20
20
  import { SomaRuntimeStore } from './store';
21
21
  import type { SomaRuntimeLayout, SomaStandardPage } from './types';
@@ -25,7 +25,7 @@ export const SOMA_PREWARM_META_FILE = 'meta.json';
25
25
 
26
26
  /** 旁档:一个静态页的构建期编译结果 */
27
27
  export interface SomaPrewarmCompiledRecord<T = unknown> {
28
- readonly schemaVersion: 1;
28
+ readonly schemaVersion: number;
29
29
  readonly address: string;
30
30
  /** 对应标准格式产物的摘要;与索引不一致即视为失效 */
31
31
  readonly digest: string;
@@ -36,7 +36,7 @@ export interface SomaPrewarmCompiledRecord<T = unknown> {
36
36
 
37
37
  /** 全局元数据(路由表、词表、应用配置):不属于某一页 */
38
38
  export interface SomaPrewarmMeta<M = unknown> {
39
- readonly schemaVersion: 1;
39
+ readonly schemaVersion: number;
40
40
  readonly meta: M;
41
41
  }
42
42
 
@@ -105,7 +105,7 @@ function writeIfChanged(file: string, content: string): void {
105
105
  function readCompiledRecord<T>(file: string): SomaPrewarmCompiledRecord<T> | null {
106
106
  try {
107
107
  const record = JSON.parse(fs.readFileSync(file, 'utf8')) as SomaPrewarmCompiledRecord<T>;
108
- return record.schemaVersion === 1 && typeof record.digest === 'string' ? record : null;
108
+ return record.schemaVersion === SOMA_RUNTIME_STORE_FORMAT && typeof record.digest === 'string' ? record : null;
109
109
  } catch {
110
110
  return null;
111
111
  }
@@ -150,7 +150,7 @@ export async function runPrewarm<T = unknown, M = unknown>(options: SomaPrewarmO
150
150
  continue;
151
151
  }
152
152
  const record: SomaPrewarmCompiledRecord<T> = {
153
- schemaVersion: 1,
153
+ schemaVersion: SOMA_RUNTIME_STORE_FORMAT,
154
154
  address: item.address,
155
155
  digest,
156
156
  inputsDigest: item.inputsDigest,
@@ -174,7 +174,7 @@ export async function runPrewarm<T = unknown, M = unknown>(options: SomaPrewarmO
174
174
  }
175
175
 
176
176
  if (options.meta !== undefined) {
177
- const record: SomaPrewarmMeta<M> = { schemaVersion: 1, meta: options.meta };
177
+ const record: SomaPrewarmMeta<M> = { schemaVersion: SOMA_RUNTIME_STORE_FORMAT, meta: options.meta };
178
178
  writeIfChanged(path.join(layout.dirs.prewarm, SOMA_PREWARM_META_FILE), `${JSON.stringify(record)}\n`);
179
179
  }
180
180
 
@@ -194,7 +194,7 @@ export async function runPrewarm<T = unknown, M = unknown>(options: SomaPrewarmO
194
194
  }
195
195
 
196
196
  const sorted = Object.fromEntries(Object.entries(entries).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
197
- const indexText = `${JSON.stringify({ schemaVersion: 1, entries: sorted }, null, 2)}\n`;
197
+ const indexText = `${JSON.stringify({ schemaVersion: SOMA_RUNTIME_STORE_FORMAT, entries: sorted }, null, 2)}\n`;
198
198
  writeIfChanged(path.join(layout.dirs.prewarm, 'index.json'), indexText);
199
199
 
200
200
  return {
@@ -226,7 +226,7 @@ export function readPrewarmCompiled<T = unknown, M = unknown>(
226
226
  let meta: M | null = null;
227
227
  try {
228
228
  const parsed = JSON.parse(fs.readFileSync(path.join(layout.dirs.prewarm, SOMA_PREWARM_META_FILE), 'utf8')) as SomaPrewarmMeta<M>;
229
- if (parsed.schemaVersion === 1) meta = parsed.meta;
229
+ if (parsed.schemaVersion === SOMA_RUNTIME_STORE_FORMAT) meta = parsed.meta;
230
230
  } catch {
231
231
  /* 缺失:meta 为空 */
232
232
  }
@@ -10,7 +10,7 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { writeFileAtomic } from '../registry/registry-file-lock';
12
12
  import { SOMA_PIPELINE_LIMITS } from '../../shared/registry-generated/limits';
13
- import { bindingFileName, computeStandardPageDigest, isRuntimeDigest } from './digest';
13
+ import { bindingFileName, computeStandardPageDigest, isRuntimeDigest, SOMA_RUNTIME_STORE_FORMAT } from './digest';
14
14
  import type {
15
15
  SomaPersistedBinding,
16
16
  SomaPrewarmIndex,
@@ -194,7 +194,7 @@ export class SomaRuntimeStore {
194
194
 
195
195
  writeBinding(binding: SomaRuntimeBinding): void {
196
196
  fs.mkdirSync(this.dirs.bindings, { recursive: true });
197
- const record: SomaPersistedBinding = { schemaVersion: 1, binding };
197
+ const record: SomaPersistedBinding = { schemaVersion: SOMA_RUNTIME_STORE_FORMAT, binding };
198
198
  writeFileAtomic(this.bindingFile(binding.address), `${JSON.stringify(record, null, 2)}\n`);
199
199
  }
200
200
 
@@ -203,7 +203,7 @@ export class SomaRuntimeStore {
203
203
  try {
204
204
  const stat = fs.statSync(file);
205
205
  const record = JSON.parse(fs.readFileSync(file, 'utf8')) as SomaPersistedBinding;
206
- if (record.schemaVersion !== 1 || !record.binding) return null;
206
+ if (record.schemaVersion !== SOMA_RUNTIME_STORE_FORMAT || !record.binding) return null;
207
207
  return { binding: record.binding, mtimeMs: stat.mtimeMs };
208
208
  } catch {
209
209
  return null;
@@ -254,7 +254,8 @@ export class SomaRuntimeStore {
254
254
  const file = path.join(this.dirs.bindings, name);
255
255
  const stat = fs.statSync(file);
256
256
  const record = JSON.parse(fs.readFileSync(file, 'utf8')) as SomaPersistedBinding;
257
- if (record.schemaVersion === 1 && record.binding) out.push({ binding: record.binding, mtimeMs: stat.mtimeMs });
257
+ if (record.schemaVersion === SOMA_RUNTIME_STORE_FORMAT && record.binding) out.push({ binding: record.binding, mtimeMs: stat.mtimeMs });
258
+ else fs.unlinkSync(file); // 旧格式绑定:丢弃(产物由 GC 回收),由方言所有者重新编译注入
258
259
  } catch {
259
260
  /* 损坏的绑定文件不拖垮启动 */
260
261
  }
@@ -267,16 +268,16 @@ export class SomaRuntimeStore {
267
268
  readPrewarmIndex(): SomaPrewarmIndex {
268
269
  try {
269
270
  const parsed = JSON.parse(fs.readFileSync(path.join(this.dirs.prewarm, 'index.json'), 'utf8')) as SomaPrewarmIndex;
270
- if (parsed.schemaVersion === 1 && parsed.entries && typeof parsed.entries === 'object') return parsed;
271
+ if (parsed.schemaVersion === SOMA_RUNTIME_STORE_FORMAT && parsed.entries && typeof parsed.entries === 'object') return parsed;
271
272
  } catch {
272
273
  /* 缺失或损坏:当作空 */
273
274
  }
274
- return { schemaVersion: 1, entries: {} };
275
+ return { schemaVersion: SOMA_RUNTIME_STORE_FORMAT, entries: {} };
275
276
  }
276
277
 
277
278
  writePrewarmIndex(entries: Readonly<Record<string, string>>): void {
278
279
  fs.mkdirSync(this.dirs.prewarm, { recursive: true });
279
- const index: SomaPrewarmIndex = { schemaVersion: 1, entries };
280
+ const index: SomaPrewarmIndex = { schemaVersion: SOMA_RUNTIME_STORE_FORMAT, entries };
280
281
  writeFileAtomic(path.join(this.dirs.prewarm, 'index.json'), `${JSON.stringify(index, null, 2)}\n`);
281
282
  }
282
283
  }
@@ -214,13 +214,14 @@ export interface SomaRuntimeStoreStats {
214
214
 
215
215
  /** 一条落盘的绑定记录(`<root>/bindings/<键>.json`) */
216
216
  export interface SomaPersistedBinding {
217
- readonly schemaVersion: 1;
217
+ /** core 落盘格式版本(`SOMA_RUNTIME_STORE_FORMAT`);读回不符即丢弃 */
218
+ readonly schemaVersion: number;
218
219
  readonly binding: SomaRuntimeBinding;
219
220
  }
220
221
 
221
222
  /** 预热索引 `<root>/prewarm/index.json` */
222
223
  export interface SomaPrewarmIndex {
223
- readonly schemaVersion: 1;
224
+ readonly schemaVersion: number;
224
225
  /** 地址 → 内容摘要 */
225
226
  readonly entries: Readonly<Record<string, string>>;
226
227
  }
@@ -108889,6 +108889,63 @@ function createEChartsAdapter(adapterOptions = {}) {
108889
108889
  chart.off("mouseout", onOut);
108890
108890
  };
108891
108891
  },
108892
+ onColumn(handler) {
108893
+ const zr = chart.getZr();
108894
+ const axisOf = () => {
108895
+ const model = chart.getModel();
108896
+ for (const dim of ["x", "y"]) {
108897
+ const axis = model.getComponent(`${dim}Axis`, 0);
108898
+ if (axis !== void 0 && axis.get("type") === "category") {
108899
+ const scale3 = axis.axis?.scale;
108900
+ const metaCats = scale3?.getOrdinalMeta?.()?.categories;
108901
+ const cats = metaCats !== void 0 && metaCats.length > 0 ? metaCats : axis.getCategories?.() ?? [];
108902
+ return { dim, count: cats.length };
108903
+ }
108904
+ }
108905
+ return null;
108906
+ };
108907
+ const columnAt = (x2, y2) => {
108908
+ const axis = axisOf();
108909
+ if (axis === null || axis.count === 0) return null;
108910
+ if (!chart.containPixel({ gridIndex: 0 }, [x2, y2])) return null;
108911
+ const raw = chart.convertFromPixel({ gridIndex: 0 }, [x2, y2]);
108912
+ const v4 = Array.isArray(raw) ? raw[axis.dim === "x" ? 0 : 1] : raw;
108913
+ if (typeof v4 !== "number" || !Number.isFinite(v4)) return null;
108914
+ const dataIndex = Math.min(axis.count - 1, Math.max(0, Math.round(v4)));
108915
+ return columnAnchor(dataIndex, axis.dim);
108916
+ };
108917
+ const columnAnchor = (dataIndex, dim) => {
108918
+ const finder = dim === "x" ? { xAxisIndex: 0 } : { yAxisIndex: 0 };
108919
+ const px = chart.convertToPixel(finder, dataIndex);
108920
+ const grid = chart.getModel().getComponent("grid", 0);
108921
+ const rect = grid?.coordinateSystem?.getRect();
108922
+ const along = typeof px === "number" ? px : Array.isArray(px) ? px[0] : NaN;
108923
+ if (!Number.isFinite(along)) return null;
108924
+ const anchor = dim === "x" ? { x: along, y: rect?.y ?? 0 } : { x: rect?.x ?? 0, y: along };
108925
+ return { dataIndex, anchor };
108926
+ };
108927
+ const read = (e3) => typeof e3.offsetX === "number" && typeof e3.offsetY === "number" ? columnAt(e3.offsetX, e3.offsetY) : null;
108928
+ const onMove = (e3) => {
108929
+ const c2 = read(e3);
108930
+ handler(c2 === null ? "leave" : "hover", c2);
108931
+ };
108932
+ const onClick = (e3) => {
108933
+ const c2 = read(e3);
108934
+ if (c2 !== null) handler("click", c2);
108935
+ };
108936
+ const onOut = () => handler("leave", null);
108937
+ zr.on("mousemove", onMove);
108938
+ zr.on("click", onClick);
108939
+ zr.on("globalout", onOut);
108940
+ let active2 = true;
108941
+ return () => {
108942
+ if (!active2) return;
108943
+ active2 = false;
108944
+ zr.off("mousemove", onMove);
108945
+ zr.off("click", onClick);
108946
+ zr.off("globalout", onOut);
108947
+ };
108948
+ },
108892
108949
  resize() {
108893
108950
  chart.resize(size3 === void 0 ? void 0 : { width: size3.width, height: size3.height });
108894
108951
  },
@@ -108951,6 +109008,21 @@ function guard(inner23) {
108951
109008
  unsubs.add(wrapped);
108952
109009
  return wrapped;
108953
109010
  },
109011
+ ...inner23.onColumn === void 0 ? {} : {
109012
+ onColumn(handler) {
109013
+ live();
109014
+ const off = inner23.onColumn(handler);
109015
+ let done = false;
109016
+ const wrapped = () => {
109017
+ if (done) return;
109018
+ done = true;
109019
+ unsubs.delete(wrapped);
109020
+ off();
109021
+ };
109022
+ unsubs.add(wrapped);
109023
+ return wrapped;
109024
+ }
109025
+ },
108954
109026
  resize() {
108955
109027
  live();
108956
109028
  inner23.resize();
@@ -113302,6 +113374,19 @@ var SomaDataCycleError = class extends Error {
113302
113374
  function isPlainObject5(value) {
113303
113375
  return typeof value === "object" && value !== null && !Array.isArray(value);
113304
113376
  }
113377
+ function explicitBooleans(fields2, model, create4) {
113378
+ let next = null;
113379
+ for (const [key, field] of Object.entries(fields2)) {
113380
+ if (field?.type !== "bool") continue;
113381
+ const present = Object.hasOwn(model, key);
113382
+ const value = model[key];
113383
+ const blank = value === void 0 || value === null || value === "";
113384
+ if (present ? !blank : !create4) continue;
113385
+ next ??= { ...model };
113386
+ next[key] = false;
113387
+ }
113388
+ return next ?? model;
113389
+ }
113305
113390
  function readPath2(root, segments) {
113306
113391
  let current = root;
113307
113392
  for (const segment2 of segments) {
@@ -113719,8 +113804,10 @@ var SomaDataObjectResolver = class {
113719
113804
  */
113720
113805
  async submit(name2, model, mode, options = {}) {
113721
113806
  const intent = options.intent ?? "explicit";
113722
- const result = await this.submitRaw(name2, model, mode, options.identityField, options.signal);
113723
- const write = this.config.objects[name2]?.write;
113807
+ const declared = this.config.objects[name2];
113808
+ const write = declared?.write;
113809
+ const sent = write !== void 0 && declared?.fields !== void 0 && isPlainObject5(model) ? explicitBooleans(declared.fields, model, (mode ?? this.inferWriteMode(name2, write)) === "create") : model;
113810
+ const result = await this.submitRaw(name2, sent, mode, options.identityField, options.signal);
113724
113811
  if (!write) return result;
113725
113812
  if (result.ok) return decorateSuccess(result, write, intent);
113726
113813
  return decorateFailure(result, intent, { sentToken: readConcurrencyToken(model, write) });
@@ -113873,8 +113960,10 @@ var SomaDataObjectResolver = class {
113873
113960
  */
113874
113961
  mapSubmitError(error2, write) {
113875
113962
  const payload = extractErrorPayload(error2);
113876
- const message = payload.message ?? (error2 instanceof Error ? error2.message : "\u63D0\u4EA4\u5931\u8D25");
113877
- const status = commandStatusOf(error2) ?? splitHttpMessage(message)?.status;
113963
+ const raw = payload.message ?? (error2 instanceof Error ? error2.message : "\u63D0\u4EA4\u5931\u8D25");
113964
+ const http = splitHttpMessage(raw);
113965
+ const message = http === null ? raw : http.text !== "" ? http.text : "\u63D0\u4EA4\u5931\u8D25";
113966
+ const status = commandStatusOf(error2) ?? http?.status;
113878
113967
  const conflict = status === 409 || status === 412 ? readConflictState(error2, write) : {};
113879
113968
  const withStatus = status === void 0 ? { ...conflict } : { status, ...conflict };
113880
113969
  if (!payload.fieldErrors) return { ok: false, message, ...withStatus };
@@ -110094,6 +110094,63 @@ function createEChartsAdapter(adapterOptions = {}) {
110094
110094
  chart.off("mouseout", onOut);
110095
110095
  };
110096
110096
  },
110097
+ onColumn(handler) {
110098
+ const zr = chart.getZr();
110099
+ const axisOf = () => {
110100
+ const model = chart.getModel();
110101
+ for (const dim of ["x", "y"]) {
110102
+ const axis = model.getComponent(`${dim}Axis`, 0);
110103
+ if (axis !== void 0 && axis.get("type") === "category") {
110104
+ const scale3 = axis.axis?.scale;
110105
+ const metaCats = scale3?.getOrdinalMeta?.()?.categories;
110106
+ const cats = metaCats !== void 0 && metaCats.length > 0 ? metaCats : axis.getCategories?.() ?? [];
110107
+ return { dim, count: cats.length };
110108
+ }
110109
+ }
110110
+ return null;
110111
+ };
110112
+ const columnAt = (x2, y2) => {
110113
+ const axis = axisOf();
110114
+ if (axis === null || axis.count === 0) return null;
110115
+ if (!chart.containPixel({ gridIndex: 0 }, [x2, y2])) return null;
110116
+ const raw = chart.convertFromPixel({ gridIndex: 0 }, [x2, y2]);
110117
+ const v4 = Array.isArray(raw) ? raw[axis.dim === "x" ? 0 : 1] : raw;
110118
+ if (typeof v4 !== "number" || !Number.isFinite(v4)) return null;
110119
+ const dataIndex = Math.min(axis.count - 1, Math.max(0, Math.round(v4)));
110120
+ return columnAnchor(dataIndex, axis.dim);
110121
+ };
110122
+ const columnAnchor = (dataIndex, dim) => {
110123
+ const finder = dim === "x" ? { xAxisIndex: 0 } : { yAxisIndex: 0 };
110124
+ const px = chart.convertToPixel(finder, dataIndex);
110125
+ const grid = chart.getModel().getComponent("grid", 0);
110126
+ const rect = grid?.coordinateSystem?.getRect();
110127
+ const along = typeof px === "number" ? px : Array.isArray(px) ? px[0] : NaN;
110128
+ if (!Number.isFinite(along)) return null;
110129
+ const anchor = dim === "x" ? { x: along, y: rect?.y ?? 0 } : { x: rect?.x ?? 0, y: along };
110130
+ return { dataIndex, anchor };
110131
+ };
110132
+ const read = (e3) => typeof e3.offsetX === "number" && typeof e3.offsetY === "number" ? columnAt(e3.offsetX, e3.offsetY) : null;
110133
+ const onMove = (e3) => {
110134
+ const c2 = read(e3);
110135
+ handler(c2 === null ? "leave" : "hover", c2);
110136
+ };
110137
+ const onClick = (e3) => {
110138
+ const c2 = read(e3);
110139
+ if (c2 !== null) handler("click", c2);
110140
+ };
110141
+ const onOut = () => handler("leave", null);
110142
+ zr.on("mousemove", onMove);
110143
+ zr.on("click", onClick);
110144
+ zr.on("globalout", onOut);
110145
+ let active2 = true;
110146
+ return () => {
110147
+ if (!active2) return;
110148
+ active2 = false;
110149
+ zr.off("mousemove", onMove);
110150
+ zr.off("click", onClick);
110151
+ zr.off("globalout", onOut);
110152
+ };
110153
+ },
110097
110154
  resize() {
110098
110155
  chart.resize(size3 === void 0 ? void 0 : { width: size3.width, height: size3.height });
110099
110156
  },
@@ -110156,6 +110213,21 @@ function guard(inner23) {
110156
110213
  unsubs.add(wrapped);
110157
110214
  return wrapped;
110158
110215
  },
110216
+ ...inner23.onColumn === void 0 ? {} : {
110217
+ onColumn(handler) {
110218
+ live();
110219
+ const off = inner23.onColumn(handler);
110220
+ let done = false;
110221
+ const wrapped = () => {
110222
+ if (done) return;
110223
+ done = true;
110224
+ unsubs.delete(wrapped);
110225
+ off();
110226
+ };
110227
+ unsubs.add(wrapped);
110228
+ return wrapped;
110229
+ }
110230
+ },
110159
110231
  resize() {
110160
110232
  live();
110161
110233
  inner23.resize();
@@ -114621,6 +114693,19 @@ var SomaDataCycleError = class extends Error {
114621
114693
  function isPlainObject6(value) {
114622
114694
  return typeof value === "object" && value !== null && !Array.isArray(value);
114623
114695
  }
114696
+ function explicitBooleans(fields2, model, create4) {
114697
+ let next = null;
114698
+ for (const [key, field] of Object.entries(fields2)) {
114699
+ if (field?.type !== "bool") continue;
114700
+ const present = Object.hasOwn(model, key);
114701
+ const value = model[key];
114702
+ const blank = value === void 0 || value === null || value === "";
114703
+ if (present ? !blank : !create4) continue;
114704
+ next ??= { ...model };
114705
+ next[key] = false;
114706
+ }
114707
+ return next ?? model;
114708
+ }
114624
114709
  function readPath2(root, segments) {
114625
114710
  let current = root;
114626
114711
  for (const segment2 of segments) {
@@ -115038,8 +115123,10 @@ var SomaDataObjectResolver = class {
115038
115123
  */
115039
115124
  async submit(name2, model, mode, options = {}) {
115040
115125
  const intent = options.intent ?? "explicit";
115041
- const result = await this.submitRaw(name2, model, mode, options.identityField, options.signal);
115042
- const write = this.config.objects[name2]?.write;
115126
+ const declared = this.config.objects[name2];
115127
+ const write = declared?.write;
115128
+ const sent = write !== void 0 && declared?.fields !== void 0 && isPlainObject6(model) ? explicitBooleans(declared.fields, model, (mode ?? this.inferWriteMode(name2, write)) === "create") : model;
115129
+ const result = await this.submitRaw(name2, sent, mode, options.identityField, options.signal);
115043
115130
  if (!write) return result;
115044
115131
  if (result.ok) return decorateSuccess(result, write, intent);
115045
115132
  return decorateFailure(result, intent, { sentToken: readConcurrencyToken(model, write) });
@@ -115192,8 +115279,10 @@ var SomaDataObjectResolver = class {
115192
115279
  */
115193
115280
  mapSubmitError(error2, write) {
115194
115281
  const payload = extractErrorPayload(error2);
115195
- const message = payload.message ?? (error2 instanceof Error ? error2.message : "\u63D0\u4EA4\u5931\u8D25");
115196
- const status = commandStatusOf(error2) ?? splitHttpMessage(message)?.status;
115282
+ const raw = payload.message ?? (error2 instanceof Error ? error2.message : "\u63D0\u4EA4\u5931\u8D25");
115283
+ const http = splitHttpMessage(raw);
115284
+ const message = http === null ? raw : http.text !== "" ? http.text : "\u63D0\u4EA4\u5931\u8D25";
115285
+ const status = commandStatusOf(error2) ?? http?.status;
115197
115286
  const conflict = status === 409 || status === 412 ? readConflictState(error2, write) : {};
115198
115287
  const withStatus = status === void 0 ? { ...conflict } : { status, ...conflict };
115199
115288
  if (!payload.fieldErrors) return { ok: false, message, ...withStatus };
@@ -5935,6 +5935,7 @@ function compileFlatPage(input) {
5935
5935
 
5936
5936
  // core/server/runtime-space/digest.ts
5937
5937
  var import_node_crypto = require("node:crypto");
5938
+ var SOMA_RUNTIME_STORE_FORMAT = 2;
5938
5939
  var SOMA_RUNTIME_DIGEST_PATTERN = /^[0-9a-f]{64}$/;
5939
5940
  function isRuntimeDigest(value2) {
5940
5941
  return typeof value2 === "string" && SOMA_RUNTIME_DIGEST_PATTERN.test(value2);
@@ -8512,7 +8513,7 @@ var SomaRuntimeStore = class {
8512
8513
  }
8513
8514
  writeBinding(binding) {
8514
8515
  import_node_fs8.default.mkdirSync(this.dirs.bindings, { recursive: true });
8515
- const record3 = { schemaVersion: 1, binding };
8516
+ const record3 = { schemaVersion: SOMA_RUNTIME_STORE_FORMAT, binding };
8516
8517
  writeFileAtomic(this.bindingFile(binding.address), `${JSON.stringify(record3, null, 2)}
8517
8518
  `);
8518
8519
  }
@@ -8521,7 +8522,7 @@ var SomaRuntimeStore = class {
8521
8522
  try {
8522
8523
  const stat = import_node_fs8.default.statSync(file);
8523
8524
  const record3 = JSON.parse(import_node_fs8.default.readFileSync(file, "utf8"));
8524
- if (record3.schemaVersion !== 1 || !record3.binding) return null;
8525
+ if (record3.schemaVersion !== SOMA_RUNTIME_STORE_FORMAT || !record3.binding) return null;
8525
8526
  return { binding: record3.binding, mtimeMs: stat.mtimeMs };
8526
8527
  } catch {
8527
8528
  return null;
@@ -8568,7 +8569,8 @@ var SomaRuntimeStore = class {
8568
8569
  const file = import_node_path8.default.join(this.dirs.bindings, name);
8569
8570
  const stat = import_node_fs8.default.statSync(file);
8570
8571
  const record3 = JSON.parse(import_node_fs8.default.readFileSync(file, "utf8"));
8571
- if (record3.schemaVersion === 1 && record3.binding) out.push({ binding: record3.binding, mtimeMs: stat.mtimeMs });
8572
+ if (record3.schemaVersion === SOMA_RUNTIME_STORE_FORMAT && record3.binding) out.push({ binding: record3.binding, mtimeMs: stat.mtimeMs });
8573
+ else import_node_fs8.default.unlinkSync(file);
8572
8574
  } catch {
8573
8575
  }
8574
8576
  }
@@ -8578,14 +8580,14 @@ var SomaRuntimeStore = class {
8578
8580
  readPrewarmIndex() {
8579
8581
  try {
8580
8582
  const parsed = JSON.parse(import_node_fs8.default.readFileSync(import_node_path8.default.join(this.dirs.prewarm, "index.json"), "utf8"));
8581
- if (parsed.schemaVersion === 1 && parsed.entries && typeof parsed.entries === "object") return parsed;
8583
+ if (parsed.schemaVersion === SOMA_RUNTIME_STORE_FORMAT && parsed.entries && typeof parsed.entries === "object") return parsed;
8582
8584
  } catch {
8583
8585
  }
8584
- return { schemaVersion: 1, entries: {} };
8586
+ return { schemaVersion: SOMA_RUNTIME_STORE_FORMAT, entries: {} };
8585
8587
  }
8586
8588
  writePrewarmIndex(entries) {
8587
8589
  import_node_fs8.default.mkdirSync(this.dirs.prewarm, { recursive: true });
8588
- const index = { schemaVersion: 1, entries };
8590
+ const index = { schemaVersion: SOMA_RUNTIME_STORE_FORMAT, entries };
8589
8591
  writeFileAtomic(import_node_path8.default.join(this.dirs.prewarm, "index.json"), `${JSON.stringify(index, null, 2)}
8590
8592
  `);
8591
8593
  }
@@ -8605,7 +8607,8 @@ function space() {
8605
8607
  loadedRoots: /* @__PURE__ */ new Set(),
8606
8608
  stores: /* @__PURE__ */ new Map(),
8607
8609
  layoutMemo: null,
8608
- rootErrorReported: false
8610
+ rootErrorReported: false,
8611
+ ownerGuards: /* @__PURE__ */ new Map()
8609
8612
  };
8610
8613
  }
8611
8614
  var LAYOUT_ENV_KEYS = ["SOMA_HOST_DIR", "SOMA_RUNTIME_DIR"];
@@ -8668,11 +8671,22 @@ function ensureLoaded() {
8668
8671
  console.warn(`[soma-core][\u5F15\u64CE] \u6301\u4E45\u7ED1\u5B9A ${binding.address} \u7684\u4EA7\u7269\u7F3A\u5931\u6216\u635F\u574F\uFF08${binding.digest.slice(0, 12)}\u2026\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\uFF1B\u91CD\u65B0 inject \u5373\u53EF\u6062\u590D\u3002`);
8669
8672
  continue;
8670
8673
  }
8674
+ const envelope = page.envelope ?? readFlatEnvelope(page.uiYaml);
8675
+ if (page.format !== SOMA_PAGE_FORMAT_VERSION) {
8676
+ store.removeBinding(binding.address);
8677
+ console.warn(`[soma-core][\u5F15\u64CE] \u6301\u4E45\u7ED1\u5B9A ${binding.address} \u7684\u4EA7\u7269\u6807\u51C6\u683C\u5F0F\u7248\u672C\u4E0D\u7B26\uFF0C\u5DF2\u4E22\u5F03\uFF1B\u7531\u4EA7\u51FA\u65B9\u91CD\u65B0\u7F16\u8BD1\u6CE8\u5165\u3002`);
8678
+ continue;
8679
+ }
8680
+ const guard = binding.owner === void 0 ? void 0 : state2.ownerGuards.get(binding.owner);
8681
+ if (guard !== void 0 && !guard(binding.version)) {
8682
+ store.removeBinding(binding.address);
8683
+ continue;
8684
+ }
8671
8685
  state2.generations.set(key, Math.max(state2.generations.get(key) ?? 0, binding.generation));
8672
8686
  state2.entries.set(key, {
8673
8687
  binding: { ...binding, persisted: true },
8674
8688
  page,
8675
- envelope: page.envelope ?? null,
8689
+ envelope,
8676
8690
  prefix: null,
8677
8691
  registryName: null,
8678
8692
  mtimeMs: read.mtimeMs
@@ -14148,7 +14162,7 @@ function writeIfChanged(file, content) {
14148
14162
  function readCompiledRecord(file) {
14149
14163
  try {
14150
14164
  const record3 = JSON.parse(import_node_fs14.default.readFileSync(file, "utf8"));
14151
- return record3.schemaVersion === 1 && typeof record3.digest === "string" ? record3 : null;
14165
+ return record3.schemaVersion === SOMA_RUNTIME_STORE_FORMAT && typeof record3.digest === "string" ? record3 : null;
14152
14166
  } catch {
14153
14167
  return null;
14154
14168
  }
@@ -14181,7 +14195,7 @@ async function runPrewarm(options) {
14181
14195
  continue;
14182
14196
  }
14183
14197
  const record3 = {
14184
- schemaVersion: 1,
14198
+ schemaVersion: SOMA_RUNTIME_STORE_FORMAT,
14185
14199
  address: item.address,
14186
14200
  digest,
14187
14201
  inputsDigest: item.inputsDigest,
@@ -14202,7 +14216,7 @@ async function runPrewarm(options) {
14202
14216
  } catch {
14203
14217
  }
14204
14218
  if (options.meta !== void 0) {
14205
- const record3 = { schemaVersion: 1, meta: options.meta };
14219
+ const record3 = { schemaVersion: SOMA_RUNTIME_STORE_FORMAT, meta: options.meta };
14206
14220
  writeIfChanged(import_node_path16.default.join(layout.dirs.prewarm, SOMA_PREWARM_META_FILE), `${JSON.stringify(record3)}
14207
14221
  `);
14208
14222
  }
@@ -14219,7 +14233,7 @@ async function runPrewarm(options) {
14219
14233
  persistedBindings += 1;
14220
14234
  }
14221
14235
  const sorted = Object.fromEntries(Object.entries(entries).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
14222
- const indexText = `${JSON.stringify({ schemaVersion: 1, entries: sorted }, null, 2)}
14236
+ const indexText = `${JSON.stringify({ schemaVersion: SOMA_RUNTIME_STORE_FORMAT, entries: sorted }, null, 2)}
14223
14237
  `;
14224
14238
  writeIfChanged(import_node_path16.default.join(layout.dirs.prewarm, "index.json"), indexText);
14225
14239
  return {
@@ -14247,7 +14261,7 @@ function readPrewarmCompiled(layout) {
14247
14261
  let meta = null;
14248
14262
  try {
14249
14263
  const parsed = JSON.parse(import_node_fs14.default.readFileSync(import_node_path16.default.join(layout.dirs.prewarm, SOMA_PREWARM_META_FILE), "utf8"));
14250
- if (parsed.schemaVersion === 1) meta = parsed.meta;
14264
+ if (parsed.schemaVersion === SOMA_RUNTIME_STORE_FORMAT) meta = parsed.meta;
14251
14265
  } catch {
14252
14266
  }
14253
14267
  return { pages, meta };
@@ -14436,6 +14450,18 @@ function precompilePage(p, context) {
14436
14450
  // host-native/src/host-prepare.ts
14437
14451
  var import_host_config_paths5 = __toESM(require_host_config_paths());
14438
14452
  var SOMA_SHELL_ROUTES_ENV = "SOMA_SHELL_ROUTES";
14453
+ var coreIdentityMemo = null;
14454
+ function coreCompilerIdentity() {
14455
+ if (coreIdentityMemo !== null) return coreIdentityMemo;
14456
+ let version = "unknown";
14457
+ try {
14458
+ const raw = JSON.parse(import_node_fs15.default.readFileSync(import_node_path17.default.join(__dirname, "..", "..", "package.json"), "utf8"));
14459
+ if (typeof raw.version === "string") version = raw.version;
14460
+ } catch {
14461
+ }
14462
+ coreIdentityMemo = `soma-core@${version}/store-format-${SOMA_RUNTIME_STORE_FORMAT}`;
14463
+ return coreIdentityMemo;
14464
+ }
14439
14465
  var lastRaw;
14440
14466
  var lastParsed = [];
14441
14467
  function readShellRoutesFromEnv(env = process.env) {
@@ -14540,7 +14566,8 @@ async function prewarmHostPages(hostDir, env = process.env) {
14540
14566
  appConfigYaml: compileInput.appConfigYaml,
14541
14567
  hostAppConfigYaml: appConfigYaml,
14542
14568
  treeContext: compileInput.treeContext ?? null,
14543
- compilerIdentity: null
14569
+ // 预编译旁档只在「同一份 core 编的」时复用:core 升级后整批旁档自动失效,不需要手工清 .soma/runtime
14570
+ compilerIdentity: coreCompilerIdentity()
14544
14571
  }),
14545
14572
  compile: () => precompilePage(compileInput, { hostAppConfig: shell.appConfig })
14546
14573
  };
@@ -15488,6 +15515,13 @@ data: ${data || ""}
15488
15515
  });
15489
15516
  return refreshTask;
15490
15517
  };
15518
+ const waitForDevRefreshIdle = async () => {
15519
+ const deadline = Date.now() + 3e4;
15520
+ while (!watcherClosed && (refreshTask !== null || refreshPending || debounceTimer !== null) && Date.now() < deadline) {
15521
+ if (refreshTask !== null) await refreshTask.catch(() => void 0);
15522
+ else await new Promise((resolve4) => setTimeout(resolve4, 50));
15523
+ }
15524
+ };
15491
15525
  if (dev) {
15492
15526
  try {
15493
15527
  fsWatcher = import_node_fs17.default.watch(webRoot, { recursive: true }, (_event, filename) => {
@@ -15585,8 +15619,10 @@ data: ${data || ""}
15585
15619
  const subSegments = pathname.slice("/_soma/client/".length).split("/").filter(Boolean);
15586
15620
  const staticReq = createStaticLookupRequest(req, method);
15587
15621
  const clientStaticDir = import_node_path19.default.resolve(runtimeLayout2.dirs.static, "client");
15622
+ if (dev) await waitForDevRefreshIdle();
15588
15623
  const clientRes = serveStaticFromRoot(clientStaticDir, subSegments, staticReq, true);
15589
15624
  if (clientRes) {
15625
+ if (dev && !/immutable/.test(clientRes.headers.get("cache-control") ?? "")) clientRes.headers.set("cache-control", "no-cache");
15590
15626
  await sendWebResponse(clientRes, res, method);
15591
15627
  return;
15592
15628
  }
@@ -15650,6 +15686,7 @@ data: ${data || ""}
15650
15686
  await sendWebResponse(response, res, method);
15651
15687
  return;
15652
15688
  } catch (error) {
15689
+ if (!isStatusError(error)) console.error(`[soma-native] \u9875\u9762\u8F7D\u5165\u5931\u8D25 path=${pagePath}`, error);
15653
15690
  let response = pageErrorResponse(error, assembly);
15654
15691
  response = await applyHostAndCspHeaders(response, { method: "GET", pathname }, env);
15655
15692
  await sendWebResponse(response, res, method);
@@ -1,4 +1,4 @@
1
- export type { ChartInit, ChartInstance, ChartPointer, ChartTheme, SomaChartAdapter, SomaChartEnginePort, } from './port';
1
+ export type { ChartColumn, ChartInit, ChartInstance, ChartPointer, ChartTheme, SomaChartAdapter, SomaChartEnginePort, } from './port';
2
2
  export { assertChartAdapter } from './port';
3
3
  import type { EngineLoadTelemetry } from '../load';
4
4
  import { type SomaChartAdapter, type SomaChartEnginePort } from './port';
@@ -19,7 +19,22 @@ export interface ChartPointer {
19
19
  readonly y: number;
20
20
  };
21
21
  }
22
+ /** 指针 / 键盘所在的类目轴列;空值列、列间空白也能命中(与系列是否有图元无关) */
23
+ export interface ChartColumn {
24
+ /** 第一个类目轴上的列序号(与系列 data 下标一致) */
25
+ readonly dataIndex: number;
26
+ /** 该列在容器内的锚点像素(列中心、绘图区顶部) */
27
+ readonly anchor: {
28
+ readonly x: number;
29
+ readonly y: number;
30
+ };
31
+ }
22
32
  export interface ChartInstance {
33
+ /**
34
+ * 指针在绘图区内移动 / 点击 / 离开时按坐标轴换算所在列;落在绘图区外按 leave 处理;无类目轴的图(饼、仪表等)不触发。
35
+ * 可选:旧适配器缺该方法时调用方回落到 `onPointer`(只有带图元的列可交互)。
36
+ */
37
+ onColumn?(handler: (kind: 'hover' | 'click' | 'leave', col: ChartColumn | null) => void): () => void;
23
38
  setOption(option: Readonly<Record<string, unknown>>, mode?: 'merge' | 'replace'): void;
24
39
  /** 键盘漫游驱动 */
25
40
  highlight(p: {
@@ -3,6 +3,8 @@ import { addressShapeKey, compareAddressSpecificity } from '../../shared/runtime
3
3
  import { type SomaAccessIdentity, type SomaAccessPolicy } from './access-gate';
4
4
  import { SomaRuntimeStore } from './store';
5
5
  import type { SomaNavView, SomaRuntimeBinding, SomaRuntimeLayout, SomaStandardPage, SomaStandardPageEnvelope } from './types';
6
+ /** 方言所有者给的版本守卫:`version` 是它随产物给出的不透明版本号;返回 false = 该产物不是本版产出方编的,不得恢复 */
7
+ export type OwnerVersionGuard = (version: string | undefined) => boolean;
6
8
  /** 前缀解析器交回的东西:标准格式载荷,或兼容旧入口已经拼好的运行时资产(虚拟页的 `artifact` / 声明分支) */
7
9
  export type PrefixPageResult = {
8
10
  readonly kind: 'page';
@@ -47,10 +49,17 @@ interface SpaceState {
47
49
  readonly layout: SomaRuntimeLayout;
48
50
  } | null;
49
51
  rootErrorReported: boolean;
52
+ /** owner → 版本守卫(方言所有者登记;core 不解释 version) */
53
+ readonly ownerGuards: Map<string, OwnerVersionGuard>;
50
54
  }
51
55
  export declare function space(): SpaceState;
52
56
  /** 测试复位:清空绑定表、代次、到期记录与装入标记(不动磁盘) */
53
57
  export declare function resetRuntimeSpace(): void;
58
+ /**
59
+ * 方言所有者登记版本守卫(升级隐患闸):持久绑定恢复时,owner 相同的条目其 `version` 须被守卫接受,否则丢弃(连绑定文件),
60
+ * 页面由所有者按本版编译器重新注入。登记时已装入的同 owner 持久条目立刻对一遍。core 只存守卫、不解释 version(缓存键 = URL + version)。
61
+ */
62
+ export declare function registerOwnerVersionGuard(owner: string, guard: OwnerVersionGuard): void;
54
63
  /** 当前进程的 runtime 布局(按环境签名记忆,避免每次调用都读盘) */
55
64
  export declare function runtimeLayout(): SomaRuntimeLayout;
56
65
  export declare function runtimeStore(layout?: SomaRuntimeLayout): SomaRuntimeStore;
@@ -1,4 +1,9 @@
1
1
  import type { SomaStandardPage } from './types';
2
+ /**
3
+ * core 落盘产物的格式版本(绑定记录、预热索引与旁档、预热元数据共用)。落盘结构(信封、闸门等)有不兼容变化时递增;
4
+ * 读回时版本不符一律视为无效并丢弃,由方言所有者重新编译注入,不做迁移也不手工清目录。
5
+ */
6
+ export declare const SOMA_RUNTIME_STORE_FORMAT = 2;
2
7
  /** 摘要形状:64 位小写十六进制 */
3
8
  export declare const SOMA_RUNTIME_DIGEST_PATTERN: RegExp;
4
9
  export declare function isRuntimeDigest(value: unknown): value is string;
@@ -2,7 +2,7 @@ export { inject, injectMany, bindPrefix, unbind, validateAddress, type SomaInjec
2
2
  export { registerSomaPage, registerSomaPages, injectCompiledPage, withdrawPage, readCachedPage, pageCacheKey, listRegisteredPages, parseSomaDsl, renderHtmlTree, normalizeSomaPageInput, type SomaPageInput, type SomaCompiledPage, type SomaHtmlNode, type SomaHtmlChild, type SomaDslDoc, type SomaDslKind, type SomaDslParseResult, type SomaPageRegisterOptions, type SomaPageRegistration, type SomaPageBatchEntry, type SomaPageBatchOutcome, type SomaCachedPage, type SomaRegisteredPage, } from './dynamic-pages';
3
3
  export { resolveAddress, loadPageByAddress, listBindings, runtimeSpaceStats, type SomaLoadedPage, type SomaLoadPageOptions } from './resolve';
4
4
  export { SomaRuntimeError, type SomaRuntimeBatchFailure, type SomaRuntimeErrorCode } from './errors';
5
- export { setNavProvider, type NavProvider } from './bindings';
5
+ export { setNavProvider, registerOwnerVersionGuard, type NavProvider, type OwnerVersionGuard } from './bindings';
6
6
  export { registerPage, registerPages, validatePageGrants, adjudicateGrant, stampEnvelope, SOMA_DEFAULT_PAGE_GRANTS, type SomaRegisterOptions, type SomaRegisterManyEntry, type SomaGrantDecision, type SomaGrantRequest, } from './page-grants';
7
7
  export { SomaSubmitStepError, checkSubmitOptions, decideSubmitAddress, precheckSubmitSlot, checkExpectedGeneration, stampSubmitEnvelope, buildRegisterRequest, registerPageOrReject, findUnchangedBinding, createProvenanceLedger, unbindOwnedPage, listPageBindings, } from './submit-steps';
8
8
  export type { SomaSubmitStepIssue, SomaSubmitStepsRuntime, SomaSubmitAddressKind, SomaPageRegisterRequest, SomaPageBindingView, SomaProvenanceLedger, } from './types';
@@ -3,7 +3,7 @@ export declare const SOMA_PREWARM_COMPILED_DIR = "compiled";
3
3
  export declare const SOMA_PREWARM_META_FILE = "meta.json";
4
4
  /** 旁档:一个静态页的构建期编译结果 */
5
5
  export interface SomaPrewarmCompiledRecord<T = unknown> {
6
- readonly schemaVersion: 1;
6
+ readonly schemaVersion: number;
7
7
  readonly address: string;
8
8
  /** 对应标准格式产物的摘要;与索引不一致即视为失效 */
9
9
  readonly digest: string;
@@ -13,7 +13,7 @@ export interface SomaPrewarmCompiledRecord<T = unknown> {
13
13
  }
14
14
  /** 全局元数据(路由表、词表、应用配置):不属于某一页 */
15
15
  export interface SomaPrewarmMeta<M = unknown> {
16
- readonly schemaVersion: 1;
16
+ readonly schemaVersion: number;
17
17
  readonly meta: M;
18
18
  }
19
19
  export interface SomaPrewarmStaticPage<T = unknown> {
@@ -171,12 +171,13 @@ export interface SomaRuntimeStoreStats {
171
171
  }
172
172
  /** 一条落盘的绑定记录(`<root>/bindings/<键>.json`) */
173
173
  export interface SomaPersistedBinding {
174
- readonly schemaVersion: 1;
174
+ /** core 落盘格式版本(`SOMA_RUNTIME_STORE_FORMAT`);读回不符即丢弃 */
175
+ readonly schemaVersion: number;
175
176
  readonly binding: SomaRuntimeBinding;
176
177
  }
177
178
  /** 预热索引 `<root>/prewarm/index.json` */
178
179
  export interface SomaPrewarmIndex {
179
- readonly schemaVersion: 1;
180
+ readonly schemaVersion: number;
180
181
  /** 地址 → 内容摘要 */
181
182
  readonly entries: Readonly<Record<string, string>>;
182
183
  }
@@ -7,12 +7,28 @@ import { addressOfPageBase } from '../../core/build/compiler/page-base-resolver'
7
7
  import { loadPageMarkupConfig } from '../../core/server/host/page-markup-config';
8
8
  import { resolveHostTreeCompileContext } from '../../core/server/host/resolve-host-tree-context';
9
9
  import { runPrewarm, computePrewarmInputsDigest } from '../../core/server/runtime-space/prewarm';
10
+ import { SOMA_RUNTIME_STORE_FORMAT } from '../../core/server/runtime-space/digest';
10
11
  import { resolveAppConfigPath, resolveHostAppConfigPath } from '../../core/server/host/host-config-paths.cjs';
11
12
  import { getSomaAssetSources, collectPageEntries, collectIncludes } from '../../core/server/host/source-packages';
12
13
  import { invalidateStaticAddresses } from '../../core/server/runtime-space/static-source';
13
14
 
14
15
  export const SOMA_SHELL_ROUTES_ENV = 'SOMA_SHELL_ROUTES';
15
16
 
17
+ let coreIdentityMemo: string | null = null;
18
+ /** 预编译旁档的编译身份:soma-core 包版本 + 落盘格式版本;读不到包版本时回 `unknown`(不复用不是错,复用旧的才是错——此时随格式版本变) */
19
+ function coreCompilerIdentity(): string {
20
+ if (coreIdentityMemo !== null) return coreIdentityMemo;
21
+ let version = 'unknown';
22
+ try {
23
+ const raw = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8')) as { version?: unknown };
24
+ if (typeof raw.version === 'string') version = raw.version;
25
+ } catch {
26
+ /* 读不到:用 unknown */
27
+ }
28
+ coreIdentityMemo = `soma-core@${version}/store-format-${SOMA_RUNTIME_STORE_FORMAT}`;
29
+ return coreIdentityMemo;
30
+ }
31
+
16
32
  let lastRaw: string | undefined;
17
33
  let lastParsed: readonly string[] = [];
18
34
 
@@ -138,7 +154,8 @@ export async function prewarmHostPages(hostDir: string, env: NodeJS.ProcessEnv =
138
154
  appConfigYaml: compileInput.appConfigYaml,
139
155
  hostAppConfigYaml: appConfigYaml,
140
156
  treeContext: compileInput.treeContext ?? null,
141
- compilerIdentity: null,
157
+ // 预编译旁档只在「同一份 core 编的」时复用:core 升级后整批旁档自动失效,不需要手工清 .soma/runtime
158
+ compilerIdentity: coreCompilerIdentity(),
142
159
  }),
143
160
  compile: () => precompilePage(compileInput, { hostAppConfig: shell.appConfig }),
144
161
  };
@@ -16,6 +16,7 @@ import { clearTailwindCompilerCache } from 'soma-core/server/style-engine';
16
16
  import { resolveHostResponseHeaders } from '../../core/server/host/host-response-headers';
17
17
  import type { BrowserClientBuildResult, ServerAotManifest } from './aot-builder';
18
18
  import { pageSuccessResponse, pageErrorResponse } from './page-http';
19
+ import { isStatusError } from '../../core/server/runtime-space/errors';
19
20
  import { handleManifestGet } from './manifest-http';
20
21
  import { prepareHostAssembly, invalidateHostPreparation, prewarmHostPages } from './host-prepare';
21
22
  import { staticResponse, serveStaticFromRoot, isSafeSegments, acceptsGzip } from './static-file';
@@ -684,6 +685,15 @@ export async function createNativeServer(
684
685
  return refreshTask;
685
686
  };
686
687
 
688
+ /** 等开发态刷新队列走空(有待处理变更、debounce 中、重建中都算忙),至多等 30 秒,超时放行(不让一次卡住的重建拖死页面) */
689
+ const waitForDevRefreshIdle = async (): Promise<void> => {
690
+ const deadline = Date.now() + 30_000;
691
+ while (!watcherClosed && (refreshTask !== null || refreshPending || debounceTimer !== null) && Date.now() < deadline) {
692
+ if (refreshTask !== null) await refreshTask.catch(() => undefined);
693
+ else await new Promise<void>((resolve) => setTimeout(resolve, 50));
694
+ }
695
+ };
696
+
687
697
  if (dev) {
688
698
  try {
689
699
  fsWatcher = fs.watch(webRoot, { recursive: true }, (_event, filename) => {
@@ -807,8 +817,12 @@ export async function createNativeServer(
807
817
  const subSegments = pathname.slice('/_soma/client/'.length).split('/').filter(Boolean);
808
818
  const staticReq = createStaticLookupRequest(req, method);
809
819
  const clientStaticDir = path.resolve(runtimeLayout.dirs.static, 'client');
820
+ // 开发态:增量重建进行中先等它写完——entry 与它引用的 chunk 是同一代产物,重建中途请求会读到「新 entry + 还没写出的 chunk」或「旧 chunk 已被清掉」(偶发 404,页面无内容)
821
+ if (dev) await waitForDevRefreshIdle();
810
822
  const clientRes = serveStaticFromRoot(clientStaticDir, subSegments, staticReq, true);
811
823
  if (clientRes) {
824
+ // 开发态:不带内容哈希的 entry / 样式每次都向服务器核对(缺省 max-age=300 会让浏览器在重建后的 5 分钟里继续用旧 entry,它引用的旧哈希 chunk 已被重建清掉 → 404)
825
+ if (dev && !/immutable/.test(clientRes.headers.get('cache-control') ?? '')) clientRes.headers.set('cache-control', 'no-cache');
812
826
  await sendWebResponse(clientRes, res, method);
813
827
  return;
814
828
  }
@@ -890,6 +904,8 @@ export async function createNativeServer(
890
904
  await sendWebResponse(response, res, method);
891
905
  return;
892
906
  } catch (error) {
907
+ // 响应体对外只给通用 500(不泄露内部细节),原因必须落服务端日志,否则页面载入失败无从排查
908
+ if (!isStatusError(error)) console.error(`[soma-native] 页面载入失败 path=${pagePath}`, error);
893
909
  let response = pageErrorResponse(error, assembly);
894
910
  response = await applyHostAndCspHeaders(response, { method: 'GET', pathname }, env);
895
911
  await sendWebResponse(response, res, method);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soma-core",
3
- "version": "2.2.7",
3
+ "version": "2.2.8",
4
4
  "description": "SOMA — Semantic Oriented Modular Architecture. A declarative frontend framework runtime with no UI framework dependency; native host shell ships in host-native/.",
5
5
  "keywords": [
6
6
  "soma",
@@ -332,7 +332,7 @@
332
332
  "parse5": "7.3.0",
333
333
  "qrcode-generator": "2.0.4",
334
334
  "server-only": "0.0.1",
335
- "soma-foundation": "^0.1.4",
335
+ "soma-foundation": "^0.1.5",
336
336
  "temporal-polyfill": "0.3.2"
337
337
  },
338
338
  "peerDependencies": {