@tano.page/protocol 0.0.0-stage → 0.8.1

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,239 @@
1
+ import { parseObjectPlugin, type ObjectPluginManifest } from './plugins';
2
+
3
+ export const workspacePluginPath = '.tano/plugins.tano.json';
4
+ export const pluginPackageLimit = 4 * 1024 * 1024;
5
+ export const pluginStorageLimit = 256 * 1024;
6
+ export const pluginCacheLimit = 64 * 1024 * 1024;
7
+ export interface PluginPackageUsage {
8
+ used: number;
9
+ limit: number;
10
+ entryLimit: number;
11
+ entries: { integrity: string; pluginId: string; version: string; bytes: number;
12
+ state: 'pending' | 'ready' | 'deleting'; pinned: boolean; createdAt: string; removable?: boolean }[];
13
+ }
14
+ export const pluginPermissions = ['documents.read', 'documents.write', 'objects.read', 'objects.write',
15
+ 'relations.read', 'relations.write', 'storage', 'network', 'connections', 'native', 'ui'] as const;
16
+ export type PluginPermission = typeof pluginPermissions[number];
17
+ export type PluginMode = 'required' | 'recommended' | 'optional' | 'disabled';
18
+ export type PluginMenuLocation = 'workspace' | 'document' | 'file';
19
+ export interface PluginCommandDefinition { id: string; label: string; shortcut?: string; menus?: PluginMenuLocation[] }
20
+ export interface PluginViewDefinition { id: string; label: string; location?: 'panel' | 'tab' | 'sidebar' | 'settings' }
21
+ export interface PluginAutomationDefinition { id: string; label: string }
22
+ export interface ExecutablePluginManifest extends Omit<ObjectPluginManifest, 'manifestVersion'> {
23
+ manifestVersion: 2;
24
+ apiVersion: 1;
25
+ permissions: PluginPermission[];
26
+ networkOrigins: string[];
27
+ nativeCommands: string[];
28
+ commands: PluginCommandDefinition[];
29
+ views: PluginViewDefinition[];
30
+ /** Server entry points require separate workspace authorization; installation never schedules them. */
31
+ automations?: PluginAutomationDefinition[];
32
+ }
33
+ export type PluginManifest = ObjectPluginManifest | ExecutablePluginManifest;
34
+ export type PluginJson = null | boolean | number | string | PluginJson[] | { [key: string]: PluginJson };
35
+ export interface PluginUiBundle { html: string; css: string; source: string }
36
+ export interface PluginPackage { packageVersion: 1; manifest: PluginManifest; source?: string; ui?: Record<string, PluginUiBundle>; automationSource?: string }
37
+ export interface WorkspacePluginRule {
38
+ manifest: PluginManifest;
39
+ mode: PluginMode;
40
+ /** SHA-256 of the canonical package. Executable code is stored outside the workspace. */
41
+ integrity?: string;
42
+ sourceUrl?: string;
43
+ settings: Record<string, unknown>;
44
+ history?: PluginVersionReference[];
45
+ }
46
+ export interface PluginVersionReference { manifest: PluginManifest; integrity?: string; sourceUrl?: string; recordedAt: string }
47
+ export interface WorkspacePluginPolicy { version: 1; plugins: WorkspacePluginRule[] }
48
+
49
+ export function pluginRecord(value: unknown): value is Record<string, unknown> {
50
+ return !!value && typeof value === 'object' && !Array.isArray(value);
51
+ }
52
+ function keys(value: unknown, allowed: string[]) {
53
+ if (!pluginRecord(value) || Object.keys(value).some(key => !allowed.includes(key)))
54
+ throw new Error('插件数据包含不支持的字段');
55
+ }
56
+ export function pluginText(value: unknown, max = 200): value is string {
57
+ return typeof value === 'string' && value.length > 0 && value.length <= max && !/[\u0000-\u001f]/.test(value);
58
+ }
59
+ export function pluginKey(value: unknown): value is string {
60
+ return typeof value === 'string' && /^[a-z][a-z0-9.-]{0,79}$/.test(value);
61
+ }
62
+ export function canonicalPluginJson(value: unknown): string {
63
+ if (Array.isArray(value)) return `[${value.map(canonicalPluginJson).join(',')}]`;
64
+ if (pluginRecord(value)) return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonicalPluginJson(value[key])}`).join(',')}}`;
65
+ return JSON.stringify(value);
66
+ }
67
+ export function parsePluginSettings(value: unknown): Record<string, unknown> {
68
+ if (!pluginRecord(value)) throw new Error('插件设置必须是 JSON 对象');
69
+ const serialized = JSON.stringify(value);
70
+ if (serialized.length > 32 * 1024) throw new Error('插件设置不能超过 32 KB');
71
+ return JSON.parse(serialized);
72
+ }
73
+ export function parsePluginManifest(value: unknown): PluginManifest {
74
+ if (!pluginRecord(value)) throw new Error('插件清单无效');
75
+ if (value.manifestVersion === 1) return parseObjectPlugin(JSON.stringify(value));
76
+ keys(value, ['manifestVersion', 'apiVersion', 'id', 'name', 'version', 'description', 'objectTypes',
77
+ 'relationTypes', 'permissions', 'networkOrigins', 'nativeCommands', 'commands', 'views', 'automations']);
78
+ if (value.manifestVersion !== 2 || value.apiVersion !== 1) throw new Error('不支持此插件 API 版本');
79
+ const base = parseObjectPlugin(JSON.stringify({ manifestVersion: 1, id: value.id, name: value.name,
80
+ version: value.version, description: value.description, objectTypes: value.objectTypes ?? [], relationTypes: value.relationTypes ?? [] }));
81
+ const uniqueStrings = (input: unknown, check: (item: unknown) => boolean, limit = 50): string[] => {
82
+ if (!Array.isArray(input) || input.length > limit || input.some(item => !check(item)) || new Set(input).size !== input.length)
83
+ throw new Error('插件权限或扩展入口无效');
84
+ return input as string[];
85
+ };
86
+ const permissions = uniqueStrings(value.permissions, item => pluginPermissions.includes(item as PluginPermission)) as PluginPermission[];
87
+ const networkOrigins = uniqueStrings(value.networkOrigins ?? [], item => {
88
+ if (!pluginText(item, 250)) return false;
89
+ try { const url = new URL(item); return url.protocol === 'https:' && url.origin === item && !url.username && !url.password; } catch { return false; }
90
+ });
91
+ const nativeCommands = uniqueStrings(value.nativeCommands ?? [], pluginKey);
92
+ if ((networkOrigins.length && !permissions.includes('network') && !permissions.includes('connections')) || (nativeCommands.length && !permissions.includes('native')))
93
+ throw new Error('网络或本机能力必须声明权限');
94
+ const contributions = (input: unknown, limit: number, kind: 'command' | 'view') => {
95
+ if (!Array.isArray(input) || input.length > limit) throw new Error('插件入口数量无效');
96
+ const ids = new Set<string>();
97
+ return input.map(item => {
98
+ keys(item, kind === 'command' ? ['id', 'label', 'shortcut', 'menus'] : ['id', 'label', 'location']);
99
+ if (!pluginKey(item.id) || !pluginText(item.label, 80) || ids.has(item.id)) throw new Error('插件入口重复或无效');
100
+ ids.add(item.id);
101
+ const entry: PluginCommandDefinition & PluginViewDefinition = { id: item.id, label: item.label };
102
+ if (kind === 'command' && item.shortcut !== undefined) {
103
+ if (typeof item.shortcut !== 'string' || !/^(?:(?:Mod|Alt|Shift)\+){0,3}(?:[A-Z0-9]|F(?:[1-9]|1\d|2[0-4]))$/.test(item.shortcut) ||
104
+ (!item.shortcut.includes('Mod+') && !item.shortcut.includes('Alt+') && !/^F\d+$/.test(item.shortcut)) || item.shortcut.includes('Mod+Alt+')) throw new Error('插件快捷键无效');
105
+ const modifiers = item.shortcut.split('+').slice(0, -1);
106
+ if (new Set(modifiers).size !== modifiers.length || modifiers.join('+') !== ['Mod', 'Alt', 'Shift'].filter(key => modifiers.includes(key)).join('+')) throw new Error('插件快捷键修饰符顺序无效');
107
+ entry.shortcut = item.shortcut;
108
+ }
109
+ if (kind === 'command' && item.menus !== undefined) entry.menus = uniqueStrings(item.menus, location => typeof location === 'string' && ['workspace', 'document', 'file'].includes(location), 3) as PluginMenuLocation[];
110
+ if (kind === 'view' && item.location !== undefined) {
111
+ if (typeof item.location !== 'string' || !['panel', 'tab', 'sidebar', 'settings'].includes(item.location)) throw new Error('插件视图位置无效');
112
+ entry.location = item.location;
113
+ }
114
+ return entry;
115
+ });
116
+ };
117
+ let automations: PluginAutomationDefinition[] | undefined;
118
+ if (value.automations !== undefined) {
119
+ if (!Array.isArray(value.automations) || !value.automations.length || value.automations.length > 10) throw new Error('插件自动化入口数量无效');
120
+ const ids = new Set<string>();
121
+ automations = value.automations.map(item => {
122
+ keys(item, ['id', 'label']);
123
+ if (!pluginKey(item.id) || !pluginText(item.label, 80) || ids.has(item.id)) throw new Error('插件自动化入口重复或无效');
124
+ ids.add(item.id); return { id: item.id, label: item.label };
125
+ });
126
+ }
127
+ return { ...base, manifestVersion: 2, apiVersion: 1, permissions, networkOrigins, nativeCommands,
128
+ commands: contributions(value.commands ?? [], 50, 'command'), views: contributions(value.views ?? [], 10, 'view'),
129
+ ...(automations ? { automations } : {}) };
130
+ }
131
+ export function parsePluginPackage(content: string): PluginPackage {
132
+ if (new TextEncoder().encode(content).length > pluginPackageLimit) throw new Error('插件包不能超过 4 MiB');
133
+ const value = JSON.parse(content);
134
+ if (value?.manifestVersion === 1) return { packageVersion: 1, manifest: parsePluginManifest(value) };
135
+ keys(value, ['packageVersion', 'manifest', 'source', 'ui', 'automationSource']);
136
+ if (value.packageVersion !== 1) throw new Error('不支持此插件包版本');
137
+ const manifest = parsePluginManifest(value.manifest);
138
+ if (manifest.manifestVersion === 2) {
139
+ if (typeof value.source !== 'string' || !value.source.trim()) throw new Error('代码插件缺少入口脚本');
140
+ const ui: Record<string, PluginUiBundle> = {};
141
+ if (value.ui !== undefined) {
142
+ if (!manifest.permissions.includes('ui')) throw new Error('自定义界面必须声明 ui 权限');
143
+ if (!pluginRecord(value.ui) || Object.keys(value.ui).length > 10) throw new Error('插件界面包无效');
144
+ for (const [id, bundle] of Object.entries(value.ui)) {
145
+ if (!pluginKey(id) || !manifest.views.some(view => view.id === id)) throw new Error('插件界面必须在清单中声明视图');
146
+ if (!pluginRecord(bundle)) throw new Error('插件界面包无效');
147
+ keys(bundle, ['html', 'css', 'source']);
148
+ if (typeof bundle.html !== 'string' || typeof bundle.css !== 'string' || typeof bundle.source !== 'string' || !bundle.source.trim()) throw new Error('插件界面必须包含 HTML、CSS 和脚本');
149
+ ui[id] = { html: bundle.html, css: bundle.css, source: bundle.source };
150
+ }
151
+ }
152
+ if (manifest.automations?.length) {
153
+ if (typeof value.automationSource !== 'string' || !value.automationSource.trim()) throw new Error('自动化插件缺少服务端入口脚本');
154
+ } else if (value.automationSource !== undefined) throw new Error('服务端脚本必须声明自动化入口');
155
+ return { packageVersion: 1, manifest, source: value.source, ...(value.ui === undefined ? {} : { ui }),
156
+ ...(value.automationSource === undefined ? {} : { automationSource: value.automationSource }) };
157
+ }
158
+ if (value.source !== undefined || value.ui !== undefined || value.automationSource !== undefined) throw new Error('声明式插件不能携带脚本');
159
+ return { packageVersion: 1, manifest };
160
+ }
161
+
162
+ /** Validate at both the worker and custom-view boundaries, including non-JSON structured-clone values. */
163
+ export function parsePluginJson(value: unknown, limit = 128 * 1024): PluginJson {
164
+ let nodes = 0;
165
+ const visit = (item: unknown, depth: number): void => {
166
+ if (++nodes > 10000 || depth > 24) throw new Error('插件消息过大或嵌套过深');
167
+ if (item === null || typeof item === 'string' || typeof item === 'boolean' || (typeof item === 'number' && Number.isFinite(item))) return;
168
+ if (Array.isArray(item)) { item.forEach(child => visit(child, depth + 1)); return; }
169
+ if (pluginRecord(item) && Object.getPrototypeOf(item) === Object.prototype) { Object.values(item).forEach(child => visit(child, depth + 1)); return; }
170
+ throw new Error('插件消息必须为 JSON 数据');
171
+ };
172
+ visit(value, 0);
173
+ const content = JSON.stringify(value);
174
+ if (new TextEncoder().encode(content).length > limit) throw new Error('插件消息超过大小限制');
175
+ return JSON.parse(content);
176
+ }
177
+ export function parsePluginPolicy(content: string): WorkspacePluginPolicy {
178
+ if (content.length > 1024 * 1024) throw new Error('工作区插件规则不能超过 1 MB');
179
+ const value = JSON.parse(content);
180
+ keys(value, ['version', 'plugins']);
181
+ if (value.version !== 1 || !Array.isArray(value.plugins) || value.plugins.length > 100) throw new Error('工作区插件规则无效');
182
+ const ids = new Set<string>();
183
+ const plugins = value.plugins.map((item: unknown): WorkspacePluginRule => {
184
+ keys(item, ['manifest', 'mode', 'integrity', 'sourceUrl', 'settings', 'history']);
185
+ const row = item as Record<string, unknown>;
186
+ const manifest = parsePluginManifest(row.manifest);
187
+ if (ids.has(manifest.id) || !['required', 'recommended', 'optional', 'disabled'].includes(String(row.mode))) throw new Error('插件规则重复或模式无效');
188
+ ids.add(manifest.id);
189
+ if (row.integrity !== undefined && (typeof row.integrity !== 'string' || !/^[a-f0-9]{64}$/.test(row.integrity))) throw new Error('插件内容摘要无效');
190
+ if (manifest.manifestVersion === 2 && !row.integrity) throw new Error('代码插件必须锁定内容摘要');
191
+ if (row.sourceUrl !== undefined) {
192
+ if (!pluginText(row.sourceUrl, 2048)) throw new Error('插件下载地址无效');
193
+ const url = new URL(row.sourceUrl);
194
+ if (url.protocol !== 'https:' || url.username || url.password || url.hash) throw new Error('插件下载地址必须为 HTTPS');
195
+ }
196
+ let history: PluginVersionReference[] | undefined;
197
+ if (row.history !== undefined) {
198
+ if (!Array.isArray(row.history) || row.history.length > 10) throw new Error('插件最多保留 10 个历史版本');
199
+ history = row.history.map(value => {
200
+ keys(value, ['manifest', 'integrity', 'sourceUrl', 'recordedAt']);
201
+ if (!pluginRecord(value) || !pluginText(value.recordedAt, 40) || !Number.isFinite(Date.parse(value.recordedAt))) throw new Error('插件历史日期无效');
202
+ const previous = parsePluginPolicy(JSON.stringify({ version: 1, plugins: [{ manifest: value.manifest, integrity: value.integrity, sourceUrl: value.sourceUrl, mode: 'optional', settings: {} }] })).plugins[0]!;
203
+ if (previous.manifest.id !== manifest.id) throw new Error('插件历史身份不一致');
204
+ return { manifest: previous.manifest, ...(previous.integrity ? { integrity: previous.integrity } : {}), ...(previous.sourceUrl ? { sourceUrl: previous.sourceUrl } : {}), recordedAt: value.recordedAt };
205
+ });
206
+ }
207
+ return { manifest, mode: row.mode as PluginMode, settings: parsePluginSettings(row.settings ?? {}), ...(history ? { history } : {}),
208
+ ...(row.integrity ? { integrity: row.integrity as string } : {}), ...(row.sourceUrl ? { sourceUrl: row.sourceUrl as string } : {}) };
209
+ });
210
+ return { version: 1, plugins };
211
+ }
212
+
213
+ /** Bounded host-rendered UI: plugin strings never become HTML, CSS or event handlers. */
214
+ export type PluginViewNode = { type: 'text' | 'heading' | 'code'; text: string }
215
+ | { type: 'button'; label: string; action: string }
216
+ | { type: 'input'; label: string; key: string; value: string }
217
+ | { type: 'table'; columns: string[]; rows: string[][] }
218
+ | { type: 'stack'; children: PluginViewNode[] };
219
+ export function parsePluginView(value: unknown): PluginViewNode {
220
+ let count = 0;
221
+ const visit = (node: unknown, depth: number): PluginViewNode => {
222
+ if (++count > 300 || depth > 8 || !pluginRecord(node)) throw new Error('插件视图过大或无效');
223
+ if (node.type === 'stack') {
224
+ if (!Array.isArray(node.children)) throw new Error('插件视图节点无效');
225
+ return { type: 'stack', children: node.children.map(child => visit(child, depth + 1)) };
226
+ }
227
+ if (node.type === 'table') {
228
+ if (!Array.isArray(node.columns) || node.columns.length > 20 || !Array.isArray(node.rows) || node.rows.length > 500 ||
229
+ node.columns.some(cell => !pluginText(cell, 200)) || node.rows.some(row => !Array.isArray(row) || row.length !== (node.columns as unknown[]).length || row.some(cell => typeof cell !== 'string' || cell.length > 4000))) throw new Error('插件表格无效');
230
+ return { type: 'table', columns: node.columns as string[], rows: node.rows as string[][] };
231
+ }
232
+ if (node.type === 'button' && pluginText(node.label, 80) && pluginKey(node.action)) return { type: 'button', label: node.label, action: node.action };
233
+ if (node.type === 'input' && pluginText(node.label, 80) && pluginKey(node.key) && typeof node.value === 'string' && node.value.length <= 4000) return { type: 'input', label: node.label, key: node.key, value: node.value };
234
+ if (['text', 'heading', 'code'].includes(String(node.type)) && typeof node.text === 'string' && node.text.length <= 32000) return { type: node.type as 'text', text: node.text };
235
+ throw new Error('插件视图节点无效');
236
+ };
237
+ if (JSON.stringify(value).length > 256 * 1024) throw new Error('插件视图过大');
238
+ return visit(value, 0);
239
+ }
@@ -0,0 +1,70 @@
1
+ import type { FileEntry, Workspace } from './index';
2
+ import { isWorkspaceInternalPath } from './workspace-paths';
3
+
4
+ export type FilePreviewKind = 'markdown' | 'table' | 'image' | 'pdf' | 'csv' | 'json' | 'code' | 'text' | 'audio' | 'video' | 'binary';
5
+ export interface FileHandler {
6
+ readonly id: string;
7
+ readonly extensions: readonly string[];
8
+ readonly mimeType: string;
9
+ readonly preview: FilePreviewKind;
10
+ readonly canEdit: boolean;
11
+ /** Declarative host capabilities; never permissions granted by a file. */
12
+ readonly permissions: readonly ('read' | 'write')[];
13
+ }
14
+ const handler = (id: string, extensions: string[], mimeType: string, preview: FilePreviewKind, canEdit = false): FileHandler =>
15
+ Object.freeze({ id, extensions: Object.freeze(extensions), mimeType, preview, canEdit,
16
+ permissions: Object.freeze(canEdit ? ['read', 'write'] as const : ['read'] as const) });
17
+ export const builtInFileHandlers: readonly FileHandler[] = Object.freeze([
18
+ handler('table', ['table.json'], 'application/json', 'table', true),
19
+ handler('markdown', ['md', 'markdown'], 'text/markdown', 'markdown', true),
20
+ handler('pdf', ['pdf'], 'application/pdf', 'pdf'),
21
+ ...Object.entries({ png: 'png', jpg: 'jpeg', jpeg: 'jpeg', gif: 'gif', webp: 'webp', avif: 'avif', bmp: 'bmp', svg: 'svg+xml' })
22
+ .map(([ext, mime]) => handler(`image-${ext}`, [ext], `image/${mime}`, 'image')),
23
+ handler('csv', ['csv', 'tsv'], 'text/csv', 'csv'),
24
+ handler('json', ['json'], 'application/json', 'json'),
25
+ handler('code', ['js', 'ts', 'jsx', 'tsx', 'vue', 'py', 'rs', 'css', 'html', 'htm', 'xml', 'yaml', 'yml', 'toml', 'ini', 'sh', 'sql', 'c', 'h', 'cpp', 'hpp', 'java', 'go', 'rb', 'php', 'ps1'], 'text/plain', 'code'),
26
+ handler('text', ['txt', 'log'], 'text/plain', 'text'),
27
+ handler('audio', ['mp3', 'wav', 'ogg', 'm4a', 'flac'], 'audio/*', 'audio'),
28
+ handler('video', ['mp4', 'webm', 'mov'], 'video/*', 'video'),
29
+ ]);
30
+ const binaryHandler = handler('binary', [], 'application/octet-stream', 'binary');
31
+ export class FileHandlerRegistry {
32
+ constructor(readonly handlers: readonly FileHandler[] = builtInFileHandlers) {
33
+ if (new Set(handlers.map(item => item.id)).size !== handlers.length) throw new Error('文件处理程序身份重复');
34
+ }
35
+ resolve(path: string): FileHandler {
36
+ const name = path.toLowerCase();
37
+ return this.handlers.find(item => item.extensions.some(ext => name.endsWith(`.${ext}`))) ?? binaryHandler;
38
+ }
39
+ }
40
+ export const fileHandlers = new FileHandlerRegistry();
41
+ export interface WorkspaceFile extends FileEntry {
42
+ workspaceId: string;
43
+ kind: 'file';
44
+ mimeType: string;
45
+ handlerId: string;
46
+ /** A missing hash means unknown; size/mtime must never authorize writes. */
47
+ revision?: string;
48
+ }
49
+
50
+ /** Rebuildable index of adapter snapshots. The adapter alone owns persistent identity. */
51
+ export class FileRegistry {
52
+ readonly files: readonly WorkspaceFile[];
53
+ private readonly byId = new Map<string, WorkspaceFile>();
54
+ private readonly byPath = new Map<string, WorkspaceFile>();
55
+ constructor(readonly workspaceId: string, entries: readonly FileEntry[], handlers = fileHandlers) {
56
+ for (const entry of entries) {
57
+ if (entry.kind !== 'file') continue;
58
+ if (this.byId.has(entry.id) || this.byPath.has(entry.path)) throw new Error('文件注册表包含重复身份或路径');
59
+ const handler = handlers.resolve(entry.path);
60
+ const file: WorkspaceFile = Object.freeze({ ...entry, kind: 'file', workspaceId,
61
+ mimeType: handler.mimeType, handlerId: handler.id, revision: entry.contentHash });
62
+ this.byId.set(file.id, file); this.byPath.set(file.path, file);
63
+ }
64
+ this.files = Object.freeze([...this.byId.values()]);
65
+ }
66
+ get(id: string) { return this.byId.get(id); }
67
+ at(path: string) { return this.byPath.get(path); }
68
+ userFiles() { return this.files.filter(file => !isWorkspaceInternalPath(file.path)); }
69
+ static from(workspace: Workspace) { return new FileRegistry(workspace.id, workspace.files); }
70
+ }
@@ -0,0 +1,65 @@
1
+ import type { FileMetadata } from './file-metadata';
2
+ import type { WorkspaceFile } from './file-core';
3
+ export interface FileDatabaseFilter { field: string; operator: 'contains' | 'equals' | 'empty'; value: string }
4
+ export interface FileDatabaseQuery {
5
+ directory: string;
6
+ recursive: boolean;
7
+ filters: FileDatabaseFilter[];
8
+ sort: { field: string; direction: 'asc' | 'desc' };
9
+ groupBy: string;
10
+ }
11
+ export const defaultFileDatabaseQuery = (directory = ''): FileDatabaseQuery => ({
12
+ directory, recursive: true, filters: [], sort: { field: 'path', direction: 'asc' }, groupBy: '',
13
+ });
14
+ export function validateFileDatabaseQuery(value: FileDatabaseQuery) {
15
+ const field = (key: unknown) => typeof key === 'string' && /^(path|name|type|size|modified|tags|property:[\s\S]{1,100})$/.test(key);
16
+ if (!value || typeof value !== 'object' || typeof value.directory !== 'string' || value.directory.length > 2000 || /[\u0000-\u001f]/.test(value.directory) ||
17
+ (value.directory !== '' && (value.directory.includes('\\') || value.directory.split('/').some(p => !p || p === '.' || p === '..' || p === '.tano' || p.includes(':')))) ||
18
+ typeof value.recursive !== 'boolean' || !Array.isArray(value.filters) || value.filters.length > 20 ||
19
+ value.filters.some(f => !f || !field(f.field) || !['contains', 'equals', 'empty'].includes(f.operator) || typeof f.value !== 'string' || f.value.length > 1000) ||
20
+ !value.sort || !field(value.sort.field) || !['asc', 'desc'].includes(value.sort.direction) ||
21
+ (value.groupBy !== '' && !field(value.groupBy))) throw new Error('文件数据库查询格式无效');
22
+ return value;
23
+ }
24
+ export interface FileDatabaseRow { file: WorkspaceFile; metadata: FileMetadata }
25
+ export function fileDatabaseValue(row: FileDatabaseRow, field: string): string | number | boolean | null | string[] {
26
+ if (field.startsWith('property:')) return Object.hasOwn(row.metadata.properties, field.slice(9)) ? row.metadata.properties[field.slice(9)]! : null;
27
+ if (field === 'tags') return row.metadata.tags;
28
+ if (field === 'type') return row.file.handlerId;
29
+ if (field === 'size') return row.file.size;
30
+ if (field === 'modified') return row.file.modified;
31
+ if (field === 'name') return row.file.name;
32
+ return row.file.path;
33
+ }
34
+ export function queryFileDatabase(rows: readonly FileDatabaseRow[], query: FileDatabaseQuery) {
35
+ validateFileDatabaseQuery(query);
36
+ const text = (v: ReturnType<typeof fileDatabaseValue>) => v === null ? '' : String(v).toLocaleLowerCase();
37
+ return rows.filter(row => {
38
+ if (row.file.path.startsWith('.tano/')) return false;
39
+ const prefix = query.directory ? `${query.directory}/` : '';
40
+ if (!row.file.path.startsWith(prefix) || (!query.recursive && row.file.path.slice(prefix.length).includes('/'))) return false;
41
+ return query.filters.every(filter => {
42
+ const value = fileDatabaseValue(row, filter.field);
43
+ if (filter.operator === 'empty') return value === null || value === '' || (Array.isArray(value) && !value.length);
44
+ const expected = filter.value.toLocaleLowerCase();
45
+ const values = Array.isArray(value) ? value : [value];
46
+ return values.some(v => filter.operator === 'equals' ? text(v) === expected : text(v).includes(expected));
47
+ });
48
+ }).sort((a, b) => {
49
+ const av = fileDatabaseValue(a, query.sort.field), bv = fileDatabaseValue(b, query.sort.field);
50
+ const order = typeof av === 'number' && typeof bv === 'number' ? av - bv : text(av).localeCompare(text(bv), 'zh-CN', { numeric: true });
51
+ return (query.sort.direction === 'desc' ? -order : order) || a.file.id.localeCompare(b.file.id);
52
+ });
53
+ }
54
+ export function groupFileDatabase(rows: readonly FileDatabaseRow[], field: string) {
55
+ const groups = new Map<string, FileDatabaseRow[]>();
56
+ for (const row of rows) {
57
+ const value = field ? fileDatabaseValue(row, field) : '';
58
+ const keys = Array.isArray(value) ? (value.length ? value : ['']) : [value === null ? '' : String(value)];
59
+ for (const key of keys) {
60
+ const group = groups.get(key);
61
+ if (group) group.push(row); else groups.set(key, [row]);
62
+ }
63
+ }
64
+ return [...groups].map(([name, rows]) => ({ name, rows }));
65
+ }
@@ -0,0 +1,28 @@
1
+ import { isShortId } from './short-id';
2
+
3
+ export interface FileMetadata {
4
+ version: 1;
5
+ fileId: string;
6
+ tags: string[];
7
+ properties: Record<string, string | number | boolean | null>;
8
+ }
9
+ export function fileMetadataPath(fileId: string) {
10
+ if (!isShortId(fileId)) throw new Error('文件身份无效');
11
+ return `.tano/files/${fileId}.tano.json`;
12
+ }
13
+ export const emptyFileMetadata = (fileId: string): FileMetadata => ({ version: 1, fileId, tags: [], properties: {} });
14
+ export function parseFileMetadata(content: string, fileId: string): FileMetadata {
15
+ fileMetadataPath(fileId);
16
+ const value = JSON.parse(content) as FileMetadata;
17
+ if (!value || value.version !== 1 || value.fileId !== fileId ||
18
+ !Array.isArray(value.tags) || value.tags.length > 100 ||
19
+ value.tags.some(tag => typeof tag !== 'string' || !tag.trim() || tag.length > 100) ||
20
+ new Set(value.tags).size !== value.tags.length ||
21
+ !value.properties || typeof value.properties !== 'object' || Array.isArray(value.properties) ||
22
+ Object.keys(value.properties).length > 100 ||
23
+ Object.entries(value.properties).some(([key, item]) => !key.trim() || key.length > 100 ||
24
+ ['__proto__', 'constructor', 'prototype'].includes(key) ||
25
+ !(item === null || typeof item === 'boolean' || (typeof item === 'number' && Number.isFinite(item)) ||
26
+ (typeof item === 'string' && item.length <= 10000)))) throw new Error('文件元数据格式无效');
27
+ return { version: 1, fileId, tags: value.tags, properties: value.properties };
28
+ }
@@ -0,0 +1,78 @@
1
+ import { isMap, isScalar, parseDocument } from 'yaml';
2
+
3
+ export interface FrontmatterProperty {
4
+ name: string;
5
+ value: string;
6
+ kind: 'date' | 'list' | 'text';
7
+ }
8
+
9
+ function propertyValue(value: unknown): string {
10
+ if (value === null) return '空';
11
+ if (Array.isArray(value)) return value.map(propertyValue).join('、');
12
+ if (typeof value === 'object') return JSON.stringify(value);
13
+ return String(value);
14
+ }
15
+
16
+ export function frontmatterDocument(prefix: string) {
17
+ const opening = /^\uFEFF?---(\r?\n)/.exec(prefix);
18
+ if (!opening) return null;
19
+ const remainder = prefix.slice(opening[0].length);
20
+ const match = /(?:^|\r?\n)(---|\.\.\.)(?:\r?\n|$)/.exec(remainder);
21
+ if (!match) return null;
22
+ const end = opening[0].length + match.index + (match[0].startsWith('\r\n') ? 2 : match[0].startsWith('\n') ? 1 : 0);
23
+ const source = prefix.slice(opening[0].length, end);
24
+ const document = parseDocument(source);
25
+ if (document.errors.length || (document.contents !== null && !isMap(document.contents))) return null;
26
+ return { source, document, start: opening[0].length, end };
27
+ }
28
+
29
+ /** Read YAML values without changing the Markdown source. */
30
+ export function frontmatterProperties(prefix: string): FrontmatterProperty[] | null {
31
+ try {
32
+ const parsed = frontmatterDocument(prefix);
33
+ if (!parsed) return null;
34
+ const { document } = parsed;
35
+ const data: unknown = document.toJS({ maxAliasCount: 100 });
36
+ if (data === null) return [];
37
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null;
38
+ const sourceOrder = new Map(
39
+ isMap(document.contents)
40
+ ? document.contents.items.flatMap((item, index) =>
41
+ isScalar(item.key) ? [[String(item.key.value), index] as const] : [])
42
+ : [],
43
+ );
44
+ return Object.entries(data).sort(([left], [right]) =>
45
+ (sourceOrder.get(left) ?? Infinity) - (sourceOrder.get(right) ?? Infinity)).map(([name, value]) => ({
46
+ name,
47
+ value: propertyValue(value),
48
+ kind: Array.isArray(value)
49
+ ? 'list'
50
+ : /^(created|updated|date|created_at|updated_at)$/i.test(name)
51
+ ? 'date'
52
+ : 'text',
53
+ }));
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ export type FrontmatterValueKind = 'text' | 'number' | 'boolean' | 'date' | 'datetime' | 'list' | 'object' | 'null';
60
+
61
+ export function frontmatterValue(prefix: string, name: string): { kind: FrontmatterValueKind; value: string } | null {
62
+ const parsed = frontmatterDocument(prefix);
63
+ if (!parsed || !isMap(parsed.document.contents)) return null;
64
+ const pair = parsed.document.contents.items.find((item) => isScalar(item.key) && String(item.key.value) === name);
65
+ if (!pair) return null;
66
+ const value = pair.value?.toJSON() ?? null;
67
+ if (value === null) return { kind: 'null', value: '' };
68
+ if (Array.isArray(value)) return { kind: 'list', value: JSON.stringify(value, null, 2) };
69
+ if (typeof value === 'object') return { kind: 'object', value: JSON.stringify(value, null, 2) };
70
+ if (typeof value === 'boolean') return { kind: 'boolean', value: String(value) };
71
+ if (typeof value === 'number') return { kind: 'number', value: String(value) };
72
+ const plain = isScalar(pair.value) && pair.value.type === 'PLAIN';
73
+ if (plain && typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(value))
74
+ return { kind: 'datetime', value };
75
+ if (plain && typeof value === 'string' && /^\d{4}[-/]\d{2}[-/]\d{2}$/.test(value))
76
+ return { kind: 'date', value: value.replaceAll('/', '-') };
77
+ return { kind: 'text', value: String(value) };
78
+ }