@tano.page/protocol 0.0.0-stage → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,329 @@
1
+ import type { DataAggregate, DataField, DataRow, DataTable, DataValue, DataView } from './data-tables';
2
+ type Token = { kind: 'number' | 'string' | 'field' | 'word' | 'symbol'; value: string };
3
+ type Expression =
4
+ | { kind: 'literal'; value: DataValue }
5
+ | { kind: 'field'; id: string }
6
+ | { kind: 'unary'; op: string; child: Expression }
7
+ | { kind: 'binary'; op: string; left: Expression; right: Expression }
8
+ | { kind: 'call'; name: string; args: Expression[] };
9
+ function tokenize(source: string): Token[] {
10
+ if (source.length > 4000) throw new Error('公式过长');
11
+ const tokens: Token[] = [];
12
+ let rest = source.trim().replace(/^=/, '');
13
+ while (rest.trim()) {
14
+ rest = rest.trimStart();
15
+ const match =
16
+ /^(\d+(?:\.\d*)?|\.\d+)|^("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')|^\[([^\]\r\n]+)\]|^([a-zA-Z_][a-zA-Z_0-9]*)|^(>=|<=|!=|==|<>|[+*/(),=<>-])/.exec(
17
+ rest,
18
+ );
19
+ if (!match) throw new Error(`无法识别:${rest.slice(0, 16)}`);
20
+ tokens.push({
21
+ kind: match[1]
22
+ ? 'number'
23
+ : match[2]
24
+ ? 'string'
25
+ : match[3]
26
+ ? 'field'
27
+ : match[4]
28
+ ? 'word'
29
+ : 'symbol',
30
+ value: match[3] ?? match[0],
31
+ });
32
+ rest = rest.slice(match[0].length);
33
+ if (tokens.length > 600) throw new Error('公式过于复杂');
34
+ }
35
+ return tokens;
36
+ }
37
+ const precedence: Record<string, number> = {
38
+ '=': 1,
39
+ '==': 1,
40
+ '!=': 1,
41
+ '<>': 1,
42
+ '>': 1,
43
+ '<': 1,
44
+ '>=': 1,
45
+ '<=': 1,
46
+ '+': 2,
47
+ '-': 2,
48
+ '*': 3,
49
+ '/': 3,
50
+ };
51
+ function parseFormula(source: string, fields: DataField[]): Expression {
52
+ const tokens = tokenize(source);
53
+ let at = 0;
54
+ const take = (value: string) => {
55
+ if (tokens[at]?.value === value) {
56
+ at++;
57
+ return true;
58
+ }
59
+ return false;
60
+ };
61
+ const require = (value: string) => {
62
+ if (!take(value)) throw new Error(`缺少 ${value}`);
63
+ };
64
+ function expression(min = 0, depth = 0): Expression {
65
+ if (depth > 60) throw new Error('公式嵌套过深');
66
+ const token = tokens[at++];
67
+ if (!token) throw new Error('公式不完整');
68
+ let left: Expression;
69
+ if (token.kind === 'number') left = { kind: 'literal', value: Number(token.value) };
70
+ else if (token.kind === 'string')
71
+ left = { kind: 'literal', value: token.value.slice(1, -1).replace(/\\([\\"'])/g, '$1') };
72
+ else if (token.kind === 'field') {
73
+ const field =
74
+ fields.find((field) => field.id === token.value) ??
75
+ fields.find((field) => field.name === token.value);
76
+ if (!field) throw new Error(`字段不存在:${token.value}`);
77
+ left = { kind: 'field', id: field.id };
78
+ } else if (token.value === '-' || token.value === '+')
79
+ left = { kind: 'unary', op: token.value, child: expression(4, depth + 1) };
80
+ else if (token.value === '(') {
81
+ left = expression(0, depth + 1);
82
+ require(')');
83
+ } else if (token.kind === 'word') {
84
+ const name = token.value.toUpperCase();
85
+ if (['TRUE', 'FALSE'].includes(name)) left = { kind: 'literal', value: name === 'TRUE' };
86
+ else {
87
+ if (!['IF', 'ROUND', 'ABS', 'MIN', 'MAX', 'SUM', 'AND', 'OR', 'NOT'].includes(name))
88
+ throw new Error(`不支持函数:${name}`);
89
+ require('(');
90
+ const args: Expression[] = [];
91
+ if (!take(')')) {
92
+ do {
93
+ args.push(expression(0, depth + 1));
94
+ } while (take(','));
95
+ require(')');
96
+ }
97
+ if (
98
+ !args.length ||
99
+ (name === 'IF' && args.length !== 3) ||
100
+ (['ABS', 'NOT'].includes(name) && args.length !== 1) ||
101
+ (name === 'ROUND' && args.length > 2)
102
+ )
103
+ throw new Error(`${name} 参数数量错误`);
104
+ left = { kind: 'call', name, args };
105
+ }
106
+ } else throw new Error(`意外的符号:${token.value}`);
107
+ while (tokens[at]?.kind === 'symbol' && (precedence[tokens[at].value] ?? -1) >= min) {
108
+ const op = tokens[at++].value;
109
+ left = { kind: 'binary', op, left, right: expression(precedence[op] + 1, depth + 1) };
110
+ }
111
+ return left;
112
+ }
113
+ const result = expression();
114
+ if (at !== tokens.length) throw new Error('公式存在多余内容');
115
+ return result;
116
+ }
117
+ export function canonicalFormula(source: string, fields: DataField[]) {
118
+ parseFormula(source, fields);
119
+ // Token-based rewriting leaves quoted strings unchanged.
120
+ return tokenize(source)
121
+ .map((token) =>
122
+ token.kind === 'field'
123
+ ? `[${(fields.find((field) => field.id === token.value) ?? fields.find((field) => field.name === token.value))!.id}]`
124
+ : token.value,
125
+ )
126
+ .join(' ');
127
+ }
128
+ export const displayFormula = (source: string, fields: DataField[]) => {
129
+ try {
130
+ return tokenize(source)
131
+ .map((token) =>
132
+ token.kind === 'field'
133
+ ? `[${fields.find((field) => field.id === token.value)?.name ?? token.value}]`
134
+ : token.value,
135
+ )
136
+ .join(' ');
137
+ } catch {
138
+ return source;
139
+ }
140
+ };
141
+ export interface CellResult {
142
+ value: DataValue;
143
+ error?: string;
144
+ }
145
+ const number = (value: DataValue) => {
146
+ if (value === null || value === '') return 0;
147
+ if (typeof value !== 'number') throw new Error('需要数字字段');
148
+ return value;
149
+ };
150
+ /** An interpreter with no eval, property access, filesystem, or network capability. */
151
+ export function dataEvaluator(table: DataTable) {
152
+ const compiled = new Map<string, Expression | Error>();
153
+ const cache = new Map<string, CellResult>();
154
+ function cell(row: DataRow, fieldId: string, trail: string[] = []): CellResult {
155
+ const key = `${row.id}/${fieldId}`;
156
+ if (cache.has(key)) return cache.get(key)!;
157
+ const field = table.fields.find((field) => field.id === fieldId);
158
+ if (!field) return { value: null, error: '字段已删除' };
159
+ if (field.type !== 'formula') return { value: row.values[fieldId] ?? null };
160
+ try {
161
+ if (trail.includes(fieldId) || trail.length > 60) throw new Error('公式循环引用');
162
+ if (!compiled.has(fieldId)) {
163
+ try {
164
+ compiled.set(fieldId, parseFormula(field.formula ?? '', table.fields));
165
+ } catch (error) {
166
+ compiled.set(fieldId, error as Error);
167
+ }
168
+ }
169
+ const tree = compiled.get(fieldId)!;
170
+ if (tree instanceof Error) throw tree;
171
+ function run(node: Expression): DataValue {
172
+ if (node.kind === 'literal') return node.value;
173
+ if (node.kind === 'field') {
174
+ const result = cell(row, node.id, [...trail, fieldId]);
175
+ if (result.error) throw new Error(result.error);
176
+ return result.value;
177
+ }
178
+ if (node.kind === 'unary') return (node.op === '-' ? -1 : 1) * number(run(node.child));
179
+ if (node.kind === 'binary') {
180
+ const a = run(node.left),
181
+ b = run(node.right);
182
+ if (['=', '=='].includes(node.op)) return JSON.stringify(a) === JSON.stringify(b);
183
+ if (['!=', '<>'].includes(node.op)) return JSON.stringify(a) !== JSON.stringify(b);
184
+ if (node.op === '>') return number(a) > number(b);
185
+ if (node.op === '<') return number(a) < number(b);
186
+ if (node.op === '>=') return number(a) >= number(b);
187
+ if (node.op === '<=') return number(a) <= number(b);
188
+ if (node.op === '+') return number(a) + number(b);
189
+ if (node.op === '-') return number(a) - number(b);
190
+ if (node.op === '*') return number(a) * number(b);
191
+ if (number(b) === 0) throw new Error('除数为零');
192
+ return number(a) / number(b);
193
+ }
194
+ if (node.name === 'IF') return run(node.args[0]) ? run(node.args[1]) : run(node.args[2]);
195
+ if (node.name === 'AND') return node.args.every((arg) => !!run(arg));
196
+ if (node.name === 'OR') return node.args.some((arg) => !!run(arg));
197
+ if (node.name === 'NOT') return !run(node.args[0]);
198
+ const args = node.args.map((arg) => number(run(arg)));
199
+ if (node.name === 'ABS') return Math.abs(args[0]);
200
+ if (node.name === 'ROUND') {
201
+ const digits = args[1] ?? 0;
202
+ if (!Number.isInteger(digits) || Math.abs(digits) > 12)
203
+ throw new Error('小数位须为 -12 到 12 的整数');
204
+ return Math.round(args[0] * 10 ** digits) / 10 ** digits;
205
+ }
206
+ if (node.name === 'MIN') return Math.min(...args);
207
+ if (node.name === 'MAX') return Math.max(...args);
208
+ return args.reduce((sum, n) => sum + n, 0);
209
+ }
210
+ const value = run(tree);
211
+ if (typeof value === 'number' && !Number.isFinite(value)) throw new Error('计算结果超出范围');
212
+ const result = { value };
213
+ cache.set(key, result);
214
+ return result;
215
+ } catch (error) {
216
+ const result = { value: null, error: (error as Error).message };
217
+ cache.set(key, result);
218
+ return result;
219
+ }
220
+ }
221
+ return cell;
222
+ }
223
+ export const dataValueText = (value: DataValue) =>
224
+ value === null
225
+ ? ''
226
+ : Array.isArray(value)
227
+ ? value.join('、')
228
+ : typeof value === 'boolean'
229
+ ? value
230
+ ? '是'
231
+ : '否'
232
+ : String(value);
233
+ export function dataViewRows(
234
+ table: DataTable,
235
+ view: DataView,
236
+ query = '',
237
+ evaluate = dataEvaluator(table),
238
+ ) {
239
+ const empty = (value: DataValue) =>
240
+ value === null || value === '' || (Array.isArray(value) && !value.length);
241
+ return table.rows
242
+ .filter((row) => {
243
+ if (
244
+ query &&
245
+ !table.fields.some((field) =>
246
+ dataValueText(evaluate(row, field.id).value)
247
+ .toLocaleLowerCase()
248
+ .includes(query.toLocaleLowerCase()),
249
+ )
250
+ )
251
+ return false;
252
+ return view.filters.every((filter) => {
253
+ const result = evaluate(row, filter.field),
254
+ value = result.value;
255
+ if (result.error) return false;
256
+ if (filter.operator === 'empty') return empty(value);
257
+ if (filter.operator === 'notEmpty') return !empty(value);
258
+ if (filter.operator === 'contains')
259
+ return dataValueText(value)
260
+ .toLocaleLowerCase()
261
+ .includes(filter.value.toLocaleLowerCase());
262
+ if (filter.operator === 'gt' || filter.operator === 'lt') {
263
+ if (empty(value)) return false;
264
+ const field = table.fields.find((field) => field.id === filter.field)!;
265
+ if (field.type === 'date')
266
+ return filter.operator === 'gt'
267
+ ? String(value) > filter.value
268
+ : String(value) < filter.value;
269
+ return (
270
+ typeof value === 'number' &&
271
+ filter.value.trim() !== '' &&
272
+ Number.isFinite(Number(filter.value)) &&
273
+ (filter.operator === 'gt' ? value > Number(filter.value) : value < Number(filter.value))
274
+ );
275
+ }
276
+ const equal = Array.isArray(value)
277
+ ? value.includes(filter.value)
278
+ : typeof value === 'boolean'
279
+ ? String(value) === filter.value || dataValueText(value) === filter.value
280
+ : typeof value === 'number'
281
+ ? filter.value.trim() !== '' && Number(filter.value) === value
282
+ : dataValueText(value) === filter.value;
283
+ return filter.operator === 'ne' ? !equal : equal;
284
+ });
285
+ })
286
+ .sort((a, b) => {
287
+ for (const sort of view.sorts) {
288
+ const av = evaluate(a, sort.field).value,
289
+ bv = evaluate(b, sort.field).value;
290
+ if (empty(av) !== empty(bv)) return empty(av) ? 1 : -1;
291
+ const delta =
292
+ typeof av === 'number' && typeof bv === 'number'
293
+ ? av - bv
294
+ : dataValueText(av).localeCompare(dataValueText(bv), 'zh-CN', { numeric: true });
295
+ if (delta) return delta * (sort.direction === 'desc' ? -1 : 1);
296
+ }
297
+ return 0;
298
+ });
299
+ }
300
+ export function aggregateData(
301
+ rows: DataRow[],
302
+ fieldId: string,
303
+ mode: DataAggregate,
304
+ evaluate: ReturnType<typeof dataEvaluator>,
305
+ ) {
306
+ if (mode === 'none') return '';
307
+ if (mode === 'count') return String(rows.length);
308
+ const results = rows.map((row) => evaluate(row, fieldId));
309
+ if (results.some((result) => result.error)) return '含公式错误';
310
+ const values = results.map((result) => result.value);
311
+ if (mode === 'filled')
312
+ return String(
313
+ values.filter(
314
+ (value) => value !== null && value !== '' && (!Array.isArray(value) || value.length),
315
+ ).length,
316
+ );
317
+ const numbers = values.filter((value): value is number => typeof value === 'number');
318
+ if (!numbers.length) return mode === 'sum' ? '0' : '—';
319
+ const sum = numbers.reduce((a, b) => a + b, 0);
320
+ const result =
321
+ mode === 'sum'
322
+ ? sum
323
+ : mode === 'average'
324
+ ? sum / numbers.length
325
+ : mode === 'min'
326
+ ? Math.min(...numbers)
327
+ : Math.max(...numbers);
328
+ return Number.isFinite(result) ? String(Number(result.toFixed(8))) : '结果超出范围';
329
+ }
@@ -0,0 +1,299 @@
1
+ import { basename, pathKey, validatePath } from './paths';
2
+
3
+ /** Portable structured tables. Rows are records, never automatically-created documents. */
4
+ export type DataFieldType =
5
+ | 'text'
6
+ | 'number'
7
+ | 'date'
8
+ | 'checkbox'
9
+ | 'select'
10
+ | 'multiselect'
11
+ | 'url'
12
+ | 'attachment'
13
+ | 'formula';
14
+ export type DataValue = string | number | boolean | string[] | null;
15
+ export const dataOptionColors = [
16
+ 'default',
17
+ 'gray',
18
+ 'brown',
19
+ 'orange',
20
+ 'yellow',
21
+ 'green',
22
+ 'blue',
23
+ 'purple',
24
+ 'pink',
25
+ 'red',
26
+ ] as const;
27
+ export type DataOptionColor = (typeof dataOptionColors)[number];
28
+ export interface DataField {
29
+ id: string;
30
+ name: string;
31
+ type: DataFieldType;
32
+ options?: string[];
33
+ optionColors?: Record<string, DataOptionColor>;
34
+ formula?: string;
35
+ }
36
+ export interface DataRow {
37
+ id: string;
38
+ values: Record<string, DataValue>;
39
+ }
40
+ export type DataAggregate = 'none' | 'sum' | 'average' | 'min' | 'max' | 'count' | 'filled';
41
+ export interface DataFilter {
42
+ id: string;
43
+ field: string;
44
+ operator: 'eq' | 'ne' | 'contains' | 'empty' | 'notEmpty' | 'gt' | 'lt';
45
+ value: string;
46
+ }
47
+ export interface DataView {
48
+ id: string;
49
+ name: string;
50
+ type: 'table' | 'cards' | 'board';
51
+ filters: DataFilter[];
52
+ sorts: { field: string; direction: 'asc' | 'desc' }[];
53
+ groupBy: string;
54
+ hiddenFields: string[];
55
+ widths: Record<string, number>;
56
+ aggregates: Record<string, DataAggregate>;
57
+ wrap: boolean;
58
+ fieldWrap?: Record<string, boolean>;
59
+ freeze: boolean;
60
+ }
61
+ export interface DataTable {
62
+ version: 1;
63
+ id: string;
64
+ name: string;
65
+ archived: boolean;
66
+ icon?: string;
67
+ cover?: string;
68
+ fields: DataField[];
69
+ rows: DataRow[];
70
+ views: DataView[];
71
+ }
72
+ export const dataTableDirectory = '.tano/tables';
73
+ export const isLegacyDataTablePath = (path: string) =>
74
+ /^\.tano\/tables\/[0-9a-f]{6}\.tano\.json$/.test(path);
75
+ export const isDataTableFilePath = (path: string) =>
76
+ /\.table\.json$/i.test(path) && !validatePath(path);
77
+ export const isDataTablePath = (path: string) =>
78
+ isDataTableFilePath(path) || isLegacyDataTablePath(path);
79
+ export const dataTableName = (path: string) => basename(path).replace(/\.table\.json$/i, '');
80
+ /** Choose a portable, unoccupied filename; adapters still enforce no-clobber creation. */
81
+ export function newDataTablePath(name: string, parent: string, paths: readonly string[]) {
82
+ let stem =
83
+ name
84
+ .normalize('NFC')
85
+ .replace(/[\\/<>:"|?*\u0000-\u001f]/g, '-')
86
+ .replace(/^[. ]+|[. ]+$/g, '')
87
+ .slice(0, 80) || '未命名数据表';
88
+ if (validatePath(`${stem}.table.json`)) stem = `数据表-${stem}`;
89
+ const prefix = `${parent ? `${parent}/` : ''}${stem}`;
90
+ const occupied = new Set(paths.map(pathKey));
91
+ let path = `${prefix}.table.json`;
92
+ for (let index = 2; occupied.has(pathKey(path)); index++) path = `${prefix} ${index}.table.json`;
93
+ const error = validatePath(path);
94
+ if (error) throw new Error(error);
95
+ return path;
96
+ }
97
+ /** Previous hidden storage location, retained only for migration and old session recovery. */
98
+ export function dataTablePath(id: string) {
99
+ if (!/^[0-9a-f]{6}$/.test(id)) throw new Error('数据表身份无效');
100
+ return `${dataTableDirectory}/${id}.tano.json`;
101
+ }
102
+ export const dataFieldTypes: Record<DataFieldType, string> = {
103
+ text: '文本',
104
+ number: '数字',
105
+ date: '日期',
106
+ checkbox: '勾选',
107
+ select: '单选',
108
+ multiselect: '多选',
109
+ url: '链接',
110
+ attachment: '附件',
111
+ formula: '公式',
112
+ };
113
+ const record = (value: unknown): value is Record<string, unknown> =>
114
+ !!value && typeof value === 'object' && !Array.isArray(value);
115
+ const validId = (value: unknown): value is string =>
116
+ typeof value === 'string' &&
117
+ /^[a-zA-Z0-9_-]{1,64}$/.test(value) &&
118
+ !['__proto__', 'constructor', 'prototype'].includes(value);
119
+ const validName = (value: unknown): value is string =>
120
+ typeof value === 'string' &&
121
+ !!value.trim() &&
122
+ value.length <= 200 &&
123
+ !/[\u0000-\u001f]/.test(value);
124
+ const strings = (value: unknown): value is string[] =>
125
+ Array.isArray(value) && value.every((item) => typeof item === 'string' && item.length <= 2000);
126
+ function unique(items: { id: string }[]) {
127
+ return new Set(items.map((item) => item.id)).size === items.length;
128
+ }
129
+ export function validDataValue(field: DataField, value: unknown): value is DataValue {
130
+ if (value === null) return true;
131
+ if (field.type === 'formula') return false;
132
+ if (field.type === 'number') return typeof value === 'number' && Number.isFinite(value);
133
+ if (field.type === 'checkbox') return typeof value === 'boolean';
134
+ if (field.type === 'multiselect')
135
+ return (
136
+ strings(value) &&
137
+ value.every((item) => field.options?.includes(item)) &&
138
+ new Set(value).size === value.length
139
+ );
140
+ if (field.type === 'attachment')
141
+ return (
142
+ strings(value) &&
143
+ value.every((item) => /^[0-9a-f]{6}$/.test(item)) &&
144
+ new Set(value).size === value.length
145
+ );
146
+ if (typeof value !== 'string' || value.length > 100000) return false;
147
+ if (field.type === 'select') return value === '' || !!field.options?.includes(value);
148
+ if (field.type === 'date') {
149
+ const date = new Date(`${value}T00:00:00Z`);
150
+ return (
151
+ value === '' ||
152
+ (/^\d{4}-\d{2}-\d{2}$/.test(value) &&
153
+ Number.isFinite(date.getTime()) &&
154
+ date.toISOString().slice(0, 10) === value)
155
+ );
156
+ }
157
+ return true;
158
+ }
159
+ /** Reject corrupt/unsupported content without resetting it; retain unknown extension keys. */
160
+ export function parseDataTable(content: string, expectedId?: string): DataTable {
161
+ if (new TextEncoder().encode(content).length > 8 * 1024 * 1024)
162
+ throw new Error('数据表超过 8 MiB,请拆分为多个表');
163
+ const table = JSON.parse(content) as DataTable;
164
+ const fail = (message: string): never => {
165
+ throw new Error(`数据表格式无效:${message}`);
166
+ };
167
+ if (
168
+ !record(table) ||
169
+ table.version !== 1 ||
170
+ !/^[0-9a-f]{6}$/.test(table.id) ||
171
+ (expectedId && table.id !== expectedId) ||
172
+ !validName(table.name) ||
173
+ typeof table.archived !== 'boolean'
174
+ )
175
+ fail('版本、身份或名称');
176
+ if (['icon', 'cover'].some(key => table[key as 'icon' | 'cover'] !== undefined &&
177
+ typeof table[key as 'icon' | 'cover'] !== 'string')) fail('图标或封面');
178
+ if (
179
+ !Array.isArray(table.fields) ||
180
+ !table.fields.length ||
181
+ table.fields.length > 200 ||
182
+ !unique(table.fields)
183
+ )
184
+ fail('字段重复或数量超出范围');
185
+ const names = new Set<string>();
186
+ for (const field of table.fields) {
187
+ if (
188
+ !record(field) ||
189
+ !validId(field.id) ||
190
+ !validName(field.name) ||
191
+ names.has(field.name) ||
192
+ !Object.hasOwn(dataFieldTypes, field.type)
193
+ )
194
+ fail('字段名称、身份或类型');
195
+ names.add(field.name);
196
+ if (
197
+ field.options !== undefined &&
198
+ (!strings(field.options) ||
199
+ new Set(field.options).size !== field.options.length ||
200
+ field.options.some((option) => !option.trim()))
201
+ )
202
+ fail('选项');
203
+ if (
204
+ field.optionColors !== undefined &&
205
+ (!record(field.optionColors) ||
206
+ Object.entries(field.optionColors).some(
207
+ ([option, color]) =>
208
+ !field.options?.includes(option) || !dataOptionColors.includes(color),
209
+ ))
210
+ )
211
+ fail('选项颜色');
212
+ if (
213
+ field.formula !== undefined &&
214
+ (typeof field.formula !== 'string' || field.formula.length > 4000)
215
+ )
216
+ fail('公式过长');
217
+ }
218
+ const fields = new Map(table.fields.map((field) => [field.id, field]));
219
+ if (!Array.isArray(table.rows) || table.rows.length > 50000 || !unique(table.rows))
220
+ fail('记录重复或数量超出范围');
221
+ for (const row of table.rows) {
222
+ if (!record(row) || !validId(row.id) || !record(row.values)) fail('记录身份或单元格');
223
+ for (const [key, value] of Object.entries(row.values))
224
+ if (!fields.has(key) || !validDataValue(fields.get(key)!, value))
225
+ fail(`单元格 ${row.id}/${key}`);
226
+ }
227
+ if (
228
+ !Array.isArray(table.views) ||
229
+ !table.views.length ||
230
+ table.views.length > 100 ||
231
+ !unique(table.views)
232
+ )
233
+ fail('视图');
234
+ for (const view of table.views) {
235
+ if (
236
+ !record(view) ||
237
+ !validId(view.id) ||
238
+ !validName(view.name) ||
239
+ !['table', 'cards', 'board'].includes(view.type) ||
240
+ typeof view.wrap !== 'boolean' ||
241
+ typeof view.freeze !== 'boolean'
242
+ )
243
+ fail('视图设置');
244
+ if (
245
+ view.fieldWrap !== undefined &&
246
+ (!record(view.fieldWrap) ||
247
+ Object.entries(view.fieldWrap).some(
248
+ ([id, wrap]) => !fields.has(id) || typeof wrap !== 'boolean',
249
+ ))
250
+ )
251
+ fail('列换行设置');
252
+ if (
253
+ !Array.isArray(view.filters) ||
254
+ view.filters.length > 100 ||
255
+ !unique(view.filters) ||
256
+ view.filters.some(
257
+ (filter) =>
258
+ !record(filter) ||
259
+ !validId(filter.id) ||
260
+ !fields.has(filter.field) ||
261
+ !['eq', 'ne', 'contains', 'empty', 'notEmpty', 'gt', 'lt'].includes(filter.operator) ||
262
+ typeof filter.value !== 'string',
263
+ )
264
+ )
265
+ fail('筛选');
266
+ if (
267
+ !Array.isArray(view.sorts) ||
268
+ view.sorts.some(
269
+ (sort) =>
270
+ !record(sort) || !fields.has(sort.field) || !['asc', 'desc'].includes(sort.direction),
271
+ )
272
+ )
273
+ fail('排序');
274
+ if (
275
+ typeof view.groupBy !== 'string' ||
276
+ (view.groupBy && !fields.has(view.groupBy)) ||
277
+ !strings(view.hiddenFields) ||
278
+ view.hiddenFields.some((id) => !fields.has(id))
279
+ )
280
+ fail('分组或隐藏字段');
281
+ if (
282
+ !record(view.widths) ||
283
+ Object.entries(view.widths).some(
284
+ ([id, width]) => !fields.has(id) || !Number.isFinite(width) || width < 80 || width > 1200,
285
+ )
286
+ )
287
+ fail('列宽');
288
+ if (
289
+ !record(view.aggregates) ||
290
+ Object.entries(view.aggregates).some(
291
+ ([id, aggregate]) =>
292
+ !fields.has(id) ||
293
+ !['none', 'sum', 'average', 'min', 'max', 'count', 'filled'].includes(aggregate),
294
+ )
295
+ )
296
+ fail('汇总');
297
+ }
298
+ return table;
299
+ }
@@ -0,0 +1,53 @@
1
+ export const defaultTableColumnWidth = 160;
2
+ export const minimumTableColumnWidth = 48;
3
+ export const tableColors = ['gray', 'brown', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink', 'red'] as const;
4
+ export type TableColor = typeof tableColors[number];
5
+
6
+ export interface TableLayout {
7
+ id: string;
8
+ widths: number[];
9
+ /** Color-only layouts keep fitting the container; omitted means fixed pixel widths. */
10
+ autoWidth?: true;
11
+ backgrounds?: (TableColor | null)[][];
12
+ foregrounds?: (TableColor | null)[][];
13
+ anchor: { content: string; before: string; after: string };
14
+ }
15
+
16
+ export interface DocumentLayoutFile {
17
+ version: 1;
18
+ fileId: string;
19
+ tables: TableLayout[];
20
+ }
21
+
22
+ export function documentLayoutPath(fileId: string) {
23
+ if (!/^[0-9a-f]{6}$/.test(fileId)) throw new Error('文档身份无效');
24
+ return `.tano/document-layout/${fileId}.tano.json`;
25
+ }
26
+
27
+ export function parseDocumentLayout(content: string, fileId: string): DocumentLayoutFile {
28
+ documentLayoutPath(fileId);
29
+ const file = JSON.parse(content) as DocumentLayoutFile;
30
+ if (!file || file.version !== 1 || file.fileId !== fileId ||
31
+ !Array.isArray(file.tables) || file.tables.length > 2000)
32
+ throw new Error('表格布局文件格式或身份无效');
33
+ const ids = new Set<string>();
34
+ for (const table of file.tables) {
35
+ if (!table || typeof table.id !== 'string' || !/^[0-9a-z-]{8,80}$/i.test(table.id) ||
36
+ ids.has(table.id) || !Array.isArray(table.widths) || !table.widths.length ||
37
+ (table.autoWidth !== undefined && table.autoWidth !== true) ||
38
+ table.widths.length > 1000 || table.widths.some(width =>
39
+ !Number.isInteger(width) || width < minimumTableColumnWidth || width > 100_000) ||
40
+ !table.anchor || typeof table.anchor.content !== 'string' || table.anchor.content.length > 8_000_000 ||
41
+ typeof table.anchor.before !== 'string' || table.anchor.before.length > 80 ||
42
+ typeof table.anchor.after !== 'string' || table.anchor.after.length > 80)
43
+ throw new Error('表格列宽或锚点格式无效');
44
+ ids.add(table.id);
45
+ for (const colors of [table.backgrounds, table.foregrounds]) {
46
+ if (colors !== undefined && (!Array.isArray(colors) || colors.length > 10000 ||
47
+ colors.some(row => !Array.isArray(row) || row.length !== table.widths.length ||
48
+ row.some(color => color !== null && !tableColors.includes(color)))))
49
+ throw new Error('表格颜色格式无效');
50
+ }
51
+ }
52
+ return file;
53
+ }