@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.
package/src/index.ts ADDED
@@ -0,0 +1,192 @@
1
+ export * from './references';
2
+ export * from './agent';
3
+ export * from './assistant';
4
+ export * from './objects';
5
+ export * from './object-types';
6
+ export * from './short-id';
7
+ export * from './relations';
8
+ export * from './plugins';
9
+ export * from './extensions';
10
+ export * from './workspace-paths';
11
+ export * from './comments';
12
+ export * from './suggestions';
13
+ export * from './document-layout';
14
+ export * from './data-tables';
15
+ export * from './workspace-contract';
16
+ export * from './file-core';
17
+ export * from './file-metadata';
18
+
19
+ export interface FileEntry {
20
+ id: string;
21
+ path: string;
22
+ name: string;
23
+ kind: 'file' | 'directory';
24
+ size: number;
25
+ modified: number;
26
+ /** Content hash supplied by the authority when available, never inferred from mtime. */
27
+ contentHash?: string;
28
+ readOnly?: boolean;
29
+ /** Local draft; the authority has not yet confirmed creation. */
30
+ pendingCreation?: boolean;
31
+ }
32
+
33
+ export interface Workspace {
34
+ id: string;
35
+ name: string;
36
+ path: string;
37
+ files: FileEntry[];
38
+ readOnly?: boolean;
39
+ /** Transient creation result; omitted on subsequent opens and refreshes. */
40
+ newlyCreated?: boolean;
41
+ /** Local metadata was deleted; this open initialized a new workspace identity. */
42
+ reinitialized?: boolean;
43
+ /** True only when the current user may delete this workspace. */
44
+ canDelete?: boolean;
45
+ /** Supplied by the authority owning workspace membership, never by portable files. */
46
+ canManagePlugins?: boolean;
47
+ /** Supplied by the authority; content editing alone does not grant settings access. */
48
+ canManageSettings?: boolean;
49
+ }
50
+
51
+ export class WorkspaceAccessRevokedError extends Error {
52
+ constructor() {
53
+ super('你已失去此工作区的访问权限');
54
+ this.name = 'WorkspaceAccessRevokedError';
55
+ }
56
+ }
57
+
58
+ export interface FileSnapshot {
59
+ content: string;
60
+ hash: string;
61
+ modified: number;
62
+ }
63
+
64
+ export type WriteResult =
65
+ | { status: 'saved'; snapshot: FileSnapshot }
66
+ | { status: 'conflict'; snapshot: FileSnapshot }
67
+ | { status: 'missing' };
68
+
69
+ /** Compare identity and content at the filesystem boundary before moving/deleting a document. */
70
+ export interface FileChangeRequest {
71
+ workspaceId: string;
72
+ fileId: string;
73
+ path: string;
74
+ expectedHash: string;
75
+ /** Omitted for deletion. Saved returns the source snapshot, including for deletion. */
76
+ destination?: string;
77
+ }
78
+
79
+ export interface WorkspaceAdapter {
80
+ readonly mode: 'desktop' | 'demo' | 'web';
81
+ reserveObjectId?(occupied: string[]): Promise<string>;
82
+ /** Reserve an externally proposed, never-used object or table ID before exclusive creation. */
83
+ createAgentRecord?(path: string, content: string): Promise<void>;
84
+ /** Select a folder without opening it or changing the active workspace; null cancels. */
85
+ selectWorkspacePath?(): Promise<string | null>;
86
+ open(path?: string): Promise<Workspace | null>;
87
+ close?(workspaceId: string): Promise<void>;
88
+ createWorkspace?(name: string): Promise<Workspace>;
89
+ deleteWorkspace?(workspaceId: string): Promise<void>;
90
+ recent?(): Promise<RecentWorkspace[]>;
91
+ loadSession?(workspaceId: string): Promise<WorkspaceSession | null>;
92
+ saveSession?(workspaceId: string, session: WorkspaceSession): Promise<void>;
93
+ refresh(): Promise<Workspace>;
94
+ search?(workspaceId: string, query: string, signal?: AbortSignal): Promise<SearchHit[]>;
95
+ read(path: string): Promise<FileSnapshot>;
96
+ /** Optional version-checked, synchronous cache. Never returns speculative content. */
97
+ readCached?(path: string): FileSnapshot | undefined;
98
+ /** Best-effort read ahead; implementations bound speculative network work. */
99
+ prefetch?(path: string): Promise<void>;
100
+ write(path: string, content: string, expectedHash: string): Promise<WriteResult>;
101
+ /** May return the workspace including the confirmed creation to avoid a redundant refresh. */
102
+ create(path: string, content: string): Promise<void | Workspace>;
103
+ /** Persist a recoverable local draft without waiting for the remote authority. */
104
+ stageCreate?(path: string, content: string): Promise<{ workspace: Workspace; file: FileEntry }>;
105
+ /** Confirm the staged request, reusing its durable identity and idempotency key on retry. */
106
+ commitCreate?(id: string): Promise<{ file: FileEntry; snapshot: FileSnapshot }>;
107
+ createFolder(path: string): Promise<void>;
108
+ rename(from: string, to: string): Promise<void>;
109
+ move(from: string, to: string, kind: FileEntry['kind']): Promise<void>;
110
+ duplicate?(workspaceId: string, path: string): Promise<string>;
111
+ remove(path: string): Promise<void>;
112
+ changeFile?(request: FileChangeRequest): Promise<WriteResult>;
113
+ /** Object-only compare-and-delete. Keeps the assistant file boundary unchanged. */
114
+ removeObjectFile?(request: FileChangeRequest): Promise<WriteResult>;
115
+ reveal(): Promise<void>;
116
+ watch(callback: () => void): Promise<() => void>;
117
+ }
118
+
119
+ export interface SearchHit {
120
+ id: string;
121
+ path: string;
122
+ excerpt: string;
123
+ }
124
+
125
+ export interface RecentWorkspace {
126
+ id: string;
127
+ name: string;
128
+ path: string;
129
+ openedAt: number;
130
+ /** Owner display label supplied by the storage adapter, when available. */
131
+ owner?: string;
132
+ /** Stable owner identity used by workspace dashboard filters. */
133
+ ownerUserId?: string;
134
+ /** Display identity for a cloud workspace owner, when the server provides it. */
135
+ ownerProfile?: { userId: string; name: string; avatar?: string };
136
+ /** Workspace creation time in milliseconds; absent for legacy workspaces. */
137
+ createdAt?: number | null;
138
+ /** Optional user selection state supplied by a storage adapter. */
139
+ favorite?: boolean;
140
+ /** Whether this workspace was explicitly shared with the current user. */
141
+ shared?: boolean;
142
+ icon?: string;
143
+ }
144
+ export interface SessionDocument {
145
+ id: string;
146
+ path: string;
147
+ draft?: { content: string; base: FileSnapshot };
148
+ }
149
+ export interface WorkspaceSession {
150
+ version: 1;
151
+ activeId: string;
152
+ documents: SessionDocument[];
153
+ tabs?: string[];
154
+ layout?: WorkspaceLayout;
155
+ dataTables?: {
156
+ id: string;
157
+ fileId?: string;
158
+ path?: string;
159
+ content: string;
160
+ base: FileSnapshot;
161
+ }[];
162
+ }
163
+
164
+ export interface WorkspacePane {
165
+ kind: 'pane';
166
+ id: string;
167
+ tabs: string[];
168
+ activeId: string;
169
+ }
170
+ export interface WorkspaceSplit {
171
+ kind: 'split';
172
+ id: string;
173
+ axis: 'horizontal' | 'vertical';
174
+ ratio: number;
175
+ first: WorkspaceLayout;
176
+ second: WorkspaceLayout;
177
+ }
178
+ export type WorkspaceLayout = WorkspacePane | WorkspaceSplit;
179
+
180
+ export * from './paths';
181
+ export * from './plugin-catalog';
182
+ export * from './plugin-connections';
183
+ export * from './plugin-automations';
184
+ export * from './task-review';
185
+ export * from './task-repeat';
186
+ export * from './file-database';
187
+ export * from './view-engine';
188
+ export * from './agent-gateway';
189
+
190
+ export * from './data-table-query';
191
+
192
+ export * from './structured-merge';
@@ -0,0 +1,24 @@
1
+ import { emptyFileMetadata, type FileMetadata } from './file-metadata';
2
+ import { frontmatterProperties, frontmatterValue } from './frontmatter';
3
+
4
+ /** Read-only projection; Markdown properties remain in the source document. */
5
+ export function markdownFileMetadata(id: string, content: string): FileMetadata {
6
+ const file = emptyFileMetadata(id);
7
+ for (const property of frontmatterProperties(content) ?? []) {
8
+ const value = frontmatterValue(content, property.name);
9
+ if (!value) continue;
10
+ if (['tags', '标签'].includes(property.name)) {
11
+ const tags: unknown = value.kind === 'list' ? JSON.parse(value.value) : value.value.split(/[,,]/);
12
+ if (Array.isArray(tags)) file.tags.push(...tags.filter((tag): tag is string => typeof tag === 'string').map(tag => tag.trim()).filter(Boolean));
13
+ } else if (!['object', 'list'].includes(value.kind)) {
14
+ Object.defineProperty(file.properties, property.name, { enumerable: true, configurable: true, writable: true,
15
+ value: value.kind === 'null' ? null : value.kind === 'number' ? Number(value.value) : value.kind === 'boolean' ? value.value === 'true' : value.value });
16
+ }
17
+ }
18
+ file.tags = [...new Set(file.tags)];
19
+ // Aliases are only for querying the common columns; never write them back.
20
+ for (const [key, alias] of [['owner', '负责人'], ['status', '状态']]) {
21
+ if (!Object.hasOwn(file.properties, key) && Object.hasOwn(file.properties, alias!)) file.properties[key!] = file.properties[alias!]!;
22
+ }
23
+ return file;
24
+ }
@@ -0,0 +1,225 @@
1
+ /** Declarative object types shared by the editor, storage validation and future plugin hosts. */
2
+ import { parseTaskReview } from './task-review';
3
+ import { validateTaskRepeat } from './task-repeat';
4
+ export interface ObjectField {
5
+ key: string;
6
+ label: string;
7
+ type: 'text' | 'number' | 'boolean' | 'datetime';
8
+ required?: boolean;
9
+ }
10
+ export interface ObjectTypeDefinition {
11
+ type: string;
12
+ label: string;
13
+ level: 2;
14
+ category: 'core' | 'plugin';
15
+ storage: 'record' | 'resource';
16
+ /** Retained for existing files and references; not offered for new objects. */
17
+ legacy?: boolean;
18
+ /** Compatibility metadata only; excluded from available types and all mutations. */
19
+ retired?: boolean;
20
+ plugin?: string;
21
+ fields: readonly ObjectField[];
22
+ }
23
+ export const coreObjectTypes: readonly ObjectTypeDefinition[] = [
24
+ {
25
+ type: 'task', label: '任务', level: 2, category: 'core', storage: 'record', fields: [
26
+ { key: 'status', label: '状态', type: 'text' },
27
+ { key: 'due', label: '截止日期', type: 'text' },
28
+ { key: 'priority', label: '优先级', type: 'number' },
29
+ { key: 'completed', label: '已完成', type: 'boolean' },
30
+ ],
31
+ },
32
+ { type: 'project', label: '项目', level: 2, category: 'core', storage: 'record', fields: [
33
+ { key: 'status', label: '状态', type: 'text' },
34
+ { key: 'goal', label: '项目目标', type: 'text' },
35
+ { key: 'due', label: '截止日期', type: 'text' },
36
+ ] },
37
+ { type: 'experiment', label: '实验', level: 2, category: 'core', storage: 'record', fields: [
38
+ { key: 'status', label: '状态', type: 'text' },
39
+ { key: 'hypothesis', label: '假设', type: 'text' },
40
+ { key: 'result', label: '实验结果', type: 'text' },
41
+ { key: 'metric', label: '指标', type: 'number' },
42
+ { key: 'runAt', label: '运行时间', type: 'datetime' },
43
+ ] },
44
+ { type: 'person', label: '人物', level: 2, category: 'core', storage: 'record', fields: [] },
45
+ { type: 'document', label: '文档', level: 2, category: 'core', storage: 'resource', fields: [] },
46
+ {
47
+ type: 'event',
48
+ label: '事件',
49
+ level: 2,
50
+ category: 'core',
51
+ storage: 'record',
52
+ fields: [
53
+ { key: 'checkable', label: '需要完成', type: 'boolean' },
54
+ { key: 'completed', label: '已完成', type: 'boolean' },
55
+ { key: 'due', label: '截止日期', type: 'text' },
56
+ { key: 'date', label: '计划日期(不指定时间)', type: 'text' },
57
+ { key: 'start', label: '开始时间', type: 'datetime' },
58
+ { key: 'end', label: '结束时间', type: 'datetime' },
59
+ ],
60
+ },
61
+ { type: 'asset', label: '资产', level: 2, category: 'core', storage: 'resource', fields: [] },
62
+ ].map((definition) =>
63
+ Object.freeze({
64
+ ...definition,
65
+ fields: Object.freeze(definition.fields.map((field) => Object.freeze(field))),
66
+ }),
67
+ ) as readonly ObjectTypeDefinition[];
68
+
69
+ export const validObjectType = (type: unknown): type is string =>
70
+ typeof type === 'string' &&
71
+ /^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)*$/.test(type) &&
72
+ type.length <= 80;
73
+ export class ObjectTypeRegistry {
74
+ private definitions = new Map(coreObjectTypes.map((definition) => [definition.type, definition]));
75
+ private listeners = new Set<() => void>();
76
+ list() {
77
+ return [...this.definitions.values()];
78
+ }
79
+ get(type: string) {
80
+ return this.definitions.get(type);
81
+ }
82
+ subscribe(listener: () => void) {
83
+ this.listeners.add(listener);
84
+ return () => {
85
+ this.listeners.delete(listener);
86
+ };
87
+ }
88
+ /** Namespaced IDs prevent two domain plugins or a plugin and core from shadowing each other. */
89
+ registerObjectType(input: {
90
+ plugin: string;
91
+ type: string;
92
+ label: string;
93
+ fields?: readonly ObjectField[];
94
+ }) {
95
+ if (
96
+ !/^[a-z][a-z0-9-]*$/.test(input.plugin) ||
97
+ !validObjectType(input.type) ||
98
+ !input.type.startsWith(`${input.plugin}.`)
99
+ )
100
+ throw new Error('插件对象类型须使用 plugin.type 命名空间');
101
+ if (this.definitions.has(input.type)) throw new Error('对象类型已注册');
102
+ if (!input.label.trim() || input.label.length > 80) throw new Error('对象类型需要有效名称');
103
+ const keys = new Set<string>();
104
+ for (const field of input.fields ?? []) {
105
+ if (
106
+ !/^[a-zA-Z][a-zA-Z0-9_]*$/.test(field.key) ||
107
+ ['constructor', 'prototype', '__proto__'].includes(field.key) ||
108
+ keys.has(field.key) ||
109
+ !field.label.trim() ||
110
+ !['text', 'number', 'boolean', 'datetime'].includes(field.type)
111
+ )
112
+ throw new Error('插件属性定义无效或重复');
113
+ keys.add(field.key);
114
+ }
115
+ const definition: ObjectTypeDefinition = Object.freeze({
116
+ type: input.type,
117
+ label: input.label,
118
+ plugin: input.plugin,
119
+ level: 2,
120
+ category: 'plugin',
121
+ storage: 'record',
122
+ fields: Object.freeze((input.fields ?? []).map((field) => Object.freeze({ ...field }))),
123
+ });
124
+ this.definitions.set(input.type, definition);
125
+ for (const listener of this.listeners) listener();
126
+ return () => {
127
+ if (this.definitions.get(input.type) !== definition) return;
128
+ this.definitions.delete(input.type);
129
+ for (const listener of this.listeners) listener();
130
+ };
131
+ }
132
+ }
133
+ /** Shared schema authority for object CRUD, relation endpoints and view fields. */
134
+ export class SchemaRegistry extends ObjectTypeRegistry {
135
+ readonly version = 1;
136
+ validate(type: string, properties: Record<string, unknown>) {
137
+ validateObjectProperties(type, properties, this);
138
+ }
139
+ }
140
+ export const schemaRegistry = new SchemaRegistry();
141
+ /** Compatibility name used by editor and plugin integrations. */
142
+ export const objectTypeRegistry: ObjectTypeRegistry = schemaRegistry;
143
+ export const registerObjectType = (
144
+ input: Parameters<ObjectTypeRegistry['registerObjectType']>[0],
145
+ ) => objectTypeRegistry.registerObjectType(input);
146
+
147
+ /** A local calendar date, intentionally independent of a time zone. */
148
+ export function validEventDate(value: unknown): value is string {
149
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
150
+ const date = new Date(`${value}T00:00:00Z`);
151
+ return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
152
+ }
153
+
154
+ /** RFC 3339 timestamps with an explicit offset keep events unambiguous across devices. */
155
+ export function validEventTime(value: unknown): value is string {
156
+ if (typeof value !== 'string') return false;
157
+ const match =
158
+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,3})?)?(Z|[+-](\d{2}):(\d{2}))$/.exec(
159
+ value,
160
+ );
161
+ if (!match || !Number.isFinite(Date.parse(value))) return false;
162
+ const [, year, month, day, hour, minute, second] = match;
163
+ return (
164
+ +month! >= 1 &&
165
+ +month! <= 12 &&
166
+ +day! >= 1 &&
167
+ +day! <= new Date(Date.UTC(+year!, +month!, 0)).getUTCDate() &&
168
+ +hour! < 24 &&
169
+ +minute! < 60 &&
170
+ +(second ?? 0) < 60 &&
171
+ +(match[8] ?? 0) <= 23 &&
172
+ +(match[9] ?? 0) < 60
173
+ );
174
+ }
175
+ export function validateObjectProperties(
176
+ type: string,
177
+ properties: Record<string, unknown>,
178
+ registry = objectTypeRegistry,
179
+ ) {
180
+ validateTaskRepeat(type, properties);
181
+ if (properties.deliveryReview !== undefined) {
182
+ const review = parseTaskReview(properties.deliveryReview);
183
+ if (!(type === 'task' || (type === 'event' && properties.checkable === true))) throw new Error('只有任务可以提交交付审阅');
184
+ if ((properties.completed === true || type === 'task' && ['done', 'completed'].includes(String(properties.status))) && review.state !== 'approved') throw new Error('此任务需由指定审阅人确认通过后完成');
185
+ }
186
+ const definition = registry.get(type);
187
+ if (!definition) throw new Error(`类型 ${type} 未启用,请先注册对应领域插件;原文件已保留`);
188
+ if (definition.retired)
189
+ throw new Error('项目对象已停用;请使用工作区文件夹和 Markdown 文档组织项目,旧记录只读保留');
190
+ if (definition.storage !== 'record')
191
+ throw new Error('文档和资产来自工作区文件,不创建重复内容对象');
192
+ for (const field of definition.fields) {
193
+ const value = properties[field.key];
194
+ if (value === undefined || value === '') {
195
+ if (field.required) throw new Error(`请填写${field.label}`);
196
+ continue;
197
+ }
198
+ const valid =
199
+ field.type === 'datetime'
200
+ ? validEventTime(value)
201
+ : field.type === 'text'
202
+ ? typeof value === 'string'
203
+ : field.type === 'number'
204
+ ? typeof value === 'number' && Number.isFinite(value)
205
+ : typeof value === 'boolean';
206
+ if (!valid)
207
+ throw new Error(
208
+ `${field.label}格式无效${field.type === 'datetime' ? ',请使用带时区的日期时间' : ''}`,
209
+ );
210
+ }
211
+ if (['task', 'project'].includes(type) && properties.due !== undefined && properties.due !== '' && !validEventDate(properties.due)) throw new Error('截止日期格式无效,请使用 YYYY-MM-DD');
212
+ if (type === 'event') {
213
+ const hasStart = properties.start !== undefined && properties.start !== '';
214
+ const hasEnd = properties.end !== undefined && properties.end !== '';
215
+ const hasDate = properties.date !== undefined && properties.date !== '';
216
+ if (hasStart !== hasEnd) throw new Error('开始时间和结束时间需要一起填写');
217
+ if (hasStart && Date.parse(String(properties.end)) < Date.parse(String(properties.start)))
218
+ throw new Error('结束时间不能早于开始时间');
219
+ if (hasDate && !validEventDate(properties.date)) throw new Error('计划日期格式无效');
220
+ if (properties.due !== undefined && properties.due !== '' && !validEventDate(properties.due)) throw new Error('截止日期格式无效,请使用 YYYY-MM-DD');
221
+ if (hasDate && hasStart) throw new Error('计划日期与具体时间段只能选择一种安排方式');
222
+ if (properties.completed === true && properties.checkable !== true)
223
+ throw new Error('只有需要完成的事件可以标记为已完成');
224
+ }
225
+ }
package/src/objects.ts ADDED
@@ -0,0 +1,172 @@
1
+ import type { FileEntry } from './index';
2
+ import { isMarkdown } from './paths';
3
+ import { isWorkspaceInternalPath } from './workspace-paths';
4
+ import { isShortId } from './short-id';
5
+ import { coreObjectTypes, objectTypeRegistry, validObjectType } from './object-types';
6
+ import { parseTaskReview } from './task-review';
7
+ import { validateTaskRepeat } from './task-repeat';
8
+
9
+ export const objectTypes = coreObjectTypes;
10
+ export type ObjectType = string;
11
+ export type ReferenceType = string;
12
+ export interface WorkspaceObject {
13
+ version: 1;
14
+ id: string;
15
+ type: ObjectType;
16
+ name: string;
17
+ description: string;
18
+ archived: boolean;
19
+ properties: Record<string, unknown>;
20
+ [key: string]: unknown;
21
+ }
22
+ export interface ReferenceIdentity {
23
+ type: ReferenceType;
24
+ id: string;
25
+ }
26
+ export interface ReferenceTarget extends ReferenceIdentity {
27
+ workspace: string;
28
+ name: string;
29
+ path: string;
30
+ archived?: boolean;
31
+ description?: string;
32
+ size?: number;
33
+ mime?: string;
34
+ modified?: number;
35
+ properties?: Record<string, unknown>;
36
+ }
37
+ export const objectSuffix = '.tano.json';
38
+ export const isObjectPath = (path: string) => path.endsWith(objectSuffix) &&
39
+ (!path.startsWith('.tano/') || path.startsWith('.tano/objects/'));
40
+ export const referenceTypeLabel = (type: string) =>
41
+ objectTypeRegistry.get(type)?.label ?? `未启用类型(${type})`;
42
+ export function parseObject(content: string): WorkspaceObject {
43
+ const data = JSON.parse(content) as WorkspaceObject;
44
+ if (
45
+ !data ||
46
+ typeof data !== 'object' ||
47
+ Array.isArray(data) ||
48
+ data.version !== 1 ||
49
+ !isShortId(data.id) ||
50
+ !validObjectType(data.type) ||
51
+ typeof data.name !== 'string' ||
52
+ !data.name.trim() ||
53
+ data.name.length > 200 ||
54
+ /[\u0000-\u001f]/.test(data.name) ||
55
+ typeof data.description !== 'string' ||
56
+ data.description.length > 20000 ||
57
+ typeof data.archived !== 'boolean' ||
58
+ !data.properties ||
59
+ typeof data.properties !== 'object' ||
60
+ Array.isArray(data.properties)
61
+ )
62
+ throw new Error('对象格式无效,请检查 version、id、type、name 和 properties');
63
+ if (data.properties.deliveryReview !== undefined) parseTaskReview(data.properties.deliveryReview);
64
+ validateTaskRepeat(data.type, data.properties);
65
+ return data;
66
+ }
67
+ export function referenceUrl(target: ReferenceIdentity): string {
68
+ if (!isShortId(target.id) || !validObjectType(target.type)) throw new Error('引用身份无效');
69
+ return `object://${target.type}/${target.id}`;
70
+ }
71
+ export function referenceMarkdown(target: ReferenceIdentity, label: string): string {
72
+ const name = label.replace(/[\r\n]+/g, ' ').replace(/[\\\[\]]/g, '\\$&');
73
+ return `[@${name}](${referenceUrl(target)})`;
74
+ }
75
+ export function parseReferenceUrl(url: string): ReferenceIdentity | null {
76
+ const match = /^object:\/\/([a-z][a-z0-9.-]*)\/([0-9a-f]{6})$/.exec(url);
77
+ return match && validObjectType(match[1]) ? { type: match[1]!, id: match[2]! } : null;
78
+ }
79
+ export function documentTargets(workspace: string, files: FileEntry[]): ReferenceTarget[] {
80
+ return files
81
+ .filter((file) => file.kind === 'file' && !isWorkspaceInternalPath(file.path) && isMarkdown(file.path) && isShortId(file.id))
82
+ .map((file) => ({
83
+ workspace,
84
+ type: 'document',
85
+ id: file.id,
86
+ name: file.name.replace(/\.(md|markdown)$/i, ''),
87
+ path: file.path,
88
+ size: file.size,
89
+ modified: file.modified,
90
+ mime: 'text/markdown',
91
+ }));
92
+ }
93
+ const mimeTypes: Record<string, string> = {
94
+ png: 'image/png',
95
+ jpg: 'image/jpeg',
96
+ jpeg: 'image/jpeg',
97
+ gif: 'image/gif',
98
+ webp: 'image/webp',
99
+ svg: 'image/svg+xml',
100
+ pdf: 'application/pdf',
101
+ mp4: 'video/mp4',
102
+ webm: 'video/webm',
103
+ mp3: 'audio/mpeg',
104
+ wav: 'audio/wav',
105
+ txt: 'text/plain',
106
+ csv: 'text/csv',
107
+ json: 'application/json',
108
+ zip: 'application/zip',
109
+ };
110
+ /** Resource metadata is derived from files; it never contains their body or bytes. MIME is an extension hint. */
111
+ export function assetTargets(workspace: string, files: FileEntry[]): ReferenceTarget[] {
112
+ return files
113
+ .filter(
114
+ (file) =>
115
+ file.kind === 'file' &&
116
+ isShortId(file.id) &&
117
+ !isMarkdown(file.path) &&
118
+ !isObjectPath(file.path) &&
119
+ !file.path.endsWith('.tano-relations.json') &&
120
+ file.path !== 'capabilities.json' &&
121
+ !file.path.split('/').some((part) => part.startsWith('.')),
122
+ )
123
+ .map((file) => ({
124
+ workspace,
125
+ type: 'asset',
126
+ id: file.id,
127
+ name: file.name,
128
+ path: file.path,
129
+ size: file.size,
130
+ modified: file.modified,
131
+ mime:
132
+ mimeTypes[file.name.split('.').at(-1)?.toLowerCase() ?? ''] ?? 'application/octet-stream',
133
+ }));
134
+ }
135
+ /** Callers provide the current workspace's targets. Names are search input, never identity. */
136
+ export function resolveReference(targets: readonly ReferenceTarget[], identity: ReferenceIdentity) {
137
+ if (!objectTypeRegistry.get(identity.type)) return { error: 'unregistered' as const };
138
+ const matches = targets.filter(
139
+ (target) => target.type === identity.type && target.id === identity.id,
140
+ );
141
+ return matches.length === 1
142
+ ? { target: matches[0]! }
143
+ : { error: matches.length ? ('ambiguous' as const) : ('missing' as const) };
144
+ }
145
+ export function referenceCandidates(
146
+ targets: readonly ReferenceTarget[],
147
+ query: string,
148
+ ): ReferenceTarget[] {
149
+ const input = query
150
+ .replace(/^@|^\[\[/, '')
151
+ .replace(/\]\]$/, '')
152
+ .trim();
153
+ const qualifier = /^([a-z][a-z0-9.-]*)[:/](.*)$/i.exec(input);
154
+ const name = (qualifier?.[2] ?? input).normalize('NFKC').toLocaleLowerCase();
155
+ return targets
156
+ .filter(
157
+ (target) =>
158
+ !!objectTypeRegistry.get(target.type) &&
159
+ !objectTypeRegistry.get(target.type)?.retired &&
160
+ !target.archived &&
161
+ (!qualifier || target.type === qualifier[1]!.toLowerCase()) &&
162
+ `${target.name}\n${target.path}`.normalize('NFKC').toLocaleLowerCase().includes(name),
163
+ )
164
+ .sort(
165
+ (a, b) =>
166
+ Number(b.name.normalize('NFKC').toLocaleLowerCase() === name) -
167
+ Number(a.name.normalize('NFKC').toLocaleLowerCase() === name) ||
168
+ a.name.localeCompare(b.name) ||
169
+ a.type.localeCompare(b.type) ||
170
+ a.id.localeCompare(b.id),
171
+ );
172
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,43 @@
1
+ export function isMarkdown(path: string) {
2
+ return /\.(md|markdown)$/i.test(path);
3
+ }
4
+ export function basename(path: string) {
5
+ return path.split('/').at(-1) ?? path;
6
+ }
7
+ export function parentPath(path: string) {
8
+ return path.split('/').slice(0, -1).join('/');
9
+ }
10
+
11
+ /**
12
+ * Stable cross-platform comparison key for workspace paths. Filesystems vary
13
+ * in case and Unicode compatibility handling, so sync must reject aliases
14
+ * before they can become two different remote file identities.
15
+ */
16
+ export function pathKey(path: string) {
17
+ return path
18
+ .split('/')
19
+ .map((part) => part.normalize('NFKC').toLocaleUpperCase('en-US').toLocaleLowerCase('en-US'))
20
+ .join('/');
21
+ }
22
+
23
+ export function validatePath(path: string): string | null {
24
+ if (!path.trim() || path !== path.trim()) return '请输入有效的相对路径,首尾不能有空格';
25
+ if (path !== path.normalize('NFC')) return '路径必须使用 NFC Unicode';
26
+ if (path.length > 220) return '路径过长,请使用更短的名称';
27
+ if (
28
+ path
29
+ .split('/')
30
+ .some(
31
+ (p) =>
32
+ !p ||
33
+ p === '.' ||
34
+ p === '..' ||
35
+ p.startsWith('.') ||
36
+ /[\\<>:"|?*\u0000-\u001f]/.test(p) ||
37
+ /[. ]$/.test(p) ||
38
+ /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p),
39
+ )
40
+ )
41
+ return '路径不能包含隐藏目录、上级目录或系统保留字符';
42
+ return null;
43
+ }