An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
feat: add normalize() spec entry, $schema stamp, and spec-compat fixtures
Elwynn Chen3849b16d153f
diff --git a/docs/terse-spec-design.md b/docs/terse-spec-design.mdnew file mode 100644index 00000000..e0200de4--- /dev/null+++ b/docs/terse-spec-design.md@@ -0,0 +1,199 @@+# TerseSpec 设计草案(v0,供设计评审)++> 状态:第二阶段交付的设计文档,**不含实现**。实现排在第三阶段,接入方式见 §6。+> 前置阅读:`docs/dsl-design-review.md`(§1.4、§3.3 修订版)。+> 核心原则:TerseSpec 是 **authoring format(为人写)**,canonical IChart 是**持久化与机器格式**。TerseSpec → `normalize()` → canonical 单向转换;canonical → TerseSpec 是可选的**有损投影**(丢弃未被图表引用的字段),持久化永远走 canonical。++## 1. 设计目标与非目标++**目标**++1. 一个懂数据的人在文档陪伴下 5 分钟内能手写出第一张图;+2. 全字段可省略:最小合法 spec 是 `{}`(得到空图表)或 `{ x: "Region", y: "sum(Sales)" }`(得到一张柱状图);+3. 渐进式:TerseSpec 与 canonical 不是两门语言,而是同一 schema 的省略程度谱系——任何 canonical 片段都可以混写在 terse spec 里做精细控制,normalize 都接得住;+4. 自包含:被引用的 computed 字段定义内联在 spec 内,离开原 workspace 依然有效;+5. LLM 友好:字段按名字引用、结构浅、与 Vega-Lite 的心智模型对齐,便于模型生成。++**非目标**++- 不替代 canonical IChart(持久化、undo/redo、store 内部一律不变);+- 不描述 dashboard/多图布局(单图表 spec);+- 不引入新的计算能力(表达式仍是 `IExpression` 的能力边界);+- v0 不支持 paint(画笔字段无法合理手写,投影时遇到 paint 字段报 warning 并跳过)。++## 2. Schema 草案++```typescript+/** 字段引用:名字或 fid;或带 per-channel 覆盖的对象形式 */+type TerseFieldRef =+ | string // 'Sales' | 'sum(Sales)' | 'fid:sales'(见 §3、§4)+ | {+ field: string; // 名字、shorthand 或 'fid:' 前缀引用+ aggregate?: IAggregator; // 与 shorthand 二选一,重复时报错+ sort?: 'ascending' | 'descending';+ timeUnit?: (typeof DATE_TIME_DRILL_LEVELS)[number];+ };++/** 过滤器:三种规则的字面语法 */+type TerseFilter =+ | { field: string; oneOf: any[] }+ | { field: string; notIn: any[] }+ | { field: string; range: [number | null, number | null] }+ | { field: string; timeRange: [string | number | null, string | number | null] };++/** 内联 computed 字段定义(自包含的关键) */+interface TerseComputedField {+ name: string; // terse 内的引用名,亦作展示名+ /** 三选一的定义方式 */+ expr?: string; // SQL-like 表达式,如 'sales * 0.85'+ bin?: { field: string; count?: number }; // 等宽分箱+ log?: { field: string; base?: number }; // 对数变换+ analyticType?: 'dimension' | 'measure'; // 缺省按定义方式推断+}++interface TerseSpec {+ /** 版本戳,可选;缺省视为最新 terse 版本 */+ $schema?: string; // 'https://graphic-walker.kanaries.net/tersespec_v1.json'++ /** 图表类型,对应 config.geoms[0];缺省 'auto' */+ mark?: string;++ name?: string;++ /** 主轴:x → columns,y → rows;数组表示多字段(facet/多度量) */+ x?: TerseFieldRef | TerseFieldRef[];+ y?: TerseFieldRef | TerseFieldRef[];++ /** 视觉通道,单字段 */+ color?: TerseFieldRef;+ opacity?: TerseFieldRef;+ size?: TerseFieldRef;+ shape?: TerseFieldRef;+ text?: TerseFieldRef;+ /** 多字段通道 */+ details?: TerseFieldRef | TerseFieldRef[];+ /** 极坐标 / 地理通道 */+ theta?: TerseFieldRef;+ radius?: TerseFieldRef;+ longitude?: TerseFieldRef;+ latitude?: TerseFieldRef;+ geoId?: TerseFieldRef;++ filters?: TerseFilter[];++ /** 内联 computed 字段;只需列出本图用到的 */+ computed?: TerseComputedField[];++ /** 常用旋钮的扁平化提升(高频配置不该藏在两层深处) */+ aggregate?: boolean; // → config.defaultAggregated,缺省 true+ stack?: 'none' | 'stack' | 'normalize' | 'center'; // → layout.stack+ limit?: number; // → config.limit+ sort?: 'ascending' | 'descending'; // 应用于最后一个度量,与 Tableau 心智一致++ /** 渐进式逃生舱:任何 canonical 片段,最后浅合并(见 §5 优先级) */+ config?: Partial<IVisualConfigNew>;+ layout?: Partial<IVisualLayout>;+}+```++**JSON 示例**++最小:++```json+{ "x": "Region", "y": "sum(Sales)" }+```++典型:++```json+{+ "mark": "bar",+ "x": "Region",+ "y": ["sum(Sales)", "mean(Profit)"],+ "color": "Segment",+ "filters": [{ "field": "Year", "oneOf": [2024, 2025] }],+ "stack": "normalize",+ "limit": 20+}+```++含内联 computed 字段与精细控制:++```json+{+ "mark": "point",+ "computed": [+ { "name": "Net Sales", "expr": "sales * 0.85", "analyticType": "measure" },+ { "name": "Sales Bucket", "bin": { "field": "Sales", "count": 10 } }+ ],+ "x": "Sales Bucket",+ "y": "sum(Net Sales)",+ "size": { "field": "Profit", "aggregate": "mean" },+ "layout": { "size": { "mode": "fixed", "width": 800, "height": 600 } }+}+```++## 3. 字段引用解析(name → fid)++解析在 `normalize()` 内进行,依赖传入的 `meta: IMutField[]`,规则按序:++1. **`fid:` 前缀直引**:`'fid:sales'` 绕过名字解析直接引用 fid。用于重名兜底与程序化生成;+2. **精确名字匹配**:与 `meta[].name` 精确相等(区分大小写);+3. **内联 computed 匹配**:与 `computed[].name` 精确相等;+4. **fid 直接匹配**:与 `meta[].fid` 精确相等(容忍用户把 fid 当名字写);+5. **大小写不敏感兜底**:唯一命中时接受并产生 warning;多命中报错。++**错误报告格式**(实现约束,不是建议):找不到字段时,错误信息必须包含:输入的引用串、最相近的 3 个候选名(编辑距离)、可用字段总数。重名(两个字段同名)时:报错并要求 `fid:` 前缀,错误信息列出冲突各方的 fid。++**为什么不做模糊匹配**:LLM 与人都会写错字段名,但静默容错会把错误图表当正确结果交付;显式报错 + 候选提示的纠错回路更短。++## 4. 聚合 shorthand 文法++```+shorthand := aggName '(' fieldRef ')' | fieldRef+aggName := 'sum' | 'count' | 'max' | 'min' | 'mean' | 'median'+ | 'variance' | 'stdev' | 'distinctCount'+```++- `'sum(Sales)'` ≡ `{ field: 'Sales', aggregate: 'sum' }`;+- `aggName` 全集与 `IAggregator` 对齐,唯 `expr` 除外(聚合表达式必须走对象形式 + 内联 computed,shorthand 里没有合理的语法位置);+- `'count()'` 无参形式映射到内置 count 字段(`gw_count_fid`);+- 字段名本身含 `(` 的用 `fid:` 前缀或对象形式绕开;shorthand 解析只在**最外层一对括号且前缀恰为合法 aggName** 时触发,否则整串按字段名处理——`'log(x)'` 不是合法 aggName,按名字解析,不会静默变成聚合。++## 5. Normalize 展开规则(terse → canonical)++按序执行,每步都是纯函数:++1. **解析引用**:全部 `TerseFieldRef` / `TerseFilter.field` / `TerseComputedField` 内的字段引用按 §3 解析成 fid;内联 computed 字段生成确定性 fid(`gw_t_` + name 的短哈希,同名同 fid,保证幂等);+2. **构建池子**:`dimensions/measures 池 = meta 全体字段(newChart 语义,含 count/mea_key/mea_val 合成字段) + 内联 computed 字段`。这正是 dsl-design-review §3.3 的重建规则——terse 不含池子,池子是推导物;+3. **通道映射**:`x → columns`、`y → rows`,其余通道同名映射;`TerseFieldRef` 展开为完整 `IViewField`(从池子取字段对象,叠加 aggregate/sort/timeUnit 覆盖);+4. **旋钮映射**:`mark → config.geoms[0]`、`aggregate → config.defaultAggregated`、`stack → layout.stack`、`limit → config.limit`、`sort → 最后一个 y 度量的 sort`;+5. **canonical 片段合并**:`config`/`layout` 字段浅合并,**优先级最高**(显式的 canonical 写法压过扁平旋钮;两处都写时产生 warning);+6. **进入既有管线**:结果作为 `PartialChart` 走 `fillChart` → `algebraLint` + `lintExtraFields` → `$schema` 戳——与 normalize 现有出口完全一致。++## 6. 与 `normalize()` 的接入方式(第三阶段)++- `detectSpecKind` 增加第一优先级规则:`$schema` 为 tersespec URL,或存在 terse 特征键(`x`/`y`/`mark`/`computed` 且无 `encodings`/`layout`)→ `'terse'`;+- `normalize()` switch 增加 `case 'terse': chart = expandTerse(input, meta)`,之后共用现有出口管线;+- 新增 `project(chart: IChart, meta: IMutField[]): TerseSpec` 反向投影:遍历 channels/filters/folds 收集实际引用的字段,computed 字段内联为 `TerseComputedField`,未引用字段全部丢弃(有损,文档明示);`expr`/`bin`/`log` 之外的 expression op(dateTimeDrill 等)投影为对象形式的 `timeUnit`,paint 跳过并 warning;+- `gen-schema` 管线新增 `tersespec_v1.json` 产物,`$schema` URL 指向它;+- 废弃 `Specification` 接口与 `renderSpec()`(标 `@deprecated`,下个 major 删除)。++## 7. 开放问题(留给设计评审)++1. **`sort` 的作用目标**:v0 定义为"最后一个 y 度量"(Tableau 心智),但对多度量 + facet 场景是否该支持 per-field sort 语法(对象形式已支持,扁平旋钮是否多余)?+2. **`timeRange` 过滤器的字符串日期**:计算层规范(computation.md §3)规定 temporal range 只接受毫秒;terse 层接受 ISO 字符串意味着 normalize 要做解析并选定时区语义——用 `config.timezoneDisplayOffset` 还是 UTC?这是横跨两层 DSL 的语义决策,建议与 conformance 套件的时区用例一起定;+3. **内联 computed 的 fid 生成**:短哈希方案保证幂等,但两张图内联同名不同表达式的字段会产生 fid 冲突的隐患(单图内可检测报错,跨图无法);替代方案是 fid = 全表达式哈希(更安全但 fid 不稳定,重命名表达式即换 fid,破坏 per-chart 覆盖)。v0 倾向 name 哈希 + 单图冲突检测,征求意见;+4. **投影的往返测试标准**:`project(normalize(t)) ≡ t` 不可能严格成立(t 的 shorthand 有多种等价写法);建议标准为 `normalize(project(normalize(t))) ≡ normalize(t)`(canonical 层等价),是否足够?+5. **多 y 字段 + mark 数组**:Vega-Lite 允许 layer 不同 mark;GW 的 geoms 是单值语义(`geoms[0]`)。terse 的 `mark` 是否要预留数组形式,还是明确宣布 layer 不在此层解决?++## 8. 与现有机制的关系速查++| 现有物 | TerseSpec 落地后 |+|---|---|+| `Specification` + `renderSpec()` | 标 `@deprecated`,功能被 TerseSpec 全量覆盖 |+| `spec` prop(root.tsx) | 下个 major 换为接受 TerseSpec |+| `vlSpec` prop | 保留(vega-lite 路径已在 normalize 内) |+| `chart` prop / `importCode` | 完全不变(canonical 层) |+| `exportCode()` | 完全不变;新增可选的 `exportTerse()` 投影 |diff --git a/packages/graphic-walker/src/index.tsx b/packages/graphic-walker/src/index.tsxindex 0f6053b5..03cce15e 100644--- a/packages/graphic-walker/src/index.tsx+++ b/packages/graphic-walker/src/index.tsx@@ -5,6 +5,8 @@ export { embedGraphicWalker, embedGraphicRenderer, embedPureRenderer, embedTableexport * from './interfaces';export * from './store/visualSpecStore';export { resolveChart, convertChart, parseChart } from './models/visSpecHistory';+export { normalize, detectSpecKind } from './models/normalize';+export type { ISpecKind } from './models/normalize';export { getGlobalConfig } from './config';export { DataSourceSegmentComponent } from './dataSource';export * from './models/visSpecHistory';diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.tsindex c48a94bd..8e480884 100644--- a/packages/graphic-walker/src/interfaces.ts+++ b/packages/graphic-walker/src/interfaces.ts@@ -692,7 +692,15 @@ export interface IRawQuery {export type IViewQuery = IAggQuery | IFoldQuery | IBinQuery | IRawQuery;+export const IChartSchemaUrl = 'https://graphic-walker.kanaries.net/chartinfo.json';+export interface IChart {+ /**+ * Version stamp added by `normalize()`. Optional so that specs persisted by+ * earlier releases (which never carried it) stay valid, and readers must+ * tolerate its absence. `exportCode()` output is unaffected.+ */+ $schema?: string;visId: string;name?: string;encodings: DraggableFieldState;diff --git a/packages/graphic-walker/src/models/normalize.test.ts b/packages/graphic-walker/src/models/normalize.test.tsnew file mode 100644index 00000000..58bb5fbf--- /dev/null+++ b/packages/graphic-walker/src/models/normalize.test.ts@@ -0,0 +1,247 @@+jest.mock('nanoid', () => ({ nanoid: () => 'mock-id' }));++import { IChart, IChartSchemaUrl, IMutField, IViewField } from '../interfaces';+import { detectSpecKind, normalize } from './normalize';+import { fillChart, parseChart } from './visSpecHistory';+import { chartToWorkflow } from '../utils/workflow';+import { VizSpecStore } from '../store/visualSpecStore';++const META: IMutField[] = [+ { fid: 'category', name: 'Category', semanticType: 'nominal', analyticType: 'dimension' },+ { fid: 'region', name: 'Region', semanticType: 'nominal', analyticType: 'dimension' },+ { fid: 'city', name: 'City', semanticType: 'nominal', analyticType: 'dimension' },+ { fid: 'sales', name: 'Sales', semanticType: 'quantitative', analyticType: 'measure' },+];++const dim = (fid: string): IViewField => ({ fid, name: fid, semanticType: 'nominal', analyticType: 'dimension' });+const mea = (fid: string): IViewField => ({ fid, name: fid, semanticType: 'quantitative', analyticType: 'measure', aggName: 'sum' });++const ALL_CHANNELS = [+ 'dimensions',+ 'measures',+ 'rows',+ 'columns',+ 'color',+ 'opacity',+ 'size',+ 'shape',+ 'radius',+ 'theta',+ 'longitude',+ 'latitude',+ 'geoId',+ 'details',+ 'filters',+ 'text',+] as const;++describe('detectSpecKind', () => {+ test('vega-lite by $schema url', () => {+ expect(detectSpecKind({ $schema: 'https://vega.github.io/schema/vega-lite/v5.json' })).toBe('vega-lite');+ });+ test('vega-lite by structural keys', () => {+ expect(detectSpecKind({ mark: 'bar' })).toBe('vega-lite');+ expect(detectSpecKind({ encoding: { x: { field: 'a' } } })).toBe('vega-lite');+ expect(detectSpecKind({ hconcat: [] })).toBe('vega-lite');+ });+ test('chart by layout key, including normalize output with gw $schema', () => {+ expect(detectSpecKind({ layout: {} })).toBe('chart');+ const stamped = normalize({}, META);+ expect(detectSpecKind(stamped)).toBe('chart');+ });+ test('vis-spec by legacy config keys', () => {+ expect(detectSpecKind({ visId: 'a', encodings: {}, config: { stack: 'stack' } })).toBe('vis-spec');+ expect(detectSpecKind({ visId: 'a', encodings: {}, config: { size: { mode: 'auto', width: 320, height: 200 } } })).toBe('vis-spec');+ });+ test('partial-chart for everything else', () => {+ expect(detectSpecKind({})).toBe('partial-chart');+ expect(detectSpecKind({ encodings: { rows: [] } })).toBe('partial-chart');+ expect(detectSpecKind({ visId: 'a', config: { geoms: ['bar'], defaultAggregated: true, limit: -1 } })).toBe('partial-chart');+ });+ test('rejects non-object input', () => {+ expect(() => detectSpecKind(null as any)).toThrow(TypeError);+ expect(() => detectSpecKind([] as any)).toThrow(TypeError);+ });+});++describe('normalize', () => {+ test('fills a partial chart into a complete canonical chart', () => {+ const result = normalize({ encodings: { columns: [dim('category')], rows: [mea('sales')] } }, META);+ for (const channel of ALL_CHANNELS) {+ expect(Array.isArray(result.encodings[channel])).toBe(true);+ }+ expect(result.visId).toBe('gw_mock-id');+ expect(result.name).toBe('Chart');+ expect(result.config).toEqual({ defaultAggregated: true, geoms: ['auto'], coordSystem: 'generic', limit: -1 });+ expect(result.layout.size).toEqual({ mode: 'auto', width: 320, height: 200 });+ expect(result.layout.renderer).toBe('vega-lite');+ expect(result.encodings.columns).toEqual([dim('category')]);+ expect(result.encodings.rows).toEqual([mea('sales')]);+ expect(result.$schema).toBe(IChartSchemaUrl);+ });++ test('preserves provided values over defaults', () => {+ const result = normalize(+ {+ visId: 'my-vis',+ name: 'My Chart',+ config: { geoms: ['line'], limit: 50 },+ layout: { stack: 'none', size: { mode: 'fixed', width: 800, height: 600 } },+ },+ META,+ );+ expect(result.visId).toBe('my-vis');+ expect(result.name).toBe('My Chart');+ expect(result.config.geoms).toEqual(['line']);+ expect(result.config.limit).toBe(50);+ expect(result.config.defaultAggregated).toBe(true);+ expect(result.layout.stack).toBe('none');+ expect(result.layout.size).toEqual({ mode: 'fixed', width: 800, height: 600 });+ });++ test('migrates the deprecated IVisSpec format', () => {+ const legacy = {+ visId: 'legacy-1',+ name: 'Legacy',+ encodings: {+ dimensions: [dim('category')],+ measures: [mea('sales')],+ rows: [mea('sales')],+ columns: [dim('category')],+ },+ config: {+ defaultAggregated: true,+ geoms: ['bar'],+ stack: 'normalize',+ showTableSummary: true,+ size: { mode: 'fixed', width: 640, height: 480 },+ background: '#fff',+ limit: 25,+ },+ };+ const result = normalize(legacy as any, META);+ expect(result.config.geoms).toEqual(['bar']);+ expect(result.config.limit).toBe(25);+ expect(result.layout.stack).toBe('normalize');+ expect(result.layout.showTableSummary).toBe(true);+ expect(result.layout.background).toBe('#fff');+ expect(result.layout.size).toEqual({ mode: 'fixed', width: 640, height: 480 });+ for (const channel of ALL_CHANNELS) {+ expect(Array.isArray(result.encodings[channel])).toBe(true);+ }+ expect(result.$schema).toBe(IChartSchemaUrl);+ });++ test('maps a Vega-Lite spec through VegaliteMapper', () => {+ const vl = {+ mark: 'bar',+ title: 'VL Chart',+ encoding: {+ x: { field: 'Category', type: 'nominal' },+ y: { field: 'Sales', type: 'quantitative', aggregate: 'sum' },+ },+ };+ const result = normalize(vl, META);+ expect(result.config.geoms).toEqual(['bar']);+ expect(result.name).toBe('VL Chart');+ expect(result.encodings.columns.map((f) => f.fid)).toEqual(['category']);+ expect(result.encodings.rows.map((f) => f.fid)).toEqual(['sales']);+ expect(result.encodings.rows[0].aggName).toBe('sum');+ expect(result.$schema).toBe(IChartSchemaUrl);+ });++ test('applies algebraLint: dimensions first, at most 2 cross dimensions for non-table geoms', () => {+ const result = normalize(+ {+ config: { geoms: ['bar'], defaultAggregated: true, limit: -1 },+ encodings: { rows: [mea('sales'), dim('category'), dim('region'), dim('city')] },+ },+ META,+ );+ expect(result.encodings.rows.map((f) => f.fid)).toEqual(['category', 'region', 'sales']);+ });++ test('algebraLint keeps all dimensions for table geom', () => {+ const result = normalize(+ {+ config: { geoms: ['table'], defaultAggregated: true, limit: -1 },+ encodings: { rows: [dim('category'), dim('region'), dim('city')] },+ },+ META,+ );+ expect(result.encodings.rows.map((f) => f.fid)).toEqual(['category', 'region', 'city']);+ });++ test('is idempotent for all input kinds', () => {+ const inputs = [+ { encodings: { columns: [dim('category')], rows: [mea('sales'), dim('region')] } },+ {+ visId: 'legacy-2',+ encodings: { dimensions: [dim('category')], rows: [mea('sales')] },+ config: { defaultAggregated: false, geoms: ['line'], stack: 'stack', limit: -1 },+ },+ { mark: 'bar', encoding: { x: { field: 'Category' }, y: { field: 'Sales', aggregate: 'sum' } } },+ ];+ for (const input of inputs) {+ const once = normalize(input as any, META);+ const twice = normalize(once, META);+ expect(twice).toEqual(once);+ }+ });++ test('does not mutate its input', () => {+ const input = {+ visId: 'immutable',+ encodings: { rows: [mea('sales'), dim('category'), dim('region'), dim('city')] },+ config: { geoms: ['bar'], defaultAggregated: true, limit: -1 },+ };+ const snapshot = JSON.parse(JSON.stringify(input));+ normalize(input, META);+ expect(input).toEqual(snapshot);+ });+});++describe('$schema forward compatibility', () => {+ const stamped = normalize(+ {+ visId: 'fc-1',+ encodings: { columns: [dim('category')], rows: [mea('sales')], filters: [] },+ config: { geoms: ['bar'], defaultAggregated: true, limit: 10 },+ },+ META,+ );+ const unstamped: IChart = (({ $schema, ...rest }) => rest)(stamped) as IChart;++ test('parseChart passes a stamped chart through unchanged', () => {+ expect(parseChart(stamped)).toBe(stamped);+ });++ test('fillChart strips $schema and keeps everything else', () => {+ const filled = fillChart(stamped);+ expect('$schema' in filled).toBe(false);+ expect(filled).toEqual(unstamped);+ });++ test('chartToWorkflow output is identical with and without the stamp', () => {+ const withStamp = chartToWorkflow(stamped);+ const withoutStamp = chartToWorkflow(unstamped);+ expect(withStamp).toEqual(withoutStamp);+ expect(withStamp.workflow.length).toBeGreaterThan(0);+ });++ test('store import/export round trip does not persist the stamp', () => {+ const store = new VizSpecStore(META, { empty: true });+ store.importCode([stamped]);+ const exported = store.exportCode();+ expect(exported).toHaveLength(1);+ expect('$schema' in exported[0]).toBe(false);+ expect(JSON.stringify(exported)).not.toContain('$schema');+ expect(exported[0]).toEqual(unstamped);+ });++ test('normalize does not stamp charts that skip it: exportCode output shape is unchanged', () => {+ const store = new VizSpecStore(META);+ const exported = store.exportCode();+ expect(JSON.stringify(exported)).not.toContain('$schema');+ });+});diff --git a/packages/graphic-walker/src/models/normalize.ts b/packages/graphic-walker/src/models/normalize.tsnew file mode 100644index 00000000..4f6ae540--- /dev/null+++ b/packages/graphic-walker/src/models/normalize.ts@@ -0,0 +1,125 @@+import { DraggableFieldState, IChart, IChartSchemaUrl, IMutField, IVisSpec, PartialChart } from '../interfaces';+import { fillChart, lintExtraFields, newChart, parseChart } from './visSpecHistory';+import { uniqueId } from './utils';+import { VegaliteMapper } from '../lib/vl2gw';+import { algebraLint } from '../lib/gog';++/**+ * The kind of spec accepted by {@link normalize}:+ * - `chart`: a (possibly partial) modern spec that already has a `layout` key. Routed through+ * `parseChart` passthrough, then completed with defaults.+ * - `vis-spec`: the deprecated `IVisSpec` format (single `config` object carrying layout-ish+ * fields). Routed through the `forwardVisualConfigs` → `visSpecDecoder` → `convertChart`+ * migration chain inside `parseChart`.+ * - `vega-lite`: a Vega-Lite-like spec. Routed through `VegaliteMapper`; requires `meta` to+ * resolve field names, otherwise unresolved fields fall back to the count field.+ * - `partial-chart`: everything else — treated as `PartialChart` and completed with defaults.+ */+export type ISpecKind = 'chart' | 'vis-spec' | 'vega-lite' | 'partial-chart';++// Structural keys that exist on Vega-Lite specs but never on IChart / IVisSpec / PartialChart.+const VEGA_LITE_KEYS = ['mark', 'encoding', 'spec', 'concat', 'hconcat', 'vconcat'] as const;++// Keys of the deprecated IVisualConfig that IVisualConfigNew does not have. Real-world IVisSpec+// exports always carry them because they were serialized from initVisualConfig()-filled configs;+// their presence is what distinguishes a legacy spec from a PartialChart that has a `config` but+// no `layout`. A config without any of these keys is safer to treat as partial (fillChart keeps+// defaults for absent keys, while convertChart would overwrite them with `undefined`).+const LEGACY_CONFIG_KEYS = [+ 'showTableSummary',+ 'stack',+ 'showActions',+ 'interactiveScale',+ 'sorted',+ 'zeroScale',+ 'size',+ 'format',+ 'geoKey',+ 'resolve',+ 'scaleIncludeUnmatchedChoropleth',+ 'background',+ 'colorPalette',+ 'primaryColor',+ 'scale',+ 'geojson',+ 'geoUrl',+ 'useSvg',+] as const;++/**+ * Detect which input format a spec is in. The rules are ordered and explicit:+ * 1. a `$schema` pointing at vega.github.io, or any Vega-Lite structural key+ * (`mark` / `encoding` / `spec` / `concat` / `hconcat` / `vconcat`) → `vega-lite`;+ * 2. a `layout` key → `chart` (same duck-typing as `parseChart` / `importCode`);+ * 3. a `config` carrying legacy-only keys (`stack`, `size`, `resolve`, …) → `vis-spec`;+ * 4. anything else → `partial-chart`.+ */+export function detectSpecKind(input: object): ISpecKind {+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {+ throw new TypeError('normalize() expects a single spec object; got ' + (Array.isArray(input) ? 'an array' : String(input)));+ }+ const spec = input as Record<string, unknown>;+ if (typeof spec.$schema === 'string' && spec.$schema.includes('vega.github.io')) {+ return 'vega-lite';+ }+ if (VEGA_LITE_KEYS.some((key) => key in spec)) {+ return 'vega-lite';+ }+ if ('layout' in spec) {+ return 'chart';+ }+ if (spec.config && typeof spec.config === 'object' && LEGACY_CONFIG_KEYS.some((key) => key in (spec.config as object))) {+ return 'vis-spec';+ }+ return 'partial-chart';+}++/**+ * Normalize any accepted spec input into a complete, canonical IChart:+ * every encoding channel present, config/layout defaults filled, `visId` generated when missing,+ * spatial channels linted by `algebraLint`, and a `$schema` version stamp attached.+ *+ * This is a pure function (no store, no React, no side effects) and is idempotent:+ * `normalize(normalize(x, meta), meta)` deep-equals `normalize(x, meta)`.+ *+ * Existing import/export paths do not call this function; it is a purely additive entry point.+ *+ * @param input a full or partial IChart, a deprecated IVisSpec, or a Vega-Lite-like spec.+ * @param meta dataset fields; required to resolve field names for the Vega-Lite path.+ */+export function normalize(input: IChart | IVisSpec | PartialChart | Record<string, unknown>, meta: IMutField[] = []): IChart {+ const kind = detectSpecKind(input);+ let chart: IChart;+ switch (kind) {+ case 'vega-lite': {+ const vl = input as Record<string, unknown>;+ const base = newChart(meta, '');+ const allFields = [...base.encodings.dimensions, ...base.encodings.measures];+ const name = typeof vl.title === 'string' ? vl.title : 'Chart';+ chart = VegaliteMapper(vl, allFields, uniqueId(), name);+ break;+ }+ case 'chart':+ case 'vis-spec':+ chart = parseChart(input as IChart | IVisSpec);+ break;+ case 'partial-chart':+ default:+ chart = fillChart(input as PartialChart);+ break;+ }+ const filled = fillChart(chart);+ const geom = filled.config.geoms[0] ?? 'auto';+ // Same lint pass the store reducer applies on every encoding change (diffLinter middleware),+ // so normalized output matches what the UI would converge to for the same spec.+ const encodings: DraggableFieldState = {+ ...filled.encodings,+ ...algebraLint(geom, filled.encodings),+ ...lintExtraFields(filled.encodings),+ };+ return {+ ...filled,+ encodings,+ $schema: IChartSchemaUrl,+ };+}diff --git a/packages/graphic-walker/src/models/visSpecHistory.ts b/packages/graphic-walker/src/models/visSpecHistory.tsindex d9b7b52d..e86af841 100644--- a/packages/graphic-walker/src/models/visSpecHistory.ts+++ b/packages/graphic-walker/src/models/visSpecHistory.ts@@ -516,7 +516,7 @@ function makeFieldAtLast<T>(arr: T[], lasts: ((item: T) => boolean)[]): T[] {return result.concat(found.flat());}-function lintExtraFields<T extends Partial<DraggableFieldState>>(encodings: T): Partial<T> {+export function lintExtraFields<T extends Partial<DraggableFieldState>>(encodings: T): Partial<T> {const result: Partial<T> = {};if (encodings.dimensions && encodings.dimensions.length > 0) {result.dimensions = makeFieldAtLast(encodings.dimensions, [(i) => i.fid === PAINT_FIELD_ID, (i) => i.fid === MEA_KEY_ID]);diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/chart-current-complex.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/chart-current-complex.expected.jsonnew file mode 100644index 00000000..fd7c14dc--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/chart-current-complex.expected.json@@ -0,0 +1,211 @@+{+ "config": {+ "defaultAggregated": true,+ "geoms": [+ "bar"+ ],+ "coordSystem": "generic",+ "limit": 10,+ "folds": [],+ "timezoneDisplayOffset": -480+ },+ "encodings": {+ "dimensions": [+ {+ "fid": "region",+ "name": "Region",+ "basename": "Region",+ "semanticType": "nominal",+ "analyticType": "dimension"+ },+ {+ "fid": "order_date",+ "name": "Order Date",+ "basename": "Order Date",+ "semanticType": "temporal",+ "analyticType": "dimension"+ },+ {+ "fid": "segment",+ "name": "Segment",+ "basename": "Segment",+ "semanticType": "nominal",+ "analyticType": "dimension"+ }+ ],+ "measures": [+ {+ "fid": "sales",+ "name": "Sales",+ "basename": "Sales",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "sum"+ },+ {+ "fid": "profit",+ "name": "Profit",+ "basename": "Profit",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "mean"+ },+ {+ "fid": "gw_log1",+ "name": "log10(Sales)",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "sum",+ "computed": true,+ "expression": {+ "op": "log10",+ "as": "gw_log1",+ "params": [+ {+ "type": "field",+ "value": "sales"+ }+ ]+ }+ }+ ],+ "rows": [+ {+ "fid": "sales",+ "name": "Sales",+ "basename": "Sales",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "sum"+ },+ {+ "fid": "profit",+ "name": "Profit",+ "basename": "Profit",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "mean"+ }+ ],+ "columns": [+ {+ "fid": "region",+ "name": "Region",+ "basename": "Region",+ "semanticType": "nominal",+ "analyticType": "dimension"+ },+ {+ "fid": "order_date",+ "name": "Order Date",+ "basename": "Order Date",+ "semanticType": "temporal",+ "analyticType": "dimension",+ "timeUnit": "month"+ }+ ],+ "color": [+ {+ "fid": "segment",+ "name": "Segment",+ "basename": "Segment",+ "semanticType": "nominal",+ "analyticType": "dimension"+ }+ ],+ "opacity": [],+ "size": [+ {+ "fid": "gw_log1",+ "name": "log10(Sales)",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "sum",+ "computed": true,+ "expression": {+ "op": "log10",+ "as": "gw_log1",+ "params": [+ {+ "type": "field",+ "value": "sales"+ }+ ]+ }+ }+ ],+ "shape": [],+ "radius": [],+ "theta": [],+ "longitude": [],+ "latitude": [],+ "geoId": [],+ "details": [+ {+ "fid": "order_date",+ "name": "Order Date",+ "basename": "Order Date",+ "semanticType": "temporal",+ "analyticType": "dimension"+ }+ ],+ "filters": [+ {+ "fid": "profit",+ "name": "Profit",+ "basename": "Profit",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "sum",+ "enableAgg": true,+ "rule": {+ "type": "range",+ "value": [+ 0,+ 10000+ ]+ }+ }+ ],+ "text": []+ },+ "layout": {+ "showActions": true,+ "showTableSummary": false,+ "stack": "stack",+ "interactiveScale": true,+ "zeroScale": false,+ "background": "#fafafa",+ "size": {+ "mode": "full",+ "width": 320,+ "height": 200+ },+ "format": {+ "numberFormat": ",.0f",+ "timeFormat": "%Y-%m-%d"+ },+ "geoKey": "name",+ "resolve": {+ "x": false,+ "y": true,+ "color": false,+ "opacity": false,+ "shape": false,+ "size": false+ },+ "renderer": "observable-plot",+ "primaryColor": "#e15759",+ "colorPalette": "category10",+ "useSvg": false,+ "scale": {+ "size": {+ "rangeMin": 4,+ "rangeMax": 36+ }+ }+ },+ "visId": "gw-fixture-modern",+ "name": "Complex Modern Chart",+ "$schema": "https://graphic-walker.kanaries.net/chartinfo.json"+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/chart-current-complex.input.json b/packages/graphic-walker/tests/fixtures/spec-compat/chart-current-complex.input.jsonnew file mode 100644index 00000000..656e7ccf--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/chart-current-complex.input.json@@ -0,0 +1,82 @@+{+ "visId": "gw-fixture-modern",+ "name": "Complex Modern Chart",+ "encodings": {+ "dimensions": [+ { "fid": "region", "name": "Region", "basename": "Region", "semanticType": "nominal", "analyticType": "dimension" },+ { "fid": "order_date", "name": "Order Date", "basename": "Order Date", "semanticType": "temporal", "analyticType": "dimension" },+ { "fid": "segment", "name": "Segment", "basename": "Segment", "semanticType": "nominal", "analyticType": "dimension" }+ ],+ "measures": [+ { "fid": "sales", "name": "Sales", "basename": "Sales", "analyticType": "measure", "semanticType": "quantitative", "aggName": "sum" },+ { "fid": "profit", "name": "Profit", "basename": "Profit", "analyticType": "measure", "semanticType": "quantitative", "aggName": "mean" },+ {+ "fid": "gw_log1",+ "name": "log10(Sales)",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "sum",+ "computed": true,+ "expression": { "op": "log10", "as": "gw_log1", "params": [{ "type": "field", "value": "sales" }] }+ }+ ],+ "rows": [+ { "fid": "sales", "name": "Sales", "basename": "Sales", "analyticType": "measure", "semanticType": "quantitative", "aggName": "sum" },+ { "fid": "profit", "name": "Profit", "basename": "Profit", "analyticType": "measure", "semanticType": "quantitative", "aggName": "mean" }+ ],+ "columns": [+ { "fid": "region", "name": "Region", "basename": "Region", "semanticType": "nominal", "analyticType": "dimension" },+ { "fid": "order_date", "name": "Order Date", "basename": "Order Date", "semanticType": "temporal", "analyticType": "dimension", "timeUnit": "month" }+ ],+ "color": [{ "fid": "segment", "name": "Segment", "basename": "Segment", "semanticType": "nominal", "analyticType": "dimension" }],+ "opacity": [],+ "size": [+ { "fid": "gw_log1", "name": "log10(Sales)", "analyticType": "measure", "semanticType": "quantitative", "aggName": "sum", "computed": true, "expression": { "op": "log10", "as": "gw_log1", "params": [{ "type": "field", "value": "sales" }] } }+ ],+ "shape": [],+ "radius": [],+ "theta": [],+ "longitude": [],+ "latitude": [],+ "geoId": [],+ "details": [{ "fid": "order_date", "name": "Order Date", "basename": "Order Date", "semanticType": "temporal", "analyticType": "dimension" }],+ "filters": [+ {+ "fid": "profit",+ "name": "Profit",+ "basename": "Profit",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "sum",+ "enableAgg": true,+ "rule": { "type": "range", "value": [0, 10000] }+ }+ ],+ "text": []+ },+ "config": {+ "defaultAggregated": true,+ "geoms": ["bar"],+ "coordSystem": "generic",+ "limit": 10,+ "folds": [],+ "timezoneDisplayOffset": -480+ },+ "layout": {+ "showTableSummary": false,+ "format": { "numberFormat": ",.0f", "timeFormat": "%Y-%m-%d" },+ "resolve": { "x": false, "y": true, "color": false, "opacity": false, "shape": false, "size": false },+ "size": { "mode": "full", "width": 320, "height": 200 },+ "interactiveScale": true,+ "stack": "stack",+ "showActions": true,+ "zeroScale": false,+ "background": "#fafafa",+ "primaryColor": "#e15759",+ "colorPalette": "category10",+ "useSvg": false,+ "renderer": "observable-plot",+ "scale": { "size": { "rangeMin": 4, "rangeMax": 36 } },+ "geoKey": "name"+ }+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/chart-geographic.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/chart-geographic.expected.jsonnew file mode 100644index 00000000..5e593706--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/chart-geographic.expected.json@@ -0,0 +1,112 @@+{+ "config": {+ "defaultAggregated": false,+ "geoms": [+ "poi"+ ],+ "coordSystem": "geographic",+ "limit": -1+ },+ "encodings": {+ "dimensions": [+ {+ "fid": "store",+ "name": "Store",+ "semanticType": "nominal",+ "analyticType": "dimension"+ }+ ],+ "measures": [+ {+ "fid": "lng",+ "name": "Longitude",+ "semanticType": "quantitative",+ "analyticType": "measure",+ "aggName": "sum"+ },+ {+ "fid": "lat",+ "name": "Latitude",+ "semanticType": "quantitative",+ "analyticType": "measure",+ "aggName": "sum"+ },+ {+ "fid": "revenue",+ "name": "Revenue",+ "semanticType": "quantitative",+ "analyticType": "measure",+ "aggName": "sum"+ }+ ],+ "rows": [],+ "columns": [],+ "color": [],+ "opacity": [],+ "size": [+ {+ "fid": "revenue",+ "name": "Revenue",+ "semanticType": "quantitative",+ "analyticType": "measure",+ "aggName": "sum"+ }+ ],+ "shape": [],+ "radius": [],+ "theta": [],+ "longitude": [+ {+ "fid": "lng",+ "name": "Longitude",+ "semanticType": "quantitative",+ "analyticType": "dimension",+ "aggName": "sum"+ }+ ],+ "latitude": [+ {+ "fid": "lat",+ "name": "Latitude",+ "semanticType": "quantitative",+ "analyticType": "dimension",+ "aggName": "sum"+ }+ ],+ "geoId": [],+ "details": [+ {+ "fid": "store",+ "name": "Store",+ "semanticType": "nominal",+ "analyticType": "dimension"+ }+ ],+ "filters": [],+ "text": []+ },+ "layout": {+ "showActions": false,+ "showTableSummary": false,+ "stack": "stack",+ "interactiveScale": false,+ "zeroScale": true,+ "size": {+ "mode": "auto",+ "width": 320,+ "height": 200+ },+ "format": {},+ "geoKey": "name",+ "resolve": {},+ "renderer": "vega-lite",+ "geoUrl": {+ "type": "GeoJSON",+ "url": "https://example.com/regions.geo.json"+ },+ "geoMapTileUrl": "https://tile.example.com/{z}/{x}/{y}.png"+ },+ "visId": "gw-fixture-geo",+ "name": "Store Locations",+ "$schema": "https://graphic-walker.kanaries.net/chartinfo.json"+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/chart-geographic.input.json b/packages/graphic-walker/tests/fixtures/spec-compat/chart-geographic.input.jsonnew file mode 100644index 00000000..e31c7185--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/chart-geographic.input.json@@ -0,0 +1,45 @@+{+ "visId": "gw-fixture-geo",+ "name": "Store Locations",+ "encodings": {+ "dimensions": [{ "fid": "store", "name": "Store", "semanticType": "nominal", "analyticType": "dimension" }],+ "measures": [+ { "fid": "lng", "name": "Longitude", "semanticType": "quantitative", "analyticType": "measure", "aggName": "sum" },+ { "fid": "lat", "name": "Latitude", "semanticType": "quantitative", "analyticType": "measure", "aggName": "sum" },+ { "fid": "revenue", "name": "Revenue", "semanticType": "quantitative", "analyticType": "measure", "aggName": "sum" }+ ],+ "rows": [],+ "columns": [],+ "color": [],+ "opacity": [],+ "size": [{ "fid": "revenue", "name": "Revenue", "semanticType": "quantitative", "analyticType": "measure", "aggName": "sum" }],+ "shape": [],+ "radius": [],+ "theta": [],+ "longitude": [{ "fid": "lng", "name": "Longitude", "semanticType": "quantitative", "analyticType": "measure", "aggName": "sum" }],+ "latitude": [{ "fid": "lat", "name": "Latitude", "semanticType": "quantitative", "analyticType": "measure", "aggName": "sum" }],+ "geoId": [],+ "details": [{ "fid": "store", "name": "Store", "semanticType": "nominal", "analyticType": "dimension" }],+ "filters": [],+ "text": []+ },+ "config": {+ "defaultAggregated": false,+ "geoms": ["poi"],+ "coordSystem": "geographic",+ "limit": -1+ },+ "layout": {+ "showTableSummary": false,+ "format": {},+ "resolve": {},+ "size": { "mode": "auto", "width": 320, "height": 200 },+ "interactiveScale": false,+ "stack": "stack",+ "showActions": false,+ "zeroScale": true,+ "geoKey": "name",+ "geoUrl": { "type": "GeoJSON", "url": "https://example.com/regions.geo.json" },+ "geoMapTileUrl": "https://tile.example.com/{z}/{x}/{y}.png"+ }+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/partial-minimal.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/partial-minimal.expected.jsonnew file mode 100644index 00000000..3d52fed6--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/partial-minimal.expected.json@@ -0,0 +1,69 @@+{+ "config": {+ "defaultAggregated": true,+ "geoms": [+ "auto"+ ],+ "coordSystem": "generic",+ "limit": -1+ },+ "encodings": {+ "dimensions": [],+ "measures": [],+ "rows": [+ {+ "fid": "sales",+ "name": "Sales",+ "semanticType": "quantitative",+ "analyticType": "measure",+ "aggName": "sum"+ }+ ],+ "columns": [+ {+ "fid": "category",+ "name": "Category",+ "semanticType": "nominal",+ "analyticType": "dimension"+ }+ ],+ "color": [],+ "opacity": [],+ "size": [],+ "shape": [],+ "radius": [],+ "theta": [],+ "longitude": [],+ "latitude": [],+ "geoId": [],+ "details": [],+ "filters": [],+ "text": []+ },+ "layout": {+ "showActions": false,+ "showTableSummary": false,+ "stack": "stack",+ "interactiveScale": false,+ "zeroScale": true,+ "size": {+ "mode": "auto",+ "width": 320,+ "height": 200+ },+ "format": {},+ "geoKey": "name",+ "resolve": {+ "x": false,+ "y": false,+ "color": false,+ "opacity": false,+ "shape": false,+ "size": false+ },+ "renderer": "vega-lite"+ },+ "visId": "gw_mock-id",+ "name": "Chart",+ "$schema": "https://graphic-walker.kanaries.net/chartinfo.json"+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/partial-minimal.input.json b/packages/graphic-walker/tests/fixtures/spec-compat/partial-minimal.input.jsonnew file mode 100644index 00000000..38fce35c--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/partial-minimal.input.json@@ -0,0 +1,6 @@+{+ "encodings": {+ "columns": [{ "fid": "category", "name": "Category", "semanticType": "nominal", "analyticType": "dimension" }],+ "rows": [{ "fid": "sales", "name": "Sales", "semanticType": "quantitative", "analyticType": "measure", "aggName": "sum" }]+ }+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/special-chars.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/special-chars.expected.jsonnew file mode 100644index 00000000..50ed140a--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/special-chars.expected.json@@ -0,0 +1,83 @@+{+ "config": {+ "defaultAggregated": true,+ "geoms": [+ "bar"+ ],+ "coordSystem": "generic",+ "limit": -1+ },+ "encodings": {+ "dimensions": [],+ "measures": [],+ "rows": [+ {+ "fid": "销售额 \"净\"",+ "name": "销售额 \"净\"",+ "semanticType": "quantitative",+ "analyticType": "measure",+ "aggName": "sum"+ }+ ],+ "columns": [+ {+ "fid": "Price (USD)",+ "name": "Price (USD)",+ "semanticType": "nominal",+ "analyticType": "dimension"+ }+ ],+ "color": [],+ "opacity": [],+ "size": [],+ "shape": [],+ "radius": [],+ "theta": [],+ "longitude": [],+ "latitude": [],+ "geoId": [],+ "details": [],+ "filters": [+ {+ "fid": "Price (USD)",+ "name": "Price (USD)",+ "semanticType": "nominal",+ "analyticType": "dimension",+ "rule": {+ "type": "one of",+ "value": [+ "$1.00",+ "a'b\\c"+ ]+ }+ }+ ],+ "text": []+ },+ "layout": {+ "showActions": false,+ "showTableSummary": false,+ "stack": "stack",+ "interactiveScale": false,+ "zeroScale": true,+ "size": {+ "mode": "auto",+ "width": 320,+ "height": 200+ },+ "format": {},+ "geoKey": "name",+ "resolve": {+ "x": false,+ "y": false,+ "color": false,+ "opacity": false,+ "shape": false,+ "size": false+ },+ "renderer": "vega-lite"+ },+ "visId": "gw-fixture-special",+ "name": "特殊字符 \"图表\"",+ "$schema": "https://graphic-walker.kanaries.net/chartinfo.json"+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/special-chars.input.json b/packages/graphic-walker/tests/fixtures/spec-compat/special-chars.input.jsonnew file mode 100644index 00000000..a6aae07c--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/special-chars.input.json@@ -0,0 +1,24 @@+{+ "visId": "gw-fixture-special",+ "name": "特殊字符 \"图表\"",+ "encodings": {+ "columns": [{ "fid": "Price (USD)", "name": "Price (USD)", "semanticType": "nominal", "analyticType": "dimension" }],+ "rows": [+ { "fid": "销售额 \"净\"", "name": "销售额 \"净\"", "semanticType": "quantitative", "analyticType": "measure", "aggName": "sum" }+ ],+ "filters": [+ {+ "fid": "Price (USD)",+ "name": "Price (USD)",+ "semanticType": "nominal",+ "analyticType": "dimension",+ "rule": { "type": "one of", "value": ["$1.00", "a'b\\c"] }+ }+ ]+ },+ "config": {+ "defaultAggregated": true,+ "geoms": ["bar"],+ "limit": -1+ }+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-old.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-old.expected.jsonnew file mode 100644index 00000000..78164b66--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-old.expected.json@@ -0,0 +1,81 @@+{+ "metaDict": {+ "meta-sales": [+ {+ "fid": "category",+ "name": "Category",+ "semanticType": "nominal",+ "analyticType": "dimension"+ },+ {+ "fid": "sales",+ "name": "Sales",+ "semanticType": "quantitative",+ "analyticType": "measure"+ }+ ]+ },+ "dataSources": [+ {+ "data": [+ {+ "category": "A",+ "sales": 10+ },+ {+ "category": "B",+ "sales": 20+ }+ ],+ "id": "src-sales",+ "metaId": "meta-sales",+ "name": "Sales Dataset"+ }+ ],+ "visDict": {+ "meta-sales": [+ "{\"base\":{\"config\":{\"defaultAggregated\":true,\"geoms\":[\"bar\"],\"coordSystem\":\"generic\",\"limit\":-1},\"encodings\":{\"dimensions\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"measures\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"rows\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"columns\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"color\":[],\"opacity\":[],\"size\":[],\"shape\":[],\"radius\":[],\"theta\":[],\"longitude\":[],\"latitude\":[],\"geoId\":[],\"details\":[],\"filters\":[],\"text\":[]},\"layout\":{\"showActions\":false,\"showTableSummary\":false,\"stack\":\"stack\",\"interactiveScale\":false,\"zeroScale\":true,\"size\":{\"mode\":\"auto\",\"width\":320,\"height\":200},\"format\":{},\"geoKey\":\"name\",\"resolve\":{\"x\":false,\"y\":false,\"color\":false,\"opacity\":false,\"shape\":false,\"size\":false},\"renderer\":\"vega-lite\",\"scaleIncludeUnmatchedChoropleth\":false},\"visId\":\"gw-old-app-chart\",\"name\":\"Chart 1\"},\"timeline\":[]}"+ ]+ },+ "exportData": {+ "$schema": "https://graphic-walker.kanaries.net/stoinfo_v2.json",+ "datasets": [+ {+ "data": [+ {+ "category": "A",+ "sales": 10+ },+ {+ "category": "B",+ "sales": 20+ }+ ],+ "id": "src-sales",+ "metaId": "meta-sales",+ "name": "Sales Dataset"+ }+ ],+ "metaDict": {+ "meta-sales": [+ {+ "fid": "category",+ "name": "Category",+ "semanticType": "nominal",+ "analyticType": "dimension"+ },+ {+ "fid": "sales",+ "name": "Sales",+ "semanticType": "quantitative",+ "analyticType": "measure"+ }+ ]+ },+ "specDict": {+ "meta-sales": [+ "{\"base\":{\"config\":{\"defaultAggregated\":true,\"geoms\":[\"bar\"],\"coordSystem\":\"generic\",\"limit\":-1},\"encodings\":{\"dimensions\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"measures\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"rows\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"columns\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"color\":[],\"opacity\":[],\"size\":[],\"shape\":[],\"radius\":[],\"theta\":[],\"longitude\":[],\"latitude\":[],\"geoId\":[],\"details\":[],\"filters\":[],\"text\":[]},\"layout\":{\"showActions\":false,\"showTableSummary\":false,\"stack\":\"stack\",\"interactiveScale\":false,\"zeroScale\":true,\"size\":{\"mode\":\"auto\",\"width\":320,\"height\":200},\"format\":{},\"geoKey\":\"name\",\"resolve\":{\"x\":false,\"y\":false,\"color\":false,\"opacity\":false,\"shape\":false,\"size\":false},\"renderer\":\"vega-lite\",\"scaleIncludeUnmatchedChoropleth\":false},\"visId\":\"gw-old-app-chart\",\"name\":\"Chart 1\"},\"timeline\":[]}"+ ]+ }+ }+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-old.input.json b/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-old.input.jsonnew file mode 100644index 00000000..ddad2afd--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-old.input.json@@ -0,0 +1,41 @@+{+ "datasets": [+ {+ "id": "meta-sales",+ "name": "Sales Dataset",+ "dsId": "src-sales",+ "rawFields": [+ { "fid": "category", "name": "Category", "semanticType": "nominal", "analyticType": "dimension" },+ { "fid": "sales", "name": "Sales", "semanticType": "quantitative", "analyticType": "measure" }+ ]+ }+ ],+ "dataSources": [+ {+ "id": "src-sales",+ "data": [+ { "category": "A", "sales": 10 },+ { "category": "B", "sales": 20 }+ ]+ }+ ],+ "specList": [+ {+ "visId": "gw-old-app-chart",+ "name": "Chart 1",+ "encodings": {+ "dimensions": [{ "fid": "category", "name": "Category", "semanticType": "nominal", "analyticType": "dimension" }],+ "measures": [{ "fid": "sales", "name": "Sales", "semanticType": "quantitative", "analyticType": "measure", "aggName": "sum" }],+ "rows": [{ "fid": "sales", "name": "Sales", "semanticType": "quantitative", "analyticType": "measure", "aggName": "sum" }],+ "columns": [{ "fid": "category", "name": "Category", "semanticType": "nominal", "analyticType": "dimension" }]+ },+ "config": {+ "defaultAggregated": true,+ "geoms": ["bar"],+ "stack": "stack",+ "showTableSummary": false,+ "limit": -1+ }+ }+ ]+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-v2.input.json b/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-v2.input.jsonnew file mode 100644index 00000000..9c926b70--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-v2.input.json@@ -0,0 +1,41 @@+{+ "$schema": "https://graphic-walker.kanaries.net/stoinfo_v2.json",+ "datasets": [+ {+ "data": [+ {+ "category": "A",+ "sales": 10+ },+ {+ "category": "B",+ "sales": 20+ }+ ],+ "id": "src-sales",+ "metaId": "meta-sales",+ "name": "Sales Dataset"+ }+ ],+ "metaDict": {+ "meta-sales": [+ {+ "fid": "category",+ "name": "Category",+ "semanticType": "nominal",+ "analyticType": "dimension"+ },+ {+ "fid": "sales",+ "name": "Sales",+ "semanticType": "quantitative",+ "analyticType": "measure"+ }+ ]+ },+ "specDict": {+ "meta-sales": [+ "{\"base\":{\"config\":{\"defaultAggregated\":true,\"geoms\":[\"bar\"],\"coordSystem\":\"generic\",\"limit\":-1},\"encodings\":{\"dimensions\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"measures\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"rows\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"columns\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"color\":[],\"opacity\":[],\"size\":[],\"shape\":[],\"radius\":[],\"theta\":[],\"longitude\":[],\"latitude\":[],\"geoId\":[],\"details\":[],\"filters\":[],\"text\":[]},\"layout\":{\"showActions\":false,\"showTableSummary\":false,\"stack\":\"stack\",\"interactiveScale\":false,\"zeroScale\":true,\"size\":{\"mode\":\"auto\",\"width\":320,\"height\":200},\"format\":{},\"geoKey\":\"name\",\"resolve\":{\"x\":false,\"y\":false,\"color\":false,\"opacity\":false,\"shape\":false,\"size\":false},\"renderer\":\"vega-lite\",\"scaleIncludeUnmatchedChoropleth\":false},\"visId\":\"gw-old-app-chart\",\"name\":\"Chart 1\"},\"timeline\":[]}"+ ]+ }+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-full.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-full.expected.jsonnew file mode 100644index 00000000..7c5209de--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-full.expected.json@@ -0,0 +1,177 @@+{+ "config": {+ "defaultAggregated": true,+ "geoms": [+ "bar"+ ],+ "coordSystem": "generic",+ "limit": 30,+ "folds": [+ "sales",+ "profit"+ ]+ },+ "encodings": {+ "dimensions": [+ {+ "fid": "region",+ "name": "Region",+ "basename": "Region",+ "semanticType": "nominal",+ "analyticType": "dimension"+ },+ {+ "fid": "order_date",+ "name": "Order Date",+ "basename": "Order Date",+ "semanticType": "temporal",+ "analyticType": "dimension"+ },+ {+ "fid": "gw_bin4",+ "name": "bin(Profit)",+ "semanticType": "ordinal",+ "analyticType": "dimension",+ "computed": true,+ "expression": {+ "op": "bin",+ "as": "gw_bin4",+ "params": [+ {+ "type": "field",+ "value": "profit"+ }+ ]+ }+ }+ ],+ "measures": [+ {+ "fid": "sales",+ "name": "Sales",+ "basename": "Sales",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "sum"+ },+ {+ "fid": "profit",+ "name": "Profit",+ "basename": "Profit",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "sum"+ },+ {+ "fid": "gw_count_fid",+ "name": "Row count",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "sum",+ "computed": true,+ "expression": {+ "op": "one",+ "params": [],+ "as": "gw_count_fid"+ }+ }+ ],+ "rows": [+ {+ "fid": "sales",+ "name": "Sales",+ "basename": "Sales",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "sum"+ }+ ],+ "columns": [+ {+ "fid": "region",+ "name": "Region",+ "basename": "Region",+ "semanticType": "nominal",+ "analyticType": "dimension"+ }+ ],+ "color": [+ {+ "fid": "gw_bin4",+ "name": "bin(Profit)",+ "semanticType": "ordinal",+ "analyticType": "dimension",+ "computed": true,+ "expression": {+ "op": "bin",+ "as": "gw_bin4",+ "params": [+ {+ "type": "field",+ "value": "profit"+ }+ ]+ }+ }+ ],+ "opacity": [],+ "size": [],+ "shape": [],+ "radius": [],+ "theta": [],+ "longitude": [],+ "latitude": [],+ "geoId": [],+ "details": [],+ "filters": [+ {+ "fid": "region",+ "name": "Region",+ "basename": "Region",+ "semanticType": "nominal",+ "analyticType": "dimension",+ "rule": {+ "type": "one of",+ "value": [+ "East",+ "West"+ ]+ }+ }+ ],+ "text": []+ },+ "layout": {+ "showActions": false,+ "showTableSummary": false,+ "stack": "normalize",+ "interactiveScale": false,+ "zeroScale": true,+ "background": "#ffffff",+ "size": {+ "mode": "fixed",+ "width": 640,+ "height": 480+ },+ "format": {+ "numberFormat": ",.2f"+ },+ "geoKey": "name",+ "resolve": {+ "x": false,+ "y": false,+ "color": false,+ "opacity": false,+ "shape": false,+ "size": false+ },+ "renderer": "vega-lite",+ "colorPalette": "tableau10",+ "primaryColor": "#4e79a7",+ "scaleIncludeUnmatchedChoropleth": false,+ "useSvg": true+ },+ "visId": "gw-fixture-old-full",+ "name": "Sales by Region",+ "$schema": "https://graphic-walker.kanaries.net/chartinfo.json"+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-full.input.json b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-full.input.jsonnew file mode 100644index 00000000..ad24afe7--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-full.input.json@@ -0,0 +1,80 @@+{+ "visId": "gw-fixture-old-full",+ "name": "Sales by Region",+ "encodings": {+ "dimensions": [+ { "fid": "region", "name": "Region", "basename": "Region", "semanticType": "nominal", "analyticType": "dimension" },+ { "fid": "order_date", "name": "Order Date", "basename": "Order Date", "semanticType": "temporal", "analyticType": "dimension" },+ {+ "fid": "gw_bin4",+ "name": "bin(Profit)",+ "semanticType": "ordinal",+ "analyticType": "dimension",+ "computed": true,+ "expression": { "op": "bin", "as": "gw_bin4", "params": [{ "type": "field", "value": "profit" }] }+ }+ ],+ "measures": [+ { "fid": "sales", "name": "Sales", "basename": "Sales", "analyticType": "measure", "semanticType": "quantitative", "aggName": "sum" },+ { "fid": "profit", "name": "Profit", "basename": "Profit", "analyticType": "measure", "semanticType": "quantitative", "aggName": "sum" },+ {+ "fid": "gw_count_fid",+ "name": "Row count",+ "analyticType": "measure",+ "semanticType": "quantitative",+ "aggName": "sum",+ "computed": true,+ "expression": { "op": "one", "params": [], "as": "gw_count_fid" }+ }+ ],+ "rows": [+ { "fid": "sales", "name": "Sales", "basename": "Sales", "analyticType": "measure", "semanticType": "quantitative", "aggName": "sum" }+ ],+ "columns": [{ "fid": "region", "name": "Region", "basename": "Region", "semanticType": "nominal", "analyticType": "dimension" }],+ "color": [+ { "fid": "gw_bin4", "name": "bin(Profit)", "semanticType": "ordinal", "analyticType": "dimension", "computed": true, "expression": { "op": "bin", "as": "gw_bin4", "params": [{ "type": "field", "value": "profit" }] } }+ ],+ "opacity": [],+ "size": [],+ "shape": [],+ "radius": [],+ "theta": [],+ "longitude": [],+ "latitude": [],+ "geoId": [],+ "details": [],+ "filters": [+ {+ "fid": "region",+ "name": "Region",+ "basename": "Region",+ "semanticType": "nominal",+ "analyticType": "dimension",+ "rule": { "type": "one of", "value": ["East", "West"] }+ }+ ],+ "text": []+ },+ "config": {+ "defaultAggregated": true,+ "geoms": ["bar"],+ "showTableSummary": false,+ "coordSystem": "generic",+ "stack": "normalize",+ "showActions": false,+ "interactiveScale": false,+ "sorted": "none",+ "zeroScale": true,+ "scaleIncludeUnmatchedChoropleth": false,+ "size": { "mode": "fixed", "width": 640, "height": 480 },+ "format": { "numberFormat": ",.2f" },+ "geoKey": "name",+ "resolve": { "x": false, "y": false, "color": false, "opacity": false, "shape": false, "size": false },+ "limit": 30,+ "folds": ["sales", "profit"],+ "background": "#ffffff",+ "useSvg": true,+ "primaryColor": "#4e79a7",+ "colorPalette": "tableau10"+ }+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-sparse.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-sparse.expected.jsonnew file mode 100644index 00000000..d7fbad3b--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-sparse.expected.json@@ -0,0 +1,70 @@+{+ "config": {+ "defaultAggregated": false,+ "geoms": [+ "line"+ ],+ "coordSystem": "generic",+ "limit": -1+ },+ "encodings": {+ "dimensions": [+ {+ "fid": "category",+ "name": "Category",+ "semanticType": "nominal",+ "analyticType": "dimension"+ }+ ],+ "measures": [],+ "rows": [+ {+ "fid": "sales",+ "name": "Sales",+ "semanticType": "quantitative",+ "analyticType": "measure",+ "aggName": "mean"+ }+ ],+ "columns": [],+ "color": [],+ "opacity": [],+ "size": [],+ "shape": [],+ "radius": [],+ "theta": [],+ "longitude": [],+ "latitude": [],+ "geoId": [],+ "details": [],+ "filters": [],+ "text": []+ },+ "layout": {+ "showActions": false,+ "showTableSummary": false,+ "stack": "stack",+ "interactiveScale": false,+ "zeroScale": true,+ "size": {+ "mode": "auto",+ "width": 320,+ "height": 200+ },+ "format": {},+ "geoKey": "name",+ "resolve": {+ "x": false,+ "y": false,+ "color": false,+ "opacity": false,+ "shape": false,+ "size": false+ },+ "renderer": "vega-lite",+ "scaleIncludeUnmatchedChoropleth": false+ },+ "visId": "gw-fixture-old-sparse",+ "name": "Chart",+ "$schema": "https://graphic-walker.kanaries.net/chartinfo.json"+}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-sparse.input.json b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-sparse.input.jsonnew file mode 100644index 00000000..93dbca51--- /dev/null+++ b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-sparse.input.json@@ -0,0 +1,12 @@+{+ "visId": "gw-fixture-old-sparse",+ "encodings": {+ "dimensions": [{ "fid": "category", "name": "Category", "semanticType": "nominal", "analyticType": "dimension" }],+ "rows": [{ "fid": "sales", "name": "Sales", "semanticType": "quantitative", "analyticType": "measure", "aggName": "mean" }]+ },+ "config": {+ "defaultAggregated": false,+ "geoms": ["line"],+ "stack": "stack"+ }+}diff --git a/packages/graphic-walker/tests/specCompat.test.ts b/packages/graphic-walker/tests/specCompat.test.tsnew file mode 100644index 00000000..9698ece3--- /dev/null+++ b/packages/graphic-walker/tests/specCompat.test.ts@@ -0,0 +1,71 @@+/**+ * Spec compatibility contract tests.+ *+ * Every fixture pair under tests/fixtures/spec-compat/ is a persistence-compatibility+ * contract: the *.input.json files replay spec shapes as persisted by current and past+ * releases, and the *.expected.json files are explicitly committed, hand-verified+ * canonical outputs. If a change to the spec pipeline breaks any of these assertions,+ * it breaks previously persisted user charts — fix the change, not the fixture,+ * unless a migration path is added deliberately.+ */+jest.mock('nanoid', () => ({ nanoid: () => 'mock-id' }));++import fs from 'fs';+import path from 'path';+import { normalize } from '../src/models/normalize';+import { chartToWorkflow } from '../src/utils/workflow';+import { resolveChart } from '../src/models/visSpecHistory';+import { DataStore } from '../src/store/dataStore';++const DIR = path.join(__dirname, 'fixtures', 'spec-compat');+const read = (name: string) => JSON.parse(fs.readFileSync(path.join(DIR, name), 'utf8'));++const CHART_FIXTURES = ['visspec-old-full', 'visspec-old-sparse', 'chart-current-complex', 'chart-geographic', 'partial-minimal', 'special-chars'];++describe.each(CHART_FIXTURES)('chart fixture: %s', (name) => {+ const input = read(`${name}.input.json`);+ const expected = read(`${name}.expected.json`);++ test('normalize matches the committed expected output', () => {+ expect(normalize(input)).toEqual(expected);+ });++ test('normalize is idempotent on the expected output', () => {+ expect(normalize(expected)).toEqual(expected);+ });++ test('normalized output feeds toWorkflow without throwing', () => {+ const payload = chartToWorkflow(normalize(input));+ expect(Array.isArray(payload.workflow)).toBe(true);+ });+});++describe('app-level store import compatibility', () => {+ test('legacy IStoInfoOld import produces the committed store state', () => {+ const store = new DataStore();+ store.importData(read('stoinfo-old.input.json'));+ const expected = read('stoinfo-old.expected.json');+ expect(store.metaDict).toEqual(expected.metaDict);+ expect(store.dataSources).toEqual(expected.dataSources);+ expect(store.visDict).toEqual(expected.visDict);+ expect(store.exportData()).toEqual(expected.exportData);+ });++ test('every chart stored by the legacy import resolves and feeds toWorkflow', () => {+ const expected = read('stoinfo-old.expected.json');+ for (const specs of Object.values(expected.visDict) as string[][]) {+ for (const raw of specs) {+ const chart = resolveChart(raw);+ const payload = chartToWorkflow(chart);+ expect(Array.isArray(payload.workflow)).toBe(true);+ }+ }+ });++ test('IStoInfoV2 import/export round trip is identity', () => {+ const input = read('stoinfo-v2.input.json');+ const store = new DataStore();+ store.importData(input);+ expect(store.exportData()).toEqual(input);+ });+});